@deepagents/experimental 4.2.1 → 5.0.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 +18 -5
- package/dist/coding-agent-reminders/context.d.ts +15 -0
- package/dist/coding-agent-reminders/context.d.ts.map +1 -0
- package/dist/coding-agent-reminders/evaluate.d.ts +3 -0
- package/dist/coding-agent-reminders/evaluate.d.ts.map +1 -0
- package/dist/coding-agent-reminders/index.d.ts +5 -0
- package/dist/coding-agent-reminders/index.d.ts.map +1 -0
- package/dist/coding-agent-reminders/index.js +310 -0
- package/dist/coding-agent-reminders/index.js.map +7 -0
- package/dist/coding-agent-reminders/io.d.ts +4 -0
- package/dist/coding-agent-reminders/io.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/classifier.d.ts +10 -0
- package/dist/coding-agent-reminders/predicates/classifier.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/combinators.d.ts +6 -0
- package/dist/coding-agent-reminders/predicates/combinators.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/content.d.ts +7 -0
- package/dist/coding-agent-reminders/predicates/content.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/count.d.ts +4 -0
- package/dist/coding-agent-reminders/predicates/count.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/environment.d.ts +3 -0
- package/dist/coding-agent-reminders/predicates/environment.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/event.d.ts +3 -0
- package/dist/coding-agent-reminders/predicates/event.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/index.d.ts +8 -0
- package/dist/coding-agent-reminders/predicates/index.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/tool.d.ts +11 -0
- package/dist/coding-agent-reminders/predicates/tool.d.ts.map +1 -0
- package/dist/coding-agent-reminders/types.d.ts +86 -0
- package/dist/coding-agent-reminders/types.d.ts.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2036 -158
- package/dist/index.js.map +4 -4
- package/dist/zukhruf/agent-control-plane.d.ts +68 -0
- package/dist/zukhruf/agent-control-plane.d.ts.map +1 -0
- package/dist/zukhruf/agent-declaration-registry.d.ts +9 -0
- package/dist/zukhruf/agent-declaration-registry.d.ts.map +1 -0
- package/dist/zukhruf/agent-directory.d.ts +21 -0
- package/dist/zukhruf/agent-directory.d.ts.map +1 -0
- package/dist/zukhruf/agent-path.d.ts +15 -0
- package/dist/zukhruf/agent-path.d.ts.map +1 -0
- package/dist/zukhruf/agent-runtime.d.ts +53 -0
- package/dist/zukhruf/agent-runtime.d.ts.map +1 -0
- package/dist/zukhruf/agent-status-projector.d.ts +32 -0
- package/dist/zukhruf/agent-status-projector.d.ts.map +1 -0
- package/dist/zukhruf/agent-thread.d.ts +31 -0
- package/dist/zukhruf/agent-thread.d.ts.map +1 -0
- package/dist/zukhruf/agent-tool-context.d.ts +6 -0
- package/dist/zukhruf/agent-tool-context.d.ts.map +1 -0
- package/dist/zukhruf/agent-turn-executor.d.ts +19 -0
- package/dist/zukhruf/agent-turn-executor.d.ts.map +1 -0
- package/dist/zukhruf/agent-turn-id.d.ts +11 -0
- package/dist/zukhruf/agent-turn-id.d.ts.map +1 -0
- package/dist/zukhruf/agent.d.ts +13 -8
- package/dist/zukhruf/agent.d.ts.map +1 -1
- package/dist/zukhruf/approval-controller.d.ts +34 -0
- package/dist/zukhruf/approval-controller.d.ts.map +1 -0
- package/dist/zukhruf/approval-mutex.d.ts +5 -0
- package/dist/zukhruf/approval-mutex.d.ts.map +1 -0
- package/dist/zukhruf/index.d.ts +15 -11
- package/dist/zukhruf/index.d.ts.map +1 -1
- package/dist/zukhruf/index.js +1716 -152
- package/dist/zukhruf/index.js.map +4 -4
- package/dist/zukhruf/list-agents.d.ts +234 -0
- package/dist/zukhruf/list-agents.d.ts.map +1 -0
- package/dist/zukhruf/mailbox/coordinator.d.ts +22 -0
- package/dist/zukhruf/mailbox/coordinator.d.ts.map +1 -0
- package/dist/zukhruf/mailbox/sqlite.store.d.ts +16 -0
- package/dist/zukhruf/mailbox/sqlite.store.d.ts.map +1 -0
- package/dist/zukhruf/mailbox/store.d.ts +20 -0
- package/dist/zukhruf/mailbox/store.d.ts.map +1 -0
- package/dist/zukhruf/mailbox/types.d.ts +35 -0
- package/dist/zukhruf/mailbox/types.d.ts.map +1 -0
- package/dist/zukhruf/message-tools.d.ts +456 -0
- package/dist/zukhruf/message-tools.d.ts.map +1 -0
- package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +2 -1
- package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
- package/dist/zukhruf/queue/turn-queue.d.ts +14 -0
- package/dist/zukhruf/queue/turn-queue.d.ts.map +1 -1
- package/dist/zukhruf/spawn-agent.d.ts +301 -0
- package/dist/zukhruf/spawn-agent.d.ts.map +1 -0
- package/dist/zukhruf/sqlite-approval-mutex.d.ts +17 -0
- package/dist/zukhruf/sqlite-approval-mutex.d.ts.map +1 -0
- package/package.json +14 -7
- package/dist/zukhruf/runtime.d.ts +0 -67
- package/dist/zukhruf/runtime.d.ts.map +0 -1
package/dist/zukhruf/index.js
CHANGED
|
@@ -1,217 +1,1674 @@
|
|
|
1
|
+
// packages/experimental/src/zukhruf/agent-path.ts
|
|
2
|
+
var AgentPath = class _AgentPath {
|
|
3
|
+
#value;
|
|
4
|
+
constructor(value) {
|
|
5
|
+
this.#value = value;
|
|
6
|
+
}
|
|
7
|
+
static root() {
|
|
8
|
+
return new _AgentPath("/root");
|
|
9
|
+
}
|
|
10
|
+
static parse(value) {
|
|
11
|
+
const path = value.trim();
|
|
12
|
+
if (path !== "/root" && !path.startsWith("/root/")) {
|
|
13
|
+
throw new Error(`agent path "${value}" must start at /root`);
|
|
14
|
+
}
|
|
15
|
+
const segments = path.slice(1).split("/");
|
|
16
|
+
if (segments.some(
|
|
17
|
+
(segment) => segment.length === 0 || segment !== segment.trim() || segment === "." || segment === ".."
|
|
18
|
+
)) {
|
|
19
|
+
throw new Error(`agent path "${value}" contains an invalid segment`);
|
|
20
|
+
}
|
|
21
|
+
return new _AgentPath(path);
|
|
22
|
+
}
|
|
23
|
+
/** Relative targets name descendants; absolute targets keep their canonical path. */
|
|
24
|
+
resolve(target) {
|
|
25
|
+
const requested = target.trim();
|
|
26
|
+
if (!requested) throw new Error("agent path cannot be empty");
|
|
27
|
+
return _AgentPath.parse(
|
|
28
|
+
requested.startsWith("/") ? requested : `${this.#value}/${requested}`
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
contains(candidate) {
|
|
32
|
+
return this.equals(candidate) || candidate.#value.startsWith(`${this.#value}/`);
|
|
33
|
+
}
|
|
34
|
+
equals(other) {
|
|
35
|
+
return this.#value === other.#value;
|
|
36
|
+
}
|
|
37
|
+
get isRoot() {
|
|
38
|
+
return this.#value === "/root";
|
|
39
|
+
}
|
|
40
|
+
get parent() {
|
|
41
|
+
if (this.isRoot) return null;
|
|
42
|
+
return _AgentPath.parse(this.#value.slice(0, this.#value.lastIndexOf("/")));
|
|
43
|
+
}
|
|
44
|
+
toString() {
|
|
45
|
+
return this.#value;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
// packages/experimental/src/zukhruf/agent-thread.ts
|
|
50
|
+
var AgentThread = class _AgentThread {
|
|
51
|
+
conversation;
|
|
52
|
+
treeId;
|
|
53
|
+
path;
|
|
54
|
+
parentChatId;
|
|
55
|
+
declarationName;
|
|
56
|
+
lastTurnId;
|
|
57
|
+
constructor(options) {
|
|
58
|
+
_AgentThread.#assertTopology(options);
|
|
59
|
+
this.conversation = options.conversation;
|
|
60
|
+
this.treeId = options.treeId;
|
|
61
|
+
this.path = options.path;
|
|
62
|
+
this.parentChatId = options.parentChatId;
|
|
63
|
+
this.declarationName = options.declarationName;
|
|
64
|
+
this.lastTurnId = options.lastTurnId;
|
|
65
|
+
}
|
|
66
|
+
static root(conversation, declarationName) {
|
|
67
|
+
return new _AgentThread({
|
|
68
|
+
conversation,
|
|
69
|
+
treeId: conversation.chatId,
|
|
70
|
+
path: AgentPath.root(),
|
|
71
|
+
parentChatId: null,
|
|
72
|
+
declarationName
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
static metadataFilter(treeId) {
|
|
76
|
+
return { key: "zukhrufTreeId", value: treeId };
|
|
77
|
+
}
|
|
78
|
+
static hasReservedMetadata(metadata) {
|
|
79
|
+
return Boolean(
|
|
80
|
+
metadata && (Object.hasOwn(metadata, "zukhrufTreeId") || Object.hasOwn(metadata, "zukhruf"))
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
static fromMetadata(conversation, metadata) {
|
|
84
|
+
const treeId = metadata?.zukhrufTreeId;
|
|
85
|
+
const zukhruf = metadata?.zukhruf;
|
|
86
|
+
if (typeof treeId !== "string" || !_AgentThread.#isRecord(zukhruf)) {
|
|
87
|
+
return void 0;
|
|
88
|
+
}
|
|
89
|
+
const { path, parentChatId, declarationName, lastTurnId } = zukhruf;
|
|
90
|
+
if (typeof path !== "string" || parentChatId !== null && typeof parentChatId !== "string" || typeof declarationName !== "string" || lastTurnId !== void 0 && typeof lastTurnId !== "string") {
|
|
91
|
+
return void 0;
|
|
92
|
+
}
|
|
93
|
+
let parsedPath;
|
|
94
|
+
try {
|
|
95
|
+
parsedPath = AgentPath.parse(path);
|
|
96
|
+
} catch {
|
|
97
|
+
return void 0;
|
|
98
|
+
}
|
|
99
|
+
if (parsedPath.toString() !== path) return void 0;
|
|
100
|
+
try {
|
|
101
|
+
return new _AgentThread({
|
|
102
|
+
conversation,
|
|
103
|
+
treeId,
|
|
104
|
+
path: parsedPath,
|
|
105
|
+
parentChatId,
|
|
106
|
+
declarationName,
|
|
107
|
+
...lastTurnId === void 0 ? {} : { lastTurnId }
|
|
108
|
+
});
|
|
109
|
+
} catch {
|
|
110
|
+
return void 0;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
withLatestTurn(lastTurnId) {
|
|
114
|
+
return new _AgentThread({
|
|
115
|
+
conversation: this.conversation,
|
|
116
|
+
treeId: this.treeId,
|
|
117
|
+
path: this.path,
|
|
118
|
+
parentChatId: this.parentChatId,
|
|
119
|
+
declarationName: this.declarationName,
|
|
120
|
+
lastTurnId
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
toMetadata(metadata) {
|
|
124
|
+
const existing = _AgentThread.#isRecord(metadata?.zukhruf) ? metadata.zukhruf : {};
|
|
125
|
+
return {
|
|
126
|
+
...metadata,
|
|
127
|
+
zukhrufTreeId: this.treeId,
|
|
128
|
+
zukhruf: {
|
|
129
|
+
...existing,
|
|
130
|
+
path: this.path.toString(),
|
|
131
|
+
parentChatId: this.parentChatId,
|
|
132
|
+
declarationName: this.declarationName,
|
|
133
|
+
...this.lastTurnId === void 0 ? {} : { lastTurnId: this.lastTurnId }
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
static #isRecord(value) {
|
|
138
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
139
|
+
}
|
|
140
|
+
static #assertTopology(options) {
|
|
141
|
+
if (options.path.isRoot) {
|
|
142
|
+
if (options.treeId !== options.conversation.chatId) {
|
|
143
|
+
throw new Error("root agent thread treeId must match its chatId");
|
|
144
|
+
}
|
|
145
|
+
if (options.parentChatId !== null) {
|
|
146
|
+
throw new Error("root agent thread cannot have a parent");
|
|
147
|
+
}
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (options.parentChatId === null) {
|
|
151
|
+
throw new Error("child agent thread requires a parent");
|
|
152
|
+
}
|
|
153
|
+
if (options.parentChatId === options.conversation.chatId) {
|
|
154
|
+
throw new Error("child agent thread cannot parent itself");
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
|
|
1
159
|
// packages/experimental/src/zukhruf/agent.ts
|
|
2
160
|
function defineAgent(declaration) {
|
|
3
161
|
return {
|
|
4
|
-
name: declaration.name
|
|
162
|
+
name: declaration.name,
|
|
5
163
|
model: declaration.model,
|
|
6
164
|
sandbox: declaration.sandbox,
|
|
7
165
|
instructions: declaration.instructions,
|
|
8
|
-
tools: declaration.tools
|
|
166
|
+
tools: declaration.tools ?? {},
|
|
167
|
+
subagents: declaration.subagents ?? [],
|
|
168
|
+
telemetry: declaration.telemetry
|
|
9
169
|
};
|
|
10
170
|
}
|
|
11
171
|
|
|
12
|
-
// packages/experimental/src/zukhruf/
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
172
|
+
// packages/experimental/src/zukhruf/agent-runtime.ts
|
|
173
|
+
import {
|
|
174
|
+
ContextEngine as ContextEngine4,
|
|
175
|
+
PollingChangeSource,
|
|
176
|
+
StreamManager
|
|
177
|
+
} from "@deepagents/context";
|
|
16
178
|
|
|
17
|
-
// packages/experimental/src/zukhruf/
|
|
18
|
-
import {
|
|
179
|
+
// packages/experimental/src/zukhruf/agent-control-plane.ts
|
|
180
|
+
import { v5 as uuidv53 } from "uuid";
|
|
19
181
|
|
|
20
|
-
// packages/experimental/src/zukhruf/
|
|
182
|
+
// packages/experimental/src/zukhruf/agent-declaration-registry.ts
|
|
183
|
+
var AgentDeclarationRegistry = class {
|
|
184
|
+
root;
|
|
185
|
+
#declarations = /* @__PURE__ */ new Map();
|
|
186
|
+
constructor(root) {
|
|
187
|
+
this.root = root;
|
|
188
|
+
this.#register(root, /* @__PURE__ */ new Set());
|
|
189
|
+
}
|
|
190
|
+
get(name) {
|
|
191
|
+
return this.#declarations.get(name);
|
|
192
|
+
}
|
|
193
|
+
#register(declaration, visited) {
|
|
194
|
+
if (visited.has(declaration)) return;
|
|
195
|
+
visited.add(declaration);
|
|
196
|
+
if (!declaration.name.trim()) {
|
|
197
|
+
throw new Error("AgentRuntime: agent declaration name cannot be empty");
|
|
198
|
+
}
|
|
199
|
+
if (declaration.name !== declaration.name.trim()) {
|
|
200
|
+
throw new Error(
|
|
201
|
+
`AgentRuntime: agent declaration name "${declaration.name}" must not contain surrounding whitespace`
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
const existing = this.#declarations.get(declaration.name);
|
|
205
|
+
if (existing && existing !== declaration) {
|
|
206
|
+
throw new Error(
|
|
207
|
+
`AgentRuntime: duplicate agent declaration name "${declaration.name}"`
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
this.#declarations.set(declaration.name, declaration);
|
|
211
|
+
for (const subagent of declaration.subagents ?? []) {
|
|
212
|
+
this.#register(subagent, visited);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
// packages/experimental/src/zukhruf/agent-directory.ts
|
|
218
|
+
import { v5 as uuidv5 } from "uuid";
|
|
219
|
+
var AgentDirectory = class _AgentDirectory {
|
|
220
|
+
#store;
|
|
221
|
+
constructor(store) {
|
|
222
|
+
this.#store = store;
|
|
223
|
+
}
|
|
224
|
+
async assertOwnerIfExists(conversation) {
|
|
225
|
+
const chat2 = await this.#store.getChat(conversation.chatId);
|
|
226
|
+
if (!chat2) return;
|
|
227
|
+
this.#assertOwner(conversation, chat2.userId);
|
|
228
|
+
const thread = this.#threadFromMetadata(conversation, chat2.metadata);
|
|
229
|
+
if (thread) await this.#assertValidParent(thread);
|
|
230
|
+
}
|
|
231
|
+
async load(conversation) {
|
|
232
|
+
const chat2 = await this.#store.getChat(conversation.chatId);
|
|
233
|
+
if (chat2) this.#assertOwner(conversation, chat2.userId);
|
|
234
|
+
if (!chat2) return void 0;
|
|
235
|
+
const thread = this.#threadFromMetadata(conversation, chat2.metadata);
|
|
236
|
+
if (thread) await this.#assertValidParent(thread);
|
|
237
|
+
return thread;
|
|
238
|
+
}
|
|
239
|
+
async loadOrCreateRoot(conversation, declarationName) {
|
|
240
|
+
await this.#store.upsertChat({
|
|
241
|
+
id: conversation.chatId,
|
|
242
|
+
userId: conversation.userId
|
|
243
|
+
});
|
|
244
|
+
let thread;
|
|
245
|
+
let adopted = false;
|
|
246
|
+
await this.#store.updateChat(conversation.chatId, (chat2) => {
|
|
247
|
+
this.#assertOwner(conversation, chat2.userId);
|
|
248
|
+
const existing = this.#threadFromMetadata(conversation, chat2.metadata);
|
|
249
|
+
if (existing) {
|
|
250
|
+
thread = existing;
|
|
251
|
+
adopted = true;
|
|
252
|
+
return void 0;
|
|
253
|
+
}
|
|
254
|
+
thread = AgentThread.root(conversation, declarationName);
|
|
255
|
+
adopted = false;
|
|
256
|
+
return { metadata: thread.toMetadata(chat2.metadata) };
|
|
257
|
+
});
|
|
258
|
+
if (adopted) {
|
|
259
|
+
await this.#assertValidParent(thread);
|
|
260
|
+
}
|
|
261
|
+
return thread;
|
|
262
|
+
}
|
|
263
|
+
async recordLatestTurn(conversation, streamId) {
|
|
264
|
+
return this.#updateLatestTurn(conversation, streamId);
|
|
265
|
+
}
|
|
266
|
+
async recordLatestTurnIfCurrent(conversation, streamId, expectedLastTurnId) {
|
|
267
|
+
return this.#updateLatestTurn(conversation, streamId, expectedLastTurnId);
|
|
268
|
+
}
|
|
269
|
+
async listTree(thread) {
|
|
270
|
+
const chats = await this.#store.listChats({
|
|
271
|
+
userId: thread.conversation.userId,
|
|
272
|
+
metadata: AgentThread.metadataFilter(thread.treeId)
|
|
273
|
+
});
|
|
274
|
+
return Promise.all(
|
|
275
|
+
chats.map(async (chat2) => {
|
|
276
|
+
const conversation = { chatId: chat2.id, userId: chat2.userId };
|
|
277
|
+
const member = this.#threadFromMetadata(conversation, chat2.metadata);
|
|
278
|
+
if (!member) {
|
|
279
|
+
throw new Error(
|
|
280
|
+
`AgentDirectory.listTree: chat "${chat2.id}" is missing Zukhruf metadata`
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
await this.#assertValidParent(member);
|
|
284
|
+
return member;
|
|
285
|
+
})
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
async resolve(thread, target) {
|
|
289
|
+
const path = thread.path.resolve(target);
|
|
290
|
+
const match = (await this.listTree(thread)).find(
|
|
291
|
+
(candidate) => candidate.path.equals(path)
|
|
292
|
+
);
|
|
293
|
+
if (match) return match;
|
|
294
|
+
throw new Error(`agent path "${path}" does not exist in this tree`);
|
|
295
|
+
}
|
|
296
|
+
async createChild(options) {
|
|
297
|
+
const path = options.parent.path.resolve(options.taskName);
|
|
298
|
+
const pathString = path.toString();
|
|
299
|
+
const conversation = {
|
|
300
|
+
chatId: _AgentDirectory.#childChatId(
|
|
301
|
+
options.parent.conversation.userId,
|
|
302
|
+
options.parent.treeId,
|
|
303
|
+
pathString
|
|
304
|
+
),
|
|
305
|
+
userId: options.parent.conversation.userId
|
|
306
|
+
};
|
|
307
|
+
const occupied = (await this.listTree(options.parent)).find(
|
|
308
|
+
(thread) => thread.path.equals(path)
|
|
309
|
+
);
|
|
310
|
+
if (occupied && occupied.conversation.chatId !== conversation.chatId) {
|
|
311
|
+
throw new Error(`agent path "${pathString}" already exists`);
|
|
312
|
+
}
|
|
313
|
+
const child = new AgentThread({
|
|
314
|
+
conversation,
|
|
315
|
+
treeId: options.parent.treeId,
|
|
316
|
+
path,
|
|
317
|
+
parentChatId: options.parent.conversation.chatId,
|
|
318
|
+
declarationName: options.declarationName
|
|
319
|
+
});
|
|
320
|
+
const storedChat = await this.#store.upsertChat({
|
|
321
|
+
id: conversation.chatId,
|
|
322
|
+
userId: conversation.userId,
|
|
323
|
+
metadata: child.toMetadata(void 0)
|
|
324
|
+
});
|
|
325
|
+
const stored = AgentThread.fromMetadata(
|
|
326
|
+
{ chatId: storedChat.id, userId: storedChat.userId },
|
|
327
|
+
storedChat.metadata
|
|
328
|
+
);
|
|
329
|
+
if (storedChat.userId !== conversation.userId || stored?.treeId !== child.treeId || !stored.path.equals(child.path) || stored.parentChatId !== child.parentChatId || stored.declarationName !== child.declarationName) {
|
|
330
|
+
throw new Error(`agent path "${pathString}" already exists`);
|
|
331
|
+
}
|
|
332
|
+
return stored;
|
|
333
|
+
}
|
|
334
|
+
static #childChatId(userId, treeId, path) {
|
|
335
|
+
return uuidv5(
|
|
336
|
+
`urn:deepagents:zukhruf:agent:${JSON.stringify([userId, treeId, path])}`,
|
|
337
|
+
uuidv5.URL
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
#assertOwner(conversation, storedUserId) {
|
|
341
|
+
if (storedUserId === conversation.userId) return;
|
|
342
|
+
throw new Error(
|
|
343
|
+
`chat "${conversation.chatId}" belongs to user "${storedUserId}", not "${conversation.userId}"`
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
#threadFromMetadata(conversation, metadata) {
|
|
347
|
+
const thread = AgentThread.fromMetadata(conversation, metadata);
|
|
348
|
+
if (!thread && AgentThread.hasReservedMetadata(metadata)) {
|
|
349
|
+
throw new Error(
|
|
350
|
+
`invalid Zukhruf metadata for chat "${conversation.chatId}"`
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
return thread;
|
|
354
|
+
}
|
|
355
|
+
async #assertValidParent(thread) {
|
|
356
|
+
if (thread.path.isRoot) return;
|
|
357
|
+
const parentChatId = thread.parentChatId;
|
|
358
|
+
if (!parentChatId) {
|
|
359
|
+
throw new Error(
|
|
360
|
+
`invalid Zukhruf parent for chat "${thread.conversation.chatId}"`
|
|
361
|
+
);
|
|
362
|
+
}
|
|
363
|
+
const parentChat = await this.#store.getChat(parentChatId);
|
|
364
|
+
if (!parentChat || parentChat.userId !== thread.conversation.userId) {
|
|
365
|
+
throw new Error(
|
|
366
|
+
`invalid Zukhruf parent for chat "${thread.conversation.chatId}"`
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
const parent = this.#threadFromMetadata(
|
|
370
|
+
{ chatId: parentChat.id, userId: parentChat.userId },
|
|
371
|
+
parentChat.metadata
|
|
372
|
+
);
|
|
373
|
+
const expectedPath = thread.path.parent;
|
|
374
|
+
if (!parent || !expectedPath || parent.treeId !== thread.treeId || !parent.path.equals(expectedPath)) {
|
|
375
|
+
throw new Error(
|
|
376
|
+
`invalid Zukhruf parent for chat "${thread.conversation.chatId}"`
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
async #updateLatestTurn(conversation, streamId, ...expected) {
|
|
381
|
+
let result;
|
|
382
|
+
await this.#store.updateChat(conversation.chatId, (chat2) => {
|
|
383
|
+
this.#assertOwner(conversation, chat2.userId);
|
|
384
|
+
const thread = this.#threadFromMetadata(conversation, chat2.metadata);
|
|
385
|
+
if (!thread) {
|
|
386
|
+
throw new Error(
|
|
387
|
+
`AgentDirectory.recordLatestTurn: missing agent metadata for chat "${conversation.chatId}"`
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
if (expected.length > 0 && thread.lastTurnId !== expected[0]) {
|
|
391
|
+
result = void 0;
|
|
392
|
+
return void 0;
|
|
393
|
+
}
|
|
394
|
+
if (thread.lastTurnId === streamId) {
|
|
395
|
+
result = thread;
|
|
396
|
+
return void 0;
|
|
397
|
+
}
|
|
398
|
+
result = thread.withLatestTurn(streamId);
|
|
399
|
+
return { metadata: result.toMetadata(chat2.metadata) };
|
|
400
|
+
});
|
|
401
|
+
return result;
|
|
402
|
+
}
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
// packages/experimental/src/zukhruf/agent-status-projector.ts
|
|
406
|
+
import { isTextUIPart } from "ai";
|
|
21
407
|
import {
|
|
22
|
-
|
|
408
|
+
ContextEngine
|
|
23
409
|
} from "@deepagents/context";
|
|
24
|
-
|
|
25
|
-
|
|
410
|
+
|
|
411
|
+
// packages/experimental/src/zukhruf/mailbox/types.ts
|
|
412
|
+
import { randomUUID } from "node:crypto";
|
|
413
|
+
var MessageDeliveryMode = {
|
|
414
|
+
QueueOnly: "queue-only",
|
|
415
|
+
TriggerTurn: "trigger-turn"
|
|
416
|
+
};
|
|
417
|
+
var InterAgentCommunicationType = {
|
|
418
|
+
Message: "MESSAGE",
|
|
419
|
+
NewTask: "NEW_TASK",
|
|
420
|
+
FinalAnswer: "FINAL_ANSWER"
|
|
421
|
+
};
|
|
422
|
+
function createInterAgentCommunication(communication) {
|
|
423
|
+
const value = {
|
|
424
|
+
...communication,
|
|
425
|
+
id: communication.id ?? randomUUID(),
|
|
426
|
+
type: communication.type ?? InterAgentCommunicationType.Message,
|
|
427
|
+
otherRecipients: communication.otherRecipients ?? [],
|
|
428
|
+
triggerTurn: false
|
|
429
|
+
};
|
|
430
|
+
assertCommunication(value);
|
|
431
|
+
return value;
|
|
432
|
+
}
|
|
433
|
+
function assertCommunication(communication) {
|
|
434
|
+
if (!communication.id.trim()) {
|
|
435
|
+
throw new Error("inter-agent communication id cannot be empty");
|
|
436
|
+
}
|
|
437
|
+
if (!Object.values(InterAgentCommunicationType).includes(communication.type)) {
|
|
438
|
+
throw new Error("inter-agent communication type is invalid");
|
|
439
|
+
}
|
|
440
|
+
assertConversationId(communication.author, "author");
|
|
441
|
+
assertConversationId(communication.recipient, "recipient");
|
|
442
|
+
for (const recipient of communication.otherRecipients) {
|
|
443
|
+
assertConversationId(recipient, "other recipient");
|
|
444
|
+
}
|
|
445
|
+
if (!communication.content.trim()) {
|
|
446
|
+
throw new Error("inter-agent communication content cannot be empty");
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
function assertConversationId(value, label) {
|
|
450
|
+
if (!value.chatId.trim() || !value.userId.trim()) {
|
|
451
|
+
throw new Error(
|
|
452
|
+
`inter-agent communication ${label} requires chatId and userId`
|
|
453
|
+
);
|
|
454
|
+
}
|
|
26
455
|
}
|
|
27
456
|
|
|
28
|
-
// packages/experimental/src/zukhruf/
|
|
29
|
-
|
|
457
|
+
// packages/experimental/src/zukhruf/agent-status-projector.ts
|
|
458
|
+
var AgentStatusProjector = class _AgentStatusProjector {
|
|
459
|
+
#store;
|
|
460
|
+
#streams;
|
|
461
|
+
#queue;
|
|
462
|
+
#mailbox;
|
|
463
|
+
#directory;
|
|
464
|
+
#approvals;
|
|
465
|
+
constructor(options) {
|
|
466
|
+
this.#store = options.store;
|
|
467
|
+
this.#streams = options.streams;
|
|
468
|
+
this.#queue = options.queue;
|
|
469
|
+
this.#mailbox = options.mailbox;
|
|
470
|
+
this.#directory = options.directory;
|
|
471
|
+
this.#approvals = options.approvals;
|
|
472
|
+
}
|
|
473
|
+
async projectListedAgent(currentTurn, thread) {
|
|
474
|
+
const messages = await this.#messages(thread);
|
|
475
|
+
const head = messages.at(-1);
|
|
476
|
+
const streamId = thread.lastTurnId ?? (head?.role === "assistant" ? head.id : void 0);
|
|
477
|
+
const stream = streamId ? await this.#streams.store.getStream(streamId) : void 0;
|
|
478
|
+
const activity = await this.#queue.getTurnActivity(thread.conversation);
|
|
479
|
+
let status = _AgentStatusProjector.#listedStatus(
|
|
480
|
+
stream?.status,
|
|
481
|
+
stream?.error,
|
|
482
|
+
head
|
|
483
|
+
);
|
|
484
|
+
if (stream?.status === "completed" && this.#approvals.isPaused(head)) {
|
|
485
|
+
status = "waiting_approval";
|
|
486
|
+
}
|
|
487
|
+
if (thread.conversation.chatId === currentTurn.chatId || activity === "running" || activity === "queued" && stream !== void 0) {
|
|
488
|
+
status = "running";
|
|
489
|
+
}
|
|
490
|
+
return {
|
|
491
|
+
agent_name: thread.path.toString(),
|
|
492
|
+
agent_status: status,
|
|
493
|
+
last_task_message: thread.path.isRoot ? "Main thread" : _AgentStatusProjector.#lastUserMessage(messages)
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
async projectTerminal(turn, thread) {
|
|
497
|
+
if (thread.parentChatId === null) return;
|
|
498
|
+
const stream = await this.#streams.store.getStream(turn.streamId);
|
|
499
|
+
if (!stream || stream.status !== "completed" && stream.status !== "failed" && stream.status !== "cancelled") {
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
const message = (await this.#messages(thread)).find(
|
|
503
|
+
(candidate) => candidate.role === "assistant" && candidate.id === turn.streamId
|
|
504
|
+
);
|
|
505
|
+
if (stream.status === "completed" && this.#approvals.isPaused(message)) {
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
const text = message?.role === "assistant" ? _AgentStatusProjector.#messageText(message) : "";
|
|
509
|
+
const content = stream.status === "failed" ? `Agent failed: ${stream.error || "unknown error"}` : stream.status === "cancelled" ? "Agent was interrupted." : text || "Agent completed without a text response.";
|
|
510
|
+
const parent = await this.#directory.load({
|
|
511
|
+
chatId: thread.parentChatId,
|
|
512
|
+
userId: thread.conversation.userId
|
|
513
|
+
});
|
|
514
|
+
await this.#mailbox.deliver(
|
|
515
|
+
createInterAgentCommunication({
|
|
516
|
+
id: `zukhruf:child-terminal:${turn.streamId}`,
|
|
517
|
+
type: InterAgentCommunicationType.FinalAnswer,
|
|
518
|
+
author: thread.conversation,
|
|
519
|
+
recipient: {
|
|
520
|
+
chatId: thread.parentChatId,
|
|
521
|
+
userId: thread.conversation.userId
|
|
522
|
+
},
|
|
523
|
+
content,
|
|
524
|
+
metadata: {
|
|
525
|
+
authorPath: thread.path.toString(),
|
|
526
|
+
recipientPath: parent?.path.toString() ?? thread.parentChatId,
|
|
527
|
+
streamId: turn.streamId,
|
|
528
|
+
status: stream.status
|
|
529
|
+
}
|
|
530
|
+
}),
|
|
531
|
+
MessageDeliveryMode.QueueOnly
|
|
532
|
+
);
|
|
533
|
+
}
|
|
534
|
+
async #messages(thread) {
|
|
535
|
+
const engine = new ContextEngine({
|
|
536
|
+
store: this.#store,
|
|
537
|
+
chatId: thread.conversation.chatId,
|
|
538
|
+
userId: thread.conversation.userId
|
|
539
|
+
});
|
|
540
|
+
return engine.getMessages();
|
|
541
|
+
}
|
|
542
|
+
static #listedStatus(status, error, head) {
|
|
543
|
+
switch (status) {
|
|
544
|
+
case "running":
|
|
545
|
+
return "running";
|
|
546
|
+
case "completed":
|
|
547
|
+
return {
|
|
548
|
+
completed: head?.role === "assistant" ? _AgentStatusProjector.#messageText(head) || null : null
|
|
549
|
+
};
|
|
550
|
+
case "failed":
|
|
551
|
+
return { errored: error || "Agent turn failed." };
|
|
552
|
+
case "cancelled":
|
|
553
|
+
return "interrupted";
|
|
554
|
+
case "queued":
|
|
555
|
+
case void 0:
|
|
556
|
+
return "pending_init";
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
static #lastUserMessage(messages) {
|
|
560
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
561
|
+
const message = messages[index];
|
|
562
|
+
if (message?.role === "user") {
|
|
563
|
+
return _AgentStatusProjector.#messageText(message) || null;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
return null;
|
|
567
|
+
}
|
|
568
|
+
static #messageText(message) {
|
|
569
|
+
return message.parts.filter(isTextUIPart).map((part) => part.text).join("\n").trim();
|
|
570
|
+
}
|
|
571
|
+
};
|
|
572
|
+
|
|
573
|
+
// packages/experimental/src/zukhruf/agent-turn-id.ts
|
|
574
|
+
import { v5 as uuidv52 } from "uuid";
|
|
575
|
+
var AgentTurnId = class _AgentTurnId {
|
|
576
|
+
static #prefix = "zukhruf-turn";
|
|
577
|
+
#value;
|
|
578
|
+
constructor(value) {
|
|
579
|
+
this.#value = value;
|
|
580
|
+
}
|
|
581
|
+
static fromRequest(conversation, requestId) {
|
|
582
|
+
if (!requestId.trim()) {
|
|
583
|
+
throw new Error("turn id cannot be empty");
|
|
584
|
+
}
|
|
585
|
+
const scope = _AgentTurnId.#scope(conversation);
|
|
586
|
+
return new _AgentTurnId(
|
|
587
|
+
`${_AgentTurnId.#prefix}:${scope}:${uuidv52(requestId, scope)}`
|
|
588
|
+
);
|
|
589
|
+
}
|
|
590
|
+
static random(conversation) {
|
|
591
|
+
return _AgentTurnId.fromRequest(conversation, crypto.randomUUID());
|
|
592
|
+
}
|
|
593
|
+
static assertOwner(conversation, streamId) {
|
|
594
|
+
const expectedPrefix = `${_AgentTurnId.#prefix}:${_AgentTurnId.#scope(conversation)}:`;
|
|
595
|
+
if (!streamId.startsWith(expectedPrefix)) {
|
|
596
|
+
throw new Error(
|
|
597
|
+
`stream "${streamId}" does not belong to conversation "${conversation.chatId}"`
|
|
598
|
+
);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
toString() {
|
|
602
|
+
return this.#value;
|
|
603
|
+
}
|
|
604
|
+
static #scope(conversation) {
|
|
605
|
+
if (!conversation.chatId.trim() || !conversation.userId.trim()) {
|
|
606
|
+
throw new Error("conversation requires non-empty chatId and userId");
|
|
607
|
+
}
|
|
608
|
+
return uuidv52(
|
|
609
|
+
JSON.stringify([conversation.userId, conversation.chatId]),
|
|
610
|
+
uuidv52.URL
|
|
611
|
+
);
|
|
612
|
+
}
|
|
613
|
+
};
|
|
614
|
+
|
|
615
|
+
// packages/experimental/src/zukhruf/agent-control-plane.ts
|
|
616
|
+
var AgentControlPlane = class _AgentControlPlane {
|
|
617
|
+
#root;
|
|
618
|
+
#streams;
|
|
619
|
+
#queue;
|
|
620
|
+
#mailbox;
|
|
621
|
+
#declarations;
|
|
622
|
+
#directory;
|
|
623
|
+
#statusProjector;
|
|
624
|
+
constructor(options) {
|
|
625
|
+
this.#root = options.root;
|
|
626
|
+
this.#streams = options.streams;
|
|
627
|
+
this.#queue = options.queue;
|
|
628
|
+
this.#mailbox = options.mailbox;
|
|
629
|
+
this.#declarations = options.declarations;
|
|
630
|
+
this.#directory = options.directory;
|
|
631
|
+
this.#statusProjector = options.statusProjector;
|
|
632
|
+
}
|
|
633
|
+
async resolve(conversation) {
|
|
634
|
+
const thread = await this.#directory.loadOrCreateRoot(
|
|
635
|
+
conversation,
|
|
636
|
+
this.#root.name
|
|
637
|
+
);
|
|
638
|
+
const declaration = this.#declarations.get(thread.declarationName);
|
|
639
|
+
if (!declaration) {
|
|
640
|
+
throw new Error(
|
|
641
|
+
`AgentControlPlane.resolve: unknown agent declaration "${thread.declarationName}"`
|
|
642
|
+
);
|
|
643
|
+
}
|
|
644
|
+
return { declaration, thread };
|
|
645
|
+
}
|
|
646
|
+
async enqueue(conversation, turn) {
|
|
647
|
+
if (!turn.id.trim()) {
|
|
648
|
+
throw new Error(
|
|
649
|
+
"enqueue: turn id is required \u2014 it names the ask, making retries idempotent"
|
|
650
|
+
);
|
|
651
|
+
}
|
|
652
|
+
await this.#directory.assertOwnerIfExists(conversation);
|
|
653
|
+
const streamId = AgentTurnId.fromRequest(conversation, turn.id).toString();
|
|
654
|
+
await this.#streams.register(streamId);
|
|
655
|
+
await this.#queue.push({
|
|
656
|
+
kind: "ask",
|
|
657
|
+
streamId,
|
|
658
|
+
chatId: conversation.chatId,
|
|
659
|
+
userId: conversation.userId,
|
|
660
|
+
input: turn.input
|
|
661
|
+
});
|
|
662
|
+
return streamId;
|
|
663
|
+
}
|
|
664
|
+
recordLatestTurn(conversation, streamId) {
|
|
665
|
+
return this.#directory.recordLatestTurn(conversation, streamId);
|
|
666
|
+
}
|
|
667
|
+
recordLatestTurnIfCurrent(conversation, streamId, expectedLastTurnId) {
|
|
668
|
+
return this.#directory.recordLatestTurnIfCurrent(
|
|
669
|
+
conversation,
|
|
670
|
+
streamId,
|
|
671
|
+
expectedLastTurnId
|
|
672
|
+
);
|
|
673
|
+
}
|
|
674
|
+
async spawn(actor, input) {
|
|
675
|
+
const childDeclaration = (actor.declaration.subagents ?? []).find(
|
|
676
|
+
(subagent) => subagent.name === input.agentType
|
|
677
|
+
);
|
|
678
|
+
if (!childDeclaration) {
|
|
679
|
+
throw new Error(
|
|
680
|
+
`spawn_agent: agent type "${input.agentType}" is not a subagent of "${actor.declaration.name}"`
|
|
681
|
+
);
|
|
682
|
+
}
|
|
683
|
+
let child;
|
|
684
|
+
try {
|
|
685
|
+
child = await this.#directory.createChild({
|
|
686
|
+
parent: actor.thread,
|
|
687
|
+
taskName: input.taskName,
|
|
688
|
+
declarationName: childDeclaration.name
|
|
689
|
+
});
|
|
690
|
+
} catch (error) {
|
|
691
|
+
if (error instanceof Error && error.message.startsWith("agent path ")) {
|
|
692
|
+
throw new Error(`spawn_agent: ${error.message}`);
|
|
693
|
+
}
|
|
694
|
+
throw error;
|
|
695
|
+
}
|
|
696
|
+
const childPath = child.path.toString();
|
|
697
|
+
const requestId = _AgentControlPlane.#initialTurnId(
|
|
698
|
+
child.conversation.chatId
|
|
699
|
+
);
|
|
700
|
+
const streamId = AgentTurnId.fromRequest(
|
|
701
|
+
child.conversation,
|
|
702
|
+
requestId
|
|
703
|
+
).toString();
|
|
704
|
+
const status = await this.#streams.store.getStreamStatus(streamId);
|
|
705
|
+
if (status === "completed" || status === "failed" || status === "cancelled") {
|
|
706
|
+
throw new Error(
|
|
707
|
+
`spawn_agent: agent path "${childPath}" already finished with status "${status}"`
|
|
708
|
+
);
|
|
709
|
+
}
|
|
710
|
+
await this.enqueue(child.conversation, {
|
|
711
|
+
id: requestId,
|
|
712
|
+
input: input.message
|
|
713
|
+
});
|
|
714
|
+
return { task_name: input.taskName, agent_path: childPath };
|
|
715
|
+
}
|
|
716
|
+
async sendMessage(actor, input) {
|
|
717
|
+
return this.#deliverAgentMessage(actor, input, {
|
|
718
|
+
type: InterAgentCommunicationType.Message,
|
|
719
|
+
mode: MessageDeliveryMode.QueueOnly,
|
|
720
|
+
rejectRoot: false
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
async followupTask(actor, input) {
|
|
724
|
+
return this.#deliverAgentMessage(actor, input, {
|
|
725
|
+
type: InterAgentCommunicationType.NewTask,
|
|
726
|
+
mode: MessageDeliveryMode.TriggerTurn,
|
|
727
|
+
rejectRoot: true
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
async listAgents(actor, pathPrefix) {
|
|
731
|
+
const prefix = pathPrefix ? actor.thread.path.resolve(pathPrefix) : void 0;
|
|
732
|
+
const threads = await this.#directory.listTree(actor.thread);
|
|
733
|
+
const agents = await Promise.all(
|
|
734
|
+
threads.flatMap((thread) => {
|
|
735
|
+
if (prefix && !prefix.contains(thread.path)) return [];
|
|
736
|
+
return [this.#statusProjector.projectListedAgent(actor.turn, thread)];
|
|
737
|
+
})
|
|
738
|
+
);
|
|
739
|
+
agents.sort(
|
|
740
|
+
(left, right) => left.agent_name.localeCompare(right.agent_name)
|
|
741
|
+
);
|
|
742
|
+
return { agents };
|
|
743
|
+
}
|
|
744
|
+
async projectTerminal(turn, thread) {
|
|
745
|
+
await this.#statusProjector.projectTerminal(turn, thread);
|
|
746
|
+
}
|
|
747
|
+
async #deliverAgentMessage(actor, input, options) {
|
|
748
|
+
const target = await this.#directory.resolve(actor.thread, input.target);
|
|
749
|
+
if (options.rejectRoot && target.path.isRoot) {
|
|
750
|
+
throw new Error(
|
|
751
|
+
"followup_task: the root agent cannot receive a follow-up"
|
|
752
|
+
);
|
|
753
|
+
}
|
|
754
|
+
await this.#mailbox.deliver(
|
|
755
|
+
createInterAgentCommunication({
|
|
756
|
+
type: options.type,
|
|
757
|
+
author: actor.thread.conversation,
|
|
758
|
+
recipient: target.conversation,
|
|
759
|
+
content: input.message,
|
|
760
|
+
metadata: {
|
|
761
|
+
authorPath: actor.thread.path.toString(),
|
|
762
|
+
recipientPath: target.path.toString()
|
|
763
|
+
}
|
|
764
|
+
}),
|
|
765
|
+
options.mode
|
|
766
|
+
);
|
|
767
|
+
return { target: target.path.toString() };
|
|
768
|
+
}
|
|
769
|
+
static #initialTurnId(chatId) {
|
|
770
|
+
return uuidv53(`urn:deepagents:zukhruf:initial-turn:${chatId}`, uuidv53.URL);
|
|
771
|
+
}
|
|
772
|
+
};
|
|
773
|
+
|
|
774
|
+
// packages/experimental/src/zukhruf/agent-turn-executor.ts
|
|
30
775
|
import {
|
|
31
|
-
ContextEngine,
|
|
32
|
-
PollingChangeSource,
|
|
33
|
-
StreamManager,
|
|
776
|
+
ContextEngine as ContextEngine2,
|
|
34
777
|
agent,
|
|
35
778
|
assistant,
|
|
36
779
|
chat,
|
|
37
780
|
user
|
|
38
781
|
} from "@deepagents/context";
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
782
|
+
|
|
783
|
+
// packages/experimental/src/zukhruf/list-agents.ts
|
|
784
|
+
import { tool } from "ai";
|
|
785
|
+
import { z } from "zod";
|
|
786
|
+
var listAgentsInputSchema = z.object({
|
|
787
|
+
path_prefix: z.string().trim().min(1).describe(
|
|
788
|
+
"Task-path prefix without a trailing slash. Omit to list the whole tree."
|
|
789
|
+
).optional()
|
|
790
|
+
});
|
|
791
|
+
var listAgentsTool = tool({
|
|
792
|
+
description: "List live agents in the current root thread tree. Optionally filter by task-path prefix.",
|
|
793
|
+
inputSchema: listAgentsInputSchema,
|
|
794
|
+
execute: async ({ path_prefix }, { context }) => context.controlPlane.listAgents(context.actor, path_prefix)
|
|
795
|
+
});
|
|
796
|
+
|
|
797
|
+
// packages/experimental/src/zukhruf/message-tools.ts
|
|
798
|
+
import { tool as tool2 } from "ai";
|
|
799
|
+
import { z as z2 } from "zod";
|
|
800
|
+
var agentMessageInputSchema = z2.object({
|
|
801
|
+
target: z2.string().trim().min(1).describe(
|
|
802
|
+
"The canonical /root/... path, or a descendant-relative target name."
|
|
803
|
+
),
|
|
804
|
+
message: z2.string().trim().min(1).describe("The message or follow-up task.")
|
|
805
|
+
});
|
|
806
|
+
var sendMessageTool = tool2({
|
|
807
|
+
description: "Queue a message for another agent. Address siblings with their canonical /root/... path.",
|
|
808
|
+
inputSchema: agentMessageInputSchema,
|
|
809
|
+
execute: async (input, { context }) => context.controlPlane.sendMessage(context.actor, input)
|
|
810
|
+
});
|
|
811
|
+
var followupTaskTool = tool2({
|
|
812
|
+
description: "Send a follow-up task to an existing non-root agent and wake its thread.",
|
|
813
|
+
inputSchema: agentMessageInputSchema,
|
|
814
|
+
execute: async (input, { context }) => context.controlPlane.followupTask(context.actor, input)
|
|
815
|
+
});
|
|
816
|
+
|
|
817
|
+
// packages/experimental/src/zukhruf/spawn-agent.ts
|
|
818
|
+
import { tool as tool3 } from "ai";
|
|
819
|
+
import { z as z3 } from "zod";
|
|
820
|
+
var spawnAgentInputSchema = z3.object({
|
|
821
|
+
agent_type: z3.string().trim().min(1).describe("The name of one available subagent declaration."),
|
|
822
|
+
task_name: z3.string().trim().min(1).refine(
|
|
823
|
+
(value) => value !== "." && value !== ".." && !value.includes("/"),
|
|
824
|
+
"task_name must be one non-empty path segment"
|
|
825
|
+
).describe("One path segment naming this independent agent task."),
|
|
826
|
+
message: z3.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent.")
|
|
827
|
+
});
|
|
828
|
+
var spawnAgentTool = tool3({
|
|
829
|
+
description: ({ context }) => {
|
|
830
|
+
const available = (context.actor.declaration.subagents ?? []).map((subagent) => subagent.name).join(", ");
|
|
831
|
+
return `Spawn an independent subagent. Available agent types: ${available || "none"}.`;
|
|
832
|
+
},
|
|
833
|
+
inputSchema: spawnAgentInputSchema,
|
|
834
|
+
execute: async ({ agent_type, task_name, message }, { context }) => context.controlPlane.spawn(context.actor, {
|
|
835
|
+
agentType: agent_type,
|
|
836
|
+
taskName: task_name,
|
|
837
|
+
message
|
|
838
|
+
})
|
|
839
|
+
});
|
|
840
|
+
|
|
841
|
+
// packages/experimental/src/zukhruf/agent-turn-executor.ts
|
|
842
|
+
var AgentTurnExecutor = class {
|
|
843
|
+
#store;
|
|
844
|
+
#streams;
|
|
845
|
+
#controlPlane;
|
|
846
|
+
#mailbox;
|
|
847
|
+
#approvals;
|
|
848
|
+
constructor(options) {
|
|
849
|
+
this.#store = options.store;
|
|
850
|
+
this.#streams = options.streams;
|
|
851
|
+
this.#controlPlane = options.controlPlane;
|
|
852
|
+
this.#mailbox = options.mailbox;
|
|
853
|
+
this.#approvals = options.approvals;
|
|
854
|
+
}
|
|
855
|
+
async execute(turn, context) {
|
|
856
|
+
if (await this.#projectSkippedTerminalTurn(turn)) return;
|
|
857
|
+
let parked = false;
|
|
858
|
+
await this.#mailbox.beginTurn(turn);
|
|
859
|
+
try {
|
|
860
|
+
await this.#executeTurn(turn, {
|
|
861
|
+
...context,
|
|
862
|
+
park: async () => {
|
|
863
|
+
parked = true;
|
|
864
|
+
await context.park();
|
|
865
|
+
}
|
|
866
|
+
});
|
|
867
|
+
} finally {
|
|
868
|
+
await this.#mailbox.endTurn(turn, { parked });
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
async #executeTurn(turn, { signal, park }) {
|
|
872
|
+
if (await this.#projectSkippedTerminalTurn(turn)) return;
|
|
873
|
+
const { declaration, thread } = await this.#controlPlane.resolve(turn);
|
|
874
|
+
const engine = this.#engineFor(turn).set(...declaration.instructions);
|
|
875
|
+
if (turn.kind === "ask" || turn.kind === "mailbox") {
|
|
63
876
|
const head = (await engine.getMessages()).at(-1);
|
|
64
|
-
if (
|
|
877
|
+
if (this.#approvals.isPaused(head)) {
|
|
65
878
|
await park();
|
|
66
879
|
return;
|
|
67
880
|
}
|
|
68
|
-
engine.set(
|
|
69
|
-
user(turn.input),
|
|
70
|
-
assistant({ id: turn.streamId, role: "assistant", parts: [] })
|
|
71
|
-
);
|
|
72
|
-
await engine.save({ branch: true });
|
|
73
881
|
}
|
|
882
|
+
const communications = turn.kind === "ask" ? await this.#mailbox.drainLeadingQueueOnly(turn) : turn.kind === "mailbox" ? await this.#mailbox.drain(turn) : [];
|
|
883
|
+
if (turn.kind === "mailbox" && communications.length === 0) {
|
|
884
|
+
await this.#streams.store.updateStreamStatus(turn.streamId, "completed");
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
887
|
+
await this.#controlPlane.recordLatestTurn(turn, turn.streamId);
|
|
888
|
+
await this.#prepareChain(turn, engine, communications);
|
|
74
889
|
const sandbox = await declaration.sandbox({
|
|
75
890
|
chatId: turn.chatId,
|
|
76
891
|
userId: turn.userId
|
|
77
892
|
});
|
|
893
|
+
if (await this.#projectSkippedTerminalTurn(turn)) return;
|
|
894
|
+
if (!await this.#streams.claim(turn.streamId)) {
|
|
895
|
+
await this.#projectSkippedTerminalTurn(turn);
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
const mailboxState = { firstRequest: true };
|
|
78
899
|
const ai = agent({
|
|
79
900
|
name: declaration.name,
|
|
80
901
|
model: declaration.model,
|
|
81
902
|
sandbox,
|
|
82
903
|
context: engine,
|
|
83
|
-
tools:
|
|
904
|
+
tools: {
|
|
905
|
+
...declaration.tools,
|
|
906
|
+
spawn_agent: spawnAgentTool,
|
|
907
|
+
send_message: sendMessageTool,
|
|
908
|
+
followup_task: followupTaskTool,
|
|
909
|
+
list_agents: listAgentsTool
|
|
910
|
+
},
|
|
911
|
+
telemetry: declaration.telemetry,
|
|
912
|
+
prepareStepInput: () => this.#prepareStepInput(turn, mailboxState)
|
|
84
913
|
});
|
|
85
914
|
const abort = new AbortController();
|
|
86
915
|
const onWorkerAbort = () => abort.abort();
|
|
87
916
|
signal.addEventListener("abort", onWorkerAbort, { once: true });
|
|
88
917
|
try {
|
|
89
|
-
const
|
|
90
|
-
|
|
918
|
+
const setupCancellation = this.#streams.monitorCancellation(
|
|
919
|
+
turn.streamId,
|
|
920
|
+
() => abort.abort()
|
|
921
|
+
);
|
|
922
|
+
let stream;
|
|
923
|
+
try {
|
|
924
|
+
stream = await chat(ai, {
|
|
925
|
+
abortSignal: abort.signal,
|
|
926
|
+
contextVariables: {
|
|
927
|
+
controlPlane: this.#controlPlane,
|
|
928
|
+
actor: { turn, thread, declaration }
|
|
929
|
+
}
|
|
930
|
+
});
|
|
931
|
+
} finally {
|
|
932
|
+
await setupCancellation[Symbol.asyncDispose]();
|
|
933
|
+
}
|
|
934
|
+
await this.#streams.persist(stream, turn.streamId, {
|
|
935
|
+
preclaimed: true,
|
|
91
936
|
onCancelDetected: () => abort.abort()
|
|
92
937
|
});
|
|
938
|
+
if (turn.kind === "continuation") {
|
|
939
|
+
await this.#reconcileTerminalContinuation(turn);
|
|
940
|
+
}
|
|
941
|
+
await this.#controlPlane.projectTerminal(turn, thread);
|
|
93
942
|
} finally {
|
|
94
943
|
signal.removeEventListener("abort", onWorkerAbort);
|
|
95
944
|
}
|
|
96
945
|
}
|
|
97
|
-
async
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
if (
|
|
101
|
-
|
|
102
|
-
|
|
946
|
+
async #projectSkippedTerminalTurn(turn) {
|
|
947
|
+
const status = await this.#streams.store.getStreamStatus(turn.streamId);
|
|
948
|
+
if (status === "queued" || status === "running") return false;
|
|
949
|
+
if (status === void 0 || turn.kind === "mailbox") return true;
|
|
950
|
+
if (turn.kind === "continuation") {
|
|
951
|
+
await this.#reconcileTerminalContinuation(turn);
|
|
952
|
+
}
|
|
953
|
+
const { thread } = await this.#controlPlane.resolve(turn);
|
|
954
|
+
if (thread.lastTurnId === void 0 || thread.lastTurnId === turn.streamId) {
|
|
955
|
+
await this.#controlPlane.recordLatestTurnIfCurrent(
|
|
956
|
+
turn,
|
|
957
|
+
turn.streamId,
|
|
958
|
+
thread.lastTurnId
|
|
103
959
|
);
|
|
104
960
|
}
|
|
105
|
-
|
|
106
|
-
|
|
961
|
+
await this.#controlPlane.projectTerminal(turn, thread);
|
|
962
|
+
return true;
|
|
963
|
+
}
|
|
964
|
+
async #reconcileTerminalContinuation(turn) {
|
|
965
|
+
const stream = await this.#streams.store.getStream(turn.streamId);
|
|
966
|
+
if (stream?.status !== "completed" && stream?.status !== "failed" && stream?.status !== "cancelled") {
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
969
|
+
await this.#approvals.reconcileTerminalContinuation(
|
|
970
|
+
turn,
|
|
971
|
+
turn.streamId,
|
|
972
|
+
stream.status,
|
|
973
|
+
stream.error
|
|
107
974
|
);
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
975
|
+
}
|
|
976
|
+
async #prepareChain(turn, engine, communications) {
|
|
977
|
+
if (turn.kind === "ask") {
|
|
978
|
+
engine.set(
|
|
979
|
+
...communications.map(
|
|
980
|
+
(communication) => user(this.#mailboxInputMessage(communication))
|
|
981
|
+
),
|
|
982
|
+
user(turn.input),
|
|
983
|
+
assistant({ id: turn.streamId, role: "assistant", parts: [] })
|
|
111
984
|
);
|
|
985
|
+
await engine.save({ branch: true });
|
|
986
|
+
} else if (turn.kind === "mailbox") {
|
|
987
|
+
engine.set(
|
|
988
|
+
...communications.map(
|
|
989
|
+
(communication) => user(this.#mailboxInputMessage(communication))
|
|
990
|
+
),
|
|
991
|
+
assistant({ id: turn.streamId, role: "assistant", parts: [] })
|
|
992
|
+
);
|
|
993
|
+
await engine.save({ branch: true });
|
|
112
994
|
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
995
|
+
}
|
|
996
|
+
async #prepareStepInput(turn, state) {
|
|
997
|
+
const communications = turn.kind === "ask" && state.firstRequest ? await this.#mailbox.drainLeadingQueueOnly(turn) : await this.#mailbox.drain(turn);
|
|
998
|
+
state.firstRequest = false;
|
|
999
|
+
return communications.length === 0 ? void 0 : communications.map(
|
|
1000
|
+
(communication) => this.#mailboxInputMessage(communication)
|
|
1001
|
+
);
|
|
1002
|
+
}
|
|
1003
|
+
#engineFor({ chatId, userId }) {
|
|
1004
|
+
return new ContextEngine2({ store: this.#store, chatId, userId });
|
|
1005
|
+
}
|
|
1006
|
+
#mailboxInputMessage(communication) {
|
|
1007
|
+
return {
|
|
1008
|
+
id: crypto.randomUUID(),
|
|
1009
|
+
role: "user",
|
|
1010
|
+
parts: [
|
|
1011
|
+
{
|
|
1012
|
+
type: "text",
|
|
1013
|
+
text: this.#renderInterAgentCommunication(communication)
|
|
1014
|
+
}
|
|
1015
|
+
],
|
|
1016
|
+
metadata: { interAgentCommunication: communication }
|
|
120
1017
|
};
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
1018
|
+
}
|
|
1019
|
+
#renderInterAgentCommunication(communication) {
|
|
1020
|
+
const recipientPath = communication.metadata?.recipientPath;
|
|
1021
|
+
const authorPath = communication.metadata?.authorPath;
|
|
1022
|
+
const taskName = typeof recipientPath === "string" ? recipientPath : communication.recipient.chatId;
|
|
1023
|
+
const sender = typeof authorPath === "string" ? authorPath : communication.author.chatId;
|
|
1024
|
+
return `Message Type: ${communication.type}
|
|
1025
|
+
Task name: ${taskName}
|
|
1026
|
+
Sender: ${sender}
|
|
1027
|
+
Payload:
|
|
1028
|
+
${communication.content}`;
|
|
1029
|
+
}
|
|
1030
|
+
};
|
|
1031
|
+
|
|
1032
|
+
// packages/experimental/src/zukhruf/approval-controller.ts
|
|
1033
|
+
import {
|
|
1034
|
+
isToolUIPart
|
|
1035
|
+
} from "ai";
|
|
1036
|
+
import {
|
|
1037
|
+
ContextEngine as ContextEngine3,
|
|
1038
|
+
assistant as assistant2
|
|
1039
|
+
} from "@deepagents/context";
|
|
1040
|
+
var ApprovalController = class _ApprovalController {
|
|
1041
|
+
static #settledToolStates = /* @__PURE__ */ new Set([
|
|
1042
|
+
"output-available",
|
|
1043
|
+
"output-error",
|
|
1044
|
+
"output-denied"
|
|
1045
|
+
]);
|
|
1046
|
+
#store;
|
|
1047
|
+
#streams;
|
|
1048
|
+
#queue;
|
|
1049
|
+
#mutex;
|
|
1050
|
+
constructor(options) {
|
|
1051
|
+
this.#store = options.store;
|
|
1052
|
+
this.#streams = options.streams;
|
|
1053
|
+
this.#queue = options.queue;
|
|
1054
|
+
this.#mutex = options.mutex;
|
|
1055
|
+
}
|
|
1056
|
+
isPaused(message) {
|
|
1057
|
+
return message?.role === "assistant" && this.#pendingToolPart(message) !== void 0;
|
|
1058
|
+
}
|
|
1059
|
+
approve(conversation, input) {
|
|
1060
|
+
return this.#respond("approve", conversation, input.toolCallId, {
|
|
1061
|
+
approved: true
|
|
1062
|
+
});
|
|
1063
|
+
}
|
|
1064
|
+
deny(conversation, input) {
|
|
1065
|
+
return this.#respond("deny", conversation, input.toolCallId, {
|
|
1066
|
+
approved: false,
|
|
1067
|
+
reason: input.reason
|
|
1068
|
+
});
|
|
1069
|
+
}
|
|
1070
|
+
async settleDeniedApprovals(conversation, streamId) {
|
|
1071
|
+
await this.#mutex.runExclusive(conversation.chatId, async () => {
|
|
1072
|
+
const engine = this.#engineFor(conversation);
|
|
1073
|
+
const head = (await engine.getMessages()).at(-1);
|
|
1074
|
+
if (head?.role !== "assistant" || head.id !== streamId) return;
|
|
1075
|
+
const denied = head.parts.filter(
|
|
1076
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === false
|
|
1077
|
+
);
|
|
1078
|
+
if (denied.length === 0) return;
|
|
1079
|
+
const updated = {
|
|
1080
|
+
...head,
|
|
1081
|
+
parts: head.parts.map(
|
|
1082
|
+
(part) => denied.includes(part) ? { ...part, state: "output-denied" } : part
|
|
1083
|
+
)
|
|
1084
|
+
};
|
|
1085
|
+
await engine.continue(assistant2(updated));
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
async settleFailedApprovals(conversation, streamId, error) {
|
|
1089
|
+
await this.#mutex.runExclusive(conversation.chatId, async () => {
|
|
1090
|
+
const engine = this.#engineFor(conversation);
|
|
1091
|
+
const head = (await engine.getMessages()).at(-1);
|
|
1092
|
+
if (head?.role !== "assistant" || head.id !== streamId) return;
|
|
1093
|
+
const responded = head.parts.filter(
|
|
1094
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded"
|
|
1095
|
+
);
|
|
1096
|
+
if (responded.length === 0) return;
|
|
1097
|
+
const updated = {
|
|
1098
|
+
...head,
|
|
1099
|
+
parts: head.parts.map(
|
|
1100
|
+
(part) => isToolUIPart(part) && part.state === "approval-responded" ? part.approval.approved === false ? { ...part, state: "output-denied" } : { ...part, state: "output-error", errorText: error } : part
|
|
1101
|
+
)
|
|
1102
|
+
};
|
|
1103
|
+
await engine.continue(assistant2(updated));
|
|
1104
|
+
});
|
|
1105
|
+
}
|
|
1106
|
+
async reconcileTerminalContinuation(conversation, streamId, status, error) {
|
|
1107
|
+
if (status === "completed") {
|
|
1108
|
+
await this.settleDeniedApprovals(conversation, streamId);
|
|
1109
|
+
} else {
|
|
1110
|
+
await this.settleFailedApprovals(
|
|
1111
|
+
conversation,
|
|
1112
|
+
streamId,
|
|
1113
|
+
error ?? (status === "cancelled" ? "approval continuation cancelled" : "approval continuation failed")
|
|
1114
|
+
);
|
|
1115
|
+
}
|
|
1116
|
+
await this.#queue.resumeParked(conversation.chatId);
|
|
1117
|
+
}
|
|
1118
|
+
async #respond(operation, conversation, toolCallId, approval) {
|
|
1119
|
+
const result = await this.#mutex.runExclusive(
|
|
1120
|
+
conversation.chatId,
|
|
1121
|
+
async () => {
|
|
1122
|
+
const engine = this.#engineFor(conversation);
|
|
1123
|
+
const head = (await engine.getMessages()).at(-1);
|
|
1124
|
+
if (head?.role !== "assistant") {
|
|
1125
|
+
throw new Error(
|
|
1126
|
+
`ApprovalController.${operation}: no paused turn \u2014 the chain head is not an assistant message`
|
|
1127
|
+
);
|
|
1128
|
+
}
|
|
1129
|
+
const part = this.#findToolPart(head, toolCallId);
|
|
1130
|
+
if (!part) {
|
|
1131
|
+
throw new Error(
|
|
1132
|
+
`ApprovalController.${operation}: no tool call "${toolCallId}" on the paused turn`
|
|
1133
|
+
);
|
|
1134
|
+
}
|
|
1135
|
+
if (part.approval?.approved !== void 0 && part.approval.approved !== approval.approved) {
|
|
1136
|
+
throw new Error(
|
|
1137
|
+
`ApprovalController.${operation}: approval already answered with a different decision`
|
|
1138
|
+
);
|
|
1139
|
+
}
|
|
1140
|
+
let updated = head;
|
|
1141
|
+
let answered = part;
|
|
1142
|
+
if (part.state === "approval-requested") {
|
|
1143
|
+
const responded = {
|
|
1144
|
+
...part,
|
|
1145
|
+
state: "approval-responded",
|
|
1146
|
+
approval: { ...part.approval, ...approval }
|
|
1147
|
+
};
|
|
1148
|
+
updated = {
|
|
1149
|
+
...head,
|
|
1150
|
+
parts: head.parts.map(
|
|
1151
|
+
(candidate) => candidate === part ? responded : candidate
|
|
1152
|
+
)
|
|
1153
|
+
};
|
|
1154
|
+
await engine.continue(assistant2(updated));
|
|
1155
|
+
answered = responded;
|
|
1156
|
+
}
|
|
1157
|
+
return {
|
|
1158
|
+
id: updated.id,
|
|
1159
|
+
hasUnansweredApprovals: this.#hasUnansweredApprovals(updated),
|
|
1160
|
+
shouldSchedule: answered.state === "approval-responded"
|
|
1161
|
+
};
|
|
1162
|
+
}
|
|
1163
|
+
);
|
|
1164
|
+
if (!result.hasUnansweredApprovals) {
|
|
1165
|
+
if (result.shouldSchedule) {
|
|
1166
|
+
await this.#scheduleContinuation(conversation, result.id);
|
|
1167
|
+
} else {
|
|
1168
|
+
await this.#queue.resumeParked(conversation.chatId);
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
return { id: result.id, stream: this.#streams.watch(result.id) };
|
|
1172
|
+
}
|
|
1173
|
+
async #scheduleContinuation(conversation, streamId) {
|
|
1174
|
+
let status = await this.#streams.store.getStreamStatus(streamId);
|
|
1175
|
+
if (status === "completed") {
|
|
1176
|
+
try {
|
|
1177
|
+
await this.#streams.reopen(streamId);
|
|
1178
|
+
status = "queued";
|
|
1179
|
+
} catch (error) {
|
|
1180
|
+
status = await this.#streams.store.getStreamStatus(streamId);
|
|
1181
|
+
if (status !== "queued" && status !== "running") throw error;
|
|
1182
|
+
}
|
|
1183
|
+
} else if (status !== "queued" && status !== "running") {
|
|
1184
|
+
return;
|
|
1185
|
+
}
|
|
1186
|
+
if (status !== "running") {
|
|
1187
|
+
await this.#queue.push({
|
|
1188
|
+
kind: "continuation",
|
|
1189
|
+
streamId,
|
|
1190
|
+
chatId: conversation.chatId,
|
|
1191
|
+
userId: conversation.userId
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
await this.#queue.resumeParked(conversation.chatId);
|
|
1195
|
+
}
|
|
1196
|
+
#pendingToolPart(message) {
|
|
1197
|
+
return message.parts.find(
|
|
1198
|
+
(part) => isToolUIPart(part) && !_ApprovalController.#settledToolStates.has(part.state)
|
|
1199
|
+
);
|
|
1200
|
+
}
|
|
1201
|
+
#hasUnansweredApprovals(message) {
|
|
1202
|
+
return message.parts.some(
|
|
1203
|
+
(part) => isToolUIPart(part) && part.state === "approval-requested"
|
|
1204
|
+
);
|
|
1205
|
+
}
|
|
1206
|
+
#findToolPart(message, toolCallId) {
|
|
1207
|
+
return message.parts.find(
|
|
1208
|
+
(part) => isToolUIPart(part) && part.toolCallId === toolCallId
|
|
1209
|
+
);
|
|
1210
|
+
}
|
|
1211
|
+
#engineFor({ chatId, userId }) {
|
|
1212
|
+
return new ContextEngine3({ store: this.#store, chatId, userId });
|
|
1213
|
+
}
|
|
1214
|
+
};
|
|
1215
|
+
|
|
1216
|
+
// packages/experimental/src/zukhruf/mailbox/coordinator.ts
|
|
1217
|
+
var MailboxCoordinator = class {
|
|
1218
|
+
#store;
|
|
1219
|
+
#queue;
|
|
1220
|
+
#streams;
|
|
1221
|
+
#wakeRequests = /* @__PURE__ */ new Map();
|
|
1222
|
+
constructor(options) {
|
|
1223
|
+
this.#store = options.store;
|
|
1224
|
+
this.#queue = options.queue;
|
|
1225
|
+
this.#streams = options.streams;
|
|
1226
|
+
}
|
|
1227
|
+
async deliver(communication, mode) {
|
|
1228
|
+
const delivered = {
|
|
1229
|
+
...communication,
|
|
1230
|
+
type: mode === MessageDeliveryMode.TriggerTurn ? InterAgentCommunicationType.NewTask : communication.type,
|
|
1231
|
+
triggerTurn: mode === MessageDeliveryMode.TriggerTurn
|
|
124
1232
|
};
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
1233
|
+
assertCommunication(delivered);
|
|
1234
|
+
const { recipientActive } = await this.#store.enqueue(delivered);
|
|
1235
|
+
if (delivered.triggerTurn || recipientActive) {
|
|
1236
|
+
await this.#scheduleWake(delivered.recipient);
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
beginTurn(turn) {
|
|
1240
|
+
return this.#store.beginTurn(turn, turn.streamId);
|
|
1241
|
+
}
|
|
1242
|
+
async endTurn(turn, options = {}) {
|
|
1243
|
+
const { hasPending, turnEnded } = await this.#store.endTurn(
|
|
1244
|
+
turn,
|
|
1245
|
+
turn.streamId
|
|
1246
|
+
);
|
|
1247
|
+
if (turnEnded && hasPending && !options.parked) {
|
|
1248
|
+
await this.#scheduleWake(turn);
|
|
130
1249
|
}
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
1250
|
+
}
|
|
1251
|
+
drainLeadingQueueOnly(recipient) {
|
|
1252
|
+
return this.#store.drainLeadingQueueOnly(recipient);
|
|
1253
|
+
}
|
|
1254
|
+
drain(recipient) {
|
|
1255
|
+
return this.#store.drain(recipient);
|
|
1256
|
+
}
|
|
1257
|
+
#scheduleWake(target) {
|
|
1258
|
+
const key = this.#conversationKey(target);
|
|
1259
|
+
const existing = this.#wakeRequests.get(key);
|
|
1260
|
+
if (existing) return existing;
|
|
1261
|
+
const request = (async () => {
|
|
1262
|
+
const wakeId = AgentTurnId.random(target).toString();
|
|
1263
|
+
await this.#streams.register(wakeId);
|
|
1264
|
+
try {
|
|
1265
|
+
await this.#queue.push({
|
|
1266
|
+
kind: "mailbox",
|
|
1267
|
+
streamId: wakeId,
|
|
1268
|
+
chatId: target.chatId,
|
|
1269
|
+
userId: target.userId
|
|
1270
|
+
});
|
|
1271
|
+
} catch (error) {
|
|
1272
|
+
await this.#streams.store.updateStreamStatus(wakeId, "failed", {
|
|
1273
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1274
|
+
});
|
|
1275
|
+
throw error;
|
|
1276
|
+
}
|
|
1277
|
+
})();
|
|
1278
|
+
this.#wakeRequests.set(key, request);
|
|
1279
|
+
const clearRequest = () => {
|
|
1280
|
+
if (this.#wakeRequests.get(key) === request) {
|
|
1281
|
+
this.#wakeRequests.delete(key);
|
|
1282
|
+
}
|
|
1283
|
+
};
|
|
1284
|
+
void request.then(clearRequest, clearRequest);
|
|
1285
|
+
return request;
|
|
1286
|
+
}
|
|
1287
|
+
#conversationKey(conversation) {
|
|
1288
|
+
return JSON.stringify([conversation.chatId, conversation.userId]);
|
|
1289
|
+
}
|
|
1290
|
+
};
|
|
1291
|
+
|
|
1292
|
+
// packages/experimental/src/zukhruf/agent-runtime.ts
|
|
1293
|
+
var AgentObservation = class {
|
|
1294
|
+
engine;
|
|
1295
|
+
#conversation;
|
|
1296
|
+
#store;
|
|
1297
|
+
#streams;
|
|
1298
|
+
constructor(conversation, store, streams) {
|
|
1299
|
+
this.engine = new ContextEngine4({
|
|
1300
|
+
store,
|
|
134
1301
|
chatId: conversation.chatId,
|
|
135
1302
|
userId: conversation.userId
|
|
136
1303
|
});
|
|
137
|
-
|
|
138
|
-
|
|
1304
|
+
this.#conversation = conversation;
|
|
1305
|
+
this.#store = store;
|
|
1306
|
+
this.#streams = streams;
|
|
139
1307
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
1308
|
+
async resume() {
|
|
1309
|
+
const id = await this.#headStreamId();
|
|
1310
|
+
if (!id) return null;
|
|
1311
|
+
AgentTurnId.assertOwner(this.#conversation, id);
|
|
1312
|
+
const status = await this.#streams.store.getStreamStatus(id);
|
|
1313
|
+
return status ? this.#streams.watch(id) : null;
|
|
1314
|
+
}
|
|
1315
|
+
async cancel(streamId) {
|
|
1316
|
+
const chat2 = await this.#store.getChat(this.#conversation.chatId);
|
|
1317
|
+
if (chat2 && chat2.userId !== this.#conversation.userId) {
|
|
1318
|
+
throw new Error(
|
|
1319
|
+
`chat "${this.#conversation.chatId}" belongs to user "${chat2.userId}", not "${this.#conversation.userId}"`
|
|
1320
|
+
);
|
|
1321
|
+
}
|
|
1322
|
+
const id = streamId ?? await this.#headStreamId();
|
|
1323
|
+
if (!id) return;
|
|
1324
|
+
AgentTurnId.assertOwner(this.#conversation, id);
|
|
1325
|
+
const status = await this.#streams.store.getStreamStatus(id);
|
|
1326
|
+
if (status === "queued" || status === "running") {
|
|
1327
|
+
await this.#streams.cancel(id);
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
async #headStreamId() {
|
|
1331
|
+
const head = await this.engine.headMessage();
|
|
1332
|
+
return head?.name === "assistant" ? head.id : void 0;
|
|
1333
|
+
}
|
|
1334
|
+
};
|
|
1335
|
+
var AgentRuntime = class {
|
|
1336
|
+
#store;
|
|
1337
|
+
#queue;
|
|
1338
|
+
#streams;
|
|
1339
|
+
#mailbox;
|
|
1340
|
+
#directory;
|
|
1341
|
+
#controlPlane;
|
|
1342
|
+
#approvals;
|
|
1343
|
+
#executor;
|
|
1344
|
+
constructor(root, options) {
|
|
1345
|
+
const declarations = new AgentDeclarationRegistry(root);
|
|
1346
|
+
const directory = new AgentDirectory(options.store);
|
|
1347
|
+
const streams = new StreamManager({
|
|
1348
|
+
store: options.streamStore,
|
|
1349
|
+
changeSource: new PollingChangeSource({ reads: options.streamStore })
|
|
1350
|
+
});
|
|
1351
|
+
const mailbox = new MailboxCoordinator({
|
|
1352
|
+
store: options.mailboxStore,
|
|
1353
|
+
queue: options.queue,
|
|
1354
|
+
streams
|
|
1355
|
+
});
|
|
1356
|
+
const approvals = new ApprovalController({
|
|
1357
|
+
store: options.store,
|
|
1358
|
+
streams,
|
|
1359
|
+
queue: options.queue,
|
|
1360
|
+
mutex: options.approvalMutex
|
|
1361
|
+
});
|
|
1362
|
+
const statusProjector = new AgentStatusProjector({
|
|
1363
|
+
store: options.store,
|
|
1364
|
+
streams,
|
|
1365
|
+
queue: options.queue,
|
|
1366
|
+
mailbox,
|
|
1367
|
+
directory,
|
|
1368
|
+
approvals
|
|
1369
|
+
});
|
|
1370
|
+
const controlPlane = new AgentControlPlane({
|
|
1371
|
+
root,
|
|
1372
|
+
streams,
|
|
1373
|
+
queue: options.queue,
|
|
1374
|
+
mailbox,
|
|
1375
|
+
declarations,
|
|
1376
|
+
directory,
|
|
1377
|
+
statusProjector
|
|
1378
|
+
});
|
|
1379
|
+
this.#store = options.store;
|
|
1380
|
+
this.#queue = options.queue;
|
|
1381
|
+
this.#streams = streams;
|
|
1382
|
+
this.#mailbox = mailbox;
|
|
1383
|
+
this.#directory = directory;
|
|
1384
|
+
this.#controlPlane = controlPlane;
|
|
1385
|
+
this.#approvals = approvals;
|
|
1386
|
+
this.#executor = new AgentTurnExecutor({
|
|
1387
|
+
store: options.store,
|
|
1388
|
+
streams,
|
|
1389
|
+
controlPlane,
|
|
1390
|
+
mailbox,
|
|
1391
|
+
approvals
|
|
1392
|
+
});
|
|
1393
|
+
}
|
|
1394
|
+
async enqueue(conversation, turn) {
|
|
1395
|
+
const streamId = await this.#controlPlane.enqueue(conversation, turn);
|
|
1396
|
+
return { id: streamId, stream: this.#streams.watch(streamId) };
|
|
1397
|
+
}
|
|
1398
|
+
async deliver(communication, mode) {
|
|
1399
|
+
await this.#directory.assertOwnerIfExists(communication.recipient);
|
|
1400
|
+
await this.#mailbox.deliver(communication, mode);
|
|
1401
|
+
}
|
|
1402
|
+
approve(conversation, input) {
|
|
1403
|
+
return this.#approvals.approve(conversation, input);
|
|
1404
|
+
}
|
|
1405
|
+
deny(conversation, input) {
|
|
1406
|
+
return this.#approvals.deny(conversation, input);
|
|
1407
|
+
}
|
|
1408
|
+
observe(conversation) {
|
|
1409
|
+
return new AgentObservation(conversation, this.#store, this.#streams);
|
|
1410
|
+
}
|
|
1411
|
+
work(options) {
|
|
1412
|
+
return this.#queue.consume(this.#executor.execute.bind(this.#executor), {
|
|
1413
|
+
concurrency: options?.concurrency,
|
|
1414
|
+
onOrphaned: this.#onOrphaned.bind(this)
|
|
1415
|
+
});
|
|
1416
|
+
}
|
|
1417
|
+
async #onOrphaned(turn, error) {
|
|
1418
|
+
try {
|
|
1419
|
+
let stream = await this.#streams.store.getStream(turn.streamId);
|
|
1420
|
+
const firstReconciliation = stream?.status === "queued" || stream?.status === "running";
|
|
1421
|
+
if (firstReconciliation) {
|
|
1422
|
+
await this.#streams.store.updateStreamStatus(turn.streamId, "failed", {
|
|
1423
|
+
error
|
|
1424
|
+
});
|
|
1425
|
+
stream = await this.#streams.store.getStream(turn.streamId);
|
|
1426
|
+
}
|
|
1427
|
+
if (turn.kind === "continuation" && (stream?.status === "completed" || stream?.status === "failed" || stream?.status === "cancelled")) {
|
|
1428
|
+
await this.#approvals.reconcileTerminalContinuation(
|
|
1429
|
+
turn,
|
|
1430
|
+
turn.streamId,
|
|
1431
|
+
stream.status,
|
|
1432
|
+
stream.error ?? error
|
|
145
1433
|
);
|
|
146
1434
|
}
|
|
147
|
-
await
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
});
|
|
155
|
-
return { id: turn.id, stream: manager.watch(turn.id) };
|
|
156
|
-
},
|
|
157
|
-
async approve(conversation, input) {
|
|
158
|
-
return respondToApproval(conversation, input.toolCallId, {
|
|
159
|
-
approved: true
|
|
160
|
-
});
|
|
161
|
-
},
|
|
162
|
-
async deny(conversation, input) {
|
|
163
|
-
return respondToApproval(conversation, input.toolCallId, {
|
|
164
|
-
approved: false,
|
|
165
|
-
reason: input.reason
|
|
166
|
-
});
|
|
167
|
-
},
|
|
168
|
-
observe({ chatId, userId }) {
|
|
169
|
-
const engine = engineFor({ chatId, userId });
|
|
170
|
-
async function headStreamId() {
|
|
171
|
-
const head = await engine.headMessage();
|
|
172
|
-
return head?.name === "assistant" ? head.id : void 0;
|
|
1435
|
+
const { thread } = await this.#controlPlane.resolve(turn);
|
|
1436
|
+
if (thread.lastTurnId === void 0 || thread.lastTurnId === turn.streamId) {
|
|
1437
|
+
await this.#controlPlane.recordLatestTurnIfCurrent(
|
|
1438
|
+
turn,
|
|
1439
|
+
turn.streamId,
|
|
1440
|
+
thread.lastTurnId
|
|
1441
|
+
);
|
|
173
1442
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
const status = await streamStore.getStreamStatus(id);
|
|
180
|
-
return status ? manager.watch(id) : null;
|
|
181
|
-
},
|
|
182
|
-
async cancel(streamId) {
|
|
183
|
-
const id = streamId ?? await headStreamId();
|
|
184
|
-
if (!id) return;
|
|
185
|
-
const status = await streamStore.getStreamStatus(id);
|
|
186
|
-
if (status === "queued" || status === "running") {
|
|
187
|
-
await manager.cancel(id);
|
|
188
|
-
}
|
|
1443
|
+
await this.#controlPlane.projectTerminal(turn, thread);
|
|
1444
|
+
} finally {
|
|
1445
|
+
try {
|
|
1446
|
+
if (turn.kind === "continuation") {
|
|
1447
|
+
await this.#queue.resumeParked(turn.chatId);
|
|
189
1448
|
}
|
|
1449
|
+
} finally {
|
|
1450
|
+
await this.#mailbox.endTurn(turn);
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
};
|
|
1455
|
+
|
|
1456
|
+
// packages/experimental/src/zukhruf/approval-mutex.ts
|
|
1457
|
+
var ApprovalMutex = class {
|
|
1458
|
+
};
|
|
1459
|
+
|
|
1460
|
+
// packages/experimental/src/zukhruf/instructions.ts
|
|
1461
|
+
function defineInstructions(...fragments) {
|
|
1462
|
+
return fragments;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
// packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
|
|
1466
|
+
import { DatabaseSync } from "node:sqlite";
|
|
1467
|
+
|
|
1468
|
+
// packages/experimental/src/zukhruf/mailbox/store.ts
|
|
1469
|
+
var MailboxStore = class {
|
|
1470
|
+
};
|
|
1471
|
+
|
|
1472
|
+
// packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
|
|
1473
|
+
var DDL = `
|
|
1474
|
+
PRAGMA journal_mode = WAL;
|
|
1475
|
+
PRAGMA synchronous = NORMAL;
|
|
1476
|
+
|
|
1477
|
+
CREATE TABLE IF NOT EXISTS zukhruf_mailbox_items (
|
|
1478
|
+
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1479
|
+
recipient_chat_id TEXT NOT NULL,
|
|
1480
|
+
recipient_user_id TEXT NOT NULL,
|
|
1481
|
+
communication TEXT NOT NULL
|
|
1482
|
+
);
|
|
1483
|
+
|
|
1484
|
+
CREATE TABLE IF NOT EXISTS zukhruf_mailbox_activity (
|
|
1485
|
+
recipient_chat_id TEXT NOT NULL,
|
|
1486
|
+
recipient_user_id TEXT NOT NULL,
|
|
1487
|
+
turn_id TEXT NOT NULL,
|
|
1488
|
+
PRIMARY KEY (recipient_chat_id, recipient_user_id)
|
|
1489
|
+
);
|
|
1490
|
+
|
|
1491
|
+
CREATE TABLE IF NOT EXISTS zukhruf_mailbox_consumed_terminal_ids (
|
|
1492
|
+
communication_id TEXT PRIMARY KEY
|
|
1493
|
+
);
|
|
1494
|
+
|
|
1495
|
+
CREATE INDEX IF NOT EXISTS zukhruf_mailbox_recipient_sequence
|
|
1496
|
+
ON zukhruf_mailbox_items (
|
|
1497
|
+
recipient_chat_id,
|
|
1498
|
+
recipient_user_id,
|
|
1499
|
+
sequence
|
|
1500
|
+
);
|
|
1501
|
+
|
|
1502
|
+
CREATE UNIQUE INDEX IF NOT EXISTS zukhruf_mailbox_communication_id
|
|
1503
|
+
ON zukhruf_mailbox_items (
|
|
1504
|
+
json_extract(communication, '$.id')
|
|
1505
|
+
);
|
|
1506
|
+
`;
|
|
1507
|
+
var BUSY_TIMEOUT_MS = 5e3;
|
|
1508
|
+
var SqliteMailboxStore = class extends MailboxStore {
|
|
1509
|
+
#database;
|
|
1510
|
+
#closed = false;
|
|
1511
|
+
constructor(path) {
|
|
1512
|
+
super();
|
|
1513
|
+
this.#database = new DatabaseSync(path, { timeout: BUSY_TIMEOUT_MS });
|
|
1514
|
+
this.#database.exec(DDL);
|
|
1515
|
+
}
|
|
1516
|
+
async beginTurn(recipient, turnId) {
|
|
1517
|
+
this.#transaction(() => {
|
|
1518
|
+
this.#database.prepare(
|
|
1519
|
+
`INSERT INTO zukhruf_mailbox_activity (
|
|
1520
|
+
recipient_chat_id,
|
|
1521
|
+
recipient_user_id,
|
|
1522
|
+
turn_id
|
|
1523
|
+
) VALUES (?, ?, ?)
|
|
1524
|
+
ON CONFLICT (recipient_chat_id, recipient_user_id)
|
|
1525
|
+
DO UPDATE SET turn_id = excluded.turn_id`
|
|
1526
|
+
).run(recipient.chatId, recipient.userId, turnId);
|
|
1527
|
+
});
|
|
1528
|
+
}
|
|
1529
|
+
async enqueue(communication) {
|
|
1530
|
+
return this.#transaction(() => {
|
|
1531
|
+
const consumedTerminal = communication.type === InterAgentCommunicationType.FinalAnswer && this.#hasConsumedTerminal(communication.id);
|
|
1532
|
+
if (!consumedTerminal) {
|
|
1533
|
+
this.#database.prepare(
|
|
1534
|
+
`INSERT OR IGNORE INTO zukhruf_mailbox_items (
|
|
1535
|
+
recipient_chat_id,
|
|
1536
|
+
recipient_user_id,
|
|
1537
|
+
communication
|
|
1538
|
+
) VALUES (?, ?, ?)`
|
|
1539
|
+
).run(
|
|
1540
|
+
communication.recipient.chatId,
|
|
1541
|
+
communication.recipient.userId,
|
|
1542
|
+
JSON.stringify(communication)
|
|
1543
|
+
);
|
|
1544
|
+
}
|
|
1545
|
+
return {
|
|
1546
|
+
recipientActive: this.#isTurnActive(communication.recipient)
|
|
1547
|
+
};
|
|
1548
|
+
});
|
|
1549
|
+
}
|
|
1550
|
+
async endTurn(recipient, turnId) {
|
|
1551
|
+
return this.#transaction(() => {
|
|
1552
|
+
const result = this.#database.prepare(
|
|
1553
|
+
`DELETE FROM zukhruf_mailbox_activity
|
|
1554
|
+
WHERE recipient_chat_id = ?
|
|
1555
|
+
AND recipient_user_id = ?
|
|
1556
|
+
AND turn_id = ?`
|
|
1557
|
+
).run(recipient.chatId, recipient.userId, turnId);
|
|
1558
|
+
return {
|
|
1559
|
+
hasPending: this.#hasPending(recipient),
|
|
1560
|
+
turnEnded: result.changes > 0
|
|
190
1561
|
};
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
1562
|
+
});
|
|
1563
|
+
}
|
|
1564
|
+
async hasPending(recipient) {
|
|
1565
|
+
return this.#hasPending(recipient);
|
|
1566
|
+
}
|
|
1567
|
+
#hasPending(recipient) {
|
|
1568
|
+
const row = this.#database.prepare(
|
|
1569
|
+
`SELECT 1
|
|
1570
|
+
FROM zukhruf_mailbox_items
|
|
1571
|
+
WHERE recipient_chat_id = ?
|
|
1572
|
+
AND recipient_user_id = ?
|
|
1573
|
+
LIMIT 1`
|
|
1574
|
+
).get(recipient.chatId, recipient.userId);
|
|
1575
|
+
return row !== void 0;
|
|
1576
|
+
}
|
|
1577
|
+
#isTurnActive(recipient) {
|
|
1578
|
+
const row = this.#database.prepare(
|
|
1579
|
+
`SELECT 1
|
|
1580
|
+
FROM zukhruf_mailbox_activity
|
|
1581
|
+
WHERE recipient_chat_id = ?
|
|
1582
|
+
AND recipient_user_id = ?
|
|
1583
|
+
LIMIT 1`
|
|
1584
|
+
).get(recipient.chatId, recipient.userId);
|
|
1585
|
+
return row !== void 0;
|
|
1586
|
+
}
|
|
1587
|
+
#hasConsumedTerminal(communicationId) {
|
|
1588
|
+
const row = this.#database.prepare(
|
|
1589
|
+
`SELECT 1
|
|
1590
|
+
FROM zukhruf_mailbox_consumed_terminal_ids
|
|
1591
|
+
WHERE communication_id = ?
|
|
1592
|
+
LIMIT 1`
|
|
1593
|
+
).get(communicationId);
|
|
1594
|
+
return row !== void 0;
|
|
1595
|
+
}
|
|
1596
|
+
async drain(recipient) {
|
|
1597
|
+
return this.#drain(recipient, false);
|
|
1598
|
+
}
|
|
1599
|
+
async drainLeadingQueueOnly(recipient) {
|
|
1600
|
+
return this.#drain(recipient, true);
|
|
1601
|
+
}
|
|
1602
|
+
#drain(recipient, leadingQueueOnly) {
|
|
1603
|
+
return this.#transaction(() => {
|
|
1604
|
+
const rows = this.#database.prepare(
|
|
1605
|
+
`SELECT sequence, communication
|
|
1606
|
+
FROM zukhruf_mailbox_items
|
|
1607
|
+
WHERE recipient_chat_id = ?
|
|
1608
|
+
AND recipient_user_id = ?
|
|
1609
|
+
ORDER BY sequence`
|
|
1610
|
+
).all(recipient.chatId, recipient.userId);
|
|
1611
|
+
const items = rows.map((row) => ({
|
|
1612
|
+
sequence: row.sequence,
|
|
1613
|
+
communication: JSON.parse(row.communication)
|
|
1614
|
+
}));
|
|
1615
|
+
const firstTrigger = leadingQueueOnly ? items.findIndex(({ communication }) => communication.triggerTurn) : -1;
|
|
1616
|
+
const consumed = firstTrigger === -1 ? items : items.slice(0, firstTrigger);
|
|
1617
|
+
const lastConsumed = consumed.at(-1);
|
|
1618
|
+
if (lastConsumed) {
|
|
1619
|
+
const tombstone = this.#database.prepare(
|
|
1620
|
+
`INSERT OR IGNORE
|
|
1621
|
+
INTO zukhruf_mailbox_consumed_terminal_ids (communication_id)
|
|
1622
|
+
VALUES (?)`
|
|
1623
|
+
);
|
|
1624
|
+
for (const { communication } of consumed) {
|
|
1625
|
+
if (communication.type === InterAgentCommunicationType.FinalAnswer) {
|
|
1626
|
+
tombstone.run(communication.id);
|
|
201
1627
|
}
|
|
202
1628
|
}
|
|
203
|
-
|
|
1629
|
+
this.#database.prepare(
|
|
1630
|
+
`DELETE FROM zukhruf_mailbox_items
|
|
1631
|
+
WHERE recipient_chat_id = ?
|
|
1632
|
+
AND recipient_user_id = ?
|
|
1633
|
+
AND sequence <= ?`
|
|
1634
|
+
).run(recipient.chatId, recipient.userId, lastConsumed.sequence);
|
|
1635
|
+
}
|
|
1636
|
+
return consumed.map(({ communication }) => communication);
|
|
1637
|
+
});
|
|
1638
|
+
}
|
|
1639
|
+
#transaction(operation) {
|
|
1640
|
+
this.#database.exec("BEGIN IMMEDIATE");
|
|
1641
|
+
try {
|
|
1642
|
+
const result = operation();
|
|
1643
|
+
this.#database.exec("COMMIT");
|
|
1644
|
+
return result;
|
|
1645
|
+
} catch (error) {
|
|
1646
|
+
try {
|
|
1647
|
+
this.#database.exec("ROLLBACK");
|
|
1648
|
+
} catch {
|
|
1649
|
+
}
|
|
1650
|
+
throw error;
|
|
204
1651
|
}
|
|
205
|
-
}
|
|
206
|
-
|
|
1652
|
+
}
|
|
1653
|
+
close() {
|
|
1654
|
+
if (this.#closed) return;
|
|
1655
|
+
this.#closed = true;
|
|
1656
|
+
this.#database.close();
|
|
1657
|
+
}
|
|
1658
|
+
[Symbol.dispose]() {
|
|
1659
|
+
this.close();
|
|
1660
|
+
}
|
|
1661
|
+
};
|
|
1662
|
+
|
|
1663
|
+
// packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
|
|
1664
|
+
import { v7 as uuidv7 } from "uuid";
|
|
207
1665
|
|
|
208
1666
|
// packages/experimental/src/zukhruf/queue/turn-queue.ts
|
|
209
1667
|
var TurnQueue = class {
|
|
210
1668
|
};
|
|
211
1669
|
|
|
212
1670
|
// packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
|
|
213
|
-
|
|
214
|
-
var PgBossTurnQueue = class extends TurnQueue {
|
|
1671
|
+
var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
|
|
215
1672
|
#boss;
|
|
216
1673
|
#queue;
|
|
217
1674
|
#expireInSeconds;
|
|
@@ -253,6 +1710,18 @@ var PgBossTurnQueue = class extends TurnQueue {
|
|
|
253
1710
|
priority: turn.kind === "continuation" ? 1 : 0
|
|
254
1711
|
});
|
|
255
1712
|
}
|
|
1713
|
+
async getTurnActivity(conversation) {
|
|
1714
|
+
const jobs = await this.#boss.findJobs(this.#queue, {
|
|
1715
|
+
key: conversation.chatId
|
|
1716
|
+
});
|
|
1717
|
+
const conversationJobs = jobs.filter(
|
|
1718
|
+
(job) => job.data.userId === conversation.userId && (job.state === "created" || job.state === "retry" || job.state === "active")
|
|
1719
|
+
);
|
|
1720
|
+
if (conversationJobs.some((job) => job.state === "active")) {
|
|
1721
|
+
return "running";
|
|
1722
|
+
}
|
|
1723
|
+
return conversationJobs.length > 0 ? "queued" : "idle";
|
|
1724
|
+
}
|
|
256
1725
|
async consume(handler, options) {
|
|
257
1726
|
const turnWorkerId = await this.#boss.work(
|
|
258
1727
|
this.#queue,
|
|
@@ -285,9 +1754,15 @@ var PgBossTurnQueue = class extends TurnQueue {
|
|
|
285
1754
|
pollingIntervalSeconds: this.#pollingIntervalSeconds
|
|
286
1755
|
},
|
|
287
1756
|
async ([job]) => {
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
1757
|
+
try {
|
|
1758
|
+
await options.onOrphaned(
|
|
1759
|
+
job.data,
|
|
1760
|
+
_PgBossTurnQueue.#orphanError(job.output)
|
|
1761
|
+
);
|
|
1762
|
+
} finally {
|
|
1763
|
+
if (job.sourceId) {
|
|
1764
|
+
await this.#boss.deleteJob(this.#queue, job.sourceId);
|
|
1765
|
+
}
|
|
291
1766
|
}
|
|
292
1767
|
}
|
|
293
1768
|
);
|
|
@@ -305,20 +1780,109 @@ var PgBossTurnQueue = class extends TurnQueue {
|
|
|
305
1780
|
await this.#boss.resume(this.#queue, parked);
|
|
306
1781
|
}
|
|
307
1782
|
}
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
1783
|
+
static #orphanError(output) {
|
|
1784
|
+
if (output && "message" in output && typeof output.message === "string") {
|
|
1785
|
+
return output.message;
|
|
1786
|
+
}
|
|
1787
|
+
return output ? JSON.stringify(output) : "turn orphaned";
|
|
312
1788
|
}
|
|
313
|
-
|
|
1789
|
+
};
|
|
1790
|
+
|
|
1791
|
+
// packages/experimental/src/zukhruf/sandbox/define.ts
|
|
1792
|
+
import {
|
|
1793
|
+
createBashTool
|
|
1794
|
+
} from "@deepagents/context";
|
|
1795
|
+
function defineSandbox(createBackend, options) {
|
|
1796
|
+
return async (context) => createBashTool({ sandbox: await createBackend(context), ...options });
|
|
314
1797
|
}
|
|
1798
|
+
|
|
1799
|
+
// packages/experimental/src/zukhruf/sqlite-approval-mutex.ts
|
|
1800
|
+
import { resolve } from "node:path";
|
|
1801
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
1802
|
+
var SqliteApprovalMutex = class _SqliteApprovalMutex extends ApprovalMutex {
|
|
1803
|
+
static #tails = /* @__PURE__ */ new Map();
|
|
1804
|
+
#db;
|
|
1805
|
+
#coordinationKey;
|
|
1806
|
+
constructor(path) {
|
|
1807
|
+
super();
|
|
1808
|
+
this.#coordinationKey = path === ":memory:" ? crypto.randomUUID() : resolve(path);
|
|
1809
|
+
this.#db = new DatabaseSync2(path);
|
|
1810
|
+
this.#db.exec(`
|
|
1811
|
+
PRAGMA busy_timeout = 5000;
|
|
1812
|
+
CREATE TABLE IF NOT EXISTS approval_mutex (
|
|
1813
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
1814
|
+
conversationId TEXT NOT NULL,
|
|
1815
|
+
touchedAt INTEGER NOT NULL
|
|
1816
|
+
);
|
|
1817
|
+
`);
|
|
1818
|
+
}
|
|
1819
|
+
async runExclusive(conversationId, operation) {
|
|
1820
|
+
const release = await this.#acquireLocalGate();
|
|
1821
|
+
try {
|
|
1822
|
+
this.#db.exec("BEGIN IMMEDIATE");
|
|
1823
|
+
try {
|
|
1824
|
+
this.#db.prepare(
|
|
1825
|
+
`INSERT INTO approval_mutex (id, conversationId, touchedAt)
|
|
1826
|
+
VALUES (1, ?, ?)
|
|
1827
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
1828
|
+
conversationId = excluded.conversationId,
|
|
1829
|
+
touchedAt = excluded.touchedAt`
|
|
1830
|
+
).run(conversationId, Date.now());
|
|
1831
|
+
const result = await operation();
|
|
1832
|
+
this.#db.exec("COMMIT");
|
|
1833
|
+
return result;
|
|
1834
|
+
} catch (error) {
|
|
1835
|
+
try {
|
|
1836
|
+
this.#db.exec("ROLLBACK");
|
|
1837
|
+
} catch {
|
|
1838
|
+
}
|
|
1839
|
+
throw error;
|
|
1840
|
+
}
|
|
1841
|
+
} finally {
|
|
1842
|
+
release();
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
close() {
|
|
1846
|
+
this.#db.close();
|
|
1847
|
+
}
|
|
1848
|
+
[Symbol.dispose]() {
|
|
1849
|
+
this.close();
|
|
1850
|
+
}
|
|
1851
|
+
async #acquireLocalGate() {
|
|
1852
|
+
const previous = _SqliteApprovalMutex.#tails.get(this.#coordinationKey) ?? Promise.resolve();
|
|
1853
|
+
const gate = Promise.withResolvers();
|
|
1854
|
+
const tail = previous.then(() => gate.promise);
|
|
1855
|
+
_SqliteApprovalMutex.#tails.set(this.#coordinationKey, tail);
|
|
1856
|
+
await previous;
|
|
1857
|
+
return () => {
|
|
1858
|
+
gate.resolve();
|
|
1859
|
+
if (_SqliteApprovalMutex.#tails.get(this.#coordinationKey) === tail) {
|
|
1860
|
+
_SqliteApprovalMutex.#tails.delete(this.#coordinationKey);
|
|
1861
|
+
}
|
|
1862
|
+
};
|
|
1863
|
+
}
|
|
1864
|
+
};
|
|
1865
|
+
|
|
1866
|
+
// packages/experimental/src/zukhruf/tool.ts
|
|
1867
|
+
import { tool as tool4 } from "ai";
|
|
315
1868
|
export {
|
|
1869
|
+
AgentObservation,
|
|
1870
|
+
AgentPath,
|
|
1871
|
+
AgentRuntime,
|
|
1872
|
+
AgentThread,
|
|
1873
|
+
ApprovalMutex,
|
|
1874
|
+
InterAgentCommunicationType,
|
|
1875
|
+
MailboxStore,
|
|
1876
|
+
MessageDeliveryMode,
|
|
316
1877
|
PgBossTurnQueue,
|
|
1878
|
+
SqliteApprovalMutex,
|
|
1879
|
+
SqliteMailboxStore,
|
|
317
1880
|
TurnQueue,
|
|
318
|
-
|
|
1881
|
+
assertCommunication,
|
|
1882
|
+
createInterAgentCommunication,
|
|
319
1883
|
defineAgent,
|
|
320
1884
|
defineInstructions,
|
|
321
1885
|
defineSandbox,
|
|
322
|
-
|
|
1886
|
+
tool4 as defineTool
|
|
323
1887
|
};
|
|
324
1888
|
//# sourceMappingURL=index.js.map
|