feat: Passwordless cross-device authentication

- Arkitektur: docs/auth/passwordless-architecture.md
- Backend: iom/quixzoom-auth-service/ (FastAPI + Redis)
- Webb: quixzoom-market-pages/se/login/ (QR-kod + polling)
- App: iom/quixzoom-app/src/features/auth/ (push + deep links)

Flöde: QR-kod → app-godkännande → webb-inloggad
This commit is contained in:
Bernt
2026-07-07 07:11:50 +00:00
parent 4aa984ad74
commit 6989a98d75
61843 changed files with 5491611 additions and 872231 deletions
+6
View File
@@ -0,0 +1,6 @@
export { InputItems, type ResponseItemList, type InputItemListParams } from "./input-items.mjs";
export { InputTokens, type InputTokenCountResponse, type InputTokenCountParams } from "./input-tokens.mjs";
export { Responses } from "./responses.mjs";
export { type ResponsesWSClientOptions } from "./ws.mjs";
export { type ResponsesWSReconnectOptions } from "./ws-base.mjs";
//# sourceMappingURL=index.d.mts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../src/resources/responses/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,KAAK,mBAAmB,EAAE,0BAAsB;AAC5F,OAAO,EAAE,WAAW,EAAE,KAAK,uBAAuB,EAAE,KAAK,qBAAqB,EAAE,2BAAuB;AACvG,OAAO,EAAE,SAAS,EAAE,wBAAoB;AACxC,OAAO,EAAE,KAAK,wBAAwB,EAAE,iBAAa;AACrD,OAAO,EAAE,KAAK,2BAA2B,EAAE,sBAAkB"}
+6
View File
@@ -0,0 +1,6 @@
export { InputItems, type ResponseItemList, type InputItemListParams } from "./input-items.js";
export { InputTokens, type InputTokenCountResponse, type InputTokenCountParams } from "./input-tokens.js";
export { Responses } from "./responses.js";
export { type ResponsesWSClientOptions } from "./ws.js";
export { type ResponsesWSReconnectOptions } from "./ws-base.js";
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/resources/responses/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,KAAK,mBAAmB,EAAE,yBAAsB;AAC5F,OAAO,EAAE,WAAW,EAAE,KAAK,uBAAuB,EAAE,KAAK,qBAAqB,EAAE,0BAAuB;AACvG,OAAO,EAAE,SAAS,EAAE,uBAAoB;AACxC,OAAO,EAAE,KAAK,wBAAwB,EAAE,gBAAa;AACrD,OAAO,EAAE,KAAK,2BAA2B,EAAE,qBAAkB"}
+11
View File
@@ -0,0 +1,11 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Responses = exports.InputTokens = exports.InputItems = void 0;
var input_items_1 = require("./input-items.js");
Object.defineProperty(exports, "InputItems", { enumerable: true, get: function () { return input_items_1.InputItems; } });
var input_tokens_1 = require("./input-tokens.js");
Object.defineProperty(exports, "InputTokens", { enumerable: true, get: function () { return input_tokens_1.InputTokens; } });
var responses_1 = require("./responses.js");
Object.defineProperty(exports, "Responses", { enumerable: true, get: function () { return responses_1.Responses; } });
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/resources/responses/index.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,gDAA4F;AAAnF,yGAAA,UAAU,OAAA;AACnB,kDAAuG;AAA9F,2GAAA,WAAW,OAAA;AACpB,4CAAwC;AAA/B,sGAAA,SAAS,OAAA"}
+5
View File
@@ -0,0 +1,5 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export { InputItems } from "./input-items.mjs";
export { InputTokens } from "./input-tokens.mjs";
export { Responses } from "./responses.mjs";
//# sourceMappingURL=index.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../../src/resources/responses/index.ts"],"names":[],"mappings":"AAAA,sFAAsF;AAEtF,OAAO,EAAE,UAAU,EAAmD,0BAAsB;AAC5F,OAAO,EAAE,WAAW,EAA4D,2BAAuB;AACvG,OAAO,EAAE,SAAS,EAAE,wBAAoB"}
+65
View File
@@ -0,0 +1,65 @@
import { APIResource } from "../../core/resource.mjs";
import * as ResponsesAPI from "./responses.mjs";
import { ResponseItemsPage } from "./responses.mjs";
import { type CursorPageParams, PagePromise } from "../../core/pagination.mjs";
import { RequestOptions } from "../../internal/request-options.mjs";
export declare class InputItems extends APIResource {
/**
* Returns a list of input items for a given response.
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const responseItem of client.responses.inputItems.list(
* 'response_id',
* )) {
* // ...
* }
* ```
*/
list(responseID: string, query?: InputItemListParams | null | undefined, options?: RequestOptions): PagePromise<ResponseItemsPage, ResponsesAPI.ResponseItem>;
}
/**
* A list of Response items.
*/
export interface ResponseItemList {
/**
* A list of items used to generate this response.
*/
data: Array<ResponsesAPI.ResponseItem>;
/**
* The ID of the first item in the list.
*/
first_id: string;
/**
* Whether there are more items available.
*/
has_more: boolean;
/**
* The ID of the last item in the list.
*/
last_id: string;
/**
* The type of object returned, must be `list`.
*/
object: 'list';
}
export interface InputItemListParams extends CursorPageParams {
/**
* Additional fields to include in the response. See the `include` parameter for
* Response creation above for more information.
*/
include?: Array<ResponsesAPI.ResponseIncludable>;
/**
* The order to return the input items in. Default is `desc`.
*
* - `asc`: Return the input items in ascending order.
* - `desc`: Return the input items in descending order.
*/
order?: 'asc' | 'desc';
}
export declare namespace InputItems {
export { type ResponseItemList as ResponseItemList, type InputItemListParams as InputItemListParams };
}
export { type ResponseItemsPage };
//# sourceMappingURL=input-items.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"input-items.d.mts","sourceRoot":"","sources":["../../src/resources/responses/input-items.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,gCAA4B;AAClD,OAAO,KAAK,YAAY,wBAAoB;AAC5C,OAAO,EAAE,iBAAiB,EAAE,wBAAoB;AAChD,OAAO,EAAc,KAAK,gBAAgB,EAAE,WAAW,EAAE,kCAA8B;AACvF,OAAO,EAAE,cAAc,EAAE,2CAAuC;AAGhE,qBAAa,UAAW,SAAQ,WAAW;IACzC;;;;;;;;;;;;OAYG;IACH,IAAI,CACF,UAAU,EAAE,MAAM,EAClB,KAAK,GAAE,mBAAmB,GAAG,IAAI,GAAG,SAAc,EAClD,OAAO,CAAC,EAAE,cAAc,GACvB,WAAW,CAAC,iBAAiB,EAAE,YAAY,CAAC,YAAY,CAAC;CAO7D;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,IAAI,EAAE,KAAK,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC;IAEvC;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,QAAQ,EAAE,OAAO,CAAC;IAElB;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,mBAAoB,SAAQ,gBAAgB;IAC3D;;;OAGG;IACH,OAAO,CAAC,EAAE,KAAK,CAAC,YAAY,CAAC,kBAAkB,CAAC,CAAC;IAEjD;;;;;OAKG;IACH,KAAK,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;CACxB;AAED,MAAM,CAAC,OAAO,WAAW,UAAU,CAAC;IAClC,OAAO,EAAE,KAAK,gBAAgB,IAAI,gBAAgB,EAAE,KAAK,mBAAmB,IAAI,mBAAmB,EAAE,CAAC;CACvG;AAED,OAAO,EAAE,KAAK,iBAAiB,EAAE,CAAC"}
+65
View File
@@ -0,0 +1,65 @@
import { APIResource } from "../../core/resource.js";
import * as ResponsesAPI from "./responses.js";
import { ResponseItemsPage } from "./responses.js";
import { type CursorPageParams, PagePromise } from "../../core/pagination.js";
import { RequestOptions } from "../../internal/request-options.js";
export declare class InputItems extends APIResource {
/**
* Returns a list of input items for a given response.
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const responseItem of client.responses.inputItems.list(
* 'response_id',
* )) {
* // ...
* }
* ```
*/
list(responseID: string, query?: InputItemListParams | null | undefined, options?: RequestOptions): PagePromise<ResponseItemsPage, ResponsesAPI.ResponseItem>;
}
/**
* A list of Response items.
*/
export interface ResponseItemList {
/**
* A list of items used to generate this response.
*/
data: Array<ResponsesAPI.ResponseItem>;
/**
* The ID of the first item in the list.
*/
first_id: string;
/**
* Whether there are more items available.
*/
has_more: boolean;
/**
* The ID of the last item in the list.
*/
last_id: string;
/**
* The type of object returned, must be `list`.
*/
object: 'list';
}
export interface InputItemListParams extends CursorPageParams {
/**
* Additional fields to include in the response. See the `include` parameter for
* Response creation above for more information.
*/
include?: Array<ResponsesAPI.ResponseIncludable>;
/**
* The order to return the input items in. Default is `desc`.
*
* - `asc`: Return the input items in ascending order.
* - `desc`: Return the input items in descending order.
*/
order?: 'asc' | 'desc';
}
export declare namespace InputItems {
export { type ResponseItemList as ResponseItemList, type InputItemListParams as InputItemListParams };
}
export { type ResponseItemsPage };
//# sourceMappingURL=input-items.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"input-items.d.ts","sourceRoot":"","sources":["../../src/resources/responses/input-items.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,+BAA4B;AAClD,OAAO,KAAK,YAAY,uBAAoB;AAC5C,OAAO,EAAE,iBAAiB,EAAE,uBAAoB;AAChD,OAAO,EAAc,KAAK,gBAAgB,EAAE,WAAW,EAAE,iCAA8B;AACvF,OAAO,EAAE,cAAc,EAAE,0CAAuC;AAGhE,qBAAa,UAAW,SAAQ,WAAW;IACzC;;;;;;;;;;;;OAYG;IACH,IAAI,CACF,UAAU,EAAE,MAAM,EAClB,KAAK,GAAE,mBAAmB,GAAG,IAAI,GAAG,SAAc,EAClD,OAAO,CAAC,EAAE,cAAc,GACvB,WAAW,CAAC,iBAAiB,EAAE,YAAY,CAAC,YAAY,CAAC;CAO7D;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,IAAI,EAAE,KAAK,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC;IAEvC;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,QAAQ,EAAE,OAAO,CAAC;IAElB;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,mBAAoB,SAAQ,gBAAgB;IAC3D;;;OAGG;IACH,OAAO,CAAC,EAAE,KAAK,CAAC,YAAY,CAAC,kBAAkB,CAAC,CAAC;IAEjD;;;;;OAKG;IACH,KAAK,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;CACxB;AAED,MAAM,CAAC,OAAO,WAAW,UAAU,CAAC;IAClC,OAAO,EAAE,KAAK,gBAAgB,IAAI,gBAAgB,EAAE,KAAK,mBAAmB,IAAI,mBAAmB,EAAE,CAAC;CACvG;AAED,OAAO,EAAE,KAAK,iBAAiB,EAAE,CAAC"}
+27
View File
@@ -0,0 +1,27 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.InputItems = void 0;
const resource_1 = require("../../core/resource.js");
const pagination_1 = require("../../core/pagination.js");
const path_1 = require("../../internal/utils/path.js");
class InputItems extends resource_1.APIResource {
/**
* Returns a list of input items for a given response.
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const responseItem of client.responses.inputItems.list(
* 'response_id',
* )) {
* // ...
* }
* ```
*/
list(responseID, query = {}, options) {
return this._client.getAPIList((0, path_1.path) `/responses/${responseID}/input_items`, (pagination_1.CursorPage), { query, ...options, __security: { bearerAuth: true } });
}
}
exports.InputItems = InputItems;
//# sourceMappingURL=input-items.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"input-items.js","sourceRoot":"","sources":["../../src/resources/responses/input-items.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,qDAAkD;AAGlD,yDAAuF;AAEvF,uDAAiD;AAEjD,MAAa,UAAW,SAAQ,sBAAW;IACzC;;;;;;;;;;;;OAYG;IACH,IAAI,CACF,UAAkB,EAClB,QAAgD,EAAE,EAClD,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAC5B,IAAA,WAAI,EAAA,cAAc,UAAU,cAAc,EAC1C,CAAA,uBAAqC,CAAA,EACrC,EAAE,KAAK,EAAE,GAAG,OAAO,EAAE,UAAU,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,EAAE,CACxD,CAAC;IACJ,CAAC;CACF;AAzBD,gCAyBC"}
+23
View File
@@ -0,0 +1,23 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../core/resource.mjs";
import { CursorPage } from "../../core/pagination.mjs";
import { path } from "../../internal/utils/path.mjs";
export class InputItems extends APIResource {
/**
* Returns a list of input items for a given response.
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const responseItem of client.responses.inputItems.list(
* 'response_id',
* )) {
* // ...
* }
* ```
*/
list(responseID, query = {}, options) {
return this._client.getAPIList(path `/responses/${responseID}/input_items`, (CursorPage), { query, ...options, __security: { bearerAuth: true } });
}
}
//# sourceMappingURL=input-items.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"input-items.mjs","sourceRoot":"","sources":["../../src/resources/responses/input-items.ts"],"names":[],"mappings":"AAAA,sFAAsF;AAEtF,OAAO,EAAE,WAAW,EAAE,gCAA4B;AAGlD,OAAO,EAAE,UAAU,EAAsC,kCAA8B;AAEvF,OAAO,EAAE,IAAI,EAAE,sCAAkC;AAEjD,MAAM,OAAO,UAAW,SAAQ,WAAW;IACzC;;;;;;;;;;;;OAYG;IACH,IAAI,CACF,UAAkB,EAClB,QAAgD,EAAE,EAClD,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAC5B,IAAI,CAAA,cAAc,UAAU,cAAc,EAC1C,CAAA,UAAqC,CAAA,EACrC,EAAE,KAAK,EAAE,GAAG,OAAO,EAAE,UAAU,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,EAAE,CACxD,CAAC;IACJ,CAAC;CACF"}
+136
View File
@@ -0,0 +1,136 @@
import { APIResource } from "../../core/resource.mjs";
import * as Shared from "../shared.mjs";
import * as ResponsesAPI from "./responses.mjs";
import { APIPromise } from "../../core/api-promise.mjs";
import { RequestOptions } from "../../internal/request-options.mjs";
export declare class InputTokens extends APIResource {
/**
* Returns input token counts of the request.
*
* Returns an object with `object` set to `response.input_tokens` and an
* `input_tokens` count.
*
* @example
* ```ts
* const response = await client.responses.inputTokens.count();
* ```
*/
count(body?: InputTokenCountParams | null | undefined, options?: RequestOptions): APIPromise<InputTokenCountResponse>;
}
export interface InputTokenCountResponse {
input_tokens: number;
object: 'response.input_tokens';
}
export interface InputTokenCountParams {
/**
* The conversation that this response belongs to. Items from this conversation are
* prepended to `input_items` for this response request. Input items and output
* items from this response are automatically added to this conversation after this
* response completes.
*/
conversation?: string | ResponsesAPI.ResponseConversationParam | null;
/**
* Text, image, or file inputs to the model, used to generate a response
*/
input?: string | Array<ResponsesAPI.ResponseInputItem> | null;
/**
* A system (or developer) message inserted into the model's context. When used
* along with `previous_response_id`, the instructions from a previous response
* will not be carried over to the next response. This makes it simple to swap out
* system (or developer) messages in new responses.
*/
instructions?: string | null;
/**
* Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a
* wide range of models with different capabilities, performance characteristics,
* and price points. Refer to the
* [model guide](https://platform.openai.com/docs/models) to browse and compare
* available models.
*/
model?: string | null;
/**
* Whether to allow the model to run tool calls in parallel.
*/
parallel_tool_calls?: boolean | null;
/**
* A model-owned style preset to apply to this request. Omit this parameter to use
* the model's default style. Supported values may expand over time. Values must be
* at most 64 characters.
*/
personality?: (string & {}) | 'friendly' | 'pragmatic';
/**
* The unique ID of the previous response to the model. Use this to create
* multi-turn conversations. Learn more about
* [conversation state](https://platform.openai.com/docs/guides/conversation-state).
* Cannot be used in conjunction with `conversation`.
*/
previous_response_id?: string | null;
/**
* **gpt-5 and o-series models only** Configuration options for
* [reasoning models](https://platform.openai.com/docs/guides/reasoning).
*/
reasoning?: Shared.Reasoning | null;
/**
* Configuration options for a text response from the model. Can be plain text or
* structured JSON data. Learn more:
*
* - [Text inputs and outputs](https://platform.openai.com/docs/guides/text)
* - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)
*/
text?: InputTokenCountParams.Text | null;
/**
* Controls which tool the model should use, if any.
*/
tool_choice?: ResponsesAPI.ToolChoiceOptions | ResponsesAPI.ToolChoiceAllowed | ResponsesAPI.ToolChoiceTypes | ResponsesAPI.ToolChoiceFunction | ResponsesAPI.ToolChoiceMcp | ResponsesAPI.ToolChoiceCustom | ResponsesAPI.ToolChoiceApplyPatch | ResponsesAPI.ToolChoiceShell | null;
/**
* An array of tools the model may call while generating a response. You can
* specify which tool to use by setting the `tool_choice` parameter.
*/
tools?: Array<ResponsesAPI.Tool> | null;
/**
* @deprecated The truncation strategy to use for the model response. - `auto`: If
* the input to this Response exceeds the model's context window size, the model
* will truncate the response to fit the context window by dropping items from the
* beginning of the conversation. - `disabled` (default): If the input size will
* exceed the context window size for a model, the request will fail with a 400
* error.
*/
truncation?: 'auto' | 'disabled';
}
export declare namespace InputTokenCountParams {
/**
* Configuration options for a text response from the model. Can be plain text or
* structured JSON data. Learn more:
*
* - [Text inputs and outputs](https://platform.openai.com/docs/guides/text)
* - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)
*/
interface Text {
/**
* An object specifying the format that the model must output.
*
* Configuring `{ "type": "json_schema" }` enables Structured Outputs, which
* ensures the model will match your supplied JSON schema. Learn more in the
* [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).
*
* The default format is `{ "type": "text" }` with no additional options.
*
* **Not recommended for gpt-4o and newer models:**
*
* Setting to `{ "type": "json_object" }` enables the older JSON mode, which
* ensures the message the model generates is valid JSON. Using `json_schema` is
* preferred for models that support it.
*/
format?: ResponsesAPI.ResponseFormatTextConfig;
/**
* Constrains the verbosity of the model's response. Lower values will result in
* more concise responses, while higher values will result in more verbose
* responses. Currently supported values are `low`, `medium`, and `high`.
*/
verbosity?: 'low' | 'medium' | 'high' | null;
}
}
export declare namespace InputTokens {
export { type InputTokenCountResponse as InputTokenCountResponse, type InputTokenCountParams as InputTokenCountParams, };
}
//# sourceMappingURL=input-tokens.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"input-tokens.d.mts","sourceRoot":"","sources":["../../src/resources/responses/input-tokens.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,gCAA4B;AAClD,OAAO,KAAK,MAAM,sBAAkB;AACpC,OAAO,KAAK,YAAY,wBAAoB;AAC5C,OAAO,EAAE,UAAU,EAAE,mCAA+B;AACpD,OAAO,EAAE,cAAc,EAAE,2CAAuC;AAEhE,qBAAa,WAAY,SAAQ,WAAW;IAC1C;;;;;;;;;;OAUG;IACH,KAAK,CACH,IAAI,GAAE,qBAAqB,GAAG,IAAI,GAAG,SAAc,EACnD,OAAO,CAAC,EAAE,cAAc,GACvB,UAAU,CAAC,uBAAuB,CAAC;CAOvC;AAED,MAAM,WAAW,uBAAuB;IACtC,YAAY,EAAE,MAAM,CAAC;IAErB,MAAM,EAAE,uBAAuB,CAAC;CACjC;AAED,MAAM,WAAW,qBAAqB;IACpC;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,YAAY,CAAC,yBAAyB,GAAG,IAAI,CAAC;IAEtE;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC,YAAY,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC;IAE9D;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAE7B;;;;;;OAMG;IACH,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAEtB;;OAEG;IACH,mBAAmB,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;IAErC;;;;OAIG;IACH,WAAW,CAAC,EAAE,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,UAAU,GAAG,WAAW,CAAC;IAEvD;;;;;OAKG;IACH,oBAAoB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAErC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC;IAEpC;;;;;;OAMG;IACH,IAAI,CAAC,EAAE,qBAAqB,CAAC,IAAI,GAAG,IAAI,CAAC;IAEzC;;OAEG;IACH,WAAW,CAAC,EACR,YAAY,CAAC,iBAAiB,GAC9B,YAAY,CAAC,iBAAiB,GAC9B,YAAY,CAAC,eAAe,GAC5B,YAAY,CAAC,kBAAkB,GAC/B,YAAY,CAAC,aAAa,GAC1B,YAAY,CAAC,gBAAgB,GAC7B,YAAY,CAAC,oBAAoB,GACjC,YAAY,CAAC,eAAe,GAC5B,IAAI,CAAC;IAET;;;OAGG;IACH,KAAK,CAAC,EAAE,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAExC;;;;;;;OAOG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC;CAClC;AAED,yBAAiB,qBAAqB,CAAC;IACrC;;;;;;OAMG;IACH,UAAiB,IAAI;QACnB;;;;;;;;;;;;;;WAcG;QACH,MAAM,CAAC,EAAE,YAAY,CAAC,wBAAwB,CAAC;QAE/C;;;;WAIG;QACH,SAAS,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,IAAI,CAAC;KAC9C;CACF;AAED,MAAM,CAAC,OAAO,WAAW,WAAW,CAAC;IACnC,OAAO,EACL,KAAK,uBAAuB,IAAI,uBAAuB,EACvD,KAAK,qBAAqB,IAAI,qBAAqB,GACpD,CAAC;CACH"}
+136
View File
@@ -0,0 +1,136 @@
import { APIResource } from "../../core/resource.js";
import * as Shared from "../shared.js";
import * as ResponsesAPI from "./responses.js";
import { APIPromise } from "../../core/api-promise.js";
import { RequestOptions } from "../../internal/request-options.js";
export declare class InputTokens extends APIResource {
/**
* Returns input token counts of the request.
*
* Returns an object with `object` set to `response.input_tokens` and an
* `input_tokens` count.
*
* @example
* ```ts
* const response = await client.responses.inputTokens.count();
* ```
*/
count(body?: InputTokenCountParams | null | undefined, options?: RequestOptions): APIPromise<InputTokenCountResponse>;
}
export interface InputTokenCountResponse {
input_tokens: number;
object: 'response.input_tokens';
}
export interface InputTokenCountParams {
/**
* The conversation that this response belongs to. Items from this conversation are
* prepended to `input_items` for this response request. Input items and output
* items from this response are automatically added to this conversation after this
* response completes.
*/
conversation?: string | ResponsesAPI.ResponseConversationParam | null;
/**
* Text, image, or file inputs to the model, used to generate a response
*/
input?: string | Array<ResponsesAPI.ResponseInputItem> | null;
/**
* A system (or developer) message inserted into the model's context. When used
* along with `previous_response_id`, the instructions from a previous response
* will not be carried over to the next response. This makes it simple to swap out
* system (or developer) messages in new responses.
*/
instructions?: string | null;
/**
* Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a
* wide range of models with different capabilities, performance characteristics,
* and price points. Refer to the
* [model guide](https://platform.openai.com/docs/models) to browse and compare
* available models.
*/
model?: string | null;
/**
* Whether to allow the model to run tool calls in parallel.
*/
parallel_tool_calls?: boolean | null;
/**
* A model-owned style preset to apply to this request. Omit this parameter to use
* the model's default style. Supported values may expand over time. Values must be
* at most 64 characters.
*/
personality?: (string & {}) | 'friendly' | 'pragmatic';
/**
* The unique ID of the previous response to the model. Use this to create
* multi-turn conversations. Learn more about
* [conversation state](https://platform.openai.com/docs/guides/conversation-state).
* Cannot be used in conjunction with `conversation`.
*/
previous_response_id?: string | null;
/**
* **gpt-5 and o-series models only** Configuration options for
* [reasoning models](https://platform.openai.com/docs/guides/reasoning).
*/
reasoning?: Shared.Reasoning | null;
/**
* Configuration options for a text response from the model. Can be plain text or
* structured JSON data. Learn more:
*
* - [Text inputs and outputs](https://platform.openai.com/docs/guides/text)
* - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)
*/
text?: InputTokenCountParams.Text | null;
/**
* Controls which tool the model should use, if any.
*/
tool_choice?: ResponsesAPI.ToolChoiceOptions | ResponsesAPI.ToolChoiceAllowed | ResponsesAPI.ToolChoiceTypes | ResponsesAPI.ToolChoiceFunction | ResponsesAPI.ToolChoiceMcp | ResponsesAPI.ToolChoiceCustom | ResponsesAPI.ToolChoiceApplyPatch | ResponsesAPI.ToolChoiceShell | null;
/**
* An array of tools the model may call while generating a response. You can
* specify which tool to use by setting the `tool_choice` parameter.
*/
tools?: Array<ResponsesAPI.Tool> | null;
/**
* @deprecated The truncation strategy to use for the model response. - `auto`: If
* the input to this Response exceeds the model's context window size, the model
* will truncate the response to fit the context window by dropping items from the
* beginning of the conversation. - `disabled` (default): If the input size will
* exceed the context window size for a model, the request will fail with a 400
* error.
*/
truncation?: 'auto' | 'disabled';
}
export declare namespace InputTokenCountParams {
/**
* Configuration options for a text response from the model. Can be plain text or
* structured JSON data. Learn more:
*
* - [Text inputs and outputs](https://platform.openai.com/docs/guides/text)
* - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)
*/
interface Text {
/**
* An object specifying the format that the model must output.
*
* Configuring `{ "type": "json_schema" }` enables Structured Outputs, which
* ensures the model will match your supplied JSON schema. Learn more in the
* [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).
*
* The default format is `{ "type": "text" }` with no additional options.
*
* **Not recommended for gpt-4o and newer models:**
*
* Setting to `{ "type": "json_object" }` enables the older JSON mode, which
* ensures the message the model generates is valid JSON. Using `json_schema` is
* preferred for models that support it.
*/
format?: ResponsesAPI.ResponseFormatTextConfig;
/**
* Constrains the verbosity of the model's response. Lower values will result in
* more concise responses, while higher values will result in more verbose
* responses. Currently supported values are `low`, `medium`, and `high`.
*/
verbosity?: 'low' | 'medium' | 'high' | null;
}
}
export declare namespace InputTokens {
export { type InputTokenCountResponse as InputTokenCountResponse, type InputTokenCountParams as InputTokenCountParams, };
}
//# sourceMappingURL=input-tokens.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"input-tokens.d.ts","sourceRoot":"","sources":["../../src/resources/responses/input-tokens.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,+BAA4B;AAClD,OAAO,KAAK,MAAM,qBAAkB;AACpC,OAAO,KAAK,YAAY,uBAAoB;AAC5C,OAAO,EAAE,UAAU,EAAE,kCAA+B;AACpD,OAAO,EAAE,cAAc,EAAE,0CAAuC;AAEhE,qBAAa,WAAY,SAAQ,WAAW;IAC1C;;;;;;;;;;OAUG;IACH,KAAK,CACH,IAAI,GAAE,qBAAqB,GAAG,IAAI,GAAG,SAAc,EACnD,OAAO,CAAC,EAAE,cAAc,GACvB,UAAU,CAAC,uBAAuB,CAAC;CAOvC;AAED,MAAM,WAAW,uBAAuB;IACtC,YAAY,EAAE,MAAM,CAAC;IAErB,MAAM,EAAE,uBAAuB,CAAC;CACjC;AAED,MAAM,WAAW,qBAAqB;IACpC;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,YAAY,CAAC,yBAAyB,GAAG,IAAI,CAAC;IAEtE;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC,YAAY,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC;IAE9D;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAE7B;;;;;;OAMG;IACH,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAEtB;;OAEG;IACH,mBAAmB,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;IAErC;;;;OAIG;IACH,WAAW,CAAC,EAAE,CAAC,MAAM,GAAG,EAAE,CAAC,GAAG,UAAU,GAAG,WAAW,CAAC;IAEvD;;;;;OAKG;IACH,oBAAoB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAErC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC;IAEpC;;;;;;OAMG;IACH,IAAI,CAAC,EAAE,qBAAqB,CAAC,IAAI,GAAG,IAAI,CAAC;IAEzC;;OAEG;IACH,WAAW,CAAC,EACR,YAAY,CAAC,iBAAiB,GAC9B,YAAY,CAAC,iBAAiB,GAC9B,YAAY,CAAC,eAAe,GAC5B,YAAY,CAAC,kBAAkB,GAC/B,YAAY,CAAC,aAAa,GAC1B,YAAY,CAAC,gBAAgB,GAC7B,YAAY,CAAC,oBAAoB,GACjC,YAAY,CAAC,eAAe,GAC5B,IAAI,CAAC;IAET;;;OAGG;IACH,KAAK,CAAC,EAAE,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAExC;;;;;;;OAOG;IACH,UAAU,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC;CAClC;AAED,yBAAiB,qBAAqB,CAAC;IACrC;;;;;;OAMG;IACH,UAAiB,IAAI;QACnB;;;;;;;;;;;;;;WAcG;QACH,MAAM,CAAC,EAAE,YAAY,CAAC,wBAAwB,CAAC;QAE/C;;;;WAIG;QACH,SAAS,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,IAAI,CAAC;KAC9C;CACF;AAED,MAAM,CAAC,OAAO,WAAW,WAAW,CAAC;IACnC,OAAO,EACL,KAAK,uBAAuB,IAAI,uBAAuB,EACvD,KAAK,qBAAqB,IAAI,qBAAqB,GACpD,CAAC;CACH"}
+27
View File
@@ -0,0 +1,27 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.InputTokens = void 0;
const resource_1 = require("../../core/resource.js");
class InputTokens extends resource_1.APIResource {
/**
* Returns input token counts of the request.
*
* Returns an object with `object` set to `response.input_tokens` and an
* `input_tokens` count.
*
* @example
* ```ts
* const response = await client.responses.inputTokens.count();
* ```
*/
count(body = {}, options) {
return this._client.post('/responses/input_tokens', {
body,
...options,
__security: { bearerAuth: true },
});
}
}
exports.InputTokens = InputTokens;
//# sourceMappingURL=input-tokens.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"input-tokens.js","sourceRoot":"","sources":["../../src/resources/responses/input-tokens.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,qDAAkD;AAMlD,MAAa,WAAY,SAAQ,sBAAW;IAC1C;;;;;;;;;;OAUG;IACH,KAAK,CACH,OAAiD,EAAE,EACnD,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,yBAAyB,EAAE;YAClD,IAAI;YACJ,GAAG,OAAO;YACV,UAAU,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE;SACjC,CAAC,CAAC;IACL,CAAC;CACF;AAtBD,kCAsBC"}
+23
View File
@@ -0,0 +1,23 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../core/resource.mjs";
export class InputTokens extends APIResource {
/**
* Returns input token counts of the request.
*
* Returns an object with `object` set to `response.input_tokens` and an
* `input_tokens` count.
*
* @example
* ```ts
* const response = await client.responses.inputTokens.count();
* ```
*/
count(body = {}, options) {
return this._client.post('/responses/input_tokens', {
body,
...options,
__security: { bearerAuth: true },
});
}
}
//# sourceMappingURL=input-tokens.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"input-tokens.mjs","sourceRoot":"","sources":["../../src/resources/responses/input-tokens.ts"],"names":[],"mappings":"AAAA,sFAAsF;AAEtF,OAAO,EAAE,WAAW,EAAE,gCAA4B;AAMlD,MAAM,OAAO,WAAY,SAAQ,WAAW;IAC1C;;;;;;;;;;OAUG;IACH,KAAK,CACH,OAAiD,EAAE,EACnD,OAAwB;QAExB,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,yBAAyB,EAAE;YAClD,IAAI;YACJ,GAAG,OAAO;YACV,UAAU,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE;SACjC,CAAC,CAAC;IACL,CAAC;CACF"}
+71
View File
@@ -0,0 +1,71 @@
import * as ResponsesAPI from "./responses.mjs";
import { OpenAI } from "../../client.mjs";
import { EventEmitter } from "../../core/EventEmitter.mjs";
import { OpenAIError } from "../../core/error.mjs";
import type { RawWebSocketData, ReconnectingEvent, UnsentMessage } from "../../internal/ws.mjs";
export type ResponsesStreamMessage = {
type: 'connecting' | 'open' | 'closing';
} | {
type: 'close';
code: number;
reason: string;
unsent: UnsentMessage<ResponsesAPI.ResponsesClientEvent>[];
} | {
type: 'reconnecting';
reconnect: ReconnectingEvent;
} | {
type: 'reconnected';
} | {
type: 'message';
message: ResponsesAPI.ResponsesServerEvent;
} | {
type: 'raw';
data: RawWebSocketData;
} | {
type: 'error';
error: WebSocketError;
};
export declare class WebSocketError extends OpenAIError {
/**
* The error data that the API sent back in an error event.
*/
error?: ResponsesAPI.ResponseErrorEvent | undefined;
constructor(message: string, event: ResponsesAPI.ResponseErrorEvent | null);
}
type Simplify<T> = {
[KeyType in keyof T]: T[KeyType];
} & {};
type WebSocketEvents = Simplify<{
event: (event: ResponsesAPI.ResponsesServerEvent) => void;
raw: (data: RawWebSocketData) => void;
error: (error: WebSocketError) => void;
close: (code: number, reason: string, unsent: UnsentMessage<ResponsesAPI.ResponsesClientEvent>[]) => void;
reconnecting: (event: ReconnectingEvent) => void;
reconnected: () => void;
} & {
[EventType in Exclude<NonNullable<ResponsesAPI.ResponsesServerEvent['type']>, 'error'>]: (event: Extract<ResponsesAPI.ResponsesServerEvent, {
type?: EventType;
}>) => unknown;
}>;
export declare abstract class ResponsesEmitter extends EventEmitter<WebSocketEvents> {
/**
* Send an event to the API.
*/
abstract send(event: ResponsesAPI.ResponsesClientEvent): void;
/**
* Send raw data over the WebSocket without JSON serialization.
*/
abstract sendRaw(data: RawWebSocketData): void;
/**
* Close the WebSocket connection.
*/
abstract close(props?: {
code: number;
reason: string;
}): void;
protected _onError(event: null, message: string, cause: any): void;
protected _onError(event: ResponsesAPI.ResponseErrorEvent, message?: string | undefined): void;
}
export declare function buildURL(client: OpenAI, parameters: Record<string, unknown>): URL;
export {};
//# sourceMappingURL=internal-base.d.mts.map
@@ -0,0 +1 @@
{"version":3,"file":"internal-base.d.mts","sourceRoot":"","sources":["../../src/resources/responses/internal-base.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,YAAY,wBAAoB;AAC5C,OAAO,EAAE,MAAM,EAAE,yBAAqB;AACtC,OAAO,EAAE,YAAY,EAAE,oCAAgC;AACvD,OAAO,EAAE,WAAW,EAAE,6BAAyB;AAE/C,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,aAAa,EAAE,8BAA0B;AAE5F,MAAM,MAAM,sBAAsB,GAC9B;IAAE,IAAI,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAAA;CAAE,GAC3C;IACE,IAAI,EAAE,OAAO,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,aAAa,CAAC,YAAY,CAAC,oBAAoB,CAAC,EAAE,CAAC;CAC5D,GACD;IAAE,IAAI,EAAE,cAAc,CAAC;IAAC,SAAS,EAAE,iBAAiB,CAAA;CAAE,GACtD;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,GACvB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,YAAY,CAAC,oBAAoB,CAAA;CAAE,GAC/D;IAAE,IAAI,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,gBAAgB,CAAA;CAAE,GACvC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,cAAc,CAAA;CAAE,CAAC;AAE7C,qBAAa,cAAe,SAAQ,WAAW;IAC7C;;OAEG;IACH,KAAK,CAAC,EAAE,YAAY,CAAC,kBAAkB,GAAG,SAAS,CAAC;gBAExC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,CAAC,kBAAkB,GAAG,IAAI;CAK3E;AAED,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,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,IAAI;IAClE,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC,kBAAkB,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;CA0B/F;AAED,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,GAAG,CAMjF"}
+71
View File
@@ -0,0 +1,71 @@
import * as ResponsesAPI from "./responses.js";
import { OpenAI } from "../../client.js";
import { EventEmitter } from "../../core/EventEmitter.js";
import { OpenAIError } from "../../core/error.js";
import type { RawWebSocketData, ReconnectingEvent, UnsentMessage } from "../../internal/ws.js";
export type ResponsesStreamMessage = {
type: 'connecting' | 'open' | 'closing';
} | {
type: 'close';
code: number;
reason: string;
unsent: UnsentMessage<ResponsesAPI.ResponsesClientEvent>[];
} | {
type: 'reconnecting';
reconnect: ReconnectingEvent;
} | {
type: 'reconnected';
} | {
type: 'message';
message: ResponsesAPI.ResponsesServerEvent;
} | {
type: 'raw';
data: RawWebSocketData;
} | {
type: 'error';
error: WebSocketError;
};
export declare class WebSocketError extends OpenAIError {
/**
* The error data that the API sent back in an error event.
*/
error?: ResponsesAPI.ResponseErrorEvent | undefined;
constructor(message: string, event: ResponsesAPI.ResponseErrorEvent | null);
}
type Simplify<T> = {
[KeyType in keyof T]: T[KeyType];
} & {};
type WebSocketEvents = Simplify<{
event: (event: ResponsesAPI.ResponsesServerEvent) => void;
raw: (data: RawWebSocketData) => void;
error: (error: WebSocketError) => void;
close: (code: number, reason: string, unsent: UnsentMessage<ResponsesAPI.ResponsesClientEvent>[]) => void;
reconnecting: (event: ReconnectingEvent) => void;
reconnected: () => void;
} & {
[EventType in Exclude<NonNullable<ResponsesAPI.ResponsesServerEvent['type']>, 'error'>]: (event: Extract<ResponsesAPI.ResponsesServerEvent, {
type?: EventType;
}>) => unknown;
}>;
export declare abstract class ResponsesEmitter extends EventEmitter<WebSocketEvents> {
/**
* Send an event to the API.
*/
abstract send(event: ResponsesAPI.ResponsesClientEvent): void;
/**
* Send raw data over the WebSocket without JSON serialization.
*/
abstract sendRaw(data: RawWebSocketData): void;
/**
* Close the WebSocket connection.
*/
abstract close(props?: {
code: number;
reason: string;
}): void;
protected _onError(event: null, message: string, cause: any): void;
protected _onError(event: ResponsesAPI.ResponseErrorEvent, message?: string | undefined): void;
}
export declare function buildURL(client: OpenAI, parameters: Record<string, unknown>): URL;
export {};
//# sourceMappingURL=internal-base.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"internal-base.d.ts","sourceRoot":"","sources":["../../src/resources/responses/internal-base.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,YAAY,uBAAoB;AAC5C,OAAO,EAAE,MAAM,EAAE,wBAAqB;AACtC,OAAO,EAAE,YAAY,EAAE,mCAAgC;AACvD,OAAO,EAAE,WAAW,EAAE,4BAAyB;AAE/C,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,aAAa,EAAE,6BAA0B;AAE5F,MAAM,MAAM,sBAAsB,GAC9B;IAAE,IAAI,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAAA;CAAE,GAC3C;IACE,IAAI,EAAE,OAAO,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,aAAa,CAAC,YAAY,CAAC,oBAAoB,CAAC,EAAE,CAAC;CAC5D,GACD;IAAE,IAAI,EAAE,cAAc,CAAC;IAAC,SAAS,EAAE,iBAAiB,CAAA;CAAE,GACtD;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,GACvB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,YAAY,CAAC,oBAAoB,CAAA;CAAE,GAC/D;IAAE,IAAI,EAAE,KAAK,CAAC;IAAC,IAA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AAQ,CAAC,IAAI,CAAC,KAAK,EAAE,YAAY,CAAC,oBAAoB,GAAG,IAAI;IAE7D;;OAEG;IACH,QAAQ,CAAC,OAAO,CAAC,IAAI,EAAE,gBAAgB,GAAG,IAAI;IAE9C;;OAEG;IACH,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI;IAE9D,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,IAAI;IAClE,SAAS,CAAC,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC,kBAAkB,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;CA0B/F;AAED,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,GAAG,CAMjF"}
+48
View File
@@ -0,0 +1,48 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResponsesEmitter = exports.WebSocketError = void 0;
exports.buildURL = buildURL;
const EventEmitter_1 = require("../../core/EventEmitter.js");
const error_1 = require("../../core/error.js");
class WebSocketError extends error_1.OpenAIError {
constructor(message, event) {
super(message);
this.error = event ?? undefined;
}
}
exports.WebSocketError = WebSocketError;
class ResponsesEmitter extends EventEmitter_1.EventEmitter {
_onError(event, message, cause) {
message = message ?? safeJSONStringify(event) ?? 'unknown error';
if (!this._hasListener('error')) {
const error = new WebSocketError(message +
`\n\nTo resolve these unhandled rejection errors you should bind an \`error\` callback, e.g. \`ws.on('error', (error) => ...)\` `, event);
// @ts-ignore
error.cause = cause;
Promise.reject(error);
return;
}
const error = new WebSocketError(message, event);
// @ts-ignore
error.cause = cause;
this._emit('error', error);
}
}
exports.ResponsesEmitter = ResponsesEmitter;
function buildURL(client, parameters) {
const { ...query } = parameters;
const endpoint = '/responses';
const url = new URL(client.buildURL(endpoint, query, undefined));
url.protocol = url.protocol === 'http:' || url.protocol === 'ws:' ? 'ws:' : 'wss:';
return url;
}
function safeJSONStringify(value) {
try {
return JSON.stringify(value);
}
catch {
return null;
}
}
//# sourceMappingURL=internal-base.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"internal-base.js","sourceRoot":"","sources":["../../src/resources/responses/internal-base.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAkGtF,4BAMC;AApGD,6DAAuD;AACvD,+CAA+C;AAkB/C,MAAa,cAAe,SAAQ,mBAAW;IAM7C,YAAY,OAAe,EAAE,KAA6C;QACxE,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,KAAK,GAAG,KAAK,IAAI,SAAS,CAAC;IAClC,CAAC;CACF;AAXD,wCAWC;AAmBD,MAAsB,gBAAiB,SAAQ,2BAA6B;IAkBhE,QAAQ,CAChB,KAA6C,EAC7C,OAA4B,EAC5B,KAAW;QAEX,OAAO,GAAG,OAAO,IAAI,iBAAiB,CAAC,KAAK,CAAC,IAAI,eAAe,CAAC;QAEjE,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE,CAAC;YAChC,MAAM,KAAK,GAAG,IAAI,cAAc,CAC9B,OAAO;gBACL,iIAAiI,EACnI,KAAK,CACN,CAAC;YACF,aAAa;YACb,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;YACpB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACtB,OAAO;QACT,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,cAAc,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACjD,aAAa;QACb,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;QAEpB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC7B,CAAC;CACF;AA3CD,4CA2CC;AAED,SAAgB,QAAQ,CAAC,MAAc,EAAE,UAAmC;IAC1E,MAAM,EAAE,GAAG,KAAK,EAAE,GAAG,UAAU,CAAC;IAChC,MAAM,QAAQ,GAAG,YAAY,CAAC;IAC9B,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC;IACjE,GAAG,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,KAAK,OAAO,IAAI,GAAG,CAAC,QAAQ,KAAK,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC;IACnF,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc;IACvC,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAC/B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC"}
+42
View File
@@ -0,0 +1,42 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { EventEmitter } from "../../core/EventEmitter.mjs";
import { OpenAIError } from "../../core/error.mjs";
export class WebSocketError extends OpenAIError {
constructor(message, event) {
super(message);
this.error = event ?? undefined;
}
}
export class ResponsesEmitter extends EventEmitter {
_onError(event, message, cause) {
message = message ?? safeJSONStringify(event) ?? 'unknown error';
if (!this._hasListener('error')) {
const error = new WebSocketError(message +
`\n\nTo resolve these unhandled rejection errors you should bind an \`error\` callback, e.g. \`ws.on('error', (error) => ...)\` `, event);
// @ts-ignore
error.cause = cause;
Promise.reject(error);
return;
}
const error = new WebSocketError(message, event);
// @ts-ignore
error.cause = cause;
this._emit('error', error);
}
}
export function buildURL(client, parameters) {
const { ...query } = parameters;
const endpoint = '/responses';
const url = new URL(client.buildURL(endpoint, query, undefined));
url.protocol = url.protocol === 'http:' || url.protocol === 'ws:' ? 'ws:' : 'wss:';
return url;
}
function safeJSONStringify(value) {
try {
return JSON.stringify(value);
}
catch {
return null;
}
}
//# sourceMappingURL=internal-base.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"internal-base.mjs","sourceRoot":"","sources":["../../src/resources/responses/internal-base.ts"],"names":[],"mappings":"AAAA,sFAAsF;AAItF,OAAO,EAAE,YAAY,EAAE,oCAAgC;AACvD,OAAO,EAAE,WAAW,EAAE,6BAAyB;AAkB/C,MAAM,OAAO,cAAe,SAAQ,WAAW;IAM7C,YAAY,OAAe,EAAE,KAA6C;QACxE,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,KAAK,GAAG,KAAK,IAAI,SAAS,CAAC;IAClC,CAAC;CACF;AAmBD,MAAM,OAAgB,gBAAiB,SAAQ,YAA6B;IAkBhE,QAAQ,CAChB,KAA6C,EAC7C,OAA4B,EAC5B,KAAW;QAEX,OAAO,GAAG,OAAO,IAAI,iBAAiB,CAAC,KAAK,CAAC,IAAI,eAAe,CAAC;QAEjE,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE,CAAC;YAChC,MAAM,KAAK,GAAG,IAAI,cAAc,CAC9B,OAAO;gBACL,iIAAiI,EACnI,KAAK,CACN,CAAC;YACF,aAAa;YACb,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;YACpB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACtB,OAAO;QACT,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,cAAc,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACjD,aAAa;QACb,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC;QAEpB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC7B,CAAC;CACF;AAED,MAAM,UAAU,QAAQ,CAAC,MAAc,EAAE,UAAmC;IAC1E,MAAM,EAAE,GAAG,KAAK,EAAE,GAAG,UAAU,CAAC;IAChC,MAAM,QAAQ,GAAG,YAAY,CAAC;IAC9B,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC;IACjE,GAAG,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,KAAK,OAAO,IAAI,GAAG,CAAC,QAAQ,KAAK,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC;IACnF,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc;IACvC,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAC/B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC"}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+115
View File
@@ -0,0 +1,115 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Responses = void 0;
const tslib_1 = require("../../internal/tslib.js");
const ResponsesParser_1 = require("../../lib/ResponsesParser.js");
const ResponseStream_1 = require("../../lib/responses/ResponseStream.js");
const resource_1 = require("../../core/resource.js");
const InputItemsAPI = tslib_1.__importStar(require("./input-items.js"));
const input_items_1 = require("./input-items.js");
const InputTokensAPI = tslib_1.__importStar(require("./input-tokens.js"));
const input_tokens_1 = require("./input-tokens.js");
const headers_1 = require("../../internal/headers.js");
const path_1 = require("../../internal/utils/path.js");
class Responses extends resource_1.APIResource {
constructor() {
super(...arguments);
this.inputItems = new InputItemsAPI.InputItems(this._client);
this.inputTokens = new InputTokensAPI.InputTokens(this._client);
}
create(body, options) {
return this._client.post('/responses', {
body,
...options,
stream: body.stream ?? false,
__security: { bearerAuth: true },
})._thenUnwrap((rsp) => {
if ('object' in rsp && rsp.object === 'response') {
(0, ResponsesParser_1.addOutputText)(rsp);
}
return rsp;
});
}
retrieve(responseID, query = {}, options) {
return this._client.get((0, path_1.path) `/responses/${responseID}`, {
query,
...options,
stream: query?.stream ?? false,
__security: { bearerAuth: true },
})._thenUnwrap((rsp) => {
if ('object' in rsp && rsp.object === 'response') {
(0, ResponsesParser_1.addOutputText)(rsp);
}
return rsp;
});
}
/**
* Deletes a model response with the given ID.
*
* @example
* ```ts
* await client.responses.delete(
* 'resp_677efb5139a88190b512bc3fef8e535d',
* );
* ```
*/
delete(responseID, options) {
return this._client.delete((0, path_1.path) `/responses/${responseID}`, {
...options,
headers: (0, headers_1.buildHeaders)([{ Accept: '*/*' }, options?.headers]),
__security: { bearerAuth: true },
});
}
parse(body, options) {
return this._client.responses
.create(body, options)
._thenUnwrap((response) => (0, ResponsesParser_1.parseResponse)(response, body));
}
/**
* Creates a model response stream
*/
stream(body, options) {
return ResponseStream_1.ResponseStream.createResponse(this._client, body, options);
}
/**
* Cancels a model response with the given ID. Only responses created with the
* `background` parameter set to `true` can be cancelled.
* [Learn more](https://platform.openai.com/docs/guides/background).
*
* @example
* ```ts
* const response = await client.responses.cancel(
* 'resp_677efb5139a88190b512bc3fef8e535d',
* );
* ```
*/
cancel(responseID, options) {
return this._client.post((0, path_1.path) `/responses/${responseID}/cancel`, {
...options,
__security: { bearerAuth: true },
});
}
/**
* Compact a conversation. Returns a compacted response object.
*
* Learn when and how to compact long-running conversations in the
* [conversation state guide](https://platform.openai.com/docs/guides/conversation-state#managing-the-context-window).
* For ZDR-compatible compaction details, see
* [Compaction (advanced)](https://platform.openai.com/docs/guides/conversation-state#compaction-advanced).
*
* @example
* ```ts
* const compactedResponse = await client.responses.compact({
* model: 'gpt-5.4',
* });
* ```
*/
compact(body, options) {
return this._client.post('/responses/compact', { body, ...options, __security: { bearerAuth: true } });
}
}
exports.Responses = Responses;
Responses.InputItems = input_items_1.InputItems;
Responses.InputTokens = input_tokens_1.InputTokens;
//# sourceMappingURL=responses.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"responses.js","sourceRoot":"","sources":["../../src/resources/responses/responses.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;AAEtF,kEAKmC;AACnC,0EAA0F;AAC1F,qDAAkD;AAGlD,wEAA+C;AAC/C,kDAAkF;AAClF,0EAAiD;AACjD,oDAA6F;AAI7F,uDAAsD;AAEtD,uDAAiD;AAoDjD,MAAa,SAAU,SAAQ,sBAAW;IAA1C;;QACE,eAAU,GAA6B,IAAI,aAAa,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAClF,gBAAW,GAA+B,IAAI,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAyKzF,CAAC;IA5IC,MAAM,CACJ,IAA0B,EAC1B,OAAwB;QAExB,OACE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,EAAE;YAC9B,IAAI;YACJ,GAAG,OAAO;YACV,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,KAAK;YAC5B,UAAU,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE;SACjC,CACF,CAAC,WAAW,CAAC,CAAC,GAAG,EAAE,EAAE;YACpB,IAAI,QAAQ,IAAI,GAAG,IAAI,GAAG,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;gBACjD,IAAA,+BAAa,EAAC,GAAe,CAAC,CAAC;YACjC,CAAC;YAED,OAAO,GAAG,CAAC;QACb,CAAC,CAAmE,CAAC;IACvE,CAAC;IA2BD,QAAQ,CACN,UAAkB,EAClB,QAA4C,EAAE,EAC9C,OAAwB;QAExB,OACE,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAA,WAAI,EAAA,cAAc,UAAU,EAAE,EAAE;YAC/C,KAAK;YACL,GAAG,OAAO;YACV,MAAM,EAAE,KAAK,EAAE,MAAM,IAAI,KAAK;YAC9B,UAAU,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE;SACjC,CACF,CAAC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;;;;;;;;OAcG;IACH,OAAO,CAAC,IAA2B,EAAE,OAAwB;QAC3D,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,oBAAoB,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,EAAE,UAAU,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;IACzG,CAAC;CACF;AA3KD,8BA2KC;AAi5PD,SAAS,CAAC,UAAU,GAAG,wBAAU,CAAC;AAClC,SAAS,CAAC,WAAW,GAAG,0BAAW,CAAC"}
+110
View File
@@ -0,0 +1,110 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { parseResponse, addOutputText, } from "../../lib/ResponsesParser.mjs";
import { ResponseStream } from "../../lib/responses/ResponseStream.mjs";
import { APIResource } from "../../core/resource.mjs";
import * as InputItemsAPI from "./input-items.mjs";
import { InputItems } from "./input-items.mjs";
import * as InputTokensAPI from "./input-tokens.mjs";
import { InputTokens } from "./input-tokens.mjs";
import { buildHeaders } from "../../internal/headers.mjs";
import { path } from "../../internal/utils/path.mjs";
export class Responses extends APIResource {
constructor() {
super(...arguments);
this.inputItems = new InputItemsAPI.InputItems(this._client);
this.inputTokens = new InputTokensAPI.InputTokens(this._client);
}
create(body, options) {
return this._client.post('/responses', {
body,
...options,
stream: body.stream ?? false,
__security: { bearerAuth: true },
})._thenUnwrap((rsp) => {
if ('object' in rsp && rsp.object === 'response') {
addOutputText(rsp);
}
return rsp;
});
}
retrieve(responseID, query = {}, options) {
return this._client.get(path `/responses/${responseID}`, {
query,
...options,
stream: query?.stream ?? false,
__security: { bearerAuth: true },
})._thenUnwrap((rsp) => {
if ('object' in rsp && rsp.object === 'response') {
addOutputText(rsp);
}
return rsp;
});
}
/**
* Deletes a model response with the given ID.
*
* @example
* ```ts
* await client.responses.delete(
* 'resp_677efb5139a88190b512bc3fef8e535d',
* );
* ```
*/
delete(responseID, options) {
return this._client.delete(path `/responses/${responseID}`, {
...options,
headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
__security: { bearerAuth: true },
});
}
parse(body, options) {
return this._client.responses
.create(body, options)
._thenUnwrap((response) => parseResponse(response, body));
}
/**
* Creates a model response stream
*/
stream(body, options) {
return ResponseStream.createResponse(this._client, body, options);
}
/**
* Cancels a model response with the given ID. Only responses created with the
* `background` parameter set to `true` can be cancelled.
* [Learn more](https://platform.openai.com/docs/guides/background).
*
* @example
* ```ts
* const response = await client.responses.cancel(
* 'resp_677efb5139a88190b512bc3fef8e535d',
* );
* ```
*/
cancel(responseID, options) {
return this._client.post(path `/responses/${responseID}/cancel`, {
...options,
__security: { bearerAuth: true },
});
}
/**
* Compact a conversation. Returns a compacted response object.
*
* Learn when and how to compact long-running conversations in the
* [conversation state guide](https://platform.openai.com/docs/guides/conversation-state#managing-the-context-window).
* For ZDR-compatible compaction details, see
* [Compaction (advanced)](https://platform.openai.com/docs/guides/conversation-state#compaction-advanced).
*
* @example
* ```ts
* const compactedResponse = await client.responses.compact({
* model: 'gpt-5.4',
* });
* ```
*/
compact(body, options) {
return this._client.post('/responses/compact', { body, ...options, __security: { bearerAuth: true } });
}
}
Responses.InputItems = InputItems;
Responses.InputTokens = InputTokens;
//# sourceMappingURL=responses.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"responses.mjs","sourceRoot":"","sources":["../../src/resources/responses/responses.ts"],"names":[],"mappings":"AAAA,sFAAsF;AAEtF,OAAO,EAEL,aAAa,EAEb,aAAa,GACd,sCAAkC;AACnC,OAAO,EAAE,cAAc,EAAwB,+CAA2C;AAC1F,OAAO,EAAE,WAAW,EAAE,gCAA4B;AAGlD,OAAO,KAAK,aAAa,0BAAsB;AAC/C,OAAO,EAAuB,UAAU,EAAoB,0BAAsB;AAClF,OAAO,KAAK,cAAc,2BAAuB;AACjD,OAAO,EAAkD,WAAW,EAAE,2BAAuB;AAI7F,OAAO,EAAE,YAAY,EAAE,mCAA+B;AAEtD,OAAO,EAAE,IAAI,EAAE,sCAAkC;AAo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W,GAAG,WAAW,CAAC"}
+106
View File
@@ -0,0 +1,106 @@
import { ResponsesEmitter, ResponsesStreamMessage } from "./internal-base.mjs";
import { type WebSocketLike } from "../../internal/ws-adapter.mjs";
import { type RawWebSocketData, type ReconnectingEvent, type ReconnectingOverrides } from "../../internal/ws.mjs";
import * as ResponsesAPI from "./responses.mjs";
import { OpenAI } from "../../client.mjs";
export interface ResponsesWSReconnectOptions {
/**
* Called before each reconnect attempt. Return an object with
* `parameters` to override query parameters for the next connection.
*/
onReconnecting(event: ReconnectingEvent<Record<string, unknown>>): ReconnectingOverrides<Record<string, unknown>> | void;
/**
* Maximum number of reconnection attempts. Default: 5.
* Set to 0 to disable reconnection entirely.
*/
maxRetries?: number;
/**
* Initial backoff delay in milliseconds. Default: 500.
*/
initialDelay?: number;
/**
* Maximum backoff delay in milliseconds. Default: 8000.
*/
maxDelay?: number;
}
export interface ResponsesWSBaseOptions {
/**
* Options for automatic reconnection on recoverable close codes.
* Automatic reconnection is only enabled when this has a non-null value.
*/
reconnect?: ResponsesWSReconnectOptions | null | undefined;
/**
* Maximum size of the outgoing message queue in bytes.
* Messages queued while the socket is connecting or reconnecting are held
* in memory up to this limit. Once the limit is reached, new messages are
* discarded and an `error` event is emitted.
* Default: 1 MB
*/
maxQueueSize?: number | undefined;
}
export declare abstract class ResponsesWSBase<TSocket extends WebSocketLike> extends ResponsesEmitter {
url: URL;
socket: TSocket;
protected _client: OpenAI;
protected _parameters: Record<string, unknown> | null | undefined;
private _reconnectOptions;
private _sendQueue;
private _isReconnecting;
private _intentionallyClosed;
private _closeCode;
private _closeReason;
private _lastCloseCode;
private _lastCloseReason;
private _internalEvents;
constructor(client: OpenAI, options?: ResponsesWSBaseOptions | undefined);
/** Establishes the initial WebSocket connection. */
protected _connectInitial(): void;
/** Creates a platform-specific WebSocket for the given URL and auth headers. */
protected abstract _createSocket(url: URL, authHeaders: Record<string, string>): TSocket;
send(event: ResponsesAPI.ResponsesClientEvent): void;
sendRaw(data: RawWebSocketData): void;
close(props?: {
code: number;
reason: string;
}): void;
/**
* Returns an async iterator over WebSocket lifecycle and message events,
* providing an alternative to the event-based `.on()` API.
* The iterator will exit if the socket closes but exiting the iterator
* does not close the socket.
*
* @example
* ```ts
* for await (const event of client.stream()) {
* switch (event.type) {
* case 'message':
* console.log('received:', event.message);
* break;
* case 'error':
* console.error(event.error);
* break;
* case 'close':
* console.log('connection closed');
* break;
* }
* }
* ```
*/
stream(): AsyncIterableIterator<ResponsesStreamMessage>;
[Symbol.asyncIterator](): AsyncIterableIterator<ResponsesStreamMessage>;
private _connect;
private _canReconnect;
private _reconnect;
/**
* Resolves once the socket is open, rejects if it errors or closes first
*/
private _awaitOpen;
private _flushSendQueue;
/**
* Emits the public `close` event with unsent messages and the internal
* `close` event used by the async iterator.
*/
private _emitPermanentClose;
protected _authHeaders(): Record<string, string>;
}
//# sourceMappingURL=ws-base.d.mts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"ws-base.d.mts","sourceRoot":"","sources":["../../src/resources/responses/ws-base.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,sBAAsB,EAA4B,4BAAwB;AAGrG,OAAO,EAAE,KAAK,aAAa,EAAc,sCAAkC;AAC3E,OAAO,EAIL,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,KAAK,qBAAqB,EAE3B,8BAA0B;AAC3B,OAAO,KAAK,YAAY,wBAAoB;AAC5C,OAAO,EAAE,MAAM,EAAE,yBAAqB;AAGtC,MAAM,WAAW,2BAA2B;IAC1C;;;OAGG;IACH,cAAc,CACZ,KAAK,EAAE,iBAAiB,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAChD,qBAAqB,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC;IAEzD;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,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,MAAM,CAAA;KAAE;IAe9C;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,MAAM,IAAI,qBAAqB,CAAC,sBAAsB,CAAC;IAIvD,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,qBAAqB,CAAC,sBAAsB,CAAC;IAwJvE,OAAO,CAAC,QAAQ;IA2DhB,OAAO,CAAC,aAAa;YAQP,UAAU;IA+IxB;;OAEG;IACH,OAAO,CAAC,UAAU;IAyBlB,OAAO,CAAC,eAAe;IAYvB;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IAU3B,SAAS,CAAC,YAAY,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;CAMjD"}
+106
View File
@@ -0,0 +1,106 @@
import { ResponsesEmitter, ResponsesStreamMessage } from "./internal-base.js";
import { type WebSocketLike } from "../../internal/ws-adapter.js";
import { type RawWebSocketData, type ReconnectingEvent, type ReconnectingOverrides } from "../../internal/ws.js";
import * as ResponsesAPI from "./responses.js";
import { OpenAI } from "../../client.js";
export interface ResponsesWSReconnectOptions {
/**
* Called before each reconnect attempt. Return an object with
* `parameters` to override query parameters for the next connection.
*/
onReconnecting(event: ReconnectingEvent<Record<string, unknown>>): ReconnectingOverrides<Record<string, unknown>> | void;
/**
* Maximum number of reconnection attempts. Default: 5.
* Set to 0 to disable reconnection entirely.
*/
maxRetries?: number;
/**
* Initial backoff delay in milliseconds. Default: 500.
*/
initialDelay?: number;
/**
* Maximum backoff delay in milliseconds. Default: 8000.
*/
maxDelay?: number;
}
export interface ResponsesWSBaseOptions {
/**
* Options for automatic reconnection on recoverable close codes.
* Automatic reconnection is only enabled when this has a non-null value.
*/
reconnect?: ResponsesWSReconnectOptions | null | undefined;
/**
* Maximum size of the outgoing message queue in bytes.
* Messages queued while the socket is connecting or reconnecting are held
* in memory up to this limit. Once the limit is reached, new messages are
* discarded and an `error` event is emitted.
* Default: 1 MB
*/
maxQueueSize?: number | undefined;
}
export declare abstract class ResponsesWSBase<TSocket extends WebSocketLike> extends ResponsesEmitter {
url: URL;
socket: TSocket;
protected _client: OpenAI;
protected _parameters: Record<string, unknown> | null | undefined;
private _reconnectOptions;
private _sendQueue;
private _isReconnecting;
private _intentionallyClosed;
private _closeCode;
private _closeReason;
private _lastCloseCode;
private _lastCloseReason;
private _internalEvents;
constructor(client: OpenAI, options?: ResponsesWSBaseOptions | undefined);
/** Establishes the initial WebSocket connection. */
protected _connectInitial(): void;
/** Creates a platform-specific WebSocket for the given URL and auth headers. */
protected abstract _createSocket(url: URL, authHeaders: Record<string, string>): TSocket;
send(event: ResponsesAPI.ResponsesClientEvent): void;
sendRaw(data: RawWebSocketData): void;
close(props?: {
code: number;
reason: string;
}): void;
/**
* Returns an async iterator over WebSocket lifecycle and message events,
* providing an alternative to the event-based `.on()` API.
* The iterator will exit if the socket closes but exiting the iterator
* does not close the socket.
*
* @example
* ```ts
* for await (const event of client.stream()) {
* switch (event.type) {
* case 'message':
* console.log('received:', event.message);
* break;
* case 'error':
* console.error(event.error);
* break;
* case 'close':
* console.log('connection closed');
* break;
* }
* }
* ```
*/
stream(): AsyncIterableIterator<ResponsesStreamMessage>;
[Symbol.asyncIterator](): AsyncIterableIterator<ResponsesStreamMessage>;
private _connect;
private _canReconnect;
private _reconnect;
/**
* Resolves once the socket is open, rejects if it errors or closes first
*/
private _awaitOpen;
private _flushSendQueue;
/**
* Emits the public `close` event with unsent messages and the internal
* `close` event used by the async iterator.
*/
private _emitPermanentClose;
protected _authHeaders(): Record<string, string>;
}
//# sourceMappingURL=ws-base.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"ws-base.d.ts","sourceRoot":"","sources":["../../src/resources/responses/ws-base.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,sBAAsB,EAA4B,2BAAwB;AAGrG,OAAO,EAAE,KAAK,aAAa,EAAc,qCAAkC;AAC3E,OAAO,EAIL,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,KAAK,qBAAqB,E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BAAsB,GAAG,SAAS;IAQxE,oDAAoD;IACpD,SAAS,CAAC,eAAe,IAAI,IAAI;IAKjC,gFAAgF;IAChF,SAAS,CAAC,QAAQ,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,OAAO;IAExF,IAAI,CAAC,KAAK,EAAE,YAAY,CAAC,oBAAoB;IAsB7C,OAAO,CAAC,IAAI,EAAE,gBAAgB;IAsB9B,KAAK,CAAC,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE;IAe9C;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,MAAM,IAAI,qBAAqB,CAAC,sBAAsB,CAAC;IAIvD,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,qBAAqB,CAAC,sBAAsB,CAAC;IAwJvE,OAAO,CAAC,QAAQ;IA2DhB,OAAO,CAAC,aAAa;YAQP,UAAU;IA+IxB;;OAEG;IACH,OAAO,CAAC,UAAU;IAyBlB,OAAO,CAAC,eAAe;IAYvB;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IAU3B,SAAS,CAAC,YAAY,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;CAMjD"}
+476
View File
@@ -0,0 +1,476 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResponsesWSBase = void 0;
const internal_base_1 = require("./internal-base.js");
const EventEmitter_1 = require("../../core/EventEmitter.js");
const sleep_1 = require("../../internal/utils/sleep.js");
const ws_adapter_1 = require("../../internal/ws-adapter.js");
const ws_1 = require("../../internal/ws.js");
const error_1 = require("../../core/error.js");
class ResponsesWSBase extends internal_base_1.ResponsesEmitter {
constructor(client, options) {
super();
this._isReconnecting = false;
this._intentionallyClosed = false;
this._closeCode = 1000;
this._closeReason = 'OK';
this._lastCloseCode = 1006;
this._lastCloseReason = '';
// Necessary to keep the public event interface clean while we manage reconnecting
this._internalEvents = new EventEmitter_1.InternalEventEmitter();
this._client = client;
this._parameters = undefined;
this._reconnectOptions = options?.reconnect ?? null;
this._sendQueue = new ws_1.SendQueue(options?.maxQueueSize);
}
/** Establishes the initial WebSocket connection. */
_connectInitial() {
this.url = (0, internal_base_1.buildURL)(this._client, {});
this.socket = this._connect();
}
send(event) {
if (!this.socket) {
throw new error_1.OpenAIError('Internal error: failed to initialize socket. Please report this issue.');
}
if (this._isReconnecting || this.socket.readyState === ws_adapter_1.ReadyState.CONNECTING) {
if (!this._sendQueue.enqueue(event)) {
this._onError(null, 'send queue is full, message discarded', undefined);
}
return;
}
if (this.socket.readyState !== ws_adapter_1.ReadyState.OPEN) {
this._onError(null, 'cannot send on a closed WebSocket', undefined);
return;
}
try {
this.socket.send(JSON.stringify(event));
}
catch (err) {
this._onError(null, 'could not send data', err);
}
}
sendRaw(data) {
if (!this.socket) {
throw new error_1.OpenAIError('Internal error: failed to initialize socket. Please report this issue.');
}
if (this._isReconnecting || this.socket.readyState === ws_adapter_1.ReadyState.CONNECTING) {
if (!this._sendQueue.enqueueRaw(data)) {
this._onError(null, 'send queue is full, message discarded', undefined);
}
return;
}
if (this.socket.readyState !== ws_adapter_1.ReadyState.OPEN) {
this._onError(null, 'cannot send on a closed WebSocket', undefined);
return;
}
try {
this.socket.send((0, ws_1.flattenRawData)(data));
}
catch (err) {
this._onError(null, 'could not send data', err);
}
}
close(props) {
if (!this.socket) {
throw new error_1.OpenAIError('Internal error: failed to initialize socket. Please report this issue.');
}
this._intentionallyClosed = true;
this._closeCode = props?.code ?? 1000;
this._closeReason = props?.reason ?? 'OK';
try {
this.socket.close(this._closeCode, this._closeReason);
}
catch (err) {
this._onError(null, 'could not close the connection', err);
}
}
/**
* Returns an async iterator over WebSocket lifecycle and message events,
* providing an alternative to the event-based `.on()` API.
* The iterator will exit if the socket closes but exiting the iterator
* does not close the socket.
*
* @example
* ```ts
* for await (const event of client.stream()) {
* switch (event.type) {
* case 'message':
* console.log('received:', event.message);
* break;
* case 'error':
* console.error(event.error);
* break;
* case 'close':
* console.log('connection closed');
* break;
* }
* }
* ```
*/
stream() {
return this[Symbol.asyncIterator]();
}
[Symbol.asyncIterator]() {
if (!this.socket) {
throw new error_1.OpenAIError('Internal error: failed to initialize socket. Please report this issue.');
}
// Two-queue async iterator: `queue` buffers incoming messages,
// `resolvers` buffers waiting next() calls. A push wakes the
// oldest next(); a next() drains the oldest message.
const queue = [];
const resolvers = [];
let done = false;
let currentSocket = this.socket;
const push = (msg) => {
queue.push(msg);
resolvers.shift()?.();
};
const onEvent = (event) => {
if (event.type === 'error')
return; // handled by onEmitterError
push({ type: 'message', message: event });
};
const onRaw = (data) => {
push({ type: 'raw', data });
};
// All errors (API + socket) funnel through _onError → 'error' event
const onEmitterError = (err) => {
push({ type: 'error', error: err });
};
const onOpen = () => {
push({ type: 'open' });
};
const onReconnecting = (evt) => {
push({ type: 'reconnecting', reconnect: evt });
};
const onReconnected = () => {
push({ type: 'reconnected' });
};
const flushResolvers = () => {
for (let resolver = resolvers.shift(); resolver; resolver = resolvers.shift()) {
resolver();
}
};
const onClose = (code, reason, unsent) => {
push({ type: 'close', code, reason, unsent });
done = true;
flushResolvers();
cleanup();
};
const onSocketSwap = (oldSocket, newSocket) => {
oldSocket.off('open', onOpen);
newSocket.on('open', onOpen);
currentSocket = newSocket;
};
const cleanup = () => {
this.off('event', onEvent);
this.off('raw', onRaw);
this.off('error', onEmitterError);
currentSocket.off('open', onOpen);
this._internalEvents.off('close', onClose);
this._internalEvents.off('socketSwap', onSocketSwap);
this._internalEvents.off('reconnecting', onReconnecting);
this._internalEvents.off('reconnected', onReconnected);
};
this.on('event', onEvent);
this.on('raw', onRaw);
this.on('error', onEmitterError);
this.socket.on('open', onOpen);
this._internalEvents.on('close', onClose);
this._internalEvents.on('socketSwap', onSocketSwap);
this._internalEvents.on('reconnecting', onReconnecting);
this._internalEvents.on('reconnected', onReconnected);
if (this._isReconnecting) {
// A reconnect is already in flight. The socket may be CLOSED but the
// instance is still alive. Emit 'reconnecting' so the iterator stays
// open and receives the upcoming reconnected/message events.
push({
type: 'reconnecting',
reconnect: { attempt: 0, maxAttempts: 0, delay: 0, closeCode: 0, parameters: undefined },
});
}
else {
switch (this.socket.readyState) {
case ws_adapter_1.ReadyState.CONNECTING:
push({ type: 'connecting' });
break;
case ws_adapter_1.ReadyState.OPEN:
push({ type: 'open' });
break;
case ws_adapter_1.ReadyState.CLOSING:
push({ type: 'closing' });
break;
case ws_adapter_1.ReadyState.CLOSED:
push({
type: 'close',
code: this._lastCloseCode,
reason: this._lastCloseReason,
unsent: this._sendQueue.drain(),
});
done = true;
cleanup();
break;
}
}
const resolve = (res) => {
if (queue.length > 0) {
res({ value: queue.shift(), done: false });
}
else if (done) {
res({ value: undefined, done: true });
}
else {
return false;
}
return true;
};
const next = () => new Promise((res) => {
if (resolve(res))
return;
resolvers.push(() => {
resolve(res);
});
});
return {
next,
return: () => {
done = true;
cleanup();
flushResolvers();
return Promise.resolve({ value: undefined, done: true });
},
[Symbol.asyncIterator]() {
return this;
},
};
}
_connect() {
this.url = (0, internal_base_1.buildURL)(this._client, this._parameters ?? {});
const socket = this._createSocket(this.url, this._authHeaders());
socket.on('message', (data, isBinary) => {
if (isBinary) {
this._emit('raw', data);
return;
}
// Coerce to string in case the adapter delivers a typed-array for text frames.
const text = typeof data === 'string' ? data : String(data);
let event;
try {
event = JSON.parse(text);
}
catch {
this._emit('raw', data);
return;
}
this._emit('event', event);
if (event.type === 'error') {
this._onError(event);
}
else {
// @ts-ignore TS isn't smart enough to get the relationship right here
this._emit(event.type, event);
}
});
socket.on('error', (err) => {
// Suppress transient errors during reconnection — the retry loop
// already handles them and will surface a close if retries exhaust.
if (this._isReconnecting)
return;
this._onError(null, err.message, err);
});
socket.on('open', () => {
this._flushSendQueue();
});
socket.on('close', (code, reason) => {
// Ignore close events from superseded sockets — a stale socket's
// late close must not kick off a second reconnect loop.
if (socket !== this.socket)
return;
if (!this._intentionallyClosed && this._canReconnect(code)) {
this._reconnect(code);
}
else if (!this._isReconnecting) {
this._emitPermanentClose(code, reason);
}
});
return socket;
}
// Reconnect is opt-in via onReconnecting so callers can pass
// state (e.g. session IDs) into the new connection.
_canReconnect(code) {
if (this._intentionallyClosed)
return false;
if (!this._reconnectOptions)
return false;
if (this._reconnectOptions.maxRetries === 0)
return false;
if (!this._reconnectOptions.onReconnecting)
return false;
return (0, ws_1.isRecoverableClose)(code);
}
async _reconnect(closeCode) {
if (!this.socket) {
throw new error_1.OpenAIError('Internal error: failed to initialize socket. Please report this issue.');
}
if (this._isReconnecting || !this._reconnectOptions)
return;
this._isReconnecting = true;
const maxRetries = this._reconnectOptions.maxRetries ?? 5;
const initialDelay = this._reconnectOptions.initialDelay ?? 500;
const maxDelay = this._reconnectOptions.maxDelay ?? 8000;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
if (!this._canReconnect(closeCode)) {
this._isReconnecting = false;
if (!this._intentionallyClosed) {
this._onError(null, `WebSocket reconnect aborted: non-recoverable close code ${closeCode}`, undefined);
}
this._emitPermanentClose(this._intentionallyClosed ? this._closeCode : closeCode, this._intentionallyClosed ? this._closeReason : 'reconnect aborted');
return;
}
const baseDelay = Math.min(initialDelay * Math.pow(2, attempt - 1), maxDelay);
// Jitter: rand [0.75, 1.0] to spread out connection attempts without over-delaying
const jitter = 0.75 + Math.random() * 0.25;
const actualDelay = Math.round(baseDelay * jitter);
let reconnectingEvent = {
attempt,
maxAttempts: maxRetries,
delay: actualDelay,
closeCode,
parameters: this._parameters ? { ...this._parameters } : undefined,
};
let overrides;
try {
overrides = this._reconnectOptions.onReconnecting(reconnectingEvent);
}
catch (err) {
this._isReconnecting = false;
this._onError(null, 'onReconnecting callback threw', err);
this._emitPermanentClose(closeCode, 'onReconnecting callback threw');
return;
}
if (overrides && 'abort' in overrides && overrides.abort) {
this._isReconnecting = false;
this._emitPermanentClose(closeCode, 'reconnect aborted by handler');
return;
}
if (overrides && 'parameters' in overrides) {
this._parameters = overrides.parameters;
reconnectingEvent = { ...reconnectingEvent, parameters: this._parameters };
}
try {
this._emit('reconnecting', reconnectingEvent);
}
catch (err) {
this._onError(null, 'onReconnecting callback threw', err);
}
this._internalEvents._emit('reconnecting', reconnectingEvent);
if (!this._canReconnect(closeCode)) {
this._isReconnecting = false;
if (!this._intentionallyClosed) {
this._onError(null, `WebSocket reconnect aborted: non-recoverable close code ${closeCode}`, undefined);
}
this._emitPermanentClose(this._intentionallyClosed ? this._closeCode : closeCode, this._intentionallyClosed ? this._closeReason : 'reconnect aborted');
return;
}
await (0, sleep_1.sleep)(actualDelay);
if (!this._canReconnect(closeCode)) {
this._isReconnecting = false;
if (!this._intentionallyClosed) {
this._onError(null, `WebSocket reconnect aborted: non-recoverable close code ${closeCode}`, undefined);
}
this._emitPermanentClose(this._intentionallyClosed ? this._closeCode : closeCode, this._intentionallyClosed ? this._closeReason : 'reconnect aborted');
return;
}
let closeCodePromise;
try {
const oldSocket = this.socket;
this.socket = this._connect();
// Registered synchronously after _connect() and before any
// await so the code is captured even when ws emits 'close'
// in the same tick as 'error' (e.g. abortHandshake).
closeCodePromise = new Promise((resolve) => {
this.socket.once('close', resolve);
});
await this._awaitOpen(this.socket);
this._internalEvents._emit('socketSwap', oldSocket, this.socket);
this._isReconnecting = false;
this._flushSendQueue();
this._emit('reconnected');
this._internalEvents._emit('reconnected');
return;
}
catch {
if (closeCodePromise) {
// ws may emit 'error' before 'close', so await the code
// rather than reading it synchronously.
closeCode = await closeCodePromise;
}
}
}
// All retries exhausted — surface an error so consumers can
// distinguish retry failure from a clean close.
this._isReconnecting = false;
this._onError(null, `WebSocket reconnect failed after ${maxRetries} attempts (close code: ${closeCode})`, undefined);
this._emitPermanentClose(closeCode, `reconnect failed after ${maxRetries} attempts`);
}
/**
* Resolves once the socket is open, rejects if it errors or closes first
*/
_awaitOpen(socket) {
return new Promise((resolve, reject) => {
const cleanup = () => {
socket.off('open', onOpen);
socket.off('error', onError);
socket.off('close', onFail);
};
const onOpen = () => {
cleanup();
resolve();
};
const onError = (err) => {
cleanup();
reject(err);
};
const onFail = () => {
cleanup();
reject(new Error('socket closed before open'));
};
socket.once('open', onOpen);
socket.once('error', onError);
socket.once('close', onFail);
});
}
_flushSendQueue() {
if (!this.socket) {
throw new error_1.OpenAIError('Internal error: failed to initialize socket. Please report this issue.');
}
try {
this._sendQueue.flush((data) => this.socket.send((0, ws_1.flattenRawData)(data)));
}
catch (err) {
this._onError(null, 'could not send queued data', err);
}
}
/**
* Emits the public `close` event with unsent messages and the internal
* `close` event used by the async iterator.
*/
_emitPermanentClose(code, reason) {
this._lastCloseCode = code;
this._lastCloseReason = reason;
const unsent = this._sendQueue.drain();
// Internal close fires first so the async iterator is guaranteed to
// terminate even if a public 'close' listener throws.
this._internalEvents._emit('close', code, reason, unsent);
this._emit('close', code, reason, unsent);
}
_authHeaders() {
if (this._client.apiKey) {
return { Authorization: `Bearer ${this._client.apiKey}` };
}
return {};
}
}
exports.ResponsesWSBase = ResponsesWSBase;
//# sourceMappingURL=ws-base.js.map
File diff suppressed because one or more lines are too long
+472
View File
@@ -0,0 +1,472 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { ResponsesEmitter, buildURL } from "./internal-base.mjs";
import { InternalEventEmitter } from "../../core/EventEmitter.mjs";
import { sleep } from "../../internal/utils/sleep.mjs";
import { ReadyState } from "../../internal/ws-adapter.mjs";
import { SendQueue, flattenRawData, isRecoverableClose, } from "../../internal/ws.mjs";
import { OpenAIError } from "../../core/error.mjs";
export class ResponsesWSBase extends ResponsesEmitter {
constructor(client, options) {
super();
this._isReconnecting = false;
this._intentionallyClosed = false;
this._closeCode = 1000;
this._closeReason = 'OK';
this._lastCloseCode = 1006;
this._lastCloseReason = '';
// Necessary to keep the public event interface clean while we manage reconnecting
this._internalEvents = new InternalEventEmitter();
this._client = client;
this._parameters = undefined;
this._reconnectOptions = options?.reconnect ?? null;
this._sendQueue = new SendQueue(options?.maxQueueSize);
}
/** Establishes the initial WebSocket connection. */
_connectInitial() {
this.url = buildURL(this._client, {});
this.socket = this._connect();
}
send(event) {
if (!this.socket) {
throw new OpenAIError('Internal error: failed to initialize socket. Please report this issue.');
}
if (this._isReconnecting || this.socket.readyState === ReadyState.CONNECTING) {
if (!this._sendQueue.enqueue(event)) {
this._onError(null, 'send queue is full, message discarded', undefined);
}
return;
}
if (this.socket.readyState !== ReadyState.OPEN) {
this._onError(null, 'cannot send on a closed WebSocket', undefined);
return;
}
try {
this.socket.send(JSON.stringify(event));
}
catch (err) {
this._onError(null, 'could not send data', err);
}
}
sendRaw(data) {
if (!this.socket) {
throw new OpenAIError('Internal error: failed to initialize socket. Please report this issue.');
}
if (this._isReconnecting || this.socket.readyState === ReadyState.CONNECTING) {
if (!this._sendQueue.enqueueRaw(data)) {
this._onError(null, 'send queue is full, message discarded', undefined);
}
return;
}
if (this.socket.readyState !== ReadyState.OPEN) {
this._onError(null, 'cannot send on a closed WebSocket', undefined);
return;
}
try {
this.socket.send(flattenRawData(data));
}
catch (err) {
this._onError(null, 'could not send data', err);
}
}
close(props) {
if (!this.socket) {
throw new OpenAIError('Internal error: failed to initialize socket. Please report this issue.');
}
this._intentionallyClosed = true;
this._closeCode = props?.code ?? 1000;
this._closeReason = props?.reason ?? 'OK';
try {
this.socket.close(this._closeCode, this._closeReason);
}
catch (err) {
this._onError(null, 'could not close the connection', err);
}
}
/**
* Returns an async iterator over WebSocket lifecycle and message events,
* providing an alternative to the event-based `.on()` API.
* The iterator will exit if the socket closes but exiting the iterator
* does not close the socket.
*
* @example
* ```ts
* for await (const event of client.stream()) {
* switch (event.type) {
* case 'message':
* console.log('received:', event.message);
* break;
* case 'error':
* console.error(event.error);
* break;
* case 'close':
* console.log('connection closed');
* break;
* }
* }
* ```
*/
stream() {
return this[Symbol.asyncIterator]();
}
[Symbol.asyncIterator]() {
if (!this.socket) {
throw new OpenAIError('Internal error: failed to initialize socket. Please report this issue.');
}
// Two-queue async iterator: `queue` buffers incoming messages,
// `resolvers` buffers waiting next() calls. A push wakes the
// oldest next(); a next() drains the oldest message.
const queue = [];
const resolvers = [];
let done = false;
let currentSocket = this.socket;
const push = (msg) => {
queue.push(msg);
resolvers.shift()?.();
};
const onEvent = (event) => {
if (event.type === 'error')
return; // handled by onEmitterError
push({ type: 'message', message: event });
};
const onRaw = (data) => {
push({ type: 'raw', data });
};
// All errors (API + socket) funnel through _onError → 'error' event
const onEmitterError = (err) => {
push({ type: 'error', error: err });
};
const onOpen = () => {
push({ type: 'open' });
};
const onReconnecting = (evt) => {
push({ type: 'reconnecting', reconnect: evt });
};
const onReconnected = () => {
push({ type: 'reconnected' });
};
const flushResolvers = () => {
for (let resolver = resolvers.shift(); resolver; resolver = resolvers.shift()) {
resolver();
}
};
const onClose = (code, reason, unsent) => {
push({ type: 'close', code, reason, unsent });
done = true;
flushResolvers();
cleanup();
};
const onSocketSwap = (oldSocket, newSocket) => {
oldSocket.off('open', onOpen);
newSocket.on('open', onOpen);
currentSocket = newSocket;
};
const cleanup = () => {
this.off('event', onEvent);
this.off('raw', onRaw);
this.off('error', onEmitterError);
currentSocket.off('open', onOpen);
this._internalEvents.off('close', onClose);
this._internalEvents.off('socketSwap', onSocketSwap);
this._internalEvents.off('reconnecting', onReconnecting);
this._internalEvents.off('reconnected', onReconnected);
};
this.on('event', onEvent);
this.on('raw', onRaw);
this.on('error', onEmitterError);
this.socket.on('open', onOpen);
this._internalEvents.on('close', onClose);
this._internalEvents.on('socketSwap', onSocketSwap);
this._internalEvents.on('reconnecting', onReconnecting);
this._internalEvents.on('reconnected', onReconnected);
if (this._isReconnecting) {
// A reconnect is already in flight. The socket may be CLOSED but the
// instance is still alive. Emit 'reconnecting' so the iterator stays
// open and receives the upcoming reconnected/message events.
push({
type: 'reconnecting',
reconnect: { attempt: 0, maxAttempts: 0, delay: 0, closeCode: 0, parameters: undefined },
});
}
else {
switch (this.socket.readyState) {
case ReadyState.CONNECTING:
push({ type: 'connecting' });
break;
case ReadyState.OPEN:
push({ type: 'open' });
break;
case ReadyState.CLOSING:
push({ type: 'closing' });
break;
case ReadyState.CLOSED:
push({
type: 'close',
code: this._lastCloseCode,
reason: this._lastCloseReason,
unsent: this._sendQueue.drain(),
});
done = true;
cleanup();
break;
}
}
const resolve = (res) => {
if (queue.length > 0) {
res({ value: queue.shift(), done: false });
}
else if (done) {
res({ value: undefined, done: true });
}
else {
return false;
}
return true;
};
const next = () => new Promise((res) => {
if (resolve(res))
return;
resolvers.push(() => {
resolve(res);
});
});
return {
next,
return: () => {
done = true;
cleanup();
flushResolvers();
return Promise.resolve({ value: undefined, done: true });
},
[Symbol.asyncIterator]() {
return this;
},
};
}
_connect() {
this.url = buildURL(this._client, this._parameters ?? {});
const socket = this._createSocket(this.url, this._authHeaders());
socket.on('message', (data, isBinary) => {
if (isBinary) {
this._emit('raw', data);
return;
}
// Coerce to string in case the adapter delivers a typed-array for text frames.
const text = typeof data === 'string' ? data : String(data);
let event;
try {
event = JSON.parse(text);
}
catch {
this._emit('raw', data);
return;
}
this._emit('event', event);
if (event.type === 'error') {
this._onError(event);
}
else {
// @ts-ignore TS isn't smart enough to get the relationship right here
this._emit(event.type, event);
}
});
socket.on('error', (err) => {
// Suppress transient errors during reconnection — the retry loop
// already handles them and will surface a close if retries exhaust.
if (this._isReconnecting)
return;
this._onError(null, err.message, err);
});
socket.on('open', () => {
this._flushSendQueue();
});
socket.on('close', (code, reason) => {
// Ignore close events from superseded sockets — a stale socket's
// late close must not kick off a second reconnect loop.
if (socket !== this.socket)
return;
if (!this._intentionallyClosed && this._canReconnect(code)) {
this._reconnect(code);
}
else if (!this._isReconnecting) {
this._emitPermanentClose(code, reason);
}
});
return socket;
}
// Reconnect is opt-in via onReconnecting so callers can pass
// state (e.g. session IDs) into the new connection.
_canReconnect(code) {
if (this._intentionallyClosed)
return false;
if (!this._reconnectOptions)
return false;
if (this._reconnectOptions.maxRetries === 0)
return false;
if (!this._reconnectOptions.onReconnecting)
return false;
return isRecoverableClose(code);
}
async _reconnect(closeCode) {
if (!this.socket) {
throw new OpenAIError('Internal error: failed to initialize socket. Please report this issue.');
}
if (this._isReconnecting || !this._reconnectOptions)
return;
this._isReconnecting = true;
const maxRetries = this._reconnectOptions.maxRetries ?? 5;
const initialDelay = this._reconnectOptions.initialDelay ?? 500;
const maxDelay = this._reconnectOptions.maxDelay ?? 8000;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
if (!this._canReconnect(closeCode)) {
this._isReconnecting = false;
if (!this._intentionallyClosed) {
this._onError(null, `WebSocket reconnect aborted: non-recoverable close code ${closeCode}`, undefined);
}
this._emitPermanentClose(this._intentionallyClosed ? this._closeCode : closeCode, this._intentionallyClosed ? this._closeReason : 'reconnect aborted');
return;
}
const baseDelay = Math.min(initialDelay * Math.pow(2, attempt - 1), maxDelay);
// Jitter: rand [0.75, 1.0] to spread out connection attempts without over-delaying
const jitter = 0.75 + Math.random() * 0.25;
const actualDelay = Math.round(baseDelay * jitter);
let reconnectingEvent = {
attempt,
maxAttempts: maxRetries,
delay: actualDelay,
closeCode,
parameters: this._parameters ? { ...this._parameters } : undefined,
};
let overrides;
try {
overrides = this._reconnectOptions.onReconnecting(reconnectingEvent);
}
catch (err) {
this._isReconnecting = false;
this._onError(null, 'onReconnecting callback threw', err);
this._emitPermanentClose(closeCode, 'onReconnecting callback threw');
return;
}
if (overrides && 'abort' in overrides && overrides.abort) {
this._isReconnecting = false;
this._emitPermanentClose(closeCode, 'reconnect aborted by handler');
return;
}
if (overrides && 'parameters' in overrides) {
this._parameters = overrides.parameters;
reconnectingEvent = { ...reconnectingEvent, parameters: this._parameters };
}
try {
this._emit('reconnecting', reconnectingEvent);
}
catch (err) {
this._onError(null, 'onReconnecting callback threw', err);
}
this._internalEvents._emit('reconnecting', reconnectingEvent);
if (!this._canReconnect(closeCode)) {
this._isReconnecting = false;
if (!this._intentionallyClosed) {
this._onError(null, `WebSocket reconnect aborted: non-recoverable close code ${closeCode}`, undefined);
}
this._emitPermanentClose(this._intentionallyClosed ? this._closeCode : closeCode, this._intentionallyClosed ? this._closeReason : 'reconnect aborted');
return;
}
await sleep(actualDelay);
if (!this._canReconnect(closeCode)) {
this._isReconnecting = false;
if (!this._intentionallyClosed) {
this._onError(null, `WebSocket reconnect aborted: non-recoverable close code ${closeCode}`, undefined);
}
this._emitPermanentClose(this._intentionallyClosed ? this._closeCode : closeCode, this._intentionallyClosed ? this._closeReason : 'reconnect aborted');
return;
}
let closeCodePromise;
try {
const oldSocket = this.socket;
this.socket = this._connect();
// Registered synchronously after _connect() and before any
// await so the code is captured even when ws emits 'close'
// in the same tick as 'error' (e.g. abortHandshake).
closeCodePromise = new Promise((resolve) => {
this.socket.once('close', resolve);
});
await this._awaitOpen(this.socket);
this._internalEvents._emit('socketSwap', oldSocket, this.socket);
this._isReconnecting = false;
this._flushSendQueue();
this._emit('reconnected');
this._internalEvents._emit('reconnected');
return;
}
catch {
if (closeCodePromise) {
// ws may emit 'error' before 'close', so await the code
// rather than reading it synchronously.
closeCode = await closeCodePromise;
}
}
}
// All retries exhausted — surface an error so consumers can
// distinguish retry failure from a clean close.
this._isReconnecting = false;
this._onError(null, `WebSocket reconnect failed after ${maxRetries} attempts (close code: ${closeCode})`, undefined);
this._emitPermanentClose(closeCode, `reconnect failed after ${maxRetries} attempts`);
}
/**
* Resolves once the socket is open, rejects if it errors or closes first
*/
_awaitOpen(socket) {
return new Promise((resolve, reject) => {
const cleanup = () => {
socket.off('open', onOpen);
socket.off('error', onError);
socket.off('close', onFail);
};
const onOpen = () => {
cleanup();
resolve();
};
const onError = (err) => {
cleanup();
reject(err);
};
const onFail = () => {
cleanup();
reject(new Error('socket closed before open'));
};
socket.once('open', onOpen);
socket.once('error', onError);
socket.once('close', onFail);
});
}
_flushSendQueue() {
if (!this.socket) {
throw new OpenAIError('Internal error: failed to initialize socket. Please report this issue.');
}
try {
this._sendQueue.flush((data) => this.socket.send(flattenRawData(data)));
}
catch (err) {
this._onError(null, 'could not send queued data', err);
}
}
/**
* Emits the public `close` event with unsent messages and the internal
* `close` event used by the async iterator.
*/
_emitPermanentClose(code, reason) {
this._lastCloseCode = code;
this._lastCloseReason = reason;
const unsent = this._sendQueue.drain();
// Internal close fires first so the async iterator is guaranteed to
// terminate even if a public 'close' listener throws.
this._internalEvents._emit('close', code, reason, unsent);
this._emit('close', code, reason, unsent);
}
_authHeaders() {
if (this._client.apiKey) {
return { Authorization: `Bearer ${this._client.apiKey}` };
}
return {};
}
}
//# sourceMappingURL=ws-base.mjs.map
File diff suppressed because one or more lines are too long
+13
View File
@@ -0,0 +1,13 @@
import * as WS from 'ws';
import { NodeWebSocket } from "../../internal/ws-adapter-node.mjs";
import { ResponsesWSBase, type ResponsesWSBaseOptions } from "./ws-base.mjs";
import { OpenAI } from "../../client.mjs";
export type { ResponsesWSReconnectOptions } from "./ws-base.mjs";
export interface ResponsesWSClientOptions extends WS.ClientOptions, ResponsesWSBaseOptions {
}
export declare class ResponsesWS extends ResponsesWSBase<NodeWebSocket> {
private _wsOptions;
constructor(client: OpenAI, options?: ResponsesWSClientOptions | null | undefined);
protected _createSocket(url: URL, authHeaders: Record<string, string>): NodeWebSocket;
}
//# sourceMappingURL=ws.d.mts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"ws.d.mts","sourceRoot":"","sources":["../../src/resources/responses/ws.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,2CAAuC;AAC/D,OAAO,EAAE,eAAe,EAAE,KAAK,sBAAsB,EAAE,sBAAkB;AACzE,OAAO,EAAE,MAAM,EAAE,yBAAqB;AAEtC,YAAY,EAAE,2BAA2B,EAAE,sBAAkB;AAE7D,MAAM,WAAW,wBAAyB,SAAQ,EAAE,CAAC,aAAa,EAAE,sBAAsB;CAAG;AAE7F,qBAAa,WAAY,SAAQ,eAAe,CAAC,aAAa,CAAC;IAC7D,OAAO,CAAC,UAAU,CAAsC;gBAE5C,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,wBAAwB,GAAG,IAAI,GAAG,SAAS;IAajF,SAAS,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,aAAa;CAUtF"}
+13
View File
@@ -0,0 +1,13 @@
import * as WS from 'ws';
import { NodeWebSocket } from "../../internal/ws-adapter-node.js";
import { ResponsesWSBase, type ResponsesWSBaseOptions } from "./ws-base.js";
import { OpenAI } from "../../client.js";
export type { ResponsesWSReconnectOptions } from "./ws-base.js";
export interface ResponsesWSClientOptions extends WS.ClientOptions, ResponsesWSBaseOptions {
}
export declare class ResponsesWS extends ResponsesWSBase<NodeWebSocket> {
private _wsOptions;
constructor(client: OpenAI, options?: ResponsesWSClientOptions | null | undefined);
protected _createSocket(url: URL, authHeaders: Record<string, string>): NodeWebSocket;
}
//# sourceMappingURL=ws.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"ws.d.ts","sourceRoot":"","sources":["../../src/resources/responses/ws.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,0CAAuC;AAC/D,OAAO,EAAE,eAAe,EAAE,KAAK,sBAAsB,EAAE,qBAAkB;AACzE,OAAO,EAAE,MAAM,EAAE,wBAAqB;AAEtC,YAAY,EAAE,2BAA2B,EAAE,qBAAkB;AAE7D,MAAM,WAAW,wBAAyB,SAAQ,EAAE,CAAC,aAAa,EAAE,sBAAsB;CAAG;AAE7F,qBAAa,WAAY,SAAQ,eAAe,CAAC,aAAa,CAAC;IAC7D,OAAO,CAAC,UAAU,CAAsC;gBAE5C,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,wBAAwB,GAAG,IAAI,GAAG,SAAS;IAajF,SAAS,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,aAAa;CAUtF"}
+31
View File
@@ -0,0 +1,31 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResponsesWS = void 0;
const tslib_1 = require("../../internal/tslib.js");
const WS = tslib_1.__importStar(require("ws"));
const ws_adapter_node_1 = require("../../internal/ws-adapter-node.js");
const ws_base_1 = require("./ws-base.js");
class ResponsesWS extends ws_base_1.ResponsesWSBase {
constructor(client, options) {
if (!WS?.WebSocket) {
throw new Error('ResponsesWS from "openai/resources/responses/ws" requires the "ws" package but it could not be loaded.');
}
const { reconnect, maxQueueSize, ...wsOptions } = options ?? {};
super(client, { reconnect, maxQueueSize });
this._wsOptions = wsOptions;
this._connectInitial();
}
_createSocket(url, authHeaders) {
const ws = new WS.WebSocket(url, {
...this._wsOptions,
headers: {
...authHeaders,
...this._wsOptions?.headers,
},
});
return new ws_adapter_node_1.NodeWebSocket(ws);
}
}
exports.ResponsesWS = ResponsesWS;
//# sourceMappingURL=ws.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"ws.js","sourceRoot":"","sources":["../../src/resources/responses/ws.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;AAEtF,+CAAyB;AACzB,uEAA+D;AAC/D,0CAAyE;AAOzE,MAAa,WAAY,SAAQ,yBAA8B;IAG7D,YAAY,MAAc,EAAE,OAAqD;QAC/E,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CACb,wGAAwG,CACzG,CAAC;QACJ,CAAC;QAED,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,GAAG,SAAS,EAAE,GAAG,OAAO,IAAI,EAAE,CAAC;QAChE,KAAK,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,YAAY,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,CAAC,eAAe,EAAE,CAAC;IACzB,CAAC;IAES,aAAa,CAAC,GAAQ,EAAE,WAAmC;QACnE,MAAM,EAAE,GAAG,IAAI,EAAE,CAAC,SAAS,CAAC,GAAG,EAAE;YAC/B,GAAG,IAAI,CAAC,UAAU;YAClB,OAAO,EAAE;gBACP,GAAG,WAAW;gBACd,GAAG,IAAI,CAAC,UAAU,EAAE,OAAO;aAC5B;SACF,CAAC,CAAC;QACH,OAAO,IAAI,+BAAa,CAAC,EAAE,CAAC,CAAC;IAC/B,CAAC;CACF;AA1BD,kCA0BC"}
+26
View File
@@ -0,0 +1,26 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import * as WS from 'ws';
import { NodeWebSocket } from "../../internal/ws-adapter-node.mjs";
import { ResponsesWSBase } from "./ws-base.mjs";
export class ResponsesWS extends ResponsesWSBase {
constructor(client, options) {
if (!WS?.WebSocket) {
throw new Error('ResponsesWS from "openai/resources/responses/ws" requires the "ws" package but it could not be loaded.');
}
const { reconnect, maxQueueSize, ...wsOptions } = options ?? {};
super(client, { reconnect, maxQueueSize });
this._wsOptions = wsOptions;
this._connectInitial();
}
_createSocket(url, authHeaders) {
const ws = new WS.WebSocket(url, {
...this._wsOptions,
headers: {
...authHeaders,
...this._wsOptions?.headers,
},
});
return new NodeWebSocket(ws);
}
}
//# sourceMappingURL=ws.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"ws.mjs","sourceRoot":"","sources":["../../src/resources/responses/ws.ts"],"names":[],"mappings":"AAAA,sFAAsF;AAEtF,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,2CAAuC;AAC/D,OAAO,EAAE,eAAe,EAA+B,sBAAkB;AAOzE,MAAM,OAAO,WAAY,SAAQ,eAA8B;IAG7D,YAAY,MAAc,EAAE,OAAqD;QAC/E,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CACb,wGAAwG,CACzG,CAAC;QACJ,CAAC;QAED,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,GAAG,SAAS,EAAE,GAAG,OAAO,IAAI,EAAE,CAAC;QAChE,KAAK,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,YAAY,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,IAAI,CAAC,eAAe,EAAE,CAAC;IACzB,CAAC;IAES,aAAa,CAAC,GAAQ,EAAE,WAAmC;QACnE,MAAM,EAAE,GAAG,IAAI,EAAE,CAAC,SAAS,CAAC,GAAG,EAAE;YAC/B,GAAG,IAAI,CAAC,UAAU;YAClB,OAAO,EAAE;gBACP,GAAG,WAAW;gBACd,GAAG,IAAI,CAAC,UAAU,EAAE,OAAO;aAC5B;SACF,CAAC,CAAC;QACH,OAAO,IAAI,aAAa,CAAC,EAAE,CAAC,CAAC;IAC/B,CAAC;CACF"}