@codex-app-sdk/core 0.18.0 → 0.18.1
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/dist/chunks/{prompt-content-BCcHFqCj.js → prompt-content-B8o5tNuN.js} +4 -3
- package/dist/chunks/prompt-content-B8o5tNuN.js.map +1 -0
- package/dist/chunks/{surface-bridge-DThrFjJl.js → surface-bridge-oO22We2G.js} +2 -2
- package/dist/chunks/{surface-bridge-DThrFjJl.js.map → surface-bridge-oO22We2G.js.map} +1 -1
- package/dist/index.js +2 -2
- package/dist/prompt-content.d.ts.map +1 -1
- package/dist/surface-bridge.js +1 -1
- package/dist/surface.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/prompt-content-BCcHFqCj.js.map +0 -1
|
@@ -3,10 +3,11 @@ function e(e) {
|
|
|
3
3
|
return e.map((e) => e.type === "text" ? e.text : e.label).join("");
|
|
4
4
|
}
|
|
5
5
|
function t(e) {
|
|
6
|
-
|
|
6
|
+
let t = (e.kind === "custom" ? e.label : e.value).replace(/[\\[\]]/g, "\\$&"), n = e.kind === "plugin" ? `plugin://${e.id}` : e.id, r = (e) => `%${e.charCodeAt(0).toString(16).toUpperCase()}`, i = e.kind === "custom" ? `mention://${encodeURIComponent(e.groupId ?? "custom")}/${encodeURIComponent(e.id)}?value=${encodeURIComponent(e.value)}` : encodeURI(n).replace(/[?#]/g, r);
|
|
7
|
+
return `[${e.kind === "skill" ? "$" : "@"}${t}](${i.replace(/[()]/g, r)})`;
|
|
7
8
|
}
|
|
8
9
|
function n(n, r) {
|
|
9
|
-
let i = n.map((e) => e.type === "text" ? e.text : e.kind === "
|
|
10
|
+
let i = n.map((e) => e.type === "text" ? e.text : e.kind === "file" ? `@${e.id}` : t(e)).join("");
|
|
10
11
|
if (r === void 0) return i;
|
|
11
12
|
let a = e(n);
|
|
12
13
|
return r.startsWith(i) || !r.startsWith(a) ? r : i + r.slice(a.length);
|
|
@@ -82,4 +83,4 @@ function o(e) {
|
|
|
82
83
|
//#endregion
|
|
83
84
|
export { r as a, i, n, o, e as r, a as t };
|
|
84
85
|
|
|
85
|
-
//# sourceMappingURL=prompt-content-
|
|
86
|
+
//# sourceMappingURL=prompt-content-B8o5tNuN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt-content-B8o5tNuN.js","names":[],"sources":["../../src/prompt-content.ts"],"sourcesContent":["/** Serializable authored content. Mentions exist only after explicit selection. */\nexport type CodexPromptMention = {\n type: 'mention';\n kind: 'skill' | 'plugin' | 'file' | 'custom';\n id: string;\n /** Exact visible chip label, without an added $ or @ prefix. */\n label: string;\n /** Selected catalog name/value; never inferred from surrounding text. */\n value: string;\n groupId?: string;\n};\n\nexport type CodexPromptPart = { type: 'text'; text: string } | CodexPromptMention;\n\nexport function promptContentText(content: readonly CodexPromptPart[]): string {\n return content.map(part => part.type === 'text' ? part.text : part.label).join('');\n}\n\nfunction linkedReference(part: CodexPromptMention): string {\n const name = (part.kind === 'custom' ? part.label : part.value).replace(/[\\\\[\\]]/g, '\\\\$&');\n const target = part.kind === 'plugin' ? `plugin://${part.id}` : part.id;\n const encodeDelimiter = (char: string) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`;\n const path = part.kind === 'custom'\n ? `mention://${encodeURIComponent(part.groupId ?? 'custom')}/${encodeURIComponent(part.id)}?value=${encodeURIComponent(part.value)}`\n : encodeURI(target).replace(/[?#]/g, encodeDelimiter);\n return `[${part.kind === 'skill' ? '$' : '@'}${name}](${path.replace(/[()]/g, encodeDelimiter)})`;\n}\n\n/** Model-facing references. An optional prompt retains context after its authored prefix. */\nexport function promptContentDispatchText(content: readonly CodexPromptPart[], prompt?: string): string {\n const text = content.map(part => part.type === 'text' ? part.text\n : part.kind === 'file' ? `@${part.id}` : linkedReference(part)).join('');\n if (prompt === undefined) return text;\n const visible = promptContentText(content);\n if (prompt.startsWith(text) || !prompt.startsWith(visible)) return prompt;\n return text + prompt.slice(visible.length);\n}\n\n/** Offsets are UTF-16 visible-text offsets, as in JavaScript strings and DOM selections. */\nexport function slicePromptContent(content: readonly CodexPromptPart[], start: number, end = promptContentText(content).length): CodexPromptPart[] {\n let offset = 0;\n return normalizePromptContent(content).flatMap((part): CodexPromptPart[] => {\n const text = part.type === 'text' ? part.text : part.label;\n const from = Math.max(0, start - offset);\n const to = Math.min(text.length, end - offset);\n offset += text.length;\n if (from >= to) return [];\n return part.type === 'mention' && from === 0 && to === text.length\n ? [part] : [{ type: 'text', text: text.slice(from, to) }];\n });\n}\n\nexport function replacePromptContentRange(\n content: readonly CodexPromptPart[], start: number, end: number, replacement: readonly CodexPromptPart[],\n): CodexPromptPart[] {\n return normalizePromptContent([...slicePromptContent(content, 0, start), ...normalizePromptContent(replacement), ...slicePromptContent(content, Math.max(start, end))]);\n}\n\n/** Validate and copy content at transport and persisted-message boundaries. */\nexport function normalizePromptContent(content: unknown): CodexPromptPart[] {\n if (!Array.isArray(content)) throw new Error('Prompt content must be an array');\n const parts = content.map((part: unknown): CodexPromptPart => {\n if (!part || typeof part !== 'object') throw new Error('Invalid prompt content part');\n const value = part as Record<string, unknown>;\n if (value.type === 'text' && typeof value.text === 'string') return { type: 'text', text: value.text };\n if (value.type !== 'mention' || !['skill', 'plugin', 'file', 'custom'].includes(value.kind as string)\n || !['id', 'label', 'value'].every(key => typeof value[key] === 'string' && value[key] !== '')\n || (value.groupId !== undefined && typeof value.groupId !== 'string')) {\n throw new Error('Invalid prompt mention');\n }\n return {\n type: 'mention', kind: value.kind as CodexPromptMention['kind'],\n id: value.id as string, label: value.label as string, value: value.value as string,\n ...(value.groupId === undefined ? {} : { groupId: value.groupId as string }),\n };\n });\n const normalized: CodexPromptPart[] = [];\n for (const part of parts) {\n const previous = normalized.at(-1);\n if (part.type === 'text') {\n if (!part.text) continue;\n if (previous?.type === 'text') { previous.text += part.text; continue; }\n }\n normalized.push(part);\n }\n return normalized;\n}\n\nexport function trimPromptContent(content: readonly CodexPromptPart[]): CodexPromptPart[] {\n const parts = normalizePromptContent(content);\n while (parts[0]?.type === 'text') {\n parts[0].text = parts[0].text.trimStart();\n if (parts[0].text) break;\n parts.shift();\n }\n while (parts.at(-1)?.type === 'text') {\n const last = parts.at(-1) as Extract<CodexPromptPart, { type: 'text' }>;\n last.text = last.text.trimEnd();\n if (last.text) break;\n parts.pop();\n }\n return parts;\n}\n"],"mappings":";AAcA,SAAgB,EAAkB,GAA6C;CAC7E,OAAO,EAAQ,KAAI,MAAQ,EAAK,SAAS,SAAS,EAAK,OAAO,EAAK,KAAK,CAAC,CAAC,KAAK,EAAE;AACnF;AAEA,SAAS,EAAgB,GAAkC;CACzD,IAAM,KAAQ,EAAK,SAAS,WAAW,EAAK,QAAQ,EAAK,MAAA,CAAO,QAAQ,YAAY,MAAM,GACpF,IAAS,EAAK,SAAS,WAAW,YAAY,EAAK,OAAO,EAAK,IAC/D,KAAmB,MAAiB,IAAI,EAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,KACpF,IAAO,EAAK,SAAS,WACvB,aAAa,mBAAmB,EAAK,WAAW,QAAQ,EAAE,GAAG,mBAAmB,EAAK,EAAE,EAAE,SAAS,mBAAmB,EAAK,KAAK,MAC/H,UAAU,CAAM,CAAC,CAAC,QAAQ,SAAS,CAAe;CACtD,OAAO,IAAI,EAAK,SAAS,UAAU,MAAM,MAAM,EAAK,IAAI,EAAK,QAAQ,SAAS,CAAe,EAAE;AACjG;AAGA,SAAgB,EAA0B,GAAqC,GAAyB;CACtG,IAAM,IAAO,EAAQ,KAAI,MAAQ,EAAK,SAAS,SAAS,EAAK,OACzD,EAAK,SAAS,SAAS,IAAI,EAAK,OAAO,EAAgB,CAAI,CAAC,CAAC,CAAC,KAAK,EAAE;CACzE,IAAI,MAAW,KAAA,GAAW,OAAO;CACjC,IAAM,IAAU,EAAkB,CAAO;CAEzC,OADI,EAAO,WAAW,CAAI,KAAK,CAAC,EAAO,WAAW,CAAO,IAAU,IAC5D,I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EAAM,OAAS,EAAE,KACzF,EAAM,YAAY,KAAA,KAAa,OAAO,EAAM,WAAY,UAC5D,MAAU,MAAM,wBAAwB;EAE1C,OAAO;GACL,MAAM;GAAW,MAAM,EAAM;GAC7B,IAAI,EAAM;GAAc,OAAO,EAAM;GAAiB,OAAO,EAAM;GACnE,GAAI,EAAM,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,EAAM,QAAkB;EAC5E;CACF,CAAC,GACK,IAAgC,CAAC;CACvC,KAAK,IAAM,KAAQ,GAAO;EACxB,IAAM,IAAW,EAAW,GAAG,EAAE;EACjC,IAAI,EAAK,SAAS,QAAQ;GACxB,IAAI,CAAC,EAAK,MAAM;GAChB,IAAI,GAAU,SAAS,QAAQ;IAAE,EAAS,QAAQ,EAAK;IAAM;GAAU;EACzE;EACA,EAAW,KAAK,CAAI;CACtB;CACA,OAAO;AACT;AAEA,SAAgB,EAAkB,GAAwD;CACxF,IAAM,IAAQ,EAAuB,CAAO;CAC5C,OAAO,EAAM,EAAE,EAAE,SAAS,WACxB,EAAM,EAAE,CAAC,OAAO,EAAM,EAAE,CAAC,KAAK,UAAU,GACpC,GAAM,EAAE,CAAC,QACb,EAAM,MAAM;CAEd,OAAO,EAAM,GAAG,EAAE,CAAC,EAAE,SAAS,SAAQ;EACpC,IAAM,IAAO,EAAM,GAAG,EAAE;EAExB,IADA,EAAK,OAAO,EAAK,KAAK,QAAQ,GAC1B,EAAK,MAAM;EACf,EAAM,IAAI;CACZ;CACA,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as e } from "./prompt-content-
|
|
1
|
+
import { t as e } from "./prompt-content-B8o5tNuN.js";
|
|
2
2
|
//#region src/surface-state.ts
|
|
3
3
|
var t = 1e3;
|
|
4
4
|
function n(e) {
|
|
@@ -691,4 +691,4 @@ function X(e, t = /* @__PURE__ */ new Set()) {
|
|
|
691
691
|
//#endregion
|
|
692
692
|
export { x as a, m as c, a as d, r as f, p as i, h as l, o as m, v as n, f as o, n as p, g as r, b as s, u as t, i as u };
|
|
693
693
|
|
|
694
|
-
//# sourceMappingURL=surface-bridge-
|
|
694
|
+
//# sourceMappingURL=surface-bridge-oO22We2G.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"surface-bridge-DThrFjJl.js","names":[],"sources":["../../src/surface-state.ts","../../src/surface-bridge.ts"],"sourcesContent":["import type {\n CodexSurfaceSnapshot,\n CodexSurfaceStateChange,\n CodexSurfaceStatePatch,\n CodexVersionedSurfaceSnapshot,\n} from './surface';\n\ntype Awaitable<Value> = Value | Promise<Value>;\ntype KeyedItem = { id: string };\ntype SnapshotRecord = Record<string, unknown>;\n\n/**\n * A state source that can serve a versioned base snapshot and the patches that\n * follow it. `getVersionedSnapshot` resolves null when the other side of a\n * transport cannot stream patches; consumers then use `onStateChange`.\n */\nexport type CodexSurfaceStatePatchSource = {\n getVersionedSnapshot(): Awaitable<CodexVersionedSurfaceSnapshot | null>;\n onStatePatch(listener: (patch: CodexSurfaceStatePatch) => void): () => void;\n};\n\nexport type SubscribeCodexSurfaceStateOptions = {\n /**\n * Whether to notify with the base snapshot once it arrives. Defaults to\n * true. Turn it off when another channel already delivered that state.\n */\n emitInitialSnapshot?: boolean;\n};\n\nexport type CodexSurfaceStateSource =\n | CodexSurfaceStatePatchSource\n | (Partial<CodexSurfaceStatePatchSource> & {\n onStateChange(listener: (snapshot: CodexSurfaceSnapshot) => void): () => void;\n });\n\nexport type CodexSurfaceStateMirrorResult =\n | { status: 'applied'; snapshot: CodexSurfaceSnapshot }\n | { status: 'ignored' }\n | { status: 'resync' };\n\n/** Keeps a local snapshot current from a versioned base and sequential patches. */\nexport type CodexSurfaceStateMirror = {\n readonly snapshot: CodexSurfaceSnapshot | null;\n /** The state version of `snapshot`, or -1 before the first base. */\n readonly version: number;\n /** Adopts an authoritative base, then replays buffered patches that are newer than it. */\n reset(state: CodexVersionedSurfaceSnapshot): CodexSurfaceSnapshot;\n /** Applies the next patch, or buffers it and asks for a new base when the sequence is broken. */\n receive(patch: CodexSurfaceStatePatch): CodexSurfaceStateMirrorResult;\n};\n\nconst maximumBufferedPatches = 1_000;\n\nexport function isCodexSurfaceStatePatchSource(value: unknown): value is CodexSurfaceStatePatchSource {\n const candidate = value as Partial<CodexSurfaceStatePatchSource> | null;\n return typeof candidate?.getVersionedSnapshot === 'function' && typeof candidate.onStatePatch === 'function';\n}\n\n/**\n * Describes how `next` differs from `previous` by reference. Arrays whose items\n * all carry unique string ids become `list` changes that ship only the items\n * whose identity changed; everything else is replaced or deleted per key.\n */\nexport function diffCodexSurfaceState(\n previous: CodexSurfaceSnapshot,\n next: CodexSurfaceSnapshot,\n): CodexSurfaceStateChange[] {\n const before = previous as unknown as SnapshotRecord;\n const after = next as unknown as SnapshotRecord;\n const changes: CodexSurfaceStateChange[] = [];\n for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {\n const snapshotKey = key as keyof CodexSurfaceSnapshot;\n if (before[key] === after[key]) continue;\n if (!(key in after)) {\n changes.push({ type: 'delete', key: snapshotKey });\n continue;\n }\n changes.push(keyedListChange(snapshotKey, before[key], after[key]) ?? {\n type: 'set',\n key: snapshotKey,\n value: after[key],\n });\n }\n return changes;\n}\n\n/** Applies changes to a snapshot without mutating it; unchanged values keep their identity. */\nexport function applyCodexSurfaceStateChanges(\n snapshot: CodexSurfaceSnapshot,\n changes: readonly CodexSurfaceStateChange[],\n): CodexSurfaceSnapshot {\n const current = snapshot as unknown as SnapshotRecord;\n const next: SnapshotRecord = { ...current };\n for (const change of changes) {\n if (change.type === 'delete') {\n delete next[change.key];\n } else if (change.type === 'set') {\n next[change.key] = change.value;\n } else {\n const previous = current[change.key];\n if (!Array.isArray(previous)) throw new Error(`Cannot apply a list patch to non-list state '${change.key}'`);\n const itemsById = new Map((previous as KeyedItem[]).map((item) => [item.id, item]));\n for (const item of change.items) itemsById.set(item.id, item);\n next[change.key] = change.ids.map((id) => {\n const item = itemsById.get(id);\n if (!item) throw new Error(`State patch references unknown '${change.key}' item '${id}'`);\n return item;\n });\n }\n }\n return next as unknown as CodexSurfaceSnapshot;\n}\n\nexport function createCodexSurfaceStateMirror(): CodexSurfaceStateMirror {\n let snapshot: CodexSurfaceSnapshot | null = null;\n let version = -1;\n let stale = true;\n const pending: CodexSurfaceStatePatch[] = [];\n\n const buffer = (patch: CodexSurfaceStatePatch): CodexSurfaceStateMirrorResult => {\n stale = true;\n pending.push(patch);\n if (pending.length > maximumBufferedPatches) pending.shift();\n return { status: 'resync' };\n };\n\n const mirror: CodexSurfaceStateMirror = {\n get snapshot() {\n return snapshot;\n },\n get version() {\n return version;\n },\n reset(state) {\n snapshot = state.snapshot;\n version = state.version;\n stale = false;\n const replay = pending.splice(0).sort((left, right) => left.version - right.version);\n for (const patch of replay) {\n if (mirror.receive(patch).status === 'resync') break;\n }\n return snapshot;\n },\n receive(patch) {\n if (stale || !snapshot) return buffer(patch);\n if (patch.version <= version) return { status: 'ignored' };\n if (patch.version !== version + 1) return buffer(patch);\n try {\n snapshot = applyCodexSurfaceStateChanges(snapshot, patch.changes);\n } catch {\n return buffer(patch);\n }\n version = patch.version;\n return { status: 'applied', snapshot };\n },\n };\n return mirror;\n}\n\n/**\n * Subscribes to surface state, mirroring patches locally when the source\n * supports them. Unchanged messages, turns, and other keyed items keep their\n * object identity between notifications, so UI frameworks can skip them.\n * Falls back to full `onStateChange` snapshots when the source has no patch\n * members or reports that patches are unavailable.\n */\nexport function subscribeCodexSurfaceState(\n source: CodexSurfaceStateSource,\n listener: (snapshot: CodexSurfaceSnapshot) => void,\n options: SubscribeCodexSurfaceStateOptions = {},\n): () => void {\n const subscribeToSnapshots = () => (\n 'onStateChange' in source && typeof source.onStateChange === 'function'\n ? source.onStateChange(listener)\n : () => undefined\n );\n if (!isCodexSurfaceStatePatchSource(source)) return subscribeToSnapshots();\n const mirror = createCodexSurfaceStateMirror();\n let active = true;\n let initialized = false;\n let resyncing = false;\n let unsubscribe: () => void = () => undefined;\n const resync = () => {\n if (resyncing || !active) return;\n resyncing = true;\n void Promise.resolve()\n .then(() => source.getVersionedSnapshot())\n .then((state) => {\n resyncing = false;\n if (!active) return;\n if (!isVersionedSnapshot(state)) {\n if (initialized) return;\n unsubscribe();\n unsubscribe = subscribeToSnapshots();\n return;\n }\n const snapshot = mirror.reset(state);\n // Buffered patches replayed onto the base are changes even when the base itself is not reported.\n const notify = initialized || options.emitInitialSnapshot !== false || mirror.version > state.version;\n initialized = true;\n if (notify) listener(snapshot);\n }, () => {\n resyncing = false;\n });\n };\n unsubscribe = source.onStatePatch((patch) => {\n const result = mirror.receive(patch);\n if (result.status === 'applied') listener(result.snapshot);\n else if (result.status === 'resync') resync();\n });\n resync();\n return () => {\n active = false;\n unsubscribe();\n };\n}\n\nfunction keyedListChange(\n key: keyof CodexSurfaceSnapshot,\n before: unknown,\n after: unknown,\n): CodexSurfaceStateChange | null {\n if (!Array.isArray(before) || !Array.isArray(after)) return null;\n const previousById = new Map<string, unknown>();\n for (const item of before) {\n if (!isKeyedItem(item) || previousById.has(item.id)) return null;\n previousById.set(item.id, item);\n }\n const ids: string[] = [];\n const items: KeyedItem[] = [];\n const seen = new Set<string>();\n for (const item of after) {\n if (!isKeyedItem(item) || seen.has(item.id)) return null;\n seen.add(item.id);\n ids.push(item.id);\n if (previousById.get(item.id) !== item) items.push(item);\n }\n // Replacing the whole list is smaller when nothing can be reused.\n return items.length === after.length ? null : { type: 'list', key, ids, items };\n}\n\nfunction isVersionedSnapshot(value: unknown): value is CodexVersionedSurfaceSnapshot {\n const candidate = value as Partial<CodexVersionedSurfaceSnapshot> | null | undefined;\n return Number.isSafeInteger(candidate?.version)\n && Boolean(candidate?.snapshot)\n && typeof candidate?.snapshot === 'object';\n}\n\nfunction isKeyedItem(value: unknown): value is KeyedItem {\n return Boolean(value) && typeof value === 'object' && typeof (value as { id?: unknown }).id === 'string';\n}\n","import { normalizePromptContent } from './prompt-content';\nimport type {\n CodexConversationEvent,\n CodexConversationHistory,\n CodexConversationHistoryPage,\n CodexConversationPromptHistory,\n CodexConversationSnapshot,\n CodexSurfaceApi,\n CodexSurfaceApprovalDecision,\n CodexSurfaceApprovalScope,\n CodexSurfaceAskUserAnswers,\n CodexSurfaceClientRequestResponse,\n CodexSurfaceJsonValue,\n CodexRendererAttachment,\n CodexRendererSendMessageOptions,\n CodexSurfaceAttachment,\n CodexSurfaceRendererApi,\n CreateCodexRendererConversationOptions,\n ListCodexConversationsOptions,\n ListCodexModelsOptions,\n ReadCodexRateLimitsOptions,\n ConsumeCodexRateLimitResetCreditOptions,\n SendCodexMessageOptions,\n StartCodexReviewOptions,\n StartCodexLiveChatOptions,\n UpdateCodexConversationSettings,\n} from './surface';\n\ntype RequiredRendererApi = Required<CodexSurfaceRendererApi>;\nexport type CodexSurfaceBridgeOperation = Exclude<\n keyof RequiredRendererApi,\n 'onEvent' | 'onStateChange' | 'onStatePatch' | 'getVersionedSnapshot'\n>;\ntype OperationFunction<Name extends CodexSurfaceBridgeOperation> = Extract<\n RequiredRendererApi[Name],\n (...args: never[]) => unknown\n>;\nexport type CodexSurfaceBridgeOperationArguments<Name extends CodexSurfaceBridgeOperation> =\n Parameters<OperationFunction<Name>>;\nexport type CodexSurfaceBridgeOperationResult<Name extends CodexSurfaceBridgeOperation> =\n Awaited<ReturnType<OperationFunction<Name>>>;\ntype Awaitable<Value> = Value | Promise<Value>;\ntype SurfaceOperationFunction<Name extends CodexSurfaceBridgeOperation> = Name extends keyof Required<CodexSurfaceApi>\n ? Extract<Required<CodexSurfaceApi>[Name], (...args: never[]) => unknown>\n : never;\ntype OptionalAccountOperation = 'readRateLimits' | 'readAccountUsage' | 'consumeRateLimitResetCredit';\ntype BridgeOperationMethods = {\n [Name in CodexSurfaceBridgeOperation]: (\n ...args: Parameters<SurfaceOperationFunction<Name>>\n ) => Awaitable<Awaited<ReturnType<SurfaceOperationFunction<Name>>>>;\n};\nexport type CodexSurfaceBridgeTarget = Omit<BridgeOperationMethods, OptionalAccountOperation>\n & Partial<Pick<BridgeOperationMethods, OptionalAccountOperation>>\n & Pick<CodexSurfaceApi, 'onEvent' | 'onStateChange'>;\n\nexport type CodexSurfaceBridgeAttachmentResolver = (\n attachment: CodexRendererAttachment,\n) => Awaitable<CodexSurfaceAttachment>;\n\nexport type CodexSurfaceBridgeInvokeOptions = {\n operationLabel?: string;\n resolveAttachment?: CodexSurfaceBridgeAttachmentResolver;\n};\n\ntype CodexConversationBridgeOperationFunctions = {\n clearGoal(): Awaitable<CodexConversationSnapshot>;\n compactConversation(): Awaitable<CodexConversationSnapshot>;\n continueInterruptedTurn(): Awaitable<CodexConversationSnapshot>;\n deleteTurn(turnId: string): Awaitable<CodexConversationSnapshot>;\n deleteQueuedPrompt(promptId: string): Awaitable<CodexConversationSnapshot>;\n editTurn(turnId: string, content: string, options?: CodexRendererSendMessageOptions): Awaitable<CodexConversationSnapshot>;\n forkTurn(turnId: string): Awaitable<CodexConversationSnapshot>;\n getSnapshot(): Awaitable<CodexConversationSnapshot>;\n interrupt(): Awaitable<CodexConversationSnapshot>;\n loadOlderConversationHistory(): Awaitable<CodexConversationHistoryPage>;\n readConversationHistory(): Awaitable<CodexConversationHistory>;\n readConversationPromptHistory(): Awaitable<CodexConversationPromptHistory>;\n renameConversation(title: string): Awaitable<CodexConversationSnapshot>;\n respondToClientRequest(response: CodexSurfaceClientRequestResponse): Awaitable<CodexConversationSnapshot>;\n resolveApproval(\n approvalId: string,\n decision: CodexSurfaceApprovalDecision,\n scope?: CodexSurfaceApprovalScope,\n ): Awaitable<CodexConversationSnapshot>;\n retryTurn(turnId: string): Awaitable<CodexConversationSnapshot>;\n sendMessage(prompt: string, options?: CodexRendererSendMessageOptions): Awaitable<CodexConversationSnapshot>;\n setGoal(objective: string, tokenBudget?: number | null): Awaitable<CodexConversationSnapshot>;\n startReview(options?: StartCodexReviewOptions): Awaitable<CodexConversationSnapshot>;\n steerMessage(prompt: string, options?: CodexRendererSendMessageOptions): Awaitable<CodexConversationSnapshot>;\n steerQueuedPrompt(promptId: string, prompt?: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n updateConversationSettings(settings: UpdateCodexConversationSettings): Awaitable<CodexConversationSnapshot>;\n updateQueuedPrompt(promptId: string, prompt: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n};\n\nexport const codexConversationBridgeOperations = [\n 'clearGoal', 'compactConversation', 'continueInterruptedTurn', 'deleteTurn', 'deleteQueuedPrompt', 'editTurn',\n 'forkTurn', 'getSnapshot', 'interrupt', 'loadOlderConversationHistory',\n 'readConversationHistory', 'readConversationPromptHistory', 'renameConversation',\n 'respondToClientRequest', 'resolveApproval', 'retryTurn', 'sendMessage', 'setGoal',\n 'startReview', 'steerMessage', 'steerQueuedPrompt', 'updateConversationSettings',\n 'updateQueuedPrompt',\n] as const satisfies readonly (keyof CodexConversationBridgeOperationFunctions)[];\n\nexport type CodexConversationBridgeOperation = typeof codexConversationBridgeOperations[number];\nexport type CodexConversationBridgeOperationArguments<Name extends CodexConversationBridgeOperation> =\n Parameters<CodexConversationBridgeOperationFunctions[Name]>;\nexport type CodexConversationBridgeOperationResult<Name extends CodexConversationBridgeOperation> =\n Awaited<ReturnType<CodexConversationBridgeOperationFunctions[Name]>>;\n\nexport type CodexConversationBridgeHandle = {\n clearGoal(): Awaitable<CodexConversationSnapshot>;\n compact(): Awaitable<CodexConversationSnapshot>;\n continueInterruptedTurn(): Awaitable<CodexConversationSnapshot>;\n deleteTurn(turnId: string): Awaitable<CodexConversationSnapshot>;\n deleteQueuedPrompt(promptId: string): Awaitable<CodexConversationSnapshot>;\n editTurn(turnId: string, content: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n forkTurn(turnId: string): Awaitable<{ snapshot: CodexConversationSnapshot }>;\n getSnapshot(): CodexConversationSnapshot;\n interrupt(): Awaitable<CodexConversationSnapshot>;\n loadOlderHistory(): Awaitable<CodexConversationHistoryPage>;\n onEvent(listener: (event: CodexConversationEvent) => void): () => void;\n onStateChange(listener: (snapshot: CodexConversationSnapshot) => void): () => void;\n readHistory(): Awaitable<CodexConversationHistory>;\n readPromptHistory(): Awaitable<CodexConversationPromptHistory>;\n rename(title: string): Awaitable<CodexConversationSnapshot>;\n respondToClientRequest(response: CodexSurfaceClientRequestResponse): Awaitable<CodexConversationSnapshot>;\n resolveApproval(\n approvalId: string,\n decision: CodexSurfaceApprovalDecision,\n scope?: CodexSurfaceApprovalScope,\n ): Awaitable<CodexConversationSnapshot>;\n retryTurn(turnId: string): Awaitable<CodexConversationSnapshot>;\n sendMessage(prompt: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n setGoal(objective: string, tokenBudget?: number | null): Awaitable<CodexConversationSnapshot>;\n startReview(options?: StartCodexReviewOptions): Awaitable<CodexConversationSnapshot>;\n steerMessage(prompt: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n steerQueuedPrompt(promptId: string, prompt?: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n updateQueuedPrompt(promptId: string, prompt: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n updateSettings(settings: UpdateCodexConversationSettings): Awaitable<CodexConversationSnapshot>;\n};\n\nexport type CodexConversationBridgeTarget = {\n conversation(conversationId: string): CodexConversationBridgeHandle;\n};\n\nexport type CodexConversationBridgeNotification =\n | {\n type: 'snapshot';\n conversationId: string;\n snapshot: CodexConversationSnapshot;\n }\n | {\n type: 'event';\n conversationId: string;\n event: CodexConversationEvent;\n };\n\nconst conversationOperationSet = new Set<string>(codexConversationBridgeOperations);\n\nexport function isCodexConversationBridgeOperation(value: unknown): value is CodexConversationBridgeOperation {\n return typeof value === 'string' && conversationOperationSet.has(value);\n}\n\nexport async function invokeCodexConversationBridgeOperation<Name extends CodexConversationBridgeOperation>(\n target: CodexConversationBridgeTarget,\n conversationId: string,\n operation: Name,\n args: readonly unknown[],\n options: CodexSurfaceBridgeInvokeOptions = {},\n): Promise<CodexConversationBridgeOperationResult<Name>> {\n const id = nonEmptyString(conversationId, 'Conversation id');\n const [minimum, maximum] = conversationArities[operation];\n if (args.length < minimum || args.length > maximum) {\n throw new TypeError(`${options.operationLabel ?? operation} received an invalid number of arguments`);\n }\n const conversation = target.conversation(id);\n const bridgeTarget = conversationOperationTarget(conversation);\n const result = await invokeCodexSurfaceBridgeOperation(bridgeTarget, operation, args, options);\n return result as CodexConversationBridgeOperationResult<Name>;\n}\n\nexport function subscribeCodexConversationBridge(\n target: CodexConversationBridgeTarget,\n conversationId: string,\n listener: (notification: CodexConversationBridgeNotification) => void,\n): () => void {\n const id = nonEmptyString(conversationId, 'Conversation id');\n const conversation = target.conversation(id);\n const emitSnapshot = (snapshot: CodexConversationSnapshot) => {\n if (snapshot.activeConversationId === id) {\n listener({ type: 'snapshot', conversationId: id, snapshot });\n }\n };\n const emitEvent = (event: CodexConversationEvent) => {\n if (event.conversationId === id) listener({ type: 'event', conversationId: id, event });\n };\n const unsubscribeState = conversation.onStateChange(emitSnapshot);\n let unsubscribeEvent: () => void;\n try {\n unsubscribeEvent = conversation.onEvent(emitEvent);\n } catch (error) {\n unsubscribeState();\n throw error;\n }\n return () => {\n unsubscribeEvent();\n unsubscribeState();\n };\n}\n\n/**\n * Emits exactly one targeted snapshot followed by semantic conversation events.\n * Events raised while the initial snapshot is captured are buffered so consumers\n * can always initialize a replica before applying deltas.\n */\nexport function subscribeCodexConversationReplicaBridge(\n target: CodexConversationBridgeTarget,\n conversationId: string,\n listener: (notification: CodexConversationBridgeNotification) => void,\n): () => void {\n const id = nonEmptyString(conversationId, 'Conversation id');\n const conversation = target.conversation(id);\n const pending: CodexConversationEvent[] = [];\n let initialized = false;\n const unsubscribe = conversation.onEvent((event) => {\n if (event.conversationId !== id) return;\n if (!initialized) pending.push(event);\n else listener({ type: 'event', conversationId: id, event });\n });\n try {\n const snapshot = conversation.getSnapshot();\n if (snapshot.activeConversationId !== id) {\n throw new Error(\n `Snapshot belongs to '${snapshot.activeConversationId}', not bridge conversation '${id}'`,\n );\n }\n listener({ type: 'snapshot', conversationId: id, snapshot });\n initialized = true;\n for (const event of pending) listener({ type: 'event', conversationId: id, event });\n pending.length = 0;\n } catch (error) {\n unsubscribe();\n throw error;\n }\n return unsubscribe;\n}\n\nexport const codexSurfaceBridgeOperations = [\n 'archiveConversation', 'cancelLogin', 'clearGoal', 'compactConversation', 'connect',\n 'continueInterruptedTurn', 'createConversation', 'deleteConversation', 'deleteTurn', 'deleteQueuedPrompt',\n 'editTurn', 'forkTurn', 'getSnapshot', 'interrupt', 'listConversations',\n 'listModels', 'loadOlderConversationHistory', 'logout', 'readConversationHistory',\n 'readConversationPromptHistory', 'refreshAccount', 'refreshConversations', 'renameConversation', 'respondToClientRequest',\n 'resolveApproval', 'retryTurn', 'selectConversation', 'sendMessage', 'setGoal',\n 'startChatGptDeviceCodeLogin', 'startChatGptLogin', 'startReview', 'steerMessage', 'steerQueuedPrompt',\n 'unarchiveConversation', 'updateConversationSettings', 'updateQueuedPrompt',\n 'startLiveChat', 'stopLiveChat',\n 'readRateLimits',\n 'readAccountUsage',\n 'consumeRateLimitResetCredit',\n] as const satisfies readonly CodexSurfaceBridgeOperation[];\n\nconst operationSet = new Set<string>(codexSurfaceBridgeOperations);\nexport const codexSurfaceBridgeArities: Readonly<\n Record<CodexSurfaceBridgeOperation, readonly [minimum: number, maximum: number]>\n> = {\n startLiveChat: [2, 2], stopLiveChat: [1, 1],\n archiveConversation: [1, 1], cancelLogin: [0, 1], clearGoal: [0, 0],\n compactConversation: [0, 0], connect: [0, 0], continueInterruptedTurn: [0, 0], createConversation: [0, 1],\n deleteConversation: [1, 1], deleteTurn: [1, 1], deleteQueuedPrompt: [1, 1],\n editTurn: [2, 3], forkTurn: [1, 1], getSnapshot: [0, 0], interrupt: [0, 0],\n listConversations: [0, 1], listModels: [0, 1], loadOlderConversationHistory: [0, 1],\n logout: [0, 0], readConversationHistory: [0, 1], readConversationPromptHistory: [0, 1],\n refreshAccount: [0, 0],\n readRateLimits: [0, 1],\n readAccountUsage: [0, 0],\n consumeRateLimitResetCredit: [1, 1],\n refreshConversations: [0, 0], renameConversation: [1, 1], respondToClientRequest: [1, 1],\n resolveApproval: [2, 3], retryTurn: [1, 1], selectConversation: [1, 1],\n sendMessage: [1, 2], setGoal: [1, 2], startChatGptDeviceCodeLogin: [0, 0],\n startChatGptLogin: [0, 0], startReview: [0, 1],\n steerMessage: [1, 2], steerQueuedPrompt: [1, 3], unarchiveConversation: [1, 1],\n updateConversationSettings: [1, 1], updateQueuedPrompt: [2, 3],\n};\n\nconst conversationArities: Readonly<\n Record<CodexConversationBridgeOperation, readonly [minimum: number, maximum: number]>\n> = {\n clearGoal: [0, 0], compactConversation: [0, 0], continueInterruptedTurn: [0, 0], deleteTurn: [1, 1],\n deleteQueuedPrompt: [1, 1], editTurn: [2, 3], forkTurn: [1, 1], getSnapshot: [0, 0],\n interrupt: [0, 0], loadOlderConversationHistory: [0, 0], readConversationHistory: [0, 0],\n readConversationPromptHistory: [0, 0], renameConversation: [1, 1], respondToClientRequest: [1, 1],\n resolveApproval: [2, 3], retryTurn: [1, 1], sendMessage: [1, 2], setGoal: [1, 2],\n startReview: [0, 1], steerMessage: [1, 2], steerQueuedPrompt: [1, 3],\n updateConversationSettings: [1, 1], updateQueuedPrompt: [2, 3],\n};\n\nexport function isCodexSurfaceBridgeOperation(value: unknown): value is CodexSurfaceBridgeOperation {\n return typeof value === 'string' && operationSet.has(value);\n}\n\nexport async function invokeCodexSurfaceBridgeOperation<Name extends CodexSurfaceBridgeOperation>(\n target: CodexSurfaceBridgeTarget,\n operation: Name,\n args: readonly unknown[],\n options: CodexSurfaceBridgeInvokeOptions = {},\n): Promise<CodexSurfaceBridgeOperationResult<Name>> {\n const [minimum, maximum] = codexSurfaceBridgeArities[operation];\n if (args.length < minimum || args.length > maximum) {\n throw new TypeError(`${options.operationLabel ?? operation} received an invalid number of arguments`);\n }\n const result = await invokeValidated(target, operation, args, options);\n return result as CodexSurfaceBridgeOperationResult<Name>;\n}\n\nfunction conversationOperationTarget(conversation: CodexConversationBridgeHandle): CodexSurfaceBridgeTarget {\n const target: Pick<CodexSurfaceBridgeTarget, CodexConversationBridgeOperation> = {\n clearGoal: () => conversation.clearGoal(),\n compactConversation: () => conversation.compact(),\n continueInterruptedTurn: () => conversation.continueInterruptedTurn(),\n deleteTurn: (turnId) => conversation.deleteTurn(turnId),\n deleteQueuedPrompt: (promptId) => conversation.deleteQueuedPrompt(promptId),\n editTurn: (turnId, content, options) => conversation.editTurn(turnId, content, options),\n forkTurn: async (turnId) => (await conversation.forkTurn(turnId)).snapshot,\n getSnapshot: () => conversation.getSnapshot(),\n interrupt: () => conversation.interrupt(),\n loadOlderConversationHistory: () => conversation.loadOlderHistory(),\n readConversationHistory: () => conversation.readHistory(),\n readConversationPromptHistory: () => conversation.readPromptHistory(),\n renameConversation: (title) => conversation.rename(title),\n respondToClientRequest: (response) => conversation.respondToClientRequest(response),\n resolveApproval: (approvalId, decision, scope) => conversation.resolveApproval(approvalId, decision, scope),\n retryTurn: (turnId) => conversation.retryTurn(turnId),\n sendMessage: (prompt, options) => conversation.sendMessage(prompt, options),\n setGoal: (objective, tokenBudget) => conversation.setGoal(objective, tokenBudget),\n startReview: (options) => conversation.startReview(options),\n steerMessage: (prompt, options) => conversation.steerMessage(prompt, options),\n steerQueuedPrompt: (promptId, prompt, options) => conversation.steerQueuedPrompt(promptId, prompt, options),\n updateConversationSettings: (settings) => conversation.updateSettings(settings),\n updateQueuedPrompt: (promptId, prompt, options) => conversation.updateQueuedPrompt(promptId, prompt, options),\n };\n return target as unknown as CodexSurfaceBridgeTarget;\n}\n\nasync function invokeValidated(\n target: CodexSurfaceBridgeTarget,\n operation: CodexSurfaceBridgeOperation,\n args: readonly unknown[],\n options: CodexSurfaceBridgeInvokeOptions,\n): Promise<unknown> {\n switch (operation) {\n case 'startLiveChat': return target.startLiveChat(\n nonEmptyString(args[0], 'Conversation id'), liveChatOptions(args[1]),\n );\n case 'stopLiveChat': return target.stopLiveChat(nonEmptyString(args[0], 'Conversation id'));\n case 'archiveConversation': return target.archiveConversation(nonEmptyString(args[0], 'Conversation id'));\n case 'cancelLogin': return target.cancelLogin(optionalString(args[0], 'Login id'));\n case 'clearGoal': return target.clearGoal();\n case 'compactConversation': return target.compactConversation();\n case 'connect': return target.connect();\n case 'continueInterruptedTurn': return target.continueInterruptedTurn();\n case 'createConversation': return target.createConversation(conversationOptions(args[0]));\n case 'deleteConversation': return target.deleteConversation(nonEmptyString(args[0], 'Conversation id'));\n case 'deleteTurn': return target.deleteTurn(nonEmptyString(args[0], 'Turn id'));\n case 'deleteQueuedPrompt': return target.deleteQueuedPrompt(nonEmptyString(args[0], 'Queued prompt id'));\n case 'editTurn': return target.editTurn(nonEmptyString(args[0], 'Turn id'), nonEmptyString(args[1], 'Turn content'), await sendOptions(args[2], options.resolveAttachment));\n case 'forkTurn': return target.forkTurn(nonEmptyString(args[0], 'Turn id'));\n case 'getSnapshot': return target.getSnapshot();\n case 'interrupt': return target.interrupt();\n case 'listConversations': return target.listConversations(listConversationOptions(args[0]));\n case 'listModels': return target.listModels(listModelOptions(args[0]));\n case 'loadOlderConversationHistory': return target.loadOlderConversationHistory(optionalString(args[0], 'Conversation id'));\n case 'logout': return target.logout();\n case 'readConversationHistory': return target.readConversationHistory(optionalString(args[0], 'Conversation id'));\n case 'readConversationPromptHistory': return target.readConversationPromptHistory(\n optionalString(args[0], 'Conversation id'),\n );\n case 'refreshAccount': return target.refreshAccount();\n case 'readRateLimits': {\n const options = rateLimitsOptions(args[0]);\n if (!target.readRateLimits) throw new Error('Account rate-limit reads are not available.');\n return target.readRateLimits(options);\n }\n case 'readAccountUsage': {\n if (!target.readAccountUsage) throw new Error('Account usage reads are not available.');\n return target.readAccountUsage();\n }\n case 'consumeRateLimitResetCredit': {\n const options = resetCreditOptions(args[0]);\n if (!target.consumeRateLimitResetCredit) throw new Error('Rate-limit reset credits are not available.');\n return target.consumeRateLimitResetCredit(options);\n }\n case 'refreshConversations': return target.refreshConversations();\n case 'renameConversation': return target.renameConversation(nonEmptyString(args[0], 'Conversation title'));\n case 'respondToClientRequest': return target.respondToClientRequest(clientRequestResponse(args[0]));\n case 'resolveApproval': return target.resolveApproval(\n nonEmptyString(args[0], 'Approval id'), approvalDecision(args[1]), approvalScope(args[2]),\n );\n case 'retryTurn': return target.retryTurn(nonEmptyString(args[0], 'Turn id'));\n case 'selectConversation': return target.selectConversation(nonEmptyString(args[0], 'Conversation id'));\n case 'sendMessage': return target.sendMessage(\n nonEmptyString(args[0], 'Message prompt'),\n await sendOptions(args[1], options.resolveAttachment),\n );\n case 'setGoal': return target.setGoal(nonEmptyString(args[0], 'Goal objective'), tokenBudget(args[1]));\n case 'startChatGptDeviceCodeLogin': return target.startChatGptDeviceCodeLogin();\n case 'startChatGptLogin': return target.startChatGptLogin();\n case 'startReview': return target.startReview(reviewOptions(args[0]));\n case 'steerMessage': return target.steerMessage(\n nonEmptyString(args[0], 'Steer prompt'),\n await sendOptions(args[1], options.resolveAttachment),\n );\n case 'steerQueuedPrompt': return target.steerQueuedPrompt(\n nonEmptyString(args[0], 'Queued prompt id'),\n optionalString(args[1], 'Queued prompt'),\n await sendOptions(args[2], options.resolveAttachment),\n );\n case 'unarchiveConversation': return target.unarchiveConversation(nonEmptyString(args[0], 'Conversation id'));\n case 'updateConversationSettings': return target.updateConversationSettings(settings(args[0]));\n case 'updateQueuedPrompt': return target.updateQueuedPrompt(\n nonEmptyString(args[0], 'Queued prompt id'), nonEmptyString(args[1], 'Queued prompt'),\n await sendOptions(args[2], options.resolveAttachment),\n );\n }\n}\n\nfunction liveChatOptions(value: unknown): StartCodexLiveChatOptions {\n const record = plainObject(value, 'Live chat options');\n onlyKeys(record, ['sdp', 'version', 'voice', 'model', 'prompt', 'includeStartupContext', 'flushTranscriptTailOnSessionEnd'], 'Live chat options');\n const result: StartCodexLiveChatOptions = { sdp: nonEmptyString(record.sdp, 'SDP offer') };\n if (record.version !== undefined) {\n if (record.version !== 'v1' && record.version !== 'v2' && record.version !== 'v3') throw new TypeError('Invalid realtime version');\n result.version = record.version;\n }\n for (const key of ['voice', 'model'] as const) {\n if (record[key] !== undefined) result[key] = nonEmptyString(record[key], key);\n }\n if (record.prompt !== undefined) {\n if (record.prompt !== null && typeof record.prompt !== 'string') throw new TypeError('Prompt must be a string or null');\n result.prompt = record.prompt;\n }\n for (const key of ['includeStartupContext', 'flushTranscriptTailOnSessionEnd'] as const) {\n if (record[key] !== undefined) {\n if (typeof record[key] !== 'boolean') throw new TypeError(`${key} must be a boolean`);\n result[key] = record[key];\n }\n }\n return result;\n}\n\nfunction conversationOptions(value: unknown): CreateCodexRendererConversationOptions | undefined {\n if (value === undefined) return undefined;\n const record = plainObject(value, 'Conversation options');\n onlyKeys(record, ['model', 'reasoningEffort', 'serviceTier', 'approvalPreset'], 'Conversation options');\n return {\n ...(record.model === undefined ? {} : { model: nonEmptyString(record.model, 'Conversation model') }),\n ...(record.reasoningEffort === undefined ? {} : { reasoningEffort: nonEmptyString(record.reasoningEffort, 'Conversation reasoning effort') }),\n ...(record.serviceTier === undefined ? {} : { serviceTier: nullableString(record.serviceTier, 'Conversation service tier') }),\n ...(record.approvalPreset === undefined ? {} : { approvalPreset: approvalPreset(record.approvalPreset) }),\n };\n}\n\nfunction listConversationOptions(value: unknown): ListCodexConversationsOptions | undefined {\n if (value === undefined) return undefined;\n const record = plainObject(value, 'Conversation list options');\n onlyKeys(record, ['archived', 'cwd', 'limit', 'searchTerm'], 'Conversation list options');\n if (record.archived !== undefined && typeof record.archived !== 'boolean') {\n throw new TypeError('Conversation list archived flag must be a boolean');\n }\n if (record.limit !== undefined && (!Number.isInteger(record.limit) || (record.limit as number) < 0)) {\n throw new TypeError('Conversation list limit must be a non-negative integer');\n }\n const cwd = record.cwd === undefined ? undefined : Array.isArray(record.cwd)\n ? record.cwd.map((entry) => nonEmptyString(entry, 'Conversation list cwd'))\n : nonEmptyString(record.cwd, 'Conversation list cwd');\n return {\n ...(record.archived === undefined ? {} : { archived: record.archived }),\n ...(cwd === undefined ? {} : { cwd }),\n ...(record.limit === undefined ? {} : { limit: record.limit as number }),\n ...(record.searchTerm === undefined ? {} : { searchTerm: nonEmptyString(record.searchTerm, 'Conversation list search term') }),\n };\n}\n\nfunction rateLimitsOptions(value: unknown): ReadCodexRateLimitsOptions | undefined {\n if (value === undefined) return undefined;\n const record = plainObject(value, 'Rate-limit read options');\n onlyKeys(record, ['excludeResetCreditDetails'], 'Rate-limit read options');\n return record.excludeResetCreditDetails === undefined ? {} : {\n excludeResetCreditDetails: booleanValue(record.excludeResetCreditDetails, 'Exclude reset credit details'),\n };\n}\n\nfunction resetCreditOptions(value: unknown): ConsumeCodexRateLimitResetCreditOptions {\n const record = plainObject(value, 'Reset-credit options');\n onlyKeys(record, ['idempotencyKey', 'creditId'], 'Reset-credit options');\n return {\n idempotencyKey: nonEmptyString(record.idempotencyKey, 'Reset-credit idempotency key'),\n ...(record.creditId === undefined ? {} : { creditId: nonEmptyString(record.creditId, 'Reset credit id') }),\n };\n}\n\nfunction listModelOptions(value: unknown): ListCodexModelsOptions | undefined {\n if (value === undefined) return undefined;\n const record = plainObject(value, 'Model list options');\n onlyKeys(record, ['includeHidden', 'forceReload'], 'Model list options');\n return {\n ...(record.includeHidden === undefined ? {} : { includeHidden: booleanValue(record.includeHidden, 'Model list includeHidden') }),\n ...(record.forceReload === undefined ? {} : { forceReload: booleanValue(record.forceReload, 'Model list forceReload') }),\n };\n}\n\nfunction settings(value: unknown): UpdateCodexConversationSettings {\n const record = plainObject(value, 'Conversation settings');\n onlyKeys(record, ['modelId', 'reasoningEffort', 'serviceTier', 'approvalPreset', 'planMode'], 'Conversation settings');\n return {\n ...(record.modelId === undefined ? {} : { modelId: nonEmptyString(record.modelId, 'Conversation model id') }),\n ...(record.reasoningEffort === undefined ? {} : { reasoningEffort: nonEmptyString(record.reasoningEffort, 'Conversation reasoning effort') }),\n ...(record.serviceTier === undefined ? {} : { serviceTier: nullableString(record.serviceTier, 'Conversation service tier') }),\n ...(record.approvalPreset === undefined ? {} : { approvalPreset: approvalPreset(record.approvalPreset) }),\n ...(record.planMode === undefined ? {} : { planMode: booleanValue(record.planMode, 'Conversation plan mode') }),\n };\n}\n\nfunction clientRequestResponse(value: unknown): CodexSurfaceClientRequestResponse {\n const record = plainObject(value, 'Client request response');\n onlyKeys(record, ['id', 'payload'], 'Client request response');\n const id = nonEmptyString(record.id, 'Client request id');\n if (record.payload === undefined) return { id };\n const payload = plainObject(record.payload, 'Client request response payload');\n onlyKeys(payload, ['answers', 'cancelled', 'decision'], 'Client request response payload');\n const decision = payload.decision;\n const validDecisions = [null, 'allow', 'allow_conversation', 'always_allow', 'deny'];\n if (decision !== undefined && !validDecisions.includes(decision as string | null)) {\n throw new TypeError('Client request decision is invalid');\n }\n const answers = payload.answers === undefined ? undefined : askUserAnswers(payload.answers);\n return {\n id,\n payload: {\n ...(answers === undefined ? {} : { answers }),\n ...(payload.cancelled === undefined ? {} : { cancelled: booleanValue(payload.cancelled, 'Client request cancelled flag') }),\n ...(decision === undefined ? {} : { decision: decision as NonNullable<CodexSurfaceClientRequestResponse['payload']>['decision'] }),\n },\n };\n}\n\nfunction askUserAnswers(value: unknown): CodexSurfaceAskUserAnswers {\n const record = plainObject(value, 'Client request answers');\n const answers: CodexSurfaceAskUserAnswers = {};\n for (const [questionId, rawAnswer] of Object.entries(record)) {\n if (!questionId.trim()) throw new TypeError('Client request question id must be non-empty');\n const answer = plainObject(rawAnswer, 'Client request answer');\n onlyKeys(answer, ['answers'], 'Client request answer');\n if (!Array.isArray(answer.answers) || !answer.answers.every((item) => typeof item === 'string')) {\n throw new TypeError('Client request answer values must be an array of strings');\n }\n answers[questionId] = { answers: [...answer.answers] };\n }\n return answers;\n}\n\nasync function sendOptions(\n value: unknown,\n resolveAttachment: CodexSurfaceBridgeAttachmentResolver | undefined,\n): Promise<SendCodexMessageOptions | undefined> {\n if (value === undefined) return undefined;\n const record = plainObject(value, 'Message options');\n onlyKeys(record, ['content', 'inputMethod', 'attachments', 'model', 'reasoningEffort', 'serviceTier', 'planMode', 'skills', 'outputSchema'], 'Message options');\n const attachments = record.attachments === undefined\n ? undefined\n : await attachmentInputs(record.attachments, resolveAttachment);\n const skills = record.skills === undefined ? undefined : skillInputs(record.skills);\n const inputMethod = record.inputMethod;\n if (inputMethod !== undefined && inputMethod !== 'typed' && inputMethod !== 'dictated') {\n throw new TypeError('Message input method must be typed or dictated');\n }\n if (record.outputSchema !== undefined && !isJsonValue(record.outputSchema)) {\n throw new TypeError('Message output schema must be JSON-serializable');\n }\n return {\n ...(record.content === undefined ? {} : { content: normalizePromptContent(record.content) }),\n ...(inputMethod === undefined ? {} : { inputMethod }),\n ...(attachments === undefined ? {} : { attachments }),\n ...(record.model === undefined ? {} : { model: nonEmptyString(record.model, 'Message model') }),\n ...(record.reasoningEffort === undefined ? {} : { reasoningEffort: nonEmptyString(record.reasoningEffort, 'Message reasoning effort') }),\n ...(record.serviceTier === undefined ? {} : { serviceTier: nullableString(record.serviceTier, 'Message service tier') }),\n ...(record.planMode === undefined ? {} : { planMode: booleanValue(record.planMode, 'Message plan mode') }),\n ...(skills === undefined ? {} : { skills }),\n ...(record.outputSchema === undefined ? {} : { outputSchema: record.outputSchema }),\n };\n}\n\nasync function attachmentInputs(\n value: unknown,\n resolveAttachment: CodexSurfaceBridgeAttachmentResolver | undefined,\n): Promise<NonNullable<SendCodexMessageOptions['attachments']>> {\n if (!Array.isArray(value)) throw new TypeError('Message attachments must be an array');\n if (value.length > 0 && !resolveAttachment) {\n throw new TypeError('Message attachment references are not supported by this host');\n }\n return Promise.all(value.map(async (rawAttachment) => {\n const attachment = plainObject(rawAttachment, 'Message attachment');\n if (attachment.type !== 'image' && attachment.type !== 'file') {\n throw new TypeError('Message attachment type is invalid');\n }\n const image = attachment.type === 'image';\n onlyKeys(\n attachment,\n image ? ['type', 'reference', 'detail'] : ['type', 'reference'],\n 'Message attachment',\n );\n if (image && attachment.detail !== undefined && !['auto', 'low', 'high', 'original'].includes(String(attachment.detail))) {\n throw new TypeError('Message image detail is invalid');\n }\n const rendererAttachment: CodexRendererAttachment = image ? {\n type: 'image' as const,\n reference: nonEmptyString(attachment.reference, 'Message attachment reference'),\n ...(attachment.detail === undefined ? {} : { detail: attachment.detail as 'auto' | 'low' | 'high' | 'original' }),\n } : {\n type: 'file' as const,\n reference: nonEmptyString(attachment.reference, 'Message attachment reference'),\n };\n const resolved = await resolveAttachment!(rendererAttachment);\n return resolvedAttachment(resolved, rendererAttachment);\n }));\n}\n\nfunction resolvedAttachment(\n value: CodexSurfaceAttachment,\n source: CodexRendererAttachment,\n): CodexSurfaceAttachment {\n const attachment = plainObject(value, 'Resolved message attachment');\n if (attachment.type !== source.type) throw new TypeError('Resolved message attachment type does not match');\n const common = {\n path: nonEmptyString(attachment.path, 'Resolved message attachment path'),\n ...(attachment.name === undefined ? {} : { name: displayString(attachment.name, 'Resolved message attachment name') }),\n ...(attachment.mimeType === undefined ? {} : { mimeType: displayString(attachment.mimeType, 'Resolved message attachment MIME type') }),\n };\n return source.type === 'image' ? {\n type: 'image',\n ...common,\n ...(source.detail === undefined ? {} : { detail: source.detail }),\n ...(attachment.previewUrl === undefined\n ? {}\n : { previewUrl: imagePreviewUrl(attachment.previewUrl) }),\n } : { type: 'file', ...common };\n}\n\nfunction skillInputs(value: unknown): NonNullable<SendCodexMessageOptions['skills']> {\n if (!Array.isArray(value)) throw new TypeError('Message skills must be an array');\n return value.map((rawSkill) => {\n const skill = plainObject(rawSkill, 'Message skill');\n onlyKeys(skill, ['name', 'path'], 'Message skill');\n return { name: nonEmptyString(skill.name, 'Message skill name'), path: nonEmptyString(skill.path, 'Message skill path') };\n });\n}\n\nfunction reviewOptions(value: unknown): StartCodexReviewOptions | undefined {\n if (value === undefined) return undefined;\n const record = plainObject(value, 'Review options');\n onlyKeys(record, ['target'], 'Review options');\n if (record.target === undefined) return {};\n const target = plainObject(record.target, 'Review target');\n if (target.type === 'uncommittedChanges') {\n onlyKeys(target, ['type'], 'Review target');\n return { target: { type: 'uncommittedChanges' } };\n }\n if (target.type === 'baseBranch') {\n onlyKeys(target, ['type', 'branch'], 'Review target');\n return { target: { type: 'baseBranch', branch: nonEmptyString(target.branch, 'Review branch') } };\n }\n if (target.type === 'commit') {\n onlyKeys(target, ['type', 'sha', 'title'], 'Review target');\n if (target.title !== undefined && target.title !== null && typeof target.title !== 'string') {\n throw new TypeError('Review commit title must be a string or null');\n }\n return { target: { type: 'commit', sha: nonEmptyString(target.sha, 'Review commit SHA'), ...(target.title === undefined ? {} : { title: target.title }) } };\n }\n if (target.type === 'custom') {\n onlyKeys(target, ['type', 'instructions'], 'Review target');\n return { target: { type: 'custom', instructions: nonEmptyString(target.instructions, 'Review instructions') } };\n }\n throw new TypeError('Review target type is invalid');\n}\n\nfunction plainObject(value: unknown, label: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new TypeError(`${label} must be an object`);\n const prototype = Object.getPrototypeOf(value) as object | null;\n if (prototype !== Object.prototype && prototype !== null) throw new TypeError(`${label} must be a plain object`);\n if (Reflect.ownKeys(value).some((key) => typeof key === 'symbol')) throw new TypeError(`${label} must not contain symbol properties`);\n return value as Record<string, unknown>;\n}\n\nfunction onlyKeys(record: Record<string, unknown>, keys: readonly string[], label: string): void {\n const allowed = new Set(keys);\n const unknownKey = Object.getOwnPropertyNames(record).find((key) => !allowed.has(key));\n if (unknownKey) throw new TypeError(`${label} contains unsupported property \"${unknownKey}\"`);\n}\n\nfunction nonEmptyString(value: unknown, label: string): string {\n if (typeof value !== 'string' || !value.trim()) throw new TypeError(`${label} must be a non-empty string`);\n return value;\n}\nfunction optionalString(value: unknown, label: string): string | undefined {\n return value === undefined ? undefined : nonEmptyString(value, label);\n}\nfunction nullableString(value: unknown, label: string): string | null {\n return value === null ? null : nonEmptyString(value, label);\n}\nfunction booleanValue(value: unknown, label: string): boolean {\n if (typeof value !== 'boolean') throw new TypeError(`${label} must be a boolean`);\n return value;\n}\nfunction approvalDecision(value: unknown): CodexSurfaceApprovalDecision {\n if (value !== 'approve' && value !== 'deny') throw new TypeError('Approval decision is invalid');\n return value;\n}\nfunction approvalScope(value: unknown): CodexSurfaceApprovalScope | undefined {\n if (value === undefined) return undefined;\n if (value !== 'once' && value !== 'session') throw new TypeError('Approval scope is invalid');\n return value;\n}\nfunction approvalPreset(value: unknown): UpdateCodexConversationSettings['approvalPreset'] {\n if (!['ask-for-approval', 'approve-for-me', 'full-access'].includes(String(value))) {\n throw new TypeError('Conversation approval preset is invalid');\n }\n return value as UpdateCodexConversationSettings['approvalPreset'];\n}\nfunction tokenBudget(value: unknown): number | null | undefined {\n if (value === undefined || value === null) return value;\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n throw new TypeError('Goal token budget must be a positive number or null');\n }\n return value;\n}\nfunction displayString(value: unknown, label: string): string {\n const result = nonEmptyString(value, label);\n if (result.length > 1_024) throw new RangeError(`${label} is too long`);\n return result;\n}\nfunction imagePreviewUrl(value: unknown): string {\n if (typeof value !== 'string'\n || value.length > 16 * 1024 * 1024\n || !/^data:image\\/(?:avif|bmp|gif|heic|heif|jpe?g|png|webp);base64,[a-z\\d+/]+={0,2}$/i.test(value)) {\n throw new TypeError('Resolved message attachment preview must be a bounded image data URL');\n }\n return value;\n}\nfunction isJsonValue(value: unknown, seen = new Set<object>()): value is CodexSurfaceJsonValue {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;\n if (typeof value === 'number') return Number.isFinite(value);\n if (typeof value !== 'object' || seen.has(value) || Reflect.ownKeys(value).some((key) => typeof key === 'symbol')) return false;\n if (Array.isArray(value)) {\n const keys = Object.keys(value);\n if (keys.length !== value.length || keys.some((key) => !/^(0|[1-9]\\d*)$/.test(key) || Number(key) >= value.length)) return false;\n } else {\n const prototype = Object.getPrototypeOf(value) as object | null;\n if ((prototype !== Object.prototype && prototype !== null) || Object.keys(value).length !== Object.getOwnPropertyNames(value).length) return false;\n }\n seen.add(value);\n const valid = Array.isArray(value)\n ? value.every((item) => isJsonValue(item, seen))\n : Object.values(value as Record<string, unknown>).every((item) => isJsonValue(item, seen));\n seen.delete(value);\n return valid;\n}\n\nexport {\n applyCodexSurfaceStateChanges,\n createCodexSurfaceStateMirror,\n diffCodexSurfaceState,\n isCodexSurfaceStatePatchSource,\n subscribeCodexSurfaceState,\n type CodexSurfaceStateMirror,\n type CodexSurfaceStateMirrorResult,\n type CodexSurfaceStatePatchSource,\n type CodexSurfaceStateSource,\n type SubscribeCodexSurfaceStateOptions,\n} from './surface-state';\n"],"mappings":";;AAmDA,IAAM,IAAyB;AAE/B,SAAgB,EAA+B,GAAuD;CACpG,IAAM,IAAY;CAClB,OAAO,OAAO,GAAW,wBAAyB,cAAc,OAAO,EAAU,gBAAiB;AACpG;AAOA,SAAgB,EACd,GACA,GAC2B;CAC3B,IAAM,IAAS,GACT,IAAQ,GACR,IAAqC,CAAC;CAC5C,KAAK,IAAM,qBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,CAAM,GAAG,GAAG,OAAO,KAAK,CAAK,CAAC,CAAC,GAAG;EAC1E,IAAM,IAAc;EAChB,MAAO,OAAS,EAAM,IAC1B;OAAI,EAAE,KAAO,IAAQ;IACnB,EAAQ,KAAK;KAAE,MAAM;KAAU,KAAK;IAAY,CAAC;IACjD;GACF;GACA,EAAQ,KAAK,EAAgB,GAAa,EAAO,IAAM,EAAM,EAAI,KAAK;IACpE,MAAM;IACN,KAAK;IACL,OAAO,EAAM;GACf,CAAC;EALD;CAMF;CACA,OAAO;AACT;AAGA,SAAgB,EACd,GACA,GACsB;CACtB,IAAM,IAAU,GACV,IAAuB,EAAE,GAAG,EAAQ;CAC1C,KAAK,IAAM,KAAU,GACnB,IAAI,EAAO,SAAS,UAClB,OAAO,EAAK,EAAO;MACd,IAAI,EAAO,SAAS,OACzB,EAAK,EAAO,OAAO,EAAO;MACrB;EACL,IAAM,IAAW,EAAQ,EAAO;EAChC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AAO,oBAAoB,CAAK,CAAC,CAAC,QAAQ,OAAO;CAC/I;CACA,EAAK,IAAI,CAAK;CACd,IAAM,IAAQ,MAAM,QAAQ,CAAK,IAC7B,EAAM,OAAO,MAAS,EAAY,GAAM,CAAI,CAAC,IAC7C,OAAO,OAAO,CAAgC,CAAC,CAAC,OAAO,MAAS,EAAY,GAAM,CAAI,CAAC;CAE3F,OADA,EAAK,OAAO,CAAK,GACV;AACT"}
|
|
1
|
+
{"version":3,"file":"surface-bridge-oO22We2G.js","names":[],"sources":["../../src/surface-state.ts","../../src/surface-bridge.ts"],"sourcesContent":["import type {\n CodexSurfaceSnapshot,\n CodexSurfaceStateChange,\n CodexSurfaceStatePatch,\n CodexVersionedSurfaceSnapshot,\n} from './surface';\n\ntype Awaitable<Value> = Value | Promise<Value>;\ntype KeyedItem = { id: string };\ntype SnapshotRecord = Record<string, unknown>;\n\n/**\n * A state source that can serve a versioned base snapshot and the patches that\n * follow it. `getVersionedSnapshot` resolves null when the other side of a\n * transport cannot stream patches; consumers then use `onStateChange`.\n */\nexport type CodexSurfaceStatePatchSource = {\n getVersionedSnapshot(): Awaitable<CodexVersionedSurfaceSnapshot | null>;\n onStatePatch(listener: (patch: CodexSurfaceStatePatch) => void): () => void;\n};\n\nexport type SubscribeCodexSurfaceStateOptions = {\n /**\n * Whether to notify with the base snapshot once it arrives. Defaults to\n * true. Turn it off when another channel already delivered that state.\n */\n emitInitialSnapshot?: boolean;\n};\n\nexport type CodexSurfaceStateSource =\n | CodexSurfaceStatePatchSource\n | (Partial<CodexSurfaceStatePatchSource> & {\n onStateChange(listener: (snapshot: CodexSurfaceSnapshot) => void): () => void;\n });\n\nexport type CodexSurfaceStateMirrorResult =\n | { status: 'applied'; snapshot: CodexSurfaceSnapshot }\n | { status: 'ignored' }\n | { status: 'resync' };\n\n/** Keeps a local snapshot current from a versioned base and sequential patches. */\nexport type CodexSurfaceStateMirror = {\n readonly snapshot: CodexSurfaceSnapshot | null;\n /** The state version of `snapshot`, or -1 before the first base. */\n readonly version: number;\n /** Adopts an authoritative base, then replays buffered patches that are newer than it. */\n reset(state: CodexVersionedSurfaceSnapshot): CodexSurfaceSnapshot;\n /** Applies the next patch, or buffers it and asks for a new base when the sequence is broken. */\n receive(patch: CodexSurfaceStatePatch): CodexSurfaceStateMirrorResult;\n};\n\nconst maximumBufferedPatches = 1_000;\n\nexport function isCodexSurfaceStatePatchSource(value: unknown): value is CodexSurfaceStatePatchSource {\n const candidate = value as Partial<CodexSurfaceStatePatchSource> | null;\n return typeof candidate?.getVersionedSnapshot === 'function' && typeof candidate.onStatePatch === 'function';\n}\n\n/**\n * Describes how `next` differs from `previous` by reference. Arrays whose items\n * all carry unique string ids become `list` changes that ship only the items\n * whose identity changed; everything else is replaced or deleted per key.\n */\nexport function diffCodexSurfaceState(\n previous: CodexSurfaceSnapshot,\n next: CodexSurfaceSnapshot,\n): CodexSurfaceStateChange[] {\n const before = previous as unknown as SnapshotRecord;\n const after = next as unknown as SnapshotRecord;\n const changes: CodexSurfaceStateChange[] = [];\n for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {\n const snapshotKey = key as keyof CodexSurfaceSnapshot;\n if (before[key] === after[key]) continue;\n if (!(key in after)) {\n changes.push({ type: 'delete', key: snapshotKey });\n continue;\n }\n changes.push(keyedListChange(snapshotKey, before[key], after[key]) ?? {\n type: 'set',\n key: snapshotKey,\n value: after[key],\n });\n }\n return changes;\n}\n\n/** Applies changes to a snapshot without mutating it; unchanged values keep their identity. */\nexport function applyCodexSurfaceStateChanges(\n snapshot: CodexSurfaceSnapshot,\n changes: readonly CodexSurfaceStateChange[],\n): CodexSurfaceSnapshot {\n const current = snapshot as unknown as SnapshotRecord;\n const next: SnapshotRecord = { ...current };\n for (const change of changes) {\n if (change.type === 'delete') {\n delete next[change.key];\n } else if (change.type === 'set') {\n next[change.key] = change.value;\n } else {\n const previous = current[change.key];\n if (!Array.isArray(previous)) throw new Error(`Cannot apply a list patch to non-list state '${change.key}'`);\n const itemsById = new Map((previous as KeyedItem[]).map((item) => [item.id, item]));\n for (const item of change.items) itemsById.set(item.id, item);\n next[change.key] = change.ids.map((id) => {\n const item = itemsById.get(id);\n if (!item) throw new Error(`State patch references unknown '${change.key}' item '${id}'`);\n return item;\n });\n }\n }\n return next as unknown as CodexSurfaceSnapshot;\n}\n\nexport function createCodexSurfaceStateMirror(): CodexSurfaceStateMirror {\n let snapshot: CodexSurfaceSnapshot | null = null;\n let version = -1;\n let stale = true;\n const pending: CodexSurfaceStatePatch[] = [];\n\n const buffer = (patch: CodexSurfaceStatePatch): CodexSurfaceStateMirrorResult => {\n stale = true;\n pending.push(patch);\n if (pending.length > maximumBufferedPatches) pending.shift();\n return { status: 'resync' };\n };\n\n const mirror: CodexSurfaceStateMirror = {\n get snapshot() {\n return snapshot;\n },\n get version() {\n return version;\n },\n reset(state) {\n snapshot = state.snapshot;\n version = state.version;\n stale = false;\n const replay = pending.splice(0).sort((left, right) => left.version - right.version);\n for (const patch of replay) {\n if (mirror.receive(patch).status === 'resync') break;\n }\n return snapshot;\n },\n receive(patch) {\n if (stale || !snapshot) return buffer(patch);\n if (patch.version <= version) return { status: 'ignored' };\n if (patch.version !== version + 1) return buffer(patch);\n try {\n snapshot = applyCodexSurfaceStateChanges(snapshot, patch.changes);\n } catch {\n return buffer(patch);\n }\n version = patch.version;\n return { status: 'applied', snapshot };\n },\n };\n return mirror;\n}\n\n/**\n * Subscribes to surface state, mirroring patches locally when the source\n * supports them. Unchanged messages, turns, and other keyed items keep their\n * object identity between notifications, so UI frameworks can skip them.\n * Falls back to full `onStateChange` snapshots when the source has no patch\n * members or reports that patches are unavailable.\n */\nexport function subscribeCodexSurfaceState(\n source: CodexSurfaceStateSource,\n listener: (snapshot: CodexSurfaceSnapshot) => void,\n options: SubscribeCodexSurfaceStateOptions = {},\n): () => void {\n const subscribeToSnapshots = () => (\n 'onStateChange' in source && typeof source.onStateChange === 'function'\n ? source.onStateChange(listener)\n : () => undefined\n );\n if (!isCodexSurfaceStatePatchSource(source)) return subscribeToSnapshots();\n const mirror = createCodexSurfaceStateMirror();\n let active = true;\n let initialized = false;\n let resyncing = false;\n let unsubscribe: () => void = () => undefined;\n const resync = () => {\n if (resyncing || !active) return;\n resyncing = true;\n void Promise.resolve()\n .then(() => source.getVersionedSnapshot())\n .then((state) => {\n resyncing = false;\n if (!active) return;\n if (!isVersionedSnapshot(state)) {\n if (initialized) return;\n unsubscribe();\n unsubscribe = subscribeToSnapshots();\n return;\n }\n const snapshot = mirror.reset(state);\n // Buffered patches replayed onto the base are changes even when the base itself is not reported.\n const notify = initialized || options.emitInitialSnapshot !== false || mirror.version > state.version;\n initialized = true;\n if (notify) listener(snapshot);\n }, () => {\n resyncing = false;\n });\n };\n unsubscribe = source.onStatePatch((patch) => {\n const result = mirror.receive(patch);\n if (result.status === 'applied') listener(result.snapshot);\n else if (result.status === 'resync') resync();\n });\n resync();\n return () => {\n active = false;\n unsubscribe();\n };\n}\n\nfunction keyedListChange(\n key: keyof CodexSurfaceSnapshot,\n before: unknown,\n after: unknown,\n): CodexSurfaceStateChange | null {\n if (!Array.isArray(before) || !Array.isArray(after)) return null;\n const previousById = new Map<string, unknown>();\n for (const item of before) {\n if (!isKeyedItem(item) || previousById.has(item.id)) return null;\n previousById.set(item.id, item);\n }\n const ids: string[] = [];\n const items: KeyedItem[] = [];\n const seen = new Set<string>();\n for (const item of after) {\n if (!isKeyedItem(item) || seen.has(item.id)) return null;\n seen.add(item.id);\n ids.push(item.id);\n if (previousById.get(item.id) !== item) items.push(item);\n }\n // Replacing the whole list is smaller when nothing can be reused.\n return items.length === after.length ? null : { type: 'list', key, ids, items };\n}\n\nfunction isVersionedSnapshot(value: unknown): value is CodexVersionedSurfaceSnapshot {\n const candidate = value as Partial<CodexVersionedSurfaceSnapshot> | null | undefined;\n return Number.isSafeInteger(candidate?.version)\n && Boolean(candidate?.snapshot)\n && typeof candidate?.snapshot === 'object';\n}\n\nfunction isKeyedItem(value: unknown): value is KeyedItem {\n return Boolean(value) && typeof value === 'object' && typeof (value as { id?: unknown }).id === 'string';\n}\n","import { normalizePromptContent } from './prompt-content';\nimport type {\n CodexConversationEvent,\n CodexConversationHistory,\n CodexConversationHistoryPage,\n CodexConversationPromptHistory,\n CodexConversationSnapshot,\n CodexSurfaceApi,\n CodexSurfaceApprovalDecision,\n CodexSurfaceApprovalScope,\n CodexSurfaceAskUserAnswers,\n CodexSurfaceClientRequestResponse,\n CodexSurfaceJsonValue,\n CodexRendererAttachment,\n CodexRendererSendMessageOptions,\n CodexSurfaceAttachment,\n CodexSurfaceRendererApi,\n CreateCodexRendererConversationOptions,\n ListCodexConversationsOptions,\n ListCodexModelsOptions,\n ReadCodexRateLimitsOptions,\n ConsumeCodexRateLimitResetCreditOptions,\n SendCodexMessageOptions,\n StartCodexReviewOptions,\n StartCodexLiveChatOptions,\n UpdateCodexConversationSettings,\n} from './surface';\n\ntype RequiredRendererApi = Required<CodexSurfaceRendererApi>;\nexport type CodexSurfaceBridgeOperation = Exclude<\n keyof RequiredRendererApi,\n 'onEvent' | 'onStateChange' | 'onStatePatch' | 'getVersionedSnapshot'\n>;\ntype OperationFunction<Name extends CodexSurfaceBridgeOperation> = Extract<\n RequiredRendererApi[Name],\n (...args: never[]) => unknown\n>;\nexport type CodexSurfaceBridgeOperationArguments<Name extends CodexSurfaceBridgeOperation> =\n Parameters<OperationFunction<Name>>;\nexport type CodexSurfaceBridgeOperationResult<Name extends CodexSurfaceBridgeOperation> =\n Awaited<ReturnType<OperationFunction<Name>>>;\ntype Awaitable<Value> = Value | Promise<Value>;\ntype SurfaceOperationFunction<Name extends CodexSurfaceBridgeOperation> = Name extends keyof Required<CodexSurfaceApi>\n ? Extract<Required<CodexSurfaceApi>[Name], (...args: never[]) => unknown>\n : never;\ntype OptionalAccountOperation = 'readRateLimits' | 'readAccountUsage' | 'consumeRateLimitResetCredit';\ntype BridgeOperationMethods = {\n [Name in CodexSurfaceBridgeOperation]: (\n ...args: Parameters<SurfaceOperationFunction<Name>>\n ) => Awaitable<Awaited<ReturnType<SurfaceOperationFunction<Name>>>>;\n};\nexport type CodexSurfaceBridgeTarget = Omit<BridgeOperationMethods, OptionalAccountOperation>\n & Partial<Pick<BridgeOperationMethods, OptionalAccountOperation>>\n & Pick<CodexSurfaceApi, 'onEvent' | 'onStateChange'>;\n\nexport type CodexSurfaceBridgeAttachmentResolver = (\n attachment: CodexRendererAttachment,\n) => Awaitable<CodexSurfaceAttachment>;\n\nexport type CodexSurfaceBridgeInvokeOptions = {\n operationLabel?: string;\n resolveAttachment?: CodexSurfaceBridgeAttachmentResolver;\n};\n\ntype CodexConversationBridgeOperationFunctions = {\n clearGoal(): Awaitable<CodexConversationSnapshot>;\n compactConversation(): Awaitable<CodexConversationSnapshot>;\n continueInterruptedTurn(): Awaitable<CodexConversationSnapshot>;\n deleteTurn(turnId: string): Awaitable<CodexConversationSnapshot>;\n deleteQueuedPrompt(promptId: string): Awaitable<CodexConversationSnapshot>;\n editTurn(turnId: string, content: string, options?: CodexRendererSendMessageOptions): Awaitable<CodexConversationSnapshot>;\n forkTurn(turnId: string): Awaitable<CodexConversationSnapshot>;\n getSnapshot(): Awaitable<CodexConversationSnapshot>;\n interrupt(): Awaitable<CodexConversationSnapshot>;\n loadOlderConversationHistory(): Awaitable<CodexConversationHistoryPage>;\n readConversationHistory(): Awaitable<CodexConversationHistory>;\n readConversationPromptHistory(): Awaitable<CodexConversationPromptHistory>;\n renameConversation(title: string): Awaitable<CodexConversationSnapshot>;\n respondToClientRequest(response: CodexSurfaceClientRequestResponse): Awaitable<CodexConversationSnapshot>;\n resolveApproval(\n approvalId: string,\n decision: CodexSurfaceApprovalDecision,\n scope?: CodexSurfaceApprovalScope,\n ): Awaitable<CodexConversationSnapshot>;\n retryTurn(turnId: string): Awaitable<CodexConversationSnapshot>;\n sendMessage(prompt: string, options?: CodexRendererSendMessageOptions): Awaitable<CodexConversationSnapshot>;\n setGoal(objective: string, tokenBudget?: number | null): Awaitable<CodexConversationSnapshot>;\n startReview(options?: StartCodexReviewOptions): Awaitable<CodexConversationSnapshot>;\n steerMessage(prompt: string, options?: CodexRendererSendMessageOptions): Awaitable<CodexConversationSnapshot>;\n steerQueuedPrompt(promptId: string, prompt?: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n updateConversationSettings(settings: UpdateCodexConversationSettings): Awaitable<CodexConversationSnapshot>;\n updateQueuedPrompt(promptId: string, prompt: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n};\n\nexport const codexConversationBridgeOperations = [\n 'clearGoal', 'compactConversation', 'continueInterruptedTurn', 'deleteTurn', 'deleteQueuedPrompt', 'editTurn',\n 'forkTurn', 'getSnapshot', 'interrupt', 'loadOlderConversationHistory',\n 'readConversationHistory', 'readConversationPromptHistory', 'renameConversation',\n 'respondToClientRequest', 'resolveApproval', 'retryTurn', 'sendMessage', 'setGoal',\n 'startReview', 'steerMessage', 'steerQueuedPrompt', 'updateConversationSettings',\n 'updateQueuedPrompt',\n] as const satisfies readonly (keyof CodexConversationBridgeOperationFunctions)[];\n\nexport type CodexConversationBridgeOperation = typeof codexConversationBridgeOperations[number];\nexport type CodexConversationBridgeOperationArguments<Name extends CodexConversationBridgeOperation> =\n Parameters<CodexConversationBridgeOperationFunctions[Name]>;\nexport type CodexConversationBridgeOperationResult<Name extends CodexConversationBridgeOperation> =\n Awaited<ReturnType<CodexConversationBridgeOperationFunctions[Name]>>;\n\nexport type CodexConversationBridgeHandle = {\n clearGoal(): Awaitable<CodexConversationSnapshot>;\n compact(): Awaitable<CodexConversationSnapshot>;\n continueInterruptedTurn(): Awaitable<CodexConversationSnapshot>;\n deleteTurn(turnId: string): Awaitable<CodexConversationSnapshot>;\n deleteQueuedPrompt(promptId: string): Awaitable<CodexConversationSnapshot>;\n editTurn(turnId: string, content: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n forkTurn(turnId: string): Awaitable<{ snapshot: CodexConversationSnapshot }>;\n getSnapshot(): CodexConversationSnapshot;\n interrupt(): Awaitable<CodexConversationSnapshot>;\n loadOlderHistory(): Awaitable<CodexConversationHistoryPage>;\n onEvent(listener: (event: CodexConversationEvent) => void): () => void;\n onStateChange(listener: (snapshot: CodexConversationSnapshot) => void): () => void;\n readHistory(): Awaitable<CodexConversationHistory>;\n readPromptHistory(): Awaitable<CodexConversationPromptHistory>;\n rename(title: string): Awaitable<CodexConversationSnapshot>;\n respondToClientRequest(response: CodexSurfaceClientRequestResponse): Awaitable<CodexConversationSnapshot>;\n resolveApproval(\n approvalId: string,\n decision: CodexSurfaceApprovalDecision,\n scope?: CodexSurfaceApprovalScope,\n ): Awaitable<CodexConversationSnapshot>;\n retryTurn(turnId: string): Awaitable<CodexConversationSnapshot>;\n sendMessage(prompt: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n setGoal(objective: string, tokenBudget?: number | null): Awaitable<CodexConversationSnapshot>;\n startReview(options?: StartCodexReviewOptions): Awaitable<CodexConversationSnapshot>;\n steerMessage(prompt: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n steerQueuedPrompt(promptId: string, prompt?: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n updateQueuedPrompt(promptId: string, prompt: string, options?: SendCodexMessageOptions): Awaitable<CodexConversationSnapshot>;\n updateSettings(settings: UpdateCodexConversationSettings): Awaitable<CodexConversationSnapshot>;\n};\n\nexport type CodexConversationBridgeTarget = {\n conversation(conversationId: string): CodexConversationBridgeHandle;\n};\n\nexport type CodexConversationBridgeNotification =\n | {\n type: 'snapshot';\n conversationId: string;\n snapshot: CodexConversationSnapshot;\n }\n | {\n type: 'event';\n conversationId: string;\n event: CodexConversationEvent;\n };\n\nconst conversationOperationSet = new Set<string>(codexConversationBridgeOperations);\n\nexport function isCodexConversationBridgeOperation(value: unknown): value is CodexConversationBridgeOperation {\n return typeof value === 'string' && conversationOperationSet.has(value);\n}\n\nexport async function invokeCodexConversationBridgeOperation<Name extends CodexConversationBridgeOperation>(\n target: CodexConversationBridgeTarget,\n conversationId: string,\n operation: Name,\n args: readonly unknown[],\n options: CodexSurfaceBridgeInvokeOptions = {},\n): Promise<CodexConversationBridgeOperationResult<Name>> {\n const id = nonEmptyString(conversationId, 'Conversation id');\n const [minimum, maximum] = conversationArities[operation];\n if (args.length < minimum || args.length > maximum) {\n throw new TypeError(`${options.operationLabel ?? operation} received an invalid number of arguments`);\n }\n const conversation = target.conversation(id);\n const bridgeTarget = conversationOperationTarget(conversation);\n const result = await invokeCodexSurfaceBridgeOperation(bridgeTarget, operation, args, options);\n return result as CodexConversationBridgeOperationResult<Name>;\n}\n\nexport function subscribeCodexConversationBridge(\n target: CodexConversationBridgeTarget,\n conversationId: string,\n listener: (notification: CodexConversationBridgeNotification) => void,\n): () => void {\n const id = nonEmptyString(conversationId, 'Conversation id');\n const conversation = target.conversation(id);\n const emitSnapshot = (snapshot: CodexConversationSnapshot) => {\n if (snapshot.activeConversationId === id) {\n listener({ type: 'snapshot', conversationId: id, snapshot });\n }\n };\n const emitEvent = (event: CodexConversationEvent) => {\n if (event.conversationId === id) listener({ type: 'event', conversationId: id, event });\n };\n const unsubscribeState = conversation.onStateChange(emitSnapshot);\n let unsubscribeEvent: () => void;\n try {\n unsubscribeEvent = conversation.onEvent(emitEvent);\n } catch (error) {\n unsubscribeState();\n throw error;\n }\n return () => {\n unsubscribeEvent();\n unsubscribeState();\n };\n}\n\n/**\n * Emits exactly one targeted snapshot followed by semantic conversation events.\n * Events raised while the initial snapshot is captured are buffered so consumers\n * can always initialize a replica before applying deltas.\n */\nexport function subscribeCodexConversationReplicaBridge(\n target: CodexConversationBridgeTarget,\n conversationId: string,\n listener: (notification: CodexConversationBridgeNotification) => void,\n): () => void {\n const id = nonEmptyString(conversationId, 'Conversation id');\n const conversation = target.conversation(id);\n const pending: CodexConversationEvent[] = [];\n let initialized = false;\n const unsubscribe = conversation.onEvent((event) => {\n if (event.conversationId !== id) return;\n if (!initialized) pending.push(event);\n else listener({ type: 'event', conversationId: id, event });\n });\n try {\n const snapshot = conversation.getSnapshot();\n if (snapshot.activeConversationId !== id) {\n throw new Error(\n `Snapshot belongs to '${snapshot.activeConversationId}', not bridge conversation '${id}'`,\n );\n }\n listener({ type: 'snapshot', conversationId: id, snapshot });\n initialized = true;\n for (const event of pending) listener({ type: 'event', conversationId: id, event });\n pending.length = 0;\n } catch (error) {\n unsubscribe();\n throw error;\n }\n return unsubscribe;\n}\n\nexport const codexSurfaceBridgeOperations = [\n 'archiveConversation', 'cancelLogin', 'clearGoal', 'compactConversation', 'connect',\n 'continueInterruptedTurn', 'createConversation', 'deleteConversation', 'deleteTurn', 'deleteQueuedPrompt',\n 'editTurn', 'forkTurn', 'getSnapshot', 'interrupt', 'listConversations',\n 'listModels', 'loadOlderConversationHistory', 'logout', 'readConversationHistory',\n 'readConversationPromptHistory', 'refreshAccount', 'refreshConversations', 'renameConversation', 'respondToClientRequest',\n 'resolveApproval', 'retryTurn', 'selectConversation', 'sendMessage', 'setGoal',\n 'startChatGptDeviceCodeLogin', 'startChatGptLogin', 'startReview', 'steerMessage', 'steerQueuedPrompt',\n 'unarchiveConversation', 'updateConversationSettings', 'updateQueuedPrompt',\n 'startLiveChat', 'stopLiveChat',\n 'readRateLimits',\n 'readAccountUsage',\n 'consumeRateLimitResetCredit',\n] as const satisfies readonly CodexSurfaceBridgeOperation[];\n\nconst operationSet = new Set<string>(codexSurfaceBridgeOperations);\nexport const codexSurfaceBridgeArities: Readonly<\n Record<CodexSurfaceBridgeOperation, readonly [minimum: number, maximum: number]>\n> = {\n startLiveChat: [2, 2], stopLiveChat: [1, 1],\n archiveConversation: [1, 1], cancelLogin: [0, 1], clearGoal: [0, 0],\n compactConversation: [0, 0], connect: [0, 0], continueInterruptedTurn: [0, 0], createConversation: [0, 1],\n deleteConversation: [1, 1], deleteTurn: [1, 1], deleteQueuedPrompt: [1, 1],\n editTurn: [2, 3], forkTurn: [1, 1], getSnapshot: [0, 0], interrupt: [0, 0],\n listConversations: [0, 1], listModels: [0, 1], loadOlderConversationHistory: [0, 1],\n logout: [0, 0], readConversationHistory: [0, 1], readConversationPromptHistory: [0, 1],\n refreshAccount: [0, 0],\n readRateLimits: [0, 1],\n readAccountUsage: [0, 0],\n consumeRateLimitResetCredit: [1, 1],\n refreshConversations: [0, 0], renameConversation: [1, 1], respondToClientRequest: [1, 1],\n resolveApproval: [2, 3], retryTurn: [1, 1], selectConversation: [1, 1],\n sendMessage: [1, 2], setGoal: [1, 2], startChatGptDeviceCodeLogin: [0, 0],\n startChatGptLogin: [0, 0], startReview: [0, 1],\n steerMessage: [1, 2], steerQueuedPrompt: [1, 3], unarchiveConversation: [1, 1],\n updateConversationSettings: [1, 1], updateQueuedPrompt: [2, 3],\n};\n\nconst conversationArities: Readonly<\n Record<CodexConversationBridgeOperation, readonly [minimum: number, maximum: number]>\n> = {\n clearGoal: [0, 0], compactConversation: [0, 0], continueInterruptedTurn: [0, 0], deleteTurn: [1, 1],\n deleteQueuedPrompt: [1, 1], editTurn: [2, 3], forkTurn: [1, 1], getSnapshot: [0, 0],\n interrupt: [0, 0], loadOlderConversationHistory: [0, 0], readConversationHistory: [0, 0],\n readConversationPromptHistory: [0, 0], renameConversation: [1, 1], respondToClientRequest: [1, 1],\n resolveApproval: [2, 3], retryTurn: [1, 1], sendMessage: [1, 2], setGoal: [1, 2],\n startReview: [0, 1], steerMessage: [1, 2], steerQueuedPrompt: [1, 3],\n updateConversationSettings: [1, 1], updateQueuedPrompt: [2, 3],\n};\n\nexport function isCodexSurfaceBridgeOperation(value: unknown): value is CodexSurfaceBridgeOperation {\n return typeof value === 'string' && operationSet.has(value);\n}\n\nexport async function invokeCodexSurfaceBridgeOperation<Name extends CodexSurfaceBridgeOperation>(\n target: CodexSurfaceBridgeTarget,\n operation: Name,\n args: readonly unknown[],\n options: CodexSurfaceBridgeInvokeOptions = {},\n): Promise<CodexSurfaceBridgeOperationResult<Name>> {\n const [minimum, maximum] = codexSurfaceBridgeArities[operation];\n if (args.length < minimum || args.length > maximum) {\n throw new TypeError(`${options.operationLabel ?? operation} received an invalid number of arguments`);\n }\n const result = await invokeValidated(target, operation, args, options);\n return result as CodexSurfaceBridgeOperationResult<Name>;\n}\n\nfunction conversationOperationTarget(conversation: CodexConversationBridgeHandle): CodexSurfaceBridgeTarget {\n const target: Pick<CodexSurfaceBridgeTarget, CodexConversationBridgeOperation> = {\n clearGoal: () => conversation.clearGoal(),\n compactConversation: () => conversation.compact(),\n continueInterruptedTurn: () => conversation.continueInterruptedTurn(),\n deleteTurn: (turnId) => conversation.deleteTurn(turnId),\n deleteQueuedPrompt: (promptId) => conversation.deleteQueuedPrompt(promptId),\n editTurn: (turnId, content, options) => conversation.editTurn(turnId, content, options),\n forkTurn: async (turnId) => (await conversation.forkTurn(turnId)).snapshot,\n getSnapshot: () => conversation.getSnapshot(),\n interrupt: () => conversation.interrupt(),\n loadOlderConversationHistory: () => conversation.loadOlderHistory(),\n readConversationHistory: () => conversation.readHistory(),\n readConversationPromptHistory: () => conversation.readPromptHistory(),\n renameConversation: (title) => conversation.rename(title),\n respondToClientRequest: (response) => conversation.respondToClientRequest(response),\n resolveApproval: (approvalId, decision, scope) => conversation.resolveApproval(approvalId, decision, scope),\n retryTurn: (turnId) => conversation.retryTurn(turnId),\n sendMessage: (prompt, options) => conversation.sendMessage(prompt, options),\n setGoal: (objective, tokenBudget) => conversation.setGoal(objective, tokenBudget),\n startReview: (options) => conversation.startReview(options),\n steerMessage: (prompt, options) => conversation.steerMessage(prompt, options),\n steerQueuedPrompt: (promptId, prompt, options) => conversation.steerQueuedPrompt(promptId, prompt, options),\n updateConversationSettings: (settings) => conversation.updateSettings(settings),\n updateQueuedPrompt: (promptId, prompt, options) => conversation.updateQueuedPrompt(promptId, prompt, options),\n };\n return target as unknown as CodexSurfaceBridgeTarget;\n}\n\nasync function invokeValidated(\n target: CodexSurfaceBridgeTarget,\n operation: CodexSurfaceBridgeOperation,\n args: readonly unknown[],\n options: CodexSurfaceBridgeInvokeOptions,\n): Promise<unknown> {\n switch (operation) {\n case 'startLiveChat': return target.startLiveChat(\n nonEmptyString(args[0], 'Conversation id'), liveChatOptions(args[1]),\n );\n case 'stopLiveChat': return target.stopLiveChat(nonEmptyString(args[0], 'Conversation id'));\n case 'archiveConversation': return target.archiveConversation(nonEmptyString(args[0], 'Conversation id'));\n case 'cancelLogin': return target.cancelLogin(optionalString(args[0], 'Login id'));\n case 'clearGoal': return target.clearGoal();\n case 'compactConversation': return target.compactConversation();\n case 'connect': return target.connect();\n case 'continueInterruptedTurn': return target.continueInterruptedTurn();\n case 'createConversation': return target.createConversation(conversationOptions(args[0]));\n case 'deleteConversation': return target.deleteConversation(nonEmptyString(args[0], 'Conversation id'));\n case 'deleteTurn': return target.deleteTurn(nonEmptyString(args[0], 'Turn id'));\n case 'deleteQueuedPrompt': return target.deleteQueuedPrompt(nonEmptyString(args[0], 'Queued prompt id'));\n case 'editTurn': return target.editTurn(nonEmptyString(args[0], 'Turn id'), nonEmptyString(args[1], 'Turn content'), await sendOptions(args[2], options.resolveAttachment));\n case 'forkTurn': return target.forkTurn(nonEmptyString(args[0], 'Turn id'));\n case 'getSnapshot': return target.getSnapshot();\n case 'interrupt': return target.interrupt();\n case 'listConversations': return target.listConversations(listConversationOptions(args[0]));\n case 'listModels': return target.listModels(listModelOptions(args[0]));\n case 'loadOlderConversationHistory': return target.loadOlderConversationHistory(optionalString(args[0], 'Conversation id'));\n case 'logout': return target.logout();\n case 'readConversationHistory': return target.readConversationHistory(optionalString(args[0], 'Conversation id'));\n case 'readConversationPromptHistory': return target.readConversationPromptHistory(\n optionalString(args[0], 'Conversation id'),\n );\n case 'refreshAccount': return target.refreshAccount();\n case 'readRateLimits': {\n const options = rateLimitsOptions(args[0]);\n if (!target.readRateLimits) throw new Error('Account rate-limit reads are not available.');\n return target.readRateLimits(options);\n }\n case 'readAccountUsage': {\n if (!target.readAccountUsage) throw new Error('Account usage reads are not available.');\n return target.readAccountUsage();\n }\n case 'consumeRateLimitResetCredit': {\n const options = resetCreditOptions(args[0]);\n if (!target.consumeRateLimitResetCredit) throw new Error('Rate-limit reset credits are not available.');\n return target.consumeRateLimitResetCredit(options);\n }\n case 'refreshConversations': return target.refreshConversations();\n case 'renameConversation': return target.renameConversation(nonEmptyString(args[0], 'Conversation title'));\n case 'respondToClientRequest': return target.respondToClientRequest(clientRequestResponse(args[0]));\n case 'resolveApproval': return target.resolveApproval(\n nonEmptyString(args[0], 'Approval id'), approvalDecision(args[1]), approvalScope(args[2]),\n );\n case 'retryTurn': return target.retryTurn(nonEmptyString(args[0], 'Turn id'));\n case 'selectConversation': return target.selectConversation(nonEmptyString(args[0], 'Conversation id'));\n case 'sendMessage': return target.sendMessage(\n nonEmptyString(args[0], 'Message prompt'),\n await sendOptions(args[1], options.resolveAttachment),\n );\n case 'setGoal': return target.setGoal(nonEmptyString(args[0], 'Goal objective'), tokenBudget(args[1]));\n case 'startChatGptDeviceCodeLogin': return target.startChatGptDeviceCodeLogin();\n case 'startChatGptLogin': return target.startChatGptLogin();\n case 'startReview': return target.startReview(reviewOptions(args[0]));\n case 'steerMessage': return target.steerMessage(\n nonEmptyString(args[0], 'Steer prompt'),\n await sendOptions(args[1], options.resolveAttachment),\n );\n case 'steerQueuedPrompt': return target.steerQueuedPrompt(\n nonEmptyString(args[0], 'Queued prompt id'),\n optionalString(args[1], 'Queued prompt'),\n await sendOptions(args[2], options.resolveAttachment),\n );\n case 'unarchiveConversation': return target.unarchiveConversation(nonEmptyString(args[0], 'Conversation id'));\n case 'updateConversationSettings': return target.updateConversationSettings(settings(args[0]));\n case 'updateQueuedPrompt': return target.updateQueuedPrompt(\n nonEmptyString(args[0], 'Queued prompt id'), nonEmptyString(args[1], 'Queued prompt'),\n await sendOptions(args[2], options.resolveAttachment),\n );\n }\n}\n\nfunction liveChatOptions(value: unknown): StartCodexLiveChatOptions {\n const record = plainObject(value, 'Live chat options');\n onlyKeys(record, ['sdp', 'version', 'voice', 'model', 'prompt', 'includeStartupContext', 'flushTranscriptTailOnSessionEnd'], 'Live chat options');\n const result: StartCodexLiveChatOptions = { sdp: nonEmptyString(record.sdp, 'SDP offer') };\n if (record.version !== undefined) {\n if (record.version !== 'v1' && record.version !== 'v2' && record.version !== 'v3') throw new TypeError('Invalid realtime version');\n result.version = record.version;\n }\n for (const key of ['voice', 'model'] as const) {\n if (record[key] !== undefined) result[key] = nonEmptyString(record[key], key);\n }\n if (record.prompt !== undefined) {\n if (record.prompt !== null && typeof record.prompt !== 'string') throw new TypeError('Prompt must be a string or null');\n result.prompt = record.prompt;\n }\n for (const key of ['includeStartupContext', 'flushTranscriptTailOnSessionEnd'] as const) {\n if (record[key] !== undefined) {\n if (typeof record[key] !== 'boolean') throw new TypeError(`${key} must be a boolean`);\n result[key] = record[key];\n }\n }\n return result;\n}\n\nfunction conversationOptions(value: unknown): CreateCodexRendererConversationOptions | undefined {\n if (value === undefined) return undefined;\n const record = plainObject(value, 'Conversation options');\n onlyKeys(record, ['model', 'reasoningEffort', 'serviceTier', 'approvalPreset'], 'Conversation options');\n return {\n ...(record.model === undefined ? {} : { model: nonEmptyString(record.model, 'Conversation model') }),\n ...(record.reasoningEffort === undefined ? {} : { reasoningEffort: nonEmptyString(record.reasoningEffort, 'Conversation reasoning effort') }),\n ...(record.serviceTier === undefined ? {} : { serviceTier: nullableString(record.serviceTier, 'Conversation service tier') }),\n ...(record.approvalPreset === undefined ? {} : { approvalPreset: approvalPreset(record.approvalPreset) }),\n };\n}\n\nfunction listConversationOptions(value: unknown): ListCodexConversationsOptions | undefined {\n if (value === undefined) return undefined;\n const record = plainObject(value, 'Conversation list options');\n onlyKeys(record, ['archived', 'cwd', 'limit', 'searchTerm'], 'Conversation list options');\n if (record.archived !== undefined && typeof record.archived !== 'boolean') {\n throw new TypeError('Conversation list archived flag must be a boolean');\n }\n if (record.limit !== undefined && (!Number.isInteger(record.limit) || (record.limit as number) < 0)) {\n throw new TypeError('Conversation list limit must be a non-negative integer');\n }\n const cwd = record.cwd === undefined ? undefined : Array.isArray(record.cwd)\n ? record.cwd.map((entry) => nonEmptyString(entry, 'Conversation list cwd'))\n : nonEmptyString(record.cwd, 'Conversation list cwd');\n return {\n ...(record.archived === undefined ? {} : { archived: record.archived }),\n ...(cwd === undefined ? {} : { cwd }),\n ...(record.limit === undefined ? {} : { limit: record.limit as number }),\n ...(record.searchTerm === undefined ? {} : { searchTerm: nonEmptyString(record.searchTerm, 'Conversation list search term') }),\n };\n}\n\nfunction rateLimitsOptions(value: unknown): ReadCodexRateLimitsOptions | undefined {\n if (value === undefined) return undefined;\n const record = plainObject(value, 'Rate-limit read options');\n onlyKeys(record, ['excludeResetCreditDetails'], 'Rate-limit read options');\n return record.excludeResetCreditDetails === undefined ? {} : {\n excludeResetCreditDetails: booleanValue(record.excludeResetCreditDetails, 'Exclude reset credit details'),\n };\n}\n\nfunction resetCreditOptions(value: unknown): ConsumeCodexRateLimitResetCreditOptions {\n const record = plainObject(value, 'Reset-credit options');\n onlyKeys(record, ['idempotencyKey', 'creditId'], 'Reset-credit options');\n return {\n idempotencyKey: nonEmptyString(record.idempotencyKey, 'Reset-credit idempotency key'),\n ...(record.creditId === undefined ? {} : { creditId: nonEmptyString(record.creditId, 'Reset credit id') }),\n };\n}\n\nfunction listModelOptions(value: unknown): ListCodexModelsOptions | undefined {\n if (value === undefined) return undefined;\n const record = plainObject(value, 'Model list options');\n onlyKeys(record, ['includeHidden', 'forceReload'], 'Model list options');\n return {\n ...(record.includeHidden === undefined ? {} : { includeHidden: booleanValue(record.includeHidden, 'Model list includeHidden') }),\n ...(record.forceReload === undefined ? {} : { forceReload: booleanValue(record.forceReload, 'Model list forceReload') }),\n };\n}\n\nfunction settings(value: unknown): UpdateCodexConversationSettings {\n const record = plainObject(value, 'Conversation settings');\n onlyKeys(record, ['modelId', 'reasoningEffort', 'serviceTier', 'approvalPreset', 'planMode'], 'Conversation settings');\n return {\n ...(record.modelId === undefined ? {} : { modelId: nonEmptyString(record.modelId, 'Conversation model id') }),\n ...(record.reasoningEffort === undefined ? {} : { reasoningEffort: nonEmptyString(record.reasoningEffort, 'Conversation reasoning effort') }),\n ...(record.serviceTier === undefined ? {} : { serviceTier: nullableString(record.serviceTier, 'Conversation service tier') }),\n ...(record.approvalPreset === undefined ? {} : { approvalPreset: approvalPreset(record.approvalPreset) }),\n ...(record.planMode === undefined ? {} : { planMode: booleanValue(record.planMode, 'Conversation plan mode') }),\n };\n}\n\nfunction clientRequestResponse(value: unknown): CodexSurfaceClientRequestResponse {\n const record = plainObject(value, 'Client request response');\n onlyKeys(record, ['id', 'payload'], 'Client request response');\n const id = nonEmptyString(record.id, 'Client request id');\n if (record.payload === undefined) return { id };\n const payload = plainObject(record.payload, 'Client request response payload');\n onlyKeys(payload, ['answers', 'cancelled', 'decision'], 'Client request response payload');\n const decision = payload.decision;\n const validDecisions = [null, 'allow', 'allow_conversation', 'always_allow', 'deny'];\n if (decision !== undefined && !validDecisions.includes(decision as string | null)) {\n throw new TypeError('Client request decision is invalid');\n }\n const answers = payload.answers === undefined ? undefined : askUserAnswers(payload.answers);\n return {\n id,\n payload: {\n ...(answers === undefined ? {} : { answers }),\n ...(payload.cancelled === undefined ? {} : { cancelled: booleanValue(payload.cancelled, 'Client request cancelled flag') }),\n ...(decision === undefined ? {} : { decision: decision as NonNullable<CodexSurfaceClientRequestResponse['payload']>['decision'] }),\n },\n };\n}\n\nfunction askUserAnswers(value: unknown): CodexSurfaceAskUserAnswers {\n const record = plainObject(value, 'Client request answers');\n const answers: CodexSurfaceAskUserAnswers = {};\n for (const [questionId, rawAnswer] of Object.entries(record)) {\n if (!questionId.trim()) throw new TypeError('Client request question id must be non-empty');\n const answer = plainObject(rawAnswer, 'Client request answer');\n onlyKeys(answer, ['answers'], 'Client request answer');\n if (!Array.isArray(answer.answers) || !answer.answers.every((item) => typeof item === 'string')) {\n throw new TypeError('Client request answer values must be an array of strings');\n }\n answers[questionId] = { answers: [...answer.answers] };\n }\n return answers;\n}\n\nasync function sendOptions(\n value: unknown,\n resolveAttachment: CodexSurfaceBridgeAttachmentResolver | undefined,\n): Promise<SendCodexMessageOptions | undefined> {\n if (value === undefined) return undefined;\n const record = plainObject(value, 'Message options');\n onlyKeys(record, ['content', 'inputMethod', 'attachments', 'model', 'reasoningEffort', 'serviceTier', 'planMode', 'skills', 'outputSchema'], 'Message options');\n const attachments = record.attachments === undefined\n ? undefined\n : await attachmentInputs(record.attachments, resolveAttachment);\n const skills = record.skills === undefined ? undefined : skillInputs(record.skills);\n const inputMethod = record.inputMethod;\n if (inputMethod !== undefined && inputMethod !== 'typed' && inputMethod !== 'dictated') {\n throw new TypeError('Message input method must be typed or dictated');\n }\n if (record.outputSchema !== undefined && !isJsonValue(record.outputSchema)) {\n throw new TypeError('Message output schema must be JSON-serializable');\n }\n return {\n ...(record.content === undefined ? {} : { content: normalizePromptContent(record.content) }),\n ...(inputMethod === undefined ? {} : { inputMethod }),\n ...(attachments === undefined ? {} : { attachments }),\n ...(record.model === undefined ? {} : { model: nonEmptyString(record.model, 'Message model') }),\n ...(record.reasoningEffort === undefined ? {} : { reasoningEffort: nonEmptyString(record.reasoningEffort, 'Message reasoning effort') }),\n ...(record.serviceTier === undefined ? {} : { serviceTier: nullableString(record.serviceTier, 'Message service tier') }),\n ...(record.planMode === undefined ? {} : { planMode: booleanValue(record.planMode, 'Message plan mode') }),\n ...(skills === undefined ? {} : { skills }),\n ...(record.outputSchema === undefined ? {} : { outputSchema: record.outputSchema }),\n };\n}\n\nasync function attachmentInputs(\n value: unknown,\n resolveAttachment: CodexSurfaceBridgeAttachmentResolver | undefined,\n): Promise<NonNullable<SendCodexMessageOptions['attachments']>> {\n if (!Array.isArray(value)) throw new TypeError('Message attachments must be an array');\n if (value.length > 0 && !resolveAttachment) {\n throw new TypeError('Message attachment references are not supported by this host');\n }\n return Promise.all(value.map(async (rawAttachment) => {\n const attachment = plainObject(rawAttachment, 'Message attachment');\n if (attachment.type !== 'image' && attachment.type !== 'file') {\n throw new TypeError('Message attachment type is invalid');\n }\n const image = attachment.type === 'image';\n onlyKeys(\n attachment,\n image ? ['type', 'reference', 'detail'] : ['type', 'reference'],\n 'Message attachment',\n );\n if (image && attachment.detail !== undefined && !['auto', 'low', 'high', 'original'].includes(String(attachment.detail))) {\n throw new TypeError('Message image detail is invalid');\n }\n const rendererAttachment: CodexRendererAttachment = image ? {\n type: 'image' as const,\n reference: nonEmptyString(attachment.reference, 'Message attachment reference'),\n ...(attachment.detail === undefined ? {} : { detail: attachment.detail as 'auto' | 'low' | 'high' | 'original' }),\n } : {\n type: 'file' as const,\n reference: nonEmptyString(attachment.reference, 'Message attachment reference'),\n };\n const resolved = await resolveAttachment!(rendererAttachment);\n return resolvedAttachment(resolved, rendererAttachment);\n }));\n}\n\nfunction resolvedAttachment(\n value: CodexSurfaceAttachment,\n source: CodexRendererAttachment,\n): CodexSurfaceAttachment {\n const attachment = plainObject(value, 'Resolved message attachment');\n if (attachment.type !== source.type) throw new TypeError('Resolved message attachment type does not match');\n const common = {\n path: nonEmptyString(attachment.path, 'Resolved message attachment path'),\n ...(attachment.name === undefined ? {} : { name: displayString(attachment.name, 'Resolved message attachment name') }),\n ...(attachment.mimeType === undefined ? {} : { mimeType: displayString(attachment.mimeType, 'Resolved message attachment MIME type') }),\n };\n return source.type === 'image' ? {\n type: 'image',\n ...common,\n ...(source.detail === undefined ? {} : { detail: source.detail }),\n ...(attachment.previewUrl === undefined\n ? {}\n : { previewUrl: imagePreviewUrl(attachment.previewUrl) }),\n } : { type: 'file', ...common };\n}\n\nfunction skillInputs(value: unknown): NonNullable<SendCodexMessageOptions['skills']> {\n if (!Array.isArray(value)) throw new TypeError('Message skills must be an array');\n return value.map((rawSkill) => {\n const skill = plainObject(rawSkill, 'Message skill');\n onlyKeys(skill, ['name', 'path'], 'Message skill');\n return { name: nonEmptyString(skill.name, 'Message skill name'), path: nonEmptyString(skill.path, 'Message skill path') };\n });\n}\n\nfunction reviewOptions(value: unknown): StartCodexReviewOptions | undefined {\n if (value === undefined) return undefined;\n const record = plainObject(value, 'Review options');\n onlyKeys(record, ['target'], 'Review options');\n if (record.target === undefined) return {};\n const target = plainObject(record.target, 'Review target');\n if (target.type === 'uncommittedChanges') {\n onlyKeys(target, ['type'], 'Review target');\n return { target: { type: 'uncommittedChanges' } };\n }\n if (target.type === 'baseBranch') {\n onlyKeys(target, ['type', 'branch'], 'Review target');\n return { target: { type: 'baseBranch', branch: nonEmptyString(target.branch, 'Review branch') } };\n }\n if (target.type === 'commit') {\n onlyKeys(target, ['type', 'sha', 'title'], 'Review target');\n if (target.title !== undefined && target.title !== null && typeof target.title !== 'string') {\n throw new TypeError('Review commit title must be a string or null');\n }\n return { target: { type: 'commit', sha: nonEmptyString(target.sha, 'Review commit SHA'), ...(target.title === undefined ? {} : { title: target.title }) } };\n }\n if (target.type === 'custom') {\n onlyKeys(target, ['type', 'instructions'], 'Review target');\n return { target: { type: 'custom', instructions: nonEmptyString(target.instructions, 'Review instructions') } };\n }\n throw new TypeError('Review target type is invalid');\n}\n\nfunction plainObject(value: unknown, label: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new TypeError(`${label} must be an object`);\n const prototype = Object.getPrototypeOf(value) as object | null;\n if (prototype !== Object.prototype && prototype !== null) throw new TypeError(`${label} must be a plain object`);\n if (Reflect.ownKeys(value).some((key) => typeof key === 'symbol')) throw new TypeError(`${label} must not contain symbol properties`);\n return value as Record<string, unknown>;\n}\n\nfunction onlyKeys(record: Record<string, unknown>, keys: readonly string[], label: string): void {\n const allowed = new Set(keys);\n const unknownKey = Object.getOwnPropertyNames(record).find((key) => !allowed.has(key));\n if (unknownKey) throw new TypeError(`${label} contains unsupported property \"${unknownKey}\"`);\n}\n\nfunction nonEmptyString(value: unknown, label: string): string {\n if (typeof value !== 'string' || !value.trim()) throw new TypeError(`${label} must be a non-empty string`);\n return value;\n}\nfunction optionalString(value: unknown, label: string): string | undefined {\n return value === undefined ? undefined : nonEmptyString(value, label);\n}\nfunction nullableString(value: unknown, label: string): string | null {\n return value === null ? null : nonEmptyString(value, label);\n}\nfunction booleanValue(value: unknown, label: string): boolean {\n if (typeof value !== 'boolean') throw new TypeError(`${label} must be a boolean`);\n return value;\n}\nfunction approvalDecision(value: unknown): CodexSurfaceApprovalDecision {\n if (value !== 'approve' && value !== 'deny') throw new TypeError('Approval decision is invalid');\n return value;\n}\nfunction approvalScope(value: unknown): CodexSurfaceApprovalScope | undefined {\n if (value === undefined) return undefined;\n if (value !== 'once' && value !== 'session') throw new TypeError('Approval scope is invalid');\n return value;\n}\nfunction approvalPreset(value: unknown): UpdateCodexConversationSettings['approvalPreset'] {\n if (!['ask-for-approval', 'approve-for-me', 'full-access'].includes(String(value))) {\n throw new TypeError('Conversation approval preset is invalid');\n }\n return value as UpdateCodexConversationSettings['approvalPreset'];\n}\nfunction tokenBudget(value: unknown): number | null | undefined {\n if (value === undefined || value === null) return value;\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n throw new TypeError('Goal token budget must be a positive number or null');\n }\n return value;\n}\nfunction displayString(value: unknown, label: string): string {\n const result = nonEmptyString(value, label);\n if (result.length > 1_024) throw new RangeError(`${label} is too long`);\n return result;\n}\nfunction imagePreviewUrl(value: unknown): string {\n if (typeof value !== 'string'\n || value.length > 16 * 1024 * 1024\n || !/^data:image\\/(?:avif|bmp|gif|heic|heif|jpe?g|png|webp);base64,[a-z\\d+/]+={0,2}$/i.test(value)) {\n throw new TypeError('Resolved message attachment preview must be a bounded image data URL');\n }\n return value;\n}\nfunction isJsonValue(value: unknown, seen = new Set<object>()): value is CodexSurfaceJsonValue {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;\n if (typeof value === 'number') return Number.isFinite(value);\n if (typeof value !== 'object' || seen.has(value) || Reflect.ownKeys(value).some((key) => typeof key === 'symbol')) return false;\n if (Array.isArray(value)) {\n const keys = Object.keys(value);\n if (keys.length !== value.length || keys.some((key) => !/^(0|[1-9]\\d*)$/.test(key) || Number(key) >= value.length)) return false;\n } else {\n const prototype = Object.getPrototypeOf(value) as object | null;\n if ((prototype !== Object.prototype && prototype !== null) || Object.keys(value).length !== Object.getOwnPropertyNames(value).length) return false;\n }\n seen.add(value);\n const valid = Array.isArray(value)\n ? value.every((item) => isJsonValue(item, seen))\n : Object.values(value as Record<string, unknown>).every((item) => isJsonValue(item, seen));\n seen.delete(value);\n return valid;\n}\n\nexport {\n applyCodexSurfaceStateChanges,\n createCodexSurfaceStateMirror,\n diffCodexSurfaceState,\n isCodexSurfaceStatePatchSource,\n subscribeCodexSurfaceState,\n type CodexSurfaceStateMirror,\n type CodexSurfaceStateMirrorResult,\n type CodexSurfaceStatePatchSource,\n type CodexSurfaceStateSource,\n type SubscribeCodexSurfaceStateOptions,\n} from './surface-state';\n"],"mappings":";;AAmDA,IAAM,IAAyB;AAE/B,SAAgB,EAA+B,GAAuD;CACpG,IAAM,IAAY;CAClB,OAAO,OAAO,GAAW,wBAAyB,cAAc,OAAO,EAAU,gBAAiB;AACpG;AAOA,SAAgB,EACd,GACA,GAC2B;CAC3B,IAAM,IAAS,GACT,IAAQ,GACR,IAAqC,CAAC;CAC5C,KAAK,IAAM,qBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,CAAM,GAAG,GAAG,OAAO,KAAK,CAAK,CAAC,CAAC,GAAG;EAC1E,IAAM,IAAc;EAChB,MAAO,OAAS,EAAM,IAC1B;OAAI,EAAE,KAAO,IAAQ;IACnB,EAAQ,KAAK;KAAE,MAAM;KAAU,KAAK;IAAY,CAAC;IACjD;GACF;GACA,EAAQ,KAAK,EAAgB,GAAa,EAAO,IAAM,EAAM,EAAI,KAAK;IACpE,MAAM;IACN,KAAK;IACL,OAAO,EAAM;GACf,CAAC;EALD;CAMF;CACA,OAAO;AACT;AAGA,SAAgB,EACd,GACA,GACsB;CACtB,IAAM,IAAU,GACV,IAAuB,EAAE,GAAG,EAAQ;CAC1C,KAAK,IAAM,KAAU,GACnB,IAAI,EAAO,SAAS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AO;EACL,IAAM,IAAY,OAAO,eAAe,CAAK;EAC7C,IAAK,MAAc,OAAO,aAAa,MAAc,QAAS,OAAO,KAAK,CAAK,CAAC,CAAC,WAAW,OAAO,oBAAoB,CAAK,CAAC,CAAC,QAAQ,OAAO;CAC/I;CACA,EAAK,IAAI,CAAK;CACd,IAAM,IAAQ,MAAM,QAAQ,CAAK,IAC7B,EAAM,OAAO,MAAS,EAAY,GAAM,CAAI,CAAC,IAC7C,OAAO,OAAO,CAAgC,CAAC,CAAC,OAAO,MAAS,EAAY,GAAM,CAAI,CAAC;CAE3F,OADA,EAAK,OAAO,CAAK,GACV;AACT"}
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { TypedEventBus as e } from "./events.js";
|
|
2
2
|
import { createCodexConversationReplica as t } from "./conversation-replica.js";
|
|
3
|
-
import { a as n, c as r, d as i, f as a, i as o, l as s, m as c, n as l, o as u, p as d, r as f, s as p, t as m, u as h } from "./chunks/surface-bridge-
|
|
4
|
-
import { a as g, i as _, n as v, o as y, r as b, t as x } from "./chunks/prompt-content-
|
|
3
|
+
import { a as n, c as r, d as i, f as a, i as o, l as s, m as c, n as l, o as u, p as d, r as f, s as p, t as m, u as h } from "./chunks/surface-bridge-oO22We2G.js";
|
|
4
|
+
import { a as g, i as _, n as v, o as y, r as b, t as x } from "./chunks/prompt-content-B8o5tNuN.js";
|
|
5
5
|
export { e as TypedEventBus, h as applyCodexSurfaceStateChanges, m as codexConversationBridgeOperations, l as codexSurfaceBridgeArities, f as codexSurfaceBridgeOperations, t as createCodexConversationReplica, i as createCodexSurfaceStateMirror, a as diffCodexSurfaceState, o as invokeCodexConversationBridgeOperation, n as invokeCodexSurfaceBridgeOperation, u as isCodexConversationBridgeOperation, p as isCodexSurfaceBridgeOperation, d as isCodexSurfaceStatePatchSource, x as normalizePromptContent, v as promptContentDispatchText, b as promptContentText, _ as replacePromptContentRange, g as slicePromptContent, r as subscribeCodexConversationBridge, s as subscribeCodexConversationReplicaBridge, c as subscribeCodexSurfaceState, y as trimPromptContent };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt-content.d.ts","sourceRoot":"","sources":["../src/prompt-content.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE,SAAS,CAAC;IAChB,IAAI,EAAE,OAAO,GAAG,QAAQ,GAAG,MAAM,GAAG,QAAQ,CAAC;IAC7C,EAAE,EAAE,MAAM,CAAC;IACX,gEAAgE;IAChE,KAAK,EAAE,MAAM,CAAC;IACd,yEAAyE;IACzE,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,kBAAkB,CAAC;AAElF,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,SAAS,eAAe,EAAE,GAAG,MAAM,CAE7E;
|
|
1
|
+
{"version":3,"file":"prompt-content.d.ts","sourceRoot":"","sources":["../src/prompt-content.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE,SAAS,CAAC;IAChB,IAAI,EAAE,OAAO,GAAG,QAAQ,GAAG,MAAM,GAAG,QAAQ,CAAC;IAC7C,EAAE,EAAE,MAAM,CAAC;IACX,gEAAgE;IAChE,KAAK,EAAE,MAAM,CAAC;IACd,yEAAyE;IACzE,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,kBAAkB,CAAC;AAElF,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,SAAS,eAAe,EAAE,GAAG,MAAM,CAE7E;AAYD,6FAA6F;AAC7F,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,SAAS,eAAe,EAAE,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAOtG;AAED,4FAA4F;AAC5F,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,SAAS,eAAe,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,SAAoC,GAAG,eAAe,EAAE,CAWjJ;AAED,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,SAAS,eAAe,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,WAAW,EAAE,SAAS,eAAe,EAAE,GACvG,eAAe,EAAE,CAEnB;AAED,+EAA+E;AAC/E,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,OAAO,GAAG,eAAe,EAAE,CA2B1E;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,SAAS,eAAe,EAAE,GAAG,eAAe,EAAE,CAcxF"}
|
package/dist/surface-bridge.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as e, c as t, d as n, f as r, i, l as a, m as o, n as s, o as c, p as l, r as u, s as d, t as f, u as p } from "./chunks/surface-bridge-
|
|
1
|
+
import { a as e, c as t, d as n, f as r, i, l as a, m as o, n as s, o as c, p as l, r as u, s as d, t as f, u as p } from "./chunks/surface-bridge-oO22We2G.js";
|
|
2
2
|
export { p as applyCodexSurfaceStateChanges, f as codexConversationBridgeOperations, s as codexSurfaceBridgeArities, u as codexSurfaceBridgeOperations, n as createCodexSurfaceStateMirror, r as diffCodexSurfaceState, i as invokeCodexConversationBridgeOperation, e as invokeCodexSurfaceBridgeOperation, c as isCodexConversationBridgeOperation, d as isCodexSurfaceBridgeOperation, l as isCodexSurfaceStatePatchSource, t as subscribeCodexConversationBridge, a as subscribeCodexConversationReplicaBridge, o as subscribeCodexSurfaceState };
|
package/dist/surface.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as e, i as t, n, o as r, r as i, t as a } from "./chunks/prompt-content-
|
|
1
|
+
import { a as e, i as t, n, o as r, r as i, t as a } from "./chunks/prompt-content-B8o5tNuN.js";
|
|
2
2
|
export { a as normalizePromptContent, n as promptContentDispatchText, i as promptContentText, t as replacePromptContentRange, e as slicePromptContent, r as trimPromptContent };
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"prompt-content-BCcHFqCj.js","names":[],"sources":["../../src/prompt-content.ts"],"sourcesContent":["/** Serializable authored content. Mentions exist only after explicit selection. */\nexport type CodexPromptMention = {\n type: 'mention';\n kind: 'skill' | 'plugin' | 'file' | 'custom';\n id: string;\n /** Exact visible chip label, without an added $ or @ prefix. */\n label: string;\n /** Selected catalog name/value; never inferred from surrounding text. */\n value: string;\n groupId?: string;\n};\n\nexport type CodexPromptPart = { type: 'text'; text: string } | CodexPromptMention;\n\nexport function promptContentText(content: readonly CodexPromptPart[]): string {\n return content.map(part => part.type === 'text' ? part.text : part.label).join('');\n}\n\nfunction skillReference(part: CodexPromptMention): string {\n const name = part.value.replace(/[\\\\[\\]]/g, '\\\\$&');\n const path = encodeURI(part.id).replace(/[()#?]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);\n return `[$${name}](${path})`;\n}\n\n/** Model-facing references. An optional prompt retains context after its authored prefix. */\nexport function promptContentDispatchText(content: readonly CodexPromptPart[], prompt?: string): string {\n const text = content.map(part => part.type === 'text' ? part.text\n : part.kind === 'skill' ? skillReference(part)\n : part.kind === 'file' ? `@${part.id}` : `@${part.value}`).join('');\n if (prompt === undefined) return text;\n const visible = promptContentText(content);\n if (prompt.startsWith(text) || !prompt.startsWith(visible)) return prompt;\n return text + prompt.slice(visible.length);\n}\n\n/** Offsets are UTF-16 visible-text offsets, as in JavaScript strings and DOM selections. */\nexport function slicePromptContent(content: readonly CodexPromptPart[], start: number, end = promptContentText(content).length): CodexPromptPart[] {\n let offset = 0;\n return normalizePromptContent(content).flatMap((part): CodexPromptPart[] => {\n const text = part.type === 'text' ? part.text : part.label;\n const from = Math.max(0, start - offset);\n const to = Math.min(text.length, end - offset);\n offset += text.length;\n if (from >= to) return [];\n return part.type === 'mention' && from === 0 && to === text.length\n ? [part] : [{ type: 'text', text: text.slice(from, to) }];\n });\n}\n\nexport function replacePromptContentRange(\n content: readonly CodexPromptPart[], start: number, end: number, replacement: readonly CodexPromptPart[],\n): CodexPromptPart[] {\n return normalizePromptContent([...slicePromptContent(content, 0, start), ...normalizePromptContent(replacement), ...slicePromptContent(content, Math.max(start, end))]);\n}\n\n/** Validate and copy content at transport and persisted-message boundaries. */\nexport function normalizePromptContent(content: unknown): CodexPromptPart[] {\n if (!Array.isArray(content)) throw new Error('Prompt content must be an array');\n const parts = content.map((part: unknown): CodexPromptPart => {\n if (!part || typeof part !== 'object') throw new Error('Invalid prompt content part');\n const value = part as Record<string, unknown>;\n if (value.type === 'text' && typeof value.text === 'string') return { type: 'text', text: value.text };\n if (value.type !== 'mention' || !['skill', 'plugin', 'file', 'custom'].includes(value.kind as string)\n || !['id', 'label', 'value'].every(key => typeof value[key] === 'string' && value[key] !== '')\n || (value.groupId !== undefined && typeof value.groupId !== 'string')) {\n throw new Error('Invalid prompt mention');\n }\n return {\n type: 'mention', kind: value.kind as CodexPromptMention['kind'],\n id: value.id as string, label: value.label as string, value: value.value as string,\n ...(value.groupId === undefined ? {} : { groupId: value.groupId as string }),\n };\n });\n const normalized: CodexPromptPart[] = [];\n for (const part of parts) {\n const previous = normalized.at(-1);\n if (part.type === 'text') {\n if (!part.text) continue;\n if (previous?.type === 'text') { previous.text += part.text; continue; }\n }\n normalized.push(part);\n }\n return normalized;\n}\n\nexport function trimPromptContent(content: readonly CodexPromptPart[]): CodexPromptPart[] {\n const parts = normalizePromptContent(content);\n while (parts[0]?.type === 'text') {\n parts[0].text = parts[0].text.trimStart();\n if (parts[0].text) break;\n parts.shift();\n }\n while (parts.at(-1)?.type === 'text')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