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.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  resolveResolvable
3
- } from "./chunk-PVOKR4CN.js";
3
+ } from "./chunk-K2EU63MB.js";
4
4
 
5
5
  // src/guidance.ts
6
6
  import { createHash } from "node:crypto";
@@ -104,7 +104,13 @@ async function mountFoundryGuidance(glove, context, options) {
104
104
  };
105
105
  const cleanups = [];
106
106
  try {
107
- for (const provider of options.contextProviders) cleanups.push(glove.addContextProvider(provider));
107
+ for (const entry of options.contextProviders) {
108
+ if (typeof entry === "function") cleanups.push(glove.addContextProvider(entry));
109
+ else {
110
+ const { provider, ...delivery } = entry;
111
+ cleanups.push(glove.addContextProvider(provider, delivery));
112
+ }
113
+ }
108
114
  if (facts || goals || forms) {
109
115
  await snapshot();
110
116
  cleanups.push(glove.addContextProvider(async () => {
@@ -285,7 +291,7 @@ function programmaticToolFunction(selection, options) {
285
291
  );
286
292
  }
287
293
  const validated = parsed?.success ? parsed.data : input;
288
- const permission = typeof tool.requiresPermission === "function" ? tool.requiresPermission(validated) : Boolean(tool.requiresPermission);
294
+ const permission = typeof tool.requiresPermission === "function" ? Boolean(await tool.requiresPermission(validated)) : Boolean(tool.requiresPermission);
289
295
  if (permission) {
290
296
  options.context.controls.emit({
291
297
  type: "foundry.repl.programmatic-tool.denied",
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  mountFoundryGuidance,
3
3
  mountFoundryWorkbench
4
- } from "./chunk-NHV64WNO.js";
4
+ } from "./chunk-RSU7NEDK.js";
5
5
  import {
6
6
  EMPTY_CAPABILITY_REGISTRY,
7
7
  EMPTY_FOUNDRY_APPLICATION,
@@ -27,7 +27,24 @@ import {
27
27
  toGloveMessage,
28
28
  toGloveRequestInput,
29
29
  withFoundryPermissions
30
- } from "./chunk-6Q2LGPSC.js";
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";
31
48
  import {
32
49
  FOUNDRY_APPLICATION_ENV,
33
50
  FOUNDRY_EVENT_PREFIX,
@@ -37,7 +54,7 @@ import {
37
54
  internalAgentName,
38
55
  mountFoundrySurfaces,
39
56
  resolveResolvable
40
- } from "./chunk-PVOKR4CN.js";
57
+ } from "./chunk-K2EU63MB.js";
41
58
 
42
59
  // src/agent-runtime.ts
43
60
  import { pathToFileURL } from "node:url";
@@ -46,6 +63,7 @@ import { mountMesh } from "glove-mesh";
46
63
  import { Effect } from "effect";
47
64
  import { signal } from "station-signal";
48
65
  import { z } from "zod";
66
+ var DEFAULT_ANSWER_WAIT_MS = 9e4;
49
67
  var INBOX_ITEMS_SCHEMA = z.array(z.object({
50
68
  id: z.string().min(1),
51
69
  tag: z.string(),
@@ -190,6 +208,16 @@ async function executeDefinition(definition, id, runtimeValue) {
190
208
  const abortController = new AbortController();
191
209
  const onTerminate = () => abortController.abort();
192
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
+ }
193
221
  let disposeSurfaces;
194
222
  const cleanups = [];
195
223
  const application = await loadRuntimeApplication();
@@ -237,6 +265,8 @@ async function executeDefinition(definition, id, runtimeValue) {
237
265
  agentInstance: envelope.agent,
238
266
  conversation: envelope.conversation,
239
267
  activations: Object.freeze([...envelope.activations ?? []]),
268
+ delegations: Object.freeze([...envelope.delegations ?? []]),
269
+ ...delegationFromContext(envelope.conversation.context) ? { delegation: delegationFromContext(envelope.conversation.context) } : {},
240
270
  data,
241
271
  input,
242
272
  message,
@@ -277,8 +307,10 @@ async function executeDefinition(definition, id, runtimeValue) {
277
307
  resolveOptional("compactionInstructions", definition.compactionInstructions, "Preserve goals, decisions, unresolved work, tool results, and pending inbox items."),
278
308
  resolveOptional("maxTurns", definition.maxTurns, void 0)
279
309
  ]);
310
+ const eventQueue = new RunEventQueue();
280
311
  const base = new Glove({
281
312
  ...runtimeStore ? { store: runtimeStore } : {},
313
+ events: { queue: eventQueue, policy: () => "defer", deferTimeoutMs: Infinity, formatter: formatRunEvents },
282
314
  model,
283
315
  displayManager,
284
316
  systemPrompt,
@@ -293,11 +325,12 @@ async function executeDefinition(definition, id, runtimeValue) {
293
325
  ...definition.enableToolResultSummary !== void 0 ? { enableToolResultSummary: definition.enableToolResultSummary } : {}
294
326
  }).build();
295
327
  base.addSubscriber(subscriber);
296
- const [tools, hooks, skills, subagents, memory, inboxItems, layers, subscribers, calls, playbooks, schedules, mesh, workingEnvironment, repl] = await Promise.all([
328
+ const [tools, hooks, skills, subagents, delegates, memory, inboxItems, layers, subscribers, calls, playbooks, schedules, mesh, workingEnvironment, repl] = await Promise.all([
297
329
  resolveOptional("tools", definition.tools, []),
298
330
  resolveOptional("hooks", definition.hooks, []),
299
331
  resolveOptional("skills", definition.skills, []),
300
332
  resolveOptional("subagents", definition.subagents, []),
333
+ resolveOptional("delegates", definition.delegates, []),
301
334
  resolveOptional("memory", definition.memory, []),
302
335
  definition.inboxes ? resolveAgentValue(
303
336
  definition,
@@ -402,6 +435,112 @@ async function executeDefinition(definition, id, runtimeValue) {
402
435
  for (const hook of hooks) base.defineHook(hook.name, hook.handler);
403
436
  for (const skill of skills) base.defineSkill(skill);
404
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();
405
544
  const workbench = await mountFoundryWorkbench({
406
545
  glove: base,
407
546
  context: assemblyContext,
@@ -457,7 +596,12 @@ async function executeDefinition(definition, id, runtimeValue) {
457
596
  onCleanup: (cleanup) => {
458
597
  cleanups.push(cleanup);
459
598
  },
460
- invoke
599
+ invoke,
600
+ onDelegationUpdate: (handler) => {
601
+ const stop = mailbox().onUpdates(handler);
602
+ cleanups.push(stop);
603
+ return stop;
604
+ }
461
605
  };
462
606
  for (const call of calls) {
463
607
  if (callByName.has(call.name)) throw new Error(`Duplicate Foundry call "${call.name}".`);
@@ -540,6 +684,11 @@ async function executeDefinition(definition, id, runtimeValue) {
540
684
  }
541
685
  if (mesh) {
542
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",
543
692
  adapter: mesh.adapter,
544
693
  identity: {
545
694
  id: mesh.identity?.id ?? request.agentId,
@@ -584,13 +733,14 @@ async function executeDefinition(definition, id, runtimeValue) {
584
733
  const sleep = [...controls.commands].reverse().find(
585
734
  (command) => command.type === "sleep"
586
735
  );
736
+ const question = pendingQuestion.current;
587
737
  return {
588
- status: sleep ? "suspended" : "completed",
738
+ status: sleep || question ? "suspended" : "completed",
589
739
  value: serializable(result),
590
740
  agentId: request.agentId,
591
741
  conversationId: request.conversationId,
592
742
  workspaceId: request.workspaceId,
593
- ...sleep && sleep.type === "sleep" ? { suspension: { commandId: sleep.id, wakeAt: sleep.wakeAt } } : {}
743
+ ...question ? { suspension: { kind: "question", ...question } } : sleep && sleep.type === "sleep" ? { suspension: { commandId: sleep.id, wakeAt: sleep.wakeAt } } : {}
594
744
  };
595
745
  } finally {
596
746
  const failures = [];
@@ -630,7 +780,7 @@ function compileAgentDefinition(definition, route) {
630
780
  payload: z.unknown().optional(),
631
781
  context: z.record(z.string(), z.unknown()).optional(),
632
782
  source: z.object({
633
- kind: z.enum(["direct", "transmission", "activation", "spawn", "background"]),
783
+ kind: z.enum(["direct", "transmission", "activation", "spawn", "background", "delegation"]),
634
784
  id: z.string().optional(),
635
785
  provider: z.string().optional(),
636
786
  eventId: z.string().optional(),
@@ -715,7 +865,27 @@ function compileAgentDefinition(definition, route) {
715
865
  lastRunId: z.string().optional(),
716
866
  createdAt: z.string(),
717
867
  updatedAt: z.string()
718
- })).default([])
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()
719
889
  });
720
890
  let builder = signal(internalAgentName(route)).input(executionEnvelope).output(z.object({
721
891
  status: z.enum(["completed", "suspended"]),
@@ -723,7 +893,15 @@ function compileAgentDefinition(definition, route) {
723
893
  agentId: z.string(),
724
894
  conversationId: z.string(),
725
895
  workspaceId: z.string(),
726
- suspension: z.object({ commandId: z.string(), wakeAt: z.string() }).optional()
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()
727
905
  }));
728
906
  const built = builder.run(
729
907
  (value) => runDefinition(definition, route, value)