@ceasarxuu/dsh-agent-team 0.0.0-stage → 0.2.4

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/lib/index.js ADDED
@@ -0,0 +1,751 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
5
+ var __typeError = (msg) => {
6
+ throw TypeError(msg);
7
+ };
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
11
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
12
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
13
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
14
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
15
+ var __runInitializers = (array, flags, self, value) => {
16
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
17
+ return value;
18
+ };
19
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
20
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
21
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
22
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
23
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
24
+ return __privateGet(this, extra);
25
+ }, set [name](x) {
26
+ return __privateSet(this, extra, x);
27
+ } }, name));
28
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
29
+ for (var i = decorators.length - 1; i >= 0; i--) {
30
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
31
+ if (k) {
32
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
33
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
34
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
35
+ }
36
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
37
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
38
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
39
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
40
+ }
41
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
42
+ };
43
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
44
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
45
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
46
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
47
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
48
+ var __using = (stack, value, async) => {
49
+ if (value != null) {
50
+ if (typeof value !== "object" && typeof value !== "function") __typeError("Object expected");
51
+ var dispose, inner;
52
+ if (async) dispose = value[__knownSymbol("asyncDispose")];
53
+ if (dispose === void 0) {
54
+ dispose = value[__knownSymbol("dispose")];
55
+ if (async) inner = dispose;
56
+ }
57
+ if (typeof dispose !== "function") __typeError("Object not disposable");
58
+ if (inner) dispose = function() {
59
+ try {
60
+ inner.call(this);
61
+ } catch (e) {
62
+ return Promise.reject(e);
63
+ }
64
+ };
65
+ stack.push([async, dispose, value]);
66
+ } else if (async) {
67
+ stack.push([async]);
68
+ }
69
+ return value;
70
+ };
71
+ var __callDispose = (stack, error, hasError) => {
72
+ var E = typeof SuppressedError === "function" ? SuppressedError : function(e, s, m, _) {
73
+ return _ = Error(m), _.name = "SuppressedError", _.error = e, _.suppressed = s, _;
74
+ };
75
+ var fail = (e) => error = hasError ? new E(e, error, "An error was suppressed during disposal") : (hasError = true, e);
76
+ var next = (it) => {
77
+ while (it = stack.pop()) {
78
+ try {
79
+ var result = it[1] && it[1].call(it[2]);
80
+ if (it[0]) return Promise.resolve(result).then(next, (e) => (fail(e), next()));
81
+ } catch (e) {
82
+ fail(e);
83
+ }
84
+ }
85
+ if (hasError) throw error;
86
+ };
87
+ return next();
88
+ };
89
+
90
+ // src/index.ts
91
+ import { Service } from "@deepseek-ai/cordis";
92
+
93
+ // src/host/runtime.ts
94
+ import { randomUUID } from "node:crypto";
95
+ import { defineTool } from "@deepseek-ai/dsh-tools";
96
+
97
+ // src/host/admission.ts
98
+ var SeatAdmission = class {
99
+ pending = /* @__PURE__ */ new Map();
100
+ async start(root, prefix, max, ops) {
101
+ const key = `${root}/${prefix}`;
102
+ const previous = this.pending.get(key) ?? Promise.resolve();
103
+ const turn = previous.then(async () => {
104
+ const names = new Set(await ops.readNames());
105
+ for (let slot = 1; slot <= max; slot++) {
106
+ const name = `${prefix}-${slot.toString(36)}`;
107
+ if (!names.has(name)) return ops.start(name);
108
+ }
109
+ throw new Error("Role instance limit reached. Use send_message to continue an existing teammate.");
110
+ });
111
+ const settled = turn.then(() => void 0, () => void 0);
112
+ this.pending.set(key, settled);
113
+ try {
114
+ return await turn;
115
+ } finally {
116
+ if (this.pending.get(key) === settled) this.pending.delete(key);
117
+ }
118
+ }
119
+ };
120
+
121
+ // src/host/tool-policy.ts
122
+ var collaboration = /* @__PURE__ */ new Set([
123
+ "skill",
124
+ "list_agents",
125
+ "send_message",
126
+ "wait_agent",
127
+ "team_task_create",
128
+ "team_task_list",
129
+ "team_task_get",
130
+ "team_task_update"
131
+ ]);
132
+ var coordination = /* @__PURE__ */ new Set(["team_spawn", "ask_user_question", "interrupt_agent"]);
133
+ var artifactReads = /* @__PURE__ */ new Set(["read", "ls", "glob", "grep", "list_dir", "web_fetch", "web_search"]);
134
+ var execution = /* @__PURE__ */ new Set([
135
+ "edit",
136
+ "write",
137
+ "bash",
138
+ "pwsh",
139
+ "apply_patch",
140
+ "todo_write",
141
+ "job_list",
142
+ "job_output",
143
+ "job_kill"
144
+ ]);
145
+ function roleToolAllowed(kind, tool) {
146
+ if (collaboration.has(tool)) return true;
147
+ if (kind === "commander") return coordination.has(tool);
148
+ if (artifactReads.has(tool)) return true;
149
+ return kind === "worker" && execution.has(tool);
150
+ }
151
+
152
+ // src/host/runtime.ts
153
+ var TEAM_PRESET = "standard";
154
+ var SPAWN_TOOL = "team_spawn";
155
+ var busyMessage = "Wait for this conversation and its teammates to finish before switching teams.";
156
+ var TeamRuntime = class {
157
+ constructor(ctx, store) {
158
+ this.ctx = ctx;
159
+ this.store = store;
160
+ }
161
+ seats = new SeatAdmission();
162
+ installed = /* @__PURE__ */ new Map();
163
+ activeRuns = /* @__PURE__ */ new Map();
164
+ async launch(team, workspaceId, signal) {
165
+ signal.throwIfAborted();
166
+ await Promise.all(team.roles.map((role2) => this.checkRoute(role2, signal)));
167
+ const sessionId = `session-${randomUUID()}`;
168
+ await this.store.setRoot(sessionId, this.store.createSnapshot(team));
169
+ signal.throwIfAborted();
170
+ const created = await this.ctx.sessionController.create({ workspaceId, sessionId, agentPreset: TEAM_PRESET });
171
+ if (created.sessionId !== sessionId) throw new Error("DSH did not assign the reserved team session");
172
+ return sessionId;
173
+ }
174
+ trackRun(runId, parentId) {
175
+ const parent = this.ctx.agents.get(parentId);
176
+ if (parent !== void 0) this.activeRuns.set(runId, this.ctx.subagents.rootOf(parent));
177
+ }
178
+ finishRun(runId) {
179
+ this.activeRuns.delete(runId);
180
+ }
181
+ async switchTeam(sessionId, assignment, choice, signal) {
182
+ signal.throwIfAborted();
183
+ const resolved = await this.ctx.sessionController.resolveAgent(sessionId);
184
+ if ("error" in resolved || resolved.agent.session.header.origin === "subagent") {
185
+ throw new Error("Choose a team from the main conversation.");
186
+ }
187
+ const root = resolved.agent;
188
+ if (root.inbox.nextTurn.length !== 0 || root.inbox.nextStep.length !== 0) throw new Error(busyMessage);
189
+ try {
190
+ return root.runMaintenance((lock) => this.changeAssignment(root, assignment, choice, AbortSignal.any([lock, signal])));
191
+ } catch {
192
+ throw new Error(busyMessage);
193
+ }
194
+ }
195
+ async changeAssignment(root, assignment, choice, signal) {
196
+ signal.throwIfAborted();
197
+ const previous = this.store.rootSnapshot(root.id);
198
+ const state = this.store.listForSession(root.id);
199
+ if ((state.active?.assignment ?? null) !== assignment) {
200
+ throw new Error("The team selection changed in another window. Choose the team again.");
201
+ }
202
+ if (choice === null ? previous === void 0 : previous?.team.id === choice.id && previous.team.revision === choice.revision) return state;
203
+ const team = choice === null ? void 0 : this.store.getTeam(choice.id, choice.revision);
204
+ const beforeModel = root.model.current();
205
+ const savedNativeModel = previous?.nativeModel;
206
+ const nativeModel = previous === void 0 ? beforeModel : savedNativeModel ?? defaultModel(root);
207
+ if (team !== void 0) await Promise.all(team.roles.map((role2) => this.checkRoute(role2, signal)));
208
+ const next = team === void 0 ? void 0 : this.store.createSnapshot(team, nativeModel);
209
+ const children = await this.ctx.subagents.listDescendants(root.id, signal);
210
+ if (children.some((child) => child.kind === "diagnostic" || child.activity === "running" || this.ctx.agents.get(child.id)?.status === "running") || [...this.activeRuns.values()].includes(root)) throw new Error(busyMessage);
211
+ if (!this.ctx.agentTeams.isEnabled(root)) throw new Error("Enable intelligent team collaboration to switch teams.");
212
+ if (this.ctx.agentTeams.listTasks(root).some((task) => task.status !== "completed")) {
213
+ throw new Error("Finish the open tasks on the team board before switching teams.");
214
+ }
215
+ signal.throwIfAborted();
216
+ this.detach(root);
217
+ let committed = false;
218
+ try {
219
+ if (next === void 0 && nativeModel !== void 0) {
220
+ root.model.select(nativeModel);
221
+ await this.ctx.sessions.flush(root.session);
222
+ }
223
+ await this.store.setRoot(root.id, next);
224
+ committed = true;
225
+ if (next !== void 0) this.install(root, root.id, next, commander(next));
226
+ } catch (error) {
227
+ if (committed) await this.store.setRoot(root.id, previous);
228
+ if (previous !== void 0) this.install(root, root.id, previous, commander(previous));
229
+ else if (beforeModel !== void 0) root.model.select(beforeModel);
230
+ throw error;
231
+ }
232
+ return this.store.listForSession(root.id);
233
+ }
234
+ async attach(agent, initialize, signal) {
235
+ if (this.installed.has(agent)) return;
236
+ const bound = this.store.binding(agent.id);
237
+ if (bound === void 0) return;
238
+ const { role: role2, snapshot, rootId } = bound;
239
+ if (rootId !== agent.id && this.store.rootSnapshot(rootId) === void 0) return;
240
+ this.install(agent, rootId, snapshot, role2);
241
+ if (rootId === agent.id && initialize) {
242
+ try {
243
+ await this.ctx.agentTeams.setEnabled(agent, true, signal);
244
+ } catch (error) {
245
+ this.detach(agent);
246
+ throw error;
247
+ }
248
+ }
249
+ }
250
+ install(agent, rootId, snapshot, role2) {
251
+ const model = expectRoleModel(role2);
252
+ const disposers = [];
253
+ const dispose = () => {
254
+ for (const release of disposers.splice(0).reverse()) release();
255
+ };
256
+ try {
257
+ const allowed = agent.ctx.tools.definitions(agent).map((tool) => tool.name).filter((name) => roleToolAllowed(role2.kind, name));
258
+ disposers.push(
259
+ agent.ctx.tools.restrict({ allow: allowed }),
260
+ agent.ctx.tools.guard((exec) => roleToolAllowed(role2.kind, exec.name) ? void 0 : `Team role ${role2.name} cannot use ${exec.name}`),
261
+ agent.ctx.on("agent/pre-step", ({ modelSelection }, next) => {
262
+ if (modelSelection.provider !== model.provider || modelSelection.model !== model.model) {
263
+ agent.model.select(model);
264
+ throw new Error(`Team role \u201C${role2.name}\u201D uses ${model.provider}/${model.model}. Send the message again with that model selected.`);
265
+ }
266
+ return next();
267
+ })
268
+ );
269
+ disposers.push(agent.ctx.systemPrompt.section({
270
+ name: "agent-team-config:role",
271
+ order: agent.ctx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_SUFFIX") + 1,
272
+ text: promptFor(snapshot, role2),
273
+ interpolate: false
274
+ }));
275
+ if (rootId === agent.id) {
276
+ disposers.push(this.registerSpawn(agent, snapshot));
277
+ if (snapshot.generation !== void 0) {
278
+ disposers.push(this.guardMemberReferences(agent, snapshot.generation));
279
+ }
280
+ }
281
+ agent.model.select(model);
282
+ this.installed.set(agent, dispose);
283
+ } catch (error) {
284
+ this.installed.delete(agent);
285
+ dispose();
286
+ throw error;
287
+ }
288
+ }
289
+ detach(agent) {
290
+ this.installed.get(agent)?.();
291
+ this.installed.delete(agent);
292
+ }
293
+ close() {
294
+ for (const agent of this.installed.keys()) this.detach(agent);
295
+ }
296
+ guardMemberReferences(root, generation) {
297
+ return root.ctx.on("tools/pre-execute", async (exec, next) => {
298
+ const name = exec.name;
299
+ const args = exec.arguments;
300
+ const target = name === "team_task_update" ? args?.owner : name === "send_message" || name === "interrupt_agent" ? args?.agent : void 0;
301
+ if (typeof target === "string") {
302
+ const id2 = await this.ctx.subagents.resolveName(root, target, exec.signal);
303
+ if (id2 !== root.id && !this.store.isCurrentMember(id2, root.id, generation)) {
304
+ return { kind: "deny", reason: "This teammate belongs to a previous team. Start or reuse a member of the current team." };
305
+ }
306
+ }
307
+ return next();
308
+ });
309
+ }
310
+ registerSpawn(root, snapshot) {
311
+ return root.ctx.tools.register(defineTool({
312
+ name: SPAWN_TOOL,
313
+ description: "Start one fresh teammate from a configured role. Each role has a fixed seat limit. Use send_message to reuse a teammate.",
314
+ parameters: {
315
+ roleId: { type: "string", required: true, description: "The configured role ID from the team roster." },
316
+ task: { type: "string", required: true, description: "A task brief with the objective, scope, acceptance criteria and relevant artifact references." }
317
+ },
318
+ output: {
319
+ schema: {
320
+ type: "object",
321
+ additionalProperties: false,
322
+ properties: { name: { type: "string", required: true } }
323
+ },
324
+ render: (_args, result) => [{ type: "text", text: `Started team member ${result.name}` }]
325
+ },
326
+ isConcurrencySafe: () => true,
327
+ execute: (args, exec) => {
328
+ if (exec.agent !== root) throw new Error("Only the active team Commander can start members");
329
+ return this.spawn(root, snapshot, args.roleId, args.task, exec.signal);
330
+ }
331
+ }));
332
+ }
333
+ async spawn(root, snapshot, roleId, task, signal) {
334
+ const index = snapshot.team.roles.findIndex((role3) => role3.id === roleId && role3.kind !== "commander");
335
+ const role2 = snapshot.team.roles[index];
336
+ if (role2 === void 0) throw new Error("Choose a configured teammate role");
337
+ if (!task.trim()) throw new Error("Provide a task brief");
338
+ const suffix = snapshot.generation === void 0 ? "" : `-${snapshot.generation.slice(-10)}`;
339
+ const prefix = `${role2.kind}-${(index + 1).toString(36)}${suffix}`;
340
+ return this.seats.start(root.id, prefix, role2.maxInstances, {
341
+ readNames: async () => {
342
+ signal.throwIfAborted();
343
+ if (!this.ctx.agentTeams.isEnabled(root)) throw new Error("Enable the native Team mode on this conversation");
344
+ const entries = await this.ctx.subagents.listDescendants(root.id, signal);
345
+ return entries.flatMap((entry) => entry.kind === "child" && entry.parentId === root.id && "name" in entry && entry.name !== void 0 ? [entry.name] : []);
346
+ },
347
+ start: async (name) => {
348
+ const agentOptions = await this.checkRoute(role2, signal);
349
+ const childId = randomUUID();
350
+ await this.store.bindMember(childId, root.id, role2.id, snapshot.generation);
351
+ signal.throwIfAborted();
352
+ const maxDepth = Math.min(1, this.ctx.subagents.resolveMaxDepth(void 0) ?? 1);
353
+ const started = await this.ctx.subagents.startActivation({
354
+ provider: "spawn",
355
+ parent: root,
356
+ label: role2.name,
357
+ delivery: "parent",
358
+ name,
359
+ childId,
360
+ agentPreset: TEAM_PRESET,
361
+ agentOptions,
362
+ signal,
363
+ maxDepth,
364
+ prompt: [{ type: "text", text: task }]
365
+ });
366
+ return { name: started.name ?? name };
367
+ }
368
+ });
369
+ }
370
+ async checkRoute(role2, signal) {
371
+ const model = expectRoleModel(role2);
372
+ try {
373
+ await this.ctx.llm.resolveCallConfig(model, signal);
374
+ } catch (error) {
375
+ if (signal.aborted) throw error;
376
+ throw new Error(`Model ${model.provider}/${model.model} is unavailable for \u201C${role2.name}\u201D`);
377
+ }
378
+ return model;
379
+ }
380
+ };
381
+ function commander(snapshot) {
382
+ const role2 = snapshot.team.roles.find((role3) => role3.kind === "commander");
383
+ if (role2 === void 0) throw new Error("Missing Commander in the saved team configuration");
384
+ return role2;
385
+ }
386
+ function defaultModel(agent) {
387
+ const { provider, model, reasoningEffort } = agent.options;
388
+ return provider === void 0 || model === void 0 ? void 0 : { provider, model, reasoningEffort };
389
+ }
390
+ function expectRoleModel(role2) {
391
+ if (role2.model === null) throw new Error(`Select a model for \u201C${role2.name}\u201D`);
392
+ return role2.model;
393
+ }
394
+ function promptFor(snapshot, role2) {
395
+ const identity = `Managed DSH team ${JSON.stringify(snapshot.team.name)}. Your configured role is ${JSON.stringify(role2.name)} (${role2.kind}).`;
396
+ const rolePrompt2 = snapshot.prompts[role2.id] ?? "";
397
+ if (role2.kind !== "commander") {
398
+ return [identity, 'Coordinate via the native task board and report to the Commander using send_message with agent "lead".', rolePrompt2].filter(Boolean).join("\n\n");
399
+ }
400
+ const roster = snapshot.team.roles.filter((item) => item.kind !== "commander").map(({ id: id2, name, kind, description, maxInstances }) => ({ id: id2, name, kind, description, maxInstances }));
401
+ return [
402
+ identity,
403
+ "Coordinate only. Use team_spawn with a configured role ID and a concrete task brief. Use list_agents and send_message to reuse the members below.",
404
+ snapshot.generation === void 0 ? "" : `Current teammate names contain -${snapshot.generation.slice(-10)}-. Treat older members as conversation history.`,
405
+ JSON.stringify(roster, null, 2),
406
+ rolePrompt2
407
+ ].filter(Boolean).join("\n\n");
408
+ }
409
+
410
+ // src/host/store.ts
411
+ import { randomUUID as randomUUID2 } from "node:crypto";
412
+ import { defineDomain, domainTable } from "@deepseek-ai/dsh-storage-domain";
413
+ import { z as z2 } from "zod";
414
+
415
+ // src/shared/config.ts
416
+ import { z } from "zod";
417
+ var id = z.string().regex(/^[a-z][a-z0-9-]*$/);
418
+ var skillName = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
419
+ var roleModel = z.strictObject({
420
+ provider: z.string().trim().min(1),
421
+ model: z.string().trim().min(1)
422
+ });
423
+ var role = z.strictObject({
424
+ id,
425
+ kind: z.enum(["commander", "worker", "reviewer", "custom"]),
426
+ name: z.string().trim().min(1),
427
+ description: z.string().trim(),
428
+ model: roleModel.nullable(),
429
+ maxInstances: z.int().positive(),
430
+ promptOverride: z.string().nullable(),
431
+ preferredSkills: z.array(skillName).refine((names) => new Set(names).size === names.length, "Duplicate preferred skill")
432
+ });
433
+ var roles = z.array(role).superRefine((values, context) => {
434
+ const roleIds = /* @__PURE__ */ new Set();
435
+ let commanders = 0;
436
+ for (const [index, value] of values.entries()) {
437
+ if (roleIds.has(value.id)) context.addIssue({ code: "custom", path: [index, "id"], message: "Duplicate role ID" });
438
+ roleIds.add(value.id);
439
+ if (value.kind !== "commander") continue;
440
+ commanders++;
441
+ if (commanders > 1) context.addIssue({ code: "custom", path: [index, "kind"], message: "Use at most one Commander" });
442
+ if (value.maxInstances !== 1) {
443
+ context.addIssue({ code: "custom", path: [index, "maxInstances"], message: "Commander has exactly one seat" });
444
+ }
445
+ }
446
+ });
447
+ var teamName = z.string().trim().min(1);
448
+ var teamDraftSchema = z.strictObject({
449
+ id: id.nullable(),
450
+ revision: z.int().nonnegative(),
451
+ name: teamName,
452
+ roles
453
+ });
454
+ var teamConfigSchema = z.strictObject({
455
+ id,
456
+ revision: z.int().positive(),
457
+ name: teamName,
458
+ roles
459
+ });
460
+ function teamForLaunch(team) {
461
+ const config = teamConfigSchema.parse(team);
462
+ if (!config.roles.some((role2) => role2.kind === "commander")) throw new Error("Select a Commander before starting the team");
463
+ if (!config.roles.some((role2) => role2.kind !== "commander")) throw new Error("Add a teammate before starting the team");
464
+ const unconfigured = config.roles.find((role2) => role2.model === null);
465
+ if (unconfigured !== void 0) throw new Error(`Select a model for \u201C${unconfigured.name}\u201D`);
466
+ return config;
467
+ }
468
+
469
+ // src/shared/prompts.ts
470
+ var prompts = {
471
+ commander: `\u4F60\u662F Commander\uFF0C\u8D1F\u8D23\u7406\u89E3\u7528\u6237\u76EE\u6807\u3001\u786E\u5B9A\u9A8C\u6536\u6761\u4EF6\u3001\u5206\u6D3E\u4EFB\u52A1\u3001\u8DDF\u8FDB\u963B\u585E\u5E76\u5411\u7528\u6237\u6C47\u62A5\u3002\u628A\u8C03\u67E5\u3001\u5B9E\u73B0\u548C\u9A8C\u8BC1\u4EA4\u7ED9\u9002\u5F53\u89D2\u8272\u3002\u59D4\u6D3E\u65F6\u63D0\u4F9B\u539F\u59CB\u8981\u6C42\u3001\u9A8C\u6536\u6761\u4EF6\u3001\u8303\u56F4\u3001\u4F9D\u8D56\u53CA\u9884\u671F\u56DE\u62A5\u3002\u53EA\u5728\u4EFB\u52A1\u76F8\u4E92\u72EC\u7ACB\u4E14\u5199\u5165\u8303\u56F4\u53EF\u5206\u5F00\u65F6\u5E76\u884C\u3002\u4F18\u5148\u7528 send_message \u590D\u7528\u7A7A\u95F2\u6210\u5458\u3002
472
+ \u7528\u4EFB\u52A1\u677F\u8BB0\u5F55\u5F52\u5C5E\u548C\u8FDB\u5EA6\uFF0C\u7528\u6D88\u606F\u4EA4\u63A5\u3002\u4EFB\u52A1\u677F\u66F4\u65B0\u540E\uFF0C\u9700\u8981\u6210\u5458\u884C\u52A8\u65F6\u5411\u5176\u53D1\u6D88\u606F\u3002\u4ECE\u6536\u4EF6\u7BB1\u63A5\u6536\u8FDB\u5EA6\uFF0C\u6309\u9700\u4F7F\u7528 wait_agent\u3002\u6240\u6709\u5FC5\u8981\u7ED3\u679C\u9F50\u5907\u540E\u518D\u5BA3\u5E03\u5B8C\u6210\u3002
473
+ \u914D\u7F6E\u4E86 Reviewer \u65F6\uFF0C\u9ED8\u8BA4\u5C06\u53EF\u9A8C\u6536\u7684\u4EA4\u4ED8\u7269\u4EA4\u5176\u72EC\u7ACB\u5BA1\u67E5\u3002\u63D0\u4F9B\u539F\u59CB\u8981\u6C42\u3001\u9A8C\u6536\u6761\u4EF6\u3001\u57FA\u7EBF\u548C\u76EE\u6807\u7248\u672C\uFF0C\u8BA9 Reviewer \u81EA\u5DF1\u68C0\u67E5\u4EA7\u7269\u3002\u6309\u8BC1\u636E\u5904\u7406\u963B\u585E\u9879\uFF0C\u6D3E\u539F Worker \u4FEE\u590D\uFF0C\u6700\u591A\u5B89\u6392\u4E00\u6B21\u805A\u7126\u539F\u963B\u585E\u9879\u53CA\u76F4\u63A5\u56DE\u5F52\u7684\u81EA\u52A8\u590D\u6838\u3002\u7ED3\u8BBA\u7ED1\u5B9A\u76EE\u6807\u7248\u672C\u3002\u4ECD\u6709\u963B\u585E\u6216\u8BC1\u636E\u4E0D\u8DB3\u65F6\uFF0C\u5411\u7528\u6237\u8BF4\u660E\u5B9E\u9645\u72B6\u6001\u548C\u6240\u9700\u51B3\u5B9A\u3002`,
474
+ worker: `\u4F60\u662F Worker\uFF0C\u8D1F\u8D23\u5B8C\u6210\u5206\u6D3E\u7ED9\u4F60\u7684\u4EFB\u52A1\u3002\u9605\u8BFB\u4EFB\u52A1\u3001\u9879\u76EE\u89C4\u5219\u548C\u76F8\u5173\u6750\u6599\uFF0C\u786E\u8BA4\u5F53\u524D\u72B6\u6001\u53CA\u5199\u5165\u8303\u56F4\u3002\u91C7\u7528\u6EE1\u8DB3\u9A8C\u6536\u6761\u4EF6\u7684\u6700\u5C0F\u6539\u52A8\uFF0C\u4FDD\u62A4\u5DF2\u6709\u4FEE\u6539\u548C\u5176\u4ED6\u6210\u5458\u7684\u5DE5\u4F5C\u3002\u8303\u56F4\u51B2\u7A81\u3001\u6743\u9650\u4E0D\u8DB3\u6216\u6838\u5FC3\u8981\u6C42\u4E0D\u660E\u786E\u65F6\uFF0C\u5E26\u7740\u5177\u4F53\u8BC1\u636E\u4EA4\u56DE Commander\uFF0C\u7EE7\u7EED\u53EF\u72EC\u7ACB\u5B8C\u6210\u7684\u5DE5\u4F5C\u3002
475
+ \u6309\u6388\u6743\u505A\u4E0E\u6539\u52A8\u76F8\u5173\u7684\u9A8C\u8BC1\u3002\u901A\u8FC7\u6D88\u606F\u4EA4\u4ED8\u4EFB\u52A1 ID\u3001\u6539\u52A8\u5185\u5BB9\u3001\u4EA7\u7269\u8DEF\u5F84\u548C\u7248\u672C\u3001\u5B9E\u9645\u9A8C\u8BC1\u7ED3\u679C\u53CA\u963B\u585E\u3002\u6536\u5230\u5BA1\u67E5\u53CD\u9988\u540E\uFF0C\u56F4\u7ED5\u5DF2\u786E\u8BA4\u7684\u95EE\u9898\u4FEE\u590D\uFF0C\u5E76\u62A5\u544A\u65B0\u7248\u672C\u53CA\u5BF9\u5E94\u8BC1\u636E\u3002`,
476
+ reviewer: `\u4F60\u662F Reviewer\u3002\u76F4\u63A5\u9605\u8BFB\u539F\u59CB\u9700\u6C42\u3001\u9A8C\u6536\u6761\u4EF6\u548C\u6307\u5B9A\u4EA7\u7269\u7248\u672C\uFF0C\u5C1D\u8BD5\u6784\u9020\u80FD\u63A8\u7FFB\u4EA4\u4ED8\u7ED3\u8BBA\u7684\u53CD\u4F8B\u3002\u4F18\u5148\u770B\u9700\u6C42\u9057\u6F0F\u3001\u8FB9\u754C\u6761\u4EF6\u3001\u5931\u8D25\u6062\u590D\u3001\u5E76\u53D1\u51B2\u7A81\u548C\u56DE\u5F52\u3002\u5B9E\u73B0\u8005\u7684\u81EA\u8BC4\u53EF\u4EE5\u63D0\u4F9B\u7EBF\u7D22\uFF0C\u7ED3\u8BBA\u4EE5\u53EF\u6838\u5BF9\u7684\u8BC1\u636E\u4E3A\u51C6\u3002
477
+ \u6BCF\u6761\u53D1\u73B0\u5199\u660E\u4F4D\u7F6E\u3001\u89E6\u53D1\u6761\u4EF6\u3001\u9884\u671F\u4E0E\u5B9E\u9645\u7ED3\u679C\u3001\u5F71\u54CD\u548C\u8BC1\u636E\u3002\u5C06\u5F71\u54CD\u9A8C\u6536\u4E14\u6709\u8BC1\u636E\u7684\u95EE\u9898\u6807\u4E3A\u963B\u585E\uFF0C\u5F85\u9A8C\u8BC1\u7684\u63A8\u6D4B\u5355\u72EC\u5199\u660E\u3002\u901A\u8FC7\u6D88\u606F\u56DE\u62A5\u300C\u901A\u8FC7\u300D\u300C\u9700\u8981\u4FEE\u590D\u300D\u6216\u300C\u8BC1\u636E\u4E0D\u8DB3\u300D\uFF0C\u5E76\u9644\u76EE\u6807\u7248\u672C\u548C\u68C0\u67E5\u8303\u56F4\u3002\u590D\u6838\u805A\u7126\u4E0A\u4E00\u8F6E\u963B\u585E\u9879\u53CA\u4FEE\u590D\u76F4\u63A5\u5F15\u5165\u7684\u56DE\u5F52\u3002\u4EA7\u7269\u4FEE\u6539\u7531 Worker \u5904\u7406\u3002`,
478
+ custom: ""
479
+ };
480
+ function defaultPrompt(kind) {
481
+ return prompts[kind];
482
+ }
483
+ function rolePrompt(role2) {
484
+ const body = role2.promptOverride ?? defaultPrompt(role2.kind);
485
+ if (role2.preferredSkills.length === 0) return body;
486
+ const skills = role2.preferredSkills.join(", ");
487
+ const preference = `Preferred skills: ${skills}. When a listed skill is available and relevant to the current task, consider loading it first using DSH's skill tool. Choose other skills as the task requires.`;
488
+ return [body, preference].filter(Boolean).join("\n\n");
489
+ }
490
+
491
+ // src/host/store.ts
492
+ var snapshotSchema = z2.strictObject({
493
+ team: teamConfigSchema,
494
+ prompts: z2.record(z2.string(), z2.string()),
495
+ generation: z2.string().optional(),
496
+ nativeModel: z2.strictObject({
497
+ provider: z2.string(),
498
+ model: z2.string(),
499
+ reasoningEffort: z2.string().optional()
500
+ }).optional()
501
+ });
502
+ var memberSchema = z2.strictObject({ rootId: z2.string(), roleId: z2.string(), generation: z2.string().optional() });
503
+ var teamSpec = defineDomain({
504
+ name: "agent_team_config",
505
+ version: 1,
506
+ tables: {
507
+ teams: domainTable(teamConfigSchema),
508
+ snapshots: domainTable(snapshotSchema),
509
+ bindings: domainTable(memberSchema)
510
+ }
511
+ });
512
+ var TeamStore = class _TeamStore {
513
+ constructor(domain) {
514
+ this.domain = domain;
515
+ }
516
+ templateWrites = Promise.resolve();
517
+ static async open(ctx) {
518
+ return new _TeamStore(await ctx.storageDomain.open(teamSpec));
519
+ }
520
+ close() {
521
+ return this.domain.close();
522
+ }
523
+ list() {
524
+ return Array.from(this.domain.table("teams").entries(), ([, team]) => team);
525
+ }
526
+ listForSession(rootId) {
527
+ const snapshot = this.rootSnapshot(rootId);
528
+ const active = snapshot === void 0 ? null : {
529
+ id: snapshot.team.id,
530
+ revision: snapshot.team.revision,
531
+ name: snapshot.team.name,
532
+ assignment: snapshot.generation ?? initialKey(rootId)
533
+ };
534
+ return { active, templates: this.list() };
535
+ }
536
+ async save(input) {
537
+ const draft = teamDraftSchema.parse(input);
538
+ const teams = this.domain.table("teams");
539
+ return this.writeTemplate(async () => {
540
+ if (draft.id === null) {
541
+ const team = { ...draft, id: `team-${randomUUID2()}`, revision: 1 };
542
+ await teams.put(team.id, team);
543
+ return team;
544
+ }
545
+ return teams.update(draft.id, (current) => {
546
+ assertRevision(current, draft.revision);
547
+ return { ...draft, id: current.id, revision: current.revision + 1 };
548
+ });
549
+ });
550
+ }
551
+ remove(id2, revision) {
552
+ return this.writeTemplate(() => {
553
+ this.getTeam(id2, revision);
554
+ return this.domain.table("teams").delete(id2);
555
+ });
556
+ }
557
+ writeTemplate(write) {
558
+ const pending = this.templateWrites.then(write);
559
+ this.templateWrites = pending.catch(() => void 0);
560
+ return pending;
561
+ }
562
+ getTeam(id2, revision) {
563
+ const team = this.domain.table("teams").get(id2);
564
+ if (team === void 0) throw new Error("Team configuration is unavailable");
565
+ assertRevision(team, revision);
566
+ return team;
567
+ }
568
+ createSnapshot(team, nativeModel) {
569
+ const snapshot = teamForLaunch(team);
570
+ const prompts2 = Object.fromEntries(snapshot.roles.map((role2) => [role2.id, rolePrompt(role2)]));
571
+ const generation = `assignment-${randomUUID2()}`;
572
+ return { team: snapshot, prompts: prompts2, generation, nativeModel };
573
+ }
574
+ rootSnapshot(rootId) {
575
+ return this.domain.table("snapshots").get(rootId);
576
+ }
577
+ async setRoot(rootId, next) {
578
+ const snapshots = this.domain.table("snapshots");
579
+ const previous = snapshots.get(rootId);
580
+ if (previous !== void 0 && previous.generation === void 0 && snapshots.get(initialKey(rootId)) === void 0) {
581
+ await snapshots.put(initialKey(rootId), previous);
582
+ }
583
+ if (next === void 0) {
584
+ await snapshots.delete(rootId);
585
+ } else {
586
+ if (next.generation !== void 0 && snapshots.get(next.generation) === void 0) {
587
+ await snapshots.put(next.generation, next);
588
+ }
589
+ await snapshots.put(rootId, next);
590
+ }
591
+ }
592
+ async bindMember(childId, rootId, roleId, generation) {
593
+ await this.domain.table("bindings").put(childId, { rootId, roleId, generation });
594
+ }
595
+ isCurrentMember(childId, rootId, generation) {
596
+ const member = this.domain.table("bindings").get(childId);
597
+ return member?.rootId === rootId && member.generation === generation;
598
+ }
599
+ binding(sessionId) {
600
+ const snapshot = this.domain.table("snapshots").get(sessionId);
601
+ if (snapshot !== void 0) {
602
+ const role3 = snapshot.team.roles.find((role4) => role4.kind === "commander");
603
+ if (role3 === void 0) throw new Error("Missing Commander in the saved team configuration");
604
+ return { rootId: sessionId, snapshot, role: role3 };
605
+ }
606
+ const member = this.domain.table("bindings").get(sessionId);
607
+ if (member === void 0) return void 0;
608
+ const snapshots = this.domain.table("snapshots");
609
+ const saved = member.generation === void 0 ? snapshots.get(initialKey(member.rootId)) ?? snapshots.get(member.rootId) : snapshots.get(member.generation);
610
+ const role2 = saved?.team.roles.find((role3) => role3.id === member.roleId);
611
+ if (saved === void 0 || role2 === void 0) throw new Error("Missing configuration for the saved team member");
612
+ return { rootId: member.rootId, snapshot: saved, role: role2 };
613
+ }
614
+ };
615
+ function initialKey(rootId) {
616
+ return `initial-${rootId}`;
617
+ }
618
+ function assertRevision(current, revision) {
619
+ if (current.revision !== revision) throw new Error("This team was updated. Refresh the team before trying again.");
620
+ }
621
+
622
+ // src/remote.ts
623
+ import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
624
+ import { ZodError } from "zod";
625
+ var _switchTeam_dec, _launch_dec, _skills_dec, _deleteTemplate_dec, _save_dec, _listForSession_dec, _list_dec, _a, _init;
626
+ var TeamConfigRemote = class extends (_a = TypertRemoteService, _list_dec = [Remote], _listForSession_dec = [Remote], _save_dec = [Remote], _deleteTemplate_dec = [Remote], _skills_dec = [Remote], _launch_dec = [Remote], _switchTeam_dec = [Remote], _a) {
627
+ constructor(ctx, operations) {
628
+ super(ctx, "teamConfig");
629
+ this.operations = operations;
630
+ __runInitializers(_init, 5, this);
631
+ }
632
+ list() {
633
+ return this.operations.list();
634
+ }
635
+ listForSession(rootSessionId) {
636
+ return this.operations.listForSession(rootSessionId);
637
+ }
638
+ save(draft) {
639
+ return this.checked(() => this.operations.save(draft));
640
+ }
641
+ deleteTemplate(teamId, revision) {
642
+ return this.checked(() => this.operations.remove(teamId, revision));
643
+ }
644
+ skills(workspaceId, signal) {
645
+ return this.checked(() => this.operations.skills(workspaceId, signal));
646
+ }
647
+ launch(teamId, revision, workspaceId, signal) {
648
+ return this.checked(() => this.operations.launch(teamId, revision, workspaceId, signal));
649
+ }
650
+ switchTeam(sessionId, assignment, choice, signal) {
651
+ return this.checked(() => this.operations.switchTeam(sessionId, assignment, choice, signal));
652
+ }
653
+ async checked(operation) {
654
+ try {
655
+ return await operation();
656
+ } catch (error) {
657
+ const reason = error instanceof ZodError ? error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("\n") : error instanceof Error ? error.message : "The team operation failed";
658
+ throw new RemoteError("agent-team-config/rejected", reason, { reason });
659
+ }
660
+ }
661
+ };
662
+ _init = __decoratorStart(_a);
663
+ __decorateElement(_init, 1, "list", _list_dec, TeamConfigRemote);
664
+ __decorateElement(_init, 1, "listForSession", _listForSession_dec, TeamConfigRemote);
665
+ __decorateElement(_init, 1, "save", _save_dec, TeamConfigRemote);
666
+ __decorateElement(_init, 1, "deleteTemplate", _deleteTemplate_dec, TeamConfigRemote);
667
+ __decorateElement(_init, 1, "skills", _skills_dec, TeamConfigRemote);
668
+ __decorateElement(_init, 1, "launch", _launch_dec, TeamConfigRemote);
669
+ __decorateElement(_init, 1, "switchTeam", _switchTeam_dec, TeamConfigRemote);
670
+ __decoratorMetadata(_init, TeamConfigRemote);
671
+
672
+ // src/index.ts
673
+ var AgentTeamConfig = class extends TeamConfigRemote {
674
+ static inject = [
675
+ "agents",
676
+ "agentPresets",
677
+ "agentTeams",
678
+ "llm",
679
+ "sessionController",
680
+ "skills",
681
+ "sessions",
682
+ "storageDomain",
683
+ "subagents",
684
+ "systemPrompt",
685
+ "tools",
686
+ "typert",
687
+ "workspaceRegistry"
688
+ ];
689
+ store;
690
+ runtime;
691
+ constructor(ctx) {
692
+ super(ctx, {
693
+ list: () => this.store.list(),
694
+ listForSession: (rootSessionId) => this.store.listForSession(rootSessionId),
695
+ save: (draft) => this.store.save(draft),
696
+ remove: (id2, revision) => this.store.remove(id2, revision),
697
+ skills: (workspaceId, signal) => this.listSkills(workspaceId, signal),
698
+ launch: (teamId, revision, workspaceId, signal) => this.runtime.launch(
699
+ this.store.getTeam(teamId, revision),
700
+ workspaceId,
701
+ signal
702
+ ),
703
+ switchTeam: (rootSessionId, assignment, choice, signal) => this.runtime.switchTeam(
704
+ rootSessionId,
705
+ assignment,
706
+ choice,
707
+ signal
708
+ )
709
+ });
710
+ }
711
+ async [Service.init]() {
712
+ this.store = await TeamStore.open(this.ctx);
713
+ this.runtime = new TeamRuntime(this.ctx, this.store);
714
+ this.ctx.effect(() => async () => {
715
+ this.runtime.close();
716
+ await this.store.close();
717
+ }, "agent-team-config: persistence and role scopes");
718
+ this.ctx.on("agent/created", async ({ agent, source, signal }) => {
719
+ await this.runtime.attach(agent, source === "startup", signal);
720
+ });
721
+ this.ctx.on("agent/disposed", ({ agent }) => {
722
+ this.runtime.detach(agent);
723
+ });
724
+ this.ctx.on("subagent/start", ({ runId, parentSessionId }) => {
725
+ this.runtime.trackRun(runId, parentSessionId);
726
+ });
727
+ this.ctx.on("subagent/end", ({ runId }) => {
728
+ this.runtime.finishRun(runId);
729
+ });
730
+ await Promise.all(this.ctx.agents.list().map((agent) => this.runtime.attach(agent, false)));
731
+ }
732
+ /** Native scoped catalog; an unbound template looks up skills without a project directory. */
733
+ async listSkills(workspaceId, signal) {
734
+ var _stack = [];
735
+ try {
736
+ const workspace = workspaceId === null ? void 0 : this.ctx.workspaceRegistry.get(workspaceId);
737
+ if (workspaceId !== null && workspace === void 0) throw new Error("The workspace is unavailable");
738
+ const scope = __using(_stack, await this.ctx.agentPresets.acquireScope(TEAM_PRESET), true);
739
+ const list = await this.ctx.skills.list({ cwd: workspace?.path, scope: scope.key, signal });
740
+ return list.filter((skill) => skill.invocation.modelInvocable).map(({ name, description }) => ({ name, description }));
741
+ } catch (_) {
742
+ var _error = _, _hasError = true;
743
+ } finally {
744
+ var _promise = __callDispose(_stack, _error, _hasError);
745
+ _promise && await _promise;
746
+ }
747
+ }
748
+ };
749
+ export {
750
+ AgentTeamConfig as default
751
+ };