@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/turn.js
ADDED
|
@@ -0,0 +1,1012 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { addAbortListener } from "node:events";
|
|
3
|
+
import { offloadedImageText, ToolCallId, } from "@deepseek-ai/dsh-llm";
|
|
4
|
+
import { connectCodex } from "./connection.js";
|
|
5
|
+
import { AgentMessageDeltaParams, CommandExecutionOutputDeltaParams, DynamicToolCallParams, DynamicToolCallResponse, ErrorNotificationParams, Incoming, ItemEventParams, KMH_TOOL_NAMESPACE, McpToolCallProgressParams, ReasoningDeltaParams, ThreadResult, ThreadForkParams, TokenUsageParams, TurnCompletedParams, TurnDiffUpdatedParams, TurnResult, TurnStartParams, TurnSteerParams, TurnSteerResult, imageProjectionOf, reasoningItemText, } from "./protocol.js";
|
|
6
|
+
import { prepareIsolation, verifyIsolation, } from "./isolation.js";
|
|
7
|
+
import { blockDigest, emptySnapshot, } from "./cursor.js";
|
|
8
|
+
import { buildToolRegistry, resolveKmhToolName, } from "./tool-registry.js";
|
|
9
|
+
import { CodexApprovalBridge } from "./approval.js";
|
|
10
|
+
import { NATIVE_DIFF_NOTE_ID, NATIVE_NOTE_LIMIT, NATIVE_TRUNCATED_NOTE, NATIVE_UNSETTLED_NOTE, diffBudgetAccepts, diffSummaryLineOf, nativeCompletionNoteOf, nativeHeaderOf, newDiffBudget, newNoteBudget, } from "./native-items.js";
|
|
11
|
+
import { imageFailureNote, imageSizeNote, imageSizeRequirementOf, pngSizeOf, } from "./image-delivery.js";
|
|
12
|
+
import { fieldOf } from "./protocol.js";
|
|
13
|
+
/**
|
|
14
|
+
* 管理一个 KMH 回合内的 CLI 进程与 Codex turn。
|
|
15
|
+
* 工具请求到达时挂起 Codex(延迟回执),由 adapter 在下一次 stream 调用回传结果续推;
|
|
16
|
+
* turn 终止后连接与进程回收。
|
|
17
|
+
*/
|
|
18
|
+
export class CodexTurn {
|
|
19
|
+
ctx;
|
|
20
|
+
config;
|
|
21
|
+
cwd;
|
|
22
|
+
extraOverrides;
|
|
23
|
+
onConnectionState;
|
|
24
|
+
connection;
|
|
25
|
+
queue = [];
|
|
26
|
+
wakeup;
|
|
27
|
+
closed = false;
|
|
28
|
+
itemIndex = new Map();
|
|
29
|
+
nextIndex = 0;
|
|
30
|
+
pending = new Map();
|
|
31
|
+
/** 已投影为会话图片块的生图项 id:防重复投影。 */
|
|
32
|
+
projectedImages = new Set();
|
|
33
|
+
/** 文本/推理块的类型与 delta 累积(摘要补算用),按流块索引。 */
|
|
34
|
+
blockTypes = new Map();
|
|
35
|
+
blockText = new Map();
|
|
36
|
+
endedBlocks = new Set();
|
|
37
|
+
/** 已开块索引;同一 item 的后续 delta 沿用现有块及累积文本。 */
|
|
38
|
+
openBlocks = new Set();
|
|
39
|
+
threadId;
|
|
40
|
+
turnId;
|
|
41
|
+
/** 最近一次完成(含 interrupted)的 turn id;fork 重建的边界。 */
|
|
42
|
+
lastCompletedTurnId;
|
|
43
|
+
/** 差分游标:已投递到 Codex thread 的对齐点。 */
|
|
44
|
+
cursor = emptySnapshot();
|
|
45
|
+
/**
|
|
46
|
+
* 待核对回合块摘要队列:本 turn 投影的块入队(block-end 时),差分
|
|
47
|
+
* 消费历史中的 assistant 消息时出队。adapter 在每次差分后把它对账为
|
|
48
|
+
* 游标返回的剩余队列,再随快照持久化(见 cursor.ts 注释)。
|
|
49
|
+
*/
|
|
50
|
+
pendingDigests = [];
|
|
51
|
+
/** 回合终止状态;completed 或 interrupted 后进程可回收。 */
|
|
52
|
+
terminalStatus;
|
|
53
|
+
/** 最近一次投递的用户输入文本:生图尺寸要求识别来源(feat10)。 */
|
|
54
|
+
lastUserText = "";
|
|
55
|
+
/** 会话标识:审批桥取活跃 Agent 用。 */
|
|
56
|
+
sessionId;
|
|
57
|
+
/** 回合级审批中止:dispose/interrupt 时待审批决定随回合取消(feat06 场景1)。 */
|
|
58
|
+
approvalAbort;
|
|
59
|
+
/** 原生叙述账目(feat08 v1):按 item 的体积与收尾状态;reopen 重置。 */
|
|
60
|
+
nativeNotes = new Map();
|
|
61
|
+
/** turn 级 diff 叙述账目。 */
|
|
62
|
+
diffBudget = newDiffBudget();
|
|
63
|
+
/**
|
|
64
|
+
* 本回合的工具声明表(D13):声明名 kmh-<原名> 与目录指纹。
|
|
65
|
+
* start/rebuild 时建立;临时会话(adopt)保持 undefined,仅兼容裸名。
|
|
66
|
+
*/
|
|
67
|
+
toolRegistry;
|
|
68
|
+
/**
|
|
69
|
+
* 未上报的逐响应用量样本队列(token 用量):Codex 每次上游响应完成发
|
|
70
|
+
* 一条 thread/tokenUsage/updated(last=该响应用量),turn/completed 不带
|
|
71
|
+
* 用量;KMH 要求每个 step 的 assistant 消息都有样本(缺一则整轮不显示),
|
|
72
|
+
* 且首个样本常在本侧 yield 工具挂起之后才到达——队列 + finish 时消费
|
|
73
|
+
* (空则补零样本)使各样本之和恒等于回合总量,与到达时序解耦。
|
|
74
|
+
*/
|
|
75
|
+
usageQueue = [];
|
|
76
|
+
constructor(ctx, config, cwd,
|
|
77
|
+
/** 调用方在隔离覆盖之上追加的进程配置(测试 fixture 等)。 */
|
|
78
|
+
extraOverrides = [],
|
|
79
|
+
/** 官方重试通知及恢复输出时的连接状态。 */
|
|
80
|
+
onConnectionState) {
|
|
81
|
+
this.ctx = ctx;
|
|
82
|
+
this.config = config;
|
|
83
|
+
this.cwd = cwd;
|
|
84
|
+
this.extraOverrides = extraOverrides;
|
|
85
|
+
this.onConnectionState = onConnectionState;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* 重启已回收的 turn 对象:复位关闭与终止标志并清空残留事件。
|
|
89
|
+
* start/rebuild 会复用本对象重新拉起进程;此前若经 dispose 回收,
|
|
90
|
+
* closed 标志会让 push 静默丢弃全部事件(恢复路径实测挂死于此)。
|
|
91
|
+
*/
|
|
92
|
+
reopen() {
|
|
93
|
+
this.closed = false;
|
|
94
|
+
this.terminalStatus = undefined;
|
|
95
|
+
this.queue = [];
|
|
96
|
+
this.itemIndex.clear();
|
|
97
|
+
this.nextIndex = 0;
|
|
98
|
+
this.pending.clear();
|
|
99
|
+
this.wakeup = undefined;
|
|
100
|
+
this.pendingDigests = [];
|
|
101
|
+
this.blockTypes.clear();
|
|
102
|
+
this.blockText.clear();
|
|
103
|
+
this.endedBlocks.clear();
|
|
104
|
+
this.openBlocks.clear();
|
|
105
|
+
this.lastUserText = "";
|
|
106
|
+
this.toolRegistry = undefined;
|
|
107
|
+
this.approvalAbort = undefined;
|
|
108
|
+
this.nativeNotes.clear();
|
|
109
|
+
this.diffBudget = newDiffBudget();
|
|
110
|
+
this.usageQueue.length = 0;
|
|
111
|
+
}
|
|
112
|
+
/** 等待结果回传的挂起工具调用标识。 */
|
|
113
|
+
pendingCallIds() {
|
|
114
|
+
return [...this.pending.keys()];
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* 消费一条未上报用量样本;队列空时补零样本(该步样本尚未到达或本轮
|
|
118
|
+
* 无上游响应)。晚到样本留给下一步,各步样本之和仍等于回合总量。
|
|
119
|
+
*/
|
|
120
|
+
consumeUsageSample() {
|
|
121
|
+
return (this.usageQueue.shift() ?? {
|
|
122
|
+
inputTokens: 0,
|
|
123
|
+
outputTokens: 0,
|
|
124
|
+
totalTokens: 0,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* 回合终局消费:合并队列全部剩余样本为一个(KMH 消费端只认最后一条
|
|
129
|
+
* usage chunk,逐条发会被覆盖;样本不相交,逐字段求和保持口径一致)。
|
|
130
|
+
* 队列空时补零样本,保证终局步也有样本。
|
|
131
|
+
*/
|
|
132
|
+
consumeUsageTotal() {
|
|
133
|
+
const merged = this.consumeUsageSample();
|
|
134
|
+
merged.totalTokens = merged.totalTokens ?? 0;
|
|
135
|
+
while (this.usageQueue.length > 0) {
|
|
136
|
+
const next = this.usageQueue.shift();
|
|
137
|
+
if (next === undefined)
|
|
138
|
+
break;
|
|
139
|
+
merged.inputTokens += next.inputTokens;
|
|
140
|
+
merged.outputTokens += next.outputTokens;
|
|
141
|
+
merged.totalTokens += next.totalTokens ?? 0;
|
|
142
|
+
merged.cacheReadTokens =
|
|
143
|
+
(merged.cacheReadTokens ?? 0) + (next.cacheReadTokens ?? 0);
|
|
144
|
+
merged.cacheWriteTokens =
|
|
145
|
+
(merged.cacheWriteTokens ?? 0) + (next.cacheWriteTokens ?? 0);
|
|
146
|
+
if (next.reasoningTokens !== undefined)
|
|
147
|
+
merged.reasoningTokens =
|
|
148
|
+
(merged.reasoningTokens ?? 0) + next.reasoningTokens;
|
|
149
|
+
}
|
|
150
|
+
return merged;
|
|
151
|
+
}
|
|
152
|
+
/** 是否已经终止(进程应回收)。 */
|
|
153
|
+
get terminated() {
|
|
154
|
+
return this.terminalStatus !== undefined || this.closed;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* 启动进程与 turn:隔离准备、连接、thread 创建或恢复、turn/start。
|
|
158
|
+
* @param input - 用户输入、模型与工具目录。
|
|
159
|
+
* @param threadId - 已有绑定的 thread;缺省时创建新 thread。
|
|
160
|
+
* @param signal - 取消信号。
|
|
161
|
+
* @param onBound - 收到编号后、发送任务前等待的保存操作;失败时停止发送。
|
|
162
|
+
* @returns 新建或恢复后的 threadId。
|
|
163
|
+
*/
|
|
164
|
+
async start(input, threadId, signal, onBound) {
|
|
165
|
+
const content = await this.encodeInput(input.content, signal);
|
|
166
|
+
this.reopen();
|
|
167
|
+
this.lastUserText = content
|
|
168
|
+
.flatMap((block) => (block.type === "text" ? [block.text] : []))
|
|
169
|
+
.join("\n");
|
|
170
|
+
this.sessionId = input.sessionId;
|
|
171
|
+
this.approvalAbort = new AbortController();
|
|
172
|
+
const plan = await prepareIsolation(this.ctx, this.config, {
|
|
173
|
+
cwd: this.cwd,
|
|
174
|
+
signal,
|
|
175
|
+
selection: input.selection,
|
|
176
|
+
permission: input.permission,
|
|
177
|
+
});
|
|
178
|
+
const connection = await connectCodex(this.ctx, {
|
|
179
|
+
command: this.config.command,
|
|
180
|
+
cwd: this.cwd,
|
|
181
|
+
configOverrides: [...plan.configOverrides, ...this.extraOverrides],
|
|
182
|
+
env: this.config.env,
|
|
183
|
+
graceMs: this.config.graceMs,
|
|
184
|
+
startupTimeoutMs: this.config.startupTimeoutMs,
|
|
185
|
+
}, signal);
|
|
186
|
+
this.connection = connection;
|
|
187
|
+
this.installHandlers();
|
|
188
|
+
await verifyIsolation(connection, plan, signal);
|
|
189
|
+
// D13:统一 kmh- 前缀声明(含范围与碰撞校验),回执按声明表解析。
|
|
190
|
+
const registry = buildToolRegistry(input.tools, input.policyFingerprint);
|
|
191
|
+
this.toolRegistry = registry;
|
|
192
|
+
if (threadId === undefined) {
|
|
193
|
+
const raw = await connection.request("thread/start", {
|
|
194
|
+
model: input.model,
|
|
195
|
+
experimentalRawEvents: true,
|
|
196
|
+
cwd: this.cwd,
|
|
197
|
+
baseInstructions: input.baseInstructions,
|
|
198
|
+
developerInstructions: input.developerInstructions,
|
|
199
|
+
// 平铺 legacy 声明:canonical namespace 的模型侧名称为无点拼接
|
|
200
|
+
// (kmh+name),不适合人读与防撞,沿用已验证的平铺真名形态。
|
|
201
|
+
dynamicTools: input.tools.map((tool) => ({
|
|
202
|
+
name: registry.kmhToDeclared.get(tool.name),
|
|
203
|
+
description: tool.description,
|
|
204
|
+
inputSchema: tool.inputSchema,
|
|
205
|
+
})),
|
|
206
|
+
}, signal);
|
|
207
|
+
this.threadId = ThreadResult.parse(raw).thread.id;
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
// 旧 thread 以其建立时的声明续用:当前目录的裸名经兼容路径解析。
|
|
211
|
+
const raw = await connection.request("thread/resume", { threadId }, signal);
|
|
212
|
+
this.threadId = ThreadResult.parse(raw).thread.id;
|
|
213
|
+
if (this.threadId !== threadId)
|
|
214
|
+
throw new Error("CODEX_SESSION_ID_MISMATCH");
|
|
215
|
+
}
|
|
216
|
+
await onBound?.(this.threadId);
|
|
217
|
+
const turn = await connection.request("turn/start", TurnStartParams.parse({
|
|
218
|
+
threadId: this.threadId,
|
|
219
|
+
input: content,
|
|
220
|
+
model: input.model,
|
|
221
|
+
effort: input.reasoningEffort,
|
|
222
|
+
summary: this.config.reasoningSummary,
|
|
223
|
+
}), signal);
|
|
224
|
+
this.turnId = TurnResult.parse(turn).turn.id;
|
|
225
|
+
return this.threadId;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* 原生分叉继承已选位置的历史,仅提交新增输入;失败保留源会话。
|
|
229
|
+
* @param input - 新增或编辑后的输入、源会话工具与本次模型和权限选择。
|
|
230
|
+
* @param source - 原生父会话及完成回合前后的位置。
|
|
231
|
+
* @param signal - 取消信号。
|
|
232
|
+
* @param onBound - 新编号保存操作;发送输入前等待完成。
|
|
233
|
+
* @returns 原生分叉创建的会话编号。
|
|
234
|
+
*/
|
|
235
|
+
async rebuild(input, source, signal, onBound) {
|
|
236
|
+
const content = await this.encodeInput(input.content, signal);
|
|
237
|
+
this.reopen();
|
|
238
|
+
this.lastUserText = content
|
|
239
|
+
.flatMap((block) => (block.type === "text" ? [block.text] : []))
|
|
240
|
+
.join("\n");
|
|
241
|
+
this.sessionId = input.sessionId;
|
|
242
|
+
this.approvalAbort = new AbortController();
|
|
243
|
+
const plan = await prepareIsolation(this.ctx, this.config, {
|
|
244
|
+
cwd: this.cwd,
|
|
245
|
+
signal,
|
|
246
|
+
selection: input.selection,
|
|
247
|
+
permission: input.permission,
|
|
248
|
+
});
|
|
249
|
+
const connection = await connectCodex(this.ctx, {
|
|
250
|
+
command: this.config.command,
|
|
251
|
+
cwd: this.cwd,
|
|
252
|
+
configOverrides: [...plan.configOverrides, ...this.extraOverrides],
|
|
253
|
+
env: this.config.env,
|
|
254
|
+
graceMs: this.config.graceMs,
|
|
255
|
+
startupTimeoutMs: this.config.startupTimeoutMs,
|
|
256
|
+
}, signal);
|
|
257
|
+
this.connection = connection;
|
|
258
|
+
this.installHandlers();
|
|
259
|
+
await verifyIsolation(connection, plan, signal);
|
|
260
|
+
const registry = buildToolRegistry(input.tools, input.policyFingerprint);
|
|
261
|
+
this.toolRegistry = registry;
|
|
262
|
+
const params = ThreadForkParams.parse(source);
|
|
263
|
+
const raw = await connection.request("thread/fork", params, signal);
|
|
264
|
+
this.threadId = ThreadResult.parse(raw).thread.id;
|
|
265
|
+
if (this.threadId === source.threadId)
|
|
266
|
+
throw new Error("CODEX_FORK_ID_MISMATCH");
|
|
267
|
+
await onBound?.(this.threadId);
|
|
268
|
+
const threadId = this.threadId;
|
|
269
|
+
if (threadId === undefined)
|
|
270
|
+
throw new Error("CODEX_REBUILD_THREAD_MISSING");
|
|
271
|
+
const turn = await connection.request("turn/start", TurnStartParams.parse({
|
|
272
|
+
threadId,
|
|
273
|
+
input: content,
|
|
274
|
+
model: input.model,
|
|
275
|
+
effort: input.reasoningEffort,
|
|
276
|
+
summary: this.config.reasoningSummary,
|
|
277
|
+
}), signal);
|
|
278
|
+
this.turnId = TurnResult.parse(turn).turn.id;
|
|
279
|
+
return threadId;
|
|
280
|
+
}
|
|
281
|
+
/** 读取附件服务校验过的图片字节,转换为 Codex 接受的输入。 */
|
|
282
|
+
async encodeInput(content, signal) {
|
|
283
|
+
return await Promise.all(content.map(async (block) => {
|
|
284
|
+
if (block.type === "text")
|
|
285
|
+
return block;
|
|
286
|
+
if (block.offloaded === true)
|
|
287
|
+
return { type: "text", text: offloadedImageText(block.attachment) };
|
|
288
|
+
const image = await this.ctx.attachments.readImage(block.attachment, signal);
|
|
289
|
+
return {
|
|
290
|
+
type: "image",
|
|
291
|
+
url: `data:${image.ref.mediaType};base64,${Buffer.from(image.data).toString("base64")}`,
|
|
292
|
+
};
|
|
293
|
+
}));
|
|
294
|
+
}
|
|
295
|
+
/** 移交外部建立的连接(临时会话路径);此后由本对象负责回收。 */
|
|
296
|
+
adopt(connection) {
|
|
297
|
+
this.connection = connection;
|
|
298
|
+
this.installHandlers();
|
|
299
|
+
}
|
|
300
|
+
/** 设置 thread 与 turn 标识(临时会话路径)。 */
|
|
301
|
+
setIds(threadId, turnId) {
|
|
302
|
+
this.threadId = threadId;
|
|
303
|
+
this.turnId = turnId;
|
|
304
|
+
}
|
|
305
|
+
/** 安装通知与服务端请求处理。 */
|
|
306
|
+
installHandlers() {
|
|
307
|
+
const connection = this.connection;
|
|
308
|
+
if (connection === undefined)
|
|
309
|
+
return;
|
|
310
|
+
connection.onNotification((method, params) => {
|
|
311
|
+
try {
|
|
312
|
+
this.handleNotification(method, params);
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
this.push({
|
|
316
|
+
kind: "failure",
|
|
317
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
});
|
|
321
|
+
connection.onServerRequest(async (method, params) => {
|
|
322
|
+
// 审批类服务端请求:交审批桥转 KMH 用户决定(feat09,D18)。
|
|
323
|
+
const bridge = new CodexApprovalBridge(this.ctx, this.sessionId, this.approvalAbort?.signal);
|
|
324
|
+
switch (method) {
|
|
325
|
+
case Incoming.itemCommandExecutionRequestApproval:
|
|
326
|
+
try {
|
|
327
|
+
return await bridge.handleCommandApproval(params);
|
|
328
|
+
}
|
|
329
|
+
catch (error) {
|
|
330
|
+
this.ctx.logger.warn(`codex-cli command approval failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
331
|
+
throw error;
|
|
332
|
+
}
|
|
333
|
+
case Incoming.itemFileChangeRequestApproval:
|
|
334
|
+
return await bridge.handleFileChangeApproval(params);
|
|
335
|
+
case Incoming.itemPermissionsRequestApproval:
|
|
336
|
+
return await bridge.handlePermissionsApproval(params);
|
|
337
|
+
case Incoming.itemToolRequestUserInput:
|
|
338
|
+
return await bridge.handleUserInput(params);
|
|
339
|
+
case Incoming.mcpServerElicitationRequest:
|
|
340
|
+
return await bridge.handleElicitation(params);
|
|
341
|
+
}
|
|
342
|
+
if (method !== Incoming.itemToolCall &&
|
|
343
|
+
method !== Incoming.itemDynamicToolCall) {
|
|
344
|
+
this.ctx.logger.warn(`codex-cli unexpected server request: ${method}; params=${JSON.stringify(params).slice(0, 400)}`);
|
|
345
|
+
throw new Error(`CODEX_SERVER_REQUEST_UNEXPECTED: ${method}`);
|
|
346
|
+
}
|
|
347
|
+
const call = DynamicToolCallParams.parse(params);
|
|
348
|
+
if (this.threadId !== undefined && call.threadId !== this.threadId)
|
|
349
|
+
throw new Error("CODEX_TOOL_CALL_THREAD_MISMATCH");
|
|
350
|
+
if (call.namespace !== undefined &&
|
|
351
|
+
call.namespace !== null &&
|
|
352
|
+
call.namespace !== KMH_TOOL_NAMESPACE)
|
|
353
|
+
throw new Error("CODEX_TOOL_CALL_NAMESPACE_UNEXPECTED");
|
|
354
|
+
// D13:按声明表解析(兼容旧 thread 裸名);未知名明确错误回执,不挂起。
|
|
355
|
+
const kmhName = resolveKmhToolName(this.toolRegistry, call.tool);
|
|
356
|
+
if (kmhName === undefined) {
|
|
357
|
+
this.ctx.logger.warn(`codex-cli unknown tool callback: ${call.tool} (call ${call.callId})`);
|
|
358
|
+
return DynamicToolCallResponse.parse({
|
|
359
|
+
success: false,
|
|
360
|
+
contentItems: [
|
|
361
|
+
{
|
|
362
|
+
type: "inputText",
|
|
363
|
+
text: `CODEX_TOOL_UNKNOWN: ${call.tool} 不在当前 KMH 工具目录中`,
|
|
364
|
+
},
|
|
365
|
+
],
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
return await new Promise((resolve, reject) => {
|
|
369
|
+
this.pending.set(call.callId, {
|
|
370
|
+
callId: call.callId,
|
|
371
|
+
tool: kmhName,
|
|
372
|
+
arguments: call.arguments,
|
|
373
|
+
reply: resolve,
|
|
374
|
+
fail: reject,
|
|
375
|
+
});
|
|
376
|
+
const id = ToolCallId(call.callId);
|
|
377
|
+
const index = this.allocate("");
|
|
378
|
+
const argumentsDelta = JSON.stringify(call.arguments ?? {});
|
|
379
|
+
this.push({
|
|
380
|
+
kind: "chunk",
|
|
381
|
+
chunk: { type: "block-start", index, blockType: "tool-call" },
|
|
382
|
+
});
|
|
383
|
+
this.push({
|
|
384
|
+
kind: "chunk",
|
|
385
|
+
chunk: {
|
|
386
|
+
type: "tool-call-delta",
|
|
387
|
+
index,
|
|
388
|
+
id,
|
|
389
|
+
name: kmhName,
|
|
390
|
+
argumentsDelta,
|
|
391
|
+
},
|
|
392
|
+
});
|
|
393
|
+
this.push({
|
|
394
|
+
kind: "chunk",
|
|
395
|
+
chunk: {
|
|
396
|
+
type: "block-end",
|
|
397
|
+
index,
|
|
398
|
+
block: {
|
|
399
|
+
type: "tool-call",
|
|
400
|
+
id,
|
|
401
|
+
name: kmhName,
|
|
402
|
+
arguments: argumentsDelta,
|
|
403
|
+
},
|
|
404
|
+
},
|
|
405
|
+
});
|
|
406
|
+
// 工具挂起也是一步 assistant 消息:pump 收尾时补用量样本。
|
|
407
|
+
this.push({ kind: "tool-pause" });
|
|
408
|
+
});
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
/** 通知投影。 */
|
|
412
|
+
handleNotification(method, params) {
|
|
413
|
+
if (this.threadId !== undefined &&
|
|
414
|
+
params.threadId !== undefined &&
|
|
415
|
+
params.threadId !== this.threadId)
|
|
416
|
+
return;
|
|
417
|
+
switch (method) {
|
|
418
|
+
case Incoming.agentMessageDelta: {
|
|
419
|
+
const delta = AgentMessageDeltaParams.parse(params);
|
|
420
|
+
const index = this.allocate(delta.itemId);
|
|
421
|
+
if (!this.openBlocks.has(index))
|
|
422
|
+
this.push({
|
|
423
|
+
kind: "chunk",
|
|
424
|
+
chunk: { type: "block-start", index, blockType: "text" },
|
|
425
|
+
});
|
|
426
|
+
this.push({
|
|
427
|
+
kind: "chunk",
|
|
428
|
+
chunk: { type: "text-delta", index, text: delta.delta },
|
|
429
|
+
});
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
case Incoming.reasoningTextDelta:
|
|
433
|
+
case Incoming.reasoningSummaryTextDelta: {
|
|
434
|
+
const delta = ReasoningDeltaParams.parse(params);
|
|
435
|
+
const index = this.allocate(delta.itemId);
|
|
436
|
+
if (!this.openBlocks.has(index))
|
|
437
|
+
this.push({
|
|
438
|
+
kind: "chunk",
|
|
439
|
+
chunk: { type: "block-start", index, blockType: "reasoning" },
|
|
440
|
+
});
|
|
441
|
+
this.push({
|
|
442
|
+
kind: "chunk",
|
|
443
|
+
chunk: { type: "reasoning-delta", index, text: delta.delta },
|
|
444
|
+
});
|
|
445
|
+
break;
|
|
446
|
+
}
|
|
447
|
+
case Incoming.itemStarted: {
|
|
448
|
+
// 原生执行叙述(feat08 v1):开始即开一个独立文本块(场景1/3)。
|
|
449
|
+
const started = ItemEventParams.parse(params);
|
|
450
|
+
const header = nativeHeaderOf(started.item);
|
|
451
|
+
if (header !== undefined)
|
|
452
|
+
this.openNativeNote(header.itemId, header.header);
|
|
453
|
+
break;
|
|
454
|
+
}
|
|
455
|
+
case Incoming.commandExecutionOutputDelta: {
|
|
456
|
+
// 命令输出随执行更新(场景1):增量追加进该调用的叙述块,超限截断。
|
|
457
|
+
const output = CommandExecutionOutputDeltaParams.parse(params);
|
|
458
|
+
this.appendNativeNote(output.itemId, output.delta);
|
|
459
|
+
break;
|
|
460
|
+
}
|
|
461
|
+
case Incoming.mcpToolCallProgress: {
|
|
462
|
+
const progress = McpToolCallProgressParams.parse(params);
|
|
463
|
+
this.appendNativeNote(progress.itemId, `▸ 进度:${progress.message}\n`);
|
|
464
|
+
break;
|
|
465
|
+
}
|
|
466
|
+
case Incoming.turnDiffUpdated: {
|
|
467
|
+
// turn 级文件变更摘要(D14):按范围统计行数,更新次数封顶。
|
|
468
|
+
const updated = TurnDiffUpdatedParams.parse(params);
|
|
469
|
+
if (diffBudgetAccepts(this.diffBudget)) {
|
|
470
|
+
this.diffBudget.updates += 1;
|
|
471
|
+
if (!this.nativeNotes.has(NATIVE_DIFF_NOTE_ID))
|
|
472
|
+
this.openNativeNote(NATIVE_DIFF_NOTE_ID, "▸ [codex 原生·变更] 本回合文件变更:");
|
|
473
|
+
this.appendNativeNote(NATIVE_DIFF_NOTE_ID, `${diffSummaryLineOf(updated.diff)}\n`);
|
|
474
|
+
}
|
|
475
|
+
break;
|
|
476
|
+
}
|
|
477
|
+
case Incoming.itemCompleted: {
|
|
478
|
+
const item = params.item;
|
|
479
|
+
if (item !== null && typeof item === "object") {
|
|
480
|
+
const record = item;
|
|
481
|
+
if (record.type === "agentMessage" &&
|
|
482
|
+
typeof record.id === "string" &&
|
|
483
|
+
typeof record.text === "string") {
|
|
484
|
+
const index = this.allocate(record.id);
|
|
485
|
+
this.push({
|
|
486
|
+
kind: "chunk",
|
|
487
|
+
chunk: {
|
|
488
|
+
type: "block-end",
|
|
489
|
+
index,
|
|
490
|
+
block: { type: "text", text: record.text },
|
|
491
|
+
},
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
else if (record.type === "reasoning" &&
|
|
495
|
+
typeof record.id === "string") {
|
|
496
|
+
const text = reasoningItemText(item);
|
|
497
|
+
if (text !== undefined) {
|
|
498
|
+
const index = this.allocate(record.id);
|
|
499
|
+
this.push({
|
|
500
|
+
kind: "chunk",
|
|
501
|
+
chunk: {
|
|
502
|
+
type: "block-end",
|
|
503
|
+
index,
|
|
504
|
+
block: { type: "reasoning", text },
|
|
505
|
+
},
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
else if (record.type === "imageGeneration") {
|
|
510
|
+
this.projectImage(item).catch(() => undefined);
|
|
511
|
+
this.closeNativeNote(item);
|
|
512
|
+
}
|
|
513
|
+
else {
|
|
514
|
+
// 其余原生 item:追加完成状态并收尾叙述块(场景1:结果)。
|
|
515
|
+
this.closeNativeNote(item);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
break;
|
|
519
|
+
}
|
|
520
|
+
case Incoming.turnCompleted: {
|
|
521
|
+
const completed = TurnCompletedParams.parse(params);
|
|
522
|
+
if (this.turnId !== undefined && completed.turn.id !== this.turnId)
|
|
523
|
+
return;
|
|
524
|
+
this.terminalStatus = completed.turn.status;
|
|
525
|
+
this.lastCompletedTurnId = completed.turn.id;
|
|
526
|
+
// 缺结束确认的调用补记待确认(场景5/6),再补算未闭合块摘要。
|
|
527
|
+
this.closeUnsettledNativeNotes();
|
|
528
|
+
this.digestOpenBlocks();
|
|
529
|
+
// turn/completed 的 turn 不带 usage(0.162 wire 实测);样本来自
|
|
530
|
+
// thread/tokenUsage/updated 队列,pump 收尾时统一消费。
|
|
531
|
+
this.push({ kind: "turn-done", status: completed.turn.status });
|
|
532
|
+
break;
|
|
533
|
+
}
|
|
534
|
+
case Incoming.tokenUsageUpdated: {
|
|
535
|
+
// 记录本回合的逐响应用量样本(跨回合/旧回合回放按 turnId 过滤)。
|
|
536
|
+
const usageEvent = TokenUsageParams.parse(params);
|
|
537
|
+
if (usageEvent.turnId !== this.turnId)
|
|
538
|
+
return;
|
|
539
|
+
const mapped = breakdownToUsage(usageEvent.tokenUsage.last);
|
|
540
|
+
if (mapped !== undefined)
|
|
541
|
+
this.usageQueue.push(mapped);
|
|
542
|
+
break;
|
|
543
|
+
}
|
|
544
|
+
case Incoming.error: {
|
|
545
|
+
const failure = ErrorNotificationParams.parse(params);
|
|
546
|
+
if (this.turnId !== undefined &&
|
|
547
|
+
failure.turnId !== undefined &&
|
|
548
|
+
failure.turnId !== this.turnId)
|
|
549
|
+
return;
|
|
550
|
+
const detail = [
|
|
551
|
+
failure.error?.message ?? failure.message ?? "unknown",
|
|
552
|
+
failure.error?.additionalDetails,
|
|
553
|
+
]
|
|
554
|
+
.filter(Boolean)
|
|
555
|
+
.join(": ");
|
|
556
|
+
if (failure.willRetry === true) {
|
|
557
|
+
this.onConnectionState?.(true, detail);
|
|
558
|
+
break;
|
|
559
|
+
}
|
|
560
|
+
this.push({
|
|
561
|
+
kind: "failure",
|
|
562
|
+
error: new Error(`CODEX_SERVER_ERROR: ${detail}`),
|
|
563
|
+
});
|
|
564
|
+
break;
|
|
565
|
+
}
|
|
566
|
+
default:
|
|
567
|
+
break;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* 把 Codex 原生生图结果投影为会话图片块:读取落盘产物、经宿主附件服务
|
|
572
|
+
* 落成 ImageAttachmentRef 后以 image 块送回 KMH 展示,并随图报告实际
|
|
573
|
+
* 像素尺寸(feat10)。投影失败不打断生成(跳过并告警):投影是展示
|
|
574
|
+
* 增强,生成与续推链路不依赖它;失败时改为推送双态报告文本块。
|
|
575
|
+
* @param item - item/completed 携带的 ThreadItem::ImageGeneration。
|
|
576
|
+
*/
|
|
577
|
+
async projectImage(item) {
|
|
578
|
+
const projection = imageProjectionOf(item);
|
|
579
|
+
if (projection === undefined)
|
|
580
|
+
return;
|
|
581
|
+
if (this.projectedImages.has(projection.id))
|
|
582
|
+
return;
|
|
583
|
+
this.projectedImages.add(projection.id);
|
|
584
|
+
try {
|
|
585
|
+
// 附件服务缺失(headless 部署)时跳过投影;访问放在 try 内——
|
|
586
|
+
// cordis 上下文代理对未注入服务的访问是抛错而非 undefined。
|
|
587
|
+
const store = this.ctx.attachments;
|
|
588
|
+
if (store === undefined)
|
|
589
|
+
return;
|
|
590
|
+
const data = await readFile(projection.path);
|
|
591
|
+
const [first] = await store.saveImages([
|
|
592
|
+
{
|
|
593
|
+
data,
|
|
594
|
+
mediaType: "image/png",
|
|
595
|
+
...(projection.name !== undefined ? { name: projection.name } : {}),
|
|
596
|
+
},
|
|
597
|
+
]);
|
|
598
|
+
if (first === undefined)
|
|
599
|
+
throw new Error("CODEX_IMAGE_REF_MISSING");
|
|
600
|
+
// 索引键不能与叙述块共用:openNativeNote 已按同一 item id 开过文本块
|
|
601
|
+
// (先关先赢会让同索引的 image 块被组装器静默丢弃),用独立后缀。
|
|
602
|
+
const index = this.allocate(`${projection.id}:image`);
|
|
603
|
+
this.push({
|
|
604
|
+
kind: "chunk",
|
|
605
|
+
chunk: { type: "block-start", index, blockType: "image" },
|
|
606
|
+
});
|
|
607
|
+
this.push({
|
|
608
|
+
kind: "chunk",
|
|
609
|
+
chunk: {
|
|
610
|
+
type: "block-end",
|
|
611
|
+
index,
|
|
612
|
+
block: { type: "image", attachment: first },
|
|
613
|
+
},
|
|
614
|
+
});
|
|
615
|
+
this.pushNote(`${projection.id}:size`, imageSizeNote(pngSizeOf(data), imageSizeRequirementOf(this.lastUserText)));
|
|
616
|
+
}
|
|
617
|
+
catch (error) {
|
|
618
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
619
|
+
this.ctx.logger.warn(`codex-cli image projection failed: ${reason}`);
|
|
620
|
+
// 双态报告:Codex 侧已生成(原生产物路径即恢复入口),KMH 侧接入失败。
|
|
621
|
+
this.pushNote(`${projection.id}:failure`, imageFailureNote(projection.path, reason));
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
/** 推送一个自成一体的文本块(尺寸/失败等投影附注)。 */
|
|
625
|
+
pushNote(itemId, text) {
|
|
626
|
+
const index = this.allocate(itemId);
|
|
627
|
+
this.push({
|
|
628
|
+
kind: "chunk",
|
|
629
|
+
chunk: { type: "block-start", index, blockType: "text" },
|
|
630
|
+
});
|
|
631
|
+
this.push({
|
|
632
|
+
kind: "chunk",
|
|
633
|
+
chunk: { type: "text-delta", index, text },
|
|
634
|
+
});
|
|
635
|
+
this.push({
|
|
636
|
+
kind: "chunk",
|
|
637
|
+
chunk: { type: "block-end", index, block: { type: "text", text } },
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
/** 开启一条原生叙述块(item/started)。 */
|
|
641
|
+
openNativeNote(itemId, header) {
|
|
642
|
+
if (this.nativeNotes.has(itemId))
|
|
643
|
+
return;
|
|
644
|
+
const budget = newNoteBudget();
|
|
645
|
+
budget.chars = header.length;
|
|
646
|
+
budget.text = `${header}\n`;
|
|
647
|
+
this.nativeNotes.set(itemId, budget);
|
|
648
|
+
const index = this.allocate(itemId);
|
|
649
|
+
this.push({
|
|
650
|
+
kind: "chunk",
|
|
651
|
+
chunk: { type: "block-start", index, blockType: "text" },
|
|
652
|
+
});
|
|
653
|
+
this.push({
|
|
654
|
+
kind: "chunk",
|
|
655
|
+
chunk: { type: "text-delta", index, text: budget.text },
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
/** 向原生叙述块追加增量(输出/进度/diff 摘要),超限截断、收尾后拒收。 */
|
|
659
|
+
appendNativeNote(itemId, text) {
|
|
660
|
+
const budget = this.nativeNotes.get(itemId);
|
|
661
|
+
if (budget === undefined || budget.closed || budget.truncated)
|
|
662
|
+
return;
|
|
663
|
+
if (budget.chars + text.length > NATIVE_NOTE_LIMIT) {
|
|
664
|
+
budget.truncated = true;
|
|
665
|
+
budget.text += NATIVE_TRUNCATED_NOTE;
|
|
666
|
+
const index = this.allocate(itemId);
|
|
667
|
+
this.push({
|
|
668
|
+
kind: "chunk",
|
|
669
|
+
chunk: { type: "text-delta", index, text: NATIVE_TRUNCATED_NOTE },
|
|
670
|
+
});
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
budget.chars += text.length;
|
|
674
|
+
budget.text += text;
|
|
675
|
+
const index = this.allocate(itemId);
|
|
676
|
+
this.push({
|
|
677
|
+
kind: "chunk",
|
|
678
|
+
chunk: { type: "text-delta", index, text },
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
/** 收尾原生叙述块(item/completed):补完成状态并块结束(一次性)。 */
|
|
682
|
+
closeNativeNote(item) {
|
|
683
|
+
const note = nativeCompletionNoteOf(item);
|
|
684
|
+
if (note === undefined)
|
|
685
|
+
return;
|
|
686
|
+
const id = fieldOf(item, "id");
|
|
687
|
+
if (typeof id !== "string")
|
|
688
|
+
return;
|
|
689
|
+
const budget = this.nativeNotes.get(id);
|
|
690
|
+
const index = this.allocate(id);
|
|
691
|
+
if (budget === undefined) {
|
|
692
|
+
// 错过 started 的完成事件:以完整单块补记(开头 + 完成状态)。
|
|
693
|
+
const header = nativeHeaderOf(item);
|
|
694
|
+
if (header === undefined)
|
|
695
|
+
return;
|
|
696
|
+
const full = `${header.header}\n${note}`;
|
|
697
|
+
this.nativeNotes.set(id, {
|
|
698
|
+
...newNoteBudget(),
|
|
699
|
+
closed: true,
|
|
700
|
+
text: full,
|
|
701
|
+
});
|
|
702
|
+
this.push({
|
|
703
|
+
kind: "chunk",
|
|
704
|
+
chunk: { type: "block-start", index, blockType: "text" },
|
|
705
|
+
});
|
|
706
|
+
this.push({
|
|
707
|
+
kind: "chunk",
|
|
708
|
+
chunk: { type: "text-delta", index, text: full },
|
|
709
|
+
});
|
|
710
|
+
this.push({
|
|
711
|
+
kind: "chunk",
|
|
712
|
+
chunk: {
|
|
713
|
+
type: "block-end",
|
|
714
|
+
index,
|
|
715
|
+
block: { type: "text", text: full },
|
|
716
|
+
},
|
|
717
|
+
});
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
if (budget.closed)
|
|
721
|
+
return;
|
|
722
|
+
budget.closed = true;
|
|
723
|
+
budget.text += note;
|
|
724
|
+
this.push({
|
|
725
|
+
kind: "chunk",
|
|
726
|
+
chunk: { type: "text-delta", index, text: note },
|
|
727
|
+
});
|
|
728
|
+
this.push({
|
|
729
|
+
kind: "chunk",
|
|
730
|
+
chunk: {
|
|
731
|
+
type: "block-end",
|
|
732
|
+
index,
|
|
733
|
+
block: { type: "text", text: budget.text },
|
|
734
|
+
},
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
/** 回合终局:仍未收尾的原生叙述补记待确认并闭合(场景5/6)。 */
|
|
738
|
+
closeUnsettledNativeNotes() {
|
|
739
|
+
for (const [itemId, budget] of this.nativeNotes) {
|
|
740
|
+
if (budget.closed)
|
|
741
|
+
continue;
|
|
742
|
+
// diff 摘要不是调用记录:无"待确认"语义,交给 digestOpenBlocks 常规闭合。
|
|
743
|
+
if (itemId === NATIVE_DIFF_NOTE_ID)
|
|
744
|
+
continue;
|
|
745
|
+
budget.closed = true;
|
|
746
|
+
budget.text += NATIVE_UNSETTLED_NOTE;
|
|
747
|
+
const index = this.allocate(itemId);
|
|
748
|
+
this.push({
|
|
749
|
+
kind: "chunk",
|
|
750
|
+
chunk: { type: "text-delta", index, text: NATIVE_UNSETTLED_NOTE },
|
|
751
|
+
});
|
|
752
|
+
this.push({
|
|
753
|
+
kind: "chunk",
|
|
754
|
+
chunk: {
|
|
755
|
+
type: "block-end",
|
|
756
|
+
index,
|
|
757
|
+
block: { type: "text", text: budget.text },
|
|
758
|
+
},
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
/** 为流块分配序号;同一 itemId 复用。 */
|
|
763
|
+
allocate(itemId) {
|
|
764
|
+
let index = this.itemIndex.get(itemId);
|
|
765
|
+
if (index === undefined) {
|
|
766
|
+
index = this.nextIndex++;
|
|
767
|
+
this.itemIndex.set(itemId, index);
|
|
768
|
+
}
|
|
769
|
+
return index;
|
|
770
|
+
}
|
|
771
|
+
push(event) {
|
|
772
|
+
if (this.closed)
|
|
773
|
+
return;
|
|
774
|
+
const chunk = event.kind === "chunk" ? event.chunk : undefined;
|
|
775
|
+
if (chunk !== undefined) {
|
|
776
|
+
if (chunk.type === "text-delta" ||
|
|
777
|
+
chunk.type === "reasoning-delta" ||
|
|
778
|
+
chunk.type === "tool-call-delta")
|
|
779
|
+
this.onConnectionState?.(false, "CLI 通信中");
|
|
780
|
+
// 文本/推理块按索引累积:Codex 对 turn 末条消息常不发 item/completed,
|
|
781
|
+
// 摘要在 turn-done 时以累积文本补算(与 KMH 侧按 delta 组装一致)。
|
|
782
|
+
if (chunk.type === "block-start") {
|
|
783
|
+
this.openBlocks.add(chunk.index);
|
|
784
|
+
if (chunk.blockType === "text" || chunk.blockType === "reasoning") {
|
|
785
|
+
this.blockTypes.set(chunk.index, chunk.blockType);
|
|
786
|
+
this.blockText.set(chunk.index, "");
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
else if (chunk.type === "text-delta" ||
|
|
790
|
+
chunk.type === "reasoning-delta") {
|
|
791
|
+
const text = this.blockText.get(chunk.index) ?? "";
|
|
792
|
+
this.blockText.set(chunk.index, text + chunk.text);
|
|
793
|
+
}
|
|
794
|
+
else if (chunk.type === "block-end") {
|
|
795
|
+
this.openBlocks.delete(chunk.index);
|
|
796
|
+
this.endedBlocks.add(chunk.index);
|
|
797
|
+
const block = chunk.block;
|
|
798
|
+
if ((block.type === "text" || block.type === "reasoning") &&
|
|
799
|
+
typeof block.text === "string")
|
|
800
|
+
this.blockText.set(chunk.index, block.text);
|
|
801
|
+
// 本回合产出的块入待核对队列:turn 边界差分用它核对历史 assistant 消息。
|
|
802
|
+
const d = blockDigest(chunk.block);
|
|
803
|
+
if (d !== undefined)
|
|
804
|
+
this.pendingDigests.push(d);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
this.queue.push(event);
|
|
808
|
+
this.wakeup?.();
|
|
809
|
+
}
|
|
810
|
+
/** turn 终局补算未闭合文本/推理块的摘要(内容取 delta 累积)。 */
|
|
811
|
+
digestOpenBlocks() {
|
|
812
|
+
for (const [index, type] of this.blockTypes) {
|
|
813
|
+
if (this.endedBlocks.has(index))
|
|
814
|
+
continue;
|
|
815
|
+
this.endedBlocks.add(index);
|
|
816
|
+
const d = blockDigest({ type, text: this.blockText.get(index) ?? "" });
|
|
817
|
+
if (d !== undefined)
|
|
818
|
+
this.pendingDigests.push(d);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
async wait(signal) {
|
|
822
|
+
signal.throwIfAborted();
|
|
823
|
+
if (this.queue.length > 0)
|
|
824
|
+
return Promise.resolve();
|
|
825
|
+
let listener;
|
|
826
|
+
try {
|
|
827
|
+
await new Promise((resolve, reject) => {
|
|
828
|
+
this.wakeup = resolve;
|
|
829
|
+
listener = addAbortListener(signal, () => {
|
|
830
|
+
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- DSH 以 AgentCancelCause 对象传递停止原因。
|
|
831
|
+
reject(signal.reason);
|
|
832
|
+
});
|
|
833
|
+
});
|
|
834
|
+
signal.throwIfAborted();
|
|
835
|
+
}
|
|
836
|
+
finally {
|
|
837
|
+
this.wakeup = undefined;
|
|
838
|
+
listener?.[Symbol.dispose]();
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* 消费投影流直到工具挂起或 turn 终止。
|
|
843
|
+
* @param signal - 取消或超时信号;等待期间中止会立即抛出 signal.reason。
|
|
844
|
+
*/
|
|
845
|
+
async *pump(signal) {
|
|
846
|
+
while (true) {
|
|
847
|
+
signal.throwIfAborted();
|
|
848
|
+
if (this.queue.length === 0)
|
|
849
|
+
await this.wait(signal);
|
|
850
|
+
const event = this.queue.shift();
|
|
851
|
+
if (event === undefined)
|
|
852
|
+
continue;
|
|
853
|
+
if (event.kind === "chunk") {
|
|
854
|
+
yield event.chunk;
|
|
855
|
+
continue;
|
|
856
|
+
}
|
|
857
|
+
if (event.kind === "tool-pause") {
|
|
858
|
+
// 工具挂起:先补本步用量样本再结束本次流,不回收进程,等待下一
|
|
859
|
+
// 次调用回传结果续推。样本此刻未到时补零,真实样本留在队列供下一
|
|
860
|
+
// 步消费(各步样本之和恒等于回合总量)。
|
|
861
|
+
yield { type: "usage", usage: this.consumeUsageSample() };
|
|
862
|
+
yield { type: "finish", reason: { kind: "tool-calls" } };
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
865
|
+
if (event.kind === "failure") {
|
|
866
|
+
await this.dispose();
|
|
867
|
+
throw event.error;
|
|
868
|
+
}
|
|
869
|
+
// turn-done:报用量并按状态收尾(终局合并全部剩余样本)。
|
|
870
|
+
const chunks = [];
|
|
871
|
+
chunks.push({ type: "usage", usage: this.consumeUsageTotal() });
|
|
872
|
+
const status = event.status;
|
|
873
|
+
chunks.push({
|
|
874
|
+
type: "finish",
|
|
875
|
+
reason: status === "completed"
|
|
876
|
+
? { kind: "stop" }
|
|
877
|
+
: {
|
|
878
|
+
kind: status === "interrupted" ? "aborted" : "error",
|
|
879
|
+
failure: {
|
|
880
|
+
message: `CODEX_TURN_STATUS_${status}`,
|
|
881
|
+
code: status === "interrupted" ? "ABORTED" : "PROVIDER_ERROR",
|
|
882
|
+
},
|
|
883
|
+
},
|
|
884
|
+
});
|
|
885
|
+
try {
|
|
886
|
+
for (const chunk of chunks)
|
|
887
|
+
yield chunk;
|
|
888
|
+
}
|
|
889
|
+
finally {
|
|
890
|
+
await this.dispose();
|
|
891
|
+
}
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
/**
|
|
896
|
+
* 回传一组工具结果并继续消费投影流。
|
|
897
|
+
* @param results - 与挂起工具逐一匹配的结果集合。
|
|
898
|
+
* @param signal - 取消或超时信号。
|
|
899
|
+
* @param followup - 先交给活跃回合的追加输入及接纳后保存游标的回调。
|
|
900
|
+
*/
|
|
901
|
+
async *resumeWithToolResults(results, signal, followup) {
|
|
902
|
+
if (this.pending.size === 0)
|
|
903
|
+
throw new Error("CODEX_NO_PENDING_TOOL");
|
|
904
|
+
const replies = await Promise.all(results.map(async (result) => {
|
|
905
|
+
const tool = this.pending.get(result.callId);
|
|
906
|
+
if (tool === undefined)
|
|
907
|
+
throw new Error("CODEX_TOOL_CALL_MISMATCH");
|
|
908
|
+
const content = await this.encodeInput(result.content, signal);
|
|
909
|
+
const response = DynamicToolCallResponse.parse({
|
|
910
|
+
success: !result.isError,
|
|
911
|
+
contentItems: content.map((block) => block.type === "text"
|
|
912
|
+
? { type: "inputText", text: block.text }
|
|
913
|
+
: { type: "inputImage", imageUrl: block.url }),
|
|
914
|
+
});
|
|
915
|
+
return { tool, response };
|
|
916
|
+
}));
|
|
917
|
+
if (followup !== undefined) {
|
|
918
|
+
const connection = this.connection;
|
|
919
|
+
const expectedTurnId = this.turnId;
|
|
920
|
+
if (connection === undefined || expectedTurnId === undefined)
|
|
921
|
+
throw new Error("CODEX_NO_ACTIVE_TURN");
|
|
922
|
+
// 工具回传会解除原生回合的等待,先确认追加输入已进入其队列。
|
|
923
|
+
const accepted = TurnSteerResult.parse(await connection.request("turn/steer", TurnSteerParams.parse({
|
|
924
|
+
threadId: this.threadId,
|
|
925
|
+
expectedTurnId,
|
|
926
|
+
input: await this.encodeInput(followup.content, signal),
|
|
927
|
+
}), signal));
|
|
928
|
+
if (accepted.turnId !== expectedTurnId)
|
|
929
|
+
throw new Error("CODEX_TURN_ID_MISMATCH");
|
|
930
|
+
}
|
|
931
|
+
for (const { tool, response } of replies) {
|
|
932
|
+
this.pending.delete(tool.callId);
|
|
933
|
+
tool.reply(response);
|
|
934
|
+
}
|
|
935
|
+
await followup?.onAccepted();
|
|
936
|
+
yield* this.pump(signal);
|
|
937
|
+
}
|
|
938
|
+
/** 中断当前 turn 并等待终止通知,随后回收进程。 */
|
|
939
|
+
async interrupt(signal) {
|
|
940
|
+
const connection = this.connection;
|
|
941
|
+
if (connection === undefined || this.terminalStatus !== undefined) {
|
|
942
|
+
await this.dispose();
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
const threadId = this.threadId;
|
|
946
|
+
const turnId = this.turnId;
|
|
947
|
+
if (threadId === undefined || turnId === undefined) {
|
|
948
|
+
await this.dispose();
|
|
949
|
+
return;
|
|
950
|
+
}
|
|
951
|
+
try {
|
|
952
|
+
await connection.request("turn/interrupt", { threadId, turnId }, AbortSignal.any([
|
|
953
|
+
signal,
|
|
954
|
+
AbortSignal.timeout(this.config.cancelReceiptTimeoutMs),
|
|
955
|
+
]));
|
|
956
|
+
// 等待 interrupted 终止通知到达(有界)。
|
|
957
|
+
const deadline = Date.now() + this.config.cancelReceiptTimeoutMs;
|
|
958
|
+
while (this.terminalStatus === undefined && Date.now() < deadline)
|
|
959
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
960
|
+
if (this.terminalStatus === undefined)
|
|
961
|
+
throw new Error("CODEX_INTERRUPT_UNCONFIRMED");
|
|
962
|
+
}
|
|
963
|
+
finally {
|
|
964
|
+
this.failPending(new Error("CODEX_TURN_CANCELLED"));
|
|
965
|
+
await this.dispose();
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
/** 拒绝全部挂起工具请求。 */
|
|
969
|
+
failPending(error) {
|
|
970
|
+
for (const tool of this.pending.values())
|
|
971
|
+
tool.fail(error);
|
|
972
|
+
this.pending.clear();
|
|
973
|
+
}
|
|
974
|
+
/** 回收连接与进程;幂等。 */
|
|
975
|
+
async dispose() {
|
|
976
|
+
if (this.closed)
|
|
977
|
+
return;
|
|
978
|
+
this.closed = true;
|
|
979
|
+
this.wakeup?.();
|
|
980
|
+
this.failPending(new Error("CODEX_TURN_DISPOSED"));
|
|
981
|
+
// 待审批决定随本回合取消:中止使 approval/request 归结 cancelled、
|
|
982
|
+
// userQuestions.ask 抛 ASK_ABORTED,迟到的用户答复按过期处理。
|
|
983
|
+
this.approvalAbort?.abort(new Error("CODEX_TURN_DISPOSED"));
|
|
984
|
+
const connection = this.connection;
|
|
985
|
+
this.connection = undefined;
|
|
986
|
+
if (connection !== undefined && !connection.exited)
|
|
987
|
+
await connection.stop(this.config.cleanupTimeoutMs);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
/**
|
|
991
|
+
* Codex 用量明细(TokenUsageBreakdown,总量口径含缓存)投影为 KMH 用量
|
|
992
|
+
* (拆分口径:inputTokens 仅未缓存部分,缓存单独计)。totalTokens 保留
|
|
993
|
+
* 官方精确总数——KMH 的 normalizeUsage 缺它且缺 cacheWrite 桶时直接拒绝。
|
|
994
|
+
*/
|
|
995
|
+
function breakdownToUsage(value) {
|
|
996
|
+
const cacheWrite = Math.max(0, value.cacheWriteInputTokens);
|
|
997
|
+
const cacheRead = Math.max(0, value.cachedInputTokens);
|
|
998
|
+
const input = Math.max(0, value.inputTokens - cacheRead - cacheWrite);
|
|
999
|
+
const output = Math.max(0, value.outputTokens);
|
|
1000
|
+
const reasoning = Math.max(0, value.reasoningOutputTokens);
|
|
1001
|
+
return {
|
|
1002
|
+
inputTokens: input,
|
|
1003
|
+
outputTokens: output,
|
|
1004
|
+
// 与官方总数一致性:total = input + cached + cacheWrite + output。
|
|
1005
|
+
totalTokens: Math.max(0, value.totalTokens),
|
|
1006
|
+
cacheReadTokens: cacheRead,
|
|
1007
|
+
cacheWriteTokens: cacheWrite,
|
|
1008
|
+
...(reasoning > 0 && reasoning <= output
|
|
1009
|
+
? { reasoningTokens: reasoning }
|
|
1010
|
+
: {}),
|
|
1011
|
+
};
|
|
1012
|
+
}
|