glove-foundry 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -285,8 +285,12 @@ Provisioning modes:
285
285
 
286
286
  The data adapter atomically enforces `provisioningKey`. Inbound delivery claims are also adapter-backed, so retrying the same route/event does not create duplicate runs.
287
287
 
288
+ A conversation has one run at a time. An inbound event for a thread whose run is still working joins that run's turn at its next tool step; one that arrives during its final answer starts the thread's next run once it is free. Until a run has finished with an event, the event is kept as pending in the data adapter (`FileFoundryDataAdapter` keeps it on disk; custom adapters implement the optional `putPendingInbound`, `deletePendingInbound` and `listPendingInbound`), and a restart delivers it again.
289
+
288
290
  ## Conversations and shared work
289
291
 
292
+ Different conversations run in parallel; one conversation runs one run at a time. A run asked for while another holds the conversation waits (pending, holding no concurrency slot, its wait not counted against its timeout) and starts once the run ahead has finished. Steering's replacement goes ahead of waiting runs. Schedule firings wait in their process, before reading history.
293
+
290
294
  One agent instance can own many conversations. Messages use native Glove content parts,
291
295
  and media parts may retain an optional human-facing filename. The server keeps JSON at
292
296
  a conservative 1 MB by default; a trusted multimodal deployment can set the typed
@@ -345,6 +349,79 @@ Its `layers` and `subscribers` mount when the subagent is invoked and are
345
349
  disposed when its request ends. Parent subscribers still receive the subagent
346
350
  lifecycle bracket, so delegation remains visible in the same run trace.
347
351
 
352
+ ## Layered agents: delegates
353
+
354
+ Split an assistant by how fast each part must answer, what it must remember,
355
+ and how long it runs. The agent that talks to the person stays fast and keeps
356
+ their context; sibling agents do the slow, tool-heavy work in their own
357
+ processes and conversations, and report back.
358
+
359
+ ```ts
360
+ // agents/assistant/agent.ts — the interactor
361
+ export default defineAgent({
362
+ description: "Talks with the person and hands work to the others",
363
+ model: fastModel,
364
+ systemPrompt: interactorPrompt,
365
+ memory: [personal],
366
+ delegates: [
367
+ { agent: "coder", description: "Writes and runs code. Takes minutes." },
368
+ { agent: "researcher", description: "Reads the web and cites sources." },
369
+ ],
370
+ })
371
+
372
+ // agents/coder/agent.ts — a worker
373
+ export default defineAgent({
374
+ description: "Writes and runs code in a sandbox",
375
+ model: strongModel,
376
+ systemPrompt: coderPrompt,
377
+ workingEnvironment: coderWorkspace,
378
+ answerWaitMs: 120_000,
379
+ })
380
+ ```
381
+
382
+ `delegates` names siblings by route and adds two tools to the interactor:
383
+ `glove_foundry_delegate` hands off a task and returns at once, and
384
+ `glove_foundry_reply` answers a worker's question or sends more instructions.
385
+ Each delegation runs as its own conversation on a worker instance (one per
386
+ interactor instance and worker), which carries the interactor instance's
387
+ context. The worker gets `glove_foundry_ask`; its final reply is the result.
388
+
389
+ Results and questions come back to the conversation that delegated. A handler
390
+ registered with `ctx.onDelegationUpdate` (`voiceCall` uses one) takes them
391
+ directly. Otherwise, one that arrives while the delegating turn is still
392
+ calling tools joins it at the next tool step as a Glove event, read as the same
393
+ `<delegation>` message. Anything the run did not read goes back to the runtime
394
+ when it ends and, once the conversation is free, starts one run carrying
395
+ everything that arrived. A worker's question waits up to `answerWaitMs`
396
+ (default 90 s) inside the same run, so a worker holding a browser or sandbox
397
+ session keeps it; after that the run suspends and the answer starts a new run
398
+ in the same conversation. Follow-up replies reach a worker that is still
399
+ working at its next tool step. Open
400
+ delegations appear in the interactor's runtime context, and
401
+ `runtime.listDelegations()` lists them all. See
402
+ [`examples/foundry-layered-assistant`](../../examples/foundry-layered-assistant).
403
+
404
+ ## Voice calls
405
+
406
+ `glove-foundry/voice` runs an agent as a live call. Use it as the definition's
407
+ `run`; the agent's model must be `s2sDrivenModel(...)`.
408
+
409
+ ```ts
410
+ import { voiceCall, webSocketRoom } from "glove-foundry/voice"
411
+
412
+ run: voiceCall({
413
+ room: (ctx) => webSocketRoom({ port: callPort(ctx), token: callToken(ctx) }),
414
+ greeting: "Greet the caller in one short sentence.",
415
+ })
416
+ ```
417
+
418
+ The call uses the assembled agent's prompt, tools and runtime context, saves
419
+ what both sides say to the conversation store, and speaks delegation results
420
+ and questions at the next pause. Foundry's bookkeeping tools and any tool that
421
+ needs an approval stay off the call; delegate that work instead. A room is any
422
+ `{ open(call), close() }`: `webSocketRoom` serves PCM16 over one WebSocket, and
423
+ a LiveKit or phone room calls `call.joined()` and `call.left()` the same way.
424
+
348
425
  ## Programmatic tool workflows
349
426
 
350
427
  `defineRepl` can expose an explicit projection of the fully assembled agent as
@@ -0,0 +1,530 @@
1
+ // src/delegation.ts
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdir, readdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { defaultEventFormatter } from "glove-core";
6
+ import { z } from "zod";
7
+ var FOUNDRY_MAILBOX_DIRECTORY_ENV = "GLOVE_FOUNDRY_MAILBOX_DIRECTORY";
8
+ var FOUNDRY_CONVERSATION_LISTEN_EVENT = "foundry.conversation.listen";
9
+ var FOUNDRY_CONVERSATION_LEASE_EVENT = "foundry.conversation.lease";
10
+ var DELEGATION_ID = /^delegation_[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
11
+ var ROUTE = /^[a-z][a-z0-9-]*(?:\/[a-z][a-z0-9-]*)*$/;
12
+ function isDelegationUpdate(delivery) {
13
+ return delivery.kind === "result" || delivery.kind === "question" || delivery.kind === "failed";
14
+ }
15
+ function isDelegationId(value) {
16
+ return DELEGATION_ID.test(value);
17
+ }
18
+ function newDelegationId() {
19
+ return `delegation_${randomUUID()}`;
20
+ }
21
+ function workerAgentId(delegatorAgentId, route) {
22
+ return `${delegatorAgentId}.${route.replaceAll("/", ".")}`;
23
+ }
24
+ function normalizeDelegates(delegates) {
25
+ const seen = /* @__PURE__ */ new Map();
26
+ for (const delegate of delegates) {
27
+ const options = typeof delegate === "string" ? { agent: delegate } : delegate;
28
+ if (!ROUTE.test(options.agent) || options.agent.includes("__")) {
29
+ throw new Error(
30
+ `Invalid delegate "${options.agent}". Name a sibling agent by its route, such as "coder" for agents/coder/agent.ts.`
31
+ );
32
+ }
33
+ if (seen.has(options.agent)) {
34
+ throw new Error(`Delegate "${options.agent}" is listed twice.`);
35
+ }
36
+ seen.set(options.agent, {
37
+ agent: options.agent,
38
+ description: options.description ?? `The ${options.agent} agent.`
39
+ });
40
+ }
41
+ return [...seen.values()];
42
+ }
43
+ function delegationFromContext(context) {
44
+ const value = context?.delegation;
45
+ if (!value || typeof value !== "object") return void 0;
46
+ const item = value;
47
+ return typeof item.id === "string" && typeof item.to === "string" && typeof item.workerAgentId === "string" && typeof item.task === "string" && typeof item.status === "string" && item.from && typeof item.from === "object" ? item : void 0;
48
+ }
49
+ function undeliveredUpdate(delegation) {
50
+ const base = { delegationId: delegation.id, agent: delegation.to, task: delegation.task };
51
+ if (delegation.undelivered === "result") return { kind: "result", ...base, result: delegation.result ?? "" };
52
+ if (delegation.undelivered === "question") return { kind: "question", ...base, question: delegation.question ?? "" };
53
+ if (delegation.undelivered === "failed") return { kind: "failed", ...base, error: delegation.error ?? "" };
54
+ return void 0;
55
+ }
56
+ function isOpenDelegation(delegation) {
57
+ return delegation.status === "working" || delegation.status === "waiting";
58
+ }
59
+ function clip(text, max) {
60
+ const flat = text.replace(/\s+/g, " ").trim();
61
+ return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
62
+ }
63
+ function escapeAttribute(value) {
64
+ return value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;");
65
+ }
66
+ function renderDelegatedTask(input) {
67
+ return [
68
+ `<delegated-task id="${escapeAttribute(input.delegationId)}" from="${escapeAttribute(input.from)}">`,
69
+ input.task,
70
+ "</delegated-task>",
71
+ `Work on this task. Your final reply is sent back to the ${input.from} agent automatically, so make it the answer itself.`,
72
+ "If you cannot continue without something only they or the user know, call glove_foundry_ask with one clear question."
73
+ ].join("\n");
74
+ }
75
+ function renderDelivery(delivery) {
76
+ if (delivery.kind === "transmission") return delivery.message;
77
+ if (delivery.kind === "reply") {
78
+ return [
79
+ `<delegation-reply id="${escapeAttribute(delivery.delegationId)}" from="${escapeAttribute(delivery.from)}">`,
80
+ delivery.message,
81
+ "</delegation-reply>"
82
+ ].join("\n");
83
+ }
84
+ const status = delivery.kind === "result" ? "completed" : delivery.kind;
85
+ const open = `<delegation id="${escapeAttribute(delivery.delegationId)}" agent="${escapeAttribute(delivery.agent)}" status="${status}">`;
86
+ const task = `Task: ${clip(delivery.task, 240)}`;
87
+ if (delivery.kind === "result") {
88
+ return [open, task, "Result:", delivery.result, "</delegation>"].join("\n");
89
+ }
90
+ if (delivery.kind === "question") {
91
+ return [
92
+ open,
93
+ task,
94
+ `The ${delivery.agent} agent needs an answer to continue: ${delivery.question}`,
95
+ "If you already know the answer, reply with glove_foundry_reply. Otherwise ask the user, then reply.",
96
+ "</delegation>"
97
+ ].join("\n");
98
+ }
99
+ return [open, task, `It stopped: ${delivery.error}`, "</delegation>"].join("\n");
100
+ }
101
+ function renderDeliveries(deliveries) {
102
+ return deliveries.map(renderDelivery).join("\n\n");
103
+ }
104
+ function renderOpenDelegations(open) {
105
+ if (open.length === 0) return null;
106
+ const lines = open.map(
107
+ (item) => item.status === "waiting" ? `- ${item.id} (${item.to}): waiting for your answer to "${clip(item.question ?? "", 200)}"` : `- ${item.id} (${item.to}): working on "${clip(item.task, 160)}"`
108
+ );
109
+ return [
110
+ "Delegations still open (results and questions arrive as <delegation> messages):",
111
+ ...lines
112
+ ].join("\n");
113
+ }
114
+ function commandId() {
115
+ return `command_${randomUUID()}`;
116
+ }
117
+ function createDelegatorTools(context, delegates, onDelegated, onReplied = () => {
118
+ }) {
119
+ if (delegates.length === 0) return [];
120
+ const routes = delegates.map((delegate) => delegate.agent);
121
+ const listing = delegates.map((delegate) => `- ${delegate.agent}: ${delegate.description}`).join("\n");
122
+ return [
123
+ {
124
+ name: "glove_foundry_delegate",
125
+ description: [
126
+ "Hand a task to another agent and carry on. This returns at once with a delegation id.",
127
+ "The agent's result, or a question it needs answered, arrives later as a message in <delegation> tags; it is not from the user.",
128
+ "Write the task so it stands alone: the other agent cannot see this conversation.",
129
+ "Agents you can delegate to:",
130
+ listing
131
+ ].join("\n"),
132
+ inputSchema: z.object({
133
+ to: z.enum(routes).describe("Which agent to hand the task to."),
134
+ task: z.string().min(1).describe("Everything the agent needs to do the work, in one message.")
135
+ }),
136
+ async do(input) {
137
+ const delegationId = newDelegationId();
138
+ context.emit({
139
+ id: commandId(),
140
+ type: "delegate",
141
+ definitionId: context.definitionId,
142
+ agentId: context.agentId,
143
+ conversationId: context.conversationId,
144
+ workspaceId: context.workspaceId,
145
+ delegationId,
146
+ to: input.to,
147
+ task: input.task
148
+ });
149
+ onDelegated({ id: delegationId, to: input.to, task: input.task });
150
+ return {
151
+ status: "success",
152
+ data: { delegationId, to: input.to, status: "working" }
153
+ };
154
+ }
155
+ },
156
+ {
157
+ name: "glove_foundry_reply",
158
+ description: "Answer a question from an agent you delegated to, or send it more instructions about that task. Use the delegation id from the <delegation> message.",
159
+ inputSchema: z.object({
160
+ delegationId: z.string().min(1).describe("The id from the delegation."),
161
+ message: z.string().min(1).describe("The answer or the new instructions.")
162
+ }),
163
+ async do(input) {
164
+ if (!isDelegationId(input.delegationId)) {
165
+ return {
166
+ status: "error",
167
+ data: null,
168
+ message: `"${input.delegationId}" is not a delegation id.`
169
+ };
170
+ }
171
+ context.emit({
172
+ id: commandId(),
173
+ type: "delegate.reply",
174
+ definitionId: context.definitionId,
175
+ agentId: context.agentId,
176
+ conversationId: context.conversationId,
177
+ workspaceId: context.workspaceId,
178
+ delegationId: input.delegationId,
179
+ message: input.message
180
+ });
181
+ onReplied(input.delegationId);
182
+ return { status: "success", data: { delegationId: input.delegationId, sent: true } };
183
+ }
184
+ }
185
+ ];
186
+ }
187
+ function createWorkerTools(context, delegation, options) {
188
+ return [
189
+ {
190
+ name: "glove_foundry_ask",
191
+ description: [
192
+ `Ask the ${delegation.from.definitionId} agent, who gave you this task, one question you cannot answer yourself.`,
193
+ "They answer from what they know or ask the user. If the answer comes quickly it is returned here; otherwise end your turn and it arrives as your next message."
194
+ ].join(" "),
195
+ inputSchema: z.object({
196
+ question: z.string().min(1).describe("One clear question, with the options if there are any.")
197
+ }),
198
+ async do(input) {
199
+ const command = {
200
+ id: commandId(),
201
+ type: "delegate.ask",
202
+ definitionId: context.definitionId,
203
+ agentId: context.agentId,
204
+ conversationId: context.conversationId,
205
+ workspaceId: context.workspaceId,
206
+ delegationId: delegation.id,
207
+ question: input.question
208
+ };
209
+ options.pending.current = {
210
+ commandId: command.id,
211
+ delegationId: delegation.id,
212
+ question: input.question
213
+ };
214
+ const reply = options.waitForReply(options.answerWaitMs);
215
+ context.emit(command);
216
+ const answer = await reply;
217
+ if (answer) {
218
+ options.pending.current = void 0;
219
+ return { status: "success", data: { answered: true, answer: answer.message } };
220
+ }
221
+ return {
222
+ status: "success",
223
+ data: {
224
+ answered: false,
225
+ note: "No answer yet. End your turn now with one short line saying what you are waiting for. The answer will arrive as your next message."
226
+ }
227
+ };
228
+ }
229
+ }
230
+ ];
231
+ }
232
+ function conversationDirectory(directory, conversationId) {
233
+ return join(directory, Buffer.from(conversationId, "utf8").toString("hex"));
234
+ }
235
+ async function writeMailboxDelivery(directory, conversationId, delivery) {
236
+ const target = conversationDirectory(directory, conversationId);
237
+ await mkdir(target, { recursive: true, mode: 448 });
238
+ const name = `${Date.now().toString().padStart(15, "0")}-${randomUUID()}.json`;
239
+ const temporary = join(target, `.tmp-${name}`);
240
+ await writeFile(temporary, `${JSON.stringify(delivery)}
241
+ `, { encoding: "utf8", mode: 384 });
242
+ await rename(temporary, join(target, name));
243
+ }
244
+ var DELIVERY_SCHEMA = z.union([
245
+ z.object({
246
+ kind: z.literal("reply"),
247
+ delegationId: z.string(),
248
+ from: z.string(),
249
+ message: z.string()
250
+ }),
251
+ z.object({
252
+ kind: z.literal("result"),
253
+ delegationId: z.string(),
254
+ agent: z.string(),
255
+ task: z.string(),
256
+ result: z.string()
257
+ }),
258
+ z.object({
259
+ kind: z.literal("question"),
260
+ delegationId: z.string(),
261
+ agent: z.string(),
262
+ task: z.string(),
263
+ question: z.string()
264
+ }),
265
+ z.object({
266
+ kind: z.literal("failed"),
267
+ delegationId: z.string(),
268
+ agent: z.string(),
269
+ task: z.string(),
270
+ error: z.string()
271
+ }),
272
+ z.object({
273
+ kind: z.literal("transmission"),
274
+ pendingId: z.string(),
275
+ routeId: z.string(),
276
+ eventId: z.string(),
277
+ message: z.string()
278
+ })
279
+ ]);
280
+ async function drainMailbox(directory, conversationId) {
281
+ const target = conversationDirectory(directory, conversationId);
282
+ let names;
283
+ try {
284
+ names = (await readdir(target)).filter((name) => name.endsWith(".json") && !name.startsWith(".tmp-")).sort();
285
+ } catch (cause) {
286
+ if (cause.code === "ENOENT") return [];
287
+ throw cause;
288
+ }
289
+ const deliveries = [];
290
+ for (const name of names) {
291
+ const path = join(target, name);
292
+ let text;
293
+ try {
294
+ text = await readFile(path, "utf8");
295
+ await unlink(path);
296
+ } catch (cause) {
297
+ if (cause.code === "ENOENT") continue;
298
+ throw cause;
299
+ }
300
+ const parsed = DELIVERY_SCHEMA.safeParse(JSON.parse(text));
301
+ if (parsed.success) deliveries.push(parsed.data);
302
+ }
303
+ return deliveries;
304
+ }
305
+ function listenToConversation(options) {
306
+ const pollMs = options.pollMs ?? 100;
307
+ let stopped = false;
308
+ let timer;
309
+ let polling = Promise.resolve();
310
+ const reported = Promise.resolve(options.report("on"));
311
+ const poll = async () => {
312
+ const deliveries = await drainMailbox(options.directory, options.conversationId);
313
+ if (deliveries.length > 0) await options.handler(deliveries);
314
+ };
315
+ const tick = () => {
316
+ if (stopped) return;
317
+ polling = poll().catch((cause) => {
318
+ process.stderr.write(
319
+ `Foundry mailbox read failed: ${cause instanceof Error ? cause.message : String(cause)}
320
+ `
321
+ );
322
+ }).finally(() => {
323
+ if (!stopped) timer = setTimeout(tick, pollMs);
324
+ });
325
+ };
326
+ void reported.then(tick);
327
+ return {
328
+ async stop(beforeOff) {
329
+ if (stopped) return;
330
+ stopped = true;
331
+ if (timer) clearTimeout(timer);
332
+ await reported;
333
+ await polling;
334
+ try {
335
+ if (beforeOff) await beforeOff();
336
+ } finally {
337
+ await options.report("off");
338
+ }
339
+ }
340
+ };
341
+ }
342
+ function openRunMailbox(options) {
343
+ const waiters = /* @__PURE__ */ new Map();
344
+ const handlers = /* @__PURE__ */ new Set();
345
+ let closed = false;
346
+ const toHandlers = async (updates) => {
347
+ for (const handler of [...handlers]) await handler(updates);
348
+ };
349
+ const listener = listenToConversation({
350
+ directory: options.directory,
351
+ conversationId: options.conversationId,
352
+ report: options.report,
353
+ ...options.pollMs !== void 0 ? { pollMs: options.pollMs } : {},
354
+ handler: async (deliveries) => {
355
+ const replies = /* @__PURE__ */ new Map();
356
+ const updates = [];
357
+ const rest = [];
358
+ for (const delivery of deliveries) {
359
+ if (delivery.kind === "reply" && waiters.has(delivery.delegationId)) {
360
+ replies.set(delivery.delegationId, [...replies.get(delivery.delegationId) ?? [], delivery]);
361
+ } else if (isDelegationUpdate(delivery) && handlers.size > 0) {
362
+ updates.push(delivery);
363
+ } else {
364
+ rest.push(delivery);
365
+ }
366
+ }
367
+ for (const [delegationId, batch] of replies) {
368
+ waiters.get(delegationId)?.({ ...batch[0], message: batch.map((reply) => reply.message).join("\n\n") });
369
+ }
370
+ if (updates.length > 0) await toHandlers(updates);
371
+ if (rest.length > 0) await options.sink.forward(rest);
372
+ }
373
+ });
374
+ return {
375
+ waitForReply(delegationId, timeoutMs, signal) {
376
+ return new Promise((resolveReply) => {
377
+ if (closed || timeoutMs <= 0 || signal.aborted || waiters.has(delegationId)) {
378
+ resolveReply(null);
379
+ return;
380
+ }
381
+ const finish = (reply) => {
382
+ if (waiters.get(delegationId) !== finish) return;
383
+ waiters.delete(delegationId);
384
+ clearTimeout(timer);
385
+ signal.removeEventListener("abort", onAbort);
386
+ resolveReply(reply);
387
+ };
388
+ const onAbort = () => finish(null);
389
+ const timer = setTimeout(() => finish(null), timeoutMs);
390
+ waiters.set(delegationId, finish);
391
+ signal.addEventListener("abort", onAbort, { once: true });
392
+ });
393
+ },
394
+ onUpdates(handler) {
395
+ handlers.add(handler);
396
+ const waiting = options.sink.reclaim(isDelegationUpdate).then(async (updates) => {
397
+ if (updates.length > 0) await handler(updates);
398
+ });
399
+ return async () => {
400
+ handlers.delete(handler);
401
+ await waiting;
402
+ };
403
+ },
404
+ async close() {
405
+ if (closed) return;
406
+ closed = true;
407
+ for (const finish of [...waiters.values()]) finish(null);
408
+ await listener.stop(async () => {
409
+ for (const delivery of await options.sink.reclaim(() => true)) {
410
+ await writeMailboxDelivery(options.directory, options.conversationId, delivery);
411
+ }
412
+ });
413
+ }
414
+ };
415
+ }
416
+ var DELIVERY_KEY = "foundry_delivery";
417
+ function deliveryEvent(delivery) {
418
+ if (delivery.kind === "transmission") {
419
+ return {
420
+ id: `transmission:${delivery.pendingId}:${randomUUID()}`,
421
+ source: `foundry:route:${delivery.routeId}`,
422
+ kind: "transmission",
423
+ content: delivery.message,
424
+ metadata: { [DELIVERY_KEY]: delivery }
425
+ };
426
+ }
427
+ const from = delivery.kind === "reply" ? delivery.from : delivery.agent;
428
+ return {
429
+ id: `${delivery.kind}:${delivery.delegationId}:${randomUUID()}`,
430
+ source: `foundry:${from}`,
431
+ kind: `delegation.${delivery.kind}`,
432
+ content: renderDelivery(delivery),
433
+ metadata: { [DELIVERY_KEY]: delivery }
434
+ };
435
+ }
436
+ function deliveryOf(event) {
437
+ return event.metadata?.[DELIVERY_KEY];
438
+ }
439
+ var formatRunEvents = (events, phase) => {
440
+ const deliveries = events.map(deliveryOf).filter((delivery) => Boolean(delivery));
441
+ const others = events.filter((event) => !deliveryOf(event));
442
+ const text = renderDeliveries(deliveries);
443
+ if (others.length === 0) return { sender: "user", framework_context: "event", text };
444
+ const rest = defaultEventFormatter(others, phase);
445
+ if (deliveries.length === 0) return rest;
446
+ return {
447
+ ...rest,
448
+ text: `${text}
449
+
450
+ ${rest.text}`,
451
+ ...rest.content ? { content: [{ type: "text", text }, ...rest.content] } : {}
452
+ };
453
+ };
454
+ var RunEventQueue = class {
455
+ events = [];
456
+ async push(event) {
457
+ if (this.events.some((queued) => queued.id === event.id)) return false;
458
+ this.events.push(structuredClone(event));
459
+ return true;
460
+ }
461
+ async peek() {
462
+ return structuredClone(this.events);
463
+ }
464
+ async take() {
465
+ const taken = this.events;
466
+ this.events = [];
467
+ return taken;
468
+ }
469
+ async remove(ids) {
470
+ const drop = new Set(ids);
471
+ this.events = this.events.filter((event) => !drop.has(event.id));
472
+ }
473
+ /** Remove and return queued deliveries that match, with their event ids, in one step. */
474
+ async reclaim(match) {
475
+ const taken = [];
476
+ this.events = this.events.filter((event) => {
477
+ const delivery = deliveryOf(event);
478
+ if (!delivery || !match(delivery)) return true;
479
+ taken.push({ id: event.id, delivery });
480
+ return false;
481
+ });
482
+ return taken;
483
+ }
484
+ };
485
+ function leaseFile(directory, runId) {
486
+ return join(directory, ".leases", Buffer.from(runId, "utf8").toString("hex"));
487
+ }
488
+ async function writeConversationLease(directory, runId) {
489
+ await mkdir(join(directory, ".leases"), { recursive: true, mode: 448 });
490
+ await writeFile(leaseFile(directory, runId), "", { mode: 384 });
491
+ }
492
+ async function waitForConversationLease(directory, runId, signal, pollMs = 25) {
493
+ const file = leaseFile(directory, runId);
494
+ for (; ; ) {
495
+ if (signal.aborted) throw new Error("The run was cancelled while it waited for its conversation.");
496
+ try {
497
+ await unlink(file);
498
+ return;
499
+ } catch (cause) {
500
+ if (cause.code !== "ENOENT") throw cause;
501
+ }
502
+ await new Promise((resolveWait) => setTimeout(resolveWait, pollMs));
503
+ }
504
+ }
505
+
506
+ export {
507
+ FOUNDRY_MAILBOX_DIRECTORY_ENV,
508
+ FOUNDRY_CONVERSATION_LISTEN_EVENT,
509
+ FOUNDRY_CONVERSATION_LEASE_EVENT,
510
+ isDelegationUpdate,
511
+ isDelegationId,
512
+ workerAgentId,
513
+ normalizeDelegates,
514
+ delegationFromContext,
515
+ undeliveredUpdate,
516
+ isOpenDelegation,
517
+ renderDelegatedTask,
518
+ renderDeliveries,
519
+ renderOpenDelegations,
520
+ createDelegatorTools,
521
+ createWorkerTools,
522
+ writeMailboxDelivery,
523
+ drainMailbox,
524
+ openRunMailbox,
525
+ deliveryEvent,
526
+ formatRunEvents,
527
+ RunEventQueue,
528
+ writeConversationLease,
529
+ waitForConversationLease
530
+ };
@@ -248,6 +248,9 @@ function validateDefinition(options, route) {
248
248
  if (options.model && options.systemPrompt === void 0) {
249
249
  throw new Error(`Foundry agent "${id ?? "<file route>"}" must define systemPrompt when it defines a model.`);
250
250
  }
251
+ if (options.answerWaitMs !== void 0 && (!Number.isFinite(options.answerWaitMs) || options.answerWaitMs < 0)) {
252
+ throw new Error(`Foundry agent "${id ?? "<file route>"}" answerWaitMs must be a non-negative number.`);
253
+ }
251
254
  if (options.inboxes !== void 0 && typeof options.inboxes !== "function") {
252
255
  throw new Error(
253
256
  `Foundry agent "${id ?? "<file route>"}" inboxes must be a lazy resolver function.`
@@ -291,6 +294,8 @@ var CONVENTION_EXPORTS = [
291
294
  "hooks",
292
295
  "skills",
293
296
  "subagents",
297
+ "delegates",
298
+ "answerWaitMs",
294
299
  "memory",
295
300
  "goals",
296
301
  "facts",
@@ -8,7 +8,7 @@ import {
8
8
  fileDefinitionLabel,
9
9
  fileIdentified,
10
10
  internalAgentName
11
- } from "./chunk-PVOKR4CN.js";
11
+ } from "./chunk-K2EU63MB.js";
12
12
 
13
13
  // src/application.ts
14
14
  var FOUNDRY_APPLICATION_BRAND = /* @__PURE__ */ Symbol.for(
@@ -1171,6 +1171,7 @@ var MemoryFoundryDataAdapter = class {
1171
1171
  agentsByProvisioningKey = /* @__PURE__ */ new Map();
1172
1172
  subscriptions = /* @__PURE__ */ new Map();
1173
1173
  inboundDeliveries = /* @__PURE__ */ new Map();
1174
+ pendingInbound = /* @__PURE__ */ new Map();
1174
1175
  activations = /* @__PURE__ */ new Map();
1175
1176
  conversations = /* @__PURE__ */ new Map();
1176
1177
  workspace = /* @__PURE__ */ new Map();
@@ -1303,6 +1304,19 @@ var MemoryFoundryDataAdapter = class {
1303
1304
  }
1304
1305
  });
1305
1306
  }
1307
+ putPendingInbound(record) {
1308
+ return Effect3.sync(() => {
1309
+ this.pendingInbound.set(record.id, structuredClone(record));
1310
+ });
1311
+ }
1312
+ deletePendingInbound(id2) {
1313
+ return Effect3.sync(() => {
1314
+ this.pendingInbound.delete(id2);
1315
+ });
1316
+ }
1317
+ listPendingInbound() {
1318
+ return Effect3.sync(() => [...this.pendingInbound.values()].map((record) => structuredClone(record)));
1319
+ }
1306
1320
  getActivation(id2) {
1307
1321
  return Effect3.succeed(this.activations.get(id2) ?? null);
1308
1322
  }