@particle-academy/agent-integrations 0.48.0 → 0.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -0
- package/README.md +45 -0
- package/dist/bridges/screens.d.cts +36 -5
- package/dist/bridges/screens.d.ts +36 -5
- package/dist/bridges-catalog.cjs +24 -8
- package/dist/bridges-catalog.cjs.map +1 -1
- package/dist/bridges-catalog.js +1 -1
- package/dist/bridges-features.cjs +10 -6
- package/dist/bridges-features.cjs.map +1 -1
- package/dist/bridges-features.js +1 -1
- package/dist/bridges-navigation.cjs +4 -4
- package/dist/bridges-navigation.cjs.map +1 -1
- package/dist/bridges-navigation.js +1 -1
- package/dist/bridges-passkeys.cjs +6 -2
- package/dist/bridges-passkeys.cjs.map +1 -1
- package/dist/bridges-passkeys.js +1 -1
- package/dist/bridges-screens.cjs +71 -17
- package/dist/bridges-screens.cjs.map +1 -1
- package/dist/bridges-screens.js +1 -1
- package/dist/{chunk-G6CRHFWU.js → chunk-4WVLZ6YP.js} +8 -4
- package/dist/chunk-4WVLZ6YP.js.map +1 -0
- package/dist/{chunk-GVTBMJU6.js → chunk-5M5ELTHE.js} +12 -8
- package/dist/chunk-5M5ELTHE.js.map +1 -0
- package/dist/{chunk-OHNGURUJ.js → chunk-BG3QXNM6.js} +6 -6
- package/dist/chunk-BG3QXNM6.js.map +1 -0
- package/dist/{chunk-7NVATRLE.js → chunk-HOZCDDRA.js} +74 -19
- package/dist/chunk-HOZCDDRA.js.map +1 -0
- package/dist/{chunk-CS3CHGYC.js → chunk-NH6HUVXQ.js} +26 -10
- package/dist/chunk-NH6HUVXQ.js.map +1 -0
- package/dist/index.cjs +123 -44
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +6 -6
- package/package.json +2 -2
- package/dist/chunk-7NVATRLE.js.map +0 -1
- package/dist/chunk-CS3CHGYC.js.map +0 -1
- package/dist/chunk-G6CRHFWU.js.map +0 -1
- package/dist/chunk-GVTBMJU6.js.map +0 -1
- package/dist/chunk-OHNGURUJ.js.map +0 -1
|
@@ -129,8 +129,12 @@ function registerPasskeyBridge(host, options) {
|
|
|
129
129
|
bridgeId: surfaceId,
|
|
130
130
|
action: "passkey_rename",
|
|
131
131
|
label: `Renamed passkey to ${name || "(unnamed)"}`,
|
|
132
|
-
undo: () =>
|
|
133
|
-
|
|
132
|
+
undo: async () => {
|
|
133
|
+
await adapter.rename({ id, name: previous });
|
|
134
|
+
},
|
|
135
|
+
redo: async () => {
|
|
136
|
+
await adapter.rename({ id, name });
|
|
137
|
+
}
|
|
134
138
|
});
|
|
135
139
|
return textResult(`Renamed passkey ${id} to ${name || "(unnamed)"}`, { id, name, previous });
|
|
136
140
|
},
|
|
@@ -189,5 +193,5 @@ function registerPasskeyBridge(host, options) {
|
|
|
189
193
|
}
|
|
190
194
|
|
|
191
195
|
export { PASSKEY_BRIDGE_TOOLS, registerPasskeyBridge };
|
|
192
|
-
//# sourceMappingURL=chunk-
|
|
193
|
-
//# sourceMappingURL=chunk-
|
|
196
|
+
//# sourceMappingURL=chunk-4WVLZ6YP.js.map
|
|
197
|
+
//# sourceMappingURL=chunk-4WVLZ6YP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bridges/passkeys.ts"],"names":[],"mappings":";;;;;AAiKA,IAAM,gBAAgB,EAAE,EAAA,EAAI,SAAS,IAAA,EAAM,OAAA,EAAS,OAAO,SAAA,EAAU;AAErE,IAAM,GAAA,GAAM,CAAC,CAAA,EAAY,QAAA,GAAW,OAAgB,OAAO,CAAA,KAAM,WAAW,CAAA,GAAI,QAAA;AAUhF,SAAS,UAAU,MAAA,EAAgD;AACjE,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,GAAA,CAAI,MAAA,EAAQ,EAAE,CAAA;AAAA,IAClB,MAAM,OAAO,MAAA,EAAQ,IAAA,KAAS,QAAA,GA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CAAA,IAAK,SAAA,CAAU,MAAA,CAAO,CAAC,GAAG,CAAA,EAAE;AAAA,IACzC;AAAA,GACF;AACF","file":"chunk-4WVLZ6YP.js","sourcesContent":["import { textResult, errorResult } from \"../mcp/server\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport type { JsonObject } from \"../mcp/types\";\nimport type { Bridge } from \"./types\";\nimport { wrapToolWithActivity } from \"../presence/wrap-tool-with-activity\";\nimport type { AgentTarget } from \"../presence/types\";\nimport { pushUndoEntry } from \"../undo/undo-stack\";\nimport { ensureUndoToolsRegistered } from \"../undo/undo-tools\";\n\n/**\n * Bridge for `@particle-academy/fancy-passkeys-ui` — the **management** half of\n * a passkey (WebAuthn) surface, and only that half.\n *\n * ## The absence is the design\n *\n * There is **no tool here that completes an authentication or registration\n * ceremony**, and there must never be one. Not `passkey_authenticate`, not\n * `passkey_sign_in`, not `passkey_complete`, not a \"headless\" variant behind a\n * flag.\n *\n * The reason is construction, not policy. `navigator.credentials.get()` requires\n * a user gesture and a biometric or PIN — both things only the person at the\n * keyboard has. An agent-drivable passkey login would be a bypass of the exact\n * property that makes a passkey worth more than a password: that possession of\n * the credential cannot be delegated, replayed, or phished. A bridge offering\n * one would quietly turn a phishing-resistant factor back into a bearer token.\n *\n * So the boundary sits where the cryptography already puts it, and the tool set\n * is drawn to match: **read the management surface, rename, propose, ask the\n * human to start a ceremony.** `bridges/__tests__/passkeys.test.ts` asserts the\n * registered tool names against a closed list, so \"finishing\" this bridge with a\n * sign-in tool fails CI rather than shipping.\n *\n * ## What it does do\n *\n * passkey_list the user's credentials (whitelisted fields only)\n * passkey_status browser support + what the surface currently shows\n * passkey_rename relabel one credential, by credential ID (undoable)\n * passkey_revoke **STAGES** a revoke for the human to confirm\n * passkey_begin_enrollment opens the enrollment prompt; returns immediately\n *\n * `passkey_revoke` never revokes. Revoking a passkey is destructive and revoking\n * the last one is a lockout, so the confirming click comes from the human at the\n * surface — there is deliberately **no `pendingMode: false`**, no `confirm: true`\n * argument, and no host hook that turns staging off. On this bridge staging is\n * not a mode.\n *\n * The adapter type is declared LOCALLY (like `features` / `catalog`) so the\n * bridge builds and type-checks with the sibling package absent. A host wiring a\n * live `PasskeyManager` satisfies it structurally, with no import.\n */\n\n/**\n * One credential as the bridge is willing to describe it — the `PasskeySummary`\n * shape both passkey backends already serialise.\n *\n * Everything the server stores that is NOT on this list — the COSE public key,\n * the user handle, the signature counter, the attestation statement and trust\n * path — is absent on purpose, and {@link toSummary} re-projects onto exactly\n * these keys rather than trusting the adapter to have withheld them. A host that\n * hands `list()` its raw ORM model (the obvious thing to do) therefore cannot\n * leak credential material through an MCP tool by accident.\n */\nexport type PasskeySummaryLike = {\n /** base64url credential ID — the handle every action here is keyed by. */\n id: string;\n /** Human-chosen label, or null when the user never named it. */\n name: string | null;\n /** ISO-8601. */\n createdAt: string;\n /** ISO-8601, or null when never used to sign in. */\n lastUsedAt: string | null;\n /** Transport hints (\"internal\", \"hybrid\", \"usb\", …). */\n transports: string[];\n /** True for a synced passkey (BE/BS flags); false means this device only. */\n backedUp: boolean;\n /** Authenticator model id. Stored, never a trust decision. */\n aaguid: string;\n /** ISO-8601 when the signature counter regressed — a suspected clone. */\n clonedAt: string | null;\n};\n\n/** What the browser can do, as the three `./client` predicates report it. */\nexport type PasskeySupport = {\n supported: boolean;\n /** Touch ID / Windows Hello present? `null` while unknown. */\n platformAuthenticator?: boolean | null;\n /** Can the browser offer a passkey from a username field? `null` while unknown. */\n conditionalUi?: boolean | null;\n};\n\n/** A read of what the management surface is currently showing. */\nexport type PasskeySurfaceState = {\n status?: \"idle\" | \"busy\" | \"error\";\n /** `{ code, message }` as carried in surface state — never an Error. */\n error?: { code: string; message: string } | null;\n /** The revoke awaiting a human's confirmation, if any. */\n pendingRevoke?: { id: string; isLastPasskey: boolean } | null;\n /** Credential ID currently being renamed, if any. */\n renamingId?: string | null;\n};\n\n/**\n * Host-provided access to the management surface. Mirrors the props a\n * `PasskeyManager` is already wired with, so a host usually passes the same four\n * callbacks it passed the component.\n */\nexport type PasskeyBridgeAdapter = {\n /** Stable id for this surface instance. Surfaces in activity logs. */\n id?: string;\n title?: string;\n screenId?: string;\n\n /** The signed-in user's credentials. */\n list(): PasskeySummaryLike[] | Promise<PasskeySummaryLike[]>;\n\n /** Relabel one credential. Cosmetic, reversible, and undoable here. */\n rename(input: { id: string; name: string }): void | Promise<void>;\n\n /**\n * **Stage** a revoke for human confirmation — the `pendingRevoke` the surface\n * renders a confirm/cancel dialog for. It must NOT revoke; a host that wires\n * this to a delete call has removed the human from the loop the bridge was\n * built around.\n */\n proposeRevoke(input: { id: string }): PasskeyProposal | Promise<PasskeyProposal>;\n\n /**\n * Open the enrollment prompt on the human's screen and return immediately.\n * The ceremony completes on their authenticator or not at all.\n */\n beginEnrollment?(input: { name?: string }): void | Promise<void>;\n\n /** Browser capability flags, if the host tracks them. */\n support?(): PasskeySupport | Promise<PasskeySupport>;\n\n /** What the surface currently shows. */\n state?(): PasskeySurfaceState | Promise<PasskeySurfaceState>;\n};\n\nexport type PasskeyProposal = { staged: true; isLastPasskey: boolean };\n\nexport type PasskeyBridgeOptions = {\n adapter: PasskeyBridgeAdapter;\n agent?: { id: string; name?: string; color?: string };\n /**\n * Also route `passkey_rename` through {@link confirm}. Off by default: a\n * rename is cosmetic, reversible and pushed onto the undo stack. Worth turning\n * on where the label itself carries trust — a rogue credential relabelled\n * \"Avery's iPhone\" survives a human's audit of the list.\n */\n confirmRename?: boolean;\n /**\n * Host confirmation hook for renames, when {@link confirmRename} is on.\n *\n * Note there is no revoke case: a revoke is staged into the surface and\n * confirmed there, never through a hook the agent's own host supplies.\n */\n confirm?: (req: { action: \"passkey_rename\"; id: string; name: string }) => boolean | Promise<boolean>;\n};\n\nconst DEFAULT_AGENT = { id: \"agent\", name: \"Agent\", color: \"#a855f7\" };\n\nconst str = (v: unknown, fallback = \"\"): string => (typeof v === \"string\" ? v : fallback);\n\n/**\n * Project an adapter record onto exactly the public summary fields.\n *\n * Deliberately a whitelist and not a `delete` of known-bad keys: a blacklist has\n * to be updated every time a backend grows a column, and the failure mode of\n * forgetting is silently publishing credential material to every agent in the\n * session.\n */\nfunction toSummary(record: PasskeySummaryLike): PasskeySummaryLike {\n return {\n id: str(record?.id),\n name: typeof record?.name === \"string\" ? record.name : null,\n createdAt: str(record?.createdAt),\n lastUsedAt: typeof record?.lastUsedAt === \"string\" ? record.lastUsedAt : null,\n transports: Array.isArray(record?.transports) ? record.transports.map((t) => String(t)) : [],\n backedUp: record?.backedUp === true,\n aaguid: str(record?.aaguid),\n clonedAt: typeof record?.clonedAt === \"string\" ? record.clonedAt : null,\n };\n}\n\n/**\n * The complete set of tools this bridge may ever register.\n *\n * Exported so the test suite — and anyone auditing what an agent can reach —\n * can assert the registered names against it rather than eyeballing the file.\n */\nexport const PASSKEY_BRIDGE_TOOLS = [\n \"passkey_list\",\n \"passkey_status\",\n \"passkey_rename\",\n \"passkey_revoke\",\n \"passkey_begin_enrollment\",\n] as const;\n\n/**\n * registerPasskeyBridge — MCP tools over a passkey **management** surface.\n *\n * Read the credential list, read browser support and surface state, rename a\n * credential, propose a revoke for the human to confirm, and ask for an\n * enrollment prompt. Nothing signs anyone in; see the file header for why that\n * is a property rather than a gap.\n */\nexport function registerPasskeyBridge(host: ToolHost, options: PasskeyBridgeOptions): Bridge {\n const { adapter } = options;\n const agent = { ...DEFAULT_AGENT, ...(options.agent ?? {}) };\n const surfaceId = adapter.id ?? \"passkeys\";\n const disposers: Array<() => void> = [];\n\n ensureUndoToolsRegistered(host, { defaultAgentId: agent.id });\n\n const target = (elementId?: string, label?: string): AgentTarget => ({\n kind: \"custom\",\n screenId: adapter.screenId,\n elementId,\n label: label ?? surfaceId,\n });\n\n const reg = (\n name: string,\n description: string,\n properties: Record<string, unknown>,\n required: string[],\n handler: (args: JsonObject) => Promise<unknown> | unknown,\n resolveTarget: false | ((args: JsonObject) => AgentTarget),\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 as never, {\n toolName: name,\n agent,\n kind: \"custom\",\n screenId: adapter.screenId,\n resolveTarget: ({ args }) => resolveTarget(args as JsonObject),\n })\n : wrapped;\n disposers.push(\n host.registerTool(\n {\n name,\n description,\n inputSchema: {\n type: \"object\",\n properties: properties as Record<string, never>,\n required,\n additionalProperties: false,\n },\n },\n final as never,\n ),\n );\n };\n\n const findById = async (id: string): Promise<PasskeySummaryLike | null> =>\n (await adapter.list()).map(toSummary).find((p) => p.id === id) ?? null;\n\n // ─── Read ────────────────────────────────────────────────────────────────\n\n reg(\n \"passkey_list\",\n \"List the signed-in user's passkeys: credential id, label, when it was added and last used, transports, whether it is a synced passkey, and whether the server flagged it as a possible clone. Read-only. Public keys, user handles and signature counters are never returned.\",\n {},\n [],\n async () => {\n const passkeys = (await adapter.list()).map(toSummary);\n return textResult(JSON.stringify(passkeys, null, 2), { passkeys, count: passkeys.length });\n },\n false,\n );\n\n reg(\n \"passkey_status\",\n \"Read what this browser can do (passkey support, a built-in authenticator, autofill sign-in) and what the management surface is currently showing (busy/error, a revoke awaiting confirmation, a rename in progress).\",\n {},\n [],\n async () => {\n const support = adapter.support ? await adapter.support() : null;\n const state = adapter.state ? await adapter.state() : null;\n const out = {\n support,\n state,\n // Said in the payload, not only in the docs: an agent reading this to\n // work out \"how do I sign the user in\" should find the answer here.\n canCompleteCeremony: false,\n note: \"A passkey ceremony needs a user gesture and a biometric or PIN. No tool on this bridge can perform one; ask the human to complete it on their device.\",\n };\n return textResult(JSON.stringify(out, null, 2), out);\n },\n false,\n );\n\n // ─── Rename (undoable) ───────────────────────────────────────────────────\n\n reg(\n \"passkey_rename\",\n \"Rename one passkey, by credential id (from passkey_list). Cosmetic and undoable with agent_undo.\",\n {\n id: { type: \"string\", description: \"base64url credential id.\" },\n name: { type: \"string\", description: \"New label, e.g. 'MacBook Touch ID'. Empty string clears it.\" },\n },\n [\"id\", \"name\"],\n async (args) => {\n const id = str(args.id);\n const name = str(args.name);\n if (!id) return errorResult(\"id is required.\");\n\n const existing = await findById(id);\n if (!existing) return errorResult(`No passkey with id ${id}.`);\n\n if (options.confirmRename) {\n if (!options.confirm) {\n return errorResult(\n \"passkey_rename requires confirmation (confirmRename), but the host wired no confirm hook.\",\n );\n }\n const ok = await options.confirm({ action: \"passkey_rename\", id, name });\n if (!ok) return errorResult(`Declined: rename ${id} (human did not confirm).`);\n }\n\n const previous = existing.name ?? \"\";\n await adapter.rename({ id, name });\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: surfaceId,\n action: \"passkey_rename\",\n label: `Renamed passkey to ${name || \"(unnamed)\"}`,\n undo: async () => { await adapter.rename({ id, name: previous }); },\n redo: async () => { await adapter.rename({ id, name }); },\n });\n\n return textResult(`Renamed passkey ${id} to ${name || \"(unnamed)\"}`, { id, name, previous });\n },\n (args) => target(str(args.id), `rename ${str(args.id)}`),\n );\n\n // ─── Revoke — PROPOSAL ONLY ──────────────────────────────────────────────\n\n reg(\n \"passkey_revoke\",\n \"PROPOSE revoking one passkey. This does NOT revoke it: the request is staged on the surface and the human confirms or cancels there. Revoking the last passkey can lock the user out, and the response says when that is the case so you can tell them before they confirm.\",\n { id: { type: \"string\", description: \"base64url credential id.\" } },\n [\"id\"],\n async (args) => {\n const id = str(args.id);\n if (!id) return errorResult(\"id is required.\");\n\n const existing = await findById(id);\n if (!existing) return errorResult(`No passkey with id ${id}.`);\n\n const proposal = await adapter.proposeRevoke({ id });\n const isLastPasskey = proposal?.isLastPasskey === true;\n const out = {\n id,\n name: existing.name,\n staged: true as const,\n awaitingHuman: true as const,\n isLastPasskey,\n };\n\n return textResult(\n isLastPasskey\n ? `Staged a revoke of ${existing.name ?? id}. This is the account's LAST passkey — confirming it removes passkey sign-in entirely. Waiting for the human to confirm or cancel.`\n : `Staged a revoke of ${existing.name ?? id}. Waiting for the human to confirm or cancel on the surface.`,\n out,\n );\n },\n (args) => target(str(args.id), `propose revoke ${str(args.id)}`),\n );\n\n // ─── Enrollment — opens the prompt, never completes it ───────────────────\n\n reg(\n \"passkey_begin_enrollment\",\n \"Ask the surface to start enrolling a new passkey. This only opens the prompt: the ceremony completes on the human's authenticator (Touch ID, Windows Hello, phone, security key) or it does not complete at all. Returns immediately.\",\n { name: { type: \"string\", description: \"Optional label to pre-fill for the new passkey.\" } },\n [],\n async (args) => {\n if (!adapter.beginEnrollment) return errorResult(\"Host did not wire beginEnrollment().\");\n const name = args.name === undefined ? undefined : str(args.name);\n await adapter.beginEnrollment(name === undefined ? {} : { name });\n const out = { awaitingHuman: true as const, ...(name === undefined ? {} : { name }) };\n return textResult(\n \"Enrollment prompt opened. The human has to complete it on their authenticator — there is no tool that can finish it for them.\",\n out,\n );\n },\n (args) => target(undefined, `begin enrollment${args.name ? ` (${str(args.name)})` : \"\"}`),\n );\n\n // ── There is deliberately NO tool below that completes a ceremony. ────────\n // No passkey_authenticate, no passkey_sign_in, no passkey_complete, no\n // passkey_assert. Do not \"finish\" this bridge by adding one — see the header,\n // and see the closed-tool-list test that will fail if you do.\n\n return {\n id: `passkeys:${surfaceId}`,\n title: adapter.title ?? \"Passkeys\",\n dispose: () => {\n for (const d of disposers.splice(0)) d();\n },\n };\n}\n"]}
|
|
@@ -156,10 +156,12 @@ function registerFeaturesBridge(host, options) {
|
|
|
156
156
|
action: "features_grant",
|
|
157
157
|
label: `Granted group ${groupKey}`,
|
|
158
158
|
// Only reverse if WE added it (idempotent assign — don't revoke a pre-existing grant).
|
|
159
|
-
undo: () => {
|
|
160
|
-
if (!already)
|
|
159
|
+
undo: async () => {
|
|
160
|
+
if (!already) await adapter.detachGroup(args.subject, groupKey);
|
|
161
161
|
},
|
|
162
|
-
redo: () =>
|
|
162
|
+
redo: async () => {
|
|
163
|
+
await adapter.assignGroup(args.subject, groupKey);
|
|
164
|
+
}
|
|
163
165
|
});
|
|
164
166
|
return textResult(`Granted group ${groupKey}`, { subject: args.subject, group: groupKey });
|
|
165
167
|
},
|
|
@@ -182,10 +184,12 @@ function registerFeaturesBridge(host, options) {
|
|
|
182
184
|
bridgeId: featuresId,
|
|
183
185
|
action: "features_revoke",
|
|
184
186
|
label: `Revoked group ${groupKey}`,
|
|
185
|
-
undo: () => {
|
|
186
|
-
if (had)
|
|
187
|
+
undo: async () => {
|
|
188
|
+
if (had) await adapter.assignGroup(args.subject, groupKey);
|
|
187
189
|
},
|
|
188
|
-
redo: () =>
|
|
190
|
+
redo: async () => {
|
|
191
|
+
await adapter.detachGroup(args.subject, groupKey);
|
|
192
|
+
}
|
|
189
193
|
});
|
|
190
194
|
return textResult(`Revoked group ${groupKey}`, { subject: args.subject, group: groupKey });
|
|
191
195
|
},
|
|
@@ -217,5 +221,5 @@ function registerFeaturesBridge(host, options) {
|
|
|
217
221
|
}
|
|
218
222
|
|
|
219
223
|
export { registerFeaturesBridge };
|
|
220
|
-
//# sourceMappingURL=chunk-
|
|
221
|
-
//# sourceMappingURL=chunk-
|
|
224
|
+
//# sourceMappingURL=chunk-5M5ELTHE.js.map
|
|
225
|
+
//# sourceMappingURL=chunk-5M5ELTHE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bridges/features.ts"],"names":[],"mappings":";;;;;AAuGA,IAAM,gBAAgB,EAAE,EAAA,EAAI,SAAS,IAAA,EAAM,OAAA,EAAS,OAAO,SAAA,EAAU;AAErE,IAAM,GAAA,GAAM,CAAC,CAAA,EAAY,QAAA,GAAW,OAAgB,OAAO,CAAA,KAAM,WAAW,CAAA,GAAI,QAAA;AAChF,IAAM,GAAA,GAAM,CAAC,CAAA,EAAY,QAAA,GAAW,CAAA,KAAe,OAAO,CAAA,KAAM,QAAA,IAAY,MAAA,CAAO,QAAA,CAAS,CAAC,CAAA,GAAI,CAAA,GAAI,QAAA;AAc9F,SAAS,sBAAA,CAAuB,MAAgB,OAAA,EAAwC;AAC7F,EAAA,MAAM,EAAE,SAAQ,GAA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AAA,IACnM,CAAC,WAAW,SAAS,CAAA;AAAA,IACrB,OAAO,IAAA,KAAS;AACd,MAAA,IAAI,CAAC,OAAA,CAAQ,UAAA,EAAY,OAAO,YAAY,gDAAgD,CAAA;AAC5F,MAAA,MAAM,OAAA,GAAU,GAAA,CAAI,IAAA,CAAK,OAAO,CAAA;AAChC,MAAA,MAAM,MAAA,GAAS,GAAA,CAAI,IAAA,CAAK,MAAA,EAAQ,CAAC,CAAA;AACjC,MAAA,MAAM,EAAA,GAAK,MAAM,OAAA,CAAQ,UAAA,CAAW,SAAS,IAAA,CAAK,OAAA,EAAS,MAAA,EAAQ,IAAA,CAAK,OAAO,CAAA;AAC/E,MAAA,MAAM,SAAA,GAAY,MAAM,OAAA,CAAQ,SAAA,CAAU,SAAS,IAAA,CAAK,OAAA,EAAS,KAAK,OAAO,CAAA;AAC7E,MAAA,MAAM,GAAA,GAAM,EAAE,OAAA,EAAS,EAAA,EAAI,QAAQ,SAAA,EAAU;AAC7C,MAAA,OAAO,UAAA,CAAW,IAAA,CAAK,SAAA,CAAU,GAAG,GAAG,GAAG,CAAA;AAAA,IAC5C,CAAA;AAAA,IACA,CAAC,IAAA,KAAS,MAAA,CAAO,GAAA,CAAI,IAAA,CAAK,OAAO,CAAA,EAAG,CAAA,QAAA,EAAW,GAAA,CAAI,IAAA,CAAK,OAAO,CAAC,CAAA,CAAE;AAAA,GACpE;AAEA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,YAAY,UAAU,CAAA,CAAA;AAAA,IAC1B,KAAA,EAAO,QAAQ,KAAA,IAAS,UAAA;AAAA,IACxB,SAAS,MAAM;AACb,MAAA,KAAA,MAAW,CAAA,IAAK,SAAA,CAAU,MAAA,CAAO,CAAC,GAAG,CAAA,EAAE;AAAA,IACzC;AAAA,GACF;AACF","file":"chunk-5M5ELTHE.js","sourcesContent":["import { textResult, errorResult } from \"../mcp/server\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport type { JsonObject } from \"../mcp/types\";\nimport type { Bridge } from \"./types\";\nimport { wrapToolWithActivity } from \"../presence/wrap-tool-with-activity\";\nimport type { AgentTarget } from \"../presence/types\";\nimport { pushUndoEntry } from \"../undo/undo-stack\";\nimport { ensureUndoToolsRegistered } from \"../undo/undo-tools\";\n\n/**\n * Headless bridge for `@particle-academy/fancy-features` — feature management\n * with NO UI surface. The adapter is the `FeatureManager` (a `FeatureSource`\n * consumer): define features in the registry, check access for a subject,\n * grant/revoke via group assignment, and meter resource usage. Mutations\n * funnel through `wrapToolWithActivity` so presence + undo compose; `grant` /\n * `revoke` are `pendingMode`-gated (they change what a real user can do).\n *\n * The adapter shapes mirror fancy-features' public `FeatureManager` +\n * `FeatureRegistry` + `GroupStore`, defined LOCALLY so the bridge builds with\n * the sibling absent (optional peer). A live `FeatureManager` (plus its\n * `.registry` / `.groupStore`) satisfies this structurally with no import.\n *\n * SUBJECTS over the wire: `Subject` is opaque (`unknown`) in fancy-features.\n * Agents pass a JSON-serializable subject (string id or `{ id, … }` object);\n * the host's stores key on it via their `defaultSubjectKey`.\n */\n\nexport type FeatureGrant = {\n key: string;\n type: \"boolean\" | \"resource\";\n enabled: boolean;\n includedQuantity?: number | null;\n overageLimit?: number | null;\n source?: string;\n config?: Record<string, unknown>;\n};\n\n/** Normalized feature definition (mirror of fancy-features `FeatureDefinition`). */\nexport type FeatureDefinition = {\n key?: string;\n name?: string;\n description?: string;\n type?: \"boolean\" | \"resource\";\n enabled?: boolean;\n limit?: number;\n [k: string]: unknown;\n};\n\n/**\n * Adapter = the `FeatureManager` + its registry + group store. The bridge only\n * needs these members; a real manager exposes them directly.\n */\nexport type FeaturesBridgeAdapter = {\n /** Stable id for this feature manager instance. */\n id?: string;\n title?: string;\n screenId?: string;\n\n // ── Access checks (FeatureManager) ──\n /** Can the subject access the feature now? `manager.canAccess`. */\n canAccess(feature: string, subject?: unknown, context?: unknown): boolean | Promise<boolean>;\n /** Remaining quota for a resource feature (null = unlimited / n-a). `manager.remaining`. */\n remaining(feature: string, subject?: unknown, context?: unknown): number | null | Promise<number | null>;\n /** All enabled feature keys for the subject. `manager.enabled`. */\n enabled(subject?: unknown, context?: unknown): string[] | Promise<string[]>;\n /** Trace a feature's resolution to an AccessResult. `manager.explain`. */\n explain?(feature: string, subject?: unknown, context?: unknown): Promise<unknown> | unknown;\n\n // ── Registry (define) ──\n /** Register a programmatic feature. `manager.registerFeature` / `manager.registry.register`. */\n registerFeature(key: string, definition: FeatureDefinition): void;\n /** Registered feature keys. `manager.registry.keys`. */\n registryKeys(): string[];\n /** Resolve a registered definition (or null). `manager.registry.definition`. */\n definition?(key: string): FeatureDefinition | null | Promise<FeatureDefinition | null>;\n\n // ── Group store (grant / revoke) ──\n /** Assign a subject to a feature group (the grant primitive). `manager.groupStore.assign`. */\n assignGroup(subject: unknown, groupKey: string): void | Promise<void>;\n /** Detach a subject from a group (the revoke primitive). `manager.groupStore.detach`. */\n detachGroup(subject: unknown, groupKey: string): void | Promise<void>;\n /** Group keys assigned to a subject. `manager.groupStore.list`. */\n listGroups(subject: unknown): string[] | Promise<string[]>;\n\n // ── Usage / metering (resource features) ──\n /** Current usage for a resource feature. `manager.usageFor`. Optional. */\n usageFor?(feature: string, subject: unknown): number | Promise<number>;\n /** Atomic check-and-increment quota. `manager.tryConsume`. Optional. */\n tryConsume?(feature: string, subject: unknown, amount?: number, context?: unknown): boolean | Promise<boolean>;\n};\n\nexport type FeaturesBridgeOptions = {\n adapter: FeaturesBridgeAdapter;\n agent?: { id: string; name?: string; color?: string };\n /**\n * Trust-but-verify. When on (default), `features_grant` / `features_revoke`\n * (they change a real subject's entitlements) require `confirm:true` OR a\n * host `confirm` hook. Checks + define + usage are unaffected.\n */\n pendingMode?: boolean;\n confirm?: (req: { action: string; subject: unknown; groupKey: string }) => Promise<boolean> | boolean;\n};\n\nconst DEFAULT_AGENT = { id: \"agent\", name: \"Agent\", color: \"#a855f7\" };\n\nconst str = (v: unknown, fallback = \"\"): string => (typeof v === \"string\" ? v : fallback);\nconst num = (v: unknown, fallback = 0): number => (typeof v === \"number\" && Number.isFinite(v) ? v : fallback);\n\n/**\n * registerFeaturesBridge — full MCP tool set over a headless feature manager.\n *\n * features_list enabled feature keys for a subject\n * features_check can a subject access a feature? (+ remaining for resources)\n * features_explain trace why a feature is on/off for a subject\n * features_define register a feature definition (boolean / resource)\n * features_grant assign a subject to a group (pendingMode-gated, undoable)\n * features_revoke detach a subject from a group (pendingMode-gated, undoable)\n * features_groups list a subject's assigned groups\n * features_consume meter a resource feature (atomic check-and-increment)\n */\nexport function registerFeaturesBridge(host: ToolHost, options: FeaturesBridgeOptions): Bridge {\n const { adapter } = options;\n const agent = { ...DEFAULT_AGENT, ...(options.agent ?? {}) };\n const pendingMode = options.pendingMode ?? true;\n const featuresId = adapter.id ?? \"features\";\n const disposers: Array<() => void> = [];\n\n ensureUndoToolsRegistered(host, { defaultAgentId: agent.id });\n\n const target = (elementId?: string, label?: string): AgentTarget => ({\n kind: \"custom\",\n screenId: adapter.screenId,\n elementId,\n label: label ?? featuresId,\n });\n\n const reg = (\n name: string,\n description: string,\n properties: Record<string, unknown>,\n required: string[],\n handler: (args: JsonObject) => Promise<unknown> | unknown,\n resolveTarget: false | ((args: JsonObject) => AgentTarget),\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 as never, {\n toolName: name,\n agent,\n kind: \"custom\",\n screenId: adapter.screenId,\n resolveTarget: ({ args }) => resolveTarget(args as JsonObject),\n })\n : wrapped;\n disposers.push(\n host.registerTool(\n { name, description, inputSchema: { type: \"object\", properties: properties as Record<string, never>, required, additionalProperties: false } },\n final as never,\n ),\n );\n };\n\n const guardGrant = async (action: string, subject: unknown, groupKey: string, hasConfirmArg: boolean) => {\n if (!pendingMode) return null;\n if (options.confirm) {\n const ok = await options.confirm({ action, subject, groupKey });\n return ok ? null : errorResult(`Declined: ${action} ${groupKey} (human did not confirm).`);\n }\n if (!hasConfirmArg) {\n return errorResult(`${action} is staged (pendingMode). Re-call with confirm:true to apply, or wire a host confirm hook.`);\n }\n return null;\n };\n\n // ─── Read / check tools ──────────────────────────────────────────────────\n\n reg(\n \"features_list\",\n \"List the feature keys enabled for a subject. Pass `subject` (a string id or object).\",\n { subject: { description: \"Opaque subject — string id or { id, … } object.\" }, context: { description: \"Optional resolution context.\" } },\n [],\n async (args) => {\n const keys = await adapter.enabled(args.subject, args.context);\n return textResult(JSON.stringify(keys, null, 2), { subject: args.subject, enabled: keys });\n },\n false,\n );\n\n reg(\n \"features_check\",\n \"Check whether a subject can access a feature. For resource features also returns the remaining quota.\",\n { feature: { type: \"string\" }, subject: { description: \"Opaque subject.\" }, context: { description: \"Optional context.\" } },\n [\"feature\"],\n async (args) => {\n const feature = str(args.feature);\n const allowed = await adapter.canAccess(feature, args.subject, args.context);\n const remaining = await adapter.remaining(feature, args.subject, args.context);\n const out = { feature, allowed, remaining };\n return textResult(JSON.stringify(out), out);\n },\n false,\n );\n\n reg(\n \"features_explain\",\n \"Trace why a feature is on/off for a subject — returns the AccessResult (source, remaining, limit, used).\",\n { feature: { type: \"string\" }, subject: { description: \"Opaque subject.\" }, context: { description: \"Optional context.\" } },\n [\"feature\"],\n async (args) => {\n if (!adapter.explain) return errorResult(\"Host did not wire explain().\");\n const result = await adapter.explain(str(args.feature), args.subject, args.context);\n return textResult(JSON.stringify(result, null, 2), result as Record<string, unknown>);\n },\n false,\n );\n\n reg(\n \"features_groups\",\n \"List the feature groups a subject is assigned to.\",\n { subject: { description: \"Opaque subject.\" } },\n [\"subject\"],\n async (args) => {\n const groups = await adapter.listGroups(args.subject);\n return textResult(JSON.stringify(groups, null, 2), { subject: args.subject, groups });\n },\n false,\n );\n\n // ─── Define ──────────────────────────────────────────────────────────────\n\n reg(\n \"features_define\",\n \"Register a feature definition. type 'boolean' (on/off) or 'resource' (metered with a `limit`). `enabled` sets the default gate.\",\n {\n key: { type: \"string\" },\n name: { type: \"string\" },\n description: { type: \"string\" },\n type: { type: \"string\", enum: [\"boolean\", \"resource\"] },\n enabled: { type: \"boolean\" },\n limit: { type: \"number\", description: \"Resource quota per period (resource type).\" },\n },\n [\"key\"],\n (args) => {\n const key = str(args.key);\n if (!key) return errorResult(\"key is required.\");\n const existed = adapter.registryKeys().includes(key);\n const definition: FeatureDefinition = {\n ...(args.name !== undefined ? { name: str(args.name) } : {}),\n ...(args.description !== undefined ? { description: str(args.description) } : {}),\n ...(args.type !== undefined ? { type: str(args.type) as \"boolean\" | \"resource\" } : {}),\n ...(args.enabled !== undefined ? { enabled: args.enabled === true } : {}),\n ...(args.limit !== undefined ? { limit: num(args.limit) } : {}),\n };\n adapter.registerFeature(key, definition);\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: featuresId,\n action: \"features_define\",\n // Registry has no unregister; undo re-registers the prior definition when we had one.\n label: existed ? `Redefined feature ${key}` : `Defined feature ${key}`,\n undo: () => {},\n redo: () => adapter.registerFeature(key, definition),\n });\n return textResult(`${existed ? \"Redefined\" : \"Defined\"} feature ${key} (${definition.type ?? \"boolean\"})`, { key, definition });\n },\n (args) => target(str(args.key), `define ${str(args.key)}`),\n );\n\n // ─── Grant / revoke (pendingMode-gated) ──────────────────────────────────\n\n reg(\n \"features_grant\",\n \"Grant a subject access by assigning it to a feature group. Staged in pendingMode — pass confirm:true or wire a host confirm hook.\",\n { subject: { description: \"Opaque subject.\" }, group: { type: \"string\", description: \"Feature group key.\" }, confirm: { type: \"boolean\" } },\n [\"subject\", \"group\"],\n async (args) => {\n const groupKey = str(args.group);\n if (!groupKey) return errorResult(\"group is required.\");\n const blocked = await guardGrant(\"features_grant\", args.subject, groupKey, args.confirm === true);\n if (blocked) return blocked;\n const already = (await adapter.listGroups(args.subject)).includes(groupKey);\n await adapter.assignGroup(args.subject, groupKey);\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: featuresId,\n action: \"features_grant\",\n label: `Granted group ${groupKey}`,\n // Only reverse if WE added it (idempotent assign — don't revoke a pre-existing grant).\n undo: async () => { if (!already) await adapter.detachGroup(args.subject, groupKey); },\n redo: async () => { await adapter.assignGroup(args.subject, groupKey); },\n });\n return textResult(`Granted group ${groupKey}`, { subject: args.subject, group: groupKey });\n },\n (args) => target(str(args.group), `grant ${str(args.group)}`),\n );\n\n reg(\n \"features_revoke\",\n \"Revoke access by detaching a subject from a feature group. Staged in pendingMode — pass confirm:true or wire a host confirm hook.\",\n { subject: { description: \"Opaque subject.\" }, group: { type: \"string\" }, confirm: { type: \"boolean\" } },\n [\"subject\", \"group\"],\n async (args) => {\n const groupKey = str(args.group);\n if (!groupKey) return errorResult(\"group is required.\");\n const blocked = await guardGrant(\"features_revoke\", args.subject, groupKey, args.confirm === true);\n if (blocked) return blocked;\n const had = (await adapter.listGroups(args.subject)).includes(groupKey);\n await adapter.detachGroup(args.subject, groupKey);\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: featuresId,\n action: \"features_revoke\",\n label: `Revoked group ${groupKey}`,\n undo: async () => { if (had) await adapter.assignGroup(args.subject, groupKey); },\n redo: async () => { await adapter.detachGroup(args.subject, groupKey); },\n });\n return textResult(`Revoked group ${groupKey}`, { subject: args.subject, group: groupKey });\n },\n (args) => target(str(args.group), `revoke ${str(args.group)}`),\n );\n\n // ─── Usage / metering ────────────────────────────────────────────────────\n\n reg(\n \"features_consume\",\n \"Meter a resource feature: atomic check-and-increment. Returns ok:false if the quota would be exceeded (nothing recorded).\",\n { feature: { type: \"string\" }, subject: { description: \"Opaque subject.\" }, amount: { type: \"number\", description: \"Units to consume. Default 1.\" }, context: { description: \"Optional context.\" } },\n [\"feature\", \"subject\"],\n async (args) => {\n if (!adapter.tryConsume) return errorResult(\"Host did not wire usage metering (tryConsume).\");\n const feature = str(args.feature);\n const amount = num(args.amount, 1);\n const ok = await adapter.tryConsume(feature, args.subject, amount, args.context);\n const remaining = await adapter.remaining(feature, args.subject, args.context);\n const out = { feature, ok, amount, remaining };\n return textResult(JSON.stringify(out), out);\n },\n (args) => target(str(args.feature), `consume ${str(args.feature)}`),\n );\n\n return {\n id: `features:${featuresId}`,\n title: adapter.title ?? \"Features\",\n dispose: () => {\n for (const d of disposers.splice(0)) d();\n },\n };\n}\n"]}
|
|
@@ -159,11 +159,11 @@ function registerNavigationBridge(host, options) {
|
|
|
159
159
|
bridgeId: "navigation",
|
|
160
160
|
action: "nav_visit",
|
|
161
161
|
label: `Navigate to ${url}`,
|
|
162
|
-
undo: () => {
|
|
163
|
-
adapter.visit(from);
|
|
162
|
+
undo: async () => {
|
|
163
|
+
await adapter.visit(from);
|
|
164
164
|
},
|
|
165
|
-
redo: () => {
|
|
166
|
-
adapter.visit(url);
|
|
165
|
+
redo: async () => {
|
|
166
|
+
await adapter.visit(url);
|
|
167
167
|
}
|
|
168
168
|
});
|
|
169
169
|
return textResult(`Navigated to ${url}`, { url });
|
|
@@ -313,5 +313,5 @@ function registerNavigationBridge(host, options) {
|
|
|
313
313
|
}
|
|
314
314
|
|
|
315
315
|
export { registerNavigationBridge };
|
|
316
|
-
//# sourceMappingURL=chunk-
|
|
317
|
-
//# sourceMappingURL=chunk-
|
|
316
|
+
//# sourceMappingURL=chunk-BG3QXNM6.js.map
|
|
317
|
+
//# sourceMappingURL=chunk-BG3QXNM6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bridges/navigation.ts"],"names":[],"mappings":";;;;;AAgHA,IAAM,gBAAgB,EAAE,EAAA,EAAI,SAAS,IAAA,EAAM,OAAA,EAAS,OAAO,SAAA,EAAU;AAYrE,IAAM,SAAA,GAAY,CAAC,IAAA,KACjB,IAAA,GAAO,EAAA,IAAS,IAAA,IAAQ,GAAA,IAAQ,IAAA,IAAQ,GAAA,IAAS,IAAA,KAAS,IAAA,IAAU,IAAA,KAAS,IAAA;AAG/E,SAAS,OAAA,CAAQ,OAAgB,GAAA,EAAqB;AACpD,EAAA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E,CAAC;AAAA,GACnF;AAEA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,YAAA;AAAA,IACJ,KAAA,EAAO,aAAA;AAAA,IACP,SAAS,MAAM;AACb,MAAA,KAAA,MAAW,CAAA,IAAK,WAAW,CAAA,EAAE;AAAA,IAC/B;AAAA,GACF;AACF","file":"chunk-BG3QXNM6.js","sourcesContent":["import { textResult, errorResult } from \"../mcp/server\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport type { JsonObject } from \"../mcp/types\";\nimport type { Bridge } from \"./types\";\nimport { wrapToolWithActivity } from \"../presence/wrap-tool-with-activity\";\nimport type { AgentTarget } from \"../presence/types\";\nimport { pushUndoEntry } from \"../undo/undo-stack\";\nimport { ensureUndoToolsRegistered } from \"../undo/undo-tools\";\n\n/**\n * One interactive element the agent can act on, addressed by a STABLE handle\n * (not a CSS selector) so the agent drives the page the Human+ way — never DOM\n * scraping. The host builds these in `describe()` (data-co-handle → name/id →\n * ARIA role + accessible name).\n */\nexport type PageAction = {\n /** Stable, opaque handle the agent passes back to act on this element. */\n handle: string;\n /** ARIA-ish role: \"link\" | \"button\" | \"textbox\" | \"checkbox\" | \"select\" | … */\n role: string;\n /** Accessible name / label. */\n label: string;\n /** Current value for inputs (omitted/masked for sensitive fields). */\n value?: unknown;\n /** True when activating this is destructive / submits (agent should stage). */\n destructive?: boolean;\n};\n\n/** The page as the agent sees it: where it is + what it can do. */\nexport type PageSnapshot = {\n url: string;\n title: string;\n actions: PageAction[];\n /** Monotonic host revision. Human input advances it and invalidates stale agent intent. */\n revision?: number;\n};\n\n/**\n * Structured page text. Preferred over a plain string from `read()`: the bridge\n * can then put every page-supplied string on its own single line and keep the\n * outline. A plain string is untrusted as a whole and is rendered as ONE line.\n */\nexport type PageReadout = {\n title: string;\n headings: Array<{ level: number; text: string }>;\n text: string;\n};\n\n/** A write the host may want the human to confirm (trust-but-verify). */\nexport type NavigationConfirmRequest = {\n action: \"submit\" | \"click\";\n handle: string;\n label: string;\n};\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/**\n * Host-provided adapter. In the sandbox this is backed by Inertia's `router` +\n * the DOM walker from `@particle-academy/agent-integrations/dom-navigation`.\n * Every method works on stable handles, never raw selectors.\n *\n * Any method may return a Promise: a host driving a page it does not run in\n * (an Electron WebContentsView, via `createRemoteNavigationAdapter`) can only\n * answer asynchronously. The bridge awaits every call.\n */\nexport type NavigationBridgeAdapter = {\n /** Optional fancy-screens screen id for presence targeting. */\n screenId?: string;\n /** Current location. */\n getLocation: () => MaybePromise<{ url: string; title: string }>;\n /** Current human-control revision. Omit to disable stale-intent protection. */\n getRevision?: () => MaybePromise<number>;\n /** Snapshot of the page's actionable elements (stable handles + labels). */\n describe: () => MaybePromise<PageSnapshot>;\n /** Visible text / heading outline for grounding (optional). Prefer a {@link PageReadout}. */\n read?: () => MaybePromise<string | PageReadout>;\n /** Navigate to a URL (host wires to router.visit). */\n visit: (url: string) => void | Promise<void>;\n back?: () => void | Promise<void>;\n forward?: () => void | Promise<void>;\n /** Scroll to coords or to a handle's element. */\n scrollTo: (opts: { x?: number; y?: number; handle?: string }) => void | Promise<void>;\n scrollBy: (dy: number) => void | Promise<void>;\n /** Set a field's value by handle (host dispatches input/change for React). */\n setField: (handle: string, value: unknown) => MaybePromise<{ ok: boolean; error?: string }>;\n /** Activate an element by handle. */\n click: (handle: string) => MaybePromise<{ ok: boolean; error?: string }>;\n /** Submit a form by handle. */\n submit: (handle: string) => Promise<{ ok: boolean; error?: string }> | { ok: boolean; error?: string };\n /**\n * Viewport rect of a handle's element, for agent-presence rendering (cursor +\n * highlight). Returned in tool `meta.rect` so `<CoBrowseCursorLayer>` can show\n * the agent acting on the page. Optional — omit and there's just no cursor.\n */\n rectFor?: (handle: string) => MaybePromise<{ x: number; y: number; width: number; height: number } | null>;\n /**\n * Trust-but-verify hook. When `pendingMode` is on, `page_submit` and\n * destructive `page_click` route through this; the host shows a prompt and\n * resolves true (proceed) / false (declined).\n */\n confirm?: (req: NavigationConfirmRequest) => Promise<boolean>;\n};\n\nexport type NavigationBridgeOptions = {\n adapter: NavigationBridgeAdapter;\n /** Identity tagged into activity events (so the human sees who's driving). */\n agent?: { id: string; name?: string; color?: string };\n /** Route submit + destructive clicks through `adapter.confirm`. Default true. */\n pendingMode?: boolean;\n};\n\nconst DEFAULT_AGENT = { id: \"agent\", name: \"Agent\", color: \"#a855f7\" };\n\n// ───────────── Text safety ─────────────\n//\n// Every string below the adapter is page-supplied, and the page may be hostile.\n// The tool TEXT is what lands in the agent's context, so a line break inside a\n// label would let the page write its own lines there: a forged action, a forged\n// heading, forged tool framing. Each page string is therefore rendered on ONE\n// line, with C0/C1 controls and the Unicode line/paragraph separators replaced,\n// and capped. (Control characters are tested by code point, so no escape\n// sequence is involved.)\n\nconst isControl = (code: number) =>\n code < 0x20 || (code >= 0x7f && code <= 0x9f) || code === 0x2028 || code === 0x2029;\n\n/** One line, controls replaced by spaces, whitespace collapsed, capped at `max`. */\nfunction oneLine(value: unknown, max: number): string {\n const raw = typeof value === \"string\" ? value : value == null ? \"\" : String(value);\n // Bound the work on a hostile multi-megabyte string before scanning it.\n const bounded = raw.length > max * 4 ? raw.slice(0, max * 4) : raw;\n let out = \"\";\n for (const c of bounded) out += isControl(c.charCodeAt(0)) ? \" \" : c;\n out = out.replace(/\\s+/g, \" \").trim();\n return out.length > max ? out.slice(0, max - 3) + \"...\" : out;\n}\n\n/**\n * A handle shown verbatim must not be able to imitate the `[handle] role:`\n * syntax, so only this charset is shown as-is. Anything else — spaces,\n * brackets, controls, or a `~`, which is reserved so a page cannot squat on an\n * alias — is shown as a bridge-minted `~N` alias that resolves back to it.\n */\nconst SAFE_HANDLE = /^[A-Za-z0-9_.:#@/-]{1,80}$/;\n\nconst CAP = { url: 500, title: 200, role: 40, label: 200, heading: 200, text: 4000, error: 300, headings: 50 };\n\nfunction formatReadout(r: string | PageReadout): string {\n if (typeof r === \"string\") return oneLine(r, CAP.text);\n const headings = (Array.isArray(r.headings) ? r.headings : [])\n .slice(0, CAP.headings)\n .map((h) => `H${Math.min(6, Math.max(1, Math.trunc(Number(h?.level)) || 1))}: ${oneLine(h?.text, CAP.heading)}`);\n return [oneLine(r.title, CAP.title), ...headings, \"\", oneLine(r.text, CAP.text)].join(\"\\n\");\n}\n\n/**\n * registerNavigationBridge — site-wide co-browsing. Lets a connected agent\n * navigate, scroll, and (with staged confirm) fill + click any page, addressed\n * by stable handles. Pairs with `useCoBrowseSession` (server + relay) and\n * `<CoBrowsePresence>` (the human's view of the agent). The 12th Fancy bridge.\n */\nexport function registerNavigationBridge(\n host: ToolHost,\n options: NavigationBridgeOptions,\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 let groundedRevision: number | null = null;\n\n const staleIntent = async () => {\n const current = await adapter.getRevision?.();\n if (current === undefined) return null;\n if (groundedRevision === null || groundedRevision !== current) {\n return errorResult(\n `Human took control at page revision ${current}. This agent action was cancelled; call page_describe before acting again.`,\n );\n }\n return null;\n };\n\n /** Alias → page handle, from the latest page_describe. */\n let aliases = new Map<string, string>();\n /** The handle the adapter knows, for a handle the agent passed back. */\n const pageHandle = (handle: string) => aliases.get(handle) ?? handle;\n /** A failure message that may carry page-supplied text. */\n const failure = (message: unknown, fallback: string) => errorResult(oneLine(message ?? fallback, CAP.error) || fallback);\n\n ensureUndoToolsRegistered(host, { defaultAgentId: agent.id });\n\n const target = (label: string, elementId?: string): AgentTarget => ({\n kind: \"navigation\",\n screenId: adapter.screenId,\n elementId,\n label,\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 activity: false | ((args: JsonObject) => AgentTarget),\n ) => {\n const wrapped = async (args: JsonObject) => {\n try {\n return await handler(args);\n } catch (e) {\n // A transport into the page can surface the page's own error text.\n return failure(e instanceof Error ? e.message : String(e), `${name} failed`);\n }\n };\n const final = activity\n ? wrapToolWithActivity(wrapped, {\n toolName: name,\n agent: { id: agent.id, name: agent.name, color: agent.color },\n kind: \"navigation\",\n screenId: adapter.screenId,\n resolveTarget: ({ args }) => activity(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 ),\n );\n };\n\n // ───────────── Read ─────────────\n\n reg(\n \"page_describe\",\n \"Describe the current page: its URL, title, and the interactive elements you can act on (each with a stable `handle`, role, and label). Call this first, and again after navigating.\",\n {},\n [],\n async () => {\n const raw = await adapter.describe();\n const next = new Map<string, string>();\n const actions = (Array.isArray(raw.actions) ? raw.actions : []).map((a) => {\n const handle = String(a.handle ?? \"\");\n if (SAFE_HANDLE.test(handle)) return a;\n const alias = `~${next.size}`;\n next.set(alias, handle);\n return { ...a, handle: alias };\n });\n aliases = next;\n const snap: PageSnapshot = { ...raw, actions };\n const revision = await adapter.getRevision?.();\n if (revision !== undefined) {\n snap.revision = revision;\n groundedRevision = revision;\n }\n const text = [\n `URL: ${oneLine(snap.url, CAP.url)}`,\n `Title: ${oneLine(snap.title, CAP.title)}`,\n \"\",\n ...actions.map(\n (a) =>\n `[${a.handle}] ${oneLine(a.role, CAP.role)}: ${oneLine(a.label, CAP.label)}${a.destructive ? \" (destructive)\" : \"\"}`,\n ),\n ].join(\"\\n\");\n return textResult(text, snap);\n },\n () => target(\"Inspect page\"),\n );\n\n reg(\n \"page_read\",\n \"Read the page's visible text / heading outline for grounding.\",\n {},\n [],\n async () => {\n const r = adapter.read ? await adapter.read() : undefined;\n return textResult(r == null ? \"(host did not provide page text)\" : formatReadout(r));\n },\n () => target(\"Read page\"),\n );\n\n reg(\n \"page_focus\",\n \"Move the agent's visible focus to an interactive element by stable handle without activating it.\",\n { handle: { type: \"string\" } },\n [\"handle\"],\n async (args) => {\n const stale = await staleIntent();\n if (stale) return stale;\n const shown = String(args.handle ?? \"\");\n const handle = pageHandle(shown);\n const action = (await adapter.describe()).actions.find((candidate) => candidate.handle === handle);\n if (!action) return failure(`No element for handle \"${shown}\"`, \"No element for that handle\");\n return textResult(`Focused ${oneLine(shown, CAP.label)}`, {\n handle: shown,\n rect: (await adapter.rectFor?.(handle)) ?? undefined,\n });\n },\n (args) => target(`Focus ${String(args.handle ?? \"\")}`, String(args.handle ?? \"\")),\n );\n\n // ───────────── Navigate / scroll ─────────────\n\n reg(\n \"nav_visit\",\n \"Navigate to a URL (same-site path or absolute). The human watches the page change.\",\n { url: { type: \"string\", description: \"Path like /packages or an absolute URL.\" } },\n [\"url\"],\n async (args) => {\n const stale = await staleIntent();\n if (stale) return stale;\n const url = String(args.url ?? \"\");\n if (!url) return errorResult(\"url is required\");\n // Scheme allow-list: permit only same-site/relative paths and http(s)\n // absolutes. A `javascript:` / `data:` / `file:` / `vbscript:` URL handed\n // to a host that wires visit() to window.location would execute as the\n // human — a semi-trusted agent (steerable via page_read prompt injection)\n // must not reach those.\n const scheme = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(url)?.[1]?.toLowerCase();\n if (scheme && scheme !== \"http\" && scheme !== \"https\") {\n return errorResult(\n `Refusing to navigate to a '${scheme}:' URL. Only http(s) URLs or same-site paths are allowed.`,\n );\n }\n const from = (await adapter.getLocation()).url;\n await adapter.visit(url);\n pushUndoEntry(agent.id, {\n timestamp: Date.now(),\n bridgeId: \"navigation\",\n action: \"nav_visit\",\n label: `Navigate to ${url}`,\n undo: async () => {\n await adapter.visit(from);\n },\n redo: async () => {\n await adapter.visit(url);\n },\n });\n return textResult(`Navigated to ${url}`, { url });\n },\n (args) => target(`Navigate → ${String(args.url ?? \"\")}`),\n );\n\n reg(\n \"nav_back\",\n \"Go back to the previous page.\",\n {},\n [],\n async () => {\n const stale = await staleIntent();\n if (stale) return stale;\n if (!adapter.back) return errorResult(\"Host did not provide back navigation.\");\n await adapter.back();\n return textResult(\"Went back\");\n },\n () => target(\"Back\"),\n );\n\n reg(\n \"nav_forward\",\n \"Go forward to the next page.\",\n {},\n [],\n async () => {\n const stale = await staleIntent();\n if (stale) return stale;\n if (!adapter.forward) return errorResult(\"Host did not provide forward navigation.\");\n await adapter.forward();\n return textResult(\"Went forward\");\n },\n () => target(\"Forward\"),\n );\n\n reg(\n \"nav_scroll_to\",\n \"Scroll the page to absolute coordinates, or to a specific element by its handle.\",\n {\n handle: { type: \"string\", description: \"Scroll this element into view.\" },\n x: { type: \"number\" },\n y: { type: \"number\" },\n },\n [],\n async (args) => {\n const stale = await staleIntent();\n if (stale) return stale;\n const shown = typeof args.handle === \"string\" ? args.handle : undefined;\n const handle = shown === undefined ? undefined : pageHandle(shown);\n await adapter.scrollTo({\n handle,\n x: typeof args.x === \"number\" ? args.x : undefined,\n y: typeof args.y === \"number\" ? args.y : undefined,\n });\n return textResult(\n \"Scrolled\",\n handle ? { handle: shown, rect: (await adapter.rectFor?.(handle)) ?? undefined } : undefined,\n );\n },\n () => target(\"Scroll\"),\n );\n\n reg(\n \"nav_scroll_by\",\n \"Scroll the page by a vertical delta in pixels (negative scrolls up).\",\n { dy: { type: \"number\" } },\n [\"dy\"],\n async (args) => {\n const stale = await staleIntent();\n if (stale) return stale;\n await adapter.scrollBy(Number(args.dy ?? 0));\n return textResult(`Scrolled by ${Number(args.dy ?? 0)}px`);\n },\n () => target(\"Scroll\"),\n );\n\n // ───────────── Co-drive (fill / click / submit) ─────────────\n\n reg(\n \"page_set_field\",\n \"Set a form field's value by handle. The host updates the controlled input and the human sees it change.\",\n {\n handle: { type: \"string\" },\n value: { description: \"Value to set; type matches the field.\" },\n },\n [\"handle\", \"value\"],\n async (args) => {\n const stale = await staleIntent();\n if (stale) return stale;\n const shown = String(args.handle ?? \"\");\n const handle = pageHandle(shown);\n const res = await adapter.setField(handle, args.value);\n if (!res.ok) return failure(res.error, `Could not set ${oneLine(shown, CAP.label)}`);\n return textResult(`${oneLine(shown, CAP.label)} ← ${JSON.stringify(args.value)}`, {\n handle: shown,\n value: args.value,\n rect: (await adapter.rectFor?.(handle)) ?? undefined,\n });\n },\n (args) => target(`Set ${String(args.handle ?? \"\")}`, String(args.handle ?? \"\")),\n );\n\n reg(\n \"page_click\",\n \"Activate an element by handle (link, button, checkbox…). Destructive elements are staged for the human to confirm.\",\n { handle: { type: \"string\" } },\n [\"handle\"],\n async (args) => {\n const stale = await staleIntent();\n if (stale) return stale;\n const shown = String(args.handle ?? \"\");\n const handle = pageHandle(shown);\n const action = (await adapter.describe()).actions.find((a) => a.handle === handle);\n const rect = (await adapter.rectFor?.(handle)) ?? undefined; // capture before the click may navigate away\n if (pendingMode && action?.destructive && adapter.confirm) {\n const ok = await adapter.confirm({ action: \"click\", handle, label: action.label });\n if (!ok) return errorResult(\"Declined by user\");\n }\n const res = await adapter.click(handle);\n if (!res.ok) return failure(res.error, `Could not click ${oneLine(shown, CAP.label)}`);\n return textResult(`Clicked ${oneLine(shown, CAP.label)}`, { handle: shown, rect });\n },\n (args) => target(`Click ${String(args.handle ?? \"\")}`, String(args.handle ?? \"\")),\n );\n\n reg(\n \"page_submit\",\n \"Submit a form by handle. Always staged for the human to confirm when pendingMode is on.\",\n { handle: { type: \"string\" } },\n [\"handle\"],\n async (args) => {\n const stale = await staleIntent();\n if (stale) return stale;\n const shown = String(args.handle ?? \"\");\n const handle = pageHandle(shown);\n const rect = (await adapter.rectFor?.(handle)) ?? undefined; // capture before the submit navigates\n if (pendingMode && adapter.confirm) {\n const ok = await adapter.confirm({ action: \"submit\", handle, label: handle });\n if (!ok) return errorResult(\"Declined by user\");\n }\n const res = await adapter.submit(handle);\n if (!res.ok) return failure(res.error, \"Submit failed\");\n return textResult(`Submitted ${oneLine(shown, CAP.label)}`, { handle: shown, rect });\n },\n (args) => target(`Submit ${String(args.handle ?? \"\")}`, String(args.handle ?? \"\")),\n );\n\n return {\n id: \"navigation\",\n title: \"Co-browsing\",\n dispose: () => {\n for (const d of disposers) d();\n },\n };\n}\n"]}
|
|
@@ -1,9 +1,33 @@
|
|
|
1
1
|
import { ensureUndoToolsRegistered } from './chunk-R4XXOGQH.js';
|
|
2
2
|
import { wrapToolWithActivity } from './chunk-2VENWGLZ.js';
|
|
3
|
+
import { emitActivity } from './chunk-C3TYI5TJ.js';
|
|
3
4
|
import { textResult, errorResult } from './chunk-CZV3WUW5.js';
|
|
4
5
|
|
|
5
6
|
// src/bridges/screens.ts
|
|
6
7
|
var DEFAULT_AGENT = { id: "agent", name: "Agent", color: "#a855f7" };
|
|
8
|
+
function hostErrorMessage(e, fallback) {
|
|
9
|
+
let msg;
|
|
10
|
+
if (e instanceof Error) msg = e.message;
|
|
11
|
+
else if (typeof e === "string") msg = e;
|
|
12
|
+
else if (e && typeof e === "object" && typeof e.message === "string") {
|
|
13
|
+
msg = e.message;
|
|
14
|
+
}
|
|
15
|
+
const firstFrame = msg ? msg.search(/\n\s+at\s/) : -1;
|
|
16
|
+
if (msg && firstFrame >= 0) msg = msg.slice(0, firstFrame);
|
|
17
|
+
msg = msg?.trim();
|
|
18
|
+
return msg ? msg : fallback;
|
|
19
|
+
}
|
|
20
|
+
async function commit(run, fallback) {
|
|
21
|
+
try {
|
|
22
|
+
const r = await run();
|
|
23
|
+
if (r && typeof r === "object" && r.ok === false) {
|
|
24
|
+
return { ok: false, error: hostErrorMessage(r.error, fallback) };
|
|
25
|
+
}
|
|
26
|
+
return { ok: true };
|
|
27
|
+
} catch (e) {
|
|
28
|
+
return { ok: false, error: hostErrorMessage(e, fallback) };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
7
31
|
function registerScreensBridge(host, options) {
|
|
8
32
|
const { adapter } = options;
|
|
9
33
|
const agent = { ...DEFAULT_AGENT, ...options.agent ?? {} };
|
|
@@ -19,7 +43,7 @@ function registerScreensBridge(host, options) {
|
|
|
19
43
|
try {
|
|
20
44
|
return await handler(args);
|
|
21
45
|
} catch (e) {
|
|
22
|
-
return errorResult(e
|
|
46
|
+
return errorResult(hostErrorMessage(e, `${name} failed.`));
|
|
23
47
|
}
|
|
24
48
|
};
|
|
25
49
|
const final = isMutation ? wrapToolWithActivity(wrapped, {
|
|
@@ -81,20 +105,40 @@ function registerScreensBridge(host, options) {
|
|
|
81
105
|
config: { type: "object", description: "Template-specific config (e.g. { fields: [...] } for a form)." }
|
|
82
106
|
},
|
|
83
107
|
["id", "kind"],
|
|
84
|
-
(args) => {
|
|
85
|
-
|
|
108
|
+
async (args) => {
|
|
109
|
+
const createScreen = adapter.createScreen;
|
|
110
|
+
if (!createScreen) return errorResult("Host did not provide createScreen.");
|
|
86
111
|
const id = String(args.id);
|
|
87
112
|
const kind = String(args.kind);
|
|
88
113
|
if (adapter.listScreens().find((s) => s.id === id)) {
|
|
89
114
|
return errorResult(`Screen ${id} already exists. Use screens_destroy first or pick a fresh id.`);
|
|
90
115
|
}
|
|
91
|
-
|
|
116
|
+
const created = await commit(() => createScreen({
|
|
92
117
|
id,
|
|
93
118
|
title: typeof args.title === "string" ? args.title : void 0,
|
|
94
119
|
kind,
|
|
95
120
|
config: args.config && typeof args.config === "object" ? args.config : void 0
|
|
96
|
-
});
|
|
97
|
-
|
|
121
|
+
}), `Host failed to create screen "${id}".`);
|
|
122
|
+
if (!created.ok) return errorResult(created.error);
|
|
123
|
+
const activated = await commit(() => adapter.setActive(id), `Host failed to activate screen "${id}".`);
|
|
124
|
+
if (!activated.ok) {
|
|
125
|
+
const state = { id, kind, created: true, activated: false };
|
|
126
|
+
emitActivity({
|
|
127
|
+
agentId: agent.id,
|
|
128
|
+
agentName: agent.name,
|
|
129
|
+
agentColor: agent.color,
|
|
130
|
+
target: target(id),
|
|
131
|
+
action: "screens_create",
|
|
132
|
+
timestamp: Date.now(),
|
|
133
|
+
meta: state
|
|
134
|
+
});
|
|
135
|
+
return {
|
|
136
|
+
...errorResult(
|
|
137
|
+
`Screen "${id}" was created but not activated: ${activated.error} The screen exists; do not call screens_create again. Call screens_navigate to show it, or screens_destroy to remove it.`
|
|
138
|
+
),
|
|
139
|
+
structuredContent: state
|
|
140
|
+
};
|
|
141
|
+
}
|
|
98
142
|
return textResult(`Created ${kind} screen "${id}"`, { id, kind });
|
|
99
143
|
},
|
|
100
144
|
true,
|
|
@@ -105,13 +149,15 @@ function registerScreensBridge(host, options) {
|
|
|
105
149
|
"Remove a previously-created screen. Active screen falls back to the first remaining one (or null).",
|
|
106
150
|
{ id: { type: "string" } },
|
|
107
151
|
["id"],
|
|
108
|
-
(args) => {
|
|
109
|
-
|
|
152
|
+
async (args) => {
|
|
153
|
+
const destroyScreen = adapter.destroyScreen;
|
|
154
|
+
if (!destroyScreen) return errorResult("Host did not provide destroyScreen.");
|
|
110
155
|
const id = String(args.id);
|
|
111
156
|
if (!adapter.listScreens().find((s) => s.id === id)) {
|
|
112
157
|
return errorResult(`No screen with id ${id}`);
|
|
113
158
|
}
|
|
114
|
-
|
|
159
|
+
const done = await commit(() => destroyScreen(id), `Host failed to destroy screen "${id}".`);
|
|
160
|
+
if (!done.ok) return errorResult(done.error);
|
|
115
161
|
return textResult(`Destroyed screen ${id}`, { id });
|
|
116
162
|
},
|
|
117
163
|
true,
|
|
@@ -125,9 +171,15 @@ function registerScreensBridge(host, options) {
|
|
|
125
171
|
layout: { type: "string", enum: ["single", "split-h", "split-v", "grid-2x2", "stack"] }
|
|
126
172
|
},
|
|
127
173
|
["id", "layout"],
|
|
128
|
-
(args) => {
|
|
129
|
-
|
|
130
|
-
|
|
174
|
+
async (args) => {
|
|
175
|
+
const updateScreenContent = adapter.updateScreenContent;
|
|
176
|
+
if (!updateScreenContent) return errorResult("Host did not provide updateScreenContent.");
|
|
177
|
+
const id = String(args.id);
|
|
178
|
+
const done = await commit(
|
|
179
|
+
() => updateScreenContent(id, { layout: String(args.layout) }),
|
|
180
|
+
`Host failed to change the layout of screen "${id}".`
|
|
181
|
+
);
|
|
182
|
+
if (!done.ok) return errorResult(done.error);
|
|
131
183
|
return textResult(`Layout of ${args.id} \u2192 ${args.layout}`, { id: args.id, layout: args.layout });
|
|
132
184
|
},
|
|
133
185
|
true,
|
|
@@ -141,11 +193,13 @@ function registerScreensBridge(host, options) {
|
|
|
141
193
|
partial: { type: "object", description: "Shallow-merged into the screen's config." }
|
|
142
194
|
},
|
|
143
195
|
["id", "partial"],
|
|
144
|
-
(args) => {
|
|
145
|
-
|
|
196
|
+
async (args) => {
|
|
197
|
+
const updateScreenContent = adapter.updateScreenContent;
|
|
198
|
+
if (!updateScreenContent) return errorResult("Host did not provide updateScreenContent.");
|
|
146
199
|
const id = String(args.id);
|
|
147
200
|
const partial = args.partial && typeof args.partial === "object" ? args.partial : {};
|
|
148
|
-
|
|
201
|
+
const done = await commit(() => updateScreenContent(id, partial), `Host failed to update screen "${id}".`);
|
|
202
|
+
if (!done.ok) return errorResult(done.error);
|
|
149
203
|
return textResult(`Updated content of ${id}`, { id });
|
|
150
204
|
},
|
|
151
205
|
true,
|
|
@@ -156,13 +210,14 @@ function registerScreensBridge(host, options) {
|
|
|
156
210
|
"Switch the human's view to a different screen. The host updates its router / tab state and re-renders.",
|
|
157
211
|
{ screen: { type: "string", description: "Screen id to activate." } },
|
|
158
212
|
["screen"],
|
|
159
|
-
(args) => {
|
|
213
|
+
async (args) => {
|
|
160
214
|
const screenId = String(args.screen ?? "");
|
|
161
215
|
const screens = adapter.listScreens();
|
|
162
216
|
if (!screens.find((s) => s.id === screenId)) {
|
|
163
217
|
return errorResult(`No screen registered with id "${screenId}". Call screens_list first.`);
|
|
164
218
|
}
|
|
165
|
-
adapter.setActive(screenId);
|
|
219
|
+
const done = await commit(() => adapter.setActive(screenId), `Host failed to navigate to screen "${screenId}".`);
|
|
220
|
+
if (!done.ok) return errorResult(done.error);
|
|
166
221
|
return textResult(`Navigated to ${screenId}`, { screen: screenId });
|
|
167
222
|
},
|
|
168
223
|
true,
|
|
@@ -178,5 +233,5 @@ function registerScreensBridge(host, options) {
|
|
|
178
233
|
}
|
|
179
234
|
|
|
180
235
|
export { registerScreensBridge };
|
|
181
|
-
//# sourceMappingURL=chunk-
|
|
182
|
-
//# sourceMappingURL=chunk-
|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AAA,EAAQ,EAAE,MAAM,QAAA,EAAU,WAAA,EAAa,0BAAyB,EAAE;AAAA,IACpE,CAAC,QAAQ,CAAA;AAAA,IACT,OAAO,IAAA,KAAS;AACd,MAAA,MAAM,QAAA,GAAW,MAAA,CAAO,IAAA,CAAK,MAAA,IAAU,EAAE,CAAA;AACzC,MAAA,MAAM,OAAA,GAAU,QAAQ,WAAA,EAAY;AACpC,MAAA,IAAI,CAAC,QAAQ,IAAA,CAAK,CAAC,MAAM,CAAA,CAAE,EAAA,KAAO,QAAQ,CAAA,EAAG;AAC3C,QAAA,OAAO,WAAA,CAAY,CAAA,8BAAA,EAAiC,QAAQ,CAAA,2BAAA,CAA6B,CAAA;AAAA,MAC3F;AACA,MAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,MAAM,OAAA,CAAQ,UAAU,QAAQ,CAAA,EAAG,CAAA,mCAAA,EAAsC,QAAQ,CAAA,EAAA,CAAI,CAAA;AAC/G,MAAA,IAAI,CAAC,IAAA,CAAK,EAAA,EAAI,OAAO,WAAA,CAAY,KAAK,KAAK,CAAA;AAC3C,MAAA,OAAO,WAAW,CAAA,aAAA,EAAgB,QAAQ,IAAI,EAAE,MAAA,EAAQ,UAAU,CAAA;AAAA,IACpE,CAAA;AAAA,IACA,IAAA;AAAA,IACA,CAAC,IAAA,KAAS,MAAA,CAAO,OAAO,IAAA,CAAK,MAAA,IAAU,EAAE,CAAC;AAAA,GAC5C;AAEA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,SAAA;AAAA,IACJ,KAAA,EAAO,SAAA;AAAA,IACP,SAAS,MAAM;AAAE,MAAA,KAAA,MAAW,CAAA,IAAK,WAAW,CAAA,EAAE;AAAA,IAAG;AAAA,GACnD;AACF","file":"chunk-HOZCDDRA.js","sourcesContent":["import { textResult, errorResult } from \"../mcp/server\";\nimport type { ToolHost } from \"../mcp/tool-host\";\nimport type { JsonObject } from \"../mcp/types\";\nimport type { Bridge } from \"./types\";\nimport { wrapToolWithActivity } from \"../presence/wrap-tool-with-activity\";\nimport { ensureUndoToolsRegistered } from \"../undo/undo-tools\";\nimport { emitActivity } from \"../presence/registry\";\nimport type { AgentTarget } from \"../presence/types\";\n\n/**\n * Loose snapshot of a screen — what's in fancy-screens' ScreenMeta plus\n * the host's optional activity status. Kept here so this bridge has no\n * hard dep on fancy-screens.\n */\nexport type ScreenSnapshot = {\n id: string;\n title?: string;\n /** Whether this screen is the one the human / agent is looking at. */\n active: boolean;\n /** Optional category / kind (e.g. \"form\", \"whiteboard\"). */\n kind?: string;\n};\n\n/**\n * Spec for a dynamically-created screen. The host's `createScreen`\n * implementation looks up `kind` in its template registry and instantiates\n * the matching surface (form / whiteboard / sheet / chart / markdown / etc.).\n */\nexport type ScreenCreateSpec = {\n id: string;\n title?: string;\n /** Template kind. Hosts decide the catalog. */\n kind: string;\n /** Template-specific config. Form: { fields }. Sheet: { headers }. etc. */\n config?: Record<string, unknown>;\n};\n\n/**\n * What a mutating adapter method may resolve to, to acknowledge (or refuse)\n * a commit. `{ ok: false }` is a refusal the agent can act on: `error` is\n * shown to the agent verbatim, so keep it a human-readable sentence, never a\n * stack trace or an internal path. `code` is a machine-readable hint\n * (e.g. `\"conflict\"`) for the host's own use; it is not shown to the agent.\n */\nexport type ScreensAdapterResult = { ok: true } | { ok: false; error: string; code?: string };\n\n/**\n * Return type of every mutating adapter method. A sync `void` return keeps\n * the original behaviour. A Promise makes the bridge WAIT: the tool reports\n * success, and emits its AgentActivity event, only after the promise\n * resolves. A rejection or an `{ ok: false }` result becomes an error result\n * and emits no activity.\n */\nexport type ScreensAdapterCommit = void | Promise<void | ScreensAdapterResult>;\n\n/**\n * Adapter exposes the host's screen-navigation surface to the bridge.\n * Hosts wire this up against react-router, a custom tab state, or the\n * fancy-screens registry — wherever \"current screen\" lives.\n *\n * The optional create / destroy / update hooks let agents author screens\n * dynamically against a host-defined template catalog.\n *\n * Every mutating method may be sync (`void`) or async (`Promise`); see\n * {@link ScreensAdapterCommit}. Return a Promise when the host's commit is\n * authoritative — persisted, or able to refuse or conflict — so the agent is\n * told the truth instead of \"success\" before anything was committed.\n *\n * This bridge pushes NO undo entries: `agent_undo` cannot revert a screens\n * tool. A host that needs undo for navigation or screen authoring must keep\n * its own history.\n */\nexport type ScreensBridgeAdapter = {\n /** List every available screen. */\n listScreens: () => ScreenSnapshot[];\n /** Read which screen is currently active. */\n getActive: () => string | null;\n /** Navigate to a screen by id. Host updates router / tab state. */\n setActive: (screenId: string) => ScreensAdapterCommit;\n /** Optional: instantiate a new screen from a template + config. */\n createScreen?: (spec: ScreenCreateSpec) => ScreensAdapterCommit;\n /** Optional: remove a previously-created screen. */\n destroyScreen?: (screenId: string) => ScreensAdapterCommit;\n /** Optional: shallow-merge new config into an existing screen. */\n updateScreenContent?: (screenId: string, partial: Record<string, unknown>) => ScreensAdapterCommit;\n /** Optional: enumerate the kinds the host knows how to instantiate. */\n listKinds?: () => Array<{ kind: string; label?: string; description?: string; configSchema?: unknown }>;\n};\n\nexport type ScreensBridgeOptions = {\n adapter: ScreensBridgeAdapter;\n agent?: { id: string; name?: string; color?: string };\n};\n\nconst DEFAULT_AGENT = { id: \"agent\", name: \"Agent\", color: \"#a855f7\" };\n\n/**\n * The agent-facing text for a host failure. Only the message is used — never\n * `stack`, which carries file paths — matching the other bridges. A message\n * that itself embeds stack frames is cut at the first frame. A non-Error\n * rejection (a plain object, a response) has no reliable message, so it gets\n * the fallback rather than \"[object Object]\".\n */\nfunction hostErrorMessage(e: unknown, fallback: string): string {\n let msg: string | undefined;\n if (e instanceof Error) msg = e.message;\n else if (typeof e === \"string\") msg = e;\n else if (e && typeof e === \"object\" && typeof (e as { message?: unknown }).message === \"string\") {\n msg = (e as { message: string }).message;\n }\n const firstFrame = msg ? msg.search(/\\n\\s+at\\s/) : -1;\n if (msg && firstFrame >= 0) msg = msg.slice(0, firstFrame);\n msg = msg?.trim();\n return msg ? msg : fallback;\n}\n\ntype CommitOutcome = { ok: true } | { ok: false; error: string };\n\n/** Run one adapter commit, await it, and normalise every way it can fail. */\nasync function commit(run: () => ScreensAdapterCommit, fallback: string): Promise<CommitOutcome> {\n try {\n const r = await run();\n if (r && typeof r === \"object\" && r.ok === false) {\n return { ok: false, error: hostErrorMessage(r.error, fallback) };\n }\n return { ok: true };\n } catch (e) {\n return { ok: false, error: hostErrorMessage(e, fallback) };\n }\n}\n\n/**\n * registerScreensBridge — top-level navigation bridge so agents can\n * switch between screens (`screens_navigate`) and discover what surfaces\n * exist (`screens_list`, `screens_describe_active`).\n *\n * Pair with the per-surface bridges (whiteboard, form, sheet, etc.) so\n * the agent has both navigation and per-screen control.\n */\nexport function registerScreensBridge(\n host: ToolHost,\n options: ScreensBridgeOptions,\n): Bridge {\n const { adapter } = options;\n const agent = { ...DEFAULT_AGENT, ...(options.agent ?? {}) };\n const disposers: Array<() => void> = [];\n\n // agent_undo / agent_redo / agent_history are registered whenever any bridge\n // mounts, so undo availability doesn't hinge on which bridges are co-present.\n ensureUndoToolsRegistered(host, { defaultAgentId: agent.id });\n\n const target = (screenId: string): AgentTarget => ({\n kind: \"screens\",\n screenId,\n label: `Screen ${screenId}`,\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 targetFromArgs?: (args: JsonObject) => AgentTarget,\n ) => {\n const wrapped = async (args: JsonObject) => {\n try { return await handler(args); }\n catch (e) { return errorResult(hostErrorMessage(e, `${name} failed.`)); }\n };\n const final = isMutation\n ? wrapToolWithActivity(wrapped, {\n toolName: name, agent, kind: \"screens\",\n resolveTarget: ({ args }) => targetFromArgs?.(args) ?? null,\n })\n : wrapped;\n disposers.push(\n host.registerTool(\n { name, description, inputSchema: { type: \"object\", properties: properties as any, required, additionalProperties: false } },\n final as any,\n ),\n );\n };\n\n reg(\n \"screens_list\",\n \"List every screen the host has registered. Returns id, title, active flag, and optional kind.\",\n {},\n [],\n () => {\n const screens = adapter.listScreens();\n const text = screens\n .map((s) => `${s.active ? \"▸\" : \" \"} ${s.id}${s.title ? ` — ${s.title}` : \"\"}${s.kind ? ` [${s.kind}]` : \"\"}`)\n .join(\"\\n\");\n return textResult(text || \"(no screens)\", { screens, active: adapter.getActive() });\n },\n false,\n );\n\n reg(\n \"screens_describe_active\",\n \"Get the currently-active screen id (or null).\",\n {},\n [],\n () => {\n const active = adapter.getActive();\n return textResult(active ?? \"(none)\", { active });\n },\n false,\n );\n\n reg(\n \"screens_list_kinds\",\n \"List the screen kinds (templates) the host knows how to instantiate. Use this before screens_create to know what's available.\",\n {},\n [],\n () => {\n if (!adapter.listKinds) return errorResult(\"Host did not register a kind catalog. Cannot create screens dynamically.\");\n const kinds = adapter.listKinds();\n const text = kinds.map((k) => `${k.kind}${k.label ? ` — ${k.label}` : \"\"}${k.description ? ` (${k.description})` : \"\"}`).join(\"\\n\");\n return textResult(text || \"(no kinds registered)\", kinds);\n },\n false,\n );\n\n reg(\n \"screens_create\",\n \"Instantiate a new screen from a template kind + config. Switches the active view to the new screen.\",\n {\n id: { type: \"string\", description: \"Stable screen id. Must be unique.\" },\n title: { type: \"string\" },\n kind: { type: \"string\", description: \"Template kind — call screens_list_kinds for the catalog.\" },\n config: { type: \"object\", description: \"Template-specific config (e.g. { fields: [...] } for a form).\" },\n },\n [\"id\", \"kind\"],\n async (args) => {\n const createScreen = adapter.createScreen;\n if (!createScreen) return errorResult(\"Host did not provide createScreen.\");\n const id = String(args.id);\n const kind = String(args.kind);\n if (adapter.listScreens().find((s) => s.id === id)) {\n return errorResult(`Screen ${id} already exists. Use screens_destroy first or pick a fresh id.`);\n }\n const created = await commit(() => createScreen({\n id,\n title: typeof args.title === \"string\" ? args.title : undefined,\n kind,\n config: (args.config && typeof args.config === \"object\") ? args.config as Record<string, unknown> : undefined,\n }), `Host failed to create screen \"${id}\".`);\n // Nothing was created, so there is nothing to activate.\n if (!created.ok) return errorResult(created.error);\n\n const activated = await commit(() => adapter.setActive(id), `Host failed to activate screen \"${id}\".`);\n if (!activated.ok) {\n // Partial commit: the screen EXISTS but is not showing. Reported as an\n // error so an agent branching on isError does not go on to tell the\n // human \"look at the new screen\". The create DID commit, though, and\n // every committed mutation must be observable, so its activity is\n // emitted here by hand (wrapToolWithActivity skips error results).\n const state = { id, kind, created: true, activated: false };\n emitActivity({\n agentId: agent.id,\n agentName: agent.name,\n agentColor: agent.color,\n target: target(id),\n action: \"screens_create\",\n timestamp: Date.now(),\n meta: state,\n });\n return {\n ...errorResult(\n `Screen \"${id}\" was created but not activated: ${activated.error} ` +\n \"The screen exists; do not call screens_create again. \" +\n \"Call screens_navigate to show it, or screens_destroy to remove it.\",\n ),\n structuredContent: state,\n };\n }\n return textResult(`Created ${kind} screen \"${id}\"`, { id, kind });\n },\n true,\n (args) => target(String(args.id ?? \"\")),\n );\n\n reg(\n \"screens_destroy\",\n \"Remove a previously-created screen. Active screen falls back to the first remaining one (or null).\",\n { id: { type: \"string\" } },\n [\"id\"],\n async (args) => {\n const destroyScreen = adapter.destroyScreen;\n if (!destroyScreen) return errorResult(\"Host did not provide destroyScreen.\");\n const id = String(args.id);\n if (!adapter.listScreens().find((s) => s.id === id)) {\n return errorResult(`No screen with id ${id}`);\n }\n const done = await commit(() => destroyScreen(id), `Host failed to destroy screen \"${id}\".`);\n if (!done.ok) return errorResult(done.error);\n return textResult(`Destroyed screen ${id}`, { id });\n },\n true,\n (args) => target(String(args.id ?? \"\")),\n );\n\n reg(\n \"screens_set_layout\",\n \"Change the layout of an existing composite screen. Layouts: 'single', 'split-h' (left/right), 'split-v' (top/bottom), 'grid-2x2', 'stack' (tabs).\",\n {\n id: { type: \"string\" },\n layout: { type: \"string\", enum: [\"single\", \"split-h\", \"split-v\", \"grid-2x2\", \"stack\"] },\n },\n [\"id\", \"layout\"],\n async (args) => {\n const updateScreenContent = adapter.updateScreenContent;\n if (!updateScreenContent) return errorResult(\"Host did not provide updateScreenContent.\");\n const id = String(args.id);\n const done = await commit(\n () => updateScreenContent(id, { layout: String(args.layout) }),\n `Host failed to change the layout of screen \"${id}\".`,\n );\n if (!done.ok) return errorResult(done.error);\n return textResult(`Layout of ${args.id} → ${args.layout}`, { id: args.id, layout: args.layout });\n },\n true,\n (args) => target(String(args.id ?? \"\")),\n );\n\n reg(\n \"screens_update_content\",\n \"Merge new config into an existing screen (e.g. add a field to a form, append a sheet column, change chart series).\",\n {\n id: { type: \"string\" },\n partial: { type: \"object\", description: \"Shallow-merged into the screen's config.\" },\n },\n [\"id\", \"partial\"],\n async (args) => {\n const updateScreenContent = adapter.updateScreenContent;\n if (!updateScreenContent) return errorResult(\"Host did not provide updateScreenContent.\");\n const id = String(args.id);\n const partial = (args.partial && typeof args.partial === \"object\") ? args.partial as Record<string, unknown> : {};\n const done = await commit(() => updateScreenContent(id, partial), `Host failed to update screen \"${id}\".`);\n if (!done.ok) return errorResult(done.error);\n return textResult(`Updated content of ${id}`, { id });\n },\n true,\n (args) => target(String(args.id ?? \"\")),\n );\n\n reg(\n \"screens_navigate\",\n \"Switch the human's view to a different screen. The host updates its router / tab state and re-renders.\",\n { screen: { type: \"string\", description: \"Screen id to activate.\" } },\n [\"screen\"],\n async (args) => {\n const screenId = String(args.screen ?? \"\");\n const screens = adapter.listScreens();\n if (!screens.find((s) => s.id === screenId)) {\n return errorResult(`No screen registered with id \"${screenId}\". Call screens_list first.`);\n }\n const done = await commit(() => adapter.setActive(screenId), `Host failed to navigate to screen \"${screenId}\".`);\n if (!done.ok) return errorResult(done.error);\n return textResult(`Navigated to ${screenId}`, { screen: screenId });\n },\n true,\n (args) => target(String(args.screen ?? \"\")),\n );\n\n return {\n id: \"screens\",\n title: \"Screens\",\n dispose: () => { for (const d of disposers) d(); },\n };\n}\n"]}
|
|
@@ -134,8 +134,12 @@ function registerCatalogBridge(host, options) {
|
|
|
134
134
|
bridgeId: catalogId,
|
|
135
135
|
action: "catalog_create_product",
|
|
136
136
|
label: `Created product ${product.id} (${product.name})`,
|
|
137
|
-
undo: () =>
|
|
138
|
-
|
|
137
|
+
undo: async () => {
|
|
138
|
+
await adapter.products.remove(product.id);
|
|
139
|
+
},
|
|
140
|
+
redo: async () => {
|
|
141
|
+
await adapter.createProduct({ ...product });
|
|
142
|
+
}
|
|
139
143
|
});
|
|
140
144
|
return textResult(`Created product ${product.id} (${product.name})`, product);
|
|
141
145
|
},
|
|
@@ -176,8 +180,12 @@ function registerCatalogBridge(host, options) {
|
|
|
176
180
|
bridgeId: catalogId,
|
|
177
181
|
action: "catalog_create_price",
|
|
178
182
|
label: `Created price ${price.id} on ${productId}`,
|
|
179
|
-
undo: () =>
|
|
180
|
-
|
|
183
|
+
undo: async () => {
|
|
184
|
+
await adapter.prices.remove(price.id);
|
|
185
|
+
},
|
|
186
|
+
redo: async () => {
|
|
187
|
+
await adapter.createPrice({ ...price });
|
|
188
|
+
}
|
|
181
189
|
});
|
|
182
190
|
return textResult(`Created ${type} price ${price.id} on ${productId}`, price);
|
|
183
191
|
},
|
|
@@ -201,8 +209,12 @@ function registerCatalogBridge(host, options) {
|
|
|
201
209
|
bridgeId: catalogId,
|
|
202
210
|
action: "catalog_delete_product",
|
|
203
211
|
label: `Deleted product ${id} (${product.name})`,
|
|
204
|
-
undo: () =>
|
|
205
|
-
|
|
212
|
+
undo: async () => {
|
|
213
|
+
await adapter.createProduct({ ...snapshot });
|
|
214
|
+
},
|
|
215
|
+
redo: async () => {
|
|
216
|
+
await adapter.products.remove(id);
|
|
217
|
+
}
|
|
206
218
|
});
|
|
207
219
|
return textResult(`Deleted product ${id}`, { id });
|
|
208
220
|
},
|
|
@@ -226,8 +238,12 @@ function registerCatalogBridge(host, options) {
|
|
|
226
238
|
bridgeId: catalogId,
|
|
227
239
|
action: "catalog_delete_price",
|
|
228
240
|
label: `Deleted price ${id}`,
|
|
229
|
-
undo: () =>
|
|
230
|
-
|
|
241
|
+
undo: async () => {
|
|
242
|
+
await adapter.createPrice({ ...snapshot });
|
|
243
|
+
},
|
|
244
|
+
redo: async () => {
|
|
245
|
+
await adapter.prices.remove(id);
|
|
246
|
+
}
|
|
231
247
|
});
|
|
232
248
|
return textResult(`Deleted price ${id}`, { id });
|
|
233
249
|
},
|
|
@@ -304,5 +320,5 @@ function registerCatalogBridge(host, options) {
|
|
|
304
320
|
}
|
|
305
321
|
|
|
306
322
|
export { registerCatalogBridge };
|
|
307
|
-
//# sourceMappingURL=chunk-
|
|
308
|
-
//# sourceMappingURL=chunk-
|
|
323
|
+
//# sourceMappingURL=chunk-NH6HUVXQ.js.map
|
|
324
|
+
//# sourceMappingURL=chunk-NH6HUVXQ.js.map
|