@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,97 @@
1
+ /** 浏览器与宿主共用的只读额度协议;时间统一为毫秒。 */
2
+ import { z } from "zod";
3
+ const timestamp = z.number().int().nonnegative().max(8640000000000000);
4
+ /** 传输层校验字段类型,范围与默认值由宿主 Config 定义。 */
5
+ export const QuotaPreferences = z.object({
6
+ quotaDisplayMode: z.enum(["percent", "bar", "off"]),
7
+ quotaAlertsEnabled: z.boolean(),
8
+ quotaShortThresholdPercent: z.number(),
9
+ quotaWeeklyThresholdPercent: z.number(),
10
+ });
11
+ export const QuotaContext = z.object({
12
+ settingsNamespace: z.string().min(1).nullable(),
13
+ preferences: QuotaPreferences,
14
+ });
15
+ export const QuotaQuery = z
16
+ .object({
17
+ detail: z.enum(["summary", "full"]).default("summary"),
18
+ force: z.enum(["0", "1"]).default("0"),
19
+ })
20
+ .strict();
21
+ export const QuotaWindow = z.object({
22
+ usedPercent: z.number().min(0).max(100),
23
+ remainingPercent: z.number().min(0).max(100),
24
+ windowMinutes: z.number().int().positive().nullable(),
25
+ resetsAtMs: timestamp.nullable(),
26
+ });
27
+ export const QuotaGroup = z.object({
28
+ id: z.string(),
29
+ name: z.string().nullable(),
30
+ windows: z.array(QuotaWindow),
31
+ });
32
+ export const QuotaError = z.object({
33
+ area: z.enum(["account", "windows", "credits", "spend", "resets"]),
34
+ code: z.enum(["read-failed", "invalid-data", "unsupported"]),
35
+ message: z.string(),
36
+ });
37
+ export const QuotaView = z.object({
38
+ accountEpoch: z.number().int().nonnegative(),
39
+ state: z.enum(["loading", "ready", "signed-out", "unsupported", "error"]),
40
+ fetchedAtMs: timestamp.nullable(),
41
+ nextRefreshAtMs: timestamp,
42
+ groups: z.array(QuotaGroup),
43
+ credits: z
44
+ .object({
45
+ hasCredits: z.boolean(),
46
+ unlimited: z.boolean(),
47
+ balance: z.string().nullable(),
48
+ })
49
+ .nullable(),
50
+ creditsAtMs: timestamp.nullable(),
51
+ spend: z
52
+ .object({
53
+ limit: z.string(),
54
+ used: z.string(),
55
+ remainingPercent: z.number().min(0).max(100),
56
+ resetsAtMs: timestamp,
57
+ })
58
+ .nullable(),
59
+ spendAtMs: timestamp.nullable(),
60
+ resets: z
61
+ .object({
62
+ availableCount: z
63
+ .number()
64
+ .int()
65
+ .nonnegative()
66
+ .max(Number.MAX_SAFE_INTEGER),
67
+ cards: z
68
+ .array(z.object({
69
+ id: z.string(),
70
+ title: z.string().nullable(),
71
+ description: z.string().nullable(),
72
+ status: z.string(),
73
+ expiresAtMs: timestamp.nullable(),
74
+ }))
75
+ .nullable(),
76
+ })
77
+ .nullable(),
78
+ resetsAtMs: timestamp.nullable(),
79
+ errors: z.array(QuotaError),
80
+ });
81
+ /** 初始化或账号失效时清空所有区域,保留共享冷却时间。 */
82
+ export function emptyQuota(accountEpoch = 0, nextRefreshAtMs = 0) {
83
+ return {
84
+ accountEpoch,
85
+ state: "loading",
86
+ fetchedAtMs: null,
87
+ nextRefreshAtMs,
88
+ groups: [],
89
+ credits: null,
90
+ creditsAtMs: null,
91
+ spend: null,
92
+ spendAtMs: null,
93
+ resets: null,
94
+ resetsAtMs: null,
95
+ errors: [],
96
+ };
97
+ }
@@ -0,0 +1,18 @@
1
+ /** 额度展示的纯规则;模型匹配依据参考插件 sidebar-quota.js 的精确、Spark、Reserve 规则。 */
2
+ import type { QuotaGroup, QuotaPreferences, QuotaWindow } from "./quota-protocol.ts";
3
+ export declare const QUOTA_MIN_INTERVAL_MS = 300000;
4
+ /** 覆盖响应头与正文读取,给宿主15秒中止和进程收尾保留余量。 */
5
+ export declare const QUOTA_HTTP_TIMEOUT_MS = 30000;
6
+ export declare const QUOTA_HTTP_TIMEOUT_ERROR = "QUOTA_HTTP_TIMEOUT";
7
+ export declare const QUOTA_REFRESH_INTERVAL_MS = 300000;
8
+ export declare const QUOTA_ERROR_BACKOFF_MS = 300000;
9
+ export declare const QUOTA_STALE_AFTER_MS = 300000;
10
+ export declare const QUOTA_DETAIL_CACHE_MS = 300000;
11
+ /** 已确认的周期分类;其他时长保留实际值。 */
12
+ export declare function windowKind(window: QuotaWindow): "short" | "weekly" | "other";
13
+ /** 仅新鲜且重置时间仍有效的结果可以触发颜色提醒。 */
14
+ export declare function windowFresh(window: QuotaWindow, at: number | null, now: number): boolean;
15
+ /** 阈值采用原始百分比严格小于比较,显示舍入保持独立。 */
16
+ export declare function windowLow(window: QuotaWindow, at: number | null, now: number, settings: QuotaPreferences | null): boolean;
17
+ /** 缺失独立额度组保留未知状态,普通模型共享 codex 主组。 */
18
+ export declare function modelQuota(groups: readonly QuotaGroup[], model: string): QuotaWindow[];
@@ -0,0 +1,49 @@
1
+ export const QUOTA_MIN_INTERVAL_MS = 300000;
2
+ /** 覆盖响应头与正文读取,给宿主15秒中止和进程收尾保留余量。 */
3
+ export const QUOTA_HTTP_TIMEOUT_MS = 30000;
4
+ export const QUOTA_HTTP_TIMEOUT_ERROR = "QUOTA_HTTP_TIMEOUT";
5
+ export const QUOTA_REFRESH_INTERVAL_MS = QUOTA_MIN_INTERVAL_MS;
6
+ export const QUOTA_ERROR_BACKOFF_MS = QUOTA_MIN_INTERVAL_MS;
7
+ export const QUOTA_STALE_AFTER_MS = QUOTA_MIN_INTERVAL_MS;
8
+ export const QUOTA_DETAIL_CACHE_MS = QUOTA_MIN_INTERVAL_MS;
9
+ /** 已确认的周期分类;其他时长保留实际值。 */
10
+ export function windowKind(window) {
11
+ return window.windowMinutes === 300
12
+ ? "short"
13
+ : window.windowMinutes === 10080
14
+ ? "weekly"
15
+ : "other";
16
+ }
17
+ /** 仅新鲜且重置时间仍有效的结果可以触发颜色提醒。 */
18
+ export function windowFresh(window, at, now) {
19
+ return (at !== null &&
20
+ now >= at &&
21
+ now - at <= QUOTA_STALE_AFTER_MS &&
22
+ (window.resetsAtMs === null || window.resetsAtMs > now));
23
+ }
24
+ /** 阈值采用原始百分比严格小于比较,显示舍入保持独立。 */
25
+ export function windowLow(window, at, now, settings) {
26
+ if (!settings?.quotaAlertsEnabled || !windowFresh(window, at, now))
27
+ return false;
28
+ const kind = windowKind(window);
29
+ return kind === "short"
30
+ ? window.remainingPercent < settings.quotaShortThresholdPercent
31
+ : kind === "weekly" &&
32
+ window.remainingPercent < settings.quotaWeeklyThresholdPercent;
33
+ }
34
+ const normalize = (value) => value.toLocaleLowerCase("en-US").replaceAll(/[^a-z0-9]+/gu, "-");
35
+ /** 缺失独立额度组保留未知状态,普通模型共享 codex 主组。 */
36
+ export function modelQuota(groups, model) {
37
+ const key = normalize(model);
38
+ const exact = groups.filter((g) => [g.id, g.name].some((v) => v !== null && normalize(v) === key));
39
+ const selected = exact.length > 0
40
+ ? exact
41
+ : key === "gpt-reserve"
42
+ ? []
43
+ : /\bspark\b/u.test(key)
44
+ ? groups.filter((g) => /\bspark\b/u.test(normalize(`${g.id} ${g.name ?? ""}`)))
45
+ : groups.filter((g) => g.id === "codex");
46
+ return selected
47
+ .flatMap((g) => g.windows)
48
+ .sort((a, b) => (a.windowMinutes ?? Infinity) - (b.windowMinutes ?? Infinity));
49
+ }
@@ -0,0 +1,32 @@
1
+ /** 官方 CLI 只读额度读取:共享请求、五分钟冷却、账号代数及分区投影。 */
2
+ import type { Context } from "@deepseek-ai/cordis";
3
+ import type { Config } from "./config.ts";
4
+ import { type CodexConnection } from "./connection.ts";
5
+ import { QuotaView } from "./quota-protocol.ts";
6
+ export type QuotaConnection = Pick<CodexConnection, "request" | "stop" | "onNotification">;
7
+ export interface QuotaDependencies {
8
+ now?: () => number;
9
+ connect?: (signal: AbortSignal) => Promise<QuotaConnection>;
10
+ }
11
+ export declare class CodexQuotaService {
12
+ private readonly config;
13
+ private view;
14
+ private inFlight;
15
+ private controller;
16
+ private identity;
17
+ private accountKey;
18
+ private disposed;
19
+ private readonly now;
20
+ private readonly connect;
21
+ constructor(ctx: Context, config: Config, dependencies?: QuotaDependencies);
22
+ /** 返回副本,消费者无法修改共享缓存。 */
23
+ snapshot(): QuotaView;
24
+ /** 账号变化立即淘汰所有区域;冷却时间保留,旧请求失去提交资格。 */
25
+ invalidate(state?: "loading" | "signed-out"): void;
26
+ /** 插件卸载中止读取;共享等待者仍由同一回收路径完成。 */
27
+ dispose(): void;
28
+ /** 自动读取与 force 均共享同一冷却;force 只表达刷新意图。 */
29
+ read(): Promise<QuotaView>;
30
+ private load;
31
+ private project;
32
+ }
@@ -0,0 +1,227 @@
1
+ import { connectCodex } from "./connection.js";
2
+ import { Method, fieldOf, QuotaAccountResult, NativeQuotaResult, NativeQuotaSnapshot, NativeQuotaWindow, NativeCredits, NativeSpendLimit, NativeResetCredits, } from "./protocol.js";
3
+ import { emptyQuota, QuotaView, } from "./quota-protocol.js";
4
+ import { QUOTA_MIN_INTERVAL_MS } from "./quota-rules.js";
5
+ /** errors 中只发送稳定文案,原始 RPC 错误与账号标识保留在宿主。 */
6
+ function failure(area, code = "invalid-data") {
7
+ return {
8
+ area,
9
+ code,
10
+ message: code === "unsupported"
11
+ ? "This CLI version does not support quota reads"
12
+ : code === "read-failed"
13
+ ? "Quota read failed; retry after the cooldown"
14
+ : "This quota section is temporarily unavailable",
15
+ };
16
+ }
17
+ export class CodexQuotaService {
18
+ config;
19
+ view = emptyQuota();
20
+ inFlight;
21
+ controller;
22
+ identity;
23
+ accountKey;
24
+ disposed = false;
25
+ now;
26
+ connect;
27
+ constructor(ctx, config, dependencies = {}) {
28
+ this.config = config;
29
+ this.now = dependencies.now ?? Date.now;
30
+ this.connect =
31
+ dependencies.connect ??
32
+ ((signal) => connectCodex(ctx, {
33
+ command: config.command,
34
+ cwd: config.cwd,
35
+ env: config.env,
36
+ configOverrides: [],
37
+ graceMs: config.graceMs,
38
+ startupTimeoutMs: config.startupTimeoutMs,
39
+ }, signal));
40
+ }
41
+ /** 返回副本,消费者无法修改共享缓存。 */
42
+ snapshot() {
43
+ return structuredClone(this.view);
44
+ }
45
+ /** 账号变化立即淘汰所有区域;冷却时间保留,旧请求失去提交资格。 */
46
+ invalidate(state = "loading") {
47
+ this.view = emptyQuota(this.view.accountEpoch + 1, this.view.nextRefreshAtMs);
48
+ this.view.state = state;
49
+ this.identity = undefined;
50
+ this.accountKey = undefined;
51
+ this.controller?.abort();
52
+ }
53
+ /** 插件卸载中止读取;共享等待者仍由同一回收路径完成。 */
54
+ dispose() {
55
+ this.disposed = true;
56
+ this.invalidate();
57
+ }
58
+ /** 自动读取与 force 均共享同一冷却;force 只表达刷新意图。 */
59
+ read() {
60
+ if (this.inFlight !== undefined)
61
+ return this.inFlight.then(() => this.snapshot());
62
+ if (this.disposed || this.now() < this.view.nextRefreshAtMs)
63
+ return Promise.resolve(this.snapshot());
64
+ this.view.nextRefreshAtMs = this.now() + QUOTA_MIN_INTERVAL_MS;
65
+ const epoch = this.view.accountEpoch;
66
+ const controller = new AbortController();
67
+ this.controller = controller;
68
+ const signal = AbortSignal.any([
69
+ controller.signal,
70
+ AbortSignal.timeout(this.config.probeTimeoutMs),
71
+ ]);
72
+ this.inFlight = this.load(epoch, signal).finally(() => {
73
+ this.inFlight = undefined;
74
+ this.controller = undefined;
75
+ });
76
+ return this.inFlight.then(() => this.snapshot());
77
+ }
78
+ async load(epoch, signal) {
79
+ let connection;
80
+ let activeEpoch = epoch;
81
+ let readingAccount = true;
82
+ try {
83
+ connection = await this.connect(signal);
84
+ connection.onNotification((method) => {
85
+ // CLI 在 account/read 回执前公布初始元数据;该阶段用回执核对账号身份。
86
+ if (method === "account/updated" && !readingAccount)
87
+ this.invalidate();
88
+ });
89
+ const { account } = QuotaAccountResult.parse(await connection.request(Method.accountRead, { refreshToken: false }, signal));
90
+ readingAccount = false;
91
+ if (activeEpoch !== this.view.accountEpoch || signal.aborted)
92
+ return this.snapshot();
93
+ const identity = JSON.stringify(account);
94
+ if (this.identity !== undefined && this.identity !== identity) {
95
+ this.view = emptyQuota(this.view.accountEpoch + 1, this.view.nextRefreshAtMs);
96
+ }
97
+ this.identity = identity;
98
+ activeEpoch = this.view.accountEpoch;
99
+ if (account === null || account.type !== "chatgpt") {
100
+ this.view = {
101
+ ...emptyQuota(this.view.accountEpoch, this.view.nextRefreshAtMs),
102
+ state: account === null ? "signed-out" : "unsupported",
103
+ };
104
+ return this.snapshot();
105
+ }
106
+ const raw = NativeQuotaResult.parse(await connection.request(Method.accountRateLimitsRead, { excludeResetCreditDetails: false }, signal));
107
+ if (activeEpoch !== this.view.accountEpoch || signal.aborted)
108
+ return this.snapshot();
109
+ if (raw.accountId != null &&
110
+ this.accountKey !== undefined &&
111
+ this.accountKey !== raw.accountId) {
112
+ this.view = emptyQuota(this.view.accountEpoch + 1, this.view.nextRefreshAtMs);
113
+ }
114
+ this.accountKey = raw.accountId ?? identity;
115
+ this.project(raw);
116
+ }
117
+ catch (error) {
118
+ if (activeEpoch === this.view.accountEpoch &&
119
+ !this.controller?.signal.aborted) {
120
+ const unsupported = fieldOf(error, "code") === -32601 ||
121
+ (error instanceof Error &&
122
+ /method not found|unsupported|-32601/iu.test(error.message));
123
+ this.view = {
124
+ ...this.view,
125
+ state: unsupported ? "unsupported" : "error",
126
+ errors: [
127
+ failure("account", unsupported ? "unsupported" : "read-failed"),
128
+ ],
129
+ };
130
+ }
131
+ }
132
+ finally {
133
+ if (connection !== undefined)
134
+ await connection
135
+ .stop(this.config.cleanupTimeoutMs)
136
+ .catch(() => undefined);
137
+ }
138
+ return this.snapshot();
139
+ }
140
+ project(raw) {
141
+ const at = this.now();
142
+ const errors = [];
143
+ const groups = [];
144
+ const entries = raw.rateLimitsByLimitId === null ||
145
+ raw.rateLimitsByLimitId === undefined ||
146
+ Object.keys(raw.rateLimitsByLimitId).length === 0
147
+ ? [["codex", raw.rateLimits]]
148
+ : Object.entries(raw.rateLimitsByLimitId);
149
+ for (const [key, value] of entries) {
150
+ const parsed = NativeQuotaSnapshot.safeParse(value);
151
+ if (!parsed.success) {
152
+ errors.push(failure("windows"));
153
+ continue;
154
+ }
155
+ const group = parsed.data;
156
+ const windows = [];
157
+ for (const value of [group.primary, group.secondary]) {
158
+ if (value == null)
159
+ continue;
160
+ const window = NativeQuotaWindow.safeParse(value);
161
+ if (!window.success) {
162
+ errors.push(failure("windows"));
163
+ continue;
164
+ }
165
+ windows.push({
166
+ usedPercent: window.data.usedPercent,
167
+ remainingPercent: 100 - window.data.usedPercent,
168
+ windowMinutes: window.data.windowDurationMins,
169
+ resetsAtMs: window.data.resetsAt === null ? null : window.data.resetsAt * 1000,
170
+ });
171
+ }
172
+ windows.sort((a, b) => (a.windowMinutes ?? Infinity) - (b.windowMinutes ?? Infinity));
173
+ groups.push({
174
+ id: group.limitId ?? String(key),
175
+ name: group.limitName ?? null,
176
+ windows,
177
+ });
178
+ }
179
+ const main = NativeQuotaSnapshot.safeParse(raw.rateLimits);
180
+ const credits = NativeCredits.nullish().safeParse(main.success ? main.data.credits : {});
181
+ const spend = NativeSpendLimit.nullish().safeParse(main.success ? main.data.individualLimit : {});
182
+ const resets = NativeResetCredits.nullish().safeParse(raw.rateLimitResetCredits);
183
+ if (!credits.success)
184
+ errors.push(failure("credits"));
185
+ if (!spend.success)
186
+ errors.push(failure("spend"));
187
+ if (!resets.success)
188
+ errors.push(failure("resets"));
189
+ this.view = QuotaView.parse({
190
+ ...this.view,
191
+ state: "ready",
192
+ errors,
193
+ ...(groups.some((group) => group.windows.length > 0) ||
194
+ !errors.some((e) => e.area === "windows")
195
+ ? { groups, fetchedAtMs: at }
196
+ : {}),
197
+ ...(credits.success
198
+ ? { credits: credits.data ?? null, creditsAtMs: at }
199
+ : {}),
200
+ ...(spend.success
201
+ ? {
202
+ spend: spend.data == null
203
+ ? null
204
+ : { ...spend.data, resetsAtMs: spend.data.resetsAt * 1000 },
205
+ spendAtMs: at,
206
+ }
207
+ : {}),
208
+ ...(resets.success
209
+ ? {
210
+ resets: resets.data == null
211
+ ? null
212
+ : {
213
+ availableCount: resets.data.availableCount,
214
+ cards: resets.data.credits?.map((c) => ({
215
+ id: c.id,
216
+ title: c.title,
217
+ description: c.description,
218
+ status: c.status,
219
+ expiresAtMs: c.expiresAt === null ? null : c.expiresAt * 1000,
220
+ })) ?? null,
221
+ },
222
+ resetsAtMs: at,
223
+ }
224
+ : {}),
225
+ });
226
+ }
227
+ }
@@ -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
+ }