@particle-academy/agent-integrations 0.44.0 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -3
- package/dist/bridges/artboard.d.cts +3 -3
- package/dist/bridges/artboard.d.ts +3 -3
- package/dist/bridges/catalog.d.cts +3 -3
- package/dist/bridges/catalog.d.ts +3 -3
- package/dist/bridges/charts.d.cts +3 -3
- package/dist/bridges/charts.d.ts +3 -3
- package/dist/bridges/cms.d.cts +3 -3
- package/dist/bridges/cms.d.ts +3 -3
- package/dist/bridges/code.d.cts +3 -3
- package/dist/bridges/code.d.ts +3 -3
- package/dist/bridges/doc.d.cts +3 -3
- package/dist/bridges/doc.d.ts +3 -3
- package/dist/bridges/features.d.cts +3 -3
- package/dist/bridges/features.d.ts +3 -3
- package/dist/bridges/files.d.cts +3 -3
- package/dist/bridges/files.d.ts +3 -3
- package/dist/bridges/flow.d.cts +3 -3
- package/dist/bridges/flow.d.ts +3 -3
- package/dist/bridges/forms.d.cts +3 -3
- package/dist/bridges/forms.d.ts +3 -3
- package/dist/bridges/git.d.cts +3 -3
- package/dist/bridges/git.d.ts +3 -3
- package/dist/bridges/grid.d.cts +3 -3
- package/dist/bridges/grid.d.ts +3 -3
- package/dist/bridges/map.d.cts +3 -3
- package/dist/bridges/map.d.ts +3 -3
- package/dist/bridges/passkeys.d.cts +3 -3
- package/dist/bridges/passkeys.d.ts +3 -3
- package/dist/bridges/scene.d.cts +3 -3
- package/dist/bridges/scene.d.ts +3 -3
- package/dist/bridges/screens.d.cts +3 -3
- package/dist/bridges/screens.d.ts +3 -3
- package/dist/bridges/sheets.d.cts +3 -3
- package/dist/bridges/sheets.d.ts +3 -3
- package/dist/bridges/slides.d.cts +3 -3
- package/dist/bridges/slides.d.ts +3 -3
- package/dist/bridges/terminal.d.cts +3 -3
- package/dist/bridges/terminal.d.ts +3 -3
- package/dist/bridges/tui.d.cts +2 -2
- package/dist/bridges/tui.d.ts +2 -2
- package/dist/bridges/whiteboard.d.cts +3 -3
- package/dist/bridges/whiteboard.d.ts +3 -3
- package/dist/bridges-artboard.cjs.map +1 -1
- package/dist/bridges-artboard.js +2 -2
- package/dist/bridges-catalog.cjs.map +1 -1
- package/dist/bridges-catalog.js +3 -3
- package/dist/bridges-charts.cjs.map +1 -1
- package/dist/bridges-charts.js +3 -3
- package/dist/bridges-cms.cjs.map +1 -1
- package/dist/bridges-cms.js +4 -4
- package/dist/bridges-code.cjs.map +1 -1
- package/dist/bridges-code.js +3 -3
- package/dist/bridges-doc.cjs.map +1 -1
- package/dist/bridges-doc.js +3 -3
- package/dist/bridges-features.cjs.map +1 -1
- package/dist/bridges-features.js +3 -3
- package/dist/bridges-files.cjs.map +1 -1
- package/dist/bridges-files.js +3 -3
- package/dist/bridges-flow.cjs.map +1 -1
- package/dist/bridges-flow.js +2 -2
- package/dist/bridges-forms.cjs.map +1 -1
- package/dist/bridges-forms.js +3 -3
- package/dist/bridges-git.cjs.map +1 -1
- package/dist/bridges-git.js +3 -3
- package/dist/bridges-grid.cjs.map +1 -1
- package/dist/bridges-grid.js +3 -3
- package/dist/bridges-map.cjs.map +1 -1
- package/dist/bridges-map.js +3 -3
- package/dist/bridges-passkeys.cjs.map +1 -1
- package/dist/bridges-passkeys.js +3 -3
- package/dist/bridges-scene.cjs.map +1 -1
- package/dist/bridges-scene.js +3 -3
- package/dist/bridges-screens.cjs.map +1 -1
- package/dist/bridges-screens.js +3 -3
- package/dist/bridges-sheets.cjs.map +1 -1
- package/dist/bridges-sheets.js +3 -3
- package/dist/bridges-slides.cjs.map +1 -1
- package/dist/bridges-slides.js +3 -3
- package/dist/bridges-terminal.cjs.map +1 -1
- package/dist/bridges-terminal.js +3 -3
- package/dist/bridges-tui.cjs.map +1 -1
- package/dist/bridges-tui.js +2 -2
- package/dist/bridges-whiteboard.cjs.map +1 -1
- package/dist/bridges-whiteboard.js +3 -3
- package/dist/{chunk-5W6YOXLT.js → chunk-36MKPTVD.js} +4 -4
- package/dist/{chunk-5W6YOXLT.js.map → chunk-36MKPTVD.js.map} +1 -1
- package/dist/{chunk-SXVRIIXW.js → chunk-3HVYUMQF.js} +4 -4
- package/dist/{chunk-SXVRIIXW.js.map → chunk-3HVYUMQF.js.map} +1 -1
- package/dist/{chunk-MZ74LLDS.js → chunk-3UUF5KKZ.js} +4 -4
- package/dist/{chunk-MZ74LLDS.js.map → chunk-3UUF5KKZ.js.map} +1 -1
- package/dist/{chunk-WEXMZMJH.js → chunk-3WVXAB3D.js} +3 -3
- package/dist/{chunk-WEXMZMJH.js.map → chunk-3WVXAB3D.js.map} +1 -1
- package/dist/{chunk-OZBUPO4K.js → chunk-5W34X4EY.js} +263 -58
- package/dist/chunk-5W34X4EY.js.map +1 -0
- package/dist/{chunk-Z4L2GOAK.js → chunk-5ZWNCHZS.js} +4 -4
- package/dist/{chunk-Z4L2GOAK.js.map → chunk-5ZWNCHZS.js.map} +1 -1
- package/dist/{chunk-TEB5U6Y5.js → chunk-7NVATRLE.js} +4 -4
- package/dist/{chunk-TEB5U6Y5.js.map → chunk-7NVATRLE.js.map} +1 -1
- package/dist/{chunk-PUMQDV67.js → chunk-AXWMWYH5.js} +4 -4
- package/dist/{chunk-PUMQDV67.js.map → chunk-AXWMWYH5.js.map} +1 -1
- package/dist/{chunk-NKAH67JK.js → chunk-CS3CHGYC.js} +4 -4
- package/dist/{chunk-NKAH67JK.js.map → chunk-CS3CHGYC.js.map} +1 -1
- package/dist/{chunk-QJYRWEXD.js → chunk-CZV3WUW5.js} +35 -8
- package/dist/chunk-CZV3WUW5.js.map +1 -0
- package/dist/{chunk-PCFRBVKS.js → chunk-FCXSR7I5.js} +4 -4
- package/dist/{chunk-PCFRBVKS.js.map → chunk-FCXSR7I5.js.map} +1 -1
- package/dist/{chunk-NIFPRC7P.js → chunk-GVTBMJU6.js} +4 -4
- package/dist/{chunk-NIFPRC7P.js.map → chunk-GVTBMJU6.js.map} +1 -1
- package/dist/{chunk-E2I3YVKC.js → chunk-JLHVQWOV.js} +3 -3
- package/dist/{chunk-E2I3YVKC.js.map → chunk-JLHVQWOV.js.map} +1 -1
- package/dist/{chunk-2LSU3NFO.js → chunk-LQB42OSA.js} +4 -4
- package/dist/{chunk-2LSU3NFO.js.map → chunk-LQB42OSA.js.map} +1 -1
- package/dist/{chunk-VJD3Y7E5.js → chunk-MIDZWKIF.js} +4 -4
- package/dist/{chunk-VJD3Y7E5.js.map → chunk-MIDZWKIF.js.map} +1 -1
- package/dist/{chunk-LOD77NCD.js → chunk-PWYEW6NL.js} +4 -4
- package/dist/{chunk-LOD77NCD.js.map → chunk-PWYEW6NL.js.map} +1 -1
- package/dist/{chunk-HVDHT7DM.js → chunk-R4XXOGQH.js} +3 -3
- package/dist/{chunk-HVDHT7DM.js.map → chunk-R4XXOGQH.js.map} +1 -1
- package/dist/{chunk-7LLMILTM.js → chunk-RVMM4BHK.js} +4 -4
- package/dist/{chunk-7LLMILTM.js.map → chunk-RVMM4BHK.js.map} +1 -1
- package/dist/{chunk-NIXOY473.js → chunk-SWWJUOCY.js} +3 -3
- package/dist/{chunk-NIXOY473.js.map → chunk-SWWJUOCY.js.map} +1 -1
- package/dist/{chunk-EIBV76IB.js → chunk-VFWFT3OK.js} +4 -4
- package/dist/{chunk-EIBV76IB.js.map → chunk-VFWFT3OK.js.map} +1 -1
- package/dist/{chunk-2Q4EGZHJ.js → chunk-VMRUW4B4.js} +4 -4
- package/dist/{chunk-2Q4EGZHJ.js.map → chunk-VMRUW4B4.js.map} +1 -1
- package/dist/{chunk-GT63LSPJ.js → chunk-VOCUGTZB.js} +4 -4
- package/dist/{chunk-GT63LSPJ.js.map → chunk-VOCUGTZB.js.map} +1 -1
- package/dist/{chunk-N5VOPV64.js → chunk-Z5NL5D4J.js} +4 -4
- package/dist/{chunk-N5VOPV64.js.map → chunk-Z5NL5D4J.js.map} +1 -1
- package/dist/components-shared-whiteboard.cjs +33 -6
- package/dist/components-shared-whiteboard.cjs.map +1 -1
- package/dist/components-shared-whiteboard.js +3 -3
- package/dist/index.cjs +33 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +27 -27
- package/dist/mcp/index.d.cts +5 -5
- package/dist/mcp/index.d.ts +5 -5
- package/dist/mcp/stdio.d.cts +94 -0
- package/dist/mcp/stdio.d.ts +94 -0
- package/dist/mcp-stdio.cjs +120 -0
- package/dist/mcp-stdio.cjs.map +1 -0
- package/dist/mcp-stdio.js +117 -0
- package/dist/mcp-stdio.js.map +1 -0
- package/dist/mcp.cjs +33 -6
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.js +1 -1
- package/dist/presence/index.d.cts +1 -1
- package/dist/presence/index.d.ts +1 -1
- package/dist/relay-server/index.d.cts +110 -26
- package/dist/relay-server/index.d.ts +110 -26
- package/dist/relay-server-cli.cjs +374 -89
- package/dist/relay-server-cli.cjs.map +1 -1
- package/dist/relay-server-cli.js +120 -38
- package/dist/relay-server-cli.js.map +1 -1
- package/dist/relay-server.cjs +255 -51
- package/dist/relay-server.cjs.map +1 -1
- package/dist/relay-server.js +1 -1
- package/dist/{server-BJNF7pQe.d.cts → server-BIcA3ZtK.d.cts} +32 -3
- package/dist/{server-Dt97UxuD.d.ts → server-DnUyeavY.d.ts} +32 -3
- package/dist/sharing/index.d.cts +3 -3
- package/dist/sharing/index.d.ts +3 -3
- package/dist/sheets-adapter.d.cts +3 -3
- package/dist/sheets-adapter.d.ts +3 -3
- package/dist/{tool-host-BpEBqf5u.d.cts → tool-host-LVBgCN5m.d.cts} +1 -1
- package/dist/{tool-host-xY5F-eqG.d.ts → tool-host-Wo0pkY83.d.ts} +1 -1
- package/dist/{types-DSwsNTBG.d.ts → types-BxNRKSVd.d.ts} +1 -1
- package/dist/{types-C58ZXs4K.d.cts → types-C2DtnHIn.d.cts} +25 -1
- package/dist/{types-C58ZXs4K.d.ts → types-C2DtnHIn.d.ts} +25 -1
- package/dist/{types-C4NaIW6B.d.cts → types-EcElKOlk.d.cts} +1 -1
- package/dist/undo/index.d.cts +2 -2
- package/dist/undo/index.d.ts +2 -2
- package/dist/undo.cjs.map +1 -1
- package/dist/undo.js +3 -3
- package/docs/relay-protocol.md +41 -5
- package/docs/relay-server.md +102 -15
- package/package.json +19 -2
- package/dist/chunk-OZBUPO4K.js.map +0 -1
- package/dist/chunk-QJYRWEXD.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/server.ts","../src/presence/wrap-tool-with-activity.ts","../src/undo/undo-tools.ts","../src/bridges/charts.ts"],"names":["emitActivity","undoOne","redoOne","readHistory"],"mappings":";;;;;AAsLO,SAAS,UAAA,CAAW,MAAc,UAAA,EAAkC;AACzE,EAAA,OAAO;AAAA,IACL,SAAS,CAAC,EAAE,IAAA,EAAM,MAAA,EAAQ,MAAM,CAAA;AAAA,IAChC,GAAI,UAAA,KAAe,MAAA,GAAY,EAAE,iBAAA,EAAmB,UAAA,KAAe;AAAC,GACtE;AACF;AAEO,SAAS,YAAY,IAAA,EAA8B;AACxD,EAAA,OAAO,EAAE,OAAA,EAAS,CAAC,EAAE,IAAA,EAAM,QAAQ,IAAA,EAAM,CAAA,EAAG,OAAA,EAAS,IAAA,EAAK;AAC5D;;;AChJO,SAAS,oBAAA,CACd,SACA,OAAA,EAmBoB;AACpB,EAAA,OAAO,OAAO,IAAA,KAAS;AACrB,IAAA,MAAM,MAAA,GAAS,MAAM,OAAA,CAAQ,IAAI,CAAA;AACjC,IAAA,IAAI,MAAA,CAAO,SAAS,OAAO,MAAA;AAE3B,IAAA,IAAI,MAAA;AACJ,IAAA,IAAI,QAAQ,aAAA,EAAe;AACzB,MAAA,MAAA,GAAS,OAAA,CAAQ,cAAc,EAAE,QAAA,EAAU,QAAQ,QAAA,EAAU,IAAA,EAAM,QAAQ,CAAA;AAAA,IAC7E,CAAA,MAAO;AACL,MAAA,MAAA,GAAS,EAAE,IAAA,EAAM,OAAA,CAAQ,I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AA,GACF;AAEA,EAAA,GAAA;AAAA,IACE,mBAAA;AAAA,IACA,2FAAA;AAAA,IACA,EAAE,IAAA,EAAM,EAAE,WAAA,EAAa,oEAAmE,EAAE;AAAA,IAC5F,CAAC,MAAM,CAAA;AAAA,IACP,CAAC,IAAA,KAAS;AACR,MAAA,IAAI,CAAC,OAAA,CAAQ,UAAA,EAAY,OAAO,YAAY,kCAAkC,CAAA;AAC9E,MAAA,OAAA,CAAQ,UAAA,CAAW,KAAK,IAAI,CAAA;AAC5B,MAAA,OAAO,UAAA,CAAW,oBAAA,EAAsB,EAAG,CAAA;AAAA,IAC7C,CAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,CAAA,MAAA,EAAS,OAAA,CAAQ,EAAE,CAAA,CAAA;AAAA,IACvB,KAAA,EAAO,OAAA,CAAQ,KAAA,IAAS,OAAA,CAAQ,EAAA;AAAA,IAChC,SAAS,MAAM;AAAE,MAAA,KAAA,MAAW,CAAA,IAAK,WAAW,CAAA,EAAE;AAAA,IAAG;AAAA,GACnD;AACF","file":"bridges-charts.cjs","sourcesContent":["import {\n type CallToolResult,\n type JsonObject,\n type JsonRpcMessage,\n type JsonRpcRequest,\n type JsonRpcId,\n type RegisteredTool,\n type ServerCapabilities,\n type ServerInfo,\n type ToolDefinition,\n type ToolHandler,\n JSONRPC_INTERNAL_ERROR,\n JSONRPC_INVALID_PARAMS,\n JSONRPC_METHOD_NOT_FOUND,\n MCP_PROTOCOL_VERSION,\n} from \"./types\";\nimport { ToolRegistry } from \"./tool-host\";\n\nexport type McpServerOptions = {\n info: ServerInfo;\n /** Defaults to { tools: { listChanged: true } } */\n capabilities?: ServerCapabilities;\n /** Free-text instructions surfaced to clients during initialize. */\n instructions?: string;\n};\n\nexport type Transport = {\n /** Called by the server when it has a message to deliver to the client. */\n send: (message: JsonRpcMessage) => void;\n /** Called by the server when it's torn down so the transport can clean up. */\n close?: () => void;\n};\n\n/**\n * MicroMcpServer — protocol-level MCP server, transport-agnostic.\n *\n * Use it like:\n *\n * const server = new MicroMcpServer({ info: { name: \"session\", version: \"0.1\" } });\n * server.registerTool({ name: \"...\", inputSchema: { type: \"object\" } }, async (args) => ({...}));\n * const transport = new InProcessTransport();\n * server.attach(transport);\n * transport.deliver({ ... }); // client → server frames\n *\n * The same server can serve multiple transports (e.g. an in-process agent\n * AND a relayed external client) by attaching each one.\n */\nexport class MicroMcpServer extends ToolRegistry {\n private transports = new Set<Transport>();\n private notifyListChangedScheduled = false;\n\n readonly info: ServerInfo;\n readonly capabilities: ServerCapabilities;\n readonly instructions?: string;\n\n constructor(options: McpServerOptions) {\n super();\n this.info = options.info;\n this.capabilities = options.capabilities ?? { tools: { listChanged: true } };\n this.instructions = options.instructions;\n }\n\n attach(transport: Transport): () => void {\n this.transports.add(transport);\n return () => this.detach(transport);\n }\n\n detach(transport: Transport): void {\n if (this.transports.delete(transport)) {\n transport.close?.();\n }\n }\n\n unregisterTool(name: string): void {\n if (this.tools.delete(name)) {\n this.scheduleListChangedNotification();\n }\n }\n\n protected onToolsChanged(): void {\n this.scheduleListChangedNotification();\n }\n\n /**\n * Receive a JSON-RPC frame from a client (called by the transport).\n * The transport is responsible for sending the response back.\n */\n async receive(transport: Transport, message: JsonRpcMessage): Promise<void> {\n if (!(\"method\" in message)) return; // It's a response, not a request — ignore.\n\n const isNotification = !(\"id\" in message);\n if (isNotification) {\n // Notifications are fire-and-forget. We ignore unknown methods.\n return;\n }\n\n const request = message as JsonRpcRequest;\n try {\n const result = await this.handle(request, transport);\n transport.send({ jsonrpc: \"2.0\", id: request.id, result });\n } catch (err) {\n transport.send({\n jsonrpc: \"2.0\",\n id: request.id,\n error: this.toRpcError(err),\n });\n }\n }\n\n private async handle(request: JsonRpcRequest, transport: Transport): Promise<any> {\n const { method, params } = request;\n switch (method) {\n case \"initialize\":\n return {\n protocolVersion: MCP_PROTOCOL_VERSION,\n capabilities: this.capabilities,\n serverInfo: this.info,\n ...(this.instructions ? { instructions: this.instructions } : {}),\n };\n\n case \"tools/list\":\n return { tools: this.listTools() };\n\n case \"tools/call\": {\n const name = params?.name;\n const args = (params?.arguments ?? {}) as JsonObject;\n if (typeof name !== \"string\") {\n throw rpcError(JSONRPC_INVALID_PARAMS, \"tools/call requires `name`\");\n }\n const tool = this.tools.get(name);\n if (!tool) {\n throw rpcError(JSONRPC_METHOD_NOT_FOUND, this.missingToolMessage(name));\n }\n const result = await tool.handler(args, { transport });\n return result satisfies CallToolResult;\n }\n\n case \"ping\":\n return {};\n\n default:\n throw rpcError(JSONRPC_METHOD_NOT_FOUND, `Unsupported method: ${method}`);\n }\n }\n\n private scheduleListChangedNotification(): void {\n if (this.notifyListChangedScheduled) return;\n this.notifyListChangedScheduled = true;\n queueMicrotask(() => {\n this.notifyListChangedScheduled = false;\n this.broadcast({ jsonrpc: \"2.0\", method: \"notifications/tools/list_changed\" });\n });\n }\n\n /** Send an application notification to every client, or one attached transport. */\n notify(message: JsonRpcMessage, transport?: Transport): void {\n if (transport) transport.send(message);\n else this.broadcast(message);\n }\n\n private broadcast(message: JsonRpcMessage): void {\n for (const t of this.transports) t.send(message);\n }\n\n private toRpcError(err: unknown): { code: number; message: string; data?: any } {\n if (err && typeof err === \"object\" && \"code\" in err && \"message\" in err) {\n return err as any;\n }\n return {\n code: JSONRPC_INTERNAL_ERROR,\n message: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nexport function rpcError(code: number, message: string, data?: any) {\n return { code, message, ...(data !== undefined ? { data } : {}) };\n}\n\n/**\n * Helper to build a CallToolResult from a string or structured value.\n */\nexport function textResult(text: string, structured?: any): CallToolResult {\n return {\n content: [{ type: \"text\", text }],\n ...(structured !== undefined ? { structuredContent: structured } : {}),\n };\n}\n\nexport function errorResult(text: string): CallToolResult {\n return { content: [{ type: \"text\", text }], isError: true };\n}\n\n// Internal helper so the JsonRpcId import isn't dropped by tsup\ntype _KeepIdImport = JsonRpcId;\n","import type { CallToolResult } from \"../mcp/types\";\nimport { emitActivity } from \"./registry\";\nimport type { AgentTarget } from \"./types\";\n\nexport type ActivityAgent = { id: string; name?: string; color?: string };\n\nexport type ActivityResolverContext<TArgs = Record<string, unknown>> = {\n /** Tool name as registered. */\n toolName: string;\n /** Arguments the tool was called with. */\n args: TArgs;\n /** The CallToolResult the underlying handler produced. */\n result: CallToolResult;\n};\n\n/**\n * Resolves an `AgentTarget` for an executed tool. Bridges declare one of\n * these per registration so the wrapper knows which surface / element /\n * screen the activity belongs to.\n *\n * The resolver runs AFTER the tool handler so it can inspect the result\n * (e.g. read a newly-created item id from `structuredContent`).\n */\nexport type ActivityTargetResolver<TArgs = Record<string, unknown>> = (\n ctx: ActivityResolverContext<TArgs>,\n) => AgentTarget | null;\n\nexport type ToolHandler<TArgs = Record<string, unknown>> = (\n args: TArgs,\n) => Promise<CallToolResult> | CallToolResult;\n\n/**\n * wrapToolWithActivity — decorate a bridge tool handler so every successful\n * call emits an `AgentActivityEvent`. Returns a new handler with the same shape.\n *\n * Usage in a bridge:\n *\n * server.registerTool(\n * definition,\n * wrapToolWithActivity(\n * handler,\n * { agent, kind: \"whiteboard\", resolveTarget: ({ args }) => ({\n * kind: \"whiteboard\", elementId: args.id as string,\n * }) },\n * ),\n * );\n */\nexport function wrapToolWithActivity<TArgs = Record<string, unknown>>(\n handler: ToolHandler<TArgs>,\n options: {\n toolName: string;\n agent: ActivityAgent;\n /** Optional fancy-screens screen id this bridge is scoped to. */\n screenId?: string;\n /** Default target kind if the resolver returns one without `kind`. */\n kind: AgentTarget[\"kind\"];\n /** Per-call resolver. Return `null` to skip emitting (e.g. for read-only tools). */\n resolveTarget?: ActivityTargetResolver<TArgs>;\n /** Optional ttl override. */\n ttlMs?: number;\n /**\n * Build the `meta` broadcast to all relay peers. Defaults to the tool's full\n * `structuredContent`. Override to REDACT sensitive fields before fan-out —\n * e.g. the terminal bridge strips raw command/keystroke bytes so a command\n * line (or its secrets) is never broadcast verbatim to every peer.\n */\n buildMeta?: (result: CallToolResult) => Record<string, unknown> | undefined;\n },\n): ToolHandler<TArgs> {\n return async (args) => {\n const result = await handler(args);\n if (result.isError) return result;\n\n let target: AgentTarget | null;\n if (options.resolveTarget) {\n target = options.resolveTarget({ toolName: options.toolName, args, result });\n } else {\n target = { kind: options.kind, screenId: options.screenId };\n }\n if (!target) return result;\n\n emitActivity({\n agentId: options.agent.id,\n agentName: options.agent.name,\n agentColor: options.agent.color,\n target: { ...target, kind: target.kind ?? options.kind, screenId: target.screenId ?? options.screenId },\n action: options.toolName,\n timestamp: Date.now(),\n meta: options.buildMeta ? options.buildMeta(result) : extractMeta(result),\n ttlMs: options.ttlMs,\n });\n return result;\n };\n}\n\nfunction extractMeta(result: CallToolResult): Record<string, unknown> | undefined {\n const sc = result.structuredContent;\n if (sc && typeof sc === \"object\" && !Array.isArray(sc)) {\n return sc as Record<string, unknown>;\n }\n return undefined;\n}\n","import { textResult, errorResult } from \"../mcp/server\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport { readHistory, redoOne, undoOne } from \"./undo-stack\";\n\nexport type UndoToolsOptions = {\n /** Default agent id when the caller doesn't pass one. */\n defaultAgentId?: string;\n};\n\n/**\n * Idempotent tracker so multiple bridges on the same server only register\n * agent_undo / agent_redo / agent_history once.\n */\nconst installedHosts = new WeakSet<ToolHost>();\n\n/**\n * ensureUndoToolsRegistered — bridges call this on construction. Safe to\n * call repeatedly with the same server; subsequent calls are no-ops.\n */\nexport function ensureUndoToolsRegistered(host: ToolHost, options: UndoToolsOptions = {}): void {\n if (installedHosts.has(host)) return;\n installedHosts.add(host);\n registerUndoTools(host, options);\n}\n\n/**\n * registerUndoTools — add agent_undo / agent_redo / agent_history to the\n * server. Returns a disposer that unregisters all three.\n */\nexport function registerUndoTools(host: ToolHost, options: UndoToolsOptions = {}): () => void {\n const defaultAgent = options.defaultAgentId ?? \"agent\";\n const disposers: Array<() => void> = [];\n const agentOf = (args: any): string =>\n typeof args?.agentId === \"string\" ? args.agentId : defaultAgent;\n\n disposers.push(\n host.registerTool(\n {\n name: \"agent_undo\",\n description: \"Undo the most recent action on the agent's stack. Optional agentId targets a specific agent.\",\n inputSchema: {\n type: \"object\",\n properties: { agentId: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n async (args) => {\n const entry = await undoOne(agentOf(args));\n if (!entry) return errorResult(\"Nothing to undo.\");\n return textResult(`Undid: ${entry.label}`, { entry: serialize(entry) });\n },\n ),\n );\n\n disposers.push(\n host.registerTool(\n {\n name: \"agent_redo\",\n description: \"Redo the most recently undone action.\",\n inputSchema: {\n type: \"object\",\n properties: { agentId: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n async (args) => {\n const entry = await redoOne(agentOf(args));\n if (!entry) return errorResult(\"Nothing to redo.\");\n return textResult(`Redid: ${entry.label}`, { entry: serialize(entry) });\n },\n ),\n );\n\n disposers.push(\n host.registerTool(\n {\n name: \"agent_history\",\n description: \"List the agent's undo stack (oldest first). Useful for understanding what's reversible.\",\n inputSchema: {\n type: \"object\",\n properties: { agentId: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n async (args) => {\n const history = readHistory(agentOf(args)).map(serialize);\n const text = history.map((e) => `${new Date(e.timestamp).toISOString()} ${e.bridgeId} ${e.action}: ${e.label}`).join(\"\\n\");\n return textResult(text || \"(empty)\", history);\n },\n ),\n );\n\n return () => disposers.forEach((d) => d());\n}\n\nfunction serialize(entry: import(\"./undo-stack\").UndoEntry) {\n return {\n timestamp: entry.timestamp,\n bridgeId: entry.bridgeId,\n action: entry.action,\n label: entry.label,\n };\n}\n","import { textResult, errorResult } from \"../mcp/server\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport type { JsonObject } from \"../mcp/types\";\nimport type { Bridge } from \"./types\";\nimport { wrapToolWithActivity } from \"../presence/wrap-tool-with-activity\";\nimport { ensureUndoToolsRegistered } from \"../undo/undo-tools\";\nimport type { AgentTarget } from \"../presence/types\";\n\n/**\n * Adapter wires a single fancy-echarts chart to the bridge. Charts are\n * already prop-driven, so the adapter just exposes the data + option\n * setters and a way to read what's currently rendered.\n */\nexport type ChartsBridgeAdapter = {\n /** Stable id for this chart instance. */\n id: string;\n title?: string;\n screenId?: string;\n /** Read the current ECharts option object the chart is rendering. */\n getOption: () => Record<string, unknown>;\n /** Replace the entire option. */\n setOption: (option: Record<string, unknown>) => void;\n /** Convenience: shallow-merge a partial option update. */\n updateOption?: (partial: Record<string, unknown>) => void;\n /** Read just the data series (subset of option for quick agent reads). */\n getData?: () => unknown;\n /** Update only the data, leaving axes/colors/etc. alone. */\n updateData?: (data: unknown) => void;\n};\n\nexport type ChartsBridgeOptions = {\n adapter: ChartsBridgeAdapter;\n agent?: { id: string; name?: string; color?: string };\n};\n\nconst DEFAULT_AGENT = { id: \"agent\", name: \"Agent\", color: \"#a855f7\" };\n\n/**\n * registerChartsBridge — schema-aware MCP access to a single chart.\n */\nexport function registerChartsBridge(\n host: ToolHost,\n options: ChartsBridgeOptions,\n): Bridge {\n const { adapter } = options;\n const agent = { ...DEFAULT_AGENT, ...(options.agent ?? {}) };\n const disposers: Array<() => void> = [];\n\n // agent_undo / agent_redo / agent_history are registered whenever any bridge\n // mounts, so undo availability doesn't hinge on which bridges are co-present.\n ensureUndoToolsRegistered(host, { defaultAgentId: agent.id });\n\n const target: AgentTarget = {\n kind: \"chart\",\n screenId: adapter.screenId,\n elementId: adapter.id,\n label: adapter.title ?? adapter.id,\n };\n\n const reg = (\n name: string,\n description: string,\n properties: Record<string, unknown>,\n required: string[],\n handler: (args: JsonObject) => Promise<any> | any,\n isMutation: boolean,\n ) => {\n const wrapped = async (args: JsonObject) => {\n try { return await handler(args); }\n catch (e) { return errorResult(e instanceof Error ? e.message : String(e)); }\n };\n const final = isMutation\n ? wrapToolWithActivity(wrapped, {\n toolName: name, agent, kind: \"chart\", screenId: adapter.screenId,\n resolveTarget: () => target,\n })\n : wrapped;\n disposers.push(\n host.registerTool(\n { name, description, inputSchema: { type: \"object\", properties: properties as any, required, additionalProperties: false } },\n final as any,\n ),\n );\n };\n\n reg(\n \"chart_describe\",\n `Describe the chart \"${adapter.id}\" — series count, type guesses, axis info.`,\n {},\n [],\n () => {\n const opt = adapter.getOption();\n const series = Array.isArray(opt.series) ? opt.series : [];\n const summary = {\n id: adapter.id,\n title: adapter.title,\n seriesCount: series.length,\n seriesTypes: series.map((s: any) => s?.type ?? \"unknown\"),\n hasXAxis: !!opt.xAxis,\n hasYAxis: !!opt.yAxis,\n };\n return textResult(JSON.stringify(summary), summary);\n },\n false,\n );\n\n reg(\n \"chart_get_option\",\n \"Read the full ECharts option object the chart is rendering.\",\n {},\n [],\n () => {\n const opt = adapter.getOption();\n return textResult(JSON.stringify(opt, null, 2), opt);\n },\n false,\n );\n\n reg(\n \"chart_set_option\",\n \"Replace the entire ECharts option. Use chart_update_option for partial updates.\",\n { option: { type: \"object\" } },\n [\"option\"],\n (args) => {\n const opt = (args.option && typeof args.option === \"object\") ? args.option as Record<string, unknown> : {};\n adapter.setOption(opt);\n return textResult(\"Replaced chart option\", { });\n },\n true,\n );\n\n reg(\n \"chart_update_option\",\n \"Shallow-merge a partial option update — only the keys you provide change.\",\n { partial: { type: \"object\" } },\n [\"partial\"],\n (args) => {\n const partial = (args.partial && typeof args.partial === \"object\") ? args.partial as Record<string, unknown> : {};\n if (adapter.updateOption) {\n adapter.updateOption(partial);\n } else {\n adapter.setOption({ ...adapter.getOption(), ...partial });\n }\n return textResult(\"Merged chart option\", { keys: Object.keys(partial) });\n },\n true,\n );\n\n reg(\n \"chart_update_data\",\n \"Update only the data (typically the `series` field). Leaves layout / axes / colors alone.\",\n { data: { description: \"New series array (or whatever shape the host's adapter expects).\" } },\n [\"data\"],\n (args) => {\n if (!adapter.updateData) return errorResult(\"Host did not provide updateData.\");\n adapter.updateData(args.data);\n return textResult(\"Updated chart data\", { });\n },\n true,\n );\n\n return {\n id: `chart:${adapter.id}`,\n title: adapter.title ?? adapter.id,\n dispose: () => { for (const d of disposers) d(); },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/mcp/server.ts","../src/presence/wrap-tool-with-activity.ts","../src/undo/undo-tools.ts","../src/bridges/charts.ts"],"names":["emitActivity","undoOne","redoOne","readHistory"],"mappings":";;;;;AAoOO,SAAS,UAAA,CAAW,MAAc,UAAA,EAAkC;AACzE,EAAA,OAAO;AAAA,IACL,SAAS,CAAC,EAAE,IAAA,EAAM,MAAA,EAAQ,MAAM,CAAA;AAAA,IAChC,GAAI,UAAA,KAAe,MAAA,GAAY,EAAE,iBAAA,EAAmB,UAAA,KAAe;AAAC,GACtE;AACF;AAEO,SAAS,YAAY,IAAA,EAA8B;AACxD,EAAA,OAAO,EAAE,OAAA,EAAS,CAAC,EAAE,IAAA,EAAM,QAAQ,IAAA,EAAM,CAAA,EAAG,OAAA,EAAS,IAAA,EAAK;AAC5D;;;AC9LO,SAAS,oBAAA,CACd,SACA,OAAA,EAmBoB;AACpB,EAAA,OAAO,OAAO,IAAA,KAAS;AACrB,IAAA,MAAM,MAAA,GAAS,MAAM,OAAA,CAAQ,IAAI,CAAA;AACjC,IAAA,IAAI,MAAA,CAAO,SAAS,OAAO,MAAA;AAE3B,IAAA,IAAI,MAAA;AACJ,IAAA,IAAI,QAAQ,aAAA,EAAe;AACzB,MAAA,MAAA,GAAS,OAAA,CAAQ,cAAc,EAAE,QAAA,EAAU,QAAQ,QAAA,EAAU,IAAA,EAAM,QAAQ,CAAA;AAAA,IAC7E,CAAA,MAAO;AACL,MAAA,MAAA,GAAS,EAAE,IAAA,EAAM,OAAA,CAAQ,IAAA,EAAM,QAAA,EAAU,QAAQ,QAAA,EAAS;AAAA,IAC5D;AACA,IAAA,IAAI,CAAC,QAAQ,OAAO,MAAA;AAEpB,IAAAA,4BAAA,CAAa;AAAA,MACX,OAAA,EAAS,QAAQ,KAAA,CAAM,EAAA;AAAA,MACvB,SAAA,EAAW,QAAQ,KAAA,CAAM,IAAA;AAAA,MACzB,UAAA,EAAY,QAAQ,KAAA,CAAM,KAAA;AAAA,MAC1B,MAAA,E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AAW,KAAK,IAAI,CAAA;AAC5B,MAAA,OAAO,UAAA,CAAW,oBAAA,EAAsB,EAAG,CAAA;AAAA,IAC7C,CAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,CAAA,MAAA,EAAS,OAAA,CAAQ,EAAE,CAAA,CAAA;AAAA,IACvB,KAAA,EAAO,OAAA,CAAQ,KAAA,IAAS,OAAA,CAAQ,EAAA;AAAA,IAChC,SAAS,MAAM;AAAE,MAAA,KAAA,MAAW,CAAA,IAAK,WAAW,CAAA,EAAE;AAAA,IAAG;AAAA,GACnD;AACF","file":"bridges-charts.cjs","sourcesContent":["import {\n type CallToolResult,\n type JsonObject,\n type JsonRpcMessage,\n type JsonRpcRequest,\n type JsonRpcId,\n type RegisteredTool,\n type ServerCapabilities,\n type ServerInfo,\n type ToolDefinition,\n type ToolHandler,\n JSONRPC_INTERNAL_ERROR,\n JSONRPC_INVALID_PARAMS,\n JSONRPC_METHOD_NOT_FOUND,\n MCP_PROTOCOL_VERSION,\n} from \"./types\";\nimport { ToolRegistry } from \"./tool-host\";\n\nexport type McpServerOptions = {\n info: ServerInfo;\n /** Defaults to { tools: { listChanged: true } } */\n capabilities?: ServerCapabilities;\n /** Free-text instructions surfaced to clients during initialize. */\n instructions?: string;\n /**\n * The protocol revisions this server speaks, NEWEST FIRST.\n *\n * `initialize` echoes the client's requested revision when it is in this\n * list, and answers the first entry otherwise — the spec's rule, which leaves\n * the client to decide whether it can live with the answer.\n *\n * Defaults to `[MCP_PROTOCOL_VERSION]`: one revision, answered whatever the\n * client asks, which is exactly what this server did before the option\n * existed. Only list a revision the tools you register are correct under.\n */\n protocolVersions?: readonly string[];\n};\n\nexport type Transport = {\n /** Called by the server when it has a message to deliver to the client. */\n send: (message: JsonRpcMessage) => void;\n /** Called by the server when it's torn down so the transport can clean up. */\n close?: () => void;\n};\n\n/**\n * MicroMcpServer — protocol-level MCP server, transport-agnostic.\n *\n * Use it like:\n *\n * const server = new MicroMcpServer({ info: { name: \"session\", version: \"0.1\" } });\n * server.registerTool({ name: \"...\", inputSchema: { type: \"object\" } }, async (args) => ({...}));\n * const transport = new InProcessTransport();\n * server.attach(transport);\n * transport.deliver({ ... }); // client → server frames\n *\n * The same server can serve multiple transports (e.g. an in-process agent\n * AND a relayed external client) by attaching each one.\n */\nexport class MicroMcpServer extends ToolRegistry {\n private transports = new Set<Transport>();\n /**\n * Transports owed a `tools/list_changed` at the end of this tick. Empty when\n * none is scheduled. See {@link scheduleListChangedNotification}.\n */\n private listChangedOwed = new Set<Transport>();\n\n readonly info: ServerInfo;\n readonly capabilities: ServerCapabilities;\n readonly instructions?: string;\n readonly protocolVersions: readonly string[];\n\n constructor(options: McpServerOptions) {\n super();\n this.info = options.info;\n this.capabilities = options.capabilities ?? { tools: { listChanged: true } };\n this.instructions = options.instructions;\n if (options.protocolVersions && options.protocolVersions.length === 0) {\n // No answer exists for a client's initialize. Fail here, next to the\n // mistake, rather than in a handshake nobody is watching.\n throw new Error(\"MicroMcpServer: protocolVersions is empty — a server must speak at least one protocol revision.\");\n }\n this.protocolVersions = options.protocolVersions ? [...options.protocolVersions] : [MCP_PROTOCOL_VERSION];\n }\n\n attach(transport: Transport): () => void {\n this.transports.add(transport);\n return () => this.detach(transport);\n }\n\n detach(transport: Transport): void {\n if (this.transports.delete(transport)) {\n transport.close?.();\n }\n }\n\n unregisterTool(name: string): void {\n if (this.tools.delete(name)) {\n this.scheduleListChangedNotification();\n }\n }\n\n protected onToolsChanged(): void {\n this.scheduleListChangedNotification();\n }\n\n /**\n * Receive a JSON-RPC frame from a client (called by the transport).\n * The transport is responsible for sending the response back.\n */\n async receive(transport: Transport, message: JsonRpcMessage): Promise<void> {\n if (!(\"method\" in message)) return; // It's a response, not a request — ignore.\n\n const isNotification = !(\"id\" in message);\n if (isNotification) {\n // Notifications are fire-and-forget. We ignore unknown methods.\n return;\n }\n\n const request = message as JsonRpcRequest;\n try {\n const result = await this.handle(request, transport);\n transport.send({ jsonrpc: \"2.0\", id: request.id, result });\n } catch (err) {\n transport.send({\n jsonrpc: \"2.0\",\n id: request.id,\n error: this.toRpcError(err),\n });\n }\n }\n\n private async handle(request: JsonRpcRequest, transport: Transport): Promise<any> {\n const { method, params } = request;\n switch (method) {\n case \"initialize\":\n return {\n protocolVersion: this.negotiate(params?.protocolVersion),\n capabilities: this.capabilities,\n serverInfo: this.info,\n ...(this.instructions ? { instructions: this.instructions } : {}),\n };\n\n case \"tools/list\":\n return { tools: this.listTools() };\n\n case \"tools/call\": {\n const name = params?.name;\n const args = (params?.arguments ?? {}) as JsonObject;\n if (typeof name !== \"string\") {\n throw rpcError(JSONRPC_INVALID_PARAMS, \"tools/call requires `name`\");\n }\n const tool = this.tools.get(name);\n if (!tool) {\n throw rpcError(JSONRPC_METHOD_NOT_FOUND, this.missingToolMessage(name));\n }\n const result = await tool.handler(args, { transport });\n return result satisfies CallToolResult;\n }\n\n case \"ping\":\n return {};\n\n default:\n throw rpcError(JSONRPC_METHOD_NOT_FOUND, `Unsupported method: ${method}`);\n }\n }\n\n /** The revision to answer `initialize` with: the one asked for if spoken, else the newest. */\n private negotiate(requested: unknown): string {\n return typeof requested === \"string\" && this.protocolVersions.includes(requested)\n ? requested\n : this.protocolVersions[0];\n }\n\n /**\n * Tell the transports that SAW the old tool list that it changed.\n *\n * Changes in one tick coalesce into one notification. The recipients are the\n * transports attached at the moment of a change, not at the moment the\n * notification goes out: a transport attached afterwards never had the old\n * list, so \"your list is stale\" is noise to it — and on stdio, where a host\n * builds the server and attaches stdin/stdout in the same tick, it was the\n * first frame a client received, before it had even sent `initialize`.\n */\n private scheduleListChangedNotification(): void {\n if (this.transports.size === 0) return;\n const scheduled = this.listChangedOwed.size > 0;\n for (const t of this.transports) this.listChangedOwed.add(t);\n if (scheduled) return;\n queueMicrotask(() => {\n const owed = this.listChangedOwed;\n this.listChangedOwed = new Set();\n for (const t of owed) {\n // Detached since the change: it is not listening any more.\n if (this.transports.has(t)) t.send({ jsonrpc: \"2.0\", method: \"notifications/tools/list_changed\" });\n }\n });\n }\n\n /** Send an application notification to every client, or one attached transport. */\n notify(message: JsonRpcMessage, transport?: Transport): void {\n if (transport) transport.send(message);\n else this.broadcast(message);\n }\n\n private broadcast(message: JsonRpcMessage): void {\n for (const t of this.transports) t.send(message);\n }\n\n private toRpcError(err: unknown): { code: number; message: string; data?: any } {\n if (err && typeof err === \"object\" && \"code\" in err && \"message\" in err) {\n return err as any;\n }\n return {\n code: JSONRPC_INTERNAL_ERROR,\n message: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nexport function rpcError(code: number, message: string, data?: any) {\n return { code, message, ...(data !== undefined ? { data } : {}) };\n}\n\n/**\n * Helper to build a CallToolResult from a string or structured value.\n */\nexport function textResult(text: string, structured?: any): CallToolResult {\n return {\n content: [{ type: \"text\", text }],\n ...(structured !== undefined ? { structuredContent: structured } : {}),\n };\n}\n\nexport function errorResult(text: string): CallToolResult {\n return { content: [{ type: \"text\", text }], isError: true };\n}\n\n// Internal helper so the JsonRpcId import isn't dropped by tsup\ntype _KeepIdImport = JsonRpcId;\n","import type { CallToolResult } from \"../mcp/types\";\nimport { emitActivity } from \"./registry\";\nimport type { AgentTarget } from \"./types\";\n\nexport type ActivityAgent = { id: string; name?: string; color?: string };\n\nexport type ActivityResolverContext<TArgs = Record<string, unknown>> = {\n /** Tool name as registered. */\n toolName: string;\n /** Arguments the tool was called with. */\n args: TArgs;\n /** The CallToolResult the underlying handler produced. */\n result: CallToolResult;\n};\n\n/**\n * Resolves an `AgentTarget` for an executed tool. Bridges declare one of\n * these per registration so the wrapper knows which surface / element /\n * screen the activity belongs to.\n *\n * The resolver runs AFTER the tool handler so it can inspect the result\n * (e.g. read a newly-created item id from `structuredContent`).\n */\nexport type ActivityTargetResolver<TArgs = Record<string, unknown>> = (\n ctx: ActivityResolverContext<TArgs>,\n) => AgentTarget | null;\n\nexport type ToolHandler<TArgs = Record<string, unknown>> = (\n args: TArgs,\n) => Promise<CallToolResult> | CallToolResult;\n\n/**\n * wrapToolWithActivity — decorate a bridge tool handler so every successful\n * call emits an `AgentActivityEvent`. Returns a new handler with the same shape.\n *\n * Usage in a bridge:\n *\n * server.registerTool(\n * definition,\n * wrapToolWithActivity(\n * handler,\n * { agent, kind: \"whiteboard\", resolveTarget: ({ args }) => ({\n * kind: \"whiteboard\", elementId: args.id as string,\n * }) },\n * ),\n * );\n */\nexport function wrapToolWithActivity<TArgs = Record<string, unknown>>(\n handler: ToolHandler<TArgs>,\n options: {\n toolName: string;\n agent: ActivityAgent;\n /** Optional fancy-screens screen id this bridge is scoped to. */\n screenId?: string;\n /** Default target kind if the resolver returns one without `kind`. */\n kind: AgentTarget[\"kind\"];\n /** Per-call resolver. Return `null` to skip emitting (e.g. for read-only tools). */\n resolveTarget?: ActivityTargetResolver<TArgs>;\n /** Optional ttl override. */\n ttlMs?: number;\n /**\n * Build the `meta` broadcast to all relay peers. Defaults to the tool's full\n * `structuredContent`. Override to REDACT sensitive fields before fan-out —\n * e.g. the terminal bridge strips raw command/keystroke bytes so a command\n * line (or its secrets) is never broadcast verbatim to every peer.\n */\n buildMeta?: (result: CallToolResult) => Record<string, unknown> | undefined;\n },\n): ToolHandler<TArgs> {\n return async (args) => {\n const result = await handler(args);\n if (result.isError) return result;\n\n let target: AgentTarget | null;\n if (options.resolveTarget) {\n target = options.resolveTarget({ toolName: options.toolName, args, result });\n } else {\n target = { kind: options.kind, screenId: options.screenId };\n }\n if (!target) return result;\n\n emitActivity({\n agentId: options.agent.id,\n agentName: options.agent.name,\n agentColor: options.agent.color,\n target: { ...target, kind: target.kind ?? options.kind, screenId: target.screenId ?? options.screenId },\n action: options.toolName,\n timestamp: Date.now(),\n meta: options.buildMeta ? options.buildMeta(result) : extractMeta(result),\n ttlMs: options.ttlMs,\n });\n return result;\n };\n}\n\nfunction extractMeta(result: CallToolResult): Record<string, unknown> | undefined {\n const sc = result.structuredContent;\n if (sc && typeof sc === \"object\" && !Array.isArray(sc)) {\n return sc as Record<string, unknown>;\n }\n return undefined;\n}\n","import { textResult, errorResult } from \"../mcp/server\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport { readHistory, redoOne, undoOne } from \"./undo-stack\";\n\nexport type UndoToolsOptions = {\n /** Default agent id when the caller doesn't pass one. */\n defaultAgentId?: string;\n};\n\n/**\n * Idempotent tracker so multiple bridges on the same server only register\n * agent_undo / agent_redo / agent_history once.\n */\nconst installedHosts = new WeakSet<ToolHost>();\n\n/**\n * ensureUndoToolsRegistered — bridges call this on construction. Safe to\n * call repeatedly with the same server; subsequent calls are no-ops.\n */\nexport function ensureUndoToolsRegistered(host: ToolHost, options: UndoToolsOptions = {}): void {\n if (installedHosts.has(host)) return;\n installedHosts.add(host);\n registerUndoTools(host, options);\n}\n\n/**\n * registerUndoTools — add agent_undo / agent_redo / agent_history to the\n * server. Returns a disposer that unregisters all three.\n */\nexport function registerUndoTools(host: ToolHost, options: UndoToolsOptions = {}): () => void {\n const defaultAgent = options.defaultAgentId ?? \"agent\";\n const disposers: Array<() => void> = [];\n const agentOf = (args: any): string =>\n typeof args?.agentId === \"string\" ? args.agentId : defaultAgent;\n\n disposers.push(\n host.registerTool(\n {\n name: \"agent_undo\",\n description: \"Undo the most recent action on the agent's stack. Optional agentId targets a specific agent.\",\n inputSchema: {\n type: \"object\",\n properties: { agentId: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n async (args) => {\n const entry = await undoOne(agentOf(args));\n if (!entry) return errorResult(\"Nothing to undo.\");\n return textResult(`Undid: ${entry.label}`, { entry: serialize(entry) });\n },\n ),\n );\n\n disposers.push(\n host.registerTool(\n {\n name: \"agent_redo\",\n description: \"Redo the most recently undone action.\",\n inputSchema: {\n type: \"object\",\n properties: { agentId: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n async (args) => {\n const entry = await redoOne(agentOf(args));\n if (!entry) return errorResult(\"Nothing to redo.\");\n return textResult(`Redid: ${entry.label}`, { entry: serialize(entry) });\n },\n ),\n );\n\n disposers.push(\n host.registerTool(\n {\n name: \"agent_history\",\n description: \"List the agent's undo stack (oldest first). Useful for understanding what's reversible.\",\n inputSchema: {\n type: \"object\",\n properties: { agentId: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n async (args) => {\n const history = readHistory(agentOf(args)).map(serialize);\n const text = history.map((e) => `${new Date(e.timestamp).toISOString()} ${e.bridgeId} ${e.action}: ${e.label}`).join(\"\\n\");\n return textResult(text || \"(empty)\", history);\n },\n ),\n );\n\n return () => disposers.forEach((d) => d());\n}\n\nfunction serialize(entry: import(\"./undo-stack\").UndoEntry) {\n return {\n timestamp: entry.timestamp,\n bridgeId: entry.bridgeId,\n action: entry.action,\n label: entry.label,\n };\n}\n","import { textResult, errorResult } from \"../mcp/server\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport type { JsonObject } from \"../mcp/types\";\nimport type { Bridge } from \"./types\";\nimport { wrapToolWithActivity } from \"../presence/wrap-tool-with-activity\";\nimport { ensureUndoToolsRegistered } from \"../undo/undo-tools\";\nimport type { AgentTarget } from \"../presence/types\";\n\n/**\n * Adapter wires a single fancy-echarts chart to the bridge. Charts are\n * already prop-driven, so the adapter just exposes the data + option\n * setters and a way to read what's currently rendered.\n */\nexport type ChartsBridgeAdapter = {\n /** Stable id for this chart instance. */\n id: string;\n title?: string;\n screenId?: string;\n /** Read the current ECharts option object the chart is rendering. */\n getOption: () => Record<string, unknown>;\n /** Replace the entire option. */\n setOption: (option: Record<string, unknown>) => void;\n /** Convenience: shallow-merge a partial option update. */\n updateOption?: (partial: Record<string, unknown>) => void;\n /** Read just the data series (subset of option for quick agent reads). */\n getData?: () => unknown;\n /** Update only the data, leaving axes/colors/etc. alone. */\n updateData?: (data: unknown) => void;\n};\n\nexport type ChartsBridgeOptions = {\n adapter: ChartsBridgeAdapter;\n agent?: { id: string; name?: string; color?: string };\n};\n\nconst DEFAULT_AGENT = { id: \"agent\", name: \"Agent\", color: \"#a855f7\" };\n\n/**\n * registerChartsBridge — schema-aware MCP access to a single chart.\n */\nexport function registerChartsBridge(\n host: ToolHost,\n options: ChartsBridgeOptions,\n): Bridge {\n const { adapter } = options;\n const agent = { ...DEFAULT_AGENT, ...(options.agent ?? {}) };\n const disposers: Array<() => void> = [];\n\n // agent_undo / agent_redo / agent_history are registered whenever any bridge\n // mounts, so undo availability doesn't hinge on which bridges are co-present.\n ensureUndoToolsRegistered(host, { defaultAgentId: agent.id });\n\n const target: AgentTarget = {\n kind: \"chart\",\n screenId: adapter.screenId,\n elementId: adapter.id,\n label: adapter.title ?? adapter.id,\n };\n\n const reg = (\n name: string,\n description: string,\n properties: Record<string, unknown>,\n required: string[],\n handler: (args: JsonObject) => Promise<any> | any,\n isMutation: boolean,\n ) => {\n const wrapped = async (args: JsonObject) => {\n try { return await handler(args); }\n catch (e) { return errorResult(e instanceof Error ? e.message : String(e)); }\n };\n const final = isMutation\n ? wrapToolWithActivity(wrapped, {\n toolName: name, agent, kind: \"chart\", screenId: adapter.screenId,\n resolveTarget: () => target,\n })\n : wrapped;\n disposers.push(\n host.registerTool(\n { name, description, inputSchema: { type: \"object\", properties: properties as any, required, additionalProperties: false } },\n final as any,\n ),\n );\n };\n\n reg(\n \"chart_describe\",\n `Describe the chart \"${adapter.id}\" — series count, type guesses, axis info.`,\n {},\n [],\n () => {\n const opt = adapter.getOption();\n const series = Array.isArray(opt.series) ? opt.series : [];\n const summary = {\n id: adapter.id,\n title: adapter.title,\n seriesCount: series.length,\n seriesTypes: series.map((s: any) => s?.type ?? \"unknown\"),\n hasXAxis: !!opt.xAxis,\n hasYAxis: !!opt.yAxis,\n };\n return textResult(JSON.stringify(summary), summary);\n },\n false,\n );\n\n reg(\n \"chart_get_option\",\n \"Read the full ECharts option object the chart is rendering.\",\n {},\n [],\n () => {\n const opt = adapter.getOption();\n return textResult(JSON.stringify(opt, null, 2), opt);\n },\n false,\n );\n\n reg(\n \"chart_set_option\",\n \"Replace the entire ECharts option. Use chart_update_option for partial updates.\",\n { option: { type: \"object\" } },\n [\"option\"],\n (args) => {\n const opt = (args.option && typeof args.option === \"object\") ? args.option as Record<string, unknown> : {};\n adapter.setOption(opt);\n return textResult(\"Replaced chart option\", { });\n },\n true,\n );\n\n reg(\n \"chart_update_option\",\n \"Shallow-merge a partial option update — only the keys you provide change.\",\n { partial: { type: \"object\" } },\n [\"partial\"],\n (args) => {\n const partial = (args.partial && typeof args.partial === \"object\") ? args.partial as Record<string, unknown> : {};\n if (adapter.updateOption) {\n adapter.updateOption(partial);\n } else {\n adapter.setOption({ ...adapter.getOption(), ...partial });\n }\n return textResult(\"Merged chart option\", { keys: Object.keys(partial) });\n },\n true,\n );\n\n reg(\n \"chart_update_data\",\n \"Update only the data (typically the `series` field). Leaves layout / axes / colors alone.\",\n { data: { description: \"New series array (or whatever shape the host's adapter expects).\" } },\n [\"data\"],\n (args) => {\n if (!adapter.updateData) return errorResult(\"Host did not provide updateData.\");\n adapter.updateData(args.data);\n return textResult(\"Updated chart data\", { });\n },\n true,\n );\n\n return {\n id: `chart:${adapter.id}`,\n title: adapter.title ?? adapter.id,\n dispose: () => { for (const d of disposers) d(); },\n };\n}\n"]}
|
package/dist/bridges-charts.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { registerChartsBridge } from './chunk-
|
|
2
|
-
import './chunk-
|
|
1
|
+
export { registerChartsBridge } from './chunk-36MKPTVD.js';
|
|
2
|
+
import './chunk-R4XXOGQH.js';
|
|
3
3
|
import './chunk-2VENWGLZ.js';
|
|
4
4
|
import './chunk-C3TYI5TJ.js';
|
|
5
|
-
import './chunk-
|
|
5
|
+
import './chunk-CZV3WUW5.js';
|
|
6
6
|
//# sourceMappingURL=bridges-charts.js.map
|
|
7
7
|
//# sourceMappingURL=bridges-charts.js.map
|
package/dist/bridges-cms.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/server.ts","../src/presence/wrap-tool-with-activity.ts","../src/undo/undo-tools.ts","../src/bridges/doc.ts","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C;AAAA,MACA;AAAA,QACE,IAAA,EAAM,YAAA;AAAA,QACN,WAAA,EAAa,2DAAA;AAAA,QACb,YAAY,EAAE,EAAA,EAAI,EAAE,IAAA,EAAM,UAAS,EAAG,MAAA,EAAQ,EAAE,IAAA,EAAM,UAAU,IAAA,EAAM,CAAC,QAAQ,OAAA,EAAS,MAAM,GAAE,EAAE;AAAA,QAClG,QAAA,EAAU,CAAC,IAAI,CAAA;AAAA,QACf,KAAA,EAAO,CAAC,IAAA,EAAM,IAAA,KAAS;AACrB,UAAA,MAAM,EAAA,GAAK,MAAA,CAAO,IAAA,CAAK,EAAE,CAAA;AACzB,UAAA,IAAI,CAAC,IAAA,CAAK,KAAA,CAAM,EAAE,CAAA,SAAU,EAAE,KAAA,EAAO,CAAA,QAAA,EAAW,EAAE,CAAA,CAAA,EAAG;AACrD,UAAA,OAAO,EAAE,CAAA,EAAG,YAAA,EAAc,EAAA,EAAI,MAAA,EAAQ,KAAK,MAAA,EAAiC;AAAA,QAC9E,CAAA;AAAA,QACA,QAAA,EAAU,CAAC,IAAA,KAAS,MAAA,CAAO,KAAK,EAAE;AAAA;AACpC;AACF,GACD,CAAA;AACH","file":"bridges-cms.cjs","sourcesContent":["import {\n type CallToolResult,\n type JsonObject,\n type JsonRpcMessage,\n type JsonRpcRequest,\n type JsonRpcId,\n type RegisteredTool,\n type ServerCapabilities,\n type ServerInfo,\n type ToolDefinition,\n type ToolHandler,\n JSONRPC_INTERNAL_ERROR,\n JSONRPC_INVALID_PARAMS,\n JSONRPC_METHOD_NOT_FOUND,\n MCP_PROTOCOL_VERSION,\n} from \"./types\";\nimport { ToolRegistry } from \"./tool-host\";\n\nexport type McpServerOptions = {\n info: ServerInfo;\n /** Defaults to { tools: { listChanged: true } } */\n capabilities?: ServerCapabilities;\n /** Free-text instructions surfaced to clients during initialize. */\n instructions?: string;\n};\n\nexport type Transport = {\n /** Called by the server when it has a message to deliver to the client. */\n send: (message: JsonRpcMessage) => void;\n /** Called by the server when it's torn down so the transport can clean up. */\n close?: () => void;\n};\n\n/**\n * MicroMcpServer — protocol-level MCP server, transport-agnostic.\n *\n * Use it like:\n *\n * const server = new MicroMcpServer({ info: { name: \"session\", version: \"0.1\" } });\n * server.registerTool({ name: \"...\", inputSchema: { type: \"object\" } }, async (args) => ({...}));\n * const transport = new InProcessTransport();\n * server.attach(transport);\n * transport.deliver({ ... }); // client → server frames\n *\n * The same server can serve multiple transports (e.g. an in-process agent\n * AND a relayed external client) by attaching each one.\n */\nexport class MicroMcpServer extends ToolRegistry {\n private transports = new Set<Transport>();\n private notifyListChangedScheduled = false;\n\n readonly info: ServerInfo;\n readonly capabilities: ServerCapabilities;\n readonly instructions?: string;\n\n constructor(options: McpServerOptions) {\n super();\n this.info = options.info;\n this.capabilities = options.capabilities ?? { tools: { listChanged: true } };\n this.instructions = options.instructions;\n }\n\n attach(transport: Transport): () => void {\n this.transports.add(transport);\n return () => this.detach(transport);\n }\n\n detach(transport: Transport): void {\n if (this.transports.delete(transport)) {\n transport.close?.();\n }\n }\n\n unregisterTool(name: string): void {\n if (this.tools.delete(name)) {\n this.scheduleListChangedNotification();\n }\n }\n\n protected onToolsChanged(): void {\n this.scheduleListChangedNotification();\n }\n\n /**\n * Receive a JSON-RPC frame from a client (called by the transport).\n * The transport is responsible for sending the response back.\n */\n async receive(transport: Transport, message: JsonRpcMessage): Promise<void> {\n if (!(\"method\" in message)) return; // It's a response, not a request — ignore.\n\n const isNotification = !(\"id\" in message);\n if (isNotification) {\n // Notifications are fire-and-forget. We ignore unknown methods.\n return;\n }\n\n const request = message as JsonRpcRequest;\n try {\n const result = await this.handle(request, transport);\n transport.send({ jsonrpc: \"2.0\", id: request.id, result });\n } catch (err) {\n transport.send({\n jsonrpc: \"2.0\",\n id: request.id,\n error: this.toRpcError(err),\n });\n }\n }\n\n private async handle(request: JsonRpcRequest, transport: Transport): Promise<any> {\n const { method, params } = request;\n switch (method) {\n case \"initialize\":\n return {\n protocolVersion: MCP_PROTOCOL_VERSION,\n capabilities: this.capabilities,\n serverInfo: this.info,\n ...(this.instructions ? { instructions: this.instructions } : {}),\n };\n\n case \"tools/list\":\n return { tools: this.listTools() };\n\n case \"tools/call\": {\n const name = params?.name;\n const args = (params?.arguments ?? {}) as JsonObject;\n if (typeof name !== \"string\") {\n throw rpcError(JSONRPC_INVALID_PARAMS, \"tools/call requires `name`\");\n }\n const tool = this.tools.get(name);\n if (!tool) {\n throw rpcError(JSONRPC_METHOD_NOT_FOUND, this.missingToolMessage(name));\n }\n const result = await tool.handler(args, { transport });\n return result satisfies CallToolResult;\n }\n\n case \"ping\":\n return {};\n\n default:\n throw rpcError(JSONRPC_METHOD_NOT_FOUND, `Unsupported method: ${method}`);\n }\n }\n\n private scheduleListChangedNotification(): void {\n if (this.notifyListChangedScheduled) return;\n this.notifyListChangedScheduled = true;\n queueMicrotask(() => {\n this.notifyListChangedScheduled = false;\n this.broadcast({ jsonrpc: \"2.0\", method: \"notifications/tools/list_changed\" });\n });\n }\n\n /** Send an application notification to every client, or one attached transport. */\n notify(message: JsonRpcMessage, transport?: Transport): void {\n if (transport) transport.send(message);\n else this.broadcast(message);\n }\n\n private broadcast(message: JsonRpcMessage): void {\n for (const t of this.transports) t.send(message);\n }\n\n private toRpcError(err: unknown): { code: number; message: string; data?: any } {\n if (err && typeof err === \"object\" && \"code\" in err && \"message\" in err) {\n return err as any;\n }\n return {\n code: JSONRPC_INTERNAL_ERROR,\n message: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nexport function rpcError(code: number, message: string, data?: any) {\n return { code, message, ...(data !== undefined ? { data } : {}) };\n}\n\n/**\n * Helper to build a CallToolResult from a string or structured value.\n */\nexport function textResult(text: string, structured?: any): CallToolResult {\n return {\n content: [{ type: \"text\", text }],\n ...(structured !== undefined ? { structuredContent: structured } : {}),\n };\n}\n\nexport function errorResult(text: string): CallToolResult {\n return { content: [{ type: \"text\", text }], isError: true };\n}\n\n// Internal helper so the JsonRpcId import isn't dropped by tsup\ntype _KeepIdImport = JsonRpcId;\n","import type { CallToolResult } from \"../mcp/types\";\nimport { emitActivity } from \"./registry\";\nimport type { AgentTarget } from \"./types\";\n\nexport type ActivityAgent = { id: string; name?: string; color?: string };\n\nexport type ActivityResolverContext<TArgs = Record<string, unknown>> = {\n /** Tool name as registered. */\n toolName: string;\n /** Arguments the tool was called with. */\n args: TArgs;\n /** The CallToolResult the underlying handler produced. */\n result: CallToolResult;\n};\n\n/**\n * Resolves an `AgentTarget` for an executed tool. Bridges declare one of\n * these per registration so the wrapper knows which surface / element /\n * screen the activity belongs to.\n *\n * The resolver runs AFTER the tool handler so it can inspect the result\n * (e.g. read a newly-created item id from `structuredContent`).\n */\nexport type ActivityTargetResolver<TArgs = Record<string, unknown>> = (\n ctx: ActivityResolverContext<TArgs>,\n) => AgentTarget | null;\n\nexport type ToolHandler<TArgs = Record<string, unknown>> = (\n args: TArgs,\n) => Promise<CallToolResult> | CallToolResult;\n\n/**\n * wrapToolWithActivity — decorate a bridge tool handler so every successful\n * call emits an `AgentActivityEvent`. Returns a new handler with the same shape.\n *\n * Usage in a bridge:\n *\n * server.registerTool(\n * definition,\n * wrapToolWithActivity(\n * handler,\n * { agent, kind: \"whiteboard\", resolveTarget: ({ args }) => ({\n * kind: \"whiteboard\", elementId: args.id as string,\n * }) },\n * ),\n * );\n */\nexport function wrapToolWithActivity<TArgs = Record<string, unknown>>(\n handler: ToolHandler<TArgs>,\n options: {\n toolName: string;\n agent: ActivityAgent;\n /** Optional fancy-screens screen id this bridge is scoped to. */\n screenId?: string;\n /** Default target kind if the resolver returns one without `kind`. */\n kind: AgentTarget[\"kind\"];\n /** Per-call resolver. Return `null` to skip emitting (e.g. for read-only tools). */\n resolveTarget?: ActivityTargetResolver<TArgs>;\n /** Optional ttl override. */\n ttlMs?: number;\n /**\n * Build the `meta` broadcast to all relay peers. Defaults to the tool's full\n * `structuredContent`. Override to REDACT sensitive fields before fan-out —\n * e.g. the terminal bridge strips raw command/keystroke bytes so a command\n * line (or its secrets) is never broadcast verbatim to every peer.\n */\n buildMeta?: (result: CallToolResult) => Record<string, unknown> | undefined;\n },\n): ToolHandler<TArgs> {\n return async (args) => {\n const result = await handler(args);\n if (result.isError) return result;\n\n let target: AgentTarget | null;\n if (options.resolveTarget) {\n target = options.resolveTarget({ toolName: options.toolName, args, result });\n } else {\n target = { kind: options.kind, screenId: options.screenId };\n }\n if (!target) return result;\n\n emitActivity({\n agentId: options.agent.id,\n agentName: options.agent.name,\n agentColor: options.agent.color,\n target: { ...target, kind: target.kind ?? options.kind, screenId: target.screenId ?? options.screenId },\n action: options.toolName,\n timestamp: Date.now(),\n meta: options.buildMeta ? options.buildMeta(result) : extractMeta(result),\n ttlMs: options.ttlMs,\n });\n return result;\n };\n}\n\nfunction extractMeta(result: CallToolResult): Record<string, unknown> | undefined {\n const sc = result.structuredContent;\n if (sc && typeof sc === \"object\" && !Array.isArray(sc)) {\n return sc as Record<string, unknown>;\n }\n return undefined;\n}\n","import { textResult, errorResult } from \"../mcp/server\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport { readHistory, redoOne, undoOne } from \"./undo-stack\";\n\nexport type UndoToolsOptions = {\n /** Default agent id when the caller doesn't pass one. */\n defaultAgentId?: string;\n};\n\n/**\n * Idempotent tracker so multiple bridges on the same server only register\n * agent_undo / agent_redo / agent_history once.\n */\nconst installedHosts = new WeakSet<ToolHost>();\n\n/**\n * ensureUndoToolsRegistered — bridges call this on construction. Safe to\n * call repeatedly with the same server; subsequent calls are no-ops.\n */\nexport function ensureUndoToolsRegistered(host: ToolHost, options: UndoToolsOptions = {}): void {\n if (installedHosts.has(host)) return;\n installedHosts.add(host);\n registerUndoTools(host, options);\n}\n\n/**\n * registerUndoTools — add agent_undo / agent_redo / agent_history to the\n * server. Returns a disposer that unregisters all three.\n */\nexport function registerUndoTools(host: ToolHost, options: UndoToolsOptions = {}): () => void {\n const defaultAgent = options.defaultAgentId ?? \"agent\";\n const disposers: Array<() => void> = [];\n const agentOf = (args: any): string =>\n typeof args?.agentId === \"string\" ? args.agentId : defaultAgent;\n\n disposers.push(\n host.registerTool(\n {\n name: \"agent_undo\",\n description: \"Undo the most recent action on the agent's stack. Optional agentId targets a specific agent.\",\n inputSchema: {\n type: \"object\",\n properties: { agentId: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n async (args) => {\n const entry = await undoOne(agentOf(args));\n if (!entry) return errorResult(\"Nothing to undo.\");\n return textResult(`Undid: ${entry.label}`, { entry: serialize(entry) });\n },\n ),\n );\n\n disposers.push(\n host.registerTool(\n {\n name: \"agent_redo\",\n description: \"Redo the most recently undone action.\",\n inputSchema: {\n type: \"object\",\n properties: { agentId: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n async (args) => {\n const entry = await redoOne(agentOf(args));\n if (!entry) return errorResult(\"Nothing to redo.\");\n return textResult(`Redid: ${entry.label}`, { entry: serialize(entry) });\n },\n ),\n );\n\n disposers.push(\n host.registerTool(\n {\n name: \"agent_history\",\n description: \"List the agent's undo stack (oldest first). Useful for understanding what's reversible.\",\n inputSchema: {\n type: \"object\",\n properties: { agentId: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n async (args) => {\n const history = readHistory(agentOf(args)).map(serialize);\n const text = history.map((e) => `${new Date(e.timestamp).toISOString()} ${e.bridgeId} ${e.action}: ${e.label}`).join(\"\\n\");\n return textResult(text || \"(empty)\", history);\n },\n ),\n );\n\n return () => disposers.forEach((d) => d());\n}\n\nfunction serialize(entry: import(\"./undo-stack\").UndoEntry) {\n return {\n timestamp: entry.timestamp,\n bridgeId: entry.bridgeId,\n action: entry.action,\n label: entry.label,\n };\n}\n","/**\n * registerDocBridge — a GENERIC MCP bridge over a `@particle-academy/fancy-doc-commons`\n * `DocTree`. Give it an adapter (`{ get, set }`) and it generates, from the shared\n * op-spine, a full Human+ surface: uniform read tools + the canonical node op tools\n * (add / update / remove / move) under one verb lexicon, with **undo derived from\n * the reducer**, agent-activity broadcasts, unconditional `agent_undo/redo/history`,\n * and an optional **staged-write** (confirm / reject) channel — replacing the ~500-line\n * bespoke bridges (whiteboard/flow/artboard/…) with one builder. A surface adds its\n * domain ops (e.g. cms `set_style`) via `opTools` + a matching reducer.\n */\nimport { textResult, errorResult } from \"../mcp/server\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport type { JsonObject } from \"../mcp/types\";\nimport type { Bridge } from \"./types\";\nimport { wrapToolWithActivity } from \"../presence/wrap-tool-with-activity\";\nimport type { AgentTarget } from \"../presence/types\";\nimport { pushUndoEntry } from \"../undo/undo-stack\";\nimport { ensureUndoToolsRegistered } from \"../undo/undo-tools\";\nimport {\n treeReducer,\n childrenOf,\n descendantsOf,\n appendOrder,\n autoApply,\n type DocTree,\n type DocNode,\n type TreeOp,\n type DocReducer,\n type StagePolicy,\n} from \"@particle-academy/fancy-doc-commons\";\n\nconst DEFAULT_AGENT = { id: \"agent\", name: \"Agent\", color: \"#a855f7\" };\n\n/** Host-provided access to the document tree. */\nexport interface DocAdapter<N extends DocNode> {\n /** Read the current tree. */\n get(): DocTree<N>;\n /** Replace the tree — host wires this to its `onChange` / `setState`. */\n set(next: DocTree<N>): void;\n /** Optional fancy-screens screen id, for presence scoping. */\n screenId?: string;\n /** Mint a fresh, unique node id. Default: `<surface>-<n>`. */\n newId?(): string;\n}\n\n/**\n * A domain op tool beyond the built-in add/update/remove/move — lets a surface\n * expose its own ops (e.g. cms `set_style`) through the same undo + activity path.\n */\nexport interface DocOpTool<N extends DocNode, TOp> {\n /** Verb, prefixed with the surface (e.g. `set_style` → `cms_set_style`). */\n verb: string;\n description: string;\n properties: Record<string, unknown>;\n required: string[];\n /** Build the op from the args (or return `{ error }`). */\n build(args: JsonObject, tree: DocTree<N>): TOp | { error: string };\n /** Node id this op targets (for the activity target + undo label). */\n targetId?(args: JsonObject): string | undefined;\n}\n\nexport interface DocBridgeOptions<N extends DocNode, TOp = TreeOp<N>> {\n adapter: DocAdapter<N>;\n /** Tool-name prefix + activity kind (e.g. `\"cms\"` → `cms_add`, kind `\"cms\"`). */\n surface: string;\n agent?: { id: string; name?: string; color?: string };\n /** Reducer for reduce + invert. Default: the substrate `treeReducer<N>()`. */\n reducer?: DocReducer<DocTree<N>, TOp>;\n /** Build a full node from the core fields + props (fill surface defaults, e.g. `style`). */\n makeNode?: (core: { id: string; type: string; parent: string | null; order: string }, props: Record<string, unknown>) => N;\n /** Domain op tools beyond the built-ins. */\n opTools?: DocOpTool<N, TOp>[];\n /** Decide auto-apply vs. confirm per op. Default: everything auto-applies. */\n stagePolicy?: StagePolicy<TOp>;\n /** Fired when an op is staged pending human confirmation. */\n onPending?: (staged: { id: string; op: TOp; label: string }) => void;\n /** Summarize a node for describe/list. Default: id/type/parent + prop keys. */\n describeNode?: (node: N) => Record<string, unknown>;\n}\n\n/** Register the generic doc-surface bridge. Returns a {@link Bridge}. */\nexport function registerDocBridge<N extends DocNode, TOp = TreeOp<N>>(\n host: ToolHost,\n options: DocBridgeOptions<N, TOp>,\n): Bridge {\n const { adapter, surface } = options;\n const agent = { ...DEFAULT_AGENT, ...(options.agent ?? {}) };\n const reducer = (options.reducer ?? (treeReducer<N>() as unknown as DocReducer<DocTree<N>, TOp>));\n const stage = options.stagePolicy ?? (autoApply as StagePolicy<TOp>);\n const makeNode =\n options.makeNode ?? (({ id, type, parent, order }, props) => ({ id, type, parent, order, props }) as N);\n const describeNode =\n options.describeNode ?? ((n: N) => ({ id: n.id, type: n.type, parent: n.parent, props: Object.keys(n.props ?? {}) }));\n const disposers: Array<() => void> = [];\n\n // agent_undo / agent_redo / agent_history — always present (undo derives from\n // the reducer, so every doc surface gets working undo for free).\n ensureUndoToolsRegistered(host, { defaultAgentId: agent.id });\n\n let idSeq = 0;\n // The counter restarts with the bridge, so on a tree loaded from elsewhere\n // `surface-1` may well be taken. Skip past anything that already exists\n // rather than minting an id that silently overwrites a node.\n const mintId = () => {\n if (adapter.newId) return adapter.newId();\n const taken = adapter.get().nodes;\n let id: string;\n do id = `${surface}-${(idSeq += 1)}`;\n while (taken[id]);\n return id;\n };\n const target = (elementId?: string): AgentTarget => ({ kind: surface, screenId: adapter.screenId, elementId });\n\n // Staged ops awaiting confirmation.\n const pending = new Map<string, { op: TOp; label: string; targetId?: string }>();\n\n /** Apply an op immediately: reduce → set → push a snapshot-based undo entry. */\n function commit(op: TOp, label: string, targetId?: string): Record<string, unknown> {\n const prev = adapter.get();\n const next = reducer.reduce(prev, op);\n adapter.set(next);\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: surface,\n action: label,\n label,\n undo: () => adapter.set(prev),\n redo: () => adapter.set(next),\n });\n return { ok: true, id: targetId };\n }\n\n /**\n * Auto-apply, or stage for confirmation per the stage policy.\n *\n * The staged case reports the pending id under its OWN key. Returning it as\n * `id` — as this used to — collided with the node id every mutation already\n * reports, so `update`/`remove`/`move` overwrote it and left the agent holding\n * a node id that `confirm` does not accept. The staged write was unconfirmable\n * for three of the four canonical ops, and looked fine from the outside.\n */\n function submit(op: TOp, label: string, targetId?: string): { staged: boolean; id?: string; pendingId?: string } {\n if (stage(op) === \"confirm\") {\n const pendingId = `${surface}-pending-${(idSeq += 1)}`;\n pending.set(pendingId, { op, label, targetId });\n options.onPending?.({ id: pendingId, op, label });\n return { staged: true, id: targetId, pendingId };\n }\n commit(op, label, targetId);\n return { staged: false, id: targetId };\n }\n\n const reg = (\n verb: string,\n description: string,\n properties: Record<string, unknown>,\n required: string[],\n handler: (args: JsonObject) => Record<string, unknown> | Promise<Record<string, unknown>>,\n isMutation: boolean,\n resolveTarget?: (args: JsonObject, result: Record<string, unknown>) => AgentTarget | null,\n ): void => {\n const name = `${surface}_${verb}`;\n const wrapped = async (args: JsonObject) => {\n try {\n // `_text` is the human-facing line; the rest is structuredContent.\n const { _text, ...structured } = await handler(args);\n return textResult(typeof _text === \"string\" ? _text : name, structured);\n } catch (e) {\n return errorResult(e instanceof Error ? e.message : String(e));\n }\n };\n const final = isMutation\n ? wrapToolWithActivity(wrapped, {\n toolName: name,\n agent,\n kind: surface,\n screenId: adapter.screenId,\n resolveTarget: ({ args, result }) => {\n if ((result.structuredContent as JsonObject | undefined)?.staged) return null;\n return resolveTarget?.(args, (result.structuredContent as JsonObject) ?? {}) ?? target();\n },\n })\n : wrapped;\n disposers.push(\n host.registerTool(\n { name, description, inputSchema: { type: \"object\", properties: properties as never, required, additionalProperties: false } },\n final as never,\n ),\n );\n };\n\n // ── Read tools ──────────────────────────────────────────────────────────\n reg(\n \"describe\",\n `Summarize the ${surface} document: node count, roots, and the active surface. Call before reading or writing.`,\n {},\n [],\n () => {\n const tree = adapter.get();\n const ids = Object.keys(tree.nodes);\n return { nodeCount: ids.length, roots: childrenOf(tree, null).map((n) => n.id), _text: `${ids.length} nodes` };\n },\n false,\n );\n reg(\n \"get\",\n `Get the whole ${surface} document tree as JSON.`,\n {},\n [],\n () => ({ tree: adapter.get(), _text: \"full tree\" }),\n false,\n );\n reg(\n \"list\",\n \"List nodes (optionally the children of `parent`), in order.\",\n { parent: { type: [\"string\", \"null\"], description: \"Parent id, or null/omitted for roots.\" } },\n [],\n (args) => {\n const tree = adapter.get();\n const parent = typeof args.parent === \"string\" ? args.parent : null;\n return { nodes: childrenOf(tree, parent).map(describeNode), _text: `children of ${parent ?? \"root\"}` };\n },\n false,\n );\n reg(\n \"get_node\",\n \"Get one node by id.\",\n { id: { type: \"string\" } },\n [\"id\"],\n (args) => {\n const node = adapter.get().nodes[String(args.id)];\n if (!node) throw new Error(`No node ${args.id}`);\n return { node, _text: `node ${node.id}` };\n },\n false,\n );\n\n // ── Canonical op tools ──────────────────────────────────────────────────\n reg(\n \"add\",\n \"Insert a node. Returns its id. Appends under `parent` (or roots) unless `order` is given.\",\n {\n type: { type: \"string\", description: \"Node type discriminant.\" },\n parent: { type: [\"string\", \"null\"], description: \"Parent id, or null for a root.\" },\n props: { type: \"object\", description: \"JSON props bag.\" },\n order: { type: \"string\", description: \"Fractional order key (default: append).\" },\n id: {\n type: \"string\",\n description:\n \"Id for the new node. Supply a meaningful one if you intend to address this node later; omitted means one is minted for you. Must not already exist.\",\n },\n },\n [\"type\"],\n (args) => {\n const tree = adapter.get();\n const parent = typeof args.parent === \"string\" ? args.parent : null;\n // An agent that names the node names the handle it will use afterwards.\n // Minted ids are addressable too, just less memorable.\n const requested = typeof args.id === \"string\" ? args.id : undefined;\n if (requested !== undefined && tree.nodes[requested]) {\n throw new Error(`Node ${requested} already exists — pick a different id or update it instead`);\n }\n const id = requested ?? mintId();\n const order = typeof args.order === \"string\" ? args.order : appendOrder(tree, parent);\n const props = (args.props && typeof args.props === \"object\" ? args.props : {}) as Record<string, unknown>;\n const node = makeNode({ id, type: String(args.type), parent, order }, props);\n const res = submit({ t: \"insert\", node } as unknown as TOp, `add ${args.type} ${id}`, id);\n return { ...res, _text: res.staged ? `staged add ${id} — confirm ${res.pendingId}` : `added ${id}` };\n },\n true,\n (_args, result) => target(result.id as string | undefined),\n );\n reg(\n \"update\",\n \"Merge a props patch into a node.\",\n { id: { type: \"string\" }, patch: { type: \"object\" } },\n [\"id\", \"patch\"],\n (args) => {\n const id = String(args.id);\n if (!adapter.get().nodes[id]) throw new Error(`No node ${id}`);\n const patch = (args.patch && typeof args.patch === \"object\" ? args.patch : {}) as Record<string, unknown>;\n const res = submit({ t: \"set_props\", id, patch } as unknown as TOp, `update ${id}`, id);\n return { ...res, id, _text: res.staged ? `staged update ${id} — confirm ${res.pendingId}` : `updated ${id}` };\n },\n true,\n (args) => target(String(args.id)),\n );\n reg(\n \"remove\",\n \"Remove a node and its subtree.\",\n { id: { type: \"string\" } },\n [\"id\"],\n (args) => {\n const id = String(args.id);\n const tree = adapter.get();\n if (!tree.nodes[id]) throw new Error(`No node ${id}`);\n const count = descendantsOf(tree, id).length + 1;\n const res = submit({ t: \"remove\", id } as unknown as TOp, `remove ${id} (${count} node${count === 1 ? \"\" : \"s\"})`, id);\n return { ...res, id, removed: count, _text: res.staged ? `staged remove ${id} — confirm ${res.pendingId}` : `removed ${id}` };\n },\n true,\n (args) => target(String(args.id)),\n );\n reg(\n \"move\",\n \"Reparent + reorder a node.\",\n { id: { type: \"string\" }, parent: { type: [\"string\", \"null\"] }, order: { type: \"string\", description: \"Fractional order key (default: append under the new parent).\" } },\n [\"id\"],\n (args) => {\n const id = String(args.id);\n const tree = adapter.get();\n if (!tree.nodes[id]) throw new Error(`No node ${id}`);\n const parent = args.parent === null ? null : typeof args.parent === \"string\" ? args.parent : tree.nodes[id]!.parent;\n const order = typeof args.order === \"string\" ? args.order : appendOrder(tree, parent);\n const res = submit({ t: \"move\", id, parent, order } as unknown as TOp, `move ${id}`, id);\n return { ...res, id, _text: res.staged ? `staged move ${id} — confirm ${res.pendingId}` : `moved ${id}` };\n },\n true,\n (args) => target(String(args.id)),\n );\n\n // ── Domain op tools ─────────────────────────────────────────────────────\n for (const t of options.opTools ?? []) {\n reg(\n t.verb,\n t.description,\n t.properties,\n t.required,\n (args) => {\n const built = t.build(args, adapter.get());\n if (built && typeof built === \"object\" && \"error\" in built) throw new Error((built as { error: string }).error);\n const tid = t.targetId?.(args);\n const res = submit(built as TOp, `${t.verb} ${tid ?? \"\"}`.trim(), tid);\n return { ...res, id: tid, _text: res.staged ? `staged ${t.verb} — confirm ${res.pendingId}` : t.verb };\n },\n true,\n (args) => target(t.targetId?.(args)),\n );\n }\n\n // ── Staged-write confirm / reject ───────────────────────────────────────\n reg(\n \"confirm\",\n \"Apply a staged op. Pass the `pendingId` a staged mutation returned — not the node `id` it also returns.\",\n { id: { type: \"string\", description: \"The `pendingId` from a staged mutation.\" } },\n [\"id\"],\n (args) => {\n const id = String(args.id);\n const p = pending.get(id);\n if (!p) throw new Error(`No pending op ${id}`);\n pending.delete(id);\n commit(p.op, p.label, p.targetId);\n return { ok: true, applied: p.label, id: p.targetId, _text: `applied ${p.label}` };\n },\n true,\n (_args, result) => target(result.id as string | undefined),\n );\n reg(\n \"reject\",\n \"Discard a staged op. Pass the `pendingId` a staged mutation returned — not the node `id` it also returns.\",\n { id: { type: \"string\", description: \"The `pendingId` from a staged mutation.\" } },\n [\"id\"],\n (args) => {\n const id = String(args.id);\n const p = pending.get(id);\n if (!p) throw new Error(`No pending op ${id}`);\n pending.delete(id);\n return { ok: true, rejected: p.label, _text: `rejected ${p.label}` };\n },\n false,\n );\n\n return {\n id: surface,\n title: surface,\n dispose: () => {\n for (const d of disposers) d();\n pending.clear();\n },\n };\n}\n","/**\n * registerCmsBridge — the greenfield CMS agent bridge, built entirely on\n * {@link registerDocBridge}. cms had NO bridge before (its op-spine was\n * agent-ready but unwired); this is the §8-decided \"build registerCmsBridge on\n * registerDocBridge BEFORE deprecating ScreenSchema\" step.\n *\n * A CMS page is a `DocTree<StyledNode>` (fancy-doc-commons): the generic bridge\n * supplies `cms_describe/get/list/get_node` + `cms_add/update/remove/move` +\n * undo/activity/staging for free; this layer adds the two domain ops a page\n * needs — `cms_set_style` (per-node base StyleProps) and `cms_set_layout` — and a\n * reducer that handles them alongside the substrate tree ops.\n */\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport type { Bridge } from \"./types\";\nimport { registerDocBridge, type DocAdapter } from \"./doc\";\nimport {\n treeReducer,\n type DocReducer,\n type DocTree,\n type LayoutMode,\n type StyledNode,\n type StyleProps,\n type TreeOp,\n type StagePolicy,\n} from \"@particle-academy/fancy-doc-commons\";\n\n/** The CMS op union: the substrate tree ops + per-node style/layout. */\nexport type CmsOp =\n | TreeOp<StyledNode>\n | { t: \"set_style\"; id: string; patch: Partial<StyleProps> }\n | { t: \"set_layout\"; id: string; layout?: LayoutMode };\n\n/** A pure reducer over a `DocTree<StyledNode>` handling tree ops + style/layout. */\nexport function cmsReducer(): DocReducer<DocTree<StyledNode>, CmsOp> {\n const base = treeReducer<StyledNode>();\n return {\n reduce(doc, op) {\n if (op.t === \"set_style\") {\n const node = doc.nodes[op.id];\n if (!node) return doc;\n return { nodes: { ...doc.nodes, [op.id]: { ...node, style: { ...node.style, base: { ...node.style.base, ...op.patch } } } } };\n }\n if (op.t === \"set_layout\") {\n const node = doc.nodes[op.id];\n if (!node) return doc;\n return { nodes: { ...doc.nodes, [op.id]: { ...node, layout: op.layout } } };\n }\n return base.reduce(doc, op);\n },\n invert(doc, op) {\n if (op.t === \"set_style\") {\n const node = doc.nodes[op.id];\n if (!node) return [];\n const prev: Partial<StyleProps> = {};\n for (const k in op.patch) (prev as Record<string, unknown>)[k as keyof StyleProps] = node.style.base[k as keyof StyleProps];\n return [{ t: \"set_style\", id: op.id, patch: prev }];\n }\n if (op.t === \"set_layout\") {\n const node = doc.nodes[op.id];\n if (!node) return [];\n return [{ t: \"set_layout\", id: op.id, layout: node.layout }];\n }\n return base.invert(doc, op) as CmsOp[];\n },\n };\n}\n\nexport interface CmsBridgeOptions {\n adapter: DocAdapter<StyledNode>;\n agent?: { id: string; name?: string; color?: string };\n /** Auto-apply vs. confirm per op (trust-but-verify). Default: auto. */\n stagePolicy?: StagePolicy<CmsOp>;\n onPending?: (staged: { id: string; op: CmsOp; label: string }) => void;\n}\n\n/** Register the CMS bridge (prefix `cms_`) over a `DocTree<StyledNode>`. */\nexport function registerCmsBridge(host: ToolHost, options: CmsBridgeOptions): Bridge {\n return registerDocBridge<StyledNode, CmsOp>(host, {\n adapter: options.adapter,\n surface: \"cms\",\n agent: options.agent,\n reducer: cmsReducer(),\n stagePolicy: options.stagePolicy,\n onPending: options.onPending,\n // New nodes get an empty base style so they satisfy StyledNode.\n makeNode: ({ id, type, parent, order }, props) => ({ id, type, parent, order, props, style: { base: {} } }),\n describeNode: (n) => ({ id: n.id, type: n.type, parent: n.parent, layout: n.layout }),\n opTools: [\n {\n verb: \"set_style\",\n description: \"Merge a StyleProps patch into a node's base style (color, background, padding, fontSize, gap, …).\",\n properties: { id: { type: \"string\" }, patch: { type: \"object\", description: \"Partial StyleProps.\" } },\n required: [\"id\", \"patch\"],\n build: (args, tree) => {\n const id = String(args.id);\n if (!tree.nodes[id]) return { error: `No node ${id}` };\n return { t: \"set_style\", id, patch: (args.patch && typeof args.patch === \"object\" ? args.patch : {}) as Partial<StyleProps> };\n },\n targetId: (args) => String(args.id),\n },\n {\n verb: \"set_layout\",\n description: \"Set a container node's layout mode (free | stack | grid).\",\n properties: { id: { type: \"string\" }, layout: { type: \"string\", enum: [\"free\", \"stack\", \"grid\"] } },\n required: [\"id\"],\n build: (args, tree) => {\n const id = String(args.id);\n if (!tree.nodes[id]) return { error: `No node ${id}` };\n return { t: \"set_layout\", id, layout: args.layout as LayoutMode | undefined };\n },\n targetId: (args) => String(args.id),\n },\n ],\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/mcp/server.ts","../src/presence/wrap-tool-with-activity.ts","../src/undo/undo-tools.ts","../src/bridges/doc.ts","../src/bridges/cms.ts"],"names":["emitActivity","undoOne","redoOne","readHistory","treeReducer","autoApply","pushUndoEntry","childrenOf","appendOrder","descendantsOf"],"mappings":";;;;;;AAoOO,SAAS,UAAA,CAAW,MAAc,UAAA,EAAkC;AACzE,EAAA,OAAO;AAAA,IACL,SAAS,CAAC,EAAE,IAAA,EAAM,MAAA,EAAQ,MAAM,CAAA;AAAA,IAChC,GAAI,UAAA,KAAe,MAAA,GAAY,EAAE,iBAAA,EAAmB,UAAA,KAAe;AAAC,GACtE;AACF;AAEO,SAAS,YAAY,IAAA,EAA8B;AACxD,EAAA,OAAO,EAAE,OAAA,EAAS,CAAC,EAAE,IAAA,EAAM,QAAQ,IAAA,EAAM,CAAA,EAAG,OAAA,EAAS,IAAA,EAAK;AAC5D;;;AC9LO,SAAS,oBAAA,CACd,SACA,OAAA,EAmBoB;AACpB,EAAA,OAAO,OAAO,IAAA,KAAS;AACrB,IAAA,MAAM,MAAA,GAAS,MAAM,OAAA,CAAQ,IAAI,CAAA;AACjC,IAAA,IAAI,MAAA,CAAO,SAAS,OAAO,MAAA;AAE3B,IAAA,IAAI,MAAA;AACJ,IAAA,IAAI,QAAQ,aAAA,EAAe;AACzB,MAAA,MAAA,GAAS,OAAA,CAAQ,cAAc,EAAE,QAAA,EAAU,QAAQ,QAAA,EAAU,IAAA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,\n type RegisteredTool,\n type ServerCapabilities,\n type ServerInfo,\n type ToolDefinition,\n type ToolHandler,\n JSONRPC_INTERNAL_ERROR,\n JSONRPC_INVALID_PARAMS,\n JSONRPC_METHOD_NOT_FOUND,\n MCP_PROTOCOL_VERSION,\n} from \"./types\";\nimport { ToolRegistry } from \"./tool-host\";\n\nexport type McpServerOptions = {\n info: ServerInfo;\n /** Defaults to { tools: { listChanged: true } } */\n capabilities?: ServerCapabilities;\n /** Free-text instructions surfaced to clients during initialize. */\n instructions?: string;\n /**\n * The protocol revisions this server speaks, NEWEST FIRST.\n *\n * `initialize` echoes the client's requested revision when it is in this\n * list, and answers the first entry otherwise — the spec's rule, which leaves\n * the client to decide whether it can live with the answer.\n *\n * Defaults to `[MCP_PROTOCOL_VERSION]`: one revision, answered whatever the\n * client asks, which is exactly what this server did before the option\n * existed. Only list a revision the tools you register are correct under.\n */\n protocolVersions?: readonly string[];\n};\n\nexport type Transport = {\n /** Called by the server when it has a message to deliver to the client. */\n send: (message: JsonRpcMessage) => void;\n /** Called by the server when it's torn down so the transport can clean up. */\n close?: () => void;\n};\n\n/**\n * MicroMcpServer — protocol-level MCP server, transport-agnostic.\n *\n * Use it like:\n *\n * const server = new MicroMcpServer({ info: { name: \"session\", version: \"0.1\" } });\n * server.registerTool({ name: \"...\", inputSchema: { type: \"object\" } }, async (args) => ({...}));\n * const transport = new InProcessTransport();\n * server.attach(transport);\n * transport.deliver({ ... }); // client → server frames\n *\n * The same server can serve multiple transports (e.g. an in-process agent\n * AND a relayed external client) by attaching each one.\n */\nexport class MicroMcpServer extends ToolRegistry {\n private transports = new Set<Transport>();\n /**\n * Transports owed a `tools/list_changed` at the end of this tick. Empty when\n * none is scheduled. See {@link scheduleListChangedNotification}.\n */\n private listChangedOwed = new Set<Transport>();\n\n readonly info: ServerInfo;\n readonly capabilities: ServerCapabilities;\n readonly instructions?: string;\n readonly protocolVersions: readonly string[];\n\n constructor(options: McpServerOptions) {\n super();\n this.info = options.info;\n this.capabilities = options.capabilities ?? { tools: { listChanged: true } };\n this.instructions = options.instructions;\n if (options.protocolVersions && options.protocolVersions.length === 0) {\n // No answer exists for a client's initialize. Fail here, next to the\n // mistake, rather than in a handshake nobody is watching.\n throw new Error(\"MicroMcpServer: protocolVersions is empty — a server must speak at least one protocol revision.\");\n }\n this.protocolVersions = options.protocolVersions ? [...options.protocolVersions] : [MCP_PROTOCOL_VERSION];\n }\n\n attach(transport: Transport): () => void {\n this.transports.add(transport);\n return () => this.detach(transport);\n }\n\n detach(transport: Transport): void {\n if (this.transports.delete(transport)) {\n transport.close?.();\n }\n }\n\n unregisterTool(name: string): void {\n if (this.tools.delete(name)) {\n this.scheduleListChangedNotification();\n }\n }\n\n protected onToolsChanged(): void {\n this.scheduleListChangedNotification();\n }\n\n /**\n * Receive a JSON-RPC frame from a client (called by the transport).\n * The transport is responsible for sending the response back.\n */\n async receive(transport: Transport, message: JsonRpcMessage): Promise<void> {\n if (!(\"method\" in message)) return; // It's a response, not a request — ignore.\n\n const isNotification = !(\"id\" in message);\n if (isNotification) {\n // Notifications are fire-and-forget. We ignore unknown methods.\n return;\n }\n\n const request = message as JsonRpcRequest;\n try {\n const result = await this.handle(request, transport);\n transport.send({ jsonrpc: \"2.0\", id: request.id, result });\n } catch (err) {\n transport.send({\n jsonrpc: \"2.0\",\n id: request.id,\n error: this.toRpcError(err),\n });\n }\n }\n\n private async handle(request: JsonRpcRequest, transport: Transport): Promise<any> {\n const { method, params } = request;\n switch (method) {\n case \"initialize\":\n return {\n protocolVersion: this.negotiate(params?.protocolVersion),\n capabilities: this.capabilities,\n serverInfo: this.info,\n ...(this.instructions ? { instructions: this.instructions } : {}),\n };\n\n case \"tools/list\":\n return { tools: this.listTools() };\n\n case \"tools/call\": {\n const name = params?.name;\n const args = (params?.arguments ?? {}) as JsonObject;\n if (typeof name !== \"string\") {\n throw rpcError(JSONRPC_INVALID_PARAMS, \"tools/call requires `name`\");\n }\n const tool = this.tools.get(name);\n if (!tool) {\n throw rpcError(JSONRPC_METHOD_NOT_FOUND, this.missingToolMessage(name));\n }\n const result = await tool.handler(args, { transport });\n return result satisfies CallToolResult;\n }\n\n case \"ping\":\n return {};\n\n default:\n throw rpcError(JSONRPC_METHOD_NOT_FOUND, `Unsupported method: ${method}`);\n }\n }\n\n /** The revision to answer `initialize` with: the one asked for if spoken, else the newest. */\n private negotiate(requested: unknown): string {\n return typeof requested === \"string\" && this.protocolVersions.includes(requested)\n ? requested\n : this.protocolVersions[0];\n }\n\n /**\n * Tell the transports that SAW the old tool list that it changed.\n *\n * Changes in one tick coalesce into one notification. The recipients are the\n * transports attached at the moment of a change, not at the moment the\n * notification goes out: a transport attached afterwards never had the old\n * list, so \"your list is stale\" is noise to it — and on stdio, where a host\n * builds the server and attaches stdin/stdout in the same tick, it was the\n * first frame a client received, before it had even sent `initialize`.\n */\n private scheduleListChangedNotification(): void {\n if (this.transports.size === 0) return;\n const scheduled = this.listChangedOwed.size > 0;\n for (const t of this.transports) this.listChangedOwed.add(t);\n if (scheduled) return;\n queueMicrotask(() => {\n const owed = this.listChangedOwed;\n this.listChangedOwed = new Set();\n for (const t of owed) {\n // Detached since the change: it is not listening any more.\n if (this.transports.has(t)) t.send({ jsonrpc: \"2.0\", method: \"notifications/tools/list_changed\" });\n }\n });\n }\n\n /** Send an application notification to every client, or one attached transport. */\n notify(message: JsonRpcMessage, transport?: Transport): void {\n if (transport) transport.send(message);\n else this.broadcast(message);\n }\n\n private broadcast(message: JsonRpcMessage): void {\n for (const t of this.transports) t.send(message);\n }\n\n private toRpcError(err: unknown): { code: number; message: string; data?: any } {\n if (err && typeof err === \"object\" && \"code\" in err && \"message\" in err) {\n return err as any;\n }\n return {\n code: JSONRPC_INTERNAL_ERROR,\n message: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nexport function rpcError(code: number, message: string, data?: any) {\n return { code, message, ...(data !== undefined ? { data } : {}) };\n}\n\n/**\n * Helper to build a CallToolResult from a string or structured value.\n */\nexport function textResult(text: string, structured?: any): CallToolResult {\n return {\n content: [{ type: \"text\", text }],\n ...(structured !== undefined ? { structuredContent: structured } : {}),\n };\n}\n\nexport function errorResult(text: string): CallToolResult {\n return { content: [{ type: \"text\", text }], isError: true };\n}\n\n// Internal helper so the JsonRpcId import isn't dropped by tsup\ntype _KeepIdImport = JsonRpcId;\n","import type { CallToolResult } from \"../mcp/types\";\nimport { emitActivity } from \"./registry\";\nimport type { AgentTarget } from \"./types\";\n\nexport type ActivityAgent = { id: string; name?: string; color?: string };\n\nexport type ActivityResolverContext<TArgs = Record<string, unknown>> = {\n /** Tool name as registered. */\n toolName: string;\n /** Arguments the tool was called with. */\n args: TArgs;\n /** The CallToolResult the underlying handler produced. */\n result: CallToolResult;\n};\n\n/**\n * Resolves an `AgentTarget` for an executed tool. Bridges declare one of\n * these per registration so the wrapper knows which surface / element /\n * screen the activity belongs to.\n *\n * The resolver runs AFTER the tool handler so it can inspect the result\n * (e.g. read a newly-created item id from `structuredContent`).\n */\nexport type ActivityTargetResolver<TArgs = Record<string, unknown>> = (\n ctx: ActivityResolverContext<TArgs>,\n) => AgentTarget | null;\n\nexport type ToolHandler<TArgs = Record<string, unknown>> = (\n args: TArgs,\n) => Promise<CallToolResult> | CallToolResult;\n\n/**\n * wrapToolWithActivity — decorate a bridge tool handler so every successful\n * call emits an `AgentActivityEvent`. Returns a new handler with the same shape.\n *\n * Usage in a bridge:\n *\n * server.registerTool(\n * definition,\n * wrapToolWithActivity(\n * handler,\n * { agent, kind: \"whiteboard\", resolveTarget: ({ args }) => ({\n * kind: \"whiteboard\", elementId: args.id as string,\n * }) },\n * ),\n * );\n */\nexport function wrapToolWithActivity<TArgs = Record<string, unknown>>(\n handler: ToolHandler<TArgs>,\n options: {\n toolName: string;\n agent: ActivityAgent;\n /** Optional fancy-screens screen id this bridge is scoped to. */\n screenId?: string;\n /** Default target kind if the resolver returns one without `kind`. */\n kind: AgentTarget[\"kind\"];\n /** Per-call resolver. Return `null` to skip emitting (e.g. for read-only tools). */\n resolveTarget?: ActivityTargetResolver<TArgs>;\n /** Optional ttl override. */\n ttlMs?: number;\n /**\n * Build the `meta` broadcast to all relay peers. Defaults to the tool's full\n * `structuredContent`. Override to REDACT sensitive fields before fan-out —\n * e.g. the terminal bridge strips raw command/keystroke bytes so a command\n * line (or its secrets) is never broadcast verbatim to every peer.\n */\n buildMeta?: (result: CallToolResult) => Record<string, unknown> | undefined;\n },\n): ToolHandler<TArgs> {\n return async (args) => {\n const result = await handler(args);\n if (result.isError) return result;\n\n let target: AgentTarget | null;\n if (options.resolveTarget) {\n target = options.resolveTarget({ toolName: options.toolName, args, result });\n } else {\n target = { kind: options.kind, screenId: options.screenId };\n }\n if (!target) return result;\n\n emitActivity({\n agentId: options.agent.id,\n agentName: options.agent.name,\n agentColor: options.agent.color,\n target: { ...target, kind: target.kind ?? options.kind, screenId: target.screenId ?? options.screenId },\n action: options.toolName,\n timestamp: Date.now(),\n meta: options.buildMeta ? options.buildMeta(result) : extractMeta(result),\n ttlMs: options.ttlMs,\n });\n return result;\n };\n}\n\nfunction extractMeta(result: CallToolResult): Record<string, unknown> | undefined {\n const sc = result.structuredContent;\n if (sc && typeof sc === \"object\" && !Array.isArray(sc)) {\n return sc as Record<string, unknown>;\n }\n return undefined;\n}\n","import { textResult, errorResult } from \"../mcp/server\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport { readHistory, redoOne, undoOne } from \"./undo-stack\";\n\nexport type UndoToolsOptions = {\n /** Default agent id when the caller doesn't pass one. */\n defaultAgentId?: string;\n};\n\n/**\n * Idempotent tracker so multiple bridges on the same server only register\n * agent_undo / agent_redo / agent_history once.\n */\nconst installedHosts = new WeakSet<ToolHost>();\n\n/**\n * ensureUndoToolsRegistered — bridges call this on construction. Safe to\n * call repeatedly with the same server; subsequent calls are no-ops.\n */\nexport function ensureUndoToolsRegistered(host: ToolHost, options: UndoToolsOptions = {}): void {\n if (installedHosts.has(host)) return;\n installedHosts.add(host);\n registerUndoTools(host, options);\n}\n\n/**\n * registerUndoTools — add agent_undo / agent_redo / agent_history to the\n * server. Returns a disposer that unregisters all three.\n */\nexport function registerUndoTools(host: ToolHost, options: UndoToolsOptions = {}): () => void {\n const defaultAgent = options.defaultAgentId ?? \"agent\";\n const disposers: Array<() => void> = [];\n const agentOf = (args: any): string =>\n typeof args?.agentId === \"string\" ? args.agentId : defaultAgent;\n\n disposers.push(\n host.registerTool(\n {\n name: \"agent_undo\",\n description: \"Undo the most recent action on the agent's stack. Optional agentId targets a specific agent.\",\n inputSchema: {\n type: \"object\",\n properties: { agentId: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n async (args) => {\n const entry = await undoOne(agentOf(args));\n if (!entry) return errorResult(\"Nothing to undo.\");\n return textResult(`Undid: ${entry.label}`, { entry: serialize(entry) });\n },\n ),\n );\n\n disposers.push(\n host.registerTool(\n {\n name: \"agent_redo\",\n description: \"Redo the most recently undone action.\",\n inputSchema: {\n type: \"object\",\n properties: { agentId: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n async (args) => {\n const entry = await redoOne(agentOf(args));\n if (!entry) return errorResult(\"Nothing to redo.\");\n return textResult(`Redid: ${entry.label}`, { entry: serialize(entry) });\n },\n ),\n );\n\n disposers.push(\n host.registerTool(\n {\n name: \"agent_history\",\n description: \"List the agent's undo stack (oldest first). Useful for understanding what's reversible.\",\n inputSchema: {\n type: \"object\",\n properties: { agentId: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n async (args) => {\n const history = readHistory(agentOf(args)).map(serialize);\n const text = history.map((e) => `${new Date(e.timestamp).toISOString()} ${e.bridgeId} ${e.action}: ${e.label}`).join(\"\\n\");\n return textResult(text || \"(empty)\", history);\n },\n ),\n );\n\n return () => disposers.forEach((d) => d());\n}\n\nfunction serialize(entry: import(\"./undo-stack\").UndoEntry) {\n return {\n timestamp: entry.timestamp,\n bridgeId: entry.bridgeId,\n action: entry.action,\n label: entry.label,\n };\n}\n","/**\n * registerDocBridge — a GENERIC MCP bridge over a `@particle-academy/fancy-doc-commons`\n * `DocTree`. Give it an adapter (`{ get, set }`) and it generates, from the shared\n * op-spine, a full Human+ surface: uniform read tools + the canonical node op tools\n * (add / update / remove / move) under one verb lexicon, with **undo derived from\n * the reducer**, agent-activity broadcasts, unconditional `agent_undo/redo/history`,\n * and an optional **staged-write** (confirm / reject) channel — replacing the ~500-line\n * bespoke bridges (whiteboard/flow/artboard/…) with one builder. A surface adds its\n * domain ops (e.g. cms `set_style`) via `opTools` + a matching reducer.\n */\nimport { textResult, errorResult } from \"../mcp/server\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport type { JsonObject } from \"../mcp/types\";\nimport type { Bridge } from \"./types\";\nimport { wrapToolWithActivity } from \"../presence/wrap-tool-with-activity\";\nimport type { AgentTarget } from \"../presence/types\";\nimport { pushUndoEntry } from \"../undo/undo-stack\";\nimport { ensureUndoToolsRegistered } from \"../undo/undo-tools\";\nimport {\n treeReducer,\n childrenOf,\n descendantsOf,\n appendOrder,\n autoApply,\n type DocTree,\n type DocNode,\n type TreeOp,\n type DocReducer,\n type StagePolicy,\n} from \"@particle-academy/fancy-doc-commons\";\n\nconst DEFAULT_AGENT = { id: \"agent\", name: \"Agent\", color: \"#a855f7\" };\n\n/** Host-provided access to the document tree. */\nexport interface DocAdapter<N extends DocNode> {\n /** Read the current tree. */\n get(): DocTree<N>;\n /** Replace the tree — host wires this to its `onChange` / `setState`. */\n set(next: DocTree<N>): void;\n /** Optional fancy-screens screen id, for presence scoping. */\n screenId?: string;\n /** Mint a fresh, unique node id. Default: `<surface>-<n>`. */\n newId?(): string;\n}\n\n/**\n * A domain op tool beyond the built-in add/update/remove/move — lets a surface\n * expose its own ops (e.g. cms `set_style`) through the same undo + activity path.\n */\nexport interface DocOpTool<N extends DocNode, TOp> {\n /** Verb, prefixed with the surface (e.g. `set_style` → `cms_set_style`). */\n verb: string;\n description: string;\n properties: Record<string, unknown>;\n required: string[];\n /** Build the op from the args (or return `{ error }`). */\n build(args: JsonObject, tree: DocTree<N>): TOp | { error: string };\n /** Node id this op targets (for the activity target + undo label). */\n targetId?(args: JsonObject): string | undefined;\n}\n\nexport interface DocBridgeOptions<N extends DocNode, TOp = TreeOp<N>> {\n adapter: DocAdapter<N>;\n /** Tool-name prefix + activity kind (e.g. `\"cms\"` → `cms_add`, kind `\"cms\"`). */\n surface: string;\n agent?: { id: string; name?: string; color?: string };\n /** Reducer for reduce + invert. Default: the substrate `treeReducer<N>()`. */\n reducer?: DocReducer<DocTree<N>, TOp>;\n /** Build a full node from the core fields + props (fill surface defaults, e.g. `style`). */\n makeNode?: (core: { id: string; type: string; parent: string | null; order: string }, props: Record<string, unknown>) => N;\n /** Domain op tools beyond the built-ins. */\n opTools?: DocOpTool<N, TOp>[];\n /** Decide auto-apply vs. confirm per op. Default: everything auto-applies. */\n stagePolicy?: StagePolicy<TOp>;\n /** Fired when an op is staged pending human confirmation. */\n onPending?: (staged: { id: string; op: TOp; label: string }) => void;\n /** Summarize a node for describe/list. Default: id/type/parent + prop keys. */\n describeNode?: (node: N) => Record<string, unknown>;\n}\n\n/** Register the generic doc-surface bridge. Returns a {@link Bridge}. */\nexport function registerDocBridge<N extends DocNode, TOp = TreeOp<N>>(\n host: ToolHost,\n options: DocBridgeOptions<N, TOp>,\n): Bridge {\n const { adapter, surface } = options;\n const agent = { ...DEFAULT_AGENT, ...(options.agent ?? {}) };\n const reducer = (options.reducer ?? (treeReducer<N>() as unknown as DocReducer<DocTree<N>, TOp>));\n const stage = options.stagePolicy ?? (autoApply as StagePolicy<TOp>);\n const makeNode =\n options.makeNode ?? (({ id, type, parent, order }, props) => ({ id, type, parent, order, props }) as N);\n const describeNode =\n options.describeNode ?? ((n: N) => ({ id: n.id, type: n.type, parent: n.parent, props: Object.keys(n.props ?? {}) }));\n const disposers: Array<() => void> = [];\n\n // agent_undo / agent_redo / agent_history — always present (undo derives from\n // the reducer, so every doc surface gets working undo for free).\n ensureUndoToolsRegistered(host, { defaultAgentId: agent.id });\n\n let idSeq = 0;\n // The counter restarts with the bridge, so on a tree loaded from elsewhere\n // `surface-1` may well be taken. Skip past anything that already exists\n // rather than minting an id that silently overwrites a node.\n const mintId = () => {\n if (adapter.newId) return adapter.newId();\n const taken = adapter.get().nodes;\n let id: string;\n do id = `${surface}-${(idSeq += 1)}`;\n while (taken[id]);\n return id;\n };\n const target = (elementId?: string): AgentTarget => ({ kind: surface, screenId: adapter.screenId, elementId });\n\n // Staged ops awaiting confirmation.\n const pending = new Map<string, { op: TOp; label: string; targetId?: string }>();\n\n /** Apply an op immediately: reduce → set → push a snapshot-based undo entry. */\n function commit(op: TOp, label: string, targetId?: string): Record<string, unknown> {\n const prev = adapter.get();\n const next = reducer.reduce(prev, op);\n adapter.set(next);\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: surface,\n action: label,\n label,\n undo: () => adapter.set(prev),\n redo: () => adapter.set(next),\n });\n return { ok: true, id: targetId };\n }\n\n /**\n * Auto-apply, or stage for confirmation per the stage policy.\n *\n * The staged case reports the pending id under its OWN key. Returning it as\n * `id` — as this used to — collided with the node id every mutation already\n * reports, so `update`/`remove`/`move` overwrote it and left the agent holding\n * a node id that `confirm` does not accept. The staged write was unconfirmable\n * for three of the four canonical ops, and looked fine from the outside.\n */\n function submit(op: TOp, label: string, targetId?: string): { staged: boolean; id?: string; pendingId?: string } {\n if (stage(op) === \"confirm\") {\n const pendingId = `${surface}-pending-${(idSeq += 1)}`;\n pending.set(pendingId, { op, label, targetId });\n options.onPending?.({ id: pendingId, op, label });\n return { staged: true, id: targetId, pendingId };\n }\n commit(op, label, targetId);\n return { staged: false, id: targetId };\n }\n\n const reg = (\n verb: string,\n description: string,\n properties: Record<string, unknown>,\n required: string[],\n handler: (args: JsonObject) => Record<string, unknown> | Promise<Record<string, unknown>>,\n isMutation: boolean,\n resolveTarget?: (args: JsonObject, result: Record<string, unknown>) => AgentTarget | null,\n ): void => {\n const name = `${surface}_${verb}`;\n const wrapped = async (args: JsonObject) => {\n try {\n // `_text` is the human-facing line; the rest is structuredContent.\n const { _text, ...structured } = await handler(args);\n return textResult(typeof _text === \"string\" ? _text : name, structured);\n } catch (e) {\n return errorResult(e instanceof Error ? e.message : String(e));\n }\n };\n const final = isMutation\n ? wrapToolWithActivity(wrapped, {\n toolName: name,\n agent,\n kind: surface,\n screenId: adapter.screenId,\n resolveTarget: ({ args, result }) => {\n if ((result.structuredContent as JsonObject | undefined)?.staged) return null;\n return resolveTarget?.(args, (result.structuredContent as JsonObject) ?? {}) ?? target();\n },\n })\n : wrapped;\n disposers.push(\n host.registerTool(\n { name, description, inputSchema: { type: \"object\", properties: properties as never, required, additionalProperties: false } },\n final as never,\n ),\n );\n };\n\n // ── Read tools ──────────────────────────────────────────────────────────\n reg(\n \"describe\",\n `Summarize the ${surface} document: node count, roots, and the active surface. Call before reading or writing.`,\n {},\n [],\n () => {\n const tree = adapter.get();\n const ids = Object.keys(tree.nodes);\n return { nodeCount: ids.length, roots: childrenOf(tree, null).map((n) => n.id), _text: `${ids.length} nodes` };\n },\n false,\n );\n reg(\n \"get\",\n `Get the whole ${surface} document tree as JSON.`,\n {},\n [],\n () => ({ tree: adapter.get(), _text: \"full tree\" }),\n false,\n );\n reg(\n \"list\",\n \"List nodes (optionally the children of `parent`), in order.\",\n { parent: { type: [\"string\", \"null\"], description: \"Parent id, or null/omitted for roots.\" } },\n [],\n (args) => {\n const tree = adapter.get();\n const parent = typeof args.parent === \"string\" ? args.parent : null;\n return { nodes: childrenOf(tree, parent).map(describeNode), _text: `children of ${parent ?? \"root\"}` };\n },\n false,\n );\n reg(\n \"get_node\",\n \"Get one node by id.\",\n { id: { type: \"string\" } },\n [\"id\"],\n (args) => {\n const node = adapter.get().nodes[String(args.id)];\n if (!node) throw new Error(`No node ${args.id}`);\n return { node, _text: `node ${node.id}` };\n },\n false,\n );\n\n // ── Canonical op tools ──────────────────────────────────────────────────\n reg(\n \"add\",\n \"Insert a node. Returns its id. Appends under `parent` (or roots) unless `order` is given.\",\n {\n type: { type: \"string\", description: \"Node type discriminant.\" },\n parent: { type: [\"string\", \"null\"], description: \"Parent id, or null for a root.\" },\n props: { type: \"object\", description: \"JSON props bag.\" },\n order: { type: \"string\", description: \"Fractional order key (default: append).\" },\n id: {\n type: \"string\",\n description:\n \"Id for the new node. Supply a meaningful one if you intend to address this node later; omitted means one is minted for you. Must not already exist.\",\n },\n },\n [\"type\"],\n (args) => {\n const tree = adapter.get();\n const parent = typeof args.parent === \"string\" ? args.parent : null;\n // An agent that names the node names the handle it will use afterwards.\n // Minted ids are addressable too, just less memorable.\n const requested = typeof args.id === \"string\" ? args.id : undefined;\n if (requested !== undefined && tree.nodes[requested]) {\n throw new Error(`Node ${requested} already exists — pick a different id or update it instead`);\n }\n const id = requested ?? mintId();\n const order = typeof args.order === \"string\" ? args.order : appendOrder(tree, parent);\n const props = (args.props && typeof args.props === \"object\" ? args.props : {}) as Record<string, unknown>;\n const node = makeNode({ id, type: String(args.type), parent, order }, props);\n const res = submit({ t: \"insert\", node } as unknown as TOp, `add ${args.type} ${id}`, id);\n return { ...res, _text: res.staged ? `staged add ${id} — confirm ${res.pendingId}` : `added ${id}` };\n },\n true,\n (_args, result) => target(result.id as string | undefined),\n );\n reg(\n \"update\",\n \"Merge a props patch into a node.\",\n { id: { type: \"string\" }, patch: { type: \"object\" } },\n [\"id\", \"patch\"],\n (args) => {\n const id = String(args.id);\n if (!adapter.get().nodes[id]) throw new Error(`No node ${id}`);\n const patch = (args.patch && typeof args.patch === \"object\" ? args.patch : {}) as Record<string, unknown>;\n const res = submit({ t: \"set_props\", id, patch } as unknown as TOp, `update ${id}`, id);\n return { ...res, id, _text: res.staged ? `staged update ${id} — confirm ${res.pendingId}` : `updated ${id}` };\n },\n true,\n (args) => target(String(args.id)),\n );\n reg(\n \"remove\",\n \"Remove a node and its subtree.\",\n { id: { type: \"string\" } },\n [\"id\"],\n (args) => {\n const id = String(args.id);\n const tree = adapter.get();\n if (!tree.nodes[id]) throw new Error(`No node ${id}`);\n const count = descendantsOf(tree, id).length + 1;\n const res = submit({ t: \"remove\", id } as unknown as TOp, `remove ${id} (${count} node${count === 1 ? \"\" : \"s\"})`, id);\n return { ...res, id, removed: count, _text: res.staged ? `staged remove ${id} — confirm ${res.pendingId}` : `removed ${id}` };\n },\n true,\n (args) => target(String(args.id)),\n );\n reg(\n \"move\",\n \"Reparent + reorder a node.\",\n { id: { type: \"string\" }, parent: { type: [\"string\", \"null\"] }, order: { type: \"string\", description: \"Fractional order key (default: append under the new parent).\" } },\n [\"id\"],\n (args) => {\n const id = String(args.id);\n const tree = adapter.get();\n if (!tree.nodes[id]) throw new Error(`No node ${id}`);\n const parent = args.parent === null ? null : typeof args.parent === \"string\" ? args.parent : tree.nodes[id]!.parent;\n const order = typeof args.order === \"string\" ? args.order : appendOrder(tree, parent);\n const res = submit({ t: \"move\", id, parent, order } as unknown as TOp, `move ${id}`, id);\n return { ...res, id, _text: res.staged ? `staged move ${id} — confirm ${res.pendingId}` : `moved ${id}` };\n },\n true,\n (args) => target(String(args.id)),\n );\n\n // ── Domain op tools ─────────────────────────────────────────────────────\n for (const t of options.opTools ?? []) {\n reg(\n t.verb,\n t.description,\n t.properties,\n t.required,\n (args) => {\n const built = t.build(args, adapter.get());\n if (built && typeof built === \"object\" && \"error\" in built) throw new Error((built as { error: string }).error);\n const tid = t.targetId?.(args);\n const res = submit(built as TOp, `${t.verb} ${tid ?? \"\"}`.trim(), tid);\n return { ...res, id: tid, _text: res.staged ? `staged ${t.verb} — confirm ${res.pendingId}` : t.verb };\n },\n true,\n (args) => target(t.targetId?.(args)),\n );\n }\n\n // ── Staged-write confirm / reject ───────────────────────────────────────\n reg(\n \"confirm\",\n \"Apply a staged op. Pass the `pendingId` a staged mutation returned — not the node `id` it also returns.\",\n { id: { type: \"string\", description: \"The `pendingId` from a staged mutation.\" } },\n [\"id\"],\n (args) => {\n const id = String(args.id);\n const p = pending.get(id);\n if (!p) throw new Error(`No pending op ${id}`);\n pending.delete(id);\n commit(p.op, p.label, p.targetId);\n return { ok: true, applied: p.label, id: p.targetId, _text: `applied ${p.label}` };\n },\n true,\n (_args, result) => target(result.id as string | undefined),\n );\n reg(\n \"reject\",\n \"Discard a staged op. Pass the `pendingId` a staged mutation returned — not the node `id` it also returns.\",\n { id: { type: \"string\", description: \"The `pendingId` from a staged mutation.\" } },\n [\"id\"],\n (args) => {\n const id = String(args.id);\n const p = pending.get(id);\n if (!p) throw new Error(`No pending op ${id}`);\n pending.delete(id);\n return { ok: true, rejected: p.label, _text: `rejected ${p.label}` };\n },\n false,\n );\n\n return {\n id: surface,\n title: surface,\n dispose: () => {\n for (const d of disposers) d();\n pending.clear();\n },\n };\n}\n","/**\n * registerCmsBridge — the greenfield CMS agent bridge, built entirely on\n * {@link registerDocBridge}. cms had NO bridge before (its op-spine was\n * agent-ready but unwired); this is the §8-decided \"build registerCmsBridge on\n * registerDocBridge BEFORE deprecating ScreenSchema\" step.\n *\n * A CMS page is a `DocTree<StyledNode>` (fancy-doc-commons): the generic bridge\n * supplies `cms_describe/get/list/get_node` + `cms_add/update/remove/move` +\n * undo/activity/staging for free; this layer adds the two domain ops a page\n * needs — `cms_set_style` (per-node base StyleProps) and `cms_set_layout` — and a\n * reducer that handles them alongside the substrate tree ops.\n */\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport type { Bridge } from \"./types\";\nimport { registerDocBridge, type DocAdapter } from \"./doc\";\nimport {\n treeReducer,\n type DocReducer,\n type DocTree,\n type LayoutMode,\n type StyledNode,\n type StyleProps,\n type TreeOp,\n type StagePolicy,\n} from \"@particle-academy/fancy-doc-commons\";\n\n/** The CMS op union: the substrate tree ops + per-node style/layout. */\nexport type CmsOp =\n | TreeOp<StyledNode>\n | { t: \"set_style\"; id: string; patch: Partial<StyleProps> }\n | { t: \"set_layout\"; id: string; layout?: LayoutMode };\n\n/** A pure reducer over a `DocTree<StyledNode>` handling tree ops + style/layout. */\nexport function cmsReducer(): DocReducer<DocTree<StyledNode>, CmsOp> {\n const base = treeReducer<StyledNode>();\n return {\n reduce(doc, op) {\n if (op.t === \"set_style\") {\n const node = doc.nodes[op.id];\n if (!node) return doc;\n return { nodes: { ...doc.nodes, [op.id]: { ...node, style: { ...node.style, base: { ...node.style.base, ...op.patch } } } } };\n }\n if (op.t === \"set_layout\") {\n const node = doc.nodes[op.id];\n if (!node) return doc;\n return { nodes: { ...doc.nodes, [op.id]: { ...node, layout: op.layout } } };\n }\n return base.reduce(doc, op);\n },\n invert(doc, op) {\n if (op.t === \"set_style\") {\n const node = doc.nodes[op.id];\n if (!node) return [];\n const prev: Partial<StyleProps> = {};\n for (const k in op.patch) (prev as Record<string, unknown>)[k as keyof StyleProps] = node.style.base[k as keyof StyleProps];\n return [{ t: \"set_style\", id: op.id, patch: prev }];\n }\n if (op.t === \"set_layout\") {\n const node = doc.nodes[op.id];\n if (!node) return [];\n return [{ t: \"set_layout\", id: op.id, layout: node.layout }];\n }\n return base.invert(doc, op) as CmsOp[];\n },\n };\n}\n\nexport interface CmsBridgeOptions {\n adapter: DocAdapter<StyledNode>;\n agent?: { id: string; name?: string; color?: string };\n /** Auto-apply vs. confirm per op (trust-but-verify). Default: auto. */\n stagePolicy?: StagePolicy<CmsOp>;\n onPending?: (staged: { id: string; op: CmsOp; label: string }) => void;\n}\n\n/** Register the CMS bridge (prefix `cms_`) over a `DocTree<StyledNode>`. */\nexport function registerCmsBridge(host: ToolHost, options: CmsBridgeOptions): Bridge {\n return registerDocBridge<StyledNode, CmsOp>(host, {\n adapter: options.adapter,\n surface: \"cms\",\n agent: options.agent,\n reducer: cmsReducer(),\n stagePolicy: options.stagePolicy,\n onPending: options.onPending,\n // New nodes get an empty base style so they satisfy StyledNode.\n makeNode: ({ id, type, parent, order }, props) => ({ id, type, parent, order, props, style: { base: {} } }),\n describeNode: (n) => ({ id: n.id, type: n.type, parent: n.parent, layout: n.layout }),\n opTools: [\n {\n verb: \"set_style\",\n description: \"Merge a StyleProps patch into a node's base style (color, background, padding, fontSize, gap, …).\",\n properties: { id: { type: \"string\" }, patch: { type: \"object\", description: \"Partial StyleProps.\" } },\n required: [\"id\", \"patch\"],\n build: (args, tree) => {\n const id = String(args.id);\n if (!tree.nodes[id]) return { error: `No node ${id}` };\n return { t: \"set_style\", id, patch: (args.patch && typeof args.patch === \"object\" ? args.patch : {}) as Partial<StyleProps> };\n },\n targetId: (args) => String(args.id),\n },\n {\n verb: \"set_layout\",\n description: \"Set a container node's layout mode (free | stack | grid).\",\n properties: { id: { type: \"string\" }, layout: { type: \"string\", enum: [\"free\", \"stack\", \"grid\"] } },\n required: [\"id\"],\n build: (args, tree) => {\n const id = String(args.id);\n if (!tree.nodes[id]) return { error: `No node ${id}` };\n return { t: \"set_layout\", id, layout: args.layout as LayoutMode | undefined };\n },\n targetId: (args) => String(args.id),\n },\n ],\n });\n}\n"]}
|
package/dist/bridges-cms.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { cmsReducer, registerCmsBridge } from './chunk-
|
|
2
|
-
import './chunk-
|
|
3
|
-
import './chunk-
|
|
1
|
+
export { cmsReducer, registerCmsBridge } from './chunk-SWWJUOCY.js';
|
|
2
|
+
import './chunk-3HVYUMQF.js';
|
|
3
|
+
import './chunk-R4XXOGQH.js';
|
|
4
4
|
import './chunk-2VENWGLZ.js';
|
|
5
5
|
import './chunk-C3TYI5TJ.js';
|
|
6
|
-
import './chunk-
|
|
6
|
+
import './chunk-CZV3WUW5.js';
|
|
7
7
|
//# sourceMappingURL=bridges-cms.js.map
|
|
8
8
|
//# sourceMappingURL=bridges-cms.js.map
|