glove-foundry 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,27 @@
1
1
  import {
2
+ DURABLE_SEGMENT,
3
+ EMPTY_CAPABILITY_REGISTRY,
2
4
  EMPTY_NATIVE_REGISTRY,
5
+ FOUNDRY_AGENT_APPLICATION_BRAND,
6
+ FOUNDRY_CORE_COMMAND_DIRECTORY_ENV,
3
7
  FOUNDRY_LAYER_BRAND,
8
+ FOUNDRY_MCP_BRAND,
9
+ FOUNDRY_MEMORY_BRAND,
10
+ FOUNDRY_SHARED_TOOL_BRAND,
4
11
  FOUNDRY_SUBSCRIBER_BRAND,
5
12
  bindFileIdentity,
13
+ composeDurableAgent,
14
+ createFoundryCoreCommandRequest,
6
15
  defineAgentFromModule,
16
+ defineSharedTool,
17
+ durableRoute,
7
18
  fileDefinitionKey,
8
19
  fileDefinitionLabel,
9
20
  fileIdentified,
10
- internalAgentName
11
- } from "./chunk-K2EU63MB.js";
21
+ installationKey,
22
+ internalAgentName,
23
+ waitForFoundryCoreCommandResult
24
+ } from "./chunk-CYOIHSUX.js";
12
25
 
13
26
  // src/application.ts
14
27
  var FOUNDRY_APPLICATION_BRAND = /* @__PURE__ */ Symbol.for(
@@ -48,369 +61,6 @@ var EMPTY_FOUNDRY_APPLICATION = defineApplication({
48
61
  name: "Glove Foundry"
49
62
  });
50
63
 
51
- // src/capabilities.ts
52
- import { Effect } from "effect";
53
- import { mountMcp } from "glove-mcp";
54
- import {
55
- useContext,
56
- useEpisodicCurator,
57
- useEpisodicReader,
58
- useMemoryCurator,
59
- useMemoryReader,
60
- useResourcesCurator,
61
- useResourcesReader
62
- } from "glove-memory/tools";
63
- var FOUNDRY_SHARED_TOOL_BRAND = /* @__PURE__ */ Symbol.for(
64
- "glove-foundry-shared-tool"
65
- );
66
- var FOUNDRY_AGENT_APPLICATION_BRAND = /* @__PURE__ */ Symbol.for(
67
- "glove-foundry-agent-application"
68
- );
69
- var FOUNDRY_MCP_BRAND = /* @__PURE__ */ Symbol.for("glove-foundry-mcp");
70
- var FOUNDRY_MEMORY_BRAND = /* @__PURE__ */ Symbol.for("glove-foundry-memory");
71
- function install(capability, ...configuration) {
72
- const config = configuration[0];
73
- const selection = configuration[1];
74
- const kind = FOUNDRY_SHARED_TOOL_BRAND in capability ? "tool" : FOUNDRY_AGENT_APPLICATION_BRAND in capability ? "application" : "mcp";
75
- const installation = {
76
- kind,
77
- ...config !== void 0 ? { config } : {}
78
- };
79
- Object.defineProperty(installation, "id", {
80
- enumerable: true,
81
- get: () => capability.id
82
- });
83
- if (selection?.account) {
84
- Object.defineProperty(installation, "accountId", {
85
- enumerable: true,
86
- get: () => selection.account.id
87
- });
88
- }
89
- return Object.freeze(installation);
90
- }
91
- function installationKey(installation) {
92
- return `${installation.kind}:${installation.id}`;
93
- }
94
- function assertCapabilityId(id2, label) {
95
- if (!/^[a-z][a-z0-9-]*(?:\/[a-z][a-z0-9-]*)*$/.test(id2)) {
96
- throw new Error(
97
- `Invalid Foundry ${label} id "${id2}". Use lowercase path segments containing letters, digits, and hyphens.`
98
- );
99
- }
100
- }
101
- function decodeCapabilityConfig(definition, installation) {
102
- if (!definition.config) return installation.config;
103
- const parsed = definition.config.safeParse(installation.config ?? {});
104
- if (!parsed.success) {
105
- throw new Error(
106
- `Invalid config for ${installation.kind} "${definition.id}": ${parsed.error.message}`
107
- );
108
- }
109
- return parsed.data;
110
- }
111
- function defineSharedTool(options) {
112
- if (options.id) assertCapabilityId(options.id, "shared tool");
113
- const { id: id2, ...definition } = options;
114
- return Object.freeze(fileIdentified({
115
- ...definition,
116
- [FOUNDRY_SHARED_TOOL_BRAND]: true
117
- }, "tool", id2));
118
- }
119
- function defineAgentApplication(options) {
120
- if (options.id) assertCapabilityId(options.id, "agent application");
121
- const label = options.id ?? "<application file route>";
122
- const inbound = Object.freeze([...options.inbound ?? []]);
123
- const outbound = Object.freeze([...options.outbound ?? []]);
124
- for (const transmission of inbound) {
125
- if (!transmission.inbound) {
126
- throw new Error(
127
- `Application "${label}" declares an outbound-only transmission as inbound.`
128
- );
129
- }
130
- }
131
- for (const transmission of outbound) {
132
- if (!transmission.outbound) {
133
- throw new Error(
134
- `Application "${label}" declares an inbound-only transmission as outbound.`
135
- );
136
- }
137
- }
138
- const transmissionDefinitions = /* @__PURE__ */ new Map();
139
- for (const transmission of [
140
- ...options.transmissions ?? [],
141
- ...inbound,
142
- ...outbound
143
- ]) {
144
- const key = fileDefinitionKey(transmission);
145
- const existing = transmissionDefinitions.get(key);
146
- if (!existing) transmissionDefinitions.set(key, transmission);
147
- }
148
- const transmissions = Object.freeze([...transmissionDefinitions.values()]);
149
- const connections = Object.freeze([...options.connections ?? []]);
150
- const connectionIds = /* @__PURE__ */ new Set();
151
- for (const connection of connections) {
152
- const connectionKey = fileDefinitionKey(connection);
153
- if (connectionIds.has(connectionKey)) {
154
- throw new Error(`Application "${label}" contains the same connection more than once.`);
155
- }
156
- connectionIds.add(connectionKey);
157
- for (const transmission of connection.transmissions) {
158
- if (!transmissionDefinitions.has(fileDefinitionKey(transmission))) {
159
- throw new Error(
160
- `Application "${label}" contains a connection for a transmission it does not own.`
161
- );
162
- }
163
- }
164
- }
165
- const { id: id2, ...definition } = options;
166
- return Object.freeze(fileIdentified({
167
- ...definition,
168
- inbound,
169
- outbound,
170
- transmissions,
171
- connections,
172
- [FOUNDRY_AGENT_APPLICATION_BRAND]: true
173
- }, "application", id2));
174
- }
175
- var defineApp = defineAgentApplication;
176
- function identifyMcpEntry(entry, id2) {
177
- if (entry.transport) return { ...entry, id: id2 };
178
- return { ...entry, id: id2, url: entry.url };
179
- }
180
- function defineMcp(options) {
181
- if (options.id) assertCapabilityId(options.id, "MCP");
182
- const { id: id2, ...definition } = options;
183
- return Object.freeze(fileIdentified({
184
- ...definition,
185
- [FOUNDRY_MCP_BRAND]: true
186
- }, "mcp", id2));
187
- }
188
- function defineMemory(options) {
189
- if (options.id) assertCapabilityId(options.id, "memory profile");
190
- if (!options.entity && !options.episodic && !options.resources && !options.context && !options.mount) {
191
- throw new Error(`Foundry memory profile "${options.id ?? "<file route>"}" is empty.`);
192
- }
193
- const { id: id2, ...definition } = options;
194
- return Object.freeze(fileIdentified({
195
- ...definition,
196
- [FOUNDRY_MEMORY_BRAND]: true
197
- }, "memory", id2));
198
- }
199
- var EMPTY_CAPABILITY_REGISTRY = Object.freeze({
200
- tools: Object.freeze([]),
201
- applications: Object.freeze([]),
202
- mcp: Object.freeze([]),
203
- memory: Object.freeze([])
204
- });
205
- function inboxMethods(store) {
206
- return typeof store.getInboxItems === "function" && typeof store.addInboxItem === "function" && typeof store.updateInboxItem === "function" && typeof store.getResolvedInboxItems === "function";
207
- }
208
- function isInboxCapableStore(store) {
209
- return inboxMethods(store);
210
- }
211
- function indexRegistry(values, kind) {
212
- const result = /* @__PURE__ */ new Map();
213
- for (const value of values) {
214
- if (result.has(value.id)) {
215
- throw new Error(`Duplicate Foundry ${kind} id "${value.id}".`);
216
- }
217
- result.set(value.id, value);
218
- }
219
- return result;
220
- }
221
- function mountMemory(profile, context) {
222
- return Effect.gen(function* () {
223
- if (profile.entity) {
224
- const adapter = yield* profile.entity.adapter(context);
225
- const options = profile.entity.tools ? { tools: profile.entity.tools } : void 0;
226
- if ((profile.entity.access ?? "reader") === "curator") {
227
- useMemoryCurator(context.glove, adapter, options);
228
- } else {
229
- useMemoryReader(context.glove, adapter, options);
230
- }
231
- }
232
- if (profile.episodic) {
233
- const adapter = yield* profile.episodic.adapter(context);
234
- const options = profile.episodic.tools ? { tools: profile.episodic.tools } : void 0;
235
- if ((profile.episodic.access ?? "reader") === "curator") {
236
- useEpisodicCurator(context.glove, adapter, options);
237
- } else {
238
- useEpisodicReader(context.glove, adapter, options);
239
- }
240
- }
241
- if (profile.resources) {
242
- const adapter = yield* profile.resources.adapter(context);
243
- const options = profile.resources.tools ? { tools: profile.resources.tools } : void 0;
244
- if ((profile.resources.access ?? "reader") === "curator") {
245
- useResourcesCurator(context.glove, adapter, options);
246
- } else {
247
- useResourcesReader(context.glove, adapter, options);
248
- }
249
- }
250
- if (profile.context) {
251
- const adapter = yield* profile.context.adapter(context);
252
- useContext(
253
- context.glove,
254
- adapter,
255
- profile.context.tools ? { tools: profile.context.tools } : void 0
256
- );
257
- }
258
- if (profile.mount) yield* profile.mount(context);
259
- });
260
- }
261
- function configureMemory(profile, config) {
262
- return Object.freeze({ profile, config });
263
- }
264
- function mountAgentDefinitionMemory(options) {
265
- return Effect.gen(function* () {
266
- const memory = indexRegistry(options.registry.memory, "memory profile");
267
- const seen = /* @__PURE__ */ new Set();
268
- for (const selection of options.memory) {
269
- const reference = "profile" in selection ? selection.profile : selection;
270
- const profile = memory.get(reference.id);
271
- if (!profile) {
272
- throw new Error(`Unknown agent memory profile "${reference.id}".`);
273
- }
274
- if (seen.has(`memory:${profile.id}`)) {
275
- throw new Error(`Duplicate agent memory profile "${profile.id}".`);
276
- }
277
- seen.add(`memory:${profile.id}`);
278
- const config = typeof selection === "object" && "profile" in selection ? selection.config : void 0;
279
- const capability = {
280
- kind: "memory",
281
- id: profile.id,
282
- ...config !== void 0 ? { config } : {}
283
- };
284
- const context = {
285
- ...options.context,
286
- surface: { kind: "memory", id: profile.id },
287
- config: decodeCapabilityConfig(profile, capability)
288
- };
289
- yield* mountMemory(profile, context);
290
- options.context.emit({
291
- type: "foundry.definition.memory.mounted",
292
- data: { id: profile.id }
293
- });
294
- }
295
- });
296
- }
297
- function installRegistry(options) {
298
- return Effect.gen(function* () {
299
- const tools = indexRegistry(options.registry.tools, "shared tool");
300
- const applications = indexRegistry(
301
- options.registry.applications,
302
- "agent application"
303
- );
304
- const mcp = indexRegistry(options.registry.mcp, "MCP");
305
- const seen = /* @__PURE__ */ new Set();
306
- const installedMcp = [];
307
- const installed = [];
308
- for (const installation of options.installations) {
309
- assertCapabilityId(installation.id, installation.kind);
310
- if (installation.config && typeof installation.config === "object" && Object.prototype.hasOwnProperty.call(installation.config, "accountId")) {
311
- throw new Error(
312
- `Installation config for ${installation.kind} "${installation.id}" cannot contain accountId. Select a persisted account on the installation, or pass { account } as install()'s third argument in code.`
313
- );
314
- }
315
- const key = installationKey(installation);
316
- if (seen.has(key)) continue;
317
- seen.add(key);
318
- const definition = installation.kind === "tool" ? tools.get(installation.id) : installation.kind === "application" ? applications.get(installation.id) : mcp.get(installation.id);
319
- if (!definition) {
320
- throw new Error(
321
- `Agent "${options.context.agentId}" requests unknown ${installation.kind} "${installation.id}".`
322
- );
323
- }
324
- const config = decodeCapabilityConfig(
325
- definition,
326
- installation
327
- );
328
- const context = {
329
- ...options.context,
330
- installation,
331
- config,
332
- ...installation.accountId ? {
333
- accountId: installation.accountId,
334
- ...options.accountSessions ? {
335
- withAccountSession: (operation, use) => options.accountSessions.withSession({
336
- accountId: installation.accountId,
337
- operation,
338
- agentId: options.context.agentId,
339
- conversationId: options.context.conversationId,
340
- workspaceId: options.context.workspaceId
341
- }, use)
342
- } : {}
343
- } : {}
344
- };
345
- if (installation.kind === "tool") {
346
- const shared = definition;
347
- const tool = shared.tool ?? (yield* shared.create(context));
348
- options.context.glove.fold(tool);
349
- } else if (installation.kind === "application") {
350
- const { glove: _glove, store: _store, ...headlessContext } = context;
351
- const application = definition;
352
- const contribution = application.install ? yield* application.install(headlessContext) : void 0;
353
- for (const tool of contribution?.tools ?? []) options.context.glove.fold(tool);
354
- } else {
355
- const mcpDefinition = definition;
356
- const headlessContext = (() => {
357
- const { glove: _glove, store: _store, ...headless } = context;
358
- return headless;
359
- })();
360
- const source = typeof mcpDefinition.entry === "function" ? mcpDefinition.entry(headlessContext) : mcpDefinition.entry;
361
- const entry = Effect.isEffect(source) ? yield* source : source instanceof Promise ? yield* Effect.tryPromise({ try: () => source, catch: (cause) => cause }) : source;
362
- installedMcp.push({
363
- definition: mcpDefinition,
364
- installation,
365
- config,
366
- entry: identifyMcpEntry(entry, mcpDefinition.id)
367
- });
368
- }
369
- installed.push(installation);
370
- options.context.emit({
371
- type: "foundry.installation.completed",
372
- data: { kind: installation.kind, id: installation.id }
373
- });
374
- }
375
- if (installedMcp.length > 0) {
376
- if (!options.mcpAdapter) {
377
- throw new Error(
378
- `Agent "${options.context.agentId}" installs MCP capabilities but the application does not define mcpAdapter.`
379
- );
380
- }
381
- const adapter = yield* options.mcpAdapter({
382
- ...options.context,
383
- installed: installedMcp.map(({ definition }) => definition),
384
- resolved: installedMcp
385
- });
386
- const selectedIds = new Set(installedMcp.map(({ definition }) => definition.id));
387
- const scopedAdapter = {
388
- identifier: adapter.identifier,
389
- getActive: async () => [...selectedIds],
390
- activate: (id2) => adapter.activate(id2),
391
- deactivate: (id2) => adapter.deactivate(id2),
392
- ...adapter.getAccessToken ? { getAccessToken: (id2) => adapter.getAccessToken(id2) } : {},
393
- ...adapter.getAuthHeaders ? { getAuthHeaders: (id2) => adapter.getAuthHeaders(id2) } : {},
394
- ...adapter.getStdioEnvironment ? { getStdioEnvironment: (id2) => adapter.getStdioEnvironment(id2) } : {}
395
- };
396
- yield* Effect.tryPromise({
397
- try: () => mountMcp(options.context.glove, {
398
- adapter: scopedAdapter,
399
- entries: installedMcp.map(({ entry }) => entry),
400
- ambiguityPolicy: { type: "auto-pick-best" }
401
- }),
402
- catch: (cause) => cause
403
- });
404
- }
405
- return Object.freeze(installed);
406
- });
407
- }
408
- function isFoundryCapability(value) {
409
- if (!value || typeof value !== "object") return false;
410
- const object = value;
411
- return object[FOUNDRY_SHARED_TOOL_BRAND] === true || object[FOUNDRY_AGENT_APPLICATION_BRAND] === true || object[FOUNDRY_MCP_BRAND] === true || object[FOUNDRY_MEMORY_BRAND] === true;
412
- }
413
-
414
64
  // src/composition.ts
415
65
  var composedToolBodies = /* @__PURE__ */ new WeakMap();
416
66
  function isToolBody(value) {
@@ -580,7 +230,7 @@ var CREDENTIAL_FIELD_NAMES = /* @__PURE__ */ new Set([
580
230
  "credentials"
581
231
  ]);
582
232
  function assertSchemaContainsNoCredentialFields(transmissionId, area, schema) {
583
- const json = JSONSchema.make(schema);
233
+ const json2 = JSONSchema.make(schema);
584
234
  const visit = (value, path) => {
585
235
  if (!value || typeof value !== "object") return;
586
236
  if (Array.isArray(value)) {
@@ -606,7 +256,7 @@ function assertSchemaContainsNoCredentialFields(transmissionId, area, schema) {
606
256
  if (name !== "properties") visit(child, path);
607
257
  }
608
258
  };
609
- visit(json, area);
259
+ visit(json2, area);
610
260
  }
611
261
  function isFoundryTransmission(value) {
612
262
  return Boolean(
@@ -1055,6 +705,21 @@ async function discoverAgents(options) {
1055
705
  executionName: internalAgentName(route)
1056
706
  });
1057
707
  }
708
+ const expand = (entry, ancestors) => {
709
+ for (const [name, selection] of Object.entries(entry.definition.durableSubagents ?? {})) {
710
+ if (ancestors.has(selection.agent)) throw new Error(`Cyclic durable subagents at "${entry.route}/${name}".`);
711
+ const route = durableRoute(entry.route, name);
712
+ if (seen.has(route)) throw new Error(`Durable subagent route "${route}" conflicts with an existing agent.`);
713
+ seen.set(route, entry.filePath);
714
+ const child = { ...entry, route, definition: composeDurableAgent(entry.definition, name, selection), executionName: internalAgentName(route) };
715
+ discovered.push(child);
716
+ expand(child, /* @__PURE__ */ new Set([...ancestors, selection.agent]));
717
+ }
718
+ };
719
+ for (const entry of [...discovered]) {
720
+ if (entry.route.includes(DURABLE_SEGMENT)) throw new Error(`The route segment "workers" is reserved for durable subagents.`);
721
+ expand(entry, /* @__PURE__ */ new Set([entry.definition]));
722
+ }
1058
723
  return discovered;
1059
724
  }
1060
725
  function createManifest(agents) {
@@ -1083,6 +748,7 @@ function createManifest(agents) {
1083
748
  subagents: (typeof definition.subagents === "function" ? [] : definition.subagents ?? []).map(
1084
749
  (subagent) => subagent.name
1085
750
  ),
751
+ durableSubagents: Object.entries(definition.durableSubagents ?? {}).map(([name, child]) => ({ name, definitionId: durableRoute(route, name), ...child.description ? { description: child.description } : {} })),
1086
752
  memory: (typeof definition.memory === "function" ? [] : definition.memory ?? []).map(
1087
753
  (selection) => {
1088
754
  const profile = "profile" in selection ? selection.profile : selection;
@@ -1134,7 +800,7 @@ function createManifest(agents) {
1134
800
 
1135
801
  // src/primitives.ts
1136
802
  import { randomUUID } from "node:crypto";
1137
- import { Effect as Effect3 } from "effect";
803
+ import { Effect as Effect2 } from "effect";
1138
804
  function toGloveMessage(input) {
1139
805
  if (typeof input === "string") {
1140
806
  return freezeGloveMessage({ sender: "user", text: input });
@@ -1171,7 +837,9 @@ var MemoryFoundryDataAdapter = class {
1171
837
  agentsByProvisioningKey = /* @__PURE__ */ new Map();
1172
838
  subscriptions = /* @__PURE__ */ new Map();
1173
839
  inboundDeliveries = /* @__PURE__ */ new Map();
840
+ events = /* @__PURE__ */ new Map();
1174
841
  pendingInbound = /* @__PURE__ */ new Map();
842
+ approvals = /* @__PURE__ */ new Map();
1175
843
  activations = /* @__PURE__ */ new Map();
1176
844
  conversations = /* @__PURE__ */ new Map();
1177
845
  workspace = /* @__PURE__ */ new Map();
@@ -1207,13 +875,13 @@ var MemoryFoundryDataAdapter = class {
1207
875
  this.pendingSubscriptions = [];
1208
876
  }
1209
877
  getAgent(id2) {
1210
- return Effect3.sync(() => {
878
+ return Effect2.sync(() => {
1211
879
  this.materializeSeeds();
1212
880
  return this.agents.get(id2) ?? null;
1213
881
  });
1214
882
  }
1215
883
  putAgent(agent) {
1216
- return Effect3.sync(() => {
884
+ return Effect2.sync(() => {
1217
885
  this.materializeSeeds();
1218
886
  const reconstructed = reconstructAgentInstance(agent);
1219
887
  const prior = this.agents.get(agent.id);
@@ -1227,16 +895,17 @@ var MemoryFoundryDataAdapter = class {
1227
895
  });
1228
896
  }
1229
897
  listAgents(definitionId) {
1230
- return Effect3.sync(() => {
898
+ return Effect2.sync(() => {
1231
899
  this.materializeSeeds();
1232
900
  return [...this.agents.values()].filter((item) => !definitionId || item.definitionId === definitionId);
1233
901
  });
1234
902
  }
1235
903
  provisionAgent(input) {
1236
- return Effect3.sync(() => {
904
+ return Effect2.sync(() => {
1237
905
  this.materializeSeeds();
1238
906
  const existingId = this.agentsByProvisioningKey.get(input.provisioningKey);
1239
907
  if (existingId) return this.agents.get(existingId);
908
+ if (input.id && this.agents.has(input.id)) throw new Error(`Agent instance "${input.id}" already exists with another provisioning key.`);
1240
909
  const created = createAgentInstance(input.definitionId, {
1241
910
  ...input,
1242
911
  id: input.id ?? `agent_${randomUUID()}`
@@ -1246,35 +915,56 @@ var MemoryFoundryDataAdapter = class {
1246
915
  return created;
1247
916
  });
1248
917
  }
918
+ purgeAgentData(agentId) {
919
+ return Effect2.sync(() => {
920
+ this.materializeSeeds();
921
+ const agent = this.agents.get(agentId);
922
+ if (!agent?.durableSubagent || agent.durableSubagent.status !== "archived") throw new Error("Only archived durable workers can be purged.");
923
+ const conversationIds = new Set([...this.conversations.values()].filter((item) => item.agentId === agentId).map((item) => item.id));
924
+ for (const [id2, item] of this.events) if (item.target.agentId === agentId) this.events.delete(id2);
925
+ for (const [id2, item] of this.pendingInbound) if (item.request.agentId === agentId) this.pendingInbound.delete(id2);
926
+ for (const [id2, item] of this.approvals) if (item.agentId === agentId) this.approvals.delete(id2);
927
+ for (const [id2, item] of this.activations) if (item.agentId === agentId) this.activations.delete(id2);
928
+ for (const id2 of conversationIds) this.conversations.delete(id2);
929
+ for (const [id2, item] of this.inbox) if (item.agentId === agentId || conversationIds.has(item.conversationId ?? "")) this.inbox.delete(id2);
930
+ for (const [id2, item] of this.tasks) if (item.agentId === agentId || conversationIds.has(item.conversationId ?? "")) this.tasks.delete(id2);
931
+ for (let i = this.environment.length - 1; i >= 0; i--) {
932
+ const item = this.environment[i];
933
+ if (item.scope !== "workspace" && (item.agentId === agentId || conversationIds.has(item.conversationId ?? ""))) this.environment.splice(i, 1);
934
+ }
935
+ for (const key of this.workingEnvironments.keys()) if (key.split("\0")[3] === agentId) this.workingEnvironments.delete(key);
936
+ this.agents.set(agentId, reconstructAgentInstance({ ...agent, context: {}, installations: [], playbooks: [], durableSubagent: { ...agent.durableSubagent, status: "purged" }, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }));
937
+ });
938
+ }
1249
939
  getPlaybookSubscription(id2) {
1250
- return Effect3.sync(() => {
940
+ return Effect2.sync(() => {
1251
941
  this.materializeSeeds();
1252
942
  return this.subscriptions.get(id2) ?? null;
1253
943
  });
1254
944
  }
1255
945
  putPlaybookSubscription(subscription) {
1256
- return Effect3.sync(() => {
946
+ return Effect2.sync(() => {
1257
947
  this.materializeSeeds();
1258
948
  this.subscriptions.set(subscription.id, reconstructPlaybookSubscription(subscription));
1259
949
  });
1260
950
  }
1261
951
  deletePlaybookSubscription(id2) {
1262
- return Effect3.sync(() => {
952
+ return Effect2.sync(() => {
1263
953
  this.materializeSeeds();
1264
954
  return this.subscriptions.delete(id2);
1265
955
  });
1266
956
  }
1267
957
  listPlaybookSubscriptions(workspaceId) {
1268
- return Effect3.sync(() => {
958
+ return Effect2.sync(() => {
1269
959
  this.materializeSeeds();
1270
960
  return [...this.subscriptions.values()].filter((item) => !workspaceId || item.workspaceId === workspaceId);
1271
961
  });
1272
962
  }
1273
963
  getInboundDelivery(key) {
1274
- return Effect3.succeed(this.inboundDeliveries.get(key) ?? null);
964
+ return Effect2.succeed(this.inboundDeliveries.get(key) ?? null);
1275
965
  }
1276
966
  claimInboundDelivery(key) {
1277
- return Effect3.sync(() => {
967
+ return Effect2.sync(() => {
1278
968
  if (this.inboundDeliveries.has(key)) return false;
1279
969
  this.inboundDeliveries.set(key, Object.freeze({
1280
970
  key,
@@ -1286,7 +976,7 @@ var MemoryFoundryDataAdapter = class {
1286
976
  });
1287
977
  }
1288
978
  completeInboundDelivery(key, runIds) {
1289
- return Effect3.sync(() => {
979
+ return Effect2.sync(() => {
1290
980
  const prior = this.inboundDeliveries.get(key);
1291
981
  if (!prior) throw new Error(`Inbound delivery claim "${key}" does not exist.`);
1292
982
  this.inboundDeliveries.set(key, Object.freeze({
@@ -1298,59 +988,89 @@ var MemoryFoundryDataAdapter = class {
1298
988
  });
1299
989
  }
1300
990
  releaseInboundDelivery(key) {
1301
- return Effect3.sync(() => {
991
+ return Effect2.sync(() => {
1302
992
  if (this.inboundDeliveries.get(key)?.status === "pending") {
1303
993
  this.inboundDeliveries.delete(key);
1304
994
  }
1305
995
  });
1306
996
  }
997
+ claimEvent(record) {
998
+ return Effect2.sync(() => {
999
+ if (this.agents.get(record.target.agentId)?.durableSubagent?.status === "purged") throw new Error("Cannot deliver an event to a purged worker.");
1000
+ if (this.events.has(record.id)) return false;
1001
+ this.events.set(record.id, structuredClone(record));
1002
+ return true;
1003
+ });
1004
+ }
1005
+ putEvent(record) {
1006
+ return Effect2.sync(() => {
1007
+ if (this.agents.get(record.target.agentId)?.durableSubagent?.status !== "purged") this.events.set(record.id, structuredClone(record));
1008
+ });
1009
+ }
1010
+ listEvents() {
1011
+ return Effect2.sync(() => [...this.events.values()].map((record) => structuredClone(record)));
1012
+ }
1307
1013
  putPendingInbound(record) {
1308
- return Effect3.sync(() => {
1014
+ return Effect2.sync(() => {
1309
1015
  this.pendingInbound.set(record.id, structuredClone(record));
1310
1016
  });
1311
1017
  }
1312
1018
  deletePendingInbound(id2) {
1313
- return Effect3.sync(() => {
1019
+ return Effect2.sync(() => {
1314
1020
  this.pendingInbound.delete(id2);
1315
1021
  });
1316
1022
  }
1317
1023
  listPendingInbound() {
1318
- return Effect3.sync(() => [...this.pendingInbound.values()].map((record) => structuredClone(record)));
1024
+ return Effect2.sync(() => [...this.pendingInbound.values()].map((record) => structuredClone(record)));
1025
+ }
1026
+ putApproval(approval) {
1027
+ return Effect2.sync(() => {
1028
+ this.approvals.set(approval.id, structuredClone(approval));
1029
+ });
1030
+ }
1031
+ getApproval(id2) {
1032
+ return Effect2.sync(() => {
1033
+ const approval = this.approvals.get(id2);
1034
+ return approval ? structuredClone(approval) : null;
1035
+ });
1036
+ }
1037
+ listApprovals() {
1038
+ return Effect2.sync(() => [...this.approvals.values()].map((approval) => structuredClone(approval)));
1319
1039
  }
1320
1040
  getActivation(id2) {
1321
- return Effect3.succeed(this.activations.get(id2) ?? null);
1041
+ return Effect2.succeed(this.activations.get(id2) ?? null);
1322
1042
  }
1323
1043
  putActivation(activation) {
1324
- return Effect3.sync(() => {
1044
+ return Effect2.sync(() => {
1325
1045
  this.activations.set(activation.id, reconstructActivation(activation));
1326
1046
  });
1327
1047
  }
1328
1048
  listActivations(workspaceId) {
1329
- return Effect3.succeed(
1049
+ return Effect2.succeed(
1330
1050
  [...this.activations.values()].filter((item) => !workspaceId || item.workspaceId === workspaceId)
1331
1051
  );
1332
1052
  }
1333
1053
  getConversation(id2) {
1334
- return Effect3.succeed(this.conversations.get(id2) ?? null);
1054
+ return Effect2.succeed(this.conversations.get(id2) ?? null);
1335
1055
  }
1336
1056
  putConversation(conversation) {
1337
- return Effect3.sync(() => {
1057
+ return Effect2.sync(() => {
1338
1058
  this.conversations.set(conversation.id, Object.freeze({ ...conversation }));
1339
1059
  });
1340
1060
  }
1341
1061
  listConversations(agentId) {
1342
- return Effect3.succeed([...this.conversations.values()].filter((item) => item.agentId === agentId));
1062
+ return Effect2.succeed([...this.conversations.values()].filter((item) => item.agentId === agentId));
1343
1063
  }
1344
1064
  getWorkspaceEntry(workspaceId, key) {
1345
- return Effect3.succeed(this.workspace.get(`${workspaceId}:${key}`) ?? null);
1065
+ return Effect2.succeed(this.workspace.get(`${workspaceId}:${key}`) ?? null);
1346
1066
  }
1347
1067
  putWorkspaceEntry(entry) {
1348
- return Effect3.sync(() => {
1068
+ return Effect2.sync(() => {
1349
1069
  this.workspace.set(`${entry.workspaceId}:${entry.key}`, Object.freeze({ ...entry }));
1350
1070
  });
1351
1071
  }
1352
1072
  compareAndSetWorkspaceEntry(entry, expectedUpdatedAt) {
1353
- return Effect3.sync(() => {
1073
+ return Effect2.sync(() => {
1354
1074
  const key = `${entry.workspaceId}:${entry.key}`;
1355
1075
  const current = this.workspace.get(key);
1356
1076
  if ((current?.updatedAt ?? null) !== expectedUpdatedAt) return false;
@@ -1362,16 +1082,16 @@ var MemoryFoundryDataAdapter = class {
1362
1082
  });
1363
1083
  }
1364
1084
  listWorkspaceEntries(workspaceId) {
1365
- return Effect3.succeed([...this.workspace.values()].filter((item) => item.workspaceId === workspaceId));
1085
+ return Effect2.succeed([...this.workspace.values()].filter((item) => item.workspaceId === workspaceId));
1366
1086
  }
1367
1087
  getWorkingEnvironmentSnapshot(owner) {
1368
- return Effect3.sync(() => {
1088
+ return Effect2.sync(() => {
1369
1089
  const snapshot = this.workingEnvironments.get(workingEnvironmentOwnerKey(owner));
1370
1090
  return snapshot ? structuredClone(snapshot) : null;
1371
1091
  });
1372
1092
  }
1373
1093
  putWorkingEnvironmentSnapshot(owner, snapshot) {
1374
- return Effect3.sync(() => {
1094
+ return Effect2.sync(() => {
1375
1095
  this.workingEnvironments.set(
1376
1096
  workingEnvironmentOwnerKey(owner),
1377
1097
  structuredClone(snapshot)
@@ -1379,23 +1099,23 @@ var MemoryFoundryDataAdapter = class {
1379
1099
  });
1380
1100
  }
1381
1101
  putInboxItem(item) {
1382
- return Effect3.sync(() => {
1102
+ return Effect2.sync(() => {
1383
1103
  this.inbox.set(item.id, Object.freeze({ ...item }));
1384
1104
  });
1385
1105
  }
1386
1106
  listInboxItems(workspaceId) {
1387
- return Effect3.succeed([...this.inbox.values()].filter((item) => item.workspaceId === workspaceId));
1107
+ return Effect2.succeed([...this.inbox.values()].filter((item) => item.workspaceId === workspaceId));
1388
1108
  }
1389
1109
  putTask(task) {
1390
- return Effect3.sync(() => {
1110
+ return Effect2.sync(() => {
1391
1111
  this.tasks.set(task.id, Object.freeze({ ...task }));
1392
1112
  });
1393
1113
  }
1394
1114
  listTasks(workspaceId) {
1395
- return Effect3.succeed([...this.tasks.values()].filter((item) => item.workspaceId === workspaceId));
1115
+ return Effect2.succeed([...this.tasks.values()].filter((item) => item.workspaceId === workspaceId));
1396
1116
  }
1397
1117
  listEnvironment(scope) {
1398
- return Effect3.succeed(this.environment.filter(
1118
+ return Effect2.succeed(this.environment.filter(
1399
1119
  (item) => item.workspaceId === scope.workspaceId && (item.scope === "workspace" || item.scope === "agent" && item.agentId === scope.agentId || item.scope === "conversation" && item.conversationId === scope.conversationId)
1400
1120
  ));
1401
1121
  }
@@ -1421,8 +1141,11 @@ function createAgentInstance(definitionId, options = {}, provisioningKey) {
1421
1141
  return reconstructAgentInstance({
1422
1142
  id: options.id ?? `agent_${randomUUID()}`,
1423
1143
  definitionId,
1144
+ ...options.durableSubagent ? { durableSubagent: options.durableSubagent } : {},
1424
1145
  workspaceId: options.workspaceId ?? "default",
1425
1146
  ...provisioningKey ? { provisioningKey } : {},
1147
+ ...options.name !== void 0 ? { name: options.name } : {},
1148
+ ...options.description !== void 0 ? { description: options.description } : {},
1426
1149
  context: options.context ?? {},
1427
1150
  installations: options.installations ?? [],
1428
1151
  playbooks: options.playbooks ?? [],
@@ -1435,6 +1158,8 @@ function defineAgentInstance(definition, options = {}) {
1435
1158
  const seed = {
1436
1159
  id: options.id ?? `agent_${randomUUID()}`,
1437
1160
  workspaceId: options.workspaceId ?? "default",
1161
+ ...options.name !== void 0 ? { name: options.name } : {},
1162
+ ...options.description !== void 0 ? { description: options.description } : {},
1438
1163
  context: options.context ?? {},
1439
1164
  installations: options.installations ?? [],
1440
1165
  playbooks: options.playbooks ?? [],
@@ -1450,6 +1175,7 @@ function defineAgentInstance(definition, options = {}) {
1450
1175
  function reconstructAgentInstance(agent) {
1451
1176
  return Object.freeze({
1452
1177
  ...agent,
1178
+ ...agent.durableSubagent ? { durableSubagent: Object.freeze({ ...agent.durableSubagent }) } : {},
1453
1179
  context: freezeInstanceData(structuredClone(agent.context)),
1454
1180
  installations: normalizeAgentInstallations(agent.installations),
1455
1181
  playbooks: Object.freeze(agent.playbooks.map(reconstructPlaybook))
@@ -1550,189 +1276,8 @@ function agentScheduleRevision(schedule) {
1550
1276
 
1551
1277
  // src/core-tools.ts
1552
1278
  import { randomUUID as randomUUID2 } from "node:crypto";
1553
- import { Effect as Effect4, JSONSchema as JSONSchema2, Schema as Schema2 } from "effect";
1279
+ import { Effect as Effect3, Either, JSONSchema as JSONSchema2, ParseResult, Schema as Schema2 } from "effect";
1554
1280
  import { z } from "zod";
1555
-
1556
- // src/core-command-result.ts
1557
- import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
1558
- import { join } from "node:path";
1559
- var FOUNDRY_CORE_COMMAND_DIRECTORY_ENV = "GLOVE_FOUNDRY_CORE_COMMAND_DIRECTORY";
1560
- var REQUEST_SUFFIX = ".request.json";
1561
- var CLAIM_SUFFIX = ".claim";
1562
- var CANCELLATION_SUFFIX = ".cancellation.json";
1563
- var RESULT_SUFFIX = ".result.json";
1564
- var COMMAND_ID = /^command_[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
1565
- function commandPath(directory, id2, suffix) {
1566
- if (!COMMAND_ID.test(id2)) throw new Error("Invalid Foundry core command id.");
1567
- return join(directory, `${id2}${suffix}`);
1568
- }
1569
- async function readJson(path) {
1570
- try {
1571
- return JSON.parse(await readFile(path, "utf8"));
1572
- } catch (cause) {
1573
- if (cause.code === "ENOENT") return null;
1574
- throw cause;
1575
- }
1576
- }
1577
- function requestRecord(value) {
1578
- if (!value || typeof value !== "object") return null;
1579
- const item = value;
1580
- const valid = typeof item.id === "string" && COMMAND_ID.test(item.id) && typeof item.runId === "string" && item.type === "transmit" && typeof item.requestedAt === "string" && typeof item.expiresAt === "string";
1581
- if (!valid) return null;
1582
- if (item.command !== void 0) {
1583
- const command = item.command;
1584
- if (!command || typeof command !== "object" || command.type !== "transmit" || command.id !== item.id || typeof command.definitionId !== "string" || typeof command.agentId !== "string" || typeof command.conversationId !== "string" || typeof command.workspaceId !== "string" || typeof command.routeId !== "string" || !("payload" in command)) return null;
1585
- }
1586
- return item;
1587
- }
1588
- function resultRecord(value) {
1589
- if (!value || typeof value !== "object") return null;
1590
- const item = value;
1591
- if (typeof item.id !== "string" || !COMMAND_ID.test(item.id) || typeof item.resolvedAt !== "string") return null;
1592
- if (item.status === "success") return item;
1593
- return item.status === "error" && typeof item.error === "string" ? item : null;
1594
- }
1595
- function cancellationRecord(value) {
1596
- if (!value || typeof value !== "object") return null;
1597
- const item = value;
1598
- return typeof item.id === "string" && COMMAND_ID.test(item.id) && (item.status === "cancelled" || item.status === "expired") && typeof item.cancelledAt === "string" ? item : null;
1599
- }
1600
- function jsonValue(value) {
1601
- if (value === void 0) return void 0;
1602
- return JSON.parse(JSON.stringify(value));
1603
- }
1604
- async function createFoundryCoreCommandRequest(directory, input) {
1605
- await mkdir(directory, { recursive: true, mode: 448 });
1606
- const requestedAt = /* @__PURE__ */ new Date();
1607
- const timeoutMs = Math.min(Math.max(input.timeoutMs ?? 3e5, 1e3), 6e5);
1608
- const request = Object.freeze({
1609
- id: input.id,
1610
- runId: input.runId,
1611
- type: input.type,
1612
- requestedAt: requestedAt.toISOString(),
1613
- expiresAt: new Date(requestedAt.getTime() + timeoutMs).toISOString(),
1614
- ...input.command ? { command: jsonValue(input.command) } : {}
1615
- });
1616
- await writeFile(
1617
- commandPath(directory, request.id, REQUEST_SUFFIX),
1618
- `${JSON.stringify(request)}
1619
- `,
1620
- { encoding: "utf8", flag: "wx", mode: 384 }
1621
- );
1622
- return request;
1623
- }
1624
- async function getFoundryCoreCommandRequest(directory, id2) {
1625
- return requestRecord(await readJson(commandPath(directory, id2, REQUEST_SUFFIX)));
1626
- }
1627
- async function claimFoundryCoreCommandRequest(directory, id2) {
1628
- try {
1629
- await writeFile(
1630
- commandPath(directory, id2, CLAIM_SUFFIX),
1631
- `${(/* @__PURE__ */ new Date()).toISOString()}
1632
- `,
1633
- { encoding: "utf8", flag: "wx", mode: 384 }
1634
- );
1635
- return true;
1636
- } catch (cause) {
1637
- if (cause.code === "EEXIST") return false;
1638
- throw cause;
1639
- }
1640
- }
1641
- async function settleFoundryCoreCommandRequest(directory, id2, outcome) {
1642
- const result = outcome.status === "success" ? Object.freeze({
1643
- id: id2,
1644
- status: "success",
1645
- ...outcome.output !== void 0 ? { output: jsonValue(outcome.output) } : {},
1646
- resolvedAt: (/* @__PURE__ */ new Date()).toISOString()
1647
- }) : Object.freeze({
1648
- id: id2,
1649
- status: "error",
1650
- error: outcome.error,
1651
- resolvedAt: (/* @__PURE__ */ new Date()).toISOString()
1652
- });
1653
- try {
1654
- await writeFile(
1655
- commandPath(directory, id2, RESULT_SUFFIX),
1656
- `${JSON.stringify(result)}
1657
- `,
1658
- { encoding: "utf8", flag: "wx", mode: 384 }
1659
- );
1660
- } catch (cause) {
1661
- if (cause.code !== "EEXIST") throw cause;
1662
- }
1663
- }
1664
- async function cancelFoundryCoreCommandRequest(directory, id2, status) {
1665
- const cancellation = Object.freeze({
1666
- id: id2,
1667
- status,
1668
- cancelledAt: (/* @__PURE__ */ new Date()).toISOString()
1669
- });
1670
- try {
1671
- await writeFile(
1672
- commandPath(directory, id2, CANCELLATION_SUFFIX),
1673
- `${JSON.stringify(cancellation)}
1674
- `,
1675
- { encoding: "utf8", flag: "wx", mode: 384 }
1676
- );
1677
- } catch (cause) {
1678
- if (cause.code !== "EEXIST") throw cause;
1679
- }
1680
- }
1681
- async function monitorFoundryCoreCommandRequest(directory, request, delivery, stopped) {
1682
- while (!stopped.aborted && !delivery.signal.aborted) {
1683
- const cancellation = cancellationRecord(
1684
- await readJson(commandPath(directory, request.id, CANCELLATION_SUFFIX))
1685
- );
1686
- if (cancellation) {
1687
- delivery.abort(new Error(
1688
- cancellation.status === "cancelled" ? "Foundry transmission call was cancelled." : "Foundry transmission call timed out."
1689
- ));
1690
- return;
1691
- }
1692
- if (Date.parse(request.expiresAt) <= Date.now()) {
1693
- delivery.abort(new Error("Foundry transmission call timed out."));
1694
- return;
1695
- }
1696
- await new Promise((resolveWait) => setTimeout(resolveWait, 50));
1697
- }
1698
- }
1699
- async function waitForFoundryCoreCommandResult(directory, request, signal, options = {}) {
1700
- for (; ; ) {
1701
- const result = resultRecord(
1702
- await readJson(commandPath(directory, request.id, RESULT_SUFFIX))
1703
- );
1704
- if (result) {
1705
- if (options.cleanup) await cleanupFoundryCoreCommandRequest(directory, request.id);
1706
- if (result.status === "error") throw new Error(result.error);
1707
- return result.output;
1708
- }
1709
- if (signal.aborted) {
1710
- await cancelFoundryCoreCommandRequest(directory, request.id, "cancelled");
1711
- throw new Error("Foundry transmission call was cancelled.");
1712
- }
1713
- if (Date.parse(request.expiresAt) <= Date.now()) {
1714
- await cancelFoundryCoreCommandRequest(directory, request.id, "expired");
1715
- throw new Error("Foundry transmission call timed out.");
1716
- }
1717
- await new Promise((resolveWait) => setTimeout(resolveWait, 50));
1718
- }
1719
- }
1720
- async function cleanupFoundryCoreCommandRequest(directory, id2) {
1721
- await Promise.all([
1722
- REQUEST_SUFFIX,
1723
- CLAIM_SUFFIX,
1724
- RESULT_SUFFIX,
1725
- CANCELLATION_SUFFIX
1726
- ].map(async (suffix) => {
1727
- try {
1728
- await unlink(commandPath(directory, id2, suffix));
1729
- } catch (cause) {
1730
- if (cause.code !== "ENOENT") throw cause;
1731
- }
1732
- }));
1733
- }
1734
-
1735
- // src/core-tools.ts
1736
1281
  var FOUNDRY_CORE_COMMAND_EVENT = "foundry.core.command";
1737
1282
  function commandId() {
1738
1283
  return `command_${randomUUID2()}`;
@@ -1795,6 +1340,7 @@ function createInstalledApplicationTransmissionTools(context, applications, inst
1795
1340
  for (const application of applications) {
1796
1341
  if (!installed.has(application.id)) continue;
1797
1342
  for (const transmission of application.transmissions ?? []) {
1343
+ if (application.restrictions && !application.restrictions.transmissions?.includes(transmission.id)) continue;
1798
1344
  if (!transmission.outbound) continue;
1799
1345
  const routeIds = [...new Set(
1800
1346
  playbooks.filter(
@@ -1902,7 +1448,30 @@ function success(command) {
1902
1448
  }
1903
1449
  };
1904
1450
  }
1905
- function createFoundryCoreTools(context, desiredSchedules = []) {
1451
+ function declaredOutbound(playbooks, applications) {
1452
+ const outboundOf = (owners) => owners.flatMap((application) => (application.transmissions ?? []).filter((transmission) => transmission.outbound));
1453
+ const routes = /* @__PURE__ */ new Map();
1454
+ for (const playbook of playbooks) {
1455
+ if (playbook.enabled === false) continue;
1456
+ for (const outbound of playbook.outbound ?? []) {
1457
+ const owners = outbound.applicationId ? applications.filter((application) => application.id === outbound.applicationId) : applications;
1458
+ const candidates = routes.get(outbound.routeId) ?? /* @__PURE__ */ new Set();
1459
+ for (const transmission of outboundOf(owners)) candidates.add(transmission);
1460
+ routes.set(outbound.routeId, candidates);
1461
+ }
1462
+ }
1463
+ return new Map([...routes].map(([routeId, candidates]) => [routeId, [...candidates]]));
1464
+ }
1465
+ function asksFirst(transmission, payload) {
1466
+ const rule = transmission.outbound?.requiresPermission;
1467
+ if (rule === void 0) return false;
1468
+ if (typeof rule !== "function") return rule;
1469
+ const decoded = Schema2.decodeUnknownEither(transmission.outbound.input)(payload);
1470
+ if (Either.isRight(decoded)) return rule(decoded.right);
1471
+ return ParseResult.ArrayFormatter.formatIssueSync(decoded.left.issue).some((issue) => issue._tag === "Forbidden");
1472
+ }
1473
+ function createFoundryCoreTools(context, desiredSchedules = [], outbound = {}) {
1474
+ const routes = declaredOutbound(outbound.playbooks ?? context.agentInstance.playbooks, outbound.applications ?? []);
1906
1475
  const emit = (command) => {
1907
1476
  context.controls.commands.push(command);
1908
1477
  context.controls.emit({ type: FOUNDRY_CORE_COMMAND_EVENT, data: command });
@@ -1910,7 +1479,7 @@ function createFoundryCoreTools(context, desiredSchedules = []) {
1910
1479
  };
1911
1480
  const scheduleView = async () => {
1912
1481
  const records = new Map(
1913
- [...context.activations, ...await Effect4.runPromise(context.data.listActivations(context.workspaceId))].filter((item) => item.kind === "scheduled" && item.agentId === context.agentId).map((item) => [item.id, item])
1482
+ [...context.activations, ...await Effect3.runPromise(context.data.listActivations(context.workspaceId))].filter((item) => item.kind === "scheduled" && item.agentId === context.agentId).map((item) => [item.id, item])
1914
1483
  );
1915
1484
  const now = (/* @__PURE__ */ new Date()).toISOString();
1916
1485
  for (const desired of desiredSchedules) {
@@ -2181,7 +1750,22 @@ function createFoundryCoreTools(context, desiredSchedules = []) {
2181
1750
  routeId: z.string(),
2182
1751
  payload: z.unknown()
2183
1752
  }),
1753
+ // The route's transmission decides, as for its application's send tool. When
1754
+ // more than one could own the route, any that would ask makes this ask.
1755
+ requiresPermission: (input) => {
1756
+ const answers = (routes.get(input.routeId) ?? []).map((transmission) => asksFirst(transmission, input.payload));
1757
+ if (answers.some((answer) => answer === true)) return true;
1758
+ const pending = answers.filter((answer) => typeof answer !== "boolean");
1759
+ return pending.length ? Promise.all(pending).then((all) => all.some(Boolean)) : false;
1760
+ },
2184
1761
  async do(input) {
1762
+ if (!routes.has(input.routeId)) {
1763
+ return {
1764
+ status: "error",
1765
+ data: null,
1766
+ message: `Route "${input.routeId}" is not declared by this agent's playbooks.`
1767
+ };
1768
+ }
2185
1769
  const command = {
2186
1770
  id: commandId(),
2187
1771
  type: "transmit",
@@ -2228,7 +1812,7 @@ function createFoundryCoreTools(context, desiredSchedules = []) {
2228
1812
  description: "List the conversations owned by this runtime agent instance.",
2229
1813
  inputSchema: z.object({}),
2230
1814
  async do() {
2231
- return { status: "success", data: await Effect4.runPromise(context.data.listConversations(context.agentId)) };
1815
+ return { status: "success", data: await Effect3.runPromise(context.data.listConversations(context.agentId)) };
2232
1816
  }
2233
1817
  },
2234
1818
  {
@@ -2241,12 +1825,12 @@ function createFoundryCoreTools(context, desiredSchedules = []) {
2241
1825
  ]),
2242
1826
  async do(input) {
2243
1827
  if (input.action === "get") {
2244
- return { status: "success", data: await Effect4.runPromise(context.data.getWorkspaceEntry(context.workspaceId, input.key)) };
1828
+ return { status: "success", data: await Effect3.runPromise(context.data.getWorkspaceEntry(context.workspaceId, input.key)) };
2245
1829
  }
2246
1830
  if (input.action === "list") {
2247
- return { status: "success", data: await Effect4.runPromise(context.data.listWorkspaceEntries(context.workspaceId)) };
1831
+ return { status: "success", data: await Effect3.runPromise(context.data.listWorkspaceEntries(context.workspaceId)) };
2248
1832
  }
2249
- await Effect4.runPromise(context.data.putWorkspaceEntry({
1833
+ await Effect3.runPromise(context.data.putWorkspaceEntry({
2250
1834
  workspaceId: context.workspaceId,
2251
1835
  key: input.key,
2252
1836
  value: input.value,
@@ -2275,13 +1859,13 @@ function createFoundryCoreTools(context, desiredSchedules = []) {
2275
1859
  ]),
2276
1860
  async do(input) {
2277
1861
  if (input.action === "list") {
2278
- return { status: "success", data: await Effect4.runPromise(context.data.listInboxItems(context.workspaceId)) };
1862
+ return { status: "success", data: await Effect3.runPromise(context.data.listInboxItems(context.workspaceId)) };
2279
1863
  }
2280
1864
  if (input.action === "update") {
2281
- const current = (await Effect4.runPromise(context.data.listInboxItems(context.workspaceId))).find((item3) => item3.id === input.itemId);
1865
+ const current = (await Effect3.runPromise(context.data.listInboxItems(context.workspaceId))).find((item3) => item3.id === input.itemId);
2282
1866
  if (!current) return { status: "error", data: null, error: `Shared inbox item "${input.itemId}" was not found.` };
2283
1867
  const item2 = { ...current, status: input.status, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
2284
- await Effect4.runPromise(context.data.putInboxItem(item2));
1868
+ await Effect3.runPromise(context.data.putInboxItem(item2));
2285
1869
  return { status: "success", data: item2 };
2286
1870
  }
2287
1871
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -2296,7 +1880,7 @@ function createFoundryCoreTools(context, desiredSchedules = []) {
2296
1880
  createdAt: now,
2297
1881
  updatedAt: now
2298
1882
  };
2299
- await Effect4.runPromise(context.data.putInboxItem(item));
1883
+ await Effect3.runPromise(context.data.putInboxItem(item));
2300
1884
  return { status: "success", data: item };
2301
1885
  }
2302
1886
  },
@@ -2314,13 +1898,13 @@ function createFoundryCoreTools(context, desiredSchedules = []) {
2314
1898
  ]),
2315
1899
  async do(input) {
2316
1900
  if (input.action === "list") {
2317
- return { status: "success", data: await Effect4.runPromise(context.data.listTasks(context.workspaceId)) };
1901
+ return { status: "success", data: await Effect3.runPromise(context.data.listTasks(context.workspaceId)) };
2318
1902
  }
2319
1903
  if (input.action === "update") {
2320
- const current = (await Effect4.runPromise(context.data.listTasks(context.workspaceId))).find((task3) => task3.id === input.taskId);
1904
+ const current = (await Effect3.runPromise(context.data.listTasks(context.workspaceId))).find((task3) => task3.id === input.taskId);
2321
1905
  if (!current) return { status: "error", data: null, error: `Task "${input.taskId}" was not found.` };
2322
1906
  const task2 = { ...current, status: input.status, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
2323
- await Effect4.runPromise(context.data.putTask(task2));
1907
+ await Effect3.runPromise(context.data.putTask(task2));
2324
1908
  return { status: "success", data: task2 };
2325
1909
  }
2326
1910
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -2335,7 +1919,7 @@ function createFoundryCoreTools(context, desiredSchedules = []) {
2335
1919
  createdAt: now,
2336
1920
  updatedAt: now
2337
1921
  };
2338
- await Effect4.runPromise(context.data.putTask(task));
1922
+ await Effect3.runPromise(context.data.putTask(task));
2339
1923
  return { status: "success", data: task };
2340
1924
  }
2341
1925
  },
@@ -2346,7 +1930,7 @@ function createFoundryCoreTools(context, desiredSchedules = []) {
2346
1930
  async do() {
2347
1931
  return {
2348
1932
  status: "success",
2349
- data: await Effect4.runPromise(context.data.listEnvironment({
1933
+ data: await Effect3.runPromise(context.data.listEnvironment({
2350
1934
  workspaceId: context.workspaceId,
2351
1935
  agentId: context.agentId,
2352
1936
  conversationId: context.conversationId
@@ -2359,19 +1943,34 @@ function createFoundryCoreTools(context, desiredSchedules = []) {
2359
1943
 
2360
1944
  // src/approval.ts
2361
1945
  import { randomUUID as randomUUID3 } from "node:crypto";
2362
- import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, writeFile as writeFile2 } from "node:fs/promises";
2363
- import { join as join2 } from "node:path";
1946
+ import { mkdir, readFile, readdir as readdir2, writeFile } from "node:fs/promises";
1947
+ import { join } from "node:path";
2364
1948
  import {
2365
1949
  Displaymanager,
1950
+ ToolPermissionDeferred,
2366
1951
  permissionKey
2367
1952
  } from "glove-core";
2368
1953
  var FOUNDRY_APPROVAL_DIRECTORY_ENV = "GLOVE_FOUNDRY_APPROVAL_DIRECTORY";
2369
- var REQUEST_SUFFIX2 = ".request.json";
1954
+ var FOUNDRY_APPROVAL_POLICY_ENV = "GLOVE_FOUNDRY_APPROVAL_POLICY";
1955
+ var REQUEST_SUFFIX = ".request.json";
2370
1956
  var RESOLUTION_SUFFIX = ".resolution.json";
1957
+ var SUSPENDED_SUFFIX = ".suspended.json";
1958
+ var DEFAULT_APPROVAL_WAIT_MS = 6e4;
1959
+ var DEFAULT_APPROVAL_EXPIRES_AFTER_MS = 7 * 24 * 60 * 60 * 1e3;
1960
+ function readApprovalPolicy(value) {
1961
+ if (!value) return void 0;
1962
+ try {
1963
+ const parsed = JSON.parse(value);
1964
+ if (typeof parsed.durable !== "boolean" || typeof parsed.waitMs !== "number" || typeof parsed.expiresAfterMs !== "number") return void 0;
1965
+ return { durable: parsed.durable, waitMs: parsed.waitMs, expiresAfterMs: parsed.expiresAfterMs };
1966
+ } catch {
1967
+ return void 0;
1968
+ }
1969
+ }
2371
1970
  var APPROVAL_ID = /^approval_[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
2372
1971
  function approvalPath(directory, id2, suffix) {
2373
1972
  if (!APPROVAL_ID.test(id2)) throw new Error("Invalid Foundry approval id.");
2374
- return join2(directory, `${id2}${suffix}`);
1973
+ return join(directory, `${id2}${suffix}`);
2375
1974
  }
2376
1975
  function serializable(value) {
2377
1976
  try {
@@ -2380,15 +1979,15 @@ function serializable(value) {
2380
1979
  return String(value);
2381
1980
  }
2382
1981
  }
2383
- async function readJson2(path) {
1982
+ async function readJson(path) {
2384
1983
  try {
2385
- return JSON.parse(await readFile2(path, "utf8"));
1984
+ return JSON.parse(await readFile(path, "utf8"));
2386
1985
  } catch (cause) {
2387
1986
  if (cause.code === "ENOENT") return null;
2388
1987
  throw cause;
2389
1988
  }
2390
1989
  }
2391
- function requestRecord2(value) {
1990
+ function requestRecord(value) {
2392
1991
  if (!value || typeof value !== "object") return null;
2393
1992
  const item = value;
2394
1993
  return typeof item.id === "string" && APPROVAL_ID.test(item.id) && typeof item.runId === "string" && typeof item.definitionId === "string" && typeof item.agentId === "string" && typeof item.conversationId === "string" && typeof item.workspaceId === "string" && typeof item.toolName === "string" && typeof item.requestedAt === "string" && typeof item.expiresAt === "string" ? item : null;
@@ -2401,7 +2000,7 @@ function resolutionRecord(value) {
2401
2000
  async function writeResolution(directory, id2, status, rejectExisting = false) {
2402
2001
  const resolution = Object.freeze({ id: id2, status, resolvedAt: (/* @__PURE__ */ new Date()).toISOString() });
2403
2002
  try {
2404
- await writeFile2(
2003
+ await writeFile(
2405
2004
  approvalPath(directory, id2, RESOLUTION_SUFFIX),
2406
2005
  `${JSON.stringify(resolution)}
2407
2006
  `,
@@ -2411,7 +2010,7 @@ async function writeResolution(directory, id2, status, rejectExisting = false) {
2411
2010
  } catch (cause) {
2412
2011
  if (cause.code !== "EEXIST") throw cause;
2413
2012
  const existing = resolutionRecord(
2414
- await readJson2(approvalPath(directory, id2, RESOLUTION_SUFFIX))
2013
+ await readJson(approvalPath(directory, id2, RESOLUTION_SUFFIX))
2415
2014
  );
2416
2015
  if (!existing) throw new Error(`Foundry approval "${id2}" has an invalid resolution.`);
2417
2016
  if (rejectExisting) {
@@ -2421,9 +2020,9 @@ async function writeResolution(directory, id2, status, rejectExisting = false) {
2421
2020
  }
2422
2021
  }
2423
2022
  async function createFoundryApproval(directory, input) {
2424
- await mkdir2(directory, { recursive: true, mode: 448 });
2023
+ await mkdir(directory, { recursive: true, mode: 448 });
2425
2024
  const requestedAt = /* @__PURE__ */ new Date();
2426
- const timeoutMs = Math.min(Math.max(input.timeoutMs ?? 3e5, 1e3), 6e5);
2025
+ const timeoutMs = input.expiresAfterMs !== void 0 ? Math.max(input.expiresAfterMs, 1e3) : Math.min(Math.max(input.timeoutMs ?? 3e5, 1e3), 6e5);
2427
2026
  const request = Object.freeze({
2428
2027
  id: `approval_${randomUUID3()}`,
2429
2028
  runId: input.runId,
@@ -2433,11 +2032,12 @@ async function createFoundryApproval(directory, input) {
2433
2032
  workspaceId: input.workspaceId,
2434
2033
  toolName: input.toolName,
2435
2034
  toolInput: serializable(input.toolInput),
2035
+ ...input.toolCallId ? { toolCallId: input.toolCallId } : {},
2436
2036
  requestedAt: requestedAt.toISOString(),
2437
2037
  expiresAt: new Date(requestedAt.getTime() + timeoutMs).toISOString()
2438
2038
  });
2439
- await writeFile2(
2440
- approvalPath(directory, request.id, REQUEST_SUFFIX2),
2039
+ await writeFile(
2040
+ approvalPath(directory, request.id, REQUEST_SUFFIX),
2441
2041
  `${JSON.stringify(request)}
2442
2042
  `,
2443
2043
  { encoding: "utf8", flag: "wx", mode: 384 }
@@ -2453,11 +2053,11 @@ async function listFoundryApprovals(directory, filter = {}) {
2453
2053
  throw cause;
2454
2054
  }
2455
2055
  const approvals = [];
2456
- for (const name of names.filter((item) => item.endsWith(REQUEST_SUFFIX2)).sort()) {
2457
- const request = requestRecord2(await readJson2(join2(directory, name)));
2056
+ for (const name of names.filter((item) => item.endsWith(REQUEST_SUFFIX)).sort()) {
2057
+ const request = requestRecord(await readJson(join(directory, name)));
2458
2058
  if (!request) continue;
2459
2059
  const resolution = resolutionRecord(
2460
- await readJson2(approvalPath(directory, request.id, RESOLUTION_SUFFIX))
2060
+ await readJson(approvalPath(directory, request.id, RESOLUTION_SUFFIX))
2461
2061
  );
2462
2062
  const status = resolution?.status ?? (Date.parse(request.expiresAt) <= Date.now() ? "expired" : "pending");
2463
2063
  const approval = Object.freeze({
@@ -2472,7 +2072,7 @@ async function listFoundryApprovals(directory, filter = {}) {
2472
2072
  return approvals.sort((a, b) => a.requestedAt.localeCompare(b.requestedAt));
2473
2073
  }
2474
2074
  async function resolveFoundryApproval(directory, id2, decision) {
2475
- const request = requestRecord2(await readJson2(approvalPath(directory, id2, REQUEST_SUFFIX2)));
2075
+ const request = requestRecord(await readJson(approvalPath(directory, id2, REQUEST_SUFFIX)));
2476
2076
  if (!request) throw new Error(`Foundry approval "${id2}" was not found.`);
2477
2077
  const current = (await listFoundryApprovals(directory)).find((item) => item.id === id2);
2478
2078
  if (!current || current.status !== "pending") {
@@ -2486,10 +2086,44 @@ async function resolveFoundryApproval(directory, id2, decision) {
2486
2086
  );
2487
2087
  return Object.freeze({ ...request, status: resolution.status, resolvedAt: resolution.resolvedAt });
2488
2088
  }
2089
+ async function foundryApprovalRequested(directory, id2) {
2090
+ return requestRecord(await readJson(approvalPath(directory, id2, REQUEST_SUFFIX))) !== null;
2091
+ }
2092
+ async function readFoundryApprovalResolution(directory, id2) {
2093
+ return resolutionRecord(await readJson(approvalPath(directory, id2, RESOLUTION_SUFFIX)));
2094
+ }
2095
+ async function markFoundryApprovalSuspended(directory, id2) {
2096
+ try {
2097
+ await writeFile(
2098
+ approvalPath(directory, id2, SUSPENDED_SUFFIX),
2099
+ `${JSON.stringify({ id: id2, suspendedAt: (/* @__PURE__ */ new Date()).toISOString() })}
2100
+ `,
2101
+ { encoding: "utf8", flag: "wx", mode: 384 }
2102
+ );
2103
+ return true;
2104
+ } catch (cause) {
2105
+ if (cause.code === "EEXIST") return false;
2106
+ throw cause;
2107
+ }
2108
+ }
2109
+ async function foundryApprovalSuspended(directory, id2) {
2110
+ return await readJson(approvalPath(directory, id2, SUSPENDED_SUFFIX)) !== null;
2111
+ }
2112
+ async function waitForDecision(directory, approval, signal, waitMs) {
2113
+ const until = Math.min(Date.now() + waitMs, Date.parse(approval.expiresAt));
2114
+ for (; ; ) {
2115
+ const resolved = resolutionRecord(
2116
+ await readJson(approvalPath(directory, approval.id, RESOLUTION_SUFFIX))
2117
+ );
2118
+ if (resolved) return resolved;
2119
+ if (signal.aborted || Date.now() >= until) return null;
2120
+ await new Promise((resolveWait) => setTimeout(resolveWait, 100));
2121
+ }
2122
+ }
2489
2123
  async function waitForResolution(directory, approval, signal) {
2490
2124
  for (; ; ) {
2491
2125
  const resolved = resolutionRecord(
2492
- await readJson2(approvalPath(directory, approval.id, RESOLUTION_SUFFIX))
2126
+ await readJson(approvalPath(directory, approval.id, RESOLUTION_SUFFIX))
2493
2127
  );
2494
2128
  if (resolved) return resolved;
2495
2129
  if (signal.aborted) return writeResolution(directory, approval.id, "cancelled");
@@ -2517,6 +2151,9 @@ var FoundryApprovalDisplayManager = class extends Displaymanager {
2517
2151
  });
2518
2152
  return false;
2519
2153
  }
2154
+ const toolCallId = typeof request.toolCallId === "string" ? request.toolCallId : void 0;
2155
+ const durable = this.context.policy?.durable ? this.context.policy : void 0;
2156
+ if (durable) return this.durableDecision(this.context.directory, toolName, request.toolInput, toolCallId, durable);
2520
2157
  try {
2521
2158
  const approval = await createFoundryApproval(this.context.directory, {
2522
2159
  runId: this.context.runId,
@@ -2525,7 +2162,9 @@ var FoundryApprovalDisplayManager = class extends Displaymanager {
2525
2162
  conversationId: this.context.conversationId,
2526
2163
  workspaceId: this.context.workspaceId,
2527
2164
  toolName,
2528
- toolInput: request.toolInput
2165
+ toolInput: request.toolInput,
2166
+ ...toolCallId ? { toolCallId } : {},
2167
+ ...this.context.policy ? { timeoutMs: this.context.policy.waitMs } : {}
2529
2168
  });
2530
2169
  this.context.emit({ type: "foundry.approval.requested", data: approval });
2531
2170
  const resolution = await waitForResolution(
@@ -2546,6 +2185,52 @@ var FoundryApprovalDisplayManager = class extends Displaymanager {
2546
2185
  return false;
2547
2186
  }
2548
2187
  }
2188
+ /**
2189
+ * A durable approval: wait a while for the decision in this run. If nobody
2190
+ * decides in time, or the run is stopping, the approval stays open and the
2191
+ * turn suspends at this tool call (`ToolPermissionDeferred`), with no
2192
+ * result recorded for it. The runtime resumes it when someone decides.
2193
+ */
2194
+ async durableDecision(directory, toolName, toolInput, toolCallId, policy) {
2195
+ let approval;
2196
+ try {
2197
+ approval = await createFoundryApproval(directory, {
2198
+ runId: this.context.runId,
2199
+ definitionId: this.context.definitionId,
2200
+ agentId: this.context.agentId,
2201
+ conversationId: this.context.conversationId,
2202
+ workspaceId: this.context.workspaceId,
2203
+ toolName,
2204
+ toolInput,
2205
+ ...toolCallId ? { toolCallId } : {},
2206
+ expiresAfterMs: policy.expiresAfterMs
2207
+ });
2208
+ } catch (cause) {
2209
+ this.context.emit({
2210
+ type: "foundry.approval.failed",
2211
+ data: { toolName, error: cause instanceof Error ? cause.message : String(cause) }
2212
+ });
2213
+ return false;
2214
+ }
2215
+ this.context.emit({ type: "foundry.approval.requested", data: approval });
2216
+ let resolution = await waitForDecision(directory, approval, this.context.signal, policy.waitMs);
2217
+ if (!resolution) {
2218
+ await markFoundryApprovalSuspended(directory, approval.id);
2219
+ resolution = resolutionRecord(await readJson(approvalPath(directory, approval.id, RESOLUTION_SUFFIX)));
2220
+ }
2221
+ if (resolution) {
2222
+ this.context.emit({
2223
+ type: "foundry.approval.settled",
2224
+ data: { approvalId: approval.id, toolName, status: resolution.status }
2225
+ });
2226
+ return resolution.status === "approved";
2227
+ }
2228
+ this.context.emit({ type: "foundry.approval.suspended", data: { approvalId: approval.id, toolName } });
2229
+ throw new ToolPermissionDeferred(
2230
+ `Approval ${approval.id} for ${toolName} waits for a decision.`,
2231
+ { approvalId: approval.id, toolName }
2232
+ );
2233
+ }
2549
2234
  };
2550
2235
  function withFoundryPermissions(store) {
2551
2236
  if (store.getPermission && store.setPermission) return store;
@@ -2568,28 +2253,172 @@ function withFoundryPermissions(store) {
2568
2253
  });
2569
2254
  }
2570
2255
 
2256
+ // src/request-trace.ts
2257
+ import { createHash as createHash3 } from "node:crypto";
2258
+ var FOUNDRY_MODEL_REQUESTS_ENV = "GLOVE_FOUNDRY_MODEL_REQUESTS";
2259
+ var TEXT_LIMIT = 16e3;
2260
+ var JSON_LIMIT = 16e3;
2261
+ var SYSTEM_PROMPT_LIMIT = 64e3;
2262
+ var TOOL_SCHEMA_LIMIT = 8e3;
2263
+ var MESSAGES_BUDGET = 4e5;
2264
+ function hash(value) {
2265
+ return createHash3("sha256").update(value).digest("base64url").slice(0, 16);
2266
+ }
2267
+ function json(value) {
2268
+ try {
2269
+ return JSON.stringify(value) ?? "null";
2270
+ } catch {
2271
+ return JSON.stringify(String(value));
2272
+ }
2273
+ }
2274
+ function cut(text, limit) {
2275
+ return text.length > limit ? { text: text.slice(0, limit), chars: text.length } : { text };
2276
+ }
2277
+ function capped(value, limit = JSON_LIMIT) {
2278
+ if (value === void 0) return void 0;
2279
+ if (typeof value === "string") {
2280
+ const { text, chars } = cut(value, limit);
2281
+ return chars === void 0 ? text : `${text}\u2026 [${chars} characters]`;
2282
+ }
2283
+ const serialized = json(value);
2284
+ if (serialized.length <= limit) return JSON.parse(serialized);
2285
+ return { truncated: true, chars: serialized.length, preview: serialized.slice(0, limit) };
2286
+ }
2287
+ function tracePart(part) {
2288
+ if (part.type === "text") return { type: "text", text: cut(part.text ?? "", TEXT_LIMIT).text };
2289
+ return {
2290
+ type: part.type,
2291
+ ...part.name ? { name: part.name } : {},
2292
+ ...part.source?.media_type ? { media_type: part.source.media_type } : {}
2293
+ };
2294
+ }
2295
+ function traceCall(call) {
2296
+ return { ...call.id ? { id: call.id } : {}, tool_name: call.tool_name, input_args: capped(call.input_args) };
2297
+ }
2298
+ function traceResult(result) {
2299
+ return {
2300
+ ...result.call_id ? { call_id: result.call_id } : {},
2301
+ tool_name: result.tool_name,
2302
+ status: result.result.status,
2303
+ data: capped(result.result.data),
2304
+ ...result.result.message ? { message: cut(result.result.message, TEXT_LIMIT).text } : {},
2305
+ ...result.duration_ms !== void 0 ? { duration_ms: result.duration_ms } : {}
2306
+ };
2307
+ }
2308
+ function traceMessage(message) {
2309
+ const { text, chars } = cut(message.text ?? "", TEXT_LIMIT);
2310
+ return {
2311
+ sender: message.sender,
2312
+ text,
2313
+ ...chars !== void 0 ? { text_chars: chars } : {},
2314
+ ...message.framework_context ? { framework_context: message.framework_context } : {},
2315
+ ...message.is_compaction ? { is_compaction: true } : {},
2316
+ ...message.is_compaction_request ? { is_compaction_request: true } : {},
2317
+ ...message.is_skill_injection ? { is_skill_injection: true } : {},
2318
+ ...message.content?.length ? { content: message.content.map(tracePart) } : {},
2319
+ ...message.tool_calls?.length ? { tool_calls: message.tool_calls.map(traceCall) } : {},
2320
+ ...message.tool_results?.length ? { tool_results: message.tool_results.map(traceResult) } : {},
2321
+ ...message.reasoning_content ? { reasoning_omitted: true } : {}
2322
+ };
2323
+ }
2324
+ function traceTool(tool) {
2325
+ const schema = capped(tool.input_schema, TOOL_SCHEMA_LIMIT);
2326
+ return {
2327
+ name: tool.name,
2328
+ description: cut(tool.description ?? "", TEXT_LIMIT).text,
2329
+ input_schema: schema && typeof schema === "object" ? schema : {}
2330
+ };
2331
+ }
2332
+ function requestTracer() {
2333
+ const prompts = /* @__PURE__ */ new Set();
2334
+ const toolSets = /* @__PURE__ */ new Set();
2335
+ const threads = /* @__PURE__ */ new Map();
2336
+ const messageHashes = /* @__PURE__ */ new WeakMap();
2337
+ const messageHash = (message) => {
2338
+ let value = messageHashes.get(message);
2339
+ if (!value) {
2340
+ value = hash(json(message));
2341
+ messageHashes.set(message, value);
2342
+ }
2343
+ return value;
2344
+ };
2345
+ return {
2346
+ request(data) {
2347
+ let contextStart = data.messages.length;
2348
+ while (contextStart > 0 && data.messages[contextStart - 1].framework_context === "runtime") contextStart--;
2349
+ const history = data.messages.slice(0, contextStart);
2350
+ const context = data.messages.slice(contextStart);
2351
+ const promptHash = hash(data.system_prompt);
2352
+ const firstPrompt = !prompts.has(promptHash);
2353
+ prompts.add(promptHash);
2354
+ const toolsHash = hash(json(data.tools.map((tool) => [tool.name, tool.description, tool.input_schema])));
2355
+ const firstTools = !toolSets.has(toolsHash);
2356
+ toolSets.add(toolsHash);
2357
+ const hashes = history.map(messageHash);
2358
+ const previous = threads.get(promptHash);
2359
+ let kept = 0;
2360
+ if (previous) {
2361
+ const limit = Math.min(previous.hashes.length, hashes.length);
2362
+ while (kept < limit && previous.hashes[kept] === hashes[kept]) kept++;
2363
+ }
2364
+ threads.set(promptHash, { requestId: data.request_id, hashes });
2365
+ const added = [];
2366
+ let budget = MESSAGES_BUDGET;
2367
+ for (let index = history.length - 1; index >= kept; index--) {
2368
+ const traced = traceMessage(history[index]);
2369
+ budget -= json(traced).length;
2370
+ if (budget < 0 && added.length) break;
2371
+ added.unshift(traced);
2372
+ }
2373
+ const skipped = history.length - kept - added.length;
2374
+ return {
2375
+ request_id: data.request_id,
2376
+ model: data.model,
2377
+ purpose: data.purpose,
2378
+ system_prompt: {
2379
+ hash: promptHash,
2380
+ chars: data.system_prompt.length,
2381
+ ...firstPrompt ? { text: cut(data.system_prompt, SYSTEM_PROMPT_LIMIT).text } : {}
2382
+ },
2383
+ tools: {
2384
+ hash: toolsHash,
2385
+ names: data.tools.map((tool) => tool.name),
2386
+ ...firstTools ? { list: data.tools.map(traceTool) } : {}
2387
+ },
2388
+ messages: {
2389
+ total: history.length,
2390
+ ...previous && kept > 0 ? { base: previous.requestId } : {},
2391
+ kept: previous && kept > 0 ? kept : 0,
2392
+ ...skipped > 0 ? { skipped } : {},
2393
+ added
2394
+ },
2395
+ context: context.map(traceMessage)
2396
+ };
2397
+ },
2398
+ end(data) {
2399
+ return {
2400
+ request_id: data.request_id,
2401
+ model: data.model,
2402
+ duration_ms: data.duration_ms,
2403
+ status: data.status,
2404
+ ...data.error ? { error: cut(data.error, TEXT_LIMIT).text } : {},
2405
+ ...data.messages ? { response: data.messages.map(traceMessage) } : {},
2406
+ ...data.tokens_in !== void 0 ? { tokens_in: data.tokens_in } : {},
2407
+ ...data.tokens_out !== void 0 ? { tokens_out: data.tokens_out } : {},
2408
+ ...data.cache_read_input_tokens !== void 0 ? { cache_read_input_tokens: data.cache_read_input_tokens } : {},
2409
+ ...data.cache_creation_input_tokens !== void 0 ? { cache_creation_input_tokens: data.cache_creation_input_tokens } : {}
2410
+ };
2411
+ }
2412
+ };
2413
+ }
2414
+
2571
2415
  export {
2572
2416
  FOUNDRY_APPLICATION_BRAND,
2573
2417
  isFoundryApplication,
2574
2418
  defineApplication,
2575
2419
  EMPTY_FOUNDRY_APPLICATION,
2576
- FOUNDRY_SHARED_TOOL_BRAND,
2577
- FOUNDRY_AGENT_APPLICATION_BRAND,
2578
- FOUNDRY_MCP_BRAND,
2579
- FOUNDRY_MEMORY_BRAND,
2580
- install,
2581
- installationKey,
2582
- defineSharedTool,
2583
- defineAgentApplication,
2584
- defineApp,
2585
- defineMcp,
2586
- defineMemory,
2587
- EMPTY_CAPABILITY_REGISTRY,
2588
- isInboxCapableStore,
2589
- configureMemory,
2590
- mountAgentDefinitionMemory,
2591
- installRegistry,
2592
- isFoundryCapability,
2420
+ FOUNDRY_MODEL_REQUESTS_ENV,
2421
+ requestTracer,
2593
2422
  composeAgent,
2594
2423
  EMPTY_AGENT_COMPOSITION,
2595
2424
  FOUNDRY_CONNECTION_BRAND,
@@ -2633,19 +2462,22 @@ export {
2633
2462
  isFoundrySchedule,
2634
2463
  agentScheduleActivationId,
2635
2464
  agentScheduleRevision,
2636
- FOUNDRY_CORE_COMMAND_DIRECTORY_ENV,
2637
- getFoundryCoreCommandRequest,
2638
- claimFoundryCoreCommandRequest,
2639
- settleFoundryCoreCommandRequest,
2640
- monitorFoundryCoreCommandRequest,
2641
2465
  FOUNDRY_CORE_COMMAND_EVENT,
2642
2466
  installedApplicationTransmissionToolName,
2643
2467
  createInstalledApplicationTransmissionTools,
2644
2468
  createFoundryCoreTools,
2645
2469
  FOUNDRY_APPROVAL_DIRECTORY_ENV,
2470
+ FOUNDRY_APPROVAL_POLICY_ENV,
2471
+ DEFAULT_APPROVAL_WAIT_MS,
2472
+ DEFAULT_APPROVAL_EXPIRES_AFTER_MS,
2473
+ readApprovalPolicy,
2646
2474
  createFoundryApproval,
2647
2475
  listFoundryApprovals,
2648
2476
  resolveFoundryApproval,
2477
+ foundryApprovalRequested,
2478
+ readFoundryApprovalResolution,
2479
+ markFoundryApprovalSuspended,
2480
+ foundryApprovalSuspended,
2649
2481
  FoundryApprovalDisplayManager,
2650
2482
  withFoundryPermissions
2651
2483
  };