@opengeni/sdk 4.0.2 → 5.0.3-canary.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 +58 -9
- package/dist/artifact-client.d.ts +18 -8
- package/dist/artifacts.js +4 -4
- package/dist/browser.js +2 -2
- package/dist/chat/ids.d.ts +3 -3
- package/dist/chat/index.js +38 -51
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/opengeni.d.ts +10 -12
- package/dist/chat/types.d.ts +7 -3
- package/dist/{chunk-O23OOWJK.js → chunk-4YAL54F3.js} +2 -2
- package/dist/{chunk-UW22XVCT.js → chunk-ARGX7UY4.js} +97 -2
- package/dist/chunk-ARGX7UY4.js.map +1 -0
- package/dist/chunk-J5USCWPE.js +195 -0
- package/dist/chunk-J5USCWPE.js.map +1 -0
- package/dist/{chunk-WNEGCYCE.js → chunk-TARU5CD2.js} +1 -1
- package/dist/chunk-TARU5CD2.js.map +1 -0
- package/dist/{chunk-3IZMCD2K.js → chunk-TOB3B4ZJ.js} +28 -41
- package/dist/chunk-TOB3B4ZJ.js.map +1 -0
- package/dist/{chunk-2H7P45YQ.js → chunk-UQGHX4DI.js} +173 -7
- package/dist/chunk-UQGHX4DI.js.map +1 -0
- package/dist/client.d.ts +39 -4
- package/dist/core.js +3 -3
- package/dist/document-authority.js +3 -3
- package/dist/editable-artifacts.js +1 -1
- package/dist/embedding-client.d.ts +72 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.js +13 -8
- package/dist/index.js.map +1 -1
- package/dist/site-tool-bridge.d.ts +39 -0
- package/dist/site.d.ts +2 -0
- package/dist/site.js +7 -3
- package/dist/types.d.ts +23 -12
- package/package.json +3 -2
- package/src/artifact-client.ts +38 -63
- package/src/chat/ids.ts +3 -3
- package/src/chat/opengeni.ts +41 -57
- package/src/chat/types.ts +7 -3
- package/src/client.ts +253 -12
- package/src/embedding-client.ts +308 -0
- package/src/index.ts +16 -1
- package/src/site-tool-bridge.ts +141 -0
- package/src/site.ts +7 -0
- package/src/types.ts +18 -6
- package/dist/chunk-2H7P45YQ.js.map +0 -1
- package/dist/chunk-3IZMCD2K.js.map +0 -1
- package/dist/chunk-UW22XVCT.js.map +0 -1
- package/dist/chunk-WNEGCYCE.js.map +0 -1
- /package/dist/{chunk-O23OOWJK.js.map → chunk-4YAL54F3.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../contracts/src/session-titles.ts","../src/proxy.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":["/** Human-authored session titles keep the existing public API ceiling. */\nexport const SESSION_TITLE_MAX_CHARACTERS = 200;\n\n/**\n * Automatic titles are intentionally much shorter than the manual rename\n * ceiling. This is measured in grapheme clusters so emoji and combining text\n * are never split into malformed display strings.\n */\nexport const AUTOMATIC_SESSION_TITLE_MAX_GRAPHEMES = 80;\n\n/**\n * Safe durable title used until semantic generation succeeds. It contains no\n * user prompt bytes, so provider failure/offline operation cannot leak a\n * credential or leave a raw prompt prefix in navigation surfaces.\n */\nexport const AUTOMATIC_SESSION_TITLE_FALLBACK = \"New conversation\";\n\n// Session creation accepts a body far larger than a navigation label. Bound\n// the source before any replace/split/normalization so a persisted large prompt\n// cannot amplify memory or CPU on every client render.\nconst PROMPT_PREVIEW_SCAN_MAX_CODE_UNITS = 4_096;\n\nconst SESSION_ID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\n\nlet titleSegmenter: Intl.Segmenter | null | undefined;\n\nconst KNOWN_SENSITIVE_VALUE_PATTERNS = [\n /-----BEGIN [A-Z ]*PRIVATE KEY-----/iu,\n /\\bBearer\\s+[A-Za-z0-9._~+/=-]{8,}/iu,\n /\\b(?:sk-(?:proj-)?|gh[oprsu]_|github_pat_|glpat-|xox[baprs]-)[A-Za-z0-9_-]{8,}/iu,\n /\\bAKIA[0-9A-Z]{16}\\b/u,\n /\\bAIza[0-9A-Za-z_-]{20,}\\b/u,\n /\\beyJ[A-Za-z0-9_-]+\\.eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b/u,\n /[?&](?:access_token|api_key|apikey|password|secret|token)=[^\\s&#]+/iu,\n] as const;\n\nconst URI_SCHEME_CANDIDATE_PATTERN = /\\b[a-z][a-z0-9+.-]*:\\S+/giu;\nconst WINDOWS_DRIVE_PATH_PATTERN = /^[a-z]:[\\\\/](?![\\\\/])[^:]*$/iu;\n\nconst SCHEMELESS_HOST_CANDIDATE_PATTERN =\n /\\b(?:www\\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?(?::\\d{1,5})?(?:[/?#][^\\s]*)?/giu;\n\nconst SCHEMELESS_LOCAL_NETWORK_PATTERNS = [\n /\\blocalhost(?:(?::\\d{1,5})(?:[/?#][^\\s]*)?|[/?#][^\\s]*)/iu,\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)(?:(?::\\d{1,5})(?:[/?#][^\\s]*)?|[/?#][^\\s]*)/u,\n /\\[(?=[0-9a-f:.]*:[0-9a-f:.]*\\])[0-9a-f:.]+\\](?:(?::\\d{1,5})(?:[/?#][^\\s]*)?|[/?#][^\\s]*)/iu,\n] as const;\n\nconst FILE_LIKE_HOST_SUFFIXES = new Set([\n \"css\",\n \"html\",\n \"js\",\n \"json\",\n \"jsx\",\n \"lock\",\n \"md\",\n \"sql\",\n \"toml\",\n \"ts\",\n \"tsx\",\n \"xml\",\n \"yaml\",\n \"yml\",\n]);\n\n// These authorities are established framework/namespace notation whose exact\n// casing is meaningful. Keep this exception deliberately narrow: generic\n// PascalCase or uppercase authorities remain host-like because an uppercase\n// real domain (for example MICROSOFT.COM/Admin) must not bypass the URL gate.\nconst DOTTED_TECHNOLOGY_PATH_AUTHORITIES = new Set([\n \"ASP.NET\",\n \"AWS.SDK\",\n \"Microsoft.Extensions\",\n \"System.IO\",\n]);\n\nconst SECRET_ASSIGNMENT_CANDIDATE_PATTERN =\n /(?:^|[^A-Za-z0-9])(?:(['\"])([A-Za-z][A-Za-z0-9_. -]*)\\1|([A-Za-z][A-Za-z0-9_.-]*))\\s*[=:]\\s*[^\\s,;]+/gu;\n\nconst SECRET_LABEL_ASSIGNMENT_PATTERN =\n /\\b(?:api[ _-]?key|access[ _-]?token|auth[ _-]?token|credential|credentials|password|passwd|private[ _-]?key|secret|token)\\b\\s*[=:]\\s*[^\\s,;]+/iu;\n\nconst SENSITIVE_ASSIGNMENT_KEY_SUFFIXES = new Set([\n \"credential\",\n \"credentials\",\n \"password\",\n \"passwd\",\n \"secret\",\n \"token\",\n]);\n\nconst COMPACT_SENSITIVE_ASSIGNMENT_KEY_SUFFIXES = [\n \"apikey\",\n \"accesskey\",\n \"accesskeyid\",\n \"accesstoken\",\n \"authtoken\",\n \"credential\",\n \"credentials\",\n \"password\",\n \"passwd\",\n \"privatekey\",\n \"secret\",\n \"secretkey\",\n \"token\",\n] as const;\n\nconst SENSITIVE_ASSIGNMENT_KEY_WORD_SUFFIXES = [\n [\"api\", \"key\"],\n [\"access\", \"key\"],\n [\"access\", \"key\", \"id\"],\n [\"auth\", \"key\"],\n [\"private\", \"key\"],\n [\"secret\", \"key\"],\n] as const;\n\nfunction hasWordSuffix(words: readonly string[], suffix: readonly string[]): boolean {\n if (words.length < suffix.length) return false;\n const offset = words.length - suffix.length;\n return suffix.every((word, index) => words[offset + index] === word);\n}\n\nfunction containsSensitiveAssignment(value: string): boolean {\n for (const match of value.matchAll(SECRET_ASSIGNMENT_CANDIDATE_PATTERN)) {\n const key = match[2] ?? match[3];\n if (!key) continue;\n const words = key\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1 $2\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter(Boolean);\n const last = words.at(-1);\n if (last && SENSITIVE_ASSIGNMENT_KEY_SUFFIXES.has(last)) return true;\n if (last && COMPACT_SENSITIVE_ASSIGNMENT_KEY_SUFFIXES.some((suffix) => last.endsWith(suffix))) {\n return true;\n }\n if (SENSITIVE_ASSIGNMENT_KEY_WORD_SUFFIXES.some((suffix) => hasWordSuffix(words, suffix))) {\n return true;\n }\n }\n return false;\n}\n\nfunction containsUriScheme(value: string): boolean {\n for (const match of value.matchAll(URI_SCHEME_CANDIDATE_PATTERN)) {\n // A Windows drive path is the one scheme-shaped token accepted here. Keep\n // the exception exact: one separator after the drive letter and no later\n // colon, so x://host and a nested scheme remain rejected.\n if (!WINDOWS_DRIVE_PATH_PATTERN.test(match[0])) return true;\n }\n return false;\n}\n\nfunction isDottedTechnologyPath(candidate: string): boolean {\n if (/[?:#]/u.test(candidate)) return false;\n const [authority, ...pathSegments] = candidate.split(\"/\");\n if (!authority || pathSegments.length === 0 || pathSegments.some((segment) => !segment)) {\n return false;\n }\n if (\n !DOTTED_TECHNOLOGY_PATH_AUTHORITIES.has(authority) ||\n pathSegments.some((segment) => !/^[A-Z][A-Za-z0-9_-]*$/u.test(segment))\n ) {\n return false;\n }\n return true;\n}\n\nfunction containsSchemelessUrl(value: string): boolean {\n if (SCHEMELESS_LOCAL_NETWORK_PATTERNS.some((pattern) => pattern.test(value))) return true;\n\n for (const match of value.matchAll(SCHEMELESS_HOST_CANDIDATE_PATTERN)) {\n const candidate = match[0];\n if (candidate.toLowerCase().startsWith(\"www.\")) return true;\n if (!/[/?#]/u.test(candidate)) continue;\n\n const authority = candidate.split(/[/?#]/u, 1)[0] ?? \"\";\n const hostname = authority.replace(/:\\d{1,5}$/u, \"\");\n const suffix = hostname.split(\".\").at(-1)?.toLowerCase();\n if (suffix && FILE_LIKE_HOST_SUFFIXES.has(suffix)) continue;\n if (isDottedTechnologyPath(candidate)) continue;\n return true;\n }\n return false;\n}\n\nconst OPAQUE_IDENTIFIER_PATTERN =\n /\\b(?=[A-Za-z0-9_-]{32,}\\b)(?=[A-Za-z0-9_-]*[A-Za-z])(?=[A-Za-z0-9_-]*\\d)[A-Za-z0-9_-]+\\b/u;\n\nconst DEFAULT_IGNORABLE_CODE_POINTS = /\\p{Default_Ignorable_Code_Point}+/gu;\nconst ESCAPED_QUOTE_DELIMITERS = /\\\\+(?=[\"'])/gu;\n\nconst TITLE_LABEL_PATTERN =\n /^(?:(?:suggested|generated|concise)\\s+)?(?:(?:session|chat|conversation|task)\\s+)?title\\s*[:\\-–—]\\s*/iu;\n\nconst LEADING_BOILERPLATE_PATTERNS = [\n /^(?:hi|hello|hey)(?:\\s+there)?\\s*[,!:.\\-–—]*\\s*/iu,\n /^(?:i\\s+(?:would\\s+like|want|need)\\s+you\\s+to|i['’]d\\s+like\\s+you\\s+to)\\s+/iu,\n /^(?:please\\s+)?(?:can|could|would|will)\\s+you\\s+/iu,\n /^(?:your|the)\\s+(?:task|job)\\s+is\\s+to\\s+/iu,\n /^(?:please\\s+)?help\\s+me\\s+(?:to\\s+)?/iu,\n /^please(?:\\s*[,!:.\\-–—]+\\s*|\\s+|$)/iu,\n] as const;\n\nfunction automaticTitleDetectionValue(value: string): string {\n // Detection uses a compatibility-normalized shadow value so fullwidth\n // punctuation/letters, invisible token splits, and serialized quote\n // delimiters cannot evade the policy.\n // The accepted title itself stays byte-for-byte in the user's language and\n // emoji form; this shadow is never returned or persisted.\n return value\n .normalize(\"NFKC\")\n .replace(DEFAULT_IGNORABLE_CODE_POINTS, \"\")\n .replace(ESCAPED_QUOTE_DELIMITERS, \"\");\n}\n\nfunction hasVisibleAutomaticTitleContent(value: string): boolean {\n return automaticTitleDetectionValue(value).trim().length > 0;\n}\n\n/**\n * Whether a bounded automatic-title candidate contains a credential, URL, or\n * opaque identifier that must stay out of navigation and other display-title\n * surfaces. Callers handling an unbounded source must bound it before invoking\n * this helper.\n */\nexport function containsSensitiveAutomaticSessionTitleValue(value: string): boolean {\n const detectionValue = automaticTitleDetectionValue(value);\n\n if (KNOWN_SENSITIVE_VALUE_PATTERNS.some((pattern) => pattern.test(detectionValue))) return true;\n if (containsUriScheme(detectionValue)) return true;\n if (containsSchemelessUrl(detectionValue)) return true;\n if (SECRET_LABEL_ASSIGNMENT_PATTERN.test(detectionValue)) return true;\n if (containsSensitiveAssignment(detectionValue)) return true;\n if (OPAQUE_IDENTIFIER_PATTERN.test(detectionValue)) return true;\n return false;\n}\n\nfunction stripAutomaticTitleBoilerplate(value: string): string {\n let title = value;\n for (let pass = 0; pass < 4; pass += 1) {\n const before = title;\n title = title\n .replace(/^(?:```[^\\n]*|[\\s#>*_`\"'“”‘’\\-–—]+)+/u, \"\")\n .replace(TITLE_LABEL_PATTERN, \"\");\n for (const pattern of LEADING_BOILERPLATE_PATTERNS) {\n title = title.replace(pattern, \"\");\n }\n title = title.trim();\n if (title === before) break;\n }\n return title;\n}\n\nfunction automaticTitleGraphemes(value: string): string[] {\n if (titleSegmenter === undefined) {\n titleSegmenter =\n typeof Intl.Segmenter === \"function\"\n ? new Intl.Segmenter(undefined, { granularity: \"grapheme\" })\n : null;\n }\n if (titleSegmenter) {\n return Array.from(titleSegmenter.segment(value), (part) => part.segment);\n }\n\n // Older embedded runtimes may not ship Intl.Segmenter. Preserve surrogate\n // pairs plus common combining/emoji sequences instead of failing module load\n // or slicing UTF-16 code units.\n const graphemes: string[] = [];\n for (const point of value) {\n const prior = graphemes.at(-1);\n if (\n prior &&\n (/^[\\p{Mark}\\u{FE0E}\\u{FE0F}\\p{Emoji_Modifier}]$/u.test(point) ||\n point === \"\\u200d\" ||\n prior.endsWith(\"\\u200d\"))\n ) {\n graphemes[graphemes.length - 1] = `${prior}${point}`;\n } else {\n graphemes.push(point);\n }\n }\n return graphemes;\n}\n\n/** Bound an already-normalized automatic-title candidate without splitting graphemes. */\nexport function boundAutomaticSessionTitle(value: string): string {\n const words = value.split(/\\s+/u);\n const wordBounded = words.length > 10 ? words.slice(0, 10).join(\" \") : value;\n const graphemes = automaticTitleGraphemes(wordBounded);\n if (graphemes.length <= AUTOMATIC_SESSION_TITLE_MAX_GRAPHEMES) return wordBounded;\n\n const prefix = graphemes.slice(0, AUTOMATIC_SESSION_TITLE_MAX_GRAPHEMES).join(\"\");\n const lastWhitespace = prefix.search(/\\s+\\S*$/u);\n return (lastWhitespace >= 16 ? prefix.slice(0, lastWhitespace) : prefix).trimEnd();\n}\n\n/**\n * Normalize a model/system-authored title before it reaches durable session\n * metadata. Human renames intentionally do not use this path.\n *\n * Returns null when the candidate is empty, only boilerplate, or appears to\n * contain a credential/opaque prompt value. Callers should retain the current\n * title (normally {@link AUTOMATIC_SESSION_TITLE_FALLBACK}) in that case.\n */\nexport function normalizeAutomaticSessionTitle(value: string): string | null {\n const firstLine = value\n .replace(/[\\u0000-\\u001f\\u007f-\\u009f]+/gu, \"\\n\")\n .split(/\\n+/u)\n .map((line) => line.trim())\n .find(Boolean);\n if (\n !firstLine ||\n !hasVisibleAutomaticTitleContent(firstLine) ||\n containsSensitiveAutomaticSessionTitleValue(firstLine)\n ) {\n return null;\n }\n\n let title = stripAutomaticTitleBoilerplate(firstLine)\n .replace(/\\s+/gu, \" \")\n .replace(/[\\s.!?,;:\\-–—]+$/u, \"\")\n .trim();\n if (\n !title ||\n !hasVisibleAutomaticTitleContent(title) ||\n containsSensitiveAutomaticSessionTitleValue(title)\n ) {\n return null;\n }\n\n title = boundAutomaticSessionTitle(title)\n .replace(/[\\s.!?,;:\\-–—]+$/u, \"\")\n .trim();\n if (!title || !hasVisibleAutomaticTitleContent(title)) return null;\n return title;\n}\n\nexport type SessionDisplayTitleInput = {\n id?: string | null | undefined;\n title?: string | null | undefined;\n titleSource?: \"user\" | \"agent\" | null | undefined;\n initialMessage?: string | null | undefined;\n metadata?: Readonly<Record<string, unknown>> | undefined;\n};\n\nexport type SessionDisplayTitleOptions = {\n /** Optional metadata fields to try before the opening-prompt preview. */\n metadataKeys?: readonly string[] | undefined;\n};\n\n/**\n * Derive a bounded, sensitive-safe preview from the opening prompt.\n *\n * Unsafe leading lines are skipped instead of forcing the whole session back\n * to a generic label. This covers prompts that begin with a pasted URL or\n * identifier followed by an ordinary natural-language request on the next\n * line, without putting the rejected value into navigation surfaces.\n */\nexport function deriveAutomaticSessionTitlePreview(value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n\n const lines = value\n .slice(0, PROMPT_PREVIEW_SCAN_MAX_CODE_UNITS)\n .replace(/[\\u0000-\\u001f\\u007f-\\u009f]+/gu, \"\\n\")\n .split(/\\n+/u);\n\n for (const candidate of lines) {\n const line = candidate.trim();\n if (!line || containsSensitiveAutomaticSessionTitleValue(line)) continue;\n\n const preview = boundAutomaticSessionTitle(line.replace(/\\s+/gu, \" \"))\n .replace(/[\\s.!?,;:\\-–—]+$/u, \"\")\n .trim();\n if (preview) return preview;\n }\n\n return null;\n}\n\nfunction automaticSessionReferenceTitle(id: unknown): string {\n const sessionId = typeof id === \"string\" ? id.trim() : \"\";\n return SESSION_ID_PATTERN.test(sessionId)\n ? `Conversation ${sessionId.slice(0, 13)}`\n : AUTOMATIC_SESSION_TITLE_FALLBACK;\n}\n\n/**\n * Whether the durable title still represents the automatic-title pending state.\n * A user-authored title always wins, even when its literal value is the marker.\n */\nexport function sessionTitleIsPending(input: SessionDisplayTitleInput): boolean {\n const title = input.title?.trim() ?? \"\";\n return input.titleSource !== \"user\" && (!title || title === AUTOMATIC_SESSION_TITLE_FALLBACK);\n}\n\n/**\n * Derive the title a human-facing client should display for a session.\n *\n * A semantic agent title or human rename wins. While automatic naming is still\n * pending, clients show a short, sensitive-safe preview of the opening prompt.\n * If no safe prompt text exists, a UUID-derived reference keeps real sessions\n * distinguishable without exposing prompt bytes. The durable pending marker is\n * therefore an internal lifecycle value rather than the ordinary visible name.\n */\nexport function deriveSessionDisplayTitle(\n input: SessionDisplayTitleInput,\n options: SessionDisplayTitleOptions = {},\n): string {\n const title = input.title?.trim() ?? \"\";\n if (input.titleSource === \"user\") {\n return title || automaticSessionReferenceTitle(input.id);\n }\n if (title && !sessionTitleIsPending(input)) {\n return title;\n }\n\n for (const key of options.metadataKeys ?? []) {\n const value = input.metadata?.[key];\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value.trim();\n }\n }\n\n return (\n deriveAutomaticSessionTitlePreview(input.initialMessage) ??\n automaticSessionReferenceTitle(input.id)\n );\n}\n","import type { OpenGeniClient } from \"./client\";\nimport { sessionEventStreamCoveredThrough, type StreamSessionEventsOptions } from \"./stream\";\nimport type { SessionEvent } from \"./types\";\n\n/**\n * Proxy-through-your-own-API helpers.\n *\n * The intended pattern: a customer's server consumes the OpenGeni event\n * stream with its own API key (`client.streamEvents(...)`) and re-emits it to\n * its browser clients over its own authenticated endpoint — the OpenGeni key\n * never reaches the browser. The re-emitted wire format is identical to\n * OpenGeni's own SSE stream (`id: <sequence>`, `event: <type>`,\n * `data: <event JSON>`), so the browser side can consume it with this same\n * SDK's streaming core (or a plain `EventSource`), including resume via\n * `?after=` / `Last-Event-ID`. An ordinary event uses its own sequence as the\n * SSE `id`; a compact event uses the server-owned sequence it covers through.\n */\n\n/** Format one event with the exact OpenGeni data and resume-cursor semantics. */\nexport function formatSseEvent(event: SessionEvent): string {\n const streamedCoverage = sessionEventStreamCoveredThrough(event);\n const projectedCoverage = event.coveredThrough;\n const coveredThrough =\n streamedCoverage ??\n (typeof projectedCoverage === \"number\" &&\n Number.isSafeInteger(projectedCoverage) &&\n projectedCoverage >= event.sequence\n ? projectedCoverage\n : event.sequence);\n return `id: ${coveredThrough}\\nevent: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`;\n}\n\nexport type SseReStreamOptions = {\n /**\n * Emit `: ping` comment lines at this interval, keeping intermediaries from\n * idling the connection out. Disabled when omitted.\n */\n heartbeatMs?: number;\n /**\n * Called when the downstream consumer cancels (e.g. the browser\n * disconnected). Use it to abort the upstream OpenGeni stream — an async\n * iterator that is mid-`await` cannot be interrupted by `return()` alone.\n */\n onCancel?: () => void;\n};\n\n/**\n * Re-emit a stream of session events as an SSE byte stream. Pull-based, so\n * upstream consumption follows downstream demand; cancelling the returned\n * stream fires `onCancel` and ends the upstream iterator.\n */\nexport function sessionEventsToSseStream(\n events: AsyncIterable<SessionEvent>,\n options: SseReStreamOptions = {},\n): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n const iterator = events[Symbol.asyncIterator]();\n let heartbeat: ReturnType<typeof setInterval> | undefined;\n let cancelled = false;\n\n const stopHeartbeat = (): void => {\n if (heartbeat !== undefined) {\n clearInterval(heartbeat);\n heartbeat = undefined;\n }\n };\n\n return new ReadableStream<Uint8Array>({\n start: (controller) => {\n if (options.heartbeatMs !== undefined) {\n heartbeat = setInterval(() => {\n try {\n controller.enqueue(encoder.encode(\": ping\\n\\n\"));\n } catch {\n stopHeartbeat();\n }\n }, options.heartbeatMs);\n }\n },\n pull: async (controller) => {\n let result: IteratorResult<SessionEvent, unknown>;\n try {\n result = await iterator.next();\n } catch (error) {\n stopHeartbeat();\n throw error;\n }\n if (cancelled) {\n return;\n }\n if (result.done) {\n stopHeartbeat();\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(formatSseEvent(result.value)));\n },\n cancel: () => {\n cancelled = true;\n stopHeartbeat();\n options.onCancel?.();\n // Fire-and-forget: if the iterator is suspended mid-await, return()\n // settles only after onCancel unblocks it; cancel must not hang on it.\n void Promise.resolve(iterator.return?.(undefined)).then(\n () => undefined,\n () => undefined,\n );\n },\n });\n}\n\n/** Wrap an event stream in a ready-to-return SSE `Response`. */\nexport function sessionEventsToSseResponse(\n events: AsyncIterable<SessionEvent>,\n options: SseReStreamOptions = {},\n): Response {\n return new Response(sessionEventsToSseStream(events, options), {\n headers: {\n \"Content-Type\": \"text/event-stream; charset=utf-8\",\n \"Cache-Control\": \"no-cache, no-transform\",\n Connection: \"keep-alive\",\n },\n });\n}\n\n/**\n * Read the resume cursor a reconnecting SSE client sent: the `after` query\n * parameter, or the standard `Last-Event-ID` header. Re-emitted streams set\n * `id:` to the event sequence for ordinary events and the covered high-water\n * sequence for compact events. Returns 0 (full replay) when absent.\n */\nexport function resumeSequenceFromRequest(request: Request): number {\n const url = new URL(request.url);\n const raw = url.searchParams.get(\"after\") ?? request.headers.get(\"Last-Event-ID\");\n const parsed = raw === null ? 0 : Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0;\n}\n\nexport type ProxySessionEventStreamOptions = Omit<StreamSessionEventsOptions, \"after\"> & {\n /**\n * Resume cursor. Pass a number, or the incoming browser `Request` to\n * honor its `?after=` / `Last-Event-ID` automatically.\n */\n after?: number | Request;\n /** See {@link SseReStreamOptions.heartbeatMs}. */\n heartbeatMs?: number;\n};\n\n/**\n * One-call proxy: consume the OpenGeni stream server-side and return an SSE\n * `Response` for your own browser clients. Works anywhere WHATWG `Response`\n * is the handler return type (Hono, Next.js route handlers, Bun.serve,\n * Cloudflare Workers, ...).\n *\n * The upstream OpenGeni connection is torn down when the downstream client\n * disconnects, and also when `options.signal` (e.g. the incoming request's\n * signal) aborts.\n */\nexport function proxySessionEventStream(\n client: OpenGeniClient,\n workspaceId: string,\n sessionId: string,\n options: ProxySessionEventStreamOptions = {},\n): Response {\n const { after, heartbeatMs, signal, ...streamOptions } = options;\n const upstream = new AbortController();\n if (signal?.aborted) {\n upstream.abort();\n } else {\n signal?.addEventListener(\"abort\", () => upstream.abort(), { once: true });\n }\n const resolvedAfter = after instanceof Request ? resumeSequenceFromRequest(after) : (after ?? 0);\n const events = client.streamEvents(workspaceId, sessionId, {\n ...streamOptions,\n after: resolvedAfter,\n signal: upstream.signal,\n });\n return sessionEventsToSseResponse(events, {\n ...(heartbeatMs !== undefined ? { heartbeatMs } : {}),\n onCancel: () => upstream.abort(),\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 | \"knowledge_proposal\"\n | \"legacy_import\";\nexport type WorkspaceInstructionPolicyDraftProvenanceSource = Exclude<\n WorkspaceInstructionPolicyProvenanceSource,\n \"legacy_import\"\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 KnowledgeBrowseRequest as ContractKnowledgeBrowseRequest,\n KnowledgeBrowseResponse as ContractKnowledgeBrowseResponse,\n KnowledgeGetResponse as ContractKnowledgeGetResponse,\n KnowledgeRecord as ContractKnowledgeRecord,\n KnowledgeSearchRequest as ContractKnowledgeSearchRequest,\n KnowledgeSearchResponse as ContractKnowledgeSearchResponse,\n} from \"@opengeni/contracts\";\n\nexport type CompanyBrainOkfPackage = ContractCompanyBrainOkfPackage;\nexport type CompanyBrainContextReceiptPage = ContractCompanyBrainContextReceiptPage;\nexport type CompanyBrainKnowledgeProposalPage = ContractCompanyBrainKnowledgeProposalPage;\nexport type CompanyBrainKnowledgeSearchRequest = ContractKnowledgeSearchRequest;\nexport type CompanyBrainKnowledgeSearchResponse = ContractKnowledgeSearchResponse;\nexport type CompanyBrainKnowledgeBrowseRequest = ContractKnowledgeBrowseRequest;\nexport type CompanyBrainKnowledgeBrowseResponse = ContractKnowledgeBrowseResponse;\nexport type CompanyBrainKnowledgeGetResponse = ContractKnowledgeGetResponse;\nexport type CompanyBrainKnowledgeRecord = ContractKnowledgeRecord;\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\n/** Human-authorized, permission-first Knowledge search for Company Brain inspectors. */\nexport function searchCompanyBrainKnowledge(\n client: CompanyBrainInspectorTransport,\n workspaceId: string,\n request: CompanyBrainKnowledgeSearchRequest,\n): Promise<CompanyBrainKnowledgeSearchResponse> {\n return client.requestJson(\"POST\", inspectorPath(workspaceId, \"knowledge/search\"), request);\n}\n\nexport function getCompanyBrainKnowledge(\n client: CompanyBrainInspectorTransport,\n workspaceId: string,\n recordId: string,\n): Promise<CompanyBrainKnowledgeGetResponse> {\n return client.requestJson(\n \"GET\",\n `${inspectorPath(workspaceId, \"knowledge/record\")}?id=${encodeURIComponent(recordId)}`,\n );\n}\n\nexport function browseCompanyBrainKnowledge(\n client: CompanyBrainInspectorTransport,\n workspaceId: string,\n request: CompanyBrainKnowledgeBrowseRequest = {},\n): Promise<CompanyBrainKnowledgeBrowseResponse> {\n return client.requestJson(\"POST\", inspectorPath(workspaceId, \"knowledge/browse\"), request);\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQO,IAAM,wCAAwC;AAO9C,IAAM,mCAAmC;AAKhD,IAAM,qCAAqC;AAE3C,IAAM,qBACJ;AAEF,IAAI;AAEJ,IAAM,iCAAiC;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,+BAA+B;AACrC,IAAM,6BAA6B;AAEnC,IAAM,oCACJ;AAEF,IAAM,oC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,OAAO,YAAY,QAAQ,cAAc,aAAa,kBAAkB,GAAG,OAAO;AAC3F;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;;;ACnEO,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/session-titles.ts","../src/proxy.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":["/** Human-authored session titles keep the existing public API ceiling. */\nexport const SESSION_TITLE_MAX_CHARACTERS = 200;\n\n/**\n * Automatic titles are intentionally much shorter than the manual rename\n * ceiling. This is measured in grapheme clusters so emoji and combining text\n * are never split into malformed display strings.\n */\nexport const AUTOMATIC_SESSION_TITLE_MAX_GRAPHEMES = 80;\n\n/**\n * Safe durable title used until semantic generation succeeds. It contains no\n * user prompt bytes, so provider failure/offline operation cannot leak a\n * credential or leave a raw prompt prefix in navigation surfaces.\n */\nexport const AUTOMATIC_SESSION_TITLE_FALLBACK = \"New conversation\";\n\n// Session creation accepts a body far larger than a navigation label. Bound\n// the source before any replace/split/normalization so a persisted large prompt\n// cannot amplify memory or CPU on every client render.\nconst PROMPT_PREVIEW_SCAN_MAX_CODE_UNITS = 4_096;\n\nconst SESSION_ID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\n\nlet titleSegmenter: Intl.Segmenter | null | undefined;\n\nconst KNOWN_SENSITIVE_VALUE_PATTERNS = [\n /-----BEGIN [A-Z ]*PRIVATE KEY-----/iu,\n /\\bBearer\\s+[A-Za-z0-9._~+/=-]{8,}/iu,\n /\\b(?:sk-(?:proj-)?|gh[oprsu]_|github_pat_|glpat-|xox[baprs]-)[A-Za-z0-9_-]{8,}/iu,\n /\\bAKIA[0-9A-Z]{16}\\b/u,\n /\\bAIza[0-9A-Za-z_-]{20,}\\b/u,\n /\\beyJ[A-Za-z0-9_-]+\\.eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b/u,\n /[?&](?:access_token|api_key|apikey|password|secret|token)=[^\\s&#]+/iu,\n] as const;\n\nconst URI_SCHEME_CANDIDATE_PATTERN = /\\b[a-z][a-z0-9+.-]*:\\S+/giu;\nconst WINDOWS_DRIVE_PATH_PATTERN = /^[a-z]:[\\\\/](?![\\\\/])[^:]*$/iu;\n\nconst SCHEMELESS_HOST_CANDIDATE_PATTERN =\n /\\b(?:www\\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?(?::\\d{1,5})?(?:[/?#][^\\s]*)?/giu;\n\nconst SCHEMELESS_LOCAL_NETWORK_PATTERNS = [\n /\\blocalhost(?:(?::\\d{1,5})(?:[/?#][^\\s]*)?|[/?#][^\\s]*)/iu,\n /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)(?:(?::\\d{1,5})(?:[/?#][^\\s]*)?|[/?#][^\\s]*)/u,\n /\\[(?=[0-9a-f:.]*:[0-9a-f:.]*\\])[0-9a-f:.]+\\](?:(?::\\d{1,5})(?:[/?#][^\\s]*)?|[/?#][^\\s]*)/iu,\n] as const;\n\nconst FILE_LIKE_HOST_SUFFIXES = new Set([\n \"css\",\n \"html\",\n \"js\",\n \"json\",\n \"jsx\",\n \"lock\",\n \"md\",\n \"sql\",\n \"toml\",\n \"ts\",\n \"tsx\",\n \"xml\",\n \"yaml\",\n \"yml\",\n]);\n\n// These authorities are established framework/namespace notation whose exact\n// casing is meaningful. Keep this exception deliberately narrow: generic\n// PascalCase or uppercase authorities remain host-like because an uppercase\n// real domain (for example MICROSOFT.COM/Admin) must not bypass the URL gate.\nconst DOTTED_TECHNOLOGY_PATH_AUTHORITIES = new Set([\n \"ASP.NET\",\n \"AWS.SDK\",\n \"Microsoft.Extensions\",\n \"System.IO\",\n]);\n\nconst SECRET_ASSIGNMENT_CANDIDATE_PATTERN =\n /(?:^|[^A-Za-z0-9])(?:(['\"])([A-Za-z][A-Za-z0-9_. -]*)\\1|([A-Za-z][A-Za-z0-9_.-]*))\\s*[=:]\\s*[^\\s,;]+/gu;\n\nconst SECRET_LABEL_ASSIGNMENT_PATTERN =\n /\\b(?:api[ _-]?key|access[ _-]?token|auth[ _-]?token|credential|credentials|password|passwd|private[ _-]?key|secret|token)\\b\\s*[=:]\\s*[^\\s,;]+/iu;\n\nconst SENSITIVE_ASSIGNMENT_KEY_SUFFIXES = new Set([\n \"credential\",\n \"credentials\",\n \"password\",\n \"passwd\",\n \"secret\",\n \"token\",\n]);\n\nconst COMPACT_SENSITIVE_ASSIGNMENT_KEY_SUFFIXES = [\n \"apikey\",\n \"accesskey\",\n \"accesskeyid\",\n \"accesstoken\",\n \"authtoken\",\n \"credential\",\n \"credentials\",\n \"password\",\n \"passwd\",\n \"privatekey\",\n \"secret\",\n \"secretkey\",\n \"token\",\n] as const;\n\nconst SENSITIVE_ASSIGNMENT_KEY_WORD_SUFFIXES = [\n [\"api\", \"key\"],\n [\"access\", \"key\"],\n [\"access\", \"key\", \"id\"],\n [\"auth\", \"key\"],\n [\"private\", \"key\"],\n [\"secret\", \"key\"],\n] as const;\n\nfunction hasWordSuffix(words: readonly string[], suffix: readonly string[]): boolean {\n if (words.length < suffix.length) return false;\n const offset = words.length - suffix.length;\n return suffix.every((word, index) => words[offset + index] === word);\n}\n\nfunction containsSensitiveAssignment(value: string): boolean {\n for (const match of value.matchAll(SECRET_ASSIGNMENT_CANDIDATE_PATTERN)) {\n const key = match[2] ?? match[3];\n if (!key) continue;\n const words = key\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1 $2\")\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter(Boolean);\n const last = words.at(-1);\n if (last && SENSITIVE_ASSIGNMENT_KEY_SUFFIXES.has(last)) return true;\n if (last && COMPACT_SENSITIVE_ASSIGNMENT_KEY_SUFFIXES.some((suffix) => last.endsWith(suffix))) {\n return true;\n }\n if (SENSITIVE_ASSIGNMENT_KEY_WORD_SUFFIXES.some((suffix) => hasWordSuffix(words, suffix))) {\n return true;\n }\n }\n return false;\n}\n\nfunction containsUriScheme(value: string): boolean {\n for (const match of value.matchAll(URI_SCHEME_CANDIDATE_PATTERN)) {\n // A Windows drive path is the one scheme-shaped token accepted here. Keep\n // the exception exact: one separator after the drive letter and no later\n // colon, so x://host and a nested scheme remain rejected.\n if (!WINDOWS_DRIVE_PATH_PATTERN.test(match[0])) return true;\n }\n return false;\n}\n\nfunction isDottedTechnologyPath(candidate: string): boolean {\n if (/[?:#]/u.test(candidate)) return false;\n const [authority, ...pathSegments] = candidate.split(\"/\");\n if (!authority || pathSegments.length === 0 || pathSegments.some((segment) => !segment)) {\n return false;\n }\n if (\n !DOTTED_TECHNOLOGY_PATH_AUTHORITIES.has(authority) ||\n pathSegments.some((segment) => !/^[A-Z][A-Za-z0-9_-]*$/u.test(segment))\n ) {\n return false;\n }\n return true;\n}\n\nfunction containsSchemelessUrl(value: string): boolean {\n if (SCHEMELESS_LOCAL_NETWORK_PATTERNS.some((pattern) => pattern.test(value))) return true;\n\n for (const match of value.matchAll(SCHEMELESS_HOST_CANDIDATE_PATTERN)) {\n const candidate = match[0];\n if (candidate.toLowerCase().startsWith(\"www.\")) return true;\n if (!/[/?#]/u.test(candidate)) continue;\n\n const authority = candidate.split(/[/?#]/u, 1)[0] ?? \"\";\n const hostname = authority.replace(/:\\d{1,5}$/u, \"\");\n const suffix = hostname.split(\".\").at(-1)?.toLowerCase();\n if (suffix && FILE_LIKE_HOST_SUFFIXES.has(suffix)) continue;\n if (isDottedTechnologyPath(candidate)) continue;\n return true;\n }\n return false;\n}\n\nconst OPAQUE_IDENTIFIER_PATTERN =\n /\\b(?=[A-Za-z0-9_-]{32,}\\b)(?=[A-Za-z0-9_-]*[A-Za-z])(?=[A-Za-z0-9_-]*\\d)[A-Za-z0-9_-]+\\b/u;\n\nconst DEFAULT_IGNORABLE_CODE_POINTS = /\\p{Default_Ignorable_Code_Point}+/gu;\nconst ESCAPED_QUOTE_DELIMITERS = /\\\\+(?=[\"'])/gu;\n\nconst TITLE_LABEL_PATTERN =\n /^(?:(?:suggested|generated|concise)\\s+)?(?:(?:session|chat|conversation|task)\\s+)?title\\s*[:\\-–—]\\s*/iu;\n\nconst LEADING_BOILERPLATE_PATTERNS = [\n /^(?:hi|hello|hey)(?:\\s+there)?\\s*[,!:.\\-–—]*\\s*/iu,\n /^(?:i\\s+(?:would\\s+like|want|need)\\s+you\\s+to|i['’]d\\s+like\\s+you\\s+to)\\s+/iu,\n /^(?:please\\s+)?(?:can|could|would|will)\\s+you\\s+/iu,\n /^(?:your|the)\\s+(?:task|job)\\s+is\\s+to\\s+/iu,\n /^(?:please\\s+)?help\\s+me\\s+(?:to\\s+)?/iu,\n /^please(?:\\s*[,!:.\\-–—]+\\s*|\\s+|$)/iu,\n] as const;\n\nfunction automaticTitleDetectionValue(value: string): string {\n // Detection uses a compatibility-normalized shadow value so fullwidth\n // punctuation/letters, invisible token splits, and serialized quote\n // delimiters cannot evade the policy.\n // The accepted title itself stays byte-for-byte in the user's language and\n // emoji form; this shadow is never returned or persisted.\n return value\n .normalize(\"NFKC\")\n .replace(DEFAULT_IGNORABLE_CODE_POINTS, \"\")\n .replace(ESCAPED_QUOTE_DELIMITERS, \"\");\n}\n\nfunction hasVisibleAutomaticTitleContent(value: string): boolean {\n return automaticTitleDetectionValue(value).trim().length > 0;\n}\n\n/**\n * Whether a bounded automatic-title candidate contains a credential, URL, or\n * opaque identifier that must stay out of navigation and other display-title\n * surfaces. Callers handling an unbounded source must bound it before invoking\n * this helper.\n */\nexport function containsSensitiveAutomaticSessionTitleValue(value: string): boolean {\n const detectionValue = automaticTitleDetectionValue(value);\n\n if (KNOWN_SENSITIVE_VALUE_PATTERNS.some((pattern) => pattern.test(detectionValue))) return true;\n if (containsUriScheme(detectionValue)) return true;\n if (containsSchemelessUrl(detectionValue)) return true;\n if (SECRET_LABEL_ASSIGNMENT_PATTERN.test(detectionValue)) return true;\n if (containsSensitiveAssignment(detectionValue)) return true;\n if (OPAQUE_IDENTIFIER_PATTERN.test(detectionValue)) return true;\n return false;\n}\n\nfunction stripAutomaticTitleBoilerplate(value: string): string {\n let title = value;\n for (let pass = 0; pass < 4; pass += 1) {\n const before = title;\n title = title\n .replace(/^(?:```[^\\n]*|[\\s#>*_`\"'“”‘’\\-–—]+)+/u, \"\")\n .replace(TITLE_LABEL_PATTERN, \"\");\n for (const pattern of LEADING_BOILERPLATE_PATTERNS) {\n title = title.replace(pattern, \"\");\n }\n title = title.trim();\n if (title === before) break;\n }\n return title;\n}\n\nfunction automaticTitleGraphemes(value: string): string[] {\n if (titleSegmenter === undefined) {\n titleSegmenter =\n typeof Intl.Segmenter === \"function\"\n ? new Intl.Segmenter(undefined, { granularity: \"grapheme\" })\n : null;\n }\n if (titleSegmenter) {\n return Array.from(titleSegmenter.segment(value), (part) => part.segment);\n }\n\n // Older embedded runtimes may not ship Intl.Segmenter. Preserve surrogate\n // pairs plus common combining/emoji sequences instead of failing module load\n // or slicing UTF-16 code units.\n const graphemes: string[] = [];\n for (const point of value) {\n const prior = graphemes.at(-1);\n if (\n prior &&\n (/^[\\p{Mark}\\u{FE0E}\\u{FE0F}\\p{Emoji_Modifier}]$/u.test(point) ||\n point === \"\\u200d\" ||\n prior.endsWith(\"\\u200d\"))\n ) {\n graphemes[graphemes.length - 1] = `${prior}${point}`;\n } else {\n graphemes.push(point);\n }\n }\n return graphemes;\n}\n\n/** Bound an already-normalized automatic-title candidate without splitting graphemes. */\nexport function boundAutomaticSessionTitle(value: string): string {\n const words = value.split(/\\s+/u);\n const wordBounded = words.length > 10 ? words.slice(0, 10).join(\" \") : value;\n const graphemes = automaticTitleGraphemes(wordBounded);\n if (graphemes.length <= AUTOMATIC_SESSION_TITLE_MAX_GRAPHEMES) return wordBounded;\n\n const prefix = graphemes.slice(0, AUTOMATIC_SESSION_TITLE_MAX_GRAPHEMES).join(\"\");\n const lastWhitespace = prefix.search(/\\s+\\S*$/u);\n return (lastWhitespace >= 16 ? prefix.slice(0, lastWhitespace) : prefix).trimEnd();\n}\n\n/**\n * Normalize a model/system-authored title before it reaches durable session\n * metadata. Human renames intentionally do not use this path.\n *\n * Returns null when the candidate is empty, only boilerplate, or appears to\n * contain a credential/opaque prompt value. Callers should retain the current\n * title (normally {@link AUTOMATIC_SESSION_TITLE_FALLBACK}) in that case.\n */\nexport function normalizeAutomaticSessionTitle(value: string): string | null {\n const firstLine = value\n .replace(/[\\u0000-\\u001f\\u007f-\\u009f]+/gu, \"\\n\")\n .split(/\\n+/u)\n .map((line) => line.trim())\n .find(Boolean);\n if (\n !firstLine ||\n !hasVisibleAutomaticTitleContent(firstLine) ||\n containsSensitiveAutomaticSessionTitleValue(firstLine)\n ) {\n return null;\n }\n\n let title = stripAutomaticTitleBoilerplate(firstLine)\n .replace(/\\s+/gu, \" \")\n .replace(/[\\s.!?,;:\\-–—]+$/u, \"\")\n .trim();\n if (\n !title ||\n !hasVisibleAutomaticTitleContent(title) ||\n containsSensitiveAutomaticSessionTitleValue(title)\n ) {\n return null;\n }\n\n title = boundAutomaticSessionTitle(title)\n .replace(/[\\s.!?,;:\\-–—]+$/u, \"\")\n .trim();\n if (!title || !hasVisibleAutomaticTitleContent(title)) return null;\n return title;\n}\n\nexport type SessionDisplayTitleInput = {\n id?: string | null | undefined;\n title?: string | null | undefined;\n titleSource?: \"user\" | \"agent\" | null | undefined;\n initialMessage?: string | null | undefined;\n metadata?: Readonly<Record<string, unknown>> | undefined;\n};\n\nexport type SessionDisplayTitleOptions = {\n /** Optional metadata fields to try before the opening-prompt preview. */\n metadataKeys?: readonly string[] | undefined;\n};\n\n/**\n * Derive a bounded, sensitive-safe preview from the opening prompt.\n *\n * Unsafe leading lines are skipped instead of forcing the whole session back\n * to a generic label. This covers prompts that begin with a pasted URL or\n * identifier followed by an ordinary natural-language request on the next\n * line, without putting the rejected value into navigation surfaces.\n */\nexport function deriveAutomaticSessionTitlePreview(value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n\n const lines = value\n .slice(0, PROMPT_PREVIEW_SCAN_MAX_CODE_UNITS)\n .replace(/[\\u0000-\\u001f\\u007f-\\u009f]+/gu, \"\\n\")\n .split(/\\n+/u);\n\n for (const candidate of lines) {\n const line = candidate.trim();\n if (!line || containsSensitiveAutomaticSessionTitleValue(line)) continue;\n\n const preview = boundAutomaticSessionTitle(line.replace(/\\s+/gu, \" \"))\n .replace(/[\\s.!?,;:\\-–—]+$/u, \"\")\n .trim();\n if (preview) return preview;\n }\n\n return null;\n}\n\nfunction automaticSessionReferenceTitle(id: unknown): string {\n const sessionId = typeof id === \"string\" ? id.trim() : \"\";\n return SESSION_ID_PATTERN.test(sessionId)\n ? `Conversation ${sessionId.slice(0, 13)}`\n : AUTOMATIC_SESSION_TITLE_FALLBACK;\n}\n\n/**\n * Whether the durable title still represents the automatic-title pending state.\n * A user-authored title always wins, even when its literal value is the marker.\n */\nexport function sessionTitleIsPending(input: SessionDisplayTitleInput): boolean {\n const title = input.title?.trim() ?? \"\";\n return input.titleSource !== \"user\" && (!title || title === AUTOMATIC_SESSION_TITLE_FALLBACK);\n}\n\n/**\n * Derive the title a human-facing client should display for a session.\n *\n * A semantic agent title or human rename wins. While automatic naming is still\n * pending, clients show a short, sensitive-safe preview of the opening prompt.\n * If no safe prompt text exists, a UUID-derived reference keeps real sessions\n * distinguishable without exposing prompt bytes. The durable pending marker is\n * therefore an internal lifecycle value rather than the ordinary visible name.\n */\nexport function deriveSessionDisplayTitle(\n input: SessionDisplayTitleInput,\n options: SessionDisplayTitleOptions = {},\n): string {\n const title = input.title?.trim() ?? \"\";\n if (input.titleSource === \"user\") {\n return title || automaticSessionReferenceTitle(input.id);\n }\n if (title && !sessionTitleIsPending(input)) {\n return title;\n }\n\n for (const key of options.metadataKeys ?? []) {\n const value = input.metadata?.[key];\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value.trim();\n }\n }\n\n return (\n deriveAutomaticSessionTitlePreview(input.initialMessage) ??\n automaticSessionReferenceTitle(input.id)\n );\n}\n","import type { OpenGeniClient } from \"./client\";\nimport { sessionEventStreamCoveredThrough, type StreamSessionEventsOptions } from \"./stream\";\nimport type { SessionEvent } from \"./types\";\n\n/**\n * Proxy-through-your-own-API helpers.\n *\n * The intended pattern: a customer's server consumes the OpenGeni event\n * stream with its own API key (`client.streamEvents(...)`) and re-emits it to\n * its browser clients over its own authenticated endpoint — the OpenGeni key\n * never reaches the browser. The re-emitted wire format is identical to\n * OpenGeni's own SSE stream (`id: <sequence>`, `event: <type>`,\n * `data: <event JSON>`), so the browser side can consume it with this same\n * SDK's streaming core (or a plain `EventSource`), including resume via\n * `?after=` / `Last-Event-ID`. An ordinary event uses its own sequence as the\n * SSE `id`; a compact event uses the server-owned sequence it covers through.\n */\n\n/** Format one event with the exact OpenGeni data and resume-cursor semantics. */\nexport function formatSseEvent(event: SessionEvent): string {\n const streamedCoverage = sessionEventStreamCoveredThrough(event);\n const projectedCoverage = event.coveredThrough;\n const coveredThrough =\n streamedCoverage ??\n (typeof projectedCoverage === \"number\" &&\n Number.isSafeInteger(projectedCoverage) &&\n projectedCoverage >= event.sequence\n ? projectedCoverage\n : event.sequence);\n return `id: ${coveredThrough}\\nevent: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`;\n}\n\nexport type SseReStreamOptions = {\n /**\n * Emit `: ping` comment lines at this interval, keeping intermediaries from\n * idling the connection out. Disabled when omitted.\n */\n heartbeatMs?: number;\n /**\n * Called when the downstream consumer cancels (e.g. the browser\n * disconnected). Use it to abort the upstream OpenGeni stream — an async\n * iterator that is mid-`await` cannot be interrupted by `return()` alone.\n */\n onCancel?: () => void;\n};\n\n/**\n * Re-emit a stream of session events as an SSE byte stream. Pull-based, so\n * upstream consumption follows downstream demand; cancelling the returned\n * stream fires `onCancel` and ends the upstream iterator.\n */\nexport function sessionEventsToSseStream(\n events: AsyncIterable<SessionEvent>,\n options: SseReStreamOptions = {},\n): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n const iterator = events[Symbol.asyncIterator]();\n let heartbeat: ReturnType<typeof setInterval> | undefined;\n let cancelled = false;\n\n const stopHeartbeat = (): void => {\n if (heartbeat !== undefined) {\n clearInterval(heartbeat);\n heartbeat = undefined;\n }\n };\n\n return new ReadableStream<Uint8Array>({\n start: (controller) => {\n if (options.heartbeatMs !== undefined) {\n heartbeat = setInterval(() => {\n try {\n controller.enqueue(encoder.encode(\": ping\\n\\n\"));\n } catch {\n stopHeartbeat();\n }\n }, options.heartbeatMs);\n }\n },\n pull: async (controller) => {\n let result: IteratorResult<SessionEvent, unknown>;\n try {\n result = await iterator.next();\n } catch (error) {\n stopHeartbeat();\n throw error;\n }\n if (cancelled) {\n return;\n }\n if (result.done) {\n stopHeartbeat();\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(formatSseEvent(result.value)));\n },\n cancel: () => {\n cancelled = true;\n stopHeartbeat();\n options.onCancel?.();\n // Fire-and-forget: if the iterator is suspended mid-await, return()\n // settles only after onCancel unblocks it; cancel must not hang on it.\n void Promise.resolve(iterator.return?.(undefined)).then(\n () => undefined,\n () => undefined,\n );\n },\n });\n}\n\n/** Wrap an event stream in a ready-to-return SSE `Response`. */\nexport function sessionEventsToSseResponse(\n events: AsyncIterable<SessionEvent>,\n options: SseReStreamOptions = {},\n): Response {\n return new Response(sessionEventsToSseStream(events, options), {\n headers: {\n \"Content-Type\": \"text/event-stream; charset=utf-8\",\n \"Cache-Control\": \"no-cache, no-transform\",\n Connection: \"keep-alive\",\n },\n });\n}\n\n/**\n * Read the resume cursor a reconnecting SSE client sent: the `after` query\n * parameter, or the standard `Last-Event-ID` header. Re-emitted streams set\n * `id:` to the event sequence for ordinary events and the covered high-water\n * sequence for compact events. Returns 0 (full replay) when absent.\n */\nexport function resumeSequenceFromRequest(request: Request): number {\n const url = new URL(request.url);\n const raw = url.searchParams.get(\"after\") ?? request.headers.get(\"Last-Event-ID\");\n const parsed = raw === null ? 0 : Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0;\n}\n\nexport type ProxySessionEventStreamOptions = Omit<StreamSessionEventsOptions, \"after\"> & {\n /**\n * Resume cursor. Pass a number, or the incoming browser `Request` to\n * honor its `?after=` / `Last-Event-ID` automatically.\n */\n after?: number | Request;\n /** See {@link SseReStreamOptions.heartbeatMs}. */\n heartbeatMs?: number;\n};\n\n/**\n * One-call proxy: consume the OpenGeni stream server-side and return an SSE\n * `Response` for your own browser clients. Works anywhere WHATWG `Response`\n * is the handler return type (Hono, Next.js route handlers, Bun.serve,\n * Cloudflare Workers, ...).\n *\n * The upstream OpenGeni connection is torn down when the downstream client\n * disconnects, and also when `options.signal` (e.g. the incoming request's\n * signal) aborts.\n */\nexport function proxySessionEventStream(\n client: OpenGeniClient,\n workspaceId: string,\n sessionId: string,\n options: ProxySessionEventStreamOptions = {},\n): Response {\n const { after, heartbeatMs, signal, ...streamOptions } = options;\n const upstream = new AbortController();\n if (signal?.aborted) {\n upstream.abort();\n } else {\n signal?.addEventListener(\"abort\", () => upstream.abort(), { once: true });\n }\n const resolvedAfter = after instanceof Request ? resumeSequenceFromRequest(after) : (after ?? 0);\n const events = client.streamEvents(workspaceId, sessionId, {\n ...streamOptions,\n after: resolvedAfter,\n signal: upstream.signal,\n });\n return sessionEventsToSseResponse(events, {\n ...(heartbeatMs !== undefined ? { heartbeatMs } : {}),\n onCancel: () => upstream.abort(),\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 | \"knowledge_proposal\"\n | \"legacy_import\";\nexport type WorkspaceInstructionPolicyDraftProvenanceSource = Exclude<\n WorkspaceInstructionPolicyProvenanceSource,\n \"legacy_import\"\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 KnowledgeBrowseRequest as ContractKnowledgeBrowseRequest,\n KnowledgeBrowseResponse as ContractKnowledgeBrowseResponse,\n KnowledgeGetResponse as ContractKnowledgeGetResponse,\n KnowledgeRecord as ContractKnowledgeRecord,\n KnowledgeSearchRequest as ContractKnowledgeSearchRequest,\n KnowledgeSearchResponse as ContractKnowledgeSearchResponse,\n} from \"@opengeni/contracts\";\n\nexport type CompanyBrainOkfPackage = ContractCompanyBrainOkfPackage;\nexport type CompanyBrainContextReceiptPage = ContractCompanyBrainContextReceiptPage;\nexport type CompanyBrainKnowledgeProposalPage = ContractCompanyBrainKnowledgeProposalPage;\nexport type CompanyBrainKnowledgeSearchRequest = ContractKnowledgeSearchRequest;\nexport type CompanyBrainKnowledgeSearchResponse = ContractKnowledgeSearchResponse;\nexport type CompanyBrainKnowledgeBrowseRequest = ContractKnowledgeBrowseRequest;\nexport type CompanyBrainKnowledgeBrowseResponse = ContractKnowledgeBrowseResponse;\nexport type CompanyBrainKnowledgeGetResponse = ContractKnowledgeGetResponse;\nexport type CompanyBrainKnowledgeRecord = ContractKnowledgeRecord;\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\n/** Human-authorized, permission-first Knowledge search for Company Brain inspectors. */\nexport function searchCompanyBrainKnowledge(\n client: CompanyBrainInspectorTransport,\n workspaceId: string,\n request: CompanyBrainKnowledgeSearchRequest,\n): Promise<CompanyBrainKnowledgeSearchResponse> {\n return client.requestJson(\"POST\", inspectorPath(workspaceId, \"knowledge/search\"), request);\n}\n\nexport function getCompanyBrainKnowledge(\n client: CompanyBrainInspectorTransport,\n workspaceId: string,\n recordId: string,\n): Promise<CompanyBrainKnowledgeGetResponse> {\n return client.requestJson(\n \"GET\",\n `${inspectorPath(workspaceId, \"knowledge/record\")}?id=${encodeURIComponent(recordId)}`,\n );\n}\n\nexport function browseCompanyBrainKnowledge(\n client: CompanyBrainInspectorTransport,\n workspaceId: string,\n request: CompanyBrainKnowledgeBrowseRequest = {},\n): Promise<CompanyBrainKnowledgeBrowseResponse> {\n return client.requestJson(\"POST\", inspectorPath(workspaceId, \"knowledge/browse\"), request);\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQO,IAAM,wCAAwC;AAO9C,IAAM,mCAAmC;AAKhD,IAAM,qCAAqC;AAE3C,IAAM,qBACJ;AAEF,IAAI;AAEJ,IAAM,iCAAiC;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,+BAA+B;AACrC,IAAM,6BAA6B;AAEnC,IAAM,oCACJ;AAEF,IAAM,oCAAoC;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAMD,IAAM,qCAAqC,oBAAI,IAAI;AAAA,EACjD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,sCACJ;AAEF,IAAM,kCACJ;AAEF,IAAM,oCAAoC,oBAAI,IAAI;AAAA,EAChD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,4CAA4C;AAAA,EAChD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA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AO,OAAO,YAAY,OAAO,GAAG,cAAc,aAAa,qBAAqB,CAAC,GAAG,KAAK,EAAE;AACjG;;;ACnEO,SAAS,qCAAqC,OAAuB;AAC1E,SAAO,MAAM,UAAU,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,QAAQ,SAAS,GAAG,EAAE,QAAQ,OAAO,GAAG;AAC9F;","names":[]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type SiteHttpRequest } from "./site-http.js";
|
|
2
|
+
import type { OpenGeniSiteToolCatalog } from "./site.js";
|
|
3
|
+
import type { OpenGeniWorkspaceTools } from "./tools.js";
|
|
4
|
+
import type { ToolGatewayCallRequest, ToolGatewayCallResponse, ToolGatewayIdentity } from "./types.js";
|
|
5
|
+
export type SiteToolCallRequest = ToolGatewayCallRequest & {
|
|
6
|
+
siteArtifactId: string;
|
|
7
|
+
siteVersionId: string;
|
|
8
|
+
};
|
|
9
|
+
export type SiteToolCaller = (input: {
|
|
10
|
+
workspaceId: string;
|
|
11
|
+
request: SiteToolCallRequest;
|
|
12
|
+
signal: AbortSignal;
|
|
13
|
+
}) => Promise<ToolGatewayCallResponse>;
|
|
14
|
+
export type SiteToolBridge = {
|
|
15
|
+
fetch?: (request: SiteHttpRequest, signal: AbortSignal) => Promise<Response>;
|
|
16
|
+
catalog: (options: {
|
|
17
|
+
signal: AbortSignal;
|
|
18
|
+
}) => Promise<OpenGeniSiteToolCatalog>;
|
|
19
|
+
call: (request: ToolGatewayCallRequest, options: {
|
|
20
|
+
signal: AbortSignal;
|
|
21
|
+
}) => Promise<ToolGatewayCallResponse>;
|
|
22
|
+
};
|
|
23
|
+
export type CreateSiteToolBridgeOptions = {
|
|
24
|
+
workspaceTools: Pick<OpenGeniWorkspaceTools, "$catalog">;
|
|
25
|
+
workspaceId: string;
|
|
26
|
+
artifactId: string;
|
|
27
|
+
siteVersionId: string;
|
|
28
|
+
requestedTools: readonly ToolGatewayIdentity[];
|
|
29
|
+
callTool: SiteToolCaller;
|
|
30
|
+
isCatalogStale?: (error: unknown) => boolean;
|
|
31
|
+
/** Optional authenticated host transport for the host-bound workspace API.
|
|
32
|
+
* Omit to expose tools only. Site-provided authorization headers are never forwarded. */
|
|
33
|
+
fetchResponse?: (path: string, init: RequestInit) => Promise<Response>;
|
|
34
|
+
};
|
|
35
|
+
/** Host-side bridge for the opaque Site frame. Supply an authenticated transport;
|
|
36
|
+
* the server independently checks live viewer access and the exact Site version.
|
|
37
|
+
* Recreate on actor/version change. Never take these pinned fields from HTML. */
|
|
38
|
+
export declare function createSiteToolBridge(input: CreateSiteToolBridgeOptions): SiteToolBridge;
|
|
39
|
+
export declare function isSiteCatalogStaleError(error: unknown): boolean;
|
package/dist/site.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
export { createSiteToolBridge, isSiteCatalogStaleError } from "./site-tool-bridge.js";
|
|
2
|
+
export type { SiteToolBridge, SiteToolCaller, SiteToolCallRequest, CreateSiteToolBridgeOptions, } from "./site-tool-bridge.js";
|
|
1
3
|
import { type OpenGeniWorkspaceTools } from "./tools.js";
|
|
2
4
|
import { OpenGeniClient } from "./client.js";
|
|
3
5
|
export { isSiteHttpRequest, serveSiteHttp, siteSessionPath, type SiteHttpRequest, } from "./site-http.js";
|
package/dist/site.js
CHANGED
|
@@ -9,18 +9,20 @@ import {
|
|
|
9
9
|
OPENGENI_SITE_LOCAL_CODEMODE_PATH,
|
|
10
10
|
OpenGeniSiteBridgeError,
|
|
11
11
|
createOpenGeniSiteClient,
|
|
12
|
+
createSiteToolBridge,
|
|
12
13
|
isOpenGeniSiteBridgeCancelMessage,
|
|
13
14
|
isOpenGeniSiteBridgeConnectMessage,
|
|
14
15
|
isOpenGeniSiteBridgeRequestMessage,
|
|
16
|
+
isSiteCatalogStaleError,
|
|
15
17
|
isSiteHttpRequest,
|
|
16
18
|
sanitizeOpenGeniSiteToolCallRequest,
|
|
17
19
|
serveSiteHttp,
|
|
18
20
|
siteSessionPath
|
|
19
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-ARGX7UY4.js";
|
|
20
22
|
import "./chunk-FMLDFJ2Q.js";
|
|
21
|
-
import "./chunk-
|
|
23
|
+
import "./chunk-UQGHX4DI.js";
|
|
22
24
|
import "./chunk-QTBAMHEF.js";
|
|
23
|
-
import "./chunk-
|
|
25
|
+
import "./chunk-TARU5CD2.js";
|
|
24
26
|
import "./chunk-OO5LPTO7.js";
|
|
25
27
|
export {
|
|
26
28
|
OPENGENI_SITE_BRIDGE_BOOTSTRAP_GLOBAL,
|
|
@@ -33,9 +35,11 @@ export {
|
|
|
33
35
|
OPENGENI_SITE_LOCAL_CODEMODE_PATH,
|
|
34
36
|
OpenGeniSiteBridgeError,
|
|
35
37
|
createOpenGeniSiteClient,
|
|
38
|
+
createSiteToolBridge,
|
|
36
39
|
isOpenGeniSiteBridgeCancelMessage,
|
|
37
40
|
isOpenGeniSiteBridgeConnectMessage,
|
|
38
41
|
isOpenGeniSiteBridgeRequestMessage,
|
|
42
|
+
isSiteCatalogStaleError,
|
|
39
43
|
isSiteHttpRequest,
|
|
40
44
|
sanitizeOpenGeniSiteToolCallRequest,
|
|
41
45
|
serveSiteHttp,
|
package/dist/types.d.ts
CHANGED
|
@@ -512,6 +512,10 @@ export type McpConnectionAuthoritySelection = {
|
|
|
512
512
|
export type McpServerConnectionRef = {
|
|
513
513
|
connectionId?: string | undefined;
|
|
514
514
|
authoritySource?: "host" | undefined;
|
|
515
|
+
hostBinding?: {
|
|
516
|
+
bindingId: string;
|
|
517
|
+
generation: number;
|
|
518
|
+
} | undefined;
|
|
515
519
|
provider?: string | undefined;
|
|
516
520
|
providerDomain: string;
|
|
517
521
|
kind?: ConnectionKind | undefined;
|
|
@@ -669,6 +673,7 @@ export type FikenInstallRequest = {
|
|
|
669
673
|
connectionId?: string | undefined;
|
|
670
674
|
};
|
|
671
675
|
export type FikenOAuthStartRequest = {
|
|
676
|
+
returnPath?: string | undefined;
|
|
672
677
|
/** Existing Fiken connection to re-authorize in place (reconnect). */
|
|
673
678
|
connectionId?: string | undefined;
|
|
674
679
|
};
|
|
@@ -928,6 +933,8 @@ export type OAuthStartRequest = {
|
|
|
928
933
|
resource?: string | undefined;
|
|
929
934
|
requestedScopes?: string[] | undefined;
|
|
930
935
|
returnPath?: string | undefined;
|
|
936
|
+
/** Exact trusted-host destination; requires verified external-user mode. */
|
|
937
|
+
returnUrl?: string | undefined;
|
|
931
938
|
connectionId?: string | undefined;
|
|
932
939
|
ownership?: ConnectionOwnership | undefined;
|
|
933
940
|
oauthClient?: {
|
|
@@ -1193,7 +1200,7 @@ export type Session = {
|
|
|
1193
1200
|
/** Agent access scope; absent on servers before the agent-access release. */
|
|
1194
1201
|
agentAccess?: SessionAgentAccess | undefined;
|
|
1195
1202
|
/** Opaque end-user label; null when the session carries none. */
|
|
1196
|
-
|
|
1203
|
+
scopeSubjectId?: SessionScopeSubjectId | null | undefined;
|
|
1197
1204
|
/** Memory scope; absent on servers before the agent-access release. */
|
|
1198
1205
|
memoryScope?: SessionMemoryScope | undefined;
|
|
1199
1206
|
createdAt: string;
|
|
@@ -2314,6 +2321,12 @@ export type ScheduledTask = {
|
|
|
2314
2321
|
updatedAt: string;
|
|
2315
2322
|
};
|
|
2316
2323
|
export type CreateSessionRequest = {
|
|
2324
|
+
/** Opt-in host grants for a direct external-user initial turn. */
|
|
2325
|
+
selectedHostMcpDelegations?: {
|
|
2326
|
+
serverId: string;
|
|
2327
|
+
delegationId: string;
|
|
2328
|
+
generation: number;
|
|
2329
|
+
}[] | undefined;
|
|
2317
2330
|
/** Omitted: defaults/inheritance; []: no bundled guidance. Children cannot widen. */
|
|
2318
2331
|
bundledSkillIds?: BundledSkillId[] | undefined;
|
|
2319
2332
|
requestedSessionId?: string | undefined;
|
|
@@ -2360,16 +2373,14 @@ export type CreateSessionRequest = {
|
|
|
2360
2373
|
} | undefined;
|
|
2361
2374
|
agentAccess?: SessionAgentAccess | undefined;
|
|
2362
2375
|
/** Opaque end-user label inside the workspace. Not a subject, not authority. */
|
|
2363
|
-
|
|
2364
|
-
|
|
2376
|
+
/** Select identity with server-side asUser(), not session creation data. */
|
|
2377
|
+
scopeSubjectId?: never;
|
|
2378
|
+
/** Which Memory the agent reads and where it saves; "user" requires `scopeSubjectId`. */
|
|
2365
2379
|
memoryScope?: SessionMemoryScope | undefined;
|
|
2366
2380
|
};
|
|
2367
2381
|
export type SessionAgentAccess = "session" | "user" | "workspace";
|
|
2368
|
-
export type
|
|
2369
|
-
|
|
2370
|
-
id: string;
|
|
2371
|
-
};
|
|
2372
|
-
export type SessionMemoryScope = "workspace" | "user" | "session" | "off";
|
|
2382
|
+
export type SessionScopeSubjectId = string;
|
|
2383
|
+
export type SessionMemoryScope = "workspace" | "user" | "off";
|
|
2373
2384
|
export declare const KNOWN_PERMISSIONS: readonly ["account:read", "account:admin", "members:manage", "workspace:create", "billing:read", "billing:manage", "workspace:read", "workspace:admin", "sessions:create", "sessions:read", "sessions:control", "stream:view", "stream:control", "stream:acknowledge", "files:upload", "files:read", "files:write", "terminal:attach", "documents:manage", "documents:search", "scheduled_tasks:manage", "scheduled_tasks:run", "github:manage", "github:use", "api_keys:manage", "connections:read", "connections:write", "capabilities:manage", "environments:manage", "environments:use", "variable-sets:list", "variable-sets:read", "variable-sets:write", "variable-sets:manage", "variable-sets:attach", "variable-sets:use", "secrets:list", "secrets:read", "secrets:write", "mcp_servers:attach", "codemode:call", "goals:manage", "enrollments:read", "enrollments:manage", "rigs:use", "rigs:manage", "artifacts:read", "artifacts:publish"];
|
|
2374
2385
|
export type KnownPermission = (typeof KNOWN_PERMISSIONS)[number];
|
|
2375
2386
|
/**
|
|
@@ -3663,10 +3674,7 @@ export type ListOrganizationSessionsOptions = {
|
|
|
3663
3674
|
/** `nextCursor` from the previous page. */
|
|
3664
3675
|
cursor?: string | undefined;
|
|
3665
3676
|
/** Keep only sessions labelled with this exact end user. */
|
|
3666
|
-
|
|
3667
|
-
source: string;
|
|
3668
|
-
id: string;
|
|
3669
|
-
} | undefined;
|
|
3677
|
+
scopeSubjectId?: string | undefined;
|
|
3670
3678
|
/** Keep only sessions in this exact lifecycle state. */
|
|
3671
3679
|
status?: SessionStatus | undefined;
|
|
3672
3680
|
signal?: AbortSignal | undefined;
|
|
@@ -4152,6 +4160,7 @@ export type CreateAgentScheduledTaskRequest = {
|
|
|
4152
4160
|
runMode?: ScheduledTaskRunMode | undefined;
|
|
4153
4161
|
targetSessionId?: string | null | undefined;
|
|
4154
4162
|
connectionAuthorities?: McpConnectionAuthoritySelection[] | undefined;
|
|
4163
|
+
selectedHostMcpDelegations?: CreateSessionRequest["selectedHostMcpDelegations"];
|
|
4155
4164
|
overlapPolicy?: ScheduledTaskOverlapPolicy | undefined;
|
|
4156
4165
|
agentConfig: ScheduledTaskAgentConfigInput;
|
|
4157
4166
|
status?: ScheduledTaskStatus | undefined;
|
|
@@ -4178,6 +4187,7 @@ export type UpdateScheduledTaskRequest = {
|
|
|
4178
4187
|
runMode?: ScheduledTaskRunMode | undefined;
|
|
4179
4188
|
targetSessionId?: string | null | undefined;
|
|
4180
4189
|
connectionAuthorities?: McpConnectionAuthoritySelection[] | undefined;
|
|
4190
|
+
selectedHostMcpDelegations?: CreateSessionRequest["selectedHostMcpDelegations"];
|
|
4181
4191
|
overlapPolicy?: ScheduledTaskOverlapPolicy | undefined;
|
|
4182
4192
|
action?: ScheduledTaskAction | undefined;
|
|
4183
4193
|
agentConfig?: ScheduledTaskAgentConfigInput | undefined;
|
|
@@ -6432,6 +6442,7 @@ export type UserMessageEventInput = {
|
|
|
6432
6442
|
expectedDraftRevision?: number | undefined;
|
|
6433
6443
|
mcpCredentialUpdates?: SessionMcpCredentialUpdateInput[] | undefined;
|
|
6434
6444
|
connectionAuthorities?: McpConnectionAuthoritySelection[] | undefined;
|
|
6445
|
+
selectedHostMcpDelegations?: CreateSessionRequest["selectedHostMcpDelegations"];
|
|
6435
6446
|
personalResourceAttachment?: PersonalResourceAttachmentIntent | undefined;
|
|
6436
6447
|
};
|
|
6437
6448
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opengeni/sdk",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "5.0.3-canary.0",
|
|
4
4
|
"description": "Framework-agnostic TypeScript SDK for the OpenGeni API: typed client, session lifecycle, SSE event streaming with reconnect + replay-by-sequence, and proxy re-streaming helpers.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -117,7 +117,8 @@
|
|
|
117
117
|
"prepublishOnly": "bash ../../scripts/prepublish-guard"
|
|
118
118
|
},
|
|
119
119
|
"dependencies": {
|
|
120
|
-
"@opengeni/
|
|
120
|
+
"@opengeni/connect": "^0.2.0-canary.1",
|
|
121
|
+
"@opengeni/contracts": "^3.0.1-canary.0"
|
|
121
122
|
},
|
|
122
123
|
"engines": {
|
|
123
124
|
"node": ">=18"
|