glove-foundry 0.5.2 → 0.6.1
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.
- package/README.md +77 -0
- package/dist/chunk-B36BGF5R.js +530 -0
- package/dist/{chunk-PVOKR4CN.js → chunk-K2EU63MB.js} +5 -0
- package/dist/{chunk-6Q2LGPSC.js → chunk-OBTOFA7W.js} +15 -1
- package/dist/{chunk-NHV64WNO.js → chunk-RSU7NEDK.js} +9 -3
- package/dist/{chunk-MABLKZVO.js → chunk-TFGETZYH.js} +188 -10
- package/dist/{chunk-D2AHSYOB.js → chunk-X6EWEWWM.js} +875 -53
- package/dist/cli.js +4 -3
- package/dist/client-DWPYe_Nc.d.ts +888 -0
- package/dist/client.d.ts +2 -1
- package/dist/{client-CLTds1uV.d.ts → definition-A8o11aez.d.ts} +193 -822
- package/dist/execution-agent.js +5 -4
- package/dist/execution-daemon.js +37 -2
- package/dist/execution-loader.js +5 -4
- package/dist/index.d.ts +8 -3
- package/dist/index.js +29 -4
- package/dist/voice.d.ts +168 -0
- package/dist/voice.js +348 -0
- package/docs/building-with-foundry.md +28 -19
- package/docs/durable-execution.md +56 -0
- package/package.json +16 -9
|
@@ -35,7 +35,22 @@ import {
|
|
|
35
35
|
resolveFoundryApproval,
|
|
36
36
|
settleFoundryCoreCommandRequest,
|
|
37
37
|
transmissionPredicate
|
|
38
|
-
} from "./chunk-
|
|
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";
|
|
39
54
|
import {
|
|
40
55
|
EMPTY_NATIVE_REGISTRY,
|
|
41
56
|
FOUNDRY_APPLICATION_ENV,
|
|
@@ -45,7 +60,7 @@ import {
|
|
|
45
60
|
FOUNDRY_RUN_PROCESS_EVENT,
|
|
46
61
|
FOUNDRY_SUBSCRIBER_BRAND,
|
|
47
62
|
bindFileIdentity
|
|
48
|
-
} from "./chunk-
|
|
63
|
+
} from "./chunk-K2EU63MB.js";
|
|
49
64
|
|
|
50
65
|
// src/codegen.ts
|
|
51
66
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
@@ -724,12 +739,16 @@ function encodedAgentEvent(message) {
|
|
|
724
739
|
}
|
|
725
740
|
}
|
|
726
741
|
var FoundryObserver = class {
|
|
727
|
-
constructor(adapter, routeForSignalName, onAgentEvent) {
|
|
742
|
+
constructor(adapter, routeForSignalName, onAgentEvent, onRunSettled) {
|
|
728
743
|
this.adapter = adapter;
|
|
729
744
|
this.routeForSignalName = routeForSignalName;
|
|
730
745
|
this.onAgentEvent = onAgentEvent;
|
|
746
|
+
this.onRunSettled = onRunSettled;
|
|
731
747
|
}
|
|
732
748
|
logBuffers = /* @__PURE__ */ new Map();
|
|
749
|
+
settled(run, status, detail = {}) {
|
|
750
|
+
this.onRunSettled?.({ route: this.route(run.signalName), run, status, ...detail });
|
|
751
|
+
}
|
|
733
752
|
route(name) {
|
|
734
753
|
return this.routeForSignalName(name);
|
|
735
754
|
}
|
|
@@ -759,6 +778,7 @@ var FoundryObserver = class {
|
|
|
759
778
|
onRunCompleted(event) {
|
|
760
779
|
this.flushRunLogs(event.run);
|
|
761
780
|
this.runEvent("run.completed", event.run, { output: event.output });
|
|
781
|
+
this.settled(event.run, "completed", event.output !== void 0 ? { output: event.output } : {});
|
|
762
782
|
}
|
|
763
783
|
onRunTimeout({ run }) {
|
|
764
784
|
this.runEvent("run.timeout", run);
|
|
@@ -772,10 +792,12 @@ var FoundryObserver = class {
|
|
|
772
792
|
onRunFailed(event) {
|
|
773
793
|
this.flushRunLogs(event.run);
|
|
774
794
|
this.runEvent("run.failed", event.run, { error: event.error });
|
|
795
|
+
this.settled(event.run, "failed", event.error !== void 0 ? { error: event.error } : {});
|
|
775
796
|
}
|
|
776
797
|
onRunCancelled({ run }) {
|
|
777
798
|
this.flushRunLogs(run);
|
|
778
799
|
this.runEvent("run.cancelled", run);
|
|
800
|
+
this.settled(run, "cancelled");
|
|
779
801
|
}
|
|
780
802
|
onRunSkipped(event) {
|
|
781
803
|
this.runEvent("run.skipped", event.run, { reason: event.reason });
|
|
@@ -986,8 +1008,12 @@ var FoundryExecutionBackend = class {
|
|
|
986
1008
|
})();
|
|
987
1009
|
return this.stopping;
|
|
988
1010
|
}
|
|
989
|
-
triggerSignal(name, input) {
|
|
990
|
-
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 });
|
|
991
1017
|
}
|
|
992
1018
|
getRun(id2) {
|
|
993
1019
|
return this.request({ method: "get", id: id2 });
|
|
@@ -1025,6 +1051,151 @@ import {
|
|
|
1025
1051
|
nextCronOccurrence
|
|
1026
1052
|
} from "station-schedules";
|
|
1027
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
|
+
|
|
1028
1199
|
// src/connection-supervisor.ts
|
|
1029
1200
|
import { Effect as Effect4 } from "effect";
|
|
1030
1201
|
function safeError(cause) {
|
|
@@ -1434,6 +1605,23 @@ var FoundryRuntimeError = class extends Schema3.TaggedError(
|
|
|
1434
1605
|
message: Schema3.String
|
|
1435
1606
|
}) {
|
|
1436
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
|
+
}
|
|
1437
1625
|
function parseJson(value) {
|
|
1438
1626
|
if (value === void 0) return void 0;
|
|
1439
1627
|
try {
|
|
@@ -1497,7 +1685,41 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1497
1685
|
"glove-foundry-core-commands",
|
|
1498
1686
|
randomUUID2()
|
|
1499
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();
|
|
1500
1721
|
started = false;
|
|
1722
|
+
stopping = false;
|
|
1501
1723
|
disposed = false;
|
|
1502
1724
|
constructor(options) {
|
|
1503
1725
|
this.rootDir = options.rootDir;
|
|
@@ -1562,7 +1784,22 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1562
1784
|
(event) => {
|
|
1563
1785
|
if (event.type === FOUNDRY_RUN_PROCESS_EVENT) {
|
|
1564
1786
|
const state = event.data?.state;
|
|
1565
|
-
if (state === "acquired" || state === "released")
|
|
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));
|
|
1566
1803
|
return;
|
|
1567
1804
|
}
|
|
1568
1805
|
if (event.type === FOUNDRY_CORE_COMMAND_EVENT) {
|
|
@@ -1576,6 +1813,17 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1576
1813
|
});
|
|
1577
1814
|
});
|
|
1578
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
|
+
});
|
|
1579
1827
|
}
|
|
1580
1828
|
);
|
|
1581
1829
|
this.connectionSupervisor = new ApplicationConnectionSupervisor({
|
|
@@ -1630,6 +1878,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1630
1878
|
env: {
|
|
1631
1879
|
[FOUNDRY_APPROVAL_DIRECTORY_ENV]: this.approvalDirectory,
|
|
1632
1880
|
[FOUNDRY_CORE_COMMAND_DIRECTORY_ENV]: this.coreCommandDirectory,
|
|
1881
|
+
[FOUNDRY_MAILBOX_DIRECTORY_ENV]: this.mailboxDirectory,
|
|
1633
1882
|
...this.applicationFilePath ? { [FOUNDRY_APPLICATION_ENV]: this.applicationFilePath } : {}
|
|
1634
1883
|
}
|
|
1635
1884
|
});
|
|
@@ -1680,7 +1929,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1680
1929
|
try {
|
|
1681
1930
|
await Promise.all([
|
|
1682
1931
|
mkdir2(this.approvalDirectory, { recursive: true, mode: 448 }),
|
|
1683
|
-
mkdir2(this.coreCommandDirectory, { recursive: true, mode: 448 })
|
|
1932
|
+
mkdir2(this.coreCommandDirectory, { recursive: true, mode: 448 }),
|
|
1933
|
+
mkdir2(this.mailboxDirectory, { recursive: true, mode: 448 })
|
|
1684
1934
|
]);
|
|
1685
1935
|
await this.seedTopology();
|
|
1686
1936
|
for (const instance of await this.listAgentInstances()) {
|
|
@@ -1705,6 +1955,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1705
1955
|
await this.reconstructActivations();
|
|
1706
1956
|
this.runInBackground("signal", this.signalRunner.start());
|
|
1707
1957
|
await this.reconcileApplicationConnections();
|
|
1958
|
+
void this.redeliverDelegations().catch((cause) => this.reportDeliveryFailure("startup", cause));
|
|
1959
|
+
void this.redeliverInbound().catch((cause) => this.reportDeliveryFailure("startup", cause));
|
|
1708
1960
|
} catch (cause) {
|
|
1709
1961
|
try {
|
|
1710
1962
|
await this.stop();
|
|
@@ -1724,11 +1976,13 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1724
1976
|
await this.services.dispose();
|
|
1725
1977
|
await Promise.all([
|
|
1726
1978
|
rm2(this.approvalDirectory, { recursive: true, force: true }),
|
|
1727
|
-
rm2(this.coreCommandDirectory, { recursive: true, force: true })
|
|
1979
|
+
rm2(this.coreCommandDirectory, { recursive: true, force: true }),
|
|
1980
|
+
rm2(this.mailboxDirectory, { recursive: true, force: true })
|
|
1728
1981
|
]);
|
|
1729
1982
|
this.disposed = true;
|
|
1730
1983
|
return;
|
|
1731
1984
|
}
|
|
1985
|
+
this.stopping = true;
|
|
1732
1986
|
for (const timer of this.activationTimers.values()) clearTimeout(timer);
|
|
1733
1987
|
this.activationTimers.clear();
|
|
1734
1988
|
this.activationDispatches.clear();
|
|
@@ -1741,7 +1995,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1741
1995
|
await this.services.dispose();
|
|
1742
1996
|
await Promise.all([
|
|
1743
1997
|
rm2(this.approvalDirectory, { recursive: true, force: true }),
|
|
1744
|
-
rm2(this.coreCommandDirectory, { recursive: true, force: true })
|
|
1998
|
+
rm2(this.coreCommandDirectory, { recursive: true, force: true }),
|
|
1999
|
+
rm2(this.mailboxDirectory, { recursive: true, force: true })
|
|
1745
2000
|
]);
|
|
1746
2001
|
this.started = false;
|
|
1747
2002
|
this.disposed = true;
|
|
@@ -1751,7 +2006,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1751
2006
|
stop() {
|
|
1752
2007
|
return Effect5.runPromise(this.stopEffect());
|
|
1753
2008
|
}
|
|
1754
|
-
requestEffect(route, request) {
|
|
2009
|
+
requestEffect(route, request, options = {}) {
|
|
1755
2010
|
return promiseEffect("agent.request", async () => {
|
|
1756
2011
|
if (!this.started) throw new Error("Foundry runtime is not started.");
|
|
1757
2012
|
const discovered = this.byRoute.get(route);
|
|
@@ -1772,10 +2027,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1772
2027
|
...conversation,
|
|
1773
2028
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1774
2029
|
})));
|
|
1775
|
-
const runId = await this.
|
|
1776
|
-
discovered.executionName,
|
|
1777
|
-
await this.executionEnvelope(request)
|
|
1778
|
-
);
|
|
2030
|
+
const runId = await this.admitRun(discovered.executionName, request, options);
|
|
1779
2031
|
const run = await this.signalRunner.getRun(runId);
|
|
1780
2032
|
if (!run) throw new Error(`Foundry failed to create run "${runId}".`);
|
|
1781
2033
|
return this.toFoundryRun(run);
|
|
@@ -2063,6 +2315,9 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2063
2315
|
return runs.map((run) => this.toFoundryRun(run));
|
|
2064
2316
|
}
|
|
2065
2317
|
async waitForRun(runId, options) {
|
|
2318
|
+
while (this.gate.waiting(runId)) {
|
|
2319
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, options?.pollMs ?? 100));
|
|
2320
|
+
}
|
|
2066
2321
|
const run = await this.signalRunner.waitForRun(runId, options);
|
|
2067
2322
|
return run ? this.toFoundryRun(run) : null;
|
|
2068
2323
|
}
|
|
@@ -2120,24 +2375,40 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2120
2375
|
throw new Error(`Foundry run "${runId}" does not expose an agent conversation to steer.`);
|
|
2121
2376
|
}
|
|
2122
2377
|
const active = source.status === "pending" || source.status === "running";
|
|
2123
|
-
const
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
if (!
|
|
2130
|
-
|
|
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);
|
|
2131
2394
|
}
|
|
2132
|
-
await this.
|
|
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();
|
|
2133
2411
|
}
|
|
2134
|
-
const run = await this.send(source.agentId, source.conversationId, message, {
|
|
2135
|
-
context: {
|
|
2136
|
-
protocol: "foundry-control",
|
|
2137
|
-
steeredFromRunId: runId,
|
|
2138
|
-
steeringMode: "interrupt-and-restart"
|
|
2139
|
-
}
|
|
2140
|
-
});
|
|
2141
2412
|
this.observability.append({
|
|
2142
2413
|
type: "run.steered",
|
|
2143
2414
|
category: "system",
|
|
@@ -2487,29 +2758,34 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2487
2758
|
event,
|
|
2488
2759
|
playbooks: matched
|
|
2489
2760
|
});
|
|
2490
|
-
const run = await this.
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
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
|
+
}
|
|
2506
2782
|
}
|
|
2507
2783
|
});
|
|
2508
|
-
runs.push(run);
|
|
2784
|
+
if (run && !runs.some((item) => item.id === run.id)) runs.push(run);
|
|
2509
2785
|
deliveries.push({
|
|
2510
2786
|
agentId: agent.id,
|
|
2511
2787
|
playbookIds: matched.map((playbook) => playbook.id),
|
|
2512
|
-
runId: run.id
|
|
2788
|
+
...run ? { runId: run.id } : {}
|
|
2513
2789
|
});
|
|
2514
2790
|
}
|
|
2515
2791
|
await Effect5.runPromise(
|
|
@@ -3076,15 +3352,547 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3076
3352
|
});
|
|
3077
3353
|
}
|
|
3078
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
|
+
}
|
|
3079
3868
|
async enqueueCoreRequest(definitionId, request) {
|
|
3080
3869
|
const discovered = this.byRoute.get(definitionId);
|
|
3081
3870
|
if (!discovered) throw new Error(`Foundry agent definition "${definitionId}" was not found.`);
|
|
3082
3871
|
const agent = await Effect5.runPromise(this.data.getAgent(request.agentId));
|
|
3083
3872
|
const conversation = await Effect5.runPromise(this.data.getConversation(request.conversationId));
|
|
3084
3873
|
if (!agent || !conversation) throw new Error("Core command references an unknown agent instance or conversation.");
|
|
3085
|
-
return this.
|
|
3086
|
-
|
|
3087
|
-
|
|
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
|
|
3088
3896
|
);
|
|
3089
3897
|
}
|
|
3090
3898
|
withActivationTransition(work) {
|
|
@@ -3100,6 +3908,10 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3100
3908
|
return this.executeCoreCommandUnlocked(command, parentRunId);
|
|
3101
3909
|
}
|
|
3102
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
|
+
}
|
|
3103
3915
|
if (command.type === "transmit") {
|
|
3104
3916
|
const request2 = await getFoundryCoreCommandRequest(
|
|
3105
3917
|
this.coreCommandDirectory,
|
|
@@ -3637,12 +4449,21 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3637
4449
|
...signal ? { signal } : {}
|
|
3638
4450
|
});
|
|
3639
4451
|
}
|
|
3640
|
-
async executionEnvelope(request) {
|
|
4452
|
+
async executionEnvelope(request, options = {}) {
|
|
3641
4453
|
const agent = await Effect5.runPromise(this.data.getAgent(request.agentId));
|
|
3642
4454
|
const conversation = await Effect5.runPromise(this.data.getConversation(request.conversationId));
|
|
3643
4455
|
if (!agent || !conversation) throw new Error("Cannot schedule an unknown agent instance or conversation.");
|
|
3644
4456
|
const activations = (await Effect5.runPromise(this.data.listActivations(request.workspaceId))).filter((activation) => activation.agentId === request.agentId);
|
|
3645
|
-
|
|
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
|
+
};
|
|
3646
4467
|
}
|
|
3647
4468
|
toFoundryRun(run) {
|
|
3648
4469
|
const storedInput = parseJson(run.input);
|
|
@@ -3901,6 +4722,7 @@ function explainRun(run){
|
|
|
3901
4722
|
if(source==="activation")return"Started by a scheduled activation or wake-up.";
|
|
3902
4723
|
if(source==="spawn")return"Spawned by another agent run.";
|
|
3903
4724
|
if(source==="background")return"Continued as background work.";
|
|
4725
|
+
if(source==="delegation")return"Delegated work, or a delegation result or question coming back.";
|
|
3904
4726
|
if(run.status==="completed")return"The agent completed the requested work.";
|
|
3905
4727
|
return"The agent is processing a direct message.";
|
|
3906
4728
|
}
|