@ktkid/kmh-codex-cli 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +296 -2
- package/bin/README.md +25 -0
- package/bin/codex +36 -0
- package/bin/runtime-receipt.json +9 -0
- package/bin/version +1 -0
- package/cordis.patch.yml +7 -0
- package/lib/browser-types/src/account-status.d.ts +9 -0
- package/lib/browser-types/src/client/ComposerQuota.d.ts +10 -0
- package/lib/browser-types/src/client/DetailCard.d.ts +12 -0
- package/lib/browser-types/src/client/LiveBall.d.ts +19 -0
- package/lib/browser-types/src/client/QuotaCard.d.ts +20 -0
- package/lib/browser-types/src/client/QuotaDisplaySettings.d.ts +6 -0
- package/lib/browser-types/src/client/index.d.ts +18 -0
- package/lib/browser-types/src/client/locales.d.ts +54 -0
- package/lib/browser-types/src/client/quota-store.d.ts +56 -0
- package/lib/browser-types/src/live-state.d.ts +31 -0
- package/lib/browser-types/src/quota-protocol.d.ts +135 -0
- package/lib/browser-types/src/quota-rules.d.ts +18 -0
- package/lib/browser-types/src/tool-switches.d.ts +63 -0
- package/lib/client.js +16193 -0
- package/lib/src/account-status.d.ts +9 -0
- package/lib/src/account-status.js +1 -0
- package/lib/src/account.d.ts +35 -0
- package/lib/src/account.js +173 -0
- package/lib/src/adapter.d.ts +22 -0
- package/lib/src/adapter.js +222 -0
- package/lib/src/approval.d.ts +48 -0
- package/lib/src/approval.js +235 -0
- package/lib/src/capabilities.d.ts +40 -0
- package/lib/src/capabilities.js +85 -0
- package/lib/src/config.d.ts +69 -0
- package/lib/src/config.js +75 -0
- package/lib/src/connection.d.ts +65 -0
- package/lib/src/connection.js +178 -0
- package/lib/src/cursor.d.ts +61 -0
- package/lib/src/cursor.js +339 -0
- package/lib/src/image-delivery.d.ts +36 -0
- package/lib/src/image-delivery.js +65 -0
- package/lib/src/imagegen.d.ts +21 -0
- package/lib/src/imagegen.js +132 -0
- package/lib/src/index.d.ts +146 -0
- package/lib/src/index.js +551 -0
- package/lib/src/isolation.d.ts +61 -0
- package/lib/src/isolation.js +298 -0
- package/lib/src/live-state.d.ts +31 -0
- package/lib/src/live-state.js +14 -0
- package/lib/src/models.d.ts +24 -0
- package/lib/src/models.js +98 -0
- package/lib/src/native-items.d.ts +59 -0
- package/lib/src/native-items.js +122 -0
- package/lib/src/native-tools/catalog.d.ts +29 -0
- package/lib/src/native-tools/catalog.js +197 -0
- package/lib/src/probe.d.ts +17 -0
- package/lib/src/probe.js +54 -0
- package/lib/src/protocol.d.ts +508 -0
- package/lib/src/protocol.js +511 -0
- package/lib/src/quota-protocol.d.ts +135 -0
- package/lib/src/quota-protocol.js +97 -0
- package/lib/src/quota-rules.d.ts +18 -0
- package/lib/src/quota-rules.js +49 -0
- package/lib/src/quota.d.ts +32 -0
- package/lib/src/quota.js +227 -0
- package/lib/src/session-history.d.ts +18 -0
- package/lib/src/session-history.js +113 -0
- package/lib/src/session-store.d.ts +592 -0
- package/lib/src/session-store.js +275 -0
- package/lib/src/status.d.ts +19 -0
- package/lib/src/status.js +69 -0
- package/lib/src/tool-policy.d.ts +47 -0
- package/lib/src/tool-policy.js +454 -0
- package/lib/src/tool-registry.d.ts +42 -0
- package/lib/src/tool-registry.js +70 -0
- package/lib/src/tool-selection.d.ts +88 -0
- package/lib/src/tool-selection.js +60 -0
- package/lib/src/tool-switches-service.d.ts +24 -0
- package/lib/src/tool-switches-service.js +129 -0
- package/lib/src/tool-switches.d.ts +63 -0
- package/lib/src/tool-switches.js +43 -0
- package/lib/src/turn.d.ts +200 -0
- package/lib/src/turn.js +1012 -0
- package/lib/src/web.d.ts +9 -0
- package/lib/src/web.js +143 -0
- package/package.json +172 -4
- package/vendor/codex/LICENSE +201 -0
- package/vendor/codex/NOTICE +4 -0
- package/vendor/codex/models.json +1613 -0
- package/vendor/native-tools/0.162.0-alpha.17.2.json +143 -0
- package/vendor/native-tools/0.163.0-alpha.10.2.json +128 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** 详情页与 Host 共享的账号状态类型(浏览器侧安全,不含凭据值)。 */
|
|
2
|
+
export interface AccountStatus {
|
|
3
|
+
login: "signed-in" | "idle" | "starting" | "waiting" | "failed";
|
|
4
|
+
/** 凭据来源说明(路径级,不含内容)。 */
|
|
5
|
+
credentialSource?: string;
|
|
6
|
+
/** 进行中登录的授权链接。 */
|
|
7
|
+
authorizeUrl?: string;
|
|
8
|
+
error?: string;
|
|
9
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** 官方账号状态与登录转发:凭据由官方 CLI 保存于用户 Codex home,插件只读判定。 */
|
|
2
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
3
|
+
import type { Config } from "./config.ts";
|
|
4
|
+
import type { AccountStatus } from "./account-status.ts";
|
|
5
|
+
export type { AccountStatus };
|
|
6
|
+
/**
|
|
7
|
+
* 账号操作:状态按本地凭据存在性判定(不发请求);登录经官方 CLI 的
|
|
8
|
+
* account/login/start 打开授权页并等待完成通知;退出转发 account/logout。
|
|
9
|
+
*/
|
|
10
|
+
export declare class CodexAccount {
|
|
11
|
+
private readonly ctx;
|
|
12
|
+
private readonly config;
|
|
13
|
+
private state;
|
|
14
|
+
private active;
|
|
15
|
+
constructor(ctx: Context, config: Config);
|
|
16
|
+
/**
|
|
17
|
+
* 当前账号状态:仅检查本地凭据文件存在性与可解析性,不发起任何请求。
|
|
18
|
+
*/
|
|
19
|
+
status(): Promise<AccountStatus>;
|
|
20
|
+
/**
|
|
21
|
+
* 开始一次官方授权登录;重复调用共享进行中的尝试。
|
|
22
|
+
* @returns 安全状态:含授权链接,等待 account/login/completed。
|
|
23
|
+
*/
|
|
24
|
+
login(): Promise<AccountStatus>;
|
|
25
|
+
/**
|
|
26
|
+
* 取消进行中的登录尝试。
|
|
27
|
+
* @returns 取消后的状态;无进行中尝试时为 no-op。
|
|
28
|
+
*/
|
|
29
|
+
cancel(): Promise<AccountStatus>;
|
|
30
|
+
/**
|
|
31
|
+
* 退出当前 Codex CLI 账号(作用于用户 Codex home 的登录态)。
|
|
32
|
+
* 验收约定:本操作不执行真实退出验证,仅保证协议调用路径正确。
|
|
33
|
+
*/
|
|
34
|
+
logout(): Promise<AccountStatus>;
|
|
35
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { readFile, stat } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { connectCodex } from "./connection.js";
|
|
5
|
+
import { Incoming } from "./protocol.js";
|
|
6
|
+
/** 用户默认 Codex home 下的凭据文件。 */
|
|
7
|
+
function authFilePath() {
|
|
8
|
+
return join(homedir(), ".codex", "auth.json");
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* 账号操作:状态按本地凭据存在性判定(不发请求);登录经官方 CLI 的
|
|
12
|
+
* account/login/start 打开授权页并等待完成通知;退出转发 account/logout。
|
|
13
|
+
*/
|
|
14
|
+
export class CodexAccount {
|
|
15
|
+
ctx;
|
|
16
|
+
config;
|
|
17
|
+
state = { login: "idle" };
|
|
18
|
+
active;
|
|
19
|
+
constructor(ctx, config) {
|
|
20
|
+
this.ctx = ctx;
|
|
21
|
+
this.config = config;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* 当前账号状态:仅检查本地凭据文件存在性与可解析性,不发起任何请求。
|
|
25
|
+
*/
|
|
26
|
+
async status() {
|
|
27
|
+
if (this.active !== undefined)
|
|
28
|
+
return { ...this.state };
|
|
29
|
+
try {
|
|
30
|
+
await stat(authFilePath());
|
|
31
|
+
const text = await readFile(authFilePath(), "utf8");
|
|
32
|
+
JSON.parse(typeof text === "string" ? text : "");
|
|
33
|
+
this.state = {
|
|
34
|
+
login: "signed-in",
|
|
35
|
+
credentialSource: "~/.codex/auth.json(Codex 原生登录)",
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
this.state = { login: "idle" };
|
|
40
|
+
}
|
|
41
|
+
return { ...this.state };
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* 开始一次官方授权登录;重复调用共享进行中的尝试。
|
|
45
|
+
* @returns 安全状态:含授权链接,等待 account/login/completed。
|
|
46
|
+
*/
|
|
47
|
+
async login() {
|
|
48
|
+
if (this.active !== undefined)
|
|
49
|
+
return { ...this.state };
|
|
50
|
+
this.state = { login: "starting" };
|
|
51
|
+
const signal = AbortSignal.timeout(this.config.loginTimeoutMs);
|
|
52
|
+
try {
|
|
53
|
+
const connection = await connectCodex(this.ctx, {
|
|
54
|
+
command: this.config.command,
|
|
55
|
+
cwd: this.config.cwd,
|
|
56
|
+
configOverrides: [],
|
|
57
|
+
env: this.config.env,
|
|
58
|
+
graceMs: this.config.graceMs,
|
|
59
|
+
startupTimeoutMs: this.config.startupTimeoutMs,
|
|
60
|
+
}, signal);
|
|
61
|
+
this.active = { connection };
|
|
62
|
+
const completion = new Promise((resolve, reject) => {
|
|
63
|
+
connection.onNotification((method, params) => {
|
|
64
|
+
if (method !== Incoming.accountLoginCompleted)
|
|
65
|
+
return;
|
|
66
|
+
const success = params.success === true;
|
|
67
|
+
const error = typeof params.error === "string" ? params.error : undefined;
|
|
68
|
+
resolve(success
|
|
69
|
+
? {
|
|
70
|
+
login: "signed-in",
|
|
71
|
+
credentialSource: "~/.codex/auth.json(Codex 原生登录)",
|
|
72
|
+
}
|
|
73
|
+
: { login: "failed", error: error ?? "CODEX_LOGIN_FAILED" });
|
|
74
|
+
});
|
|
75
|
+
signal.addEventListener("abort", () => reject(new Error("CODEX_LOGIN_TIMEOUT")));
|
|
76
|
+
});
|
|
77
|
+
const raw = await connection.request("account/login/start", { type: "chatgpt" }, signal);
|
|
78
|
+
const authUrl = extractAuthUrl(raw);
|
|
79
|
+
const loginId = extractLoginId(raw);
|
|
80
|
+
if (authUrl === undefined)
|
|
81
|
+
throw new Error("CODEX_LOGIN_URL_MISSING");
|
|
82
|
+
if (loginId !== undefined)
|
|
83
|
+
this.active.loginId = loginId;
|
|
84
|
+
this.state = {
|
|
85
|
+
login: "waiting",
|
|
86
|
+
...(authUrl === undefined ? {} : { authorizeUrl: authUrl }),
|
|
87
|
+
};
|
|
88
|
+
const final = await completion;
|
|
89
|
+
this.state = final;
|
|
90
|
+
return {
|
|
91
|
+
...final,
|
|
92
|
+
...(authUrl === undefined ? {} : { authorizeUrl: authUrl }),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
this.state = {
|
|
97
|
+
login: "failed",
|
|
98
|
+
error: /^CODEX_[A-Z_]+/.test(error instanceof Error ? error.message : String(error))
|
|
99
|
+
? error instanceof Error
|
|
100
|
+
? error.message
|
|
101
|
+
: String(error)
|
|
102
|
+
: "CODEX_LOGIN_FAILED",
|
|
103
|
+
};
|
|
104
|
+
return { ...this.state };
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
const active = this.active;
|
|
108
|
+
this.active = undefined;
|
|
109
|
+
if (active !== undefined)
|
|
110
|
+
await active.connection.stop(this.config.cleanupTimeoutMs);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* 取消进行中的登录尝试。
|
|
115
|
+
* @returns 取消后的状态;无进行中尝试时为 no-op。
|
|
116
|
+
*/
|
|
117
|
+
async cancel() {
|
|
118
|
+
const active = this.active;
|
|
119
|
+
if (active?.loginId !== undefined) {
|
|
120
|
+
try {
|
|
121
|
+
await active.connection.request("account/login/cancel", { loginId: active.loginId }, AbortSignal.timeout(this.config.cancelReceiptTimeoutMs));
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
// 取消失败不阻断:连接随后关闭即终止等待。
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (this.active !== undefined) {
|
|
128
|
+
this.state = { login: "idle" };
|
|
129
|
+
this.active = undefined;
|
|
130
|
+
await active?.connection.stop(this.config.cleanupTimeoutMs);
|
|
131
|
+
}
|
|
132
|
+
return await this.status();
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* 退出当前 Codex CLI 账号(作用于用户 Codex home 的登录态)。
|
|
136
|
+
* 验收约定:本操作不执行真实退出验证,仅保证协议调用路径正确。
|
|
137
|
+
*/
|
|
138
|
+
async logout() {
|
|
139
|
+
const signal = AbortSignal.timeout(this.config.probeTimeoutMs);
|
|
140
|
+
const connection = await connectCodex(this.ctx, {
|
|
141
|
+
command: this.config.command,
|
|
142
|
+
cwd: this.config.cwd,
|
|
143
|
+
configOverrides: [],
|
|
144
|
+
env: this.config.env,
|
|
145
|
+
graceMs: this.config.graceMs,
|
|
146
|
+
startupTimeoutMs: this.config.startupTimeoutMs,
|
|
147
|
+
}, signal);
|
|
148
|
+
try {
|
|
149
|
+
await connection.request("account/logout", {}, signal);
|
|
150
|
+
}
|
|
151
|
+
finally {
|
|
152
|
+
await connection.stop(this.config.cleanupTimeoutMs);
|
|
153
|
+
}
|
|
154
|
+
return await this.status();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/** 从 login/start 响应提取授权链接(chatgpt / chatgptDeviceCode 两形态)。 */
|
|
158
|
+
function extractAuthUrl(value) {
|
|
159
|
+
const url = fieldOf(value, "authUrl") ?? fieldOf(value, "verificationUrl");
|
|
160
|
+
return typeof url === "string" && url.length > 0 ? url : undefined;
|
|
161
|
+
}
|
|
162
|
+
function extractLoginId(value) {
|
|
163
|
+
const id = fieldOf(value, "loginId");
|
|
164
|
+
return typeof id === "string" ? id : undefined;
|
|
165
|
+
}
|
|
166
|
+
function fieldOf(value, key) {
|
|
167
|
+
if (value === null || typeof value !== "object")
|
|
168
|
+
return undefined;
|
|
169
|
+
for (const [name, item] of Object.entries(value))
|
|
170
|
+
if (name === key)
|
|
171
|
+
return item;
|
|
172
|
+
return undefined;
|
|
173
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Codex 模型提供方 adapter:差分投递、动态工具桥与流式投影。 */
|
|
2
|
+
import { LlmAdapter, type GenerateOptions, type LlmModelInfo, type LlmResolvedModelInfo, type StreamChunk } from "@deepseek-ai/dsh-llm";
|
|
3
|
+
import type { CodexCli } from "./index.ts";
|
|
4
|
+
/**
|
|
5
|
+
* 注册为 `codex-cli` 提供方的适配器。一次 stream 调用映射为 Codex turn 的
|
|
6
|
+
* 一段生成:新用户输入发起 turn,工具结果回传续推挂起的 turn;
|
|
7
|
+
* 全量历史经差分游标只投增量。
|
|
8
|
+
*/
|
|
9
|
+
export declare class CodexAdapter extends LlmAdapter {
|
|
10
|
+
private readonly runtime;
|
|
11
|
+
constructor(runtime: CodexCli);
|
|
12
|
+
providerInfo(provider: string): {
|
|
13
|
+
id: string;
|
|
14
|
+
name: string;
|
|
15
|
+
};
|
|
16
|
+
listModels(provider: string): Promise<readonly LlmModelInfo[]>;
|
|
17
|
+
resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo>;
|
|
18
|
+
/** 接受宿主各生产插件声明的辅助请求 purpose;请求转发独立于生产插件的类型扩展。 */
|
|
19
|
+
stream(options: GenerateOptions<string>): AsyncIterable<StreamChunk>;
|
|
20
|
+
/** 驱动一次差分投递与流投影。 */
|
|
21
|
+
private drive;
|
|
22
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/** Codex 模型提供方 adapter:差分投递、动态工具桥与流式投影。 */
|
|
2
|
+
import { LlmAdapter, LlmError, } from "@deepseek-ai/dsh-llm";
|
|
3
|
+
import { diffIncrement, snapshotAt, emptySnapshot, } from "./cursor.js";
|
|
4
|
+
import { resolveLlmModel, toLlmModels } from "./models.js";
|
|
5
|
+
import { toolDeclarationNote } from "./tool-registry.js";
|
|
6
|
+
/**
|
|
7
|
+
* 注册为 `codex-cli` 提供方的适配器。一次 stream 调用映射为 Codex turn 的
|
|
8
|
+
* 一段生成:新用户输入发起 turn,工具结果回传续推挂起的 turn;
|
|
9
|
+
* 全量历史经差分游标只投增量。
|
|
10
|
+
*/
|
|
11
|
+
export class CodexAdapter extends LlmAdapter {
|
|
12
|
+
runtime;
|
|
13
|
+
constructor(runtime) {
|
|
14
|
+
super();
|
|
15
|
+
this.runtime = runtime;
|
|
16
|
+
}
|
|
17
|
+
providerInfo(provider) {
|
|
18
|
+
return { id: provider, name: "KMH / Codex CLI" };
|
|
19
|
+
}
|
|
20
|
+
async listModels(provider) {
|
|
21
|
+
return toLlmModels(provider, await this.runtime.catalog());
|
|
22
|
+
}
|
|
23
|
+
async resolveModel(provider, model) {
|
|
24
|
+
if (provider !== "codex-cli")
|
|
25
|
+
throw new LlmError("Codex model route is unavailable", "INVALID_MODEL");
|
|
26
|
+
const entries = await this.runtime.catalog();
|
|
27
|
+
const entry = entries.find((candidate) => candidate.id === model);
|
|
28
|
+
if (entry === undefined)
|
|
29
|
+
throw new LlmError(`Unknown Codex model: ${model}`, "INVALID_MODEL");
|
|
30
|
+
return resolveLlmModel(provider, entry, this.runtime.config.defaultMaxTokens);
|
|
31
|
+
}
|
|
32
|
+
/** 接受宿主各生产插件声明的辅助请求 purpose;请求转发独立于生产插件的类型扩展。 */
|
|
33
|
+
async *stream(options) {
|
|
34
|
+
if (options.provider !== "codex-cli")
|
|
35
|
+
throw new LlmError("Codex model route is unavailable", "INVALID_MODEL");
|
|
36
|
+
if (options.temperature !== undefined)
|
|
37
|
+
throw new LlmError("Codex app-server does not accept temperature", "INVALID_ARGS");
|
|
38
|
+
if (options.stop !== undefined)
|
|
39
|
+
throw new LlmError("Codex app-server does not accept stop sequences", "INVALID_ARGS");
|
|
40
|
+
const deadline = AbortSignal.timeout(this.runtime.config.requestTimeoutMs);
|
|
41
|
+
const signal = options.signal === undefined
|
|
42
|
+
? deadline
|
|
43
|
+
: AbortSignal.any([options.signal, deadline]);
|
|
44
|
+
const request = { ...options, signal };
|
|
45
|
+
const sessionKey = options.sessionId === undefined
|
|
46
|
+
? "kmh-codex-anonymous"
|
|
47
|
+
: String(options.sessionId);
|
|
48
|
+
try {
|
|
49
|
+
// 辅助请求与主对话共用单次请求时限。
|
|
50
|
+
if (options.purpose === "session-title" ||
|
|
51
|
+
options.purpose === "compaction") {
|
|
52
|
+
yield* this.runtime.streamAuxiliary(request);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
yield* this.runtime.withSession(sessionKey, this.runtime.resolveCwd(options.sessionId), (turn) => this.drive(turn, request), signal);
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (signal.aborted) {
|
|
59
|
+
if (signal.reason === deadline.reason && deadline.aborted)
|
|
60
|
+
throw new LlmError(`CODEX_REQUEST_TIMEOUT: ${this.runtime.config.requestTimeoutMs}ms`, "CODEX_REQUEST_TIMEOUT");
|
|
61
|
+
throw new LlmError("Codex request stopped", "ABORTED");
|
|
62
|
+
}
|
|
63
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
64
|
+
const code = /^CODEX_[A-Z_]+/.test(message)
|
|
65
|
+
? (message.split(":")[0] ?? "CODEX_REQUEST_FAILED")
|
|
66
|
+
: "CODEX_REQUEST_FAILED";
|
|
67
|
+
throw new LlmError(message, code);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** 驱动一次差分投递与流投影。 */
|
|
71
|
+
async *drive(turn, options) {
|
|
72
|
+
const sessionKey = options.sessionId === undefined
|
|
73
|
+
? "kmh-codex-anonymous"
|
|
74
|
+
: String(options.sessionId);
|
|
75
|
+
const signal = options.signal ?? new AbortController().signal;
|
|
76
|
+
const preparedPolicy = this.runtime.toolPolicy?.forStream(options);
|
|
77
|
+
// 只把创建时冻结选择中开启的 Harness 工具交给 Codex;辅助请求原样传递。
|
|
78
|
+
const tools = (options.tools ?? []).filter((tool) => preparedPolicy === undefined ||
|
|
79
|
+
preparedPolicy.names.includes(tool.name));
|
|
80
|
+
const startInput = {
|
|
81
|
+
policyFingerprint: preparedPolicy?.fingerprint,
|
|
82
|
+
model: options.model,
|
|
83
|
+
// 业务工具使用创建时选择,独立技能由策略按本回合读取。
|
|
84
|
+
selection: preparedPolicy?.native ?? this.runtime.settings.selection,
|
|
85
|
+
// 会话身份与权限档(D17/feat09):审批桥取活跃 Agent、-c 映射档位。
|
|
86
|
+
sessionId: options.sessionId,
|
|
87
|
+
permission: this.runtime.resolvePermission(options.sessionId),
|
|
88
|
+
reasoningEffort: options.reasoningEffort,
|
|
89
|
+
baseInstructions: systemPromptOf(options),
|
|
90
|
+
// D13:不改写提示正文(整词替换会改普通词义),以一段声明约定说明
|
|
91
|
+
// 指明 KMH 工具名与 kmh- 前缀声明名的对应关系。
|
|
92
|
+
developerInstructions: tools.length > 0 ? toolDeclarationNote() : undefined,
|
|
93
|
+
tools: tools.map((tool) => ({
|
|
94
|
+
name: tool.name,
|
|
95
|
+
description: tool.description,
|
|
96
|
+
inputSchema: tool.parameters,
|
|
97
|
+
})),
|
|
98
|
+
};
|
|
99
|
+
const record = await this.runtime.bindingRecord(sessionKey);
|
|
100
|
+
const source = record?.threadId === undefined
|
|
101
|
+
? await this.runtime.sourceBinding(options.sessionId)
|
|
102
|
+
: undefined;
|
|
103
|
+
let plan;
|
|
104
|
+
const evidence = this.runtime.historyEvidence(options.sessionId);
|
|
105
|
+
let increment = diffIncrement(options.messages, {
|
|
106
|
+
fingerprints: turn.cursor.fingerprints,
|
|
107
|
+
delivered: turn.pendingDigests,
|
|
108
|
+
}, evidence);
|
|
109
|
+
if (source?.threadId !== undefined) {
|
|
110
|
+
plan = forkPlanOf(source, options.messages, evidence);
|
|
111
|
+
increment = plan.increment;
|
|
112
|
+
}
|
|
113
|
+
else if (increment.kind === "baseline-lost") {
|
|
114
|
+
if (record?.threadId === undefined ||
|
|
115
|
+
!["prefix-mismatch", "history-shrunk", "history-rewritten"].includes(increment.reason)) {
|
|
116
|
+
throw new Error(`CODEX_SESSION_HISTORY_MISMATCH: ${increment.reason}`);
|
|
117
|
+
}
|
|
118
|
+
plan = forkPlanOf(record, options.messages, evidence);
|
|
119
|
+
increment = plan.increment;
|
|
120
|
+
}
|
|
121
|
+
const consumed = increment.consumed;
|
|
122
|
+
const saveCursor = async () => {
|
|
123
|
+
turn.cursor = snapshotAt(options.messages, consumed, turn.pendingDigests);
|
|
124
|
+
await this.runtime.recordBinding(sessionKey, turn);
|
|
125
|
+
};
|
|
126
|
+
const pending = turn.pendingCallIds().length;
|
|
127
|
+
if (increment.kind === "new-input" ||
|
|
128
|
+
(increment.followup !== undefined &&
|
|
129
|
+
pending === 0 &&
|
|
130
|
+
record?.threadId !== undefined)) {
|
|
131
|
+
if (pending > 0)
|
|
132
|
+
throw new Error("CODEX_TOOL_PENDING");
|
|
133
|
+
const content = increment.kind === "new-input"
|
|
134
|
+
? increment.content
|
|
135
|
+
: [
|
|
136
|
+
// 原生工具连接已结束。用模型上下文补交已保存结果,避免重跑工具或重复回执。
|
|
137
|
+
...increment.results.flatMap((result) => [
|
|
138
|
+
{
|
|
139
|
+
type: "text",
|
|
140
|
+
text: `KMH recorded this tool result before the native turn stopped (${result.callId}, ${result.isError ? "error" : "success"}):`,
|
|
141
|
+
},
|
|
142
|
+
...result.content,
|
|
143
|
+
]),
|
|
144
|
+
...(increment.followup ?? []),
|
|
145
|
+
];
|
|
146
|
+
const input = { ...startInput, content };
|
|
147
|
+
if (plan !== undefined) {
|
|
148
|
+
await turn.dispose();
|
|
149
|
+
turn.cursor = plan.cursor;
|
|
150
|
+
turn.pendingDigests = [...plan.cursor.delivered];
|
|
151
|
+
turn.lastCompletedTurnId = plan.turns.at(-1)?.turnId;
|
|
152
|
+
await turn.rebuild(input, plan.source, signal, async () => this.runtime.recordBinding(sessionKey, turn, plan?.turns));
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
await turn.start(input, record?.threadId, signal, async () => this.runtime.recordBinding(sessionKey, turn));
|
|
156
|
+
}
|
|
157
|
+
turn.pendingDigests = [...increment.delivered, ...turn.pendingDigests];
|
|
158
|
+
// 原生确认接纳后立即推进;中断仍保留输入已投递的事实。
|
|
159
|
+
await saveCursor();
|
|
160
|
+
yield* turn.pump(signal);
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
turn.pendingDigests = [...increment.delivered];
|
|
164
|
+
yield* turn.resumeWithToolResults(increment.results, signal, increment.followup === undefined
|
|
165
|
+
? undefined
|
|
166
|
+
: { content: increment.followup, onAccepted: saveCursor });
|
|
167
|
+
}
|
|
168
|
+
await saveCursor();
|
|
169
|
+
if (turn.terminated)
|
|
170
|
+
this.runtime.releaseSession(turn);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/** 根据源回合已接受的消息位置选择精确的原生回合切点。 */
|
|
174
|
+
function forkPlanOf(record, messages, evidence) {
|
|
175
|
+
const threadId = record.threadId;
|
|
176
|
+
if (threadId === undefined)
|
|
177
|
+
throw new Error("CODEX_FORK_SOURCE_MISSING");
|
|
178
|
+
const turns = record.turns ?? [];
|
|
179
|
+
for (let index = turns.length - 1; index >= 0; index--) {
|
|
180
|
+
const turn = turns[index];
|
|
181
|
+
if (turn === undefined)
|
|
182
|
+
continue;
|
|
183
|
+
const cursor = {
|
|
184
|
+
fingerprints: turn.fingerprints,
|
|
185
|
+
delivered: turn.delivered,
|
|
186
|
+
};
|
|
187
|
+
const increment = diffIncrement(messages, cursor, evidence);
|
|
188
|
+
if (increment.kind === "new-input")
|
|
189
|
+
return {
|
|
190
|
+
source: { threadId, lastTurnId: turn.turnId },
|
|
191
|
+
cursor,
|
|
192
|
+
turns: turns.slice(0, index + 1),
|
|
193
|
+
increment,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
const cursor = emptySnapshot();
|
|
197
|
+
const increment = diffIncrement(messages, cursor);
|
|
198
|
+
const first = turns[0];
|
|
199
|
+
if (increment.kind === "new-input" && first !== undefined)
|
|
200
|
+
return {
|
|
201
|
+
source: { threadId, beforeTurnId: first.turnId },
|
|
202
|
+
cursor,
|
|
203
|
+
turns: [],
|
|
204
|
+
increment,
|
|
205
|
+
};
|
|
206
|
+
throw new Error("CODEX_FORK_BOUNDARY_UNSUPPORTED: exact native turn position is unavailable");
|
|
207
|
+
}
|
|
208
|
+
/** 提取请求的系统提示:循环请求的系统消息或一次性调用的 system 字段。 */
|
|
209
|
+
function systemPromptOf(options) {
|
|
210
|
+
if (options.system !== undefined)
|
|
211
|
+
return options.system;
|
|
212
|
+
for (const message of options.messages)
|
|
213
|
+
if (message.role === "system" || message.role === "developer") {
|
|
214
|
+
const texts = [];
|
|
215
|
+
for (const block of message.content ?? [])
|
|
216
|
+
if (block.type === "text")
|
|
217
|
+
texts.push(block.text);
|
|
218
|
+
if (texts.length > 0)
|
|
219
|
+
return texts.join("\n");
|
|
220
|
+
}
|
|
221
|
+
return undefined;
|
|
222
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** 原生审批桥(feat09):Codex 审批类服务端请求转 KMH 用户决定(D18)。 */
|
|
2
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
3
|
+
import type { z } from "zod";
|
|
4
|
+
import type { ApprovalOutcome } from "@deepseek-ai/dsh-user-approval";
|
|
5
|
+
import type { SessionId } from "@deepseek-ai/dsh-session";
|
|
6
|
+
import { CommandExecutionRequestApprovalParams, FileChangeRequestApprovalParams, PermissionsRequestApprovalParams } from "./protocol.ts";
|
|
7
|
+
/** KMH 审批四态 → Codex 命令/文件审批决定值。 */
|
|
8
|
+
export declare function commandDecisionOf(outcome: ApprovalOutcome): "accept" | "decline" | "cancel";
|
|
9
|
+
/** 审批请求展示信息(approval.request 的 toolName 与 reason,用户可见)。 */
|
|
10
|
+
export interface ApprovalPrompt {
|
|
11
|
+
toolName: string;
|
|
12
|
+
reason: string;
|
|
13
|
+
}
|
|
14
|
+
/** 命令执行审批的展示信息:命令、工作目录与申请原因。 */
|
|
15
|
+
export declare function commandApprovalPromptOf(params: z.infer<typeof CommandExecutionRequestApprovalParams>): ApprovalPrompt;
|
|
16
|
+
/** 文件修改审批的展示信息。 */
|
|
17
|
+
export declare function fileChangeApprovalPromptOf(params: z.infer<typeof FileChangeRequestApprovalParams>): ApprovalPrompt;
|
|
18
|
+
/** 权限申请审批的展示信息:请求范围原样展示供审阅。 */
|
|
19
|
+
export declare function permissionsApprovalPromptOf(params: z.infer<typeof PermissionsRequestApprovalParams>): ApprovalPrompt;
|
|
20
|
+
/**
|
|
21
|
+
* 原生审批桥:把审批类服务端请求交给 KMH 公开服务决定。
|
|
22
|
+
* 审批走 `approval.request()`(需活跃 Agent 与开放 turn),用户输入与
|
|
23
|
+
* MCP 确认走 `userQuestions.ask()`(需要结构化答案);两者缺失时
|
|
24
|
+
* fail closed。每个服务端请求由行协议保证恰有一次回执(一次性语义);
|
|
25
|
+
* 停止/中断经 signal 传导为 cancelled / ASK_ABORTED。
|
|
26
|
+
*/
|
|
27
|
+
export declare class CodexApprovalBridge {
|
|
28
|
+
private readonly ctx;
|
|
29
|
+
private readonly sessionId;
|
|
30
|
+
private readonly signal;
|
|
31
|
+
constructor(ctx: Context, sessionId: SessionId | undefined, signal: AbortSignal | undefined);
|
|
32
|
+
/** 会话的活跃 Agent;查不到(临时会话、无 agent 服务)返回 undefined。 */
|
|
33
|
+
private agentOf;
|
|
34
|
+
/** 经 KMH 审批服务决定一次请求;无入口时 fail closed 并记录可读原因。 */
|
|
35
|
+
private decide;
|
|
36
|
+
/** item/commandExecution/requestApproval → Codex 决定回执。 */
|
|
37
|
+
handleCommandApproval(params: unknown): Promise<unknown>;
|
|
38
|
+
/** item/fileChange/requestApproval → Codex 决定回执。 */
|
|
39
|
+
handleFileChangeApproval(params: unknown): Promise<unknown>;
|
|
40
|
+
/** item/permissions/requestApproval → 授权回执(批准=请求范围/拒绝=空)。 */
|
|
41
|
+
handlePermissionsApproval(params: unknown): Promise<unknown>;
|
|
42
|
+
/** item/tool/requestUserInput → 结构化答案回执。 */
|
|
43
|
+
handleUserInput(params: unknown): Promise<unknown>;
|
|
44
|
+
/** mcpServer/elicitation/request → accept/decline/cancel + content 回执。 */
|
|
45
|
+
handleElicitation(params: unknown): Promise<unknown>;
|
|
46
|
+
/** 经用户问题服务取得结构化答案并组装回执;中止取消、无应答者拒绝。 */
|
|
47
|
+
private askQuestions;
|
|
48
|
+
}
|