@skaile/workspaces 3.24.0 → 3.26.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/CHANGELOG.md +44 -0
- package/dist/app-sdk/index.js +1 -1
- package/dist/{asset-feeds-M3XC5SQD.js → asset-feeds-ISSC2HYE.js} +4 -4
- package/dist/{asset-feeds-M3XC5SQD.js.map → asset-feeds-ISSC2HYE.js.map} +1 -1
- package/dist/asset-manager/index.js +1 -1
- package/dist/bridge/drivers/claude-sdk.js +4 -3
- package/dist/bridge/drivers/claude-sdk.js.map +1 -1
- package/dist/bridge/drivers/codex.js +1 -1
- package/dist/bridge/drivers/continue.js +2 -2
- package/dist/bridge/drivers/echo.js +3 -3
- package/dist/bridge/drivers/gemini.js +3 -3
- package/dist/bridge/drivers/goose.js +2 -2
- package/dist/bridge/drivers/omp.js +1 -1
- package/dist/bridge/drivers/opencode.js +2 -2
- package/dist/bridge/drivers/qwen.js +3 -3
- package/dist/bridge/index.js +4 -4
- package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
- package/dist/bridge/src/normalizer.d.ts +6 -0
- package/dist/bridge/src/normalizer.d.ts.map +1 -1
- package/dist/{chunk-NTWVXLOZ.js → chunk-3DOLXE4Z.js} +3 -3
- package/dist/{chunk-NTWVXLOZ.js.map → chunk-3DOLXE4Z.js.map} +1 -1
- package/dist/{chunk-HTIGD3DR.js → chunk-5SXY4B65.js} +3 -3
- package/dist/{chunk-HTIGD3DR.js.map → chunk-5SXY4B65.js.map} +1 -1
- package/dist/{chunk-WQ7DE5UC.js → chunk-73ZXUUL6.js} +25 -8
- package/dist/chunk-73ZXUUL6.js.map +1 -0
- package/dist/{chunk-VOT47UVY.js → chunk-A565EFTW.js} +3 -3
- package/dist/{chunk-VOT47UVY.js.map → chunk-A565EFTW.js.map} +1 -1
- package/dist/{chunk-Y5PKES63.js → chunk-ALSDJ6F4.js} +2 -2
- package/dist/{chunk-Y5PKES63.js.map → chunk-ALSDJ6F4.js.map} +1 -1
- package/dist/{chunk-U3BH5VCG.js → chunk-AY4OKT3U.js} +2 -2
- package/dist/{chunk-U3BH5VCG.js.map → chunk-AY4OKT3U.js.map} +1 -1
- package/dist/{chunk-6EJOXLVH.js → chunk-DGPCBJNQ.js} +2 -2
- package/dist/{chunk-6EJOXLVH.js.map → chunk-DGPCBJNQ.js.map} +1 -1
- package/dist/{chunk-VKLCLC7K.js → chunk-GLOHIJ7B.js} +3 -3
- package/dist/{chunk-VKLCLC7K.js.map → chunk-GLOHIJ7B.js.map} +1 -1
- package/dist/{chunk-J4WDQL42.js → chunk-KFH5GCDB.js} +3 -3
- package/dist/{chunk-J4WDQL42.js.map → chunk-KFH5GCDB.js.map} +1 -1
- package/dist/{chunk-6NTKN6QC.js → chunk-NQG77HXO.js} +3 -3
- package/dist/{chunk-6NTKN6QC.js.map → chunk-NQG77HXO.js.map} +1 -1
- package/dist/{chunk-Z6YHCANW.js → chunk-NRKEZBVP.js} +42 -12
- package/dist/chunk-NRKEZBVP.js.map +1 -0
- package/dist/{chunk-Q3YS5M3E.js → chunk-Q6SWQEF7.js} +284 -61
- package/dist/chunk-Q6SWQEF7.js.map +1 -0
- package/dist/{chunk-QBR3WRXB.js → chunk-RPE5VYB6.js} +65 -11
- package/dist/chunk-RPE5VYB6.js.map +1 -0
- package/dist/{chunk-IDY7A5KA.js → chunk-S3Z5KF6R.js} +3 -3
- package/dist/{chunk-IDY7A5KA.js.map → chunk-S3Z5KF6R.js.map} +1 -1
- package/dist/{chunk-V6QKAC3Z.js → chunk-U2QALNKX.js} +8 -5
- package/dist/chunk-U2QALNKX.js.map +1 -0
- package/dist/{chunk-UPGHKBJ7.js → chunk-UOERRCR3.js} +6 -6
- package/dist/{chunk-UPGHKBJ7.js.map → chunk-UOERRCR3.js.map} +1 -1
- package/dist/{chunk-HIZH3CSZ.js → chunk-UQTPSVJV.js} +6 -6
- package/dist/{chunk-HIZH3CSZ.js.map → chunk-UQTPSVJV.js.map} +1 -1
- package/dist/{chunk-EEOY4LI5.js → chunk-XGO6CP5S.js} +3 -3
- package/dist/{chunk-EEOY4LI5.js.map → chunk-XGO6CP5S.js.map} +1 -1
- package/dist/{chunk-EE627CQN.js → chunk-XHPWI6XF.js} +4 -4
- package/dist/{chunk-EE627CQN.js.map → chunk-XHPWI6XF.js.map} +1 -1
- package/dist/cli/index.js +33 -33
- package/dist/connectors/index.js +5 -5
- package/dist/connectors/src/connector-prompt.d.ts +32 -0
- package/dist/connectors/src/connector-prompt.d.ts.map +1 -1
- package/dist/connectors/src/index.d.ts +2 -2
- package/dist/connectors/src/index.d.ts.map +1 -1
- package/dist/{ensure-sources-YMHAHTN2.js → ensure-sources-YH6X5XI4.js} +4 -4
- package/dist/{ensure-sources-YMHAHTN2.js.map → ensure-sources-YH6X5XI4.js.map} +1 -1
- package/dist/factory-assets/connectors/box.js +5 -5
- package/dist/factory-assets/connectors/deploy.js +5 -5
- package/dist/factory-assets/connectors/devserver.js +5 -5
- package/dist/factory-assets/connectors/flow/adapter.d.ts +8 -1
- package/dist/factory-assets/connectors/flow/adapter.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/adapter.js +5 -5
- package/dist/factory-assets/connectors/flow/index.d.ts +1 -1
- package/dist/factory-assets/connectors/flow/index.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/run-flow.js +6 -6
- package/dist/factory-assets/connectors/flow.js +5 -5
- package/dist/factory-assets/connectors/git.js +5 -5
- package/dist/factory-assets/connectors/gmail.js +5 -5
- package/dist/factory-assets/connectors/googledrive.js +5 -5
- package/dist/factory-assets/connectors/local.js +5 -5
- package/dist/factory-assets/connectors/mattermost.js +5 -5
- package/dist/factory-assets/connectors/memory.js +5 -5
- package/dist/factory-assets/connectors/minio.js +5 -5
- package/dist/factory-assets/connectors/postgres.js +5 -5
- package/dist/factory-assets/connectors/s3.js +5 -5
- package/dist/factory-assets/connectors/sharepoint.js +5 -5
- package/dist/factory-assets/connectors/sqlite.js +5 -5
- package/dist/factory-assets/connectors/static-server.js +5 -5
- package/dist/factory-assets/connectors/tunnel.js +5 -5
- package/dist/factory-assets/connectors/webdav.js +5 -5
- package/dist/factory-assets/connectors/xstate-store.js +5 -5
- package/dist/factory-assets/connectors/xstate.js +5 -5
- package/dist/{helpers-4SPTON2W.js → helpers-EJEK6NN6.js} +4 -4
- package/dist/{helpers-4SPTON2W.js.map → helpers-EJEK6NN6.js.map} +1 -1
- package/dist/{library-publish-TE3JGRLE.js → library-publish-66FHWXAA.js} +6 -6
- package/dist/{library-publish-TE3JGRLE.js.map → library-publish-66FHWXAA.js.map} +1 -1
- package/dist/{open-library-SZFLVRIH.js → open-library-4W2UGVJN.js} +5 -5
- package/dist/{open-library-SZFLVRIH.js.map → open-library-4W2UGVJN.js.map} +1 -1
- package/dist/{project-F54LXGLW.js → project-6OECVELE.js} +5 -5
- package/dist/{project-F54LXGLW.js.map → project-6OECVELE.js.map} +1 -1
- package/dist/runner/index.js +10 -10
- package/dist/runner/src/compaction-gate.d.ts +2 -0
- package/dist/runner/src/compaction-gate.d.ts.map +1 -1
- package/dist/runner/src/driver-swap-gate.d.ts +13 -0
- package/dist/runner/src/driver-swap-gate.d.ts.map +1 -1
- package/dist/runner/src/flow-turn-dispatch.d.ts +40 -0
- package/dist/runner/src/flow-turn-dispatch.d.ts.map +1 -0
- package/dist/runner/src/resource-handler.d.ts +34 -1
- package/dist/runner/src/resource-handler.d.ts.map +1 -1
- package/dist/runner/src/serve.d.ts +25 -1
- package/dist/runner/src/serve.d.ts.map +1 -1
- package/dist/runner/src/session-builder.d.ts +10 -0
- package/dist/runner/src/session-builder.d.ts.map +1 -1
- package/dist/sdk/asset-manager.js +1 -1
- package/dist/sdk/bridge.js +4 -4
- package/dist/sdk/index.js +10 -10
- package/dist/sdk/runner.js +10 -10
- package/dist/sdk/session.js +2 -2
- package/dist/sdk/transport/ws/server.js +1 -1
- package/dist/sdk/transport/ws.js +1 -1
- package/dist/sdk/transport.js +1 -1
- package/dist/sdk/types.js +1 -1
- package/dist/session/index.js +2 -2
- package/dist/{setup-K6CUBTZS.js → setup-6IEVFDWB.js} +6 -6
- package/dist/{setup-K6CUBTZS.js.map → setup-6IEVFDWB.js.map} +1 -1
- package/dist/{source-5FLDWOBP.js → source-HJQNRGTP.js} +6 -6
- package/dist/{source-5FLDWOBP.js.map → source-HJQNRGTP.js.map} +1 -1
- package/dist/{source-manifest-publish-NPNXIC56.js → source-manifest-publish-VU4BGFDU.js} +7 -7
- package/dist/{source-manifest-publish-NPNXIC56.js.map → source-manifest-publish-VU4BGFDU.js.map} +1 -1
- package/dist/transport/index.js +1 -1
- package/dist/transport/src/ws/server.d.ts +3 -1
- package/dist/transport/src/ws/server.d.ts.map +1 -1
- package/dist/transport/ws/server.js +1 -1
- package/dist/transport/ws.js +1 -1
- package/dist/tui/index.js +10 -10
- package/dist/types/index.js +1 -1
- package/dist/types/src/events.d.ts +7 -0
- package/dist/types/src/events.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/protocol.d.ts +11 -0
- package/dist/types/src/protocol.d.ts.map +1 -1
- package/dist/types/src/version.d.ts +6 -1
- package/dist/types/src/version.d.ts.map +1 -1
- package/dist/workspace-plugin/adapters/mcp.js +2 -2
- package/dist/workspace-plugin/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-Q3YS5M3E.js.map +0 -1
- package/dist/chunk-QBR3WRXB.js.map +0 -1
- package/dist/chunk-V6QKAC3Z.js.map +0 -1
- package/dist/chunk-WQ7DE5UC.js.map +0 -1
- package/dist/chunk-Z6YHCANW.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../bridge/src/normalizer.ts","../bridge/src/runtime.ts","../bridge/src/validation.ts"],"names":[],"mappings":";;;;;;AAsBA,SAAS,kBACP,KAAA,EAIA;AACA,EAAA,OAAO;AAAA,IACL,GAAI,MAAM,MAAA,GAAS,EAAE,QA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AAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,CAAA,kBAAA,EAAqB,MAAM,CAAA,CAAA,EAAG;AAAA,EAC3D,SAAS,GAAA,EAAU;AACjB,IAAA,IAAI,GAAA,CAAI,SAAS,YAAA,EAAc,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,OAAO,wBAAA,EAAyB;AACnF,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,GAAA,CAAI,WAAW,eAAA,EAAgB;AAAA,EAC5D;AACF","file":"chunk-QBR3WRXB.js","sourcesContent":["/**\n * EventNormalizer — converts bridge-level AgentEvent (raw driver events) to\n * skaile-agent-types AgentEvent (normalized, human-readable events).\n *\n * Stateful: tracks active subagents and dev-server detection across a session.\n * Call reset() between sessions.\n */\n\nimport {\n type AgentEvent as NormalizedEvent,\n type NativeApprovalDescription,\n stripActivityLabel,\n TOOL_ACTIVITY_LABEL_MAX_CHARS,\n TOOL_ACTIVITY_LABEL_PARAM,\n} from \"@skaile/workspaces/types\";\nimport { classifyClaudeSdkError } from \"./error-classifier.js\";\nimport type { AgentMessage, AgentEvent as BridgeEvent, ContentBlock } from \"./types.js\";\n\n/**\n * The optional usage keys a `result` event carries, in the shape both\n * `finished` and a result-sourced `error` emit them. Absent keys stay absent.\n */\nfunction resultUsageFields(\n event: Pick<\n Extract<BridgeEvent, { type: \"result\" | \"error\" }>,\n \"tokens\" | \"modelUsage\" | \"contextTokens\" | \"contextWindow\"\n >,\n) {\n return {\n ...(event.tokens ? { tokens: event.tokens } : {}),\n ...(event.modelUsage ? { modelUsage: event.modelUsage } : {}),\n ...(typeof event.contextTokens === \"number\" ? { contextTokens: event.contextTokens } : {}),\n ...(typeof event.contextWindow === \"number\" ? { contextWindow: event.contextWindow } : {}),\n };\n}\n\n/**\n * The tool a driver uses to park a turn on a human answer. Both branches that\n * recognise it must use this constant: `message_start` turns it into a\n * `question`, and `tool_call` must then stay silent about it.\n */\nconst QUESTION_TOOL = \"AskUserQuestion\";\n\n/**\n * Converts raw bridge-level {@link BridgeEvent} payloads into normalized\n * `@skaile/workspaces/types` `AgentEvent` payloads consumed by the runner and transport.\n *\n * Stateful: tracks active subagents and dev-server detection across a session.\n * Call {@link EventNormalizer.reset} between sessions to clear accumulated state.\n *\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport class EventNormalizer {\n private activeSubagents = new Map<string, string>();\n private devServerStartingEmitted = false;\n private devServerReadyEmitted = false;\n /** True when message_update deltas have been emitted for the current message. */\n private hasStreamedText = false;\n\n /**\n * Convert a single bridge event into zero or more normalized events.\n * One bridge event can produce multiple normalized events (e.g., a message_start\n * with text + tool_use blocks produces both text and tool_call events).\n */\n normalize(event: BridgeEvent): NormalizedEvent[] {\n switch (event.type) {\n case \"message_start\":\n return this.handleMessageStart(event.message);\n\n case \"message_update\":\n return this.handleMessageUpdate(event);\n\n case \"message_end\":\n return [];\n\n case \"turn_end\":\n return this.handleTurnEnd(event.toolResults);\n\n case \"result\":\n return this.handleResult(event);\n\n case \"error\":\n return [\n {\n type: \"error\",\n message: event.error,\n fatal: event.fatal ?? true,\n category: event.detail?.category,\n ...(event.detail?.hint ? { hint: event.detail.hint } : {}),\n ...resultUsageFields(event),\n },\n ];\n\n case \"tool_call\": {\n // Already handled in message_start — emit status only. The question tool\n // is the exception: the turn parks on the user's answer, so reporting\n // work here would undo the idle its `question` event just set, and\n // nothing follows to correct it while the user reads the prompt.\n const toolName = event.name ?? event.tool?.name;\n if (toolName === QUESTION_TOOL) return [];\n return [{ type: \"status\", phase: \"working\" }];\n }\n\n case \"tool_execution_end\":\n return [];\n\n case \"agent_end\":\n return [{ type: \"status\", phase: \"idle\" }];\n\n case \"commands_available\":\n // Pass through to transport — the gateway caches this event\n return [event as unknown as NormalizedEvent];\n\n case \"session_info\":\n // Pass through to transport — the forge layer stores the OMP session ID\n return [event as unknown as NormalizedEvent];\n\n case \"ui_render\":\n case \"ui_render_update\":\n case \"ui_clear\":\n // Pass through verbatim — drivers that implement the Agent UI Protocol emit these directly\n return [event as unknown as NormalizedEvent];\n\n default:\n return [];\n }\n }\n\n /** Clear all stateful tracking between sessions. */\n reset(): void {\n this.activeSubagents.clear();\n this.devServerStartingEmitted = false;\n this.devServerReadyEmitted = false;\n this.hasStreamedText = false;\n }\n\n // ---------------------------------------------------------------------------\n // message_start → text, tool_call, question, subagent\n // ---------------------------------------------------------------------------\n\n private handleMessageStart(message: AgentMessage): NormalizedEvent[] {\n // Only process assistant messages. Drivers (e.g. omp) may echo the user's\n // message as a message_start with role:\"user\" before streaming the response.\n // Emitting a text event for that echo would prepend the user's input to the\n // assistant bubble on the frontend.\n if (message.role !== \"assistant\") return [];\n\n const events: NormalizedEvent[] = [];\n const blocks = this.getContentBlocks(message);\n\n for (const block of blocks) {\n if (block.type === \"text\" && block.text) {\n // Skip full text if we already streamed it via message_update deltas\n if (!this.hasStreamedText) {\n events.push({ type: \"text\", content: block.text });\n }\n } else if (block.type === \"tool_use\" && block.name) {\n events.push(...this.handleToolUse(block));\n }\n }\n\n this.hasStreamedText = false;\n return events;\n }\n\n private handleToolUse(block: ContentBlock): NormalizedEvent[] {\n const name = block.name!;\n const input = (block.input ?? {}) as Record<string, unknown>;\n\n if (name === QUESTION_TOOL) {\n return this.handleAskUserQuestion(input);\n }\n if (name === \"Agent\") {\n return this.handleAgentToolUse(block, input);\n }\n return this.handleGenericToolUse(name, input);\n }\n\n private handleAskUserQuestion(input: Record<string, unknown>): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n const candidate = input.approval as Partial<NativeApprovalDescription> | undefined;\n const approval =\n candidate &&\n [\"command\", \"file\", \"permissions\", \"mcp\"].includes(candidate.kind ?? \"\") &&\n Array.isArray(candidate.details) &&\n candidate.details.length > 0 &&\n candidate.details.length <= 64 &&\n candidate.details.every((detail) => typeof detail === \"string\" && detail.length <= 8192) &&\n candidate.details.reduce((total, detail) => total + detail.length, 0) <= 65536\n ? (candidate as NativeApprovalDescription)\n : undefined;\n if (Object.hasOwn(input, \"approval\") && !approval) return [];\n // Claude SDK sends { questions: [{ question, header, options: [{ label, description }] }] }\n // Legacy/simple format sends { question: string, options?: string[] }\n const questions = input.questions;\n if (Array.isArray(questions)) {\n for (const q of questions) {\n const qObj = q as Record<string, unknown>;\n const question = String(qObj.question ?? \"\");\n const rawOpts = qObj.options;\n const options = Array.isArray(rawOpts)\n ? rawOpts.map((o: any) => (typeof o === \"string\" ? o : String(o.label ?? o)))\n : undefined;\n events.push({\n type: \"question\",\n question,\n options,\n ...(typeof input.requestId === \"string\" ? { requestId: input.requestId } : {}),\n ...(approval ? { approval } : {}),\n });\n }\n } else {\n const question = String(input.question ?? input.text ?? \"\");\n const rawOptions = input.options;\n const options = Array.isArray(rawOptions) ? rawOptions.map(String) : undefined;\n events.push({\n type: \"question\",\n question,\n options,\n ...(typeof input.requestId === \"string\" ? { requestId: input.requestId } : {}),\n ...(approval ? { approval } : {}),\n });\n }\n return events;\n }\n\n private handleAgentToolUse(\n block: ContentBlock,\n input: Record<string, unknown>,\n ): NormalizedEvent[] {\n const agentName = String(input.subagent_type ?? input.description ?? \"unknown\");\n const description = String(input.description ?? input.prompt ?? \"\").slice(0, 200);\n if (block.id) {\n this.activeSubagents.set(block.id, agentName);\n }\n return [\n { type: \"subagent\", name: agentName, status: \"started\", description },\n { type: \"status\", phase: \"working\" },\n ];\n }\n\n private handleGenericToolUse(name: string, input: Record<string, unknown>): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n const label = labelToolCall(name, input);\n events.push({\n type: \"tool_call\",\n tool: name,\n input,\n // Summarize without the label: it would eat the default branch's\n // 100-char argument budget and push the real args out.\n summary: summarizeToolCall(name, stripActivityLabel(input)),\n ...(label ? { label } : {}),\n });\n events.push({ type: \"status\", phase: \"working\" });\n\n if (name === \"Bash\" && typeof input.command === \"string\") {\n const devEvent = this.detectDevServerStarting(input.command);\n if (devEvent) events.push(devEvent);\n }\n\n return events;\n }\n\n // ---------------------------------------------------------------------------\n // message_update → streaming text\n // ---------------------------------------------------------------------------\n\n private handleMessageUpdate(event: BridgeEvent): NormalizedEvent[] {\n const delta = (event as any)._textDelta as string | undefined;\n if (delta) {\n this.hasStreamedText = true;\n return [{ type: \"text\", content: delta }];\n }\n return [];\n }\n\n // ---------------------------------------------------------------------------\n // turn_end → tool_result, subagent finished, file_changed, dev_server\n // ---------------------------------------------------------------------------\n\n private handleTurnEnd(toolResults?: AgentMessage[]): NormalizedEvent[] {\n if (!toolResults?.length) return [];\n\n const events: NormalizedEvent[] = [];\n\n for (const result of toolResults) {\n const toolName = result.toolName ?? \"unknown\";\n const outputData = result.data ?? result.content;\n const output = typeof outputData === \"string\" ? outputData : JSON.stringify(outputData);\n\n // Check if this is a subagent result\n if (toolName === \"Agent\" || this.isSubagentResult(result)) {\n events.push(...this.handleSubagentResult(result, output));\n } else {\n events.push(...this.handleToolResult(toolName, outputData, output));\n }\n }\n\n return events;\n }\n\n private handleSubagentResult(result: AgentMessage, output: string): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n const agentName = this.resolveSubagentName(result);\n const description = output.slice(0, 200);\n events.push({ type: \"subagent\", name: agentName, status: \"finished\", description });\n\n if (agentName === \"dev-server\") {\n const devEvent = this.detectDevServerReady(output);\n if (devEvent) events.push(devEvent);\n }\n return events;\n }\n\n private handleToolResult(\n toolName: string,\n outputData: unknown,\n output: string,\n ): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n events.push({\n type: \"tool_result\",\n tool: toolName,\n output: outputData,\n summary: summarizeToolResult(toolName, outputData),\n });\n\n // Detect file changes from Write/Edit results\n const fileEvents = detectFileChanges(toolName, outputData);\n if (fileEvents.length > 0) events.push(...fileEvents);\n\n // Detect dev server from Bash output\n if (toolName === \"Bash\") {\n const devEvent = this.detectDevServerReady(output);\n if (devEvent) events.push(devEvent);\n }\n return events;\n }\n\n private isSubagentResult(result: AgentMessage): boolean {\n // Check if the tool result's id maps to a tracked subagent\n if (result.toolName && this.activeSubagents.has(result.toolName)) return true;\n return false;\n }\n\n private resolveSubagentName(result: AgentMessage): string {\n // toolName on bridge AgentMessage is resolved from toolIdToName in the driver\n const name = result.toolName ? this.activeSubagents.get(result.toolName) : undefined;\n if (name) {\n this.activeSubagents.delete(result.toolName!);\n return name;\n }\n return result.toolName ?? \"unknown\";\n }\n\n // ---------------------------------------------------------------------------\n // result → finished or error\n // ---------------------------------------------------------------------------\n\n private handleResult(event: BridgeEvent & { type: \"result\" }): NormalizedEvent[] {\n const usage = resultUsageFields(event);\n if (event.subtype === \"success\") {\n return [\n {\n type: \"finished\",\n summary: event.summary ?? \"Task completed\",\n costUsd: event.costUsd ?? 0,\n ...usage,\n },\n ];\n }\n\n const errors = event.errors ?? [];\n // Run the same classifier the claude-sdk driver uses on its `error`\n // event so the result-error path also surfaces a category and hint\n // (drivers other than claude-sdk emit `result` without a paired\n // `error`, so this is the only place they get classified).\n const detail = classifyClaudeSdkError({ errors, subtype: event.subtype });\n // The turn billed even though it failed: carry its usage so a ledger\n // that only writes on `finished` can write here too. Unlike the finished\n // branch, no `costUsd: 0` fallback — an absent figure stays absent.\n return [\n {\n type: \"error\",\n message: `Agent stopped: ${event.subtype}${errors.length ? ` — ${errors.join(\"; \")}` : \"\"}`,\n fatal: event.subtype === \"error_during_execution\",\n category: detail.category,\n ...(detail.hint ? { hint: detail.hint } : {}),\n ...(typeof event.costUsd === \"number\" ? { costUsd: event.costUsd } : {}),\n ...usage,\n },\n ];\n }\n\n // ---------------------------------------------------------------------------\n // Dev server detection\n // ---------------------------------------------------------------------------\n\n private detectDevServerStarting(command: string): NormalizedEvent | null {\n if (this.devServerStartingEmitted) return null;\n const cmd = command.toLowerCase();\n const isFrontendStart =\n (cmd.includes(\"pnpm run dev\") || cmd.includes(\"pnpm dev\") || cmd.includes(\"vite\")) &&\n (cmd.includes(\"frontend\") || cmd.includes(\"dev:preview\"));\n if (isFrontendStart) {\n this.devServerStartingEmitted = true;\n return { type: \"dev_server\", url: \"http://localhost:3000\", status: \"starting\" };\n }\n return null;\n }\n\n private detectDevServerReady(text: string): NormalizedEvent | null {\n if (this.devServerReadyEmitted) return null;\n\n const explicitMatch = text.match(/DEVSERVER_READY:(https?:\\/\\/[^\\s\"\\\\]+)/);\n if (explicitMatch) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: explicitMatch[1]!, status: \"ready\" };\n }\n\n const viteMatch = text.match(/Local:\\s+(https?:\\/\\/localhost:\\d+)/);\n if (viteMatch) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: viteMatch[1]!, status: \"ready\" };\n }\n\n if (text.includes(\"FRONTEND_READY\")) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: \"http://localhost:3000\", status: \"ready\" };\n }\n\n return null;\n }\n\n // ---------------------------------------------------------------------------\n // Helpers\n // ---------------------------------------------------------------------------\n\n private getContentBlocks(message: AgentMessage): ContentBlock[] {\n if (Array.isArray(message.content)) return message.content;\n if (typeof message.content === \"string\" && message.content) {\n return [{ type: \"text\", text: message.content }];\n }\n return [];\n }\n}\n\n// ---------------------------------------------------------------------------\n// Pure helper functions (exported for reuse)\n// ---------------------------------------------------------------------------\n\n/**\n * Produce a human-readable one-line summary of a tool call for the activity log.\n *\n * Returns a string like `$ git status` for Bash, `Read src/index.ts` for Read, etc.\n * Falls back to `ToolName({...input...})` for unrecognised tools.\n *\n * @param tool - Tool name (e.g. `\"Bash\"`, `\"Write\"`, `\"Grep\"`).\n * @param input - Tool input record passed to the call.\n * @returns A short display string suitable for the activity feed.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function summarizeToolCall(tool: string, input: Record<string, unknown>): string {\n switch (tool) {\n case \"Bash\":\n return `$ ${String(input.command ?? \"\").slice(0, 200)}`;\n case \"Write\":\n return `Create ${String(input.file_path)}`;\n case \"Edit\":\n return `Edit ${String(input.file_path)}`;\n case \"Read\":\n return `Read ${String(input.file_path)}`;\n case \"Glob\":\n return `Find ${String(input.pattern)}`;\n case \"Grep\":\n return `Search for ${String(input.pattern)}`;\n default:\n return `${tool}(${JSON.stringify(input).slice(0, 100)})`;\n }\n}\n\n/**\n * Produce the plain-language label shown to non-technical users while a tool\n * call runs: the agent's own `activity_label`, Bash's `description`, else a\n * derived phrase for Claude Code built-ins. `undefined` for any other tool —\n * the UI then falls back to a generic \"working\" line rather than raw input.\n *\n * @param tool - Tool name as the model called it.\n * @param input - Tool input record, still carrying `activity_label`.\n * @returns A trimmed label capped at `TOOL_ACTIVITY_LABEL_MAX_CHARS`, or `undefined`.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function labelToolCall(tool: string, input: Record<string, unknown>): string | undefined {\n const authored =\n nonEmpty(input[TOOL_ACTIVITY_LABEL_PARAM]) ??\n (tool === \"Bash\" ? nonEmpty(input.description) : undefined);\n const label = authored ?? builtinToolLabel(tool, input);\n if (!label) return undefined;\n return label.length > TOOL_ACTIVITY_LABEL_MAX_CHARS\n ? `${label.slice(0, TOOL_ACTIVITY_LABEL_MAX_CHARS - 1).trimEnd()}…`\n : label;\n}\n\nfunction nonEmpty(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.replace(/\\s+/g, \" \").trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction builtinToolLabel(tool: string, input: Record<string, unknown>): string | undefined {\n switch (tool) {\n case \"Read\":\n return withTarget(\"Reading\", baseName(input.file_path));\n case \"Edit\":\n case \"MultiEdit\":\n case \"NotebookEdit\":\n return withTarget(\"Editing\", baseName(input.file_path ?? input.notebook_path));\n case \"Write\":\n return withTarget(\"Creating\", baseName(input.file_path));\n case \"Grep\":\n case \"Glob\":\n return \"Searching files\";\n case \"WebSearch\":\n return \"Searching the web\";\n case \"WebFetch\":\n return withTarget(\"Fetching\", hostOf(input.url), \"a web page\");\n case \"TodoWrite\":\n return \"Updating the task list\";\n default:\n return undefined;\n }\n}\n\nfunction withTarget(verb: string, target: string | undefined, fallback = \"a file\"): string {\n return `${verb} ${target ?? fallback}`;\n}\n\nfunction baseName(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) return undefined;\n return value.split(/[\\\\/]/).filter(Boolean).pop();\n}\n\nfunction hostOf(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n try {\n return new URL(value).host || undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Extract plain text from an Anthropic content-block array (e.g. tool results returned by Claude SDK). */\nfunction extractContentBlockText(blocks: unknown[]): string | null {\n const textBlocks = blocks.filter(\n (b): b is { type: \"text\"; text: string } =>\n typeof b === \"object\" &&\n b !== null &&\n (b as Record<string, unknown>).type === \"text\" &&\n typeof (b as Record<string, unknown>).text === \"string\",\n );\n if (textBlocks.length === 0) return null;\n return textBlocks.map((b) => b.text).join(\"\\n\");\n}\n\n/**\n * Produce a human-readable one-line summary of a tool result for the activity log.\n *\n * Handles Bash stdout/stderr, Write/Edit file paths, ApplyPatch change counts, and\n * Anthropic content-block arrays. Falls back to `JSON.stringify` for unknown shapes.\n *\n * @param tool - Tool name.\n * @param result - Raw tool result payload.\n * @returns A short display string, truncated to 200 characters.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function summarizeToolResult(tool: string, result: unknown): string {\n // Handle Anthropic content-block arrays: [{ type: \"text\", text: \"...\" }, ...]\n if (Array.isArray(result)) {\n const text = extractContentBlockText(result);\n return (text ?? JSON.stringify(result)).slice(0, 200);\n }\n if (typeof result !== \"object\" || !result) {\n return String(result).slice(0, 200);\n }\n const r = result as Record<string, unknown>;\n switch (tool) {\n case \"Bash\": {\n const stderr = String(r.stderr ?? \"\").trim();\n if (stderr) return `stderr: ${stderr.slice(0, 200)}`;\n return (\n String(r.stdout ?? \"\")\n .trim()\n .slice(0, 200) || \"(no output)\"\n );\n }\n case \"Write\":\n return `${String(r.type)}: ${String(r.filePath)}`;\n case \"Edit\":\n return `Edited ${String(r.filePath)}`;\n case \"ApplyPatch\":\n return `${Array.isArray(r.changes) ? r.changes.length : 0} file changes`;\n default:\n return JSON.stringify(result).slice(0, 200);\n }\n}\n\n/**\n * Detect file-change events from a tool result, returning zero or more `file_changed` events.\n *\n * Handles `Write` (single create/edit), `Edit` (single edit), and `ApplyPatch` (multi-file\n * patch with per-change `kind` classification). Returns an empty array for all other tools.\n *\n * @param toolName - Name of the tool that produced the result.\n * @param result - Raw tool result payload.\n * @returns Array of `file_changed` normalized events.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function detectFileChanges(toolName: string, result: unknown): NormalizedEvent[] {\n if (typeof result !== \"object\" || !result) return [];\n const r = result as Record<string, unknown>;\n\n if (toolName === \"Write\" && r.filePath) {\n return [\n {\n type: \"file_changed\",\n path: String(r.filePath),\n action: r.type === \"create\" ? \"create\" : \"edit\",\n },\n ];\n }\n if (toolName === \"Edit\" && r.filePath) {\n return [{ type: \"file_changed\", path: String(r.filePath), action: \"edit\" }];\n }\n if (toolName === \"ApplyPatch\" && Array.isArray(r.changes)) {\n return r.changes\n .filter(\n (change): change is { path: string; kind: \"add\" | \"delete\" | \"update\" } =>\n typeof change === \"object\" &&\n change !== null &&\n typeof (change as Record<string, unknown>).path === \"string\" &&\n typeof (change as Record<string, unknown>).kind === \"string\",\n )\n .map((change) => ({\n type: \"file_changed\" as const,\n path: change.path,\n action: change.kind === \"add\" ? \"create\" : change.kind === \"delete\" ? \"delete\" : \"edit\",\n }));\n }\n\n return [];\n}\n\n/**\n * Backward-compatible single-event helper; returns the first `file_changed` event or `null`.\n *\n * Prefer {@link detectFileChanges} for multi-file patches (e.g. `ApplyPatch`).\n *\n * @param toolName - Name of the tool that produced the result.\n * @param result - Raw tool result payload.\n * @returns First detected `file_changed` event, or `null`.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function detectFileChange(toolName: string, result: unknown): NormalizedEvent | null {\n return detectFileChanges(toolName, result)[0] ?? null;\n}\n","/**\n * BridgeRuntime — implements IAgentRuntime from @skaile/workspaces/types by wrapping\n * an AgentDriver + EventNormalizer. This is the primary integration point for\n * consumers that want normalized events from any driver.\n */\n\nimport type {\n AgentEvent,\n AgentPromptInput,\n AgentReconfigureOptions,\n AgentRuntimeConfig,\n IAgentRuntime,\n} from \"@skaile/workspaces/types\";\n\nimport { EventNormalizer } from \"./normalizer.js\";\nimport { createDriver } from \"./registry.js\";\nimport type { AgentConfig, AgentDriver } from \"./types.js\";\n\n/**\n * Implements `IAgentRuntime` from `@skaile/workspaces/types` by wrapping an {@link AgentDriver}\n * and an {@link EventNormalizer}.\n *\n * This is the primary integration point for consumers that want normalized `AgentEvent`\n * payloads from any driver without managing the driver lifecycle directly. Create via\n * {@link createRuntime} to avoid coupling to `BridgeRuntime` directly.\n *\n * @docLink packages/bridge/api-reference#runtime\n */\nexport class BridgeRuntime implements IAgentRuntime {\n private driver: AgentDriver | null = null;\n private normalizer = new EventNormalizer();\n private handlers = new Set<(event: AgentEvent) => void>();\n private boundEventHandler: ((event: any) => void) | null = null;\n private driverId: string;\n\n constructor(driverId: string = \"claude-sdk\") {\n this.driverId = driverId;\n }\n\n async start(config: AgentRuntimeConfig): Promise<void> {\n // Dispose previous driver if any\n if (this.driver) {\n await this.dispose();\n }\n\n this.normalizer.reset();\n\n const bridgeConfig: AgentConfig = {\n cwd: config.cwd,\n provider: config.provider,\n model: config.model,\n systemPrompt: config.systemPrompt,\n apiKeys: config.apiKeys,\n env: config.env,\n agentDir: config.agentDir,\n sessionId: config.sessionId,\n resumeSessionId: config.resumeSessionId,\n maxTurns: config.maxTurns,\n };\n\n this.driver = await createDriver(this.driverId, bridgeConfig);\n\n // Wire bridge events through normalizer to handlers\n this.boundEventHandler = (bridgeEvent: any) => {\n const normalized = this.normalizer.normalize(bridgeEvent);\n for (const event of normalized) {\n for (const handler of this.handlers) {\n handler(event);\n }\n }\n };\n this.driver.on(\"agent-event\", this.boundEventHandler);\n\n await this.driver.start();\n }\n\n async configure(_config: AgentReconfigureOptions): Promise<void> {\n // Runtime reconfiguration for BridgeRuntime is a no-op for now.\n // Future: reconnect connectors, reload ai-assets, update subagents.\n }\n\n async prompt(message: string): Promise<void> {\n if (!this.driver) throw new Error(\"Runtime not started — call start() first\");\n await this.driver.prompt(message);\n }\n\n async promptInput(input: AgentPromptInput): Promise<void> {\n if (!this.driver) throw new Error(\"Runtime not started — call start() first\");\n await this.driver.promptInput(input);\n }\n\n async reply(answer: string, question?: string, requestId?: string): Promise<void> {\n if (!this.driver) throw new Error(\"Runtime not started — call start() first\");\n // Mirror serve.ts handleReply: an answer must resume the paused turn. Falling through to\n // prompt() would deny the question as superseded and drop the structured answer.\n if (\n this.driver?.hasPendingQuestion() &&\n this.driver.answerQuestion(answer, question, requestId)\n )\n return;\n if (this.driver?.acceptsReplyAsPrompt) await this.prompt(answer);\n }\n\n async abort(): Promise<void> {\n if (this.driver) {\n await this.driver.abort();\n }\n }\n\n async dispose(): Promise<void> {\n if (this.driver) {\n if (this.boundEventHandler) {\n this.driver.off(\"agent-event\", this.boundEventHandler);\n this.boundEventHandler = null;\n }\n this.driver.kill();\n this.driver = null;\n }\n this.normalizer.reset();\n }\n\n onEvent(handler: (event: AgentEvent) => void): void {\n this.handlers.add(handler);\n }\n\n offEvent(handler: (event: AgentEvent) => void): void {\n this.handlers.delete(handler);\n }\n\n get isRunning(): boolean {\n return this.driver?.isRunning ?? false;\n }\n}\n\n/**\n * Factory function to create a {@link BridgeRuntime} with the specified driver.\n *\n * @param driverId - Registered driver id (default: `\"claude-sdk\"`).\n * @returns A new `IAgentRuntime` wrapping the selected driver with event normalization.\n * @docLink packages/bridge/api-reference#runtime\n */\nexport function createRuntime(driverId: string = \"claude-sdk\"): IAgentRuntime {\n return new BridgeRuntime(driverId);\n}\n","/** Provider API key validation — hits each provider's models endpoint to verify the key works. */\n\nimport { PROVIDER_ENDPOINTS, resolveProviderModelsUrl } from \"./provider-endpoints.js\";\n\n/**\n * Result of an API key validation check performed by {@link validateApiKey}.\n *\n * @docLink packages/bridge/api-reference#validation\n */\nexport interface ValidationResult {\n /** `true` when the API key was accepted by the provider's models endpoint. */\n ok: boolean;\n /** Human-readable error description when `ok` is `false`. */\n error?: string;\n}\n\n/**\n * Validate an API key by sending a lightweight GET request to the provider's models endpoint.\n *\n * Returns `{ ok: true }` when the provider accepts the key (HTTP 2xx). Returns\n * `{ ok: false, error }` on 401/403 (invalid key), other HTTP errors, network failures,\n * or unsupported providers. Requests time out after 8 seconds.\n *\n * @param provider - Provider name matching a key in the shared `PROVIDER_ENDPOINTS` map\n * (e.g. `\"anthropic\"`, `\"openai\"`, `\"google\"`).\n * @param key - API key to validate.\n * @param options - Optional base-URL / environment overrides; defaults to the\n * provider's own API, or its `baseUrlEnv` value when one is set.\n * @returns Validation result with optional error description.\n * @docLink packages/bridge/api-reference#validation\n */\nexport async function validateApiKey(\n provider: string,\n key: string,\n options: { baseUrl?: string; env?: Record<string, string | undefined> } = {},\n): Promise<ValidationResult> {\n const endpoint = PROVIDER_ENDPOINTS[provider];\n if (!endpoint) return { ok: false, error: `Unknown provider: ${provider}` };\n\n // Validate against the same endpoint discovery/dispatch use: behind a gateway\n // the key is the gateway's, and the provider's public API would reject it.\n let url =\n resolveProviderModelsUrl(provider, {\n baseUrl: options.baseUrl,\n env: options.env ?? process.env,\n }) ?? endpoint.url;\n if (endpoint.queryParam) url += `?${endpoint.queryParam}=${encodeURIComponent(key)}`;\n\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 8000);\n\n const response = await fetch(url, {\n method: \"GET\",\n headers: endpoint.headers(key),\n signal: controller.signal,\n });\n\n clearTimeout(timeout);\n\n if (response.ok) return { ok: true };\n\n const status = response.status;\n if (status === 401 || status === 403) {\n return { ok: false, error: \"Invalid API key (authentication failed)\" };\n }\n return { ok: false, error: `API returned HTTP ${status}` };\n } catch (err: any) {\n if (err.name === \"AbortError\") return { ok: false, error: \"Request timed out (8s)\" };\n return { ok: false, error: err.message ?? \"Network error\" };\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../types/src/mentions.ts","../types/src/reactions.ts","../types/src/capabilities.ts","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ACE,CAAC,OAAO,SAAA,CAAU,KAAK,KACvB,CAAC,MAAA,CAAO,UAAU,KAAK,CAAA,IACvB,CAAC,MAAA,CAAO,SAAA,CAAU,KAAK,CAAA,IACvB,KAAA,GAAQ,KACR,KAAA,GAAQ,CAAA,IACR,QAAQ,CAAA,EACR;AACA,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,0BAAA,EAA6B,CAAC,CAAA,4CAAA,CAA8C,CAAA;AAAA,EAC9F;AACA,EAAA,OAAO,EAAE,KAAA,EAAO,KAAA,EAAO,KAAA,EAAM;AAC/B;AAiBO,SAAS,cAAc,CAAA,EAA4B;AACxD,EAAA,OAAO,CAAA,EAAG,EAAE,KAAK,CAAA,CAAA,EAAI,EAAE,KAAK,CAAA,CAAA,EAAI,EAAE,KAAK,CAAA,CAAA;AACzC","file":"chunk-V6QKAC3Z.js","sourcesContent":["/**\n * Mentions — types for @-mention support in session messages.\n *\n * A Mention records who was addressed in a message, whether a specific user\n * or a well-known group. Group mentions carry a resolved array of user IDs\n * so consumers can perform membership checks without the resolver.\n */\n\n// ---------------------------------------------------------------------------\n// Groups\n// ---------------------------------------------------------------------------\n\n/**\n * Well-known group mention targets as a `const` array.\n *\n * Use this for validation or exhaustive checks against `MentionGroup`.\n *\n * @docLink packages/types/messages#mention\n */\nexport const MENTION_GROUPS = [\"agent\", \"humans\", \"humans_here\", \"here\", \"all\"] as const;\n\n/**\n * A well-known group that can be `@`-mentioned: `'agent' | 'humans' | 'humans_here' | 'here' | 'all'`.\n *\n * @docLink packages/types/messages#mention\n */\nexport type MentionGroup = (typeof MENTION_GROUPS)[number];\n\n// ---------------------------------------------------------------------------\n// Mention discriminated union\n// ---------------------------------------------------------------------------\n\n/**\n * A parsed `@`-mention in a session message. Records who was addressed — either a\n * specific user or a well-known group — along with the source text position.\n *\n * Group mentions carry a resolved array of user IDs so consumers can perform\n * membership checks without needing the resolver.\n *\n * @docLink packages/types/messages#mention\n */\nexport type Mention =\n | {\n type: \"user\";\n userId: string;\n name: string;\n /** Position of the `@` character in the source text. */\n offset: number;\n /** Length of the full `@token` string including the `@`. */\n length: number;\n }\n | {\n type: \"group\";\n group: MentionGroup;\n /** User IDs resolved at parse time (e.g. all online users for `@here`). */\n resolved: string[];\n /** Position of the `@` character in the source text. */\n offset: number;\n /** Length of the full `@token` string including the `@`. */\n length: number;\n }\n | {\n type: \"custom\";\n /** Consumer-defined mention kind, e.g. \"assistant\". */\n kind: string;\n /** User IDs this mention resolves to (so isMentioned works); may be empty. */\n resolved: string[];\n /** Optional consumer payload, e.g. { sessionId, ownerId }. */\n data?: Record<string, unknown>;\n /** Position of the `@` character in the source text. */\n offset: number;\n /** Length of the full `@token` string including the `@`. */\n length: number;\n };\n","/**\n * Reactions -- emoji reactions on session messages.\n *\n * Any session participant (user or agent) can react to any message.\n * Reactions are persisted in a dedicated DB model and broadcast as\n * transient events for real-time updates.\n */\n\n/**\n * A single emoji reaction on a message, set by any session participant (user or agent).\n *\n * Reactions are persisted in a dedicated DB model and broadcast as transient events\n * for real-time updates.\n *\n * @docLink packages/types/messages#reaction\n */\nexport type Reaction = {\n /** Unicode emoji character (e.g. \"thumbs up\", not \":thumbsup:\"). */\n emoji: string;\n /** ID of the user (or \"agent\" for agent reactions). */\n userId: string;\n /** Display name at reaction time (avoids extra lookups for tooltip rendering). */\n userName: string;\n /** Unix epoch milliseconds. */\n timestamp: number;\n};\n\n/**\n * Quick-access emojis shown in the reaction bar picker.\n *\n * An `as const` array of eight Unicode emoji characters in display order.\n *\n * @docLink packages/types/messages#reaction\n */\nexport const QUICK_REACTIONS = [\n \"\\u{1F44D}\",\n \"\\u{1F440}\",\n \"\\u2705\",\n \"\\u2764\\uFE0F\",\n \"\\u{1F914}\",\n \"\\u{1FAE1}\",\n \"\\u{1F44F}\",\n \"\\u{1F389}\",\n] as const;\n","/**\n * Capability layer — Protocol v2's unified registry of LLM-invokable entry points.\n *\n * A {@link Capability} is a named, schema-typed entry point that the LLM can call\n * during a session. Capabilities are registered into a per-session\n * registry by either side (host platform via `side: 'client'` or runtime via\n * `side: 'agent'`) and routed by the bridge at invocation time.\n *\n * This module defines the wire types only; the runtime registry, the\n * `defineCapability` helper, and the per-handler logger live in\n * `@skaile/workspaces/runner`.\n *\n * @see {@link MessageV2} envelope that carries capability commands and events\n * @see {@link ProtocolVersion} for the version contract\n *\n * @category Capabilities\n * @since 2.0.0\n */\n\n// ---------------------------------------------------------------------------\n// Capability shape\n// ---------------------------------------------------------------------------\n\n/**\n * Visibility scope for a capability. Determines which surfaces the capability\n * appears on and which callers can invoke it.\n *\n * - `'llm'`: registered as an LLM tool, surfaced in the `<CAPABILITIES>` system\n * prompt section. The agent driver can invoke it.\n * - `'user'`: appears in user-facing surfaces — the command palette (cmdK),\n * debug menus, capability lists.\n * - `'runtime'`: invocable only by trusted runner / platform code paths. Never\n * reaches the LLM tool list. Never reaches the command palette. Used for\n * host RPCs (`host.refresh_credential`, `host.audit`, `host.notify_user`,\n * `host.persist_compaction_attempt`) and runner RPCs (`runner.add_mount`,\n * `runner.set_log_level`, `runner.lifecycle`, ...).\n *\n * Multiple audiences are allowed (e.g. `['llm', 'user']`). The default when\n * {@link Capability.audience} is omitted is `['llm', 'user']`, preserving the\n * v2.x default visibility for capabilities that haven't migrated yet.\n *\n * @category Capabilities\n * @since 3.0.0\n * @docLink packages/types/capabilities#capability-audience\n */\nexport type CapabilityAudience = \"llm\" | \"user\" | \"runtime\";\n\n/**\n * Source of truth for who registered a capability. Used for trust enforcement\n * (the bridge rejects mismatches between registering side and origin kind)\n * and for the `capability:<origin>:<name>` log taxonomy.\n *\n * Variants:\n * - `framework`: built-in (e.g. `__capabilities.list`)\n * - `client`: host platform (e.g. `platform.react`)\n * - `agent`: self-registered by the agent runtime\n * - `flow`: injected by an active flow execution\n * - `skill`: from a skill's MCP surface\n * - `mcp`: from a generic MCP server\n * - `connector`: from a connector (e.g. `postgres.query`)\n * - `mount`: surfaced by a filesystem mount\n * - `app`: from an embedded, agent-controllable app (carries the originating\n * `appId`). Handlers run in the app itself — see {@link Capability.side} `'app'`.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-origin\n */\nexport type CapabilityOrigin =\n | { kind: \"framework\" }\n | { kind: \"client\" }\n | { kind: \"agent\" }\n | { kind: \"flow\"; flowId: string }\n | { kind: \"skill\"; skillId: string }\n | { kind: \"mcp\"; serverId: string }\n | { kind: \"connector\"; connectorId: string }\n | { kind: \"mount\"; mountId: string }\n | { kind: \"app\"; appId: string };\n\n/**\n * Render contract for a capability that produces a UI surface when invoked.\n *\n * When the LLM invokes a capability whose `render` is set, the bridge emits\n * a {@link RenderInvokedEvent} carrying the capability name and props. The\n * client renders the configured `source` at the chosen `target`. Clients\n * without a render layer can fall back to the markdown `fallback` template.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#render-spec\n */\nexport type RenderSpec = {\n /** Where the rendered component lives. */\n source: { kind: \"web-component\"; url: string; tagName: string } | { kind: \"iframe\"; url: string };\n /** Render placements supported by the component. */\n targets: (\"chat\" | \"preview\" | \"modal\" | \"input-extension\")[];\n /** Markdown template with `{{prop}}` placeholders for clients without a render layer. */\n fallback?: string;\n /** True when props may be partial during streaming. */\n streaming?: boolean;\n /** Interaction names the rendered component may fire back as state events. */\n interactions?: string[];\n};\n\n/**\n * A named, schema-typed entry point that the LLM can invoke during a session.\n *\n * Capabilities can be declared statically (via `ConfigureCommand.capabilities`)\n * or dynamically (via {@link CapabilityRegisterCommand} /\n * {@link CapabilityRegisterEvent}). They are cached for replay across\n * subscriber reconnects and session hibernation.\n *\n * @example Defining a client-side fire-and-forget tool (uses the runner's\n * `defineCapability` helper, which serializes a {@link Capability} to the wire):\n * ```ts\n * const reactTool = defineCapability({\n * name: 'platform.react',\n * description: 'Acknowledge a user message with a Unicode emoji.',\n * side: 'client',\n * origin: { kind: 'client' },\n * fireAndForget: true,\n * input: z.object({ emoji: z.string(), targetSeq: z.number().optional() }),\n * handler: async ({ emoji, targetSeq }, ctx) => { ... },\n * });\n * ```\n *\n * @see {@link RenderCapability} for capabilities that render UI components\n * @see {@link CapabilityOrigin} for who-registered-it metadata\n * @see {@link isRenderCapability} for the type-guard\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability\n */\nexport type Capability = {\n /** Unique within a session. Convention: namespaced as `<origin>.<name>` (e.g. `platform.react`, `ui.gif`). */\n name: string;\n /**\n * Human-readable label for user-facing surfaces (cmdK action palette,\n * capability menus, debug panels). Falls back to {@link Capability.name}\n * when omitted. Pure presentation — the LLM sees `name`, not `displayName`.\n */\n displayName?: string;\n /** Human/LLM-readable summary. Shown to the LLM as part of tool registration. */\n description: string;\n /** JSON Schema validating the invocation arguments. Authored as Zod, converted at register time. */\n inputSchema: Record<string, unknown>;\n /** Optional return shape. Omit for fire-and-forget effects. */\n outputSchema?: Record<string, unknown>;\n /** Where the handler runs. `client` = host platform, `agent` = runtime/skill/connector, `app` = embedded app. */\n side: \"client\" | \"agent\" | \"app\";\n /** Discriminated tag identifying who registered the capability. Used for trust enforcement and audit. */\n origin: CapabilityOrigin;\n /** Lifetime: `session` survives the whole session, `turn` is dropped at end-of-turn. */\n scope?: \"session\" | \"turn\";\n /** When true, the bridge auto-resolves with `{}` immediately and runs the handler in the background. */\n fireAndForget?: boolean;\n /** When true, the platform shows a confirm UI before dispatch and waits for {@link CapabilityApproveCommand}. */\n requiresApproval?: boolean;\n /** Documentation hint (not enforced) describing whether this is a side-effect, render, or pure query. */\n kind?: \"effect\" | \"render\" | \"query\";\n /**\n * Whether this capability should be exposed in user-facing surfaces (cmdK\n * action palette, capability menus). When omitted, the consumer applies a\n * default per-origin via {@link isUserInvokable}.\n *\n * - `true`: surface in cmdK and capability menus.\n * - `false`: hide from user surfaces (LLM-only or low-level).\n * - `undefined`: defer to {@link isUserInvokable}'s inference rules.\n *\n * @deprecated Set {@link Capability.audience} instead. `userInvokable` is\n * kept as a read-only shim for v2.x consumers and is honoured by\n * {@link isUserInvokable} when {@link Capability.audience} is absent.\n */\n userInvokable?: boolean;\n /**\n * Audience scoping for this capability. See {@link CapabilityAudience} for\n * the meaning of each value and combinations.\n *\n * When omitted, consumers treat the capability as `['llm', 'user']` (the\n * v2.x default). Host RPCs and runner RPCs MUST set this to `['runtime']`\n * so they never leak to the LLM tool list or the user-facing surfaces.\n *\n * @category Capabilities\n * @since 3.0.0\n */\n audience?: CapabilityAudience[];\n /** Appended to the system prompt's `<CAPABILITIES>` section. Use for usage hints the LLM should always see. */\n promptFragment?: string;\n /**\n * Per-capability override for how long the runner waits on the\n * `capability_result` round-trip before timing out. When omitted the\n * runner applies its default (`DEFAULT_CAPABILITY_CALL_TIMEOUT_MS`, 60s).\n *\n * Set this for capabilities that legitimately block far longer than a\n * normal tool call — e.g. `platform.ask_session` suspends the caller's\n * turn until a peer session answers, which can take minutes.\n *\n * @category Capabilities\n * @since 3.3.0\n */\n callTimeoutMs?: number;\n /** Present iff this is a render capability — see {@link RenderCapability}. */\n render?: RenderSpec;\n};\n\n/**\n * A {@link Capability} that produces a UI surface when invoked. The narrowed\n * type guarantees `render` is set, which simplifies frontend lookup.\n *\n * @see {@link isRenderCapability}\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#render-capability\n */\nexport type RenderCapability = Capability & { render: NonNullable<Capability[\"render\"]> };\n\n/**\n * Type-guard for {@link RenderCapability}. Use after {@link Capability}\n * lookup to narrow the type before reading `render`.\n *\n * @example\n * ```ts\n * for (const cap of registry.list()) {\n * if (isRenderCapability(cap)) console.log(cap.render.targets);\n * }\n * ```\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#is-render-capability\n */\nexport function isRenderCapability(cap: Capability): cap is RenderCapability {\n return cap.render !== undefined;\n}\n\n/**\n * Decide whether a capability should be surfaced in user-facing actions\n * (cmdK action palette, capability menus).\n *\n * Resolution order (first match wins):\n *\n * 1. {@link Capability.audience} is set — return `audience.includes('user')`.\n * Capabilities scoped to `'runtime'` only never appear in user surfaces.\n * 2. {@link Capability.userInvokable} is set (v2.x shim) — return that value.\n * 3. Default per-origin inference table below.\n *\n * Default-inference rules (when both `audience` and `userInvokable` are\n * omitted):\n * | Origin | Default |\n * | ------------ | ---------------------------------------------------------------------- |\n * | `framework` | `false` (LLM discovery surfaces, e.g. `__capabilities.list`) |\n * | `client` | `false` (platform ack tools — `platform.react`, `platform.pass`) |\n * | `agent` | `false` (agent-defined; assume internal unless flagged) |\n * | `flow` | `false` (per-cap opt-in) |\n * | `connector` | `false` (low-level FS / data ops) |\n * | `mount` | `false` (low-level FS ops) |\n * | `app` | `false` (LLM-only; app authors opt in via `audience: ['llm','user']`) |\n * | `mcp` | `true` if `kind === 'effect'`, else `false` |\n * | `skill` | `true` if `kind` ∈ {`effect`, `render`}, else `false` |\n *\n * @example\n * ```ts\n * for (const cap of capabilities.values()) {\n * if (isUserInvokable(cap)) registerCommandPaletteAction(cap);\n * }\n * ```\n *\n * @category Capabilities\n * @since 2.1.0\n * @docLink packages/types/capabilities#is-user-invokable\n */\nexport function isUserInvokable(cap: Capability): boolean {\n if (cap.audience !== undefined) {\n return cap.audience.includes(\"user\");\n }\n if (cap.userInvokable !== undefined) {\n return cap.userInvokable;\n }\n switch (cap.origin.kind) {\n case \"framework\":\n case \"client\":\n case \"agent\":\n case \"flow\":\n case \"connector\":\n case \"mount\":\n case \"app\":\n return false;\n case \"mcp\":\n return cap.kind === \"effect\";\n case \"skill\":\n return cap.kind === \"effect\" || cap.kind === \"render\";\n default:\n return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Capability commands (client → agent)\n// ---------------------------------------------------------------------------\n\n/**\n * Register one or more capabilities mid-session (client → agent).\n *\n * The platform sends this when a new client-side tool becomes available\n * after `configure` has already returned (e.g. a user installs a new\n * extension during the session).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-register-command\n */\nexport type CapabilityRegisterCommand = {\n type: \"capability_register\";\n capabilities: Capability[];\n};\n\n/**\n * Deregister capabilities by name (client → agent). Names that are not\n * currently registered are ignored silently.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-deregister-command\n */\nexport type CapabilityDeregisterCommand = {\n type: \"capability_deregister\";\n names: string[];\n};\n\n/**\n * Return the result of a previously {@link CapabilityInvokedEvent | invoked} client-side\n * capability (client → agent). Bridges that registered the capability with\n * `fireAndForget: true` MAY skip this command; the bridge auto-resolves with `{}`.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-result-command\n */\nexport type CapabilityResultCommand = {\n type: \"capability_result\";\n /** Correlation token matching the {@link CapabilityInvokedEvent.callId}. */\n callId: string;\n /** Successful result payload, or an error envelope. */\n result: unknown | { error: string };\n};\n\n/**\n * Invoke an **agent-side** capability (client → agent). The host names the\n * capability and supplies its input; the runner answers with a matching\n * {@link CapabilityResultEvent}. The mirror of {@link CapabilityInvokedEvent},\n * which reports the LLM invoking a client-side capability in the opposite\n * direction and shares this discriminant.\n *\n * @category Capabilities\n * @since 3.23.0\n * @docLink packages/types/capabilities#capability-invoke-command\n */\nexport type CapabilityInvokeCommand = {\n type: \"capability_invoked\";\n /** Correlation token the answering {@link CapabilityResultEvent} echoes. */\n callId: string;\n /** Name of the {@link Capability} to invoke. */\n name: string;\n /** Input payload, validated against the capability's schema by the registry. */\n input: unknown;\n};\n\n/**\n * Return the result of a platform-invoked **agent-side** capability\n * (agent → client). The mirror of {@link CapabilityResultCommand}, which\n * carries the same shape in the opposite direction for client-side\n * capabilities; `runner.attach_instance` and its `runner.*` siblings answer\n * with this one.\n *\n * Both directions share the `capability_result` discriminant, so the sender\n * decides which type applies — they are never both valid on one hop.\n *\n * @category Capabilities\n * @since 3.23.0\n * @docLink packages/types/capabilities#capability-result-event\n */\nexport type CapabilityResultEvent = {\n type: \"capability_result\";\n /** Correlation token matching the invoking call. */\n callId: string;\n /** Successful result payload, or an error envelope. */\n result: unknown | { error: string };\n};\n\n/**\n * Approve or reject a capability call that was invoked with\n * `requiresApproval: true` (client → agent). The platform shows a confirm\n * UI and forwards the user's decision via this command.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-approve-command\n */\nexport type CapabilityApproveCommand = {\n type: \"capability_approve\";\n /** Correlation token matching the {@link CapabilityInvokedEvent.callId}. */\n callId: string;\n /** User's decision. */\n decision: \"approved\" | \"rejected\";\n /** Optional rationale stored alongside the decision for audit. */\n feedback?: string;\n /** User ID of the decider (informational — framework enforces no policy). */\n decidedBy: string;\n};\n\n// ---------------------------------------------------------------------------\n// Capability events (agent → client)\n// ---------------------------------------------------------------------------\n\n/**\n * Register one or more capabilities mid-session (agent → client). Mirrors\n * {@link CapabilityRegisterCommand} for the agent-initiated direction; used\n * when the runtime adds a capability after `configure` (e.g. when a flow\n * starts and injects flow-scoped tools).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-register-event\n */\nexport type CapabilityRegisterEvent = {\n type: \"capability_register\";\n capabilities: Capability[];\n};\n\n/**\n * Deregister capabilities by name (agent → client).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-deregister-event\n */\nexport type CapabilityDeregisterEvent = {\n type: \"capability_deregister\";\n names: string[];\n};\n\n/**\n * Notify the client that a capability has been invoked by the LLM (agent →\n * client). For client-side capabilities the platform's handler runs in\n * response to this event and replies with {@link CapabilityResultCommand}.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#capability-invoked-event\n */\nexport type CapabilityInvokedEvent = {\n type: \"capability_invoked\";\n /** Correlation token for the eventual {@link CapabilityResultCommand}. */\n callId: string;\n /** Name of the invoked {@link Capability}. */\n name: string;\n /** Validated input payload (already conforms to the capability's `inputSchema`). */\n input: unknown;\n /** In v2.0.0 the LLM is the only invoker. */\n invokedBy: \"agent\";\n};\n\n/**\n * Notify the client that a render capability should be drawn (agent →\n * client). Emitted alongside {@link CapabilityInvokedEvent} when the\n * invoked capability's `render` block is populated.\n *\n * Clients without a render layer can fall back to the capability's\n * `render.fallback` markdown template.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/types/capabilities#render-invoked-event\n */\nexport type RenderInvokedEvent = {\n type: \"render_invoked\";\n /** Name of the invoked render capability. */\n capabilityName: string;\n /** Props passed to the rendered component (already conforms to `inputSchema`). */\n props: unknown;\n /** Correlation token shared with the matching {@link CapabilityInvokedEvent}. */\n callId: string;\n};\n","/**\n * Agent-authored tool-call activity labels.\n *\n * Every tool the runtime advertises to the model carries one extra optional\n * string parameter, {@link TOOL_ACTIVITY_LABEL_PARAM}, in which the agent\n * describes the call in plain language (\"Reading the Q3 budget spreadsheet\").\n * The normalizer surfaces it as `ToolCallEvent.label` so the chat can show it\n * instead of the raw tool name and arguments.\n *\n * The parameter is added at the ADVERTISE layer only and stripped before the\n * real handler runs. It never enters a capability's registered `inputSchema`,\n * because that schema is hashed into the resume signature.\n *\n * Zod is passed in rather than imported: the Claude SDK and the bridge each\n * bring their own zod instance, and the schema must be built with the one the\n * SDK validates against.\n *\n * @category Tools\n * @since 3.24.0\n */\n\n/** Name of the optional parameter injected into every advertised tool schema. */\nexport const TOOL_ACTIVITY_LABEL_PARAM = \"activity_label\";\n\n/** Longest label the normalizer passes on; longer text is truncated with an ellipsis. */\nexport const TOOL_ACTIVITY_LABEL_MAX_CHARS = 120;\n\n/** LLM-facing description of {@link TOOL_ACTIVITY_LABEL_PARAM}. */\nexport const TOOL_ACTIVITY_LABEL_DESCRIPTION =\n \"Short plain-language description (under ~12 words, present tense) of what this call does, \" +\n \"shown to the user while it runs, e.g. 'Reading the Q3 budget spreadsheet'. \" +\n \"Never include secrets.\";\n\n/** System-prompt guidance telling the agent to fill the label on every call. */\nexport const TOOL_ACTIVITY_PROMPT_SECTION = [\n \"## Tool-call activity labels\",\n \"\",\n `Whenever a tool offers an \\`${TOOL_ACTIVITY_LABEL_PARAM}\\` parameter, always fill it. For the Bash tool, always fill its \\`description\\` parameter.`,\n \"The text is shown to the user while the call runs, in place of the tool's technical details, so write it for a non-technical reader:\",\n \"under ~12 words, present tense, naming the thing being worked on (e.g. 'Reading the Q3 budget spreadsheet', 'Checking which invoices are overdue').\",\n \"Never put secrets, tokens or raw file contents in it.\",\n].join(\"\\n\");\n\n/**\n * Add {@link TOOL_ACTIVITY_LABEL_PARAM} to a zod raw shape (a record of zod\n * fields, as `createSdkMcpServer` accepts). Returns the shape unchanged when\n * the tool already declares a property of that name.\n */\nexport function withActivityLabelShape(\n shape: Record<string, unknown>,\n z: any,\n): Record<string, unknown> {\n if (Object.hasOwn(shape, TOOL_ACTIVITY_LABEL_PARAM)) return shape;\n return {\n ...shape,\n [TOOL_ACTIVITY_LABEL_PARAM]: z.string().optional().describe(TOOL_ACTIVITY_LABEL_DESCRIPTION),\n };\n}\n\n/**\n * Add {@link TOOL_ACTIVITY_LABEL_PARAM} to a JSON Schema object's top-level\n * `properties`. Returns the schema unchanged when it already declares the\n * property.\n */\nexport function withActivityLabelJsonSchema(\n schema: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n const base = schema ?? {};\n if (declaresActivityLabel(base)) return base;\n const props = (base.properties ?? {}) as Record<string, unknown>;\n return {\n ...base,\n properties: {\n ...props,\n [TOOL_ACTIVITY_LABEL_PARAM]: { type: \"string\", description: TOOL_ACTIVITY_LABEL_DESCRIPTION },\n },\n };\n}\n\n/** True when a JSON Schema object itself declares {@link TOOL_ACTIVITY_LABEL_PARAM}. */\nexport function declaresActivityLabel(schema: unknown): boolean {\n if (!schema || typeof schema !== \"object\") return false;\n const props = (schema as Record<string, unknown>).properties;\n return !!props && typeof props === \"object\" && Object.hasOwn(props, TOOL_ACTIVITY_LABEL_PARAM);\n}\n\n/**\n * Remove {@link TOOL_ACTIVITY_LABEL_PARAM} from a tool input before it reaches\n * the handler. Returns a shallow copy; non-object inputs and inputs without\n * the key are returned as-is.\n */\nexport function stripActivityLabel<T>(input: T): T {\n if (!input || typeof input !== \"object\" || Array.isArray(input)) return input;\n if (!Object.hasOwn(input, TOOL_ACTIVITY_LABEL_PARAM)) return input;\n const { [TOOL_ACTIVITY_LABEL_PARAM]: _label, ...rest } = input as Record<string, unknown>;\n return rest as T;\n}\n\n/**\n * Wrap in-process SDK tool defs: advertise {@link TOOL_ACTIVITY_LABEL_PARAM}\n * and strip it before each handler runs. A def that already declares the\n * property is returned untouched — the value is then the tool's own argument.\n */\nexport function withActivityLabelDefs<\n T extends { inputSchema: Record<string, unknown>; handler: (args: any) => unknown },\n>(defs: T[], z: any): T[] {\n return defs.map((def) => {\n if (Object.hasOwn(def.inputSchema, TOOL_ACTIVITY_LABEL_PARAM)) return def;\n return {\n ...def,\n inputSchema: withActivityLabelShape(def.inputSchema, z),\n // Forward the SDK's trailing args (`extra`) untouched.\n handler: (args: unknown, ...rest: unknown[]) =>\n (def.handler as (a: unknown, ...r: unknown[]) => unknown)(\n stripActivityLabel(args),\n ...rest,\n ),\n };\n });\n}\n","/**\n * Protocol versioning primitives for Skaile Agent Protocol v2.\n *\n * The protocol is versioned by a structured {@link ProtocolVersion} record\n * (`major.minor.patch`). The compatibility rule applied at handshake is\n * **major-equality**: a runner emits {@link IncompatibleProtocolEvent} and\n * shuts down when its declared major does not match the platform's announced\n * major. Minor and patch differences ride through transparently because\n * unknown fields are preserved on round-trip (see `MessageMeta` round-trip\n * contract in `messaging.ts`).\n *\n * @category Protocol\n * @since 2.0.0\n */\n\n/**\n * Structured semantic version triple for the agent protocol.\n *\n * @example\n * ```ts\n * const v: ProtocolVersion = { major: 2, minor: 0, patch: 0 };\n * ```\n *\n * @category Protocol\n * @since 2.0.0\n * @docLink packages/types/protocol-v2#protocol-version\n */\nexport type ProtocolVersion = {\n /** Incremented on breaking wire-format changes (field removed, semantics changed, required field added). */\n major: number;\n /** Incremented on additive wire-format changes (new optional fields, new event types). */\n minor: number;\n /** Incremented on bug-fix or doc-only changes that do not affect the wire. */\n patch: number;\n};\n\n/**\n * The protocol version the framework currently speaks. Runners and platforms\n * compare this against the peer's announced version at session boot via\n * `SessionInitCommand.protocolVersion`.\n *\n * @example\n * ```ts\n * import { PROTOCOL_VERSION } from '@skaile/workspaces/types';\n * if (cmd.protocolVersion.major !== PROTOCOL_VERSION.major) {\n * emit({ type: 'incompatible_protocol', agentVersion: PROTOCOL_VERSION, platformVersion: cmd.protocolVersion });\n * }\n * ```\n *\n * @category Protocol\n * @since 3.0.0\n *\n * Changed in 3.13.0:\n * Optional agent-authored `label` on the `tool_call` event, and a new\n * `\"tool-activity\"` member of `SystemPromptSection.label`. Older peers ignore\n * both; a host that renders `label` can feature-detect it by this minor.\n *\n * Changed in 3.12.0:\n * Optional structured prompt attachments and question/reply requestId correlation.\n * Older peers retain text prompts and ignore unknown optional fields. Managed\n * question hosts must echo requestId; this minor does not advertise or admit the\n * separately gated codex-app-server-v1 runtime.\n *\n * Changed in 3.10.0:\n * Additive rejection cause on the AI-credential refresh input. The\n * `host.refresh_credential` `ai-credentials` input gains an optional\n * `rejection?: CredentialRejection` (`'auth' | 'usage-limit'`), sent only\n * alongside `reason: 'retry-401'` and only from the two runner call sites that\n * genuinely classified the failure — the driver's auth self-heal (`'auth'`) and\n * its usage-limit failover (`'usage-limit'`). `reason: 'retry-401'` collapsed\n * both, so a limit-blocked session on a config that is not opted into\n * `autoActivate` never re-resolved; the field is what lets the platform tell\n * them apart. `auth` asserts only that the rejection was auth-shaped, never\n * that capacity is fine (Anthropic mislabels OAuth quota exhaustion as\n * `authentication_error`); only `usage-limit` is a positive assertion. The\n * connector and MCP refresh paths classify nothing and keep emitting exactly\n * today's bytes. There is no peer-version gate, so a 3.9 peer does receive the\n * key on those two inputs; it is unaffected because nothing was removed or\n * reshaped and it must ignore an unknown key — and an unrecognised value —\n * rather than reject the input, which is also what allows a third rejection\n * later without a major bump. A 3.10 host against a 3.9 runner never sees the\n * field and must not read its absence as \"not a limit\" (feature-detect on\n * `major === 3 && minor >= 10`).\n * Spec: skaile-ai/platform#3562.\n *\n * Changed in 3.9.0:\n * Additive live AI-provider-seat signals, all optional under the\n * major-equality rule:\n * - `AgentEvent` gains `provider_response_seen`, emitted when the runner\n * observes a 401 or a 429 / subscription-limit rejection from the AI\n * provider, attributed to the pinned `AIProviderConfig`. A platform with\n * no handler broadcasts it harmlessly; consumers must ignore unknown\n * fields, since the platform half ships independently.\n * - The `CredentialMint` success branch gains an optional `configId` — the\n * seat the platform actually minted for. When it differs from the one the\n * runner asked for, the runner repoints the live session at it. A platform\n * that omits the field produces exactly 3.8 behaviour (no switch is ever\n * detected).\n * - The `credentialRotated` broadcast may carry `entry.data.configId` to\n * move a running session to a different seat rather than merely rotating\n * the token on the current one. Absent → today's re-pull.\n * A 3.8 peer is unaffected: nothing was removed or re-shaped, every addition is\n * opt-in on a field a 3.8 peer never sets. A 3.9 host against a 3.8 runner sees\n * no `provider_response_seen` and must not read that as \"no limits were hit\"\n * (feature-detect on `major === 3 && minor >= 9`).\n *\n * Changed in 3.8.0:\n * Additive `prompt` receipt acknowledgement. The `prompt` command gains an\n * optional `messageId`; when set the runner emits exactly one new `prompt_ack`\n * event echoing it, as the first act of handling the frame — before the\n * session-readiness gate, the secrets check and the driver start, each of which\n * could previously drop a prompt with no trace at all. When absent nothing is\n * emitted, so a 3.7 host sees byte-identical behaviour. A 3.8 host against a\n * 3.7 runner gets no ack and must not read that as a lost prompt — feature-detect\n * on `major === 3 && minor >= 8`. The ack is receipt-only: it says the frame\n * arrived, never that the turn ran.\n *\n * Changed in 3.7.0:\n * Additive `connector_mutate` acknowledgement + flow-hydrate reconciliation.\n * Three changes, all additive under the major-equality rule:\n * - `ConnectorMutateCommand` gains an optional `requestId`. When set, the\n * runner emits exactly one new `connector_mutate_response` event (with\n * `ok` / `result` / `error` / `code` / `reconciled`) on every terminal path,\n * including the paths that previously only logged. When absent nothing is\n * emitted, so a 3.6 host sees byte-identical behaviour.\n * - `flow.hydrate` accepts an optional `payload.pendingDecisions` —\n * `PendingGateDecision[]` the runner replays against the snapshot in the\n * same invocation that creates the flow connector, reporting the outcome as\n * `reconciled`. A host that omits the key gets today's hydrate.\n * - A flow-targeted mutate whose connector is not yet registered now waits\n * (bounded, `SKAILE_FLOW_MUTATE_CONNECTOR_WAIT_MS`, default 8000 ms) and\n * re-plans instead of failing — a behaviour change on a path that used to\n * fail silently, visible to a 3.6 host only as the op succeeding.\n * A 3.6 peer is unaffected: no symbol was removed or re-shaped, the ack is\n * opt-in on a field a 3.6 host never sets, and unknown fields ride through the\n * round-trip. A 3.7 host against a 3.6 runner sees `requestId` ignored and no\n * response, which it must treat as \"unacknowledged\" (feature-detect on\n * `major === 3 && minor >= 7`). Spec: `runner/MIGRATION-flow-connector.md`.\n *\n * Changed in 3.6.0:\n * Additive resolved-agent-config wire field. `ResolvedSkaileConfig` gains an\n * optional `agentConfig?: ResolvedAgentConfig` carrying the platform-resolved\n * driver / provider / model / cloud / cloudConfig / thinking / effort — the\n * same values the platform bakes into the generated skaile.yaml\n * `agent-config.default`. The runner applies it disk-first: any on-disk\n * `agent-config` profile with at least one agent setting disables the wire\n * value outright, so yaml-on-disk (docker-mode) sessions are byte-identical.\n * Additive under the major-equality rule: an older runner ignores the field\n * and an older platform simply omits it.\n *\n * Changed in 3.5.0:\n * Flow-connector host-contract fix (workspaces#379). Three coordinated changes,\n * all additive under the major-equality rule:\n * - `op:\"hydrate\"` on the bare `\"flow\"` connector now auto-creates the\n * `flow:<runId>` connector on a cold container from its `{ state, flow }`\n * payload, so a persisted run rehydrates in one op. A peer that still issues\n * `start` then `hydrate` keeps working unchanged.\n * - The dead `SessionInit.activeFlows` field (never read by the runner) and its\n * `ActiveFlowRehydration` type are removed — wire-compatible (nothing produced\n * or consumed them) but source-breaking for typed hosts, hence the bump.\n * - Malformed / conflicting flow `start` and `hydrate` payloads now fail loudly\n * (warn with a reason) instead of silently falling through.\n * Because the handshake compares only `major`, a 3.4 host and a 3.5 runner\n * interoperate: the auto-create path is opt-in on the payload the host sends, and\n * the removed field was already inert. Spec: `runner/MIGRATION-flow-connector.md`.\n *\n * Changed in 3.4.0:\n * Additive embedded-app capability source. `CapabilityOrigin` gains a\n * `{ kind: 'app'; appId: string }` variant and `Capability.side` gains `'app'`\n * (\"the handler runs in the embedded app\"). Both are additive: a peer that does\n * not understand `origin:'app'` / `side:'app'` never produces or routes them, so\n * they ride through transparently under the major-equality rule. No new message\n * types — `capability_register` / `capability_invoked` / `capability_result` /\n * `capability_approve` / `render_invoked` are reused verbatim. Spec:\n * `_devlog/specs/2026-07-07-app-capability-source.md`.\n *\n * Changed in 3.3.0:\n * Additive agent-to-agent (session-to-session) communication extension.\n * `AgentEvent` gains an `a2a_message` variant carrying cross-session messages\n * (`direction`, `peerSessionId`, `peerName`, `exchangeId`, `text`). `Capability`\n * gains an optional `callTimeoutMs?: number` so a long-running capability call\n * (e.g. a 5-minute `platform.ask_session`) can exceed the default capability-call\n * timeout. Both are additive: a peer that does not understand them ignores the\n * event / falls back to the default timeout, so they ride through transparently\n * under the major-equality rule.\n *\n * Changed in 3.2.0:\n * Additive wake-time resume cascade. `AgentReconfigureOptions` gains optional\n * `resumeSessionId` and `expectedCapabilitySignature` fields driving the tier-1\n * native SDK resume path; `AgentEvent` gains `ResumeAttemptedEvent` and\n * `ResumeFailedEvent`. `FinishedEvent` gains optional `customType` /\n * `customData` for capability-routed custom payloads. All additive — clients\n * that omit the resume hint or ignore the new events keep working unchanged.\n *\n * Changed in 3.1.0:\n * Additive cost / token usage extension. `FinishedEvent` gains an optional\n * `tokens?: TokenUsage` field carrying per-turn input / output / cache-read /\n * cache-creation / reasoning token counts. `AgentDriver.getTokenUsage()` is\n * widened to return the same `TokenUsage` shape (existing consumers reading\n * `inputTokens` / `outputTokens` keep working unchanged). Drivers that do not\n * surface token usage continue to return `null` / omit the field.\n *\n * Changed in 3.0.0:\n * Major bump for the deterministic session bootstrap rewrite. `ConfigureCommandV2`,\n * `provision_secrets`, `request_access_token`, `add_resource`, `remove_resource`,\n * `set_log_level`, `state_action`, `lifecycle`, `remount_mount`, `compact`, and\n * `reconfigure_agent` are removed from the `AgentCommand` union. Their semantics\n * are reachable through:\n * - `session_init` (one deterministic envelope at session start that delivers\n * identity, resolved config, pre-minted credentials, secrets, capabilities,\n * shared state, active flows, resume hints, and logging config),\n * - `host.refresh_credential` (capability invocation that replaces the\n * refresh-on-401 path of `request_access_token`), and\n * - `runner.*` capabilities (`runner.add_mount`, `runner.add_connector`,\n * `runner.remove_resource`, `runner.update_credential`, `runner.set_log_level`,\n * `runner.set_state`, `runner.lifecycle`) invoked by the platform via the\n * bidirectional capability registry.\n *\n * Capabilities gain an `audience: ('llm' | 'user' | 'runtime')[]` field that\n * scopes visibility: host RPCs (`host.*`) and runner RPCs (`runner.*`) are\n * `['runtime']` and never reach the LLM tool list or the user-facing command\n * palette. v2.x capabilities without an explicit `audience` default to\n * `['llm', 'user']`, preserving prior behaviour.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`.\n *\n * @docLink packages/types/protocol-v3#protocol-version\n */\nexport const PROTOCOL_VERSION: ProtocolVersion = { major: 3, minor: 13, patch: 0 };\n\n/**\n * String form of {@link PROTOCOL_VERSION}, kept in lock-step. Useful for\n * `package.json` version fields and HTTP `User-Agent` strings.\n *\n * @category Protocol\n * @since 3.0.0\n * @docLink packages/types/protocol-v3#protocol-version\n */\nexport const PROTOCOL_VERSION_STRING = \"3.13.0\";\n\n/**\n * Parse a `\"major.minor.patch\"` string into a {@link ProtocolVersion}.\n *\n * @param s - the version string to parse, exactly three dot-separated non-negative integers\n * @returns the parsed protocol version\n * @throws {Error} if the string is not exactly three dot-separated non-negative integers\n *\n * @example\n * ```ts\n * parseVersion('2.0.0'); // { major: 2, minor: 0, patch: 0 }\n * parseVersion('2.1'); // throws\n * ```\n *\n * @category Protocol\n * @since 2.0.0\n * @docLink packages/types/protocol-v2#parse-version\n */\nexport function parseVersion(s: string): ProtocolVersion {\n const parts = s.split(\".\");\n if (parts.length !== 3) {\n throw new Error(`Invalid ProtocolVersion: \"${s}\" (expected \"major.minor.patch\")`);\n }\n const [maj, min, pat] = parts;\n const major = Number(maj);\n const minor = Number(min);\n const patch = Number(pat);\n if (\n !Number.isInteger(major) ||\n !Number.isInteger(minor) ||\n !Number.isInteger(patch) ||\n major < 0 ||\n minor < 0 ||\n patch < 0\n ) {\n throw new Error(`Invalid ProtocolVersion: \"${s}\" (each part must be a non-negative integer)`);\n }\n return { major, minor, patch };\n}\n\n/**\n * Format a {@link ProtocolVersion} record into its `\"major.minor.patch\"` string form.\n *\n * @param v - the protocol version to format\n * @returns the dot-joined string form\n *\n * @example\n * ```ts\n * formatVersion({ major: 2, minor: 0, patch: 0 }); // '2.0.0'\n * ```\n *\n * @category Protocol\n * @since 2.0.0\n * @docLink packages/types/protocol-v2#format-version\n */\nexport function formatVersion(v: ProtocolVersion): string {\n return `${v.major}.${v.minor}.${v.patch}`;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../transport/src/ws/server.ts"],"names":[],"mappings":";;;;AA6CA,SAAS,yBAAyB,GAAA,EAA6C;AAC7E,EAAA,IAAI,GAAA,CAAI,IAAA,KAAS,cAAA,EAAgB,OAAO,6BAAA;AAExC,EAAA,MAAM,WAAW,GAAA,CAAI,QAAA;AACrB,EAAA,IAAI,CAAC,YAAY,OAAO,QAAA,KAAa,YAAY,KAAA,CAAM,OAAA,CAAQ,QAAQ,CAAA,EAAG;AACxE,IAAA,OAAO,4BAAA;AAAA,EACT;AACA,EAAA,IAAI,OAAO,QAAA,CAAS,WAAA,KAAgB,QAAA,EAAU,OAAO,uCAAA;AACrD,EAAA,IAAI,OAAO,QAAA,CAAS,SAAA,KAAc,QAAA,EAAU,OAAO,qCAAA;AACnD,EAAA,IAAI,OAAO,QAAA,CAAS,SAAA,KAAc,QAAA,EAAU,OAAO,qCAAA;AAEnD,EAAA,MAAM,kBAAkB,GAAA,CAAI,eAAA;AAC5B,EAAA,IAAI,CAAC,mBAAmB,OAAO,eAAA,KAAoB,YAAY,KAAA,CAAM,OA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AAA,IACF,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AACF","file":"chunk-WQ7DE5UC.js","sourcesContent":["/**\n * WebSocketServerTransport — `ws`-based WebSocket server.\n *\n * Accepts one client at a time. Implements ServerTransport from @skaile/workspaces/types.\n * Built on the `ws` package + `node:http`, both of which run under Node and Bun.\n */\n\nimport { createServer, type Server as HttpServer } from \"node:http\";\nimport type { AgentCommand, AgentEvent, ServerTransport } from \"@skaile/workspaces/types\";\nimport { type WebSocket, WebSocketServer } from \"ws\";\nimport { decodeBearerFromHeader, tokensEqual } from \"./auth.js\";\n\n/**\n * Options for {@link WebSocketServerTransport}.\n *\n * @param port - TCP port to bind to.\n * @param onLog - Optional callback for internal log lines (client connect/disconnect events).\n * @param authToken - When set, every upgrade must present this token via the\n * `skaile-bearer.<base64url>` subprotocol or the handshake is rejected with\n * HTTP 401. When unset, no auth is enforced (back-compatible default).\n *\n * @docLink packages/transport/dev-guide#websocket-server-transport\n */\nexport interface WebSocketServerOptions {\n port: number;\n onLog?: (line: string) => void;\n authToken?: string;\n}\n\n/**\n * Shape-validate a `session_init` frame at ingress before forwarding to the\n * runner. Protocol v3 requires the deterministic bootstrap envelope to carry\n * an identity tuple, a semver-shaped `protocolVersion`, a resolved config\n * object, and a `credentials` map keyed by `mounts` / `connectors`. Frames\n * that fail the guard are rejected on the wire so the runner never sees a\n * malformed boot envelope.\n *\n * Returns `null` when the frame is well-formed, or a human-readable reason\n * when it should be rejected.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`\n * § \"SessionInitCommand schema\".\n *\n * @internal\n */\nfunction validateSessionInitShape(cmd: Record<string, unknown>): string | null {\n if (cmd.type !== \"session_init\") return \"type must be 'session_init'\";\n\n const identity = cmd.identity as Record<string, unknown> | undefined;\n if (!identity || typeof identity !== \"object\" || Array.isArray(identity)) {\n return \"identity must be an object\";\n }\n if (typeof identity.containerId !== \"string\") return \"identity.containerId must be a string\";\n if (typeof identity.sessionId !== \"string\") return \"identity.sessionId must be a string\";\n if (typeof identity.projectId !== \"string\") return \"identity.projectId must be a string\";\n\n const protocolVersion = cmd.protocolVersion as Record<string, unknown> | undefined;\n if (!protocolVersion || typeof protocolVersion !== \"object\" || Array.isArray(protocolVersion)) {\n return \"protocolVersion must be an object\";\n }\n if (typeof protocolVersion.major !== \"number\") return \"protocolVersion.major must be a number\";\n if (typeof protocolVersion.minor !== \"number\") return \"protocolVersion.minor must be a number\";\n if (typeof protocolVersion.patch !== \"number\") return \"protocolVersion.patch must be a number\";\n\n if (\n !cmd.resolvedConfig ||\n typeof cmd.resolvedConfig !== \"object\" ||\n Array.isArray(cmd.resolvedConfig)\n ) {\n return \"resolvedConfig must be an object\";\n }\n\n if (!cmd.credentials || typeof cmd.credentials !== \"object\" || Array.isArray(cmd.credentials)) {\n return \"credentials must be an object\";\n }\n\n return null;\n}\n\n/**\n * `ServerTransport` implementation backed by the `ws` package on top of a\n * `node:http` server.\n *\n * Enforces a single-client policy: if a new connection arrives while a client is\n * already connected, the stale connection is closed with code 4001 and replaced.\n * Incoming frames are parsed as JSON `AgentCommand` messages and fanned out to\n * registered `onCommand` handlers; outgoing `AgentEvent` objects are JSON-serialised\n * before sending. Call `listen()` to start accepting connections and `close()` to\n * shut down cleanly — `close()` terminates the active socket immediately rather\n * than keeping the event loop alive.\n *\n * @example\n * ```ts\n * const server = new WebSocketServerTransport({ port: 8080 });\n * await server.listen();\n * server.onCommand((cmd) => console.log(cmd));\n * server.send({ type: 'agent_end' });\n * await server.close();\n * ```\n *\n * @docLink packages/transport/dev-guide#websocket-server-transport\n */\nexport class WebSocketServerTransport implements ServerTransport {\n private httpServer: HttpServer | null = null;\n private wss: WebSocketServer | null = null;\n private activeClient: WebSocket | null = null;\n private readonly port: number;\n private readonly log: (line: string) => void;\n private readonly authToken?: string;\n\n private readonly commandHandlers = new Set<(command: AgentCommand) => void>();\n private readonly connectHandlers = new Set<() => void>();\n private readonly disconnectHandlers = new Set<() => void>();\n\n constructor(options: WebSocketServerOptions) {\n this.port = options.port;\n this.log = options.onLog ?? console.log;\n this.authToken = options.authToken;\n }\n\n /** Start the server and accept connections. */\n async listen(): Promise<void> {\n const httpServer = createServer((_req, res) => {\n res.writeHead(200, { \"content-type\": \"text/plain\" });\n res.end(\"skaile agent server\");\n });\n // When an auth token is configured, reject the upgrade at handshake time\n // (HTTP 401) unless the client presents the matching bearer subprotocol.\n // Rejecting here — before `connection` — keeps unauthenticated sockets from\n // ever reaching the command handlers.\n const expected = this.authToken;\n const wss = new WebSocketServer({\n server: httpServer,\n verifyClient: expected\n ? (info, cb) => {\n const presented = decodeBearerFromHeader(info.req.headers[\"sec-websocket-protocol\"]);\n if (presented !== null && tokensEqual(presented, expected)) {\n cb(true);\n } else {\n this.log(\"[ws-server] rejecting unauthenticated upgrade\");\n cb(false, 401, \"Unauthorized\");\n }\n }\n : undefined,\n });\n wss.on(\"connection\", (ws) => this.handleConnection(ws));\n this.httpServer = httpServer;\n this.wss = wss;\n\n await new Promise<void>((resolve, reject) => {\n httpServer.once(\"error\", reject);\n httpServer.listen(this.port, () => {\n httpServer.off(\"error\", reject);\n resolve();\n });\n });\n\n const addr = httpServer.address();\n const boundPort = typeof addr === \"object\" && addr ? addr.port : this.port;\n this.log(`[ws-server] listening on port ${boundPort}`);\n }\n\n private handleConnection(ws: WebSocket): void {\n if (this.activeClient) {\n // Close the stale connection instead of rejecting the new one.\n // This handles the race where waitForWsReady's probe hasn't\n // fully disconnected before the real gateway client connects.\n this.log(\"[ws-server] replacing previous connection\");\n try {\n this.activeClient.close(4001, \"Replaced by new connection\");\n } catch {\n // already closed\n }\n }\n this.log(\"[ws-server] client connected\");\n this.activeClient = ws;\n for (const handler of this.connectHandlers) {\n handler();\n }\n\n ws.on(\"message\", (data) => {\n try {\n const parsed = JSON.parse(String(data)) as Record<string, unknown>;\n // Protocol v3: shape-validate `session_init` at ingress so the\n // runner never receives a malformed boot envelope. Other command\n // shapes pass through unchanged — invalid `AgentCommand`s surface\n // through the existing per-command handlers in serve.ts.\n if (parsed && typeof parsed === \"object\" && parsed.type === \"session_init\") {\n const reason = validateSessionInitShape(parsed);\n if (reason !== null) {\n this.log(`[ws-server] rejecting invalid session_init: ${reason}`);\n this.sendRaw({\n type: \"error\",\n message: `Invalid session_init: ${reason}`,\n fatal: false,\n });\n return;\n }\n }\n const cmd = parsed as unknown as AgentCommand;\n for (const handler of this.commandHandlers) {\n handler(cmd);\n }\n } catch (err) {\n this.sendRaw({\n type: \"error\",\n message: `Invalid message: ${err instanceof Error ? err.message : String(err)}`,\n fatal: false,\n });\n }\n });\n\n ws.on(\"close\", () => {\n this.log(\"[ws-server] client disconnected\");\n if (this.activeClient === ws) {\n this.activeClient = null;\n for (const handler of this.disconnectHandlers) {\n handler();\n }\n }\n });\n }\n\n /**\n * Stop the server.\n *\n * Terminates the active socket immediately — otherwise a still-connected\n * client would keep the event loop alive and block process shutdown.\n */\n async close(): Promise<void> {\n try {\n this.activeClient?.terminate();\n } catch {\n // already closed\n }\n this.activeClient = null;\n this.wss?.close();\n this.wss = null;\n const httpServer = this.httpServer;\n this.httpServer = null;\n if (httpServer) {\n httpServer.closeAllConnections();\n await new Promise<void>((resolve) => httpServer.close(() => resolve()));\n }\n }\n\n send(event: AgentEvent): void {\n this.sendRaw(event);\n }\n\n onCommand(handler: (command: AgentCommand) => void): () => void {\n this.commandHandlers.add(handler);\n return () => {\n this.commandHandlers.delete(handler);\n };\n }\n\n onConnect(handler: () => void): () => void {\n this.connectHandlers.add(handler);\n return () => {\n this.connectHandlers.delete(handler);\n };\n }\n\n onDisconnect(handler: () => void): () => void {\n this.disconnectHandlers.add(handler);\n return () => {\n this.disconnectHandlers.delete(handler);\n };\n }\n\n get connected(): boolean {\n return this.activeClient !== null;\n }\n\n private sendRaw(data: unknown): void {\n try {\n const client = this.activeClient;\n if (client && client.readyState === 1) {\n client.send(JSON.stringify(data));\n }\n } catch {\n // Silently ignore send failures\n }\n }\n}\n"]}
|