glove-foundry 0.7.0 → 0.9.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.
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  FOUNDRY_APPLICATION_ENV,
6
6
  internalAgentName
7
- } from "./chunk-64UBLGYM.js";
7
+ } from "./chunk-CYOIHSUX.js";
8
8
 
9
9
  // src/execution-daemon.ts
10
10
  import { randomBytes } from "node:crypto";
@@ -26,8 +26,12 @@ var schedules = new ScheduleMemoryAdapter();
26
26
  var definitions = /* @__PURE__ */ new Map();
27
27
  var stopping;
28
28
  var resources;
29
- function send(message) {
30
- if (process.connected) process.send?.(message);
29
+ function send(message, then) {
30
+ if (!process.connected || !process.send) {
31
+ then?.();
32
+ return;
33
+ }
34
+ process.send(message, void 0, {}, () => then?.());
31
35
  }
32
36
  async function stop() {
33
37
  return stopping ??= (async () => {
@@ -178,8 +182,9 @@ export default await loadExecutionAgent(${JSON.stringify(agent.route)}, ${JSON.s
178
182
  value = null;
179
183
  break;
180
184
  }
181
- send({ id: message.id, value });
182
- if (command.method === "stop") process.disconnect?.();
185
+ send({ id: message.id, value }, command.method === "stop" ? () => {
186
+ if (process.connected) process.disconnect?.();
187
+ } : void 0);
183
188
  })().catch(() => {
184
189
  send({ id: message.id, error: `Execution daemon ${message.command.method} failed. Inspect daemon health before repeating mutations.` });
185
190
  });
@@ -1,12 +1,14 @@
1
1
  import {
2
2
  mountFoundryGuidance,
3
3
  mountFoundryWorkbench
4
- } from "./chunk-IPASF7PK.js";
4
+ } from "./chunk-X3HZYVZS.js";
5
5
  import {
6
6
  EMPTY_FOUNDRY_APPLICATION,
7
7
  FOUNDRY_APPROVAL_DIRECTORY_ENV,
8
+ FOUNDRY_APPROVAL_POLICY_ENV,
8
9
  FOUNDRY_COMPOSED_PLAYBOOK_BRAND,
9
10
  FOUNDRY_CORE_COMMAND_EVENT,
11
+ FOUNDRY_MODEL_REQUESTS_ENV,
10
12
  FoundryApprovalDisplayManager,
11
13
  MemoryFoundryDataAdapter,
12
14
  agentPlaybookId,
@@ -22,45 +24,57 @@ import {
22
24
  isFoundrySchedule,
23
25
  materializeComposedPlaybook,
24
26
  normalizeScheduleTiming,
27
+ readApprovalPolicy,
28
+ requestTracer,
25
29
  routeFromAgentFile,
26
30
  toGloveMessage,
27
31
  toGloveRequestInput,
28
32
  withFoundryPermissions
29
- } from "./chunk-EJZJAVNG.js";
33
+ } from "./chunk-EUGKVW3J.js";
30
34
  import {
31
35
  FOUNDRY_CONVERSATION_LEASE_EVENT,
32
36
  FOUNDRY_CONVERSATION_LISTEN_EVENT,
33
37
  FOUNDRY_MAILBOX_DIRECTORY_ENV,
34
38
  RunEventQueue,
35
39
  createDelegatorTools,
40
+ createMeshTools,
36
41
  createWorkerTools,
37
42
  delegationFromContext,
38
43
  deliveryEvent,
39
44
  formatRunEvents,
40
45
  isDelegationUpdate,
41
46
  isOpenDelegation,
47
+ isOpenThread,
42
48
  normalizeDelegates,
43
49
  openRunMailbox,
44
50
  renderDeliveries,
45
51
  renderOpenDelegations,
52
+ renderOpenThreads,
53
+ renderOwnThread,
54
+ threadFromContext,
46
55
  waitForConversationLease
47
- } from "./chunk-AC6SRI5V.js";
56
+ } from "./chunk-J6NHL4SM.js";
48
57
  import {
49
58
  EMPTY_CAPABILITY_REGISTRY,
50
59
  FOUNDRY_APPLICATION_ENV,
60
+ FOUNDRY_CORE_COMMAND_DIRECTORY_ENV,
51
61
  FOUNDRY_EVENT_PREFIX,
52
62
  FOUNDRY_EXECUTION_MARKER,
53
63
  FOUNDRY_RUN_PROCESS_EVENT,
54
64
  createAgentMessagingTool,
65
+ createFoundryCoreCommandRequest,
55
66
  defineAgentFromModule,
67
+ hostedMeshOptions,
56
68
  installRegistry,
57
69
  internalAgentName,
58
70
  isInboxCapableStore,
71
+ isMeshTransport,
59
72
  mountAgentDefinitionMemory,
60
73
  mountFoundrySurfaces,
61
74
  refreshDurableAuthority,
62
- resolveResolvable
63
- } from "./chunk-64UBLGYM.js";
75
+ resolveResolvable,
76
+ waitForFoundryCoreCommandResult
77
+ } from "./chunk-CYOIHSUX.js";
64
78
 
65
79
  // src/execution-loader.ts
66
80
  import { dirname } from "node:path";
@@ -68,11 +82,43 @@ import { pathToFileURL as pathToFileURL2 } from "node:url";
68
82
 
69
83
  // src/agent-runtime.ts
70
84
  import { pathToFileURL } from "node:url";
71
- import { Glove } from "glove-core";
85
+ import { Glove, isTurnSuspended } from "glove-core";
72
86
  import { mountMesh } from "glove-mesh";
73
87
  import { Effect } from "effect";
74
88
  import { signal } from "station-signal";
75
89
  import { z } from "zod";
90
+
91
+ // src/assembly-trace.ts
92
+ var FOUNDRY_ASSEMBLY_COMPOSED_EVENT = "foundry.assembly.composed";
93
+ function assemblyRecorder(glove, now = Date.now) {
94
+ const started = now();
95
+ let last = started;
96
+ const known = /* @__PURE__ */ new Set();
97
+ const steps = [];
98
+ return {
99
+ mark(step, label, options = {}) {
100
+ const names = (options.glove ?? glove).tools.map((tool) => tool.name);
101
+ const added = names.filter((name) => !known.has(name));
102
+ for (const name of names) known.add(name);
103
+ const at = now();
104
+ const ms = at - last;
105
+ last = at;
106
+ if (!added.length && ms < 1 && !options.keep) return;
107
+ steps.push({
108
+ step,
109
+ label,
110
+ ...options.kind ? { kind: options.kind } : {},
111
+ ...options.id ? { id: options.id } : {},
112
+ tools: added,
113
+ ms
114
+ });
115
+ },
116
+ steps,
117
+ elapsedMs: () => now() - started
118
+ };
119
+ }
120
+
121
+ // src/agent-runtime.ts
76
122
  var DEFAULT_ANSWER_WAIT_MS = 9e4;
77
123
  var INBOX_ITEMS_SCHEMA = z.array(z.object({
78
124
  id: z.string().min(1),
@@ -113,6 +159,20 @@ async function hydrateInbox(store, items, emit) {
113
159
  data: { count: loaded.length, added, updated }
114
160
  });
115
161
  }
162
+ function approvalDecisionOf(delivery) {
163
+ const event = delivery.durable?.event;
164
+ if (event?.source !== "foundry:approval" || event.kind !== "approval.decided") return void 0;
165
+ const approval = event.metadata?.approval;
166
+ if (typeof approval?.id !== "string" || typeof approval.toolName !== "string") return void 0;
167
+ if (approval.status !== "approved" && approval.status !== "denied") return void 0;
168
+ return {
169
+ id: approval.id,
170
+ toolName: approval.toolName,
171
+ toolInput: approval.toolInput,
172
+ status: approval.status,
173
+ ...typeof approval.toolCallId === "string" ? { toolCallId: approval.toolCallId } : {}
174
+ };
175
+ }
116
176
  function extractOutput(result) {
117
177
  if (result == null || typeof result !== "object") return result;
118
178
  const object = result;
@@ -144,9 +204,24 @@ function writeAgentEvent(type, data) {
144
204
  });
145
205
  }
146
206
  function executionSubscriber() {
207
+ const trace = requestTracer();
147
208
  return {
209
+ modelRequests: process.env[FOUNDRY_MODEL_REQUESTS_ENV] !== "off",
148
210
  async record(eventType, data) {
149
- await writeAgentEvent(eventType, data);
211
+ if (eventType === "model_request" || eventType === "model_request_end") {
212
+ let recorded;
213
+ try {
214
+ recorded = eventType === "model_request" ? trace.request(data) : trace.end(data);
215
+ } catch (cause) {
216
+ recorded = {
217
+ request_id: data.request_id,
218
+ unrecorded: cause instanceof Error ? cause.message : String(cause)
219
+ };
220
+ }
221
+ await writeAgentEvent(eventType, recorded);
222
+ } else {
223
+ await writeAgentEvent(eventType, data);
224
+ }
150
225
  }
151
226
  };
152
227
  }
@@ -291,6 +366,8 @@ async function executeDefinition(definition, id, runtimeValue) {
291
366
  activations: Object.freeze([...envelope.activations ?? []]),
292
367
  delegations: Object.freeze([...envelope.delegations ?? []]),
293
368
  ...delegationFromContext(envelope.conversation.context) ? { delegation: delegationFromContext(envelope.conversation.context) } : {},
369
+ threads: Object.freeze([...envelope.threads ?? []]),
370
+ ...threadFromContext(envelope.conversation.context)?.to.agentId === envelope.agent.id ? { thread: threadFromContext(envelope.conversation.context) } : {},
294
371
  data,
295
372
  input,
296
373
  message,
@@ -325,7 +402,8 @@ async function executeDefinition(definition, id, runtimeValue) {
325
402
  conversationId: request.conversationId,
326
403
  workspaceId: request.workspaceId,
327
404
  signal: abortController.signal,
328
- emit: controls.emit
405
+ emit: controls.emit,
406
+ policy: readApprovalPolicy(process.env[FOUNDRY_APPROVAL_POLICY_ENV])
329
407
  })
330
408
  ),
331
409
  resolveOptional("compactionLimit", definition.compactionLimit, void 0),
@@ -350,6 +428,8 @@ async function executeDefinition(definition, id, runtimeValue) {
350
428
  ...definition.enableToolResultSummary !== void 0 ? { enableToolResultSummary: definition.enableToolResultSummary } : {}
351
429
  }).build();
352
430
  base.addSubscriber(subscriber);
431
+ const assembly = assemblyRecorder(base);
432
+ assembly.mark("glove", "Glove built-ins");
353
433
  const [tools, hooks, skills, subagents, delegates, memory, inboxItems, layers, subscribers, calls, playbooks, schedules, mesh, workingEnvironment, repl] = await Promise.all([
354
434
  resolveOptional("tools", definition.tools, []),
355
435
  resolveOptional("hooks", definition.hooks, []),
@@ -368,7 +448,8 @@ async function executeDefinition(definition, id, runtimeValue) {
368
448
  resolveOptional("calls", definition.calls, []),
369
449
  resolveOptional("playbooks", definition.playbooks, []),
370
450
  resolveOptional("schedules", definition.schedules, []),
371
- resolveOptional("mesh", definition.mesh, void 0),
451
+ // Your own mesh transport; the mesh Foundry hosts is mounted below.
452
+ resolveOptional("mesh", isMeshTransport(definition.mesh) ? definition.mesh : void 0, void 0),
372
453
  resolveOptional("workingEnvironment", definition.workingEnvironment, void 0),
373
454
  resolveOptional("repl", definition.repl, void 0)
374
455
  ]);
@@ -440,7 +521,11 @@ async function executeDefinition(definition, id, runtimeValue) {
440
521
  data: { count: desiredSchedules.length, names: desiredSchedules.map((item) => item.name) }
441
522
  });
442
523
  const effectiveInstallations = [...installations];
443
- for (const tool of createFoundryCoreTools(assemblyContext, desiredSchedules)) base.fold(tool);
524
+ for (const tool of createFoundryCoreTools(assemblyContext, desiredSchedules, {
525
+ playbooks: desiredPlaybooks,
526
+ applications: registry.capabilities.applications
527
+ })) base.fold(tool);
528
+ assembly.mark("foundry-core", "Foundry core tools");
444
529
  const applicationTransmissionTools = createInstalledApplicationTransmissionTools(
445
530
  assemblyContext,
446
531
  registry.capabilities.applications,
@@ -448,6 +533,7 @@ async function executeDefinition(definition, id, runtimeValue) {
448
533
  desiredPlaybooks
449
534
  );
450
535
  for (const tool of applicationTransmissionTools) base.fold(tool);
536
+ assembly.mark("transmissions", "App transmissions");
451
537
  if (applicationTransmissionTools.length > 0) {
452
538
  controls.emit({
453
539
  type: "foundry.application.transmission-tools.mounted",
@@ -460,6 +546,7 @@ async function executeDefinition(definition, id, runtimeValue) {
460
546
  for (const hook of hooks) base.defineHook(hook.name, hook.handler);
461
547
  for (const skill of skills) base.defineSkill(skill);
462
548
  for (const subagent of subagents) base.defineSubAgent(subagent);
549
+ assembly.mark("definition", "Definition tools, skills and subagents");
463
550
  const mailboxDirectory = process.env[FOUNDRY_MAILBOX_DIRECTORY_ENV];
464
551
  const emitDelegationCommand = (command) => {
465
552
  controls.commands.push(command);
@@ -479,6 +566,8 @@ async function executeDefinition(definition, id, runtimeValue) {
479
566
  return;
480
567
  }
481
568
  for (const delivery of deliveries) {
569
+ const decision = approvalDecisionOf(delivery);
570
+ if (decision) await runtimeStore?.setPermission?.(decision.toolName, decision.status === "approved" ? "granted" : "denied", decision.toolInput);
482
571
  const event = { ...deliveryEvent(delivery), whenIdle: "defer" };
483
572
  forwarded.set(event.id, delivery);
484
573
  await eventRecipient.emitEvent(event);
@@ -598,15 +687,69 @@ async function executeDefinition(definition, id, runtimeValue) {
598
687
  waitForReply
599
688
  })) base.fold(tool);
600
689
  }
690
+ const coreCommandDirectory = process.env[FOUNDRY_CORE_COMMAND_DIRECTORY_ENV];
691
+ const emitMeshCommand = (command) => {
692
+ controls.commands.push(command);
693
+ controls.emit({ type: FOUNDRY_CORE_COMMAND_EVENT, data: command });
694
+ };
695
+ const callMesh = async (command) => {
696
+ if (!coreCommandDirectory) throw new Error("Foundry cannot answer mesh calls without its parent runtime.");
697
+ const pending = await createFoundryCoreCommandRequest(coreCommandDirectory, {
698
+ id: command.id,
699
+ runId,
700
+ type: "mesh",
701
+ timeoutMs: 6e4
702
+ });
703
+ emitMeshCommand(command);
704
+ return waitForFoundryCoreCommandResult(coreCommandDirectory, pending, abortController.signal, { cleanup: true });
705
+ };
706
+ const waitFrom = (agentId, timeoutMs) => {
707
+ const stop = new AbortController();
708
+ const onAbort = () => stop.abort();
709
+ abortController.signal.addEventListener("abort", onAbort, { once: true });
710
+ const message2 = (mailboxDirectory ? mailbox().waitForMesh(agentId, timeoutMs, stop.signal) : Promise.resolve(null)).finally(() => abortController.signal.removeEventListener("abort", onAbort));
711
+ return { message: message2, cancel: () => stop.abort() };
712
+ };
713
+ const pendingReply = {};
714
+ const ownThread = assemblyContext.thread;
715
+ const hostedMesh = hostedMeshOptions(definition.mesh);
716
+ if (ownDelegation || normalizedDelegates.length || durableNames.length) assembly.mark("delegation", "Delegation");
717
+ const meshHosted = Boolean(hostedMesh && (hostedMesh.mount?.(assemblyContext) ?? true));
718
+ if (hostedMesh && meshHosted) {
719
+ for (const tool of createMeshTools({
720
+ definitionId: id,
721
+ agentId: request.agentId,
722
+ conversationId: request.conversationId,
723
+ workspaceId: request.workspaceId,
724
+ options: hostedMesh,
725
+ call: callMesh,
726
+ waitFrom,
727
+ pending: pendingReply
728
+ })) base.fold(tool);
729
+ controls.emit({
730
+ type: "foundry.mesh.mounted",
731
+ data: { open: assemblyContext.threads.length, thread: ownThread?.id ?? null }
732
+ });
733
+ assembly.mark("mesh", "Hosted mesh");
734
+ }
735
+ if (hostedMesh || assemblyContext.threads.length > 0 || ownThread) {
736
+ base.addContextProvider(() => [
737
+ ownThread ? renderOwnThread(ownThread) : null,
738
+ renderOpenThreads(assemblyContext.threads.filter(isOpenThread))
739
+ ].filter(Boolean).join("\n\n") || null);
740
+ }
601
741
  if (mailboxDirectory) mailbox();
742
+ const installedApps = [];
602
743
  const workbench = await mountFoundryWorkbench({
603
744
  glove: base,
604
745
  context: assemblyContext,
605
746
  ...workingEnvironment ? { workingEnvironment } : {},
606
747
  ...repl ? { repl } : {},
607
- deferRepl: Boolean(repl?.programmaticTools)
748
+ deferRepl: Boolean(repl?.programmaticTools),
749
+ apps: () => installedApps
608
750
  });
609
751
  cleanups.push(workbench.dispose);
752
+ assembly.mark("workbench", "Working environment");
610
753
  const callByName = /* @__PURE__ */ new Map();
611
754
  const invoke = async (name, callInput) => {
612
755
  const call = callByName.get(name);
@@ -647,11 +790,15 @@ async function executeDefinition(definition, id, runtimeValue) {
647
790
  guidance.dispose();
648
791
  }
649
792
  });
793
+ assembly.mark("guidance", "Goals, facts and forms");
650
794
  const callContext = {
651
795
  ...surfaceContext,
652
796
  ...guidance.handles,
653
797
  events: assemblyContext.events,
654
798
  delegations: assemblyContext.delegations,
799
+ agentInstance: assemblyContext.agentInstance,
800
+ conversation: assemblyContext.conversation,
801
+ data: assemblyContext.data,
655
802
  installations: effectiveInstallations,
656
803
  onCleanup: (cleanup) => {
657
804
  cleanups.push(cleanup);
@@ -661,6 +808,11 @@ async function executeDefinition(definition, id, runtimeValue) {
661
808
  const stop = mailbox().onUpdates(handler);
662
809
  cleanups.push(stop);
663
810
  return stop;
811
+ },
812
+ onMeshMessage: (handler) => {
813
+ const stop = mailbox().onMesh(handler);
814
+ cleanups.push(stop);
815
+ return stop;
664
816
  }
665
817
  };
666
818
  for (const call of calls) {
@@ -685,12 +837,14 @@ async function executeDefinition(definition, id, runtimeValue) {
685
837
  });
686
838
  }
687
839
  }
840
+ assembly.mark("calls", "Calls");
688
841
  disposeSurfaces = await mountFoundrySurfaces({
689
842
  registry: registry.native,
690
843
  layers,
691
844
  subscribers,
692
845
  context: surfaceContext
693
846
  });
847
+ assembly.mark("surfaces", "Layers and subscribers");
694
848
  await Effect.runPromise(
695
849
  installRegistry({
696
850
  registry: registry.capabilities,
@@ -720,12 +874,26 @@ async function executeDefinition(definition, id, runtimeValue) {
720
874
  messages,
721
875
  glove: base,
722
876
  store: base.store,
723
- emit: controls.emit
877
+ // Each installation's tools are folded just before it reports completing.
878
+ emit: (event) => {
879
+ if (event.type === "foundry.installation.completed") {
880
+ const installed = event.data;
881
+ assembly.mark("installation", installed.id ?? "installation", { keep: true, ...installed.kind ? { kind: installed.kind } : {}, ...installed.id ? { id: installed.id } : {} });
882
+ }
883
+ controls.emit(event);
884
+ }
724
885
  },
725
886
  ...definition.mcpAdapter ? { mcpAdapter: definition.mcpAdapter } : {},
726
- ...definition.accountSessions ? { accountSessions: definition.accountSessions } : {}
887
+ ...definition.accountSessions ? { accountSessions: definition.accountSessions } : {},
888
+ onApp: (app) => {
889
+ installedApps.push(app);
890
+ },
891
+ onCleanup: (cleanup) => {
892
+ cleanups.push(cleanup);
893
+ }
727
894
  })
728
895
  );
896
+ assembly.mark("mcp", "MCP servers");
729
897
  await Effect.runPromise(
730
898
  mountAgentDefinitionMemory({
731
899
  registry: registry.capabilities,
@@ -749,6 +917,7 @@ async function executeDefinition(definition, id, runtimeValue) {
749
917
  }
750
918
  })
751
919
  );
920
+ assembly.mark("memory", "Memory");
752
921
  if (definition.inboxes) {
753
922
  await hydrateInbox(base.store, inboxItems, controls.emit);
754
923
  }
@@ -772,12 +941,16 @@ async function executeDefinition(definition, id, runtimeValue) {
772
941
  }
773
942
  });
774
943
  cleanups.push(() => mesh.adapter.unregister());
944
+ assembly.mark("mesh", "Mesh transport");
775
945
  }
776
946
  if (definition.configure) {
777
947
  await resolveResolvable(definition.configure(base, callContext));
948
+ assembly.mark("configure", "configure()");
778
949
  }
779
950
  await workbench.mountRepl();
951
+ assembly.mark("repl", "REPL");
780
952
  const glove = definition.build ? await resolveResolvable(definition.build(base, assemblyContext)) ?? base : base;
953
+ if (glove !== base) assembly.mark("build", "build()", { glove });
781
954
  if (glove !== base) {
782
955
  base.removeSubscriber(subscriber);
783
956
  base.removeSubscriber(deliverySubscriber);
@@ -789,12 +962,56 @@ async function executeDefinition(definition, id, runtimeValue) {
789
962
  glove.removeSubscriber(deliverySubscriber);
790
963
  });
791
964
  eventRecipient = glove;
965
+ controls.emit({
966
+ type: FOUNDRY_ASSEMBLY_COMPOSED_EVENT,
967
+ data: {
968
+ durationMs: assembly.elapsedMs(),
969
+ steps: assembly.steps,
970
+ tools: glove.tools.map((tool) => tool.name),
971
+ installations: effectiveInstallations.map((installation) => ({ kind: installation.kind, id: installation.id, ...installation.accountId ? { accountId: installation.accountId } : {} })),
972
+ apps: installedApps.map((app) => ({ id: app.id, description: app.description, ...app.accountId ? { accountId: app.accountId } : {}, tools: app.tools })),
973
+ playbooks: desiredPlaybooks.map((playbook) => ({ id: playbook.id, ...playbook.playbookName ? { name: playbook.playbookName } : {} })),
974
+ schedules: desiredSchedules.map((schedule) => ({ name: schedule.name, timing: schedule.timing, enabled: schedule.enabled })),
975
+ delegates: normalizedDelegates.map((delegate) => ({ agent: delegate.agent, ...delegate.description ? { description: delegate.description } : {} })),
976
+ durableSubagents: durableNames,
977
+ openDelegations: assemblyContext.delegations.length,
978
+ ...ownDelegation ? { delegation: { id: ownDelegation.id, from: ownDelegation.from.definitionId, task: ownDelegation.task } } : {},
979
+ mesh: { hosted: meshHosted, transport: Boolean(mesh), threads: assemblyContext.threads.length, ...ownThread ? { thread: ownThread.id } : {} },
980
+ hooks: hooks.map((hook) => hook.name),
981
+ skills: skills.map((skill) => skill.name),
982
+ subagents: subagents.map((subagent) => subagent.name),
983
+ calls: calls.map((call) => ({ name: call.name, exposed: call.exposeToAgent ?? true })),
984
+ workingEnvironment: Boolean(workbench.workingEnvironment),
985
+ repl: Boolean(workbench.repl),
986
+ events: { initial: initialDeliveries.length, buffered: bufferedDeliveries.length }
987
+ }
988
+ });
792
989
  await forwardDeliveries(bufferedDeliveries.splice(0));
793
990
  const runtimeContext = { ...callContext, glove };
794
991
  let initialEventsPending = initialDeliveries.length > 0;
795
992
  const defaultRun = async (messageInput = assemblyContext.messageInput) => {
796
993
  if (initialEventsPending && messageInput === assemblyContext.messageInput) {
797
994
  initialEventsPending = false;
995
+ const decisions = initialDeliveries.filter((delivery) => approvalDecisionOf(delivery));
996
+ if (decisions.length && glove.resumeToolCalls) {
997
+ for (const delivery of decisions) {
998
+ const decision = approvalDecisionOf(delivery);
999
+ await runtimeStore?.setPermission?.(decision.toolName, decision.status === "approved" ? "granted" : "denied", decision.toolInput);
1000
+ }
1001
+ const resumed = await glove.resumeToolCalls(abortController.signal);
1002
+ const answered = resumed === void 0 && runtimeStore ? new Set((await runtimeStore.getMessages()).flatMap((message2) => (message2.tool_results ?? []).map((result2) => result2.call_id))) : void 0;
1003
+ const done = decisions.filter((delivery) => {
1004
+ const callId = approvalDecisionOf(delivery).toolCallId;
1005
+ return resumed !== void 0 || callId !== void 0 && answered?.has(callId);
1006
+ });
1007
+ if (done.length) {
1008
+ consumed(done);
1009
+ const rest = initialDeliveries.filter((delivery) => !done.includes(delivery));
1010
+ if (!rest.length) return resumed === void 0 ? null : extractOutput(resumed);
1011
+ await forwardDeliveries(rest);
1012
+ return extractOutput(await glove.processEvents(abortController.signal));
1013
+ }
1014
+ }
798
1015
  await forwardDeliveries(initialDeliveries);
799
1016
  return extractOutput(await glove.processEvents(abortController.signal));
800
1017
  }
@@ -811,21 +1028,31 @@ async function executeDefinition(definition, id, runtimeValue) {
811
1028
  defaultHandler: defaultRun,
812
1029
  spawn
813
1030
  };
814
- const result = definition.run ? await resolveResolvable(definition.run(glove, handlerContext)) : definition.handler ? await resolveResolvable(definition.handler(handlerContext)) : definition.spawn ? await spawn() : await defaultRun();
1031
+ let awaitingApproval;
1032
+ let result;
1033
+ try {
1034
+ result = definition.run ? await resolveResolvable(definition.run(glove, handlerContext)) : definition.handler ? await resolveResolvable(definition.handler(handlerContext)) : definition.spawn ? await spawn() : await defaultRun();
1035
+ } catch (cause) {
1036
+ const deferral = isTurnSuspended(cause) ? cause.deferral.data : void 0;
1037
+ if (typeof deferral?.approvalId !== "string") throw cause;
1038
+ awaitingApproval = { approvalId: deferral.approvalId, toolName: String(deferral.toolName ?? "") };
1039
+ result = `Waiting for approval to run ${awaitingApproval.toolName || "a tool"} (${awaitingApproval.approvalId}).`;
1040
+ }
815
1041
  if (initialEventsPending) consumed(initialDeliveries);
816
1042
  await guidance.snapshot();
817
1043
  const sleep = [...controls.commands].reverse().find(
818
1044
  (command) => command.type === "sleep"
819
1045
  );
820
1046
  const question = pendingQuestion.current;
1047
+ const waiting = pendingReply.current;
821
1048
  return {
822
- status: sleep || question ? "suspended" : "completed",
1049
+ status: sleep || question || waiting || awaitingApproval ? "suspended" : "completed",
823
1050
  value: serializable(result),
824
1051
  ...consumedEventIds.size ? { consumedEventIds: [...consumedEventIds] } : {},
825
1052
  agentId: request.agentId,
826
1053
  conversationId: request.conversationId,
827
1054
  workspaceId: request.workspaceId,
828
- ...question ? { suspension: { kind: "question", ...question } } : sleep && sleep.type === "sleep" ? { suspension: { commandId: sleep.id, wakeAt: sleep.wakeAt } } : {}
1055
+ ...awaitingApproval ? { suspension: { kind: "approval", ...awaitingApproval } } : question ? { suspension: { kind: "question", ...question } } : waiting ? { suspension: { kind: "mesh", ...waiting } } : sleep && sleep.type === "sleep" ? { suspension: { commandId: sleep.id, wakeAt: sleep.wakeAt } } : {}
829
1056
  };
830
1057
  } finally {
831
1058
  const failures = [];
@@ -865,7 +1092,7 @@ function compileAgentDefinition(definition, route) {
865
1092
  payload: z.unknown().optional(),
866
1093
  context: z.record(z.string(), z.unknown()).optional(),
867
1094
  source: z.object({
868
- kind: z.enum(["direct", "transmission", "activation", "spawn", "background", "delegation", "agent-message"]),
1095
+ kind: z.enum(["direct", "transmission", "activation", "spawn", "background", "delegation", "agent-message", "mesh"]),
869
1096
  id: z.string().optional(),
870
1097
  provider: z.string().optional(),
871
1098
  eventId: z.string().optional(),
@@ -881,6 +1108,9 @@ function compileAgentDefinition(definition, route) {
881
1108
  id: z.string(),
882
1109
  definitionId: z.string(),
883
1110
  workspaceId: z.string(),
1111
+ provisioningKey: z.string().optional(),
1112
+ name: z.string().optional(),
1113
+ description: z.string().optional(),
884
1114
  durableSubagent: z.object({ parentAgentId: z.string(), name: z.string(), status: z.enum(["active", "archived", "purged"]) }).optional(),
885
1115
  context: z.record(z.string(), z.unknown()),
886
1116
  installations: z.array(z.object({
@@ -974,6 +1204,7 @@ function compileAgentDefinition(definition, route) {
974
1204
  createdAt: z.string(),
975
1205
  updatedAt: z.string()
976
1206
  })).default([]),
1207
+ threads: z.array(z.record(z.string(), z.unknown())).default([]),
977
1208
  conversationLease: z.literal(true).optional()
978
1209
  });
979
1210
  let builder = signal(internalAgentName(route)).input(executionEnvelope).output(z.object({
@@ -990,7 +1221,14 @@ function compileAgentDefinition(definition, route) {
990
1221
  commandId: z.string(),
991
1222
  delegationId: z.string(),
992
1223
  question: z.string()
993
- })
1224
+ }),
1225
+ z.object({
1226
+ kind: z.literal("mesh"),
1227
+ commandId: z.string(),
1228
+ threadId: z.string(),
1229
+ messageId: z.string()
1230
+ }),
1231
+ z.object({ kind: z.literal("approval"), approvalId: z.string(), toolName: z.string() })
994
1232
  ]).optional()
995
1233
  }));
996
1234
  if (definition.runTimeoutMs !== void 0) builder = builder.timeout(definition.runTimeoutMs);