@opengeni/sdk 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -3
- package/dist/adapters/next.js +2 -2
- package/dist/artifacts.js +4 -4
- package/dist/azure-live-transport.d.ts +32 -0
- package/dist/browser.js +3 -3
- package/dist/chat/index.js +5 -5
- package/dist/{chunk-RSKO3CMZ.js → chunk-BVIIRSJY.js} +2 -2
- package/dist/{chunk-G5NZGPTB.js → chunk-CA2T7QT4.js} +2 -2
- package/dist/{chunk-ZBICMU4Z.js → chunk-D534PIXF.js} +2 -2
- package/dist/{chunk-CNSPJYF6.js → chunk-FYQAMXDW.js} +104 -5
- package/dist/chunk-FYQAMXDW.js.map +1 -0
- package/dist/{chunk-IB6SUE3R.js → chunk-GYM54GKM.js} +1 -1
- package/dist/chunk-GYM54GKM.js.map +1 -0
- package/dist/{chunk-VYCTL62C.js → chunk-GZQSWAKD.js} +1 -1
- package/dist/chunk-GZQSWAKD.js.map +1 -0
- package/dist/{chunk-CREM7YRK.js → chunk-LEBDXYMA.js} +2 -2
- package/dist/{chunk-YVH2PH4X.js → chunk-MXV5O25O.js} +2 -2
- package/dist/{chunk-2UXZUCEZ.js → chunk-ZNC44QEX.js} +77 -7
- package/dist/chunk-ZNC44QEX.js.map +1 -0
- package/dist/codex-realtime-controller.d.ts +13 -0
- package/dist/codex-realtime-controller.js +3 -1
- package/dist/codex-realtime-v3-wire.d.ts +3 -2
- package/dist/codex-realtime.d.ts +4 -0
- package/dist/core.js +4 -4
- package/dist/document-authority.js +3 -3
- package/dist/editable-artifacts.js +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +55 -18
- package/dist/index.js.map +1 -1
- package/dist/realtime.d.ts +1 -1
- package/dist/realtime.js +248 -2
- package/dist/realtime.js.map +1 -1
- package/dist/session-proxy-client.d.ts +7 -3
- package/dist/session-proxy.d.ts +9 -1
- package/dist/session-proxy.js +2 -2
- package/dist/site.js +3 -3
- package/dist/transcription.d.ts +1 -1
- package/dist/types.d.ts +30 -8
- package/package.json +3 -3
- package/src/azure-live-transport.ts +286 -0
- package/src/codex-realtime-controller.ts +95 -2
- package/src/codex-realtime-v3-wire.ts +4 -3
- package/src/codex-realtime-v3.ts +11 -2
- package/src/codex-realtime.ts +9 -1
- package/src/index.ts +3 -0
- package/src/realtime.ts +15 -6
- package/src/session-proxy-client.ts +7 -3
- package/src/session-proxy.ts +137 -4
- package/src/transcription.ts +3 -0
- package/src/types.ts +34 -5
- package/dist/chunk-2UXZUCEZ.js.map +0 -1
- package/dist/chunk-CNSPJYF6.js.map +0 -1
- package/dist/chunk-IB6SUE3R.js.map +0 -1
- package/dist/chunk-VYCTL62C.js.map +0 -1
- /package/dist/{chunk-RSKO3CMZ.js.map → chunk-BVIIRSJY.js.map} +0 -0
- /package/dist/{chunk-G5NZGPTB.js.map → chunk-CA2T7QT4.js.map} +0 -0
- /package/dist/{chunk-ZBICMU4Z.js.map → chunk-D534PIXF.js.map} +0 -0
- /package/dist/{chunk-CREM7YRK.js.map → chunk-LEBDXYMA.js.map} +0 -0
- /package/dist/{chunk-YVH2PH4X.js.map → chunk-MXV5O25O.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../contracts/src/tool-review-presentation.ts","../../contracts/src/mcp-endpoint.ts","../src/tool-display-metadata.ts","../src/mcp-output.ts","../src/desktop.ts","../src/terminal.ts","../src/workspace-instruction-policies.ts","../src/company-profile.ts","../src/company-brain.ts","../src/preference-registry.ts"],"sourcesContent":["import type {\n ToolActionReview,\n ToolReviewContext,\n ToolReviewDetailsPage,\n} from \"./tool-action-review\";\n\nconst protectedName =\n /password|passwd|secret|credential|authorization|cookie|(^|[_-])token($|[_-])|api[_-]?key|accessToken|refreshToken|privateKey/i;\nconst protectedReviewField = (key: string, fields: readonly string[] = []) =>\n protectedName.test(key) || fields.includes(key) || fields.includes(\"*\");\nconst bound = (value: string, limit: number) =>\n value.length > limit ? `${value.slice(0, limit)}…` : value;\nexport function toolReviewFieldLabel(key: string): string {\n const label = key\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[_-]+/g, \" \")\n .replace(/\\bids?\\b/gi, (word) => (word.length === 3 ? \"IDs\" : \"ID\"));\n return label.charAt(0).toUpperCase() + label.slice(1);\n}\nexport function decodeReviewArguments(value: unknown): Record<string, unknown> | null {\n // Historical SDK entries sometimes wrapped arguments in JSON. Decode only once.\n let decoded = value;\n if (typeof decoded === \"string\") {\n try {\n decoded = JSON.parse(decoded);\n } catch {\n return null;\n }\n }\n return decoded && typeof decoded === \"object\" && !Array.isArray(decoded)\n ? (decoded as Record<string, unknown>)\n : null;\n}\nexport function safeReviewValue(\n value: unknown,\n key = \"\",\n protectedFields: readonly string[] = [],\n depth = 0,\n): unknown {\n if (protectedReviewField(key, protectedFields)) return \"[Protected value]\";\n if (depth > 20) return \"[Nested value; open this field for details]\";\n if (Array.isArray(value))\n return value.map((entry) => safeReviewValue(entry, \"\", protectedFields, depth + 1));\n if (value && typeof value === \"object\")\n return Object.fromEntries(\n Object.entries(value).map(([name, entry]) => [\n name,\n safeReviewValue(entry, name, protectedFields, depth + 1),\n ]),\n );\n return value;\n}\nfunction valueText(value: unknown): string {\n return typeof value === \"string\"\n ? value\n : value === null\n ? \"None\"\n : typeof value === \"boolean\"\n ? value\n ? \"Yes\"\n : \"No\"\n : (JSON.stringify(value) ?? \"Unavailable\");\n}\nconst pointer = (name: string) => `/${name.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\")}`;\n// Long arbitrary property names remain readable without placing them in every\n// preview or URL. An indexed segment opens their saved name and value together.\nconst fieldPointer = (key: string, index: number, parent = \"\") =>\n pointer(key).length > 256 || parent.length + pointer(key).length > 1024\n ? `/~2${index}`\n : pointer(key);\n\nexport function toolReviewFields(\n argumentsValue: unknown,\n context?: ToolReviewContext,\n): { fields: ToolActionReview[\"fields\"]; moreFields: number } {\n const args = decodeReviewArguments(argumentsValue);\n if (!args) return { fields: [], moreFields: 0 };\n const entries = Object.entries(args);\n if (context?.email) {\n const email = toolReviewFields(context.email);\n const original = toolReviewFields(args, { ...context, email: undefined });\n const fields = [\n ...email.fields\n .filter(\n (field) =>\n field.path !== \"/contentSha256\" && field.path !== \"/htmlBody\" && field.preview !== \"\",\n )\n .map((field) => ({ ...field, path: `/$email${field.path}` })),\n ...original.fields,\n ];\n return {\n fields: fields.slice(0, 16),\n moreFields: original.moreFields + Math.max(0, fields.length - 16),\n };\n }\n return {\n moreFields: Math.max(0, entries.length - 16),\n fields: entries.slice(0, 16).map(([key, value], index) => {\n const hidden = protectedReviewField(key, context?.protectedFields);\n const safe = hidden ? \"[Protected value]\" : value;\n const count = Array.isArray(value) ? value.length : undefined;\n const text =\n count !== undefined\n ? `${count.toLocaleString(\"en-US\")} item${count === 1 ? \"\" : \"s\"}`\n : safe && typeof safe === \"object\"\n ? `${Object.keys(safe).length} field${Object.keys(safe).length === 1 ? \"\" : \"s\"}`\n : valueText(safe);\n return {\n path: fieldPointer(key, index),\n label: bound(\n (context?.fieldLabels && Object.hasOwn(context.fieldLabels, key)\n ? context.fieldLabels[key]\n : undefined) ?? toolReviewFieldLabel(key),\n 256,\n ),\n preview: bound(text, 240),\n ...(count !== undefined ? { count } : {}),\n truncated: !hidden && (text.length > 240 || (typeof value === \"object\" && value !== null)),\n ...(hidden ? { protected: true } : {}),\n };\n }),\n };\n}\n\n/** Deterministic consequences from the reviewed bytes. Unknown fields remain visible. */\nexport function toolReviewAction(\n toolName: string,\n argumentsValue: unknown,\n context?: ToolReviewContext,\n): Pick<\n ToolActionReview,\n \"title\" | \"approveLabel\" | \"effects\" | \"consequence\" | \"selectionCount\" | \"selectionKind\"\n> {\n const fallback = {\n title: context?.title ?? bound(toolReviewFieldLabel(toolName.replace(/^mcp_[^_]+__/, \"\")), 256),\n approveLabel: \"Approve action\",\n effects: [] as string[],\n };\n if (context?.kind !== \"gmail\") return fallback;\n const args = decodeReviewArguments(argumentsValue);\n if (!args) return fallback;\n const thread = toolName.endsWith(\"_thread\");\n const selectionKind = thread ? (\"threads\" as const) : (\"messages\" as const);\n const ids =\n thread && typeof args.threadId === \"string\"\n ? [args.threadId]\n : Array.isArray(args.messageIds)\n ? args.messageIds\n : typeof args.messageId === \"string\"\n ? [args.messageId]\n : null;\n const selectionCount = ids?.every((id) => typeof id === \"string\") ? new Set(ids).size : undefined;\n const noun =\n selectionCount === undefined\n ? selectionKind\n : `${selectionCount.toLocaleString(\"en-US\")} ${thread ? \"thread\" : \"message\"}${selectionCount === 1 ? \"\" : \"s\"}`;\n const addValues = toolName.startsWith(\"label_\") ? args.labelIds : args.addLabelIds;\n const adds = Array.isArray(addValues)\n ? addValues.filter((v): v is string => typeof v === \"string\")\n : [];\n const removeValues = toolName.startsWith(\"unlabel_\") ? args.labelIds : args.removeLabelIds;\n const removes = Array.isArray(removeValues)\n ? removeValues.filter((v): v is string => typeof v === \"string\")\n : [];\n const labelEffect = (label: string, adding: boolean): string => {\n const known: Record<string, [string, string]> = {\n TRASH: [\"Move to Trash\", \"Remove from Trash\"],\n INBOX: [\"Move to Inbox\", \"Remove from Inbox\"],\n UNREAD: [\"Mark as unread\", \"Mark as read\"],\n STARRED: [\"Add star\", \"Remove star\"],\n SPAM: [\"Mark as spam\", \"Remove from Spam\"],\n IMPORTANT: [\"Mark as important\", \"Remove importance\"],\n };\n return (\n (Object.hasOwn(known, label) ? known[label]?.[adding ? 0 : 1] : undefined) ??\n `${adding ? \"Add\" : \"Remove\"} label ${bound(label, 120)}`\n );\n };\n const effects = [\n ...adds.map((id) => labelEffect(id, true)),\n ...removes.map((id) => labelEffect(id, false)),\n ];\n if (\n [\n \"batch_modify_messages\",\n \"modify_message\",\n \"modify_thread\",\n \"label_message\",\n \"label_thread\",\n \"unlabel_message\",\n \"unlabel_thread\",\n ].includes(toolName)\n ) {\n const trash = adds.includes(\"TRASH\");\n return {\n title: trash ? `Move ${noun} to Trash` : `Update ${noun}`,\n approveLabel: trash ? \"Move to Trash\" : \"Apply changes\",\n effects,\n ...(selectionCount === undefined ? {} : { selectionCount, selectionKind }),\n ...(trash\n ? { consequence: \"Messages stay recoverable in Trash until Gmail deletes them.\" }\n : thread\n ? { consequence: \"Applies to every message in the selected thread.\" }\n : {}),\n };\n }\n if ([\"trash_message\", \"restore_message\", \"trash_thread\", \"restore_thread\"].includes(toolName))\n return {\n title: toolName.startsWith(\"trash_\") ? `Move ${noun} to Trash` : `Remove ${noun} from Trash`,\n approveLabel: toolName.startsWith(\"trash_\") ? \"Move to Trash\" : \"Remove from Trash\",\n effects,\n ...(selectionCount === undefined ? {} : { selectionCount, selectionKind }),\n };\n const named: Record<string, [string, string]> = {\n send_message: [\"Send email\", \"Send email\"],\n send_draft: [\"Send draft\", \"Send draft\"],\n create_draft: [\"Create email draft\", \"Create draft\"],\n update_draft: [\"Update email draft\", \"Update draft\"],\n delete_draft: [\"Delete email draft\", \"Delete draft\"],\n create_label: [\"Create label\", \"Create label\"],\n update_label: [\"Update label\", \"Update label\"],\n delete_label: [\"Delete label\", \"Delete label\"],\n };\n const action = Object.hasOwn(named, toolName) ? named[toolName] : undefined;\n return action ? { title: action[0], approveLabel: action[1], effects } : fallback;\n}\n\n/** A bounded slice of the immutable saved arguments; never evaluates a fresh provider query. */\nexport function toolReviewDetails(\n argumentsValue: unknown,\n context: ToolReviewContext | undefined,\n path: string,\n offset: number,\n limit = 25,\n): Omit<ToolReviewDetailsPage, \"id\" | \"actionDigest\" | \"version\"> {\n if (\n !Number.isSafeInteger(offset) ||\n offset < 0 ||\n !Number.isSafeInteger(limit) ||\n limit < 1 ||\n limit > 50\n )\n throw new Error(\"Invalid review page\");\n const args = decodeReviewArguments(argumentsValue);\n let value: unknown = context?.email ? { ...args, $email: context.email } : args;\n if (path !== \"\") {\n if (!path.startsWith(\"/\")) throw new Error(\"Invalid review field\");\n for (const escaped of path.slice(1).split(\"/\")) {\n if (/^~2\\d+$/.test(escaped)) {\n if (!value || typeof value !== \"object\" || Array.isArray(value))\n throw new Error(\"Review field not found\");\n const selected = Object.entries(value)[Number(escaped.slice(2))];\n if (!selected) throw new Error(\"Review field not found\");\n value = {\n fieldName: selected[0],\n value: protectedReviewField(selected[0], context?.protectedFields)\n ? \"[Protected value]\"\n : selected[1],\n };\n continue;\n }\n const key = escaped.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n if (protectedReviewField(key, context?.protectedFields)) {\n value = \"[Protected value]\";\n break;\n }\n if (!value || typeof value !== \"object\" || !Object.hasOwn(value, key))\n throw new Error(\"Review field not found\");\n value = (value as Record<string, unknown>)[key];\n }\n }\n type DetailItem = ToolReviewDetailsPage[\"items\"][number];\n const preview = (\n entry: unknown,\n key: string,\n childPath: string,\n ): Pick<DetailItem, \"value\" | \"truncated\" | \"path\"> => {\n const hidden = protectedReviewField(key, context?.protectedFields);\n if (!hidden && entry !== null && typeof entry === \"object\") {\n const count = Array.isArray(entry) ? entry.length : Object.keys(entry).length;\n return {\n value: `${count.toLocaleString(\"en-US\")} ${Array.isArray(entry) ? (count === 1 ? \"item\" : \"items\") : count === 1 ? \"field\" : \"fields\"}`,\n path: childPath,\n truncated: true,\n };\n }\n const text = valueText(safeReviewValue(entry, key, context?.protectedFields));\n return {\n value: bound(text, 4000),\n ...(hidden ? {} : { path: childPath }),\n truncated: !hidden && text.length > 4000,\n };\n };\n let total: number;\n let items: DetailItem[];\n if (Array.isArray(value)) {\n total = value.length;\n items = value.slice(offset, offset + limit).map((entry, index) => ({\n label: `${offset + index + 1}`,\n ...preview(entry, \"\", `${path}/${offset + index}`),\n }));\n } else if (value && typeof value === \"object\") {\n const entries = Object.entries(value);\n total = entries.length;\n items = entries.slice(offset, offset + limit).map(([key, entry], index) => ({\n label: bound(\n (context?.fieldLabels && Object.hasOwn(context.fieldLabels, key)\n ? context.fieldLabels[key]\n : undefined) ?? toolReviewFieldLabel(key),\n 256,\n ),\n ...preview(entry, key, `${path}${fieldPointer(key, offset + index, path)}`),\n }));\n } else {\n const text = valueText(value);\n total = Math.max(1, Math.ceil(text.length / 4000));\n items = Array.from({ length: Math.max(0, Math.min(limit, total - offset)) }, (_, index) => ({\n label: `Part ${offset + index + 1}`,\n value: text.slice((offset + index) * 4000, (offset + index + 1) * 4000),\n }));\n }\n return { path, items, total, nextOffset: offset + limit < total ? offset + limit : null };\n}\n","/** Exact endpoint identity: normalize URL syntax, preserve paths and query parameters. */\nexport function mcpEndpointIdentity(value: string | null | undefined): string | null {\n if (!value) return null;\n try {\n const url = new URL(value);\n if (![\"https:\", \"http:\"].includes(url.protocol) || url.username || url.password) return null;\n url.hash = \"\";\n return url.href;\n } catch {\n return null;\n }\n}\n\nexport function pluginMcpUnavailableReason(server: {\n endpoint: string | null;\n transport?: string;\n requiresConfiguration?: boolean;\n}): string | null {\n if (server.transport === \"stdio\" || !server.endpoint) return \"Requires a local runtime\";\n if (\n server.transport &&\n ![\"http\", \"streamable-http\", \"streamable_http\"].includes(server.transport)\n )\n return \"Unsupported transport: \" + server.transport;\n if (server.requiresConfiguration || server.endpoint.includes(\"{\"))\n return \"Requires custom connection configuration\";\n const endpoint = mcpEndpointIdentity(server.endpoint);\n if (!endpoint?.startsWith(\"https://\")) return \"Requires a valid HTTPS endpoint\";\n return null;\n}\n","import type { ToolDisplayMetadata } from \"@opengeni/contracts\";\n\n/** Browser/native-safe event projection; do not import server schema runtimes. */\nexport function parseToolDisplayMetadata(value: unknown): ToolDisplayMetadata | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const item = value as Record<string, unknown>;\n if (Object.keys(item).some((key) => ![\"toolName\", \"title\", \"accountLabel\"].includes(key)))\n return undefined;\n const text = (v: unknown, max: number): v is string =>\n typeof v === \"string\" && v.length > 0 && v.length <= max;\n if (!text(item.toolName, 512) || /[\\u0000-\\u001f\\u007f]/u.test(item.toolName)) return undefined;\n if (item.title !== undefined && !text(item.title, 512)) return undefined;\n if (item.accountLabel !== undefined && !text(item.accountLabel, 1024)) return undefined;\n return {\n toolName: item.toolName,\n ...(item.title !== undefined ? { title: item.title as string } : {}),\n ...(item.accountLabel !== undefined ? { accountLabel: item.accountLabel as string } : {}),\n };\n}\n","/**\n * A transport-tolerant MCP tool result.\n *\n * `value` is the canonical machine-readable payload after recognized MCP/JSON\n * envelopes are removed. `text` is the best presentation string without\n * discarding structured data. `raw` always retains the original evidence.\n */\nexport type NormalizedMcpOutput = Readonly<{\n raw: unknown;\n value: unknown;\n text: string;\n isError: boolean;\n}>;\n\nconst MAX_MCP_OUTPUT_DEPTH = 8;\nconst RESULT_ENVELOPE_KEYS = new Set([\"result\", \"isError\", \"jsonrpc\", \"id\", \"_meta\"]);\n\n/** Normalize common direct, JSON, and standard MCP result envelopes without throwing. */\nexport function normalizeMcpOutput(output: unknown): NormalizedMcpOutput {\n const normalized = normalizeValue(output, 0, new Set<object>());\n return {\n raw: output,\n value: normalized.value,\n text: normalized.text,\n isError: normalized.isError,\n };\n}\n\ntype NormalizedValue = Omit<NormalizedMcpOutput, \"raw\">;\n\nfunction normalizeValue(value: unknown, depth: number, ancestors: Set<object>): NormalizedValue {\n if (value === null || value === undefined) {\n return { value, text: \"\", isError: false };\n }\n if (typeof value === \"string\") {\n return normalizeText(value, depth, ancestors);\n }\n if (typeof value !== \"object\") {\n return { value, text: String(value), isError: false };\n }\n if (depth >= MAX_MCP_OUTPUT_DEPTH || ancestors.has(value)) {\n return { value, text: safeStringify(value), isError: false };\n }\n\n ancestors.add(value);\n try {\n if (Array.isArray(value)) {\n return { value, text: safeStringify(value), isError: false };\n }\n\n const record = value as Record<string, unknown>;\n const envelopeError = record.isError === true;\n\n if (record.type === \"text\" && typeof record.text === \"string\") {\n const normalized = normalizeText(record.text, depth + 1, ancestors);\n return {\n value: normalized.value,\n text: record.text,\n isError: envelopeError || normalized.isError,\n };\n }\n\n if (\"structuredContent\" in record) {\n const normalized = normalizeValue(record.structuredContent, depth + 1, ancestors);\n return {\n value: normalized.value,\n text: firstMcpText(record.content) ?? normalized.text,\n isError: envelopeError || normalized.isError,\n };\n }\n\n if (isMcpContent(record.content)) {\n const text = firstMcpText(record.content);\n if (text !== null) {\n const normalized = normalizeText(text, depth + 1, ancestors);\n return {\n value: normalized.value,\n text,\n isError: envelopeError || normalized.isError,\n };\n }\n return {\n value,\n text: safeStringify(value),\n isError: envelopeError,\n };\n }\n\n if (isResultEnvelope(record)) {\n const normalized = normalizeValue(record.result, depth + 1, ancestors);\n return {\n value: normalized.value,\n text: normalized.text,\n isError: envelopeError || normalized.isError,\n };\n }\n\n return {\n value,\n text: safeStringify(value),\n isError: envelopeError,\n };\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction normalizeText(text: string, depth: number, ancestors: Set<object>): NormalizedValue {\n try {\n const parsed: unknown = JSON.parse(text);\n const normalized = normalizeValue(parsed, depth + 1, ancestors);\n return {\n value: normalized.value,\n text,\n isError: normalized.isError,\n };\n } catch {\n return { value: text, text, isError: false };\n }\n}\n\nfunction isMcpContent(value: unknown): value is readonly Record<string, unknown>[] {\n return (\n Array.isArray(value) &&\n value.some(\n (part) =>\n part !== null &&\n typeof part === \"object\" &&\n typeof (part as { type?: unknown }).type === \"string\",\n )\n );\n}\n\nfunction firstMcpText(value: unknown): string | null {\n if (!Array.isArray(value)) {\n return null;\n }\n for (const part of value) {\n if (\n part !== null &&\n typeof part === \"object\" &&\n (part as { type?: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n return (part as { text: string }).text;\n }\n }\n return null;\n}\n\nfunction isResultEnvelope(record: Record<string, unknown>): boolean {\n return \"result\" in record && Object.keys(record).every((key) => RESULT_ENVELOPE_KEYS.has(key));\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? \"\";\n } catch {\n return String(value);\n }\n}\n","// Zero-dependency desktop (noVNC) transport contract.\n//\n// The actual `@novnc/novnc` RFB import is a browser-only DOM dependency and\n// lives in `@opengeni/react` (lazily imported, SSR-safe). The framework-agnostic\n// SDK ships only the transport CONTRACT: a URL assembler, the minimal RFB\n// surface the component drives, the connection state machine, and the\n// rotation/fence reducers — all pure and unit-testable, with no DOM and no deps.\n//\n// Channel A (terminal-as-events, files, git) needs NO new transport here: those\n// are event projections + the synchronous fs/git/terminal point queries on\n// `OpenGeniClient`. Only the desktop pixel plane (Channel B, direct-to-provider)\n// needs this.\n\nimport type { DesktopStreamCapability, StreamUrlRotatedPayload } from \"./types\";\n\n/**\n * Translate the negotiated desktop capability into the WebSocket URL the noVNC\n * RFB client connects to. The scoped provider token is ALREADY embedded in the\n * minted `url` (Modal tunnel host, Blaxel `bl_preview_token`, Daytona signed\n * preview) by `session.resolveExposedPort(6080)` — we do NOT append `cap.token`\n * as a query param (that double-auth was an adversarial-review bug: the box runs\n * `-nopw` in v1, so the RFB password is meaningless and the real auth is the\n * tunnel token in the host). We only normalize the scheme to `ws`/`wss` and, when\n * the minted URL points at a `vnc.html` viewer page, rewrite it to the\n * websockify socket path noVNC actually dials.\n */\nexport function desktopSocketUrl(cap: Pick<DesktopStreamCapability, \"url\">): string {\n if (!cap.url) {\n throw new Error(\"desktop capability has no url (transport is null)\");\n }\n const u = new URL(cap.url);\n // https → wss, http → ws (noVNC dials a WebSocket, not the HTTP viewer page).\n if (u.protocol === \"https:\") {\n u.protocol = \"wss:\";\n } else if (u.protocol === \"http:\") {\n u.protocol = \"ws:\";\n }\n // A minted `…/vnc.html` (or `…/vnc_lite.html`) viewer page → the websockify\n // socket the page itself would open (`…/websockify`). A bare host/path with no\n // viewer page is already the socket path; leave it untouched.\n if (/\\/vnc(_lite)?\\.html$/.test(u.pathname)) {\n u.pathname = u.pathname.replace(/\\/vnc(_lite)?\\.html$/, \"/websockify\");\n u.search = \"\";\n u.hash = \"\";\n }\n return u.toString();\n}\n\n/**\n * The minimal RFB surface the React component drives. Lets tests (and 3rd\n * parties swapping noVNC for a WebRTC client in v3) provide a fake without the\n * DOM. Matches `@novnc/novnc`'s RFB constructor + lifecycle.\n */\nexport interface DesktopRfbLike {\n viewOnly: boolean;\n scaleViewport: boolean;\n /**\n * 1:1 viewport clipping. We always drive this FALSE: with clipping on, noVNC\n * paints the framebuffer pixel-for-pixel and scrolls/crops to the container\n * (the \"zoomed in\" look). FALSE lets `scaleViewport` shrink the 1280x800 frame\n * to fit the panel (aspect-preserved). Declared so the hook can pin it instead\n * of relying on noVNC's default — `scaleViewport=true` forces clip off\n * internally, but a stale/partial state on reconnect could leave it on.\n */\n clipViewport: boolean;\n addEventListener(\n type: \"connect\" | \"disconnect\" | \"securityfailure\",\n cb: (e?: unknown) => void,\n ): void;\n removeEventListener?: (\n type: \"connect\" | \"disconnect\" | \"securityfailure\",\n cb: (e?: unknown) => void,\n ) => void;\n /** Send clipboard text over the already-open RFB connection. */\n clipboardPasteFrom?(text: string): void;\n /** Send one RFB key event. A missing `down` emits a complete key press. */\n sendKey?(keysym: number, code: string, down?: boolean): void;\n /** Focus or release the RFB keyboard sink without reconnecting. */\n focus?(options?: FocusOptions): void;\n blur?(): void;\n disconnect(): void;\n}\n\nexport type DesktopRfbFactory = (\n target: HTMLElement,\n url: string,\n opts: {\n credentials?: { password?: string | undefined } | undefined;\n wsProtocols?: string[] | undefined;\n },\n) => DesktopRfbLike;\n\nexport type DesktopConnectionState =\n | \"idle\"\n | \"negotiating\"\n | \"connecting\"\n | \"connected\"\n | \"rotating\"\n | \"reconnecting\"\n | \"error\"\n | \"ended\";\n\nexport type DesktopStreamEvent =\n | { type: \"negotiated\" }\n | { type: \"connected\" }\n | { type: \"disconnected\" }\n | { type: \"rotate\" }\n | { type: \"fail\" }\n | { type: \"abort\" };\n\n/**\n * Pure reducer for the desktop connection lifecycle. The component owns the RFB\n * object + DOM; this owns the transitions so they are unit-testable. Mirrors the\n * Channel-A stream reducer discipline.\n */\nexport function nextDesktopState(\n current: DesktopConnectionState,\n ev: DesktopStreamEvent,\n): DesktopConnectionState {\n switch (ev.type) {\n case \"negotiated\":\n return \"connecting\";\n case \"connected\":\n return \"connected\";\n case \"rotate\":\n return current === \"connected\" ? \"rotating\" : current;\n case \"disconnected\":\n // A deliberate teardown (ended) stays ended; everything else reconnects.\n return current === \"ended\" ? \"ended\" : \"reconnecting\";\n case \"fail\":\n return \"error\";\n case \"abort\":\n return \"ended\";\n default:\n return current;\n }\n}\n\n// `DesktopStreamCapability` is the desktop cell of `SessionCapabilities`; alias\n// it for the rotation reducer below without depending on the whole doc.\nexport type DesktopStreamCapabilityLike = {\n url: string | null;\n token: string | null;\n expiresAt: string | null;\n};\n\n/**\n * Apply a `stream.url.rotated` event onto a desktop capability, fencing on\n * leaseEpoch (split-brain). A rotation minted under an epoch the client has\n * already advanced PAST is from a superseded owner and is dropped (returns\n * null); otherwise the fresh url/token/expiresAt are folded in.\n */\nexport function applyUrlRotation<T extends DesktopStreamCapabilityLike>(\n cap: T,\n payload: StreamUrlRotatedPayload,\n knownEpoch: number,\n): T | null {\n if (payload.leaseEpoch < knownEpoch) {\n return null;\n }\n return { ...cap, url: payload.url, token: payload.token, expiresAt: payload.expiresAt };\n}\n","// Zero-dependency interactive-terminal (ttyd PTY-over-websocket) transport\n// contract. Symmetric with `desktop.ts`: the SDK ships only the pure transport\n// CONTRACT (a URL assembler + the ttyd wire-protocol frame codec), with no DOM\n// and no deps. The actual WebSocket open + xterm attach lives in `@opengeni/react`\n// (`use-terminal-stream.ts`).\n//\n// The interactive terminal is a REAL PTY streamed over the SAME Modal raw-TLS\n// tunnel as the desktop noVNC, with the SAME scoped stream-token mechanism. The\n// box bakes `ttyd` on `TERMINAL_STREAM_PORT` (7681); `session.resolveExposedPort`\n// mints the tunnel URL. The Terminal capability cell carries transport \"pty-ws\" +\n// that url + the scoped token when the box is warm and a viewer is attached.\n\nimport type { TerminalCapability } from \"./types\";\n\n/**\n * Translate the negotiated `pty-ws` Terminal capability into the WebSocket URL\n * the ttyd client dials. The scoped provider token is ALREADY embedded in the\n * minted `url` (the Modal tunnel host) by `session.resolveExposedPort(7681)` —\n * we do NOT append `cap.token` (identical posture to the desktop: the gate is the\n * unguessable short-TTL tunnel URL + the server-recorded scoped stream token; ttyd\n * runs `--writable` with no `-c` credential in v1). We only normalize the scheme\n * to `ws`/`wss`; a bare host is already the ttyd websocket endpoint.\n */\nexport function terminalSocketUrl(cap: Pick<TerminalCapability, \"url\">): string {\n if (!cap.url) {\n throw new Error(\"terminal capability has no url (transport is not pty-ws)\");\n }\n const u = new URL(cap.url);\n // https → wss, http → ws (ttyd is dialed as a WebSocket, not an HTTP page).\n if (u.protocol === \"https:\") {\n u.protocol = \"wss:\";\n } else if (u.protocol === \"http:\") {\n u.protocol = \"ws:\";\n }\n return u.toString();\n}\n\n// ── ttyd wire protocol ───────────────────────────────────────────────────────\n// ttyd frames are a single ASCII command char + payload. These mirror ttyd's\n// `protocol.h` Command enum. Client→server and server→client share the byte 0/1/2\n// values but mean different things per direction (see below).\n\n/** ttyd subprotocol — REQUIRED on the WebSocket handshake or ttyd refuses it. */\nexport const TTYD_SUBPROTOCOL = \"tty\";\n\n/** Client→server command bytes (the first char of each outbound text frame). */\nexport const TtydClientCommand = {\n /** stdin: \"0\" + raw input bytes. */\n INPUT: \"0\",\n /** window resize: \"1\" + JSON.stringify({ columns, rows }). */\n RESIZE: \"1\",\n /** flow-control pause (back-pressure): \"2\". */\n PAUSE: \"2\",\n /** flow-control resume: \"3\". */\n RESUME: \"3\",\n} as const;\n\n/** Server→client command bytes (the first char of each inbound frame). */\nexport const TtydServerCommand = {\n /** stdout/stderr: \"0\" + raw output bytes (write the rest into xterm). */\n OUTPUT: \"0\",\n /** set the window title: \"1\" + title string. */\n SET_WINDOW_TITLE: \"1\",\n /** ttyd client preferences JSON: \"2\" + json (ignored by us). */\n SET_PREFERENCES: \"2\",\n} as const;\n\n/**\n * The ttyd handshake's first frame: an auth message. ttyd expects\n * `JSON.stringify({ AuthToken })` as the FIRST text frame on the socket. We send\n * an empty token — our gate is the tunnel URL + scoped stream token, NOT a ttyd\n * `-c` basic-auth credential (which the box does not set in v1). Optional ttyd\n * `columns`/`rows` can ride this frame to seed the PTY size before the first\n * resize. Pure (string-building only) so it stays unit-testable in the SDK.\n */\nexport function ttydAuthFrame(opts?: { columns?: number; rows?: number }): string {\n const frame: { AuthToken: string; columns?: number; rows?: number } = { AuthToken: \"\" };\n if (opts?.columns && opts.columns > 0) frame.columns = opts.columns;\n if (opts?.rows && opts.rows > 0) frame.rows = opts.rows;\n return JSON.stringify(frame);\n}\n\n/** Build a client→server INPUT (stdin) frame: \"0\" + data. */\nexport function ttydInputFrame(data: string): string {\n return TtydClientCommand.INPUT + data;\n}\n\n/** Build a client→server RESIZE frame: \"1\" + JSON.stringify({ columns, rows }). */\nexport function ttydResizeFrame(columns: number, rows: number): string {\n return TtydClientCommand.RESIZE + JSON.stringify({ columns, rows });\n}\n","export const WORKSPACE_INSTRUCTION_POLICY_CONTENT_MAX_CHARS = 262_144;\n\nexport type WorkspaceInstructionPolicyKind = \"charter\" | \"policy\";\nexport type WorkspaceInstructionPolicyScope = \"global\" | \"role\";\nexport type WorkspaceInstructionPolicyProvenanceSource =\n | \"human\"\n | \"onboarding\"\n | \"agent_learning\"\n | \"knowledge_proposal\"\n | \"legacy_import\";\nexport type WorkspaceInstructionPolicyDraftProvenanceSource = Exclude<\n WorkspaceInstructionPolicyProvenanceSource,\n \"legacy_import\" | \"agent_learning\"\n>;\nexport type WorkspaceInstructionPolicyActivationType = \"activate\" | \"rollback\";\n\nexport function normalizeWorkspaceInstructionPolicyRoleKey(value: string): string {\n return value.normalize(\"NFKC\").trim().toLowerCase().replace(/\\s+/gu, \"-\").replace(/-+/g, \"-\");\n}\n\nexport type WorkspaceInstructionPolicyTarget = {\n kind: WorkspaceInstructionPolicyKind;\n scope: WorkspaceInstructionPolicyScope;\n roleKey: string | null;\n};\n\nexport type WorkspaceInstructionPolicyRevisionIdentity = {\n id: string;\n revision: number;\n contentHash: string;\n};\n\nexport type WorkspaceInstructionPolicyRevision = WorkspaceInstructionPolicyRevisionIdentity &\n WorkspaceInstructionPolicyTarget & {\n operationId: string;\n accountId: string;\n workspaceId: string;\n content: string;\n provenance: {\n source: WorkspaceInstructionPolicyProvenanceSource;\n sourceId: string | null;\n };\n supersedesRevisionId: string | null;\n createdBySubjectId: string;\n createdAt: string;\n };\n\nexport type WorkspaceInstructionPolicyHead = WorkspaceInstructionPolicyTarget & {\n workspaceId: string;\n revisionId: string;\n revision: number;\n contentHash: string;\n activationVersion: number;\n activatedAt: string;\n};\n\nexport type WorkspaceInstructionPolicyInactiveHead = WorkspaceInstructionPolicyTarget & {\n workspaceId: string;\n activationVersion: number;\n deactivatedAt: string;\n};\n\nexport type WorkspaceInstructionPolicyActivationEvent = WorkspaceInstructionPolicyTarget & {\n id: string;\n operationId: string;\n accountId: string;\n workspaceId: string;\n type: WorkspaceInstructionPolicyActivationType;\n activationVersion: number;\n oldRevision: WorkspaceInstructionPolicyRevisionIdentity | null;\n newRevision: WorkspaceInstructionPolicyRevisionIdentity;\n actorSubjectId: string;\n reason: string;\n createdAt: string;\n};\n\nexport type WorkspaceInstructionPolicyDeactivationEvent = WorkspaceInstructionPolicyTarget & {\n id: string;\n operationId: string;\n accountId: string;\n workspaceId: string;\n type: \"automatic_deactivate\";\n activationVersion: number;\n oldRevision: WorkspaceInstructionPolicyRevisionIdentity;\n actorSubjectId: string;\n reason: string;\n createdAt: string;\n};\n\nexport type CreateWorkspaceInstructionPolicyDraftRequest = WorkspaceInstructionPolicyTarget & {\n operationId?: string;\n content: string;\n provenanceSource?: WorkspaceInstructionPolicyDraftProvenanceSource;\n provenanceSourceId?: string | null;\n supersedesRevisionId?: string | null;\n};\n\nexport type ImportLegacyWorkspaceInstructionPolicyDraftRequest = {\n operationId?: string;\n supersedesRevisionId?: string | null;\n};\n\nexport type WorkspaceInstructionPolicyListOptions = {\n kind?: WorkspaceInstructionPolicyKind;\n scope?: WorkspaceInstructionPolicyScope;\n roleKey?: string;\n afterRevision?: number;\n limit?: number;\n};\n\nexport type WorkspaceInstructionPolicyListResponse = {\n revisions: WorkspaceInstructionPolicyRevision[];\n activeHeads: WorkspaceInstructionPolicyHead[];\n /** Additive current inactive target boundaries; absent on pre-controller servers. */\n inactiveHeads?: WorkspaceInstructionPolicyInactiveHead[];\n inactiveHeadsTruncated?: boolean;\n activationEvents: WorkspaceInstructionPolicyActivationEvent[];\n /** Additive lifecycle history; absent on pre-controller servers. */\n deactivationEvents?: WorkspaceInstructionPolicyDeactivationEvent[];\n nextAfterRevision: number | null;\n};\n\nexport type WorkspaceInstructionPolicyDiffRequest = {\n fromRevisionId: string;\n toRevisionId: string;\n};\n\nexport type WorkspaceInstructionPolicyDiffResponse = {\n from: WorkspaceInstructionPolicyRevision;\n to: WorkspaceInstructionPolicyRevision;\n format: \"unified\";\n diff: string;\n};\n\nexport type ActivateWorkspaceInstructionPolicyRequest = {\n operationId?: string;\n expectedCurrentRevisionId: string | null;\n expectedActivationVersion?: number;\n reason: string;\n};\n\nexport type RollbackWorkspaceInstructionPolicyRequest = {\n operationId?: string;\n targetRevisionId: string;\n expectedCurrentRevisionId: string;\n expectedActivationVersion?: number;\n reason: string;\n};\n\nexport type WorkspaceInstructionPolicyActivationResponse = {\n head: WorkspaceInstructionPolicyHead;\n event: WorkspaceInstructionPolicyActivationEvent;\n};\n\nexport type WorkspaceInstructionPolicyConflictResponse = {\n code: \"WORKSPACE_INSTRUCTION_POLICY_CONFLICT\";\n message: string;\n currentHead: WorkspaceInstructionPolicyHead | null;\n};\n\nexport type WorkspaceInstructionPolicyOperationReuseResponse = {\n code: \"WORKSPACE_INSTRUCTION_POLICY_OPERATION_REUSED\";\n message: string;\n};\n\nexport type WorkspaceInstructionPolicyOnboardingProposalSource = {\n id: string;\n version: string;\n confidenceBps: number;\n};\n\nexport type CreateWorkspaceInstructionPolicyOnboardingProposalRequest =\n WorkspaceInstructionPolicyTarget & {\n operationId?: string;\n content: string;\n sourceId: string;\n sourceVersion: string;\n confidenceBps: number;\n expectedCurrentRevisionId: string | null;\n expectedActivationVersion: number;\n };\n\nexport type WorkspaceInstructionPolicyOnboardingProposal = WorkspaceInstructionPolicyTarget & {\n id: string;\n operationId: string;\n accountId: string;\n workspaceId: string;\n source: WorkspaceInstructionPolicyOnboardingProposalSource;\n baseline: WorkspaceInstructionPolicyHead | null;\n draft: WorkspaceInstructionPolicyRevision;\n status: \"proposed\";\n createdBySubjectId: string;\n createdAt: string;\n};\n\nexport type WorkspaceInstructionPolicyOnboardingProposalListOptions = {\n limit?: number;\n};\n\nexport type WorkspaceInstructionPolicyOnboardingProposalListResponse = {\n proposals: WorkspaceInstructionPolicyOnboardingProposal[];\n truncated: boolean;\n};\n\nexport type WorkspaceInstructionPolicyOnboardingProposalContentErrorResponse = {\n code:\n | \"WORKSPACE_INSTRUCTION_POLICY_ONBOARDING_PROPOSAL_EMPTY\"\n | \"WORKSPACE_INSTRUCTION_POLICY_ONBOARDING_PROPOSAL_OVERSIZED\";\n message: string;\n maxChars: number;\n};\n\nexport type WorkspaceInstructionPolicyOnboardingProposalStaleResponse = {\n code: \"WORKSPACE_INSTRUCTION_POLICY_ONBOARDING_PROPOSAL_STALE\";\n message: string;\n currentHead: WorkspaceInstructionPolicyHead | null;\n};\n\nexport type WorkspaceInstructionPolicyOnboardingProposalConflictResponse = {\n code: \"WORKSPACE_INSTRUCTION_POLICY_ONBOARDING_PROPOSAL_CONFLICT\";\n message: string;\n existingProposalId: string;\n existingDraftRevisionId: string;\n};\n","export const COMPANY_PROFILE_SCALAR_MAX_CHARS = 2_048;\nexport const COMPANY_PROFILE_ENTRY_MAX_CHARS = 1_024;\nexport const COMPANY_PROFILE_ENTRY_MAX_COUNT = 16;\n\nexport type CompanyProfileEntry = { key: string; content: string };\nexport type CompanyProfileContent = {\n identity: string | null;\n mission: string | null;\n products: CompanyProfileEntry[];\n customers: CompanyProfileEntry[];\n goals: CompanyProfileEntry[];\n constraints: CompanyProfileEntry[];\n};\nexport type CompanyProfileRevisionIdentity = {\n id: string;\n revision: number;\n contentHash: string;\n};\nexport type CompanyProfileRevision = CompanyProfileRevisionIdentity & {\n operationId: string;\n accountId: string;\n intent: \"active\" | \"proposal\";\n profile: CompanyProfileContent;\n provenance: {\n source: \"human\" | \"agent_admin\" | \"durable_learning\" | \"migration\";\n sourceId: string | null;\n };\n supersedesRevisionId: string | null;\n createdBySubjectId: string;\n createdAt: string;\n};\nexport type CompanyProfileHead = {\n accountId: string;\n revisionId: string;\n revision: number;\n contentHash: string;\n activationVersion: number;\n activatedAt: string;\n};\nexport type CompanyProfileActivationEvent = {\n id: string;\n operationId: string;\n accountId: string;\n type: \"activate\" | \"rollback\";\n activationVersion: number;\n oldRevision: CompanyProfileRevisionIdentity | null;\n newRevision: CompanyProfileRevisionIdentity | null;\n actorSubjectId: string;\n reason: string;\n createdAt: string;\n};\nexport type CompanyProfileListOptions = { afterRevision?: number; limit?: number };\nexport type CompanyProfileListResponse = {\n current: CompanyProfileHead | null;\n activeRevision: CompanyProfileRevision | null;\n revisions: CompanyProfileRevision[];\n activationEvents: CompanyProfileActivationEvent[];\n nextAfterRevision: number | null;\n};\nexport type UpdateCompanyProfileRequest = {\n operationId?: string;\n profile: CompanyProfileContent;\n expectedCurrentRevisionId: string | null;\n expectedActivationVersion: number;\n reason: string;\n};\nexport type ActivateCompanyProfileRevisionRequest = {\n operationId?: string;\n expectedCurrentRevisionId: string | null;\n expectedActivationVersion: number;\n reason: string;\n};\nexport type RollbackCompanyProfileRequest = {\n operationId?: string;\n targetRevisionId: string;\n expectedCurrentRevisionId: string;\n expectedActivationVersion: number;\n reason: string;\n};\nexport type CompanyProfileMutationResponse = {\n revision: CompanyProfileRevision | null;\n head: CompanyProfileHead | null;\n event: CompanyProfileActivationEvent | null;\n};\nexport type CompanyProfileAgentPolicyMode = \"off\" | \"suggest\" | \"automatic\";\nexport type CompanyProfileAgentPolicy = {\n organizationId: string;\n mode: CompanyProfileAgentPolicyMode;\n version: number;\n updatedAt: string;\n changed?: boolean;\n};\nexport type UpdateCompanyProfileAgentPolicyRequest = {\n mode: CompanyProfileAgentPolicyMode;\n expectedVersion: number;\n operationId: string;\n};\nexport type CompanyProfileDiffRequest = { fromRevisionId: string; toRevisionId: string };\nexport type CompanyProfileDiffResponse = {\n from: CompanyProfileRevision;\n to: CompanyProfileRevision;\n format: \"unified_json\";\n diff: string;\n};\n\nexport function normalizeCompanyProfileStableKey(value: string): string {\n return value.normalize(\"NFKC\").trim().toLowerCase().replace(/\\s+/gu, \"-\").replace(/-+/g, \"-\");\n}\n","import type {\n CompanyBrainContextReceiptPage as ContractCompanyBrainContextReceiptPage,\n CompanyBrainKnowledgeProposalPage as ContractCompanyBrainKnowledgeProposalPage,\n CompanyBrainOkfPackage as ContractCompanyBrainOkfPackage,\n} from \"@opengeni/contracts\";\n\nexport type CompanyBrainOkfPackage = ContractCompanyBrainOkfPackage;\nexport type CompanyBrainContextReceiptPage = ContractCompanyBrainContextReceiptPage;\nexport type CompanyBrainKnowledgeProposalPage = ContractCompanyBrainKnowledgeProposalPage;\n\nexport type CompanyBrainContextReceiptListOptions = {\n attemptId?: string;\n cursor?: string;\n limit?: number;\n};\n\nexport type CompanyBrainKnowledgeProposalListOptions = {\n limit?: number;\n};\n\nexport type CompanyBrainInspectorTransport = {\n requestJson<T>(method: string, path: string, body?: unknown): Promise<T>;\n};\n\nfunction inspectorPath(workspaceId: string, suffix: string): string {\n return `/v1/workspaces/${workspaceId}/company-brain/${suffix}`;\n}\n\nexport function listCompanyBrainContextReceipts(\n client: CompanyBrainInspectorTransport,\n workspaceId: string,\n options: CompanyBrainContextReceiptListOptions = {},\n): Promise<CompanyBrainContextReceiptPage> {\n const params = new URLSearchParams();\n if (options.attemptId) params.set(\"attemptId\", options.attemptId);\n if (options.cursor) params.set(\"cursor\", options.cursor);\n if (options.limit !== undefined) params.set(\"limit\", String(options.limit));\n const query = params.toString();\n return client.requestJson(\n \"GET\",\n `${inspectorPath(workspaceId, \"context-receipts\")}${query ? `?${query}` : \"\"}`,\n );\n}\n\nexport function listCompanyBrainKnowledgeProposals(\n client: CompanyBrainInspectorTransport,\n workspaceId: string,\n options: CompanyBrainKnowledgeProposalListOptions = {},\n): Promise<CompanyBrainKnowledgeProposalPage> {\n const query =\n options.limit === undefined ? \"\" : `?limit=${encodeURIComponent(String(options.limit))}`;\n return client.requestJson(\"GET\", `${inspectorPath(workspaceId, \"knowledge-proposals\")}${query}`);\n}\n\nexport type CompanyBrainOkfDownload = {\n content: string;\n contentType: string;\n filename: string;\n};\n","export type PreferenceRegistryScope = \"organization\" | \"workspace\" | \"user\";\nexport type PreferenceRegistryStatus =\n | \"proposed\"\n | \"active\"\n | \"inactive\"\n | \"rejected\"\n | \"superseded\"\n | \"expired\";\nexport type PreferenceRegistryProvenanceSource =\n | \"human\"\n | \"onboarding\"\n | \"knowledge_proposal\"\n | \"agent\"\n | \"portable_skill\"\n | \"imported_document\"\n | \"slack\"\n | \"meeting_transcript\"\n | \"call_transcript\";\nexport type PreferenceRegistryTrust =\n | \"untrusted_proposal\"\n | \"personal\"\n | \"workspace_managed\"\n | \"organization_managed\";\nexport type PreferenceRegistryConflictStrategy = \"override\" | \"merge\" | \"reject\" | \"inform\";\n\nexport function normalizePreferenceRegistryStableKey(value: string): string {\n return value.normalize(\"NFKC\").trim().toLowerCase().replace(/\\s+/gu, \"-\").replace(/-+/g, \"-\");\n}\n\nexport type PreferenceRegistryScopeTarget = {\n scope: PreferenceRegistryScope;\n workspaceId: string | null;\n subjectId: string | null;\n};\n\nexport type PreferenceRegistryPrecedence = {\n tier: PreferenceRegistryScope;\n rank: number;\n conflictStrategy: PreferenceRegistryConflictStrategy;\n conflictsWith: string[];\n};\n\nexport type PreferenceRegistryRevisionSummary = {\n id: string;\n preferenceId: string;\n revision: number;\n contentHash: string;\n title: string;\n description: string;\n precedence: PreferenceRegistryPrecedence;\n provenance: {\n source: PreferenceRegistryProvenanceSource;\n sourceId: string | null;\n trust: PreferenceRegistryTrust;\n };\n expiresAt: string | null;\n correctsRevisionId: string | null;\n createdBySubjectId: string;\n createdAt: string;\n};\n\nexport type PreferenceRegistryDescriptorProvenance = {\n source: PreferenceRegistryProvenanceSource;\n sourceIdHash: string | null;\n trust: PreferenceRegistryTrust;\n};\n\nexport type PreferenceRegistryRecord = {\n id: string;\n accountId: string;\n stableKey: string;\n target: PreferenceRegistryScopeTarget;\n status: PreferenceRegistryStatus;\n scopeVersion: number;\n activationVersion: number;\n activeRevision: PreferenceRegistryRevisionSummary | null;\n supersededByPreferenceId: string | null;\n createdBySubjectId: string;\n createdAt: string;\n updatedAt: string;\n};\n\nexport type PreferenceRegistryEvent = {\n id: string;\n accountId: string;\n preferenceId: string;\n type:\n | \"proposal_created\"\n | \"activated\"\n | \"corrected\"\n | \"rejected\"\n | \"deactivated\"\n | \"superseded\"\n | \"scope_changed\";\n version: number;\n oldRevisionId: string | null;\n newRevisionId: string | null;\n oldTarget: PreferenceRegistryScopeTarget | null;\n newTarget: PreferenceRegistryScopeTarget | null;\n relatedPreferenceId: string | null;\n actorSubjectId: string;\n reason: string;\n createdAt: string;\n};\n\nexport type PreferenceRegistryActivationAuthority = \"human_confirmed\" | \"automatic\";\n\nexport type PreferenceRegistryDescriptor = {\n id: string;\n stableKey: string;\n title: string;\n description: string;\n scope: PreferenceRegistryScope;\n activeVersion: number;\n revisionId: string;\n contentHash: string;\n precedence: PreferenceRegistryPrecedence;\n provenance: PreferenceRegistryDescriptorProvenance;\n /**\n * How the active revision became active. `provenance.trust` stays the frozen\n * creation-time fact; this is the separate activation question. Null when the\n * revision became active outside governed learning, or when the descriptor\n * predates this field.\n */\n activationAuthority: PreferenceRegistryActivationAuthority | null;\n expiresAt: string | null;\n retrievalHandle: string;\n};\n\nexport type PreferenceRegistrySnapshot = {\n id: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n initiatingHumanSubjectId: string;\n descriptorHash: string;\n descriptors: PreferenceRegistryDescriptor[];\n truncated: boolean;\n createdAt: string;\n};\n\nexport type PreferenceRegistryFullContent = {\n descriptor: PreferenceRegistryDescriptor;\n content: string;\n};\n\nexport type CreatePreferenceRegistryProposalRequest = {\n stableKey: string;\n scope: PreferenceRegistryScope;\n title: string;\n description: string;\n content: string;\n precedenceRank?: number;\n conflictStrategy?: PreferenceRegistryConflictStrategy;\n conflictsWith?: string[];\n expiresAt?: string | null;\n provenanceSource?: PreferenceRegistryProvenanceSource;\n provenanceSourceId?: string | null;\n};\n\nexport type ActivatePreferenceRegistryRevisionRequest = {\n revisionId: string;\n expectedCurrentRevisionId: string | null;\n expectedScopeVersion: number;\n reason: string;\n};\n\nexport type CorrectPreferenceRegistryRequest = {\n expectedCurrentRevisionId: string;\n expectedScopeVersion: number;\n title: string;\n description: string;\n content: string;\n precedenceRank?: number;\n conflictStrategy?: PreferenceRegistryConflictStrategy;\n conflictsWith?: string[];\n expiresAt?: string | null;\n reason: string;\n};\n\nexport type DeactivatePreferenceRegistryRequest = {\n expectedCurrentRevisionId: string;\n expectedScopeVersion: number;\n reason: string;\n};\n\nexport type ChangePreferenceRegistryScopeRequest = {\n scope: PreferenceRegistryScope;\n expectedScopeVersion: number;\n reason: string;\n};\n\nexport type SupersedePreferenceRegistryRequest = {\n replacementPreferenceId: string;\n expectedCurrentRevisionId: string;\n expectedScopeVersion: number;\n reason: string;\n};\n\nexport type RejectPreferenceRegistryProposalRequest = {\n revisionId: string;\n expectedScopeVersion: number;\n reason: string;\n};\nexport type PreferenceRegistryListOptions = {\n scope?: PreferenceRegistryScope;\n status?: PreferenceRegistryStatus;\n limit?: number;\n};\nexport type PreferenceRegistryListResponse = { preferences: PreferenceRegistryRecord[] };\nexport type PreferenceRegistryDetailResponse = {\n preference: PreferenceRegistryRecord;\n revisions: PreferenceRegistryRevisionSummary[];\n events: PreferenceRegistryEvent[];\n};\nexport type PreferenceRegistryMutationResponse = {\n preference: PreferenceRegistryRecord;\n event: PreferenceRegistryEvent;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,KAAK,EAAE,YAAY,EAAE,QAAQ,SAAS,GAAG,EAAE,QAAQ,OAAO,GAAG;AAC9F;;;ACnFA,SAAS,cAAc,aAAqB,QAAwB;AAClE,SAAO,kBAAkB,WAAW,kBAAkB,MAAM;AAC9D;AAEO,SAAS,gCACd,QACA,aACA,UAAiD,CAAC,GACT;AACzC,QAAM,SAAS,IAAI,gBAAgB;AACnC,MAAI,QAAQ,UAAW,QAAO,IAAI,aAAa,QAAQ,SAAS;AAChE,MAAI,QAAQ,OAAQ,QAAO,IAAI,UAAU,QAAQ,MAAM;AACvD,MAAI,QAAQ,UAAU,OAAW,QAAO,IAAI,SAAS,OAAO,QAAQ,KAAK,CAAC;AAC1E,QAAM,QAAQ,OAAO,SAAS;AAC9B,SAAO,OAAO;AAAA,IACZ;AAAA,IACA,GAAG,cAAc,aAAa,kBAAkB,CAAC,GAAG,QAAQ,IAAI,KAAK,KAAK,EAAE;AAAA,EAC9E;AACF;AAEO,SAAS,mCACd,QACA,aACA,UAAoD,CAAC,GACT;AAC5C,QAAM,QACJ,QAAQ,UAAU,SAAY,KAAK,UAAU,mBAAmB,OAAO,QAAQ,KAAK,CAAC,CAAC;AACxF,SAAO,OAAO,YAAY,OAAO,GAAG,cAAc,aAAa,qBAAqB,CAAC,GAAG,KAAK,EAAE;AACjG;;;AC3BO,SAAS,qCAAqC,OAAuB;AAC1E,SAAO,MAAM,UAAU,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,QAAQ,SAAS,GAAG,EAAE,QAAQ,OAAO,GAAG;AAC9F;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../contracts/src/tool-review-presentation.ts","../../contracts/src/mcp-endpoint.ts","../src/tool-display-metadata.ts","../src/mcp-output.ts","../src/desktop.ts","../src/terminal.ts","../src/workspace-instruction-policies.ts","../src/company-profile.ts","../src/company-brain.ts","../src/preference-registry.ts"],"sourcesContent":["import type {\n ToolActionReview,\n ToolReviewContext,\n ToolReviewDetailsPage,\n} from \"./tool-action-review\";\n\nconst protectedName =\n /password|passwd|secret|credential|authorization|cookie|(^|[_-])token($|[_-])|api[_-]?key|accessToken|refreshToken|privateKey/i;\nconst protectedReviewField = (key: string, fields: readonly string[] = []) =>\n protectedName.test(key) || fields.includes(key) || fields.includes(\"*\");\nconst bound = (value: string, limit: number) =>\n value.length > limit ? `${value.slice(0, limit)}…` : value;\nexport function toolReviewFieldLabel(key: string): string {\n const label = key\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[_-]+/g, \" \")\n .replace(/\\bids?\\b/gi, (word) => (word.length === 3 ? \"IDs\" : \"ID\"))\n .replace(\n /\\b(api|url|uri|http|https|ip|sql|json|html)(s?)\\b/gi,\n (_word, name: string, plural: string) => `${name.toUpperCase()}${plural}`,\n )\n // Sentence case, keeping acronyms: \"Working Directory\" → \"Working directory\".\n .replace(\n /(?<=\\S\\s+)([A-Z])([a-z]+)\\b/g,\n (_word, first: string, rest: string) => `${first.toLowerCase()}${rest}`,\n )\n .trim();\n return label.charAt(0).toUpperCase() + label.slice(1);\n}\nexport function decodeReviewArguments(value: unknown): Record<string, unknown> | null {\n // Historical SDK entries sometimes wrapped arguments in JSON. Decode only once.\n let decoded = value;\n if (typeof decoded === \"string\") {\n try {\n decoded = JSON.parse(decoded);\n } catch {\n return null;\n }\n }\n return decoded && typeof decoded === \"object\" && !Array.isArray(decoded)\n ? (decoded as Record<string, unknown>)\n : null;\n}\nexport function safeReviewValue(\n value: unknown,\n key = \"\",\n protectedFields: readonly string[] = [],\n depth = 0,\n): unknown {\n if (protectedReviewField(key, protectedFields)) return \"[Protected value]\";\n if (depth > 20) return \"[Nested value; open this field for details]\";\n if (Array.isArray(value))\n return value.map((entry) => safeReviewValue(entry, \"\", protectedFields, depth + 1));\n if (value && typeof value === \"object\")\n return Object.fromEntries(\n Object.entries(value).map(([name, entry]) => [\n name,\n safeReviewValue(entry, name, protectedFields, depth + 1),\n ]),\n );\n return value;\n}\nfunction valueText(value: unknown): string {\n return typeof value === \"string\"\n ? value\n : value === null\n ? \"None\"\n : typeof value === \"boolean\"\n ? value\n ? \"Yes\"\n : \"No\"\n : (JSON.stringify(value) ?? \"Unavailable\");\n}\nconst pointer = (name: string) => `/${name.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\")}`;\n// Long arbitrary property names remain readable without placing them in every\n// preview or URL. An indexed segment opens their saved name and value together.\nconst fieldPointer = (key: string, index: number, parent = \"\") =>\n pointer(key).length > 256 || parent.length + pointer(key).length > 1024\n ? `/~2${index}`\n : pointer(key);\n\nexport function toolReviewFields(\n argumentsValue: unknown,\n context?: ToolReviewContext,\n): { fields: ToolActionReview[\"fields\"]; moreFields: number } {\n const args = decodeReviewArguments(argumentsValue);\n if (!args) return { fields: [], moreFields: 0 };\n const entries = Object.entries(args);\n if (context?.email) {\n const email = toolReviewFields(context.email);\n const original = toolReviewFields(args, { ...context, email: undefined });\n const fields = [\n ...email.fields\n .filter(\n (field) =>\n field.path !== \"/contentSha256\" && field.path !== \"/htmlBody\" && field.preview !== \"\",\n )\n .map((field) => ({\n ...field,\n label: field.path === \"/textBody\" ? \"Message\" : field.label,\n path: `/$email${field.path}`,\n ...(field.path === \"/attachments\"\n ? {\n preview: context\n .email!.attachments.map((attachment) => attachment.name)\n .join(\", \")\n .slice(0, 240),\n }\n : {}),\n })),\n ...original.fields.filter(\n (field) =>\n ![\n \"/raw\",\n \"/expectedContentSha256\",\n \"/from\",\n \"/to\",\n \"/cc\",\n \"/bcc\",\n \"/subject\",\n \"/body\",\n \"/textBody\",\n \"/htmlBody\",\n \"/attachments\",\n ].includes(field.path),\n ),\n ];\n return {\n fields: fields.slice(0, 16),\n moreFields: original.moreFields + Math.max(0, fields.length - 16),\n };\n }\n return {\n moreFields: Math.max(0, entries.length - 16),\n fields: entries.slice(0, 16).map(([key, value], index) => {\n const hidden = protectedReviewField(key, context?.protectedFields);\n const safe = hidden ? \"[Protected value]\" : value;\n const count = !hidden && Array.isArray(value) ? value.length : undefined;\n const compactList =\n !hidden &&\n Array.isArray(value) &&\n value.length > 0 &&\n value.length <= 4 &&\n value.every(\n (entry) =>\n typeof entry === \"string\" || typeof entry === \"number\" || typeof entry === \"boolean\",\n )\n ? value.map(valueText).join(\", \")\n : undefined;\n const text =\n compactList !== undefined\n ? compactList\n : count !== undefined\n ? `${count.toLocaleString(\"en-US\")} item${count === 1 ? \"\" : \"s\"}`\n : safe && typeof safe === \"object\"\n ? `${Object.keys(safe).length} field${Object.keys(safe).length === 1 ? \"\" : \"s\"}`\n : valueText(safe);\n return {\n path: fieldPointer(key, index),\n label: bound(\n (context?.fieldLabels && Object.hasOwn(context.fieldLabels, key)\n ? context.fieldLabels[key]\n : undefined) ?? toolReviewFieldLabel(key),\n 256,\n ),\n preview: bound(text, 240),\n ...(count !== undefined ? { count } : {}),\n truncated:\n !hidden &&\n (text.length > 240 ||\n (compactList === undefined && typeof value === \"object\" && value !== null)),\n ...(hidden ? { protected: true } : {}),\n };\n }),\n };\n}\n\n/** Deterministic consequences from the reviewed bytes. Unknown fields remain visible. */\nexport function toolReviewAction(\n toolName: string,\n argumentsValue: unknown,\n context?: ToolReviewContext,\n): Pick<\n ToolActionReview,\n \"title\" | \"approveLabel\" | \"effects\" | \"consequence\" | \"selectionCount\" | \"selectionKind\"\n> {\n const fallback = {\n title:\n context?.title ??\n bound(\n toolReviewFieldLabel(\n toolName.replace(/^mcp_[^_]+__/, \"\").replace(/^batch[_-](?=[a-z])/i, \"\"),\n ),\n 256,\n ),\n approveLabel: \"Approve action\",\n effects: [] as string[],\n };\n if (context?.kind !== \"gmail\") return fallback;\n const args = decodeReviewArguments(argumentsValue);\n if (!args) return fallback;\n const thread = toolName.endsWith(\"_thread\");\n const selectionKind = thread ? (\"threads\" as const) : (\"messages\" as const);\n const ids =\n thread && typeof args.threadId === \"string\"\n ? [args.threadId]\n : Array.isArray(args.messageIds)\n ? args.messageIds\n : typeof args.messageId === \"string\"\n ? [args.messageId]\n : null;\n const selectionCount = ids?.every((id) => typeof id === \"string\") ? new Set(ids).size : undefined;\n const noun =\n selectionCount === undefined\n ? thread\n ? \"conversations\"\n : \"messages\"\n : `${selectionCount.toLocaleString(\"en-US\")} ${thread ? \"conversation\" : \"message\"}${selectionCount === 1 ? \"\" : \"s\"}`;\n const addValues = toolName.startsWith(\"label_\") ? args.labelIds : args.addLabelIds;\n const adds = Array.isArray(addValues)\n ? addValues.filter((v): v is string => typeof v === \"string\")\n : [];\n const removeValues = toolName.startsWith(\"unlabel_\") ? args.labelIds : args.removeLabelIds;\n const removes = Array.isArray(removeValues)\n ? removeValues.filter((v): v is string => typeof v === \"string\")\n : [];\n const labelEffect = (label: string, adding: boolean): string => {\n const known: Record<string, [string, string]> = {\n TRASH: [\"Move to Trash\", \"Remove from Trash\"],\n INBOX: [\"Move to Inbox\", \"Remove from Inbox\"],\n UNREAD: [\"Mark as unread\", \"Mark as read\"],\n STARRED: [\"Add star\", \"Remove star\"],\n SPAM: [\"Mark as spam\", \"Remove from Spam\"],\n IMPORTANT: [\"Mark as important\", \"Remove importance\"],\n };\n return (\n (Object.hasOwn(known, label) ? known[label]?.[adding ? 0 : 1] : undefined) ??\n `${adding ? \"Add\" : \"Remove\"} label ${bound(label, 120)}`\n );\n };\n const effects = [\n ...adds.map((id) => labelEffect(id, true)),\n ...removes.map((id) => labelEffect(id, false)),\n ];\n if (\n [\n \"batch_modify_messages\",\n \"modify_message\",\n \"modify_thread\",\n \"label_message\",\n \"label_thread\",\n \"unlabel_message\",\n \"unlabel_thread\",\n ].includes(toolName)\n ) {\n const trash = adds.includes(\"TRASH\");\n return {\n title: trash ? `Move ${noun} to Trash` : `Update ${noun}`,\n approveLabel: trash ? \"Move to Trash\" : \"Apply changes\",\n effects,\n ...(selectionCount === undefined ? {} : { selectionCount, selectionKind }),\n ...(trash\n ? { consequence: \"Messages stay recoverable in Trash until Gmail deletes them.\" }\n : thread\n ? { consequence: \"Applies to every message in the conversation.\" }\n : {}),\n };\n }\n if ([\"trash_message\", \"restore_message\", \"trash_thread\", \"restore_thread\"].includes(toolName))\n return {\n title: toolName.startsWith(\"trash_\") ? `Move ${noun} to Trash` : `Remove ${noun} from Trash`,\n approveLabel: toolName.startsWith(\"trash_\") ? \"Move to Trash\" : \"Remove from Trash\",\n effects,\n ...(selectionCount === undefined ? {} : { selectionCount, selectionKind }),\n };\n const named: Record<string, [string, string]> = {\n send_message: [\"Send email\", \"Send email\"],\n send_draft: [\"Send draft\", \"Send draft\"],\n create_draft: [\"Create email draft\", \"Create draft\"],\n update_draft: [\"Update email draft\", \"Update draft\"],\n delete_draft: [\"Delete email draft\", \"Delete draft\"],\n create_label: [\"Create label\", \"Create label\"],\n update_label: [\"Update label\", \"Update label\"],\n delete_label: [\"Delete label\", \"Delete label\"],\n };\n const action = Object.hasOwn(named, toolName) ? named[toolName] : undefined;\n return action ? { title: action[0], approveLabel: action[1], effects } : fallback;\n}\n\n/** A bounded slice of the immutable saved arguments; never evaluates a fresh provider query. */\nexport function toolReviewDetails(\n argumentsValue: unknown,\n context: ToolReviewContext | undefined,\n path: string,\n offset: number,\n limit = 25,\n): Omit<ToolReviewDetailsPage, \"id\" | \"actionDigest\" | \"version\"> {\n if (\n !Number.isSafeInteger(offset) ||\n offset < 0 ||\n !Number.isSafeInteger(limit) ||\n limit < 1 ||\n limit > 50\n )\n throw new Error(\"Invalid review page\");\n const args = decodeReviewArguments(argumentsValue);\n let value: unknown = context?.email ? { ...args, $email: context.email } : args;\n if (path !== \"\") {\n if (!path.startsWith(\"/\")) throw new Error(\"Invalid review field\");\n for (const escaped of path.slice(1).split(\"/\")) {\n if (/^~2\\d+$/.test(escaped)) {\n if (!value || typeof value !== \"object\" || Array.isArray(value))\n throw new Error(\"Review field not found\");\n const selected = Object.entries(value)[Number(escaped.slice(2))];\n if (!selected) throw new Error(\"Review field not found\");\n value = {\n fieldName: selected[0],\n value: protectedReviewField(selected[0], context?.protectedFields)\n ? \"[Protected value]\"\n : selected[1],\n };\n continue;\n }\n const key = escaped.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n if (protectedReviewField(key, context?.protectedFields)) {\n value = \"[Protected value]\";\n break;\n }\n if (!value || typeof value !== \"object\" || !Object.hasOwn(value, key))\n throw new Error(\"Review field not found\");\n value = (value as Record<string, unknown>)[key];\n }\n }\n type DetailItem = ToolReviewDetailsPage[\"items\"][number];\n const preview = (\n entry: unknown,\n key: string,\n childPath: string,\n ): Pick<DetailItem, \"value\" | \"truncated\" | \"path\"> => {\n const hidden = protectedReviewField(key, context?.protectedFields);\n if (!hidden && entry !== null && typeof entry === \"object\") {\n const count = Array.isArray(entry) ? entry.length : Object.keys(entry).length;\n return {\n value: `${count.toLocaleString(\"en-US\")} ${Array.isArray(entry) ? (count === 1 ? \"item\" : \"items\") : count === 1 ? \"field\" : \"fields\"}`,\n path: childPath,\n truncated: true,\n };\n }\n const text = valueText(safeReviewValue(entry, key, context?.protectedFields));\n return {\n value: bound(text, 4000),\n ...(hidden ? {} : { path: childPath }),\n truncated: !hidden && text.length > 4000,\n };\n };\n let total: number;\n let items: DetailItem[];\n if (Array.isArray(value)) {\n total = value.length;\n items = value.slice(offset, offset + limit).map((entry, index) => ({\n label: `${offset + index + 1}`,\n ...preview(entry, \"\", `${path}/${offset + index}`),\n }));\n } else if (value && typeof value === \"object\") {\n const entries = Object.entries(value);\n total = entries.length;\n items = entries.slice(offset, offset + limit).map(([key, entry], index) => ({\n label: bound(\n (context?.fieldLabels && Object.hasOwn(context.fieldLabels, key)\n ? context.fieldLabels[key]\n : undefined) ?? toolReviewFieldLabel(key),\n 256,\n ),\n ...preview(entry, key, `${path}${fieldPointer(key, offset + index, path)}`),\n }));\n } else {\n const text = valueText(value);\n total = Math.max(1, Math.ceil(text.length / 4000));\n items = Array.from({ length: Math.max(0, Math.min(limit, total - offset)) }, (_, index) => ({\n label: `Part ${offset + index + 1}`,\n value: text.slice((offset + index) * 4000, (offset + index + 1) * 4000),\n }));\n }\n return { path, items, total, nextOffset: offset + limit < total ? offset + limit : null };\n}\n","/** Exact endpoint identity: normalize URL syntax, preserve paths and query parameters. */\nexport function mcpEndpointIdentity(value: string | null | undefined): string | null {\n if (!value) return null;\n try {\n const url = new URL(value);\n if (![\"https:\", \"http:\"].includes(url.protocol) || url.username || url.password) return null;\n url.hash = \"\";\n return url.href;\n } catch {\n return null;\n }\n}\n\nexport function pluginMcpUnavailableReason(server: {\n endpoint: string | null;\n transport?: string;\n requiresConfiguration?: boolean;\n}): string | null {\n if (server.transport === \"stdio\" || !server.endpoint) return \"Requires a local runtime\";\n if (\n server.transport &&\n ![\"http\", \"streamable-http\", \"streamable_http\"].includes(server.transport)\n )\n return \"Unsupported transport: \" + server.transport;\n if (server.requiresConfiguration || server.endpoint.includes(\"{\"))\n return \"Requires custom connection configuration\";\n const endpoint = mcpEndpointIdentity(server.endpoint);\n if (!endpoint?.startsWith(\"https://\")) return \"Requires a valid HTTPS endpoint\";\n return null;\n}\n","import type { ToolDisplayMetadata } from \"@opengeni/contracts\";\n\n/** Browser/native-safe event projection; do not import server schema runtimes. */\nexport function parseToolDisplayMetadata(value: unknown): ToolDisplayMetadata | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const item = value as Record<string, unknown>;\n if (Object.keys(item).some((key) => ![\"toolName\", \"title\", \"accountLabel\"].includes(key)))\n return undefined;\n const text = (v: unknown, max: number): v is string =>\n typeof v === \"string\" && v.length > 0 && v.length <= max;\n if (!text(item.toolName, 512) || /[\\u0000-\\u001f\\u007f]/u.test(item.toolName)) return undefined;\n if (item.title !== undefined && !text(item.title, 512)) return undefined;\n if (item.accountLabel !== undefined && !text(item.accountLabel, 1024)) return undefined;\n return {\n toolName: item.toolName,\n ...(item.title !== undefined ? { title: item.title as string } : {}),\n ...(item.accountLabel !== undefined ? { accountLabel: item.accountLabel as string } : {}),\n };\n}\n","/**\n * A transport-tolerant MCP tool result.\n *\n * `value` is the canonical machine-readable payload after recognized MCP/JSON\n * envelopes are removed. `text` is the best presentation string without\n * discarding structured data. `raw` always retains the original evidence.\n */\nexport type NormalizedMcpOutput = Readonly<{\n raw: unknown;\n value: unknown;\n text: string;\n isError: boolean;\n}>;\n\nconst MAX_MCP_OUTPUT_DEPTH = 8;\nconst RESULT_ENVELOPE_KEYS = new Set([\"result\", \"isError\", \"jsonrpc\", \"id\", \"_meta\"]);\n\n/** Normalize common direct, JSON, and standard MCP result envelopes without throwing. */\nexport function normalizeMcpOutput(output: unknown): NormalizedMcpOutput {\n const normalized = normalizeValue(output, 0, new Set<object>());\n return {\n raw: output,\n value: normalized.value,\n text: normalized.text,\n isError: normalized.isError,\n };\n}\n\ntype NormalizedValue = Omit<NormalizedMcpOutput, \"raw\">;\n\nfunction normalizeValue(value: unknown, depth: number, ancestors: Set<object>): NormalizedValue {\n if (value === null || value === undefined) {\n return { value, text: \"\", isError: false };\n }\n if (typeof value === \"string\") {\n return normalizeText(value, depth, ancestors);\n }\n if (typeof value !== \"object\") {\n return { value, text: String(value), isError: false };\n }\n if (depth >= MAX_MCP_OUTPUT_DEPTH || ancestors.has(value)) {\n return { value, text: safeStringify(value), isError: false };\n }\n\n ancestors.add(value);\n try {\n if (Array.isArray(value)) {\n return { value, text: safeStringify(value), isError: false };\n }\n\n const record = value as Record<string, unknown>;\n const envelopeError = record.isError === true;\n\n if (record.type === \"text\" && typeof record.text === \"string\") {\n const normalized = normalizeText(record.text, depth + 1, ancestors);\n return {\n value: normalized.value,\n text: record.text,\n isError: envelopeError || normalized.isError,\n };\n }\n\n if (\"structuredContent\" in record) {\n const normalized = normalizeValue(record.structuredContent, depth + 1, ancestors);\n return {\n value: normalized.value,\n text: firstMcpText(record.content) ?? normalized.text,\n isError: envelopeError || normalized.isError,\n };\n }\n\n if (isMcpContent(record.content)) {\n const text = firstMcpText(record.content);\n if (text !== null) {\n const normalized = normalizeText(text, depth + 1, ancestors);\n return {\n value: normalized.value,\n text,\n isError: envelopeError || normalized.isError,\n };\n }\n return {\n value,\n text: safeStringify(value),\n isError: envelopeError,\n };\n }\n\n if (isResultEnvelope(record)) {\n const normalized = normalizeValue(record.result, depth + 1, ancestors);\n return {\n value: normalized.value,\n text: normalized.text,\n isError: envelopeError || normalized.isError,\n };\n }\n\n return {\n value,\n text: safeStringify(value),\n isError: envelopeError,\n };\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction normalizeText(text: string, depth: number, ancestors: Set<object>): NormalizedValue {\n try {\n const parsed: unknown = JSON.parse(text);\n const normalized = normalizeValue(parsed, depth + 1, ancestors);\n return {\n value: normalized.value,\n text,\n isError: normalized.isError,\n };\n } catch {\n return { value: text, text, isError: false };\n }\n}\n\nfunction isMcpContent(value: unknown): value is readonly Record<string, unknown>[] {\n return (\n Array.isArray(value) &&\n value.some(\n (part) =>\n part !== null &&\n typeof part === \"object\" &&\n typeof (part as { type?: unknown }).type === \"string\",\n )\n );\n}\n\nfunction firstMcpText(value: unknown): string | null {\n if (!Array.isArray(value)) {\n return null;\n }\n for (const part of value) {\n if (\n part !== null &&\n typeof part === \"object\" &&\n (part as { type?: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n return (part as { text: string }).text;\n }\n }\n return null;\n}\n\nfunction isResultEnvelope(record: Record<string, unknown>): boolean {\n return \"result\" in record && Object.keys(record).every((key) => RESULT_ENVELOPE_KEYS.has(key));\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? \"\";\n } catch {\n return String(value);\n }\n}\n","// Zero-dependency desktop (noVNC) transport contract.\n//\n// The actual `@novnc/novnc` RFB import is a browser-only DOM dependency and\n// lives in `@opengeni/react` (lazily imported, SSR-safe). The framework-agnostic\n// SDK ships only the transport CONTRACT: a URL assembler, the minimal RFB\n// surface the component drives, the connection state machine, and the\n// rotation/fence reducers — all pure and unit-testable, with no DOM and no deps.\n//\n// Channel A (terminal-as-events, files, git) needs NO new transport here: those\n// are event projections + the synchronous fs/git/terminal point queries on\n// `OpenGeniClient`. Only the desktop pixel plane (Channel B, direct-to-provider)\n// needs this.\n\nimport type { DesktopStreamCapability, StreamUrlRotatedPayload } from \"./types\";\n\n/**\n * Translate the negotiated desktop capability into the WebSocket URL the noVNC\n * RFB client connects to. The scoped provider token is ALREADY embedded in the\n * minted `url` (Modal tunnel host, Blaxel `bl_preview_token`, Daytona signed\n * preview) by `session.resolveExposedPort(6080)` — we do NOT append `cap.token`\n * as a query param (that double-auth was an adversarial-review bug: the box runs\n * `-nopw` in v1, so the RFB password is meaningless and the real auth is the\n * tunnel token in the host). We only normalize the scheme to `ws`/`wss` and, when\n * the minted URL points at a `vnc.html` viewer page, rewrite it to the\n * websockify socket path noVNC actually dials.\n */\nexport function desktopSocketUrl(cap: Pick<DesktopStreamCapability, \"url\">): string {\n if (!cap.url) {\n throw new Error(\"desktop capability has no url (transport is null)\");\n }\n const u = new URL(cap.url);\n // https → wss, http → ws (noVNC dials a WebSocket, not the HTTP viewer page).\n if (u.protocol === \"https:\") {\n u.protocol = \"wss:\";\n } else if (u.protocol === \"http:\") {\n u.protocol = \"ws:\";\n }\n // A minted `…/vnc.html` (or `…/vnc_lite.html`) viewer page → the websockify\n // socket the page itself would open (`…/websockify`). A bare host/path with no\n // viewer page is already the socket path; leave it untouched.\n if (/\\/vnc(_lite)?\\.html$/.test(u.pathname)) {\n u.pathname = u.pathname.replace(/\\/vnc(_lite)?\\.html$/, \"/websockify\");\n u.search = \"\";\n u.hash = \"\";\n }\n return u.toString();\n}\n\n/**\n * The minimal RFB surface the React component drives. Lets tests (and 3rd\n * parties swapping noVNC for a WebRTC client in v3) provide a fake without the\n * DOM. Matches `@novnc/novnc`'s RFB constructor + lifecycle.\n */\nexport interface DesktopRfbLike {\n viewOnly: boolean;\n scaleViewport: boolean;\n /**\n * 1:1 viewport clipping. We always drive this FALSE: with clipping on, noVNC\n * paints the framebuffer pixel-for-pixel and scrolls/crops to the container\n * (the \"zoomed in\" look). FALSE lets `scaleViewport` shrink the 1280x800 frame\n * to fit the panel (aspect-preserved). Declared so the hook can pin it instead\n * of relying on noVNC's default — `scaleViewport=true` forces clip off\n * internally, but a stale/partial state on reconnect could leave it on.\n */\n clipViewport: boolean;\n addEventListener(\n type: \"connect\" | \"disconnect\" | \"securityfailure\",\n cb: (e?: unknown) => void,\n ): void;\n removeEventListener?: (\n type: \"connect\" | \"disconnect\" | \"securityfailure\",\n cb: (e?: unknown) => void,\n ) => void;\n /** Send clipboard text over the already-open RFB connection. */\n clipboardPasteFrom?(text: string): void;\n /** Send one RFB key event. A missing `down` emits a complete key press. */\n sendKey?(keysym: number, code: string, down?: boolean): void;\n /** Focus or release the RFB keyboard sink without reconnecting. */\n focus?(options?: FocusOptions): void;\n blur?(): void;\n disconnect(): void;\n}\n\nexport type DesktopRfbFactory = (\n target: HTMLElement,\n url: string,\n opts: {\n credentials?: { password?: string | undefined } | undefined;\n wsProtocols?: string[] | undefined;\n },\n) => DesktopRfbLike;\n\nexport type DesktopConnectionState =\n | \"idle\"\n | \"negotiating\"\n | \"connecting\"\n | \"connected\"\n | \"rotating\"\n | \"reconnecting\"\n | \"error\"\n | \"ended\";\n\nexport type DesktopStreamEvent =\n | { type: \"negotiated\" }\n | { type: \"connected\" }\n | { type: \"disconnected\" }\n | { type: \"rotate\" }\n | { type: \"fail\" }\n | { type: \"abort\" };\n\n/**\n * Pure reducer for the desktop connection lifecycle. The component owns the RFB\n * object + DOM; this owns the transitions so they are unit-testable. Mirrors the\n * Channel-A stream reducer discipline.\n */\nexport function nextDesktopState(\n current: DesktopConnectionState,\n ev: DesktopStreamEvent,\n): DesktopConnectionState {\n switch (ev.type) {\n case \"negotiated\":\n return \"connecting\";\n case \"connected\":\n return \"connected\";\n case \"rotate\":\n return current === \"connected\" ? \"rotating\" : current;\n case \"disconnected\":\n // A deliberate teardown (ended) stays ended; everything else reconnects.\n return current === \"ended\" ? \"ended\" : \"reconnecting\";\n case \"fail\":\n return \"error\";\n case \"abort\":\n return \"ended\";\n default:\n return current;\n }\n}\n\n// `DesktopStreamCapability` is the desktop cell of `SessionCapabilities`; alias\n// it for the rotation reducer below without depending on the whole doc.\nexport type DesktopStreamCapabilityLike = {\n url: string | null;\n token: string | null;\n expiresAt: string | null;\n};\n\n/**\n * Apply a `stream.url.rotated` event onto a desktop capability, fencing on\n * leaseEpoch (split-brain). A rotation minted under an epoch the client has\n * already advanced PAST is from a superseded owner and is dropped (returns\n * null); otherwise the fresh url/token/expiresAt are folded in.\n */\nexport function applyUrlRotation<T extends DesktopStreamCapabilityLike>(\n cap: T,\n payload: StreamUrlRotatedPayload,\n knownEpoch: number,\n): T | null {\n if (payload.leaseEpoch < knownEpoch) {\n return null;\n }\n return { ...cap, url: payload.url, token: payload.token, expiresAt: payload.expiresAt };\n}\n","// Zero-dependency interactive-terminal (ttyd PTY-over-websocket) transport\n// contract. Symmetric with `desktop.ts`: the SDK ships only the pure transport\n// CONTRACT (a URL assembler + the ttyd wire-protocol frame codec), with no DOM\n// and no deps. The actual WebSocket open + xterm attach lives in `@opengeni/react`\n// (`use-terminal-stream.ts`).\n//\n// The interactive terminal is a REAL PTY streamed over the SAME Modal raw-TLS\n// tunnel as the desktop noVNC, with the SAME scoped stream-token mechanism. The\n// box bakes `ttyd` on `TERMINAL_STREAM_PORT` (7681); `session.resolveExposedPort`\n// mints the tunnel URL. The Terminal capability cell carries transport \"pty-ws\" +\n// that url + the scoped token when the box is warm and a viewer is attached.\n\nimport type { TerminalCapability } from \"./types\";\n\n/**\n * Translate the negotiated `pty-ws` Terminal capability into the WebSocket URL\n * the ttyd client dials. The scoped provider token is ALREADY embedded in the\n * minted `url` (the Modal tunnel host) by `session.resolveExposedPort(7681)` —\n * we do NOT append `cap.token` (identical posture to the desktop: the gate is the\n * unguessable short-TTL tunnel URL + the server-recorded scoped stream token; ttyd\n * runs `--writable` with no `-c` credential in v1). We only normalize the scheme\n * to `ws`/`wss`; a bare host is already the ttyd websocket endpoint.\n */\nexport function terminalSocketUrl(cap: Pick<TerminalCapability, \"url\">): string {\n if (!cap.url) {\n throw new Error(\"terminal capability has no url (transport is not pty-ws)\");\n }\n const u = new URL(cap.url);\n // https → wss, http → ws (ttyd is dialed as a WebSocket, not an HTTP page).\n if (u.protocol === \"https:\") {\n u.protocol = \"wss:\";\n } else if (u.protocol === \"http:\") {\n u.protocol = \"ws:\";\n }\n return u.toString();\n}\n\n// ── ttyd wire protocol ───────────────────────────────────────────────────────\n// ttyd frames are a single ASCII command char + payload. These mirror ttyd's\n// `protocol.h` Command enum. Client→server and server→client share the byte 0/1/2\n// values but mean different things per direction (see below).\n\n/** ttyd subprotocol — REQUIRED on the WebSocket handshake or ttyd refuses it. */\nexport const TTYD_SUBPROTOCOL = \"tty\";\n\n/** Client→server command bytes (the first char of each outbound text frame). */\nexport const TtydClientCommand = {\n /** stdin: \"0\" + raw input bytes. */\n INPUT: \"0\",\n /** window resize: \"1\" + JSON.stringify({ columns, rows }). */\n RESIZE: \"1\",\n /** flow-control pause (back-pressure): \"2\". */\n PAUSE: \"2\",\n /** flow-control resume: \"3\". */\n RESUME: \"3\",\n} as const;\n\n/** Server→client command bytes (the first char of each inbound frame). */\nexport const TtydServerCommand = {\n /** stdout/stderr: \"0\" + raw output bytes (write the rest into xterm). */\n OUTPUT: \"0\",\n /** set the window title: \"1\" + title string. */\n SET_WINDOW_TITLE: \"1\",\n /** ttyd client preferences JSON: \"2\" + json (ignored by us). */\n SET_PREFERENCES: \"2\",\n} as const;\n\n/**\n * The ttyd handshake's first frame: an auth message. ttyd expects\n * `JSON.stringify({ AuthToken })` as the FIRST text frame on the socket. We send\n * an empty token — our gate is the tunnel URL + scoped stream token, NOT a ttyd\n * `-c` basic-auth credential (which the box does not set in v1). Optional ttyd\n * `columns`/`rows` can ride this frame to seed the PTY size before the first\n * resize. Pure (string-building only) so it stays unit-testable in the SDK.\n */\nexport function ttydAuthFrame(opts?: { columns?: number; rows?: number }): string {\n const frame: { AuthToken: string; columns?: number; rows?: number } = { AuthToken: \"\" };\n if (opts?.columns && opts.columns > 0) frame.columns = opts.columns;\n if (opts?.rows && opts.rows > 0) frame.rows = opts.rows;\n return JSON.stringify(frame);\n}\n\n/** Build a client→server INPUT (stdin) frame: \"0\" + data. */\nexport function ttydInputFrame(data: string): string {\n return TtydClientCommand.INPUT + data;\n}\n\n/** Build a client→server RESIZE frame: \"1\" + JSON.stringify({ columns, rows }). */\nexport function ttydResizeFrame(columns: number, rows: number): string {\n return TtydClientCommand.RESIZE + JSON.stringify({ columns, rows });\n}\n","export const WORKSPACE_INSTRUCTION_POLICY_CONTENT_MAX_CHARS = 262_144;\n\nexport type WorkspaceInstructionPolicyKind = \"charter\" | \"policy\";\nexport type WorkspaceInstructionPolicyScope = \"global\" | \"role\";\nexport type WorkspaceInstructionPolicyProvenanceSource =\n | \"human\"\n | \"onboarding\"\n | \"agent_learning\"\n | \"knowledge_proposal\"\n | \"legacy_import\";\nexport type WorkspaceInstructionPolicyDraftProvenanceSource = Exclude<\n WorkspaceInstructionPolicyProvenanceSource,\n \"legacy_import\" | \"agent_learning\"\n>;\nexport type WorkspaceInstructionPolicyActivationType = \"activate\" | \"rollback\";\n\nexport function normalizeWorkspaceInstructionPolicyRoleKey(value: string): string {\n return value.normalize(\"NFKC\").trim().toLowerCase().replace(/\\s+/gu, \"-\").replace(/-+/g, \"-\");\n}\n\nexport type WorkspaceInstructionPolicyTarget = {\n kind: WorkspaceInstructionPolicyKind;\n scope: WorkspaceInstructionPolicyScope;\n roleKey: string | null;\n};\n\nexport type WorkspaceInstructionPolicyRevisionIdentity = {\n id: string;\n revision: number;\n contentHash: string;\n};\n\nexport type WorkspaceInstructionPolicyRevision = WorkspaceInstructionPolicyRevisionIdentity &\n WorkspaceInstructionPolicyTarget & {\n operationId: string;\n accountId: string;\n workspaceId: string;\n content: string;\n provenance: {\n source: WorkspaceInstructionPolicyProvenanceSource;\n sourceId: string | null;\n };\n supersedesRevisionId: string | null;\n createdBySubjectId: string;\n createdAt: string;\n };\n\nexport type WorkspaceInstructionPolicyHead = WorkspaceInstructionPolicyTarget & {\n workspaceId: string;\n revisionId: string;\n revision: number;\n contentHash: string;\n activationVersion: number;\n activatedAt: string;\n};\n\nexport type WorkspaceInstructionPolicyInactiveHead = WorkspaceInstructionPolicyTarget & {\n workspaceId: string;\n activationVersion: number;\n deactivatedAt: string;\n};\n\nexport type WorkspaceInstructionPolicyActivationEvent = WorkspaceInstructionPolicyTarget & {\n id: string;\n operationId: string;\n accountId: string;\n workspaceId: string;\n type: WorkspaceInstructionPolicyActivationType;\n activationVersion: number;\n oldRevision: WorkspaceInstructionPolicyRevisionIdentity | null;\n newRevision: WorkspaceInstructionPolicyRevisionIdentity;\n actorSubjectId: string;\n reason: string;\n createdAt: string;\n};\n\nexport type WorkspaceInstructionPolicyDeactivationEvent = WorkspaceInstructionPolicyTarget & {\n id: string;\n operationId: string;\n accountId: string;\n workspaceId: string;\n type: \"automatic_deactivate\";\n activationVersion: number;\n oldRevision: WorkspaceInstructionPolicyRevisionIdentity;\n actorSubjectId: string;\n reason: string;\n createdAt: string;\n};\n\nexport type CreateWorkspaceInstructionPolicyDraftRequest = WorkspaceInstructionPolicyTarget & {\n operationId?: string;\n content: string;\n provenanceSource?: WorkspaceInstructionPolicyDraftProvenanceSource;\n provenanceSourceId?: string | null;\n supersedesRevisionId?: string | null;\n};\n\nexport type ImportLegacyWorkspaceInstructionPolicyDraftRequest = {\n operationId?: string;\n supersedesRevisionId?: string | null;\n};\n\nexport type WorkspaceInstructionPolicyListOptions = {\n kind?: WorkspaceInstructionPolicyKind;\n scope?: WorkspaceInstructionPolicyScope;\n roleKey?: string;\n afterRevision?: number;\n limit?: number;\n};\n\nexport type WorkspaceInstructionPolicyListResponse = {\n revisions: WorkspaceInstructionPolicyRevision[];\n activeHeads: WorkspaceInstructionPolicyHead[];\n /** Additive current inactive target boundaries; absent on pre-controller servers. */\n inactiveHeads?: WorkspaceInstructionPolicyInactiveHead[];\n inactiveHeadsTruncated?: boolean;\n activationEvents: WorkspaceInstructionPolicyActivationEvent[];\n /** Additive lifecycle history; absent on pre-controller servers. */\n deactivationEvents?: WorkspaceInstructionPolicyDeactivationEvent[];\n nextAfterRevision: number | null;\n};\n\nexport type WorkspaceInstructionPolicyDiffRequest = {\n fromRevisionId: string;\n toRevisionId: string;\n};\n\nexport type WorkspaceInstructionPolicyDiffResponse = {\n from: WorkspaceInstructionPolicyRevision;\n to: WorkspaceInstructionPolicyRevision;\n format: \"unified\";\n diff: string;\n};\n\nexport type ActivateWorkspaceInstructionPolicyRequest = {\n operationId?: string;\n expectedCurrentRevisionId: string | null;\n expectedActivationVersion?: number;\n reason: string;\n};\n\nexport type RollbackWorkspaceInstructionPolicyRequest = {\n operationId?: string;\n targetRevisionId: string;\n expectedCurrentRevisionId: string;\n expectedActivationVersion?: number;\n reason: string;\n};\n\nexport type WorkspaceInstructionPolicyActivationResponse = {\n head: WorkspaceInstructionPolicyHead;\n event: WorkspaceInstructionPolicyActivationEvent;\n};\n\nexport type WorkspaceInstructionPolicyConflictResponse = {\n code: \"WORKSPACE_INSTRUCTION_POLICY_CONFLICT\";\n message: string;\n currentHead: WorkspaceInstructionPolicyHead | null;\n};\n\nexport type WorkspaceInstructionPolicyOperationReuseResponse = {\n code: \"WORKSPACE_INSTRUCTION_POLICY_OPERATION_REUSED\";\n message: string;\n};\n\nexport type WorkspaceInstructionPolicyOnboardingProposalSource = {\n id: string;\n version: string;\n confidenceBps: number;\n};\n\nexport type CreateWorkspaceInstructionPolicyOnboardingProposalRequest =\n WorkspaceInstructionPolicyTarget & {\n operationId?: string;\n content: string;\n sourceId: string;\n sourceVersion: string;\n confidenceBps: number;\n expectedCurrentRevisionId: string | null;\n expectedActivationVersion: number;\n };\n\nexport type WorkspaceInstructionPolicyOnboardingProposal = WorkspaceInstructionPolicyTarget & {\n id: string;\n operationId: string;\n accountId: string;\n workspaceId: string;\n source: WorkspaceInstructionPolicyOnboardingProposalSource;\n baseline: WorkspaceInstructionPolicyHead | null;\n draft: WorkspaceInstructionPolicyRevision;\n status: \"proposed\";\n createdBySubjectId: string;\n createdAt: string;\n};\n\nexport type WorkspaceInstructionPolicyOnboardingProposalListOptions = {\n limit?: number;\n};\n\nexport type WorkspaceInstructionPolicyOnboardingProposalListResponse = {\n proposals: WorkspaceInstructionPolicyOnboardingProposal[];\n truncated: boolean;\n};\n\nexport type WorkspaceInstructionPolicyOnboardingProposalContentErrorResponse = {\n code:\n | \"WORKSPACE_INSTRUCTION_POLICY_ONBOARDING_PROPOSAL_EMPTY\"\n | \"WORKSPACE_INSTRUCTION_POLICY_ONBOARDING_PROPOSAL_OVERSIZED\";\n message: string;\n maxChars: number;\n};\n\nexport type WorkspaceInstructionPolicyOnboardingProposalStaleResponse = {\n code: \"WORKSPACE_INSTRUCTION_POLICY_ONBOARDING_PROPOSAL_STALE\";\n message: string;\n currentHead: WorkspaceInstructionPolicyHead | null;\n};\n\nexport type WorkspaceInstructionPolicyOnboardingProposalConflictResponse = {\n code: \"WORKSPACE_INSTRUCTION_POLICY_ONBOARDING_PROPOSAL_CONFLICT\";\n message: string;\n existingProposalId: string;\n existingDraftRevisionId: string;\n};\n","export const COMPANY_PROFILE_SCALAR_MAX_CHARS = 2_048;\nexport const COMPANY_PROFILE_ENTRY_MAX_CHARS = 1_024;\nexport const COMPANY_PROFILE_ENTRY_MAX_COUNT = 16;\n\nexport type CompanyProfileEntry = { key: string; content: string };\nexport type CompanyProfileContent = {\n identity: string | null;\n mission: string | null;\n products: CompanyProfileEntry[];\n customers: CompanyProfileEntry[];\n goals: CompanyProfileEntry[];\n constraints: CompanyProfileEntry[];\n};\nexport type CompanyProfileRevisionIdentity = {\n id: string;\n revision: number;\n contentHash: string;\n};\nexport type CompanyProfileRevision = CompanyProfileRevisionIdentity & {\n operationId: string;\n accountId: string;\n intent: \"active\" | \"proposal\";\n profile: CompanyProfileContent;\n provenance: {\n source: \"human\" | \"agent_admin\" | \"durable_learning\" | \"migration\";\n sourceId: string | null;\n };\n supersedesRevisionId: string | null;\n createdBySubjectId: string;\n createdAt: string;\n};\nexport type CompanyProfileHead = {\n accountId: string;\n revisionId: string;\n revision: number;\n contentHash: string;\n activationVersion: number;\n activatedAt: string;\n};\nexport type CompanyProfileActivationEvent = {\n id: string;\n operationId: string;\n accountId: string;\n type: \"activate\" | \"rollback\";\n activationVersion: number;\n oldRevision: CompanyProfileRevisionIdentity | null;\n newRevision: CompanyProfileRevisionIdentity | null;\n actorSubjectId: string;\n reason: string;\n createdAt: string;\n};\nexport type CompanyProfileListOptions = { afterRevision?: number; limit?: number };\nexport type CompanyProfileListResponse = {\n current: CompanyProfileHead | null;\n activeRevision: CompanyProfileRevision | null;\n revisions: CompanyProfileRevision[];\n activationEvents: CompanyProfileActivationEvent[];\n nextAfterRevision: number | null;\n};\nexport type UpdateCompanyProfileRequest = {\n operationId?: string;\n profile: CompanyProfileContent;\n expectedCurrentRevisionId: string | null;\n expectedActivationVersion: number;\n reason: string;\n};\nexport type ActivateCompanyProfileRevisionRequest = {\n operationId?: string;\n expectedCurrentRevisionId: string | null;\n expectedActivationVersion: number;\n reason: string;\n};\nexport type RollbackCompanyProfileRequest = {\n operationId?: string;\n targetRevisionId: string;\n expectedCurrentRevisionId: string;\n expectedActivationVersion: number;\n reason: string;\n};\nexport type CompanyProfileMutationResponse = {\n revision: CompanyProfileRevision | null;\n head: CompanyProfileHead | null;\n event: CompanyProfileActivationEvent | null;\n};\nexport type CompanyProfileAgentPolicyMode = \"off\" | \"suggest\" | \"automatic\";\nexport type CompanyProfileAgentPolicy = {\n organizationId: string;\n mode: CompanyProfileAgentPolicyMode;\n version: number;\n updatedAt: string;\n changed?: boolean;\n};\nexport type UpdateCompanyProfileAgentPolicyRequest = {\n mode: CompanyProfileAgentPolicyMode;\n expectedVersion: number;\n operationId: string;\n};\nexport type CompanyProfileDiffRequest = { fromRevisionId: string; toRevisionId: string };\nexport type CompanyProfileDiffResponse = {\n from: CompanyProfileRevision;\n to: CompanyProfileRevision;\n format: \"unified_json\";\n diff: string;\n};\n\nexport function normalizeCompanyProfileStableKey(value: string): string {\n return value.normalize(\"NFKC\").trim().toLowerCase().replace(/\\s+/gu, \"-\").replace(/-+/g, \"-\");\n}\n","import type {\n CompanyBrainContextReceiptPage as ContractCompanyBrainContextReceiptPage,\n CompanyBrainKnowledgeProposalPage as ContractCompanyBrainKnowledgeProposalPage,\n CompanyBrainOkfPackage as ContractCompanyBrainOkfPackage,\n} from \"@opengeni/contracts\";\n\nexport type CompanyBrainOkfPackage = ContractCompanyBrainOkfPackage;\nexport type CompanyBrainContextReceiptPage = ContractCompanyBrainContextReceiptPage;\nexport type CompanyBrainKnowledgeProposalPage = ContractCompanyBrainKnowledgeProposalPage;\n\nexport type CompanyBrainContextReceiptListOptions = {\n attemptId?: string;\n cursor?: string;\n limit?: number;\n};\n\nexport type CompanyBrainKnowledgeProposalListOptions = {\n limit?: number;\n};\n\nexport type CompanyBrainInspectorTransport = {\n requestJson<T>(method: string, path: string, body?: unknown): Promise<T>;\n};\n\nfunction inspectorPath(workspaceId: string, suffix: string): string {\n return `/v1/workspaces/${workspaceId}/company-brain/${suffix}`;\n}\n\nexport function listCompanyBrainContextReceipts(\n client: CompanyBrainInspectorTransport,\n workspaceId: string,\n options: CompanyBrainContextReceiptListOptions = {},\n): Promise<CompanyBrainContextReceiptPage> {\n const params = new URLSearchParams();\n if (options.attemptId) params.set(\"attemptId\", options.attemptId);\n if (options.cursor) params.set(\"cursor\", options.cursor);\n if (options.limit !== undefined) params.set(\"limit\", String(options.limit));\n const query = params.toString();\n return client.requestJson(\n \"GET\",\n `${inspectorPath(workspaceId, \"context-receipts\")}${query ? `?${query}` : \"\"}`,\n );\n}\n\nexport function listCompanyBrainKnowledgeProposals(\n client: CompanyBrainInspectorTransport,\n workspaceId: string,\n options: CompanyBrainKnowledgeProposalListOptions = {},\n): Promise<CompanyBrainKnowledgeProposalPage> {\n const query =\n options.limit === undefined ? \"\" : `?limit=${encodeURIComponent(String(options.limit))}`;\n return client.requestJson(\"GET\", `${inspectorPath(workspaceId, \"knowledge-proposals\")}${query}`);\n}\n\nexport type CompanyBrainOkfDownload = {\n content: string;\n contentType: string;\n filename: string;\n};\n","export type PreferenceRegistryScope = \"organization\" | \"workspace\" | \"user\";\nexport type PreferenceRegistryStatus =\n | \"proposed\"\n | \"active\"\n | \"inactive\"\n | \"rejected\"\n | \"superseded\"\n | \"expired\";\nexport type PreferenceRegistryProvenanceSource =\n | \"human\"\n | \"onboarding\"\n | \"knowledge_proposal\"\n | \"agent\"\n | \"portable_skill\"\n | \"imported_document\"\n | \"slack\"\n | \"meeting_transcript\"\n | \"call_transcript\";\nexport type PreferenceRegistryTrust =\n | \"untrusted_proposal\"\n | \"personal\"\n | \"workspace_managed\"\n | \"organization_managed\";\nexport type PreferenceRegistryConflictStrategy = \"override\" | \"merge\" | \"reject\" | \"inform\";\n\nexport function normalizePreferenceRegistryStableKey(value: string): string {\n return value.normalize(\"NFKC\").trim().toLowerCase().replace(/\\s+/gu, \"-\").replace(/-+/g, \"-\");\n}\n\nexport type PreferenceRegistryScopeTarget = {\n scope: PreferenceRegistryScope;\n workspaceId: string | null;\n subjectId: string | null;\n};\n\nexport type PreferenceRegistryPrecedence = {\n tier: PreferenceRegistryScope;\n rank: number;\n conflictStrategy: PreferenceRegistryConflictStrategy;\n conflictsWith: string[];\n};\n\nexport type PreferenceRegistryRevisionSummary = {\n id: string;\n preferenceId: string;\n revision: number;\n contentHash: string;\n title: string;\n description: string;\n precedence: PreferenceRegistryPrecedence;\n provenance: {\n source: PreferenceRegistryProvenanceSource;\n sourceId: string | null;\n trust: PreferenceRegistryTrust;\n };\n expiresAt: string | null;\n correctsRevisionId: string | null;\n createdBySubjectId: string;\n createdAt: string;\n};\n\nexport type PreferenceRegistryDescriptorProvenance = {\n source: PreferenceRegistryProvenanceSource;\n sourceIdHash: string | null;\n trust: PreferenceRegistryTrust;\n};\n\nexport type PreferenceRegistryRecord = {\n id: string;\n accountId: string;\n stableKey: string;\n target: PreferenceRegistryScopeTarget;\n status: PreferenceRegistryStatus;\n scopeVersion: number;\n activationVersion: number;\n activeRevision: PreferenceRegistryRevisionSummary | null;\n supersededByPreferenceId: string | null;\n createdBySubjectId: string;\n createdAt: string;\n updatedAt: string;\n};\n\nexport type PreferenceRegistryEvent = {\n id: string;\n accountId: string;\n preferenceId: string;\n type:\n | \"proposal_created\"\n | \"activated\"\n | \"corrected\"\n | \"rejected\"\n | \"deactivated\"\n | \"superseded\"\n | \"scope_changed\";\n version: number;\n oldRevisionId: string | null;\n newRevisionId: string | null;\n oldTarget: PreferenceRegistryScopeTarget | null;\n newTarget: PreferenceRegistryScopeTarget | null;\n relatedPreferenceId: string | null;\n actorSubjectId: string;\n reason: string;\n createdAt: string;\n};\n\nexport type PreferenceRegistryActivationAuthority = \"human_confirmed\" | \"automatic\";\n\nexport type PreferenceRegistryDescriptor = {\n id: string;\n stableKey: string;\n title: string;\n description: string;\n scope: PreferenceRegistryScope;\n activeVersion: number;\n revisionId: string;\n contentHash: string;\n precedence: PreferenceRegistryPrecedence;\n provenance: PreferenceRegistryDescriptorProvenance;\n /**\n * How the active revision became active. `provenance.trust` stays the frozen\n * creation-time fact; this is the separate activation question. Null when the\n * revision became active outside governed learning, or when the descriptor\n * predates this field.\n */\n activationAuthority: PreferenceRegistryActivationAuthority | null;\n expiresAt: string | null;\n retrievalHandle: string;\n};\n\nexport type PreferenceRegistrySnapshot = {\n id: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n initiatingHumanSubjectId: string;\n descriptorHash: string;\n descriptors: PreferenceRegistryDescriptor[];\n truncated: boolean;\n createdAt: string;\n};\n\nexport type PreferenceRegistryFullContent = {\n descriptor: PreferenceRegistryDescriptor;\n content: string;\n};\n\nexport type CreatePreferenceRegistryProposalRequest = {\n stableKey: string;\n scope: PreferenceRegistryScope;\n title: string;\n description: string;\n content: string;\n precedenceRank?: number;\n conflictStrategy?: PreferenceRegistryConflictStrategy;\n conflictsWith?: string[];\n expiresAt?: string | null;\n provenanceSource?: PreferenceRegistryProvenanceSource;\n provenanceSourceId?: string | null;\n};\n\nexport type ActivatePreferenceRegistryRevisionRequest = {\n revisionId: string;\n expectedCurrentRevisionId: string | null;\n expectedScopeVersion: number;\n reason: string;\n};\n\nexport type CorrectPreferenceRegistryRequest = {\n expectedCurrentRevisionId: string;\n expectedScopeVersion: number;\n title: string;\n description: string;\n content: string;\n precedenceRank?: number;\n conflictStrategy?: PreferenceRegistryConflictStrategy;\n conflictsWith?: string[];\n expiresAt?: string | null;\n reason: string;\n};\n\nexport type DeactivatePreferenceRegistryRequest = {\n expectedCurrentRevisionId: string;\n expectedScopeVersion: number;\n reason: string;\n};\n\nexport type ChangePreferenceRegistryScopeRequest = {\n scope: PreferenceRegistryScope;\n expectedScopeVersion: number;\n reason: string;\n};\n\nexport type SupersedePreferenceRegistryRequest = {\n replacementPreferenceId: string;\n expectedCurrentRevisionId: string;\n expectedScopeVersion: number;\n reason: string;\n};\n\nexport type RejectPreferenceRegistryProposalRequest = {\n revisionId: string;\n expectedScopeVersion: number;\n reason: string;\n};\nexport type PreferenceRegistryListOptions = {\n scope?: PreferenceRegistryScope;\n status?: PreferenceRegistryStatus;\n limit?: number;\n};\nexport type PreferenceRegistryListResponse = { preferences: PreferenceRegistryRecord[] };\nexport type PreferenceRegistryDetailResponse = {\n preference: PreferenceRegistryRecord;\n revisions: PreferenceRegistryRevisionSummary[];\n events: PreferenceRegistryEvent[];\n};\nexport type PreferenceRegistryMutationResponse = {\n preference: PreferenceRegistryRecord;\n event: PreferenceRegistryEvent;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAM,gBACJ;AACF,IAAM,uBAAuB,CAAC,KAAa,SAA4B,CAAC,M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AG,cAAc,aAAa,kBAAkB,CAAC,GAAG,QAAQ,IAAI,KAAK,KAAK,EAAE;AAAA,EAC9E;AACF;AAEO,SAAS,mCACd,QACA,aACA,UAAoD,CAAC,GACT;AAC5C,QAAM,QACJ,QAAQ,UAAU,SAAY,KAAK,UAAU,mBAAmB,OAAO,QAAQ,KAAK,CAAC,CAAC;AACxF,SAAO,OAAO,YAAY,OAAO,GAAG,cAAc,aAAa,qBAAqB,CAAC,GAAG,KAAK,EAAE;AACjG;;;AC3BO,SAAS,qCAAqC,OAAuB;AAC1E,SAAO,MAAM,UAAU,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,QAAQ,SAAS,GAAG,EAAE,QAAQ,OAAO,GAAG;AAC9F;","names":[]}
|
package/dist/realtime.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ export type SessionRealtimeClientLike = CodexRealtimeControllerClient & {
|
|
|
13
13
|
signal?: AbortSignal | undefined;
|
|
14
14
|
}): Promise<WorkspaceRealtimeModelCatalogResponse>;
|
|
15
15
|
};
|
|
16
|
-
export type SessionRealtimeTransportKind = "codex" | "gateway" | "xai-subscription";
|
|
16
|
+
export type SessionRealtimeTransportKind = "codex" | "gateway" | "xai-subscription" | "azure-live";
|
|
17
17
|
/** Provider-neutral names for the existing, battle-tested controller projection. */
|
|
18
18
|
export type SessionRealtimeController = CodexRealtimeController;
|
|
19
19
|
export type SessionRealtimeControllerSnapshot = CodexRealtimeControllerSnapshot;
|
package/dist/realtime.js
CHANGED
|
@@ -23,15 +23,256 @@ import {
|
|
|
23
23
|
sessionRealtimeOwnerStorageKey,
|
|
24
24
|
sessionRealtimeOwnerStorageNamespace,
|
|
25
25
|
startCodexRealtimeWebrtc
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-ZNC44QEX.js";
|
|
27
27
|
import {
|
|
28
28
|
createGatewayRealtimeTransportStarter,
|
|
29
29
|
createXaiSubscriptionRealtimeTransportStarter
|
|
30
30
|
} from "./chunk-KWADQ227.js";
|
|
31
31
|
import "./chunk-V6GIY62B.js";
|
|
32
32
|
|
|
33
|
+
// src/azure-live-transport.ts
|
|
34
|
+
var MAX_FRAGMENT_BYTES = 64e3;
|
|
35
|
+
function takeUtf8Tail(text, maxBytes = MAX_FRAGMENT_BYTES) {
|
|
36
|
+
const encoder = new TextEncoder();
|
|
37
|
+
if (encoder.encode(text).byteLength <= maxBytes) return text;
|
|
38
|
+
let tail = text.slice(-maxBytes);
|
|
39
|
+
while (encoder.encode(tail).byteLength > maxBytes) tail = tail.slice(1);
|
|
40
|
+
return tail;
|
|
41
|
+
}
|
|
42
|
+
var AzureLiveDataChannel = class extends EventTarget {
|
|
43
|
+
constructor(raw, drainTimeoutMs = 5e3) {
|
|
44
|
+
super();
|
|
45
|
+
this.raw = raw;
|
|
46
|
+
this.drainTimeoutMs = drainTimeoutMs;
|
|
47
|
+
raw.addEventListener("open", this.onOpen);
|
|
48
|
+
raw.addEventListener("close", this.onClose);
|
|
49
|
+
raw.addEventListener("error", this.onError);
|
|
50
|
+
raw.addEventListener("message", this.onMessage);
|
|
51
|
+
}
|
|
52
|
+
pending = null;
|
|
53
|
+
timer = null;
|
|
54
|
+
ordinal = 0;
|
|
55
|
+
prefix = crypto.randomUUID();
|
|
56
|
+
closed = false;
|
|
57
|
+
closeSent = false;
|
|
58
|
+
providerClosed = false;
|
|
59
|
+
delegations = /* @__PURE__ */ new Set();
|
|
60
|
+
// Azure delegations carry no content, so the user's words since the previous
|
|
61
|
+
// delegation become the delegation input.
|
|
62
|
+
userSinceDelegation = "";
|
|
63
|
+
draining = null;
|
|
64
|
+
finishDrain = null;
|
|
65
|
+
onOpen = () => this.dispatchEvent(new Event("open"));
|
|
66
|
+
onClose = () => {
|
|
67
|
+
this.providerClosed = true;
|
|
68
|
+
this.flush();
|
|
69
|
+
this.finishDrain?.();
|
|
70
|
+
this.dispatchEvent(new Event("close"));
|
|
71
|
+
};
|
|
72
|
+
onError = () => this.dispatchEvent(new Event("error"));
|
|
73
|
+
onMessage = (event) => {
|
|
74
|
+
if (typeof event.data !== "string" || event.data.length > 1048576) return;
|
|
75
|
+
let value;
|
|
76
|
+
try {
|
|
77
|
+
value = JSON.parse(event.data);
|
|
78
|
+
} catch {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (!value || typeof value !== "object") return;
|
|
82
|
+
this.receive(value);
|
|
83
|
+
};
|
|
84
|
+
get readyState() {
|
|
85
|
+
return this.closed || this.providerClosed ? "closed" : this.closeSent ? "closing" : this.raw.readyState;
|
|
86
|
+
}
|
|
87
|
+
asRtcDataChannel() {
|
|
88
|
+
return this;
|
|
89
|
+
}
|
|
90
|
+
emit(value) {
|
|
91
|
+
if (!this.closed)
|
|
92
|
+
this.dispatchEvent(new MessageEvent("message", { data: JSON.stringify(value) }));
|
|
93
|
+
}
|
|
94
|
+
flush() {
|
|
95
|
+
if (this.timer) clearTimeout(this.timer);
|
|
96
|
+
this.timer = null;
|
|
97
|
+
const pending = this.pending;
|
|
98
|
+
this.pending = null;
|
|
99
|
+
if (!pending?.text) return;
|
|
100
|
+
this.emit({
|
|
101
|
+
type: "transcript.segment",
|
|
102
|
+
turn: {
|
|
103
|
+
id: `${this.prefix}:${++this.ordinal}`,
|
|
104
|
+
role: pending.role,
|
|
105
|
+
transcript: pending.text
|
|
106
|
+
},
|
|
107
|
+
start_ms: pending.startMs,
|
|
108
|
+
end_ms: pending.endMs
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
receive(value) {
|
|
112
|
+
if (this.closed) return;
|
|
113
|
+
if (value.type === "session.input_transcript.delta" || value.type === "session.output_transcript.delta") {
|
|
114
|
+
if (typeof value.delta !== "string" || typeof value.start_ms !== "number" || typeof value.end_ms !== "number")
|
|
115
|
+
return;
|
|
116
|
+
const role = value.type === "session.input_transcript.delta" ? "user" : "assistant";
|
|
117
|
+
if (role === "user")
|
|
118
|
+
this.userSinceDelegation = takeUtf8Tail(this.userSinceDelegation + value.delta);
|
|
119
|
+
if (this.pending && (this.pending.role !== role || new TextEncoder().encode(this.pending.text + value.delta).byteLength > MAX_FRAGMENT_BYTES))
|
|
120
|
+
this.flush();
|
|
121
|
+
if (new TextEncoder().encode(value.delta).byteLength > MAX_FRAGMENT_BYTES) {
|
|
122
|
+
this.emit({
|
|
123
|
+
type: "error",
|
|
124
|
+
error: { message: "Voice transcript fragment exceeded the supported size" }
|
|
125
|
+
});
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
this.pending = {
|
|
129
|
+
role,
|
|
130
|
+
text: (this.pending?.text ?? "") + value.delta,
|
|
131
|
+
startMs: this.pending?.startMs ?? value.start_ms,
|
|
132
|
+
endMs: value.end_ms
|
|
133
|
+
};
|
|
134
|
+
if (!this.timer) this.timer = setTimeout(() => this.flush(), 1e3);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (value.type === "session.delegation.created") {
|
|
138
|
+
const delegation = value.delegation;
|
|
139
|
+
if (delegation?.target !== "client" || typeof delegation.id !== "string") return;
|
|
140
|
+
this.delegations.add(delegation.id);
|
|
141
|
+
this.flush();
|
|
142
|
+
const spoken = this.userSinceDelegation.trim();
|
|
143
|
+
this.userSinceDelegation = "";
|
|
144
|
+
this.emit({
|
|
145
|
+
type: "delegation.created",
|
|
146
|
+
item: {
|
|
147
|
+
id: delegation.id,
|
|
148
|
+
type: "delegation",
|
|
149
|
+
target: "client",
|
|
150
|
+
content: spoken ? [{ type: "input_text", text: spoken }] : []
|
|
151
|
+
},
|
|
152
|
+
offset_ms: value.offset_ms
|
|
153
|
+
});
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (value.type === "session.closed") {
|
|
157
|
+
this.providerClosed = true;
|
|
158
|
+
this.flush();
|
|
159
|
+
this.finishDrain?.();
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
if (value.type === "session.started" || value.type === "session.updated" || value.type === "error")
|
|
163
|
+
this.emit(value);
|
|
164
|
+
}
|
|
165
|
+
send(payload) {
|
|
166
|
+
if (this.readyState !== "open") throw Error("Hosted voice channel is not open");
|
|
167
|
+
const value = JSON.parse(payload);
|
|
168
|
+
if (value.type !== "session.context.append" && value.type !== "delegation.context.append")
|
|
169
|
+
throw Error("Unsupported hosted voice context event");
|
|
170
|
+
const content = Array.isArray(value.content) ? value.content.map((part) => typeof part?.text === "string" ? part.text : "").join("") : "";
|
|
171
|
+
this.raw.send(
|
|
172
|
+
JSON.stringify({
|
|
173
|
+
type: value.channel === "speakable" ? "session.commentary.append" : "session.thinking.append",
|
|
174
|
+
content,
|
|
175
|
+
// Replayed tasks from an earlier provider session are general context.
|
|
176
|
+
delegation_id: value.type === "delegation.context.append" && typeof value.delegation_item_id === "string" && this.delegations.has(value.delegation_item_id) ? value.delegation_item_id : null
|
|
177
|
+
})
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
drain() {
|
|
181
|
+
if (this.draining) return this.draining;
|
|
182
|
+
if (this.providerClosed || this.raw.readyState === "closed") {
|
|
183
|
+
this.flush();
|
|
184
|
+
return Promise.resolve();
|
|
185
|
+
}
|
|
186
|
+
if (this.closed || this.raw.readyState !== "open") {
|
|
187
|
+
return Promise.reject(new Error("Hosted voice close is not confirmed"));
|
|
188
|
+
}
|
|
189
|
+
const pending = new Promise((resolve, reject) => {
|
|
190
|
+
const timeout = setTimeout(() => {
|
|
191
|
+
this.flush();
|
|
192
|
+
this.finishDrain?.(
|
|
193
|
+
new Error("Hosted voice is still closing; retry to preserve final speech")
|
|
194
|
+
);
|
|
195
|
+
}, this.drainTimeoutMs);
|
|
196
|
+
this.finishDrain = (error) => {
|
|
197
|
+
clearTimeout(timeout);
|
|
198
|
+
this.finishDrain = null;
|
|
199
|
+
if (error) reject(error);
|
|
200
|
+
else resolve();
|
|
201
|
+
};
|
|
202
|
+
if (!this.closeSent) {
|
|
203
|
+
this.closeSent = true;
|
|
204
|
+
try {
|
|
205
|
+
this.raw.send(JSON.stringify({ type: "session.close" }));
|
|
206
|
+
} catch {
|
|
207
|
+
this.finishDrain(new Error("Hosted voice close could not be sent"));
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
this.draining = pending;
|
|
212
|
+
void pending.then(
|
|
213
|
+
() => {
|
|
214
|
+
if (this.draining === pending) this.draining = null;
|
|
215
|
+
},
|
|
216
|
+
() => {
|
|
217
|
+
if (this.draining === pending) this.draining = null;
|
|
218
|
+
}
|
|
219
|
+
);
|
|
220
|
+
return pending;
|
|
221
|
+
}
|
|
222
|
+
close() {
|
|
223
|
+
if (this.closed) return;
|
|
224
|
+
if (this.timer) clearTimeout(this.timer);
|
|
225
|
+
this.timer = null;
|
|
226
|
+
this.pending = null;
|
|
227
|
+
this.finishDrain?.(new Error("Hosted voice channel was disposed before close confirmation"));
|
|
228
|
+
this.closed = true;
|
|
229
|
+
this.raw.removeEventListener("open", this.onOpen);
|
|
230
|
+
this.raw.removeEventListener("close", this.onClose);
|
|
231
|
+
this.raw.removeEventListener("error", this.onError);
|
|
232
|
+
this.raw.removeEventListener("message", this.onMessage);
|
|
233
|
+
this.dispatchEvent(new Event("close"));
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
function createAzureLiveTransportStarter(options = {}) {
|
|
237
|
+
return async (input) => {
|
|
238
|
+
let channel;
|
|
239
|
+
try {
|
|
240
|
+
const transport = await startCodexRealtimeWebrtc({
|
|
241
|
+
...input,
|
|
242
|
+
...options,
|
|
243
|
+
activateRemoteAudio: false,
|
|
244
|
+
expectedModel: "opengeni-azure/gpt-live-1",
|
|
245
|
+
onEventsCreated(raw) {
|
|
246
|
+
channel = new AzureLiveDataChannel(raw);
|
|
247
|
+
input.onEventsCreated(channel.asRtcDataChannel());
|
|
248
|
+
},
|
|
249
|
+
negotiate: (request, requestOptions) => input.client.negotiateCodexRealtimeWebrtc(
|
|
250
|
+
input.workspaceId,
|
|
251
|
+
input.sessionId,
|
|
252
|
+
request,
|
|
253
|
+
requestOptions
|
|
254
|
+
)
|
|
255
|
+
});
|
|
256
|
+
const events = channel;
|
|
257
|
+
return {
|
|
258
|
+
...transport,
|
|
259
|
+
events: events.asRtcDataChannel(),
|
|
260
|
+
drain: () => events.drain(),
|
|
261
|
+
stop() {
|
|
262
|
+
events.close();
|
|
263
|
+
transport.stop();
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
} catch (error) {
|
|
267
|
+
channel?.close();
|
|
268
|
+
throw error;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
33
273
|
// src/realtime.ts
|
|
34
274
|
function sessionRealtimeTransportKind(model) {
|
|
275
|
+
if (model === "opengeni-azure/gpt-live-1") return "azure-live";
|
|
35
276
|
if (model === "gpt-live-1-boulder-alpha") return "codex";
|
|
36
277
|
if (model === "supergrok/grok-voice-think-fast-2.0") return "xai-subscription";
|
|
37
278
|
return "gateway";
|
|
@@ -41,7 +282,12 @@ function createSessionRealtimeController(options) {
|
|
|
41
282
|
return createCodexRealtimeController({
|
|
42
283
|
...options,
|
|
43
284
|
ownerStorageNamespace: sessionRealtimeOwnerStorageNamespace(options.model),
|
|
44
|
-
...transport === "
|
|
285
|
+
...transport === "azure-live" ? {
|
|
286
|
+
startTransport: createAzureLiveTransportStarter({
|
|
287
|
+
remoteAudio: options.remoteAudio,
|
|
288
|
+
createPeerConnection: options.createPeerConnection
|
|
289
|
+
})
|
|
290
|
+
} : transport === "gateway" ? { startTransport: createGatewayRealtimeTransportStarter() } : transport === "xai-subscription" ? { startTransport: createXaiSubscriptionRealtimeTransportStarter() } : {}
|
|
45
291
|
});
|
|
46
292
|
}
|
|
47
293
|
export {
|