@ktkid/kmh-codex-cli 0.1.1 → 0.1.3

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.
@@ -101,12 +101,13 @@ export class CodexAdapter extends LlmAdapter {
101
101
  ? await this.runtime.sourceBinding(options.sessionId)
102
102
  : undefined;
103
103
  let plan;
104
+ const evidence = this.runtime.historyEvidence(options.sessionId);
104
105
  let increment = diffIncrement(options.messages, {
105
106
  fingerprints: turn.cursor.fingerprints,
106
107
  delivered: turn.pendingDigests,
107
- });
108
+ }, evidence);
108
109
  if (source?.threadId !== undefined) {
109
- plan = forkPlanOf(source, options.messages);
110
+ plan = forkPlanOf(source, options.messages, evidence);
110
111
  increment = plan.increment;
111
112
  }
112
113
  else if (increment.kind === "baseline-lost") {
@@ -114,7 +115,7 @@ export class CodexAdapter extends LlmAdapter {
114
115
  !["prefix-mismatch", "history-shrunk", "history-rewritten"].includes(increment.reason)) {
115
116
  throw new Error(`CODEX_SESSION_HISTORY_MISMATCH: ${increment.reason}`);
116
117
  }
117
- plan = forkPlanOf(record, options.messages);
118
+ plan = forkPlanOf(record, options.messages, evidence);
118
119
  increment = plan.increment;
119
120
  }
120
121
  const consumed = increment.consumed;
@@ -170,7 +171,7 @@ export class CodexAdapter extends LlmAdapter {
170
171
  }
171
172
  }
172
173
  /** 根据源回合已接受的消息位置选择精确的原生回合切点。 */
173
- function forkPlanOf(record, messages) {
174
+ function forkPlanOf(record, messages, evidence) {
174
175
  const threadId = record.threadId;
175
176
  if (threadId === undefined)
176
177
  throw new Error("CODEX_FORK_SOURCE_MISSING");
@@ -183,7 +184,7 @@ function forkPlanOf(record, messages) {
183
184
  fingerprints: turn.fingerprints,
184
185
  delivered: turn.delivered,
185
186
  };
186
- const increment = diffIncrement(messages, cursor);
187
+ const increment = diffIncrement(messages, cursor, evidence);
187
188
  if (increment.kind === "new-input")
188
189
  return {
189
190
  source: { threadId, lastTurnId: turn.turnId },
package/lib/src/config.js CHANGED
@@ -2,8 +2,11 @@
2
2
  import { ToolSelectionSchema } from "./tool-selection.js";
3
3
  import schema from "@deepseek-ai/schemastery";
4
4
  import { dirname, isAbsolute, join } from "node:path";
5
- import { createRequire } from "node:module";
6
- const bundledCommand = join(dirname(createRequire(import.meta.url).resolve("@ktkid/kmh-codex-cli/package.json")), "bin", "codex");
5
+ import { findPackageJSON } from "node:module";
6
+ const packageJson = findPackageJSON(import.meta.url);
7
+ if (packageJson === undefined)
8
+ throw new Error("CODEX_PACKAGE_MANIFEST_MISSING");
9
+ const bundledCommand = join(dirname(packageJson), "bin", "codex");
7
10
  // 共享 schema 保持选择类型;联动检查可在配置 schema 传到客户端后独立执行。
8
11
  const codexToolSelection = schema.intersect([
9
12
  ToolSelectionSchema,
@@ -1,4 +1,4 @@
1
- import type { ImageBlock, RequestMessage, TextBlock } from "@deepseek-ai/dsh-llm";
1
+ import type { ImageBlock, RequestMessage, SystemMessage, TextBlock } from "@deepseek-ai/dsh-llm";
2
2
  /** Codex 支持从 KMH 接收的消息内容。 */
3
3
  export type TurnInputBlock = TextBlock | ImageBlock;
4
4
  export interface ToolResult {
@@ -16,6 +16,11 @@ export interface CursorSnapshot {
16
16
  */
17
17
  delivered: string[];
18
18
  }
19
+ /** 由 DSH 已提交事件证明的系统提示替换和首步未投递输入。 */
20
+ export interface CursorEvidence {
21
+ matchesPreviousPrompt(message: SystemMessage, current: string, expected: string): boolean;
22
+ retryableUserInputs: ReadonlySet<string>;
23
+ }
19
24
  /** 一次差分识别出的待投递增量。 */
20
25
  export type Increment = {
21
26
  kind: "new-input";
@@ -35,6 +40,8 @@ export type Increment = {
35
40
  };
36
41
  /** 空游标:thread 尚未投递任何内容。 */
37
42
  export declare function emptySnapshot(): CursorSnapshot;
43
+ /** 消息指纹(短哈希)。 */
44
+ export declare function messageFingerprint(message: RequestMessage): string;
38
45
  /**
39
46
  * 单个内容块的摘要:与 CodexTurn 投影块(block-end)同算法。
40
47
  * text/reasoning/tool-call/image 四类可摘要;其他块返回 undefined
@@ -49,6 +56,6 @@ export declare function blockDigest(block: unknown): string | undefined;
49
56
  * tool-results 表示尾部是工具调用与结果,应回传给挂起中的 turn;
50
57
  * baseline-lost 表示历史缩短、前缀不同或尾部不符合增量要求,由调用方处理。
51
58
  */
52
- export declare function diffIncrement(messages: readonly RequestMessage[], snapshot: CursorSnapshot): Increment;
59
+ export declare function diffIncrement(messages: readonly RequestMessage[], snapshot: CursorSnapshot, evidence?: CursorEvidence): Increment;
53
60
  /** 计算推进到 total 条后的新快照。 */
54
61
  export declare function snapshotAt(messages: readonly RequestMessage[], total: number, delivered?: string[]): CursorSnapshot;
package/lib/src/cursor.js CHANGED
@@ -41,7 +41,7 @@ function sortObject(value) {
41
41
  return value;
42
42
  }
43
43
  /** 消息指纹(短哈希)。 */
44
- function fingerprint(message) {
44
+ export function messageFingerprint(message) {
45
45
  return createHash("sha256")
46
46
  .update(messageKey(message))
47
47
  .digest("hex")
@@ -140,17 +140,28 @@ function inputSourceOf(message) {
140
140
  * tool-results 表示尾部是工具调用与结果,应回传给挂起中的 turn;
141
141
  * baseline-lost 表示历史缩短、前缀不同或尾部不符合增量要求,由调用方处理。
142
142
  */
143
- export function diffIncrement(messages, snapshot) {
143
+ export function diffIncrement(messages, snapshot, evidence) {
144
144
  const count = snapshot.fingerprints.length;
145
145
  if (count > messages.length)
146
146
  return { kind: "baseline-lost", reason: "history-shrunk" };
147
147
  for (let index = 0; index < count; index++) {
148
148
  const message = messages[index];
149
- if (message === undefined ||
150
- fingerprint(message) !== snapshot.fingerprints[index])
149
+ const expected = snapshot.fingerprints[index];
150
+ if (message === undefined || expected === undefined)
151
+ return { kind: "baseline-lost", reason: "prefix-mismatch" };
152
+ const current = messageFingerprint(message);
153
+ if (current === expected)
154
+ continue;
155
+ if (message.role !== "system" ||
156
+ evidence?.matchesPreviousPrompt(message, current, expected) !== true)
151
157
  return { kind: "baseline-lost", reason: "prefix-mismatch" };
152
158
  }
153
- const tail = messages.slice(count);
159
+ // 工具目录通知由 DSH 保留。Codex 使用工具声明,游标仍推进原请求的位置。
160
+ const tail = messages
161
+ .slice(count)
162
+ .filter((message) => !(message.role === "developer" &&
163
+ message.source.kind === "tool-registry" &&
164
+ message.content.every((block) => block.type === "tool-addition" || block.type === "tool-removal")));
154
165
  const last = tail[tail.length - 1];
155
166
  if (last === undefined)
156
167
  return { kind: "baseline-lost", reason: "empty-increment" };
@@ -159,7 +170,7 @@ export function diffIncrement(messages, snapshot) {
159
170
  const lastTool = tail.findLastIndex((message) => message.role === "tool");
160
171
  if (lastTool >= 0)
161
172
  return toolResultsWithInput(tail, lastTool + 1, messages.length, snapshot);
162
- return newUserInput(tail, messages.length, snapshot);
173
+ return newUserInput(tail, messages.length, snapshot, false, evidence?.retryableUserInputs);
163
174
  }
164
175
  /** 将已核对的工具结果与紧随其后的输入一起交给适配器。 */
165
176
  function toolResultsWithInput(tail, split, total, snapshot) {
@@ -178,7 +189,7 @@ function toolResultsWithInput(tail, split, total, snapshot) {
178
189
  * 核对已生成的回复后,在同一个原生回合按原顺序提交待处理的唤醒消息和本轮输入。
179
190
  * 尾随上下文随输入提交。排在本轮输入前的旧收尾提醒已失效。
180
191
  */
181
- function newUserInput(tail, total, snapshot, mergeUserInputs = false) {
192
+ function newUserInput(tail, total, snapshot, mergeUserInputs = false, retryableUserInputs) {
182
193
  const rest = [...snapshot.delivered];
183
194
  const lastInput = tail.findLastIndex((message) => inputSourceOf(message) !== undefined);
184
195
  if (lastInput < 0)
@@ -202,7 +213,10 @@ function newUserInput(tail, total, snapshot, mergeUserInputs = false) {
202
213
  message.role === "developer" ||
203
214
  source === "kmh-junji:memory-reminder")
204
215
  continue;
205
- if (message.role !== "user" || (source === "user" && !mergeUserInputs))
216
+ if (message.role !== "user" ||
217
+ (source === "user" &&
218
+ !mergeUserInputs &&
219
+ (message.id === undefined || !retryableUserInputs?.has(message.id))))
206
220
  return { kind: "baseline-lost", reason: "unexpected-tail" };
207
221
  if (source === undefined && content.length === 0)
208
222
  continue;
@@ -319,7 +333,7 @@ export function snapshotAt(messages, total, delivered = []) {
319
333
  for (let index = 0; index < total; index++) {
320
334
  const message = messages[index];
321
335
  if (message !== undefined)
322
- fingerprints.push(fingerprint(message));
336
+ fingerprints.push(messageFingerprint(message));
323
337
  }
324
338
  return { fingerprints, delivered: [...delivered] };
325
339
  }
@@ -8,7 +8,9 @@ import { CodexQuotaService } from "./quota.ts";
8
8
  import type { GenerateOptions, StreamChunk } from "@deepseek-ai/dsh-llm";
9
9
  import type { Config } from "./config.ts";
10
10
  import { type NativeSelection } from "./capabilities.ts";
11
- import { emptySnapshot } from "./cursor.ts";
11
+ import { emptySnapshot, type CursorEvidence } from "./cursor.ts";
12
+ import type { ProjectionHandle } from "@deepseek-ai/dsh-session-projection";
13
+ import { type CodexSessionHistory } from "./session-history.ts";
12
14
  import { type CodexModelEntry } from "./models.ts";
13
15
  import { type BindingRecord, type SavedToolPolicy } from "./session-store.ts";
14
16
  import { type PermissionKnobs } from "./isolation.ts";
@@ -43,6 +45,7 @@ export interface RuntimeSettings {
43
45
  }
44
46
  export declare class CodexCli extends Service {
45
47
  readonly config: Config;
48
+ private readonly history?;
46
49
  private catalogCache;
47
50
  private readonly sessions;
48
51
  /** 会话 → CLI 连接实时状态(状态小球轮询数据源)。 */
@@ -56,7 +59,7 @@ export declare class CodexCli extends Service {
56
59
  readonly settings: RuntimeSettings;
57
60
  /** 由 profile 插件挂载的 Config 策略与执行守卫。 */
58
61
  toolPolicy: CodexToolPolicy | undefined;
59
- constructor(ctx: Context, config: Config);
62
+ constructor(ctx: Context, config: Config, history?: ProjectionHandle<CodexSessionHistory> | undefined);
60
63
  /** 本插件自报的工具开关清单;refresh 时重新发现原生目录(详情页选择器读取)。 */
61
64
  toolSwitches(signal: AbortSignal, refresh?: boolean): Promise<ToolSwitchList>;
62
65
  /** 切换一个开关并带修订号写入 profile 配置,返回新清单;只对普通新建会话生效。 */
@@ -80,6 +83,8 @@ export declare class CodexCli extends Service {
80
83
  * @returns 独立记录副本;尚未创建时为空,保存文件损坏时抛错。
81
84
  */
82
85
  bindingRecord(sessionKey: string): Promise<BindingRecord | undefined>;
86
+ /** 给差分校验提供当前会话上已提交的宿主提示变更及失败输入。 */
87
+ historyEvidence(sessionId: GenerateOptions["sessionId"]): CursorEvidence | undefined;
83
88
  /**
84
89
  * 读取分叉的源会话绑定。
85
90
  * @param sessionId - KMH 会话标识。
@@ -138,4 +143,4 @@ export { emptySnapshot };
138
143
  * @param ctx - Plugin owner of the runtime and process ranges.
139
144
  * @param config - Validated execution and storage settings.
140
145
  */
141
- export declare function apply(ctx: Context, config: Config): void;
146
+ export declare function apply(ctx: Context, config: Config): Promise<void>;
package/lib/src/index.js CHANGED
@@ -15,6 +15,7 @@ import { fieldOf } from "./protocol.js";
15
15
  import { CodexAdapter } from "./adapter.js";
16
16
  import { connectCodex } from "./connection.js";
17
17
  import { emptySnapshot } from "./cursor.js";
18
+ import { codexSessionHistory, cursorEvidence, } from "./session-history.js";
18
19
  import { fetchCatalog } from "./models.js";
19
20
  import { CodexSessionStore, cursorToRecord, recordToCursor, } from "./session-store.js";
20
21
  import { prepareIsolation, verifyIsolation, } from "./isolation.js";
@@ -36,6 +37,7 @@ export const inject = [
36
37
  "userQuestions",
37
38
  "attachments",
38
39
  "tools",
40
+ "sessionProjections",
39
41
  ];
40
42
  /** 读取持久化设置;缺失或损坏时按旧开关迁移(feat02 场景7)。 */
41
43
  function loadSettings(config) {
@@ -52,6 +54,7 @@ function loadSettings(config) {
52
54
  }
53
55
  export class CodexCli extends Service {
54
56
  config;
57
+ history;
55
58
  catalogCache;
56
59
  sessions = new Map();
57
60
  /** 会话 → CLI 连接实时状态(状态小球轮询数据源)。 */
@@ -65,9 +68,10 @@ export class CodexCli extends Service {
65
68
  settings;
66
69
  /** 由 profile 插件挂载的 Config 策略与执行守卫。 */
67
70
  toolPolicy;
68
- constructor(ctx, config) {
71
+ constructor(ctx, config, history) {
69
72
  super(ctx, "codexCli");
70
73
  this.config = config;
74
+ this.history = history;
71
75
  this.store = new CodexSessionStore(config.dataDir);
72
76
  this.account = new CodexAccount(ctx, config);
73
77
  this.quota = new CodexQuotaService(ctx, config);
@@ -182,15 +186,27 @@ export class CodexCli extends Service {
182
186
  async bindingRecord(sessionKey) {
183
187
  return await this.store.get(sessionKey);
184
188
  }
189
+ /** 给差分校验提供当前会话上已提交的宿主提示变更及失败输入。 */
190
+ historyEvidence(sessionId) {
191
+ if (sessionId === undefined || this.history === undefined)
192
+ return undefined;
193
+ const session = this.ctx.get("sessions")?.get(sessionId);
194
+ return session === undefined
195
+ ? undefined
196
+ : cursorEvidence(this.history.stateOf(session));
197
+ }
185
198
  /**
186
199
  * 读取分叉的源会话绑定。
187
200
  * @param sessionId - KMH 会话标识。
188
201
  * @returns 父会话记录;普通会话或父记录缺失时为空。
189
202
  */
190
203
  async sourceBinding(sessionId) {
191
- const parent = sessionId === undefined
204
+ const session = sessionId === undefined
192
205
  ? undefined
193
- : this.ctx.get("sessions")?.get(sessionId)?.header.parentSession;
206
+ : this.ctx.get("sessions")?.get(sessionId);
207
+ const parent = session?.header.isSeeded
208
+ ? session.header.parentSession
209
+ : undefined;
194
210
  return parent === undefined ? undefined : this.store.get(parent);
195
211
  }
196
212
  /**
@@ -525,8 +541,9 @@ export { emptySnapshot };
525
541
  * @param ctx - Plugin owner of the runtime and process ranges.
526
542
  * @param config - Validated execution and storage settings.
527
543
  */
528
- export function apply(ctx, config) {
529
- const runtime = new CodexCli(ctx, config);
544
+ export async function apply(ctx, config) {
545
+ const history = await ctx.sessionProjections.register(codexSessionHistory);
546
+ const runtime = new CodexCli(ctx, config, history);
530
547
  ctx.codexCli = runtime;
531
548
  runtime.toolPolicy = new CodexToolPolicy(ctx, runtime);
532
549
  ctx.llm.registerAdapter(["codex-cli"], new CodexAdapter(runtime));
@@ -0,0 +1,18 @@
1
+ import type { ProjectionDefinition } from "@deepseek-ai/dsh-session-projection";
2
+ import { z } from "zod";
3
+ import { type CursorEvidence } from "./cursor.ts";
4
+ declare const stateSchema: z.ZodObject<{
5
+ prompts: z.ZodRecord<z.ZodString, z.ZodObject<{
6
+ fingerprint: z.ZodString;
7
+ replaces: z.ZodOptional<z.ZodNumber>;
8
+ }, z.core.$strip>>;
9
+ replacements: z.ZodRecord<z.ZodString, z.ZodNumber>;
10
+ firstStepInputs: z.ZodNullable<z.ZodArray<z.ZodString>>;
11
+ retryableUserInputs: z.ZodArray<z.ZodString>;
12
+ }, z.core.$strip>;
13
+ export type CodexSessionHistory = z.infer<typeof stateSchema>;
14
+ /** 会话恢复时由 DSH 重放。状态仅保留指纹、替换关系及输入编号。 */
15
+ export declare const codexSessionHistory: ProjectionDefinition<"kmh-codex-cli/session-history", CodexSessionHistory>;
16
+ /** 只为同一条系统提示的已记录前身提供兼容匹配。 */
17
+ export declare function cursorEvidence(history: CodexSessionHistory): CursorEvidence;
18
+ export {};
@@ -0,0 +1,113 @@
1
+ /** 投影 Codex 差分所需的宿主提示替换与首步投递失败记录。 */
2
+ import { isReplacementSurfaceEvent } from "@deepseek-ai/dsh-session";
3
+ import { z } from "zod";
4
+ import { messageFingerprint } from "./cursor.js";
5
+ const stateSchema = z.object({
6
+ prompts: z.record(z.string(), z.object({
7
+ fingerprint: z.string(),
8
+ replaces: z.number().int().nonnegative().optional(),
9
+ })),
10
+ replacements: z.record(z.string(), z.number().int().nonnegative()),
11
+ firstStepInputs: z.array(z.string()).nullable(),
12
+ retryableUserInputs: z.array(z.string()),
13
+ });
14
+ /** 会话恢复时由 DSH 重放。状态仅保留指纹、替换关系及输入编号。 */
15
+ export const codexSessionHistory = {
16
+ key: "kmh-codex-cli/session-history",
17
+ stateSchema,
18
+ stateVersion: 1,
19
+ init: () => ({
20
+ prompts: {},
21
+ replacements: {},
22
+ firstStepInputs: null,
23
+ retryableUserInputs: [],
24
+ }),
25
+ apply(state, event) {
26
+ if (event.type === "system/message") {
27
+ const message = event.data.message;
28
+ if (message.source.kind !== "system-prompt")
29
+ return state;
30
+ const seq = event.seq;
31
+ const target = isReplacementSurfaceEvent(event) &&
32
+ event.surfaceOp.startSeq === event.surfaceOp.endSeq
33
+ ? event.surfaceOp.startSeq
34
+ : undefined;
35
+ const replaces = target !== undefined && Object.hasOwn(state.prompts, target)
36
+ ? target
37
+ : undefined;
38
+ return {
39
+ ...state,
40
+ prompts: {
41
+ ...state.prompts,
42
+ [seq]: {
43
+ fingerprint: messageFingerprint(message),
44
+ ...(replaces === undefined ? {} : { replaces }),
45
+ },
46
+ },
47
+ replacements: replaces === undefined
48
+ ? state.replacements
49
+ : { ...state.replacements, [message.id]: seq },
50
+ };
51
+ }
52
+ if (event.type === "step/start") {
53
+ const firstStepInputs = event.data.step === 1 ? [] : null;
54
+ return firstStepInputs === state.firstStepInputs
55
+ ? state
56
+ : { ...state, firstStepInputs };
57
+ }
58
+ if (event.type === "user/message") {
59
+ if (state.firstStepInputs === null ||
60
+ event.surfaceOp !== "append" ||
61
+ event.data.source.kind !== "user")
62
+ return state;
63
+ return {
64
+ ...state,
65
+ firstStepInputs: [...state.firstStepInputs, event.data.id],
66
+ };
67
+ }
68
+ if (event.type === "turn/end") {
69
+ if (state.firstStepInputs === null)
70
+ return state;
71
+ const { reason } = event.data;
72
+ // 适配器在请求原生回合前拒绝这类分叉。其它失败可能发生在原生接纳之后。
73
+ const unaccepted = reason.kind === "error" &&
74
+ reason.error.code === "CODEX_FORK_BOUNDARY_UNSUPPORTED";
75
+ return {
76
+ ...state,
77
+ firstStepInputs: null,
78
+ retryableUserInputs: unaccepted
79
+ ? [...state.retryableUserInputs, ...state.firstStepInputs]
80
+ : state.retryableUserInputs,
81
+ };
82
+ }
83
+ return state;
84
+ },
85
+ };
86
+ /** 只为同一条系统提示的已记录前身提供兼容匹配。 */
87
+ export function cursorEvidence(history) {
88
+ return {
89
+ matchesPreviousPrompt(message, current, expected) {
90
+ let seq = Object.hasOwn(history.replacements, message.id)
91
+ ? history.replacements[message.id]
92
+ : undefined;
93
+ if (seq === undefined)
94
+ return false;
95
+ const prompt = history.prompts[seq];
96
+ if (prompt?.fingerprint !== current)
97
+ return false;
98
+ for (let replaces = prompt.replaces; replaces !== undefined;) {
99
+ if (replaces >= seq)
100
+ return false;
101
+ const previous = history.prompts[replaces];
102
+ if (previous === undefined)
103
+ return false;
104
+ if (previous.fingerprint === expected)
105
+ return true;
106
+ seq = replaces;
107
+ replaces = previous.replaces;
108
+ }
109
+ return false;
110
+ },
111
+ retryableUserInputs: new Set(history.retryableUserInputs),
112
+ };
113
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ktkid/kmh-codex-cli",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "type": "module",
5
5
  "description": "Official Codex CLI app-server transport and KMH account UI",
6
6
  "license": "MIT",
@@ -76,7 +76,7 @@
76
76
  "react-dom": "^18.3.1"
77
77
  },
78
78
  "dependencies": {
79
- "zod": "^4.4.3",
79
+ "zod": "4.4.3",
80
80
  "@openai/codex-darwin-arm64": "npm:@openai/codex@0.163.0-alpha.10.2-darwin-arm64"
81
81
  },
82
82
  "devDependencies": {
@@ -169,5 +169,6 @@
169
169
  ],
170
170
  "cpu": [
171
171
  "arm64"
172
- ]
172
+ ],
173
+ "gitHead": "9d90441b0c8aa7b253d839c7f50607a653405a84"
173
174
  }