@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,60 @@
1
+ /** CLI 工具选择的数据形状:Config 字段 toolSelection、目录行、来源与目标身份及开关判定。 */
2
+ import Schema from "@deepseek-ai/schemastery";
3
+ import { brandString } from "@deepseek-ai/dsh-brand";
4
+ /** 把来源字符串标记为来源身份。 */
5
+ export function ToolSourceId(value) {
6
+ return brandString(value);
7
+ }
8
+ /** 把条目 id 标记为目标身份。 */
9
+ export function CliTargetId(value) {
10
+ return brandString(value);
11
+ }
12
+ const entryFields = {
13
+ source: Schema.string().min(1).required(),
14
+ name: Schema.string().min(1).required(),
15
+ enabled: Schema.boolean().required(),
16
+ };
17
+ const entry = Schema.object(entryFields);
18
+ const selectionFields = {
19
+ version: Schema.const(1).required(),
20
+ harness: Schema.array(entry).required(),
21
+ native: Schema.array(entry).required(),
22
+ };
23
+ const selection = Schema.object(selectionFields);
24
+ /**
25
+ * 带版本的 Config 值;同侧重复身份在配置提交前失败。
26
+ * transform 回调收到的是 inner 校验后的输出,输入输出因此都按已校验形状声明。
27
+ */
28
+ export const ToolSelectionSchema = Schema.transform(selection, (value) => {
29
+ const parsed = selection(value);
30
+ for (const side of ["harness", "native"]) {
31
+ const identities = new Set();
32
+ for (const row of parsed[side]) {
33
+ const key = JSON.stringify([row.source, row.name]);
34
+ if (identities.has(key))
35
+ throw new Error(`Duplicate ${side} tool ${row.source}/${row.name}`);
36
+ identities.add(key);
37
+ }
38
+ }
39
+ return parsed;
40
+ });
41
+ /**
42
+ * 判定一行是否开启:固定行取其实际状态;其余按保存的身份查找。
43
+ * Harness 侧的公开注册表不暴露插件来源,身份未命中时按名称回退,
44
+ * 以兼容带旧来源 id 的已保存配置;名称也未出现时默认开启——导入只能
45
+ * 看到当时可见的工具,缺行不能关掉既有 KMH 工具。原生行缺省关闭。
46
+ * @param value 已接受的 toolSelection。
47
+ * @param row 实际目录行。
48
+ * @returns 保存的选择、固定行的实际状态或该侧的缺省值。
49
+ */
50
+ export function choiceEnabled(value, row) {
51
+ if (row.control.kind === "fixed")
52
+ return row.control.enabled;
53
+ const rows = value[row.side];
54
+ const exact = rows.find((item) => item.source === row.source && item.name === row.name);
55
+ if (exact !== undefined)
56
+ return exact.enabled;
57
+ if (row.side !== "harness")
58
+ return false;
59
+ return rows.find((item) => item.name === row.name)?.enabled ?? true;
60
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * 工具开关清单的拼装与切换行映射:本插件自报"我的开关",详情页选择器只消费。
3
+ * listToolSwitches 读目录与配置拼清单;applyToolSwitch 把一次切换映射为
4
+ * toolSelection 的行并经公开 settings 服务带修订号写入,失败原样抛出。
5
+ */
6
+ import type { Context } from "@deepseek-ai/cordis";
7
+ import type { CodexCli } from "./index.ts";
8
+ import { type ToolSwitchList, type ToolSwitchUpdate } from "./tool-switches.ts";
9
+ /**
10
+ * 读取当前开关清单。
11
+ * @param runtime 插件运行时。
12
+ * @param ctx 插件上下文(取 settings 修订号)。
13
+ * @param signal 取消信号。
14
+ * @param refresh 是否清除原生目录缓存重新发现(详情页"重新读取")。
15
+ * @returns 经契约校验的清单;原生诊断进入 nativeStatus 而不抛错。
16
+ * @throws CODEX_TOOL_SELECTION_UNINITIALIZED 首次导入失败、配置仍为空。
17
+ */
18
+ export declare function listToolSwitches(runtime: CodexCli, ctx: Context, signal: AbortSignal, refresh: boolean): Promise<ToolSwitchList>;
19
+ /**
20
+ * 应用一次切换:映射为 toolSelection 的行并写入 profile 配置,返回新清单。
21
+ * @throws CLI_TOOL_SWITCH_UNKNOWN 身份不在当前清单内。
22
+ * @throws SettingsConflictError 修订号与当前不符(由 settings 服务抛出)。
23
+ */
24
+ export declare function applyToolSwitch(runtime: CodexCli, ctx: Context, update: ToolSwitchUpdate, signal: AbortSignal): Promise<ToolSwitchList>;
@@ -0,0 +1,129 @@
1
+ import { choiceEnabled, } from "./tool-selection.js";
2
+ import { NativeSwitchId, ToolSwitchListSchema, } from "./tool-switches.js";
3
+ const NATIVE_SOURCE = "codex/native";
4
+ const KMH_ID_PREFIX = "kmh:";
5
+ /** 原生能力覆盖的 Codex 工具名;命令执行三者共用一个 -c 覆盖,必须一起写。 */
6
+ const NATIVE_COVERS = {
7
+ "native:command-execution": ["exec_command", "write_stdin", "shell_command"],
8
+ "native:file-change": ["apply_patch"],
9
+ "native:view-image": ["view_image"],
10
+ "native:web-search": ["web_search"],
11
+ };
12
+ function requirePolicy(runtime) {
13
+ if (runtime.toolPolicy === undefined)
14
+ throw new Error("CODEX_TOOL_POLICY_UNAVAILABLE");
15
+ return runtime.toolPolicy;
16
+ }
17
+ function revisionOf(ctx, targetId) {
18
+ const settings = ctx.get("settings");
19
+ if (settings === undefined)
20
+ throw new Error("CODEX_TOOL_SWITCHES_NEED_PROFILE_SETTINGS");
21
+ const descriptor = settings
22
+ .describe()
23
+ .find((row) => String(row.ns) === targetId);
24
+ if (descriptor === undefined)
25
+ throw new Error("CODEX_TOOL_SWITCHES_NEED_WRITABLE_PROFILE");
26
+ return descriptor.revision;
27
+ }
28
+ /** 原生能力的当前值:取其首个覆盖行;web_search 行尚不存在时回落旧设置。 */
29
+ function nativeEnabled(runtime, choices, id) {
30
+ const name = NATIVE_COVERS[id][0];
31
+ const row = choices.native.find((item) => item.source === NATIVE_SOURCE && item.name === name);
32
+ if (row !== undefined)
33
+ return row.enabled;
34
+ return id === "native:web-search"
35
+ ? runtime.settings.selection.webSearch
36
+ : false;
37
+ }
38
+ function compare(a, b) {
39
+ return a < b ? -1 : a > b ? 1 : 0;
40
+ }
41
+ function assemble(runtime, ctx, targetId, catalog, choices) {
42
+ const kmh = catalog.tools
43
+ .filter((row) => row.side === "harness")
44
+ .sort((a, b) => compare(a.name, b.name))
45
+ .map((row) => ({
46
+ id: KMH_ID_PREFIX + row.name,
47
+ name: row.name,
48
+ description: row.description,
49
+ enabled: choiceEnabled(choices, row),
50
+ covers: [],
51
+ }));
52
+ const native = NativeSwitchId.options.map((id) => ({
53
+ id,
54
+ name: id.slice("native:".length),
55
+ description: catalog.tools.find((row) => row.side === "native" && row.name === NATIVE_COVERS[id][0])?.description ?? "",
56
+ enabled: nativeEnabled(runtime, choices, id),
57
+ covers: [...NATIVE_COVERS[id]],
58
+ }));
59
+ return ToolSwitchListSchema.parse({
60
+ target: "codex-cli",
61
+ revision: revisionOf(ctx, targetId),
62
+ kmh,
63
+ native,
64
+ nativeStatus: catalog.diagnostics?.native === undefined
65
+ ? { ok: true }
66
+ : { ok: false, reason: catalog.diagnostics.native },
67
+ });
68
+ }
69
+ /**
70
+ * 读取当前开关清单。
71
+ * @param runtime 插件运行时。
72
+ * @param ctx 插件上下文(取 settings 修订号)。
73
+ * @param signal 取消信号。
74
+ * @param refresh 是否清除原生目录缓存重新发现(详情页"重新读取")。
75
+ * @returns 经契约校验的清单;原生诊断进入 nativeStatus 而不抛错。
76
+ * @throws CODEX_TOOL_SELECTION_UNINITIALIZED 首次导入失败、配置仍为空。
77
+ */
78
+ export async function listToolSwitches(runtime, ctx, signal, refresh) {
79
+ const policy = requirePolicy(runtime);
80
+ const catalog = await policy.catalog(signal, refresh);
81
+ const choices = runtime.config.toolSelection.get();
82
+ if (choices === undefined)
83
+ throw new Error(`CODEX_TOOL_SELECTION_UNINITIALIZED${catalog.diagnostics?.harness === undefined ? "" : `: ${catalog.diagnostics.harness}`}`);
84
+ return assemble(runtime, ctx, String(policy.targetId), catalog, choices);
85
+ }
86
+ function upsert(rows, source, name, enabled, matchSource) {
87
+ const row = rows.find((item) => item.name === name && (!matchSource || item.source === source));
88
+ if (row === undefined)
89
+ rows.push({ source, name, enabled });
90
+ else
91
+ row.enabled = enabled;
92
+ }
93
+ /**
94
+ * 应用一次切换:映射为 toolSelection 的行并写入 profile 配置,返回新清单。
95
+ * @throws CLI_TOOL_SWITCH_UNKNOWN 身份不在当前清单内。
96
+ * @throws SettingsConflictError 修订号与当前不符(由 settings 服务抛出)。
97
+ */
98
+ export async function applyToolSwitch(runtime, ctx, update, signal) {
99
+ const policy = requirePolicy(runtime);
100
+ const catalog = await policy.catalog(signal, false);
101
+ const current = runtime.config.toolSelection.get();
102
+ if (current === undefined)
103
+ throw new Error("CODEX_TOOL_SELECTION_UNINITIALIZED");
104
+ const next = {
105
+ version: 1,
106
+ harness: current.harness.map((row) => ({ ...row })),
107
+ native: current.native.map((row) => ({ ...row })),
108
+ };
109
+ if (update.id.startsWith(KMH_ID_PREFIX)) {
110
+ const name = update.id.slice(KMH_ID_PREFIX.length);
111
+ const known = catalog.tools.some((row) => row.side === "harness" && row.name === name);
112
+ if (!known)
113
+ throw new Error(`CLI_TOOL_SWITCH_UNKNOWN: ${update.id}`);
114
+ // KMH 行按名称匹配:旧配置可能带其他来源 id,保留原行只改状态。
115
+ upsert(next.harness, "harness", name, update.enabled, false);
116
+ }
117
+ else {
118
+ const parsed = NativeSwitchId.safeParse(update.id);
119
+ if (!parsed.success)
120
+ throw new Error(`CLI_TOOL_SWITCH_UNKNOWN: ${update.id}`);
121
+ for (const name of NATIVE_COVERS[parsed.data])
122
+ upsert(next.native, NATIVE_SOURCE, name, update.enabled, true);
123
+ }
124
+ const settings = ctx.get("settings");
125
+ if (settings === undefined)
126
+ throw new Error("CODEX_TOOL_SWITCHES_NEED_PROFILE_SETTINGS");
127
+ await settings.update(String(policy.targetId), { toolSelection: next }, update.revision);
128
+ return listToolSwitches(runtime, ctx, signal, false);
129
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * CLI 工具开关契约:详情页选择器与本插件之间共用的清单与切换载荷。
3
+ * 纯 zod 与推导类型,不依赖 node,可随客户端打包;类型只从 schema 推导。
4
+ */
5
+ import { z } from "zod";
6
+ /** 原生能力开关的固定身份;KMH 工具开关的 id 为 `kmh:<工具名>`。 */
7
+ export declare const NativeSwitchId: z.ZodEnum<{
8
+ "native:command-execution": "native:command-execution";
9
+ "native:file-change": "native:file-change";
10
+ "native:view-image": "native:view-image";
11
+ "native:web-search": "native:web-search";
12
+ }>;
13
+ export type NativeSwitchId = z.infer<typeof NativeSwitchId>;
14
+ /** 一个开关:KMH 工具一行,或原生能力一行。 */
15
+ export declare const ToolSwitchSchema: z.ZodObject<{
16
+ id: z.ZodString;
17
+ name: z.ZodString;
18
+ description: z.ZodString;
19
+ enabled: z.ZodBoolean;
20
+ covers: z.ZodArray<z.ZodString>;
21
+ }, z.core.$strip>;
22
+ export type ToolSwitch = z.infer<typeof ToolSwitchSchema>;
23
+ /** 原生目录核实状态:失败时携带原因,前端据此降级并提供重新读取。 */
24
+ export declare const NativeStatusSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
25
+ ok: z.ZodLiteral<true>;
26
+ }, z.core.$strip>, z.ZodObject<{
27
+ ok: z.ZodLiteral<false>;
28
+ reason: z.ZodString;
29
+ }, z.core.$strip>], "ok">;
30
+ export type NativeStatus = z.infer<typeof NativeStatusSchema>;
31
+ /** 详情页一次读取得到的完整清单。 */
32
+ export declare const ToolSwitchListSchema: z.ZodObject<{
33
+ target: z.ZodLiteral<"codex-cli">;
34
+ revision: z.ZodNumber;
35
+ kmh: z.ZodArray<z.ZodObject<{
36
+ id: z.ZodString;
37
+ name: z.ZodString;
38
+ description: z.ZodString;
39
+ enabled: z.ZodBoolean;
40
+ covers: z.ZodArray<z.ZodString>;
41
+ }, z.core.$strip>>;
42
+ native: z.ZodArray<z.ZodObject<{
43
+ id: z.ZodString;
44
+ name: z.ZodString;
45
+ description: z.ZodString;
46
+ enabled: z.ZodBoolean;
47
+ covers: z.ZodArray<z.ZodString>;
48
+ }, z.core.$strip>>;
49
+ nativeStatus: z.ZodDiscriminatedUnion<[z.ZodObject<{
50
+ ok: z.ZodLiteral<true>;
51
+ }, z.core.$strip>, z.ZodObject<{
52
+ ok: z.ZodLiteral<false>;
53
+ reason: z.ZodString;
54
+ }, z.core.$strip>], "ok">;
55
+ }, z.core.$strip>;
56
+ export type ToolSwitchList = z.infer<typeof ToolSwitchListSchema>;
57
+ /** 一次切换请求。 */
58
+ export declare const ToolSwitchUpdateSchema: z.ZodObject<{
59
+ id: z.ZodString;
60
+ enabled: z.ZodBoolean;
61
+ revision: z.ZodNumber;
62
+ }, z.core.$strip>;
63
+ export type ToolSwitchUpdate = z.infer<typeof ToolSwitchUpdateSchema>;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * CLI 工具开关契约:详情页选择器与本插件之间共用的清单与切换载荷。
3
+ * 纯 zod 与推导类型,不依赖 node,可随客户端打包;类型只从 schema 推导。
4
+ */
5
+ import { z } from "zod";
6
+ /** 原生能力开关的固定身份;KMH 工具开关的 id 为 `kmh:<工具名>`。 */
7
+ export const NativeSwitchId = z.enum([
8
+ "native:command-execution",
9
+ "native:file-change",
10
+ "native:view-image",
11
+ "native:web-search",
12
+ ]);
13
+ /** 一个开关:KMH 工具一行,或原生能力一行。 */
14
+ export const ToolSwitchSchema = z.object({
15
+ /** 切换时回传的身份:KMH 为 `kmh:<工具名>`,原生为 NativeSwitchId。 */
16
+ id: z.string().min(1),
17
+ /** 显示名:KMH 为工具名(含 kmh- 前缀);原生为能力键,客户端本地化。 */
18
+ name: z.string().min(1),
19
+ description: z.string(),
20
+ enabled: z.boolean(),
21
+ /** 原生能力覆盖的 Codex 工具名,仅作说明;KMH 为空数组。 */
22
+ covers: z.array(z.string()),
23
+ });
24
+ /** 原生目录核实状态:失败时携带原因,前端据此降级并提供重新读取。 */
25
+ export const NativeStatusSchema = z.discriminatedUnion("ok", [
26
+ z.object({ ok: z.literal(true) }),
27
+ z.object({ ok: z.literal(false), reason: z.string() }),
28
+ ]);
29
+ /** 详情页一次读取得到的完整清单。 */
30
+ export const ToolSwitchListSchema = z.object({
31
+ target: z.literal("codex-cli"),
32
+ /** settings 服务对 Codex 条目的当前修订号,切换时原样带回做并发核对。 */
33
+ revision: z.number().int(),
34
+ kmh: z.array(ToolSwitchSchema),
35
+ native: z.array(ToolSwitchSchema),
36
+ nativeStatus: NativeStatusSchema,
37
+ });
38
+ /** 一次切换请求。 */
39
+ export const ToolSwitchUpdateSchema = z.object({
40
+ id: z.string().min(1),
41
+ enabled: z.boolean(),
42
+ revision: z.number().int(),
43
+ });
@@ -0,0 +1,200 @@
1
+ /** 一个 KMH 回合内的 Codex turn:进程、thread、挂起工具与流式投影。 */
2
+ import type { Context } from "@deepseek-ai/cordis";
3
+ import { type StreamChunk } from "@deepseek-ai/dsh-llm";
4
+ import type { Config } from "./config.ts";
5
+ import type { NativeSelection } from "./capabilities.ts";
6
+ import type { SessionId } from "@deepseek-ai/dsh-session";
7
+ import { type CodexConnection } from "./connection.ts";
8
+ import { type PermissionKnobs } from "./isolation.ts";
9
+ import { type CursorSnapshot, type ToolResult, type TurnInputBlock } from "./cursor.ts";
10
+ import { type ToolRegistry } from "./tool-registry.ts";
11
+ /** turn 启动所需请求侧信息。 */
12
+ export interface TurnStartInput {
13
+ /** 完整冻结工具策略参与 thread 复用。 */
14
+ policyFingerprint?: string | undefined;
15
+ content: readonly TurnInputBlock[];
16
+ model: string;
17
+ reasoningEffort?: string | undefined;
18
+ baseInstructions?: string | undefined;
19
+ developerInstructions?: string | undefined;
20
+ tools: {
21
+ name: string;
22
+ description: string;
23
+ inputSchema: unknown;
24
+ }[];
25
+ /** 逐项选择覆盖;缺省用部署配置迁移。 */
26
+ selection?: NativeSelection | undefined;
27
+ /** 会话标识:审批桥据此取活跃 Agent(feat09)。 */
28
+ sessionId?: SessionId | undefined;
29
+ /** 会话生效权限档(D17);选中执行类原生工具时映射为 -c 沙箱/审批参数。 */
30
+ permission?: PermissionKnobs | undefined;
31
+ }
32
+ /**
33
+ * 管理一个 KMH 回合内的 CLI 进程与 Codex turn。
34
+ * 工具请求到达时挂起 Codex(延迟回执),由 adapter 在下一次 stream 调用回传结果续推;
35
+ * turn 终止后连接与进程回收。
36
+ */
37
+ export declare class CodexTurn {
38
+ private readonly ctx;
39
+ private readonly config;
40
+ private readonly cwd;
41
+ /** 调用方在隔离覆盖之上追加的进程配置(测试 fixture 等)。 */
42
+ private readonly extraOverrides;
43
+ /** 官方重试通知及恢复输出时的连接状态。 */
44
+ private readonly onConnectionState?;
45
+ private connection;
46
+ private queue;
47
+ private wakeup;
48
+ private closed;
49
+ private itemIndex;
50
+ private nextIndex;
51
+ private readonly pending;
52
+ /** 已投影为会话图片块的生图项 id:防重复投影。 */
53
+ private readonly projectedImages;
54
+ /** 文本/推理块的类型与 delta 累积(摘要补算用),按流块索引。 */
55
+ private readonly blockTypes;
56
+ private readonly blockText;
57
+ private readonly endedBlocks;
58
+ /** 已开块索引;同一 item 的后续 delta 沿用现有块及累积文本。 */
59
+ private readonly openBlocks;
60
+ threadId: string | undefined;
61
+ turnId: string | undefined;
62
+ /** 最近一次完成(含 interrupted)的 turn id;fork 重建的边界。 */
63
+ lastCompletedTurnId: string | undefined;
64
+ /** 差分游标:已投递到 Codex thread 的对齐点。 */
65
+ cursor: CursorSnapshot;
66
+ /**
67
+ * 待核对回合块摘要队列:本 turn 投影的块入队(block-end 时),差分
68
+ * 消费历史中的 assistant 消息时出队。adapter 在每次差分后把它对账为
69
+ * 游标返回的剩余队列,再随快照持久化(见 cursor.ts 注释)。
70
+ */
71
+ pendingDigests: string[];
72
+ /** 回合终止状态;completed 或 interrupted 后进程可回收。 */
73
+ terminalStatus: string | undefined;
74
+ /** 最近一次投递的用户输入文本:生图尺寸要求识别来源(feat10)。 */
75
+ private lastUserText;
76
+ /** 会话标识:审批桥取活跃 Agent 用。 */
77
+ private sessionId;
78
+ /** 回合级审批中止:dispose/interrupt 时待审批决定随回合取消(feat06 场景1)。 */
79
+ private approvalAbort;
80
+ /** 原生叙述账目(feat08 v1):按 item 的体积与收尾状态;reopen 重置。 */
81
+ private readonly nativeNotes;
82
+ /** turn 级 diff 叙述账目。 */
83
+ private diffBudget;
84
+ /**
85
+ * 本回合的工具声明表(D13):声明名 kmh-<原名> 与目录指纹。
86
+ * start/rebuild 时建立;临时会话(adopt)保持 undefined,仅兼容裸名。
87
+ */
88
+ toolRegistry: ToolRegistry | undefined;
89
+ /**
90
+ * 未上报的逐响应用量样本队列(token 用量):Codex 每次上游响应完成发
91
+ * 一条 thread/tokenUsage/updated(last=该响应用量),turn/completed 不带
92
+ * 用量;KMH 要求每个 step 的 assistant 消息都有样本(缺一则整轮不显示),
93
+ * 且首个样本常在本侧 yield 工具挂起之后才到达——队列 + finish 时消费
94
+ * (空则补零样本)使各样本之和恒等于回合总量,与到达时序解耦。
95
+ */
96
+ private readonly usageQueue;
97
+ constructor(ctx: Context, config: Config, cwd: string,
98
+ /** 调用方在隔离覆盖之上追加的进程配置(测试 fixture 等)。 */
99
+ extraOverrides?: readonly string[],
100
+ /** 官方重试通知及恢复输出时的连接状态。 */
101
+ onConnectionState?: ((retrying: boolean, detail: string) => void) | undefined);
102
+ /**
103
+ * 重启已回收的 turn 对象:复位关闭与终止标志并清空残留事件。
104
+ * start/rebuild 会复用本对象重新拉起进程;此前若经 dispose 回收,
105
+ * closed 标志会让 push 静默丢弃全部事件(恢复路径实测挂死于此)。
106
+ */
107
+ private reopen;
108
+ /** 等待结果回传的挂起工具调用标识。 */
109
+ pendingCallIds(): string[];
110
+ /**
111
+ * 消费一条未上报用量样本;队列空时补零样本(该步样本尚未到达或本轮
112
+ * 无上游响应)。晚到样本留给下一步,各步样本之和仍等于回合总量。
113
+ */
114
+ private consumeUsageSample;
115
+ /**
116
+ * 回合终局消费:合并队列全部剩余样本为一个(KMH 消费端只认最后一条
117
+ * usage chunk,逐条发会被覆盖;样本不相交,逐字段求和保持口径一致)。
118
+ * 队列空时补零样本,保证终局步也有样本。
119
+ */
120
+ private consumeUsageTotal;
121
+ /** 是否已经终止(进程应回收)。 */
122
+ get terminated(): boolean;
123
+ /**
124
+ * 启动进程与 turn:隔离准备、连接、thread 创建或恢复、turn/start。
125
+ * @param input - 用户输入、模型与工具目录。
126
+ * @param threadId - 已有绑定的 thread;缺省时创建新 thread。
127
+ * @param signal - 取消信号。
128
+ * @param onBound - 收到编号后、发送任务前等待的保存操作;失败时停止发送。
129
+ * @returns 新建或恢复后的 threadId。
130
+ */
131
+ start(input: TurnStartInput, threadId: string | undefined, signal: AbortSignal, onBound?: (id: string) => Promise<void>): Promise<string>;
132
+ /**
133
+ * 原生分叉继承已选位置的历史,仅提交新增输入;失败保留源会话。
134
+ * @param input - 新增或编辑后的输入、源会话工具与本次模型和权限选择。
135
+ * @param source - 原生父会话及完成回合前后的位置。
136
+ * @param signal - 取消信号。
137
+ * @param onBound - 新编号保存操作;发送输入前等待完成。
138
+ * @returns 原生分叉创建的会话编号。
139
+ */
140
+ rebuild(input: TurnStartInput, source: {
141
+ threadId: string;
142
+ lastTurnId?: string;
143
+ beforeTurnId?: string;
144
+ }, signal: AbortSignal, onBound?: (id: string) => Promise<void>): Promise<string>;
145
+ /** 读取附件服务校验过的图片字节,转换为 Codex 接受的输入。 */
146
+ private encodeInput;
147
+ /** 移交外部建立的连接(临时会话路径);此后由本对象负责回收。 */
148
+ adopt(connection: CodexConnection): void;
149
+ /** 设置 thread 与 turn 标识(临时会话路径)。 */
150
+ setIds(threadId: string, turnId: string): void;
151
+ /** 安装通知与服务端请求处理。 */
152
+ private installHandlers;
153
+ /** 通知投影。 */
154
+ private handleNotification;
155
+ /**
156
+ * 把 Codex 原生生图结果投影为会话图片块:读取落盘产物、经宿主附件服务
157
+ * 落成 ImageAttachmentRef 后以 image 块送回 KMH 展示,并随图报告实际
158
+ * 像素尺寸(feat10)。投影失败不打断生成(跳过并告警):投影是展示
159
+ * 增强,生成与续推链路不依赖它;失败时改为推送双态报告文本块。
160
+ * @param item - item/completed 携带的 ThreadItem::ImageGeneration。
161
+ */
162
+ private projectImage;
163
+ /** 推送一个自成一体的文本块(尺寸/失败等投影附注)。 */
164
+ private pushNote;
165
+ /** 开启一条原生叙述块(item/started)。 */
166
+ private openNativeNote;
167
+ /** 向原生叙述块追加增量(输出/进度/diff 摘要),超限截断、收尾后拒收。 */
168
+ private appendNativeNote;
169
+ /** 收尾原生叙述块(item/completed):补完成状态并块结束(一次性)。 */
170
+ private closeNativeNote;
171
+ /** 回合终局:仍未收尾的原生叙述补记待确认并闭合(场景5/6)。 */
172
+ private closeUnsettledNativeNotes;
173
+ /** 为流块分配序号;同一 itemId 复用。 */
174
+ private allocate;
175
+ private push;
176
+ /** turn 终局补算未闭合文本/推理块的摘要(内容取 delta 累积)。 */
177
+ private digestOpenBlocks;
178
+ private wait;
179
+ /**
180
+ * 消费投影流直到工具挂起或 turn 终止。
181
+ * @param signal - 取消或超时信号;等待期间中止会立即抛出 signal.reason。
182
+ */
183
+ pump(signal: AbortSignal): AsyncGenerator<StreamChunk>;
184
+ /**
185
+ * 回传一组工具结果并继续消费投影流。
186
+ * @param results - 与挂起工具逐一匹配的结果集合。
187
+ * @param signal - 取消或超时信号。
188
+ * @param followup - 先交给活跃回合的追加输入及接纳后保存游标的回调。
189
+ */
190
+ resumeWithToolResults(results: ToolResult[], signal: AbortSignal, followup?: {
191
+ content: TurnInputBlock[];
192
+ onAccepted: () => Promise<void>;
193
+ }): AsyncGenerator<StreamChunk>;
194
+ /** 中断当前 turn 并等待终止通知,随后回收进程。 */
195
+ interrupt(signal: AbortSignal): Promise<void>;
196
+ /** 拒绝全部挂起工具请求。 */
197
+ private failPending;
198
+ /** 回收连接与进程;幂等。 */
199
+ dispose(): Promise<void>;
200
+ }