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.
- package/README.md +80 -4
- package/dist/chunk-CYOIHSUX.js +1365 -0
- package/dist/{chunk-X6EWEWWM.js → chunk-DTFCEX67.js} +2003 -200
- package/dist/{chunk-OBTOFA7W.js → chunk-EUGKVW3J.js} +470 -638
- package/dist/{chunk-B36BGF5R.js → chunk-J6NHL4SM.js} +370 -74
- package/dist/{chunk-7F7QVO6I.js → chunk-L5JQVTHD.js} +30 -0
- package/dist/{chunk-RSU7NEDK.js → chunk-X3HZYVZS.js} +36 -1
- package/dist/cli.js +4 -4
- package/dist/{client-DWPYe_Nc.d.ts → client-CekanYLW.d.ts} +252 -161
- package/dist/client.d.ts +3 -3
- package/dist/client.js +1 -1
- package/dist/config.d.ts +7 -0
- package/dist/{definition-A8o11aez.d.ts → event-delivery-CNCsVqi8.d.ts} +1380 -871
- package/dist/execution-agent.d.ts +0 -1
- package/dist/execution-agent.js +3 -14
- package/dist/execution-daemon.js +10 -5
- package/dist/execution-loader.js +1171 -8
- package/dist/index.d.ts +21 -6
- package/dist/index.js +178 -32
- package/dist/voice.d.ts +12 -8
- package/dist/voice.js +51 -10
- package/docs/README.md +1 -1
- package/docs/architecture.md +8 -0
- package/docs/building-with-foundry.md +137 -5
- package/docs/durable-subagents.md +337 -0
- package/docs/execution.md +4 -0
- package/docs/inspector.md +137 -29
- package/package.json +12 -11
- package/templates/travel-concierge/README.md +1 -1
- package/dist/chunk-K2EU63MB.js +0 -468
- package/dist/chunk-TFGETZYH.js +0 -917
|
@@ -0,0 +1,1365 @@
|
|
|
1
|
+
// src/surfaces.ts
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
|
|
4
|
+
// src/identity.ts
|
|
5
|
+
var identities = /* @__PURE__ */ new WeakMap();
|
|
6
|
+
function fileIdentified(value, kind, explicitId) {
|
|
7
|
+
const cell = {
|
|
8
|
+
kind,
|
|
9
|
+
...explicitId ? { id: explicitId } : {},
|
|
10
|
+
explicit: explicitId !== void 0
|
|
11
|
+
};
|
|
12
|
+
const identified = { ...value };
|
|
13
|
+
Object.defineProperty(identified, "id", {
|
|
14
|
+
enumerable: true,
|
|
15
|
+
configurable: false,
|
|
16
|
+
get() {
|
|
17
|
+
if (cell.id) return cell.id;
|
|
18
|
+
throw new Error(
|
|
19
|
+
`Foundry ${kind} identity has not been bound yet. Default-export it from its convention file and let Foundry discovery derive the id.`
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
identities.set(identified, cell);
|
|
24
|
+
return identified;
|
|
25
|
+
}
|
|
26
|
+
function bindFileIdentity(value, id, expectedKind) {
|
|
27
|
+
const cell = identities.get(value);
|
|
28
|
+
if (!cell) {
|
|
29
|
+
const current = value.id;
|
|
30
|
+
if (typeof current === "string" && current !== id) {
|
|
31
|
+
throw new Error(`Foundry file route resolves to "${id}" but the definition declares "${current}".`);
|
|
32
|
+
}
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
if (expectedKind && cell.kind !== expectedKind) {
|
|
36
|
+
throw new Error(
|
|
37
|
+
`Foundry ${expectedKind} route "${id}" received a ${cell.kind} definition.`
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
if (cell.id && cell.id !== id) {
|
|
41
|
+
throw new Error(
|
|
42
|
+
`Foundry ${cell.kind} route resolves to "${id}" but the definition declares "${cell.id}". Remove the explicit id and let the file own identity.`
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
cell.id = id;
|
|
46
|
+
}
|
|
47
|
+
function fileDefinitionKey(value) {
|
|
48
|
+
const cell = identities.get(value);
|
|
49
|
+
return cell ?? value;
|
|
50
|
+
}
|
|
51
|
+
function fileDefinitionLabel(value) {
|
|
52
|
+
const cell = identities.get(value);
|
|
53
|
+
return cell?.id ?? `<${cell?.kind ?? "definition"} file route>`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// src/surfaces.ts
|
|
57
|
+
var FOUNDRY_LAYER_BRAND = /* @__PURE__ */ Symbol.for("glove-foundry-layer");
|
|
58
|
+
var FOUNDRY_SUBSCRIBER_BRAND = /* @__PURE__ */ Symbol.for(
|
|
59
|
+
"glove-foundry-subscriber"
|
|
60
|
+
);
|
|
61
|
+
var SURFACE_ID = /^[a-z][a-z0-9-]*(?:\/[a-z][a-z0-9-]*)*$/;
|
|
62
|
+
function assertSurfaceId(id, label) {
|
|
63
|
+
if (!SURFACE_ID.test(id)) {
|
|
64
|
+
throw new Error(
|
|
65
|
+
`Invalid Foundry ${label} id "${id}". Use lowercase path segments containing letters, digits, and hyphens.`
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function defineLayer(options) {
|
|
70
|
+
if (options.id) assertSurfaceId(options.id, "layer");
|
|
71
|
+
const { id, ...definition } = options;
|
|
72
|
+
return Object.freeze(fileIdentified({
|
|
73
|
+
...definition,
|
|
74
|
+
[FOUNDRY_LAYER_BRAND]: true
|
|
75
|
+
}, "layer", id));
|
|
76
|
+
}
|
|
77
|
+
function configureLayer(layer, config) {
|
|
78
|
+
return Object.freeze({ layer, config });
|
|
79
|
+
}
|
|
80
|
+
function defineSubscriber(options) {
|
|
81
|
+
if (options.id) assertSurfaceId(options.id, "subscriber");
|
|
82
|
+
const { id, ...definition } = options;
|
|
83
|
+
return Object.freeze(fileIdentified({
|
|
84
|
+
...definition,
|
|
85
|
+
[FOUNDRY_SUBSCRIBER_BRAND]: true
|
|
86
|
+
}, "subscriber", id));
|
|
87
|
+
}
|
|
88
|
+
var EMPTY_NATIVE_REGISTRY = Object.freeze({
|
|
89
|
+
layers: Object.freeze([]),
|
|
90
|
+
subscribers: Object.freeze([])
|
|
91
|
+
});
|
|
92
|
+
function indexById(values, label) {
|
|
93
|
+
const indexed = /* @__PURE__ */ new Map();
|
|
94
|
+
for (const value of values) {
|
|
95
|
+
if (indexed.has(value.id)) {
|
|
96
|
+
throw new Error(`Duplicate Foundry ${label} id "${value.id}".`);
|
|
97
|
+
}
|
|
98
|
+
indexed.set(value.id, value);
|
|
99
|
+
}
|
|
100
|
+
return indexed;
|
|
101
|
+
}
|
|
102
|
+
async function mountFoundrySurfaces(options) {
|
|
103
|
+
const layers = indexById(options.registry.layers, "layer");
|
|
104
|
+
const subscribers = indexById(options.registry.subscribers, "subscriber");
|
|
105
|
+
const cleanup = [];
|
|
106
|
+
const disposeAll = async () => {
|
|
107
|
+
const failures = [];
|
|
108
|
+
for (const dispose of cleanup.reverse()) {
|
|
109
|
+
try {
|
|
110
|
+
const result = dispose();
|
|
111
|
+
if (Effect.isEffect(result)) await Effect.runPromise(result);
|
|
112
|
+
else await Promise.resolve(result);
|
|
113
|
+
} catch (cause) {
|
|
114
|
+
failures.push(cause);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (failures.length > 0) {
|
|
118
|
+
throw new AggregateError(failures, "Foundry surface cleanup failed.");
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
try {
|
|
122
|
+
for (const selected of options.subscribers ?? []) {
|
|
123
|
+
let definition = selected;
|
|
124
|
+
if (typeof definition === "object" && definition !== null && FOUNDRY_SUBSCRIBER_BRAND in definition) {
|
|
125
|
+
const registered = subscribers.get(definition.id);
|
|
126
|
+
if (!registered) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
`Agent "${options.context.agentId}" references unknown subscriber "${definition.id}".`
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
definition = registered;
|
|
132
|
+
}
|
|
133
|
+
let subscriber;
|
|
134
|
+
let subscriberId = "inline";
|
|
135
|
+
if (typeof definition === "object" && definition !== null && definition[FOUNDRY_SUBSCRIBER_BRAND] === true) {
|
|
136
|
+
const foundrySubscriber = definition;
|
|
137
|
+
const created = typeof foundrySubscriber.create === "function" ? foundrySubscriber.create(options.context) : foundrySubscriber.create;
|
|
138
|
+
subscriber = Effect.isEffect(created) ? await Effect.runPromise(created) : await Promise.resolve(created);
|
|
139
|
+
subscriberId = foundrySubscriber.id;
|
|
140
|
+
} else {
|
|
141
|
+
subscriber = definition;
|
|
142
|
+
}
|
|
143
|
+
options.context.glove.addSubscriber(subscriber);
|
|
144
|
+
cleanup.push(() => options.context.glove.removeSubscriber(subscriber));
|
|
145
|
+
options.context.emit({
|
|
146
|
+
type: "foundry.subscriber.mounted",
|
|
147
|
+
data: { id: subscriberId }
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
for (const selected of options.layers ?? []) {
|
|
151
|
+
const reference = FOUNDRY_LAYER_BRAND in selected ? { layer: selected } : selected;
|
|
152
|
+
const definition = layers.get(reference.layer.id);
|
|
153
|
+
if (!definition) {
|
|
154
|
+
throw new Error(
|
|
155
|
+
`Agent "${options.context.agentId}" references unknown layer "${reference.layer.id}".`
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
const referenceConfig = "config" in reference ? reference.config : void 0;
|
|
159
|
+
const parsed = definition.config ? definition.config.safeParse(referenceConfig ?? {}) : { success: true, data: referenceConfig };
|
|
160
|
+
if (!parsed.success) {
|
|
161
|
+
throw new Error(
|
|
162
|
+
`Invalid config for layer "${definition.id}": ${parsed.error.message}`
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
const dispose = await Effect.runPromise(
|
|
166
|
+
definition.setup({ ...options.context, config: parsed.data })
|
|
167
|
+
);
|
|
168
|
+
if (dispose) cleanup.push(dispose);
|
|
169
|
+
options.context.emit({
|
|
170
|
+
type: "foundry.layer.mounted",
|
|
171
|
+
data: { id: definition.id }
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
} catch (cause) {
|
|
175
|
+
try {
|
|
176
|
+
await disposeAll();
|
|
177
|
+
} catch (cleanupCause) {
|
|
178
|
+
throw new AggregateError(
|
|
179
|
+
[cause, cleanupCause],
|
|
180
|
+
"Foundry surface mount and cleanup failed."
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
throw cause;
|
|
184
|
+
}
|
|
185
|
+
return disposeAll;
|
|
186
|
+
}
|
|
187
|
+
function isFoundryLayer(value) {
|
|
188
|
+
return Boolean(
|
|
189
|
+
value && typeof value === "object" && value[FOUNDRY_LAYER_BRAND] === true
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
function isFoundrySubscriber(value) {
|
|
193
|
+
return Boolean(
|
|
194
|
+
value && typeof value === "object" && value[FOUNDRY_SUBSCRIBER_BRAND] === true
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// src/event-delivery.ts
|
|
199
|
+
import { createHash } from "node:crypto";
|
|
200
|
+
import { z } from "zod";
|
|
201
|
+
var eventPolicySchema = z.object({
|
|
202
|
+
whenIdle: z.enum(["wake", "defer"]).optional(),
|
|
203
|
+
deferTimeoutMs: z.number().int().nonnegative().max(2147483647).optional()
|
|
204
|
+
});
|
|
205
|
+
var messageOptionsSchema = eventPolicySchema.extend({
|
|
206
|
+
conversationId: z.string().min(1).optional(),
|
|
207
|
+
id: z.string().min(1).optional(),
|
|
208
|
+
expiresAt: z.string().datetime({ offset: true }).optional()
|
|
209
|
+
});
|
|
210
|
+
var foundryEventSchema = z.object({
|
|
211
|
+
id: z.string().trim().min(1),
|
|
212
|
+
source: z.string().trim().min(1),
|
|
213
|
+
kind: z.string().optional(),
|
|
214
|
+
content: z.union([z.string().refine((value) => value.trim().length > 0), z.array(z.object({
|
|
215
|
+
type: z.enum(["text", "image", "video", "document"]),
|
|
216
|
+
text: z.string().optional(),
|
|
217
|
+
name: z.string().optional(),
|
|
218
|
+
source: z.object({ type: z.enum(["base64", "url"]), media_type: z.string(), data: z.string().optional(), url: z.string().optional() }).optional()
|
|
219
|
+
})).min(1)]),
|
|
220
|
+
expiresAt: z.string().datetime({ offset: true }).optional(),
|
|
221
|
+
metadata: z.record(z.string(), z.unknown()).optional()
|
|
222
|
+
});
|
|
223
|
+
function eventRecordId(target, eventId) {
|
|
224
|
+
return `event_${createHash("sha256").update(JSON.stringify([target.agentId, target.conversationId, eventId])).digest("hex")}`;
|
|
225
|
+
}
|
|
226
|
+
function eventDue(record, now = Date.now()) {
|
|
227
|
+
return record.policy.whenIdle !== "defer" || record.policy.deferTimeoutMs !== void 0 && now >= Date.parse(record.createdAt) + record.policy.deferTimeoutMs;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// src/core-command-result.ts
|
|
231
|
+
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
|
|
232
|
+
import { join } from "node:path";
|
|
233
|
+
var FOUNDRY_CORE_COMMAND_DIRECTORY_ENV = "GLOVE_FOUNDRY_CORE_COMMAND_DIRECTORY";
|
|
234
|
+
var REQUEST_SUFFIX = ".request.json";
|
|
235
|
+
var CLAIM_SUFFIX = ".claim";
|
|
236
|
+
var CANCELLATION_SUFFIX = ".cancellation.json";
|
|
237
|
+
var RESULT_SUFFIX = ".result.json";
|
|
238
|
+
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;
|
|
239
|
+
function commandPath(directory, id, suffix) {
|
|
240
|
+
if (!COMMAND_ID.test(id)) throw new Error("Invalid Foundry core command id.");
|
|
241
|
+
return join(directory, `${id}${suffix}`);
|
|
242
|
+
}
|
|
243
|
+
async function readJson(path) {
|
|
244
|
+
try {
|
|
245
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
246
|
+
} catch (cause) {
|
|
247
|
+
if (cause.code === "ENOENT") return null;
|
|
248
|
+
throw cause;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
function requestRecord(value) {
|
|
252
|
+
if (!value || typeof value !== "object") return null;
|
|
253
|
+
const item = value;
|
|
254
|
+
const valid = typeof item.id === "string" && COMMAND_ID.test(item.id) && typeof item.runId === "string" && (item.type === "transmit" || item.type === "agent.message" || item.type === "mesh") && typeof item.requestedAt === "string" && typeof item.expiresAt === "string";
|
|
255
|
+
if (!valid) return null;
|
|
256
|
+
if (item.command !== void 0) {
|
|
257
|
+
const command = item.command;
|
|
258
|
+
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;
|
|
259
|
+
}
|
|
260
|
+
return item;
|
|
261
|
+
}
|
|
262
|
+
function resultRecord(value) {
|
|
263
|
+
if (!value || typeof value !== "object") return null;
|
|
264
|
+
const item = value;
|
|
265
|
+
if (typeof item.id !== "string" || !COMMAND_ID.test(item.id) || typeof item.resolvedAt !== "string") return null;
|
|
266
|
+
if (item.status === "success") return item;
|
|
267
|
+
return item.status === "error" && typeof item.error === "string" ? item : null;
|
|
268
|
+
}
|
|
269
|
+
function cancellationRecord(value) {
|
|
270
|
+
if (!value || typeof value !== "object") return null;
|
|
271
|
+
const item = value;
|
|
272
|
+
return typeof item.id === "string" && COMMAND_ID.test(item.id) && (item.status === "cancelled" || item.status === "expired") && typeof item.cancelledAt === "string" ? item : null;
|
|
273
|
+
}
|
|
274
|
+
function jsonValue(value) {
|
|
275
|
+
if (value === void 0) return void 0;
|
|
276
|
+
return JSON.parse(JSON.stringify(value));
|
|
277
|
+
}
|
|
278
|
+
async function createFoundryCoreCommandRequest(directory, input) {
|
|
279
|
+
await mkdir(directory, { recursive: true, mode: 448 });
|
|
280
|
+
const requestedAt = /* @__PURE__ */ new Date();
|
|
281
|
+
const timeoutMs = Math.min(Math.max(input.timeoutMs ?? 3e5, 1e3), 6e5);
|
|
282
|
+
const request = Object.freeze({
|
|
283
|
+
id: input.id,
|
|
284
|
+
runId: input.runId,
|
|
285
|
+
type: input.type,
|
|
286
|
+
requestedAt: requestedAt.toISOString(),
|
|
287
|
+
expiresAt: new Date(requestedAt.getTime() + timeoutMs).toISOString(),
|
|
288
|
+
...input.command ? { command: jsonValue(input.command) } : {}
|
|
289
|
+
});
|
|
290
|
+
await writeFile(
|
|
291
|
+
commandPath(directory, request.id, REQUEST_SUFFIX),
|
|
292
|
+
`${JSON.stringify(request)}
|
|
293
|
+
`,
|
|
294
|
+
{ encoding: "utf8", flag: "wx", mode: 384 }
|
|
295
|
+
);
|
|
296
|
+
return request;
|
|
297
|
+
}
|
|
298
|
+
async function getFoundryCoreCommandRequest(directory, id) {
|
|
299
|
+
return requestRecord(await readJson(commandPath(directory, id, REQUEST_SUFFIX)));
|
|
300
|
+
}
|
|
301
|
+
async function claimFoundryCoreCommandRequest(directory, id) {
|
|
302
|
+
try {
|
|
303
|
+
await writeFile(
|
|
304
|
+
commandPath(directory, id, CLAIM_SUFFIX),
|
|
305
|
+
`${(/* @__PURE__ */ new Date()).toISOString()}
|
|
306
|
+
`,
|
|
307
|
+
{ encoding: "utf8", flag: "wx", mode: 384 }
|
|
308
|
+
);
|
|
309
|
+
return true;
|
|
310
|
+
} catch (cause) {
|
|
311
|
+
if (cause.code === "EEXIST") return false;
|
|
312
|
+
throw cause;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
async function settleFoundryCoreCommandRequest(directory, id, outcome) {
|
|
316
|
+
const result = outcome.status === "success" ? Object.freeze({
|
|
317
|
+
id,
|
|
318
|
+
status: "success",
|
|
319
|
+
...outcome.output !== void 0 ? { output: jsonValue(outcome.output) } : {},
|
|
320
|
+
resolvedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
321
|
+
}) : Object.freeze({
|
|
322
|
+
id,
|
|
323
|
+
status: "error",
|
|
324
|
+
error: outcome.error,
|
|
325
|
+
resolvedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
326
|
+
});
|
|
327
|
+
try {
|
|
328
|
+
await writeFile(
|
|
329
|
+
commandPath(directory, id, RESULT_SUFFIX),
|
|
330
|
+
`${JSON.stringify(result)}
|
|
331
|
+
`,
|
|
332
|
+
{ encoding: "utf8", flag: "wx", mode: 384 }
|
|
333
|
+
);
|
|
334
|
+
} catch (cause) {
|
|
335
|
+
if (cause.code !== "EEXIST") throw cause;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
async function cancelFoundryCoreCommandRequest(directory, id, status) {
|
|
339
|
+
const cancellation = Object.freeze({
|
|
340
|
+
id,
|
|
341
|
+
status,
|
|
342
|
+
cancelledAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
343
|
+
});
|
|
344
|
+
try {
|
|
345
|
+
await writeFile(
|
|
346
|
+
commandPath(directory, id, CANCELLATION_SUFFIX),
|
|
347
|
+
`${JSON.stringify(cancellation)}
|
|
348
|
+
`,
|
|
349
|
+
{ encoding: "utf8", flag: "wx", mode: 384 }
|
|
350
|
+
);
|
|
351
|
+
} catch (cause) {
|
|
352
|
+
if (cause.code !== "EEXIST") throw cause;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
async function monitorFoundryCoreCommandRequest(directory, request, delivery, stopped) {
|
|
356
|
+
while (!stopped.aborted && !delivery.signal.aborted) {
|
|
357
|
+
const cancellation = cancellationRecord(
|
|
358
|
+
await readJson(commandPath(directory, request.id, CANCELLATION_SUFFIX))
|
|
359
|
+
);
|
|
360
|
+
if (cancellation) {
|
|
361
|
+
delivery.abort(new Error(
|
|
362
|
+
cancellation.status === "cancelled" ? "Foundry transmission call was cancelled." : "Foundry transmission call timed out."
|
|
363
|
+
));
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
if (Date.parse(request.expiresAt) <= Date.now()) {
|
|
367
|
+
delivery.abort(new Error("Foundry transmission call timed out."));
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 50));
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
async function waitForFoundryCoreCommandResult(directory, request, signal, options = {}) {
|
|
374
|
+
for (; ; ) {
|
|
375
|
+
const result = resultRecord(
|
|
376
|
+
await readJson(commandPath(directory, request.id, RESULT_SUFFIX))
|
|
377
|
+
);
|
|
378
|
+
if (result) {
|
|
379
|
+
if (options.cleanup) await cleanupFoundryCoreCommandRequest(directory, request.id);
|
|
380
|
+
if (result.status === "error") throw new Error(result.error);
|
|
381
|
+
return result.output;
|
|
382
|
+
}
|
|
383
|
+
if (signal.aborted) {
|
|
384
|
+
await cancelFoundryCoreCommandRequest(directory, request.id, "cancelled");
|
|
385
|
+
throw new Error(request.type === "mesh" ? "The mesh call was cancelled." : "Foundry transmission call was cancelled.");
|
|
386
|
+
}
|
|
387
|
+
if (Date.parse(request.expiresAt) <= Date.now()) {
|
|
388
|
+
await cancelFoundryCoreCommandRequest(directory, request.id, "expired");
|
|
389
|
+
throw new Error(request.type === "mesh" ? "The mesh call timed out." : "Foundry transmission call timed out.");
|
|
390
|
+
}
|
|
391
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 50));
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
async function cleanupFoundryCoreCommandRequest(directory, id) {
|
|
395
|
+
await Promise.all([
|
|
396
|
+
REQUEST_SUFFIX,
|
|
397
|
+
CLAIM_SUFFIX,
|
|
398
|
+
RESULT_SUFFIX,
|
|
399
|
+
CANCELLATION_SUFFIX
|
|
400
|
+
].map(async (suffix) => {
|
|
401
|
+
try {
|
|
402
|
+
await unlink(commandPath(directory, id, suffix));
|
|
403
|
+
} catch (cause) {
|
|
404
|
+
if (cause.code !== "ENOENT") throw cause;
|
|
405
|
+
}
|
|
406
|
+
}));
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// src/durable-subagents.ts
|
|
410
|
+
import { createHash as createHash2, randomUUID } from "node:crypto";
|
|
411
|
+
import { Effect as Effect3 } from "effect";
|
|
412
|
+
import { z as z2 } from "zod";
|
|
413
|
+
|
|
414
|
+
// src/capabilities.ts
|
|
415
|
+
import { Effect as Effect2 } from "effect";
|
|
416
|
+
import { connectMcpEntry, mountMcp, mountMcpToolSet } from "glove-mcp";
|
|
417
|
+
import {
|
|
418
|
+
useContext,
|
|
419
|
+
useEpisodicCurator,
|
|
420
|
+
useEpisodicReader,
|
|
421
|
+
useMemoryCurator,
|
|
422
|
+
useMemoryReader,
|
|
423
|
+
useResourcesCurator,
|
|
424
|
+
useResourcesReader
|
|
425
|
+
} from "glove-memory/tools";
|
|
426
|
+
var FOUNDRY_SHARED_TOOL_BRAND = /* @__PURE__ */ Symbol.for(
|
|
427
|
+
"glove-foundry-shared-tool"
|
|
428
|
+
);
|
|
429
|
+
var FOUNDRY_AGENT_APPLICATION_BRAND = /* @__PURE__ */ Symbol.for(
|
|
430
|
+
"glove-foundry-agent-application"
|
|
431
|
+
);
|
|
432
|
+
var FOUNDRY_MCP_BRAND = /* @__PURE__ */ Symbol.for("glove-foundry-mcp");
|
|
433
|
+
var FOUNDRY_MEMORY_BRAND = /* @__PURE__ */ Symbol.for("glove-foundry-memory");
|
|
434
|
+
function install(capability, ...configuration) {
|
|
435
|
+
const config = configuration[0];
|
|
436
|
+
const selection = configuration[1];
|
|
437
|
+
const kind = FOUNDRY_SHARED_TOOL_BRAND in capability ? "tool" : FOUNDRY_AGENT_APPLICATION_BRAND in capability ? "application" : "mcp";
|
|
438
|
+
const installation = {
|
|
439
|
+
kind,
|
|
440
|
+
...config !== void 0 ? { config } : {}
|
|
441
|
+
};
|
|
442
|
+
Object.defineProperty(installation, "id", {
|
|
443
|
+
enumerable: true,
|
|
444
|
+
get: () => capability.id
|
|
445
|
+
});
|
|
446
|
+
if (selection?.account) {
|
|
447
|
+
Object.defineProperty(installation, "accountId", {
|
|
448
|
+
enumerable: true,
|
|
449
|
+
get: () => selection.account.id
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
return Object.freeze(installation);
|
|
453
|
+
}
|
|
454
|
+
function installationKey(installation) {
|
|
455
|
+
return `${installation.kind}:${installation.id}`;
|
|
456
|
+
}
|
|
457
|
+
function assertCapabilityId(id, label) {
|
|
458
|
+
if (!/^[a-z][a-z0-9-]*(?:\/[a-z][a-z0-9-]*)*$/.test(id)) {
|
|
459
|
+
throw new Error(
|
|
460
|
+
`Invalid Foundry ${label} id "${id}". Use lowercase path segments containing letters, digits, and hyphens.`
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
function decodeCapabilityConfig(definition, installation) {
|
|
465
|
+
if (!definition.config) return installation.config;
|
|
466
|
+
const parsed = definition.config.safeParse(installation.config ?? {});
|
|
467
|
+
if (!parsed.success) {
|
|
468
|
+
throw new Error(
|
|
469
|
+
`Invalid config for ${installation.kind} "${definition.id}": ${parsed.error.message}`
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
return parsed.data;
|
|
473
|
+
}
|
|
474
|
+
function defineSharedTool(options) {
|
|
475
|
+
if (options.id) assertCapabilityId(options.id, "shared tool");
|
|
476
|
+
const { id, ...definition } = options;
|
|
477
|
+
return Object.freeze(fileIdentified({
|
|
478
|
+
...definition,
|
|
479
|
+
[FOUNDRY_SHARED_TOOL_BRAND]: true
|
|
480
|
+
}, "tool", id));
|
|
481
|
+
}
|
|
482
|
+
function defineAgentApplication(options) {
|
|
483
|
+
if (options.id) assertCapabilityId(options.id, "agent application");
|
|
484
|
+
const label = options.id ?? "<application file route>";
|
|
485
|
+
if (options.mcp && (!options.mcp.entry || !["object", "function"].includes(typeof options.mcp.entry))) {
|
|
486
|
+
throw new Error(`Application "${label}" declares mcp without an entry.`);
|
|
487
|
+
}
|
|
488
|
+
const inbound = Object.freeze([...options.inbound ?? []]);
|
|
489
|
+
const outbound = Object.freeze([...options.outbound ?? []]);
|
|
490
|
+
for (const transmission of inbound) {
|
|
491
|
+
if (!transmission.inbound) {
|
|
492
|
+
throw new Error(
|
|
493
|
+
`Application "${label}" declares an outbound-only transmission as inbound.`
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
for (const transmission of outbound) {
|
|
498
|
+
if (!transmission.outbound) {
|
|
499
|
+
throw new Error(
|
|
500
|
+
`Application "${label}" declares an inbound-only transmission as outbound.`
|
|
501
|
+
);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
const transmissionDefinitions = /* @__PURE__ */ new Map();
|
|
505
|
+
for (const transmission of [
|
|
506
|
+
...options.transmissions ?? [],
|
|
507
|
+
...inbound,
|
|
508
|
+
...outbound
|
|
509
|
+
]) {
|
|
510
|
+
const key = fileDefinitionKey(transmission);
|
|
511
|
+
const existing = transmissionDefinitions.get(key);
|
|
512
|
+
if (!existing) transmissionDefinitions.set(key, transmission);
|
|
513
|
+
}
|
|
514
|
+
const transmissions = Object.freeze([...transmissionDefinitions.values()]);
|
|
515
|
+
const connections = Object.freeze([...options.connections ?? []]);
|
|
516
|
+
const connectionIds = /* @__PURE__ */ new Set();
|
|
517
|
+
for (const connection of connections) {
|
|
518
|
+
const connectionKey = fileDefinitionKey(connection);
|
|
519
|
+
if (connectionIds.has(connectionKey)) {
|
|
520
|
+
throw new Error(`Application "${label}" contains the same connection more than once.`);
|
|
521
|
+
}
|
|
522
|
+
connectionIds.add(connectionKey);
|
|
523
|
+
for (const transmission of connection.transmissions) {
|
|
524
|
+
if (!transmissionDefinitions.has(fileDefinitionKey(transmission))) {
|
|
525
|
+
throw new Error(
|
|
526
|
+
`Application "${label}" contains a connection for a transmission it does not own.`
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
const { id, ...definition } = options;
|
|
532
|
+
return Object.freeze(fileIdentified({
|
|
533
|
+
...definition,
|
|
534
|
+
inbound,
|
|
535
|
+
outbound,
|
|
536
|
+
transmissions,
|
|
537
|
+
connections,
|
|
538
|
+
[FOUNDRY_AGENT_APPLICATION_BRAND]: true
|
|
539
|
+
}, "application", id));
|
|
540
|
+
}
|
|
541
|
+
function restrictApp(app, restrictions) {
|
|
542
|
+
const intersect = (next = [], previous) => Object.freeze([...new Set(next)].filter((name) => !previous || previous.includes(name)));
|
|
543
|
+
const limits = Object.freeze({
|
|
544
|
+
tools: intersect(restrictions.tools, app.restrictions?.tools),
|
|
545
|
+
operations: intersect(restrictions.operations, app.restrictions?.operations),
|
|
546
|
+
transmissions: intersect(restrictions.transmissions, app.restrictions?.transmissions)
|
|
547
|
+
});
|
|
548
|
+
const descriptors = Object.getOwnPropertyDescriptors(app);
|
|
549
|
+
delete descriptors.restrictions;
|
|
550
|
+
const result = Object.defineProperties({}, descriptors);
|
|
551
|
+
Object.defineProperty(result, "restrictions", { enumerable: true, value: limits });
|
|
552
|
+
return Object.freeze(result);
|
|
553
|
+
}
|
|
554
|
+
var defineApp = defineAgentApplication;
|
|
555
|
+
function identifyMcpEntry(entry, id) {
|
|
556
|
+
if (entry.transport) return { ...entry, id };
|
|
557
|
+
return { ...entry, id, url: entry.url };
|
|
558
|
+
}
|
|
559
|
+
function defineMcp(options) {
|
|
560
|
+
if (options.id) assertCapabilityId(options.id, "MCP");
|
|
561
|
+
const { id, ...definition } = options;
|
|
562
|
+
return Object.freeze(fileIdentified({
|
|
563
|
+
...definition,
|
|
564
|
+
[FOUNDRY_MCP_BRAND]: true
|
|
565
|
+
}, "mcp", id));
|
|
566
|
+
}
|
|
567
|
+
function defineMemory(options) {
|
|
568
|
+
if (options.id) assertCapabilityId(options.id, "memory profile");
|
|
569
|
+
if (!options.entity && !options.episodic && !options.resources && !options.context && !options.mount) {
|
|
570
|
+
throw new Error(`Foundry memory profile "${options.id ?? "<file route>"}" is empty.`);
|
|
571
|
+
}
|
|
572
|
+
const { id, ...definition } = options;
|
|
573
|
+
return Object.freeze(fileIdentified({
|
|
574
|
+
...definition,
|
|
575
|
+
[FOUNDRY_MEMORY_BRAND]: true
|
|
576
|
+
}, "memory", id));
|
|
577
|
+
}
|
|
578
|
+
var EMPTY_CAPABILITY_REGISTRY = Object.freeze({
|
|
579
|
+
tools: Object.freeze([]),
|
|
580
|
+
applications: Object.freeze([]),
|
|
581
|
+
mcp: Object.freeze([]),
|
|
582
|
+
memory: Object.freeze([])
|
|
583
|
+
});
|
|
584
|
+
function inboxMethods(store) {
|
|
585
|
+
return typeof store.getInboxItems === "function" && typeof store.addInboxItem === "function" && typeof store.updateInboxItem === "function" && typeof store.getResolvedInboxItems === "function";
|
|
586
|
+
}
|
|
587
|
+
function isInboxCapableStore(store) {
|
|
588
|
+
return inboxMethods(store);
|
|
589
|
+
}
|
|
590
|
+
function indexRegistry(values, kind) {
|
|
591
|
+
const result = /* @__PURE__ */ new Map();
|
|
592
|
+
for (const value of values) {
|
|
593
|
+
if (result.has(value.id)) {
|
|
594
|
+
throw new Error(`Duplicate Foundry ${kind} id "${value.id}".`);
|
|
595
|
+
}
|
|
596
|
+
result.set(value.id, value);
|
|
597
|
+
}
|
|
598
|
+
return result;
|
|
599
|
+
}
|
|
600
|
+
function mountMemory(profile, context) {
|
|
601
|
+
return Effect2.gen(function* () {
|
|
602
|
+
if (profile.entity) {
|
|
603
|
+
const adapter = yield* profile.entity.adapter(context);
|
|
604
|
+
const options = profile.entity.tools ? { tools: profile.entity.tools } : void 0;
|
|
605
|
+
if ((profile.entity.access ?? "reader") === "curator") {
|
|
606
|
+
useMemoryCurator(context.glove, adapter, options);
|
|
607
|
+
} else {
|
|
608
|
+
useMemoryReader(context.glove, adapter, options);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
if (profile.episodic) {
|
|
612
|
+
const adapter = yield* profile.episodic.adapter(context);
|
|
613
|
+
const options = profile.episodic.tools ? { tools: profile.episodic.tools } : void 0;
|
|
614
|
+
if ((profile.episodic.access ?? "reader") === "curator") {
|
|
615
|
+
useEpisodicCurator(context.glove, adapter, options);
|
|
616
|
+
} else {
|
|
617
|
+
useEpisodicReader(context.glove, adapter, options);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
if (profile.resources) {
|
|
621
|
+
const adapter = yield* profile.resources.adapter(context);
|
|
622
|
+
const options = profile.resources.tools ? { tools: profile.resources.tools } : void 0;
|
|
623
|
+
if ((profile.resources.access ?? "reader") === "curator") {
|
|
624
|
+
useResourcesCurator(context.glove, adapter, options);
|
|
625
|
+
} else {
|
|
626
|
+
useResourcesReader(context.glove, adapter, options);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
if (profile.context) {
|
|
630
|
+
const adapter = yield* profile.context.adapter(context);
|
|
631
|
+
useContext(
|
|
632
|
+
context.glove,
|
|
633
|
+
adapter,
|
|
634
|
+
profile.context.tools ? { tools: profile.context.tools } : void 0
|
|
635
|
+
);
|
|
636
|
+
}
|
|
637
|
+
if (profile.mount) yield* profile.mount(context);
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
function configureMemory(profile, config) {
|
|
641
|
+
return Object.freeze({ profile, config });
|
|
642
|
+
}
|
|
643
|
+
function mountAgentDefinitionMemory(options) {
|
|
644
|
+
return Effect2.gen(function* () {
|
|
645
|
+
const memory = indexRegistry(options.registry.memory, "memory profile");
|
|
646
|
+
const seen = /* @__PURE__ */ new Set();
|
|
647
|
+
for (const selection of options.memory) {
|
|
648
|
+
const reference = "profile" in selection ? selection.profile : selection;
|
|
649
|
+
const profile = memory.get(reference.id);
|
|
650
|
+
if (!profile) {
|
|
651
|
+
throw new Error(`Unknown agent memory profile "${reference.id}".`);
|
|
652
|
+
}
|
|
653
|
+
if (seen.has(`memory:${profile.id}`)) {
|
|
654
|
+
throw new Error(`Duplicate agent memory profile "${profile.id}".`);
|
|
655
|
+
}
|
|
656
|
+
seen.add(`memory:${profile.id}`);
|
|
657
|
+
const config = typeof selection === "object" && "profile" in selection ? selection.config : void 0;
|
|
658
|
+
const capability = {
|
|
659
|
+
kind: "memory",
|
|
660
|
+
id: profile.id,
|
|
661
|
+
...config !== void 0 ? { config } : {}
|
|
662
|
+
};
|
|
663
|
+
const context = {
|
|
664
|
+
...options.context,
|
|
665
|
+
surface: { kind: "memory", id: profile.id },
|
|
666
|
+
config: decodeCapabilityConfig(profile, capability)
|
|
667
|
+
};
|
|
668
|
+
yield* mountMemory(profile, context);
|
|
669
|
+
options.context.emit({
|
|
670
|
+
type: "foundry.definition.memory.mounted",
|
|
671
|
+
data: { id: profile.id }
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
function appNamespace(id) {
|
|
677
|
+
return id.replace(/[^A-Za-z0-9_]/g, "_");
|
|
678
|
+
}
|
|
679
|
+
function mountAppMcp(application, context, options, guard = (tool) => tool) {
|
|
680
|
+
return Effect2.gen(function* () {
|
|
681
|
+
const spec = application.mcp;
|
|
682
|
+
if (spec.auth && !context.withAccountSession) {
|
|
683
|
+
throw new Error(
|
|
684
|
+
`App "${application.id}" connects with an account. Install it with an account and give the agent definition accountSessions.`
|
|
685
|
+
);
|
|
686
|
+
}
|
|
687
|
+
const source = typeof spec.entry === "function" ? spec.entry(context) : spec.entry;
|
|
688
|
+
const resolved = Effect2.isEffect(source) ? yield* source : source instanceof Promise ? yield* Effect2.tryPromise({ try: () => source, catch: (cause) => cause }) : source;
|
|
689
|
+
const entry = identifyMcpEntry(resolved, appNamespace(application.id));
|
|
690
|
+
const credentials = () => Effect2.runPromise(context.withAccountSession(
|
|
691
|
+
"mcp:connect",
|
|
692
|
+
(session) => Effect2.tryPromise({
|
|
693
|
+
try: async () => spec.auth(session, context),
|
|
694
|
+
catch: (cause) => cause
|
|
695
|
+
})
|
|
696
|
+
));
|
|
697
|
+
const adapter = {
|
|
698
|
+
identifier: `foundry-app:${application.id}`,
|
|
699
|
+
getActive: async () => [entry.id],
|
|
700
|
+
activate: async () => void 0,
|
|
701
|
+
deactivate: async () => void 0,
|
|
702
|
+
...spec.auth ? entry.transport?.kind === "stdio" ? { getStdioEnvironment: async () => credentials() } : { getAuthHeaders: async () => credentials() } : {}
|
|
703
|
+
};
|
|
704
|
+
const decisions = /* @__PURE__ */ new Map();
|
|
705
|
+
const decide = (tool) => {
|
|
706
|
+
if (application.restrictions && !application.restrictions.tools?.includes(tool.name)) return false;
|
|
707
|
+
const described = {
|
|
708
|
+
name: tool.name,
|
|
709
|
+
...tool.description ? { description: tool.description } : {},
|
|
710
|
+
readOnly: tool.annotations?.readOnlyHint === true,
|
|
711
|
+
destructive: tool.annotations?.destructiveHint === true
|
|
712
|
+
};
|
|
713
|
+
const decision = spec.tools ? spec.tools(described, context) : described.readOnly ? "allow" : "ask";
|
|
714
|
+
if (decision !== "allow" && decision !== "ask" && decision !== "hide") {
|
|
715
|
+
throw new Error(
|
|
716
|
+
`App "${application.id}" returned "${String(decision)}" for tool "${tool.name}". Return "allow", "ask" or "hide".`
|
|
717
|
+
);
|
|
718
|
+
}
|
|
719
|
+
decisions.set(`${entry.id}__${tool.name}`, { decision, readOnly: described.readOnly });
|
|
720
|
+
return decision !== "hide";
|
|
721
|
+
};
|
|
722
|
+
const toolSet = yield* Effect2.tryPromise({
|
|
723
|
+
try: async () => {
|
|
724
|
+
const connection = await connectMcpEntry({
|
|
725
|
+
adapter,
|
|
726
|
+
entry,
|
|
727
|
+
clientInfo: { name: `glove-foundry:${application.id}`, version: "1" },
|
|
728
|
+
filterTools: decide
|
|
729
|
+
});
|
|
730
|
+
try {
|
|
731
|
+
return await mountMcpToolSet({
|
|
732
|
+
glove: options.context.glove,
|
|
733
|
+
connection,
|
|
734
|
+
entry,
|
|
735
|
+
// Foundry's agents run in server mode, where bridged MCP tools would
|
|
736
|
+
// never ask. The app's decision sets the approval instead.
|
|
737
|
+
wrapTool: (tool) => {
|
|
738
|
+
const decided = decisions.get(tool.name);
|
|
739
|
+
return guard(decided ? { ...tool, requiresPermission: decided.decision === "ask" } : tool);
|
|
740
|
+
}
|
|
741
|
+
});
|
|
742
|
+
} catch (cause) {
|
|
743
|
+
await connection.close().catch(() => void 0);
|
|
744
|
+
throw cause;
|
|
745
|
+
}
|
|
746
|
+
},
|
|
747
|
+
catch: (cause) => cause
|
|
748
|
+
});
|
|
749
|
+
options.onCleanup?.(() => toolSet.dispose());
|
|
750
|
+
options.context.emit({
|
|
751
|
+
type: "foundry.application.mcp.mounted",
|
|
752
|
+
data: { id: application.id, tools: toolSet.toolNames }
|
|
753
|
+
});
|
|
754
|
+
const readOnly = /* @__PURE__ */ new Map();
|
|
755
|
+
for (const [name, decided] of decisions) readOnly.set(name, decided.readOnly);
|
|
756
|
+
return { toolSet, readOnly };
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
function installRegistry(options) {
|
|
760
|
+
return Effect2.gen(function* () {
|
|
761
|
+
const tools = indexRegistry(options.registry.tools, "shared tool");
|
|
762
|
+
const applications = indexRegistry(
|
|
763
|
+
options.registry.applications,
|
|
764
|
+
"agent application"
|
|
765
|
+
);
|
|
766
|
+
const mcp = indexRegistry(options.registry.mcp, "MCP");
|
|
767
|
+
const seen = /* @__PURE__ */ new Set();
|
|
768
|
+
const installedMcp = [];
|
|
769
|
+
const installed = [];
|
|
770
|
+
const guardedTool = (tool, installation) => options.authorizeInstallation ? { ...tool, do: async (...args) => {
|
|
771
|
+
await Effect2.runPromise(options.authorizeInstallation(installation));
|
|
772
|
+
return tool.do(...args);
|
|
773
|
+
} } : tool;
|
|
774
|
+
for (const installation of options.installations) {
|
|
775
|
+
assertCapabilityId(installation.id, installation.kind);
|
|
776
|
+
if (installation.config && typeof installation.config === "object" && Object.prototype.hasOwnProperty.call(installation.config, "accountId")) {
|
|
777
|
+
throw new Error(
|
|
778
|
+
`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.`
|
|
779
|
+
);
|
|
780
|
+
}
|
|
781
|
+
const key = installationKey(installation);
|
|
782
|
+
if (seen.has(key)) continue;
|
|
783
|
+
seen.add(key);
|
|
784
|
+
const definition = installation.kind === "tool" ? tools.get(installation.id) : installation.kind === "application" ? applications.get(installation.id) : mcp.get(installation.id);
|
|
785
|
+
if (!definition) {
|
|
786
|
+
throw new Error(
|
|
787
|
+
`Agent "${options.context.agentId}" requests unknown ${installation.kind} "${installation.id}".`
|
|
788
|
+
);
|
|
789
|
+
}
|
|
790
|
+
const config = decodeCapabilityConfig(
|
|
791
|
+
definition,
|
|
792
|
+
installation
|
|
793
|
+
);
|
|
794
|
+
const context = {
|
|
795
|
+
...options.context,
|
|
796
|
+
installation,
|
|
797
|
+
config,
|
|
798
|
+
...installation.accountId ? {
|
|
799
|
+
accountId: installation.accountId,
|
|
800
|
+
...options.accountSessions ? {
|
|
801
|
+
withAccountSession: (operation, use) => Effect2.zipRight(options.authorizeInstallation?.(installation) ?? Effect2.void, Effect2.suspend(() => options.accountSessions.withSession({
|
|
802
|
+
accountId: installation.accountId,
|
|
803
|
+
operation,
|
|
804
|
+
agentId: options.context.agentId,
|
|
805
|
+
conversationId: options.context.conversationId,
|
|
806
|
+
workspaceId: options.context.workspaceId
|
|
807
|
+
}, use)))
|
|
808
|
+
} : {}
|
|
809
|
+
} : {}
|
|
810
|
+
};
|
|
811
|
+
if (installation.kind === "tool") {
|
|
812
|
+
const shared = definition;
|
|
813
|
+
const tool = shared.tool ?? (yield* shared.create(context));
|
|
814
|
+
options.context.glove.fold(guardedTool(tool, installation));
|
|
815
|
+
} else if (installation.kind === "application") {
|
|
816
|
+
const { glove: _glove, store: _store, ...headlessContext } = context;
|
|
817
|
+
const application = definition;
|
|
818
|
+
const restrictedContext = application.restrictions && headlessContext.withAccountSession ? { ...headlessContext, withAccountSession: (operation, use) => application.restrictions.operations?.includes(operation) ? headlessContext.withAccountSession(operation, use) : Effect2.fail(new Error(`Application "${application.id}" does not permit operation "${operation}".`)) } : headlessContext;
|
|
819
|
+
const contribution = application.install ? yield* application.install(restrictedContext) : void 0;
|
|
820
|
+
const ownTools = (contribution?.tools ?? []).filter((tool) => !application.restrictions || application.restrictions.tools?.includes(tool.name));
|
|
821
|
+
for (const tool of ownTools) options.context.glove.fold(guardedTool(tool, installation));
|
|
822
|
+
const mounted = application.mcp ? yield* mountAppMcp(application, restrictedContext, options, (tool) => guardedTool(tool, installation)) : void 0;
|
|
823
|
+
options.onApp?.(Object.freeze({
|
|
824
|
+
id: application.id,
|
|
825
|
+
description: application.description,
|
|
826
|
+
...installation.accountId ? { accountId: installation.accountId } : {},
|
|
827
|
+
get tools() {
|
|
828
|
+
return [
|
|
829
|
+
...ownTools.map((tool) => ({ name: tool.name })),
|
|
830
|
+
...(mounted?.toolSet.toolNames ?? []).map((name) => ({
|
|
831
|
+
name,
|
|
832
|
+
readOnly: mounted?.readOnly.get(name) ?? true
|
|
833
|
+
}))
|
|
834
|
+
];
|
|
835
|
+
}
|
|
836
|
+
}));
|
|
837
|
+
} else {
|
|
838
|
+
const mcpDefinition = definition;
|
|
839
|
+
const headlessContext = (() => {
|
|
840
|
+
const { glove: _glove, store: _store, ...headless } = context;
|
|
841
|
+
return headless;
|
|
842
|
+
})();
|
|
843
|
+
const source = typeof mcpDefinition.entry === "function" ? mcpDefinition.entry(headlessContext) : mcpDefinition.entry;
|
|
844
|
+
const entry = Effect2.isEffect(source) ? yield* source : source instanceof Promise ? yield* Effect2.tryPromise({ try: () => source, catch: (cause) => cause }) : source;
|
|
845
|
+
installedMcp.push({
|
|
846
|
+
definition: mcpDefinition,
|
|
847
|
+
installation,
|
|
848
|
+
config,
|
|
849
|
+
entry: identifyMcpEntry(entry, mcpDefinition.id)
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
installed.push(installation);
|
|
853
|
+
options.context.emit({
|
|
854
|
+
type: "foundry.installation.completed",
|
|
855
|
+
data: { kind: installation.kind, id: installation.id }
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
if (installedMcp.length > 0) {
|
|
859
|
+
if (!options.mcpAdapter) {
|
|
860
|
+
throw new Error(
|
|
861
|
+
`Agent "${options.context.agentId}" installs MCP capabilities but the application does not define mcpAdapter.`
|
|
862
|
+
);
|
|
863
|
+
}
|
|
864
|
+
const adapter = yield* options.mcpAdapter({
|
|
865
|
+
...options.context,
|
|
866
|
+
installed: installedMcp.map(({ definition }) => definition),
|
|
867
|
+
resolved: installedMcp
|
|
868
|
+
});
|
|
869
|
+
const selectedIds = new Set(installedMcp.map(({ definition }) => definition.id));
|
|
870
|
+
const scopedAdapter = {
|
|
871
|
+
identifier: adapter.identifier,
|
|
872
|
+
getActive: async () => [...selectedIds],
|
|
873
|
+
activate: (id) => adapter.activate(id),
|
|
874
|
+
deactivate: (id) => adapter.deactivate(id),
|
|
875
|
+
...adapter.getAccessToken ? { getAccessToken: (id) => adapter.getAccessToken(id) } : {},
|
|
876
|
+
...adapter.getAuthHeaders ? { getAuthHeaders: (id) => adapter.getAuthHeaders(id) } : {},
|
|
877
|
+
...adapter.getStdioEnvironment ? { getStdioEnvironment: (id) => adapter.getStdioEnvironment(id) } : {}
|
|
878
|
+
};
|
|
879
|
+
yield* Effect2.tryPromise({
|
|
880
|
+
try: () => mountMcp(options.context.glove, {
|
|
881
|
+
adapter: scopedAdapter,
|
|
882
|
+
entries: installedMcp.map(({ entry }) => entry),
|
|
883
|
+
ambiguityPolicy: { type: "auto-pick-best" }
|
|
884
|
+
}),
|
|
885
|
+
catch: (cause) => cause
|
|
886
|
+
});
|
|
887
|
+
}
|
|
888
|
+
return Object.freeze(installed);
|
|
889
|
+
});
|
|
890
|
+
}
|
|
891
|
+
function isFoundryCapability(value) {
|
|
892
|
+
if (!value || typeof value !== "object") return false;
|
|
893
|
+
const object = value;
|
|
894
|
+
return object[FOUNDRY_SHARED_TOOL_BRAND] === true || object[FOUNDRY_AGENT_APPLICATION_BRAND] === true || object[FOUNDRY_MCP_BRAND] === true || object[FOUNDRY_MEMORY_BRAND] === true;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
// src/durable-subagents.ts
|
|
898
|
+
var memoryOrigins = /* @__PURE__ */ new WeakMap();
|
|
899
|
+
var compositions = /* @__PURE__ */ new WeakMap();
|
|
900
|
+
var DURABLE_SEGMENT = "/workers/";
|
|
901
|
+
var durableRoute = (parent, name) => `${parent}${DURABLE_SEGMENT}${name}`;
|
|
902
|
+
var durableKey = (parent, name) => `subagent:${JSON.stringify([parent, name])}`;
|
|
903
|
+
var durableInstanceId = (parent, name) => `worker_${createHash2("sha256").update(durableKey(parent, name)).digest("hex")}`;
|
|
904
|
+
var agentInboxId = (agentId) => `inbox_${createHash2("sha256").update(agentId).digest("hex")}`;
|
|
905
|
+
function validateDurableSubagents(children = {}) {
|
|
906
|
+
for (const [name, child] of Object.entries(children)) {
|
|
907
|
+
if (!/^[a-z][a-z0-9-]*$/.test(name) || name === "parent") throw new Error(`Invalid durable subagent name "${name}".`);
|
|
908
|
+
if (child.eventDelivery) eventPolicySchema.parse(child.eventDelivery);
|
|
909
|
+
if (!isFoundryAgentDefinition(child.agent)) throw new Error(`Durable subagent "${name}" requires an agent definition.`);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
async function resolveList(definition, field, ctx) {
|
|
913
|
+
const value = typeof field === "function" ? field(definition, ctx) : field ?? [];
|
|
914
|
+
return Effect3.isEffect(value) ? Effect3.runPromise(value) : await value;
|
|
915
|
+
}
|
|
916
|
+
function composeDurableAgent(parent, name, selection) {
|
|
917
|
+
const child = selection.agent;
|
|
918
|
+
const inherited = selection.inherit;
|
|
919
|
+
const parentRegistry = parent.components?.capabilities ?? EMPTY_CAPABILITY_REGISTRY;
|
|
920
|
+
const childRegistry = child.components?.capabilities ?? EMPTY_CAPABILITY_REGISTRY;
|
|
921
|
+
const apps = (inherited?.apps ?? []).map((app) => {
|
|
922
|
+
const id = typeof app === "string" ? app : app.id;
|
|
923
|
+
const source = parentRegistry.applications.find((candidate) => candidate.id === id);
|
|
924
|
+
if (!source) throw new Error(`Cannot inherit unknown parent application "${id}".`);
|
|
925
|
+
const limits = typeof app === "string" ? {} : app.restrictions ?? {};
|
|
926
|
+
return restrictApp(source, limits);
|
|
927
|
+
});
|
|
928
|
+
for (const app of apps) {
|
|
929
|
+
if (childRegistry.applications.some((candidate) => candidate.id === app.id)) throw new Error(`Inherited application "${app.id}" conflicts with the child's own catalogue.`);
|
|
930
|
+
}
|
|
931
|
+
const memoryOption = inherited?.memory;
|
|
932
|
+
const memoryPolicy = typeof memoryOption === "string" ? { scope: memoryOption, access: "reader" } : memoryOption;
|
|
933
|
+
const selectedMemory = memoryPolicy ? parentRegistry.memory.filter((profile) => !memoryPolicy.profiles || memoryPolicy.profiles.includes(profile.id)) : [];
|
|
934
|
+
const inheritedMemory = selectedMemory.map((profile) => {
|
|
935
|
+
if (profile.mount) throw new Error(`Memory "${profile.id}" has a custom mount and cannot be safely inherited. Define a restricted profile instead.`);
|
|
936
|
+
const readonly = memoryPolicy?.access !== "curator";
|
|
937
|
+
const origin = memoryOrigins.get(profile) ?? profile;
|
|
938
|
+
const adapters = memoryPolicy?.scope === "isolated" ? origin : profile;
|
|
939
|
+
const factory = (adapter) => (context) => Effect3.gen(function* () {
|
|
940
|
+
const owner = context.request.context?.durableMemoryOwners?.[parent.id];
|
|
941
|
+
if (memoryPolicy?.scope === "shared" && !owner) throw new Error("Shared memory requires a validated parent instance.");
|
|
942
|
+
return yield* adapter(memoryPolicy?.scope === "shared" ? { ...context, agentId: owner.id, definitionId: owner.definitionId, conversationId: agentInboxId(owner.id) } : context);
|
|
943
|
+
});
|
|
944
|
+
const restricted = {
|
|
945
|
+
...profile,
|
|
946
|
+
...profile.entity ? { entity: { ...profile.entity, access: readonly ? "reader" : profile.entity.access, adapter: factory(adapters.entity.adapter) } } : {},
|
|
947
|
+
...profile.episodic ? { episodic: { ...profile.episodic, access: readonly ? "reader" : profile.episodic.access, adapter: factory(adapters.episodic.adapter) } } : {},
|
|
948
|
+
...profile.resources ? { resources: { ...profile.resources, access: readonly ? "reader" : profile.resources.access, adapter: factory(adapters.resources.adapter) } } : {},
|
|
949
|
+
...profile.context ? { context: { ...profile.context, adapter: factory(adapters.context.adapter), ...readonly ? { tools: { ...profile.context.tools, deny: [...profile.context.tools?.deny ?? [], "glove_context_set", "glove_context_update", "glove_context_unset"] } } : {} } } : {}
|
|
950
|
+
};
|
|
951
|
+
memoryOrigins.set(restricted, origin);
|
|
952
|
+
return restricted;
|
|
953
|
+
});
|
|
954
|
+
for (const profile of inheritedMemory) {
|
|
955
|
+
if (childRegistry.memory.some((candidate) => candidate.id === profile.id)) throw new Error(`Inherited memory "${profile.id}" conflicts with the child's own catalogue.`);
|
|
956
|
+
}
|
|
957
|
+
const options = Object.fromEntries(Object.entries(Object.getOwnPropertyDescriptors(child)).filter(([key]) => key !== "id").map(([key, descriptor]) => [key, descriptor.value]));
|
|
958
|
+
const definition = defineAgent({
|
|
959
|
+
...options,
|
|
960
|
+
id: durableRoute(parent.id, name),
|
|
961
|
+
description: selection.description ?? child.description,
|
|
962
|
+
eventDelivery: selection.eventDelivery ?? child.eventDelivery,
|
|
963
|
+
components: {
|
|
964
|
+
capabilities: { ...childRegistry, applications: [...childRegistry.applications, ...apps], memory: [...childRegistry.memory, ...inheritedMemory] },
|
|
965
|
+
native: child.components?.native ?? { layers: [], subscribers: [] }
|
|
966
|
+
},
|
|
967
|
+
tools: async (_definition, ctx) => {
|
|
968
|
+
const own = await resolveList(child, child.tools, ctx);
|
|
969
|
+
const inheritedTools = inherited?.tools?.length ? (await resolveList(parent, parent.tools, ctx)).filter((tool) => inherited.tools.includes(tool.name)) : [];
|
|
970
|
+
for (const tool of inheritedTools) if (own.some((candidate) => candidate.name === tool.name)) throw new Error(`Inherited tool "${tool.name}" conflicts with a child tool.`);
|
|
971
|
+
return [...own, ...inheritedTools];
|
|
972
|
+
},
|
|
973
|
+
memory: async (_definition, ctx) => {
|
|
974
|
+
const own = await resolveList(child, child.memory, ctx);
|
|
975
|
+
const inheritedSelections = memoryPolicy ? (await resolveList(parent, parent.memory, ctx)).filter((item) => inheritedMemory.some((profile) => profile.id === ("profile" in item ? item.profile.id : item.id))) : [];
|
|
976
|
+
return [...own, ...inheritedSelections];
|
|
977
|
+
},
|
|
978
|
+
accountSessions: child.accountSessions ?? (apps.length ? parent.accountSessions : void 0)
|
|
979
|
+
});
|
|
980
|
+
compositions.set(definition, { parent, selection });
|
|
981
|
+
return definition;
|
|
982
|
+
}
|
|
983
|
+
function inheritedInstallations(parent, definition, selection) {
|
|
984
|
+
const allowed = new Set((selection.inherit?.apps ?? []).map((app) => typeof app === "string" ? app : app.id));
|
|
985
|
+
return parent.installations.filter((installation) => installation.kind === "application" && allowed.has(installation.id) && definition.components?.capabilities.applications.some((app) => app.id === installation.id));
|
|
986
|
+
}
|
|
987
|
+
function createAgentMessagingTool(ctx, names, hasParent) {
|
|
988
|
+
return {
|
|
989
|
+
name: "glove_foundry_message",
|
|
990
|
+
description: "Send an asynchronous message to a persistent worker or your parent. The recipient receives a spontaneous event in its addressed runtime context; this does not wait for its answer. Use delegation for a task whose final result should return to this conversation.",
|
|
991
|
+
inputSchema: z2.object({ to: z2.enum([...hasParent ? ["parent"] : [], ...names]), message: z2.string().min(1), delivery: messageOptionsSchema.optional() }),
|
|
992
|
+
async do(input) {
|
|
993
|
+
const command = { type: "agent.message", id: `command_${randomUUID()}`, definitionId: ctx.definitionId, agentId: ctx.agentId, conversationId: ctx.conversationId, workspaceId: ctx.workspaceId, ...input };
|
|
994
|
+
const directory = process.env[FOUNDRY_CORE_COMMAND_DIRECTORY_ENV];
|
|
995
|
+
if (!directory) throw new Error("Durable messaging requires a running Foundry control process.");
|
|
996
|
+
const request = await createFoundryCoreCommandRequest(directory, { id: command.id, runId: ctx.runId, type: "agent.message", timeoutMs: 3e4 });
|
|
997
|
+
ctx.controls.commands.push(command);
|
|
998
|
+
ctx.controls.emit({ type: "foundry.core.command", data: command });
|
|
999
|
+
return { status: "success", data: await waitForFoundryCoreCommandResult(directory, request, ctx.controls.signal, { cleanup: true }) };
|
|
1000
|
+
}
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
async function refreshDurableAuthority(definition, snapshot, data) {
|
|
1004
|
+
const owners = {};
|
|
1005
|
+
const visit = async (currentDefinition, instance) => {
|
|
1006
|
+
const current = await Effect3.runPromise(data.getAgent(instance.id));
|
|
1007
|
+
if (!current) throw new Error(`Durable agent "${instance.id}" was removed.`);
|
|
1008
|
+
if (current.definitionId !== currentDefinition.id || current.workspaceId !== snapshot.workspaceId) throw new Error("Durable agent ownership changed.");
|
|
1009
|
+
if (!current.durableSubagent) return current;
|
|
1010
|
+
if (current.durableSubagent.status !== "active") throw new Error(`Durable worker is ${current.durableSubagent.status}.`);
|
|
1011
|
+
const composition = compositions.get(currentDefinition);
|
|
1012
|
+
if (!composition) throw new Error("Durable worker definition is detached.");
|
|
1013
|
+
const parentSnapshot = await Effect3.runPromise(data.getAgent(current.durableSubagent.parentAgentId));
|
|
1014
|
+
if (!parentSnapshot) throw new Error("Durable worker parent is missing.");
|
|
1015
|
+
const parent = await visit(composition.parent, parentSnapshot);
|
|
1016
|
+
owners[parent.definitionId] = { id: parent.id, definitionId: parent.definitionId, workspaceId: parent.workspaceId };
|
|
1017
|
+
const ids = new Set((composition.selection.inherit?.apps ?? []).map((app) => typeof app === "string" ? app : app.id));
|
|
1018
|
+
return { ...current, installations: [...current.installations.filter((item) => item.kind !== "application" || !ids.has(item.id)), ...inheritedInstallations(parent, currentDefinition, composition.selection)] };
|
|
1019
|
+
};
|
|
1020
|
+
return { agent: await visit(definition, snapshot), owners };
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
// src/definition.ts
|
|
1024
|
+
import { Displaymanager, Glove } from "glove-core";
|
|
1025
|
+
import { Effect as Effect4 } from "effect";
|
|
1026
|
+
var FOUNDRY_AGENT_DEFINITION_BRAND = /* @__PURE__ */ Symbol.for(
|
|
1027
|
+
"glove-foundry-agent-definition"
|
|
1028
|
+
);
|
|
1029
|
+
var FOUNDRY_AGENT_BRAND = FOUNDRY_AGENT_DEFINITION_BRAND;
|
|
1030
|
+
var FOUNDRY_EVENT_PREFIX = "__GLOVE_FOUNDRY_EVENT__";
|
|
1031
|
+
var FOUNDRY_RUN_PROCESS_EVENT = "foundry.run.process";
|
|
1032
|
+
var FOUNDRY_APPLICATION_ENV = "GLOVE_FOUNDRY_APPLICATION_FILE";
|
|
1033
|
+
var FOUNDRY_AGENT_ROUTE_ENV = "GLOVE_FOUNDRY_AGENT_ROUTE";
|
|
1034
|
+
var FOUNDRY_AGENT_FILE_ENV = "GLOVE_FOUNDRY_AGENT_FILE";
|
|
1035
|
+
var FOUNDRY_EXECUTION_MARKER = "__glove_foundry_execution_v1";
|
|
1036
|
+
function defineCall(options) {
|
|
1037
|
+
if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(options.name)) {
|
|
1038
|
+
throw new Error(`Invalid Foundry call name "${options.name}".`);
|
|
1039
|
+
}
|
|
1040
|
+
return Object.freeze({ ...options });
|
|
1041
|
+
}
|
|
1042
|
+
function isMeshTransport(mesh) {
|
|
1043
|
+
if (mesh === void 0 || mesh === true) return false;
|
|
1044
|
+
return typeof mesh === "function" || typeof mesh === "object" && mesh !== null && "adapter" in mesh;
|
|
1045
|
+
}
|
|
1046
|
+
function hostedMeshOptions(mesh) {
|
|
1047
|
+
if (mesh === void 0 || isMeshTransport(mesh)) return void 0;
|
|
1048
|
+
return mesh === true ? {} : mesh;
|
|
1049
|
+
}
|
|
1050
|
+
var ROUTE_PATTERN = /^[a-z][a-z0-9-]*(?:\/[a-z][a-z0-9-]*)*$/;
|
|
1051
|
+
function assertAgentRoute(route) {
|
|
1052
|
+
if (!ROUTE_PATTERN.test(route)) {
|
|
1053
|
+
throw new Error(
|
|
1054
|
+
`Invalid Foundry agent id "${route}". Use lowercase path segments containing letters, digits, and hyphens.`
|
|
1055
|
+
);
|
|
1056
|
+
}
|
|
1057
|
+
if (route.includes("__")) {
|
|
1058
|
+
throw new Error(`Invalid Foundry agent id "${route}": "__" is reserved.`);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
function internalAgentName(route) {
|
|
1062
|
+
assertAgentRoute(route);
|
|
1063
|
+
return `foundry_${route.replaceAll("/", "__").replaceAll("-", "_")}`;
|
|
1064
|
+
}
|
|
1065
|
+
function routeFromInternalAgentName(name) {
|
|
1066
|
+
if (!name.startsWith("foundry_")) return name;
|
|
1067
|
+
return name.slice("foundry_".length).replaceAll("__", "/").replaceAll("_", "-");
|
|
1068
|
+
}
|
|
1069
|
+
function isFoundryAgentDefinition(value) {
|
|
1070
|
+
return Boolean(
|
|
1071
|
+
value && typeof value === "object" && value[FOUNDRY_AGENT_DEFINITION_BRAND] === true
|
|
1072
|
+
);
|
|
1073
|
+
}
|
|
1074
|
+
var isFoundryAgent = isFoundryAgentDefinition;
|
|
1075
|
+
function validateDefinition(options, route) {
|
|
1076
|
+
validateDurableSubagents(options.durableSubagents);
|
|
1077
|
+
if (options.eventDelivery) eventPolicySchema.parse(options.eventDelivery);
|
|
1078
|
+
for (const key of ["runTimeoutMs", "maxConcurrentRuns"]) {
|
|
1079
|
+
if (options[key] !== void 0 && (!Number.isSafeInteger(options[key]) || options[key] <= 0)) throw new Error(`${key} must be a positive safe integer.`);
|
|
1080
|
+
}
|
|
1081
|
+
const id = route ?? options.id;
|
|
1082
|
+
if (id) assertAgentRoute(id);
|
|
1083
|
+
if (!options.model && !options.run && !options.handler && !options.spawn) {
|
|
1084
|
+
throw new Error(`Foundry agent "${id ?? "<file route>"}" must define model, run, handler, or spawn.`);
|
|
1085
|
+
}
|
|
1086
|
+
if (options.model && options.systemPrompt === void 0) {
|
|
1087
|
+
throw new Error(`Foundry agent "${id ?? "<file route>"}" must define systemPrompt when it defines a model.`);
|
|
1088
|
+
}
|
|
1089
|
+
if (options.answerWaitMs !== void 0 && (!Number.isFinite(options.answerWaitMs) || options.answerWaitMs < 0)) {
|
|
1090
|
+
throw new Error(`Foundry agent "${id ?? "<file route>"}" answerWaitMs must be a non-negative number.`);
|
|
1091
|
+
}
|
|
1092
|
+
if (options.mesh !== void 0 && options.mesh !== true && !isMeshTransport(options.mesh)) {
|
|
1093
|
+
if (typeof options.mesh !== "object" || options.mesh === null) {
|
|
1094
|
+
throw new Error(`Foundry agent "${id ?? "<file route>"}" mesh must be true, hosted-mesh options, or a mesh config with an adapter.`);
|
|
1095
|
+
}
|
|
1096
|
+
if (options.mesh.mount !== void 0 && typeof options.mesh.mount !== "function") {
|
|
1097
|
+
throw new Error(`Foundry agent "${id ?? "<file route>"}" mesh.mount must be a function of the run's context.`);
|
|
1098
|
+
}
|
|
1099
|
+
if (options.mesh.peers !== void 0 && typeof options.mesh.peers !== "function") {
|
|
1100
|
+
throw new Error(`Foundry agent "${id ?? "<file route>"}" mesh.peers must be a function of (self, peer).`);
|
|
1101
|
+
}
|
|
1102
|
+
if (options.mesh.waitMs !== void 0 && (!Number.isFinite(options.mesh.waitMs) || options.mesh.waitMs < 0)) {
|
|
1103
|
+
throw new Error(`Foundry agent "${id ?? "<file route>"}" mesh.waitMs must be a non-negative number.`);
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
if (options.inboxes !== void 0 && typeof options.inboxes !== "function") {
|
|
1107
|
+
throw new Error(
|
|
1108
|
+
`Foundry agent "${id ?? "<file route>"}" inboxes must be a lazy resolver function.`
|
|
1109
|
+
);
|
|
1110
|
+
}
|
|
1111
|
+
const forbidden = ["input", "output"];
|
|
1112
|
+
for (const key of forbidden) {
|
|
1113
|
+
if (key in options) {
|
|
1114
|
+
throw new Error(`Foundry agent "${id ?? "<file route>"}" cannot define ${key}; invocation contracts are framework-owned.`);
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
function defineAgent(options) {
|
|
1119
|
+
validateDefinition(options);
|
|
1120
|
+
const { id, ...definition } = options;
|
|
1121
|
+
return Object.freeze(fileIdentified({
|
|
1122
|
+
...definition,
|
|
1123
|
+
tags: Object.freeze([...options.tags ?? []]),
|
|
1124
|
+
[FOUNDRY_AGENT_DEFINITION_BRAND]: true
|
|
1125
|
+
}, "agent", id));
|
|
1126
|
+
}
|
|
1127
|
+
var CONVENTION_EXPORTS = [
|
|
1128
|
+
"id",
|
|
1129
|
+
"description",
|
|
1130
|
+
"tags",
|
|
1131
|
+
"components",
|
|
1132
|
+
"mcpAdapter",
|
|
1133
|
+
"accountSessions",
|
|
1134
|
+
"store",
|
|
1135
|
+
"model",
|
|
1136
|
+
"systemPrompt",
|
|
1137
|
+
"displayManager",
|
|
1138
|
+
"serverMode",
|
|
1139
|
+
"runTimeoutMs",
|
|
1140
|
+
"maxConcurrentRuns",
|
|
1141
|
+
"maxRetries",
|
|
1142
|
+
"maxConsecutiveErrors",
|
|
1143
|
+
"compactionLimit",
|
|
1144
|
+
"compactionInstructions",
|
|
1145
|
+
"maxTurns",
|
|
1146
|
+
"enableToolResultSummary",
|
|
1147
|
+
"tools",
|
|
1148
|
+
"hooks",
|
|
1149
|
+
"skills",
|
|
1150
|
+
"subagents",
|
|
1151
|
+
"delegates",
|
|
1152
|
+
"durableSubagents",
|
|
1153
|
+
"eventDelivery",
|
|
1154
|
+
"answerWaitMs",
|
|
1155
|
+
"memory",
|
|
1156
|
+
"goals",
|
|
1157
|
+
"facts",
|
|
1158
|
+
"forms",
|
|
1159
|
+
"contextProviders",
|
|
1160
|
+
"inboxes",
|
|
1161
|
+
"subscribers",
|
|
1162
|
+
"layers",
|
|
1163
|
+
"calls",
|
|
1164
|
+
"schedules",
|
|
1165
|
+
"playbooks",
|
|
1166
|
+
"mesh",
|
|
1167
|
+
"workingEnvironment",
|
|
1168
|
+
"repl",
|
|
1169
|
+
"configure",
|
|
1170
|
+
"build",
|
|
1171
|
+
"spawn",
|
|
1172
|
+
"run",
|
|
1173
|
+
"handler"
|
|
1174
|
+
];
|
|
1175
|
+
function defineAgentFromModule(route, module) {
|
|
1176
|
+
assertAgentRoute(route);
|
|
1177
|
+
if (isFoundryAgentDefinition(module.default)) {
|
|
1178
|
+
const definition2 = module.default;
|
|
1179
|
+
bindFileIdentity(definition2, route, "agent");
|
|
1180
|
+
validateDefinition(definition2, route);
|
|
1181
|
+
return definition2;
|
|
1182
|
+
}
|
|
1183
|
+
if (!module.description) {
|
|
1184
|
+
throw new Error(`Foundry route "${route}" must default-export defineAgent(...) or export description.`);
|
|
1185
|
+
}
|
|
1186
|
+
const options = {};
|
|
1187
|
+
for (const key of CONVENTION_EXPORTS) {
|
|
1188
|
+
if (module[key] !== void 0) options[key] = module[key];
|
|
1189
|
+
}
|
|
1190
|
+
const definition = defineAgent(options);
|
|
1191
|
+
bindFileIdentity(definition, route, "agent");
|
|
1192
|
+
return definition;
|
|
1193
|
+
}
|
|
1194
|
+
function defineSubagent(options) {
|
|
1195
|
+
if (!/^[A-Za-z][\w-]*$/.test(options.name)) throw new Error(`Invalid Foundry subagent name "${options.name}".`);
|
|
1196
|
+
return Object.freeze({
|
|
1197
|
+
name: options.name,
|
|
1198
|
+
description: options.description,
|
|
1199
|
+
factory: async ({ parentStore, parentControls, prompt }) => {
|
|
1200
|
+
const store = await parentStore.createSubAgentStore?.(options.name, options.durable ?? false) ?? void 0;
|
|
1201
|
+
const tools = typeof options.tools === "function" ? await resolveResolvable(options.tools({
|
|
1202
|
+
name: options.name,
|
|
1203
|
+
prompt,
|
|
1204
|
+
parent: parentControls.glove
|
|
1205
|
+
})) : options.tools ?? [];
|
|
1206
|
+
const glove = new Glove({
|
|
1207
|
+
...store ? { store } : {},
|
|
1208
|
+
model: options.model ?? parentControls.glove.model,
|
|
1209
|
+
displayManager: parentControls.displayManager ?? new Displaymanager(),
|
|
1210
|
+
systemPrompt: options.systemPrompt,
|
|
1211
|
+
serverMode: options.serverMode ?? parentControls.glove.serverMode,
|
|
1212
|
+
...options.maxRetries !== void 0 ? { maxRetries: options.maxRetries } : {},
|
|
1213
|
+
...options.maxConsecutiveErrors !== void 0 ? { maxConsecutiveErrors: options.maxConsecutiveErrors } : {},
|
|
1214
|
+
compaction_config: {
|
|
1215
|
+
compaction_instructions: options.compactionInstructions ?? `Preserve the ${options.name} subagent's findings and unresolved work.`,
|
|
1216
|
+
...options.maxTurns !== void 0 ? { max_turns: options.maxTurns } : {},
|
|
1217
|
+
...options.compactionLimit !== void 0 ? { compaction_context_limit: options.compactionLimit } : {}
|
|
1218
|
+
},
|
|
1219
|
+
...options.enableToolResultSummary !== void 0 ? { enableToolResultSummary: options.enableToolResultSummary } : {}
|
|
1220
|
+
}).build();
|
|
1221
|
+
for (const tool of tools) glove.fold(tool);
|
|
1222
|
+
for (const hook of options.hooks ?? []) glove.defineHook(hook.name, hook.handler);
|
|
1223
|
+
for (const skill of options.skills ?? []) glove.defineSkill(skill);
|
|
1224
|
+
for (const subagent of options.subagents ?? []) glove.defineSubAgent(subagent);
|
|
1225
|
+
const message = { sender: "user", text: prompt };
|
|
1226
|
+
const request = {
|
|
1227
|
+
agentId: options.name,
|
|
1228
|
+
conversationId: `subagent:${options.name}`,
|
|
1229
|
+
workspaceId: "subagent",
|
|
1230
|
+
message: prompt,
|
|
1231
|
+
source: { kind: "spawn" }
|
|
1232
|
+
};
|
|
1233
|
+
const context = {
|
|
1234
|
+
definitionId: options.name,
|
|
1235
|
+
agentId: options.name,
|
|
1236
|
+
conversationId: request.conversationId,
|
|
1237
|
+
workspaceId: request.workspaceId,
|
|
1238
|
+
runId: `subagent:${options.name}`,
|
|
1239
|
+
input: prompt,
|
|
1240
|
+
request,
|
|
1241
|
+
message,
|
|
1242
|
+
messageInput: prompt,
|
|
1243
|
+
messageText: prompt,
|
|
1244
|
+
history: [],
|
|
1245
|
+
messages: [message],
|
|
1246
|
+
glove,
|
|
1247
|
+
signal: new AbortController().signal,
|
|
1248
|
+
emit: () => void 0
|
|
1249
|
+
};
|
|
1250
|
+
const disposeSurfaces = await mountFoundrySurfaces({
|
|
1251
|
+
registry: {
|
|
1252
|
+
layers: uniqueById((options.layers ?? []).map((selected) => "layer" in selected ? selected.layer : selected)),
|
|
1253
|
+
subscribers: uniqueById((options.subscribers ?? []).filter(isFoundrySubscriber))
|
|
1254
|
+
},
|
|
1255
|
+
layers: options.layers ?? [],
|
|
1256
|
+
subscribers: options.subscribers ?? [],
|
|
1257
|
+
context
|
|
1258
|
+
});
|
|
1259
|
+
try {
|
|
1260
|
+
if (options.configure) await resolveResolvable(options.configure(context));
|
|
1261
|
+
} catch (cause) {
|
|
1262
|
+
await disposeSurfaces();
|
|
1263
|
+
throw cause;
|
|
1264
|
+
}
|
|
1265
|
+
const processRequest = glove.processRequest.bind(glove);
|
|
1266
|
+
let disposed = false;
|
|
1267
|
+
glove.processRequest = async (...args) => {
|
|
1268
|
+
try {
|
|
1269
|
+
return await processRequest(...args);
|
|
1270
|
+
} finally {
|
|
1271
|
+
if (!disposed) {
|
|
1272
|
+
disposed = true;
|
|
1273
|
+
await disposeSurfaces();
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
};
|
|
1277
|
+
return glove;
|
|
1278
|
+
}
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1281
|
+
function uniqueById(values) {
|
|
1282
|
+
return [...new Map(values.map((value) => [value.id, value])).values()];
|
|
1283
|
+
}
|
|
1284
|
+
async function resolveResolvable(value) {
|
|
1285
|
+
if (Effect4.isEffect(value)) return Effect4.runPromise(value);
|
|
1286
|
+
return Promise.resolve(value);
|
|
1287
|
+
}
|
|
1288
|
+
function defineRoutes(routes) {
|
|
1289
|
+
return Object.freeze({ ...routes });
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
export {
|
|
1293
|
+
eventPolicySchema,
|
|
1294
|
+
messageOptionsSchema,
|
|
1295
|
+
foundryEventSchema,
|
|
1296
|
+
eventRecordId,
|
|
1297
|
+
eventDue,
|
|
1298
|
+
FOUNDRY_CORE_COMMAND_DIRECTORY_ENV,
|
|
1299
|
+
createFoundryCoreCommandRequest,
|
|
1300
|
+
getFoundryCoreCommandRequest,
|
|
1301
|
+
claimFoundryCoreCommandRequest,
|
|
1302
|
+
settleFoundryCoreCommandRequest,
|
|
1303
|
+
monitorFoundryCoreCommandRequest,
|
|
1304
|
+
waitForFoundryCoreCommandResult,
|
|
1305
|
+
fileIdentified,
|
|
1306
|
+
bindFileIdentity,
|
|
1307
|
+
fileDefinitionKey,
|
|
1308
|
+
fileDefinitionLabel,
|
|
1309
|
+
FOUNDRY_LAYER_BRAND,
|
|
1310
|
+
FOUNDRY_SUBSCRIBER_BRAND,
|
|
1311
|
+
defineLayer,
|
|
1312
|
+
configureLayer,
|
|
1313
|
+
defineSubscriber,
|
|
1314
|
+
EMPTY_NATIVE_REGISTRY,
|
|
1315
|
+
mountFoundrySurfaces,
|
|
1316
|
+
isFoundryLayer,
|
|
1317
|
+
isFoundrySubscriber,
|
|
1318
|
+
FOUNDRY_AGENT_DEFINITION_BRAND,
|
|
1319
|
+
FOUNDRY_AGENT_BRAND,
|
|
1320
|
+
FOUNDRY_EVENT_PREFIX,
|
|
1321
|
+
FOUNDRY_RUN_PROCESS_EVENT,
|
|
1322
|
+
FOUNDRY_APPLICATION_ENV,
|
|
1323
|
+
FOUNDRY_AGENT_ROUTE_ENV,
|
|
1324
|
+
FOUNDRY_AGENT_FILE_ENV,
|
|
1325
|
+
FOUNDRY_EXECUTION_MARKER,
|
|
1326
|
+
defineCall,
|
|
1327
|
+
isMeshTransport,
|
|
1328
|
+
hostedMeshOptions,
|
|
1329
|
+
internalAgentName,
|
|
1330
|
+
routeFromInternalAgentName,
|
|
1331
|
+
isFoundryAgentDefinition,
|
|
1332
|
+
isFoundryAgent,
|
|
1333
|
+
defineAgent,
|
|
1334
|
+
defineAgentFromModule,
|
|
1335
|
+
defineSubagent,
|
|
1336
|
+
resolveResolvable,
|
|
1337
|
+
defineRoutes,
|
|
1338
|
+
FOUNDRY_SHARED_TOOL_BRAND,
|
|
1339
|
+
FOUNDRY_AGENT_APPLICATION_BRAND,
|
|
1340
|
+
FOUNDRY_MCP_BRAND,
|
|
1341
|
+
FOUNDRY_MEMORY_BRAND,
|
|
1342
|
+
install,
|
|
1343
|
+
installationKey,
|
|
1344
|
+
defineSharedTool,
|
|
1345
|
+
defineAgentApplication,
|
|
1346
|
+
restrictApp,
|
|
1347
|
+
defineApp,
|
|
1348
|
+
defineMcp,
|
|
1349
|
+
defineMemory,
|
|
1350
|
+
EMPTY_CAPABILITY_REGISTRY,
|
|
1351
|
+
isInboxCapableStore,
|
|
1352
|
+
configureMemory,
|
|
1353
|
+
mountAgentDefinitionMemory,
|
|
1354
|
+
installRegistry,
|
|
1355
|
+
isFoundryCapability,
|
|
1356
|
+
DURABLE_SEGMENT,
|
|
1357
|
+
durableRoute,
|
|
1358
|
+
durableKey,
|
|
1359
|
+
durableInstanceId,
|
|
1360
|
+
agentInboxId,
|
|
1361
|
+
composeDurableAgent,
|
|
1362
|
+
inheritedInstallations,
|
|
1363
|
+
createAgentMessagingTool,
|
|
1364
|
+
refreshDurableAuthority
|
|
1365
|
+
};
|