@deepagents/experimental 5.0.0 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -11
- package/dist/index.js +1315 -433
- package/dist/index.js.map +4 -4
- package/dist/zukhruf/agent.d.ts +4 -3
- 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 +1316 -434
- 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} +23 -12
- package/dist/zukhruf/runtime/agent-runtime.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/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) {
|
|
@@ -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;
|
|
@@ -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;
|
|
@@ -287,12 +331,16 @@ var AgentDirectory = class _AgentDirectory {
|
|
|
287
331
|
}
|
|
288
332
|
async resolve(thread, target) {
|
|
289
333
|
const path = thread.path.resolve(target);
|
|
290
|
-
const match =
|
|
291
|
-
(candidate) => candidate.path.equals(path)
|
|
292
|
-
);
|
|
334
|
+
const match = await this.find(thread, target);
|
|
293
335
|
if (match) return match;
|
|
294
336
|
throw new Error(`agent path "${path}" does not exist in this tree`);
|
|
295
337
|
}
|
|
338
|
+
async find(thread, target) {
|
|
339
|
+
const path = thread.path.resolve(target);
|
|
340
|
+
return (await this.listTree(thread)).find(
|
|
341
|
+
(candidate) => candidate.path.equals(path)
|
|
342
|
+
);
|
|
343
|
+
}
|
|
296
344
|
async createChild(options) {
|
|
297
345
|
const path = options.parent.path.resolve(options.taskName);
|
|
298
346
|
const pathString = path.toString();
|
|
@@ -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;
|
|
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
|
+
);
|
|
447
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,446 @@ 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
|
-
|
|
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";
|
|
782
1340
|
|
|
783
|
-
// packages/experimental/src/zukhruf/
|
|
1341
|
+
// packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
|
|
784
1342
|
import { tool } from "ai";
|
|
785
|
-
import { z } from "zod";
|
|
786
|
-
var
|
|
787
|
-
|
|
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
|
+
}
|
|
1449
|
+
|
|
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
|
+
}
|
|
840
1474
|
|
|
841
|
-
// packages/experimental/src/zukhruf/
|
|
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-turn-executor.ts
|
|
842
1526
|
var AgentTurnExecutor = class {
|
|
843
1527
|
#store;
|
|
844
1528
|
#streams;
|
|
845
1529
|
#controlPlane;
|
|
846
1530
|
#mailbox;
|
|
847
1531
|
#approvals;
|
|
1532
|
+
#multiAgentV2;
|
|
1533
|
+
#collaborationTools;
|
|
848
1534
|
constructor(options) {
|
|
849
1535
|
this.#store = options.store;
|
|
850
1536
|
this.#streams = options.streams;
|
|
851
1537
|
this.#controlPlane = options.controlPlane;
|
|
852
1538
|
this.#mailbox = options.mailbox;
|
|
853
1539
|
this.#approvals = options.approvals;
|
|
1540
|
+
this.#multiAgentV2 = options.multiAgentV2;
|
|
1541
|
+
this.#collaborationTools = createCollaborationTools(options.multiAgentV2);
|
|
854
1542
|
}
|
|
855
1543
|
async execute(turn, context) {
|
|
1544
|
+
if (turn.kind === "approval") {
|
|
1545
|
+
if (!await this.#approvals.applyDecision(turn)) return;
|
|
1546
|
+
await this.#reopen(turn.streamId);
|
|
1547
|
+
return this.execute(
|
|
1548
|
+
{
|
|
1549
|
+
kind: "continuation",
|
|
1550
|
+
streamId: turn.streamId,
|
|
1551
|
+
chatId: turn.chatId,
|
|
1552
|
+
userId: turn.userId
|
|
1553
|
+
},
|
|
1554
|
+
context
|
|
1555
|
+
);
|
|
1556
|
+
}
|
|
1557
|
+
if (turn.kind === "continuation" && turn.recovery !== void 0) {
|
|
1558
|
+
await this.#reopen(turn.streamId);
|
|
1559
|
+
}
|
|
856
1560
|
if (await this.#projectSkippedTerminalTurn(turn)) return;
|
|
857
1561
|
let parked = false;
|
|
858
1562
|
await this.#mailbox.beginTurn(turn);
|
|
@@ -871,7 +1575,11 @@ var AgentTurnExecutor = class {
|
|
|
871
1575
|
async #executeTurn(turn, { signal, park }) {
|
|
872
1576
|
if (await this.#projectSkippedTerminalTurn(turn)) return;
|
|
873
1577
|
const { declaration, thread } = await this.#controlPlane.resolve(turn);
|
|
874
|
-
const
|
|
1578
|
+
const usageHint = thread.path.isRoot ? this.#multiAgentV2.rootAgentUsageHintText : this.#multiAgentV2.subagentUsageHintText;
|
|
1579
|
+
const engine = this.#engineFor(turn).set(
|
|
1580
|
+
...declaration.instructions,
|
|
1581
|
+
...usageHint === void 0 ? [] : [role(usageHint)]
|
|
1582
|
+
);
|
|
875
1583
|
if (turn.kind === "ask" || turn.kind === "mailbox") {
|
|
876
1584
|
const head = (await engine.getMessages()).at(-1);
|
|
877
1585
|
if (this.#approvals.isPaused(head)) {
|
|
@@ -879,7 +1587,12 @@ var AgentTurnExecutor = class {
|
|
|
879
1587
|
return;
|
|
880
1588
|
}
|
|
881
1589
|
}
|
|
882
|
-
|
|
1590
|
+
let communications = [];
|
|
1591
|
+
if (turn.kind === "ask") {
|
|
1592
|
+
communications = await this.#mailbox.drainLeadingQueueOnly(turn);
|
|
1593
|
+
} else if (turn.kind === "mailbox") {
|
|
1594
|
+
communications = await this.#mailbox.drain(turn);
|
|
1595
|
+
}
|
|
883
1596
|
if (turn.kind === "mailbox" && communications.length === 0) {
|
|
884
1597
|
await this.#streams.store.updateStreamStatus(turn.streamId, "completed");
|
|
885
1598
|
return;
|
|
@@ -903,10 +1616,7 @@ var AgentTurnExecutor = class {
|
|
|
903
1616
|
context: engine,
|
|
904
1617
|
tools: {
|
|
905
1618
|
...declaration.tools,
|
|
906
|
-
|
|
907
|
-
send_message: sendMessageTool,
|
|
908
|
-
followup_task: followupTaskTool,
|
|
909
|
-
list_agents: listAgentsTool
|
|
1619
|
+
...this.#collaborationTools
|
|
910
1620
|
},
|
|
911
1621
|
telemetry: declaration.telemetry,
|
|
912
1622
|
prepareStepInput: () => this.#prepareStepInput(turn, mailboxState)
|
|
@@ -973,6 +1683,11 @@ var AgentTurnExecutor = class {
|
|
|
973
1683
|
stream.error
|
|
974
1684
|
);
|
|
975
1685
|
}
|
|
1686
|
+
async #reopen(streamId) {
|
|
1687
|
+
const status = await this.#streams.store.getStreamStatus(streamId);
|
|
1688
|
+
if (status === "queued" || status === "running") return;
|
|
1689
|
+
await this.#streams.reopen(streamId);
|
|
1690
|
+
}
|
|
976
1691
|
async #prepareChain(turn, engine, communications) {
|
|
977
1692
|
if (turn.kind === "ask") {
|
|
978
1693
|
engine.set(
|
|
@@ -1029,14 +1744,23 @@ ${communication.content}`;
|
|
|
1029
1744
|
}
|
|
1030
1745
|
};
|
|
1031
1746
|
|
|
1032
|
-
// packages/experimental/src/zukhruf/approval-controller.ts
|
|
1747
|
+
// packages/experimental/src/zukhruf/runtime/approval-controller.ts
|
|
1033
1748
|
import {
|
|
1749
|
+
getToolName,
|
|
1034
1750
|
isToolUIPart
|
|
1035
1751
|
} from "ai";
|
|
1036
1752
|
import {
|
|
1037
1753
|
ContextEngine as ContextEngine3,
|
|
1038
1754
|
assistant as assistant2
|
|
1039
1755
|
} from "@deepagents/context";
|
|
1756
|
+
|
|
1757
|
+
// packages/experimental/src/zukhruf/runtime/approval-job-id.ts
|
|
1758
|
+
import { v5 as uuidv55 } from "uuid";
|
|
1759
|
+
function approvalJobId(conversation, approvalId) {
|
|
1760
|
+
return uuidv55(`approval:${approvalId}`, conversationNamespace(conversation));
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
// packages/experimental/src/zukhruf/runtime/approval-controller.ts
|
|
1040
1764
|
var ApprovalController = class _ApprovalController {
|
|
1041
1765
|
static #settledToolStates = /* @__PURE__ */ new Set([
|
|
1042
1766
|
"output-available",
|
|
@@ -1044,14 +1768,10 @@ var ApprovalController = class _ApprovalController {
|
|
|
1044
1768
|
"output-denied"
|
|
1045
1769
|
]);
|
|
1046
1770
|
#store;
|
|
1047
|
-
#streams;
|
|
1048
1771
|
#queue;
|
|
1049
|
-
#mutex;
|
|
1050
1772
|
constructor(options) {
|
|
1051
1773
|
this.#store = options.store;
|
|
1052
|
-
this.#streams = options.streams;
|
|
1053
1774
|
this.#queue = options.queue;
|
|
1054
|
-
this.#mutex = options.mutex;
|
|
1055
1775
|
}
|
|
1056
1776
|
isPaused(message) {
|
|
1057
1777
|
return message?.role === "assistant" && this.#pendingToolPart(message) !== void 0;
|
|
@@ -1068,40 +1788,61 @@ var ApprovalController = class _ApprovalController {
|
|
|
1068
1788
|
});
|
|
1069
1789
|
}
|
|
1070
1790
|
async settleDeniedApprovals(conversation, streamId) {
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1791
|
+
const engine = this.#engineFor(conversation);
|
|
1792
|
+
const head = (await engine.getMessages()).at(-1);
|
|
1793
|
+
if (head?.role !== "assistant" || head.id !== streamId) return;
|
|
1794
|
+
const hasDenied = head.parts.some(
|
|
1795
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === false
|
|
1796
|
+
);
|
|
1797
|
+
if (!hasDenied) return;
|
|
1798
|
+
const updated = {
|
|
1799
|
+
...head,
|
|
1800
|
+
parts: head.parts.map((part) => {
|
|
1801
|
+
if (!isToolUIPart(part) || part.state !== "approval-responded" || part.approval.approved !== false) {
|
|
1802
|
+
return part;
|
|
1803
|
+
}
|
|
1804
|
+
const settled = {
|
|
1805
|
+
...part,
|
|
1806
|
+
state: "output-denied",
|
|
1807
|
+
approval: { ...part.approval, approved: false }
|
|
1808
|
+
};
|
|
1809
|
+
return settled;
|
|
1810
|
+
})
|
|
1811
|
+
};
|
|
1812
|
+
await engine.continue(assistant2(updated));
|
|
1087
1813
|
}
|
|
1088
1814
|
async settleFailedApprovals(conversation, streamId, error) {
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1815
|
+
const engine = this.#engineFor(conversation);
|
|
1816
|
+
const head = (await engine.getMessages()).at(-1);
|
|
1817
|
+
if (head?.role !== "assistant" || head.id !== streamId) return;
|
|
1818
|
+
const hasResponded = head.parts.some(
|
|
1819
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded"
|
|
1820
|
+
);
|
|
1821
|
+
if (!hasResponded) return;
|
|
1822
|
+
const updated = {
|
|
1823
|
+
...head,
|
|
1824
|
+
parts: head.parts.map((part) => {
|
|
1825
|
+
if (!isToolUIPart(part) || part.state !== "approval-responded") {
|
|
1826
|
+
return part;
|
|
1827
|
+
}
|
|
1828
|
+
if (part.approval.approved === false) {
|
|
1829
|
+
const denied = {
|
|
1830
|
+
...part,
|
|
1831
|
+
state: "output-denied",
|
|
1832
|
+
approval: { ...part.approval, approved: false }
|
|
1833
|
+
};
|
|
1834
|
+
return denied;
|
|
1835
|
+
}
|
|
1836
|
+
const failed = {
|
|
1837
|
+
...part,
|
|
1838
|
+
state: "output-error",
|
|
1839
|
+
errorText: error,
|
|
1840
|
+
approval: { ...part.approval, approved: true }
|
|
1841
|
+
};
|
|
1842
|
+
return failed;
|
|
1843
|
+
})
|
|
1844
|
+
};
|
|
1845
|
+
await engine.continue(assistant2(updated));
|
|
1105
1846
|
}
|
|
1106
1847
|
async reconcileTerminalContinuation(conversation, streamId, status, error) {
|
|
1107
1848
|
if (status === "completed") {
|
|
@@ -1110,88 +1851,116 @@ var ApprovalController = class _ApprovalController {
|
|
|
1110
1851
|
await this.settleFailedApprovals(
|
|
1111
1852
|
conversation,
|
|
1112
1853
|
streamId,
|
|
1113
|
-
error ??
|
|
1854
|
+
error ?? `approval continuation ${status}`
|
|
1114
1855
|
);
|
|
1115
1856
|
}
|
|
1116
1857
|
await this.#queue.resumeParked(conversation.chatId);
|
|
1117
1858
|
}
|
|
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
|
-
}
|
|
1859
|
+
async retryIdempotentContinuation(conversation, streamId, tools) {
|
|
1860
|
+
const head = (await this.#engineFor(conversation).getMessages()).at(-1);
|
|
1861
|
+
if (head?.role !== "assistant" || head.id !== streamId) return false;
|
|
1862
|
+
const approved = head.parts.filter(
|
|
1863
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === true
|
|
1163
1864
|
);
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1865
|
+
const retryable = approved.length > 0 && approved.every((part) => {
|
|
1866
|
+
const tool7 = tools[getToolName(part)];
|
|
1867
|
+
return tool7?.recovery === "idempotent" && typeof tool7.execute === "function";
|
|
1868
|
+
});
|
|
1869
|
+
if (!retryable) return false;
|
|
1870
|
+
await this.#queue.push({
|
|
1871
|
+
kind: "continuation",
|
|
1872
|
+
streamId,
|
|
1873
|
+
chatId: conversation.chatId,
|
|
1874
|
+
userId: conversation.userId,
|
|
1875
|
+
recovery: "idempotent"
|
|
1876
|
+
});
|
|
1877
|
+
return true;
|
|
1878
|
+
}
|
|
1879
|
+
async applyDecision(turn) {
|
|
1880
|
+
const engine = this.#engineFor(turn);
|
|
1881
|
+
const head = (await engine.getMessages()).at(-1);
|
|
1882
|
+
if (head?.role !== "assistant" || head.id !== turn.streamId) return false;
|
|
1883
|
+
const part = this.#findToolPart(head, turn.toolCallId);
|
|
1884
|
+
if (part?.approval?.id !== turn.approvalId) return false;
|
|
1885
|
+
if (part.approval.approved !== void 0) return false;
|
|
1886
|
+
if (part.state !== "approval-requested") return false;
|
|
1887
|
+
const responded = {
|
|
1888
|
+
...part,
|
|
1889
|
+
state: "approval-responded",
|
|
1890
|
+
approval: { ...part.approval, ...turn.decision }
|
|
1891
|
+
};
|
|
1892
|
+
const updated = {
|
|
1893
|
+
...head,
|
|
1894
|
+
parts: head.parts.map(
|
|
1895
|
+
(candidate) => candidate === part ? responded : candidate
|
|
1896
|
+
)
|
|
1897
|
+
};
|
|
1898
|
+
await engine.continue(assistant2(updated));
|
|
1899
|
+
return !this.#hasUnansweredApprovals(updated);
|
|
1900
|
+
}
|
|
1901
|
+
async recoverUnstartedContinuation(turn, streamId) {
|
|
1902
|
+
if (turn.kind === "approval") await this.applyDecision(turn);
|
|
1903
|
+
const head = (await this.#engineFor(turn).getMessages()).at(-1);
|
|
1904
|
+
if (head?.role !== "assistant" || head.id !== streamId || this.#hasUnansweredApprovals(head) || !head.parts.some(
|
|
1905
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded"
|
|
1906
|
+
)) {
|
|
1907
|
+
return false;
|
|
1170
1908
|
}
|
|
1171
|
-
|
|
1909
|
+
await this.#queue.push({
|
|
1910
|
+
kind: "continuation",
|
|
1911
|
+
streamId,
|
|
1912
|
+
chatId: turn.chatId,
|
|
1913
|
+
userId: turn.userId,
|
|
1914
|
+
recovery: "handoff"
|
|
1915
|
+
});
|
|
1916
|
+
return true;
|
|
1172
1917
|
}
|
|
1173
|
-
async #
|
|
1174
|
-
|
|
1175
|
-
if (
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1918
|
+
async #respond(operation, conversation, toolCallId, approval) {
|
|
1919
|
+
const head = (await this.#engineFor(conversation).getMessages()).at(-1);
|
|
1920
|
+
if (head?.role !== "assistant") {
|
|
1921
|
+
throw new Error(
|
|
1922
|
+
`ApprovalController.${operation}: no paused turn \u2014 the chain head is not an assistant message`
|
|
1923
|
+
);
|
|
1924
|
+
}
|
|
1925
|
+
const part = this.#findToolPart(head, toolCallId);
|
|
1926
|
+
if (!part) {
|
|
1927
|
+
throw new Error(
|
|
1928
|
+
`ApprovalController.${operation}: no tool call "${toolCallId}" on the paused turn`
|
|
1929
|
+
);
|
|
1930
|
+
}
|
|
1931
|
+
if (!part.approval) {
|
|
1932
|
+
throw new Error(
|
|
1933
|
+
`ApprovalController.${operation}: tool call "${toolCallId}" is not awaiting approval`
|
|
1934
|
+
);
|
|
1935
|
+
}
|
|
1936
|
+
const jobId = approvalJobId(conversation, part.approval.id);
|
|
1937
|
+
if (part.approval.approved !== void 0) {
|
|
1938
|
+
if (part.approval.approved !== approval.approved) {
|
|
1939
|
+
throw new Error(
|
|
1940
|
+
`ApprovalController.${operation}: approval already answered with a different decision`
|
|
1941
|
+
);
|
|
1182
1942
|
}
|
|
1183
|
-
|
|
1184
|
-
return;
|
|
1943
|
+
return { id: head.id, jobId, status: "already-applied" };
|
|
1185
1944
|
}
|
|
1186
|
-
if (
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
chatId: conversation.chatId,
|
|
1191
|
-
userId: conversation.userId
|
|
1192
|
-
});
|
|
1945
|
+
if (part.state !== "approval-requested") {
|
|
1946
|
+
throw new Error(
|
|
1947
|
+
`ApprovalController.${operation}: tool call "${toolCallId}" is not awaiting approval`
|
|
1948
|
+
);
|
|
1193
1949
|
}
|
|
1194
|
-
await this.#queue.
|
|
1950
|
+
const result = await this.#queue.push({
|
|
1951
|
+
kind: "approval",
|
|
1952
|
+
streamId: head.id,
|
|
1953
|
+
chatId: conversation.chatId,
|
|
1954
|
+
userId: conversation.userId,
|
|
1955
|
+
toolCallId,
|
|
1956
|
+
approvalId: part.approval.id,
|
|
1957
|
+
decision: approval
|
|
1958
|
+
});
|
|
1959
|
+
return {
|
|
1960
|
+
id: head.id,
|
|
1961
|
+
jobId,
|
|
1962
|
+
status: result.inserted ? "queued" : "already-queued"
|
|
1963
|
+
};
|
|
1195
1964
|
}
|
|
1196
1965
|
#pendingToolPart(message) {
|
|
1197
1966
|
return message.parts.find(
|
|
@@ -1213,83 +1982,7 @@ var ApprovalController = class _ApprovalController {
|
|
|
1213
1982
|
}
|
|
1214
1983
|
};
|
|
1215
1984
|
|
|
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
|
|
1985
|
+
// packages/experimental/src/zukhruf/runtime/agent-runtime.ts
|
|
1293
1986
|
var AgentObservation = class {
|
|
1294
1987
|
engine;
|
|
1295
1988
|
#conversation;
|
|
@@ -1342,12 +2035,10 @@ var AgentRuntime = class {
|
|
|
1342
2035
|
#approvals;
|
|
1343
2036
|
#executor;
|
|
1344
2037
|
constructor(root, options) {
|
|
2038
|
+
const multiAgentV2 = resolveMultiAgentV2HostConfig(options.multiAgentV2);
|
|
1345
2039
|
const declarations = new AgentDeclarationRegistry(root);
|
|
1346
2040
|
const directory = new AgentDirectory(options.store);
|
|
1347
|
-
const streams =
|
|
1348
|
-
store: options.streamStore,
|
|
1349
|
-
changeSource: new PollingChangeSource({ reads: options.streamStore })
|
|
1350
|
-
});
|
|
2041
|
+
const streams = options.streams;
|
|
1351
2042
|
const mailbox = new MailboxCoordinator({
|
|
1352
2043
|
store: options.mailboxStore,
|
|
1353
2044
|
queue: options.queue,
|
|
@@ -1355,9 +2046,7 @@ var AgentRuntime = class {
|
|
|
1355
2046
|
});
|
|
1356
2047
|
const approvals = new ApprovalController({
|
|
1357
2048
|
store: options.store,
|
|
1358
|
-
|
|
1359
|
-
queue: options.queue,
|
|
1360
|
-
mutex: options.approvalMutex
|
|
2049
|
+
queue: options.queue
|
|
1361
2050
|
});
|
|
1362
2051
|
const statusProjector = new AgentStatusProjector({
|
|
1363
2052
|
store: options.store,
|
|
@@ -1367,6 +2056,7 @@ var AgentRuntime = class {
|
|
|
1367
2056
|
directory,
|
|
1368
2057
|
approvals
|
|
1369
2058
|
});
|
|
2059
|
+
const historyForker = new AgentHistoryForker(options.store);
|
|
1370
2060
|
const controlPlane = new AgentControlPlane({
|
|
1371
2061
|
root,
|
|
1372
2062
|
streams,
|
|
@@ -1374,7 +2064,8 @@ var AgentRuntime = class {
|
|
|
1374
2064
|
mailbox,
|
|
1375
2065
|
declarations,
|
|
1376
2066
|
directory,
|
|
1377
|
-
statusProjector
|
|
2067
|
+
statusProjector,
|
|
2068
|
+
historyForker
|
|
1378
2069
|
});
|
|
1379
2070
|
this.#store = options.store;
|
|
1380
2071
|
this.#queue = options.queue;
|
|
@@ -1388,7 +2079,8 @@ var AgentRuntime = class {
|
|
|
1388
2079
|
streams,
|
|
1389
2080
|
controlPlane,
|
|
1390
2081
|
mailbox,
|
|
1391
|
-
approvals
|
|
2082
|
+
approvals,
|
|
2083
|
+
multiAgentV2
|
|
1392
2084
|
});
|
|
1393
2085
|
}
|
|
1394
2086
|
async enqueue(conversation, turn) {
|
|
@@ -1424,7 +2116,28 @@ var AgentRuntime = class {
|
|
|
1424
2116
|
});
|
|
1425
2117
|
stream = await this.#streams.store.getStream(turn.streamId);
|
|
1426
2118
|
}
|
|
1427
|
-
|
|
2119
|
+
let declaration;
|
|
2120
|
+
if ((turn.kind === "approval" || turn.kind === "continuation" && turn.recovery !== "idempotent") && stream?.status === "failed") {
|
|
2121
|
+
try {
|
|
2122
|
+
({ declaration } = await this.#controlPlane.resolve(turn));
|
|
2123
|
+
} catch {
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
if (declaration !== void 0 && await this.#approvals.retryIdempotentContinuation(
|
|
2127
|
+
turn,
|
|
2128
|
+
turn.streamId,
|
|
2129
|
+
declaration.tools ?? {}
|
|
2130
|
+
)) {
|
|
2131
|
+
return;
|
|
2132
|
+
}
|
|
2133
|
+
if ((turn.kind === "approval" || turn.kind === "continuation") && stream?.status === "completed" && await this.#approvals.recoverUnstartedContinuation(
|
|
2134
|
+
turn,
|
|
2135
|
+
turn.streamId
|
|
2136
|
+
)) {
|
|
2137
|
+
return;
|
|
2138
|
+
}
|
|
2139
|
+
stream = await this.#streams.store.getStream(turn.streamId);
|
|
2140
|
+
if ((turn.kind === "approval" || turn.kind === "continuation") && (stream?.status === "completed" || stream?.status === "failed" || stream?.status === "cancelled")) {
|
|
1428
2141
|
await this.#approvals.reconcileTerminalContinuation(
|
|
1429
2142
|
turn,
|
|
1430
2143
|
turn.streamId,
|
|
@@ -1443,7 +2156,7 @@ var AgentRuntime = class {
|
|
|
1443
2156
|
await this.#controlPlane.projectTerminal(turn, thread);
|
|
1444
2157
|
} finally {
|
|
1445
2158
|
try {
|
|
1446
|
-
if (turn.kind === "continuation") {
|
|
2159
|
+
if (turn.kind === "approval" || turn.kind === "continuation") {
|
|
1447
2160
|
await this.#queue.resumeParked(turn.chatId);
|
|
1448
2161
|
}
|
|
1449
2162
|
} finally {
|
|
@@ -1453,10 +2166,6 @@ var AgentRuntime = class {
|
|
|
1453
2166
|
}
|
|
1454
2167
|
};
|
|
1455
2168
|
|
|
1456
|
-
// packages/experimental/src/zukhruf/approval-mutex.ts
|
|
1457
|
-
var ApprovalMutex = class {
|
|
1458
|
-
};
|
|
1459
|
-
|
|
1460
2169
|
// packages/experimental/src/zukhruf/instructions.ts
|
|
1461
2170
|
function defineInstructions(...fragments) {
|
|
1462
2171
|
return fragments;
|
|
@@ -1668,17 +2377,39 @@ var TurnQueue = class {
|
|
|
1668
2377
|
};
|
|
1669
2378
|
|
|
1670
2379
|
// packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
|
|
2380
|
+
var MAX_TIMEOUT_MS = 2147483647;
|
|
1671
2381
|
var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
|
|
1672
2382
|
#boss;
|
|
1673
2383
|
#queue;
|
|
2384
|
+
#schema;
|
|
2385
|
+
#schemaConfigurationError;
|
|
2386
|
+
#table;
|
|
1674
2387
|
#expireInSeconds;
|
|
2388
|
+
#cancelIntentTtlMs;
|
|
1675
2389
|
#heartbeatSeconds;
|
|
1676
2390
|
#pollingIntervalSeconds;
|
|
2391
|
+
#active = /* @__PURE__ */ new Map();
|
|
2392
|
+
#cancelIntents = /* @__PURE__ */ new Map();
|
|
2393
|
+
#cancelIntentExpiryTimer;
|
|
1677
2394
|
constructor(boss, options = {}) {
|
|
1678
2395
|
super();
|
|
1679
2396
|
this.#boss = boss;
|
|
1680
2397
|
this.#queue = options.queue ?? "zukhruf-turns";
|
|
2398
|
+
const configuredSchema = boss.getDb().config?.schema;
|
|
2399
|
+
const bossSchema = typeof configuredSchema === "string" ? configuredSchema : void 0;
|
|
2400
|
+
this.#schema = options.schema ?? bossSchema ?? "pgboss";
|
|
2401
|
+
if (options.schema === void 0 && bossSchema === void 0) {
|
|
2402
|
+
this.#schemaConfigurationError = "PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema";
|
|
2403
|
+
} else if (options.schema !== void 0 && bossSchema !== void 0 && options.schema !== bossSchema) {
|
|
2404
|
+
this.#schemaConfigurationError = `PgBossTurnQueue schema "${options.schema}" does not match the PgBoss schema "${bossSchema}"`;
|
|
2405
|
+
}
|
|
1681
2406
|
this.#expireInSeconds = options.expireInSeconds ?? 3600;
|
|
2407
|
+
this.#cancelIntentTtlMs = this.#expireInSeconds * 1e3;
|
|
2408
|
+
if (!Number.isFinite(this.#expireInSeconds) || this.#expireInSeconds <= 0 || !Number.isSafeInteger(this.#cancelIntentTtlMs) || this.#cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()) {
|
|
2409
|
+
throw new Error(
|
|
2410
|
+
"PgBossTurnQueue expireInSeconds must be a finite positive duration"
|
|
2411
|
+
);
|
|
2412
|
+
}
|
|
1682
2413
|
this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;
|
|
1683
2414
|
this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;
|
|
1684
2415
|
}
|
|
@@ -1689,10 +2420,14 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
|
|
|
1689
2420
|
return `${this.#queue}-dead`;
|
|
1690
2421
|
}
|
|
1691
2422
|
async initialize() {
|
|
2423
|
+
if (this.#schemaConfigurationError) {
|
|
2424
|
+
throw new Error(this.#schemaConfigurationError);
|
|
2425
|
+
}
|
|
1692
2426
|
if (!await this.#boss.getQueue(this.deadLetterQueue)) {
|
|
1693
2427
|
await this.#boss.createQueue(this.deadLetterQueue);
|
|
1694
2428
|
}
|
|
1695
|
-
|
|
2429
|
+
let queue = await this.#boss.getQueue(this.#queue);
|
|
2430
|
+
if (!queue) {
|
|
1696
2431
|
await this.#boss.createQueue(this.#queue, {
|
|
1697
2432
|
policy: "key_strict_fifo",
|
|
1698
2433
|
retryLimit: 0,
|
|
@@ -1701,14 +2436,40 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
|
|
|
1701
2436
|
deleteAfterSeconds: 0,
|
|
1702
2437
|
deadLetter: this.deadLetterQueue
|
|
1703
2438
|
});
|
|
2439
|
+
queue = await this.#boss.getQueue(this.#queue);
|
|
2440
|
+
}
|
|
2441
|
+
if (!queue) throw new Error(`Queue "${this.#queue}" was not initialized`);
|
|
2442
|
+
this.#table = queue.table;
|
|
2443
|
+
try {
|
|
2444
|
+
const catalog = await this.#boss.getDb().executeSql(
|
|
2445
|
+
`SELECT table_name AS "table"
|
|
2446
|
+
FROM ${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}."queue"
|
|
2447
|
+
WHERE name = $1`,
|
|
2448
|
+
[this.#queue]
|
|
2449
|
+
);
|
|
2450
|
+
if (catalog.rows.length !== 1 || catalog.rows[0].table !== this.#table) {
|
|
2451
|
+
throw new Error("queue catalog does not match");
|
|
2452
|
+
}
|
|
2453
|
+
await this.#boss.getDb().executeSql(`SELECT 1 FROM ${this.#relation()} WHERE false`);
|
|
2454
|
+
} catch (cause) {
|
|
2455
|
+
throw new Error(
|
|
2456
|
+
`PgBossTurnQueue schema "${this.#schema}" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,
|
|
2457
|
+
{ cause }
|
|
2458
|
+
);
|
|
1704
2459
|
}
|
|
1705
2460
|
}
|
|
1706
2461
|
async push(turn) {
|
|
1707
|
-
|
|
1708
|
-
|
|
2462
|
+
const jobId = turn.kind === "approval" ? approvalJobId(turn, turn.approvalId) : uuidv7();
|
|
2463
|
+
const inserted = await this.#boss.send(this.#queue, turn, {
|
|
2464
|
+
id: jobId,
|
|
1709
2465
|
singletonKey: turn.chatId,
|
|
1710
|
-
|
|
2466
|
+
group: { id: turn.chatId },
|
|
2467
|
+
priority: turn.kind === "approval" || turn.kind === "continuation" ? 1 : 0
|
|
1711
2468
|
});
|
|
2469
|
+
if (inserted === null && turn.kind !== "approval") {
|
|
2470
|
+
throw new Error(`PgBossTurnQueue job id collision: ${jobId}`);
|
|
2471
|
+
}
|
|
2472
|
+
return { jobId, inserted: inserted !== null };
|
|
1712
2473
|
}
|
|
1713
2474
|
async getTurnActivity(conversation) {
|
|
1714
2475
|
const jobs = await this.#boss.findJobs(this.#queue, {
|
|
@@ -1722,26 +2483,64 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
|
|
|
1722
2483
|
}
|
|
1723
2484
|
return conversationJobs.length > 0 ? "queued" : "idle";
|
|
1724
2485
|
}
|
|
2486
|
+
async getCurrentTurn(conversation) {
|
|
2487
|
+
const jobs = await this.#boss.findJobs(this.#queue, {
|
|
2488
|
+
key: conversation.chatId
|
|
2489
|
+
});
|
|
2490
|
+
return jobs.filter(
|
|
2491
|
+
(job) => job.data.userId === conversation.userId && (job.state === "active" || job.state === "created" || job.state === "retry")
|
|
2492
|
+
).sort(_PgBossTurnQueue.#interruptOrder)[0]?.data;
|
|
2493
|
+
}
|
|
2494
|
+
async cancel(streamId) {
|
|
2495
|
+
this.#rememberCancelIntent(streamId);
|
|
2496
|
+
this.#abortLocal(streamId);
|
|
2497
|
+
const jobs = await this.#boss.findJobs(this.#queue, {
|
|
2498
|
+
data: { streamId }
|
|
2499
|
+
});
|
|
2500
|
+
const queued = jobs.filter((job) => job.state === "created" || job.state === "retry").map((job) => job.id);
|
|
2501
|
+
if (queued.length > 0) await this.#deleteIfStillQueued(queued);
|
|
2502
|
+
this.#abortLocal(streamId);
|
|
2503
|
+
const remaining = await this.#boss.findJobs(this.#queue, {
|
|
2504
|
+
data: { streamId }
|
|
2505
|
+
});
|
|
2506
|
+
if (!remaining.some((job) => job.state === "active")) {
|
|
2507
|
+
this.#forgetCancelIntent(streamId);
|
|
2508
|
+
}
|
|
2509
|
+
}
|
|
1725
2510
|
async consume(handler, options) {
|
|
1726
2511
|
const turnWorkerId = await this.#boss.work(
|
|
1727
2512
|
this.#queue,
|
|
1728
2513
|
{
|
|
1729
2514
|
localConcurrency: options.concurrency ?? 1,
|
|
2515
|
+
groupConcurrency: 1,
|
|
1730
2516
|
pollingIntervalSeconds: this.#pollingIntervalSeconds
|
|
1731
2517
|
},
|
|
1732
2518
|
async ([job]) => {
|
|
1733
2519
|
let parked = false;
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
2520
|
+
const localAbort = new AbortController();
|
|
2521
|
+
const active = this.#active.get(job.data.streamId) ?? /* @__PURE__ */ new Set();
|
|
2522
|
+
active.add(localAbort);
|
|
2523
|
+
this.#active.set(job.data.streamId, active);
|
|
2524
|
+
if (this.#hasCancelIntent(job.data.streamId)) localAbort.abort();
|
|
2525
|
+
try {
|
|
2526
|
+
await handler(job.data, {
|
|
2527
|
+
signal: AbortSignal.any([job.signal, localAbort.signal]),
|
|
2528
|
+
// Parking = self-cancel: a cancelled job stops blocking the chat's
|
|
2529
|
+
// key and is revived (original created_on, so original order) by
|
|
2530
|
+
// resumeParked(). The worker's completion of a cancelled job is a
|
|
2531
|
+
// clean no-op (probe-verified).
|
|
2532
|
+
park: async () => {
|
|
2533
|
+
parked = true;
|
|
2534
|
+
await this.#boss.cancel(this.#queue, job.id);
|
|
2535
|
+
}
|
|
2536
|
+
});
|
|
2537
|
+
} finally {
|
|
2538
|
+
active.delete(localAbort);
|
|
2539
|
+
if (active.size === 0) {
|
|
2540
|
+
this.#active.delete(job.data.streamId);
|
|
2541
|
+
this.#forgetCancelIntent(job.data.streamId);
|
|
1743
2542
|
}
|
|
1744
|
-
}
|
|
2543
|
+
}
|
|
1745
2544
|
if (!parked) {
|
|
1746
2545
|
await this.#boss.deleteJob(this.#queue, job.id);
|
|
1747
2546
|
}
|
|
@@ -1780,14 +2579,162 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
|
|
|
1780
2579
|
await this.#boss.resume(this.#queue, parked);
|
|
1781
2580
|
}
|
|
1782
2581
|
}
|
|
2582
|
+
#abortLocal(streamId) {
|
|
2583
|
+
for (const controller of this.#active.get(streamId) ?? []) {
|
|
2584
|
+
controller.abort();
|
|
2585
|
+
}
|
|
2586
|
+
}
|
|
2587
|
+
#rememberCancelIntent(streamId) {
|
|
2588
|
+
this.#pruneCancelIntents();
|
|
2589
|
+
this.#cancelIntents.set(streamId, Date.now() + this.#cancelIntentTtlMs);
|
|
2590
|
+
this.#scheduleCancelIntentExpiry();
|
|
2591
|
+
}
|
|
2592
|
+
#hasCancelIntent(streamId) {
|
|
2593
|
+
this.#pruneCancelIntents();
|
|
2594
|
+
return this.#cancelIntents.has(streamId);
|
|
2595
|
+
}
|
|
2596
|
+
#pruneCancelIntents() {
|
|
2597
|
+
const now = Date.now();
|
|
2598
|
+
for (const [streamId, expiresAt] of this.#cancelIntents) {
|
|
2599
|
+
if (expiresAt <= now) this.#cancelIntents.delete(streamId);
|
|
2600
|
+
}
|
|
2601
|
+
this.#scheduleCancelIntentExpiry();
|
|
2602
|
+
}
|
|
2603
|
+
#forgetCancelIntent(streamId) {
|
|
2604
|
+
this.#cancelIntents.delete(streamId);
|
|
2605
|
+
this.#scheduleCancelIntentExpiry();
|
|
2606
|
+
}
|
|
2607
|
+
#scheduleCancelIntentExpiry() {
|
|
2608
|
+
if (this.#cancelIntentExpiryTimer !== void 0) {
|
|
2609
|
+
globalThis.clearTimeout(this.#cancelIntentExpiryTimer);
|
|
2610
|
+
this.#cancelIntentExpiryTimer = void 0;
|
|
2611
|
+
}
|
|
2612
|
+
let nextExpiry = Number.POSITIVE_INFINITY;
|
|
2613
|
+
for (const expiresAt of this.#cancelIntents.values()) {
|
|
2614
|
+
nextExpiry = Math.min(nextExpiry, expiresAt);
|
|
2615
|
+
}
|
|
2616
|
+
if (!Number.isFinite(nextExpiry)) return;
|
|
2617
|
+
const timer = globalThis.setTimeout(
|
|
2618
|
+
() => {
|
|
2619
|
+
if (this.#cancelIntentExpiryTimer !== timer) return;
|
|
2620
|
+
this.#cancelIntentExpiryTimer = void 0;
|
|
2621
|
+
this.#pruneCancelIntents();
|
|
2622
|
+
},
|
|
2623
|
+
Math.min(MAX_TIMEOUT_MS, Math.max(1, nextExpiry - Date.now()))
|
|
2624
|
+
);
|
|
2625
|
+
this.#cancelIntentExpiryTimer = timer;
|
|
2626
|
+
timer.unref?.();
|
|
2627
|
+
}
|
|
2628
|
+
async #deleteIfStillQueued(ids) {
|
|
2629
|
+
if (!this.#table) {
|
|
2630
|
+
throw new Error("PgBossTurnQueue.initialize() must run before cancel()");
|
|
2631
|
+
}
|
|
2632
|
+
await this.#boss.getDb().executeSql(
|
|
2633
|
+
`DELETE FROM ${this.#relation()}
|
|
2634
|
+
WHERE name = $1
|
|
2635
|
+
AND id = ANY($2::uuid[])
|
|
2636
|
+
AND state IN ('created', 'retry')`,
|
|
2637
|
+
[this.#queue, ids]
|
|
2638
|
+
);
|
|
2639
|
+
}
|
|
2640
|
+
#relation() {
|
|
2641
|
+
if (!this.#table) {
|
|
2642
|
+
throw new Error(
|
|
2643
|
+
"PgBossTurnQueue.initialize() must resolve its job table"
|
|
2644
|
+
);
|
|
2645
|
+
}
|
|
2646
|
+
return `${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}.${_PgBossTurnQueue.#quoteIdentifier(this.#table)}`;
|
|
2647
|
+
}
|
|
2648
|
+
static #quoteIdentifier(identifier) {
|
|
2649
|
+
return `"${identifier.replaceAll('"', '""')}"`;
|
|
2650
|
+
}
|
|
1783
2651
|
static #orphanError(output) {
|
|
1784
2652
|
if (output && "message" in output && typeof output.message === "string") {
|
|
1785
2653
|
return output.message;
|
|
1786
2654
|
}
|
|
1787
2655
|
return output ? JSON.stringify(output) : "turn orphaned";
|
|
1788
2656
|
}
|
|
2657
|
+
static #interruptOrder(left, right) {
|
|
2658
|
+
if (left.state === "active" && right.state !== "active") return -1;
|
|
2659
|
+
if (left.state !== "active" && right.state === "active") return 1;
|
|
2660
|
+
if (left.priority !== right.priority) return right.priority - left.priority;
|
|
2661
|
+
const created = left.createdOn.getTime() - right.createdOn.getTime();
|
|
2662
|
+
return created || left.id.localeCompare(right.id);
|
|
2663
|
+
}
|
|
1789
2664
|
};
|
|
1790
2665
|
|
|
2666
|
+
// packages/experimental/src/zukhruf/render-turn.ts
|
|
2667
|
+
import { styleText } from "node:util";
|
|
2668
|
+
var dim = (text) => styleText("dim", text);
|
|
2669
|
+
var red = (text) => styleText("red", text);
|
|
2670
|
+
function oneLine(value, max = 88) {
|
|
2671
|
+
const text = String(value ?? "").replaceAll(/\s+/g, " ").trim();
|
|
2672
|
+
return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
|
|
2673
|
+
}
|
|
2674
|
+
function describeToolCall(toolName, input) {
|
|
2675
|
+
const args = input ?? {};
|
|
2676
|
+
switch (toolName) {
|
|
2677
|
+
case "spawn_agent":
|
|
2678
|
+
return `\u21C4 spawn ${args.agent_type} "${args.task_name}" \u2014 ${args.message}`;
|
|
2679
|
+
case "send_message":
|
|
2680
|
+
return `\u21C4 mail ${args.target} \u2014 ${args.message}`;
|
|
2681
|
+
case "followup_task":
|
|
2682
|
+
return `\u21C4 follow-up ${args.target} \u2014 ${args.message}`;
|
|
2683
|
+
case "list_agents":
|
|
2684
|
+
return "\u21C4 list agents";
|
|
2685
|
+
default:
|
|
2686
|
+
return `\xB7 ${toolName}`;
|
|
2687
|
+
}
|
|
2688
|
+
}
|
|
2689
|
+
async function renderTurn(stream) {
|
|
2690
|
+
const toolNames = /* @__PURE__ */ new Map();
|
|
2691
|
+
let midText = false;
|
|
2692
|
+
let thinkingShown = false;
|
|
2693
|
+
const breakText = () => {
|
|
2694
|
+
if (midText) process.stdout.write("\n");
|
|
2695
|
+
midText = false;
|
|
2696
|
+
};
|
|
2697
|
+
for await (const chunk of stream) {
|
|
2698
|
+
switch (chunk.type) {
|
|
2699
|
+
case "reasoning-start":
|
|
2700
|
+
if (!thinkingShown) {
|
|
2701
|
+
console.log(dim("\u2026"));
|
|
2702
|
+
thinkingShown = true;
|
|
2703
|
+
}
|
|
2704
|
+
break;
|
|
2705
|
+
case "text-delta":
|
|
2706
|
+
process.stdout.write(chunk.delta);
|
|
2707
|
+
midText = true;
|
|
2708
|
+
break;
|
|
2709
|
+
case "text-end":
|
|
2710
|
+
breakText();
|
|
2711
|
+
break;
|
|
2712
|
+
case "tool-input-available":
|
|
2713
|
+
toolNames.set(chunk.toolCallId, chunk.toolName);
|
|
2714
|
+
breakText();
|
|
2715
|
+
console.log(dim(describeToolCall(chunk.toolName, chunk.input)));
|
|
2716
|
+
break;
|
|
2717
|
+
case "tool-output-error":
|
|
2718
|
+
breakText();
|
|
2719
|
+
console.log(
|
|
2720
|
+
red(
|
|
2721
|
+
`\u2717 ${toolNames.get(chunk.toolCallId) ?? "tool"}: ${oneLine(chunk.errorText)}`
|
|
2722
|
+
)
|
|
2723
|
+
);
|
|
2724
|
+
break;
|
|
2725
|
+
case "error":
|
|
2726
|
+
breakText();
|
|
2727
|
+
console.log(red(`\u2717 ${oneLine(chunk.errorText)}`));
|
|
2728
|
+
break;
|
|
2729
|
+
case "abort":
|
|
2730
|
+
breakText();
|
|
2731
|
+
console.log(dim("\xB7 turn aborted"));
|
|
2732
|
+
break;
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
breakText();
|
|
2736
|
+
}
|
|
2737
|
+
|
|
1791
2738
|
// packages/experimental/src/zukhruf/sandbox/define.ts
|
|
1792
2739
|
import {
|
|
1793
2740
|
createBashTool
|
|
@@ -1796,86 +2743,20 @@ function defineSandbox(createBackend, options) {
|
|
|
1796
2743
|
return async (context) => createBashTool({ sandbox: await createBackend(context), ...options });
|
|
1797
2744
|
}
|
|
1798
2745
|
|
|
1799
|
-
// packages/experimental/src/zukhruf/sqlite-approval-mutex.ts
|
|
1800
|
-
import { resolve } from "node:path";
|
|
1801
|
-
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
1802
|
-
var SqliteApprovalMutex = class _SqliteApprovalMutex extends ApprovalMutex {
|
|
1803
|
-
static #tails = /* @__PURE__ */ new Map();
|
|
1804
|
-
#db;
|
|
1805
|
-
#coordinationKey;
|
|
1806
|
-
constructor(path) {
|
|
1807
|
-
super();
|
|
1808
|
-
this.#coordinationKey = path === ":memory:" ? crypto.randomUUID() : resolve(path);
|
|
1809
|
-
this.#db = new DatabaseSync2(path);
|
|
1810
|
-
this.#db.exec(`
|
|
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
|
-
`);
|
|
1818
|
-
}
|
|
1819
|
-
async runExclusive(conversationId, operation) {
|
|
1820
|
-
const release = await this.#acquireLocalGate();
|
|
1821
|
-
try {
|
|
1822
|
-
this.#db.exec("BEGIN IMMEDIATE");
|
|
1823
|
-
try {
|
|
1824
|
-
this.#db.prepare(
|
|
1825
|
-
`INSERT INTO approval_mutex (id, conversationId, touchedAt)
|
|
1826
|
-
VALUES (1, ?, ?)
|
|
1827
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
1828
|
-
conversationId = excluded.conversationId,
|
|
1829
|
-
touchedAt = excluded.touchedAt`
|
|
1830
|
-
).run(conversationId, Date.now());
|
|
1831
|
-
const result = await operation();
|
|
1832
|
-
this.#db.exec("COMMIT");
|
|
1833
|
-
return result;
|
|
1834
|
-
} catch (error) {
|
|
1835
|
-
try {
|
|
1836
|
-
this.#db.exec("ROLLBACK");
|
|
1837
|
-
} catch {
|
|
1838
|
-
}
|
|
1839
|
-
throw error;
|
|
1840
|
-
}
|
|
1841
|
-
} finally {
|
|
1842
|
-
release();
|
|
1843
|
-
}
|
|
1844
|
-
}
|
|
1845
|
-
close() {
|
|
1846
|
-
this.#db.close();
|
|
1847
|
-
}
|
|
1848
|
-
[Symbol.dispose]() {
|
|
1849
|
-
this.close();
|
|
1850
|
-
}
|
|
1851
|
-
async #acquireLocalGate() {
|
|
1852
|
-
const previous = _SqliteApprovalMutex.#tails.get(this.#coordinationKey) ?? Promise.resolve();
|
|
1853
|
-
const gate = Promise.withResolvers();
|
|
1854
|
-
const tail = previous.then(() => gate.promise);
|
|
1855
|
-
_SqliteApprovalMutex.#tails.set(this.#coordinationKey, tail);
|
|
1856
|
-
await previous;
|
|
1857
|
-
return () => {
|
|
1858
|
-
gate.resolve();
|
|
1859
|
-
if (_SqliteApprovalMutex.#tails.get(this.#coordinationKey) === tail) {
|
|
1860
|
-
_SqliteApprovalMutex.#tails.delete(this.#coordinationKey);
|
|
1861
|
-
}
|
|
1862
|
-
};
|
|
1863
|
-
}
|
|
1864
|
-
};
|
|
1865
|
-
|
|
1866
2746
|
// packages/experimental/src/zukhruf/tool.ts
|
|
1867
|
-
import { tool as
|
|
2747
|
+
import { tool as tool6 } from "ai";
|
|
2748
|
+
function defineTool(definition) {
|
|
2749
|
+
return tool6(definition);
|
|
2750
|
+
}
|
|
1868
2751
|
export {
|
|
1869
2752
|
AgentObservation,
|
|
1870
2753
|
AgentPath,
|
|
1871
2754
|
AgentRuntime,
|
|
1872
2755
|
AgentThread,
|
|
1873
|
-
ApprovalMutex,
|
|
1874
2756
|
InterAgentCommunicationType,
|
|
1875
2757
|
MailboxStore,
|
|
1876
2758
|
MessageDeliveryMode,
|
|
1877
2759
|
PgBossTurnQueue,
|
|
1878
|
-
SqliteApprovalMutex,
|
|
1879
2760
|
SqliteMailboxStore,
|
|
1880
2761
|
TurnQueue,
|
|
1881
2762
|
assertCommunication,
|
|
@@ -1883,6 +2764,7 @@ export {
|
|
|
1883
2764
|
defineAgent,
|
|
1884
2765
|
defineInstructions,
|
|
1885
2766
|
defineSandbox,
|
|
1886
|
-
|
|
2767
|
+
defineTool,
|
|
2768
|
+
renderTurn
|
|
1887
2769
|
};
|
|
1888
2770
|
//# sourceMappingURL=index.js.map
|