@ktkid/kmh-codex-cli 0.0.0-stage → 0.1.1
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 +295 -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 +21396 -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 +221 -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 +54 -0
- package/lib/src/cursor.js +325 -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 +141 -0
- package/lib/src/index.js +534 -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-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 +171 -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,298 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile, rename } from "node:fs/promises";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { join, dirname } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { selectionFromLegacy } from "./capabilities.js";
|
|
7
|
+
import { connectCodex } from "./connection.js";
|
|
8
|
+
import { ModelListResult, fieldOf, shallowCopy } from "./protocol.js";
|
|
9
|
+
const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
/** 包内随附的官方基线目录(未修改的 vendored 副本)。 */
|
|
11
|
+
function vendoredCatalogPath() {
|
|
12
|
+
return join(moduleDir, "..", "..", "vendor", "codex", "models.json");
|
|
13
|
+
}
|
|
14
|
+
/** TOML 基本字符串。 */
|
|
15
|
+
function tomlString(value) {
|
|
16
|
+
return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
|
|
17
|
+
}
|
|
18
|
+
/** probe 验证过的每模型基础裁剪字段:工具模式直通、未开放的原生工具清空。 */
|
|
19
|
+
const BASE_PRUNED_MODEL_FIELDS = {
|
|
20
|
+
tool_mode: "direct",
|
|
21
|
+
experimental_supported_tools: [],
|
|
22
|
+
multi_agent_version: "disabled",
|
|
23
|
+
use_responses_lite: false,
|
|
24
|
+
include_apps_usage_instructions: false,
|
|
25
|
+
include_plugin_usage_instructions: false,
|
|
26
|
+
};
|
|
27
|
+
/** 各选择项未开放时追加的裁剪字段(允许清单:关一项裁一项)。 */
|
|
28
|
+
const ITEM_PRUNED_MODEL_FIELDS = [
|
|
29
|
+
{ key: "commandExecution", fields: { shell_type: "disabled" } },
|
|
30
|
+
{ key: "fileChange", fields: { apply_patch_tool_type: null } },
|
|
31
|
+
{ key: "webSearch", fields: { supports_search_tool: false } },
|
|
32
|
+
{ key: "skills", fields: { include_skills_usage_instructions: false } },
|
|
33
|
+
];
|
|
34
|
+
/**
|
|
35
|
+
* 官方 CLI `-c` 进程参数的基础功能关闭集合(probe 与冒烟验证过)。
|
|
36
|
+
* 基础隔离不随选择开放:多 agent、apps、插件、目标、Code Mode 等始终关闭;
|
|
37
|
+
* 逐项可开放的(shell_tool、view_image)按选择条件注入。每项对应
|
|
38
|
+
* `features.<名称>=false`:只影响本次进程,不落任何配置文件。
|
|
39
|
+
*/
|
|
40
|
+
const FEATURE_OFF_BASE = [
|
|
41
|
+
// 关闭多 agent 编排(两代开关都关)。
|
|
42
|
+
"multi_agent",
|
|
43
|
+
"multi_agent_v2",
|
|
44
|
+
// 关闭 Codex 应用(apps)能力。
|
|
45
|
+
"apps",
|
|
46
|
+
// 关闭插件市场装载(dynamic tools 不受影响)。
|
|
47
|
+
"plugins",
|
|
48
|
+
// 关闭目标(goals)能力。
|
|
49
|
+
"goals",
|
|
50
|
+
// 关闭 token 预算控制:用量统计由 KMH 侧完成。
|
|
51
|
+
"token_budget",
|
|
52
|
+
// 关闭记忆(memories)读写。
|
|
53
|
+
"memories",
|
|
54
|
+
// 关闭 Code Mode 嵌套 agent 与其独占模式。
|
|
55
|
+
"code_mode",
|
|
56
|
+
"code_mode_only",
|
|
57
|
+
// 关闭休眠定时工具。
|
|
58
|
+
"sleep_tool",
|
|
59
|
+
// 关闭当前时间提醒注入。
|
|
60
|
+
"current_time_reminder",
|
|
61
|
+
];
|
|
62
|
+
/** 逐项可开放的功能开关:选择项关闭时才注入对应 features.<名>=false。 */
|
|
63
|
+
const ITEM_FEATURE_OFF = [
|
|
64
|
+
{ key: "commandExecution", features: ["shell_tool"] },
|
|
65
|
+
{ key: "viewImage", features: ["view_image"] },
|
|
66
|
+
];
|
|
67
|
+
/**
|
|
68
|
+
* 探针进程上发现会话范围的原生技能路径与用户钩子。
|
|
69
|
+
* 钩子 key 形如 `<hooks.json 路径>:<事件>:<组序>:<项序>`,是
|
|
70
|
+
* `hooks.state` 禁用配置的键;user/project 来源都收集(KMH 回合
|
|
71
|
+
* 不应触发用户本机钩子)。
|
|
72
|
+
* @param ctx - 宿主上下文。
|
|
73
|
+
* @param config - 插件配置。
|
|
74
|
+
* @param input - 会话工作目录与中止信号。
|
|
75
|
+
* @throws CODEX_SKILLS_DISCOVERY_FAILED 发现请求失败。
|
|
76
|
+
*/
|
|
77
|
+
async function discoverUserCapabilities(ctx, config, input) {
|
|
78
|
+
const connection = await connectCodex(ctx, {
|
|
79
|
+
command: config.command,
|
|
80
|
+
cwd: input.cwd,
|
|
81
|
+
configOverrides: [],
|
|
82
|
+
env: config.env,
|
|
83
|
+
graceMs: config.graceMs,
|
|
84
|
+
startupTimeoutMs: config.startupTimeoutMs,
|
|
85
|
+
}, input.signal);
|
|
86
|
+
try {
|
|
87
|
+
const raw = await connection.request("skills/list", { cwds: [input.cwd], forceReload: false }, input.signal);
|
|
88
|
+
const entries = SkillListResult.parse(raw);
|
|
89
|
+
const paths = [];
|
|
90
|
+
for (const entry of entries.data)
|
|
91
|
+
for (const skill of entry.skills)
|
|
92
|
+
if (skill.enabled && !paths.includes(skill.path))
|
|
93
|
+
paths.push(skill.path);
|
|
94
|
+
const rawHooks = await connection.request("hooks/list", { cwds: [input.cwd] }, input.signal);
|
|
95
|
+
const hookKeys = [];
|
|
96
|
+
for (const entry of HooksListResult.parse(rawHooks).data)
|
|
97
|
+
for (const hook of entry.hooks)
|
|
98
|
+
if (hook.enabled &&
|
|
99
|
+
(hook.source === "user" || hook.source === "project") &&
|
|
100
|
+
!hookKeys.includes(hook.key))
|
|
101
|
+
hookKeys.push(hook.key);
|
|
102
|
+
const imageOverrides = [];
|
|
103
|
+
if (input.imageOnly) {
|
|
104
|
+
const settings = ImageOnlyConfig.parse(await connection.request("config/read", { includeLayers: false }, input.signal)).config;
|
|
105
|
+
for (const key of Object.keys(settings.mcp_servers ?? {}))
|
|
106
|
+
imageOverrides.push(imageExtensionOverride("mcp_servers", key));
|
|
107
|
+
for (const key of Object.keys(settings.plugins ?? {}))
|
|
108
|
+
imageOverrides.push(imageExtensionOverride("plugins", key));
|
|
109
|
+
}
|
|
110
|
+
return { skills: paths, hookKeys, imageOverrides };
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
throw new Error(`CODEX_SKILLS_DISCOVERY_FAILED: ${error instanceof Error ? error.message : String(error)}`);
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
await connection.stop(config.cleanupTimeoutMs);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** config/read 的执行扩展字段;仅消费名称,凭据留在 CLI 内部。 */
|
|
120
|
+
const ImageOnlyConfig = z.object({
|
|
121
|
+
config: z.object({
|
|
122
|
+
mcp_servers: z.record(z.string(), z.unknown()).optional(),
|
|
123
|
+
plugins: z.record(z.string(), z.unknown()).optional(),
|
|
124
|
+
}),
|
|
125
|
+
});
|
|
126
|
+
/** CLI 按点分割覆盖路径;仅接收可直接定位的扩展名,其他名称使生图准备失败。 */
|
|
127
|
+
function imageExtensionOverride(group, key) {
|
|
128
|
+
if (!/^[a-zA-Z0-9_@-]+$/.test(key))
|
|
129
|
+
throw new Error("CODEX_IMAGE_EXTENSION_NAME_UNSUPPORTED");
|
|
130
|
+
return `${group}.${key}.enabled=false`;
|
|
131
|
+
}
|
|
132
|
+
/** skills/list 响应形态。 */
|
|
133
|
+
const SkillListResult = z.object({
|
|
134
|
+
data: z.array(z.object({
|
|
135
|
+
skills: z.array(z.object({ path: z.string(), enabled: z.boolean() })),
|
|
136
|
+
})),
|
|
137
|
+
});
|
|
138
|
+
/** hooks/list 响应形态(只取禁用所需字段)。 */
|
|
139
|
+
const HooksListResult = z.object({
|
|
140
|
+
data: z.array(z.object({
|
|
141
|
+
hooks: z.array(z.object({
|
|
142
|
+
key: z.string(),
|
|
143
|
+
source: z.string(),
|
|
144
|
+
enabled: z.boolean(),
|
|
145
|
+
})),
|
|
146
|
+
})),
|
|
147
|
+
});
|
|
148
|
+
/**
|
|
149
|
+
* 按选择计算每模型裁剪字段(允许清单:基础 + 未开放项的追加)。
|
|
150
|
+
* @param selection - 逐项选择。
|
|
151
|
+
* @returns 将覆盖到目录每个模型上的字段表。
|
|
152
|
+
*/
|
|
153
|
+
export function prunedFieldsFor(selection) {
|
|
154
|
+
const fields = { ...BASE_PRUNED_MODEL_FIELDS };
|
|
155
|
+
for (const item of ITEM_PRUNED_MODEL_FIELDS)
|
|
156
|
+
if (!selection[item.key])
|
|
157
|
+
Object.assign(fields, item.fields);
|
|
158
|
+
return fields;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* 按选择计算功能关闭集合(基础始终关闭 + 未开放项的条件关闭)。
|
|
162
|
+
* @param selection - 逐项选择。
|
|
163
|
+
* @returns 将注入 `features.<名>=false` 的功能名列表。
|
|
164
|
+
*/
|
|
165
|
+
export function featureOffFor(selection) {
|
|
166
|
+
const features = [...FEATURE_OFF_BASE];
|
|
167
|
+
for (const item of ITEM_FEATURE_OFF)
|
|
168
|
+
if (!selection[item.key])
|
|
169
|
+
features.push(...item.features);
|
|
170
|
+
return features;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* 生成隔离计划(允许清单式):基础隔离始终保留,未选择的项维持关闭、
|
|
174
|
+
* 选中的项开放(目录字段与功能开关按项条件注入),改写 vendored 目录
|
|
175
|
+
* 为裁剪目录并落盘,汇总全部 -c 覆盖。
|
|
176
|
+
* @param ctx - 宿主上下文。
|
|
177
|
+
* @param config - 插件配置;selection 未提供时按旧开关迁移。
|
|
178
|
+
* @param input - 会话工作目录、选择与中止信号。
|
|
179
|
+
* @returns 进程启动参数所需的覆盖数组。
|
|
180
|
+
* @throws CODEX_CATALOG_PRUNE_FAILED 目录读取或改写失败。
|
|
181
|
+
*/
|
|
182
|
+
export async function prepareIsolation(ctx, config, input) {
|
|
183
|
+
const selection = input.selection ?? selectionFromLegacy(config.nativeToolsEnabled);
|
|
184
|
+
const discovered = await discoverUserCapabilities(ctx, config, input);
|
|
185
|
+
const disabledSkills = selection.skills ? [] : discovered.skills;
|
|
186
|
+
let catalog;
|
|
187
|
+
try {
|
|
188
|
+
const text = await readFile(vendoredCatalogPath(), "utf8");
|
|
189
|
+
catalog = JSON.parse(typeof text === "string" ? text : "");
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
throw new Error(`CODEX_CATALOG_PRUNE_FAILED: ${error instanceof Error ? error.message : String(error)}`);
|
|
193
|
+
}
|
|
194
|
+
const models = fieldOf(catalog, "models");
|
|
195
|
+
if (!Array.isArray(models))
|
|
196
|
+
throw new Error("CODEX_CATALOG_PRUNE_FAILED: malformed vendored catalog");
|
|
197
|
+
const prunedFields = prunedFieldsFor(selection);
|
|
198
|
+
const pruned = shallowCopy(catalog, "CODEX_CATALOG_PRUNE_FAILED: malformed vendored catalog");
|
|
199
|
+
pruned.models = models.map((model) => ({
|
|
200
|
+
...shallowCopy(model, "CODEX_CATALOG_PRUNE_FAILED: malformed model entry"),
|
|
201
|
+
...prunedFields,
|
|
202
|
+
}));
|
|
203
|
+
await mkdir(config.dataDir, { recursive: true, mode: 0o700 });
|
|
204
|
+
const body = JSON.stringify(pruned);
|
|
205
|
+
const catalogPath = join(config.dataDir, `models-${createHash("sha256").update(body).digest("hex")}.json`);
|
|
206
|
+
const pendingPath = `${catalogPath}.${randomUUID()}.tmp`;
|
|
207
|
+
await writeFile(pendingPath, body, { mode: 0o600 });
|
|
208
|
+
await rename(pendingPath, catalogPath);
|
|
209
|
+
// 禁止修改任何 Codex 配置文件:隔离全部经进程 -c 参数注入,只影响本次调用。
|
|
210
|
+
// CODEX_HOME 沿用用户默认(~/.codex):登录共享、无需额外登录;
|
|
211
|
+
// 用户配置的 MCP 设备随之可见(已拍板接受)。
|
|
212
|
+
const featureOff = featureOffFor(selection);
|
|
213
|
+
const overrides = [
|
|
214
|
+
...discovered.imageOverrides,
|
|
215
|
+
// 模型目录指向插件裁剪副本:未开放项的工具能力字段被改写为关闭形态,
|
|
216
|
+
// 选中项保持 vendored 原生值。
|
|
217
|
+
`model_catalog_json=${tomlString(catalogPath)}`,
|
|
218
|
+
// 启动时不检查更新,避免额外网络请求。
|
|
219
|
+
"check_for_update_on_startup=false",
|
|
220
|
+
// 项目说明文档(AGENTS.md 类)注入字节数归零:提示由 KMH 统一提供。
|
|
221
|
+
"project_doc_max_bytes=0",
|
|
222
|
+
// 逐项关闭基础功能(含义见 FEATURE_OFF_BASE 注释)。
|
|
223
|
+
...featureOff.map((feature) => `features.${feature}=false`),
|
|
224
|
+
// 关闭计划工具(update_plan):任务规划由 KMH 侧完成。
|
|
225
|
+
"tools.update_plan.enabled=false",
|
|
226
|
+
// 关闭实验性用户输入工具:用户交互走 KMH。
|
|
227
|
+
"tools.experimental_request_user_input.enabled=false",
|
|
228
|
+
// 关闭编排器的技能与 MCP 装载(基础隔离,不随选择开放)。
|
|
229
|
+
"orchestrator.skills.enabled=false",
|
|
230
|
+
"orchestrator.mcp.enabled=false",
|
|
231
|
+
// 关闭遥测分析上报。
|
|
232
|
+
"analytics.enabled=false",
|
|
233
|
+
];
|
|
234
|
+
if (!selection.webSearch)
|
|
235
|
+
// 关闭联网搜索工具(选中时不注入,保持原生可用)。
|
|
236
|
+
overrides.push(`web_search=${tomlString("disabled")}`);
|
|
237
|
+
if (!selection.skills) {
|
|
238
|
+
overrides.push(
|
|
239
|
+
// 不向模型注入技能使用说明。
|
|
240
|
+
"skills.include_instructions=false",
|
|
241
|
+
// 关闭官方捆绑技能。
|
|
242
|
+
"skills.bundled.enabled=false");
|
|
243
|
+
if (disabledSkills.length > 0)
|
|
244
|
+
overrides.push(
|
|
245
|
+
// 按路径逐个关闭原生技能:堵住 `$技能名` 显式调用触发原生技能的
|
|
246
|
+
// 路径;每回合启动前重新发现(技能目录可能变化)。
|
|
247
|
+
`skills.config=[${disabledSkills
|
|
248
|
+
.map((path) => `{path=${tomlString(path)},enabled=false}`)
|
|
249
|
+
.join(",")}]`);
|
|
250
|
+
}
|
|
251
|
+
if (discovered.hookKeys.length > 0)
|
|
252
|
+
overrides.push(
|
|
253
|
+
// 逐个禁用用户/项目级钩子(hooks.json):共享 ~/.codex 的连带,
|
|
254
|
+
// KMH 回合不应触发用户本机钩子(userPromptSubmit/stop 等)。
|
|
255
|
+
`hooks.state={${discovered.hookKeys
|
|
256
|
+
.map((key) => `${tomlString(key)}={enabled=false}`)
|
|
257
|
+
.join(",")}}`);
|
|
258
|
+
if (input.permission !== undefined &&
|
|
259
|
+
(selection.commandExecution || selection.fileChange)) {
|
|
260
|
+
// 帮我审批保留 KMH 的 never 旋钮,原生权限请求交 Codex 自动审查。
|
|
261
|
+
const autoReview = input.permission.sandbox === "workspace-write" &&
|
|
262
|
+
input.permission.approval === "never";
|
|
263
|
+
overrides.push(`sandbox_mode=${tomlString(input.permission.sandbox)}`, `approval_policy=${tomlString(autoReview || input.permission.approval === "ask"
|
|
264
|
+
? "on-request"
|
|
265
|
+
: "never")}`);
|
|
266
|
+
if (autoReview || input.permission.approval === "ask")
|
|
267
|
+
overrides.push(`approvals_reviewer=${tomlString(autoReview ? "auto_review" : "user")}`);
|
|
268
|
+
}
|
|
269
|
+
return { configOverrides: overrides, catalogPath, disabledSkills };
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* 隔离生效核对:正式进程目录必须来自裁剪文件。
|
|
273
|
+
* @param connection - 已带隔离覆盖启动的连接。
|
|
274
|
+
* @param plan - 本次隔离计划。
|
|
275
|
+
* @param signal - 中止信号。
|
|
276
|
+
* @throws CODEX_ISOLATION_FAILED 目录与裁剪文件不一致。
|
|
277
|
+
*/
|
|
278
|
+
export async function verifyIsolation(connection, plan, signal) {
|
|
279
|
+
if (plan.catalogPath === "")
|
|
280
|
+
return;
|
|
281
|
+
const raw = await connection.request("model/list", { includeHidden: false }, signal);
|
|
282
|
+
const live = ModelListResult.parse(raw);
|
|
283
|
+
let prunedIds;
|
|
284
|
+
try {
|
|
285
|
+
const text = await readFile(plan.catalogPath, "utf8");
|
|
286
|
+
const catalog = JSON.parse(typeof text === "string" ? text : "");
|
|
287
|
+
const models = fieldOf(catalog, "models");
|
|
288
|
+
prunedIds = new Set((Array.isArray(models) ? models : [])
|
|
289
|
+
.map((model) => fieldOf(model, "slug"))
|
|
290
|
+
.filter((slug) => typeof slug === "string"));
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
throw new Error("CODEX_ISOLATION_FAILED: unreadable pruned catalog");
|
|
294
|
+
}
|
|
295
|
+
for (const entry of live.data)
|
|
296
|
+
if (!prunedIds.has(entry.id))
|
|
297
|
+
throw new Error(`CODEX_ISOLATION_FAILED: live catalog has ${entry.id} outside pruned set`);
|
|
298
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Host 与 Client 共用的会话连接状态响应。 */
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
/** CLI 连接状态;重试期间 streaming 保持 true。 */
|
|
4
|
+
export declare const SessionLiveState: z.ZodObject<{
|
|
5
|
+
color: z.ZodEnum<{
|
|
6
|
+
green: "green";
|
|
7
|
+
gray: "gray";
|
|
8
|
+
red: "red";
|
|
9
|
+
}>;
|
|
10
|
+
streaming: z.ZodBoolean;
|
|
11
|
+
retrying: z.ZodDefault<z.ZodBoolean>;
|
|
12
|
+
detail: z.ZodString;
|
|
13
|
+
updatedAt: z.ZodNumber;
|
|
14
|
+
}, z.core.$strip>;
|
|
15
|
+
/** 已校验的 CLI 连接状态。 */
|
|
16
|
+
export type SessionLiveState = z.infer<typeof SessionLiveState>;
|
|
17
|
+
/** /api/codex-cli/live 响应;旧 Host 缺少 retrying 时按空闲重试状态读取。 */
|
|
18
|
+
export declare const LiveSnapshot: z.ZodObject<{
|
|
19
|
+
sessions: z.ZodArray<z.ZodObject<{
|
|
20
|
+
color: z.ZodEnum<{
|
|
21
|
+
green: "green";
|
|
22
|
+
gray: "gray";
|
|
23
|
+
red: "red";
|
|
24
|
+
}>;
|
|
25
|
+
streaming: z.ZodBoolean;
|
|
26
|
+
retrying: z.ZodDefault<z.ZodBoolean>;
|
|
27
|
+
detail: z.ZodString;
|
|
28
|
+
updatedAt: z.ZodNumber;
|
|
29
|
+
sessionId: z.ZodString;
|
|
30
|
+
}, z.core.$strip>>;
|
|
31
|
+
}, z.core.$strip>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Host 与 Client 共用的会话连接状态响应。 */
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
/** CLI 连接状态;重试期间 streaming 保持 true。 */
|
|
4
|
+
export const SessionLiveState = z.object({
|
|
5
|
+
color: z.enum(["green", "gray", "red"]),
|
|
6
|
+
streaming: z.boolean(),
|
|
7
|
+
retrying: z.boolean().default(false),
|
|
8
|
+
detail: z.string(),
|
|
9
|
+
updatedAt: z.number(),
|
|
10
|
+
});
|
|
11
|
+
/** /api/codex-cli/live 响应;旧 Host 缺少 retrying 时按空闲重试状态读取。 */
|
|
12
|
+
export const LiveSnapshot = z.object({
|
|
13
|
+
sessions: z.array(SessionLiveState.extend({ sessionId: z.string() })),
|
|
14
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** 模型目录:分页聚合与 KMH 模型元数据映射。 */
|
|
2
|
+
import { type LlmModelInfo, type LlmResolvedModelInfo, type ModelModality } from "@deepseek-ai/dsh-llm";
|
|
3
|
+
import type { CodexConnection } from "./connection.ts";
|
|
4
|
+
/** 目录条目的插件侧形态。 */
|
|
5
|
+
export interface CodexModelEntry {
|
|
6
|
+
id: string;
|
|
7
|
+
displayName: string;
|
|
8
|
+
inputModalities: readonly ModelModality[];
|
|
9
|
+
/** 模型声明的推理等级;空表示不可调节。 */
|
|
10
|
+
efforts: string[];
|
|
11
|
+
defaultEffort?: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* 拉取并聚合模型目录(含分页)。
|
|
15
|
+
* @param connection - 已建立的连接。
|
|
16
|
+
* @param signal - 中止信号。
|
|
17
|
+
* @returns 按 CLI 返回顺序排列的目录条目。
|
|
18
|
+
* @throws CODEX_MODEL_LIST_FAILED 请求失败或响应不合法。
|
|
19
|
+
*/
|
|
20
|
+
export declare function fetchCatalog(connection: CodexConnection, signal: AbortSignal): Promise<CodexModelEntry[]>;
|
|
21
|
+
/** 目录条目映射为 KMH 模型列表项。 */
|
|
22
|
+
export declare function toLlmModels(provider: string, entries: readonly CodexModelEntry[]): LlmModelInfo[];
|
|
23
|
+
/** 目录条目映射为解析结果;推理等级取模型声明的可选值。 */
|
|
24
|
+
export declare function resolveLlmModel(provider: string, entry: CodexModelEntry | undefined, defaultMaxTokens: number): LlmResolvedModelInfo;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/** 模型目录:分页聚合与 KMH 模型元数据映射。 */
|
|
2
|
+
import { ReasoningEffortId, } from "@deepseek-ai/dsh-llm";
|
|
3
|
+
import { ModelListResult, fieldOf } from "./protocol.js";
|
|
4
|
+
/** 推理等级的展示名。 */
|
|
5
|
+
const effortName = {
|
|
6
|
+
minimal: "Minimal",
|
|
7
|
+
low: "Low",
|
|
8
|
+
medium: "Medium",
|
|
9
|
+
high: "High",
|
|
10
|
+
xhigh: "XHigh",
|
|
11
|
+
max: "Max",
|
|
12
|
+
ultra: "Ultra",
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* 拉取并聚合模型目录(含分页)。
|
|
16
|
+
* @param connection - 已建立的连接。
|
|
17
|
+
* @param signal - 中止信号。
|
|
18
|
+
* @returns 按 CLI 返回顺序排列的目录条目。
|
|
19
|
+
* @throws CODEX_MODEL_LIST_FAILED 请求失败或响应不合法。
|
|
20
|
+
*/
|
|
21
|
+
export async function fetchCatalog(connection, signal) {
|
|
22
|
+
const entries = [];
|
|
23
|
+
let cursor;
|
|
24
|
+
try {
|
|
25
|
+
for (let page = 0; page < 20; page++) {
|
|
26
|
+
const params = { includeHidden: false };
|
|
27
|
+
if (cursor !== undefined)
|
|
28
|
+
params.cursor = cursor;
|
|
29
|
+
const raw = await connection.request("model/list", params, signal);
|
|
30
|
+
const result = ModelListResult.parse(raw);
|
|
31
|
+
for (const model of result.data) {
|
|
32
|
+
const efforts = [];
|
|
33
|
+
for (const effort of model.supportedReasoningEfforts ?? []) {
|
|
34
|
+
if (typeof effort === "string")
|
|
35
|
+
efforts.push(effort);
|
|
36
|
+
else {
|
|
37
|
+
const value = fieldOf(effort, "reasoningEffort");
|
|
38
|
+
if (typeof value === "string")
|
|
39
|
+
efforts.push(value);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const entry = {
|
|
43
|
+
id: model.id,
|
|
44
|
+
displayName: model.displayName ?? model.id,
|
|
45
|
+
inputModalities: model.inputModalities?.includes("image")
|
|
46
|
+
? ["text", "image"]
|
|
47
|
+
: ["text"],
|
|
48
|
+
efforts,
|
|
49
|
+
};
|
|
50
|
+
if (model.defaultReasoningEffort !== undefined)
|
|
51
|
+
entry.defaultEffort = model.defaultReasoningEffort;
|
|
52
|
+
entries.push(entry);
|
|
53
|
+
}
|
|
54
|
+
cursor = result.nextPageCursor;
|
|
55
|
+
if (cursor === undefined)
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
if (error instanceof Error && error.message.startsWith("CODEX_"))
|
|
61
|
+
throw error;
|
|
62
|
+
throw new Error(`CODEX_MODEL_LIST_FAILED: ${error instanceof Error ? error.message : String(error)}`);
|
|
63
|
+
}
|
|
64
|
+
return entries;
|
|
65
|
+
}
|
|
66
|
+
/** 目录条目映射为 KMH 模型列表项。 */
|
|
67
|
+
export function toLlmModels(provider, entries) {
|
|
68
|
+
return entries.map((entry) => ({
|
|
69
|
+
provider,
|
|
70
|
+
id: entry.id,
|
|
71
|
+
name: entry.displayName,
|
|
72
|
+
inputModalities: entry.inputModalities,
|
|
73
|
+
}));
|
|
74
|
+
}
|
|
75
|
+
/** 目录条目映射为解析结果;推理等级取模型声明的可选值。 */
|
|
76
|
+
export function resolveLlmModel(provider, entry, defaultMaxTokens) {
|
|
77
|
+
if (entry === undefined)
|
|
78
|
+
throw new Error("CODEX_MODEL_UNKNOWN");
|
|
79
|
+
const efforts = entry.efforts.map((effort) => ({
|
|
80
|
+
id: ReasoningEffortId(effort),
|
|
81
|
+
name: effortName[effort] ?? effort,
|
|
82
|
+
}));
|
|
83
|
+
return {
|
|
84
|
+
provider,
|
|
85
|
+
id: entry.id,
|
|
86
|
+
name: entry.displayName,
|
|
87
|
+
inputModalities: entry.inputModalities,
|
|
88
|
+
defaultMaxTokens,
|
|
89
|
+
...(efforts.length > 0
|
|
90
|
+
? {
|
|
91
|
+
reasoning: {
|
|
92
|
+
efforts,
|
|
93
|
+
defaultEffort: ReasoningEffortId(entry.defaultEffort ?? entry.efforts[0] ?? "medium"),
|
|
94
|
+
},
|
|
95
|
+
}
|
|
96
|
+
: {}),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* v1 形态说明(D14 预案的落地取舍):完整的独立观察记录与对话卡片需要
|
|
3
|
+
* 宿主新增公开扩展点(可 ignorable 的插件会话事件或扩展块类型;现有
|
|
4
|
+
* Session.append 无法写 ignorable 标记,自定义事件会破坏旧宿主的会话
|
|
5
|
+
* 重载)。v1 用既有公开通道:原生活动叙述为助手消息内独立文本块,
|
|
6
|
+
* 与生图附注同一形态——差分账目(blockDigest)自动把它们识别为
|
|
7
|
+
* Codex 自产内容,刷新/重开后随会话历史可查。
|
|
8
|
+
*/
|
|
9
|
+
/** 单条原生调用的叙述体积上限;超出截断并标注(D14:限制记录体积)。 */
|
|
10
|
+
export declare const NATIVE_NOTE_LIMIT = 8000;
|
|
11
|
+
/** 可叙述的原生 item wire 类型(0.160.0 ThreadItem 变体,camelCase)。 */
|
|
12
|
+
export type NativeItemType = "commandExecution" | "fileChange" | "mcpToolCall" | "imageView" | "imageGeneration";
|
|
13
|
+
/** 叙述条目:item 定位与开头一行。 */
|
|
14
|
+
export interface NativeHeader {
|
|
15
|
+
itemId: string;
|
|
16
|
+
header: string;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* 从 item/started 或 item/completed 的 item 提取叙述开头。
|
|
20
|
+
* @param item - ThreadItem 原始对象。
|
|
21
|
+
* @returns 可叙述类型时返回条目;其余(KMH 桥的 dynamicToolCall、模型
|
|
22
|
+
* 自产 agentMessage/reasoning 等)返回 undefined,不叙述。
|
|
23
|
+
*/
|
|
24
|
+
export declare function nativeHeaderOf(item: unknown): NativeHeader | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* 构造 item/completed 的收尾叙述:完成状态、退出码与耗时(增量输出
|
|
27
|
+
* 已随 delta 流入,此处只收状态,避免与 aggregatedOutput 重复)。
|
|
28
|
+
* @param item - ThreadItem 原始对象。
|
|
29
|
+
* @returns 收尾文本;不可叙述类型返回 undefined。
|
|
30
|
+
*/
|
|
31
|
+
export declare function nativeCompletionNoteOf(item: unknown): string | undefined;
|
|
32
|
+
/** 回合终止时未收到完成确认的调用补记(场景5/6:状态待确认)。 */
|
|
33
|
+
export declare const NATIVE_UNSETTLED_NOTE = "\u25B8 \u56DE\u5408\u7ED3\u675F\u4ECD\u672A\u6536\u5230\u5B8C\u6210\u786E\u8BA4\uFF0C\u72B6\u6001\u5F85\u786E\u8BA4\uFF1B\u5DF2\u6709\u8F93\u51FA\u4FDD\u7559\u3002";
|
|
34
|
+
/** turn 级 diff 叙述的固定 item 标识(懒开启)。 */
|
|
35
|
+
export declare const NATIVE_DIFF_NOTE_ID = "codex-native-diff";
|
|
36
|
+
/** 输出截断标注。 */
|
|
37
|
+
export declare const NATIVE_TRUNCATED_NOTE = "\n\u25B8 \uFF08\u8F93\u51FA\u8D85\u8FC7\u8BB0\u5F55\u4E0A\u9650\uFF0C\u5DF2\u622A\u65AD\uFF09";
|
|
38
|
+
/** turn 级 diff 更新的摘要行(按 +/- 行数统计,排除 +++/--- 文件头)。 */
|
|
39
|
+
export declare function diffSummaryLineOf(diff: string): string;
|
|
40
|
+
/** 叙述条目的体积账目(turn 持有,reopen 重置)。 */
|
|
41
|
+
export interface NativeNoteBudget {
|
|
42
|
+
/** 已累积字符数(按 item)。 */
|
|
43
|
+
chars: number;
|
|
44
|
+
/** 已截断后停止追加。 */
|
|
45
|
+
truncated: boolean;
|
|
46
|
+
/** 是否已收尾(一次性:完成后不再追加)。 */
|
|
47
|
+
closed: boolean;
|
|
48
|
+
/** 累积的叙述全文:block-end 的权威内容(差分与消息组装以它为准)。 */
|
|
49
|
+
text: string;
|
|
50
|
+
}
|
|
51
|
+
/** 新账目。 */
|
|
52
|
+
export declare function newNoteBudget(): NativeNoteBudget;
|
|
53
|
+
/** diff 叙述账目:更新次数封顶。 */
|
|
54
|
+
export interface DiffNoteBudget {
|
|
55
|
+
updates: number;
|
|
56
|
+
}
|
|
57
|
+
export declare function newDiffBudget(): DiffNoteBudget;
|
|
58
|
+
/** diff 是否还应继续追加(封顶保护)。 */
|
|
59
|
+
export declare function diffBudgetAccepts(budget: DiffNoteBudget): boolean;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/** 原生执行叙述投影(feat08 v1):原生工具活动以文本块呈现进对话。 */
|
|
2
|
+
import { fieldOf } from "./protocol.js";
|
|
3
|
+
/**
|
|
4
|
+
* v1 形态说明(D14 预案的落地取舍):完整的独立观察记录与对话卡片需要
|
|
5
|
+
* 宿主新增公开扩展点(可 ignorable 的插件会话事件或扩展块类型;现有
|
|
6
|
+
* Session.append 无法写 ignorable 标记,自定义事件会破坏旧宿主的会话
|
|
7
|
+
* 重载)。v1 用既有公开通道:原生活动叙述为助手消息内独立文本块,
|
|
8
|
+
* 与生图附注同一形态——差分账目(blockDigest)自动把它们识别为
|
|
9
|
+
* Codex 自产内容,刷新/重开后随会话历史可查。
|
|
10
|
+
*/
|
|
11
|
+
/** 单条原生调用的叙述体积上限;超出截断并标注(D14:限制记录体积)。 */
|
|
12
|
+
export const NATIVE_NOTE_LIMIT = 8000;
|
|
13
|
+
/** turn 级 diff 叙述的最大更新次数;超出后停止追加(防刷屏)。 */
|
|
14
|
+
const DIFF_NOTE_MAX_UPDATES = 20;
|
|
15
|
+
/**
|
|
16
|
+
* 从 item/started 或 item/completed 的 item 提取叙述开头。
|
|
17
|
+
* @param item - ThreadItem 原始对象。
|
|
18
|
+
* @returns 可叙述类型时返回条目;其余(KMH 桥的 dynamicToolCall、模型
|
|
19
|
+
* 自产 agentMessage/reasoning 等)返回 undefined,不叙述。
|
|
20
|
+
*/
|
|
21
|
+
export function nativeHeaderOf(item) {
|
|
22
|
+
const type = fieldOf(item, "type");
|
|
23
|
+
const id = fieldOf(item, "id");
|
|
24
|
+
if (typeof id !== "string")
|
|
25
|
+
return undefined;
|
|
26
|
+
switch (type) {
|
|
27
|
+
case "commandExecution": {
|
|
28
|
+
const command = fieldOf(item, "command");
|
|
29
|
+
const cwd = fieldOf(item, "cwd");
|
|
30
|
+
const where = typeof cwd === "string" && cwd !== "" ? `(目录 ${cwd})` : "";
|
|
31
|
+
return {
|
|
32
|
+
itemId: id,
|
|
33
|
+
header: `▸ [codex 原生·命令] ${typeof command === "string" ? command : "(未知命令)"}${where}`,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
case "fileChange": {
|
|
37
|
+
const changes = fieldOf(item, "changes");
|
|
38
|
+
const count = Array.isArray(changes) ? changes.length : 0;
|
|
39
|
+
return {
|
|
40
|
+
itemId: id,
|
|
41
|
+
header: `▸ [codex 原生·文件修改] ${count} 个文件变更`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
case "mcpToolCall": {
|
|
45
|
+
const server = fieldOf(item, "server");
|
|
46
|
+
const tool = fieldOf(item, "tool");
|
|
47
|
+
return {
|
|
48
|
+
itemId: id,
|
|
49
|
+
header: `▸ [codex 原生·MCP] ${typeof server === "string" ? server : "?"}/${typeof tool === "string" ? tool : "?"}`,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
case "imageView":
|
|
53
|
+
return { itemId: id, header: "▸ [codex 原生·查看图片]" };
|
|
54
|
+
case "imageGeneration":
|
|
55
|
+
return {
|
|
56
|
+
itemId: id,
|
|
57
|
+
header: "▸ [codex 原生·图片生成] 执行中,等待产物…",
|
|
58
|
+
};
|
|
59
|
+
default:
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* 构造 item/completed 的收尾叙述:完成状态、退出码与耗时(增量输出
|
|
65
|
+
* 已随 delta 流入,此处只收状态,避免与 aggregatedOutput 重复)。
|
|
66
|
+
* @param item - ThreadItem 原始对象。
|
|
67
|
+
* @returns 收尾文本;不可叙述类型返回 undefined。
|
|
68
|
+
*/
|
|
69
|
+
export function nativeCompletionNoteOf(item) {
|
|
70
|
+
const type = fieldOf(item, "type");
|
|
71
|
+
const status = fieldOf(item, "status");
|
|
72
|
+
const statusText = typeof status === "string" ? status : "unknown";
|
|
73
|
+
const duration = fieldOf(item, "durationMs");
|
|
74
|
+
const suffix = typeof duration === "number" && Number.isFinite(duration)
|
|
75
|
+
? `,耗时 ${Math.max(1, Math.round(duration / 100) / 10)}s`
|
|
76
|
+
: "";
|
|
77
|
+
switch (type) {
|
|
78
|
+
case "commandExecution": {
|
|
79
|
+
const exit = fieldOf(item, "exitCode");
|
|
80
|
+
const exitText = typeof exit === "number" ? `退出码 ${exit}` : "已结束";
|
|
81
|
+
return `▸ 完成:${exitText}${suffix}(${statusText})`;
|
|
82
|
+
}
|
|
83
|
+
case "fileChange":
|
|
84
|
+
case "mcpToolCall":
|
|
85
|
+
case "imageView":
|
|
86
|
+
case "imageGeneration":
|
|
87
|
+
return `▸ 完成(${statusText}${suffix})`;
|
|
88
|
+
default:
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** 回合终止时未收到完成确认的调用补记(场景5/6:状态待确认)。 */
|
|
93
|
+
export const NATIVE_UNSETTLED_NOTE = "▸ 回合结束仍未收到完成确认,状态待确认;已有输出保留。";
|
|
94
|
+
/** turn 级 diff 叙述的固定 item 标识(懒开启)。 */
|
|
95
|
+
export const NATIVE_DIFF_NOTE_ID = "codex-native-diff";
|
|
96
|
+
/** 输出截断标注。 */
|
|
97
|
+
export const NATIVE_TRUNCATED_NOTE = "\n▸ (输出超过记录上限,已截断)";
|
|
98
|
+
/** turn 级 diff 更新的摘要行(按 +/- 行数统计,排除 +++/--- 文件头)。 */
|
|
99
|
+
export function diffSummaryLineOf(diff) {
|
|
100
|
+
let added = 0;
|
|
101
|
+
let removed = 0;
|
|
102
|
+
for (const line of diff.split("\n")) {
|
|
103
|
+
if (line.startsWith("+++") || line.startsWith("---"))
|
|
104
|
+
continue;
|
|
105
|
+
if (line.startsWith("+"))
|
|
106
|
+
added += 1;
|
|
107
|
+
else if (line.startsWith("-"))
|
|
108
|
+
removed += 1;
|
|
109
|
+
}
|
|
110
|
+
return `▸ [codex 原生·变更] turn diff 更新:+${added}/−${removed} 行`;
|
|
111
|
+
}
|
|
112
|
+
/** 新账目。 */
|
|
113
|
+
export function newNoteBudget() {
|
|
114
|
+
return { chars: 0, truncated: false, closed: false, text: "" };
|
|
115
|
+
}
|
|
116
|
+
export function newDiffBudget() {
|
|
117
|
+
return { updates: 0 };
|
|
118
|
+
}
|
|
119
|
+
/** diff 是否还应继续追加(封顶保护)。 */
|
|
120
|
+
export function diffBudgetAccepts(budget) {
|
|
121
|
+
return budget.updates < DIFF_NOTE_MAX_UPDATES;
|
|
122
|
+
}
|