@suifei/dsh-ai-team 0.3.54 → 0.3.56
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 +32 -0
- package/client.js +289 -332
- package/index.js +181 -28
- package/lib/diaglog.js +105 -0
- package/lib/domain/member-profile.js +4 -11
- package/lib/domain/policy.js +31 -0
- package/lib/host/member-tools.js +1 -1
- package/lib/host/project-registry.js +6 -1
- package/lib/host/project-runtime.js +31 -3
- package/lib/host/service.js +173 -99
- package/lib/host/views.js +6 -16
- package/lib/ledger/fold.js +36 -8
- package/lib/ledger/writer.js +110 -9
- package/lib/runtime/failure-policy.js +19 -7
- package/lib/runtime/member-runtime.js +6 -1
- package/lib/runtime/skill-provider.js +96 -33
- package/lib/vendor/skillopt/src/index.js +51 -3
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +6 -1
package/lib/ledger/fold.js
CHANGED
|
@@ -31,9 +31,18 @@
|
|
|
31
31
|
*/
|
|
32
32
|
|
|
33
33
|
import { GENESIS_HASH, isPlainObject } from './events.js';
|
|
34
|
+
import { isReviewCandidate } from '../domain/policy.js';
|
|
34
35
|
|
|
35
36
|
/** 投影状态版本;改动折叠语义时必须递增(03 §6.4)。 */
|
|
36
|
-
export const FOLD_STATE_VERSION =
|
|
37
|
+
export const FOLD_STATE_VERSION = 2;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 投影封顶:大规模/长迭代账本下,stream 与每个 Thread 的 entries 不随事件数
|
|
41
|
+
* 无界增长(它们只是展示投影,完整历史在账本事件里,可按需重放)。
|
|
42
|
+
* headSeq/seq 单调计数不受影响,回复基线与去重仍然成立。
|
|
43
|
+
*/
|
|
44
|
+
export const STREAM_TAIL_LIMIT = 500;
|
|
45
|
+
export const THREAD_ENTRIES_LIMIT = 500;
|
|
37
46
|
|
|
38
47
|
export const TASK_STATUS = Object.freeze({
|
|
39
48
|
PENDING: 'pending',
|
|
@@ -84,6 +93,7 @@ function emptyState() {
|
|
|
84
93
|
threads: {},
|
|
85
94
|
inbox: {},
|
|
86
95
|
stream: [],
|
|
96
|
+
streamTotal: 0,
|
|
87
97
|
followers: {},
|
|
88
98
|
humanMemberId: null,
|
|
89
99
|
};
|
|
@@ -527,7 +537,13 @@ function applyThreadPosted(state, event, payload) {
|
|
|
527
537
|
eventId: event.id,
|
|
528
538
|
};
|
|
529
539
|
|
|
530
|
-
|
|
540
|
+
// Thread 条目 seq 单调递增(dedupe 已挡同 seq),直接追加;仅手工乱序回放
|
|
541
|
+
// 才回退到插入排序。entries 按 THREAD_ENTRIES_LIMIT 封顶,headSeq 仍单调。
|
|
542
|
+
const lastEntry = previous.entries[previous.entries.length - 1];
|
|
543
|
+
let entries = lastEntry !== undefined && lastEntry.seq > entrySeq
|
|
544
|
+
? [...previous.entries, entry].sort((left, right) => left.seq - right.seq)
|
|
545
|
+
: [...previous.entries, entry];
|
|
546
|
+
if (entries.length > THREAD_ENTRIES_LIMIT) entries = entries.slice(entries.length - THREAD_ENTRIES_LIMIT);
|
|
531
547
|
const headEntry = entries[entries.length - 1];
|
|
532
548
|
const headSeq = Math.max(previous.headSeq, entrySeq, headEntry.seq);
|
|
533
549
|
const thread = {
|
|
@@ -604,8 +620,16 @@ function applyStreamPosted(state, event, payload) {
|
|
|
604
620
|
parentEventId: stringOrNull(payload.parentEventId),
|
|
605
621
|
at: event.at,
|
|
606
622
|
};
|
|
607
|
-
|
|
608
|
-
|
|
623
|
+
// 事件按 seq 递增到达(applyEvent 已挡住 seq <= lastSeq),直接追加即可;
|
|
624
|
+
// 只有手工构造的乱序回放才需要插入排序,用末尾比较识别。投影按
|
|
625
|
+
// STREAM_TAIL_LIMIT 封顶:完整历史在账本里,可重放。
|
|
626
|
+
const last = state.stream[state.stream.length - 1];
|
|
627
|
+
let stream = last !== undefined && last.seq > event.seq
|
|
628
|
+
? [...state.stream, entry].sort((left, right) => left.seq - right.seq)
|
|
629
|
+
: [...state.stream, entry];
|
|
630
|
+
const streamTotal = (state.streamTotal ?? 0) + 1;
|
|
631
|
+
if (stream.length > STREAM_TAIL_LIMIT) stream = stream.slice(stream.length - STREAM_TAIL_LIMIT);
|
|
632
|
+
return advance(state, event, { stream, streamTotal });
|
|
609
633
|
}
|
|
610
634
|
|
|
611
635
|
function applyFollow(state, event, payload, following) {
|
|
@@ -698,6 +722,8 @@ export function applyEvent(state, event) {
|
|
|
698
722
|
const sessionId = textOr(payload.sessionId, null);
|
|
699
723
|
const member = memberId === null ? undefined : state.members[memberId];
|
|
700
724
|
if (member === undefined || sessionId === null) return advance(state, event);
|
|
725
|
+
// 投影防御:retired 成员不得被绑定事件复活,必须走 member.rejoin。
|
|
726
|
+
if (member.status === MEMBER_STATUS.RETIRED) return advance(state, event);
|
|
701
727
|
return advance(state, event, {
|
|
702
728
|
members: {
|
|
703
729
|
...state.members,
|
|
@@ -802,6 +828,8 @@ export function applyEvent(state, event) {
|
|
|
802
828
|
const memberId = textOr(payload.memberId, null);
|
|
803
829
|
const member = memberId === null ? undefined : state.members[memberId];
|
|
804
830
|
if (member === undefined) return advance(state, event);
|
|
831
|
+
// 投影防御:retired 成员的旧会话回报 completed 不算恢复。
|
|
832
|
+
if (member.status === MEMBER_STATUS.RETIRED) return advance(state, event);
|
|
805
833
|
return advance(state, event, {
|
|
806
834
|
members: {
|
|
807
835
|
...state.members,
|
|
@@ -820,6 +848,8 @@ export function applyEvent(state, event) {
|
|
|
820
848
|
const memberId = textOr(payload.memberId, null);
|
|
821
849
|
const member = memberId === null ? undefined : state.members[memberId];
|
|
822
850
|
if (member === undefined) return advance(state, event);
|
|
851
|
+
// 投影防御:重试退役成员必须走 member.rejoin(顺带清 talentPool)。
|
|
852
|
+
if (member.status === MEMBER_STATUS.RETIRED) return advance(state, event);
|
|
823
853
|
return advance(state, event, {
|
|
824
854
|
members: {
|
|
825
855
|
...state.members,
|
|
@@ -998,17 +1028,15 @@ export function isTaskBlocked(state, taskOrId) {
|
|
|
998
1028
|
|
|
999
1029
|
/**
|
|
1000
1030
|
* 验收资格纯函数(02 INV-04 / Q-05):
|
|
1001
|
-
* - Agent 必须未退役、不是当前 assignee、且从未 claim 过(历史谓词)。
|
|
1002
1031
|
* - Human 是唯一例外,可验收自己执行的 Task;二次确认由命令层负责。
|
|
1032
|
+
* - Agent 的资格判定统一走 policy.isReviewCandidate(与 views/Waker 同一实现)。
|
|
1003
1033
|
*/
|
|
1004
1034
|
export function isEligibleReviewer(state, taskId, memberId) {
|
|
1005
1035
|
const task = state.tasks[taskId];
|
|
1006
1036
|
const member = state.members[memberId];
|
|
1007
1037
|
if (!task || task.tombstone || !member) return false;
|
|
1008
1038
|
if (member.kind === 'human') return true;
|
|
1009
|
-
|
|
1010
|
-
if (task.assigneeId === memberId) return false;
|
|
1011
|
-
return !hasClaimed(task, memberId);
|
|
1039
|
+
return isReviewCandidate(member, task);
|
|
1012
1040
|
}
|
|
1013
1041
|
|
|
1014
1042
|
/** 状态里的 Task 是否处于已知状态值(供测试/诊断使用)。 */
|
package/lib/ledger/writer.js
CHANGED
|
@@ -29,7 +29,8 @@ import {
|
|
|
29
29
|
verifyChain,
|
|
30
30
|
verifyEvent,
|
|
31
31
|
} from './events.js';
|
|
32
|
-
import { applyEvent, fold, initialState } from './fold.js';
|
|
32
|
+
import { applyEvent, FOLD_STATE_VERSION, fold, initialState } from './fold.js';
|
|
33
|
+
import { loadCheckpoint, saveCheckpoint } from './checkpoint.js';
|
|
33
34
|
|
|
34
35
|
export { LedgerError };
|
|
35
36
|
|
|
@@ -403,7 +404,10 @@ export class LedgerWriter {
|
|
|
403
404
|
if (this._closed) throw new LedgerError('E_LEDGER_CLOSED', 'ledger is closed');
|
|
404
405
|
|
|
405
406
|
const plans = [];
|
|
406
|
-
|
|
407
|
+
// 批内查重只用临时小集合;全局查重直接查 _ids(O(1)),避免每次
|
|
408
|
+
// append 全量拷贝已存事件集合带来的平方级开销。
|
|
409
|
+
const seenIds = new Set();
|
|
410
|
+
const hasId = (id) => seenIds.has(id) || this._ids.has(id);
|
|
407
411
|
let seq = this._head.seq;
|
|
408
412
|
let prevHash = this._head.hash;
|
|
409
413
|
|
|
@@ -431,7 +435,7 @@ export class LedgerWriter {
|
|
|
431
435
|
|
|
432
436
|
const at = draft.at ?? this._clock();
|
|
433
437
|
const id = draft.id ?? newEventId(at);
|
|
434
|
-
if (
|
|
438
|
+
if (hasId(id)) {
|
|
435
439
|
throw new LedgerError('E_DUPLICATE_ID', 'event id already exists in this ledger', { id });
|
|
436
440
|
}
|
|
437
441
|
seenIds.add(id);
|
|
@@ -488,7 +492,13 @@ export class LedgerWriter {
|
|
|
488
492
|
(segCount > 0 &&
|
|
489
493
|
(segCount >= this.segmentEvents || segSize + plan.line.length > this.segmentBytes));
|
|
490
494
|
if (needRoll) {
|
|
491
|
-
if (segFd !== null)
|
|
495
|
+
if (segFd !== null) {
|
|
496
|
+
// 落盘后再关闭旧段:closeSync 不保证刷盘,若旧段尾部整行
|
|
497
|
+
// 只留在 OS 缓冲而崩溃丢失,新段首行的 prevHash/seq 将与
|
|
498
|
+
// 截断后的旧段尾对不上,哈希链断裂且无法修复。
|
|
499
|
+
if (this.fsync) this._fs.fsyncSync(segFd);
|
|
500
|
+
this._fs.closeSync(segFd);
|
|
501
|
+
}
|
|
492
502
|
// 段号 = 上一个已存在段的编号 + 1;全新账本的第一段仍是 000001。
|
|
493
503
|
const lastIndex =
|
|
494
504
|
created.length > 0
|
|
@@ -884,15 +894,86 @@ export class LedgerWriter {
|
|
|
884
894
|
export function openLedger(options = {}) {
|
|
885
895
|
const writer = new LedgerWriter(options);
|
|
886
896
|
const opened = writer.open();
|
|
887
|
-
|
|
888
|
-
|
|
897
|
+
// checkpoint 命中且账本与检查点齐平时,跳过全量 readAll(boot 的大头):
|
|
898
|
+
// state 直接取自检查点,events 惰性化(首次访问才读盘,append 只增新事件)。
|
|
899
|
+
// 尾部存在时才需要一次 readAll 来续放投影。
|
|
900
|
+
const checkpointOptions = options.checkpoint ?? null;
|
|
901
|
+
const checkpointDir = checkpointOptions?.dir ?? writer.dir;
|
|
902
|
+
const stateVersion = checkpointOptions?.stateVersion ?? FOLD_STATE_VERSION;
|
|
903
|
+
let state;
|
|
904
|
+
let recovery = null;
|
|
905
|
+
let events = null;
|
|
906
|
+
const ensureEvents = () => {
|
|
907
|
+
if (events === null) events = writer.readAll({ repairTail: false });
|
|
908
|
+
return events;
|
|
909
|
+
};
|
|
910
|
+
if (checkpointOptions) {
|
|
911
|
+
const loaded = loadCheckpoint(checkpointDir, {
|
|
912
|
+
stateVersion,
|
|
913
|
+
hashAt: (seq) => writer.hashAt(seq),
|
|
914
|
+
});
|
|
915
|
+
if (loaded.checkpoint && loaded.checkpoint.lastSeq === writer.head.seq) {
|
|
916
|
+
// 齐平:零尾放,账本事件列表不进内存。
|
|
917
|
+
state = loaded.checkpoint.state;
|
|
918
|
+
recovery = {
|
|
919
|
+
source: loaded.source,
|
|
920
|
+
fromSeq: loaded.checkpoint.lastSeq + 1,
|
|
921
|
+
tailReplayed: 0,
|
|
922
|
+
errors: loaded.errors,
|
|
923
|
+
};
|
|
924
|
+
} else {
|
|
925
|
+
const fromSeq = loaded.checkpoint ? loaded.checkpoint.lastSeq + 1 : 1;
|
|
926
|
+
state = loaded.checkpoint ? loaded.checkpoint.state : initialState();
|
|
927
|
+
const all = ensureEvents();
|
|
928
|
+
for (const event of all) {
|
|
929
|
+
if (event.seq >= fromSeq) Object.assign(state, applyEvent(state, event));
|
|
930
|
+
}
|
|
931
|
+
recovery = {
|
|
932
|
+
source: loaded.source ?? 'replay',
|
|
933
|
+
fromSeq,
|
|
934
|
+
tailReplayed: Math.max(0, writer.head.seq - fromSeq + 1),
|
|
935
|
+
errors: loaded.errors,
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
} else {
|
|
939
|
+
events = writer.readAll({ repairTail: false });
|
|
940
|
+
state = fold(events);
|
|
941
|
+
}
|
|
889
942
|
|
|
890
943
|
let onEvent = typeof options.onEvent === 'function' ? options.onEvent : null;
|
|
944
|
+
// 检查点节奏:boot 后落一次地板,之后每 saveEvery 次追加落一次,close
|
|
945
|
+
// 前必落——崩溃窗口最多丢 saveEvery 个事件的投影进度(账本本体无损)。
|
|
946
|
+
const saveEvery = Number.isSafeInteger(checkpointOptions?.saveEvery)
|
|
947
|
+
? Math.max(50, checkpointOptions.saveEvery)
|
|
948
|
+
: 500;
|
|
949
|
+
let eventsSinceCheckpoint = 0;
|
|
950
|
+
const saveCheckpointNow = () => {
|
|
951
|
+
if (!checkpointOptions) return null;
|
|
952
|
+
try {
|
|
953
|
+
return saveCheckpoint(
|
|
954
|
+
checkpointDir,
|
|
955
|
+
{ stateVersion, lastSeq: writer.head.seq, lastHash: writer.head.hash, state },
|
|
956
|
+
{ hashAt: (seq) => writer.hashAt(seq) },
|
|
957
|
+
);
|
|
958
|
+
} catch (error) {
|
|
959
|
+
// 检查点保存失败绝不影响追加,但必须可见:静默失败会让检查点
|
|
960
|
+
// 名存实亡(boot 退化为全量重放而无人知晓)。
|
|
961
|
+
console.warn(`[ai-team] ledger ${writer.projectId} checkpoint save failed:`, error?.message ?? error);
|
|
962
|
+
return { error: error.message ?? String(error) };
|
|
963
|
+
}
|
|
964
|
+
};
|
|
965
|
+
if (checkpointOptions) {
|
|
966
|
+
const saved = saveCheckpointNow();
|
|
967
|
+
recovery.saved = saved && !saved.error ? saved.path : (saved?.error ?? null);
|
|
968
|
+
}
|
|
891
969
|
const ledger = {
|
|
892
970
|
projectId: writer.projectId,
|
|
893
971
|
writer,
|
|
894
972
|
state,
|
|
895
|
-
|
|
973
|
+
/** 账本事件全列表(checkpoint 模式下惰性读盘,append 持续追加)。 */
|
|
974
|
+
get events() {
|
|
975
|
+
return ensureEvents();
|
|
976
|
+
},
|
|
896
977
|
opened,
|
|
897
978
|
get onEvent() {
|
|
898
979
|
return onEvent;
|
|
@@ -910,20 +991,28 @@ export function openLedger(options = {}) {
|
|
|
910
991
|
const event = await writer.append(draft);
|
|
911
992
|
// 只有 append 成功(含 fsync)后才推进内存状态。
|
|
912
993
|
Object.assign(state, applyEvent(state, event));
|
|
913
|
-
|
|
994
|
+
ensureEvents().push(event);
|
|
914
995
|
try {
|
|
915
996
|
onEvent?.(event);
|
|
916
997
|
} catch {
|
|
917
998
|
/* a projection listener must never break the append */
|
|
918
999
|
}
|
|
1000
|
+
if (checkpointOptions) {
|
|
1001
|
+
eventsSinceCheckpoint += 1;
|
|
1002
|
+
if (eventsSinceCheckpoint >= saveEvery) {
|
|
1003
|
+
eventsSinceCheckpoint = 0;
|
|
1004
|
+
saveCheckpointNow();
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
919
1007
|
return event;
|
|
920
1008
|
},
|
|
921
1009
|
async appendMany(drafts) {
|
|
922
1010
|
const appended = await writer.appendMany(drafts);
|
|
923
1011
|
let next = state;
|
|
1012
|
+
const list = ensureEvents();
|
|
924
1013
|
for (const event of appended) {
|
|
925
1014
|
next = applyEvent(next, event);
|
|
926
|
-
|
|
1015
|
+
list.push(event);
|
|
927
1016
|
}
|
|
928
1017
|
Object.assign(state, next);
|
|
929
1018
|
for (const event of appended) {
|
|
@@ -933,8 +1022,19 @@ export function openLedger(options = {}) {
|
|
|
933
1022
|
/* a projection listener must never break the append */
|
|
934
1023
|
}
|
|
935
1024
|
}
|
|
1025
|
+
if (checkpointOptions) {
|
|
1026
|
+
eventsSinceCheckpoint += appended.length;
|
|
1027
|
+
if (eventsSinceCheckpoint >= saveEvery) {
|
|
1028
|
+
eventsSinceCheckpoint = 0;
|
|
1029
|
+
saveCheckpointNow();
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
936
1032
|
return appended;
|
|
937
1033
|
},
|
|
1034
|
+
/** boot 时检查点恢复方式:'primary'/'backup'/'replay' 与尾放区间。 */
|
|
1035
|
+
get recovery() {
|
|
1036
|
+
return recovery;
|
|
1037
|
+
},
|
|
938
1038
|
readAll(readOptions = {}) {
|
|
939
1039
|
return writer.readAll(readOptions);
|
|
940
1040
|
},
|
|
@@ -975,6 +1075,7 @@ export function openLedger(options = {}) {
|
|
|
975
1075
|
return writer.repair();
|
|
976
1076
|
},
|
|
977
1077
|
close() {
|
|
1078
|
+
if (checkpointOptions) saveCheckpointNow();
|
|
978
1079
|
writer.close();
|
|
979
1080
|
},
|
|
980
1081
|
};
|
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* LLM failure classification and the deterministic retry/fallback decision.
|
|
3
3
|
*
|
|
4
|
-
* The
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* a
|
|
4
|
+
* The listener on `agent/request-error` owns the retry for transient
|
|
5
|
+
* server/network failures and re-dispatches the same request immediately
|
|
6
|
+
* (DSH's agent loop supports that via `{ kind: 'retry' }`). There are no
|
|
7
|
+
* timers: a fallback patch only rewrites the member's persisted config, so it
|
|
8
|
+
* takes effect on the next wake — the current turn ends (`fail`). Rate limits
|
|
9
|
+
* also end the turn: hammering the same route at once burns the retry budget
|
|
10
|
+
* without a backoff clock. Auth/billing/policy failures are fail-closed and
|
|
11
|
+
* require a Human or the Project owner to change the environment.
|
|
8
12
|
*/
|
|
9
13
|
|
|
10
14
|
export const FAILURE_CATEGORY = Object.freeze({
|
|
@@ -80,8 +84,10 @@ function fallbackAt(config, index) {
|
|
|
80
84
|
}
|
|
81
85
|
|
|
82
86
|
/**
|
|
83
|
-
* Decide what the
|
|
84
|
-
*
|
|
87
|
+
* Decide what the request-error listener does next. `retry` re-dispatches the
|
|
88
|
+
* same request immediately; `fallback` writes the config patch and ends the
|
|
89
|
+
* turn (it can only take effect on the next wake, because a step's route is
|
|
90
|
+
* captured before dispatch); `fail` ends the turn unchanged.
|
|
85
91
|
*/
|
|
86
92
|
export function retryDecision(failure, config = {}, attempt = 1) {
|
|
87
93
|
const maxAttempts = Number.isSafeInteger(config.retry?.maxAttempts)
|
|
@@ -105,7 +111,13 @@ export function retryDecision(failure, config = {}, attempt = 1) {
|
|
|
105
111
|
reason: `fallback to ${fallback.provider ?? config.provider}/${fallback.model ?? config.model}`,
|
|
106
112
|
};
|
|
107
113
|
}
|
|
108
|
-
|
|
114
|
+
// No fallback route configured: a rate limit would hit again at once
|
|
115
|
+
// without a backoff clock — end the turn and let the next event/startup
|
|
116
|
+
// try fresh instead of burning the budget on a throttled route.
|
|
117
|
+
if (failure.category === FAILURE_CATEGORY.RATE_LIMIT) {
|
|
118
|
+
return { action: 'fail', attempt, reason: 'rate limited; left to the next wake' };
|
|
119
|
+
}
|
|
120
|
+
return { action: 'retry', attempt, reason: 'same route, immediate retry' };
|
|
109
121
|
}
|
|
110
122
|
|
|
111
123
|
export function describeFailure(failure) {
|
|
@@ -98,6 +98,9 @@ export class MemberRuntime {
|
|
|
98
98
|
this.preset = options.preset ?? null;
|
|
99
99
|
this.agentPresets = options.agentPresets ?? null;
|
|
100
100
|
this.direct = options.direct === true;
|
|
101
|
+
// Cold resumes produce AgentHandles the caller does not store; the owner
|
|
102
|
+
// tracks them here so teardown can dispose every member activation.
|
|
103
|
+
this.trackHandle = typeof options.trackHandle === 'function' ? options.trackHandle : null;
|
|
101
104
|
this.clock = options.clock ?? (() => Date.now());
|
|
102
105
|
}
|
|
103
106
|
|
|
@@ -241,6 +244,7 @@ export class MemberRuntime {
|
|
|
241
244
|
setup: async (agentCtx) => { await this.agentPresets.mount(agentCtx, preset); },
|
|
242
245
|
} : {}),
|
|
243
246
|
});
|
|
247
|
+
this.trackHandle?.(handle);
|
|
244
248
|
agent = handle.agent;
|
|
245
249
|
} catch (error) {
|
|
246
250
|
fail('E_SESSION_MISSING', `member ${member.id} cannot be resumed: ${error?.message ?? error}`);
|
|
@@ -259,7 +263,8 @@ export class MemberRuntime {
|
|
|
259
263
|
// for a spawned subagent. Then the normal permission check applies.
|
|
260
264
|
if ((session === undefined || session === null) && this.agents?.resume !== undefined) {
|
|
261
265
|
try {
|
|
262
|
-
await this.agents.resume({ resumeSessionId: member.sessionId, parentAgent: this.parent });
|
|
266
|
+
const handle = await this.agents.resume({ resumeSessionId: member.sessionId, parentAgent: this.parent });
|
|
267
|
+
this.trackHandle?.(handle);
|
|
263
268
|
session = this.sessions?.get?.(member.sessionId);
|
|
264
269
|
} catch { /* fall through to sendMessage cold path */ }
|
|
265
270
|
}
|
|
@@ -3,6 +3,12 @@
|
|
|
3
3
|
* marketplace's user-skill scanner. It exposes `<dshHome>/skills` and project
|
|
4
4
|
* `.dsh/skills` / `.agents/skills` to the normal `skills` service, so members can
|
|
5
5
|
* load installed skills through their own `skill` tool.
|
|
6
|
+
*
|
|
7
|
+
* Discovery parity with @deepseek-ai/dsh-skill-filesystem (README L36-56):
|
|
8
|
+
* directory bundles `<name>/SKILL.md` and flat `<name>.md` files, required
|
|
9
|
+
* kebab-case `name` + `description`, loose-boolean `disable-model-invocation`
|
|
10
|
+
* / `user-invocable` keys, and the official rank order (project-dsh 100,
|
|
11
|
+
* project-agents 200, user-dsh 400, bundled 600; lower rank wins a name).
|
|
6
12
|
*/
|
|
7
13
|
|
|
8
14
|
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
|
@@ -11,6 +17,14 @@ import { isSkillExcluded } from './skill-policy.js';
|
|
|
11
17
|
|
|
12
18
|
const MAX_BODY_BYTES = 512 * 1024;
|
|
13
19
|
|
|
20
|
+
/** Official per-source ranks; a lower rank beats a higher one on name clash. */
|
|
21
|
+
const SOURCE_RANK = Object.freeze({
|
|
22
|
+
'project-dsh': 100,
|
|
23
|
+
'project-agents': 200,
|
|
24
|
+
'user-dsh': 400,
|
|
25
|
+
bundled: 600,
|
|
26
|
+
});
|
|
27
|
+
|
|
14
28
|
function parseFrontmatter(text) {
|
|
15
29
|
if (!text.startsWith('---')) return {};
|
|
16
30
|
const end = text.indexOf('\n---', 3);
|
|
@@ -39,6 +53,68 @@ function unquote(value) {
|
|
|
39
53
|
: text;
|
|
40
54
|
}
|
|
41
55
|
|
|
56
|
+
/**
|
|
57
|
+
* Official loose boolean syntax (skill-filesystem README L38): YAML booleans
|
|
58
|
+
* plus case-insensitive true/false, yes/no, on/off, 1/0. `null` marks a
|
|
59
|
+
* rejected spelling, which drops the whole skill instead of silently allowing
|
|
60
|
+
* an interface.
|
|
61
|
+
*/
|
|
62
|
+
function parseLooseBoolean(value) {
|
|
63
|
+
if (typeof value === 'boolean') return value;
|
|
64
|
+
const text = String(value ?? '').trim().toLowerCase();
|
|
65
|
+
if (['true', 'yes', 'on', '1'].includes(text)) return true;
|
|
66
|
+
if (['false', 'no', 'off', '0'].includes(text)) return false;
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Resolve one invocation flag; returns null when the skill must be dropped. */
|
|
71
|
+
function invocationFlag(fields, key, inverted) {
|
|
72
|
+
const raw = fields[key];
|
|
73
|
+
if (raw === undefined) return true;
|
|
74
|
+
const parsed = parseLooseBoolean(raw);
|
|
75
|
+
if (parsed === null) return null;
|
|
76
|
+
return inverted ? !parsed : parsed;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function scanCandidate(file, fallbackName, source) {
|
|
80
|
+
if (!existsSync(file)) return null;
|
|
81
|
+
let text;
|
|
82
|
+
try {
|
|
83
|
+
if (statSync(file).size > MAX_BODY_BYTES) return null;
|
|
84
|
+
text = readFileSync(file, 'utf8');
|
|
85
|
+
} catch {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
const fields = parseFrontmatter(text);
|
|
89
|
+
const name = unquote(fields.name) || fallbackName;
|
|
90
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) return null;
|
|
91
|
+
if (isSkillExcluded(name)) return null;
|
|
92
|
+
const description = unquote(fields.description);
|
|
93
|
+
// Official semantics: `description` is required; a skill without one is
|
|
94
|
+
// dropped with a warning rather than synthesized into the catalog.
|
|
95
|
+
if (description === '') {
|
|
96
|
+
console.warn(`[ai-team] skill "${name}" dropped: frontmatter description is required`);
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
const modelInvocable = invocationFlag(fields, 'disable-model-invocation', true);
|
|
100
|
+
const userInvocable = invocationFlag(fields, 'user-invocable', false);
|
|
101
|
+
if (modelInvocable === null || userInvocable === null) {
|
|
102
|
+
console.warn(`[ai-team] skill "${name}" dropped: "${modelInvocable === null ? 'disable-model-invocation' : 'user-invocable'}" is not a recognized boolean`);
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
name,
|
|
107
|
+
description,
|
|
108
|
+
whenToUse: unquote(fields.whenToUse) || unquote(fields['when-to-use']) || undefined,
|
|
109
|
+
invocation: { modelInvocable, userInvocable },
|
|
110
|
+
source,
|
|
111
|
+
provider: 'ai-team-files',
|
|
112
|
+
path: file,
|
|
113
|
+
locator: file,
|
|
114
|
+
rank: SOURCE_RANK[source] ?? 500,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
42
118
|
function scanRoot(root, source) {
|
|
43
119
|
const candidates = [];
|
|
44
120
|
if (!existsSync(root)) return candidates;
|
|
@@ -49,43 +125,30 @@ function scanRoot(root, source) {
|
|
|
49
125
|
return candidates;
|
|
50
126
|
}
|
|
51
127
|
for (const entry of entries) {
|
|
52
|
-
if (
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
try {
|
|
57
|
-
if (statSync(file).size > MAX_BODY_BYTES) continue;
|
|
58
|
-
text = readFileSync(file, 'utf8');
|
|
59
|
-
} catch {
|
|
128
|
+
if (entry.name.startsWith('.')) continue;
|
|
129
|
+
if (entry.isDirectory()) {
|
|
130
|
+
const found = scanCandidate(join(root, entry.name, 'SKILL.md'), entry.name, source);
|
|
131
|
+
if (found !== null) candidates.push(found);
|
|
60
132
|
continue;
|
|
61
133
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
candidates.push({
|
|
67
|
-
name,
|
|
68
|
-
description: unquote(fields.description) || `Skill ${name}`,
|
|
69
|
-
whenToUse: unquote(fields.whenToUse) || unquote(fields['when-to-use']) || undefined,
|
|
70
|
-
invocation: { modelInvocable: true, userInvocable: true },
|
|
71
|
-
source,
|
|
72
|
-
provider: 'ai-team-files',
|
|
73
|
-
path: file,
|
|
74
|
-
locator: file,
|
|
75
|
-
rank: 0,
|
|
76
|
-
});
|
|
134
|
+
if (entry.isFile() && entry.name.endsWith('.md')) {
|
|
135
|
+
const found = scanCandidate(join(root, entry.name), entry.name.replace(/\.md$/, ''), source);
|
|
136
|
+
if (found !== null) candidates.push(found);
|
|
137
|
+
}
|
|
77
138
|
}
|
|
78
139
|
return candidates;
|
|
79
140
|
}
|
|
80
141
|
|
|
81
142
|
export function createFileSkillProvider({ dshHome, projectCwd, bundledDir } = {}) {
|
|
143
|
+
// Bundled last: the official rank order puts disk roots above the packaged
|
|
144
|
+
// copy, so a user's own edit of a same-named skill wins (README L48-56).
|
|
82
145
|
const roots = [];
|
|
83
|
-
if (bundledDir) roots.push([join(bundledDir, 'skills'), 'bundled']);
|
|
84
|
-
if (dshHome) roots.push([join(dshHome, 'skills'), 'user-dsh']);
|
|
85
146
|
if (projectCwd) {
|
|
86
147
|
roots.push([join(projectCwd, '.dsh', 'skills'), 'project-dsh']);
|
|
87
148
|
roots.push([join(projectCwd, '.agents', 'skills'), 'project-agents']);
|
|
88
149
|
}
|
|
150
|
+
if (dshHome) roots.push([join(dshHome, 'skills'), 'user-dsh']);
|
|
151
|
+
if (bundledDir) roots.push([join(bundledDir, 'skills'), 'bundled']);
|
|
89
152
|
return {
|
|
90
153
|
name: 'ai-team-files',
|
|
91
154
|
async list(options = {}) {
|
|
@@ -95,16 +158,17 @@ export function createFileSkillProvider({ dshHome, projectCwd, bundledDir } = {}
|
|
|
95
158
|
[join(options.cwd, '.agents', 'skills'), 'project-agents'],
|
|
96
159
|
]
|
|
97
160
|
: [];
|
|
98
|
-
const seen = new Set();
|
|
99
161
|
const all = [];
|
|
100
162
|
for (const [root, source] of [...roots, ...extra]) {
|
|
101
|
-
|
|
102
|
-
if (seen.has(candidate.name)) continue;
|
|
103
|
-
seen.add(candidate.name);
|
|
104
|
-
all.push(candidate);
|
|
105
|
-
}
|
|
163
|
+
all.push(...scanRoot(root, source));
|
|
106
164
|
}
|
|
107
|
-
|
|
165
|
+
// Same-name clash: the lowest rank wins, mirroring the registry's
|
|
166
|
+
// rank → provider-order → local-order adjudication.
|
|
167
|
+
const byName = new Map();
|
|
168
|
+
for (const candidate of all.sort((left, right) => left.rank - right.rank)) {
|
|
169
|
+
if (!byName.has(candidate.name)) byName.set(candidate.name, candidate);
|
|
170
|
+
}
|
|
171
|
+
return [...byName.values()].sort((left, right) => left.name.localeCompare(right.name));
|
|
108
172
|
},
|
|
109
173
|
async get(candidate) {
|
|
110
174
|
const file = candidate?.locator;
|
|
@@ -120,4 +184,3 @@ export function installFileSkillProvider(skills, options) {
|
|
|
120
184
|
const provider = createFileSkillProvider(options);
|
|
121
185
|
return skills.registerProvider(() => provider);
|
|
122
186
|
}
|
|
123
|
-
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
const defineTool = (definition) => definition
|
|
10
10
|
import { dirname, join } from 'node:path'
|
|
11
11
|
import { fileURLToPath } from 'node:url'
|
|
12
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs'
|
|
12
13
|
|
|
13
14
|
export const name = 'skillopt'
|
|
14
15
|
|
|
@@ -17,7 +18,7 @@ export const name = 'skillopt'
|
|
|
17
18
|
const PLUGIN_DIR = dirname(fileURLToPath(import.meta.url)) + '/..'
|
|
18
19
|
|
|
19
20
|
// Exported for the canary test (scripts/canary.mjs).
|
|
20
|
-
export { buildArgv, quoteArgv, q, IS_WINDOWS }
|
|
21
|
+
export { buildArgv, quoteArgv, q, IS_WINDOWS, adoptGuardVerdict }
|
|
21
22
|
|
|
22
23
|
// Wait for the tool registry and the shell executor before applying.
|
|
23
24
|
export const inject = ['tools', 'shell']
|
|
@@ -147,8 +148,47 @@ function pick(obj, keys) {
|
|
|
147
148
|
return out
|
|
148
149
|
}
|
|
149
150
|
|
|
151
|
+
/**
|
|
152
|
+
* adopt 的 live-change 归因门(一手证据来自引擎 staging 布局:
|
|
153
|
+
* <project>/.skillopt-sleep/staging/<ts>/,.latest 指针 + manifest.json +
|
|
154
|
+
* diagnostics.json(cycle.py 每轮写入 `"backend": cfg.get("backend")`)。
|
|
155
|
+
* 返回 null 表示放行;返回字符串表示拒绝原因(fail-closed)。
|
|
156
|
+
*/
|
|
157
|
+
function adoptGuardVerdict(project) {
|
|
158
|
+
const root = join(project, '.skillopt-sleep', 'staging')
|
|
159
|
+
let latest = null
|
|
160
|
+
try {
|
|
161
|
+
latest = readFileSync(join(root, '.latest'), 'utf8').trim() || null
|
|
162
|
+
} catch { /* 无指针:退化为扫描 ts 目录 */ }
|
|
163
|
+
if (!latest) {
|
|
164
|
+
try {
|
|
165
|
+
latest = readdirSync(root)
|
|
166
|
+
.filter((n) => /^\d{8}-\d{6}(-\d+)?$/.test(n) && existsSync(join(root, n, 'manifest.json')))
|
|
167
|
+
.sort()
|
|
168
|
+
.at(-1) ?? null
|
|
169
|
+
} catch {
|
|
170
|
+
return 'refusing to adopt: no staged proposal found (run skillopt_run first)'
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (!latest) return 'refusing to adopt: no staged proposal found (run skillopt_run first)'
|
|
174
|
+
const stagedDir = join(root, latest)
|
|
175
|
+
let backend = null
|
|
176
|
+
try {
|
|
177
|
+
const diag = JSON.parse(readFileSync(join(stagedDir, 'diagnostics.json'), 'utf8'))
|
|
178
|
+
backend = typeof diag.backend === 'string' ? diag.backend : null
|
|
179
|
+
} catch {
|
|
180
|
+
return `refusing to adopt: cannot attribute this proposal to a validating backend (no readable diagnostics.json in ${stagedDir}). Re-run skillopt_run to stage a fresh, attributable proposal.`
|
|
181
|
+
}
|
|
182
|
+
if (backend === 'mock') {
|
|
183
|
+
return `refusing to adopt: this staged proposal was validated by the MOCK backend — no real model ran and its scores are synthetic. Run skillopt_run with a real backend (config skilloptBackend, or per-call backend) to produce a genuine gate result. Staged dir: ${stagedDir}`
|
|
184
|
+
}
|
|
185
|
+
if (!backend) {
|
|
186
|
+
return `refusing to adopt: diagnostics.json in ${stagedDir} does not name the validating backend. Re-run skillopt_run to stage a fresh, attributable proposal.`
|
|
187
|
+
}
|
|
188
|
+
return null
|
|
189
|
+
}
|
|
190
|
+
|
|
150
191
|
// Value-domain guard for model-supplied path-like strings.
|
|
151
|
-
//
|
|
152
192
|
// argv-level quoting (quoteArgv) protects the dsh `bash -c` boundary, but the
|
|
153
193
|
// engine re-interpolates these values into its OWN shell/command strings:
|
|
154
194
|
// scheduler.py builds `--project "{project}"` inside a crontab line and a
|
|
@@ -264,10 +304,12 @@ export function apply(ctx, config = {}) {
|
|
|
264
304
|
{
|
|
265
305
|
name: 'skillopt_adopt',
|
|
266
306
|
description:
|
|
267
|
-
'Apply the latest staged proposal, backing up existing target files first. This is the live-change boundary.',
|
|
307
|
+
'Apply the latest staged proposal, backing up existing target files first. This is the live-change boundary. Refuses proposals validated by the mock backend (scores are synthetic, no real model ran).',
|
|
268
308
|
parameters: {
|
|
269
309
|
project: { type: 'string', description: 'Project directory' },
|
|
270
310
|
},
|
|
311
|
+
// live-change boundary 前的一手证据门:拒绝时不发起引擎调用。
|
|
312
|
+
guard: (project) => adoptGuardVerdict(project),
|
|
271
313
|
build: (a) => buildArgv(config, 'adopt', pick(a, ['project']), [], ['project']),
|
|
272
314
|
},
|
|
273
315
|
{
|
|
@@ -339,6 +381,12 @@ export function apply(ctx, config = {}) {
|
|
|
339
381
|
} catch (err) {
|
|
340
382
|
return `[skillopt ${t.name}] ${err.message}`
|
|
341
383
|
}
|
|
384
|
+
// 工具自带的前置门(如 adopt 的 mock 验证归因检查):拒绝时不发起
|
|
385
|
+
// 引擎调用,直接返回拒绝原因。
|
|
386
|
+
if (typeof t.guard === 'function') {
|
|
387
|
+
const verdict = t.guard(a.project ?? config.project ?? process.cwd())
|
|
388
|
+
if (verdict) return `[skillopt ${t.name}] ${verdict}`
|
|
389
|
+
}
|
|
342
390
|
const argv = t.build(a)
|
|
343
391
|
// `command` must be the shell-quoted form for the platform executor;
|
|
344
392
|
// resolve() applies the executor's workdir/output-cap/sandbox defaults.
|
package/locale/en.json
ADDED