@suifei/dsh-ai-team 0.3.90 → 0.4.0
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/index.js +127 -55
- package/lib/skillopt/adopt-gate.js +20 -2
- package/lib/skillopt/job-runner.js +149 -0
- package/lib/skillopt/jobs.js +113 -0
- package/lib/skillopt/judge-runner.js +3 -18
- package/lib/skillopt/optimize-wiring.js +27 -13
- package/lib/skillopt/optimizer.js +7 -2
- package/lib/skillopt/subagent-text.js +101 -0
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -28,8 +28,10 @@ import { apply as applySkillOpt } from './lib/vendor/skillopt/src/index.js';
|
|
|
28
28
|
import { createAdoptGate, wrapToolsWithAdoptGate } from './lib/skillopt/adopt-gate.js';
|
|
29
29
|
import { formatRubric, scoreSkillRubric } from './lib/skillopt/rubric.js';
|
|
30
30
|
import { makeJudge, makeReadPair } from './lib/skillopt/gate-wiring.js';
|
|
31
|
-
import { runOptimizeLoop } from './lib/skillopt/optimizer.js';
|
|
32
|
-
import { makeGenerator, makeResultAppender, makeVcs } from './lib/skillopt/optimize-wiring.js';
|
|
31
|
+
import { runOptimizeLoop, weakestDimension } from './lib/skillopt/optimizer.js';
|
|
32
|
+
import { hasPairedKeepRecord, makeGenerator, makeResultAppender, makeVcs } from './lib/skillopt/optimize-wiring.js';
|
|
33
|
+
import { listJobs, readJob, writeJob } from './lib/skillopt/jobs.js';
|
|
34
|
+
import { reconcileJobs } from './lib/skillopt/job-runner.js';
|
|
33
35
|
import { createMemberPermissionGuard } from './lib/host/permission-guard.js';
|
|
34
36
|
import { installFaultAdapter } from './lib/host/fault-adapter.js';
|
|
35
37
|
import { buildModelCatalog } from './lib/host/model-catalog.js';
|
|
@@ -46,7 +48,7 @@ export const name = 'ai-team';
|
|
|
46
48
|
/** The workbench only makes sense where the Web carrier exists. */
|
|
47
49
|
export const inject = ['webServer', 'permissionPresets', 'sandboxPolicy', 'tools', 'shell'];
|
|
48
50
|
|
|
49
|
-
const VERSION = '0.
|
|
51
|
+
const VERSION = '0.4.0';
|
|
50
52
|
const HUMAN_ID = 'mem_human';
|
|
51
53
|
|
|
52
54
|
const SKILLOPT_BACKENDS = ['mock', 'claude', 'codex', 'copilot', 'cursor', 'pi', 'opencode', 'handoff', 'azure_openai'];
|
|
@@ -73,6 +75,28 @@ export const Config = z.object({
|
|
|
73
75
|
skilloptJudgeVotes: z.number().step(1).min(3).max(9).default(3),
|
|
74
76
|
});
|
|
75
77
|
|
|
78
|
+
/**
|
|
79
|
+
* 惰性 shell 服务代理:插件注入时机可能早于 shell 服务就绪,注册与 tick 都
|
|
80
|
+
* 必须在调用时现取,避免「boot 时未就绪 → 整条技能链静默跳过」。
|
|
81
|
+
*/
|
|
82
|
+
function lazyShellService(ctx) {
|
|
83
|
+
const get = () => {
|
|
84
|
+
const service = ctx.get('shell');
|
|
85
|
+
if (service === undefined || service === null) throw new Error('shell service is not available');
|
|
86
|
+
return service;
|
|
87
|
+
};
|
|
88
|
+
return {
|
|
89
|
+
resolve: (spec) => {
|
|
90
|
+
const service = get();
|
|
91
|
+
return typeof service.resolve === 'function' ? service.resolve(spec) : spec;
|
|
92
|
+
},
|
|
93
|
+
execute: async (spec) => {
|
|
94
|
+
const service = get();
|
|
95
|
+
return typeof service.execute === 'function' ? service.execute(spec) : service.run(spec);
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
76
100
|
function send(res, body, status = 200) {
|
|
77
101
|
if (res.writableEnded) return;
|
|
78
102
|
res.statusCode = status;
|
|
@@ -462,7 +486,7 @@ export function apply(ctx, config = {}) {
|
|
|
462
486
|
agentPresets: ctx.get('agentPresets'),
|
|
463
487
|
direct: false,
|
|
464
488
|
parent: parentInfo.agent,
|
|
465
|
-
provider:
|
|
489
|
+
provider: (ctx.get('subagents')?.list?.() ?? [])[0],
|
|
466
490
|
preset: 'standard',
|
|
467
491
|
cwd,
|
|
468
492
|
trackHandle: (sessionId, handle) => resumedHandles.set(sessionId, handle),
|
|
@@ -542,6 +566,33 @@ export function apply(ctx, config = {}) {
|
|
|
542
566
|
const state = projectRuntime.service.state;
|
|
543
567
|
const project = state.projects?.[projectRuntime.id];
|
|
544
568
|
if (project === undefined || project.pmoAuto === false || project.status === 'archived') return;
|
|
569
|
+
// 两阶段异步优化 job 收割:与任务派发无关,放在停止门之前——
|
|
570
|
+
// Human 启动的 job 必须在任意运行态下收敛(生成/评审/落盘)。
|
|
571
|
+
try {
|
|
572
|
+
const parentInfo = await ensureParent();
|
|
573
|
+
await reconcileJobs({
|
|
574
|
+
ctx,
|
|
575
|
+
projectDir: project.workspacePath || projectRuntime.dir,
|
|
576
|
+
deps: {
|
|
577
|
+
now: () => Date.now(),
|
|
578
|
+
provider: (ctx.get('subagents')?.list?.() ?? [])[0],
|
|
579
|
+
parent: parentInfo?.agent,
|
|
580
|
+
votes: config.skilloptJudgeVotes ?? 3,
|
|
581
|
+
startChild: async (label, spec) => {
|
|
582
|
+
const child = await subagents.startActivation({ ...spec, label });
|
|
583
|
+
return { childId: child.childId, outputStart: child.outputStart ?? null };
|
|
584
|
+
},
|
|
585
|
+
readText: (file) => readFileSync(file, 'utf8'),
|
|
586
|
+
writeText: (file, next) => writeFileSync(file, next, 'utf8'),
|
|
587
|
+
score: (value) => scoreSkillRubric(value, { measured: false }),
|
|
588
|
+
appendResult: makeResultAppender({ projectDir: project.workspacePath || projectRuntime.dir }),
|
|
589
|
+
vcs: await makeVcs({ shell: lazyShellService(ctx), projectDir: project.workspacePath || projectRuntime.dir }),
|
|
590
|
+
diag: (row) => diag.append(row),
|
|
591
|
+
},
|
|
592
|
+
});
|
|
593
|
+
} catch (error) {
|
|
594
|
+
diag.append({ ev: 'skillopt.job.tick.fail', message: error?.message ?? String(error) });
|
|
595
|
+
}
|
|
545
596
|
// P6 停止门:stopped 项目停止一切派发(补派/心跳/升级/continue 全停),
|
|
546
597
|
// 正在执行的回合自然完成;唤醒事件 hook 同样检查(见 wakeFromResult)。
|
|
547
598
|
if (project.runState === 'stopped') return;
|
|
@@ -753,34 +804,32 @@ export function apply(ctx, config = {}) {
|
|
|
753
804
|
const tools = ctx.get('tools');
|
|
754
805
|
let disposeSkillOpt = () => {};
|
|
755
806
|
try {
|
|
756
|
-
|
|
757
|
-
//
|
|
758
|
-
|
|
759
|
-
if (!tools?.register
|
|
760
|
-
diag.append({
|
|
761
|
-
|
|
762
|
-
hasToolsRegister: typeof tools?.register === 'function',
|
|
763
|
-
hasShell: Boolean(shell),
|
|
764
|
-
});
|
|
765
|
-
console.warn('[ai-team] SkillOpt tools not registered:', { hasToolsRegister: typeof tools?.register === 'function', hasShell: Boolean(shell) });
|
|
807
|
+
// shell 惰性代理:注入时机早于 shell 服务就绪时,注册仍必须完成——
|
|
808
|
+
// 每次调用现取,避免「boot 时 shell 未就绪 → 整条技能链静默跳过」。
|
|
809
|
+
const shellProxy = lazyShellService(ctx);
|
|
810
|
+
if (!tools?.register) {
|
|
811
|
+
diag.append({ ev: 'skillopt.skip.fail', hasToolsRegister: false, hasShell: Boolean(ctx.get('shell')) });
|
|
812
|
+
console.warn('[ai-team] SkillOpt tools not registered: no tool registry');
|
|
766
813
|
}
|
|
767
|
-
if (tools?.register
|
|
814
|
+
if (tools?.register) {
|
|
768
815
|
// Darwin validation gate(对齐 darwin-skill v2.1):adopt 之前必须
|
|
769
816
|
// 通过 paired 独立 judge 的多数决;绝对 rubric 分只做 triage。
|
|
770
817
|
const engineScript = fileURLToPath(new URL('./lib/vendor/skillopt/scripts/sleep.py', import.meta.url));
|
|
771
|
-
const readPair = makeReadPair({ shell, engineScript, diag });
|
|
818
|
+
const readPair = makeReadPair({ shell: shellProxy, engineScript, diag });
|
|
772
819
|
const judge = makeJudge({
|
|
773
820
|
subagents: ctx.get('subagents'),
|
|
774
821
|
// 惰性解析:ensureParent 在 apply 之后才定义(const TDZ),
|
|
775
822
|
// judge 只在 adopt 时调用,此处不能立即取值。
|
|
776
823
|
ensureParent: () => ensureParent(),
|
|
777
|
-
providerName: () =>
|
|
824
|
+
providerName: () => (ctx.get('subagents')?.list?.() ?? [])[0],
|
|
778
825
|
votes: config.skilloptJudgeVotes ?? 3,
|
|
779
826
|
diag,
|
|
780
827
|
});
|
|
781
828
|
const adoptGate = createAdoptGate({
|
|
782
829
|
readPair,
|
|
783
|
-
|
|
830
|
+
// 两阶段异步模式:工具 execute 内无法等待子代理,判据改为
|
|
831
|
+
// results.tsv 中该 skill 已存在 paired keep 记录(同步可查)。
|
|
832
|
+
hasKeepRecord: async ({ projectDir, skillPath }) => hasPairedKeepRecord(projectDir, skillPath),
|
|
784
833
|
diag: (line, extra) => diag.append({
|
|
785
834
|
ev: extra?.ev ?? 'skillopt.adoptgate',
|
|
786
835
|
message: line,
|
|
@@ -791,7 +840,7 @@ export function apply(ctx, config = {}) {
|
|
|
791
840
|
// operator can move the skillopt_* tools off the safe mock default.
|
|
792
841
|
disposeSkillOpt = applySkillOpt({
|
|
793
842
|
tools: wrapToolsWithAdoptGate(tools, adoptGate),
|
|
794
|
-
shell,
|
|
843
|
+
shell: shellProxy,
|
|
795
844
|
logger: console,
|
|
796
845
|
}, {
|
|
797
846
|
backend: config.skilloptBackend ?? 'mock',
|
|
@@ -855,56 +904,79 @@ export function apply(ctx, config = {}) {
|
|
|
855
904
|
});
|
|
856
905
|
// Darwin Phase 2:自动 hill-climbing(诊断→生成→写入→judge→keep/revert)。
|
|
857
906
|
// 同一轮只改一个维度,版本化走干净 git 仓库,否则 .bak 备份。
|
|
907
|
+
// 两阶段异步:工具只启动生成子代理并写 job,收割由 PMO tick 完成
|
|
908
|
+
// (工具 execute 内无法同步等待一次性子代理——实测 result 永不 settle)。
|
|
858
909
|
const optimizeTool = tools.register({
|
|
859
910
|
name: 'skillopt_optimize',
|
|
860
|
-
description: '
|
|
911
|
+
description: 'Start a Darwin hill-climbing job for one SKILL.md (diagnose, generate candidate, paired judge, keep/revert). The PMO tick harvests it; poll skillopt_jobs for the outcome.',
|
|
861
912
|
parameters: {
|
|
862
913
|
project: { type: 'string', description: 'Project directory' },
|
|
863
914
|
skillPath: { type: 'string', description: 'Path to SKILL.md to optimize' },
|
|
864
|
-
rounds: { type: 'number', description: 'Max rounds (default 3)' },
|
|
865
915
|
},
|
|
866
916
|
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
|
|
867
917
|
async execute(args) {
|
|
868
918
|
const project = typeof args?.project === 'string' && args.project !== '' ? args.project : process.cwd();
|
|
869
919
|
const skillPath = typeof args?.skillPath === 'string' && args.skillPath !== '' ? args.skillPath : join(project, 'SKILL.md');
|
|
870
920
|
if (!existsSync(skillPath)) return `[skillopt optimize] SKILL.md not found: ${skillPath}`;
|
|
871
|
-
const
|
|
872
|
-
const
|
|
873
|
-
const
|
|
921
|
+
const text0 = readFileSync(skillPath, 'utf8');
|
|
922
|
+
const rubric = scoreSkillRubric(text0, { measured: false });
|
|
923
|
+
const dimension = weakestDimension(rubric);
|
|
924
|
+
if (dimension === null) return '[skillopt optimize] rubric produced no scorable dimension';
|
|
925
|
+
const parentInfo = await ensureParent();
|
|
926
|
+
const generator = makeGenerator({
|
|
927
|
+
subagents: ctx.get('subagents'),
|
|
928
|
+
ensureParent: () => ensureParent(),
|
|
929
|
+
providerName: () => (ctx.get('subagents')?.list?.() ?? [])[0],
|
|
930
|
+
cwd: project,
|
|
931
|
+
diag,
|
|
932
|
+
});
|
|
933
|
+
const jobId = 'job_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
|
|
934
|
+
const child = await generator.start({
|
|
874
935
|
skillPath,
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
votes: config.skilloptJudgeVotes ?? 3,
|
|
891
|
-
diag,
|
|
892
|
-
});
|
|
893
|
-
return judge({ before, after, projectDir: project });
|
|
894
|
-
},
|
|
895
|
-
vcs,
|
|
896
|
-
appendResult: makeResultAppender({ projectDir: project }),
|
|
936
|
+
before: text0,
|
|
937
|
+
dimension,
|
|
938
|
+
round: 1,
|
|
939
|
+
});
|
|
940
|
+
writeJob(project, {
|
|
941
|
+
id: jobId,
|
|
942
|
+
state: 'generating',
|
|
943
|
+
project,
|
|
944
|
+
skillPath,
|
|
945
|
+
skillName: skillPath.split(/[\\/]/).slice(-2, -1)[0] ?? skillPath,
|
|
946
|
+
dimension: `dim${dimension.id}` + ' ' + dimension.name,
|
|
947
|
+
generatorChildId: child.childId,
|
|
948
|
+
outputStart: child.outputStart ?? null,
|
|
949
|
+
parentId: parentInfo?.agent?.id ?? null,
|
|
950
|
+
createdAt: Date.now(),
|
|
897
951
|
});
|
|
898
|
-
diag.append({ ev: 'skillopt.
|
|
899
|
-
|
|
900
|
-
`[skillopt optimize]
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
].
|
|
904
|
-
return lines.join('\n');
|
|
952
|
+
diag.append({ ev: 'skillopt.job.started', jobId, project, skillPath, dimension: `dim${dimension.id}`, generatorChildId: child.childId });
|
|
953
|
+
return [
|
|
954
|
+
`[skillopt optimize] started job=${jobId} target=dim${dimension.id} ${dimension.name} baseline=${rubric.total}` ,
|
|
955
|
+
' two-phase async: the PMO tick harvests generator -> judges -> keep/revert and appends results.tsv',
|
|
956
|
+
' poll with skillopt_jobs',
|
|
957
|
+
].join('\n');
|
|
905
958
|
},
|
|
906
959
|
});
|
|
907
|
-
|
|
960
|
+
const jobsTool = tools.register({
|
|
961
|
+
name: 'skillopt_jobs',
|
|
962
|
+
description: 'List optimize jobs (state, target dimension, verdict) for a project.',
|
|
963
|
+
parameters: { project: { type: 'string', description: 'Project directory' } },
|
|
964
|
+
output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
|
|
965
|
+
async execute(args) {
|
|
966
|
+
const project = typeof args?.project === 'string' && args.project !== '' ? args.project : process.cwd();
|
|
967
|
+
const jobs = listJobs(project);
|
|
968
|
+
if (jobs.length === 0) return '[skillopt jobs] none';
|
|
969
|
+
return ['[skillopt jobs]', ...jobs.map((job) => ` ${job.id} ${job.state} ${job.dimension ?? '-'}${job.decision ? ` verdict=${job.decision.verdict} (${job.decision.better}-${job.decision.worse})` : ''}${job.error ? ` error=${job.error}` : ''}`)].join('\n');
|
|
970
|
+
},
|
|
971
|
+
});
|
|
972
|
+
const disposeExtra = () => {
|
|
973
|
+
try { disposeSkillOpt?.(); } catch { /* already disposed */ }
|
|
974
|
+
try { rubricTool?.(); } catch { /* noop */ }
|
|
975
|
+
try { judgeTool?.(); } catch { /* noop */ }
|
|
976
|
+
try { optimizeTool?.(); } catch { /* noop */ }
|
|
977
|
+
try { jobsTool?.(); } catch { /* noop */ }
|
|
978
|
+
};
|
|
979
|
+
disposeSkillOpt = disposeExtra;
|
|
908
980
|
diag.append({ ev: 'skillopt.registered', backend: config.skilloptBackend ?? 'mock', timeoutMs: config.skilloptTimeoutMs ?? 120_000, adoptGate: true, judgeVotes: config.skilloptJudgeVotes ?? 3, optimize: true });
|
|
909
981
|
}
|
|
910
982
|
} catch (error) {
|
|
@@ -1037,7 +1109,7 @@ export function apply(ctx, config = {}) {
|
|
|
1037
1109
|
agentPresets: ctx.get('agentPresets'),
|
|
1038
1110
|
direct: false,
|
|
1039
1111
|
parent: parentInfo.agent,
|
|
1040
|
-
provider:
|
|
1112
|
+
provider: (ctx.get('subagents')?.list?.() ?? [])[0],
|
|
1041
1113
|
preset: 'standard',
|
|
1042
1114
|
cwd: effectiveDir,
|
|
1043
1115
|
trackHandle: (sessionId, handle) => resumedHandles.set(sessionId, handle),
|
|
@@ -12,12 +12,15 @@
|
|
|
12
12
|
/**
|
|
13
13
|
* @param {object} deps
|
|
14
14
|
* @param {(projectDir: string) => Promise<{before: string|null, after: string|null, skillPath: string|null}>} deps.readPair
|
|
15
|
-
* @param {(input: object) => Promise<{verdict:string, better:number, worse:number, ties:number, valid:number, votes:Array, errors:string[]}>} deps.judge
|
|
15
|
+
* @param {(input: object) => Promise<{verdict:string, better:number, worse:number, ties:number, valid:number, votes:Array, errors:string[]}>} [deps.judge]
|
|
16
|
+
* 同步不可行时(工具 execute 内无法等待子代理)改用 deps.hasKeepRecord。
|
|
17
|
+
* @param {(input:{projectDir:string, skillPath:string|null}) => Promise<boolean>|boolean} [deps.hasKeepRecord]
|
|
18
|
+
* 两阶段异步模式的同步判据:results.tsv 中存在该 skill 的 paired keep 记录。
|
|
16
19
|
* @param {(line: string, extra?: object) => void} [deps.diag]
|
|
17
20
|
* @returns {(args: object, exec?: object) => Promise<string|null>} 返回拒绝原因;null = 放行
|
|
18
21
|
*/
|
|
19
22
|
export function createAdoptGate(deps) {
|
|
20
|
-
const { readPair, judge, diag } = deps;
|
|
23
|
+
const { readPair, judge, hasKeepRecord, diag } = deps;
|
|
21
24
|
return async (args) => {
|
|
22
25
|
const projectDir = typeof args?.project === 'string' && args.project.trim() !== '' ? args.project : null;
|
|
23
26
|
if (projectDir === null) return 'adopt gate: project directory is required';
|
|
@@ -34,6 +37,21 @@ export function createAdoptGate(deps) {
|
|
|
34
37
|
diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
|
|
35
38
|
return message;
|
|
36
39
|
}
|
|
40
|
+
// 两阶段异步模式:判据来自已落盘的 paired keep 记录(同步可查)。
|
|
41
|
+
if (typeof hasKeepRecord === 'function') {
|
|
42
|
+
let verified = false;
|
|
43
|
+
try {
|
|
44
|
+
verified = await hasKeepRecord({ projectDir, skillPath: pair.skillPath ?? null });
|
|
45
|
+
} catch (error) {
|
|
46
|
+
const message = `adopt gate: cannot read judge records (${error?.message ?? error})`;
|
|
47
|
+
diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
|
|
48
|
+
return message;
|
|
49
|
+
}
|
|
50
|
+
diag?.('skillopt.adoptgate.decision', { ev: 'skillopt.adoptgate', project: projectDir, source: 'paired-keep-record', verified });
|
|
51
|
+
if (verified) return null;
|
|
52
|
+
return 'adopt gate: no paired keep record for this skill — run the optimize loop to a keep first (unverified adopt is refused)';
|
|
53
|
+
}
|
|
54
|
+
if (typeof judge !== 'function') return 'adopt gate: no verification source configured (unverified adopt is refused)';
|
|
37
55
|
let result;
|
|
38
56
|
try {
|
|
39
57
|
result = await judge({ before: pair.before, after: pair.after, projectDir, skillPath: pair.skillPath ?? null });
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 优化 job 的宿主侧收割:每个 PMO tick 调用一次,把状态机的一步动作落到
|
|
3
|
+
* 真实文件/子代理/结果记录上。
|
|
4
|
+
*
|
|
5
|
+
* 与 jobs.js(纯逻辑)分离;本模块只做注入式 I/O,因此测试可用内存实现。
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { extractAssistantText } from './subagent-text.js';
|
|
9
|
+
import { isChildSettled, planJobStep, readJob, writeJob, listJobs } from './jobs.js';
|
|
10
|
+
import { decideByMajority, normalizeVoteCount, parseJudgeOutput, buildPairPrompt, voteFromParsed } from './judge.js';
|
|
11
|
+
import { validateCandidate } from './optimizer.js';
|
|
12
|
+
|
|
13
|
+
/** 观测一个在飞子代理:状态 + 会话事件(同步,供状态机使用)。 */
|
|
14
|
+
export function observeChild(ctx, childId, outputStart) {
|
|
15
|
+
const agent = ctx.get('agents')?.get?.(childId);
|
|
16
|
+
if (agent === undefined || agent === null) return { status: null, events: [] };
|
|
17
|
+
let events = [];
|
|
18
|
+
try {
|
|
19
|
+
events = agent.session?.snapshotEvents?.(outputStart) ?? [];
|
|
20
|
+
} catch { /* session may be gone */ }
|
|
21
|
+
return { status: agent.status ?? null, events, text: extractAssistantText(events) };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 推进一个 job 一步。
|
|
26
|
+
*
|
|
27
|
+
* @param {object} input
|
|
28
|
+
* @param {object} input.ctx DSH context
|
|
29
|
+
* @param {string} input.projectDir
|
|
30
|
+
* @param {object} input.job job 记录
|
|
31
|
+
* @param {object} input.deps
|
|
32
|
+
* @param {(name:string, spec:object)=>Promise<object>} input.deps.startChild 启动子代理(返回 {childId})
|
|
33
|
+
* @param {(path:string, text:string)=>void} input.deps.writeText
|
|
34
|
+
* @param {(path:string)=>string} input.deps.readText
|
|
35
|
+
* @param {object} input.deps.vcs makeVcs 结果
|
|
36
|
+
* @param {(line:string)=>Promise<void>} input.deps.appendResult
|
|
37
|
+
* @param {(text:string)=>object} input.deps.score
|
|
38
|
+
* @param {() => number} input.deps.now
|
|
39
|
+
* @param {string} input.deps.provider
|
|
40
|
+
* @param {object} input.deps.parent
|
|
41
|
+
* @param {number} [input.deps.votes]
|
|
42
|
+
* @param {(row:object)=>void} [input.deps.diag]
|
|
43
|
+
* @returns {Promise<{job:object, changed:boolean}>}
|
|
44
|
+
*/
|
|
45
|
+
export async function stepJob(input) {
|
|
46
|
+
const { ctx, projectDir, deps } = input;
|
|
47
|
+
let job = input.job;
|
|
48
|
+
const children = {};
|
|
49
|
+
for (const childId of [job.generatorChildId, ...(job.judgeChildIds ?? [])].filter(Boolean)) {
|
|
50
|
+
children[childId] = observeChild(ctx, childId, job.outputStart);
|
|
51
|
+
}
|
|
52
|
+
const plan = planJobStep(job, { children, now: deps.now() });
|
|
53
|
+
if (plan.next === job.state && plan.actions.every((action) => action.type === 'await')) {
|
|
54
|
+
return { job, changed: false };
|
|
55
|
+
}
|
|
56
|
+
for (const action of plan.actions) {
|
|
57
|
+
if (action.type === 'fail') {
|
|
58
|
+
await rollback({ deps, job, projectDir });
|
|
59
|
+
job = { ...job, state: 'failed', error: action.payload?.reason ?? 'failed', updatedAt: deps.now() };
|
|
60
|
+
deps.diag?.({ ev: 'skillopt.job.fail', jobId: job.id, reason: job.error });
|
|
61
|
+
} else if (action.type === 'apply-candidate') {
|
|
62
|
+
// 备份基线 → 写入候选 → 校验(超限时回滚)。
|
|
63
|
+
const before = deps.readText(job.skillPath);
|
|
64
|
+
const validation = validateCandidate({ before, after: action.payload?.text ?? '' });
|
|
65
|
+
if (!validation.ok) {
|
|
66
|
+
await rollback({ deps, job, projectDir });
|
|
67
|
+
job = { ...job, state: 'failed', error: validation.reason, updatedAt: deps.now() };
|
|
68
|
+
deps.diag?.({ ev: 'skillopt.job.fail', jobId: job.id, reason: validation.reason });
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
job = { ...job, before, candidate: action.payload.text, backup: await deps.vcs.backup(job.skillPath, before) };
|
|
72
|
+
deps.writeText(job.skillPath, action.payload.text);
|
|
73
|
+
} else if (action.type === 'start-judges') {
|
|
74
|
+
const votes = normalizeVoteCount(deps.votes ?? 3);
|
|
75
|
+
const judgeChildIds = [];
|
|
76
|
+
const judgeOrders = [];
|
|
77
|
+
for (let index = 0; index < votes; index++) {
|
|
78
|
+
const order = Math.random() < 0.5 ? 'ab' : 'ba';
|
|
79
|
+
const { prompt } = buildPairPrompt({ before: job.before, after: job.candidate, order });
|
|
80
|
+
const child = await deps.startChild(`skillopt-judge-${job.id}-${index + 1}`, {
|
|
81
|
+
provider: deps.provider,
|
|
82
|
+
request: {
|
|
83
|
+
cwd: projectDir,
|
|
84
|
+
prompt: [{ type: 'text', text: prompt }],
|
|
85
|
+
parent: deps.parent,
|
|
86
|
+
},
|
|
87
|
+
delivery: 'parent',
|
|
88
|
+
signal: new AbortController().signal,
|
|
89
|
+
});
|
|
90
|
+
judgeChildIds.push(child.childId);
|
|
91
|
+
judgeOrders.push({ childId: child.childId, order });
|
|
92
|
+
}
|
|
93
|
+
job = { ...job, state: 'judging', judgeChildIds, judgeOrders, updatedAt: deps.now() };
|
|
94
|
+
} else if (action.type === 'finish') {
|
|
95
|
+
const votes = [];
|
|
96
|
+
for (const row of action.payload?.votes ?? []) {
|
|
97
|
+
const mapping = (job.judgeOrders ?? []).find((entry) => entry.childId === row.childId);
|
|
98
|
+
const parsed = parseJudgeOutput(row.text);
|
|
99
|
+
const vote = voteFromParsed(parsed === null ? null : { ...parsed, aIsAfter: mapping?.order === 'ba' });
|
|
100
|
+
votes.push({ childId: row.childId, vote, margin: parsed?.margin ?? null, reason: parsed?.reason ?? '' });
|
|
101
|
+
}
|
|
102
|
+
const decision = decideByMajority(votes.map((entry) => entry.vote));
|
|
103
|
+
const kept = decision.verdict === 'keep';
|
|
104
|
+
if (!kept) await rollback({ deps, job, projectDir });
|
|
105
|
+
job = { ...job, state: 'done', decision: { ...decision, votes, kept }, updatedAt: deps.now() };
|
|
106
|
+
const afterText = kept ? job.candidate : job.before;
|
|
107
|
+
const beforeScore = deps.score(job.before)?.total ?? null;
|
|
108
|
+
const afterScore = deps.score(afterText)?.total ?? null;
|
|
109
|
+
await deps.appendResult([
|
|
110
|
+
new Date(deps.now()).toISOString().slice(0, 19),
|
|
111
|
+
deps.vcs.kind === 'git' ? (job.commit ?? '-') : '-',
|
|
112
|
+
job.skillName,
|
|
113
|
+
String(beforeScore ?? '-'),
|
|
114
|
+
String(afterScore ?? '-'),
|
|
115
|
+
kept ? 'keep' : 'revert',
|
|
116
|
+
job.dimension ?? '-',
|
|
117
|
+
`${decision.better}-${decision.worse} ${decision.verdict}`,
|
|
118
|
+
'paired',
|
|
119
|
+
].join('\t'));
|
|
120
|
+
deps.diag?.({ ev: 'skillopt.job.done', jobId: job.id, verdict: decision.verdict, better: decision.better, worse: decision.worse, kept });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (plan.next !== job.state && plan.next !== 'failed') job = { ...job, state: plan.next, updatedAt: deps.now() };
|
|
124
|
+
writeJob(projectDir, job);
|
|
125
|
+
return { job, changed: true };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function rollback({ deps, job, projectDir }) {
|
|
129
|
+
if (job?.candidate === undefined || job?.before === undefined) return;
|
|
130
|
+
try {
|
|
131
|
+
if (deps.vcs.kind === 'file' && typeof job.backup === 'string') {
|
|
132
|
+
await deps.vcs.restore(job.skillPath, job.backup);
|
|
133
|
+
} else {
|
|
134
|
+
deps.writeText(job.skillPath, job.before);
|
|
135
|
+
}
|
|
136
|
+
} catch { /* best effort */ }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 收割全部 pending job(tick 入口)。 */
|
|
140
|
+
export async function reconcileJobs(input) {
|
|
141
|
+
const jobs = listJobs(input.projectDir).filter((job) => job.state === 'generating' || job.state === 'judging');
|
|
142
|
+
const results = [];
|
|
143
|
+
for (const job of jobs) {
|
|
144
|
+
results.push(await stepJob({ ...input, job }));
|
|
145
|
+
}
|
|
146
|
+
return results;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export { isChildSettled, readJob, writeJob };
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 两阶段异步优化 job(tick 驱动状态机)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么必须两阶段:插件工具**无法在 execute 内同步等待一次性子代理**——
|
|
5
|
+
* `activation.result` 由宿主在子代理回合完成时 resolve,而工具执行本身就在
|
|
6
|
+
* 一个回合内(实测等待 121s 超时、输出为空)。因此:
|
|
7
|
+
*
|
|
8
|
+
* 阶段 1(工具调用):启动生成子代理,写 job 文件,立即返回 started;
|
|
9
|
+
* 阶段 2(PMO tick):每轮检查在飞子代理是否完成 → 取输出 → 校验候选 →
|
|
10
|
+
* 写文件 → 启动 judge 组 → judge 完成 → 多数决 → keep/revert → results.tsv。
|
|
11
|
+
*
|
|
12
|
+
* job 状态:`generating` → `judging` → `done` | `failed`。
|
|
13
|
+
* 全部为纯逻辑 + 注入式 I/O,便于在测试里用内存文件系统驱动任意 tick 序列。
|
|
14
|
+
*/
|
|
15
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
|
|
18
|
+
export const JOB_STATES = Object.freeze(['generating', 'judging', 'done', 'failed']);
|
|
19
|
+
const JOB_TTL_MS = 30 * 60 * 1000;
|
|
20
|
+
|
|
21
|
+
/** job 目录(项目内,随 .skillopt-sleep 一起被忽略/清理)。 */
|
|
22
|
+
export function jobsDir(projectDir) {
|
|
23
|
+
return join(projectDir, '.skillopt-sleep', 'jobs');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 读取一个 job 文件(损坏视为不存在)。 */
|
|
27
|
+
export function readJob(projectDir, jobId) {
|
|
28
|
+
try {
|
|
29
|
+
return JSON.parse(readFileSync(join(jobsDir(projectDir), `${jobId}.json`), 'utf8'));
|
|
30
|
+
} catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 列出全部 job(按创建时间升序)。 */
|
|
36
|
+
export function listJobs(projectDir) {
|
|
37
|
+
const dir = jobsDir(projectDir);
|
|
38
|
+
if (!existsSync(dir)) return [];
|
|
39
|
+
const jobs = [];
|
|
40
|
+
for (const name of readdirSync(dir)) {
|
|
41
|
+
if (!name.endsWith('.json')) continue;
|
|
42
|
+
try {
|
|
43
|
+
jobs.push(JSON.parse(readFileSync(join(dir, name), 'utf8')));
|
|
44
|
+
} catch { /* skip corrupt */ }
|
|
45
|
+
}
|
|
46
|
+
return jobs.sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 写入 job(原子性靠单写者约定;插件 tick 单线程)。 */
|
|
50
|
+
export function writeJob(projectDir, job) {
|
|
51
|
+
const dir = jobsDir(projectDir);
|
|
52
|
+
mkdirSync(dir, { recursive: true });
|
|
53
|
+
writeFileSync(join(dir, `${job.id}.json`), JSON.stringify(job, null, 2), 'utf8');
|
|
54
|
+
return job;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 删除 job 文件(done/failed 的收尾清理)。 */
|
|
58
|
+
export function removeJob(projectDir, jobId) {
|
|
59
|
+
try { unlinkSync(join(jobsDir(projectDir), `${jobId}.json`)); } catch { /* already gone */ }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 判定在飞子代理是否已完成。
|
|
64
|
+
* @param {{status?: string, events?: Array}} observation 宿主观测(agent.status + 会话事件)
|
|
65
|
+
* @returns {boolean}
|
|
66
|
+
*/
|
|
67
|
+
export function isChildSettled(observation) {
|
|
68
|
+
const events = Array.isArray(observation?.events) ? observation.events : [];
|
|
69
|
+
if (events.some((event) => event?.type === 'subagent/end' || event?.type === 'session/end')) return true;
|
|
70
|
+
// 一次性子代理完成后 agent 回到 idle;无 agent(已释放)同样视为结束。
|
|
71
|
+
return observation?.status === 'idle' || observation?.status === null || observation?.status === undefined && events.length > 0;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** job 是否超时(TTL)。 */
|
|
75
|
+
export function isJobExpired(job, nowMs, ttlMs = JOB_TTL_MS) {
|
|
76
|
+
return typeof job?.createdAt === 'number' && nowMs - job.createdAt > ttlMs;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 状态机的一步决策(纯函数):
|
|
81
|
+
* @param {object} job 当前 job
|
|
82
|
+
* @param {{children: Record<string, {status?:string, events?:Array}>, now: number}} observation
|
|
83
|
+
* @returns {{next: string, actions: Array<{type:string, payload?:object}>, reason?: string}}
|
|
84
|
+
* actions.type: 'finish-keep'|'finish-revert'|'fail'|'start-judges'|'apply-candidate'|'await'
|
|
85
|
+
*/
|
|
86
|
+
export function planJobStep(job, observation) {
|
|
87
|
+
const state = job?.state;
|
|
88
|
+
if (state === 'done' || state === 'failed') return { next: state, actions: [], reason: 'terminal' };
|
|
89
|
+
if (isJobExpired(job, observation.now)) {
|
|
90
|
+
return { next: 'failed', actions: [{ type: 'fail', payload: { reason: 'job timeout' } }], reason: 'timeout' };
|
|
91
|
+
}
|
|
92
|
+
if (state === 'generating') {
|
|
93
|
+
const child = observation.children?.[job.generatorChildId];
|
|
94
|
+
if (!isChildSettled(child)) return { next: state, actions: [{ type: 'await' }], reason: 'generator running' };
|
|
95
|
+
const text = typeof child?.text === 'string' ? child.text : '';
|
|
96
|
+
if (text.trim() === '') {
|
|
97
|
+
return { next: 'failed', actions: [{ type: 'fail', payload: { reason: 'generator returned an empty candidate' } }], reason: 'empty candidate' };
|
|
98
|
+
}
|
|
99
|
+
return { next: 'judging', actions: [{ type: 'apply-candidate', payload: { text } }, { type: 'start-judges' }], reason: 'generator settled' };
|
|
100
|
+
}
|
|
101
|
+
if (state === 'judging') {
|
|
102
|
+
const votes = [];
|
|
103
|
+
let allSettled = true;
|
|
104
|
+
for (const childId of job.judgeChildIds ?? []) {
|
|
105
|
+
const child = observation.children?.[childId];
|
|
106
|
+
if (!isChildSettled(child)) { allSettled = false; continue; }
|
|
107
|
+
votes.push({ childId, text: typeof child?.text === 'string' ? child.text : '' });
|
|
108
|
+
}
|
|
109
|
+
if (!allSettled) return { next: state, actions: [{ type: 'await' }], reason: 'judges running' };
|
|
110
|
+
return { next: 'done', actions: [{ type: 'finish', payload: { votes } }], reason: 'judges settled' };
|
|
111
|
+
}
|
|
112
|
+
return { next: 'failed', actions: [{ type: 'fail', payload: { reason: `unknown state ${String(state)}` } }], reason: 'unknown state' };
|
|
113
|
+
}
|
|
@@ -7,22 +7,10 @@
|
|
|
7
7
|
* 汇总成 paired 多数决 verdict。
|
|
8
8
|
*/
|
|
9
9
|
import { buildPairPrompt, decideByMajority, normalizeVoteCount, parseJudgeOutput, voteFromParsed } from './judge.js';
|
|
10
|
+
import { awaitActivationText } from './subagent-text.js';
|
|
10
11
|
|
|
11
12
|
const JUDGE_TIMEOUT_MS = 120_000;
|
|
12
13
|
|
|
13
|
-
/** 从子代理的 result.output 里取纯文本。 */
|
|
14
|
-
function outputText(output) {
|
|
15
|
-
if (typeof output === 'string') return output;
|
|
16
|
-
if (Array.isArray(output)) {
|
|
17
|
-
return output.map((part) => (typeof part === 'string' ? part : part?.text ?? part?.content ?? '')).join('\n');
|
|
18
|
-
}
|
|
19
|
-
if (output && typeof output === 'object') {
|
|
20
|
-
if (typeof output.text === 'string') return output.text;
|
|
21
|
-
if (typeof output.content === 'string') return output.content;
|
|
22
|
-
}
|
|
23
|
-
return '';
|
|
24
|
-
}
|
|
25
|
-
|
|
26
14
|
/**
|
|
27
15
|
* 起 N 个独立 judge 子代理做 paired 比较。
|
|
28
16
|
*
|
|
@@ -61,12 +49,9 @@ export async function judgePair(input) {
|
|
|
61
49
|
label: `skillopt-judge-${index + 1}`,
|
|
62
50
|
request: { cwd, prompt: [{ type: 'text', text: prompt }], parent },
|
|
63
51
|
delivery: 'parent',
|
|
52
|
+
signal: new AbortController().signal,
|
|
64
53
|
});
|
|
65
|
-
const
|
|
66
|
-
Promise.resolve(activation?.result),
|
|
67
|
-
new Promise((resolve) => setTimeout(() => resolve(null), JUDGE_TIMEOUT_MS)),
|
|
68
|
-
]);
|
|
69
|
-
const text = outputText(result?.output ?? result ?? '');
|
|
54
|
+
const text = await awaitActivationText(activation, { timeoutMs: JUDGE_TIMEOUT_MS });
|
|
70
55
|
const parsed = parseJudgeOutput(text);
|
|
71
56
|
const vote = voteFromParsed(parsed === null ? null : { ...parsed, aIsAfter: mapping.aIsAfter });
|
|
72
57
|
if (vote === null) errors.push(`judge ${index + 1}: unparseable output`);
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { existsSync, mkdirSync, readFileSync, writeFileSync, copyFileSync } from 'node:fs';
|
|
6
6
|
import { dirname, join } from 'node:path';
|
|
7
7
|
import { runEngineCli, quoteArgv } from './gate-wiring.js';
|
|
8
|
+
import { awaitActivationText } from './subagent-text.js';
|
|
8
9
|
|
|
9
10
|
/** 项目是否为干净 git 仓库(决定 git 棘轮还是文件备份)。 */
|
|
10
11
|
async function isCleanGitRepo(shell, cwd) {
|
|
@@ -58,9 +59,13 @@ export async function makeVcs({ shell, projectDir, now = () => Date.now() }) {
|
|
|
58
59
|
};
|
|
59
60
|
}
|
|
60
61
|
|
|
61
|
-
|
|
62
|
+
|
|
62
63
|
export function makeGenerator({ subagents, ensureParent, providerName, cwd }) {
|
|
63
|
-
|
|
64
|
+
/**
|
|
65
|
+
* 启动生成子代理(两阶段:只启动,不等待)。返回 { childId, outputStart };
|
|
66
|
+
* 输出由 PMO tick 从会话事件里收割(工具 execute 内无法同步等待)。
|
|
67
|
+
*/
|
|
68
|
+
const start = async ({ before, dimension, round }) => {
|
|
64
69
|
const parentInfo = await ensureParent();
|
|
65
70
|
const provider = providerName();
|
|
66
71
|
const prompt = [
|
|
@@ -78,19 +83,28 @@ export function makeGenerator({ subagents, ensureParent, providerName, cwd }) {
|
|
|
78
83
|
label: `skillopt-optimize-${round}`,
|
|
79
84
|
request: { cwd, prompt: [{ type: 'text', text: prompt }], parent: parentInfo?.agent },
|
|
80
85
|
delivery: 'parent',
|
|
86
|
+
signal: new AbortController().signal,
|
|
81
87
|
});
|
|
82
|
-
|
|
83
|
-
const result = await activation?.result;
|
|
84
|
-
const raw = Array.isArray(result?.output)
|
|
85
|
-
? result.output.map((part) => (typeof part === 'string' ? part : part?.text ?? '')).join('\n')
|
|
86
|
-
: String(result?.output ?? '');
|
|
87
|
-
// 去掉可能包裹的 ```markdown 围栏。
|
|
88
|
-
const fenced = raw.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```/);
|
|
89
|
-
return fenced !== null ? fenced[1] : raw.trim();
|
|
90
|
-
} finally {
|
|
91
|
-
try { await activation?.dispose?.(); } catch { /* already gone */ }
|
|
92
|
-
}
|
|
88
|
+
return { childId: activation.childId, outputStart: activation.outputStart ?? null };
|
|
93
89
|
};
|
|
90
|
+
return { start };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 同步判据:results.tsv 中该 skill 的**最后一条**记录是否为 paired keep。
|
|
95
|
+
* adopt 门在工具 execute 内无法等待子代理,因此以已落盘的 judge 结论为准。
|
|
96
|
+
*/
|
|
97
|
+
export function hasPairedKeepRecord(projectDir, skillPath) {
|
|
98
|
+
const name = typeof skillPath === 'string' && skillPath !== ''
|
|
99
|
+
? skillPath.split(/[\\/]/).slice(-2, -1)[0]
|
|
100
|
+
: null;
|
|
101
|
+
const file = join(projectDir, '.skillopt-sleep', 'results.tsv');
|
|
102
|
+
if (!existsSync(file)) return false;
|
|
103
|
+
const lines = readFileSync(file, 'utf8').trim().split(/\r?\n/).slice(1);
|
|
104
|
+
const rows = lines.map((line) => line.split('\t')).filter((cells) => name === null || cells[2] === name);
|
|
105
|
+
const last = rows.at(-1);
|
|
106
|
+
if (last === undefined) return false;
|
|
107
|
+
return last[5] === 'keep' && last[8] === 'paired';
|
|
94
108
|
}
|
|
95
109
|
|
|
96
110
|
/** results.tsv 追加(表头自动补)。 */
|
|
@@ -18,9 +18,14 @@
|
|
|
18
18
|
export const DEFAULT_ROUNDS = 3;
|
|
19
19
|
const MAX_GROWTH = 1.5;
|
|
20
20
|
|
|
21
|
-
/**
|
|
21
|
+
/**
|
|
22
|
+
* 最大加权短板(weight × (10 - score) / 10;同分时取原始分更低者)。
|
|
23
|
+
*
|
|
24
|
+
* dim8「实测表现」被排除:它由测试 prompt 的真实运行决定,静态改写无法改进,
|
|
25
|
+
* 选它会让生成器空转(实测暴露的问题)。dim8 的改进走 full_test 流程。
|
|
26
|
+
*/
|
|
22
27
|
export function weakestDimension(rubric) {
|
|
23
|
-
const scored = (rubric?.dimensions ?? []).filter((dimension) => Number.isFinite(dimension?.score));
|
|
28
|
+
const scored = (rubric?.dimensions ?? []).filter((dimension) => Number.isFinite(dimension?.score) && dimension?.id !== 8);
|
|
24
29
|
if (scored.length === 0) return null;
|
|
25
30
|
return scored.reduce((worst, dimension) => {
|
|
26
31
|
const gap = dimension.weight * (10 - dimension.score) / 10;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 一次性子代理的「等完成 + 取最终文本」——单一份实现,judge 与生成器共用。
|
|
3
|
+
*
|
|
4
|
+
* 取证依据(@deepseek-ai/dsh-subagent/lib/types/assistant-output.js):
|
|
5
|
+
* 子代理的最终输出**不是** `activation.result`,而是
|
|
6
|
+
* `activation.handle.agent.session.snapshotEvents(activation.outputStart)` 中
|
|
7
|
+
* **最后一个非空 `assistant/message`** 的 `data.message.content`;
|
|
8
|
+
* 若无消息,回退到 `assistant/attempt|message` 的 `data.stream` 累积文本。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const END_EVENTS = new Set(['subagent/end', 'session/end']);
|
|
12
|
+
|
|
13
|
+
/** 从会话事件里提取最终 assistant 文本。 */
|
|
14
|
+
export function extractAssistantText(events) {
|
|
15
|
+
let message = null;
|
|
16
|
+
const streamPieces = [];
|
|
17
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
18
|
+
if (event?.type === 'assistant/message') {
|
|
19
|
+
const content = event?.data?.message?.content;
|
|
20
|
+
if (Array.isArray(content) && content.length > 0) message = content;
|
|
21
|
+
}
|
|
22
|
+
if (event?.type === 'assistant/message' || event?.type === 'assistant/attempt') {
|
|
23
|
+
const pieces = event?.data?.stream;
|
|
24
|
+
if (Array.isArray(pieces)) {
|
|
25
|
+
for (const piece of pieces) {
|
|
26
|
+
const text = typeof piece === 'string' ? piece : piece?.text;
|
|
27
|
+
if (typeof text === 'string' && text !== '') streamPieces.push(text);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (message === null) return streamPieces.join('');
|
|
33
|
+
return message
|
|
34
|
+
.map((block) => (typeof block === 'string' ? block : block?.text ?? ''))
|
|
35
|
+
.filter((text) => text !== '')
|
|
36
|
+
.join('\n');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 等子代理结束并返回最终文本。
|
|
41
|
+
*
|
|
42
|
+
* 两条真实路径(按可用性选择):
|
|
43
|
+
* 1. `activation.result` 是执行结果 Promise(实测返回对象含 childId/result/
|
|
44
|
+
* dispose/messageId)——解析其 output/content/lastAssistantMessage;
|
|
45
|
+
* 2. 若只有 `activation.handle.agent.session`,则轮询 snapshotEvents
|
|
46
|
+
* (见 extractAssistantText 的事件规则)。
|
|
47
|
+
*
|
|
48
|
+
* @param {object} activation startActivation 返回
|
|
49
|
+
* @param {{timeoutMs?: number, pollMs?: number}} [options]
|
|
50
|
+
* @returns {Promise<string>}
|
|
51
|
+
*/
|
|
52
|
+
export async function awaitActivationText(activation, options = {}) {
|
|
53
|
+
const timeoutMs = options.timeoutMs ?? 120_000;
|
|
54
|
+
const pollMs = options.pollMs ?? 400;
|
|
55
|
+
const timeout = new Promise((resolve) => setTimeout(() => resolve(null), timeoutMs));
|
|
56
|
+
|
|
57
|
+
// 路径 1:result Promise(实测的主路径)。
|
|
58
|
+
const pending = activation?.result;
|
|
59
|
+
if (pending !== undefined && pending !== null && typeof pending.then === 'function') {
|
|
60
|
+
const settled = await Promise.race([Promise.resolve(pending).catch(() => null), timeout]);
|
|
61
|
+
const text = textOfResult(settled);
|
|
62
|
+
if (text !== '') return text;
|
|
63
|
+
// 空结果时继续走事件路径(某些 backend 只在会话事件里留输出)。
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 路径 2:会话事件轮询。
|
|
67
|
+
const agent = activation?.handle?.agent;
|
|
68
|
+
const readEvents = () => {
|
|
69
|
+
try {
|
|
70
|
+
return agent?.session?.snapshotEvents?.(activation?.outputStart) ?? [];
|
|
71
|
+
} catch {
|
|
72
|
+
return [];
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
const deadline = Date.now() + timeoutMs;
|
|
76
|
+
const finished = (events) => events.some((event) => END_EVENTS.has(event?.type));
|
|
77
|
+
while (Date.now() < deadline) {
|
|
78
|
+
const events = readEvents();
|
|
79
|
+
if (finished(events) || (agent?.status === 'idle' && events.length > 0)) return extractAssistantText(events);
|
|
80
|
+
await new Promise((resolve) => setTimeout(resolve, pollMs));
|
|
81
|
+
}
|
|
82
|
+
return extractAssistantText(readEvents());
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 把 activation.result 的值归一成文本(兼容 string / output 数组 / content)。 */
|
|
86
|
+
export function textOfResult(settled) {
|
|
87
|
+
if (settled === null || settled === undefined) return '';
|
|
88
|
+
if (typeof settled === 'string') return settled;
|
|
89
|
+
const candidates = [settled.output, settled.content, settled.lastAssistantMessage, settled.text];
|
|
90
|
+
for (const candidate of candidates) {
|
|
91
|
+
if (typeof candidate === 'string' && candidate !== '') return candidate;
|
|
92
|
+
if (Array.isArray(candidate)) {
|
|
93
|
+
const text = candidate
|
|
94
|
+
.map((part) => (typeof part === 'string' ? part : part?.text ?? part?.content ?? ''))
|
|
95
|
+
.filter((piece) => piece !== '')
|
|
96
|
+
.join('\n');
|
|
97
|
+
if (text !== '') return text;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return '';
|
|
101
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@suifei/dsh-ai-team",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "文渊阁 (Wenyuan Pavilion) — AI Team mode for DeepSeek Harness: concurrent projects, owned tasks, threads, inbox and an append-only team ledger",
|
|
6
6
|
"license": "MIT",
|