@deepagents/experimental 5.0.0 → 6.1.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 +30 -11
- package/dist/index.js +1453 -459
- package/dist/index.js.map +4 -4
- package/dist/zukhruf/agent.d.ts +9 -4
- package/dist/zukhruf/agent.d.ts.map +1 -1
- package/dist/zukhruf/collaboration/agent-tool-context.d.ts +6 -0
- package/dist/zukhruf/collaboration/agent-tool-context.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/collaboration-tools.d.ts +4 -0
- package/dist/zukhruf/collaboration/collaboration-tools.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/interrupt-agent.d.ts +234 -0
- package/dist/zukhruf/collaboration/interrupt-agent.d.ts.map +1 -0
- package/dist/zukhruf/{list-agents.d.ts → collaboration/list-agents.d.ts} +1 -1
- package/dist/zukhruf/collaboration/list-agents.d.ts.map +1 -0
- package/dist/zukhruf/{message-tools.d.ts → collaboration/message-tools.d.ts} +84 -88
- package/dist/zukhruf/collaboration/message-tools.d.ts.map +1 -0
- package/dist/zukhruf/{spawn-agent.d.ts → collaboration/spawn-agent.d.ts} +55 -43
- package/dist/zukhruf/collaboration/spawn-agent.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/wait-agent.d.ts +253 -0
- package/dist/zukhruf/collaboration/wait-agent.d.ts.map +1 -0
- package/dist/zukhruf/{agent-control-plane.d.ts → control-plane/agent-control-plane.d.ts} +17 -5
- package/dist/zukhruf/control-plane/agent-control-plane.d.ts.map +1 -0
- package/dist/zukhruf/{agent-declaration-registry.d.ts → control-plane/agent-declaration-registry.d.ts} +1 -1
- package/dist/zukhruf/control-plane/agent-declaration-registry.d.ts.map +1 -0
- package/dist/zukhruf/{agent-directory.d.ts → control-plane/agent-directory.d.ts} +2 -1
- package/dist/zukhruf/control-plane/agent-directory.d.ts.map +1 -0
- package/dist/zukhruf/control-plane/agent-history-forker.d.ts +10 -0
- package/dist/zukhruf/control-plane/agent-history-forker.d.ts.map +1 -0
- package/dist/zukhruf/control-plane/agent-path.d.ts.map +1 -0
- package/dist/zukhruf/control-plane/agent-status-projector.d.ts +50 -0
- package/dist/zukhruf/control-plane/agent-status-projector.d.ts.map +1 -0
- package/dist/zukhruf/{agent-thread.d.ts → control-plane/agent-thread.d.ts} +1 -1
- package/dist/zukhruf/control-plane/agent-thread.d.ts.map +1 -0
- package/dist/zukhruf/{agent-turn-id.d.ts → control-plane/agent-turn-id.d.ts} +2 -1
- package/dist/zukhruf/control-plane/agent-turn-id.d.ts.map +1 -0
- package/dist/zukhruf/control-plane/fork-turns.d.ts +4 -0
- package/dist/zukhruf/control-plane/fork-turns.d.ts.map +1 -0
- package/dist/zukhruf/index.d.ts +6 -6
- package/dist/zukhruf/index.d.ts.map +1 -1
- package/dist/zukhruf/index.js +1453 -459
- package/dist/zukhruf/index.js.map +4 -4
- package/dist/zukhruf/mailbox/coordinator.d.ts +4 -0
- package/dist/zukhruf/mailbox/coordinator.d.ts.map +1 -1
- package/dist/zukhruf/multi-agent-v2-config.d.ts +32 -0
- package/dist/zukhruf/multi-agent-v2-config.d.ts.map +1 -0
- package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +16 -4
- package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
- package/dist/zukhruf/queue/turn-queue.d.ts +35 -6
- package/dist/zukhruf/queue/turn-queue.d.ts.map +1 -1
- package/dist/zukhruf/render-turn.d.ts +9 -0
- package/dist/zukhruf/render-turn.d.ts.map +1 -0
- package/dist/zukhruf/{agent-runtime.d.ts → runtime/agent-runtime.d.ts} +24 -13
- package/dist/zukhruf/runtime/agent-runtime.d.ts.map +1 -0
- package/dist/zukhruf/runtime/agent-skills.d.ts +9 -0
- package/dist/zukhruf/runtime/agent-skills.d.ts.map +1 -0
- package/dist/zukhruf/{agent-turn-executor.d.ts → runtime/agent-turn-executor.d.ts} +5 -3
- package/dist/zukhruf/runtime/agent-turn-executor.d.ts.map +1 -0
- package/dist/zukhruf/{approval-controller.d.ts → runtime/approval-controller.d.ts} +19 -8
- package/dist/zukhruf/runtime/approval-controller.d.ts.map +1 -0
- package/dist/zukhruf/runtime/approval-job-id.d.ts +3 -0
- package/dist/zukhruf/runtime/approval-job-id.d.ts.map +1 -0
- package/dist/zukhruf/sandbox/define.d.ts +4 -3
- package/dist/zukhruf/sandbox/define.d.ts.map +1 -1
- package/dist/zukhruf/tool.d.ts +18 -6
- package/dist/zukhruf/tool.d.ts.map +1 -1
- package/package.json +9 -9
- package/dist/zukhruf/agent-control-plane.d.ts.map +0 -1
- package/dist/zukhruf/agent-declaration-registry.d.ts.map +0 -1
- package/dist/zukhruf/agent-directory.d.ts.map +0 -1
- package/dist/zukhruf/agent-path.d.ts.map +0 -1
- package/dist/zukhruf/agent-runtime.d.ts.map +0 -1
- package/dist/zukhruf/agent-status-projector.d.ts +0 -32
- package/dist/zukhruf/agent-status-projector.d.ts.map +0 -1
- package/dist/zukhruf/agent-thread.d.ts.map +0 -1
- package/dist/zukhruf/agent-tool-context.d.ts +0 -6
- package/dist/zukhruf/agent-tool-context.d.ts.map +0 -1
- package/dist/zukhruf/agent-turn-executor.d.ts.map +0 -1
- package/dist/zukhruf/agent-turn-id.d.ts.map +0 -1
- package/dist/zukhruf/approval-controller.d.ts.map +0 -1
- package/dist/zukhruf/approval-mutex.d.ts +0 -5
- package/dist/zukhruf/approval-mutex.d.ts.map +0 -1
- package/dist/zukhruf/list-agents.d.ts.map +0 -1
- package/dist/zukhruf/message-tools.d.ts.map +0 -1
- package/dist/zukhruf/spawn-agent.d.ts.map +0 -1
- package/dist/zukhruf/sqlite-approval-mutex.d.ts +0 -17
- package/dist/zukhruf/sqlite-approval-mutex.d.ts.map +0 -1
- /package/dist/zukhruf/{agent-path.d.ts → control-plane/agent-path.d.ts} +0 -0
package/dist/zukhruf/index.js
CHANGED
|
@@ -1,4 +1,17 @@
|
|
|
1
|
-
// packages/experimental/src/zukhruf/agent
|
|
1
|
+
// packages/experimental/src/zukhruf/agent.ts
|
|
2
|
+
function defineAgent(declaration) {
|
|
3
|
+
return {
|
|
4
|
+
name: declaration.name,
|
|
5
|
+
model: declaration.model,
|
|
6
|
+
sandbox: declaration.sandbox,
|
|
7
|
+
instructions: declaration.instructions,
|
|
8
|
+
tools: declaration.tools ?? {},
|
|
9
|
+
subagents: declaration.subagents ?? [],
|
|
10
|
+
telemetry: declaration.telemetry
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// packages/experimental/src/zukhruf/control-plane/agent-path.ts
|
|
2
15
|
var AgentPath = class _AgentPath {
|
|
3
16
|
#value;
|
|
4
17
|
constructor(value) {
|
|
@@ -8,17 +21,17 @@ var AgentPath = class _AgentPath {
|
|
|
8
21
|
return new _AgentPath("/root");
|
|
9
22
|
}
|
|
10
23
|
static parse(value) {
|
|
11
|
-
const
|
|
12
|
-
if (
|
|
24
|
+
const path2 = value.trim();
|
|
25
|
+
if (path2 !== "/root" && !path2.startsWith("/root/")) {
|
|
13
26
|
throw new Error(`agent path "${value}" must start at /root`);
|
|
14
27
|
}
|
|
15
|
-
const segments =
|
|
28
|
+
const segments = path2.slice(1).split("/");
|
|
16
29
|
if (segments.some(
|
|
17
30
|
(segment) => segment.length === 0 || segment !== segment.trim() || segment === "." || segment === ".."
|
|
18
31
|
)) {
|
|
19
32
|
throw new Error(`agent path "${value}" contains an invalid segment`);
|
|
20
33
|
}
|
|
21
|
-
return new _AgentPath(
|
|
34
|
+
return new _AgentPath(path2);
|
|
22
35
|
}
|
|
23
36
|
/** Relative targets name descendants; absolute targets keep their canonical path. */
|
|
24
37
|
resolve(target) {
|
|
@@ -46,7 +59,7 @@ var AgentPath = class _AgentPath {
|
|
|
46
59
|
}
|
|
47
60
|
};
|
|
48
61
|
|
|
49
|
-
// packages/experimental/src/zukhruf/agent-thread.ts
|
|
62
|
+
// packages/experimental/src/zukhruf/control-plane/agent-thread.ts
|
|
50
63
|
var AgentThread = class _AgentThread {
|
|
51
64
|
conversation;
|
|
52
65
|
treeId;
|
|
@@ -86,17 +99,17 @@ var AgentThread = class _AgentThread {
|
|
|
86
99
|
if (typeof treeId !== "string" || !_AgentThread.#isRecord(zukhruf)) {
|
|
87
100
|
return void 0;
|
|
88
101
|
}
|
|
89
|
-
const { path, parentChatId, declarationName, lastTurnId } = zukhruf;
|
|
90
|
-
if (typeof
|
|
102
|
+
const { path: path2, parentChatId, declarationName, lastTurnId } = zukhruf;
|
|
103
|
+
if (typeof path2 !== "string" || parentChatId !== null && typeof parentChatId !== "string" || typeof declarationName !== "string" || lastTurnId !== void 0 && typeof lastTurnId !== "string") {
|
|
91
104
|
return void 0;
|
|
92
105
|
}
|
|
93
106
|
let parsedPath;
|
|
94
107
|
try {
|
|
95
|
-
parsedPath = AgentPath.parse(
|
|
108
|
+
parsedPath = AgentPath.parse(path2);
|
|
96
109
|
} catch {
|
|
97
110
|
return void 0;
|
|
98
111
|
}
|
|
99
|
-
if (parsedPath.toString() !==
|
|
112
|
+
if (parsedPath.toString() !== path2) return void 0;
|
|
100
113
|
try {
|
|
101
114
|
return new _AgentThread({
|
|
102
115
|
conversation,
|
|
@@ -156,30 +169,61 @@ var AgentThread = class _AgentThread {
|
|
|
156
169
|
}
|
|
157
170
|
};
|
|
158
171
|
|
|
159
|
-
// packages/experimental/src/zukhruf/agent.ts
|
|
160
|
-
function defineAgent(declaration) {
|
|
161
|
-
return {
|
|
162
|
-
name: declaration.name,
|
|
163
|
-
model: declaration.model,
|
|
164
|
-
sandbox: declaration.sandbox,
|
|
165
|
-
instructions: declaration.instructions,
|
|
166
|
-
tools: declaration.tools ?? {},
|
|
167
|
-
subagents: declaration.subagents ?? [],
|
|
168
|
-
telemetry: declaration.telemetry
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
// packages/experimental/src/zukhruf/agent-runtime.ts
|
|
172
|
+
// packages/experimental/src/zukhruf/runtime/agent-runtime.ts
|
|
173
173
|
import {
|
|
174
|
-
ContextEngine as ContextEngine4
|
|
175
|
-
PollingChangeSource,
|
|
176
|
-
StreamManager
|
|
174
|
+
ContextEngine as ContextEngine4
|
|
177
175
|
} from "@deepagents/context";
|
|
178
176
|
|
|
179
|
-
// packages/experimental/src/zukhruf/agent-control-plane.ts
|
|
180
|
-
import { v5 as
|
|
177
|
+
// packages/experimental/src/zukhruf/control-plane/agent-control-plane.ts
|
|
178
|
+
import { v5 as uuidv54 } from "uuid";
|
|
179
|
+
|
|
180
|
+
// packages/experimental/src/zukhruf/mailbox/types.ts
|
|
181
|
+
import { randomUUID } from "node:crypto";
|
|
182
|
+
var MessageDeliveryMode = {
|
|
183
|
+
QueueOnly: "queue-only",
|
|
184
|
+
TriggerTurn: "trigger-turn"
|
|
185
|
+
};
|
|
186
|
+
var InterAgentCommunicationType = {
|
|
187
|
+
Message: "MESSAGE",
|
|
188
|
+
NewTask: "NEW_TASK",
|
|
189
|
+
FinalAnswer: "FINAL_ANSWER"
|
|
190
|
+
};
|
|
191
|
+
function createInterAgentCommunication(communication) {
|
|
192
|
+
const value = {
|
|
193
|
+
...communication,
|
|
194
|
+
id: communication.id ?? randomUUID(),
|
|
195
|
+
type: communication.type ?? InterAgentCommunicationType.Message,
|
|
196
|
+
otherRecipients: communication.otherRecipients ?? [],
|
|
197
|
+
triggerTurn: false
|
|
198
|
+
};
|
|
199
|
+
assertCommunication(value);
|
|
200
|
+
return value;
|
|
201
|
+
}
|
|
202
|
+
function assertCommunication(communication) {
|
|
203
|
+
if (!communication.id.trim()) {
|
|
204
|
+
throw new Error("inter-agent communication id cannot be empty");
|
|
205
|
+
}
|
|
206
|
+
if (!Object.values(InterAgentCommunicationType).includes(communication.type)) {
|
|
207
|
+
throw new Error("inter-agent communication type is invalid");
|
|
208
|
+
}
|
|
209
|
+
assertConversationId(communication.author, "author");
|
|
210
|
+
assertConversationId(communication.recipient, "recipient");
|
|
211
|
+
for (const recipient of communication.otherRecipients) {
|
|
212
|
+
assertConversationId(recipient, "other recipient");
|
|
213
|
+
}
|
|
214
|
+
if (!communication.content.trim()) {
|
|
215
|
+
throw new Error("inter-agent communication content cannot be empty");
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
function assertConversationId(value, label) {
|
|
219
|
+
if (!value.chatId.trim() || !value.userId.trim()) {
|
|
220
|
+
throw new Error(
|
|
221
|
+
`inter-agent communication ${label} requires chatId and userId`
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
181
225
|
|
|
182
|
-
// packages/experimental/src/zukhruf/agent-declaration-registry.ts
|
|
226
|
+
// packages/experimental/src/zukhruf/control-plane/agent-declaration-registry.ts
|
|
183
227
|
var AgentDeclarationRegistry = class {
|
|
184
228
|
root;
|
|
185
229
|
#declarations = /* @__PURE__ */ new Map();
|
|
@@ -214,7 +258,7 @@ var AgentDeclarationRegistry = class {
|
|
|
214
258
|
}
|
|
215
259
|
};
|
|
216
260
|
|
|
217
|
-
// packages/experimental/src/zukhruf/agent-directory.ts
|
|
261
|
+
// packages/experimental/src/zukhruf/control-plane/agent-directory.ts
|
|
218
262
|
import { v5 as uuidv5 } from "uuid";
|
|
219
263
|
var AgentDirectory = class _AgentDirectory {
|
|
220
264
|
#store;
|
|
@@ -286,16 +330,20 @@ var AgentDirectory = class _AgentDirectory {
|
|
|
286
330
|
);
|
|
287
331
|
}
|
|
288
332
|
async resolve(thread, target) {
|
|
289
|
-
const
|
|
290
|
-
const match =
|
|
291
|
-
(candidate) => candidate.path.equals(path)
|
|
292
|
-
);
|
|
333
|
+
const path2 = thread.path.resolve(target);
|
|
334
|
+
const match = await this.find(thread, target);
|
|
293
335
|
if (match) return match;
|
|
294
|
-
throw new Error(`agent path "${
|
|
336
|
+
throw new Error(`agent path "${path2}" does not exist in this tree`);
|
|
337
|
+
}
|
|
338
|
+
async find(thread, target) {
|
|
339
|
+
const path2 = thread.path.resolve(target);
|
|
340
|
+
return (await this.listTree(thread)).find(
|
|
341
|
+
(candidate) => candidate.path.equals(path2)
|
|
342
|
+
);
|
|
295
343
|
}
|
|
296
344
|
async createChild(options) {
|
|
297
|
-
const
|
|
298
|
-
const pathString =
|
|
345
|
+
const path2 = options.parent.path.resolve(options.taskName);
|
|
346
|
+
const pathString = path2.toString();
|
|
299
347
|
const conversation = {
|
|
300
348
|
chatId: _AgentDirectory.#childChatId(
|
|
301
349
|
options.parent.conversation.userId,
|
|
@@ -305,7 +353,7 @@ var AgentDirectory = class _AgentDirectory {
|
|
|
305
353
|
userId: options.parent.conversation.userId
|
|
306
354
|
};
|
|
307
355
|
const occupied = (await this.listTree(options.parent)).find(
|
|
308
|
-
(thread) => thread.path.equals(
|
|
356
|
+
(thread) => thread.path.equals(path2)
|
|
309
357
|
);
|
|
310
358
|
if (occupied && occupied.conversation.chatId !== conversation.chatId) {
|
|
311
359
|
throw new Error(`agent path "${pathString}" already exists`);
|
|
@@ -313,7 +361,7 @@ var AgentDirectory = class _AgentDirectory {
|
|
|
313
361
|
const child = new AgentThread({
|
|
314
362
|
conversation,
|
|
315
363
|
treeId: options.parent.treeId,
|
|
316
|
-
path,
|
|
364
|
+
path: path2,
|
|
317
365
|
parentChatId: options.parent.conversation.chatId,
|
|
318
366
|
declarationName: options.declarationName
|
|
319
367
|
});
|
|
@@ -331,9 +379,9 @@ var AgentDirectory = class _AgentDirectory {
|
|
|
331
379
|
}
|
|
332
380
|
return stored;
|
|
333
381
|
}
|
|
334
|
-
static #childChatId(userId, treeId,
|
|
382
|
+
static #childChatId(userId, treeId, path2) {
|
|
335
383
|
return uuidv5(
|
|
336
|
-
`urn:deepagents:zukhruf:agent:${JSON.stringify([userId, treeId,
|
|
384
|
+
`urn:deepagents:zukhruf:agent:${JSON.stringify([userId, treeId, path2])}`,
|
|
337
385
|
uuidv5.URL
|
|
338
386
|
);
|
|
339
387
|
}
|
|
@@ -402,59 +450,330 @@ var AgentDirectory = class _AgentDirectory {
|
|
|
402
450
|
}
|
|
403
451
|
};
|
|
404
452
|
|
|
405
|
-
// packages/experimental/src/zukhruf/agent-
|
|
406
|
-
import {
|
|
453
|
+
// packages/experimental/src/zukhruf/control-plane/agent-history-forker.ts
|
|
454
|
+
import { validateUIMessages } from "ai";
|
|
455
|
+
import { v5 as uuidv52 } from "uuid";
|
|
407
456
|
import {
|
|
408
|
-
|
|
457
|
+
isSyntheticReminderMessage
|
|
409
458
|
} from "@deepagents/context";
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
QueueOnly: "queue-only",
|
|
415
|
-
TriggerTurn: "trigger-turn"
|
|
416
|
-
};
|
|
417
|
-
var InterAgentCommunicationType = {
|
|
418
|
-
Message: "MESSAGE",
|
|
419
|
-
NewTask: "NEW_TASK",
|
|
420
|
-
FinalAnswer: "FINAL_ANSWER"
|
|
421
|
-
};
|
|
422
|
-
function createInterAgentCommunication(communication) {
|
|
423
|
-
const value = {
|
|
424
|
-
...communication,
|
|
425
|
-
id: communication.id ?? randomUUID(),
|
|
426
|
-
type: communication.type ?? InterAgentCommunicationType.Message,
|
|
427
|
-
otherRecipients: communication.otherRecipients ?? [],
|
|
428
|
-
triggerTurn: false
|
|
429
|
-
};
|
|
430
|
-
assertCommunication(value);
|
|
431
|
-
return value;
|
|
432
|
-
}
|
|
433
|
-
function assertCommunication(communication) {
|
|
434
|
-
if (!communication.id.trim()) {
|
|
435
|
-
throw new Error("inter-agent communication id cannot be empty");
|
|
459
|
+
var AgentHistoryForker = class {
|
|
460
|
+
#store;
|
|
461
|
+
constructor(store) {
|
|
462
|
+
this.#store = store;
|
|
436
463
|
}
|
|
437
|
-
|
|
438
|
-
|
|
464
|
+
async fork(parent, child, forkTurns) {
|
|
465
|
+
const record = await this.#claim(parent, child, forkTurns);
|
|
466
|
+
if (record.forkTurns === "none" || record.parentHeadMessageId === null) {
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
const selected = await this.#selectedMessages(parent, child, record);
|
|
470
|
+
if (selected.length === 0) return;
|
|
471
|
+
const cloned = this.#cloneMessages(child, selected);
|
|
472
|
+
const expectedIds = cloned.map((message) => message.id);
|
|
473
|
+
const branch = await this.#store.getActiveBranch(child.conversation.chatId);
|
|
474
|
+
if (!branch) {
|
|
475
|
+
throw new Error(
|
|
476
|
+
`spawn_agent: child chat "${child.conversation.chatId}" has no active branch`
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
if (branch.headMessageId !== null) {
|
|
480
|
+
if (await this.#hasForkedPrefix(child, expectedIds)) return;
|
|
481
|
+
throw new Error(
|
|
482
|
+
`spawn_agent: cannot apply parent history after child "${child.path}" has started`
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
const head = cloned.at(-1);
|
|
486
|
+
if (!head) return;
|
|
487
|
+
await this.#store.addMessages(cloned);
|
|
488
|
+
const committed = await this.#store.updateBranchHead(
|
|
489
|
+
branch.id,
|
|
490
|
+
head.id,
|
|
491
|
+
null
|
|
492
|
+
);
|
|
493
|
+
if (!committed && !await this.#hasForkedPrefix(child, expectedIds)) {
|
|
494
|
+
throw new Error(
|
|
495
|
+
`spawn_agent: child "${child.path}" started before parent history was applied`
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
if (!await this.#hasForkedPrefix(child, expectedIds)) {
|
|
499
|
+
throw new Error(
|
|
500
|
+
`spawn_agent: failed to persist parent history for child "${child.path}"`
|
|
501
|
+
);
|
|
502
|
+
}
|
|
439
503
|
}
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
504
|
+
async #claim(parent, child, forkTurns) {
|
|
505
|
+
const parentBranch = await this.#store.getActiveBranch(
|
|
506
|
+
parent.conversation.chatId
|
|
507
|
+
);
|
|
508
|
+
if (!parentBranch) {
|
|
509
|
+
throw new Error(
|
|
510
|
+
`spawn_agent: parent chat "${parent.conversation.chatId}" has no active branch`
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
const proposed = {
|
|
514
|
+
forkTurns,
|
|
515
|
+
parentChatId: parent.conversation.chatId,
|
|
516
|
+
parentHeadMessageId: forkTurns === "none" ? null : parentBranch.headMessageId
|
|
517
|
+
};
|
|
518
|
+
let claimed;
|
|
519
|
+
await this.#store.updateChat(child.conversation.chatId, (chat2) => {
|
|
520
|
+
const metadata = chat2.metadata;
|
|
521
|
+
const zukhruf = metadata?.zukhruf;
|
|
522
|
+
if (!isRecord(zukhruf)) {
|
|
523
|
+
throw new Error(
|
|
524
|
+
`spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
|
|
525
|
+
);
|
|
526
|
+
}
|
|
527
|
+
if (zukhruf.historyFork !== void 0) {
|
|
528
|
+
claimed = parseHistoryForkRecord(zukhruf.historyFork);
|
|
529
|
+
if (claimed.parentChatId !== proposed.parentChatId || claimed.forkTurns !== proposed.forkTurns) {
|
|
530
|
+
throw new Error(
|
|
531
|
+
`spawn_agent: agent path "${child.path}" already exists with a different fork_turns setting`
|
|
532
|
+
);
|
|
533
|
+
}
|
|
534
|
+
return void 0;
|
|
535
|
+
}
|
|
536
|
+
claimed = proposed;
|
|
537
|
+
return {
|
|
538
|
+
metadata: {
|
|
539
|
+
...metadata,
|
|
540
|
+
zukhruf: { ...zukhruf, historyFork: proposed }
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
});
|
|
544
|
+
if (!claimed) {
|
|
545
|
+
throw new Error(
|
|
546
|
+
`spawn_agent: failed to claim history for child "${child.path}"`
|
|
547
|
+
);
|
|
548
|
+
}
|
|
549
|
+
return claimed;
|
|
444
550
|
}
|
|
445
|
-
|
|
446
|
-
|
|
551
|
+
async #sourceMessages(parent, record) {
|
|
552
|
+
const headId = record.parentHeadMessageId;
|
|
553
|
+
if (headId === null) return [];
|
|
554
|
+
const chain = await this.#store.getMessageChain(headId);
|
|
555
|
+
if (chain.at(-1)?.id !== headId) {
|
|
556
|
+
throw new Error(
|
|
557
|
+
`spawn_agent: parent history head "${headId}" is unavailable`
|
|
558
|
+
);
|
|
559
|
+
}
|
|
560
|
+
if (chain.some((message) => message.chatId !== parent.conversation.chatId)) {
|
|
561
|
+
throw new Error("spawn_agent: parent history crosses chat boundaries");
|
|
562
|
+
}
|
|
563
|
+
const materialized = chain.filter(
|
|
564
|
+
(message) => !isEmptyAssistantPlaceholder(message.data)
|
|
565
|
+
);
|
|
566
|
+
const messages = await validateUIMessages({
|
|
567
|
+
messages: materialized.map((message) => message.data)
|
|
568
|
+
});
|
|
569
|
+
return materialized.map((stored, index) => {
|
|
570
|
+
const message = messages[index];
|
|
571
|
+
if (message.id !== stored.id) {
|
|
572
|
+
throw new Error(
|
|
573
|
+
`spawn_agent: stored message "${stored.id}" has a mismatched payload id`
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
return { stored, message };
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
async #selectedMessages(parent, child, record) {
|
|
580
|
+
if (record.forkTurns === "none") return [];
|
|
581
|
+
if (record.sourceMessageIds !== void 0) {
|
|
582
|
+
return this.#messagesById(parent, record.sourceMessageIds);
|
|
583
|
+
}
|
|
584
|
+
const source = await this.#sourceMessages(parent, record);
|
|
585
|
+
const selected = this.#select(source, record.forkTurns).map((entry) => this.#keepHistoryMessage(entry)).filter((entry) => entry !== void 0);
|
|
586
|
+
const sourceMessageIds = await this.#claimSelection(
|
|
587
|
+
child,
|
|
588
|
+
selected.map(({ stored }) => stored.id)
|
|
589
|
+
);
|
|
590
|
+
return arraysEqual(
|
|
591
|
+
sourceMessageIds,
|
|
592
|
+
selected.map(({ stored }) => stored.id)
|
|
593
|
+
) ? selected : this.#messagesById(parent, sourceMessageIds);
|
|
594
|
+
}
|
|
595
|
+
async #messagesById(parent, sourceMessageIds) {
|
|
596
|
+
const storedMessages = await Promise.all(
|
|
597
|
+
sourceMessageIds.map((id) => this.#store.getMessage(id))
|
|
598
|
+
);
|
|
599
|
+
if (storedMessages.some(
|
|
600
|
+
(message) => message === void 0 || message.chatId !== parent.conversation.chatId
|
|
601
|
+
)) {
|
|
602
|
+
throw new Error(
|
|
603
|
+
"spawn_agent: persisted parent-history snapshot is unavailable"
|
|
604
|
+
);
|
|
605
|
+
}
|
|
606
|
+
const stored = storedMessages;
|
|
607
|
+
const messages = await validateUIMessages({
|
|
608
|
+
messages: stored.map((message) => message.data)
|
|
609
|
+
});
|
|
610
|
+
return stored.map((messageData, index) => {
|
|
611
|
+
const source = this.#keepHistoryMessage({
|
|
612
|
+
stored: messageData,
|
|
613
|
+
message: messages[index]
|
|
614
|
+
});
|
|
615
|
+
if (!source || source.message.id !== messageData.id) {
|
|
616
|
+
throw new Error(
|
|
617
|
+
`spawn_agent: persisted parent-history message "${messageData.id}" changed shape`
|
|
618
|
+
);
|
|
619
|
+
}
|
|
620
|
+
return source;
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
async #claimSelection(child, proposedIds) {
|
|
624
|
+
let sourceMessageIds;
|
|
625
|
+
await this.#store.updateChat(child.conversation.chatId, (chat2) => {
|
|
626
|
+
const metadata = chat2.metadata;
|
|
627
|
+
const zukhruf = metadata?.zukhruf;
|
|
628
|
+
if (!isRecord(zukhruf)) {
|
|
629
|
+
throw new Error(
|
|
630
|
+
`spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
const record = parseHistoryForkRecord(zukhruf.historyFork);
|
|
634
|
+
if (record.sourceMessageIds !== void 0) {
|
|
635
|
+
sourceMessageIds = record.sourceMessageIds;
|
|
636
|
+
return void 0;
|
|
637
|
+
}
|
|
638
|
+
sourceMessageIds = proposedIds;
|
|
639
|
+
return {
|
|
640
|
+
metadata: {
|
|
641
|
+
...metadata,
|
|
642
|
+
zukhruf: {
|
|
643
|
+
...zukhruf,
|
|
644
|
+
historyFork: { ...record, sourceMessageIds: proposedIds }
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
};
|
|
648
|
+
});
|
|
649
|
+
if (!sourceMessageIds) {
|
|
650
|
+
throw new Error(
|
|
651
|
+
`spawn_agent: failed to claim parent-history messages for child "${child.path}"`
|
|
652
|
+
);
|
|
653
|
+
}
|
|
654
|
+
return sourceMessageIds;
|
|
447
655
|
}
|
|
656
|
+
#select(source, forkTurns) {
|
|
657
|
+
if (forkTurns === "all") return source;
|
|
658
|
+
const boundaries = source.flatMap(
|
|
659
|
+
(entry, index) => isForkTurnBoundary(entry.message) ? [index] : []
|
|
660
|
+
);
|
|
661
|
+
const start = boundaries.at(-forkTurns) ?? boundaries[0];
|
|
662
|
+
return start === void 0 ? [] : source.slice(start);
|
|
663
|
+
}
|
|
664
|
+
#keepHistoryMessage(entry) {
|
|
665
|
+
const { message } = entry;
|
|
666
|
+
if (message.role === "user") {
|
|
667
|
+
if (isSyntheticReminderMessage(message) || interAgentCommunication(message) !== void 0) {
|
|
668
|
+
return void 0;
|
|
669
|
+
}
|
|
670
|
+
return entry;
|
|
671
|
+
}
|
|
672
|
+
if (message.role !== "assistant") return void 0;
|
|
673
|
+
const finalStepStart = message.parts.findLastIndex(
|
|
674
|
+
(part) => part.type === "step-start"
|
|
675
|
+
);
|
|
676
|
+
const parts = message.parts.slice(finalStepStart + 1).filter(
|
|
677
|
+
(part) => ["text", "file", "source-url", "source-document"].includes(part.type)
|
|
678
|
+
);
|
|
679
|
+
return parts.length === 0 ? void 0 : { ...entry, message: { ...message, parts } };
|
|
680
|
+
}
|
|
681
|
+
#cloneMessages(child, selected) {
|
|
682
|
+
let parentId = null;
|
|
683
|
+
return selected.map(({ stored, message }) => {
|
|
684
|
+
const id = uuidv52(
|
|
685
|
+
`urn:deepagents:zukhruf:forked-message:${JSON.stringify([
|
|
686
|
+
child.conversation.chatId,
|
|
687
|
+
stored.id
|
|
688
|
+
])}`,
|
|
689
|
+
uuidv52.URL
|
|
690
|
+
);
|
|
691
|
+
const clone = {
|
|
692
|
+
id,
|
|
693
|
+
chatId: child.conversation.chatId,
|
|
694
|
+
parentId,
|
|
695
|
+
name: message.role,
|
|
696
|
+
type: "message",
|
|
697
|
+
data: { ...message, id },
|
|
698
|
+
createdAt: stored.createdAt
|
|
699
|
+
};
|
|
700
|
+
parentId = id;
|
|
701
|
+
return clone;
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
async #hasForkedPrefix(child, expectedIds) {
|
|
705
|
+
const branch = await this.#store.getActiveBranch(child.conversation.chatId);
|
|
706
|
+
if (!branch?.headMessageId) return false;
|
|
707
|
+
const chain = await this.#store.getMessageChain(branch.headMessageId);
|
|
708
|
+
return expectedIds.every(
|
|
709
|
+
(id, index) => chain[index]?.id === id && chain[index]?.chatId === child.conversation.chatId
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
function isForkTurnBoundary(message) {
|
|
714
|
+
if (message.role !== "user" || isSyntheticReminderMessage(message)) {
|
|
715
|
+
return false;
|
|
716
|
+
}
|
|
717
|
+
return interAgentCommunication(message)?.triggerTurn ?? true;
|
|
448
718
|
}
|
|
449
|
-
function
|
|
450
|
-
if (!
|
|
719
|
+
function interAgentCommunication(message) {
|
|
720
|
+
if (!isRecord(message.metadata)) return void 0;
|
|
721
|
+
if (!Object.hasOwn(message.metadata, "interAgentCommunication")) {
|
|
722
|
+
return void 0;
|
|
723
|
+
}
|
|
724
|
+
const communication = message.metadata.interAgentCommunication;
|
|
725
|
+
if (!isRecord(communication) || typeof communication.triggerTurn !== "boolean") {
|
|
451
726
|
throw new Error(
|
|
452
|
-
`
|
|
727
|
+
`spawn_agent: message "${message.id}" has invalid inter-agent metadata`
|
|
453
728
|
);
|
|
454
729
|
}
|
|
730
|
+
return { triggerTurn: communication.triggerTurn };
|
|
731
|
+
}
|
|
732
|
+
function parseHistoryForkRecord(value) {
|
|
733
|
+
if (!isRecord(value)) {
|
|
734
|
+
throw new Error("spawn_agent: invalid persisted history-fork metadata");
|
|
735
|
+
}
|
|
736
|
+
const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } = value;
|
|
737
|
+
if (!isForkTurns(forkTurns) || typeof parentChatId !== "string" || !parentChatId.trim() || parentHeadMessageId !== null && (typeof parentHeadMessageId !== "string" || parentHeadMessageId.length === 0) || sourceMessageIds !== void 0 && (!Array.isArray(sourceMessageIds) || !sourceMessageIds.every(
|
|
738
|
+
(id) => typeof id === "string" && id.trim().length > 0
|
|
739
|
+
) || new Set(sourceMessageIds).size !== sourceMessageIds.length)) {
|
|
740
|
+
throw new Error("spawn_agent: invalid persisted history-fork metadata");
|
|
741
|
+
}
|
|
742
|
+
return {
|
|
743
|
+
forkTurns,
|
|
744
|
+
parentChatId,
|
|
745
|
+
parentHeadMessageId,
|
|
746
|
+
...sourceMessageIds === void 0 ? {} : { sourceMessageIds }
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
function isForkTurns(value) {
|
|
750
|
+
return value === "none" || value === "all" || typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
751
|
+
}
|
|
752
|
+
function isRecord(value) {
|
|
753
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
754
|
+
}
|
|
755
|
+
function isEmptyAssistantPlaceholder(value) {
|
|
756
|
+
return isRecord(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
|
|
757
|
+
}
|
|
758
|
+
function arraysEqual(left, right) {
|
|
759
|
+
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
455
760
|
}
|
|
456
761
|
|
|
457
|
-
// packages/experimental/src/zukhruf/agent-status-projector.ts
|
|
762
|
+
// packages/experimental/src/zukhruf/control-plane/agent-status-projector.ts
|
|
763
|
+
import { isTextUIPart } from "ai";
|
|
764
|
+
import { z } from "zod";
|
|
765
|
+
import {
|
|
766
|
+
ContextEngine
|
|
767
|
+
} from "@deepagents/context";
|
|
768
|
+
var listedAgentStatusSchema = z.union([
|
|
769
|
+
z.enum(["pending_init", "running", "interrupted", "shutdown", "not_found"]),
|
|
770
|
+
z.object({ completed: z.string().nullable() }).strict(),
|
|
771
|
+
z.object({ errored: z.string() }).strict()
|
|
772
|
+
]);
|
|
773
|
+
var listedAgentSchema = z.object({
|
|
774
|
+
agent_name: z.string(),
|
|
775
|
+
agent_status: listedAgentStatusSchema
|
|
776
|
+
}).strict();
|
|
458
777
|
var AgentStatusProjector = class _AgentStatusProjector {
|
|
459
778
|
#store;
|
|
460
779
|
#streams;
|
|
@@ -475,22 +794,22 @@ var AgentStatusProjector = class _AgentStatusProjector {
|
|
|
475
794
|
const head = messages.at(-1);
|
|
476
795
|
const streamId = thread.lastTurnId ?? (head?.role === "assistant" ? head.id : void 0);
|
|
477
796
|
const stream = streamId ? await this.#streams.store.getStream(streamId) : void 0;
|
|
478
|
-
const
|
|
797
|
+
const scheduledTurn = await this.#queue.getCurrentTurn(thread.conversation);
|
|
798
|
+
const scheduledStream = scheduledTurn ? await this.#streams.store.getStream(scheduledTurn.streamId) : void 0;
|
|
479
799
|
let status = _AgentStatusProjector.#listedStatus(
|
|
480
800
|
stream?.status,
|
|
481
801
|
stream?.error,
|
|
482
802
|
head
|
|
483
803
|
);
|
|
484
804
|
if (stream?.status === "completed" && this.#approvals.isPaused(head)) {
|
|
485
|
-
status = "
|
|
805
|
+
status = "running";
|
|
486
806
|
}
|
|
487
|
-
if (thread.conversation.chatId === currentTurn.chatId ||
|
|
807
|
+
if (thread.conversation.chatId === currentTurn.chatId || thread.lastTurnId !== void 0 && scheduledTurn?.streamId !== thread.lastTurnId && (scheduledStream?.status === "queued" || scheduledStream?.status === "running")) {
|
|
488
808
|
status = "running";
|
|
489
809
|
}
|
|
490
810
|
return {
|
|
491
811
|
agent_name: thread.path.toString(),
|
|
492
|
-
agent_status: status
|
|
493
|
-
last_task_message: thread.path.isRoot ? "Main thread" : _AgentStatusProjector.#lastUserMessage(messages)
|
|
812
|
+
agent_status: status
|
|
494
813
|
};
|
|
495
814
|
}
|
|
496
815
|
async projectTerminal(turn, thread) {
|
|
@@ -506,7 +825,12 @@ var AgentStatusProjector = class _AgentStatusProjector {
|
|
|
506
825
|
return;
|
|
507
826
|
}
|
|
508
827
|
const text = message?.role === "assistant" ? _AgentStatusProjector.#messageText(message) : "";
|
|
509
|
-
|
|
828
|
+
let content = text || "Agent completed without a text response.";
|
|
829
|
+
if (stream.status === "failed") {
|
|
830
|
+
content = `Agent failed: ${stream.error || "unknown error"}`;
|
|
831
|
+
} else if (stream.status === "cancelled") {
|
|
832
|
+
content = "Agent was interrupted.";
|
|
833
|
+
}
|
|
510
834
|
const parent = await this.#directory.load({
|
|
511
835
|
chatId: thread.parentChatId,
|
|
512
836
|
userId: thread.conversation.userId
|
|
@@ -556,22 +880,13 @@ var AgentStatusProjector = class _AgentStatusProjector {
|
|
|
556
880
|
return "pending_init";
|
|
557
881
|
}
|
|
558
882
|
}
|
|
559
|
-
static #lastUserMessage(messages) {
|
|
560
|
-
for (let index = messages.length - 1; index >= 0; index--) {
|
|
561
|
-
const message = messages[index];
|
|
562
|
-
if (message?.role === "user") {
|
|
563
|
-
return _AgentStatusProjector.#messageText(message) || null;
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
return null;
|
|
567
|
-
}
|
|
568
883
|
static #messageText(message) {
|
|
569
884
|
return message.parts.filter(isTextUIPart).map((part) => part.text).join("\n").trim();
|
|
570
885
|
}
|
|
571
886
|
};
|
|
572
887
|
|
|
573
|
-
// packages/experimental/src/zukhruf/agent-turn-id.ts
|
|
574
|
-
import { v5 as
|
|
888
|
+
// packages/experimental/src/zukhruf/control-plane/agent-turn-id.ts
|
|
889
|
+
import { v5 as uuidv53 } from "uuid";
|
|
575
890
|
var AgentTurnId = class _AgentTurnId {
|
|
576
891
|
static #prefix = "zukhruf-turn";
|
|
577
892
|
#value;
|
|
@@ -582,16 +897,16 @@ var AgentTurnId = class _AgentTurnId {
|
|
|
582
897
|
if (!requestId.trim()) {
|
|
583
898
|
throw new Error("turn id cannot be empty");
|
|
584
899
|
}
|
|
585
|
-
const scope =
|
|
900
|
+
const scope = conversationNamespace(conversation);
|
|
586
901
|
return new _AgentTurnId(
|
|
587
|
-
`${_AgentTurnId.#prefix}:${scope}:${
|
|
902
|
+
`${_AgentTurnId.#prefix}:${scope}:${uuidv53(requestId, scope)}`
|
|
588
903
|
);
|
|
589
904
|
}
|
|
590
905
|
static random(conversation) {
|
|
591
906
|
return _AgentTurnId.fromRequest(conversation, crypto.randomUUID());
|
|
592
907
|
}
|
|
593
908
|
static assertOwner(conversation, streamId) {
|
|
594
|
-
const expectedPrefix = `${_AgentTurnId.#prefix}:${
|
|
909
|
+
const expectedPrefix = `${_AgentTurnId.#prefix}:${conversationNamespace(conversation)}:`;
|
|
595
910
|
if (!streamId.startsWith(expectedPrefix)) {
|
|
596
911
|
throw new Error(
|
|
597
912
|
`stream "${streamId}" does not belong to conversation "${conversation.chatId}"`
|
|
@@ -601,18 +916,18 @@ var AgentTurnId = class _AgentTurnId {
|
|
|
601
916
|
toString() {
|
|
602
917
|
return this.#value;
|
|
603
918
|
}
|
|
604
|
-
static #scope(conversation) {
|
|
605
|
-
if (!conversation.chatId.trim() || !conversation.userId.trim()) {
|
|
606
|
-
throw new Error("conversation requires non-empty chatId and userId");
|
|
607
|
-
}
|
|
608
|
-
return uuidv52(
|
|
609
|
-
JSON.stringify([conversation.userId, conversation.chatId]),
|
|
610
|
-
uuidv52.URL
|
|
611
|
-
);
|
|
612
|
-
}
|
|
613
919
|
};
|
|
920
|
+
function conversationNamespace(conversation) {
|
|
921
|
+
if (!conversation.chatId.trim() || !conversation.userId.trim()) {
|
|
922
|
+
throw new Error("conversation requires non-empty chatId and userId");
|
|
923
|
+
}
|
|
924
|
+
return uuidv53(
|
|
925
|
+
JSON.stringify([conversation.userId, conversation.chatId]),
|
|
926
|
+
uuidv53.URL
|
|
927
|
+
);
|
|
928
|
+
}
|
|
614
929
|
|
|
615
|
-
// packages/experimental/src/zukhruf/agent-control-plane.ts
|
|
930
|
+
// packages/experimental/src/zukhruf/control-plane/agent-control-plane.ts
|
|
616
931
|
var AgentControlPlane = class _AgentControlPlane {
|
|
617
932
|
#root;
|
|
618
933
|
#streams;
|
|
@@ -621,6 +936,7 @@ var AgentControlPlane = class _AgentControlPlane {
|
|
|
621
936
|
#declarations;
|
|
622
937
|
#directory;
|
|
623
938
|
#statusProjector;
|
|
939
|
+
#historyForker;
|
|
624
940
|
constructor(options) {
|
|
625
941
|
this.#root = options.root;
|
|
626
942
|
this.#streams = options.streams;
|
|
@@ -629,6 +945,7 @@ var AgentControlPlane = class _AgentControlPlane {
|
|
|
629
945
|
this.#declarations = options.declarations;
|
|
630
946
|
this.#directory = options.directory;
|
|
631
947
|
this.#statusProjector = options.statusProjector;
|
|
948
|
+
this.#historyForker = options.historyForker;
|
|
632
949
|
}
|
|
633
950
|
async resolve(conversation) {
|
|
634
951
|
const thread = await this.#directory.loadOrCreateRoot(
|
|
@@ -707,11 +1024,12 @@ var AgentControlPlane = class _AgentControlPlane {
|
|
|
707
1024
|
`spawn_agent: agent path "${childPath}" already finished with status "${status}"`
|
|
708
1025
|
);
|
|
709
1026
|
}
|
|
1027
|
+
await this.#historyForker.fork(actor.thread, child, input.forkTurns);
|
|
710
1028
|
await this.enqueue(child.conversation, {
|
|
711
1029
|
id: requestId,
|
|
712
1030
|
input: input.message
|
|
713
1031
|
});
|
|
714
|
-
return { task_name:
|
|
1032
|
+
return { task_name: childPath };
|
|
715
1033
|
}
|
|
716
1034
|
async sendMessage(actor, input) {
|
|
717
1035
|
return this.#deliverAgentMessage(actor, input, {
|
|
@@ -741,6 +1059,38 @@ var AgentControlPlane = class _AgentControlPlane {
|
|
|
741
1059
|
);
|
|
742
1060
|
return { agents };
|
|
743
1061
|
}
|
|
1062
|
+
async interruptAgent(actor, input) {
|
|
1063
|
+
const target = await this.#directory.find(actor.thread, input.target);
|
|
1064
|
+
if (!target) return { previous_status: "not_found" };
|
|
1065
|
+
if (target.path.isRoot) {
|
|
1066
|
+
throw new Error("interrupt_agent: the root agent cannot be interrupted");
|
|
1067
|
+
}
|
|
1068
|
+
if (target.path.equals(actor.thread.path)) {
|
|
1069
|
+
throw new Error("interrupt_agent: an agent cannot interrupt itself");
|
|
1070
|
+
}
|
|
1071
|
+
const previous = await this.#statusProjector.projectListedAgent(
|
|
1072
|
+
actor.turn,
|
|
1073
|
+
target
|
|
1074
|
+
);
|
|
1075
|
+
const currentTurn = await this.#queue.getCurrentTurn(target.conversation);
|
|
1076
|
+
if (currentTurn) {
|
|
1077
|
+
const interruptedThread = await this.#directory.recordLatestTurnIfCurrent(
|
|
1078
|
+
target.conversation,
|
|
1079
|
+
currentTurn.streamId,
|
|
1080
|
+
target.lastTurnId
|
|
1081
|
+
) ?? target;
|
|
1082
|
+
await this.#streams.cancel(currentTurn.streamId);
|
|
1083
|
+
await this.#statusProjector.projectTerminal(
|
|
1084
|
+
currentTurn,
|
|
1085
|
+
interruptedThread
|
|
1086
|
+
);
|
|
1087
|
+
await this.#queue.cancel(currentTurn.streamId);
|
|
1088
|
+
}
|
|
1089
|
+
return { previous_status: previous.agent_status };
|
|
1090
|
+
}
|
|
1091
|
+
waitForMailbox(actor, options) {
|
|
1092
|
+
return this.#mailbox.waitForPending(actor.thread.conversation, options);
|
|
1093
|
+
}
|
|
744
1094
|
async projectTerminal(turn, thread) {
|
|
745
1095
|
await this.#statusProjector.projectTerminal(turn, thread);
|
|
746
1096
|
}
|
|
@@ -767,92 +1117,499 @@ var AgentControlPlane = class _AgentControlPlane {
|
|
|
767
1117
|
return { target: target.path.toString() };
|
|
768
1118
|
}
|
|
769
1119
|
static #initialTurnId(chatId) {
|
|
770
|
-
return
|
|
1120
|
+
return uuidv54(`urn:deepagents:zukhruf:initial-turn:${chatId}`, uuidv54.URL);
|
|
771
1121
|
}
|
|
772
1122
|
};
|
|
773
1123
|
|
|
774
|
-
// packages/experimental/src/zukhruf/
|
|
775
|
-
import {
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
1124
|
+
// packages/experimental/src/zukhruf/mailbox/coordinator.ts
|
|
1125
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
1126
|
+
var WAIT_POLL_INTERVAL_MS = 50;
|
|
1127
|
+
var MailboxCoordinator = class {
|
|
1128
|
+
#store;
|
|
1129
|
+
#queue;
|
|
1130
|
+
#streams;
|
|
1131
|
+
#wakeRequests = /* @__PURE__ */ new Map();
|
|
1132
|
+
constructor(options) {
|
|
1133
|
+
this.#store = options.store;
|
|
1134
|
+
this.#queue = options.queue;
|
|
1135
|
+
this.#streams = options.streams;
|
|
1136
|
+
}
|
|
1137
|
+
async deliver(communication, mode) {
|
|
1138
|
+
const delivered = {
|
|
1139
|
+
...communication,
|
|
1140
|
+
type: mode === MessageDeliveryMode.TriggerTurn ? InterAgentCommunicationType.NewTask : communication.type,
|
|
1141
|
+
triggerTurn: mode === MessageDeliveryMode.TriggerTurn
|
|
1142
|
+
};
|
|
1143
|
+
assertCommunication(delivered);
|
|
1144
|
+
const { recipientActive } = await this.#store.enqueue(delivered);
|
|
1145
|
+
if (delivered.triggerTurn || recipientActive) {
|
|
1146
|
+
await this.#scheduleWake(delivered.recipient);
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
beginTurn(turn) {
|
|
1150
|
+
return this.#store.beginTurn(turn, turn.streamId);
|
|
1151
|
+
}
|
|
1152
|
+
async endTurn(turn, options = {}) {
|
|
1153
|
+
const { hasPending, turnEnded } = await this.#store.endTurn(
|
|
1154
|
+
turn,
|
|
1155
|
+
turn.streamId
|
|
1156
|
+
);
|
|
1157
|
+
if (turnEnded && hasPending && !options.parked) {
|
|
1158
|
+
await this.#scheduleWake(turn);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
drainLeadingQueueOnly(recipient) {
|
|
1162
|
+
return this.#store.drainLeadingQueueOnly(recipient);
|
|
1163
|
+
}
|
|
1164
|
+
drain(recipient) {
|
|
1165
|
+
return this.#store.drain(recipient);
|
|
1166
|
+
}
|
|
1167
|
+
async waitForPending(recipient, options) {
|
|
1168
|
+
const deadline = Date.now() + options.timeoutMs;
|
|
1169
|
+
while (true) {
|
|
1170
|
+
options.signal?.throwIfAborted();
|
|
1171
|
+
if (await this.#store.hasPending(recipient)) return true;
|
|
1172
|
+
const remaining = deadline - Date.now();
|
|
1173
|
+
if (remaining <= 0) return false;
|
|
1174
|
+
await delay(Math.min(WAIT_POLL_INTERVAL_MS, remaining), void 0, {
|
|
1175
|
+
signal: options.signal
|
|
1176
|
+
});
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
#scheduleWake(target) {
|
|
1180
|
+
const key = this.#conversationKey(target);
|
|
1181
|
+
const existing = this.#wakeRequests.get(key);
|
|
1182
|
+
if (existing) return existing;
|
|
1183
|
+
const request = (async () => {
|
|
1184
|
+
const wakeId = AgentTurnId.random(target).toString();
|
|
1185
|
+
await this.#streams.register(wakeId);
|
|
1186
|
+
try {
|
|
1187
|
+
await this.#queue.push({
|
|
1188
|
+
kind: "mailbox",
|
|
1189
|
+
streamId: wakeId,
|
|
1190
|
+
chatId: target.chatId,
|
|
1191
|
+
userId: target.userId
|
|
1192
|
+
});
|
|
1193
|
+
} catch (error) {
|
|
1194
|
+
await this.#streams.store.updateStreamStatus(wakeId, "failed", {
|
|
1195
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1196
|
+
});
|
|
1197
|
+
throw error;
|
|
1198
|
+
}
|
|
1199
|
+
})();
|
|
1200
|
+
this.#wakeRequests.set(key, request);
|
|
1201
|
+
const clearRequest = () => {
|
|
1202
|
+
if (this.#wakeRequests.get(key) === request) {
|
|
1203
|
+
this.#wakeRequests.delete(key);
|
|
1204
|
+
}
|
|
1205
|
+
};
|
|
1206
|
+
void request.then(clearRequest, clearRequest);
|
|
1207
|
+
return request;
|
|
1208
|
+
}
|
|
1209
|
+
#conversationKey(conversation) {
|
|
1210
|
+
return JSON.stringify([conversation.chatId, conversation.userId]);
|
|
1211
|
+
}
|
|
1212
|
+
};
|
|
1213
|
+
|
|
1214
|
+
// packages/experimental/src/zukhruf/multi-agent-v2-config.ts
|
|
1215
|
+
var DEFAULT_MIN_WAIT_TIMEOUT_MS = 1e4;
|
|
1216
|
+
var DEFAULT_WAIT_TIMEOUT_MS = 3e4;
|
|
1217
|
+
var DEFAULT_MAX_WAIT_TIMEOUT_MS = 36e5;
|
|
1218
|
+
var RESERVED_TOOL_NAMESPACES = /* @__PURE__ */ new Set([
|
|
1219
|
+
"api_tool",
|
|
1220
|
+
"browser",
|
|
1221
|
+
"computer",
|
|
1222
|
+
"container",
|
|
1223
|
+
"file_search",
|
|
1224
|
+
"functions",
|
|
1225
|
+
"image_gen",
|
|
1226
|
+
"multi_tool_use",
|
|
1227
|
+
"python",
|
|
1228
|
+
"python_user_visible",
|
|
1229
|
+
"submodel_delegator",
|
|
1230
|
+
"terminal",
|
|
1231
|
+
"tool_search",
|
|
1232
|
+
"web"
|
|
1233
|
+
]);
|
|
1234
|
+
function resolveMultiAgentV2HostConfig(input = {}) {
|
|
1235
|
+
const minWaitTimeoutMs = input.minWaitTimeoutMs ?? DEFAULT_MIN_WAIT_TIMEOUT_MS;
|
|
1236
|
+
const defaultWaitTimeoutMs = input.defaultWaitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
|
|
1237
|
+
const maxWaitTimeoutMs = input.maxWaitTimeoutMs ?? DEFAULT_MAX_WAIT_TIMEOUT_MS;
|
|
1238
|
+
assertTimeout("minWaitTimeoutMs", minWaitTimeoutMs);
|
|
1239
|
+
assertTimeout("defaultWaitTimeoutMs", defaultWaitTimeoutMs);
|
|
1240
|
+
assertTimeout("maxWaitTimeoutMs", maxWaitTimeoutMs);
|
|
1241
|
+
if (minWaitTimeoutMs > maxWaitTimeoutMs) {
|
|
1242
|
+
throw new Error(
|
|
1243
|
+
"AgentRuntime: multiAgentV2.minWaitTimeoutMs must be at most maxWaitTimeoutMs"
|
|
1244
|
+
);
|
|
1245
|
+
}
|
|
1246
|
+
if (defaultWaitTimeoutMs < minWaitTimeoutMs) {
|
|
1247
|
+
throw new Error(
|
|
1248
|
+
"AgentRuntime: multiAgentV2.defaultWaitTimeoutMs must be at least minWaitTimeoutMs"
|
|
1249
|
+
);
|
|
1250
|
+
}
|
|
1251
|
+
if (defaultWaitTimeoutMs > maxWaitTimeoutMs) {
|
|
1252
|
+
throw new Error(
|
|
1253
|
+
"AgentRuntime: multiAgentV2.defaultWaitTimeoutMs must be at most maxWaitTimeoutMs"
|
|
1254
|
+
);
|
|
1255
|
+
}
|
|
1256
|
+
const toolNamespace = input.toolNamespace;
|
|
1257
|
+
if (toolNamespace !== void 0 && (toolNamespace.length === 0 || toolNamespace.trim() !== toolNamespace)) {
|
|
1258
|
+
throw new Error(
|
|
1259
|
+
"AgentRuntime: multiAgentV2.toolNamespace cannot be empty or padded"
|
|
1260
|
+
);
|
|
1261
|
+
}
|
|
1262
|
+
if (toolNamespace !== void 0) validateToolNamespace(toolNamespace);
|
|
1263
|
+
const nonCodeModeOnly = input.nonCodeModeOnly ?? true;
|
|
1264
|
+
if (!nonCodeModeOnly) {
|
|
1265
|
+
throw new Error(
|
|
1266
|
+
"AgentRuntime: multiAgentV2.nonCodeModeOnly=false requires a nested code-mode executor, which Zukhruf does not provide"
|
|
1267
|
+
);
|
|
1268
|
+
}
|
|
1269
|
+
const tool7 = (name) => toolNamespace === void 0 ? name : `${toolNamespace}.${name}`;
|
|
1270
|
+
const collaborationTools = [
|
|
1271
|
+
"spawn_agent",
|
|
1272
|
+
"send_message",
|
|
1273
|
+
"followup_task",
|
|
1274
|
+
"wait_agent",
|
|
1275
|
+
"interrupt_agent",
|
|
1276
|
+
"list_agents"
|
|
1277
|
+
].map((name) => `\`${tool7(name)}\``).join(", ");
|
|
1278
|
+
const shared = `Call ${collaborationTools} directly. They are intentionally unavailable inside nested code execution.
|
|
1279
|
+
|
|
1280
|
+
All agents share the same workspace, current working directory, and filesystem.`;
|
|
1281
|
+
return {
|
|
1282
|
+
minWaitTimeoutMs,
|
|
1283
|
+
defaultWaitTimeoutMs,
|
|
1284
|
+
maxWaitTimeoutMs,
|
|
1285
|
+
usageHintText: nonEmptyText(input.usageHintText),
|
|
1286
|
+
rootAgentUsageHintText: input.rootAgentUsageHintText === void 0 ? defaultRootUsageHint(tool7, shared) : nonEmptyText(input.rootAgentUsageHintText),
|
|
1287
|
+
subagentUsageHintText: input.subagentUsageHintText === void 0 ? defaultSubagentUsageHint(tool7, shared) : nonEmptyText(input.subagentUsageHintText),
|
|
1288
|
+
toolNamespace,
|
|
1289
|
+
nonCodeModeOnly
|
|
1290
|
+
};
|
|
1291
|
+
}
|
|
1292
|
+
function assertTimeout(name, value) {
|
|
1293
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
1294
|
+
throw new Error(
|
|
1295
|
+
`AgentRuntime: multiAgentV2.${name} must be a non-negative safe integer`
|
|
1296
|
+
);
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
function validateToolNamespace(namespace) {
|
|
1300
|
+
if (namespace.length > 64 || !/^[a-zA-Z0-9_-]+$/.test(namespace) || namespace === "mcp" || namespace.startsWith("mcp__") || RESERVED_TOOL_NAMESPACES.has(namespace)) {
|
|
1301
|
+
throw new Error(
|
|
1302
|
+
`AgentRuntime: multiAgentV2.toolNamespace "${namespace}" is a reserved tool namespace or invalid`
|
|
1303
|
+
);
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
function nonEmptyText(value) {
|
|
1307
|
+
if (value === void 0) return void 0;
|
|
1308
|
+
return value.length === 0 ? void 0 : value;
|
|
1309
|
+
}
|
|
1310
|
+
function defaultRootUsageHint(tool7, shared) {
|
|
1311
|
+
return `You are \`/root\`, the primary agent in a team of agents collaborating to fulfill the user's goals.
|
|
1312
|
+
|
|
1313
|
+
At the start of your turn, you are the active agent. You can spawn sub-agents to handle subtasks, and those agents can recursively spawn their own declared sub-agents. All agents are equally capable and receive the tools declared for their agent type.
|
|
1314
|
+
|
|
1315
|
+
Use \`${tool7("spawn_agent")}\` to create an agent, \`${tool7("followup_task")}\` to assign a new task and trigger a turn, and \`${tool7("send_message")}\` to queue a message without triggering a turn. Use \`fork_turns\` to control how much parent history the child receives.
|
|
1316
|
+
|
|
1317
|
+
Child messages arrive as \`MESSAGE\` or \`FINAL_ANSWER\` mailbox envelopes with their task name, sender, and payload preserved.
|
|
1318
|
+
|
|
1319
|
+
${shared}`;
|
|
1320
|
+
}
|
|
1321
|
+
function defaultSubagentUsageHint(tool7, shared) {
|
|
1322
|
+
return `You are an agent in a team collaborating to complete a task.
|
|
1323
|
+
|
|
1324
|
+
You can spawn declared sub-agents recursively. All agents are equally capable and receive the tools declared for their agent type. Use \`${tool7("spawn_agent")}\` to create one, \`${tool7("followup_task")}\` to assign a new task and trigger a turn, and \`${tool7("send_message")}\` to queue a message for another agent.
|
|
1325
|
+
|
|
1326
|
+
Your final response is delivered automatically to your parent agent. Mailbox messages arrive as \`NEW_TASK\`, \`MESSAGE\`, or \`FINAL_ANSWER\` envelopes with their task name, sender, and payload preserved.
|
|
1327
|
+
|
|
1328
|
+
${shared}`;
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
// packages/experimental/src/zukhruf/runtime/agent-turn-executor.ts
|
|
1332
|
+
import {
|
|
1333
|
+
ContextEngine as ContextEngine2,
|
|
1334
|
+
agent,
|
|
1335
|
+
assistant,
|
|
1336
|
+
chat,
|
|
1337
|
+
role,
|
|
1338
|
+
user
|
|
1339
|
+
} from "@deepagents/context";
|
|
1340
|
+
|
|
1341
|
+
// packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
|
|
1342
|
+
import { tool } from "ai";
|
|
1343
|
+
import { z as z2 } from "zod";
|
|
1344
|
+
var interruptAgentInputSchema = z2.object({
|
|
1345
|
+
target: z2.string().trim().min(1).describe(
|
|
1346
|
+
"The canonical /root/... path, or a descendant-relative target name."
|
|
1347
|
+
)
|
|
1348
|
+
});
|
|
1349
|
+
var interruptAgentOutputSchema = z2.object({ previous_status: listedAgentStatusSchema }).strict();
|
|
1350
|
+
var interruptAgentTool = tool({
|
|
1351
|
+
description: "Interrupt an agent's current turn, if any, and return its previous status. The agent remains available for messages and follow-up tasks.",
|
|
1352
|
+
inputSchema: interruptAgentInputSchema,
|
|
1353
|
+
outputSchema: interruptAgentOutputSchema,
|
|
1354
|
+
execute: async (input, { context }) => context.controlPlane.interruptAgent(context.actor, input)
|
|
1355
|
+
});
|
|
1356
|
+
|
|
1357
|
+
// packages/experimental/src/zukhruf/collaboration/list-agents.ts
|
|
1358
|
+
import { tool as tool2 } from "ai";
|
|
1359
|
+
import { z as z3 } from "zod";
|
|
1360
|
+
var listAgentsInputSchema = z3.object({
|
|
1361
|
+
path_prefix: z3.string().trim().min(1).describe(
|
|
788
1362
|
"Task-path prefix without a trailing slash. Omit to list the whole tree."
|
|
789
1363
|
).optional()
|
|
790
1364
|
});
|
|
791
|
-
var
|
|
1365
|
+
var listAgentsOutputSchema = z3.object({ agents: z3.array(listedAgentSchema) }).strict();
|
|
1366
|
+
var listAgentsTool = tool2({
|
|
792
1367
|
description: "List live agents in the current root thread tree. Optionally filter by task-path prefix.",
|
|
793
1368
|
inputSchema: listAgentsInputSchema,
|
|
1369
|
+
outputSchema: listAgentsOutputSchema,
|
|
794
1370
|
execute: async ({ path_prefix }, { context }) => context.controlPlane.listAgents(context.actor, path_prefix)
|
|
795
1371
|
});
|
|
796
1372
|
|
|
797
|
-
// packages/experimental/src/zukhruf/message-tools.ts
|
|
798
|
-
import { tool as
|
|
799
|
-
import { z as
|
|
800
|
-
var agentMessageInputSchema =
|
|
801
|
-
target:
|
|
1373
|
+
// packages/experimental/src/zukhruf/collaboration/message-tools.ts
|
|
1374
|
+
import { tool as tool3 } from "ai";
|
|
1375
|
+
import { z as z4 } from "zod";
|
|
1376
|
+
var agentMessageInputSchema = z4.object({
|
|
1377
|
+
target: z4.string().trim().min(1).describe(
|
|
802
1378
|
"The canonical /root/... path, or a descendant-relative target name."
|
|
803
1379
|
),
|
|
804
|
-
message:
|
|
1380
|
+
message: z4.string().trim().min(1).describe("The message or follow-up task.")
|
|
805
1381
|
});
|
|
806
|
-
var sendMessageTool =
|
|
1382
|
+
var sendMessageTool = tool3({
|
|
807
1383
|
description: "Queue a message for another agent. Address siblings with their canonical /root/... path.",
|
|
808
1384
|
inputSchema: agentMessageInputSchema,
|
|
809
|
-
execute: async (input, { context }) =>
|
|
1385
|
+
execute: async (input, { context }) => {
|
|
1386
|
+
await context.controlPlane.sendMessage(context.actor, input);
|
|
1387
|
+
return "";
|
|
1388
|
+
}
|
|
810
1389
|
});
|
|
811
|
-
var followupTaskTool =
|
|
1390
|
+
var followupTaskTool = tool3({
|
|
812
1391
|
description: "Send a follow-up task to an existing non-root agent and wake its thread.",
|
|
813
1392
|
inputSchema: agentMessageInputSchema,
|
|
814
|
-
execute: async (input, { context }) =>
|
|
1393
|
+
execute: async (input, { context }) => {
|
|
1394
|
+
await context.controlPlane.followupTask(context.actor, input);
|
|
1395
|
+
return "";
|
|
1396
|
+
}
|
|
815
1397
|
});
|
|
816
1398
|
|
|
817
|
-
// packages/experimental/src/zukhruf/spawn-agent.ts
|
|
818
|
-
import { tool as
|
|
819
|
-
import { z as
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
1399
|
+
// packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
|
|
1400
|
+
import { tool as tool4 } from "ai";
|
|
1401
|
+
import { z as z5 } from "zod";
|
|
1402
|
+
|
|
1403
|
+
// packages/experimental/src/zukhruf/control-plane/fork-turns.ts
|
|
1404
|
+
var forkTurnsError = "fork_turns must be `none`, `all`, or a positive integer string";
|
|
1405
|
+
function parseForkTurns(value) {
|
|
1406
|
+
const normalized = value.trim().toLowerCase();
|
|
1407
|
+
if (normalized === "none" || normalized === "all") return normalized;
|
|
1408
|
+
if (!/^\d+$/.test(normalized)) return void 0;
|
|
1409
|
+
const turns = Number(normalized);
|
|
1410
|
+
return Number.isSafeInteger(turns) && turns > 0 ? turns : void 0;
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
// packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
|
|
1414
|
+
var spawnAgentInputSchema = z5.object({
|
|
1415
|
+
agent_type: z5.string().trim().min(1).describe("The name of one available subagent declaration."),
|
|
1416
|
+
task_name: z5.string().trim().min(1).refine(
|
|
823
1417
|
(value) => value !== "." && value !== ".." && !value.includes("/"),
|
|
824
1418
|
"task_name must be one non-empty path segment"
|
|
825
1419
|
).describe("One path segment naming this independent agent task."),
|
|
826
|
-
message:
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
const available = (context.actor.declaration.subagents ?? []).map((subagent) => subagent.name).join(", ");
|
|
831
|
-
return `Spawn an independent subagent. Available agent types: ${available || "none"}.`;
|
|
832
|
-
},
|
|
833
|
-
inputSchema: spawnAgentInputSchema,
|
|
834
|
-
execute: async ({ agent_type, task_name, message }, { context }) => context.controlPlane.spawn(context.actor, {
|
|
835
|
-
agentType: agent_type,
|
|
836
|
-
taskName: task_name,
|
|
837
|
-
message
|
|
838
|
-
})
|
|
1420
|
+
message: z5.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent."),
|
|
1421
|
+
fork_turns: z5.string().trim().default("all").refine((value) => parseForkTurns(value) !== void 0, forkTurnsError).describe(
|
|
1422
|
+
"Optional number of parent turns to fork. Defaults to `all`. Use `none`, `all`, or a positive integer string such as `3`."
|
|
1423
|
+
)
|
|
839
1424
|
});
|
|
1425
|
+
var spawnAgentOutputSchema = z5.object({ task_name: z5.string() }).strict();
|
|
1426
|
+
function createSpawnAgentTool(options) {
|
|
1427
|
+
return tool4({
|
|
1428
|
+
description: ({ context }) => {
|
|
1429
|
+
const available = (context.actor.declaration.subagents ?? []).map((subagent) => subagent.name).join(", ");
|
|
1430
|
+
return [
|
|
1431
|
+
`Spawn an independent subagent. Available agent types: ${available || "none"}.`,
|
|
1432
|
+
options?.usageHintText
|
|
1433
|
+
].filter(Boolean).join(" ");
|
|
1434
|
+
},
|
|
1435
|
+
inputSchema: spawnAgentInputSchema,
|
|
1436
|
+
outputSchema: spawnAgentOutputSchema,
|
|
1437
|
+
execute: async ({ agent_type, task_name, message, fork_turns }, { context }) => {
|
|
1438
|
+
const forkTurns = parseForkTurns(fork_turns);
|
|
1439
|
+
if (forkTurns === void 0) throw new Error(forkTurnsError);
|
|
1440
|
+
return context.controlPlane.spawn(context.actor, {
|
|
1441
|
+
agentType: agent_type,
|
|
1442
|
+
taskName: task_name,
|
|
1443
|
+
message,
|
|
1444
|
+
forkTurns
|
|
1445
|
+
});
|
|
1446
|
+
}
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
840
1449
|
|
|
841
|
-
// packages/experimental/src/zukhruf/agent
|
|
1450
|
+
// packages/experimental/src/zukhruf/collaboration/wait-agent.ts
|
|
1451
|
+
import { tool as tool5 } from "ai";
|
|
1452
|
+
import { z as z6 } from "zod";
|
|
1453
|
+
var waitAgentOutputSchema = z6.object({ message: z6.string(), timed_out: z6.boolean() }).strict();
|
|
1454
|
+
function createWaitAgentTool(options) {
|
|
1455
|
+
const waitAgentInputSchema = z6.object({
|
|
1456
|
+
timeout_ms: z6.number().int().min(options.minTimeoutMs).max(options.maxTimeoutMs).optional().describe("Maximum time to wait in milliseconds.")
|
|
1457
|
+
});
|
|
1458
|
+
return tool5({
|
|
1459
|
+
description: "Wait for pending mail addressed to this agent without consuming it.",
|
|
1460
|
+
inputSchema: waitAgentInputSchema,
|
|
1461
|
+
outputSchema: waitAgentOutputSchema,
|
|
1462
|
+
execute: async ({ timeout_ms }, { abortSignal, context }) => {
|
|
1463
|
+
const received = await context.controlPlane.waitForMailbox(
|
|
1464
|
+
context.actor,
|
|
1465
|
+
{
|
|
1466
|
+
timeoutMs: timeout_ms ?? options.defaultTimeoutMs,
|
|
1467
|
+
signal: abortSignal
|
|
1468
|
+
}
|
|
1469
|
+
);
|
|
1470
|
+
return received ? { message: "Wait completed.", timed_out: false } : { message: "Wait timed out.", timed_out: true };
|
|
1471
|
+
}
|
|
1472
|
+
});
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
// packages/experimental/src/zukhruf/collaboration/collaboration-tools.ts
|
|
1476
|
+
var NAMESPACE_DESCRIPTION = "Tools for spawning and managing sub-agents.";
|
|
1477
|
+
function createCollaborationTools(config) {
|
|
1478
|
+
const tools = {
|
|
1479
|
+
spawn_agent: createSpawnAgentTool({
|
|
1480
|
+
usageHintText: config.usageHintText
|
|
1481
|
+
}),
|
|
1482
|
+
send_message: sendMessageTool,
|
|
1483
|
+
followup_task: followupTaskTool,
|
|
1484
|
+
list_agents: listAgentsTool,
|
|
1485
|
+
wait_agent: createWaitAgentTool({
|
|
1486
|
+
minTimeoutMs: config.minWaitTimeoutMs,
|
|
1487
|
+
defaultTimeoutMs: config.defaultWaitTimeoutMs,
|
|
1488
|
+
maxTimeoutMs: config.maxWaitTimeoutMs
|
|
1489
|
+
}),
|
|
1490
|
+
interrupt_agent: interruptAgentTool
|
|
1491
|
+
};
|
|
1492
|
+
return Object.fromEntries(
|
|
1493
|
+
Object.entries(tools).map(([name, collaborationTool]) => [
|
|
1494
|
+
name,
|
|
1495
|
+
configureTool(collaborationTool, config)
|
|
1496
|
+
])
|
|
1497
|
+
);
|
|
1498
|
+
}
|
|
1499
|
+
function configureTool(collaborationTool, config) {
|
|
1500
|
+
const openai = collaborationTool.providerOptions?.openai;
|
|
1501
|
+
return {
|
|
1502
|
+
...collaborationTool,
|
|
1503
|
+
providerOptions: {
|
|
1504
|
+
...collaborationTool.providerOptions,
|
|
1505
|
+
...config.toolNamespace === void 0 ? {} : {
|
|
1506
|
+
openai: {
|
|
1507
|
+
...typeof openai === "object" && openai !== null ? openai : {},
|
|
1508
|
+
namespace: {
|
|
1509
|
+
name: config.toolNamespace,
|
|
1510
|
+
description: NAMESPACE_DESCRIPTION
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
},
|
|
1515
|
+
metadata: {
|
|
1516
|
+
...collaborationTool.metadata,
|
|
1517
|
+
zukhruf: {
|
|
1518
|
+
kind: "collaboration",
|
|
1519
|
+
codeModeExposure: "direct-model-only"
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
// packages/experimental/src/zukhruf/runtime/agent-skills.ts
|
|
1526
|
+
import path from "node:path";
|
|
1527
|
+
import {
|
|
1528
|
+
parseFrontmatter,
|
|
1529
|
+
skills
|
|
1530
|
+
} from "@deepagents/context";
|
|
1531
|
+
var EMPTY_SKILLS = { available: [], fragments: [] };
|
|
1532
|
+
async function discoverAgentSkills(sandbox, signal) {
|
|
1533
|
+
if (sandbox.workingDirectory === void 0) return EMPTY_SKILLS;
|
|
1534
|
+
const skillsDirectory = path.posix.join(sandbox.workingDirectory, "skills");
|
|
1535
|
+
const quotedSkillsDirectory = shellQuote(skillsDirectory);
|
|
1536
|
+
const result = await sandbox.sandbox.executeCommand(
|
|
1537
|
+
`if [ -d ${quotedSkillsDirectory} ]; then find ${quotedSkillsDirectory} -mindepth 1 -maxdepth 1 -type d -print; fi`,
|
|
1538
|
+
{ signal }
|
|
1539
|
+
);
|
|
1540
|
+
if (result.exitCode !== 0) {
|
|
1541
|
+
throw new Error(
|
|
1542
|
+
`AgentRuntime: failed to discover sandbox skills: ${result.stderr.trim() || `exit ${result.exitCode}`}`
|
|
1543
|
+
);
|
|
1544
|
+
}
|
|
1545
|
+
const skillDirectories = result.stdout.split("\n").filter(Boolean).filter((directory) => !path.posix.basename(directory).startsWith(".")).toSorted();
|
|
1546
|
+
if (skillDirectories.length === 0) return EMPTY_SKILLS;
|
|
1547
|
+
const discovered = await Promise.all(
|
|
1548
|
+
skillDirectories.map((directory) => loadSkill(sandbox, directory))
|
|
1549
|
+
);
|
|
1550
|
+
return createAgentSkills(discovered);
|
|
1551
|
+
}
|
|
1552
|
+
function createAgentSkills(available) {
|
|
1553
|
+
if (available.length === 0) return EMPTY_SKILLS;
|
|
1554
|
+
const snapshot = [...available];
|
|
1555
|
+
return { available: snapshot, fragments: [skills(snapshot)] };
|
|
1556
|
+
}
|
|
1557
|
+
async function loadSkill(sandbox, directory) {
|
|
1558
|
+
const directoryName = path.posix.basename(directory);
|
|
1559
|
+
const skillMd = await sandbox.sandbox.readFile(
|
|
1560
|
+
path.posix.join(directory, "SKILL.md")
|
|
1561
|
+
);
|
|
1562
|
+
const { frontmatter } = parseFrontmatter(skillMd);
|
|
1563
|
+
if (frontmatter.name !== directoryName) {
|
|
1564
|
+
throw new Error(
|
|
1565
|
+
`AgentRuntime: skill "${frontmatter.name}" must use matching directory "${directoryName}"`
|
|
1566
|
+
);
|
|
1567
|
+
}
|
|
1568
|
+
return {
|
|
1569
|
+
name: frontmatter.name,
|
|
1570
|
+
description: frontmatter.description,
|
|
1571
|
+
path: path.posix.join("skills", directoryName, "SKILL.md")
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
function shellQuote(value) {
|
|
1575
|
+
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
// packages/experimental/src/zukhruf/runtime/agent-turn-executor.ts
|
|
842
1579
|
var AgentTurnExecutor = class {
|
|
843
1580
|
#store;
|
|
844
1581
|
#streams;
|
|
845
1582
|
#controlPlane;
|
|
846
1583
|
#mailbox;
|
|
847
1584
|
#approvals;
|
|
1585
|
+
#multiAgentV2;
|
|
1586
|
+
#collaborationTools;
|
|
848
1587
|
constructor(options) {
|
|
849
1588
|
this.#store = options.store;
|
|
850
1589
|
this.#streams = options.streams;
|
|
851
1590
|
this.#controlPlane = options.controlPlane;
|
|
852
1591
|
this.#mailbox = options.mailbox;
|
|
853
1592
|
this.#approvals = options.approvals;
|
|
1593
|
+
this.#multiAgentV2 = options.multiAgentV2;
|
|
1594
|
+
this.#collaborationTools = createCollaborationTools(options.multiAgentV2);
|
|
854
1595
|
}
|
|
855
1596
|
async execute(turn, context) {
|
|
1597
|
+
if (turn.kind === "approval") {
|
|
1598
|
+
if (!await this.#approvals.applyDecision(turn)) return;
|
|
1599
|
+
await this.#reopen(turn.streamId);
|
|
1600
|
+
return this.execute(
|
|
1601
|
+
{
|
|
1602
|
+
kind: "continuation",
|
|
1603
|
+
streamId: turn.streamId,
|
|
1604
|
+
chatId: turn.chatId,
|
|
1605
|
+
userId: turn.userId
|
|
1606
|
+
},
|
|
1607
|
+
context
|
|
1608
|
+
);
|
|
1609
|
+
}
|
|
1610
|
+
if (turn.kind === "continuation" && turn.recovery !== void 0) {
|
|
1611
|
+
await this.#reopen(turn.streamId);
|
|
1612
|
+
}
|
|
856
1613
|
if (await this.#projectSkippedTerminalTurn(turn)) return;
|
|
857
1614
|
let parked = false;
|
|
858
1615
|
await this.#mailbox.beginTurn(turn);
|
|
@@ -871,7 +1628,8 @@ var AgentTurnExecutor = class {
|
|
|
871
1628
|
async #executeTurn(turn, { signal, park }) {
|
|
872
1629
|
if (await this.#projectSkippedTerminalTurn(turn)) return;
|
|
873
1630
|
const { declaration, thread } = await this.#controlPlane.resolve(turn);
|
|
874
|
-
const
|
|
1631
|
+
const usageHint = thread.path.isRoot ? this.#multiAgentV2.rootAgentUsageHintText : this.#multiAgentV2.subagentUsageHintText;
|
|
1632
|
+
const engine = this.#engineFor(turn);
|
|
875
1633
|
if (turn.kind === "ask" || turn.kind === "mailbox") {
|
|
876
1634
|
const head = (await engine.getMessages()).at(-1);
|
|
877
1635
|
if (this.#approvals.isPaused(head)) {
|
|
@@ -879,7 +1637,12 @@ var AgentTurnExecutor = class {
|
|
|
879
1637
|
return;
|
|
880
1638
|
}
|
|
881
1639
|
}
|
|
882
|
-
|
|
1640
|
+
let communications = [];
|
|
1641
|
+
if (turn.kind === "ask") {
|
|
1642
|
+
communications = await this.#mailbox.drainLeadingQueueOnly(turn);
|
|
1643
|
+
} else if (turn.kind === "mailbox") {
|
|
1644
|
+
communications = await this.#mailbox.drain(turn);
|
|
1645
|
+
}
|
|
883
1646
|
if (turn.kind === "mailbox" && communications.length === 0) {
|
|
884
1647
|
await this.#streams.store.updateStreamStatus(turn.streamId, "completed");
|
|
885
1648
|
return;
|
|
@@ -890,6 +1653,12 @@ var AgentTurnExecutor = class {
|
|
|
890
1653
|
chatId: turn.chatId,
|
|
891
1654
|
userId: turn.userId
|
|
892
1655
|
});
|
|
1656
|
+
const agentSkills = await this.#skillsFor(turn, sandbox, signal);
|
|
1657
|
+
engine.set(
|
|
1658
|
+
...declaration.instructions,
|
|
1659
|
+
...agentSkills.fragments,
|
|
1660
|
+
...usageHint === void 0 ? [] : [role(usageHint)]
|
|
1661
|
+
);
|
|
893
1662
|
if (await this.#projectSkippedTerminalTurn(turn)) return;
|
|
894
1663
|
if (!await this.#streams.claim(turn.streamId)) {
|
|
895
1664
|
await this.#projectSkippedTerminalTurn(turn);
|
|
@@ -903,10 +1672,7 @@ var AgentTurnExecutor = class {
|
|
|
903
1672
|
context: engine,
|
|
904
1673
|
tools: {
|
|
905
1674
|
...declaration.tools,
|
|
906
|
-
|
|
907
|
-
send_message: sendMessageTool,
|
|
908
|
-
followup_task: followupTaskTool,
|
|
909
|
-
list_agents: listAgentsTool
|
|
1675
|
+
...this.#collaborationTools
|
|
910
1676
|
},
|
|
911
1677
|
telemetry: declaration.telemetry,
|
|
912
1678
|
prepareStepInput: () => this.#prepareStepInput(turn, mailboxState)
|
|
@@ -973,6 +1739,11 @@ var AgentTurnExecutor = class {
|
|
|
973
1739
|
stream.error
|
|
974
1740
|
);
|
|
975
1741
|
}
|
|
1742
|
+
async #reopen(streamId) {
|
|
1743
|
+
const status = await this.#streams.store.getStreamStatus(streamId);
|
|
1744
|
+
if (status === "queued" || status === "running") return;
|
|
1745
|
+
await this.#streams.reopen(streamId);
|
|
1746
|
+
}
|
|
976
1747
|
async #prepareChain(turn, engine, communications) {
|
|
977
1748
|
if (turn.kind === "ask") {
|
|
978
1749
|
engine.set(
|
|
@@ -1000,6 +1771,29 @@ var AgentTurnExecutor = class {
|
|
|
1000
1771
|
(communication) => this.#mailboxInputMessage(communication)
|
|
1001
1772
|
);
|
|
1002
1773
|
}
|
|
1774
|
+
async #skillsFor(turn, sandbox, signal) {
|
|
1775
|
+
const chat2 = await this.#store.getChat(turn.chatId);
|
|
1776
|
+
const existing = readSkills(chat2?.metadata);
|
|
1777
|
+
if (existing !== void 0) return createAgentSkills(existing);
|
|
1778
|
+
if (sandbox.workingDirectory === void 0) return createAgentSkills([]);
|
|
1779
|
+
const discovered = await discoverAgentSkills(sandbox, signal);
|
|
1780
|
+
let available = discovered.available;
|
|
1781
|
+
await this.#store.updateChat(turn.chatId, ({ metadata }) => {
|
|
1782
|
+
const persisted = readSkills(metadata);
|
|
1783
|
+
if (persisted !== void 0) {
|
|
1784
|
+
available = persisted;
|
|
1785
|
+
return void 0;
|
|
1786
|
+
}
|
|
1787
|
+
const zukhruf = isRecord2(metadata?.zukhruf) ? metadata.zukhruf : {};
|
|
1788
|
+
return {
|
|
1789
|
+
metadata: {
|
|
1790
|
+
...metadata,
|
|
1791
|
+
zukhruf: { ...zukhruf, skills: available }
|
|
1792
|
+
}
|
|
1793
|
+
};
|
|
1794
|
+
});
|
|
1795
|
+
return available === discovered.available ? discovered : createAgentSkills(available);
|
|
1796
|
+
}
|
|
1003
1797
|
#engineFor({ chatId, userId }) {
|
|
1004
1798
|
return new ContextEngine2({ store: this.#store, chatId, userId });
|
|
1005
1799
|
}
|
|
@@ -1028,15 +1822,40 @@ Payload:
|
|
|
1028
1822
|
${communication.content}`;
|
|
1029
1823
|
}
|
|
1030
1824
|
};
|
|
1825
|
+
function readSkills(metadata) {
|
|
1826
|
+
const zukhruf = metadata?.zukhruf;
|
|
1827
|
+
if (!isRecord2(zukhruf) || !Object.hasOwn(zukhruf, "skills")) {
|
|
1828
|
+
return void 0;
|
|
1829
|
+
}
|
|
1830
|
+
if (!Array.isArray(zukhruf.skills) || !zukhruf.skills.every(isSkill)) {
|
|
1831
|
+
throw new Error("AgentRuntime: stored skill catalog is invalid");
|
|
1832
|
+
}
|
|
1833
|
+
return zukhruf.skills;
|
|
1834
|
+
}
|
|
1835
|
+
function isSkill(value) {
|
|
1836
|
+
return isRecord2(value) && typeof value.name === "string" && typeof value.description === "string" && typeof value.path === "string";
|
|
1837
|
+
}
|
|
1838
|
+
function isRecord2(value) {
|
|
1839
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1840
|
+
}
|
|
1031
1841
|
|
|
1032
|
-
// packages/experimental/src/zukhruf/approval-controller.ts
|
|
1842
|
+
// packages/experimental/src/zukhruf/runtime/approval-controller.ts
|
|
1033
1843
|
import {
|
|
1844
|
+
getToolName,
|
|
1034
1845
|
isToolUIPart
|
|
1035
1846
|
} from "ai";
|
|
1036
1847
|
import {
|
|
1037
1848
|
ContextEngine as ContextEngine3,
|
|
1038
1849
|
assistant as assistant2
|
|
1039
1850
|
} from "@deepagents/context";
|
|
1851
|
+
|
|
1852
|
+
// packages/experimental/src/zukhruf/runtime/approval-job-id.ts
|
|
1853
|
+
import { v5 as uuidv55 } from "uuid";
|
|
1854
|
+
function approvalJobId(conversation, approvalId) {
|
|
1855
|
+
return uuidv55(`approval:${approvalId}`, conversationNamespace(conversation));
|
|
1856
|
+
}
|
|
1857
|
+
|
|
1858
|
+
// packages/experimental/src/zukhruf/runtime/approval-controller.ts
|
|
1040
1859
|
var ApprovalController = class _ApprovalController {
|
|
1041
1860
|
static #settledToolStates = /* @__PURE__ */ new Set([
|
|
1042
1861
|
"output-available",
|
|
@@ -1044,14 +1863,10 @@ var ApprovalController = class _ApprovalController {
|
|
|
1044
1863
|
"output-denied"
|
|
1045
1864
|
]);
|
|
1046
1865
|
#store;
|
|
1047
|
-
#streams;
|
|
1048
1866
|
#queue;
|
|
1049
|
-
#mutex;
|
|
1050
1867
|
constructor(options) {
|
|
1051
1868
|
this.#store = options.store;
|
|
1052
|
-
this.#streams = options.streams;
|
|
1053
1869
|
this.#queue = options.queue;
|
|
1054
|
-
this.#mutex = options.mutex;
|
|
1055
1870
|
}
|
|
1056
1871
|
isPaused(message) {
|
|
1057
1872
|
return message?.role === "assistant" && this.#pendingToolPart(message) !== void 0;
|
|
@@ -1068,40 +1883,61 @@ var ApprovalController = class _ApprovalController {
|
|
|
1068
1883
|
});
|
|
1069
1884
|
}
|
|
1070
1885
|
async settleDeniedApprovals(conversation, streamId) {
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1886
|
+
const engine = this.#engineFor(conversation);
|
|
1887
|
+
const head = (await engine.getMessages()).at(-1);
|
|
1888
|
+
if (head?.role !== "assistant" || head.id !== streamId) return;
|
|
1889
|
+
const hasDenied = head.parts.some(
|
|
1890
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === false
|
|
1891
|
+
);
|
|
1892
|
+
if (!hasDenied) return;
|
|
1893
|
+
const updated = {
|
|
1894
|
+
...head,
|
|
1895
|
+
parts: head.parts.map((part) => {
|
|
1896
|
+
if (!isToolUIPart(part) || part.state !== "approval-responded" || part.approval.approved !== false) {
|
|
1897
|
+
return part;
|
|
1898
|
+
}
|
|
1899
|
+
const settled = {
|
|
1900
|
+
...part,
|
|
1901
|
+
state: "output-denied",
|
|
1902
|
+
approval: { ...part.approval, approved: false }
|
|
1903
|
+
};
|
|
1904
|
+
return settled;
|
|
1905
|
+
})
|
|
1906
|
+
};
|
|
1907
|
+
await engine.continue(assistant2(updated));
|
|
1087
1908
|
}
|
|
1088
1909
|
async settleFailedApprovals(conversation, streamId, error) {
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1910
|
+
const engine = this.#engineFor(conversation);
|
|
1911
|
+
const head = (await engine.getMessages()).at(-1);
|
|
1912
|
+
if (head?.role !== "assistant" || head.id !== streamId) return;
|
|
1913
|
+
const hasResponded = head.parts.some(
|
|
1914
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded"
|
|
1915
|
+
);
|
|
1916
|
+
if (!hasResponded) return;
|
|
1917
|
+
const updated = {
|
|
1918
|
+
...head,
|
|
1919
|
+
parts: head.parts.map((part) => {
|
|
1920
|
+
if (!isToolUIPart(part) || part.state !== "approval-responded") {
|
|
1921
|
+
return part;
|
|
1922
|
+
}
|
|
1923
|
+
if (part.approval.approved === false) {
|
|
1924
|
+
const denied = {
|
|
1925
|
+
...part,
|
|
1926
|
+
state: "output-denied",
|
|
1927
|
+
approval: { ...part.approval, approved: false }
|
|
1928
|
+
};
|
|
1929
|
+
return denied;
|
|
1930
|
+
}
|
|
1931
|
+
const failed = {
|
|
1932
|
+
...part,
|
|
1933
|
+
state: "output-error",
|
|
1934
|
+
errorText: error,
|
|
1935
|
+
approval: { ...part.approval, approved: true }
|
|
1936
|
+
};
|
|
1937
|
+
return failed;
|
|
1938
|
+
})
|
|
1939
|
+
};
|
|
1940
|
+
await engine.continue(assistant2(updated));
|
|
1105
1941
|
}
|
|
1106
1942
|
async reconcileTerminalContinuation(conversation, streamId, status, error) {
|
|
1107
1943
|
if (status === "completed") {
|
|
@@ -1110,88 +1946,116 @@ var ApprovalController = class _ApprovalController {
|
|
|
1110
1946
|
await this.settleFailedApprovals(
|
|
1111
1947
|
conversation,
|
|
1112
1948
|
streamId,
|
|
1113
|
-
error ??
|
|
1949
|
+
error ?? `approval continuation ${status}`
|
|
1114
1950
|
);
|
|
1115
1951
|
}
|
|
1116
1952
|
await this.#queue.resumeParked(conversation.chatId);
|
|
1117
1953
|
}
|
|
1118
|
-
async
|
|
1119
|
-
const
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
const head = (await engine.getMessages()).at(-1);
|
|
1124
|
-
if (head?.role !== "assistant") {
|
|
1125
|
-
throw new Error(
|
|
1126
|
-
`ApprovalController.${operation}: no paused turn \u2014 the chain head is not an assistant message`
|
|
1127
|
-
);
|
|
1128
|
-
}
|
|
1129
|
-
const part = this.#findToolPart(head, toolCallId);
|
|
1130
|
-
if (!part) {
|
|
1131
|
-
throw new Error(
|
|
1132
|
-
`ApprovalController.${operation}: no tool call "${toolCallId}" on the paused turn`
|
|
1133
|
-
);
|
|
1134
|
-
}
|
|
1135
|
-
if (part.approval?.approved !== void 0 && part.approval.approved !== approval.approved) {
|
|
1136
|
-
throw new Error(
|
|
1137
|
-
`ApprovalController.${operation}: approval already answered with a different decision`
|
|
1138
|
-
);
|
|
1139
|
-
}
|
|
1140
|
-
let updated = head;
|
|
1141
|
-
let answered = part;
|
|
1142
|
-
if (part.state === "approval-requested") {
|
|
1143
|
-
const responded = {
|
|
1144
|
-
...part,
|
|
1145
|
-
state: "approval-responded",
|
|
1146
|
-
approval: { ...part.approval, ...approval }
|
|
1147
|
-
};
|
|
1148
|
-
updated = {
|
|
1149
|
-
...head,
|
|
1150
|
-
parts: head.parts.map(
|
|
1151
|
-
(candidate) => candidate === part ? responded : candidate
|
|
1152
|
-
)
|
|
1153
|
-
};
|
|
1154
|
-
await engine.continue(assistant2(updated));
|
|
1155
|
-
answered = responded;
|
|
1156
|
-
}
|
|
1157
|
-
return {
|
|
1158
|
-
id: updated.id,
|
|
1159
|
-
hasUnansweredApprovals: this.#hasUnansweredApprovals(updated),
|
|
1160
|
-
shouldSchedule: answered.state === "approval-responded"
|
|
1161
|
-
};
|
|
1162
|
-
}
|
|
1954
|
+
async retryIdempotentContinuation(conversation, streamId, tools) {
|
|
1955
|
+
const head = (await this.#engineFor(conversation).getMessages()).at(-1);
|
|
1956
|
+
if (head?.role !== "assistant" || head.id !== streamId) return false;
|
|
1957
|
+
const approved = head.parts.filter(
|
|
1958
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === true
|
|
1163
1959
|
);
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1960
|
+
const retryable = approved.length > 0 && approved.every((part) => {
|
|
1961
|
+
const tool7 = tools[getToolName(part)];
|
|
1962
|
+
return tool7?.recovery === "idempotent" && typeof tool7.execute === "function";
|
|
1963
|
+
});
|
|
1964
|
+
if (!retryable) return false;
|
|
1965
|
+
await this.#queue.push({
|
|
1966
|
+
kind: "continuation",
|
|
1967
|
+
streamId,
|
|
1968
|
+
chatId: conversation.chatId,
|
|
1969
|
+
userId: conversation.userId,
|
|
1970
|
+
recovery: "idempotent"
|
|
1971
|
+
});
|
|
1972
|
+
return true;
|
|
1973
|
+
}
|
|
1974
|
+
async applyDecision(turn) {
|
|
1975
|
+
const engine = this.#engineFor(turn);
|
|
1976
|
+
const head = (await engine.getMessages()).at(-1);
|
|
1977
|
+
if (head?.role !== "assistant" || head.id !== turn.streamId) return false;
|
|
1978
|
+
const part = this.#findToolPart(head, turn.toolCallId);
|
|
1979
|
+
if (part?.approval?.id !== turn.approvalId) return false;
|
|
1980
|
+
if (part.approval.approved !== void 0) return false;
|
|
1981
|
+
if (part.state !== "approval-requested") return false;
|
|
1982
|
+
const responded = {
|
|
1983
|
+
...part,
|
|
1984
|
+
state: "approval-responded",
|
|
1985
|
+
approval: { ...part.approval, ...turn.decision }
|
|
1986
|
+
};
|
|
1987
|
+
const updated = {
|
|
1988
|
+
...head,
|
|
1989
|
+
parts: head.parts.map(
|
|
1990
|
+
(candidate) => candidate === part ? responded : candidate
|
|
1991
|
+
)
|
|
1992
|
+
};
|
|
1993
|
+
await engine.continue(assistant2(updated));
|
|
1994
|
+
return !this.#hasUnansweredApprovals(updated);
|
|
1995
|
+
}
|
|
1996
|
+
async recoverUnstartedContinuation(turn, streamId) {
|
|
1997
|
+
if (turn.kind === "approval") await this.applyDecision(turn);
|
|
1998
|
+
const head = (await this.#engineFor(turn).getMessages()).at(-1);
|
|
1999
|
+
if (head?.role !== "assistant" || head.id !== streamId || this.#hasUnansweredApprovals(head) || !head.parts.some(
|
|
2000
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded"
|
|
2001
|
+
)) {
|
|
2002
|
+
return false;
|
|
1170
2003
|
}
|
|
1171
|
-
|
|
2004
|
+
await this.#queue.push({
|
|
2005
|
+
kind: "continuation",
|
|
2006
|
+
streamId,
|
|
2007
|
+
chatId: turn.chatId,
|
|
2008
|
+
userId: turn.userId,
|
|
2009
|
+
recovery: "handoff"
|
|
2010
|
+
});
|
|
2011
|
+
return true;
|
|
1172
2012
|
}
|
|
1173
|
-
async #
|
|
1174
|
-
|
|
1175
|
-
if (
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
2013
|
+
async #respond(operation, conversation, toolCallId, approval) {
|
|
2014
|
+
const head = (await this.#engineFor(conversation).getMessages()).at(-1);
|
|
2015
|
+
if (head?.role !== "assistant") {
|
|
2016
|
+
throw new Error(
|
|
2017
|
+
`ApprovalController.${operation}: no paused turn \u2014 the chain head is not an assistant message`
|
|
2018
|
+
);
|
|
2019
|
+
}
|
|
2020
|
+
const part = this.#findToolPart(head, toolCallId);
|
|
2021
|
+
if (!part) {
|
|
2022
|
+
throw new Error(
|
|
2023
|
+
`ApprovalController.${operation}: no tool call "${toolCallId}" on the paused turn`
|
|
2024
|
+
);
|
|
2025
|
+
}
|
|
2026
|
+
if (!part.approval) {
|
|
2027
|
+
throw new Error(
|
|
2028
|
+
`ApprovalController.${operation}: tool call "${toolCallId}" is not awaiting approval`
|
|
2029
|
+
);
|
|
2030
|
+
}
|
|
2031
|
+
const jobId = approvalJobId(conversation, part.approval.id);
|
|
2032
|
+
if (part.approval.approved !== void 0) {
|
|
2033
|
+
if (part.approval.approved !== approval.approved) {
|
|
2034
|
+
throw new Error(
|
|
2035
|
+
`ApprovalController.${operation}: approval already answered with a different decision`
|
|
2036
|
+
);
|
|
1182
2037
|
}
|
|
1183
|
-
|
|
1184
|
-
return;
|
|
2038
|
+
return { id: head.id, jobId, status: "already-applied" };
|
|
1185
2039
|
}
|
|
1186
|
-
if (
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
chatId: conversation.chatId,
|
|
1191
|
-
userId: conversation.userId
|
|
1192
|
-
});
|
|
2040
|
+
if (part.state !== "approval-requested") {
|
|
2041
|
+
throw new Error(
|
|
2042
|
+
`ApprovalController.${operation}: tool call "${toolCallId}" is not awaiting approval`
|
|
2043
|
+
);
|
|
1193
2044
|
}
|
|
1194
|
-
await this.#queue.
|
|
2045
|
+
const result = await this.#queue.push({
|
|
2046
|
+
kind: "approval",
|
|
2047
|
+
streamId: head.id,
|
|
2048
|
+
chatId: conversation.chatId,
|
|
2049
|
+
userId: conversation.userId,
|
|
2050
|
+
toolCallId,
|
|
2051
|
+
approvalId: part.approval.id,
|
|
2052
|
+
decision: approval
|
|
2053
|
+
});
|
|
2054
|
+
return {
|
|
2055
|
+
id: head.id,
|
|
2056
|
+
jobId,
|
|
2057
|
+
status: result.inserted ? "queued" : "already-queued"
|
|
2058
|
+
};
|
|
1195
2059
|
}
|
|
1196
2060
|
#pendingToolPart(message) {
|
|
1197
2061
|
return message.parts.find(
|
|
@@ -1213,89 +2077,14 @@ var ApprovalController = class _ApprovalController {
|
|
|
1213
2077
|
}
|
|
1214
2078
|
};
|
|
1215
2079
|
|
|
1216
|
-
// packages/experimental/src/zukhruf/
|
|
1217
|
-
var MailboxCoordinator = class {
|
|
1218
|
-
#store;
|
|
1219
|
-
#queue;
|
|
1220
|
-
#streams;
|
|
1221
|
-
#wakeRequests = /* @__PURE__ */ new Map();
|
|
1222
|
-
constructor(options) {
|
|
1223
|
-
this.#store = options.store;
|
|
1224
|
-
this.#queue = options.queue;
|
|
1225
|
-
this.#streams = options.streams;
|
|
1226
|
-
}
|
|
1227
|
-
async deliver(communication, mode) {
|
|
1228
|
-
const delivered = {
|
|
1229
|
-
...communication,
|
|
1230
|
-
type: mode === MessageDeliveryMode.TriggerTurn ? InterAgentCommunicationType.NewTask : communication.type,
|
|
1231
|
-
triggerTurn: mode === MessageDeliveryMode.TriggerTurn
|
|
1232
|
-
};
|
|
1233
|
-
assertCommunication(delivered);
|
|
1234
|
-
const { recipientActive } = await this.#store.enqueue(delivered);
|
|
1235
|
-
if (delivered.triggerTurn || recipientActive) {
|
|
1236
|
-
await this.#scheduleWake(delivered.recipient);
|
|
1237
|
-
}
|
|
1238
|
-
}
|
|
1239
|
-
beginTurn(turn) {
|
|
1240
|
-
return this.#store.beginTurn(turn, turn.streamId);
|
|
1241
|
-
}
|
|
1242
|
-
async endTurn(turn, options = {}) {
|
|
1243
|
-
const { hasPending, turnEnded } = await this.#store.endTurn(
|
|
1244
|
-
turn,
|
|
1245
|
-
turn.streamId
|
|
1246
|
-
);
|
|
1247
|
-
if (turnEnded && hasPending && !options.parked) {
|
|
1248
|
-
await this.#scheduleWake(turn);
|
|
1249
|
-
}
|
|
1250
|
-
}
|
|
1251
|
-
drainLeadingQueueOnly(recipient) {
|
|
1252
|
-
return this.#store.drainLeadingQueueOnly(recipient);
|
|
1253
|
-
}
|
|
1254
|
-
drain(recipient) {
|
|
1255
|
-
return this.#store.drain(recipient);
|
|
1256
|
-
}
|
|
1257
|
-
#scheduleWake(target) {
|
|
1258
|
-
const key = this.#conversationKey(target);
|
|
1259
|
-
const existing = this.#wakeRequests.get(key);
|
|
1260
|
-
if (existing) return existing;
|
|
1261
|
-
const request = (async () => {
|
|
1262
|
-
const wakeId = AgentTurnId.random(target).toString();
|
|
1263
|
-
await this.#streams.register(wakeId);
|
|
1264
|
-
try {
|
|
1265
|
-
await this.#queue.push({
|
|
1266
|
-
kind: "mailbox",
|
|
1267
|
-
streamId: wakeId,
|
|
1268
|
-
chatId: target.chatId,
|
|
1269
|
-
userId: target.userId
|
|
1270
|
-
});
|
|
1271
|
-
} catch (error) {
|
|
1272
|
-
await this.#streams.store.updateStreamStatus(wakeId, "failed", {
|
|
1273
|
-
error: error instanceof Error ? error.message : String(error)
|
|
1274
|
-
});
|
|
1275
|
-
throw error;
|
|
1276
|
-
}
|
|
1277
|
-
})();
|
|
1278
|
-
this.#wakeRequests.set(key, request);
|
|
1279
|
-
const clearRequest = () => {
|
|
1280
|
-
if (this.#wakeRequests.get(key) === request) {
|
|
1281
|
-
this.#wakeRequests.delete(key);
|
|
1282
|
-
}
|
|
1283
|
-
};
|
|
1284
|
-
void request.then(clearRequest, clearRequest);
|
|
1285
|
-
return request;
|
|
1286
|
-
}
|
|
1287
|
-
#conversationKey(conversation) {
|
|
1288
|
-
return JSON.stringify([conversation.chatId, conversation.userId]);
|
|
1289
|
-
}
|
|
1290
|
-
};
|
|
1291
|
-
|
|
1292
|
-
// packages/experimental/src/zukhruf/agent-runtime.ts
|
|
2080
|
+
// packages/experimental/src/zukhruf/runtime/agent-runtime.ts
|
|
1293
2081
|
var AgentObservation = class {
|
|
1294
2082
|
engine;
|
|
1295
2083
|
#conversation;
|
|
1296
2084
|
#store;
|
|
1297
2085
|
#streams;
|
|
1298
|
-
|
|
2086
|
+
#queue;
|
|
2087
|
+
constructor(conversation, store, streams, queue) {
|
|
1299
2088
|
this.engine = new ContextEngine4({
|
|
1300
2089
|
store,
|
|
1301
2090
|
chatId: conversation.chatId,
|
|
@@ -1304,6 +2093,7 @@ var AgentObservation = class {
|
|
|
1304
2093
|
this.#conversation = conversation;
|
|
1305
2094
|
this.#store = store;
|
|
1306
2095
|
this.#streams = streams;
|
|
2096
|
+
this.#queue = queue;
|
|
1307
2097
|
}
|
|
1308
2098
|
async resume() {
|
|
1309
2099
|
const id = await this.#headStreamId();
|
|
@@ -1323,8 +2113,9 @@ var AgentObservation = class {
|
|
|
1323
2113
|
if (!id) return;
|
|
1324
2114
|
AgentTurnId.assertOwner(this.#conversation, id);
|
|
1325
2115
|
const status = await this.#streams.store.getStreamStatus(id);
|
|
1326
|
-
if (status === "queued" || status === "running") {
|
|
2116
|
+
if (status === "queued" || status === "running" || status === "cancelled") {
|
|
1327
2117
|
await this.#streams.cancel(id);
|
|
2118
|
+
await this.#queue.cancel(id);
|
|
1328
2119
|
}
|
|
1329
2120
|
}
|
|
1330
2121
|
async #headStreamId() {
|
|
@@ -1342,12 +2133,10 @@ var AgentRuntime = class {
|
|
|
1342
2133
|
#approvals;
|
|
1343
2134
|
#executor;
|
|
1344
2135
|
constructor(root, options) {
|
|
2136
|
+
const multiAgentV2 = resolveMultiAgentV2HostConfig(options.multiAgentV2);
|
|
1345
2137
|
const declarations = new AgentDeclarationRegistry(root);
|
|
1346
2138
|
const directory = new AgentDirectory(options.store);
|
|
1347
|
-
const streams =
|
|
1348
|
-
store: options.streamStore,
|
|
1349
|
-
changeSource: new PollingChangeSource({ reads: options.streamStore })
|
|
1350
|
-
});
|
|
2139
|
+
const streams = options.streams;
|
|
1351
2140
|
const mailbox = new MailboxCoordinator({
|
|
1352
2141
|
store: options.mailboxStore,
|
|
1353
2142
|
queue: options.queue,
|
|
@@ -1355,9 +2144,7 @@ var AgentRuntime = class {
|
|
|
1355
2144
|
});
|
|
1356
2145
|
const approvals = new ApprovalController({
|
|
1357
2146
|
store: options.store,
|
|
1358
|
-
|
|
1359
|
-
queue: options.queue,
|
|
1360
|
-
mutex: options.approvalMutex
|
|
2147
|
+
queue: options.queue
|
|
1361
2148
|
});
|
|
1362
2149
|
const statusProjector = new AgentStatusProjector({
|
|
1363
2150
|
store: options.store,
|
|
@@ -1367,6 +2154,7 @@ var AgentRuntime = class {
|
|
|
1367
2154
|
directory,
|
|
1368
2155
|
approvals
|
|
1369
2156
|
});
|
|
2157
|
+
const historyForker = new AgentHistoryForker(options.store);
|
|
1370
2158
|
const controlPlane = new AgentControlPlane({
|
|
1371
2159
|
root,
|
|
1372
2160
|
streams,
|
|
@@ -1374,7 +2162,8 @@ var AgentRuntime = class {
|
|
|
1374
2162
|
mailbox,
|
|
1375
2163
|
declarations,
|
|
1376
2164
|
directory,
|
|
1377
|
-
statusProjector
|
|
2165
|
+
statusProjector,
|
|
2166
|
+
historyForker
|
|
1378
2167
|
});
|
|
1379
2168
|
this.#store = options.store;
|
|
1380
2169
|
this.#queue = options.queue;
|
|
@@ -1388,7 +2177,8 @@ var AgentRuntime = class {
|
|
|
1388
2177
|
streams,
|
|
1389
2178
|
controlPlane,
|
|
1390
2179
|
mailbox,
|
|
1391
|
-
approvals
|
|
2180
|
+
approvals,
|
|
2181
|
+
multiAgentV2
|
|
1392
2182
|
});
|
|
1393
2183
|
}
|
|
1394
2184
|
async enqueue(conversation, turn) {
|
|
@@ -1406,7 +2196,12 @@ var AgentRuntime = class {
|
|
|
1406
2196
|
return this.#approvals.deny(conversation, input);
|
|
1407
2197
|
}
|
|
1408
2198
|
observe(conversation) {
|
|
1409
|
-
return new AgentObservation(
|
|
2199
|
+
return new AgentObservation(
|
|
2200
|
+
conversation,
|
|
2201
|
+
this.#store,
|
|
2202
|
+
this.#streams,
|
|
2203
|
+
this.#queue
|
|
2204
|
+
);
|
|
1410
2205
|
}
|
|
1411
2206
|
work(options) {
|
|
1412
2207
|
return this.#queue.consume(this.#executor.execute.bind(this.#executor), {
|
|
@@ -1424,7 +2219,28 @@ var AgentRuntime = class {
|
|
|
1424
2219
|
});
|
|
1425
2220
|
stream = await this.#streams.store.getStream(turn.streamId);
|
|
1426
2221
|
}
|
|
1427
|
-
|
|
2222
|
+
let declaration;
|
|
2223
|
+
if ((turn.kind === "approval" || turn.kind === "continuation" && turn.recovery !== "idempotent") && stream?.status === "failed") {
|
|
2224
|
+
try {
|
|
2225
|
+
({ declaration } = await this.#controlPlane.resolve(turn));
|
|
2226
|
+
} catch {
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
if (declaration !== void 0 && await this.#approvals.retryIdempotentContinuation(
|
|
2230
|
+
turn,
|
|
2231
|
+
turn.streamId,
|
|
2232
|
+
declaration.tools ?? {}
|
|
2233
|
+
)) {
|
|
2234
|
+
return;
|
|
2235
|
+
}
|
|
2236
|
+
if ((turn.kind === "approval" || turn.kind === "continuation") && stream?.status === "completed" && await this.#approvals.recoverUnstartedContinuation(
|
|
2237
|
+
turn,
|
|
2238
|
+
turn.streamId
|
|
2239
|
+
)) {
|
|
2240
|
+
return;
|
|
2241
|
+
}
|
|
2242
|
+
stream = await this.#streams.store.getStream(turn.streamId);
|
|
2243
|
+
if ((turn.kind === "approval" || turn.kind === "continuation") && (stream?.status === "completed" || stream?.status === "failed" || stream?.status === "cancelled")) {
|
|
1428
2244
|
await this.#approvals.reconcileTerminalContinuation(
|
|
1429
2245
|
turn,
|
|
1430
2246
|
turn.streamId,
|
|
@@ -1443,7 +2259,7 @@ var AgentRuntime = class {
|
|
|
1443
2259
|
await this.#controlPlane.projectTerminal(turn, thread);
|
|
1444
2260
|
} finally {
|
|
1445
2261
|
try {
|
|
1446
|
-
if (turn.kind === "continuation") {
|
|
2262
|
+
if (turn.kind === "approval" || turn.kind === "continuation") {
|
|
1447
2263
|
await this.#queue.resumeParked(turn.chatId);
|
|
1448
2264
|
}
|
|
1449
2265
|
} finally {
|
|
@@ -1453,10 +2269,6 @@ var AgentRuntime = class {
|
|
|
1453
2269
|
}
|
|
1454
2270
|
};
|
|
1455
2271
|
|
|
1456
|
-
// packages/experimental/src/zukhruf/approval-mutex.ts
|
|
1457
|
-
var ApprovalMutex = class {
|
|
1458
|
-
};
|
|
1459
|
-
|
|
1460
2272
|
// packages/experimental/src/zukhruf/instructions.ts
|
|
1461
2273
|
function defineInstructions(...fragments) {
|
|
1462
2274
|
return fragments;
|
|
@@ -1508,9 +2320,9 @@ var BUSY_TIMEOUT_MS = 5e3;
|
|
|
1508
2320
|
var SqliteMailboxStore = class extends MailboxStore {
|
|
1509
2321
|
#database;
|
|
1510
2322
|
#closed = false;
|
|
1511
|
-
constructor(
|
|
2323
|
+
constructor(path2) {
|
|
1512
2324
|
super();
|
|
1513
|
-
this.#database = new DatabaseSync(
|
|
2325
|
+
this.#database = new DatabaseSync(path2, { timeout: BUSY_TIMEOUT_MS });
|
|
1514
2326
|
this.#database.exec(DDL);
|
|
1515
2327
|
}
|
|
1516
2328
|
async beginTurn(recipient, turnId) {
|
|
@@ -1668,17 +2480,39 @@ var TurnQueue = class {
|
|
|
1668
2480
|
};
|
|
1669
2481
|
|
|
1670
2482
|
// packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
|
|
2483
|
+
var MAX_TIMEOUT_MS = 2147483647;
|
|
1671
2484
|
var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
|
|
1672
2485
|
#boss;
|
|
1673
2486
|
#queue;
|
|
2487
|
+
#schema;
|
|
2488
|
+
#schemaConfigurationError;
|
|
2489
|
+
#table;
|
|
1674
2490
|
#expireInSeconds;
|
|
2491
|
+
#cancelIntentTtlMs;
|
|
1675
2492
|
#heartbeatSeconds;
|
|
1676
2493
|
#pollingIntervalSeconds;
|
|
2494
|
+
#active = /* @__PURE__ */ new Map();
|
|
2495
|
+
#cancelIntents = /* @__PURE__ */ new Map();
|
|
2496
|
+
#cancelIntentExpiryTimer;
|
|
1677
2497
|
constructor(boss, options = {}) {
|
|
1678
2498
|
super();
|
|
1679
2499
|
this.#boss = boss;
|
|
1680
2500
|
this.#queue = options.queue ?? "zukhruf-turns";
|
|
2501
|
+
const configuredSchema = boss.getDb().config?.schema;
|
|
2502
|
+
const bossSchema = typeof configuredSchema === "string" ? configuredSchema : void 0;
|
|
2503
|
+
this.#schema = options.schema ?? bossSchema ?? "pgboss";
|
|
2504
|
+
if (options.schema === void 0 && bossSchema === void 0) {
|
|
2505
|
+
this.#schemaConfigurationError = "PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema";
|
|
2506
|
+
} else if (options.schema !== void 0 && bossSchema !== void 0 && options.schema !== bossSchema) {
|
|
2507
|
+
this.#schemaConfigurationError = `PgBossTurnQueue schema "${options.schema}" does not match the PgBoss schema "${bossSchema}"`;
|
|
2508
|
+
}
|
|
1681
2509
|
this.#expireInSeconds = options.expireInSeconds ?? 3600;
|
|
2510
|
+
this.#cancelIntentTtlMs = this.#expireInSeconds * 1e3;
|
|
2511
|
+
if (!Number.isFinite(this.#expireInSeconds) || this.#expireInSeconds <= 0 || !Number.isSafeInteger(this.#cancelIntentTtlMs) || this.#cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()) {
|
|
2512
|
+
throw new Error(
|
|
2513
|
+
"PgBossTurnQueue expireInSeconds must be a finite positive duration"
|
|
2514
|
+
);
|
|
2515
|
+
}
|
|
1682
2516
|
this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;
|
|
1683
2517
|
this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;
|
|
1684
2518
|
}
|
|
@@ -1689,10 +2523,14 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
|
|
|
1689
2523
|
return `${this.#queue}-dead`;
|
|
1690
2524
|
}
|
|
1691
2525
|
async initialize() {
|
|
2526
|
+
if (this.#schemaConfigurationError) {
|
|
2527
|
+
throw new Error(this.#schemaConfigurationError);
|
|
2528
|
+
}
|
|
1692
2529
|
if (!await this.#boss.getQueue(this.deadLetterQueue)) {
|
|
1693
2530
|
await this.#boss.createQueue(this.deadLetterQueue);
|
|
1694
2531
|
}
|
|
1695
|
-
|
|
2532
|
+
let queue = await this.#boss.getQueue(this.#queue);
|
|
2533
|
+
if (!queue) {
|
|
1696
2534
|
await this.#boss.createQueue(this.#queue, {
|
|
1697
2535
|
policy: "key_strict_fifo",
|
|
1698
2536
|
retryLimit: 0,
|
|
@@ -1701,14 +2539,40 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
|
|
|
1701
2539
|
deleteAfterSeconds: 0,
|
|
1702
2540
|
deadLetter: this.deadLetterQueue
|
|
1703
2541
|
});
|
|
2542
|
+
queue = await this.#boss.getQueue(this.#queue);
|
|
2543
|
+
}
|
|
2544
|
+
if (!queue) throw new Error(`Queue "${this.#queue}" was not initialized`);
|
|
2545
|
+
this.#table = queue.table;
|
|
2546
|
+
try {
|
|
2547
|
+
const catalog = await this.#boss.getDb().executeSql(
|
|
2548
|
+
`SELECT table_name AS "table"
|
|
2549
|
+
FROM ${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}."queue"
|
|
2550
|
+
WHERE name = $1`,
|
|
2551
|
+
[this.#queue]
|
|
2552
|
+
);
|
|
2553
|
+
if (catalog.rows.length !== 1 || catalog.rows[0].table !== this.#table) {
|
|
2554
|
+
throw new Error("queue catalog does not match");
|
|
2555
|
+
}
|
|
2556
|
+
await this.#boss.getDb().executeSql(`SELECT 1 FROM ${this.#relation()} WHERE false`);
|
|
2557
|
+
} catch (cause) {
|
|
2558
|
+
throw new Error(
|
|
2559
|
+
`PgBossTurnQueue schema "${this.#schema}" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,
|
|
2560
|
+
{ cause }
|
|
2561
|
+
);
|
|
1704
2562
|
}
|
|
1705
2563
|
}
|
|
1706
2564
|
async push(turn) {
|
|
1707
|
-
|
|
1708
|
-
|
|
2565
|
+
const jobId = turn.kind === "approval" ? approvalJobId(turn, turn.approvalId) : uuidv7();
|
|
2566
|
+
const inserted = await this.#boss.send(this.#queue, turn, {
|
|
2567
|
+
id: jobId,
|
|
1709
2568
|
singletonKey: turn.chatId,
|
|
1710
|
-
|
|
2569
|
+
group: { id: turn.chatId },
|
|
2570
|
+
priority: turn.kind === "approval" || turn.kind === "continuation" ? 1 : 0
|
|
1711
2571
|
});
|
|
2572
|
+
if (inserted === null && turn.kind !== "approval") {
|
|
2573
|
+
throw new Error(`PgBossTurnQueue job id collision: ${jobId}`);
|
|
2574
|
+
}
|
|
2575
|
+
return { jobId, inserted: inserted !== null };
|
|
1712
2576
|
}
|
|
1713
2577
|
async getTurnActivity(conversation) {
|
|
1714
2578
|
const jobs = await this.#boss.findJobs(this.#queue, {
|
|
@@ -1722,26 +2586,64 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
|
|
|
1722
2586
|
}
|
|
1723
2587
|
return conversationJobs.length > 0 ? "queued" : "idle";
|
|
1724
2588
|
}
|
|
2589
|
+
async getCurrentTurn(conversation) {
|
|
2590
|
+
const jobs = await this.#boss.findJobs(this.#queue, {
|
|
2591
|
+
key: conversation.chatId
|
|
2592
|
+
});
|
|
2593
|
+
return jobs.filter(
|
|
2594
|
+
(job) => job.data.userId === conversation.userId && (job.state === "active" || job.state === "created" || job.state === "retry")
|
|
2595
|
+
).sort(_PgBossTurnQueue.#interruptOrder)[0]?.data;
|
|
2596
|
+
}
|
|
2597
|
+
async cancel(streamId) {
|
|
2598
|
+
this.#rememberCancelIntent(streamId);
|
|
2599
|
+
this.#abortLocal(streamId);
|
|
2600
|
+
const jobs = await this.#boss.findJobs(this.#queue, {
|
|
2601
|
+
data: { streamId }
|
|
2602
|
+
});
|
|
2603
|
+
const queued = jobs.filter((job) => job.state === "created" || job.state === "retry").map((job) => job.id);
|
|
2604
|
+
if (queued.length > 0) await this.#deleteIfStillQueued(queued);
|
|
2605
|
+
this.#abortLocal(streamId);
|
|
2606
|
+
const remaining = await this.#boss.findJobs(this.#queue, {
|
|
2607
|
+
data: { streamId }
|
|
2608
|
+
});
|
|
2609
|
+
if (!remaining.some((job) => job.state === "active")) {
|
|
2610
|
+
this.#forgetCancelIntent(streamId);
|
|
2611
|
+
}
|
|
2612
|
+
}
|
|
1725
2613
|
async consume(handler, options) {
|
|
1726
2614
|
const turnWorkerId = await this.#boss.work(
|
|
1727
2615
|
this.#queue,
|
|
1728
2616
|
{
|
|
1729
2617
|
localConcurrency: options.concurrency ?? 1,
|
|
2618
|
+
groupConcurrency: 1,
|
|
1730
2619
|
pollingIntervalSeconds: this.#pollingIntervalSeconds
|
|
1731
2620
|
},
|
|
1732
2621
|
async ([job]) => {
|
|
1733
2622
|
let parked = false;
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
2623
|
+
const localAbort = new AbortController();
|
|
2624
|
+
const active = this.#active.get(job.data.streamId) ?? /* @__PURE__ */ new Set();
|
|
2625
|
+
active.add(localAbort);
|
|
2626
|
+
this.#active.set(job.data.streamId, active);
|
|
2627
|
+
if (this.#hasCancelIntent(job.data.streamId)) localAbort.abort();
|
|
2628
|
+
try {
|
|
2629
|
+
await handler(job.data, {
|
|
2630
|
+
signal: AbortSignal.any([job.signal, localAbort.signal]),
|
|
2631
|
+
// Parking = self-cancel: a cancelled job stops blocking the chat's
|
|
2632
|
+
// key and is revived (original created_on, so original order) by
|
|
2633
|
+
// resumeParked(). The worker's completion of a cancelled job is a
|
|
2634
|
+
// clean no-op (probe-verified).
|
|
2635
|
+
park: async () => {
|
|
2636
|
+
parked = true;
|
|
2637
|
+
await this.#boss.cancel(this.#queue, job.id);
|
|
2638
|
+
}
|
|
2639
|
+
});
|
|
2640
|
+
} finally {
|
|
2641
|
+
active.delete(localAbort);
|
|
2642
|
+
if (active.size === 0) {
|
|
2643
|
+
this.#active.delete(job.data.streamId);
|
|
2644
|
+
this.#forgetCancelIntent(job.data.streamId);
|
|
1743
2645
|
}
|
|
1744
|
-
}
|
|
2646
|
+
}
|
|
1745
2647
|
if (!parked) {
|
|
1746
2648
|
await this.#boss.deleteJob(this.#queue, job.id);
|
|
1747
2649
|
}
|
|
@@ -1780,102 +2682,193 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
|
|
|
1780
2682
|
await this.#boss.resume(this.#queue, parked);
|
|
1781
2683
|
}
|
|
1782
2684
|
}
|
|
2685
|
+
#abortLocal(streamId) {
|
|
2686
|
+
for (const controller of this.#active.get(streamId) ?? []) {
|
|
2687
|
+
controller.abort();
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
#rememberCancelIntent(streamId) {
|
|
2691
|
+
this.#pruneCancelIntents();
|
|
2692
|
+
this.#cancelIntents.set(streamId, Date.now() + this.#cancelIntentTtlMs);
|
|
2693
|
+
this.#scheduleCancelIntentExpiry();
|
|
2694
|
+
}
|
|
2695
|
+
#hasCancelIntent(streamId) {
|
|
2696
|
+
this.#pruneCancelIntents();
|
|
2697
|
+
return this.#cancelIntents.has(streamId);
|
|
2698
|
+
}
|
|
2699
|
+
#pruneCancelIntents() {
|
|
2700
|
+
const now = Date.now();
|
|
2701
|
+
for (const [streamId, expiresAt] of this.#cancelIntents) {
|
|
2702
|
+
if (expiresAt <= now) this.#cancelIntents.delete(streamId);
|
|
2703
|
+
}
|
|
2704
|
+
this.#scheduleCancelIntentExpiry();
|
|
2705
|
+
}
|
|
2706
|
+
#forgetCancelIntent(streamId) {
|
|
2707
|
+
this.#cancelIntents.delete(streamId);
|
|
2708
|
+
this.#scheduleCancelIntentExpiry();
|
|
2709
|
+
}
|
|
2710
|
+
#scheduleCancelIntentExpiry() {
|
|
2711
|
+
if (this.#cancelIntentExpiryTimer !== void 0) {
|
|
2712
|
+
globalThis.clearTimeout(this.#cancelIntentExpiryTimer);
|
|
2713
|
+
this.#cancelIntentExpiryTimer = void 0;
|
|
2714
|
+
}
|
|
2715
|
+
let nextExpiry = Number.POSITIVE_INFINITY;
|
|
2716
|
+
for (const expiresAt of this.#cancelIntents.values()) {
|
|
2717
|
+
nextExpiry = Math.min(nextExpiry, expiresAt);
|
|
2718
|
+
}
|
|
2719
|
+
if (!Number.isFinite(nextExpiry)) return;
|
|
2720
|
+
const timer = globalThis.setTimeout(
|
|
2721
|
+
() => {
|
|
2722
|
+
if (this.#cancelIntentExpiryTimer !== timer) return;
|
|
2723
|
+
this.#cancelIntentExpiryTimer = void 0;
|
|
2724
|
+
this.#pruneCancelIntents();
|
|
2725
|
+
},
|
|
2726
|
+
Math.min(MAX_TIMEOUT_MS, Math.max(1, nextExpiry - Date.now()))
|
|
2727
|
+
);
|
|
2728
|
+
this.#cancelIntentExpiryTimer = timer;
|
|
2729
|
+
timer.unref?.();
|
|
2730
|
+
}
|
|
2731
|
+
async #deleteIfStillQueued(ids) {
|
|
2732
|
+
if (!this.#table) {
|
|
2733
|
+
throw new Error("PgBossTurnQueue.initialize() must run before cancel()");
|
|
2734
|
+
}
|
|
2735
|
+
await this.#boss.getDb().executeSql(
|
|
2736
|
+
`DELETE FROM ${this.#relation()}
|
|
2737
|
+
WHERE name = $1
|
|
2738
|
+
AND id = ANY($2::uuid[])
|
|
2739
|
+
AND state IN ('created', 'retry')`,
|
|
2740
|
+
[this.#queue, ids]
|
|
2741
|
+
);
|
|
2742
|
+
}
|
|
2743
|
+
#relation() {
|
|
2744
|
+
if (!this.#table) {
|
|
2745
|
+
throw new Error(
|
|
2746
|
+
"PgBossTurnQueue.initialize() must resolve its job table"
|
|
2747
|
+
);
|
|
2748
|
+
}
|
|
2749
|
+
return `${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}.${_PgBossTurnQueue.#quoteIdentifier(this.#table)}`;
|
|
2750
|
+
}
|
|
2751
|
+
static #quoteIdentifier(identifier) {
|
|
2752
|
+
return `"${identifier.replaceAll('"', '""')}"`;
|
|
2753
|
+
}
|
|
1783
2754
|
static #orphanError(output) {
|
|
1784
2755
|
if (output && "message" in output && typeof output.message === "string") {
|
|
1785
2756
|
return output.message;
|
|
1786
2757
|
}
|
|
1787
2758
|
return output ? JSON.stringify(output) : "turn orphaned";
|
|
1788
2759
|
}
|
|
2760
|
+
static #interruptOrder(left, right) {
|
|
2761
|
+
if (left.state === "active" && right.state !== "active") return -1;
|
|
2762
|
+
if (left.state !== "active" && right.state === "active") return 1;
|
|
2763
|
+
if (left.priority !== right.priority) return right.priority - left.priority;
|
|
2764
|
+
const created = left.createdOn.getTime() - right.createdOn.getTime();
|
|
2765
|
+
return created || left.id.localeCompare(right.id);
|
|
2766
|
+
}
|
|
1789
2767
|
};
|
|
1790
2768
|
|
|
1791
|
-
// packages/experimental/src/zukhruf/
|
|
1792
|
-
import {
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
function
|
|
1796
|
-
|
|
2769
|
+
// packages/experimental/src/zukhruf/render-turn.ts
|
|
2770
|
+
import { styleText } from "node:util";
|
|
2771
|
+
var dim = (text) => styleText("dim", text);
|
|
2772
|
+
var red = (text) => styleText("red", text);
|
|
2773
|
+
function oneLine(value, max = 88) {
|
|
2774
|
+
const text = String(value ?? "").replaceAll(/\s+/g, " ").trim();
|
|
2775
|
+
return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
|
|
1797
2776
|
}
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
PRAGMA busy_timeout = 5000;
|
|
1812
|
-
CREATE TABLE IF NOT EXISTS approval_mutex (
|
|
1813
|
-
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
1814
|
-
conversationId TEXT NOT NULL,
|
|
1815
|
-
touchedAt INTEGER NOT NULL
|
|
1816
|
-
);
|
|
1817
|
-
`);
|
|
2777
|
+
function describeToolCall(toolName, input) {
|
|
2778
|
+
const args = input ?? {};
|
|
2779
|
+
switch (toolName) {
|
|
2780
|
+
case "spawn_agent":
|
|
2781
|
+
return `\u21C4 spawn ${args.agent_type} "${args.task_name}" \u2014 ${args.message}`;
|
|
2782
|
+
case "send_message":
|
|
2783
|
+
return `\u21C4 mail ${args.target} \u2014 ${args.message}`;
|
|
2784
|
+
case "followup_task":
|
|
2785
|
+
return `\u21C4 follow-up ${args.target} \u2014 ${args.message}`;
|
|
2786
|
+
case "list_agents":
|
|
2787
|
+
return "\u21C4 list agents";
|
|
2788
|
+
default:
|
|
2789
|
+
return `\xB7 ${toolName}`;
|
|
1818
2790
|
}
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
} catch (error) {
|
|
1835
|
-
try {
|
|
1836
|
-
this.#db.exec("ROLLBACK");
|
|
1837
|
-
} catch {
|
|
2791
|
+
}
|
|
2792
|
+
async function renderTurn(stream) {
|
|
2793
|
+
const toolNames = /* @__PURE__ */ new Map();
|
|
2794
|
+
let midText = false;
|
|
2795
|
+
let thinkingShown = false;
|
|
2796
|
+
const breakText = () => {
|
|
2797
|
+
if (midText) process.stdout.write("\n");
|
|
2798
|
+
midText = false;
|
|
2799
|
+
};
|
|
2800
|
+
for await (const chunk of stream) {
|
|
2801
|
+
switch (chunk.type) {
|
|
2802
|
+
case "reasoning-start":
|
|
2803
|
+
if (!thinkingShown) {
|
|
2804
|
+
console.log(dim("\u2026"));
|
|
2805
|
+
thinkingShown = true;
|
|
1838
2806
|
}
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
2807
|
+
break;
|
|
2808
|
+
case "text-delta":
|
|
2809
|
+
process.stdout.write(chunk.delta);
|
|
2810
|
+
midText = true;
|
|
2811
|
+
break;
|
|
2812
|
+
case "text-end":
|
|
2813
|
+
breakText();
|
|
2814
|
+
break;
|
|
2815
|
+
case "tool-input-available":
|
|
2816
|
+
toolNames.set(chunk.toolCallId, chunk.toolName);
|
|
2817
|
+
breakText();
|
|
2818
|
+
console.log(dim(describeToolCall(chunk.toolName, chunk.input)));
|
|
2819
|
+
break;
|
|
2820
|
+
case "tool-output-error":
|
|
2821
|
+
breakText();
|
|
2822
|
+
console.log(
|
|
2823
|
+
red(
|
|
2824
|
+
`\u2717 ${toolNames.get(chunk.toolCallId) ?? "tool"}: ${oneLine(chunk.errorText)}`
|
|
2825
|
+
)
|
|
2826
|
+
);
|
|
2827
|
+
break;
|
|
2828
|
+
case "error":
|
|
2829
|
+
breakText();
|
|
2830
|
+
console.log(red(`\u2717 ${oneLine(chunk.errorText)}`));
|
|
2831
|
+
break;
|
|
2832
|
+
case "abort":
|
|
2833
|
+
breakText();
|
|
2834
|
+
console.log(dim("\xB7 turn aborted"));
|
|
2835
|
+
break;
|
|
1843
2836
|
}
|
|
1844
2837
|
}
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
const
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
};
|
|
2838
|
+
breakText();
|
|
2839
|
+
}
|
|
2840
|
+
|
|
2841
|
+
// packages/experimental/src/zukhruf/sandbox/define.ts
|
|
2842
|
+
import { createBashTool } from "@deepagents/context";
|
|
2843
|
+
var DEFAULT_WORKING_DIRECTORY = "/workspace";
|
|
2844
|
+
function defineSandbox(createBackend, options) {
|
|
2845
|
+
return async (context) => {
|
|
2846
|
+
const workingDirectory = options?.destination ?? DEFAULT_WORKING_DIRECTORY;
|
|
2847
|
+
return Object.assign(
|
|
2848
|
+
await createBashTool({
|
|
2849
|
+
sandbox: await createBackend(context),
|
|
2850
|
+
...options,
|
|
2851
|
+
destination: workingDirectory
|
|
2852
|
+
}),
|
|
2853
|
+
{ workingDirectory }
|
|
2854
|
+
);
|
|
2855
|
+
};
|
|
2856
|
+
}
|
|
1865
2857
|
|
|
1866
2858
|
// packages/experimental/src/zukhruf/tool.ts
|
|
1867
|
-
import { tool as
|
|
2859
|
+
import { tool as tool6 } from "ai";
|
|
2860
|
+
function defineTool(definition) {
|
|
2861
|
+
return tool6(definition);
|
|
2862
|
+
}
|
|
1868
2863
|
export {
|
|
1869
2864
|
AgentObservation,
|
|
1870
2865
|
AgentPath,
|
|
1871
2866
|
AgentRuntime,
|
|
1872
2867
|
AgentThread,
|
|
1873
|
-
ApprovalMutex,
|
|
1874
2868
|
InterAgentCommunicationType,
|
|
1875
2869
|
MailboxStore,
|
|
1876
2870
|
MessageDeliveryMode,
|
|
1877
2871
|
PgBossTurnQueue,
|
|
1878
|
-
SqliteApprovalMutex,
|
|
1879
2872
|
SqliteMailboxStore,
|
|
1880
2873
|
TurnQueue,
|
|
1881
2874
|
assertCommunication,
|
|
@@ -1883,6 +2876,7 @@ export {
|
|
|
1883
2876
|
defineAgent,
|
|
1884
2877
|
defineInstructions,
|
|
1885
2878
|
defineSandbox,
|
|
1886
|
-
|
|
2879
|
+
defineTool,
|
|
2880
|
+
renderTurn
|
|
1887
2881
|
};
|
|
1888
2882
|
//# sourceMappingURL=index.js.map
|