@suifei/dsh-ai-team 0.4.151 → 0.4.153

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.
@@ -443,16 +443,6 @@ export class TeamService {
443
443
  // one done row with the duration in every case. 前置校验失败也必须留痕
444
444
  // (errors 档只留 .fail 行,校验抛出必须发生在 try 内才能落行)。
445
445
  const startedAt = Date.now();
446
- const failRow = (code, message) => {
447
- this.diag?.append({
448
- ev: 'dispatch.fail',
449
- type: command.type,
450
- code,
451
- projectId: command.projectId ?? null,
452
- message,
453
- elapsedMs: Date.now() - startedAt,
454
- });
455
- };
456
446
  this.diag?.append({
457
447
  ev: 'dispatch.start',
458
448
  type: command.type,
@@ -460,9 +450,8 @@ export class TeamService {
460
450
  memberId: actor?.memberId ?? null,
461
451
  projectId: command.projectId ?? null,
462
452
  });
463
- try {
464
- if (actor === undefined || (actor.kind !== 'human' && actor.kind !== 'agent')) {
465
- failRow(ERRORS.UNAUTHORIZED, 'an exact Team member is required');
453
+ const checkCommand = () => {
454
+ if (actor?.kind !== 'human' && actor?.kind !== 'agent') {
466
455
  fail(ERRORS.UNAUTHORIZED, 'an exact Team member is required');
467
456
  }
468
457
  // An agent actor must resolve to a live, non-retired member: otherwise a
@@ -470,62 +459,68 @@ export class TeamService {
470
459
  if (actor.kind === 'agent') {
471
460
  const actingMember = this.state.members?.[actor.memberId];
472
461
  if (actingMember === undefined || actingMember.kind !== 'agent') {
473
- failRow(ERRORS.UNAUTHORIZED, `agent actor ${String(actor.memberId ?? '?')} is not a Team member`);
474
462
  fail(ERRORS.UNAUTHORIZED, `agent actor ${String(actor.memberId ?? '?')} is not a Team member`);
475
463
  }
476
464
  if (actingMember.status === 'retired') {
477
- failRow(ERRORS.INVALID_STATE, `agent ${actingMember.name ?? actingMember.id} is retired`);
478
465
  fail(ERRORS.INVALID_STATE, `agent ${actingMember.name ?? actingMember.id} is retired`);
479
466
  }
480
467
  }
481
468
  this.checkBlueprintCommand(command, payload);
469
+ };
470
+ const dispatchExclusive = (work) => this.runExclusive(() => {
471
+ // A queued task mutation can outlive the actor's team membership.
472
+ checkCommand();
473
+ return work();
474
+ });
475
+ try {
476
+ checkCommand();
482
477
  switch (command.type) {
483
478
  case 'project.create': return await this.createProject(command, payload);
484
479
  case 'project.blueprint.prepare':
485
480
  case 'project.blueprint.recordTime':
486
481
  case 'project.blueprint.start':
487
482
  case 'project.blueprint.measure':
488
- case 'project.blueprint.expand': return await this.runExclusive(() => this.advanceBlueprint(command, payload));
483
+ case 'project.blueprint.expand': return await dispatchExclusive(() => this.advanceBlueprint(command, payload));
489
484
  case 'project.owner.update': return await this.changeProjectOwner(command, payload);
490
485
  case 'project.workspace.update': return await this.changeProjectWorkspace(command, payload);
491
- case 'project.repair': return await this.runExclusive(() => this.repairLedger(command));
492
- case 'project.pmo.update': return await this.runExclusive(() => this.setProjectPmo(command, payload));
493
- case 'project.archive': return await this.runExclusive(() => this.setProjectArchive(command, payload));
494
- case 'project.runState': return await this.runExclusive(() => this.setProjectRunState(command, payload));
486
+ case 'project.repair': return await dispatchExclusive(() => this.repairLedger(command));
487
+ case 'project.pmo.update': return await dispatchExclusive(() => this.setProjectPmo(command, payload));
488
+ case 'project.archive': return await dispatchExclusive(() => this.setProjectArchive(command, payload));
489
+ case 'project.runState': return await dispatchExclusive(() => this.setProjectRunState(command, payload));
495
490
  case 'project.handoff': return await this.handoffProject(command, payload);
496
491
  case 'stream.post': return await this.postStream(command, payload);
497
492
  case 'member.add': return await this.addMember(command, payload);
498
493
  case 'member.bind': return await this.bindMemberSession(command, payload);
499
494
  case 'member.fail': return await this.failMember(command, payload);
500
- case 'member.retire': return await this.retireMember(command, payload);
495
+ case 'member.retire': return await dispatchExclusive(() => this.retireMember(command, payload));
501
496
  case 'member.profile.update': return await this.updateMemberProfile(command, payload);
502
497
  case 'member.evolve': return await this.evolveMember(command, payload);
503
498
  case 'member.distill': return await this.distillMember(command, payload);
504
- case 'member.leave': return await this.leaveMember(command, payload);
505
- case 'member.rejoin': return await this.rejoinMember(command, payload);
506
- case 'member.takeover': return await this.takeoverMember(command, payload);
499
+ case 'member.leave': return await dispatchExclusive(() => this.leaveMember(command, payload));
500
+ case 'member.rejoin': return await dispatchExclusive(() => this.rejoinMember(command, payload));
501
+ case 'member.takeover': return await dispatchExclusive(() => this.takeoverMember(command, payload));
507
502
  case 'member.message': return await this.messageMember(command, payload);
508
503
  case 'member.note': return await this.addMemberNote(command, payload);
509
504
  case 'member.skill': return await this.addMemberSkill(command, payload);
510
505
  case 'member.config.update': return await this.updateMemberConfig(command, payload);
511
506
  case 'member.retry': return await this.retryMember(command, payload);
512
- case 'task.create': return await this.runExclusive(() => this.createTask(command, payload));
513
- case 'task.claim': return await this.runExclusive(() => this.taskCommand(command, 'claim'));
514
- case 'task.release': return await this.runExclusive(() => this.taskCommand(command, 'release'));
515
- case 'task.assign': return await this.runExclusive(() => this.taskCommand(command, 'assign'));
516
- case 'task.submit': return await this.runExclusive(() => this.taskCommand(command, 'submit'));
517
- case 'task.accept': return await this.runExclusive(() => this.taskCommand(command, 'accept'));
518
- case 'task.request_changes': return await this.runExclusive(() => this.taskCommand(command, 'request_changes'));
519
- case 'task.cancel': return await this.runExclusive(() => this.taskCommand(command, 'cancel'));
520
- case 'task.reopen': return await this.runExclusive(() => this.taskCommand(command, 'reopen'));
521
- case 'task.reassign': return await this.runExclusive(() => this.taskCommand(command, 'reassign'));
522
- case 'task.delete': return await this.runExclusive(() => this.taskCommand(command, 'delete'));
523
- case 'task.convert': return await this.runExclusive(() => this.convert(command, payload));
507
+ case 'task.create': return await dispatchExclusive(() => this.createTask(command, payload));
508
+ case 'task.claim': return await dispatchExclusive(() => this.taskCommand(command, 'claim'));
509
+ case 'task.release': return await dispatchExclusive(() => this.taskCommand(command, 'release'));
510
+ case 'task.assign': return await dispatchExclusive(() => this.taskCommand(command, 'assign'));
511
+ case 'task.submit': return await dispatchExclusive(() => this.taskCommand(command, 'submit'));
512
+ case 'task.accept': return await dispatchExclusive(() => this.taskCommand(command, 'accept'));
513
+ case 'task.request_changes': return await dispatchExclusive(() => this.taskCommand(command, 'request_changes'));
514
+ case 'task.cancel': return await dispatchExclusive(() => this.taskCommand(command, 'cancel'));
515
+ case 'task.reopen': return await dispatchExclusive(() => this.taskCommand(command, 'reopen'));
516
+ case 'task.reassign': return await dispatchExclusive(() => this.taskCommand(command, 'reassign'));
517
+ case 'task.delete': return await dispatchExclusive(() => this.taskCommand(command, 'delete'));
518
+ case 'task.convert': return await dispatchExclusive(() => this.convert(command, payload));
524
519
  case 'task.follow': return await this.follow(command, payload);
525
520
  case 'thread.post': return await this.postThread(command, payload);
526
521
  case 'inbox.ack': return await this.ack(command, payload);
527
- case 'decision.request': return await this.runExclusive(() => this.requestDecision(command, payload));
528
- case 'decision.answer': return await this.runExclusive(() => this.answerDecision(command, payload));
522
+ case 'decision.request': return await dispatchExclusive(() => this.requestDecision(command, payload));
523
+ case 'decision.answer': return await dispatchExclusive(() => this.answerDecision(command, payload));
529
524
  default: fail(ERRORS.INVALID_ARGUMENT, `unknown command: ${String(command.type)}`);
530
525
  }
531
526
  } catch (error) {
@@ -1,204 +1,204 @@
1
- import { lstat, mkdir, mkdtemp, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
2
- import { dirname, join, posix, relative } from 'node:path';
3
- import { buffer } from 'node:stream/consumers';
4
- import { setTimeout as delay } from 'node:timers/promises';
5
- import { crc32 } from 'node:zlib';
6
- import yauzl from 'yauzl';
7
- import { inspectFileSkill, MAX_SKILL_BODY_BYTES } from '../runtime/skill-provider.js';
8
-
9
- export const MAX_SKILL_IMPORT_REQUEST_BYTES = 64 * 1024 * 1024;
10
- const MAX_FILES = 10_000;
11
- const MAX_FILE_BYTES = 64 * 1024 * 1024;
12
- const MAX_EXPANDED_BYTES = 256 * 1024 * 1024;
13
- const MANIFEST = 'SKILL.md';
14
- const imports = new Set();
15
- const publishDelays = [0, 50, 150, 350, 800];
16
- const transientRenameErrors = new Set(['EACCES', 'EBUSY', 'EPERM']);
17
-
18
- function importError(message, { code = 'E_INVALID_SKILL_PACK', status = 400, details } = {}) {
19
- return Object.assign(new Error(message), { code, status, details });
20
- }
21
-
22
- function packTooLarge() {
23
- return importError('Skill package exceeds the import size limit.', { code: 'E_SKILL_PACK_TOO_LARGE', status: 413 });
24
- }
25
-
26
- function filePath(path) {
27
- if (typeof path !== 'string' || !path.isWellFormed() || path.split('/').some((part) => (
28
- part === '' || /[. ]$/.test(part) || /[\x00-\x1f<>:"\\|?*]/.test(part)
29
- || /^(?:con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(part)
30
- ))) throw importError('Skill package contains an invalid file path.');
31
- return path;
32
- }
33
-
34
- function base64(value) {
35
- if (typeof value !== 'string' || value.length % 4 !== 0 || /[^A-Za-z0-9+/=]|=[^=]|={3}/.test(value)) {
36
- throw importError('Skill package contains invalid file data.');
37
- }
38
- return Buffer.from(value, 'base64');
39
- }
40
-
41
- async function zipFiles(encoded) {
42
- try {
43
- const zip = await yauzl.fromBufferPromise(base64(encoded), { validateEntrySizes: true });
44
- if (zip.entryCount > MAX_FILES) throw packTooLarge();
45
- const files = [];
46
- let expanded = 0;
47
- for await (const entry of zip.eachEntry()) {
48
- const directory = entry.fileName.endsWith('/');
49
- const path = filePath(directory ? entry.fileName.slice(0, -1) : entry.fileName);
50
- const kind = (entry.externalFileAttributes >>> 16) & 0o170000;
51
- if (kind && kind !== (directory ? 0o040000 : 0o100000)) {
52
- throw importError('Skill package may contain only regular files and directories.');
53
- }
54
- if (directory) continue;
55
- if (entry.uncompressedSize > MAX_FILE_BYTES) throw packTooLarge();
56
- expanded += entry.uncompressedSize;
57
- if (expanded > MAX_EXPANDED_BYTES) throw packTooLarge();
58
- files.push({
59
- path,
60
- size: entry.uncompressedSize,
61
- async read() {
62
- let bytes;
63
- try {
64
- bytes = await buffer(await zip.openReadStreamPromise(entry));
65
- } catch {
66
- throw importError('A file in the ZIP skill package could not be read.');
67
- }
68
- if (crc32(bytes) !== entry.crc32) throw importError('A file in the ZIP skill package failed its checksum.');
69
- return bytes;
70
- },
71
- });
72
- }
73
- return files;
74
- } catch (error) {
75
- if (error?.status) throw error;
76
- throw importError('The ZIP or .skill package could not be opened.');
77
- }
78
- }
79
-
80
- async function readPack(payload) {
81
- const hasArchive = typeof payload?.zipBase64 === 'string';
82
- const hasFiles = Array.isArray(payload?.files);
83
- if (hasArchive === hasFiles) throw importError('Upload one skill folder or one ZIP/.skill package.');
84
- if (hasFiles && payload.files.length > MAX_FILES) throw packTooLarge();
85
- const files = hasArchive ? await zipFiles(payload.zipBase64) : payload.files.map((file) => {
86
- const bytes = base64(file?.contentBase64);
87
- if (bytes.length > MAX_FILE_BYTES) throw packTooLarge();
88
- return { path: filePath(file?.path), size: bytes.length, read: () => bytes };
89
- });
90
- const manifests = files.filter((file) => posix.basename(file.path) === MANIFEST)
91
- .sort((a, b) => a.path.length - b.path.length);
92
- if (!manifests.length) throw importError('The skill package is missing SKILL.md.');
93
- const manifest = manifests[0];
94
- const folder = posix.dirname(manifest.path);
95
- const prefix = folder === '.' ? '' : folder + '/';
96
- if (manifests.some((file) => !file.path.startsWith(prefix))) {
97
- throw importError('Select one skill package per import.');
98
- }
99
- if (manifest.size > MAX_SKILL_BODY_BYTES) throw packTooLarge();
100
- const selected = files.filter((file) => file.path.startsWith(prefix))
101
- .map((file) => ({ ...file, path: file.path.slice(prefix.length) }));
102
- const paths = new Set(selected.map((file) => file.path.normalize('NFC').toLowerCase()));
103
- if (paths.size !== selected.length) throw importError('The skill package contains duplicate file paths.');
104
- for (const path of paths) {
105
- for (let parent = posix.dirname(path); parent !== '.'; parent = posix.dirname(parent)) {
106
- if (paths.has(parent)) throw importError('The skill package uses a file as a directory.');
107
- }
108
- }
109
- const markdown = await manifest.read();
110
- let text;
111
- try {
112
- text = new TextDecoder('utf-8', { fatal: true }).decode(markdown);
113
- } catch {
114
- throw importError('SKILL.md must be UTF-8 text.');
115
- }
116
- const metadata = inspectFileSkill(text);
117
- if (metadata.problem || metadata.name.length > 64) {
118
- throw importError('SKILL.md needs a valid skill name, description, and invocation settings.', {
119
- details: { reason: metadata.problem ?? 'name-too-long' },
120
- });
121
- }
122
- if (!metadata.invocation.modelInvocable) throw importError('This skill disables model invocation.');
123
- return { name: filePath(metadata.name), selected, markdown };
124
- }
125
-
126
- async function installRoot(baseDir, project) {
127
- let root = await realpath(baseDir);
128
- if (!(await stat(root)).isDirectory()) throw importError('The skill destination must be a directory.');
129
- for (const segment of project ? ['.dsh', 'skills'] : ['skills']) {
130
- root = join(root, segment);
131
- await mkdir(root).catch((error) => { if (error.code !== 'EEXIST') throw error; });
132
- if (!(await lstat(root)).isDirectory()) throw importError('The skill destination must be a real directory.');
133
- }
134
- return root;
135
- }
136
-
137
- async function pathExists(path) {
138
- try {
139
- await lstat(path);
140
- return true;
141
- } catch (error) {
142
- if (error.code === 'ENOENT') return false;
143
- throw error;
144
- }
145
- }
146
-
147
- /** Both upload formats create one complete, discoverable DSH skill directory. */
148
- export async function installSkillPack(payload, { baseDir, project, installedNames, confirm, moveDirectory = rename }) {
149
- const { name, selected, markdown } = await readPack(payload);
150
- const conflict = () => importError('A skill with this name is already installed or being imported.', {
151
- code: 'E_SKILL_EXISTS', status: 409, details: { name },
152
- });
153
- if (installedNames?.has(name)) throw conflict();
154
- const root = await installRoot(baseDir, project);
155
- const target = join(root, name);
156
- const checkDestination = async () => {
157
- if (await pathExists(target) || await pathExists(target + '.md')) throw conflict();
158
- };
159
- if (imports.has(target)) throw conflict();
160
- imports.add(target);
161
- let temporary;
162
- try {
163
- await checkDestination();
164
- // DSH scans every immediate child of the skill root, including most dot directories.
165
- temporary = await mkdtemp(join(dirname(root), '.ai-team-skill-'));
166
- for (const file of selected) {
167
- const destination = join(temporary, file.path);
168
- await mkdir(dirname(destination), { recursive: true });
169
- await writeFile(destination, file.path === MANIFEST ? markdown : await file.read(), { flag: 'wx' });
170
- }
171
- for (const [attempt, pause] of publishDelays.entries()) {
172
- if (pause > 0) await delay(pause);
173
- await checkDestination();
174
- try {
175
- await moveDirectory(temporary, target);
176
- break;
177
- } catch (error) {
178
- if (attempt === publishDelays.length - 1 || !transientRenameErrors.has(error?.code)) {
179
- await checkDestination();
180
- throw error;
181
- }
182
- }
183
- }
184
- // Keep ownership of this newly published directory until the DSH catalog confirms it.
185
- temporary = target;
186
- const installed = await confirm({ name, path: join(target, MANIFEST) });
187
- temporary = undefined;
188
- return installed;
189
- } finally {
190
- try {
191
- if (temporary) {
192
- const canonical = await realpath(temporary).catch((error) => {
193
- if (error.code === 'ENOENT') return null;
194
- throw error;
195
- });
196
- if (canonical !== null && relative(temporary, canonical) === '') {
197
- await rm(temporary, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
198
- }
199
- }
200
- } finally {
201
- imports.delete(target);
202
- }
203
- }
204
- }
1
+ import { lstat, mkdir, mkdtemp, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { dirname, join, posix, relative } from 'node:path';
3
+ import { buffer } from 'node:stream/consumers';
4
+ import { setTimeout as delay } from 'node:timers/promises';
5
+ import { crc32 } from 'node:zlib';
6
+ import yauzl from 'yauzl';
7
+ import { inspectFileSkill, MAX_SKILL_BODY_BYTES } from '../runtime/skill-provider.js';
8
+
9
+ export const MAX_SKILL_IMPORT_REQUEST_BYTES = 64 * 1024 * 1024;
10
+ const MAX_FILES = 10_000;
11
+ const MAX_FILE_BYTES = 64 * 1024 * 1024;
12
+ const MAX_EXPANDED_BYTES = 256 * 1024 * 1024;
13
+ const MANIFEST = 'SKILL.md';
14
+ const imports = new Set();
15
+ const publishDelays = [0, 50, 150, 350, 800];
16
+ const transientRenameErrors = new Set(['EACCES', 'EBUSY', 'EPERM']);
17
+
18
+ function importError(message, { code = 'E_INVALID_SKILL_PACK', status = 400, details } = {}) {
19
+ return Object.assign(new Error(message), { code, status, details });
20
+ }
21
+
22
+ function packTooLarge() {
23
+ return importError('Skill package exceeds the import size limit.', { code: 'E_SKILL_PACK_TOO_LARGE', status: 413 });
24
+ }
25
+
26
+ function filePath(path) {
27
+ if (typeof path !== 'string' || !path.isWellFormed() || path.split('/').some((part) => (
28
+ part === '' || /[. ]$/.test(part) || /[\x00-\x1f<>:"\\|?*]/.test(part)
29
+ || /^(?:con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(part)
30
+ ))) throw importError('Skill package contains an invalid file path.');
31
+ return path;
32
+ }
33
+
34
+ function base64(value) {
35
+ if (typeof value !== 'string' || value.length % 4 !== 0 || /[^A-Za-z0-9+/=]|=[^=]|={3}/.test(value)) {
36
+ throw importError('Skill package contains invalid file data.');
37
+ }
38
+ return Buffer.from(value, 'base64');
39
+ }
40
+
41
+ async function zipFiles(encoded) {
42
+ try {
43
+ const zip = await yauzl.fromBufferPromise(base64(encoded), { validateEntrySizes: true });
44
+ if (zip.entryCount > MAX_FILES) throw packTooLarge();
45
+ const files = [];
46
+ let expanded = 0;
47
+ for await (const entry of zip.eachEntry()) {
48
+ const directory = entry.fileName.endsWith('/');
49
+ const path = filePath(directory ? entry.fileName.slice(0, -1) : entry.fileName);
50
+ const kind = (entry.externalFileAttributes >>> 16) & 0o170000;
51
+ if (kind && kind !== (directory ? 0o040000 : 0o100000)) {
52
+ throw importError('Skill package may contain only regular files and directories.');
53
+ }
54
+ if (directory) continue;
55
+ if (entry.uncompressedSize > MAX_FILE_BYTES) throw packTooLarge();
56
+ expanded += entry.uncompressedSize;
57
+ if (expanded > MAX_EXPANDED_BYTES) throw packTooLarge();
58
+ files.push({
59
+ path,
60
+ size: entry.uncompressedSize,
61
+ async read() {
62
+ let bytes;
63
+ try {
64
+ bytes = await buffer(await zip.openReadStreamPromise(entry));
65
+ } catch {
66
+ throw importError('A file in the ZIP skill package could not be read.');
67
+ }
68
+ if (crc32(bytes) !== entry.crc32) throw importError('A file in the ZIP skill package failed its checksum.');
69
+ return bytes;
70
+ },
71
+ });
72
+ }
73
+ return files;
74
+ } catch (error) {
75
+ if (error?.status) throw error;
76
+ throw importError('The ZIP or .skill package could not be opened.');
77
+ }
78
+ }
79
+
80
+ async function readPack(payload) {
81
+ const hasArchive = typeof payload?.zipBase64 === 'string';
82
+ const hasFiles = Array.isArray(payload?.files);
83
+ if (hasArchive === hasFiles) throw importError('Upload one skill folder or one ZIP/.skill package.');
84
+ if (hasFiles && payload.files.length > MAX_FILES) throw packTooLarge();
85
+ const files = hasArchive ? await zipFiles(payload.zipBase64) : payload.files.map((file) => {
86
+ const bytes = base64(file?.contentBase64);
87
+ if (bytes.length > MAX_FILE_BYTES) throw packTooLarge();
88
+ return { path: filePath(file?.path), size: bytes.length, read: () => bytes };
89
+ });
90
+ const manifests = files.filter((file) => posix.basename(file.path) === MANIFEST)
91
+ .sort((a, b) => a.path.length - b.path.length);
92
+ if (!manifests.length) throw importError('The skill package is missing SKILL.md.');
93
+ const manifest = manifests[0];
94
+ const folder = posix.dirname(manifest.path);
95
+ const prefix = folder === '.' ? '' : folder + '/';
96
+ if (manifests.some((file) => !file.path.startsWith(prefix))) {
97
+ throw importError('Select one skill package per import.');
98
+ }
99
+ if (manifest.size > MAX_SKILL_BODY_BYTES) throw packTooLarge();
100
+ const selected = files.filter((file) => file.path.startsWith(prefix))
101
+ .map((file) => ({ ...file, path: file.path.slice(prefix.length) }));
102
+ const paths = new Set(selected.map((file) => file.path.normalize('NFC').toLowerCase()));
103
+ if (paths.size !== selected.length) throw importError('The skill package contains duplicate file paths.');
104
+ for (const path of paths) {
105
+ for (let parent = posix.dirname(path); parent !== '.'; parent = posix.dirname(parent)) {
106
+ if (paths.has(parent)) throw importError('The skill package uses a file as a directory.');
107
+ }
108
+ }
109
+ const markdown = await manifest.read();
110
+ let text;
111
+ try {
112
+ text = new TextDecoder('utf-8', { fatal: true }).decode(markdown);
113
+ } catch {
114
+ throw importError('SKILL.md must be UTF-8 text.');
115
+ }
116
+ const metadata = inspectFileSkill(text);
117
+ if (metadata.problem || metadata.name.length > 64) {
118
+ throw importError('SKILL.md needs a valid skill name, description, and invocation settings.', {
119
+ details: { reason: metadata.problem ?? 'name-too-long' },
120
+ });
121
+ }
122
+ if (!metadata.invocation.modelInvocable) throw importError('This skill disables model invocation.');
123
+ return { name: filePath(metadata.name), selected, markdown };
124
+ }
125
+
126
+ async function installRoot(baseDir, project) {
127
+ let root = await realpath(baseDir);
128
+ if (!(await stat(root)).isDirectory()) throw importError('The skill destination must be a directory.');
129
+ for (const segment of project ? ['.dsh', 'skills'] : ['skills']) {
130
+ root = join(root, segment);
131
+ await mkdir(root).catch((error) => { if (error.code !== 'EEXIST') throw error; });
132
+ if (!(await lstat(root)).isDirectory()) throw importError('The skill destination must be a real directory.');
133
+ }
134
+ return root;
135
+ }
136
+
137
+ async function pathExists(path) {
138
+ try {
139
+ await lstat(path);
140
+ return true;
141
+ } catch (error) {
142
+ if (error.code === 'ENOENT') return false;
143
+ throw error;
144
+ }
145
+ }
146
+
147
+ /** Both upload formats create one complete, discoverable DSH skill directory. */
148
+ export async function installSkillPack(payload, { baseDir, project, installedNames, confirm, moveDirectory = rename }) {
149
+ const { name, selected, markdown } = await readPack(payload);
150
+ const conflict = () => importError('A skill with this name is already installed or being imported.', {
151
+ code: 'E_SKILL_EXISTS', status: 409, details: { name },
152
+ });
153
+ if (installedNames?.has(name)) throw conflict();
154
+ const root = await installRoot(baseDir, project);
155
+ const target = join(root, name);
156
+ const checkDestination = async () => {
157
+ if (await pathExists(target) || await pathExists(target + '.md')) throw conflict();
158
+ };
159
+ if (imports.has(target)) throw conflict();
160
+ imports.add(target);
161
+ let temporary;
162
+ try {
163
+ await checkDestination();
164
+ // DSH scans every immediate child of the skill root, including most dot directories.
165
+ temporary = await mkdtemp(join(dirname(root), '.ai-team-skill-'));
166
+ for (const file of selected) {
167
+ const destination = join(temporary, file.path);
168
+ await mkdir(dirname(destination), { recursive: true });
169
+ await writeFile(destination, file.path === MANIFEST ? markdown : await file.read(), { flag: 'wx' });
170
+ }
171
+ for (const [attempt, pause] of publishDelays.entries()) {
172
+ if (pause > 0) await delay(pause);
173
+ await checkDestination();
174
+ try {
175
+ await moveDirectory(temporary, target);
176
+ break;
177
+ } catch (error) {
178
+ if (attempt === publishDelays.length - 1 || !transientRenameErrors.has(error?.code)) {
179
+ await checkDestination();
180
+ throw error;
181
+ }
182
+ }
183
+ }
184
+ // Keep ownership of this newly published directory until the DSH catalog confirms it.
185
+ temporary = target;
186
+ const installed = await confirm({ name, path: join(target, MANIFEST) });
187
+ temporary = undefined;
188
+ return installed;
189
+ } finally {
190
+ try {
191
+ if (temporary) {
192
+ const canonical = await realpath(temporary).catch((error) => {
193
+ if (error.code === 'ENOENT') return null;
194
+ throw error;
195
+ });
196
+ if (canonical !== null && relative(temporary, canonical) === '') {
197
+ await rm(temporary, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
198
+ }
199
+ }
200
+ } finally {
201
+ imports.delete(target);
202
+ }
203
+ }
204
+ }
package/lib/host/waker.js CHANGED
@@ -11,6 +11,16 @@ import { pairedReviewer, projectOwnerId, reviewPairs } from '../domain/policy.js
11
11
  import { isBoardIdle } from '../ledger/fold.js';
12
12
  import { describeAttachments, normalizeAttachments } from '../domain/rich-message.js';
13
13
  import { blocksBlueprintTask } from '../domain/team-blueprint.js';
14
+ import { canDispatchTask } from '../domain/task.js';
15
+
16
+ const CLAIM_WAKE_REASONS = new Set(['task_assigned', 'pmo_dispatch', 'pmo_claim']);
17
+
18
+ export function canDeliverWake(state, { memberId, taskId, reason }) {
19
+ const task = state.tasks?.[taskId];
20
+ const ownerClaims = reason === 'task_created' && (task?.assigneeId == null || task.assigneeId === memberId);
21
+ if (ownerClaims || CLAIM_WAKE_REASONS.has(reason)) return canDispatchTask(state, task, memberId);
22
+ return agentMember(state, memberId, reason === 'route_changed') !== null;
23
+ }
14
24
 
15
25
  function text(value) {
16
26
  return typeof value === 'string' ? value : '';
@@ -20,14 +30,14 @@ function stringIds(value) {
20
30
  return Array.isArray(value) ? [...new Set(value.filter((id) => typeof id === 'string' && id !== ''))] : [];
21
31
  }
22
32
 
23
- function agentMember(state, memberId) {
33
+ function agentMember(state, memberId, allowFailed = false) {
24
34
  if (typeof memberId !== 'string') return null;
25
35
  const member = state.members?.[memberId];
26
36
  if (member === undefined || member.kind !== 'agent') return null;
27
37
  // failed 成员不自动唤醒(其 LLM 正在失败,自动唤醒只会烧预算):
28
38
  // 恢复走 member.retry(Human/Project owner 显式动作)或 Human 在成员
29
39
  // 资料里的「重试」;review 路径另经 eligibleReviewers 的同一排除。
30
- if (member.status === 'retired' || member.status === 'failed') return null;
40
+ if (member.status === 'retired' || (!allowFailed && member.status === 'failed')) return null;
31
41
  return member;
32
42
  }
33
43
 
@@ -136,8 +146,7 @@ export function planWakes(state, result, actor = {}, options = {}) {
136
146
  const blueprint = Boolean(Object.values(state.projects ?? {})[0]?.blueprint);
137
147
  const targets = new Map();
138
148
  const add = (memberId, taskId, reason, key, promptOverride) => {
139
- const member = agentMember(state, memberId);
140
- if (member === null) return;
149
+ if (!canDeliverWake(state, { memberId, taskId, reason })) return;
141
150
  // A thread author must not be woken by their own reply, and the reviewer
142
151
  // candidate is already filtered by eligibility. Other Agent-authored
143
152
  // events (notably a Lead creating a task owned by itself) still need a
@@ -163,10 +172,9 @@ export function planWakes(state, result, actor = {}, options = {}) {
163
172
  // 模型就是明确的修复动作,必须放行,否则改完仍然卡死。
164
173
  if (event?.type === 'member/config-updated' && event.payload?.routeChanged === true) {
165
174
  const memberId = event.payload.memberId;
166
- const member = typeof memberId === 'string' ? state.members?.[memberId] : undefined;
167
175
  // 只唤醒手上有未完成任务的成员:fold 已把 routeStale 记进账本,空闲成员下次被
168
176
  // 真正唤醒时自然在新路由下重建。否则改一次全员模型就空转激活 N 个会话(r08:6 次)。
169
- if (member !== undefined && member.kind === 'agent' && member.status !== 'retired' && unfinishedTasksFor(state, memberId).length > 0) {
177
+ if (canDeliverWake(state, { memberId, reason: 'route_changed' }) && unfinishedTasksFor(state, memberId).length > 0) {
170
178
  targets.set(`${memberId}:route_changed`, {
171
179
  memberId,
172
180
  taskId: null,