@aiti-ai/ext-shared 0.0.0-stage → 0.1.11
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/README.md +36 -2
- 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
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ext-session-usage —— 外部 agent 会话 → token 用量行 的共享纯函数解析层。
|
|
3
|
+
*
|
|
4
|
+
* 权威源:pi-web-ext/_shared/ext-session-usage.ts(改动后同步到各扩展副本——按
|
|
5
|
+
* cursor-cli-store.ts 先例:_shared 为唯一权威,aiti-ai-usage / session-manager
|
|
6
|
+
* 各留副本或直接引用)。
|
|
7
|
+
*
|
|
8
|
+
* 覆盖源(P0,wire 形状均本机 2026-09 实测钉死,见 docs/aiti-ai-usage-ext-agent-token-ingest-plan.md §2.2):
|
|
9
|
+
* - claude Claude Code ~/.claude/projects/<cwd>/<sid>.jsonl
|
|
10
|
+
* message.usage.{input_tokens, output_tokens,
|
|
11
|
+
* cache_creation_input_tokens, cache_read_input_tokens} + message.model
|
|
12
|
+
* - qodercn QoderCN ~/.qoder-cn/projects/<cwd>/<sid>.jsonl(CC 同构 fork,1.1.44 逐键一致)
|
|
13
|
+
* message.model + message.usage.credits(Qoder 自有积分单位、非金额);
|
|
14
|
+
* token 恒 0(Qoder 不落盘计费 token)
|
|
15
|
+
* - codebuddy CodeBuddy Code ~/.codebuddy/projects/<cwd>/<sid>.jsonl
|
|
16
|
+
* providerData.rawUsage.{prompt_tokens, completion_tokens, total_tokens,
|
|
17
|
+
* cache_read_input_tokens, cache_creation_input_tokens,
|
|
18
|
+
* completion_tokens_details.reasoning_tokens} + providerData.model
|
|
19
|
+
* - zcode ZCode ~/.zcode/cli/db/db.sqlite(readOnly 直读,禁整库复制——2026-09-12 拷贝风暴教训)
|
|
20
|
+
* message.data JSON: tokens{total,input,output,reasoning,cache{read,write}}
|
|
21
|
+
* + modelID + providerID + cost
|
|
22
|
+
*
|
|
23
|
+
* P1 model-only 三源(token/成本恒 0——源不落盘计费数据;会话级 model/provider 归因,报表按
|
|
24
|
+
* totalTokens=0 标注「token 无数据」):
|
|
25
|
+
* - codex Codex CLI ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl 的 turn_context/message.model
|
|
26
|
+
* - opencode OpenCode ~/.local/share/opencode/storage/message/<sid>/msg_*.json 的 modelID/providerID
|
|
27
|
+
* - cursor Cursor CLI ~/.cursor/ai-tracking/ai-code-tracking.db ai_code_hashes.model(最新一条)
|
|
28
|
+
*
|
|
29
|
+
* 噪音过滤(防零数据源污染报表):
|
|
30
|
+
* - Qoder 0.1.24 国际版 usage 恒 0 且无 model/credits → 不产出行(官方不写 token/model);
|
|
31
|
+
* - ZCode timeline_event 类消息 tokens 恒 0 且 cost 0 → 不产出行。
|
|
32
|
+
*
|
|
33
|
+
* 格式回归测试:pi-web-ext/_shared/ext-session-usage.test.mjs(fixture 钉死 wire 假设)。
|
|
34
|
+
*/
|
|
35
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
36
|
+
import { homedir } from "node:os";
|
|
37
|
+
import { join } from "node:path";
|
|
38
|
+
import { DatabaseSync } from "node:sqlite";
|
|
39
|
+
|
|
40
|
+
// ---------------------------------------------------------------- 类型
|
|
41
|
+
|
|
42
|
+
/** 统一用量行(agent 维度归因;credits 为 Qoder 系独立积分,非金额)。 */
|
|
43
|
+
export interface ExtUsageRow {
|
|
44
|
+
agent: string;
|
|
45
|
+
sid: string;
|
|
46
|
+
ts: number; // epoch ms
|
|
47
|
+
provider: string;
|
|
48
|
+
model: string;
|
|
49
|
+
input: number;
|
|
50
|
+
output: number;
|
|
51
|
+
cacheRead: number;
|
|
52
|
+
cacheWrite: number;
|
|
53
|
+
reasoning: number;
|
|
54
|
+
totalTokens: number;
|
|
55
|
+
costTotal: number;
|
|
56
|
+
credits: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 会话引用:path 为物理文件或 "db#session:<id>" 虚拟路径;rev = 源侧版本(time_updated ms)。 */
|
|
60
|
+
export interface ExtSessionRef {
|
|
61
|
+
agent: string;
|
|
62
|
+
sid: string;
|
|
63
|
+
path: string;
|
|
64
|
+
rev?: number;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface ExtUsageSource {
|
|
68
|
+
id: string;
|
|
69
|
+
label: string;
|
|
70
|
+
/** roots 任一存在 → 源已安装。 */
|
|
71
|
+
probe(): boolean;
|
|
72
|
+
/** 枚举会话(zcode db 短暂不可读时允许抛错,调用方 catch 静默跳过本轮)。 */
|
|
73
|
+
list(): ExtSessionRef[];
|
|
74
|
+
/** 解析一个会话 → 用量行(空数组 = 无可摄入数据)。 */
|
|
75
|
+
parse(ref: ExtSessionRef): ExtUsageRow[];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ---------------------------------------------------------------- 工具
|
|
79
|
+
|
|
80
|
+
function num(v: unknown): number {
|
|
81
|
+
const n = Number(v);
|
|
82
|
+
return Number.isFinite(n) && n >= 0 ? n : 0;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const SID_UUID_RE = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i;
|
|
86
|
+
|
|
87
|
+
function listProjectJsonls(root: string): Array<{ sid: string; path: string }> {
|
|
88
|
+
const out: Array<{ sid: string; path: string }> = [];
|
|
89
|
+
if (!existsSync(root)) return out;
|
|
90
|
+
for (const dir of readdirSync(root)) {
|
|
91
|
+
const d = join(root, dir);
|
|
92
|
+
try { if (!statSync(d).isDirectory()) continue; } catch { continue; }
|
|
93
|
+
for (const f of readdirSync(d)) {
|
|
94
|
+
const m = SID_UUID_RE.exec(f);
|
|
95
|
+
if (m) out.push({ sid: m[1], path: join(d, f) });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** provider 归一(无显式 providerID 的源按 agent 身份 + 模型名前缀推断)。 */
|
|
102
|
+
export function inferProvider(agent: string, model: string): string {
|
|
103
|
+
const m = (model || "").toLowerCase();
|
|
104
|
+
if (m.startsWith("glm")) return "zhipu";
|
|
105
|
+
if (m.startsWith("qmodel")) return "qoder";
|
|
106
|
+
if (m.startsWith("claude")) return "anthropic";
|
|
107
|
+
if (m.includes("/")) return m.split("/")[0]!.trim() || agent; // codex 的 nvidia/xxx
|
|
108
|
+
return agent;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ---------------------------------------------------------------- claude-like 家族(claude / qodercn)
|
|
112
|
+
|
|
113
|
+
function numUsage(u: Record<string, unknown>): { input: number; output: number; cacheRead: number; cacheWrite: number; credits: number } {
|
|
114
|
+
return {
|
|
115
|
+
input: num(u.input_tokens),
|
|
116
|
+
output: num(u.output_tokens),
|
|
117
|
+
cacheRead: num(u.cache_read_input_tokens),
|
|
118
|
+
cacheWrite: num(u.cache_creation_input_tokens),
|
|
119
|
+
credits: num(u.credits),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** CC / QoderCN / Qoder 同构 jsonl → 用量行。
|
|
124
|
+
* 噪音过滤:usage 存在但全部字段 0 且无 model 且无 credits 的行(Qoder 0.1.24 空计费)不产出。 */
|
|
125
|
+
export function parseClaudeLikeSession(agent: string, filePath: string, sid: string): ExtUsageRow[] {
|
|
126
|
+
let raw: string;
|
|
127
|
+
try { raw = readFileSync(filePath, "utf8"); } catch { return []; }
|
|
128
|
+
const rows: ExtUsageRow[] = [];
|
|
129
|
+
for (const line of raw.split("\n")) {
|
|
130
|
+
if (!line.trim()) continue;
|
|
131
|
+
let e: any;
|
|
132
|
+
try { e = JSON.parse(line); } catch { continue; }
|
|
133
|
+
if (e?.type !== "assistant") continue;
|
|
134
|
+
const m = e.message ?? {};
|
|
135
|
+
const u = m.usage;
|
|
136
|
+
if (!u || typeof u !== "object") continue;
|
|
137
|
+
const { input, output, cacheRead, cacheWrite, credits } = numUsage(u);
|
|
138
|
+
const model = typeof m.model === "string" ? m.model : "";
|
|
139
|
+
if (model === "<synthetic>") continue; // aiti e2e 测试占位模型,非真实使用
|
|
140
|
+
if (!input && !output && !cacheRead && !cacheWrite && !credits && !model) continue; // 空计费噪音
|
|
141
|
+
const ts = Date.parse(String(e.timestamp ?? ""));
|
|
142
|
+
if (!Number.isFinite(ts) || ts <= 0) continue;
|
|
143
|
+
rows.push({
|
|
144
|
+
agent, sid, ts,
|
|
145
|
+
provider: inferProvider(agent, model),
|
|
146
|
+
model: model || "?",
|
|
147
|
+
input, output, cacheRead, cacheWrite,
|
|
148
|
+
reasoning: 0,
|
|
149
|
+
totalTokens: input + output, // CC 的 total 不含 cache;cache 单独列展示
|
|
150
|
+
costTotal: 0,
|
|
151
|
+
credits,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
return rows;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ---------------------------------------------------------------- CodeBuddy Code(腾讯 cbc)
|
|
158
|
+
|
|
159
|
+
/** cbc jsonl → 用量行(token 在 providerData.rawUsage,OpenAI 兼容字段名)。 */
|
|
160
|
+
export function parseCodebuddySession(filePath: string, sid: string): ExtUsageRow[] {
|
|
161
|
+
let raw: string;
|
|
162
|
+
try { raw = readFileSync(filePath, "utf8"); } catch { return []; }
|
|
163
|
+
const rows: ExtUsageRow[] = [];
|
|
164
|
+
for (const line of raw.split("\n")) {
|
|
165
|
+
if (!line.trim()) continue;
|
|
166
|
+
let e: any;
|
|
167
|
+
try { e = JSON.parse(line); } catch { continue; }
|
|
168
|
+
if (e?.type !== "message" || e.role !== "assistant") continue;
|
|
169
|
+
const pd = e.providerData ?? {};
|
|
170
|
+
const ru = pd.rawUsage;
|
|
171
|
+
if (!ru || typeof ru !== "object") continue;
|
|
172
|
+
const input = num(ru.prompt_tokens);
|
|
173
|
+
const output = num(ru.completion_tokens);
|
|
174
|
+
const cacheRead = num(ru.cache_read_input_tokens) || num(ru.prompt_cache_hit_tokens);
|
|
175
|
+
const cacheWrite = num(ru.cache_creation_input_tokens) || num(ru.prompt_cache_write_tokens);
|
|
176
|
+
const reasoning = num(ru.completion_tokens_details?.reasoning_tokens);
|
|
177
|
+
const model = typeof pd.model === "string" && pd.model ? pd.model
|
|
178
|
+
: typeof pd.requestModelId === "string" ? pd.requestModelId : "";
|
|
179
|
+
// cbc timestamp 是数字 epoch 毫秒
|
|
180
|
+
const ts = num(e.timestamp);
|
|
181
|
+
if (!ts) continue;
|
|
182
|
+
rows.push({
|
|
183
|
+
agent: "codebuddy", sid,
|
|
184
|
+
ts,
|
|
185
|
+
provider: inferProvider("codebuddy", model),
|
|
186
|
+
model: model || "?",
|
|
187
|
+
input, output, cacheRead, cacheWrite, reasoning,
|
|
188
|
+
totalTokens: num(ru.total_tokens) || (input + output),
|
|
189
|
+
costTotal: 0, // cbc 的 rawUsage.credit 是账号余额语义,非本轮单价 × token
|
|
190
|
+
credits: 0,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
return rows;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ---------------------------------------------------------------- ZCode(智谱,SQLite 直读)
|
|
197
|
+
|
|
198
|
+
function openZcodeDb(dbPath: string): DatabaseSync | null {
|
|
199
|
+
if (!existsSync(dbPath)) return null;
|
|
200
|
+
try {
|
|
201
|
+
const db = new DatabaseSync(dbPath, { readOnly: true });
|
|
202
|
+
try { db.exec("PRAGMA busy_timeout = 2000"); } catch { /* pragma 不支持时忽略 */ }
|
|
203
|
+
return db;
|
|
204
|
+
} catch {
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** zcode message.data JSON → 用量行(禁整库复制,readOnly 直读)。
|
|
210
|
+
* ⚠ tokens 语义(2026-09 本机实测钉死):`input`/`cache.read` 是**会话级累积值**
|
|
211
|
+
* (逐条单调递增,含历史 context),`output` 是单轮值,`reasoning` 单轮。
|
|
212
|
+
* 摄入必须按会话内顺序对 input/cacheRead 做差分(当前 − 上一条 = 本轮增量),
|
|
213
|
+
* output/reasoning 直取;total = input增 + output(cache 单独列,不并入 total 防双计)。 */
|
|
214
|
+
export function parseZcodeSession(dbPath: string, sid: string): ExtUsageRow[] {
|
|
215
|
+
const db = openZcodeDb(dbPath);
|
|
216
|
+
if (!db) return [];
|
|
217
|
+
try {
|
|
218
|
+
const rows: ExtUsageRow[] = [];
|
|
219
|
+
const msgRows = db.prepare(
|
|
220
|
+
"SELECT data FROM message WHERE session_id = ? ORDER BY sequence, time_created, id",
|
|
221
|
+
).all(sid) as Array<{ data: string | null }>;
|
|
222
|
+
let prevInput = 0, prevCacheRead = 0, prevTotal: number | null = null;
|
|
223
|
+
for (const r of msgRows) {
|
|
224
|
+
if (!r.data) continue;
|
|
225
|
+
let d: Record<string, any>;
|
|
226
|
+
try { d = JSON.parse(r.data); } catch { continue; }
|
|
227
|
+
if (d.role !== "assistant") continue;
|
|
228
|
+
const t = d.tokens;
|
|
229
|
+
if (!t || typeof t !== "object") continue;
|
|
230
|
+
const output = num(t.output), reasoning = num(t.reasoning);
|
|
231
|
+
const cacheRead = num(t.cache?.read), cacheWrite = num(t.cache?.write);
|
|
232
|
+
const cost = num(d.cost);
|
|
233
|
+
const rawInput = num(t.input);
|
|
234
|
+
// 差分:input/cacheRead 为会话累积(窗口重置时当前 < 上一条 → 取当前)
|
|
235
|
+
const input = rawInput >= prevInput ? rawInput - prevInput : rawInput;
|
|
236
|
+
const cacheReadInc = cacheRead >= prevCacheRead ? cacheRead - prevCacheRead : cacheRead;
|
|
237
|
+
if (rawInput > 0) prevInput = rawInput;
|
|
238
|
+
if (cacheRead > 0) prevCacheRead = cacheRead;
|
|
239
|
+
if (!input && !output && !reasoning && !cacheReadInc && !cacheWrite && !cost) continue; // timeline_event 噪音
|
|
240
|
+
// 3.16.3 起新版只写 modelId/providerId(旧版双写 modelID/providerID 两种键)——双键兼容;
|
|
241
|
+
// provider 归一与 session-manager zcode adapter 对齐(builtin:/account: 前缀、-coding-plan/-start-plan 后缀)
|
|
242
|
+
const model = typeof d.modelId === "string" ? d.modelId : typeof d.modelID === "string" ? d.modelID : "";
|
|
243
|
+
const rawProvider = typeof d.providerId === "string" ? d.providerId : typeof d.providerID === "string" ? d.providerID : "";
|
|
244
|
+
const provider = rawProvider.replace(/^(?:builtin|account):/, "").replace(/-(?:coding|start)-plan$/, "") || "zcode";
|
|
245
|
+
const created = num(d.time?.created);
|
|
246
|
+
if (!created) continue;
|
|
247
|
+
rows.push({
|
|
248
|
+
agent: "zcode", sid,
|
|
249
|
+
ts: created,
|
|
250
|
+
provider,
|
|
251
|
+
model: model || "?",
|
|
252
|
+
input, output, cacheRead: cacheReadInc, cacheWrite, reasoning,
|
|
253
|
+
totalTokens: num(t.total) > 0
|
|
254
|
+
// 官方 total 也是累积:差分 same 方式(无上一条 total 时取 total 本身)
|
|
255
|
+
? (prevTotal !== null && num(t.total) >= prevTotal ? num(t.total) - prevTotal : num(t.total))
|
|
256
|
+
: (input + output + reasoning + cacheReadInc + cacheWrite),
|
|
257
|
+
costTotal: cost,
|
|
258
|
+
credits: 0,
|
|
259
|
+
});
|
|
260
|
+
if (num(t.total) > 0) prevTotal = num(t.total);
|
|
261
|
+
}
|
|
262
|
+
return rows;
|
|
263
|
+
} finally {
|
|
264
|
+
db.close();
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// ---------------------------------------------------------------- 源工厂
|
|
269
|
+
|
|
270
|
+
/** 枚举 ~/.claude 或 ~/.qoder-cn 的 projects(claude-like 结构)。 */
|
|
271
|
+
function listClaudeLikeProjects(projectsRoot: string, agent: string): ExtSessionRef[] {
|
|
272
|
+
return listProjectJsonls(projectsRoot).map(({ sid, path }) => ({ agent, sid, path }));
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** 枚举 ~/.codebuddy/projects。 */
|
|
276
|
+
function listCodebuddyProjects(projectsRoot: string): ExtSessionRef[] {
|
|
277
|
+
return listProjectJsonls(projectsRoot).map(({ sid, path }) => ({ agent: "codebuddy", sid, path }));
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// ---------------------------------------------------------------- P1 model-only 家族(codex / opencode / cursor)
|
|
281
|
+
|
|
282
|
+
/** model-only 行骨架:token/成本全 0(源不落盘计费数据)——会话级 model/provider 归因用;
|
|
283
|
+
* 报表层按 totalTokens=0 标注「token 无数据」,不进 token 汇总口径。 */
|
|
284
|
+
function modelOnlyRow(agent: string, sid: string, ts: number, model: string, provider?: string): ExtUsageRow {
|
|
285
|
+
return {
|
|
286
|
+
agent, sid, ts,
|
|
287
|
+
provider: provider || inferProvider(agent, model),
|
|
288
|
+
model,
|
|
289
|
+
input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0,
|
|
290
|
+
totalTokens: 0, costTotal: 0, credits: 0,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Codex:~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl —— turn_context/message 行的 model 字段(首个即启动模型)。 */
|
|
295
|
+
export function parseCodexModelOnly(filePath: string, sid: string): ExtUsageRow[] {
|
|
296
|
+
let model = "";
|
|
297
|
+
let ts = 0;
|
|
298
|
+
try {
|
|
299
|
+
for (const line of readFileSync(filePath, "utf8").split("\n")) {
|
|
300
|
+
if (!line.includes('"model"')) continue;
|
|
301
|
+
try {
|
|
302
|
+
const d = JSON.parse(line) as { payload?: { model?: unknown }; model?: unknown; timestamp?: unknown };
|
|
303
|
+
const m = d.payload?.model ?? d.model;
|
|
304
|
+
if (typeof m === "string" && m) {
|
|
305
|
+
model = m;
|
|
306
|
+
if (typeof d.timestamp === "string") ts = Date.parse(d.timestamp) || ts;
|
|
307
|
+
break;
|
|
308
|
+
}
|
|
309
|
+
} catch { /* 跳坏行 */ }
|
|
310
|
+
}
|
|
311
|
+
if (!ts) ts = statSync(filePath).mtimeMs;
|
|
312
|
+
} catch { return []; }
|
|
313
|
+
if (!model) return [];
|
|
314
|
+
return [modelOnlyRow("codex", sid, ts, model)];
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function listCodexSessions(root: string): ExtSessionRef[] {
|
|
318
|
+
const out: ExtSessionRef[] = [];
|
|
319
|
+
if (!existsSync(root)) return out;
|
|
320
|
+
const uuidRe = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i;
|
|
321
|
+
const walk = (dir: string, depth: number) => {
|
|
322
|
+
if (depth > 3) return;
|
|
323
|
+
for (const name of readdirSync(dir)) {
|
|
324
|
+
const p = join(dir, name);
|
|
325
|
+
try { if (statSync(p).isDirectory()) { walk(p, depth + 1); continue; } } catch { continue; }
|
|
326
|
+
const m = uuidRe.exec(name);
|
|
327
|
+
if (!m) continue;
|
|
328
|
+
try { out.push({ agent: "codex", sid: m[1], path: p, rev: statSync(p).mtimeMs }); } catch { continue; }
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
walk(root, 0);
|
|
332
|
+
return out;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** OpenCode:storage/session/<proj>/ses_*.json(元数据)+ storage/message/<proj>/msg_*.json(modelID/providerID)。 */
|
|
336
|
+
export function parseOpencodeModelOnly(root: string, sessionJsonPath: string, sid: string): ExtUsageRow[] {
|
|
337
|
+
try {
|
|
338
|
+
const sess = JSON.parse(readFileSync(sessionJsonPath, "utf8")) as {
|
|
339
|
+
projectID?: unknown; time?: { updated?: unknown; created?: unknown };
|
|
340
|
+
};
|
|
341
|
+
void sess;
|
|
342
|
+
const msgDir = join(root, "storage", "message", sid); // 实测:message 按会话分目录(storage/message/<sid>/msg_*.json)
|
|
343
|
+
if (!existsSync(msgDir)) return [];
|
|
344
|
+
let best: { ts: number; modelID: string; providerID: string } | null = null;
|
|
345
|
+
for (const name of readdirSync(msgDir)) {
|
|
346
|
+
if (!name.endsWith(".json")) continue;
|
|
347
|
+
const p = join(msgDir, name);
|
|
348
|
+
let m: any;
|
|
349
|
+
try { m = JSON.parse(readFileSync(p, "utf8")); } catch { continue; }
|
|
350
|
+
if (m?.sessionID !== sid || m?.role !== "assistant" || typeof m?.modelID !== "string" || !m.modelID) continue;
|
|
351
|
+
const ts = Number(m?.time?.created) || 0;
|
|
352
|
+
if (!best || ts >= best.ts) best = { ts, modelID: m.modelID, providerID: typeof m.providerID === "string" ? m.providerID : "" };
|
|
353
|
+
}
|
|
354
|
+
if (!best) return [];
|
|
355
|
+
const ts = best.ts || Number(sess.time?.updated) || Number(sess.time?.created) || 0;
|
|
356
|
+
return [modelOnlyRow("opencode", sid, ts, best.modelID, best.providerID || undefined)];
|
|
357
|
+
} catch { return []; }
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function listOpencodeSessions(root: string): ExtSessionRef[] {
|
|
361
|
+
const sessDir = join(root, "storage", "session");
|
|
362
|
+
const out: ExtSessionRef[] = [];
|
|
363
|
+
if (!existsSync(sessDir)) return out;
|
|
364
|
+
for (const proj of readdirSync(sessDir)) {
|
|
365
|
+
const dir = join(sessDir, proj);
|
|
366
|
+
try { if (!statSync(dir).isDirectory()) continue; } catch { continue; }
|
|
367
|
+
for (const name of readdirSync(dir)) {
|
|
368
|
+
if (!name.startsWith("ses_") || !name.endsWith(".json")) continue;
|
|
369
|
+
const p = join(dir, name);
|
|
370
|
+
try {
|
|
371
|
+
const j = JSON.parse(readFileSync(p, "utf8")) as { id?: unknown; time?: { updated?: unknown } };
|
|
372
|
+
if (typeof j.id !== "string") continue;
|
|
373
|
+
out.push({ agent: "opencode", sid: j.id, path: p, ...(typeof j.time?.updated === "number" ? { rev: j.time.updated } : {}) });
|
|
374
|
+
} catch { continue; }
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return out;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Cursor CLI:~/.cursor/ai-tracking/ai-code-tracking.db(readOnly 直读)——ai_code_hashes.model 按会话最新一条。 */
|
|
381
|
+
function openCursorDb(dbPath: string): DatabaseSync | null {
|
|
382
|
+
if (!existsSync(dbPath)) return null;
|
|
383
|
+
try {
|
|
384
|
+
const db = new DatabaseSync(dbPath, { readOnly: true });
|
|
385
|
+
try { db.exec("PRAGMA busy_timeout = 2000"); } catch { /* ignore */ }
|
|
386
|
+
return db;
|
|
387
|
+
} catch { return null; }
|
|
388
|
+
}
|
|
389
|
+
export function parseCursorModelOnly(dbPath: string, sid: string): ExtUsageRow[] {
|
|
390
|
+
const db = openCursorDb(dbPath);
|
|
391
|
+
if (!db) return [];
|
|
392
|
+
try {
|
|
393
|
+
const r = db.prepare(
|
|
394
|
+
"SELECT model, timestamp FROM ai_code_hashes WHERE conversationId=? AND model IS NOT NULL ORDER BY timestamp DESC LIMIT 1").get(sid) as any;
|
|
395
|
+
if (!r?.model) return [];
|
|
396
|
+
const ts = Number(r.timestamp) || 0;
|
|
397
|
+
return [modelOnlyRow("cursor", sid, ts > 1e12 ? ts : ts * 1000, String(r.model))];
|
|
398
|
+
} finally { db.close(); }
|
|
399
|
+
}
|
|
400
|
+
function listCursorSessions(dbPath: string): ExtSessionRef[] {
|
|
401
|
+
const db = openCursorDb(dbPath);
|
|
402
|
+
if (!db) return [];
|
|
403
|
+
try {
|
|
404
|
+
const rows = db.prepare(
|
|
405
|
+
"SELECT conversationId, MAX(timestamp) ts FROM ai_code_hashes WHERE conversationId IS NOT NULL GROUP BY conversationId").all() as any[];
|
|
406
|
+
return rows.map((r) => {
|
|
407
|
+
const ts = Number(r.ts) || 0;
|
|
408
|
+
return { agent: "cursor", sid: String(r.conversationId), path: `${dbPath}#conversation:${r.conversationId}`, ...(ts > 0 ? { rev: ts > 1e12 ? ts : ts * 1000 } : {}) };
|
|
409
|
+
});
|
|
410
|
+
} finally { db.close(); }
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
export interface ExtUsageSourceEnv {
|
|
414
|
+
/** 测试隔离口:覆盖各源默认根目录(对齐 AITI_ZCODE_HOME 先例)。 */
|
|
415
|
+
claudeHome?: string; // 默认 ~/.claude
|
|
416
|
+
qodercnHome?: string; // 默认 ~/.qoder-cn
|
|
417
|
+
codebuddyHome?: string; // 默认 ~/.codebuddy
|
|
418
|
+
zcodeHome?: string; // 默认 ~/.zcode
|
|
419
|
+
codexHome?: string; // 默认 ~/.codex(A11 P1 model-only)
|
|
420
|
+
opencodeHome?: string; // 默认 ~/.local/share/opencode
|
|
421
|
+
cursorHome?: string; // 默认 ~/.cursor
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
export function builtinExtUsageSources(env: ExtUsageSourceEnv = {}): ExtUsageSource[] {
|
|
425
|
+
const home = homedir();
|
|
426
|
+
const claudeRoot = () => env.claudeHome || join(home, ".claude", "projects");
|
|
427
|
+
const qodercnRoot = () => env.qodercnHome || join(home, ".qoder-cn", "projects");
|
|
428
|
+
const codebuddyRoot = () => env.codebuddyHome || join(home, ".codebuddy", "projects");
|
|
429
|
+
const zcodeDbPath = () => env.zcodeHome ? join(env.zcodeHome, "cli", "db", "db.sqlite") : join(home, ".zcode", "cli", "db", "db.sqlite");
|
|
430
|
+
const codexRoot = () => (env.codexHome || join(home, ".codex")) + "/sessions";
|
|
431
|
+
const opencodeRoot = () => env.opencodeHome || join(home, ".local", "share", "opencode");
|
|
432
|
+
const cursorDbPath = () => env.cursorHome ? join(env.cursorHome, "ai-tracking", "ai-code-tracking.db") : join(home, ".cursor", "ai-tracking", "ai-code-tracking.db");
|
|
433
|
+
|
|
434
|
+
return [
|
|
435
|
+
{
|
|
436
|
+
id: "claude",
|
|
437
|
+
label: "Claude Code",
|
|
438
|
+
probe: () => existsSync(claudeRoot()),
|
|
439
|
+
list: () => listClaudeLikeProjects(claudeRoot(), "claude"),
|
|
440
|
+
parse: (ref) => parseClaudeLikeSession("claude", ref.path, ref.sid),
|
|
441
|
+
},
|
|
442
|
+
{
|
|
443
|
+
id: "qodercn",
|
|
444
|
+
label: "QoderCN",
|
|
445
|
+
probe: () => existsSync(qodercnRoot()),
|
|
446
|
+
list: () => listClaudeLikeProjects(qodercnRoot(), "qodercn"),
|
|
447
|
+
parse: (ref) => parseClaudeLikeSession("qodercn", ref.path, ref.sid),
|
|
448
|
+
},
|
|
449
|
+
{
|
|
450
|
+
id: "codebuddy",
|
|
451
|
+
label: "CodeBuddy Code",
|
|
452
|
+
probe: () => existsSync(codebuddyRoot()),
|
|
453
|
+
list: () => listCodebuddyProjects(codebuddyRoot()),
|
|
454
|
+
parse: (ref) => parseCodebuddySession(ref.path, ref.sid),
|
|
455
|
+
},
|
|
456
|
+
{
|
|
457
|
+
id: "zcode",
|
|
458
|
+
label: "ZCode",
|
|
459
|
+
probe: () => existsSync(zcodeDbPath()),
|
|
460
|
+
list: () => {
|
|
461
|
+
const db = openZcodeDb(zcodeDbPath());
|
|
462
|
+
if (!db) throw new Error(`zcode db unreadable: ${zcodeDbPath()}`);
|
|
463
|
+
try {
|
|
464
|
+
const rows = db.prepare("SELECT id, time_updated FROM session ORDER BY time_updated DESC").all() as
|
|
465
|
+
Array<{ id: string; time_updated?: number | null }>;
|
|
466
|
+
return rows.map((r) => ({
|
|
467
|
+
agent: "zcode",
|
|
468
|
+
sid: r.id,
|
|
469
|
+
path: `${zcodeDbPath()}#session:${r.id}`,
|
|
470
|
+
...(typeof r.time_updated === "number" && r.time_updated > 0 ? { rev: r.time_updated } : {}),
|
|
471
|
+
}));
|
|
472
|
+
} finally {
|
|
473
|
+
db.close();
|
|
474
|
+
}
|
|
475
|
+
},
|
|
476
|
+
parse: (ref) => {
|
|
477
|
+
const [dbPath] = ref.path.split("#");
|
|
478
|
+
return parseZcodeSession(dbPath || zcodeDbPath(), ref.sid);
|
|
479
|
+
},
|
|
480
|
+
},
|
|
481
|
+
// ── P1 model-only 三源(token 恒 0:源不落盘计费数据;会话级 model/provider 归因)──
|
|
482
|
+
{
|
|
483
|
+
id: "codex",
|
|
484
|
+
label: "Codex CLI(model-only)",
|
|
485
|
+
probe: () => existsSync(codexRoot()),
|
|
486
|
+
list: () => listCodexSessions(codexRoot()),
|
|
487
|
+
parse: (ref) => parseCodexModelOnly(ref.path, ref.sid),
|
|
488
|
+
},
|
|
489
|
+
{
|
|
490
|
+
id: "opencode",
|
|
491
|
+
label: "OpenCode(model-only)",
|
|
492
|
+
probe: () => existsSync(opencodeRoot()),
|
|
493
|
+
list: () => listOpencodeSessions(opencodeRoot()),
|
|
494
|
+
parse: (ref) => parseOpencodeModelOnly(opencodeRoot(), ref.path, ref.sid),
|
|
495
|
+
},
|
|
496
|
+
{
|
|
497
|
+
id: "cursor",
|
|
498
|
+
label: "Cursor CLI(model-only)",
|
|
499
|
+
probe: () => existsSync(cursorDbPath()),
|
|
500
|
+
list: () => listCursorSessions(cursorDbPath()),
|
|
501
|
+
parse: (ref) => {
|
|
502
|
+
const [dbPath] = ref.path.split("#");
|
|
503
|
+
return parseCursorModelOnly(dbPath || cursorDbPath(), ref.sid);
|
|
504
|
+
},
|
|
505
|
+
},
|
|
506
|
+
];
|
|
507
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* external-cli-governance —— 外部 CLI provider 的治理模式(共享源,复制到各扩展目录部署)
|
|
3
|
+
*
|
|
4
|
+
* 来源:pi-subagents 0.58 外部 runner 的治理模式抄写(MIT),适配本仓库 provider 槽。
|
|
5
|
+
* 权威源:pi-web-ext/_shared/external-cli-governance.ts(改动后同步到各扩展副本)。
|
|
6
|
+
* 当前副本:aiti-{claude-code,codex,pi,acp,zcode}-agent/external-governance.ts
|
|
7
|
+
*
|
|
8
|
+
* 四件治理:
|
|
9
|
+
* 1. env allowlist(governanceEnv)——spawn 只透传白名单环境变量,父进程的
|
|
10
|
+
* 其他密钥(各家 API key/auth token)不再泄入子 CLI 进程。
|
|
11
|
+
* 2. preflight(preflightCli)——启动前探测二进制存在 + 版本(带 TTL 缓存),
|
|
12
|
+
* fail-loud 提示替代运行时 spawn ENOENT。
|
|
13
|
+
* 3. 能力收窄文案表(CAPABILITY_NOTICE 模式)——不支持的能力带人话理由
|
|
14
|
+
* (我们 provider 槽 capabilities 布尔位之上的文案层,guard 消费后续接)。
|
|
15
|
+
* 4. 读写分型(READONLY_TOOL_ARGS 模式)——只读变体显式声明(-writer 后缀
|
|
16
|
+
* 反向约定:默认只读,writer 才放开写)。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { execFile } from "node:child_process";
|
|
20
|
+
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
// 1) env allowlist
|
|
23
|
+
// ---------------------------------------------------------------------------
|
|
24
|
+
|
|
25
|
+
/** 所有外部 CLI 通用的基础白名单(系统定位 + 代理 + TLS)。 */
|
|
26
|
+
export const BASE_ENV_ALLOW = [
|
|
27
|
+
"PATH", "HOME", "USERPROFILE", "USER", "LOGNAME", "TMPDIR", "TEMP", "TMP",
|
|
28
|
+
"LANG", "LC_ALL", "TERM",
|
|
29
|
+
"HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY",
|
|
30
|
+
"http_proxy", "https_proxy", "no_proxy",
|
|
31
|
+
"SSL_CERT_FILE", "SSL_CERT_DIR",
|
|
32
|
+
] as const;
|
|
33
|
+
|
|
34
|
+
/** 各 CLI 专属键(与 pi-subagents claude-code adapter 对齐 + 本仓库常用 provider)。 */
|
|
35
|
+
export const CLI_ENV_ALLOW: Record<string, string[]> = {
|
|
36
|
+
"claude-code": [
|
|
37
|
+
"CLAUDE_CONFIG_DIR",
|
|
38
|
+
"ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL",
|
|
39
|
+
"CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX",
|
|
40
|
+
"CLAUDE_CODE_USE_FOUNDRY",
|
|
41
|
+
"AWS_PROFILE", "AWS_REGION", "AWS_DEFAULT_REGION",
|
|
42
|
+
"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_BEARER_TOKEN_BEDROCK",
|
|
43
|
+
"GOOGLE_APPLICATION_CREDENTIALS", "CLOUD_ML_REGION", "ANTHROPIC_VERTEX_PROJECT_ID",
|
|
44
|
+
],
|
|
45
|
+
"codex": [
|
|
46
|
+
"OPENAI_API_KEY", "OPENAI_BASE_URL", "CODEX_HOME", "CODEX_API_KEY",
|
|
47
|
+
// 自定义 provider 认证(~/.codex/config.toml 的 model_providers.*.env_key),
|
|
48
|
+
// 如 openrouter 桥接 provider——缺了它轮次直接 turn.failed(Missing environment variable)。
|
|
49
|
+
"OPENROUTER_API_KEY",
|
|
50
|
+
],
|
|
51
|
+
"pi": [
|
|
52
|
+
// pi 自身及其 provider 认证走 agent 目录(models.json/auth.json),
|
|
53
|
+
// 环境变量只留运行时与常见 provider 前缀(防误伤自定义 provider)。
|
|
54
|
+
"PI_CODING_AGENT_DIR", "PI_WEB_PKG_DIR",
|
|
55
|
+
"ANTHROPIC_API_KEY", "OPENAI_API_KEY", "GOOGLE_API_KEY", "GEMINI_API_KEY",
|
|
56
|
+
"ZAI_API_KEY", "DEEPSEEK_API_KEY", "MOONSHOT_API_KEY", "KIMI_API_KEY",
|
|
57
|
+
"QWEN_API_KEY", "DASHSCOPE_API_KEY", "OPENROUTER_API_KEY",
|
|
58
|
+
"SILICONFLOW_API_KEY", "XAI_API_KEY", "GROQ_API_KEY", "MISTRAL_API_KEY",
|
|
59
|
+
],
|
|
60
|
+
"acp": [
|
|
61
|
+
"ACP_*",
|
|
62
|
+
],
|
|
63
|
+
"zcode": [
|
|
64
|
+
// 官方 env 注入通道(调研 docs/zcode-desktop-cli-agent-analysis.md §5.1/§8.6):
|
|
65
|
+
// 模型/端点/key 全走 env,不写 ~/.zcode/cli/config.json;
|
|
66
|
+
// UA/指纹/工具定义全由官方 CLI 本体构造,扩展只做协议层驱动。
|
|
67
|
+
"ZCODE_MODEL", "ZCODE_BASE_URL", "ZCODE_API_KEY", "ZCODE_APP_VERSION", "ZCODE_ENV",
|
|
68
|
+
"ZCODE_STORAGE_DIR", "ZCODE_SESSION_DB_PATH", "ZCODE_HTTP_PROXY", "ZCODE_NO_PROXY",
|
|
69
|
+
],
|
|
70
|
+
"codebuddy": [
|
|
71
|
+
// 官方 env 直读通道(iam.md 优先级 CODEBUDDY_AUTH_TOKEN > apiKeyHelper > CODEBUDDY_API_KEY;
|
|
72
|
+
// 第三方模型 = CODEBUDDY_API_KEY + CODEBUDDY_BASE_URL 指向 OpenAI 兼容端点)。
|
|
73
|
+
"CODEBUDDY_API_KEY", "CODEBUDDY_AUTH_TOKEN", "CODEBUDDY_BASE_URL",
|
|
74
|
+
"CODEBUDDY_IS_SANDBOX", "CODEBUDDY_CONFIG_DIR",
|
|
75
|
+
// aiti 桥直连(shim 自协商端点;服务进程带此 env 时 cbc 会话即有 aiti_* 工具)
|
|
76
|
+
"AITI_BRIDGE_URL",
|
|
77
|
+
],
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 生成治理后的子进程 env:白名单键(精确 + `前缀*` 通配)+ extra 覆盖。
|
|
82
|
+
* 替代 `env: { ...process.env }` 的全量透传。
|
|
83
|
+
*/
|
|
84
|
+
export function governanceEnv(cli: keyof typeof CLI_ENV_ALLOW | string, extra?: Record<string, string>): Record<string, string> {
|
|
85
|
+
const allow = [...BASE_ENV_ALLOW, ...(CLI_ENV_ALLOW[cli as string] ?? [])];
|
|
86
|
+
const out: Record<string, string> = {};
|
|
87
|
+
for (const k of Object.keys(process.env)) {
|
|
88
|
+
const hit = allow.some((a) => (a.endsWith("*") ? k.startsWith(a.slice(0, -1)) : k === a));
|
|
89
|
+
if (hit && process.env[k] !== undefined) out[k] = process.env[k] as string;
|
|
90
|
+
}
|
|
91
|
+
return { ...out, ...(extra ?? {}) };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
// 2) preflight
|
|
96
|
+
// ---------------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
const preflightCache = new Map<string, { at: number; version: string | null; ok: boolean }>();
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 启动前探测:二进制可执行 + 可选版本(`--version`)。TTL 缓存,失败不缓存负面结果以外的信息。
|
|
102
|
+
* 返回 { ok, version, error }——ok=false 时 error 是给人看的失败原因(fail-loud)。
|
|
103
|
+
*/
|
|
104
|
+
export function preflightCli(bin: string, opts: { versionArgs?: string[]; timeoutMs?: number; ttlMs?: number } = {}): Promise<{ ok: boolean; version: string | null; error?: string }> {
|
|
105
|
+
const ttl = opts.ttlMs ?? 60_000;
|
|
106
|
+
const cached = preflightCache.get(bin);
|
|
107
|
+
if (cached && Date.now() - cached.at < ttl) {
|
|
108
|
+
return Promise.resolve(cached.ok
|
|
109
|
+
? { ok: true, version: cached.version }
|
|
110
|
+
: { ok: false, version: null, error: cached.version ?? `${bin} 探测失败` });
|
|
111
|
+
}
|
|
112
|
+
return new Promise((resolve) => {
|
|
113
|
+
execFile(bin, opts.versionArgs ?? ["--version"], { timeout: opts.timeoutMs ?? 5_000 }, (err, stdout) => {
|
|
114
|
+
if (err) {
|
|
115
|
+
const msg = String((err as NodeJS.ErrnoException).code) === "ENOENT"
|
|
116
|
+
? `${bin} 未安装或不在 PATH`
|
|
117
|
+
: `${bin} 探测失败: ${err.message.split("\n")[0]}`;
|
|
118
|
+
preflightCache.set(bin, { at: Date.now(), version: msg, ok: false });
|
|
119
|
+
resolve({ ok: false, version: null, error: msg });
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const version = String(stdout).trim().split("\n")[0]?.slice(0, 64) ?? null;
|
|
123
|
+
preflightCache.set(bin, { at: Date.now(), version, ok: true });
|
|
124
|
+
resolve({ ok: true, version });
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ---------------------------------------------------------------------------
|
|
130
|
+
// 3) 能力收窄文案表(模式示例——provider 按需声明,guard 消费后续接)
|
|
131
|
+
// ---------------------------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
/** 不支持能力的人话理由(替代裸 false;provider 的 capabilities 旁路声明)。 */
|
|
134
|
+
export interface CapabilityNotices {
|
|
135
|
+
[capability: string]: string;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** one-shot stdin 型外部 CLI 的通用收窄理由(pi-subagents external-cli-contract 对齐)。 */
|
|
139
|
+
export const ONESHOT_CLI_NOTICES: CapabilityNotices = {
|
|
140
|
+
steer: "one-shot stdin 模式在启动后关闭输入,无法接受运行中导向消息。",
|
|
141
|
+
fork: "外部 CLI 会话无原生 fork 语义(无 pi session 树)。",
|
|
142
|
+
compact: "外部 CLI 不暴露上下文压缩接口。",
|
|
143
|
+
setActiveTools: "外部 CLI 的工具白名单只能启动时声明,不能运行中切换。",
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
// ---------------------------------------------------------------------------
|
|
147
|
+
// 4) 读写分型
|
|
148
|
+
// ---------------------------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
/** 只读变体的 CLI 参数(writer 变体反向约定:默认只读,writer 才放开写)。 */
|
|
151
|
+
export const READONLY_TOOL_ARGS: Record<string, string[]> = {
|
|
152
|
+
"claude-code": ["--allowedTools", "Read,Glob,Grep"],
|
|
153
|
+
};
|