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