taskboard-workbench 0.3.1 → 0.3.3
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 +101 -2
- package/index.js +112 -13
- package/package.json +6 -2
- package/scripts/tb-flow.mjs +109 -8
- package/skills/taskboard-flow/SKILL.md +2 -2
- package/skills/taskboard-flow/references/injection.md +76 -29
- package/skills/taskboard-flow/references/steps/S5.md +21 -1
- package/spec/docs/01-/351/241/271/347/233/256/345/274/200/345/261/200.md +63 -0
- package/spec/docs/02-/346/265/201/347/250/213/346/211/247/350/241/214/344/270/216/346/235/241/347/233/256.md +110 -0
- package/spec/docs/README.md +36 -0
- package/spec/docs/assets//346/235/241/347/233/256/350/257/246/346/203/205/346/250/241/346/235/277.md +105 -0
- package/spec/norms/item-detail.md +73 -0
- package/spec/norms/manifest.json +7 -0
- package/src/core/config.mjs +12 -3
- package/src/core/contract.mjs +17 -7
- package/src/core/data-dir-hint.mjs +52 -0
- package/src/core/docs-assets.mjs +135 -0
- package/src/core/errors.mjs +11 -0
- package/src/core/evidence.mjs +28 -0
- package/src/core/executor.mjs +27 -7
- package/src/core/executors.mjs +279 -0
- package/src/core/flow-inject.mjs +190 -0
- package/src/core/instance-lease.mjs +113 -0
- package/src/core/kickoff.mjs +289 -0
- package/src/core/norms.mjs +177 -0
- package/src/core/requirements.mjs +38 -0
- package/src/core/store.mjs +333 -36
- package/src/core/verify.mjs +39 -4
- package/src/mcp/flow-block.mjs +30 -0
- package/src/mcp/server.mjs +19 -6
- package/src/mcp/tools.mjs +99 -7
- package/src/server/api.mjs +361 -11
- package/web/app.js +1077 -82
- package/web/tokens.css +166 -28
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* executors.mjs —— **执行者注册表(唯一真源)**。
|
|
3
|
+
*
|
|
4
|
+
* 背景(卡 `-238` / 需求 `R174`,2026-11-10 真机批注):「用哪个执行者跑这一张卡」当时只能靠
|
|
5
|
+
* **项目级** `teamTemplate.roles[].executor` 决定 —— 人在卡片上看到的只有一句「交给 CLI 执行器执行」,
|
|
6
|
+
* 想换执行者得先去配置页改项目设置、再回来重新点,且换不了「这一次」。本模块把执行者做成**一张表**:
|
|
7
|
+
* 前端只渲染这张表给的 `id`,服务端只在收到 `id` 时按表解析 —— **两边都不再散落执行者知识**。
|
|
8
|
+
*
|
|
9
|
+
* 四条通道的真实能力(2026-11-10 逐条读 `--help` 实测,**不猜**):
|
|
10
|
+
* · `team` —— 团队派发(`POST /api/teams`),执行者由项目 `executionTeam` 与 roles 决定
|
|
11
|
+
* · `host:dsh` —— 宿主会话执行(`POST /api/tasks/:ref/execute`)。**`dsh` 没有 oneshot 入口**
|
|
12
|
+
* (`dsh [--profile] <name>` 是启动宿主、`dsh plugin` 是管插件),
|
|
13
|
+
* 故它**只能**映射到既有的宿主会话通道,**不伪造一个 `dsh -p` 出来**
|
|
14
|
+
* · `cli:claude` —— `claude -p --permission-mode acceptEdits --allowedTools … --add-dir <cwd>`(既有通道)
|
|
15
|
+
* · `cli:codex` —— `codex exec -s workspace-write -C <cwd> -`(prompt 走 stdin,`-` 显式声明)
|
|
16
|
+
* · `cli:hermes` —— `hermes -z <prompt> --in <cwd> --yolo`(`-z` 一次一答、`--yolo` 跳审批;
|
|
17
|
+
* **prompt 走 argv**——该 CLI 的单次入口不吃 stdin)
|
|
18
|
+
*
|
|
19
|
+
* 纪律:
|
|
20
|
+
* · 纯 Node 内置模块,零依赖;探测可注入(`detect` / `now`),便于单测造「未安装」。
|
|
21
|
+
* · **不自己 spawn 干活**:参数只负责**描述**怎么调用,真正 spawn 仍在 `executor.mjs`(一处执行)。
|
|
22
|
+
* · `forbiddenExecutors` **优先级最高**:项目禁掉的执行者,按卡选也一律不可用。
|
|
23
|
+
*/
|
|
24
|
+
import { execFile } from "node:child_process";
|
|
25
|
+
import { accessSync, constants as FS, statSync } from "node:fs";
|
|
26
|
+
import { homedir } from "node:os";
|
|
27
|
+
import { delimiter, join } from "node:path";
|
|
28
|
+
|
|
29
|
+
// 参数真源复用既有 claude 通道(含 `teamTemplate.engineer.args` 整体覆盖语义)——**不抄第二份**。
|
|
30
|
+
import { cliArgsFor } from "./executor.mjs";
|
|
31
|
+
|
|
32
|
+
/** 执行者形态:团队派发 / 宿主会话 / CLI 子进程。 */
|
|
33
|
+
export const EXECUTOR_KINDS = Object.freeze({
|
|
34
|
+
TEAM: "team",
|
|
35
|
+
HOST_SESSION: "host-session",
|
|
36
|
+
CLI: "cli",
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
/** 探测缓存 TTL:60s(同一台机器上「装没装」不会秒级变化,但人装完不该等重启)。 */
|
|
40
|
+
export const DETECT_TTL_MS = 60 * 1000;
|
|
41
|
+
/**
|
|
42
|
+
* `--version` 探测超时:2s。
|
|
43
|
+
*
|
|
44
|
+
* 为什么只有 2s 且**并行**:真机实测 `hermes --version` **不退出**(超过 10s 仍在跑,只能杀掉)——
|
|
45
|
+
* 串行 + 长超时会让「打开抽屉」卡住好几秒去等一个**只用于 tooltip** 的字段。
|
|
46
|
+
* 版本拿不到就是 `null`,绝不为它拖慢接口。
|
|
47
|
+
*/
|
|
48
|
+
export const VERSION_TIMEOUT_MS = 2000;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 探测路径(**只用于探测与取绝对路径,不改 `process.env.PATH`**)。
|
|
52
|
+
*
|
|
53
|
+
* 为什么不能只按 `PATH`:宿主(`dsh web`)常由 launchd 拉起,`PATH` 往往只有
|
|
54
|
+
* `/usr/bin:/bin:/usr/sbin:/sbin` —— 用户在终端里跑得好好的 `claude` / `codex` / `hermes`
|
|
55
|
+
* 一个都不在。只按 PATH 判会把「装了」误报成「没装」,界面上就是**一排全灰的图标**
|
|
56
|
+
* (人只会以为功能坏了,不会想到是 PATH 不全)。
|
|
57
|
+
*/
|
|
58
|
+
export function executorSearchDirs({ env = process.env } = {}) {
|
|
59
|
+
const dirs = new Set();
|
|
60
|
+
const push = (value) => {
|
|
61
|
+
const dir = String(value ?? "").trim();
|
|
62
|
+
if (dir) dirs.add(dir);
|
|
63
|
+
};
|
|
64
|
+
for (const dir of String(env?.PATH ?? "").split(delimiter)) push(dir);
|
|
65
|
+
const home = String(env?.HOME ?? "") || homedir();
|
|
66
|
+
push(join(home, ".npm-global", "bin"));
|
|
67
|
+
push(join(home, ".local", "bin"));
|
|
68
|
+
push(join(home, ".bun", "bin"));
|
|
69
|
+
push(join(home, ".cargo", "bin"));
|
|
70
|
+
push("/opt/homebrew/bin");
|
|
71
|
+
push("/usr/local/bin");
|
|
72
|
+
push("/usr/bin");
|
|
73
|
+
return [...dirs];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const detectCache = new Map();
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 探测某个命令是否可执行,并给出**绝对路径**(拿到就优先用它 spawn:launchd 的 PATH 问题就绕开了)。
|
|
80
|
+
* @returns {{ installed: boolean, binPath: string|null, searched: string[] }}
|
|
81
|
+
*/
|
|
82
|
+
export function detectBinary(command, { env = process.env, now = () => Date.now(), ttlMs = DETECT_TTL_MS, fresh = false, searchDirs = null } = {}) {
|
|
83
|
+
const name = String(command ?? "").trim();
|
|
84
|
+
if (!name) return { installed: false, binPath: null, searched: [] };
|
|
85
|
+
const dirs = searchDirs ?? executorSearchDirs({ env });
|
|
86
|
+
const key = `${name}\u0000${dirs.join("\u0000")}`;
|
|
87
|
+
const hit = detectCache.get(key);
|
|
88
|
+
if (!fresh && hit && now() - hit.at < ttlMs) return hit.value;
|
|
89
|
+
let binPath = null;
|
|
90
|
+
for (const dir of dirs) {
|
|
91
|
+
const candidate = join(dir, name);
|
|
92
|
+
try {
|
|
93
|
+
// 仅 `access(X_OK)` 不够:同名**目录**也过。必须确认是常规文件(符号链接跟随)。
|
|
94
|
+
if (!statSync(candidate).isFile()) continue;
|
|
95
|
+
accessSync(candidate, FS.X_OK);
|
|
96
|
+
binPath = candidate;
|
|
97
|
+
break;
|
|
98
|
+
} catch { /* 换下一个目录 */ }
|
|
99
|
+
}
|
|
100
|
+
const value = { installed: Boolean(binPath), binPath, searched: dirs };
|
|
101
|
+
detectCache.set(key, { at: now(), value });
|
|
102
|
+
return value;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 清探测缓存(测试与「刚装完想立刻看到」用)。 */
|
|
106
|
+
export function resetExecutorDetectCache() { detectCache.clear(); }
|
|
107
|
+
|
|
108
|
+
/** 读版本号(拿不到就是 `null`,**不抛**:版本只用于 tooltip,不应让接口失败)。 */
|
|
109
|
+
export function readBinaryVersion(binPath, { timeoutMs = VERSION_TIMEOUT_MS, execFileImpl = execFile } = {}) {
|
|
110
|
+
return new Promise((resolve) => {
|
|
111
|
+
if (!binPath) { resolve(null); return; }
|
|
112
|
+
try {
|
|
113
|
+
execFileImpl(binPath, ["--version"], { timeout: timeoutMs, encoding: "utf8", maxBuffer: 256 * 1024 }, (error, stdout, stderr) => {
|
|
114
|
+
if (error) { resolve(null); return; }
|
|
115
|
+
const line = String(stdout ?? "").trim().split("\n")[0] || String(stderr ?? "").trim().split("\n")[0] || "";
|
|
116
|
+
resolve(line ? line.slice(0, 80) : null);
|
|
117
|
+
});
|
|
118
|
+
} catch { resolve(null); }
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* 注册表本体。**顺序即界面顺序**(团队 → dsh → claude → codex → hermes)。
|
|
124
|
+
* `buildArgs` 只在 `kind === "cli"` 上有意义;`promptVia` 说明这条 CLI 的指令怎么给(`stdin` / `argv`)。
|
|
125
|
+
*/
|
|
126
|
+
export const EXECUTOR_SPECS = Object.freeze([
|
|
127
|
+
Object.freeze({
|
|
128
|
+
id: "team",
|
|
129
|
+
agent: "team",
|
|
130
|
+
kind: EXECUTOR_KINDS.TEAM,
|
|
131
|
+
label: "团队",
|
|
132
|
+
hint: "派发给项目执行团队(角色与成员由项目 executionTeam / teamTemplate 决定)",
|
|
133
|
+
command: null,
|
|
134
|
+
promptVia: null,
|
|
135
|
+
}),
|
|
136
|
+
Object.freeze({
|
|
137
|
+
id: "host:dsh",
|
|
138
|
+
agent: "dsh",
|
|
139
|
+
kind: EXECUTOR_KINDS.HOST_SESSION,
|
|
140
|
+
label: "DSH 宿主会话",
|
|
141
|
+
hint: "投给项目主会话执行(dsh 没有 oneshot 入口,故走宿主会话通道,不伪造 CLI)",
|
|
142
|
+
command: "dsh",
|
|
143
|
+
promptVia: null,
|
|
144
|
+
}),
|
|
145
|
+
Object.freeze({
|
|
146
|
+
id: "cli:claude",
|
|
147
|
+
agent: "claude",
|
|
148
|
+
kind: EXECUTOR_KINDS.CLI,
|
|
149
|
+
label: "Claude Code",
|
|
150
|
+
hint: "claude -p(非交互;参数可被 teamTemplate.engineer.args 整体覆盖)",
|
|
151
|
+
command: "claude",
|
|
152
|
+
promptVia: "stdin",
|
|
153
|
+
buildArgs: ({ cwd, settings }) => cliArgsFor({ executorId: "cli:claude", cwd, settings }),
|
|
154
|
+
}),
|
|
155
|
+
Object.freeze({
|
|
156
|
+
id: "cli:codex",
|
|
157
|
+
agent: "codex",
|
|
158
|
+
kind: EXECUTOR_KINDS.CLI,
|
|
159
|
+
label: "Codex",
|
|
160
|
+
hint: "codex exec(workspace-write 沙箱;prompt 走 stdin)",
|
|
161
|
+
command: "codex",
|
|
162
|
+
promptVia: "stdin",
|
|
163
|
+
buildArgs: ({ cwd }) => ["exec", "-s", "workspace-write", "-C", cwd, "-"],
|
|
164
|
+
}),
|
|
165
|
+
Object.freeze({
|
|
166
|
+
id: "cli:hermes",
|
|
167
|
+
agent: "hermes",
|
|
168
|
+
kind: EXECUTOR_KINDS.CLI,
|
|
169
|
+
label: "Hermes",
|
|
170
|
+
hint: "hermes -z(一次一答、跳审批;prompt 走 argv)",
|
|
171
|
+
command: "hermes",
|
|
172
|
+
promptVia: "argv",
|
|
173
|
+
buildArgs: ({ cwd, prompt }) => ["-z", String(prompt ?? ""), "--in", cwd, "--yolo"],
|
|
174
|
+
}),
|
|
175
|
+
]);
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* 执行者 id 归一:既接受全标识(`cli:codex` / `host:dsh`),也接受裸的 agent 名(`codex` / `dsh` / `team`)。
|
|
179
|
+
* 裸名只在**唯一命中**时归一;命中不了原样返回(交给上层判「未知执行者」)。
|
|
180
|
+
*/
|
|
181
|
+
export function normalizeExecutorId(raw) {
|
|
182
|
+
const text = String(raw ?? "").trim();
|
|
183
|
+
if (!text) return null;
|
|
184
|
+
if (text.includes(":")) return text;
|
|
185
|
+
const hits = EXECUTOR_SPECS.filter((spec) => spec.agent === text || spec.id === text);
|
|
186
|
+
return hits.length === 1 ? hits[0].id : text;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 按 id / 裸名找注册项(找不到回 `null`,**不抛** —— 抛什么错误归路由层定)。 */
|
|
190
|
+
export function findExecutorSpec(raw) {
|
|
191
|
+
const id = normalizeExecutorId(raw);
|
|
192
|
+
if (!id) return null;
|
|
193
|
+
return EXECUTOR_SPECS.find((spec) => spec.id === id) ?? null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** 项目的禁用清单(`teamTemplate.forbiddenExecutors`)——全标识与裸 agent 名都算命中。 */
|
|
197
|
+
export function forbiddenSetOf(settings) {
|
|
198
|
+
return new Set((settings?.teamTemplate?.forbiddenExecutors ?? []).map((x) => String(x)));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function isExecutorForbidden(spec, settings) {
|
|
202
|
+
if (!spec) return false;
|
|
203
|
+
const forbidden = forbiddenSetOf(settings);
|
|
204
|
+
return forbidden.has(spec.id) || forbidden.has(spec.agent);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* CLI 参数(传 `prompt` 是因为 hermes 走 argv)。
|
|
209
|
+
* 非 CLI 形态回 `null`(团队 / 宿主会话不 spawn 子进程)。
|
|
210
|
+
*/
|
|
211
|
+
export function buildExecutorArgs(spec, { cwd = null, settings = null, prompt = "" } = {}) {
|
|
212
|
+
if (!spec || spec.kind !== EXECUTOR_KINDS.CLI || typeof spec.buildArgs !== "function") return null;
|
|
213
|
+
const args = spec.buildArgs({ cwd, settings, prompt });
|
|
214
|
+
return Array.isArray(args) ? args.map(String) : null;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* 列出全部执行者及**当下能不能用**。
|
|
219
|
+
*
|
|
220
|
+
* 三处「不可用」要分开说清,别混成一句「不可用」:
|
|
221
|
+
* · 未安装(CLI 找不到可执行文件)—— 人能自己装
|
|
222
|
+
* · 被项目禁用(`forbiddenExecutors`)—— 要改项目设置,**优先级最高**
|
|
223
|
+
* · 通道不成立(宿主实例没有会话通道 / 项目没配执行团队)—— 换环境或先配团队
|
|
224
|
+
*
|
|
225
|
+
* `hostSessionAvailable` / `teamAvailable` 传 `null` 表示「**判不准**」——按可用处理,
|
|
226
|
+
* 不把「不知道」冒充成「不可用」(本仓既有纪律:判不准时不得谎报失效)。
|
|
227
|
+
*/
|
|
228
|
+
export async function listExecutors({
|
|
229
|
+
settings = null, hostSessionAvailable = null, teamAvailable = null,
|
|
230
|
+
env = process.env, withVersion = true, now = () => Date.now(), fresh = false,
|
|
231
|
+
detect = null, readVersion = readBinaryVersion, versionTimeoutMs = VERSION_TIMEOUT_MS,
|
|
232
|
+
} = {}) {
|
|
233
|
+
const forbidden = forbiddenSetOf(settings);
|
|
234
|
+
const probeOf = detect ?? ((command, opts) => detectBinary(command, opts));
|
|
235
|
+
// 第一遍:形态与安装态(同步、无子进程)。
|
|
236
|
+
const rows = EXECUTOR_SPECS.map((spec) => {
|
|
237
|
+
let installed = true;
|
|
238
|
+
let binPath = null;
|
|
239
|
+
let reason = null;
|
|
240
|
+
if (spec.kind === EXECUTOR_KINDS.CLI) {
|
|
241
|
+
const probe = probeOf(spec.command, { env, now, fresh });
|
|
242
|
+
installed = Boolean(probe?.installed);
|
|
243
|
+
binPath = probe?.binPath ?? null;
|
|
244
|
+
if (!installed) reason = `未检测到 ${spec.command}(已查 PATH · ~/.npm-global/bin · ~/.local/bin · /opt/homebrew/bin)`;
|
|
245
|
+
} else if (spec.kind === EXECUTOR_KINDS.HOST_SESSION) {
|
|
246
|
+
// `null` = 判不准 ⇒ 按可用处理(不把「不知道」冒充成「不可用」)。
|
|
247
|
+
installed = hostSessionAvailable !== false;
|
|
248
|
+
if (installed === false) reason = "宿主会话通道不可用(该实例没有 sessionController / prompt:独立进程实例做不到)";
|
|
249
|
+
} else if (spec.kind === EXECUTOR_KINDS.TEAM) {
|
|
250
|
+
installed = teamAvailable !== false;
|
|
251
|
+
if (installed === false) reason = "项目未配置执行团队(teamTemplate.executionTeam 为空):先建团队或去配置页选择";
|
|
252
|
+
}
|
|
253
|
+
const blocked = forbidden.has(spec.id) || forbidden.has(spec.agent);
|
|
254
|
+
if (blocked) reason = `项目 forbiddenExecutors 已禁 ${spec.id}:项目禁用的执行者不得按卡选择`;
|
|
255
|
+
return { spec, installed, binPath, version: null, blocked, reason };
|
|
256
|
+
});
|
|
257
|
+
// 第二遍:版本号**并行**探测(拿不到就 null;不参与 usable 判定)。
|
|
258
|
+
if (withVersion) {
|
|
259
|
+
const targets = rows.filter((row) => row.spec.kind === EXECUTOR_KINDS.CLI && row.binPath);
|
|
260
|
+
const versions = await Promise.all(targets.map((row) => Promise.resolve()
|
|
261
|
+
.then(() => readVersion(row.binPath, { timeoutMs: versionTimeoutMs }))
|
|
262
|
+
.catch(() => null)));
|
|
263
|
+
targets.forEach((row, index) => { row.version = versions[index] ?? null; });
|
|
264
|
+
}
|
|
265
|
+
return rows.map(({ spec, installed, binPath, version, blocked, reason }) => ({
|
|
266
|
+
id: spec.id,
|
|
267
|
+
agent: spec.agent,
|
|
268
|
+
kind: spec.kind,
|
|
269
|
+
label: spec.label,
|
|
270
|
+
hint: spec.hint,
|
|
271
|
+
command: spec.command,
|
|
272
|
+
installed,
|
|
273
|
+
binPath,
|
|
274
|
+
version,
|
|
275
|
+
blocked,
|
|
276
|
+
usable: installed && !blocked,
|
|
277
|
+
reason,
|
|
278
|
+
}));
|
|
279
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* flow-inject.mjs —— 开局注入的**唯一实现**(P5 档 C · 卡 `-210` · 需求 `R128`)
|
|
3
|
+
*
|
|
4
|
+
* 方案依据:`skills/taskboard-flow/references/injection.md`(三档装载 + 分层注入策略)。
|
|
5
|
+
* 接线前的事实:`flow_inject_policy` 是**全仓无 reader 的静默缺口**(卡 `-186` 用守卫钉住),
|
|
6
|
+
* 本文件就是那个 reader —— 从此改它**真的会改变行为**。
|
|
7
|
+
*
|
|
8
|
+
* 三档里的位置:
|
|
9
|
+
* · 档 A(人贴 `tb-flow start`)/ 档 B(项目 `AGENTS.md` 约定)= 已可用,与本文件无关;
|
|
10
|
+
* · **档 C(宿主自动注入)= 本文件 + `index.js` 的 `createSession()` 出口**;
|
|
11
|
+
* · 人工一次性投递(`tb-flow inject --session`)也走本文件 ⇒ **只有一条注入实现**。
|
|
12
|
+
*
|
|
13
|
+
* 四条硬约束(对应验收 ①③④⑤):
|
|
14
|
+
* ① **内容只有一个生成器**:完整版 = `buildFlowBlock().text`(与 `tb-flow start` / MCP `prompts/get`
|
|
15
|
+
* **逐字节相同**);摘要版 = `buildFlowSummary(block)`(由同一个 block 剪裁,不另写规则);
|
|
16
|
+
* ② **失败不阻断调用方**:本模块**从不抛错**,一律返回 `{ injected, delivered, reason, ... }`,
|
|
17
|
+
* 宿主/HTTP/CLI 自行决定怎么报(会话创建流程不得被注入异常打断);
|
|
18
|
+
* ③ **每次投递留审计**:成功即写 `flow_injections`(六字段:session_id / project_id / policy /
|
|
19
|
+
* contract_version / digest / injected_at);`digest = sha256(实际投出的正文)`,可事后核「投的是哪一版」;
|
|
20
|
+
* ④ **默认零行为变化**:`flow_inject_policy` 缺省 `off` ⇒ 不构建、不投递、不写行。
|
|
21
|
+
*
|
|
22
|
+
* 依赖方向:本模块在 `src/core/`,但只 import `flow-block.mjs` 这个**纯文本生成器**(不 import 任何 MCP
|
|
23
|
+
* 协议 / stdio 代码);这样宿主、HTTP、CLI 三处能共用同一段判定,不会出现「六个入口两种语义」。
|
|
24
|
+
*/
|
|
25
|
+
import { sha256 } from "./contract.mjs";
|
|
26
|
+
import { TbError } from "./errors.mjs";
|
|
27
|
+
import { buildFlowBlock, buildFlowSummary } from "../mcp/flow-block.mjs";
|
|
28
|
+
import { resolveProject } from "../mcp/tools.mjs";
|
|
29
|
+
|
|
30
|
+
/** 自动注入策略(`project_settings.flow_inject_policy` 的合法取值)。默认 `off`。 */
|
|
31
|
+
export const DEFAULT_FLOW_INJECT_POLICY = "off";
|
|
32
|
+
export const FLOW_INJECT_POLICIES = Object.freeze(["off", "main-only", "main+exec", "all"]);
|
|
33
|
+
/** 人工一次性投递的审计标签(`tb-flow inject --session`):它显式绕过 `off`,所以必须能被区分出来。 */
|
|
34
|
+
export const FLOW_INJECT_MANUAL = "manual";
|
|
35
|
+
/** 会话角色:主会话(完整版)/ 执行会话(摘要版)/ 关联会话(摘要版)/ 子 agent(**永不注入**)。 */
|
|
36
|
+
export const FLOW_INJECT_ROLES = Object.freeze(["main", "exec", "related", "subagent"]);
|
|
37
|
+
/** 摘要版 token 上限(验收 ④)。用 `estimateFlowTokens()` 度量,口径见该函数。 */
|
|
38
|
+
export const FLOW_INJECT_SUMMARY_MAX_TOKENS = 300;
|
|
39
|
+
/** 审计表 `policy` 列的合法取值(四个策略 + 人工)。 */
|
|
40
|
+
export const FLOW_INJECT_AUDIT_VALUES = Object.freeze([...FLOW_INJECT_POLICIES, FLOW_INJECT_MANUAL]);
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 归一化策略值。空值 ⇒ 默认 `off`;非法值 ⇒ `null`(`strict` 时抛 `INVALID_FLOW_INJECT_POLICY`)。
|
|
44
|
+
* 只做形状归一(大小写 / 下划线与连字符),**不猜语义**。
|
|
45
|
+
*/
|
|
46
|
+
export function normalizeFlowInjectPolicy(value, { strict = false } = {}) {
|
|
47
|
+
const raw = String(value ?? "").trim().toLowerCase().replace(/_/g, "-");
|
|
48
|
+
if (raw === "") return DEFAULT_FLOW_INJECT_POLICY;
|
|
49
|
+
const canon = raw === "main-exec" ? "main+exec" : raw;
|
|
50
|
+
if (FLOW_INJECT_AUDIT_VALUES.includes(canon)) return canon;
|
|
51
|
+
if (strict) {
|
|
52
|
+
throw new TbError(
|
|
53
|
+
"INVALID_FLOW_INJECT_POLICY",
|
|
54
|
+
`flow_inject_policy 只能是 ${FLOW_INJECT_POLICIES.join(" / ")}(收到 ${JSON.stringify(value)})`,
|
|
55
|
+
{ value: value ?? null, allowed: FLOW_INJECT_POLICIES },
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 纯判定:这条会话该不该注入、注入哪一版。**不读库、不投递、不写审计** —— 所以能单测、能被任何入口复用。
|
|
63
|
+
*
|
|
64
|
+
* 角色 × 策略矩阵(`✓` = 注入):
|
|
65
|
+
*
|
|
66
|
+
* | 角色 \ 策略 | off | main-only | main+exec | all | manual |
|
|
67
|
+
* |---|---|---|---|---|---|
|
|
68
|
+
* | main | — | ✓ 完整版 | ✓ 完整版 | ✓ 完整版 | ✓ 完整版 |
|
|
69
|
+
* | exec | — | — | ✓ 摘要版 | ✓ 摘要版 | ✓ 摘要版 |
|
|
70
|
+
* | related | — | — | — | ✓ 摘要版 | ✓ 摘要版 |
|
|
71
|
+
* | subagent| — | — | — | —(**硬规则:子 agent 永不注入**) | — |
|
|
72
|
+
*
|
|
73
|
+
* `manual` 只给 `tb-flow inject --session` 用:人显式要求时不受 `off` 约束,但**子 agent 仍不注入**
|
|
74
|
+
* (子 agent 由父会话派活,塞流程只会稀释它自己的任务上下文 —— 这条不因"人工"而放开)。
|
|
75
|
+
*
|
|
76
|
+
* @returns {{inject:boolean, version:"full"|"summary"|null, reason:string}}
|
|
77
|
+
*/
|
|
78
|
+
export function decideFlowInjection({ policy = DEFAULT_FLOW_INJECT_POLICY, role = null } = {}) {
|
|
79
|
+
const p = normalizeFlowInjectPolicy(policy);
|
|
80
|
+
if (!p) return { inject: false, version: null, reason: "policy-invalid" };
|
|
81
|
+
const r = String(role ?? "").trim() || null;
|
|
82
|
+
if (!r) return { inject: false, version: null, reason: "role-unknown" };
|
|
83
|
+
if (!FLOW_INJECT_ROLES.includes(r)) return { inject: false, version: null, reason: "role-invalid" };
|
|
84
|
+
if (r === "subagent") return { inject: false, version: null, reason: "subagent-never" };
|
|
85
|
+
if (p === "off") return { inject: false, version: null, reason: "policy-off" };
|
|
86
|
+
if (p === "main-only" && r !== "main") return { inject: false, version: null, reason: "policy-main-only" };
|
|
87
|
+
if (p === "main+exec" && r === "related") return { inject: false, version: null, reason: "policy-main+exec" };
|
|
88
|
+
return { inject: true, version: r === "main" ? "full" : "summary", reason: "ok" };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 估算 tokens(**保守上界**:CJK 一字算 1、其余 4 字符算 1 —— 宁可高估)。
|
|
93
|
+
* 用于验收 ④「摘要版 ≤ 300 tokens」,不追求与某个具体 tokenizer 对齐。
|
|
94
|
+
*/
|
|
95
|
+
export function estimateFlowTokens(text) {
|
|
96
|
+
const s = String(text ?? "");
|
|
97
|
+
const cjk = (s.match(/[\u2e80-\u9fff\uff00-\uffef\u3000-\u303f]/g) ?? []).length;
|
|
98
|
+
const rest = Math.max(0, s.length - cjk);
|
|
99
|
+
return Math.ceil(cjk + rest / 4);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 注入一次(唯一入口)。**不抛错**:任何异常都收成 `{ injected:false, reason }`。
|
|
104
|
+
*
|
|
105
|
+
* @param {object} opts
|
|
106
|
+
* @param {object} opts.store 已打开的 store(缺 ⇒ `no-store`)
|
|
107
|
+
* @param {Function} opts.deliver `(sessionId, text) => Promise<{sent|delivered, reason?}>`
|
|
108
|
+
* @param {string} [opts.projectId] 项目 id(优先;宿主建会话时调用方已知)
|
|
109
|
+
* @param {object} [opts.project] 项目对象(给了就不再查库)
|
|
110
|
+
* @param {string} opts.sessionId 目标会话
|
|
111
|
+
* @param {string} [opts.role] `main` / `exec` / `related` / `subagent`
|
|
112
|
+
* @param {string} [opts.cwd] 未给 projectId 时按工作区匹配项目
|
|
113
|
+
* @param {string} [opts.policy] 显式策略(缺省读项目设置;`manual` = 人工一次性投递)
|
|
114
|
+
* @param {string} [opts.source] 审计来源标记(`createSession` / `tb-flow-cli` / `api`),只回带不落库
|
|
115
|
+
* @returns {Promise<{injected:boolean, delivered:boolean, reason:string, sessionId:string|null,
|
|
116
|
+
* projectId:string|null, policy:string|null, role:string|null, version:string|null,
|
|
117
|
+
* contractVersion:string|null, digest:string|null, chars:number, injectedAt:string|null,
|
|
118
|
+
* injectionId:number|null, auditRecorded:boolean, text:string|null, source:string}>}
|
|
119
|
+
*/
|
|
120
|
+
export async function injectFlow({
|
|
121
|
+
store = null,
|
|
122
|
+
deliver = null,
|
|
123
|
+
projectId = null,
|
|
124
|
+
project = null,
|
|
125
|
+
sessionId = null,
|
|
126
|
+
role = null,
|
|
127
|
+
cwd = null,
|
|
128
|
+
policy = null,
|
|
129
|
+
source = "manual",
|
|
130
|
+
} = {}) {
|
|
131
|
+
const out = {
|
|
132
|
+
injected: false, delivered: false, reason: "inject-error",
|
|
133
|
+
sessionId: sessionId ?? null, projectId: projectId ?? null, policy: null, role: role ?? null,
|
|
134
|
+
version: null, contractVersion: null, digest: null, chars: 0,
|
|
135
|
+
injectedAt: null, injectionId: null, auditRecorded: false, text: null, source,
|
|
136
|
+
};
|
|
137
|
+
try {
|
|
138
|
+
if (!store) return { ...out, reason: "no-store" };
|
|
139
|
+
if (!sessionId) return { ...out, reason: "no-session" };
|
|
140
|
+
|
|
141
|
+
let proj = project && typeof project === "object" ? project : null;
|
|
142
|
+
if (!proj) {
|
|
143
|
+
proj = projectId
|
|
144
|
+
? store.requireProject(String(projectId))
|
|
145
|
+
: resolveProject(store, { cwd: cwd ?? process.cwd() }).project;
|
|
146
|
+
}
|
|
147
|
+
out.projectId = proj.id;
|
|
148
|
+
|
|
149
|
+
const configured = policy === null || policy === undefined
|
|
150
|
+
? (normalizeFlowInjectPolicy(store.getProjectSettings(proj.id)?.flowInjectPolicy) ?? DEFAULT_FLOW_INJECT_POLICY)
|
|
151
|
+
: (normalizeFlowInjectPolicy(policy) ?? String(policy));
|
|
152
|
+
const decision = decideFlowInjection({ policy: configured, role });
|
|
153
|
+
// 审计里记**实际生效的**那个值;非法值原样记下来(便于追「谁写坏了配置」)。
|
|
154
|
+
out.policy = normalizeFlowInjectPolicy(configured) ?? String(configured);
|
|
155
|
+
if (!decision.inject) return { ...out, reason: decision.reason };
|
|
156
|
+
|
|
157
|
+
const block = buildFlowBlock({ store, project: proj, matchedBy: "explicit" });
|
|
158
|
+
const text = decision.version === "full" ? block.text : buildFlowSummary(block);
|
|
159
|
+
out.version = decision.version;
|
|
160
|
+
out.contractVersion = block.contract?.version ?? null;
|
|
161
|
+
out.digest = sha256(text);
|
|
162
|
+
out.chars = text.length;
|
|
163
|
+
out.text = text;
|
|
164
|
+
|
|
165
|
+
if (typeof deliver !== "function") return { ...out, reason: "no-delivery-channel" };
|
|
166
|
+
const sent = await deliver(sessionId, text);
|
|
167
|
+
out.delivered = Boolean(sent?.sent ?? sent?.delivered ?? false);
|
|
168
|
+
if (!out.delivered) return { ...out, reason: sent?.reason ?? "delivery-failed" };
|
|
169
|
+
out.injected = true;
|
|
170
|
+
out.reason = "ok";
|
|
171
|
+
|
|
172
|
+
// 审计写失败**不回退投递结论**:内容确实进了会话,谎报"没注入"会让调用方重复注入。
|
|
173
|
+
try {
|
|
174
|
+
const row = store.recordFlowInjection({
|
|
175
|
+
projectId: proj.id, sessionId, policy: out.policy,
|
|
176
|
+
contractVersion: out.contractVersion, digest: out.digest,
|
|
177
|
+
});
|
|
178
|
+
out.injectionId = row.id;
|
|
179
|
+
out.injectedAt = row.injectedAt;
|
|
180
|
+
out.auditRecorded = true;
|
|
181
|
+
} catch (error) {
|
|
182
|
+
out.auditRecorded = false;
|
|
183
|
+
out.reason = "injected-audit-failed";
|
|
184
|
+
out.auditError = error?.code ?? String(error?.message ?? error ?? "audit-failed");
|
|
185
|
+
}
|
|
186
|
+
return out;
|
|
187
|
+
} catch (error) {
|
|
188
|
+
return { ...out, reason: error?.code ?? String(error?.message ?? error ?? "inject-error") };
|
|
189
|
+
}
|
|
190
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* instance-lease.mjs —— 多实例「单写者」租约(卡 `-237` / 需求 `R173`)。
|
|
3
|
+
*
|
|
4
|
+
* 背景(真机 2026-11-10):dsh web 与 dsh desktop 可以**同时**打开同一个库。两个宿主各自
|
|
5
|
+
* 起一份插件实例,而 `index.js` 里有两处**按进程**的行为:
|
|
6
|
+
* ① 启动期 `reconcileOrphanRuns({ boot: true })` —— 它分不清「上一进程」与「另一个活着的进程」,
|
|
7
|
+
* 会把对端正**在跑**的执行当孤儿结清;
|
|
8
|
+
* ② 30s 执行循环 —— 两边各起一个定时器,同一张卡可能被**双派发**。
|
|
9
|
+
* ⇒ 同一时刻只允许一个实例是 `writer`;其余降级为 `follower`(只读、不起循环、不做 boot 收口)。
|
|
10
|
+
*
|
|
11
|
+
* 语义(刻意保守):
|
|
12
|
+
* - 表只有一行(`id = 1`),心跳 15s、过期 45s;
|
|
13
|
+
* - **不夺权**:对端心跳还新鲜就老实当 follower —— 静默夺权比只读更危险;
|
|
14
|
+
* - 只有对端**已过期**才接管,并回 `tookOver: true`(调用方据此补一次 boot 收口);
|
|
15
|
+
* - 释放是尽力而为:进程被 kill 时行会留到过期,接管方自然会接上。
|
|
16
|
+
* - **默认 role = writer**:不开租约的调用方(CLI / 测试 / 单进程)行为一字不变。
|
|
17
|
+
*/
|
|
18
|
+
export const LEASE_TTL_MS = 45_000;
|
|
19
|
+
export const LEASE_HEARTBEAT_MS = 15_000;
|
|
20
|
+
|
|
21
|
+
const CREATE_LEASE_TABLE = `create table if not exists db_instance_lease (
|
|
22
|
+
id integer primary key check (id = 1),
|
|
23
|
+
instance_id text not null,
|
|
24
|
+
host text not null,
|
|
25
|
+
pid integer not null,
|
|
26
|
+
started_at text not null,
|
|
27
|
+
heartbeat_at integer not null
|
|
28
|
+
)`;
|
|
29
|
+
|
|
30
|
+
export function createLeaseApi({ db, nowIso, randomUUID }) {
|
|
31
|
+
db.exec(CREATE_LEASE_TABLE);
|
|
32
|
+
let role = "writer";
|
|
33
|
+
let owner = null;
|
|
34
|
+
let selfId = null;
|
|
35
|
+
|
|
36
|
+
const readRow = () => db.prepare("select * from db_instance_lease where id = 1").get() ?? null;
|
|
37
|
+
const describe = (row) => (row
|
|
38
|
+
? { instanceId: row.instance_id, host: row.host, pid: row.pid, startedAt: row.started_at, heartbeatAt: row.heartbeat_at }
|
|
39
|
+
: null);
|
|
40
|
+
|
|
41
|
+
return {
|
|
42
|
+
/**
|
|
43
|
+
* 抢/续租约。**幂等**:同一个 instanceId 重复调用等于心跳。
|
|
44
|
+
* @returns {{role:"writer"|"follower", owner:object|null, tookOver:boolean, previous?:object|null, instanceId:string}}
|
|
45
|
+
*/
|
|
46
|
+
acquireInstanceLease({ host = "local", pid = process.pid, nowMs = Date.now(), ttlMs = LEASE_TTL_MS, instanceId } = {}) {
|
|
47
|
+
const self = instanceId || selfId || (selfId = `inst-${randomUUID().replace(/-/g, "").slice(0, 10)}`);
|
|
48
|
+
const stamp = nowIso();
|
|
49
|
+
const row = readRow();
|
|
50
|
+
if (!row) {
|
|
51
|
+
db.prepare("insert into db_instance_lease (id, instance_id, host, pid, started_at, heartbeat_at) values (1, ?, ?, ?, ?, ?)")
|
|
52
|
+
.run(self, String(host), Number(pid), stamp, Number(nowMs));
|
|
53
|
+
role = "writer"; owner = null;
|
|
54
|
+
return { role, owner: null, tookOver: false, instanceId: self };
|
|
55
|
+
}
|
|
56
|
+
if (row.instance_id === self) {
|
|
57
|
+
db.prepare("update db_instance_lease set heartbeat_at = ?, host = ?, pid = ? where id = 1")
|
|
58
|
+
.run(Number(nowMs), String(host), Number(pid));
|
|
59
|
+
role = "writer"; owner = null;
|
|
60
|
+
return { role, owner: null, tookOver: false, instanceId: self };
|
|
61
|
+
}
|
|
62
|
+
const age = Number(nowMs) - Number(row.heartbeat_at ?? 0);
|
|
63
|
+
if (age <= Number(ttlMs)) {
|
|
64
|
+
role = "follower"; owner = describe(row);
|
|
65
|
+
return { role, owner, tookOver: false, instanceId: self };
|
|
66
|
+
}
|
|
67
|
+
const previous = describe(row);
|
|
68
|
+
db.prepare("update db_instance_lease set instance_id = ?, host = ?, pid = ?, started_at = ?, heartbeat_at = ? where id = 1")
|
|
69
|
+
.run(self, String(host), Number(pid), stamp, Number(nowMs));
|
|
70
|
+
role = "writer"; owner = null;
|
|
71
|
+
return { role, owner: null, tookOver: true, previous, instanceId: self };
|
|
72
|
+
},
|
|
73
|
+
|
|
74
|
+
/** 本实例当前角色(**本地缓存**,只在 acquire 时更新)。未调用过 acquire 的调用方恒为 `writer`(零行为变化)。 */
|
|
75
|
+
instanceRole() { return role; },
|
|
76
|
+
|
|
77
|
+
/** follower 时是「谁在写」;writer 时为 null。 */
|
|
78
|
+
instanceLeaseOwner() { return owner; },
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* **现读**当前角色(每个写请求都要用这一条,不要用上面的缓存):
|
|
82
|
+
* 缓存最多滞后一个心跳周期(15s)——被夺权的一方在这 15s 里仍会以为自己是 writer,
|
|
83
|
+
* 若写门只看缓存,就有一段真实的双写窗口。这里直接读那一行,代价是一次主键查询。
|
|
84
|
+
* 行不存在 / 是自己 / 对端已过期 ⇒ `writer`(过期由下一次心跳正式接管)。
|
|
85
|
+
*/
|
|
86
|
+
instanceRoleFresh() {
|
|
87
|
+
const row = readRow();
|
|
88
|
+
if (!row) return "writer";
|
|
89
|
+
if (selfId && row.instance_id === selfId) return "writer";
|
|
90
|
+
const age = Date.now() - Number(row.heartbeat_at ?? 0);
|
|
91
|
+
return age <= LEASE_TTL_MS ? "follower" : "writer";
|
|
92
|
+
},
|
|
93
|
+
|
|
94
|
+
/** 现读「谁在写」(搭配 instanceRoleFresh,仅 follower 时非 null)。 */
|
|
95
|
+
instanceLeaseOwnerFresh() {
|
|
96
|
+
const row = readRow();
|
|
97
|
+
if (!row || (selfId && row.instance_id === selfId)) return null;
|
|
98
|
+
const age = Date.now() - Number(row.heartbeat_at ?? 0);
|
|
99
|
+
return age <= LEASE_TTL_MS ? describe(row) : null;
|
|
100
|
+
},
|
|
101
|
+
|
|
102
|
+
/** 释放租约(仅当本实例是持有者)。返回是否真的释放了。 */
|
|
103
|
+
releaseInstanceLease() {
|
|
104
|
+
const row = readRow();
|
|
105
|
+
if (row && selfId && row.instance_id === selfId) {
|
|
106
|
+
db.prepare("delete from db_instance_lease where id = 1").run();
|
|
107
|
+
role = "writer"; owner = null;
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
return false;
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|