@particle-academy/agent-integrations 0.31.0 → 0.33.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/dist/bridges/flow.d.cts +38 -1
- package/dist/bridges/flow.d.ts +38 -1
- package/dist/bridges-files.cjs +1 -1
- package/dist/bridges-files.cjs.map +1 -1
- package/dist/bridges-files.js +1 -1
- package/dist/bridges-flow.cjs +97 -31
- package/dist/bridges-flow.cjs.map +1 -1
- package/dist/bridges-flow.js +97 -31
- package/dist/bridges-flow.js.map +1 -1
- package/dist/{chunk-HRHC5GM5.js → chunk-A25E22WW.js} +3 -3
- package/dist/{chunk-HRHC5GM5.js.map → chunk-A25E22WW.js.map} +1 -1
- package/dist/{chunk-HSI5RVF4.js → chunk-SJTLTITO.js} +29 -2
- package/dist/chunk-SJTLTITO.js.map +1 -0
- package/dist/components-shared-whiteboard.cjs +27 -0
- package/dist/components-shared-whiteboard.cjs.map +1 -1
- package/dist/components-shared-whiteboard.js +1 -1
- package/dist/index.cjs +28 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +15 -1
- package/dist/index.d.ts +15 -1
- package/dist/index.js +3 -3
- package/dist/styles.css +46 -0
- package/dist/styles.css.map +1 -1
- package/package.json +9 -5
- package/dist/chunk-HSI5RVF4.js.map +0 -1
package/dist/bridges/flow.d.cts
CHANGED
|
@@ -52,6 +52,20 @@ type FlowBridgeAdapter = {
|
|
|
52
52
|
/** Optional: set per-node status text without going through the runner
|
|
53
53
|
* (useful for agents narrating). */
|
|
54
54
|
setNodeStatus?: (id: string, status: NodeRunStatus, text?: string) => void;
|
|
55
|
+
/**
|
|
56
|
+
* Human confirm gate for staged actions (trust-but-verify). When
|
|
57
|
+
* `pendingMode` is on, the bridge calls this before a destructive action;
|
|
58
|
+
* return false to decline. Wire it to a human control.
|
|
59
|
+
*/
|
|
60
|
+
confirm?: (request: FlowConfirmRequest) => Promise<boolean> | boolean;
|
|
61
|
+
};
|
|
62
|
+
/** What a staged (pendingMode) flow action asks a human to approve. */
|
|
63
|
+
type FlowConfirmRequest = {
|
|
64
|
+
action: "delete_node";
|
|
65
|
+
nodeId: string;
|
|
66
|
+
label?: string;
|
|
67
|
+
} | {
|
|
68
|
+
action: "run";
|
|
55
69
|
};
|
|
56
70
|
type FlowBridgeOptions = {
|
|
57
71
|
adapter: FlowBridgeAdapter;
|
|
@@ -61,6 +75,29 @@ type FlowBridgeOptions = {
|
|
|
61
75
|
name?: string;
|
|
62
76
|
color?: string;
|
|
63
77
|
};
|
|
78
|
+
/**
|
|
79
|
+
* Enforce port-type compatibility on `flow_connect`, using fancy-flow's
|
|
80
|
+
* `createConnectionValidator` — the SAME rule `<FlowCanvas>` applies, so an
|
|
81
|
+
* agent can't build an edge the canvas would refuse. `true` (default) uses the
|
|
82
|
+
* default rule (untyped ports permissive); pass `ConnectionValidatorOptions`
|
|
83
|
+
* to tune it, or `false` to disable. No-ops if fancy-flow (>= 0.18.0) isn't
|
|
84
|
+
* importable — the bridge falls back to the existence-only check.
|
|
85
|
+
*/
|
|
86
|
+
validateConnections?: boolean | Record<string, unknown>;
|
|
87
|
+
/**
|
|
88
|
+
* Validate a node's config against its kind's `configSchema` on
|
|
89
|
+
* `flow_add_node` / `flow_update_node`. `"reject"` (default) refuses an
|
|
90
|
+
* invalid write; `"warn"` applies it but reports the issues; `"off"` skips.
|
|
91
|
+
* No-ops for the legacy 6-pack (no schema) and when fancy-flow isn't importable.
|
|
92
|
+
*/
|
|
93
|
+
validateConfig?: "reject" | "warn" | "off";
|
|
94
|
+
/**
|
|
95
|
+
* Stage destructive/human-visible actions (`flow_delete_node`, `flow_run`) for
|
|
96
|
+
* human confirmation via `adapter.confirm` instead of applying immediately.
|
|
97
|
+
* **Default: OFF** — flow authoring is high-frequency, unlike a form submit.
|
|
98
|
+
* When on without an `adapter.confirm`, the action proceeds (nothing to gate).
|
|
99
|
+
*/
|
|
100
|
+
pendingMode?: boolean;
|
|
64
101
|
};
|
|
65
102
|
/**
|
|
66
103
|
* registerFlowBridge — wires an MCP tool set against a fancy-flow editor's
|
|
@@ -70,4 +107,4 @@ type FlowBridgeOptions = {
|
|
|
70
107
|
*/
|
|
71
108
|
declare function registerFlowBridge(host: ToolHost, options: FlowBridgeOptions): Bridge;
|
|
72
109
|
|
|
73
|
-
export { type FlowBridgeAdapter, type FlowBridgeOptions, registerFlowBridge };
|
|
110
|
+
export { type FlowBridgeAdapter, type FlowBridgeOptions, type FlowConfirmRequest, registerFlowBridge };
|
package/dist/bridges/flow.d.ts
CHANGED
|
@@ -52,6 +52,20 @@ type FlowBridgeAdapter = {
|
|
|
52
52
|
/** Optional: set per-node status text without going through the runner
|
|
53
53
|
* (useful for agents narrating). */
|
|
54
54
|
setNodeStatus?: (id: string, status: NodeRunStatus, text?: string) => void;
|
|
55
|
+
/**
|
|
56
|
+
* Human confirm gate for staged actions (trust-but-verify). When
|
|
57
|
+
* `pendingMode` is on, the bridge calls this before a destructive action;
|
|
58
|
+
* return false to decline. Wire it to a human control.
|
|
59
|
+
*/
|
|
60
|
+
confirm?: (request: FlowConfirmRequest) => Promise<boolean> | boolean;
|
|
61
|
+
};
|
|
62
|
+
/** What a staged (pendingMode) flow action asks a human to approve. */
|
|
63
|
+
type FlowConfirmRequest = {
|
|
64
|
+
action: "delete_node";
|
|
65
|
+
nodeId: string;
|
|
66
|
+
label?: string;
|
|
67
|
+
} | {
|
|
68
|
+
action: "run";
|
|
55
69
|
};
|
|
56
70
|
type FlowBridgeOptions = {
|
|
57
71
|
adapter: FlowBridgeAdapter;
|
|
@@ -61,6 +75,29 @@ type FlowBridgeOptions = {
|
|
|
61
75
|
name?: string;
|
|
62
76
|
color?: string;
|
|
63
77
|
};
|
|
78
|
+
/**
|
|
79
|
+
* Enforce port-type compatibility on `flow_connect`, using fancy-flow's
|
|
80
|
+
* `createConnectionValidator` — the SAME rule `<FlowCanvas>` applies, so an
|
|
81
|
+
* agent can't build an edge the canvas would refuse. `true` (default) uses the
|
|
82
|
+
* default rule (untyped ports permissive); pass `ConnectionValidatorOptions`
|
|
83
|
+
* to tune it, or `false` to disable. No-ops if fancy-flow (>= 0.18.0) isn't
|
|
84
|
+
* importable — the bridge falls back to the existence-only check.
|
|
85
|
+
*/
|
|
86
|
+
validateConnections?: boolean | Record<string, unknown>;
|
|
87
|
+
/**
|
|
88
|
+
* Validate a node's config against its kind's `configSchema` on
|
|
89
|
+
* `flow_add_node` / `flow_update_node`. `"reject"` (default) refuses an
|
|
90
|
+
* invalid write; `"warn"` applies it but reports the issues; `"off"` skips.
|
|
91
|
+
* No-ops for the legacy 6-pack (no schema) and when fancy-flow isn't importable.
|
|
92
|
+
*/
|
|
93
|
+
validateConfig?: "reject" | "warn" | "off";
|
|
94
|
+
/**
|
|
95
|
+
* Stage destructive/human-visible actions (`flow_delete_node`, `flow_run`) for
|
|
96
|
+
* human confirmation via `adapter.confirm` instead of applying immediately.
|
|
97
|
+
* **Default: OFF** — flow authoring is high-frequency, unlike a form submit.
|
|
98
|
+
* When on without an `adapter.confirm`, the action proceeds (nothing to gate).
|
|
99
|
+
*/
|
|
100
|
+
pendingMode?: boolean;
|
|
64
101
|
};
|
|
65
102
|
/**
|
|
66
103
|
* registerFlowBridge — wires an MCP tool set against a fancy-flow editor's
|
|
@@ -70,4 +107,4 @@ type FlowBridgeOptions = {
|
|
|
70
107
|
*/
|
|
71
108
|
declare function registerFlowBridge(host: ToolHost, options: FlowBridgeOptions): Bridge;
|
|
72
109
|
|
|
73
|
-
export { type FlowBridgeAdapter, type FlowBridgeOptions, registerFlowBridge };
|
|
110
|
+
export { type FlowBridgeAdapter, type FlowBridgeOptions, type FlowConfirmRequest, registerFlowBridge };
|
package/dist/bridges-files.cjs
CHANGED
|
@@ -132,7 +132,7 @@ function assertPathWithinRoot(root, path) {
|
|
|
132
132
|
}
|
|
133
133
|
const isAbsolute = /^([A-Za-z]:)?[\\/]/.test(path) || /^[A-Za-z]:/.test(path);
|
|
134
134
|
if (isAbsolute) {
|
|
135
|
-
const norm = (p2) => p2.replace(/[\\/]+/g, "/").replace(
|
|
135
|
+
const norm = (p2) => p2.replace(/[\\/]+/g, "/").replace(/\/$/, "").toLowerCase();
|
|
136
136
|
const r = norm(root);
|
|
137
137
|
const p = norm(path);
|
|
138
138
|
if (p !== r && !p.startsWith(r + "/")) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/server.ts","../src/presence/wrap-tool-with-activity.ts","../src/undo/undo-tools.ts","../src/bridges/files.ts"],"names":["emitActivity","undoOne","redoOne","readHistory","p","pushUndoEntry"],"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,IAAA,EAAM,QAAA,EAAU,QAAQ,QAAA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AAI,OAAA,CAAQ,OAAA,EAAS,CAAA;AAE/E,MAAA,MAAM,KAAA,GACJ,IAAA,CAAK,KAAA,KAAU,KAAA,CAAA,GAAY,KAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,GAAA,CAAI,oBAAoB,GAAA,CAAI,IAAA,CAAK,KAAK,CAAC,CAAC,CAAA,GAAI,KAAA,CAAA;AAC1F,MAAA,MAAM,IAAA,GAAO,MAAM,OAAA,CAAQ,eAAA,CAAgB,MAAM,KAAK,CAAA;AACtD,MAAA,MAAM,QAAQ,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA,GAAI,KAAK,MAAA,GAAS,CAAA;AAClD,MAAA,OAAO,UAAA,CAAW,CAAA,YAAA,EAAe,IAAI,CAAA,EAAA,EAAK,KAAK,kBAAkB,KAAA,KAAU,CAAA,GAAI,GAAA,GAAM,KAAK,CAAA,CAAA,CAAA,EAAK;AAAA,QAC7F,IAAA;AAAA,QACA,QAAA,EAAU;AAAA,OACX,CAAA;AAAA,IACH,CAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,OAAA;AAAA,IACJ,KAAA,EAAO,OAAA;AAAA,IACP,SAAS,MAAM;AACb,MAAA,KAAA,MAAW,CAAA,IAAK,WAAW,CAAA,EAAE;AAAA,IAC/B;AAAA,GACF;AACF","file":"bridges-files.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, `Unknown tool: ${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","// Loose types so this bridge builds standalone without a hard dep on\n// @particle-academy/react-fancy. Hosts using FileBrowser pass its own\n// FileEntry / FileSnapshotNode values straight through — the shapes match.\ntype FileKind = \"file\" | \"dir\";\ntype FileEntry = {\n path: string;\n name: string;\n kind: FileKind;\n size?: number;\n mtime?: string;\n hasChildren?: boolean;\n disabled?: boolean;\n};\ntype FileSnapshotNode = FileEntry & { children?: FileSnapshotNode[] };\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 as FilesAgentTarget } from \"../presence/types\";\nimport { pushUndoEntry } from \"../undo/undo-stack\";\nimport { ensureUndoToolsRegistered } from \"../undo/undo-tools\";\n\n/**\n * Adapter the host provides — getters/setters over the SAME controlled props it\n * passes to react-fancy's `<FileBrowser>` (`value`/`path`/`expandedPaths`), plus\n * `listChildren` (wire to your `provider.loadChildren` or the loaded cache) and,\n * for snapshot mode, an optional `requestSnapshot`.\n */\nexport type FilesBridgeAdapter = {\n /** Current directory (the `path` prop). */\n getPath: () => string;\n setPath: (path: string) => void;\n /** Selected path(s) — normalize FileBrowser's `value` (string | string[] | null) to an array. */\n getSelection: () => string[];\n setSelection: (paths: string[]) => void;\n /** Expanded folder paths (the `expandedPaths` prop). */\n getExpanded: () => string[];\n setExpanded: (next: string[] | ((prev: string[]) => string[])) => void;\n /** Direct children of a path — wire to `provider.loadChildren` (async) or the loaded/snapshot cache. */\n listChildren: (path: string) => Promise<FileEntry[]> | FileEntry[];\n /** Optional (snapshot mode): fetch/refresh a snapshot subtree so an agent can pull remote state on demand. */\n requestSnapshot?: (path: string, depth?: number) => Promise<FileSnapshotNode[]> | FileSnapshotNode[];\n};\n\nexport type FilesBridgeOptions = {\n adapter: FilesBridgeAdapter;\n /** Identity tagged onto agent-driven actions. */\n agent?: { id: string; name?: string; color?: string };\n /**\n * Optional containment root. When set, every agent-supplied path is checked\n * with {@link assertPathWithinRoot} before it reaches the adapter: a `..`\n * segment or an absolute path outside `root` is rejected. This is a\n * fail-closed, string-level guard (no filesystem access — the bridge runs in\n * the browser). It is NOT sufficient on its own: a host over a real\n * filesystem MUST additionally resolve symlinks/junctions (realpath) and\n * enforce the root, because a link under `root` can still point outside it.\n * When `root` is unset the bridge does no containment and the adapter is\n * SOLELY responsible for sandboxing what `listChildren`/`requestSnapshot` expose.\n */\n root?: string;\n};\n\nconst DEFAULT_AGENT = { id: \"agent\", name: \"Agent\", color: \"#a855f7\" };\n\n/** Host default cap on snapshot recursion, so an agent can't request an\n * unbounded deep walk. */\nconst MAX_SNAPSHOT_DEPTH = 8;\n\n/**\n * Fail-closed, filesystem-free path containment. Throws when `path` contains a\n * `..` segment, or is absolute and not within `root`. Relative paths without\n * `..` pass (resolved within root by the host). String-level only — see the\n * `root` docs: hosts over a real fs must ALSO realpath to defeat symlinks.\n */\nexport function assertPathWithinRoot(root: string, path: string): void {\n const segments = path.replace(/[\\\\/]+/g, \"/\").split(\"/\");\n if (segments.includes(\"..\")) {\n throw new Error(`Path may not contain '..': ${path}`);\n }\n const isAbsolute = /^([A-Za-z]:)?[\\\\/]/.test(path) || /^[A-Za-z]:/.test(path);\n if (isAbsolute) {\n const norm = (p: string): string => p.replace(/[\\\\/]+/g, \"/\").replace(/\\/+$/, \"\").toLowerCase();\n const r = norm(root);\n const p = norm(path);\n if (p !== r && !p.startsWith(r + \"/\")) {\n throw new Error(`Path escapes the configured root: ${path}`);\n }\n }\n}\n\nconst str = (v: unknown, fallback = \"\"): string => (typeof v === \"string\" ? v : fallback);\nconst num = (v: unknown, fallback?: number): number =>\n typeof v === \"number\" && Number.isFinite(v) ? v : fallback ?? 0;\nconst asPaths = (v: unknown): string[] => {\n if (typeof v === \"string\") {\n return [v];\n }\n if (Array.isArray(v)) {\n return v.filter((x): x is string => typeof x === \"string\");\n }\n return [];\n};\n\n/**\n * registerFilesBridge — an MCP tool set over a react-fancy `<FileBrowser>`'s\n * controlled state, so a human and an agent share one file browser. The agent\n * lists a folder's children, navigates, expands/collapses folders, selects\n * entries, and (in snapshot mode) requests a fresh subtree — driving the same\n * `value`/`path`/`expandedPaths` props, no DOM scraping. Every mutation\n * broadcasts AgentActivity (presence) and pushes an undo entry. Mirrors the\n * map / whiteboard / flow bridges in shape.\n *\n * Read-only browse in v1: no content preview (pair with fancy-code's\n * FileViewer) and no write ops (rename/delete/upload) — those arrive later\n * behind a pendingMode-gated iteration.\n */\nexport function registerFilesBridge(host: ToolHost, options: FilesBridgeOptions): Bridge {\n const { adapter } = options;\n const agent = { ...DEFAULT_AGENT, ...(options.agent ?? {}) };\n const disposers: Array<() => void> = [];\n\n // Reject traversal / out-of-root paths before they reach the adapter (no-op\n // when no root is configured — the adapter is then responsible for sandboxing).\n const guard = (path: string): string => {\n if (options.root !== undefined) assertPathWithinRoot(options.root, path);\n return path;\n };\n\n // Register agent_undo / agent_redo / agent_history once per host. Idempotent.\n ensureUndoToolsRegistered(host, { defaultAgentId: agent.id });\n\n const fTarget = (args: any, _result: any): FilesAgentTarget => ({\n kind: \"files\",\n elementId: (args?.path as string | undefined) ?? undefined,\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 resolveTarget?: (args: JsonObject, result: any) => FilesAgentTarget | null,\n ) => {\n const wrapped = async (args: JsonObject) => {\n try {\n return await handler(args);\n } catch (e) {\n return errorResult(e instanceof Error ? e.message : String(e));\n }\n };\n const final = resolveTarget\n ? wrapToolWithActivity(wrapped, {\n toolName: name,\n agent: { id: agent.id, name: agent.name, color: agent.color },\n kind: \"files\",\n resolveTarget: ({ args, result }) => resolveTarget(args, result),\n })\n : wrapped;\n disposers.push(\n host.registerTool(\n {\n name,\n description,\n inputSchema: {\n type: \"object\",\n properties: properties as any,\n required,\n additionalProperties: false,\n },\n },\n final as any,\n ),\n );\n };\n\n // ───────────── Read ─────────────\n\n reg(\n \"files_get_state\",\n \"Get the file browser's current directory, selected path(s), and expanded folders.\",\n {},\n [],\n () => {\n const state = {\n path: adapter.getPath(),\n selected: adapter.getSelection(),\n expanded: adapter.getExpanded(),\n };\n return textResult(JSON.stringify(state, null, 2), state);\n },\n );\n\n reg(\n \"files_list\",\n \"List the direct children of a folder (files + subfolders). Omit `path` for the current directory. Loads lazily from the host's provider/snapshot — never an eager tree walk.\",\n { path: { type: \"string\", description: \"Folder path to list; defaults to the current directory.\" } },\n [],\n async (args) => {\n const path = guard(args.path !== undefined ? str(args.path) : adapter.getPath());\n const entries = await adapter.listChildren(path);\n const summary = entries.map((e) => ({\n path: e.path,\n name: e.name,\n kind: e.kind,\n ...(e.size !== undefined ? { size: e.size } : {}),\n ...(e.mtime !== undefined ? { mtime: e.mtime } : {}),\n }));\n const text =\n summary.map((e) => `${e.kind === \"dir\" ? \"📁\" : \"📄\"} ${e.path}`).join(\"\\n\") ||\n `(empty: ${path})`;\n return textResult(text, { path, entries: summary });\n },\n );\n\n // ───────────── Navigation ─────────────\n\n reg(\n \"files_navigate\",\n \"Set the current directory (as if the user clicked a breadcrumb or opened a folder).\",\n { path: { type: \"string\" } },\n [\"path\"],\n (args) => {\n const path = guard(str(args.path));\n const prev = adapter.getPath();\n adapter.setPath(path);\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: \"files\",\n action: \"files_navigate\",\n label: `Navigated to ${path}`,\n undo: () => adapter.setPath(prev),\n redo: () => adapter.setPath(path),\n });\n return textResult(`Current directory → ${path}`, { path });\n },\n fTarget,\n );\n\n // ───────────── Expansion ─────────────\n\n reg(\n \"files_expand\",\n \"Expand a folder in the tree (loads its children if needed).\",\n { path: { type: \"string\" } },\n [\"path\"],\n (args) => {\n const path = guard(str(args.path));\n if (adapter.getExpanded().includes(path)) {\n return textResult(`${path} already expanded`, { path, expanded: true });\n }\n adapter.setExpanded((prev) => [...prev, path]);\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: \"files\",\n action: \"files_expand\",\n label: `Expanded ${path}`,\n undo: () => adapter.setExpanded((prev) => prev.filter((p) => p !== path)),\n redo: () => adapter.setExpanded((prev) => (prev.includes(path) ? prev : [...prev, path])),\n });\n return textResult(`Expanded ${path}`, { path, expanded: true });\n },\n fTarget,\n );\n\n reg(\n \"files_collapse\",\n \"Collapse a folder in the tree.\",\n { path: { type: \"string\" } },\n [\"path\"],\n (args) => {\n const path = guard(str(args.path));\n if (!adapter.getExpanded().includes(path)) {\n return textResult(`${path} already collapsed`, { path, expanded: false });\n }\n adapter.setExpanded((prev) => prev.filter((p) => p !== path));\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: \"files\",\n action: \"files_collapse\",\n label: `Collapsed ${path}`,\n undo: () => adapter.setExpanded((prev) => (prev.includes(path) ? prev : [...prev, path])),\n redo: () => adapter.setExpanded((prev) => prev.filter((p) => p !== path)),\n });\n return textResult(`Collapsed ${path}`, { path, expanded: false });\n },\n fTarget,\n );\n\n // ───────────── Selection ─────────────\n\n reg(\n \"files_select\",\n \"Set the selection to the given path(s). Pass a single `path`, or `paths` for a multi-select browser; either empty clears the selection.\",\n {\n path: { type: \"string\", description: \"A single path to select.\" },\n paths: { type: \"array\", items: { type: \"string\" }, description: \"Multiple paths (multi-select browsers).\" },\n },\n [],\n (args) => {\n const next = (args.paths !== undefined ? asPaths(args.paths) : asPaths(args.path)).map(guard);\n const prev = adapter.getSelection();\n adapter.setSelection(next);\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: \"files\",\n action: \"files_select\",\n label: next.length ? `Selected ${next.join(\", \")}` : \"Cleared selection\",\n undo: () => adapter.setSelection(prev),\n redo: () => adapter.setSelection(next),\n });\n return textResult(next.length ? `Selected ${next.join(\", \")}` : \"Cleared selection\", {\n selected: next,\n });\n },\n fTarget,\n );\n\n // ───────────── Snapshot (streamed remote trees) ─────────────\n\n reg(\n \"files_request_snapshot\",\n \"Request a fresh snapshot subtree rooted at `path` (snapshot mode) — e.g. to pull a remote machine's current tree. Requires the host to wire requestSnapshot.\",\n {\n path: { type: \"string\", description: \"Root of the subtree; defaults to the current directory.\" },\n depth: { type: \"number\", description: \"How many levels deep to materialize (host-defined default).\" },\n },\n [],\n async (args) => {\n if (!adapter.requestSnapshot) {\n return errorResult(\"Host did not wire requestSnapshot (snapshot mode not enabled).\");\n }\n const path = guard(args.path !== undefined ? str(args.path) : adapter.getPath());\n // Clamp depth so an agent can't demand an unbounded recursive walk.\n const depth =\n args.depth !== undefined ? Math.max(0, Math.min(MAX_SNAPSHOT_DEPTH, num(args.depth))) : undefined;\n const tree = await adapter.requestSnapshot(path, depth);\n const count = Array.isArray(tree) ? tree.length : 0;\n return textResult(`Snapshot of ${path}: ${count} top-level entr${count === 1 ? \"y\" : \"ies\"}.`, {\n path,\n snapshot: tree,\n });\n },\n fTarget,\n );\n\n return {\n id: \"files\",\n title: \"Files\",\n dispose: () => {\n for (const d of disposers) d();\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/files.ts"],"names":["emitActivity","undoOne","redoOne","readHistory","p","pushUndoEntry"],"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,CAA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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, `Unknown tool: ${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","// Loose types so this bridge builds standalone without a hard dep on\n// @particle-academy/react-fancy. Hosts using FileBrowser pass its own\n// FileEntry / FileSnapshotNode values straight through — the shapes match.\ntype FileKind = \"file\" | \"dir\";\ntype FileEntry = {\n path: string;\n name: string;\n kind: FileKind;\n size?: number;\n mtime?: string;\n hasChildren?: boolean;\n disabled?: boolean;\n};\ntype FileSnapshotNode = FileEntry & { children?: FileSnapshotNode[] };\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 as FilesAgentTarget } from \"../presence/types\";\nimport { pushUndoEntry } from \"../undo/undo-stack\";\nimport { ensureUndoToolsRegistered } from \"../undo/undo-tools\";\n\n/**\n * Adapter the host provides — getters/setters over the SAME controlled props it\n * passes to react-fancy's `<FileBrowser>` (`value`/`path`/`expandedPaths`), plus\n * `listChildren` (wire to your `provider.loadChildren` or the loaded cache) and,\n * for snapshot mode, an optional `requestSnapshot`.\n */\nexport type FilesBridgeAdapter = {\n /** Current directory (the `path` prop). */\n getPath: () => string;\n setPath: (path: string) => void;\n /** Selected path(s) — normalize FileBrowser's `value` (string | string[] | null) to an array. */\n getSelection: () => string[];\n setSelection: (paths: string[]) => void;\n /** Expanded folder paths (the `expandedPaths` prop). */\n getExpanded: () => string[];\n setExpanded: (next: string[] | ((prev: string[]) => string[])) => void;\n /** Direct children of a path — wire to `provider.loadChildren` (async) or the loaded/snapshot cache. */\n listChildren: (path: string) => Promise<FileEntry[]> | FileEntry[];\n /** Optional (snapshot mode): fetch/refresh a snapshot subtree so an agent can pull remote state on demand. */\n requestSnapshot?: (path: string, depth?: number) => Promise<FileSnapshotNode[]> | FileSnapshotNode[];\n};\n\nexport type FilesBridgeOptions = {\n adapter: FilesBridgeAdapter;\n /** Identity tagged onto agent-driven actions. */\n agent?: { id: string; name?: string; color?: string };\n /**\n * Optional containment root. When set, every agent-supplied path is checked\n * with {@link assertPathWithinRoot} before it reaches the adapter: a `..`\n * segment or an absolute path outside `root` is rejected. This is a\n * fail-closed, string-level guard (no filesystem access — the bridge runs in\n * the browser). It is NOT sufficient on its own: a host over a real\n * filesystem MUST additionally resolve symlinks/junctions (realpath) and\n * enforce the root, because a link under `root` can still point outside it.\n * When `root` is unset the bridge does no containment and the adapter is\n * SOLELY responsible for sandboxing what `listChildren`/`requestSnapshot` expose.\n */\n root?: string;\n};\n\nconst DEFAULT_AGENT = { id: \"agent\", name: \"Agent\", color: \"#a855f7\" };\n\n/** Host default cap on snapshot recursion, so an agent can't request an\n * unbounded deep walk. */\nconst MAX_SNAPSHOT_DEPTH = 8;\n\n/**\n * Fail-closed, filesystem-free path containment. Throws when `path` contains a\n * `..` segment, or is absolute and not within `root`. Relative paths without\n * `..` pass (resolved within root by the host). String-level only — see the\n * `root` docs: hosts over a real fs must ALSO realpath to defeat symlinks.\n */\nexport function assertPathWithinRoot(root: string, path: string): void {\n const segments = path.replace(/[\\\\/]+/g, \"/\").split(\"/\");\n if (segments.includes(\"..\")) {\n throw new Error(`Path may not contain '..': ${path}`);\n }\n const isAbsolute = /^([A-Za-z]:)?[\\\\/]/.test(path) || /^[A-Za-z]:/.test(path);\n if (isAbsolute) {\n // Strip a trailing slash with `\\/$`, NOT `\\/+$`. The quantified `\\/+$`\n // is a polynomial-ReDoS on paths with many slashes (CodeQL js/polynomial-\n // redos), and the `+` is redundant here: the preceding\n // `.replace(/[\\\\/]+/g, \"/\")` has already collapsed every slash-run to a\n // single `/`, so at most one trailing slash can remain. Non-quantified\n // `\\/$` matches the same input in linear time.\n const norm = (p: string): string => p.replace(/[\\\\/]+/g, \"/\").replace(/\\/$/, \"\").toLowerCase();\n const r = norm(root);\n const p = norm(path);\n if (p !== r && !p.startsWith(r + \"/\")) {\n throw new Error(`Path escapes the configured root: ${path}`);\n }\n }\n}\n\nconst str = (v: unknown, fallback = \"\"): string => (typeof v === \"string\" ? v : fallback);\nconst num = (v: unknown, fallback?: number): number =>\n typeof v === \"number\" && Number.isFinite(v) ? v : fallback ?? 0;\nconst asPaths = (v: unknown): string[] => {\n if (typeof v === \"string\") {\n return [v];\n }\n if (Array.isArray(v)) {\n return v.filter((x): x is string => typeof x === \"string\");\n }\n return [];\n};\n\n/**\n * registerFilesBridge — an MCP tool set over a react-fancy `<FileBrowser>`'s\n * controlled state, so a human and an agent share one file browser. The agent\n * lists a folder's children, navigates, expands/collapses folders, selects\n * entries, and (in snapshot mode) requests a fresh subtree — driving the same\n * `value`/`path`/`expandedPaths` props, no DOM scraping. Every mutation\n * broadcasts AgentActivity (presence) and pushes an undo entry. Mirrors the\n * map / whiteboard / flow bridges in shape.\n *\n * Read-only browse in v1: no content preview (pair with fancy-code's\n * FileViewer) and no write ops (rename/delete/upload) — those arrive later\n * behind a pendingMode-gated iteration.\n */\nexport function registerFilesBridge(host: ToolHost, options: FilesBridgeOptions): Bridge {\n const { adapter } = options;\n const agent = { ...DEFAULT_AGENT, ...(options.agent ?? {}) };\n const disposers: Array<() => void> = [];\n\n // Reject traversal / out-of-root paths before they reach the adapter (no-op\n // when no root is configured — the adapter is then responsible for sandboxing).\n const guard = (path: string): string => {\n if (options.root !== undefined) assertPathWithinRoot(options.root, path);\n return path;\n };\n\n // Register agent_undo / agent_redo / agent_history once per host. Idempotent.\n ensureUndoToolsRegistered(host, { defaultAgentId: agent.id });\n\n const fTarget = (args: any, _result: any): FilesAgentTarget => ({\n kind: \"files\",\n elementId: (args?.path as string | undefined) ?? undefined,\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 resolveTarget?: (args: JsonObject, result: any) => FilesAgentTarget | null,\n ) => {\n const wrapped = async (args: JsonObject) => {\n try {\n return await handler(args);\n } catch (e) {\n return errorResult(e instanceof Error ? e.message : String(e));\n }\n };\n const final = resolveTarget\n ? wrapToolWithActivity(wrapped, {\n toolName: name,\n agent: { id: agent.id, name: agent.name, color: agent.color },\n kind: \"files\",\n resolveTarget: ({ args, result }) => resolveTarget(args, result),\n })\n : wrapped;\n disposers.push(\n host.registerTool(\n {\n name,\n description,\n inputSchema: {\n type: \"object\",\n properties: properties as any,\n required,\n additionalProperties: false,\n },\n },\n final as any,\n ),\n );\n };\n\n // ───────────── Read ─────────────\n\n reg(\n \"files_get_state\",\n \"Get the file browser's current directory, selected path(s), and expanded folders.\",\n {},\n [],\n () => {\n const state = {\n path: adapter.getPath(),\n selected: adapter.getSelection(),\n expanded: adapter.getExpanded(),\n };\n return textResult(JSON.stringify(state, null, 2), state);\n },\n );\n\n reg(\n \"files_list\",\n \"List the direct children of a folder (files + subfolders). Omit `path` for the current directory. Loads lazily from the host's provider/snapshot — never an eager tree walk.\",\n { path: { type: \"string\", description: \"Folder path to list; defaults to the current directory.\" } },\n [],\n async (args) => {\n const path = guard(args.path !== undefined ? str(args.path) : adapter.getPath());\n const entries = await adapter.listChildren(path);\n const summary = entries.map((e) => ({\n path: e.path,\n name: e.name,\n kind: e.kind,\n ...(e.size !== undefined ? { size: e.size } : {}),\n ...(e.mtime !== undefined ? { mtime: e.mtime } : {}),\n }));\n const text =\n summary.map((e) => `${e.kind === \"dir\" ? \"📁\" : \"📄\"} ${e.path}`).join(\"\\n\") ||\n `(empty: ${path})`;\n return textResult(text, { path, entries: summary });\n },\n );\n\n // ───────────── Navigation ─────────────\n\n reg(\n \"files_navigate\",\n \"Set the current directory (as if the user clicked a breadcrumb or opened a folder).\",\n { path: { type: \"string\" } },\n [\"path\"],\n (args) => {\n const path = guard(str(args.path));\n const prev = adapter.getPath();\n adapter.setPath(path);\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: \"files\",\n action: \"files_navigate\",\n label: `Navigated to ${path}`,\n undo: () => adapter.setPath(prev),\n redo: () => adapter.setPath(path),\n });\n return textResult(`Current directory → ${path}`, { path });\n },\n fTarget,\n );\n\n // ───────────── Expansion ─────────────\n\n reg(\n \"files_expand\",\n \"Expand a folder in the tree (loads its children if needed).\",\n { path: { type: \"string\" } },\n [\"path\"],\n (args) => {\n const path = guard(str(args.path));\n if (adapter.getExpanded().includes(path)) {\n return textResult(`${path} already expanded`, { path, expanded: true });\n }\n adapter.setExpanded((prev) => [...prev, path]);\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: \"files\",\n action: \"files_expand\",\n label: `Expanded ${path}`,\n undo: () => adapter.setExpanded((prev) => prev.filter((p) => p !== path)),\n redo: () => adapter.setExpanded((prev) => (prev.includes(path) ? prev : [...prev, path])),\n });\n return textResult(`Expanded ${path}`, { path, expanded: true });\n },\n fTarget,\n );\n\n reg(\n \"files_collapse\",\n \"Collapse a folder in the tree.\",\n { path: { type: \"string\" } },\n [\"path\"],\n (args) => {\n const path = guard(str(args.path));\n if (!adapter.getExpanded().includes(path)) {\n return textResult(`${path} already collapsed`, { path, expanded: false });\n }\n adapter.setExpanded((prev) => prev.filter((p) => p !== path));\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: \"files\",\n action: \"files_collapse\",\n label: `Collapsed ${path}`,\n undo: () => adapter.setExpanded((prev) => (prev.includes(path) ? prev : [...prev, path])),\n redo: () => adapter.setExpanded((prev) => prev.filter((p) => p !== path)),\n });\n return textResult(`Collapsed ${path}`, { path, expanded: false });\n },\n fTarget,\n );\n\n // ───────────── Selection ─────────────\n\n reg(\n \"files_select\",\n \"Set the selection to the given path(s). Pass a single `path`, or `paths` for a multi-select browser; either empty clears the selection.\",\n {\n path: { type: \"string\", description: \"A single path to select.\" },\n paths: { type: \"array\", items: { type: \"string\" }, description: \"Multiple paths (multi-select browsers).\" },\n },\n [],\n (args) => {\n const next = (args.paths !== undefined ? asPaths(args.paths) : asPaths(args.path)).map(guard);\n const prev = adapter.getSelection();\n adapter.setSelection(next);\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: \"files\",\n action: \"files_select\",\n label: next.length ? `Selected ${next.join(\", \")}` : \"Cleared selection\",\n undo: () => adapter.setSelection(prev),\n redo: () => adapter.setSelection(next),\n });\n return textResult(next.length ? `Selected ${next.join(\", \")}` : \"Cleared selection\", {\n selected: next,\n });\n },\n fTarget,\n );\n\n // ───────────── Snapshot (streamed remote trees) ─────────────\n\n reg(\n \"files_request_snapshot\",\n \"Request a fresh snapshot subtree rooted at `path` (snapshot mode) — e.g. to pull a remote machine's current tree. Requires the host to wire requestSnapshot.\",\n {\n path: { type: \"string\", description: \"Root of the subtree; defaults to the current directory.\" },\n depth: { type: \"number\", description: \"How many levels deep to materialize (host-defined default).\" },\n },\n [],\n async (args) => {\n if (!adapter.requestSnapshot) {\n return errorResult(\"Host did not wire requestSnapshot (snapshot mode not enabled).\");\n }\n const path = guard(args.path !== undefined ? str(args.path) : adapter.getPath());\n // Clamp depth so an agent can't demand an unbounded recursive walk.\n const depth =\n args.depth !== undefined ? Math.max(0, Math.min(MAX_SNAPSHOT_DEPTH, num(args.depth))) : undefined;\n const tree = await adapter.requestSnapshot(path, depth);\n const count = Array.isArray(tree) ? tree.length : 0;\n return textResult(`Snapshot of ${path}: ${count} top-level entr${count === 1 ? \"y\" : \"ies\"}.`, {\n path,\n snapshot: tree,\n });\n },\n fTarget,\n );\n\n return {\n id: \"files\",\n title: \"Files\",\n dispose: () => {\n for (const d of disposers) d();\n },\n };\n}\n"]}
|
package/dist/bridges-files.js
CHANGED
package/dist/bridges-flow.cjs
CHANGED
|
@@ -131,6 +131,21 @@ function registerFlowBridge(host, options) {
|
|
|
131
131
|
const { adapter } = options;
|
|
132
132
|
const agent = { ...DEFAULT_AGENT, ...options.agent ?? {} };
|
|
133
133
|
const disposers = [];
|
|
134
|
+
const pendingMode = options.pendingMode ?? false;
|
|
135
|
+
const validateConfigMode = options.validateConfig ?? "reject";
|
|
136
|
+
let connValidator = void 0;
|
|
137
|
+
const getConnValidator = async () => {
|
|
138
|
+
if (connValidator !== void 0) return connValidator;
|
|
139
|
+
if (options.validateConnections === false) return connValidator = null;
|
|
140
|
+
try {
|
|
141
|
+
const { createConnectionValidator } = await import('@particle-academy/fancy-flow');
|
|
142
|
+
const opts = options.validateConnections && options.validateConnections !== true ? options.validateConnections : void 0;
|
|
143
|
+
connValidator = createConnectionValidator(() => adapter.getNodes(), opts);
|
|
144
|
+
} catch {
|
|
145
|
+
connValidator = null;
|
|
146
|
+
}
|
|
147
|
+
return connValidator ?? null;
|
|
148
|
+
};
|
|
134
149
|
ensureUndoToolsRegistered(host, { defaultAgentId: agent.id });
|
|
135
150
|
const flTarget = (args, result) => ({
|
|
136
151
|
kind: "flow",
|
|
@@ -194,11 +209,11 @@ function registerFlowBridge(host, options) {
|
|
|
194
209
|
"List every node kind registered in fancy-flow's registry. Use this to discover what's authorable before adding nodes.",
|
|
195
210
|
{ category: { type: "string", description: "Optional category filter: trigger | logic | data | ai | io | human | output | custom." } },
|
|
196
211
|
[],
|
|
197
|
-
async () => {
|
|
212
|
+
async (args) => {
|
|
198
213
|
try {
|
|
199
214
|
const { listNodeKinds } = await import('@particle-academy/fancy-flow');
|
|
200
|
-
const
|
|
201
|
-
const all = (
|
|
215
|
+
const category = typeof args.category === "string" ? args.category : void 0;
|
|
216
|
+
const all = (category ? listNodeKinds().filter((k) => k.category === category) : listNodeKinds()).map((k) => ({
|
|
202
217
|
name: k.name,
|
|
203
218
|
category: k.category,
|
|
204
219
|
label: k.label,
|
|
@@ -279,6 +294,22 @@ function registerFlowBridge(host, options) {
|
|
|
279
294
|
}
|
|
280
295
|
const id = newId("n");
|
|
281
296
|
const config = { ...defaults, ...args.config && typeof args.config === "object" ? args.config : {} };
|
|
297
|
+
let configWarnings = [];
|
|
298
|
+
if (kindDef && validateConfigMode !== "off") {
|
|
299
|
+
try {
|
|
300
|
+
const { validateConfig } = await import('@particle-academy/fancy-flow');
|
|
301
|
+
const issues = validateConfig(kindDef, config) ?? [];
|
|
302
|
+
if (issues.length) {
|
|
303
|
+
if (validateConfigMode === "reject") {
|
|
304
|
+
return errorResult(
|
|
305
|
+
`Config invalid for ${kindName}: ${issues.map((i) => i.message).join("; ")}. Call flow_get_node_schema for the accepted fields.`
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
configWarnings = issues.map((i) => i.message);
|
|
309
|
+
}
|
|
310
|
+
} catch {
|
|
311
|
+
}
|
|
312
|
+
}
|
|
282
313
|
const node = {
|
|
283
314
|
id,
|
|
284
315
|
type: kindName,
|
|
@@ -292,7 +323,10 @@ function registerFlowBridge(host, options) {
|
|
|
292
323
|
}
|
|
293
324
|
};
|
|
294
325
|
adapter.setNodes((all) => [...all, node]);
|
|
295
|
-
return textResult(
|
|
326
|
+
return textResult(
|
|
327
|
+
`Added ${kindName} ${id} ("${str(args.label)}")${configWarnings.length ? ` \u2014 config warnings: ${configWarnings.join("; ")}` : ""}`,
|
|
328
|
+
node
|
|
329
|
+
);
|
|
296
330
|
},
|
|
297
331
|
flTarget
|
|
298
332
|
);
|
|
@@ -308,30 +342,46 @@ function registerFlowBridge(host, options) {
|
|
|
308
342
|
config: { type: "object" }
|
|
309
343
|
},
|
|
310
344
|
["id"],
|
|
311
|
-
(args) => {
|
|
345
|
+
async (args) => {
|
|
312
346
|
const id = str(args.id);
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
347
|
+
const current = adapter.getNodes().find((n) => n.id === id);
|
|
348
|
+
if (!current) return errorResult(`No node with id ${id}`);
|
|
349
|
+
const mergedConfig = args.config && typeof args.config === "object" ? { ...current.data.config ?? {}, ...args.config } : current.data.config;
|
|
350
|
+
let configWarnings = [];
|
|
351
|
+
if (args.config && typeof args.config === "object" && validateConfigMode !== "off") {
|
|
352
|
+
try {
|
|
353
|
+
const { getNodeKind, validateConfig } = await import('@particle-academy/fancy-flow');
|
|
354
|
+
const kindDef = getNodeKind(current.data.kind ?? current.type);
|
|
355
|
+
if (kindDef) {
|
|
356
|
+
const issues = validateConfig(kindDef, mergedConfig ?? {}) ?? [];
|
|
357
|
+
if (issues.length) {
|
|
358
|
+
if (validateConfigMode === "reject") {
|
|
359
|
+
return errorResult(`Config invalid for ${id}: ${issues.map((i) => i.message).join("; ")}.`);
|
|
360
|
+
}
|
|
361
|
+
configWarnings = issues.map((i) => i.message);
|
|
328
362
|
}
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
}
|
|
363
|
+
}
|
|
364
|
+
} catch {
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
const updated = {
|
|
368
|
+
...current,
|
|
369
|
+
position: {
|
|
370
|
+
x: args.x !== void 0 ? num(args.x) : current.position.x,
|
|
371
|
+
y: args.y !== void 0 ? num(args.y) : current.position.y
|
|
372
|
+
},
|
|
373
|
+
data: {
|
|
374
|
+
...current.data,
|
|
375
|
+
...args.label !== void 0 ? { label: str(args.label) } : {},
|
|
376
|
+
...args.description !== void 0 ? { description: str(args.description) } : {},
|
|
377
|
+
...args.config && typeof args.config === "object" ? { config: mergedConfig } : {}
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
adapter.setNodes((all) => all.map((n) => n.id === id ? updated : n));
|
|
381
|
+
return textResult(
|
|
382
|
+
`Updated node ${id}${configWarnings.length ? ` \u2014 config warnings: ${configWarnings.join("; ")}` : ""}`,
|
|
383
|
+
updated
|
|
332
384
|
);
|
|
333
|
-
if (!updated) return errorResult(`No node with id ${id}`);
|
|
334
|
-
return textResult(`Updated node ${id}`, updated);
|
|
335
385
|
},
|
|
336
386
|
flTarget
|
|
337
387
|
);
|
|
@@ -340,10 +390,13 @@ function registerFlowBridge(host, options) {
|
|
|
340
390
|
"Remove a node by id (also removes any connected edges).",
|
|
341
391
|
{ id: { type: "string" } },
|
|
342
392
|
["id"],
|
|
343
|
-
(args) => {
|
|
393
|
+
async (args) => {
|
|
344
394
|
const id = str(args.id);
|
|
345
|
-
|
|
346
|
-
|
|
395
|
+
const target = adapter.getNodes().find((n) => n.id === id);
|
|
396
|
+
if (!target) return errorResult(`No node with id ${id}`);
|
|
397
|
+
if (pendingMode && adapter.confirm) {
|
|
398
|
+
const ok = await adapter.confirm({ action: "delete_node", nodeId: id, label: target.data?.label });
|
|
399
|
+
if (!ok) return textResult(`Delete of node ${id} was declined by the human.`);
|
|
347
400
|
}
|
|
348
401
|
adapter.setNodes((all) => all.filter((n) => n.id !== id));
|
|
349
402
|
adapter.setEdges((all) => all.filter((e) => e.source !== id && e.target !== id));
|
|
@@ -362,18 +415,27 @@ function registerFlowBridge(host, options) {
|
|
|
362
415
|
label: { type: "string" }
|
|
363
416
|
},
|
|
364
417
|
["source", "target"],
|
|
365
|
-
(args) => {
|
|
418
|
+
async (args) => {
|
|
366
419
|
const source = str(args.source);
|
|
367
420
|
const target = str(args.target);
|
|
421
|
+
const sourceHandle = args.sourceHandle ? str(args.sourceHandle) : void 0;
|
|
422
|
+
const targetHandle = args.targetHandle ? str(args.targetHandle) : void 0;
|
|
368
423
|
const all = adapter.getNodes();
|
|
369
424
|
if (!all.find((n) => n.id === source)) return errorResult(`No source node ${source}`);
|
|
370
425
|
if (!all.find((n) => n.id === target)) return errorResult(`No target node ${target}`);
|
|
426
|
+
const validate = await getConnValidator();
|
|
427
|
+
if (validate && !validate({ source, target, sourceHandle: sourceHandle ?? null, targetHandle: targetHandle ?? null })) {
|
|
428
|
+
if (source === target) return errorResult(`Cannot connect node ${source} to itself.`);
|
|
429
|
+
return errorResult(
|
|
430
|
+
`Invalid connection ${source}${sourceHandle ? `:${sourceHandle}` : ""} \u2192 ${target}${targetHandle ? `:${targetHandle}` : ""}: incompatible port types or unknown handle. Call flow_get_node_schema to check the ports.`
|
|
431
|
+
);
|
|
432
|
+
}
|
|
371
433
|
const edge = {
|
|
372
434
|
id: newId("e"),
|
|
373
435
|
source,
|
|
374
436
|
target,
|
|
375
|
-
...
|
|
376
|
-
...
|
|
437
|
+
...sourceHandle ? { sourceHandle } : {},
|
|
438
|
+
...targetHandle ? { targetHandle } : {},
|
|
377
439
|
...args.label ? { label: str(args.label) } : {}
|
|
378
440
|
};
|
|
379
441
|
adapter.setEdges((existing) => [...existing, edge]);
|
|
@@ -433,6 +495,10 @@ function registerFlowBridge(host, options) {
|
|
|
433
495
|
[],
|
|
434
496
|
async () => {
|
|
435
497
|
if (!adapter.run) return errorResult("Host did not provide a run handler.");
|
|
498
|
+
if (pendingMode && adapter.confirm) {
|
|
499
|
+
const ok = await adapter.confirm({ action: "run" });
|
|
500
|
+
if (!ok) return textResult("Run was declined by the human.");
|
|
501
|
+
}
|
|
436
502
|
const result = await adapter.run();
|
|
437
503
|
return textResult(result.ok ? "Run complete" : `Run failed: ${result.error ?? "unknown"}`, result);
|
|
438
504
|
},
|