@particle-academy/agent-integrations 0.52.0 → 0.53.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/index.js CHANGED
@@ -34,8 +34,8 @@ export { registerMapBridge } from './chunk-QEVSNDJW.js';
34
34
  export { RelayTransport, attachRelay } from './chunk-G6N2TQVO.js';
35
35
  import { attachInProcess } from './chunk-AFUULW5E.js';
36
36
  export { InProcessTransport, attachInProcess } from './chunk-AFUULW5E.js';
37
- import { registerFormBridge } from './chunk-AL77RO25.js';
38
- export { registerFormBridge } from './chunk-AL77RO25.js';
37
+ import { registerFormBridge } from './chunk-AET2R7DJ.js';
38
+ export { registerFormBridge } from './chunk-AET2R7DJ.js';
39
39
  import './chunk-DPBAEWB5.js';
40
40
  export { registerSheetsBridge } from './chunk-S4DA2UTJ.js';
41
41
  export { clearStack as clearUndoStack, ensureUndoToolsRegistered, pushUndoEntry, readHistory as readUndoHistory, redoOne, registerUndoTools, resetAllUndoStacks, undoOne } from './chunk-ZDKYKJFH.js';
@@ -1,9 +1,11 @@
1
1
  # Several forms on one host — design note
2
2
 
3
- **Status: proposal, not implemented. The choice is the owner's.** Written
4
- 2026-10-30 against 0.51.0, prompted by a consumer asking for the supported model.
3
+ **Status: option A is BUILT (0.53.0).** The owner chose A on 2026-10-30. The
4
+ proposal below is kept as written against 0.51.0 for the reasoning; "Where it
5
+ stands" describes the state before 0.53.0. What was built, and what another
6
+ bridge would need to adopt it, is at the end ("As built").
5
7
 
6
- ## Where it stands
8
+ ## Where it stood (0.51.0 and 0.52.0)
7
9
 
8
10
  `registerFormBridge` registers `form_describe`, `form_get_value`,
9
11
  `form_get_values`, `form_set_value`, `form_set_values`, `form_focus` and
@@ -20,7 +22,7 @@ surfaces. Whatever is chosen for forms should be the pattern for those too.
20
22
  There is already one precedent for scoping: `registerScreenDocBridge` takes a
21
23
  `surface` option that prefixes its tool names (`screen_checkout_add`).
22
24
 
23
- Today's supported answer is **one form bridge per host**.
25
+ Until 0.53.0 the supported answer was **one form bridge per host**.
24
26
 
25
27
  ## Options
26
28
 
@@ -95,3 +97,67 @@ form mounted every existing call shape still succeeds; disposing one form leaves
95
97
  the other drivable and settles only the disposed form's pending writes; a remount
96
98
  of the same id re-joins rather than duplicating; `form_list` reflects mounts and
97
99
  unmounts.
100
+
101
+ ## As built (0.53.0)
102
+
103
+ - `src/bridges/multi-instance.ts` holds the shared piece, `joinInstanceRouter`.
104
+ It is internal (no entry point). It keeps one router per (host, family) in a
105
+ `WeakMap`, calls the family's `install` once when the first instance joins,
106
+ and calls the disposer `install` returned when the last instance leaves. It
107
+ also resolves the selecting argument by the rules below. If `install` throws
108
+ because a name is held by an unrelated registrant, no router is left behind.
109
+ - `registerFormBridge` builds its handlers per form, with that form's adapter,
110
+ `pendingMode`, `agent` and close handling, then joins the `"form"` router. The
111
+ shared tools are registered once, under the single owner `"form-bridge"`.
112
+ Each one resolves `form` and then calls the chosen form's handler, so the
113
+ activity, presence target and outcome-unknown settling stay per form.
114
+ - Resolution: with exactly one form mounted `form` is optional. With two or
115
+ more, a call without it is an error listing the ids. An id that is not
116
+ mounted is an error listing the ids, even when only one form is mounted, so a
117
+ call aimed at a form that has closed never lands on another one.
118
+ - A registration whose `adapter.id` is already mounted **replaces** it. A
119
+ duplicate cannot be told apart from a remount whose cleanup has not run yet,
120
+ and 0.51.0 already let the same form re-register, so this keeps that
121
+ behaviour. The earlier registration's `dispose()` then leaves the newer one
122
+ in place. A missing or empty `adapter.id` throws.
123
+ - Tool descriptions are now generic (the "Cons" above). `form_describe` still
124
+ returns the form's `id` and `title` in its result.
125
+
126
+ Acceptance tests: `src/bridges/__tests__/forms-multi.test.ts` (the form
127
+ behaviour) and `src/bridges/__tests__/multi-instance.test.ts` (the helper).
128
+
129
+ ### Adopting it in another bridge (charts, grids, code, scene, …)
130
+
131
+ Charts and grids have the same shape as forms did: tools named for the family
132
+ (`chart_set_option`, `grid_sort`), a registrant id carrying `adapter.id`, and
133
+ handlers that close over one adapter. Adopting the router takes four steps:
134
+
135
+ 1. **Lift the tool definitions out of the factory** into a module-level list,
136
+ and add the selecting argument (`chart`, `grid`) to every tool's schema as
137
+ an optional string.
138
+ 2. **Build the handlers per instance** inside `register<X>Bridge`, wrapped with
139
+ `wrapToolWithActivity` using that instance's agent and `screenId`, into a
140
+ `name -> handler` record. Today they are registered directly.
141
+ 3. **Write an `install(router)`** that registers each shared tool under one
142
+ family owner (`"chart-bridge"`). Its handler calls
143
+ `router.resolve(args.<argument>)`, returns the error if resolution fails,
144
+ and otherwise calls `instance.handlers[name](args)`. Add a `<family>_list`
145
+ tool. On a registration failure, withdraw whatever was already registered
146
+ and rethrow, as `installFormTools` does.
147
+ 4. **Join and leave.** Call `joinInstanceRouter(host, { family, argument,
148
+ listTool, install }, adapter.id, { adapter, handlers })`, and make the
149
+ bridge's `dispose()` call `leave()` and then settle anything that
150
+ instance still has pending.
151
+
152
+ Per-bridge points to check:
153
+
154
+ - **Undo** (grid, charts): `pushUndoEntry` closes over the instance's own
155
+ adapter, so it is per instance already. The entry's `bridgeId`
156
+ (`grid:<id>`) should keep naming the instance.
157
+ - **Descriptions** that name the instance today become generic. The
158
+ `<family>_list` result carries the names instead.
159
+ - **Census:** `tool-name-census.test.ts` builds each bridge with a proxy
160
+ adapter whose `id` is not a string. Coerce the id with `String(...)` as
161
+ `registerFormBridge` does, or the census throws.
162
+ - Bridges that already scope their names (screen-doc's `surface`) or are
163
+ inherently singletons (navigation, screens, tui) should not adopt it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@particle-academy/agent-integrations",
3
- "version": "0.52.0",
3
+ "version": "0.53.0",
4
4
  "description": "MCP-driven agent presence in collab sessions: per-session micro-MCP server, pluggable bridges to fancy-* packages, and agent UX components (panel + on-canvas cursor).",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/bridges/forms.ts"],"names":[],"mappings":";;;;;;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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\";\nimport { emitActivity } from \"../presence/registry\";\nimport { commit, hostErrorMessage } from \"./host-commit\";\n\n/**\n * Field descriptor — what the host says about each form field. Mirrors the\n * subset of HTML / react-fancy input shapes agents care about.\n */\nexport type FormFieldDescriptor = {\n /** Form-local field name. Matches the key the host uses in its values map. */\n name: string;\n /** Display label. */\n label?: string;\n /** Logical type. Drives validation + agent expectations. */\n type:\n | \"text\"\n | \"textarea\"\n | \"number\"\n | \"email\"\n | \"password\"\n | \"url\"\n | \"date\"\n | \"select\"\n | \"multi-select\"\n | \"checkbox\"\n | \"switch\"\n | \"radio\"\n | \"file\"\n | \"json\";\n /** Allowed values for select / radio. */\n options?: Array<{ value: string; label: string }>;\n /** Whether the field must be filled before submit. */\n required?: boolean;\n /** Free-text hint surfaced to the agent. */\n description?: string;\n /** Default value (presented in get_value when nothing set). */\n defaultValue?: unknown;\n};\n\n/**\n * Adapter the host wires per form. Matches the controlled-state pattern\n * react-fancy already uses (`value` / `onValueChange`); this adapter just\n * exposes those state slots in a form-shaped way the bridge can call.\n *\n * `setValue` / `setValues` may be sync (`void`) or async (a Promise); see\n * {@link FormAdapterCommit}. Return a Promise when the host's write is\n * authoritative — a persisted draft, or one the host can refuse or report\n * stale — so the agent is told the truth instead of \"success\" before anything\n * was accepted.\n *\n * This bridge pushes NO undo entries: `agent_undo` cannot revert a form write.\n */\nexport type FormBridgeAdapter = {\n /** Stable id for the form (used in form_describe + presence target). */\n id: string;\n /** Display title for human-readable logs. */\n title?: string;\n /** Optional fancy-screens screen id this form belongs to. */\n screenId?: string;\n /** Field descriptors. The bridge uses these for schema introspection\n * (form_describe). Agents call this first to know what to fill. */\n getFields: () => FormFieldDescriptor[];\n /** Read a single field's current value. */\n getValue: (name: string) => unknown;\n /** Read all values as { fieldName: value }. */\n getValues: () => Record<string, unknown>;\n /**\n * Set a single field's value. The host wires this to its setState, or to\n * an authoritative write it awaits. Sync `void` behaves as it always has; a\n * Promise is awaited, and a rejection or `{ ok: false }` is the tool's error.\n */\n setValue: (name: string, value: unknown) => FormAdapterCommit;\n /**\n * Set many at once, ideally as one host commit. Same sync/async contract as\n * `setValue`. When absent, the bridge awaits `setValue` once per field in\n * order and stops at the first refusal (so that path is NOT atomic).\n */\n setValues?: (values: Record<string, unknown>) => FormAdapterCommit;\n /** Programmatically focus a field (host implements DOM focus). Optional. */\n focus?: (name: string) => void;\n /** Submit the form. Returns the values that were submitted (or rejection). */\n submit?: () => Promise<{ ok: boolean; values?: Record<string, unknown>; error?: string }>;\n /**\n * Human confirm gate for `form_submit` (trust-but-verify). When `pendingMode`\n * is on, the bridge calls this before submitting; return false to decline.\n * Wire it to a human control — submitting a form is a human-visible,\n * often-destructive action (checkout, delete, invite).\n */\n confirm?: (request: FormConfirmRequest) => Promise<boolean> | boolean;\n};\n\n/**\n * What an async `setValue` / `setValues` may resolve to, to acknowledge (or\n * refuse) a write. `{ ok: false }` is a refusal the agent can act on: `error`\n * is shown to the agent verbatim, so keep it a human-readable sentence (e.g.\n * \"Draft changed since you read it; re-read and retry\"), never a stack trace or\n * an internal path. `code` (e.g. `\"stale\"`, `\"forbidden\"`) is for the host's own\n * use; it is not shown to the agent.\n */\nexport type FormAdapterResult = { ok: true } | { ok: false; error: string; code?: string };\n\n/**\n * Return type of `setValue` / `setValues`. A sync `void` return keeps the\n * original behaviour. A Promise makes the bridge WAIT: the tool reports\n * success, and emits its AgentActivity event, only after the promise resolves\n * (to `void` or `{ ok: true }`). A rejection or `{ ok: false }` becomes that\n * tool call's error result and emits no activity. If the bridge is disposed\n * while the write is pending, the call settles at once as an error saying the\n * outcome is unknown, and a later settle is ignored.\n */\nexport type FormAdapterCommit = void | Promise<void | FormAdapterResult>;\n\n/** What a `form_submit` confirm gate is asked to approve. */\nexport type FormConfirmRequest = {\n action: \"submit\";\n form: string;\n title?: string;\n values: Record<string, unknown>;\n};\n\nexport type FormBridgeOptions = {\n adapter: FormBridgeAdapter;\n /** Identity tagged into activity events. */\n agent?: { id: string; name?: string; color?: string };\n /**\n * Stage `form_submit` for human confirmation via `adapter.confirm` instead of\n * submitting immediately. **Default: ON** (matches the navigation bridge and\n * the Human+ trust-but-verify contract). Set false only when auto-submit is\n * safe. If on without an `adapter.confirm`, submit proceeds (nothing to gate).\n */\n pendingMode?: boolean;\n};\n\nconst DEFAULT_AGENT = { id: \"agent\", name: \"Agent\", color: \"#a855f7\" };\n\n/**\n * registerFormBridge — wires schema-driven MCP access to a single form.\n *\n * ONE form bridge per host. The tool names (`form_set_value`, …) are not\n * scoped to the form id, so since 0.51.0 a second form bridge with a different\n * adapter id on the same host throws (the duplicate-registrant refusal); a\n * remount of the SAME form re-registers fine. For several forms, give each its\n * own host for now — see `docs/multi-form-hosts.md`.\n */\nexport function registerFormBridge(\n host: ToolHost,\n options: FormBridgeOptions,\n): Bridge {\n const { adapter } = options;\n const agent = { ...DEFAULT_AGENT, ...(options.agent ?? {}) };\n const pendingMode = options.pendingMode ?? true;\n const disposers: Array<() => void> = [];\n // The bridge id is also its registrant identity on the host: the same bridge\n // may re-register (a remount), a different one claiming a name is refused.\n const bridgeId = `form:${adapter.id}`;\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 const formId = adapter.id;\n\n // Close handling. A host may dispose the bridge (the form unmounts) while a\n // write or a human confirm is still pending; its promise may then never\n // settle. Every awaited host call is raced against dispose, so the tool call\n // settles at once instead of hanging, and a late settle is ignored.\n let disposed = false;\n const onDispose = new Set<() => void>();\n const CLOSED: unique symbol = Symbol(\"form-closed\");\n const untilClosed = <T>(p: Promise<T>): Promise<T | typeof CLOSED> => {\n if (disposed) {\n p.catch(() => {}); // a late rejection must never be unhandled\n return Promise.resolve(CLOSED);\n }\n return new Promise<T | typeof CLOSED>((resolve, reject) => {\n const close = () => resolve(CLOSED);\n onDispose.add(close);\n p.then(\n (v) => { onDispose.delete(close); resolve(v); },\n (e) => { onDispose.delete(close); reject(e); },\n );\n });\n };\n const closedUnknown = (what: string) =>\n errorResult(\n `Form \"${formId}\" was closed before the host confirmed ${what}, so whether it was applied is unknown. ` +\n \"Do not assume it was. If the form is open again, read it back (form_get_values) before retrying.\",\n );\n\n const target =(args: any): AgentTarget => ({\n kind: \"form\",\n screenId: adapter.screenId,\n elementId: typeof args?.field === \"string\" ? `${formId}:${args.field}` : formId,\n label: typeof args?.field === \"string\"\n ? `${adapter.title ?? formId} → ${args.field}`\n : adapter.title ?? formId,\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 {\n return await handler(args);\n } catch (e) {\n return errorResult(hostErrorMessage(e, `${name} failed.`));\n }\n };\n const final = isMutation\n ? wrapToolWithActivity(wrapped, {\n toolName: name,\n agent: { id: agent.id, name: agent.name, color: agent.color },\n kind: \"form\",\n screenId: adapter.screenId,\n resolveTarget: ({ args }) => target(args),\n })\n : wrapped;\n disposers.push(\n host.registerTool(\n {\n name,\n description,\n inputSchema: { type: \"object\", properties: properties as any, required, additionalProperties: false },\n },\n final as any,\n { owner: bridgeId },\n ),\n );\n };\n\n // ───────────── Read tools ─────────────\n\n reg(\n \"form_describe\",\n `Describe the form \"${formId}\" — fields, types, options, required flags. Call this first to know what's fillable.`,\n {},\n [],\n () => {\n const fields = adapter.getFields();\n const text = fields\n .map((f) => `${f.name}${f.required ? \"*\" : \"\"} (${f.type})${f.label ? ` — ${f.label}` : \"\"}`)\n .join(\"\\n\");\n return textResult(text || \"(no fields)\", { id: formId, title: adapter.title, fields });\n },\n false,\n );\n\n reg(\n \"form_get_value\",\n \"Read a single field's current value.\",\n { field: { type: \"string\" } },\n [\"field\"],\n (args) => {\n const name = String(args.field ?? \"\");\n if (!adapter.getFields().find((f) => f.name === name)) {\n return errorResult(`Unknown field: ${name}`);\n }\n const value = adapter.getValue(name);\n return textResult(JSON.stringify(value), { field: name, value });\n },\n false,\n );\n\n reg(\n \"form_get_values\",\n \"Read every field's current value as a JSON object.\",\n {},\n [],\n () => {\n const values = adapter.getValues();\n return textResult(JSON.stringify(values, null, 2), values);\n },\n false,\n );\n\n // ───────────── Mutation tools ─────────────\n\n reg(\n \"form_set_value\",\n \"Set one field's value. The host's controlled state updates and the human sees the field change.\",\n {\n field: { type: \"string\" },\n value: { description: \"Value to set. Type depends on the field's `type`.\" },\n },\n [\"field\", \"value\"],\n async (args) => {\n const name = String(args.field ?? \"\");\n const fieldDef = adapter.getFields().find((f) => f.name === name);\n if (!fieldDef) return errorResult(`Unknown field: ${name}`);\n const done = await untilClosed(\n commit(() => adapter.setValue(name, args.value), `Host refused the write to \"${name}\".`),\n );\n if (done === CLOSED) return closedUnknown(`the write to \"${name}\"`);\n if (!done.ok) return errorResult(done.error);\n return textResult(`${name} ← ${JSON.stringify(args.value)}`, { field: name, value: args.value });\n },\n true,\n );\n\n reg(\n \"form_set_values\",\n \"Set multiple fields atomically. Pass a `values` object keyed by field name.\",\n { values: { type: \"object\" } },\n [\"values\"],\n async (args) => {\n const values = (args.values && typeof args.values === \"object\") ? args.values as Record<string, unknown> : {};\n const fields = adapter.getFields();\n const known = new Set(fields.map((f) => f.name));\n const unknownKeys = Object.keys(values).filter((k) => !known.has(k));\n if (unknownKeys.length) return errorResult(`Unknown fields: ${unknownKeys.join(\", \")}`);\n const setValues = adapter.setValues;\n if (setValues) {\n const done = await untilClosed(commit(() => setValues(values), \"Host refused the write.\"));\n if (done === CLOSED) return closedUnknown(\"the write\");\n if (!done.ok) return errorResult(done.error);\n } else {\n // No batch setter: one host commit per field, in order, stopping at the\n // first refusal. Earlier fields stay committed, so say exactly which.\n const keys = Object.keys(values);\n const committed: string[] = [];\n for (const [i, k] of keys.entries()) {\n const done = await untilClosed(\n commit(() => adapter.setValue(k, values[k]), `Host refused the write to \"${k}\".`),\n );\n if (done === CLOSED) {\n return {\n ...closedUnknown(`the write to \"${k}\"`),\n structuredContent: { committed, pending: k, notAttempted: keys.slice(i + 1) },\n };\n }\n if (!done.ok) {\n const state = { committed, failed: k, notAttempted: keys.slice(i + 1) };\n if (committed.length) {\n // Those writes DID commit; every committed mutation is observable,\n // and wrapToolWithActivity skips error results, so emit it here.\n emitActivity({\n agentId: agent.id,\n agentName: agent.name,\n agentColor: agent.color,\n target: target({}),\n action: \"form_set_values\",\n timestamp: Date.now(),\n meta: state,\n });\n }\n return {\n ...errorResult(\n `\"${k}\" was refused: ${done.error} ` +\n (committed.length\n ? `Already committed and NOT rolled back: ${committed.join(\", \")}. `\n : \"Nothing was committed. \") +\n (state.notAttempted.length ? `Not attempted: ${state.notAttempted.join(\", \")}.` : \"\"),\n ),\n structuredContent: state,\n };\n }\n committed.push(k);\n }\n }\n return textResult(`Set ${Object.keys(values).length} field(s)`, { values });\n },\n true,\n );\n\n reg(\n \"form_focus\",\n \"Move browser focus to a field (host-implemented). Useful before streaming text into it.\",\n { field: { type: \"string\" } },\n [\"field\"],\n (args) => {\n const name = String(args.field ?? \"\");\n if (!adapter.focus) return errorResult(\"Host did not provide a focus implementation.\");\n if (!adapter.getFields().find((f) => f.name === name)) {\n return errorResult(`Unknown field: ${name}`);\n }\n adapter.focus(name);\n return textResult(`Focused ${name}`, { field: name });\n },\n true,\n );\n\n reg(\n \"form_submit\",\n \"Submit the form. Host returns ok + values (or an error). In pendingMode this is staged for the human to confirm first.\",\n {},\n [],\n async () => {\n if (!adapter.submit) return errorResult(\"Host did not provide a submit implementation.\");\n // Trust-but-verify: a form submit is a human-visible / often-destructive\n // action, so gate it on a human confirm when one is wired.\n if (pendingMode && adapter.confirm) {\n const confirm = adapter.confirm;\n const ok = await untilClosed(Promise.resolve().then(() => confirm({\n action: \"submit\",\n form: formId,\n title: adapter.title,\n values: adapter.getValues(),\n })));\n // The form went away while the human was deciding: never submit a\n // form that is no longer on screen, whatever the late answer is.\n if (ok === CLOSED) {\n return errorResult(`Form \"${formId}\" was closed before the submit was confirmed. Nothing was submitted.`);\n }\n if (!ok) return errorResult(\"Declined by user\");\n }\n const submit = adapter.submit;\n const result = await untilClosed(Promise.resolve().then(() => submit()));\n if (result === CLOSED) return closedUnknown(\"the submit\");\n if (!result.ok) return errorResult(hostErrorMessage(result.error, \"Submit failed\"));\n return textResult(\"Submitted\", { values: result.values });\n },\n true,\n );\n\n return {\n id: bridgeId,\n title: adapter.title ?? formId,\n dispose: () => {\n disposed = true;\n for (const d of disposers) d();\n // Settle every call still waiting on the host; see untilClosed.\n for (const close of [...onDispose]) close();\n onDispose.clear();\n },\n };\n}\n"]}