glove-foundry 0.5.1 → 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.
Files changed (44) hide show
  1. package/README.md +104 -15
  2. package/dist/{chunk-GKZLWD5M.js → chunk-7F7QVO6I.js} +4 -1
  3. package/dist/chunk-B36BGF5R.js +530 -0
  4. package/dist/{chunk-5NFLGHOC.js → chunk-K2EU63MB.js} +216 -29
  5. package/dist/{chunk-KBMD4RYU.js → chunk-OBTOFA7W.js} +63 -198
  6. package/dist/{chunk-LW5PJ2FN.js → chunk-RSU7NEDK.js} +9 -3
  7. package/dist/{chunk-TH5ETCG2.js → chunk-TFGETZYH.js} +198 -11
  8. package/dist/{chunk-SGF3CFUR.js → chunk-X6EWEWWM.js} +942 -57
  9. package/dist/cli.js +8 -5
  10. package/dist/client-DWPYe_Nc.d.ts +888 -0
  11. package/dist/client.d.ts +2 -1
  12. package/dist/client.js +1 -1
  13. package/dist/{client-DcsnudMI.d.ts → definition-A8o11aez.d.ts} +195 -812
  14. package/dist/execution-agent.js +5 -4
  15. package/dist/execution-daemon.js +37 -2
  16. package/dist/execution-loader.js +5 -4
  17. package/dist/index.d.ts +8 -3
  18. package/dist/index.js +39 -14
  19. package/dist/voice.d.ts +168 -0
  20. package/dist/voice.js +348 -0
  21. package/docs/building-with-foundry.md +32 -21
  22. package/docs/durable-execution.md +56 -0
  23. package/docs/release-verification.md +1 -1
  24. package/package.json +16 -9
  25. package/templates/minimal/README.md +34 -8
  26. package/templates/minimal/agents/assistant/agent.ts +24 -10
  27. package/templates/minimal/foundry.application.ts +11 -3
  28. package/templates/minimal/gitignore +1 -0
  29. package/templates/minimal/lib/file-store.ts +95 -0
  30. package/templates/travel-concierge/README.md +46 -12
  31. package/templates/travel-concierge/agents/concierge/agent.ts +10 -4
  32. package/templates/travel-concierge/agents/concierge/composition.ts +9 -2
  33. package/templates/travel-concierge/agents/concierge/flights.ts +43 -0
  34. package/templates/travel-concierge/agents/concierge/instances.ts +42 -0
  35. package/templates/travel-concierge/agents/concierge/memory/traveller.memory.ts +13 -8
  36. package/templates/travel-concierge/agents/concierge/tools/convert-currency.tool.ts +34 -0
  37. package/templates/travel-concierge/agents/concierge/workbench.ts +4 -1
  38. package/templates/travel-concierge/foundry.application.ts +15 -6
  39. package/templates/travel-concierge/gitignore +1 -0
  40. package/templates/travel-concierge/lib/demo-model.ts +89 -25
  41. package/templates/travel-concierge/lib/file-context.ts +60 -0
  42. package/templates/travel-concierge/lib/file-store.ts +95 -0
  43. package/templates/minimal/agents/assistant/tools/current-time.tool.ts +0 -17
  44. package/templates/travel-concierge/agents/concierge/tools/find-flights.tool.ts +0 -49
@@ -8,16 +8,13 @@ import {
8
8
  EMPTY_AGENT_COMPOSITION,
9
9
  EMPTY_CAPABILITY_REGISTRY,
10
10
  EMPTY_FOUNDRY_APPLICATION,
11
- EMPTY_NATIVE_REGISTRY,
12
11
  FOUNDRY_AGENT_APPLICATION_BRAND,
13
12
  FOUNDRY_APPROVAL_DIRECTORY_ENV,
14
13
  FOUNDRY_CORE_COMMAND_DIRECTORY_ENV,
15
14
  FOUNDRY_CORE_COMMAND_EVENT,
16
- FOUNDRY_LAYER_BRAND,
17
15
  FOUNDRY_MCP_BRAND,
18
16
  FOUNDRY_MEMORY_BRAND,
19
17
  FOUNDRY_SHARED_TOOL_BRAND,
20
- FOUNDRY_SUBSCRIBER_BRAND,
21
18
  MemoryFoundryDataAdapter,
22
19
  claimFoundryCoreCommandRequest,
23
20
  createAgentInstance,
@@ -38,13 +35,32 @@ import {
38
35
  resolveFoundryApproval,
39
36
  settleFoundryCoreCommandRequest,
40
37
  transmissionPredicate
41
- } from "./chunk-KBMD4RYU.js";
38
+ } from "./chunk-OBTOFA7W.js";
39
+ import {
40
+ FOUNDRY_CONVERSATION_LEASE_EVENT,
41
+ FOUNDRY_CONVERSATION_LISTEN_EVENT,
42
+ FOUNDRY_MAILBOX_DIRECTORY_ENV,
43
+ delegationFromContext,
44
+ drainMailbox,
45
+ isDelegationId,
46
+ isOpenDelegation,
47
+ renderDelegatedTask,
48
+ renderDeliveries,
49
+ undeliveredUpdate,
50
+ workerAgentId,
51
+ writeConversationLease,
52
+ writeMailboxDelivery
53
+ } from "./chunk-B36BGF5R.js";
42
54
  import {
55
+ EMPTY_NATIVE_REGISTRY,
43
56
  FOUNDRY_APPLICATION_ENV,
44
57
  FOUNDRY_EVENT_PREFIX,
45
58
  FOUNDRY_EXECUTION_MARKER,
59
+ FOUNDRY_LAYER_BRAND,
60
+ FOUNDRY_RUN_PROCESS_EVENT,
61
+ FOUNDRY_SUBSCRIBER_BRAND,
46
62
  bindFileIdentity
47
- } from "./chunk-5NFLGHOC.js";
63
+ } from "./chunk-K2EU63MB.js";
48
64
 
49
65
  // src/codegen.ts
50
66
  import { mkdir, writeFile } from "node:fs/promises";
@@ -723,12 +739,16 @@ function encodedAgentEvent(message) {
723
739
  }
724
740
  }
725
741
  var FoundryObserver = class {
726
- constructor(adapter, routeForSignalName, onAgentEvent) {
742
+ constructor(adapter, routeForSignalName, onAgentEvent, onRunSettled) {
727
743
  this.adapter = adapter;
728
744
  this.routeForSignalName = routeForSignalName;
729
745
  this.onAgentEvent = onAgentEvent;
746
+ this.onRunSettled = onRunSettled;
730
747
  }
731
748
  logBuffers = /* @__PURE__ */ new Map();
749
+ settled(run, status, detail = {}) {
750
+ this.onRunSettled?.({ route: this.route(run.signalName), run, status, ...detail });
751
+ }
732
752
  route(name) {
733
753
  return this.routeForSignalName(name);
734
754
  }
@@ -758,6 +778,7 @@ var FoundryObserver = class {
758
778
  onRunCompleted(event) {
759
779
  this.flushRunLogs(event.run);
760
780
  this.runEvent("run.completed", event.run, { output: event.output });
781
+ this.settled(event.run, "completed", event.output !== void 0 ? { output: event.output } : {});
761
782
  }
762
783
  onRunTimeout({ run }) {
763
784
  this.runEvent("run.timeout", run);
@@ -771,10 +792,12 @@ var FoundryObserver = class {
771
792
  onRunFailed(event) {
772
793
  this.flushRunLogs(event.run);
773
794
  this.runEvent("run.failed", event.run, { error: event.error });
795
+ this.settled(event.run, "failed", event.error !== void 0 ? { error: event.error } : {});
774
796
  }
775
797
  onRunCancelled({ run }) {
776
798
  this.flushRunLogs(run);
777
799
  this.runEvent("run.cancelled", run);
800
+ this.settled(run, "cancelled");
778
801
  }
779
802
  onRunSkipped(event) {
780
803
  this.runEvent("run.skipped", event.run, { reason: event.reason });
@@ -985,8 +1008,12 @@ var FoundryExecutionBackend = class {
985
1008
  })();
986
1009
  return this.stopping;
987
1010
  }
988
- triggerSignal(name, input) {
989
- return this.request({ method: "trigger", name, input });
1011
+ triggerSignal(name, input, options = {}) {
1012
+ return this.request({ method: "trigger", name, input, ...options.parked ? { parked: true } : {} });
1013
+ }
1014
+ /** Make a parked run due, with the input it should start from. False when it is no longer pending. */
1015
+ releaseRun(id2, input) {
1016
+ return this.request({ method: "release", id: id2, input });
990
1017
  }
991
1018
  getRun(id2) {
992
1019
  return this.request({ method: "get", id: id2 });
@@ -1024,6 +1051,151 @@ import {
1024
1051
  nextCronOccurrence
1025
1052
  } from "station-schedules";
1026
1053
 
1054
+ // src/conversation-gate.ts
1055
+ var ConversationGate = class {
1056
+ constructor(hooks) {
1057
+ this.hooks = hooks;
1058
+ }
1059
+ lanes = /* @__PURE__ */ new Map();
1060
+ conversationByRun = /* @__PURE__ */ new Map();
1061
+ /** Something is running, waiting, or held for this conversation. */
1062
+ busy(conversationId) {
1063
+ const lane = this.lanes.get(conversationId);
1064
+ return Boolean(lane && (lane.active || lane.waiting.length > 0 || lane.holds > 0));
1065
+ }
1066
+ /** The run is waiting for its conversation. */
1067
+ waiting(runId) {
1068
+ const conversationId = this.conversationByRun.get(runId);
1069
+ const lane = conversationId ? this.lanes.get(conversationId) : void 0;
1070
+ return Boolean(lane?.waiting.some((slot) => slot.runId === runId));
1071
+ }
1072
+ /** The run that holds the conversation, once its id is known. */
1073
+ activeRun(conversationId) {
1074
+ return this.lanes.get(conversationId)?.active?.runId;
1075
+ }
1076
+ /**
1077
+ * Create a run for the conversation. `create(parked)` makes it: started
1078
+ * at once when the lane is free, parked otherwise; `start` makes a parked
1079
+ * run due when its turn comes. `front` puts it ahead of runs already waiting.
1080
+ */
1081
+ async admit(conversationId, create, start, options = {}) {
1082
+ const lane = this.lane(conversationId);
1083
+ const slot = { start };
1084
+ const parked = Boolean(lane.active) || lane.waiting.length > 0 || lane.holds > 0;
1085
+ if (!parked) lane.active = slot;
1086
+ else if (options.front) lane.waiting.unshift(slot);
1087
+ else lane.waiting.push(slot);
1088
+ let runId;
1089
+ try {
1090
+ runId = await create(parked);
1091
+ } catch (cause) {
1092
+ this.remove(conversationId, slot);
1093
+ throw cause;
1094
+ }
1095
+ slot.runId = runId;
1096
+ this.conversationByRun.set(runId, conversationId);
1097
+ if (slot.promoted) this.begin(conversationId, slot);
1098
+ return runId;
1099
+ }
1100
+ /**
1101
+ * A run the gate did not create asks for the conversation. Resolves when it
1102
+ * holds it. A run that already holds it resolves at once.
1103
+ */
1104
+ claim(conversationId, runId) {
1105
+ const known = this.conversationByRun.get(runId);
1106
+ const lane = this.lane(conversationId);
1107
+ if (known === conversationId && lane.active?.runId === runId) return Promise.resolve();
1108
+ return new Promise((resolveClaim) => {
1109
+ const slot = {
1110
+ runId,
1111
+ start: async () => {
1112
+ resolveClaim();
1113
+ return true;
1114
+ }
1115
+ };
1116
+ this.conversationByRun.set(runId, conversationId);
1117
+ if (!this.busy(conversationId)) {
1118
+ lane.active = slot;
1119
+ resolveClaim();
1120
+ return;
1121
+ }
1122
+ lane.waiting.push(slot);
1123
+ });
1124
+ }
1125
+ /** The run settled and its process let go: the next one may start. */
1126
+ settled(runId) {
1127
+ const conversationId = this.conversationByRun.get(runId);
1128
+ if (!conversationId) return;
1129
+ this.conversationByRun.delete(runId);
1130
+ const lane = this.lanes.get(conversationId);
1131
+ if (!lane) return;
1132
+ if (lane.active?.runId === runId) {
1133
+ lane.active = void 0;
1134
+ } else {
1135
+ const index = lane.waiting.findIndex((slot) => slot.runId === runId);
1136
+ if (index >= 0) lane.waiting.splice(index, 1);
1137
+ }
1138
+ this.pump(conversationId);
1139
+ }
1140
+ /** Keep the conversation from starting its next run until the returned release is called. */
1141
+ hold(conversationId) {
1142
+ const lane = this.lane(conversationId);
1143
+ lane.holds += 1;
1144
+ let released = false;
1145
+ return () => {
1146
+ if (released) return;
1147
+ released = true;
1148
+ lane.holds -= 1;
1149
+ this.pump(conversationId);
1150
+ };
1151
+ }
1152
+ lane(conversationId) {
1153
+ let lane = this.lanes.get(conversationId);
1154
+ if (!lane) {
1155
+ lane = { waiting: [], holds: 0 };
1156
+ this.lanes.set(conversationId, lane);
1157
+ }
1158
+ return lane;
1159
+ }
1160
+ remove(conversationId, slot) {
1161
+ const lane = this.lanes.get(conversationId);
1162
+ if (!lane) return;
1163
+ if (lane.active === slot) lane.active = void 0;
1164
+ else {
1165
+ const index = lane.waiting.indexOf(slot);
1166
+ if (index >= 0) lane.waiting.splice(index, 1);
1167
+ }
1168
+ this.pump(conversationId);
1169
+ }
1170
+ pump(conversationId) {
1171
+ const lane = this.lanes.get(conversationId);
1172
+ if (!lane || lane.active || lane.holds > 0) return;
1173
+ const next = lane.waiting.shift();
1174
+ if (!next) {
1175
+ this.lanes.delete(conversationId);
1176
+ this.hooks.idle(conversationId);
1177
+ return;
1178
+ }
1179
+ lane.active = next;
1180
+ if (next.runId) this.begin(conversationId, next);
1181
+ else next.promoted = true;
1182
+ }
1183
+ begin(conversationId, slot) {
1184
+ const runId = slot.runId;
1185
+ const start = slot.start;
1186
+ if (!start) return;
1187
+ void start(runId).then(
1188
+ (started) => {
1189
+ if (!started) this.settled(runId);
1190
+ },
1191
+ (cause) => {
1192
+ this.hooks.failed?.(conversationId, runId, cause);
1193
+ this.settled(runId);
1194
+ }
1195
+ );
1196
+ }
1197
+ };
1198
+
1027
1199
  // src/connection-supervisor.ts
1028
1200
  import { Effect as Effect4 } from "effect";
1029
1201
  function safeError(cause) {
@@ -1038,6 +1210,7 @@ var ApplicationConnectionSupervisor = class {
1038
1210
  }
1039
1211
  running = /* @__PURE__ */ new Map();
1040
1212
  states = /* @__PURE__ */ new Map();
1213
+ closed = false;
1041
1214
  list() {
1042
1215
  return [...this.states.values()].map((state) => ({
1043
1216
  ...state,
@@ -1063,10 +1236,18 @@ var ApplicationConnectionSupervisor = class {
1063
1236
  await this.stop(id2);
1064
1237
  this.start(current);
1065
1238
  }
1239
+ /**
1240
+ * Stop every connection for good. A reconcile still in flight (a run's
1241
+ * playbook sync, an installation change) must not start a connection after
1242
+ * this: nothing would stop it, and a provider connection runs until it is
1243
+ * interrupted, so the process could never exit.
1244
+ */
1066
1245
  async stopAll() {
1246
+ this.closed = true;
1067
1247
  await Promise.all([...this.running.keys()].map((id2) => this.stop(id2)));
1068
1248
  }
1069
1249
  start(desired) {
1250
+ if (this.closed) return;
1070
1251
  const controller = new AbortController();
1071
1252
  const task = this.run(desired, controller.signal).finally(() => {
1072
1253
  const current = this.running.get(desired.id);
@@ -1424,6 +1605,23 @@ var FoundryRuntimeError = class extends Schema3.TaggedError(
1424
1605
  message: Schema3.String
1425
1606
  }) {
1426
1607
  };
1608
+ function deliverySource(deliveries) {
1609
+ const first = deliveries[0];
1610
+ if (deliveries.every((delivery) => delivery.kind === "transmission")) {
1611
+ return first.kind === "transmission" ? { kind: "transmission", id: first.routeId, eventId: first.eventId } : { kind: "transmission" };
1612
+ }
1613
+ const delegation = deliveries.find((delivery) => delivery.kind !== "transmission");
1614
+ return { kind: "delegation", ...delegation && "delegationId" in delegation ? { id: delegation.delegationId } : {} };
1615
+ }
1616
+ function deliveryText(value) {
1617
+ if (typeof value === "string") return value;
1618
+ if (value === void 0 || value === null) return "";
1619
+ try {
1620
+ return JSON.stringify(value);
1621
+ } catch {
1622
+ return String(value);
1623
+ }
1624
+ }
1427
1625
  function parseJson(value) {
1428
1626
  if (value === void 0) return void 0;
1429
1627
  try {
@@ -1444,6 +1642,9 @@ function promiseEffect(operation, evaluate) {
1444
1642
  catch: (cause) => runtimeFailure(operation, cause)
1445
1643
  }).pipe(Effect5.withSpan(`foundry.${operation}`));
1446
1644
  }
1645
+ var RUN_PROCESS_RELEASE_TIMEOUT_MS = 1e4;
1646
+ var RUN_PROCESS_REPORT_GRACE_MS = 1e3;
1647
+ var RUN_PROCESS_RETENTION_MS = 6e4;
1447
1648
  var FoundryRuntime = class _FoundryRuntime {
1448
1649
  rootDir;
1449
1650
  agents;
@@ -1472,6 +1673,8 @@ var FoundryRuntime = class _FoundryRuntime {
1472
1673
  activationTransitions = Effect5.unsafeMakeSemaphore(1);
1473
1674
  activationDispatches = /* @__PURE__ */ new Map();
1474
1675
  activationTimers = /* @__PURE__ */ new Map();
1676
+ /** Whether each run's child process still holds its conversation, from FOUNDRY_RUN_PROCESS_EVENT. */
1677
+ runProcesses = /* @__PURE__ */ new Map();
1475
1678
  approvalDirectory = join2(
1476
1679
  tmpdir2(),
1477
1680
  "glove-foundry-approvals",
@@ -1482,7 +1685,41 @@ var FoundryRuntime = class _FoundryRuntime {
1482
1685
  "glove-foundry-core-commands",
1483
1686
  randomUUID2()
1484
1687
  );
1688
+ mailboxDirectory = join2(
1689
+ tmpdir2(),
1690
+ "glove-foundry-mailboxes",
1691
+ randomUUID2()
1692
+ );
1693
+ /** The run listening for deliveries on each conversation. */
1694
+ conversationListeners = /* @__PURE__ */ new Map();
1695
+ /** Runs holding each conversation, from enqueue or acquire until release. */
1696
+ conversationRuns = /* @__PURE__ */ new Map();
1697
+ runConversations = /* @__PURE__ */ new Map();
1698
+ /** Deliveries waiting for their conversation to be free. */
1699
+ heldDeliveries = /* @__PURE__ */ new Map();
1700
+ conversationQueues = /* @__PURE__ */ new Map();
1701
+ /** Runs cancelled by steering: a replacement follows, so their delegation stays open. */
1702
+ steeredRuns = /* @__PURE__ */ new Set();
1703
+ /** One run at a time per conversation; the next starts once the one ahead has let go. */
1704
+ gate = new ConversationGate({
1705
+ idle: (conversationId) => {
1706
+ void this.inConversation(conversationId, () => this.flushHeldDeliveries(conversationId)).catch((cause) => this.reportDeliveryFailure(conversationId, cause));
1707
+ },
1708
+ failed: (conversationId, runId, cause) => {
1709
+ this.observability.append({
1710
+ type: "conversation.run.start-failed",
1711
+ category: "system",
1712
+ runId,
1713
+ data: { conversationId, error: cause instanceof Error ? cause.message : String(cause) }
1714
+ });
1715
+ }
1716
+ });
1717
+ /** Pending inbound records each run is handling, so they are cleared when it settles. */
1718
+ pendingInboundByRun = /* @__PURE__ */ new Map();
1719
+ /** Recently settled runs, for a record assigned to a run that already finished. */
1720
+ settledRuns = /* @__PURE__ */ new Set();
1485
1721
  started = false;
1722
+ stopping = false;
1486
1723
  disposed = false;
1487
1724
  constructor(options) {
1488
1725
  this.rootDir = options.rootDir;
@@ -1545,6 +1782,26 @@ var FoundryRuntime = class _FoundryRuntime {
1545
1782
  this.observability,
1546
1783
  (name) => this.routeBySignalName.get(name) ?? name,
1547
1784
  (event) => {
1785
+ if (event.type === FOUNDRY_RUN_PROCESS_EVENT) {
1786
+ const state = event.data?.state;
1787
+ if (state === "acquired" || state === "released") {
1788
+ this.trackRunProcess(event.run.id, state);
1789
+ this.trackConversationRun(event.run, state);
1790
+ }
1791
+ return;
1792
+ }
1793
+ if (event.type === FOUNDRY_CONVERSATION_LISTEN_EVENT) {
1794
+ const state = event.data?.state;
1795
+ if (state === "on" || state === "off") this.trackConversationListener(event.run, state);
1796
+ return;
1797
+ }
1798
+ if (event.type === FOUNDRY_CONVERSATION_LEASE_EVENT) {
1799
+ const conversationId = this.toFoundryRun(event.run).conversationId;
1800
+ if (!conversationId) return;
1801
+ const runId = event.run.id;
1802
+ void this.gate.claim(conversationId, runId).then(() => writeConversationLease(this.mailboxDirectory, runId)).catch((cause) => this.reportDeliveryFailure(conversationId, cause));
1803
+ return;
1804
+ }
1548
1805
  if (event.type === FOUNDRY_CORE_COMMAND_EVENT) {
1549
1806
  void this.executeCoreCommand(event.data, event.run.id).catch((cause) => {
1550
1807
  this.observability.append({
@@ -1556,6 +1813,17 @@ var FoundryRuntime = class _FoundryRuntime {
1556
1813
  });
1557
1814
  });
1558
1815
  }
1816
+ },
1817
+ (settled) => {
1818
+ void this.handleRunSettled(settled).catch((cause) => {
1819
+ this.observability.append({
1820
+ type: "delegation.failed-to-report",
1821
+ category: "system",
1822
+ agent: settled.route,
1823
+ runId: settled.run.id,
1824
+ data: { error: cause instanceof Error ? cause.message : String(cause) }
1825
+ });
1826
+ });
1559
1827
  }
1560
1828
  );
1561
1829
  this.connectionSupervisor = new ApplicationConnectionSupervisor({
@@ -1610,6 +1878,7 @@ var FoundryRuntime = class _FoundryRuntime {
1610
1878
  env: {
1611
1879
  [FOUNDRY_APPROVAL_DIRECTORY_ENV]: this.approvalDirectory,
1612
1880
  [FOUNDRY_CORE_COMMAND_DIRECTORY_ENV]: this.coreCommandDirectory,
1881
+ [FOUNDRY_MAILBOX_DIRECTORY_ENV]: this.mailboxDirectory,
1613
1882
  ...this.applicationFilePath ? { [FOUNDRY_APPLICATION_ENV]: this.applicationFilePath } : {}
1614
1883
  }
1615
1884
  });
@@ -1660,7 +1929,8 @@ var FoundryRuntime = class _FoundryRuntime {
1660
1929
  try {
1661
1930
  await Promise.all([
1662
1931
  mkdir2(this.approvalDirectory, { recursive: true, mode: 448 }),
1663
- mkdir2(this.coreCommandDirectory, { recursive: true, mode: 448 })
1932
+ mkdir2(this.coreCommandDirectory, { recursive: true, mode: 448 }),
1933
+ mkdir2(this.mailboxDirectory, { recursive: true, mode: 448 })
1664
1934
  ]);
1665
1935
  await this.seedTopology();
1666
1936
  for (const instance of await this.listAgentInstances()) {
@@ -1685,6 +1955,8 @@ var FoundryRuntime = class _FoundryRuntime {
1685
1955
  await this.reconstructActivations();
1686
1956
  this.runInBackground("signal", this.signalRunner.start());
1687
1957
  await this.reconcileApplicationConnections();
1958
+ void this.redeliverDelegations().catch((cause) => this.reportDeliveryFailure("startup", cause));
1959
+ void this.redeliverInbound().catch((cause) => this.reportDeliveryFailure("startup", cause));
1688
1960
  } catch (cause) {
1689
1961
  try {
1690
1962
  await this.stop();
@@ -1704,11 +1976,13 @@ var FoundryRuntime = class _FoundryRuntime {
1704
1976
  await this.services.dispose();
1705
1977
  await Promise.all([
1706
1978
  rm2(this.approvalDirectory, { recursive: true, force: true }),
1707
- rm2(this.coreCommandDirectory, { recursive: true, force: true })
1979
+ rm2(this.coreCommandDirectory, { recursive: true, force: true }),
1980
+ rm2(this.mailboxDirectory, { recursive: true, force: true })
1708
1981
  ]);
1709
1982
  this.disposed = true;
1710
1983
  return;
1711
1984
  }
1985
+ this.stopping = true;
1712
1986
  for (const timer of this.activationTimers.values()) clearTimeout(timer);
1713
1987
  this.activationTimers.clear();
1714
1988
  this.activationDispatches.clear();
@@ -1721,7 +1995,8 @@ var FoundryRuntime = class _FoundryRuntime {
1721
1995
  await this.services.dispose();
1722
1996
  await Promise.all([
1723
1997
  rm2(this.approvalDirectory, { recursive: true, force: true }),
1724
- rm2(this.coreCommandDirectory, { recursive: true, force: true })
1998
+ rm2(this.coreCommandDirectory, { recursive: true, force: true }),
1999
+ rm2(this.mailboxDirectory, { recursive: true, force: true })
1725
2000
  ]);
1726
2001
  this.started = false;
1727
2002
  this.disposed = true;
@@ -1731,7 +2006,7 @@ var FoundryRuntime = class _FoundryRuntime {
1731
2006
  stop() {
1732
2007
  return Effect5.runPromise(this.stopEffect());
1733
2008
  }
1734
- requestEffect(route, request) {
2009
+ requestEffect(route, request, options = {}) {
1735
2010
  return promiseEffect("agent.request", async () => {
1736
2011
  if (!this.started) throw new Error("Foundry runtime is not started.");
1737
2012
  const discovered = this.byRoute.get(route);
@@ -1752,10 +2027,7 @@ var FoundryRuntime = class _FoundryRuntime {
1752
2027
  ...conversation,
1753
2028
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1754
2029
  })));
1755
- const runId = await this.signalRunner.triggerSignal(
1756
- discovered.executionName,
1757
- await this.executionEnvelope(request)
1758
- );
2030
+ const runId = await this.admitRun(discovered.executionName, request, options);
1759
2031
  const run = await this.signalRunner.getRun(runId);
1760
2032
  if (!run) throw new Error(`Foundry failed to create run "${runId}".`);
1761
2033
  return this.toFoundryRun(run);
@@ -2043,12 +2315,51 @@ var FoundryRuntime = class _FoundryRuntime {
2043
2315
  return runs.map((run) => this.toFoundryRun(run));
2044
2316
  }
2045
2317
  async waitForRun(runId, options) {
2318
+ while (this.gate.waiting(runId)) {
2319
+ await new Promise((resolveWait) => setTimeout(resolveWait, options?.pollMs ?? 100));
2320
+ }
2046
2321
  const run = await this.signalRunner.waitForRun(runId, options);
2047
2322
  return run ? this.toFoundryRun(run) : null;
2048
2323
  }
2049
2324
  cancel(runId) {
2050
2325
  return this.signalRunner.cancel(runId);
2051
2326
  }
2327
+ trackRunProcess(runId, state) {
2328
+ this.runProcesses.set(runId, state);
2329
+ if (state !== "released") return;
2330
+ const forget = setTimeout(() => {
2331
+ if (this.runProcesses.get(runId) === "released") this.runProcesses.delete(runId);
2332
+ }, RUN_PROCESS_RETENTION_MS);
2333
+ forget.unref?.();
2334
+ }
2335
+ /**
2336
+ * Wait until a cancelled run's process has let go of its conversation. A run
2337
+ * that never started has no process. A process that dies before it reports
2338
+ * (SIGTERM during startup, or Station's SIGKILL five seconds after the
2339
+ * cancel) cannot report, so the wait is bounded by that kill.
2340
+ */
2341
+ async waitForRunProcessRelease(run, agent) {
2342
+ if (!run.startedAt) return;
2343
+ const started = Date.now();
2344
+ for (; ; ) {
2345
+ const state = this.runProcesses.get(run.id);
2346
+ const waited = Date.now() - started;
2347
+ if (state === "released") return;
2348
+ if (state === void 0 && waited >= RUN_PROCESS_REPORT_GRACE_MS) return;
2349
+ if (waited >= RUN_PROCESS_RELEASE_TIMEOUT_MS) {
2350
+ this.runProcesses.delete(run.id);
2351
+ this.observability.append({
2352
+ type: "run.steer.release-timeout",
2353
+ category: "system",
2354
+ agent,
2355
+ runId: run.id,
2356
+ data: { waitedMs: waited }
2357
+ });
2358
+ return;
2359
+ }
2360
+ await new Promise((resolveWait) => setTimeout(resolveWait, 25));
2361
+ }
2362
+ }
2052
2363
  /**
2053
2364
  * Change course at a run boundary.
2054
2365
  *
@@ -2064,23 +2375,40 @@ var FoundryRuntime = class _FoundryRuntime {
2064
2375
  throw new Error(`Foundry run "${runId}" does not expose an agent conversation to steer.`);
2065
2376
  }
2066
2377
  const active = source.status === "pending" || source.status === "running";
2067
- const interrupted = active ? await this.cancel(runId) : false;
2068
- if (interrupted) {
2069
- const terminal = await this.waitForRun(runId, {
2070
- pollMs: 25,
2071
- timeoutMs: Math.min(Math.max(source.timeoutMs, 1e3), 3e4)
2072
- });
2073
- if (!terminal || (terminal.status === "pending" || terminal.status === "running")) {
2074
- throw new Error(`Foundry could not reach a safe steering boundary for run "${runId}".`);
2378
+ const release = this.gate.hold(source.conversationId);
2379
+ let run;
2380
+ let interrupted = false;
2381
+ try {
2382
+ if (active) this.steeredRuns.add(runId);
2383
+ interrupted = active ? await this.cancel(runId) : false;
2384
+ if (!interrupted) this.steeredRuns.delete(runId);
2385
+ if (interrupted) {
2386
+ const terminal = await this.waitForRun(runId, {
2387
+ pollMs: 25,
2388
+ timeoutMs: Math.min(Math.max(source.timeoutMs, 1e3), 3e4)
2389
+ });
2390
+ if (!terminal || (terminal.status === "pending" || terminal.status === "running")) {
2391
+ throw new Error(`Foundry could not reach a safe steering boundary for run "${runId}".`);
2392
+ }
2393
+ await this.waitForRunProcessRelease(terminal, source.agent);
2075
2394
  }
2395
+ const agent = await Effect5.runPromise(this.data.getAgent(source.agentId));
2396
+ if (!agent) throw new Error(`Foundry agent instance "${source.agentId}" was not found.`);
2397
+ run = await Effect5.runPromise(this.requestEffect(agent.definitionId, {
2398
+ agentId: source.agentId,
2399
+ conversationId: source.conversationId,
2400
+ workspaceId: agent.workspaceId,
2401
+ message,
2402
+ context: {
2403
+ protocol: "foundry-control",
2404
+ steeredFromRunId: runId,
2405
+ steeringMode: "interrupt-and-restart"
2406
+ },
2407
+ source: { kind: "direct" }
2408
+ }, { front: true }));
2409
+ } finally {
2410
+ release();
2076
2411
  }
2077
- const run = await this.send(source.agentId, source.conversationId, message, {
2078
- context: {
2079
- protocol: "foundry-control",
2080
- steeredFromRunId: runId,
2081
- steeringMode: "interrupt-and-restart"
2082
- }
2083
- });
2084
2412
  this.observability.append({
2085
2413
  type: "run.steered",
2086
2414
  category: "system",
@@ -2430,29 +2758,34 @@ var FoundryRuntime = class _FoundryRuntime {
2430
2758
  event,
2431
2759
  playbooks: matched
2432
2760
  });
2433
- const run = await this.request(agent.definitionId, {
2434
- agentId: agent.id,
2435
- conversationId: conversation.id,
2436
- workspaceId: agent.workspaceId,
2437
- message: eventMessage,
2438
- payload: event,
2439
- context: {
2440
- playbookIds: matched.map((playbook) => playbook.id),
2441
- outbound: matched.flatMap((playbook) => playbook.outbound ?? [])
2442
- },
2443
- source: {
2444
- kind: "transmission",
2445
- id: route.id,
2446
- provider: route.transmissionId,
2447
- eventId: input.eventId,
2448
- threadKey: input.threadKey
2761
+ const run = await this.admitInbound({
2762
+ id: `${claim}:${agent.id}`,
2763
+ definitionId: agent.definitionId,
2764
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2765
+ request: {
2766
+ agentId: agent.id,
2767
+ conversationId: conversation.id,
2768
+ workspaceId: agent.workspaceId,
2769
+ message: eventMessage,
2770
+ payload: event,
2771
+ context: {
2772
+ playbookIds: matched.map((playbook) => playbook.id),
2773
+ outbound: matched.flatMap((playbook) => playbook.outbound ?? [])
2774
+ },
2775
+ source: {
2776
+ kind: "transmission",
2777
+ id: route.id,
2778
+ provider: route.transmissionId,
2779
+ eventId: input.eventId,
2780
+ threadKey: input.threadKey
2781
+ }
2449
2782
  }
2450
2783
  });
2451
- runs.push(run);
2784
+ if (run && !runs.some((item) => item.id === run.id)) runs.push(run);
2452
2785
  deliveries.push({
2453
2786
  agentId: agent.id,
2454
2787
  playbookIds: matched.map((playbook) => playbook.id),
2455
- runId: run.id
2788
+ ...run ? { runId: run.id } : {}
2456
2789
  });
2457
2790
  }
2458
2791
  await Effect5.runPromise(
@@ -3019,15 +3352,547 @@ var FoundryRuntime = class _FoundryRuntime {
3019
3352
  });
3020
3353
  }
3021
3354
  }
3355
+ // ── Delegation ──────────────────────────────────────────────────────────
3356
+ //
3357
+ // A delegation is a worker conversation whose context carries the record.
3358
+ // Results and questions go back to the delegating conversation, replies go
3359
+ // to the worker. Each delivery reaches a run that is listening on the
3360
+ // conversation, or waits until the conversation is free and starts one run
3361
+ // carrying everything that arrived meanwhile.
3362
+ /** Every delegation, newest first, optionally narrowed to one delegating conversation. */
3363
+ async listDelegations(filter = {}) {
3364
+ const found = [];
3365
+ for (const agent of await Effect5.runPromise(this.data.listAgents())) {
3366
+ for (const conversation of await Effect5.runPromise(this.data.listConversations(agent.id))) {
3367
+ const delegation = delegationFromContext(conversation.context);
3368
+ if (!delegation || delegation.workerAgentId !== agent.id) continue;
3369
+ if (filter.agentId && delegation.from.agentId !== filter.agentId) continue;
3370
+ if (filter.conversationId && delegation.from.conversationId !== filter.conversationId) continue;
3371
+ if (filter.status && delegation.status !== filter.status) continue;
3372
+ found.push(delegation);
3373
+ }
3374
+ }
3375
+ return found.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
3376
+ }
3377
+ async openDelegationsFrom(agentId, conversationId) {
3378
+ const open = [];
3379
+ for (const route of this.byRoute.keys()) {
3380
+ const workerId = workerAgentId(agentId, route);
3381
+ if (!await Effect5.runPromise(this.data.getAgent(workerId))) continue;
3382
+ for (const conversation of await Effect5.runPromise(this.data.listConversations(workerId))) {
3383
+ const delegation = delegationFromContext(conversation.context);
3384
+ if (delegation && delegation.from.conversationId === conversationId && isOpenDelegation(delegation)) {
3385
+ open.push(delegation);
3386
+ }
3387
+ }
3388
+ }
3389
+ return open.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
3390
+ }
3391
+ /** Run work for one conversation after the work already queued for it. */
3392
+ inConversation(conversationId, work) {
3393
+ const previous = this.conversationQueues.get(conversationId) ?? Promise.resolve();
3394
+ const next = previous.catch(() => void 0).then(work);
3395
+ const tail = next.catch(() => void 0);
3396
+ this.conversationQueues.set(conversationId, tail);
3397
+ void tail.then(() => {
3398
+ if (this.conversationQueues.get(conversationId) === tail) this.conversationQueues.delete(conversationId);
3399
+ });
3400
+ return next;
3401
+ }
3402
+ occupyConversation(conversationId, runId) {
3403
+ this.runConversations.set(runId, conversationId);
3404
+ const runs = this.conversationRuns.get(conversationId) ?? /* @__PURE__ */ new Set();
3405
+ runs.add(runId);
3406
+ this.conversationRuns.set(conversationId, runs);
3407
+ }
3408
+ trackConversationRun(run, state) {
3409
+ if (state === "released") {
3410
+ this.releaseConversationRun(run.id);
3411
+ return;
3412
+ }
3413
+ const conversationId = this.toFoundryRun(run).conversationId;
3414
+ if (conversationId) this.occupyConversation(conversationId, run.id);
3415
+ }
3416
+ releaseConversationRun(runId) {
3417
+ const conversationId = this.runConversations.get(runId);
3418
+ if (!conversationId) return;
3419
+ this.runConversations.delete(runId);
3420
+ const runs = this.conversationRuns.get(conversationId);
3421
+ runs?.delete(runId);
3422
+ if (runs && runs.size === 0) this.conversationRuns.delete(conversationId);
3423
+ void this.inConversation(conversationId, async () => {
3424
+ if (this.conversationListeners.get(conversationId) === runId) {
3425
+ this.conversationListeners.delete(conversationId);
3426
+ await this.reclaimMailbox(conversationId);
3427
+ }
3428
+ await this.flushHeldDeliveries(conversationId);
3429
+ }).catch((cause) => this.reportDeliveryFailure(conversationId, cause));
3430
+ }
3431
+ trackConversationListener(run, state) {
3432
+ const conversationId = this.toFoundryRun(run).conversationId;
3433
+ if (!conversationId) return;
3434
+ void this.inConversation(conversationId, async () => {
3435
+ if (state === "on") {
3436
+ this.conversationListeners.set(conversationId, run.id);
3437
+ const held = this.heldDeliveries.get(conversationId);
3438
+ if (held) {
3439
+ this.heldDeliveries.delete(conversationId);
3440
+ for (const delivery of held.deliveries) {
3441
+ await writeMailboxDelivery(this.mailboxDirectory, conversationId, delivery);
3442
+ }
3443
+ await this.markHandedOver(held.deliveries, run.id);
3444
+ }
3445
+ return;
3446
+ }
3447
+ if (this.conversationListeners.get(conversationId) !== run.id) return;
3448
+ this.conversationListeners.delete(conversationId);
3449
+ await this.reclaimMailbox(conversationId);
3450
+ await this.flushHeldDeliveries(conversationId);
3451
+ }).catch((cause) => this.reportDeliveryFailure(conversationId, cause));
3452
+ }
3453
+ /** Take back deliveries a listener did not read, to deliver as a run. */
3454
+ async reclaimMailbox(conversationId) {
3455
+ const deliveries = await drainMailbox(this.mailboxDirectory, conversationId);
3456
+ if (deliveries.length === 0) return;
3457
+ const target = await this.deliveryTargetFor(conversationId);
3458
+ if (!target) return;
3459
+ for (const delivery of deliveries) {
3460
+ if (delivery.kind === "transmission") await this.assignPendingInbound(delivery.pendingId, void 0);
3461
+ }
3462
+ this.holdDeliveries(target, deliveries);
3463
+ }
3464
+ async deliveryTargetFor(conversationId) {
3465
+ const conversation = await Effect5.runPromise(this.data.getConversation(conversationId));
3466
+ if (!conversation) return null;
3467
+ const agent = await Effect5.runPromise(this.data.getAgent(conversation.agentId));
3468
+ if (!agent) return null;
3469
+ return {
3470
+ definitionId: agent.definitionId,
3471
+ agentId: agent.id,
3472
+ conversationId,
3473
+ workspaceId: conversation.workspaceId
3474
+ };
3475
+ }
3476
+ holdDeliveries(target, deliveries) {
3477
+ const held = this.heldDeliveries.get(target.conversationId);
3478
+ if (held) held.deliveries.push(...deliveries);
3479
+ else this.heldDeliveries.set(target.conversationId, { target, deliveries: [...deliveries] });
3480
+ }
3481
+ deliver(target, deliveries) {
3482
+ return this.inConversation(target.conversationId, async () => {
3483
+ if (this.conversationListeners.has(target.conversationId)) {
3484
+ for (const delivery of deliveries) {
3485
+ await writeMailboxDelivery(this.mailboxDirectory, target.conversationId, delivery);
3486
+ }
3487
+ await this.markHandedOver(deliveries, this.conversationListeners.get(target.conversationId));
3488
+ this.observability.append({
3489
+ type: "delegation.delivered",
3490
+ category: "system",
3491
+ agent: target.definitionId,
3492
+ runId: this.conversationListeners.get(target.conversationId),
3493
+ data: { conversationId: target.conversationId, mode: "live", count: deliveries.length }
3494
+ });
3495
+ return;
3496
+ }
3497
+ this.holdDeliveries(target, deliveries);
3498
+ await this.flushHeldDeliveries(target.conversationId);
3499
+ });
3500
+ }
3501
+ /** Start one run with everything held for a conversation, once nothing else holds it. */
3502
+ async flushHeldDeliveries(conversationId) {
3503
+ if (!this.started) return;
3504
+ if (this.gate.busy(conversationId)) return;
3505
+ if (this.conversationListeners.has(conversationId)) return;
3506
+ const held = this.heldDeliveries.get(conversationId);
3507
+ if (!held || held.deliveries.length === 0) return;
3508
+ this.heldDeliveries.delete(conversationId);
3509
+ const { target, deliveries } = held;
3510
+ const runId = await this.enqueueCoreRequest(target.definitionId, {
3511
+ agentId: target.agentId,
3512
+ conversationId,
3513
+ workspaceId: target.workspaceId,
3514
+ message: renderDeliveries(deliveries),
3515
+ payload: { deliveries },
3516
+ source: deliverySource(deliveries)
3517
+ });
3518
+ this.occupyConversation(conversationId, runId);
3519
+ await this.markHandedOver(deliveries, runId);
3520
+ this.observability.append({
3521
+ type: "delegation.delivered",
3522
+ category: "system",
3523
+ agent: target.definitionId,
3524
+ runId,
3525
+ data: { conversationId, mode: "run", count: deliveries.length }
3526
+ });
3527
+ }
3528
+ /** Clear the bookkeeping that lets a restart hand these deliveries over again. */
3529
+ async markHandedOver(deliveries, runId) {
3530
+ for (const delivery of deliveries) {
3531
+ if (delivery.kind === "transmission") {
3532
+ await this.assignPendingInbound(delivery.pendingId, runId);
3533
+ } else if (delivery.kind === "reply") {
3534
+ await this.updateDelegation(delivery.delegationId, (current) => {
3535
+ const pending = [...current.pendingReplies ?? []];
3536
+ const index = pending.indexOf(delivery.message);
3537
+ if (index >= 0) pending.splice(index, 1);
3538
+ return { pendingReplies: pending.length > 0 ? pending : void 0 };
3539
+ });
3540
+ } else {
3541
+ await this.updateDelegation(delivery.delegationId, (current) => current.undelivered === delivery.kind ? { undelivered: void 0 } : {});
3542
+ }
3543
+ }
3544
+ }
3545
+ /** Record which run is handling a pending inbound event (none while it waits). */
3546
+ async assignPendingInbound(pendingId, runId) {
3547
+ for (const ids of this.pendingInboundByRun.values()) ids.delete(pendingId);
3548
+ if (runId) {
3549
+ const ids = this.pendingInboundByRun.get(runId) ?? /* @__PURE__ */ new Set();
3550
+ ids.add(pendingId);
3551
+ this.pendingInboundByRun.set(runId, ids);
3552
+ }
3553
+ if (this.data.putPendingInbound && this.data.listPendingInbound) {
3554
+ const record = (await Effect5.runPromise(this.data.listPendingInbound())).find((item) => item.id === pendingId);
3555
+ if (record) {
3556
+ const { runId: _previous, ...rest } = record;
3557
+ await Effect5.runPromise(this.data.putPendingInbound(runId ? { ...rest, runId } : rest));
3558
+ }
3559
+ }
3560
+ if (runId && this.settledRuns.has(runId)) await this.finishPendingInbound(runId);
3561
+ }
3562
+ /** The run settled: the inbound events it was handling are done with. */
3563
+ async finishPendingInbound(runId) {
3564
+ const ids = this.pendingInboundByRun.get(runId);
3565
+ if (!ids) return;
3566
+ this.pendingInboundByRun.delete(runId);
3567
+ if (this.stopping || !this.data.deletePendingInbound) return;
3568
+ for (const id2 of ids) await Effect5.runPromise(this.data.deletePendingInbound(id2));
3569
+ }
3570
+ /**
3571
+ * Hand an inbound event to one agent's conversation. A free conversation
3572
+ * starts a run for it. A busy one gets it as a delivery: it joins the
3573
+ * running turn at its next tool step, or waits and starts the
3574
+ * conversation's next run with anything else that arrived meanwhile.
3575
+ * Returns the run handling it now, when there is one.
3576
+ */
3577
+ async admitInbound(record) {
3578
+ if (this.data.putPendingInbound) await Effect5.runPromise(this.data.putPendingInbound(record));
3579
+ const { request } = record;
3580
+ if (!this.gate.busy(request.conversationId)) {
3581
+ const run = await this.request(record.definitionId, request);
3582
+ await this.assignPendingInbound(record.id, run.id);
3583
+ return run;
3584
+ }
3585
+ const source = request.source;
3586
+ await this.deliver(
3587
+ {
3588
+ definitionId: record.definitionId,
3589
+ agentId: request.agentId,
3590
+ conversationId: request.conversationId,
3591
+ workspaceId: request.workspaceId
3592
+ },
3593
+ [{
3594
+ kind: "transmission",
3595
+ pendingId: record.id,
3596
+ routeId: source?.id ?? "",
3597
+ eventId: source?.eventId ?? "",
3598
+ message: typeof request.message === "string" ? request.message : JSON.stringify(request.message)
3599
+ }]
3600
+ );
3601
+ const active = this.gate.activeRun(request.conversationId);
3602
+ return active ? this.getRun(active) : null;
3603
+ }
3604
+ /** After a restart, deliver the inbound events no run had finished with. */
3605
+ async redeliverInbound() {
3606
+ if (!this.data.listPendingInbound) return;
3607
+ const pending = [...await Effect5.runPromise(this.data.listPendingInbound())].sort((left, right) => left.createdAt.localeCompare(right.createdAt));
3608
+ for (const record of pending) {
3609
+ const { runId: _lost, ...waiting } = record;
3610
+ await this.admitInbound(waiting);
3611
+ }
3612
+ }
3613
+ /** After a restart, hand over whatever was waiting when the runtime stopped. */
3614
+ async redeliverDelegations() {
3615
+ for (const delegation of await this.listDelegations()) {
3616
+ const update = undeliveredUpdate(delegation);
3617
+ if (update) await this.deliver(this.delegatorTarget(delegation), [update]);
3618
+ if (delegation.pendingReplies?.length) {
3619
+ await this.deliver(
3620
+ {
3621
+ definitionId: delegation.to,
3622
+ agentId: delegation.workerAgentId,
3623
+ conversationId: delegation.id,
3624
+ workspaceId: delegation.workspaceId
3625
+ },
3626
+ delegation.pendingReplies.map((message) => ({
3627
+ kind: "reply",
3628
+ delegationId: delegation.id,
3629
+ from: delegation.from.definitionId,
3630
+ message
3631
+ }))
3632
+ );
3633
+ }
3634
+ }
3635
+ }
3636
+ reportDeliveryFailure(conversationId, cause) {
3637
+ this.observability.append({
3638
+ type: "delegation.delivery.failed",
3639
+ category: "system",
3640
+ data: { conversationId, error: cause instanceof Error ? cause.message : String(cause) }
3641
+ });
3642
+ }
3643
+ async loadDelegation(id2) {
3644
+ const conversation = await Effect5.runPromise(this.data.getConversation(id2));
3645
+ return delegationFromContext(conversation?.context) ?? null;
3646
+ }
3647
+ updateDelegation(id2, change) {
3648
+ return this.inConversation(`record:${id2}`, async () => {
3649
+ const conversation = await Effect5.runPromise(this.data.getConversation(id2));
3650
+ const current = delegationFromContext(conversation?.context);
3651
+ if (!conversation || !current) return null;
3652
+ const patch = typeof change === "function" ? change(current) : change;
3653
+ if (Object.keys(patch).length === 0) return current;
3654
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3655
+ const merged = { ...current, ...patch, updatedAt: now };
3656
+ for (const key of Object.keys(merged)) if (merged[key] === void 0) delete merged[key];
3657
+ const next = Object.freeze(merged);
3658
+ await Effect5.runPromise(this.data.putConversation(Object.freeze({
3659
+ ...conversation,
3660
+ context: Object.freeze({ ...conversation.context, delegation: next }),
3661
+ updatedAt: now
3662
+ })));
3663
+ return next;
3664
+ });
3665
+ }
3666
+ delegatorTarget(delegation) {
3667
+ return {
3668
+ definitionId: delegation.from.definitionId,
3669
+ agentId: delegation.from.agentId,
3670
+ conversationId: delegation.from.conversationId,
3671
+ workspaceId: delegation.workspaceId
3672
+ };
3673
+ }
3674
+ async executeDelegationCommand(command, parentRunId) {
3675
+ if (!isDelegationId(command.delegationId)) {
3676
+ throw new Error(`"${command.delegationId}" is not a delegation id.`);
3677
+ }
3678
+ if (command.type === "delegate") {
3679
+ await this.startDelegation(command, parentRunId);
3680
+ return;
3681
+ }
3682
+ const delegation = await this.loadDelegation(command.delegationId);
3683
+ if (command.type === "delegate.reply") {
3684
+ if (!delegation || delegation.from.agentId !== command.agentId || delegation.from.conversationId !== command.conversationId) {
3685
+ throw new Error(`Delegation "${command.delegationId}" was not started by this conversation.`);
3686
+ }
3687
+ await this.updateDelegation(delegation.id, (current) => ({
3688
+ status: "working",
3689
+ question: void 0,
3690
+ ...current.undelivered === "question" ? { undelivered: void 0 } : {},
3691
+ pendingReplies: [...current.pendingReplies ?? [], command.message]
3692
+ }));
3693
+ await this.deliver(
3694
+ {
3695
+ definitionId: delegation.to,
3696
+ agentId: delegation.workerAgentId,
3697
+ conversationId: delegation.id,
3698
+ workspaceId: delegation.workspaceId
3699
+ },
3700
+ [{ kind: "reply", delegationId: delegation.id, from: command.definitionId, message: command.message }]
3701
+ );
3702
+ this.observability.append({
3703
+ type: "delegation.replied",
3704
+ category: "system",
3705
+ agent: command.definitionId,
3706
+ runId: parentRunId,
3707
+ data: { delegationId: delegation.id, to: delegation.to }
3708
+ });
3709
+ return;
3710
+ }
3711
+ if (!delegation || delegation.workerAgentId !== command.agentId || delegation.id !== command.conversationId) {
3712
+ throw new Error(`Only the worker on delegation "${command.delegationId}" can ask about it.`);
3713
+ }
3714
+ await this.updateDelegation(delegation.id, {
3715
+ status: "waiting",
3716
+ question: command.question,
3717
+ undelivered: "question"
3718
+ });
3719
+ await this.deliver(this.delegatorTarget(delegation), [{
3720
+ kind: "question",
3721
+ delegationId: delegation.id,
3722
+ agent: delegation.to,
3723
+ task: delegation.task,
3724
+ question: command.question
3725
+ }]);
3726
+ this.observability.append({
3727
+ type: "delegation.question",
3728
+ category: "system",
3729
+ agent: delegation.to,
3730
+ runId: parentRunId,
3731
+ data: { delegationId: delegation.id, question: command.question }
3732
+ });
3733
+ }
3734
+ async startDelegation(command, parentRunId) {
3735
+ const from = {
3736
+ definitionId: command.definitionId,
3737
+ agentId: command.agentId,
3738
+ conversationId: command.conversationId,
3739
+ workspaceId: command.workspaceId
3740
+ };
3741
+ if (!this.byRoute.has(command.to)) {
3742
+ await this.deliver(from, [{
3743
+ kind: "failed",
3744
+ delegationId: command.delegationId,
3745
+ agent: command.to,
3746
+ task: command.task,
3747
+ error: `There is no "${command.to}" agent in this project.`
3748
+ }]);
3749
+ return;
3750
+ }
3751
+ const delegator = await Effect5.runPromise(this.data.getAgent(command.agentId));
3752
+ if (!delegator || delegator.workspaceId !== command.workspaceId) {
3753
+ throw new Error("A delegation must come from an agent instance in its workspace.");
3754
+ }
3755
+ const workerId = workerAgentId(command.agentId, command.to);
3756
+ const worker = await Effect5.runPromise(this.data.getAgent(workerId)) ?? await this.createAgent(command.to, {
3757
+ id: workerId,
3758
+ workspaceId: command.workspaceId,
3759
+ context: {
3760
+ ...delegator.context,
3761
+ delegatedBy: { agentId: command.agentId, definitionId: command.definitionId }
3762
+ }
3763
+ });
3764
+ if (worker.definitionId !== command.to || worker.workspaceId !== command.workspaceId) {
3765
+ throw new Error(`Agent instance "${workerId}" is not a ${command.to} worker in this workspace.`);
3766
+ }
3767
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3768
+ const delegation = Object.freeze({
3769
+ id: command.delegationId,
3770
+ to: command.to,
3771
+ workerAgentId: workerId,
3772
+ workspaceId: command.workspaceId,
3773
+ from: Object.freeze({
3774
+ definitionId: command.definitionId,
3775
+ agentId: command.agentId,
3776
+ conversationId: command.conversationId,
3777
+ runId: parentRunId
3778
+ }),
3779
+ task: command.task,
3780
+ status: "working",
3781
+ createdAt: now,
3782
+ updatedAt: now
3783
+ });
3784
+ const title = command.task.replace(/\s+/g, " ").trim();
3785
+ await this.createConversation(workerId, {
3786
+ id: delegation.id,
3787
+ workspaceId: command.workspaceId,
3788
+ title: title.length > 80 ? `${title.slice(0, 79)}\u2026` : title,
3789
+ context: { delegation }
3790
+ });
3791
+ const runId = await this.enqueueCoreRequest(command.to, {
3792
+ agentId: workerId,
3793
+ conversationId: delegation.id,
3794
+ workspaceId: command.workspaceId,
3795
+ message: renderDelegatedTask({ delegationId: delegation.id, from: command.definitionId, task: command.task }),
3796
+ payload: { delegation },
3797
+ source: { kind: "delegation", id: delegation.id }
3798
+ });
3799
+ this.occupyConversation(delegation.id, runId);
3800
+ this.observability.append({
3801
+ type: "delegation.started",
3802
+ category: "system",
3803
+ agent: command.definitionId,
3804
+ runId: parentRunId,
3805
+ data: { delegationId: delegation.id, to: command.to, workerAgentId: workerId, workerRunId: runId }
3806
+ });
3807
+ }
3808
+ /** Report a worker's finished run back to whoever delegated to it. */
3809
+ async handleRunSettled(event) {
3810
+ this.releaseConversationRun(event.run.id);
3811
+ void this.waitForRunProcessRelease(this.toFoundryRun(event.run), event.route).finally(() => this.gate.settled(event.run.id));
3812
+ this.settledRuns.add(event.run.id);
3813
+ if (this.settledRuns.size > 1e3) this.settledRuns.delete(this.settledRuns.values().next().value);
3814
+ await this.finishPendingInbound(event.run.id).catch((cause) => this.reportDeliveryFailure(this.toFoundryRun(event.run).conversationId ?? "settle", cause));
3815
+ const steered = this.steeredRuns.delete(event.run.id);
3816
+ const run = this.toFoundryRun(event.run);
3817
+ if (!run.conversationId || !isDelegationId(run.conversationId)) return;
3818
+ const delegation = await this.loadDelegation(run.conversationId);
3819
+ if (!delegation || run.agentId !== delegation.workerAgentId) return;
3820
+ if (event.status === "completed") {
3821
+ const output = parseJson(event.output);
3822
+ if (output?.status === "suspended") return;
3823
+ const result = deliveryText(output?.value);
3824
+ await this.updateDelegation(delegation.id, {
3825
+ status: "completed",
3826
+ result,
3827
+ question: void 0,
3828
+ undelivered: "result"
3829
+ });
3830
+ await this.deliver(this.delegatorTarget(delegation), [{
3831
+ kind: "result",
3832
+ delegationId: delegation.id,
3833
+ agent: delegation.to,
3834
+ task: delegation.task,
3835
+ result
3836
+ }]);
3837
+ this.observability.append({
3838
+ type: "delegation.completed",
3839
+ category: "system",
3840
+ agent: delegation.to,
3841
+ runId: event.run.id,
3842
+ data: { delegationId: delegation.id }
3843
+ });
3844
+ return;
3845
+ }
3846
+ if (event.status === "cancelled" && steered) return;
3847
+ const error = event.status === "cancelled" ? "The work was cancelled." : event.error ?? "The run failed.";
3848
+ await this.updateDelegation(delegation.id, {
3849
+ status: event.status === "cancelled" ? "cancelled" : "failed",
3850
+ error,
3851
+ undelivered: "failed"
3852
+ });
3853
+ await this.deliver(this.delegatorTarget(delegation), [{
3854
+ kind: "failed",
3855
+ delegationId: delegation.id,
3856
+ agent: delegation.to,
3857
+ task: delegation.task,
3858
+ error
3859
+ }]);
3860
+ this.observability.append({
3861
+ type: event.status === "cancelled" ? "delegation.cancelled" : "delegation.failed",
3862
+ category: "system",
3863
+ agent: delegation.to,
3864
+ runId: event.run.id,
3865
+ data: { delegationId: delegation.id, error }
3866
+ });
3867
+ }
3022
3868
  async enqueueCoreRequest(definitionId, request) {
3023
3869
  const discovered = this.byRoute.get(definitionId);
3024
3870
  if (!discovered) throw new Error(`Foundry agent definition "${definitionId}" was not found.`);
3025
3871
  const agent = await Effect5.runPromise(this.data.getAgent(request.agentId));
3026
3872
  const conversation = await Effect5.runPromise(this.data.getConversation(request.conversationId));
3027
3873
  if (!agent || !conversation) throw new Error("Core command references an unknown agent instance or conversation.");
3028
- return this.signalRunner.triggerSignal(
3029
- discovered.executionName,
3030
- await this.executionEnvelope(request)
3874
+ return this.admitRun(discovered.executionName, request);
3875
+ }
3876
+ /**
3877
+ * Create the run for a request through its conversation's gate: it starts
3878
+ * at once when the conversation is free and waits parked, holding no
3879
+ * concurrency slot, behind the run that holds it otherwise. A parked run
3880
+ * starts from an envelope built when its turn comes, not when it was asked
3881
+ * for, so it sees the conversation as the runs ahead of it left it.
3882
+ */
3883
+ admitRun(executionName, request, options = {}) {
3884
+ return this.gate.admit(
3885
+ request.conversationId,
3886
+ async (parked) => this.signalRunner.triggerSignal(
3887
+ executionName,
3888
+ await this.executionEnvelope(request, { leased: true }),
3889
+ { parked }
3890
+ ),
3891
+ async (runId) => this.signalRunner.releaseRun(
3892
+ runId,
3893
+ await this.executionEnvelope(request, { leased: true })
3894
+ ),
3895
+ options
3031
3896
  );
3032
3897
  }
3033
3898
  withActivationTransition(work) {
@@ -3043,6 +3908,10 @@ var FoundryRuntime = class _FoundryRuntime {
3043
3908
  return this.executeCoreCommandUnlocked(command, parentRunId);
3044
3909
  }
3045
3910
  async executeCoreCommandUnlocked(command, parentRunId) {
3911
+ if (command.type === "delegate" || command.type === "delegate.reply" || command.type === "delegate.ask") {
3912
+ await this.executeDelegationCommand(command, parentRunId);
3913
+ return;
3914
+ }
3046
3915
  if (command.type === "transmit") {
3047
3916
  const request2 = await getFoundryCoreCommandRequest(
3048
3917
  this.coreCommandDirectory,
@@ -3580,12 +4449,21 @@ var FoundryRuntime = class _FoundryRuntime {
3580
4449
  ...signal ? { signal } : {}
3581
4450
  });
3582
4451
  }
3583
- async executionEnvelope(request) {
4452
+ async executionEnvelope(request, options = {}) {
3584
4453
  const agent = await Effect5.runPromise(this.data.getAgent(request.agentId));
3585
4454
  const conversation = await Effect5.runPromise(this.data.getConversation(request.conversationId));
3586
4455
  if (!agent || !conversation) throw new Error("Cannot schedule an unknown agent instance or conversation.");
3587
4456
  const activations = (await Effect5.runPromise(this.data.listActivations(request.workspaceId))).filter((activation) => activation.agentId === request.agentId);
3588
- return { [FOUNDRY_EXECUTION_MARKER]: true, request, agent, conversation, activations };
4457
+ const delegations = await this.openDelegationsFrom(request.agentId, request.conversationId);
4458
+ return {
4459
+ [FOUNDRY_EXECUTION_MARKER]: true,
4460
+ request,
4461
+ agent,
4462
+ conversation,
4463
+ activations,
4464
+ delegations,
4465
+ ...options.leased ? { conversationLease: true } : {}
4466
+ };
3589
4467
  }
3590
4468
  toFoundryRun(run) {
3591
4469
  const storedInput = parseJson(run.input);
@@ -3771,7 +4649,8 @@ function skeleton(rows){
3771
4649
  async function api(url,options){
3772
4650
  const response=await fetch(url,options);let body;
3773
4651
  try{body=await response.json()}catch{body={error:"The runtime returned an unreadable response."}}
3774
- if(!response.ok)throw new Error(body.error||("Request failed ("+response.status+")"));return body;
4652
+ /* /health answers 503 with the same body when a subsystem is down; the header shows it. */
4653
+ if(!response.ok&&!(url==="/health"&&response.status===503))throw new Error(body.error||("Request failed ("+response.status+")"));return body;
3775
4654
  }
3776
4655
  function toast(message){const node=$("toast");node.textContent=message;node.classList.add("show");setTimeout(()=>node.classList.remove("show"),2400)}
3777
4656
  function route(){const parts=location.pathname.split("/").filter(Boolean).map(decodeURIComponent);return{parts,section:parts[0]||"overview",id:parts.slice(1).join("/")}}
@@ -3843,6 +4722,7 @@ function explainRun(run){
3843
4722
  if(source==="activation")return"Started by a scheduled activation or wake-up.";
3844
4723
  if(source==="spawn")return"Spawned by another agent run.";
3845
4724
  if(source==="background")return"Continued as background work.";
4725
+ if(source==="delegation")return"Delegated work, or a delegation result or question coming back.";
3846
4726
  if(run.status==="completed")return"The agent completed the requested work.";
3847
4727
  return"The agent is processing a direct message.";
3848
4728
  }
@@ -4772,11 +5652,15 @@ function installationFrom(value) {
4772
5652
  if (typeof body.id !== "string" || !body.id) {
4773
5653
  throw new RequestError(400, "id is required.");
4774
5654
  }
5655
+ if (body.accountId !== void 0 && (typeof body.accountId !== "string" || !body.accountId)) {
5656
+ throw new RequestError(400, "accountId must be a non-empty string.");
5657
+ }
4775
5658
  return {
4776
5659
  agentId: body.agentId,
4777
5660
  installation: {
4778
5661
  kind: body.kind,
4779
5662
  id: body.id,
5663
+ ...body.accountId !== void 0 ? { accountId: body.accountId } : {},
4780
5664
  ...body.config !== void 0 ? { config: body.config } : {}
4781
5665
  }
4782
5666
  };
@@ -5097,12 +5981,13 @@ var FoundryServer = class {
5097
5981
  return;
5098
5982
  }
5099
5983
  if (method === "GET" && url.pathname === "/health") {
5100
- json(response, 200, await this.runtime.health());
5984
+ const health = await this.runtime.health();
5985
+ json(response, health.ok ? 200 : 503, health);
5101
5986
  return;
5102
5987
  }
5103
5988
  if (method === "GET" && url.pathname === "/health/detailed") {
5104
5989
  const health = await this.runtime.health();
5105
- json(response, 200, {
5990
+ json(response, health.ok ? 200 : 503, {
5106
5991
  ...health,
5107
5992
  connections: this.runtime.listApplicationConnections(),
5108
5993
  runs: await this.runtime.listRuns()