@archboard/codex-realtime-voice 0.0.0-stage → 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +621 -2
- package/dist/app-server-contract-D4E5bibD.mjs +177 -0
- package/dist/browser.d.mts +10 -0
- package/dist/browser.mjs +475 -0
- package/dist/contract-CZDUvuVt.d.mts +19587 -0
- package/dist/contract-Cupd2jDS.d.mts +131 -0
- package/dist/contract-DTEwX7x-.d.mts +164 -0
- package/dist/contract-qg6q9-vH.d.mts +6905 -0
- package/dist/contract.d.mts +2 -0
- package/dist/contract.mjs +1 -0
- package/dist/controllers.d.mts +588 -0
- package/dist/controllers.mjs +4754 -0
- package/dist/gateway-envelope-CODkg5rz.mjs +43 -0
- package/dist/gateway-envelope-Ch4BsYcK.d.mts +36 -0
- package/dist/instructions-CmBJHqpa.mjs +8980 -0
- package/dist/media-state-CakgDCk4.d.mts +215 -0
- package/dist/model-YHUwnXnC.mjs +2808 -0
- package/dist/react.d.mts +34 -0
- package/dist/react.mjs +49 -0
- package/dist/realtime-contract-DwkCluo2.mjs +1167 -0
- package/dist/realtime-contract-wHmSyUIe.d.mts +150 -0
- package/dist/realtime-state-CTBmCjt1.mjs +182 -0
- package/dist/realtime-state-DT4uvrIV.d.mts +16 -0
- package/dist/realtime.d.mts +3 -0
- package/dist/realtime.mjs +3 -0
- package/dist/runtime.d.mts +93 -0
- package/dist/runtime.mjs +289 -0
- package/dist/schemas.d.mts +7075 -0
- package/dist/schemas.mjs +1 -0
- package/dist/server.d.mts +1374 -0
- package/dist/server.mjs +38224 -0
- package/dist/snapshot-BCrCORmt.d.mts +8597 -0
- package/dist/transport-CqOvXrAE.mjs +5168 -0
- package/package.json +71 -5
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
// ../codex-app-server/src/shared/protocol/app-server-contract.ts
|
|
3
|
+
/** JSON representation of one generated ts-rs bigint/i64 field. */
|
|
4
|
+
const CodexSafeI64Schema = z.number().int().safe().brand();
|
|
5
|
+
/** Client requests this client implements, checked against the generated request union. */
|
|
6
|
+
const CODEX_CLIENT_REQUEST_METHODS = [
|
|
7
|
+
"initialize",
|
|
8
|
+
"config/read",
|
|
9
|
+
"configRequirements/read",
|
|
10
|
+
"account/read",
|
|
11
|
+
"account/login/start",
|
|
12
|
+
"account/login/cancel",
|
|
13
|
+
"account/logout",
|
|
14
|
+
"model/list",
|
|
15
|
+
"thread/start",
|
|
16
|
+
"thread/fork",
|
|
17
|
+
"thread/list",
|
|
18
|
+
"thread/loaded/list",
|
|
19
|
+
"thread/read",
|
|
20
|
+
"thread/turns/list",
|
|
21
|
+
"thread/items/list",
|
|
22
|
+
"thread/delete",
|
|
23
|
+
"thread/unsubscribe",
|
|
24
|
+
"thread/settings/update",
|
|
25
|
+
"turn/start",
|
|
26
|
+
"turn/steer",
|
|
27
|
+
"turn/interrupt",
|
|
28
|
+
"thread/queue/add",
|
|
29
|
+
"thread/queue/list",
|
|
30
|
+
"thread/queue/update",
|
|
31
|
+
"thread/queue/delete",
|
|
32
|
+
"thread/queue/reorder",
|
|
33
|
+
"thread/queue/start",
|
|
34
|
+
"thread/inject_items",
|
|
35
|
+
"thread/realtime/start",
|
|
36
|
+
"thread/realtime/appendText",
|
|
37
|
+
"thread/realtime/appendSpeech",
|
|
38
|
+
"thread/realtime/stop",
|
|
39
|
+
"thread/timeline/list"
|
|
40
|
+
];
|
|
41
|
+
const CodexThreadStatusSchema = z.discriminatedUnion("type", [
|
|
42
|
+
z.looseObject({ type: z.literal("notLoaded") }),
|
|
43
|
+
z.looseObject({ type: z.literal("idle") }),
|
|
44
|
+
z.looseObject({ type: z.literal("systemError") }),
|
|
45
|
+
z.looseObject({
|
|
46
|
+
type: z.literal("active"),
|
|
47
|
+
activeFlags: z.array(z.enum(["waitingOnApproval", "waitingOnUserInput"]))
|
|
48
|
+
})
|
|
49
|
+
]);
|
|
50
|
+
const CODEX_THREAD_STATUS_TYPES = [
|
|
51
|
+
"notLoaded",
|
|
52
|
+
"idle",
|
|
53
|
+
"systemError",
|
|
54
|
+
"active"
|
|
55
|
+
];
|
|
56
|
+
const CodexThreadStatusTypeSchema = z.enum(CODEX_THREAD_STATUS_TYPES);
|
|
57
|
+
const CodexTurnStatusSchema = z.enum([
|
|
58
|
+
"completed",
|
|
59
|
+
"interrupted",
|
|
60
|
+
"failed",
|
|
61
|
+
"inProgress"
|
|
62
|
+
]);
|
|
63
|
+
const CodexTurnPlanStepStatusSchema = z.enum({
|
|
64
|
+
pending: "pending",
|
|
65
|
+
inProgress: "inProgress",
|
|
66
|
+
completed: "completed"
|
|
67
|
+
});
|
|
68
|
+
const CodexPatchChangeKindTypeSchema = z.enum({
|
|
69
|
+
add: "add",
|
|
70
|
+
delete: "delete",
|
|
71
|
+
update: "update"
|
|
72
|
+
});
|
|
73
|
+
/** One token usage breakdown, closed to exactly the fields Codex reports. */
|
|
74
|
+
const CodexTokenUsageBreakdownSchema = z.strictObject({
|
|
75
|
+
totalTokens: z.number(),
|
|
76
|
+
inputTokens: z.number(),
|
|
77
|
+
cachedInputTokens: z.number(),
|
|
78
|
+
cacheWriteInputTokens: z.number(),
|
|
79
|
+
outputTokens: z.number(),
|
|
80
|
+
reasoningOutputTokens: z.number()
|
|
81
|
+
});
|
|
82
|
+
/**
|
|
83
|
+
* Builds the schema for a command-execution approval decision. It is a
|
|
84
|
+
* factory because a caller that already constrains strings (the browser
|
|
85
|
+
* model's bounded text) can plug its own text and host schemas into the
|
|
86
|
+
* amendment branches while keeping the vendor shape.
|
|
87
|
+
* @param options - Optional replacements for the plain string schemas.
|
|
88
|
+
* @param options.text - The schema for execpolicy amendment entries.
|
|
89
|
+
* @param options.host - The schema for the network amendment host; defaults to `text`.
|
|
90
|
+
* @returns A zod union accepting the four bare decisions and both amendment forms.
|
|
91
|
+
*/
|
|
92
|
+
function createCodexCommandExecutionApprovalDecisionSchema(options = {}) {
|
|
93
|
+
const text = options.text ?? z.string();
|
|
94
|
+
const host = options.host ?? text;
|
|
95
|
+
return z.union([
|
|
96
|
+
z.enum([
|
|
97
|
+
"accept",
|
|
98
|
+
"acceptForSession",
|
|
99
|
+
"decline",
|
|
100
|
+
"cancel"
|
|
101
|
+
]),
|
|
102
|
+
z.strictObject({ acceptWithExecpolicyAmendment: z.strictObject({ execpolicy_amendment: z.array(text) }) }),
|
|
103
|
+
z.strictObject({ applyNetworkPolicyAmendment: z.strictObject({ network_policy_amendment: z.strictObject({
|
|
104
|
+
host,
|
|
105
|
+
action: z.enum(["allow", "deny"])
|
|
106
|
+
}) }) })
|
|
107
|
+
]);
|
|
108
|
+
}
|
|
109
|
+
const CodexCommandExecutionApprovalDecisionSchema = createCodexCommandExecutionApprovalDecisionSchema();
|
|
110
|
+
const CodexFileChangeApprovalDecisionSchema = z.enum([
|
|
111
|
+
"accept",
|
|
112
|
+
"acceptForSession",
|
|
113
|
+
"decline",
|
|
114
|
+
"cancel"
|
|
115
|
+
]);
|
|
116
|
+
/**
|
|
117
|
+
* Normalizes a JSON scalar, refusing the values JSON cannot carry: non-finite
|
|
118
|
+
* numbers and bigints.
|
|
119
|
+
* @param value - A primitive that is not an object.
|
|
120
|
+
* @param path - Where the value sits in the payload, for the error message.
|
|
121
|
+
* @returns The scalar unchanged.
|
|
122
|
+
* @throws {TypeError} When the scalar is not representable in Codex JSON.
|
|
123
|
+
*/
|
|
124
|
+
function normalizeScalar(value, path) {
|
|
125
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
126
|
+
if (typeof value === "number") return normalizeNumber(value, path);
|
|
127
|
+
if (typeof value === "bigint") throw new TypeError(`${path} is bigint; Codex JSON i64 values must be safe numbers`);
|
|
128
|
+
throw new TypeError(`${path} is not a JSON value`);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Accepts only the numbers JSON can spell.
|
|
132
|
+
* @param value - A number.
|
|
133
|
+
* @param path - Where the number sits in the payload, for the error message.
|
|
134
|
+
* @returns The number unchanged.
|
|
135
|
+
* @throws {TypeError} When the number is NaN or infinite.
|
|
136
|
+
*/
|
|
137
|
+
function normalizeNumber(value, path) {
|
|
138
|
+
if (!Number.isFinite(value)) throw new TypeError(`${path} is not a finite JSON number`);
|
|
139
|
+
return value;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Normalizes a JSON object, accepting only plain objects so a class instance
|
|
143
|
+
* or a prototype-carrying value never reaches an ingress parser.
|
|
144
|
+
* @param value - A non-null, non-array object.
|
|
145
|
+
* @param path - Where the object sits in the payload, for the error message.
|
|
146
|
+
* @returns A fresh plain object with every entry normalized.
|
|
147
|
+
* @throws {TypeError} When the object has a prototype other than Object or null.
|
|
148
|
+
*/
|
|
149
|
+
function normalizeObject(value, path) {
|
|
150
|
+
const prototype = Object.getPrototypeOf(value);
|
|
151
|
+
if (prototype !== Object.prototype && prototype !== null) throw new TypeError(`${path} is not a plain JSON object`);
|
|
152
|
+
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, normalizeValue(entry, `${path}.${key}`)]));
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Recursively normalizes one untrusted value into the closed Codex JSON
|
|
156
|
+
* vocabulary, naming the offending path when something is not JSON.
|
|
157
|
+
* @param value - Any value decoded from the app-server stream.
|
|
158
|
+
* @param path - Where the value sits in the payload, for the error message.
|
|
159
|
+
* @returns The equivalent value built only from JSON scalars, arrays and plain objects.
|
|
160
|
+
* @throws {TypeError} When the value or anything inside it is not Codex JSON.
|
|
161
|
+
*/
|
|
162
|
+
function normalizeValue(value, path) {
|
|
163
|
+
if (Array.isArray(value)) return value.map((entry, index) => normalizeValue(entry, `${path}[${index}]`));
|
|
164
|
+
if (typeof value === "object" && value !== null) return normalizeObject(value, path);
|
|
165
|
+
return normalizeScalar(value, path);
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Normalizes untrusted app-server JSON before any handwritten ingress parser runs.
|
|
169
|
+
* @param value - The decoded payload, or undefined when a message carried none.
|
|
170
|
+
* @returns The normalized payload, or undefined when there was none.
|
|
171
|
+
* @throws {TypeError} When the payload is not Codex JSON.
|
|
172
|
+
*/
|
|
173
|
+
function normalizeCodexJsonWire(value) {
|
|
174
|
+
if (value === void 0) return;
|
|
175
|
+
return normalizeValue(value, "$codex");
|
|
176
|
+
}
|
|
177
|
+
export { CodexPatchChangeKindTypeSchema as a, CodexThreadStatusTypeSchema as c, CodexTurnStatusSchema as d, createCodexCommandExecutionApprovalDecisionSchema as f, CodexFileChangeApprovalDecisionSchema as i, CodexTokenUsageBreakdownSchema as l, CODEX_THREAD_STATUS_TYPES as n, CodexSafeI64Schema as o, normalizeCodexJsonWire as p, CodexCommandExecutionApprovalDecisionSchema as r, CodexThreadStatusSchema as s, CODEX_CLIENT_REQUEST_METHODS as t, CodexTurnPlanStepStatusSchema as u };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import "./media-state-CakgDCk4.mjs";
|
|
2
|
+
import "./contract-DTEwX7x-.mjs";
|
|
3
|
+
import { a as VoiceClientSnapshot, i as VoiceClientOptions, n as VoiceApprovalResponse, o as VoiceSignIn, r as VoiceClient, t as VoiceApproval } from "./contract-Cupd2jDS.mjs";
|
|
4
|
+
/**
|
|
5
|
+
* Connect one page view to the voice server through the real browser.
|
|
6
|
+
* @param options The socket path and the chat.
|
|
7
|
+
* @returns The client. Call `connect()` to open the socket.
|
|
8
|
+
*/
|
|
9
|
+
declare function createVoiceClient(options: VoiceClientOptions): VoiceClient;
|
|
10
|
+
export { type VoiceApproval, type VoiceApprovalResponse, type VoiceClient, type VoiceClientSnapshot, type VoiceSignIn, createVoiceClient };
|
package/dist/browser.mjs
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
import { c as CODEX_REALTIME_MS } from "./model-YHUwnXnC.mjs";
|
|
2
|
+
import { t as INITIAL_REALTIME_STATE } from "./realtime-state-CTBmCjt1.mjs";
|
|
3
|
+
import { n as BrowserWorkbenchTransportError, r as createBrowserWorkbenchMediaOwner, t as createBrowserWorkbenchTransport } from "./transport-CqOvXrAE.mjs";
|
|
4
|
+
// src/ui/voice-client/clients/voice-client.ts
|
|
5
|
+
const UNCERTAIN = "Delivery is uncertain. Refresh the conversation before trying another action.";
|
|
6
|
+
const TAB_SESSION_KEY = "codex-realtime-voice:tab";
|
|
7
|
+
/** The `readyState` of a socket whose close has begun; `CLOSED` is 3. */
|
|
8
|
+
const SOCKET_CLOSING = 2;
|
|
9
|
+
/**
|
|
10
|
+
* Connect one page view to the voice server through the real browser.
|
|
11
|
+
* @param options The socket path and the chat.
|
|
12
|
+
* @returns The client. Call `connect()` to open the socket.
|
|
13
|
+
*/
|
|
14
|
+
function createVoiceClient(options) {
|
|
15
|
+
return openVoiceClient(options, {
|
|
16
|
+
transport: createBrowserWorkbenchTransport(),
|
|
17
|
+
media: createBrowserWorkbenchMediaOwner(),
|
|
18
|
+
/**
|
|
19
|
+
* A browser WebSocket.
|
|
20
|
+
* @param url Where it connects.
|
|
21
|
+
* @returns The socket.
|
|
22
|
+
*/
|
|
23
|
+
openSocket: (url) => new WebSocket(url),
|
|
24
|
+
/**
|
|
25
|
+
* The id kept for this tab.
|
|
26
|
+
* @returns The id.
|
|
27
|
+
*/
|
|
28
|
+
tabSessionId: () => storedTabSessionId(TAB_SESSION_KEY),
|
|
29
|
+
/**
|
|
30
|
+
* The page's own location.
|
|
31
|
+
* @returns The URL.
|
|
32
|
+
*/
|
|
33
|
+
pageUrl: () => location.href,
|
|
34
|
+
/**
|
|
35
|
+
* A browser timer.
|
|
36
|
+
* @param delayMs How long to wait.
|
|
37
|
+
* @param run What runs then.
|
|
38
|
+
* @returns How to cancel it.
|
|
39
|
+
*/
|
|
40
|
+
after: (delayMs, run) => {
|
|
41
|
+
const timer = setTimeout(run, delayMs);
|
|
42
|
+
return () => clearTimeout(timer);
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The client over the owners it is given.
|
|
48
|
+
* @param options The socket path and the chat.
|
|
49
|
+
* @param owners The transport, the media owner, the socket factory and the tab identity.
|
|
50
|
+
* @returns The client.
|
|
51
|
+
*/
|
|
52
|
+
function openVoiceClient(options, owners) {
|
|
53
|
+
const { transport, media } = owners;
|
|
54
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
55
|
+
let socket = null;
|
|
56
|
+
let failure = null;
|
|
57
|
+
/** Whether `failure` came from a `connect` that did not open, which a later opening clears. */
|
|
58
|
+
let failedToConnect = false;
|
|
59
|
+
let pending = 0;
|
|
60
|
+
let disposed = false;
|
|
61
|
+
let cancelReconnect = null;
|
|
62
|
+
let current = read();
|
|
63
|
+
/**
|
|
64
|
+
* Project the owners into one frozen state.
|
|
65
|
+
* @returns The state.
|
|
66
|
+
*/
|
|
67
|
+
function read() {
|
|
68
|
+
const state = transport.state();
|
|
69
|
+
return Object.freeze({
|
|
70
|
+
connection: state.connection,
|
|
71
|
+
server: state.snapshot,
|
|
72
|
+
voice: voiceOf(media),
|
|
73
|
+
busy: pending > 0,
|
|
74
|
+
failure,
|
|
75
|
+
intent: transport.capabilities().canCommand ? transport.captureCommandIntent() : null
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
/** Publish a new state to every listener. */
|
|
79
|
+
const publish = () => {
|
|
80
|
+
if (disposed) return;
|
|
81
|
+
current = read();
|
|
82
|
+
for (const listener of listeners) listener();
|
|
83
|
+
};
|
|
84
|
+
const unsubscribeTransport = transport.subscribe(publish);
|
|
85
|
+
const unsubscribeMedia = media.subscribe(publish);
|
|
86
|
+
/**
|
|
87
|
+
* Run an operation as a running action, publishing `busy` around it.
|
|
88
|
+
* @param operation The operation.
|
|
89
|
+
* @param fail Takes what the operation threw.
|
|
90
|
+
* @returns Whether it completed.
|
|
91
|
+
*/
|
|
92
|
+
const busyWith = async (operation, fail) => {
|
|
93
|
+
pending++;
|
|
94
|
+
publish();
|
|
95
|
+
try {
|
|
96
|
+
await operation();
|
|
97
|
+
return true;
|
|
98
|
+
} catch (error) {
|
|
99
|
+
fail(error);
|
|
100
|
+
return false;
|
|
101
|
+
} finally {
|
|
102
|
+
pending--;
|
|
103
|
+
publish();
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* Run one action, keeping its failure visible.
|
|
108
|
+
* @param operation The action.
|
|
109
|
+
* @param interrupt Whether it may run during another action.
|
|
110
|
+
* @returns Whether it completed.
|
|
111
|
+
*/
|
|
112
|
+
const run = async (operation, interrupt = false) => {
|
|
113
|
+
if (pending > 0 && !interrupt || disposed) return false;
|
|
114
|
+
failure = null;
|
|
115
|
+
failedToConnect = false;
|
|
116
|
+
return busyWith(operation, (error) => {
|
|
117
|
+
failure = failureOf(error);
|
|
118
|
+
});
|
|
119
|
+
};
|
|
120
|
+
/**
|
|
121
|
+
* Deliver one human command once.
|
|
122
|
+
* @param draft The command.
|
|
123
|
+
*/
|
|
124
|
+
const command = async (draft) => {
|
|
125
|
+
delivered(await transport.executeCommand(draft));
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* The executable conversation, created when the link is still unbound.
|
|
129
|
+
* @returns The thread id.
|
|
130
|
+
*/
|
|
131
|
+
const ensureConversation = async () => {
|
|
132
|
+
if (transport.snapshot()?.threadLink.state === "unbound") await command({ command: "threadLinkCreate" });
|
|
133
|
+
const link = transport.snapshot()?.threadLink;
|
|
134
|
+
if (link?.state !== "executable") throw new Error("The conversation is not ready. Refresh its state before continuing.");
|
|
135
|
+
return link.threadId;
|
|
136
|
+
};
|
|
137
|
+
/** Release the socket and the owners attached to it. */
|
|
138
|
+
const release = async () => {
|
|
139
|
+
const previous = socket;
|
|
140
|
+
if (previous === null) return;
|
|
141
|
+
socket = null;
|
|
142
|
+
await media.detach(transport);
|
|
143
|
+
await transport.detach(previous);
|
|
144
|
+
previous.close();
|
|
145
|
+
};
|
|
146
|
+
/**
|
|
147
|
+
* Open a socket and attach the owners to it. A socket that closes before the
|
|
148
|
+
* server's first snapshot fails with the reason the server closed it with.
|
|
149
|
+
*/
|
|
150
|
+
const open = async () => {
|
|
151
|
+
const next = owners.openSocket(socketUrl(options, owners.pageUrl(), owners.tabSessionId()));
|
|
152
|
+
socket = next;
|
|
153
|
+
const closed = closeReasonOf(next);
|
|
154
|
+
await opened(next);
|
|
155
|
+
if (disposed) return;
|
|
156
|
+
const attached = await transport.attach(next);
|
|
157
|
+
if (attached.kind === "connection") {
|
|
158
|
+
const reason = next.readyState >= SOCKET_CLOSING ? await closed : "";
|
|
159
|
+
throw new Error(reason || attached.reason);
|
|
160
|
+
}
|
|
161
|
+
await media.attach(transport);
|
|
162
|
+
await transport.accountRead();
|
|
163
|
+
};
|
|
164
|
+
/**
|
|
165
|
+
* Release the socket, then open a new one and attach the owners to it. A
|
|
166
|
+
* dispose while it runs opens no socket, or closes the one it opened.
|
|
167
|
+
*/
|
|
168
|
+
const reopen = async () => {
|
|
169
|
+
await release();
|
|
170
|
+
if (!disposed) await open();
|
|
171
|
+
};
|
|
172
|
+
/**
|
|
173
|
+
* Open the socket again and attach the owners to it.
|
|
174
|
+
* @returns Whether it opened.
|
|
175
|
+
*/
|
|
176
|
+
const connect = async () => {
|
|
177
|
+
const completed = await run(reopen);
|
|
178
|
+
failedToConnect = !completed && failure !== null;
|
|
179
|
+
return completed && !disposed;
|
|
180
|
+
};
|
|
181
|
+
/**
|
|
182
|
+
* Connect again after a delay, unless the socket is connected by then, and
|
|
183
|
+
* try again after each attempt that does not open. One attempt waits at a time.
|
|
184
|
+
* @param delayMs How long to wait.
|
|
185
|
+
*/
|
|
186
|
+
const reconnectAfter = (delayMs) => {
|
|
187
|
+
if (disposed || cancelReconnect !== null) return;
|
|
188
|
+
cancelReconnect = owners.after(Math.max(0, delayMs), () => {
|
|
189
|
+
cancelReconnect = null;
|
|
190
|
+
if (disposed || transport.state().connection === "connected") return;
|
|
191
|
+
reconnect();
|
|
192
|
+
});
|
|
193
|
+
};
|
|
194
|
+
/**
|
|
195
|
+
* Whether the server spoke a contract this browser cannot read, which no
|
|
196
|
+
* attempt heals. The page then shows why, unless it shows another failure.
|
|
197
|
+
* @returns True when attempts must stop.
|
|
198
|
+
*/
|
|
199
|
+
const unreadableServer = () => {
|
|
200
|
+
const state = transport.state();
|
|
201
|
+
if (state.kind !== "connection" || state.state !== "incompatible_contract") return false;
|
|
202
|
+
failure ??= Object.freeze({
|
|
203
|
+
message: state.reason,
|
|
204
|
+
uncertain: false
|
|
205
|
+
});
|
|
206
|
+
publish();
|
|
207
|
+
return true;
|
|
208
|
+
};
|
|
209
|
+
/**
|
|
210
|
+
* Connect once while no action runs, and wait to try again when the socket
|
|
211
|
+
* does not open. The attempt keeps the failure the page shows, such as an
|
|
212
|
+
* uncertain delivery.
|
|
213
|
+
*/
|
|
214
|
+
const reconnect = async () => {
|
|
215
|
+
if (pending === 0 && !disposed && await busyWith(reopen, ignore)) {
|
|
216
|
+
if (failedToConnect) failure = null;
|
|
217
|
+
failedToConnect = false;
|
|
218
|
+
publish();
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (!unreadableServer()) reconnectAfter(CODEX_REALTIME_MS.clientReconnect);
|
|
222
|
+
};
|
|
223
|
+
const unsubscribeLoss = transport.subscribe(() => {
|
|
224
|
+
const state = transport.state();
|
|
225
|
+
if (state.kind === "connection" && state.state === "backoff") reconnectAfter(state.retryAtMs - Date.now());
|
|
226
|
+
});
|
|
227
|
+
/**
|
|
228
|
+
* Cancel the sign-in the server shows as pending.
|
|
229
|
+
* @returns Whether it completed.
|
|
230
|
+
*/
|
|
231
|
+
const cancelSignIn = () => run(async () => {
|
|
232
|
+
const login = transport.snapshot()?.login;
|
|
233
|
+
if (login?.state === "pending") await command({
|
|
234
|
+
command: "accountLoginCancel",
|
|
235
|
+
loginId: login.loginId
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
/**
|
|
239
|
+
* Interrupt the workhorse's running turn, if one runs.
|
|
240
|
+
* @returns Whether it completed.
|
|
241
|
+
*/
|
|
242
|
+
const stopWork = () => run(async () => {
|
|
243
|
+
const state = transport.snapshot();
|
|
244
|
+
const turn = state?.timeline?.turns.findLast((entry) => entry.status === "inProgress");
|
|
245
|
+
if (state?.threadLink.state !== "executable" || turn === void 0) return;
|
|
246
|
+
await command({
|
|
247
|
+
command: "interrupt",
|
|
248
|
+
threadId: state.threadLink.threadId,
|
|
249
|
+
turnId: turn.turnId
|
|
250
|
+
});
|
|
251
|
+
}, true);
|
|
252
|
+
/**
|
|
253
|
+
* Answer one approval against the intent that rendered it.
|
|
254
|
+
* @param approval The request.
|
|
255
|
+
* @param response The answer.
|
|
256
|
+
* @param intent The rendered state's intent.
|
|
257
|
+
* @returns Whether it was delivered.
|
|
258
|
+
*/
|
|
259
|
+
const answerApproval = (approval, response, intent) => run(async () => {
|
|
260
|
+
const draft = {
|
|
261
|
+
command: "approvalRespond",
|
|
262
|
+
requestId: approval.requestId,
|
|
263
|
+
approvalId: approval.approvalId,
|
|
264
|
+
response
|
|
265
|
+
};
|
|
266
|
+
delivered(await transport.executeCommand(draft, intent));
|
|
267
|
+
});
|
|
268
|
+
/**
|
|
269
|
+
* Hear every publication.
|
|
270
|
+
* @param listener The listener.
|
|
271
|
+
* @returns The unsubscribe.
|
|
272
|
+
*/
|
|
273
|
+
const subscribe = (listener) => {
|
|
274
|
+
listeners.add(listener);
|
|
275
|
+
return () => {
|
|
276
|
+
listeners.delete(listener);
|
|
277
|
+
};
|
|
278
|
+
};
|
|
279
|
+
/** Stop voice, release the socket and end every subscription. */
|
|
280
|
+
const dispose = async () => {
|
|
281
|
+
disposed = true;
|
|
282
|
+
cancelReconnect?.();
|
|
283
|
+
cancelReconnect = null;
|
|
284
|
+
unsubscribeLoss();
|
|
285
|
+
unsubscribeTransport();
|
|
286
|
+
unsubscribeMedia();
|
|
287
|
+
listeners.clear();
|
|
288
|
+
try {
|
|
289
|
+
await media.dispose();
|
|
290
|
+
} finally {
|
|
291
|
+
try {
|
|
292
|
+
await transport.dispose();
|
|
293
|
+
} finally {
|
|
294
|
+
socket?.close();
|
|
295
|
+
socket = null;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
return Object.freeze({
|
|
300
|
+
connect,
|
|
301
|
+
/**
|
|
302
|
+
* Read the server's state again.
|
|
303
|
+
* @returns Whether it completed.
|
|
304
|
+
*/
|
|
305
|
+
refresh: () => run(() => transport.refresh()),
|
|
306
|
+
/**
|
|
307
|
+
* Start a sign-in.
|
|
308
|
+
* @param login How the account signs in.
|
|
309
|
+
* @returns Whether it was delivered.
|
|
310
|
+
*/
|
|
311
|
+
signIn: (login = { type: "chatgpt" }) => run(() => command({
|
|
312
|
+
command: "accountLogin",
|
|
313
|
+
login
|
|
314
|
+
})),
|
|
315
|
+
cancelSignIn,
|
|
316
|
+
/**
|
|
317
|
+
* Sign the account out.
|
|
318
|
+
* @returns Whether it was delivered.
|
|
319
|
+
*/
|
|
320
|
+
signOut: () => run(() => command({ command: "accountLogout" })),
|
|
321
|
+
/**
|
|
322
|
+
* Send a message to the workhorse.
|
|
323
|
+
* @param message The message.
|
|
324
|
+
* @returns Whether it was delivered.
|
|
325
|
+
*/
|
|
326
|
+
send: (message) => run(async () => command({
|
|
327
|
+
command: "start",
|
|
328
|
+
threadId: await ensureConversation(),
|
|
329
|
+
prompt: message
|
|
330
|
+
})),
|
|
331
|
+
/**
|
|
332
|
+
* Start the coordinator's voice once the conversation exists.
|
|
333
|
+
* @returns Whether it started.
|
|
334
|
+
*/
|
|
335
|
+
startVoice: () => run(async () => {
|
|
336
|
+
await ensureConversation();
|
|
337
|
+
await media.start();
|
|
338
|
+
}),
|
|
339
|
+
/**
|
|
340
|
+
* Stop voice, even during another action.
|
|
341
|
+
* @returns Whether it stopped.
|
|
342
|
+
*/
|
|
343
|
+
stopVoice: () => run(() => media.stop(), true),
|
|
344
|
+
/**
|
|
345
|
+
* Silence or restore the microphone.
|
|
346
|
+
* @param muted Whether to silence it.
|
|
347
|
+
* @returns Whether it changed.
|
|
348
|
+
*/
|
|
349
|
+
setMuted: (muted) => run(() => muted ? media.mute() : media.unmute()),
|
|
350
|
+
stopWork,
|
|
351
|
+
answerApproval,
|
|
352
|
+
/**
|
|
353
|
+
* The current state.
|
|
354
|
+
* @returns The state.
|
|
355
|
+
*/
|
|
356
|
+
snapshot: () => current,
|
|
357
|
+
subscribe,
|
|
358
|
+
dispose
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
/** A reconnect attempt that fails leaves the page's failure as it is. */
|
|
362
|
+
function ignore() {}
|
|
363
|
+
/** The id this page names while storage cannot hold one; a reload then starts another. */
|
|
364
|
+
let pageTabSessionId = null;
|
|
365
|
+
/**
|
|
366
|
+
* The tab's session id, minted once and kept in `sessionStorage`. Storage that
|
|
367
|
+
* refuses, as a privacy setting can make it, leaves one id for this page.
|
|
368
|
+
* @param key The storage key.
|
|
369
|
+
* @returns The id.
|
|
370
|
+
*/
|
|
371
|
+
function storedTabSessionId(key) {
|
|
372
|
+
try {
|
|
373
|
+
const id = sessionStorage.getItem(key) ?? crypto.randomUUID();
|
|
374
|
+
sessionStorage.setItem(key, id);
|
|
375
|
+
return id;
|
|
376
|
+
} catch {
|
|
377
|
+
pageTabSessionId ??= crypto.randomUUID();
|
|
378
|
+
return pageTabSessionId;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* The socket URL with the chat and tab identity.
|
|
383
|
+
* @param options The socket path and the chat.
|
|
384
|
+
* @param pageUrl The page location the path resolves against.
|
|
385
|
+
* @param tabSessionId The tab's session id.
|
|
386
|
+
* @returns The URL.
|
|
387
|
+
*/
|
|
388
|
+
function socketUrl(options, pageUrl, tabSessionId) {
|
|
389
|
+
const url = new URL(options.socketPath, pageUrl);
|
|
390
|
+
if (url.protocol === "http:") url.protocol = "ws:";
|
|
391
|
+
if (url.protocol === "https:") url.protocol = "wss:";
|
|
392
|
+
url.searchParams.set("chatId", options.chatId ?? "main");
|
|
393
|
+
url.searchParams.set("tabSessionId", tabSessionId);
|
|
394
|
+
return url.href;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* The voice run as the page shows it.
|
|
398
|
+
* @param media The media owner.
|
|
399
|
+
* @returns The phase, whether a run can start, and the problem.
|
|
400
|
+
*/
|
|
401
|
+
function voiceOf(media) {
|
|
402
|
+
const owner = media.state();
|
|
403
|
+
const run = media.snapshot()?.state ?? INITIAL_REALTIME_STATE;
|
|
404
|
+
const problem = owner.state === "unavailable" ? owner.message : runProblem(run);
|
|
405
|
+
return Object.freeze({
|
|
406
|
+
phase: run.phase,
|
|
407
|
+
available: owner.state === "ready",
|
|
408
|
+
problem
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Why a voice run failed.
|
|
413
|
+
* @param run The run's state.
|
|
414
|
+
* @returns The reason, or null while it has not failed.
|
|
415
|
+
*/
|
|
416
|
+
function runProblem(run) {
|
|
417
|
+
return run.phase === "recoverable_error" || run.phase === "terminal_error" ? run.reason : null;
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Refuse a command result that was not delivered.
|
|
421
|
+
* @param result The command result.
|
|
422
|
+
* @param result.outcome Whether it reached the server.
|
|
423
|
+
* @param result.message The server's words for a refusal.
|
|
424
|
+
*/
|
|
425
|
+
function delivered(result) {
|
|
426
|
+
if (result.outcome === "delivered") return;
|
|
427
|
+
if (result.outcome === "outcome_unknown") throw new UncertainDelivery();
|
|
428
|
+
throw new Error(result.message ?? "The action was not delivered.");
|
|
429
|
+
}
|
|
430
|
+
/** A command whose delivery cannot be known. */
|
|
431
|
+
var UncertainDelivery = class extends Error {
|
|
432
|
+
name = "UncertainDelivery";
|
|
433
|
+
/** Build it with the words the page shows. */
|
|
434
|
+
constructor() {
|
|
435
|
+
super(UNCERTAIN);
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
/**
|
|
439
|
+
* The failure the page shows for a thrown value.
|
|
440
|
+
* @param error The thrown value.
|
|
441
|
+
* @returns The failure, uncertain when the delivery cannot be known.
|
|
442
|
+
*/
|
|
443
|
+
function failureOf(error) {
|
|
444
|
+
if (error instanceof UncertainDelivery || error instanceof BrowserWorkbenchTransportError && error.outcome === "outcome_unknown") return Object.freeze({
|
|
445
|
+
message: UNCERTAIN,
|
|
446
|
+
uncertain: true
|
|
447
|
+
});
|
|
448
|
+
return Object.freeze({
|
|
449
|
+
message: error instanceof Error ? error.message : String(error),
|
|
450
|
+
uncertain: false
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* The reason a socket's close names, such as the server's words for a refusal.
|
|
455
|
+
* @param socket The socket.
|
|
456
|
+
* @returns The reason once the socket closed, empty when its close names none.
|
|
457
|
+
*/
|
|
458
|
+
function closeReasonOf(socket) {
|
|
459
|
+
return new Promise((resolve) => {
|
|
460
|
+
socket.addEventListener("close", (event) => resolve("reason" in event && typeof event.reason === "string" ? event.reason : ""), { once: true });
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Wait for a socket to open.
|
|
465
|
+
* @param socket The socket.
|
|
466
|
+
* @returns Its opening, or the failure that ended it.
|
|
467
|
+
*/
|
|
468
|
+
function opened(socket) {
|
|
469
|
+
return new Promise((resolve, reject) => {
|
|
470
|
+
socket.addEventListener("open", () => resolve(), { once: true });
|
|
471
|
+
socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error("The voice connection failed. Reconnect to try again.")), { once: true });
|
|
472
|
+
socket.addEventListener("close", () => reject(/* @__PURE__ */ new Error("The voice connection closed.")), { once: true });
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
export { createVoiceClient };
|