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