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
|
@@ -1,9 +1,224 @@
|
|
|
1
|
-
// src/
|
|
1
|
+
// src/mesh.ts
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
var THREAD_ID = /^thread_[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
5
|
+
var DEFAULT_MESH_WAIT_MS = 9e4;
|
|
6
|
+
function meshIdentity(agent) {
|
|
7
|
+
return {
|
|
8
|
+
id: agent.id,
|
|
9
|
+
name: agent.name ?? agent.id,
|
|
10
|
+
description: agent.description ?? "",
|
|
11
|
+
metadata: { definitionId: agent.definitionId }
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
function isThreadId(value) {
|
|
15
|
+
return THREAD_ID.test(value);
|
|
16
|
+
}
|
|
17
|
+
function newThreadId() {
|
|
18
|
+
return `thread_${randomUUID()}`;
|
|
19
|
+
}
|
|
20
|
+
function newMessageId() {
|
|
21
|
+
return `msg_${randomUUID()}`;
|
|
22
|
+
}
|
|
23
|
+
function threadFromContext(context) {
|
|
24
|
+
const value = context?.meshThread;
|
|
25
|
+
if (!value || typeof value !== "object") return void 0;
|
|
26
|
+
const item = value;
|
|
27
|
+
return typeof item.id === "string" && typeof item.status === "string" && Array.isArray(item.messageIds) && item.from && typeof item.from === "object" && item.to && typeof item.to === "object" ? item : void 0;
|
|
28
|
+
}
|
|
29
|
+
function startedThreadIds(context) {
|
|
30
|
+
const value = context?.meshThreads;
|
|
31
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
32
|
+
}
|
|
33
|
+
function isOpenThread(thread) {
|
|
34
|
+
return thread.status === "working" || thread.status === "waiting";
|
|
35
|
+
}
|
|
36
|
+
function clip(text, max) {
|
|
37
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
38
|
+
return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
|
|
39
|
+
}
|
|
40
|
+
function threadSubject(content) {
|
|
41
|
+
return clip(content, 120);
|
|
42
|
+
}
|
|
43
|
+
function escapeAttribute(value) {
|
|
44
|
+
return value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<");
|
|
45
|
+
}
|
|
46
|
+
function renderMeshMessage(message, side) {
|
|
47
|
+
const who = `${message.from.name} (${message.from.agentId})`;
|
|
48
|
+
const status = message.kind === "message" ? "" : ` status="${message.kind === "reply" ? "replied" : message.kind}"`;
|
|
49
|
+
const open = `<mesh-message id="${escapeAttribute(message.id)}" thread="${escapeAttribute(message.threadId)}" from="${escapeAttribute(message.from.agentId)}" name="${escapeAttribute(message.from.name)}"${status}>`;
|
|
50
|
+
const body = message.kind === "failed" ? `It stopped: ${message.content}` : message.content;
|
|
51
|
+
const lines = [open, body, "</mesh-message>"];
|
|
52
|
+
if (side === "recipient") {
|
|
53
|
+
lines.push(
|
|
54
|
+
`${who} is another agent, not the user. Your final reply goes back to them on its own, so make it the answer itself.`,
|
|
55
|
+
`If you cannot go on without something only they or their user know, ask with glove_mesh_send_message to "${message.from.agentId}".`
|
|
56
|
+
);
|
|
57
|
+
} else if (message.kind === "message") {
|
|
58
|
+
lines.push(
|
|
59
|
+
`${who} needs an answer to go on. If you know it, reply with glove_mesh_send_message to "${message.from.agentId}" with in_reply_to "${message.id}". Otherwise ask the user first, then reply.`
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
return lines.join("\n");
|
|
63
|
+
}
|
|
64
|
+
function renderMeshMessages(messages, side) {
|
|
65
|
+
return messages.map((message) => renderMeshMessage(message, side(message))).join("\n\n");
|
|
66
|
+
}
|
|
67
|
+
function renderOpenThreads(open) {
|
|
68
|
+
if (open.length === 0) return null;
|
|
69
|
+
const lines = open.map(
|
|
70
|
+
(thread) => thread.status === "waiting" ? `- ${thread.to.name} (${thread.to.agentId}), thread ${thread.id}: waiting for your answer to "${clip(thread.question ?? "", 200)}"` : `- ${thread.to.name} (${thread.to.agentId}), thread ${thread.id}: working on "${clip(thread.subject, 160)}"`
|
|
71
|
+
);
|
|
72
|
+
return [
|
|
73
|
+
"Agents still working on what you sent them (their replies arrive as <mesh-message> messages):",
|
|
74
|
+
...lines
|
|
75
|
+
].join("\n");
|
|
76
|
+
}
|
|
77
|
+
function renderOwnThread(thread) {
|
|
78
|
+
return `In this conversation you are working for ${thread.from.name} (${thread.from.agentId}), another agent. Your final reply is sent to them.`;
|
|
79
|
+
}
|
|
80
|
+
function isMeshCommand(command) {
|
|
81
|
+
return command.type === "mesh.list" || command.type === "mesh.send" || command.type === "mesh.ack";
|
|
82
|
+
}
|
|
83
|
+
function commandId() {
|
|
84
|
+
return `command_${randomUUID()}`;
|
|
85
|
+
}
|
|
86
|
+
var failure = (cause) => ({
|
|
87
|
+
status: "error",
|
|
88
|
+
data: null,
|
|
89
|
+
message: cause instanceof Error ? cause.message : String(cause)
|
|
90
|
+
});
|
|
91
|
+
function createMeshTools(context) {
|
|
92
|
+
const waitMs = context.options.waitMs ?? DEFAULT_MESH_WAIT_MS;
|
|
93
|
+
const base = () => ({
|
|
94
|
+
id: commandId(),
|
|
95
|
+
definitionId: context.definitionId,
|
|
96
|
+
agentId: context.agentId,
|
|
97
|
+
conversationId: context.conversationId,
|
|
98
|
+
workspaceId: context.workspaceId
|
|
99
|
+
});
|
|
100
|
+
const send = (input) => {
|
|
101
|
+
const command = {
|
|
102
|
+
...base(),
|
|
103
|
+
type: "mesh.send",
|
|
104
|
+
message: {
|
|
105
|
+
id: newMessageId(),
|
|
106
|
+
threadId: newThreadId(),
|
|
107
|
+
to: input.to,
|
|
108
|
+
content: input.content,
|
|
109
|
+
...input.in_reply_to ? { inReplyTo: input.in_reply_to } : {}
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
return { command, sent: () => context.call(command) };
|
|
113
|
+
};
|
|
114
|
+
return [
|
|
115
|
+
{
|
|
116
|
+
name: "glove_mesh_list_agents",
|
|
117
|
+
description: "List the agents you can message: their ids, names and what they do. Filter by a name substring.",
|
|
118
|
+
inputSchema: z.object({
|
|
119
|
+
name: z.string().optional().describe("Only agents whose name contains this, ignoring case.")
|
|
120
|
+
}),
|
|
121
|
+
async do(input) {
|
|
122
|
+
try {
|
|
123
|
+
const agents = await context.call({ ...base(), type: "mesh.list", ...input.name ? { name: input.name } : {} });
|
|
124
|
+
return { status: "success", data: { agents } };
|
|
125
|
+
} catch (cause) {
|
|
126
|
+
return failure(cause);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
name: "glove_mesh_send_message",
|
|
132
|
+
description: [
|
|
133
|
+
"Send a message to another agent by its id. A new message starts a thread: the agent works on it in its own conversation, and its reply arrives later as a <mesh-message> message.",
|
|
134
|
+
"Set in_reply_to to answer a message you received in a thread. Set blocking to wait here for the reply; if it does not come in time, end your turn and it arrives as your next message.",
|
|
135
|
+
"The other agent cannot see this conversation, so write the message so it stands alone."
|
|
136
|
+
].join(" "),
|
|
137
|
+
inputSchema: z.object({
|
|
138
|
+
to: z.string().min(1).describe("The agent's id, from glove_mesh_list_agents or a message it sent."),
|
|
139
|
+
content: z.string().min(1).describe("Everything the agent needs, in one message."),
|
|
140
|
+
in_reply_to: z.string().optional().describe("The id of the message you are answering."),
|
|
141
|
+
blocking: z.boolean().default(false).describe("Wait here for the reply.")
|
|
142
|
+
}),
|
|
143
|
+
async do(input) {
|
|
144
|
+
const { command, sent } = send(input);
|
|
145
|
+
const waiting = input.blocking ? context.waitFrom(input.to, waitMs) : void 0;
|
|
146
|
+
let result;
|
|
147
|
+
try {
|
|
148
|
+
result = await sent();
|
|
149
|
+
} catch (cause) {
|
|
150
|
+
waiting?.cancel();
|
|
151
|
+
return failure(cause);
|
|
152
|
+
}
|
|
153
|
+
const data = { message_id: result.messageId, thread_id: result.threadId, to: result.to };
|
|
154
|
+
if (!waiting) return { status: "success", data };
|
|
155
|
+
context.pending.current = { commandId: command.id, threadId: result.threadId, messageId: result.messageId };
|
|
156
|
+
const answer = await waiting.message;
|
|
157
|
+
if (answer) {
|
|
158
|
+
context.pending.current = void 0;
|
|
159
|
+
return {
|
|
160
|
+
status: "success",
|
|
161
|
+
data: {
|
|
162
|
+
...data,
|
|
163
|
+
reply: answer.kind === "failed" ? `It stopped: ${answer.content}` : answer.content,
|
|
164
|
+
reply_id: answer.id
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
return {
|
|
169
|
+
status: "success",
|
|
170
|
+
data: {
|
|
171
|
+
...data,
|
|
172
|
+
note: "No reply yet. End your turn now with one short line saying what you are waiting for. The reply arrives as your next message."
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
{
|
|
178
|
+
name: "glove_mesh_broadcast",
|
|
179
|
+
description: "Send the same message to every agent you can message. Each one starts its own thread, and each reply arrives on its own.",
|
|
180
|
+
inputSchema: z.object({
|
|
181
|
+
content: z.string().min(1).describe("The message, written to stand alone.")
|
|
182
|
+
}),
|
|
183
|
+
async do(input) {
|
|
184
|
+
try {
|
|
185
|
+
const agents = await context.call({ ...base(), type: "mesh.list" });
|
|
186
|
+
const sent = [];
|
|
187
|
+
for (const agent of agents) {
|
|
188
|
+
await send({ to: agent.id, content: input.content }).sent();
|
|
189
|
+
sent.push(agent.id);
|
|
190
|
+
}
|
|
191
|
+
return { status: "success", data: { to: sent } };
|
|
192
|
+
} catch (cause) {
|
|
193
|
+
return failure(cause);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
},
|
|
197
|
+
{
|
|
198
|
+
name: "glove_mesh_acknowledge",
|
|
199
|
+
description: "Tell an agent you got its message, without answering yet. It reaches the agent only while it is waiting for you.",
|
|
200
|
+
inputSchema: z.object({
|
|
201
|
+
message_id: z.string().min(1),
|
|
202
|
+
note: z.string().optional()
|
|
203
|
+
}),
|
|
204
|
+
async do(input) {
|
|
205
|
+
try {
|
|
206
|
+
await context.call({ ...base(), type: "mesh.ack", messageId: input.message_id, note: input.note ?? "Got it." });
|
|
207
|
+
return { status: "success", data: { acknowledged: input.message_id } };
|
|
208
|
+
} catch (cause) {
|
|
209
|
+
return failure(cause);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
];
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// src/delegation.ts
|
|
217
|
+
import { createHash, randomUUID as randomUUID2 } from "node:crypto";
|
|
3
218
|
import { mkdir, readdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
4
219
|
import { join } from "node:path";
|
|
5
220
|
import { defaultEventFormatter } from "glove-core";
|
|
6
|
-
import { z } from "zod";
|
|
221
|
+
import { z as z2 } from "zod";
|
|
7
222
|
var FOUNDRY_MAILBOX_DIRECTORY_ENV = "GLOVE_FOUNDRY_MAILBOX_DIRECTORY";
|
|
8
223
|
var FOUNDRY_CONVERSATION_LISTEN_EVENT = "foundry.conversation.listen";
|
|
9
224
|
var FOUNDRY_CONVERSATION_LEASE_EVENT = "foundry.conversation.lease";
|
|
@@ -16,7 +231,7 @@ function isDelegationId(value) {
|
|
|
16
231
|
return DELEGATION_ID.test(value);
|
|
17
232
|
}
|
|
18
233
|
function newDelegationId() {
|
|
19
|
-
return `delegation_${
|
|
234
|
+
return `delegation_${randomUUID2()}`;
|
|
20
235
|
}
|
|
21
236
|
function workerAgentId(delegatorAgentId, route) {
|
|
22
237
|
return `${delegatorAgentId}.${route.replaceAll("/", ".")}`;
|
|
@@ -47,7 +262,7 @@ function delegationFromContext(context) {
|
|
|
47
262
|
return typeof item.id === "string" && typeof item.to === "string" && typeof item.workerAgentId === "string" && typeof item.task === "string" && typeof item.status === "string" && item.from && typeof item.from === "object" ? item : void 0;
|
|
48
263
|
}
|
|
49
264
|
function undeliveredUpdate(delegation) {
|
|
50
|
-
const base = { delegationId: delegation.id, agent: delegation.to, task: delegation.task };
|
|
265
|
+
const base = { deliveryId: delegation.updateId, delegationId: delegation.id, agent: delegation.to, task: delegation.task };
|
|
51
266
|
if (delegation.undelivered === "result") return { kind: "result", ...base, result: delegation.result ?? "" };
|
|
52
267
|
if (delegation.undelivered === "question") return { kind: "question", ...base, question: delegation.question ?? "" };
|
|
53
268
|
if (delegation.undelivered === "failed") return { kind: "failed", ...base, error: delegation.error ?? "" };
|
|
@@ -56,16 +271,16 @@ function undeliveredUpdate(delegation) {
|
|
|
56
271
|
function isOpenDelegation(delegation) {
|
|
57
272
|
return delegation.status === "working" || delegation.status === "waiting";
|
|
58
273
|
}
|
|
59
|
-
function
|
|
274
|
+
function clip2(text, max) {
|
|
60
275
|
const flat = text.replace(/\s+/g, " ").trim();
|
|
61
276
|
return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
|
|
62
277
|
}
|
|
63
|
-
function
|
|
278
|
+
function escapeAttribute2(value) {
|
|
64
279
|
return value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<");
|
|
65
280
|
}
|
|
66
281
|
function renderDelegatedTask(input) {
|
|
67
282
|
return [
|
|
68
|
-
`<delegated-task id="${
|
|
283
|
+
`<delegated-task id="${escapeAttribute2(input.delegationId)}" from="${escapeAttribute2(input.from)}">`,
|
|
69
284
|
input.task,
|
|
70
285
|
"</delegated-task>",
|
|
71
286
|
`Work on this task. Your final reply is sent back to the ${input.from} agent automatically, so make it the answer itself.`,
|
|
@@ -73,17 +288,18 @@ function renderDelegatedTask(input) {
|
|
|
73
288
|
].join("\n");
|
|
74
289
|
}
|
|
75
290
|
function renderDelivery(delivery) {
|
|
76
|
-
if (delivery.kind === "transmission") return delivery.message;
|
|
291
|
+
if (delivery.kind === "transmission" || delivery.kind === "agent-message") return delivery.message;
|
|
292
|
+
if (delivery.kind === "mesh") return renderMeshMessage(delivery.message, delivery.side);
|
|
77
293
|
if (delivery.kind === "reply") {
|
|
78
294
|
return [
|
|
79
|
-
`<delegation-reply id="${
|
|
295
|
+
`<delegation-reply id="${escapeAttribute2(delivery.delegationId)}" from="${escapeAttribute2(delivery.from)}">`,
|
|
80
296
|
delivery.message,
|
|
81
297
|
"</delegation-reply>"
|
|
82
298
|
].join("\n");
|
|
83
299
|
}
|
|
84
300
|
const status = delivery.kind === "result" ? "completed" : delivery.kind;
|
|
85
|
-
const open = `<delegation id="${
|
|
86
|
-
const task = `Task: ${
|
|
301
|
+
const open = `<delegation id="${escapeAttribute2(delivery.delegationId)}" agent="${escapeAttribute2(delivery.agent)}" status="${status}">`;
|
|
302
|
+
const task = `Task: ${clip2(delivery.task, 240)}`;
|
|
87
303
|
if (delivery.kind === "result") {
|
|
88
304
|
return [open, task, "Result:", delivery.result, "</delegation>"].join("\n");
|
|
89
305
|
}
|
|
@@ -104,15 +320,15 @@ function renderDeliveries(deliveries) {
|
|
|
104
320
|
function renderOpenDelegations(open) {
|
|
105
321
|
if (open.length === 0) return null;
|
|
106
322
|
const lines = open.map(
|
|
107
|
-
(item) => item.status === "waiting" ? `- ${item.id} (${item.to}): waiting for your answer to "${
|
|
323
|
+
(item) => item.status === "waiting" ? `- ${item.id} (${item.to}): waiting for your answer to "${clip2(item.question ?? "", 200)}"` : `- ${item.id} (${item.to}): working on "${clip2(item.task, 160)}"`
|
|
108
324
|
);
|
|
109
325
|
return [
|
|
110
326
|
"Delegations still open (results and questions arrive as <delegation> messages):",
|
|
111
327
|
...lines
|
|
112
328
|
].join("\n");
|
|
113
329
|
}
|
|
114
|
-
function
|
|
115
|
-
return `command_${
|
|
330
|
+
function commandId2() {
|
|
331
|
+
return `command_${randomUUID2()}`;
|
|
116
332
|
}
|
|
117
333
|
function createDelegatorTools(context, delegates, onDelegated, onReplied = () => {
|
|
118
334
|
}) {
|
|
@@ -129,14 +345,14 @@ function createDelegatorTools(context, delegates, onDelegated, onReplied = () =>
|
|
|
129
345
|
"Agents you can delegate to:",
|
|
130
346
|
listing
|
|
131
347
|
].join("\n"),
|
|
132
|
-
inputSchema:
|
|
133
|
-
to:
|
|
134
|
-
task:
|
|
348
|
+
inputSchema: z2.object({
|
|
349
|
+
to: z2.enum(routes).describe("Which agent to hand the task to."),
|
|
350
|
+
task: z2.string().min(1).describe("Everything the agent needs to do the work, in one message.")
|
|
135
351
|
}),
|
|
136
352
|
async do(input) {
|
|
137
353
|
const delegationId = newDelegationId();
|
|
138
354
|
context.emit({
|
|
139
|
-
id:
|
|
355
|
+
id: commandId2(),
|
|
140
356
|
type: "delegate",
|
|
141
357
|
definitionId: context.definitionId,
|
|
142
358
|
agentId: context.agentId,
|
|
@@ -156,9 +372,9 @@ function createDelegatorTools(context, delegates, onDelegated, onReplied = () =>
|
|
|
156
372
|
{
|
|
157
373
|
name: "glove_foundry_reply",
|
|
158
374
|
description: "Answer a question from an agent you delegated to, or send it more instructions about that task. Use the delegation id from the <delegation> message.",
|
|
159
|
-
inputSchema:
|
|
160
|
-
delegationId:
|
|
161
|
-
message:
|
|
375
|
+
inputSchema: z2.object({
|
|
376
|
+
delegationId: z2.string().min(1).describe("The id from the delegation."),
|
|
377
|
+
message: z2.string().min(1).describe("The answer or the new instructions.")
|
|
162
378
|
}),
|
|
163
379
|
async do(input) {
|
|
164
380
|
if (!isDelegationId(input.delegationId)) {
|
|
@@ -169,7 +385,7 @@ function createDelegatorTools(context, delegates, onDelegated, onReplied = () =>
|
|
|
169
385
|
};
|
|
170
386
|
}
|
|
171
387
|
context.emit({
|
|
172
|
-
id:
|
|
388
|
+
id: commandId2(),
|
|
173
389
|
type: "delegate.reply",
|
|
174
390
|
definitionId: context.definitionId,
|
|
175
391
|
agentId: context.agentId,
|
|
@@ -192,12 +408,12 @@ function createWorkerTools(context, delegation, options) {
|
|
|
192
408
|
`Ask the ${delegation.from.definitionId} agent, who gave you this task, one question you cannot answer yourself.`,
|
|
193
409
|
"They answer from what they know or ask the user. If the answer comes quickly it is returned here; otherwise end your turn and it arrives as your next message."
|
|
194
410
|
].join(" "),
|
|
195
|
-
inputSchema:
|
|
196
|
-
question:
|
|
411
|
+
inputSchema: z2.object({
|
|
412
|
+
question: z2.string().min(1).describe("One clear question, with the options if there are any.")
|
|
197
413
|
}),
|
|
198
414
|
async do(input) {
|
|
199
415
|
const command = {
|
|
200
|
-
id:
|
|
416
|
+
id: commandId2(),
|
|
201
417
|
type: "delegate.ask",
|
|
202
418
|
definitionId: context.definitionId,
|
|
203
419
|
agentId: context.agentId,
|
|
@@ -235,48 +451,64 @@ function conversationDirectory(directory, conversationId) {
|
|
|
235
451
|
async function writeMailboxDelivery(directory, conversationId, delivery) {
|
|
236
452
|
const target = conversationDirectory(directory, conversationId);
|
|
237
453
|
await mkdir(target, { recursive: true, mode: 448 });
|
|
238
|
-
const name = `${Date.now().toString().padStart(15, "0")}-${
|
|
454
|
+
const name = `${Date.now().toString().padStart(15, "0")}-${randomUUID2()}.json`;
|
|
239
455
|
const temporary = join(target, `.tmp-${name}`);
|
|
240
456
|
await writeFile(temporary, `${JSON.stringify(delivery)}
|
|
241
457
|
`, { encoding: "utf8", mode: 384 });
|
|
242
458
|
await rename(temporary, join(target, name));
|
|
243
459
|
}
|
|
244
|
-
var DELIVERY_SCHEMA =
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
message:
|
|
460
|
+
var DELIVERY_SCHEMA = z2.intersection(z2.object({ request: z2.custom().optional(), deliveryId: z2.string().optional(), durable: z2.object({ id: z2.string(), event: z2.custom(), policy: z2.custom() }).optional() }), z2.union([
|
|
461
|
+
z2.object({ kind: z2.literal("agent-message"), pendingId: z2.string(), message: z2.string() }),
|
|
462
|
+
z2.object({
|
|
463
|
+
kind: z2.literal("mesh"),
|
|
464
|
+
side: z2.enum(["recipient", "starter"]),
|
|
465
|
+
message: z2.object({
|
|
466
|
+
kind: z2.enum(["message", "reply", "failed", "ack"]),
|
|
467
|
+
id: z2.string(),
|
|
468
|
+
threadId: z2.string(),
|
|
469
|
+
from: z2.object({ agentId: z2.string(), name: z2.string() }),
|
|
470
|
+
to: z2.string(),
|
|
471
|
+
// A read receipt's note is optional, and JSON drops it when absent.
|
|
472
|
+
content: z2.string().default(""),
|
|
473
|
+
inReplyTo: z2.string().optional(),
|
|
474
|
+
createdAt: z2.string()
|
|
475
|
+
})
|
|
476
|
+
}),
|
|
477
|
+
z2.object({
|
|
478
|
+
kind: z2.literal("reply"),
|
|
479
|
+
delegationId: z2.string(),
|
|
480
|
+
from: z2.string(),
|
|
481
|
+
message: z2.string()
|
|
250
482
|
}),
|
|
251
|
-
|
|
252
|
-
kind:
|
|
253
|
-
delegationId:
|
|
254
|
-
agent:
|
|
255
|
-
task:
|
|
256
|
-
result:
|
|
483
|
+
z2.object({
|
|
484
|
+
kind: z2.literal("result"),
|
|
485
|
+
delegationId: z2.string(),
|
|
486
|
+
agent: z2.string(),
|
|
487
|
+
task: z2.string(),
|
|
488
|
+
result: z2.string()
|
|
257
489
|
}),
|
|
258
|
-
|
|
259
|
-
kind:
|
|
260
|
-
delegationId:
|
|
261
|
-
agent:
|
|
262
|
-
task:
|
|
263
|
-
question:
|
|
490
|
+
z2.object({
|
|
491
|
+
kind: z2.literal("question"),
|
|
492
|
+
delegationId: z2.string(),
|
|
493
|
+
agent: z2.string(),
|
|
494
|
+
task: z2.string(),
|
|
495
|
+
question: z2.string()
|
|
264
496
|
}),
|
|
265
|
-
|
|
266
|
-
kind:
|
|
267
|
-
delegationId:
|
|
268
|
-
agent:
|
|
269
|
-
task:
|
|
270
|
-
error:
|
|
497
|
+
z2.object({
|
|
498
|
+
kind: z2.literal("failed"),
|
|
499
|
+
delegationId: z2.string(),
|
|
500
|
+
agent: z2.string(),
|
|
501
|
+
task: z2.string(),
|
|
502
|
+
error: z2.string()
|
|
271
503
|
}),
|
|
272
|
-
|
|
273
|
-
kind:
|
|
274
|
-
pendingId:
|
|
275
|
-
routeId:
|
|
276
|
-
eventId:
|
|
277
|
-
message:
|
|
504
|
+
z2.object({
|
|
505
|
+
kind: z2.literal("transmission"),
|
|
506
|
+
pendingId: z2.string(),
|
|
507
|
+
routeId: z2.string(),
|
|
508
|
+
eventId: z2.string(),
|
|
509
|
+
message: z2.string()
|
|
278
510
|
})
|
|
279
|
-
]);
|
|
511
|
+
]));
|
|
280
512
|
async function drainMailbox(directory, conversationId) {
|
|
281
513
|
const target = conversationDirectory(directory, conversationId);
|
|
282
514
|
let names;
|
|
@@ -341,7 +573,9 @@ function listenToConversation(options) {
|
|
|
341
573
|
}
|
|
342
574
|
function openRunMailbox(options) {
|
|
343
575
|
const waiters = /* @__PURE__ */ new Map();
|
|
576
|
+
const meshWaiters = /* @__PURE__ */ new Map();
|
|
344
577
|
const handlers = /* @__PURE__ */ new Set();
|
|
578
|
+
const meshHandlers = /* @__PURE__ */ new Set();
|
|
345
579
|
let closed = false;
|
|
346
580
|
const toHandlers = async (updates) => {
|
|
347
581
|
for (const handler of [...handlers]) await handler(updates);
|
|
@@ -353,9 +587,23 @@ function openRunMailbox(options) {
|
|
|
353
587
|
...options.pollMs !== void 0 ? { pollMs: options.pollMs } : {},
|
|
354
588
|
handler: async (deliveries) => {
|
|
355
589
|
const replies = /* @__PURE__ */ new Map();
|
|
590
|
+
const meshAnswers = /* @__PURE__ */ new Map();
|
|
591
|
+
const heardMesh = [];
|
|
356
592
|
const updates = [];
|
|
357
593
|
const rest = [];
|
|
358
594
|
for (const delivery of deliveries) {
|
|
595
|
+
if (delivery.durable?.event.expiresAt && Date.parse(delivery.durable.event.expiresAt) <= Date.now()) {
|
|
596
|
+
options.consumed?.([delivery]);
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
if (delivery.kind === "mesh") {
|
|
600
|
+
const from = delivery.message.from.agentId;
|
|
601
|
+
if (meshWaiters.has(from)) meshAnswers.set(from, [...meshAnswers.get(from) ?? [], delivery]);
|
|
602
|
+
else if (delivery.message.kind === "ack") options.consumed?.([delivery]);
|
|
603
|
+
else if (meshHandlers.size > 0) heardMesh.push(delivery);
|
|
604
|
+
else rest.push(delivery);
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
359
607
|
if (delivery.kind === "reply" && waiters.has(delivery.delegationId)) {
|
|
360
608
|
replies.set(delivery.delegationId, [...replies.get(delivery.delegationId) ?? [], delivery]);
|
|
361
609
|
} else if (isDelegationUpdate(delivery) && handlers.size > 0) {
|
|
@@ -367,7 +615,13 @@ function openRunMailbox(options) {
|
|
|
367
615
|
for (const [delegationId, batch] of replies) {
|
|
368
616
|
waiters.get(delegationId)?.({ ...batch[0], message: batch.map((reply) => reply.message).join("\n\n") });
|
|
369
617
|
}
|
|
618
|
+
for (const [from, batch] of meshAnswers) {
|
|
619
|
+
const last = batch.at(-1).message;
|
|
620
|
+
meshWaiters.get(from)?.({ ...last, content: batch.map((item) => item.message.content).join("\n\n") });
|
|
621
|
+
}
|
|
370
622
|
if (updates.length > 0) await toHandlers(updates);
|
|
623
|
+
if (heardMesh.length > 0) for (const handler of [...meshHandlers]) await handler(heardMesh.map((item) => item.message));
|
|
624
|
+
options.consumed?.([...[...replies.values()].flat(), ...[...meshAnswers.values()].flat(), ...updates, ...heardMesh]);
|
|
371
625
|
if (rest.length > 0) await options.sink.forward(rest);
|
|
372
626
|
}
|
|
373
627
|
});
|
|
@@ -391,10 +645,42 @@ function openRunMailbox(options) {
|
|
|
391
645
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
392
646
|
});
|
|
393
647
|
},
|
|
648
|
+
waitForMesh(fromAgentId, timeoutMs, signal) {
|
|
649
|
+
return new Promise((resolveMessage) => {
|
|
650
|
+
if (closed || timeoutMs <= 0 || signal.aborted || meshWaiters.has(fromAgentId)) {
|
|
651
|
+
resolveMessage(null);
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
const finish = (message) => {
|
|
655
|
+
if (meshWaiters.get(fromAgentId) !== finish) return;
|
|
656
|
+
meshWaiters.delete(fromAgentId);
|
|
657
|
+
clearTimeout(timer);
|
|
658
|
+
signal.removeEventListener("abort", onAbort);
|
|
659
|
+
resolveMessage(message);
|
|
660
|
+
};
|
|
661
|
+
const onAbort = () => finish(null);
|
|
662
|
+
const timer = setTimeout(() => finish(null), timeoutMs);
|
|
663
|
+
meshWaiters.set(fromAgentId, finish);
|
|
664
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
665
|
+
});
|
|
666
|
+
},
|
|
667
|
+
onMesh(handler) {
|
|
668
|
+
meshHandlers.add(handler);
|
|
669
|
+
const waiting = options.sink.reclaim((delivery) => delivery.kind === "mesh" && delivery.message.kind !== "ack").then(async (taken) => {
|
|
670
|
+
const messages = taken.flatMap((delivery) => delivery.kind === "mesh" ? [delivery.message] : []);
|
|
671
|
+
if (messages.length > 0) await handler(messages);
|
|
672
|
+
options.consumed?.(taken);
|
|
673
|
+
});
|
|
674
|
+
return async () => {
|
|
675
|
+
meshHandlers.delete(handler);
|
|
676
|
+
await waiting;
|
|
677
|
+
};
|
|
678
|
+
},
|
|
394
679
|
onUpdates(handler) {
|
|
395
680
|
handlers.add(handler);
|
|
396
681
|
const waiting = options.sink.reclaim(isDelegationUpdate).then(async (updates) => {
|
|
397
682
|
if (updates.length > 0) await handler(updates);
|
|
683
|
+
options.consumed?.(updates);
|
|
398
684
|
});
|
|
399
685
|
return async () => {
|
|
400
686
|
handlers.delete(handler);
|
|
@@ -405,6 +691,7 @@ function openRunMailbox(options) {
|
|
|
405
691
|
if (closed) return;
|
|
406
692
|
closed = true;
|
|
407
693
|
for (const finish of [...waiters.values()]) finish(null);
|
|
694
|
+
for (const finish of [...meshWaiters.values()]) finish(null);
|
|
408
695
|
await listener.stop(async () => {
|
|
409
696
|
for (const delivery of await options.sink.reclaim(() => true)) {
|
|
410
697
|
await writeMailboxDelivery(options.directory, options.conversationId, delivery);
|
|
@@ -415,9 +702,20 @@ function openRunMailbox(options) {
|
|
|
415
702
|
}
|
|
416
703
|
var DELIVERY_KEY = "foundry_delivery";
|
|
417
704
|
function deliveryEvent(delivery) {
|
|
705
|
+
if (delivery.durable) return { ...delivery.durable.event, metadata: { ...delivery.durable.event.metadata, [DELIVERY_KEY]: delivery } };
|
|
706
|
+
if (delivery.kind === "agent-message") return { id: `agent-message:${delivery.pendingId}`, source: "foundry:agent", kind: "agent-message", content: delivery.message, metadata: { [DELIVERY_KEY]: delivery } };
|
|
707
|
+
if (delivery.kind === "mesh") {
|
|
708
|
+
return {
|
|
709
|
+
id: `mesh:${delivery.message.id}`,
|
|
710
|
+
source: `foundry:mesh:${delivery.message.from.agentId}`,
|
|
711
|
+
kind: `mesh.${delivery.message.kind}`,
|
|
712
|
+
content: renderDelivery(delivery),
|
|
713
|
+
metadata: { [DELIVERY_KEY]: delivery }
|
|
714
|
+
};
|
|
715
|
+
}
|
|
418
716
|
if (delivery.kind === "transmission") {
|
|
419
717
|
return {
|
|
420
|
-
id: `transmission:${delivery.pendingId}
|
|
718
|
+
id: `transmission:${delivery.pendingId}`,
|
|
421
719
|
source: `foundry:route:${delivery.routeId}`,
|
|
422
720
|
kind: "transmission",
|
|
423
721
|
content: delivery.message,
|
|
@@ -426,7 +724,7 @@ function deliveryEvent(delivery) {
|
|
|
426
724
|
}
|
|
427
725
|
const from = delivery.kind === "reply" ? delivery.from : delivery.agent;
|
|
428
726
|
return {
|
|
429
|
-
id: `${delivery.kind}:${delivery.delegationId}:${
|
|
727
|
+
id: delivery.deliveryId ?? `${delivery.kind}:${delivery.delegationId}:${createHash("sha256").update(JSON.stringify(delivery)).digest("hex")}`,
|
|
430
728
|
source: `foundry:${from}`,
|
|
431
729
|
kind: `delegation.${delivery.kind}`,
|
|
432
730
|
content: renderDelivery(delivery),
|
|
@@ -436,21 +734,7 @@ function deliveryEvent(delivery) {
|
|
|
436
734
|
function deliveryOf(event) {
|
|
437
735
|
return event.metadata?.[DELIVERY_KEY];
|
|
438
736
|
}
|
|
439
|
-
var formatRunEvents =
|
|
440
|
-
const deliveries = events.map(deliveryOf).filter((delivery) => Boolean(delivery));
|
|
441
|
-
const others = events.filter((event) => !deliveryOf(event));
|
|
442
|
-
const text = renderDeliveries(deliveries);
|
|
443
|
-
if (others.length === 0) return { sender: "user", framework_context: "event", text };
|
|
444
|
-
const rest = defaultEventFormatter(others, phase);
|
|
445
|
-
if (deliveries.length === 0) return rest;
|
|
446
|
-
return {
|
|
447
|
-
...rest,
|
|
448
|
-
text: `${text}
|
|
449
|
-
|
|
450
|
-
${rest.text}`,
|
|
451
|
-
...rest.content ? { content: [{ type: "text", text }, ...rest.content] } : {}
|
|
452
|
-
};
|
|
453
|
-
};
|
|
737
|
+
var formatRunEvents = defaultEventFormatter;
|
|
454
738
|
var RunEventQueue = class {
|
|
455
739
|
events = [];
|
|
456
740
|
async push(event) {
|
|
@@ -504,6 +788,18 @@ async function waitForConversationLease(directory, runId, signal, pollMs = 25) {
|
|
|
504
788
|
}
|
|
505
789
|
|
|
506
790
|
export {
|
|
791
|
+
meshIdentity,
|
|
792
|
+
isThreadId,
|
|
793
|
+
newMessageId,
|
|
794
|
+
threadFromContext,
|
|
795
|
+
startedThreadIds,
|
|
796
|
+
isOpenThread,
|
|
797
|
+
threadSubject,
|
|
798
|
+
renderMeshMessages,
|
|
799
|
+
renderOpenThreads,
|
|
800
|
+
renderOwnThread,
|
|
801
|
+
isMeshCommand,
|
|
802
|
+
createMeshTools,
|
|
507
803
|
FOUNDRY_MAILBOX_DIRECTORY_ENV,
|
|
508
804
|
FOUNDRY_CONVERSATION_LISTEN_EVENT,
|
|
509
805
|
FOUNDRY_CONVERSATION_LEASE_EVENT,
|
|
@@ -111,6 +111,32 @@ var FoundryClient = class {
|
|
|
111
111
|
body: JSON.stringify({ definitionId, ...options })
|
|
112
112
|
}));
|
|
113
113
|
}
|
|
114
|
+
async emitEvent(target, event, policy = {}) {
|
|
115
|
+
return readResponse(await this.fetcher(`${this.baseUrl}/api/events`, {
|
|
116
|
+
method: "POST",
|
|
117
|
+
headers: { "content-type": "application/json" },
|
|
118
|
+
body: JSON.stringify({ target, event, policy })
|
|
119
|
+
}));
|
|
120
|
+
}
|
|
121
|
+
async subagents(parentAgentId) {
|
|
122
|
+
return readResponse(await this.fetcher(`${this.baseUrl}/api/agent-instances/${encodeURIComponent(parentAgentId)}/subagents`));
|
|
123
|
+
}
|
|
124
|
+
subagent(parentAgentId, name) {
|
|
125
|
+
const base = `${this.baseUrl}/api/agent-instances/${encodeURIComponent(parentAgentId)}/subagents/${encodeURIComponent(name)}`;
|
|
126
|
+
const post = async (suffix, body = {}) => readResponse(await this.fetcher(`${base}${suffix}`, {
|
|
127
|
+
method: "POST",
|
|
128
|
+
headers: { "content-type": "application/json" },
|
|
129
|
+
body: JSON.stringify(body)
|
|
130
|
+
}));
|
|
131
|
+
return {
|
|
132
|
+
ensure: () => post(""),
|
|
133
|
+
send: (message, delivery = {}) => post("/messages", { message, delivery }),
|
|
134
|
+
data: async () => readResponse(await this.fetcher(`${base}/data`)),
|
|
135
|
+
archive: () => post("/archive"),
|
|
136
|
+
resume: () => post("/resume"),
|
|
137
|
+
purge: () => post("/purge")
|
|
138
|
+
};
|
|
139
|
+
}
|
|
114
140
|
async agentInstances(definitionId) {
|
|
115
141
|
const query = definitionId ? `?definition=${encodeURIComponent(definitionId)}` : "";
|
|
116
142
|
return readResponse(await this.fetcher(`${this.baseUrl}/api/agent-instances${query}`));
|
|
@@ -322,6 +348,10 @@ var FoundryClient = class {
|
|
|
322
348
|
const suffix = query.size ? `?${query}` : "";
|
|
323
349
|
return readResponse(await this.fetcher(`${this.baseUrl}/api/approvals${suffix}`));
|
|
324
350
|
}
|
|
351
|
+
/** One approval, by id: what a link to it opens. */
|
|
352
|
+
async approval(approvalId) {
|
|
353
|
+
return readResponse(await this.fetcher(`${this.baseUrl}/api/approvals/${encodeURIComponent(approvalId)}`));
|
|
354
|
+
}
|
|
325
355
|
async resolveApproval(approvalId, decision) {
|
|
326
356
|
return readResponse(await this.fetcher(
|
|
327
357
|
`${this.baseUrl}/api/approvals/${encodeURIComponent(approvalId)}`,
|