@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,132 @@
1
+ import { addAbortListener } from "node:events";
2
+ import { readFile, realpath, stat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { isAbsolute, join, relative, sep } from "node:path";
5
+ import { z } from "zod";
6
+ import { connectCodex } from "./connection.js";
7
+ import { prepareIsolation, verifyIsolation } from "./isolation.js";
8
+ import { DEFAULT_SELECTION } from "./capabilities.js";
9
+ import { ImageGenerationItemParams, QuotaAccountResult, ThreadResult, TurnCompletedParams, TurnResult, TurnStartParams, } from "./protocol.js";
10
+ import { pngSizeOf } from "./image-delivery.js";
11
+ export { Config } from "./config.js";
12
+ /** 专用服务请求;模型和执行时限由部署者配置。 */
13
+ export const ImageRequest = z
14
+ .object({ prompt: z.string().trim().min(1).max(16000) })
15
+ .strict();
16
+ const ImageEvent = z.object({
17
+ threadId: z.string(),
18
+ item: ImageGenerationItemParams,
19
+ });
20
+ const MAX_IMAGE_BYTES = 32 * 1024 * 1024;
21
+ /**
22
+ * 使用本机 ChatGPT 登录执行一次生图;signal 中止或 CLI 出错时抛出错误类别。
23
+ * 返回的字节来自本次 thread 的 generated_images 目录,返回前已释放全部 CLI 进程。
24
+ */
25
+ export async function generateImage(ctx, config, input, signal) {
26
+ const request = ImageRequest.parse(input);
27
+ const plan = await prepareIsolation(ctx, config, {
28
+ cwd: config.cwd,
29
+ signal,
30
+ selection: DEFAULT_SELECTION,
31
+ imageOnly: true,
32
+ });
33
+ const connection = await connectCodex(ctx, {
34
+ command: config.command,
35
+ cwd: config.cwd,
36
+ env: config.env,
37
+ graceMs: config.graceMs,
38
+ startupTimeoutMs: config.startupTimeoutMs,
39
+ configOverrides: [
40
+ ...plan.configOverrides,
41
+ 'model_provider="openai"',
42
+ 'forced_login_method="chatgpt"',
43
+ 'sandbox_mode="read-only"',
44
+ 'approval_policy="never"',
45
+ ],
46
+ }, signal);
47
+ try {
48
+ await verifyIsolation(connection, plan, signal);
49
+ const identity = QuotaAccountResult.parse(await connection.request("account/read", { refreshToken: false }, signal));
50
+ if (identity.account?.type !== "chatgpt")
51
+ throw new Error("CODEX_IMAGE_CHATGPT_REQUIRED");
52
+ connection.onServerRequest(() => Promise.reject(new Error("CODEX_IMAGE_TOOL_DENIED")));
53
+ const started = ThreadResult.parse(await connection.request("thread/start", {
54
+ model: config.model || "gpt-6.1-sol",
55
+ ephemeral: true,
56
+ cwd: config.cwd,
57
+ baseInstructions: "You generate exactly one image for the user's request. Call image_gen.imagegen directly. Use only the native image generation tool. After the image completes, finish with a short confirmation.",
58
+ dynamicTools: [],
59
+ }, signal));
60
+ const threadId = started.thread.id;
61
+ const completed = Promise.withResolvers();
62
+ const images = new Map();
63
+ connection.onNotification((method, params) => {
64
+ try {
65
+ if (method === "item/completed") {
66
+ const event = ImageEvent.safeParse(params);
67
+ if (event.success &&
68
+ event.data.threadId === threadId &&
69
+ event.data.item.status === "completed" &&
70
+ event.data.item.savedPath)
71
+ images.set(event.data.item.id, event.data.item.savedPath);
72
+ }
73
+ else if (method === "turn/completed") {
74
+ const event = TurnCompletedParams.parse(params);
75
+ if (event.threadId !== threadId)
76
+ return;
77
+ if (event.turn.status === "completed")
78
+ completed.resolve();
79
+ else
80
+ completed.reject(new Error("CODEX_IMAGE_TURN_FAILED"));
81
+ }
82
+ }
83
+ catch (error) {
84
+ completed.reject(error);
85
+ }
86
+ });
87
+ const abort = addAbortListener(signal, () => completed.reject(signal.reason));
88
+ // 启动失败与进程提前退出也消费终态 Promise,避免迟到拒绝成为未处理异常。
89
+ completed.promise.catch(() => undefined);
90
+ connection.done
91
+ .then(() => completed.reject(new Error("CODEX_IMAGE_PROCESS_EXITED")), () => completed.reject(new Error("CODEX_IMAGE_PROCESS_EXITED")))
92
+ .catch(() => undefined);
93
+ try {
94
+ TurnResult.parse(await connection.request("turn/start", TurnStartParams.parse({
95
+ threadId,
96
+ input: [{ type: "text", text: request.prompt }],
97
+ model: config.model || "gpt-6.1-sol",
98
+ effort: "medium",
99
+ summary: "none",
100
+ }), signal));
101
+ await completed.promise;
102
+ signal.throwIfAborted();
103
+ const [savedPath] = images.values();
104
+ if (savedPath === undefined)
105
+ throw new Error("CODEX_IMAGE_MISSING");
106
+ const codexHome = config.env.CODEX_HOME ||
107
+ process.env.CODEX_HOME ||
108
+ join(homedir(), ".codex");
109
+ const allowed = await realpath(join(codexHome, "generated_images", threadId));
110
+ const file = await realpath(savedPath);
111
+ const within = relative(allowed, file);
112
+ if (within === "" ||
113
+ within === ".." ||
114
+ within.startsWith(`..${sep}`) ||
115
+ isAbsolute(within))
116
+ throw new Error("CODEX_IMAGE_PATH_REJECTED");
117
+ if ((await stat(file)).size > MAX_IMAGE_BYTES)
118
+ throw new Error("CODEX_IMAGE_TOO_LARGE");
119
+ const data = await readFile(file);
120
+ const size = pngSizeOf(data);
121
+ if (size === undefined)
122
+ throw new Error("CODEX_IMAGE_INVALID_PNG");
123
+ return { data, ...size };
124
+ }
125
+ finally {
126
+ abort[Symbol.dispose]();
127
+ }
128
+ }
129
+ finally {
130
+ await connection.stop(config.cleanupTimeoutMs);
131
+ }
132
+ }
@@ -0,0 +1,141 @@
1
+ import { Service, type Context } from "@deepseek-ai/cordis";
2
+ import type { SessionLiveState } from "./live-state.ts";
3
+ export type { SessionLiveState } from "./live-state.ts";
4
+ import { CodexToolPolicy } from "./tool-policy.ts";
5
+ import type { ToolSwitchList, ToolSwitchUpdate } from "./tool-switches.ts";
6
+ import { CodexAccount } from "./account.ts";
7
+ import { CodexQuotaService } from "./quota.ts";
8
+ import type { GenerateOptions, StreamChunk } from "@deepseek-ai/dsh-llm";
9
+ import type { Config } from "./config.ts";
10
+ import { type NativeSelection } from "./capabilities.ts";
11
+ import { emptySnapshot } from "./cursor.ts";
12
+ import { type CodexModelEntry } from "./models.ts";
13
+ import { type BindingRecord, type SavedToolPolicy } from "./session-store.ts";
14
+ import { type PermissionKnobs } from "./isolation.ts";
15
+ import { CodexTurn } from "./turn.ts";
16
+ export { Config } from "./config.ts";
17
+ export { connectCodex, CodexConnection } from "./connection.ts";
18
+ export { CodexAdapter } from "./adapter.ts";
19
+ export * from "./protocol.ts";
20
+ export { CodexQuotaService } from "./quota.ts";
21
+ /** Cordis plugin identity. */
22
+ export declare const name = "kmh/codex-cli";
23
+ /** Required model, process, user-interaction and attachment services(审批桥与生图投影依赖)。 */
24
+ export declare const inject: string[];
25
+ declare module "@deepseek-ai/cordis" {
26
+ interface Context {
27
+ codexCli: CodexCli;
28
+ }
29
+ }
30
+ /**
31
+ * Own shared runtime state for the Codex CLI provider.
32
+ * 目录缓存、会话串行与 thread 绑定挂在此服务上,adapter 与 Web 共用。
33
+ */
34
+ /** 详情页可变设置:逐项选择与最近测试结果。 */
35
+ export interface RuntimeSettings {
36
+ selection: NativeSelection;
37
+ defaultModel?: string;
38
+ lastProbe?: {
39
+ at: string;
40
+ ok: boolean;
41
+ error?: string;
42
+ };
43
+ }
44
+ export declare class CodexCli extends Service {
45
+ readonly config: Config;
46
+ private catalogCache;
47
+ private readonly sessions;
48
+ /** 会话 → CLI 连接实时状态(状态小球轮询数据源)。 */
49
+ private readonly liveStates;
50
+ private readonly store;
51
+ /** 账号操作(状态/登录/取消/退出)。 */
52
+ readonly account: CodexAccount;
53
+ readonly quota: CodexQuotaService;
54
+ readonly settingsNamespace: string | null;
55
+ /** 详情页可变设置;逐项选择立即保存、下一回合生效。 */
56
+ readonly settings: RuntimeSettings;
57
+ /** 由 profile 插件挂载的 Config 策略与执行守卫。 */
58
+ toolPolicy: CodexToolPolicy | undefined;
59
+ constructor(ctx: Context, config: Config);
60
+ /** 本插件自报的工具开关清单;refresh 时重新发现原生目录(详情页选择器读取)。 */
61
+ toolSwitches(signal: AbortSignal, refresh?: boolean): Promise<ToolSwitchList>;
62
+ /** 切换一个开关并带修订号写入 profile 配置,返回新清单;只对普通新建会话生效。 */
63
+ setToolSwitch(update: ToolSwitchUpdate, signal: AbortSignal): Promise<ToolSwitchList>;
64
+ /** 保存逐项选择:原子落盘后立即生效于下一回合(进行中回合不受影响)。 */
65
+ saveSelection(selection: NativeSelection): Promise<void>;
66
+ /** 解析请求会话的工作目录;查不到时回落插件配置 cwd。 */
67
+ resolveCwd(sessionId: GenerateOptions["sessionId"]): string;
68
+ /** 权限档回落:与 kmh-web 组合默认(workspace-write + ask)一致。 */
69
+ private static readonly DEFAULT_PERMISSION;
70
+ /**
71
+ * 读取会话所属沙箱与审批服务的生效权限;缺少会话或服务读取失败时使用
72
+ * workspace-write + ask。每次 start 重新读取,进行中回合保留开始时的档位。
73
+ */
74
+ resolvePermission(sessionId: GenerateOptions["sessionId"]): PermissionKnobs;
75
+ /** 模型目录缓存;每次调用复用在途请求。 */
76
+ catalog(): Promise<CodexModelEntry[]>;
77
+ /**
78
+ * 读取会话的持久化绑定记录。
79
+ * @param sessionKey - KMH 会话标识。
80
+ * @returns 独立记录副本;尚未创建时为空,保存文件损坏时抛错。
81
+ */
82
+ bindingRecord(sessionKey: string): Promise<BindingRecord | undefined>;
83
+ /**
84
+ * 读取分叉的源会话绑定。
85
+ * @param sessionId - KMH 会话标识。
86
+ * @returns 父会话记录;普通会话或父记录缺失时为空。
87
+ */
88
+ sourceBinding(sessionId: GenerateOptions["sessionId"]): Promise<BindingRecord | undefined>;
89
+ /**
90
+ * 保存创建时工具信息;保留已经接受的原生编号和消息处理位置。
91
+ * @param sessionKey - KMH 会话标识。
92
+ * @param toolPolicy - 创建时的完整工具选择与目录。
93
+ */
94
+ saveToolPolicy(sessionKey: string, toolPolicy: SavedToolPolicy): Promise<void>;
95
+ /**
96
+ * 持久化会话绑定并保留创建时的工具信息。
97
+ * @param sessionKey - KMH 会话标识。
98
+ * @param turn - 持有原生编号及消息处理位置的回合。
99
+ * @param inheritedTurns - 原生分叉实际继承的完成回合;缺省保留原记录。
100
+ */
101
+ recordBinding(sessionKey: string, turn: CodexTurn, inheritedTurns?: NonNullable<BindingRecord["turns"]>): Promise<void>;
102
+ /** 恢复会话 turn 的差分游标(进程重启后续聊不重复投递)。 */
103
+ private restoreCursor;
104
+ /** 会话终止后释放其 turn 归属。 */
105
+ releaseSession(turn: CodexTurn): void;
106
+ /** 记录会话的 CLI 连接实时状态(小球数据源)。 */
107
+ private markLive;
108
+ /**
109
+ * 全部会话的实时状态快照(/api/codex-cli/live 返回体)。
110
+ * 空闲但 turn 仍挂起工具回执属正常步间状态(KMH 执行完工具会续推),
111
+ * 重试期间红色状态携带原因;停止或完成后 streaming 为 false。
112
+ */
113
+ liveSnapshot(): {
114
+ sessions: Array<SessionLiveState & {
115
+ sessionId: string;
116
+ }>;
117
+ };
118
+ /**
119
+ * 会话内串行执行:同一会话的 turn 操作排队,共用同一 CodexTurn。
120
+ * @param sessionKey - 会话标识。
121
+ * @param cwd - 会话工作目录。
122
+ * @param run - 本次要执行的流式驱动。
123
+ * @param signal - 排队等待的取消与超时信号。
124
+ */
125
+ withSession(sessionKey: string, cwd: string, run: (turn: CodexTurn) => AsyncGenerator<StreamChunk>, signal?: AbortSignal): AsyncGenerator<StreamChunk>;
126
+ /** 取或建会话状态;已终止的 turn 重建以复用绑定。 */
127
+ private stateOf;
128
+ /**
129
+ * 辅助请求(标题生成、压缩评估):独立临时会话,完成后回收。
130
+ * 业务 thread 绑定与历史不受影响。
131
+ */
132
+ streamAuxiliary(options: GenerateOptions<string>): AsyncGenerator<StreamChunk>;
133
+ }
134
+ /** 空游标导出(临时会话与测试用)。 */
135
+ export { emptySnapshot };
136
+ /**
137
+ * Register the provider runtime and adapter routes.
138
+ * @param ctx - Plugin owner of the runtime and process ranges.
139
+ * @param config - Validated execution and storage settings.
140
+ */
141
+ export declare function apply(ctx: Context, config: Config): void;