@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,178 @@
|
|
|
1
|
+
import { SubprocessExecutableNotFoundError, } from "@deepseek-ai/dsh-subprocess";
|
|
2
|
+
import { JsonRpcLineTransport, JsonRpcResponseError, } from "@deepseek-ai/dsh-sdk-protocol";
|
|
3
|
+
import { realpath } from "node:fs/promises";
|
|
4
|
+
import { createFrameBridge, InitializeParams, InitializeResult, } from "./protocol.js";
|
|
5
|
+
/**
|
|
6
|
+
* 一条到官方 CLI 的行协议连接。进程随连接存活:关闭输入并等待退出后连接不可复用。
|
|
7
|
+
* 进程意外退出时,在途请求以 JSON-RPC transport closed 拒绝。
|
|
8
|
+
*/
|
|
9
|
+
export class CodexConnection {
|
|
10
|
+
child;
|
|
11
|
+
bridge;
|
|
12
|
+
stderrTail;
|
|
13
|
+
transport;
|
|
14
|
+
exitState = false;
|
|
15
|
+
constructor(input, child, bridge, stderrTail) {
|
|
16
|
+
this.child = child;
|
|
17
|
+
this.bridge = bridge;
|
|
18
|
+
this.stderrTail = stderrTail;
|
|
19
|
+
this.transport = new JsonRpcLineTransport(input, bridge);
|
|
20
|
+
void child.done.then(() => {
|
|
21
|
+
this.exitState = true;
|
|
22
|
+
}, () => {
|
|
23
|
+
this.exitState = true;
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/** 进程退出观察回执;用于等待回收完成。 */
|
|
27
|
+
get done() {
|
|
28
|
+
return this.child.done;
|
|
29
|
+
}
|
|
30
|
+
/** 是否已经退出。 */
|
|
31
|
+
get exited() {
|
|
32
|
+
return this.exitState;
|
|
33
|
+
}
|
|
34
|
+
/** 诊断用 stderr 尾部(有界)。 */
|
|
35
|
+
get stderr() {
|
|
36
|
+
return this.stderrTail.value;
|
|
37
|
+
}
|
|
38
|
+
/** 开始读取输入流;幂等。 */
|
|
39
|
+
start() {
|
|
40
|
+
this.transport.start();
|
|
41
|
+
}
|
|
42
|
+
/** 停止读取并拆除桥接流;不触碰进程本身。 */
|
|
43
|
+
close() {
|
|
44
|
+
this.transport.close();
|
|
45
|
+
this.bridge.destroy();
|
|
46
|
+
}
|
|
47
|
+
/** 安装服务端请求处理;未安装时服务端请求收到 method not found 错误回执。 */
|
|
48
|
+
onServerRequest(handler) {
|
|
49
|
+
this.transport.onRequest(handler);
|
|
50
|
+
}
|
|
51
|
+
/** 安装通知处理。 */
|
|
52
|
+
onNotification(handler) {
|
|
53
|
+
this.transport.onNotification(handler);
|
|
54
|
+
}
|
|
55
|
+
/** 发起一次请求并等待响应;signal 中止时在途条目立即拒绝。 */
|
|
56
|
+
request(method, params, signal) {
|
|
57
|
+
return this.transport.request(method, params, signal);
|
|
58
|
+
}
|
|
59
|
+
/** 发送一条通知。 */
|
|
60
|
+
notify(method, params) {
|
|
61
|
+
this.transport.notify(method, params);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* 关闭输入并等待进程退出;超时后经 subprocess 托管强制回收。
|
|
65
|
+
* @param cleanupTimeoutMs - 干净退出的等待时限。
|
|
66
|
+
* @returns clean 表示进程自行退出,forced 表示超时后强制回收。
|
|
67
|
+
*/
|
|
68
|
+
async stop(cleanupTimeoutMs) {
|
|
69
|
+
if (this.exited)
|
|
70
|
+
return "clean";
|
|
71
|
+
this.child.stdin?.end();
|
|
72
|
+
this.close();
|
|
73
|
+
const confirmed = await this.child.waitForExit(AbortSignal.timeout(cleanupTimeoutMs));
|
|
74
|
+
if (!confirmed)
|
|
75
|
+
this.child.terminate();
|
|
76
|
+
await this.child.done.catch(() => undefined);
|
|
77
|
+
return confirmed ? "clean" : "forced";
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* 拉起官方 CLI、完成 initialize 握手并返回可用连接。
|
|
82
|
+
* @param ctx - 宿主上下文,提供受管 subprocess 服务。
|
|
83
|
+
* @param options - 可执行文件、工作目录、-c 覆盖与超时设置。
|
|
84
|
+
* @param signal - 中止信号:启动阶段中止即终止进程并抛 CODEX_STARTUP_CANCELLED。
|
|
85
|
+
* @throws CODEX_CLI_MISSING 可执行文件不存在;CODEX_STDIO_MISSING 管道缺失;
|
|
86
|
+
* CODEX_STARTUP_TIMEOUT 握手超时;CODEX_STARTUP_FAILED 握手被拒或进程提前退出。
|
|
87
|
+
*/
|
|
88
|
+
export async function connectCodex(ctx, options, signal) {
|
|
89
|
+
signal.throwIfAborted();
|
|
90
|
+
let executable;
|
|
91
|
+
try {
|
|
92
|
+
const resolved = await ctx.subprocess.resolveExecutable(options.command, {}, signal);
|
|
93
|
+
if (resolved === undefined)
|
|
94
|
+
throw new Error("CODEX_CLI_MISSING");
|
|
95
|
+
executable = await realpath(resolved);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (error instanceof SubprocessExecutableNotFoundError)
|
|
99
|
+
throw new Error("CODEX_CLI_MISSING");
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
// 会话来源标注为 CLI(Product 归类与默认 vscode 同为 Codex,agent
|
|
104
|
+
// 身份标识为 codex-cli)。较旧的本机二进制可能尚不支持该参数:识别
|
|
105
|
+
// 拒收特征后去参重试一次,标注随二进制升级自动生效。
|
|
106
|
+
return await launch(executable, ["--session-source", "cli"]);
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
110
|
+
if (!message.includes("unexpected argument '--session-source'"))
|
|
111
|
+
throw error;
|
|
112
|
+
return await launch(executable, []);
|
|
113
|
+
}
|
|
114
|
+
/** 以给定服务端参数拉起进程并完成握手。 */
|
|
115
|
+
async function launch(executable, serverArgs) {
|
|
116
|
+
const argv = [executable, "app-server", "--stdio", ...serverArgs];
|
|
117
|
+
for (const override of options.configOverrides)
|
|
118
|
+
argv.push("-c", override);
|
|
119
|
+
const env = {};
|
|
120
|
+
for (const [key, value] of Object.entries(options.env ?? {}))
|
|
121
|
+
if (value !== undefined)
|
|
122
|
+
env[key] = value;
|
|
123
|
+
const child = ctx.subprocess.spawn({
|
|
124
|
+
argv,
|
|
125
|
+
cwd: options.cwd,
|
|
126
|
+
env,
|
|
127
|
+
graceMs: options.graceMs,
|
|
128
|
+
stdio: { stdin: "pipe", stdout: "pipe", stderr: "pipe" },
|
|
129
|
+
});
|
|
130
|
+
const stderrTail = { value: "" };
|
|
131
|
+
child.stderr?.on("data", (chunk) => {
|
|
132
|
+
stderrTail.value = (stderrTail.value + chunk.toString("utf8")).slice(-2000);
|
|
133
|
+
});
|
|
134
|
+
const input = child.stdout;
|
|
135
|
+
const output = child.stdin;
|
|
136
|
+
if (!input || !output) {
|
|
137
|
+
child.terminate();
|
|
138
|
+
await child.done.catch(() => undefined);
|
|
139
|
+
throw new Error("CODEX_STDIO_MISSING");
|
|
140
|
+
}
|
|
141
|
+
const bridge = createFrameBridge(output);
|
|
142
|
+
const connection = new CodexConnection(input, child, bridge, stderrTail);
|
|
143
|
+
const startup = AbortSignal.any([
|
|
144
|
+
signal,
|
|
145
|
+
AbortSignal.timeout(options.startupTimeoutMs),
|
|
146
|
+
]);
|
|
147
|
+
try {
|
|
148
|
+
const params = InitializeParams.parse({
|
|
149
|
+
clientInfo: {
|
|
150
|
+
name: "kmh_codex_cli",
|
|
151
|
+
title: "KMH Codex CLI",
|
|
152
|
+
version: "0.1.0",
|
|
153
|
+
},
|
|
154
|
+
capabilities: { experimentalApi: true },
|
|
155
|
+
});
|
|
156
|
+
connection.start();
|
|
157
|
+
const raw = await connection.request("initialize", params, startup);
|
|
158
|
+
InitializeResult.parse(raw);
|
|
159
|
+
connection.notify("initialized", {});
|
|
160
|
+
return connection;
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
connection.close();
|
|
164
|
+
child.terminate();
|
|
165
|
+
await child.done.catch(() => undefined);
|
|
166
|
+
if (signal.aborted)
|
|
167
|
+
throw new Error("CODEX_STARTUP_CANCELLED");
|
|
168
|
+
if (startup.aborted)
|
|
169
|
+
throw new Error("CODEX_STARTUP_TIMEOUT");
|
|
170
|
+
if (error instanceof JsonRpcResponseError)
|
|
171
|
+
throw new Error("CODEX_STARTUP_FAILED");
|
|
172
|
+
if (error instanceof Error && error.message === "CODEX_STDIO_MISSING")
|
|
173
|
+
throw error;
|
|
174
|
+
// 进程提前退出等传输层失败:带 stderr 尾部辅助定位。
|
|
175
|
+
throw new Error(`CODEX_STARTUP_FAILED: ${error instanceof Error ? error.message : String(error)}${stderrTail.value ? `; stderr: ${stderrTail.value.slice(-300)}` : ""}`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { ImageBlock, RequestMessage, TextBlock } from "@deepseek-ai/dsh-llm";
|
|
2
|
+
/** Codex 支持从 KMH 接收的消息内容。 */
|
|
3
|
+
export type TurnInputBlock = TextBlock | ImageBlock;
|
|
4
|
+
export interface ToolResult {
|
|
5
|
+
callId: string;
|
|
6
|
+
content: TurnInputBlock[];
|
|
7
|
+
isError: boolean;
|
|
8
|
+
}
|
|
9
|
+
/** 已投递到 Codex thread 的对齐点:逐条消息指纹与待核对回合块摘要。 */
|
|
10
|
+
export interface CursorSnapshot {
|
|
11
|
+
fingerprints: string[];
|
|
12
|
+
/**
|
|
13
|
+
* Codex 本身已生成、历史尚未推进越过的块摘要队列(turn 边界核对用)。
|
|
14
|
+
* KMH 在流结束后才组装 assistant 消息,指纹永远滞后一拍;此队列让差分
|
|
15
|
+
* 能区分「Codex 自己的输出」(吞掉不重投)与「外来/被改写内容」(重建)。
|
|
16
|
+
*/
|
|
17
|
+
delivered: string[];
|
|
18
|
+
}
|
|
19
|
+
/** 一次差分识别出的待投递增量。 */
|
|
20
|
+
export type Increment = {
|
|
21
|
+
kind: "new-input";
|
|
22
|
+
content: TurnInputBlock[];
|
|
23
|
+
consumed: number;
|
|
24
|
+
/** 核对后剩余的待核对摘要(新输入路径通常为空)。 */
|
|
25
|
+
delivered: string[];
|
|
26
|
+
} | {
|
|
27
|
+
kind: "tool-results";
|
|
28
|
+
results: ToolResult[];
|
|
29
|
+
followup?: TurnInputBlock[];
|
|
30
|
+
consumed: number;
|
|
31
|
+
delivered: string[];
|
|
32
|
+
} | {
|
|
33
|
+
kind: "baseline-lost";
|
|
34
|
+
reason: string;
|
|
35
|
+
};
|
|
36
|
+
/** 空游标:thread 尚未投递任何内容。 */
|
|
37
|
+
export declare function emptySnapshot(): CursorSnapshot;
|
|
38
|
+
/**
|
|
39
|
+
* 单个内容块的摘要:与 CodexTurn 投影块(block-end)同算法。
|
|
40
|
+
* text/reasoning/tool-call/image 四类可摘要;其他块返回 undefined
|
|
41
|
+
* (意味着无法证明该消息来自 Codex 本身,差分将按基线丢失处理)。
|
|
42
|
+
*/
|
|
43
|
+
export declare function blockDigest(block: unknown): string | undefined;
|
|
44
|
+
/**
|
|
45
|
+
* 对比全量历史与已投快照,切出本次应投给 Codex 的尾部增量。
|
|
46
|
+
* @param messages - 本次请求的完整对话历史。
|
|
47
|
+
* @param snapshot - 上次投递成功后记录的对齐点。
|
|
48
|
+
* @returns new-input 表示尾部是待提交的输入,包含与其一起投递的上下文;
|
|
49
|
+
* tool-results 表示尾部是工具调用与结果,应回传给挂起中的 turn;
|
|
50
|
+
* baseline-lost 表示历史缩短、前缀不同或尾部不符合增量要求,由调用方处理。
|
|
51
|
+
*/
|
|
52
|
+
export declare function diffIncrement(messages: readonly RequestMessage[], snapshot: CursorSnapshot): Increment;
|
|
53
|
+
/** 计算推进到 total 条后的新快照。 */
|
|
54
|
+
export declare function snapshotAt(messages: readonly RequestMessage[], total: number, delivered?: string[]): CursorSnapshot;
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
/** KMH 全量对话历史与 Codex thread 已投递内容的差分游标。 */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { fieldOf } from "./protocol.js";
|
|
4
|
+
/** unknown 数组化:Array.isArray 守卫后的元素保持 unknown 而非 any。 */
|
|
5
|
+
function asArray(value) {
|
|
6
|
+
const out = [];
|
|
7
|
+
if (Array.isArray(value))
|
|
8
|
+
for (const item of value)
|
|
9
|
+
out.push(item);
|
|
10
|
+
return out;
|
|
11
|
+
}
|
|
12
|
+
/** 提取内容块的文本字段。 */
|
|
13
|
+
function textOf(block) {
|
|
14
|
+
const text = fieldOf(block, "text");
|
|
15
|
+
return typeof text === "string" ? text : undefined;
|
|
16
|
+
}
|
|
17
|
+
/** 空游标:thread 尚未投递任何内容。 */
|
|
18
|
+
export function emptySnapshot() {
|
|
19
|
+
return { fingerprints: [], delivered: [] };
|
|
20
|
+
}
|
|
21
|
+
/** 提取消息的稳定指纹原料:角色、内容块与工具关联。 */
|
|
22
|
+
function messageKey(message) {
|
|
23
|
+
const parts = [message.role];
|
|
24
|
+
for (const block of asArray(fieldOf(message, "content")))
|
|
25
|
+
parts.push(JSON.stringify(sortObject(block)));
|
|
26
|
+
const toolCallId = fieldOf(message, "toolCallId");
|
|
27
|
+
if (typeof toolCallId === "string")
|
|
28
|
+
parts.push(toolCallId);
|
|
29
|
+
return parts.join("\u0000");
|
|
30
|
+
}
|
|
31
|
+
/** 递归排序对象键,消除等价 JSON 的键序差异。 */
|
|
32
|
+
function sortObject(value) {
|
|
33
|
+
if (Array.isArray(value))
|
|
34
|
+
return value.map(sortObject);
|
|
35
|
+
if (value !== null && typeof value === "object") {
|
|
36
|
+
const sorted = {};
|
|
37
|
+
for (const key of Object.keys(value).sort())
|
|
38
|
+
sorted[key] = sortObject(fieldOf(value, key));
|
|
39
|
+
return sorted;
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
/** 消息指纹(短哈希)。 */
|
|
44
|
+
function fingerprint(message) {
|
|
45
|
+
return createHash("sha256")
|
|
46
|
+
.update(messageKey(message))
|
|
47
|
+
.digest("hex")
|
|
48
|
+
.slice(0, 16);
|
|
49
|
+
}
|
|
50
|
+
/** 短哈希摘要。 */
|
|
51
|
+
function digest(text) {
|
|
52
|
+
return createHash("sha256").update(text).digest("hex").slice(0, 16);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 单个内容块的摘要:与 CodexTurn 投影块(block-end)同算法。
|
|
56
|
+
* text/reasoning/tool-call/image 四类可摘要;其他块返回 undefined
|
|
57
|
+
* (意味着无法证明该消息来自 Codex 本身,差分将按基线丢失处理)。
|
|
58
|
+
*/
|
|
59
|
+
export function blockDigest(block) {
|
|
60
|
+
const type = fieldOf(block, "type");
|
|
61
|
+
if (type === "text") {
|
|
62
|
+
const text = textOf(block);
|
|
63
|
+
if (text === undefined || text === "")
|
|
64
|
+
return undefined;
|
|
65
|
+
return `t:${digest(text)}`;
|
|
66
|
+
}
|
|
67
|
+
if (type === "reasoning") {
|
|
68
|
+
const text = textOf(block);
|
|
69
|
+
if (text === undefined || text === "")
|
|
70
|
+
return undefined;
|
|
71
|
+
return `r:${digest(text)}`;
|
|
72
|
+
}
|
|
73
|
+
if (type === "tool-call") {
|
|
74
|
+
const id = fieldOf(block, "id");
|
|
75
|
+
const name = fieldOf(block, "name");
|
|
76
|
+
const args = fieldOf(block, "arguments");
|
|
77
|
+
if (typeof id !== "string" || typeof name !== "string")
|
|
78
|
+
return undefined;
|
|
79
|
+
const argsText = typeof args === "string" ? args : JSON.stringify(args);
|
|
80
|
+
return `c:${digest(`${id}\u0000${name}\u0000${argsText}`)}`;
|
|
81
|
+
}
|
|
82
|
+
if (type === "image") {
|
|
83
|
+
const attachment = fieldOf(block, "attachment");
|
|
84
|
+
const id = attachment === null || attachment === undefined
|
|
85
|
+
? undefined
|
|
86
|
+
: fieldOf(attachment, "attachmentId");
|
|
87
|
+
return typeof id === "string" ? `i:${digest(id)}` : undefined;
|
|
88
|
+
}
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* 一条 assistant 消息的块摘要序列;含不可摘要块时返回 undefined。
|
|
93
|
+
* 空文本/空推理块跳过(两侧投影与组装对空块的取舍可能不同,空块无信息量)。
|
|
94
|
+
*/
|
|
95
|
+
function assistantDigests(message) {
|
|
96
|
+
const out = [];
|
|
97
|
+
for (const block of asArray(fieldOf(message, "content"))) {
|
|
98
|
+
const type = fieldOf(block, "type");
|
|
99
|
+
const text = textOf(block);
|
|
100
|
+
if ((type === "text" || type === "reasoning") &&
|
|
101
|
+
(text === undefined || text === ""))
|
|
102
|
+
continue;
|
|
103
|
+
const d = blockDigest(block);
|
|
104
|
+
if (d === undefined)
|
|
105
|
+
return undefined;
|
|
106
|
+
out.push(d);
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
/** 只随本轮输入投递的宿主上下文来源,包含旧历史中的上下文标记。 */
|
|
111
|
+
const PASSIVE_CONTEXT_SOURCES = new Set([
|
|
112
|
+
"context",
|
|
113
|
+
"runtime-context",
|
|
114
|
+
"agent-instructions",
|
|
115
|
+
"skill-catalog",
|
|
116
|
+
"time-context",
|
|
117
|
+
"tmux-context",
|
|
118
|
+
"session-reference",
|
|
119
|
+
"model-selection",
|
|
120
|
+
"plan-mode",
|
|
121
|
+
"user-approval",
|
|
122
|
+
"repeat-tool-reminder",
|
|
123
|
+
]);
|
|
124
|
+
/** 用户角色消息的来源可扩展。排除被动上下文,缺省来源按手工输入处理。 */
|
|
125
|
+
function inputSourceOf(message) {
|
|
126
|
+
if (message.role !== "user")
|
|
127
|
+
return undefined;
|
|
128
|
+
const kind = fieldOf(fieldOf(message, "source"), "kind");
|
|
129
|
+
if (kind === undefined)
|
|
130
|
+
return "user";
|
|
131
|
+
if (typeof kind === "string" && !PASSIVE_CONTEXT_SOURCES.has(kind))
|
|
132
|
+
return kind;
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* 对比全量历史与已投快照,切出本次应投给 Codex 的尾部增量。
|
|
137
|
+
* @param messages - 本次请求的完整对话历史。
|
|
138
|
+
* @param snapshot - 上次投递成功后记录的对齐点。
|
|
139
|
+
* @returns new-input 表示尾部是待提交的输入,包含与其一起投递的上下文;
|
|
140
|
+
* tool-results 表示尾部是工具调用与结果,应回传给挂起中的 turn;
|
|
141
|
+
* baseline-lost 表示历史缩短、前缀不同或尾部不符合增量要求,由调用方处理。
|
|
142
|
+
*/
|
|
143
|
+
export function diffIncrement(messages, snapshot) {
|
|
144
|
+
const count = snapshot.fingerprints.length;
|
|
145
|
+
if (count > messages.length)
|
|
146
|
+
return { kind: "baseline-lost", reason: "history-shrunk" };
|
|
147
|
+
for (let index = 0; index < count; index++) {
|
|
148
|
+
const message = messages[index];
|
|
149
|
+
if (message === undefined ||
|
|
150
|
+
fingerprint(message) !== snapshot.fingerprints[index])
|
|
151
|
+
return { kind: "baseline-lost", reason: "prefix-mismatch" };
|
|
152
|
+
}
|
|
153
|
+
const tail = messages.slice(count);
|
|
154
|
+
const last = tail[tail.length - 1];
|
|
155
|
+
if (last === undefined)
|
|
156
|
+
return { kind: "baseline-lost", reason: "empty-increment" };
|
|
157
|
+
if (last.role === "tool")
|
|
158
|
+
return toolResults(tail, messages.length, snapshot);
|
|
159
|
+
const lastTool = tail.findLastIndex((message) => message.role === "tool");
|
|
160
|
+
if (lastTool >= 0)
|
|
161
|
+
return toolResultsWithInput(tail, lastTool + 1, messages.length, snapshot);
|
|
162
|
+
return newUserInput(tail, messages.length, snapshot);
|
|
163
|
+
}
|
|
164
|
+
/** 将已核对的工具结果与紧随其后的输入一起交给适配器。 */
|
|
165
|
+
function toolResultsWithInput(tail, split, total, snapshot) {
|
|
166
|
+
const following = tail.slice(split);
|
|
167
|
+
if (following.some((message) => message.role === "assistant"))
|
|
168
|
+
return { kind: "baseline-lost", reason: "unexpected-tail" };
|
|
169
|
+
const input = newUserInput(following, total, snapshot, true);
|
|
170
|
+
if (input.kind === "baseline-lost")
|
|
171
|
+
return input;
|
|
172
|
+
const batch = toolResults(tail.slice(0, split), total, snapshot, true);
|
|
173
|
+
if (batch.kind === "baseline-lost")
|
|
174
|
+
return batch;
|
|
175
|
+
return { ...batch, followup: input.content };
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* 核对已生成的回复后,在同一个原生回合按原顺序提交待处理的唤醒消息和本轮输入。
|
|
179
|
+
* 尾随上下文随输入提交。排在本轮输入前的旧收尾提醒已失效。
|
|
180
|
+
*/
|
|
181
|
+
function newUserInput(tail, total, snapshot, mergeUserInputs = false) {
|
|
182
|
+
const rest = [...snapshot.delivered];
|
|
183
|
+
const lastInput = tail.findLastIndex((message) => inputSourceOf(message) !== undefined);
|
|
184
|
+
if (lastInput < 0)
|
|
185
|
+
return { kind: "baseline-lost", reason: "unexpected-tail" };
|
|
186
|
+
const content = [];
|
|
187
|
+
for (const [index, message] of tail.entries()) {
|
|
188
|
+
const source = inputSourceOf(message);
|
|
189
|
+
if (index < lastInput) {
|
|
190
|
+
if (message.role === "assistant") {
|
|
191
|
+
const digests = assistantDigests(message);
|
|
192
|
+
if (digests === undefined)
|
|
193
|
+
return { kind: "baseline-lost", reason: "history-rewritten" };
|
|
194
|
+
for (const digest of digests)
|
|
195
|
+
if (rest.shift() !== digest)
|
|
196
|
+
return { kind: "baseline-lost", reason: "history-rewritten" };
|
|
197
|
+
if (content.length > 0)
|
|
198
|
+
return { kind: "baseline-lost", reason: "unexpected-tail" };
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
if (message.role === "system" ||
|
|
202
|
+
message.role === "developer" ||
|
|
203
|
+
source === "kmh-junji:memory-reminder")
|
|
204
|
+
continue;
|
|
205
|
+
if (message.role !== "user" || (source === "user" && !mergeUserInputs))
|
|
206
|
+
return { kind: "baseline-lost", reason: "unexpected-tail" };
|
|
207
|
+
if (source === undefined && content.length === 0)
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (message.role !== "user" &&
|
|
211
|
+
message.role !== "system" &&
|
|
212
|
+
message.role !== "developer")
|
|
213
|
+
return { kind: "baseline-lost", reason: "unexpected-tail" };
|
|
214
|
+
// 唤醒消息和手工输入保留图片;随附上下文只接收文本。
|
|
215
|
+
const blocks = turnInputBlocks(message.content, source === undefined);
|
|
216
|
+
if (blocks === undefined)
|
|
217
|
+
return { kind: "baseline-lost", reason: "unsupported-input-block" };
|
|
218
|
+
const lastBlock = content.at(-1);
|
|
219
|
+
const [firstBlock, ...remainingBlocks] = blocks;
|
|
220
|
+
if (lastBlock?.type === "text" && firstBlock?.type === "text") {
|
|
221
|
+
lastBlock.text += "\n\n" + firstBlock.text;
|
|
222
|
+
content.push(...remainingBlocks);
|
|
223
|
+
}
|
|
224
|
+
else {
|
|
225
|
+
content.push(...blocks);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return {
|
|
229
|
+
kind: "new-input",
|
|
230
|
+
content,
|
|
231
|
+
consumed: total,
|
|
232
|
+
delivered: rest,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
/** 合并连续文本,保留图片相对于文本及其他图片的位置。 */
|
|
236
|
+
function turnInputBlocks(blocks, textOnly = false) {
|
|
237
|
+
const content = [];
|
|
238
|
+
const texts = [];
|
|
239
|
+
for (const block of blocks) {
|
|
240
|
+
if (block.type === "text") {
|
|
241
|
+
texts.push(block.text);
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
if (textOnly || block.type !== "image")
|
|
245
|
+
return undefined;
|
|
246
|
+
if (texts.length > 0) {
|
|
247
|
+
content.push({ type: "text", text: texts.join("\n") });
|
|
248
|
+
texts.length = 0;
|
|
249
|
+
}
|
|
250
|
+
content.push(block);
|
|
251
|
+
}
|
|
252
|
+
if (texts.length > 0 || content.length === 0)
|
|
253
|
+
content.push({ type: "text", text: texts.join("\n") });
|
|
254
|
+
return content;
|
|
255
|
+
}
|
|
256
|
+
/** 尾部识别为工具结果:收集末组 assistant 工具调用之后的全部 tool 消息。 */
|
|
257
|
+
function toolResults(tail, total, snapshot, requireMatchedBatch = false) {
|
|
258
|
+
let split = tail.length;
|
|
259
|
+
while (split > 0 && tail[split - 1]?.role === "tool")
|
|
260
|
+
split--;
|
|
261
|
+
const results = [];
|
|
262
|
+
for (const message of tail.slice(split)) {
|
|
263
|
+
if (message.role !== "tool" || typeof message.toolCallId !== "string")
|
|
264
|
+
return { kind: "baseline-lost", reason: "tool-without-call" };
|
|
265
|
+
const content = turnInputBlocks(message.content);
|
|
266
|
+
if (content === undefined)
|
|
267
|
+
return { kind: "baseline-lost", reason: "unsupported-tool-block" };
|
|
268
|
+
results.push({
|
|
269
|
+
callId: message.toolCallId,
|
|
270
|
+
content,
|
|
271
|
+
isError: message.isError === true,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
if (results.length === 0)
|
|
275
|
+
return { kind: "baseline-lost", reason: "no-results" };
|
|
276
|
+
// 增量中必须存在 assistant 工具调用记录(Codex 已自行生成);
|
|
277
|
+
// 全部为 tool 结果说明游标错位到了调用记录之前。
|
|
278
|
+
if (!tail.some((message) => message.role === "assistant"))
|
|
279
|
+
return { kind: "baseline-lost", reason: "no-call-before-results" };
|
|
280
|
+
// 尾部中已被指纹覆盖推进的 assistant 消息,其块摘要同步出队:
|
|
281
|
+
// 后续 turn 边界核对只面对尚未越过的新回复。
|
|
282
|
+
const rest = [...snapshot.delivered];
|
|
283
|
+
const callIds = new Set();
|
|
284
|
+
for (const message of tail.slice(0, split)) {
|
|
285
|
+
if (message.role !== "assistant") {
|
|
286
|
+
if (requireMatchedBatch)
|
|
287
|
+
return { kind: "baseline-lost", reason: "unexpected-tail" };
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
const digests = assistantDigests(message);
|
|
291
|
+
if (digests === undefined) {
|
|
292
|
+
if (requireMatchedBatch)
|
|
293
|
+
return { kind: "baseline-lost", reason: "digest-desync" };
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
for (const d of digests)
|
|
297
|
+
if (rest.shift() !== d)
|
|
298
|
+
return { kind: "baseline-lost", reason: "digest-desync" };
|
|
299
|
+
if (requireMatchedBatch)
|
|
300
|
+
for (const block of message.content)
|
|
301
|
+
if (block.type === "tool-call")
|
|
302
|
+
callIds.add(block.id);
|
|
303
|
+
}
|
|
304
|
+
if (requireMatchedBatch &&
|
|
305
|
+
(rest.length > 0 ||
|
|
306
|
+
results.some((result) => !callIds.delete(result.callId)) ||
|
|
307
|
+
callIds.size > 0))
|
|
308
|
+
return { kind: "baseline-lost", reason: "tool-result-mismatch" };
|
|
309
|
+
return {
|
|
310
|
+
kind: "tool-results",
|
|
311
|
+
results,
|
|
312
|
+
consumed: total,
|
|
313
|
+
delivered: rest,
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
/** 计算推进到 total 条后的新快照。 */
|
|
317
|
+
export function snapshotAt(messages, total, delivered = []) {
|
|
318
|
+
const fingerprints = [];
|
|
319
|
+
for (let index = 0; index < total; index++) {
|
|
320
|
+
const message = messages[index];
|
|
321
|
+
if (message !== undefined)
|
|
322
|
+
fingerprints.push(fingerprint(message));
|
|
323
|
+
}
|
|
324
|
+
return { fingerprints, delivered: [...delivered] };
|
|
325
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** 实际像素尺寸。 */
|
|
2
|
+
export interface PixelSize {
|
|
3
|
+
width: number;
|
|
4
|
+
height: number;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* 从 PNG 字节读取实际像素尺寸(IHDR 宽高,大端 uint32)。
|
|
8
|
+
* @param data - 产物文件字节。
|
|
9
|
+
* @returns PNG 且 IHDR 可读时返回宽高;否则 undefined(不构成错误)。
|
|
10
|
+
*/
|
|
11
|
+
export declare function pngSizeOf(data: Buffer): PixelSize | undefined;
|
|
12
|
+
/** 用户输入中的明确像素尺寸要求。 */
|
|
13
|
+
export type SizeRequirement = PixelSize;
|
|
14
|
+
/**
|
|
15
|
+
* 从用户输入识别明确像素尺寸要求(R3 从简:识别只用于如实报告,
|
|
16
|
+
* 无副作用,偶发误识别仅多一句附注)。
|
|
17
|
+
* @param text - 本回合用户输入文本。
|
|
18
|
+
* @returns 出现宽×高数字对时返回该尺寸;否则 undefined。
|
|
19
|
+
*/
|
|
20
|
+
export declare function imageSizeRequirementOf(text: string): SizeRequirement | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* 构造随图片展示的尺寸报告:始终报实际像素尺寸;存在明确要求且不符时
|
|
23
|
+
* 如实说明未满足(R3 从简:不自动另存改尺寸副本,原图可保存)。
|
|
24
|
+
* @param actual - 产物实际尺寸;无法解析时为 undefined,报告改用占位说明。
|
|
25
|
+
* @param requirement - 用户明确要求的尺寸;无要求时为 undefined。
|
|
26
|
+
* @returns 报告文本。
|
|
27
|
+
*/
|
|
28
|
+
export declare function imageSizeNote(actual: PixelSize | undefined, requirement: SizeRequirement | undefined): string;
|
|
29
|
+
/**
|
|
30
|
+
* 构造产物接入失败的双态报告:生成成功(Codex 侧)与接入失败(KMH 侧)
|
|
31
|
+
* 分开陈述,并给出原生产物路径作为恢复入口。
|
|
32
|
+
* @param path - Codex 侧已落盘的原生产物路径。
|
|
33
|
+
* @param reason - 接入失败原因。
|
|
34
|
+
* @returns 报告文本。
|
|
35
|
+
*/
|
|
36
|
+
export declare function imageFailureNote(path: string, reason: string): string;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** 生图产物验收(feat10,R3 从简版):PNG 实际尺寸解析与明确尺寸要求识别。 */
|
|
2
|
+
/** PNG 文件签名(前 8 字节)。 */
|
|
3
|
+
const PNG_SIGNATURE = Buffer.from([
|
|
4
|
+
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
|
5
|
+
]);
|
|
6
|
+
/**
|
|
7
|
+
* 从 PNG 字节读取实际像素尺寸(IHDR 宽高,大端 uint32)。
|
|
8
|
+
* @param data - 产物文件字节。
|
|
9
|
+
* @returns PNG 且 IHDR 可读时返回宽高;否则 undefined(不构成错误)。
|
|
10
|
+
*/
|
|
11
|
+
export function pngSizeOf(data) {
|
|
12
|
+
if (data.length < 24 || !data.subarray(0, 8).equals(PNG_SIGNATURE))
|
|
13
|
+
return undefined;
|
|
14
|
+
const width = data.readUInt32BE(16);
|
|
15
|
+
const height = data.readUInt32BE(20);
|
|
16
|
+
if (width === 0 || height === 0)
|
|
17
|
+
return undefined;
|
|
18
|
+
return { width, height };
|
|
19
|
+
}
|
|
20
|
+
/** 宽×高数字对(允许 x/×/* 与空白变体);2–5 位数字排除棋盘行列类单数字对。 */
|
|
21
|
+
const SIZE_PAIR = /(\d{2,5})\s*[x×*]\s*(\d{2,5})/i;
|
|
22
|
+
/**
|
|
23
|
+
* 从用户输入识别明确像素尺寸要求(R3 从简:识别只用于如实报告,
|
|
24
|
+
* 无副作用,偶发误识别仅多一句附注)。
|
|
25
|
+
* @param text - 本回合用户输入文本。
|
|
26
|
+
* @returns 出现宽×高数字对时返回该尺寸;否则 undefined。
|
|
27
|
+
*/
|
|
28
|
+
export function imageSizeRequirementOf(text) {
|
|
29
|
+
const match = SIZE_PAIR.exec(text);
|
|
30
|
+
if (match === null)
|
|
31
|
+
return undefined;
|
|
32
|
+
const width = Number(match[1]);
|
|
33
|
+
const height = Number(match[2]);
|
|
34
|
+
if (!Number.isInteger(width) || !Number.isInteger(height))
|
|
35
|
+
return undefined;
|
|
36
|
+
return { width, height };
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* 构造随图片展示的尺寸报告:始终报实际像素尺寸;存在明确要求且不符时
|
|
40
|
+
* 如实说明未满足(R3 从简:不自动另存改尺寸副本,原图可保存)。
|
|
41
|
+
* @param actual - 产物实际尺寸;无法解析时为 undefined,报告改用占位说明。
|
|
42
|
+
* @param requirement - 用户明确要求的尺寸;无要求时为 undefined。
|
|
43
|
+
* @returns 报告文本。
|
|
44
|
+
*/
|
|
45
|
+
export function imageSizeNote(actual, requirement) {
|
|
46
|
+
const actualText = actual === undefined
|
|
47
|
+
? "未知(产物非 PNG 或元数据不可读)"
|
|
48
|
+
: `${actual.width}×${actual.height}`;
|
|
49
|
+
if (requirement === undefined ||
|
|
50
|
+
(actual !== undefined &&
|
|
51
|
+
actual.width === requirement.width &&
|
|
52
|
+
actual.height === requirement.height))
|
|
53
|
+
return `图片实际尺寸 ${actualText} 像素。`;
|
|
54
|
+
return `图片实际尺寸 ${actualText} 像素,与要求的 ${requirement.width}×${requirement.height} 不符(未改尺寸另存,原图可直接保存)。`;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* 构造产物接入失败的双态报告:生成成功(Codex 侧)与接入失败(KMH 侧)
|
|
58
|
+
* 分开陈述,并给出原生产物路径作为恢复入口。
|
|
59
|
+
* @param path - Codex 侧已落盘的原生产物路径。
|
|
60
|
+
* @param reason - 接入失败原因。
|
|
61
|
+
* @returns 报告文本。
|
|
62
|
+
*/
|
|
63
|
+
export function imageFailureNote(path, reason) {
|
|
64
|
+
return `图片已由 Codex 生成并保存(${path}),但 KMH 产物接入失败:${reason}。可从原生产物路径恢复。`;
|
|
65
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** 独立订阅生图执行器:复用 CLI 连接与隔离,读取原生产图,返回前等待进程回收。 */
|
|
2
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import type { Config } from "./config.ts";
|
|
5
|
+
export { Config } from "./config.ts";
|
|
6
|
+
/** 专用服务请求;模型和执行时限由部署者配置。 */
|
|
7
|
+
export declare const ImageRequest: z.ZodObject<{
|
|
8
|
+
prompt: z.ZodString;
|
|
9
|
+
}, z.core.$strict>;
|
|
10
|
+
export type ImageRequest = z.infer<typeof ImageRequest>;
|
|
11
|
+
/** 已验收的原生 PNG 字节;调用方负责持久保存。 */
|
|
12
|
+
export interface GeneratedImage {
|
|
13
|
+
data: Buffer;
|
|
14
|
+
width: number;
|
|
15
|
+
height: number;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* 使用本机 ChatGPT 登录执行一次生图;signal 中止或 CLI 出错时抛出错误类别。
|
|
19
|
+
* 返回的字节来自本次 thread 的 generated_images 目录,返回前已释放全部 CLI 进程。
|
|
20
|
+
*/
|
|
21
|
+
export declare function generateImage(ctx: Context, config: Config, input: ImageRequest, signal: AbortSignal): Promise<GeneratedImage>;
|