@archboard/codex-realtime-voice 0.5.0 → 0.6.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.
Files changed (34) hide show
  1. package/README.md +32 -41
  2. package/dist/browser.d.mts +1 -3
  3. package/dist/browser.mjs +67 -66
  4. package/dist/{contract-CDS04znV.d.mts → contract-B2ILifH5.d.mts} +3 -3
  5. package/dist/{contract-qg6q9-vH.d.mts → contract-CkitFygd.d.mts} +97 -3054
  6. package/dist/{contract-DkiXnfc8.d.mts → contract-D9_WuSxD.d.mts} +3 -3
  7. package/dist/contract.d.mts +1 -1
  8. package/dist/controllers.d.mts +221 -6
  9. package/dist/controllers.mjs +3 -3
  10. package/dist/{gateway-envelope-DRBUhFx9.d.mts → gateway-envelope-O67wCRD7.d.mts} +3 -2
  11. package/dist/{realtime-state-CTBmCjt1.mjs → gateway-envelope-jUP82Pq1.mjs} +71 -3
  12. package/dist/identity-capabilities-3Q_2tJiT.d.mts +147 -0
  13. package/dist/instructions-B-6HVmoD.mjs +1024 -0
  14. package/dist/{contract-JI3xv17m.d.mts → instructions-C6TkBWcp.d.mts} +14 -998
  15. package/dist/{model-DnitkA24.mjs → model-MSyAviwx.mjs} +1652 -85
  16. package/dist/react.d.mts +1 -1
  17. package/dist/{realtime-contract-wHmSyUIe.d.mts → realtime-contract-C-1bMn-F.d.mts} +1 -22
  18. package/dist/realtime.d.mts +2 -3
  19. package/dist/realtime.mjs +1 -3
  20. package/dist/runtime.d.mts +3 -18
  21. package/dist/runtime.mjs +2 -2
  22. package/dist/schemas.d.mts +3 -13
  23. package/dist/schemas.mjs +1 -1
  24. package/dist/server.d.mts +977 -217
  25. package/dist/server.mjs +17771 -10076
  26. package/dist/{snapshot-BCrCORmt.d.mts → snapshot-DCl2vsJl.d.mts} +9 -154
  27. package/dist/{transport-Bqb8KE5T.mjs → transport-DVUz3EK0.mjs} +17 -13
  28. package/package.json +1 -1
  29. package/dist/app-server-contract-D4E5bibD.mjs +0 -177
  30. package/dist/gateway-envelope-DXTRMB3q.mjs +0 -45
  31. package/dist/instructions-8ACs49yJ.mjs +0 -8980
  32. package/dist/media-state-CNkFo93s.d.mts +0 -215
  33. package/dist/realtime-contract-DwkCluo2.mjs +0 -1167
  34. package/dist/realtime-state-DT4uvrIV.d.mts +0 -16
@@ -1,1167 +0,0 @@
1
- import { z } from "zod";
2
- // ../codex-app-server/src/shared/schemas/identity-values.ts
3
- const RECORD_PREFIX_SOURCE = `[a-z][a-z0-9-]{0,15}`;
4
- const RECORD_PREFIX_PATTERN = new RegExp(`^${RECORD_PREFIX_SOURCE}$`, "u");
5
- const RAW_ID_LIMIT_BYTES = 4096;
6
- const CANONICAL_ITEM_ID_MAX_LENGTH = 8215;
7
- const TOKEN_PATTERN = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._~-]{0,8192}$`, "u");
8
- const WIRE_PATTERN = new RegExp(`^(${RECORD_PREFIX_SOURCE}):([a-z-]+):([A-Za-z0-9][A-Za-z0-9._~-]{0,8192})$`, "u");
9
- const EPOCH_TOKEN_PATTERN = new RegExp(`^([A-Za-z0-9][A-Za-z0-9._~-]{0,8192})\\.([A-Za-z0-9][A-Za-z0-9._~-]{0,8192})$`, "u");
10
- const IDENTITY_DOMAINS = /* @__PURE__ */ new Set([
11
- "child",
12
- "epoch",
13
- "browser-command",
14
- "thread",
15
- "turn",
16
- "item",
17
- "queued-submission",
18
- "login",
19
- "json-rpc-request",
20
- "dynamic-tool-call",
21
- "realtime-session",
22
- "approval",
23
- "operation"
24
- ]);
25
- var IdentityValidationError = class extends Error {
26
- code;
27
- domain;
28
- /**
29
- * Creates a refusal that names both the rule broken and, when known, the
30
- * identity domain it was broken in.
31
- * @param code - Which validation rule refused the value.
32
- * @param message - The human-readable reason.
33
- * @param domain - The identity domain being validated, when one applies.
34
- */
35
- constructor(code, message, domain) {
36
- super(message);
37
- this.name = "IdentityValidationError";
38
- this.code = code;
39
- this.domain = domain;
40
- }
41
- };
42
- /**
43
- * Refuses a value with a typed validation error. Declared `never` so a caller
44
- * can `return fail(...)` inside a function that must otherwise produce a value.
45
- * @param code - Which validation rule refused the value.
46
- * @param message - The human-readable reason.
47
- * @param domain - The identity domain being validated, when one applies.
48
- * @throws {IdentityValidationError} Always.
49
- */
50
- function fail(code, message, domain) {
51
- throw new IdentityValidationError(code, message, domain);
52
- }
53
- /**
54
- * Tells whether a string names one of the identity domains.
55
- * @param value - The domain segment of a wire value.
56
- * @returns True when it is a declared identity domain.
57
- */
58
- function isIdentityDomain(value) {
59
- return IDENTITY_DOMAINS.has(value);
60
- }
61
- /**
62
- * Brands a string that has already been validated as a canonical wire value
63
- * of `domain`. This is the one site that manufactures a branded identity; every
64
- * other path reaches a brand only by validating first.
65
- * @param value - A string already checked against the wire pattern for `domain`.
66
- * @returns The same string, carrying the domain brand.
67
- */
68
- function brand(value) {
69
- return value;
70
- }
71
- /**
72
- * Splits a canonical wire value into its record prefix, domain and token segments.
73
- * @param value - The string to match.
74
- * @returns The three segments, or null when the string is not a wire value.
75
- */
76
- function wireSegments(value) {
77
- const match = WIRE_PATTERN.exec(value);
78
- if (match === null) return null;
79
- const [, prefix, domain, token] = match;
80
- if (prefix === void 0 || domain === void 0 || token === void 0) return null;
81
- return {
82
- prefix,
83
- domain,
84
- token
85
- };
86
- }
87
- /**
88
- * Validates that a value is a canonical wire identity of `domain` and returns
89
- * its token, refusing with the most specific code available.
90
- * @param value - The untrusted value.
91
- * @param domain - The domain the caller expects.
92
- * @returns The token segment after the domain.
93
- * @throws {IdentityValidationError} When the value is not a wire identity of that domain.
94
- */
95
- function requireToken(value, domain) {
96
- if (typeof value !== "string") return fail("invalid-shape", `${domain} identity must be a string.`, domain);
97
- if (value.length === 0) return fail("empty", `${domain} identity must not be empty.`, domain);
98
- if (value.trim() !== value) return fail("invalid-shape", `${domain} identity must not have surrounding whitespace.`, domain);
99
- const segments = wireSegments(value);
100
- if (segments === null) return fail("invalid-shape", `Invalid ${domain} identity wire value.`, domain);
101
- if (segments.domain !== domain) return fail("wrong-domain", `Expected a ${domain} identity.`, domain);
102
- return segments.token;
103
- }
104
- /**
105
- * Spells a canonical wire value from a record prefix, a domain and a token.
106
- * @param prefix - A valid record prefix: `prefixOf` an identity, or one `requireRecordPrefix` passed.
107
- * @param domain - The identity domain.
108
- * @param token - The token, which must match the token grammar.
109
- * @returns The branded `<prefix>:<domain>:<token>` value.
110
- * @throws {IdentityValidationError} When the token does not fit the grammar.
111
- */
112
- function wireValue(prefix, domain, token) {
113
- if (!TOKEN_PATTERN.test(token)) return fail("invalid-shape", `Invalid ${domain} identity token.`, domain);
114
- return brand(`${prefix}:${domain}:${token}`);
115
- }
116
- /**
117
- * Checks a host's record prefix, which every identity its ledger spells begins with.
118
- * @param prefix - The untrusted prefix.
119
- * @returns The same prefix.
120
- * @throws {TypeError} When it is not 1 to 16 characters of `[a-z][a-z0-9-]*`.
121
- */
122
- function requireRecordPrefix(prefix) {
123
- if (typeof prefix !== "string" || !RECORD_PREFIX_PATTERN.test(prefix)) throw new TypeError(`A record prefix must match ^${RECORD_PREFIX_SOURCE}$.`);
124
- return prefix;
125
- }
126
- /**
127
- * Mints a fresh random token for a server-owned identity.
128
- * @returns Thirty-two lowercase hexadecimal characters.
129
- */
130
- function mintToken() {
131
- return crypto.randomUUID().replaceAll("-", "");
132
- }
133
- /**
134
- * Reads the token segment back out of a branded identity.
135
- * @param value - A branded identity of any domain.
136
- * @returns The token after the domain segment.
137
- * @throws {IdentityValidationError} When the string is not canonical after all.
138
- */
139
- function tokenOf(value) {
140
- const segments = wireSegments(value);
141
- if (segments === null) return fail("invalid-shape", "Identity is not a canonical wire value.");
142
- return segments.token;
143
- }
144
- /**
145
- * Reads the record prefix back out of a branded identity.
146
- * @param value - A branded identity of any domain.
147
- * @returns The prefix before the domain segment.
148
- * @throws {IdentityValidationError} When the string is not canonical after all.
149
- */
150
- function prefixOf(value) {
151
- const segments = wireSegments(value);
152
- if (segments === null) return fail("invalid-shape", "Identity is not a canonical wire value.");
153
- return segments.prefix;
154
- }
155
- /**
156
- * Mints a server-owned identity whose token is marked with the `h` prefix.
157
- * @param prefix - The host's record prefix.
158
- * @param domain - The identity domain to mint in.
159
- * @returns A fresh branded identity.
160
- * @throws {TypeError} When the record prefix is not of its shape.
161
- */
162
- function mintServerValue(prefix, domain) {
163
- return wireValue(requireRecordPrefix(prefix), domain, `h${mintToken()}`);
164
- }
165
- /**
166
- * Validates an untrusted value as a wire identity of `domain` and brands it.
167
- * @param value - The untrusted value.
168
- * @param domain - The domain the caller expects.
169
- * @returns The value, branded.
170
- * @throws {IdentityValidationError} When the value is not a wire identity of that domain.
171
- */
172
- function parseValue(value, domain) {
173
- requireToken(value, domain);
174
- return brand(String(value));
175
- }
176
- /**
177
- * Validates a child epoch, whose token is `<child token>.<epoch token>`, and
178
- * optionally checks that it belongs to one particular child.
179
- * @param value - The untrusted value.
180
- * @param expectedChild - When given, the child the epoch must belong to.
181
- * @returns The value, branded as an epoch.
182
- * @throws {IdentityValidationError} When it is not an epoch or belongs to another child.
183
- */
184
- function parseEpochValue(value, expectedChild) {
185
- const token = requireToken(value, "epoch");
186
- const match = EPOCH_TOKEN_PATTERN.exec(token);
187
- if (!match) return fail("invalid-shape", "A child epoch must bind to a child identity.", "epoch");
188
- const epoch = brand(String(value));
189
- if (expectedChild !== void 0 && (match[1] !== tokenOf(expectedChild) || prefixOf(epoch) !== prefixOf(expectedChild))) return fail("wrong-child", "The child epoch belongs to another child.", "epoch");
190
- return epoch;
191
- }
192
- /**
193
- * Mints a new epoch bound to `child`.
194
- * @param child - The child the epoch belongs to.
195
- * @returns A fresh branded epoch.
196
- */
197
- function mintEpochValue(child) {
198
- return wireValue(prefixOf(child), "epoch", `${tokenOf(child)}.h${mintToken()}`);
199
- }
200
- /**
201
- * Tells whether a UTF-16 code unit opens a surrogate pair.
202
- * @param codeUnit - The code unit.
203
- * @returns True for a high surrogate.
204
- */
205
- function isHighSurrogate(codeUnit) {
206
- return codeUnit >= 55296 && codeUnit <= 56319;
207
- }
208
- /**
209
- * Tells whether a UTF-16 code unit closes a surrogate pair.
210
- * @param codeUnit - The code unit, or NaN past the end of the string.
211
- * @returns True for a low surrogate.
212
- */
213
- function isLowSurrogate(codeUnit) {
214
- return codeUnit >= 56320 && codeUnit <= 57343;
215
- }
216
- /**
217
- * Tells whether a string has no lone surrogates, so its UTF-8 encoding is a
218
- * faithful and reversible spelling of it.
219
- * @param value - The string to check.
220
- * @returns True when every surrogate is part of a complete pair.
221
- */
222
- function isWellFormedUnicode(value) {
223
- for (let index = 0; index < value.length; index++) {
224
- const codeUnit = value.charCodeAt(index);
225
- if (isHighSurrogate(codeUnit)) {
226
- if (!isLowSurrogate(value.charCodeAt(index + 1))) return false;
227
- index++;
228
- } else if (isLowSurrogate(codeUnit)) return false;
229
- }
230
- return true;
231
- }
232
- /**
233
- * Spells bytes as lowercase hexadecimal.
234
- * @param bytes - The bytes to spell.
235
- * @returns Two hexadecimal characters per byte.
236
- */
237
- function hex(bytes) {
238
- let encoded = "";
239
- for (const byte of bytes) encoded += byte.toString(16).padStart(2, "0");
240
- return encoded;
241
- }
242
- /**
243
- * Encodes a raw server-issued id into a token that fits the wire grammar
244
- * whatever characters the server used: hex of its UTF-8 bytes, marked `s`.
245
- * @param raw - The id exactly as the server sent it.
246
- * @param domain - The domain it belongs to, for error messages.
247
- * @returns The `s`-prefixed hexadecimal token.
248
- * @throws {IdentityValidationError} When the id is empty, ill-formed, too large or contains NUL.
249
- */
250
- function encodeRawIdentity(raw, domain) {
251
- if (raw.length === 0) return fail("empty", `${domain} identity must not be empty.`, domain);
252
- if (!isWellFormedUnicode(raw)) return fail("invalid-shape", `The server ${domain} identity contains ill-formed Unicode.`, domain);
253
- const bytes = new TextEncoder().encode(raw);
254
- if (bytes.byteLength > RAW_ID_LIMIT_BYTES || raw.includes("\0")) return fail("invalid-shape", `The server ${domain} identity is not a valid wire value.`, domain);
255
- return `s${hex(bytes)}`;
256
- }
257
- /**
258
- * Encodes a JSON-RPC request id, which the protocol allows to be a string or
259
- * an integer, keeping the two kinds apart with different token markers so
260
- * the original can be given back unchanged.
261
- * @param raw - The id as the server sent it.
262
- * @returns An `s`-prefixed token for a string, an `n`-prefixed one for an integer.
263
- * @throws {IdentityValidationError} When the id is neither, or too large.
264
- */
265
- function encodeRawJsonRpcRequestId(raw) {
266
- if (typeof raw === "string") return encodeRawIdentity(raw, "json-rpc-request");
267
- if (!Number.isSafeInteger(raw)) return fail("invalid-shape", "The server json-rpc-request identity must be a string or integer.", "json-rpc-request");
268
- const encoded = new TextEncoder().encode(Object.is(raw, -0) ? "-0" : String(raw));
269
- if (encoded.byteLength > RAW_ID_LIMIT_BYTES) return fail("invalid-shape", "The server json-rpc-request identity is too large.", "json-rpc-request");
270
- return `n${hex(encoded)}`;
271
- }
272
- /**
273
- * Reads the domain of an untrusted value that should be a wire identity.
274
- * @param value - The untrusted value.
275
- * @returns The identity domain the value names.
276
- * @throws {IdentityValidationError} When the value is not a canonical workbench identity.
277
- */
278
- function identityDomain(value) {
279
- if (typeof value !== "string") return fail("invalid-shape", "Identity must be a string.");
280
- const segments = wireSegments(value);
281
- if (segments === null || !isIdentityDomain(segments.domain)) return fail("invalid-shape", "Identity is not a canonical workbench identity.");
282
- return segments.domain;
283
- }
284
- // ../codex-app-server/src/shared/rules/identity-correlations.ts
285
- const TEXT_LIMIT = 256;
286
- const CORRELATION_KEYS = [
287
- "child",
288
- "epoch",
289
- "requestId"
290
- ];
291
- const TOOL_CORRELATION_KEYS = [
292
- "child",
293
- "epoch",
294
- "threadId",
295
- "turnId",
296
- "callId",
297
- "namespace",
298
- "tool",
299
- "manifestHash"
300
- ];
301
- /**
302
- * Stable identity for one logical dynamic-tool call across wire retries and owners.
303
- * @param call - The correlation to key.
304
- * @returns A JSON array of every field, in declaration order, as one string.
305
- */
306
- function logicalToolCallKey(call) {
307
- return JSON.stringify([
308
- call.child,
309
- call.epoch,
310
- call.threadId,
311
- call.turnId,
312
- call.callId,
313
- call.namespace,
314
- call.tool,
315
- call.manifestHash
316
- ]);
317
- }
318
- /**
319
- * Tells whether a value is a non-array object, so its keys can be read.
320
- * @param value - The untrusted value.
321
- * @returns True for a plain record shape.
322
- */
323
- function isRecord(value) {
324
- return value !== null && typeof value === "object" && !Array.isArray(value);
325
- }
326
- /**
327
- * Refuses a record that carries any key, string or symbol, outside `keys`.
328
- * @param record - The record to inspect.
329
- * @param keys - The only keys allowed.
330
- * @throws {IdentityValidationError} As `extra-field` when another key is present.
331
- */
332
- function assertOnlyKeys(record, keys) {
333
- for (const key of Reflect.ownKeys(record)) if (typeof key !== "string" || !keys.includes(key)) fail("extra-field", "An identity correlation contains an unexpected field.");
334
- }
335
- /**
336
- * Refuses a record missing any of `keys` as an own property.
337
- * @param record - The record to inspect.
338
- * @param keys - The keys that must all be present.
339
- * @throws {IdentityValidationError} As `invalid-shape` naming the first missing key.
340
- */
341
- function assertAllKeys(record, keys) {
342
- for (const key of keys) if (!Object.prototype.hasOwnProperty.call(record, key)) fail("invalid-shape", `Missing correlation field "${key}".`);
343
- }
344
- /**
345
- * Narrows an untrusted value to a record with exactly the given keys.
346
- * @param value - The untrusted value.
347
- * @param keys - The complete key set the record must have.
348
- * @returns The value as a record.
349
- * @throws {IdentityValidationError} When it is not a record or its key set differs.
350
- */
351
- function requireRecord(value, keys) {
352
- if (!isRecord(value)) return fail("invalid-shape", "An identity correlation must be a record.");
353
- assertOnlyKeys(value, keys);
354
- assertAllKeys(value, keys);
355
- return value;
356
- }
357
- /**
358
- * Validates a bounded text field of a correlation: non-empty, trimmed, short,
359
- * and free of NUL.
360
- * @param value - The untrusted value.
361
- * @param field - The field name, for the error message.
362
- * @returns The text unchanged.
363
- * @throws {IdentityValidationError} As `invalid-field` when the text is unacceptable.
364
- */
365
- function assertText(value, field) {
366
- if (typeof value !== "string" || value.length === 0 || value.trim() !== value || value.length > TEXT_LIMIT) return fail("invalid-field", `${field} must be a non-empty bounded string.`);
367
- if (value.includes("\0")) return fail("invalid-field", `${field} must not contain NUL.`);
368
- return value;
369
- }
370
- /**
371
- * Refuses a correlation that names another child or an earlier epoch.
372
- * @param child - The child the correlation names.
373
- * @param epoch - The epoch the correlation names.
374
- * @param currentChild - This session's child.
375
- * @param currentEpoch - This session's epoch.
376
- * @throws {IdentityValidationError} As `wrong-child` or `stale-epoch`.
377
- */
378
- function assertCurrent(child, epoch, currentChild, currentEpoch) {
379
- if (child !== currentChild) fail("wrong-child", "The correlation belongs to another child.");
380
- if (epoch !== currentEpoch) fail("stale-epoch", "The correlation belongs to a stale child epoch.");
381
- }
382
- /**
383
- * Refuses an identity this session never issued, whatever its shape.
384
- * @param value - The branded identity.
385
- * @param domain - Its domain.
386
- * @param issued - The issuance ledger, by domain.
387
- * @throws {IdentityValidationError} As `unissued` when the ledger lacks it.
388
- */
389
- function assertIssued(value, domain, issued) {
390
- if (!issued.get(domain)?.has(value)) fail("unissued", `The ${domain} identity was not issued by this workbench session.`, domain);
391
- }
392
- /**
393
- * Decodes a wire request correlation and proves every part of it current
394
- * and issued here.
395
- * @param value - The untrusted record.
396
- * @param childId - This session's child.
397
- * @param epoch - This session's epoch.
398
- * @param issued - The issuance ledger, by domain.
399
- * @returns The frozen correlation.
400
- * @throws {IdentityValidationError} When any field is malformed, foreign, stale or unissued.
401
- */
402
- function parseWireRequestCorrelationValue(value, childId, epoch, issued) {
403
- const record = requireRecord(value, CORRELATION_KEYS);
404
- const child = parseValue(record["child"], "child");
405
- const parsedEpoch = parseEpochValue(record["epoch"], child);
406
- const requestId = parseValue(record["requestId"], "json-rpc-request");
407
- assertCurrent(child, parsedEpoch, childId, epoch);
408
- assertIssued(child, "child", issued);
409
- assertIssued(parsedEpoch, "epoch", issued);
410
- assertIssued(requestId, "json-rpc-request", issued);
411
- return Object.freeze({
412
- child,
413
- epoch: parsedEpoch,
414
- requestId
415
- });
416
- }
417
- /**
418
- * Decodes a logical tool-call correlation and proves every identity in it
419
- * current and issued here, and every text field bounded.
420
- * @param value - The untrusted record.
421
- * @param childId - This session's child.
422
- * @param epoch - This session's epoch.
423
- * @param issued - The issuance ledger, by domain.
424
- * @returns The frozen correlation.
425
- * @throws {IdentityValidationError} When any field is malformed, foreign, stale or unissued.
426
- */
427
- function parseLogicalToolCallCorrelationValue(value, childId, epoch, issued) {
428
- const record = requireRecord(value, TOOL_CORRELATION_KEYS);
429
- const child = parseValue(record["child"], "child");
430
- const parsedEpoch = parseEpochValue(record["epoch"], child);
431
- const threadId = parseValue(record["threadId"], "thread");
432
- const turnId = parseValue(record["turnId"], "turn");
433
- const callId = parseValue(record["callId"], "dynamic-tool-call");
434
- assertCurrent(child, parsedEpoch, childId, epoch);
435
- assertIssued(child, "child", issued);
436
- assertIssued(parsedEpoch, "epoch", issued);
437
- assertIssued(threadId, "thread", issued);
438
- assertIssued(turnId, "turn", issued);
439
- assertIssued(callId, "dynamic-tool-call", issued);
440
- return Object.freeze({
441
- child,
442
- epoch: parsedEpoch,
443
- threadId,
444
- turnId,
445
- callId,
446
- namespace: assertText(record["namespace"], "namespace"),
447
- tool: assertText(record["tool"], "tool"),
448
- manifestHash: assertText(record["manifestHash"], "manifestHash")
449
- });
450
- }
451
- const OPERATION_TOKEN_PATTERN = new RegExp(`^([A-Za-z0-9][A-Za-z0-9._~-]{0,8192})\\.(h[0-9a-f]{32})$`, "u");
452
- const OPERATION_NONCE_PATTERN = /^[0-9a-f]{32}$/u;
453
- /**
454
- * Spells an operation identity from the epoch it is issued in and a nonce.
455
- * @param epoch - The current child epoch.
456
- * @param nonce - Thirty-two lowercase hexadecimal characters.
457
- * @returns The branded operation identity.
458
- * @throws {IdentityValidationError} When the nonce is malformed or the value exceeds the byte limit.
459
- */
460
- function operationWireValue(epoch, nonce) {
461
- if (typeof nonce !== "string" || !OPERATION_NONCE_PATTERN.test(nonce)) return fail("invalid-shape", "Operation identity nonce must be 32 lowercase hexadecimal characters.", "operation");
462
- const value = wireValue(prefixOf(epoch), "operation", `${tokenOf(epoch)}.h${nonce}`);
463
- if (new TextEncoder().encode(value).byteLength > 128) return fail("invalid-shape", `Operation identity exceeds 128 UTF-8 bytes.`, "operation");
464
- return value;
465
- }
466
- /**
467
- * Names why an operation's epoch token is not the current one: it belongs to
468
- * an earlier epoch of the same child, or to another child altogether.
469
- * @param epochToken - The epoch token carried by the operation.
470
- * @param childId - The current child.
471
- * @returns Never; always refuses with the matching code.
472
- * @throws {IdentityValidationError} Always, as `stale-epoch` or `wrong-child`.
473
- */
474
- function refuseForeignEpoch(epochToken, childId) {
475
- if (epochToken.startsWith(`${tokenOf(childId)}.`)) return fail("stale-epoch", "The operation belongs to a stale child epoch.", "operation");
476
- return fail("wrong-child", "The operation belongs to another child.", "operation");
477
- }
478
- /**
479
- * Validates an operation identity against the current child and epoch and
480
- * returns its token.
481
- * @param value - The untrusted value.
482
- * @param childId - The current child.
483
- * @param epoch - The current epoch.
484
- * @returns The token segment of the operation identity.
485
- * @throws {IdentityValidationError} When the value is malformed, oversized, stale or foreign.
486
- */
487
- function requireOperationToken(value, childId, epoch) {
488
- const token = requireToken(value, "operation");
489
- if (new TextEncoder().encode(String(value)).byteLength > 128) return fail("invalid-shape", `Operation identity exceeds 128 UTF-8 bytes.`, "operation");
490
- const epochToken = OPERATION_TOKEN_PATTERN.exec(token)?.[1];
491
- if (epochToken === void 0 || !EPOCH_TOKEN_PATTERN.test(epochToken)) return fail("invalid-shape", "Operation identity must carry a durable epoch token.", "operation");
492
- if (epochToken !== tokenOf(epoch)) return refuseForeignEpoch(epochToken, childId);
493
- return token;
494
- }
495
- // ../codex-app-server/src/shared/rules/identity-ledger.ts
496
- /** The domains whose identities may be handed back to Codex on the wire. */
497
- const CODEX_WIRE_DOMAINS = /* @__PURE__ */ new Set([
498
- "thread",
499
- "turn",
500
- "item",
501
- "queued-submission",
502
- "login",
503
- "json-rpc-request",
504
- "dynamic-tool-call",
505
- "approval"
506
- ]);
507
- /**
508
- * Records a token as issued in `domain` and remembers the raw value it stands
509
- * for, so it can later be proven issued and serialized back.
510
- * @param ledger - The ledger to write to.
511
- * @param domain - The identity domain.
512
- * @param token - The token to spell the wire value from.
513
- * @param raw - The value the token stands for: the app-server's own value, or for a server
514
- * identity the unprefixed nonce the token was spelled from.
515
- * @returns The branded identity.
516
- */
517
- function issue(ledger, domain, token, raw) {
518
- const value = wireValue(prefixOf(ledger.childId), domain, token);
519
- let values = ledger.issued.get(domain);
520
- if (values === void 0) {
521
- values = /* @__PURE__ */ new Set();
522
- ledger.issued.set(domain, values);
523
- }
524
- values.add(value);
525
- ledger.rawByIdentity.set(value, raw);
526
- return value;
527
- }
528
- /**
529
- * Records an already-branded identity as issued.
530
- * @param ledger - The ledger to write to.
531
- * @param domain - The identity domain.
532
- * @param value - The branded identity.
533
- * @param raw - The app-server's raw value, or the token for a server identity.
534
- * @returns The same identity.
535
- */
536
- function issueExisting(ledger, domain, value, raw) {
537
- return issue(ledger, domain, tokenOf(value), raw);
538
- }
539
- /**
540
- * Mints and records a server-owned identity.
541
- * @param ledger - The ledger to write to.
542
- * @param domain - The identity domain.
543
- * @returns The fresh branded identity.
544
- */
545
- function mint(ledger, domain) {
546
- const raw = mintToken();
547
- return issue(ledger, domain, `h${raw}`, raw);
548
- }
549
- /**
550
- * Mints and records a new epoch for the ledger's child.
551
- * @param ledger - The ledger to write to.
552
- * @returns The fresh branded epoch.
553
- */
554
- function mintEpoch(ledger) {
555
- const nextEpoch = mintEpochValue(ledger.childId);
556
- issueExisting(ledger, "epoch", nextEpoch, tokenOf(nextEpoch));
557
- return nextEpoch;
558
- }
559
- /**
560
- * Mints an operation identity bound to the current epoch, retrying a bounded
561
- * number of times should the random nonce collide with one already issued.
562
- * @param ledger - The ledger to write to.
563
- * @returns The fresh branded operation identity.
564
- * @throws {IdentityValidationError} As `issuance-exhausted` after too many collisions.
565
- */
566
- function mintOperation(ledger) {
567
- for (let attempt = 0; attempt < 16; attempt++) {
568
- const value = operationWireValue(ledger.epoch, mintToken());
569
- if (ledger.issued.get("operation")?.has(value) !== true) return issue(ledger, "operation", tokenOf(value), value);
570
- }
571
- return fail("issuance-exhausted", `Could not issue a unique operation identity after 16 attempts.`, "operation");
572
- }
573
- /**
574
- * Adopts a raw server-issued string id into `domain`, recording it as issued.
575
- * @param ledger - The ledger to write to.
576
- * @param domain - The identity domain.
577
- * @param rawValue - The id as the server sent it.
578
- * @returns The branded identity.
579
- * @throws {IdentityValidationError} When the raw id is not an acceptable string.
580
- */
581
- function adopt(ledger, domain, rawValue) {
582
- if (typeof rawValue !== "string") return fail("invalid-shape", `The server ${domain} identity must be a string.`, domain);
583
- return issue(ledger, domain, encodeRawIdentity(rawValue, domain), rawValue);
584
- }
585
- /**
586
- * Tells whether a raw value is a JSON-RPC id the protocol allows: a string
587
- * or a safe integer.
588
- * @param rawValue - The id as the server sent it.
589
- * @returns True when it may be adopted.
590
- */
591
- function isJsonRpcRequestIdWireValue(rawValue) {
592
- return typeof rawValue === "string" || Number.isSafeInteger(rawValue);
593
- }
594
- /**
595
- * Adopts a raw server-issued JSON-RPC request id, which may be a string or an
596
- * integer, recording it as issued.
597
- * @param ledger - The ledger to write to.
598
- * @param rawValue - The id as the server sent it.
599
- * @returns The branded request id.
600
- * @throws {IdentityValidationError} When the id is neither a string nor a safe integer.
601
- */
602
- function adoptJsonRpcRequestId(ledger, rawValue) {
603
- if (!isJsonRpcRequestIdWireValue(rawValue)) return fail("invalid-shape", "The server json-rpc-request identity must be a string or integer.", "json-rpc-request");
604
- return issue(ledger, "json-rpc-request", encodeRawJsonRpcRequestId(rawValue), rawValue);
605
- }
606
- /**
607
- * Validates one raw response identity without recording it yet.
608
- * @param domain - The identity domain.
609
- * @param rawValue - The id as the server sent it.
610
- * @returns The staged identity, ready to commit.
611
- * @throws {IdentityValidationError} When the raw id is not an acceptable string.
612
- */
613
- function stageResponseIdentity(domain, rawValue) {
614
- if (typeof rawValue !== "string") return fail("invalid-shape", `The server ${domain} identity must be a string.`, domain);
615
- return {
616
- domain,
617
- raw: rawValue,
618
- token: encodeRawIdentity(rawValue, domain)
619
- };
620
- }
621
- /**
622
- * Stages every raw identity of one domain from a response.
623
- * @param domain - The identity domain.
624
- * @param values - The raw ids, absent when the response carried none.
625
- * @returns The staged identities in the same order.
626
- */
627
- function stageResponseIdentities(domain, values) {
628
- return (values ?? []).map((value) => stageResponseIdentity(domain, value));
629
- }
630
- /**
631
- * Records staged identities as issued.
632
- * @param ledger - The ledger to write to.
633
- * @param values - The staged identities.
634
- * @returns The branded identities in the same order.
635
- */
636
- function commitResponseIdentities(ledger, values) {
637
- return values.map(({ domain, raw, token }) => issue(ledger, domain, token, raw));
638
- }
639
- /**
640
- * Validates a complete decoded response before adopting any identity from it.
641
- * Staging every domain first makes a hostile late field fail without trusting
642
- * the valid identities that preceded it in the response.
643
- * @param ledger - The ledger to write to.
644
- * @param batch - The raw identities collected from one response.
645
- * @returns The branded identities, frozen, in the batch's order.
646
- * @throws {IdentityValidationError} When any raw identity is unacceptable.
647
- */
648
- function adoptCodexResponseIdentities(ledger, batch) {
649
- const threadIds = stageResponseIdentities("thread", batch.threadIds);
650
- const turnIds = stageResponseIdentities("turn", batch.turnIds);
651
- const itemIds = stageResponseIdentities("item", batch.itemIds);
652
- const queuedSubmissionIds = stageResponseIdentities("queued-submission", batch.queuedSubmissionIds);
653
- const loginIds = stageResponseIdentities("login", batch.loginIds);
654
- return Object.freeze({
655
- threadIds: Object.freeze(commitResponseIdentities(ledger, threadIds)),
656
- turnIds: Object.freeze(commitResponseIdentities(ledger, turnIds)),
657
- itemIds: Object.freeze(commitResponseIdentities(ledger, itemIds)),
658
- queuedSubmissionIds: Object.freeze(commitResponseIdentities(ledger, queuedSubmissionIds)),
659
- loginIds: Object.freeze(commitResponseIdentities(ledger, loginIds))
660
- });
661
- }
662
- /**
663
- * Parses an untrusted value as an identity of `domain` that this ledger issued.
664
- * @param ledger - The ledger to check against.
665
- * @param domain - The identity domain.
666
- * @param value - The untrusted value.
667
- * @returns The branded identity.
668
- * @throws {IdentityValidationError} When malformed or unissued.
669
- */
670
- function parseIssued(ledger, domain, value) {
671
- const parsed = parseValue(value, domain);
672
- assertIssued(parsed, domain, ledger.issued);
673
- return parsed;
674
- }
675
- /**
676
- * Parses an untrusted value as an operation identity issued in the current
677
- * epoch of this ledger.
678
- * @param ledger - The ledger to check against.
679
- * @param value - The untrusted value.
680
- * @returns The branded operation identity.
681
- * @throws {IdentityValidationError} When malformed, stale, foreign or unissued.
682
- */
683
- function parseOperation(ledger, value) {
684
- const parsed = parseValue(value, "operation");
685
- requireOperationToken(parsed, ledger.childId, ledger.epoch);
686
- assertIssued(parsed, "operation", ledger.issued);
687
- return parsed;
688
- }
689
- /**
690
- * Parses an untrusted value as the current child epoch of this ledger.
691
- * @param ledger - The ledger to check against.
692
- * @param value - The untrusted value.
693
- * @returns The branded epoch.
694
- * @throws {IdentityValidationError} When malformed, foreign or unissued.
695
- */
696
- function parseIssuedEpoch(ledger, value) {
697
- const parsed = parseEpochValue(value, ledger.childId);
698
- assertIssued(parsed, "epoch", ledger.issued);
699
- return parsed;
700
- }
701
- /**
702
- * Resolves a raw Codex id to the identity this ledger already adopted for it,
703
- * refusing an id that was never adopted.
704
- * @param ledger - The ledger to check against.
705
- * @param domain - The identity domain.
706
- * @param rawValue - The id as the server sent it.
707
- * @returns The branded identity.
708
- * @throws {IdentityValidationError} When the raw id is unacceptable or unissued.
709
- */
710
- function resolve(ledger, domain, rawValue) {
711
- if (typeof rawValue !== "string") return fail("invalid-shape", `The server ${domain} identity must be a string.`, domain);
712
- return parseIssued(ledger, domain, wireValue(prefixOf(ledger.childId), domain, encodeRawIdentity(rawValue, domain)));
713
- }
714
- /**
715
- * Gives back the raw wire value an issued identity stands for.
716
- * @param ledger - The ledger to read from.
717
- * @param value - The branded identity.
718
- * @param domain - Its domain, already checked by the caller.
719
- * @returns The raw value recorded at issuance.
720
- * @throws {IdentityValidationError} As `unissued` when the ledger has no raw value for it.
721
- */
722
- function rawValueOf(ledger, value, domain) {
723
- assertIssued(value, domain, ledger.issued);
724
- const raw = ledger.rawByIdentity.get(value);
725
- if (raw === void 0) return fail("unissued", "Identity has no trusted wire value.", domain);
726
- return raw;
727
- }
728
- /**
729
- * Serializes a Codex identity back to the string the server knows it by.
730
- * @param ledger - The ledger to read from.
731
- * @param value - The branded identity.
732
- * @returns The server's raw id as a string.
733
- * @throws {IdentityValidationError} When the identity is not a Codex wire identity or unissued.
734
- */
735
- function serialize(ledger, value) {
736
- const domain = identityDomain(value);
737
- if (!CODEX_WIRE_DOMAINS.has(domain)) return fail("wrong-domain", "Identity is not a Codex wire identity.", domain);
738
- return String(rawValueOf(ledger, value, domain));
739
- }
740
- /**
741
- * Serializes a JSON-RPC request identity back to the exact value, string or
742
- * integer, the server used.
743
- * @param ledger - The ledger to read from.
744
- * @param value - The branded request id.
745
- * @returns The server's raw id.
746
- * @throws {IdentityValidationError} When the identity is not a request id or unissued.
747
- */
748
- function serializeJsonRpc(ledger, value) {
749
- const domain = identityDomain(value);
750
- if (domain !== "json-rpc-request") return fail("wrong-domain", "Identity is not a JSON-RPC request identity.", domain);
751
- return rawValueOf(ledger, value, domain);
752
- }
753
- /**
754
- * Builds a wire request correlation for a request id this ledger issued.
755
- * @param ledger - The ledger to check against.
756
- * @param input - The request id.
757
- * @returns The frozen correlation bound to the current child and epoch.
758
- * @throws {IdentityValidationError} When the request id was not issued here.
759
- */
760
- function createWireRequestCorrelation(ledger, input) {
761
- const requestId = parseIssued(ledger, "json-rpc-request", input.requestId);
762
- return Object.freeze({
763
- child: ledger.childId,
764
- epoch: ledger.epoch,
765
- requestId
766
- });
767
- }
768
- /**
769
- * Builds a logical tool-call correlation from identities this ledger issued
770
- * and bounded text fields.
771
- * @param ledger - The ledger to check against.
772
- * @param input - The identities and text of the call.
773
- * @returns The frozen correlation bound to the current child and epoch.
774
- * @throws {IdentityValidationError} When an identity was not issued here or a text field is unacceptable.
775
- */
776
- function createLogicalToolCallCorrelation(ledger, input) {
777
- const threadId = parseIssued(ledger, "thread", input.threadId);
778
- const turnId = parseIssued(ledger, "turn", input.turnId);
779
- const callId = parseIssued(ledger, "dynamic-tool-call", input.callId);
780
- return Object.freeze({
781
- child: ledger.childId,
782
- epoch: ledger.epoch,
783
- threadId,
784
- turnId,
785
- callId,
786
- namespace: assertText(input.namespace, "namespace"),
787
- tool: assertText(input.tool, "tool"),
788
- manifestHash: assertText(input.manifestHash, "manifestHash")
789
- });
790
- }
791
- // ../codex-app-server/src/shared/rules/workbench-identity.ts
792
- /**
793
- * Builds the validator: the epoch facts every owner may compare against.
794
- * @param ledger - The ledger the validator reads.
795
- * @returns A frozen validator.
796
- */
797
- function createValidator(ledger) {
798
- const { childId, epoch } = ledger;
799
- return Object.freeze({
800
- childId,
801
- epoch,
802
- /**
803
- * Tells whether a child and epoch are this session's current ones.
804
- * @param child - The child to compare.
805
- * @param candidateEpoch - The epoch to compare.
806
- * @returns True when both match.
807
- */
808
- isCurrentEpoch: (child, candidateEpoch) => child === childId && candidateEpoch === epoch,
809
- /**
810
- * Refuses a child and epoch that are not this session's current ones.
811
- * @param child - The child to compare.
812
- * @param candidateEpoch - The epoch to compare.
813
- */
814
- assertCurrentEpoch: (child, candidateEpoch) => {
815
- assertCurrent(child, candidateEpoch, childId, epoch);
816
- }
817
- });
818
- }
819
- /**
820
- * Builds the issuer: the server-owned identities this session may mint.
821
- * @param ledger - The ledger the issuer records into.
822
- * @returns A frozen issuer.
823
- */
824
- function createIssuer(ledger) {
825
- return Object.freeze({
826
- /**
827
- * Mints a browser command id.
828
- * @returns The fresh id.
829
- */
830
- mintBrowserCommandId: () => mint(ledger, "browser-command"),
831
- /**
832
- * Mints a JSON-RPC request id for a request this server sends.
833
- * @returns The fresh id.
834
- */
835
- mintJsonRpcRequestId: () => mint(ledger, "json-rpc-request"),
836
- /**
837
- * Mints a realtime session id.
838
- * @returns The fresh id.
839
- */
840
- mintRealtimeSessionId: () => mint(ledger, "realtime-session"),
841
- /**
842
- * Mints and records a new epoch for this session's child.
843
- * @returns The fresh epoch.
844
- */
845
- mintChildEpoch: () => mintEpoch(ledger)
846
- });
847
- }
848
- /**
849
- * Builds the trusted decoder: parsing, adopting and serializing identities
850
- * against the ledger.
851
- * @param ledger - The ledger the decoder reads and records into.
852
- * @returns A frozen decoder.
853
- */
854
- function createDecoder(ledger) {
855
- const { childId, epoch, issued } = ledger;
856
- return Object.freeze({
857
- /**
858
- * Parses a child id this session issued.
859
- * @param value - The untrusted value.
860
- * @returns The issued child id.
861
- */
862
- parseChildId: (value) => parseIssued(ledger, "child", value),
863
- /**
864
- * Parses an epoch of this session's child that it issued.
865
- * @param value - The untrusted value.
866
- * @returns The issued epoch of this child.
867
- */
868
- parseChildEpoch: (value) => parseIssuedEpoch(ledger, value),
869
- /**
870
- * Parses a browser command id this session issued.
871
- * @param value - The untrusted value.
872
- * @returns The issued browser command id.
873
- */
874
- parseBrowserCommandId: (value) => parseIssued(ledger, "browser-command", value),
875
- /**
876
- * Parses a thread id this session issued or adopted.
877
- * @param value - The untrusted value.
878
- * @returns The issued thread id.
879
- */
880
- parseThreadId: (value) => parseIssued(ledger, "thread", value),
881
- /**
882
- * Parses a turn id this session issued or adopted.
883
- * @param value - The untrusted value.
884
- * @returns The issued turn id.
885
- */
886
- parseTurnId: (value) => parseIssued(ledger, "turn", value),
887
- /**
888
- * Parses an item id this session issued or adopted.
889
- * @param value - The untrusted value.
890
- * @returns The issued item id.
891
- */
892
- parseItemId: (value) => parseIssued(ledger, "item", value),
893
- /**
894
- * Parses a queued submission id this session adopted.
895
- * @param value - The untrusted value.
896
- * @returns The issued queued submission id.
897
- */
898
- parseQueuedSubmissionId: (value) => parseIssued(ledger, "queued-submission", value),
899
- /**
900
- * Parses a login id this session adopted.
901
- * @param value - The untrusted value.
902
- * @returns The issued login id.
903
- */
904
- parseLoginId: (value) => parseIssued(ledger, "login", value),
905
- /**
906
- * Parses a JSON-RPC request id this session issued or adopted.
907
- * @param value - The untrusted value.
908
- * @returns The issued JSON-RPC request id.
909
- */
910
- parseJsonRpcRequestId: (value) => parseIssued(ledger, "json-rpc-request", value),
911
- /**
912
- * Parses a dynamic tool call id this session adopted.
913
- * @param value - The untrusted value.
914
- * @returns The issued dynamic tool call id.
915
- */
916
- parseDynamicToolCallId: (value) => parseIssued(ledger, "dynamic-tool-call", value),
917
- /**
918
- * Parses a realtime session id this session issued.
919
- * @param value - The untrusted value.
920
- * @returns The issued realtime session id.
921
- */
922
- parseRealtimeSessionId: (value) => parseIssued(ledger, "realtime-session", value),
923
- /**
924
- * Parses an approval id this session adopted.
925
- * @param value - The untrusted value.
926
- * @returns The issued approval id.
927
- */
928
- parseApprovalId: (value) => parseIssued(ledger, "approval", value),
929
- /**
930
- * Looks up the thread id already adopted for a raw Codex thread id.
931
- * @param raw - The raw Codex thread id.
932
- * @returns The thread id already adopted for it.
933
- */
934
- resolveThreadId: (raw) => resolve(ledger, "thread", raw),
935
- /**
936
- * Looks up the item id already adopted for a raw Codex item id.
937
- * @param raw - The raw Codex item id.
938
- * @returns The item id already adopted for it.
939
- */
940
- resolveItemId: (raw) => resolve(ledger, "item", raw),
941
- /**
942
- * Adopts a raw Codex thread id into this session.
943
- * @param raw - The raw Codex thread id.
944
- * @returns The newly adopted thread id.
945
- */
946
- adoptThreadId: (raw) => adopt(ledger, "thread", raw),
947
- /**
948
- * Adopts a raw Codex turn id into this session.
949
- * @param raw - The raw Codex turn id.
950
- * @returns The newly adopted turn id.
951
- */
952
- adoptTurnId: (raw) => adopt(ledger, "turn", raw),
953
- /**
954
- * Adopts a raw Codex item id into this session.
955
- * @param raw - The raw Codex item id.
956
- * @returns The newly adopted item id.
957
- */
958
- adoptItemId: (raw) => adopt(ledger, "item", raw),
959
- /**
960
- * Adopts a raw Codex queued submission id into this session.
961
- * @param raw - The raw Codex queued submission id.
962
- * @returns The newly adopted queued submission id.
963
- */
964
- adoptQueuedSubmissionId: (raw) => adopt(ledger, "queued-submission", raw),
965
- /**
966
- * Adopts a raw Codex login id into this session.
967
- * @param raw - The raw Codex login id.
968
- * @returns The newly adopted login id.
969
- */
970
- adoptLoginId: (raw) => adopt(ledger, "login", raw),
971
- /**
972
- * Adopts a raw JSON-RPC request id the server chose.
973
- * @param raw - The raw JSON-RPC request id, string or integer.
974
- * @returns The newly adopted request id.
975
- */
976
- adoptJsonRpcRequestId: (raw) => adoptJsonRpcRequestId(ledger, raw),
977
- /**
978
- * Adopts a raw Codex dynamic tool call id into this session.
979
- * @param raw - The raw Codex dynamic tool call id.
980
- * @returns The newly adopted call id.
981
- */
982
- adoptDynamicToolCallId: (raw) => adopt(ledger, "dynamic-tool-call", raw),
983
- /**
984
- * Adopts a raw Codex approval id into this session.
985
- * @param raw - The raw Codex approval id.
986
- * @returns The newly adopted approval id.
987
- */
988
- adoptApprovalId: (raw) => adopt(ledger, "approval", raw),
989
- /**
990
- * Adopts every identity of one decoded response, all or none.
991
- * @param batch - The raw identities of one decoded response.
992
- * @returns The adopted identities, or nothing adopted when any is bad.
993
- */
994
- adoptCodexResponseIdentities: (batch) => adoptCodexResponseIdentities(ledger, batch),
995
- /**
996
- * Serializes an issued Codex identity back to the server's raw id.
997
- * @param identity - An issued Codex identity.
998
- * @returns The raw string the server knows it by.
999
- */
1000
- serializeCodexIdentity: (identity) => serialize(ledger, identity),
1001
- /**
1002
- * Serializes an issued request id back to the exact value the server used.
1003
- * @param identity - An issued JSON-RPC request id.
1004
- * @returns The raw value, string or integer, the server used.
1005
- */
1006
- serializeJsonRpcRequestId: (identity) => serializeJsonRpc(ledger, identity),
1007
- /**
1008
- * Correlates an issued request id with the current child and epoch.
1009
- * @param input - The request id to correlate.
1010
- * @returns The correlation bound to the current child and epoch.
1011
- */
1012
- createWireRequestCorrelation: (input) => createWireRequestCorrelation(ledger, input),
1013
- /**
1014
- * Parses a wire request correlation and proves it current.
1015
- * @param value - The untrusted correlation record.
1016
- * @returns The proven-current correlation.
1017
- */
1018
- parseWireRequestCorrelation: (value) => parseWireRequestCorrelationValue(value, childId, epoch, issued),
1019
- /**
1020
- * Correlates issued call identities and bounded text with the current child and epoch.
1021
- * @param input - The identities and text of the call.
1022
- * @returns The correlation bound to the current child and epoch.
1023
- */
1024
- createLogicalToolCallCorrelation: (input) => createLogicalToolCallCorrelation(ledger, input),
1025
- /**
1026
- * Parses a logical tool-call correlation and proves it current.
1027
- * @param value - The untrusted correlation record.
1028
- * @returns The proven-current correlation.
1029
- */
1030
- parseLogicalToolCallCorrelation: (value) => parseLogicalToolCallCorrelationValue(value, childId, epoch, issued)
1031
- });
1032
- }
1033
- /**
1034
- * Builds the operation capability: validation, issuance and decoding of
1035
- * operation identities, kept apart from the identity capability so ordinary
1036
- * owners can be handed only the validator.
1037
- * @param ledger - The ledger the capability reads and records into.
1038
- * @returns A frozen operation authority.
1039
- */
1040
- function createOperationAuthority(ledger) {
1041
- /**
1042
- * Refuses an operation id that is not current and issued here.
1043
- * @param value - The operation id.
1044
- */
1045
- const assertCurrentOperationId = (value) => {
1046
- parseOperation(ledger, value);
1047
- };
1048
- /**
1049
- * Tells whether an operation id is current and issued here, letting
1050
- * only validation refusals answer false.
1051
- * @param value - The operation id.
1052
- * @returns True when it validates.
1053
- */
1054
- const isCurrentOperationId = (value) => {
1055
- try {
1056
- assertCurrentOperationId(value);
1057
- return true;
1058
- } catch (error) {
1059
- if (error instanceof IdentityValidationError) return false;
1060
- throw error;
1061
- }
1062
- };
1063
- return Object.freeze({
1064
- validator: Object.freeze({
1065
- isCurrentOperationId,
1066
- assertCurrentOperationId
1067
- }),
1068
- issuer: Object.freeze({
1069
- /**
1070
- * Mints an operation id in the current epoch.
1071
- * @returns The fresh operation id.
1072
- */
1073
- mintOperationId: () => mintOperation(ledger) }),
1074
- decoder: Object.freeze({
1075
- /**
1076
- * Parses an operation id issued in the current epoch.
1077
- * @param value - The untrusted value.
1078
- * @returns The proven-current operation id.
1079
- */
1080
- parseOperationId: (value) => parseOperation(ledger, value),
1081
- /**
1082
- * Serializes an operation id; a canonical value is its own wire form.
1083
- * @param value - An operation id.
1084
- * @returns The same value, once proven current; it is its own wire form.
1085
- */
1086
- serializeOperationId: (value) => parseOperation(ledger, value)
1087
- })
1088
- });
1089
- }
1090
- /**
1091
- * Composes every capability over one ledger, first recording the ledger's own
1092
- * child and epoch as issued.
1093
- * @param ledger - The ledger to build over.
1094
- * @returns The identity and operation authorities.
1095
- */
1096
- function createAuthority(ledger) {
1097
- issueExisting(ledger, "child", ledger.childId, tokenOf(ledger.childId));
1098
- issueExisting(ledger, "epoch", ledger.epoch, tokenOf(ledger.epoch));
1099
- return {
1100
- identity: Object.freeze({
1101
- validator: createValidator(ledger),
1102
- issuer: createIssuer(ledger),
1103
- decoder: createDecoder(ledger)
1104
- }),
1105
- operation: createOperationAuthority(ledger)
1106
- };
1107
- }
1108
- /** The record prefix of a ledger that no host names: the authorities made without one. */
1109
- const UNNAMED_RECORD_PREFIX = "codex";
1110
- /**
1111
- * Starts a fresh ledger with a newly minted child and epoch.
1112
- * @param recordPrefix - The host's record prefix, `^[a-z][a-z0-9-]{0,15}$`. The child is minted
1113
- * with it, and every identity the ledger spells after that copies the child's.
1114
- * @returns An empty ledger for a new process.
1115
- * @throws {TypeError} When the record prefix is not of its shape.
1116
- */
1117
- function createIdentityLedger(recordPrefix) {
1118
- const childId = mintServerValue(recordPrefix, "child");
1119
- return {
1120
- childId,
1121
- epoch: mintEpochValue(childId),
1122
- issued: /* @__PURE__ */ new Map(),
1123
- rawByIdentity: /* @__PURE__ */ new Map()
1124
- };
1125
- }
1126
- /**
1127
- * Builds authorities over a ledger, by default a fresh one that no host names.
1128
- * @param ledger - The ledger to build over.
1129
- * @returns The identity and operation authorities.
1130
- */
1131
- function createIdentityAuthorities(ledger = createIdentityLedger(UNNAMED_RECORD_PREFIX)) {
1132
- return createAuthority(ledger);
1133
- }
1134
- // src/shared/protocol/realtime-contract.ts
1135
- const BrowserRealtimeIdentitySchemas = {
1136
- session: z.string().brand(),
1137
- correlation: z.string().brand(),
1138
- item: z.string().min(1).max(CANONICAL_ITEM_ID_MAX_LENGTH).refine((value) => !value.includes("\0")).brand()
1139
- };
1140
- /**
1141
- * Narrows an untrusted value to a realtime session id.
1142
- * @param value - The raw value from the wire.
1143
- * @returns The validated session id.
1144
- * @throws {ZodError} when the value is not a well-formed session id.
1145
- */
1146
- function parseRealtimeSessionId(value) {
1147
- return BrowserRealtimeIdentitySchemas.session.parse(value);
1148
- }
1149
- /**
1150
- * Narrows an untrusted value to a realtime correlation id.
1151
- * @param value - The raw value from the wire.
1152
- * @returns The validated correlation id.
1153
- * @throws {ZodError} when the value is not a well-formed correlation id.
1154
- */
1155
- function parseRealtimeCorrelationId(value) {
1156
- return BrowserRealtimeIdentitySchemas.correlation.parse(value);
1157
- }
1158
- /**
1159
- * Narrows an untrusted value to a realtime item id.
1160
- * @param value - The raw value from the wire.
1161
- * @returns The validated item id.
1162
- * @throws {ZodError} when the value is not a well-formed item id.
1163
- */
1164
- function parseRealtimeItemId(value) {
1165
- return BrowserRealtimeIdentitySchemas.item.parse(value);
1166
- }
1167
- export { createIdentityLedger as a, createIdentityAuthorities as i, parseRealtimeItemId as n, logicalToolCallKey as o, parseRealtimeSessionId as r, IdentityValidationError as s, parseRealtimeCorrelationId as t };