@deepagents/experimental 4.3.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.
Files changed (70) hide show
  1. package/README.md +24 -9
  2. package/dist/index.js +2613 -167
  3. package/dist/index.js.map +4 -4
  4. package/dist/zukhruf/agent.d.ts +15 -9
  5. package/dist/zukhruf/agent.d.ts.map +1 -1
  6. package/dist/zukhruf/collaboration/agent-tool-context.d.ts +6 -0
  7. package/dist/zukhruf/collaboration/agent-tool-context.d.ts.map +1 -0
  8. package/dist/zukhruf/collaboration/collaboration-tools.d.ts +4 -0
  9. package/dist/zukhruf/collaboration/collaboration-tools.d.ts.map +1 -0
  10. package/dist/zukhruf/collaboration/interrupt-agent.d.ts +234 -0
  11. package/dist/zukhruf/collaboration/interrupt-agent.d.ts.map +1 -0
  12. package/dist/zukhruf/collaboration/list-agents.d.ts +234 -0
  13. package/dist/zukhruf/collaboration/list-agents.d.ts.map +1 -0
  14. package/dist/zukhruf/collaboration/message-tools.d.ts +452 -0
  15. package/dist/zukhruf/collaboration/message-tools.d.ts.map +1 -0
  16. package/dist/zukhruf/collaboration/spawn-agent.d.ts +313 -0
  17. package/dist/zukhruf/collaboration/spawn-agent.d.ts.map +1 -0
  18. package/dist/zukhruf/collaboration/wait-agent.d.ts +253 -0
  19. package/dist/zukhruf/collaboration/wait-agent.d.ts.map +1 -0
  20. package/dist/zukhruf/control-plane/agent-control-plane.d.ts +80 -0
  21. package/dist/zukhruf/control-plane/agent-control-plane.d.ts.map +1 -0
  22. package/dist/zukhruf/control-plane/agent-declaration-registry.d.ts +9 -0
  23. package/dist/zukhruf/control-plane/agent-declaration-registry.d.ts.map +1 -0
  24. package/dist/zukhruf/control-plane/agent-directory.d.ts +22 -0
  25. package/dist/zukhruf/control-plane/agent-directory.d.ts.map +1 -0
  26. package/dist/zukhruf/control-plane/agent-history-forker.d.ts +10 -0
  27. package/dist/zukhruf/control-plane/agent-history-forker.d.ts.map +1 -0
  28. package/dist/zukhruf/control-plane/agent-path.d.ts +15 -0
  29. package/dist/zukhruf/control-plane/agent-path.d.ts.map +1 -0
  30. package/dist/zukhruf/control-plane/agent-status-projector.d.ts +50 -0
  31. package/dist/zukhruf/control-plane/agent-status-projector.d.ts.map +1 -0
  32. package/dist/zukhruf/control-plane/agent-thread.d.ts +31 -0
  33. package/dist/zukhruf/control-plane/agent-thread.d.ts.map +1 -0
  34. package/dist/zukhruf/control-plane/agent-turn-id.d.ts +12 -0
  35. package/dist/zukhruf/control-plane/agent-turn-id.d.ts.map +1 -0
  36. package/dist/zukhruf/control-plane/fork-turns.d.ts +4 -0
  37. package/dist/zukhruf/control-plane/fork-turns.d.ts.map +1 -0
  38. package/dist/zukhruf/index.d.ts +15 -11
  39. package/dist/zukhruf/index.d.ts.map +1 -1
  40. package/dist/zukhruf/index.js +2613 -167
  41. package/dist/zukhruf/index.js.map +4 -4
  42. package/dist/zukhruf/mailbox/coordinator.d.ts +26 -0
  43. package/dist/zukhruf/mailbox/coordinator.d.ts.map +1 -0
  44. package/dist/zukhruf/mailbox/sqlite.store.d.ts +16 -0
  45. package/dist/zukhruf/mailbox/sqlite.store.d.ts.map +1 -0
  46. package/dist/zukhruf/mailbox/store.d.ts +20 -0
  47. package/dist/zukhruf/mailbox/store.d.ts.map +1 -0
  48. package/dist/zukhruf/mailbox/types.d.ts +35 -0
  49. package/dist/zukhruf/mailbox/types.d.ts.map +1 -0
  50. package/dist/zukhruf/multi-agent-v2-config.d.ts +32 -0
  51. package/dist/zukhruf/multi-agent-v2-config.d.ts.map +1 -0
  52. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +17 -4
  53. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
  54. package/dist/zukhruf/queue/turn-queue.d.ts +49 -6
  55. package/dist/zukhruf/queue/turn-queue.d.ts.map +1 -1
  56. package/dist/zukhruf/render-turn.d.ts +9 -0
  57. package/dist/zukhruf/render-turn.d.ts.map +1 -0
  58. package/dist/zukhruf/runtime/agent-runtime.d.ts +64 -0
  59. package/dist/zukhruf/runtime/agent-runtime.d.ts.map +1 -0
  60. package/dist/zukhruf/runtime/agent-turn-executor.d.ts +21 -0
  61. package/dist/zukhruf/runtime/agent-turn-executor.d.ts.map +1 -0
  62. package/dist/zukhruf/runtime/approval-controller.d.ts +45 -0
  63. package/dist/zukhruf/runtime/approval-controller.d.ts.map +1 -0
  64. package/dist/zukhruf/runtime/approval-job-id.d.ts +3 -0
  65. package/dist/zukhruf/runtime/approval-job-id.d.ts.map +1 -0
  66. package/dist/zukhruf/tool.d.ts +18 -6
  67. package/dist/zukhruf/tool.d.ts.map +1 -1
  68. package/package.json +11 -10
  69. package/dist/zukhruf/runtime.d.ts +0 -67
  70. package/dist/zukhruf/runtime.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -320,239 +320,2437 @@ 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
+ InterAgentCommunicationType: () => InterAgentCommunicationType,
328
+ MailboxStore: () => MailboxStore,
329
+ MessageDeliveryMode: () => MessageDeliveryMode,
323
330
  PgBossTurnQueue: () => PgBossTurnQueue,
331
+ SqliteMailboxStore: () => SqliteMailboxStore,
324
332
  TurnQueue: () => TurnQueue,
325
- createRuntime: () => createRuntime,
333
+ assertCommunication: () => assertCommunication,
334
+ createInterAgentCommunication: () => createInterAgentCommunication,
326
335
  defineAgent: () => defineAgent,
327
336
  defineInstructions: () => defineInstructions,
328
337
  defineSandbox: () => defineSandbox,
329
- defineTool: () => tool
338
+ defineTool: () => defineTool,
339
+ renderTurn: () => renderTurn
330
340
  });
331
341
 
332
342
  // packages/experimental/src/zukhruf/agent.ts
333
343
  function defineAgent(declaration) {
334
344
  return {
335
- name: declaration.name ?? "agent",
345
+ name: declaration.name,
336
346
  model: declaration.model,
337
347
  sandbox: declaration.sandbox,
338
348
  instructions: declaration.instructions,
339
- tools: declaration.tools
349
+ tools: declaration.tools ?? {},
350
+ subagents: declaration.subagents ?? [],
351
+ telemetry: declaration.telemetry
340
352
  };
341
353
  }
342
354
 
343
- // packages/experimental/src/zukhruf/instructions.ts
344
- function defineInstructions(...fragments) {
345
- return fragments;
355
+ // packages/experimental/src/zukhruf/control-plane/agent-path.ts
356
+ var AgentPath = class _AgentPath {
357
+ #value;
358
+ constructor(value) {
359
+ this.#value = value;
360
+ }
361
+ static root() {
362
+ return new _AgentPath("/root");
363
+ }
364
+ static parse(value) {
365
+ const path = value.trim();
366
+ if (path !== "/root" && !path.startsWith("/root/")) {
367
+ throw new Error(`agent path "${value}" must start at /root`);
368
+ }
369
+ const segments = path.slice(1).split("/");
370
+ if (segments.some(
371
+ (segment) => segment.length === 0 || segment !== segment.trim() || segment === "." || segment === ".."
372
+ )) {
373
+ throw new Error(`agent path "${value}" contains an invalid segment`);
374
+ }
375
+ return new _AgentPath(path);
376
+ }
377
+ /** Relative targets name descendants; absolute targets keep their canonical path. */
378
+ resolve(target) {
379
+ const requested = target.trim();
380
+ if (!requested) throw new Error("agent path cannot be empty");
381
+ return _AgentPath.parse(
382
+ requested.startsWith("/") ? requested : `${this.#value}/${requested}`
383
+ );
384
+ }
385
+ contains(candidate) {
386
+ return this.equals(candidate) || candidate.#value.startsWith(`${this.#value}/`);
387
+ }
388
+ equals(other) {
389
+ return this.#value === other.#value;
390
+ }
391
+ get isRoot() {
392
+ return this.#value === "/root";
393
+ }
394
+ get parent() {
395
+ if (this.isRoot) return null;
396
+ return _AgentPath.parse(this.#value.slice(0, this.#value.lastIndexOf("/")));
397
+ }
398
+ toString() {
399
+ return this.#value;
400
+ }
401
+ };
402
+
403
+ // packages/experimental/src/zukhruf/control-plane/agent-thread.ts
404
+ var AgentThread = class _AgentThread {
405
+ conversation;
406
+ treeId;
407
+ path;
408
+ parentChatId;
409
+ declarationName;
410
+ lastTurnId;
411
+ constructor(options) {
412
+ _AgentThread.#assertTopology(options);
413
+ this.conversation = options.conversation;
414
+ this.treeId = options.treeId;
415
+ this.path = options.path;
416
+ this.parentChatId = options.parentChatId;
417
+ this.declarationName = options.declarationName;
418
+ this.lastTurnId = options.lastTurnId;
419
+ }
420
+ static root(conversation, declarationName) {
421
+ return new _AgentThread({
422
+ conversation,
423
+ treeId: conversation.chatId,
424
+ path: AgentPath.root(),
425
+ parentChatId: null,
426
+ declarationName
427
+ });
428
+ }
429
+ static metadataFilter(treeId) {
430
+ return { key: "zukhrufTreeId", value: treeId };
431
+ }
432
+ static hasReservedMetadata(metadata) {
433
+ return Boolean(
434
+ metadata && (Object.hasOwn(metadata, "zukhrufTreeId") || Object.hasOwn(metadata, "zukhruf"))
435
+ );
436
+ }
437
+ static fromMetadata(conversation, metadata) {
438
+ const treeId = metadata?.zukhrufTreeId;
439
+ const zukhruf = metadata?.zukhruf;
440
+ if (typeof treeId !== "string" || !_AgentThread.#isRecord(zukhruf)) {
441
+ return void 0;
442
+ }
443
+ const { path, parentChatId, declarationName, lastTurnId } = zukhruf;
444
+ if (typeof path !== "string" || parentChatId !== null && typeof parentChatId !== "string" || typeof declarationName !== "string" || lastTurnId !== void 0 && typeof lastTurnId !== "string") {
445
+ return void 0;
446
+ }
447
+ let parsedPath;
448
+ try {
449
+ parsedPath = AgentPath.parse(path);
450
+ } catch {
451
+ return void 0;
452
+ }
453
+ if (parsedPath.toString() !== path) return void 0;
454
+ try {
455
+ return new _AgentThread({
456
+ conversation,
457
+ treeId,
458
+ path: parsedPath,
459
+ parentChatId,
460
+ declarationName,
461
+ ...lastTurnId === void 0 ? {} : { lastTurnId }
462
+ });
463
+ } catch {
464
+ return void 0;
465
+ }
466
+ }
467
+ withLatestTurn(lastTurnId) {
468
+ return new _AgentThread({
469
+ conversation: this.conversation,
470
+ treeId: this.treeId,
471
+ path: this.path,
472
+ parentChatId: this.parentChatId,
473
+ declarationName: this.declarationName,
474
+ lastTurnId
475
+ });
476
+ }
477
+ toMetadata(metadata) {
478
+ const existing = _AgentThread.#isRecord(metadata?.zukhruf) ? metadata.zukhruf : {};
479
+ return {
480
+ ...metadata,
481
+ zukhrufTreeId: this.treeId,
482
+ zukhruf: {
483
+ ...existing,
484
+ path: this.path.toString(),
485
+ parentChatId: this.parentChatId,
486
+ declarationName: this.declarationName,
487
+ ...this.lastTurnId === void 0 ? {} : { lastTurnId: this.lastTurnId }
488
+ }
489
+ };
490
+ }
491
+ static #isRecord(value) {
492
+ return typeof value === "object" && value !== null && !Array.isArray(value);
493
+ }
494
+ static #assertTopology(options) {
495
+ if (options.path.isRoot) {
496
+ if (options.treeId !== options.conversation.chatId) {
497
+ throw new Error("root agent thread treeId must match its chatId");
498
+ }
499
+ if (options.parentChatId !== null) {
500
+ throw new Error("root agent thread cannot have a parent");
501
+ }
502
+ return;
503
+ }
504
+ if (options.parentChatId === null) {
505
+ throw new Error("child agent thread requires a parent");
506
+ }
507
+ if (options.parentChatId === options.conversation.chatId) {
508
+ throw new Error("child agent thread cannot parent itself");
509
+ }
510
+ }
511
+ };
512
+
513
+ // packages/experimental/src/zukhruf/runtime/agent-runtime.ts
514
+ import {
515
+ ContextEngine as ContextEngine4
516
+ } from "@deepagents/context";
517
+
518
+ // packages/experimental/src/zukhruf/control-plane/agent-control-plane.ts
519
+ import { v5 as uuidv54 } from "uuid";
520
+
521
+ // packages/experimental/src/zukhruf/mailbox/types.ts
522
+ import { randomUUID } from "node:crypto";
523
+ var MessageDeliveryMode = {
524
+ QueueOnly: "queue-only",
525
+ TriggerTurn: "trigger-turn"
526
+ };
527
+ var InterAgentCommunicationType = {
528
+ Message: "MESSAGE",
529
+ NewTask: "NEW_TASK",
530
+ FinalAnswer: "FINAL_ANSWER"
531
+ };
532
+ function createInterAgentCommunication(communication) {
533
+ const value = {
534
+ ...communication,
535
+ id: communication.id ?? randomUUID(),
536
+ type: communication.type ?? InterAgentCommunicationType.Message,
537
+ otherRecipients: communication.otherRecipients ?? [],
538
+ triggerTurn: false
539
+ };
540
+ assertCommunication(value);
541
+ return value;
542
+ }
543
+ function assertCommunication(communication) {
544
+ if (!communication.id.trim()) {
545
+ throw new Error("inter-agent communication id cannot be empty");
546
+ }
547
+ if (!Object.values(InterAgentCommunicationType).includes(communication.type)) {
548
+ throw new Error("inter-agent communication type is invalid");
549
+ }
550
+ assertConversationId(communication.author, "author");
551
+ assertConversationId(communication.recipient, "recipient");
552
+ for (const recipient of communication.otherRecipients) {
553
+ assertConversationId(recipient, "other recipient");
554
+ }
555
+ if (!communication.content.trim()) {
556
+ throw new Error("inter-agent communication content cannot be empty");
557
+ }
558
+ }
559
+ function assertConversationId(value, label) {
560
+ if (!value.chatId.trim() || !value.userId.trim()) {
561
+ throw new Error(
562
+ `inter-agent communication ${label} requires chatId and userId`
563
+ );
564
+ }
346
565
  }
347
566
 
348
- // packages/experimental/src/zukhruf/tool.ts
349
- import { tool } from "ai";
567
+ // packages/experimental/src/zukhruf/control-plane/agent-declaration-registry.ts
568
+ var AgentDeclarationRegistry = class {
569
+ root;
570
+ #declarations = /* @__PURE__ */ new Map();
571
+ constructor(root) {
572
+ this.root = root;
573
+ this.#register(root, /* @__PURE__ */ new Set());
574
+ }
575
+ get(name) {
576
+ return this.#declarations.get(name);
577
+ }
578
+ #register(declaration, visited) {
579
+ if (visited.has(declaration)) return;
580
+ visited.add(declaration);
581
+ if (!declaration.name.trim()) {
582
+ throw new Error("AgentRuntime: agent declaration name cannot be empty");
583
+ }
584
+ if (declaration.name !== declaration.name.trim()) {
585
+ throw new Error(
586
+ `AgentRuntime: agent declaration name "${declaration.name}" must not contain surrounding whitespace`
587
+ );
588
+ }
589
+ const existing = this.#declarations.get(declaration.name);
590
+ if (existing && existing !== declaration) {
591
+ throw new Error(
592
+ `AgentRuntime: duplicate agent declaration name "${declaration.name}"`
593
+ );
594
+ }
595
+ this.#declarations.set(declaration.name, declaration);
596
+ for (const subagent of declaration.subagents ?? []) {
597
+ this.#register(subagent, visited);
598
+ }
599
+ }
600
+ };
350
601
 
351
- // packages/experimental/src/zukhruf/sandbox/define.ts
602
+ // packages/experimental/src/zukhruf/control-plane/agent-directory.ts
603
+ import { v5 as uuidv5 } from "uuid";
604
+ var AgentDirectory = class _AgentDirectory {
605
+ #store;
606
+ constructor(store) {
607
+ this.#store = store;
608
+ }
609
+ async assertOwnerIfExists(conversation) {
610
+ const chat2 = await this.#store.getChat(conversation.chatId);
611
+ if (!chat2) return;
612
+ this.#assertOwner(conversation, chat2.userId);
613
+ const thread = this.#threadFromMetadata(conversation, chat2.metadata);
614
+ if (thread) await this.#assertValidParent(thread);
615
+ }
616
+ async load(conversation) {
617
+ const chat2 = await this.#store.getChat(conversation.chatId);
618
+ if (chat2) this.#assertOwner(conversation, chat2.userId);
619
+ if (!chat2) return void 0;
620
+ const thread = this.#threadFromMetadata(conversation, chat2.metadata);
621
+ if (thread) await this.#assertValidParent(thread);
622
+ return thread;
623
+ }
624
+ async loadOrCreateRoot(conversation, declarationName) {
625
+ await this.#store.upsertChat({
626
+ id: conversation.chatId,
627
+ userId: conversation.userId
628
+ });
629
+ let thread;
630
+ let adopted = false;
631
+ await this.#store.updateChat(conversation.chatId, (chat2) => {
632
+ this.#assertOwner(conversation, chat2.userId);
633
+ const existing = this.#threadFromMetadata(conversation, chat2.metadata);
634
+ if (existing) {
635
+ thread = existing;
636
+ adopted = true;
637
+ return void 0;
638
+ }
639
+ thread = AgentThread.root(conversation, declarationName);
640
+ adopted = false;
641
+ return { metadata: thread.toMetadata(chat2.metadata) };
642
+ });
643
+ if (adopted) {
644
+ await this.#assertValidParent(thread);
645
+ }
646
+ return thread;
647
+ }
648
+ async recordLatestTurn(conversation, streamId) {
649
+ return this.#updateLatestTurn(conversation, streamId);
650
+ }
651
+ async recordLatestTurnIfCurrent(conversation, streamId, expectedLastTurnId) {
652
+ return this.#updateLatestTurn(conversation, streamId, expectedLastTurnId);
653
+ }
654
+ async listTree(thread) {
655
+ const chats = await this.#store.listChats({
656
+ userId: thread.conversation.userId,
657
+ metadata: AgentThread.metadataFilter(thread.treeId)
658
+ });
659
+ return Promise.all(
660
+ chats.map(async (chat2) => {
661
+ const conversation = { chatId: chat2.id, userId: chat2.userId };
662
+ const member = this.#threadFromMetadata(conversation, chat2.metadata);
663
+ if (!member) {
664
+ throw new Error(
665
+ `AgentDirectory.listTree: chat "${chat2.id}" is missing Zukhruf metadata`
666
+ );
667
+ }
668
+ await this.#assertValidParent(member);
669
+ return member;
670
+ })
671
+ );
672
+ }
673
+ async resolve(thread, target) {
674
+ const path = thread.path.resolve(target);
675
+ const match = await this.find(thread, target);
676
+ if (match) return match;
677
+ throw new Error(`agent path "${path}" does not exist in this tree`);
678
+ }
679
+ async find(thread, target) {
680
+ const path = thread.path.resolve(target);
681
+ return (await this.listTree(thread)).find(
682
+ (candidate) => candidate.path.equals(path)
683
+ );
684
+ }
685
+ async createChild(options) {
686
+ const path = options.parent.path.resolve(options.taskName);
687
+ const pathString = path.toString();
688
+ const conversation = {
689
+ chatId: _AgentDirectory.#childChatId(
690
+ options.parent.conversation.userId,
691
+ options.parent.treeId,
692
+ pathString
693
+ ),
694
+ userId: options.parent.conversation.userId
695
+ };
696
+ const occupied = (await this.listTree(options.parent)).find(
697
+ (thread) => thread.path.equals(path)
698
+ );
699
+ if (occupied && occupied.conversation.chatId !== conversation.chatId) {
700
+ throw new Error(`agent path "${pathString}" already exists`);
701
+ }
702
+ const child = new AgentThread({
703
+ conversation,
704
+ treeId: options.parent.treeId,
705
+ path,
706
+ parentChatId: options.parent.conversation.chatId,
707
+ declarationName: options.declarationName
708
+ });
709
+ const storedChat = await this.#store.upsertChat({
710
+ id: conversation.chatId,
711
+ userId: conversation.userId,
712
+ metadata: child.toMetadata(void 0)
713
+ });
714
+ const stored = AgentThread.fromMetadata(
715
+ { chatId: storedChat.id, userId: storedChat.userId },
716
+ storedChat.metadata
717
+ );
718
+ if (storedChat.userId !== conversation.userId || stored?.treeId !== child.treeId || !stored.path.equals(child.path) || stored.parentChatId !== child.parentChatId || stored.declarationName !== child.declarationName) {
719
+ throw new Error(`agent path "${pathString}" already exists`);
720
+ }
721
+ return stored;
722
+ }
723
+ static #childChatId(userId, treeId, path) {
724
+ return uuidv5(
725
+ `urn:deepagents:zukhruf:agent:${JSON.stringify([userId, treeId, path])}`,
726
+ uuidv5.URL
727
+ );
728
+ }
729
+ #assertOwner(conversation, storedUserId) {
730
+ if (storedUserId === conversation.userId) return;
731
+ throw new Error(
732
+ `chat "${conversation.chatId}" belongs to user "${storedUserId}", not "${conversation.userId}"`
733
+ );
734
+ }
735
+ #threadFromMetadata(conversation, metadata) {
736
+ const thread = AgentThread.fromMetadata(conversation, metadata);
737
+ if (!thread && AgentThread.hasReservedMetadata(metadata)) {
738
+ throw new Error(
739
+ `invalid Zukhruf metadata for chat "${conversation.chatId}"`
740
+ );
741
+ }
742
+ return thread;
743
+ }
744
+ async #assertValidParent(thread) {
745
+ if (thread.path.isRoot) return;
746
+ const parentChatId = thread.parentChatId;
747
+ if (!parentChatId) {
748
+ throw new Error(
749
+ `invalid Zukhruf parent for chat "${thread.conversation.chatId}"`
750
+ );
751
+ }
752
+ const parentChat = await this.#store.getChat(parentChatId);
753
+ if (!parentChat || parentChat.userId !== thread.conversation.userId) {
754
+ throw new Error(
755
+ `invalid Zukhruf parent for chat "${thread.conversation.chatId}"`
756
+ );
757
+ }
758
+ const parent = this.#threadFromMetadata(
759
+ { chatId: parentChat.id, userId: parentChat.userId },
760
+ parentChat.metadata
761
+ );
762
+ const expectedPath = thread.path.parent;
763
+ if (!parent || !expectedPath || parent.treeId !== thread.treeId || !parent.path.equals(expectedPath)) {
764
+ throw new Error(
765
+ `invalid Zukhruf parent for chat "${thread.conversation.chatId}"`
766
+ );
767
+ }
768
+ }
769
+ async #updateLatestTurn(conversation, streamId, ...expected) {
770
+ let result;
771
+ await this.#store.updateChat(conversation.chatId, (chat2) => {
772
+ this.#assertOwner(conversation, chat2.userId);
773
+ const thread = this.#threadFromMetadata(conversation, chat2.metadata);
774
+ if (!thread) {
775
+ throw new Error(
776
+ `AgentDirectory.recordLatestTurn: missing agent metadata for chat "${conversation.chatId}"`
777
+ );
778
+ }
779
+ if (expected.length > 0 && thread.lastTurnId !== expected[0]) {
780
+ result = void 0;
781
+ return void 0;
782
+ }
783
+ if (thread.lastTurnId === streamId) {
784
+ result = thread;
785
+ return void 0;
786
+ }
787
+ result = thread.withLatestTurn(streamId);
788
+ return { metadata: result.toMetadata(chat2.metadata) };
789
+ });
790
+ return result;
791
+ }
792
+ };
793
+
794
+ // packages/experimental/src/zukhruf/control-plane/agent-history-forker.ts
795
+ import { validateUIMessages } from "ai";
796
+ import { v5 as uuidv52 } from "uuid";
352
797
  import {
353
- createBashTool
798
+ isSyntheticReminderMessage
354
799
  } from "@deepagents/context";
355
- function defineSandbox(createBackend, options) {
356
- return async (context) => createBashTool({ sandbox: await createBackend(context), ...options });
800
+ var AgentHistoryForker = class {
801
+ #store;
802
+ constructor(store) {
803
+ this.#store = store;
804
+ }
805
+ async fork(parent, child, forkTurns) {
806
+ const record = await this.#claim(parent, child, forkTurns);
807
+ if (record.forkTurns === "none" || record.parentHeadMessageId === null) {
808
+ return;
809
+ }
810
+ const selected = await this.#selectedMessages(parent, child, record);
811
+ if (selected.length === 0) return;
812
+ const cloned = this.#cloneMessages(child, selected);
813
+ const expectedIds = cloned.map((message) => message.id);
814
+ const branch = await this.#store.getActiveBranch(child.conversation.chatId);
815
+ if (!branch) {
816
+ throw new Error(
817
+ `spawn_agent: child chat "${child.conversation.chatId}" has no active branch`
818
+ );
819
+ }
820
+ if (branch.headMessageId !== null) {
821
+ if (await this.#hasForkedPrefix(child, expectedIds)) return;
822
+ throw new Error(
823
+ `spawn_agent: cannot apply parent history after child "${child.path}" has started`
824
+ );
825
+ }
826
+ const head = cloned.at(-1);
827
+ if (!head) return;
828
+ await this.#store.addMessages(cloned);
829
+ const committed = await this.#store.updateBranchHead(
830
+ branch.id,
831
+ head.id,
832
+ null
833
+ );
834
+ if (!committed && !await this.#hasForkedPrefix(child, expectedIds)) {
835
+ throw new Error(
836
+ `spawn_agent: child "${child.path}" started before parent history was applied`
837
+ );
838
+ }
839
+ if (!await this.#hasForkedPrefix(child, expectedIds)) {
840
+ throw new Error(
841
+ `spawn_agent: failed to persist parent history for child "${child.path}"`
842
+ );
843
+ }
844
+ }
845
+ async #claim(parent, child, forkTurns) {
846
+ const parentBranch = await this.#store.getActiveBranch(
847
+ parent.conversation.chatId
848
+ );
849
+ if (!parentBranch) {
850
+ throw new Error(
851
+ `spawn_agent: parent chat "${parent.conversation.chatId}" has no active branch`
852
+ );
853
+ }
854
+ const proposed = {
855
+ forkTurns,
856
+ parentChatId: parent.conversation.chatId,
857
+ parentHeadMessageId: forkTurns === "none" ? null : parentBranch.headMessageId
858
+ };
859
+ let claimed;
860
+ await this.#store.updateChat(child.conversation.chatId, (chat2) => {
861
+ const metadata = chat2.metadata;
862
+ const zukhruf = metadata?.zukhruf;
863
+ if (!isRecord(zukhruf)) {
864
+ throw new Error(
865
+ `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
866
+ );
867
+ }
868
+ if (zukhruf.historyFork !== void 0) {
869
+ claimed = parseHistoryForkRecord(zukhruf.historyFork);
870
+ if (claimed.parentChatId !== proposed.parentChatId || claimed.forkTurns !== proposed.forkTurns) {
871
+ throw new Error(
872
+ `spawn_agent: agent path "${child.path}" already exists with a different fork_turns setting`
873
+ );
874
+ }
875
+ return void 0;
876
+ }
877
+ claimed = proposed;
878
+ return {
879
+ metadata: {
880
+ ...metadata,
881
+ zukhruf: { ...zukhruf, historyFork: proposed }
882
+ }
883
+ };
884
+ });
885
+ if (!claimed) {
886
+ throw new Error(
887
+ `spawn_agent: failed to claim history for child "${child.path}"`
888
+ );
889
+ }
890
+ return claimed;
891
+ }
892
+ async #sourceMessages(parent, record) {
893
+ const headId = record.parentHeadMessageId;
894
+ if (headId === null) return [];
895
+ const chain = await this.#store.getMessageChain(headId);
896
+ if (chain.at(-1)?.id !== headId) {
897
+ throw new Error(
898
+ `spawn_agent: parent history head "${headId}" is unavailable`
899
+ );
900
+ }
901
+ if (chain.some((message) => message.chatId !== parent.conversation.chatId)) {
902
+ throw new Error("spawn_agent: parent history crosses chat boundaries");
903
+ }
904
+ const materialized = chain.filter(
905
+ (message) => !isEmptyAssistantPlaceholder(message.data)
906
+ );
907
+ const messages = await validateUIMessages({
908
+ messages: materialized.map((message) => message.data)
909
+ });
910
+ return materialized.map((stored, index) => {
911
+ const message = messages[index];
912
+ if (message.id !== stored.id) {
913
+ throw new Error(
914
+ `spawn_agent: stored message "${stored.id}" has a mismatched payload id`
915
+ );
916
+ }
917
+ return { stored, message };
918
+ });
919
+ }
920
+ async #selectedMessages(parent, child, record) {
921
+ if (record.forkTurns === "none") return [];
922
+ if (record.sourceMessageIds !== void 0) {
923
+ return this.#messagesById(parent, record.sourceMessageIds);
924
+ }
925
+ const source = await this.#sourceMessages(parent, record);
926
+ const selected = this.#select(source, record.forkTurns).map((entry) => this.#keepHistoryMessage(entry)).filter((entry) => entry !== void 0);
927
+ const sourceMessageIds = await this.#claimSelection(
928
+ child,
929
+ selected.map(({ stored }) => stored.id)
930
+ );
931
+ return arraysEqual(
932
+ sourceMessageIds,
933
+ selected.map(({ stored }) => stored.id)
934
+ ) ? selected : this.#messagesById(parent, sourceMessageIds);
935
+ }
936
+ async #messagesById(parent, sourceMessageIds) {
937
+ const storedMessages = await Promise.all(
938
+ sourceMessageIds.map((id) => this.#store.getMessage(id))
939
+ );
940
+ if (storedMessages.some(
941
+ (message) => message === void 0 || message.chatId !== parent.conversation.chatId
942
+ )) {
943
+ throw new Error(
944
+ "spawn_agent: persisted parent-history snapshot is unavailable"
945
+ );
946
+ }
947
+ const stored = storedMessages;
948
+ const messages = await validateUIMessages({
949
+ messages: stored.map((message) => message.data)
950
+ });
951
+ return stored.map((messageData, index) => {
952
+ const source = this.#keepHistoryMessage({
953
+ stored: messageData,
954
+ message: messages[index]
955
+ });
956
+ if (!source || source.message.id !== messageData.id) {
957
+ throw new Error(
958
+ `spawn_agent: persisted parent-history message "${messageData.id}" changed shape`
959
+ );
960
+ }
961
+ return source;
962
+ });
963
+ }
964
+ async #claimSelection(child, proposedIds) {
965
+ let sourceMessageIds;
966
+ await this.#store.updateChat(child.conversation.chatId, (chat2) => {
967
+ const metadata = chat2.metadata;
968
+ const zukhruf = metadata?.zukhruf;
969
+ if (!isRecord(zukhruf)) {
970
+ throw new Error(
971
+ `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
972
+ );
973
+ }
974
+ const record = parseHistoryForkRecord(zukhruf.historyFork);
975
+ if (record.sourceMessageIds !== void 0) {
976
+ sourceMessageIds = record.sourceMessageIds;
977
+ return void 0;
978
+ }
979
+ sourceMessageIds = proposedIds;
980
+ return {
981
+ metadata: {
982
+ ...metadata,
983
+ zukhruf: {
984
+ ...zukhruf,
985
+ historyFork: { ...record, sourceMessageIds: proposedIds }
986
+ }
987
+ }
988
+ };
989
+ });
990
+ if (!sourceMessageIds) {
991
+ throw new Error(
992
+ `spawn_agent: failed to claim parent-history messages for child "${child.path}"`
993
+ );
994
+ }
995
+ return sourceMessageIds;
996
+ }
997
+ #select(source, forkTurns) {
998
+ if (forkTurns === "all") return source;
999
+ const boundaries = source.flatMap(
1000
+ (entry, index) => isForkTurnBoundary(entry.message) ? [index] : []
1001
+ );
1002
+ const start = boundaries.at(-forkTurns) ?? boundaries[0];
1003
+ return start === void 0 ? [] : source.slice(start);
1004
+ }
1005
+ #keepHistoryMessage(entry) {
1006
+ const { message } = entry;
1007
+ if (message.role === "user") {
1008
+ if (isSyntheticReminderMessage(message) || interAgentCommunication(message) !== void 0) {
1009
+ return void 0;
1010
+ }
1011
+ return entry;
1012
+ }
1013
+ if (message.role !== "assistant") return void 0;
1014
+ const finalStepStart = message.parts.findLastIndex(
1015
+ (part) => part.type === "step-start"
1016
+ );
1017
+ const parts = message.parts.slice(finalStepStart + 1).filter(
1018
+ (part) => ["text", "file", "source-url", "source-document"].includes(part.type)
1019
+ );
1020
+ return parts.length === 0 ? void 0 : { ...entry, message: { ...message, parts } };
1021
+ }
1022
+ #cloneMessages(child, selected) {
1023
+ let parentId = null;
1024
+ return selected.map(({ stored, message }) => {
1025
+ const id = uuidv52(
1026
+ `urn:deepagents:zukhruf:forked-message:${JSON.stringify([
1027
+ child.conversation.chatId,
1028
+ stored.id
1029
+ ])}`,
1030
+ uuidv52.URL
1031
+ );
1032
+ const clone = {
1033
+ id,
1034
+ chatId: child.conversation.chatId,
1035
+ parentId,
1036
+ name: message.role,
1037
+ type: "message",
1038
+ data: { ...message, id },
1039
+ createdAt: stored.createdAt
1040
+ };
1041
+ parentId = id;
1042
+ return clone;
1043
+ });
1044
+ }
1045
+ async #hasForkedPrefix(child, expectedIds) {
1046
+ const branch = await this.#store.getActiveBranch(child.conversation.chatId);
1047
+ if (!branch?.headMessageId) return false;
1048
+ const chain = await this.#store.getMessageChain(branch.headMessageId);
1049
+ return expectedIds.every(
1050
+ (id, index) => chain[index]?.id === id && chain[index]?.chatId === child.conversation.chatId
1051
+ );
1052
+ }
1053
+ };
1054
+ function isForkTurnBoundary(message) {
1055
+ if (message.role !== "user" || isSyntheticReminderMessage(message)) {
1056
+ return false;
1057
+ }
1058
+ return interAgentCommunication(message)?.triggerTurn ?? true;
1059
+ }
1060
+ function interAgentCommunication(message) {
1061
+ if (!isRecord(message.metadata)) return void 0;
1062
+ if (!Object.hasOwn(message.metadata, "interAgentCommunication")) {
1063
+ return void 0;
1064
+ }
1065
+ const communication = message.metadata.interAgentCommunication;
1066
+ if (!isRecord(communication) || typeof communication.triggerTurn !== "boolean") {
1067
+ throw new Error(
1068
+ `spawn_agent: message "${message.id}" has invalid inter-agent metadata`
1069
+ );
1070
+ }
1071
+ return { triggerTurn: communication.triggerTurn };
1072
+ }
1073
+ function parseHistoryForkRecord(value) {
1074
+ if (!isRecord(value)) {
1075
+ throw new Error("spawn_agent: invalid persisted history-fork metadata");
1076
+ }
1077
+ const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } = value;
1078
+ if (!isForkTurns(forkTurns) || typeof parentChatId !== "string" || !parentChatId.trim() || parentHeadMessageId !== null && (typeof parentHeadMessageId !== "string" || parentHeadMessageId.length === 0) || sourceMessageIds !== void 0 && (!Array.isArray(sourceMessageIds) || !sourceMessageIds.every(
1079
+ (id) => typeof id === "string" && id.trim().length > 0
1080
+ ) || new Set(sourceMessageIds).size !== sourceMessageIds.length)) {
1081
+ throw new Error("spawn_agent: invalid persisted history-fork metadata");
1082
+ }
1083
+ return {
1084
+ forkTurns,
1085
+ parentChatId,
1086
+ parentHeadMessageId,
1087
+ ...sourceMessageIds === void 0 ? {} : { sourceMessageIds }
1088
+ };
1089
+ }
1090
+ function isForkTurns(value) {
1091
+ return value === "none" || value === "all" || typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1092
+ }
1093
+ function isRecord(value) {
1094
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1095
+ }
1096
+ function isEmptyAssistantPlaceholder(value) {
1097
+ return isRecord(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
1098
+ }
1099
+ function arraysEqual(left, right) {
1100
+ return left.length === right.length && left.every((value, index) => value === right[index]);
1101
+ }
1102
+
1103
+ // packages/experimental/src/zukhruf/control-plane/agent-status-projector.ts
1104
+ import { isTextUIPart } from "ai";
1105
+ import { z } from "zod";
1106
+ import {
1107
+ ContextEngine
1108
+ } from "@deepagents/context";
1109
+ var listedAgentStatusSchema = z.union([
1110
+ z.enum(["pending_init", "running", "interrupted", "shutdown", "not_found"]),
1111
+ z.object({ completed: z.string().nullable() }).strict(),
1112
+ z.object({ errored: z.string() }).strict()
1113
+ ]);
1114
+ var listedAgentSchema = z.object({
1115
+ agent_name: z.string(),
1116
+ agent_status: listedAgentStatusSchema
1117
+ }).strict();
1118
+ var AgentStatusProjector = class _AgentStatusProjector {
1119
+ #store;
1120
+ #streams;
1121
+ #queue;
1122
+ #mailbox;
1123
+ #directory;
1124
+ #approvals;
1125
+ constructor(options) {
1126
+ this.#store = options.store;
1127
+ this.#streams = options.streams;
1128
+ this.#queue = options.queue;
1129
+ this.#mailbox = options.mailbox;
1130
+ this.#directory = options.directory;
1131
+ this.#approvals = options.approvals;
1132
+ }
1133
+ async projectListedAgent(currentTurn, thread) {
1134
+ const messages = await this.#messages(thread);
1135
+ const head = messages.at(-1);
1136
+ const streamId = thread.lastTurnId ?? (head?.role === "assistant" ? head.id : void 0);
1137
+ const stream = streamId ? await this.#streams.store.getStream(streamId) : void 0;
1138
+ const scheduledTurn = await this.#queue.getCurrentTurn(thread.conversation);
1139
+ const scheduledStream = scheduledTurn ? await this.#streams.store.getStream(scheduledTurn.streamId) : void 0;
1140
+ let status = _AgentStatusProjector.#listedStatus(
1141
+ stream?.status,
1142
+ stream?.error,
1143
+ head
1144
+ );
1145
+ if (stream?.status === "completed" && this.#approvals.isPaused(head)) {
1146
+ status = "running";
1147
+ }
1148
+ if (thread.conversation.chatId === currentTurn.chatId || thread.lastTurnId !== void 0 && scheduledTurn?.streamId !== thread.lastTurnId && (scheduledStream?.status === "queued" || scheduledStream?.status === "running")) {
1149
+ status = "running";
1150
+ }
1151
+ return {
1152
+ agent_name: thread.path.toString(),
1153
+ agent_status: status
1154
+ };
1155
+ }
1156
+ async projectTerminal(turn, thread) {
1157
+ if (thread.parentChatId === null) return;
1158
+ const stream = await this.#streams.store.getStream(turn.streamId);
1159
+ if (!stream || stream.status !== "completed" && stream.status !== "failed" && stream.status !== "cancelled") {
1160
+ return;
1161
+ }
1162
+ const message = (await this.#messages(thread)).find(
1163
+ (candidate) => candidate.role === "assistant" && candidate.id === turn.streamId
1164
+ );
1165
+ if (stream.status === "completed" && this.#approvals.isPaused(message)) {
1166
+ return;
1167
+ }
1168
+ const text = message?.role === "assistant" ? _AgentStatusProjector.#messageText(message) : "";
1169
+ let content = text || "Agent completed without a text response.";
1170
+ if (stream.status === "failed") {
1171
+ content = `Agent failed: ${stream.error || "unknown error"}`;
1172
+ } else if (stream.status === "cancelled") {
1173
+ content = "Agent was interrupted.";
1174
+ }
1175
+ const parent = await this.#directory.load({
1176
+ chatId: thread.parentChatId,
1177
+ userId: thread.conversation.userId
1178
+ });
1179
+ await this.#mailbox.deliver(
1180
+ createInterAgentCommunication({
1181
+ id: `zukhruf:child-terminal:${turn.streamId}`,
1182
+ type: InterAgentCommunicationType.FinalAnswer,
1183
+ author: thread.conversation,
1184
+ recipient: {
1185
+ chatId: thread.parentChatId,
1186
+ userId: thread.conversation.userId
1187
+ },
1188
+ content,
1189
+ metadata: {
1190
+ authorPath: thread.path.toString(),
1191
+ recipientPath: parent?.path.toString() ?? thread.parentChatId,
1192
+ streamId: turn.streamId,
1193
+ status: stream.status
1194
+ }
1195
+ }),
1196
+ MessageDeliveryMode.QueueOnly
1197
+ );
1198
+ }
1199
+ async #messages(thread) {
1200
+ const engine = new ContextEngine({
1201
+ store: this.#store,
1202
+ chatId: thread.conversation.chatId,
1203
+ userId: thread.conversation.userId
1204
+ });
1205
+ return engine.getMessages();
1206
+ }
1207
+ static #listedStatus(status, error, head) {
1208
+ switch (status) {
1209
+ case "running":
1210
+ return "running";
1211
+ case "completed":
1212
+ return {
1213
+ completed: head?.role === "assistant" ? _AgentStatusProjector.#messageText(head) || null : null
1214
+ };
1215
+ case "failed":
1216
+ return { errored: error || "Agent turn failed." };
1217
+ case "cancelled":
1218
+ return "interrupted";
1219
+ case "queued":
1220
+ case void 0:
1221
+ return "pending_init";
1222
+ }
1223
+ }
1224
+ static #messageText(message) {
1225
+ return message.parts.filter(isTextUIPart).map((part) => part.text).join("\n").trim();
1226
+ }
1227
+ };
1228
+
1229
+ // packages/experimental/src/zukhruf/control-plane/agent-turn-id.ts
1230
+ import { v5 as uuidv53 } from "uuid";
1231
+ var AgentTurnId = class _AgentTurnId {
1232
+ static #prefix = "zukhruf-turn";
1233
+ #value;
1234
+ constructor(value) {
1235
+ this.#value = value;
1236
+ }
1237
+ static fromRequest(conversation, requestId) {
1238
+ if (!requestId.trim()) {
1239
+ throw new Error("turn id cannot be empty");
1240
+ }
1241
+ const scope = conversationNamespace(conversation);
1242
+ return new _AgentTurnId(
1243
+ `${_AgentTurnId.#prefix}:${scope}:${uuidv53(requestId, scope)}`
1244
+ );
1245
+ }
1246
+ static random(conversation) {
1247
+ return _AgentTurnId.fromRequest(conversation, crypto.randomUUID());
1248
+ }
1249
+ static assertOwner(conversation, streamId) {
1250
+ const expectedPrefix = `${_AgentTurnId.#prefix}:${conversationNamespace(conversation)}:`;
1251
+ if (!streamId.startsWith(expectedPrefix)) {
1252
+ throw new Error(
1253
+ `stream "${streamId}" does not belong to conversation "${conversation.chatId}"`
1254
+ );
1255
+ }
1256
+ }
1257
+ toString() {
1258
+ return this.#value;
1259
+ }
1260
+ };
1261
+ function conversationNamespace(conversation) {
1262
+ if (!conversation.chatId.trim() || !conversation.userId.trim()) {
1263
+ throw new Error("conversation requires non-empty chatId and userId");
1264
+ }
1265
+ return uuidv53(
1266
+ JSON.stringify([conversation.userId, conversation.chatId]),
1267
+ uuidv53.URL
1268
+ );
1269
+ }
1270
+
1271
+ // packages/experimental/src/zukhruf/control-plane/agent-control-plane.ts
1272
+ var AgentControlPlane = class _AgentControlPlane {
1273
+ #root;
1274
+ #streams;
1275
+ #queue;
1276
+ #mailbox;
1277
+ #declarations;
1278
+ #directory;
1279
+ #statusProjector;
1280
+ #historyForker;
1281
+ constructor(options) {
1282
+ this.#root = options.root;
1283
+ this.#streams = options.streams;
1284
+ this.#queue = options.queue;
1285
+ this.#mailbox = options.mailbox;
1286
+ this.#declarations = options.declarations;
1287
+ this.#directory = options.directory;
1288
+ this.#statusProjector = options.statusProjector;
1289
+ this.#historyForker = options.historyForker;
1290
+ }
1291
+ async resolve(conversation) {
1292
+ const thread = await this.#directory.loadOrCreateRoot(
1293
+ conversation,
1294
+ this.#root.name
1295
+ );
1296
+ const declaration = this.#declarations.get(thread.declarationName);
1297
+ if (!declaration) {
1298
+ throw new Error(
1299
+ `AgentControlPlane.resolve: unknown agent declaration "${thread.declarationName}"`
1300
+ );
1301
+ }
1302
+ return { declaration, thread };
1303
+ }
1304
+ async enqueue(conversation, turn) {
1305
+ if (!turn.id.trim()) {
1306
+ throw new Error(
1307
+ "enqueue: turn id is required \u2014 it names the ask, making retries idempotent"
1308
+ );
1309
+ }
1310
+ await this.#directory.assertOwnerIfExists(conversation);
1311
+ const streamId = AgentTurnId.fromRequest(conversation, turn.id).toString();
1312
+ await this.#streams.register(streamId);
1313
+ await this.#queue.push({
1314
+ kind: "ask",
1315
+ streamId,
1316
+ chatId: conversation.chatId,
1317
+ userId: conversation.userId,
1318
+ input: turn.input
1319
+ });
1320
+ return streamId;
1321
+ }
1322
+ recordLatestTurn(conversation, streamId) {
1323
+ return this.#directory.recordLatestTurn(conversation, streamId);
1324
+ }
1325
+ recordLatestTurnIfCurrent(conversation, streamId, expectedLastTurnId) {
1326
+ return this.#directory.recordLatestTurnIfCurrent(
1327
+ conversation,
1328
+ streamId,
1329
+ expectedLastTurnId
1330
+ );
1331
+ }
1332
+ async spawn(actor, input) {
1333
+ const childDeclaration = (actor.declaration.subagents ?? []).find(
1334
+ (subagent) => subagent.name === input.agentType
1335
+ );
1336
+ if (!childDeclaration) {
1337
+ throw new Error(
1338
+ `spawn_agent: agent type "${input.agentType}" is not a subagent of "${actor.declaration.name}"`
1339
+ );
1340
+ }
1341
+ let child;
1342
+ try {
1343
+ child = await this.#directory.createChild({
1344
+ parent: actor.thread,
1345
+ taskName: input.taskName,
1346
+ declarationName: childDeclaration.name
1347
+ });
1348
+ } catch (error) {
1349
+ if (error instanceof Error && error.message.startsWith("agent path ")) {
1350
+ throw new Error(`spawn_agent: ${error.message}`);
1351
+ }
1352
+ throw error;
1353
+ }
1354
+ const childPath = child.path.toString();
1355
+ const requestId = _AgentControlPlane.#initialTurnId(
1356
+ child.conversation.chatId
1357
+ );
1358
+ const streamId = AgentTurnId.fromRequest(
1359
+ child.conversation,
1360
+ requestId
1361
+ ).toString();
1362
+ const status = await this.#streams.store.getStreamStatus(streamId);
1363
+ if (status === "completed" || status === "failed" || status === "cancelled") {
1364
+ throw new Error(
1365
+ `spawn_agent: agent path "${childPath}" already finished with status "${status}"`
1366
+ );
1367
+ }
1368
+ await this.#historyForker.fork(actor.thread, child, input.forkTurns);
1369
+ await this.enqueue(child.conversation, {
1370
+ id: requestId,
1371
+ input: input.message
1372
+ });
1373
+ return { task_name: childPath };
1374
+ }
1375
+ async sendMessage(actor, input) {
1376
+ return this.#deliverAgentMessage(actor, input, {
1377
+ type: InterAgentCommunicationType.Message,
1378
+ mode: MessageDeliveryMode.QueueOnly,
1379
+ rejectRoot: false
1380
+ });
1381
+ }
1382
+ async followupTask(actor, input) {
1383
+ return this.#deliverAgentMessage(actor, input, {
1384
+ type: InterAgentCommunicationType.NewTask,
1385
+ mode: MessageDeliveryMode.TriggerTurn,
1386
+ rejectRoot: true
1387
+ });
1388
+ }
1389
+ async listAgents(actor, pathPrefix) {
1390
+ const prefix = pathPrefix ? actor.thread.path.resolve(pathPrefix) : void 0;
1391
+ const threads = await this.#directory.listTree(actor.thread);
1392
+ const agents = await Promise.all(
1393
+ threads.flatMap((thread) => {
1394
+ if (prefix && !prefix.contains(thread.path)) return [];
1395
+ return [this.#statusProjector.projectListedAgent(actor.turn, thread)];
1396
+ })
1397
+ );
1398
+ agents.sort(
1399
+ (left, right) => left.agent_name.localeCompare(right.agent_name)
1400
+ );
1401
+ return { agents };
1402
+ }
1403
+ async interruptAgent(actor, input) {
1404
+ const target = await this.#directory.find(actor.thread, input.target);
1405
+ if (!target) return { previous_status: "not_found" };
1406
+ if (target.path.isRoot) {
1407
+ throw new Error("interrupt_agent: the root agent cannot be interrupted");
1408
+ }
1409
+ if (target.path.equals(actor.thread.path)) {
1410
+ throw new Error("interrupt_agent: an agent cannot interrupt itself");
1411
+ }
1412
+ const previous = await this.#statusProjector.projectListedAgent(
1413
+ actor.turn,
1414
+ target
1415
+ );
1416
+ const currentTurn = await this.#queue.getCurrentTurn(target.conversation);
1417
+ if (currentTurn) {
1418
+ const interruptedThread = await this.#directory.recordLatestTurnIfCurrent(
1419
+ target.conversation,
1420
+ currentTurn.streamId,
1421
+ target.lastTurnId
1422
+ ) ?? target;
1423
+ await this.#streams.cancel(currentTurn.streamId);
1424
+ await this.#statusProjector.projectTerminal(
1425
+ currentTurn,
1426
+ interruptedThread
1427
+ );
1428
+ await this.#queue.cancel(currentTurn.streamId);
1429
+ }
1430
+ return { previous_status: previous.agent_status };
1431
+ }
1432
+ waitForMailbox(actor, options) {
1433
+ return this.#mailbox.waitForPending(actor.thread.conversation, options);
1434
+ }
1435
+ async projectTerminal(turn, thread) {
1436
+ await this.#statusProjector.projectTerminal(turn, thread);
1437
+ }
1438
+ async #deliverAgentMessage(actor, input, options) {
1439
+ const target = await this.#directory.resolve(actor.thread, input.target);
1440
+ if (options.rejectRoot && target.path.isRoot) {
1441
+ throw new Error(
1442
+ "followup_task: the root agent cannot receive a follow-up"
1443
+ );
1444
+ }
1445
+ await this.#mailbox.deliver(
1446
+ createInterAgentCommunication({
1447
+ type: options.type,
1448
+ author: actor.thread.conversation,
1449
+ recipient: target.conversation,
1450
+ content: input.message,
1451
+ metadata: {
1452
+ authorPath: actor.thread.path.toString(),
1453
+ recipientPath: target.path.toString()
1454
+ }
1455
+ }),
1456
+ options.mode
1457
+ );
1458
+ return { target: target.path.toString() };
1459
+ }
1460
+ static #initialTurnId(chatId) {
1461
+ return uuidv54(`urn:deepagents:zukhruf:initial-turn:${chatId}`, uuidv54.URL);
1462
+ }
1463
+ };
1464
+
1465
+ // packages/experimental/src/zukhruf/mailbox/coordinator.ts
1466
+ import { setTimeout as delay } from "node:timers/promises";
1467
+ var WAIT_POLL_INTERVAL_MS = 50;
1468
+ var MailboxCoordinator = class {
1469
+ #store;
1470
+ #queue;
1471
+ #streams;
1472
+ #wakeRequests = /* @__PURE__ */ new Map();
1473
+ constructor(options) {
1474
+ this.#store = options.store;
1475
+ this.#queue = options.queue;
1476
+ this.#streams = options.streams;
1477
+ }
1478
+ async deliver(communication, mode) {
1479
+ const delivered = {
1480
+ ...communication,
1481
+ type: mode === MessageDeliveryMode.TriggerTurn ? InterAgentCommunicationType.NewTask : communication.type,
1482
+ triggerTurn: mode === MessageDeliveryMode.TriggerTurn
1483
+ };
1484
+ assertCommunication(delivered);
1485
+ const { recipientActive } = await this.#store.enqueue(delivered);
1486
+ if (delivered.triggerTurn || recipientActive) {
1487
+ await this.#scheduleWake(delivered.recipient);
1488
+ }
1489
+ }
1490
+ beginTurn(turn) {
1491
+ return this.#store.beginTurn(turn, turn.streamId);
1492
+ }
1493
+ async endTurn(turn, options = {}) {
1494
+ const { hasPending, turnEnded } = await this.#store.endTurn(
1495
+ turn,
1496
+ turn.streamId
1497
+ );
1498
+ if (turnEnded && hasPending && !options.parked) {
1499
+ await this.#scheduleWake(turn);
1500
+ }
1501
+ }
1502
+ drainLeadingQueueOnly(recipient) {
1503
+ return this.#store.drainLeadingQueueOnly(recipient);
1504
+ }
1505
+ drain(recipient) {
1506
+ return this.#store.drain(recipient);
1507
+ }
1508
+ async waitForPending(recipient, options) {
1509
+ const deadline = Date.now() + options.timeoutMs;
1510
+ while (true) {
1511
+ options.signal?.throwIfAborted();
1512
+ if (await this.#store.hasPending(recipient)) return true;
1513
+ const remaining = deadline - Date.now();
1514
+ if (remaining <= 0) return false;
1515
+ await delay(Math.min(WAIT_POLL_INTERVAL_MS, remaining), void 0, {
1516
+ signal: options.signal
1517
+ });
1518
+ }
1519
+ }
1520
+ #scheduleWake(target) {
1521
+ const key = this.#conversationKey(target);
1522
+ const existing = this.#wakeRequests.get(key);
1523
+ if (existing) return existing;
1524
+ const request = (async () => {
1525
+ const wakeId = AgentTurnId.random(target).toString();
1526
+ await this.#streams.register(wakeId);
1527
+ try {
1528
+ await this.#queue.push({
1529
+ kind: "mailbox",
1530
+ streamId: wakeId,
1531
+ chatId: target.chatId,
1532
+ userId: target.userId
1533
+ });
1534
+ } catch (error) {
1535
+ await this.#streams.store.updateStreamStatus(wakeId, "failed", {
1536
+ error: error instanceof Error ? error.message : String(error)
1537
+ });
1538
+ throw error;
1539
+ }
1540
+ })();
1541
+ this.#wakeRequests.set(key, request);
1542
+ const clearRequest = () => {
1543
+ if (this.#wakeRequests.get(key) === request) {
1544
+ this.#wakeRequests.delete(key);
1545
+ }
1546
+ };
1547
+ void request.then(clearRequest, clearRequest);
1548
+ return request;
1549
+ }
1550
+ #conversationKey(conversation) {
1551
+ return JSON.stringify([conversation.chatId, conversation.userId]);
1552
+ }
1553
+ };
1554
+
1555
+ // packages/experimental/src/zukhruf/multi-agent-v2-config.ts
1556
+ var DEFAULT_MIN_WAIT_TIMEOUT_MS = 1e4;
1557
+ var DEFAULT_WAIT_TIMEOUT_MS = 3e4;
1558
+ var DEFAULT_MAX_WAIT_TIMEOUT_MS = 36e5;
1559
+ var RESERVED_TOOL_NAMESPACES = /* @__PURE__ */ new Set([
1560
+ "api_tool",
1561
+ "browser",
1562
+ "computer",
1563
+ "container",
1564
+ "file_search",
1565
+ "functions",
1566
+ "image_gen",
1567
+ "multi_tool_use",
1568
+ "python",
1569
+ "python_user_visible",
1570
+ "submodel_delegator",
1571
+ "terminal",
1572
+ "tool_search",
1573
+ "web"
1574
+ ]);
1575
+ function resolveMultiAgentV2HostConfig(input = {}) {
1576
+ const minWaitTimeoutMs = input.minWaitTimeoutMs ?? DEFAULT_MIN_WAIT_TIMEOUT_MS;
1577
+ const defaultWaitTimeoutMs = input.defaultWaitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
1578
+ const maxWaitTimeoutMs = input.maxWaitTimeoutMs ?? DEFAULT_MAX_WAIT_TIMEOUT_MS;
1579
+ assertTimeout("minWaitTimeoutMs", minWaitTimeoutMs);
1580
+ assertTimeout("defaultWaitTimeoutMs", defaultWaitTimeoutMs);
1581
+ assertTimeout("maxWaitTimeoutMs", maxWaitTimeoutMs);
1582
+ if (minWaitTimeoutMs > maxWaitTimeoutMs) {
1583
+ throw new Error(
1584
+ "AgentRuntime: multiAgentV2.minWaitTimeoutMs must be at most maxWaitTimeoutMs"
1585
+ );
1586
+ }
1587
+ if (defaultWaitTimeoutMs < minWaitTimeoutMs) {
1588
+ throw new Error(
1589
+ "AgentRuntime: multiAgentV2.defaultWaitTimeoutMs must be at least minWaitTimeoutMs"
1590
+ );
1591
+ }
1592
+ if (defaultWaitTimeoutMs > maxWaitTimeoutMs) {
1593
+ throw new Error(
1594
+ "AgentRuntime: multiAgentV2.defaultWaitTimeoutMs must be at most maxWaitTimeoutMs"
1595
+ );
1596
+ }
1597
+ const toolNamespace = input.toolNamespace;
1598
+ if (toolNamespace !== void 0 && (toolNamespace.length === 0 || toolNamespace.trim() !== toolNamespace)) {
1599
+ throw new Error(
1600
+ "AgentRuntime: multiAgentV2.toolNamespace cannot be empty or padded"
1601
+ );
1602
+ }
1603
+ if (toolNamespace !== void 0) validateToolNamespace(toolNamespace);
1604
+ const nonCodeModeOnly = input.nonCodeModeOnly ?? true;
1605
+ if (!nonCodeModeOnly) {
1606
+ throw new Error(
1607
+ "AgentRuntime: multiAgentV2.nonCodeModeOnly=false requires a nested code-mode executor, which Zukhruf does not provide"
1608
+ );
1609
+ }
1610
+ const tool7 = (name) => toolNamespace === void 0 ? name : `${toolNamespace}.${name}`;
1611
+ const collaborationTools = [
1612
+ "spawn_agent",
1613
+ "send_message",
1614
+ "followup_task",
1615
+ "wait_agent",
1616
+ "interrupt_agent",
1617
+ "list_agents"
1618
+ ].map((name) => `\`${tool7(name)}\``).join(", ");
1619
+ const shared = `Call ${collaborationTools} directly. They are intentionally unavailable inside nested code execution.
1620
+
1621
+ All agents share the same workspace, current working directory, and filesystem.`;
1622
+ return {
1623
+ minWaitTimeoutMs,
1624
+ defaultWaitTimeoutMs,
1625
+ maxWaitTimeoutMs,
1626
+ usageHintText: nonEmptyText(input.usageHintText),
1627
+ rootAgentUsageHintText: input.rootAgentUsageHintText === void 0 ? defaultRootUsageHint(tool7, shared) : nonEmptyText(input.rootAgentUsageHintText),
1628
+ subagentUsageHintText: input.subagentUsageHintText === void 0 ? defaultSubagentUsageHint(tool7, shared) : nonEmptyText(input.subagentUsageHintText),
1629
+ toolNamespace,
1630
+ nonCodeModeOnly
1631
+ };
1632
+ }
1633
+ function assertTimeout(name, value) {
1634
+ if (!Number.isSafeInteger(value) || value < 0) {
1635
+ throw new Error(
1636
+ `AgentRuntime: multiAgentV2.${name} must be a non-negative safe integer`
1637
+ );
1638
+ }
1639
+ }
1640
+ function validateToolNamespace(namespace) {
1641
+ if (namespace.length > 64 || !/^[a-zA-Z0-9_-]+$/.test(namespace) || namespace === "mcp" || namespace.startsWith("mcp__") || RESERVED_TOOL_NAMESPACES.has(namespace)) {
1642
+ throw new Error(
1643
+ `AgentRuntime: multiAgentV2.toolNamespace "${namespace}" is a reserved tool namespace or invalid`
1644
+ );
1645
+ }
1646
+ }
1647
+ function nonEmptyText(value) {
1648
+ if (value === void 0) return void 0;
1649
+ return value.length === 0 ? void 0 : value;
1650
+ }
1651
+ function defaultRootUsageHint(tool7, shared) {
1652
+ return `You are \`/root\`, the primary agent in a team of agents collaborating to fulfill the user's goals.
1653
+
1654
+ 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.
1655
+
1656
+ 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.
1657
+
1658
+ Child messages arrive as \`MESSAGE\` or \`FINAL_ANSWER\` mailbox envelopes with their task name, sender, and payload preserved.
1659
+
1660
+ ${shared}`;
1661
+ }
1662
+ function defaultSubagentUsageHint(tool7, shared) {
1663
+ return `You are an agent in a team collaborating to complete a task.
1664
+
1665
+ 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.
1666
+
1667
+ 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.
1668
+
1669
+ ${shared}`;
357
1670
  }
358
1671
 
359
- // packages/experimental/src/zukhruf/runtime.ts
360
- import { isToolUIPart } from "ai";
1672
+ // packages/experimental/src/zukhruf/runtime/agent-turn-executor.ts
361
1673
  import {
362
- ContextEngine,
363
- PollingChangeSource,
364
- StreamManager,
1674
+ ContextEngine as ContextEngine2,
365
1675
  agent,
366
1676
  assistant,
367
1677
  chat,
1678
+ role,
368
1679
  user
369
1680
  } from "@deepagents/context";
370
- var SETTLED_TOOL_STATES = /* @__PURE__ */ new Set([
371
- "output-available",
372
- "output-error",
373
- "output-denied"
374
- ]);
375
- function pendingToolPart(message) {
376
- return message.parts.find(
377
- (part) => isToolUIPart(part) && !SETTLED_TOOL_STATES.has(part.state)
378
- );
1681
+
1682
+ // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
1683
+ import { tool } from "ai";
1684
+ import { z as z2 } from "zod";
1685
+ var interruptAgentInputSchema = z2.object({
1686
+ target: z2.string().trim().min(1).describe(
1687
+ "The canonical /root/... path, or a descendant-relative target name."
1688
+ )
1689
+ });
1690
+ var interruptAgentOutputSchema = z2.object({ previous_status: listedAgentStatusSchema }).strict();
1691
+ var interruptAgentTool = tool({
1692
+ description: "Interrupt an agent's current turn, if any, and return its previous status. The agent remains available for messages and follow-up tasks.",
1693
+ inputSchema: interruptAgentInputSchema,
1694
+ outputSchema: interruptAgentOutputSchema,
1695
+ execute: async (input, { context }) => context.controlPlane.interruptAgent(context.actor, input)
1696
+ });
1697
+
1698
+ // packages/experimental/src/zukhruf/collaboration/list-agents.ts
1699
+ import { tool as tool2 } from "ai";
1700
+ import { z as z3 } from "zod";
1701
+ var listAgentsInputSchema = z3.object({
1702
+ path_prefix: z3.string().trim().min(1).describe(
1703
+ "Task-path prefix without a trailing slash. Omit to list the whole tree."
1704
+ ).optional()
1705
+ });
1706
+ var listAgentsOutputSchema = z3.object({ agents: z3.array(listedAgentSchema) }).strict();
1707
+ var listAgentsTool = tool2({
1708
+ description: "List live agents in the current root thread tree. Optionally filter by task-path prefix.",
1709
+ inputSchema: listAgentsInputSchema,
1710
+ outputSchema: listAgentsOutputSchema,
1711
+ execute: async ({ path_prefix }, { context }) => context.controlPlane.listAgents(context.actor, path_prefix)
1712
+ });
1713
+
1714
+ // packages/experimental/src/zukhruf/collaboration/message-tools.ts
1715
+ import { tool as tool3 } from "ai";
1716
+ import { z as z4 } from "zod";
1717
+ var agentMessageInputSchema = z4.object({
1718
+ target: z4.string().trim().min(1).describe(
1719
+ "The canonical /root/... path, or a descendant-relative target name."
1720
+ ),
1721
+ message: z4.string().trim().min(1).describe("The message or follow-up task.")
1722
+ });
1723
+ var sendMessageTool = tool3({
1724
+ description: "Queue a message for another agent. Address siblings with their canonical /root/... path.",
1725
+ inputSchema: agentMessageInputSchema,
1726
+ execute: async (input, { context }) => {
1727
+ await context.controlPlane.sendMessage(context.actor, input);
1728
+ return "";
1729
+ }
1730
+ });
1731
+ var followupTaskTool = tool3({
1732
+ description: "Send a follow-up task to an existing non-root agent and wake its thread.",
1733
+ inputSchema: agentMessageInputSchema,
1734
+ execute: async (input, { context }) => {
1735
+ await context.controlPlane.followupTask(context.actor, input);
1736
+ return "";
1737
+ }
1738
+ });
1739
+
1740
+ // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
1741
+ import { tool as tool4 } from "ai";
1742
+ import { z as z5 } from "zod";
1743
+
1744
+ // packages/experimental/src/zukhruf/control-plane/fork-turns.ts
1745
+ var forkTurnsError = "fork_turns must be `none`, `all`, or a positive integer string";
1746
+ function parseForkTurns(value) {
1747
+ const normalized = value.trim().toLowerCase();
1748
+ if (normalized === "none" || normalized === "all") return normalized;
1749
+ if (!/^\d+$/.test(normalized)) return void 0;
1750
+ const turns = Number(normalized);
1751
+ return Number.isSafeInteger(turns) && turns > 0 ? turns : void 0;
379
1752
  }
380
- function createRuntime(declaration, options) {
381
- const { store, streamStore, queue } = options;
382
- const manager = new StreamManager({
383
- store: streamStore,
384
- changeSource: new PollingChangeSource({ reads: streamStore })
1753
+
1754
+ // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
1755
+ var spawnAgentInputSchema = z5.object({
1756
+ agent_type: z5.string().trim().min(1).describe("The name of one available subagent declaration."),
1757
+ task_name: z5.string().trim().min(1).refine(
1758
+ (value) => value !== "." && value !== ".." && !value.includes("/"),
1759
+ "task_name must be one non-empty path segment"
1760
+ ).describe("One path segment naming this independent agent task."),
1761
+ message: z5.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent."),
1762
+ fork_turns: z5.string().trim().default("all").refine((value) => parseForkTurns(value) !== void 0, forkTurnsError).describe(
1763
+ "Optional number of parent turns to fork. Defaults to `all`. Use `none`, `all`, or a positive integer string such as `3`."
1764
+ )
1765
+ });
1766
+ var spawnAgentOutputSchema = z5.object({ task_name: z5.string() }).strict();
1767
+ function createSpawnAgentTool(options) {
1768
+ return tool4({
1769
+ description: ({ context }) => {
1770
+ const available = (context.actor.declaration.subagents ?? []).map((subagent) => subagent.name).join(", ");
1771
+ return [
1772
+ `Spawn an independent subagent. Available agent types: ${available || "none"}.`,
1773
+ options?.usageHintText
1774
+ ].filter(Boolean).join(" ");
1775
+ },
1776
+ inputSchema: spawnAgentInputSchema,
1777
+ outputSchema: spawnAgentOutputSchema,
1778
+ execute: async ({ agent_type, task_name, message, fork_turns }, { context }) => {
1779
+ const forkTurns = parseForkTurns(fork_turns);
1780
+ if (forkTurns === void 0) throw new Error(forkTurnsError);
1781
+ return context.controlPlane.spawn(context.actor, {
1782
+ agentType: agent_type,
1783
+ taskName: task_name,
1784
+ message,
1785
+ forkTurns
1786
+ });
1787
+ }
1788
+ });
1789
+ }
1790
+
1791
+ // packages/experimental/src/zukhruf/collaboration/wait-agent.ts
1792
+ import { tool as tool5 } from "ai";
1793
+ import { z as z6 } from "zod";
1794
+ var waitAgentOutputSchema = z6.object({ message: z6.string(), timed_out: z6.boolean() }).strict();
1795
+ function createWaitAgentTool(options) {
1796
+ const waitAgentInputSchema = z6.object({
1797
+ timeout_ms: z6.number().int().min(options.minTimeoutMs).max(options.maxTimeoutMs).optional().describe("Maximum time to wait in milliseconds.")
385
1798
  });
386
- function engineFor({ chatId, userId }) {
387
- return new ContextEngine({ store, chatId, userId });
1799
+ return tool5({
1800
+ description: "Wait for pending mail addressed to this agent without consuming it.",
1801
+ inputSchema: waitAgentInputSchema,
1802
+ outputSchema: waitAgentOutputSchema,
1803
+ execute: async ({ timeout_ms }, { abortSignal, context }) => {
1804
+ const received = await context.controlPlane.waitForMailbox(
1805
+ context.actor,
1806
+ {
1807
+ timeoutMs: timeout_ms ?? options.defaultTimeoutMs,
1808
+ signal: abortSignal
1809
+ }
1810
+ );
1811
+ return received ? { message: "Wait completed.", timed_out: false } : { message: "Wait timed out.", timed_out: true };
1812
+ }
1813
+ });
1814
+ }
1815
+
1816
+ // packages/experimental/src/zukhruf/collaboration/collaboration-tools.ts
1817
+ var NAMESPACE_DESCRIPTION = "Tools for spawning and managing sub-agents.";
1818
+ function createCollaborationTools(config) {
1819
+ const tools = {
1820
+ spawn_agent: createSpawnAgentTool({
1821
+ usageHintText: config.usageHintText
1822
+ }),
1823
+ send_message: sendMessageTool,
1824
+ followup_task: followupTaskTool,
1825
+ list_agents: listAgentsTool,
1826
+ wait_agent: createWaitAgentTool({
1827
+ minTimeoutMs: config.minWaitTimeoutMs,
1828
+ defaultTimeoutMs: config.defaultWaitTimeoutMs,
1829
+ maxTimeoutMs: config.maxWaitTimeoutMs
1830
+ }),
1831
+ interrupt_agent: interruptAgentTool
1832
+ };
1833
+ return Object.fromEntries(
1834
+ Object.entries(tools).map(([name, collaborationTool]) => [
1835
+ name,
1836
+ configureTool(collaborationTool, config)
1837
+ ])
1838
+ );
1839
+ }
1840
+ function configureTool(collaborationTool, config) {
1841
+ const openai = collaborationTool.providerOptions?.openai;
1842
+ return {
1843
+ ...collaborationTool,
1844
+ providerOptions: {
1845
+ ...collaborationTool.providerOptions,
1846
+ ...config.toolNamespace === void 0 ? {} : {
1847
+ openai: {
1848
+ ...typeof openai === "object" && openai !== null ? openai : {},
1849
+ namespace: {
1850
+ name: config.toolNamespace,
1851
+ description: NAMESPACE_DESCRIPTION
1852
+ }
1853
+ }
1854
+ }
1855
+ },
1856
+ metadata: {
1857
+ ...collaborationTool.metadata,
1858
+ zukhruf: {
1859
+ kind: "collaboration",
1860
+ codeModeExposure: "direct-model-only"
1861
+ }
1862
+ }
1863
+ };
1864
+ }
1865
+
1866
+ // packages/experimental/src/zukhruf/runtime/agent-turn-executor.ts
1867
+ var AgentTurnExecutor = class {
1868
+ #store;
1869
+ #streams;
1870
+ #controlPlane;
1871
+ #mailbox;
1872
+ #approvals;
1873
+ #multiAgentV2;
1874
+ #collaborationTools;
1875
+ constructor(options) {
1876
+ this.#store = options.store;
1877
+ this.#streams = options.streams;
1878
+ this.#controlPlane = options.controlPlane;
1879
+ this.#mailbox = options.mailbox;
1880
+ this.#approvals = options.approvals;
1881
+ this.#multiAgentV2 = options.multiAgentV2;
1882
+ this.#collaborationTools = createCollaborationTools(options.multiAgentV2);
388
1883
  }
389
- async function executeTurn(turn, { signal, park }) {
390
- const status = await streamStore.getStreamStatus(turn.streamId);
391
- if (status !== "queued" && status !== "running") return;
392
- const engine = engineFor(turn).set(...declaration.instructions);
393
- if (turn.kind === "ask") {
1884
+ async execute(turn, context) {
1885
+ if (turn.kind === "approval") {
1886
+ if (!await this.#approvals.applyDecision(turn)) return;
1887
+ await this.#reopen(turn.streamId);
1888
+ return this.execute(
1889
+ {
1890
+ kind: "continuation",
1891
+ streamId: turn.streamId,
1892
+ chatId: turn.chatId,
1893
+ userId: turn.userId
1894
+ },
1895
+ context
1896
+ );
1897
+ }
1898
+ if (turn.kind === "continuation" && turn.recovery !== void 0) {
1899
+ await this.#reopen(turn.streamId);
1900
+ }
1901
+ if (await this.#projectSkippedTerminalTurn(turn)) return;
1902
+ let parked = false;
1903
+ await this.#mailbox.beginTurn(turn);
1904
+ try {
1905
+ await this.#executeTurn(turn, {
1906
+ ...context,
1907
+ park: async () => {
1908
+ parked = true;
1909
+ await context.park();
1910
+ }
1911
+ });
1912
+ } finally {
1913
+ await this.#mailbox.endTurn(turn, { parked });
1914
+ }
1915
+ }
1916
+ async #executeTurn(turn, { signal, park }) {
1917
+ if (await this.#projectSkippedTerminalTurn(turn)) return;
1918
+ const { declaration, thread } = await this.#controlPlane.resolve(turn);
1919
+ const usageHint = thread.path.isRoot ? this.#multiAgentV2.rootAgentUsageHintText : this.#multiAgentV2.subagentUsageHintText;
1920
+ const engine = this.#engineFor(turn).set(
1921
+ ...declaration.instructions,
1922
+ ...usageHint === void 0 ? [] : [role(usageHint)]
1923
+ );
1924
+ if (turn.kind === "ask" || turn.kind === "mailbox") {
394
1925
  const head = (await engine.getMessages()).at(-1);
395
- if (head?.role === "assistant" && pendingToolPart(head)) {
1926
+ if (this.#approvals.isPaused(head)) {
396
1927
  await park();
397
1928
  return;
398
1929
  }
1930
+ }
1931
+ let communications = [];
1932
+ if (turn.kind === "ask") {
1933
+ communications = await this.#mailbox.drainLeadingQueueOnly(turn);
1934
+ } else if (turn.kind === "mailbox") {
1935
+ communications = await this.#mailbox.drain(turn);
1936
+ }
1937
+ if (turn.kind === "mailbox" && communications.length === 0) {
1938
+ await this.#streams.store.updateStreamStatus(turn.streamId, "completed");
1939
+ return;
1940
+ }
1941
+ await this.#controlPlane.recordLatestTurn(turn, turn.streamId);
1942
+ await this.#prepareChain(turn, engine, communications);
1943
+ const sandbox = await declaration.sandbox({
1944
+ chatId: turn.chatId,
1945
+ userId: turn.userId
1946
+ });
1947
+ if (await this.#projectSkippedTerminalTurn(turn)) return;
1948
+ if (!await this.#streams.claim(turn.streamId)) {
1949
+ await this.#projectSkippedTerminalTurn(turn);
1950
+ return;
1951
+ }
1952
+ const mailboxState = { firstRequest: true };
1953
+ const ai = agent({
1954
+ name: declaration.name,
1955
+ model: declaration.model,
1956
+ sandbox,
1957
+ context: engine,
1958
+ tools: {
1959
+ ...declaration.tools,
1960
+ ...this.#collaborationTools
1961
+ },
1962
+ telemetry: declaration.telemetry,
1963
+ prepareStepInput: () => this.#prepareStepInput(turn, mailboxState)
1964
+ });
1965
+ const abort = new AbortController();
1966
+ const onWorkerAbort = () => abort.abort();
1967
+ signal.addEventListener("abort", onWorkerAbort, { once: true });
1968
+ try {
1969
+ const setupCancellation = this.#streams.monitorCancellation(
1970
+ turn.streamId,
1971
+ () => abort.abort()
1972
+ );
1973
+ let stream;
1974
+ try {
1975
+ stream = await chat(ai, {
1976
+ abortSignal: abort.signal,
1977
+ contextVariables: {
1978
+ controlPlane: this.#controlPlane,
1979
+ actor: { turn, thread, declaration }
1980
+ }
1981
+ });
1982
+ } finally {
1983
+ await setupCancellation[Symbol.asyncDispose]();
1984
+ }
1985
+ await this.#streams.persist(stream, turn.streamId, {
1986
+ preclaimed: true,
1987
+ onCancelDetected: () => abort.abort()
1988
+ });
1989
+ if (turn.kind === "continuation") {
1990
+ await this.#reconcileTerminalContinuation(turn);
1991
+ }
1992
+ await this.#controlPlane.projectTerminal(turn, thread);
1993
+ } finally {
1994
+ signal.removeEventListener("abort", onWorkerAbort);
1995
+ }
1996
+ }
1997
+ async #projectSkippedTerminalTurn(turn) {
1998
+ const status = await this.#streams.store.getStreamStatus(turn.streamId);
1999
+ if (status === "queued" || status === "running") return false;
2000
+ if (status === void 0 || turn.kind === "mailbox") return true;
2001
+ if (turn.kind === "continuation") {
2002
+ await this.#reconcileTerminalContinuation(turn);
2003
+ }
2004
+ const { thread } = await this.#controlPlane.resolve(turn);
2005
+ if (thread.lastTurnId === void 0 || thread.lastTurnId === turn.streamId) {
2006
+ await this.#controlPlane.recordLatestTurnIfCurrent(
2007
+ turn,
2008
+ turn.streamId,
2009
+ thread.lastTurnId
2010
+ );
2011
+ }
2012
+ await this.#controlPlane.projectTerminal(turn, thread);
2013
+ return true;
2014
+ }
2015
+ async #reconcileTerminalContinuation(turn) {
2016
+ const stream = await this.#streams.store.getStream(turn.streamId);
2017
+ if (stream?.status !== "completed" && stream?.status !== "failed" && stream?.status !== "cancelled") {
2018
+ return;
2019
+ }
2020
+ await this.#approvals.reconcileTerminalContinuation(
2021
+ turn,
2022
+ turn.streamId,
2023
+ stream.status,
2024
+ stream.error
2025
+ );
2026
+ }
2027
+ async #reopen(streamId) {
2028
+ const status = await this.#streams.store.getStreamStatus(streamId);
2029
+ if (status === "queued" || status === "running") return;
2030
+ await this.#streams.reopen(streamId);
2031
+ }
2032
+ async #prepareChain(turn, engine, communications) {
2033
+ if (turn.kind === "ask") {
399
2034
  engine.set(
2035
+ ...communications.map(
2036
+ (communication) => user(this.#mailboxInputMessage(communication))
2037
+ ),
400
2038
  user(turn.input),
401
2039
  assistant({ id: turn.streamId, role: "assistant", parts: [] })
402
2040
  );
403
2041
  await engine.save({ branch: true });
2042
+ } else if (turn.kind === "mailbox") {
2043
+ engine.set(
2044
+ ...communications.map(
2045
+ (communication) => user(this.#mailboxInputMessage(communication))
2046
+ ),
2047
+ assistant({ id: turn.streamId, role: "assistant", parts: [] })
2048
+ );
2049
+ await engine.save({ branch: true });
404
2050
  }
405
- const sandbox = await declaration.sandbox({
406
- chatId: turn.chatId,
407
- userId: turn.userId
2051
+ }
2052
+ async #prepareStepInput(turn, state) {
2053
+ const communications = turn.kind === "ask" && state.firstRequest ? await this.#mailbox.drainLeadingQueueOnly(turn) : await this.#mailbox.drain(turn);
2054
+ state.firstRequest = false;
2055
+ return communications.length === 0 ? void 0 : communications.map(
2056
+ (communication) => this.#mailboxInputMessage(communication)
2057
+ );
2058
+ }
2059
+ #engineFor({ chatId, userId }) {
2060
+ return new ContextEngine2({ store: this.#store, chatId, userId });
2061
+ }
2062
+ #mailboxInputMessage(communication) {
2063
+ return {
2064
+ id: crypto.randomUUID(),
2065
+ role: "user",
2066
+ parts: [
2067
+ {
2068
+ type: "text",
2069
+ text: this.#renderInterAgentCommunication(communication)
2070
+ }
2071
+ ],
2072
+ metadata: { interAgentCommunication: communication }
2073
+ };
2074
+ }
2075
+ #renderInterAgentCommunication(communication) {
2076
+ const recipientPath = communication.metadata?.recipientPath;
2077
+ const authorPath = communication.metadata?.authorPath;
2078
+ const taskName = typeof recipientPath === "string" ? recipientPath : communication.recipient.chatId;
2079
+ const sender = typeof authorPath === "string" ? authorPath : communication.author.chatId;
2080
+ return `Message Type: ${communication.type}
2081
+ Task name: ${taskName}
2082
+ Sender: ${sender}
2083
+ Payload:
2084
+ ${communication.content}`;
2085
+ }
2086
+ };
2087
+
2088
+ // packages/experimental/src/zukhruf/runtime/approval-controller.ts
2089
+ import {
2090
+ getToolName,
2091
+ isToolUIPart
2092
+ } from "ai";
2093
+ import {
2094
+ ContextEngine as ContextEngine3,
2095
+ assistant as assistant2
2096
+ } from "@deepagents/context";
2097
+
2098
+ // packages/experimental/src/zukhruf/runtime/approval-job-id.ts
2099
+ import { v5 as uuidv55 } from "uuid";
2100
+ function approvalJobId(conversation, approvalId) {
2101
+ return uuidv55(`approval:${approvalId}`, conversationNamespace(conversation));
2102
+ }
2103
+
2104
+ // packages/experimental/src/zukhruf/runtime/approval-controller.ts
2105
+ var ApprovalController = class _ApprovalController {
2106
+ static #settledToolStates = /* @__PURE__ */ new Set([
2107
+ "output-available",
2108
+ "output-error",
2109
+ "output-denied"
2110
+ ]);
2111
+ #store;
2112
+ #queue;
2113
+ constructor(options) {
2114
+ this.#store = options.store;
2115
+ this.#queue = options.queue;
2116
+ }
2117
+ isPaused(message) {
2118
+ return message?.role === "assistant" && this.#pendingToolPart(message) !== void 0;
2119
+ }
2120
+ approve(conversation, input) {
2121
+ return this.#respond("approve", conversation, input.toolCallId, {
2122
+ approved: true
408
2123
  });
409
- const ai = agent({
410
- name: declaration.name,
411
- model: declaration.model,
412
- sandbox,
413
- context: engine,
414
- tools: declaration.tools
2124
+ }
2125
+ deny(conversation, input) {
2126
+ return this.#respond("deny", conversation, input.toolCallId, {
2127
+ approved: false,
2128
+ reason: input.reason
415
2129
  });
416
- const abort = new AbortController();
417
- const onWorkerAbort = () => abort.abort();
418
- signal.addEventListener("abort", onWorkerAbort, { once: true });
419
- try {
420
- const stream = await chat(ai, { abortSignal: abort.signal });
421
- await manager.persist(stream, turn.streamId, {
422
- onCancelDetected: () => abort.abort()
423
- });
424
- } finally {
425
- signal.removeEventListener("abort", onWorkerAbort);
426
- }
427
2130
  }
428
- async function respondToApproval(conversation, toolCallId, approval) {
429
- const engine = engineFor(conversation);
2131
+ async settleDeniedApprovals(conversation, streamId) {
2132
+ const engine = this.#engineFor(conversation);
430
2133
  const head = (await engine.getMessages()).at(-1);
431
- if (head?.role !== "assistant") {
432
- throw new Error(
433
- "approve: no paused turn \u2014 the chain head is not an assistant message"
434
- );
435
- }
436
- const part = head.parts.find(
437
- (p) => isToolUIPart(p) && p.toolCallId === toolCallId
2134
+ if (head?.role !== "assistant" || head.id !== streamId) return;
2135
+ const hasDenied = head.parts.some(
2136
+ (part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === false
438
2137
  );
439
- if (!part || !isToolUIPart(part)) {
440
- throw new Error(
441
- `approve: no tool call "${toolCallId}" on the paused turn`
2138
+ if (!hasDenied) return;
2139
+ const updated = {
2140
+ ...head,
2141
+ parts: head.parts.map((part) => {
2142
+ if (!isToolUIPart(part) || part.state !== "approval-responded" || part.approval.approved !== false) {
2143
+ return part;
2144
+ }
2145
+ const settled = {
2146
+ ...part,
2147
+ state: "output-denied",
2148
+ approval: { ...part.approval, approved: false }
2149
+ };
2150
+ return settled;
2151
+ })
2152
+ };
2153
+ await engine.continue(assistant2(updated));
2154
+ }
2155
+ async settleFailedApprovals(conversation, streamId, error) {
2156
+ const engine = this.#engineFor(conversation);
2157
+ const head = (await engine.getMessages()).at(-1);
2158
+ if (head?.role !== "assistant" || head.id !== streamId) return;
2159
+ const hasResponded = head.parts.some(
2160
+ (part) => isToolUIPart(part) && part.state === "approval-responded"
2161
+ );
2162
+ if (!hasResponded) return;
2163
+ const updated = {
2164
+ ...head,
2165
+ parts: head.parts.map((part) => {
2166
+ if (!isToolUIPart(part) || part.state !== "approval-responded") {
2167
+ return part;
2168
+ }
2169
+ if (part.approval.approved === false) {
2170
+ const denied = {
2171
+ ...part,
2172
+ state: "output-denied",
2173
+ approval: { ...part.approval, approved: false }
2174
+ };
2175
+ return denied;
2176
+ }
2177
+ const failed = {
2178
+ ...part,
2179
+ state: "output-error",
2180
+ errorText: error,
2181
+ approval: { ...part.approval, approved: true }
2182
+ };
2183
+ return failed;
2184
+ })
2185
+ };
2186
+ await engine.continue(assistant2(updated));
2187
+ }
2188
+ async reconcileTerminalContinuation(conversation, streamId, status, error) {
2189
+ if (status === "completed") {
2190
+ await this.settleDeniedApprovals(conversation, streamId);
2191
+ } else {
2192
+ await this.settleFailedApprovals(
2193
+ conversation,
2194
+ streamId,
2195
+ error ?? `approval continuation ${status}`
442
2196
  );
443
2197
  }
444
- if (part.state !== "approval-requested") {
445
- return { id: head.id, stream: manager.watch(head.id) };
446
- }
2198
+ await this.#queue.resumeParked(conversation.chatId);
2199
+ }
2200
+ async retryIdempotentContinuation(conversation, streamId, tools) {
2201
+ const head = (await this.#engineFor(conversation).getMessages()).at(-1);
2202
+ if (head?.role !== "assistant" || head.id !== streamId) return false;
2203
+ const approved = head.parts.filter(
2204
+ (part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === true
2205
+ );
2206
+ const retryable = approved.length > 0 && approved.every((part) => {
2207
+ const tool7 = tools[getToolName(part)];
2208
+ return tool7?.recovery === "idempotent" && typeof tool7.execute === "function";
2209
+ });
2210
+ if (!retryable) return false;
2211
+ await this.#queue.push({
2212
+ kind: "continuation",
2213
+ streamId,
2214
+ chatId: conversation.chatId,
2215
+ userId: conversation.userId,
2216
+ recovery: "idempotent"
2217
+ });
2218
+ return true;
2219
+ }
2220
+ async applyDecision(turn) {
2221
+ const engine = this.#engineFor(turn);
2222
+ const head = (await engine.getMessages()).at(-1);
2223
+ if (head?.role !== "assistant" || head.id !== turn.streamId) return false;
2224
+ const part = this.#findToolPart(head, turn.toolCallId);
2225
+ if (part?.approval?.id !== turn.approvalId) return false;
2226
+ if (part.approval.approved !== void 0) return false;
2227
+ if (part.state !== "approval-requested") return false;
447
2228
  const responded = {
448
2229
  ...part,
449
2230
  state: "approval-responded",
450
- approval: { ...part.approval, ...approval }
2231
+ approval: { ...part.approval, ...turn.decision }
451
2232
  };
452
2233
  const updated = {
453
2234
  ...head,
454
- parts: head.parts.map((p) => p === part ? responded : p)
2235
+ parts: head.parts.map(
2236
+ (candidate) => candidate === part ? responded : candidate
2237
+ )
455
2238
  };
456
- await engine.continue(assistant(updated));
457
- try {
458
- await manager.reopen(head.id);
459
- } catch {
460
- return { id: head.id, stream: manager.watch(head.id) };
2239
+ await engine.continue(assistant2(updated));
2240
+ return !this.#hasUnansweredApprovals(updated);
2241
+ }
2242
+ async recoverUnstartedContinuation(turn, streamId) {
2243
+ if (turn.kind === "approval") await this.applyDecision(turn);
2244
+ const head = (await this.#engineFor(turn).getMessages()).at(-1);
2245
+ if (head?.role !== "assistant" || head.id !== streamId || this.#hasUnansweredApprovals(head) || !head.parts.some(
2246
+ (part) => isToolUIPart(part) && part.state === "approval-responded"
2247
+ )) {
2248
+ return false;
461
2249
  }
462
- await queue.push({
2250
+ await this.#queue.push({
463
2251
  kind: "continuation",
2252
+ streamId,
2253
+ chatId: turn.chatId,
2254
+ userId: turn.userId,
2255
+ recovery: "handoff"
2256
+ });
2257
+ return true;
2258
+ }
2259
+ async #respond(operation, conversation, toolCallId, approval) {
2260
+ const head = (await this.#engineFor(conversation).getMessages()).at(-1);
2261
+ if (head?.role !== "assistant") {
2262
+ throw new Error(
2263
+ `ApprovalController.${operation}: no paused turn \u2014 the chain head is not an assistant message`
2264
+ );
2265
+ }
2266
+ const part = this.#findToolPart(head, toolCallId);
2267
+ if (!part) {
2268
+ throw new Error(
2269
+ `ApprovalController.${operation}: no tool call "${toolCallId}" on the paused turn`
2270
+ );
2271
+ }
2272
+ if (!part.approval) {
2273
+ throw new Error(
2274
+ `ApprovalController.${operation}: tool call "${toolCallId}" is not awaiting approval`
2275
+ );
2276
+ }
2277
+ const jobId = approvalJobId(conversation, part.approval.id);
2278
+ if (part.approval.approved !== void 0) {
2279
+ if (part.approval.approved !== approval.approved) {
2280
+ throw new Error(
2281
+ `ApprovalController.${operation}: approval already answered with a different decision`
2282
+ );
2283
+ }
2284
+ return { id: head.id, jobId, status: "already-applied" };
2285
+ }
2286
+ if (part.state !== "approval-requested") {
2287
+ throw new Error(
2288
+ `ApprovalController.${operation}: tool call "${toolCallId}" is not awaiting approval`
2289
+ );
2290
+ }
2291
+ const result = await this.#queue.push({
2292
+ kind: "approval",
464
2293
  streamId: head.id,
465
2294
  chatId: conversation.chatId,
2295
+ userId: conversation.userId,
2296
+ toolCallId,
2297
+ approvalId: part.approval.id,
2298
+ decision: approval
2299
+ });
2300
+ return {
2301
+ id: head.id,
2302
+ jobId,
2303
+ status: result.inserted ? "queued" : "already-queued"
2304
+ };
2305
+ }
2306
+ #pendingToolPart(message) {
2307
+ return message.parts.find(
2308
+ (part) => isToolUIPart(part) && !_ApprovalController.#settledToolStates.has(part.state)
2309
+ );
2310
+ }
2311
+ #hasUnansweredApprovals(message) {
2312
+ return message.parts.some(
2313
+ (part) => isToolUIPart(part) && part.state === "approval-requested"
2314
+ );
2315
+ }
2316
+ #findToolPart(message, toolCallId) {
2317
+ return message.parts.find(
2318
+ (part) => isToolUIPart(part) && part.toolCallId === toolCallId
2319
+ );
2320
+ }
2321
+ #engineFor({ chatId, userId }) {
2322
+ return new ContextEngine3({ store: this.#store, chatId, userId });
2323
+ }
2324
+ };
2325
+
2326
+ // packages/experimental/src/zukhruf/runtime/agent-runtime.ts
2327
+ var AgentObservation = class {
2328
+ engine;
2329
+ #conversation;
2330
+ #store;
2331
+ #streams;
2332
+ constructor(conversation, store, streams) {
2333
+ this.engine = new ContextEngine4({
2334
+ store,
2335
+ chatId: conversation.chatId,
466
2336
  userId: conversation.userId
467
2337
  });
468
- await queue.resumeParked(conversation.chatId);
469
- return { id: head.id, stream: manager.watch(head.id) };
2338
+ this.#conversation = conversation;
2339
+ this.#store = store;
2340
+ this.#streams = streams;
470
2341
  }
471
- return {
472
- async enqueue({ chatId, userId }, turn) {
473
- if (!turn.id) {
474
- throw new Error(
475
- "enqueue: turn id is required \u2014 it names the ask, making retries idempotent"
2342
+ async resume() {
2343
+ const id = await this.#headStreamId();
2344
+ if (!id) return null;
2345
+ AgentTurnId.assertOwner(this.#conversation, id);
2346
+ const status = await this.#streams.store.getStreamStatus(id);
2347
+ return status ? this.#streams.watch(id) : null;
2348
+ }
2349
+ async cancel(streamId) {
2350
+ const chat2 = await this.#store.getChat(this.#conversation.chatId);
2351
+ if (chat2 && chat2.userId !== this.#conversation.userId) {
2352
+ throw new Error(
2353
+ `chat "${this.#conversation.chatId}" belongs to user "${chat2.userId}", not "${this.#conversation.userId}"`
2354
+ );
2355
+ }
2356
+ const id = streamId ?? await this.#headStreamId();
2357
+ if (!id) return;
2358
+ AgentTurnId.assertOwner(this.#conversation, id);
2359
+ const status = await this.#streams.store.getStreamStatus(id);
2360
+ if (status === "queued" || status === "running") {
2361
+ await this.#streams.cancel(id);
2362
+ }
2363
+ }
2364
+ async #headStreamId() {
2365
+ const head = await this.engine.headMessage();
2366
+ return head?.name === "assistant" ? head.id : void 0;
2367
+ }
2368
+ };
2369
+ var AgentRuntime = class {
2370
+ #store;
2371
+ #queue;
2372
+ #streams;
2373
+ #mailbox;
2374
+ #directory;
2375
+ #controlPlane;
2376
+ #approvals;
2377
+ #executor;
2378
+ constructor(root, options) {
2379
+ const multiAgentV2 = resolveMultiAgentV2HostConfig(options.multiAgentV2);
2380
+ const declarations = new AgentDeclarationRegistry(root);
2381
+ const directory = new AgentDirectory(options.store);
2382
+ const streams = options.streams;
2383
+ const mailbox = new MailboxCoordinator({
2384
+ store: options.mailboxStore,
2385
+ queue: options.queue,
2386
+ streams
2387
+ });
2388
+ const approvals = new ApprovalController({
2389
+ store: options.store,
2390
+ queue: options.queue
2391
+ });
2392
+ const statusProjector = new AgentStatusProjector({
2393
+ store: options.store,
2394
+ streams,
2395
+ queue: options.queue,
2396
+ mailbox,
2397
+ directory,
2398
+ approvals
2399
+ });
2400
+ const historyForker = new AgentHistoryForker(options.store);
2401
+ const controlPlane = new AgentControlPlane({
2402
+ root,
2403
+ streams,
2404
+ queue: options.queue,
2405
+ mailbox,
2406
+ declarations,
2407
+ directory,
2408
+ statusProjector,
2409
+ historyForker
2410
+ });
2411
+ this.#store = options.store;
2412
+ this.#queue = options.queue;
2413
+ this.#streams = streams;
2414
+ this.#mailbox = mailbox;
2415
+ this.#directory = directory;
2416
+ this.#controlPlane = controlPlane;
2417
+ this.#approvals = approvals;
2418
+ this.#executor = new AgentTurnExecutor({
2419
+ store: options.store,
2420
+ streams,
2421
+ controlPlane,
2422
+ mailbox,
2423
+ approvals,
2424
+ multiAgentV2
2425
+ });
2426
+ }
2427
+ async enqueue(conversation, turn) {
2428
+ const streamId = await this.#controlPlane.enqueue(conversation, turn);
2429
+ return { id: streamId, stream: this.#streams.watch(streamId) };
2430
+ }
2431
+ async deliver(communication, mode) {
2432
+ await this.#directory.assertOwnerIfExists(communication.recipient);
2433
+ await this.#mailbox.deliver(communication, mode);
2434
+ }
2435
+ approve(conversation, input) {
2436
+ return this.#approvals.approve(conversation, input);
2437
+ }
2438
+ deny(conversation, input) {
2439
+ return this.#approvals.deny(conversation, input);
2440
+ }
2441
+ observe(conversation) {
2442
+ return new AgentObservation(conversation, this.#store, this.#streams);
2443
+ }
2444
+ work(options) {
2445
+ return this.#queue.consume(this.#executor.execute.bind(this.#executor), {
2446
+ concurrency: options?.concurrency,
2447
+ onOrphaned: this.#onOrphaned.bind(this)
2448
+ });
2449
+ }
2450
+ async #onOrphaned(turn, error) {
2451
+ try {
2452
+ let stream = await this.#streams.store.getStream(turn.streamId);
2453
+ const firstReconciliation = stream?.status === "queued" || stream?.status === "running";
2454
+ if (firstReconciliation) {
2455
+ await this.#streams.store.updateStreamStatus(turn.streamId, "failed", {
2456
+ error
2457
+ });
2458
+ stream = await this.#streams.store.getStream(turn.streamId);
2459
+ }
2460
+ let declaration;
2461
+ if ((turn.kind === "approval" || turn.kind === "continuation" && turn.recovery !== "idempotent") && stream?.status === "failed") {
2462
+ try {
2463
+ ({ declaration } = await this.#controlPlane.resolve(turn));
2464
+ } catch {
2465
+ }
2466
+ }
2467
+ if (declaration !== void 0 && await this.#approvals.retryIdempotentContinuation(
2468
+ turn,
2469
+ turn.streamId,
2470
+ declaration.tools ?? {}
2471
+ )) {
2472
+ return;
2473
+ }
2474
+ if ((turn.kind === "approval" || turn.kind === "continuation") && stream?.status === "completed" && await this.#approvals.recoverUnstartedContinuation(
2475
+ turn,
2476
+ turn.streamId
2477
+ )) {
2478
+ return;
2479
+ }
2480
+ stream = await this.#streams.store.getStream(turn.streamId);
2481
+ if ((turn.kind === "approval" || turn.kind === "continuation") && (stream?.status === "completed" || stream?.status === "failed" || stream?.status === "cancelled")) {
2482
+ await this.#approvals.reconcileTerminalContinuation(
2483
+ turn,
2484
+ turn.streamId,
2485
+ stream.status,
2486
+ stream.error ?? error
476
2487
  );
477
2488
  }
478
- await manager.register(turn.id);
479
- await queue.push({
480
- kind: "ask",
481
- streamId: turn.id,
482
- chatId,
483
- userId,
484
- input: turn.input
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;
2489
+ const { thread } = await this.#controlPlane.resolve(turn);
2490
+ if (thread.lastTurnId === void 0 || thread.lastTurnId === turn.streamId) {
2491
+ await this.#controlPlane.recordLatestTurnIfCurrent(
2492
+ turn,
2493
+ turn.streamId,
2494
+ thread.lastTurnId
2495
+ );
504
2496
  }
505
- return {
506
- engine,
507
- async resume() {
508
- const id = await headStreamId();
509
- if (!id) return null;
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
- }
2497
+ await this.#controlPlane.projectTerminal(turn, thread);
2498
+ } finally {
2499
+ try {
2500
+ if (turn.kind === "approval" || turn.kind === "continuation") {
2501
+ await this.#queue.resumeParked(turn.chatId);
520
2502
  }
2503
+ } finally {
2504
+ await this.#mailbox.endTurn(turn);
2505
+ }
2506
+ }
2507
+ }
2508
+ };
2509
+
2510
+ // packages/experimental/src/zukhruf/instructions.ts
2511
+ function defineInstructions(...fragments) {
2512
+ return fragments;
2513
+ }
2514
+
2515
+ // packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
2516
+ import { DatabaseSync } from "node:sqlite";
2517
+
2518
+ // packages/experimental/src/zukhruf/mailbox/store.ts
2519
+ var MailboxStore = class {
2520
+ };
2521
+
2522
+ // packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
2523
+ var DDL = `
2524
+ PRAGMA journal_mode = WAL;
2525
+ PRAGMA synchronous = NORMAL;
2526
+
2527
+ CREATE TABLE IF NOT EXISTS zukhruf_mailbox_items (
2528
+ sequence INTEGER PRIMARY KEY AUTOINCREMENT,
2529
+ recipient_chat_id TEXT NOT NULL,
2530
+ recipient_user_id TEXT NOT NULL,
2531
+ communication TEXT NOT NULL
2532
+ );
2533
+
2534
+ CREATE TABLE IF NOT EXISTS zukhruf_mailbox_activity (
2535
+ recipient_chat_id TEXT NOT NULL,
2536
+ recipient_user_id TEXT NOT NULL,
2537
+ turn_id TEXT NOT NULL,
2538
+ PRIMARY KEY (recipient_chat_id, recipient_user_id)
2539
+ );
2540
+
2541
+ CREATE TABLE IF NOT EXISTS zukhruf_mailbox_consumed_terminal_ids (
2542
+ communication_id TEXT PRIMARY KEY
2543
+ );
2544
+
2545
+ CREATE INDEX IF NOT EXISTS zukhruf_mailbox_recipient_sequence
2546
+ ON zukhruf_mailbox_items (
2547
+ recipient_chat_id,
2548
+ recipient_user_id,
2549
+ sequence
2550
+ );
2551
+
2552
+ CREATE UNIQUE INDEX IF NOT EXISTS zukhruf_mailbox_communication_id
2553
+ ON zukhruf_mailbox_items (
2554
+ json_extract(communication, '$.id')
2555
+ );
2556
+ `;
2557
+ var BUSY_TIMEOUT_MS = 5e3;
2558
+ var SqliteMailboxStore = class extends MailboxStore {
2559
+ #database;
2560
+ #closed = false;
2561
+ constructor(path) {
2562
+ super();
2563
+ this.#database = new DatabaseSync(path, { timeout: BUSY_TIMEOUT_MS });
2564
+ this.#database.exec(DDL);
2565
+ }
2566
+ async beginTurn(recipient, turnId) {
2567
+ this.#transaction(() => {
2568
+ this.#database.prepare(
2569
+ `INSERT INTO zukhruf_mailbox_activity (
2570
+ recipient_chat_id,
2571
+ recipient_user_id,
2572
+ turn_id
2573
+ ) VALUES (?, ?, ?)
2574
+ ON CONFLICT (recipient_chat_id, recipient_user_id)
2575
+ DO UPDATE SET turn_id = excluded.turn_id`
2576
+ ).run(recipient.chatId, recipient.userId, turnId);
2577
+ });
2578
+ }
2579
+ async enqueue(communication) {
2580
+ return this.#transaction(() => {
2581
+ const consumedTerminal = communication.type === InterAgentCommunicationType.FinalAnswer && this.#hasConsumedTerminal(communication.id);
2582
+ if (!consumedTerminal) {
2583
+ this.#database.prepare(
2584
+ `INSERT OR IGNORE INTO zukhruf_mailbox_items (
2585
+ recipient_chat_id,
2586
+ recipient_user_id,
2587
+ communication
2588
+ ) VALUES (?, ?, ?)`
2589
+ ).run(
2590
+ communication.recipient.chatId,
2591
+ communication.recipient.userId,
2592
+ JSON.stringify(communication)
2593
+ );
2594
+ }
2595
+ return {
2596
+ recipientActive: this.#isTurnActive(communication.recipient)
521
2597
  };
522
- },
523
- async work(options2) {
524
- return queue.consume(executeTurn, {
525
- concurrency: options2?.concurrency,
526
- onOrphaned: async (turn, error) => {
527
- const status = await streamStore.getStreamStatus(turn.streamId);
528
- if (status === "queued" || status === "running") {
529
- await streamStore.updateStreamStatus(turn.streamId, "failed", {
530
- error
531
- });
2598
+ });
2599
+ }
2600
+ async endTurn(recipient, turnId) {
2601
+ return this.#transaction(() => {
2602
+ const result = this.#database.prepare(
2603
+ `DELETE FROM zukhruf_mailbox_activity
2604
+ WHERE recipient_chat_id = ?
2605
+ AND recipient_user_id = ?
2606
+ AND turn_id = ?`
2607
+ ).run(recipient.chatId, recipient.userId, turnId);
2608
+ return {
2609
+ hasPending: this.#hasPending(recipient),
2610
+ turnEnded: result.changes > 0
2611
+ };
2612
+ });
2613
+ }
2614
+ async hasPending(recipient) {
2615
+ return this.#hasPending(recipient);
2616
+ }
2617
+ #hasPending(recipient) {
2618
+ const row = this.#database.prepare(
2619
+ `SELECT 1
2620
+ FROM zukhruf_mailbox_items
2621
+ WHERE recipient_chat_id = ?
2622
+ AND recipient_user_id = ?
2623
+ LIMIT 1`
2624
+ ).get(recipient.chatId, recipient.userId);
2625
+ return row !== void 0;
2626
+ }
2627
+ #isTurnActive(recipient) {
2628
+ const row = this.#database.prepare(
2629
+ `SELECT 1
2630
+ FROM zukhruf_mailbox_activity
2631
+ WHERE recipient_chat_id = ?
2632
+ AND recipient_user_id = ?
2633
+ LIMIT 1`
2634
+ ).get(recipient.chatId, recipient.userId);
2635
+ return row !== void 0;
2636
+ }
2637
+ #hasConsumedTerminal(communicationId) {
2638
+ const row = this.#database.prepare(
2639
+ `SELECT 1
2640
+ FROM zukhruf_mailbox_consumed_terminal_ids
2641
+ WHERE communication_id = ?
2642
+ LIMIT 1`
2643
+ ).get(communicationId);
2644
+ return row !== void 0;
2645
+ }
2646
+ async drain(recipient) {
2647
+ return this.#drain(recipient, false);
2648
+ }
2649
+ async drainLeadingQueueOnly(recipient) {
2650
+ return this.#drain(recipient, true);
2651
+ }
2652
+ #drain(recipient, leadingQueueOnly) {
2653
+ return this.#transaction(() => {
2654
+ const rows = this.#database.prepare(
2655
+ `SELECT sequence, communication
2656
+ FROM zukhruf_mailbox_items
2657
+ WHERE recipient_chat_id = ?
2658
+ AND recipient_user_id = ?
2659
+ ORDER BY sequence`
2660
+ ).all(recipient.chatId, recipient.userId);
2661
+ const items = rows.map((row) => ({
2662
+ sequence: row.sequence,
2663
+ communication: JSON.parse(row.communication)
2664
+ }));
2665
+ const firstTrigger = leadingQueueOnly ? items.findIndex(({ communication }) => communication.triggerTurn) : -1;
2666
+ const consumed = firstTrigger === -1 ? items : items.slice(0, firstTrigger);
2667
+ const lastConsumed = consumed.at(-1);
2668
+ if (lastConsumed) {
2669
+ const tombstone = this.#database.prepare(
2670
+ `INSERT OR IGNORE
2671
+ INTO zukhruf_mailbox_consumed_terminal_ids (communication_id)
2672
+ VALUES (?)`
2673
+ );
2674
+ for (const { communication } of consumed) {
2675
+ if (communication.type === InterAgentCommunicationType.FinalAnswer) {
2676
+ tombstone.run(communication.id);
532
2677
  }
533
2678
  }
534
- });
2679
+ this.#database.prepare(
2680
+ `DELETE FROM zukhruf_mailbox_items
2681
+ WHERE recipient_chat_id = ?
2682
+ AND recipient_user_id = ?
2683
+ AND sequence <= ?`
2684
+ ).run(recipient.chatId, recipient.userId, lastConsumed.sequence);
2685
+ }
2686
+ return consumed.map(({ communication }) => communication);
2687
+ });
2688
+ }
2689
+ #transaction(operation) {
2690
+ this.#database.exec("BEGIN IMMEDIATE");
2691
+ try {
2692
+ const result = operation();
2693
+ this.#database.exec("COMMIT");
2694
+ return result;
2695
+ } catch (error) {
2696
+ try {
2697
+ this.#database.exec("ROLLBACK");
2698
+ } catch {
2699
+ }
2700
+ throw error;
535
2701
  }
536
- };
537
- }
2702
+ }
2703
+ close() {
2704
+ if (this.#closed) return;
2705
+ this.#closed = true;
2706
+ this.#database.close();
2707
+ }
2708
+ [Symbol.dispose]() {
2709
+ this.close();
2710
+ }
2711
+ };
2712
+
2713
+ // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
2714
+ import { v7 as uuidv7 } from "uuid";
538
2715
 
539
2716
  // packages/experimental/src/zukhruf/queue/turn-queue.ts
540
2717
  var TurnQueue = class {
541
2718
  };
542
2719
 
543
2720
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
544
- import { v7 as uuidv7 } from "uuid";
545
- var PgBossTurnQueue = class extends TurnQueue {
2721
+ var MAX_TIMEOUT_MS = 2147483647;
2722
+ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
546
2723
  #boss;
547
2724
  #queue;
2725
+ #schema;
2726
+ #schemaConfigurationError;
2727
+ #table;
548
2728
  #expireInSeconds;
2729
+ #cancelIntentTtlMs;
549
2730
  #heartbeatSeconds;
550
2731
  #pollingIntervalSeconds;
2732
+ #active = /* @__PURE__ */ new Map();
2733
+ #cancelIntents = /* @__PURE__ */ new Map();
2734
+ #cancelIntentExpiryTimer;
551
2735
  constructor(boss, options = {}) {
552
2736
  super();
553
2737
  this.#boss = boss;
554
2738
  this.#queue = options.queue ?? "zukhruf-turns";
2739
+ const configuredSchema = boss.getDb().config?.schema;
2740
+ const bossSchema = typeof configuredSchema === "string" ? configuredSchema : void 0;
2741
+ this.#schema = options.schema ?? bossSchema ?? "pgboss";
2742
+ if (options.schema === void 0 && bossSchema === void 0) {
2743
+ this.#schemaConfigurationError = "PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema";
2744
+ } else if (options.schema !== void 0 && bossSchema !== void 0 && options.schema !== bossSchema) {
2745
+ this.#schemaConfigurationError = `PgBossTurnQueue schema "${options.schema}" does not match the PgBoss schema "${bossSchema}"`;
2746
+ }
555
2747
  this.#expireInSeconds = options.expireInSeconds ?? 3600;
2748
+ this.#cancelIntentTtlMs = this.#expireInSeconds * 1e3;
2749
+ if (!Number.isFinite(this.#expireInSeconds) || this.#expireInSeconds <= 0 || !Number.isSafeInteger(this.#cancelIntentTtlMs) || this.#cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()) {
2750
+ throw new Error(
2751
+ "PgBossTurnQueue expireInSeconds must be a finite positive duration"
2752
+ );
2753
+ }
556
2754
  this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;
557
2755
  this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;
558
2756
  }
@@ -563,10 +2761,14 @@ var PgBossTurnQueue = class extends TurnQueue {
563
2761
  return `${this.#queue}-dead`;
564
2762
  }
565
2763
  async initialize() {
2764
+ if (this.#schemaConfigurationError) {
2765
+ throw new Error(this.#schemaConfigurationError);
2766
+ }
566
2767
  if (!await this.#boss.getQueue(this.deadLetterQueue)) {
567
2768
  await this.#boss.createQueue(this.deadLetterQueue);
568
2769
  }
569
- if (!await this.#boss.getQueue(this.#queue)) {
2770
+ let queue = await this.#boss.getQueue(this.#queue);
2771
+ if (!queue) {
570
2772
  await this.#boss.createQueue(this.#queue, {
571
2773
  policy: "key_strict_fifo",
572
2774
  retryLimit: 0,
@@ -575,35 +2777,111 @@ var PgBossTurnQueue = class extends TurnQueue {
575
2777
  deleteAfterSeconds: 0,
576
2778
  deadLetter: this.deadLetterQueue
577
2779
  });
2780
+ queue = await this.#boss.getQueue(this.#queue);
2781
+ }
2782
+ if (!queue) throw new Error(`Queue "${this.#queue}" was not initialized`);
2783
+ this.#table = queue.table;
2784
+ try {
2785
+ const catalog = await this.#boss.getDb().executeSql(
2786
+ `SELECT table_name AS "table"
2787
+ FROM ${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}."queue"
2788
+ WHERE name = $1`,
2789
+ [this.#queue]
2790
+ );
2791
+ if (catalog.rows.length !== 1 || catalog.rows[0].table !== this.#table) {
2792
+ throw new Error("queue catalog does not match");
2793
+ }
2794
+ await this.#boss.getDb().executeSql(`SELECT 1 FROM ${this.#relation()} WHERE false`);
2795
+ } catch (cause) {
2796
+ throw new Error(
2797
+ `PgBossTurnQueue schema "${this.#schema}" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,
2798
+ { cause }
2799
+ );
578
2800
  }
579
2801
  }
580
2802
  async push(turn) {
581
- await this.#boss.send(this.#queue, turn, {
582
- id: uuidv7(),
2803
+ const jobId = turn.kind === "approval" ? approvalJobId(turn, turn.approvalId) : uuidv7();
2804
+ const inserted = await this.#boss.send(this.#queue, turn, {
2805
+ id: jobId,
583
2806
  singletonKey: turn.chatId,
584
- priority: turn.kind === "continuation" ? 1 : 0
2807
+ group: { id: turn.chatId },
2808
+ priority: turn.kind === "approval" || turn.kind === "continuation" ? 1 : 0
2809
+ });
2810
+ if (inserted === null && turn.kind !== "approval") {
2811
+ throw new Error(`PgBossTurnQueue job id collision: ${jobId}`);
2812
+ }
2813
+ return { jobId, inserted: inserted !== null };
2814
+ }
2815
+ async getTurnActivity(conversation) {
2816
+ const jobs = await this.#boss.findJobs(this.#queue, {
2817
+ key: conversation.chatId
2818
+ });
2819
+ const conversationJobs = jobs.filter(
2820
+ (job) => job.data.userId === conversation.userId && (job.state === "created" || job.state === "retry" || job.state === "active")
2821
+ );
2822
+ if (conversationJobs.some((job) => job.state === "active")) {
2823
+ return "running";
2824
+ }
2825
+ return conversationJobs.length > 0 ? "queued" : "idle";
2826
+ }
2827
+ async getCurrentTurn(conversation) {
2828
+ const jobs = await this.#boss.findJobs(this.#queue, {
2829
+ key: conversation.chatId
2830
+ });
2831
+ return jobs.filter(
2832
+ (job) => job.data.userId === conversation.userId && (job.state === "active" || job.state === "created" || job.state === "retry")
2833
+ ).sort(_PgBossTurnQueue.#interruptOrder)[0]?.data;
2834
+ }
2835
+ async cancel(streamId) {
2836
+ this.#rememberCancelIntent(streamId);
2837
+ this.#abortLocal(streamId);
2838
+ const jobs = await this.#boss.findJobs(this.#queue, {
2839
+ data: { streamId }
2840
+ });
2841
+ const queued = jobs.filter((job) => job.state === "created" || job.state === "retry").map((job) => job.id);
2842
+ if (queued.length > 0) await this.#deleteIfStillQueued(queued);
2843
+ this.#abortLocal(streamId);
2844
+ const remaining = await this.#boss.findJobs(this.#queue, {
2845
+ data: { streamId }
585
2846
  });
2847
+ if (!remaining.some((job) => job.state === "active")) {
2848
+ this.#forgetCancelIntent(streamId);
2849
+ }
586
2850
  }
587
2851
  async consume(handler, options) {
588
2852
  const turnWorkerId = await this.#boss.work(
589
2853
  this.#queue,
590
2854
  {
591
2855
  localConcurrency: options.concurrency ?? 1,
2856
+ groupConcurrency: 1,
592
2857
  pollingIntervalSeconds: this.#pollingIntervalSeconds
593
2858
  },
594
2859
  async ([job]) => {
595
2860
  let parked = false;
596
- await handler(job.data, {
597
- signal: job.signal,
598
- // Parking = self-cancel: a cancelled job stops blocking the chat's
599
- // key and is revived (original created_on, so original order) by
600
- // resumeParked(). The worker's completion of a cancelled job is a
601
- // clean no-op (probe-verified).
602
- park: async () => {
603
- parked = true;
604
- await this.#boss.cancel(this.#queue, job.id);
2861
+ const localAbort = new AbortController();
2862
+ const active = this.#active.get(job.data.streamId) ?? /* @__PURE__ */ new Set();
2863
+ active.add(localAbort);
2864
+ this.#active.set(job.data.streamId, active);
2865
+ if (this.#hasCancelIntent(job.data.streamId)) localAbort.abort();
2866
+ try {
2867
+ await handler(job.data, {
2868
+ signal: AbortSignal.any([job.signal, localAbort.signal]),
2869
+ // Parking = self-cancel: a cancelled job stops blocking the chat's
2870
+ // key and is revived (original created_on, so original order) by
2871
+ // resumeParked(). The worker's completion of a cancelled job is a
2872
+ // clean no-op (probe-verified).
2873
+ park: async () => {
2874
+ parked = true;
2875
+ await this.#boss.cancel(this.#queue, job.id);
2876
+ }
2877
+ });
2878
+ } finally {
2879
+ active.delete(localAbort);
2880
+ if (active.size === 0) {
2881
+ this.#active.delete(job.data.streamId);
2882
+ this.#forgetCancelIntent(job.data.streamId);
605
2883
  }
606
- });
2884
+ }
607
2885
  if (!parked) {
608
2886
  await this.#boss.deleteJob(this.#queue, job.id);
609
2887
  }
@@ -616,9 +2894,15 @@ var PgBossTurnQueue = class extends TurnQueue {
616
2894
  pollingIntervalSeconds: this.#pollingIntervalSeconds
617
2895
  },
618
2896
  async ([job]) => {
619
- await options.onOrphaned(job.data, orphanError(job.output));
620
- if (job.sourceId) {
621
- await this.#boss.deleteJob(this.#queue, job.sourceId);
2897
+ try {
2898
+ await options.onOrphaned(
2899
+ job.data,
2900
+ _PgBossTurnQueue.#orphanError(job.output)
2901
+ );
2902
+ } finally {
2903
+ if (job.sourceId) {
2904
+ await this.#boss.deleteJob(this.#queue, job.sourceId);
2905
+ }
622
2906
  }
623
2907
  }
624
2908
  );
@@ -636,12 +2920,174 @@ var PgBossTurnQueue = class extends TurnQueue {
636
2920
  await this.#boss.resume(this.#queue, parked);
637
2921
  }
638
2922
  }
2923
+ #abortLocal(streamId) {
2924
+ for (const controller of this.#active.get(streamId) ?? []) {
2925
+ controller.abort();
2926
+ }
2927
+ }
2928
+ #rememberCancelIntent(streamId) {
2929
+ this.#pruneCancelIntents();
2930
+ this.#cancelIntents.set(streamId, Date.now() + this.#cancelIntentTtlMs);
2931
+ this.#scheduleCancelIntentExpiry();
2932
+ }
2933
+ #hasCancelIntent(streamId) {
2934
+ this.#pruneCancelIntents();
2935
+ return this.#cancelIntents.has(streamId);
2936
+ }
2937
+ #pruneCancelIntents() {
2938
+ const now = Date.now();
2939
+ for (const [streamId, expiresAt] of this.#cancelIntents) {
2940
+ if (expiresAt <= now) this.#cancelIntents.delete(streamId);
2941
+ }
2942
+ this.#scheduleCancelIntentExpiry();
2943
+ }
2944
+ #forgetCancelIntent(streamId) {
2945
+ this.#cancelIntents.delete(streamId);
2946
+ this.#scheduleCancelIntentExpiry();
2947
+ }
2948
+ #scheduleCancelIntentExpiry() {
2949
+ if (this.#cancelIntentExpiryTimer !== void 0) {
2950
+ globalThis.clearTimeout(this.#cancelIntentExpiryTimer);
2951
+ this.#cancelIntentExpiryTimer = void 0;
2952
+ }
2953
+ let nextExpiry = Number.POSITIVE_INFINITY;
2954
+ for (const expiresAt of this.#cancelIntents.values()) {
2955
+ nextExpiry = Math.min(nextExpiry, expiresAt);
2956
+ }
2957
+ if (!Number.isFinite(nextExpiry)) return;
2958
+ const timer = globalThis.setTimeout(
2959
+ () => {
2960
+ if (this.#cancelIntentExpiryTimer !== timer) return;
2961
+ this.#cancelIntentExpiryTimer = void 0;
2962
+ this.#pruneCancelIntents();
2963
+ },
2964
+ Math.min(MAX_TIMEOUT_MS, Math.max(1, nextExpiry - Date.now()))
2965
+ );
2966
+ this.#cancelIntentExpiryTimer = timer;
2967
+ timer.unref?.();
2968
+ }
2969
+ async #deleteIfStillQueued(ids) {
2970
+ if (!this.#table) {
2971
+ throw new Error("PgBossTurnQueue.initialize() must run before cancel()");
2972
+ }
2973
+ await this.#boss.getDb().executeSql(
2974
+ `DELETE FROM ${this.#relation()}
2975
+ WHERE name = $1
2976
+ AND id = ANY($2::uuid[])
2977
+ AND state IN ('created', 'retry')`,
2978
+ [this.#queue, ids]
2979
+ );
2980
+ }
2981
+ #relation() {
2982
+ if (!this.#table) {
2983
+ throw new Error(
2984
+ "PgBossTurnQueue.initialize() must resolve its job table"
2985
+ );
2986
+ }
2987
+ return `${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}.${_PgBossTurnQueue.#quoteIdentifier(this.#table)}`;
2988
+ }
2989
+ static #quoteIdentifier(identifier) {
2990
+ return `"${identifier.replaceAll('"', '""')}"`;
2991
+ }
2992
+ static #orphanError(output) {
2993
+ if (output && "message" in output && typeof output.message === "string") {
2994
+ return output.message;
2995
+ }
2996
+ return output ? JSON.stringify(output) : "turn orphaned";
2997
+ }
2998
+ static #interruptOrder(left, right) {
2999
+ if (left.state === "active" && right.state !== "active") return -1;
3000
+ if (left.state !== "active" && right.state === "active") return 1;
3001
+ if (left.priority !== right.priority) return right.priority - left.priority;
3002
+ const created = left.createdOn.getTime() - right.createdOn.getTime();
3003
+ return created || left.id.localeCompare(right.id);
3004
+ }
639
3005
  };
640
- function orphanError(output) {
641
- if (output && "message" in output && typeof output.message === "string") {
642
- return output.message;
3006
+
3007
+ // packages/experimental/src/zukhruf/render-turn.ts
3008
+ import { styleText } from "node:util";
3009
+ var dim = (text) => styleText("dim", text);
3010
+ var red = (text) => styleText("red", text);
3011
+ function oneLine(value, max = 88) {
3012
+ const text = String(value ?? "").replaceAll(/\s+/g, " ").trim();
3013
+ return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
3014
+ }
3015
+ function describeToolCall(toolName, input) {
3016
+ const args = input ?? {};
3017
+ switch (toolName) {
3018
+ case "spawn_agent":
3019
+ return `\u21C4 spawn ${args.agent_type} "${args.task_name}" \u2014 ${args.message}`;
3020
+ case "send_message":
3021
+ return `\u21C4 mail ${args.target} \u2014 ${args.message}`;
3022
+ case "followup_task":
3023
+ return `\u21C4 follow-up ${args.target} \u2014 ${args.message}`;
3024
+ case "list_agents":
3025
+ return "\u21C4 list agents";
3026
+ default:
3027
+ return `\xB7 ${toolName}`;
3028
+ }
3029
+ }
3030
+ async function renderTurn(stream) {
3031
+ const toolNames = /* @__PURE__ */ new Map();
3032
+ let midText = false;
3033
+ let thinkingShown = false;
3034
+ const breakText = () => {
3035
+ if (midText) process.stdout.write("\n");
3036
+ midText = false;
3037
+ };
3038
+ for await (const chunk of stream) {
3039
+ switch (chunk.type) {
3040
+ case "reasoning-start":
3041
+ if (!thinkingShown) {
3042
+ console.log(dim("\u2026"));
3043
+ thinkingShown = true;
3044
+ }
3045
+ break;
3046
+ case "text-delta":
3047
+ process.stdout.write(chunk.delta);
3048
+ midText = true;
3049
+ break;
3050
+ case "text-end":
3051
+ breakText();
3052
+ break;
3053
+ case "tool-input-available":
3054
+ toolNames.set(chunk.toolCallId, chunk.toolName);
3055
+ breakText();
3056
+ console.log(dim(describeToolCall(chunk.toolName, chunk.input)));
3057
+ break;
3058
+ case "tool-output-error":
3059
+ breakText();
3060
+ console.log(
3061
+ red(
3062
+ `\u2717 ${toolNames.get(chunk.toolCallId) ?? "tool"}: ${oneLine(chunk.errorText)}`
3063
+ )
3064
+ );
3065
+ break;
3066
+ case "error":
3067
+ breakText();
3068
+ console.log(red(`\u2717 ${oneLine(chunk.errorText)}`));
3069
+ break;
3070
+ case "abort":
3071
+ breakText();
3072
+ console.log(dim("\xB7 turn aborted"));
3073
+ break;
3074
+ }
643
3075
  }
644
- return output ? JSON.stringify(output) : "turn orphaned";
3076
+ breakText();
3077
+ }
3078
+
3079
+ // packages/experimental/src/zukhruf/sandbox/define.ts
3080
+ import {
3081
+ createBashTool
3082
+ } from "@deepagents/context";
3083
+ function defineSandbox(createBackend, options) {
3084
+ return async (context) => createBashTool({ sandbox: await createBackend(context), ...options });
3085
+ }
3086
+
3087
+ // packages/experimental/src/zukhruf/tool.ts
3088
+ import { tool as tool6 } from "ai";
3089
+ function defineTool(definition) {
3090
+ return tool6(definition);
645
3091
  }
646
3092
  export {
647
3093
  coding_agent_reminders_exports as codingAgentReminders,