phonic 0.31.9 → 0.31.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/BaseClient.js +2 -2
  3. package/dist/cjs/Client.d.ts +9 -1
  4. package/dist/cjs/Client.js +1 -1
  5. package/dist/cjs/api/resources/conversations/client/Client.d.ts +8 -1
  6. package/dist/cjs/api/resources/conversations/client/Client.js +37 -3
  7. package/dist/cjs/api/resources/conversations/client/Socket.d.ts +2 -1
  8. package/dist/cjs/api/resources/conversations/client/Socket.js +4 -0
  9. package/dist/cjs/api/types/ConfigOptions.d.ts +94 -0
  10. package/dist/cjs/api/types/ConfigOptions.js +32 -0
  11. package/dist/cjs/api/types/ConfigPayload.d.ts +2 -90
  12. package/dist/cjs/api/types/ConfigPayload.js +0 -29
  13. package/dist/cjs/api/types/ResetPayload.d.ts +5 -0
  14. package/dist/cjs/api/types/ResetPayload.js +3 -0
  15. package/dist/cjs/api/types/index.d.ts +2 -0
  16. package/dist/cjs/api/types/index.js +2 -0
  17. package/dist/cjs/custom/ReconnectableConversationsSocket.d.ts +74 -0
  18. package/dist/cjs/custom/ReconnectableConversationsSocket.js +283 -0
  19. package/dist/cjs/custom/index.d.ts +1 -0
  20. package/dist/cjs/custom/index.js +5 -0
  21. package/dist/cjs/index.d.ts +1 -0
  22. package/dist/cjs/index.js +3 -1
  23. package/dist/cjs/version.d.ts +1 -1
  24. package/dist/cjs/version.js +1 -1
  25. package/dist/esm/BaseClient.mjs +2 -2
  26. package/dist/esm/Client.d.mts +9 -1
  27. package/dist/esm/Client.mjs +1 -1
  28. package/dist/esm/api/resources/conversations/client/Client.d.mts +8 -1
  29. package/dist/esm/api/resources/conversations/client/Client.mjs +37 -3
  30. package/dist/esm/api/resources/conversations/client/Socket.d.mts +2 -1
  31. package/dist/esm/api/resources/conversations/client/Socket.mjs +4 -0
  32. package/dist/esm/api/types/ConfigOptions.d.mts +94 -0
  33. package/dist/esm/api/types/ConfigOptions.mjs +29 -0
  34. package/dist/esm/api/types/ConfigPayload.d.mts +2 -90
  35. package/dist/esm/api/types/ConfigPayload.mjs +1 -28
  36. package/dist/esm/api/types/ResetPayload.d.mts +5 -0
  37. package/dist/esm/api/types/ResetPayload.mjs +2 -0
  38. package/dist/esm/api/types/index.d.mts +2 -0
  39. package/dist/esm/api/types/index.mjs +2 -0
  40. package/dist/esm/custom/ReconnectableConversationsSocket.d.mts +74 -0
  41. package/dist/esm/custom/ReconnectableConversationsSocket.mjs +246 -0
  42. package/dist/esm/custom/index.d.mts +1 -0
  43. package/dist/esm/custom/index.mjs +1 -0
  44. package/dist/esm/index.d.mts +1 -0
  45. package/dist/esm/index.mjs +1 -0
  46. package/dist/esm/version.d.mts +1 -1
  47. package/dist/esm/version.mjs +1 -1
  48. package/package.json +2 -1
@@ -1,92 +1,4 @@
1
- export interface ConfigPayload {
1
+ import type * as Phonic from "../index.mjs";
2
+ export interface ConfigPayload extends Phonic.ConfigOptions {
2
3
  type: "config";
3
- /** Agent name to use for conversation */
4
- agent?: string | undefined;
5
- /** Project name */
6
- project?: string | undefined;
7
- /** STS model to use */
8
- model?: "merritt" | undefined;
9
- /** System prompt for AI assistant */
10
- system_prompt?: string | undefined;
11
- /** Audio playback speed */
12
- audio_speed?: number | undefined;
13
- /** Background noise level for the conversation */
14
- background_noise_level?: number | undefined;
15
- /** Background noise type for the conversation */
16
- background_noise?: (ConfigPayload.BackgroundNoise | null) | undefined;
17
- /** When `true`, the welcome message will be automatically generated and the `welcome_message` field will be ignored. */
18
- generate_welcome_message?: boolean | undefined;
19
- /** Message to play when conversation starts. Ignored when `generate_welcome_message` is `true`. */
20
- welcome_message?: (string | null) | undefined;
21
- /** Voice ID to use for speech synthesis */
22
- voice_id?: string | undefined;
23
- /** Audio input format */
24
- input_format?: ConfigPayload.InputFormat | undefined;
25
- /** Audio output format */
26
- output_format?: ConfigPayload.OutputFormat | undefined;
27
- /** Voice activity detection prebuffer duration */
28
- vad_prebuffer_duration_ms?: number | undefined;
29
- /** Minimum speech duration for VAD */
30
- vad_min_speech_duration_ms?: number | undefined;
31
- /** Minimum silence duration for VAD */
32
- vad_min_silence_duration_ms?: number | undefined;
33
- /** Voice activity detection threshold */
34
- vad_threshold?: number | undefined;
35
- /** Minimum number of words required to interrupt the assistant. */
36
- min_words_to_interrupt?: number | undefined;
37
- /** Whether to have the no-input poke text be generated by AI */
38
- generate_no_input_poke_text?: boolean | undefined;
39
- /** Seconds of silence before poke message */
40
- no_input_poke_sec?: (number | null) | undefined;
41
- /** Poke message text. Ignored when generate_no_input_poke_text is true. */
42
- no_input_poke_text?: string | undefined;
43
- /** Seconds of silence before ending conversation */
44
- no_input_end_conversation_sec?: number | undefined;
45
- /** ISO 639-1 language code that sets the agent's default language to recognize and speak. Welcome message and no input poke text should be in this language. */
46
- default_language?: string | undefined;
47
- /** Array of additional ISO 639-1 language codes that the agent should be able to recognize and speak. Should not include `default_language`. */
48
- additional_languages?: string[] | undefined;
49
- /** If `"auto"`, each user audio is automatically identified for the language to respond in. If `"request"`, user must request to change language (recommended). */
50
- multilingual_mode?: ConfigPayload.MultilingualMode | undefined;
51
- /** Keywords to boost in speech recognition */
52
- boosted_keywords?: string[] | undefined;
53
- /** Names of tools available to the assistant. */
54
- tools?: ConfigPayload.Tools.Item[] | undefined;
55
- /** Template variables for system prompt and welcome message */
56
- template_variables?: Record<string, string> | undefined;
57
- }
58
- export declare namespace ConfigPayload {
59
- /** Background noise type for the conversation */
60
- const BackgroundNoise: {
61
- readonly Office: "office";
62
- readonly CallCenter: "call-center";
63
- readonly CoffeeShop: "coffee-shop";
64
- };
65
- type BackgroundNoise = (typeof BackgroundNoise)[keyof typeof BackgroundNoise];
66
- /** Audio input format */
67
- const InputFormat: {
68
- readonly Pcm44100: "pcm_44100";
69
- readonly Pcm16000: "pcm_16000";
70
- readonly Pcm8000: "pcm_8000";
71
- readonly Mulaw8000: "mulaw_8000";
72
- };
73
- type InputFormat = (typeof InputFormat)[keyof typeof InputFormat];
74
- /** Audio output format */
75
- const OutputFormat: {
76
- readonly Pcm44100: "pcm_44100";
77
- readonly Pcm16000: "pcm_16000";
78
- readonly Pcm8000: "pcm_8000";
79
- readonly Mulaw8000: "mulaw_8000";
80
- };
81
- type OutputFormat = (typeof OutputFormat)[keyof typeof OutputFormat];
82
- /** If `"auto"`, each user audio is automatically identified for the language to respond in. If `"request"`, user must request to change language (recommended). */
83
- const MultilingualMode: {
84
- readonly Auto: "auto";
85
- readonly Request: "request";
86
- };
87
- type MultilingualMode = (typeof MultilingualMode)[keyof typeof MultilingualMode];
88
- type Tools = Tools.Item[];
89
- namespace Tools {
90
- type Item = string | Record<string, unknown>;
91
- }
92
4
  }
@@ -1,29 +1,2 @@
1
1
  // This file was auto-generated by Fern from our API Definition.
2
- export var ConfigPayload;
3
- (function (ConfigPayload) {
4
- /** Background noise type for the conversation */
5
- ConfigPayload.BackgroundNoise = {
6
- Office: "office",
7
- CallCenter: "call-center",
8
- CoffeeShop: "coffee-shop",
9
- };
10
- /** Audio input format */
11
- ConfigPayload.InputFormat = {
12
- Pcm44100: "pcm_44100",
13
- Pcm16000: "pcm_16000",
14
- Pcm8000: "pcm_8000",
15
- Mulaw8000: "mulaw_8000",
16
- };
17
- /** Audio output format */
18
- ConfigPayload.OutputFormat = {
19
- Pcm44100: "pcm_44100",
20
- Pcm16000: "pcm_16000",
21
- Pcm8000: "pcm_8000",
22
- Mulaw8000: "mulaw_8000",
23
- };
24
- /** If `"auto"`, each user audio is automatically identified for the language to respond in. If `"request"`, user must request to change language (recommended). */
25
- ConfigPayload.MultilingualMode = {
26
- Auto: "auto",
27
- Request: "request",
28
- };
29
- })(ConfigPayload || (ConfigPayload = {}));
2
+ export {};
@@ -0,0 +1,5 @@
1
+ import type * as Phonic from "../index.mjs";
2
+ export interface ResetPayload {
3
+ type: "reset";
4
+ config: Phonic.ConfigOptions;
5
+ }
@@ -0,0 +1,2 @@
1
+ // This file was auto-generated by Fern from our API Definition.
2
+ export {};
@@ -8,6 +8,7 @@ export * from "./AudioChunkPayload.mjs";
8
8
  export * from "./AudioChunkResponsePayload.mjs";
9
9
  export * from "./BadRequestErrorBody.mjs";
10
10
  export * from "./BasicError.mjs";
11
+ export * from "./ConfigOptions.mjs";
11
12
  export * from "./ConfigPayload.mjs";
12
13
  export * from "./Conversation.mjs";
13
14
  export * from "./ConversationAnalysis.mjs";
@@ -33,6 +34,7 @@ export * from "./OutboundCallInitiatedResponse.mjs";
33
34
  export * from "./OutboundDryRunResponse.mjs";
34
35
  export * from "./Project.mjs";
35
36
  export * from "./ReadyToStartConversationPayload.mjs";
37
+ export * from "./ResetPayload.mjs";
36
38
  export * from "./SayPayload.mjs";
37
39
  export * from "./SetExternalIdPayload.mjs";
38
40
  export * from "./SipOutboundCallInitiatedResponse.mjs";
@@ -8,6 +8,7 @@ export * from "./AudioChunkPayload.mjs";
8
8
  export * from "./AudioChunkResponsePayload.mjs";
9
9
  export * from "./BadRequestErrorBody.mjs";
10
10
  export * from "./BasicError.mjs";
11
+ export * from "./ConfigOptions.mjs";
11
12
  export * from "./ConfigPayload.mjs";
12
13
  export * from "./Conversation.mjs";
13
14
  export * from "./ConversationAnalysis.mjs";
@@ -33,6 +34,7 @@ export * from "./OutboundCallInitiatedResponse.mjs";
33
34
  export * from "./OutboundDryRunResponse.mjs";
34
35
  export * from "./Project.mjs";
35
36
  export * from "./ReadyToStartConversationPayload.mjs";
37
+ export * from "./ResetPayload.mjs";
36
38
  export * from "./SayPayload.mjs";
37
39
  export * from "./SetExternalIdPayload.mjs";
38
40
  export * from "./SipOutboundCallInitiatedResponse.mjs";
@@ -0,0 +1,74 @@
1
+ import * as core from "../core/index.mjs";
2
+ import type * as Phonic from "../api/index.mjs";
3
+ import { ConversationsSocket } from "../api/resources/conversations/client/Socket.mjs";
4
+ export interface ReconnectableConversationsSocketArgs {
5
+ /** Called on 1006 to create a new socket with reconnect_conv_id. May be async (e.g. fresh auth). */
6
+ createReconnectSocket: (conversationId: string) => core.ReconnectingWebSocket | Promise<core.ReconnectingWebSocket>;
7
+ /** Initial socket for the first connection. */
8
+ socket: core.ReconnectingWebSocket;
9
+ /** If provided, reconnection stops when the signal is aborted. */
10
+ abortSignal?: AbortSignal;
11
+ }
12
+ type EventHandlers = {
13
+ open?: () => void;
14
+ message?: (message: ConversationsSocket.Response) => void;
15
+ close?: (event: core.CloseEvent) => void;
16
+ error?: (error: Error) => void;
17
+ };
18
+ /**
19
+ * Wraps ConversationsSocket with automatic reconnection on 1006.
20
+ *
21
+ * On abnormal closure, creates a brand new ReconnectingWebSocket (via the
22
+ * createReconnectSocket factory) and wraps it in a fresh ConversationsSocket,
23
+ * forwarding all events to user-registered handlers.
24
+ *
25
+ * Retries reconnection with exponential backoff until the server responds
26
+ * with a terminal close code (4800 session expired, 4801 invalid state),
27
+ * the safety cap is reached, or the user calls close().
28
+ *
29
+ * Uses composition rather than inheritance to avoid coupling to the parent's
30
+ * private event handler registration or ReconnectingWebSocket internals.
31
+ */
32
+ export declare class ReconnectableConversationsSocket {
33
+ private _conversationId;
34
+ private _inner;
35
+ private readonly _createReconnectSocket;
36
+ private readonly _handlers;
37
+ private _reconnectAttempts;
38
+ private _isClosed;
39
+ private readonly _abortSignal;
40
+ private _cleanupWireListeners;
41
+ private _pendingReconnect;
42
+ private _pendingReplacement;
43
+ constructor(args: ReconnectableConversationsSocketArgs);
44
+ /** The conversation ID captured from the server's conversation_created message. */
45
+ get conversationId(): string | null;
46
+ get socket(): core.ReconnectingWebSocket;
47
+ get readyState(): number;
48
+ on<T extends keyof EventHandlers>(event: T, callback: EventHandlers[T]): void;
49
+ /** Drop outbound sends when we cannot talk to a live socket (no queue). */
50
+ private _safeSend;
51
+ sendConfig(message: Phonic.ConfigPayload): void;
52
+ sendAudioChunk(message: Phonic.AudioChunkPayload): void;
53
+ sendToolCallOutput(message: Phonic.ToolCallOutputPayload): void;
54
+ sendUpdateSystemPrompt(message: Phonic.UpdateSystemPromptPayload): void;
55
+ sendAddSystemMessage(message: Phonic.AddSystemMessagePayload): void;
56
+ sendSetExternalId(message: Phonic.SetExternalIdPayload): void;
57
+ sendGenerateReply(message: Phonic.GenerateReplyPayload): void;
58
+ sendSay(message: Phonic.SayPayload): void;
59
+ sendReset(message: Phonic.ResetPayload): void;
60
+ /**
61
+ * Not supported — reconnection after 1006 is handled automatically.
62
+ * To start a new conversation, create a new socket via client.conversations.connect().
63
+ */
64
+ connect(): never;
65
+ close(): void;
66
+ waitForOpen(): Promise<core.ReconnectingWebSocket>;
67
+ private _getReconnectDelay;
68
+ /** Schedule a reconnection attempt after backoff delay. */
69
+ private _scheduleReconnect;
70
+ /** Perform the actual reconnection attempt. */
71
+ private _doReconnect;
72
+ private _wireInner;
73
+ }
74
+ export {};
@@ -0,0 +1,246 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import * as core from "../core/index.mjs";
11
+ import { ConversationsSocket } from "../api/resources/conversations/client/Socket.mjs";
12
+ import { fromJson } from "../core/json.mjs";
13
+ /** 1006 is the only close code that indicates an unexpected disconnect
14
+ * worth reconnecting for. All other codes (1000, 4000, 4800, etc.)
15
+ * are intentional server-side closes. */
16
+ const ABNORMAL_CLOSURE = 1006;
17
+ const BASE_RECONNECT_DELAY_MS = 500;
18
+ const MAX_RECONNECT_DELAY_MS = 5000;
19
+ /** Safety cap: stop retrying if the server is completely unreachable.
20
+ * In normal operation the server's terminal codes (4800/4801) stop
21
+ * retries much sooner (within the 10s grace period). */
22
+ const MAX_RECONNECT_ATTEMPTS = 10;
23
+ /**
24
+ * Wraps ConversationsSocket with automatic reconnection on 1006.
25
+ *
26
+ * On abnormal closure, creates a brand new ReconnectingWebSocket (via the
27
+ * createReconnectSocket factory) and wraps it in a fresh ConversationsSocket,
28
+ * forwarding all events to user-registered handlers.
29
+ *
30
+ * Retries reconnection with exponential backoff until the server responds
31
+ * with a terminal close code (4800 session expired, 4801 invalid state),
32
+ * the safety cap is reached, or the user calls close().
33
+ *
34
+ * Uses composition rather than inheritance to avoid coupling to the parent's
35
+ * private event handler registration or ReconnectingWebSocket internals.
36
+ */
37
+ export class ReconnectableConversationsSocket {
38
+ constructor(args) {
39
+ this._conversationId = null;
40
+ this._handlers = {};
41
+ this._reconnectAttempts = 0;
42
+ this._isClosed = false;
43
+ this._cleanupWireListeners = null;
44
+ this._pendingReconnect = null;
45
+ this._pendingReplacement = false;
46
+ this._createReconnectSocket = args.createReconnectSocket;
47
+ this._abortSignal = args.abortSignal != undefined ? args.abortSignal : null;
48
+ this._inner = new ConversationsSocket({ socket: args.socket });
49
+ this._wireInner(this._inner, args.socket);
50
+ }
51
+ /** The conversation ID captured from the server's conversation_created message. */
52
+ get conversationId() {
53
+ return this._conversationId;
54
+ }
55
+ get socket() {
56
+ return this._inner.socket;
57
+ }
58
+ get readyState() {
59
+ return this._inner.readyState;
60
+ }
61
+ on(event, callback) {
62
+ this._handlers[event] = callback;
63
+ }
64
+ /** Drop outbound sends when we cannot talk to a live socket (no queue). */
65
+ _safeSend(op) {
66
+ if (this._isClosed || this._pendingReplacement) {
67
+ return;
68
+ }
69
+ if (this._inner.readyState !== core.ReconnectingWebSocket.ReadyState.OPEN) {
70
+ return;
71
+ }
72
+ op(this._inner);
73
+ }
74
+ sendConfig(message) {
75
+ this._safeSend((inner) => inner.sendConfig(message));
76
+ }
77
+ sendAudioChunk(message) {
78
+ this._safeSend((inner) => inner.sendAudioChunk(message));
79
+ }
80
+ sendToolCallOutput(message) {
81
+ this._safeSend((inner) => inner.sendToolCallOutput(message));
82
+ }
83
+ sendUpdateSystemPrompt(message) {
84
+ this._safeSend((inner) => inner.sendUpdateSystemPrompt(message));
85
+ }
86
+ sendAddSystemMessage(message) {
87
+ this._safeSend((inner) => inner.sendAddSystemMessage(message));
88
+ }
89
+ sendSetExternalId(message) {
90
+ this._safeSend((inner) => inner.sendSetExternalId(message));
91
+ }
92
+ sendGenerateReply(message) {
93
+ this._safeSend((inner) => inner.sendGenerateReply(message));
94
+ }
95
+ sendSay(message) {
96
+ this._safeSend((inner) => inner.sendSay(message));
97
+ }
98
+ sendReset(message) {
99
+ this._safeSend((inner) => inner.sendReset(message));
100
+ }
101
+ /**
102
+ * Not supported — reconnection after 1006 is handled automatically.
103
+ * To start a new conversation, create a new socket via client.conversations.connect().
104
+ */
105
+ connect() {
106
+ throw new Error("connect() is not supported on ReconnectableConversationsSocket. "
107
+ + "Reconnection after 1006 is automatic. To start a new conversation, "
108
+ + "call client.conversations.connect() again.");
109
+ }
110
+ close() {
111
+ var _a;
112
+ this._isClosed = true;
113
+ this._pendingReplacement = false;
114
+ if (this._pendingReconnect != null) {
115
+ clearTimeout(this._pendingReconnect);
116
+ this._pendingReconnect = null;
117
+ }
118
+ (_a = this._cleanupWireListeners) === null || _a === void 0 ? void 0 : _a.call(this);
119
+ this._cleanupWireListeners = null;
120
+ this._inner.close();
121
+ }
122
+ waitForOpen() {
123
+ return __awaiter(this, void 0, void 0, function* () {
124
+ return this._inner.waitForOpen();
125
+ });
126
+ }
127
+ _getReconnectDelay() {
128
+ // Exponential backoff: 500ms, 1s, 2s, 4s, capped at 5s
129
+ const delay = BASE_RECONNECT_DELAY_MS * Math.pow(2, this._reconnectAttempts - 1);
130
+ return Math.min(delay, MAX_RECONNECT_DELAY_MS);
131
+ }
132
+ /** Schedule a reconnection attempt after backoff delay. */
133
+ _scheduleReconnect() {
134
+ var _a, _b, _c;
135
+ if (this._isClosed || this._conversationId === null || ((_a = this._abortSignal) === null || _a === void 0 ? void 0 : _a.aborted)) {
136
+ return;
137
+ }
138
+ if (this._reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
139
+ this._pendingReplacement = false;
140
+ (_c = (_b = this._handlers).error) === null || _c === void 0 ? void 0 : _c.call(_b, new Error("Max reconnect attempts reached"));
141
+ return;
142
+ }
143
+ // Clear any existing timer to prevent orphaned timeouts
144
+ if (this._pendingReconnect != null) {
145
+ clearTimeout(this._pendingReconnect);
146
+ }
147
+ this._reconnectAttempts++;
148
+ const delay = this._getReconnectDelay();
149
+ this._pendingReplacement = true;
150
+ this._pendingReconnect = setTimeout(() => {
151
+ this._pendingReconnect = null;
152
+ if (this._isClosed) {
153
+ this._pendingReplacement = false;
154
+ return;
155
+ }
156
+ void this._doReconnect();
157
+ }, delay);
158
+ }
159
+ /** Perform the actual reconnection attempt. */
160
+ _doReconnect() {
161
+ return __awaiter(this, void 0, void 0, function* () {
162
+ var _a, _b;
163
+ try {
164
+ const created = this._createReconnectSocket(this._conversationId);
165
+ const newRawSocket = created instanceof Promise ? yield created : created;
166
+ if (this._isClosed || ((_a = this._abortSignal) === null || _a === void 0 ? void 0 : _a.aborted)) {
167
+ this._pendingReplacement = false;
168
+ newRawSocket.close();
169
+ return;
170
+ }
171
+ // Clean up the old socket: remove our custom listeners and close
172
+ // the ConversationsSocket wrapper (which removes its own listeners).
173
+ (_b = this._cleanupWireListeners) === null || _b === void 0 ? void 0 : _b.call(this);
174
+ this._cleanupWireListeners = null;
175
+ try {
176
+ this._inner.close();
177
+ }
178
+ catch ( /* already closed from 1006 */_c) { /* already closed from 1006 */ }
179
+ const newInner = new ConversationsSocket({ socket: newRawSocket });
180
+ this._inner = newInner;
181
+ this._wireInner(newInner, newRawSocket);
182
+ }
183
+ catch (_d) {
184
+ this._pendingReplacement = false;
185
+ // Connection failed — schedule another attempt.
186
+ // The server's grace period (10s) is the natural limit;
187
+ // once it expires, the next attempt will get 4800 and stop.
188
+ this._scheduleReconnect();
189
+ }
190
+ });
191
+ }
192
+ _wireInner(inner, rawSocket) {
193
+ // Forward events from the inner ConversationsSocket to user handlers.
194
+ // Clear _pendingReplacement before calling the user's open handler
195
+ // so that sends inside the handler are not silently dropped.
196
+ inner.on("open", () => {
197
+ var _a, _b;
198
+ this._pendingReplacement = false;
199
+ (_b = (_a = this._handlers).open) === null || _b === void 0 ? void 0 : _b.call(_a);
200
+ });
201
+ inner.on("message", (msg) => { var _a, _b; return (_b = (_a = this._handlers).message) === null || _b === void 0 ? void 0 : _b.call(_a, msg); });
202
+ inner.on("close", (ev) => { var _a, _b; return (_b = (_a = this._handlers).close) === null || _b === void 0 ? void 0 : _b.call(_a, ev); });
203
+ inner.on("error", (err) => { var _a, _b; return (_b = (_a = this._handlers).error) === null || _b === void 0 ? void 0 : _b.call(_a, err); });
204
+ // Intercept raw messages to capture conversation_id and reset reconnect counter
205
+ const onMessage = (event) => {
206
+ try {
207
+ const data = fromJson(event.data);
208
+ if (data && typeof data === "object" && "type" in data) {
209
+ const type = data.type;
210
+ if (type === "conversation_created") {
211
+ this._conversationId = data.conversation_id;
212
+ }
213
+ if (type === "conversation_reconnected") {
214
+ this._reconnectAttempts = 0;
215
+ }
216
+ }
217
+ }
218
+ catch (_a) {
219
+ // ignore — inner socket handles parse errors
220
+ }
221
+ };
222
+ const onClose = (event) => {
223
+ if (this._isClosed) {
224
+ return;
225
+ }
226
+ if (event.code === ABNORMAL_CLOSURE && this._conversationId !== null) {
227
+ // We have a conversation to resume — cancel RWS's built-in
228
+ // auto-reconnect and handle it ourselves with reconnect_conv_id.
229
+ // _handleClose calls _connect() before notifying listeners,
230
+ // but _connect() awaits _wait() which is async. Calling
231
+ // close() synchronously sets _closeCalled = true, which
232
+ // _connect() checks before opening the new socket.
233
+ rawSocket.close();
234
+ this._scheduleReconnect();
235
+ }
236
+ // 1006 without conversationId: let RWS handle transport-level
237
+ // reconnect normally (starts a fresh conversation).
238
+ };
239
+ rawSocket.addEventListener("message", onMessage);
240
+ rawSocket.addEventListener("close", onClose);
241
+ this._cleanupWireListeners = () => {
242
+ rawSocket.removeEventListener("message", onMessage);
243
+ rawSocket.removeEventListener("close", onClose);
244
+ };
245
+ }
246
+ }
@@ -0,0 +1 @@
1
+ export { ReconnectableConversationsSocket } from "./ReconnectableConversationsSocket.mjs";
@@ -0,0 +1 @@
1
+ export { ReconnectableConversationsSocket } from "./ReconnectableConversationsSocket.mjs";
@@ -4,3 +4,4 @@ export { PhonicClient } from "./Client.mjs";
4
4
  export { PhonicEnvironment, type PhonicEnvironmentUrls } from "./environments.mjs";
5
5
  export { PhonicError, PhonicTimeoutError } from "./errors/index.mjs";
6
6
  export * from "./exports.mjs";
7
+ export { ReconnectableConversationsSocket } from "./custom/index.mjs";
@@ -3,3 +3,4 @@ export { PhonicClient } from "./Client.mjs";
3
3
  export { PhonicEnvironment } from "./environments.mjs";
4
4
  export { PhonicError, PhonicTimeoutError } from "./errors/index.mjs";
5
5
  export * from "./exports.mjs";
6
+ export { ReconnectableConversationsSocket } from "./custom/index.mjs";
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "0.31.9";
1
+ export declare const SDK_VERSION = "0.31.11";
@@ -1 +1 @@
1
- export const SDK_VERSION = "0.31.9";
1
+ export const SDK_VERSION = "0.31.11";
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "phonic",
3
- "version": "0.31.9",
3
+ "version": "0.31.11",
4
4
  "private": false,
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/Phonic-Co/phonic-node.git"
8
8
  },
9
+ "license": "MIT",
9
10
  "type": "commonjs",
10
11
  "main": "./dist/cjs/index.js",
11
12
  "module": "./dist/esm/index.mjs",