@hugesb/dsh-stream-agent 0.0.0-stage → 0.3.2
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 +622 -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 +4163 -0
- package/dist/entry/mock-provider.js +549 -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 +1081 -0
- package/dist/kernel/render.js +466 -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 +428 -0
- package/scripts/repair-session-logs.mjs +498 -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 +4163 -0
- package/src/entry/mock-provider.ts +549 -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 +1081 -0
- package/src/kernel/render.ts +466 -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/host-conformance.test.ts +418 -0
- package/test/kernel/obs.test.ts +329 -0
- package/test/kernel/parser.test.ts +451 -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/test/v032-conflict.test.ts +191 -0
- package/test/v032-truncation.test.ts +291 -0
- package/ui/client.js +576 -0
- package/ui/index.js +282 -0
- package/ui/package.json +26 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// entry/adapter-kit.ts —�?四个 07 �?entry 共用的适配胶水(分�?07�?//
|
|
2
|
+
// 不是业务逻辑,只有四类翻译助手:告警出口、entry 私有台账、文本提取�?// BlobSink �?DSH storage 桥。纪律与 loop.ts 一致:�?@deepseek-ai 静�?import�?// 宿主依赖全部 duck-type;内核只 import 公开接口(state.ts �?BlobSink/StateStore)�?
|
|
3
|
+
import { StateStore } from '../kernel/state.ts';
|
|
4
|
+
import type { BlobSink } from '../kernel/state.ts';
|
|
5
|
+
|
|
6
|
+
/** 告警出口签名(红�?5:不许静默)�?*/
|
|
7
|
+
export type Warn = (message: string, detail?: unknown) => void;
|
|
8
|
+
|
|
9
|
+
/** 宿主 logger �?duck-type 面(dsh-cordis-host-runner 装配;缺省落 stderr)�?*/
|
|
10
|
+
interface LoggerLike {
|
|
11
|
+
warn?(message: string): void;
|
|
12
|
+
error?(message: string): void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface HostCtxLike {
|
|
16
|
+
get?(service: string): unknown;
|
|
17
|
+
provide?(name: string, value: unknown): unknown;
|
|
18
|
+
on?(event: string, listener: (...args: never[]) => unknown): unknown;
|
|
19
|
+
effect?(fn: () => () => void, name?: string): unknown;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 可序列化的单条事实(Error �?message;对�?�?JSON)�?*/
|
|
23
|
+
export function detailString(detail: unknown): string {
|
|
24
|
+
if (detail instanceof Error) return detail.message;
|
|
25
|
+
if (typeof detail === 'string') return detail;
|
|
26
|
+
try {
|
|
27
|
+
return JSON.stringify(detail);
|
|
28
|
+
} catch {
|
|
29
|
+
return String(detail);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 告警出口:优先宿�?logger,否�?stderr(与 loop.ts �?apply 同款,绝不静默)�?*/
|
|
34
|
+
export function makeWarn(ctx: HostCtxLike, tag: string): Warn {
|
|
35
|
+
return (message, detail) => {
|
|
36
|
+
const logger = (ctx.get?.('logger') ?? null) as LoggerLike | null;
|
|
37
|
+
const text = `[${tag}] ${message}${detail === undefined ? '' : ` :: ${detailString(detail)}`}`;
|
|
38
|
+
if (logger?.warn !== undefined) logger.warn(text);
|
|
39
|
+
else console.error(text);
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** entry 私有台账:内�?append-only 事实流(红线 5 �?不许静默"载体)�?*/
|
|
44
|
+
export class EntryLedger {
|
|
45
|
+
readonly records: Array<{ seq: number; at: number; kind: string; data: Record<string, unknown> }> = [];
|
|
46
|
+
#seq = 0;
|
|
47
|
+
|
|
48
|
+
push(kind: string, data: Record<string, unknown> = {}): void {
|
|
49
|
+
this.records.push({ seq: ++this.#seq, at: Date.now(), kind, data });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
count(kind: string): number {
|
|
53
|
+
return this.records.filter((r) => r.kind === kind).length;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** ContentBlock[](dsh-llm/lib/types/types.d.ts �?text 块族)→ 纯文本�?*/
|
|
58
|
+
export function contentTextOf(content: unknown): string {
|
|
59
|
+
if (content === undefined || content === null) return '';
|
|
60
|
+
if (typeof content === 'string') return content;
|
|
61
|
+
if (Array.isArray(content)) {
|
|
62
|
+
return content
|
|
63
|
+
.map((block) => {
|
|
64
|
+
if (typeof block === 'string') return block;
|
|
65
|
+
if (block !== null && typeof block === 'object' && 'text' in block && typeof (block as { text?: unknown }).text === 'string') {
|
|
66
|
+
return (block as { text: string }).text;
|
|
67
|
+
}
|
|
68
|
+
return '';
|
|
69
|
+
})
|
|
70
|
+
.filter((t) => t !== '')
|
|
71
|
+
.join('\n');
|
|
72
|
+
}
|
|
73
|
+
return String(content);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 线格式消息(GenerateOptions.messages)→ 拼接文本(content �?text 块数组)�?*/
|
|
77
|
+
export function wireMessageText(m: { content: readonly { type: string; text?: string }[] }): string {
|
|
78
|
+
return m.content.map((b) => (typeof b?.text === 'string' ? b.text : '')).join('\n');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ---------------------------------------------------------------------------
|
|
82
|
+
// BlobSink �?DSH storage 桥(state-handle / obs-broker 共用�?IO 胶水,非业务逻辑�?// ---------------------------------------------------------------------------
|
|
83
|
+
|
|
84
|
+
/** 镜像 dsh-storage/lib/types/backend.d.ts KvUnit(rc.1 :82-159;duck-type�?*/
|
|
85
|
+
export interface KvUnitLike {
|
|
86
|
+
loadAll(): Promise<{ tables: Record<string, Record<string, unknown>>; global: unknown }>;
|
|
87
|
+
putRecord(table: string, key: string, value: unknown): Promise<void>;
|
|
88
|
+
close(): Promise<void>;
|
|
89
|
+
}
|
|
90
|
+
/** 镜像 dsh-storage/lib/types/index.d.ts Storage + registry.d.ts BackendRegistry(duck-type�?*/
|
|
91
|
+
export interface StorageLike {
|
|
92
|
+
backend?: { get(name: string): { kv?: { open(descriptor: unknown): Promise<KvUnitLike> } } };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* per-record 布局的表键须匹配 [a-zA-Z0-9_-]+(backend.d.ts:96-98),而键族含
|
|
97
|
+
* sha256 hex(天然安全)与句柄串(含 ':' '@' '/')——统一确定性净化;
|
|
98
|
+
* read 走同一映射。理论碰撞('a:b' vs 'a_b')对内容寻址键族不构成实际问题,如实记录�? */
|
|
99
|
+
export function safeKvKey(key: string): string {
|
|
100
|
+
return key.replace(/[^a-zA-Z0-9_-]/g, '_') || 'root';
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function bytesToB64(data: Uint8Array): string {
|
|
104
|
+
return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString('base64');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function b64ToBytes(b64: string): Uint8Array {
|
|
108
|
+
const buf = Buffer.from(b64, 'base64');
|
|
109
|
+
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 内核 BlobSink 适配:内存覆盖读 + 写回后异�?putRecord 持久�? * 内核 write 是同�?void——异步层不回压,持久化失败告警留痕不毁任务(红线 5)�? * attach() 前写入只进内存(fail-open 降级窗口);attach 时用持久层水合内存�? */
|
|
114
|
+
export class DurableBlobSink implements BlobSink {
|
|
115
|
+
readonly #mem = new Map<string, Uint8Array>();
|
|
116
|
+
readonly #warn: Warn;
|
|
117
|
+
readonly #onFault: (kind: string, data: Record<string, unknown>) => void;
|
|
118
|
+
#unit: KvUnitLike | undefined;
|
|
119
|
+
#pending: Array<Promise<void>> = [];
|
|
120
|
+
|
|
121
|
+
constructor(warn: Warn, onFault: (kind: string, data: Record<string, unknown>) => void) {
|
|
122
|
+
this.#warn = warn;
|
|
123
|
+
this.#onFault = onFault;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
get attached(): boolean {
|
|
127
|
+
return this.#unit !== undefined;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
attach(unit: KvUnitLike, hydrate: Array<[string, Uint8Array]>): void {
|
|
131
|
+
this.#unit = unit;
|
|
132
|
+
for (const [key, data] of hydrate) this.#mem.set(key, data);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
write(key: string, data: Uint8Array): void {
|
|
136
|
+
this.#mem.set(key, data);
|
|
137
|
+
const unit = this.#unit;
|
|
138
|
+
if (unit === undefined) return;
|
|
139
|
+
const put = unit
|
|
140
|
+
.putRecord('blobs', safeKvKey(key), { b64: bytesToB64(data) })
|
|
141
|
+
.catch((error) => {
|
|
142
|
+
this.#onFault('persist-error', { key, error: String(error) });
|
|
143
|
+
this.#warn(`blob ${key.slice(0, 12)}�?持久化失败(内存继续服务)`, error);
|
|
144
|
+
});
|
|
145
|
+
this.#pending.push(put);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
read(key: string): Uint8Array | undefined {
|
|
149
|
+
return this.#mem.get(key);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 内核 obs �?BlobSink 面(put(ref, string))桥接�?*/
|
|
153
|
+
asTextSink(): { put(ref: string, content: string): void; readRaw(ref: string): string | undefined } {
|
|
154
|
+
const encoder = new TextEncoder();
|
|
155
|
+
const decoder = new TextDecoder();
|
|
156
|
+
return {
|
|
157
|
+
put: (ref, content) => this.write(ref, encoder.encode(content)),
|
|
158
|
+
readRaw: (ref) => {
|
|
159
|
+
const data = this.read(ref);
|
|
160
|
+
return data === undefined ? undefined : decoder.decode(data);
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async flush(): Promise<void> {
|
|
166
|
+
await Promise.allSettled([...this.#pending]);
|
|
167
|
+
this.#pending = [];
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** 从持久层水合 blobs �?�?attach 用的键值对(state-handle 启动路径)�?*/
|
|
172
|
+
export function hydrateFromUnit(unit: KvUnitLike): Promise<Array<[string, Uint8Array]>> {
|
|
173
|
+
return unit.loadAll().then((all) => {
|
|
174
|
+
const out: Array<[string, Uint8Array]> = [];
|
|
175
|
+
for (const [key, value] of Object.entries(all.tables['blobs'] ?? {})) {
|
|
176
|
+
const b64 = (value as { b64?: unknown })?.b64;
|
|
177
|
+
if (typeof b64 === 'string') out.push([key, b64ToBytes(b64)]);
|
|
178
|
+
}
|
|
179
|
+
return out;
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** 打开 staging/state 共用�?KvUnit(后端固�?'json';失败返�?undefined 由调用方降级)�?*/
|
|
184
|
+
export async function openKvUnit(storage: StorageLike | undefined, unit: string, tables: readonly string[]): Promise<KvUnitLike | undefined> {
|
|
185
|
+
return (await storage?.backend?.get('json')?.kv?.open({ name: unit, version: 1, tables: [...tables], hasGlobal: false, layout: 'per-record' })) ?? undefined;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** 复用内核逐行 diff 的临时载体(action-gate diffStaged 用;零业务逻辑重写)�?*/
|
|
189
|
+
export function kernelDiffer(): StateStore {
|
|
190
|
+
return new StateStore();
|
|
191
|
+
}
|
|
192
|
+
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// entry/context-render.ts —— 装配器接入(M5 适配,分派 07)
|
|
2
|
+
//
|
|
3
|
+
// 形态判定(任务书:"若 06 号 loop 完整接管装配,本 entry 退化为 pre-request 断言器
|
|
4
|
+
// (只跑 O6 preflight)——以 06 的实际形态为准"):06 驱动器经内核 ContextRenderer
|
|
5
|
+
// 全权装配(稳定前缀/追加区/易变尾、O3 差分、O5 阶梯、O6 内置断言),本插件请求路径上
|
|
6
|
+
// 不存在 SystemPromptProjection 注入(dsh-agent-loop/lib/types/runtime-context.d.ts 的
|
|
7
|
+
// 前缀稳定设计目标与本 entry 方向一致,但不适用于 loop-built 请求)。因此本 entry 是:
|
|
8
|
+
// 1. llm/stream waterfall 上的 O6 pre-request 断言器(宿主边界的第二道独立见证):
|
|
9
|
+
// 逐会话断言首条消息(稳定前缀 system)逐字节不变——凡有逐请求动态字段漏进稳定前缀
|
|
10
|
+
// (O4 破坏),第二次请求必在此被拒;违反 → 内核 PrefixBrokenError 原样上抛(fail-closed,
|
|
11
|
+
// 拒绝发送,宁可任务失败不烧缓存);逐请求落 prefix 台账(08 号 prefix_hash 序列数据源)。
|
|
12
|
+
// 2. freezeDynamics(O4)出口:内核 ContextRenderer 的动态冻结语义对非 loop 装配路径
|
|
13
|
+
// 开放(volatile-tail / turn-freeze;稳定前缀结构性禁入)。
|
|
14
|
+
// fail-open(红线 5):断言器自身异常 → 放行 + ledger 记 preflight_error;
|
|
15
|
+
// 前缀破坏是策略违规不是自身异常——fail-closed 上抛,两者严格区分。
|
|
16
|
+
|
|
17
|
+
import { assertPrefixStable, PrefixBrokenError, renderHash, ContextRenderer } from '../kernel/render.ts';
|
|
18
|
+
import type { RenderMessage, DynamicPlacement } from '../kernel/render.ts';
|
|
19
|
+
import { makeWarn, EntryLedger, wireMessageText } from './adapter-kit.ts';
|
|
20
|
+
import type { HostCtxLike, Warn } from './adapter-kit.ts';
|
|
21
|
+
import { asPluginEffect } from './cordis-compat.ts';
|
|
22
|
+
|
|
23
|
+
/** 镜像 dsh-llm GenerateOptions(读子集;types.d.ts:538-580) */
|
|
24
|
+
interface WireOptions {
|
|
25
|
+
messages?: readonly { role?: string; content: unknown }[];
|
|
26
|
+
sessionId?: string;
|
|
27
|
+
}
|
|
28
|
+
type StreamListener = (options: WireOptions, next: () => AsyncIterable<unknown>) => AsyncIterable<unknown>;
|
|
29
|
+
|
|
30
|
+
/** 线格式消息 → 内核 RenderMessage(content text 块拼接)。 */
|
|
31
|
+
function toRenderMessage(m: { role?: string; content: unknown }): RenderMessage {
|
|
32
|
+
const text = wireMessageText(m as { content: readonly { type: string; text?: string }[] });
|
|
33
|
+
return { role: (m.role ?? 'user') as RenderMessage['role'], content: text };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface ContextRenderHandle {
|
|
37
|
+
/** O6 断言器本体(宿主 waterfall 之外的调用方也可显式调用)。 */
|
|
38
|
+
preflight(messages: readonly RenderMessage[], sessionId: string): { request: number; stableHash: string; fullHash: string };
|
|
39
|
+
/** O4 动态冻结出口(内核 ContextRenderer 语义;见 kernel/render.ts :267-288)。 */
|
|
40
|
+
freezeDynamics(dynamics: Record<string, string>, placement: DynamicPlacement): void;
|
|
41
|
+
faults: EntryLedger;
|
|
42
|
+
dispose: () => void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface ContextRenderConfig {
|
|
46
|
+
/** freezeDynamics 的载体 renderer(默认内置空 renderer,仅承载动态冻结语义) */
|
|
47
|
+
system?: string;
|
|
48
|
+
/** 测试注错位:断言体抛非前缀异常(fail-open 验证用;生产不得设置) */
|
|
49
|
+
faultInjection?: boolean;
|
|
50
|
+
/** 装载自证横幅(排障用;preset/patch 激活对 CLI 静默,探针 A 惯例) */
|
|
51
|
+
announce?: boolean;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const name = 'stream-agent-context-render';
|
|
55
|
+
export const inject = [];
|
|
56
|
+
|
|
57
|
+
export default function apply(ctx: HostCtxLike, config: ContextRenderConfig = {}): ContextRenderHandle {
|
|
58
|
+
const warn = makeWarn(ctx, 'context-render');
|
|
59
|
+
const faults = new EntryLedger();
|
|
60
|
+
/** 会话 → 首请求快照(首条消息 = 稳定前缀 system;逐字节冻结)。 */
|
|
61
|
+
const sessions = new Map<string, { first: RenderMessage; requests: number }>();
|
|
62
|
+
const freezeRenderer = new ContextRenderer({
|
|
63
|
+
system: config.system ?? '(stream-agent context-render:动态冻结载体,稳定前缀无业务内容)',
|
|
64
|
+
protocol: '', toolSchemas: '', invariants: '',
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
const preflight = (messages: readonly RenderMessage[], sessionId: string): { request: number; stableHash: string; fullHash: string } => {
|
|
68
|
+
if (messages.length === 0) throw new PrefixBrokenError(0, '非空消息序列', '空序列', ':preflight 拒绝空请求');
|
|
69
|
+
const first = messages[0];
|
|
70
|
+
const state = sessions.get(sessionId);
|
|
71
|
+
if (state === undefined) {
|
|
72
|
+
sessions.set(sessionId, { first, requests: 1 });
|
|
73
|
+
} else {
|
|
74
|
+
// O6 fail-closed:稳定前缀逐字节断言(内核校验器原样使用,不静默修复)
|
|
75
|
+
assertPrefixStable([state.first], [first]);
|
|
76
|
+
state.requests += 1;
|
|
77
|
+
}
|
|
78
|
+
const stableHash = renderHash([first]);
|
|
79
|
+
const fullHash = renderHash(messages);
|
|
80
|
+
faults.push('prefix', {
|
|
81
|
+
session: sessionId,
|
|
82
|
+
request: state?.requests ?? 1,
|
|
83
|
+
stableHash,
|
|
84
|
+
fullHash,
|
|
85
|
+
messages: messages.length,
|
|
86
|
+
});
|
|
87
|
+
return { request: state?.requests ?? 1, stableHash, fullHash };
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const onStream: StreamListener = (options, next) => {
|
|
91
|
+
try {
|
|
92
|
+
if (config.faultInjection === true) throw new Error('injected preflight fault');
|
|
93
|
+
if (options.messages !== undefined && options.messages.length > 0) {
|
|
94
|
+
preflight(options.messages.map(toRenderMessage), options.sessionId ?? '');
|
|
95
|
+
}
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (error instanceof PrefixBrokenError) {
|
|
98
|
+
// 策略违规:fail-closed,拒绝发送(宁可任务失败不烧缓存——README O6 原文语义)
|
|
99
|
+
faults.push('prefix-broken', { session: options.sessionId ?? '', error: error.message });
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
// 断言器自身异常:fail-open,放行不静默(红线 5)
|
|
103
|
+
faults.push('preflight_error', { error: error instanceof Error ? error.message : String(error) });
|
|
104
|
+
warn('preflight 异常:请求放行(fail-open)', error);
|
|
105
|
+
}
|
|
106
|
+
return next();
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
if (typeof ctx.on !== 'function') throw new Error('[context-render] ctx.on 不可用:无法挂载 llm/stream 断言器');
|
|
110
|
+
ctx.on('llm/stream', onStream as unknown as (...args: never[]) => unknown);
|
|
111
|
+
if (config.announce === true) console.error('[context-render] mounted: llm/stream O6 preflight asserter');
|
|
112
|
+
|
|
113
|
+
return asPluginEffect({
|
|
114
|
+
preflight,
|
|
115
|
+
freezeDynamics: (dynamics, placement) => freezeRenderer.freezeDynamics(dynamics, placement),
|
|
116
|
+
faults,
|
|
117
|
+
dispose: () => {},
|
|
118
|
+
});
|
|
119
|
+
}
|