@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
@@ -21,6 +21,708 @@ function defineAgent(declaration) {
21
21
  };
22
22
  }
23
23
 
24
+ // packages/experimental/src/zukhruf/collaboration/code-mode-tools.ts
25
+ import { experimental_codeModeTool } from "@ai-sdk/code-mode";
26
+
27
+ // packages/experimental/src/zukhruf/collaboration/tool-exposure.ts
28
+ var ToolExposure = class {
29
+ listed(toolNames) {
30
+ return toolNames.map((name) => `\`${this.toolName(name)}\``).join(", ");
31
+ }
32
+ };
33
+
34
+ // packages/experimental/src/zukhruf/collaboration/code-mode-tools.ts
35
+ var CodeModeTools = class extends ToolExposure {
36
+ toolName(name) {
37
+ return `tools.${name}`;
38
+ }
39
+ callLine(toolNames) {
40
+ return `Call ${this.listed(toolNames)} from \`code_mode\`.`;
41
+ }
42
+ tool(collaborationTool) {
43
+ return collaborationTool;
44
+ }
45
+ surface(collaborationTools) {
46
+ const tools = {
47
+ ...collaborationTools,
48
+ code_mode: experimental_codeModeTool()
49
+ };
50
+ return {
51
+ tools,
52
+ reservedToolNames: Object.keys(tools),
53
+ toolCallers: Object.fromEntries(
54
+ Object.keys(collaborationTools).map((name) => [
55
+ name,
56
+ ["code_mode"]
57
+ ])
58
+ )
59
+ };
60
+ }
61
+ callerContext(context) {
62
+ return { code_mode: context };
63
+ }
64
+ };
65
+
66
+ // packages/experimental/src/zukhruf/collaboration/message-tools.ts
67
+ import { tool } from "ai";
68
+ import { z } from "zod";
69
+ var agentMessageInputSchema = z.object({
70
+ target: z.string().trim().min(1).describe(
71
+ "The canonical /root/... path, or a descendant-relative target name."
72
+ ),
73
+ message: z.string().trim().min(1).describe("The message or follow-up task.")
74
+ });
75
+ var sendMessageTool = tool({
76
+ description: "Queue a message for another agent. Address siblings with their canonical /root/... path.",
77
+ inputSchema: agentMessageInputSchema,
78
+ execute: async (input, { context }) => {
79
+ await context.controlPlane.sendMessage(context.actor, input);
80
+ return "";
81
+ }
82
+ });
83
+ var followupTaskTool = tool({
84
+ description: "Send a follow-up task to an existing non-root agent and wake its thread.",
85
+ inputSchema: agentMessageInputSchema,
86
+ execute: async (input, { context }) => {
87
+ await context.controlPlane.followupTask(context.actor, input);
88
+ return "";
89
+ }
90
+ });
91
+
92
+ // packages/experimental/src/zukhruf/collaboration/direct-messaging.ts
93
+ var DirectMessaging = class {
94
+ tools = {
95
+ send_message: sendMessageTool,
96
+ followup_task: followupTaskTool
97
+ };
98
+ guidance(role3, name) {
99
+ return {
100
+ uses: [
101
+ `\`${name("followup_task")}\` to assign a new task and trigger a turn`,
102
+ role3 === "root" ? `\`${name("send_message")}\` to queue a message without triggering a turn` : `\`${name("send_message")}\` to queue a message for another agent`
103
+ ]
104
+ };
105
+ }
106
+ };
107
+
108
+ // packages/experimental/src/zukhruf/collaboration/direct-tools.ts
109
+ var NAMESPACE_DESCRIPTION = "Tools for spawning and managing sub-agents.";
110
+ var DirectTools = class extends ToolExposure {
111
+ #namespace;
112
+ constructor(namespace) {
113
+ super();
114
+ this.#namespace = namespace;
115
+ }
116
+ toolName(name) {
117
+ return this.#namespace?.qualify(name) ?? name;
118
+ }
119
+ callLine(toolNames) {
120
+ return `Call ${this.listed(toolNames)} directly. They are intentionally unavailable inside nested code execution.`;
121
+ }
122
+ tool(collaborationTool) {
123
+ const openai = collaborationTool.providerOptions?.openai;
124
+ return {
125
+ ...collaborationTool,
126
+ providerOptions: {
127
+ ...collaborationTool.providerOptions,
128
+ ...this.#namespace === void 0 ? {} : {
129
+ openai: {
130
+ ...typeof openai === "object" && openai !== null ? openai : {},
131
+ namespace: {
132
+ name: this.#namespace.name,
133
+ description: NAMESPACE_DESCRIPTION
134
+ }
135
+ }
136
+ }
137
+ }
138
+ };
139
+ }
140
+ surface(collaborationTools) {
141
+ return {
142
+ tools: collaborationTools,
143
+ reservedToolNames: Object.keys(collaborationTools),
144
+ toolCallers: void 0
145
+ };
146
+ }
147
+ callerContext() {
148
+ return {};
149
+ }
150
+ };
151
+
152
+ // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
153
+ import { tool as tool2 } from "ai";
154
+ import { z as z2 } from "zod";
155
+
156
+ // packages/experimental/src/zukhruf/control-plane/fork-turns.ts
157
+ var forkTurnsError = "fork_turns must be `none` or `all`";
158
+ function parseForkTurns(value) {
159
+ const normalized = value?.trim().toLowerCase() || "all";
160
+ return normalized === "none" || normalized === "all" ? normalized : void 0;
161
+ }
162
+
163
+ // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
164
+ var spawnAgentInputSchema = z2.object({
165
+ agent_type: z2.string().trim().min(1).describe("The name of one available subagent declaration."),
166
+ task_name: z2.string().trim().min(1).refine(
167
+ (value) => value !== "." && value !== ".." && !value.includes("/"),
168
+ "task_name must be one non-empty path segment"
169
+ ).describe("One path segment naming this independent agent task."),
170
+ message: z2.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent."),
171
+ fork_turns: z2.string({ error: forkTurnsError }).optional().refine((value) => parseForkTurns(value) !== void 0, forkTurnsError).describe(
172
+ "Parent history to inherit. Defaults to `all`; use `none` to start without parent history. Only `all` and `none` are supported."
173
+ )
174
+ });
175
+ var spawnAgentOutputSchema = z2.object({ task_name: z2.string() }).strict();
176
+ function createSpawnAgentTool(options) {
177
+ return tool2({
178
+ description: ({ context }) => {
179
+ const available = (context.actor.declaration.subagents ?? []).map(
180
+ ({ name, description }) => description ? `${name}: ${description}` : name
181
+ ).join(", ");
182
+ return [
183
+ `Spawn an independent subagent. Available agent types: ${available || "none"}.`,
184
+ options?.usageHintText
185
+ ].filter(Boolean).join(" ");
186
+ },
187
+ inputSchema: spawnAgentInputSchema,
188
+ outputSchema: spawnAgentOutputSchema,
189
+ execute: async ({ agent_type, task_name, message, fork_turns }, { context }) => {
190
+ const forkTurns = parseForkTurns(fork_turns);
191
+ if (forkTurns === void 0) throw new Error(forkTurnsError);
192
+ return context.controlPlane.spawn(context.actor, {
193
+ agentType: agent_type,
194
+ taskName: task_name,
195
+ message,
196
+ forkTurns
197
+ });
198
+ }
199
+ });
200
+ }
201
+
202
+ // packages/experimental/src/zukhruf/collaboration/spawning.ts
203
+ var Spawning = class {
204
+ tools;
205
+ /** `usageHintText` is appended to the `spawn_agent` description. */
206
+ constructor({ usageHintText } = {}) {
207
+ this.tools = { spawn_agent: createSpawnAgentTool({ usageHintText }) };
208
+ }
209
+ guidance(role3, name) {
210
+ const spawnAgent = `\`${name("spawn_agent")}\``;
211
+ if (role3 === "root") {
212
+ return {
213
+ 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.",
214
+ uses: [`${spawnAgent} to create an agent`],
215
+ notes: "You can decide how much context you want to propagate to your sub-agents with the `fork_turns` parameter."
216
+ };
217
+ }
218
+ return {
219
+ intro: "You can spawn declared sub-agents recursively. All agents are equally capable and receive the tools declared for their agent type.",
220
+ uses: [`${spawnAgent} to create one`]
221
+ };
222
+ }
223
+ };
224
+
225
+ // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
226
+ import { tool as tool3 } from "ai";
227
+ import { z as z4 } from "zod";
228
+
229
+ // packages/experimental/src/zukhruf/control-plane/agent-status-projector.ts
230
+ import { isTextUIPart } from "ai";
231
+ import { z as z3 } from "zod";
232
+ import {
233
+ ContextEngine
234
+ } from "@deepagents/context";
235
+
236
+ // packages/experimental/src/zukhruf/mailbox/types.ts
237
+ import { randomUUID } from "node:crypto";
238
+ var MessageDeliveryModes = {
239
+ QueueOnly: "queue-only",
240
+ TriggerTurn: "trigger-turn"
241
+ };
242
+ var InterAgentCommunicationTypes = {
243
+ Message: "MESSAGE",
244
+ NewTask: "NEW_TASK",
245
+ FinalAnswer: "FINAL_ANSWER"
246
+ };
247
+ function createInterAgentCommunication(communication) {
248
+ const value = {
249
+ ...communication,
250
+ id: communication.id ?? randomUUID(),
251
+ type: communication.type ?? InterAgentCommunicationTypes.Message,
252
+ otherRecipients: communication.otherRecipients ?? [],
253
+ triggerTurn: false
254
+ };
255
+ assertCommunication(value);
256
+ return value;
257
+ }
258
+ function assertCommunication(communication) {
259
+ if (!communication.id.trim()) {
260
+ throw new Error("inter-agent communication id cannot be empty");
261
+ }
262
+ if (!Object.values(InterAgentCommunicationTypes).includes(communication.type)) {
263
+ throw new Error("inter-agent communication type is invalid");
264
+ }
265
+ assertConversationId(communication.author, "author");
266
+ assertConversationId(communication.recipient, "recipient");
267
+ for (const recipient of communication.otherRecipients) {
268
+ assertConversationId(recipient, "other recipient");
269
+ }
270
+ if (!communication.content.trim()) {
271
+ throw new Error("inter-agent communication content cannot be empty");
272
+ }
273
+ }
274
+ function assertConversationId(value, label) {
275
+ if (!value.chatId.trim() || !value.userId.trim()) {
276
+ throw new Error(
277
+ `inter-agent communication ${label} requires chatId and userId`
278
+ );
279
+ }
280
+ }
281
+
282
+ // packages/experimental/src/zukhruf/control-plane/agent-status-projector.ts
283
+ var listedAgentStatusSchema = z3.union([
284
+ z3.enum(["pending_init", "running", "interrupted", "shutdown", "not_found"]),
285
+ z3.object({ completed: z3.string().nullable() }).strict(),
286
+ z3.object({ errored: z3.string() }).strict()
287
+ ]);
288
+ var listedAgentSchema = z3.object({
289
+ agent_name: z3.string(),
290
+ agent_status: listedAgentStatusSchema
291
+ }).strict();
292
+ var AgentStatusProjector = class _AgentStatusProjector {
293
+ #store;
294
+ #streams;
295
+ #queue;
296
+ #mailbox;
297
+ #directory;
298
+ #approvals;
299
+ constructor(options) {
300
+ this.#store = options.store;
301
+ this.#streams = options.streams;
302
+ this.#queue = options.queue;
303
+ this.#mailbox = options.mailbox;
304
+ this.#directory = options.directory;
305
+ this.#approvals = options.approvals;
306
+ }
307
+ async projectListedAgent(currentTurn, thread) {
308
+ const messages = await this.#messages(thread);
309
+ const head = messages.at(-1);
310
+ const streamId = thread.lastTurnId ?? (head?.role === "assistant" ? head.id : void 0);
311
+ const stream = streamId ? await this.#streams.store.getStream(streamId) : void 0;
312
+ const scheduledTurn = await this.#queue.getCurrentTurn(thread.conversation);
313
+ const scheduledStream = scheduledTurn ? await this.#streams.store.getStream(scheduledTurn.streamId) : void 0;
314
+ let status = _AgentStatusProjector.#listedStatus(
315
+ stream?.status,
316
+ stream?.error,
317
+ head
318
+ );
319
+ if (stream?.status === "completed" && this.#approvals.isPaused(head)) {
320
+ status = "running";
321
+ }
322
+ if (thread.conversation.chatId === currentTurn.chatId || thread.lastTurnId !== void 0 && scheduledTurn?.streamId !== thread.lastTurnId && (scheduledStream?.status === "queued" || scheduledStream?.status === "running")) {
323
+ status = "running";
324
+ }
325
+ return {
326
+ agent_name: thread.path.toString(),
327
+ agent_status: status
328
+ };
329
+ }
330
+ async projectTerminal(turn, thread) {
331
+ if (thread.parentChatId === null) return;
332
+ const stream = await this.#streams.store.getStream(turn.streamId);
333
+ if (!stream || stream.status !== "completed" && stream.status !== "failed" && stream.status !== "cancelled") {
334
+ return;
335
+ }
336
+ const message = (await this.#messages(thread)).find(
337
+ (candidate) => candidate.role === "assistant" && candidate.id === turn.streamId
338
+ );
339
+ if (stream.status === "completed" && this.#approvals.isPaused(message)) {
340
+ return;
341
+ }
342
+ const text = message?.role === "assistant" ? _AgentStatusProjector.#messageText(message) : "";
343
+ let content = text || "Agent completed without a text response.";
344
+ if (stream.status === "failed") {
345
+ content = `Agent failed: ${stream.error || "unknown error"}`;
346
+ } else if (stream.status === "cancelled") {
347
+ content = "Agent was interrupted.";
348
+ }
349
+ const parent = await this.#directory.load({
350
+ chatId: thread.parentChatId,
351
+ userId: thread.conversation.userId
352
+ });
353
+ await this.#mailbox.deliver(
354
+ createInterAgentCommunication({
355
+ id: `zukhruf:child-terminal:${turn.streamId}`,
356
+ type: InterAgentCommunicationTypes.FinalAnswer,
357
+ author: thread.conversation,
358
+ recipient: {
359
+ chatId: thread.parentChatId,
360
+ userId: thread.conversation.userId
361
+ },
362
+ content,
363
+ metadata: {
364
+ authorPath: thread.path.toString(),
365
+ recipientPath: parent?.path.toString() ?? thread.parentChatId,
366
+ streamId: turn.streamId,
367
+ status: stream.status
368
+ }
369
+ }),
370
+ MessageDeliveryModes.QueueOnly
371
+ );
372
+ return { finishedAt: stream.finishedAt, status: stream.status };
373
+ }
374
+ async #messages(thread) {
375
+ const engine = new ContextEngine({
376
+ store: this.#store,
377
+ chatId: thread.conversation.chatId,
378
+ userId: thread.conversation.userId
379
+ });
380
+ return engine.getMessages();
381
+ }
382
+ static #listedStatus(status, error, head) {
383
+ switch (status) {
384
+ case "running":
385
+ return "running";
386
+ case "completed":
387
+ return {
388
+ completed: head?.role === "assistant" ? _AgentStatusProjector.#messageText(head) || null : null
389
+ };
390
+ case "failed":
391
+ return { errored: error || "Agent turn failed." };
392
+ case "cancelled":
393
+ return "interrupted";
394
+ case "queued":
395
+ case void 0:
396
+ return "pending_init";
397
+ }
398
+ }
399
+ static #messageText(message) {
400
+ return message.parts.filter(isTextUIPart).map((part) => part.text).join("\n").trim();
401
+ }
402
+ };
403
+
404
+ // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
405
+ var interruptAgentInputSchema = z4.object({
406
+ target: z4.string().trim().min(1).describe(
407
+ "The canonical /root/... path, or a descendant-relative target name."
408
+ )
409
+ });
410
+ var interruptAgentOutputSchema = z4.object({ previous_status: listedAgentStatusSchema }).strict();
411
+ var interruptAgentTool = tool3({
412
+ description: "Interrupt an agent's current turn, if any, and return its previous status. The agent remains available for messages and follow-up tasks.",
413
+ inputSchema: interruptAgentInputSchema,
414
+ outputSchema: interruptAgentOutputSchema,
415
+ execute: async (input, { context }) => context.controlPlane.interruptAgent(context.actor, input)
416
+ });
417
+
418
+ // packages/experimental/src/zukhruf/collaboration/list-agents.ts
419
+ import { tool as tool4 } from "ai";
420
+ import { z as z5 } from "zod";
421
+ var listAgentsInputSchema = z5.object({
422
+ path_prefix: z5.string().trim().min(1).describe(
423
+ "Task-path prefix without a trailing slash. Omit to list the whole tree."
424
+ ).optional()
425
+ });
426
+ var listAgentsOutputSchema = z5.object({ agents: z5.array(listedAgentSchema) }).strict();
427
+ var listAgentsTool = tool4({
428
+ description: "List live agents in the current root thread tree. Optionally filter by task-path prefix.",
429
+ inputSchema: listAgentsInputSchema,
430
+ outputSchema: listAgentsOutputSchema,
431
+ execute: async ({ path_prefix }, { context }) => context.controlPlane.listAgents(context.actor, path_prefix)
432
+ });
433
+
434
+ // packages/experimental/src/zukhruf/collaboration/supervision.ts
435
+ var Supervision = class {
436
+ tools = {
437
+ interrupt_agent: interruptAgentTool,
438
+ list_agents: listAgentsTool
439
+ };
440
+ guidance() {
441
+ return {};
442
+ }
443
+ };
444
+
445
+ // packages/experimental/src/zukhruf/collaboration/wait-agent.ts
446
+ import { tool as tool5 } from "ai";
447
+ import { z as z6 } from "zod";
448
+ var waitAgentOutputSchema = z6.object({ message: z6.string(), timed_out: z6.boolean() }).strict();
449
+ function createWaitAgentTool(options) {
450
+ const waitAgentInputSchema = z6.object({
451
+ timeout_ms: z6.number().int().max(options.maxTimeoutMs).optional().describe("Maximum time to wait in milliseconds.")
452
+ });
453
+ return tool5({
454
+ description: "Wait for pending mail addressed to this agent without consuming it.",
455
+ inputSchema: waitAgentInputSchema,
456
+ outputSchema: waitAgentOutputSchema,
457
+ execute: async ({ timeout_ms }, { abortSignal, context }) => {
458
+ const timeoutMs = Math.max(
459
+ timeout_ms ?? options.defaultTimeoutMs,
460
+ options.minTimeoutMs
461
+ );
462
+ const received = await context.controlPlane.waitForMailbox(
463
+ context.actor,
464
+ {
465
+ timeoutMs,
466
+ signal: abortSignal
467
+ }
468
+ );
469
+ const message = received ? "Wait completed." : "Wait timed out.";
470
+ return {
471
+ message: timeout_ms !== void 0 && timeout_ms < timeoutMs ? `${message}
472
+
473
+ Requested timeout of ${timeout_ms}ms was clamped to the minimum of ${timeoutMs}ms.` : message,
474
+ timed_out: !received
475
+ };
476
+ }
477
+ });
478
+ }
479
+
480
+ // packages/experimental/src/zukhruf/collaboration/wait-bounds.ts
481
+ var WaitBounds = class {
482
+ minMs;
483
+ defaultMs;
484
+ maxMs;
485
+ constructor({
486
+ minMs = 1e4,
487
+ defaultMs = 3e4,
488
+ maxMs = 36e5
489
+ } = {}) {
490
+ assertTimeout("minMs", minMs);
491
+ assertTimeout("defaultMs", defaultMs);
492
+ assertTimeout("maxMs", maxMs);
493
+ if (minMs > maxMs) {
494
+ throw new Error("AgentRuntime: WaitBounds minMs must be at most maxMs");
495
+ }
496
+ if (defaultMs < minMs) {
497
+ throw new Error(
498
+ "AgentRuntime: WaitBounds defaultMs must be at least minMs"
499
+ );
500
+ }
501
+ if (defaultMs > maxMs) {
502
+ throw new Error(
503
+ "AgentRuntime: WaitBounds defaultMs must be at most maxMs"
504
+ );
505
+ }
506
+ this.minMs = minMs;
507
+ this.defaultMs = defaultMs;
508
+ this.maxMs = maxMs;
509
+ }
510
+ };
511
+ function assertTimeout(name, value) {
512
+ if (!Number.isSafeInteger(value) || value < 0) {
513
+ throw new Error(
514
+ `AgentRuntime: WaitBounds ${name} must be a non-negative safe integer`
515
+ );
516
+ }
517
+ }
518
+
519
+ // packages/experimental/src/zukhruf/collaboration/waiting.ts
520
+ var PREFER_LONGER_WAITS = "When calling `wait_agent`, prefer longer waits (minutes) to avoid busy polling.";
521
+ var Waiting = class {
522
+ bounds;
523
+ tools;
524
+ constructor(bounds = new WaitBounds()) {
525
+ this.bounds = bounds;
526
+ this.tools = {
527
+ wait_agent: createWaitAgentTool({
528
+ minTimeoutMs: bounds.minMs,
529
+ defaultTimeoutMs: bounds.defaultMs,
530
+ maxTimeoutMs: bounds.maxMs
531
+ })
532
+ };
533
+ }
534
+ guidance() {
535
+ return { outro: PREFER_LONGER_WAITS };
536
+ }
537
+ };
538
+
539
+ // packages/experimental/src/zukhruf/collaboration/team.ts
540
+ var DEFAULT_MAX_CONCURRENT_THREADS = 4;
541
+ var SHARED_WORKSPACE = "All agents share the same workspace, current working directory, and filesystem.";
542
+ var USE_CLAUSES = new Intl.ListFormat("en", { type: "conjunction" });
543
+ var ROLE_GUIDANCE = {
544
+ root: {
545
+ preamble: "You are `/root`, the primary agent in a team of agents collaborating to fulfill the user's goals.",
546
+ introSeparator: "\n\n",
547
+ envelopes: "Child messages arrive as `MESSAGE` or `FINAL_ANSWER` mailbox envelopes with their task name, sender, and payload preserved."
548
+ },
549
+ subagent: {
550
+ preamble: "You are an agent in a team collaborating to complete a task.",
551
+ introSeparator: " ",
552
+ 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."
553
+ }
554
+ };
555
+ function concurrencySlotsText(maxConcurrency) {
556
+ return `There are ${maxConcurrency} available concurrency slots, meaning that up to ${maxConcurrency} agents can be active at once, including you.`;
557
+ }
558
+ var Team = class _Team {
559
+ maxConcurrentThreads;
560
+ exposure;
561
+ /** What a turn's model request carries for the team's tools. */
562
+ surface;
563
+ #members;
564
+ #options;
565
+ constructor(spawning, options = {}) {
566
+ const maxConcurrentThreads = options.maxConcurrentThreads ?? DEFAULT_MAX_CONCURRENT_THREADS;
567
+ if (!Number.isSafeInteger(maxConcurrentThreads) || maxConcurrentThreads < 1) {
568
+ throw new Error(
569
+ "AgentRuntime: Team maxConcurrentThreads must be a positive integer"
570
+ );
571
+ }
572
+ this.maxConcurrentThreads = maxConcurrentThreads;
573
+ this.exposure = options.exposure ?? new DirectTools();
574
+ this.#members = spawning;
575
+ this.#options = options;
576
+ this.surface = this.exposure.surface(this.tools);
577
+ }
578
+ /** Every capability, in Codex order. */
579
+ static codex({
580
+ usageHintText,
581
+ waitBounds,
582
+ ...options
583
+ } = {}) {
584
+ return new _Team(new Spawning({ usageHintText }), options).with(new DirectMessaging()).with(new Waiting(waitBounds)).with(new Supervision());
585
+ }
586
+ /** A team that also has `capability`. Two tools of one name throw. */
587
+ with(capability) {
588
+ for (const name of Object.keys(capability.tools)) {
589
+ if (Object.hasOwn(this.#members.tools, name)) {
590
+ throw new Error(
591
+ `AgentRuntime: the team already has the "${name}" collaboration tool`
592
+ );
593
+ }
594
+ }
595
+ return new _Team(new Joined(this.#members, capability), this.#options);
596
+ }
597
+ /** The collaboration tools as the exposure carries them, in team order. */
598
+ get tools() {
599
+ const tools = { ...this.#members.tools };
600
+ for (const name in tools) {
601
+ const collaborationTool = tools[name];
602
+ tools[name] = this.exposure.tool({
603
+ ...collaborationTool,
604
+ metadata: {
605
+ ...collaborationTool.metadata,
606
+ zukhruf: {
607
+ kind: "collaboration"
608
+ }
609
+ }
610
+ });
611
+ }
612
+ return tools;
613
+ }
614
+ /** Names a plugin tool cannot take. */
615
+ get reservedToolNames() {
616
+ return this.surface.reservedToolNames;
617
+ }
618
+ /** The tools context of every tool that acts as `agent`. */
619
+ contextFor(agent2) {
620
+ const context = {};
621
+ for (const name of Object.keys(this.#members.tools)) context[name] = agent2;
622
+ if (!coversEveryTool(this.#members.tools, context)) {
623
+ throw new Error("AgentRuntime: a collaboration tool has no context");
624
+ }
625
+ return { ...context, ...this.exposure.callerContext(agent2) };
626
+ }
627
+ /** The role's collaboration guidance, or `undefined` for none. */
628
+ guidance(role3) {
629
+ const composed = this.#compose(role3);
630
+ const transform = this.#options.guidance?.[role3];
631
+ return transform === void 0 ? composed : transform(composed);
632
+ }
633
+ #compose(role3) {
634
+ const name = (toolName) => this.exposure.toolName(toolName);
635
+ const {
636
+ intro,
637
+ uses = [],
638
+ notes,
639
+ outro
640
+ } = this.#members.guidance(role3, name);
641
+ const { preamble, introSeparator, envelopes } = ROLE_GUIDANCE[role3];
642
+ const lead = [
643
+ intro,
644
+ joined(
645
+ [
646
+ uses.length === 0 ? void 0 : `Use ${USE_CLAUSES.format(uses)}.`,
647
+ notes
648
+ ],
649
+ " "
650
+ )
651
+ ];
652
+ return [
653
+ preamble,
654
+ joined(lead, introSeparator),
655
+ envelopes,
656
+ this.exposure.callLine(Object.keys(this.#members.tools)),
657
+ SHARED_WORKSPACE,
658
+ outro,
659
+ concurrencySlotsText(this.maxConcurrentThreads)
660
+ ].filter((paragraph) => paragraph !== void 0).join("\n\n");
661
+ }
662
+ };
663
+ var Joined = class {
664
+ tools;
665
+ #first;
666
+ #second;
667
+ constructor(first, second) {
668
+ this.tools = { ...first.tools, ...second.tools };
669
+ this.#first = first;
670
+ this.#second = second;
671
+ }
672
+ guidance(role3, name) {
673
+ const first = this.#first.guidance(role3, name);
674
+ const second = this.#second.guidance(role3, name);
675
+ return {
676
+ intro: joined([first.intro, second.intro], " "),
677
+ uses: [...first.uses ?? [], ...second.uses ?? []],
678
+ notes: joined([first.notes, second.notes], " "),
679
+ outro: joined([first.outro, second.outro], "\n\n")
680
+ };
681
+ }
682
+ };
683
+ function coversEveryTool(tools, context) {
684
+ return Object.keys(tools).every((name) => Object.hasOwn(context, name));
685
+ }
686
+ function joined(texts, separator) {
687
+ const present = texts.filter((text) => text !== void 0);
688
+ return present.length === 0 ? void 0 : present.join(separator);
689
+ }
690
+
691
+ // packages/experimental/src/zukhruf/collaboration/tool-namespace.ts
692
+ var RESERVED_TOOL_NAMESPACES = /* @__PURE__ */ new Set([
693
+ "api_tool",
694
+ "browser",
695
+ "computer",
696
+ "container",
697
+ "file_search",
698
+ "functions",
699
+ "image_gen",
700
+ "multi_tool_use",
701
+ "python",
702
+ "python_user_visible",
703
+ "submodel_delegator",
704
+ "terminal",
705
+ "tool_search",
706
+ "web"
707
+ ]);
708
+ var ToolNamespace = class {
709
+ name;
710
+ constructor(name) {
711
+ if (name.length === 0 || name.trim() !== name) {
712
+ throw new Error("AgentRuntime: ToolNamespace cannot be empty or padded");
713
+ }
714
+ if (name.length > 64 || !/^[a-zA-Z0-9_-]+$/.test(name) || name === "mcp" || name.startsWith("mcp__") || RESERVED_TOOL_NAMESPACES.has(name)) {
715
+ throw new Error(
716
+ `AgentRuntime: ToolNamespace "${name}" is a reserved tool namespace or invalid`
717
+ );
718
+ }
719
+ this.name = name;
720
+ }
721
+ qualify(toolName) {
722
+ return `${this.name}.${toolName}`;
723
+ }
724
+ };
725
+
24
726
  // packages/experimental/src/zukhruf/control-plane/agent-path.ts
25
727
  var AgentPath = class _AgentPath {
26
728
  #value;
@@ -229,75 +931,27 @@ function defineInstructions(...fragments) {
229
931
  }
230
932
 
231
933
  // packages/experimental/src/zukhruf/mailbox/postgres.store.ts
232
- import { z as z2 } from "zod";
934
+ import { z as z8 } from "zod";
233
935
  import {
234
936
  PostgresStoreDatabase,
235
937
  lockSchemaDDL
236
938
  } from "@deepagents/context";
237
939
 
238
940
  // packages/experimental/src/zukhruf/mailbox/communication-schema.ts
239
- import { z } from "zod";
240
-
241
- // packages/experimental/src/zukhruf/mailbox/types.ts
242
- import { randomUUID } from "node:crypto";
243
- var MessageDeliveryModes = {
244
- QueueOnly: "queue-only",
245
- TriggerTurn: "trigger-turn"
246
- };
247
- var InterAgentCommunicationTypes = {
248
- Message: "MESSAGE",
249
- NewTask: "NEW_TASK",
250
- FinalAnswer: "FINAL_ANSWER"
251
- };
252
- function createInterAgentCommunication(communication) {
253
- const value = {
254
- ...communication,
255
- id: communication.id ?? randomUUID(),
256
- type: communication.type ?? InterAgentCommunicationTypes.Message,
257
- otherRecipients: communication.otherRecipients ?? [],
258
- triggerTurn: false
259
- };
260
- assertCommunication(value);
261
- return value;
262
- }
263
- function assertCommunication(communication) {
264
- if (!communication.id.trim()) {
265
- throw new Error("inter-agent communication id cannot be empty");
266
- }
267
- if (!Object.values(InterAgentCommunicationTypes).includes(communication.type)) {
268
- throw new Error("inter-agent communication type is invalid");
269
- }
270
- assertConversationId(communication.author, "author");
271
- assertConversationId(communication.recipient, "recipient");
272
- for (const recipient of communication.otherRecipients) {
273
- assertConversationId(recipient, "other recipient");
274
- }
275
- if (!communication.content.trim()) {
276
- throw new Error("inter-agent communication content cannot be empty");
277
- }
278
- }
279
- function assertConversationId(value, label) {
280
- if (!value.chatId.trim() || !value.userId.trim()) {
281
- throw new Error(
282
- `inter-agent communication ${label} requires chatId and userId`
283
- );
284
- }
285
- }
286
-
287
- // packages/experimental/src/zukhruf/mailbox/communication-schema.ts
288
- var conversationIdSchema = z.object({
289
- chatId: z.string(),
290
- userId: z.string()
941
+ import { z as z7 } from "zod";
942
+ var conversationIdSchema = z7.object({
943
+ chatId: z7.string(),
944
+ userId: z7.string()
291
945
  });
292
- var communicationSchema = z.object({
293
- id: z.string(),
294
- type: z.enum(InterAgentCommunicationTypes),
946
+ var communicationSchema = z7.object({
947
+ id: z7.string(),
948
+ type: z7.enum(InterAgentCommunicationTypes),
295
949
  author: conversationIdSchema,
296
950
  recipient: conversationIdSchema,
297
- otherRecipients: z.array(conversationIdSchema),
298
- content: z.string(),
299
- metadata: z.record(z.string(), z.unknown()).optional(),
300
- triggerTurn: z.boolean()
951
+ otherRecipients: z7.array(conversationIdSchema),
952
+ content: z7.string(),
953
+ metadata: z7.record(z7.string(), z7.unknown()).optional(),
954
+ triggerTurn: z7.boolean()
301
955
  });
302
956
 
303
957
  // packages/experimental/src/zukhruf/mailbox/ddl.postgres.ts
@@ -334,13 +988,13 @@ var MailboxStore = class {
334
988
  };
335
989
 
336
990
  // packages/experimental/src/zukhruf/mailbox/postgres.store.ts
337
- var mailboxItemRowsSchema = z2.array(
338
- z2.object({
339
- sequence: z2.string(),
991
+ var mailboxItemRowsSchema = z8.array(
992
+ z8.object({
993
+ sequence: z8.string(),
340
994
  communication: communicationSchema
341
995
  })
342
996
  );
343
- var existsRowsSchema = z2.tuple([z2.object({ exists: z2.boolean() })]);
997
+ var existsRowsSchema = z8.tuple([z8.object({ exists: z8.boolean() })]);
344
998
  var PostgresMailboxStore = class _PostgresMailboxStore extends MailboxStore {
345
999
  #database;
346
1000
  constructor(database) {
@@ -514,7 +1168,7 @@ var PostgresMailboxStore = class _PostgresMailboxStore extends MailboxStore {
514
1168
  import { Declaration } from "@zukhruf/sqlite-drift";
515
1169
  import { open } from "@zukhruf/sqlite-open";
516
1170
  import { transaction } from "@zukhruf/sqlite-transaction";
517
- import { z as z3 } from "zod";
1171
+ import { z as z9 } from "zod";
518
1172
 
519
1173
  // packages/experimental/src/zukhruf/mailbox/ddl.sqlite.ts
520
1174
  var statements = [
@@ -548,10 +1202,10 @@ var statements = [
548
1202
 
549
1203
  // packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
550
1204
  var tables = new Declaration(statements, { rows: "keep" });
551
- var mailboxItemRowsSchema2 = z3.array(
552
- z3.object({
553
- sequence: z3.number(),
554
- communication: z3.string().transform((text) => JSON.parse(text)).pipe(communicationSchema)
1205
+ var mailboxItemRowsSchema2 = z9.array(
1206
+ z9.object({
1207
+ sequence: z9.number(),
1208
+ communication: z9.string().transform((text) => JSON.parse(text)).pipe(communicationSchema)
555
1209
  })
556
1210
  );
557
1211
  var SqliteMailboxStore = class extends MailboxStore {
@@ -720,7 +1374,7 @@ var SqliteMailboxStore = class extends MailboxStore {
720
1374
 
721
1375
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
722
1376
  import { v7 as uuidv7 } from "uuid";
723
- import { z as z4 } from "zod";
1377
+ import { z as z10 } from "zod";
724
1378
  import { isRecord as isRecord2 } from "@deepagents/context";
725
1379
 
726
1380
  // packages/experimental/src/zukhruf/queue/turn-queue.ts
@@ -728,7 +1382,7 @@ var TurnQueue = class {
728
1382
  };
729
1383
 
730
1384
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
731
- var queueCatalogRowSchema = z4.object({ table: z4.string() });
1385
+ var queueCatalogRowSchema = z10.object({ table: z10.string() });
732
1386
  function deadLetterQueueOf(queue) {
733
1387
  return `${queue}-dead`;
734
1388
  }
@@ -989,11 +1643,11 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
989
1643
  disposal.abort();
990
1644
  await this.#boss.offWork(this.#queue, {
991
1645
  id: turnWorkerId,
992
- wait: options.waitForActive
1646
+ wait: true
993
1647
  });
994
1648
  await this.#boss.offWork(this.deadLetterQueue, {
995
1649
  id: deadWorkerId,
996
- wait: options.waitForActive
1650
+ wait: true
997
1651
  });
998
1652
  }
999
1653
  };
@@ -1106,7 +1760,7 @@ import { MemoryStore } from "@zukhruf/mutex/memory";
1106
1760
  import { EventEmitter, on } from "node:events";
1107
1761
  import { isDeepStrictEqual } from "node:util";
1108
1762
  import {
1109
- ContextEngine as ContextEngine2
1763
+ ContextEngine as ContextEngine3
1110
1764
  } from "@deepagents/context";
1111
1765
 
1112
1766
  // packages/experimental/src/zukhruf/runtime/approval-controller.ts
@@ -1115,7 +1769,7 @@ import {
1115
1769
  isToolUIPart
1116
1770
  } from "ai";
1117
1771
  import {
1118
- ContextEngine,
1772
+ ContextEngine as ContextEngine2,
1119
1773
  assistant
1120
1774
  } from "@deepagents/context";
1121
1775
  function hasUnansweredApprovals(message) {
@@ -1150,11 +1804,6 @@ var ApprovalController = class {
1150
1804
  isPaused(message) {
1151
1805
  return isPausedHead(message);
1152
1806
  }
1153
- async isConversationPaused(conversation) {
1154
- return this.isPaused(
1155
- (await this.#engineFor(conversation).getMessages()).at(-1)
1156
- );
1157
- }
1158
1807
  async settleDeniedApprovals(conversation, streamId) {
1159
1808
  const engine = this.#engineFor(conversation);
1160
1809
  const head = (await engine.getMessages()).at(-1);
@@ -1271,26 +1920,26 @@ var ApprovalController = class {
1271
1920
  });
1272
1921
  }
1273
1922
  #engineFor({ chatId, userId }) {
1274
- return new ContextEngine({ store: this.#store, chatId, userId });
1923
+ return new ContextEngine2({ store: this.#store, chatId, userId });
1275
1924
  }
1276
1925
  };
1277
1926
 
1278
1927
  // packages/experimental/src/zukhruf/runtime/conversation-status/child-progress.ts
1279
- import { z as z5 } from "zod";
1280
- var childActivitySchema = z5.object({
1281
- id: z5.string(),
1282
- type: z5.enum(["spawn", "message", "followup", "interrupt", "completion"]),
1283
- at: z5.number(),
1284
- actorPath: z5.string(),
1285
- targetPath: z5.string(),
1286
- streamId: z5.string(),
1287
- outcome: z5.enum(["completed", "failed", "cancelled"]).optional()
1928
+ import { z as z11 } from "zod";
1929
+ var childActivitySchema = z11.object({
1930
+ id: z11.string(),
1931
+ type: z11.enum(["spawn", "message", "followup", "interrupt", "completion"]),
1932
+ at: z11.number(),
1933
+ actorPath: z11.string(),
1934
+ targetPath: z11.string(),
1935
+ streamId: z11.string(),
1936
+ outcome: z11.enum(["completed", "failed", "cancelled"]).optional()
1288
1937
  });
1289
- var childActivitiesSchema = z5.partialRecord(
1938
+ var childActivitiesSchema = z11.partialRecord(
1290
1939
  childActivitySchema.shape.type,
1291
1940
  childActivitySchema
1292
1941
  );
1293
- var childActivityMetadataSchema = z5.looseObject({
1942
+ var childActivityMetadataSchema = z11.looseObject({
1294
1943
  childActivities: childActivitiesSchema.default({})
1295
1944
  });
1296
1945
 
@@ -1335,7 +1984,7 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
1335
1984
  async read(conversation) {
1336
1985
  const activity = await this.#queue.getTurnActivity(conversation);
1337
1986
  if (activity === "running") return { type: "active", activeFlags: [] };
1338
- const engine = new ContextEngine2({
1987
+ const engine = new ContextEngine3({
1339
1988
  store: this.#store,
1340
1989
  chatId: conversation.chatId,
1341
1990
  userId: conversation.userId
@@ -1344,7 +1993,8 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
1344
1993
  const thread = await this.#directory.load(conversation);
1345
1994
  const streamId = thread?.lastTurnId ?? (head?.role === "assistant" ? head.id : void 0);
1346
1995
  const stream = streamId ? await this.#streams.store.getStream(streamId) : void 0;
1347
- const activeFlags = stream?.status === "completed" && head?.role === "assistant" ? activeFlagsOf(head) : [];
1996
+ const continuing = stream?.status === "queued" || stream?.status === "running";
1997
+ const activeFlags = !continuing && head?.role === "assistant" ? activeFlagsOf(head) : [];
1348
1998
  if (activity === "queued" || activeFlags.length > 0) {
1349
1999
  return { type: "active", activeFlags };
1350
2000
  }
@@ -1918,7 +2568,7 @@ var AgentHistoryForker = class {
1918
2568
  return this.#messagesById(parent, record.sourceMessageIds);
1919
2569
  }
1920
2570
  const source = await this.#sourceMessages(parent, record);
1921
- const selected = this.#select(source, record.forkTurns).map((entry) => this.#keepHistoryMessage(entry)).filter((entry) => entry !== void 0);
2571
+ const selected = source.map((entry) => this.#keepHistoryMessage(entry)).filter((entry) => entry !== void 0);
1922
2572
  const sourceMessageIds = await this.#claimSelection(
1923
2573
  child,
1924
2574
  selected.map(({ stored }) => stored.id)
@@ -1989,18 +2639,10 @@ var AgentHistoryForker = class {
1989
2639
  }
1990
2640
  return sourceMessageIds;
1991
2641
  }
1992
- #select(source, forkTurns) {
1993
- if (forkTurns === "all") return source;
1994
- const boundaries = source.flatMap(
1995
- (entry, index) => isForkTurnBoundary(entry.message) ? [index] : []
1996
- );
1997
- const start = boundaries.at(-forkTurns) ?? boundaries[0];
1998
- return start === void 0 ? [] : source.slice(start);
1999
- }
2000
2642
  #keepHistoryMessage(entry) {
2001
2643
  const { message } = entry;
2002
2644
  if (message.role === "user") {
2003
- if (isSyntheticReminderMessage(message) || interAgentCommunication(message) !== void 0) {
2645
+ if (isSyntheticReminderMessage(message) || isInterAgentCommunication(message)) {
2004
2646
  return void 0;
2005
2647
  }
2006
2648
  return entry;
@@ -2046,16 +2688,10 @@ var AgentHistoryForker = class {
2046
2688
  );
2047
2689
  }
2048
2690
  };
2049
- function isForkTurnBoundary(message) {
2050
- if (message.role !== "user" || isSyntheticReminderMessage(message)) {
2051
- return false;
2052
- }
2053
- return interAgentCommunication(message)?.triggerTurn ?? true;
2054
- }
2055
- function interAgentCommunication(message) {
2056
- if (!isRecord3(message.metadata)) return void 0;
2691
+ function isInterAgentCommunication(message) {
2692
+ if (!isRecord3(message.metadata)) return false;
2057
2693
  if (!Object.hasOwn(message.metadata, "interAgentCommunication")) {
2058
- return void 0;
2694
+ return false;
2059
2695
  }
2060
2696
  const communication = message.metadata.interAgentCommunication;
2061
2697
  if (!isRecord3(communication) || typeof communication.triggerTurn !== "boolean") {
@@ -2063,164 +2699,37 @@ function interAgentCommunication(message) {
2063
2699
  `spawn_agent: message "${message.id}" has invalid inter-agent metadata`
2064
2700
  );
2065
2701
  }
2066
- return { triggerTurn: communication.triggerTurn };
2067
- }
2068
- function parseHistoryForkRecord(value) {
2069
- if (!isRecord3(value)) {
2070
- throw new Error("spawn_agent: invalid persisted history-fork metadata");
2071
- }
2072
- const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } = value;
2073
- if (!isForkTurns(forkTurns) || typeof parentChatId !== "string" || !parentChatId.trim() || parentHeadMessageId !== null && (typeof parentHeadMessageId !== "string" || parentHeadMessageId.length === 0) || sourceMessageIds !== void 0 && (!Array.isArray(sourceMessageIds) || !sourceMessageIds.every(
2074
- (id) => typeof id === "string" && id.trim().length > 0
2075
- ) || new Set(sourceMessageIds).size !== sourceMessageIds.length)) {
2076
- throw new Error("spawn_agent: invalid persisted history-fork metadata");
2077
- }
2078
- return {
2079
- forkTurns,
2080
- parentChatId,
2081
- parentHeadMessageId,
2082
- ...sourceMessageIds === void 0 ? {} : { sourceMessageIds }
2083
- };
2084
- }
2085
- function isForkTurns(value) {
2086
- return value === "none" || value === "all" || typeof value === "number" && Number.isSafeInteger(value) && value > 0;
2087
- }
2088
- function isEmptyAssistantPlaceholder(value) {
2089
- return isRecord3(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
2090
- }
2091
-
2092
- // packages/experimental/src/zukhruf/control-plane/agent-status-projector.ts
2093
- import { isTextUIPart } from "ai";
2094
- import { z as z6 } from "zod";
2095
- import {
2096
- ContextEngine as ContextEngine3
2097
- } from "@deepagents/context";
2098
- var listedAgentStatusSchema = z6.union([
2099
- z6.enum(["pending_init", "running", "interrupted", "shutdown", "not_found"]),
2100
- z6.object({ completed: z6.string().nullable() }).strict(),
2101
- z6.object({ errored: z6.string() }).strict()
2102
- ]);
2103
- var listedAgentSchema = z6.object({
2104
- agent_name: z6.string(),
2105
- agent_status: listedAgentStatusSchema
2106
- }).strict();
2107
- var AgentStatusProjector = class _AgentStatusProjector {
2108
- #store;
2109
- #streams;
2110
- #queue;
2111
- #mailbox;
2112
- #directory;
2113
- #approvals;
2114
- constructor(options) {
2115
- this.#store = options.store;
2116
- this.#streams = options.streams;
2117
- this.#queue = options.queue;
2118
- this.#mailbox = options.mailbox;
2119
- this.#directory = options.directory;
2120
- this.#approvals = options.approvals;
2121
- }
2122
- async projectListedAgent(currentTurn, thread) {
2123
- const messages = await this.#messages(thread);
2124
- const head = messages.at(-1);
2125
- const streamId = thread.lastTurnId ?? (head?.role === "assistant" ? head.id : void 0);
2126
- const stream = streamId ? await this.#streams.store.getStream(streamId) : void 0;
2127
- const scheduledTurn = await this.#queue.getCurrentTurn(thread.conversation);
2128
- const scheduledStream = scheduledTurn ? await this.#streams.store.getStream(scheduledTurn.streamId) : void 0;
2129
- let status = _AgentStatusProjector.#listedStatus(
2130
- stream?.status,
2131
- stream?.error,
2132
- head
2133
- );
2134
- if (stream?.status === "completed" && this.#approvals.isPaused(head)) {
2135
- status = "running";
2136
- }
2137
- if (thread.conversation.chatId === currentTurn.chatId || thread.lastTurnId !== void 0 && scheduledTurn?.streamId !== thread.lastTurnId && (scheduledStream?.status === "queued" || scheduledStream?.status === "running")) {
2138
- status = "running";
2139
- }
2140
- return {
2141
- agent_name: thread.path.toString(),
2142
- agent_status: status
2143
- };
2144
- }
2145
- async projectTerminal(turn, thread) {
2146
- if (thread.parentChatId === null) return;
2147
- const stream = await this.#streams.store.getStream(turn.streamId);
2148
- if (!stream || stream.status !== "completed" && stream.status !== "failed" && stream.status !== "cancelled") {
2149
- return;
2150
- }
2151
- const message = (await this.#messages(thread)).find(
2152
- (candidate) => candidate.role === "assistant" && candidate.id === turn.streamId
2153
- );
2154
- if (stream.status === "completed" && this.#approvals.isPaused(message)) {
2155
- return;
2156
- }
2157
- const text = message?.role === "assistant" ? _AgentStatusProjector.#messageText(message) : "";
2158
- let content = text || "Agent completed without a text response.";
2159
- if (stream.status === "failed") {
2160
- content = `Agent failed: ${stream.error || "unknown error"}`;
2161
- } else if (stream.status === "cancelled") {
2162
- content = "Agent was interrupted.";
2163
- }
2164
- const parent = await this.#directory.load({
2165
- chatId: thread.parentChatId,
2166
- userId: thread.conversation.userId
2167
- });
2168
- await this.#mailbox.deliver(
2169
- createInterAgentCommunication({
2170
- id: `zukhruf:child-terminal:${turn.streamId}`,
2171
- type: InterAgentCommunicationTypes.FinalAnswer,
2172
- author: thread.conversation,
2173
- recipient: {
2174
- chatId: thread.parentChatId,
2175
- userId: thread.conversation.userId
2176
- },
2177
- content,
2178
- metadata: {
2179
- authorPath: thread.path.toString(),
2180
- recipientPath: parent?.path.toString() ?? thread.parentChatId,
2181
- streamId: turn.streamId,
2182
- status: stream.status
2183
- }
2184
- }),
2185
- MessageDeliveryModes.QueueOnly
2186
- );
2187
- return { finishedAt: stream.finishedAt, status: stream.status };
2188
- }
2189
- async #messages(thread) {
2190
- const engine = new ContextEngine3({
2191
- store: this.#store,
2192
- chatId: thread.conversation.chatId,
2193
- userId: thread.conversation.userId
2194
- });
2195
- return engine.getMessages();
2196
- }
2197
- static #listedStatus(status, error, head) {
2198
- switch (status) {
2199
- case "running":
2200
- return "running";
2201
- case "completed":
2202
- return {
2203
- completed: head?.role === "assistant" ? _AgentStatusProjector.#messageText(head) || null : null
2204
- };
2205
- case "failed":
2206
- return { errored: error || "Agent turn failed." };
2207
- case "cancelled":
2208
- return "interrupted";
2209
- case "queued":
2210
- case void 0:
2211
- return "pending_init";
2212
- }
2702
+ return true;
2703
+ }
2704
+ function parseHistoryForkRecord(value) {
2705
+ if (!isRecord3(value)) {
2706
+ throw new Error("spawn_agent: invalid persisted history-fork metadata");
2213
2707
  }
2214
- static #messageText(message) {
2215
- return message.parts.filter(isTextUIPart).map((part) => part.text).join("\n").trim();
2708
+ const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } = value;
2709
+ if (!isForkTurns(forkTurns) || typeof parentChatId !== "string" || !parentChatId.trim() || parentHeadMessageId !== null && (typeof parentHeadMessageId !== "string" || parentHeadMessageId.length === 0) || sourceMessageIds !== void 0 && (!Array.isArray(sourceMessageIds) || !sourceMessageIds.every(
2710
+ (id) => typeof id === "string" && id.trim().length > 0
2711
+ ) || new Set(sourceMessageIds).size !== sourceMessageIds.length)) {
2712
+ throw new Error("spawn_agent: invalid persisted history-fork metadata");
2216
2713
  }
2217
- };
2714
+ return {
2715
+ forkTurns,
2716
+ parentChatId,
2717
+ parentHeadMessageId,
2718
+ ...sourceMessageIds === void 0 ? {} : { sourceMessageIds }
2719
+ };
2720
+ }
2721
+ function isForkTurns(value) {
2722
+ return value === "none" || value === "all";
2723
+ }
2724
+ function isEmptyAssistantPlaceholder(value) {
2725
+ return isRecord3(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
2726
+ }
2218
2727
 
2219
2728
  // packages/experimental/src/zukhruf/control-plane/agent-turn-id.ts
2220
2729
  import { v5 as uuidv53, validate as validateUuid } from "uuid";
2221
- import { z as z7 } from "zod";
2730
+ import { z as z12 } from "zod";
2222
2731
  var prefix = "zukhruf-turn";
2223
- var agentTurnIdSchema = z7.string().refine((value) => {
2732
+ var agentTurnIdSchema = z12.string().refine((value) => {
2224
2733
  const [head, scope, turn, ...rest] = value.split(":");
2225
2734
  return head === prefix && rest.length === 0 && validateUuid(scope) && validateUuid(turn);
2226
2735
  });
@@ -2773,145 +3282,10 @@ var MailboxCoordinator = class _MailboxCoordinator {
2773
3282
  }
2774
3283
  };
2775
3284
 
2776
- // packages/experimental/src/zukhruf/multi-agent-config.ts
2777
- var DEFAULT_MIN_WAIT_TIMEOUT_MS = 1e4;
2778
- var DEFAULT_WAIT_TIMEOUT_MS = 3e4;
2779
- var DEFAULT_MAX_WAIT_TIMEOUT_MS = 36e5;
2780
- var DEFAULT_MAX_CONCURRENT_THREADS_PER_SESSION = 4;
2781
- var WAIT_AGENT_USAGE_HINT_TEXT = "When calling `wait_agent`, prefer longer waits (minutes) to avoid busy polling.";
2782
- function concurrencySlotsText(maxConcurrency) {
2783
- return `There are ${maxConcurrency} available concurrency slots, meaning that up to ${maxConcurrency} agents can be active at once, including you.`;
2784
- }
2785
- var RESERVED_TOOL_NAMESPACES = /* @__PURE__ */ new Set([
2786
- "api_tool",
2787
- "browser",
2788
- "computer",
2789
- "container",
2790
- "file_search",
2791
- "functions",
2792
- "image_gen",
2793
- "multi_tool_use",
2794
- "python",
2795
- "python_user_visible",
2796
- "submodel_delegator",
2797
- "terminal",
2798
- "tool_search",
2799
- "web"
2800
- ]);
2801
- function resolveMultiAgentHostConfig(input = {}) {
2802
- const minWaitTimeoutMs = input.minWaitTimeoutMs ?? DEFAULT_MIN_WAIT_TIMEOUT_MS;
2803
- const defaultWaitTimeoutMs = input.defaultWaitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
2804
- const maxWaitTimeoutMs = input.maxWaitTimeoutMs ?? DEFAULT_MAX_WAIT_TIMEOUT_MS;
2805
- assertTimeout("minWaitTimeoutMs", minWaitTimeoutMs);
2806
- assertTimeout("defaultWaitTimeoutMs", defaultWaitTimeoutMs);
2807
- assertTimeout("maxWaitTimeoutMs", maxWaitTimeoutMs);
2808
- const maxConcurrentThreadsPerSession = input.maxConcurrentThreadsPerSession ?? DEFAULT_MAX_CONCURRENT_THREADS_PER_SESSION;
2809
- if (!Number.isSafeInteger(maxConcurrentThreadsPerSession) || maxConcurrentThreadsPerSession < 1) {
2810
- throw new Error(
2811
- "AgentRuntime: multiAgent.maxConcurrentThreadsPerSession must be a positive integer"
2812
- );
2813
- }
2814
- if (minWaitTimeoutMs > maxWaitTimeoutMs) {
2815
- throw new Error(
2816
- "AgentRuntime: multiAgent.minWaitTimeoutMs must be at most maxWaitTimeoutMs"
2817
- );
2818
- }
2819
- if (defaultWaitTimeoutMs < minWaitTimeoutMs) {
2820
- throw new Error(
2821
- "AgentRuntime: multiAgent.defaultWaitTimeoutMs must be at least minWaitTimeoutMs"
2822
- );
2823
- }
2824
- if (defaultWaitTimeoutMs > maxWaitTimeoutMs) {
2825
- throw new Error(
2826
- "AgentRuntime: multiAgent.defaultWaitTimeoutMs must be at most maxWaitTimeoutMs"
2827
- );
2828
- }
2829
- const toolNamespace = input.toolNamespace;
2830
- if (toolNamespace !== void 0 && (toolNamespace.length === 0 || toolNamespace.trim() !== toolNamespace)) {
2831
- throw new Error(
2832
- "AgentRuntime: multiAgent.toolNamespace cannot be empty or padded"
2833
- );
2834
- }
2835
- if (toolNamespace !== void 0) validateToolNamespace(toolNamespace);
2836
- const codeMode = input.nonCodeModeOnly === false;
2837
- const tool7 = (name) => codeMode ? `tools.${name}` : toolNamespace === void 0 ? name : `${toolNamespace}.${name}`;
2838
- const collaborationTools = [
2839
- "spawn_agent",
2840
- "send_message",
2841
- "followup_task",
2842
- "wait_agent",
2843
- "interrupt_agent",
2844
- "list_agents"
2845
- ].map((name) => `\`${tool7(name)}\``).join(", ");
2846
- const shared = codeMode ? `Call ${collaborationTools} from \`code_mode\`.
2847
-
2848
- All agents share the same workspace, current working directory, and filesystem.` : `Call ${collaborationTools} directly. They are intentionally unavailable inside nested code execution.
2849
-
2850
- All agents share the same workspace, current working directory, and filesystem.`;
2851
- return {
2852
- minWaitTimeoutMs,
2853
- defaultWaitTimeoutMs,
2854
- maxWaitTimeoutMs,
2855
- maxConcurrentThreadsPerSession,
2856
- usageHintText: nonEmptyText(input.usageHintText),
2857
- rootAgentUsageHintText: input.rootAgentUsageHintText === void 0 ? defaultRootUsageHint(tool7, shared, maxConcurrentThreadsPerSession) : nonEmptyText(input.rootAgentUsageHintText),
2858
- subagentUsageHintText: input.subagentUsageHintText === void 0 ? defaultSubagentUsageHint(tool7, shared, maxConcurrentThreadsPerSession) : nonEmptyText(input.subagentUsageHintText),
2859
- toolNamespace,
2860
- codeMode
2861
- };
2862
- }
2863
- function assertTimeout(name, value) {
2864
- if (!Number.isSafeInteger(value) || value < 0) {
2865
- throw new Error(
2866
- `AgentRuntime: multiAgent.${name} must be a non-negative safe integer`
2867
- );
2868
- }
2869
- }
2870
- function validateToolNamespace(namespace) {
2871
- if (namespace.length > 64 || !/^[a-zA-Z0-9_-]+$/.test(namespace) || namespace === "mcp" || namespace.startsWith("mcp__") || RESERVED_TOOL_NAMESPACES.has(namespace)) {
2872
- throw new Error(
2873
- `AgentRuntime: multiAgent.toolNamespace "${namespace}" is a reserved tool namespace or invalid`
2874
- );
2875
- }
2876
- }
2877
- function nonEmptyText(value) {
2878
- if (value === void 0) return void 0;
2879
- return value.length === 0 ? void 0 : value;
2880
- }
2881
- function defaultRootUsageHint(tool7, shared, maxConcurrency) {
2882
- return `You are \`/root\`, the primary agent in a team of agents collaborating to fulfill the user's goals.
2883
-
2884
- 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.
2885
-
2886
- 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.
2887
-
2888
- Child messages arrive as \`MESSAGE\` or \`FINAL_ANSWER\` mailbox envelopes with their task name, sender, and payload preserved.
2889
-
2890
- ${shared}
2891
-
2892
- ${WAIT_AGENT_USAGE_HINT_TEXT}
2893
-
2894
- ${concurrencySlotsText(maxConcurrency)}`;
2895
- }
2896
- function defaultSubagentUsageHint(tool7, shared, maxConcurrency) {
2897
- return `You are an agent in a team collaborating to complete a task.
2898
-
2899
- 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.
2900
-
2901
- 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.
2902
-
2903
- ${shared}
2904
-
2905
- ${WAIT_AGENT_USAGE_HINT_TEXT}
2906
-
2907
- ${concurrencySlotsText(maxConcurrency)}`;
2908
- }
2909
-
2910
3285
  // packages/experimental/src/zukhruf/runtime/agent-turn-executor.ts
2911
- import { experimental_codeModeTool } from "@ai-sdk/code-mode";
2912
3286
  import {
2913
3287
  jsonSchema,
2914
- tool
3288
+ tool as tool6
2915
3289
  } from "ai";
2916
3290
  import path2 from "node:path";
2917
3291
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
@@ -2936,7 +3310,7 @@ import {
2936
3310
  modelMessageSchema as modelMessageSchema2
2937
3311
  } from "ai";
2938
3312
  import { hash, randomUUID as randomUUID2 } from "node:crypto";
2939
- import { z as z8 } from "zod";
3313
+ import { z as z13 } from "zod";
2940
3314
 
2941
3315
  // packages/compaction/dist/index.js
2942
3316
  import {
@@ -3143,21 +3517,21 @@ ${options.instructions}` : SUMMARY_PROMPT,
3143
3517
  import {
3144
3518
  isRecord as isRecord4
3145
3519
  } from "@deepagents/context";
3146
- var checkpointSchema = z8.object({
3147
- sourceCount: z8.number().int().positive(),
3148
- sourceHash: z8.string(),
3149
- replacement: z8.array(z8.unknown()).transform(
3520
+ var checkpointSchema = z13.object({
3521
+ sourceCount: z13.number().int().positive(),
3522
+ sourceHash: z13.string(),
3523
+ replacement: z13.array(z13.unknown()).transform(
3150
3524
  (messages) => messages.map((message) => modelMessageSchema2.parse(message))
3151
3525
  )
3152
3526
  });
3153
- var cacheObservationSchema = z8.object({
3154
- scope: z8.string(),
3155
- prefixLength: z8.number().int().nonnegative(),
3156
- prefixHash: z8.string(),
3157
- startedAt: z8.number().int().nonnegative(),
3158
- retentionMs: z8.number().int().positive().optional()
3527
+ var cacheObservationSchema = z13.object({
3528
+ scope: z13.string(),
3529
+ prefixLength: z13.number().int().nonnegative(),
3530
+ prefixHash: z13.string(),
3531
+ startedAt: z13.number().int().nonnegative(),
3532
+ retentionMs: z13.number().int().positive().optional()
3159
3533
  });
3160
- var inputUsageSchema = cacheObservationSchema.pick({ scope: true, prefixLength: true, prefixHash: true }).extend({ inputTokens: z8.number().int().nonnegative() });
3534
+ var inputUsageSchema = cacheObservationSchema.pick({ scope: true, prefixLength: true, prefixHash: true }).extend({ inputTokens: z13.number().int().nonnegative() });
3161
3535
  function jsonDigest(value) {
3162
3536
  return hash("sha256", JSON.stringify(value));
3163
3537
  }
@@ -3611,7 +3985,7 @@ var AgentTurnExecutor = class {
3611
3985
  #controlPlane;
3612
3986
  #mailbox;
3613
3987
  #approvals;
3614
- #multiAgent;
3988
+ #team;
3615
3989
  #plugins;
3616
3990
  #sandboxes;
3617
3991
  #publishConversationStatus;
@@ -3621,7 +3995,7 @@ var AgentTurnExecutor = class {
3621
3995
  this.#controlPlane = options.controlPlane;
3622
3996
  this.#mailbox = options.mailbox;
3623
3997
  this.#approvals = options.approvals;
3624
- this.#multiAgent = options.multiAgent;
3998
+ this.#team = options.team;
3625
3999
  this.#plugins = options.plugins;
3626
4000
  this.#sandboxes = options.sandboxes;
3627
4001
  this.#publishConversationStatus = options.publishConversationStatus;
@@ -3649,7 +4023,9 @@ var AgentTurnExecutor = class {
3649
4023
  async #executeTurn(turn, { signal, park }) {
3650
4024
  if (await this.#projectSkippedTerminalTurn(turn)) return;
3651
4025
  const { declaration, thread } = await this.#controlPlane.resolve(turn);
3652
- const usageHint = thread.path.isRoot ? this.#multiAgent.rootAgentUsageHintText : this.#multiAgent.subagentUsageHintText;
4026
+ const usageHint = this.#team.guidance(
4027
+ thread.path.isRoot ? "root" : "subagent"
4028
+ );
3653
4029
  const engine = this.#engineFor(turn).set(
3654
4030
  ...declaration.instructions,
3655
4031
  ...usageHint === void 0 ? [] : [role(usageHint)]
@@ -3732,38 +4108,24 @@ var AgentTurnExecutor = class {
3732
4108
  }
3733
4109
  },
3734
4110
  prepareStepInput: () => this.#prepareStepInput(turn, mailboxState),
3735
- ...this.#multiAgent.codeMode ? {
3736
- experimental_toolCallers: Object.fromEntries(
3737
- Object.keys(this.#plugins.collaborationTools).map((name) => [
3738
- name,
3739
- ["code_mode"]
3740
- ])
3741
- )
3742
- } : {}
4111
+ experimental_toolCallers: this.#team.surface.toolCallers
3743
4112
  };
3744
4113
  const modelTools = {
3745
4114
  ...turn.kind === "message" ? Object.fromEntries(
3746
4115
  Object.entries(turn.tools ?? {}).map(([name, definition]) => [
3747
4116
  name,
3748
- tool({
4117
+ tool6({
3749
4118
  description: definition.description,
3750
4119
  inputSchema: jsonSchema(definition.inputSchema)
3751
4120
  })
3752
4121
  ])
3753
4122
  ) : {},
3754
4123
  ...declaration.tools,
3755
- ...this.#plugins.collaborationTools,
3756
- ...this.#multiAgent.codeMode ? { code_mode: experimental_codeModeTool() } : {},
4124
+ ...this.#team.surface.tools,
3757
4125
  ...this.#plugins.tools
3758
4126
  };
3759
- const collaborationToolsContext = {
3760
- spawn_agent: agentContext,
3761
- send_message: agentContext,
3762
- followup_task: agentContext,
3763
- list_agents: agentContext,
3764
- wait_agent: agentContext,
3765
- interrupt_agent: agentContext,
3766
- ...this.#multiAgent.codeMode ? { code_mode: agentContext } : {},
4127
+ const toolsContext = {
4128
+ ...this.#team.contextFor(agentContext),
3767
4129
  ...Object.fromEntries(
3768
4130
  Object.keys(this.#plugins.tools).map((name) => [name, pluginContext])
3769
4131
  )
@@ -3801,7 +4163,7 @@ var AgentTurnExecutor = class {
3801
4163
  onStepStart: compaction?.onStepStart,
3802
4164
  onStepEnd: compaction?.onStepEnd,
3803
4165
  include: compaction?.include,
3804
- toolsContext: collaborationToolsContext,
4166
+ toolsContext,
3805
4167
  ...elements.length > 0 ? { transform: [elementsStreamTransform] } : {}
3806
4168
  }
3807
4169
  );
@@ -4023,6 +4385,7 @@ function isSkill(value) {
4023
4385
  }
4024
4386
 
4025
4387
  // packages/experimental/src/zukhruf/runtime/conversation-sandboxes.ts
4388
+ import { SandboxNotFoundError } from "@deepagents/context";
4026
4389
  var ConversationSandboxes = class {
4027
4390
  // One memoized acquisition for each declaration and conversation.
4028
4391
  #held = /* @__PURE__ */ new Map();
@@ -4033,7 +4396,8 @@ var ConversationSandboxes = class {
4033
4396
  context.userId
4034
4397
  ]);
4035
4398
  const held = this.#held.get(key);
4036
- if (held !== void 0) return held();
4399
+ if (held !== void 0)
4400
+ return this.#existing(key, held, declaration, context);
4037
4401
  const acquiring = declaration.sandbox(context).catch((error) => {
4038
4402
  this.#held.delete(key);
4039
4403
  throw error;
@@ -4041,6 +4405,25 @@ var ConversationSandboxes = class {
4041
4405
  this.#held.set(key, () => acquiring);
4042
4406
  return acquiring;
4043
4407
  }
4408
+ /**
4409
+ * Checked before the turn, not left to its first command: the turn's tools
4410
+ * are bound to this handle, so a sandbox found gone mid-turn fails the
4411
+ * model's tool call instead of acquiring a new sandbox.
4412
+ */
4413
+ async #existing(key, held, declaration, context) {
4414
+ const handle = await held();
4415
+ try {
4416
+ await handle.sandbox.run({ command: "true" });
4417
+ return handle;
4418
+ } catch (error) {
4419
+ if (!(error instanceof SandboxNotFoundError)) throw error;
4420
+ }
4421
+ if (this.#held.get(key) === held) {
4422
+ this.#held.delete(key);
4423
+ await handle.sandbox.dispose();
4424
+ }
4425
+ return this.acquire(declaration, context);
4426
+ }
4044
4427
  async [Symbol.asyncDispose]() {
4045
4428
  await using handles = new AsyncDisposableStack();
4046
4429
  const acquired = await Promise.allSettled(
@@ -4052,199 +4435,6 @@ var ConversationSandboxes = class {
4052
4435
  }
4053
4436
  };
4054
4437
 
4055
- // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
4056
- import { tool as tool2 } from "ai";
4057
- import { z as z9 } from "zod";
4058
- var interruptAgentInputSchema = z9.object({
4059
- target: z9.string().trim().min(1).describe(
4060
- "The canonical /root/... path, or a descendant-relative target name."
4061
- )
4062
- });
4063
- var interruptAgentOutputSchema = z9.object({ previous_status: listedAgentStatusSchema }).strict();
4064
- var interruptAgentTool = tool2({
4065
- description: "Interrupt an agent's current turn, if any, and return its previous status. The agent remains available for messages and follow-up tasks.",
4066
- inputSchema: interruptAgentInputSchema,
4067
- outputSchema: interruptAgentOutputSchema,
4068
- execute: async (input, { context }) => context.controlPlane.interruptAgent(context.actor, input)
4069
- });
4070
-
4071
- // packages/experimental/src/zukhruf/collaboration/list-agents.ts
4072
- import { tool as tool3 } from "ai";
4073
- import { z as z10 } from "zod";
4074
- var listAgentsInputSchema = z10.object({
4075
- path_prefix: z10.string().trim().min(1).describe(
4076
- "Task-path prefix without a trailing slash. Omit to list the whole tree."
4077
- ).optional()
4078
- });
4079
- var listAgentsOutputSchema = z10.object({ agents: z10.array(listedAgentSchema) }).strict();
4080
- var listAgentsTool = tool3({
4081
- description: "List live agents in the current root thread tree. Optionally filter by task-path prefix.",
4082
- inputSchema: listAgentsInputSchema,
4083
- outputSchema: listAgentsOutputSchema,
4084
- execute: async ({ path_prefix }, { context }) => context.controlPlane.listAgents(context.actor, path_prefix)
4085
- });
4086
-
4087
- // packages/experimental/src/zukhruf/collaboration/message-tools.ts
4088
- import { tool as tool4 } from "ai";
4089
- import { z as z11 } from "zod";
4090
- var agentMessageInputSchema = z11.object({
4091
- target: z11.string().trim().min(1).describe(
4092
- "The canonical /root/... path, or a descendant-relative target name."
4093
- ),
4094
- message: z11.string().trim().min(1).describe("The message or follow-up task.")
4095
- });
4096
- var sendMessageTool = tool4({
4097
- description: "Queue a message for another agent. Address siblings with their canonical /root/... path.",
4098
- inputSchema: agentMessageInputSchema,
4099
- execute: async (input, { context }) => {
4100
- await context.controlPlane.sendMessage(context.actor, input);
4101
- return "";
4102
- }
4103
- });
4104
- var followupTaskTool = tool4({
4105
- description: "Send a follow-up task to an existing non-root agent and wake its thread.",
4106
- inputSchema: agentMessageInputSchema,
4107
- execute: async (input, { context }) => {
4108
- await context.controlPlane.followupTask(context.actor, input);
4109
- return "";
4110
- }
4111
- });
4112
-
4113
- // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
4114
- import { tool as tool5 } from "ai";
4115
- import { z as z12 } from "zod";
4116
-
4117
- // packages/experimental/src/zukhruf/control-plane/fork-turns.ts
4118
- var forkTurnsError = "fork_turns must be `none`, `all`, or a positive integer string";
4119
- function parseForkTurns(value) {
4120
- const normalized = value.trim().toLowerCase();
4121
- if (normalized === "none" || normalized === "all") return normalized;
4122
- if (!/^\d+$/.test(normalized)) return void 0;
4123
- const turns = Number(normalized);
4124
- return Number.isSafeInteger(turns) && turns > 0 ? turns : void 0;
4125
- }
4126
-
4127
- // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
4128
- var spawnAgentInputSchema = z12.object({
4129
- agent_type: z12.string().trim().min(1).describe("The name of one available subagent declaration."),
4130
- task_name: z12.string().trim().min(1).refine(
4131
- (value) => value !== "." && value !== ".." && !value.includes("/"),
4132
- "task_name must be one non-empty path segment"
4133
- ).describe("One path segment naming this independent agent task."),
4134
- message: z12.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent."),
4135
- fork_turns: z12.string().trim().refine((value) => parseForkTurns(value) !== void 0, forkTurnsError).describe(
4136
- "Required number of parent turns to fork. Use `none`, `all`, or a positive integer string such as `3`."
4137
- )
4138
- });
4139
- var spawnAgentOutputSchema = z12.object({ task_name: z12.string() }).strict();
4140
- function createSpawnAgentTool(options) {
4141
- return tool5({
4142
- description: ({ context }) => {
4143
- const available = (context.actor.declaration.subagents ?? []).map(
4144
- ({ name, description }) => description ? `${name}: ${description}` : name
4145
- ).join(", ");
4146
- return [
4147
- `Spawn an independent subagent. Available agent types: ${available || "none"}.`,
4148
- options?.usageHintText
4149
- ].filter(Boolean).join(" ");
4150
- },
4151
- inputSchema: spawnAgentInputSchema,
4152
- outputSchema: spawnAgentOutputSchema,
4153
- execute: async ({ agent_type, task_name, message, fork_turns }, { context }) => {
4154
- const forkTurns = parseForkTurns(fork_turns);
4155
- if (forkTurns === void 0) throw new Error(forkTurnsError);
4156
- return context.controlPlane.spawn(context.actor, {
4157
- agentType: agent_type,
4158
- taskName: task_name,
4159
- message,
4160
- forkTurns
4161
- });
4162
- }
4163
- });
4164
- }
4165
-
4166
- // packages/experimental/src/zukhruf/collaboration/wait-agent.ts
4167
- import { tool as tool6 } from "ai";
4168
- import { z as z13 } from "zod";
4169
- var waitAgentOutputSchema = z13.object({ message: z13.string(), timed_out: z13.boolean() }).strict();
4170
- function createWaitAgentTool(options) {
4171
- const waitAgentInputSchema = z13.object({
4172
- timeout_ms: z13.number().int().max(options.maxTimeoutMs).optional().describe("Maximum time to wait in milliseconds.")
4173
- });
4174
- return tool6({
4175
- description: "Wait for pending mail addressed to this agent without consuming it.",
4176
- inputSchema: waitAgentInputSchema,
4177
- outputSchema: waitAgentOutputSchema,
4178
- execute: async ({ timeout_ms }, { abortSignal, context }) => {
4179
- const timeoutMs = Math.max(
4180
- timeout_ms ?? options.defaultTimeoutMs,
4181
- options.minTimeoutMs
4182
- );
4183
- const received = await context.controlPlane.waitForMailbox(
4184
- context.actor,
4185
- {
4186
- timeoutMs,
4187
- signal: abortSignal
4188
- }
4189
- );
4190
- const message = received ? "Wait completed." : "Wait timed out.";
4191
- return {
4192
- message: timeout_ms !== void 0 && timeout_ms < timeoutMs ? `${message}
4193
-
4194
- Requested timeout of ${timeout_ms}ms was clamped to the minimum of ${timeoutMs}ms.` : message,
4195
- timed_out: !received
4196
- };
4197
- }
4198
- });
4199
- }
4200
-
4201
- // packages/experimental/src/zukhruf/collaboration/collaboration-tools.ts
4202
- var NAMESPACE_DESCRIPTION = "Tools for spawning and managing sub-agents.";
4203
- function createCollaborationTools(config) {
4204
- return {
4205
- spawn_agent: configureTool(
4206
- createSpawnAgentTool({ usageHintText: config.usageHintText }),
4207
- config
4208
- ),
4209
- send_message: configureTool(sendMessageTool, config),
4210
- followup_task: configureTool(followupTaskTool, config),
4211
- list_agents: configureTool(listAgentsTool, config),
4212
- wait_agent: configureTool(
4213
- createWaitAgentTool({
4214
- minTimeoutMs: config.minWaitTimeoutMs,
4215
- defaultTimeoutMs: config.defaultWaitTimeoutMs,
4216
- maxTimeoutMs: config.maxWaitTimeoutMs
4217
- }),
4218
- config
4219
- ),
4220
- interrupt_agent: configureTool(interruptAgentTool, config)
4221
- };
4222
- }
4223
- function configureTool(collaborationTool, config) {
4224
- const openai = collaborationTool.providerOptions?.openai;
4225
- return {
4226
- ...collaborationTool,
4227
- providerOptions: {
4228
- ...collaborationTool.providerOptions,
4229
- ...config.toolNamespace === void 0 ? {} : {
4230
- openai: {
4231
- ...typeof openai === "object" && openai !== null ? openai : {},
4232
- namespace: {
4233
- name: config.toolNamespace,
4234
- description: NAMESPACE_DESCRIPTION
4235
- }
4236
- }
4237
- }
4238
- },
4239
- metadata: {
4240
- ...collaborationTool.metadata,
4241
- zukhruf: {
4242
- kind: "collaboration"
4243
- }
4244
- }
4245
- };
4246
- }
4247
-
4248
4438
  // packages/experimental/src/zukhruf/runtime/plugin/plugin-agents.ts
4249
4439
  import { readFileSync as readFileSync2, readdirSync as readdirSync2 } from "node:fs";
4250
4440
  import { basename, extname, join } from "node:path";
@@ -4546,7 +4736,6 @@ function initializedFrom(plugin, definition) {
4546
4736
  return plugin.definition === definition;
4547
4737
  }
4548
4738
  var PluginManager = class {
4549
- collaborationTools;
4550
4739
  declarations;
4551
4740
  agentOwners;
4552
4741
  tools;
@@ -4556,7 +4745,7 @@ var PluginManager = class {
4556
4745
  #toolComposition;
4557
4746
  #resources = new AsyncDisposableStack();
4558
4747
  #running = [];
4559
- constructor(root, bindings, multiAgent) {
4748
+ constructor(root, bindings, team) {
4560
4749
  let configuredRoot = root;
4561
4750
  const pluginBindings = new PluginBindings(root.plugins, bindings);
4562
4751
  const plugins = [];
@@ -4570,10 +4759,7 @@ var PluginManager = class {
4570
4759
  }
4571
4760
  const pluginSkills = new PluginSkillComposition();
4572
4761
  const pluginContext = new PluginContextComposition();
4573
- const collaborationTools = createCollaborationTools(multiAgent);
4574
- const reservedToolNames = Object.keys(collaborationTools);
4575
- if (multiAgent.codeMode) reservedToolNames.push("code_mode");
4576
- const toolComposition = new PluginToolComposition(reservedToolNames);
4762
+ const toolComposition = new PluginToolComposition(team.reservedToolNames);
4577
4763
  for (const { definition, instance } of plugins) {
4578
4764
  if (instance.tools) {
4579
4765
  toolComposition.add(definition.name, instance.tools);
@@ -4596,7 +4782,6 @@ var PluginManager = class {
4596
4782
  const pluginSkillsByAgent = pluginSkills.compose(declarations.values());
4597
4783
  const pluginTools = toolComposition.compose(declarations.values());
4598
4784
  this.#plugins = plugins;
4599
- this.collaborationTools = collaborationTools;
4600
4785
  this.declarations = declarations;
4601
4786
  this.agentOwners = pluginAgents.owners;
4602
4787
  this.tools = pluginTools;
@@ -4635,9 +4820,9 @@ var PluginManager = class {
4635
4820
  ({ running }) => Boolean(running.conversationAvailable)
4636
4821
  );
4637
4822
  }
4638
- async startWorkers(workers, waitForActive) {
4823
+ async startWorkers(workers) {
4639
4824
  for (const { running } of this.#running) {
4640
- if (running.work) workers.use(await running.work(waitForActive));
4825
+ if (running.work) workers.use(await running.work());
4641
4826
  }
4642
4827
  }
4643
4828
  async initialize(host) {
@@ -4805,9 +4990,9 @@ var RuntimeHost = class {
4805
4990
  #pluginHost;
4806
4991
  constructor(root, options, resources) {
4807
4992
  this.#resources = resources;
4808
- const multiAgent = resolveMultiAgentHostConfig(options.multiAgent);
4993
+ const team = options.multiAgent ?? Team.codex();
4809
4994
  const plugins = resources.use(
4810
- new PluginManager(root, options.bindings, multiAgent)
4995
+ new PluginManager(root, options.bindings, team)
4811
4996
  );
4812
4997
  const declarations = plugins.declarations;
4813
4998
  const { storage } = options;
@@ -4824,7 +5009,7 @@ var RuntimeHost = class {
4824
5009
  const residency = new AgentResidency({
4825
5010
  storage,
4826
5011
  directory,
4827
- maxConcurrentThreadsPerSession: multiAgent.maxConcurrentThreadsPerSession,
5012
+ maxConcurrentThreadsPerSession: team.maxConcurrentThreads,
4828
5013
  publish: (conversation) => conversationStatus.publish(conversation)
4829
5014
  });
4830
5015
  const mailbox = new MailboxCoordinator({
@@ -4886,7 +5071,7 @@ var RuntimeHost = class {
4886
5071
  controlPlane,
4887
5072
  mailbox,
4888
5073
  approvals,
4889
- multiAgent,
5074
+ team,
4890
5075
  plugins,
4891
5076
  sandboxes,
4892
5077
  publishConversationStatus: (conversation) => conversationStatus.publish(conversation)
@@ -4923,13 +5108,31 @@ var RuntimeHost = class {
4923
5108
  plugin(definition) {
4924
5109
  return this.#plugins.get(definition);
4925
5110
  }
5111
+ /** 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. */
4926
5112
  async createSession(conversation) {
4927
- await this.#controlPlane.resolve(conversation);
5113
+ const thread = await this.#directory.load(conversation) ?? (await this.#controlPlane.resolve(conversation)).thread;
5114
+ if (!await this.#ownsTree(thread)) {
5115
+ throw new ConversationNotFoundError(conversation.chatId);
5116
+ }
4928
5117
  }
4929
5118
  async sessionExists(conversation) {
4930
5119
  const chat2 = await this.#store.getChat(conversation.chatId);
4931
5120
  if (!chat2 || chat2.userId !== conversation.userId) return false;
4932
- return (await this.#directory.load(conversation))?.path.isRoot ?? false;
5121
+ const thread = await this.#directory.load(conversation);
5122
+ return thread !== void 0 && this.#ownsRoot(thread);
5123
+ }
5124
+ /** A root thread this runtime's root declaration started. */
5125
+ #ownsRoot(thread) {
5126
+ return thread.path.isRoot && thread.declarationName === this.info.root;
5127
+ }
5128
+ /** A thread of a tree this runtime's root declaration started: that root, or a sub-agent under it. */
5129
+ async #ownsTree(thread) {
5130
+ if (thread.path.isRoot) return this.#ownsRoot(thread);
5131
+ const root = await this.#directory.load({
5132
+ chatId: thread.treeId,
5133
+ userId: thread.conversation.userId
5134
+ });
5135
+ return root !== void 0 && this.#ownsRoot(root);
4933
5136
  }
4934
5137
  async enqueue(conversation, turn) {
4935
5138
  const streamId = await this.#controlPlane.enqueue(conversation, turn);
@@ -4962,8 +5165,9 @@ var RuntimeHost = class {
4962
5165
  subscribeConversationStatus(signal) {
4963
5166
  return this.#conversationStatus.subscribe(signal);
4964
5167
  }
5168
+ /** Available unless its status is `active`: a failed latest turn is no reason to hold work back. */
4965
5169
  async #isConversationAvailable(conversation) {
4966
- return await this.#queue.getTurnActivity(conversation) === "idle" && !await this.#approvals.isConversationPaused(conversation);
5170
+ return (await this.#conversationStatus.read(conversation)).type !== "active";
4967
5171
  }
4968
5172
  async #readConversationMetadata(conversation) {
4969
5173
  const chat2 = await this.#store.getChat(conversation.chatId);
@@ -4989,7 +5193,7 @@ var RuntimeHost = class {
4989
5193
  }
4990
5194
  return [];
4991
5195
  }
4992
- return thread.path.isRoot && thread.declarationName === this.info.root ? [{ chat: chat2, conversation }] : [];
5196
+ return this.#ownsRoot(thread) ? [{ chat: chat2, conversation }] : [];
4993
5197
  });
4994
5198
  return Promise.all(
4995
5199
  roots.map(async ({ chat: chat2, conversation }) => ({
@@ -5018,12 +5222,11 @@ var RuntimeHost = class {
5018
5222
  }
5019
5223
  async #startWorkers(options) {
5020
5224
  await using workers = new AsyncDisposableStack();
5021
- await this.#plugins.startWorkers(workers, true);
5225
+ await this.#plugins.startWorkers(workers);
5022
5226
  const reconcilesAvailability = this.#plugins.reconcilesAvailability;
5023
5227
  workers.use(
5024
5228
  await this.#queue.consume(this.#executor.execute.bind(this.#executor), {
5025
5229
  concurrency: options?.concurrency,
5026
- waitForActive: true,
5027
5230
  onOrphaned: this.#onOrphaned.bind(this),
5028
5231
  onSettled: async ({ chatId, userId }) => {
5029
5232
  await this.#conversationStatus.publish({ chatId, userId });
@@ -5711,8 +5914,11 @@ export {
5711
5914
  AgentStorageDatabaseMismatchError,
5712
5915
  AgentThread,
5713
5916
  AgentThreadLimitError,
5917
+ CodeModeTools,
5714
5918
  ConversationNotFoundError,
5715
5919
  DEFAULT_CONVERSATION_STATUS_CHANNEL,
5920
+ DirectMessaging,
5921
+ DirectTools,
5716
5922
  EmbeddedAgentStorage,
5717
5923
  EmbeddedAgentStorageInUseError,
5718
5924
  InterAgentCommunicationTypes,
@@ -5722,10 +5928,16 @@ export {
5722
5928
  PgBossTurnQueue,
5723
5929
  PostgresAgentStorage,
5724
5930
  PostgresMailboxStore,
5931
+ Spawning,
5725
5932
  SqliteMailboxStore,
5726
5933
  StaleTurnError,
5934
+ Supervision,
5935
+ Team,
5936
+ ToolNamespace,
5727
5937
  TurnNotFoundError,
5728
5938
  TurnQueue,
5939
+ WaitBounds,
5940
+ Waiting,
5729
5941
  assertCommunication,
5730
5942
  createInterAgentCommunication,
5731
5943
  defineAgent,