@aiti-ai/ext-shared 0.0.0-stage → 0.1.8
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/LICENSE +21 -0
- package/agent-accounts.test.mjs +227 -0
- package/agent-accounts.ts +324 -0
- package/agent-capability-contract.test.mjs +129 -0
- package/agent-interaction.test.mjs +194 -0
- package/agent-interaction.ts +340 -0
- package/agent-launch.test.mjs +262 -0
- package/agent-spawn-env.test.mjs +169 -0
- package/agent-spawn-env.ts +548 -0
- package/aiti-editor-inject.mjs +49 -0
- package/backend-queue.test.mjs +336 -0
- package/backend-queue.ts +469 -0
- package/blob-save-route.ts +128 -0
- package/cbc-model-catalog.ts +86 -0
- package/check-client.mjs +273 -0
- package/check-ext-globals.mjs +144 -0
- package/controlled-login-dialog.mjs +270 -0
- package/controlled-login.mjs +398 -0
- package/controlled-login.test.mjs +466 -0
- package/convert-saveas.test.mjs +39 -0
- package/convert-saveas.ts +170 -0
- package/copy-client-bundle.mjs +39 -0
- package/cursor-cli-store.ts +377 -0
- package/dedupe-fetch.test.mjs +71 -0
- package/dedupe-fetch.ts +58 -0
- package/deploy-commit.mjs +52 -0
- package/dev-pack.mjs +246 -0
- package/dock-icons.ts +127 -0
- package/esbuild-bin.test.mjs +53 -0
- package/esbuild-bin.ts +66 -0
- package/exec-async.test.mjs +86 -0
- package/exec-async.ts +179 -0
- package/ext-display-names.ts +91 -0
- package/ext-entry-contracts.test.mjs +131 -0
- package/ext-float-dock-core.test.mjs +348 -0
- package/ext-float-dock-core.ts +783 -0
- package/ext-float-dock-lite.ts +52 -0
- package/ext-float-dock.test.mjs +286 -0
- package/ext-float-dock.ts +740 -0
- package/ext-icons-deploy.mjs +24 -0
- package/ext-lazy.test.mjs +186 -0
- package/ext-lazy.tsx +183 -0
- package/ext-model-state.test.mjs +272 -0
- package/ext-model-state.ts +324 -0
- package/ext-protocol.mjs +113 -0
- package/ext-protocol.test.mjs +88 -0
- package/ext-session-usage.test.mjs +219 -0
- package/ext-session-usage.ts +507 -0
- package/external-cli-governance.ts +153 -0
- package/git-ops-client/api.mjs +56 -0
- package/git-ops-client/branch-panel.tsx +987 -0
- package/git-ops-client/i18n.mjs +328 -0
- package/host-tools-allow.test.mjs +46 -0
- package/host-tools-allow.ts +84 -0
- package/icons/alert.svg +1 -0
- package/icons/bookmark.svg +1 -0
- package/icons/bot.svg +1 -0
- package/icons/chart-column.svg +1 -0
- package/icons/check-circle.svg +1 -0
- package/icons/clipboard-list.svg +1 -0
- package/icons/clock.svg +1 -0
- package/icons/coffee.svg +1 -0
- package/icons/edit.svg +1 -0
- package/icons/eye.svg +1 -0
- package/icons/git-branch.svg +1 -0
- package/icons/git-commit-horizontal.svg +1 -0
- package/icons/globe.svg +1 -0
- package/icons/history.svg +1 -0
- package/icons/import.svg +1 -0
- package/icons/inbox.svg +1 -0
- package/icons/key-round.svg +1 -0
- package/icons/layout-grid.svg +1 -0
- package/icons/mail.svg +1 -0
- package/icons/message-circle.svg +1 -0
- package/icons/message-square.svg +1 -0
- package/icons/meter-vertical.svg +1 -0
- package/icons/mic.svg +1 -0
- package/icons/monitor.svg +1 -0
- package/icons/pen-line.svg +1 -0
- package/icons/plug.svg +1 -0
- package/icons/radio-dot.svg +1 -0
- package/icons/radio.svg +1 -0
- package/icons/refresh.svg +1 -0
- package/icons/rocket.svg +1 -0
- package/icons/search.svg +1 -0
- package/icons/shield.svg +1 -0
- package/icons/sparkles.svg +1 -0
- package/icons/square-kanban.svg +1 -0
- package/icons/terminal.svg +1 -0
- package/icons/users.svg +1 -0
- package/icons/volume-2.svg +1 -0
- package/icons/wand.svg +1 -0
- package/icons/wrench.svg +1 -0
- package/icons/x-circle.svg +1 -0
- package/icons/x.svg +1 -0
- package/ignore-semantics.ts +76 -0
- package/lazy-loading-metrics.mjs +61 -0
- package/new-session-cwd.test.mjs +389 -0
- package/new-session-cwd.ts +253 -0
- package/open-viewer-window.ts +65 -0
- package/overlay-back-client.test.mjs +123 -0
- package/overlay-back-client.ts +87 -0
- package/package.json +65 -4
- package/pi-fork-rpc/README.md +12 -0
- package/pi-fork-rpc/cli-resolve.test.mjs +42 -0
- package/pi-fork-rpc/cli-resolve.ts +79 -0
- package/pi-fork-rpc/remote-queue.test.mjs +100 -0
- package/pi-fork-rpc/remote-queue.ts +140 -0
- package/pi-fork-rpc/spec.ts +106 -0
- package/pi-fork-rpc/wire.test.mjs +260 -0
- package/pi-fork-rpc/wire.ts +367 -0
- package/popup-anchor.ts +45 -0
- package/provider-priority-contract.test.mjs +55 -0
- package/reconcile-deps.mjs +41 -0
- package/reload-instances.mjs +60 -0
- package/seed-tool.test.mjs +95 -0
- package/seed-tool.ts +88 -0
- package/session-recycle.ts +109 -0
- package/shared-copy-sync.test.mjs +115 -0
- package/soffice-locate.ts +171 -0
- package/soffice-panel.ts +239 -0
- package/sync-dir.mjs +91 -0
- package/sync-dir.test.mjs +101 -0
- package/sync-gate.test.mjs +93 -0
- package/sync-mirror.test.mjs +85 -0
- package/task-list.test.mjs +91 -0
- package/task-list.ts +118 -0
- package/test-rm-rf.mjs +33 -0
- package/ui-dialogs.test.mjs +198 -0
- package/ui-dialogs.ts +310 -0
- package/README.md +0 -3
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent-capability-contract —— Agent 类扩展 capability 声明 ↔ handle 方法存在性 静态对照
|
|
3
|
+
* (债务清单 docs/pi-web-ext-agent-authoring-debt.md D2 防回归)。
|
|
4
|
+
*
|
|
5
|
+
* 机制:适配层(pi-web lib/session/handle-adapter.ts)对 steer/followUp 等命令是
|
|
6
|
+
* 「cap("X") 通过后 await h.X!()」——声明 true 而方法缺失即运行时 TypeError;
|
|
7
|
+
* getMessages 错名则走 fail-loud 报 UnsupportedCapability(不崩但功能缺失)。
|
|
8
|
+
* 本测试静态扫描 pi-web-ext/aiti-*-agent 的 *.ts 源码(不 import、零副作用):
|
|
9
|
+
* 1. 逐行收集已知 capability 键为 `true` 的声明(剔除注释行);
|
|
10
|
+
* 2. 对照「方法定义行模式」与豁免表(无方法面的声明);
|
|
11
|
+
* 3. 声明 true 而两处皆无 → fail,提示补方法或改 false + fail-loud stub。
|
|
12
|
+
*
|
|
13
|
+
* Run: node --experimental-strip-types --test pi-web-ext/_shared/agent-capability-contract.test.mjs
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import assert from "node:assert/strict";
|
|
17
|
+
import test from "node:test";
|
|
18
|
+
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
19
|
+
import { join, dirname } from "node:path";
|
|
20
|
+
import { fileURLToPath } from "node:url";
|
|
21
|
+
|
|
22
|
+
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
23
|
+
|
|
24
|
+
/** capability 键 → handle 方法名(多候选 = 任一存在即可)。
|
|
25
|
+
* 依据 pi-web handle-adapter.ts 命令表的查名。 */
|
|
26
|
+
const CAP_TO_METHODS = {
|
|
27
|
+
prompt: ["prompt"],
|
|
28
|
+
abort: ["abort"],
|
|
29
|
+
steer: ["steer"],
|
|
30
|
+
followUp: ["followUp"],
|
|
31
|
+
getMessages: ["getMessages"],
|
|
32
|
+
getUsage: ["getUsage"],
|
|
33
|
+
contextUsage: ["getContextUsage"],
|
|
34
|
+
getCommands: ["getCommands"],
|
|
35
|
+
respondPermission: ["respondPermission"],
|
|
36
|
+
respondInteraction: ["respondInteraction"],
|
|
37
|
+
queueManage: ["queueManage"],
|
|
38
|
+
setModel: ["setModel"],
|
|
39
|
+
setThinkingLevel: ["setThinkingLevel"],
|
|
40
|
+
setPermissionMode: ["setPermissionMode"],
|
|
41
|
+
fork: ["fork"],
|
|
42
|
+
renameSession: ["setSessionName"], // adapter set_session_name → h.setSessionName!()
|
|
43
|
+
compact: ["compact"],
|
|
44
|
+
executeBash: ["executeBash"],
|
|
45
|
+
setActiveTools: ["setActiveTools"],
|
|
46
|
+
navigateTree: ["navigateTree"],
|
|
47
|
+
deleteSession: ["deleteSession"],
|
|
48
|
+
listModels: ["getAvailableModels"],
|
|
49
|
+
// adapter get_tools 走 h.send 直达通道或 getAllTools 快照,任一即可
|
|
50
|
+
listTools: ["getAllTools", "getTools", "send"],
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/** 无独立方法面的 capability(声明 true 合法,无需方法): */
|
|
54
|
+
const CAP_EXEMPT = new Set([
|
|
55
|
+
"fileAttachments", // prompt images 参数面;ACP 实例按 initialize promptCapabilities 收敛
|
|
56
|
+
]);
|
|
57
|
+
|
|
58
|
+
const KNOWN_KEYS = new Set([...Object.keys(CAP_TO_METHODS), ...CAP_EXEMPT]);
|
|
59
|
+
|
|
60
|
+
/** 方法定义行模式(逐行;不含调用——调用带 `.` / `!` 前缀或缩进不符):
|
|
61
|
+
* async followUp(text: string): Promise<void> { / getUsage() { /
|
|
62
|
+
* queueManage = (req: {...}) => ... / private steer(): never { */
|
|
63
|
+
function methodDefined(src, method) {
|
|
64
|
+
const esc = method.replace(/\$/g, "\\$");
|
|
65
|
+
const reDef = new RegExp(`^\\s*(?:private\\s+|protected\\s+|public\\s+)?(?:readonly\\s+)?(?:async\\s+)?${esc}\\s*[<(]`);
|
|
66
|
+
const reArrow = new RegExp(`^\\s*(?:private\\s+|readonly\\s+)?${esc}\\s*=\\s*(?:async\\s*)?\\(`);
|
|
67
|
+
return src.split(/\r?\n/).some((line) => {
|
|
68
|
+
const t = line.trim();
|
|
69
|
+
if (t.startsWith("//") || t.startsWith("*") || t.startsWith("/*")) return false;
|
|
70
|
+
return reDef.test(line) || reArrow.test(line);
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function listAgentExts() {
|
|
75
|
+
return readdirSync(ROOT)
|
|
76
|
+
.filter((name) => name.startsWith("aiti-") && name.endsWith("-agent"))
|
|
77
|
+
.filter((name) => statSync(join(ROOT, name)).isDirectory())
|
|
78
|
+
.sort();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function listTsFiles(dir) {
|
|
82
|
+
const out = [];
|
|
83
|
+
for (const name of readdirSync(dir)) {
|
|
84
|
+
const p = join(dir, name);
|
|
85
|
+
const st = statSync(p);
|
|
86
|
+
if (st.isDirectory()) {
|
|
87
|
+
if (name === "node_modules" || name === "dist" || name === "tools" || name === "client") continue;
|
|
88
|
+
out.push(...listTsFiles(p));
|
|
89
|
+
} else if (name.endsWith(".ts")) {
|
|
90
|
+
out.push(p);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
for (const ext of listAgentExts()) {
|
|
97
|
+
test(`[${ext}] capability 声明 ↔ handle 方法对照(D2 防回归)`, () => {
|
|
98
|
+
const files = listTsFiles(join(ROOT, ext));
|
|
99
|
+
assert.ok(files.length, `${ext}: 未找到 .ts 源文件`);
|
|
100
|
+
const src = files.map((p) => readFileSync(p, "utf8")).join("\n");
|
|
101
|
+
|
|
102
|
+
// 收集声明 true 的已知 capability 键(剔除纯注释行)
|
|
103
|
+
const claimed = new Map(); // key -> 首个声明处描述
|
|
104
|
+
for (const file of files) {
|
|
105
|
+
for (const [i, line] of readFileSync(file, "utf8").split(/\r?\n/).entries()) {
|
|
106
|
+
const t = line.trim();
|
|
107
|
+
if (t.startsWith("//") || t.startsWith("*") || t.startsWith("/*")) continue;
|
|
108
|
+
const m = t.match(/^([A-Za-z]\w*):\s*true\b/);
|
|
109
|
+
if (m && KNOWN_KEYS.has(m[1]) && !claimed.has(m[1])) {
|
|
110
|
+
claimed.set(m[1], `${file.replace(ROOT + "/", "")}:${i + 1}`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const problems = [];
|
|
116
|
+
for (const [key, at] of [...claimed].sort()) {
|
|
117
|
+
if (CAP_EXEMPT.has(key)) continue;
|
|
118
|
+
const candidates = CAP_TO_METHODS[key] ?? [];
|
|
119
|
+
const found = candidates.find((m) => methodDefined(src, m));
|
|
120
|
+
if (!found) {
|
|
121
|
+
problems.push(
|
|
122
|
+
`capabilities.${key}: true(${at})但无对应方法(${candidates.join("/")})——` +
|
|
123
|
+
`适配层调用即 TypeError/UnsupportedCapability;请实现方法或改 false + fail-loud stub`,
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
assert.deepEqual(problems, [], `\n${problems.join("\n")}`);
|
|
128
|
+
});
|
|
129
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* _shared/agent-interaction — 会话「需用户应答的请求」统一语义单测。
|
|
3
|
+
*
|
|
4
|
+
* 钉死 docs/pi-web-ext-agent-interaction-unify-plan.md §2/§3:kind 裁决、CC 族答案→线协议
|
|
5
|
+
* 换算(answers/approved 回填 = 现状 permission 卡假支持的根因)、ACP fail-closed、
|
|
6
|
+
* ledger 的 pending 生命周期(**补发必须复用原 requestId**——qoder 事故就是重建后卡片丢失
|
|
7
|
+
* 导致 CLI 永久等一个没人回答的授权)、sidecar 落盘/读回。
|
|
8
|
+
*
|
|
9
|
+
* Run: node --experimental-strip-types --test pi-web-ext/_shared/agent-interaction.test.mjs
|
|
10
|
+
*/
|
|
11
|
+
import assert from "node:assert/strict";
|
|
12
|
+
import test from "node:test";
|
|
13
|
+
import { mkdtempSync, readFileSync, readdirSync } from "node:fs";
|
|
14
|
+
import { tmpdir } from "node:os";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
|
|
17
|
+
const M = await import("@aiti-ai/ext-shared/agent-interaction");
|
|
18
|
+
const { deriveAskKind, toControlResponse, toAcpOptionId, createInteractionLedger } = M;
|
|
19
|
+
|
|
20
|
+
// ── kind 裁决 ──────────────────────────────────────────────────────────────
|
|
21
|
+
test("deriveAskKind:ExitPlanMode 族 → plan_approval(含 mcp 前缀/下划线变体)", () => {
|
|
22
|
+
for (const n of ["ExitPlanMode", "exit_plan_mode", "mcp__x__ExitPlanMode", "mcp__my_server__ExitPlanMode", "Exit-Plan-Mode"]) {
|
|
23
|
+
assert.equal(deriveAskKind(n, {}), "plan_approval", n);
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test("deriveAskKind:AskUserQuestion 有 questions 才 ask_user,无 questions 退化 tool_auth", () => {
|
|
28
|
+
const qs = [{ question: "选哪个", options: [{ label: "A" }] }];
|
|
29
|
+
assert.equal(deriveAskKind("AskUserQuestion", { questions: qs }), "ask_user");
|
|
30
|
+
assert.equal(deriveAskKind("mcp__x__ask_user_question", { questions: qs }), "ask_user");
|
|
31
|
+
assert.equal(deriveAskKind("AskUserQuestion", {}), "tool_auth");
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test("deriveAskKind:EnterPlanMode 是授权不是审批卡(实测 allow 即成,无方案可审)", () => {
|
|
35
|
+
assert.equal(deriveAskKind("EnterPlanMode", { reason: "probe" }), "tool_auth");
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("deriveAskKind:zcode schema.interaction=plan_approval 后端显式标注优先于工具名", () => {
|
|
39
|
+
assert.equal(deriveAskKind("whatever_tool", { interaction: "plan_approval", plan: "x" }), "plan_approval");
|
|
40
|
+
assert.equal(deriveAskKind("AskUserQuestion", { interaction: "plan_approval" }), "plan_approval");
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("deriveAskKind:普通工具/无名 → tool_auth", () => {
|
|
44
|
+
assert.equal(deriveAskKind("Bash", { command: "ls" }), "tool_auth");
|
|
45
|
+
assert.equal(deriveAskKind(undefined, undefined), "tool_auth");
|
|
46
|
+
assert.equal(deriveAskKind("", null), "tool_auth");
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
// ── CC 族答案 → control_response ────────────────────────────────────────────
|
|
50
|
+
test("toControlResponse:ask_user 接受 → allow + updatedInput 合并原入参与 answers(键=问题文本)", () => {
|
|
51
|
+
const input = { questions: [{ question: "选哪个", options: [{ label: "A" }, { label: "B" }] }] };
|
|
52
|
+
assert.deepEqual(toControlResponse({ kind: "ask_user", input }, { action: "accept", answers: { 选哪个: "B" } }), {
|
|
53
|
+
behavior: "allow",
|
|
54
|
+
updatedInput: { ...input, answers: { 选哪个: "B" } },
|
|
55
|
+
});
|
|
56
|
+
assert.deepEqual(toControlResponse({ kind: "ask_user", input }, { action: "accept" }), {
|
|
57
|
+
behavior: "allow", updatedInput: { ...input, answers: {} },
|
|
58
|
+
}, "没答也照发(CLI 侧回「user did not answer」,不能僵在等待)");
|
|
59
|
+
assert.deepEqual(toControlResponse({ kind: "ask_user", input }, { action: "decline", message: "不问" }), {
|
|
60
|
+
behavior: "deny", message: "不问",
|
|
61
|
+
}, "用户拒答 = 权限拒绝语义,别伪造答案");
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("toControlResponse:plan_approval 批准 → approved=true;拒绝 → approved=false + feedback(不是 deny)", () => {
|
|
65
|
+
assert.deepEqual(toControlResponse({ kind: "plan_approval", input: { plan: "p" } }, { action: "accept" }), {
|
|
66
|
+
behavior: "allow", updatedInput: { plan: "p", approved: true },
|
|
67
|
+
});
|
|
68
|
+
assert.deepEqual(toControlResponse({ kind: "plan_approval", input: {} }, { action: "decline", message: "换方案" }), {
|
|
69
|
+
behavior: "allow", updatedInput: { approved: false, feedback: "换方案" },
|
|
70
|
+
});
|
|
71
|
+
assert.deepEqual(toControlResponse({ kind: "plan_approval", input: {} }, { action: "decline" }), {
|
|
72
|
+
behavior: "allow", updatedInput: { approved: false },
|
|
73
|
+
}, "没写反馈就别发明 feedback(CLI 会提示模型去问用户要反馈)");
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("toControlResponse:tool_auth 只带 behavior/message,不发明 updatedInput", () => {
|
|
77
|
+
assert.deepEqual(toControlResponse({ kind: "tool_auth", toolName: "Bash", input: { command: "ls" } }, { action: "accept" }), {
|
|
78
|
+
behavior: "allow",
|
|
79
|
+
});
|
|
80
|
+
assert.deepEqual(toControlResponse({ kind: "tool_auth" }, { action: "decline" }), { behavior: "deny", message: "denied by user" });
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("toControlResponse:optionId 按选项 kind 解析;未知 optionId fail-closed 拒绝而非乱选", () => {
|
|
84
|
+
const ask = { kind: "tool_auth", options: [{ optionId: "always", kind: "allow_always" }, { optionId: "no", kind: "reject_once" }] };
|
|
85
|
+
assert.deepEqual(toControlResponse(ask, { action: "accept", optionId: "always" }), { behavior: "allow" });
|
|
86
|
+
assert.deepEqual(toControlResponse(ask, { action: "accept", optionId: "ghost" }), { behavior: "deny", message: "unknown optionId: ghost" });
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// ── ACP optionId 选择(各家选项 id 不同,必须查表而非猜)─────────────────────
|
|
90
|
+
test("toAcpOptionId:显式 optionId 须在 options 内;否则按 accept/decline 查 kind/name", () => {
|
|
91
|
+
const opts = [{ optionId: "o1", kind: "allow_once" }, { optionId: "o2", kind: "reject_once" }];
|
|
92
|
+
assert.equal(toAcpOptionId(opts, { action: "accept" }), "o1");
|
|
93
|
+
assert.equal(toAcpOptionId(opts, { action: "decline", message: "no" }), "o2");
|
|
94
|
+
assert.equal(toAcpOptionId(opts, { action: "accept", optionId: "o2" }), "o2");
|
|
95
|
+
assert.equal(toAcpOptionId(opts, { action: "accept", optionId: "nope" }), undefined);
|
|
96
|
+
assert.equal(toAcpOptionId(undefined, { action: "accept" }), undefined);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// ── ledger:pending 生命周期 ────────────────────────────────────────────────
|
|
100
|
+
function mkLedger(extra = {}) {
|
|
101
|
+
const events = [];
|
|
102
|
+
const notes = [];
|
|
103
|
+
const ledger = createInteractionLedger({
|
|
104
|
+
emit: (e) => events.push(e), record: (n) => notes.push(n), ...extra,
|
|
105
|
+
});
|
|
106
|
+
return { ledger, events, notes };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
test("ledger.open:分配 requestId、广播 interaction_request、留痕 pending;requestId 由调用方给则复用", () => {
|
|
110
|
+
const { ledger, events, notes } = mkLedger();
|
|
111
|
+
const id = ledger.open({ kind: "tool_auth", toolName: "Bash", input: { command: "ls" } });
|
|
112
|
+
assert.ok(id);
|
|
113
|
+
assert.deepEqual({ type: events[0].type, requestId: events[0].requestId, kind: events[0].kind, capability: events[0].capability },
|
|
114
|
+
{ type: "interaction_request", requestId: id, kind: "tool_auth", capability: "respondInteraction" });
|
|
115
|
+
assert.equal(notes.length, 1);
|
|
116
|
+
assert.equal(notes[0].decision, "pending");
|
|
117
|
+
assert.equal(ledger.open({ requestId: "wire-9", kind: "ask_user" }), "wire-9");
|
|
118
|
+
assert.equal(events[1].requestId, "wire-9", "应答必须用 CLI 原 request_id,自造即失配");
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test("ledger.settle:命中返回账项并清账 + 留痕 allow/deny;未命中返回 null(重复应答幂等)", () => {
|
|
122
|
+
const { ledger, notes } = mkLedger();
|
|
123
|
+
const id = ledger.open({ kind: "plan_approval", toolName: "ExitPlanMode", input: { plan: "p" } });
|
|
124
|
+
assert.equal(ledger.pending().length, 1);
|
|
125
|
+
const ask = ledger.settle(id, { action: "accept" });
|
|
126
|
+
assert.equal(ask.kind, "plan_approval");
|
|
127
|
+
assert.equal(ledger.pending().length, 0);
|
|
128
|
+
assert.equal(ledger.settle(id, { action: "accept" }), null);
|
|
129
|
+
assert.deepEqual(notes.map((n) => n.decision), ["pending", "allow"]);
|
|
130
|
+
const id2 = ledger.open({ kind: "tool_auth" });
|
|
131
|
+
ledger.settle(id2, { action: "decline", message: "不" });
|
|
132
|
+
assert.deepEqual(notes.map((n) => [n.decision, n.note]), [["pending", undefined], ["allow", undefined], ["pending", undefined], ["deny", "不"]]);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test("ledger.replay:只给帧不广播(补发未决;同 requestId 幂等,不新造)", () => {
|
|
136
|
+
const { ledger, events } = mkLedger();
|
|
137
|
+
const a = ledger.open({ kind: "tool_auth", toolName: "Write" });
|
|
138
|
+
const b = ledger.open({ kind: "ask_user", toolName: "AskUserQuestion", questions: [{ question: "q", options: [{ label: "A" }] }] });
|
|
139
|
+
events.length = 0;
|
|
140
|
+
const frames = ledger.replay();
|
|
141
|
+
assert.equal(events.length, 0, "replay 不 emit(发给谁由调用方定:新订阅者单独补发)");
|
|
142
|
+
assert.deepEqual(frames.map((e) => [e.type, e.requestId]), [["interaction_request", a], ["interaction_request", b]]);
|
|
143
|
+
assert.deepEqual(frames[1].questions, [{ question: "q", options: [{ label: "A" }] }], "补发的帧就是当初那帧");
|
|
144
|
+
assert.deepEqual(ledger.replay().map((e) => e.requestId), [a, b], "再次取仍同 id(幂等)");
|
|
145
|
+
ledger.settle(a, { action: "accept" });
|
|
146
|
+
assert.deepEqual(ledger.replay().map((e) => e.requestId), [b], "已应答即不再补发");
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
test("ledger.failPending:turn 收口/进程死亡 → 逐个 interaction_expired + cancelled 留痕 + 清空", () => {
|
|
150
|
+
const { ledger, events, notes } = mkLedger();
|
|
151
|
+
const id = ledger.open({ kind: "tool_auth", toolName: "Bash" });
|
|
152
|
+
events.length = 0;
|
|
153
|
+
assert.equal(ledger.failPending("turn_end"), 1);
|
|
154
|
+
assert.deepEqual(events[0], { type: "interaction_expired", requestId: id, reason: "turn_end" });
|
|
155
|
+
assert.equal(ledger.pending().length, 0);
|
|
156
|
+
assert.equal(notes.at(-1).decision, "cancelled");
|
|
157
|
+
assert.equal(ledger.failPending("dead"), 0, "已空即幂等无副作用");
|
|
158
|
+
assert.equal(events.length, 1);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test("ledger sidecar:sidecarFile 给则落盘可跨实例读回;不给静默降级", () => {
|
|
162
|
+
const dir = mkdtempSync(join(tmpdir(), "aiti-ia-"));
|
|
163
|
+
const file = join(dir, "interactions", "qodercn_s1.json");
|
|
164
|
+
const a = mkLedger({ sidecarFile: () => file });
|
|
165
|
+
const id = a.ledger.open({ kind: "tool_auth", toolName: "Bash", input: { command: "ls" } });
|
|
166
|
+
const qid = a.ledger.open({ kind: "ask_user", toolName: "AskUserQuestion", questions: [{ question: "选哪个", options: [{ label: "A" }] }] });
|
|
167
|
+
assert.deepEqual(readdirSync(join(dir, "interactions")), ["qodercn_s1.json"], "路径由调用方定(各家 sidecar 命名规则不同:冒号在 NTFS 是 ADS 分隔符)");
|
|
168
|
+
const saved = JSON.parse(readFileSync(file, "utf8"));
|
|
169
|
+
assert.equal(saved[0].requestId, id);
|
|
170
|
+
|
|
171
|
+
const restored = [];
|
|
172
|
+
const b = createInteractionLedger({ sidecarFile: () => file, emit: (e) => restored.push(e) });
|
|
173
|
+
assert.equal(b.load(), 2, "重启后从 sidecar 恢复未决");
|
|
174
|
+
assert.equal(b.pending()[0].toolName, "Bash");
|
|
175
|
+
assert.equal(restored.length, 0, "load 只读盘不广播(发给谁由调用方的订阅时机定)");
|
|
176
|
+
const revived = b.replay();
|
|
177
|
+
assert.equal(revived.length, 2, "读回后即可补发(handle 重建不用等 CLI 再问一次)");
|
|
178
|
+
assert.deepEqual(
|
|
179
|
+
revived.find((e) => e.requestId === qid)?.questions,
|
|
180
|
+
[{ question: "选哪个", options: [{ label: "A" }] }],
|
|
181
|
+
"sidecar 存的是完整广播帧——恢复出来的 ask_user 卡不能丢问题",
|
|
182
|
+
);
|
|
183
|
+
assert.equal(b.settle(id, { action: "accept" }).kind, "tool_auth");
|
|
184
|
+
assert.equal(JSON.parse(readFileSync(file, "utf8")).length, 1, "收口只清对应项");
|
|
185
|
+
assert.equal(mkLedger().ledger.load(), 0, "无 sidecarFile 时 load 返回 0 不抛");
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
test("ledger 不信任输入:questions/options 形状不合即不写进广播事件(宁缺卡不崩卡)", () => {
|
|
189
|
+
const { ledger, events } = mkLedger();
|
|
190
|
+
ledger.open({ kind: "ask_user", questions: "nope" });
|
|
191
|
+
ledger.open({ kind: "ask_user", questions: [{ question: "q", options: [{ label: "A" }] }, { bogus: 1 }] });
|
|
192
|
+
assert.equal(events[0].questions, undefined);
|
|
193
|
+
assert.deepEqual(events[1].questions, [{ question: "q", options: [{ label: "A" }] }], "逐条过滤,保留合法项");
|
|
194
|
+
});
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* _shared/agent-interaction — 会话「需用户应答的请求」统一语义(kind 裁决 + pending 账本 + 答案→线协议)。
|
|
3
|
+
*
|
|
4
|
+
* 权威契约 docs/pi-web-ext-agent-interaction-unify-plan.md §2/§3。所有会话后端(CC 族
|
|
5
|
+
* control_request/can_use_tool、ACP session/request_permission、zcode 反向请求、pi/omp fork-rpc)
|
|
6
|
+
* 把各自协议里的 ask 转成同一个 `interaction_request` 事件,答案从同一个 `respondInteraction`
|
|
7
|
+
* 回来;本层负责语义换算与生命周期,各家 handle 只留「认帧 + 写字节」。
|
|
8
|
+
*
|
|
9
|
+
* 三条不可谈判的行为(都是事故/缺陷驱动,见方案 §0):
|
|
10
|
+
* 1. `answers`/`approved`/`feedback` 必须回填进工具入参(CC 的 execute() 就从 params 读答案与
|
|
11
|
+
* 审批结论),否则 AskUserQuestion 是假支持——卡片能点、答案进不去;方案拒绝也丢反馈通道。
|
|
12
|
+
* 2. 未决 ask 落 sidecar 且可 replay 补发(**复用原 requestId**):handle 被重建/前端刷新后
|
|
13
|
+
* 卡片若不再可点,CLI 会永久等一个没人回答的授权(qoder 会话挂 5 小时的根因)。
|
|
14
|
+
* 3. 选项表缺失/未知 optionId 一律 fail-closed,绝不随便挑一个当用户同意。
|
|
15
|
+
*
|
|
16
|
+
* 测试:agent-interaction.test.mjs
|
|
17
|
+
*/
|
|
18
|
+
import { randomUUID } from "node:crypto";
|
|
19
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
20
|
+
import { dirname } from "node:path";
|
|
21
|
+
|
|
22
|
+
export type InteractionKind = "tool_auth" | "ask_user" | "plan_approval" | "open_url" | "generic";
|
|
23
|
+
export type InteractionExpireReason = "turn_end" | "cancelled" | "dead";
|
|
24
|
+
|
|
25
|
+
export interface InteractionOption {
|
|
26
|
+
optionId: string;
|
|
27
|
+
kind?: string;
|
|
28
|
+
name?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface InteractionQuestionOption {
|
|
32
|
+
label: string;
|
|
33
|
+
description?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface InteractionQuestion {
|
|
37
|
+
header?: string;
|
|
38
|
+
question: string;
|
|
39
|
+
multiSelect?: boolean;
|
|
40
|
+
options: InteractionQuestionOption[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 后端广播的统一 ask 事件(宿主原样透传到前端 sessionRequestCard 插槽)。 */
|
|
44
|
+
export interface InteractionRequestEvent {
|
|
45
|
+
type: "interaction_request";
|
|
46
|
+
requestId: string;
|
|
47
|
+
kind: InteractionKind;
|
|
48
|
+
capability: "respondInteraction";
|
|
49
|
+
toolName?: string;
|
|
50
|
+
input?: unknown;
|
|
51
|
+
questions?: InteractionQuestion[];
|
|
52
|
+
options?: InteractionOption[];
|
|
53
|
+
plan?: string;
|
|
54
|
+
url?: string;
|
|
55
|
+
launchUrl?: string;
|
|
56
|
+
prompt?: string;
|
|
57
|
+
reason?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface InteractionExpiredEvent {
|
|
61
|
+
type: "interaction_expired";
|
|
62
|
+
requestId: string;
|
|
63
|
+
reason: InteractionExpireReason;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 前端作答(宿主 respond_interaction 命令体)。 */
|
|
67
|
+
export interface InteractionAnswer {
|
|
68
|
+
action: "accept" | "decline";
|
|
69
|
+
answers?: Record<string, string | string[]>;
|
|
70
|
+
message?: string;
|
|
71
|
+
optionId?: string;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 账本条目(sidecar 落盘形态 = 事件 + 落盘时间)。 */
|
|
75
|
+
export interface PendingAsk {
|
|
76
|
+
requestId: string;
|
|
77
|
+
kind: InteractionKind;
|
|
78
|
+
toolName?: string;
|
|
79
|
+
input?: unknown;
|
|
80
|
+
options?: InteractionOption[];
|
|
81
|
+
askedAt: number;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface InteractionRecord {
|
|
85
|
+
requestId: string;
|
|
86
|
+
kind: InteractionKind;
|
|
87
|
+
toolName?: string;
|
|
88
|
+
input?: unknown;
|
|
89
|
+
decision: "pending" | "allow" | "deny" | "cancelled";
|
|
90
|
+
note?: string;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface InteractionLedger {
|
|
94
|
+
/** 记一笔未决并广播;requestId 给了就复用(应答必须回同一个 id)。 */
|
|
95
|
+
open(partial: Partial<InteractionRequestEvent> & { kind?: InteractionKind; requestId?: string }): string;
|
|
96
|
+
/** 作答收口:命中返回账项并清账,未命中 null(重复应答幂等)。 */
|
|
97
|
+
settle(requestId: string, answer: InteractionAnswer): PendingAsk | null;
|
|
98
|
+
pending(): PendingAsk[];
|
|
99
|
+
/**
|
|
100
|
+
* 未决的广播帧(不发):订阅者补发用——前端刷新后卡片丢了而 CLI 还在等,
|
|
101
|
+
* 拿这批帧重投即可(同 requestId,幂等,不新造)。
|
|
102
|
+
*/
|
|
103
|
+
replay(): InteractionRequestEvent[];
|
|
104
|
+
/** turn 收口 / 进程死亡:逐个 interaction_expired + 留痕 + 清空。 */
|
|
105
|
+
failPending(reason: InteractionExpireReason): number;
|
|
106
|
+
/** 启动时从 sidecar 恢复未决,返回恢复条数(无 sidecar 路径返回 0)。 */
|
|
107
|
+
load(): number;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ── kind 裁决 ──────────────────────────────────────────────────────────────
|
|
111
|
+
|
|
112
|
+
/** 剥 mcp__server__ 前缀并归一大小写/分隔符,供工具名匹配。 */
|
|
113
|
+
function normalizeToolName(name?: string): string {
|
|
114
|
+
if (!name) return "";
|
|
115
|
+
let base = name;
|
|
116
|
+
if (base.startsWith("mcp__")) {
|
|
117
|
+
// server 名可含下划线(mcp__my_server__AskUserQuestion)→ 取最后一个分隔符之后
|
|
118
|
+
const tail = base.lastIndexOf("__");
|
|
119
|
+
base = tail > 5 ? base.slice(tail + 2) : base.slice(5);
|
|
120
|
+
}
|
|
121
|
+
return base.replace(/[^A-Za-z]/g, "").toLowerCase();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function asRecord(value: unknown): Record<string, unknown> | null {
|
|
125
|
+
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function isValidQuestions(value: unknown): value is InteractionQuestion[] {
|
|
129
|
+
const arr = Array.isArray(value) ? value : null;
|
|
130
|
+
if (!arr || arr.length === 0) return false;
|
|
131
|
+
return arr.every((q) => {
|
|
132
|
+
const item = asRecord(q);
|
|
133
|
+
return !!item && typeof item.question === "string" && Array.isArray(item.options);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 后端显式标注(zcode schema.interaction)优先,其次工具名。 */
|
|
138
|
+
export function deriveAskKind(toolName?: string, input?: unknown): InteractionKind {
|
|
139
|
+
const marked = asRecord(input)?.interaction;
|
|
140
|
+
if (marked === "plan_approval") return "plan_approval";
|
|
141
|
+
if (marked === "ask_user") return "ask_user";
|
|
142
|
+
const name = normalizeToolName(toolName);
|
|
143
|
+
if (name === "exitplanmode") return "plan_approval";
|
|
144
|
+
if (name === "askuserquestion") return isValidQuestions(asRecord(input)?.questions) ? "ask_user" : "tool_auth";
|
|
145
|
+
return "tool_auth";
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ── 答案 → 各家线协议 ───────────────────────────────────────────────────────
|
|
149
|
+
|
|
150
|
+
function denyMessage(answer: InteractionAnswer): string {
|
|
151
|
+
return answer.message && answer.message.trim() ? answer.message : "denied by user";
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** CC 族 control_response.response(allow/deny + updatedInput 回填)。 */
|
|
155
|
+
export function toControlResponse(
|
|
156
|
+
ask: { kind: InteractionKind; input?: unknown; options?: InteractionOption[] },
|
|
157
|
+
answer: InteractionAnswer,
|
|
158
|
+
): Record<string, unknown> {
|
|
159
|
+
if (answer.optionId && ask.options?.length) {
|
|
160
|
+
const picked = ask.options.find((o) => o?.optionId === answer.optionId);
|
|
161
|
+
if (!picked) return { behavior: "deny", message: `unknown optionId: ${answer.optionId}` };
|
|
162
|
+
return normalizeOptionKind(picked) === "reject"
|
|
163
|
+
? { behavior: "deny", message: denyMessage(answer) }
|
|
164
|
+
: { behavior: "allow" };
|
|
165
|
+
}
|
|
166
|
+
if (ask.kind === "plan_approval") {
|
|
167
|
+
// 审批的拒绝**不是**权限拒绝:deny 只会回一条「用户拒绝授权」,方案反馈通道(feedback)
|
|
168
|
+
// 与「修订再继续」的语义就丢了。ExitPlanMode 的 execute 读 params.approved/feedback。
|
|
169
|
+
const base = asRecord(ask.input) ?? {};
|
|
170
|
+
if (answer.action === "decline") {
|
|
171
|
+
const feedback = answer.message && answer.message.trim() ? answer.message.trim() : undefined;
|
|
172
|
+
return { behavior: "allow", updatedInput: { ...base, approved: false, ...(feedback ? { feedback } : {}) } };
|
|
173
|
+
}
|
|
174
|
+
return { behavior: "allow", updatedInput: { ...base, approved: true } };
|
|
175
|
+
}
|
|
176
|
+
if (answer.action === "decline") return { behavior: "deny", message: denyMessage(answer) };
|
|
177
|
+
if (ask.kind === "ask_user") {
|
|
178
|
+
// AskUserQuestion 的 execute 从 params.answers 读(键=问题文本),不回填=空答案
|
|
179
|
+
return { behavior: "allow", updatedInput: { ...(asRecord(ask.input) ?? {}), answers: answer.answers ?? {} } };
|
|
180
|
+
}
|
|
181
|
+
return { behavior: "allow" };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** ACP 族:作答必须落到具体 optionId,查不到就不应答(fail-closed)。 */
|
|
185
|
+
export function toAcpOptionId(options: InteractionOption[] | undefined, answer: InteractionAnswer): string | undefined {
|
|
186
|
+
const list = (options ?? []).filter((o) => o && typeof o.optionId === "string");
|
|
187
|
+
if (answer.optionId) return list.find((o) => o.optionId === answer.optionId)?.optionId;
|
|
188
|
+
const want = answer.action === "decline" ? "reject" : "allow";
|
|
189
|
+
return list.find((o) => normalizeOptionKind(o) === want)?.optionId;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function normalizeOptionKind(option: InteractionOption): "allow" | "reject" {
|
|
193
|
+
const text = `${option.kind ?? ""} ${option.name ?? ""}`.toLowerCase();
|
|
194
|
+
return /reject|deny|cancel|refuse/.test(text) ? "reject" : "allow";
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ── pending 账本 ────────────────────────────────────────────────────────────
|
|
198
|
+
|
|
199
|
+
const ALLOWED_KINDS = new Set<InteractionKind>(["tool_auth", "ask_user", "plan_approval", "open_url", "generic"]);
|
|
200
|
+
const TEXT_FIELDS = ["plan", "url", "launchUrl", "prompt", "reason"] as const;
|
|
201
|
+
|
|
202
|
+
function sanitizeString(value: unknown): string | undefined {
|
|
203
|
+
return typeof value === "string" && value ? value : undefined;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function sanitizeOptions(value: unknown): InteractionOption[] | undefined {
|
|
207
|
+
if (!Array.isArray(value)) return undefined;
|
|
208
|
+
const list = value.filter((o) => {
|
|
209
|
+
const item = asRecord(o);
|
|
210
|
+
return !!item && typeof item.optionId === "string";
|
|
211
|
+
}) as InteractionOption[];
|
|
212
|
+
return list.length ? list : undefined;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function sanitizeQuestions(value: unknown): InteractionQuestion[] | undefined {
|
|
216
|
+
if (!Array.isArray(value)) return undefined;
|
|
217
|
+
const list = value.filter((q) => {
|
|
218
|
+
const item = asRecord(q);
|
|
219
|
+
return !!item && typeof item.question === "string" && Array.isArray(item.options);
|
|
220
|
+
}) as InteractionQuestion[];
|
|
221
|
+
return list.length ? list : undefined;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** 不信任外部输入:逐字段消毒后同时产出账项与广播事件(sidecar 读回也走这条路)。 */
|
|
225
|
+
function normalizeAsk(partial: Partial<InteractionRequestEvent> & { requestId?: string }, askedAt: number):
|
|
226
|
+
{ ask: PendingAsk; event: InteractionRequestEvent } {
|
|
227
|
+
const requestId = sanitizeString(partial.requestId) ?? randomUUID();
|
|
228
|
+
const kind = ALLOWED_KINDS.has(partial.kind as InteractionKind) ? partial.kind as InteractionKind : "tool_auth";
|
|
229
|
+
const ask: PendingAsk = { requestId, kind, askedAt };
|
|
230
|
+
const event: InteractionRequestEvent = { type: "interaction_request", requestId, kind, capability: "respondInteraction" };
|
|
231
|
+
const toolName = sanitizeString(partial.toolName);
|
|
232
|
+
if (toolName) { ask.toolName = toolName; event.toolName = toolName; }
|
|
233
|
+
if (partial.input !== undefined) { ask.input = partial.input; event.input = partial.input; }
|
|
234
|
+
const options = sanitizeOptions(partial.options);
|
|
235
|
+
if (options) { ask.options = options; event.options = options; }
|
|
236
|
+
const questions = sanitizeQuestions(partial.questions);
|
|
237
|
+
if (questions) event.questions = questions;
|
|
238
|
+
for (const key of TEXT_FIELDS) {
|
|
239
|
+
const value = sanitizeString(partial[key]);
|
|
240
|
+
if (value) event[key] = value;
|
|
241
|
+
}
|
|
242
|
+
return { ask, event };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** sidecar 落盘形态 = 广播事件 + 落盘时间(重连补发要发当初那一帧,不能只剩半截)。 */
|
|
246
|
+
type PersistedAsk = InteractionRequestEvent & { askedAt: number };
|
|
247
|
+
|
|
248
|
+
export function createInteractionLedger(opts: {
|
|
249
|
+
emit(event: InteractionRequestEvent | InteractionExpiredEvent): void;
|
|
250
|
+
/**
|
|
251
|
+
* sidecar 文件路径(惰性取:handle 构造期会话 id 还是占位值,见各家队列 sidecar 同形注释)。
|
|
252
|
+
* 返 undefined = 不落盘(跨重建重发能力自动降级)。
|
|
253
|
+
*/
|
|
254
|
+
sidecarFile?: () => string | undefined;
|
|
255
|
+
record?(note: InteractionRecord): void;
|
|
256
|
+
now?: () => number;
|
|
257
|
+
}): InteractionLedger {
|
|
258
|
+
const entries = new Map<string, { ask: PendingAsk; event: InteractionRequestEvent }>();
|
|
259
|
+
const now = opts.now ?? (() => Date.now());
|
|
260
|
+
|
|
261
|
+
const persist = (): void => {
|
|
262
|
+
const path = opts.sidecarFile?.();
|
|
263
|
+
if (!path) return;
|
|
264
|
+
// 原子写顺序(windows-compat-lessons §0.5):先写 tmp 再 rename
|
|
265
|
+
try {
|
|
266
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
267
|
+
const rows: PersistedAsk[] = [...entries.values()].map(({ ask, event }) => ({ ...event, askedAt: ask.askedAt }));
|
|
268
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
269
|
+
writeFileSync(tmp, JSON.stringify(rows), "utf8");
|
|
270
|
+
renameSync(tmp, path);
|
|
271
|
+
} catch {
|
|
272
|
+
/* sidecar 失败不得杀会话:重建时少一次重发而已 */
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
const note = (ask: PendingAsk, decision: InteractionRecord["decision"], msg?: string): void => {
|
|
277
|
+
try {
|
|
278
|
+
opts.record?.({ requestId: ask.requestId, kind: ask.kind, toolName: ask.toolName, input: ask.input, decision, note: msg });
|
|
279
|
+
} catch {
|
|
280
|
+
/* 留痕是附加品,不能反噬应答链路 */
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
return {
|
|
285
|
+
open: (partial) => {
|
|
286
|
+
const { ask, event } = normalizeAsk(partial, now());
|
|
287
|
+
entries.set(ask.requestId, { ask, event });
|
|
288
|
+
note(ask, "pending");
|
|
289
|
+
persist();
|
|
290
|
+
opts.emit(event);
|
|
291
|
+
return ask.requestId;
|
|
292
|
+
},
|
|
293
|
+
|
|
294
|
+
settle: (requestId, answer) => {
|
|
295
|
+
const entry = entries.get(requestId);
|
|
296
|
+
if (!entry) return null;
|
|
297
|
+
note(entry.ask, answer.action === "accept" ? "allow" : "deny", answer.message);
|
|
298
|
+
entries.delete(requestId);
|
|
299
|
+
persist();
|
|
300
|
+
return { ...entry.ask };
|
|
301
|
+
},
|
|
302
|
+
|
|
303
|
+
pending: () => [...entries.values()].map(({ ask }) => ({ ...ask })),
|
|
304
|
+
|
|
305
|
+
replay: () => [...entries.values()].map(({ event }) => event),
|
|
306
|
+
|
|
307
|
+
failPending: (reason) => {
|
|
308
|
+
if (entries.size === 0) return 0;
|
|
309
|
+
const list = [...entries.entries()];
|
|
310
|
+
entries.clear();
|
|
311
|
+
for (const [, { ask, event }] of list) {
|
|
312
|
+
note(ask, "cancelled");
|
|
313
|
+
opts.emit({ type: "interaction_expired", requestId: event.requestId, reason });
|
|
314
|
+
}
|
|
315
|
+
persist();
|
|
316
|
+
return list.length;
|
|
317
|
+
},
|
|
318
|
+
|
|
319
|
+
load: () => {
|
|
320
|
+
const path = opts.sidecarFile?.();
|
|
321
|
+
if (!path) return 0;
|
|
322
|
+
let raw: unknown;
|
|
323
|
+
try {
|
|
324
|
+
raw = JSON.parse(readFileSync(path, "utf8"));
|
|
325
|
+
} catch {
|
|
326
|
+
return 0;
|
|
327
|
+
}
|
|
328
|
+
if (!Array.isArray(raw)) return 0;
|
|
329
|
+
let count = 0;
|
|
330
|
+
for (const item of raw) {
|
|
331
|
+
const entry = asRecord(item);
|
|
332
|
+
if (!entry || !sanitizeString(entry.requestId) || !ALLOWED_KINDS.has(entry.kind as InteractionKind)) continue;
|
|
333
|
+
const { ask, event } = normalizeAsk(entry as Partial<InteractionRequestEvent>, Number(entry.askedAt) || now());
|
|
334
|
+
entries.set(ask.requestId, { ask, event });
|
|
335
|
+
count++;
|
|
336
|
+
}
|
|
337
|
+
return count;
|
|
338
|
+
},
|
|
339
|
+
};
|
|
340
|
+
}
|