@deepagents/experimental 7.10.0 → 7.10.2

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 (65) hide show
  1. package/README.md +16 -4
  2. package/dist/index.js +878 -666
  3. package/dist/index.js.map +4 -4
  4. package/dist/zukhruf/collaboration/capability.d.ts +22 -0
  5. package/dist/zukhruf/collaboration/capability.d.ts.map +1 -0
  6. package/dist/zukhruf/collaboration/code-mode-tools.d.ts +13 -0
  7. package/dist/zukhruf/collaboration/code-mode-tools.d.ts.map +1 -0
  8. package/dist/zukhruf/collaboration/direct-messaging.d.ts +466 -0
  9. package/dist/zukhruf/collaboration/direct-messaging.d.ts.map +1 -0
  10. package/dist/zukhruf/collaboration/direct-tools.d.ts +14 -0
  11. package/dist/zukhruf/collaboration/direct-tools.d.ts.map +1 -0
  12. package/dist/zukhruf/collaboration/spawn-agent.d.ts +26 -26
  13. package/dist/zukhruf/collaboration/spawning.d.ts +325 -0
  14. package/dist/zukhruf/collaboration/spawning.d.ts.map +1 -0
  15. package/dist/zukhruf/collaboration/supervision.d.ts +478 -0
  16. package/dist/zukhruf/collaboration/supervision.d.ts.map +1 -0
  17. package/dist/zukhruf/collaboration/team.d.ts +1549 -0
  18. package/dist/zukhruf/collaboration/team.d.ts.map +1 -0
  19. package/dist/zukhruf/collaboration/tool-exposure.d.ts +29 -0
  20. package/dist/zukhruf/collaboration/tool-exposure.d.ts.map +1 -0
  21. package/dist/zukhruf/collaboration/tool-namespace.d.ts +7 -0
  22. package/dist/zukhruf/collaboration/tool-namespace.d.ts.map +1 -0
  23. package/dist/zukhruf/collaboration/wait-bounds.d.ts +12 -0
  24. package/dist/zukhruf/collaboration/wait-bounds.d.ts.map +1 -0
  25. package/dist/zukhruf/collaboration/waiting.d.ts +262 -0
  26. package/dist/zukhruf/collaboration/waiting.d.ts.map +1 -0
  27. package/dist/zukhruf/control-plane/agent-history-forker.d.ts.map +1 -1
  28. package/dist/zukhruf/control-plane/fork-turns.d.ts +4 -3
  29. package/dist/zukhruf/control-plane/fork-turns.d.ts.map +1 -1
  30. package/dist/zukhruf/index.d.ts +11 -1
  31. package/dist/zukhruf/index.d.ts.map +1 -1
  32. package/dist/zukhruf/index.js +861 -649
  33. package/dist/zukhruf/index.js.map +4 -4
  34. package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts +1 -1
  35. package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts.map +1 -1
  36. package/dist/zukhruf/plugins/conversation-scheduling/index.js +144 -140
  37. package/dist/zukhruf/plugins/conversation-scheduling/index.js.map +4 -4
  38. package/dist/zukhruf/plugins/conversation-scheduling/pg-boss.wake-scheduler.d.ts +1 -1
  39. package/dist/zukhruf/plugins/conversation-scheduling/pg-boss.wake-scheduler.d.ts.map +1 -1
  40. package/dist/zukhruf/plugins/conversation-scheduling/wake-scheduler.d.ts +1 -1
  41. package/dist/zukhruf/plugins/conversation-scheduling/wake-scheduler.d.ts.map +1 -1
  42. package/dist/zukhruf/plugins/schedules/index.js +143 -139
  43. package/dist/zukhruf/plugins/schedules/index.js.map +4 -4
  44. package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts +1 -1
  45. package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts.map +1 -1
  46. package/dist/zukhruf/plugins/uploads/http.js +2 -9
  47. package/dist/zukhruf/plugins/uploads/http.js.map +2 -2
  48. package/dist/zukhruf/queue/turn-queue.d.ts +2 -2
  49. package/dist/zukhruf/queue/turn-queue.d.ts.map +1 -1
  50. package/dist/zukhruf/runtime/agent-runtime.d.ts +5 -4
  51. package/dist/zukhruf/runtime/agent-runtime.d.ts.map +1 -1
  52. package/dist/zukhruf/runtime/agent-turn-executor.d.ts +3 -3
  53. package/dist/zukhruf/runtime/agent-turn-executor.d.ts.map +1 -1
  54. package/dist/zukhruf/runtime/approval-controller.d.ts +3 -3
  55. package/dist/zukhruf/runtime/approval-controller.d.ts.map +1 -1
  56. package/dist/zukhruf/runtime/conversation-sandboxes.d.ts +2 -1
  57. package/dist/zukhruf/runtime/conversation-sandboxes.d.ts.map +1 -1
  58. package/dist/zukhruf/runtime/conversation-status/projector.d.ts.map +1 -1
  59. package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts +3 -5
  60. package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts.map +1 -1
  61. package/package.json +5 -4
  62. package/dist/zukhruf/collaboration/collaboration-tools.d.ts +0 -1832
  63. package/dist/zukhruf/collaboration/collaboration-tools.d.ts.map +0 -1
  64. package/dist/zukhruf/multi-agent-config.d.ts +0 -37
  65. package/dist/zukhruf/multi-agent-config.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -329,8 +329,11 @@ __export(zukhruf_exports, {
329
329
  AgentStorageDatabaseMismatchError: () => AgentStorageDatabaseMismatchError,
330
330
  AgentThread: () => AgentThread,
331
331
  AgentThreadLimitError: () => AgentThreadLimitError,
332
+ CodeModeTools: () => CodeModeTools,
332
333
  ConversationNotFoundError: () => ConversationNotFoundError,
333
334
  DEFAULT_CONVERSATION_STATUS_CHANNEL: () => DEFAULT_CONVERSATION_STATUS_CHANNEL,
335
+ DirectMessaging: () => DirectMessaging,
336
+ DirectTools: () => DirectTools,
334
337
  EmbeddedAgentStorage: () => EmbeddedAgentStorage,
335
338
  EmbeddedAgentStorageInUseError: () => EmbeddedAgentStorageInUseError,
336
339
  InterAgentCommunicationTypes: () => InterAgentCommunicationTypes,
@@ -340,10 +343,16 @@ __export(zukhruf_exports, {
340
343
  PgBossTurnQueue: () => PgBossTurnQueue,
341
344
  PostgresAgentStorage: () => PostgresAgentStorage,
342
345
  PostgresMailboxStore: () => PostgresMailboxStore,
346
+ Spawning: () => Spawning,
343
347
  SqliteMailboxStore: () => SqliteMailboxStore,
344
348
  StaleTurnError: () => StaleTurnError,
349
+ Supervision: () => Supervision,
350
+ Team: () => Team,
351
+ ToolNamespace: () => ToolNamespace,
345
352
  TurnNotFoundError: () => TurnNotFoundError,
346
353
  TurnQueue: () => TurnQueue,
354
+ WaitBounds: () => WaitBounds,
355
+ Waiting: () => Waiting,
347
356
  assertCommunication: () => assertCommunication,
348
357
  createInterAgentCommunication: () => createInterAgentCommunication,
349
358
  defineAgent: () => defineAgent,
@@ -376,6 +385,708 @@ function defineAgent(declaration) {
376
385
  };
377
386
  }
378
387
 
388
+ // packages/experimental/src/zukhruf/collaboration/code-mode-tools.ts
389
+ import { experimental_codeModeTool } from "@ai-sdk/code-mode";
390
+
391
+ // packages/experimental/src/zukhruf/collaboration/tool-exposure.ts
392
+ var ToolExposure = class {
393
+ listed(toolNames) {
394
+ return toolNames.map((name) => `\`${this.toolName(name)}\``).join(", ");
395
+ }
396
+ };
397
+
398
+ // packages/experimental/src/zukhruf/collaboration/code-mode-tools.ts
399
+ var CodeModeTools = class extends ToolExposure {
400
+ toolName(name) {
401
+ return `tools.${name}`;
402
+ }
403
+ callLine(toolNames) {
404
+ return `Call ${this.listed(toolNames)} from \`code_mode\`.`;
405
+ }
406
+ tool(collaborationTool) {
407
+ return collaborationTool;
408
+ }
409
+ surface(collaborationTools) {
410
+ const tools = {
411
+ ...collaborationTools,
412
+ code_mode: experimental_codeModeTool()
413
+ };
414
+ return {
415
+ tools,
416
+ reservedToolNames: Object.keys(tools),
417
+ toolCallers: Object.fromEntries(
418
+ Object.keys(collaborationTools).map((name) => [
419
+ name,
420
+ ["code_mode"]
421
+ ])
422
+ )
423
+ };
424
+ }
425
+ callerContext(context) {
426
+ return { code_mode: context };
427
+ }
428
+ };
429
+
430
+ // packages/experimental/src/zukhruf/collaboration/message-tools.ts
431
+ import { tool } from "ai";
432
+ import { z } from "zod";
433
+ var agentMessageInputSchema = z.object({
434
+ target: z.string().trim().min(1).describe(
435
+ "The canonical /root/... path, or a descendant-relative target name."
436
+ ),
437
+ message: z.string().trim().min(1).describe("The message or follow-up task.")
438
+ });
439
+ var sendMessageTool = tool({
440
+ description: "Queue a message for another agent. Address siblings with their canonical /root/... path.",
441
+ inputSchema: agentMessageInputSchema,
442
+ execute: async (input, { context }) => {
443
+ await context.controlPlane.sendMessage(context.actor, input);
444
+ return "";
445
+ }
446
+ });
447
+ var followupTaskTool = tool({
448
+ description: "Send a follow-up task to an existing non-root agent and wake its thread.",
449
+ inputSchema: agentMessageInputSchema,
450
+ execute: async (input, { context }) => {
451
+ await context.controlPlane.followupTask(context.actor, input);
452
+ return "";
453
+ }
454
+ });
455
+
456
+ // packages/experimental/src/zukhruf/collaboration/direct-messaging.ts
457
+ var DirectMessaging = class {
458
+ tools = {
459
+ send_message: sendMessageTool,
460
+ followup_task: followupTaskTool
461
+ };
462
+ guidance(role3, name) {
463
+ return {
464
+ uses: [
465
+ `\`${name("followup_task")}\` to assign a new task and trigger a turn`,
466
+ role3 === "root" ? `\`${name("send_message")}\` to queue a message without triggering a turn` : `\`${name("send_message")}\` to queue a message for another agent`
467
+ ]
468
+ };
469
+ }
470
+ };
471
+
472
+ // packages/experimental/src/zukhruf/collaboration/direct-tools.ts
473
+ var NAMESPACE_DESCRIPTION = "Tools for spawning and managing sub-agents.";
474
+ var DirectTools = class extends ToolExposure {
475
+ #namespace;
476
+ constructor(namespace) {
477
+ super();
478
+ this.#namespace = namespace;
479
+ }
480
+ toolName(name) {
481
+ return this.#namespace?.qualify(name) ?? name;
482
+ }
483
+ callLine(toolNames) {
484
+ return `Call ${this.listed(toolNames)} directly. They are intentionally unavailable inside nested code execution.`;
485
+ }
486
+ tool(collaborationTool) {
487
+ const openai = collaborationTool.providerOptions?.openai;
488
+ return {
489
+ ...collaborationTool,
490
+ providerOptions: {
491
+ ...collaborationTool.providerOptions,
492
+ ...this.#namespace === void 0 ? {} : {
493
+ openai: {
494
+ ...typeof openai === "object" && openai !== null ? openai : {},
495
+ namespace: {
496
+ name: this.#namespace.name,
497
+ description: NAMESPACE_DESCRIPTION
498
+ }
499
+ }
500
+ }
501
+ }
502
+ };
503
+ }
504
+ surface(collaborationTools) {
505
+ return {
506
+ tools: collaborationTools,
507
+ reservedToolNames: Object.keys(collaborationTools),
508
+ toolCallers: void 0
509
+ };
510
+ }
511
+ callerContext() {
512
+ return {};
513
+ }
514
+ };
515
+
516
+ // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
517
+ import { tool as tool2 } from "ai";
518
+ import { z as z2 } from "zod";
519
+
520
+ // packages/experimental/src/zukhruf/control-plane/fork-turns.ts
521
+ var forkTurnsError = "fork_turns must be `none` or `all`";
522
+ function parseForkTurns(value) {
523
+ const normalized = value?.trim().toLowerCase() || "all";
524
+ return normalized === "none" || normalized === "all" ? normalized : void 0;
525
+ }
526
+
527
+ // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
528
+ var spawnAgentInputSchema = z2.object({
529
+ agent_type: z2.string().trim().min(1).describe("The name of one available subagent declaration."),
530
+ task_name: z2.string().trim().min(1).refine(
531
+ (value) => value !== "." && value !== ".." && !value.includes("/"),
532
+ "task_name must be one non-empty path segment"
533
+ ).describe("One path segment naming this independent agent task."),
534
+ message: z2.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent."),
535
+ fork_turns: z2.string({ error: forkTurnsError }).optional().refine((value) => parseForkTurns(value) !== void 0, forkTurnsError).describe(
536
+ "Parent history to inherit. Defaults to `all`; use `none` to start without parent history. Only `all` and `none` are supported."
537
+ )
538
+ });
539
+ var spawnAgentOutputSchema = z2.object({ task_name: z2.string() }).strict();
540
+ function createSpawnAgentTool(options) {
541
+ return tool2({
542
+ description: ({ context }) => {
543
+ const available = (context.actor.declaration.subagents ?? []).map(
544
+ ({ name, description }) => description ? `${name}: ${description}` : name
545
+ ).join(", ");
546
+ return [
547
+ `Spawn an independent subagent. Available agent types: ${available || "none"}.`,
548
+ options?.usageHintText
549
+ ].filter(Boolean).join(" ");
550
+ },
551
+ inputSchema: spawnAgentInputSchema,
552
+ outputSchema: spawnAgentOutputSchema,
553
+ execute: async ({ agent_type, task_name, message, fork_turns }, { context }) => {
554
+ const forkTurns = parseForkTurns(fork_turns);
555
+ if (forkTurns === void 0) throw new Error(forkTurnsError);
556
+ return context.controlPlane.spawn(context.actor, {
557
+ agentType: agent_type,
558
+ taskName: task_name,
559
+ message,
560
+ forkTurns
561
+ });
562
+ }
563
+ });
564
+ }
565
+
566
+ // packages/experimental/src/zukhruf/collaboration/spawning.ts
567
+ var Spawning = class {
568
+ tools;
569
+ /** `usageHintText` is appended to the `spawn_agent` description. */
570
+ constructor({ usageHintText } = {}) {
571
+ this.tools = { spawn_agent: createSpawnAgentTool({ usageHintText }) };
572
+ }
573
+ guidance(role3, name) {
574
+ const spawnAgent = `\`${name("spawn_agent")}\``;
575
+ if (role3 === "root") {
576
+ return {
577
+ intro: "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.",
578
+ uses: [`${spawnAgent} to create an agent`],
579
+ notes: "You can decide how much context you want to propagate to your sub-agents with the `fork_turns` parameter."
580
+ };
581
+ }
582
+ return {
583
+ intro: "You can spawn declared sub-agents recursively. All agents are equally capable and receive the tools declared for their agent type.",
584
+ uses: [`${spawnAgent} to create one`]
585
+ };
586
+ }
587
+ };
588
+
589
+ // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
590
+ import { tool as tool3 } from "ai";
591
+ import { z as z4 } from "zod";
592
+
593
+ // packages/experimental/src/zukhruf/control-plane/agent-status-projector.ts
594
+ import { isTextUIPart } from "ai";
595
+ import { z as z3 } from "zod";
596
+ import {
597
+ ContextEngine
598
+ } from "@deepagents/context";
599
+
600
+ // packages/experimental/src/zukhruf/mailbox/types.ts
601
+ import { randomUUID } from "node:crypto";
602
+ var MessageDeliveryModes = {
603
+ QueueOnly: "queue-only",
604
+ TriggerTurn: "trigger-turn"
605
+ };
606
+ var InterAgentCommunicationTypes = {
607
+ Message: "MESSAGE",
608
+ NewTask: "NEW_TASK",
609
+ FinalAnswer: "FINAL_ANSWER"
610
+ };
611
+ function createInterAgentCommunication(communication) {
612
+ const value = {
613
+ ...communication,
614
+ id: communication.id ?? randomUUID(),
615
+ type: communication.type ?? InterAgentCommunicationTypes.Message,
616
+ otherRecipients: communication.otherRecipients ?? [],
617
+ triggerTurn: false
618
+ };
619
+ assertCommunication(value);
620
+ return value;
621
+ }
622
+ function assertCommunication(communication) {
623
+ if (!communication.id.trim()) {
624
+ throw new Error("inter-agent communication id cannot be empty");
625
+ }
626
+ if (!Object.values(InterAgentCommunicationTypes).includes(communication.type)) {
627
+ throw new Error("inter-agent communication type is invalid");
628
+ }
629
+ assertConversationId(communication.author, "author");
630
+ assertConversationId(communication.recipient, "recipient");
631
+ for (const recipient of communication.otherRecipients) {
632
+ assertConversationId(recipient, "other recipient");
633
+ }
634
+ if (!communication.content.trim()) {
635
+ throw new Error("inter-agent communication content cannot be empty");
636
+ }
637
+ }
638
+ function assertConversationId(value, label) {
639
+ if (!value.chatId.trim() || !value.userId.trim()) {
640
+ throw new Error(
641
+ `inter-agent communication ${label} requires chatId and userId`
642
+ );
643
+ }
644
+ }
645
+
646
+ // packages/experimental/src/zukhruf/control-plane/agent-status-projector.ts
647
+ var listedAgentStatusSchema = z3.union([
648
+ z3.enum(["pending_init", "running", "interrupted", "shutdown", "not_found"]),
649
+ z3.object({ completed: z3.string().nullable() }).strict(),
650
+ z3.object({ errored: z3.string() }).strict()
651
+ ]);
652
+ var listedAgentSchema = z3.object({
653
+ agent_name: z3.string(),
654
+ agent_status: listedAgentStatusSchema
655
+ }).strict();
656
+ var AgentStatusProjector = class _AgentStatusProjector {
657
+ #store;
658
+ #streams;
659
+ #queue;
660
+ #mailbox;
661
+ #directory;
662
+ #approvals;
663
+ constructor(options) {
664
+ this.#store = options.store;
665
+ this.#streams = options.streams;
666
+ this.#queue = options.queue;
667
+ this.#mailbox = options.mailbox;
668
+ this.#directory = options.directory;
669
+ this.#approvals = options.approvals;
670
+ }
671
+ async projectListedAgent(currentTurn, thread) {
672
+ const messages = await this.#messages(thread);
673
+ const head = messages.at(-1);
674
+ const streamId = thread.lastTurnId ?? (head?.role === "assistant" ? head.id : void 0);
675
+ const stream = streamId ? await this.#streams.store.getStream(streamId) : void 0;
676
+ const scheduledTurn = await this.#queue.getCurrentTurn(thread.conversation);
677
+ const scheduledStream = scheduledTurn ? await this.#streams.store.getStream(scheduledTurn.streamId) : void 0;
678
+ let status = _AgentStatusProjector.#listedStatus(
679
+ stream?.status,
680
+ stream?.error,
681
+ head
682
+ );
683
+ if (stream?.status === "completed" && this.#approvals.isPaused(head)) {
684
+ status = "running";
685
+ }
686
+ if (thread.conversation.chatId === currentTurn.chatId || thread.lastTurnId !== void 0 && scheduledTurn?.streamId !== thread.lastTurnId && (scheduledStream?.status === "queued" || scheduledStream?.status === "running")) {
687
+ status = "running";
688
+ }
689
+ return {
690
+ agent_name: thread.path.toString(),
691
+ agent_status: status
692
+ };
693
+ }
694
+ async projectTerminal(turn, thread) {
695
+ if (thread.parentChatId === null) return;
696
+ const stream = await this.#streams.store.getStream(turn.streamId);
697
+ if (!stream || stream.status !== "completed" && stream.status !== "failed" && stream.status !== "cancelled") {
698
+ return;
699
+ }
700
+ const message = (await this.#messages(thread)).find(
701
+ (candidate) => candidate.role === "assistant" && candidate.id === turn.streamId
702
+ );
703
+ if (stream.status === "completed" && this.#approvals.isPaused(message)) {
704
+ return;
705
+ }
706
+ const text = message?.role === "assistant" ? _AgentStatusProjector.#messageText(message) : "";
707
+ let content = text || "Agent completed without a text response.";
708
+ if (stream.status === "failed") {
709
+ content = `Agent failed: ${stream.error || "unknown error"}`;
710
+ } else if (stream.status === "cancelled") {
711
+ content = "Agent was interrupted.";
712
+ }
713
+ const parent = await this.#directory.load({
714
+ chatId: thread.parentChatId,
715
+ userId: thread.conversation.userId
716
+ });
717
+ await this.#mailbox.deliver(
718
+ createInterAgentCommunication({
719
+ id: `zukhruf:child-terminal:${turn.streamId}`,
720
+ type: InterAgentCommunicationTypes.FinalAnswer,
721
+ author: thread.conversation,
722
+ recipient: {
723
+ chatId: thread.parentChatId,
724
+ userId: thread.conversation.userId
725
+ },
726
+ content,
727
+ metadata: {
728
+ authorPath: thread.path.toString(),
729
+ recipientPath: parent?.path.toString() ?? thread.parentChatId,
730
+ streamId: turn.streamId,
731
+ status: stream.status
732
+ }
733
+ }),
734
+ MessageDeliveryModes.QueueOnly
735
+ );
736
+ return { finishedAt: stream.finishedAt, status: stream.status };
737
+ }
738
+ async #messages(thread) {
739
+ const engine = new ContextEngine({
740
+ store: this.#store,
741
+ chatId: thread.conversation.chatId,
742
+ userId: thread.conversation.userId
743
+ });
744
+ return engine.getMessages();
745
+ }
746
+ static #listedStatus(status, error, head) {
747
+ switch (status) {
748
+ case "running":
749
+ return "running";
750
+ case "completed":
751
+ return {
752
+ completed: head?.role === "assistant" ? _AgentStatusProjector.#messageText(head) || null : null
753
+ };
754
+ case "failed":
755
+ return { errored: error || "Agent turn failed." };
756
+ case "cancelled":
757
+ return "interrupted";
758
+ case "queued":
759
+ case void 0:
760
+ return "pending_init";
761
+ }
762
+ }
763
+ static #messageText(message) {
764
+ return message.parts.filter(isTextUIPart).map((part) => part.text).join("\n").trim();
765
+ }
766
+ };
767
+
768
+ // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
769
+ var interruptAgentInputSchema = z4.object({
770
+ target: z4.string().trim().min(1).describe(
771
+ "The canonical /root/... path, or a descendant-relative target name."
772
+ )
773
+ });
774
+ var interruptAgentOutputSchema = z4.object({ previous_status: listedAgentStatusSchema }).strict();
775
+ var interruptAgentTool = tool3({
776
+ description: "Interrupt an agent's current turn, if any, and return its previous status. The agent remains available for messages and follow-up tasks.",
777
+ inputSchema: interruptAgentInputSchema,
778
+ outputSchema: interruptAgentOutputSchema,
779
+ execute: async (input, { context }) => context.controlPlane.interruptAgent(context.actor, input)
780
+ });
781
+
782
+ // packages/experimental/src/zukhruf/collaboration/list-agents.ts
783
+ import { tool as tool4 } from "ai";
784
+ import { z as z5 } from "zod";
785
+ var listAgentsInputSchema = z5.object({
786
+ path_prefix: z5.string().trim().min(1).describe(
787
+ "Task-path prefix without a trailing slash. Omit to list the whole tree."
788
+ ).optional()
789
+ });
790
+ var listAgentsOutputSchema = z5.object({ agents: z5.array(listedAgentSchema) }).strict();
791
+ var listAgentsTool = tool4({
792
+ description: "List live agents in the current root thread tree. Optionally filter by task-path prefix.",
793
+ inputSchema: listAgentsInputSchema,
794
+ outputSchema: listAgentsOutputSchema,
795
+ execute: async ({ path_prefix }, { context }) => context.controlPlane.listAgents(context.actor, path_prefix)
796
+ });
797
+
798
+ // packages/experimental/src/zukhruf/collaboration/supervision.ts
799
+ var Supervision = class {
800
+ tools = {
801
+ interrupt_agent: interruptAgentTool,
802
+ list_agents: listAgentsTool
803
+ };
804
+ guidance() {
805
+ return {};
806
+ }
807
+ };
808
+
809
+ // packages/experimental/src/zukhruf/collaboration/wait-agent.ts
810
+ import { tool as tool5 } from "ai";
811
+ import { z as z6 } from "zod";
812
+ var waitAgentOutputSchema = z6.object({ message: z6.string(), timed_out: z6.boolean() }).strict();
813
+ function createWaitAgentTool(options) {
814
+ const waitAgentInputSchema = z6.object({
815
+ timeout_ms: z6.number().int().max(options.maxTimeoutMs).optional().describe("Maximum time to wait in milliseconds.")
816
+ });
817
+ return tool5({
818
+ description: "Wait for pending mail addressed to this agent without consuming it.",
819
+ inputSchema: waitAgentInputSchema,
820
+ outputSchema: waitAgentOutputSchema,
821
+ execute: async ({ timeout_ms }, { abortSignal, context }) => {
822
+ const timeoutMs = Math.max(
823
+ timeout_ms ?? options.defaultTimeoutMs,
824
+ options.minTimeoutMs
825
+ );
826
+ const received = await context.controlPlane.waitForMailbox(
827
+ context.actor,
828
+ {
829
+ timeoutMs,
830
+ signal: abortSignal
831
+ }
832
+ );
833
+ const message = received ? "Wait completed." : "Wait timed out.";
834
+ return {
835
+ message: timeout_ms !== void 0 && timeout_ms < timeoutMs ? `${message}
836
+
837
+ Requested timeout of ${timeout_ms}ms was clamped to the minimum of ${timeoutMs}ms.` : message,
838
+ timed_out: !received
839
+ };
840
+ }
841
+ });
842
+ }
843
+
844
+ // packages/experimental/src/zukhruf/collaboration/wait-bounds.ts
845
+ var WaitBounds = class {
846
+ minMs;
847
+ defaultMs;
848
+ maxMs;
849
+ constructor({
850
+ minMs = 1e4,
851
+ defaultMs = 3e4,
852
+ maxMs = 36e5
853
+ } = {}) {
854
+ assertTimeout("minMs", minMs);
855
+ assertTimeout("defaultMs", defaultMs);
856
+ assertTimeout("maxMs", maxMs);
857
+ if (minMs > maxMs) {
858
+ throw new Error("AgentRuntime: WaitBounds minMs must be at most maxMs");
859
+ }
860
+ if (defaultMs < minMs) {
861
+ throw new Error(
862
+ "AgentRuntime: WaitBounds defaultMs must be at least minMs"
863
+ );
864
+ }
865
+ if (defaultMs > maxMs) {
866
+ throw new Error(
867
+ "AgentRuntime: WaitBounds defaultMs must be at most maxMs"
868
+ );
869
+ }
870
+ this.minMs = minMs;
871
+ this.defaultMs = defaultMs;
872
+ this.maxMs = maxMs;
873
+ }
874
+ };
875
+ function assertTimeout(name, value) {
876
+ if (!Number.isSafeInteger(value) || value < 0) {
877
+ throw new Error(
878
+ `AgentRuntime: WaitBounds ${name} must be a non-negative safe integer`
879
+ );
880
+ }
881
+ }
882
+
883
+ // packages/experimental/src/zukhruf/collaboration/waiting.ts
884
+ var PREFER_LONGER_WAITS = "When calling `wait_agent`, prefer longer waits (minutes) to avoid busy polling.";
885
+ var Waiting = class {
886
+ bounds;
887
+ tools;
888
+ constructor(bounds = new WaitBounds()) {
889
+ this.bounds = bounds;
890
+ this.tools = {
891
+ wait_agent: createWaitAgentTool({
892
+ minTimeoutMs: bounds.minMs,
893
+ defaultTimeoutMs: bounds.defaultMs,
894
+ maxTimeoutMs: bounds.maxMs
895
+ })
896
+ };
897
+ }
898
+ guidance() {
899
+ return { outro: PREFER_LONGER_WAITS };
900
+ }
901
+ };
902
+
903
+ // packages/experimental/src/zukhruf/collaboration/team.ts
904
+ var DEFAULT_MAX_CONCURRENT_THREADS = 4;
905
+ var SHARED_WORKSPACE = "All agents share the same workspace, current working directory, and filesystem.";
906
+ var USE_CLAUSES = new Intl.ListFormat("en", { type: "conjunction" });
907
+ var ROLE_GUIDANCE = {
908
+ root: {
909
+ preamble: "You are `/root`, the primary agent in a team of agents collaborating to fulfill the user's goals.",
910
+ introSeparator: "\n\n",
911
+ envelopes: "Child messages arrive as `MESSAGE` or `FINAL_ANSWER` mailbox envelopes with their task name, sender, and payload preserved."
912
+ },
913
+ subagent: {
914
+ preamble: "You are an agent in a team collaborating to complete a task.",
915
+ introSeparator: " ",
916
+ envelopes: "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."
917
+ }
918
+ };
919
+ function concurrencySlotsText(maxConcurrency) {
920
+ return `There are ${maxConcurrency} available concurrency slots, meaning that up to ${maxConcurrency} agents can be active at once, including you.`;
921
+ }
922
+ var Team = class _Team {
923
+ maxConcurrentThreads;
924
+ exposure;
925
+ /** What a turn's model request carries for the team's tools. */
926
+ surface;
927
+ #members;
928
+ #options;
929
+ constructor(spawning, options = {}) {
930
+ const maxConcurrentThreads = options.maxConcurrentThreads ?? DEFAULT_MAX_CONCURRENT_THREADS;
931
+ if (!Number.isSafeInteger(maxConcurrentThreads) || maxConcurrentThreads < 1) {
932
+ throw new Error(
933
+ "AgentRuntime: Team maxConcurrentThreads must be a positive integer"
934
+ );
935
+ }
936
+ this.maxConcurrentThreads = maxConcurrentThreads;
937
+ this.exposure = options.exposure ?? new DirectTools();
938
+ this.#members = spawning;
939
+ this.#options = options;
940
+ this.surface = this.exposure.surface(this.tools);
941
+ }
942
+ /** Every capability, in Codex order. */
943
+ static codex({
944
+ usageHintText,
945
+ waitBounds,
946
+ ...options
947
+ } = {}) {
948
+ return new _Team(new Spawning({ usageHintText }), options).with(new DirectMessaging()).with(new Waiting(waitBounds)).with(new Supervision());
949
+ }
950
+ /** A team that also has `capability`. Two tools of one name throw. */
951
+ with(capability) {
952
+ for (const name of Object.keys(capability.tools)) {
953
+ if (Object.hasOwn(this.#members.tools, name)) {
954
+ throw new Error(
955
+ `AgentRuntime: the team already has the "${name}" collaboration tool`
956
+ );
957
+ }
958
+ }
959
+ return new _Team(new Joined(this.#members, capability), this.#options);
960
+ }
961
+ /** The collaboration tools as the exposure carries them, in team order. */
962
+ get tools() {
963
+ const tools = { ...this.#members.tools };
964
+ for (const name in tools) {
965
+ const collaborationTool = tools[name];
966
+ tools[name] = this.exposure.tool({
967
+ ...collaborationTool,
968
+ metadata: {
969
+ ...collaborationTool.metadata,
970
+ zukhruf: {
971
+ kind: "collaboration"
972
+ }
973
+ }
974
+ });
975
+ }
976
+ return tools;
977
+ }
978
+ /** Names a plugin tool cannot take. */
979
+ get reservedToolNames() {
980
+ return this.surface.reservedToolNames;
981
+ }
982
+ /** The tools context of every tool that acts as `agent`. */
983
+ contextFor(agent2) {
984
+ const context = {};
985
+ for (const name of Object.keys(this.#members.tools)) context[name] = agent2;
986
+ if (!coversEveryTool(this.#members.tools, context)) {
987
+ throw new Error("AgentRuntime: a collaboration tool has no context");
988
+ }
989
+ return { ...context, ...this.exposure.callerContext(agent2) };
990
+ }
991
+ /** The role's collaboration guidance, or `undefined` for none. */
992
+ guidance(role3) {
993
+ const composed = this.#compose(role3);
994
+ const transform = this.#options.guidance?.[role3];
995
+ return transform === void 0 ? composed : transform(composed);
996
+ }
997
+ #compose(role3) {
998
+ const name = (toolName) => this.exposure.toolName(toolName);
999
+ const {
1000
+ intro,
1001
+ uses = [],
1002
+ notes,
1003
+ outro
1004
+ } = this.#members.guidance(role3, name);
1005
+ const { preamble, introSeparator, envelopes } = ROLE_GUIDANCE[role3];
1006
+ const lead = [
1007
+ intro,
1008
+ joined(
1009
+ [
1010
+ uses.length === 0 ? void 0 : `Use ${USE_CLAUSES.format(uses)}.`,
1011
+ notes
1012
+ ],
1013
+ " "
1014
+ )
1015
+ ];
1016
+ return [
1017
+ preamble,
1018
+ joined(lead, introSeparator),
1019
+ envelopes,
1020
+ this.exposure.callLine(Object.keys(this.#members.tools)),
1021
+ SHARED_WORKSPACE,
1022
+ outro,
1023
+ concurrencySlotsText(this.maxConcurrentThreads)
1024
+ ].filter((paragraph) => paragraph !== void 0).join("\n\n");
1025
+ }
1026
+ };
1027
+ var Joined = class {
1028
+ tools;
1029
+ #first;
1030
+ #second;
1031
+ constructor(first, second) {
1032
+ this.tools = { ...first.tools, ...second.tools };
1033
+ this.#first = first;
1034
+ this.#second = second;
1035
+ }
1036
+ guidance(role3, name) {
1037
+ const first = this.#first.guidance(role3, name);
1038
+ const second = this.#second.guidance(role3, name);
1039
+ return {
1040
+ intro: joined([first.intro, second.intro], " "),
1041
+ uses: [...first.uses ?? [], ...second.uses ?? []],
1042
+ notes: joined([first.notes, second.notes], " "),
1043
+ outro: joined([first.outro, second.outro], "\n\n")
1044
+ };
1045
+ }
1046
+ };
1047
+ function coversEveryTool(tools, context) {
1048
+ return Object.keys(tools).every((name) => Object.hasOwn(context, name));
1049
+ }
1050
+ function joined(texts, separator) {
1051
+ const present = texts.filter((text) => text !== void 0);
1052
+ return present.length === 0 ? void 0 : present.join(separator);
1053
+ }
1054
+
1055
+ // packages/experimental/src/zukhruf/collaboration/tool-namespace.ts
1056
+ var RESERVED_TOOL_NAMESPACES = /* @__PURE__ */ new Set([
1057
+ "api_tool",
1058
+ "browser",
1059
+ "computer",
1060
+ "container",
1061
+ "file_search",
1062
+ "functions",
1063
+ "image_gen",
1064
+ "multi_tool_use",
1065
+ "python",
1066
+ "python_user_visible",
1067
+ "submodel_delegator",
1068
+ "terminal",
1069
+ "tool_search",
1070
+ "web"
1071
+ ]);
1072
+ var ToolNamespace = class {
1073
+ name;
1074
+ constructor(name) {
1075
+ if (name.length === 0 || name.trim() !== name) {
1076
+ throw new Error("AgentRuntime: ToolNamespace cannot be empty or padded");
1077
+ }
1078
+ if (name.length > 64 || !/^[a-zA-Z0-9_-]+$/.test(name) || name === "mcp" || name.startsWith("mcp__") || RESERVED_TOOL_NAMESPACES.has(name)) {
1079
+ throw new Error(
1080
+ `AgentRuntime: ToolNamespace "${name}" is a reserved tool namespace or invalid`
1081
+ );
1082
+ }
1083
+ this.name = name;
1084
+ }
1085
+ qualify(toolName) {
1086
+ return `${this.name}.${toolName}`;
1087
+ }
1088
+ };
1089
+
379
1090
  // packages/experimental/src/zukhruf/control-plane/agent-path.ts
380
1091
  var AgentPath = class _AgentPath {
381
1092
  #value;
@@ -584,75 +1295,27 @@ function defineInstructions(...fragments) {
584
1295
  }
585
1296
 
586
1297
  // packages/experimental/src/zukhruf/mailbox/postgres.store.ts
587
- import { z as z2 } from "zod";
1298
+ import { z as z8 } from "zod";
588
1299
  import {
589
1300
  PostgresStoreDatabase,
590
1301
  lockSchemaDDL
591
1302
  } from "@deepagents/context";
592
1303
 
593
1304
  // packages/experimental/src/zukhruf/mailbox/communication-schema.ts
594
- import { z } from "zod";
595
-
596
- // packages/experimental/src/zukhruf/mailbox/types.ts
597
- import { randomUUID } from "node:crypto";
598
- var MessageDeliveryModes = {
599
- QueueOnly: "queue-only",
600
- TriggerTurn: "trigger-turn"
601
- };
602
- var InterAgentCommunicationTypes = {
603
- Message: "MESSAGE",
604
- NewTask: "NEW_TASK",
605
- FinalAnswer: "FINAL_ANSWER"
606
- };
607
- function createInterAgentCommunication(communication) {
608
- const value = {
609
- ...communication,
610
- id: communication.id ?? randomUUID(),
611
- type: communication.type ?? InterAgentCommunicationTypes.Message,
612
- otherRecipients: communication.otherRecipients ?? [],
613
- triggerTurn: false
614
- };
615
- assertCommunication(value);
616
- return value;
617
- }
618
- function assertCommunication(communication) {
619
- if (!communication.id.trim()) {
620
- throw new Error("inter-agent communication id cannot be empty");
621
- }
622
- if (!Object.values(InterAgentCommunicationTypes).includes(communication.type)) {
623
- throw new Error("inter-agent communication type is invalid");
624
- }
625
- assertConversationId(communication.author, "author");
626
- assertConversationId(communication.recipient, "recipient");
627
- for (const recipient of communication.otherRecipients) {
628
- assertConversationId(recipient, "other recipient");
629
- }
630
- if (!communication.content.trim()) {
631
- throw new Error("inter-agent communication content cannot be empty");
632
- }
633
- }
634
- function assertConversationId(value, label) {
635
- if (!value.chatId.trim() || !value.userId.trim()) {
636
- throw new Error(
637
- `inter-agent communication ${label} requires chatId and userId`
638
- );
639
- }
640
- }
641
-
642
- // packages/experimental/src/zukhruf/mailbox/communication-schema.ts
643
- var conversationIdSchema = z.object({
644
- chatId: z.string(),
645
- userId: z.string()
1305
+ import { z as z7 } from "zod";
1306
+ var conversationIdSchema = z7.object({
1307
+ chatId: z7.string(),
1308
+ userId: z7.string()
646
1309
  });
647
- var communicationSchema = z.object({
648
- id: z.string(),
649
- type: z.enum(InterAgentCommunicationTypes),
1310
+ var communicationSchema = z7.object({
1311
+ id: z7.string(),
1312
+ type: z7.enum(InterAgentCommunicationTypes),
650
1313
  author: conversationIdSchema,
651
1314
  recipient: conversationIdSchema,
652
- otherRecipients: z.array(conversationIdSchema),
653
- content: z.string(),
654
- metadata: z.record(z.string(), z.unknown()).optional(),
655
- triggerTurn: z.boolean()
1315
+ otherRecipients: z7.array(conversationIdSchema),
1316
+ content: z7.string(),
1317
+ metadata: z7.record(z7.string(), z7.unknown()).optional(),
1318
+ triggerTurn: z7.boolean()
656
1319
  });
657
1320
 
658
1321
  // packages/experimental/src/zukhruf/mailbox/ddl.postgres.ts
@@ -689,13 +1352,13 @@ var MailboxStore = class {
689
1352
  };
690
1353
 
691
1354
  // packages/experimental/src/zukhruf/mailbox/postgres.store.ts
692
- var mailboxItemRowsSchema = z2.array(
693
- z2.object({
694
- sequence: z2.string(),
1355
+ var mailboxItemRowsSchema = z8.array(
1356
+ z8.object({
1357
+ sequence: z8.string(),
695
1358
  communication: communicationSchema
696
1359
  })
697
1360
  );
698
- var existsRowsSchema = z2.tuple([z2.object({ exists: z2.boolean() })]);
1361
+ var existsRowsSchema = z8.tuple([z8.object({ exists: z8.boolean() })]);
699
1362
  var PostgresMailboxStore = class _PostgresMailboxStore extends MailboxStore {
700
1363
  #database;
701
1364
  constructor(database) {
@@ -869,7 +1532,7 @@ var PostgresMailboxStore = class _PostgresMailboxStore extends MailboxStore {
869
1532
  import { Declaration } from "@zukhruf/sqlite-drift";
870
1533
  import { open } from "@zukhruf/sqlite-open";
871
1534
  import { transaction } from "@zukhruf/sqlite-transaction";
872
- import { z as z3 } from "zod";
1535
+ import { z as z9 } from "zod";
873
1536
 
874
1537
  // packages/experimental/src/zukhruf/mailbox/ddl.sqlite.ts
875
1538
  var statements = [
@@ -903,10 +1566,10 @@ var statements = [
903
1566
 
904
1567
  // packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
905
1568
  var tables = new Declaration(statements, { rows: "keep" });
906
- var mailboxItemRowsSchema2 = z3.array(
907
- z3.object({
908
- sequence: z3.number(),
909
- communication: z3.string().transform((text) => JSON.parse(text)).pipe(communicationSchema)
1569
+ var mailboxItemRowsSchema2 = z9.array(
1570
+ z9.object({
1571
+ sequence: z9.number(),
1572
+ communication: z9.string().transform((text) => JSON.parse(text)).pipe(communicationSchema)
910
1573
  })
911
1574
  );
912
1575
  var SqliteMailboxStore = class extends MailboxStore {
@@ -1075,7 +1738,7 @@ var SqliteMailboxStore = class extends MailboxStore {
1075
1738
 
1076
1739
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
1077
1740
  import { v7 as uuidv7 } from "uuid";
1078
- import { z as z4 } from "zod";
1741
+ import { z as z10 } from "zod";
1079
1742
  import { isRecord as isRecord2 } from "@deepagents/context";
1080
1743
 
1081
1744
  // packages/experimental/src/zukhruf/queue/turn-queue.ts
@@ -1083,7 +1746,7 @@ var TurnQueue = class {
1083
1746
  };
1084
1747
 
1085
1748
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
1086
- var queueCatalogRowSchema = z4.object({ table: z4.string() });
1749
+ var queueCatalogRowSchema = z10.object({ table: z10.string() });
1087
1750
  function deadLetterQueueOf(queue) {
1088
1751
  return `${queue}-dead`;
1089
1752
  }
@@ -1344,11 +2007,11 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
1344
2007
  disposal.abort();
1345
2008
  await this.#boss.offWork(this.#queue, {
1346
2009
  id: turnWorkerId,
1347
- wait: options.waitForActive
2010
+ wait: true
1348
2011
  });
1349
2012
  await this.#boss.offWork(this.deadLetterQueue, {
1350
2013
  id: deadWorkerId,
1351
- wait: options.waitForActive
2014
+ wait: true
1352
2015
  });
1353
2016
  }
1354
2017
  };
@@ -1461,7 +2124,7 @@ import { MemoryStore } from "@zukhruf/mutex/memory";
1461
2124
  import { EventEmitter, on } from "node:events";
1462
2125
  import { isDeepStrictEqual } from "node:util";
1463
2126
  import {
1464
- ContextEngine as ContextEngine2
2127
+ ContextEngine as ContextEngine3
1465
2128
  } from "@deepagents/context";
1466
2129
 
1467
2130
  // packages/experimental/src/zukhruf/runtime/approval-controller.ts
@@ -1470,7 +2133,7 @@ import {
1470
2133
  isToolUIPart
1471
2134
  } from "ai";
1472
2135
  import {
1473
- ContextEngine,
2136
+ ContextEngine as ContextEngine2,
1474
2137
  assistant
1475
2138
  } from "@deepagents/context";
1476
2139
  function hasUnansweredApprovals(message) {
@@ -1505,11 +2168,6 @@ var ApprovalController = class {
1505
2168
  isPaused(message) {
1506
2169
  return isPausedHead(message);
1507
2170
  }
1508
- async isConversationPaused(conversation) {
1509
- return this.isPaused(
1510
- (await this.#engineFor(conversation).getMessages()).at(-1)
1511
- );
1512
- }
1513
2171
  async settleDeniedApprovals(conversation, streamId) {
1514
2172
  const engine = this.#engineFor(conversation);
1515
2173
  const head = (await engine.getMessages()).at(-1);
@@ -1626,26 +2284,26 @@ var ApprovalController = class {
1626
2284
  });
1627
2285
  }
1628
2286
  #engineFor({ chatId, userId }) {
1629
- return new ContextEngine({ store: this.#store, chatId, userId });
2287
+ return new ContextEngine2({ store: this.#store, chatId, userId });
1630
2288
  }
1631
2289
  };
1632
2290
 
1633
2291
  // packages/experimental/src/zukhruf/runtime/conversation-status/child-progress.ts
1634
- import { z as z5 } from "zod";
1635
- var childActivitySchema = z5.object({
1636
- id: z5.string(),
1637
- type: z5.enum(["spawn", "message", "followup", "interrupt", "completion"]),
1638
- at: z5.number(),
1639
- actorPath: z5.string(),
1640
- targetPath: z5.string(),
1641
- streamId: z5.string(),
1642
- outcome: z5.enum(["completed", "failed", "cancelled"]).optional()
2292
+ import { z as z11 } from "zod";
2293
+ var childActivitySchema = z11.object({
2294
+ id: z11.string(),
2295
+ type: z11.enum(["spawn", "message", "followup", "interrupt", "completion"]),
2296
+ at: z11.number(),
2297
+ actorPath: z11.string(),
2298
+ targetPath: z11.string(),
2299
+ streamId: z11.string(),
2300
+ outcome: z11.enum(["completed", "failed", "cancelled"]).optional()
1643
2301
  });
1644
- var childActivitiesSchema = z5.partialRecord(
2302
+ var childActivitiesSchema = z11.partialRecord(
1645
2303
  childActivitySchema.shape.type,
1646
2304
  childActivitySchema
1647
2305
  );
1648
- var childActivityMetadataSchema = z5.looseObject({
2306
+ var childActivityMetadataSchema = z11.looseObject({
1649
2307
  childActivities: childActivitiesSchema.default({})
1650
2308
  });
1651
2309
 
@@ -1690,7 +2348,7 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
1690
2348
  async read(conversation) {
1691
2349
  const activity = await this.#queue.getTurnActivity(conversation);
1692
2350
  if (activity === "running") return { type: "active", activeFlags: [] };
1693
- const engine = new ContextEngine2({
2351
+ const engine = new ContextEngine3({
1694
2352
  store: this.#store,
1695
2353
  chatId: conversation.chatId,
1696
2354
  userId: conversation.userId
@@ -1699,7 +2357,8 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
1699
2357
  const thread = await this.#directory.load(conversation);
1700
2358
  const streamId = thread?.lastTurnId ?? (head?.role === "assistant" ? head.id : void 0);
1701
2359
  const stream = streamId ? await this.#streams.store.getStream(streamId) : void 0;
1702
- const activeFlags = stream?.status === "completed" && head?.role === "assistant" ? activeFlagsOf(head) : [];
2360
+ const continuing = stream?.status === "queued" || stream?.status === "running";
2361
+ const activeFlags = !continuing && head?.role === "assistant" ? activeFlagsOf(head) : [];
1703
2362
  if (activity === "queued" || activeFlags.length > 0) {
1704
2363
  return { type: "active", activeFlags };
1705
2364
  }
@@ -2273,7 +2932,7 @@ var AgentHistoryForker = class {
2273
2932
  return this.#messagesById(parent, record.sourceMessageIds);
2274
2933
  }
2275
2934
  const source = await this.#sourceMessages(parent, record);
2276
- const selected = this.#select(source, record.forkTurns).map((entry) => this.#keepHistoryMessage(entry)).filter((entry) => entry !== void 0);
2935
+ const selected = source.map((entry) => this.#keepHistoryMessage(entry)).filter((entry) => entry !== void 0);
2277
2936
  const sourceMessageIds = await this.#claimSelection(
2278
2937
  child,
2279
2938
  selected.map(({ stored }) => stored.id)
@@ -2344,18 +3003,10 @@ var AgentHistoryForker = class {
2344
3003
  }
2345
3004
  return sourceMessageIds;
2346
3005
  }
2347
- #select(source, forkTurns) {
2348
- if (forkTurns === "all") return source;
2349
- const boundaries = source.flatMap(
2350
- (entry, index) => isForkTurnBoundary(entry.message) ? [index] : []
2351
- );
2352
- const start = boundaries.at(-forkTurns) ?? boundaries[0];
2353
- return start === void 0 ? [] : source.slice(start);
2354
- }
2355
3006
  #keepHistoryMessage(entry) {
2356
3007
  const { message } = entry;
2357
3008
  if (message.role === "user") {
2358
- if (isSyntheticReminderMessage(message) || interAgentCommunication(message) !== void 0) {
3009
+ if (isSyntheticReminderMessage(message) || isInterAgentCommunication(message)) {
2359
3010
  return void 0;
2360
3011
  }
2361
3012
  return entry;
@@ -2392,190 +3043,57 @@ var AgentHistoryForker = class {
2392
3043
  return clone;
2393
3044
  });
2394
3045
  }
2395
- async #hasForkedPrefix(child, expectedIds) {
2396
- const branch = await this.#store.getActiveBranch(child.conversation.chatId);
2397
- if (!branch?.headMessageId) return false;
2398
- const chain = await this.#store.getMessageChain(branch.headMessageId);
2399
- return expectedIds.every(
2400
- (id, index) => chain[index]?.id === id && chain[index]?.chatId === child.conversation.chatId
2401
- );
2402
- }
2403
- };
2404
- function isForkTurnBoundary(message) {
2405
- if (message.role !== "user" || isSyntheticReminderMessage(message)) {
2406
- return false;
2407
- }
2408
- return interAgentCommunication(message)?.triggerTurn ?? true;
2409
- }
2410
- function interAgentCommunication(message) {
2411
- if (!isRecord3(message.metadata)) return void 0;
2412
- if (!Object.hasOwn(message.metadata, "interAgentCommunication")) {
2413
- return void 0;
2414
- }
2415
- const communication = message.metadata.interAgentCommunication;
2416
- if (!isRecord3(communication) || typeof communication.triggerTurn !== "boolean") {
2417
- throw new Error(
2418
- `spawn_agent: message "${message.id}" has invalid inter-agent metadata`
2419
- );
2420
- }
2421
- return { triggerTurn: communication.triggerTurn };
2422
- }
2423
- function parseHistoryForkRecord(value) {
2424
- if (!isRecord3(value)) {
2425
- throw new Error("spawn_agent: invalid persisted history-fork metadata");
2426
- }
2427
- const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } = value;
2428
- if (!isForkTurns(forkTurns) || typeof parentChatId !== "string" || !parentChatId.trim() || parentHeadMessageId !== null && (typeof parentHeadMessageId !== "string" || parentHeadMessageId.length === 0) || sourceMessageIds !== void 0 && (!Array.isArray(sourceMessageIds) || !sourceMessageIds.every(
2429
- (id) => typeof id === "string" && id.trim().length > 0
2430
- ) || new Set(sourceMessageIds).size !== sourceMessageIds.length)) {
2431
- throw new Error("spawn_agent: invalid persisted history-fork metadata");
2432
- }
2433
- return {
2434
- forkTurns,
2435
- parentChatId,
2436
- parentHeadMessageId,
2437
- ...sourceMessageIds === void 0 ? {} : { sourceMessageIds }
2438
- };
2439
- }
2440
- function isForkTurns(value) {
2441
- return value === "none" || value === "all" || typeof value === "number" && Number.isSafeInteger(value) && value > 0;
2442
- }
2443
- function isEmptyAssistantPlaceholder(value) {
2444
- return isRecord3(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
2445
- }
2446
-
2447
- // packages/experimental/src/zukhruf/control-plane/agent-status-projector.ts
2448
- import { isTextUIPart } from "ai";
2449
- import { z as z6 } from "zod";
2450
- import {
2451
- ContextEngine as ContextEngine3
2452
- } from "@deepagents/context";
2453
- var listedAgentStatusSchema = z6.union([
2454
- z6.enum(["pending_init", "running", "interrupted", "shutdown", "not_found"]),
2455
- z6.object({ completed: z6.string().nullable() }).strict(),
2456
- z6.object({ errored: z6.string() }).strict()
2457
- ]);
2458
- var listedAgentSchema = z6.object({
2459
- agent_name: z6.string(),
2460
- agent_status: listedAgentStatusSchema
2461
- }).strict();
2462
- var AgentStatusProjector = class _AgentStatusProjector {
2463
- #store;
2464
- #streams;
2465
- #queue;
2466
- #mailbox;
2467
- #directory;
2468
- #approvals;
2469
- constructor(options) {
2470
- this.#store = options.store;
2471
- this.#streams = options.streams;
2472
- this.#queue = options.queue;
2473
- this.#mailbox = options.mailbox;
2474
- this.#directory = options.directory;
2475
- this.#approvals = options.approvals;
2476
- }
2477
- async projectListedAgent(currentTurn, thread) {
2478
- const messages = await this.#messages(thread);
2479
- const head = messages.at(-1);
2480
- const streamId = thread.lastTurnId ?? (head?.role === "assistant" ? head.id : void 0);
2481
- const stream = streamId ? await this.#streams.store.getStream(streamId) : void 0;
2482
- const scheduledTurn = await this.#queue.getCurrentTurn(thread.conversation);
2483
- const scheduledStream = scheduledTurn ? await this.#streams.store.getStream(scheduledTurn.streamId) : void 0;
2484
- let status = _AgentStatusProjector.#listedStatus(
2485
- stream?.status,
2486
- stream?.error,
2487
- head
2488
- );
2489
- if (stream?.status === "completed" && this.#approvals.isPaused(head)) {
2490
- status = "running";
2491
- }
2492
- if (thread.conversation.chatId === currentTurn.chatId || thread.lastTurnId !== void 0 && scheduledTurn?.streamId !== thread.lastTurnId && (scheduledStream?.status === "queued" || scheduledStream?.status === "running")) {
2493
- status = "running";
2494
- }
2495
- return {
2496
- agent_name: thread.path.toString(),
2497
- agent_status: status
2498
- };
2499
- }
2500
- async projectTerminal(turn, thread) {
2501
- if (thread.parentChatId === null) return;
2502
- const stream = await this.#streams.store.getStream(turn.streamId);
2503
- if (!stream || stream.status !== "completed" && stream.status !== "failed" && stream.status !== "cancelled") {
2504
- return;
2505
- }
2506
- const message = (await this.#messages(thread)).find(
2507
- (candidate) => candidate.role === "assistant" && candidate.id === turn.streamId
2508
- );
2509
- if (stream.status === "completed" && this.#approvals.isPaused(message)) {
2510
- return;
2511
- }
2512
- const text = message?.role === "assistant" ? _AgentStatusProjector.#messageText(message) : "";
2513
- let content = text || "Agent completed without a text response.";
2514
- if (stream.status === "failed") {
2515
- content = `Agent failed: ${stream.error || "unknown error"}`;
2516
- } else if (stream.status === "cancelled") {
2517
- content = "Agent was interrupted.";
2518
- }
2519
- const parent = await this.#directory.load({
2520
- chatId: thread.parentChatId,
2521
- userId: thread.conversation.userId
2522
- });
2523
- await this.#mailbox.deliver(
2524
- createInterAgentCommunication({
2525
- id: `zukhruf:child-terminal:${turn.streamId}`,
2526
- type: InterAgentCommunicationTypes.FinalAnswer,
2527
- author: thread.conversation,
2528
- recipient: {
2529
- chatId: thread.parentChatId,
2530
- userId: thread.conversation.userId
2531
- },
2532
- content,
2533
- metadata: {
2534
- authorPath: thread.path.toString(),
2535
- recipientPath: parent?.path.toString() ?? thread.parentChatId,
2536
- streamId: turn.streamId,
2537
- status: stream.status
2538
- }
2539
- }),
2540
- MessageDeliveryModes.QueueOnly
2541
- );
2542
- return { finishedAt: stream.finishedAt, status: stream.status };
2543
- }
2544
- async #messages(thread) {
2545
- const engine = new ContextEngine3({
2546
- store: this.#store,
2547
- chatId: thread.conversation.chatId,
2548
- userId: thread.conversation.userId
2549
- });
2550
- return engine.getMessages();
2551
- }
2552
- static #listedStatus(status, error, head) {
2553
- switch (status) {
2554
- case "running":
2555
- return "running";
2556
- case "completed":
2557
- return {
2558
- completed: head?.role === "assistant" ? _AgentStatusProjector.#messageText(head) || null : null
2559
- };
2560
- case "failed":
2561
- return { errored: error || "Agent turn failed." };
2562
- case "cancelled":
2563
- return "interrupted";
2564
- case "queued":
2565
- case void 0:
2566
- return "pending_init";
2567
- }
2568
- }
2569
- static #messageText(message) {
2570
- return message.parts.filter(isTextUIPart).map((part) => part.text).join("\n").trim();
3046
+ async #hasForkedPrefix(child, expectedIds) {
3047
+ const branch = await this.#store.getActiveBranch(child.conversation.chatId);
3048
+ if (!branch?.headMessageId) return false;
3049
+ const chain = await this.#store.getMessageChain(branch.headMessageId);
3050
+ return expectedIds.every(
3051
+ (id, index) => chain[index]?.id === id && chain[index]?.chatId === child.conversation.chatId
3052
+ );
2571
3053
  }
2572
3054
  };
3055
+ function isInterAgentCommunication(message) {
3056
+ if (!isRecord3(message.metadata)) return false;
3057
+ if (!Object.hasOwn(message.metadata, "interAgentCommunication")) {
3058
+ return false;
3059
+ }
3060
+ const communication = message.metadata.interAgentCommunication;
3061
+ if (!isRecord3(communication) || typeof communication.triggerTurn !== "boolean") {
3062
+ throw new Error(
3063
+ `spawn_agent: message "${message.id}" has invalid inter-agent metadata`
3064
+ );
3065
+ }
3066
+ return true;
3067
+ }
3068
+ function parseHistoryForkRecord(value) {
3069
+ if (!isRecord3(value)) {
3070
+ throw new Error("spawn_agent: invalid persisted history-fork metadata");
3071
+ }
3072
+ const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } = value;
3073
+ if (!isForkTurns(forkTurns) || typeof parentChatId !== "string" || !parentChatId.trim() || parentHeadMessageId !== null && (typeof parentHeadMessageId !== "string" || parentHeadMessageId.length === 0) || sourceMessageIds !== void 0 && (!Array.isArray(sourceMessageIds) || !sourceMessageIds.every(
3074
+ (id) => typeof id === "string" && id.trim().length > 0
3075
+ ) || new Set(sourceMessageIds).size !== sourceMessageIds.length)) {
3076
+ throw new Error("spawn_agent: invalid persisted history-fork metadata");
3077
+ }
3078
+ return {
3079
+ forkTurns,
3080
+ parentChatId,
3081
+ parentHeadMessageId,
3082
+ ...sourceMessageIds === void 0 ? {} : { sourceMessageIds }
3083
+ };
3084
+ }
3085
+ function isForkTurns(value) {
3086
+ return value === "none" || value === "all";
3087
+ }
3088
+ function isEmptyAssistantPlaceholder(value) {
3089
+ return isRecord3(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
3090
+ }
2573
3091
 
2574
3092
  // packages/experimental/src/zukhruf/control-plane/agent-turn-id.ts
2575
3093
  import { v5 as uuidv53, validate as validateUuid } from "uuid";
2576
- import { z as z7 } from "zod";
3094
+ import { z as z12 } from "zod";
2577
3095
  var prefix = "zukhruf-turn";
2578
- var agentTurnIdSchema = z7.string().refine((value) => {
3096
+ var agentTurnIdSchema = z12.string().refine((value) => {
2579
3097
  const [head, scope, turn, ...rest] = value.split(":");
2580
3098
  return head === prefix && rest.length === 0 && validateUuid(scope) && validateUuid(turn);
2581
3099
  });
@@ -3128,145 +3646,10 @@ var MailboxCoordinator = class _MailboxCoordinator {
3128
3646
  }
3129
3647
  };
3130
3648
 
3131
- // packages/experimental/src/zukhruf/multi-agent-config.ts
3132
- var DEFAULT_MIN_WAIT_TIMEOUT_MS = 1e4;
3133
- var DEFAULT_WAIT_TIMEOUT_MS = 3e4;
3134
- var DEFAULT_MAX_WAIT_TIMEOUT_MS = 36e5;
3135
- var DEFAULT_MAX_CONCURRENT_THREADS_PER_SESSION = 4;
3136
- var WAIT_AGENT_USAGE_HINT_TEXT = "When calling `wait_agent`, prefer longer waits (minutes) to avoid busy polling.";
3137
- function concurrencySlotsText(maxConcurrency) {
3138
- return `There are ${maxConcurrency} available concurrency slots, meaning that up to ${maxConcurrency} agents can be active at once, including you.`;
3139
- }
3140
- var RESERVED_TOOL_NAMESPACES = /* @__PURE__ */ new Set([
3141
- "api_tool",
3142
- "browser",
3143
- "computer",
3144
- "container",
3145
- "file_search",
3146
- "functions",
3147
- "image_gen",
3148
- "multi_tool_use",
3149
- "python",
3150
- "python_user_visible",
3151
- "submodel_delegator",
3152
- "terminal",
3153
- "tool_search",
3154
- "web"
3155
- ]);
3156
- function resolveMultiAgentHostConfig(input = {}) {
3157
- const minWaitTimeoutMs = input.minWaitTimeoutMs ?? DEFAULT_MIN_WAIT_TIMEOUT_MS;
3158
- const defaultWaitTimeoutMs = input.defaultWaitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
3159
- const maxWaitTimeoutMs = input.maxWaitTimeoutMs ?? DEFAULT_MAX_WAIT_TIMEOUT_MS;
3160
- assertTimeout("minWaitTimeoutMs", minWaitTimeoutMs);
3161
- assertTimeout("defaultWaitTimeoutMs", defaultWaitTimeoutMs);
3162
- assertTimeout("maxWaitTimeoutMs", maxWaitTimeoutMs);
3163
- const maxConcurrentThreadsPerSession = input.maxConcurrentThreadsPerSession ?? DEFAULT_MAX_CONCURRENT_THREADS_PER_SESSION;
3164
- if (!Number.isSafeInteger(maxConcurrentThreadsPerSession) || maxConcurrentThreadsPerSession < 1) {
3165
- throw new Error(
3166
- "AgentRuntime: multiAgent.maxConcurrentThreadsPerSession must be a positive integer"
3167
- );
3168
- }
3169
- if (minWaitTimeoutMs > maxWaitTimeoutMs) {
3170
- throw new Error(
3171
- "AgentRuntime: multiAgent.minWaitTimeoutMs must be at most maxWaitTimeoutMs"
3172
- );
3173
- }
3174
- if (defaultWaitTimeoutMs < minWaitTimeoutMs) {
3175
- throw new Error(
3176
- "AgentRuntime: multiAgent.defaultWaitTimeoutMs must be at least minWaitTimeoutMs"
3177
- );
3178
- }
3179
- if (defaultWaitTimeoutMs > maxWaitTimeoutMs) {
3180
- throw new Error(
3181
- "AgentRuntime: multiAgent.defaultWaitTimeoutMs must be at most maxWaitTimeoutMs"
3182
- );
3183
- }
3184
- const toolNamespace = input.toolNamespace;
3185
- if (toolNamespace !== void 0 && (toolNamespace.length === 0 || toolNamespace.trim() !== toolNamespace)) {
3186
- throw new Error(
3187
- "AgentRuntime: multiAgent.toolNamespace cannot be empty or padded"
3188
- );
3189
- }
3190
- if (toolNamespace !== void 0) validateToolNamespace(toolNamespace);
3191
- const codeMode = input.nonCodeModeOnly === false;
3192
- const tool7 = (name) => codeMode ? `tools.${name}` : toolNamespace === void 0 ? name : `${toolNamespace}.${name}`;
3193
- const collaborationTools = [
3194
- "spawn_agent",
3195
- "send_message",
3196
- "followup_task",
3197
- "wait_agent",
3198
- "interrupt_agent",
3199
- "list_agents"
3200
- ].map((name) => `\`${tool7(name)}\``).join(", ");
3201
- const shared = codeMode ? `Call ${collaborationTools} from \`code_mode\`.
3202
-
3203
- All agents share the same workspace, current working directory, and filesystem.` : `Call ${collaborationTools} directly. They are intentionally unavailable inside nested code execution.
3204
-
3205
- All agents share the same workspace, current working directory, and filesystem.`;
3206
- return {
3207
- minWaitTimeoutMs,
3208
- defaultWaitTimeoutMs,
3209
- maxWaitTimeoutMs,
3210
- maxConcurrentThreadsPerSession,
3211
- usageHintText: nonEmptyText(input.usageHintText),
3212
- rootAgentUsageHintText: input.rootAgentUsageHintText === void 0 ? defaultRootUsageHint(tool7, shared, maxConcurrentThreadsPerSession) : nonEmptyText(input.rootAgentUsageHintText),
3213
- subagentUsageHintText: input.subagentUsageHintText === void 0 ? defaultSubagentUsageHint(tool7, shared, maxConcurrentThreadsPerSession) : nonEmptyText(input.subagentUsageHintText),
3214
- toolNamespace,
3215
- codeMode
3216
- };
3217
- }
3218
- function assertTimeout(name, value) {
3219
- if (!Number.isSafeInteger(value) || value < 0) {
3220
- throw new Error(
3221
- `AgentRuntime: multiAgent.${name} must be a non-negative safe integer`
3222
- );
3223
- }
3224
- }
3225
- function validateToolNamespace(namespace) {
3226
- if (namespace.length > 64 || !/^[a-zA-Z0-9_-]+$/.test(namespace) || namespace === "mcp" || namespace.startsWith("mcp__") || RESERVED_TOOL_NAMESPACES.has(namespace)) {
3227
- throw new Error(
3228
- `AgentRuntime: multiAgent.toolNamespace "${namespace}" is a reserved tool namespace or invalid`
3229
- );
3230
- }
3231
- }
3232
- function nonEmptyText(value) {
3233
- if (value === void 0) return void 0;
3234
- return value.length === 0 ? void 0 : value;
3235
- }
3236
- function defaultRootUsageHint(tool7, shared, maxConcurrency) {
3237
- return `You are \`/root\`, the primary agent in a team of agents collaborating to fulfill the user's goals.
3238
-
3239
- 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.
3240
-
3241
- 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. Every spawn must set \`fork_turns\` to \`none\`, \`all\`, or a positive count of recent turns.
3242
-
3243
- Child messages arrive as \`MESSAGE\` or \`FINAL_ANSWER\` mailbox envelopes with their task name, sender, and payload preserved.
3244
-
3245
- ${shared}
3246
-
3247
- ${WAIT_AGENT_USAGE_HINT_TEXT}
3248
-
3249
- ${concurrencySlotsText(maxConcurrency)}`;
3250
- }
3251
- function defaultSubagentUsageHint(tool7, shared, maxConcurrency) {
3252
- return `You are an agent in a team collaborating to complete a task.
3253
-
3254
- 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.
3255
-
3256
- 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.
3257
-
3258
- ${shared}
3259
-
3260
- ${WAIT_AGENT_USAGE_HINT_TEXT}
3261
-
3262
- ${concurrencySlotsText(maxConcurrency)}`;
3263
- }
3264
-
3265
3649
  // packages/experimental/src/zukhruf/runtime/agent-turn-executor.ts
3266
- import { experimental_codeModeTool } from "@ai-sdk/code-mode";
3267
3650
  import {
3268
3651
  jsonSchema,
3269
- tool
3652
+ tool as tool6
3270
3653
  } from "ai";
3271
3654
  import path2 from "node:path";
3272
3655
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
@@ -3291,7 +3674,7 @@ import {
3291
3674
  modelMessageSchema as modelMessageSchema2
3292
3675
  } from "ai";
3293
3676
  import { hash, randomUUID as randomUUID2 } from "node:crypto";
3294
- import { z as z8 } from "zod";
3677
+ import { z as z13 } from "zod";
3295
3678
 
3296
3679
  // packages/compaction/dist/index.js
3297
3680
  import {
@@ -3498,21 +3881,21 @@ ${options.instructions}` : SUMMARY_PROMPT,
3498
3881
  import {
3499
3882
  isRecord as isRecord4
3500
3883
  } from "@deepagents/context";
3501
- var checkpointSchema = z8.object({
3502
- sourceCount: z8.number().int().positive(),
3503
- sourceHash: z8.string(),
3504
- replacement: z8.array(z8.unknown()).transform(
3884
+ var checkpointSchema = z13.object({
3885
+ sourceCount: z13.number().int().positive(),
3886
+ sourceHash: z13.string(),
3887
+ replacement: z13.array(z13.unknown()).transform(
3505
3888
  (messages) => messages.map((message) => modelMessageSchema2.parse(message))
3506
3889
  )
3507
3890
  });
3508
- var cacheObservationSchema = z8.object({
3509
- scope: z8.string(),
3510
- prefixLength: z8.number().int().nonnegative(),
3511
- prefixHash: z8.string(),
3512
- startedAt: z8.number().int().nonnegative(),
3513
- retentionMs: z8.number().int().positive().optional()
3891
+ var cacheObservationSchema = z13.object({
3892
+ scope: z13.string(),
3893
+ prefixLength: z13.number().int().nonnegative(),
3894
+ prefixHash: z13.string(),
3895
+ startedAt: z13.number().int().nonnegative(),
3896
+ retentionMs: z13.number().int().positive().optional()
3514
3897
  });
3515
- var inputUsageSchema = cacheObservationSchema.pick({ scope: true, prefixLength: true, prefixHash: true }).extend({ inputTokens: z8.number().int().nonnegative() });
3898
+ var inputUsageSchema = cacheObservationSchema.pick({ scope: true, prefixLength: true, prefixHash: true }).extend({ inputTokens: z13.number().int().nonnegative() });
3516
3899
  function jsonDigest(value) {
3517
3900
  return hash("sha256", JSON.stringify(value));
3518
3901
  }
@@ -3966,7 +4349,7 @@ var AgentTurnExecutor = class {
3966
4349
  #controlPlane;
3967
4350
  #mailbox;
3968
4351
  #approvals;
3969
- #multiAgent;
4352
+ #team;
3970
4353
  #plugins;
3971
4354
  #sandboxes;
3972
4355
  #publishConversationStatus;
@@ -3976,7 +4359,7 @@ var AgentTurnExecutor = class {
3976
4359
  this.#controlPlane = options.controlPlane;
3977
4360
  this.#mailbox = options.mailbox;
3978
4361
  this.#approvals = options.approvals;
3979
- this.#multiAgent = options.multiAgent;
4362
+ this.#team = options.team;
3980
4363
  this.#plugins = options.plugins;
3981
4364
  this.#sandboxes = options.sandboxes;
3982
4365
  this.#publishConversationStatus = options.publishConversationStatus;
@@ -4004,7 +4387,9 @@ var AgentTurnExecutor = class {
4004
4387
  async #executeTurn(turn, { signal, park }) {
4005
4388
  if (await this.#projectSkippedTerminalTurn(turn)) return;
4006
4389
  const { declaration, thread } = await this.#controlPlane.resolve(turn);
4007
- const usageHint = thread.path.isRoot ? this.#multiAgent.rootAgentUsageHintText : this.#multiAgent.subagentUsageHintText;
4390
+ const usageHint = this.#team.guidance(
4391
+ thread.path.isRoot ? "root" : "subagent"
4392
+ );
4008
4393
  const engine = this.#engineFor(turn).set(
4009
4394
  ...declaration.instructions,
4010
4395
  ...usageHint === void 0 ? [] : [role(usageHint)]
@@ -4087,38 +4472,24 @@ var AgentTurnExecutor = class {
4087
4472
  }
4088
4473
  },
4089
4474
  prepareStepInput: () => this.#prepareStepInput(turn, mailboxState),
4090
- ...this.#multiAgent.codeMode ? {
4091
- experimental_toolCallers: Object.fromEntries(
4092
- Object.keys(this.#plugins.collaborationTools).map((name) => [
4093
- name,
4094
- ["code_mode"]
4095
- ])
4096
- )
4097
- } : {}
4475
+ experimental_toolCallers: this.#team.surface.toolCallers
4098
4476
  };
4099
4477
  const modelTools = {
4100
4478
  ...turn.kind === "message" ? Object.fromEntries(
4101
4479
  Object.entries(turn.tools ?? {}).map(([name, definition]) => [
4102
4480
  name,
4103
- tool({
4481
+ tool6({
4104
4482
  description: definition.description,
4105
4483
  inputSchema: jsonSchema(definition.inputSchema)
4106
4484
  })
4107
4485
  ])
4108
4486
  ) : {},
4109
4487
  ...declaration.tools,
4110
- ...this.#plugins.collaborationTools,
4111
- ...this.#multiAgent.codeMode ? { code_mode: experimental_codeModeTool() } : {},
4488
+ ...this.#team.surface.tools,
4112
4489
  ...this.#plugins.tools
4113
4490
  };
4114
- const collaborationToolsContext = {
4115
- spawn_agent: agentContext,
4116
- send_message: agentContext,
4117
- followup_task: agentContext,
4118
- list_agents: agentContext,
4119
- wait_agent: agentContext,
4120
- interrupt_agent: agentContext,
4121
- ...this.#multiAgent.codeMode ? { code_mode: agentContext } : {},
4491
+ const toolsContext = {
4492
+ ...this.#team.contextFor(agentContext),
4122
4493
  ...Object.fromEntries(
4123
4494
  Object.keys(this.#plugins.tools).map((name) => [name, pluginContext])
4124
4495
  )
@@ -4156,7 +4527,7 @@ var AgentTurnExecutor = class {
4156
4527
  onStepStart: compaction?.onStepStart,
4157
4528
  onStepEnd: compaction?.onStepEnd,
4158
4529
  include: compaction?.include,
4159
- toolsContext: collaborationToolsContext,
4530
+ toolsContext,
4160
4531
  ...elements.length > 0 ? { transform: [elementsStreamTransform] } : {}
4161
4532
  }
4162
4533
  );
@@ -4378,6 +4749,7 @@ function isSkill(value) {
4378
4749
  }
4379
4750
 
4380
4751
  // packages/experimental/src/zukhruf/runtime/conversation-sandboxes.ts
4752
+ import { SandboxNotFoundError } from "@deepagents/context";
4381
4753
  var ConversationSandboxes = class {
4382
4754
  // One memoized acquisition for each declaration and conversation.
4383
4755
  #held = /* @__PURE__ */ new Map();
@@ -4388,7 +4760,8 @@ var ConversationSandboxes = class {
4388
4760
  context.userId
4389
4761
  ]);
4390
4762
  const held = this.#held.get(key);
4391
- if (held !== void 0) return held();
4763
+ if (held !== void 0)
4764
+ return this.#existing(key, held, declaration, context);
4392
4765
  const acquiring = declaration.sandbox(context).catch((error) => {
4393
4766
  this.#held.delete(key);
4394
4767
  throw error;
@@ -4396,6 +4769,25 @@ var ConversationSandboxes = class {
4396
4769
  this.#held.set(key, () => acquiring);
4397
4770
  return acquiring;
4398
4771
  }
4772
+ /**
4773
+ * Checked before the turn, not left to its first command: the turn's tools
4774
+ * are bound to this handle, so a sandbox found gone mid-turn fails the
4775
+ * model's tool call instead of acquiring a new sandbox.
4776
+ */
4777
+ async #existing(key, held, declaration, context) {
4778
+ const handle = await held();
4779
+ try {
4780
+ await handle.sandbox.run({ command: "true" });
4781
+ return handle;
4782
+ } catch (error) {
4783
+ if (!(error instanceof SandboxNotFoundError)) throw error;
4784
+ }
4785
+ if (this.#held.get(key) === held) {
4786
+ this.#held.delete(key);
4787
+ await handle.sandbox.dispose();
4788
+ }
4789
+ return this.acquire(declaration, context);
4790
+ }
4399
4791
  async [Symbol.asyncDispose]() {
4400
4792
  await using handles = new AsyncDisposableStack();
4401
4793
  const acquired = await Promise.allSettled(
@@ -4407,199 +4799,6 @@ var ConversationSandboxes = class {
4407
4799
  }
4408
4800
  };
4409
4801
 
4410
- // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
4411
- import { tool as tool2 } from "ai";
4412
- import { z as z9 } from "zod";
4413
- var interruptAgentInputSchema = z9.object({
4414
- target: z9.string().trim().min(1).describe(
4415
- "The canonical /root/... path, or a descendant-relative target name."
4416
- )
4417
- });
4418
- var interruptAgentOutputSchema = z9.object({ previous_status: listedAgentStatusSchema }).strict();
4419
- var interruptAgentTool = tool2({
4420
- description: "Interrupt an agent's current turn, if any, and return its previous status. The agent remains available for messages and follow-up tasks.",
4421
- inputSchema: interruptAgentInputSchema,
4422
- outputSchema: interruptAgentOutputSchema,
4423
- execute: async (input, { context }) => context.controlPlane.interruptAgent(context.actor, input)
4424
- });
4425
-
4426
- // packages/experimental/src/zukhruf/collaboration/list-agents.ts
4427
- import { tool as tool3 } from "ai";
4428
- import { z as z10 } from "zod";
4429
- var listAgentsInputSchema = z10.object({
4430
- path_prefix: z10.string().trim().min(1).describe(
4431
- "Task-path prefix without a trailing slash. Omit to list the whole tree."
4432
- ).optional()
4433
- });
4434
- var listAgentsOutputSchema = z10.object({ agents: z10.array(listedAgentSchema) }).strict();
4435
- var listAgentsTool = tool3({
4436
- description: "List live agents in the current root thread tree. Optionally filter by task-path prefix.",
4437
- inputSchema: listAgentsInputSchema,
4438
- outputSchema: listAgentsOutputSchema,
4439
- execute: async ({ path_prefix }, { context }) => context.controlPlane.listAgents(context.actor, path_prefix)
4440
- });
4441
-
4442
- // packages/experimental/src/zukhruf/collaboration/message-tools.ts
4443
- import { tool as tool4 } from "ai";
4444
- import { z as z11 } from "zod";
4445
- var agentMessageInputSchema = z11.object({
4446
- target: z11.string().trim().min(1).describe(
4447
- "The canonical /root/... path, or a descendant-relative target name."
4448
- ),
4449
- message: z11.string().trim().min(1).describe("The message or follow-up task.")
4450
- });
4451
- var sendMessageTool = tool4({
4452
- description: "Queue a message for another agent. Address siblings with their canonical /root/... path.",
4453
- inputSchema: agentMessageInputSchema,
4454
- execute: async (input, { context }) => {
4455
- await context.controlPlane.sendMessage(context.actor, input);
4456
- return "";
4457
- }
4458
- });
4459
- var followupTaskTool = tool4({
4460
- description: "Send a follow-up task to an existing non-root agent and wake its thread.",
4461
- inputSchema: agentMessageInputSchema,
4462
- execute: async (input, { context }) => {
4463
- await context.controlPlane.followupTask(context.actor, input);
4464
- return "";
4465
- }
4466
- });
4467
-
4468
- // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
4469
- import { tool as tool5 } from "ai";
4470
- import { z as z12 } from "zod";
4471
-
4472
- // packages/experimental/src/zukhruf/control-plane/fork-turns.ts
4473
- var forkTurnsError = "fork_turns must be `none`, `all`, or a positive integer string";
4474
- function parseForkTurns(value) {
4475
- const normalized = value.trim().toLowerCase();
4476
- if (normalized === "none" || normalized === "all") return normalized;
4477
- if (!/^\d+$/.test(normalized)) return void 0;
4478
- const turns = Number(normalized);
4479
- return Number.isSafeInteger(turns) && turns > 0 ? turns : void 0;
4480
- }
4481
-
4482
- // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
4483
- var spawnAgentInputSchema = z12.object({
4484
- agent_type: z12.string().trim().min(1).describe("The name of one available subagent declaration."),
4485
- task_name: z12.string().trim().min(1).refine(
4486
- (value) => value !== "." && value !== ".." && !value.includes("/"),
4487
- "task_name must be one non-empty path segment"
4488
- ).describe("One path segment naming this independent agent task."),
4489
- message: z12.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent."),
4490
- fork_turns: z12.string().trim().refine((value) => parseForkTurns(value) !== void 0, forkTurnsError).describe(
4491
- "Required number of parent turns to fork. Use `none`, `all`, or a positive integer string such as `3`."
4492
- )
4493
- });
4494
- var spawnAgentOutputSchema = z12.object({ task_name: z12.string() }).strict();
4495
- function createSpawnAgentTool(options) {
4496
- return tool5({
4497
- description: ({ context }) => {
4498
- const available = (context.actor.declaration.subagents ?? []).map(
4499
- ({ name, description }) => description ? `${name}: ${description}` : name
4500
- ).join(", ");
4501
- return [
4502
- `Spawn an independent subagent. Available agent types: ${available || "none"}.`,
4503
- options?.usageHintText
4504
- ].filter(Boolean).join(" ");
4505
- },
4506
- inputSchema: spawnAgentInputSchema,
4507
- outputSchema: spawnAgentOutputSchema,
4508
- execute: async ({ agent_type, task_name, message, fork_turns }, { context }) => {
4509
- const forkTurns = parseForkTurns(fork_turns);
4510
- if (forkTurns === void 0) throw new Error(forkTurnsError);
4511
- return context.controlPlane.spawn(context.actor, {
4512
- agentType: agent_type,
4513
- taskName: task_name,
4514
- message,
4515
- forkTurns
4516
- });
4517
- }
4518
- });
4519
- }
4520
-
4521
- // packages/experimental/src/zukhruf/collaboration/wait-agent.ts
4522
- import { tool as tool6 } from "ai";
4523
- import { z as z13 } from "zod";
4524
- var waitAgentOutputSchema = z13.object({ message: z13.string(), timed_out: z13.boolean() }).strict();
4525
- function createWaitAgentTool(options) {
4526
- const waitAgentInputSchema = z13.object({
4527
- timeout_ms: z13.number().int().max(options.maxTimeoutMs).optional().describe("Maximum time to wait in milliseconds.")
4528
- });
4529
- return tool6({
4530
- description: "Wait for pending mail addressed to this agent without consuming it.",
4531
- inputSchema: waitAgentInputSchema,
4532
- outputSchema: waitAgentOutputSchema,
4533
- execute: async ({ timeout_ms }, { abortSignal, context }) => {
4534
- const timeoutMs = Math.max(
4535
- timeout_ms ?? options.defaultTimeoutMs,
4536
- options.minTimeoutMs
4537
- );
4538
- const received = await context.controlPlane.waitForMailbox(
4539
- context.actor,
4540
- {
4541
- timeoutMs,
4542
- signal: abortSignal
4543
- }
4544
- );
4545
- const message = received ? "Wait completed." : "Wait timed out.";
4546
- return {
4547
- message: timeout_ms !== void 0 && timeout_ms < timeoutMs ? `${message}
4548
-
4549
- Requested timeout of ${timeout_ms}ms was clamped to the minimum of ${timeoutMs}ms.` : message,
4550
- timed_out: !received
4551
- };
4552
- }
4553
- });
4554
- }
4555
-
4556
- // packages/experimental/src/zukhruf/collaboration/collaboration-tools.ts
4557
- var NAMESPACE_DESCRIPTION = "Tools for spawning and managing sub-agents.";
4558
- function createCollaborationTools(config) {
4559
- return {
4560
- spawn_agent: configureTool(
4561
- createSpawnAgentTool({ usageHintText: config.usageHintText }),
4562
- config
4563
- ),
4564
- send_message: configureTool(sendMessageTool, config),
4565
- followup_task: configureTool(followupTaskTool, config),
4566
- list_agents: configureTool(listAgentsTool, config),
4567
- wait_agent: configureTool(
4568
- createWaitAgentTool({
4569
- minTimeoutMs: config.minWaitTimeoutMs,
4570
- defaultTimeoutMs: config.defaultWaitTimeoutMs,
4571
- maxTimeoutMs: config.maxWaitTimeoutMs
4572
- }),
4573
- config
4574
- ),
4575
- interrupt_agent: configureTool(interruptAgentTool, config)
4576
- };
4577
- }
4578
- function configureTool(collaborationTool, config) {
4579
- const openai = collaborationTool.providerOptions?.openai;
4580
- return {
4581
- ...collaborationTool,
4582
- providerOptions: {
4583
- ...collaborationTool.providerOptions,
4584
- ...config.toolNamespace === void 0 ? {} : {
4585
- openai: {
4586
- ...typeof openai === "object" && openai !== null ? openai : {},
4587
- namespace: {
4588
- name: config.toolNamespace,
4589
- description: NAMESPACE_DESCRIPTION
4590
- }
4591
- }
4592
- }
4593
- },
4594
- metadata: {
4595
- ...collaborationTool.metadata,
4596
- zukhruf: {
4597
- kind: "collaboration"
4598
- }
4599
- }
4600
- };
4601
- }
4602
-
4603
4802
  // packages/experimental/src/zukhruf/runtime/plugin/plugin-agents.ts
4604
4803
  import { readFileSync as readFileSync2, readdirSync as readdirSync2 } from "node:fs";
4605
4804
  import { basename, extname, join } from "node:path";
@@ -4901,7 +5100,6 @@ function initializedFrom(plugin, definition) {
4901
5100
  return plugin.definition === definition;
4902
5101
  }
4903
5102
  var PluginManager = class {
4904
- collaborationTools;
4905
5103
  declarations;
4906
5104
  agentOwners;
4907
5105
  tools;
@@ -4911,7 +5109,7 @@ var PluginManager = class {
4911
5109
  #toolComposition;
4912
5110
  #resources = new AsyncDisposableStack();
4913
5111
  #running = [];
4914
- constructor(root, bindings, multiAgent) {
5112
+ constructor(root, bindings, team) {
4915
5113
  let configuredRoot = root;
4916
5114
  const pluginBindings = new PluginBindings(root.plugins, bindings);
4917
5115
  const plugins = [];
@@ -4925,10 +5123,7 @@ var PluginManager = class {
4925
5123
  }
4926
5124
  const pluginSkills = new PluginSkillComposition();
4927
5125
  const pluginContext = new PluginContextComposition();
4928
- const collaborationTools = createCollaborationTools(multiAgent);
4929
- const reservedToolNames = Object.keys(collaborationTools);
4930
- if (multiAgent.codeMode) reservedToolNames.push("code_mode");
4931
- const toolComposition = new PluginToolComposition(reservedToolNames);
5126
+ const toolComposition = new PluginToolComposition(team.reservedToolNames);
4932
5127
  for (const { definition, instance } of plugins) {
4933
5128
  if (instance.tools) {
4934
5129
  toolComposition.add(definition.name, instance.tools);
@@ -4951,7 +5146,6 @@ var PluginManager = class {
4951
5146
  const pluginSkillsByAgent = pluginSkills.compose(declarations.values());
4952
5147
  const pluginTools = toolComposition.compose(declarations.values());
4953
5148
  this.#plugins = plugins;
4954
- this.collaborationTools = collaborationTools;
4955
5149
  this.declarations = declarations;
4956
5150
  this.agentOwners = pluginAgents.owners;
4957
5151
  this.tools = pluginTools;
@@ -4990,9 +5184,9 @@ var PluginManager = class {
4990
5184
  ({ running }) => Boolean(running.conversationAvailable)
4991
5185
  );
4992
5186
  }
4993
- async startWorkers(workers, waitForActive) {
5187
+ async startWorkers(workers) {
4994
5188
  for (const { running } of this.#running) {
4995
- if (running.work) workers.use(await running.work(waitForActive));
5189
+ if (running.work) workers.use(await running.work());
4996
5190
  }
4997
5191
  }
4998
5192
  async initialize(host) {
@@ -5160,9 +5354,9 @@ var RuntimeHost = class {
5160
5354
  #pluginHost;
5161
5355
  constructor(root, options, resources) {
5162
5356
  this.#resources = resources;
5163
- const multiAgent = resolveMultiAgentHostConfig(options.multiAgent);
5357
+ const team = options.multiAgent ?? Team.codex();
5164
5358
  const plugins = resources.use(
5165
- new PluginManager(root, options.bindings, multiAgent)
5359
+ new PluginManager(root, options.bindings, team)
5166
5360
  );
5167
5361
  const declarations = plugins.declarations;
5168
5362
  const { storage } = options;
@@ -5179,7 +5373,7 @@ var RuntimeHost = class {
5179
5373
  const residency = new AgentResidency({
5180
5374
  storage,
5181
5375
  directory,
5182
- maxConcurrentThreadsPerSession: multiAgent.maxConcurrentThreadsPerSession,
5376
+ maxConcurrentThreadsPerSession: team.maxConcurrentThreads,
5183
5377
  publish: (conversation) => conversationStatus.publish(conversation)
5184
5378
  });
5185
5379
  const mailbox = new MailboxCoordinator({
@@ -5241,7 +5435,7 @@ var RuntimeHost = class {
5241
5435
  controlPlane,
5242
5436
  mailbox,
5243
5437
  approvals,
5244
- multiAgent,
5438
+ team,
5245
5439
  plugins,
5246
5440
  sandboxes,
5247
5441
  publishConversationStatus: (conversation) => conversationStatus.publish(conversation)
@@ -5278,13 +5472,31 @@ var RuntimeHost = class {
5278
5472
  plugin(definition) {
5279
5473
  return this.#plugins.get(definition);
5280
5474
  }
5475
+ /** Creates the root chat, or keeps a chat of a tree this runtime owns (its root or a sub-agent); any other chat reads as absent. */
5281
5476
  async createSession(conversation) {
5282
- await this.#controlPlane.resolve(conversation);
5477
+ const thread = await this.#directory.load(conversation) ?? (await this.#controlPlane.resolve(conversation)).thread;
5478
+ if (!await this.#ownsTree(thread)) {
5479
+ throw new ConversationNotFoundError(conversation.chatId);
5480
+ }
5283
5481
  }
5284
5482
  async sessionExists(conversation) {
5285
5483
  const chat2 = await this.#store.getChat(conversation.chatId);
5286
5484
  if (!chat2 || chat2.userId !== conversation.userId) return false;
5287
- return (await this.#directory.load(conversation))?.path.isRoot ?? false;
5485
+ const thread = await this.#directory.load(conversation);
5486
+ return thread !== void 0 && this.#ownsRoot(thread);
5487
+ }
5488
+ /** A root thread this runtime's root declaration started. */
5489
+ #ownsRoot(thread) {
5490
+ return thread.path.isRoot && thread.declarationName === this.info.root;
5491
+ }
5492
+ /** A thread of a tree this runtime's root declaration started: that root, or a sub-agent under it. */
5493
+ async #ownsTree(thread) {
5494
+ if (thread.path.isRoot) return this.#ownsRoot(thread);
5495
+ const root = await this.#directory.load({
5496
+ chatId: thread.treeId,
5497
+ userId: thread.conversation.userId
5498
+ });
5499
+ return root !== void 0 && this.#ownsRoot(root);
5288
5500
  }
5289
5501
  async enqueue(conversation, turn) {
5290
5502
  const streamId = await this.#controlPlane.enqueue(conversation, turn);
@@ -5317,8 +5529,9 @@ var RuntimeHost = class {
5317
5529
  subscribeConversationStatus(signal) {
5318
5530
  return this.#conversationStatus.subscribe(signal);
5319
5531
  }
5532
+ /** Available unless its status is `active`: a failed latest turn is no reason to hold work back. */
5320
5533
  async #isConversationAvailable(conversation) {
5321
- return await this.#queue.getTurnActivity(conversation) === "idle" && !await this.#approvals.isConversationPaused(conversation);
5534
+ return (await this.#conversationStatus.read(conversation)).type !== "active";
5322
5535
  }
5323
5536
  async #readConversationMetadata(conversation) {
5324
5537
  const chat2 = await this.#store.getChat(conversation.chatId);
@@ -5344,7 +5557,7 @@ var RuntimeHost = class {
5344
5557
  }
5345
5558
  return [];
5346
5559
  }
5347
- return thread.path.isRoot && thread.declarationName === this.info.root ? [{ chat: chat2, conversation }] : [];
5560
+ return this.#ownsRoot(thread) ? [{ chat: chat2, conversation }] : [];
5348
5561
  });
5349
5562
  return Promise.all(
5350
5563
  roots.map(async ({ chat: chat2, conversation }) => ({
@@ -5373,12 +5586,11 @@ var RuntimeHost = class {
5373
5586
  }
5374
5587
  async #startWorkers(options) {
5375
5588
  await using workers = new AsyncDisposableStack();
5376
- await this.#plugins.startWorkers(workers, true);
5589
+ await this.#plugins.startWorkers(workers);
5377
5590
  const reconcilesAvailability = this.#plugins.reconcilesAvailability;
5378
5591
  workers.use(
5379
5592
  await this.#queue.consume(this.#executor.execute.bind(this.#executor), {
5380
5593
  concurrency: options?.concurrency,
5381
- waitForActive: true,
5382
5594
  onOrphaned: this.#onOrphaned.bind(this),
5383
5595
  onSettled: async ({ chatId, userId }) => {
5384
5596
  await this.#conversationStatus.publish({ chatId, userId });