@suifei/dsh-ai-team 0.4.87 → 0.4.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,318 +1,190 @@
1
- /**
2
- * Member runtime adapter (M2 foundation).
3
- *
4
- * The registry owns names and ledger events; this module owns the one thing
5
- * that can actually start an Agent: a direct child activation under the
6
- * Project's host Agent, followed by the danger-full-access permission check.
7
- *
8
- * It is dependency-injected so it can be tested without a live DSH process:
9
- * subagents.startActivation / sendMessage
10
- * sessions.get
11
- * permissionPresets.resolve / set / catalog
12
- * sandboxPolicy.overrideOf / defaultMode
13
- */
14
-
15
- import { randomUUID } from 'node:crypto';
16
- import { buildAgentOptions } from '../domain/member-config.js';
17
-
18
- import { resolveTeamPreset } from '../host/permission-guard.js';
19
-
20
- const TEAM_PRESET = 'danger-full-access';
21
-
22
- function userMessage(text) {
23
- return {
24
- id: randomUUID(),
25
- role: 'user',
26
- content: [{ type: 'text', text }],
27
- source: { kind: 'user' },
28
- };
29
- }
30
-
31
- export class MemberRuntimeError extends Error {
32
- constructor(code, message, details = {}) {
33
- super(message);
34
- this.name = 'MemberRuntimeError';
35
- this.code = code;
36
- this.details = details;
37
- }
38
- }
39
-
40
- function fail(code, message, details) {
41
- throw new MemberRuntimeError(code, message, details);
42
- }
43
-
44
- /**
45
- * Validate the deployment before any Team feature is offered.
46
- * A profile without danger-full-access must not silently run Team mode.
47
- */
48
- export function validatePermissionProfile({ permissionPresets, sandboxPolicy }) {
49
- if (permissionPresets === undefined || sandboxPolicy === undefined) {
50
- return { ok: false, code: 'E_PERMISSION_PROFILE', reason: 'permission services are unavailable' };
51
- }
52
- let catalog;
53
- try {
54
- catalog = permissionPresets.catalog();
55
- } catch (error) {
56
- return { ok: false, code: 'E_PERMISSION_PROFILE', reason: `catalog failed: ${error?.message ?? error}` };
57
- }
58
- const presetName = catalog?.defaultPreset;
59
- if (typeof presetName !== 'string' || presetName === '') {
60
- return { ok: false, code: 'E_PERMISSION_PROFILE', reason: 'no default permission preset' };
61
- }
62
- let spec;
63
- try {
64
- spec = permissionPresets.resolve(presetName);
65
- } catch (error) {
66
- return { ok: false, code: 'E_PERMISSION_PROFILE', reason: `preset ${presetName} cannot resolve` };
67
- }
68
- if (spec?.sandbox !== TEAM_PRESET || spec?.approval !== 'never') {
69
- return { ok: false, code: 'E_PERMISSION_PROFILE', reason: `default preset ${presetName} is not danger-full-access/never` };
70
- }
71
- if (sandboxPolicy.defaultMode !== TEAM_PRESET) {
72
- return { ok: false, code: 'E_PERMISSION_PROFILE', reason: `sandbox default is ${String(sandboxPolicy.defaultMode)}` };
73
- }
74
- return { ok: true, preset: presetName, spec };
75
- }
76
-
77
- export class MemberRuntime {
78
- /**
79
- * @param {{
80
- * subagents: any,
81
- * sessions: any,
82
- * permissionPresets: any,
83
- * sandboxPolicy: any,
84
- * parent: any,
85
- * provider: string,
86
- * cwd: string,
87
- * preset?: string,
88
- * clock?: () => number
89
- * }} options
90
- */
91
- constructor(options) {
92
- this.subagents = options.subagents;
93
- this.sessions = options.sessions;
94
- this.agents = options.agents;
95
- this.permissionPresets = options.permissionPresets;
96
- this.sandboxPolicy = options.sandboxPolicy;
97
- this.parent = options.parent;
98
- this.provider = options.provider;
99
- this.cwd = options.cwd;
100
- this.preset = options.preset ?? null;
101
- this.agentPresets = options.agentPresets ?? null;
102
- this.direct = options.direct === true;
103
- // Cold resumes produce AgentHandles the caller does not store; the owner
104
- // tracks them here so teardown can dispose every member activation.
105
- this.trackHandle = typeof options.trackHandle === 'function' ? options.trackHandle : null;
106
- // 冷恢复得到的 handle 必须自己记住:第二次唤醒时 session 已经 live,但
107
- // subagent manager 并不把这次 resume 当成 resident activation,再走
108
- // sendMessage 会触发二次冷恢复 → NOT_RESUMABLE → 上层强制重建丢上下文。
109
- this.resumedHandles = new Map();
110
- this.clock = options.clock ?? (() => Date.now());
111
- }
112
-
113
- /** Re-apply and verify danger-full-access on one live member session. */
114
- async ensurePermission(sessionId) {
115
- const session = this.sessions?.get?.(sessionId);
116
- if (session === undefined || session === null) {
117
- fail('E_SESSION_MISSING', `member session ${String(sessionId)} is not live`);
118
- }
119
- if (this.sandboxPolicy.overrideOf(session) !== TEAM_PRESET) {
120
- this.permissionPresets.set(session, resolveTeamPreset(this.permissionPresets));
121
- }
122
- if (this.sandboxPolicy.overrideOf(session) !== TEAM_PRESET) {
123
- fail('E_PERMISSION', `member session ${String(sessionId)} is not ${TEAM_PRESET}`, { sessionId });
124
- }
125
- return session;
126
- }
127
-
128
- /** Start a new continuable child Agent and bind it to a member. */
129
- async activate(member, options = {}) {
130
- if (this.direct) return await this.activateDirect(member, options);
131
- if (this.subagents === undefined || this.parent === undefined || typeof this.provider !== 'string') {
132
- fail('E_RUNTIME_UNAVAILABLE', 'no subagent provider or parent Agent is available');
133
- }
134
- const prompt = Array.isArray(options.prompt) ? options.prompt : [{ type: 'text', text: options.prompt ?? '' }];
135
- const signal = options.signal ?? new AbortController().signal;
136
- const agentOptions = buildAgentOptions(member.config ?? {});
137
- let activation;
138
- try {
139
- activation = await this.subagents.startActivation({
140
- provider: options.provider ?? this.provider,
141
- label: member.name,
142
- request: {
143
- cwd: member.workspace ?? this.cwd,
144
- ...(member.preset ?? member.config?.preset ?? this.preset ? { agentPreset: member.preset ?? member.config?.preset ?? this.preset } : {}),
145
- prompt,
146
- parent: this.parent,
147
- ...(Object.keys(agentOptions).length === 0 ? {} : { agentOptions }),
148
- },
149
- signal,
150
- delivery: 'parent',
151
- });
152
- } catch (error) {
153
- fail('E_ACTIVATION', `member activation failed: ${error?.message ?? error}`, { memberId: member.id });
154
- }
155
- try {
156
- await this.ensurePermission(activation.childId);
157
- // The subagent setup appends the descriptor before the first prompt; flush
158
- // it so a later cold resume can reconstruct the continuable child.
159
- const session = this.agents?.get?.(activation.childId)?.session ?? this.sessions?.get?.(activation.childId);
160
- if (session !== undefined && session !== null && typeof this.sessions.flush === 'function') {
161
- await this.sessions.flush(session);
162
- }
163
- } catch (error) {
164
- try { await activation.dispose?.(); } catch { /* already gone */ }
165
- throw error;
166
- }
167
- return {
168
- childId: activation.childId,
169
- messageId: activation.messageId ?? null,
170
- activation,
171
- member: { ...member, sessionId: activation.childId, status: 'running', activatedAt: this.clock() },
172
- };
173
- }
174
-
175
- /**
176
- * Direct child mode: create the Agent through agents.create and start the
177
- * turn with agent.followup. This avoids the subagent manager's disposable
178
- * activation when its cold-resume edge is not usable for a long-lived member.
179
- */
180
- async activateDirect(member, options = {}) {
181
- if (this.agents?.create === undefined || this.parent === undefined) {
182
- fail('E_RUNTIME_UNAVAILABLE', 'agent creation or parent Agent is unavailable');
183
- }
184
- const sessionId = randomUUID();
185
- const preset = member.preset ?? member.config?.preset ?? this.preset;
186
- let handle;
187
- try {
188
- handle = await this.agents.create({
189
- sessionId,
190
- parentAgent: this.parent,
191
- meta: {
192
- cwd: member.workspace ?? this.cwd,
193
- parentSession: this.parent.id,
194
- delegationDepth: 1,
195
- ...(preset ? { agentPreset: preset } : {}),
196
- },
197
- agentOptions: buildAgentOptions(member.config ?? {}),
198
- ...(preset && this.agentPresets?.mount ? {
199
- setup: async (agentCtx) => { await this.agentPresets.mount(agentCtx, preset); },
200
- } : {}),
201
- ...(options.signal === undefined ? {} : { signal: options.signal }),
202
- });
203
- } catch (error) {
204
- fail('E_ACTIVATION', `member activation failed: ${error?.message ?? error}`, { memberId: member.id });
205
- }
206
- const session = handle.agent.session;
207
- try {
208
- if (this.sandboxPolicy.overrideOf(session) !== TEAM_PRESET) this.permissionPresets.set(session, resolveTeamPreset(this.permissionPresets));
209
- if (this.sandboxPolicy.overrideOf(session) !== TEAM_PRESET) {
210
- fail('E_PERMISSION', `member session ${sessionId} is not ${TEAM_PRESET}`, { sessionId });
211
- }
212
- const message = userMessage(typeof options.prompt === 'string' ? options.prompt : '开始工作');
213
- handle.agent.followup(message);
214
- if (typeof this.sessions?.flush === 'function') await this.sessions.flush(session);
215
- return {
216
- childId: sessionId,
217
- messageId: message.id,
218
- activation: { dispose: async () => { await handle.dispose?.(); } },
219
- member: { ...member, sessionId, status: 'running', activatedAt: this.clock() },
220
- debug: {
221
- agentStatus: handle.agent.status ?? null,
222
- sessionSeq: handle.agent.session?.seq ?? null,
223
- inboxNextTurn: handle.agent.inbox?.nextTurn?.length ?? null,
224
- inboxNextStep: handle.agent.inbox?.nextStep?.length ?? null,
225
- },
226
- };
227
- } catch (error) {
228
- try { await handle.dispose?.(); } catch { /* rollback */ }
229
- throw error;
230
- }
231
- }
232
-
233
- /** Wake an existing member; cold resume is the subagents service's job. */
234
- async wake(member, options = {}) {
235
- if (member.sessionId === undefined || member.sessionId === null) {
236
- fail('E_SESSION_MISSING', `member ${member.id} has no session`);
237
- }
238
- const content = Array.isArray(options.prompt) ? options.prompt : [{ type: 'text', text: options.prompt ?? '' }];
239
- if (this.direct) {
240
- let agent = this.agents?.get?.(member.sessionId);
241
- if (agent === undefined || agent === null) {
242
- try {
243
- const preset = member.preset ?? member.config?.preset ?? this.preset;
244
- const handle = await this.agents.resume({
245
- resumeSessionId: member.sessionId,
246
- parentAgent: this.parent,
247
- ...(preset && this.agentPresets?.mount ? {
248
- setup: async (agentCtx) => { await this.agentPresets.mount(agentCtx, preset); },
249
- } : {}),
250
- });
251
- this.trackHandle?.(member.sessionId, handle);
252
- agent = handle.agent;
253
- } catch (error) {
254
- fail('E_SESSION_MISSING', `member ${member.id} cannot be resumed: ${error?.message ?? error}`);
255
- }
256
- }
257
- await this.ensurePermission(member.sessionId);
258
- const message = userMessage(typeof options.prompt === 'string' ? options.prompt : '继续');
259
- agent.followup(message);
260
- const live = this.sessions?.get?.(member.sessionId);
261
- if (live !== undefined && live !== null && typeof this.sessions.flush === 'function') await this.sessions.flush(live);
262
- return { messageId: message.id, sessionId: member.sessionId, direct: true };
263
- }
264
- let session = this.sessions?.get?.(member.sessionId);
265
- // 冷会话:只走**一条**恢复路径。先 agents.resume 再 sendMessage 会让
266
- // subagent manager 再做一次冷恢复并以 NOT_RESUMABLE 失败(它的 continuable
267
- // 句柄已被前一次 resume 消耗),进而触发上层强制重建、丢成员历史。
268
- if (session === undefined || session === null) {
269
- if (this.agents?.resume !== undefined) {
270
- let handle = null;
271
- try {
272
- handle = await this.agents.resume({ resumeSessionId: member.sessionId, parentAgent: this.parent });
273
- } catch { handle = null; }
274
- if (handle?.agent !== undefined && handle?.agent !== null && typeof handle.agent.followup === 'function') {
275
- this.trackHandle?.(member.sessionId, handle);
276
- this.resumedHandles.set(member.sessionId, handle);
277
- await this.ensurePermission(member.sessionId);
278
- const message = userMessage(typeof options.prompt === 'string' ? options.prompt : '继续');
279
- handle.agent.followup(message);
280
- const live = this.sessions?.get?.(member.sessionId);
281
- if (live !== undefined && live !== null && typeof this.sessions.flush === 'function') await this.sessions.flush(live);
282
- return { messageId: message.id, sessionId: member.sessionId, cold: true, resumed: true };
283
- }
284
- }
285
- // resume 不可用:只剩 subagent manager 的冷投递(其权限预设已在会话日志里)。
286
- const messageId = await this.subagents.sendMessage(this.parent, member.sessionId, content, {
287
- signal: options.signal ?? new AbortController().signal,
288
- });
289
- return { messageId, sessionId: member.sessionId, cold: true };
290
- }
291
- // 之前由我们 resume 过的会话:继续用同一个 handle 投递,避免掉回
292
- // sendMessage 的冷恢复路径(见构造函数里的说明)。
293
- const resumed = this.resumedHandles.get(member.sessionId);
294
- if (resumed?.agent !== undefined && resumed?.agent !== null && typeof resumed.agent.followup === 'function') {
295
- try {
296
- await this.ensurePermission(member.sessionId);
297
- const message = userMessage(typeof options.prompt === 'string' ? options.prompt : '继续');
298
- resumed.agent.followup(message);
299
- if (typeof this.sessions.flush === 'function') await this.sessions.flush(session);
300
- return { messageId: message.id, sessionId: member.sessionId, cold: false, resumed: true };
301
- } catch {
302
- // handle 已失效:清掉后回退到 manager 通道。
303
- this.resumedHandles.delete(member.sessionId);
304
- }
305
- }
306
- await this.ensurePermission(member.sessionId);
307
- const messageId = await this.subagents.sendMessage(this.parent, member.sessionId, content, {
308
- signal: options.signal ?? new AbortController().signal,
309
- });
310
- const live = this.sessions?.get?.(member.sessionId);
311
- if (live !== undefined && live !== null && typeof this.sessions.flush === 'function') {
312
- await this.sessions.flush(live);
313
- }
314
- return { messageId, sessionId: member.sessionId, cold: false };
315
- }
316
- }
317
-
318
- export { TEAM_PRESET };
1
+ /**
2
+ * Member runtime adapter (M2 foundation).
3
+ *
4
+ * The registry owns names and ledger events; this module owns the one thing
5
+ * that can actually start an Agent: a direct child activation under the
6
+ * Project's host Agent, followed by the danger-full-access permission check.
7
+ *
8
+ * It is dependency-injected so it can be tested without a live DSH process:
9
+ * subagents.startActivation / sendMessage
10
+ * sessions.get
11
+ * permissionPresets.resolve / set / catalog
12
+ * sandboxPolicy.overrideOf / defaultMode
13
+ */
14
+
15
+ import { buildAgentOptions } from '../domain/member-config.js';
16
+
17
+ import { resolveTeamPreset } from '../host/permission-guard.js';
18
+
19
+ const TEAM_PRESET = 'danger-full-access';
20
+
21
+ export class MemberRuntimeError extends Error {
22
+ constructor(code, message, details = {}) {
23
+ super(message);
24
+ this.name = 'MemberRuntimeError';
25
+ this.code = code;
26
+ this.details = details;
27
+ }
28
+ }
29
+
30
+ function fail(code, message, details) {
31
+ throw new MemberRuntimeError(code, message, details);
32
+ }
33
+
34
+ /**
35
+ * Validate the deployment before any Team feature is offered.
36
+ * A profile without danger-full-access must not silently run Team mode.
37
+ */
38
+ export function validatePermissionProfile({ permissionPresets, sandboxPolicy }) {
39
+ if (permissionPresets === undefined || sandboxPolicy === undefined) {
40
+ return { ok: false, code: 'E_PERMISSION_PROFILE', reason: 'permission services are unavailable' };
41
+ }
42
+ let catalog;
43
+ try {
44
+ catalog = permissionPresets.catalog();
45
+ } catch (error) {
46
+ return { ok: false, code: 'E_PERMISSION_PROFILE', reason: `catalog failed: ${error?.message ?? error}` };
47
+ }
48
+ const presetName = catalog?.defaultPreset;
49
+ if (typeof presetName !== 'string' || presetName === '') {
50
+ return { ok: false, code: 'E_PERMISSION_PROFILE', reason: 'no default permission preset' };
51
+ }
52
+ let spec;
53
+ try {
54
+ spec = permissionPresets.resolve(presetName);
55
+ } catch (error) {
56
+ return { ok: false, code: 'E_PERMISSION_PROFILE', reason: `preset ${presetName} cannot resolve` };
57
+ }
58
+ if (spec?.sandbox !== TEAM_PRESET || spec?.approval !== 'never') {
59
+ return { ok: false, code: 'E_PERMISSION_PROFILE', reason: `default preset ${presetName} is not danger-full-access/never` };
60
+ }
61
+ if (sandboxPolicy.defaultMode !== TEAM_PRESET) {
62
+ return { ok: false, code: 'E_PERMISSION_PROFILE', reason: `sandbox default is ${String(sandboxPolicy.defaultMode)}` };
63
+ }
64
+ return { ok: true, preset: presetName, spec };
65
+ }
66
+
67
+ export class MemberRuntime {
68
+ /**
69
+ * @param {{
70
+ * subagents: any,
71
+ * sessions: any,
72
+ * permissionPresets: any,
73
+ * sandboxPolicy: any,
74
+ * parent: any,
75
+ * provider: string,
76
+ * cwd: string,
77
+ * preset?: string,
78
+ * clock?: () => number
79
+ * }} options
80
+ */
81
+ constructor(options) {
82
+ this.subagents = options.subagents;
83
+ this.sessions = options.sessions;
84
+ this.agents = options.agents;
85
+ this.permissionPresets = options.permissionPresets;
86
+ this.sandboxPolicy = options.sandboxPolicy;
87
+ this.parent = options.parent;
88
+ this.provider = options.provider;
89
+ this.cwd = options.cwd;
90
+ this.preset = options.preset ?? null;
91
+ this.clock = options.clock ?? (() => Date.now());
92
+ }
93
+
94
+ /** Re-apply and verify danger-full-access on one live member session. */
95
+ async ensurePermission(sessionId) {
96
+ const session = this.sessions?.get?.(sessionId);
97
+ if (session === undefined || session === null) {
98
+ fail('E_SESSION_MISSING', `member session ${String(sessionId)} is not live`);
99
+ }
100
+ if (this.sandboxPolicy.overrideOf(session) !== TEAM_PRESET) {
101
+ this.permissionPresets.set(session, resolveTeamPreset(this.permissionPresets));
102
+ }
103
+ if (this.sandboxPolicy.overrideOf(session) !== TEAM_PRESET) {
104
+ fail('E_PERMISSION', `member session ${String(sessionId)} is not ${TEAM_PRESET}`, { sessionId });
105
+ }
106
+ return session;
107
+ }
108
+
109
+ /** Start a new continuable child Agent and bind it to a member. */
110
+ async activate(member, options = {}) {
111
+ if (this.subagents === undefined || this.parent === undefined || typeof this.provider !== 'string') {
112
+ fail('E_RUNTIME_UNAVAILABLE', 'no subagent provider or parent Agent is available');
113
+ }
114
+ const prompt = Array.isArray(options.prompt) ? options.prompt : [{ type: 'text', text: options.prompt ?? '' }];
115
+ const signal = options.signal ?? new AbortController().signal;
116
+ const agentOptions = buildAgentOptions(member.config ?? {});
117
+ let activation;
118
+ try {
119
+ activation = await this.subagents.startActivation({
120
+ provider: options.provider ?? this.provider,
121
+ label: member.name,
122
+ request: {
123
+ cwd: member.workspace ?? this.cwd,
124
+ ...(member.preset ?? member.config?.preset ?? this.preset ? { agentPreset: member.preset ?? member.config?.preset ?? this.preset } : {}),
125
+ prompt,
126
+ parent: this.parent,
127
+ ...(Object.keys(agentOptions).length === 0 ? {} : { agentOptions }),
128
+ },
129
+ signal,
130
+ delivery: 'parent',
131
+ });
132
+ } catch (error) {
133
+ fail('E_ACTIVATION', `member activation failed: ${error?.message ?? error}`, { memberId: member.id });
134
+ }
135
+ try {
136
+ await this.ensurePermission(activation.childId);
137
+ // The subagent setup appends the descriptor before the first prompt; flush
138
+ // it so a later cold resume can reconstruct the continuable child.
139
+ const session = this.agents?.get?.(activation.childId)?.session ?? this.sessions?.get?.(activation.childId);
140
+ if (session !== undefined && session !== null && typeof this.sessions.flush === 'function') {
141
+ await this.sessions.flush(session);
142
+ }
143
+ } catch (error) {
144
+ try { await activation.dispose?.(); } catch { /* already gone */ }
145
+ throw error;
146
+ }
147
+ return {
148
+ childId: activation.childId,
149
+ messageId: activation.messageId ?? null,
150
+ activation,
151
+ member: { ...member, sessionId: activation.childId, status: 'running', activatedAt: this.clock() },
152
+ };
153
+ }
154
+
155
+ /**
156
+ * Wake an existing member. Delivery has exactly ONE path: `subagents.sendMessage`.
157
+ *
158
+ * The SubagentManager owns the continuable child: it steers a running child,
159
+ * starts a turn on an idle one and cold-resumes an offline one (official
160
+ * contract, reference/subsystems/subagent). The plugin must never resume the
161
+ * child itself: a resume handle held by the plugin is the write lease that made
162
+ * the manager's next cold resume fail with NOT_RESUMABLE ("already owned by an
163
+ * active write handle"), which the Host then "repaired" by aborting the running
164
+ * turn and reseating the member (Issue #1; .ptc/rounds/r01-evidence).
165
+ */
166
+ async wake(member, options = {}) {
167
+ if (member.sessionId === undefined || member.sessionId === null) {
168
+ fail('E_SESSION_MISSING', `member ${member.id} has no session`);
169
+ }
170
+ if (typeof this.subagents?.sendMessage !== 'function' || this.parent === undefined) {
171
+ fail('E_RUNTIME_UNAVAILABLE', 'no subagent runtime or parent Agent is available');
172
+ }
173
+ const content = Array.isArray(options.prompt) ? options.prompt : [{ type: 'text', text: options.prompt ?? '' }];
174
+ // 在线会话:投递前复核 danger-full-access。离线会话的权限预设在会话日志里,
175
+ // 由 manager 冷恢复;之后每次工具调用前还有权限守卫兜底。
176
+ const live = this.sessions?.get?.(member.sessionId);
177
+ const cold = live === undefined || live === null;
178
+ if (!cold) await this.ensurePermission(member.sessionId);
179
+ const messageId = await this.subagents.sendMessage(this.parent, member.sessionId, content, {
180
+ signal: options.signal ?? new AbortController().signal,
181
+ });
182
+ const after = this.sessions?.get?.(member.sessionId);
183
+ if (after !== undefined && after !== null && typeof this.sessions.flush === 'function') {
184
+ await this.sessions.flush(after);
185
+ }
186
+ return { messageId, sessionId: member.sessionId, cold };
187
+ }
188
+ }
189
+
190
+ export { TEAM_PRESET };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.87",
3
+ "version": "0.4.88",
4
4
  "type": "module",
5
5
  "description": "文渊阁 (Wenyuan Pavilion) — AI Team mode for DeepSeek Harness: concurrent projects, owned tasks, threads, inbox and an append-only team ledger",
6
6
  "license": "MIT",