glove-foundry 0.6.0 → 0.7.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.
@@ -1,18 +1,1024 @@
1
1
  import {
2
- compileAgentModule
3
- } from "./chunk-TFGETZYH.js";
4
- import "./chunk-RSU7NEDK.js";
2
+ mountFoundryGuidance,
3
+ mountFoundryWorkbench
4
+ } from "./chunk-IPASF7PK.js";
5
5
  import {
6
- bindAgentLocalDefinitions
7
- } from "./chunk-OBTOFA7W.js";
8
- import "./chunk-B36BGF5R.js";
9
- import "./chunk-K2EU63MB.js";
6
+ EMPTY_FOUNDRY_APPLICATION,
7
+ FOUNDRY_APPROVAL_DIRECTORY_ENV,
8
+ FOUNDRY_COMPOSED_PLAYBOOK_BRAND,
9
+ FOUNDRY_CORE_COMMAND_EVENT,
10
+ FoundryApprovalDisplayManager,
11
+ MemoryFoundryDataAdapter,
12
+ agentPlaybookId,
13
+ agentScheduleActivationId,
14
+ agentScheduleRevision,
15
+ bindAgentLocalDefinitions,
16
+ composedPlaybookRevision,
17
+ createFoundryCoreTools,
18
+ createInstalledApplicationTransmissionTools,
19
+ discoverAgents,
20
+ freezeGloveMessage,
21
+ isFoundryApplication,
22
+ isFoundrySchedule,
23
+ materializeComposedPlaybook,
24
+ normalizeScheduleTiming,
25
+ routeFromAgentFile,
26
+ toGloveMessage,
27
+ toGloveRequestInput,
28
+ withFoundryPermissions
29
+ } from "./chunk-EJZJAVNG.js";
30
+ import {
31
+ FOUNDRY_CONVERSATION_LEASE_EVENT,
32
+ FOUNDRY_CONVERSATION_LISTEN_EVENT,
33
+ FOUNDRY_MAILBOX_DIRECTORY_ENV,
34
+ RunEventQueue,
35
+ createDelegatorTools,
36
+ createWorkerTools,
37
+ delegationFromContext,
38
+ deliveryEvent,
39
+ formatRunEvents,
40
+ isDelegationUpdate,
41
+ isOpenDelegation,
42
+ normalizeDelegates,
43
+ openRunMailbox,
44
+ renderDeliveries,
45
+ renderOpenDelegations,
46
+ waitForConversationLease
47
+ } from "./chunk-AC6SRI5V.js";
48
+ import {
49
+ EMPTY_CAPABILITY_REGISTRY,
50
+ FOUNDRY_APPLICATION_ENV,
51
+ FOUNDRY_EVENT_PREFIX,
52
+ FOUNDRY_EXECUTION_MARKER,
53
+ FOUNDRY_RUN_PROCESS_EVENT,
54
+ createAgentMessagingTool,
55
+ defineAgentFromModule,
56
+ installRegistry,
57
+ internalAgentName,
58
+ isInboxCapableStore,
59
+ mountAgentDefinitionMemory,
60
+ mountFoundrySurfaces,
61
+ refreshDurableAuthority,
62
+ resolveResolvable
63
+ } from "./chunk-64UBLGYM.js";
10
64
 
11
65
  // src/execution-loader.ts
12
66
  import { dirname } from "node:path";
67
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
68
+
69
+ // src/agent-runtime.ts
13
70
  import { pathToFileURL } from "node:url";
71
+ import { Glove } from "glove-core";
72
+ import { mountMesh } from "glove-mesh";
73
+ import { Effect } from "effect";
74
+ import { signal } from "station-signal";
75
+ import { z } from "zod";
76
+ var DEFAULT_ANSWER_WAIT_MS = 9e4;
77
+ var INBOX_ITEMS_SCHEMA = z.array(z.object({
78
+ id: z.string().min(1),
79
+ tag: z.string(),
80
+ request: z.string(),
81
+ response: z.string().nullable(),
82
+ status: z.enum(["pending", "resolved", "consumed"]),
83
+ blocking: z.boolean(),
84
+ created_at: z.string(),
85
+ resolved_at: z.string().nullable()
86
+ }));
87
+ async function hydrateInbox(store, items, emit) {
88
+ if (!isInboxCapableStore(store)) {
89
+ throw new Error("Agent inbox loading requires an inbox-capable Glove StoreAdapter.");
90
+ }
91
+ const loaded = INBOX_ITEMS_SCHEMA.parse(items);
92
+ const existing = new Map((await store.getInboxItems()).map((item) => [item.id, item]));
93
+ let added = 0;
94
+ let updated = 0;
95
+ for (const item of loaded) {
96
+ const current = existing.get(item.id);
97
+ if (!current) {
98
+ await store.addInboxItem({ ...item });
99
+ added++;
100
+ continue;
101
+ }
102
+ if (current.status !== item.status || current.response !== item.response || current.resolved_at !== item.resolved_at) {
103
+ await store.updateInboxItem(item.id, {
104
+ status: item.status,
105
+ response: item.response,
106
+ resolved_at: item.resolved_at
107
+ });
108
+ updated++;
109
+ }
110
+ }
111
+ emit({
112
+ type: "foundry.definition.inboxes.loaded",
113
+ data: { count: loaded.length, added, updated }
114
+ });
115
+ }
116
+ function extractOutput(result) {
117
+ if (result == null || typeof result !== "object") return result;
118
+ const object = result;
119
+ if (Array.isArray(object.messages)) {
120
+ const last = object.messages.at(-1);
121
+ return last?.text ?? "";
122
+ }
123
+ return "text" in object ? object.text : result;
124
+ }
125
+ function serializable(value) {
126
+ try {
127
+ return JSON.parse(JSON.stringify(value));
128
+ } catch {
129
+ return String(value);
130
+ }
131
+ }
132
+ function writeAgentEvent(type, data) {
133
+ const line = `${FOUNDRY_EVENT_PREFIX}${JSON.stringify({
134
+ type,
135
+ data: serializable(data),
136
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
137
+ })}
138
+ `;
139
+ return new Promise((resolveWrite, rejectWrite) => {
140
+ process.stdout.write(line, (error) => {
141
+ if (error) rejectWrite(error);
142
+ else resolveWrite();
143
+ });
144
+ });
145
+ }
146
+ function executionSubscriber() {
147
+ return {
148
+ async record(eventType, data) {
149
+ await writeAgentEvent(eventType, data);
150
+ }
151
+ };
152
+ }
153
+ async function resolveAgentValue(definition, value, context, field) {
154
+ context.controls.emit({
155
+ type: "foundry.assembly.resolve.start",
156
+ data: { field }
157
+ });
158
+ const resolved = await resolveResolvable(
159
+ typeof value === "function" ? value(definition, context) : value
160
+ );
161
+ context.controls.emit({
162
+ type: "foundry.assembly.resolve.complete",
163
+ data: {
164
+ field,
165
+ count: Array.isArray(resolved) ? resolved.length : void 0
166
+ }
167
+ });
168
+ return resolved;
169
+ }
170
+ var HANDLER_ONLY_MODEL = {
171
+ name: "foundry-handler",
172
+ setSystemPrompt: () => void 0,
173
+ prompt: async () => {
174
+ throw new Error(
175
+ "This is a model-free Foundry agent. Define run/spawn or configure a model."
176
+ );
177
+ }
178
+ };
179
+ async function loadRuntimeApplication() {
180
+ const path = process.env[FOUNDRY_APPLICATION_ENV];
181
+ if (!path) return EMPTY_FOUNDRY_APPLICATION;
182
+ const imported = await import(pathToFileURL(path).href);
183
+ if (!isFoundryApplication(imported.default)) {
184
+ throw new Error(
185
+ `${path} must default-export defineApplication(...) for installation resolution.`
186
+ );
187
+ }
188
+ return imported.default;
189
+ }
190
+ async function executeSpawned(spawned, message, signal2) {
191
+ if (spawned && typeof spawned === "object" && "processRequest" in spawned && typeof spawned.processRequest === "function") {
192
+ return extractOutput(
193
+ await spawned.processRequest(toGloveRequestInput(message), signal2)
194
+ );
195
+ }
196
+ if (spawned && typeof spawned === "object" && "run" in spawned && typeof spawned.run === "function") {
197
+ return spawned.run(
198
+ message,
199
+ signal2
200
+ );
201
+ }
202
+ return spawned;
203
+ }
204
+ async function runDefinition(definition, id, runtimeValue) {
205
+ await writeAgentEvent(FOUNDRY_RUN_PROCESS_EVENT, { state: "acquired" }).catch(() => void 0);
206
+ try {
207
+ return await executeDefinition(definition, id, runtimeValue);
208
+ } finally {
209
+ await writeAgentEvent(FOUNDRY_RUN_PROCESS_EVENT, { state: "released" }).catch(() => void 0);
210
+ }
211
+ }
212
+ async function executeDefinition(definition, id, runtimeValue) {
213
+ let envelope = runtimeValue;
214
+ const expiredDeliveries = (envelope.events ?? []).filter((delivery) => delivery.durable?.event.expiresAt && Date.parse(delivery.durable.event.expiresAt) <= Date.now());
215
+ const expiredIds = new Set(expiredDeliveries.map((delivery) => delivery.durable.id));
216
+ envelope = { ...envelope, events: (envelope.events ?? []).filter((delivery) => !delivery.durable || !expiredIds.has(delivery.durable.id)) };
217
+ let request = envelope.request;
218
+ if (envelope.eventTurn && expiredIds.size) {
219
+ if (!envelope.events.length) return { status: "completed", value: null, agentId: request.agentId, conversationId: request.conversationId, workspaceId: request.workspaceId, consumedEventIds: [...expiredIds] };
220
+ request = { ...request, message: renderDeliveries(envelope.events) };
221
+ envelope = { ...envelope, request };
222
+ }
223
+ let input = request;
224
+ const runId = process.env.STATION_SIGNAL_RUN_ID ?? "unknown";
225
+ const subscriber = executionSubscriber();
226
+ const abortController = new AbortController();
227
+ const onTerminate = () => abortController.abort();
228
+ process.once("SIGTERM", onTerminate);
229
+ const leaseDirectory = process.env[FOUNDRY_MAILBOX_DIRECTORY_ENV];
230
+ if (!envelope.conversationLease && leaseDirectory) {
231
+ try {
232
+ await writeAgentEvent(FOUNDRY_CONVERSATION_LEASE_EVENT, { conversationId: request.conversationId });
233
+ await waitForConversationLease(leaseDirectory, runId, abortController.signal);
234
+ } catch (cause) {
235
+ process.removeListener("SIGTERM", onTerminate);
236
+ throw cause;
237
+ }
238
+ }
239
+ let disposeSurfaces;
240
+ const cleanups = [];
241
+ const application = await loadRuntimeApplication();
242
+ if (envelope.agent.durableSubagent && application.data) {
243
+ const refreshed = await refreshDurableAuthority(definition, envelope.agent, application.data);
244
+ request = { ...request, context: { ...request.context, durableMemoryOwners: refreshed.owners } };
245
+ envelope = { ...envelope, request, agent: refreshed.agent };
246
+ input = request;
247
+ }
248
+ const storeFactory = definition.store ?? application.conversationStore;
249
+ const store = storeFactory ? await storeFactory({
250
+ definitionId: id,
251
+ agentId: request.agentId,
252
+ conversationId: request.conversationId,
253
+ workspaceId: request.workspaceId
254
+ }) : null;
255
+ const runtimeStore = store ? withFoundryPermissions(store) : null;
256
+ const history = Object.freeze(
257
+ (runtimeStore ? await runtimeStore.getMessages() : []).map(freezeGloveMessage)
258
+ );
259
+ const message = toGloveMessage(request.message);
260
+ const messages = Object.freeze([...history, message]);
261
+ const controls = {
262
+ signal: abortController.signal,
263
+ commands: [],
264
+ emit: (event) => {
265
+ void writeAgentEvent(event.type, event.data).catch((cause) => {
266
+ process.stderr.write(
267
+ `Foundry failed to forward agent event: ${cause instanceof Error ? cause.message : String(cause)}
268
+ `
269
+ );
270
+ });
271
+ }
272
+ };
273
+ try {
274
+ const registry = definition.components ?? {
275
+ capabilities: EMPTY_CAPABILITY_REGISTRY,
276
+ native: { layers: Object.freeze([]), subscribers: Object.freeze([]) }
277
+ };
278
+ const installations = envelope.agent.installations;
279
+ const data = application.data ?? new MemoryFoundryDataAdapter();
280
+ const initialAssemblyContext = {
281
+ definitionId: id,
282
+ agentId: request.agentId,
283
+ conversationId: request.conversationId,
284
+ workspaceId: request.workspaceId,
285
+ name: internalAgentName(id),
286
+ runId,
287
+ mode: "agent",
288
+ request,
289
+ agentInstance: envelope.agent,
290
+ conversation: envelope.conversation,
291
+ activations: Object.freeze([...envelope.activations ?? []]),
292
+ delegations: Object.freeze([...envelope.delegations ?? []]),
293
+ ...delegationFromContext(envelope.conversation.context) ? { delegation: delegationFromContext(envelope.conversation.context) } : {},
294
+ data,
295
+ input,
296
+ message,
297
+ messageInput: request.message,
298
+ events: (envelope.events ?? []).map(deliveryEvent),
299
+ messageText: message.text,
300
+ history,
301
+ messages,
302
+ installations,
303
+ store: runtimeStore,
304
+ subscriber,
305
+ controls
306
+ };
307
+ const assemblyContext = initialAssemblyContext;
308
+ const resolveOptional = async (field, value, fallback) => value === void 0 ? fallback : resolveAgentValue(
309
+ definition,
310
+ value,
311
+ assemblyContext,
312
+ field
313
+ );
314
+ const [model, systemPrompt, displayManager, compactionLimit, compactionInstructions, maxTurns] = await Promise.all([
315
+ resolveOptional("model", definition.model, HANDLER_ONLY_MODEL),
316
+ resolveOptional("systemPrompt", definition.systemPrompt, ""),
317
+ resolveOptional(
318
+ "displayManager",
319
+ definition.displayManager,
320
+ new FoundryApprovalDisplayManager({
321
+ directory: process.env[FOUNDRY_APPROVAL_DIRECTORY_ENV],
322
+ runId,
323
+ definitionId: id,
324
+ agentId: request.agentId,
325
+ conversationId: request.conversationId,
326
+ workspaceId: request.workspaceId,
327
+ signal: abortController.signal,
328
+ emit: controls.emit
329
+ })
330
+ ),
331
+ resolveOptional("compactionLimit", definition.compactionLimit, void 0),
332
+ resolveOptional("compactionInstructions", definition.compactionInstructions, "Preserve goals, decisions, unresolved work, tool results, and pending inbox items."),
333
+ resolveOptional("maxTurns", definition.maxTurns, void 0)
334
+ ]);
335
+ const eventQueue = new RunEventQueue();
336
+ const base = new Glove({
337
+ ...runtimeStore ? { store: runtimeStore } : {},
338
+ events: { queue: eventQueue, policy: () => "defer", deferTimeoutMs: Infinity, formatter: formatRunEvents },
339
+ model,
340
+ displayManager,
341
+ systemPrompt,
342
+ serverMode: definition.serverMode ?? true,
343
+ ...definition.maxRetries !== void 0 ? { maxRetries: definition.maxRetries } : {},
344
+ ...definition.maxConsecutiveErrors !== void 0 ? { maxConsecutiveErrors: definition.maxConsecutiveErrors } : {},
345
+ compaction_config: {
346
+ compaction_instructions: compactionInstructions,
347
+ ...maxTurns !== void 0 ? { max_turns: maxTurns } : {},
348
+ ...compactionLimit !== void 0 ? { compaction_context_limit: compactionLimit } : {}
349
+ },
350
+ ...definition.enableToolResultSummary !== void 0 ? { enableToolResultSummary: definition.enableToolResultSummary } : {}
351
+ }).build();
352
+ base.addSubscriber(subscriber);
353
+ const [tools, hooks, skills, subagents, delegates, memory, inboxItems, layers, subscribers, calls, playbooks, schedules, mesh, workingEnvironment, repl] = await Promise.all([
354
+ resolveOptional("tools", definition.tools, []),
355
+ resolveOptional("hooks", definition.hooks, []),
356
+ resolveOptional("skills", definition.skills, []),
357
+ resolveOptional("subagents", definition.subagents, []),
358
+ resolveOptional("delegates", definition.delegates, []),
359
+ resolveOptional("memory", definition.memory, []),
360
+ definition.inboxes ? resolveAgentValue(
361
+ definition,
362
+ definition.inboxes,
363
+ assemblyContext,
364
+ "inboxes"
365
+ ) : Promise.resolve([]),
366
+ resolveOptional("layers", definition.layers, []),
367
+ resolveOptional("subscribers", definition.subscribers, []),
368
+ resolveOptional("calls", definition.calls, []),
369
+ resolveOptional("playbooks", definition.playbooks, []),
370
+ resolveOptional("schedules", definition.schedules, []),
371
+ resolveOptional("mesh", definition.mesh, void 0),
372
+ resolveOptional("workingEnvironment", definition.workingEnvironment, void 0),
373
+ resolveOptional("repl", definition.repl, void 0)
374
+ ]);
375
+ const playbookNames = /* @__PURE__ */ new Set();
376
+ const desiredPlaybooks = definition.playbooks === void 0 ? envelope.agent.playbooks : playbooks.map((playbook) => {
377
+ if (playbook[FOUNDRY_COMPOSED_PLAYBOOK_BRAND] !== true) {
378
+ throw new Error("Agent playbooks must be created at runtime with composePlaybook(...).");
379
+ }
380
+ if (playbookNames.has(playbook.name)) {
381
+ throw new Error(`Duplicate composed playbook name "${playbook.name}".`);
382
+ }
383
+ playbookNames.add(playbook.name);
384
+ const revision = composedPlaybookRevision(playbook);
385
+ return materializeComposedPlaybook(
386
+ playbook,
387
+ agentPlaybookId(id, request.agentId, playbook.name),
388
+ revision
389
+ );
390
+ });
391
+ if (definition.playbooks !== void 0) {
392
+ const playbookSync = {
393
+ id: `playbook_sync_${runId}`,
394
+ type: "playbook.sync",
395
+ definitionId: id,
396
+ agentId: request.agentId,
397
+ conversationId: request.conversationId,
398
+ workspaceId: request.workspaceId,
399
+ playbooks: desiredPlaybooks
400
+ };
401
+ controls.commands.push(playbookSync);
402
+ controls.emit({ type: FOUNDRY_CORE_COMMAND_EVENT, data: playbookSync });
403
+ controls.emit({
404
+ type: "foundry.definition.playbooks.composed",
405
+ data: { count: desiredPlaybooks.length, names: desiredPlaybooks.map((item) => item.playbookName) }
406
+ });
407
+ }
408
+ const scheduleNames = /* @__PURE__ */ new Set();
409
+ const desiredSchedules = schedules.map((schedule) => {
410
+ if (!isFoundrySchedule(schedule)) {
411
+ throw new Error("Agent schedules must be created with defineSchedule(...).");
412
+ }
413
+ if (scheduleNames.has(schedule.name)) {
414
+ throw new Error(`Duplicate agent schedule name "${schedule.name}".`);
415
+ }
416
+ scheduleNames.add(schedule.name);
417
+ return {
418
+ id: agentScheduleActivationId(id, request.agentId, schedule.name),
419
+ name: schedule.name,
420
+ revision: agentScheduleRevision(schedule),
421
+ message: schedule.message,
422
+ ...schedule.payload !== void 0 ? { payload: schedule.payload } : {},
423
+ timing: normalizeScheduleTiming(schedule.timing),
424
+ enabled: schedule.enabled !== false
425
+ };
426
+ });
427
+ const scheduleSync = {
428
+ id: `schedule_sync_${runId}`,
429
+ type: "schedule.sync",
430
+ definitionId: id,
431
+ agentId: request.agentId,
432
+ conversationId: request.conversationId,
433
+ workspaceId: request.workspaceId,
434
+ schedules: desiredSchedules
435
+ };
436
+ controls.commands.push(scheduleSync);
437
+ controls.emit({ type: FOUNDRY_CORE_COMMAND_EVENT, data: scheduleSync });
438
+ controls.emit({
439
+ type: "foundry.definition.schedules.loaded",
440
+ data: { count: desiredSchedules.length, names: desiredSchedules.map((item) => item.name) }
441
+ });
442
+ const effectiveInstallations = [...installations];
443
+ for (const tool of createFoundryCoreTools(assemblyContext, desiredSchedules)) base.fold(tool);
444
+ const applicationTransmissionTools = createInstalledApplicationTransmissionTools(
445
+ assemblyContext,
446
+ registry.capabilities.applications,
447
+ effectiveInstallations,
448
+ desiredPlaybooks
449
+ );
450
+ for (const tool of applicationTransmissionTools) base.fold(tool);
451
+ if (applicationTransmissionTools.length > 0) {
452
+ controls.emit({
453
+ type: "foundry.application.transmission-tools.mounted",
454
+ data: {
455
+ tools: applicationTransmissionTools.map((tool) => tool.name)
456
+ }
457
+ });
458
+ }
459
+ for (const tool of tools) base.fold(tool);
460
+ for (const hook of hooks) base.defineHook(hook.name, hook.handler);
461
+ for (const skill of skills) base.defineSkill(skill);
462
+ for (const subagent of subagents) base.defineSubAgent(subagent);
463
+ const mailboxDirectory = process.env[FOUNDRY_MAILBOX_DIRECTORY_ENV];
464
+ const emitDelegationCommand = (command) => {
465
+ controls.commands.push(command);
466
+ controls.emit({ type: FOUNDRY_CORE_COMMAND_EVENT, data: command });
467
+ };
468
+ const forwarded = /* @__PURE__ */ new Map();
469
+ const initialDeliveries = envelope.eventTurn ? envelope.events ?? [] : [];
470
+ const consumedEventIds = new Set(expiredIds);
471
+ const consumed = (deliveries) => {
472
+ for (const delivery of deliveries) if (delivery.durable) consumedEventIds.add(delivery.durable.id);
473
+ };
474
+ let eventRecipient;
475
+ const bufferedDeliveries = initialDeliveries.length ? [] : [...envelope.events ?? []];
476
+ const forwardDeliveries = async (deliveries) => {
477
+ if (!eventRecipient) {
478
+ bufferedDeliveries.push(...deliveries);
479
+ return;
480
+ }
481
+ for (const delivery of deliveries) {
482
+ const event = { ...deliveryEvent(delivery), whenIdle: "defer" };
483
+ forwarded.set(event.id, delivery);
484
+ await eventRecipient.emitEvent(event);
485
+ }
486
+ };
487
+ const heard = /* @__PURE__ */ new Map();
488
+ const pendingQuestion = {};
489
+ const ownDelegation = assemblyContext.delegation?.workerAgentId === request.agentId ? assemblyContext.delegation : void 0;
490
+ let runMailbox;
491
+ const mailbox = () => {
492
+ if (!mailboxDirectory) {
493
+ throw new Error("Foundry cannot deliver to this run without its parent runtime.");
494
+ }
495
+ if (!runMailbox) {
496
+ runMailbox = openRunMailbox({
497
+ directory: mailboxDirectory,
498
+ conversationId: request.conversationId,
499
+ report: (state) => writeAgentEvent(FOUNDRY_CONVERSATION_LISTEN_EVENT, { state }).catch(() => void 0),
500
+ consumed,
501
+ sink: {
502
+ async forward(deliveries) {
503
+ await forwardDeliveries(deliveries);
504
+ },
505
+ async reclaim(match) {
506
+ const buffered = bufferedDeliveries.filter(match);
507
+ for (let i = bufferedDeliveries.length - 1; i >= 0; i--) if (match(bufferedDeliveries[i])) bufferedDeliveries.splice(i, 1);
508
+ const taken = await eventQueue.reclaim(match);
509
+ for (const { id: id2 } of taken) forwarded.delete(id2);
510
+ return [...buffered, ...taken.map(({ delivery }) => delivery)];
511
+ }
512
+ }
513
+ });
514
+ const opened = runMailbox;
515
+ cleanups.push(() => opened.close());
516
+ }
517
+ return runMailbox;
518
+ };
519
+ const deliverySubscriber = {
520
+ async record(type, data2) {
521
+ if (type === "event_dropped") {
522
+ const id2 = data2.id;
523
+ const delivery = forwarded.get(id2);
524
+ if (delivery) {
525
+ consumed([delivery]);
526
+ forwarded.delete(id2);
527
+ }
528
+ return;
529
+ }
530
+ if (type !== "event_injected") return;
531
+ for (const id2 of data2.ids) {
532
+ const delivery = forwarded.get(id2);
533
+ if (!delivery) continue;
534
+ forwarded.delete(id2);
535
+ consumed([delivery]);
536
+ if (isDelegationUpdate(delivery)) heard.set(delivery.delegationId, delivery);
537
+ else if (delivery.kind === "reply" && pendingQuestion.current?.delegationId === delivery.delegationId) {
538
+ pendingQuestion.current = void 0;
539
+ }
540
+ }
541
+ }
542
+ };
543
+ base.addSubscriber(deliverySubscriber);
544
+ const delegationTarget = {
545
+ definitionId: id,
546
+ agentId: request.agentId,
547
+ conversationId: request.conversationId,
548
+ workspaceId: request.workspaceId,
549
+ emit: emitDelegationCommand
550
+ };
551
+ const startedHere = [];
552
+ const durableNames = Object.keys(definition.durableSubagents ?? {});
553
+ const normalizedDelegates = normalizeDelegates([
554
+ ...delegates,
555
+ ...durableNames.filter((name) => !delegates.some((item) => (typeof item === "string" ? item : item.agent) === name)).map((name) => ({ agent: name, description: definition.durableSubagents[name].description ?? `Persistent ${name} worker.` }))
556
+ ]);
557
+ if (durableNames.length || envelope.agent.durableSubagent) base.fold(createAgentMessagingTool(assemblyContext, durableNames, Boolean(envelope.agent.durableSubagent)));
558
+ const onReplied = (delegationId) => {
559
+ heard.set(delegationId, "replied");
560
+ };
561
+ for (const tool of createDelegatorTools(delegationTarget, normalizedDelegates, (started) => {
562
+ const now = (/* @__PURE__ */ new Date()).toISOString();
563
+ startedHere.push({
564
+ id: started.id,
565
+ to: started.to,
566
+ workerAgentId: "",
567
+ workspaceId: request.workspaceId,
568
+ from: { definitionId: id, agentId: request.agentId, conversationId: request.conversationId, runId },
569
+ task: started.task,
570
+ status: "working",
571
+ createdAt: now,
572
+ updatedAt: now
573
+ });
574
+ }, onReplied)) base.fold(tool);
575
+ if (normalizedDelegates.length > 0 || assemblyContext.delegations.length > 0) {
576
+ base.addContextProvider(
577
+ () => renderOpenDelegations(
578
+ [...assemblyContext.delegations.filter(isOpenDelegation), ...startedHere].flatMap((item) => {
579
+ const update = heard.get(item.id);
580
+ if (!update) return [item];
581
+ if (update === "replied") return [{ ...item, status: "working" }];
582
+ if (update.kind === "question") return [{ ...item, status: "waiting", question: update.question }];
583
+ return [];
584
+ })
585
+ )
586
+ );
587
+ controls.emit({
588
+ type: "foundry.definition.delegates.loaded",
589
+ data: { delegates: normalizedDelegates.map((delegate) => delegate.agent), open: assemblyContext.delegations.length }
590
+ });
591
+ }
592
+ if (ownDelegation) {
593
+ const answerWaitMs = definition.answerWaitMs ?? DEFAULT_ANSWER_WAIT_MS;
594
+ const waitForReply = async (timeoutMs) => mailboxDirectory ? mailbox().waitForReply(ownDelegation.id, timeoutMs, abortController.signal) : null;
595
+ for (const tool of createWorkerTools(delegationTarget, ownDelegation, {
596
+ answerWaitMs,
597
+ pending: pendingQuestion,
598
+ waitForReply
599
+ })) base.fold(tool);
600
+ }
601
+ if (mailboxDirectory) mailbox();
602
+ const workbench = await mountFoundryWorkbench({
603
+ glove: base,
604
+ context: assemblyContext,
605
+ ...workingEnvironment ? { workingEnvironment } : {},
606
+ ...repl ? { repl } : {},
607
+ deferRepl: Boolean(repl?.programmaticTools)
608
+ });
609
+ cleanups.push(workbench.dispose);
610
+ const callByName = /* @__PURE__ */ new Map();
611
+ const invoke = async (name, callInput) => {
612
+ const call = callByName.get(name);
613
+ if (!call) throw new Error(`Foundry call "${name}" is not available.`);
614
+ const parsed = call.input.parse(callInput);
615
+ const value = await resolveResolvable(call.handler(parsed, callContext));
616
+ return call.output.parse(value);
617
+ };
618
+ const surfaceContext = {
619
+ definitionId: id,
620
+ agentId: request.agentId,
621
+ conversationId: request.conversationId,
622
+ workspaceId: request.workspaceId,
623
+ runId,
624
+ input,
625
+ request,
626
+ message,
627
+ messageInput: request.message,
628
+ messageText: message.text,
629
+ history,
630
+ messages,
631
+ glove: base,
632
+ ...workbench.workingEnvironment ? { workingEnvironment: workbench.workingEnvironment, vfs: workbench.vfs } : {},
633
+ ...workbench.repl ? { repl: workbench.repl } : {},
634
+ signal: abortController.signal,
635
+ emit: controls.emit
636
+ };
637
+ const guidance = await mountFoundryGuidance(base, assemblyContext, {
638
+ facts: await resolveOptional("facts", definition.facts, void 0),
639
+ goals: await resolveOptional("goals", definition.goals, void 0),
640
+ forms: await resolveOptional("forms", definition.forms, void 0),
641
+ contextProviders: await resolveOptional("contextProviders", definition.contextProviders, [])
642
+ });
643
+ cleanups.push(async () => {
644
+ try {
645
+ await guidance.snapshot();
646
+ } finally {
647
+ guidance.dispose();
648
+ }
649
+ });
650
+ const callContext = {
651
+ ...surfaceContext,
652
+ ...guidance.handles,
653
+ events: assemblyContext.events,
654
+ delegations: assemblyContext.delegations,
655
+ installations: effectiveInstallations,
656
+ onCleanup: (cleanup) => {
657
+ cleanups.push(cleanup);
658
+ },
659
+ invoke,
660
+ onDelegationUpdate: (handler) => {
661
+ const stop = mailbox().onUpdates(handler);
662
+ cleanups.push(stop);
663
+ return stop;
664
+ }
665
+ };
666
+ for (const call of calls) {
667
+ if (callByName.has(call.name)) throw new Error(`Duplicate Foundry call "${call.name}".`);
668
+ callByName.set(call.name, call);
669
+ if (call.exposeToAgent ?? true) {
670
+ base.fold({
671
+ name: call.name,
672
+ description: call.description,
673
+ inputSchema: call.input,
674
+ async do(callInput) {
675
+ try {
676
+ return { status: "success", data: await invoke(call.name, callInput) };
677
+ } catch (cause) {
678
+ return {
679
+ status: "error",
680
+ data: null,
681
+ message: cause instanceof Error ? cause.message : String(cause)
682
+ };
683
+ }
684
+ }
685
+ });
686
+ }
687
+ }
688
+ disposeSurfaces = await mountFoundrySurfaces({
689
+ registry: registry.native,
690
+ layers,
691
+ subscribers,
692
+ context: surfaceContext
693
+ });
694
+ await Effect.runPromise(
695
+ installRegistry({
696
+ registry: registry.capabilities,
697
+ installations: effectiveInstallations,
698
+ ...envelope.agent.durableSubagent && application.data ? {
699
+ authorizeInstallation: (installation) => Effect.tryPromise({
700
+ try: async () => {
701
+ const refreshed = await refreshDurableAuthority(definition, envelope.agent, application.data);
702
+ const current = refreshed.agent.installations.find((item) => item.kind === installation.kind && item.id === installation.id);
703
+ if (!current || current.accountId !== installation.accountId || JSON.stringify(current.config) !== JSON.stringify(installation.config)) throw new Error(`Installation "${installation.id}" changed or was revoked; start a new run.`);
704
+ },
705
+ catch: (cause) => cause
706
+ })
707
+ } : {},
708
+ context: {
709
+ definitionId: id,
710
+ agentId: request.agentId,
711
+ conversationId: request.conversationId,
712
+ workspaceId: request.workspaceId,
713
+ runId,
714
+ input,
715
+ request,
716
+ message,
717
+ messageInput: request.message,
718
+ messageText: message.text,
719
+ history,
720
+ messages,
721
+ glove: base,
722
+ store: base.store,
723
+ emit: controls.emit
724
+ },
725
+ ...definition.mcpAdapter ? { mcpAdapter: definition.mcpAdapter } : {},
726
+ ...definition.accountSessions ? { accountSessions: definition.accountSessions } : {}
727
+ })
728
+ );
729
+ await Effect.runPromise(
730
+ mountAgentDefinitionMemory({
731
+ registry: registry.capabilities,
732
+ memory,
733
+ context: {
734
+ definitionId: id,
735
+ agentId: request.agentId,
736
+ conversationId: request.conversationId,
737
+ workspaceId: request.workspaceId,
738
+ runId,
739
+ input,
740
+ request,
741
+ message,
742
+ messageInput: request.message,
743
+ messageText: message.text,
744
+ history,
745
+ messages,
746
+ glove: base,
747
+ store: base.store,
748
+ emit: controls.emit
749
+ }
750
+ })
751
+ );
752
+ if (definition.inboxes) {
753
+ await hydrateInbox(base.store, inboxItems, controls.emit);
754
+ }
755
+ if (mesh) {
756
+ await mountMesh(base, {
757
+ // Optional live mesh transport. Durable addressed delivery belongs to the controller journal.
758
+ delivery: mesh.delivery ?? "inbox",
759
+ ...mesh.whenIdle ? { whenIdle: mesh.whenIdle } : {},
760
+ adapter: mesh.adapter,
761
+ identity: {
762
+ id: mesh.identity?.id ?? request.agentId,
763
+ name: mesh.identity?.name ?? request.agentId,
764
+ description: mesh.identity?.description ?? definition.description,
765
+ ...mesh.identity?.capabilities ? { capabilities: mesh.identity.capabilities } : {},
766
+ metadata: {
767
+ definitionId: id,
768
+ conversationId: request.conversationId,
769
+ workspaceId: request.workspaceId,
770
+ ...mesh.identity?.metadata ?? {}
771
+ }
772
+ }
773
+ });
774
+ cleanups.push(() => mesh.adapter.unregister());
775
+ }
776
+ if (definition.configure) {
777
+ await resolveResolvable(definition.configure(base, callContext));
778
+ }
779
+ await workbench.mountRepl();
780
+ const glove = definition.build ? await resolveResolvable(definition.build(base, assemblyContext)) ?? base : base;
781
+ if (glove !== base) {
782
+ base.removeSubscriber(subscriber);
783
+ base.removeSubscriber(deliverySubscriber);
784
+ glove.addSubscriber(subscriber);
785
+ glove.addSubscriber(deliverySubscriber);
786
+ }
787
+ cleanups.push(() => {
788
+ glove.removeSubscriber(subscriber);
789
+ glove.removeSubscriber(deliverySubscriber);
790
+ });
791
+ eventRecipient = glove;
792
+ await forwardDeliveries(bufferedDeliveries.splice(0));
793
+ const runtimeContext = { ...callContext, glove };
794
+ let initialEventsPending = initialDeliveries.length > 0;
795
+ const defaultRun = async (messageInput = assemblyContext.messageInput) => {
796
+ if (initialEventsPending && messageInput === assemblyContext.messageInput) {
797
+ initialEventsPending = false;
798
+ await forwardDeliveries(initialDeliveries);
799
+ return extractOutput(await glove.processEvents(abortController.signal));
800
+ }
801
+ return extractOutput(await glove.processRequest(toGloveRequestInput(messageInput), abortController.signal));
802
+ };
803
+ const spawn = async (messageInput = assemblyContext.messageInput) => definition.spawn ? executeSpawned(
804
+ await resolveResolvable(definition.spawn(glove, runtimeContext, messageInput)),
805
+ messageInput,
806
+ abortController.signal
807
+ ) : defaultRun(messageInput);
808
+ const handlerContext = {
809
+ ...runtimeContext,
810
+ defaultRun,
811
+ defaultHandler: defaultRun,
812
+ spawn
813
+ };
814
+ const result = definition.run ? await resolveResolvable(definition.run(glove, handlerContext)) : definition.handler ? await resolveResolvable(definition.handler(handlerContext)) : definition.spawn ? await spawn() : await defaultRun();
815
+ if (initialEventsPending) consumed(initialDeliveries);
816
+ await guidance.snapshot();
817
+ const sleep = [...controls.commands].reverse().find(
818
+ (command) => command.type === "sleep"
819
+ );
820
+ const question = pendingQuestion.current;
821
+ return {
822
+ status: sleep || question ? "suspended" : "completed",
823
+ value: serializable(result),
824
+ ...consumedEventIds.size ? { consumedEventIds: [...consumedEventIds] } : {},
825
+ agentId: request.agentId,
826
+ conversationId: request.conversationId,
827
+ workspaceId: request.workspaceId,
828
+ ...question ? { suspension: { kind: "question", ...question } } : sleep && sleep.type === "sleep" ? { suspension: { commandId: sleep.id, wakeAt: sleep.wakeAt } } : {}
829
+ };
830
+ } finally {
831
+ const failures = [];
832
+ for (const cleanup of cleanups.reverse()) {
833
+ try {
834
+ await cleanup();
835
+ } catch (cause) {
836
+ failures.push(cause);
837
+ }
838
+ }
839
+ try {
840
+ if (disposeSurfaces) await disposeSurfaces();
841
+ } catch (cause) {
842
+ failures.push(cause);
843
+ }
844
+ process.removeListener("SIGTERM", onTerminate);
845
+ if (failures.length > 0) throw new AggregateError(failures, "Foundry agent cleanup failed.");
846
+ }
847
+ }
848
+ function compileAgentDefinition(definition, route) {
849
+ const contentPartSchema = z.object({
850
+ type: z.enum(["text", "image", "video", "document"]),
851
+ text: z.string().optional(),
852
+ name: z.string().optional(),
853
+ source: z.object({
854
+ type: z.enum(["base64", "url"]),
855
+ media_type: z.string(),
856
+ data: z.string().optional(),
857
+ url: z.string().optional()
858
+ }).optional()
859
+ });
860
+ const requestSchema = z.object({
861
+ agentId: z.string().min(1),
862
+ conversationId: z.string().min(1),
863
+ workspaceId: z.string().min(1),
864
+ message: z.union([z.string(), z.array(contentPartSchema)]),
865
+ payload: z.unknown().optional(),
866
+ context: z.record(z.string(), z.unknown()).optional(),
867
+ source: z.object({
868
+ kind: z.enum(["direct", "transmission", "activation", "spawn", "background", "delegation", "agent-message"]),
869
+ id: z.string().optional(),
870
+ provider: z.string().optional(),
871
+ eventId: z.string().optional(),
872
+ threadKey: z.string().optional()
873
+ }).optional()
874
+ });
875
+ const executionEnvelope = z.object({
876
+ [FOUNDRY_EXECUTION_MARKER]: z.literal(true),
877
+ request: requestSchema,
878
+ events: z.array(z.custom()).optional(),
879
+ eventTurn: z.boolean().optional(),
880
+ agent: z.object({
881
+ id: z.string(),
882
+ definitionId: z.string(),
883
+ workspaceId: z.string(),
884
+ durableSubagent: z.object({ parentAgentId: z.string(), name: z.string(), status: z.enum(["active", "archived", "purged"]) }).optional(),
885
+ context: z.record(z.string(), z.unknown()),
886
+ installations: z.array(z.object({
887
+ kind: z.enum(["tool", "application", "mcp"]),
888
+ id: z.string(),
889
+ accountId: z.string().optional(),
890
+ config: z.unknown().optional()
891
+ })),
892
+ playbooks: z.array(z.object({
893
+ id: z.string(),
894
+ transmissionId: z.string(),
895
+ enabled: z.boolean().optional(),
896
+ match: z.object({
897
+ event: z.string().optional(),
898
+ routeIds: z.array(z.string()).optional(),
899
+ predicate: z.object({
900
+ name: z.string(),
901
+ parameters: z.record(z.string(), z.unknown()).optional()
902
+ }).optional()
903
+ }).optional(),
904
+ directives: z.array(z.object({
905
+ action: z.string(),
906
+ instruction: z.string(),
907
+ parameters: z.record(z.string(), z.unknown()).optional()
908
+ })),
909
+ applications: z.array(z.string()).optional(),
910
+ outbound: z.array(z.object({
911
+ routeId: z.string(),
912
+ applicationId: z.string().optional(),
913
+ event: z.string().optional(),
914
+ accountId: z.string().optional(),
915
+ applicationAccountId: z.string().optional(),
916
+ instruction: z.string().optional()
917
+ })).optional(),
918
+ serialization: z.record(z.string(), z.unknown()).optional(),
919
+ origin: z.enum(["agent-definition", "instance"]).optional(),
920
+ playbookName: z.string().optional(),
921
+ definitionRevision: z.string().optional()
922
+ })),
923
+ createdAt: z.string(),
924
+ updatedAt: z.string()
925
+ }),
926
+ conversation: z.object({
927
+ id: z.string(),
928
+ agentId: z.string(),
929
+ workspaceId: z.string(),
930
+ title: z.string().optional(),
931
+ context: z.record(z.string(), z.unknown()),
932
+ createdAt: z.string(),
933
+ updatedAt: z.string()
934
+ }),
935
+ activations: z.array(z.object({
936
+ id: z.string(),
937
+ kind: z.enum(["scheduled", "sleep"]),
938
+ definitionId: z.string(),
939
+ agentId: z.string(),
940
+ conversationId: z.string(),
941
+ workspaceId: z.string(),
942
+ message: z.string(),
943
+ payload: z.unknown().optional(),
944
+ timing: z.union([
945
+ z.object({ kind: z.literal("at"), at: z.string() }),
946
+ z.object({ kind: z.literal("every"), intervalMs: z.number() }),
947
+ z.object({ kind: z.literal("cron"), expression: z.string(), timezone: z.string() })
948
+ ]),
949
+ origin: z.enum(["agent-definition", "agent-tool"]),
950
+ scheduleName: z.string().optional(),
951
+ definitionRevision: z.string().optional(),
952
+ status: z.enum(["pending", "active", "paused", "completed", "cancelled"]),
953
+ createdByRunId: z.string(),
954
+ lastRunId: z.string().optional(),
955
+ createdAt: z.string(),
956
+ updatedAt: z.string()
957
+ })).default([]),
958
+ delegations: z.array(z.object({
959
+ id: z.string(),
960
+ to: z.string(),
961
+ workerAgentId: z.string(),
962
+ workspaceId: z.string(),
963
+ from: z.object({
964
+ definitionId: z.string(),
965
+ agentId: z.string(),
966
+ conversationId: z.string(),
967
+ runId: z.string()
968
+ }),
969
+ task: z.string(),
970
+ status: z.enum(["working", "waiting", "completed", "failed", "cancelled"]),
971
+ question: z.string().optional(),
972
+ result: z.string().optional(),
973
+ error: z.string().optional(),
974
+ createdAt: z.string(),
975
+ updatedAt: z.string()
976
+ })).default([]),
977
+ conversationLease: z.literal(true).optional()
978
+ });
979
+ let builder = signal(internalAgentName(route)).input(executionEnvelope).output(z.object({
980
+ consumedEventIds: z.array(z.string()).readonly().optional(),
981
+ status: z.enum(["completed", "suspended"]),
982
+ value: z.unknown(),
983
+ agentId: z.string(),
984
+ conversationId: z.string(),
985
+ workspaceId: z.string(),
986
+ suspension: z.union([
987
+ z.object({ kind: z.literal("sleep").optional(), commandId: z.string(), wakeAt: z.string() }),
988
+ z.object({
989
+ kind: z.literal("question"),
990
+ commandId: z.string(),
991
+ delegationId: z.string(),
992
+ question: z.string()
993
+ })
994
+ ]).optional()
995
+ }));
996
+ if (definition.runTimeoutMs !== void 0) builder = builder.timeout(definition.runTimeoutMs);
997
+ if (definition.maxConcurrentRuns !== void 0) builder = builder.concurrency(definition.maxConcurrentRuns);
998
+ const built = builder.run(
999
+ (value) => runDefinition(definition, route, value)
1000
+ );
1001
+ return built;
1002
+ }
1003
+ function compileAgentModule(route, module) {
1004
+ return compileAgentDefinition(defineAgentFromModule(route, module), route);
1005
+ }
1006
+
1007
+ // src/execution-loader.ts
14
1008
  async function loadExecutionAgent(route, file) {
15
- const module = await import(pathToFileURL(file).href);
1009
+ if (route.includes("/workers/")) {
1010
+ const root = route.split("/workers/")[0];
1011
+ let agentsDir = dirname(file);
1012
+ while (routeFromAgentFile(agentsDir, file) !== root) {
1013
+ const next = dirname(agentsDir);
1014
+ if (next === agentsDir) throw new Error(`Cannot locate agent root for "${route}".`);
1015
+ agentsDir = next;
1016
+ }
1017
+ const found = (await discoverAgents({ agentsDir })).find((agent) => agent.route === route);
1018
+ if (!found) throw new Error(`Durable subagent definition "${route}" was not found.`);
1019
+ return compileAgentModule(route, { default: found.definition });
1020
+ }
1021
+ const module = await import(pathToFileURL2(file).href);
16
1022
  await bindAgentLocalDefinitions(dirname(file));
17
1023
  return compileAgentModule(route, module);
18
1024
  }