@jini-ai/agentic 0.4.1 → 0.4.3

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 (72) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/a2ui/agent-to-renderer.d.ts +613 -0
  3. package/dist/a2ui/agent-to-renderer.js +191 -0
  4. package/dist/a2ui/catalog.d.ts +73 -0
  5. package/dist/a2ui/catalog.js +304 -0
  6. package/dist/a2ui/common-types.d.ts +401 -0
  7. package/dist/a2ui/common-types.js +130 -0
  8. package/dist/a2ui/index.d.ts +16 -0
  9. package/dist/a2ui/index.js +16 -0
  10. package/dist/a2ui/interpreter.d.ts +71 -0
  11. package/dist/a2ui/interpreter.js +337 -0
  12. package/dist/a2ui/json-pointer.d.ts +48 -0
  13. package/dist/a2ui/json-pointer.js +174 -0
  14. package/dist/a2ui/renderer-to-agent.d.ts +342 -0
  15. package/dist/a2ui/renderer-to-agent.js +111 -0
  16. package/dist/a2ui/resolve.d.ts +28 -0
  17. package/dist/a2ui/resolve.js +144 -0
  18. package/dist/a2ui/tree.d.ts +66 -0
  19. package/dist/a2ui/tree.js +74 -0
  20. package/dist/ag-ui.d.ts +82 -0
  21. package/dist/ag-ui.js +85 -0
  22. package/dist/agui/encoder.d.ts +50 -0
  23. package/dist/agui/encoder.js +97 -0
  24. package/dist/agui/events.d.ts +59 -0
  25. package/dist/agui/events.js +15 -0
  26. package/dist/capability.d.ts +81 -0
  27. package/dist/capability.js +79 -0
  28. package/dist/core/a2ui/index.d.ts +4 -7
  29. package/dist/core/a2ui/index.js +4 -7
  30. package/dist/core/a2ui/interpreter.d.ts +1 -1
  31. package/dist/core/a2ui/interpreter.js +0 -1
  32. package/dist/core/a2ui/surface-properties.d.ts +34 -0
  33. package/dist/core/a2ui/surface-properties.js +49 -0
  34. package/dist/core/dom/index.d.ts +3 -8
  35. package/dist/core/dom/index.js +3 -8
  36. package/dist/core/gen-ui/index.d.ts +2 -4
  37. package/dist/core/gen-ui/index.js +2 -4
  38. package/dist/core/index.d.ts +4 -30
  39. package/dist/core/index.js +4 -30
  40. package/dist/dom/dom-page-driver.d.ts +36 -0
  41. package/dist/dom/dom-page-driver.js +601 -0
  42. package/dist/dom/index.d.ts +17 -0
  43. package/dist/dom/index.js +17 -0
  44. package/dist/dom/model-context.d.ts +69 -0
  45. package/dist/dom/model-context.js +44 -0
  46. package/dist/element-handles.d.ts +120 -0
  47. package/dist/element-handles.js +39 -0
  48. package/dist/gen-ui/encoder.d.ts +50 -0
  49. package/dist/gen-ui/encoder.js +97 -0
  50. package/dist/gen-ui/events.d.ts +59 -0
  51. package/dist/gen-ui/events.js +15 -0
  52. package/dist/gen-ui/index.d.ts +18 -0
  53. package/dist/gen-ui/index.js +17 -0
  54. package/dist/guards.d.ts +96 -0
  55. package/dist/guards.js +186 -0
  56. package/dist/handle.d.ts +41 -0
  57. package/dist/handle.js +41 -0
  58. package/dist/index.d.ts +3 -35
  59. package/dist/index.js +3 -35
  60. package/dist/mcp-ui-apps.d.ts +223 -0
  61. package/dist/mcp-ui-apps.js +252 -0
  62. package/dist/mcp-ui.d.ts +133 -0
  63. package/dist/mcp-ui.js +134 -0
  64. package/dist/page-capabilities.d.ts +14 -0
  65. package/dist/page-capabilities.js +129 -0
  66. package/dist/page-driver.d.ts +120 -0
  67. package/dist/page-driver.js +2 -0
  68. package/dist/page-executor.d.ts +94 -0
  69. package/dist/page-executor.js +320 -0
  70. package/dist/webmcp.d.ts +202 -0
  71. package/dist/webmcp.js +173 -0
  72. package/package.json +20 -6
@@ -0,0 +1,66 @@
1
+ /**
2
+ * @module tree
3
+ *
4
+ * Flattens the component adjacency list (`id -> ComponentInstance`, each instance's `children`
5
+ * being an array of other ids) into an ordered, depth-first render list — the two adversarial
6
+ * cases this exists to answer sanely: **a child id that doesn't exist** in the map, and **a
7
+ * circular reference** (A -> B -> A). Neither may crash or infinite-loop a renderer; both must
8
+ * degrade to a visible, inert placeholder node instead.
9
+ *
10
+ * Scope: only the *static array* form of `ChildList` (`common_types.json#/$defs/ChildList`'s
11
+ * first `oneOf` branch) is walked here. The *template* form (`{componentId, path}`, generating N
12
+ * children from a data-model list) is accepted by the wire schema (`ChildListSchema`) but not
13
+ * expanded by this port — see `../source-map.md` for why (a distinct, substantially larger
14
+ * rendering feature: item-scoped relative-path resolution, `@index`, per-item React keys for one
15
+ * shared component definition rendered N times). A `getChildIds` callback that always returns
16
+ * `[]` for a template-shaped `children` value is a safe, honest way to consume this module without
17
+ * pretending template lists render.
18
+ */
19
+ export interface ComponentLike {
20
+ readonly id: string;
21
+ }
22
+ export type RenderNodeStatus = 'ok' | 'missing' | 'cycle' | 'truncated';
23
+ export interface RenderNode {
24
+ readonly id: string;
25
+ readonly depth: number;
26
+ readonly status: RenderNodeStatus;
27
+ }
28
+ /**
29
+ * Ceiling on how many nodes one flattening may produce.
30
+ *
31
+ * The cycle check bounds *repetition along one path*; it does not bound the tree's size, and a
32
+ * component map is an adjacency list, so a valid acyclic message can name the same child twice per
33
+ * level and double the output at every step. Measured before this cap existed: 24 components —
34
+ * a few hundred bytes of wire data — expanded to 16,777,215 render nodes in ~15 seconds. Nothing
35
+ * crashed; the renderer was simply consumed.
36
+ *
37
+ * Far above any real UI (the largest component tree a catalog of 18 types could sensibly produce
38
+ * is orders of magnitude smaller), so this is a fail-safe, not a design budget.
39
+ */
40
+ export declare const MAX_RENDER_NODES = 50000;
41
+ /**
42
+ * @param components The full component map (id -> instance).
43
+ * @param rootId The id to start walking from (typically `'root'`, but not assumed — a surface
44
+ * with no `root` component yet is the caller's concern, not this function's; see
45
+ * `interpreter.ts`'s `getRoot()`).
46
+ * @param getChildIds Given a present component, returns its child ids in render order (`[]` for
47
+ * a leaf, or a template-shaped `ChildList` this port doesn't expand — see module doc).
48
+ * @returns A depth-first, pre-order flattening. A `missing` node is a leaf in the output (its own
49
+ * children are never visited — there is nothing to look up). A `cycle` node is also a leaf: the
50
+ * id is emitted once more so a renderer can show *where* the cycle closes, but its children are
51
+ * not walked again (that walk already happened higher up the same path). A `truncated` node is the
52
+ * third such marker and always the last entry: the tree exceeded {@link MAX_RENDER_NODES} and the
53
+ * rest was not walked.
54
+ *
55
+ * The walk is iterative — an explicit stack rather than recursion — because the component map is
56
+ * agent-authored: a straight chain of components is a legal, acyclic message, and a recursive walk
57
+ * died on one with `RangeError: Maximum call stack size exceeded` somewhere past 6,000 links.
58
+ * Degrading sanely on hostile input is this module's whole purpose, and "deep" belongs on that
59
+ * list next to "missing" and "circular".
60
+ *
61
+ * The ancestor set is maintained by push/pop along the current path rather than copied per node,
62
+ * which is both what makes the iterative form equivalent (an ancestor set IS the path from the
63
+ * root) and what removes the old walk's quadratic set-copying cost.
64
+ */
65
+ export declare function flattenRenderTree<C extends ComponentLike>(components: ReadonlyMap<string, C>, rootId: string, getChildIds: (component: C) => readonly string[]): RenderNode[];
66
+ //# sourceMappingURL=tree.d.ts.map
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Ceiling on how many nodes one flattening may produce.
3
+ *
4
+ * The cycle check bounds *repetition along one path*; it does not bound the tree's size, and a
5
+ * component map is an adjacency list, so a valid acyclic message can name the same child twice per
6
+ * level and double the output at every step. Measured before this cap existed: 24 components —
7
+ * a few hundred bytes of wire data — expanded to 16,777,215 render nodes in ~15 seconds. Nothing
8
+ * crashed; the renderer was simply consumed.
9
+ *
10
+ * Far above any real UI (the largest component tree a catalog of 18 types could sensibly produce
11
+ * is orders of magnitude smaller), so this is a fail-safe, not a design budget.
12
+ */
13
+ export const MAX_RENDER_NODES = 50_000;
14
+ /**
15
+ * @param components The full component map (id -> instance).
16
+ * @param rootId The id to start walking from (typically `'root'`, but not assumed — a surface
17
+ * with no `root` component yet is the caller's concern, not this function's; see
18
+ * `interpreter.ts`'s `getRoot()`).
19
+ * @param getChildIds Given a present component, returns its child ids in render order (`[]` for
20
+ * a leaf, or a template-shaped `ChildList` this port doesn't expand — see module doc).
21
+ * @returns A depth-first, pre-order flattening. A `missing` node is a leaf in the output (its own
22
+ * children are never visited — there is nothing to look up). A `cycle` node is also a leaf: the
23
+ * id is emitted once more so a renderer can show *where* the cycle closes, but its children are
24
+ * not walked again (that walk already happened higher up the same path). A `truncated` node is the
25
+ * third such marker and always the last entry: the tree exceeded {@link MAX_RENDER_NODES} and the
26
+ * rest was not walked.
27
+ *
28
+ * The walk is iterative — an explicit stack rather than recursion — because the component map is
29
+ * agent-authored: a straight chain of components is a legal, acyclic message, and a recursive walk
30
+ * died on one with `RangeError: Maximum call stack size exceeded` somewhere past 6,000 links.
31
+ * Degrading sanely on hostile input is this module's whole purpose, and "deep" belongs on that
32
+ * list next to "missing" and "circular".
33
+ *
34
+ * The ancestor set is maintained by push/pop along the current path rather than copied per node,
35
+ * which is both what makes the iterative form equivalent (an ancestor set IS the path from the
36
+ * root) and what removes the old walk's quadratic set-copying cost.
37
+ */
38
+ export function flattenRenderTree(components, rootId, getChildIds) {
39
+ const output = [];
40
+ /** Ids on the path from the root to the node being visited — the recursive walk's `ancestors`. */
41
+ const ancestors = new Set();
42
+ const stack = [{ id: rootId, depth: 0 }];
43
+ while (stack.length > 0) {
44
+ const frame = stack.pop();
45
+ if ('leave' in frame) {
46
+ ancestors.delete(frame.leave);
47
+ continue;
48
+ }
49
+ if (output.length >= MAX_RENDER_NODES) {
50
+ output.push({ id: frame.id, depth: frame.depth, status: 'truncated' });
51
+ return output;
52
+ }
53
+ const { id, depth } = frame;
54
+ if (ancestors.has(id)) {
55
+ output.push({ id, depth, status: 'cycle' });
56
+ continue;
57
+ }
58
+ const component = components.get(id);
59
+ if (!component) {
60
+ output.push({ id, depth, status: 'missing' });
61
+ continue;
62
+ }
63
+ output.push({ id, depth, status: 'ok' });
64
+ ancestors.add(id);
65
+ stack.push({ leave: id });
66
+ // Pushed in reverse so the first child is popped first, preserving pre-order.
67
+ const childIds = getChildIds(component);
68
+ for (let index = childIds.length - 1; index >= 0; index -= 1) {
69
+ stack.push({ id: childIds[index], depth: depth + 1 });
70
+ }
71
+ }
72
+ return output;
73
+ }
74
+ //# sourceMappingURL=tree.js.map
@@ -0,0 +1,82 @@
1
+ /**
2
+ * @module ag-ui
3
+ *
4
+ * Projection: {@link CapabilityDef} → an AG-UI frontend tool.
5
+ *
6
+ * AG-UI (the Agent-User Interaction Protocol) streams typed events between an agent backend and
7
+ * a frontend. The relevant half here is its **frontend tool calls**: the frontend passes its
8
+ * tools in `RunAgentInput.tools`, the agent emits a tool call, the frontend executes it, and the
9
+ * frontend returns a `role: "tool"` message referencing the call id. That is the same handoff
10
+ * Jini's capabilities describe, which is why this projection is a rename rather than a redesign.
11
+ *
12
+ * One shape difference this file exists to absorb: **AG-UI names the JSON Schema field
13
+ * `parameters`**, where WebMCP and MCP both name it `inputSchema`. Anything reading a manifest
14
+ * through the wrong name silently sends a tool with no arguments.
15
+ *
16
+ * Transport is not here — AG-UI runs over SSE or WebSocket, and this package opens no
17
+ * connections. This is the vocabulary translation only.
18
+ */
19
+ import type { CapabilityDef, CapabilityInputSchema } from './capability.js';
20
+ /** An AG-UI tool as passed in `RunAgentInput.tools`. */
21
+ export interface AgUiTool {
22
+ readonly name: string;
23
+ readonly description: string;
24
+ /** JSON Schema. Note the field name: AG-UI says `parameters`, not `inputSchema`. */
25
+ readonly parameters: CapabilityInputSchema;
26
+ }
27
+ /**
28
+ * The tool-call event names AG-UI emits, agent → frontend.
29
+ *
30
+ * Arguments stream: `TOOL_CALL_ARGS` carries a `delta` fragment and may arrive many times for
31
+ * one call, so a consumer must accumulate by `toolCallId` and only execute after
32
+ * `TOOL_CALL_END`. Acting on a partial argument object is the obvious failure here.
33
+ */
34
+ export declare const AG_UI_TOOL_CALL_EVENTS: {
35
+ /** Fields: `toolCallId`, `toolCallName`, optional `parentMessageId`. */
36
+ readonly start: "TOOL_CALL_START";
37
+ /** Fields: `toolCallId`, `delta` — a JSON fragment, not a complete object. */
38
+ readonly args: "TOOL_CALL_ARGS";
39
+ /** Fields: `toolCallId`. Arguments are complete only once this arrives. */
40
+ readonly end: "TOOL_CALL_END";
41
+ };
42
+ /** The message a frontend returns after executing a tool call. */
43
+ export interface AgUiToolResultMessage {
44
+ readonly id: string;
45
+ readonly role: 'tool';
46
+ readonly content: string;
47
+ readonly toolCallId: string;
48
+ }
49
+ /**
50
+ * Projects one capability into an AG-UI tool.
51
+ *
52
+ * @param capability - The capability to expose.
53
+ * @returns The tool entry for `RunAgentInput.tools`.
54
+ */
55
+ export declare function toAgUiTool(capability: CapabilityDef): AgUiTool;
56
+ /**
57
+ * Projects a whole manifest.
58
+ *
59
+ * @param capabilities - Capabilities to expose, already filtered by whatever policy applies.
60
+ * @returns One tool per capability, in manifest order.
61
+ */
62
+ export declare function toAgUiTools(capabilities: readonly CapabilityDef[]): readonly AgUiTool[];
63
+ /**
64
+ * Builds the result message for a completed frontend tool call.
65
+ *
66
+ * AG-UI carries the result as a string, so structured output is JSON-encoded. Errors are
67
+ * returned through this same channel rather than thrown — the agent needs to see the refusal
68
+ * (a fill guard saying no, an unavailable capability) as a result it can reason about.
69
+ *
70
+ * @param messageId - Id for the result message itself.
71
+ * @param toolCallId - The `toolCallId` from `TOOL_CALL_START`.
72
+ * @param outcome - What happened.
73
+ * @returns The `role: "tool"` message to send back.
74
+ */
75
+ export declare function createAgUiToolResult(messageId: string, toolCallId: string, outcome: {
76
+ ok: true;
77
+ output: unknown;
78
+ } | {
79
+ ok: false;
80
+ error: string;
81
+ }): AgUiToolResultMessage;
82
+ //# sourceMappingURL=ag-ui.d.ts.map
package/dist/ag-ui.js ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The tool-call event names AG-UI emits, agent → frontend.
3
+ *
4
+ * Arguments stream: `TOOL_CALL_ARGS` carries a `delta` fragment and may arrive many times for
5
+ * one call, so a consumer must accumulate by `toolCallId` and only execute after
6
+ * `TOOL_CALL_END`. Acting on a partial argument object is the obvious failure here.
7
+ */
8
+ export const AG_UI_TOOL_CALL_EVENTS = {
9
+ /** Fields: `toolCallId`, `toolCallName`, optional `parentMessageId`. */
10
+ start: 'TOOL_CALL_START',
11
+ /** Fields: `toolCallId`, `delta` — a JSON fragment, not a complete object. */
12
+ args: 'TOOL_CALL_ARGS',
13
+ /** Fields: `toolCallId`. Arguments are complete only once this arrives. */
14
+ end: 'TOOL_CALL_END',
15
+ };
16
+ /**
17
+ * Projects one capability into an AG-UI tool.
18
+ *
19
+ * @param capability - The capability to expose.
20
+ * @returns The tool entry for `RunAgentInput.tools`.
21
+ */
22
+ export function toAgUiTool(capability) {
23
+ return {
24
+ name: capability.id,
25
+ description: capability.description,
26
+ parameters: capability.inputSchema,
27
+ };
28
+ }
29
+ /**
30
+ * Projects a whole manifest.
31
+ *
32
+ * @param capabilities - Capabilities to expose, already filtered by whatever policy applies.
33
+ * @returns One tool per capability, in manifest order.
34
+ */
35
+ export function toAgUiTools(capabilities) {
36
+ return capabilities.map(toAgUiTool);
37
+ }
38
+ /**
39
+ * JSON, or a description of why there is none — always a string, which `JSON.stringify` alone is
40
+ * not.
41
+ *
42
+ * `output` is `unknown`: whatever a host's capability actually returned. `JSON.stringify` is not
43
+ * total over that domain, in two different ways, and `content` is declared `string`:
44
+ *
45
+ * - it **throws** for a BigInt or a circular structure — landing on the transport, where the
46
+ * agent never learns its tool call produced anything at all;
47
+ * - it **returns `undefined`** (not a string) for a function or a symbol, so `content` was
48
+ * genuinely `undefined` despite its type, and whatever serialized the message downstream
49
+ * dropped the field or wrote `undefined` into the wire.
50
+ *
51
+ * Both become a result the agent can read, because that is this channel's whole premise: a
52
+ * failure it can see and reason about beats one that disappears.
53
+ */
54
+ function encodeToolContent(output) {
55
+ let encoded;
56
+ try {
57
+ encoded = JSON.stringify(output ?? null);
58
+ }
59
+ catch (error) {
60
+ const detail = error instanceof Error ? error.message : String(error);
61
+ return JSON.stringify({ error: `tool output could not be encoded as JSON: ${detail}` });
62
+ }
63
+ // `undefined` here means "not representable in JSON" (a function, a symbol), which is what
64
+ // `null` means in every other JSON position — an array element, an object property.
65
+ return encoded ?? 'null';
66
+ }
67
+ /**
68
+ * Builds the result message for a completed frontend tool call.
69
+ *
70
+ * AG-UI carries the result as a string, so structured output is JSON-encoded. Errors are
71
+ * returned through this same channel rather than thrown — the agent needs to see the refusal
72
+ * (a fill guard saying no, an unavailable capability) as a result it can reason about.
73
+ *
74
+ * @param messageId - Id for the result message itself.
75
+ * @param toolCallId - The `toolCallId` from `TOOL_CALL_START`.
76
+ * @param outcome - What happened.
77
+ * @returns The `role: "tool"` message to send back.
78
+ */
79
+ export function createAgUiToolResult(messageId, toolCallId, outcome) {
80
+ const content = outcome.ok
81
+ ? typeof outcome.output === 'string' ? outcome.output : encodeToolContent(outcome.output)
82
+ : JSON.stringify({ error: outcome.error });
83
+ return { id: messageId, role: 'tool', content, toolCallId };
84
+ }
85
+ //# sourceMappingURL=ag-ui.js.map
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @module agui/encoder
3
+ *
4
+ * Encodes `@jini/protocol`'s `RunProtocolEvent` stream into AG-UI wire events (see
5
+ * `./events.ts`'s module doc). Rewritten from scratch against `@jini/protocol`'s actual
6
+ * current shape — the ported adapter's original encoder targeted a different, product-specific
7
+ * event union with no direct correspondence to `RunProtocolEvent`/`RunAgentPayload`; only the
8
+ * *shape* of the job (a big per-event-kind switch, unrecognized events silently dropped) carried
9
+ * over. See `source-map.md` for the full old→new field-mapping table and the generalization
10
+ * writeup for the six event kinds that had no generic equivalent before this task.
11
+ *
12
+ * Folded in 2026-07-26 from the standalone `@jini/agui` package (plan §3a) into this `src/agui/`
13
+ * subdirectory — kept out of the flat `ag-ui.ts` namespace because that file is a different
14
+ * projection ({@link CapabilityDef} → an AG-UI *frontend tool*); this one turns a run's event
15
+ * stream into AG-UI *wire* events. Same protocol, two unrelated halves of it.
16
+ */
17
+ import type { RunProtocolEvent } from '@jini/protocol';
18
+ import type { AGUIEvent } from './events.js';
19
+ export interface AguiEncodeContext {
20
+ /** The run this event belongs to — stamped onto every produced `AGUIEvent`. */
21
+ readonly runId: string;
22
+ /** Passed through onto the produced event's `seq`, when the caller tracks one (e.g. an SSE `Last-Event-ID`-shaped cursor). Omitted entirely (not set to `undefined`) when absent, matching the original adapter's own base-field construction. */
23
+ readonly seq?: number;
24
+ /** Injectable clock for the produced event's `ts`. Defaults to `Date.now`. Test-only hook. */
25
+ readonly now?: () => number;
26
+ }
27
+ /**
28
+ * A stateful AG-UI encoder for one run's event stream. Stateful because `tool_use`/`tool_result`
29
+ * correlation requires remembering each in-flight tool call's name/args between the two protocol
30
+ * events that describe its start and end — a pure per-event function cannot do this alone. Create
31
+ * one instance per run (e.g. one per `RunLifecycle.stream(runId, ...)` subscription); do not share
32
+ * an instance across multiple runs, since the correlation map has no per-run partitioning of its
33
+ * own (`ctx.runId` is only used to stamp the produced event, not to scope the map).
34
+ */
35
+ export interface AguiEncoder {
36
+ /**
37
+ * Encodes one `RunProtocolEvent` into an `AGUIEvent`, or `null` if this event has no AG-UI
38
+ * equivalent (an unrecognized/not-yet-generalized event kind — silently dropped by the relay,
39
+ * matching the original adapter's own default behavior).
40
+ */
41
+ encode(event: RunProtocolEvent, ctx: AguiEncodeContext): AGUIEvent | null;
42
+ }
43
+ /**
44
+ * Creates a fresh `AguiEncoder` with its own, empty tool-call correlation map.
45
+ * @complexity `encode` is O(1) per call (one `Map` get/set/delete); memory is O(k) in the number
46
+ * of currently in-flight (not yet resolved) tool calls for the run this instance encodes.
47
+ * @overallScore 100/100
48
+ */
49
+ export declare function createAguiEncoder(): AguiEncoder;
50
+ //# sourceMappingURL=encoder.d.ts.map
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Creates a fresh `AguiEncoder` with its own, empty tool-call correlation map.
3
+ * @complexity `encode` is O(1) per call (one `Map` get/set/delete); memory is O(k) in the number
4
+ * of currently in-flight (not yet resolved) tool calls for the run this instance encodes.
5
+ * @overallScore 100/100
6
+ */
7
+ export function createAguiEncoder() {
8
+ const pendingToolCalls = new Map();
9
+ function baseFields(ctx) {
10
+ const ts = ctx.now ? ctx.now() : Date.now();
11
+ return ctx.seq !== undefined ? { runId: ctx.runId, ts, seq: ctx.seq } : { runId: ctx.runId, ts };
12
+ }
13
+ function encodeAgentPayload(payload, ctx) {
14
+ const base = baseFields(ctx);
15
+ switch (payload.type) {
16
+ case 'text_delta':
17
+ return { ...base, kind: 'agent.message', text: payload.delta };
18
+ case 'tool_use':
19
+ // Overwrites any prior entry under the same id (a duplicate tool_use for one id) — the
20
+ // most recent call's name/args are what a matching tool_result should be attributed to,
21
+ // and there is no protocol-level guarantee ids are never reused within one run.
22
+ pendingToolCalls.set(payload.id, { toolName: payload.name, args: payload.input });
23
+ return { ...base, kind: 'tool_call', toolName: payload.name, args: payload.input, callId: payload.id, status: 'started' };
24
+ case 'tool_result': {
25
+ const pending = pendingToolCalls.get(payload.toolUseId);
26
+ pendingToolCalls.delete(payload.toolUseId);
27
+ return {
28
+ ...base,
29
+ kind: 'tool_call',
30
+ // A tool_result with no matching prior tool_use (never observed, or already resolved/
31
+ // cleared — e.g. after a run-ending 'end' event, see below) falls back to an 'unknown'
32
+ // name and null args rather than throwing: the result itself is still real and worth
33
+ // relaying even when its originating call wasn't captured.
34
+ toolName: pending?.toolName ?? 'unknown',
35
+ args: pending?.args ?? null,
36
+ callId: payload.toolUseId,
37
+ status: payload.isError ? 'failed' : 'completed',
38
+ result: payload.content,
39
+ };
40
+ }
41
+ // Generalization (see source-map.md): pipeline_stage_started/completed generalized into a
42
+ // named-stage boundary any multi-step driver can emit, flowing through the same 'agent'
43
+ // channel as tool_use/tool_result.
44
+ case 'stage_start':
45
+ return {
46
+ ...base,
47
+ kind: 'run.lifecycle',
48
+ status: 'pipeline_stage_started',
49
+ stageId: payload.stageId,
50
+ ...(payload.iteration !== undefined ? { iteration: payload.iteration } : {}),
51
+ };
52
+ case 'stage_end':
53
+ return {
54
+ ...base,
55
+ kind: 'run.lifecycle',
56
+ status: 'pipeline_stage_completed',
57
+ stageId: payload.stageId,
58
+ ...(payload.iteration !== undefined ? { iteration: payload.iteration } : {}),
59
+ };
60
+ // Generalization (see source-map.md): genui_surface_request/response generalized into a
61
+ // generic human-in-the-loop ask/answer pair.
62
+ case 'surface_request':
63
+ return { ...base, kind: 'ui.surface_requested', surfaceId: payload.surfaceId, surfaceKind: payload.surfaceKind, payload: payload.payload };
64
+ case 'surface_response':
65
+ return { ...base, kind: 'ui.surface_responded', surfaceId: payload.surfaceId, value: payload.value, respondedBy: payload.respondedBy };
66
+ // 'status' / 'thinking_start' / 'thinking_delta' / 'tool_input_delta' / 'usage' / 'raw':
67
+ // no AG-UI equivalent — silently dropped, matching the original adapter's default behavior.
68
+ default:
69
+ return null;
70
+ }
71
+ }
72
+ function encode(event, ctx) {
73
+ switch (event.kind) {
74
+ case 'start':
75
+ return { ...baseFields(ctx), kind: 'run.lifecycle', status: 'started' };
76
+ case 'end': {
77
+ const status = event.payload.status === 'failed' ? 'failed' : event.payload.status === 'canceled' ? 'cancelled' : 'completed';
78
+ // A run can legitimately end while a tool_use is still in flight (its tool_result never
79
+ // arrived, or arrived after 'end' and was already rejected by RunLifecycle — see
80
+ // run-lifecycle.ts's "cannot emit on terminal run" guard). Clearing here means any such
81
+ // stale entries never leak past this run's own lifetime, and a same-id tool_result that
82
+ // somehow still reaches this encoder afterward correctly falls back to 'unknown' rather
83
+ // than resolving against a call from a run that has already ended.
84
+ pendingToolCalls.clear();
85
+ return { ...baseFields(ctx), kind: 'run.lifecycle', status };
86
+ }
87
+ case 'agent':
88
+ return encodeAgentPayload(event.payload, ctx);
89
+ // 'stdout' / 'stderr' / 'error': no AG-UI equivalent — silently dropped, matching the
90
+ // original adapter's default behavior for unrecognized event kinds.
91
+ default:
92
+ return null;
93
+ }
94
+ }
95
+ return { encode };
96
+ }
97
+ //# sourceMappingURL=encoder.js.map
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @module agui/events
3
+ *
4
+ * The AG-UI wire event shapes `./encoder.ts` produces. AG-UI (Agent-User Interaction
5
+ * Protocol) is CopilotKit's open, external wire protocol for streaming an agent's run over SSE to
6
+ * a UI client — see https://github.com/ag-ui-protocol/ag-ui. This module is a near-verbatim port
7
+ * of a 312-line adapter that encoded a product's own run-event stream into this shape; the types
8
+ * themselves are unchanged in kind, only de-branded (see `source-map.md` for the full
9
+ * field-mapping table and provenance).
10
+ *
11
+ * Folded in 2026-07-26 from the standalone `@jini/agui` package (plan §3a) into this `src/agui/`
12
+ * subdirectory — see `./encoder.ts` for why it is kept apart from the flat `ag-ui.ts`.
13
+ */
14
+ export type AGUIEventKind = 'agent.message' | 'tool_call' | 'state_update' | 'ui.surface_requested' | 'ui.surface_responded' | 'run.lifecycle';
15
+ export interface AGUIEventBase {
16
+ kind: AGUIEventKind;
17
+ runId: string;
18
+ seq?: number;
19
+ ts: number;
20
+ }
21
+ export interface AGUIAgentMessageEvent extends AGUIEventBase {
22
+ kind: 'agent.message';
23
+ text: string;
24
+ done?: boolean;
25
+ }
26
+ export interface AGUIToolCallEvent extends AGUIEventBase {
27
+ kind: 'tool_call';
28
+ toolName: string;
29
+ args: unknown;
30
+ callId?: string;
31
+ status?: 'started' | 'completed' | 'failed';
32
+ result?: unknown;
33
+ }
34
+ export interface AGUIStateUpdateEvent extends AGUIEventBase {
35
+ kind: 'state_update';
36
+ path: string;
37
+ value: unknown;
38
+ }
39
+ export interface AGUISurfaceRequestedEvent extends AGUIEventBase {
40
+ kind: 'ui.surface_requested';
41
+ surfaceId: string;
42
+ surfaceKind: 'form' | 'choice' | 'confirmation' | 'oauth-prompt';
43
+ payload: unknown;
44
+ }
45
+ export interface AGUISurfaceRespondedEvent extends AGUIEventBase {
46
+ kind: 'ui.surface_responded';
47
+ surfaceId: string;
48
+ value: unknown;
49
+ respondedBy: 'user' | 'agent' | 'auto' | 'cache';
50
+ }
51
+ export interface AGUIRunLifecycleEvent extends AGUIEventBase {
52
+ kind: 'run.lifecycle';
53
+ status: 'started' | 'pipeline_stage_started' | 'pipeline_stage_completed' | 'completed' | 'cancelled' | 'failed';
54
+ stageId?: string;
55
+ iteration?: number;
56
+ message?: string;
57
+ }
58
+ export type AGUIEvent = AGUIAgentMessageEvent | AGUIToolCallEvent | AGUIStateUpdateEvent | AGUISurfaceRequestedEvent | AGUISurfaceRespondedEvent | AGUIRunLifecycleEvent;
59
+ //# sourceMappingURL=events.d.ts.map
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @module agui/events
3
+ *
4
+ * The AG-UI wire event shapes `./encoder.ts` produces. AG-UI (Agent-User Interaction
5
+ * Protocol) is CopilotKit's open, external wire protocol for streaming an agent's run over SSE to
6
+ * a UI client — see https://github.com/ag-ui-protocol/ag-ui. This module is a near-verbatim port
7
+ * of a 312-line adapter that encoded a product's own run-event stream into this shape; the types
8
+ * themselves are unchanged in kind, only de-branded (see `source-map.md` for the full
9
+ * field-mapping table and provenance).
10
+ *
11
+ * Folded in 2026-07-26 from the standalone `@jini/agui` package (plan §3a) into this `src/agui/`
12
+ * subdirectory — see `./encoder.ts` for why it is kept apart from the flat `ag-ui.ts`.
13
+ */
14
+ export {};
15
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @module capability
3
+ *
4
+ * The vocabulary every agent-drivable surface shares: what an outside caller may ask a
5
+ * frontend to do, described as pure data with no transport, DOM, or framework attached.
6
+ *
7
+ * One noun, deliberately: **capability**. The chat pane's first draft used `tool` in its
8
+ * type names and `capability` in its ids, which forked the vocabulary across four files.
9
+ * `tool` stays reserved for the engine's own `ToolRegistry`/`ToolExecutor` nouns; anything
10
+ * an outside caller asks a *frontend* to do is a capability. Transports may of course
11
+ * present capabilities as MCP tools — that is a projection, not a rename.
12
+ */
13
+ /** How much damage a capability can do. `requiresConfirmation` is the enforcement; this is the label. */
14
+ export type CapabilityRisk = 'read' | 'write';
15
+ /**
16
+ * Whether a capability means anything without a live UI session attached.
17
+ *
18
+ * - `session` — needs a connected frontend. "Highlight this field" is meaningless with no
19
+ * tab open, and must fail closed with a distinct error rather than hanging on a timeout.
20
+ * - `server` — a product outcome the backend can satisfy headlessly. Sending a chat message
21
+ * is the same outcome whether a tab is open or not.
22
+ *
23
+ * This decides *availability*, so a caller can be told "no eligible frontend is connected"
24
+ * instead of waiting for a timeout that will never resolve.
25
+ */
26
+ export type CapabilitySurface = 'session' | 'server';
27
+ export interface CapabilityInputSchema {
28
+ readonly type: 'object';
29
+ readonly properties: Record<string, {
30
+ type: string;
31
+ description?: string;
32
+ enum?: readonly string[];
33
+ }>;
34
+ readonly required?: readonly string[];
35
+ readonly additionalProperties?: boolean;
36
+ }
37
+ export interface CapabilityDef {
38
+ readonly id: string;
39
+ readonly description: string;
40
+ readonly inputSchema: CapabilityInputSchema;
41
+ readonly risk: CapabilityRisk;
42
+ readonly surface: CapabilitySurface;
43
+ /**
44
+ * Destructive or otherwise irreversible — the caller must acknowledge before it runs. A host
45
+ * with a real confirmation gate (`@jini-ai/daemon`'s `ToolExecutor` has a resumable one) should
46
+ * enforce it there; surfaces without one enforce it in-band by requiring `confirm: true`, so
47
+ * no transport can execute it by accident.
48
+ */
49
+ readonly requiresConfirmation?: boolean;
50
+ }
51
+ /**
52
+ * Looks a capability up by id.
53
+ *
54
+ * @param capabilities - The manifest to search.
55
+ * @param id - Capability id to resolve.
56
+ * @returns The definition, or `undefined` when the id is not in the manifest.
57
+ */
58
+ export declare function findCapability(capabilities: readonly CapabilityDef[], id: string): CapabilityDef | undefined;
59
+ /**
60
+ * Checks caller input against a capability's declared schema.
61
+ *
62
+ * Manifests advertise `additionalProperties: false` and a `required` list, but nothing was
63
+ * enforcing either — handlers read the fields they knew about and ignored the rest, so a
64
+ * misnamed argument silently became a missing one. This closes that for any surface that calls
65
+ * it. Intentionally a shallow check, not a JSON Schema engine: these schemas are flat by
66
+ * construction, and a real validator is a dependency this package will not take.
67
+ *
68
+ * @param capability - The capability being invoked.
69
+ * @param input - Raw caller-supplied arguments.
70
+ * @returns An error message, or `null` when the input is acceptable.
71
+ */
72
+ export declare function findCapabilityInputError(capability: CapabilityDef, input: Record<string, unknown>): string | null;
73
+ /**
74
+ * The capabilities a caller may use given what is currently connected.
75
+ *
76
+ * @param capabilities - The full manifest.
77
+ * @param hasSession - Whether a live frontend session is attached.
78
+ * @returns Only the capabilities that can actually be satisfied right now.
79
+ */
80
+ export declare function availableCapabilities(capabilities: readonly CapabilityDef[], hasSession: boolean): readonly CapabilityDef[];
81
+ //# sourceMappingURL=capability.d.ts.map