@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.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +296 -2
  3. package/bin/README.md +25 -0
  4. package/bin/codex +36 -0
  5. package/bin/runtime-receipt.json +9 -0
  6. package/bin/version +1 -0
  7. package/cordis.patch.yml +7 -0
  8. package/lib/browser-types/src/account-status.d.ts +9 -0
  9. package/lib/browser-types/src/client/ComposerQuota.d.ts +10 -0
  10. package/lib/browser-types/src/client/DetailCard.d.ts +12 -0
  11. package/lib/browser-types/src/client/LiveBall.d.ts +19 -0
  12. package/lib/browser-types/src/client/QuotaCard.d.ts +20 -0
  13. package/lib/browser-types/src/client/QuotaDisplaySettings.d.ts +6 -0
  14. package/lib/browser-types/src/client/index.d.ts +18 -0
  15. package/lib/browser-types/src/client/locales.d.ts +54 -0
  16. package/lib/browser-types/src/client/quota-store.d.ts +56 -0
  17. package/lib/browser-types/src/live-state.d.ts +31 -0
  18. package/lib/browser-types/src/quota-protocol.d.ts +135 -0
  19. package/lib/browser-types/src/quota-rules.d.ts +18 -0
  20. package/lib/browser-types/src/tool-switches.d.ts +63 -0
  21. package/lib/client.js +16193 -0
  22. package/lib/src/account-status.d.ts +9 -0
  23. package/lib/src/account-status.js +1 -0
  24. package/lib/src/account.d.ts +35 -0
  25. package/lib/src/account.js +173 -0
  26. package/lib/src/adapter.d.ts +22 -0
  27. package/lib/src/adapter.js +222 -0
  28. package/lib/src/approval.d.ts +48 -0
  29. package/lib/src/approval.js +235 -0
  30. package/lib/src/capabilities.d.ts +40 -0
  31. package/lib/src/capabilities.js +85 -0
  32. package/lib/src/config.d.ts +69 -0
  33. package/lib/src/config.js +75 -0
  34. package/lib/src/connection.d.ts +65 -0
  35. package/lib/src/connection.js +178 -0
  36. package/lib/src/cursor.d.ts +61 -0
  37. package/lib/src/cursor.js +339 -0
  38. package/lib/src/image-delivery.d.ts +36 -0
  39. package/lib/src/image-delivery.js +65 -0
  40. package/lib/src/imagegen.d.ts +21 -0
  41. package/lib/src/imagegen.js +132 -0
  42. package/lib/src/index.d.ts +146 -0
  43. package/lib/src/index.js +551 -0
  44. package/lib/src/isolation.d.ts +61 -0
  45. package/lib/src/isolation.js +298 -0
  46. package/lib/src/live-state.d.ts +31 -0
  47. package/lib/src/live-state.js +14 -0
  48. package/lib/src/models.d.ts +24 -0
  49. package/lib/src/models.js +98 -0
  50. package/lib/src/native-items.d.ts +59 -0
  51. package/lib/src/native-items.js +122 -0
  52. package/lib/src/native-tools/catalog.d.ts +29 -0
  53. package/lib/src/native-tools/catalog.js +197 -0
  54. package/lib/src/probe.d.ts +17 -0
  55. package/lib/src/probe.js +54 -0
  56. package/lib/src/protocol.d.ts +508 -0
  57. package/lib/src/protocol.js +511 -0
  58. package/lib/src/quota-protocol.d.ts +135 -0
  59. package/lib/src/quota-protocol.js +97 -0
  60. package/lib/src/quota-rules.d.ts +18 -0
  61. package/lib/src/quota-rules.js +49 -0
  62. package/lib/src/quota.d.ts +32 -0
  63. package/lib/src/quota.js +227 -0
  64. package/lib/src/session-history.d.ts +18 -0
  65. package/lib/src/session-history.js +113 -0
  66. package/lib/src/session-store.d.ts +592 -0
  67. package/lib/src/session-store.js +275 -0
  68. package/lib/src/status.d.ts +19 -0
  69. package/lib/src/status.js +69 -0
  70. package/lib/src/tool-policy.d.ts +47 -0
  71. package/lib/src/tool-policy.js +454 -0
  72. package/lib/src/tool-registry.d.ts +42 -0
  73. package/lib/src/tool-registry.js +70 -0
  74. package/lib/src/tool-selection.d.ts +88 -0
  75. package/lib/src/tool-selection.js +60 -0
  76. package/lib/src/tool-switches-service.d.ts +24 -0
  77. package/lib/src/tool-switches-service.js +129 -0
  78. package/lib/src/tool-switches.d.ts +63 -0
  79. package/lib/src/tool-switches.js +43 -0
  80. package/lib/src/turn.d.ts +200 -0
  81. package/lib/src/turn.js +1012 -0
  82. package/lib/src/web.d.ts +9 -0
  83. package/lib/src/web.js +143 -0
  84. package/package.json +172 -4
  85. package/vendor/codex/LICENSE +201 -0
  86. package/vendor/codex/NOTICE +4 -0
  87. package/vendor/codex/models.json +1613 -0
  88. package/vendor/native-tools/0.162.0-alpha.17.2.json +143 -0
  89. package/vendor/native-tools/0.163.0-alpha.10.2.json +128 -0
@@ -0,0 +1,235 @@
1
+ import { CommandExecutionRequestApprovalParams, FileChangeRequestApprovalParams, McpServerElicitationRequestParams, PermissionsRequestApprovalParams, ToolRequestUserInputParams, fieldOf, } from "./protocol.js";
2
+ /** KMH 审批四态 → Codex 命令/文件审批决定值。 */
3
+ export function commandDecisionOf(outcome) {
4
+ if (outcome === "allowed-once")
5
+ return "accept";
6
+ if (outcome === "cancelled")
7
+ return "cancel";
8
+ // rejected 与 unavailable 都拒绝:缺入口 fail closed,模型收到拒绝可继续。
9
+ return "decline";
10
+ }
11
+ /** 命令执行审批的展示信息:命令、工作目录与申请原因。 */
12
+ export function commandApprovalPromptOf(params) {
13
+ const lines = [`命令:${params.command ?? "(未提供)"}`];
14
+ if (params.cwd !== null && params.cwd !== undefined)
15
+ lines.push(`工作目录:${params.cwd}`);
16
+ lines.push("申请权限:执行该原生命令(来源 Codex 原生工具)");
17
+ if (params.reason !== null && params.reason !== undefined)
18
+ lines.push(`原因:${params.reason}`);
19
+ return { toolName: "codex 命令执行审批", reason: lines.join("\n") };
20
+ }
21
+ /** 文件修改审批的展示信息。 */
22
+ export function fileChangeApprovalPromptOf(params) {
23
+ const lines = ["申请权限:修改文件(来源 Codex 原生工具)"];
24
+ if (params.grantRoot !== null && params.grantRoot !== undefined)
25
+ lines.push(`授权根:${params.grantRoot}(批准仅本次生效)`);
26
+ if (params.reason !== null && params.reason !== undefined)
27
+ lines.push(`原因:${params.reason}`);
28
+ return { toolName: "codex 文件修改审批", reason: lines.join("\n") };
29
+ }
30
+ /** 权限申请审批的展示信息:请求范围原样展示供审阅。 */
31
+ export function permissionsApprovalPromptOf(params) {
32
+ const lines = [`工作目录:${params.cwd}`];
33
+ lines.push(`申请权限范围:${JSON.stringify(params.permissions)}(批准仅授予该范围)`);
34
+ if (params.reason !== null && params.reason !== undefined)
35
+ lines.push(`原因:${params.reason}`);
36
+ return { toolName: "codex 权限申请审批", reason: lines.join("\n") };
37
+ }
38
+ /** 用户中止 → cancel,其余失败(含无应答者)→ decline。 */
39
+ function elicitationActionOf(error) {
40
+ const code = fieldOf(error, "code");
41
+ return code === "ASK_ABORTED" ? "cancel" : "decline";
42
+ }
43
+ /** 对象守卫(unknown → record)。 */
44
+ function isRecord(value) {
45
+ return value !== null && typeof value === "object" && !Array.isArray(value);
46
+ }
47
+ /**
48
+ * 原生审批桥:把审批类服务端请求交给 KMH 公开服务决定。
49
+ * 审批走 `approval.request()`(需活跃 Agent 与开放 turn),用户输入与
50
+ * MCP 确认走 `userQuestions.ask()`(需要结构化答案);两者缺失时
51
+ * fail closed。每个服务端请求由行协议保证恰有一次回执(一次性语义);
52
+ * 停止/中断经 signal 传导为 cancelled / ASK_ABORTED。
53
+ */
54
+ export class CodexApprovalBridge {
55
+ ctx;
56
+ sessionId;
57
+ signal;
58
+ constructor(ctx, sessionId, signal) {
59
+ this.ctx = ctx;
60
+ this.sessionId = sessionId;
61
+ this.signal = signal;
62
+ }
63
+ /** 会话的活跃 Agent;查不到(临时会话、无 agent 服务)返回 undefined。 */
64
+ agentOf() {
65
+ if (this.sessionId === undefined)
66
+ return undefined;
67
+ return this.ctx.agents?.get(this.sessionId);
68
+ }
69
+ /** 经 KMH 审批服务决定一次请求;无入口时 fail closed 并记录可读原因。 */
70
+ async decide(prompt) {
71
+ const agent = this.agentOf();
72
+ const approval = this.ctx.approval;
73
+ if (agent === undefined || approval === undefined) {
74
+ this.ctx.logger.warn(`codex-cli approval unavailable (agent=${String(agent === undefined)}, service=${String(approval === undefined)}); failing closed: ${prompt.toolName}`);
75
+ return "unavailable";
76
+ }
77
+ return await approval.request({
78
+ agent,
79
+ toolName: prompt.toolName,
80
+ reason: prompt.reason,
81
+ ...(this.signal === undefined ? {} : { signal: this.signal }),
82
+ });
83
+ }
84
+ /** item/commandExecution/requestApproval → Codex 决定回执。 */
85
+ async handleCommandApproval(params) {
86
+ const decision = commandDecisionOf(await this.decide(commandApprovalPromptOf(CommandExecutionRequestApprovalParams.parse(params))));
87
+ return { decision };
88
+ }
89
+ /** item/fileChange/requestApproval → Codex 决定回执。 */
90
+ async handleFileChangeApproval(params) {
91
+ const decision = commandDecisionOf(await this.decide(fileChangeApprovalPromptOf(FileChangeRequestApprovalParams.parse(params))));
92
+ return { decision };
93
+ }
94
+ /** item/permissions/requestApproval → 授权回执(批准=请求范围/拒绝=空)。 */
95
+ async handlePermissionsApproval(params) {
96
+ const parsed = PermissionsRequestApprovalParams.parse(params);
97
+ const outcome = await this.decide(permissionsApprovalPromptOf(parsed));
98
+ // 只授予用户明确批准的范围(原样请求的 profile),scope 取最窄 turn。
99
+ const granted = outcome === "allowed-once" && isRecord(parsed.permissions)
100
+ ? parsed.permissions
101
+ : {};
102
+ return { permissions: granted, scope: "turn" };
103
+ }
104
+ /** item/tool/requestUserInput → 结构化答案回执。 */
105
+ async handleUserInput(params) {
106
+ const parsed = ToolRequestUserInputParams.parse(params);
107
+ const questions = parsed.questions.map((question) => ({
108
+ id: question.id,
109
+ question: question.question,
110
+ ...(question.header === "" ? {} : { header: question.header }),
111
+ ...((question.options ?? []).length > 0
112
+ ? {
113
+ options: (question.options ?? []).map((option) => ({
114
+ label: option.label,
115
+ ...(option.description === undefined
116
+ ? {}
117
+ : { description: option.description }),
118
+ })),
119
+ }
120
+ : {}),
121
+ }));
122
+ return await this.askQuestions(questions, (answer) => {
123
+ const answers = {};
124
+ for (const item of answer.answers)
125
+ answers[item.id] = {
126
+ answers: [
127
+ ...item.selected,
128
+ ...(item.custom === undefined ? [] : [item.custom]),
129
+ ],
130
+ };
131
+ return { answers };
132
+ });
133
+ }
134
+ /** mcpServer/elicitation/request → accept/decline/cancel + content 回执。 */
135
+ async handleElicitation(params) {
136
+ const parsed = McpServerElicitationRequestParams.parse(params);
137
+ return await this.askQuestions(elicitationQuestionsOf(parsed), (answer) => elicitationContentOf(parsed, answer));
138
+ }
139
+ /** 经用户问题服务取得结构化答案并组装回执;中止取消、无应答者拒绝。 */
140
+ async askQuestions(questions, build) {
141
+ const agent = this.agentOf();
142
+ const service = this.ctx.userQuestions;
143
+ if (agent === undefined || service === undefined) {
144
+ this.ctx.logger.warn(`codex-cli user questions unavailable (agent=${String(agent === undefined)}, service=${String(service === undefined)}); declining`);
145
+ return { action: "decline" };
146
+ }
147
+ try {
148
+ const answer = await service.ask({
149
+ questions,
150
+ agent,
151
+ ...(this.signal === undefined ? {} : { signal: this.signal }),
152
+ });
153
+ return { action: "accept", ...build(answer) };
154
+ }
155
+ catch (error) {
156
+ return { action: elicitationActionOf(error) };
157
+ }
158
+ }
159
+ }
160
+ /** elicitation 请求的表单属性表(schema.properties);无表单返回 undefined。 */
161
+ function elicitationPropertiesOf(params) {
162
+ const schema = isRecord(params.requestedSchema)
163
+ ? params.requestedSchema
164
+ : undefined;
165
+ const raw = fieldOf(schema, "properties");
166
+ return isRecord(raw) ? raw : undefined;
167
+ }
168
+ /** elicitation 问题映射:表单属性逐个成题(枚举→选项,其余自填)。 */
169
+ function elicitationQuestionsOf(params) {
170
+ const base = { question: params.message ?? `${params.serverName} 请求确认` };
171
+ if (params.url !== undefined)
172
+ return [
173
+ {
174
+ ...base,
175
+ id: "url",
176
+ header: params.serverName,
177
+ options: [
178
+ { label: "已完成授权", description: params.url },
179
+ { label: "取消" },
180
+ ],
181
+ },
182
+ ];
183
+ const properties = elicitationPropertiesOf(params);
184
+ if (properties === undefined)
185
+ return [{ ...base, id: "elicit", header: params.serverName }];
186
+ const questions = [];
187
+ for (const [name, definition] of Object.entries(properties)) {
188
+ if (!isRecord(definition))
189
+ continue;
190
+ const values = fieldOf(definition, "enum");
191
+ const title = fieldOf(definition, "title");
192
+ const options = Array.isArray(values) && values.every((item) => typeof item === "string")
193
+ ? values.map((item) => ({ label: item }))
194
+ : undefined;
195
+ const question = {
196
+ ...base,
197
+ id: name,
198
+ header: params.serverName,
199
+ };
200
+ if (typeof title === "string" && title !== "")
201
+ question.detail = title;
202
+ if (options !== undefined)
203
+ question.options = options;
204
+ questions.push(question);
205
+ }
206
+ return questions.length > 0
207
+ ? questions
208
+ : [{ ...base, id: "elicit", header: params.serverName }];
209
+ }
210
+ /** elicitation 答案组装为 content 对象(按 schema 属性名与类型取值)。 */
211
+ function elicitationContentOf(params, answer) {
212
+ const properties = elicitationPropertiesOf(params);
213
+ if (properties === undefined)
214
+ return {};
215
+ const content = {};
216
+ for (const item of answer.answers) {
217
+ const value = [
218
+ ...item.selected,
219
+ ...(item.custom === undefined ? [] : [item.custom]),
220
+ ][0];
221
+ if (value === undefined)
222
+ continue;
223
+ const type = fieldOf(fieldOf(properties, item.id), "type");
224
+ if (type === "number") {
225
+ const parsed = Number(value);
226
+ if (Number.isFinite(parsed))
227
+ content[item.id] = parsed;
228
+ }
229
+ else if (type === "boolean")
230
+ content[item.id] = value === "true";
231
+ else
232
+ content[item.id] = value;
233
+ }
234
+ return { content };
235
+ }
@@ -0,0 +1,40 @@
1
+ /** 原生能力逐项选择(feat02 修订版):能力清单、选择模型与旧开关迁移。 */
2
+ import type { VersionStatus } from "./status.ts";
3
+ /** 一份原生能力选择:工具四项与独立的原生技能(默认全关)。 */
4
+ export interface NativeSelection {
5
+ /** 原生命令执行(shell)。 */
6
+ commandExecution: boolean;
7
+ /** 原生文件修改(apply_patch)。 */
8
+ fileChange: boolean;
9
+ /** 原生查看图片。 */
10
+ viewImage: boolean;
11
+ /** 原生网络搜索。 */
12
+ webSearch: boolean;
13
+ /** 原生技能(独立于工具选择,默认关闭)。 */
14
+ skills: boolean;
15
+ }
16
+ /** 默认选择:仅 KMH 工具/技能与既有原生图片生成(R1 已确认)。 */
17
+ export declare const DEFAULT_SELECTION: NativeSelection;
18
+ /** 全开选择:旧总开关 true 的迁移映射(已支持项全选)。 */
19
+ export declare const FULL_SELECTION: NativeSelection;
20
+ /** 旧总开关布尔到逐项选择的迁移。 */
21
+ export declare function selectionFromLegacy(enabled: boolean): NativeSelection;
22
+ /** 选择字段校验:合法布尔字段保留,缺失或非法回落默认。 */
23
+ export declare function selectionOf(value: unknown): NativeSelection;
24
+ /** 详情页能力条目:标识、文案与可用状态(服务端给出,客户端只渲染)。 */
25
+ export interface NativeCapabilityView {
26
+ id: keyof NativeSelection;
27
+ label: string;
28
+ description: string;
29
+ available: boolean;
30
+ /** 不可用的已知原因(场景6)。 */
31
+ reason?: string;
32
+ }
33
+ /**
34
+ * 组装详情页能力列表:当前版本检查结果决定可用性(场景6)。
35
+ * 版本不可用是当前唯一部署级已知原因;账号与模型粒度的限制在任务
36
+ * 发起时按实际可见工具核对,此处如实展示已知部分。
37
+ * @param version - 版本检查结果。
38
+ * @returns 按展示顺序的能力条目。
39
+ */
40
+ export declare function capabilityViews(version: VersionStatus): NativeCapabilityView[];
@@ -0,0 +1,85 @@
1
+ /** 默认选择:仅 KMH 工具/技能与既有原生图片生成(R1 已确认)。 */
2
+ export const DEFAULT_SELECTION = {
3
+ commandExecution: false,
4
+ fileChange: false,
5
+ viewImage: false,
6
+ webSearch: false,
7
+ skills: false,
8
+ };
9
+ /** 全开选择:旧总开关 true 的迁移映射(已支持项全选)。 */
10
+ export const FULL_SELECTION = {
11
+ commandExecution: true,
12
+ fileChange: true,
13
+ viewImage: true,
14
+ webSearch: true,
15
+ skills: true,
16
+ };
17
+ /** 旧总开关布尔到逐项选择的迁移。 */
18
+ export function selectionFromLegacy(enabled) {
19
+ return enabled ? { ...FULL_SELECTION } : { ...DEFAULT_SELECTION };
20
+ }
21
+ /** 选择字段校验:合法布尔字段保留,缺失或非法回落默认。 */
22
+ export function selectionOf(value) {
23
+ const pick = (key) => {
24
+ if (value === null || typeof value !== "object")
25
+ return DEFAULT_SELECTION[key];
26
+ for (const [name, item] of Object.entries(value))
27
+ if (name === key && typeof item === "boolean")
28
+ return item;
29
+ return DEFAULT_SELECTION[key];
30
+ };
31
+ return {
32
+ commandExecution: pick("commandExecution"),
33
+ fileChange: pick("fileChange"),
34
+ viewImage: pick("viewImage"),
35
+ webSearch: pick("webSearch"),
36
+ skills: pick("skills"),
37
+ };
38
+ }
39
+ /** 能力条目的静态文案(顺序即详情页展示顺序)。 */
40
+ const CAPABILITY_LABELS = [
41
+ {
42
+ id: "commandExecution",
43
+ label: "命令执行",
44
+ description: "原生 shell 命令执行(经审批档位决定是否询问)",
45
+ },
46
+ {
47
+ id: "fileChange",
48
+ label: "文件修改",
49
+ description: "原生 apply_patch 文件修改",
50
+ },
51
+ {
52
+ id: "viewImage",
53
+ label: "查看图片",
54
+ description: "原生图片查看工具",
55
+ },
56
+ {
57
+ id: "webSearch",
58
+ label: "网络搜索",
59
+ description: "原生联网搜索工具",
60
+ },
61
+ {
62
+ id: "skills",
63
+ label: "原生技能",
64
+ description: "官方 CLI 自带技能目录(默认关闭,$技能名 由 KMH 技能体系接管)",
65
+ },
66
+ ];
67
+ /**
68
+ * 组装详情页能力列表:当前版本检查结果决定可用性(场景6)。
69
+ * 版本不可用是当前唯一部署级已知原因;账号与模型粒度的限制在任务
70
+ * 发起时按实际可见工具核对,此处如实展示已知部分。
71
+ * @param version - 版本检查结果。
72
+ * @returns 按展示顺序的能力条目。
73
+ */
74
+ export function capabilityViews(version) {
75
+ const available = version.ok;
76
+ return CAPABILITY_LABELS.map((entry) => {
77
+ if (available)
78
+ return { ...entry, available };
79
+ return {
80
+ ...entry,
81
+ available,
82
+ reason: version.reason ?? "CODEX_CLI_UNAVAILABLE",
83
+ };
84
+ });
85
+ }
@@ -0,0 +1,69 @@
1
+ import schema from "@deepseek-ai/schemastery";
2
+ declare const configFields: {
3
+ command: schema<string, string, "defined">;
4
+ cwd: schema<string, string, "defined">;
5
+ dataDir: schema<string, string, "defined">;
6
+ model: schema<string, string, "defined">;
7
+ defaultMaxTokens: schema<number, number, "defined">;
8
+ reasoningSummary: schema<"auto" | "concise" | "detailed" | "none", "auto" | "concise" | "detailed" | "none", "defined">;
9
+ startupTimeoutMs: schema<number, number, "defined">;
10
+ requestTimeoutMs: schema<number, number, "defined">;
11
+ cancelReceiptTimeoutMs: schema<number, number, "defined">;
12
+ cleanupTimeoutMs: schema<number, number, "defined">;
13
+ probeTimeoutMs: schema<number, number, "defined">;
14
+ probeMaxTokens: schema<number, number, "defined">;
15
+ loginTimeoutMs: schema<number, number, "defined">;
16
+ graceMs: schema<number, number, "defined">;
17
+ nativeToolsEnabled: schema<boolean, boolean, "defined">;
18
+ quotaDisplayMode: schema<"percent" | "bar" | "off", "percent" | "bar" | "off", "volatile-defined">;
19
+ quotaAlertsEnabled: schema<boolean, boolean, "volatile-defined">;
20
+ quotaShortThresholdPercent: schema<number, number, "volatile-defined">;
21
+ quotaWeeklyThresholdPercent: schema<number, number, "volatile-defined">;
22
+ toolSelection: schema<NoInfer<Schemastery.ObjectT<{
23
+ version: schema<1, 1, "defined">;
24
+ harness: schema<Schemastery.ObjectS<{
25
+ source: schema<string, string, "defined">;
26
+ name: schema<string, string, "defined">;
27
+ enabled: schema<boolean, boolean, "defined">;
28
+ }>[], Schemastery.ObjectT<{
29
+ source: schema<string, string, "defined">;
30
+ name: schema<string, string, "defined">;
31
+ enabled: schema<boolean, boolean, "defined">;
32
+ }>[], "defined">;
33
+ native: schema<Schemastery.ObjectS<{
34
+ source: schema<string, string, "defined">;
35
+ name: schema<string, string, "defined">;
36
+ enabled: schema<boolean, boolean, "defined">;
37
+ }>[], Schemastery.ObjectT<{
38
+ source: schema<string, string, "defined">;
39
+ name: schema<string, string, "defined">;
40
+ enabled: schema<boolean, boolean, "defined">;
41
+ }>[], "defined">;
42
+ }>>, NoInfer<Schemastery.ObjectT<{
43
+ version: schema<1, 1, "defined">;
44
+ harness: schema<Schemastery.ObjectS<{
45
+ source: schema<string, string, "defined">;
46
+ name: schema<string, string, "defined">;
47
+ enabled: schema<boolean, boolean, "defined">;
48
+ }>[], Schemastery.ObjectT<{
49
+ source: schema<string, string, "defined">;
50
+ name: schema<string, string, "defined">;
51
+ enabled: schema<boolean, boolean, "defined">;
52
+ }>[], "defined">;
53
+ native: schema<Schemastery.ObjectS<{
54
+ source: schema<string, string, "defined">;
55
+ name: schema<string, string, "defined">;
56
+ enabled: schema<boolean, boolean, "defined">;
57
+ }>[], Schemastery.ObjectT<{
58
+ source: schema<string, string, "defined">;
59
+ name: schema<string, string, "defined">;
60
+ enabled: schema<boolean, boolean, "defined">;
61
+ }>[], "defined">;
62
+ }>>, "volatile">;
63
+ env: schema<Record<string, string>>;
64
+ };
65
+ /** 可配置的可执行文件、存储、模型身份与进程时限。 */
66
+ export declare const Config: schema<Schemastery.ObjectS<typeof configFields>, Schemastery.ObjectT<typeof configFields>>;
67
+ /** 校验后的 CLI 设置。 */
68
+ export type Config = ReturnType<typeof Config>;
69
+ export {};
@@ -0,0 +1,75 @@
1
+ /** 官方 Codex CLI 执行、存储与超时限制的部署配置。 */
2
+ import { ToolSelectionSchema } from "./tool-selection.js";
3
+ import schema from "@deepseek-ai/schemastery";
4
+ import { dirname, isAbsolute, join } from "node:path";
5
+ import { createRequire } from "node:module";
6
+ const bundledCommand = join(dirname(createRequire(import.meta.url).resolve("@kmh/codex-cli/package.json")), "bin", "codex");
7
+ // 共享 schema 保持选择类型;联动检查可在配置 schema 传到客户端后独立执行。
8
+ const codexToolSelection = schema.intersect([
9
+ ToolSelectionSchema,
10
+ schema.transform(ToolSelectionSchema, (value) => {
11
+ if (value === undefined)
12
+ return value;
13
+ const commands = ["exec_command", "write_stdin", "shell_command"];
14
+ const enabled = commands.map((name) => value.native?.find((row) => row.source === "codex/native" && row.name === name)?.enabled ?? false);
15
+ if (new Set(enabled).size > 1)
16
+ throw new Error("CODEX_NATIVE_LINKED_CHOICES_CONFLICT: exec_command, write_stdin, shell_command");
17
+ return value;
18
+ }),
19
+ ]);
20
+ const absolute = schema
21
+ .transform(schema.string().required(), (value) => {
22
+ if (!isAbsolute(value))
23
+ throw new schema.ValidationError("Expected absolute path", { path: [] });
24
+ return value;
25
+ })
26
+ .required();
27
+ const env = schema
28
+ .dict(schema.string())
29
+ .default({});
30
+ const configFields = {
31
+ command: schema.string().default(bundledCommand),
32
+ cwd: absolute,
33
+ dataDir: absolute,
34
+ // 空 model 表示自动:登录后取模型目录首选;非空值固定为该模型。
35
+ model: schema.string().default(""),
36
+ defaultMaxTokens: schema.natural().min(1).max(2147483647).default(1000000),
37
+ // 可见思考摘要由官方 CLI 生成;none 显式关闭摘要请求。
38
+ reasoningSummary: schema
39
+ .union(["auto", "concise", "detailed", "none"])
40
+ .default("auto"),
41
+ // 启动并完成 initialize 握手的时限。
42
+ startupTimeoutMs: schema.natural().min(1).max(2147483647).default(20000),
43
+ // 单次 stream(含排队、启动、重试与辅助请求)的总时限;收尾另有时限。
44
+ requestTimeoutMs: schema.natural().min(1).max(2147483647).default(360000),
45
+ // turn/interrupt 后等待 interrupted 终止通知的时限。
46
+ cancelReceiptTimeoutMs: schema.natural().min(1).max(2147483647).default(5000),
47
+ cleanupTimeoutMs: schema.natural().min(1).max(2147483647).default(5000),
48
+ probeTimeoutMs: schema.natural().min(1).max(2147483647).default(15000),
49
+ probeMaxTokens: schema.natural().min(1).default(1),
50
+ loginTimeoutMs: schema.natural().min(1).max(2147483647).default(1200000),
51
+ graceMs: schema.natural().min(1).max(2147483647).default(1500),
52
+ // 原生 Codex 工具与技能开关:默认关闭,模型只见 KMH 的工具与技能。
53
+ nativeToolsEnabled: schema.boolean().default(false),
54
+ quotaDisplayMode: schema
55
+ .union(["percent", "bar", "off"])
56
+ .default("percent")
57
+ .volatile(),
58
+ quotaAlertsEnabled: schema.boolean().default(true).volatile(),
59
+ quotaShortThresholdPercent: schema
60
+ .natural()
61
+ .min(1)
62
+ .max(100)
63
+ .default(20)
64
+ .volatile(),
65
+ quotaWeeklyThresholdPercent: schema
66
+ .natural()
67
+ .min(1)
68
+ .max(100)
69
+ .default(20)
70
+ .volatile(),
71
+ toolSelection: codexToolSelection.volatile(),
72
+ env,
73
+ };
74
+ /** 可配置的可执行文件、存储、模型身份与进程时限。 */
75
+ export const Config = schema.object(configFields);
@@ -0,0 +1,65 @@
1
+ /** 官方 Codex CLI app-server 连接:进程生命周期与行协议双向分发。 */
2
+ import type { Context } from "@deepseek-ai/cordis";
3
+ import { type SubprocessHandle } from "@deepseek-ai/dsh-subprocess";
4
+ import type { Readable } from "node:stream";
5
+ import { createFrameBridge } from "./protocol.ts";
6
+ /** 建立一条连接所需的执行设置。 */
7
+ export interface CodexConnectOptions {
8
+ command: string;
9
+ cwd: string;
10
+ configOverrides: readonly string[];
11
+ env?: Record<string, string | undefined>;
12
+ graceMs: number;
13
+ startupTimeoutMs: number;
14
+ }
15
+ /** 服务端请求(如 item/tool/call)的处理函数;拒绝即向 CLI 回错误。 */
16
+ export type ServerRequestHandler = (method: string, params: Record<string, unknown>) => Promise<unknown>;
17
+ /** 通知的处理函数。 */
18
+ export type NotificationHandler = (method: string, params: Record<string, unknown>) => void;
19
+ /**
20
+ * 一条到官方 CLI 的行协议连接。进程随连接存活:关闭输入并等待退出后连接不可复用。
21
+ * 进程意外退出时,在途请求以 JSON-RPC transport closed 拒绝。
22
+ */
23
+ export declare class CodexConnection {
24
+ private readonly child;
25
+ private readonly bridge;
26
+ private readonly stderrTail;
27
+ private readonly transport;
28
+ private exitState;
29
+ constructor(input: Readable, child: SubprocessHandle, bridge: ReturnType<typeof createFrameBridge>, stderrTail: {
30
+ value: string;
31
+ });
32
+ /** 进程退出观察回执;用于等待回收完成。 */
33
+ get done(): Promise<unknown>;
34
+ /** 是否已经退出。 */
35
+ get exited(): boolean;
36
+ /** 诊断用 stderr 尾部(有界)。 */
37
+ get stderr(): string;
38
+ /** 开始读取输入流;幂等。 */
39
+ start(): void;
40
+ /** 停止读取并拆除桥接流;不触碰进程本身。 */
41
+ close(): void;
42
+ /** 安装服务端请求处理;未安装时服务端请求收到 method not found 错误回执。 */
43
+ onServerRequest(handler: ServerRequestHandler): void;
44
+ /** 安装通知处理。 */
45
+ onNotification(handler: NotificationHandler): void;
46
+ /** 发起一次请求并等待响应;signal 中止时在途条目立即拒绝。 */
47
+ request(method: string, params: object, signal?: AbortSignal): Promise<unknown>;
48
+ /** 发送一条通知。 */
49
+ notify(method: string, params?: object): void;
50
+ /**
51
+ * 关闭输入并等待进程退出;超时后经 subprocess 托管强制回收。
52
+ * @param cleanupTimeoutMs - 干净退出的等待时限。
53
+ * @returns clean 表示进程自行退出,forced 表示超时后强制回收。
54
+ */
55
+ stop(cleanupTimeoutMs: number): Promise<"clean" | "forced">;
56
+ }
57
+ /**
58
+ * 拉起官方 CLI、完成 initialize 握手并返回可用连接。
59
+ * @param ctx - 宿主上下文,提供受管 subprocess 服务。
60
+ * @param options - 可执行文件、工作目录、-c 覆盖与超时设置。
61
+ * @param signal - 中止信号:启动阶段中止即终止进程并抛 CODEX_STARTUP_CANCELLED。
62
+ * @throws CODEX_CLI_MISSING 可执行文件不存在;CODEX_STDIO_MISSING 管道缺失;
63
+ * CODEX_STARTUP_TIMEOUT 握手超时;CODEX_STARTUP_FAILED 握手被拒或进程提前退出。
64
+ */
65
+ export declare function connectCodex(ctx: Context, options: CodexConnectOptions, signal: AbortSignal): Promise<CodexConnection>;