@assistant-ui/react-ag-ui 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agUiExtras.js +1 -2
- package/dist/hooks.js +1 -2
- package/dist/runtime/AgUiThreadController.d.ts.map +1 -1
- package/dist/runtime/AgUiThreadController.js +354 -68
- package/dist/runtime/AgUiThreadController.js.map +1 -1
- package/dist/runtime/adapter/conversions.d.ts.map +1 -1
- package/dist/runtime/adapter/conversions.js +10 -3
- package/dist/runtime/adapter/conversions.js.map +1 -1
- package/dist/runtime/adapter/replay-content.d.ts +9 -0
- package/dist/runtime/adapter/replay-content.d.ts.map +1 -0
- package/dist/runtime/adapter/replay-content.js +185 -0
- package/dist/runtime/adapter/replay-content.js.map +1 -0
- package/dist/runtime/adapter/run-aggregator.js +1 -2
- package/dist/runtime/adapter/subscriber.js +1 -2
- package/dist/runtime/adapter/tool-approval.d.ts +2 -0
- package/dist/runtime/adapter/tool-approval.d.ts.map +1 -1
- package/dist/runtime/adapter/tool-approval.js +23 -6
- package/dist/runtime/adapter/tool-approval.js.map +1 -1
- package/dist/runtime/agUiThreadState.d.ts +1 -1
- package/dist/runtime/agUiThreadState.d.ts.map +1 -1
- package/dist/runtime/agUiThreadState.js +3 -4
- package/dist/runtime/agUiThreadState.js.map +1 -1
- package/dist/runtime/event-parser.js +1 -2
- package/dist/runtime/interrupt-internals.js +1 -2
- package/dist/runtime/logger.js +1 -2
- package/dist/runtime/mcp-tool-result.js +1 -2
- package/dist/runtime/types.js +1 -2
- package/dist/useAgUiRuntime.js +1 -2
- package/package.json +5 -5
- package/src/runtime/AgUiThreadController.deferred-results.test.ts +548 -0
- package/src/runtime/AgUiThreadController.replay.test.ts +3932 -0
- package/src/runtime/AgUiThreadController.test.ts +79 -0
- package/src/runtime/AgUiThreadController.ts +725 -109
- package/src/runtime/adapter/conversions.content.test.ts +113 -1
- package/src/runtime/adapter/conversions.ts +18 -8
- package/src/runtime/adapter/replay-content.test.ts +235 -0
- package/src/runtime/adapter/replay-content.ts +306 -0
- package/src/runtime/adapter/tool-approval.ts +41 -3
- package/src/runtime/agUiThreadState.test.ts +21 -2
- package/src/runtime/agUiThreadState.ts +12 -3
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { preserveToolApprovalDecision } from "./tool-approval.js";
|
|
2
|
+
import { iterateToolCallParts, mapToolCallPartsDeep } from "@assistant-ui/core/internal";
|
|
3
|
+
// src/runtime/adapter/replay-content.ts
|
|
4
|
+
function indexReplayToolOwners(owners) {
|
|
5
|
+
const ownerByToolCallId = /* @__PURE__ */ new Map();
|
|
6
|
+
for (const owner of owners) for (const part of iterateToolCallParts(owner.content)) if (!ownerByToolCallId.has(part.toolCallId)) ownerByToolCallId.set(part.toolCallId, owner.id);
|
|
7
|
+
return ownerByToolCallId;
|
|
8
|
+
}
|
|
9
|
+
function groupReplayToolContent(owners, content, fallbackMessageId) {
|
|
10
|
+
const ownerByToolCallId = indexReplayToolOwners(owners);
|
|
11
|
+
const grouped = /* @__PURE__ */ new Map([[fallbackMessageId, []]]);
|
|
12
|
+
for (const part of content) {
|
|
13
|
+
const ownerId = part.type === "tool-call" ? ownerByToolCallId.get(part.toolCallId) ?? fallbackMessageId : fallbackMessageId;
|
|
14
|
+
const parts = grouped.get(ownerId) ?? [];
|
|
15
|
+
parts.push(part);
|
|
16
|
+
grouped.set(ownerId, parts);
|
|
17
|
+
}
|
|
18
|
+
return grouped;
|
|
19
|
+
}
|
|
20
|
+
function preserveToolResult(previous, next) {
|
|
21
|
+
if (previous.result === void 0 || next.result !== void 0) return next;
|
|
22
|
+
return {
|
|
23
|
+
...next,
|
|
24
|
+
result: previous.result,
|
|
25
|
+
...previous.artifact !== void 0 ? { artifact: previous.artifact } : {},
|
|
26
|
+
...previous.isError !== void 0 ? { isError: previous.isError } : {},
|
|
27
|
+
...previous.modelContent !== void 0 ? { modelContent: previous.modelContent } : {}
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function mergeOrdered(previous, next, merge) {
|
|
31
|
+
const old = new Map(previous.map(([value, key]) => [key, value]));
|
|
32
|
+
const indexes = new Map(next.map(([, key], index) => [key, index]));
|
|
33
|
+
const insertions = Array.from({ length: next.length + 1 }, () => []);
|
|
34
|
+
let predecessor = -1;
|
|
35
|
+
for (const [value, key] of previous) {
|
|
36
|
+
const index = indexes.get(key);
|
|
37
|
+
if (index === void 0) insertions[predecessor + 1].push(value);
|
|
38
|
+
else predecessor = index;
|
|
39
|
+
}
|
|
40
|
+
const result = [];
|
|
41
|
+
for (const [index, [value, key]] of next.entries()) {
|
|
42
|
+
const prior = old.get(key);
|
|
43
|
+
result.push(...insertions[index], prior === void 0 ? value : merge(prior, value));
|
|
44
|
+
}
|
|
45
|
+
result.push(...insertions[next.length]);
|
|
46
|
+
return result;
|
|
47
|
+
}
|
|
48
|
+
function mergeMessages(previous, next) {
|
|
49
|
+
return mergeOrdered(previous.map((message) => [message, message.id]), next.map((message) => [message, message.id]), (old, fresh) => old.role === "assistant" && fresh.role === "assistant" ? {
|
|
50
|
+
...fresh,
|
|
51
|
+
content: mergeReplayContent(old.content, fresh.content)
|
|
52
|
+
} : fresh);
|
|
53
|
+
}
|
|
54
|
+
function mergeTool(previous, next) {
|
|
55
|
+
const result = preserveToolResult(previous, next);
|
|
56
|
+
const approval = preserveToolApprovalDecision(previous, next);
|
|
57
|
+
return {
|
|
58
|
+
...result,
|
|
59
|
+
...approval ? { approval } : {},
|
|
60
|
+
...result.unstable_interactions === void 0 && previous.unstable_interactions !== void 0 ? { unstable_interactions: previous.unstable_interactions } : {},
|
|
61
|
+
...previous.messages !== void 0 || next.messages !== void 0 ? { messages: mergeMessages(previous.messages ?? [], next.messages ?? []) } : {}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function partKey(part) {
|
|
65
|
+
if (part.type === "tool-call") return `tool:${part.toolCallId}`;
|
|
66
|
+
if (part.type === "text" || part.type === "reasoning") return part.type;
|
|
67
|
+
if ("id" in part && typeof part.id === "string" && part.id) return `${part.type}:${part.id}`;
|
|
68
|
+
if (part.type === "data") return `data:${part.name}`;
|
|
69
|
+
return part.type;
|
|
70
|
+
}
|
|
71
|
+
function keyed(content) {
|
|
72
|
+
const ordinals = /* @__PURE__ */ new Map();
|
|
73
|
+
return content.map((part) => {
|
|
74
|
+
const base = partKey(part);
|
|
75
|
+
const ordinal = ordinals.get(base) ?? 0;
|
|
76
|
+
ordinals.set(base, ordinal + 1);
|
|
77
|
+
return [part, `${base}:${ordinal}`];
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
function identity(part, key, scope) {
|
|
81
|
+
return JSON.stringify(part.type === "tool-call" ? ["tool", part.toolCallId] : [...scope, key]);
|
|
82
|
+
}
|
|
83
|
+
function visitMessages(messages, scope, visit) {
|
|
84
|
+
for (const message of messages) {
|
|
85
|
+
const path = [
|
|
86
|
+
...scope,
|
|
87
|
+
"message",
|
|
88
|
+
message.id
|
|
89
|
+
];
|
|
90
|
+
visit(JSON.stringify(path));
|
|
91
|
+
if (message.role === "assistant") visitContent(message.content, path, visit);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function visitContent(content, scope, visit) {
|
|
95
|
+
for (const [part, key] of keyed(content)) {
|
|
96
|
+
visit(identity(part, key, scope));
|
|
97
|
+
if (part.type === "tool-call" && part.messages) visitMessages(part.messages, ["tool", part.toolCallId], visit);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function pruneMessages(messages, scope, present, owned) {
|
|
101
|
+
let hasCurrent = false;
|
|
102
|
+
return {
|
|
103
|
+
messages: messages.flatMap((message) => {
|
|
104
|
+
const path = [
|
|
105
|
+
...scope,
|
|
106
|
+
"message",
|
|
107
|
+
message.id
|
|
108
|
+
];
|
|
109
|
+
const key = JSON.stringify(path);
|
|
110
|
+
const nested = message.role === "assistant" ? pruneContent(message.content, path, present, owned) : void 0;
|
|
111
|
+
const current = present.has(key) || (nested?.hasCurrent ?? false);
|
|
112
|
+
if (owned.has(key) && !current) return [];
|
|
113
|
+
hasCurrent ||= current;
|
|
114
|
+
return [nested && message.role === "assistant" ? {
|
|
115
|
+
...message,
|
|
116
|
+
content: nested.content
|
|
117
|
+
} : message];
|
|
118
|
+
}),
|
|
119
|
+
hasCurrent
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function pruneContent(content, scope, present, owned) {
|
|
123
|
+
let hasCurrent = false;
|
|
124
|
+
return {
|
|
125
|
+
content: keyed(content).flatMap(([part, localKey]) => {
|
|
126
|
+
const key = identity(part, localKey, scope);
|
|
127
|
+
const nested = part.type === "tool-call" && part.messages ? pruneMessages(part.messages, ["tool", part.toolCallId], present, owned) : void 0;
|
|
128
|
+
const current = present.has(key) || (nested?.hasCurrent ?? false);
|
|
129
|
+
if (owned.has(key) && !current) return [];
|
|
130
|
+
hasCurrent ||= current;
|
|
131
|
+
return [nested ? {
|
|
132
|
+
...part,
|
|
133
|
+
messages: nested.messages
|
|
134
|
+
} : part];
|
|
135
|
+
}),
|
|
136
|
+
hasCurrent
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function createReplayContentMerger() {
|
|
140
|
+
const owned = /* @__PURE__ */ new Set();
|
|
141
|
+
return (previous, next) => {
|
|
142
|
+
const present = /* @__PURE__ */ new Set();
|
|
143
|
+
visitContent(next, [], (key) => present.add(key));
|
|
144
|
+
for (const key of present) owned.add(key);
|
|
145
|
+
return pruneContent(mergeReplayContent(previous, next), [], present, owned).content;
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
function nestedToolIds(content) {
|
|
149
|
+
const nestedIds = /* @__PURE__ */ new Set();
|
|
150
|
+
for (const part of content) {
|
|
151
|
+
if (part.type !== "tool-call") continue;
|
|
152
|
+
for (const message of part.messages ?? []) {
|
|
153
|
+
if (message.role !== "assistant") continue;
|
|
154
|
+
for (const child of iterateToolCallParts(message.content)) nestedIds.add(child.toolCallId);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return nestedIds;
|
|
158
|
+
}
|
|
159
|
+
function mergeReplayContent(previous, next) {
|
|
160
|
+
const nestedIds = nestedToolIds(previous);
|
|
161
|
+
const incomingNestedIds = nestedToolIds(next);
|
|
162
|
+
const movingRoots = new Map(previous.flatMap((part) => part.type === "tool-call" && incomingNestedIds.has(part.toolCallId) ? [[part.toolCallId, part]] : []));
|
|
163
|
+
const flattened = /* @__PURE__ */ new Map();
|
|
164
|
+
for (const part of next) if (part.type === "tool-call" && nestedIds.has(part.toolCallId)) flattened.set(part.toolCallId, part);
|
|
165
|
+
const prior = (flattened.size ? mapToolCallPartsDeep(previous, (part) => {
|
|
166
|
+
const fresh = flattened.get(part.toolCallId);
|
|
167
|
+
return fresh ? mergeTool(part, fresh) : part;
|
|
168
|
+
}).content : previous).filter((part) => part.type !== "tool-call" || !movingRoots.has(part.toolCallId));
|
|
169
|
+
let incoming = next.filter((part) => part.type !== "tool-call" || !flattened.has(part.toolCallId));
|
|
170
|
+
if (movingRoots.size) incoming = [...mapToolCallPartsDeep(incoming, (part) => {
|
|
171
|
+
const prior = movingRoots.get(part.toolCallId);
|
|
172
|
+
return prior ? mergeTool(prior, part) : part;
|
|
173
|
+
}).content];
|
|
174
|
+
return mergeOrdered(keyed(prior), keyed(incoming), (old, fresh) => {
|
|
175
|
+
if (old.type === "tool-call" && fresh.type === "tool-call") return mergeTool(old, fresh);
|
|
176
|
+
if ((old.type === "text" || old.type === "reasoning") && (fresh.type === "text" || fresh.type === "reasoning") && old.text.startsWith(fresh.text) && old.text.length > fresh.text.length) return {
|
|
177
|
+
...fresh,
|
|
178
|
+
text: old.text
|
|
179
|
+
};
|
|
180
|
+
return fresh;
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
export { createReplayContentMerger, groupReplayToolContent, indexReplayToolOwners, preserveToolResult };
|
|
184
|
+
|
|
185
|
+
//# sourceMappingURL=replay-content.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"replay-content.js","names":[],"sources":["../../../src/runtime/adapter/replay-content.ts"],"sourcesContent":["import type {\n ThreadAssistantMessage,\n ThreadMessage,\n ToolCallMessagePart,\n} from \"@assistant-ui/core\";\nimport {\n iterateToolCallParts,\n mapToolCallPartsDeep,\n} from \"@assistant-ui/core/internal\";\n\nimport { preserveToolApprovalDecision } from \"./tool-approval\";\n\ntype Content = ThreadAssistantMessage[\"content\"];\ntype Part = Content[number];\n\nexport function indexReplayToolOwners(\n owners: readonly ThreadAssistantMessage[],\n): ReadonlyMap<string, string> {\n const ownerByToolCallId = new Map<string, string>();\n for (const owner of owners) {\n for (const part of iterateToolCallParts(owner.content)) {\n if (!ownerByToolCallId.has(part.toolCallId))\n ownerByToolCallId.set(part.toolCallId, owner.id);\n }\n }\n return ownerByToolCallId;\n}\n\nexport function groupReplayToolContent(\n owners: readonly ThreadAssistantMessage[],\n content: Content,\n fallbackMessageId: string,\n): Map<string, Part[]> {\n const ownerByToolCallId = indexReplayToolOwners(owners);\n const grouped = new Map<string, Part[]>([[fallbackMessageId, []]]);\n for (const part of content) {\n const ownerId =\n part.type === \"tool-call\"\n ? (ownerByToolCallId.get(part.toolCallId) ?? fallbackMessageId)\n : fallbackMessageId;\n const parts = grouped.get(ownerId) ?? [];\n parts.push(part);\n grouped.set(ownerId, parts);\n }\n return grouped;\n}\n\nexport function preserveToolResult(\n previous: ToolCallMessagePart,\n next: ToolCallMessagePart,\n): ToolCallMessagePart {\n if (previous.result === undefined || next.result !== undefined) return next;\n return {\n ...next,\n result: previous.result,\n ...(previous.artifact !== undefined ? { artifact: previous.artifact } : {}),\n ...(previous.isError !== undefined ? { isError: previous.isError } : {}),\n ...(previous.modelContent !== undefined\n ? { modelContent: previous.modelContent }\n : {}),\n };\n}\n\nfunction mergeOrdered<T>(\n previous: readonly (readonly [T, string])[],\n next: readonly (readonly [T, string])[],\n merge: (old: T, fresh: T) => T,\n): T[] {\n const old = new Map(previous.map(([value, key]) => [key, value] as const));\n const indexes = new Map(next.map(([, key], index) => [key, index] as const));\n const insertions: T[][] = Array.from({ length: next.length + 1 }, () => []);\n let predecessor = -1;\n for (const [value, key] of previous) {\n const index = indexes.get(key);\n if (index === undefined) insertions[predecessor + 1]!.push(value);\n else predecessor = index;\n }\n const result: T[] = [];\n for (const [index, [value, key]] of next.entries()) {\n const prior = old.get(key);\n result.push(\n ...insertions[index]!,\n prior === undefined ? value : merge(prior, value),\n );\n }\n result.push(...insertions[next.length]!);\n return result;\n}\n\nfunction mergeMessages(\n previous: readonly ThreadMessage[],\n next: readonly ThreadMessage[],\n): readonly ThreadMessage[] {\n return mergeOrdered(\n previous.map((message) => [message, message.id] as const),\n next.map((message) => [message, message.id] as const),\n (old, fresh) =>\n old.role === \"assistant\" && fresh.role === \"assistant\"\n ? { ...fresh, content: mergeReplayContent(old.content, fresh.content) }\n : fresh,\n );\n}\n\nfunction mergeTool(\n previous: ToolCallMessagePart,\n next: ToolCallMessagePart,\n): ToolCallMessagePart {\n const result = preserveToolResult(previous, next);\n const approval = preserveToolApprovalDecision(previous, next);\n return {\n ...result,\n ...(approval ? { approval } : {}),\n ...(result.unstable_interactions === undefined &&\n previous.unstable_interactions !== undefined\n ? { unstable_interactions: previous.unstable_interactions }\n : {}),\n ...(previous.messages !== undefined || next.messages !== undefined\n ? {\n messages: mergeMessages(previous.messages ?? [], next.messages ?? []),\n }\n : {}),\n };\n}\n\nfunction partKey(part: Part): string {\n if (part.type === \"tool-call\") return `tool:${part.toolCallId}`;\n if (part.type === \"text\" || part.type === \"reasoning\") return part.type;\n if (\"id\" in part && typeof part.id === \"string\" && part.id)\n return `${part.type}:${part.id}`;\n if (part.type === \"data\") return `data:${part.name}`;\n return part.type;\n}\n\nfunction keyed(content: Content): [Part, string][] {\n const ordinals = new Map<string, number>();\n return content.map((part) => {\n const base = partKey(part);\n const ordinal = ordinals.get(base) ?? 0;\n ordinals.set(base, ordinal + 1);\n return [part, `${base}:${ordinal}`] as [Part, string];\n });\n}\n\nfunction identity(part: Part, key: string, scope: readonly string[]): string {\n return JSON.stringify(\n part.type === \"tool-call\" ? [\"tool\", part.toolCallId] : [...scope, key],\n );\n}\n\nfunction visitMessages(\n messages: readonly ThreadMessage[],\n scope: readonly string[],\n visit: (key: string) => void,\n): void {\n for (const message of messages) {\n const path = [...scope, \"message\", message.id];\n visit(JSON.stringify(path));\n if (message.role === \"assistant\")\n visitContent(message.content, path, visit);\n }\n}\n\nfunction visitContent(\n content: Content,\n scope: readonly string[],\n visit: (key: string) => void,\n): void {\n for (const [part, key] of keyed(content)) {\n visit(identity(part, key, scope));\n if (part.type === \"tool-call\" && part.messages)\n visitMessages(part.messages, [\"tool\", part.toolCallId], visit);\n }\n}\n\nfunction pruneMessages(\n messages: readonly ThreadMessage[],\n scope: readonly string[],\n present: ReadonlySet<string>,\n owned: ReadonlySet<string>,\n): { messages: readonly ThreadMessage[]; hasCurrent: boolean } {\n let hasCurrent = false;\n const kept = messages.flatMap((message) => {\n const path = [...scope, \"message\", message.id];\n const key = JSON.stringify(path);\n const nested =\n message.role === \"assistant\"\n ? pruneContent(message.content, path, present, owned)\n : undefined;\n const current = present.has(key) || (nested?.hasCurrent ?? false);\n if (owned.has(key) && !current) return [];\n hasCurrent ||= current;\n return [\n nested && message.role === \"assistant\"\n ? { ...message, content: nested.content }\n : message,\n ];\n });\n return { messages: kept, hasCurrent };\n}\n\nfunction pruneContent(\n content: Content,\n scope: readonly string[],\n present: ReadonlySet<string>,\n owned: ReadonlySet<string>,\n): { content: Content; hasCurrent: boolean } {\n let hasCurrent = false;\n const kept = keyed(content).flatMap(([part, localKey]) => {\n const key = identity(part, localKey, scope);\n const nested =\n part.type === \"tool-call\" && part.messages\n ? pruneMessages(\n part.messages,\n [\"tool\", part.toolCallId],\n present,\n owned,\n )\n : undefined;\n const current = present.has(key) || (nested?.hasCurrent ?? false);\n if (owned.has(key) && !current) return [];\n hasCurrent ||= current;\n return [nested ? { ...part, messages: nested.messages } : part];\n });\n return { content: kept, hasCurrent };\n}\n\nexport function createReplayContentMerger(): (\n previous: Content,\n next: Content,\n) => Content {\n // Remember stream-owned identities, never a second copy of tool payloads.\n const owned = new Set<string>();\n return (previous, next) => {\n const present = new Set<string>();\n visitContent(next, [], (key) => present.add(key));\n for (const key of present) owned.add(key);\n return pruneContent(mergeReplayContent(previous, next), [], present, owned)\n .content;\n };\n}\n\nfunction nestedToolIds(content: Content): Set<string> {\n const nestedIds = new Set<string>();\n for (const part of content) {\n if (part.type !== \"tool-call\") continue;\n for (const message of part.messages ?? []) {\n if (message.role !== \"assistant\") continue;\n for (const child of iterateToolCallParts(message.content)) {\n nestedIds.add(child.toolCallId);\n }\n }\n }\n return nestedIds;\n}\n\nfunction mergeReplayContent(previous: Content, next: Content): Content {\n const nestedIds = nestedToolIds(previous);\n const incomingNestedIds = nestedToolIds(next);\n const movingRoots = new Map(\n previous.flatMap((part) =>\n part.type === \"tool-call\" && incomingNestedIds.has(part.toolCallId)\n ? [[part.toolCallId, part] as const]\n : [],\n ),\n );\n const flattened = new Map<string, ToolCallMessagePart>();\n for (const part of next) {\n if (part.type === \"tool-call\" && nestedIds.has(part.toolCallId)) {\n flattened.set(part.toolCallId, part);\n }\n }\n const prior = (\n flattened.size\n ? mapToolCallPartsDeep(previous, (part) => {\n const fresh = flattened.get(part.toolCallId);\n return fresh ? mergeTool(part, fresh) : part;\n }).content\n : previous\n ).filter(\n (part) => part.type !== \"tool-call\" || !movingRoots.has(part.toolCallId),\n );\n let incoming = next.filter(\n (part) => part.type !== \"tool-call\" || !flattened.has(part.toolCallId),\n );\n if (movingRoots.size) {\n incoming = [\n ...mapToolCallPartsDeep(incoming, (part) => {\n const prior = movingRoots.get(part.toolCallId);\n return prior ? mergeTool(prior, part) : part;\n }).content,\n ];\n }\n return mergeOrdered(keyed(prior), keyed(incoming), (old, fresh) => {\n if (old.type === \"tool-call\" && fresh.type === \"tool-call\")\n return mergeTool(old, fresh);\n if (\n (old.type === \"text\" || old.type === \"reasoning\") &&\n (fresh.type === \"text\" || fresh.type === \"reasoning\") &&\n old.text.startsWith(fresh.text) &&\n old.text.length > fresh.text.length\n ) {\n return { ...fresh, text: old.text };\n }\n return fresh;\n });\n}\n"],"mappings":";;;AAeA,SAAgB,sBACd,QAC6B;CAC7B,MAAM,oCAAoB,IAAI,IAAoB;CAClD,KAAK,MAAM,SAAS,QAClB,KAAK,MAAM,QAAQ,qBAAqB,MAAM,OAAO,GACnD,IAAI,CAAC,kBAAkB,IAAI,KAAK,UAAU,GACxC,kBAAkB,IAAI,KAAK,YAAY,MAAM,EAAE;CAGrD,OAAO;AACT;AAEA,SAAgB,uBACd,QACA,SACA,mBACqB;CACrB,MAAM,oBAAoB,sBAAsB,MAAM;CACtD,MAAM,0BAAU,IAAI,IAAoB,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC;CACjE,KAAK,MAAM,QAAQ,SAAS;EAC1B,MAAM,UACJ,KAAK,SAAS,cACT,kBAAkB,IAAI,KAAK,UAAU,KAAK,oBAC3C;EACN,MAAM,QAAQ,QAAQ,IAAI,OAAO,KAAK,CAAC;EACvC,MAAM,KAAK,IAAI;EACf,QAAQ,IAAI,SAAS,KAAK;CAC5B;CACA,OAAO;AACT;AAEA,SAAgB,mBACd,UACA,MACqB;CACrB,IAAI,SAAS,WAAW,KAAA,KAAa,KAAK,WAAW,KAAA,GAAW,OAAO;CACvE,OAAO;EACL,GAAG;EACH,QAAQ,SAAS;EACjB,GAAI,SAAS,aAAa,KAAA,IAAY,EAAE,UAAU,SAAS,SAAS,IAAI,CAAC;EACzE,GAAI,SAAS,YAAY,KAAA,IAAY,EAAE,SAAS,SAAS,QAAQ,IAAI,CAAC;EACtE,GAAI,SAAS,iBAAiB,KAAA,IAC1B,EAAE,cAAc,SAAS,aAAa,IACtC,CAAC;CACP;AACF;AAEA,SAAS,aACP,UACA,MACA,OACK;CACL,MAAM,MAAM,IAAI,IAAI,SAAS,KAAK,CAAC,OAAO,SAAS,CAAC,KAAK,KAAK,CAAU,CAA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K,UAAU,CACvE;CACA,IAAI,YAAY,MACd,WAAW,CACT,GAAG,qBAAqB,WAAW,SAAS;EAC1C,MAAM,QAAQ,YAAY,IAAI,KAAK,UAAU;EAC7C,OAAO,QAAQ,UAAU,OAAO,IAAI,IAAI;CAC1C,CAAC,CAAC,CAAC,OACL;CAEF,OAAO,aAAa,MAAM,KAAK,GAAG,MAAM,QAAQ,IAAI,KAAK,UAAU;EACjE,IAAI,IAAI,SAAS,eAAe,MAAM,SAAS,aAC7C,OAAO,UAAU,KAAK,KAAK;EAC7B,KACG,IAAI,SAAS,UAAU,IAAI,SAAS,iBACpC,MAAM,SAAS,UAAU,MAAM,SAAS,gBACzC,IAAI,KAAK,WAAW,MAAM,IAAI,KAC9B,IAAI,KAAK,SAAS,MAAM,KAAK,QAE7B,OAAO;GAAE,GAAG;GAAO,MAAM,IAAI;EAAK;EAEpC,OAAO;CACT,CAAC;AACH"}
|
|
@@ -5,7 +5,7 @@ import { projectAgUiToolApprovals } from "./tool-approval.js";
|
|
|
5
5
|
import { isMcpAppUri } from "@assistant-ui/core";
|
|
6
6
|
import jsonpatch from "fast-json-patch";
|
|
7
7
|
import { applyA2uiOperations, surfaceToPresentToolCall } from "@assistant-ui/generative-ui/a2ui";
|
|
8
|
-
|
|
8
|
+
// src/runtime/adapter/run-aggregator.ts
|
|
9
9
|
const ROOT_SCOPE = "";
|
|
10
10
|
const MAX_SUBAGENT_DEPTH = 16;
|
|
11
11
|
const createJSONContainerScanner = () => ({
|
|
@@ -1032,7 +1032,6 @@ function tryParseJSON(value) {
|
|
|
1032
1032
|
return value;
|
|
1033
1033
|
}
|
|
1034
1034
|
}
|
|
1035
|
-
//#endregion
|
|
1036
1035
|
export { RunAggregator, isPlainObject, tryParseJSON };
|
|
1037
1036
|
|
|
1038
1037
|
//# sourceMappingURL=run-aggregator.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { parseAgUiEvent } from "../event-parser.js";
|
|
3
|
-
|
|
3
|
+
// src/runtime/adapter/subscriber.ts
|
|
4
4
|
const isAbortError = (error) => {
|
|
5
5
|
if (error.name === "AbortError") return true;
|
|
6
6
|
const message = typeof error.message === "string" ? error.message : "";
|
|
@@ -84,7 +84,6 @@ const createAgUiSubscriber = (options) => {
|
|
|
84
84
|
}
|
|
85
85
|
};
|
|
86
86
|
};
|
|
87
|
-
//#endregion
|
|
88
87
|
export { createAgUiSubscriber };
|
|
89
88
|
|
|
90
89
|
//# sourceMappingURL=subscriber.js.map
|
|
@@ -19,6 +19,8 @@ type ToolApproval = NonNullable<ToolCallMessagePart["approval"]>;
|
|
|
19
19
|
* message renders nowhere leaves the batch bespoke.
|
|
20
20
|
*/
|
|
21
21
|
export declare const projectAgUiToolApprovals: (interrupts: readonly AgUiInterrupt[] | undefined, boundToolCallIds?: ReadonlySet<string>) => ReadonlyMap<string, ToolApproval>;
|
|
22
|
+
/** A recorded decision authorizes one exact call and gate, not a reused id. */
|
|
23
|
+
export declare const preserveToolApprovalDecision: (previous: ToolCallMessagePart | undefined, next: ToolCallMessagePart) => ToolApproval | undefined;
|
|
22
24
|
/**
|
|
23
25
|
* Records a decision on the gated tool call. The decision is held on the part
|
|
24
26
|
* until every gate in the batch is answered, because AG-UI resumes a run with
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-approval.d.ts","sourceRoot":"","sources":["../../../src/runtime/adapter/tool-approval.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,4BAA4B,EAC5B,0BAA0B,EAC1B,mBAAmB,EACpB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,oBAAiB;AAM/D,KAAK,YAAY,GAAG,WAAW,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC,CAAC;AA0KjE;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,wBAAwB,GACnC,YAAY,SAAS,aAAa,EAAE,GAAG,SAAS,EAChD,mB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eAAe,EAAE,GAAG,IAkCtB,CAAC;AA0CF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,wBAAwB,GACnC,SAAS,SAAS,0BAA0B,EAAE,EAC9C,QAAQ,SAAS,eAAe,EAAE,KACjC,SAAS,0BAA0B,EAarC,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readRawResponseSchema, withoutRawResponseSchema } from "../interrupt-internals.js";
|
|
2
2
|
import { iterateToolCallParts, mapToolCallPartsDeep } from "@assistant-ui/core/internal";
|
|
3
3
|
import { buildResumeArray } from "@ag-ui/client";
|
|
4
|
-
|
|
4
|
+
// src/runtime/adapter/tool-approval.ts
|
|
5
5
|
const EMPTY_APPROVALS = /* @__PURE__ */ new Map();
|
|
6
6
|
const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7
7
|
const isString = (value) => typeof value === "string";
|
|
@@ -136,6 +136,23 @@ const projectAgUiToolApprovals = (interrupts, boundToolCallIds) => {
|
|
|
136
136
|
...interrupt.message !== void 0 && { prompt: interrupt.message }
|
|
137
137
|
}]));
|
|
138
138
|
};
|
|
139
|
+
/** A recorded decision authorizes one exact call and gate, not a reused id. */
|
|
140
|
+
const preserveToolApprovalDecision = (previous, next) => {
|
|
141
|
+
const prior = previous?.approval;
|
|
142
|
+
let approval = next.approval;
|
|
143
|
+
if (!approval && prior) {
|
|
144
|
+
const { approved: _approved, reason: _reason, resolution: _resolution, ...pending } = prior;
|
|
145
|
+
approval = pending;
|
|
146
|
+
}
|
|
147
|
+
if (!approval) return void 0;
|
|
148
|
+
if (!previous || prior?.id !== approval.id || previous.toolCallId !== next.toolCallId || previous.toolName !== next.toolName || (previous.argsText || "{}") !== (next.argsText || "{}")) return approval;
|
|
149
|
+
return {
|
|
150
|
+
...approval,
|
|
151
|
+
...prior.approved !== void 0 ? { approved: prior.approved } : {},
|
|
152
|
+
...prior.reason !== void 0 ? { reason: prior.reason } : {},
|
|
153
|
+
...prior.resolution !== void 0 ? { resolution: prior.resolution } : {}
|
|
154
|
+
};
|
|
155
|
+
};
|
|
139
156
|
/**
|
|
140
157
|
* Records a decision on the gated tool call. The decision is held on the part
|
|
141
158
|
* until every gate in the batch is answered, because AG-UI resumes a run with
|
|
@@ -167,12 +184,13 @@ const withToolApprovalDecision = (content, { approvalId, approved, reason }) =>
|
|
|
167
184
|
* drop the denial reason on the wire.
|
|
168
185
|
*/
|
|
169
186
|
const buildToolApprovalResume = (content, interrupts) => {
|
|
170
|
-
const
|
|
187
|
+
const calls = Array.from(iterateToolCallParts(content));
|
|
188
|
+
const gates = projectAgUiToolApprovals(interrupts, new Set(calls.map((part) => part.toolCallId)));
|
|
171
189
|
const responses = /* @__PURE__ */ new Map();
|
|
172
|
-
for (const part of
|
|
190
|
+
for (const part of calls) {
|
|
173
191
|
const approval = part.approval;
|
|
174
192
|
if (!approval || approval.approved === void 0) continue;
|
|
175
|
-
if (
|
|
193
|
+
if (gates.get(part.toolCallId)?.id !== approval.id) continue;
|
|
176
194
|
responses.set(approval.id, {
|
|
177
195
|
status: "resolved",
|
|
178
196
|
payload: {
|
|
@@ -237,7 +255,6 @@ const withSettledToolApprovals = (content, resume) => {
|
|
|
237
255
|
});
|
|
238
256
|
return changed ? next : content;
|
|
239
257
|
};
|
|
240
|
-
|
|
241
|
-
export { buildToolApprovalResume, projectAgUiToolApprovals, withSettledToolApprovals, withToolApprovalDecision };
|
|
258
|
+
export { buildToolApprovalResume, preserveToolApprovalDecision, projectAgUiToolApprovals, withSettledToolApprovals, withToolApprovalDecision };
|
|
242
259
|
|
|
243
260
|
//# sourceMappingURL=tool-approval.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-approval.js","names":[],"sources":["../../../src/runtime/adapter/tool-approval.ts"],"sourcesContent":["import {\n iterateToolCallParts,\n mapToolCallPartsDeep,\n} from \"@assistant-ui/core/internal\";\nimport { buildResumeArray } from \"@ag-ui/client\";\nimport type {\n RespondToToolApprovalOptions,\n ThreadAssistantMessagePart,\n ToolCallMessagePart,\n} from \"@assistant-ui/core\";\nimport type { AgUiInterrupt, AgUiResumeEntry } from \"../types\";\nimport {\n readRawResponseSchema,\n withoutRawResponseSchema,\n} from \"../interrupt-internals\";\n\ntype ToolApproval = NonNullable<ToolCallMessagePart[\"approval\"]>;\n\nconst EMPTY_APPROVALS: ReadonlyMap<string, ToolApproval> = new Map();\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isString = (value: unknown) => typeof value === \"string\";\n\nconst JSON_SCHEMA_TYPES = new Set([\n \"null\",\n \"boolean\",\n \"object\",\n \"array\",\n \"number\",\n \"integer\",\n \"string\",\n]);\n\nconst isUniqueStrings = (value: unknown) =>\n Array.isArray(value) &&\n value.every(isString) &&\n new Set(value).size === value.length;\n\nconst isSchemaType = (type: unknown) =>\n (isString(type) && JSON_SCHEMA_TYPES.has(type as string)) ||\n (Array.isArray(type) &&\n type.length > 0 &&\n isUniqueStrings(type) &&\n type.every((entry) => JSON_SCHEMA_TYPES.has(entry as string)));\n\nconst acceptsType = (type: unknown, primitive: string) =>\n type === primitive ||\n (Array.isArray(type) && isSchemaType(type) && type.includes(primitive));\n\nconst acceptsObject = (type: unknown) => acceptsType(type, \"object\");\n\nconst SUB_SCHEMA_ANNOTATIONS = new Set([\n \"$schema\",\n \"$id\",\n \"title\",\n \"description\",\n]);\n\n/**\n * A field schema accepts a value of `primitive` only where nothing in it can\n * narrow past the type: an annotation carries no constraint, and an absent\n * `type` constrains nothing. Any other keyword — `const`, `enum`, `anyOf`,\n * `format` — can reject the value this seam sends, so it is not interpreted.\n */\nconst acceptsOnly = (schema: unknown, primitive: string) =>\n isPlainObject(schema) &&\n Object.entries(schema).every(([keyword, value]) =>\n keyword === \"type\"\n ? acceptsType(value, primitive)\n : SUB_SCHEMA_ANNOTATIONS.has(keyword) && isString(value),\n );\n\n/**\n * Keywords of a sub-schema whose value shape a validator reads, each paired\n * with that shape: the same shapes the top-level schema is held to, plus\n * `properties` and `items`, which carry schemas, so a malformed one nested\n * under them is as uncompilable as a malformed one at the top. A keyword this\n * seam cannot judge is left alone: unlike the top-level schema, a field the\n * seam never sends needs only to be compilable, not permissive.\n */\nconst SUB_SCHEMA_SHAPES = new Map<string, (value: unknown) => boolean>([\n [\"type\", isSchemaType],\n [\"required\", isUniqueStrings],\n ...[...SUB_SCHEMA_ANNOTATIONS].map(\n (annotation) =>\n [annotation, isString] as [string, (value: unknown) => boolean],\n ),\n [\n \"properties\",\n (value) =>\n isPlainObject(value) &&\n Object.values(value).every((schema) => isWellFormedSubSchema(schema)),\n ],\n [\"items\", (value) => isWellFormedSubSchema(value)],\n]);\n\n/**\n * A schema the server cannot compile fails the run whatever payload follows, so\n * a field this seam never sends is still checked for the shape a validator\n * reads it as. A boolean is a schema in its own right.\n */\nconst isWellFormedSubSchema = (schema: unknown): boolean =>\n typeof schema === \"boolean\" ||\n (isPlainObject(schema) &&\n Object.entries(schema).every(([keyword, value]) => {\n const holds = SUB_SCHEMA_SHAPES.get(keyword);\n return holds === undefined || holds(value);\n }));\n\n/**\n * AG-UI's own tool-approval schema declares the fields it expects under\n * `properties`, so a declaration is read where it cannot reject what the seam\n * sends: `approved` must accept a boolean and `reason` a string. A field the\n * seam never sends is unconstrained by `required` (which admits only\n * `approved`), so only its well-formedness as a sub-schema is checked — the\n * `editedArgs` of the spec's approve-with-edits shape is such a field.\n */\nconst acceptsSeamProperties = (properties: unknown) =>\n isPlainObject(properties) &&\n Object.entries(properties).every(([field, schema]) => {\n if (field === \"approved\") return acceptsOnly(schema, \"boolean\");\n if (field === \"reason\") return acceptsOnly(schema, \"string\");\n return isWellFormedSubSchema(schema);\n });\n\nconst acceptsSeamPayload = (required: unknown) =>\n Array.isArray(required) &&\n required.every((field) => field === \"approved\") &&\n new Set(required).size === required.length;\n\n/**\n * Keywords that cannot reject a payload this seam emits, each paired with the\n * check that its value is the well-formed shape the keyword is read as. A\n * keyword whose value a validator would reject as an invalid schema is not\n * decided here, because a server that compiles the schema fails the run. An\n * unlisted keyword — `additionalProperties`, `allOf`, `$ref` — makes the gate\n * bespoke rather than being interpreted. The map is keyed by\n * `Map` rather than by object property, because a schema key of `constructor`\n * or `toString` would otherwise read an `Object.prototype` member as its\n * validator and `__proto__` would read the prototype itself.\n */\nconst SEAM_SAFE_KEYWORDS = new Map<string, (value: unknown) => boolean>([\n [\"$schema\", isString],\n [\"$id\", isString],\n [\"title\", isString],\n [\"description\", isString],\n [\"type\", acceptsObject],\n [\"required\", acceptsSeamPayload],\n [\"properties\", acceptsSeamProperties],\n]);\n\n/**\n * The seam sends `{ approved }` and may add `reason`, so it may answer a\n * `responseSchema` only where acceptance of those exact payloads is established\n * by construction. AG-UI answers a resume payload its schema rejects with\n * `RunError`, and the host can always build the exact payload through the\n * bespoke interrupt hooks, so an undecidable schema is left to them. Only an\n * absent schema and a plain object of well-formed allowed keywords establish\n * that: a boolean schema (`false` rejects every payload), a malformed one, and\n * a keyword whose value is not the shape it interprets are all left bespoke.\n */\nconst isSeamAnswerable = (schema: unknown) => {\n if (schema === undefined) return true;\n if (!isPlainObject(schema)) return false;\n return Object.entries(schema).every(([keyword, value]) => {\n const accepts = SEAM_SAFE_KEYWORDS.get(keyword);\n return accepts !== undefined && accepts(value);\n });\n};\n\nconst isGate = (\n interrupt: AgUiInterrupt,\n): interrupt is AgUiInterrupt & { toolCallId: string } =>\n interrupt.reason === \"tool_call\" &&\n !!interrupt.id &&\n !!interrupt.toolCallId &&\n // A restored interrupt is untyped, so `responseSchema` may hold any persisted\n // shape; a non-object schema received live arrives on the internal carrier.\n readRawResponseSchema(interrupt) === undefined &&\n isSeamAnswerable(interrupt.responseSchema);\n\nconst isPending = (approval: ToolCallMessagePart[\"approval\"]) =>\n !!approval && approval.approved === undefined && !approval.resolution;\n\n/**\n * AG-UI binds a decision to a tool call with `reason: \"tool_call\"`;\n * `confirmation` is a free-standing yes/no and `input_required` wants structured\n * input, so both stay on the bespoke interrupt hooks, as does a `tool_call`\n * whose `responseSchema` asks for more than this seam can send. A batch mixing a\n * gate with any other interrupt projects nothing: AG-UI resumes with one\n * response per open interrupt, so a half-owned batch cannot be completed from\n * either side alone.\n *\n * The same rule covers binding. A gate naming a tool call the message does not\n * render can never be decided through this seam, so the batch it belongs to\n * could never be completed either: the decisions taken on its visible siblings\n * would sit on the message while the run waited for a response that no click\n * can produce. `boundToolCallIds` spans every call the run produced — root or\n * nested on ToolCallMessagePart.messages — so only a gate naming a call the\n * message renders nowhere leaves the batch bespoke.\n */\nexport const projectAgUiToolApprovals = (\n interrupts: readonly AgUiInterrupt[] | undefined,\n boundToolCallIds?: ReadonlySet<string>,\n): ReadonlyMap<string, ToolApproval> => {\n if (!interrupts?.length || !interrupts.every(isGate)) return EMPTY_APPROVALS;\n if (\n boundToolCallIds &&\n !interrupts.every((interrupt) => boundToolCallIds.has(interrupt.toolCallId))\n ) {\n return EMPTY_APPROVALS;\n }\n // Two gates naming one tool call would collapse into a single approval, so\n // the batch could never be completed: the surviving gate takes one decision\n // while the resume array still waits on the id that no part carries.\n const toolCallIds = interrupts.map((interrupt) => interrupt.toolCallId);\n if (new Set(toolCallIds).size !== toolCallIds.length) return EMPTY_APPROVALS;\n return new Map(\n interrupts.map((interrupt) => [\n interrupt.toolCallId,\n {\n id: interrupt.id,\n ...(interrupt.message !== undefined && { prompt: interrupt.message }),\n },\n ]),\n );\n};\n\n/**\n * Records a decision on the gated tool call. The decision is held on the part\n * until every gate in the batch is answered, because AG-UI resumes a run with\n * one response per open interrupt rather than one response per gate. A chosen\n * `optionId` is not recorded: the projection exposes an approval without\n * options, and core rejects an `optionId` absent from them, so no option can\n * reach this seam.\n */\nexport const withToolApprovalDecision = (\n content: readonly ThreadAssistantMessagePart[],\n { approvalId, approved, reason }: RespondToToolApprovalOptions,\n): readonly ThreadAssistantMessagePart[] => {\n const { content: next, changed } = mapToolCallPartsDeep(content, (part) => {\n const approval = part.approval;\n if (approval?.id !== approvalId || !isPending(approval)) return part;\n return {\n ...part,\n approval: {\n ...approval,\n approved,\n ...(reason !== undefined && { reason }),\n },\n };\n });\n return changed ? next : content;\n};\n\n/**\n * Maps the recorded decisions onto AG-UI resume entries, or `null` while the\n * batch is incomplete. A denial is a resolved response carrying\n * `approved: false`, not a cancellation: `cancelled` means the user abandoned\n * the interrupt without meaningful input and carries no payload, which would\n * drop the denial reason on the wire.\n */\nexport const buildToolApprovalResume = (\n content: readonly ThreadAssistantMessagePart[],\n interrupts: readonly AgUiInterrupt[],\n): AgUiResumeEntry[] | null => {\n const open = new Set(interrupts.map((interrupt) => interrupt.id));\n // Decisions accumulate in a `Map` rather than in an object literal, because an\n // interrupt id of `__proto__` would otherwise write to the prototype chain\n // instead of recording a response, and `constructor` or `toString` would\n // report themselves as answered while undecided.\n const responses = new Map<string, { status: \"resolved\"; payload: unknown }>();\n for (const part of iterateToolCallParts(content)) {\n const approval = part.approval;\n if (!approval || approval.approved === undefined) continue;\n if (!open.has(approval.id)) continue;\n responses.set(approval.id, {\n status: \"resolved\",\n payload: {\n approved: approval.approved,\n ...(approval.reason !== undefined && { reason: approval.reason }),\n },\n });\n }\n if (interrupts.some((interrupt) => !responses.has(interrupt.id))) return null;\n // The schema is dropped rather than cast: AG-UI's own interrupt type cannot\n // express a boolean schema, and `buildResumeArray` reads only the ids.\n return buildResumeArray(\n interrupts.map((interrupt) => {\n const { responseSchema: _schema, ...rest } =\n withoutRawResponseSchema(interrupt);\n return rest;\n }),\n Object.fromEntries(responses),\n );\n};\n\nconst settle = (\n approval: ToolApproval,\n entry: AgUiResumeEntry,\n): ToolApproval | undefined => {\n // A decision this gate recorded locally but never sent is dropped rather than\n // displayed beside the settlement it contradicts: a submitted entry carries\n // the whole outcome, so no field of an earlier one may survive it.\n const {\n approved: _approved,\n reason: _reason,\n resolution: _resolution,\n ...rest\n } = approval;\n if (entry.status === \"cancelled\") {\n return { ...rest, resolution: \"cancelled\" };\n }\n const payload = entry.payload;\n if (\n typeof payload !== \"object\" ||\n payload === null ||\n typeof (payload as { approved?: unknown }).approved !== \"boolean\"\n ) {\n // The entry settles the gate with no decision. Nothing is fabricated, and a\n // decision recorded locally is dropped: the payload that went out carried\n // none, so displaying one would show what was never sent. The gate is still\n // marked terminal, because the interrupt it belonged to is closed and a\n // click on it afterwards would find nothing pending.\n return { ...rest, resolution: \"cancelled\" };\n }\n const { approved, reason } = payload as {\n approved: boolean;\n reason?: unknown;\n };\n return {\n ...rest,\n approved,\n ...(typeof reason === \"string\" && { reason }),\n };\n};\n\n/**\n * Settles every gate the submitted resume array names, so the displayed outcome\n * cannot contradict the wire. A decision recorded locally is not exempt: a gate\n * approved while the batch waited on its sibling is still cancelled when\n * `steerAway` submits a cancellation for it. A gate is shown as cancelled only\n * where its own entry is cancelled; a resolved entry supplies the decision it\n * carries, and one that carries none settles the gate with no decision rather\n * than fabricating one or keeping an unsent local decision beside it.\n *\n * A settlement always overrides an earlier one, in either direction. A resolved\n * settlement leaves no state a locally recorded decision does not also leave —\n * core's `resolution` covers only `cancelled` and `expired` — so honoring the\n * first settlement instead would mean treating an unsent local decision as\n * terminal, which is exactly what the cancellation case must override.\n */\nexport const withSettledToolApprovals = (\n content: readonly ThreadAssistantMessagePart[],\n resume: readonly AgUiResumeEntry[],\n): readonly ThreadAssistantMessagePart[] => {\n if (resume.length === 0) return content;\n const byId = new Map(resume.map((entry) => [entry.interruptId, entry]));\n const { content: next, changed } = mapToolCallPartsDeep(content, (part) => {\n const approval = part.approval;\n if (!approval) return part;\n const entry = byId.get(approval.id);\n if (!entry) return part;\n const settled = settle(approval, entry);\n if (!settled) return part;\n return { ...part, approval: settled };\n });\n return changed ? next : content;\n};\n"],"mappings":";;;;AAkBA,MAAM,kCAAqD,IAAI,IAAI;AAEnE,MAAM,iBAAiB,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,MAAM,YAAY,UAAmB,OAAO,UAAU;AAEtD,MAAM,oC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-approval.js","names":[],"sources":["../../../src/runtime/adapter/tool-approval.ts"],"sourcesContent":["import {\n iterateToolCallParts,\n mapToolCallPartsDeep,\n} from \"@assistant-ui/core/internal\";\nimport { buildResumeArray } from \"@ag-ui/client\";\nimport type {\n RespondToToolApprovalOptions,\n ThreadAssistantMessagePart,\n ToolCallMessagePart,\n} from \"@assistant-ui/core\";\nimport type { AgUiInterrupt, AgUiResumeEntry } from \"../types\";\nimport {\n readRawResponseSchema,\n withoutRawResponseSchema,\n} from \"../interrupt-internals\";\n\ntype ToolApproval = NonNullable<ToolCallMessagePart[\"approval\"]>;\n\nconst EMPTY_APPROVALS: ReadonlyMap<string, ToolApproval> = new Map();\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isString = (value: unknown) => typeof value === \"string\";\n\nconst JSON_SCHEMA_TYPES = new Set([\n \"null\",\n \"boolean\",\n \"object\",\n \"array\",\n \"number\",\n \"integer\",\n \"string\",\n]);\n\nconst isUniqueStrings = (value: unknown) =>\n Array.isArray(value) &&\n value.every(isString) &&\n new Set(value).size === value.length;\n\nconst isSchemaType = (type: unknown) =>\n (isString(type) && JSON_SCHEMA_TYPES.has(type as string)) ||\n (Array.isArray(type) &&\n type.length > 0 &&\n isUniqueStrings(type) &&\n type.every((entry) => JSON_SCHEMA_TYPES.has(entry as string)));\n\nconst acceptsType = (type: unknown, primitive: string) =>\n type === primitive ||\n (Array.isArray(type) && isSchemaType(type) && type.includes(primitive));\n\nconst acceptsObject = (type: unknown) => acceptsType(type, \"object\");\n\nconst SUB_SCHEMA_ANNOTATIONS = new Set([\n \"$schema\",\n \"$id\",\n \"title\",\n \"description\",\n]);\n\n/**\n * A field schema accepts a value of `primitive` only where nothing in it can\n * narrow past the type: an annotation carries no constraint, and an absent\n * `type` constrains nothing. Any other keyword — `const`, `enum`, `anyOf`,\n * `format` — can reject the value this seam sends, so it is not interpreted.\n */\nconst acceptsOnly = (schema: unknown, primitive: string) =>\n isPlainObject(schema) &&\n Object.entries(schema).every(([keyword, value]) =>\n keyword === \"type\"\n ? acceptsType(value, primitive)\n : SUB_SCHEMA_ANNOTATIONS.has(keyword) && isString(value),\n );\n\n/**\n * Keywords of a sub-schema whose value shape a validator reads, each paired\n * with that shape: the same shapes the top-level schema is held to, plus\n * `properties` and `items`, which carry schemas, so a malformed one nested\n * under them is as uncompilable as a malformed one at the top. A keyword this\n * seam cannot judge is left alone: unlike the top-level schema, a field the\n * seam never sends needs only to be compilable, not permissive.\n */\nconst SUB_SCHEMA_SHAPES = new Map<string, (value: unknown) => boolean>([\n [\"type\", isSchemaType],\n [\"required\", isUniqueStrings],\n ...[...SUB_SCHEMA_ANNOTATIONS].map(\n (annotation) =>\n [annotation, isString] as [string, (value: unknown) => boolean],\n ),\n [\n \"properties\",\n (value) =>\n isPlainObject(value) &&\n Object.values(value).every((schema) => isWellFormedSubSchema(schema)),\n ],\n [\"items\", (value) => isWellFormedSubSchema(value)],\n]);\n\n/**\n * A schema the server cannot compile fails the run whatever payload follows, so\n * a field this seam never sends is still checked for the shape a validator\n * reads it as. A boolean is a schema in its own right.\n */\nconst isWellFormedSubSchema = (schema: unknown): boolean =>\n typeof schema === \"boolean\" ||\n (isPlainObject(schema) &&\n Object.entries(schema).every(([keyword, value]) => {\n const holds = SUB_SCHEMA_SHAPES.get(keyword);\n return holds === undefined || holds(value);\n }));\n\n/**\n * AG-UI's own tool-approval schema declares the fields it expects under\n * `properties`, so a declaration is read where it cannot reject what the seam\n * sends: `approved` must accept a boolean and `reason` a string. A field the\n * seam never sends is unconstrained by `required` (which admits only\n * `approved`), so only its well-formedness as a sub-schema is checked — the\n * `editedArgs` of the spec's approve-with-edits shape is such a field.\n */\nconst acceptsSeamProperties = (properties: unknown) =>\n isPlainObject(properties) &&\n Object.entries(properties).every(([field, schema]) => {\n if (field === \"approved\") return acceptsOnly(schema, \"boolean\");\n if (field === \"reason\") return acceptsOnly(schema, \"string\");\n return isWellFormedSubSchema(schema);\n });\n\nconst acceptsSeamPayload = (required: unknown) =>\n Array.isArray(required) &&\n required.every((field) => field === \"approved\") &&\n new Set(required).size === required.length;\n\n/**\n * Keywords that cannot reject a payload this seam emits, each paired with the\n * check that its value is the well-formed shape the keyword is read as. A\n * keyword whose value a validator would reject as an invalid schema is not\n * decided here, because a server that compiles the schema fails the run. An\n * unlisted keyword — `additionalProperties`, `allOf`, `$ref` — makes the gate\n * bespoke rather than being interpreted. The map is keyed by\n * `Map` rather than by object property, because a schema key of `constructor`\n * or `toString` would otherwise read an `Object.prototype` member as its\n * validator and `__proto__` would read the prototype itself.\n */\nconst SEAM_SAFE_KEYWORDS = new Map<string, (value: unknown) => boolean>([\n [\"$schema\", isString],\n [\"$id\", isString],\n [\"title\", isString],\n [\"description\", isString],\n [\"type\", acceptsObject],\n [\"required\", acceptsSeamPayload],\n [\"properties\", acceptsSeamProperties],\n]);\n\n/**\n * The seam sends `{ approved }` and may add `reason`, so it may answer a\n * `responseSchema` only where acceptance of those exact payloads is established\n * by construction. AG-UI answers a resume payload its schema rejects with\n * `RunError`, and the host can always build the exact payload through the\n * bespoke interrupt hooks, so an undecidable schema is left to them. Only an\n * absent schema and a plain object of well-formed allowed keywords establish\n * that: a boolean schema (`false` rejects every payload), a malformed one, and\n * a keyword whose value is not the shape it interprets are all left bespoke.\n */\nconst isSeamAnswerable = (schema: unknown) => {\n if (schema === undefined) return true;\n if (!isPlainObject(schema)) return false;\n return Object.entries(schema).every(([keyword, value]) => {\n const accepts = SEAM_SAFE_KEYWORDS.get(keyword);\n return accepts !== undefined && accepts(value);\n });\n};\n\nconst isGate = (\n interrupt: AgUiInterrupt,\n): interrupt is AgUiInterrupt & { toolCallId: string } =>\n interrupt.reason === \"tool_call\" &&\n !!interrupt.id &&\n !!interrupt.toolCallId &&\n // A restored interrupt is untyped, so `responseSchema` may hold any persisted\n // shape; a non-object schema received live arrives on the internal carrier.\n readRawResponseSchema(interrupt) === undefined &&\n isSeamAnswerable(interrupt.responseSchema);\n\nconst isPending = (approval: ToolCallMessagePart[\"approval\"]) =>\n !!approval && approval.approved === undefined && !approval.resolution;\n\n/**\n * AG-UI binds a decision to a tool call with `reason: \"tool_call\"`;\n * `confirmation` is a free-standing yes/no and `input_required` wants structured\n * input, so both stay on the bespoke interrupt hooks, as does a `tool_call`\n * whose `responseSchema` asks for more than this seam can send. A batch mixing a\n * gate with any other interrupt projects nothing: AG-UI resumes with one\n * response per open interrupt, so a half-owned batch cannot be completed from\n * either side alone.\n *\n * The same rule covers binding. A gate naming a tool call the message does not\n * render can never be decided through this seam, so the batch it belongs to\n * could never be completed either: the decisions taken on its visible siblings\n * would sit on the message while the run waited for a response that no click\n * can produce. `boundToolCallIds` spans every call the run produced — root or\n * nested on ToolCallMessagePart.messages — so only a gate naming a call the\n * message renders nowhere leaves the batch bespoke.\n */\nexport const projectAgUiToolApprovals = (\n interrupts: readonly AgUiInterrupt[] | undefined,\n boundToolCallIds?: ReadonlySet<string>,\n): ReadonlyMap<string, ToolApproval> => {\n if (!interrupts?.length || !interrupts.every(isGate)) return EMPTY_APPROVALS;\n if (\n boundToolCallIds &&\n !interrupts.every((interrupt) => boundToolCallIds.has(interrupt.toolCallId))\n ) {\n return EMPTY_APPROVALS;\n }\n // Two gates naming one tool call would collapse into a single approval, so\n // the batch could never be completed: the surviving gate takes one decision\n // while the resume array still waits on the id that no part carries.\n const toolCallIds = interrupts.map((interrupt) => interrupt.toolCallId);\n if (new Set(toolCallIds).size !== toolCallIds.length) return EMPTY_APPROVALS;\n return new Map(\n interrupts.map((interrupt) => [\n interrupt.toolCallId,\n {\n id: interrupt.id,\n ...(interrupt.message !== undefined && { prompt: interrupt.message }),\n },\n ]),\n );\n};\n\n/** A recorded decision authorizes one exact call and gate, not a reused id. */\nexport const preserveToolApprovalDecision = (\n previous: ToolCallMessagePart | undefined,\n next: ToolCallMessagePart,\n): ToolApproval | undefined => {\n const prior = previous?.approval;\n let approval = next.approval;\n if (!approval && prior) {\n const {\n approved: _approved,\n reason: _reason,\n resolution: _resolution,\n ...pending\n } = prior;\n approval = pending;\n }\n if (!approval) return undefined;\n // AG-UI may omit argument events for a no-argument call; both forms mean {}.\n if (\n !previous ||\n prior?.id !== approval.id ||\n previous.toolCallId !== next.toolCallId ||\n previous.toolName !== next.toolName ||\n (previous.argsText || \"{}\") !== (next.argsText || \"{}\")\n )\n return approval;\n return {\n ...approval,\n ...(prior.approved !== undefined ? { approved: prior.approved } : {}),\n ...(prior.reason !== undefined ? { reason: prior.reason } : {}),\n ...(prior.resolution !== undefined ? { resolution: prior.resolution } : {}),\n };\n};\n\n/**\n * Records a decision on the gated tool call. The decision is held on the part\n * until every gate in the batch is answered, because AG-UI resumes a run with\n * one response per open interrupt rather than one response per gate. A chosen\n * `optionId` is not recorded: the projection exposes an approval without\n * options, and core rejects an `optionId` absent from them, so no option can\n * reach this seam.\n */\nexport const withToolApprovalDecision = (\n content: readonly ThreadAssistantMessagePart[],\n { approvalId, approved, reason }: RespondToToolApprovalOptions,\n): readonly ThreadAssistantMessagePart[] => {\n const { content: next, changed } = mapToolCallPartsDeep(content, (part) => {\n const approval = part.approval;\n if (approval?.id !== approvalId || !isPending(approval)) return part;\n return {\n ...part,\n approval: {\n ...approval,\n approved,\n ...(reason !== undefined && { reason }),\n },\n };\n });\n return changed ? next : content;\n};\n\n/**\n * Maps the recorded decisions onto AG-UI resume entries, or `null` while the\n * batch is incomplete. A denial is a resolved response carrying\n * `approved: false`, not a cancellation: `cancelled` means the user abandoned\n * the interrupt without meaningful input and carries no payload, which would\n * drop the denial reason on the wire.\n */\nexport const buildToolApprovalResume = (\n content: readonly ThreadAssistantMessagePart[],\n interrupts: readonly AgUiInterrupt[],\n): AgUiResumeEntry[] | null => {\n const calls = Array.from(iterateToolCallParts(content));\n const gates = projectAgUiToolApprovals(\n interrupts,\n new Set(calls.map((part) => part.toolCallId)),\n );\n // Decisions accumulate in a `Map` rather than in an object literal, because an\n // interrupt id of `__proto__` would otherwise write to the prototype chain\n // instead of recording a response, and `constructor` or `toString` would\n // report themselves as answered while undecided.\n const responses = new Map<string, { status: \"resolved\"; payload: unknown }>();\n for (const part of calls) {\n const approval = part.approval;\n if (!approval || approval.approved === undefined) continue;\n if (gates.get(part.toolCallId)?.id !== approval.id) continue;\n responses.set(approval.id, {\n status: \"resolved\",\n payload: {\n approved: approval.approved,\n ...(approval.reason !== undefined && { reason: approval.reason }),\n },\n });\n }\n if (interrupts.some((interrupt) => !responses.has(interrupt.id))) return null;\n // The schema is dropped rather than cast: AG-UI's own interrupt type cannot\n // express a boolean schema, and `buildResumeArray` reads only the ids.\n return buildResumeArray(\n interrupts.map((interrupt) => {\n const { responseSchema: _schema, ...rest } =\n withoutRawResponseSchema(interrupt);\n return rest;\n }),\n Object.fromEntries(responses),\n );\n};\n\nconst settle = (\n approval: ToolApproval,\n entry: AgUiResumeEntry,\n): ToolApproval | undefined => {\n // A decision this gate recorded locally but never sent is dropped rather than\n // displayed beside the settlement it contradicts: a submitted entry carries\n // the whole outcome, so no field of an earlier one may survive it.\n const {\n approved: _approved,\n reason: _reason,\n resolution: _resolution,\n ...rest\n } = approval;\n if (entry.status === \"cancelled\") {\n return { ...rest, resolution: \"cancelled\" };\n }\n const payload = entry.payload;\n if (\n typeof payload !== \"object\" ||\n payload === null ||\n typeof (payload as { approved?: unknown }).approved !== \"boolean\"\n ) {\n // The entry settles the gate with no decision. Nothing is fabricated, and a\n // decision recorded locally is dropped: the payload that went out carried\n // none, so displaying one would show what was never sent. The gate is still\n // marked terminal, because the interrupt it belonged to is closed and a\n // click on it afterwards would find nothing pending.\n return { ...rest, resolution: \"cancelled\" };\n }\n const { approved, reason } = payload as {\n approved: boolean;\n reason?: unknown;\n };\n return {\n ...rest,\n approved,\n ...(typeof reason === \"string\" && { reason }),\n };\n};\n\n/**\n * Settles every gate the submitted resume array names, so the displayed outcome\n * cannot contradict the wire. A decision recorded locally is not exempt: a gate\n * approved while the batch waited on its sibling is still cancelled when\n * `steerAway` submits a cancellation for it. A gate is shown as cancelled only\n * where its own entry is cancelled; a resolved entry supplies the decision it\n * carries, and one that carries none settles the gate with no decision rather\n * than fabricating one or keeping an unsent local decision beside it.\n *\n * A settlement always overrides an earlier one, in either direction. A resolved\n * settlement leaves no state a locally recorded decision does not also leave —\n * core's `resolution` covers only `cancelled` and `expired` — so honoring the\n * first settlement instead would mean treating an unsent local decision as\n * terminal, which is exactly what the cancellation case must override.\n */\nexport const withSettledToolApprovals = (\n content: readonly ThreadAssistantMessagePart[],\n resume: readonly AgUiResumeEntry[],\n): readonly ThreadAssistantMessagePart[] => {\n if (resume.length === 0) return content;\n const byId = new Map(resume.map((entry) => [entry.interruptId, entry]));\n const { content: next, changed } = mapToolCallPartsDeep(content, (part) => {\n const approval = part.approval;\n if (!approval) return part;\n const entry = byId.get(approval.id);\n if (!entry) return part;\n const settled = settle(approval, entry);\n if (!settled) return part;\n return { ...part, approval: settled };\n });\n return changed ? next : content;\n};\n"],"mappings":";;;;AAkBA,MAAM,kCAAqD,IAAI,IAAI;AAEnE,MAAM,iBAAiB,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,MAAM,YAAY,UAAmB,OAAO,UAAU;AAEtD,MAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,mBAAmB,UACvB,MAAM,QAAQ,KAAK,KACnB,MAAM,MAAM,QAAQ,KACpB,IAAI,IAAI,KAAK,CAAC,CAAC,SAAS,MAAM;AAEhC,MAAM,gBAAgB,SACnB,SAAS,IAAI,KAAK,kBAAkB,IAAI,IAAc,KACtD,MAAM,QAAQ,IAAI,KACjB,KAAK,SAAS,KACd,gBAAgB,IAAI,KACpB,KAAK,OAAO,UAAU,kBAAkB,IAAI,KAAe,CAAC;AAEhE,MAAM,eAAe,MAAe,cAClC,SAAS,aACR,MAAM,QAAQ,IAAI,KAAK,aAAa,IAAI,KAAK,KAAK,SAA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,KAAK,IAAI,SAAS,EAAE;EAClC,IAAI,CAAC,OAAO,OAAO;EACnB,MAAM,UAAU,OAAO,UAAU,KAAK;EACtC,IAAI,CAAC,SAAS,OAAO;EACrB,OAAO;GAAE,GAAG;GAAM,UAAU;EAAQ;CACtC,CAAC;CACD,OAAO,UAAU,OAAO;AAC1B"}
|
|
@@ -9,7 +9,7 @@ export type AgUiThreadState = {
|
|
|
9
9
|
lastRunConfig: RunConfig | undefined;
|
|
10
10
|
pendingResume: {
|
|
11
11
|
owner: AbortController;
|
|
12
|
-
|
|
12
|
+
messageIds: readonly string[];
|
|
13
13
|
} | null;
|
|
14
14
|
pendingA2uiResumeOwner: AbortController | null;
|
|
15
15
|
pendingA2uiAction: Record<string, unknown> | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agUiThreadState.d.ts","sourceRoot":"","sources":["../../src/runtime/agUiThreadState.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAEhE,MAAM,MAAM,eAAe,GAAG;IAC5B,SAAS,EAAE,OAAO,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;IACnB,aAAa,EAAE,OAAO,CAAC;IACvB,yBAAyB,EAAE,MAAM,CAAC;IAClC,aAAa,EAAE,iBAAiB,GAAG,SAAS,CAAC;IAC7C,aAAa,EAAE,SAAS,GAAG,SAAS,CAAC;IACrC,aAAa,EAAE;
|
|
1
|
+
{"version":3,"file":"agUiThreadState.d.ts","sourceRoot":"","sources":["../../src/runtime/agUiThreadState.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAEhE,MAAM,MAAM,eAAe,GAAG;IAC5B,SAAS,EAAE,OAAO,CAAC;I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C,MAAM,EAAE,OAAO,CAAC,CAAA;CAAE,GAC/D;IAAE,IAAI,EAAE,mBAAmB,CAAA;CAAE,GAC7B;IAAE,IAAI,EAAE,0BAA0B,CAAA;CAAE,GACpC;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,CAAC;AAE5B,eAAO,MAAM,qBAAqB,QAAO,eAUvC,CAAC;AAEH,eAAO,MAAM,qBAAqB,GAChC,OAAO,eAAe,EACtB,QAAQ,gBAAgB,KACvB,eAsFF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/runtime/agUiThreadState.ts
|
|
2
2
|
const createAgUiThreadState = () => ({
|
|
3
3
|
isRunning: false,
|
|
4
4
|
isLoading: false,
|
|
@@ -48,11 +48,11 @@ const reduceAgUiThreadState = (state, action) => {
|
|
|
48
48
|
...state,
|
|
49
49
|
lastRunConfig: action.runConfig
|
|
50
50
|
};
|
|
51
|
-
case "resumeDeferred": return state.pendingResume?.owner === action.owner && state.pendingResume.
|
|
51
|
+
case "resumeDeferred": return state.pendingResume?.owner === action.owner && state.pendingResume.messageIds.includes(action.messageId) ? state : {
|
|
52
52
|
...state,
|
|
53
53
|
pendingResume: {
|
|
54
54
|
owner: action.owner,
|
|
55
|
-
messageId: action.messageId
|
|
55
|
+
messageIds: state.pendingResume?.owner === action.owner ? [...state.pendingResume.messageIds, action.messageId] : [action.messageId]
|
|
56
56
|
}
|
|
57
57
|
};
|
|
58
58
|
case "resumeCleared": return state.pendingResume === null ? state : {
|
|
@@ -89,7 +89,6 @@ const reduceAgUiThreadState = (state, action) => {
|
|
|
89
89
|
};
|
|
90
90
|
}
|
|
91
91
|
};
|
|
92
|
-
//#endregion
|
|
93
92
|
export { createAgUiThreadState, reduceAgUiThreadState };
|
|
94
93
|
|
|
95
94
|
//# sourceMappingURL=agUiThreadState.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agUiThreadState.js","names":[],"sources":["../../src/runtime/agUiThreadState.ts"],"sourcesContent":["import type { RunConfig } from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\n\nexport type AgUiThreadState = {\n isRunning: boolean;\n isLoading: boolean;\n loadRequested: boolean;\n historyMutationGeneration: number;\n stateSnapshot: ReadonlyJSONValue | undefined;\n lastRunConfig: RunConfig | undefined;\n pendingResume: {
|
|
1
|
+
{"version":3,"file":"agUiThreadState.js","names":[],"sources":["../../src/runtime/agUiThreadState.ts"],"sourcesContent":["import type { RunConfig } from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\n\nexport type AgUiThreadState = {\n isRunning: boolean;\n isLoading: boolean;\n loadRequested: boolean;\n historyMutationGeneration: number;\n stateSnapshot: ReadonlyJSONValue | undefined;\n lastRunConfig: RunConfig | undefined;\n pendingResume: {\n owner: AbortController;\n messageIds: readonly string[];\n } | null;\n pendingA2uiResumeOwner: AbortController | null;\n pendingA2uiAction: Record<string, unknown> | undefined;\n};\n\nexport type AgUiThreadAction =\n | { type: \"runStarted\" }\n | { type: \"runFinished\" }\n | { type: \"loadRequested\" }\n | { type: \"loadStarted\" }\n | { type: \"loadFinished\" }\n | { type: \"historyMutationAdvanced\" }\n | { type: \"stateSnapshot\"; snapshot: ReadonlyJSONValue }\n | { type: \"resetState\" }\n | { type: \"runConfigRecorded\"; runConfig: RunConfig }\n | { type: \"resumeDeferred\"; owner: AbortController; messageId: string }\n | { type: \"resumeCleared\" }\n | { type: \"a2uiResumeDeferred\"; owner: AbortController }\n | { type: \"a2uiResumeCleared\" }\n | { type: \"a2uiActionDeferred\"; action: Record<string, unknown> }\n | { type: \"a2uiActionCleared\" }\n | { type: \"a2uiContinuationsCleared\" }\n | { type: \"resetThread\" };\n\nexport const createAgUiThreadState = (): AgUiThreadState => ({\n isRunning: false,\n isLoading: false,\n loadRequested: false,\n historyMutationGeneration: 0,\n stateSnapshot: undefined,\n lastRunConfig: undefined,\n pendingResume: null,\n pendingA2uiResumeOwner: null,\n pendingA2uiAction: undefined,\n});\n\nexport const reduceAgUiThreadState = (\n state: AgUiThreadState,\n action: AgUiThreadAction,\n): AgUiThreadState => {\n switch (action.type) {\n case \"runStarted\":\n return state.isRunning ? state : { ...state, isRunning: true };\n case \"runFinished\":\n return !state.isRunning ? state : { ...state, isRunning: false };\n case \"loadRequested\":\n return state.loadRequested ? state : { ...state, loadRequested: true };\n case \"loadStarted\":\n return state.isLoading ? state : { ...state, isLoading: true };\n case \"loadFinished\":\n return !state.isLoading ? state : { ...state, isLoading: false };\n case \"historyMutationAdvanced\":\n return {\n ...state,\n historyMutationGeneration: state.historyMutationGeneration + 1,\n };\n case \"stateSnapshot\":\n return state.stateSnapshot === action.snapshot\n ? state\n : { ...state, stateSnapshot: action.snapshot };\n case \"resetState\":\n return state.stateSnapshot === undefined\n ? state\n : { ...state, stateSnapshot: undefined };\n case \"runConfigRecorded\":\n return state.lastRunConfig === action.runConfig\n ? state\n : { ...state, lastRunConfig: action.runConfig };\n case \"resumeDeferred\":\n return state.pendingResume?.owner === action.owner &&\n state.pendingResume.messageIds.includes(action.messageId)\n ? state\n : {\n ...state,\n pendingResume: {\n owner: action.owner,\n messageIds:\n state.pendingResume?.owner === action.owner\n ? [...state.pendingResume.messageIds, action.messageId]\n : [action.messageId],\n },\n };\n case \"resumeCleared\":\n return state.pendingResume === null\n ? state\n : { ...state, pendingResume: null };\n case \"a2uiResumeDeferred\":\n return state.pendingA2uiResumeOwner === action.owner\n ? state\n : { ...state, pendingA2uiResumeOwner: action.owner };\n case \"a2uiResumeCleared\":\n return state.pendingA2uiResumeOwner === null\n ? state\n : { ...state, pendingA2uiResumeOwner: null };\n case \"a2uiActionDeferred\":\n return state.pendingA2uiAction === action.action\n ? state\n : { ...state, pendingA2uiAction: action.action };\n case \"a2uiActionCleared\":\n return state.pendingA2uiAction === undefined\n ? state\n : { ...state, pendingA2uiAction: undefined };\n case \"a2uiContinuationsCleared\":\n return state.pendingA2uiResumeOwner === null &&\n state.pendingA2uiAction === undefined\n ? state\n : {\n ...state,\n pendingA2uiResumeOwner: null,\n pendingA2uiAction: undefined,\n };\n case \"resetThread\":\n return state.stateSnapshot === undefined &&\n state.pendingResume === null &&\n state.pendingA2uiResumeOwner === null &&\n state.pendingA2uiAction === undefined\n ? state\n : {\n ...state,\n stateSnapshot: undefined,\n pendingResume: null,\n pendingA2uiResumeOwner: null,\n pendingA2uiAction: undefined,\n };\n }\n};\n"],"mappings":";AAqCA,MAAa,+BAAgD;CAC3D,WAAW;CACX,WAAW;CACX,eAAe;CACf,2BAA2B;CAC3B,eAAe,KAAA;CACf,eAAe,KAAA;CACf,eAAe;CACf,wBAAwB;CACxB,mBAAmB,KAAA;AACrB;AAEA,MAAa,yBACX,OACA,WACoB;CACpB,QAAQ,OAAO,MAAf;EACE,KAAK,cACH,OAAO,MAAM,YAAY,QAAQ;GAAE,GAAG;GAAO,WAAW;EAAK;EAC/D,KAAK,eACH,OAAO,CAAC,MAAM,YAAY,QAAQ;GAAE,GAAG;GAAO,WAAW;EAAM;EACjE,KAAK,iBACH,OAAO,MAAM,gBAAgB,QAAQ;GAAE,GAAG;GAAO,eAAe;EAAK;EACvE,KAAK,eACH,OAAO,MAAM,YAAY,QAAQ;GAAE,GAAG;GAAO,WAAW;EAAK;EAC/D,KAAK,gBACH,OAAO,CAAC,MAAM,YAAY,QAAQ;GAAE,GAAG;GAAO,WAAW;EAAM;EACjE,KAAK,2BACH,OAAO;GACL,GAAG;GACH,2BAA2B,MAAM,4BAA4B;EAC/D;EACF,KAAK,iBACH,OAAO,MAAM,kBAAkB,OAAO,WAClC,QACA;GAAE,GAAG;GAAO,eAAe,OAAO;EAAS;EACjD,KAAK,cACH,OAAO,MAAM,kBAAkB,KAAA,IAC3B,QACA;GAAE,GAAG;GAAO,eAAe,KAAA;EAAU;EAC3C,KAAK,qBACH,OAAO,MAAM,kBAAkB,OAAO,YAClC,QACA;GAAE,GAAG;GAAO,eAAe,OAAO;EAAU;EAClD,KAAK,kBACH,OAAO,MAAM,eAAe,UAAU,OAAO,SAC3C,MAAM,cAAc,WAAW,SAAS,OAAO,SAAS,IACtD,QACA;GACE,GAAG;GACH,eAAe;IACb,OAAO,OAAO;IACd,YACE,MAAM,eAAe,UAAU,OAAO,QAClC,CAAC,GAAG,MAAM,cAAc,YAAY,OAAO,SAAS,IACpD,CAAC,OAAO,SAAS;GACzB;EACF;EACN,KAAK,iBACH,OAAO,MAAM,kBAAkB,OAC3B,QACA;GAAE,GAAG;GAAO,eAAe;EAAK;EACtC,KAAK,sBACH,OAAO,MAAM,2BAA2B,OAAO,QAC3C,QACA;GAAE,GAAG;GAAO,wBAAwB,OAAO;EAAM;EACvD,KAAK,qBACH,OAAO,MAAM,2BAA2B,OACpC,QACA;GAAE,GAAG;GAAO,wBAAwB;EAAK;EAC/C,KAAK,sBACH,OAAO,MAAM,sBAAsB,OAAO,SACtC,QACA;GAAE,GAAG;GAAO,mBAAmB,OAAO;EAAO;EACnD,KAAK,qBACH,OAAO,MAAM,sBAAsB,KAAA,IAC/B,QACA;GAAE,GAAG;GAAO,mBAAmB,KAAA;EAAU;EAC/C,KAAK,4BACH,OAAO,MAAM,2BAA2B,QACtC,MAAM,sBAAsB,KAAA,IAC1B,QACA;GACE,GAAG;GACH,wBAAwB;GACxB,mBAAmB,KAAA;EACrB;EACN,KAAK,eACH,OAAO,MAAM,kBAAkB,KAAA,KAC7B,MAAM,kBAAkB,QACxB,MAAM,2BAA2B,QACjC,MAAM,sBAAsB,KAAA,IAC1B,QACA;GACE,GAAG;GACH,eAAe,KAAA;GACf,eAAe;GACf,wBAAwB;GACxB,mBAAmB,KAAA;EACrB;CACR;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { parseMcpToolCallResult } from "./mcp-tool-result.js";
|
|
2
2
|
import { withRawResponseSchema } from "./interrupt-internals.js";
|
|
3
|
-
|
|
3
|
+
// src/runtime/event-parser.ts
|
|
4
4
|
const isString = (value) => typeof value === "string";
|
|
5
5
|
const isNonEmptyString = (value) => isString(value) && value.length > 0;
|
|
6
6
|
const withOptional = (base, optionals) => {
|
|
@@ -362,7 +362,6 @@ const parseAgUiEvent = (event, options) => {
|
|
|
362
362
|
}, { source: isString(payload.type) ? payload.type : void 0 });
|
|
363
363
|
}
|
|
364
364
|
};
|
|
365
|
-
//#endregion
|
|
366
365
|
export { parseAgUiEvent };
|
|
367
366
|
|
|
368
367
|
//# sourceMappingURL=event-parser.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/runtime/interrupt-internals.ts
|
|
2
2
|
/**
|
|
3
3
|
* Where a received `responseSchema` travels when it is not an object. JSON
|
|
4
4
|
* Schema allows a boolean, and `false` rejects every payload, so a schema
|
|
@@ -19,7 +19,6 @@ const withoutRawResponseSchema = (interrupt) => {
|
|
|
19
19
|
const { [RAW_RESPONSE_SCHEMA]: _raw, ...rest } = interrupt;
|
|
20
20
|
return rest;
|
|
21
21
|
};
|
|
22
|
-
//#endregion
|
|
23
22
|
export { readRawResponseSchema, withRawResponseSchema, withoutRawResponseSchema };
|
|
24
23
|
|
|
25
24
|
//# sourceMappingURL=interrupt-internals.js.map
|
package/dist/runtime/logger.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { isMcpAppUri } from "@assistant-ui/core";
|
|
2
2
|
import { isRecord } from "@assistant-ui/core/internal";
|
|
3
3
|
import { contentToText } from "@ag-ui/client";
|
|
4
|
-
|
|
4
|
+
// src/runtime/mcp-tool-result.ts
|
|
5
5
|
const toolContentText = (content) => contentToText(Array.isArray(content) ? content.filter(isRecord) : content);
|
|
6
6
|
const parseMcpToolCallResult = (source, content) => {
|
|
7
7
|
const structuredContent = isRecord(source.structuredContent) ? source.structuredContent : void 0;
|
|
@@ -26,7 +26,6 @@ const readMcpAppResourceUri = (meta) => {
|
|
|
26
26
|
const flat = meta["ui/resourceUri"];
|
|
27
27
|
return typeof flat === "string" && isMcpAppUri(flat) ? flat : void 0;
|
|
28
28
|
};
|
|
29
|
-
//#endregion
|
|
30
29
|
export { parseMcpToolCallResult, readMcpAppResourceUri, toolContentText };
|
|
31
30
|
|
|
32
31
|
//# sourceMappingURL=mcp-tool-result.js.map
|
package/dist/runtime/types.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
// src/runtime/types.ts
|
|
2
2
|
const AG_UI_METADATA_NAMESPACE = "agui";
|
|
3
3
|
const MCP_APPS_ACTIVITY_TYPE = "mcp-apps";
|
|
4
4
|
const A2UI_SURFACE_ACTIVITY_TYPE = "a2ui-surface";
|
|
5
|
-
//#endregion
|
|
6
5
|
export { A2UI_SURFACE_ACTIVITY_TYPE, AG_UI_METADATA_NAMESPACE, MCP_APPS_ACTIVITY_TYPE };
|
|
7
6
|
|
|
8
7
|
//# sourceMappingURL=types.js.map
|
package/dist/useAgUiRuntime.js
CHANGED
|
@@ -6,7 +6,7 @@ import { useExternalStoreRuntime, useExternalStoreSharedOptions, useRuntimeAdapt
|
|
|
6
6
|
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
7
7
|
import { useIsomorphicLayoutEffect, useReplaySafeEffect } from "@assistant-ui/store/internal";
|
|
8
8
|
import { createMessageQueue } from "@assistant-ui/core";
|
|
9
|
-
|
|
9
|
+
// src/useAgUiRuntime.ts
|
|
10
10
|
const EMPTY_INTERRUPTS = [];
|
|
11
11
|
const EMPTY_QUEUE_ITEMS = Object.freeze([]);
|
|
12
12
|
const subscribeNoop = () => () => {};
|
|
@@ -262,7 +262,6 @@ function useAgUiRuntime(options) {
|
|
|
262
262
|
}, [core]);
|
|
263
263
|
return runtime;
|
|
264
264
|
}
|
|
265
|
-
//#endregion
|
|
266
265
|
export { useAgUiRuntime };
|
|
267
266
|
|
|
268
267
|
//# sourceMappingURL=useAgUiRuntime.js.map
|