@hugesb/dsh-stream-agent 0.0.0-stage → 0.3.1
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 +497 -0
- package/CONTRIBUTING.md +72 -0
- package/LICENSE +202 -0
- package/README.en.md +349 -0
- package/README.md +300 -3
- package/cordis.patch.yml +77 -0
- package/dist/entry/action-gate.js +206 -0
- package/dist/entry/adapter-kit.js +192 -0
- package/dist/entry/context-render.js +119 -0
- package/dist/entry/control-bar-cli.js +289 -0
- package/dist/entry/control-bar.js +123 -0
- package/dist/entry/control-session.js +115 -0
- package/dist/entry/control-state.js +125 -0
- package/dist/entry/cordis-compat.js +95 -0
- package/dist/entry/eval-probe.js +112 -0
- package/dist/entry/intent-log.js +121 -0
- package/dist/entry/json-persistence.js +306 -0
- package/dist/entry/loop.js +3852 -0
- package/dist/entry/mock-provider.js +536 -0
- package/dist/entry/obs-broker.js +178 -0
- package/dist/entry/ptc-bridge.js +405 -0
- package/dist/entry/state-handle.js +217 -0
- package/dist/entry/takeover-registry.js +60 -0
- package/dist/kernel/control-bar.js +559 -0
- package/dist/kernel/final.js +62 -0
- package/dist/kernel/gate.js +464 -0
- package/dist/kernel/modes.js +253 -0
- package/dist/kernel/obs.js +517 -0
- package/dist/kernel/parser.js +632 -0
- package/dist/kernel/render.js +444 -0
- package/dist/kernel/state.js +416 -0
- package/dist/version.js +9 -0
- package/docs/TEST-PROPOSITIONS.md +139 -0
- package/docs/adr-001-segment-boundary.md +61 -0
- package/docs/architecture.md +104 -0
- package/docs/desktop-ui-feasibility.md +277 -0
- package/docs/disabled-lines-audit.md +53 -0
- package/docs/limitations.md +181 -0
- package/docs/protocol.md +99 -0
- package/docs/v0.4.0-plan.md +50 -0
- package/eval/METRICS.md +128 -0
- package/eval/RESULTS.md +246 -0
- package/eval/tasks/fixtures/big-report.md +298 -0
- package/eval/tasks/fixtures/build-manifest.txt +5 -0
- package/eval/tasks/fixtures/deploy.yaml +4 -0
- package/eval/tasks/fixtures/error.log +200 -0
- package/eval/tasks/fixtures/features.yaml +4 -0
- package/eval/tasks/fixtures/pipeline.yaml +4 -0
- package/eval/tasks/fixtures/sales-q1.csv +61 -0
- package/eval/tasks/fixtures/settings.yaml +4 -0
- package/eval/tasks/fixtures/users-roster.json +304 -0
- package/eval/tasks/fixtures/users-scores.json +20 -0
- package/eval/tasks/gen-fixtures.cjs +80 -0
- package/eval/tasks/tasks.json +150 -0
- package/eval/tools/f6-kill-drill.cjs +176 -0
- package/eval/tools/f6-kill-drill.worker.cjs +131 -0
- package/eval/tools/gen-results.cjs +191 -0
- package/eval/tools/machine-test.cjs +200 -0
- package/eval/tools/manual-code-scenarios.md +59 -0
- package/eval/tools/replay-check.cjs +311 -0
- package/eval/tools/runner.cjs +219 -0
- package/eval/tools/session-log.cjs +106 -0
- package/eval/tools/summarize.cjs +185 -0
- package/eval/tools/t3-cells.cjs +173 -0
- package/package.json +73 -6
- package/patches/adapters-smoke.yml +41 -0
- package/patches/eval-account.yml +36 -0
- package/patches/eval-baseline.yml +33 -0
- package/patches/eval-stream-code-off.yml +46 -0
- package/patches/eval-stream-code-on.yml +47 -0
- package/patches/eval-stream.yml +54 -0
- package/patches/takeover.yml +42 -0
- package/patches/test-preset.yml +23 -0
- package/preset/stream/cordis.patch.yml +39 -0
- package/preset/stream/package.json +13 -0
- package/preset.yml +56 -0
- package/profiles/stream/README.md +66 -0
- package/profiles/stream/cordis.patch.yml +12 -0
- package/profiles/stream/package.json +17 -0
- package/profiles/stream-headless/package.json +16 -0
- package/scripts/build.mjs +103 -0
- package/scripts/check-consistency.mjs +146 -0
- package/scripts/gate.mjs +138 -0
- package/scripts/install-check.mjs +116 -0
- package/scripts/install-cycle.mjs +88 -0
- package/scripts/release.mjs +415 -0
- package/scripts/repair-session-logs.mjs +403 -0
- package/src/entry/action-gate.ts +206 -0
- package/src/entry/adapter-kit.ts +192 -0
- package/src/entry/context-render.ts +119 -0
- package/src/entry/control-bar-cli.ts +289 -0
- package/src/entry/control-bar.ts +123 -0
- package/src/entry/control-session.ts +115 -0
- package/src/entry/control-state.ts +125 -0
- package/src/entry/cordis-compat.ts +95 -0
- package/src/entry/eval-probe.ts +112 -0
- package/src/entry/intent-log.ts +121 -0
- package/src/entry/json-persistence.ts +306 -0
- package/src/entry/loop.ts +3852 -0
- package/src/entry/mock-provider.ts +536 -0
- package/src/entry/obs-broker.ts +178 -0
- package/src/entry/ptc-bridge.ts +405 -0
- package/src/entry/state-handle.ts +217 -0
- package/src/entry/takeover-registry.ts +60 -0
- package/src/kernel/control-bar.ts +559 -0
- package/src/kernel/final.ts +62 -0
- package/src/kernel/gate.ts +464 -0
- package/src/kernel/modes.ts +253 -0
- package/src/kernel/obs.ts +517 -0
- package/src/kernel/parser.ts +632 -0
- package/src/kernel/render.ts +444 -0
- package/src/kernel/state.ts +416 -0
- package/src/version.ts +9 -0
- package/test/activation.test.ts +187 -0
- package/test/adapters.test.ts +676 -0
- package/test/control-bar.test.ts +486 -0
- package/test/desktop-ui.test.ts +359 -0
- package/test/eval-probe.test.ts +139 -0
- package/test/f5-plan.test.ts +221 -0
- package/test/f6-intent.test.ts +168 -0
- package/test/f7-segment.test.ts +190 -0
- package/test/fix-limits.test.ts +599 -0
- package/test/gate.test.ts +380 -0
- package/test/helpers/stub-loop.ts +240 -0
- package/test/kernel/obs.test.ts +329 -0
- package/test/kernel/parser.test.ts +450 -0
- package/test/loop.test.ts +1393 -0
- package/test/mock-provider.test.ts +386 -0
- package/test/ptc-bridge.test.ts +356 -0
- package/test/render.test.ts +418 -0
- package/test/s2-install-check.test.ts +46 -0
- package/test/scenarios/3-file-basic.json +13 -0
- package/test/scenarios/5-file-basic.json +22 -0
- package/test/scenarios/burn-more.json +9 -0
- package/test/scenarios/degraded-final.json +10 -0
- package/test/scenarios/fault-abort-xml.json +11 -0
- package/test/scenarios/fault-malformed-command.json +12 -0
- package/test/scenarios/fault-midstream-abort.json +11 -0
- package/test/scenarios/fault-saturating-output.json +9 -0
- package/test/scenarios/fault-timeout.json +9 -0
- package/test/scenarios/peek-first.json +11 -0
- package/test/scenarios/peek-second.json +11 -0
- package/test/scenarios/peek-third.json +10 -0
- package/test/scenarios/recover-final.json +10 -0
- package/test/scenarios/reroute-first.json +17 -0
- package/test/scenarios/reroute-second.json +16 -0
- package/test/scenarios/starvation-final.json +10 -0
- package/test/scenarios/starvation-promote.json +11 -0
- package/test/scenarios/wait-tools-continue.json +10 -0
- package/test/scenarios/wait-tools-xml.json +22 -0
- package/test/scenarios/wait-tools.json +15 -0
- package/test/session-format.test.ts +234 -0
- package/test/state.test.ts +335 -0
- package/test/stream-v02.test.ts +264 -0
- package/test/v031-display.test.ts +333 -0
- package/ui/client.js +576 -0
- package/ui/index.js +282 -0
- package/ui/package.json +26 -0
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
// scripts/repair-session-logs.mjs —— 存量会话日志的 v4 工具生命周期修复(0.3.0)
|
|
2
|
+
//
|
|
3
|
+
// 背景:0.3.0 及更早版本的插件在派发 tf-* 命令时只让宿主管线落 `tool/call` +
|
|
4
|
+
// `tool/result`,从未写 v4 格式要求的 `assistant/message`(content 带 `tool-call` 块)。
|
|
5
|
+
// 宿主读取该日志时抛 `tool/call <id> has no advertised tool lifecycle`,把整条会话判为
|
|
6
|
+
// corrupt——桌面端表现为"历史加载失败"。本脚本为存量日志补入缺失的广告事件,并重排
|
|
7
|
+
// seq 与全部 seq 引用;写入前先备份,写入后用本地复核规则再验一遍。
|
|
8
|
+
//
|
|
9
|
+
// 用法:
|
|
10
|
+
// node scripts/repair-session-logs.mjs # dry-run:只报告哪些会话需要修
|
|
11
|
+
// node scripts/repair-session-logs.mjs --write # 落盘(.bak-<时间戳> 备份 + 删投影缓存)
|
|
12
|
+
// node scripts/repair-session-logs.mjs --session <id> # 只处理一个会话
|
|
13
|
+
// node scripts/repair-session-logs.mjs --root <dir> # 指定 dsh 状态根(缺省 ~/.dsh)
|
|
14
|
+
//
|
|
15
|
+
// 纪律:零依赖;只改被判定为"缺广告"的会话;已有广告的会话一个字节都不动。
|
|
16
|
+
|
|
17
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
18
|
+
import { homedir } from 'node:os';
|
|
19
|
+
import { dirname, join, resolve } from 'node:path';
|
|
20
|
+
import { randomUUID } from 'node:crypto';
|
|
21
|
+
import { zstdCompressSync, zstdDecompressSync } from 'node:zlib';
|
|
22
|
+
|
|
23
|
+
// ---------------------------------------------------------------------------
|
|
24
|
+
// 参数
|
|
25
|
+
// ---------------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
const args = process.argv.slice(2);
|
|
28
|
+
const has = (name) => args.includes(name);
|
|
29
|
+
const valueOf = (name, fallback) => {
|
|
30
|
+
const i = args.indexOf(name);
|
|
31
|
+
return i >= 0 && args[i + 1] !== undefined ? args[i + 1] : fallback;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const WRITE = has('--write');
|
|
35
|
+
const STATE_ROOT = resolve(valueOf('--root', join(homedir(), '.dsh')));
|
|
36
|
+
const ONLY_SESSION = valueOf('--session', undefined);
|
|
37
|
+
const SESSIONS_ROOT = join(STATE_ROOT, 'sessions');
|
|
38
|
+
const PROJ_CACHE = join(STATE_ROOT, 'storages', 'session_projcache', 'sessions');
|
|
39
|
+
|
|
40
|
+
if (!existsSync(SESSIONS_ROOT)) {
|
|
41
|
+
console.error(`[repair] 找不到会话目录:${SESSIONS_ROOT}(用 --root 指定 dsh 状态根)`);
|
|
42
|
+
process.exit(2);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
46
|
+
// zstd 多帧解码 / 单帧编码(宿主的日志是"每次 append 一帧")
|
|
47
|
+
// ---------------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
function frameEnd(buf, start) {
|
|
50
|
+
let p = start;
|
|
51
|
+
if (buf.readUInt32LE(p) !== 0xFD2FB528) throw new Error(`zstd magic 不符(byte ${p})`);
|
|
52
|
+
p += 4;
|
|
53
|
+
const fhd = buf[p++];
|
|
54
|
+
const fcs = fhd >> 6;
|
|
55
|
+
const singleSegment = (fhd >> 5) & 1;
|
|
56
|
+
const checksum = (fhd >> 2) & 1;
|
|
57
|
+
const dictFlag = fhd & 3;
|
|
58
|
+
if (!singleSegment) p += 1;
|
|
59
|
+
p += [0, 1, 2, 4][dictFlag];
|
|
60
|
+
p += [singleSegment ? 1 : 0, 2, 4, 8][fcs];
|
|
61
|
+
for (;;) {
|
|
62
|
+
const header = buf.readUIntLE(p, 3);
|
|
63
|
+
p += 3;
|
|
64
|
+
const last = header & 1;
|
|
65
|
+
const type = (header >> 1) & 3;
|
|
66
|
+
const size = header >> 3;
|
|
67
|
+
if (type === 3) throw new Error('zstd block type 3(reserved)');
|
|
68
|
+
p += size;
|
|
69
|
+
if (last) break;
|
|
70
|
+
}
|
|
71
|
+
if (checksum) p += 4;
|
|
72
|
+
return p;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function decodeZstdFrames(buf) {
|
|
76
|
+
let p = 0;
|
|
77
|
+
const chunks = [];
|
|
78
|
+
while (p < buf.length) {
|
|
79
|
+
const end = frameEnd(buf, p);
|
|
80
|
+
chunks.push(zstdDecompressSync(buf.subarray(p, end)));
|
|
81
|
+
p = end;
|
|
82
|
+
}
|
|
83
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ---------------------------------------------------------------------------
|
|
87
|
+
// 修复:补广告 + 重排 seq
|
|
88
|
+
// ---------------------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 第二类 corrupt(0.3.0 的 finalAnswer):assistant/message 写在 step/end 之后。
|
|
92
|
+
* 把它移到该 step 的 step/end 之前(保持原来的先后顺序),v4 才认为它落在打开的 step 内。
|
|
93
|
+
*/
|
|
94
|
+
function reorderClosedStepMessages(events) {
|
|
95
|
+
/** @type {Map<number, number[]>} step/end 下标 -> 需要移到它前面的消息下标 */
|
|
96
|
+
const moveBefore = new Map();
|
|
97
|
+
let turn = null;
|
|
98
|
+
let step = null;
|
|
99
|
+
for (let i = 0; i < events.length; i += 1) {
|
|
100
|
+
const event = events[i];
|
|
101
|
+
const data = event.data ?? {};
|
|
102
|
+
if (event.type === 'turn/start') { turn = data.turn ?? null; step = null; continue; }
|
|
103
|
+
if (event.type === 'step/start') { step = data.step ?? null; continue; }
|
|
104
|
+
if (event.type === 'step/end') { step = null; continue; }
|
|
105
|
+
if (event.type === 'turn/end') { turn = null; step = null; continue; }
|
|
106
|
+
if (step !== null) continue;
|
|
107
|
+
if (event.type !== 'assistant/message' && event.type !== 'assistant/attempt') continue;
|
|
108
|
+
if (turn === null || data.turn !== turn) continue;
|
|
109
|
+
// 往回找同一 turn 最近的 step/end(没有就找 turn/end)
|
|
110
|
+
let target = -1;
|
|
111
|
+
for (let j = i - 1; j >= 0; j -= 1) {
|
|
112
|
+
if (events[j].type === 'step/end' && events[j].data?.turn === turn) { target = j; break; }
|
|
113
|
+
if (events[j].type === 'turn/start' && events[j].data?.turn === turn) break;
|
|
114
|
+
}
|
|
115
|
+
if (target < 0) {
|
|
116
|
+
for (let j = i - 1; j >= 0; j -= 1) {
|
|
117
|
+
if (events[j].type === 'turn/end' && events[j].data?.turn === turn) { target = j; break; }
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (target < 0) continue;
|
|
121
|
+
const list = moveBefore.get(target) ?? [];
|
|
122
|
+
list.push(i);
|
|
123
|
+
moveBefore.set(target, list);
|
|
124
|
+
}
|
|
125
|
+
if (moveBefore.size === 0) return events;
|
|
126
|
+
const moved = new Set([...moveBefore.values()].flat());
|
|
127
|
+
const out = [];
|
|
128
|
+
for (let i = 0; i < events.length; i += 1) {
|
|
129
|
+
if (moved.has(i)) continue;
|
|
130
|
+
const list = moveBefore.get(i);
|
|
131
|
+
if (list !== undefined) for (const index of list) out.push(events[index]);
|
|
132
|
+
out.push(events[i]);
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function repairedRows(rows, sessionId) {
|
|
138
|
+
const [headerRow, ...rawEvents] = rows;
|
|
139
|
+
if (headerRow?.type !== 'session') throw new Error('首行不是 session header');
|
|
140
|
+
const events = reorderClosedStepMessages(rawEvents);
|
|
141
|
+
|
|
142
|
+
/** @type {Map<number, Array<{type:'tool-call', id:string, name:string, arguments:string}>>} */
|
|
143
|
+
const insertBefore = new Map();
|
|
144
|
+
let turn = null;
|
|
145
|
+
let step = null;
|
|
146
|
+
const advertised = new Set();
|
|
147
|
+
let unadvertised = 0;
|
|
148
|
+
|
|
149
|
+
for (let i = 0; i < events.length; i += 1) {
|
|
150
|
+
const event = events[i];
|
|
151
|
+
const data = event.data ?? {};
|
|
152
|
+
if (event.type === 'turn/start') {
|
|
153
|
+
turn = data.turn ?? null;
|
|
154
|
+
step = null;
|
|
155
|
+
advertised.clear();
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (event.type === 'step/start') {
|
|
159
|
+
step = data.step ?? null;
|
|
160
|
+
advertised.clear();
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
if (event.type === 'step/end') {
|
|
164
|
+
step = null;
|
|
165
|
+
advertised.clear();
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (event.type === 'assistant/message') {
|
|
169
|
+
for (const block of data.message?.content ?? []) {
|
|
170
|
+
if (block?.type === 'tool-call' && typeof block.id === 'string') advertised.add(block.id);
|
|
171
|
+
}
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (event.type === 'tool/call') {
|
|
175
|
+
const callId = data.callId;
|
|
176
|
+
if (typeof callId !== 'string') throw new Error(`tool/call#${event.seq} 缺 callId`);
|
|
177
|
+
if (advertised.has(callId)) continue;
|
|
178
|
+
unadvertised += 1;
|
|
179
|
+
const blocks = insertBefore.get(i) ?? [];
|
|
180
|
+
blocks.push({ type: 'tool-call', id: callId, name: String(data.name ?? 'unknown'), arguments: String(data.arguments ?? '{}') });
|
|
181
|
+
insertBefore.set(i, blocks);
|
|
182
|
+
advertised.add(callId); // 同一 step 内只插一条广告
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const reordered = events !== rawEvents;
|
|
187
|
+
/** 以原事件对象为锚重建 seq 与全部 seq 引用(重排/插入后旧 seq 不再等于下标)。 */
|
|
188
|
+
const rebuild = (list) => {
|
|
189
|
+
const map = new Map();
|
|
190
|
+
rawEvents.forEach((event, index) => {
|
|
191
|
+
const newIndex = list.indexOf(event);
|
|
192
|
+
if (newIndex >= 0) map.set(typeof event.seq === 'number' ? event.seq : index, newIndex);
|
|
193
|
+
});
|
|
194
|
+
list.forEach((event, index) => { event.seq = index; });
|
|
195
|
+
for (const event of list) remapReferences(event, map);
|
|
196
|
+
return list;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
if (insertBefore.size === 0) {
|
|
200
|
+
if (!reordered) return { changed: false, rows, inserted: 0, unadvertised: 0, reordered: false };
|
|
201
|
+
const out = rebuild([...events]);
|
|
202
|
+
return { changed: true, rows: [headerRow, ...out], inserted: 0, unadvertised: 0, reordered: true };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const out = [];
|
|
206
|
+
for (let i = 0; i < events.length; i += 1) {
|
|
207
|
+
const blocks = insertBefore.get(i);
|
|
208
|
+
if (blocks !== undefined) {
|
|
209
|
+
const first = events[i];
|
|
210
|
+
out.push({
|
|
211
|
+
type: 'assistant/message',
|
|
212
|
+
time: typeof first.time === 'number' ? first.time - 1 : Date.now(),
|
|
213
|
+
data: {
|
|
214
|
+
turn: first.data?.turn,
|
|
215
|
+
step: first.data?.step,
|
|
216
|
+
message: { id: `repaired-ad-${randomUUID()}`, role: 'assistant', content: blocks, source: { kind: 'model' } },
|
|
217
|
+
stream: [],
|
|
218
|
+
},
|
|
219
|
+
surfaceOp: 'append',
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
out.push(events[i]);
|
|
223
|
+
}
|
|
224
|
+
rebuild(out);
|
|
225
|
+
|
|
226
|
+
return { changed: true, rows: [headerRow, ...out], inserted: insertBefore.size, unadvertised, reordered };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function remapReferences(event, map) {
|
|
230
|
+
const m = (value) => (typeof value === 'number' && map.has(value) ? map.get(value) : value);
|
|
231
|
+
if (Array.isArray(event.sourceEventSeqs)) event.sourceEventSeqs = event.sourceEventSeqs.map(m);
|
|
232
|
+
if (event.surfaceOp !== null && typeof event.surfaceOp === 'object') {
|
|
233
|
+
event.surfaceOp.startSeq = m(event.surfaceOp.startSeq);
|
|
234
|
+
event.surfaceOp.endSeq = m(event.surfaceOp.endSeq);
|
|
235
|
+
}
|
|
236
|
+
const data = event.data;
|
|
237
|
+
if (data === null || typeof data !== 'object') return;
|
|
238
|
+
if (Array.isArray(data.messageSeqs)) data.messageSeqs = data.messageSeqs.map(m);
|
|
239
|
+
if (typeof data.throughSeq === 'number') data.throughSeq = m(data.throughSeq);
|
|
240
|
+
if (typeof data.headerSeq === 'number') data.headerSeq = m(data.headerSeq);
|
|
241
|
+
if (Array.isArray(data.shadowedSeqs)) data.shadowedSeqs = data.shadowedSeqs.map(m);
|
|
242
|
+
if (data.shadowedRange !== null && typeof data.shadowedRange === 'object') {
|
|
243
|
+
data.shadowedRange.start = m(data.shadowedRange.start);
|
|
244
|
+
data.shadowedRange.end = m(data.shadowedRange.end);
|
|
245
|
+
}
|
|
246
|
+
if (typeof data.startSeq === 'number') data.startSeq = m(data.startSeq);
|
|
247
|
+
if (typeof data.endSeq === 'number') data.endSeq = m(data.endSeq);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ---------------------------------------------------------------------------
|
|
251
|
+
// 复核:与 dsh-session-format-v3-to-v4 的 tool()/closeTools 同规则
|
|
252
|
+
// ---------------------------------------------------------------------------
|
|
253
|
+
|
|
254
|
+
function assertLifecycle(rows) {
|
|
255
|
+
const events = rows.filter((row) => row.type !== 'session');
|
|
256
|
+
const pending = new Map();
|
|
257
|
+
let turn = null;
|
|
258
|
+
let step = null;
|
|
259
|
+
for (const event of events) {
|
|
260
|
+
const data = event.data ?? {};
|
|
261
|
+
if (event.type === 'turn/start') { turn = data.turn ?? null; step = null; pending.clear(); continue; }
|
|
262
|
+
if (event.type === 'step/start') { step = data.step ?? null; continue; }
|
|
263
|
+
if (event.type === 'step/end') {
|
|
264
|
+
if (pending.size !== 0) throw new Error(`step/end 仍有未解调用:${[...pending.keys()].join(',')}`);
|
|
265
|
+
step = null;
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
if (event.type === 'assistant/message') {
|
|
269
|
+
if (data.turn !== undefined && (data.turn !== turn || data.step !== step)) {
|
|
270
|
+
throw new Error(`assistant/message#${event.seq} 不在打开的 turn+step 内`);
|
|
271
|
+
}
|
|
272
|
+
for (const block of data.message?.content ?? []) {
|
|
273
|
+
if (block?.type !== 'tool-call') continue;
|
|
274
|
+
if (pending.has(block.id)) throw new Error(`assistant/message 重复广告 ${block.id}`);
|
|
275
|
+
pending.set(block.id, { name: block.name, arguments: block.arguments, started: false });
|
|
276
|
+
}
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
if (event.type === 'tool/call') {
|
|
280
|
+
const entry = pending.get(data.callId);
|
|
281
|
+
if (entry === undefined) throw new Error(`tool/call ${data.callId} 没有广告`);
|
|
282
|
+
if (entry.name !== data.name || entry.arguments !== data.arguments) throw new Error(`tool/call ${data.callId} 与广告不一致`);
|
|
283
|
+
entry.started = true;
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
if (event.type === 'tool/result') {
|
|
287
|
+
const id = data.message?.toolCallId;
|
|
288
|
+
const entry = pending.get(id);
|
|
289
|
+
if (entry === undefined) throw new Error(`tool/result ${id} 没有对应调用`);
|
|
290
|
+
if (!entry.started) {
|
|
291
|
+
const message = data.message ?? {};
|
|
292
|
+
const error = event.error ?? {};
|
|
293
|
+
const repaired = typeof message.id === 'string' && message.id.startsWith(`interrupted-tool-result-${id}-`)
|
|
294
|
+
&& message.isError === true && error.name === 'ToolNotStartedError' && error.code === 'TOOL_NOT_STARTED';
|
|
295
|
+
if (!repaired) throw new Error(`未开始调用 ${id} 的 result 不是 TOOL_NOT_STARTED 修复形状`);
|
|
296
|
+
}
|
|
297
|
+
pending.delete(id);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
for (const event of events) {
|
|
301
|
+
const max = events.length - 1;
|
|
302
|
+
const check = (value, label) => {
|
|
303
|
+
if (typeof value === 'number' && (value < 0 || value > max)) throw new Error(`${label} 越界:${value}`);
|
|
304
|
+
};
|
|
305
|
+
check(event.seq, `${event.type} seq`);
|
|
306
|
+
for (const seq of event.sourceEventSeqs ?? []) check(seq, `${event.type} sourceEventSeqs`);
|
|
307
|
+
for (const seq of event.data?.messageSeqs ?? []) check(seq, `${event.type} messageSeqs`);
|
|
308
|
+
check(event.data?.throughSeq, `${event.type} throughSeq`);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// ---------------------------------------------------------------------------
|
|
313
|
+
// 遍历 / 落盘
|
|
314
|
+
// ---------------------------------------------------------------------------
|
|
315
|
+
|
|
316
|
+
function findSessionFiles(root) {
|
|
317
|
+
const found = [];
|
|
318
|
+
for (const project of readdirSync(root)) {
|
|
319
|
+
const projectDir = join(root, project);
|
|
320
|
+
if (!statSync(projectDir).isDirectory()) continue;
|
|
321
|
+
for (const sessionId of readdirSync(projectDir)) {
|
|
322
|
+
const sessionDir = join(projectDir, sessionId);
|
|
323
|
+
if (!statSync(sessionDir).isDirectory()) continue;
|
|
324
|
+
if (ONLY_SESSION !== undefined && !sessionId.includes(ONLY_SESSION)) continue;
|
|
325
|
+
const file = readdirSync(sessionDir).find((name) => name.endsWith('.jsonl.zstd'));
|
|
326
|
+
if (file === undefined) continue;
|
|
327
|
+
found.push({ sessionId, file: join(sessionDir, file) });
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
return found;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function readRows(file) {
|
|
334
|
+
const buf = readFileSync(file);
|
|
335
|
+
const text = file.endsWith('.zstd') ? decodeZstdFrames(buf) : buf.toString('utf8');
|
|
336
|
+
return text.split('\n').filter((line) => line.trim() !== '').map((line) => JSON.parse(line));
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
let scanned = 0;
|
|
340
|
+
let needRepair = 0;
|
|
341
|
+
let written = 0;
|
|
342
|
+
|
|
343
|
+
// 可选:用宿主自己的 v4 校验器复核(设 DSH_HOST_MODULES=<dsh 安装目录>/node_modules/@deepseek-ai)。
|
|
344
|
+
// 缺省只用本地生命周期规则——插件仓库不依赖宿主包。
|
|
345
|
+
const hostModules = process.env.DSH_HOST_MODULES;
|
|
346
|
+
let hostValidate;
|
|
347
|
+
if (hostModules !== undefined && hostModules.trim() !== '') {
|
|
348
|
+
const base = hostModules.replace(/\\/g, '/').replace(/\/$/, '');
|
|
349
|
+
const { KNOWN_SESSION_EVENT_TYPES } = await import(`file:///${base}/dsh-session/lib/index.js`);
|
|
350
|
+
const { restoreReleasedV4Artifact, assertReleasedV4Relationships } = await import(`file:///${base}/dsh-session-format-v3-to-v4/lib/index.js`);
|
|
351
|
+
hostValidate = (rows) => {
|
|
352
|
+
const [headerRow, ...events] = rows;
|
|
353
|
+
const { type: _type, ...header } = headerRow;
|
|
354
|
+
const artifact = { header, inheritedEventCount: header.isSeeded === true ? (headerRow.inheritedEventCount ?? 0) : 0, events };
|
|
355
|
+
restoreReleasedV4Artifact(artifact, KNOWN_SESSION_EVENT_TYPES);
|
|
356
|
+
assertReleasedV4Relationships(artifact, KNOWN_SESSION_EVENT_TYPES);
|
|
357
|
+
};
|
|
358
|
+
console.log(`[host] 使用宿主校验器复核:${base}`);
|
|
359
|
+
}
|
|
360
|
+
for (const { sessionId, file } of findSessionFiles(SESSIONS_ROOT)) {
|
|
361
|
+
scanned += 1;
|
|
362
|
+
let rows;
|
|
363
|
+
try {
|
|
364
|
+
rows = readRows(file);
|
|
365
|
+
} catch (error) {
|
|
366
|
+
console.log(`[skip] ${sessionId}:日志无法解码(${error.message})`);
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
let result;
|
|
370
|
+
try {
|
|
371
|
+
result = repairedRows(rows, sessionId);
|
|
372
|
+
} catch (error) {
|
|
373
|
+
console.log(`[skip] ${sessionId}:${error.message}`);
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
if (!result.changed) {
|
|
377
|
+
console.log(`[ok] ${sessionId}:无缺失广告`);
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
needRepair += 1;
|
|
381
|
+
console.log(`[fix] ${sessionId}:补 ${result.inserted} 条广告(覆盖 ${result.unadvertised} 个 tool/call)`);
|
|
382
|
+
try {
|
|
383
|
+
assertLifecycle(result.rows);
|
|
384
|
+
hostValidate?.(result.rows);
|
|
385
|
+
} catch (error) {
|
|
386
|
+
console.log(`[fail] ${sessionId}:修复后复核不通过(${error.message}),不落盘`);
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
if (!WRITE) continue;
|
|
390
|
+
const backup = `${file}.bak-${new Date().toISOString().replace(/[:.]/g, '-')}`;
|
|
391
|
+
copyFileSync(file, backup);
|
|
392
|
+
const jsonl = `${result.rows.map((row) => JSON.stringify(row)).join('\n')}\n`;
|
|
393
|
+
const tmp = `${file}.tmp`;
|
|
394
|
+
writeFileSync(tmp, zstdCompressSync(Buffer.from(jsonl, 'utf8')));
|
|
395
|
+
renameSync(tmp, file);
|
|
396
|
+
const cache = join(PROJ_CACHE, `${sessionId}.json`);
|
|
397
|
+
if (existsSync(cache)) rmSync(cache, { force: true });
|
|
398
|
+
written += 1;
|
|
399
|
+
console.log(` 已写入(备份:${backup};投影缓存已清除)`);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
console.log('');
|
|
403
|
+
console.log(`扫描 ${scanned} 个会话,需修复 ${needRepair} 个,${WRITE ? `已写入 ${written} 个` : 'dry-run 未写入(加 --write 落盘)'}`);
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// entry/action-gate.ts —— 动作门(M4 适配,分派 07)
|
|
2
|
+
//
|
|
3
|
+
// 挂点:ToolsService 管线 guard(F6,dsh-tools/lib/types/index.d.ts:136; ToolGuard 契约
|
|
4
|
+
// contracts.d.ts:374:同步、只拒绝不放行、不可改写——探针 B 实测,参数改写需 executor 层)。
|
|
5
|
+
// 职责:翻译内核 gate 的判定为管线语义:
|
|
6
|
+
// 1. 未声明 reversibility 的受治理动作 → deny + 可读理由(内核 UnknownActionError 原文透传);
|
|
7
|
+
// 非本插件治理空间的宿主工具(grep/web/…)不表意见(返回 undefined,放行权归宿主策略层)。
|
|
8
|
+
// 2. spec 级:写暂存区(StagingSink 接 DSH storage,绝不触碰真实工作区)+ 产 diff +
|
|
9
|
+
// 领一次性凭据;默认 stage-commit 模式在本守卫内完成 speculate→commit 自洽闭环后放行
|
|
10
|
+
// (否则 tf-write 永远无法落地);strict 模式走内核 admit(),拒绝透传(留给驱动器侧两段式)。
|
|
11
|
+
// 3. commit 凭据校验:kernel gate.commit 的结构化拒绝(already_used / expired /
|
|
12
|
+
// hash_mismatch / unknown)原样透传为可读拒绝串。
|
|
13
|
+
// 4. fatal 级:无批准通道 → deny(内核 admit 同款理由)。
|
|
14
|
+
// fail-open(红线 5):守卫自身异常 → 不表意见(放行)+ ledger 记 gate_error,绝不静默。
|
|
15
|
+
// 红线:本 entry 不写业务逻辑——判定/凭据/暂存泄漏探测全在 kernel/gate.ts。
|
|
16
|
+
|
|
17
|
+
import { createHash } from 'node:crypto';
|
|
18
|
+
import { readFileSync } from 'node:fs';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { ActionRegistry, ActionGate, SystemClock } from '../kernel/gate.ts';
|
|
21
|
+
import type { StagingSink, StagedWriteReceipt, Reversibility, CommitCredential } from '../kernel/gate.ts';
|
|
22
|
+
import { makeWarn, EntryLedger, kernelDiffer, openKvUnit } from './adapter-kit.ts';
|
|
23
|
+
import { asPluginEffect, getService } from './cordis-compat.ts';
|
|
24
|
+
import type { HostCtxLike, StorageLike, KvUnitLike } from './adapter-kit.ts';
|
|
25
|
+
|
|
26
|
+
export interface ActionGateConfig {
|
|
27
|
+
/** 工作区根(workspaceHash 探针与 diff 基线;默认 process.cwd()) */
|
|
28
|
+
workspaceRoot?: string;
|
|
29
|
+
/** staging KvUnit 名(默认 'tfAgentStaging';后端固定 'json',与 state-handle 同款接驳) */
|
|
30
|
+
unit?: string;
|
|
31
|
+
/** 凭据有效期 ms(默认 300_000,透传内核) */
|
|
32
|
+
credentialTtlMs?: number;
|
|
33
|
+
/** spec 级放行模式:'stage-commit'(默认,守卫内闭环)/ 'strict'(拒绝透传,两段式上移驱动器) */
|
|
34
|
+
mode?: 'stage-commit' | 'strict';
|
|
35
|
+
/** 动作声明(提供即整体替换默认声明;缺省用默认);受治理集合 = 声明集合 ∪ tf-* 前缀 */
|
|
36
|
+
actions?: Record<string, Reversibility>;
|
|
37
|
+
/** 测试注错位:守卫体抛错(fail-open 验证用;生产不得设置) */
|
|
38
|
+
faultInjection?: boolean;
|
|
39
|
+
/** 装载自证横幅(排障用;preset/patch 激活对 CLI 静默,探针 A 惯例) */
|
|
40
|
+
announce?: boolean;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface ActionGateHandle {
|
|
44
|
+
registry: ActionRegistry;
|
|
45
|
+
gate: ActionGate;
|
|
46
|
+
faults: EntryLedger;
|
|
47
|
+
dispose: () => void;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** StagingSink 适配:暂存区在 DSH storage(per-record 表),工作区探针走 fs(只读)。 */
|
|
51
|
+
function makeStagingSink(workspaceRoot: string, getUnit: () => KvUnitLike | undefined, faults: EntryLedger): StagingSink {
|
|
52
|
+
const staged = new Map<string, string>(); // path -> content(暂存区内存面;storage 异步落盘)
|
|
53
|
+
const sha = (text: string): string => createHash('sha256').update(text, 'utf8').digest('hex');
|
|
54
|
+
const safeKey = (p: string): string => p.replace(/[^a-zA-Z0-9_-]/g, '_') || 'root';
|
|
55
|
+
return {
|
|
56
|
+
writeStaged(path, content) {
|
|
57
|
+
staged.set(path, content);
|
|
58
|
+
const receipt: StagedWriteReceipt = { path, hash: sha(content) };
|
|
59
|
+
void getUnit()
|
|
60
|
+
?.putRecord('staged', safeKey(path), { path, content })
|
|
61
|
+
.catch((error) => faults.push('staging-persist-error', { path, error: String(error) })); // diff/凭据以内存为准;落盘失败不静默
|
|
62
|
+
return receipt;
|
|
63
|
+
},
|
|
64
|
+
diffStaged() {
|
|
65
|
+
if (staged.size === 0) return '';
|
|
66
|
+
const differ = kernelDiffer(); // 复用内核逐行 diff(零业务逻辑重写)
|
|
67
|
+
const out: string[] = [];
|
|
68
|
+
for (const [path, content] of staged) {
|
|
69
|
+
const before = readWorkspace(path, workspaceRoot);
|
|
70
|
+
if (before === content) continue;
|
|
71
|
+
const hFrom = differ.put(before);
|
|
72
|
+
const hTo = differ.put(content);
|
|
73
|
+
out.push(differ.diff(hFrom, hTo));
|
|
74
|
+
}
|
|
75
|
+
return out.join('\n');
|
|
76
|
+
},
|
|
77
|
+
workspaceHash(path) {
|
|
78
|
+
return sha(readWorkspace(path, workspaceRoot));
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function readWorkspace(path: string, root: string): string {
|
|
84
|
+
try {
|
|
85
|
+
return readFileSync(join(root, path), 'utf8');
|
|
86
|
+
} catch {
|
|
87
|
+
return ''; // 不存在视为空串 hash(内核 StagingSink 契约 :74-75)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 默认声明(配置可覆盖);受治理集合 = 声明集合 ∪ tf-* 前缀。
|
|
92
|
+
* tf-code 本体按 read 级准入(程序内的 tools.write 绑定走宿主管线,各自受原生守卫治理)。 */
|
|
93
|
+
function defaultActions(): Record<string, Reversibility> {
|
|
94
|
+
return {
|
|
95
|
+
'tf-write': 'spec', write: 'spec',
|
|
96
|
+
'tf-read': 'read', read: 'read',
|
|
97
|
+
'tf-peek': 'read', 'tf-final': 'read',
|
|
98
|
+
'tf-bash': 'read', bash: 'read',
|
|
99
|
+
'tf-code': 'read',
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export const name = 'stream-agent-action-gate';
|
|
104
|
+
export const inject = ['tools', 'storage'];
|
|
105
|
+
|
|
106
|
+
export default function apply(ctx: HostCtxLike, config: ActionGateConfig = {}): ActionGateHandle {
|
|
107
|
+
const warn = makeWarn(ctx, 'action-gate');
|
|
108
|
+
const faults = new EntryLedger();
|
|
109
|
+
const workspaceRoot = config.workspaceRoot ?? process.cwd();
|
|
110
|
+
|
|
111
|
+
// staging unit 异步接驳(失败降级为纯内存暂存区,内核泄漏探测仍生效)
|
|
112
|
+
let unit: KvUnitLike | undefined;
|
|
113
|
+
const storage = getService<StorageLike>(ctx, 'storage');
|
|
114
|
+
openKvUnit(storage, config.unit ?? 'tfAgentStaging', ['staged'])
|
|
115
|
+
.then((opened) => {
|
|
116
|
+
unit = opened;
|
|
117
|
+
faults.push('staging-attached', { attached: unit !== undefined });
|
|
118
|
+
})
|
|
119
|
+
.catch((error) => faults.push('staging-degraded', { error: String(error) }));
|
|
120
|
+
|
|
121
|
+
const registry = new ActionRegistry();
|
|
122
|
+
const actions = config.actions ?? defaultActions();
|
|
123
|
+
for (const [action, rev] of Object.entries(actions)) registry.declare({ name: action, reversibility: rev });
|
|
124
|
+
registry.freeze(); // 装配期失败趁早暴露(缺声明在此抛 MissingReversibilityError)
|
|
125
|
+
const gate = new ActionGate({ registry, staging: makeStagingSink(workspaceRoot, () => unit, faults), clock: new SystemClock(), ...(config.credentialTtlMs === undefined ? {} : { credentialTtlMs: config.credentialTtlMs }) });
|
|
126
|
+
const mode = config.mode ?? 'stage-commit';
|
|
127
|
+
const governed = (name: string): boolean => name.startsWith('tf-') || name in actions;
|
|
128
|
+
|
|
129
|
+
/** 拒绝串:内核 reason/detail 原样内嵌("结构化可读理由,内核输出透传")。 */
|
|
130
|
+
const denial = (reason: string, detail: string): string => `[action-gate] ${reason}: ${detail}`;
|
|
131
|
+
|
|
132
|
+
/** spec/commit 级执行体的守卫翻译(stage-commit 闭环或 strict 透传)。 */
|
|
133
|
+
function gateSpecLevel(rev: 'spec' | 'commit', name: string, args: Record<string, unknown>): string | undefined {
|
|
134
|
+
const taskId = typeof args['__taskId'] === 'string' ? (args['__taskId'] as string) : 'ungoverned-task';
|
|
135
|
+
if (mode === 'strict') {
|
|
136
|
+
// strict 模式:两段式上移驱动器侧,守卫只透传内核 admit() 的拒绝语义。
|
|
137
|
+
// 内核 admit 是 async(fatal 批准通道),而 ToolGuard 是同步面——此处按内核
|
|
138
|
+
// gate.ts admit() :455-462 的 reason/detail 原文镜像,异步批准走 pre-execute waterfall(v2)。
|
|
139
|
+
const detail = rev === 'commit'
|
|
140
|
+
? `action "${name}" 是 commit 级:先由 spec 级动作产出一次性凭据,再走 gate.commit() 放行,不允许直接准入`
|
|
141
|
+
: `action "${name}" 是 spec 级:走 gate.speculate() 写暂存区并领取一次性凭据,不允许直接准入`;
|
|
142
|
+
return denial(rev === 'commit' ? 'commit-requires-credential' : 'spec-via-speculate', detail);
|
|
143
|
+
}
|
|
144
|
+
const writes = specWritesOf(args);
|
|
145
|
+
if (writes === null) return denial('unparseable-spec', `动作 "${name}" 的参数缺 file_path/path + content,无法落暂存区`);
|
|
146
|
+
const spec = gate.speculate({ action: name, taskId, writes });
|
|
147
|
+
if (spec.verdict === 'deny') return denial(spec.reason, spec.detail);
|
|
148
|
+
const commit = gate.commit({ action: name, taskId, credential: spec.credential }); // 一次性凭据即领即验
|
|
149
|
+
return commit.verdict === 'deny' ? denial(commit.rejection.reason, commit.rejection.detail) : undefined;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ---- ToolsService guard(F6;同步、只拒绝)--------------------------------
|
|
153
|
+
const guard = (execution: { name: string; arguments?: unknown }): string | undefined => {
|
|
154
|
+
try {
|
|
155
|
+
if (config.faultInjection === true) throw new Error('injected gate fault');
|
|
156
|
+
const name = execution.name;
|
|
157
|
+
let rev: Reversibility;
|
|
158
|
+
try {
|
|
159
|
+
rev = registry.reversibilityOf(name);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
// 未声明:受治理动作 deny(内核错误原文透传);宿主自有工具不表意见
|
|
162
|
+
return governed(name) ? denial('undeclared-reversibility', error instanceof Error ? error.message : String(error)) : undefined;
|
|
163
|
+
}
|
|
164
|
+
const args = (execution.arguments ?? {}) as Record<string, unknown>;
|
|
165
|
+
if (rev === 'read') return undefined; // 直接放行(内核 admit 的 read 语义)
|
|
166
|
+
if (rev === 'fatal') {
|
|
167
|
+
// 守卫是同步面,人工批准通道需异步 waterfall;headless v1 无通道 → 内核同款拒绝
|
|
168
|
+
return denial('fatal-no-approval-channel', `action "${name}" 是 fatal 级(不可逆),当前装配没有人工批准通道,直接拒绝`);
|
|
169
|
+
}
|
|
170
|
+
if (rev === 'commit') {
|
|
171
|
+
const credential = args['__credential'] as { id?: string } | undefined;
|
|
172
|
+
if (credential === undefined || typeof credential.id !== 'string') {
|
|
173
|
+
return denial('commit-requires-credential', `action "${name}" 是 commit 级:须携带 speculate 签发的一次性凭据(arguments.__credential.id)`);
|
|
174
|
+
}
|
|
175
|
+
const commit = gate.commit({ action: name, taskId: typeof args['__taskId'] === 'string' ? (args['__taskId'] as string) : 'ungoverned-task', credential: credential as unknown as CommitCredential });
|
|
176
|
+
return commit.verdict === 'deny' ? denial(commit.rejection.reason, commit.rejection.detail) : undefined;
|
|
177
|
+
}
|
|
178
|
+
return gateSpecLevel('spec', name, args); // 走到这里 rev 必为 spec(read/fatal/commit 已处理)
|
|
179
|
+
} catch (error) {
|
|
180
|
+
faults.push('gate_error', { action: execution?.name ?? '', error: error instanceof Error ? error.message : String(error) });
|
|
181
|
+
warn('守卫异常:放行(fail-open)', error);
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
if (typeof (ctx.get?.('tools') as { guard?: unknown } | undefined)?.guard !== 'function') {
|
|
187
|
+
throw new Error('[action-gate] ctx.tools.guard 不可用:无法接入工具管线(需要 dsh-tools 服务在位)');
|
|
188
|
+
}
|
|
189
|
+
(ctx.get('tools') as { guard(g: typeof guard): () => void }).guard(guard);
|
|
190
|
+
if (config.announce === true) console.error(`[action-gate] mounted: guard registered (actions: ${Object.keys(actions).join(',')}; mode=${mode})`);
|
|
191
|
+
|
|
192
|
+
return asPluginEffect({
|
|
193
|
+
registry,
|
|
194
|
+
gate,
|
|
195
|
+
faults,
|
|
196
|
+
dispose: () => {},
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** write 类参数 → SpecWrite[](dsh-tool-fs write schema:file_path/content;兼容 path)。 */
|
|
201
|
+
function specWritesOf(args: Record<string, unknown>): Array<{ path: string; content: string }> | null {
|
|
202
|
+
const path = args['file_path'] ?? args['path'];
|
|
203
|
+
const content = args['content'];
|
|
204
|
+
if (typeof path !== 'string' || path === '' || typeof content !== 'string') return null;
|
|
205
|
+
return [{ path, content }];
|
|
206
|
+
}
|