@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
package/lib/src/index.js
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
/** Independently distributable KMH provider for the official Codex CLI app-server. */
|
|
2
|
+
import { brandString } from "@deepseek-ai/dsh-brand";
|
|
3
|
+
import { Service } from "@deepseek-ai/cordis";
|
|
4
|
+
import { mkdir, rename, writeFile } from "node:fs/promises";
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { addAbortListener } from "node:events";
|
|
8
|
+
import { CodexToolPolicy } from "./tool-policy.js";
|
|
9
|
+
import { applyToolSwitch, listToolSwitches } from "./tool-switches-service.js";
|
|
10
|
+
import { CodexAccount } from "./account.js";
|
|
11
|
+
import { CodexQuotaService } from "./quota.js";
|
|
12
|
+
import { mountWeb } from "./web.js";
|
|
13
|
+
import { selectionFromLegacy, selectionOf, } from "./capabilities.js";
|
|
14
|
+
import { fieldOf } from "./protocol.js";
|
|
15
|
+
import { CodexAdapter } from "./adapter.js";
|
|
16
|
+
import { connectCodex } from "./connection.js";
|
|
17
|
+
import { emptySnapshot } from "./cursor.js";
|
|
18
|
+
import { fetchCatalog } from "./models.js";
|
|
19
|
+
import { CodexSessionStore, cursorToRecord, recordToCursor, } from "./session-store.js";
|
|
20
|
+
import { prepareIsolation, verifyIsolation, } from "./isolation.js";
|
|
21
|
+
import { CodexTurn } from "./turn.js";
|
|
22
|
+
import { ThreadResult, TurnResult, TurnStartParams } from "./protocol.js";
|
|
23
|
+
export { Config } from "./config.js";
|
|
24
|
+
export { connectCodex, CodexConnection } from "./connection.js";
|
|
25
|
+
export { CodexAdapter } from "./adapter.js";
|
|
26
|
+
export * from "./protocol.js";
|
|
27
|
+
export { CodexQuotaService } from "./quota.js";
|
|
28
|
+
/** Cordis plugin identity. */
|
|
29
|
+
export const name = "kmh/codex-cli";
|
|
30
|
+
/** Required model, process, user-interaction and attachment services(审批桥与生图投影依赖)。 */
|
|
31
|
+
export const inject = [
|
|
32
|
+
"llm",
|
|
33
|
+
"subprocess",
|
|
34
|
+
"agents",
|
|
35
|
+
"approval",
|
|
36
|
+
"userQuestions",
|
|
37
|
+
"attachments",
|
|
38
|
+
"tools",
|
|
39
|
+
];
|
|
40
|
+
/** 读取持久化设置;缺失或损坏时按旧开关迁移(feat02 场景7)。 */
|
|
41
|
+
function loadSettings(config) {
|
|
42
|
+
try {
|
|
43
|
+
const text = readFileSync(join(config.dataDir, "codex-settings.json"), "utf8");
|
|
44
|
+
const parsed = JSON.parse(typeof text === "string" ? text : "");
|
|
45
|
+
const record = parsed === null || typeof parsed !== "object" ? undefined : parsed;
|
|
46
|
+
const selection = selectionOf(fieldOf(record, "selection"));
|
|
47
|
+
return { selection };
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return { selection: selectionFromLegacy(config.nativeToolsEnabled) };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export class CodexCli extends Service {
|
|
54
|
+
config;
|
|
55
|
+
catalogCache;
|
|
56
|
+
sessions = new Map();
|
|
57
|
+
/** 会话 → CLI 连接实时状态(状态小球轮询数据源)。 */
|
|
58
|
+
liveStates = new Map();
|
|
59
|
+
store;
|
|
60
|
+
/** 账号操作(状态/登录/取消/退出)。 */
|
|
61
|
+
account;
|
|
62
|
+
quota;
|
|
63
|
+
settingsNamespace;
|
|
64
|
+
/** 详情页可变设置;逐项选择立即保存、下一回合生效。 */
|
|
65
|
+
settings;
|
|
66
|
+
/** 由 profile 插件挂载的 Config 策略与执行守卫。 */
|
|
67
|
+
toolPolicy;
|
|
68
|
+
constructor(ctx, config) {
|
|
69
|
+
super(ctx, "codexCli");
|
|
70
|
+
this.config = config;
|
|
71
|
+
this.store = new CodexSessionStore(config.dataDir);
|
|
72
|
+
this.account = new CodexAccount(ctx, config);
|
|
73
|
+
this.quota = new CodexQuotaService(ctx, config);
|
|
74
|
+
this.settingsNamespace = ctx.fiber.entry?.options.id ?? null;
|
|
75
|
+
ctx.effect(() => () => this.quota.dispose(), "codex-cli: quota");
|
|
76
|
+
this.settings = loadSettings(config);
|
|
77
|
+
ctx.effect(() => () => {
|
|
78
|
+
for (const state of this.sessions.values())
|
|
79
|
+
state.turn.dispose().catch(() => undefined);
|
|
80
|
+
this.sessions.clear();
|
|
81
|
+
}, "codex-cli: sessions");
|
|
82
|
+
}
|
|
83
|
+
/** 本插件自报的工具开关清单;refresh 时重新发现原生目录(详情页选择器读取)。 */
|
|
84
|
+
toolSwitches(signal, refresh = false) {
|
|
85
|
+
return listToolSwitches(this, this.ctx, signal, refresh);
|
|
86
|
+
}
|
|
87
|
+
/** 切换一个开关并带修订号写入 profile 配置,返回新清单;只对普通新建会话生效。 */
|
|
88
|
+
setToolSwitch(update, signal) {
|
|
89
|
+
return applyToolSwitch(this, this.ctx, update, signal);
|
|
90
|
+
}
|
|
91
|
+
/** 保存逐项选择:原子落盘后立即生效于下一回合(进行中回合不受影响)。 */
|
|
92
|
+
async saveSelection(selection) {
|
|
93
|
+
const accepted = selectionOf(selection);
|
|
94
|
+
if (this.toolPolicy !== undefined) {
|
|
95
|
+
for (const key of [
|
|
96
|
+
"commandExecution",
|
|
97
|
+
"fileChange",
|
|
98
|
+
"viewImage",
|
|
99
|
+
"webSearch",
|
|
100
|
+
]) {
|
|
101
|
+
if (accepted[key] !== this.settings.selection[key])
|
|
102
|
+
throw new Error("CODEX_TOOLS_REQUIRE_PROFILE_CONFIG");
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
await mkdir(this.config.dataDir, { recursive: true, mode: 0o700 });
|
|
106
|
+
const file = join(this.config.dataDir, "codex-settings.json");
|
|
107
|
+
const temp = `${file}.tmp`;
|
|
108
|
+
const body = { selection: accepted };
|
|
109
|
+
await writeFile(temp, JSON.stringify(body));
|
|
110
|
+
await rename(temp, file);
|
|
111
|
+
this.settings.selection = accepted;
|
|
112
|
+
}
|
|
113
|
+
/** 解析请求会话的工作目录;查不到时回落插件配置 cwd。 */
|
|
114
|
+
resolveCwd(sessionId) {
|
|
115
|
+
if (sessionId === undefined)
|
|
116
|
+
return this.config.cwd;
|
|
117
|
+
const sessions = this.ctx.get("sessions");
|
|
118
|
+
const cwd = sessions?.get(sessionId)?.header?.cwd;
|
|
119
|
+
return cwd === undefined ? this.config.cwd : cwd;
|
|
120
|
+
}
|
|
121
|
+
/** 权限档回落:与 kmh-web 组合默认(workspace-write + ask)一致。 */
|
|
122
|
+
static DEFAULT_PERMISSION = {
|
|
123
|
+
sandbox: "workspace-write",
|
|
124
|
+
approval: "ask",
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* 读取会话所属沙箱与审批服务的生效权限;缺少会话或服务读取失败时使用
|
|
128
|
+
* workspace-write + ask。每次 start 重新读取,进行中回合保留开始时的档位。
|
|
129
|
+
*/
|
|
130
|
+
resolvePermission(sessionId) {
|
|
131
|
+
const fallback = CodexCli.DEFAULT_PERMISSION;
|
|
132
|
+
if (sessionId === undefined)
|
|
133
|
+
return fallback;
|
|
134
|
+
const sessions = this.ctx.get("sessions");
|
|
135
|
+
const session = sessions?.get(sessionId);
|
|
136
|
+
if (session === undefined)
|
|
137
|
+
return fallback;
|
|
138
|
+
try {
|
|
139
|
+
const sandboxPolicy = this.ctx.get("sandboxPolicy");
|
|
140
|
+
const approval = this.ctx.get("approval");
|
|
141
|
+
return {
|
|
142
|
+
sandbox: sandboxPolicy?.resolve({ session }).mode ?? fallback.sandbox,
|
|
143
|
+
approval: approval?.overrideOf(session) ??
|
|
144
|
+
approval?.config.policy ??
|
|
145
|
+
fallback.approval,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return fallback;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/** 模型目录缓存;每次调用复用在途请求。 */
|
|
153
|
+
catalog() {
|
|
154
|
+
this.catalogCache ??= (async () => {
|
|
155
|
+
const signal = AbortSignal.timeout(this.config.probeTimeoutMs);
|
|
156
|
+
const connection = await connectCodex(this.ctx, {
|
|
157
|
+
command: this.config.command,
|
|
158
|
+
cwd: this.config.cwd,
|
|
159
|
+
configOverrides: [],
|
|
160
|
+
env: this.config.env,
|
|
161
|
+
graceMs: this.config.graceMs,
|
|
162
|
+
startupTimeoutMs: this.config.startupTimeoutMs,
|
|
163
|
+
}, signal);
|
|
164
|
+
try {
|
|
165
|
+
const entries = await fetchCatalog(connection, signal);
|
|
166
|
+
const head = entries[0];
|
|
167
|
+
if (head !== undefined)
|
|
168
|
+
this.settings.defaultModel = head.id;
|
|
169
|
+
return entries;
|
|
170
|
+
}
|
|
171
|
+
finally {
|
|
172
|
+
await connection.stop(this.config.cleanupTimeoutMs);
|
|
173
|
+
}
|
|
174
|
+
})();
|
|
175
|
+
return this.catalogCache;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* 读取会话的持久化绑定记录。
|
|
179
|
+
* @param sessionKey - KMH 会话标识。
|
|
180
|
+
* @returns 独立记录副本;尚未创建时为空,保存文件损坏时抛错。
|
|
181
|
+
*/
|
|
182
|
+
async bindingRecord(sessionKey) {
|
|
183
|
+
return await this.store.get(sessionKey);
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* 读取分叉的源会话绑定。
|
|
187
|
+
* @param sessionId - KMH 会话标识。
|
|
188
|
+
* @returns 父会话记录;普通会话或父记录缺失时为空。
|
|
189
|
+
*/
|
|
190
|
+
async sourceBinding(sessionId) {
|
|
191
|
+
const parent = sessionId === undefined
|
|
192
|
+
? undefined
|
|
193
|
+
: this.ctx.get("sessions")?.get(sessionId)?.header.parentSession;
|
|
194
|
+
return parent === undefined ? undefined : this.store.get(parent);
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* 保存创建时工具信息;保留已经接受的原生编号和消息处理位置。
|
|
198
|
+
* @param sessionKey - KMH 会话标识。
|
|
199
|
+
* @param toolPolicy - 创建时的完整工具选择与目录。
|
|
200
|
+
*/
|
|
201
|
+
async saveToolPolicy(sessionKey, toolPolicy) {
|
|
202
|
+
const previous = await this.store.get(sessionKey);
|
|
203
|
+
await this.store.put(sessionKey, {
|
|
204
|
+
...previous,
|
|
205
|
+
fingerprints: previous?.fingerprints ?? [],
|
|
206
|
+
toolPolicy,
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* 持久化会话绑定并保留创建时的工具信息。
|
|
211
|
+
* @param sessionKey - KMH 会话标识。
|
|
212
|
+
* @param turn - 持有原生编号及消息处理位置的回合。
|
|
213
|
+
* @param inheritedTurns - 原生分叉实际继承的完成回合;缺省保留原记录。
|
|
214
|
+
*/
|
|
215
|
+
async recordBinding(sessionKey, turn, inheritedTurns) {
|
|
216
|
+
if (turn.threadId === undefined)
|
|
217
|
+
return;
|
|
218
|
+
const state = this.sessions.get(sessionKey);
|
|
219
|
+
if (state !== undefined)
|
|
220
|
+
state.threadId = turn.threadId;
|
|
221
|
+
const previous = await this.store.get(sessionKey);
|
|
222
|
+
const record = {
|
|
223
|
+
...previous,
|
|
224
|
+
...cursorToRecord(turn.threadId, turn.cursor, turn.lastCompletedTurnId),
|
|
225
|
+
};
|
|
226
|
+
const turns = inheritedTurns ?? previous?.turns ?? [];
|
|
227
|
+
record.turns = [...turns];
|
|
228
|
+
if (turn.lastCompletedTurnId !== undefined &&
|
|
229
|
+
record.turns.at(-1)?.turnId !== turn.lastCompletedTurnId) {
|
|
230
|
+
record.turns.push({
|
|
231
|
+
turnId: brandString(turn.lastCompletedTurnId),
|
|
232
|
+
fingerprints: [...turn.cursor.fingerprints],
|
|
233
|
+
delivered: [...turn.pendingDigests],
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
if (previous?.threadId !== undefined &&
|
|
237
|
+
previous.threadId !== turn.threadId) {
|
|
238
|
+
record.previousThreadIds = [
|
|
239
|
+
...(previous.previousThreadIds ?? []),
|
|
240
|
+
previous.threadId,
|
|
241
|
+
];
|
|
242
|
+
}
|
|
243
|
+
// 固定声明的名称对应关系随原绑定一起保存。
|
|
244
|
+
const registry = turn.toolRegistry;
|
|
245
|
+
if (registry !== undefined) {
|
|
246
|
+
record.toolFingerprint = registry.fingerprint;
|
|
247
|
+
record.toolMap = Object.fromEntries(registry.declaredToKmh);
|
|
248
|
+
record.toolsVersion =
|
|
249
|
+
previous !== undefined &&
|
|
250
|
+
previous.toolFingerprint === registry.fingerprint
|
|
251
|
+
? (previous.toolsVersion ?? 1)
|
|
252
|
+
: (previous?.toolsVersion ?? 0) + 1;
|
|
253
|
+
}
|
|
254
|
+
await this.store.put(sessionKey, record);
|
|
255
|
+
}
|
|
256
|
+
/** 恢复会话 turn 的差分游标(进程重启后续聊不重复投递)。 */
|
|
257
|
+
async restoreCursor(sessionKey, turn) {
|
|
258
|
+
const record = await this.store.get(sessionKey);
|
|
259
|
+
if (record === undefined)
|
|
260
|
+
return;
|
|
261
|
+
turn.cursor = recordToCursor(record);
|
|
262
|
+
turn.lastCompletedTurnId = record.lastTurnId;
|
|
263
|
+
// 待核对队列种子:上一流尾已写入绑定,此处回读幂等;新块随流追加。
|
|
264
|
+
turn.pendingDigests = [...turn.cursor.delivered];
|
|
265
|
+
const state = this.sessions.get(sessionKey);
|
|
266
|
+
if (state !== undefined)
|
|
267
|
+
state.threadId = record.threadId;
|
|
268
|
+
}
|
|
269
|
+
/** 会话终止后释放其 turn 归属。 */
|
|
270
|
+
releaseSession(turn) {
|
|
271
|
+
for (const [key, state] of this.sessions)
|
|
272
|
+
if (state.turn === turn) {
|
|
273
|
+
this.sessions.delete(key);
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
/** 记录会话的 CLI 连接实时状态(小球数据源)。 */
|
|
278
|
+
markLive(sessionKey, state) {
|
|
279
|
+
this.liveStates.set(sessionKey, {
|
|
280
|
+
retrying: false,
|
|
281
|
+
...state,
|
|
282
|
+
updatedAt: Date.now(),
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* 全部会话的实时状态快照(/api/codex-cli/live 返回体)。
|
|
287
|
+
* 空闲但 turn 仍挂起工具回执属正常步间状态(KMH 执行完工具会续推),
|
|
288
|
+
* 重试期间红色状态携带原因;停止或完成后 streaming 为 false。
|
|
289
|
+
*/
|
|
290
|
+
liveSnapshot() {
|
|
291
|
+
return {
|
|
292
|
+
sessions: [...this.liveStates].map(([key, state]) => ({
|
|
293
|
+
...state,
|
|
294
|
+
sessionId: key,
|
|
295
|
+
})),
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* 会话内串行执行:同一会话的 turn 操作排队,共用同一 CodexTurn。
|
|
300
|
+
* @param sessionKey - 会话标识。
|
|
301
|
+
* @param cwd - 会话工作目录。
|
|
302
|
+
* @param run - 本次要执行的流式驱动。
|
|
303
|
+
* @param signal - 排队等待的取消与超时信号。
|
|
304
|
+
*/
|
|
305
|
+
async *withSession(sessionKey, cwd, run, signal) {
|
|
306
|
+
const state = this.stateOf(sessionKey, cwd);
|
|
307
|
+
const previous = state.chain;
|
|
308
|
+
let drained = false;
|
|
309
|
+
let failure;
|
|
310
|
+
let done;
|
|
311
|
+
state.chain = new Promise((resolve) => {
|
|
312
|
+
done = resolve;
|
|
313
|
+
});
|
|
314
|
+
try {
|
|
315
|
+
await waitForSession(previous, signal);
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
318
|
+
// 排队取消后,后继请求仍须等待当前拥有者交还执行权。
|
|
319
|
+
previous.then(() => done?.(), () => done?.());
|
|
320
|
+
throw error;
|
|
321
|
+
}
|
|
322
|
+
try {
|
|
323
|
+
await this.restoreCursor(sessionKey, state.turn);
|
|
324
|
+
this.markLive(sessionKey, {
|
|
325
|
+
color: "green",
|
|
326
|
+
streaming: true,
|
|
327
|
+
detail: "CLI 通信中",
|
|
328
|
+
});
|
|
329
|
+
for await (const chunk of run(state.turn))
|
|
330
|
+
yield chunk;
|
|
331
|
+
drained = true;
|
|
332
|
+
}
|
|
333
|
+
catch (error) {
|
|
334
|
+
failure = error;
|
|
335
|
+
// 停止/失败链路:先发 turn/interrupt 并有界等待终止通知,再回收。
|
|
336
|
+
// interrupt 正常返回=CLI 确认停止;超时/失败=停止未确认。
|
|
337
|
+
let confirmed = false;
|
|
338
|
+
await state.turn
|
|
339
|
+
.interrupt(AbortSignal.timeout(this.config.cancelReceiptTimeoutMs))
|
|
340
|
+
.then(() => {
|
|
341
|
+
confirmed = true;
|
|
342
|
+
}, () => undefined);
|
|
343
|
+
const aborted = isCancelCause(error);
|
|
344
|
+
if (confirmed && aborted) {
|
|
345
|
+
state.turn.cursor.delivered = [...state.turn.pendingDigests];
|
|
346
|
+
await this.recordBinding(sessionKey, state.turn);
|
|
347
|
+
}
|
|
348
|
+
const reason = error instanceof Error && error.name === "TimeoutError"
|
|
349
|
+
? `CODEX_REQUEST_TIMEOUT: ${this.config.requestTimeoutMs}ms`
|
|
350
|
+
: error instanceof Error
|
|
351
|
+
? error.message
|
|
352
|
+
: String(error);
|
|
353
|
+
this.markLive(sessionKey, {
|
|
354
|
+
color: confirmed && aborted ? "gray" : "red",
|
|
355
|
+
streaming: false,
|
|
356
|
+
detail: aborted
|
|
357
|
+
? confirmed
|
|
358
|
+
? "已停止:CLI 确认中断,进程已回收"
|
|
359
|
+
: `停止未确认:CLI 未确认中断(${reason.slice(0, 120)})`
|
|
360
|
+
: `回合异常中断:${reason.slice(0, 120)}`,
|
|
361
|
+
});
|
|
362
|
+
await state.turn.dispose().catch(() => undefined);
|
|
363
|
+
}
|
|
364
|
+
finally {
|
|
365
|
+
try {
|
|
366
|
+
// 消费方提前 return 时,中断仍在产出的 turn 后再交还会话执行权。
|
|
367
|
+
if (!drained && failure === undefined) {
|
|
368
|
+
let confirmed = false;
|
|
369
|
+
await state.turn
|
|
370
|
+
.interrupt(AbortSignal.timeout(this.config.cancelReceiptTimeoutMs))
|
|
371
|
+
.then(() => {
|
|
372
|
+
confirmed = true;
|
|
373
|
+
}, () => undefined);
|
|
374
|
+
if (confirmed) {
|
|
375
|
+
state.turn.cursor.delivered = [...state.turn.pendingDigests];
|
|
376
|
+
await this.recordBinding(sessionKey, state.turn);
|
|
377
|
+
}
|
|
378
|
+
await state.turn.dispose().catch(() => undefined);
|
|
379
|
+
this.markLive(sessionKey, {
|
|
380
|
+
color: confirmed ? "gray" : "red",
|
|
381
|
+
streaming: false,
|
|
382
|
+
detail: confirmed
|
|
383
|
+
? "输出消费已结束:CLI 确认停止"
|
|
384
|
+
: "输出消费已结束:CLI 停止未确认",
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
finally {
|
|
389
|
+
done?.();
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
if (failure !== undefined) {
|
|
393
|
+
if (failure instanceof Error)
|
|
394
|
+
throw failure;
|
|
395
|
+
throw new Error("CODEX_SESSION_FAILED", { cause: failure });
|
|
396
|
+
}
|
|
397
|
+
this.markLive(sessionKey, {
|
|
398
|
+
color: state.turn.terminated ? "gray" : "green",
|
|
399
|
+
streaming: false,
|
|
400
|
+
detail: state.turn.terminated
|
|
401
|
+
? "已停止:回合已终止,进程已回收"
|
|
402
|
+
: "已连接:CLI 进程在线,随时续聊",
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
/** 取或建会话状态;已终止的 turn 重建以复用绑定。 */
|
|
406
|
+
stateOf(sessionKey, cwd) {
|
|
407
|
+
let state = this.sessions.get(sessionKey);
|
|
408
|
+
if (state === undefined || state.turn.terminated) {
|
|
409
|
+
const threadId = state?.threadId;
|
|
410
|
+
// 替换已终止的 turn 时同步回收其连接与进程:不 dispose 会让它带着
|
|
411
|
+
// 未回执的工具请求滞留(线上实测泄漏进程干等数分钟后被 Codex 侧
|
|
412
|
+
// 超时中断)。dispose 幂等,正常路径已回收时无副作用。
|
|
413
|
+
if (state !== undefined)
|
|
414
|
+
void state.turn.dispose().catch(() => undefined);
|
|
415
|
+
state = {
|
|
416
|
+
turn: new CodexTurn(this.ctx, this.config, cwd, [], (retrying, detail) => {
|
|
417
|
+
this.markLive(sessionKey, {
|
|
418
|
+
color: retrying ? "red" : "green",
|
|
419
|
+
streaming: true,
|
|
420
|
+
retrying,
|
|
421
|
+
detail,
|
|
422
|
+
});
|
|
423
|
+
}),
|
|
424
|
+
threadId,
|
|
425
|
+
chain: Promise.resolve(),
|
|
426
|
+
};
|
|
427
|
+
this.sessions.set(sessionKey, state);
|
|
428
|
+
}
|
|
429
|
+
return state;
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* 辅助请求(标题生成、压缩评估):独立临时会话,完成后回收。
|
|
433
|
+
* 业务 thread 绑定与历史不受影响。
|
|
434
|
+
*/
|
|
435
|
+
async *streamAuxiliary(options) {
|
|
436
|
+
const signal = options.signal ?? new AbortController().signal;
|
|
437
|
+
const plan = await prepareIsolation(this.ctx, this.config, {
|
|
438
|
+
cwd: this.config.cwd,
|
|
439
|
+
signal,
|
|
440
|
+
selection: this.settings.selection,
|
|
441
|
+
});
|
|
442
|
+
const connection = await connectCodex(this.ctx, {
|
|
443
|
+
command: this.config.command,
|
|
444
|
+
cwd: this.config.cwd,
|
|
445
|
+
configOverrides: plan.configOverrides,
|
|
446
|
+
env: this.config.env,
|
|
447
|
+
graceMs: this.config.graceMs,
|
|
448
|
+
startupTimeoutMs: this.config.startupTimeoutMs,
|
|
449
|
+
}, signal);
|
|
450
|
+
const turn = new CodexTurn(this.ctx, this.config, this.config.cwd);
|
|
451
|
+
turn.adopt(connection);
|
|
452
|
+
try {
|
|
453
|
+
await verifyIsolation(connection, plan, signal);
|
|
454
|
+
const ephemeral = await connection.request("thread/start", {
|
|
455
|
+
model: options.model,
|
|
456
|
+
ephemeral: true,
|
|
457
|
+
cwd: this.config.cwd,
|
|
458
|
+
baseInstructions: options.system,
|
|
459
|
+
dynamicTools: [],
|
|
460
|
+
}, signal);
|
|
461
|
+
const threadId = ThreadResult.parse(ephemeral).thread.id;
|
|
462
|
+
const texts = [];
|
|
463
|
+
for (const message of options.messages)
|
|
464
|
+
if (message.role === "user")
|
|
465
|
+
for (const block of message.content ?? [])
|
|
466
|
+
if (block.type === "text")
|
|
467
|
+
texts.push(block.text);
|
|
468
|
+
const turnResult = await connection.request("turn/start", TurnStartParams.parse({
|
|
469
|
+
threadId,
|
|
470
|
+
input: [{ type: "text", text: texts.join("\n") || "ping" }],
|
|
471
|
+
model: options.model,
|
|
472
|
+
effort: options.reasoningEffort,
|
|
473
|
+
summary: this.config.reasoningSummary,
|
|
474
|
+
}), signal);
|
|
475
|
+
turn.setIds(threadId, TurnResult.parse(turnResult).turn.id);
|
|
476
|
+
yield* turn.pump(signal);
|
|
477
|
+
}
|
|
478
|
+
finally {
|
|
479
|
+
await turn.dispose();
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
/** 等待会话执行权;取消只结束排队者的等待。 */
|
|
484
|
+
async function waitForSession(previous, signal) {
|
|
485
|
+
if (signal === undefined)
|
|
486
|
+
return await previous;
|
|
487
|
+
signal.throwIfAborted();
|
|
488
|
+
let listener;
|
|
489
|
+
try {
|
|
490
|
+
await Promise.race([
|
|
491
|
+
previous,
|
|
492
|
+
new Promise((_resolve, reject) => {
|
|
493
|
+
listener = addAbortListener(signal, () => {
|
|
494
|
+
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- DSH 以 AgentCancelCause 对象传递停止原因。
|
|
495
|
+
reject(signal.reason);
|
|
496
|
+
});
|
|
497
|
+
}),
|
|
498
|
+
]);
|
|
499
|
+
signal.throwIfAborted();
|
|
500
|
+
}
|
|
501
|
+
finally {
|
|
502
|
+
listener?.[Symbol.dispose]();
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* 是否宿主主动取消(DSH AgentCancelCause 为普通对象经 signal.reason 抛出,
|
|
507
|
+
* 形态见 dsh-session types;AbortError 也算)。用户/宿主停止且 CLI 确认中
|
|
508
|
+
* 断属正常停止(灰球),其余失败按异常(红球)。
|
|
509
|
+
*/
|
|
510
|
+
function isCancelCause(error) {
|
|
511
|
+
if (error instanceof Error)
|
|
512
|
+
return error.name === "AbortError";
|
|
513
|
+
if (error === null || typeof error !== "object")
|
|
514
|
+
return false;
|
|
515
|
+
const kind = error.kind;
|
|
516
|
+
return (kind === "user" ||
|
|
517
|
+
kind === "parent" ||
|
|
518
|
+
kind === "hook" ||
|
|
519
|
+
kind === "disposed");
|
|
520
|
+
}
|
|
521
|
+
/** 空游标导出(临时会话与测试用)。 */
|
|
522
|
+
export { emptySnapshot };
|
|
523
|
+
/**
|
|
524
|
+
* Register the provider runtime and adapter routes.
|
|
525
|
+
* @param ctx - Plugin owner of the runtime and process ranges.
|
|
526
|
+
* @param config - Validated execution and storage settings.
|
|
527
|
+
*/
|
|
528
|
+
export function apply(ctx, config) {
|
|
529
|
+
const runtime = new CodexCli(ctx, config);
|
|
530
|
+
ctx.codexCli = runtime;
|
|
531
|
+
runtime.toolPolicy = new CodexToolPolicy(ctx, runtime);
|
|
532
|
+
ctx.llm.registerAdapter(["codex-cli"], new CodexAdapter(runtime));
|
|
533
|
+
ctx.inject(["connection"], (web) => mountWeb(web, runtime));
|
|
534
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** 工具与技能隔离:允许清单式裁剪模型目录、按选择关闭原生能力、生成进程 -c 覆盖。 */
|
|
2
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
3
|
+
import type { Config } from "./config.ts";
|
|
4
|
+
import { type NativeSelection } from "./capabilities.ts";
|
|
5
|
+
import { type CodexConnection } from "./connection.ts";
|
|
6
|
+
/** 隔离准备结果:-c 覆盖数组与裁剪目录路径。 */
|
|
7
|
+
export interface IsolationPlan {
|
|
8
|
+
configOverrides: string[];
|
|
9
|
+
catalogPath: string;
|
|
10
|
+
/** 本轮发现并关闭的原生技能路径。 */
|
|
11
|
+
disabledSkills: string[];
|
|
12
|
+
}
|
|
13
|
+
/** KMH 会话权限旋钮;工作区免人工询问档对应 Codex 自动审查。 */
|
|
14
|
+
export interface PermissionKnobs {
|
|
15
|
+
/** 官方沙箱档:read-only / workspace-write / danger-full-access。 */
|
|
16
|
+
sandbox: string;
|
|
17
|
+
/** KMH 审批策略:ask 交用户决定;never 自动拒绝宿主审批请求。 */
|
|
18
|
+
approval: "ask" | "never";
|
|
19
|
+
}
|
|
20
|
+
/** 隔离输入。 */
|
|
21
|
+
export interface IsolationInput {
|
|
22
|
+
cwd: string;
|
|
23
|
+
signal: AbortSignal;
|
|
24
|
+
/** 逐项选择覆盖;缺省按部署旧开关迁移。 */
|
|
25
|
+
selection?: NativeSelection | undefined;
|
|
26
|
+
/** 权限档(D17):选中执行类原生工具时映射为 -c 沙箱/审批参数。 */
|
|
27
|
+
permission?: PermissionKnobs | undefined;
|
|
28
|
+
/** 专用生图调用额外关闭用户 MCP 与插件;普通会话沿用原选择。 */
|
|
29
|
+
imageOnly?: boolean;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* 按选择计算每模型裁剪字段(允许清单:基础 + 未开放项的追加)。
|
|
33
|
+
* @param selection - 逐项选择。
|
|
34
|
+
* @returns 将覆盖到目录每个模型上的字段表。
|
|
35
|
+
*/
|
|
36
|
+
export declare function prunedFieldsFor(selection: NativeSelection): Record<string, unknown>;
|
|
37
|
+
/**
|
|
38
|
+
* 按选择计算功能关闭集合(基础始终关闭 + 未开放项的条件关闭)。
|
|
39
|
+
* @param selection - 逐项选择。
|
|
40
|
+
* @returns 将注入 `features.<名>=false` 的功能名列表。
|
|
41
|
+
*/
|
|
42
|
+
export declare function featureOffFor(selection: NativeSelection): string[];
|
|
43
|
+
/**
|
|
44
|
+
* 生成隔离计划(允许清单式):基础隔离始终保留,未选择的项维持关闭、
|
|
45
|
+
* 选中的项开放(目录字段与功能开关按项条件注入),改写 vendored 目录
|
|
46
|
+
* 为裁剪目录并落盘,汇总全部 -c 覆盖。
|
|
47
|
+
* @param ctx - 宿主上下文。
|
|
48
|
+
* @param config - 插件配置;selection 未提供时按旧开关迁移。
|
|
49
|
+
* @param input - 会话工作目录、选择与中止信号。
|
|
50
|
+
* @returns 进程启动参数所需的覆盖数组。
|
|
51
|
+
* @throws CODEX_CATALOG_PRUNE_FAILED 目录读取或改写失败。
|
|
52
|
+
*/
|
|
53
|
+
export declare function prepareIsolation(ctx: Context, config: Config, input: IsolationInput): Promise<IsolationPlan>;
|
|
54
|
+
/**
|
|
55
|
+
* 隔离生效核对:正式进程目录必须来自裁剪文件。
|
|
56
|
+
* @param connection - 已带隔离覆盖启动的连接。
|
|
57
|
+
* @param plan - 本次隔离计划。
|
|
58
|
+
* @param signal - 中止信号。
|
|
59
|
+
* @throws CODEX_ISOLATION_FAILED 目录与裁剪文件不一致。
|
|
60
|
+
*/
|
|
61
|
+
export declare function verifyIsolation(connection: CodexConnection, plan: IsolationPlan, signal: AbortSignal): Promise<void>;
|