glove-foundry 0.6.0 → 0.7.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.
- package/dist/{chunk-X6EWEWWM.js → chunk-2GXPSIRL.js} +623 -100
- package/dist/chunk-64UBLGYM.js +1241 -0
- package/dist/{chunk-B36BGF5R.js → chunk-AC6SRI5V.js} +17 -22
- package/dist/{chunk-7F7QVO6I.js → chunk-EEHGAWXM.js} +26 -0
- package/dist/{chunk-OBTOFA7W.js → chunk-EJZJAVNG.js} +137 -633
- package/dist/{chunk-RSU7NEDK.js → chunk-IPASF7PK.js} +1 -1
- package/dist/cli.js +4 -4
- package/dist/{client-DWPYe_Nc.d.ts → client-BgpgsnoO.d.ts} +158 -107
- package/dist/client.d.ts +3 -3
- package/dist/client.js +1 -1
- package/dist/{definition-A8o11aez.d.ts → event-delivery-BaYe6d9w.d.ts} +1015 -874
- package/dist/execution-agent.d.ts +0 -1
- package/dist/execution-agent.js +3 -14
- package/dist/execution-daemon.js +1 -1
- package/dist/execution-loader.js +1014 -8
- package/dist/index.d.ts +9 -5
- package/dist/index.js +70 -23
- package/dist/voice.d.ts +2 -2
- package/dist/voice.js +1 -1
- package/docs/architecture.md +8 -0
- package/docs/building-with-foundry.md +9 -1
- package/docs/durable-subagents.md +259 -0
- package/package.json +11 -11
- package/dist/chunk-K2EU63MB.js +0 -468
- package/dist/chunk-TFGETZYH.js +0 -917
|
@@ -6,41 +6,30 @@ import {
|
|
|
6
6
|
} from "./chunk-J7ZBJM54.js";
|
|
7
7
|
import {
|
|
8
8
|
EMPTY_AGENT_COMPOSITION,
|
|
9
|
-
EMPTY_CAPABILITY_REGISTRY,
|
|
10
9
|
EMPTY_FOUNDRY_APPLICATION,
|
|
11
|
-
FOUNDRY_AGENT_APPLICATION_BRAND,
|
|
12
10
|
FOUNDRY_APPROVAL_DIRECTORY_ENV,
|
|
13
|
-
FOUNDRY_CORE_COMMAND_DIRECTORY_ENV,
|
|
14
11
|
FOUNDRY_CORE_COMMAND_EVENT,
|
|
15
|
-
FOUNDRY_MCP_BRAND,
|
|
16
|
-
FOUNDRY_MEMORY_BRAND,
|
|
17
|
-
FOUNDRY_SHARED_TOOL_BRAND,
|
|
18
12
|
MemoryFoundryDataAdapter,
|
|
19
|
-
claimFoundryCoreCommandRequest,
|
|
20
13
|
createAgentInstance,
|
|
21
14
|
createConversation,
|
|
22
15
|
createManifest,
|
|
23
16
|
definePlaybookSubscription,
|
|
24
|
-
defineSharedTool,
|
|
25
17
|
discoverAgents,
|
|
26
18
|
freezeGloveMessage,
|
|
27
|
-
getFoundryCoreCommandRequest,
|
|
28
19
|
id,
|
|
29
|
-
installationKey,
|
|
30
20
|
listFoundryApprovals,
|
|
31
|
-
monitorFoundryCoreCommandRequest,
|
|
32
21
|
normalizeAgentInstallations,
|
|
33
22
|
reconstructPlaybook,
|
|
34
23
|
reconstructPlaybookSubscription,
|
|
35
24
|
resolveFoundryApproval,
|
|
36
|
-
settleFoundryCoreCommandRequest,
|
|
37
25
|
transmissionPredicate
|
|
38
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-EJZJAVNG.js";
|
|
39
27
|
import {
|
|
40
28
|
FOUNDRY_CONVERSATION_LEASE_EVENT,
|
|
41
29
|
FOUNDRY_CONVERSATION_LISTEN_EVENT,
|
|
42
30
|
FOUNDRY_MAILBOX_DIRECTORY_ENV,
|
|
43
31
|
delegationFromContext,
|
|
32
|
+
deliveryEvent,
|
|
44
33
|
drainMailbox,
|
|
45
34
|
isDelegationId,
|
|
46
35
|
isOpenDelegation,
|
|
@@ -50,17 +39,39 @@ import {
|
|
|
50
39
|
workerAgentId,
|
|
51
40
|
writeConversationLease,
|
|
52
41
|
writeMailboxDelivery
|
|
53
|
-
} from "./chunk-
|
|
42
|
+
} from "./chunk-AC6SRI5V.js";
|
|
54
43
|
import {
|
|
44
|
+
EMPTY_CAPABILITY_REGISTRY,
|
|
55
45
|
EMPTY_NATIVE_REGISTRY,
|
|
46
|
+
FOUNDRY_AGENT_APPLICATION_BRAND,
|
|
56
47
|
FOUNDRY_APPLICATION_ENV,
|
|
48
|
+
FOUNDRY_CORE_COMMAND_DIRECTORY_ENV,
|
|
57
49
|
FOUNDRY_EVENT_PREFIX,
|
|
58
50
|
FOUNDRY_EXECUTION_MARKER,
|
|
59
51
|
FOUNDRY_LAYER_BRAND,
|
|
52
|
+
FOUNDRY_MCP_BRAND,
|
|
53
|
+
FOUNDRY_MEMORY_BRAND,
|
|
60
54
|
FOUNDRY_RUN_PROCESS_EVENT,
|
|
55
|
+
FOUNDRY_SHARED_TOOL_BRAND,
|
|
61
56
|
FOUNDRY_SUBSCRIBER_BRAND,
|
|
62
|
-
|
|
63
|
-
|
|
57
|
+
agentInboxId,
|
|
58
|
+
bindFileIdentity,
|
|
59
|
+
claimFoundryCoreCommandRequest,
|
|
60
|
+
defineSharedTool,
|
|
61
|
+
durableInstanceId,
|
|
62
|
+
durableKey,
|
|
63
|
+
durableRoute,
|
|
64
|
+
eventDue,
|
|
65
|
+
eventPolicySchema,
|
|
66
|
+
eventRecordId,
|
|
67
|
+
foundryEventSchema,
|
|
68
|
+
getFoundryCoreCommandRequest,
|
|
69
|
+
inheritedInstallations,
|
|
70
|
+
installationKey,
|
|
71
|
+
messageOptionsSchema,
|
|
72
|
+
monitorFoundryCoreCommandRequest,
|
|
73
|
+
settleFoundryCoreCommandRequest
|
|
74
|
+
} from "./chunk-64UBLGYM.js";
|
|
64
75
|
|
|
65
76
|
// src/codegen.ts
|
|
66
77
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
@@ -861,6 +872,7 @@ var FoundryObserver = class {
|
|
|
861
872
|
};
|
|
862
873
|
|
|
863
874
|
// src/runtime.ts
|
|
875
|
+
import { isDeepStrictEqual } from "node:util";
|
|
864
876
|
import { mkdir as mkdir2, rm as rm2 } from "node:fs/promises";
|
|
865
877
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
866
878
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
@@ -1607,6 +1619,8 @@ var FoundryRuntimeError = class extends Schema3.TaggedError(
|
|
|
1607
1619
|
};
|
|
1608
1620
|
function deliverySource(deliveries) {
|
|
1609
1621
|
const first = deliveries[0];
|
|
1622
|
+
if (first.durable?.event.kind?.startsWith("delegation.")) return { kind: "delegation", id: first.durable.event.id };
|
|
1623
|
+
if (first.kind === "agent-message") return { kind: "agent-message", id: first.pendingId };
|
|
1610
1624
|
if (deliveries.every((delivery) => delivery.kind === "transmission")) {
|
|
1611
1625
|
return first.kind === "transmission" ? { kind: "transmission", id: first.routeId, eventId: first.eventId } : { kind: "transmission" };
|
|
1612
1626
|
}
|
|
@@ -1715,6 +1729,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1715
1729
|
}
|
|
1716
1730
|
});
|
|
1717
1731
|
/** Pending inbound records each run is handling, so they are cleared when it settles. */
|
|
1732
|
+
eventTimers = /* @__PURE__ */ new Map();
|
|
1733
|
+
completedEventRuns = /* @__PURE__ */ new Map();
|
|
1718
1734
|
pendingInboundByRun = /* @__PURE__ */ new Map();
|
|
1719
1735
|
/** Recently settled runs, for a record assigned to a run that already finished. */
|
|
1720
1736
|
settledRuns = /* @__PURE__ */ new Set();
|
|
@@ -1934,6 +1950,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1934
1950
|
]);
|
|
1935
1951
|
await this.seedTopology();
|
|
1936
1952
|
for (const instance of await this.listAgentInstances()) {
|
|
1953
|
+
if (instance.durableSubagent) continue;
|
|
1937
1954
|
if (!this.byRoute.has(instance.definitionId)) {
|
|
1938
1955
|
throw new Error(
|
|
1939
1956
|
`Agent instance "${instance.id}" references unknown definition "${instance.definitionId}".`
|
|
@@ -1955,8 +1972,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1955
1972
|
await this.reconstructActivations();
|
|
1956
1973
|
this.runInBackground("signal", this.signalRunner.start());
|
|
1957
1974
|
await this.reconcileApplicationConnections();
|
|
1958
|
-
void this.redeliverDelegations().catch((cause) => this.reportDeliveryFailure("startup", cause));
|
|
1959
|
-
void this.redeliverInbound().catch((cause) => this.reportDeliveryFailure("startup", cause));
|
|
1975
|
+
void this.redeliverInbound().then(() => this.redeliverDelegations()).then(() => this.redeliverEvents()).catch((cause) => this.reportDeliveryFailure("startup", cause));
|
|
1960
1976
|
} catch (cause) {
|
|
1961
1977
|
try {
|
|
1962
1978
|
await this.stop();
|
|
@@ -1983,6 +1999,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1983
1999
|
return;
|
|
1984
2000
|
}
|
|
1985
2001
|
this.stopping = true;
|
|
2002
|
+
for (const timer of this.eventTimers.values()) clearTimeout(timer);
|
|
2003
|
+
this.eventTimers.clear();
|
|
1986
2004
|
for (const timer of this.activationTimers.values()) clearTimeout(timer);
|
|
1987
2005
|
this.activationTimers.clear();
|
|
1988
2006
|
this.activationDispatches.clear();
|
|
@@ -2013,6 +2031,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2013
2031
|
if (!discovered) throw new Error(`Foundry agent "${route}" was not found.`);
|
|
2014
2032
|
const agent = await Effect5.runPromise(this.data.getAgent(request.agentId));
|
|
2015
2033
|
if (!agent) throw new Error(`Foundry agent instance "${request.agentId}" was not found.`);
|
|
2034
|
+
await this.assertDurableActive(agent);
|
|
2016
2035
|
if (agent.definitionId !== route) {
|
|
2017
2036
|
throw new Error(`Agent instance "${request.agentId}" uses definition "${agent.definitionId}", not "${route}".`);
|
|
2018
2037
|
}
|
|
@@ -2041,6 +2060,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2041
2060
|
return Effect5.runPromise(this.requestEffect(route, request));
|
|
2042
2061
|
}
|
|
2043
2062
|
async createAgent(definitionId, options = {}) {
|
|
2063
|
+
if (definitionId.includes("/workers/") || options.durableSubagent) throw new Error("Create durable workers through subagent(parentAgentId, name).");
|
|
2044
2064
|
if (!this.byRoute.has(definitionId)) {
|
|
2045
2065
|
throw new Error(`Foundry agent definition "${definitionId}" was not found.`);
|
|
2046
2066
|
}
|
|
@@ -2057,6 +2077,208 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2057
2077
|
if (this.started) await this.reconcileApplicationConnections();
|
|
2058
2078
|
return agent;
|
|
2059
2079
|
}
|
|
2080
|
+
/** Provision exactly one owned worker per parent instance and declared slot. */
|
|
2081
|
+
subagent(parentAgentId, name) {
|
|
2082
|
+
return this.inConversation("durable:mutations", () => this.ensureSubagent(parentAgentId, name));
|
|
2083
|
+
}
|
|
2084
|
+
async ensureSubagent(parentAgentId, name) {
|
|
2085
|
+
const parent = await Effect5.runPromise(this.data.getAgent(parentAgentId));
|
|
2086
|
+
if (!parent) throw new Error(`Parent agent "${parentAgentId}" does not exist.`);
|
|
2087
|
+
await this.assertDurableActive(parent);
|
|
2088
|
+
const selection = this.byRoute.get(parent.definitionId)?.definition.durableSubagents?.[name];
|
|
2089
|
+
if (!selection || !Object.hasOwn(this.byRoute.get(parent.definitionId).definition.durableSubagents ?? {}, name)) throw new Error(`Agent "${parentAgentId}" has no durable worker "${name}".`);
|
|
2090
|
+
const route = durableRoute(parent.definitionId, name);
|
|
2091
|
+
const child = await Effect5.runPromise(this.data.provisionAgent({
|
|
2092
|
+
id: durableInstanceId(parent.id, name),
|
|
2093
|
+
definitionId: route,
|
|
2094
|
+
provisioningKey: durableKey(parent.id, name),
|
|
2095
|
+
workspaceId: parent.workspaceId,
|
|
2096
|
+
context: selection.inherit?.context ? parent.context : {},
|
|
2097
|
+
durableSubagent: { parentAgentId: parent.id, name, status: "active" }
|
|
2098
|
+
}));
|
|
2099
|
+
if (child.definitionId !== route || child.workspaceId !== parent.workspaceId || child.durableSubagent?.parentAgentId !== parent.id || child.durableSubagent.name !== name) throw new Error("Durable worker ownership conflict.");
|
|
2100
|
+
await this.assertDurableActive(child);
|
|
2101
|
+
return child;
|
|
2102
|
+
}
|
|
2103
|
+
async listSubagents(parentAgentId) {
|
|
2104
|
+
return (await this.listAgentInstances()).filter((agent) => agent.durableSubagent?.parentAgentId === parentAgentId);
|
|
2105
|
+
}
|
|
2106
|
+
async assertDurableActive(agent) {
|
|
2107
|
+
if (agent.definitionId.includes("/workers/") && !agent.durableSubagent) throw new Error("Durable worker ownership is missing.");
|
|
2108
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2109
|
+
let current = agent;
|
|
2110
|
+
while (current.durableSubagent) {
|
|
2111
|
+
if (seen.has(current.id)) throw new Error("Cyclic durable worker ownership.");
|
|
2112
|
+
seen.add(current.id);
|
|
2113
|
+
const ownership = current.durableSubagent;
|
|
2114
|
+
if (ownership.status !== "active") throw new Error(`Durable worker "${current.id}" is ${ownership.status}.`);
|
|
2115
|
+
const parent = await Effect5.runPromise(this.data.getAgent(ownership.parentAgentId));
|
|
2116
|
+
if (!parent || parent.workspaceId !== current.workspaceId || !this.byRoute.get(parent.definitionId)?.definition.durableSubagents?.[ownership.name] || current.definitionId !== durableRoute(parent.definitionId, ownership.name)) throw new Error(`Durable worker "${current.id}" is detached from its definition or parent.`);
|
|
2117
|
+
current = parent;
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
async effectiveAgent(agent) {
|
|
2121
|
+
await this.assertDurableActive(agent);
|
|
2122
|
+
if (!agent.durableSubagent) return agent;
|
|
2123
|
+
const parent = await this.effectiveAgent(await Effect5.runPromise(this.data.getAgent(agent.durableSubagent.parentAgentId)));
|
|
2124
|
+
const definition = this.byRoute.get(agent.definitionId).definition;
|
|
2125
|
+
const selection = this.byRoute.get(parent.definitionId).definition.durableSubagents[agent.durableSubagent.name];
|
|
2126
|
+
const inheritedIds = new Set((selection.inherit?.apps ?? []).map((app) => typeof app === "string" ? app : app.id));
|
|
2127
|
+
return { ...agent, installations: [
|
|
2128
|
+
...agent.installations.filter((item) => item.kind !== "application" || !inheritedIds.has(item.id)),
|
|
2129
|
+
...inheritedInstallations(parent, definition, selection)
|
|
2130
|
+
] };
|
|
2131
|
+
}
|
|
2132
|
+
async ensureAgentEventConversation(agent) {
|
|
2133
|
+
const id2 = agentInboxId(agent.id);
|
|
2134
|
+
return this.inConversation(`agent-events:${id2}`, async () => {
|
|
2135
|
+
const existing = await Effect5.runPromise(this.data.getConversation(id2));
|
|
2136
|
+
if (existing) {
|
|
2137
|
+
if (existing.agentId !== agent.id || existing.workspaceId !== agent.workspaceId) throw new Error("Agent event conversation ownership conflict.");
|
|
2138
|
+
return existing;
|
|
2139
|
+
}
|
|
2140
|
+
return this.createConversation(agent.id, { id: id2, title: "Agent events" });
|
|
2141
|
+
});
|
|
2142
|
+
}
|
|
2143
|
+
/** A message to an owned worker, independent of any delegated task. */
|
|
2144
|
+
async messageSubagent(parentAgentId, name, message, options = {}) {
|
|
2145
|
+
return this.inConversation("durable:mutations", async () => {
|
|
2146
|
+
const child = await this.ensureSubagent(parentAgentId, name);
|
|
2147
|
+
return this.postAgentMessage(child, message, parentAgentId, options.id, options);
|
|
2148
|
+
});
|
|
2149
|
+
}
|
|
2150
|
+
async postAgentMessage(target, message, from, messageId = `message_${randomUUID2()}`, options = {}, replyTo) {
|
|
2151
|
+
options = messageOptionsSchema.parse(options);
|
|
2152
|
+
if (typeof message !== "string" || !message.trim()) throw new Error("Agent messages must not be empty.");
|
|
2153
|
+
const conversationId = options.conversationId ?? (await this.ensureAgentEventConversation(target)).id;
|
|
2154
|
+
return this.acceptEvent({ agentId: target.id, conversationId }, {
|
|
2155
|
+
id: options.id ?? messageId,
|
|
2156
|
+
source: `foundry:agent:${from}`,
|
|
2157
|
+
kind: "agent-message",
|
|
2158
|
+
content: message,
|
|
2159
|
+
...options.expiresAt ? { expiresAt: options.expiresAt } : {},
|
|
2160
|
+
metadata: { from, ...replyTo ? { replyTo } : {} }
|
|
2161
|
+
}, options);
|
|
2162
|
+
}
|
|
2163
|
+
/** Persist a spontaneous event before dispatching it to one exact runtime context. */
|
|
2164
|
+
async emitEvent(target, event, policy = {}) {
|
|
2165
|
+
return this.inConversation("durable:mutations", () => this.acceptEvent(target, event, policy));
|
|
2166
|
+
}
|
|
2167
|
+
async acceptEvent(target, event, policy) {
|
|
2168
|
+
foundryEventSchema.parse(event);
|
|
2169
|
+
eventPolicySchema.parse(policy);
|
|
2170
|
+
const agent = await Effect5.runPromise(this.data.getAgent(target.agentId));
|
|
2171
|
+
const conversation = await Effect5.runPromise(this.data.getConversation(target.conversationId));
|
|
2172
|
+
if (!agent || conversation?.agentId !== agent.id || conversation.workspaceId !== agent.workspaceId) throw new Error("Event target must name a conversation owned by the addressed agent.");
|
|
2173
|
+
await this.assertDurableActive(agent);
|
|
2174
|
+
const defaults = this.byRoute.get(agent.definitionId)?.definition.eventDelivery;
|
|
2175
|
+
const resolved = eventPolicySchema.parse({ ...defaults, ...event.whenIdle && event.whenIdle !== "auto" ? { whenIdle: event.whenIdle } : {}, ...policy });
|
|
2176
|
+
const id2 = eventRecordId(target, event.id);
|
|
2177
|
+
await this.deliver({ ...target, definitionId: agent.definitionId, workspaceId: agent.workspaceId }, [{
|
|
2178
|
+
kind: "agent-message",
|
|
2179
|
+
pendingId: id2,
|
|
2180
|
+
message: typeof event.content === "string" ? event.content : JSON.stringify(event.content),
|
|
2181
|
+
durable: { id: id2, event, policy: resolved }
|
|
2182
|
+
}]);
|
|
2183
|
+
const record = (await Effect5.runPromise(this.data.listEvents())).find((item) => item.id === id2);
|
|
2184
|
+
return { messageId: event.id, ...target, ...record?.runId ? { runId: record.runId } : {} };
|
|
2185
|
+
}
|
|
2186
|
+
async executeAgentMessage(command) {
|
|
2187
|
+
return this.inConversation("durable:mutations", async () => {
|
|
2188
|
+
const sender = await Effect5.runPromise(this.data.getAgent(command.agentId));
|
|
2189
|
+
const conversation = await Effect5.runPromise(this.data.getConversation(command.conversationId));
|
|
2190
|
+
if (!sender || sender.definitionId !== command.definitionId || sender.workspaceId !== command.workspaceId || conversation?.agentId !== sender.id) throw new Error("Invalid agent message sender.");
|
|
2191
|
+
await this.assertDurableActive(sender);
|
|
2192
|
+
const target = command.to === "parent" ? sender.durableSubagent && await Effect5.runPromise(this.data.getAgent(sender.durableSubagent.parentAgentId)) : await this.ensureSubagent(sender.id, command.to);
|
|
2193
|
+
if (!target || target.workspaceId !== sender.workspaceId) throw new Error("Agent message recipient is not an owned worker or parent.");
|
|
2194
|
+
return this.postAgentMessage(target, command.message, sender.id, command.id, command.delivery, { agentId: sender.id, conversationId: command.conversationId });
|
|
2195
|
+
});
|
|
2196
|
+
}
|
|
2197
|
+
/** Inspect owned records without provisioning or requiring the declaration to still exist. */
|
|
2198
|
+
async subagentData(parentAgentId, name) {
|
|
2199
|
+
const agent = (await this.listSubagents(parentAgentId)).find((item) => item.durableSubagent?.name === name);
|
|
2200
|
+
if (!agent) throw new Error(`Durable worker "${name}" was not found.`);
|
|
2201
|
+
const conversations = await Effect5.runPromise(this.data.listConversations(agent.id));
|
|
2202
|
+
return {
|
|
2203
|
+
agent,
|
|
2204
|
+
conversations,
|
|
2205
|
+
events: this.data.listEvents ? (await Effect5.runPromise(this.data.listEvents())).filter((item) => item.target.agentId === agent.id) : [],
|
|
2206
|
+
children: await this.listSubagents(agent.id),
|
|
2207
|
+
activations: (await Effect5.runPromise(this.data.listActivations(agent.workspaceId))).filter((item) => item.agentId === agent.id),
|
|
2208
|
+
pendingMessages: this.data.listPendingInbound ? (await Effect5.runPromise(this.data.listPendingInbound())).filter((item) => item.request.agentId === agent.id) : [],
|
|
2209
|
+
tasks: (await Effect5.runPromise(this.data.listTasks(agent.workspaceId))).filter((item) => item.agentId === agent.id),
|
|
2210
|
+
inbox: (await Effect5.runPromise(this.data.listInboxItems(agent.workspaceId))).filter((item) => item.agentId === agent.id)
|
|
2211
|
+
};
|
|
2212
|
+
}
|
|
2213
|
+
async archiveSubagent(parentAgentId, name) {
|
|
2214
|
+
return this.inConversation("durable:mutations", async () => {
|
|
2215
|
+
const { agent } = await this.subagentData(parentAgentId, name);
|
|
2216
|
+
const archive = async (current) => {
|
|
2217
|
+
if (current.durableSubagent.status === "purged") return current;
|
|
2218
|
+
const archived2 = { ...current, durableSubagent: { ...current.durableSubagent, status: "archived" }, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
2219
|
+
await Effect5.runPromise(this.data.putAgent(archived2));
|
|
2220
|
+
for (const child of await this.listSubagents(current.id)) await archive(child);
|
|
2221
|
+
await this.withActivationTransition(async () => {
|
|
2222
|
+
for (const activation of await Effect5.runPromise(this.data.listActivations(current.workspaceId))) {
|
|
2223
|
+
if (activation.agentId !== current.id || ["cancelled", "completed"].includes(activation.status)) continue;
|
|
2224
|
+
await this.disarmActivation(activation);
|
|
2225
|
+
await Effect5.runPromise(this.data.putActivation({ ...activation, status: "paused", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
2226
|
+
}
|
|
2227
|
+
});
|
|
2228
|
+
for (const conversation of await Effect5.runPromise(this.data.listConversations(current.id))) {
|
|
2229
|
+
this.heldDeliveries.delete(conversation.id);
|
|
2230
|
+
this.conversationListeners.delete(conversation.id);
|
|
2231
|
+
await drainMailbox(this.mailboxDirectory, conversation.id);
|
|
2232
|
+
}
|
|
2233
|
+
for (const run of await this.listRuns(current.definitionId)) {
|
|
2234
|
+
if (run.agentId === current.id && !["completed", "cancelled", "failed"].includes(run.status)) {
|
|
2235
|
+
await this.cancel(run.id);
|
|
2236
|
+
const settled = await this.waitForRun(run.id, { timeoutMs: 3e4 });
|
|
2237
|
+
if (settled && !["completed", "cancelled", "failed"].includes(settled.status)) throw new Error("Worker is still stopping; retry archival before purging.");
|
|
2238
|
+
if (settled) await this.waitForRunProcessRelease(settled, current.definitionId);
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
return archived2;
|
|
2242
|
+
};
|
|
2243
|
+
const archived = await archive(agent);
|
|
2244
|
+
if (this.started) await this.reconcileApplicationConnections();
|
|
2245
|
+
this.observability.append({ type: "agent.subagent.archived", category: "agent", agent: agent.definitionId, data: { agentId: agent.id } });
|
|
2246
|
+
return archived;
|
|
2247
|
+
});
|
|
2248
|
+
}
|
|
2249
|
+
async resumeSubagent(parentAgentId, name) {
|
|
2250
|
+
return this.inConversation("durable:mutations", async () => {
|
|
2251
|
+
const { agent } = await this.subagentData(parentAgentId, name);
|
|
2252
|
+
if (agent.durableSubagent.status === "purged") throw new Error("A purged worker cannot be resumed.");
|
|
2253
|
+
if (agent.durableSubagent.status === "active") return agent;
|
|
2254
|
+
const resumed = { ...agent, durableSubagent: { ...agent.durableSubagent, status: "active" }, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
2255
|
+
await this.assertDurableActive(resumed);
|
|
2256
|
+
await Effect5.runPromise(this.data.putAgent(resumed));
|
|
2257
|
+
for (const pending of this.data.listPendingInbound ? await Effect5.runPromise(this.data.listPendingInbound()) : []) {
|
|
2258
|
+
if (pending.request.agentId === agent.id) await this.admitInbound(pending);
|
|
2259
|
+
}
|
|
2260
|
+
await this.redeliverEvents(agent.id);
|
|
2261
|
+
return resumed;
|
|
2262
|
+
});
|
|
2263
|
+
}
|
|
2264
|
+
/** Purge requires archival and an explicit application cleanup hook. Shared data is never passed to it. */
|
|
2265
|
+
async purgeSubagent(parentAgentId, name) {
|
|
2266
|
+
return this.inConversation("durable:mutations", async () => {
|
|
2267
|
+
const { agent, conversations, children } = await this.subagentData(parentAgentId, name);
|
|
2268
|
+
if (agent.durableSubagent.status === "purged") return;
|
|
2269
|
+
if (agent.durableSubagent.status !== "archived") throw new Error("Archive the worker before purging it.");
|
|
2270
|
+
const running = (await this.listRuns(agent.definitionId)).some((run) => run.agentId === agent.id && !["completed", "failed", "cancelled"].includes(run.status));
|
|
2271
|
+
if (running) throw new Error("Wait for worker runs to stop before purging.");
|
|
2272
|
+
if (children.some((child) => child.durableSubagent?.status !== "purged")) throw new Error("Purge owned child workers first.");
|
|
2273
|
+
if (!this.data.purgeAgentData) throw new Error("The data adapter does not support purging agent data.");
|
|
2274
|
+
const parent = await Effect5.runPromise(this.data.getAgent(parentAgentId));
|
|
2275
|
+
const selection = parent && this.byRoute.get(parent.definitionId)?.definition.durableSubagents?.[name];
|
|
2276
|
+
if (!selection?.cleanup) throw new Error("Define an idempotent durable subagent cleanup hook to purge private external memory, transcripts, and files. Keep the declaration until cleanup completes.");
|
|
2277
|
+
await selection.cleanup({ agent, conversationIds: conversations.map((item) => item.id) });
|
|
2278
|
+
await Effect5.runPromise(this.data.purgeAgentData(agent.id));
|
|
2279
|
+
this.observability.append({ type: "agent.subagent.purged", category: "agent", agent: agent.definitionId, data: { agentId: agent.id } });
|
|
2280
|
+
});
|
|
2281
|
+
}
|
|
2060
2282
|
async createConversation(agentId, options = {}) {
|
|
2061
2283
|
const agent = await Effect5.runPromise(this.data.getAgent(agentId));
|
|
2062
2284
|
if (!agent) throw new Error(`Foundry agent instance "${agentId}" was not found.`);
|
|
@@ -2127,6 +2349,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2127
2349
|
async configureAgent(agentId, options) {
|
|
2128
2350
|
const current = await Effect5.runPromise(this.data.getAgent(agentId));
|
|
2129
2351
|
if (!current) throw new Error(`Foundry agent instance "${agentId}" was not found.`);
|
|
2352
|
+
await this.assertDurableActive(current);
|
|
2130
2353
|
const installations = options.installations ? normalizeAgentInstallations(options.installations) : current.installations;
|
|
2131
2354
|
for (const installation of installations) {
|
|
2132
2355
|
this.assertRegisteredInstallation(current.definitionId, installation);
|
|
@@ -2505,6 +2728,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2505
2728
|
if (!agent) {
|
|
2506
2729
|
throw new Error(`Foundry agent instance "${agentId}" was not found.`);
|
|
2507
2730
|
}
|
|
2731
|
+
await this.assertDurableActive(agent);
|
|
2508
2732
|
this.assertRegisteredInstallation(agent.definitionId, installation);
|
|
2509
2733
|
const installations = normalizeAgentInstallations([
|
|
2510
2734
|
...agent.installations,
|
|
@@ -2656,12 +2880,19 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2656
2880
|
const runs = [];
|
|
2657
2881
|
const deliveries = [];
|
|
2658
2882
|
const matchedByAgent = /* @__PURE__ */ new Map();
|
|
2659
|
-
for (const
|
|
2883
|
+
for (const stored of instances) {
|
|
2884
|
+
let agent;
|
|
2885
|
+
try {
|
|
2886
|
+
agent = await this.effectiveAgent(stored);
|
|
2887
|
+
} catch {
|
|
2888
|
+
if (stored.durableSubagent) continue;
|
|
2889
|
+
throw new Error(`Cannot resolve agent "${stored.id}".`);
|
|
2890
|
+
}
|
|
2660
2891
|
const installedApplications = new Set(
|
|
2661
2892
|
agent.installations.filter((installation) => installation.kind === "application").map((installation) => installation.id)
|
|
2662
2893
|
);
|
|
2663
2894
|
const hasInstalledOwner = (this.compositionByDefinition.get(agent.definitionId)?.capabilities.applications ?? []).some(
|
|
2664
|
-
(application) => installedApplications.has(application.id) && application.transmissions?.some(
|
|
2895
|
+
(application) => installedApplications.has(application.id) && (!application.restrictions || application.restrictions.transmissions?.includes(integration.id)) && application.transmissions?.some(
|
|
2665
2896
|
(candidate) => candidate.id === integration.id && candidate.inbound
|
|
2666
2897
|
)
|
|
2667
2898
|
);
|
|
@@ -2812,7 +3043,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2812
3043
|
`Outbound route "${route.id}" does not belong to transmission "${input.transmissionId}".`
|
|
2813
3044
|
);
|
|
2814
3045
|
}
|
|
2815
|
-
const
|
|
3046
|
+
const storedAgent = await Effect5.runPromise(this.data.getAgent(input.agentId));
|
|
3047
|
+
const agent = storedAgent ? await this.effectiveAgent(storedAgent) : null;
|
|
2816
3048
|
if (!agent) {
|
|
2817
3049
|
throw new Error(`Agent instance "${input.agentId}" does not exist.`);
|
|
2818
3050
|
}
|
|
@@ -2830,6 +3062,9 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2830
3062
|
);
|
|
2831
3063
|
}
|
|
2832
3064
|
}
|
|
3065
|
+
const owners = this.compositionByDefinition.get(agent.definitionId)?.capabilities.applications.filter((app) => (!input.applicationId || app.id === input.applicationId) && agent.installations.some((item) => item.kind === "application" && item.id === app.id) && app.transmissions?.some((transmission2) => transmission2.id === route.transmissionId)) ?? [];
|
|
3066
|
+
if (owners.length && !owners.some((app) => !app.restrictions || app.restrictions.transmissions?.includes(route.transmissionId))) throw new Error("Application restrictions deny this outbound transmission.");
|
|
3067
|
+
if (agent.durableSubagent && !owners.length) throw new Error("Durable workers require an installed application for outbound transmissions.");
|
|
2833
3068
|
const grant = await this.resolveGrant({
|
|
2834
3069
|
runId: input.runId,
|
|
2835
3070
|
agentId: input.agentId
|
|
@@ -2853,7 +3088,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2853
3088
|
grant,
|
|
2854
3089
|
signal: input.signal ?? new AbortController().signal,
|
|
2855
3090
|
...account && accountSessions ? {
|
|
2856
|
-
withAccountSession: (operation, use) => accountSessions.withSession({
|
|
3091
|
+
withAccountSession: (operation, use) => owners.length && !owners.some((app) => !app.restrictions || app.restrictions.transmissions?.includes(route.transmissionId) && app.restrictions.operations?.includes(operation)) ? Effect5.fail(new Error(`Application restrictions deny account operation "${operation}".`)) : accountSessions.withSession({
|
|
2857
3092
|
accountId: account.id,
|
|
2858
3093
|
operation,
|
|
2859
3094
|
agentId: agent.id,
|
|
@@ -3054,7 +3289,14 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3054
3289
|
});
|
|
3055
3290
|
}
|
|
3056
3291
|
}
|
|
3057
|
-
for (const
|
|
3292
|
+
for (const stored of await this.listAgentInstances()) {
|
|
3293
|
+
let agent;
|
|
3294
|
+
try {
|
|
3295
|
+
agent = await this.effectiveAgent(stored);
|
|
3296
|
+
} catch {
|
|
3297
|
+
if (stored.durableSubagent) continue;
|
|
3298
|
+
throw new Error(`Cannot resolve agent "${stored.id}".`);
|
|
3299
|
+
}
|
|
3058
3300
|
const installedApplications = new Set(
|
|
3059
3301
|
agent.installations.filter((installation) => installation.kind === "application").map((installation) => installation.id)
|
|
3060
3302
|
);
|
|
@@ -3076,6 +3318,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3076
3318
|
const composition = this.compositionByDefinition.get(requirement.definitionId);
|
|
3077
3319
|
if (!composition) continue;
|
|
3078
3320
|
for (const application of composition.capabilities.applications) {
|
|
3321
|
+
if (application.restrictions && !application.restrictions.transmissions?.includes(requirement.playbook.transmissionId)) continue;
|
|
3079
3322
|
if (requirement.installedApplications && !requirement.installedApplications.has(application.id)) continue;
|
|
3080
3323
|
if (!application.transmissions?.some(
|
|
3081
3324
|
(transmission) => transmission.id === requirement.playbook.transmissionId
|
|
@@ -3155,7 +3398,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3155
3398
|
(candidate) => candidate.id === playbook.transmissionId && candidate.inbound
|
|
3156
3399
|
)
|
|
3157
3400
|
);
|
|
3158
|
-
if (!inboundOwners.some((application) => installedApplications.has(application.id))) {
|
|
3401
|
+
if (!inboundOwners.some((application) => installedApplications.has(application.id) && (!application.restrictions || application.restrictions.transmissions?.includes(playbook.transmissionId)))) {
|
|
3159
3402
|
throw new Error(
|
|
3160
3403
|
`Playbook "${playbook.id}" requires an installed application that owns inbound transmission "${playbook.transmissionId}".`
|
|
3161
3404
|
);
|
|
@@ -3375,18 +3618,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3375
3618
|
return found.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
3376
3619
|
}
|
|
3377
3620
|
async openDelegationsFrom(agentId, conversationId) {
|
|
3378
|
-
|
|
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));
|
|
3621
|
+
return (await this.listDelegations({ agentId, conversationId })).filter(isOpenDelegation).sort((left, right) => left.createdAt.localeCompare(right.createdAt));
|
|
3390
3622
|
}
|
|
3391
3623
|
/** Run work for one conversation after the work already queued for it. */
|
|
3392
3624
|
inConversation(conversationId, work) {
|
|
@@ -3457,8 +3689,9 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3457
3689
|
const target = await this.deliveryTargetFor(conversationId);
|
|
3458
3690
|
if (!target) return;
|
|
3459
3691
|
for (const delivery of deliveries) {
|
|
3460
|
-
if (delivery.kind === "transmission") await this.assignPendingInbound(delivery.pendingId, void 0);
|
|
3692
|
+
if (delivery.kind === "transmission" || delivery.kind === "agent-message") await this.assignPendingInbound(delivery.pendingId, void 0);
|
|
3461
3693
|
}
|
|
3694
|
+
await this.markHandedOver(deliveries, void 0);
|
|
3462
3695
|
this.holdDeliveries(target, deliveries);
|
|
3463
3696
|
}
|
|
3464
3697
|
async deliveryTargetFor(conversationId) {
|
|
@@ -3475,11 +3708,56 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3475
3708
|
}
|
|
3476
3709
|
holdDeliveries(target, deliveries) {
|
|
3477
3710
|
const held = this.heldDeliveries.get(target.conversationId);
|
|
3478
|
-
if (held) held.deliveries.push(...deliveries);
|
|
3711
|
+
if (held) held.deliveries.push(...deliveries.filter((delivery) => !delivery.durable || !held.deliveries.some((item) => item.durable?.id === delivery.durable.id)));
|
|
3479
3712
|
else this.heldDeliveries.set(target.conversationId, { target, deliveries: [...deliveries] });
|
|
3480
3713
|
}
|
|
3481
|
-
deliver(target, deliveries) {
|
|
3714
|
+
deliver(target, deliveries, replay = false) {
|
|
3482
3715
|
return this.inConversation(target.conversationId, async () => {
|
|
3716
|
+
if (!this.data.claimEvent || !this.data.putEvent || !this.data.listEvents) throw new Error("Durable event delivery requires claimEvent, putEvent, and listEvents on the data adapter.");
|
|
3717
|
+
const accepted = [];
|
|
3718
|
+
for (const delivery of deliveries) {
|
|
3719
|
+
const event = JSON.parse(JSON.stringify(delivery.durable?.event ?? deliveryEvent(delivery)));
|
|
3720
|
+
const id2 = eventRecordId(target, event.id);
|
|
3721
|
+
const policy = JSON.parse(JSON.stringify(delivery.durable?.policy ?? this.byRoute.get(target.definitionId)?.definition.eventDelivery ?? {}));
|
|
3722
|
+
const { durable: _transport, ...body } = delivery;
|
|
3723
|
+
const record = {
|
|
3724
|
+
id: id2,
|
|
3725
|
+
target: { agentId: target.agentId, conversationId: target.conversationId },
|
|
3726
|
+
definitionId: target.definitionId,
|
|
3727
|
+
workspaceId: target.workspaceId,
|
|
3728
|
+
event,
|
|
3729
|
+
policy,
|
|
3730
|
+
delivery: body,
|
|
3731
|
+
status: "pending",
|
|
3732
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3733
|
+
};
|
|
3734
|
+
const fresh = await Effect5.runPromise(this.data.claimEvent(record));
|
|
3735
|
+
const existing = fresh ? record : (await Effect5.runPromise(this.data.listEvents())).find((item) => item.id === id2);
|
|
3736
|
+
if (!fresh && !replay && delivery.durable && (!isDeepStrictEqual(existing.event, event) || !isDeepStrictEqual(existing.policy, policy))) {
|
|
3737
|
+
throw new Error(`Event id "${event.id}" already belongs to a different event or delivery policy at this target.`);
|
|
3738
|
+
}
|
|
3739
|
+
await this.markLegacyHandedOver([body], void 0);
|
|
3740
|
+
if (existing.status !== "pending") {
|
|
3741
|
+
if ((body.kind === "agent-message" || body.kind === "transmission") && this.data.deletePendingInbound) await Effect5.runPromise(this.data.deletePendingInbound(body.pendingId));
|
|
3742
|
+
continue;
|
|
3743
|
+
}
|
|
3744
|
+
if (!fresh && !replay) continue;
|
|
3745
|
+
if (existing.event.expiresAt && Date.parse(existing.event.expiresAt) <= Date.now()) {
|
|
3746
|
+
await Effect5.runPromise(this.data.putEvent({ ...existing, status: "expired", runId: void 0 }));
|
|
3747
|
+
continue;
|
|
3748
|
+
}
|
|
3749
|
+
accepted.push({ ...existing.delivery, durable: { id: id2, event: existing.event, policy: existing.policy } });
|
|
3750
|
+
}
|
|
3751
|
+
deliveries = accepted;
|
|
3752
|
+
if (!deliveries.length) return;
|
|
3753
|
+
const recipient = await Effect5.runPromise(this.data.getAgent(target.agentId));
|
|
3754
|
+
if (recipient?.durableSubagent) {
|
|
3755
|
+
try {
|
|
3756
|
+
await this.assertDurableActive(recipient);
|
|
3757
|
+
} catch {
|
|
3758
|
+
return;
|
|
3759
|
+
}
|
|
3760
|
+
}
|
|
3483
3761
|
if (this.conversationListeners.has(target.conversationId)) {
|
|
3484
3762
|
for (const delivery of deliveries) {
|
|
3485
3763
|
await writeMailboxDelivery(this.mailboxDirectory, target.conversationId, delivery);
|
|
@@ -3500,21 +3778,58 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3500
3778
|
}
|
|
3501
3779
|
/** Start one run with everything held for a conversation, once nothing else holds it. */
|
|
3502
3780
|
async flushHeldDeliveries(conversationId) {
|
|
3503
|
-
if (!this.started) return;
|
|
3781
|
+
if (!this.started || this.stopping) return;
|
|
3504
3782
|
if (this.gate.busy(conversationId)) return;
|
|
3505
3783
|
if (this.conversationListeners.has(conversationId)) return;
|
|
3506
3784
|
const held = this.heldDeliveries.get(conversationId);
|
|
3507
3785
|
if (!held || held.deliveries.length === 0) return;
|
|
3786
|
+
const records = this.data.listEvents ? await Effect5.runPromise(this.data.listEvents()) : [];
|
|
3787
|
+
const pending = records.filter((record) => held.deliveries.some((delivery) => delivery.durable?.id === record.id) && record.status === "pending");
|
|
3788
|
+
const now = Date.now();
|
|
3789
|
+
for (const record of pending) {
|
|
3790
|
+
if (record.event.expiresAt && Date.parse(record.event.expiresAt) <= now) await Effect5.runPromise(this.data.putEvent({ ...record, status: "expired", runId: void 0 }));
|
|
3791
|
+
}
|
|
3792
|
+
const live = pending.filter((record) => !record.event.expiresAt || Date.parse(record.event.expiresAt) > now);
|
|
3793
|
+
held.deliveries = held.deliveries.filter((delivery) => live.some((record) => record.id === delivery.durable?.id));
|
|
3794
|
+
if (!held.deliveries.length) {
|
|
3795
|
+
this.heldDeliveries.delete(conversationId);
|
|
3796
|
+
return;
|
|
3797
|
+
}
|
|
3798
|
+
if (!live.some((record) => eventDue(record, now))) {
|
|
3799
|
+
const deadlines = live.flatMap((record) => [
|
|
3800
|
+
...record.policy.deferTimeoutMs !== void 0 ? [Date.parse(record.createdAt) + record.policy.deferTimeoutMs] : [],
|
|
3801
|
+
...record.event.expiresAt ? [Date.parse(record.event.expiresAt)] : []
|
|
3802
|
+
]);
|
|
3803
|
+
const previous = this.eventTimers.get(conversationId);
|
|
3804
|
+
if (previous) clearTimeout(previous);
|
|
3805
|
+
if (deadlines.length) {
|
|
3806
|
+
const timer = setTimeout(() => {
|
|
3807
|
+
this.eventTimers.delete(conversationId);
|
|
3808
|
+
void this.inConversation(conversationId, () => this.flushHeldDeliveries(conversationId)).catch((cause) => this.reportDeliveryFailure(conversationId, cause));
|
|
3809
|
+
}, Math.max(1, Math.min(2147483647, Math.min(...deadlines) - now)));
|
|
3810
|
+
timer.unref();
|
|
3811
|
+
this.eventTimers.set(conversationId, timer);
|
|
3812
|
+
}
|
|
3813
|
+
return;
|
|
3814
|
+
}
|
|
3508
3815
|
this.heldDeliveries.delete(conversationId);
|
|
3509
3816
|
const { target, deliveries } = held;
|
|
3817
|
+
const owner = await Effect5.runPromise(this.data.getAgent(target.agentId));
|
|
3818
|
+
if (owner?.durableSubagent) {
|
|
3819
|
+
try {
|
|
3820
|
+
await this.assertDurableActive(owner);
|
|
3821
|
+
} catch {
|
|
3822
|
+
return;
|
|
3823
|
+
}
|
|
3824
|
+
}
|
|
3510
3825
|
const runId = await this.enqueueCoreRequest(target.definitionId, {
|
|
3511
3826
|
agentId: target.agentId,
|
|
3512
3827
|
conversationId,
|
|
3513
3828
|
workspaceId: target.workspaceId,
|
|
3829
|
+
...deliveries.length === 1 ? deliveries[0].request : {},
|
|
3514
3830
|
message: renderDeliveries(deliveries),
|
|
3515
|
-
|
|
3516
|
-
|
|
3517
|
-
});
|
|
3831
|
+
source: deliveries.length === 1 && deliveries[0].request?.source ? deliveries[0].request.source : deliverySource(deliveries)
|
|
3832
|
+
}, { eventTurn: true });
|
|
3518
3833
|
this.occupyConversation(conversationId, runId);
|
|
3519
3834
|
await this.markHandedOver(deliveries, runId);
|
|
3520
3835
|
this.observability.append({
|
|
@@ -3525,20 +3840,76 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3525
3840
|
data: { conversationId, mode: "run", count: deliveries.length }
|
|
3526
3841
|
});
|
|
3527
3842
|
}
|
|
3528
|
-
/** Clear the bookkeeping that lets a restart hand these deliveries over again. */
|
|
3529
3843
|
async markHandedOver(deliveries, runId) {
|
|
3844
|
+
if (!this.data.listEvents || !this.data.putEvent) return;
|
|
3845
|
+
const ids = new Set(deliveries.flatMap((delivery) => delivery.durable ? [delivery.durable.id] : []));
|
|
3846
|
+
for (const record of await Effect5.runPromise(this.data.listEvents())) {
|
|
3847
|
+
if (!ids.has(record.id) || record.status !== "pending") continue;
|
|
3848
|
+
const acknowledged = runId && this.completedEventRuns.get(runId)?.has(record.id);
|
|
3849
|
+
await Effect5.runPromise(this.data.putEvent({ ...record, runId, ...acknowledged ? { status: "acknowledged" } : {} }));
|
|
3850
|
+
}
|
|
3851
|
+
}
|
|
3852
|
+
async finishEvents(runId, consumed) {
|
|
3853
|
+
if (!this.data.listEvents || !this.data.putEvent || this.stopping) return;
|
|
3854
|
+
const run = await this.getRun(runId);
|
|
3855
|
+
const ids = new Set(consumed);
|
|
3856
|
+
this.completedEventRuns.set(runId, ids);
|
|
3857
|
+
if (this.completedEventRuns.size > 1e3) this.completedEventRuns.delete(this.completedEventRuns.keys().next().value);
|
|
3858
|
+
for (const record of await Effect5.runPromise(this.data.listEvents())) {
|
|
3859
|
+
if (record.status !== "pending" || !ids.has(record.id) || record.target.agentId !== run?.agentId || record.target.conversationId !== run?.conversationId) continue;
|
|
3860
|
+
const owner = await Effect5.runPromise(this.data.getAgent(record.target.agentId));
|
|
3861
|
+
if (!owner) continue;
|
|
3862
|
+
try {
|
|
3863
|
+
await this.assertDurableActive(owner);
|
|
3864
|
+
} catch {
|
|
3865
|
+
continue;
|
|
3866
|
+
}
|
|
3867
|
+
await Effect5.runPromise(this.data.putEvent({ ...record, status: record.event.expiresAt && Date.parse(record.event.expiresAt) <= Date.now() ? "expired" : "acknowledged", runId }));
|
|
3868
|
+
if ((record.delivery.kind === "transmission" || record.delivery.kind === "agent-message") && this.data.deletePendingInbound) {
|
|
3869
|
+
await Effect5.runPromise(this.data.deletePendingInbound(record.delivery.pendingId));
|
|
3870
|
+
}
|
|
3871
|
+
}
|
|
3872
|
+
}
|
|
3873
|
+
async redeliverEvents(agentId) {
|
|
3874
|
+
if (!this.data.listEvents) return;
|
|
3875
|
+
for (const record of await Effect5.runPromise(this.data.listEvents())) {
|
|
3876
|
+
if (record.status !== "pending" || agentId && record.target.agentId !== agentId) continue;
|
|
3877
|
+
if (record.runId) {
|
|
3878
|
+
const run = await this.getRun(record.runId);
|
|
3879
|
+
if (run && !["completed", "failed", "cancelled"].includes(run.status)) continue;
|
|
3880
|
+
if (run?.status === "completed" && run.output?.consumedEventIds?.includes(record.id)) {
|
|
3881
|
+
await this.finishEvents(run.id, [record.id]);
|
|
3882
|
+
continue;
|
|
3883
|
+
}
|
|
3884
|
+
}
|
|
3885
|
+
const owner = await Effect5.runPromise(this.data.getAgent(record.target.agentId));
|
|
3886
|
+
if (!owner) continue;
|
|
3887
|
+
try {
|
|
3888
|
+
await this.assertDurableActive(owner);
|
|
3889
|
+
} catch {
|
|
3890
|
+
continue;
|
|
3891
|
+
}
|
|
3892
|
+
await this.deliver({ ...record.target, definitionId: record.definitionId, workspaceId: record.workspaceId }, [{ ...record.delivery, durable: { id: record.id, event: record.event, policy: record.policy } }], true);
|
|
3893
|
+
}
|
|
3894
|
+
}
|
|
3895
|
+
/** Clear the bookkeeping that lets a restart hand these deliveries over again. */
|
|
3896
|
+
async markLegacyHandedOver(deliveries, runId) {
|
|
3530
3897
|
for (const delivery of deliveries) {
|
|
3531
|
-
if (delivery.kind === "transmission") {
|
|
3898
|
+
if (delivery.kind === "transmission" || delivery.kind === "agent-message") {
|
|
3532
3899
|
await this.assignPendingInbound(delivery.pendingId, runId);
|
|
3533
3900
|
} else if (delivery.kind === "reply") {
|
|
3534
3901
|
await this.updateDelegation(delivery.delegationId, (current) => {
|
|
3535
3902
|
const pending = [...current.pendingReplies ?? []];
|
|
3536
|
-
const
|
|
3537
|
-
|
|
3538
|
-
|
|
3903
|
+
const pendingIds = [...current.pendingReplyIds ?? []];
|
|
3904
|
+
const index = delivery.deliveryId ? pendingIds.indexOf(delivery.deliveryId) : pending.indexOf(delivery.message);
|
|
3905
|
+
if (index >= 0) {
|
|
3906
|
+
pending.splice(index, 1);
|
|
3907
|
+
pendingIds.splice(index, 1);
|
|
3908
|
+
}
|
|
3909
|
+
return { pendingReplies: pending.length > 0 ? pending : void 0, pendingReplyIds: pendingIds.length ? pendingIds : void 0 };
|
|
3539
3910
|
});
|
|
3540
3911
|
} else {
|
|
3541
|
-
await this.updateDelegation(delivery.delegationId, (current) => current.undelivered === delivery.kind ? { undelivered: void 0 } : {});
|
|
3912
|
+
await this.updateDelegation(delivery.delegationId, (current) => current.undelivered === delivery.kind && (!delivery.deliveryId || current.updateId === delivery.deliveryId) ? { undelivered: void 0 } : {});
|
|
3542
3913
|
}
|
|
3543
3914
|
}
|
|
3544
3915
|
}
|
|
@@ -3565,6 +3936,17 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3565
3936
|
if (!ids) return;
|
|
3566
3937
|
this.pendingInboundByRun.delete(runId);
|
|
3567
3938
|
if (this.stopping || !this.data.deletePendingInbound) return;
|
|
3939
|
+
const pending = this.data.listPendingInbound ? await Effect5.runPromise(this.data.listPendingInbound()) : [];
|
|
3940
|
+
for (const record of pending.filter((item) => ids.has(item.id))) {
|
|
3941
|
+
const agent = await Effect5.runPromise(this.data.getAgent(record.request.agentId));
|
|
3942
|
+
if (agent?.durableSubagent) {
|
|
3943
|
+
try {
|
|
3944
|
+
await this.assertDurableActive(agent);
|
|
3945
|
+
} catch {
|
|
3946
|
+
return;
|
|
3947
|
+
}
|
|
3948
|
+
}
|
|
3949
|
+
}
|
|
3568
3950
|
for (const id2 of ids) await Effect5.runPromise(this.data.deletePendingInbound(id2));
|
|
3569
3951
|
}
|
|
3570
3952
|
/**
|
|
@@ -3577,35 +3959,38 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3577
3959
|
async admitInbound(record) {
|
|
3578
3960
|
if (this.data.putPendingInbound) await Effect5.runPromise(this.data.putPendingInbound(record));
|
|
3579
3961
|
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
3962
|
const source = request.source;
|
|
3586
|
-
|
|
3587
|
-
|
|
3588
|
-
|
|
3589
|
-
|
|
3590
|
-
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
|
|
3594
|
-
|
|
3595
|
-
|
|
3596
|
-
|
|
3597
|
-
|
|
3598
|
-
|
|
3599
|
-
|
|
3600
|
-
);
|
|
3601
|
-
const
|
|
3602
|
-
return
|
|
3963
|
+
let delivery = {
|
|
3964
|
+
kind: source?.kind === "agent-message" ? "agent-message" : "transmission",
|
|
3965
|
+
request,
|
|
3966
|
+
pendingId: record.id,
|
|
3967
|
+
routeId: source?.id ?? "",
|
|
3968
|
+
eventId: source?.eventId ?? "",
|
|
3969
|
+
message: typeof request.message === "string" ? request.message : JSON.stringify(request.message)
|
|
3970
|
+
};
|
|
3971
|
+
if (source?.kind === "delegation") {
|
|
3972
|
+
const event2 = { id: record.id, source: "foundry:delegation", kind: "delegation.task", content: typeof request.message === "string" ? request.message : JSON.stringify(request.message) };
|
|
3973
|
+
delivery = { ...delivery, durable: { id: eventRecordId(request, event2.id), event: event2, policy: this.byRoute.get(record.definitionId)?.definition.eventDelivery ?? {} } };
|
|
3974
|
+
}
|
|
3975
|
+
await this.deliver({ definitionId: record.definitionId, agentId: request.agentId, conversationId: request.conversationId, workspaceId: request.workspaceId }, [delivery]);
|
|
3976
|
+
const event = deliveryEvent(delivery);
|
|
3977
|
+
const journal = this.data.listEvents && (await Effect5.runPromise(this.data.listEvents())).find((item) => item.id === eventRecordId(request, event.id));
|
|
3978
|
+
const handlingRunId = journal?.runId ?? this.gate.activeRun(request.conversationId);
|
|
3979
|
+
return handlingRunId ? this.getRun(handlingRunId) : null;
|
|
3603
3980
|
}
|
|
3604
3981
|
/** After a restart, deliver the inbound events no run had finished with. */
|
|
3605
3982
|
async redeliverInbound() {
|
|
3606
3983
|
if (!this.data.listPendingInbound) return;
|
|
3607
3984
|
const pending = [...await Effect5.runPromise(this.data.listPendingInbound())].sort((left, right) => left.createdAt.localeCompare(right.createdAt));
|
|
3608
3985
|
for (const record of pending) {
|
|
3986
|
+
const owner = await Effect5.runPromise(this.data.getAgent(record.request.agentId));
|
|
3987
|
+
if (owner?.durableSubagent) {
|
|
3988
|
+
try {
|
|
3989
|
+
await this.assertDurableActive(owner);
|
|
3990
|
+
} catch {
|
|
3991
|
+
continue;
|
|
3992
|
+
}
|
|
3993
|
+
}
|
|
3609
3994
|
const { runId: _lost, ...waiting } = record;
|
|
3610
3995
|
await this.admitInbound(waiting);
|
|
3611
3996
|
}
|
|
@@ -3613,6 +3998,31 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3613
3998
|
/** After a restart, hand over whatever was waiting when the runtime stopped. */
|
|
3614
3999
|
async redeliverDelegations() {
|
|
3615
4000
|
for (const delegation of await this.listDelegations()) {
|
|
4001
|
+
const worker = await Effect5.runPromise(this.data.getAgent(delegation.workerAgentId));
|
|
4002
|
+
if (worker && delegation.status === "working" && !delegation.pendingReplies?.length && this.data.listPendingInbound) {
|
|
4003
|
+
let active = true;
|
|
4004
|
+
try {
|
|
4005
|
+
await this.assertDurableActive(worker);
|
|
4006
|
+
} catch {
|
|
4007
|
+
active = false;
|
|
4008
|
+
}
|
|
4009
|
+
const pending = await Effect5.runPromise(this.data.listPendingInbound());
|
|
4010
|
+
if (active && !(this.data.listEvents && (await Effect5.runPromise(this.data.listEvents())).some((item) => item.target.conversationId === delegation.id)) && !pending.some((item) => item.request.conversationId === delegation.id) && (await this.loadDelegation(delegation.id))?.status === "working") {
|
|
4011
|
+
await this.admitInbound({
|
|
4012
|
+
id: `task:${delegation.id}`,
|
|
4013
|
+
definitionId: worker.definitionId,
|
|
4014
|
+
createdAt: delegation.createdAt,
|
|
4015
|
+
request: {
|
|
4016
|
+
agentId: worker.id,
|
|
4017
|
+
conversationId: delegation.id,
|
|
4018
|
+
workspaceId: worker.workspaceId,
|
|
4019
|
+
message: renderDelegatedTask({ delegationId: delegation.id, from: delegation.from.definitionId, task: delegation.task }),
|
|
4020
|
+
payload: { delegation },
|
|
4021
|
+
source: { kind: "delegation", id: delegation.id }
|
|
4022
|
+
}
|
|
4023
|
+
});
|
|
4024
|
+
}
|
|
4025
|
+
}
|
|
3616
4026
|
const update = undeliveredUpdate(delegation);
|
|
3617
4027
|
if (update) await this.deliver(this.delegatorTarget(delegation), [update]);
|
|
3618
4028
|
if (delegation.pendingReplies?.length) {
|
|
@@ -3623,7 +4033,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3623
4033
|
conversationId: delegation.id,
|
|
3624
4034
|
workspaceId: delegation.workspaceId
|
|
3625
4035
|
},
|
|
3626
|
-
delegation.pendingReplies.map((message) => ({
|
|
4036
|
+
delegation.pendingReplies.map((message, index) => ({
|
|
4037
|
+
deliveryId: delegation.pendingReplyIds?.[index],
|
|
3627
4038
|
kind: "reply",
|
|
3628
4039
|
delegationId: delegation.id,
|
|
3629
4040
|
from: delegation.from.definitionId,
|
|
@@ -3688,7 +4099,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3688
4099
|
status: "working",
|
|
3689
4100
|
question: void 0,
|
|
3690
4101
|
...current.undelivered === "question" ? { undelivered: void 0 } : {},
|
|
3691
|
-
pendingReplies: [...current.pendingReplies ?? [], command.message]
|
|
4102
|
+
pendingReplies: [...current.pendingReplies ?? [], command.message],
|
|
4103
|
+
pendingReplyIds: [...current.pendingReplyIds ?? [], command.id]
|
|
3692
4104
|
}));
|
|
3693
4105
|
await this.deliver(
|
|
3694
4106
|
{
|
|
@@ -3697,7 +4109,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3697
4109
|
conversationId: delegation.id,
|
|
3698
4110
|
workspaceId: delegation.workspaceId
|
|
3699
4111
|
},
|
|
3700
|
-
[{ kind: "reply", delegationId: delegation.id, from: command.definitionId, message: command.message }]
|
|
4112
|
+
[{ kind: "reply", deliveryId: command.id, delegationId: delegation.id, from: command.definitionId, message: command.message }]
|
|
3701
4113
|
);
|
|
3702
4114
|
this.observability.append({
|
|
3703
4115
|
type: "delegation.replied",
|
|
@@ -3714,10 +4126,12 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3714
4126
|
await this.updateDelegation(delegation.id, {
|
|
3715
4127
|
status: "waiting",
|
|
3716
4128
|
question: command.question,
|
|
3717
|
-
undelivered: "question"
|
|
4129
|
+
undelivered: "question",
|
|
4130
|
+
updateId: command.id
|
|
3718
4131
|
});
|
|
3719
4132
|
await this.deliver(this.delegatorTarget(delegation), [{
|
|
3720
4133
|
kind: "question",
|
|
4134
|
+
deliveryId: command.id,
|
|
3721
4135
|
delegationId: delegation.id,
|
|
3722
4136
|
agent: delegation.to,
|
|
3723
4137
|
task: delegation.task,
|
|
@@ -3738,7 +4152,10 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3738
4152
|
conversationId: command.conversationId,
|
|
3739
4153
|
workspaceId: command.workspaceId
|
|
3740
4154
|
};
|
|
3741
|
-
|
|
4155
|
+
const parentDefinition = this.byRoute.get(command.definitionId)?.definition;
|
|
4156
|
+
const durable = Object.hasOwn(parentDefinition?.durableSubagents ?? {}, command.to) ? parentDefinition.durableSubagents[command.to] : void 0;
|
|
4157
|
+
const targetRoute = durable ? durableRoute(command.definitionId, command.to) : command.to;
|
|
4158
|
+
if (!this.byRoute.has(targetRoute)) {
|
|
3742
4159
|
await this.deliver(from, [{
|
|
3743
4160
|
kind: "failed",
|
|
3744
4161
|
delegationId: command.delegationId,
|
|
@@ -3752,8 +4169,18 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3752
4169
|
if (!delegator || delegator.workspaceId !== command.workspaceId) {
|
|
3753
4170
|
throw new Error("A delegation must come from an agent instance in its workspace.");
|
|
3754
4171
|
}
|
|
3755
|
-
|
|
3756
|
-
|
|
4172
|
+
let ownedWorker;
|
|
4173
|
+
if (durable) {
|
|
4174
|
+
try {
|
|
4175
|
+
if (!this.data.putPendingInbound || !this.data.listPendingInbound || !this.data.deletePendingInbound) throw new Error("Durable delegation requires pending inbound persistence.");
|
|
4176
|
+
ownedWorker = await this.ensureSubagent(command.agentId, command.to);
|
|
4177
|
+
} catch (cause) {
|
|
4178
|
+
await this.deliver(from, [{ kind: "failed", delegationId: command.delegationId, agent: command.to, task: command.task, error: cause instanceof Error ? cause.message : String(cause) }]);
|
|
4179
|
+
return;
|
|
4180
|
+
}
|
|
4181
|
+
}
|
|
4182
|
+
const workerId = ownedWorker?.id ?? workerAgentId(command.agentId, command.to);
|
|
4183
|
+
const worker = ownedWorker ?? await Effect5.runPromise(this.data.getAgent(workerId)) ?? await this.createAgent(command.to, {
|
|
3757
4184
|
id: workerId,
|
|
3758
4185
|
workspaceId: command.workspaceId,
|
|
3759
4186
|
context: {
|
|
@@ -3761,13 +4188,13 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3761
4188
|
delegatedBy: { agentId: command.agentId, definitionId: command.definitionId }
|
|
3762
4189
|
}
|
|
3763
4190
|
});
|
|
3764
|
-
if (worker.definitionId !==
|
|
4191
|
+
if (worker.definitionId !== targetRoute || worker.workspaceId !== command.workspaceId) {
|
|
3765
4192
|
throw new Error(`Agent instance "${workerId}" is not a ${command.to} worker in this workspace.`);
|
|
3766
4193
|
}
|
|
3767
4194
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3768
4195
|
const delegation = Object.freeze({
|
|
3769
4196
|
id: command.delegationId,
|
|
3770
|
-
to:
|
|
4197
|
+
to: targetRoute,
|
|
3771
4198
|
workerAgentId: workerId,
|
|
3772
4199
|
workspaceId: command.workspaceId,
|
|
3773
4200
|
from: Object.freeze({
|
|
@@ -3788,15 +4215,16 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3788
4215
|
title: title.length > 80 ? `${title.slice(0, 79)}\u2026` : title,
|
|
3789
4216
|
context: { delegation }
|
|
3790
4217
|
});
|
|
3791
|
-
const
|
|
4218
|
+
const workerRequest = {
|
|
3792
4219
|
agentId: workerId,
|
|
3793
4220
|
conversationId: delegation.id,
|
|
3794
4221
|
workspaceId: command.workspaceId,
|
|
3795
4222
|
message: renderDelegatedTask({ delegationId: delegation.id, from: command.definitionId, task: command.task }),
|
|
3796
4223
|
payload: { delegation },
|
|
3797
4224
|
source: { kind: "delegation", id: delegation.id }
|
|
3798
|
-
}
|
|
3799
|
-
this.
|
|
4225
|
+
};
|
|
4226
|
+
const runId = (await this.admitInbound({ id: `task:${delegation.id}`, definitionId: targetRoute, request: workerRequest, createdAt: now }))?.id;
|
|
4227
|
+
if (runId) this.occupyConversation(delegation.id, runId);
|
|
3800
4228
|
this.observability.append({
|
|
3801
4229
|
type: "delegation.started",
|
|
3802
4230
|
category: "system",
|
|
@@ -3809,26 +4237,48 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3809
4237
|
async handleRunSettled(event) {
|
|
3810
4238
|
this.releaseConversationRun(event.run.id);
|
|
3811
4239
|
void this.waitForRunProcessRelease(this.toFoundryRun(event.run), event.route).finally(() => this.gate.settled(event.run.id));
|
|
3812
|
-
|
|
3813
|
-
|
|
3814
|
-
|
|
4240
|
+
const finishDelivery = async () => {
|
|
4241
|
+
this.settledRuns.add(event.run.id);
|
|
4242
|
+
if (this.settledRuns.size > 1e3) this.settledRuns.delete(this.settledRuns.values().next().value);
|
|
4243
|
+
if (event.status === "completed") {
|
|
4244
|
+
const result = parseJson(event.output);
|
|
4245
|
+
await this.finishEvents(event.run.id, result?.consumedEventIds ?? []);
|
|
4246
|
+
}
|
|
4247
|
+
await this.finishPendingInbound(event.run.id).catch((cause) => this.reportDeliveryFailure(this.toFoundryRun(event.run).conversationId ?? "settle", cause));
|
|
4248
|
+
};
|
|
3815
4249
|
const steered = this.steeredRuns.delete(event.run.id);
|
|
3816
4250
|
const run = this.toFoundryRun(event.run);
|
|
3817
|
-
if (!run.conversationId || !isDelegationId(run.conversationId))
|
|
4251
|
+
if (!run.conversationId || !isDelegationId(run.conversationId)) {
|
|
4252
|
+
await finishDelivery();
|
|
4253
|
+
return;
|
|
4254
|
+
}
|
|
3818
4255
|
const delegation = await this.loadDelegation(run.conversationId);
|
|
3819
|
-
if (!delegation || run.agentId !== delegation.workerAgentId)
|
|
4256
|
+
if (!delegation || run.agentId !== delegation.workerAgentId) {
|
|
4257
|
+
await finishDelivery();
|
|
4258
|
+
return;
|
|
4259
|
+
}
|
|
4260
|
+
if (this.stopping && event.status !== "completed") {
|
|
4261
|
+
const worker = await Effect5.runPromise(this.data.getAgent(delegation.workerAgentId));
|
|
4262
|
+
if (worker?.durableSubagent) return;
|
|
4263
|
+
}
|
|
3820
4264
|
if (event.status === "completed") {
|
|
3821
4265
|
const output = parseJson(event.output);
|
|
3822
|
-
if (output?.status === "suspended")
|
|
4266
|
+
if (output?.status === "suspended") {
|
|
4267
|
+
await finishDelivery();
|
|
4268
|
+
return;
|
|
4269
|
+
}
|
|
3823
4270
|
const result = deliveryText(output?.value);
|
|
3824
4271
|
await this.updateDelegation(delegation.id, {
|
|
3825
4272
|
status: "completed",
|
|
3826
4273
|
result,
|
|
3827
4274
|
question: void 0,
|
|
3828
|
-
undelivered: "result"
|
|
4275
|
+
undelivered: "result",
|
|
4276
|
+
updateId: `result:${event.run.id}`
|
|
3829
4277
|
});
|
|
4278
|
+
await finishDelivery();
|
|
3830
4279
|
await this.deliver(this.delegatorTarget(delegation), [{
|
|
3831
4280
|
kind: "result",
|
|
4281
|
+
deliveryId: `result:${event.run.id}`,
|
|
3832
4282
|
delegationId: delegation.id,
|
|
3833
4283
|
agent: delegation.to,
|
|
3834
4284
|
task: delegation.task,
|
|
@@ -3843,15 +4293,21 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3843
4293
|
});
|
|
3844
4294
|
return;
|
|
3845
4295
|
}
|
|
3846
|
-
if (event.status === "cancelled" && steered)
|
|
4296
|
+
if (event.status === "cancelled" && steered) {
|
|
4297
|
+
await finishDelivery();
|
|
4298
|
+
return;
|
|
4299
|
+
}
|
|
3847
4300
|
const error = event.status === "cancelled" ? "The work was cancelled." : event.error ?? "The run failed.";
|
|
3848
4301
|
await this.updateDelegation(delegation.id, {
|
|
3849
4302
|
status: event.status === "cancelled" ? "cancelled" : "failed",
|
|
3850
4303
|
error,
|
|
3851
|
-
undelivered: "failed"
|
|
4304
|
+
undelivered: "failed",
|
|
4305
|
+
updateId: `failed:${event.run.id}`
|
|
3852
4306
|
});
|
|
4307
|
+
await finishDelivery();
|
|
3853
4308
|
await this.deliver(this.delegatorTarget(delegation), [{
|
|
3854
4309
|
kind: "failed",
|
|
4310
|
+
deliveryId: `failed:${event.run.id}`,
|
|
3855
4311
|
delegationId: delegation.id,
|
|
3856
4312
|
agent: delegation.to,
|
|
3857
4313
|
task: delegation.task,
|
|
@@ -3865,13 +4321,13 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3865
4321
|
data: { delegationId: delegation.id, error }
|
|
3866
4322
|
});
|
|
3867
4323
|
}
|
|
3868
|
-
async enqueueCoreRequest(definitionId, request) {
|
|
4324
|
+
async enqueueCoreRequest(definitionId, request, options = {}) {
|
|
3869
4325
|
const discovered = this.byRoute.get(definitionId);
|
|
3870
4326
|
if (!discovered) throw new Error(`Foundry agent definition "${definitionId}" was not found.`);
|
|
3871
4327
|
const agent = await Effect5.runPromise(this.data.getAgent(request.agentId));
|
|
3872
4328
|
const conversation = await Effect5.runPromise(this.data.getConversation(request.conversationId));
|
|
3873
4329
|
if (!agent || !conversation) throw new Error("Core command references an unknown agent instance or conversation.");
|
|
3874
|
-
return this.admitRun(discovered.executionName, request);
|
|
4330
|
+
return this.admitRun(discovered.executionName, request, options);
|
|
3875
4331
|
}
|
|
3876
4332
|
/**
|
|
3877
4333
|
* Create the run for a request through its conversation's gate: it starts
|
|
@@ -3885,12 +4341,12 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3885
4341
|
request.conversationId,
|
|
3886
4342
|
async (parked) => this.signalRunner.triggerSignal(
|
|
3887
4343
|
executionName,
|
|
3888
|
-
await this.executionEnvelope(request, { leased: true }),
|
|
4344
|
+
await this.executionEnvelope(request, { leased: true, eventTurn: options.eventTurn }),
|
|
3889
4345
|
{ parked }
|
|
3890
4346
|
),
|
|
3891
4347
|
async (runId) => this.signalRunner.releaseRun(
|
|
3892
4348
|
runId,
|
|
3893
|
-
await this.executionEnvelope(request, { leased: true })
|
|
4349
|
+
await this.executionEnvelope(request, { leased: true, eventTurn: options.eventTurn })
|
|
3894
4350
|
),
|
|
3895
4351
|
options
|
|
3896
4352
|
);
|
|
@@ -3908,8 +4364,22 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
3908
4364
|
return this.executeCoreCommandUnlocked(command, parentRunId);
|
|
3909
4365
|
}
|
|
3910
4366
|
async executeCoreCommandUnlocked(command, parentRunId) {
|
|
4367
|
+
if (command.type === "agent.message") {
|
|
4368
|
+
try {
|
|
4369
|
+
const output = await this.executeAgentMessage(command);
|
|
4370
|
+
await settleFoundryCoreCommandRequest(this.coreCommandDirectory, command.id, { status: "success", output });
|
|
4371
|
+
} catch (cause) {
|
|
4372
|
+
await settleFoundryCoreCommandRequest(this.coreCommandDirectory, command.id, { status: "error", error: cause instanceof Error ? cause.message : String(cause) });
|
|
4373
|
+
}
|
|
4374
|
+
return;
|
|
4375
|
+
}
|
|
4376
|
+
if (command.agentId) {
|
|
4377
|
+
const sender = await Effect5.runPromise(this.data.getAgent(command.agentId));
|
|
4378
|
+
if (sender) await this.assertDurableActive(sender);
|
|
4379
|
+
}
|
|
3911
4380
|
if (command.type === "delegate" || command.type === "delegate.reply" || command.type === "delegate.ask") {
|
|
3912
|
-
await this.executeDelegationCommand(command, parentRunId);
|
|
4381
|
+
if (command.type === "delegate") await this.inConversation("durable:mutations", () => this.executeDelegationCommand(command, parentRunId));
|
|
4382
|
+
else await this.executeDelegationCommand(command, parentRunId);
|
|
3913
4383
|
return;
|
|
3914
4384
|
}
|
|
3915
4385
|
if (command.type === "transmit") {
|
|
@@ -4094,7 +4564,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4094
4564
|
playbooks: Object.freeze([...instancePlaybooks, ...reconciled]),
|
|
4095
4565
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4096
4566
|
};
|
|
4097
|
-
this.validatePlaybooks(command.definitionId, updated.playbooks, updated.installations);
|
|
4567
|
+
this.validatePlaybooks(command.definitionId, updated.playbooks, (await this.effectiveAgent(updated)).installations);
|
|
4098
4568
|
await Effect5.runPromise(this.data.putAgent(updated));
|
|
4099
4569
|
await this.reconcileApplicationConnections();
|
|
4100
4570
|
this.observability.append({
|
|
@@ -4290,6 +4760,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4290
4760
|
);
|
|
4291
4761
|
}
|
|
4292
4762
|
const storedAgent = await Effect5.runPromise(this.data.getAgent(activation.agentId));
|
|
4763
|
+
if (storedAgent) await this.assertDurableActive(storedAgent);
|
|
4293
4764
|
const storedConversation = await Effect5.runPromise(
|
|
4294
4765
|
this.data.getConversation(activation.conversationId)
|
|
4295
4766
|
);
|
|
@@ -4453,15 +4924,24 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4453
4924
|
const agent = await Effect5.runPromise(this.data.getAgent(request.agentId));
|
|
4454
4925
|
const conversation = await Effect5.runPromise(this.data.getConversation(request.conversationId));
|
|
4455
4926
|
if (!agent || !conversation) throw new Error("Cannot schedule an unknown agent instance or conversation.");
|
|
4927
|
+
const effective = await this.effectiveAgent(agent);
|
|
4928
|
+
const owners = {};
|
|
4929
|
+
let ancestor = agent;
|
|
4930
|
+
while (ancestor.durableSubagent) {
|
|
4931
|
+
ancestor = await Effect5.runPromise(this.data.getAgent(ancestor.durableSubagent.parentAgentId));
|
|
4932
|
+
owners[ancestor.definitionId] = { id: ancestor.id, definitionId: ancestor.definitionId, workspaceId: ancestor.workspaceId };
|
|
4933
|
+
}
|
|
4456
4934
|
const activations = (await Effect5.runPromise(this.data.listActivations(request.workspaceId))).filter((activation) => activation.agentId === request.agentId);
|
|
4457
4935
|
const delegations = await this.openDelegationsFrom(request.agentId, request.conversationId);
|
|
4458
4936
|
return {
|
|
4459
4937
|
[FOUNDRY_EXECUTION_MARKER]: true,
|
|
4460
|
-
request,
|
|
4461
|
-
|
|
4938
|
+
request: { ...request, context: { ...request.context, durableMemoryOwners: owners } },
|
|
4939
|
+
eventTurn: options.eventTurn ?? false,
|
|
4940
|
+
agent: effective,
|
|
4462
4941
|
conversation,
|
|
4463
4942
|
activations,
|
|
4464
4943
|
delegations,
|
|
4944
|
+
events: options.leased && this.data.listEvents ? (await Effect5.runPromise(this.data.listEvents())).filter((record) => record.status === "pending" && record.target.agentId === agent.id && record.target.conversationId === conversation.id).map((record) => ({ ...record.delivery, durable: { id: record.id, event: record.event, policy: record.policy } })) : [],
|
|
4465
4945
|
...options.leased ? { conversationLease: true } : {}
|
|
4466
4946
|
};
|
|
4467
4947
|
}
|
|
@@ -6136,6 +6616,49 @@ var FoundryServer = class {
|
|
|
6136
6616
|
}));
|
|
6137
6617
|
return;
|
|
6138
6618
|
}
|
|
6619
|
+
if (url.pathname === "/api/events" && method === "POST") {
|
|
6620
|
+
const body = await readJson(request);
|
|
6621
|
+
if (!body.target || typeof body.target.agentId !== "string" || typeof body.target.conversationId !== "string") throw new RequestError(400, "target.agentId and target.conversationId are required.");
|
|
6622
|
+
json(response, 202, await this.runtime.emitEvent(body.target, body.event, body.policy));
|
|
6623
|
+
return;
|
|
6624
|
+
}
|
|
6625
|
+
const workerRoute = url.pathname.match(/^\/api\/agent-instances\/([^/]+)\/subagents(?:\/([^/]+))?(?:\/(messages|data|archive|resume|purge))?$/);
|
|
6626
|
+
if (workerRoute) {
|
|
6627
|
+
const parent = decodeURIComponent(workerRoute[1]);
|
|
6628
|
+
const name = workerRoute[2] ? decodeURIComponent(workerRoute[2]) : void 0;
|
|
6629
|
+
const action = workerRoute[3];
|
|
6630
|
+
if (!name && method === "GET") {
|
|
6631
|
+
json(response, 200, await this.runtime.listSubagents(parent));
|
|
6632
|
+
return;
|
|
6633
|
+
}
|
|
6634
|
+
if (name && !action && method === "POST") {
|
|
6635
|
+
json(response, 200, await this.runtime.subagent(parent, name));
|
|
6636
|
+
return;
|
|
6637
|
+
}
|
|
6638
|
+
if (name && action === "data" && method === "GET") {
|
|
6639
|
+
json(response, 200, await this.runtime.subagentData(parent, name));
|
|
6640
|
+
return;
|
|
6641
|
+
}
|
|
6642
|
+
if (name && action === "messages" && method === "POST") {
|
|
6643
|
+
const body = await readJson(request);
|
|
6644
|
+
if (typeof body.message !== "string") throw new RequestError(400, "message is required.");
|
|
6645
|
+
json(response, 202, await this.runtime.messageSubagent(parent, name, body.message, body.delivery));
|
|
6646
|
+
return;
|
|
6647
|
+
}
|
|
6648
|
+
if (name && action === "archive" && method === "POST") {
|
|
6649
|
+
json(response, 200, await this.runtime.archiveSubagent(parent, name));
|
|
6650
|
+
return;
|
|
6651
|
+
}
|
|
6652
|
+
if (name && action === "resume" && method === "POST") {
|
|
6653
|
+
json(response, 200, await this.runtime.resumeSubagent(parent, name));
|
|
6654
|
+
return;
|
|
6655
|
+
}
|
|
6656
|
+
if (name && action === "purge" && method === "POST") {
|
|
6657
|
+
await this.runtime.purgeSubagent(parent, name);
|
|
6658
|
+
json(response, 200, { purged: true });
|
|
6659
|
+
return;
|
|
6660
|
+
}
|
|
6661
|
+
}
|
|
6139
6662
|
const instanceConfiguration = url.pathname.match(/^\/api\/agent-instances\/([^/]+)$/);
|
|
6140
6663
|
if (instanceConfiguration && method === "PATCH") {
|
|
6141
6664
|
const body = await readJson(request);
|