@ktkid/kmh-codex-cli 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +296 -2
- package/bin/README.md +25 -0
- package/bin/codex +36 -0
- package/bin/runtime-receipt.json +9 -0
- package/bin/version +1 -0
- package/cordis.patch.yml +7 -0
- package/lib/browser-types/src/account-status.d.ts +9 -0
- package/lib/browser-types/src/client/ComposerQuota.d.ts +10 -0
- package/lib/browser-types/src/client/DetailCard.d.ts +12 -0
- package/lib/browser-types/src/client/LiveBall.d.ts +19 -0
- package/lib/browser-types/src/client/QuotaCard.d.ts +20 -0
- package/lib/browser-types/src/client/QuotaDisplaySettings.d.ts +6 -0
- package/lib/browser-types/src/client/index.d.ts +18 -0
- package/lib/browser-types/src/client/locales.d.ts +54 -0
- package/lib/browser-types/src/client/quota-store.d.ts +56 -0
- package/lib/browser-types/src/live-state.d.ts +31 -0
- package/lib/browser-types/src/quota-protocol.d.ts +135 -0
- package/lib/browser-types/src/quota-rules.d.ts +18 -0
- package/lib/browser-types/src/tool-switches.d.ts +63 -0
- package/lib/client.js +16193 -0
- package/lib/src/account-status.d.ts +9 -0
- package/lib/src/account-status.js +1 -0
- package/lib/src/account.d.ts +35 -0
- package/lib/src/account.js +173 -0
- package/lib/src/adapter.d.ts +22 -0
- package/lib/src/adapter.js +222 -0
- package/lib/src/approval.d.ts +48 -0
- package/lib/src/approval.js +235 -0
- package/lib/src/capabilities.d.ts +40 -0
- package/lib/src/capabilities.js +85 -0
- package/lib/src/config.d.ts +69 -0
- package/lib/src/config.js +75 -0
- package/lib/src/connection.d.ts +65 -0
- package/lib/src/connection.js +178 -0
- package/lib/src/cursor.d.ts +61 -0
- package/lib/src/cursor.js +339 -0
- package/lib/src/image-delivery.d.ts +36 -0
- package/lib/src/image-delivery.js +65 -0
- package/lib/src/imagegen.d.ts +21 -0
- package/lib/src/imagegen.js +132 -0
- package/lib/src/index.d.ts +146 -0
- package/lib/src/index.js +551 -0
- package/lib/src/isolation.d.ts +61 -0
- package/lib/src/isolation.js +298 -0
- package/lib/src/live-state.d.ts +31 -0
- package/lib/src/live-state.js +14 -0
- package/lib/src/models.d.ts +24 -0
- package/lib/src/models.js +98 -0
- package/lib/src/native-items.d.ts +59 -0
- package/lib/src/native-items.js +122 -0
- package/lib/src/native-tools/catalog.d.ts +29 -0
- package/lib/src/native-tools/catalog.js +197 -0
- package/lib/src/probe.d.ts +17 -0
- package/lib/src/probe.js +54 -0
- package/lib/src/protocol.d.ts +508 -0
- package/lib/src/protocol.js +511 -0
- package/lib/src/quota-protocol.d.ts +135 -0
- package/lib/src/quota-protocol.js +97 -0
- package/lib/src/quota-rules.d.ts +18 -0
- package/lib/src/quota-rules.js +49 -0
- package/lib/src/quota.d.ts +32 -0
- package/lib/src/quota.js +227 -0
- package/lib/src/session-history.d.ts +18 -0
- package/lib/src/session-history.js +113 -0
- package/lib/src/session-store.d.ts +592 -0
- package/lib/src/session-store.js +275 -0
- package/lib/src/status.d.ts +19 -0
- package/lib/src/status.js +69 -0
- package/lib/src/tool-policy.d.ts +47 -0
- package/lib/src/tool-policy.js +454 -0
- package/lib/src/tool-registry.d.ts +42 -0
- package/lib/src/tool-registry.js +70 -0
- package/lib/src/tool-selection.d.ts +88 -0
- package/lib/src/tool-selection.js +60 -0
- package/lib/src/tool-switches-service.d.ts +24 -0
- package/lib/src/tool-switches-service.js +129 -0
- package/lib/src/tool-switches.d.ts +63 -0
- package/lib/src/tool-switches.js +43 -0
- package/lib/src/turn.d.ts +200 -0
- package/lib/src/turn.js +1012 -0
- package/lib/src/web.d.ts +9 -0
- package/lib/src/web.js +143 -0
- package/package.json +172 -4
- package/vendor/codex/LICENSE +201 -0
- package/vendor/codex/NOTICE +4 -0
- package/vendor/codex/models.json +1613 -0
- package/vendor/native-tools/0.162.0-alpha.17.2.json +143 -0
- package/vendor/native-tools/0.163.0-alpha.10.2.json +128 -0
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
import { CliTargetId, ToolSourceId, choiceEnabled, } from "./tool-selection.js";
|
|
2
|
+
import { deepFreeze } from "@deepseek-ai/dsh-util-values";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { discoverNativeTools, } from "./native-tools/catalog.js";
|
|
8
|
+
import { connectCodex } from "./connection.js";
|
|
9
|
+
import { prepareIsolation, verifyIsolation } from "./isolation.js";
|
|
10
|
+
import { SavedToolPolicySchema } from "./session-store.js";
|
|
11
|
+
import { KMH_TOOL_PREFIX } from "./tool-registry.js";
|
|
12
|
+
const legacySchema = z.object({
|
|
13
|
+
selection: z.object({
|
|
14
|
+
commandExecution: z.boolean(),
|
|
15
|
+
fileChange: z.boolean(),
|
|
16
|
+
viewImage: z.boolean(),
|
|
17
|
+
webSearch: z.boolean(),
|
|
18
|
+
skills: z.boolean(),
|
|
19
|
+
}),
|
|
20
|
+
});
|
|
21
|
+
/** 保存一次实际路由的工具状态,并把根调用身份固定到该状态。 */
|
|
22
|
+
export class CodexToolPolicy {
|
|
23
|
+
ctx;
|
|
24
|
+
runtime;
|
|
25
|
+
lifetime = new AbortController();
|
|
26
|
+
turns = new WeakMap();
|
|
27
|
+
sessions = new Map();
|
|
28
|
+
roots = new Map();
|
|
29
|
+
work = new Set();
|
|
30
|
+
migration;
|
|
31
|
+
nativeCache;
|
|
32
|
+
targetId;
|
|
33
|
+
constructor(ctx, runtime) {
|
|
34
|
+
this.ctx = ctx;
|
|
35
|
+
this.runtime = runtime;
|
|
36
|
+
const entry = ctx.fiber.entry;
|
|
37
|
+
if (entry === undefined)
|
|
38
|
+
throw new Error("CODEX_TOOL_POLICY_REQUIRES_PROFILE_ENTRY");
|
|
39
|
+
this.targetId = CliTargetId(entry.options.id);
|
|
40
|
+
ctx.on("settings/document-updated", (ns) => {
|
|
41
|
+
if (ns === entry.options.id)
|
|
42
|
+
this.nativeCache = undefined;
|
|
43
|
+
});
|
|
44
|
+
ctx.on("agent/created", async ({ agent, source, signal }) => {
|
|
45
|
+
const pending = this.capture(agent, source, signal ?? this.lifetime.signal);
|
|
46
|
+
this.work.add(pending);
|
|
47
|
+
try {
|
|
48
|
+
await pending;
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
this.work.delete(pending);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
// 在请求配置冻结阶段准备本回合策略:此时用户消息尚未提交,准备失败
|
|
55
|
+
// 不会把未投递的输入留在历史里,修正运行条件后可重试原会话。
|
|
56
|
+
ctx.on("agent/request", async ({ agent, turn, signal }, next) => {
|
|
57
|
+
const config = await next();
|
|
58
|
+
if (config.provider !== "codex-cli") {
|
|
59
|
+
this.sessions.delete(agent.session.id);
|
|
60
|
+
return config;
|
|
61
|
+
}
|
|
62
|
+
let prepared = this.turns.get(agent);
|
|
63
|
+
if (prepared?.turn !== turn) {
|
|
64
|
+
const pending = this.untilPrepared(agent.session.id, turn, config.model, signal);
|
|
65
|
+
this.work.add(pending);
|
|
66
|
+
try {
|
|
67
|
+
prepared = await pending;
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
this.work.delete(pending);
|
|
71
|
+
}
|
|
72
|
+
this.turns.set(agent, prepared);
|
|
73
|
+
}
|
|
74
|
+
this.sessions.set(agent.session.id, prepared);
|
|
75
|
+
return config;
|
|
76
|
+
});
|
|
77
|
+
ctx.on("session/event", (session, event) => {
|
|
78
|
+
if (event.type === "tool/call") {
|
|
79
|
+
const prepared = this.sessions.get(session.id);
|
|
80
|
+
if (prepared !== undefined)
|
|
81
|
+
this.roots.set(JSON.stringify([session.id, event.data.callId]), prepared);
|
|
82
|
+
}
|
|
83
|
+
else if (event.type === "turn/end") {
|
|
84
|
+
this.sessions.delete(session.id);
|
|
85
|
+
for (const key of this.roots.keys())
|
|
86
|
+
if (key.startsWith(JSON.stringify([session.id]).slice(0, -1) + ","))
|
|
87
|
+
this.roots.delete(key);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
ctx.tools.guard((exec) => {
|
|
91
|
+
const session = exec.agent?.session;
|
|
92
|
+
if (session === undefined || exec.name === "run_code")
|
|
93
|
+
return undefined;
|
|
94
|
+
const policy = this.roots.get(JSON.stringify([session.id, exec.rootCallId])) ??
|
|
95
|
+
this.sessions.get(session.id);
|
|
96
|
+
if (policy === undefined)
|
|
97
|
+
return undefined;
|
|
98
|
+
const row = policy.catalog.tools.find((tool) => tool.side === "harness" && tool.registryName === exec.name);
|
|
99
|
+
const current = ctx.tools.get(exec.name, exec.agent);
|
|
100
|
+
const saved = policy.inventory.find((item) => item.schema.name === exec.name);
|
|
101
|
+
if (row !== undefined &&
|
|
102
|
+
saved !== undefined &&
|
|
103
|
+
current !== undefined &&
|
|
104
|
+
fingerprint(current.parameters) ===
|
|
105
|
+
fingerprint(saved.schema.parameters) &&
|
|
106
|
+
choiceEnabled(policy.choices, row))
|
|
107
|
+
return undefined;
|
|
108
|
+
const source = row?.source ?? ToolSourceId("harness/unregistered");
|
|
109
|
+
return `TOOL_DISABLED: ${source}/${row?.name ?? exec.name}`;
|
|
110
|
+
});
|
|
111
|
+
ctx.effect(() => async () => {
|
|
112
|
+
this.lifetime.abort();
|
|
113
|
+
await Promise.allSettled([...this.work]);
|
|
114
|
+
this.sessions.clear();
|
|
115
|
+
this.roots.clear();
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
async capture(agent, source, signal) {
|
|
119
|
+
signal.throwIfAborted();
|
|
120
|
+
const record = await this.runtime.bindingRecord(agent.session.id);
|
|
121
|
+
if (record?.toolPolicy !== undefined) {
|
|
122
|
+
if (record.toolPolicy.target !== this.targetId)
|
|
123
|
+
throw new Error("CODEX_SESSION_STATE_INCOMPATIBLE: CLI profile entry changed");
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const parentId = agent.session.header.parentSession;
|
|
127
|
+
if (parentId !== undefined) {
|
|
128
|
+
const parent = await this.runtime.bindingRecord(parentId);
|
|
129
|
+
if (parent?.toolPolicy === undefined)
|
|
130
|
+
throw new Error("CODEX_SESSION_STATE_INCOMPLETE: source tools are unavailable");
|
|
131
|
+
await this.runtime.saveToolPolicy(agent.session.id, parent.toolPolicy);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (record?.threadId !== undefined || source !== "startup") {
|
|
135
|
+
if (record !== undefined || agent.options.provider === "codex-cli")
|
|
136
|
+
throw new Error("CODEX_SESSION_STATE_INCOMPLETE: original tools are unavailable");
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
await this.initialize(this.harnessRows(agent));
|
|
140
|
+
const current = this.runtime.config.toolSelection.get();
|
|
141
|
+
if (current === undefined)
|
|
142
|
+
throw new Error("CODEX_TOOL_SELECTION_UNINITIALIZED");
|
|
143
|
+
const enabled = (name) => current.native.some((row) => row.source === "codex/native" && row.name === name && row.enabled);
|
|
144
|
+
// web_search 行由首次导入或详情页切换写入;旧配置尚无该行时沿用旧设置。
|
|
145
|
+
const webSearchRow = current.native.find((row) => row.source === "codex/native" && row.name === "web_search");
|
|
146
|
+
const snapshot = SavedToolPolicySchema.parse({
|
|
147
|
+
version: 1,
|
|
148
|
+
target: this.targetId,
|
|
149
|
+
choices: current,
|
|
150
|
+
inventory: this.snapshotInventory(agent),
|
|
151
|
+
nativeExecution: {
|
|
152
|
+
commandExecution: enabled("exec_command"),
|
|
153
|
+
fileChange: enabled("apply_patch"),
|
|
154
|
+
viewImage: enabled("view_image"),
|
|
155
|
+
webSearch: webSearchRow === undefined
|
|
156
|
+
? this.runtime.settings.selection.webSearch
|
|
157
|
+
: webSearchRow.enabled,
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
signal.throwIfAborted();
|
|
161
|
+
await this.runtime.saveToolPolicy(agent.session.id, snapshot);
|
|
162
|
+
}
|
|
163
|
+
/** 返回配置目录;独立保留 Harness 列及原生侧诊断。 */
|
|
164
|
+
async catalog(signal, refresh = false) {
|
|
165
|
+
const native = await this.nativeCatalog(signal, this.runtime.config.cwd, refresh).catch((error) => ({
|
|
166
|
+
version: "unknown",
|
|
167
|
+
rows: [],
|
|
168
|
+
overrides: [],
|
|
169
|
+
diagnostic: error instanceof Error ? error.message : String(error),
|
|
170
|
+
}));
|
|
171
|
+
const harness = this.harnessRows();
|
|
172
|
+
const rows = [...harness, ...native.rows];
|
|
173
|
+
const diagnostics = {};
|
|
174
|
+
if (native.diagnostic !== undefined)
|
|
175
|
+
diagnostics.native = native.diagnostic;
|
|
176
|
+
try {
|
|
177
|
+
await this.initialize(rows);
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
diagnostics.harness =
|
|
181
|
+
error instanceof Error ? error.message : String(error);
|
|
182
|
+
}
|
|
183
|
+
const saved = this.runtime.config.toolSelection.get();
|
|
184
|
+
// 已保存但当前任何视图都不可见的行(如插件已禁用)仍列出,选择保留。
|
|
185
|
+
if (saved !== undefined)
|
|
186
|
+
for (const item of saved.harness)
|
|
187
|
+
if (!rows.some((row) => row.side === "harness" && row.name === item.name))
|
|
188
|
+
rows.push({
|
|
189
|
+
side: "harness",
|
|
190
|
+
source: ToolSourceId(item.source),
|
|
191
|
+
name: item.name,
|
|
192
|
+
registryName: item.name.startsWith(KMH_TOOL_PREFIX)
|
|
193
|
+
? item.name.slice(KMH_TOOL_PREFIX.length)
|
|
194
|
+
: item.name,
|
|
195
|
+
description: "",
|
|
196
|
+
control: { kind: "adjustable" },
|
|
197
|
+
});
|
|
198
|
+
if (native.diagnostic !== undefined && saved !== undefined) {
|
|
199
|
+
for (const item of saved.native) {
|
|
200
|
+
if (rows.some((row) => row.side === "native" &&
|
|
201
|
+
row.source === item.source &&
|
|
202
|
+
row.name === item.name))
|
|
203
|
+
continue;
|
|
204
|
+
rows.push({
|
|
205
|
+
side: "native",
|
|
206
|
+
source: ToolSourceId(item.source),
|
|
207
|
+
name: item.name,
|
|
208
|
+
description: "",
|
|
209
|
+
control: { kind: "unverified", reason: native.diagnostic },
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
revision: fingerprint(rows),
|
|
215
|
+
tools: rows,
|
|
216
|
+
...(Object.keys(diagnostics).length === 0 ? {} : { diagnostics }),
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* 公开注册表只投影模型侧 schema,不含插件来源,Harness 行统一记为 harness。
|
|
221
|
+
* 预设内的工具只在 agent 视图可见:无 agent 时合并全局视图与所有活动 agent 的视图。
|
|
222
|
+
*/
|
|
223
|
+
harnessRows(agent) {
|
|
224
|
+
const scopes = agent === undefined
|
|
225
|
+
? [undefined, ...(this.ctx.get("agents")?.list() ?? [])]
|
|
226
|
+
: [agent];
|
|
227
|
+
const rows = new Map();
|
|
228
|
+
for (const scope of scopes)
|
|
229
|
+
for (const schema of this.ctx.tools.schemas(scope))
|
|
230
|
+
if (!rows.has(schema.name))
|
|
231
|
+
rows.set(schema.name, {
|
|
232
|
+
side: "harness",
|
|
233
|
+
source: ToolSourceId("harness"),
|
|
234
|
+
name: KMH_TOOL_PREFIX + schema.name,
|
|
235
|
+
registryName: schema.name,
|
|
236
|
+
description: schema.description,
|
|
237
|
+
schema,
|
|
238
|
+
control: { kind: "adjustable" },
|
|
239
|
+
});
|
|
240
|
+
return [...rows.values()];
|
|
241
|
+
}
|
|
242
|
+
/** 创建时该 Agent 可见的 Harness 工具快照。 */
|
|
243
|
+
snapshotInventory(agent) {
|
|
244
|
+
return this.ctx.tools
|
|
245
|
+
.schemas(agent)
|
|
246
|
+
.map((schema) => ({ source: ToolSourceId("harness"), schema }));
|
|
247
|
+
}
|
|
248
|
+
nativeCatalog(signal, cwd, refresh, selection = this.runtime.settings.selection) {
|
|
249
|
+
const key = JSON.stringify([
|
|
250
|
+
cwd,
|
|
251
|
+
this.runtime.config.command,
|
|
252
|
+
this.runtime.config.model,
|
|
253
|
+
selection,
|
|
254
|
+
]);
|
|
255
|
+
if (refresh || this.nativeCache?.key !== key) {
|
|
256
|
+
const bounded = AbortSignal.any([
|
|
257
|
+
this.lifetime.signal,
|
|
258
|
+
AbortSignal.timeout(this.runtime.config.probeTimeoutMs),
|
|
259
|
+
]);
|
|
260
|
+
const value = discoverNativeTools(this.ctx, this.runtime.config, selection, bounded, cwd);
|
|
261
|
+
this.nativeCache = { key, value };
|
|
262
|
+
this.work.add(value);
|
|
263
|
+
void value.then(() => this.work.delete(value), () => {
|
|
264
|
+
this.work.delete(value);
|
|
265
|
+
this.nativeCache = undefined;
|
|
266
|
+
return Promise.resolve();
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
const cached = this.nativeCache.value;
|
|
270
|
+
return cancelled(cached, AbortSignal.any([signal, this.lifetime.signal]));
|
|
271
|
+
}
|
|
272
|
+
async initialize(rows) {
|
|
273
|
+
if (this.runtime.config.toolSelection.get() !== undefined)
|
|
274
|
+
return;
|
|
275
|
+
if (this.migration !== undefined)
|
|
276
|
+
return this.migration;
|
|
277
|
+
this.migration = this.importChoices(rows).finally(() => {
|
|
278
|
+
this.migration = undefined;
|
|
279
|
+
});
|
|
280
|
+
await this.migration;
|
|
281
|
+
}
|
|
282
|
+
async importChoices(rows) {
|
|
283
|
+
let legacy = this.runtime.settings.selection;
|
|
284
|
+
try {
|
|
285
|
+
legacy = legacySchema.parse(JSON.parse(await readFile(join(this.runtime.config.dataDir, "codex-settings.json"), "utf8"))).selection;
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
if (!(error instanceof Error &&
|
|
289
|
+
"code" in error &&
|
|
290
|
+
error.code === "ENOENT"))
|
|
291
|
+
throw new Error(`CODEX_TOOL_MIGRATION_FAILED: ${error instanceof Error ? error.message : String(error)}`);
|
|
292
|
+
}
|
|
293
|
+
const choices = { version: 1, harness: [], native: [] };
|
|
294
|
+
for (const row of rows) {
|
|
295
|
+
if (row.control.kind === "fixed" || row.control.kind === "unverified")
|
|
296
|
+
continue;
|
|
297
|
+
const enabled = row.side === "harness" || nativeChoice(legacy, row.name);
|
|
298
|
+
choices[row.side].push({ source: row.source, name: row.name, enabled });
|
|
299
|
+
}
|
|
300
|
+
// 已有粗粒度控制的精确 handler 身份;发现失败时保存这些选择并展示待核实。
|
|
301
|
+
for (const name of [
|
|
302
|
+
"exec_command",
|
|
303
|
+
"write_stdin",
|
|
304
|
+
"shell_command",
|
|
305
|
+
"apply_patch",
|
|
306
|
+
"view_image",
|
|
307
|
+
]) {
|
|
308
|
+
if (choices.native.some((row) => row.source === "codex/native" && row.name === name))
|
|
309
|
+
continue;
|
|
310
|
+
choices.native.push({
|
|
311
|
+
source: "codex/native",
|
|
312
|
+
name,
|
|
313
|
+
enabled: nativeChoice(legacy, name),
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
const settings = this.ctx.get("settings");
|
|
317
|
+
if (settings === undefined)
|
|
318
|
+
throw new Error("CODEX_TOOL_MIGRATION_NEEDS_PROFILE_SETTINGS");
|
|
319
|
+
const descriptor = settings
|
|
320
|
+
.describe()
|
|
321
|
+
.find((row) => String(row.ns) === String(this.targetId));
|
|
322
|
+
if (descriptor === undefined)
|
|
323
|
+
throw new Error("CODEX_TOOL_MIGRATION_NEEDS_WRITABLE_PROFILE");
|
|
324
|
+
if (this.runtime.config.toolSelection.get() !== undefined)
|
|
325
|
+
return;
|
|
326
|
+
await settings.update(this.targetId, { toolSelection: choices }, descriptor.revision);
|
|
327
|
+
}
|
|
328
|
+
async untilPrepared(sessionId, turn, model, signal) {
|
|
329
|
+
const combined = AbortSignal.any([signal, this.lifetime.signal]);
|
|
330
|
+
combined.throwIfAborted();
|
|
331
|
+
let snapshot = (await this.runtime.bindingRecord(sessionId))?.toolPolicy;
|
|
332
|
+
if (snapshot === undefined)
|
|
333
|
+
throw new Error("CODEX_SESSION_STATE_INCOMPLETE: original tools are unavailable");
|
|
334
|
+
if (snapshot.target !== this.targetId)
|
|
335
|
+
throw new Error("CODEX_SESSION_STATE_INCOMPATIBLE: CLI profile entry changed");
|
|
336
|
+
const selected = {
|
|
337
|
+
...snapshot.nativeExecution,
|
|
338
|
+
skills: this.runtime.settings.selection.skills,
|
|
339
|
+
};
|
|
340
|
+
if (snapshot.nativeCatalog === undefined) {
|
|
341
|
+
const native = await this.nativeCatalog(combined, this.runtime.resolveCwd(sessionId), true, selected);
|
|
342
|
+
if (native.diagnostic !== undefined)
|
|
343
|
+
throw new Error(native.diagnostic);
|
|
344
|
+
snapshot = SavedToolPolicySchema.parse({
|
|
345
|
+
...snapshot,
|
|
346
|
+
nativeCatalog: { version: native.version, rows: [...native.rows] },
|
|
347
|
+
});
|
|
348
|
+
await this.runtime.saveToolPolicy(sessionId, snapshot);
|
|
349
|
+
}
|
|
350
|
+
const saved = snapshot;
|
|
351
|
+
const rows = [
|
|
352
|
+
...saved.inventory.map((item) => ({
|
|
353
|
+
side: "harness",
|
|
354
|
+
source: ToolSourceId(item.source),
|
|
355
|
+
...(item.sourceLabel === undefined
|
|
356
|
+
? {}
|
|
357
|
+
: { sourceLabel: item.sourceLabel }),
|
|
358
|
+
name: KMH_TOOL_PREFIX + item.schema.name,
|
|
359
|
+
registryName: item.schema.name,
|
|
360
|
+
description: item.schema.description,
|
|
361
|
+
schema: item.schema,
|
|
362
|
+
control: { kind: "adjustable" },
|
|
363
|
+
})),
|
|
364
|
+
...(saved.nativeCatalog?.rows ?? []),
|
|
365
|
+
];
|
|
366
|
+
const catalog = { revision: fingerprint(rows), tools: rows };
|
|
367
|
+
await this.preflight(selected, this.runtime.resolveCwd(sessionId), model, combined);
|
|
368
|
+
const names = rows
|
|
369
|
+
.filter((row) => row.side === "harness" && choiceEnabled(saved.choices, row))
|
|
370
|
+
.flatMap((row) => row.registryName === undefined ? [] : [row.registryName]);
|
|
371
|
+
return {
|
|
372
|
+
turn,
|
|
373
|
+
choices: deepFreeze(saved.choices),
|
|
374
|
+
catalog: deepFreeze(catalog),
|
|
375
|
+
native: deepFreeze(selected),
|
|
376
|
+
version: saved.nativeCatalog?.version ?? "unknown",
|
|
377
|
+
fingerprint: fingerprint([saved.choices, rows, saved.nativeExecution]),
|
|
378
|
+
names,
|
|
379
|
+
inventory: saved.inventory,
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
async preflight(selection, cwd, model, signal) {
|
|
383
|
+
const bounded = AbortSignal.any([
|
|
384
|
+
signal,
|
|
385
|
+
AbortSignal.timeout(this.runtime.config.probeTimeoutMs),
|
|
386
|
+
]);
|
|
387
|
+
const plan = await prepareIsolation(this.ctx, this.runtime.config, {
|
|
388
|
+
selection,
|
|
389
|
+
cwd,
|
|
390
|
+
signal: bounded,
|
|
391
|
+
});
|
|
392
|
+
const connection = await connectCodex(this.ctx, {
|
|
393
|
+
command: this.runtime.config.command,
|
|
394
|
+
cwd,
|
|
395
|
+
configOverrides: plan.configOverrides,
|
|
396
|
+
env: this.runtime.config.env,
|
|
397
|
+
graceMs: this.runtime.config.graceMs,
|
|
398
|
+
startupTimeoutMs: this.runtime.config.startupTimeoutMs,
|
|
399
|
+
}, bounded);
|
|
400
|
+
try {
|
|
401
|
+
await verifyIsolation(connection, plan, bounded);
|
|
402
|
+
const catalog = z
|
|
403
|
+
.object({
|
|
404
|
+
models: z.array(z.object({ slug: z.string() }).passthrough()),
|
|
405
|
+
})
|
|
406
|
+
.parse(JSON.parse(await readFile(plan.catalogPath, "utf8")));
|
|
407
|
+
if (!catalog.models.some((entry) => entry.slug === model))
|
|
408
|
+
throw new Error(`CODEX_NATIVE_MODEL_UNVERIFIED: ${model}`);
|
|
409
|
+
}
|
|
410
|
+
finally {
|
|
411
|
+
await connection.stop(this.runtime.config.cleanupTimeoutMs);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
/** 已准备回合的冻结策略;辅助请求与未准备的会话返回 undefined,保留既有路径。 */
|
|
415
|
+
forStream(options) {
|
|
416
|
+
return options.sessionId === undefined
|
|
417
|
+
? undefined
|
|
418
|
+
: this.sessions.get(options.sessionId);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
/** 精确工具名对应既有 Codex 控制字段。 */
|
|
422
|
+
function nativeChoice(selection, name) {
|
|
423
|
+
switch (name) {
|
|
424
|
+
case "exec_command":
|
|
425
|
+
case "write_stdin":
|
|
426
|
+
case "shell_command":
|
|
427
|
+
return selection.commandExecution;
|
|
428
|
+
case "apply_patch":
|
|
429
|
+
return selection.fileChange;
|
|
430
|
+
case "view_image":
|
|
431
|
+
return selection.viewImage;
|
|
432
|
+
default:
|
|
433
|
+
return selection.webSearch;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
/** 完整参数与目录身份参与线程复用。 */
|
|
437
|
+
function fingerprint(value) {
|
|
438
|
+
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
439
|
+
}
|
|
440
|
+
/** 每个调用者单独取消等待,共享发现由插件生命周期管理。 */
|
|
441
|
+
async function cancelled(work, signal) {
|
|
442
|
+
signal.throwIfAborted();
|
|
443
|
+
const abort = Promise.withResolvers();
|
|
444
|
+
const listener = () => {
|
|
445
|
+
abort.reject(signal.reason);
|
|
446
|
+
};
|
|
447
|
+
signal.addEventListener("abort", listener, { once: true });
|
|
448
|
+
try {
|
|
449
|
+
return await Promise.race([work, abort.promise]);
|
|
450
|
+
}
|
|
451
|
+
finally {
|
|
452
|
+
signal.removeEventListener("abort", listener);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** 声明名前缀:模型侧可见的 KMH 工具统一挂载前缀,防与原生/其他来源同名冲突。 */
|
|
2
|
+
export declare const KMH_TOOL_PREFIX = "kmh-";
|
|
3
|
+
/** 声明表输入条目(与 TurnStartInput.tools 一致)。 */
|
|
4
|
+
export interface ToolEntry {
|
|
5
|
+
name: string;
|
|
6
|
+
description: string;
|
|
7
|
+
inputSchema: unknown;
|
|
8
|
+
}
|
|
9
|
+
/** 一份工具目录的声明映射与指纹。 */
|
|
10
|
+
export interface ToolRegistry {
|
|
11
|
+
/** 声明名 → KMH 注册名。 */
|
|
12
|
+
readonly declaredToKmh: ReadonlyMap<string, string>;
|
|
13
|
+
/** KMH 注册名 → 声明名。 */
|
|
14
|
+
readonly kmhToDeclared: ReadonlyMap<string, string>;
|
|
15
|
+
/** 目录指纹:声明名、描述和参数序列化的摘要,任何目录/展示变化都会改变。 */
|
|
16
|
+
readonly fingerprint: string;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* 计算工具目录指纹(声明名、描述和参数,按名称排序后摘要)。
|
|
20
|
+
* @param tools - KMH 工具表。
|
|
21
|
+
* @returns 十六进制摘要;空目录也有稳定指纹。
|
|
22
|
+
*/
|
|
23
|
+
export declare function toolFingerprintOf(tools: readonly ToolEntry[], policyFingerprint?: string): string;
|
|
24
|
+
/**
|
|
25
|
+
* 从 KMH 工具表构建声明表:统一加 kmh- 前缀并做范围与碰撞校验。
|
|
26
|
+
* @param tools - KMH 工具表。
|
|
27
|
+
* @returns 声明映射与指纹。
|
|
28
|
+
* @throws CODEX_TOOL_NAME_INVALID 前缀后名称超出官方接受范围。
|
|
29
|
+
* @throws CODEX_TOOL_NAME_COLLISION 声明名相互重复。
|
|
30
|
+
*/
|
|
31
|
+
export declare function buildToolRegistry(tools: readonly ToolEntry[], policyFingerprint?: string): ToolRegistry;
|
|
32
|
+
/**
|
|
33
|
+
* 解析回调中的工具名为 KMH 注册名。
|
|
34
|
+
* 先按声明表精确命中;未命中时兼容裸名(旧 thread 以裸名声明工具);
|
|
35
|
+
* 兼容范围以本回合的 KMH 工具表为准,防旧名误映射到已不存在的工具。
|
|
36
|
+
* @param registry - 本回合声明表;临时会话(无工具)传 undefined。
|
|
37
|
+
* @param name - 服务端回调携带的工具名。
|
|
38
|
+
* @returns 对应的 KMH 注册名;未知名称返回 undefined。
|
|
39
|
+
*/
|
|
40
|
+
export declare function resolveKmhToolName(registry: ToolRegistry | undefined, name: string): string | undefined;
|
|
41
|
+
/** 提示中的声明约定说明:加在 developerInstructions,避免改写正文词义。 */
|
|
42
|
+
export declare function toolDeclarationNote(): string;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/** KMH 工具声明名映射(D13):kmh- 前缀双向表、名称校验与目录指纹。 */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
/** 声明名前缀:模型侧可见的 KMH 工具统一挂载前缀,防与原生/其他来源同名冲突。 */
|
|
4
|
+
export const KMH_TOOL_PREFIX = "kmh-";
|
|
5
|
+
/** 官方动态工具名实测接受范围(平铺真名形态,0.160.0 基线)。 */
|
|
6
|
+
const DECLARED_NAME = /^[A-Za-z0-9_-]+$/;
|
|
7
|
+
/**
|
|
8
|
+
* 计算工具目录指纹(声明名、描述和参数,按名称排序后摘要)。
|
|
9
|
+
* @param tools - KMH 工具表。
|
|
10
|
+
* @returns 十六进制摘要;空目录也有稳定指纹。
|
|
11
|
+
*/
|
|
12
|
+
export function toolFingerprintOf(tools, policyFingerprint) {
|
|
13
|
+
const declared = tools
|
|
14
|
+
.map((tool) => [
|
|
15
|
+
KMH_TOOL_PREFIX + tool.name,
|
|
16
|
+
tool.description,
|
|
17
|
+
tool.inputSchema,
|
|
18
|
+
])
|
|
19
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
20
|
+
return createHash("sha256")
|
|
21
|
+
.update(JSON.stringify([declared, policyFingerprint]))
|
|
22
|
+
.digest("hex");
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* 从 KMH 工具表构建声明表:统一加 kmh- 前缀并做范围与碰撞校验。
|
|
26
|
+
* @param tools - KMH 工具表。
|
|
27
|
+
* @returns 声明映射与指纹。
|
|
28
|
+
* @throws CODEX_TOOL_NAME_INVALID 前缀后名称超出官方接受范围。
|
|
29
|
+
* @throws CODEX_TOOL_NAME_COLLISION 声明名相互重复。
|
|
30
|
+
*/
|
|
31
|
+
export function buildToolRegistry(tools, policyFingerprint) {
|
|
32
|
+
const declaredToKmh = new Map();
|
|
33
|
+
const kmhToDeclared = new Map();
|
|
34
|
+
for (const tool of tools) {
|
|
35
|
+
const declared = KMH_TOOL_PREFIX + tool.name;
|
|
36
|
+
if (!DECLARED_NAME.test(declared))
|
|
37
|
+
throw new Error(`CODEX_TOOL_NAME_INVALID: ${tool.name} 前缀后超出官方工具名接受范围`);
|
|
38
|
+
if (declaredToKmh.has(declared))
|
|
39
|
+
throw new Error(`CODEX_TOOL_NAME_COLLISION: ${declared}`);
|
|
40
|
+
declaredToKmh.set(declared, tool.name);
|
|
41
|
+
kmhToDeclared.set(tool.name, declared);
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
declaredToKmh,
|
|
45
|
+
kmhToDeclared,
|
|
46
|
+
fingerprint: toolFingerprintOf(tools, policyFingerprint),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* 解析回调中的工具名为 KMH 注册名。
|
|
51
|
+
* 先按声明表精确命中;未命中时兼容裸名(旧 thread 以裸名声明工具);
|
|
52
|
+
* 兼容范围以本回合的 KMH 工具表为准,防旧名误映射到已不存在的工具。
|
|
53
|
+
* @param registry - 本回合声明表;临时会话(无工具)传 undefined。
|
|
54
|
+
* @param name - 服务端回调携带的工具名。
|
|
55
|
+
* @returns 对应的 KMH 注册名;未知名称返回 undefined。
|
|
56
|
+
*/
|
|
57
|
+
export function resolveKmhToolName(registry, name) {
|
|
58
|
+
if (registry === undefined)
|
|
59
|
+
return undefined;
|
|
60
|
+
const mapped = registry.declaredToKmh.get(name);
|
|
61
|
+
if (mapped !== undefined)
|
|
62
|
+
return mapped;
|
|
63
|
+
if (registry.kmhToDeclared.has(name))
|
|
64
|
+
return name;
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
/** 提示中的声明约定说明:加在 developerInstructions,避免改写正文词义。 */
|
|
68
|
+
export function toolDeclarationNote() {
|
|
69
|
+
return `KMH 工具在本会话中以 ${KMH_TOOL_PREFIX} 前缀声明;系统提示或用户内容中提到的 KMH 工具名,即对应加该前缀后的同名工具。`;
|
|
70
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/** CLI 工具选择的数据形状:Config 字段 toolSelection、目录行、来源与目标身份及开关判定。 */
|
|
2
|
+
import Schema from "@deepseek-ai/schemastery";
|
|
3
|
+
import { type Branded } from "@deepseek-ai/dsh-brand";
|
|
4
|
+
import type { ToolSchema } from "@deepseek-ai/dsh-llm";
|
|
5
|
+
import type { JsonValue } from "@deepseek-ai/dsh-util-values";
|
|
6
|
+
/** 工具来源身份:codex/native、codex/mcp/<server>、harness 等。 */
|
|
7
|
+
export type ToolSourceId = Branded<"CliToolSourceId">;
|
|
8
|
+
/** 把来源字符串标记为来源身份。 */
|
|
9
|
+
export declare function ToolSourceId(value: string): ToolSourceId;
|
|
10
|
+
/** CLI profile 条目身份(profile 清单中的插件 id)。 */
|
|
11
|
+
export type CliTargetId = Branded<"CliTargetId">;
|
|
12
|
+
/** 把条目 id 标记为目标身份。 */
|
|
13
|
+
export declare function CliTargetId(value: string): CliTargetId;
|
|
14
|
+
declare const entryFields: {
|
|
15
|
+
source: Schema<string, string, "defined">;
|
|
16
|
+
name: Schema<string, string, "defined">;
|
|
17
|
+
enabled: Schema<boolean, boolean, "defined">;
|
|
18
|
+
};
|
|
19
|
+
declare const selectionFields: {
|
|
20
|
+
version: Schema<1, 1, "defined">;
|
|
21
|
+
harness: Schema<Schemastery.ObjectS<typeof entryFields>[], Schemastery.ObjectT<typeof entryFields>[], "defined">;
|
|
22
|
+
native: Schema<Schemastery.ObjectS<typeof entryFields>[], Schemastery.ObjectT<typeof entryFields>[], "defined">;
|
|
23
|
+
};
|
|
24
|
+
declare const selection: Schema<Schemastery.ObjectS<typeof selectionFields>, Schemastery.ObjectT<typeof selectionFields>>;
|
|
25
|
+
/** toolSelection 字段的明文值。 */
|
|
26
|
+
export type ToolSelection = Schemastery.TypeT<typeof selection>;
|
|
27
|
+
/**
|
|
28
|
+
* 带版本的 Config 值;同侧重复身份在配置提交前失败。
|
|
29
|
+
* transform 回调收到的是 inner 校验后的输出,输入输出因此都按已校验形状声明。
|
|
30
|
+
*/
|
|
31
|
+
export declare const ToolSelectionSchema: Schema<ToolSelection, ToolSelection>;
|
|
32
|
+
type DeepReadonly<T> = T extends object ? {
|
|
33
|
+
readonly [K in keyof T]: DeepReadonly<T[K]>;
|
|
34
|
+
} : T;
|
|
35
|
+
/** volatile Config 访问器给出的深只读快照。 */
|
|
36
|
+
export type ReadonlyToolSelection = DeepReadonly<ToolSelection>;
|
|
37
|
+
/** 目录行的控制方式:可调、联动组、固定(含原因)或待核实。 */
|
|
38
|
+
export type CliToolControl = {
|
|
39
|
+
readonly kind: "adjustable";
|
|
40
|
+
} | {
|
|
41
|
+
readonly kind: "linked";
|
|
42
|
+
readonly group: string;
|
|
43
|
+
} | {
|
|
44
|
+
readonly kind: "fixed";
|
|
45
|
+
readonly enabled: boolean;
|
|
46
|
+
readonly reason: string;
|
|
47
|
+
} | {
|
|
48
|
+
readonly kind: "unverified";
|
|
49
|
+
readonly reason: string;
|
|
50
|
+
};
|
|
51
|
+
/** 目录行身份:所属侧、来源与实际名称。 */
|
|
52
|
+
export interface CliToolRef {
|
|
53
|
+
readonly side: "harness" | "native";
|
|
54
|
+
readonly source: ToolSourceId;
|
|
55
|
+
readonly name: string;
|
|
56
|
+
}
|
|
57
|
+
/** 一行可展示、可判定的工具目录条目。 */
|
|
58
|
+
export interface CliToolRow extends CliToolRef {
|
|
59
|
+
readonly description: string;
|
|
60
|
+
readonly sourceLabel?: string;
|
|
61
|
+
readonly registryName?: string;
|
|
62
|
+
readonly declaration?: JsonValue;
|
|
63
|
+
readonly schema?: ToolSchema;
|
|
64
|
+
readonly control: CliToolControl;
|
|
65
|
+
}
|
|
66
|
+
/** 一次完整目录及两侧各自的诊断。 */
|
|
67
|
+
export interface CliToolCatalog {
|
|
68
|
+
readonly revision: string;
|
|
69
|
+
readonly tools: readonly CliToolRow[];
|
|
70
|
+
readonly diagnostics?: Partial<Record<"harness" | "native", string>>;
|
|
71
|
+
}
|
|
72
|
+
/** 会话创建时保存的 Harness 工具快照条目。 */
|
|
73
|
+
export interface SavedInventoryEntry {
|
|
74
|
+
readonly source: ToolSourceId;
|
|
75
|
+
readonly sourceLabel?: string;
|
|
76
|
+
readonly schema: ToolSchema;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* 判定一行是否开启:固定行取其实际状态;其余按保存的身份查找。
|
|
80
|
+
* Harness 侧的公开注册表不暴露插件来源,身份未命中时按名称回退,
|
|
81
|
+
* 以兼容带旧来源 id 的已保存配置;名称也未出现时默认开启——导入只能
|
|
82
|
+
* 看到当时可见的工具,缺行不能关掉既有 KMH 工具。原生行缺省关闭。
|
|
83
|
+
* @param value 已接受的 toolSelection。
|
|
84
|
+
* @param row 实际目录行。
|
|
85
|
+
* @returns 保存的选择、固定行的实际状态或该侧的缺省值。
|
|
86
|
+
*/
|
|
87
|
+
export declare function choiceEnabled(value: ReadonlyToolSelection, row: CliToolRow): boolean;
|
|
88
|
+
export {};
|