@suifei/dsh-ai-team 0.4.24 → 0.4.28
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/CHANGELOG.md +51 -0
- package/client.js +30 -10
- package/index.js +300 -42
- package/lib/domain/task.js +6 -0
- package/lib/host/decision-report.js +16 -2
- package/lib/host/member-tools.js +7 -5
- package/lib/host/project-registry.js +19 -2
- package/lib/host/service.js +172 -35
- package/lib/host/views.js +23 -1
- package/lib/host/waker.js +7 -3
- package/lib/host/weekly-view.js +3 -0
- package/lib/ledger/checkpoint.js +11 -0
- package/lib/ledger/writer.js +164 -23
- package/lib/runtime/failure-policy.js +15 -4
- package/lib/runtime/host-agent.js +38 -10
- package/lib/runtime/host-repair.js +70 -0
- package/lib/runtime/member-runtime.js +19 -12
- package/lib/runtime/skill-catalog.js +4 -1
- package/lib/runtime/skill-provider.js +29 -5
- package/lib/skillopt/adopt-gate.js +1 -1
- package/lib/skillopt/gate-wiring.js +24 -4
- package/lib/skillopt/job-runner.js +5 -0
- package/lib/skillopt/jobs.js +4 -1
- package/lib/skillopt/judge.js +46 -12
- package/lib/skillopt/optimize-wiring.js +12 -6
- package/lib/skillopt/proposal-store.js +33 -0
- package/lib/skillopt/review-runner.js +17 -3
- package/lib/skillopt/reviewer.js +4 -4
- package/lib/skillopt/rubric.js +20 -6
- package/lib/skillopt/tool-access.js +56 -0
- package/package.json +3 -3
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/__init__.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/__main__.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/backend.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/budget.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/config.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/consolidate.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/cycle.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/dream.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/evidence.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/gate.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/handoff_backend.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_codex.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_copilot.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_copilot_cli.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_cursor.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_opencode.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_pi.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_sources.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/judges.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/memory.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/mine.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/multi_skill.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/replay.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/skill_resolver.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/staging.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/state.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/tasks_file.cpython-311.pyc +0 -0
- package/lib/vendor/skillopt/skillopt_sleep/__pycache__/types.cpython-311.pyc +0 -0
package/lib/ledger/writer.js
CHANGED
|
@@ -41,6 +41,13 @@ export const DEFAULT_SEGMENT_BYTES = 32 * 1024 * 1024;
|
|
|
41
41
|
export const SEGMENT_PATTERN = /^ledger-(\d{6})\.jsonl$/;
|
|
42
42
|
export const LOCK_FILE = 'lock';
|
|
43
43
|
|
|
44
|
+
/**
|
|
45
|
+
* Grace period for an unreadable lock record. The lock file is created empty and
|
|
46
|
+
* filled immediately after, so a 0-byte file is normal for a live writer; only
|
|
47
|
+
* an unreadable record older than this counts as a crashed writer.
|
|
48
|
+
*/
|
|
49
|
+
export const LOCK_WRITE_GRACE_MS = 10_000;
|
|
50
|
+
|
|
44
51
|
const DRAFT_FIELDS = new Set([
|
|
45
52
|
'type',
|
|
46
53
|
'payload',
|
|
@@ -148,6 +155,8 @@ export class LedgerWriter {
|
|
|
148
155
|
this._repairs = [];
|
|
149
156
|
this._openResult = null;
|
|
150
157
|
this._queue = Promise.resolve();
|
|
158
|
+
// 回滚失败后置为非空:本句柄不可继续写,必须 close + open 重新扫描。
|
|
159
|
+
this._poisoned = null;
|
|
151
160
|
}
|
|
152
161
|
|
|
153
162
|
get head() {
|
|
@@ -187,6 +196,7 @@ export class LedgerWriter {
|
|
|
187
196
|
}
|
|
188
197
|
|
|
189
198
|
const repairs = [];
|
|
199
|
+
this._poisoned = null;
|
|
190
200
|
try {
|
|
191
201
|
if (this.useLock) this._acquireLock(repairs);
|
|
192
202
|
const scan = this._scan({ repairTail: this.repairTailOnOpen });
|
|
@@ -261,6 +271,14 @@ export class LedgerWriter {
|
|
|
261
271
|
return Promise.reject(new LedgerError('E_EVENT_INVALID', 'appendMany expects an array'));
|
|
262
272
|
}
|
|
263
273
|
if (drafts.length === 0) return Promise.resolve([]);
|
|
274
|
+
// 回滚失败过:本句柄的历史不再可信(可能已有半截写入留在段内),
|
|
275
|
+
// 继续接单会把后续事件追加到未知状态之后。要求 close + open 重新扫描。
|
|
276
|
+
if (this._poisoned !== null && this._poisoned !== undefined) {
|
|
277
|
+
return Promise.reject(new LedgerError('E_LEDGER_POISONED',
|
|
278
|
+
`ledger writer is unusable after a failed rollback (${this._poisoned}); close and open it again`, {
|
|
279
|
+
rollbackError: this._poisoned,
|
|
280
|
+
}));
|
|
281
|
+
}
|
|
264
282
|
return this._enqueue(() => this._appendBatch(drafts));
|
|
265
283
|
}
|
|
266
284
|
|
|
@@ -402,6 +420,16 @@ export class LedgerWriter {
|
|
|
402
420
|
|
|
403
421
|
_appendBatch(drafts) {
|
|
404
422
|
if (this._closed) throw new LedgerError('E_LEDGER_CLOSED', 'ledger is closed');
|
|
423
|
+
// poison 必须在**队列内**复核:appendMany 入口的检查发生在入队之前,
|
|
424
|
+
// 同一 tick 内并发提交的两个批次会同时通过入口检查,先失败的那个把
|
|
425
|
+
// writer 置为 poisoned 后,后一个已经排在队列里,仍会按旧 head 算出重复
|
|
426
|
+
// seq 写进新段——账本此后永久打不开。
|
|
427
|
+
if (this._poisoned !== null && this._poisoned !== undefined) {
|
|
428
|
+
throw new LedgerError('E_LEDGER_POISONED',
|
|
429
|
+
`ledger writer is unusable after a failed rollback (${this._poisoned}); close and open it again`, {
|
|
430
|
+
rollbackError: this._poisoned,
|
|
431
|
+
});
|
|
432
|
+
}
|
|
405
433
|
|
|
406
434
|
const plans = [];
|
|
407
435
|
// 批内查重只用临时小集合;全局查重直接查 _ids(O(1)),避免每次
|
|
@@ -499,13 +527,13 @@ export class LedgerWriter {
|
|
|
499
527
|
if (this.fsync) this._fs.fsyncSync(segFd);
|
|
500
528
|
this._fs.closeSync(segFd);
|
|
501
529
|
}
|
|
502
|
-
// 段号 =
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
530
|
+
// 段号 = 磁盘上已存在段的最大编号 + 1(全新账本的第一段是 000001)。
|
|
531
|
+
// 不能从 origin.index 推导:回滚失败会留下 fd=null 的当前段,
|
|
532
|
+
// 而 origin.index 是「下一个待用编号」,据此新建会复用已存在的段号。
|
|
533
|
+
const lastIndex = Math.max(
|
|
534
|
+
created.length > 0 ? created[created.length - 1].index : 0,
|
|
535
|
+
this._lastSegmentIndexOnDisk(),
|
|
536
|
+
);
|
|
509
537
|
segIndex = lastIndex + 1;
|
|
510
538
|
segName = formatSegmentName(segIndex);
|
|
511
539
|
segPath = path.join(this.dir, segName);
|
|
@@ -523,6 +551,7 @@ export class LedgerWriter {
|
|
|
523
551
|
if (this.fsync) this._fs.fsyncSync(segFd);
|
|
524
552
|
} catch (writeError) {
|
|
525
553
|
const rollbackError = this._rollback(origin, created, segFd);
|
|
554
|
+
if (rollbackError) this._poisoned = rollbackError;
|
|
526
555
|
if (writeError instanceof LedgerError) {
|
|
527
556
|
if (rollbackError) writeError.details = { ...writeError.details, rollbackError };
|
|
528
557
|
throw writeError;
|
|
@@ -611,6 +640,8 @@ export class LedgerWriter {
|
|
|
611
640
|
|
|
612
641
|
_syncCurrentFromScan(scan) {
|
|
613
642
|
if (scan.segments.length === 0) {
|
|
643
|
+
// 空账本:**不要**预创建段文件——空段会被扫描当成可修复的尾段删掉,
|
|
644
|
+
// 段号就跳到 2 了。fd 留空,首次 append 会按需创建 000001。
|
|
614
645
|
this._current = {
|
|
615
646
|
index: 1,
|
|
616
647
|
name: formatSegmentName(1),
|
|
@@ -629,6 +660,30 @@ export class LedgerWriter {
|
|
|
629
660
|
size: this._fs.statSync(last.path).size,
|
|
630
661
|
count: scan.counts.get(last.index) ?? 0,
|
|
631
662
|
};
|
|
663
|
+
this._reopenCurrent();
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/** Re-open the current segment for append when the rollback left no usable fd. */
|
|
667
|
+
_reopenCurrent() {
|
|
668
|
+
if (this._current === null || this._current.fd !== null) return;
|
|
669
|
+
try {
|
|
670
|
+
this._current = {
|
|
671
|
+
...this._current,
|
|
672
|
+
fd: this._fs.openSync(this._current.path, 'a'),
|
|
673
|
+
};
|
|
674
|
+
} catch {
|
|
675
|
+
// 段文件可能已被回滚删除;保持 fd=null,append 会按磁盘最大段号新建。
|
|
676
|
+
this._current = { ...this._current, fd: null };
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** Highest segment index that actually exists on disk (0 when the dir is empty). */
|
|
681
|
+
_lastSegmentIndexOnDisk() {
|
|
682
|
+
let max = 0;
|
|
683
|
+
for (const segment of this._listSegments()) {
|
|
684
|
+
if (segment.index > max) max = segment.index;
|
|
685
|
+
}
|
|
686
|
+
return max;
|
|
632
687
|
}
|
|
633
688
|
|
|
634
689
|
_listSegments() {
|
|
@@ -678,6 +733,7 @@ export class LedgerWriter {
|
|
|
678
733
|
const segments = this._listSegments();
|
|
679
734
|
const events = [];
|
|
680
735
|
const counts = new Map();
|
|
736
|
+
const seenIds = new Set();
|
|
681
737
|
let prevHash = GENESIS_HASH;
|
|
682
738
|
let expectedSeq = 1;
|
|
683
739
|
let repair = null;
|
|
@@ -745,6 +801,18 @@ export class LedgerWriter {
|
|
|
745
801
|
...result,
|
|
746
802
|
});
|
|
747
803
|
}
|
|
804
|
+
// 事件 id 是外部引用的唯一键:append 路径保证不重复,但双写者/外部
|
|
805
|
+
// 合并/手工修复都可能造出重复 id。载入时静默折叠会让引用产生歧义,
|
|
806
|
+
// 因此在这里按损坏账本处理(open 与 verify 都会报出来)。
|
|
807
|
+
if (seenIds.has(event.id)) {
|
|
808
|
+
throw new LedgerError('E_LEDGER_CORRUPT', 'ledger contains a duplicate event id', {
|
|
809
|
+
reason: 'duplicate-id',
|
|
810
|
+
file: segment.name,
|
|
811
|
+
line: lineIndex + 1,
|
|
812
|
+
id: event.id,
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
seenIds.add(event.id);
|
|
748
816
|
events.push(event);
|
|
749
817
|
prevHash = event.hash;
|
|
750
818
|
expectedSeq += 1;
|
|
@@ -782,6 +850,7 @@ export class LedgerWriter {
|
|
|
782
850
|
|
|
783
851
|
_acquireLock(repairs) {
|
|
784
852
|
const lockPath = path.join(this.dir, LOCK_FILE);
|
|
853
|
+
const takeoverPath = `${lockPath}.takeover`;
|
|
785
854
|
|
|
786
855
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
787
856
|
try {
|
|
@@ -807,8 +876,9 @@ export class LedgerWriter {
|
|
|
807
876
|
}
|
|
808
877
|
|
|
809
878
|
const existing = this._readLock(lockPath);
|
|
810
|
-
|
|
811
|
-
if (
|
|
879
|
+
// 锁在 fopen 与读取之间消失:没有锁可接管,直接重试创建。
|
|
880
|
+
if (existing.error === 'missing') continue;
|
|
881
|
+
if (!this._isStaleLock(existing.data, lockPath)) {
|
|
812
882
|
throw new LedgerError('E_LOCKED', 'project ledger is locked by another writer', {
|
|
813
883
|
pid: existing.data?.pid ?? null,
|
|
814
884
|
host: existing.data?.host ?? null,
|
|
@@ -820,20 +890,75 @@ export class LedgerWriter {
|
|
|
820
890
|
pid: existing.data?.pid ?? null,
|
|
821
891
|
});
|
|
822
892
|
}
|
|
893
|
+
// 单赢家接管:只有成功创建 takeover 标记的进程可以删除陈旧锁。
|
|
894
|
+
// 否则两个进程会各自"读到陈旧 → unlink → 新建",把对方的活锁删掉。
|
|
895
|
+
// 标记必须带所有者且可判陈旧:否则一次崩溃(或 unlink 失败)留下的
|
|
896
|
+
// 空标记会让该项目**永久** E_LOCKED,只能手工删文件才能恢复。
|
|
897
|
+
let held = false;
|
|
898
|
+
for (let markerAttempt = 0; markerAttempt < 2 && !held; markerAttempt += 1) {
|
|
899
|
+
try {
|
|
900
|
+
const marker = this._fs.openSync(takeoverPath, 'wx');
|
|
901
|
+
try {
|
|
902
|
+
writeAll(this._fs, marker, Buffer.from(`${canonicalJson({ pid: process.pid, startedAt: this._clock() })}\n`, 'utf8'));
|
|
903
|
+
} finally {
|
|
904
|
+
this._fs.closeSync(marker);
|
|
905
|
+
}
|
|
906
|
+
held = true;
|
|
907
|
+
} catch (markerError) {
|
|
908
|
+
if (markerError.code !== 'EEXIST') {
|
|
909
|
+
throw new LedgerError('E_LOCKED', `cannot create ledger takeover marker: ${markerError.message}`, {
|
|
910
|
+
pid: existing.data?.pid ?? null,
|
|
911
|
+
sysCode: markerError.code ?? null,
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
// 陈旧标记(创建者已死或超时)直接回收,避免永久卡死。
|
|
915
|
+
if (this._lockRecordAge(takeoverPath) > LOCK_WRITE_GRACE_MS) {
|
|
916
|
+
try { this._fs.unlinkSync(takeoverPath); } catch { /* someone else reclaimed it */ }
|
|
917
|
+
continue;
|
|
918
|
+
}
|
|
919
|
+
throw new LedgerError('E_LOCKED', 'another writer is taking over the ledger lock', {
|
|
920
|
+
pid: existing.data?.pid ?? null,
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
if (!held) {
|
|
925
|
+
throw new LedgerError('E_LOCKED', 'ledger takeover marker could not be acquired', {});
|
|
926
|
+
}
|
|
823
927
|
try {
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
928
|
+
// 标记生效后重新读取:原主可能已经写完(或已被别人接管成新锁)。
|
|
929
|
+
const fresh = this._readLock(lockPath);
|
|
930
|
+
if (fresh.error !== 'missing' && !this._isStaleLock(fresh.data, lockPath)) {
|
|
931
|
+
throw new LedgerError('E_LOCKED', 'ledger lock was refreshed by its owner during takeover', {
|
|
932
|
+
pid: fresh.data?.pid ?? null,
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
try {
|
|
936
|
+
this._fs.unlinkSync(lockPath);
|
|
937
|
+
} catch (unlinkError) {
|
|
938
|
+
if (unlinkError.code !== 'ENOENT') {
|
|
939
|
+
throw new LedgerError('E_LOCKED', `cannot remove stale ledger lock: ${unlinkError.message}`);
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
repairs.push({
|
|
943
|
+
kind: 'stale-lock',
|
|
944
|
+
pid: existing.data?.pid ?? null,
|
|
945
|
+
host: existing.data?.host ?? null,
|
|
946
|
+
startedAt: existing.data?.startedAt ?? null,
|
|
947
|
+
reason: existing.error ?? 'owner-not-running',
|
|
948
|
+
});
|
|
949
|
+
} finally {
|
|
950
|
+
try {
|
|
951
|
+
this._fs.unlinkSync(takeoverPath);
|
|
952
|
+
} catch (markerCleanupError) {
|
|
953
|
+
// 不静默:残留标记会被陈旧回收逻辑接管,但要在日志里留痕。
|
|
954
|
+
if (markerCleanupError.code !== 'ENOENT') {
|
|
955
|
+
console.warn(`[ai-team] ledger takeover marker could not be removed (${takeoverPath}): ${markerCleanupError.message}`);
|
|
956
|
+
}
|
|
957
|
+
}
|
|
827
958
|
}
|
|
828
|
-
repairs.push({
|
|
829
|
-
kind: 'stale-lock',
|
|
830
|
-
pid: existing.data?.pid ?? null,
|
|
831
|
-
host: existing.data?.host ?? null,
|
|
832
|
-
startedAt: existing.data?.startedAt ?? null,
|
|
833
|
-
reason: existing.error ?? 'owner-not-running',
|
|
834
|
-
});
|
|
835
959
|
}
|
|
836
960
|
}
|
|
961
|
+
throw new LedgerError('E_LOCKED', 'project ledger lock could not be acquired', {});
|
|
837
962
|
}
|
|
838
963
|
|
|
839
964
|
_readLock(lockPath) {
|
|
@@ -850,8 +975,21 @@ export class LedgerWriter {
|
|
|
850
975
|
}
|
|
851
976
|
}
|
|
852
977
|
|
|
853
|
-
|
|
854
|
-
|
|
978
|
+
/** Age of the on-disk lock record in ms; Infinity when it cannot be stat'd. */
|
|
979
|
+
_lockRecordAge(lockPath) {
|
|
980
|
+
try {
|
|
981
|
+
return this._clock() - this._fs.statSync(lockPath).mtimeMs;
|
|
982
|
+
} catch {
|
|
983
|
+
return Number.POSITIVE_INFINITY;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
_isStaleLock(data, lockPath) {
|
|
988
|
+
if (!data || !Number.isSafeInteger(data.pid) || data.pid <= 0) {
|
|
989
|
+
// 锁创建与写入 payload 之间文件是 0 字节:无条件判陈旧会让并发进程
|
|
990
|
+
// 接管一个仍然活着的锁。给写入一个宽限期,超时后才认为是崩溃残留。
|
|
991
|
+
return this._lockRecordAge(lockPath) > LOCK_WRITE_GRACE_MS;
|
|
992
|
+
}
|
|
855
993
|
// 不同主机共享目录:无法用本机 PID 判断,保守视为仍持有。
|
|
856
994
|
if (typeof data.host === 'string' && data.host.length > 0 && data.host !== os.hostname()) {
|
|
857
995
|
return false;
|
|
@@ -993,10 +1131,13 @@ export function openLedger(options = {}) {
|
|
|
993
1131
|
return writer.head.seq;
|
|
994
1132
|
},
|
|
995
1133
|
async append(draft) {
|
|
1134
|
+
// 先齐平 events:checkpoint 齐平启动时 events 还是 null,若等 append 之后再
|
|
1135
|
+
// readAll,刚写入的事件会被读出来、再被 push 一次(重复)。
|
|
1136
|
+
const list = ensureEvents();
|
|
996
1137
|
const event = await writer.append(draft);
|
|
997
1138
|
// 只有 append 成功(含 fsync)后才推进内存状态。
|
|
998
1139
|
Object.assign(state, applyEvent(state, event));
|
|
999
|
-
|
|
1140
|
+
list.push(event);
|
|
1000
1141
|
try {
|
|
1001
1142
|
onEvent?.(event);
|
|
1002
1143
|
} catch {
|
|
@@ -1012,9 +1153,9 @@ export function openLedger(options = {}) {
|
|
|
1012
1153
|
return event;
|
|
1013
1154
|
},
|
|
1014
1155
|
async appendMany(drafts) {
|
|
1156
|
+
const list = ensureEvents();
|
|
1015
1157
|
const appended = await writer.appendMany(drafts);
|
|
1016
1158
|
let next = state;
|
|
1017
|
-
const list = ensureEvents();
|
|
1018
1159
|
for (const event of appended) {
|
|
1019
1160
|
next = applyEvent(next, event);
|
|
1020
1161
|
list.push(event);
|
|
@@ -50,6 +50,11 @@ export function classifyLlmFailure(error) {
|
|
|
50
50
|
if (status === 401 || status === 403 || code.includes('INVALID_API_KEY') || code.includes('UNAUTHORIZED')) {
|
|
51
51
|
return { ...base, category: FAILURE_CATEGORY.AUTH, retryable: false, humanRequired: true, action: 'stop' };
|
|
52
52
|
}
|
|
53
|
+
// 429 必须先判:限流响应常带 "quota"/"insufficient" 字样,若先走 billing
|
|
54
|
+
// 分支就会被当成致命计费错误,永远不重试也不换路。
|
|
55
|
+
if (status === 429 || code.includes('RATE_LIMIT') || /rate limit/.test(text)) {
|
|
56
|
+
return { ...base, category: FAILURE_CATEGORY.RATE_LIMIT, retryable: true, humanRequired: false, action: 'retry_or_fallback' };
|
|
57
|
+
}
|
|
53
58
|
if (
|
|
54
59
|
status === 402 ||
|
|
55
60
|
/insufficient|balance|quota|billing|payment|credit/.test(code) ||
|
|
@@ -57,9 +62,6 @@ export function classifyLlmFailure(error) {
|
|
|
57
62
|
) {
|
|
58
63
|
return { ...base, category: FAILURE_CATEGORY.BILLING, retryable: false, humanRequired: true, action: 'stop' };
|
|
59
64
|
}
|
|
60
|
-
if (status === 429 || code.includes('RATE_LIMIT') || /rate limit/.test(text)) {
|
|
61
|
-
return { ...base, category: FAILURE_CATEGORY.RATE_LIMIT, retryable: true, humanRequired: false, action: 'retry_or_fallback' };
|
|
62
|
-
}
|
|
63
65
|
if (status !== null && status >= 500) {
|
|
64
66
|
return { ...base, category: FAILURE_CATEGORY.SERVER, retryable: true, humanRequired: false, action: 'retry_or_fallback' };
|
|
65
67
|
}
|
|
@@ -93,7 +95,13 @@ export function retryDecision(failure, config = {}, attempt = 1) {
|
|
|
93
95
|
const maxAttempts = Number.isSafeInteger(config.retry?.maxAttempts)
|
|
94
96
|
? Math.max(1, Math.min(config.retry.maxAttempts, 5))
|
|
95
97
|
: 3;
|
|
96
|
-
|
|
98
|
+
// 换路(fallback)能否执行取决于“路由可变”,与“同路由立刻重试”不同:
|
|
99
|
+
// model_unavailable / context_overflow 明确声明了 fallback 语义且 retryable=false,
|
|
100
|
+
// 若这里按 retryable 一刀切返回 fail,它们的 fallback 声明就永远不可达。
|
|
101
|
+
const fallbackCapable = failure?.retryable === true
|
|
102
|
+
|| failure?.action === 'fallback'
|
|
103
|
+
|| failure?.action === 'compact_or_fallback';
|
|
104
|
+
if (!fallbackCapable) return { action: 'fail', attempt, reason: `${failure?.category ?? 'unknown'} has no recoverable action` };
|
|
97
105
|
const nextFallbackIndex = attempt - 1;
|
|
98
106
|
const fallback = fallbackAt(config, nextFallbackIndex);
|
|
99
107
|
if (fallback !== null) {
|
|
@@ -112,6 +120,9 @@ export function retryDecision(failure, config = {}, attempt = 1) {
|
|
|
112
120
|
reason: `fallback to ${fallback.provider ?? config.provider}/${fallback.model ?? config.model}`,
|
|
113
121
|
};
|
|
114
122
|
}
|
|
123
|
+
if (failure?.retryable !== true) {
|
|
124
|
+
return { action: 'fail', attempt, reason: `${failure?.category ?? 'unknown'} is not retryable and has no fallback route` };
|
|
125
|
+
}
|
|
115
126
|
if (attempt >= maxAttempts) return { action: 'fail', attempt, reason: `retry budget exhausted (${maxAttempts})` };
|
|
116
127
|
// No fallback route configured: a rate limit would hit again at once
|
|
117
128
|
// without a backoff clock — end the turn and let the next event/startup
|
|
@@ -3,11 +3,20 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Preference order:
|
|
5
5
|
* 1. an existing live root Agent (the Human's current session);
|
|
6
|
-
* 2. a lazily created
|
|
6
|
+
* 2. a lazily created Team Host Agent (the Human owner has no
|
|
7
7
|
* session, e.g. the workbench was opened without a chat).
|
|
8
8
|
*
|
|
9
9
|
* The Host Agent is a runtime root, not a product member: it owns no Task,
|
|
10
|
-
* has no product decision power
|
|
10
|
+
* has no product decision power.
|
|
11
|
+
*
|
|
12
|
+
* IMPORTANT — the Host Agent must never be archived. Members are subagent
|
|
13
|
+
* descendants of it, and `archived-session-gate` (dsh-api-session-controller)
|
|
14
|
+
* rejects every `agent/pre-step` whose Session, or any Session above it in the
|
|
15
|
+
* subagent lineage, is archived. The loop then ends the turn as
|
|
16
|
+
* `{kind:'blocked'}` **without issuing a model request**, so archiving the host
|
|
17
|
+
* silently disables the whole team (observed: 453 blocked turns, 0 completed).
|
|
18
|
+
* Earlier revisions archived it to hide it from the session list; that is
|
|
19
|
+
* repaired here by unarchiving on resolve.
|
|
11
20
|
*/
|
|
12
21
|
import { randomUUID } from 'node:crypto';
|
|
13
22
|
|
|
@@ -35,6 +44,21 @@ export async function ensureHostAgent(options) {
|
|
|
35
44
|
if (agents === undefined || typeof agents.create !== 'function') {
|
|
36
45
|
throw new HostAgentError('E_RUNTIME_UNAVAILABLE', 'agents service is unavailable');
|
|
37
46
|
}
|
|
47
|
+
// Repair a Host Agent archived by an earlier revision: the archive gate
|
|
48
|
+
// covers the host's whole subagent lineage, so every member turn would end
|
|
49
|
+
// blocked before any model request. `unarchiveSession` resolves without
|
|
50
|
+
// writing when the id is not archived, so no read-back is needed — and
|
|
51
|
+
// gating on the undocumented `archivedSessionIds` accessor is what silently
|
|
52
|
+
// skipped this repair before.
|
|
53
|
+
const unarchiveHost = async (sessionId) => {
|
|
54
|
+
const registry = options.workspaceRegistry;
|
|
55
|
+
if (typeof registry?.unarchiveSession !== 'function') return;
|
|
56
|
+
try {
|
|
57
|
+
await registry.unarchiveSession(sessionId);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
console.warn('[ai-team] could not unarchive Team Host session:', error?.message ?? error);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
38
62
|
// Persist the resolved route into the session log. Live AgentOptions die
|
|
39
63
|
// with the process; without a recorded selection a restored session renders
|
|
40
64
|
// prompts with an unresolvable {{model}} variable.
|
|
@@ -51,13 +75,14 @@ export async function ensureHostAgent(options) {
|
|
|
51
75
|
if (typeof options.resumeSessionId === 'string' && options.resumeSessionId !== '') {
|
|
52
76
|
const live = typeof agents.get === 'function' ? agents.get(options.resumeSessionId) : undefined;
|
|
53
77
|
if (live !== undefined) {
|
|
78
|
+
await unarchiveHost(options.resumeSessionId);
|
|
54
79
|
const selection = typeof options.agentDefaultModel?.currentSelection === 'function' ? options.agentDefaultModel.currentSelection() : null;
|
|
55
80
|
persistSelection(options.resumeSessionId, selection);
|
|
56
81
|
return { agent: live, created: false, resumed: true, sessionId: options.resumeSessionId, dispose: async () => {} };
|
|
57
82
|
}
|
|
58
83
|
try {
|
|
59
84
|
const handle = await agents.resume({ resumeSessionId: options.resumeSessionId });
|
|
60
|
-
|
|
85
|
+
await unarchiveHost(options.resumeSessionId);
|
|
61
86
|
const selection = typeof options.agentDefaultModel?.currentSelection === 'function' ? options.agentDefaultModel.currentSelection() : null;
|
|
62
87
|
persistSelection(options.resumeSessionId, selection);
|
|
63
88
|
return {
|
|
@@ -77,7 +102,15 @@ export async function ensureHostAgent(options) {
|
|
|
77
102
|
}
|
|
78
103
|
const roots = typeof agents.roots === 'function' ? agents.roots() : [];
|
|
79
104
|
if (roots.length > 0) {
|
|
80
|
-
|
|
105
|
+
// roots() 只保证注册顺序,不保证某个元素是「Human 的根会话」;优先挑一个
|
|
106
|
+
// 真正没有父会话、且不是 subagent 出来的根,避免把成员自己的父链当成
|
|
107
|
+
// Human 通道(那会让成员成为彼此的 parent)。
|
|
108
|
+
const rootAgent = roots.find((candidate) => {
|
|
109
|
+
const header = candidate?.session?.header;
|
|
110
|
+
if (header === undefined) return true;
|
|
111
|
+
return header.origin !== 'subagent' && header.parentSession === undefined;
|
|
112
|
+
}) ?? roots[0];
|
|
113
|
+
return { agent: rootAgent, created: false, sessionId: rootAgent.id, dispose: async () => {} };
|
|
81
114
|
}
|
|
82
115
|
|
|
83
116
|
const selection = typeof options.agentDefaultModel?.currentSelection === 'function'
|
|
@@ -103,12 +136,7 @@ export async function ensureHostAgent(options) {
|
|
|
103
136
|
}
|
|
104
137
|
persistSelection(sessionId, selection);
|
|
105
138
|
const host = handle.agent;
|
|
106
|
-
|
|
107
|
-
await options.workspaceRegistry?.archiveSession?.(sessionId);
|
|
108
|
-
} catch (error) {
|
|
109
|
-
// Hiding the host session is cosmetic; activation still works.
|
|
110
|
-
console.warn('[ai-team] could not archive Team Host session:', error?.message ?? error);
|
|
111
|
-
}
|
|
139
|
+
await unarchiveHost(sessionId);
|
|
112
140
|
return {
|
|
113
141
|
agent: host,
|
|
114
142
|
created: true,
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Repair Team Host sessions archived by earlier revisions.
|
|
3
|
+
*
|
|
4
|
+
* Members are subagent descendants of the Host Agent, and
|
|
5
|
+
* `archived-session-gate` (dsh-api-session-controller) rejects every
|
|
6
|
+
* `agent/pre-step` whose Session — or any Session above it in the subagent
|
|
7
|
+
* lineage — is archived. The loop then ends the turn as `{kind:'blocked'}`
|
|
8
|
+
* **without issuing a model request**, so an archived Host silently disables
|
|
9
|
+
* the whole team (measured: 453 blocked turns, 0 completed, no `request/header`).
|
|
10
|
+
*
|
|
11
|
+
* Earlier revisions archived the Host on purpose to hide it from the session
|
|
12
|
+
* list. This sweep lifts that damage by calling `unarchiveSession` for the
|
|
13
|
+
* persisted host of each runtime and the `parentSession` of every member session.
|
|
14
|
+
*
|
|
15
|
+
* Two constraints learned the hard way:
|
|
16
|
+
* 1. Use only the **documented** API. `archivedSessionIds` is not part of the
|
|
17
|
+
* workspaceRegistry contract; gating on it silently skipped the whole
|
|
18
|
+
* repair. `unarchiveSession` on a non-archived id resolves without writing,
|
|
19
|
+
* so calling it unconditionally is safe and needs no read-back.
|
|
20
|
+
* 2. Diagnostics ending without `.fail` are dropped at the default `errors`
|
|
21
|
+
* diag level. Failure rows therefore carry `.fail`; success is proven by
|
|
22
|
+
* the durable archive list, not by a log line.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {{
|
|
27
|
+
* runtimes: Iterable<any>,
|
|
28
|
+
* sessions?: { get?: (id: string) => any },
|
|
29
|
+
* workspaceRegistry?: { unarchiveSession?: (id: string) => Promise<void> },
|
|
30
|
+
* diag?: { append?: (row: any) => any } | null,
|
|
31
|
+
* knownHostSessionIds?: Iterable<string>
|
|
32
|
+
* }} options
|
|
33
|
+
* @returns {Promise<string[]|null>} session ids the sweep asked to unarchive;
|
|
34
|
+
* `null` means the registry was not ready yet and the caller should retry.
|
|
35
|
+
*/
|
|
36
|
+
export async function repairArchivedHosts(options = {}) {
|
|
37
|
+
const registry = options.workspaceRegistry;
|
|
38
|
+
// `workspaceRegistry` 要等 sessionPersistence 与历史 bootstrap 完成才 active,
|
|
39
|
+
// 插件激活瞬间常常还取不到。此时返回 null(而不是空数组)让调用方保持
|
|
40
|
+
// 「未修复」状态,等下一个 tick 重试——而不是一次失败就永久放弃。
|
|
41
|
+
if (registry === undefined || registry === null || typeof registry.unarchiveSession !== 'function') return null;
|
|
42
|
+
|
|
43
|
+
const victims = new Set();
|
|
44
|
+
for (const known of options.knownHostSessionIds ?? []) {
|
|
45
|
+
if (typeof known === 'string' && known !== '') victims.add(known);
|
|
46
|
+
}
|
|
47
|
+
for (const runtime of options.runtimes ?? []) {
|
|
48
|
+
const hostId = runtime?.service?.state?.hostSessionId;
|
|
49
|
+
if (typeof hostId === 'string' && hostId !== '') victims.add(hostId);
|
|
50
|
+
for (const member of Object.values(runtime?.service?.state?.members ?? {})) {
|
|
51
|
+
const sessionId = member?.sessionId;
|
|
52
|
+
if (typeof sessionId !== 'string' || sessionId === '') continue;
|
|
53
|
+
try {
|
|
54
|
+
const header = options.sessions?.get?.(sessionId)?.header;
|
|
55
|
+
if (typeof header?.parentSession === 'string') victims.add(header.parentSession);
|
|
56
|
+
} catch { /* member session is not live; skip */ }
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const repaired = [];
|
|
61
|
+
for (const sessionId of victims) {
|
|
62
|
+
try {
|
|
63
|
+
await registry.unarchiveSession(sessionId);
|
|
64
|
+
repaired.push(sessionId);
|
|
65
|
+
} catch (error) {
|
|
66
|
+
options.diag?.append?.({ ev: 'host.unarchive.fail', sessionId, message: error?.message ?? String(error) });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return repaired;
|
|
70
|
+
}
|
|
@@ -256,19 +256,26 @@ export class MemberRuntime {
|
|
|
256
256
|
return { messageId: message.id, sessionId: member.sessionId, direct: true };
|
|
257
257
|
}
|
|
258
258
|
let session = this.sessions?.get?.(member.sessionId);
|
|
259
|
-
//
|
|
260
|
-
//
|
|
261
|
-
//
|
|
262
|
-
if ((session === undefined || session === null) && this.agents?.resume !== undefined) {
|
|
263
|
-
try {
|
|
264
|
-
const handle = await this.agents.resume({ resumeSessionId: member.sessionId, parentAgent: this.parent });
|
|
265
|
-
this.trackHandle?.(member.sessionId, handle);
|
|
266
|
-
session = this.sessions?.get?.(member.sessionId);
|
|
267
|
-
} catch { /* fall through to sendMessage cold path */ }
|
|
268
|
-
}
|
|
269
|
-
// If resume still could not produce a live Session, sendMessage is the
|
|
270
|
-
// only available path; its permission preset is already in the session log.
|
|
259
|
+
// 冷会话:只走**一条**恢复路径。先 agents.resume 再 sendMessage 会让
|
|
260
|
+
// subagent manager 再做一次冷恢复并以 NOT_RESUMABLE 失败(它的 continuable
|
|
261
|
+
// 句柄已被前一次 resume 消耗),进而触发上层强制重建、丢成员历史。
|
|
271
262
|
if (session === undefined || session === null) {
|
|
263
|
+
if (this.agents?.resume !== undefined) {
|
|
264
|
+
let handle = null;
|
|
265
|
+
try {
|
|
266
|
+
handle = await this.agents.resume({ resumeSessionId: member.sessionId, parentAgent: this.parent });
|
|
267
|
+
} catch { handle = null; }
|
|
268
|
+
if (handle?.agent !== undefined && handle?.agent !== null && typeof handle.agent.followup === 'function') {
|
|
269
|
+
this.trackHandle?.(member.sessionId, handle);
|
|
270
|
+
await this.ensurePermission(member.sessionId);
|
|
271
|
+
const message = userMessage(typeof options.prompt === 'string' ? options.prompt : '继续');
|
|
272
|
+
handle.agent.followup(message);
|
|
273
|
+
const live = this.sessions?.get?.(member.sessionId);
|
|
274
|
+
if (live !== undefined && live !== null && typeof this.sessions.flush === 'function') await this.sessions.flush(live);
|
|
275
|
+
return { messageId: message.id, sessionId: member.sessionId, cold: true, resumed: true };
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
// resume 不可用:只剩 subagent manager 的冷投递(其权限预设已在会话日志里)。
|
|
272
279
|
const messageId = await this.subagents.sendMessage(this.parent, member.sessionId, content, {
|
|
273
280
|
signal: options.signal ?? new AbortController().signal,
|
|
274
281
|
});
|
|
@@ -18,7 +18,10 @@ export async function formatSkillCatalog(skills, options = {}) {
|
|
|
18
18
|
...(options.cwd ? { cwd: options.cwd } : {}),
|
|
19
19
|
}).catch(() => []);
|
|
20
20
|
if (!Array.isArray(summaries) || summaries.length === 0) return '';
|
|
21
|
-
|
|
21
|
+
// 只注入「模型可以自己调用」的技能:`disable-model-invocation: true` 的技能
|
|
22
|
+
// 是给 Human 显式用的,列进成员 prompt 会把成员引向一个它无权调用的入口。
|
|
23
|
+
const available = summaries.filter((skill) =>
|
|
24
|
+
!isSkillExcluded(skill?.name) && skill?.modelInvocable !== false && skill?.disableModelInvocation !== true);
|
|
22
25
|
if (available.length === 0) return '';
|
|
23
26
|
const limit = Number.isSafeInteger(options.limit) && options.limit > 0 ? options.limit : 12;
|
|
24
27
|
const rows = available.slice(0, limit).map((skill) => {
|
|
@@ -29,7 +29,10 @@ function parseFrontmatter(text) {
|
|
|
29
29
|
if (!text.startsWith('---')) return {};
|
|
30
30
|
const end = text.indexOf('\n---', 3);
|
|
31
31
|
if (end < 0) return {};
|
|
32
|
-
|
|
32
|
+
// CRLF 必须在这里断干净:`\r` 在 JS 里是行终止符,`.$` 无法越过它,
|
|
33
|
+
// 带尾 `\r` 的最后一行(常见于 Windows 编辑器)会整行失配——
|
|
34
|
+
// description 恰好位于末尾时,整个技能被当成「缺少 description」丢弃。
|
|
35
|
+
const lines = text.slice(3, end).split(/\r\n|\r|\n/);
|
|
33
36
|
const fields = {};
|
|
34
37
|
let key = null;
|
|
35
38
|
for (const line of lines) {
|
|
@@ -87,7 +90,10 @@ function scanCandidate(file, fallbackName, source) {
|
|
|
87
90
|
}
|
|
88
91
|
const fields = parseFrontmatter(text);
|
|
89
92
|
const name = unquote(fields.name) || fallbackName;
|
|
90
|
-
|
|
93
|
+
// Must match the host registry's SKILL_NAME exactly (`^[a-z0-9]+(?:-[a-z0-9]+)*$`):
|
|
94
|
+
// a name we accept but the registry rejects makes `skills.snapshot` throw
|
|
95
|
+
// "skill provider returned invalid skill name", which aborts every agent step.
|
|
96
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) return null;
|
|
91
97
|
if (isSkillExcluded(name)) return null;
|
|
92
98
|
const description = unquote(fields.description);
|
|
93
99
|
// Official semantics: `description` is required; a skill without one is
|
|
@@ -173,8 +179,14 @@ export function createFileSkillProvider({ dshHome, projectCwd, bundledDir } = {}
|
|
|
173
179
|
async get(candidate) {
|
|
174
180
|
const file = candidate?.locator;
|
|
175
181
|
if (typeof file !== 'string' || !existsSync(file)) return undefined;
|
|
176
|
-
|
|
177
|
-
|
|
182
|
+
// 读取失败不能把 rejection 冒到 skill 工具:宿主在 agent/pre-step 里
|
|
183
|
+
// await skills.snapshot,一次 EACCES/EBUSY 会打断该 agent 的整个回合。
|
|
184
|
+
try {
|
|
185
|
+
if (statSync(file).size > MAX_BODY_BYTES) return undefined;
|
|
186
|
+
return { ...candidate, content: readFileSync(file, 'utf8') };
|
|
187
|
+
} catch {
|
|
188
|
+
return undefined;
|
|
189
|
+
}
|
|
178
190
|
},
|
|
179
191
|
};
|
|
180
192
|
}
|
|
@@ -182,5 +194,17 @@ export function createFileSkillProvider({ dshHome, projectCwd, bundledDir } = {}
|
|
|
182
194
|
export function installFileSkillProvider(skills, options) {
|
|
183
195
|
if (!skills || typeof skills.registerProvider !== 'function') return () => {};
|
|
184
196
|
const provider = createFileSkillProvider(options);
|
|
185
|
-
|
|
197
|
+
const control = skills.registerProvider(() => provider);
|
|
198
|
+
// registerProvider 可能返回 disposer,也可能返回 { dispose, invalidate } 的
|
|
199
|
+
// control:直接把它当函数调用会在 teardown 里抛错(provider 泄漏),且从不
|
|
200
|
+
// invalidate 会让技能目录一直停在注册时的快照。
|
|
201
|
+
if (typeof control === 'function') {
|
|
202
|
+
return () => {
|
|
203
|
+
try { control(); } catch { /* already disposed */ }
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
return () => {
|
|
207
|
+
try { control?.invalidate?.(); } catch { /* cache may be gone */ }
|
|
208
|
+
try { control?.dispose?.(); } catch { /* already disposed */ }
|
|
209
|
+
};
|
|
186
210
|
}
|
|
@@ -41,7 +41,7 @@ export function createAdoptGate(deps) {
|
|
|
41
41
|
if (typeof hasKeepRecord === 'function') {
|
|
42
42
|
let verified = false;
|
|
43
43
|
try {
|
|
44
|
-
verified = await hasKeepRecord({ projectDir, skillPath: pair.skillPath ?? null });
|
|
44
|
+
verified = await hasKeepRecord({ projectDir, skillPath: pair.skillPath ?? null, candidate: pair.after });
|
|
45
45
|
} catch (error) {
|
|
46
46
|
const message = `adopt gate: cannot read judge records (${error?.message ?? error})`;
|
|
47
47
|
diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
|