@skaile/forge-app-actions 0.0.0-stage → 0.2.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.
Files changed (73) hide show
  1. package/README.md +61 -2
  2. package/dist/module.d.mts +23 -0
  3. package/dist/module.json +9 -0
  4. package/dist/module.mjs +37 -0
  5. package/dist/runtime/chat/index.d.ts +52 -0
  6. package/dist/runtime/chat/index.js +100 -0
  7. package/dist/runtime/chat/server.d.ts +36 -0
  8. package/dist/runtime/chat/server.js +27 -0
  9. package/dist/runtime/chat/types.d.ts +10 -0
  10. package/dist/runtime/chat/types.js +0 -0
  11. package/dist/runtime/client-capabilities.d.ts +29 -0
  12. package/dist/runtime/client-capabilities.js +25 -0
  13. package/dist/runtime/components-nuxt-ui/ForgeCapabilityApproval.d.vue.ts +2 -0
  14. package/dist/runtime/components-nuxt-ui/ForgeCapabilityApproval.vue +125 -0
  15. package/dist/runtime/components-nuxt-ui/ForgeCapabilityApproval.vue.d.ts +2 -0
  16. package/dist/runtime/components-nuxt-ui/ForgeCommandPalette.d.vue.ts +2 -0
  17. package/dist/runtime/components-nuxt-ui/ForgeCommandPalette.vue +218 -0
  18. package/dist/runtime/components-nuxt-ui/ForgeCommandPalette.vue.d.ts +2 -0
  19. package/dist/runtime/composables/defineClientCapability.d.ts +64 -0
  20. package/dist/runtime/composables/defineClientCapability.js +40 -0
  21. package/dist/runtime/composables/defineForgeAction.d.ts +82 -0
  22. package/dist/runtime/composables/defineForgeAction.js +147 -0
  23. package/dist/runtime/composables/useAgentCapabilities.d.ts +78 -0
  24. package/dist/runtime/composables/useAgentCapabilities.js +94 -0
  25. package/dist/runtime/composables/useCapabilityApproval.d.ts +109 -0
  26. package/dist/runtime/composables/useCapabilityApproval.js +74 -0
  27. package/dist/runtime/composables/useCapabilityInvocations.d.ts +150 -0
  28. package/dist/runtime/composables/useCapabilityInvocations.js +118 -0
  29. package/dist/runtime/composables/useCommandPalette.d.ts +28 -0
  30. package/dist/runtime/composables/useCommandPalette.js +49 -0
  31. package/dist/runtime/composables/usePaletteArgStep.d.ts +47 -0
  32. package/dist/runtime/composables/usePaletteArgStep.js +51 -0
  33. package/dist/runtime/internal/describe-error.d.ts +10 -0
  34. package/dist/runtime/internal/describe-error.js +12 -0
  35. package/dist/runtime/server/index.d.ts +7 -0
  36. package/dist/runtime/server/index.js +2 -0
  37. package/dist/runtime/server/utils/capability-registry.d.ts +35 -0
  38. package/dist/runtime/server/utils/capability-registry.js +24 -0
  39. package/dist/runtime/server/utils/client-capability-bridge.d.ts +647 -0
  40. package/dist/runtime/server/utils/client-capability-bridge.js +755 -0
  41. package/dist/runtime/shims-vue.d.ts +8 -0
  42. package/dist/runtime/types/client-capability.d.ts +159 -0
  43. package/dist/runtime/types/client-capability.js +0 -0
  44. package/dist/runtime/types/command-palette.d.ts +75 -0
  45. package/dist/runtime/types/command-palette.js +0 -0
  46. package/dist/runtime/types/forge-action.d.ts +152 -0
  47. package/dist/runtime/types/forge-action.js +0 -0
  48. package/dist/runtime/types/index.d.ts +3 -0
  49. package/dist/runtime/types/index.js +0 -0
  50. package/dist/types.d.mts +9 -0
  51. package/package.json +94 -4
  52. package/src/runtime/chat/index.ts +190 -0
  53. package/src/runtime/chat/server.ts +64 -0
  54. package/src/runtime/chat/types.ts +13 -0
  55. package/src/runtime/client-capabilities.ts +82 -0
  56. package/src/runtime/components-nuxt-ui/ForgeCapabilityApproval.vue +240 -0
  57. package/src/runtime/components-nuxt-ui/ForgeCommandPalette.vue +363 -0
  58. package/src/runtime/composables/defineClientCapability.ts +119 -0
  59. package/src/runtime/composables/defineForgeAction.ts +278 -0
  60. package/src/runtime/composables/useAgentCapabilities.ts +215 -0
  61. package/src/runtime/composables/useCapabilityApproval.ts +219 -0
  62. package/src/runtime/composables/useCapabilityInvocations.ts +325 -0
  63. package/src/runtime/composables/useCommandPalette.ts +97 -0
  64. package/src/runtime/composables/usePaletteArgStep.ts +110 -0
  65. package/src/runtime/internal/describe-error.ts +21 -0
  66. package/src/runtime/server/index.ts +8 -0
  67. package/src/runtime/server/utils/capability-registry.ts +66 -0
  68. package/src/runtime/server/utils/client-capability-bridge.ts +1201 -0
  69. package/src/runtime/shims-vue.d.ts +8 -0
  70. package/src/runtime/types/client-capability.ts +178 -0
  71. package/src/runtime/types/command-palette.ts +78 -0
  72. package/src/runtime/types/forge-action.ts +166 -0
  73. package/src/runtime/types/index.ts +24 -0
@@ -0,0 +1,94 @@
1
+ import { shallowRef } from "vue";
2
+ const _capabilities = shallowRef([]);
3
+ const _subscriberId = mintSubscriberId();
4
+ function mintSubscriberId() {
5
+ const c = globalThis.crypto;
6
+ if (typeof c?.randomUUID === "function") return c.randomUUID();
7
+ return `sub-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
8
+ }
9
+ function toDescriptor(capability) {
10
+ const {
11
+ inputZod: _inputZod,
12
+ outputZod: _outputZod,
13
+ handler: _handler,
14
+ ...descriptor
15
+ } = capability;
16
+ return descriptor;
17
+ }
18
+ async function post(options, payload) {
19
+ const sent = payload.capabilities.length;
20
+ const fetcher = options.fetcher ?? globalThis.fetch ?? void 0;
21
+ if (!fetcher) {
22
+ return { ok: false, sent, error: "no fetch implementation available" };
23
+ }
24
+ try {
25
+ const res = await fetcher(options.endpoint, {
26
+ method: "POST",
27
+ headers: { "content-type": "application/json" },
28
+ body: JSON.stringify({ ...options.body, ...payload })
29
+ });
30
+ if (!res.ok) {
31
+ const error = `announce failed: HTTP ${res.status}`;
32
+ console.warn(`[useAgentCapabilities] ${error}`);
33
+ return { ok: false, sent, error };
34
+ }
35
+ return { ok: true, sent };
36
+ } catch (err) {
37
+ const error = err instanceof Error ? err.message : String(err);
38
+ console.warn(`[useAgentCapabilities] announce failed: ${error}`);
39
+ return { ok: false, sent, error };
40
+ }
41
+ }
42
+ export function useAgentCapabilities() {
43
+ function register(capability) {
44
+ const idx = _capabilities.value.findIndex((c) => c.name === capability.name);
45
+ if (idx !== -1) {
46
+ _capabilities.value = [
47
+ ..._capabilities.value.slice(0, idx),
48
+ capability,
49
+ ..._capabilities.value.slice(idx + 1)
50
+ ];
51
+ } else {
52
+ _capabilities.value = [..._capabilities.value, capability];
53
+ }
54
+ }
55
+ function registerAll(capabilities) {
56
+ for (const capability of capabilities) register(capability);
57
+ }
58
+ function unregister(name) {
59
+ const idx = _capabilities.value.findIndex((c) => c.name === name);
60
+ if (idx === -1) return;
61
+ _capabilities.value = _capabilities.value.filter((c) => c.name !== name);
62
+ }
63
+ function get(name) {
64
+ return _capabilities.value.find((c) => c.name === name);
65
+ }
66
+ function list() {
67
+ return [..._capabilities.value];
68
+ }
69
+ function toWire() {
70
+ return _capabilities.value.map(toDescriptor);
71
+ }
72
+ function announce(options) {
73
+ return post(options, { subscriberId: _subscriberId, capabilities: toWire() });
74
+ }
75
+ function withdraw(options) {
76
+ return post(options, { subscriberId: _subscriberId, capabilities: [] });
77
+ }
78
+ function reset() {
79
+ _capabilities.value = [];
80
+ }
81
+ return {
82
+ register,
83
+ registerAll,
84
+ unregister,
85
+ get,
86
+ list,
87
+ toWire,
88
+ capabilities: _capabilities,
89
+ subscriberId: _subscriberId,
90
+ announce,
91
+ withdraw,
92
+ reset
93
+ };
94
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The browser-side **approval gate** for agent-invoked capabilities
3
+ * (spec §3 L7).
4
+ *
5
+ * On the platform, `requiresApproval` is a gateway feature: the gateway parks
6
+ * the invocation, renders a confirm card, and only then forwards the call to
7
+ * the app. Forge has no such gate — but it does not need one, because the forge
8
+ * handler already runs in the browser. So the gate is simply: the inbound
9
+ * dispatcher awaits a confirm dialog before it dispatches. Far simpler
10
+ * machinery, identical observable contract (`{ error: "declined" }` back to the
11
+ * agent, handler untouched).
12
+ *
13
+ * This module is the queue behind that dialog. It holds no UI of its own —
14
+ * `<ForgeCapabilityApproval />` (one variant per UI kit) renders
15
+ * {@link UseCapabilityApprovalReturn.current} and calls `approve` / `decline`.
16
+ * A consumer that wants its own dialog can ignore the component and read the
17
+ * same queue.
18
+ *
19
+ * **Every request settles exactly once, and settling removes it from the
20
+ * queue.** That is the difference between a cancellable dialog and one that
21
+ * merely loses a race: when the per-call deadline elapses, the entry
22
+ * disappears — the dialog closes, the promise resolves `"timeout"`, and the
23
+ * dispatcher answers the parked call. Nothing is left open for a user to
24
+ * confirm after the agent has already been told the call expired.
25
+ */
26
+ import { type ComputedRef, type ShallowRef } from "vue";
27
+ /**
28
+ * How an approval request ended.
29
+ *
30
+ * `timeout` and `cancelled` are both "no answer", kept apart because they have
31
+ * different causes: `timeout` is this browser's own per-call deadline elapsing,
32
+ * `cancelled` is the caller pulling the request (an `AbortSignal`, or
33
+ * {@link UseCapabilityApprovalReturn.reset} on teardown).
34
+ */
35
+ export type CapabilityApprovalDecision = "approved" | "declined" | "timeout" | "cancelled";
36
+ /** Default per-call deadline for an unanswered dialog. */
37
+ export declare const DEFAULT_APPROVAL_TIMEOUT_MS = 30000;
38
+ /** What the caller asks the user to confirm. */
39
+ export interface CapabilityApprovalOptions {
40
+ /** Correlation token of the originating `capability_invoked` event. */
41
+ callId: string;
42
+ /** Capability name as invoked — possibly a deprecated alias. */
43
+ name: string;
44
+ /** Human-readable label, when the capability declared one. */
45
+ displayName?: string;
46
+ /** The capability's own description, shown as the "what this does" line. */
47
+ description?: string;
48
+ /**
49
+ * The **validated** arguments the handler would receive. Validation runs
50
+ * before the gate, so the user is never asked to approve a call that would
51
+ * have been rejected anyway, and what the dialog shows is what will run.
52
+ */
53
+ input?: unknown;
54
+ /**
55
+ * Deadline in ms. `undefined` falls back to
56
+ * {@link DEFAULT_APPROVAL_TIMEOUT_MS}; `0` or a negative value means no
57
+ * browser-side deadline (the agent runner's own backstop still applies).
58
+ */
59
+ timeoutMs?: number;
60
+ /** Cancels the request from outside — settles it `"cancelled"`. */
61
+ signal?: AbortSignal;
62
+ }
63
+ /** One entry in the approval queue, as the dialog renders it. */
64
+ export interface CapabilityApprovalRequest {
65
+ /** Queue-unique id. Distinct from `callId`: the queue owns this one. */
66
+ id: string;
67
+ callId: string;
68
+ name: string;
69
+ displayName?: string;
70
+ description?: string;
71
+ input?: unknown;
72
+ /** `Date.now()` when the request was enqueued. */
73
+ requestedAt: number;
74
+ /** Effective deadline in ms, or `undefined` when there is none. */
75
+ timeoutMs?: number;
76
+ /** `requestedAt + timeoutMs`, for a countdown. `undefined` when no deadline. */
77
+ expiresAt?: number;
78
+ }
79
+ export interface UseCapabilityApprovalReturn {
80
+ /**
81
+ * The pending queue, oldest first.
82
+ *
83
+ * `shallowRef` for the same reason `useAgentCapabilities` uses one: entries
84
+ * carry arbitrary handler input, and Vue's deep proxy has no business
85
+ * rewriting values that are about to be handed to application code.
86
+ */
87
+ pending: Readonly<ShallowRef<CapabilityApprovalRequest[]>>;
88
+ /** The request the dialog should show — the oldest pending one, or `null`. */
89
+ current: ComputedRef<CapabilityApprovalRequest | null>;
90
+ /**
91
+ * Ask for confirmation. Resolves — never rejects — when the user answers,
92
+ * the deadline elapses, or the request is cancelled.
93
+ */
94
+ request(options: CapabilityApprovalOptions): Promise<CapabilityApprovalDecision>;
95
+ /** Answer a request `"approved"`. Returns false if it already settled. */
96
+ approve(id: string): boolean;
97
+ /** Answer a request `"declined"`. Returns false if it already settled. */
98
+ decline(id: string): boolean;
99
+ /** Withdraw a request `"cancelled"`. Returns false if it already settled. */
100
+ cancel(id: string): boolean;
101
+ /** Cancel everything pending — session teardown, tests. */
102
+ reset(): void;
103
+ }
104
+ /**
105
+ * The approval queue behind `requiresApproval`.
106
+ *
107
+ * Stateless accessor over a module-level singleton — call it from anywhere.
108
+ */
109
+ export declare function useCapabilityApproval(): UseCapabilityApprovalReturn;
@@ -0,0 +1,74 @@
1
+ import { computed, shallowRef } from "vue";
2
+ export const DEFAULT_APPROVAL_TIMEOUT_MS = 3e4;
3
+ const _pending = shallowRef([]);
4
+ const _settlers = /* @__PURE__ */ new Map();
5
+ let _seq = 0;
6
+ function nextId() {
7
+ _seq += 1;
8
+ return `approval-${_seq}`;
9
+ }
10
+ const _current = computed(() => _pending.value[0] ?? null);
11
+ function settle(id, decision) {
12
+ return _settlers.get(id)?.(decision) ?? false;
13
+ }
14
+ function request(options) {
15
+ return new Promise((resolve) => {
16
+ if (options.signal?.aborted) {
17
+ resolve("cancelled");
18
+ return;
19
+ }
20
+ const id = nextId();
21
+ const requestedAt = Date.now();
22
+ const configured = options.timeoutMs ?? DEFAULT_APPROVAL_TIMEOUT_MS;
23
+ const timeoutMs = configured > 0 ? configured : void 0;
24
+ let timer;
25
+ let settled = false;
26
+ const finish = (decision) => {
27
+ if (settled) return false;
28
+ settled = true;
29
+ if (timer !== void 0) clearTimeout(timer);
30
+ options.signal?.removeEventListener("abort", onAbort);
31
+ _settlers.delete(id);
32
+ _pending.value = _pending.value.filter((entry) => entry.id !== id);
33
+ resolve(decision);
34
+ return true;
35
+ };
36
+ function onAbort() {
37
+ finish("cancelled");
38
+ }
39
+ _settlers.set(id, finish);
40
+ if (timeoutMs !== void 0) {
41
+ timer = setTimeout(() => finish("timeout"), timeoutMs);
42
+ timer.unref?.();
43
+ }
44
+ options.signal?.addEventListener("abort", onAbort, { once: true });
45
+ _pending.value = [
46
+ ..._pending.value,
47
+ {
48
+ id,
49
+ callId: options.callId,
50
+ name: options.name,
51
+ displayName: options.displayName,
52
+ description: options.description,
53
+ input: options.input,
54
+ requestedAt,
55
+ timeoutMs,
56
+ expiresAt: timeoutMs === void 0 ? void 0 : requestedAt + timeoutMs
57
+ }
58
+ ];
59
+ });
60
+ }
61
+ export function useCapabilityApproval() {
62
+ return {
63
+ pending: _pending,
64
+ current: _current,
65
+ request,
66
+ approve: (id) => settle(id, "approved"),
67
+ decline: (id) => settle(id, "declined"),
68
+ cancel: (id) => settle(id, "cancelled"),
69
+ reset: () => {
70
+ for (const id of [..._settlers.keys()]) settle(id, "cancelled");
71
+ _pending.value = [];
72
+ }
73
+ };
74
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Browser half of the forge app channel's **invoke** leg.
3
+ *
4
+ * `useAgentCapabilities()` announces what the browser can do; this composable
5
+ * is what happens when the agent takes it up on the offer. One
6
+ * `capability_invoked` arrives over the app's existing SSE stream and this
7
+ * module:
8
+ *
9
+ * 1. looks the name up in the browser registry (deprecated aliases included,
10
+ * because an alias is registered as its own entry sharing the handler),
11
+ * 2. validates the raw input against the capability's **live zod schema** —
12
+ * `inputSchema` on the wire is only a hint to the model, the schema here is
13
+ * the enforcement, and it runs BEFORE the handler,
14
+ * 3. for a capability that declares `requiresApproval`, awaits the user's
15
+ * confirmation (spec §3 L7) — declining answers the agent and the handler
16
+ * never runs,
17
+ * 4. runs the handler, where the real `ref()`s live,
18
+ * 5. POSTs `{ callId, result }` back so Nitro can answer the parked call.
19
+ *
20
+ * A thrown handler error becomes `{ error }`, which the agent runner turns into
21
+ * a rejected tool call — the agent is told the truth, not a silent success.
22
+ *
23
+ * See `docs/superpowers/specs/2026-08-22-forge-app-channel-design.md` §2.
24
+ */
25
+ import type { ClientCapabilityLogger } from "../types/client-capability.js";
26
+ import { type CapabilityAnnounceFetcher } from "./useAgentCapabilities.js";
27
+ /**
28
+ * The agent → browser event, as it arrives on the SSE stream. Consumer apps tag
29
+ * it with their own routing fields (forge-workspace adds `_mode`); those are
30
+ * ignored here.
31
+ */
32
+ export interface CapabilityInvokedEvent {
33
+ type: "capability_invoked";
34
+ /** Correlation token to answer with. */
35
+ callId: string;
36
+ /** Capability name as invoked — possibly a deprecated alias. */
37
+ name: string;
38
+ /** Raw, unvalidated arguments from the model. */
39
+ input?: unknown;
40
+ /**
41
+ * Spec §L4 — the one subscriber this invocation is addressed to, as elected
42
+ * by `ClientCapabilityBridge.routeTo()`. Present only when the app forwards
43
+ * it; absent (or `null`) means "whoever is listening", the pre-05 behaviour.
44
+ *
45
+ * A tab whose own `useAgentCapabilities().subscriberId` does not match is the
46
+ * *incumbent*: it stays connected and simply ignores the frame.
47
+ */
48
+ ownerId?: string | null;
49
+ /**
50
+ * Apps tag their SSE frames with their own routing fields — forge-workspace
51
+ * adds `_mode`. They are passed through untouched, and kept on the type so a
52
+ * caller can still read its own tag after the guard has narrowed the frame.
53
+ */
54
+ [key: string]: unknown;
55
+ }
56
+ export interface HandleInvocationOptions {
57
+ /**
58
+ * The upward POST endpoint that answers a parked call, e.g.
59
+ * `/api/agent/capability-result`. The consuming app owns this route —
60
+ * forge-app-actions never assumes a path.
61
+ */
62
+ endpoint: string;
63
+ /**
64
+ * Extra fields merged into the JSON body, identifying the session to the
65
+ * app's own route (e.g. `{ mode: "work" }`). The session key
66
+ * itself is derived server-side; never send it from the browser.
67
+ */
68
+ body?: Record<string, unknown>;
69
+ /**
70
+ * Opaque session key for the handler's {@link ClientCapabilityContext}.
71
+ * Informational only — the browser does not get to name its own session.
72
+ */
73
+ sessionKey?: string;
74
+ /** Override the fetcher. Defaults to `globalThis.fetch`. */
75
+ fetcher?: CapabilityAnnounceFetcher;
76
+ /** Logger handed to the handler and used for this module's own warnings. */
77
+ log?: ClientCapabilityLogger;
78
+ /**
79
+ * Deadline for an unanswered approval dialog, in ms. Only consulted for a
80
+ * capability that declares `requiresApproval`, and only when the capability
81
+ * itself declares no `callTimeoutMs`. Defaults to
82
+ * {@link DEFAULT_APPROVAL_TIMEOUT_MS}; `0` disables the browser-side deadline
83
+ * and leaves the agent runner's own backstop as the only limit.
84
+ */
85
+ approvalTimeoutMs?: number;
86
+ /**
87
+ * Cancels a pending approval dialog from outside — session teardown, a mode
88
+ * switch, a route change. An aborted signal settles the dialog as
89
+ * `approval-cancelled`; it does **not** interrupt a handler that has already
90
+ * started.
91
+ */
92
+ signal?: AbortSignal;
93
+ }
94
+ /** Why an invocation failed, when it did. */
95
+ export type InvocationFailure =
96
+ /** No capability of that name is registered in this browser. */
97
+ "unknown-capability"
98
+ /** The input did not satisfy the declared zod schema. The handler never ran. */
99
+ | "invalid-input"
100
+ /**
101
+ * The capability declared `requiresApproval` and the user said no. The
102
+ * handler never ran and nothing was mutated.
103
+ */
104
+ | "declined"
105
+ /**
106
+ * An approval dialog went unanswered past the per-call deadline. The dialog
107
+ * was closed and the handler never ran.
108
+ */
109
+ | "approval-timeout"
110
+ /**
111
+ * A pending approval dialog was withdrawn — `options.signal` aborted, or
112
+ * `useCapabilityApproval().reset()` ran on teardown. The handler never ran.
113
+ */
114
+ | "approval-cancelled"
115
+ /** The handler itself threw. */
116
+ | "handler-error";
117
+ /** What {@link UseCapabilityInvocationsReturn.handle} did with one event. */
118
+ export interface InvocationOutcome {
119
+ callId: string;
120
+ name: string;
121
+ ok: boolean;
122
+ /** The handler's return value, when `ok`. */
123
+ result?: unknown;
124
+ /** The message sent back to the agent, when not `ok`. */
125
+ error?: string;
126
+ /** Present when not `ok`. */
127
+ failure?: InvocationFailure;
128
+ /** Whether the answering POST succeeded. */
129
+ posted: boolean;
130
+ }
131
+ export interface UseCapabilityInvocationsReturn {
132
+ /** Narrowing type-guard for an SSE frame. */
133
+ isInvocation(event: unknown): event is CapabilityInvokedEvent;
134
+ /**
135
+ * Handle one SSE frame. Returns `null` — and does nothing — when the frame is
136
+ * not a `capability_invoked`, so a caller can use it as the first line of its
137
+ * event switch and fall through. Also `null` when the frame names a different
138
+ * tab as its §L4 owner: this tab is the inert incumbent for that call.
139
+ *
140
+ * Never throws: every failure path ends in an `{ error }` answer to the agent.
141
+ */
142
+ handle(event: unknown, options: HandleInvocationOptions): Promise<InvocationOutcome | null>;
143
+ }
144
+ /**
145
+ * Inbound dispatcher for agent-invoked browser capabilities.
146
+ *
147
+ * Stateless — the registry it dispatches against is
148
+ * `useAgentCapabilities()`'s module-level singleton.
149
+ */
150
+ export declare function useCapabilityInvocations(): UseCapabilityInvocationsReturn;
@@ -0,0 +1,118 @@
1
+ import { describeError } from "../internal/describe-error.js";
2
+ import { useAgentCapabilities } from "./useAgentCapabilities.js";
3
+ import { DEFAULT_APPROVAL_TIMEOUT_MS, useCapabilityApproval } from "./useCapabilityApproval.js";
4
+ const defaultLog = {
5
+ info: (message, ...args) => console.log(message, ...args),
6
+ warn: (message, ...args) => console.warn(message, ...args),
7
+ error: (message, ...args) => console.error(message, ...args)
8
+ };
9
+ function isInvocationEvent(event) {
10
+ if (!event || typeof event !== "object") return false;
11
+ const e = event;
12
+ return e.type === "capability_invoked" && typeof e.callId === "string" && e.callId.length > 0 && typeof e.name === "string" && e.name.length > 0;
13
+ }
14
+ async function postResult(options, callId, result, log) {
15
+ const fetcher = options.fetcher ?? globalThis.fetch ?? void 0;
16
+ if (!fetcher) {
17
+ log.warn("[useCapabilityInvocations] no fetch implementation available");
18
+ return false;
19
+ }
20
+ try {
21
+ const res = await fetcher(options.endpoint, {
22
+ method: "POST",
23
+ headers: { "content-type": "application/json" },
24
+ body: JSON.stringify({ ...options.body, callId, result })
25
+ });
26
+ if (!res.ok) {
27
+ log.warn(`[useCapabilityInvocations] capability-result POST failed: HTTP ${res.status}`);
28
+ return false;
29
+ }
30
+ return true;
31
+ } catch (err) {
32
+ log.warn(`[useCapabilityInvocations] capability-result POST failed: ${describeError(err)}`);
33
+ return false;
34
+ }
35
+ }
36
+ export function useCapabilityInvocations() {
37
+ async function handle(event, options) {
38
+ if (!isInvocationEvent(event)) return null;
39
+ const log = options.log ?? defaultLog;
40
+ const { callId, name } = event;
41
+ const registry = useAgentCapabilities();
42
+ if (typeof event.ownerId === "string" && event.ownerId !== registry.subscriberId) {
43
+ log.info(
44
+ `[useCapabilityInvocations] ${name} (${callId}) is addressed to another tab; ignoring`
45
+ );
46
+ return null;
47
+ }
48
+ const capability = registry.get(name);
49
+ const fail = async (failure, error) => {
50
+ log.warn(`[useCapabilityInvocations] ${name} (${callId}) ${failure}: ${error}`);
51
+ const posted2 = await postResult(options, callId, { error }, log);
52
+ return { callId, name, ok: false, error, failure, posted: posted2 };
53
+ };
54
+ if (!capability) {
55
+ return fail(
56
+ "unknown-capability",
57
+ `No capability named "${name}" is registered in this browser.`
58
+ );
59
+ }
60
+ let input;
61
+ try {
62
+ input = capability.inputZod.parse(event.input ?? {});
63
+ } catch (err) {
64
+ return fail("invalid-input", `Invalid input for "${name}": ${describeError(err)}`);
65
+ }
66
+ if (capability.requiresApproval) {
67
+ const decision = await useCapabilityApproval().request({
68
+ callId,
69
+ name,
70
+ displayName: capability.displayName,
71
+ description: capability.description,
72
+ input,
73
+ // The capability's own per-call timeout governs its dialog, so the gate
74
+ // cannot outlive the call the bridge parked for it.
75
+ timeoutMs: capability.callTimeoutMs ?? options.approvalTimeoutMs ?? DEFAULT_APPROVAL_TIMEOUT_MS,
76
+ signal: options.signal
77
+ });
78
+ if (decision === "declined") {
79
+ return fail("declined", `The user declined "${name}".`);
80
+ }
81
+ if (decision === "timeout") {
82
+ return fail(
83
+ "approval-timeout",
84
+ `Approval for "${name}" was not answered in time; the action did not run.`
85
+ );
86
+ }
87
+ if (decision !== "approved") {
88
+ return fail(
89
+ "approval-cancelled",
90
+ `Approval for "${name}" was cancelled; the action did not run.`
91
+ );
92
+ }
93
+ }
94
+ const ctx = {
95
+ sessionKey: options.sessionKey ?? "",
96
+ callId,
97
+ name,
98
+ log
99
+ };
100
+ let result;
101
+ try {
102
+ result = await capability.handler(input, ctx);
103
+ } catch (err) {
104
+ return fail("handler-error", describeError(err));
105
+ }
106
+ if (capability.outputZod) {
107
+ const check = capability.outputZod.safeParse(result);
108
+ if (!check.success) {
109
+ log.warn(
110
+ `[useCapabilityInvocations] ${name} returned a value that does not match its declared output schema: ${describeError(check.error)}`
111
+ );
112
+ }
113
+ }
114
+ const posted = await postResult(options, callId, result, log);
115
+ return { callId, name, ok: true, result, posted };
116
+ }
117
+ return { isInvocation: isInvocationEvent, handle };
118
+ }
@@ -0,0 +1,28 @@
1
+ import type { DeepReadonly, Ref } from "vue";
2
+ import type { PaletteAction } from "../types/command-palette.js";
3
+ export interface UseCommandPaletteReturn {
4
+ /** Register an action. Idempotent by id — replaces existing if same id. */
5
+ registerAction(action: PaletteAction): void;
6
+ /** Remove a previously registered action. No-op if id not found. */
7
+ unregisterAction(id: string): void;
8
+ /**
9
+ * Fuzzy-filter registered actions by search string.
10
+ * Matches against label, description, and keywords.
11
+ * Returns all actions when search is empty or whitespace-only.
12
+ * Results are sorted: exact-label-start matches first, then substring.
13
+ */
14
+ queryActions(search: string): PaletteAction[];
15
+ /** Reactive list of all currently registered actions. */
16
+ actions: DeepReadonly<Ref<PaletteAction[]>>;
17
+ /** Open/close state (read-only — toggled by ForgeCommandPalette). */
18
+ isOpen: Readonly<Ref<boolean>>;
19
+ /** Programmatically open the palette. */
20
+ open(): void;
21
+ /** Programmatically close the palette. */
22
+ close(): void;
23
+ }
24
+ /**
25
+ * Global command palette registry.
26
+ * Components call registerAction() to expose actions in the Cmd+K palette.
27
+ */
28
+ export declare function useCommandPalette(): UseCommandPaletteReturn;
@@ -0,0 +1,49 @@
1
+ import { readonly, ref } from "vue";
2
+ const _actions = ref([]);
3
+ const _isOpen = ref(false);
4
+ export function useCommandPalette() {
5
+ function registerAction(action) {
6
+ const idx = _actions.value.findIndex((a) => a.id === action.id);
7
+ if (idx !== -1) {
8
+ _actions.value = [..._actions.value.slice(0, idx), action, ..._actions.value.slice(idx + 1)];
9
+ } else {
10
+ _actions.value = [..._actions.value, action];
11
+ }
12
+ }
13
+ function unregisterAction(id) {
14
+ const idx = _actions.value.findIndex((a) => a.id === id);
15
+ if (idx === -1) return;
16
+ _actions.value = _actions.value.filter((a) => a.id !== id);
17
+ }
18
+ function queryActions(search) {
19
+ const trimmed = search.trim().toLowerCase();
20
+ if (!trimmed) return [..._actions.value];
21
+ const matches = _actions.value.filter((action) => {
22
+ const haystack = [action.label, action.description ?? "", ...action.keywords ?? []].join(" ").toLowerCase();
23
+ return haystack.includes(trimmed);
24
+ });
25
+ matches.sort((a, b) => {
26
+ const aStarts = a.label.toLowerCase().startsWith(trimmed);
27
+ const bStarts = b.label.toLowerCase().startsWith(trimmed);
28
+ if (aStarts && !bStarts) return -1;
29
+ if (!aStarts && bStarts) return 1;
30
+ return 0;
31
+ });
32
+ return matches;
33
+ }
34
+ function open() {
35
+ _isOpen.value = true;
36
+ }
37
+ function close() {
38
+ _isOpen.value = false;
39
+ }
40
+ return {
41
+ registerAction,
42
+ unregisterAction,
43
+ queryActions,
44
+ actions: readonly(_actions),
45
+ isOpen: readonly(_isOpen),
46
+ open,
47
+ close
48
+ };
49
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The command palette's **argument step**.
3
+ *
4
+ * A `PaletteAction` that declares `arg` needs one string before it can run
5
+ * (`defineForgeAction`'s `arg.toInput` turns that string into the action's
6
+ * typed input). Selecting such an action does not close the palette: it swaps
7
+ * the list for the action's candidates and waits for a second Enter.
8
+ *
9
+ * This holds the per-component state for that step. It lives here rather than
10
+ * inline in the components because both UI-kit variants of
11
+ * `ForgeCommandPalette` run it and are kept in deliberate lock-step — one copy
12
+ * cannot drift from the other if there is only one copy.
13
+ *
14
+ * Not a singleton: `useCommandPalette()` owns the shared registry, this owns
15
+ * one palette instance's transient step.
16
+ */
17
+ import { type ComputedRef, type Ref, type ShallowRef } from "vue";
18
+ import type { PaletteAction, PaletteArgOption, PaletteArgPrompt } from "../types/command-palette.js";
19
+ export interface UsePaletteArgStepReturn {
20
+ /** The action awaiting its argument, or `null` when the step is not active. */
21
+ action: ShallowRef<PaletteAction | null>;
22
+ /** Candidates for the current query. Empty for a free-text argument. */
23
+ options: ShallowRef<PaletteArgOption[]>;
24
+ /** Whether a candidate lookup is in flight. */
25
+ loading: Ref<boolean>;
26
+ /** Whether the palette is currently collecting an argument. */
27
+ active: ComputedRef<boolean>;
28
+ /** The active action's prompt declaration. */
29
+ prompt: ComputedRef<PaletteArgPrompt | null>;
30
+ /**
31
+ * Enter the argument step for `action`. Returns `false` — and changes
32
+ * nothing — when the action takes no argument, so a caller can use it as
33
+ * `if (!begin(a)) { close(); run(a) }`.
34
+ */
35
+ begin(action: PaletteAction): boolean;
36
+ /** Recompute the candidates for `query`. Stale responses are discarded. */
37
+ query(query: string): Promise<void>;
38
+ /** Leave the step without running anything. */
39
+ cancel(): void;
40
+ /**
41
+ * The string the action should run with, given what is typed and which row is
42
+ * highlighted — or `null` when the step cannot complete yet (nothing typed
43
+ * and nothing highlighted, or a typed value the prompt does not accept).
44
+ */
45
+ valueFor(typed: string, index: number): string | null;
46
+ }
47
+ export declare function usePaletteArgStep(): UsePaletteArgStepReturn;