@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.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +295 -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 +21396 -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 +221 -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 +54 -0
  37. package/lib/src/cursor.js +325 -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 +141 -0
  43. package/lib/src/index.js +534 -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-store.d.ts +592 -0
  65. package/lib/src/session-store.js +275 -0
  66. package/lib/src/status.d.ts +19 -0
  67. package/lib/src/status.js +69 -0
  68. package/lib/src/tool-policy.d.ts +47 -0
  69. package/lib/src/tool-policy.js +454 -0
  70. package/lib/src/tool-registry.d.ts +42 -0
  71. package/lib/src/tool-registry.js +70 -0
  72. package/lib/src/tool-selection.d.ts +88 -0
  73. package/lib/src/tool-selection.js +60 -0
  74. package/lib/src/tool-switches-service.d.ts +24 -0
  75. package/lib/src/tool-switches-service.js +129 -0
  76. package/lib/src/tool-switches.d.ts +63 -0
  77. package/lib/src/tool-switches.js +43 -0
  78. package/lib/src/turn.d.ts +200 -0
  79. package/lib/src/turn.js +1012 -0
  80. package/lib/src/web.d.ts +9 -0
  81. package/lib/src/web.js +143 -0
  82. package/package.json +171 -4
  83. package/vendor/codex/LICENSE +201 -0
  84. package/vendor/codex/NOTICE +4 -0
  85. package/vendor/codex/models.json +1613 -0
  86. package/vendor/native-tools/0.162.0-alpha.17.2.json +143 -0
  87. package/vendor/native-tools/0.163.0-alpha.10.2.json +128 -0
@@ -0,0 +1,275 @@
1
+ /** KMH 会话创建时的工具选择、原生编号与增量处理位置。 */
2
+ import { mkdir, readFile, rename, writeFile, unlink } from "node:fs/promises";
3
+ import { randomUUID } from "node:crypto";
4
+ import { join } from "node:path";
5
+ import { z } from "zod";
6
+ import Schema from "@deepseek-ai/schemastery";
7
+ import { brandString } from "@deepseek-ai/dsh-brand";
8
+ import { CliTargetId, ToolSourceId, ToolSelectionSchema, } from "./tool-selection.js";
9
+ import { assertSupportedJsonSchema } from "@deepseek-ai/dsh-tools";
10
+ const choices = z
11
+ .custom((value) => {
12
+ try {
13
+ Schema.resolve(value, ToolSelectionSchema, {});
14
+ return true;
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ }, "Invalid saved tool selection")
20
+ .transform((value) => ToolSelectionSchema(value));
21
+ const rawToolSchema = z.object({
22
+ name: z.string(),
23
+ description: z.string(),
24
+ parameters: z.record(z.string(), z.json()),
25
+ deferLoading: z.literal(true).optional(),
26
+ });
27
+ const toolSchema = rawToolSchema.transform(({ deferLoading, ...tool }) => ({
28
+ ...tool,
29
+ ...(deferLoading === undefined ? {} : { deferLoading }),
30
+ }));
31
+ // 来源标签与 PTC SDK 契约只存在于旧记录;公开 schemas() 投影的新快照不含它们。
32
+ const inventoryEntry = z
33
+ .object({
34
+ source: z.string().min(1).transform(ToolSourceId),
35
+ sourceLabel: z.string().optional(),
36
+ schema: toolSchema,
37
+ sdk: rawToolSchema
38
+ .extend({
39
+ output: z.record(z.string(), z.json()).transform((value) => {
40
+ assertSupportedJsonSchema(value);
41
+ return value;
42
+ }),
43
+ })
44
+ .transform(({ deferLoading, ...tool }) => ({
45
+ ...tool,
46
+ ...(deferLoading === undefined ? {} : { deferLoading }),
47
+ }))
48
+ .optional(),
49
+ })
50
+ .transform(({ sourceLabel, sdk, ...row }) => ({
51
+ ...row,
52
+ ...(sourceLabel === undefined ? {} : { sourceLabel }),
53
+ ...(sdk === undefined ? {} : { sdk }),
54
+ }));
55
+ const catalogRow = z
56
+ .object({
57
+ side: z.enum(["harness", "native"]),
58
+ source: z.string().min(1).transform(ToolSourceId),
59
+ name: z.string(),
60
+ description: z.string(),
61
+ sourceLabel: z.string().optional(),
62
+ registryName: z.string().optional(),
63
+ declaration: z.json().optional(),
64
+ schema: toolSchema.optional(),
65
+ control: z.discriminatedUnion("kind", [
66
+ z.object({ kind: z.literal("adjustable") }),
67
+ z.object({ kind: z.literal("linked"), group: z.string() }),
68
+ z.object({
69
+ kind: z.literal("fixed"),
70
+ enabled: z.boolean(),
71
+ reason: z.string(),
72
+ }),
73
+ z.object({ kind: z.literal("unverified"), reason: z.string() }),
74
+ ]),
75
+ })
76
+ .transform(({ sourceLabel, registryName, declaration, schema, ...row }) => ({
77
+ ...row,
78
+ ...(sourceLabel === undefined ? {} : { sourceLabel }),
79
+ ...(registryName === undefined ? {} : { registryName }),
80
+ ...(declaration === undefined ? {} : { declaration }),
81
+ ...(schema === undefined ? {} : { schema }),
82
+ }));
83
+ /** 创建时固定的工具信息;原生目录首次验证后补存,技能仍独立读取。 */
84
+ export const SavedToolPolicySchema = z.object({
85
+ version: z.literal(1),
86
+ target: z.string().min(1).transform(CliTargetId),
87
+ choices,
88
+ inventory: z.array(inventoryEntry),
89
+ nativeExecution: z.object({
90
+ commandExecution: z.boolean(),
91
+ fileChange: z.boolean(),
92
+ viewImage: z.boolean(),
93
+ webSearch: z.boolean(),
94
+ }),
95
+ nativeCatalog: z
96
+ .object({ version: z.string(), rows: z.array(catalogRow) })
97
+ .optional(),
98
+ });
99
+ const nativeSessionId = z
100
+ .string()
101
+ .min(1)
102
+ .transform((brandString));
103
+ const nativeTurnId = z
104
+ .string()
105
+ .min(1)
106
+ .transform((brandString));
107
+ const bindingSchema = z
108
+ .object({
109
+ threadId: nativeSessionId.optional(),
110
+ fingerprints: z.array(z.string()),
111
+ lastTurnId: nativeTurnId.optional(),
112
+ delivered: z.array(z.string()).optional(),
113
+ toolsVersion: z.number().int().nonnegative().optional(),
114
+ toolFingerprint: z.string().optional(),
115
+ turns: z
116
+ .array(z.object({
117
+ turnId: nativeTurnId,
118
+ fingerprints: z.array(z.string()),
119
+ delivered: z.array(z.string()),
120
+ }))
121
+ .optional(),
122
+ previousThreadIds: z.array(nativeSessionId).optional(),
123
+ toolMap: z.record(z.string(), z.string()).optional(),
124
+ toolPolicy: SavedToolPolicySchema.optional(),
125
+ })
126
+ .superRefine((record, context) => {
127
+ if (record.threadId === undefined &&
128
+ (record.toolPolicy === undefined ||
129
+ record.fingerprints.length > 0 ||
130
+ record.lastTurnId !== undefined ||
131
+ (record.delivered?.length ?? 0) > 0)) {
132
+ context.addIssue({
133
+ code: "custom",
134
+ message: "Missing native session id for accepted conversation",
135
+ });
136
+ }
137
+ });
138
+ const bindingFileSchema = z.record(z.string(), bindingSchema);
139
+ /** 文件为会话状态来源;内存只缓存已成功保存的记录,坏文件明确报错。 */
140
+ export class CodexSessionStore {
141
+ dataDir;
142
+ cache;
143
+ loading;
144
+ writes = Promise.resolve();
145
+ constructor(dataDir) {
146
+ this.dataDir = dataDir;
147
+ }
148
+ get file() {
149
+ return join(this.dataDir, "codex-bindings.json");
150
+ }
151
+ async load() {
152
+ if (this.cache !== undefined)
153
+ return this.cache;
154
+ const pending = (this.loading ??= this.read());
155
+ try {
156
+ this.cache = await pending;
157
+ return this.cache;
158
+ }
159
+ finally {
160
+ if (this.loading === pending)
161
+ this.loading = undefined;
162
+ }
163
+ }
164
+ async read() {
165
+ let text;
166
+ try {
167
+ text = await readFile(this.file, "utf8");
168
+ }
169
+ catch (error) {
170
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
171
+ return {};
172
+ throw new Error("CODEX_SESSION_STATE_CORRUPT: cannot read saved bindings", { cause: error });
173
+ }
174
+ try {
175
+ const parsed = JSON.parse(text);
176
+ return bindingFileSchema.parse(parsed);
177
+ }
178
+ catch (error) {
179
+ throw new Error("CODEX_SESSION_STATE_CORRUPT: invalid saved bindings", {
180
+ cause: error,
181
+ });
182
+ }
183
+ }
184
+ /**
185
+ * 读取独立副本;确实不存在的会话返回 undefined,损坏状态抛错。
186
+ * @param sessionKey - KMH 会话标识。
187
+ * @returns 保存记录的独立副本或 undefined。
188
+ */
189
+ async get(sessionKey) {
190
+ const record = (await this.load())[sessionKey];
191
+ return record === undefined ? undefined : structuredClone(record);
192
+ }
193
+ /**
194
+ * 顺序保存记录;文件写入成功后才接受新状态。
195
+ * @param sessionKey - KMH 会话标识。
196
+ * @param record - 已校验的完整记录。
197
+ */
198
+ async put(sessionKey, record) {
199
+ const accepted = structuredClone(record);
200
+ await this.enqueue(async () => {
201
+ const all = { ...(await this.load()), [sessionKey]: accepted };
202
+ await this.flush(all);
203
+ this.cache = all;
204
+ });
205
+ }
206
+ /**
207
+ * 删除记录并保存;写入失败保留已接受状态。
208
+ * @param sessionKey - KMH 会话标识。
209
+ */
210
+ async delete(sessionKey) {
211
+ await this.enqueue(async () => {
212
+ const all = { ...(await this.load()) };
213
+ if (!(sessionKey in all))
214
+ return;
215
+ delete all[sessionKey];
216
+ await this.flush(all);
217
+ this.cache = all;
218
+ });
219
+ }
220
+ async enqueue(write) {
221
+ const pending = this.writes.then(write);
222
+ // 当前调用收到失败;后继保存仍可按顺序执行。
223
+ this.writes = pending.catch(() => undefined);
224
+ await pending;
225
+ }
226
+ async flush(all) {
227
+ await mkdir(this.dataDir, { recursive: true, mode: 0o700 });
228
+ const temp = `${this.file}.${randomUUID()}.tmp`;
229
+ try {
230
+ await writeFile(temp, JSON.stringify(all), { mode: 0o600, flag: "wx" });
231
+ await rename(temp, this.file);
232
+ }
233
+ catch (error) {
234
+ try {
235
+ await unlink(temp);
236
+ }
237
+ catch (cleanup) {
238
+ if (!(cleanup instanceof Error &&
239
+ "code" in cleanup &&
240
+ cleanup.code === "ENOENT"))
241
+ throw new AggregateError([error, cleanup], "Cannot save bindings or remove its temporary file");
242
+ }
243
+ throw error;
244
+ }
245
+ }
246
+ }
247
+ /**
248
+ * 从保存记录恢复消息处理位置。
249
+ * @param record - 已校验的保存记录。
250
+ * @returns 与原记录独立的消息处理位置。
251
+ */
252
+ export function recordToCursor(record) {
253
+ return {
254
+ fingerprints: [...record.fingerprints],
255
+ delivered: [...(record.delivered ?? [])],
256
+ };
257
+ }
258
+ /**
259
+ * 将原生编号和消息处理位置写回记录;调用方合并创建时工具信息。
260
+ * @param threadId - 官方 Codex 会话编号。
261
+ * @param cursor - 已接受的消息处理位置。
262
+ * @param lastTurnId - 最近完成的官方回合编号。
263
+ * @returns 可合并到原记录的原生编号和消息处理位置。
264
+ */
265
+ export function cursorToRecord(threadId, cursor, lastTurnId) {
266
+ const delivered = cursor.delivered ?? [];
267
+ return {
268
+ threadId: brandString(threadId),
269
+ fingerprints: [...cursor.fingerprints],
270
+ ...(lastTurnId === undefined
271
+ ? {}
272
+ : { lastTurnId: brandString(lastTurnId) }),
273
+ ...(delivered.length === 0 ? {} : { delivered: [...delivered] }),
274
+ };
275
+ }
@@ -0,0 +1,19 @@
1
+ /** 官方 CLI 版本检查与账号状态展示类型。 */
2
+ import type { Context } from "@deepseek-ai/cordis";
3
+ import type { Config } from "./config.ts";
4
+ export type { AccountStatus } from "./account-status.ts";
5
+ /** 支持基线:首个验证通过的官方 CLI 版本。 */
6
+ export declare const MINIMUM_CODEX_VERSION = "0.160.0";
7
+ /** 版本检查结果。 */
8
+ export interface VersionStatus {
9
+ version: string | undefined;
10
+ ok: boolean;
11
+ reason?: string;
12
+ }
13
+ /**
14
+ * 运行 `codex --version` 并对照支持基线。
15
+ * @param ctx - 宿主上下文。
16
+ * @param config - 插件配置。
17
+ * @param signal - 中止信号。
18
+ */
19
+ export declare function checkVersion(ctx: Context, config: Config, signal: AbortSignal): Promise<VersionStatus>;
@@ -0,0 +1,69 @@
1
+ /** 支持基线:首个验证通过的官方 CLI 版本。 */
2
+ export const MINIMUM_CODEX_VERSION = "0.160.0";
3
+ /** 语义化三段比较:负数表示 a 小。 */
4
+ function compare(a, b) {
5
+ for (let index = 0; index < 3; index++) {
6
+ const left = a[index] ?? 0;
7
+ const right = b[index] ?? 0;
8
+ if (left !== right)
9
+ return left - right;
10
+ }
11
+ return 0;
12
+ }
13
+ function parseVersion(text) {
14
+ const match = /(\d+)\.(\d+)\.(\d+)/.exec(text);
15
+ return match
16
+ ? [Number(match[1]), Number(match[2]), Number(match[3])]
17
+ : undefined;
18
+ }
19
+ /**
20
+ * 运行 `codex --version` 并对照支持基线。
21
+ * @param ctx - 宿主上下文。
22
+ * @param config - 插件配置。
23
+ * @param signal - 中止信号。
24
+ */
25
+ export async function checkVersion(ctx, config, signal) {
26
+ const minimum = parseVersion(MINIMUM_CODEX_VERSION);
27
+ if (minimum === undefined)
28
+ throw new Error("CODEX_VERSION_BASELINE_INVALID");
29
+ try {
30
+ const executable = await ctx.subprocess.resolveExecutable(config.command, config.env, signal);
31
+ if (executable === undefined)
32
+ return { version: undefined, ok: false, reason: "CODEX_CLI_MISSING" };
33
+ const text = await new Promise((resolve, reject) => {
34
+ const proc = ctx.subprocess.spawn({
35
+ argv: [executable, "--version"],
36
+ cwd: config.cwd,
37
+ env: config.env,
38
+ graceMs: config.graceMs,
39
+ stdio: { stdin: "ignore", stdout: "pipe", stderr: "pipe" },
40
+ });
41
+ let output = "";
42
+ proc.stdout?.on("data", (chunk) => {
43
+ output += chunk.toString("utf8");
44
+ });
45
+ proc.done.then(() => resolve(output), (error) => reject(error instanceof Error ? error : new Error(String(error))));
46
+ });
47
+ const fullVersion = /^codex-cli ([^\s]+)$/m.exec(text)?.[1];
48
+ const version = fullVersion === undefined ? undefined : parseVersion(fullVersion);
49
+ if (version === undefined || fullVersion === undefined)
50
+ return {
51
+ version: undefined,
52
+ ok: false,
53
+ reason: "CODEX_VERSION_UNPARSED",
54
+ };
55
+ const ok = compare(version, minimum) >= 0;
56
+ return {
57
+ version: fullVersion,
58
+ ok,
59
+ ...(ok ? {} : { reason: "CODEX_VERSION_UNSUPPORTED" }),
60
+ };
61
+ }
62
+ catch (error) {
63
+ return {
64
+ version: undefined,
65
+ ok: false,
66
+ reason: error instanceof Error ? error.message : "CODEX_CLI_MISSING",
67
+ };
68
+ }
69
+ }
@@ -0,0 +1,47 @@
1
+ import type { Context } from "@deepseek-ai/cordis";
2
+ import type { GenerateOptions } from "@deepseek-ai/dsh-llm";
3
+ import { CliTargetId, type CliToolCatalog, type SavedInventoryEntry, type ReadonlyToolSelection } from "./tool-selection.ts";
4
+ import type { CodexCli } from "./index.ts";
5
+ import type { NativeSelection } from "./capabilities.ts";
6
+ /** 一个回合冻结的工具策略:保存的选择、目录、原生开关与进入请求的 Harness 工具名。 */
7
+ export interface PreparedPolicy {
8
+ readonly turn: number;
9
+ readonly choices: ReadonlyToolSelection;
10
+ readonly catalog: CliToolCatalog;
11
+ readonly native: NativeSelection;
12
+ readonly version: string;
13
+ readonly fingerprint: string;
14
+ readonly names: readonly string[];
15
+ readonly inventory: readonly SavedInventoryEntry[];
16
+ }
17
+ /** 保存一次实际路由的工具状态,并把根调用身份固定到该状态。 */
18
+ export declare class CodexToolPolicy {
19
+ private readonly ctx;
20
+ private readonly runtime;
21
+ private readonly lifetime;
22
+ private readonly turns;
23
+ private readonly sessions;
24
+ private readonly roots;
25
+ private readonly work;
26
+ private migration;
27
+ private nativeCache;
28
+ readonly targetId: CliTargetId;
29
+ constructor(ctx: Context, runtime: CodexCli);
30
+ private capture;
31
+ /** 返回配置目录;独立保留 Harness 列及原生侧诊断。 */
32
+ catalog(signal: AbortSignal, refresh?: boolean): Promise<CliToolCatalog>;
33
+ /**
34
+ * 公开注册表只投影模型侧 schema,不含插件来源,Harness 行统一记为 harness。
35
+ * 预设内的工具只在 agent 视图可见:无 agent 时合并全局视图与所有活动 agent 的视图。
36
+ */
37
+ private harnessRows;
38
+ /** 创建时该 Agent 可见的 Harness 工具快照。 */
39
+ private snapshotInventory;
40
+ private nativeCatalog;
41
+ private initialize;
42
+ private importChoices;
43
+ private untilPrepared;
44
+ private preflight;
45
+ /** 已准备回合的冻结策略;辅助请求与未准备的会话返回 undefined,保留既有路径。 */
46
+ forStream(options: GenerateOptions<string>): PreparedPolicy | undefined;
47
+ }