@particle-academy/agent-integrations 0.34.0 → 0.36.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.
@@ -14,7 +14,15 @@ function registerDocBridge(host, options) {
14
14
  const disposers = [];
15
15
  ensureUndoToolsRegistered(host, { defaultAgentId: agent.id });
16
16
  let idSeq = 0;
17
- const mintId = () => adapter.newId?.() ?? `${surface}-${idSeq += 1}`;
17
+ const mintId = () => {
18
+ if (adapter.newId) return adapter.newId();
19
+ const taken = adapter.get().nodes;
20
+ let id;
21
+ do
22
+ id = `${surface}-${idSeq += 1}`;
23
+ while (taken[id]);
24
+ return id;
25
+ };
18
26
  const target = (elementId) => ({ kind: surface, screenId: adapter.screenId, elementId });
19
27
  const pending = /* @__PURE__ */ new Map();
20
28
  function commit(op, label, targetId) {
@@ -33,10 +41,10 @@ function registerDocBridge(host, options) {
33
41
  }
34
42
  function submit(op, label, targetId) {
35
43
  if (stage(op) === "confirm") {
36
- const id = `${surface}-pending-${idSeq += 1}`;
37
- pending.set(id, { op, label, targetId });
38
- options.onPending?.({ id, op, label });
39
- return { staged: true, id };
44
+ const pendingId = `${surface}-pending-${idSeq += 1}`;
45
+ pending.set(pendingId, { op, label, targetId });
46
+ options.onPending?.({ id: pendingId, op, label });
47
+ return { staged: true, id: targetId, pendingId };
40
48
  }
41
49
  commit(op, label, targetId);
42
50
  return { staged: false, id: targetId };
@@ -119,18 +127,26 @@ function registerDocBridge(host, options) {
119
127
  type: { type: "string", description: "Node type discriminant." },
120
128
  parent: { type: ["string", "null"], description: "Parent id, or null for a root." },
121
129
  props: { type: "object", description: "JSON props bag." },
122
- order: { type: "string", description: "Fractional order key (default: append)." }
130
+ order: { type: "string", description: "Fractional order key (default: append)." },
131
+ id: {
132
+ type: "string",
133
+ description: "Id for the new node. Supply a meaningful one if you intend to address this node later; omitted means one is minted for you. Must not already exist."
134
+ }
123
135
  },
124
136
  ["type"],
125
137
  (args) => {
126
138
  const tree = adapter.get();
127
139
  const parent = typeof args.parent === "string" ? args.parent : null;
128
- const id = mintId();
140
+ const requested = typeof args.id === "string" ? args.id : void 0;
141
+ if (requested !== void 0 && tree.nodes[requested]) {
142
+ throw new Error(`Node ${requested} already exists \u2014 pick a different id or update it instead`);
143
+ }
144
+ const id = requested ?? mintId();
129
145
  const order = typeof args.order === "string" ? args.order : appendOrder(tree, parent);
130
146
  const props = args.props && typeof args.props === "object" ? args.props : {};
131
147
  const node = makeNode({ id, type: String(args.type), parent, order }, props);
132
148
  const res = submit({ t: "insert", node }, `add ${args.type} ${id}`, id);
133
- return { ...res, _text: res.staged ? `staged add ${id}` : `added ${id}` };
149
+ return { ...res, _text: res.staged ? `staged add ${id} \u2014 confirm ${res.pendingId}` : `added ${id}` };
134
150
  },
135
151
  true,
136
152
  (_args, result) => target(result.id)
@@ -145,7 +161,7 @@ function registerDocBridge(host, options) {
145
161
  if (!adapter.get().nodes[id]) throw new Error(`No node ${id}`);
146
162
  const patch = args.patch && typeof args.patch === "object" ? args.patch : {};
147
163
  const res = submit({ t: "set_props", id, patch }, `update ${id}`, id);
148
- return { ...res, id, _text: res.staged ? `staged update ${id}` : `updated ${id}` };
164
+ return { ...res, id, _text: res.staged ? `staged update ${id} \u2014 confirm ${res.pendingId}` : `updated ${id}` };
149
165
  },
150
166
  true,
151
167
  (args) => target(String(args.id))
@@ -161,7 +177,7 @@ function registerDocBridge(host, options) {
161
177
  if (!tree.nodes[id]) throw new Error(`No node ${id}`);
162
178
  const count = descendantsOf(tree, id).length + 1;
163
179
  const res = submit({ t: "remove", id }, `remove ${id} (${count} node${count === 1 ? "" : "s"})`, id);
164
- return { ...res, id, removed: count, _text: res.staged ? `staged remove ${id}` : `removed ${id}` };
180
+ return { ...res, id, removed: count, _text: res.staged ? `staged remove ${id} \u2014 confirm ${res.pendingId}` : `removed ${id}` };
165
181
  },
166
182
  true,
167
183
  (args) => target(String(args.id))
@@ -178,7 +194,7 @@ function registerDocBridge(host, options) {
178
194
  const parent = args.parent === null ? null : typeof args.parent === "string" ? args.parent : tree.nodes[id].parent;
179
195
  const order = typeof args.order === "string" ? args.order : appendOrder(tree, parent);
180
196
  const res = submit({ t: "move", id, parent, order }, `move ${id}`, id);
181
- return { ...res, id, _text: res.staged ? `staged move ${id}` : `moved ${id}` };
197
+ return { ...res, id, _text: res.staged ? `staged move ${id} \u2014 confirm ${res.pendingId}` : `moved ${id}` };
182
198
  },
183
199
  true,
184
200
  (args) => target(String(args.id))
@@ -194,7 +210,7 @@ function registerDocBridge(host, options) {
194
210
  if (built && typeof built === "object" && "error" in built) throw new Error(built.error);
195
211
  const tid = t.targetId?.(args);
196
212
  const res = submit(built, `${t.verb} ${tid ?? ""}`.trim(), tid);
197
- return { ...res, id: tid, _text: res.staged ? `staged ${t.verb}` : t.verb };
213
+ return { ...res, id: tid, _text: res.staged ? `staged ${t.verb} \u2014 confirm ${res.pendingId}` : t.verb };
198
214
  },
199
215
  true,
200
216
  (args) => target(t.targetId?.(args))
@@ -202,8 +218,8 @@ function registerDocBridge(host, options) {
202
218
  }
203
219
  reg(
204
220
  "confirm",
205
- "Apply a staged op by its pending id (from a staged mutation).",
206
- { id: { type: "string" } },
221
+ "Apply a staged op. Pass the `pendingId` a staged mutation returned \u2014 not the node `id` it also returns.",
222
+ { id: { type: "string", description: "The `pendingId` from a staged mutation." } },
207
223
  ["id"],
208
224
  (args) => {
209
225
  const id = String(args.id);
@@ -218,8 +234,8 @@ function registerDocBridge(host, options) {
218
234
  );
219
235
  reg(
220
236
  "reject",
221
- "Discard a staged op by its pending id.",
222
- { id: { type: "string" } },
237
+ "Discard a staged op. Pass the `pendingId` a staged mutation returned \u2014 not the node `id` it also returns.",
238
+ { id: { type: "string", description: "The `pendingId` from a staged mutation." } },
223
239
  ["id"],
224
240
  (args) => {
225
241
  const id = String(args.id);
@@ -241,5 +257,5 @@ function registerDocBridge(host, options) {
241
257
  }
242
258
 
243
259
  export { registerDocBridge };
244
- //# sourceMappingURL=chunk-L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GAAI,OAAA,CAAQ,GAAA,CAAI,EAAE,CAAA;AACxB,MAAA,IAAI,CAAC,CAAA,EAAG,MAAM,IAAI,KAAA,CAAM,CAAA,cAAA,EAAiB,EAAE,CAAA,CAAE,CAAA;AAC7C,MAAA,OAAA,CAAQ,OAAO,EAAE,CAAA;AACjB,MAAA,OAAO,EAAE,EAAA,EAAI,IAAA,EAAM,QAAA,EAAU,CAAA,CAAE,OAAO,KAAA,EAAO,CAAA,SAAA,EAAY,CAAA,CAAE,KAAK,CAAA,CAAA,EAAG;AAAA,IACrE,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;AAC7B,MAAA,OAAA,CAAQ,KAAA,EAAM;AAAA,IAChB;AAAA,GACF;AACF","file":"chunk-XY2TDE6E.js","sourcesContent":["/**\n * registerDocBridge — a GENERIC MCP bridge over a `@particle-academy/fancy-doc-commons`\n * `DocTree`. Give it an adapter (`{ get, set }`) and it generates, from the shared\n * op-spine, a full Human+ surface: uniform read tools + the canonical node op tools\n * (add / update / remove / move) under one verb lexicon, with **undo derived from\n * the reducer**, agent-activity broadcasts, unconditional `agent_undo/redo/history`,\n * and an optional **staged-write** (confirm / reject) channel — replacing the ~500-line\n * bespoke bridges (whiteboard/flow/artboard/…) with one builder. A surface adds its\n * domain ops (e.g. cms `set_style`) via `opTools` + a matching reducer.\n */\nimport { textResult, errorResult } from \"../mcp/server\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport type { JsonObject } from \"../mcp/types\";\nimport type { Bridge } from \"./types\";\nimport { wrapToolWithActivity } from \"../presence/wrap-tool-with-activity\";\nimport type { AgentTarget } from \"../presence/types\";\nimport { pushUndoEntry } from \"../undo/undo-stack\";\nimport { ensureUndoToolsRegistered } from \"../undo/undo-tools\";\nimport {\n treeReducer,\n childrenOf,\n descendantsOf,\n appendOrder,\n autoApply,\n type DocTree,\n type DocNode,\n type TreeOp,\n type DocReducer,\n type StagePolicy,\n} from \"@particle-academy/fancy-doc-commons\";\n\nconst DEFAULT_AGENT = { id: \"agent\", name: \"Agent\", color: \"#a855f7\" };\n\n/** Host-provided access to the document tree. */\nexport interface DocAdapter<N extends DocNode> {\n /** Read the current tree. */\n get(): DocTree<N>;\n /** Replace the tree — host wires this to its `onChange` / `setState`. */\n set(next: DocTree<N>): void;\n /** Optional fancy-screens screen id, for presence scoping. */\n screenId?: string;\n /** Mint a fresh, unique node id. Default: `<surface>-<n>`. */\n newId?(): string;\n}\n\n/**\n * A domain op tool beyond the built-in add/update/remove/move — lets a surface\n * expose its own ops (e.g. cms `set_style`) through the same undo + activity path.\n */\nexport interface DocOpTool<N extends DocNode, TOp> {\n /** Verb, prefixed with the surface (e.g. `set_style` → `cms_set_style`). */\n verb: string;\n description: string;\n properties: Record<string, unknown>;\n required: string[];\n /** Build the op from the args (or return `{ error }`). */\n build(args: JsonObject, tree: DocTree<N>): TOp | { error: string };\n /** Node id this op targets (for the activity target + undo label). */\n targetId?(args: JsonObject): string | undefined;\n}\n\nexport interface DocBridgeOptions<N extends DocNode, TOp = TreeOp<N>> {\n adapter: DocAdapter<N>;\n /** Tool-name prefix + activity kind (e.g. `\"cms\"` → `cms_add`, kind `\"cms\"`). */\n surface: string;\n agent?: { id: string; name?: string; color?: string };\n /** Reducer for reduce + invert. Default: the substrate `treeReducer<N>()`. */\n reducer?: DocReducer<DocTree<N>, TOp>;\n /** Build a full node from the core fields + props (fill surface defaults, e.g. `style`). */\n makeNode?: (core: { id: string; type: string; parent: string | null; order: string }, props: Record<string, unknown>) => N;\n /** Domain op tools beyond the built-ins. */\n opTools?: DocOpTool<N, TOp>[];\n /** Decide auto-apply vs. confirm per op. Default: everything auto-applies. */\n stagePolicy?: StagePolicy<TOp>;\n /** Fired when an op is staged pending human confirmation. */\n onPending?: (staged: { id: string; op: TOp; label: string }) => void;\n /** Summarize a node for describe/list. Default: id/type/parent + prop keys. */\n describeNode?: (node: N) => Record<string, unknown>;\n}\n\n/** Register the generic doc-surface bridge. Returns a {@link Bridge}. */\nexport function registerDocBridge<N extends DocNode, TOp = TreeOp<N>>(\n host: ToolHost,\n options: DocBridgeOptions<N, TOp>,\n): Bridge {\n const { adapter, surface } = options;\n const agent = { ...DEFAULT_AGENT, ...(options.agent ?? {}) };\n const reducer = (options.reducer ?? (treeReducer<N>() as unknown as DocReducer<DocTree<N>, TOp>));\n const stage = options.stagePolicy ?? (autoApply as StagePolicy<TOp>);\n const makeNode =\n options.makeNode ?? (({ id, type, parent, order }, props) => ({ id, type, parent, order, props }) as N);\n const describeNode =\n options.describeNode ?? ((n: N) => ({ id: n.id, type: n.type, parent: n.parent, props: Object.keys(n.props ?? {}) }));\n const disposers: Array<() => void> = [];\n\n // agent_undo / agent_redo / agent_history — always present (undo derives from\n // the reducer, so every doc surface gets working undo for free).\n ensureUndoToolsRegistered(host, { defaultAgentId: agent.id });\n\n let idSeq = 0;\n // The counter restarts with the bridge, so on a tree loaded from elsewhere\n // `surface-1` may well be taken. Skip past anything that already exists\n // rather than minting an id that silently overwrites a node.\n const mintId = () => {\n if (adapter.newId) return adapter.newId();\n const taken = adapter.get().nodes;\n let id: string;\n do id = `${surface}-${(idSeq += 1)}`;\n while (taken[id]);\n return id;\n };\n const target = (elementId?: string): AgentTarget => ({ kind: surface, screenId: adapter.screenId, elementId });\n\n // Staged ops awaiting confirmation.\n const pending = new Map<string, { op: TOp; label: string; targetId?: string }>();\n\n /** Apply an op immediately: reduce → set → push a snapshot-based undo entry. */\n function commit(op: TOp, label: string, targetId?: string): Record<string, unknown> {\n const prev = adapter.get();\n const next = reducer.reduce(prev, op);\n adapter.set(next);\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: surface,\n action: label,\n label,\n undo: () => adapter.set(prev),\n redo: () => adapter.set(next),\n });\n return { ok: true, id: targetId };\n }\n\n /**\n * Auto-apply, or stage for confirmation per the stage policy.\n *\n * The staged case reports the pending id under its OWN key. Returning it as\n * `id` — as this used to — collided with the node id every mutation already\n * reports, so `update`/`remove`/`move` overwrote it and left the agent holding\n * a node id that `confirm` does not accept. The staged write was unconfirmable\n * for three of the four canonical ops, and looked fine from the outside.\n */\n function submit(op: TOp, label: string, targetId?: string): { staged: boolean; id?: string; pendingId?: string } {\n if (stage(op) === \"confirm\") {\n const pendingId = `${surface}-pending-${(idSeq += 1)}`;\n pending.set(pendingId, { op, label, targetId });\n options.onPending?.({ id: pendingId, op, label });\n return { staged: true, id: targetId, pendingId };\n }\n commit(op, label, targetId);\n return { staged: false, id: targetId };\n }\n\n const reg = (\n verb: string,\n description: string,\n properties: Record<string, unknown>,\n required: string[],\n handler: (args: JsonObject) => Record<string, unknown> | Promise<Record<string, unknown>>,\n isMutation: boolean,\n resolveTarget?: (args: JsonObject, result: Record<string, unknown>) => AgentTarget | null,\n ): void => {\n const name = `${surface}_${verb}`;\n const wrapped = async (args: JsonObject) => {\n try {\n // `_text` is the human-facing line; the rest is structuredContent.\n const { _text, ...structured } = await handler(args);\n return textResult(typeof _text === \"string\" ? _text : name, structured);\n } catch (e) {\n return errorResult(e instanceof Error ? e.message : String(e));\n }\n };\n const final = isMutation\n ? wrapToolWithActivity(wrapped, {\n toolName: name,\n agent,\n kind: surface,\n screenId: adapter.screenId,\n resolveTarget: ({ args, result }) => {\n if ((result.structuredContent as JsonObject | undefined)?.staged) return null;\n return resolveTarget?.(args, (result.structuredContent as JsonObject) ?? {}) ?? target();\n },\n })\n : wrapped;\n disposers.push(\n host.registerTool(\n { name, description, inputSchema: { type: \"object\", properties: properties as never, required, additionalProperties: false } },\n final as never,\n ),\n );\n };\n\n // ── Read tools ──────────────────────────────────────────────────────────\n reg(\n \"describe\",\n `Summarize the ${surface} document: node count, roots, and the active surface. Call before reading or writing.`,\n {},\n [],\n () => {\n const tree = adapter.get();\n const ids = Object.keys(tree.nodes);\n return { nodeCount: ids.length, roots: childrenOf(tree, null).map((n) => n.id), _text: `${ids.length} nodes` };\n },\n false,\n );\n reg(\n \"get\",\n `Get the whole ${surface} document tree as JSON.`,\n {},\n [],\n () => ({ tree: adapter.get(), _text: \"full tree\" }),\n false,\n );\n reg(\n \"list\",\n \"List nodes (optionally the children of `parent`), in order.\",\n { parent: { type: [\"string\", \"null\"], description: \"Parent id, or null/omitted for roots.\" } },\n [],\n (args) => {\n const tree = adapter.get();\n const parent = typeof args.parent === \"string\" ? args.parent : null;\n return { nodes: childrenOf(tree, parent).map(describeNode), _text: `children of ${parent ?? \"root\"}` };\n },\n false,\n );\n reg(\n \"get_node\",\n \"Get one node by id.\",\n { id: { type: \"string\" } },\n [\"id\"],\n (args) => {\n const node = adapter.get().nodes[String(args.id)];\n if (!node) throw new Error(`No node ${args.id}`);\n return { node, _text: `node ${node.id}` };\n },\n false,\n );\n\n // ── Canonical op tools ──────────────────────────────────────────────────\n reg(\n \"add\",\n \"Insert a node. Returns its id. Appends under `parent` (or roots) unless `order` is given.\",\n {\n type: { type: \"string\", description: \"Node type discriminant.\" },\n parent: { type: [\"string\", \"null\"], description: \"Parent id, or null for a root.\" },\n props: { type: \"object\", description: \"JSON props bag.\" },\n order: { type: \"string\", description: \"Fractional order key (default: append).\" },\n id: {\n type: \"string\",\n description:\n \"Id for the new node. Supply a meaningful one if you intend to address this node later; omitted means one is minted for you. Must not already exist.\",\n },\n },\n [\"type\"],\n (args) => {\n const tree = adapter.get();\n const parent = typeof args.parent === \"string\" ? args.parent : null;\n // An agent that names the node names the handle it will use afterwards.\n // Minted ids are addressable too, just less memorable.\n const requested = typeof args.id === \"string\" ? args.id : undefined;\n if (requested !== undefined && tree.nodes[requested]) {\n throw new Error(`Node ${requested} already exists — pick a different id or update it instead`);\n }\n const id = requested ?? mintId();\n const order = typeof args.order === \"string\" ? args.order : appendOrder(tree, parent);\n const props = (args.props && typeof args.props === \"object\" ? args.props : {}) as Record<string, unknown>;\n const node = makeNode({ id, type: String(args.type), parent, order }, props);\n const res = submit({ t: \"insert\", node } as unknown as TOp, `add ${args.type} ${id}`, id);\n return { ...res, _text: res.staged ? `staged add ${id} — confirm ${res.pendingId}` : `added ${id}` };\n },\n true,\n (_args, result) => target(result.id as string | undefined),\n );\n reg(\n \"update\",\n \"Merge a props patch into a node.\",\n { id: { type: \"string\" }, patch: { type: \"object\" } },\n [\"id\", \"patch\"],\n (args) => {\n const id = String(args.id);\n if (!adapter.get().nodes[id]) throw new Error(`No node ${id}`);\n const patch = (args.patch && typeof args.patch === \"object\" ? args.patch : {}) as Record<string, unknown>;\n const res = submit({ t: \"set_props\", id, patch } as unknown as TOp, `update ${id}`, id);\n return { ...res, id, _text: res.staged ? `staged update ${id} — confirm ${res.pendingId}` : `updated ${id}` };\n },\n true,\n (args) => target(String(args.id)),\n );\n reg(\n \"remove\",\n \"Remove a node and its subtree.\",\n { id: { type: \"string\" } },\n [\"id\"],\n (args) => {\n const id = String(args.id);\n const tree = adapter.get();\n if (!tree.nodes[id]) throw new Error(`No node ${id}`);\n const count = descendantsOf(tree, id).length + 1;\n const res = submit({ t: \"remove\", id } as unknown as TOp, `remove ${id} (${count} node${count === 1 ? \"\" : \"s\"})`, id);\n return { ...res, id, removed: count, _text: res.staged ? `staged remove ${id} — confirm ${res.pendingId}` : `removed ${id}` };\n },\n true,\n (args) => target(String(args.id)),\n );\n reg(\n \"move\",\n \"Reparent + reorder a node.\",\n { id: { type: \"string\" }, parent: { type: [\"string\", \"null\"] }, order: { type: \"string\", description: \"Fractional order key (default: append under the new parent).\" } },\n [\"id\"],\n (args) => {\n const id = String(args.id);\n const tree = adapter.get();\n if (!tree.nodes[id]) throw new Error(`No node ${id}`);\n const parent = args.parent === null ? null : typeof args.parent === \"string\" ? args.parent : tree.nodes[id]!.parent;\n const order = typeof args.order === \"string\" ? args.order : appendOrder(tree, parent);\n const res = submit({ t: \"move\", id, parent, order } as unknown as TOp, `move ${id}`, id);\n return { ...res, id, _text: res.staged ? `staged move ${id} — confirm ${res.pendingId}` : `moved ${id}` };\n },\n true,\n (args) => target(String(args.id)),\n );\n\n // ── Domain op tools ─────────────────────────────────────────────────────\n for (const t of options.opTools ?? []) {\n reg(\n t.verb,\n t.description,\n t.properties,\n t.required,\n (args) => {\n const built = t.build(args, adapter.get());\n if (built && typeof built === \"object\" && \"error\" in built) throw new Error((built as { error: string }).error);\n const tid = t.targetId?.(args);\n const res = submit(built as TOp, `${t.verb} ${tid ?? \"\"}`.trim(), tid);\n return { ...res, id: tid, _text: res.staged ? `staged ${t.verb} — confirm ${res.pendingId}` : t.verb };\n },\n true,\n (args) => target(t.targetId?.(args)),\n );\n }\n\n // ── Staged-write confirm / reject ───────────────────────────────────────\n reg(\n \"confirm\",\n \"Apply a staged op. Pass the `pendingId` a staged mutation returned — not the node `id` it also returns.\",\n { id: { type: \"string\", description: \"The `pendingId` from a staged mutation.\" } },\n [\"id\"],\n (args) => {\n const id = String(args.id);\n const p = pending.get(id);\n if (!p) throw new Error(`No pending op ${id}`);\n pending.delete(id);\n commit(p.op, p.label, p.targetId);\n return { ok: true, applied: p.label, id: p.targetId, _text: `applied ${p.label}` };\n },\n true,\n (_args, result) => target(result.id as string | undefined),\n );\n reg(\n \"reject\",\n \"Discard a staged op. Pass the `pendingId` a staged mutation returned — not the node `id` it also returns.\",\n { id: { type: \"string\", description: \"The `pendingId` from a staged mutation.\" } },\n [\"id\"],\n (args) => {\n const id = String(args.id);\n const p = pending.get(id);\n if (!p) throw new Error(`No pending op ${id}`);\n pending.delete(id);\n return { ok: true, rejected: p.label, _text: `rejected ${p.label}` };\n },\n false,\n );\n\n return {\n id: surface,\n title: surface,\n dispose: () => {\n for (const d of disposers) d();\n pending.clear();\n },\n };\n}\n"]}
@@ -279,6 +279,7 @@ var SseRelayTransport = class {
279
279
  this.listeners = /* @__PURE__ */ new Set();
280
280
  this.state = "idle";
281
281
  this.peers = /* @__PURE__ */ new Set();
282
+ this.peerListeners = /* @__PURE__ */ new Set();
282
283
  this.opts = options;
283
284
  this.expectedToken = options.token;
284
285
  }
@@ -339,6 +340,8 @@ var SseRelayTransport = class {
339
340
  this.es?.close();
340
341
  this.es = void 0;
341
342
  this.connected = false;
343
+ this.peers.clear();
344
+ this.notifyPeers();
342
345
  this.setState("closed");
343
346
  }
344
347
  onStateChange(listener) {
@@ -346,6 +349,28 @@ var SseRelayTransport = class {
346
349
  listener(this.state);
347
350
  return () => this.listeners.delete(listener);
348
351
  }
352
+ /** How many remote peers (agents) are currently attached to this session. */
353
+ peerCount() {
354
+ return this.peers.size;
355
+ }
356
+ /**
357
+ * Subscribe to peer arrivals/departures. Fires immediately with the current
358
+ * count.
359
+ *
360
+ * This is the ONLY honest answer to "is an agent actually here?".
361
+ * `onStateChange` reports the BROWSER's own channel to the relay, which opens
362
+ * the instant sharing starts — so a UI keyed on it announces "Agent is
363
+ * driving" to a human who has not yet handed the link to anybody, and can
364
+ * never tell them when one really arrives.
365
+ */
366
+ onPeersChange(listener) {
367
+ this.peerListeners.add(listener);
368
+ listener(this.peers.size);
369
+ return () => this.peerListeners.delete(listener);
370
+ }
371
+ notifyPeers() {
372
+ for (const l of this.peerListeners) l(this.peers.size);
373
+ }
349
374
  /**
350
375
  * For relays that wrap each frame with auth metadata: hosts can call this
351
376
  * directly when a frame arrives via a non-SSE path. The transport will
@@ -380,6 +405,7 @@ var SseRelayTransport = class {
380
405
  if ("method" in message && message.method === "notifications/peer_joined") {
381
406
  const subscriberId = String(message.params?.subscriberId ?? "peer");
382
407
  this.peers.add(subscriberId);
408
+ this.notifyPeers();
383
409
  fancyAutoCommon.emitActivity({
384
410
  agentId: "agent",
385
411
  agentName: "Agent",
@@ -394,6 +420,7 @@ var SseRelayTransport = class {
394
420
  if ("method" in message && message.method === "notifications/peer_left") {
395
421
  const subscriberId = String(message.params?.subscriberId ?? "peer");
396
422
  this.peers.delete(subscriberId);
423
+ this.notifyPeers();
397
424
  if (this.peers.size === 0) {
398
425
  fancyAutoCommon.emitActivity({
399
426
  agentId: "agent",