@deepagents/experimental 4.2.1 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -5
- package/dist/coding-agent-reminders/context.d.ts +15 -0
- package/dist/coding-agent-reminders/context.d.ts.map +1 -0
- package/dist/coding-agent-reminders/evaluate.d.ts +3 -0
- package/dist/coding-agent-reminders/evaluate.d.ts.map +1 -0
- package/dist/coding-agent-reminders/index.d.ts +5 -0
- package/dist/coding-agent-reminders/index.d.ts.map +1 -0
- package/dist/coding-agent-reminders/index.js +310 -0
- package/dist/coding-agent-reminders/index.js.map +7 -0
- package/dist/coding-agent-reminders/io.d.ts +4 -0
- package/dist/coding-agent-reminders/io.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/classifier.d.ts +10 -0
- package/dist/coding-agent-reminders/predicates/classifier.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/combinators.d.ts +6 -0
- package/dist/coding-agent-reminders/predicates/combinators.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/content.d.ts +7 -0
- package/dist/coding-agent-reminders/predicates/content.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/count.d.ts +4 -0
- package/dist/coding-agent-reminders/predicates/count.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/environment.d.ts +3 -0
- package/dist/coding-agent-reminders/predicates/environment.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/event.d.ts +3 -0
- package/dist/coding-agent-reminders/predicates/event.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/index.d.ts +8 -0
- package/dist/coding-agent-reminders/predicates/index.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/tool.d.ts +11 -0
- package/dist/coding-agent-reminders/predicates/tool.d.ts.map +1 -0
- package/dist/coding-agent-reminders/types.d.ts +86 -0
- package/dist/coding-agent-reminders/types.d.ts.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2036 -158
- package/dist/index.js.map +4 -4
- package/dist/zukhruf/agent-control-plane.d.ts +68 -0
- package/dist/zukhruf/agent-control-plane.d.ts.map +1 -0
- package/dist/zukhruf/agent-declaration-registry.d.ts +9 -0
- package/dist/zukhruf/agent-declaration-registry.d.ts.map +1 -0
- package/dist/zukhruf/agent-directory.d.ts +21 -0
- package/dist/zukhruf/agent-directory.d.ts.map +1 -0
- package/dist/zukhruf/agent-path.d.ts +15 -0
- package/dist/zukhruf/agent-path.d.ts.map +1 -0
- package/dist/zukhruf/agent-runtime.d.ts +53 -0
- package/dist/zukhruf/agent-runtime.d.ts.map +1 -0
- package/dist/zukhruf/agent-status-projector.d.ts +32 -0
- package/dist/zukhruf/agent-status-projector.d.ts.map +1 -0
- package/dist/zukhruf/agent-thread.d.ts +31 -0
- package/dist/zukhruf/agent-thread.d.ts.map +1 -0
- package/dist/zukhruf/agent-tool-context.d.ts +6 -0
- package/dist/zukhruf/agent-tool-context.d.ts.map +1 -0
- package/dist/zukhruf/agent-turn-executor.d.ts +19 -0
- package/dist/zukhruf/agent-turn-executor.d.ts.map +1 -0
- package/dist/zukhruf/agent-turn-id.d.ts +11 -0
- package/dist/zukhruf/agent-turn-id.d.ts.map +1 -0
- package/dist/zukhruf/agent.d.ts +13 -8
- package/dist/zukhruf/agent.d.ts.map +1 -1
- package/dist/zukhruf/approval-controller.d.ts +34 -0
- package/dist/zukhruf/approval-controller.d.ts.map +1 -0
- package/dist/zukhruf/approval-mutex.d.ts +5 -0
- package/dist/zukhruf/approval-mutex.d.ts.map +1 -0
- package/dist/zukhruf/index.d.ts +15 -11
- package/dist/zukhruf/index.d.ts.map +1 -1
- package/dist/zukhruf/index.js +1716 -152
- package/dist/zukhruf/index.js.map +4 -4
- package/dist/zukhruf/list-agents.d.ts +234 -0
- package/dist/zukhruf/list-agents.d.ts.map +1 -0
- package/dist/zukhruf/mailbox/coordinator.d.ts +22 -0
- package/dist/zukhruf/mailbox/coordinator.d.ts.map +1 -0
- package/dist/zukhruf/mailbox/sqlite.store.d.ts +16 -0
- package/dist/zukhruf/mailbox/sqlite.store.d.ts.map +1 -0
- package/dist/zukhruf/mailbox/store.d.ts +20 -0
- package/dist/zukhruf/mailbox/store.d.ts.map +1 -0
- package/dist/zukhruf/mailbox/types.d.ts +35 -0
- package/dist/zukhruf/mailbox/types.d.ts.map +1 -0
- package/dist/zukhruf/message-tools.d.ts +456 -0
- package/dist/zukhruf/message-tools.d.ts.map +1 -0
- package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +2 -1
- package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
- package/dist/zukhruf/queue/turn-queue.d.ts +14 -0
- package/dist/zukhruf/queue/turn-queue.d.ts.map +1 -1
- package/dist/zukhruf/spawn-agent.d.ts +301 -0
- package/dist/zukhruf/spawn-agent.d.ts.map +1 -0
- package/dist/zukhruf/sqlite-approval-mutex.d.ts +17 -0
- package/dist/zukhruf/sqlite-approval-mutex.d.ts.map +1 -0
- package/package.json +14 -7
- package/dist/zukhruf/runtime.d.ts +0 -67
- package/dist/zukhruf/runtime.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -4,232 +4,2013 @@ var __export = (target, all) => {
|
|
|
4
4
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
5
5
|
};
|
|
6
6
|
|
|
7
|
+
// packages/experimental/src/coding-agent-reminders/index.ts
|
|
8
|
+
var coding_agent_reminders_exports = {};
|
|
9
|
+
__export(coding_agent_reminders_exports, {
|
|
10
|
+
BM25Classifier: () => BM25Classifier,
|
|
11
|
+
always: () => always,
|
|
12
|
+
and: () => and,
|
|
13
|
+
anyToolCalled: () => anyToolCalled,
|
|
14
|
+
assertCountSpec: () => assertCountSpec,
|
|
15
|
+
bashCommandMatches: () => bashCommandMatches,
|
|
16
|
+
checkCount: () => checkCount,
|
|
17
|
+
classifies: () => classifies,
|
|
18
|
+
contentIncludes: () => contentIncludes,
|
|
19
|
+
contentMatches: () => contentMatches,
|
|
20
|
+
contentPattern: () => contentPattern,
|
|
21
|
+
envFlag: () => envFlag,
|
|
22
|
+
evaluateReminderHook: () => evaluateReminderHook,
|
|
23
|
+
eventIs: () => eventIs,
|
|
24
|
+
not: () => not,
|
|
25
|
+
or: () => or,
|
|
26
|
+
outputMatches: () => outputMatches,
|
|
27
|
+
promptMatches: () => promptMatches,
|
|
28
|
+
readStdin: () => readStdin,
|
|
29
|
+
toolCall: () => toolCall,
|
|
30
|
+
toolCallCount: () => toolCallCount,
|
|
31
|
+
toolCalled: () => toolCalled,
|
|
32
|
+
toolFailed: () => toolFailed,
|
|
33
|
+
toolIs: () => toolIs,
|
|
34
|
+
toolOutputMatches: () => toolOutputMatches,
|
|
35
|
+
writeOutput: () => writeOutput
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// packages/experimental/src/coding-agent-reminders/evaluate.ts
|
|
39
|
+
async function evaluateReminderHook(input, config) {
|
|
40
|
+
const guardMatch = input.hook_event_name === "PreToolUse" ? await firstMatchingGuard(input, config.guards) : void 0;
|
|
41
|
+
if (guardMatch) {
|
|
42
|
+
return {
|
|
43
|
+
hookSpecificOutput: {
|
|
44
|
+
hookEventName: input.hook_event_name,
|
|
45
|
+
permissionDecision: "deny",
|
|
46
|
+
permissionDecisionReason: guardMatch.errorReason ?? resolveGuardReason(guardMatch.rule, input)
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
if (input.stop_hook_active === true && (input.hook_event_name === "Stop" || input.hook_event_name === "SubagentStop")) {
|
|
51
|
+
return void 0;
|
|
52
|
+
}
|
|
53
|
+
const reminders = await matchingReminders(input, config.reminders);
|
|
54
|
+
if (reminders.length === 0) return void 0;
|
|
55
|
+
return {
|
|
56
|
+
hookSpecificOutput: {
|
|
57
|
+
hookEventName: input.hook_event_name,
|
|
58
|
+
additionalContext: reminders.join("\n\n")
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
async function firstMatchingGuard(input, guards) {
|
|
63
|
+
for (const rule of guards) {
|
|
64
|
+
try {
|
|
65
|
+
if (await rule.when(input)) return { rule };
|
|
66
|
+
} catch (error) {
|
|
67
|
+
console.error(`Guard "${rule.id}" predicate failed`, error);
|
|
68
|
+
return {
|
|
69
|
+
rule,
|
|
70
|
+
errorReason: `Guard "${rule.id}" failed to evaluate; denying by default.`
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return void 0;
|
|
75
|
+
}
|
|
76
|
+
async function matchingReminders(input, reminders) {
|
|
77
|
+
const matched = [];
|
|
78
|
+
for (const rule of reminders) {
|
|
79
|
+
if (!rule.events.includes(input.hook_event_name)) continue;
|
|
80
|
+
try {
|
|
81
|
+
if (!await rule.when(input)) continue;
|
|
82
|
+
matched.push(
|
|
83
|
+
`[${rule.target}:${rule.id}]
|
|
84
|
+
${resolveText(rule.message, input)}`
|
|
85
|
+
);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
console.error(`Reminder "${rule.id}" evaluation failed`, error);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return matched;
|
|
91
|
+
}
|
|
92
|
+
function resolveText(value, input) {
|
|
93
|
+
return typeof value === "function" ? value(input) : value;
|
|
94
|
+
}
|
|
95
|
+
function resolveGuardReason(rule, input) {
|
|
96
|
+
try {
|
|
97
|
+
return resolveText(rule.deny, input);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
console.error(`Guard "${rule.id}" denial message failed`, error);
|
|
100
|
+
return `Guard "${rule.id}" matched but its denial message failed; denying by default.`;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// packages/experimental/src/coding-agent-reminders/io.ts
|
|
105
|
+
async function readStdin() {
|
|
106
|
+
const chunks = [];
|
|
107
|
+
for await (const chunk of process.stdin) {
|
|
108
|
+
chunks.push(Buffer.from(chunk));
|
|
109
|
+
}
|
|
110
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
111
|
+
}
|
|
112
|
+
function writeOutput(output) {
|
|
113
|
+
process.stdout.write(`${JSON.stringify(output)}
|
|
114
|
+
`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// packages/experimental/src/coding-agent-reminders/predicates/classifier.ts
|
|
118
|
+
import { Corpus } from "tiny-tfidf";
|
|
119
|
+
var BM25Classifier = class {
|
|
120
|
+
#corpus;
|
|
121
|
+
#itemsByName;
|
|
122
|
+
constructor(items) {
|
|
123
|
+
const names = items.map((item) => item.name);
|
|
124
|
+
const texts = items.map((item) => `${item.name} ${item.description}`);
|
|
125
|
+
this.#corpus = new Corpus(names, texts);
|
|
126
|
+
this.#itemsByName = new Map(items.map((item) => [item.name, item]));
|
|
127
|
+
}
|
|
128
|
+
match(query, options) {
|
|
129
|
+
const topN = options?.topN ?? 5;
|
|
130
|
+
const threshold = options?.threshold ?? 0;
|
|
131
|
+
return this.#corpus.getResultsForQuery(query).filter(([, score]) => score > threshold).slice(0, topN).map(([name, score]) => {
|
|
132
|
+
const item = this.#itemsByName.get(name);
|
|
133
|
+
if (!item) return null;
|
|
134
|
+
return { item, score };
|
|
135
|
+
}).filter((match) => match !== null);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
// packages/experimental/src/coding-agent-reminders/predicates/combinators.ts
|
|
140
|
+
var always = () => true;
|
|
141
|
+
var and = (...predicates) => async (ctx) => {
|
|
142
|
+
for (const predicate of predicates) {
|
|
143
|
+
if (!await predicate(ctx)) return false;
|
|
144
|
+
}
|
|
145
|
+
return true;
|
|
146
|
+
};
|
|
147
|
+
var or = (...predicates) => async (ctx) => {
|
|
148
|
+
for (const predicate of predicates) {
|
|
149
|
+
if (await predicate(ctx)) return true;
|
|
150
|
+
}
|
|
151
|
+
return false;
|
|
152
|
+
};
|
|
153
|
+
var not = (predicate) => async (ctx) => !await predicate(ctx);
|
|
154
|
+
|
|
155
|
+
// packages/experimental/src/coding-agent-reminders/context.ts
|
|
156
|
+
function contentText(ctx) {
|
|
157
|
+
return [ctx.prompt, ctx.command_name, ctx.command_args].filter((value) => typeof value === "string").join(" ");
|
|
158
|
+
}
|
|
159
|
+
function bashCommand(ctx) {
|
|
160
|
+
if (ctx.tool_name !== "Bash") return "";
|
|
161
|
+
const command = ctx.tool_input?.command;
|
|
162
|
+
return typeof command === "string" ? command : "";
|
|
163
|
+
}
|
|
164
|
+
function outputText(ctx) {
|
|
165
|
+
if (ctx.hook_event_name === "PostToolBatch" && ctx.tool_calls) {
|
|
166
|
+
return ctx.tool_calls.map((call) => textOf(call.tool_response)).filter(Boolean).join("\n");
|
|
167
|
+
}
|
|
168
|
+
const output = ctx.tool_output ?? ctx.tool_response;
|
|
169
|
+
return textOf(output);
|
|
170
|
+
}
|
|
171
|
+
function textOf(value) {
|
|
172
|
+
if (typeof value === "string") return value;
|
|
173
|
+
if (value === void 0) return "";
|
|
174
|
+
try {
|
|
175
|
+
return JSON.stringify(value);
|
|
176
|
+
} catch {
|
|
177
|
+
return String(value);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function toolCallsOf(ctx) {
|
|
181
|
+
if (ctx.hook_event_name === "PostToolBatch" && ctx.tool_calls) {
|
|
182
|
+
return ctx.tool_calls.map((call) => ({
|
|
183
|
+
name: call.tool_name,
|
|
184
|
+
state: "output-available",
|
|
185
|
+
input: call.tool_input,
|
|
186
|
+
output: call.tool_response
|
|
187
|
+
}));
|
|
188
|
+
}
|
|
189
|
+
const calls = [];
|
|
190
|
+
const toolName = ctx.tool_name;
|
|
191
|
+
if (typeof toolName === "string") {
|
|
192
|
+
calls.push({
|
|
193
|
+
name: toolName,
|
|
194
|
+
state: stateOf(ctx.hook_event_name),
|
|
195
|
+
input: ctx.tool_input,
|
|
196
|
+
output: ctx.tool_output ?? ctx.tool_response,
|
|
197
|
+
errorText: errorTextOf(ctx)
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
return calls;
|
|
201
|
+
}
|
|
202
|
+
function matchesName(spec, name) {
|
|
203
|
+
return typeof spec === "function" ? spec(name) : spec === name;
|
|
204
|
+
}
|
|
205
|
+
function stateOf(eventName) {
|
|
206
|
+
if (eventName === "PostToolUseFailure") return "output-error";
|
|
207
|
+
if (eventName === "PostToolUse") return "output-available";
|
|
208
|
+
return "input-available";
|
|
209
|
+
}
|
|
210
|
+
function errorTextOf(ctx) {
|
|
211
|
+
const error = ctx.tool_error ?? ctx.error ?? ctx.reason ?? ctx.tool_output ?? ctx.tool_response;
|
|
212
|
+
return textOf(error);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// packages/experimental/src/coding-agent-reminders/predicates/content.ts
|
|
216
|
+
function contentMatches(topics, options) {
|
|
217
|
+
const classifier = new BM25Classifier(
|
|
218
|
+
topics.map((topic, index) => ({
|
|
219
|
+
name: `t${index}`,
|
|
220
|
+
description: topic
|
|
221
|
+
}))
|
|
222
|
+
);
|
|
223
|
+
return (ctx) => classifier.match(contentText(ctx), {
|
|
224
|
+
threshold: options?.threshold
|
|
225
|
+
}).length > 0;
|
|
226
|
+
}
|
|
227
|
+
function classifies(classifier, options) {
|
|
228
|
+
return (ctx) => classifier.match(contentText(ctx), options).length > 0;
|
|
229
|
+
}
|
|
230
|
+
function contentIncludes(keywords) {
|
|
231
|
+
const lower = keywords.map((keyword) => keyword.toLowerCase());
|
|
232
|
+
return (ctx) => {
|
|
233
|
+
const text = contentText(ctx).toLowerCase();
|
|
234
|
+
return lower.some((keyword) => text.includes(keyword));
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
var contentPattern = (pattern) => (ctx) => {
|
|
238
|
+
pattern.lastIndex = 0;
|
|
239
|
+
return pattern.test(contentText(ctx));
|
|
240
|
+
};
|
|
241
|
+
var promptMatches = contentPattern;
|
|
242
|
+
|
|
243
|
+
// packages/experimental/src/coding-agent-reminders/predicates/count.ts
|
|
244
|
+
function assertCountSpec(spec) {
|
|
245
|
+
const hasEq = spec.eq !== void 0;
|
|
246
|
+
const hasRange = spec.gte !== void 0 || spec.lte !== void 0;
|
|
247
|
+
if (!hasEq && !hasRange) {
|
|
248
|
+
throw new Error("CountSpec must include at least one of gte/lte/eq");
|
|
249
|
+
}
|
|
250
|
+
if (hasEq && hasRange) {
|
|
251
|
+
throw new Error("CountSpec.eq cannot be combined with gte/lte");
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
function checkCount(count, spec) {
|
|
255
|
+
if (spec.eq !== void 0) return count === spec.eq;
|
|
256
|
+
if (spec.gte !== void 0 && count < spec.gte) return false;
|
|
257
|
+
if (spec.lte !== void 0 && count > spec.lte) return false;
|
|
258
|
+
return true;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// packages/experimental/src/coding-agent-reminders/predicates/environment.ts
|
|
262
|
+
var envFlag = (name) => () => process.env[name] === "1" || process.env[name] === "true";
|
|
263
|
+
|
|
264
|
+
// packages/experimental/src/coding-agent-reminders/predicates/event.ts
|
|
265
|
+
var eventIs = (...events) => (ctx) => events.includes(ctx.hook_event_name);
|
|
266
|
+
|
|
267
|
+
// packages/experimental/src/coding-agent-reminders/predicates/tool.ts
|
|
268
|
+
var toolIs = (name) => (ctx) => ctx.tool_name === name;
|
|
269
|
+
var bashCommandMatches = (pattern) => (ctx) => {
|
|
270
|
+
pattern.lastIndex = 0;
|
|
271
|
+
return pattern.test(bashCommand(ctx));
|
|
272
|
+
};
|
|
273
|
+
function toolCall(options) {
|
|
274
|
+
return (ctx) => {
|
|
275
|
+
return toolCallsOf(ctx).some((call) => {
|
|
276
|
+
if (options.state && call.state !== options.state) return false;
|
|
277
|
+
if (options.name !== void 0 && !matchesName(options.name, call.name)) {
|
|
278
|
+
return false;
|
|
279
|
+
}
|
|
280
|
+
if (options.input && !options.input(call.input)) return false;
|
|
281
|
+
if (options.output) {
|
|
282
|
+
if (call.state !== "output-available") return false;
|
|
283
|
+
if (!options.output(call.output)) return false;
|
|
284
|
+
}
|
|
285
|
+
if (options.errorText) {
|
|
286
|
+
if (call.state !== "output-error") return false;
|
|
287
|
+
if (!options.errorText(call.errorText ?? "")) return false;
|
|
288
|
+
}
|
|
289
|
+
return true;
|
|
290
|
+
});
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
function toolCalled(name) {
|
|
294
|
+
return toolCall({ name });
|
|
295
|
+
}
|
|
296
|
+
function toolFailed(name) {
|
|
297
|
+
return toolCall({ name, state: "output-error" });
|
|
298
|
+
}
|
|
299
|
+
function anyToolCalled() {
|
|
300
|
+
return (ctx) => toolCallsOf(ctx).length > 0;
|
|
301
|
+
}
|
|
302
|
+
function toolCallCount(name, spec) {
|
|
303
|
+
assertCountSpec(spec);
|
|
304
|
+
return (ctx) => checkCount(
|
|
305
|
+
toolCallsOf(ctx).filter((call) => matchesName(name, call.name)).length,
|
|
306
|
+
spec
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
var outputMatches = (pattern) => (ctx) => {
|
|
310
|
+
pattern.lastIndex = 0;
|
|
311
|
+
return pattern.test(outputText(ctx));
|
|
312
|
+
};
|
|
313
|
+
var toolOutputMatches = (pattern) => toolCall({
|
|
314
|
+
output: (output) => {
|
|
315
|
+
pattern.lastIndex = 0;
|
|
316
|
+
return pattern.test(textOf(output));
|
|
317
|
+
}
|
|
318
|
+
});
|
|
319
|
+
|
|
7
320
|
// packages/experimental/src/zukhruf/index.ts
|
|
8
321
|
var zukhruf_exports = {};
|
|
9
322
|
__export(zukhruf_exports, {
|
|
323
|
+
AgentObservation: () => AgentObservation,
|
|
324
|
+
AgentPath: () => AgentPath,
|
|
325
|
+
AgentRuntime: () => AgentRuntime,
|
|
326
|
+
AgentThread: () => AgentThread,
|
|
327
|
+
ApprovalMutex: () => ApprovalMutex,
|
|
328
|
+
InterAgentCommunicationType: () => InterAgentCommunicationType,
|
|
329
|
+
MailboxStore: () => MailboxStore,
|
|
330
|
+
MessageDeliveryMode: () => MessageDeliveryMode,
|
|
10
331
|
PgBossTurnQueue: () => PgBossTurnQueue,
|
|
332
|
+
SqliteApprovalMutex: () => SqliteApprovalMutex,
|
|
333
|
+
SqliteMailboxStore: () => SqliteMailboxStore,
|
|
11
334
|
TurnQueue: () => TurnQueue,
|
|
12
|
-
|
|
335
|
+
assertCommunication: () => assertCommunication,
|
|
336
|
+
createInterAgentCommunication: () => createInterAgentCommunication,
|
|
13
337
|
defineAgent: () => defineAgent,
|
|
14
338
|
defineInstructions: () => defineInstructions,
|
|
15
339
|
defineSandbox: () => defineSandbox,
|
|
16
|
-
defineTool: () =>
|
|
340
|
+
defineTool: () => tool4
|
|
17
341
|
});
|
|
18
342
|
|
|
343
|
+
// packages/experimental/src/zukhruf/agent-path.ts
|
|
344
|
+
var AgentPath = class _AgentPath {
|
|
345
|
+
#value;
|
|
346
|
+
constructor(value) {
|
|
347
|
+
this.#value = value;
|
|
348
|
+
}
|
|
349
|
+
static root() {
|
|
350
|
+
return new _AgentPath("/root");
|
|
351
|
+
}
|
|
352
|
+
static parse(value) {
|
|
353
|
+
const path = value.trim();
|
|
354
|
+
if (path !== "/root" && !path.startsWith("/root/")) {
|
|
355
|
+
throw new Error(`agent path "${value}" must start at /root`);
|
|
356
|
+
}
|
|
357
|
+
const segments = path.slice(1).split("/");
|
|
358
|
+
if (segments.some(
|
|
359
|
+
(segment) => segment.length === 0 || segment !== segment.trim() || segment === "." || segment === ".."
|
|
360
|
+
)) {
|
|
361
|
+
throw new Error(`agent path "${value}" contains an invalid segment`);
|
|
362
|
+
}
|
|
363
|
+
return new _AgentPath(path);
|
|
364
|
+
}
|
|
365
|
+
/** Relative targets name descendants; absolute targets keep their canonical path. */
|
|
366
|
+
resolve(target) {
|
|
367
|
+
const requested = target.trim();
|
|
368
|
+
if (!requested) throw new Error("agent path cannot be empty");
|
|
369
|
+
return _AgentPath.parse(
|
|
370
|
+
requested.startsWith("/") ? requested : `${this.#value}/${requested}`
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
contains(candidate) {
|
|
374
|
+
return this.equals(candidate) || candidate.#value.startsWith(`${this.#value}/`);
|
|
375
|
+
}
|
|
376
|
+
equals(other) {
|
|
377
|
+
return this.#value === other.#value;
|
|
378
|
+
}
|
|
379
|
+
get isRoot() {
|
|
380
|
+
return this.#value === "/root";
|
|
381
|
+
}
|
|
382
|
+
get parent() {
|
|
383
|
+
if (this.isRoot) return null;
|
|
384
|
+
return _AgentPath.parse(this.#value.slice(0, this.#value.lastIndexOf("/")));
|
|
385
|
+
}
|
|
386
|
+
toString() {
|
|
387
|
+
return this.#value;
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
// packages/experimental/src/zukhruf/agent-thread.ts
|
|
392
|
+
var AgentThread = class _AgentThread {
|
|
393
|
+
conversation;
|
|
394
|
+
treeId;
|
|
395
|
+
path;
|
|
396
|
+
parentChatId;
|
|
397
|
+
declarationName;
|
|
398
|
+
lastTurnId;
|
|
399
|
+
constructor(options) {
|
|
400
|
+
_AgentThread.#assertTopology(options);
|
|
401
|
+
this.conversation = options.conversation;
|
|
402
|
+
this.treeId = options.treeId;
|
|
403
|
+
this.path = options.path;
|
|
404
|
+
this.parentChatId = options.parentChatId;
|
|
405
|
+
this.declarationName = options.declarationName;
|
|
406
|
+
this.lastTurnId = options.lastTurnId;
|
|
407
|
+
}
|
|
408
|
+
static root(conversation, declarationName) {
|
|
409
|
+
return new _AgentThread({
|
|
410
|
+
conversation,
|
|
411
|
+
treeId: conversation.chatId,
|
|
412
|
+
path: AgentPath.root(),
|
|
413
|
+
parentChatId: null,
|
|
414
|
+
declarationName
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
static metadataFilter(treeId) {
|
|
418
|
+
return { key: "zukhrufTreeId", value: treeId };
|
|
419
|
+
}
|
|
420
|
+
static hasReservedMetadata(metadata) {
|
|
421
|
+
return Boolean(
|
|
422
|
+
metadata && (Object.hasOwn(metadata, "zukhrufTreeId") || Object.hasOwn(metadata, "zukhruf"))
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
static fromMetadata(conversation, metadata) {
|
|
426
|
+
const treeId = metadata?.zukhrufTreeId;
|
|
427
|
+
const zukhruf = metadata?.zukhruf;
|
|
428
|
+
if (typeof treeId !== "string" || !_AgentThread.#isRecord(zukhruf)) {
|
|
429
|
+
return void 0;
|
|
430
|
+
}
|
|
431
|
+
const { path, parentChatId, declarationName, lastTurnId } = zukhruf;
|
|
432
|
+
if (typeof path !== "string" || parentChatId !== null && typeof parentChatId !== "string" || typeof declarationName !== "string" || lastTurnId !== void 0 && typeof lastTurnId !== "string") {
|
|
433
|
+
return void 0;
|
|
434
|
+
}
|
|
435
|
+
let parsedPath;
|
|
436
|
+
try {
|
|
437
|
+
parsedPath = AgentPath.parse(path);
|
|
438
|
+
} catch {
|
|
439
|
+
return void 0;
|
|
440
|
+
}
|
|
441
|
+
if (parsedPath.toString() !== path) return void 0;
|
|
442
|
+
try {
|
|
443
|
+
return new _AgentThread({
|
|
444
|
+
conversation,
|
|
445
|
+
treeId,
|
|
446
|
+
path: parsedPath,
|
|
447
|
+
parentChatId,
|
|
448
|
+
declarationName,
|
|
449
|
+
...lastTurnId === void 0 ? {} : { lastTurnId }
|
|
450
|
+
});
|
|
451
|
+
} catch {
|
|
452
|
+
return void 0;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
withLatestTurn(lastTurnId) {
|
|
456
|
+
return new _AgentThread({
|
|
457
|
+
conversation: this.conversation,
|
|
458
|
+
treeId: this.treeId,
|
|
459
|
+
path: this.path,
|
|
460
|
+
parentChatId: this.parentChatId,
|
|
461
|
+
declarationName: this.declarationName,
|
|
462
|
+
lastTurnId
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
toMetadata(metadata) {
|
|
466
|
+
const existing = _AgentThread.#isRecord(metadata?.zukhruf) ? metadata.zukhruf : {};
|
|
467
|
+
return {
|
|
468
|
+
...metadata,
|
|
469
|
+
zukhrufTreeId: this.treeId,
|
|
470
|
+
zukhruf: {
|
|
471
|
+
...existing,
|
|
472
|
+
path: this.path.toString(),
|
|
473
|
+
parentChatId: this.parentChatId,
|
|
474
|
+
declarationName: this.declarationName,
|
|
475
|
+
...this.lastTurnId === void 0 ? {} : { lastTurnId: this.lastTurnId }
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
static #isRecord(value) {
|
|
480
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
481
|
+
}
|
|
482
|
+
static #assertTopology(options) {
|
|
483
|
+
if (options.path.isRoot) {
|
|
484
|
+
if (options.treeId !== options.conversation.chatId) {
|
|
485
|
+
throw new Error("root agent thread treeId must match its chatId");
|
|
486
|
+
}
|
|
487
|
+
if (options.parentChatId !== null) {
|
|
488
|
+
throw new Error("root agent thread cannot have a parent");
|
|
489
|
+
}
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
if (options.parentChatId === null) {
|
|
493
|
+
throw new Error("child agent thread requires a parent");
|
|
494
|
+
}
|
|
495
|
+
if (options.parentChatId === options.conversation.chatId) {
|
|
496
|
+
throw new Error("child agent thread cannot parent itself");
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
|
|
19
501
|
// packages/experimental/src/zukhruf/agent.ts
|
|
20
502
|
function defineAgent(declaration) {
|
|
21
503
|
return {
|
|
22
|
-
name: declaration.name
|
|
504
|
+
name: declaration.name,
|
|
23
505
|
model: declaration.model,
|
|
24
506
|
sandbox: declaration.sandbox,
|
|
25
507
|
instructions: declaration.instructions,
|
|
26
|
-
tools: declaration.tools
|
|
508
|
+
tools: declaration.tools ?? {},
|
|
509
|
+
subagents: declaration.subagents ?? [],
|
|
510
|
+
telemetry: declaration.telemetry
|
|
27
511
|
};
|
|
28
512
|
}
|
|
29
513
|
|
|
30
|
-
// packages/experimental/src/zukhruf/
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
514
|
+
// packages/experimental/src/zukhruf/agent-runtime.ts
|
|
515
|
+
import {
|
|
516
|
+
ContextEngine as ContextEngine4,
|
|
517
|
+
PollingChangeSource,
|
|
518
|
+
StreamManager
|
|
519
|
+
} from "@deepagents/context";
|
|
34
520
|
|
|
35
|
-
// packages/experimental/src/zukhruf/
|
|
36
|
-
import {
|
|
521
|
+
// packages/experimental/src/zukhruf/agent-control-plane.ts
|
|
522
|
+
import { v5 as uuidv53 } from "uuid";
|
|
37
523
|
|
|
38
|
-
// packages/experimental/src/zukhruf/
|
|
524
|
+
// packages/experimental/src/zukhruf/agent-declaration-registry.ts
|
|
525
|
+
var AgentDeclarationRegistry = class {
|
|
526
|
+
root;
|
|
527
|
+
#declarations = /* @__PURE__ */ new Map();
|
|
528
|
+
constructor(root) {
|
|
529
|
+
this.root = root;
|
|
530
|
+
this.#register(root, /* @__PURE__ */ new Set());
|
|
531
|
+
}
|
|
532
|
+
get(name) {
|
|
533
|
+
return this.#declarations.get(name);
|
|
534
|
+
}
|
|
535
|
+
#register(declaration, visited) {
|
|
536
|
+
if (visited.has(declaration)) return;
|
|
537
|
+
visited.add(declaration);
|
|
538
|
+
if (!declaration.name.trim()) {
|
|
539
|
+
throw new Error("AgentRuntime: agent declaration name cannot be empty");
|
|
540
|
+
}
|
|
541
|
+
if (declaration.name !== declaration.name.trim()) {
|
|
542
|
+
throw new Error(
|
|
543
|
+
`AgentRuntime: agent declaration name "${declaration.name}" must not contain surrounding whitespace`
|
|
544
|
+
);
|
|
545
|
+
}
|
|
546
|
+
const existing = this.#declarations.get(declaration.name);
|
|
547
|
+
if (existing && existing !== declaration) {
|
|
548
|
+
throw new Error(
|
|
549
|
+
`AgentRuntime: duplicate agent declaration name "${declaration.name}"`
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
this.#declarations.set(declaration.name, declaration);
|
|
553
|
+
for (const subagent of declaration.subagents ?? []) {
|
|
554
|
+
this.#register(subagent, visited);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
|
|
559
|
+
// packages/experimental/src/zukhruf/agent-directory.ts
|
|
560
|
+
import { v5 as uuidv5 } from "uuid";
|
|
561
|
+
var AgentDirectory = class _AgentDirectory {
|
|
562
|
+
#store;
|
|
563
|
+
constructor(store) {
|
|
564
|
+
this.#store = store;
|
|
565
|
+
}
|
|
566
|
+
async assertOwnerIfExists(conversation) {
|
|
567
|
+
const chat2 = await this.#store.getChat(conversation.chatId);
|
|
568
|
+
if (!chat2) return;
|
|
569
|
+
this.#assertOwner(conversation, chat2.userId);
|
|
570
|
+
const thread = this.#threadFromMetadata(conversation, chat2.metadata);
|
|
571
|
+
if (thread) await this.#assertValidParent(thread);
|
|
572
|
+
}
|
|
573
|
+
async load(conversation) {
|
|
574
|
+
const chat2 = await this.#store.getChat(conversation.chatId);
|
|
575
|
+
if (chat2) this.#assertOwner(conversation, chat2.userId);
|
|
576
|
+
if (!chat2) return void 0;
|
|
577
|
+
const thread = this.#threadFromMetadata(conversation, chat2.metadata);
|
|
578
|
+
if (thread) await this.#assertValidParent(thread);
|
|
579
|
+
return thread;
|
|
580
|
+
}
|
|
581
|
+
async loadOrCreateRoot(conversation, declarationName) {
|
|
582
|
+
await this.#store.upsertChat({
|
|
583
|
+
id: conversation.chatId,
|
|
584
|
+
userId: conversation.userId
|
|
585
|
+
});
|
|
586
|
+
let thread;
|
|
587
|
+
let adopted = false;
|
|
588
|
+
await this.#store.updateChat(conversation.chatId, (chat2) => {
|
|
589
|
+
this.#assertOwner(conversation, chat2.userId);
|
|
590
|
+
const existing = this.#threadFromMetadata(conversation, chat2.metadata);
|
|
591
|
+
if (existing) {
|
|
592
|
+
thread = existing;
|
|
593
|
+
adopted = true;
|
|
594
|
+
return void 0;
|
|
595
|
+
}
|
|
596
|
+
thread = AgentThread.root(conversation, declarationName);
|
|
597
|
+
adopted = false;
|
|
598
|
+
return { metadata: thread.toMetadata(chat2.metadata) };
|
|
599
|
+
});
|
|
600
|
+
if (adopted) {
|
|
601
|
+
await this.#assertValidParent(thread);
|
|
602
|
+
}
|
|
603
|
+
return thread;
|
|
604
|
+
}
|
|
605
|
+
async recordLatestTurn(conversation, streamId) {
|
|
606
|
+
return this.#updateLatestTurn(conversation, streamId);
|
|
607
|
+
}
|
|
608
|
+
async recordLatestTurnIfCurrent(conversation, streamId, expectedLastTurnId) {
|
|
609
|
+
return this.#updateLatestTurn(conversation, streamId, expectedLastTurnId);
|
|
610
|
+
}
|
|
611
|
+
async listTree(thread) {
|
|
612
|
+
const chats = await this.#store.listChats({
|
|
613
|
+
userId: thread.conversation.userId,
|
|
614
|
+
metadata: AgentThread.metadataFilter(thread.treeId)
|
|
615
|
+
});
|
|
616
|
+
return Promise.all(
|
|
617
|
+
chats.map(async (chat2) => {
|
|
618
|
+
const conversation = { chatId: chat2.id, userId: chat2.userId };
|
|
619
|
+
const member = this.#threadFromMetadata(conversation, chat2.metadata);
|
|
620
|
+
if (!member) {
|
|
621
|
+
throw new Error(
|
|
622
|
+
`AgentDirectory.listTree: chat "${chat2.id}" is missing Zukhruf metadata`
|
|
623
|
+
);
|
|
624
|
+
}
|
|
625
|
+
await this.#assertValidParent(member);
|
|
626
|
+
return member;
|
|
627
|
+
})
|
|
628
|
+
);
|
|
629
|
+
}
|
|
630
|
+
async resolve(thread, target) {
|
|
631
|
+
const path = thread.path.resolve(target);
|
|
632
|
+
const match = (await this.listTree(thread)).find(
|
|
633
|
+
(candidate) => candidate.path.equals(path)
|
|
634
|
+
);
|
|
635
|
+
if (match) return match;
|
|
636
|
+
throw new Error(`agent path "${path}" does not exist in this tree`);
|
|
637
|
+
}
|
|
638
|
+
async createChild(options) {
|
|
639
|
+
const path = options.parent.path.resolve(options.taskName);
|
|
640
|
+
const pathString = path.toString();
|
|
641
|
+
const conversation = {
|
|
642
|
+
chatId: _AgentDirectory.#childChatId(
|
|
643
|
+
options.parent.conversation.userId,
|
|
644
|
+
options.parent.treeId,
|
|
645
|
+
pathString
|
|
646
|
+
),
|
|
647
|
+
userId: options.parent.conversation.userId
|
|
648
|
+
};
|
|
649
|
+
const occupied = (await this.listTree(options.parent)).find(
|
|
650
|
+
(thread) => thread.path.equals(path)
|
|
651
|
+
);
|
|
652
|
+
if (occupied && occupied.conversation.chatId !== conversation.chatId) {
|
|
653
|
+
throw new Error(`agent path "${pathString}" already exists`);
|
|
654
|
+
}
|
|
655
|
+
const child = new AgentThread({
|
|
656
|
+
conversation,
|
|
657
|
+
treeId: options.parent.treeId,
|
|
658
|
+
path,
|
|
659
|
+
parentChatId: options.parent.conversation.chatId,
|
|
660
|
+
declarationName: options.declarationName
|
|
661
|
+
});
|
|
662
|
+
const storedChat = await this.#store.upsertChat({
|
|
663
|
+
id: conversation.chatId,
|
|
664
|
+
userId: conversation.userId,
|
|
665
|
+
metadata: child.toMetadata(void 0)
|
|
666
|
+
});
|
|
667
|
+
const stored = AgentThread.fromMetadata(
|
|
668
|
+
{ chatId: storedChat.id, userId: storedChat.userId },
|
|
669
|
+
storedChat.metadata
|
|
670
|
+
);
|
|
671
|
+
if (storedChat.userId !== conversation.userId || stored?.treeId !== child.treeId || !stored.path.equals(child.path) || stored.parentChatId !== child.parentChatId || stored.declarationName !== child.declarationName) {
|
|
672
|
+
throw new Error(`agent path "${pathString}" already exists`);
|
|
673
|
+
}
|
|
674
|
+
return stored;
|
|
675
|
+
}
|
|
676
|
+
static #childChatId(userId, treeId, path) {
|
|
677
|
+
return uuidv5(
|
|
678
|
+
`urn:deepagents:zukhruf:agent:${JSON.stringify([userId, treeId, path])}`,
|
|
679
|
+
uuidv5.URL
|
|
680
|
+
);
|
|
681
|
+
}
|
|
682
|
+
#assertOwner(conversation, storedUserId) {
|
|
683
|
+
if (storedUserId === conversation.userId) return;
|
|
684
|
+
throw new Error(
|
|
685
|
+
`chat "${conversation.chatId}" belongs to user "${storedUserId}", not "${conversation.userId}"`
|
|
686
|
+
);
|
|
687
|
+
}
|
|
688
|
+
#threadFromMetadata(conversation, metadata) {
|
|
689
|
+
const thread = AgentThread.fromMetadata(conversation, metadata);
|
|
690
|
+
if (!thread && AgentThread.hasReservedMetadata(metadata)) {
|
|
691
|
+
throw new Error(
|
|
692
|
+
`invalid Zukhruf metadata for chat "${conversation.chatId}"`
|
|
693
|
+
);
|
|
694
|
+
}
|
|
695
|
+
return thread;
|
|
696
|
+
}
|
|
697
|
+
async #assertValidParent(thread) {
|
|
698
|
+
if (thread.path.isRoot) return;
|
|
699
|
+
const parentChatId = thread.parentChatId;
|
|
700
|
+
if (!parentChatId) {
|
|
701
|
+
throw new Error(
|
|
702
|
+
`invalid Zukhruf parent for chat "${thread.conversation.chatId}"`
|
|
703
|
+
);
|
|
704
|
+
}
|
|
705
|
+
const parentChat = await this.#store.getChat(parentChatId);
|
|
706
|
+
if (!parentChat || parentChat.userId !== thread.conversation.userId) {
|
|
707
|
+
throw new Error(
|
|
708
|
+
`invalid Zukhruf parent for chat "${thread.conversation.chatId}"`
|
|
709
|
+
);
|
|
710
|
+
}
|
|
711
|
+
const parent = this.#threadFromMetadata(
|
|
712
|
+
{ chatId: parentChat.id, userId: parentChat.userId },
|
|
713
|
+
parentChat.metadata
|
|
714
|
+
);
|
|
715
|
+
const expectedPath = thread.path.parent;
|
|
716
|
+
if (!parent || !expectedPath || parent.treeId !== thread.treeId || !parent.path.equals(expectedPath)) {
|
|
717
|
+
throw new Error(
|
|
718
|
+
`invalid Zukhruf parent for chat "${thread.conversation.chatId}"`
|
|
719
|
+
);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
async #updateLatestTurn(conversation, streamId, ...expected) {
|
|
723
|
+
let result;
|
|
724
|
+
await this.#store.updateChat(conversation.chatId, (chat2) => {
|
|
725
|
+
this.#assertOwner(conversation, chat2.userId);
|
|
726
|
+
const thread = this.#threadFromMetadata(conversation, chat2.metadata);
|
|
727
|
+
if (!thread) {
|
|
728
|
+
throw new Error(
|
|
729
|
+
`AgentDirectory.recordLatestTurn: missing agent metadata for chat "${conversation.chatId}"`
|
|
730
|
+
);
|
|
731
|
+
}
|
|
732
|
+
if (expected.length > 0 && thread.lastTurnId !== expected[0]) {
|
|
733
|
+
result = void 0;
|
|
734
|
+
return void 0;
|
|
735
|
+
}
|
|
736
|
+
if (thread.lastTurnId === streamId) {
|
|
737
|
+
result = thread;
|
|
738
|
+
return void 0;
|
|
739
|
+
}
|
|
740
|
+
result = thread.withLatestTurn(streamId);
|
|
741
|
+
return { metadata: result.toMetadata(chat2.metadata) };
|
|
742
|
+
});
|
|
743
|
+
return result;
|
|
744
|
+
}
|
|
745
|
+
};
|
|
746
|
+
|
|
747
|
+
// packages/experimental/src/zukhruf/agent-status-projector.ts
|
|
748
|
+
import { isTextUIPart } from "ai";
|
|
39
749
|
import {
|
|
40
|
-
|
|
750
|
+
ContextEngine
|
|
41
751
|
} from "@deepagents/context";
|
|
42
|
-
|
|
43
|
-
|
|
752
|
+
|
|
753
|
+
// packages/experimental/src/zukhruf/mailbox/types.ts
|
|
754
|
+
import { randomUUID } from "node:crypto";
|
|
755
|
+
var MessageDeliveryMode = {
|
|
756
|
+
QueueOnly: "queue-only",
|
|
757
|
+
TriggerTurn: "trigger-turn"
|
|
758
|
+
};
|
|
759
|
+
var InterAgentCommunicationType = {
|
|
760
|
+
Message: "MESSAGE",
|
|
761
|
+
NewTask: "NEW_TASK",
|
|
762
|
+
FinalAnswer: "FINAL_ANSWER"
|
|
763
|
+
};
|
|
764
|
+
function createInterAgentCommunication(communication) {
|
|
765
|
+
const value = {
|
|
766
|
+
...communication,
|
|
767
|
+
id: communication.id ?? randomUUID(),
|
|
768
|
+
type: communication.type ?? InterAgentCommunicationType.Message,
|
|
769
|
+
otherRecipients: communication.otherRecipients ?? [],
|
|
770
|
+
triggerTurn: false
|
|
771
|
+
};
|
|
772
|
+
assertCommunication(value);
|
|
773
|
+
return value;
|
|
44
774
|
}
|
|
775
|
+
function assertCommunication(communication) {
|
|
776
|
+
if (!communication.id.trim()) {
|
|
777
|
+
throw new Error("inter-agent communication id cannot be empty");
|
|
778
|
+
}
|
|
779
|
+
if (!Object.values(InterAgentCommunicationType).includes(communication.type)) {
|
|
780
|
+
throw new Error("inter-agent communication type is invalid");
|
|
781
|
+
}
|
|
782
|
+
assertConversationId(communication.author, "author");
|
|
783
|
+
assertConversationId(communication.recipient, "recipient");
|
|
784
|
+
for (const recipient of communication.otherRecipients) {
|
|
785
|
+
assertConversationId(recipient, "other recipient");
|
|
786
|
+
}
|
|
787
|
+
if (!communication.content.trim()) {
|
|
788
|
+
throw new Error("inter-agent communication content cannot be empty");
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
function assertConversationId(value, label) {
|
|
792
|
+
if (!value.chatId.trim() || !value.userId.trim()) {
|
|
793
|
+
throw new Error(
|
|
794
|
+
`inter-agent communication ${label} requires chatId and userId`
|
|
795
|
+
);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// packages/experimental/src/zukhruf/agent-status-projector.ts
|
|
800
|
+
var AgentStatusProjector = class _AgentStatusProjector {
|
|
801
|
+
#store;
|
|
802
|
+
#streams;
|
|
803
|
+
#queue;
|
|
804
|
+
#mailbox;
|
|
805
|
+
#directory;
|
|
806
|
+
#approvals;
|
|
807
|
+
constructor(options) {
|
|
808
|
+
this.#store = options.store;
|
|
809
|
+
this.#streams = options.streams;
|
|
810
|
+
this.#queue = options.queue;
|
|
811
|
+
this.#mailbox = options.mailbox;
|
|
812
|
+
this.#directory = options.directory;
|
|
813
|
+
this.#approvals = options.approvals;
|
|
814
|
+
}
|
|
815
|
+
async projectListedAgent(currentTurn, thread) {
|
|
816
|
+
const messages = await this.#messages(thread);
|
|
817
|
+
const head = messages.at(-1);
|
|
818
|
+
const streamId = thread.lastTurnId ?? (head?.role === "assistant" ? head.id : void 0);
|
|
819
|
+
const stream = streamId ? await this.#streams.store.getStream(streamId) : void 0;
|
|
820
|
+
const activity = await this.#queue.getTurnActivity(thread.conversation);
|
|
821
|
+
let status = _AgentStatusProjector.#listedStatus(
|
|
822
|
+
stream?.status,
|
|
823
|
+
stream?.error,
|
|
824
|
+
head
|
|
825
|
+
);
|
|
826
|
+
if (stream?.status === "completed" && this.#approvals.isPaused(head)) {
|
|
827
|
+
status = "waiting_approval";
|
|
828
|
+
}
|
|
829
|
+
if (thread.conversation.chatId === currentTurn.chatId || activity === "running" || activity === "queued" && stream !== void 0) {
|
|
830
|
+
status = "running";
|
|
831
|
+
}
|
|
832
|
+
return {
|
|
833
|
+
agent_name: thread.path.toString(),
|
|
834
|
+
agent_status: status,
|
|
835
|
+
last_task_message: thread.path.isRoot ? "Main thread" : _AgentStatusProjector.#lastUserMessage(messages)
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
async projectTerminal(turn, thread) {
|
|
839
|
+
if (thread.parentChatId === null) return;
|
|
840
|
+
const stream = await this.#streams.store.getStream(turn.streamId);
|
|
841
|
+
if (!stream || stream.status !== "completed" && stream.status !== "failed" && stream.status !== "cancelled") {
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
const message = (await this.#messages(thread)).find(
|
|
845
|
+
(candidate) => candidate.role === "assistant" && candidate.id === turn.streamId
|
|
846
|
+
);
|
|
847
|
+
if (stream.status === "completed" && this.#approvals.isPaused(message)) {
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
const text = message?.role === "assistant" ? _AgentStatusProjector.#messageText(message) : "";
|
|
851
|
+
const content = stream.status === "failed" ? `Agent failed: ${stream.error || "unknown error"}` : stream.status === "cancelled" ? "Agent was interrupted." : text || "Agent completed without a text response.";
|
|
852
|
+
const parent = await this.#directory.load({
|
|
853
|
+
chatId: thread.parentChatId,
|
|
854
|
+
userId: thread.conversation.userId
|
|
855
|
+
});
|
|
856
|
+
await this.#mailbox.deliver(
|
|
857
|
+
createInterAgentCommunication({
|
|
858
|
+
id: `zukhruf:child-terminal:${turn.streamId}`,
|
|
859
|
+
type: InterAgentCommunicationType.FinalAnswer,
|
|
860
|
+
author: thread.conversation,
|
|
861
|
+
recipient: {
|
|
862
|
+
chatId: thread.parentChatId,
|
|
863
|
+
userId: thread.conversation.userId
|
|
864
|
+
},
|
|
865
|
+
content,
|
|
866
|
+
metadata: {
|
|
867
|
+
authorPath: thread.path.toString(),
|
|
868
|
+
recipientPath: parent?.path.toString() ?? thread.parentChatId,
|
|
869
|
+
streamId: turn.streamId,
|
|
870
|
+
status: stream.status
|
|
871
|
+
}
|
|
872
|
+
}),
|
|
873
|
+
MessageDeliveryMode.QueueOnly
|
|
874
|
+
);
|
|
875
|
+
}
|
|
876
|
+
async #messages(thread) {
|
|
877
|
+
const engine = new ContextEngine({
|
|
878
|
+
store: this.#store,
|
|
879
|
+
chatId: thread.conversation.chatId,
|
|
880
|
+
userId: thread.conversation.userId
|
|
881
|
+
});
|
|
882
|
+
return engine.getMessages();
|
|
883
|
+
}
|
|
884
|
+
static #listedStatus(status, error, head) {
|
|
885
|
+
switch (status) {
|
|
886
|
+
case "running":
|
|
887
|
+
return "running";
|
|
888
|
+
case "completed":
|
|
889
|
+
return {
|
|
890
|
+
completed: head?.role === "assistant" ? _AgentStatusProjector.#messageText(head) || null : null
|
|
891
|
+
};
|
|
892
|
+
case "failed":
|
|
893
|
+
return { errored: error || "Agent turn failed." };
|
|
894
|
+
case "cancelled":
|
|
895
|
+
return "interrupted";
|
|
896
|
+
case "queued":
|
|
897
|
+
case void 0:
|
|
898
|
+
return "pending_init";
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
static #lastUserMessage(messages) {
|
|
902
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
903
|
+
const message = messages[index];
|
|
904
|
+
if (message?.role === "user") {
|
|
905
|
+
return _AgentStatusProjector.#messageText(message) || null;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
return null;
|
|
909
|
+
}
|
|
910
|
+
static #messageText(message) {
|
|
911
|
+
return message.parts.filter(isTextUIPart).map((part) => part.text).join("\n").trim();
|
|
912
|
+
}
|
|
913
|
+
};
|
|
914
|
+
|
|
915
|
+
// packages/experimental/src/zukhruf/agent-turn-id.ts
|
|
916
|
+
import { v5 as uuidv52 } from "uuid";
|
|
917
|
+
var AgentTurnId = class _AgentTurnId {
|
|
918
|
+
static #prefix = "zukhruf-turn";
|
|
919
|
+
#value;
|
|
920
|
+
constructor(value) {
|
|
921
|
+
this.#value = value;
|
|
922
|
+
}
|
|
923
|
+
static fromRequest(conversation, requestId) {
|
|
924
|
+
if (!requestId.trim()) {
|
|
925
|
+
throw new Error("turn id cannot be empty");
|
|
926
|
+
}
|
|
927
|
+
const scope = _AgentTurnId.#scope(conversation);
|
|
928
|
+
return new _AgentTurnId(
|
|
929
|
+
`${_AgentTurnId.#prefix}:${scope}:${uuidv52(requestId, scope)}`
|
|
930
|
+
);
|
|
931
|
+
}
|
|
932
|
+
static random(conversation) {
|
|
933
|
+
return _AgentTurnId.fromRequest(conversation, crypto.randomUUID());
|
|
934
|
+
}
|
|
935
|
+
static assertOwner(conversation, streamId) {
|
|
936
|
+
const expectedPrefix = `${_AgentTurnId.#prefix}:${_AgentTurnId.#scope(conversation)}:`;
|
|
937
|
+
if (!streamId.startsWith(expectedPrefix)) {
|
|
938
|
+
throw new Error(
|
|
939
|
+
`stream "${streamId}" does not belong to conversation "${conversation.chatId}"`
|
|
940
|
+
);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
toString() {
|
|
944
|
+
return this.#value;
|
|
945
|
+
}
|
|
946
|
+
static #scope(conversation) {
|
|
947
|
+
if (!conversation.chatId.trim() || !conversation.userId.trim()) {
|
|
948
|
+
throw new Error("conversation requires non-empty chatId and userId");
|
|
949
|
+
}
|
|
950
|
+
return uuidv52(
|
|
951
|
+
JSON.stringify([conversation.userId, conversation.chatId]),
|
|
952
|
+
uuidv52.URL
|
|
953
|
+
);
|
|
954
|
+
}
|
|
955
|
+
};
|
|
956
|
+
|
|
957
|
+
// packages/experimental/src/zukhruf/agent-control-plane.ts
|
|
958
|
+
var AgentControlPlane = class _AgentControlPlane {
|
|
959
|
+
#root;
|
|
960
|
+
#streams;
|
|
961
|
+
#queue;
|
|
962
|
+
#mailbox;
|
|
963
|
+
#declarations;
|
|
964
|
+
#directory;
|
|
965
|
+
#statusProjector;
|
|
966
|
+
constructor(options) {
|
|
967
|
+
this.#root = options.root;
|
|
968
|
+
this.#streams = options.streams;
|
|
969
|
+
this.#queue = options.queue;
|
|
970
|
+
this.#mailbox = options.mailbox;
|
|
971
|
+
this.#declarations = options.declarations;
|
|
972
|
+
this.#directory = options.directory;
|
|
973
|
+
this.#statusProjector = options.statusProjector;
|
|
974
|
+
}
|
|
975
|
+
async resolve(conversation) {
|
|
976
|
+
const thread = await this.#directory.loadOrCreateRoot(
|
|
977
|
+
conversation,
|
|
978
|
+
this.#root.name
|
|
979
|
+
);
|
|
980
|
+
const declaration = this.#declarations.get(thread.declarationName);
|
|
981
|
+
if (!declaration) {
|
|
982
|
+
throw new Error(
|
|
983
|
+
`AgentControlPlane.resolve: unknown agent declaration "${thread.declarationName}"`
|
|
984
|
+
);
|
|
985
|
+
}
|
|
986
|
+
return { declaration, thread };
|
|
987
|
+
}
|
|
988
|
+
async enqueue(conversation, turn) {
|
|
989
|
+
if (!turn.id.trim()) {
|
|
990
|
+
throw new Error(
|
|
991
|
+
"enqueue: turn id is required \u2014 it names the ask, making retries idempotent"
|
|
992
|
+
);
|
|
993
|
+
}
|
|
994
|
+
await this.#directory.assertOwnerIfExists(conversation);
|
|
995
|
+
const streamId = AgentTurnId.fromRequest(conversation, turn.id).toString();
|
|
996
|
+
await this.#streams.register(streamId);
|
|
997
|
+
await this.#queue.push({
|
|
998
|
+
kind: "ask",
|
|
999
|
+
streamId,
|
|
1000
|
+
chatId: conversation.chatId,
|
|
1001
|
+
userId: conversation.userId,
|
|
1002
|
+
input: turn.input
|
|
1003
|
+
});
|
|
1004
|
+
return streamId;
|
|
1005
|
+
}
|
|
1006
|
+
recordLatestTurn(conversation, streamId) {
|
|
1007
|
+
return this.#directory.recordLatestTurn(conversation, streamId);
|
|
1008
|
+
}
|
|
1009
|
+
recordLatestTurnIfCurrent(conversation, streamId, expectedLastTurnId) {
|
|
1010
|
+
return this.#directory.recordLatestTurnIfCurrent(
|
|
1011
|
+
conversation,
|
|
1012
|
+
streamId,
|
|
1013
|
+
expectedLastTurnId
|
|
1014
|
+
);
|
|
1015
|
+
}
|
|
1016
|
+
async spawn(actor, input) {
|
|
1017
|
+
const childDeclaration = (actor.declaration.subagents ?? []).find(
|
|
1018
|
+
(subagent) => subagent.name === input.agentType
|
|
1019
|
+
);
|
|
1020
|
+
if (!childDeclaration) {
|
|
1021
|
+
throw new Error(
|
|
1022
|
+
`spawn_agent: agent type "${input.agentType}" is not a subagent of "${actor.declaration.name}"`
|
|
1023
|
+
);
|
|
1024
|
+
}
|
|
1025
|
+
let child;
|
|
1026
|
+
try {
|
|
1027
|
+
child = await this.#directory.createChild({
|
|
1028
|
+
parent: actor.thread,
|
|
1029
|
+
taskName: input.taskName,
|
|
1030
|
+
declarationName: childDeclaration.name
|
|
1031
|
+
});
|
|
1032
|
+
} catch (error) {
|
|
1033
|
+
if (error instanceof Error && error.message.startsWith("agent path ")) {
|
|
1034
|
+
throw new Error(`spawn_agent: ${error.message}`);
|
|
1035
|
+
}
|
|
1036
|
+
throw error;
|
|
1037
|
+
}
|
|
1038
|
+
const childPath = child.path.toString();
|
|
1039
|
+
const requestId = _AgentControlPlane.#initialTurnId(
|
|
1040
|
+
child.conversation.chatId
|
|
1041
|
+
);
|
|
1042
|
+
const streamId = AgentTurnId.fromRequest(
|
|
1043
|
+
child.conversation,
|
|
1044
|
+
requestId
|
|
1045
|
+
).toString();
|
|
1046
|
+
const status = await this.#streams.store.getStreamStatus(streamId);
|
|
1047
|
+
if (status === "completed" || status === "failed" || status === "cancelled") {
|
|
1048
|
+
throw new Error(
|
|
1049
|
+
`spawn_agent: agent path "${childPath}" already finished with status "${status}"`
|
|
1050
|
+
);
|
|
1051
|
+
}
|
|
1052
|
+
await this.enqueue(child.conversation, {
|
|
1053
|
+
id: requestId,
|
|
1054
|
+
input: input.message
|
|
1055
|
+
});
|
|
1056
|
+
return { task_name: input.taskName, agent_path: childPath };
|
|
1057
|
+
}
|
|
1058
|
+
async sendMessage(actor, input) {
|
|
1059
|
+
return this.#deliverAgentMessage(actor, input, {
|
|
1060
|
+
type: InterAgentCommunicationType.Message,
|
|
1061
|
+
mode: MessageDeliveryMode.QueueOnly,
|
|
1062
|
+
rejectRoot: false
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
async followupTask(actor, input) {
|
|
1066
|
+
return this.#deliverAgentMessage(actor, input, {
|
|
1067
|
+
type: InterAgentCommunicationType.NewTask,
|
|
1068
|
+
mode: MessageDeliveryMode.TriggerTurn,
|
|
1069
|
+
rejectRoot: true
|
|
1070
|
+
});
|
|
1071
|
+
}
|
|
1072
|
+
async listAgents(actor, pathPrefix) {
|
|
1073
|
+
const prefix = pathPrefix ? actor.thread.path.resolve(pathPrefix) : void 0;
|
|
1074
|
+
const threads = await this.#directory.listTree(actor.thread);
|
|
1075
|
+
const agents = await Promise.all(
|
|
1076
|
+
threads.flatMap((thread) => {
|
|
1077
|
+
if (prefix && !prefix.contains(thread.path)) return [];
|
|
1078
|
+
return [this.#statusProjector.projectListedAgent(actor.turn, thread)];
|
|
1079
|
+
})
|
|
1080
|
+
);
|
|
1081
|
+
agents.sort(
|
|
1082
|
+
(left, right) => left.agent_name.localeCompare(right.agent_name)
|
|
1083
|
+
);
|
|
1084
|
+
return { agents };
|
|
1085
|
+
}
|
|
1086
|
+
async projectTerminal(turn, thread) {
|
|
1087
|
+
await this.#statusProjector.projectTerminal(turn, thread);
|
|
1088
|
+
}
|
|
1089
|
+
async #deliverAgentMessage(actor, input, options) {
|
|
1090
|
+
const target = await this.#directory.resolve(actor.thread, input.target);
|
|
1091
|
+
if (options.rejectRoot && target.path.isRoot) {
|
|
1092
|
+
throw new Error(
|
|
1093
|
+
"followup_task: the root agent cannot receive a follow-up"
|
|
1094
|
+
);
|
|
1095
|
+
}
|
|
1096
|
+
await this.#mailbox.deliver(
|
|
1097
|
+
createInterAgentCommunication({
|
|
1098
|
+
type: options.type,
|
|
1099
|
+
author: actor.thread.conversation,
|
|
1100
|
+
recipient: target.conversation,
|
|
1101
|
+
content: input.message,
|
|
1102
|
+
metadata: {
|
|
1103
|
+
authorPath: actor.thread.path.toString(),
|
|
1104
|
+
recipientPath: target.path.toString()
|
|
1105
|
+
}
|
|
1106
|
+
}),
|
|
1107
|
+
options.mode
|
|
1108
|
+
);
|
|
1109
|
+
return { target: target.path.toString() };
|
|
1110
|
+
}
|
|
1111
|
+
static #initialTurnId(chatId) {
|
|
1112
|
+
return uuidv53(`urn:deepagents:zukhruf:initial-turn:${chatId}`, uuidv53.URL);
|
|
1113
|
+
}
|
|
1114
|
+
};
|
|
1115
|
+
|
|
1116
|
+
// packages/experimental/src/zukhruf/agent-turn-executor.ts
|
|
1117
|
+
import {
|
|
1118
|
+
ContextEngine as ContextEngine2,
|
|
1119
|
+
agent,
|
|
1120
|
+
assistant,
|
|
1121
|
+
chat,
|
|
1122
|
+
user
|
|
1123
|
+
} from "@deepagents/context";
|
|
1124
|
+
|
|
1125
|
+
// packages/experimental/src/zukhruf/list-agents.ts
|
|
1126
|
+
import { tool } from "ai";
|
|
1127
|
+
import { z } from "zod";
|
|
1128
|
+
var listAgentsInputSchema = z.object({
|
|
1129
|
+
path_prefix: z.string().trim().min(1).describe(
|
|
1130
|
+
"Task-path prefix without a trailing slash. Omit to list the whole tree."
|
|
1131
|
+
).optional()
|
|
1132
|
+
});
|
|
1133
|
+
var listAgentsTool = tool({
|
|
1134
|
+
description: "List live agents in the current root thread tree. Optionally filter by task-path prefix.",
|
|
1135
|
+
inputSchema: listAgentsInputSchema,
|
|
1136
|
+
execute: async ({ path_prefix }, { context }) => context.controlPlane.listAgents(context.actor, path_prefix)
|
|
1137
|
+
});
|
|
1138
|
+
|
|
1139
|
+
// packages/experimental/src/zukhruf/message-tools.ts
|
|
1140
|
+
import { tool as tool2 } from "ai";
|
|
1141
|
+
import { z as z2 } from "zod";
|
|
1142
|
+
var agentMessageInputSchema = z2.object({
|
|
1143
|
+
target: z2.string().trim().min(1).describe(
|
|
1144
|
+
"The canonical /root/... path, or a descendant-relative target name."
|
|
1145
|
+
),
|
|
1146
|
+
message: z2.string().trim().min(1).describe("The message or follow-up task.")
|
|
1147
|
+
});
|
|
1148
|
+
var sendMessageTool = tool2({
|
|
1149
|
+
description: "Queue a message for another agent. Address siblings with their canonical /root/... path.",
|
|
1150
|
+
inputSchema: agentMessageInputSchema,
|
|
1151
|
+
execute: async (input, { context }) => context.controlPlane.sendMessage(context.actor, input)
|
|
1152
|
+
});
|
|
1153
|
+
var followupTaskTool = tool2({
|
|
1154
|
+
description: "Send a follow-up task to an existing non-root agent and wake its thread.",
|
|
1155
|
+
inputSchema: agentMessageInputSchema,
|
|
1156
|
+
execute: async (input, { context }) => context.controlPlane.followupTask(context.actor, input)
|
|
1157
|
+
});
|
|
45
1158
|
|
|
46
|
-
// packages/experimental/src/zukhruf/
|
|
47
|
-
import {
|
|
48
|
-
import {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
57
|
-
var
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
1159
|
+
// packages/experimental/src/zukhruf/spawn-agent.ts
|
|
1160
|
+
import { tool as tool3 } from "ai";
|
|
1161
|
+
import { z as z3 } from "zod";
|
|
1162
|
+
var spawnAgentInputSchema = z3.object({
|
|
1163
|
+
agent_type: z3.string().trim().min(1).describe("The name of one available subagent declaration."),
|
|
1164
|
+
task_name: z3.string().trim().min(1).refine(
|
|
1165
|
+
(value) => value !== "." && value !== ".." && !value.includes("/"),
|
|
1166
|
+
"task_name must be one non-empty path segment"
|
|
1167
|
+
).describe("One path segment naming this independent agent task."),
|
|
1168
|
+
message: z3.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent.")
|
|
1169
|
+
});
|
|
1170
|
+
var spawnAgentTool = tool3({
|
|
1171
|
+
description: ({ context }) => {
|
|
1172
|
+
const available = (context.actor.declaration.subagents ?? []).map((subagent) => subagent.name).join(", ");
|
|
1173
|
+
return `Spawn an independent subagent. Available agent types: ${available || "none"}.`;
|
|
1174
|
+
},
|
|
1175
|
+
inputSchema: spawnAgentInputSchema,
|
|
1176
|
+
execute: async ({ agent_type, task_name, message }, { context }) => context.controlPlane.spawn(context.actor, {
|
|
1177
|
+
agentType: agent_type,
|
|
1178
|
+
taskName: task_name,
|
|
1179
|
+
message
|
|
1180
|
+
})
|
|
1181
|
+
});
|
|
1182
|
+
|
|
1183
|
+
// packages/experimental/src/zukhruf/agent-turn-executor.ts
|
|
1184
|
+
var AgentTurnExecutor = class {
|
|
1185
|
+
#store;
|
|
1186
|
+
#streams;
|
|
1187
|
+
#controlPlane;
|
|
1188
|
+
#mailbox;
|
|
1189
|
+
#approvals;
|
|
1190
|
+
constructor(options) {
|
|
1191
|
+
this.#store = options.store;
|
|
1192
|
+
this.#streams = options.streams;
|
|
1193
|
+
this.#controlPlane = options.controlPlane;
|
|
1194
|
+
this.#mailbox = options.mailbox;
|
|
1195
|
+
this.#approvals = options.approvals;
|
|
1196
|
+
}
|
|
1197
|
+
async execute(turn, context) {
|
|
1198
|
+
if (await this.#projectSkippedTerminalTurn(turn)) return;
|
|
1199
|
+
let parked = false;
|
|
1200
|
+
await this.#mailbox.beginTurn(turn);
|
|
1201
|
+
try {
|
|
1202
|
+
await this.#executeTurn(turn, {
|
|
1203
|
+
...context,
|
|
1204
|
+
park: async () => {
|
|
1205
|
+
parked = true;
|
|
1206
|
+
await context.park();
|
|
1207
|
+
}
|
|
1208
|
+
});
|
|
1209
|
+
} finally {
|
|
1210
|
+
await this.#mailbox.endTurn(turn, { parked });
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
async #executeTurn(turn, { signal, park }) {
|
|
1214
|
+
if (await this.#projectSkippedTerminalTurn(turn)) return;
|
|
1215
|
+
const { declaration, thread } = await this.#controlPlane.resolve(turn);
|
|
1216
|
+
const engine = this.#engineFor(turn).set(...declaration.instructions);
|
|
1217
|
+
if (turn.kind === "ask" || turn.kind === "mailbox") {
|
|
81
1218
|
const head = (await engine.getMessages()).at(-1);
|
|
82
|
-
if (
|
|
1219
|
+
if (this.#approvals.isPaused(head)) {
|
|
83
1220
|
await park();
|
|
84
1221
|
return;
|
|
85
1222
|
}
|
|
86
|
-
engine.set(
|
|
87
|
-
user(turn.input),
|
|
88
|
-
assistant({ id: turn.streamId, role: "assistant", parts: [] })
|
|
89
|
-
);
|
|
90
|
-
await engine.save({ branch: true });
|
|
91
1223
|
}
|
|
1224
|
+
const communications = turn.kind === "ask" ? await this.#mailbox.drainLeadingQueueOnly(turn) : turn.kind === "mailbox" ? await this.#mailbox.drain(turn) : [];
|
|
1225
|
+
if (turn.kind === "mailbox" && communications.length === 0) {
|
|
1226
|
+
await this.#streams.store.updateStreamStatus(turn.streamId, "completed");
|
|
1227
|
+
return;
|
|
1228
|
+
}
|
|
1229
|
+
await this.#controlPlane.recordLatestTurn(turn, turn.streamId);
|
|
1230
|
+
await this.#prepareChain(turn, engine, communications);
|
|
92
1231
|
const sandbox = await declaration.sandbox({
|
|
93
1232
|
chatId: turn.chatId,
|
|
94
1233
|
userId: turn.userId
|
|
95
1234
|
});
|
|
1235
|
+
if (await this.#projectSkippedTerminalTurn(turn)) return;
|
|
1236
|
+
if (!await this.#streams.claim(turn.streamId)) {
|
|
1237
|
+
await this.#projectSkippedTerminalTurn(turn);
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1240
|
+
const mailboxState = { firstRequest: true };
|
|
96
1241
|
const ai = agent({
|
|
97
1242
|
name: declaration.name,
|
|
98
1243
|
model: declaration.model,
|
|
99
1244
|
sandbox,
|
|
100
1245
|
context: engine,
|
|
101
|
-
tools:
|
|
1246
|
+
tools: {
|
|
1247
|
+
...declaration.tools,
|
|
1248
|
+
spawn_agent: spawnAgentTool,
|
|
1249
|
+
send_message: sendMessageTool,
|
|
1250
|
+
followup_task: followupTaskTool,
|
|
1251
|
+
list_agents: listAgentsTool
|
|
1252
|
+
},
|
|
1253
|
+
telemetry: declaration.telemetry,
|
|
1254
|
+
prepareStepInput: () => this.#prepareStepInput(turn, mailboxState)
|
|
102
1255
|
});
|
|
103
1256
|
const abort = new AbortController();
|
|
104
1257
|
const onWorkerAbort = () => abort.abort();
|
|
105
1258
|
signal.addEventListener("abort", onWorkerAbort, { once: true });
|
|
106
1259
|
try {
|
|
107
|
-
const
|
|
108
|
-
|
|
1260
|
+
const setupCancellation = this.#streams.monitorCancellation(
|
|
1261
|
+
turn.streamId,
|
|
1262
|
+
() => abort.abort()
|
|
1263
|
+
);
|
|
1264
|
+
let stream;
|
|
1265
|
+
try {
|
|
1266
|
+
stream = await chat(ai, {
|
|
1267
|
+
abortSignal: abort.signal,
|
|
1268
|
+
contextVariables: {
|
|
1269
|
+
controlPlane: this.#controlPlane,
|
|
1270
|
+
actor: { turn, thread, declaration }
|
|
1271
|
+
}
|
|
1272
|
+
});
|
|
1273
|
+
} finally {
|
|
1274
|
+
await setupCancellation[Symbol.asyncDispose]();
|
|
1275
|
+
}
|
|
1276
|
+
await this.#streams.persist(stream, turn.streamId, {
|
|
1277
|
+
preclaimed: true,
|
|
109
1278
|
onCancelDetected: () => abort.abort()
|
|
110
1279
|
});
|
|
1280
|
+
if (turn.kind === "continuation") {
|
|
1281
|
+
await this.#reconcileTerminalContinuation(turn);
|
|
1282
|
+
}
|
|
1283
|
+
await this.#controlPlane.projectTerminal(turn, thread);
|
|
111
1284
|
} finally {
|
|
112
1285
|
signal.removeEventListener("abort", onWorkerAbort);
|
|
113
1286
|
}
|
|
114
1287
|
}
|
|
115
|
-
async
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
if (
|
|
119
|
-
|
|
120
|
-
|
|
1288
|
+
async #projectSkippedTerminalTurn(turn) {
|
|
1289
|
+
const status = await this.#streams.store.getStreamStatus(turn.streamId);
|
|
1290
|
+
if (status === "queued" || status === "running") return false;
|
|
1291
|
+
if (status === void 0 || turn.kind === "mailbox") return true;
|
|
1292
|
+
if (turn.kind === "continuation") {
|
|
1293
|
+
await this.#reconcileTerminalContinuation(turn);
|
|
1294
|
+
}
|
|
1295
|
+
const { thread } = await this.#controlPlane.resolve(turn);
|
|
1296
|
+
if (thread.lastTurnId === void 0 || thread.lastTurnId === turn.streamId) {
|
|
1297
|
+
await this.#controlPlane.recordLatestTurnIfCurrent(
|
|
1298
|
+
turn,
|
|
1299
|
+
turn.streamId,
|
|
1300
|
+
thread.lastTurnId
|
|
121
1301
|
);
|
|
122
1302
|
}
|
|
123
|
-
|
|
124
|
-
|
|
1303
|
+
await this.#controlPlane.projectTerminal(turn, thread);
|
|
1304
|
+
return true;
|
|
1305
|
+
}
|
|
1306
|
+
async #reconcileTerminalContinuation(turn) {
|
|
1307
|
+
const stream = await this.#streams.store.getStream(turn.streamId);
|
|
1308
|
+
if (stream?.status !== "completed" && stream?.status !== "failed" && stream?.status !== "cancelled") {
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1311
|
+
await this.#approvals.reconcileTerminalContinuation(
|
|
1312
|
+
turn,
|
|
1313
|
+
turn.streamId,
|
|
1314
|
+
stream.status,
|
|
1315
|
+
stream.error
|
|
125
1316
|
);
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
1317
|
+
}
|
|
1318
|
+
async #prepareChain(turn, engine, communications) {
|
|
1319
|
+
if (turn.kind === "ask") {
|
|
1320
|
+
engine.set(
|
|
1321
|
+
...communications.map(
|
|
1322
|
+
(communication) => user(this.#mailboxInputMessage(communication))
|
|
1323
|
+
),
|
|
1324
|
+
user(turn.input),
|
|
1325
|
+
assistant({ id: turn.streamId, role: "assistant", parts: [] })
|
|
129
1326
|
);
|
|
1327
|
+
await engine.save({ branch: true });
|
|
1328
|
+
} else if (turn.kind === "mailbox") {
|
|
1329
|
+
engine.set(
|
|
1330
|
+
...communications.map(
|
|
1331
|
+
(communication) => user(this.#mailboxInputMessage(communication))
|
|
1332
|
+
),
|
|
1333
|
+
assistant({ id: turn.streamId, role: "assistant", parts: [] })
|
|
1334
|
+
);
|
|
1335
|
+
await engine.save({ branch: true });
|
|
130
1336
|
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
1337
|
+
}
|
|
1338
|
+
async #prepareStepInput(turn, state) {
|
|
1339
|
+
const communications = turn.kind === "ask" && state.firstRequest ? await this.#mailbox.drainLeadingQueueOnly(turn) : await this.#mailbox.drain(turn);
|
|
1340
|
+
state.firstRequest = false;
|
|
1341
|
+
return communications.length === 0 ? void 0 : communications.map(
|
|
1342
|
+
(communication) => this.#mailboxInputMessage(communication)
|
|
1343
|
+
);
|
|
1344
|
+
}
|
|
1345
|
+
#engineFor({ chatId, userId }) {
|
|
1346
|
+
return new ContextEngine2({ store: this.#store, chatId, userId });
|
|
1347
|
+
}
|
|
1348
|
+
#mailboxInputMessage(communication) {
|
|
1349
|
+
return {
|
|
1350
|
+
id: crypto.randomUUID(),
|
|
1351
|
+
role: "user",
|
|
1352
|
+
parts: [
|
|
1353
|
+
{
|
|
1354
|
+
type: "text",
|
|
1355
|
+
text: this.#renderInterAgentCommunication(communication)
|
|
1356
|
+
}
|
|
1357
|
+
],
|
|
1358
|
+
metadata: { interAgentCommunication: communication }
|
|
138
1359
|
};
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
1360
|
+
}
|
|
1361
|
+
#renderInterAgentCommunication(communication) {
|
|
1362
|
+
const recipientPath = communication.metadata?.recipientPath;
|
|
1363
|
+
const authorPath = communication.metadata?.authorPath;
|
|
1364
|
+
const taskName = typeof recipientPath === "string" ? recipientPath : communication.recipient.chatId;
|
|
1365
|
+
const sender = typeof authorPath === "string" ? authorPath : communication.author.chatId;
|
|
1366
|
+
return `Message Type: ${communication.type}
|
|
1367
|
+
Task name: ${taskName}
|
|
1368
|
+
Sender: ${sender}
|
|
1369
|
+
Payload:
|
|
1370
|
+
${communication.content}`;
|
|
1371
|
+
}
|
|
1372
|
+
};
|
|
1373
|
+
|
|
1374
|
+
// packages/experimental/src/zukhruf/approval-controller.ts
|
|
1375
|
+
import {
|
|
1376
|
+
isToolUIPart
|
|
1377
|
+
} from "ai";
|
|
1378
|
+
import {
|
|
1379
|
+
ContextEngine as ContextEngine3,
|
|
1380
|
+
assistant as assistant2
|
|
1381
|
+
} from "@deepagents/context";
|
|
1382
|
+
var ApprovalController = class _ApprovalController {
|
|
1383
|
+
static #settledToolStates = /* @__PURE__ */ new Set([
|
|
1384
|
+
"output-available",
|
|
1385
|
+
"output-error",
|
|
1386
|
+
"output-denied"
|
|
1387
|
+
]);
|
|
1388
|
+
#store;
|
|
1389
|
+
#streams;
|
|
1390
|
+
#queue;
|
|
1391
|
+
#mutex;
|
|
1392
|
+
constructor(options) {
|
|
1393
|
+
this.#store = options.store;
|
|
1394
|
+
this.#streams = options.streams;
|
|
1395
|
+
this.#queue = options.queue;
|
|
1396
|
+
this.#mutex = options.mutex;
|
|
1397
|
+
}
|
|
1398
|
+
isPaused(message) {
|
|
1399
|
+
return message?.role === "assistant" && this.#pendingToolPart(message) !== void 0;
|
|
1400
|
+
}
|
|
1401
|
+
approve(conversation, input) {
|
|
1402
|
+
return this.#respond("approve", conversation, input.toolCallId, {
|
|
1403
|
+
approved: true
|
|
1404
|
+
});
|
|
1405
|
+
}
|
|
1406
|
+
deny(conversation, input) {
|
|
1407
|
+
return this.#respond("deny", conversation, input.toolCallId, {
|
|
1408
|
+
approved: false,
|
|
1409
|
+
reason: input.reason
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
async settleDeniedApprovals(conversation, streamId) {
|
|
1413
|
+
await this.#mutex.runExclusive(conversation.chatId, async () => {
|
|
1414
|
+
const engine = this.#engineFor(conversation);
|
|
1415
|
+
const head = (await engine.getMessages()).at(-1);
|
|
1416
|
+
if (head?.role !== "assistant" || head.id !== streamId) return;
|
|
1417
|
+
const denied = head.parts.filter(
|
|
1418
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === false
|
|
1419
|
+
);
|
|
1420
|
+
if (denied.length === 0) return;
|
|
1421
|
+
const updated = {
|
|
1422
|
+
...head,
|
|
1423
|
+
parts: head.parts.map(
|
|
1424
|
+
(part) => denied.includes(part) ? { ...part, state: "output-denied" } : part
|
|
1425
|
+
)
|
|
1426
|
+
};
|
|
1427
|
+
await engine.continue(assistant2(updated));
|
|
1428
|
+
});
|
|
1429
|
+
}
|
|
1430
|
+
async settleFailedApprovals(conversation, streamId, error) {
|
|
1431
|
+
await this.#mutex.runExclusive(conversation.chatId, async () => {
|
|
1432
|
+
const engine = this.#engineFor(conversation);
|
|
1433
|
+
const head = (await engine.getMessages()).at(-1);
|
|
1434
|
+
if (head?.role !== "assistant" || head.id !== streamId) return;
|
|
1435
|
+
const responded = head.parts.filter(
|
|
1436
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded"
|
|
1437
|
+
);
|
|
1438
|
+
if (responded.length === 0) return;
|
|
1439
|
+
const updated = {
|
|
1440
|
+
...head,
|
|
1441
|
+
parts: head.parts.map(
|
|
1442
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded" ? part.approval.approved === false ? { ...part, state: "output-denied" } : { ...part, state: "output-error", errorText: error } : part
|
|
1443
|
+
)
|
|
1444
|
+
};
|
|
1445
|
+
await engine.continue(assistant2(updated));
|
|
1446
|
+
});
|
|
1447
|
+
}
|
|
1448
|
+
async reconcileTerminalContinuation(conversation, streamId, status, error) {
|
|
1449
|
+
if (status === "completed") {
|
|
1450
|
+
await this.settleDeniedApprovals(conversation, streamId);
|
|
1451
|
+
} else {
|
|
1452
|
+
await this.settleFailedApprovals(
|
|
1453
|
+
conversation,
|
|
1454
|
+
streamId,
|
|
1455
|
+
error ?? (status === "cancelled" ? "approval continuation cancelled" : "approval continuation failed")
|
|
1456
|
+
);
|
|
1457
|
+
}
|
|
1458
|
+
await this.#queue.resumeParked(conversation.chatId);
|
|
1459
|
+
}
|
|
1460
|
+
async #respond(operation, conversation, toolCallId, approval) {
|
|
1461
|
+
const result = await this.#mutex.runExclusive(
|
|
1462
|
+
conversation.chatId,
|
|
1463
|
+
async () => {
|
|
1464
|
+
const engine = this.#engineFor(conversation);
|
|
1465
|
+
const head = (await engine.getMessages()).at(-1);
|
|
1466
|
+
if (head?.role !== "assistant") {
|
|
1467
|
+
throw new Error(
|
|
1468
|
+
`ApprovalController.${operation}: no paused turn \u2014 the chain head is not an assistant message`
|
|
1469
|
+
);
|
|
1470
|
+
}
|
|
1471
|
+
const part = this.#findToolPart(head, toolCallId);
|
|
1472
|
+
if (!part) {
|
|
1473
|
+
throw new Error(
|
|
1474
|
+
`ApprovalController.${operation}: no tool call "${toolCallId}" on the paused turn`
|
|
1475
|
+
);
|
|
1476
|
+
}
|
|
1477
|
+
if (part.approval?.approved !== void 0 && part.approval.approved !== approval.approved) {
|
|
1478
|
+
throw new Error(
|
|
1479
|
+
`ApprovalController.${operation}: approval already answered with a different decision`
|
|
1480
|
+
);
|
|
1481
|
+
}
|
|
1482
|
+
let updated = head;
|
|
1483
|
+
let answered = part;
|
|
1484
|
+
if (part.state === "approval-requested") {
|
|
1485
|
+
const responded = {
|
|
1486
|
+
...part,
|
|
1487
|
+
state: "approval-responded",
|
|
1488
|
+
approval: { ...part.approval, ...approval }
|
|
1489
|
+
};
|
|
1490
|
+
updated = {
|
|
1491
|
+
...head,
|
|
1492
|
+
parts: head.parts.map(
|
|
1493
|
+
(candidate) => candidate === part ? responded : candidate
|
|
1494
|
+
)
|
|
1495
|
+
};
|
|
1496
|
+
await engine.continue(assistant2(updated));
|
|
1497
|
+
answered = responded;
|
|
1498
|
+
}
|
|
1499
|
+
return {
|
|
1500
|
+
id: updated.id,
|
|
1501
|
+
hasUnansweredApprovals: this.#hasUnansweredApprovals(updated),
|
|
1502
|
+
shouldSchedule: answered.state === "approval-responded"
|
|
1503
|
+
};
|
|
1504
|
+
}
|
|
1505
|
+
);
|
|
1506
|
+
if (!result.hasUnansweredApprovals) {
|
|
1507
|
+
if (result.shouldSchedule) {
|
|
1508
|
+
await this.#scheduleContinuation(conversation, result.id);
|
|
1509
|
+
} else {
|
|
1510
|
+
await this.#queue.resumeParked(conversation.chatId);
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
return { id: result.id, stream: this.#streams.watch(result.id) };
|
|
1514
|
+
}
|
|
1515
|
+
async #scheduleContinuation(conversation, streamId) {
|
|
1516
|
+
let status = await this.#streams.store.getStreamStatus(streamId);
|
|
1517
|
+
if (status === "completed") {
|
|
1518
|
+
try {
|
|
1519
|
+
await this.#streams.reopen(streamId);
|
|
1520
|
+
status = "queued";
|
|
1521
|
+
} catch (error) {
|
|
1522
|
+
status = await this.#streams.store.getStreamStatus(streamId);
|
|
1523
|
+
if (status !== "queued" && status !== "running") throw error;
|
|
1524
|
+
}
|
|
1525
|
+
} else if (status !== "queued" && status !== "running") {
|
|
1526
|
+
return;
|
|
1527
|
+
}
|
|
1528
|
+
if (status !== "running") {
|
|
1529
|
+
await this.#queue.push({
|
|
1530
|
+
kind: "continuation",
|
|
1531
|
+
streamId,
|
|
1532
|
+
chatId: conversation.chatId,
|
|
1533
|
+
userId: conversation.userId
|
|
1534
|
+
});
|
|
1535
|
+
}
|
|
1536
|
+
await this.#queue.resumeParked(conversation.chatId);
|
|
1537
|
+
}
|
|
1538
|
+
#pendingToolPart(message) {
|
|
1539
|
+
return message.parts.find(
|
|
1540
|
+
(part) => isToolUIPart(part) && !_ApprovalController.#settledToolStates.has(part.state)
|
|
1541
|
+
);
|
|
1542
|
+
}
|
|
1543
|
+
#hasUnansweredApprovals(message) {
|
|
1544
|
+
return message.parts.some(
|
|
1545
|
+
(part) => isToolUIPart(part) && part.state === "approval-requested"
|
|
1546
|
+
);
|
|
1547
|
+
}
|
|
1548
|
+
#findToolPart(message, toolCallId) {
|
|
1549
|
+
return message.parts.find(
|
|
1550
|
+
(part) => isToolUIPart(part) && part.toolCallId === toolCallId
|
|
1551
|
+
);
|
|
1552
|
+
}
|
|
1553
|
+
#engineFor({ chatId, userId }) {
|
|
1554
|
+
return new ContextEngine3({ store: this.#store, chatId, userId });
|
|
1555
|
+
}
|
|
1556
|
+
};
|
|
1557
|
+
|
|
1558
|
+
// packages/experimental/src/zukhruf/mailbox/coordinator.ts
|
|
1559
|
+
var MailboxCoordinator = class {
|
|
1560
|
+
#store;
|
|
1561
|
+
#queue;
|
|
1562
|
+
#streams;
|
|
1563
|
+
#wakeRequests = /* @__PURE__ */ new Map();
|
|
1564
|
+
constructor(options) {
|
|
1565
|
+
this.#store = options.store;
|
|
1566
|
+
this.#queue = options.queue;
|
|
1567
|
+
this.#streams = options.streams;
|
|
1568
|
+
}
|
|
1569
|
+
async deliver(communication, mode) {
|
|
1570
|
+
const delivered = {
|
|
1571
|
+
...communication,
|
|
1572
|
+
type: mode === MessageDeliveryMode.TriggerTurn ? InterAgentCommunicationType.NewTask : communication.type,
|
|
1573
|
+
triggerTurn: mode === MessageDeliveryMode.TriggerTurn
|
|
142
1574
|
};
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
1575
|
+
assertCommunication(delivered);
|
|
1576
|
+
const { recipientActive } = await this.#store.enqueue(delivered);
|
|
1577
|
+
if (delivered.triggerTurn || recipientActive) {
|
|
1578
|
+
await this.#scheduleWake(delivered.recipient);
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
beginTurn(turn) {
|
|
1582
|
+
return this.#store.beginTurn(turn, turn.streamId);
|
|
1583
|
+
}
|
|
1584
|
+
async endTurn(turn, options = {}) {
|
|
1585
|
+
const { hasPending, turnEnded } = await this.#store.endTurn(
|
|
1586
|
+
turn,
|
|
1587
|
+
turn.streamId
|
|
1588
|
+
);
|
|
1589
|
+
if (turnEnded && hasPending && !options.parked) {
|
|
1590
|
+
await this.#scheduleWake(turn);
|
|
148
1591
|
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
1592
|
+
}
|
|
1593
|
+
drainLeadingQueueOnly(recipient) {
|
|
1594
|
+
return this.#store.drainLeadingQueueOnly(recipient);
|
|
1595
|
+
}
|
|
1596
|
+
drain(recipient) {
|
|
1597
|
+
return this.#store.drain(recipient);
|
|
1598
|
+
}
|
|
1599
|
+
#scheduleWake(target) {
|
|
1600
|
+
const key = this.#conversationKey(target);
|
|
1601
|
+
const existing = this.#wakeRequests.get(key);
|
|
1602
|
+
if (existing) return existing;
|
|
1603
|
+
const request = (async () => {
|
|
1604
|
+
const wakeId = AgentTurnId.random(target).toString();
|
|
1605
|
+
await this.#streams.register(wakeId);
|
|
1606
|
+
try {
|
|
1607
|
+
await this.#queue.push({
|
|
1608
|
+
kind: "mailbox",
|
|
1609
|
+
streamId: wakeId,
|
|
1610
|
+
chatId: target.chatId,
|
|
1611
|
+
userId: target.userId
|
|
1612
|
+
});
|
|
1613
|
+
} catch (error) {
|
|
1614
|
+
await this.#streams.store.updateStreamStatus(wakeId, "failed", {
|
|
1615
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1616
|
+
});
|
|
1617
|
+
throw error;
|
|
1618
|
+
}
|
|
1619
|
+
})();
|
|
1620
|
+
this.#wakeRequests.set(key, request);
|
|
1621
|
+
const clearRequest = () => {
|
|
1622
|
+
if (this.#wakeRequests.get(key) === request) {
|
|
1623
|
+
this.#wakeRequests.delete(key);
|
|
1624
|
+
}
|
|
1625
|
+
};
|
|
1626
|
+
void request.then(clearRequest, clearRequest);
|
|
1627
|
+
return request;
|
|
1628
|
+
}
|
|
1629
|
+
#conversationKey(conversation) {
|
|
1630
|
+
return JSON.stringify([conversation.chatId, conversation.userId]);
|
|
1631
|
+
}
|
|
1632
|
+
};
|
|
1633
|
+
|
|
1634
|
+
// packages/experimental/src/zukhruf/agent-runtime.ts
|
|
1635
|
+
var AgentObservation = class {
|
|
1636
|
+
engine;
|
|
1637
|
+
#conversation;
|
|
1638
|
+
#store;
|
|
1639
|
+
#streams;
|
|
1640
|
+
constructor(conversation, store, streams) {
|
|
1641
|
+
this.engine = new ContextEngine4({
|
|
1642
|
+
store,
|
|
152
1643
|
chatId: conversation.chatId,
|
|
153
1644
|
userId: conversation.userId
|
|
154
1645
|
});
|
|
155
|
-
|
|
156
|
-
|
|
1646
|
+
this.#conversation = conversation;
|
|
1647
|
+
this.#store = store;
|
|
1648
|
+
this.#streams = streams;
|
|
157
1649
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
1650
|
+
async resume() {
|
|
1651
|
+
const id = await this.#headStreamId();
|
|
1652
|
+
if (!id) return null;
|
|
1653
|
+
AgentTurnId.assertOwner(this.#conversation, id);
|
|
1654
|
+
const status = await this.#streams.store.getStreamStatus(id);
|
|
1655
|
+
return status ? this.#streams.watch(id) : null;
|
|
1656
|
+
}
|
|
1657
|
+
async cancel(streamId) {
|
|
1658
|
+
const chat2 = await this.#store.getChat(this.#conversation.chatId);
|
|
1659
|
+
if (chat2 && chat2.userId !== this.#conversation.userId) {
|
|
1660
|
+
throw new Error(
|
|
1661
|
+
`chat "${this.#conversation.chatId}" belongs to user "${chat2.userId}", not "${this.#conversation.userId}"`
|
|
1662
|
+
);
|
|
1663
|
+
}
|
|
1664
|
+
const id = streamId ?? await this.#headStreamId();
|
|
1665
|
+
if (!id) return;
|
|
1666
|
+
AgentTurnId.assertOwner(this.#conversation, id);
|
|
1667
|
+
const status = await this.#streams.store.getStreamStatus(id);
|
|
1668
|
+
if (status === "queued" || status === "running") {
|
|
1669
|
+
await this.#streams.cancel(id);
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
async #headStreamId() {
|
|
1673
|
+
const head = await this.engine.headMessage();
|
|
1674
|
+
return head?.name === "assistant" ? head.id : void 0;
|
|
1675
|
+
}
|
|
1676
|
+
};
|
|
1677
|
+
var AgentRuntime = class {
|
|
1678
|
+
#store;
|
|
1679
|
+
#queue;
|
|
1680
|
+
#streams;
|
|
1681
|
+
#mailbox;
|
|
1682
|
+
#directory;
|
|
1683
|
+
#controlPlane;
|
|
1684
|
+
#approvals;
|
|
1685
|
+
#executor;
|
|
1686
|
+
constructor(root, options) {
|
|
1687
|
+
const declarations = new AgentDeclarationRegistry(root);
|
|
1688
|
+
const directory = new AgentDirectory(options.store);
|
|
1689
|
+
const streams = new StreamManager({
|
|
1690
|
+
store: options.streamStore,
|
|
1691
|
+
changeSource: new PollingChangeSource({ reads: options.streamStore })
|
|
1692
|
+
});
|
|
1693
|
+
const mailbox = new MailboxCoordinator({
|
|
1694
|
+
store: options.mailboxStore,
|
|
1695
|
+
queue: options.queue,
|
|
1696
|
+
streams
|
|
1697
|
+
});
|
|
1698
|
+
const approvals = new ApprovalController({
|
|
1699
|
+
store: options.store,
|
|
1700
|
+
streams,
|
|
1701
|
+
queue: options.queue,
|
|
1702
|
+
mutex: options.approvalMutex
|
|
1703
|
+
});
|
|
1704
|
+
const statusProjector = new AgentStatusProjector({
|
|
1705
|
+
store: options.store,
|
|
1706
|
+
streams,
|
|
1707
|
+
queue: options.queue,
|
|
1708
|
+
mailbox,
|
|
1709
|
+
directory,
|
|
1710
|
+
approvals
|
|
1711
|
+
});
|
|
1712
|
+
const controlPlane = new AgentControlPlane({
|
|
1713
|
+
root,
|
|
1714
|
+
streams,
|
|
1715
|
+
queue: options.queue,
|
|
1716
|
+
mailbox,
|
|
1717
|
+
declarations,
|
|
1718
|
+
directory,
|
|
1719
|
+
statusProjector
|
|
1720
|
+
});
|
|
1721
|
+
this.#store = options.store;
|
|
1722
|
+
this.#queue = options.queue;
|
|
1723
|
+
this.#streams = streams;
|
|
1724
|
+
this.#mailbox = mailbox;
|
|
1725
|
+
this.#directory = directory;
|
|
1726
|
+
this.#controlPlane = controlPlane;
|
|
1727
|
+
this.#approvals = approvals;
|
|
1728
|
+
this.#executor = new AgentTurnExecutor({
|
|
1729
|
+
store: options.store,
|
|
1730
|
+
streams,
|
|
1731
|
+
controlPlane,
|
|
1732
|
+
mailbox,
|
|
1733
|
+
approvals
|
|
1734
|
+
});
|
|
1735
|
+
}
|
|
1736
|
+
async enqueue(conversation, turn) {
|
|
1737
|
+
const streamId = await this.#controlPlane.enqueue(conversation, turn);
|
|
1738
|
+
return { id: streamId, stream: this.#streams.watch(streamId) };
|
|
1739
|
+
}
|
|
1740
|
+
async deliver(communication, mode) {
|
|
1741
|
+
await this.#directory.assertOwnerIfExists(communication.recipient);
|
|
1742
|
+
await this.#mailbox.deliver(communication, mode);
|
|
1743
|
+
}
|
|
1744
|
+
approve(conversation, input) {
|
|
1745
|
+
return this.#approvals.approve(conversation, input);
|
|
1746
|
+
}
|
|
1747
|
+
deny(conversation, input) {
|
|
1748
|
+
return this.#approvals.deny(conversation, input);
|
|
1749
|
+
}
|
|
1750
|
+
observe(conversation) {
|
|
1751
|
+
return new AgentObservation(conversation, this.#store, this.#streams);
|
|
1752
|
+
}
|
|
1753
|
+
work(options) {
|
|
1754
|
+
return this.#queue.consume(this.#executor.execute.bind(this.#executor), {
|
|
1755
|
+
concurrency: options?.concurrency,
|
|
1756
|
+
onOrphaned: this.#onOrphaned.bind(this)
|
|
1757
|
+
});
|
|
1758
|
+
}
|
|
1759
|
+
async #onOrphaned(turn, error) {
|
|
1760
|
+
try {
|
|
1761
|
+
let stream = await this.#streams.store.getStream(turn.streamId);
|
|
1762
|
+
const firstReconciliation = stream?.status === "queued" || stream?.status === "running";
|
|
1763
|
+
if (firstReconciliation) {
|
|
1764
|
+
await this.#streams.store.updateStreamStatus(turn.streamId, "failed", {
|
|
1765
|
+
error
|
|
1766
|
+
});
|
|
1767
|
+
stream = await this.#streams.store.getStream(turn.streamId);
|
|
1768
|
+
}
|
|
1769
|
+
if (turn.kind === "continuation" && (stream?.status === "completed" || stream?.status === "failed" || stream?.status === "cancelled")) {
|
|
1770
|
+
await this.#approvals.reconcileTerminalContinuation(
|
|
1771
|
+
turn,
|
|
1772
|
+
turn.streamId,
|
|
1773
|
+
stream.status,
|
|
1774
|
+
stream.error ?? error
|
|
163
1775
|
);
|
|
164
1776
|
}
|
|
165
|
-
await
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
});
|
|
173
|
-
return { id: turn.id, stream: manager.watch(turn.id) };
|
|
174
|
-
},
|
|
175
|
-
async approve(conversation, input) {
|
|
176
|
-
return respondToApproval(conversation, input.toolCallId, {
|
|
177
|
-
approved: true
|
|
178
|
-
});
|
|
179
|
-
},
|
|
180
|
-
async deny(conversation, input) {
|
|
181
|
-
return respondToApproval(conversation, input.toolCallId, {
|
|
182
|
-
approved: false,
|
|
183
|
-
reason: input.reason
|
|
184
|
-
});
|
|
185
|
-
},
|
|
186
|
-
observe({ chatId, userId }) {
|
|
187
|
-
const engine = engineFor({ chatId, userId });
|
|
188
|
-
async function headStreamId() {
|
|
189
|
-
const head = await engine.headMessage();
|
|
190
|
-
return head?.name === "assistant" ? head.id : void 0;
|
|
1777
|
+
const { thread } = await this.#controlPlane.resolve(turn);
|
|
1778
|
+
if (thread.lastTurnId === void 0 || thread.lastTurnId === turn.streamId) {
|
|
1779
|
+
await this.#controlPlane.recordLatestTurnIfCurrent(
|
|
1780
|
+
turn,
|
|
1781
|
+
turn.streamId,
|
|
1782
|
+
thread.lastTurnId
|
|
1783
|
+
);
|
|
191
1784
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
const status = await streamStore.getStreamStatus(id);
|
|
198
|
-
return status ? manager.watch(id) : null;
|
|
199
|
-
},
|
|
200
|
-
async cancel(streamId) {
|
|
201
|
-
const id = streamId ?? await headStreamId();
|
|
202
|
-
if (!id) return;
|
|
203
|
-
const status = await streamStore.getStreamStatus(id);
|
|
204
|
-
if (status === "queued" || status === "running") {
|
|
205
|
-
await manager.cancel(id);
|
|
206
|
-
}
|
|
1785
|
+
await this.#controlPlane.projectTerminal(turn, thread);
|
|
1786
|
+
} finally {
|
|
1787
|
+
try {
|
|
1788
|
+
if (turn.kind === "continuation") {
|
|
1789
|
+
await this.#queue.resumeParked(turn.chatId);
|
|
207
1790
|
}
|
|
1791
|
+
} finally {
|
|
1792
|
+
await this.#mailbox.endTurn(turn);
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
};
|
|
1797
|
+
|
|
1798
|
+
// packages/experimental/src/zukhruf/approval-mutex.ts
|
|
1799
|
+
var ApprovalMutex = class {
|
|
1800
|
+
};
|
|
1801
|
+
|
|
1802
|
+
// packages/experimental/src/zukhruf/instructions.ts
|
|
1803
|
+
function defineInstructions(...fragments) {
|
|
1804
|
+
return fragments;
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
// packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
|
|
1808
|
+
import { DatabaseSync } from "node:sqlite";
|
|
1809
|
+
|
|
1810
|
+
// packages/experimental/src/zukhruf/mailbox/store.ts
|
|
1811
|
+
var MailboxStore = class {
|
|
1812
|
+
};
|
|
1813
|
+
|
|
1814
|
+
// packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
|
|
1815
|
+
var DDL = `
|
|
1816
|
+
PRAGMA journal_mode = WAL;
|
|
1817
|
+
PRAGMA synchronous = NORMAL;
|
|
1818
|
+
|
|
1819
|
+
CREATE TABLE IF NOT EXISTS zukhruf_mailbox_items (
|
|
1820
|
+
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1821
|
+
recipient_chat_id TEXT NOT NULL,
|
|
1822
|
+
recipient_user_id TEXT NOT NULL,
|
|
1823
|
+
communication TEXT NOT NULL
|
|
1824
|
+
);
|
|
1825
|
+
|
|
1826
|
+
CREATE TABLE IF NOT EXISTS zukhruf_mailbox_activity (
|
|
1827
|
+
recipient_chat_id TEXT NOT NULL,
|
|
1828
|
+
recipient_user_id TEXT NOT NULL,
|
|
1829
|
+
turn_id TEXT NOT NULL,
|
|
1830
|
+
PRIMARY KEY (recipient_chat_id, recipient_user_id)
|
|
1831
|
+
);
|
|
1832
|
+
|
|
1833
|
+
CREATE TABLE IF NOT EXISTS zukhruf_mailbox_consumed_terminal_ids (
|
|
1834
|
+
communication_id TEXT PRIMARY KEY
|
|
1835
|
+
);
|
|
1836
|
+
|
|
1837
|
+
CREATE INDEX IF NOT EXISTS zukhruf_mailbox_recipient_sequence
|
|
1838
|
+
ON zukhruf_mailbox_items (
|
|
1839
|
+
recipient_chat_id,
|
|
1840
|
+
recipient_user_id,
|
|
1841
|
+
sequence
|
|
1842
|
+
);
|
|
1843
|
+
|
|
1844
|
+
CREATE UNIQUE INDEX IF NOT EXISTS zukhruf_mailbox_communication_id
|
|
1845
|
+
ON zukhruf_mailbox_items (
|
|
1846
|
+
json_extract(communication, '$.id')
|
|
1847
|
+
);
|
|
1848
|
+
`;
|
|
1849
|
+
var BUSY_TIMEOUT_MS = 5e3;
|
|
1850
|
+
var SqliteMailboxStore = class extends MailboxStore {
|
|
1851
|
+
#database;
|
|
1852
|
+
#closed = false;
|
|
1853
|
+
constructor(path) {
|
|
1854
|
+
super();
|
|
1855
|
+
this.#database = new DatabaseSync(path, { timeout: BUSY_TIMEOUT_MS });
|
|
1856
|
+
this.#database.exec(DDL);
|
|
1857
|
+
}
|
|
1858
|
+
async beginTurn(recipient, turnId) {
|
|
1859
|
+
this.#transaction(() => {
|
|
1860
|
+
this.#database.prepare(
|
|
1861
|
+
`INSERT INTO zukhruf_mailbox_activity (
|
|
1862
|
+
recipient_chat_id,
|
|
1863
|
+
recipient_user_id,
|
|
1864
|
+
turn_id
|
|
1865
|
+
) VALUES (?, ?, ?)
|
|
1866
|
+
ON CONFLICT (recipient_chat_id, recipient_user_id)
|
|
1867
|
+
DO UPDATE SET turn_id = excluded.turn_id`
|
|
1868
|
+
).run(recipient.chatId, recipient.userId, turnId);
|
|
1869
|
+
});
|
|
1870
|
+
}
|
|
1871
|
+
async enqueue(communication) {
|
|
1872
|
+
return this.#transaction(() => {
|
|
1873
|
+
const consumedTerminal = communication.type === InterAgentCommunicationType.FinalAnswer && this.#hasConsumedTerminal(communication.id);
|
|
1874
|
+
if (!consumedTerminal) {
|
|
1875
|
+
this.#database.prepare(
|
|
1876
|
+
`INSERT OR IGNORE INTO zukhruf_mailbox_items (
|
|
1877
|
+
recipient_chat_id,
|
|
1878
|
+
recipient_user_id,
|
|
1879
|
+
communication
|
|
1880
|
+
) VALUES (?, ?, ?)`
|
|
1881
|
+
).run(
|
|
1882
|
+
communication.recipient.chatId,
|
|
1883
|
+
communication.recipient.userId,
|
|
1884
|
+
JSON.stringify(communication)
|
|
1885
|
+
);
|
|
1886
|
+
}
|
|
1887
|
+
return {
|
|
1888
|
+
recipientActive: this.#isTurnActive(communication.recipient)
|
|
1889
|
+
};
|
|
1890
|
+
});
|
|
1891
|
+
}
|
|
1892
|
+
async endTurn(recipient, turnId) {
|
|
1893
|
+
return this.#transaction(() => {
|
|
1894
|
+
const result = this.#database.prepare(
|
|
1895
|
+
`DELETE FROM zukhruf_mailbox_activity
|
|
1896
|
+
WHERE recipient_chat_id = ?
|
|
1897
|
+
AND recipient_user_id = ?
|
|
1898
|
+
AND turn_id = ?`
|
|
1899
|
+
).run(recipient.chatId, recipient.userId, turnId);
|
|
1900
|
+
return {
|
|
1901
|
+
hasPending: this.#hasPending(recipient),
|
|
1902
|
+
turnEnded: result.changes > 0
|
|
208
1903
|
};
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
1904
|
+
});
|
|
1905
|
+
}
|
|
1906
|
+
async hasPending(recipient) {
|
|
1907
|
+
return this.#hasPending(recipient);
|
|
1908
|
+
}
|
|
1909
|
+
#hasPending(recipient) {
|
|
1910
|
+
const row = this.#database.prepare(
|
|
1911
|
+
`SELECT 1
|
|
1912
|
+
FROM zukhruf_mailbox_items
|
|
1913
|
+
WHERE recipient_chat_id = ?
|
|
1914
|
+
AND recipient_user_id = ?
|
|
1915
|
+
LIMIT 1`
|
|
1916
|
+
).get(recipient.chatId, recipient.userId);
|
|
1917
|
+
return row !== void 0;
|
|
1918
|
+
}
|
|
1919
|
+
#isTurnActive(recipient) {
|
|
1920
|
+
const row = this.#database.prepare(
|
|
1921
|
+
`SELECT 1
|
|
1922
|
+
FROM zukhruf_mailbox_activity
|
|
1923
|
+
WHERE recipient_chat_id = ?
|
|
1924
|
+
AND recipient_user_id = ?
|
|
1925
|
+
LIMIT 1`
|
|
1926
|
+
).get(recipient.chatId, recipient.userId);
|
|
1927
|
+
return row !== void 0;
|
|
1928
|
+
}
|
|
1929
|
+
#hasConsumedTerminal(communicationId) {
|
|
1930
|
+
const row = this.#database.prepare(
|
|
1931
|
+
`SELECT 1
|
|
1932
|
+
FROM zukhruf_mailbox_consumed_terminal_ids
|
|
1933
|
+
WHERE communication_id = ?
|
|
1934
|
+
LIMIT 1`
|
|
1935
|
+
).get(communicationId);
|
|
1936
|
+
return row !== void 0;
|
|
1937
|
+
}
|
|
1938
|
+
async drain(recipient) {
|
|
1939
|
+
return this.#drain(recipient, false);
|
|
1940
|
+
}
|
|
1941
|
+
async drainLeadingQueueOnly(recipient) {
|
|
1942
|
+
return this.#drain(recipient, true);
|
|
1943
|
+
}
|
|
1944
|
+
#drain(recipient, leadingQueueOnly) {
|
|
1945
|
+
return this.#transaction(() => {
|
|
1946
|
+
const rows = this.#database.prepare(
|
|
1947
|
+
`SELECT sequence, communication
|
|
1948
|
+
FROM zukhruf_mailbox_items
|
|
1949
|
+
WHERE recipient_chat_id = ?
|
|
1950
|
+
AND recipient_user_id = ?
|
|
1951
|
+
ORDER BY sequence`
|
|
1952
|
+
).all(recipient.chatId, recipient.userId);
|
|
1953
|
+
const items = rows.map((row) => ({
|
|
1954
|
+
sequence: row.sequence,
|
|
1955
|
+
communication: JSON.parse(row.communication)
|
|
1956
|
+
}));
|
|
1957
|
+
const firstTrigger = leadingQueueOnly ? items.findIndex(({ communication }) => communication.triggerTurn) : -1;
|
|
1958
|
+
const consumed = firstTrigger === -1 ? items : items.slice(0, firstTrigger);
|
|
1959
|
+
const lastConsumed = consumed.at(-1);
|
|
1960
|
+
if (lastConsumed) {
|
|
1961
|
+
const tombstone = this.#database.prepare(
|
|
1962
|
+
`INSERT OR IGNORE
|
|
1963
|
+
INTO zukhruf_mailbox_consumed_terminal_ids (communication_id)
|
|
1964
|
+
VALUES (?)`
|
|
1965
|
+
);
|
|
1966
|
+
for (const { communication } of consumed) {
|
|
1967
|
+
if (communication.type === InterAgentCommunicationType.FinalAnswer) {
|
|
1968
|
+
tombstone.run(communication.id);
|
|
219
1969
|
}
|
|
220
1970
|
}
|
|
221
|
-
|
|
1971
|
+
this.#database.prepare(
|
|
1972
|
+
`DELETE FROM zukhruf_mailbox_items
|
|
1973
|
+
WHERE recipient_chat_id = ?
|
|
1974
|
+
AND recipient_user_id = ?
|
|
1975
|
+
AND sequence <= ?`
|
|
1976
|
+
).run(recipient.chatId, recipient.userId, lastConsumed.sequence);
|
|
1977
|
+
}
|
|
1978
|
+
return consumed.map(({ communication }) => communication);
|
|
1979
|
+
});
|
|
1980
|
+
}
|
|
1981
|
+
#transaction(operation) {
|
|
1982
|
+
this.#database.exec("BEGIN IMMEDIATE");
|
|
1983
|
+
try {
|
|
1984
|
+
const result = operation();
|
|
1985
|
+
this.#database.exec("COMMIT");
|
|
1986
|
+
return result;
|
|
1987
|
+
} catch (error) {
|
|
1988
|
+
try {
|
|
1989
|
+
this.#database.exec("ROLLBACK");
|
|
1990
|
+
} catch {
|
|
1991
|
+
}
|
|
1992
|
+
throw error;
|
|
222
1993
|
}
|
|
223
|
-
}
|
|
224
|
-
|
|
1994
|
+
}
|
|
1995
|
+
close() {
|
|
1996
|
+
if (this.#closed) return;
|
|
1997
|
+
this.#closed = true;
|
|
1998
|
+
this.#database.close();
|
|
1999
|
+
}
|
|
2000
|
+
[Symbol.dispose]() {
|
|
2001
|
+
this.close();
|
|
2002
|
+
}
|
|
2003
|
+
};
|
|
2004
|
+
|
|
2005
|
+
// packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
|
|
2006
|
+
import { v7 as uuidv7 } from "uuid";
|
|
225
2007
|
|
|
226
2008
|
// packages/experimental/src/zukhruf/queue/turn-queue.ts
|
|
227
2009
|
var TurnQueue = class {
|
|
228
2010
|
};
|
|
229
2011
|
|
|
230
2012
|
// packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
|
|
231
|
-
|
|
232
|
-
var PgBossTurnQueue = class extends TurnQueue {
|
|
2013
|
+
var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
|
|
233
2014
|
#boss;
|
|
234
2015
|
#queue;
|
|
235
2016
|
#expireInSeconds;
|
|
@@ -271,6 +2052,18 @@ var PgBossTurnQueue = class extends TurnQueue {
|
|
|
271
2052
|
priority: turn.kind === "continuation" ? 1 : 0
|
|
272
2053
|
});
|
|
273
2054
|
}
|
|
2055
|
+
async getTurnActivity(conversation) {
|
|
2056
|
+
const jobs = await this.#boss.findJobs(this.#queue, {
|
|
2057
|
+
key: conversation.chatId
|
|
2058
|
+
});
|
|
2059
|
+
const conversationJobs = jobs.filter(
|
|
2060
|
+
(job) => job.data.userId === conversation.userId && (job.state === "created" || job.state === "retry" || job.state === "active")
|
|
2061
|
+
);
|
|
2062
|
+
if (conversationJobs.some((job) => job.state === "active")) {
|
|
2063
|
+
return "running";
|
|
2064
|
+
}
|
|
2065
|
+
return conversationJobs.length > 0 ? "queued" : "idle";
|
|
2066
|
+
}
|
|
274
2067
|
async consume(handler, options) {
|
|
275
2068
|
const turnWorkerId = await this.#boss.work(
|
|
276
2069
|
this.#queue,
|
|
@@ -303,9 +2096,15 @@ var PgBossTurnQueue = class extends TurnQueue {
|
|
|
303
2096
|
pollingIntervalSeconds: this.#pollingIntervalSeconds
|
|
304
2097
|
},
|
|
305
2098
|
async ([job]) => {
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
2099
|
+
try {
|
|
2100
|
+
await options.onOrphaned(
|
|
2101
|
+
job.data,
|
|
2102
|
+
_PgBossTurnQueue.#orphanError(job.output)
|
|
2103
|
+
);
|
|
2104
|
+
} finally {
|
|
2105
|
+
if (job.sourceId) {
|
|
2106
|
+
await this.#boss.deleteJob(this.#queue, job.sourceId);
|
|
2107
|
+
}
|
|
309
2108
|
}
|
|
310
2109
|
}
|
|
311
2110
|
);
|
|
@@ -323,14 +2122,93 @@ var PgBossTurnQueue = class extends TurnQueue {
|
|
|
323
2122
|
await this.#boss.resume(this.#queue, parked);
|
|
324
2123
|
}
|
|
325
2124
|
}
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
2125
|
+
static #orphanError(output) {
|
|
2126
|
+
if (output && "message" in output && typeof output.message === "string") {
|
|
2127
|
+
return output.message;
|
|
2128
|
+
}
|
|
2129
|
+
return output ? JSON.stringify(output) : "turn orphaned";
|
|
330
2130
|
}
|
|
331
|
-
|
|
2131
|
+
};
|
|
2132
|
+
|
|
2133
|
+
// packages/experimental/src/zukhruf/sandbox/define.ts
|
|
2134
|
+
import {
|
|
2135
|
+
createBashTool
|
|
2136
|
+
} from "@deepagents/context";
|
|
2137
|
+
function defineSandbox(createBackend, options) {
|
|
2138
|
+
return async (context) => createBashTool({ sandbox: await createBackend(context), ...options });
|
|
332
2139
|
}
|
|
2140
|
+
|
|
2141
|
+
// packages/experimental/src/zukhruf/sqlite-approval-mutex.ts
|
|
2142
|
+
import { resolve } from "node:path";
|
|
2143
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
2144
|
+
var SqliteApprovalMutex = class _SqliteApprovalMutex extends ApprovalMutex {
|
|
2145
|
+
static #tails = /* @__PURE__ */ new Map();
|
|
2146
|
+
#db;
|
|
2147
|
+
#coordinationKey;
|
|
2148
|
+
constructor(path) {
|
|
2149
|
+
super();
|
|
2150
|
+
this.#coordinationKey = path === ":memory:" ? crypto.randomUUID() : resolve(path);
|
|
2151
|
+
this.#db = new DatabaseSync2(path);
|
|
2152
|
+
this.#db.exec(`
|
|
2153
|
+
PRAGMA busy_timeout = 5000;
|
|
2154
|
+
CREATE TABLE IF NOT EXISTS approval_mutex (
|
|
2155
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
2156
|
+
conversationId TEXT NOT NULL,
|
|
2157
|
+
touchedAt INTEGER NOT NULL
|
|
2158
|
+
);
|
|
2159
|
+
`);
|
|
2160
|
+
}
|
|
2161
|
+
async runExclusive(conversationId, operation) {
|
|
2162
|
+
const release = await this.#acquireLocalGate();
|
|
2163
|
+
try {
|
|
2164
|
+
this.#db.exec("BEGIN IMMEDIATE");
|
|
2165
|
+
try {
|
|
2166
|
+
this.#db.prepare(
|
|
2167
|
+
`INSERT INTO approval_mutex (id, conversationId, touchedAt)
|
|
2168
|
+
VALUES (1, ?, ?)
|
|
2169
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
2170
|
+
conversationId = excluded.conversationId,
|
|
2171
|
+
touchedAt = excluded.touchedAt`
|
|
2172
|
+
).run(conversationId, Date.now());
|
|
2173
|
+
const result = await operation();
|
|
2174
|
+
this.#db.exec("COMMIT");
|
|
2175
|
+
return result;
|
|
2176
|
+
} catch (error) {
|
|
2177
|
+
try {
|
|
2178
|
+
this.#db.exec("ROLLBACK");
|
|
2179
|
+
} catch {
|
|
2180
|
+
}
|
|
2181
|
+
throw error;
|
|
2182
|
+
}
|
|
2183
|
+
} finally {
|
|
2184
|
+
release();
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
close() {
|
|
2188
|
+
this.#db.close();
|
|
2189
|
+
}
|
|
2190
|
+
[Symbol.dispose]() {
|
|
2191
|
+
this.close();
|
|
2192
|
+
}
|
|
2193
|
+
async #acquireLocalGate() {
|
|
2194
|
+
const previous = _SqliteApprovalMutex.#tails.get(this.#coordinationKey) ?? Promise.resolve();
|
|
2195
|
+
const gate = Promise.withResolvers();
|
|
2196
|
+
const tail = previous.then(() => gate.promise);
|
|
2197
|
+
_SqliteApprovalMutex.#tails.set(this.#coordinationKey, tail);
|
|
2198
|
+
await previous;
|
|
2199
|
+
return () => {
|
|
2200
|
+
gate.resolve();
|
|
2201
|
+
if (_SqliteApprovalMutex.#tails.get(this.#coordinationKey) === tail) {
|
|
2202
|
+
_SqliteApprovalMutex.#tails.delete(this.#coordinationKey);
|
|
2203
|
+
}
|
|
2204
|
+
};
|
|
2205
|
+
}
|
|
2206
|
+
};
|
|
2207
|
+
|
|
2208
|
+
// packages/experimental/src/zukhruf/tool.ts
|
|
2209
|
+
import { tool as tool4 } from "ai";
|
|
333
2210
|
export {
|
|
2211
|
+
coding_agent_reminders_exports as codingAgentReminders,
|
|
334
2212
|
zukhruf_exports as zukhruf
|
|
335
2213
|
};
|
|
336
2214
|
//# sourceMappingURL=index.js.map
|