kimi-plugin-cc 2.0.7

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 (190) hide show
  1. package/.agents/plugins/marketplace.json +20 -0
  2. package/.claude-plugin/marketplace.json +16 -0
  3. package/.claude-plugin/plugin.json +32 -0
  4. package/CHANGELOG.md +1096 -0
  5. package/LICENSE +201 -0
  6. package/README.md +772 -0
  7. package/agents/kimi-ask.md +82 -0
  8. package/agents/kimi-challenge.md +82 -0
  9. package/agents/kimi-pursue.md +91 -0
  10. package/agents/kimi-rescue.md +85 -0
  11. package/agents/kimi-review.md +82 -0
  12. package/agents/kimi-swarm-write.md +92 -0
  13. package/agents/kimi-swarm.md +83 -0
  14. package/commands/README.md +16 -0
  15. package/commands/ask.md +32 -0
  16. package/commands/cancel.md +17 -0
  17. package/commands/challenge.md +29 -0
  18. package/commands/pursue.md +37 -0
  19. package/commands/replay.md +13 -0
  20. package/commands/rescue.md +32 -0
  21. package/commands/result.md +13 -0
  22. package/commands/review.md +29 -0
  23. package/commands/setup.md +23 -0
  24. package/commands/status.md +13 -0
  25. package/commands/swarm.md +38 -0
  26. package/dist/background-spawn.js +224 -0
  27. package/dist/cli-cancellation.js +43 -0
  28. package/dist/cli-client.js +845 -0
  29. package/dist/commands/ask.js +327 -0
  30. package/dist/commands/cancel.js +178 -0
  31. package/dist/commands/cli-helpers.js +112 -0
  32. package/dist/commands/models.js +140 -0
  33. package/dist/commands/not-implemented.js +4 -0
  34. package/dist/commands/pursue.js +311 -0
  35. package/dist/commands/registry.js +87 -0
  36. package/dist/commands/repair-sessions.js +159 -0
  37. package/dist/commands/replay.js +123 -0
  38. package/dist/commands/rescue.js +333 -0
  39. package/dist/commands/result.js +58 -0
  40. package/dist/commands/review-gate.js +393 -0
  41. package/dist/commands/review.js +218 -0
  42. package/dist/commands/setup.js +1132 -0
  43. package/dist/commands/status.js +27 -0
  44. package/dist/commands/swarm.js +576 -0
  45. package/dist/commands/worker.js +31 -0
  46. package/dist/companion.js +114 -0
  47. package/dist/config.js +22 -0
  48. package/dist/errors.js +40 -0
  49. package/dist/git.js +215 -0
  50. package/dist/hooks/approval-hook.js +112 -0
  51. package/dist/hooks/approval-policy.js +254 -0
  52. package/dist/hooks/config-safety.js +637 -0
  53. package/dist/hooks/install-paths.js +504 -0
  54. package/dist/hooks/install.js +281 -0
  55. package/dist/hooks/managed-block.js +745 -0
  56. package/dist/hooks/review-gate-stop.js +19 -0
  57. package/dist/job-store.js +559 -0
  58. package/dist/jobs.js +202 -0
  59. package/dist/kimi-command.js +72 -0
  60. package/dist/kimi-engine.js +624 -0
  61. package/dist/kimi-errors.js +220 -0
  62. package/dist/kimi-home.js +9 -0
  63. package/dist/kimi-timeouts.js +68 -0
  64. package/dist/kimi-version-probe.js +1410 -0
  65. package/dist/logging.js +22 -0
  66. package/dist/native-v2-preflight.js +417 -0
  67. package/dist/package.json +1 -0
  68. package/dist/parsing.js +553 -0
  69. package/dist/paths.js +27 -0
  70. package/dist/plugin-data.js +98 -0
  71. package/dist/process-tree.js +448 -0
  72. package/dist/render.js +159 -0
  73. package/dist/rescue-approval.js +951 -0
  74. package/dist/schemas/review-gate-output.js +43 -0
  75. package/dist/session-title.js +293 -0
  76. package/dist/stream-json.js +498 -0
  77. package/dist/types.js +1 -0
  78. package/dist/vendor/shell-quote/LICENSE +24 -0
  79. package/dist/vendor/shell-quote/index.js +1 -0
  80. package/dist/vendor/shell-quote/parse.js +229 -0
  81. package/dist/vendor/smol-toml/LICENSE +24 -0
  82. package/dist/vendor/smol-toml/date.js +127 -0
  83. package/dist/vendor/smol-toml/error.js +63 -0
  84. package/dist/vendor/smol-toml/extract.js +100 -0
  85. package/dist/vendor/smol-toml/parse.js +148 -0
  86. package/dist/vendor/smol-toml/primitive.js +179 -0
  87. package/dist/vendor/smol-toml/struct.js +184 -0
  88. package/dist/vendor/smol-toml/util.js +113 -0
  89. package/dist/version.js +7 -0
  90. package/docs/migration.md +215 -0
  91. package/docs/models.md +82 -0
  92. package/docs/registry-releases.md +70 -0
  93. package/docs/safety.md +318 -0
  94. package/docs/session-visibility.md +32 -0
  95. package/hooks/README.md +9 -0
  96. package/hooks/hooks.json +16 -0
  97. package/package.json +67 -0
  98. package/plugins/kimi-codex/.codex-plugin/plugin.json +39 -0
  99. package/plugins/kimi-codex/dist/background-spawn.js +224 -0
  100. package/plugins/kimi-codex/dist/cli-cancellation.js +43 -0
  101. package/plugins/kimi-codex/dist/cli-client.js +845 -0
  102. package/plugins/kimi-codex/dist/commands/ask.js +327 -0
  103. package/plugins/kimi-codex/dist/commands/cancel.js +178 -0
  104. package/plugins/kimi-codex/dist/commands/cli-helpers.js +112 -0
  105. package/plugins/kimi-codex/dist/commands/models.js +140 -0
  106. package/plugins/kimi-codex/dist/commands/not-implemented.js +4 -0
  107. package/plugins/kimi-codex/dist/commands/pursue.js +311 -0
  108. package/plugins/kimi-codex/dist/commands/registry.js +87 -0
  109. package/plugins/kimi-codex/dist/commands/repair-sessions.js +159 -0
  110. package/plugins/kimi-codex/dist/commands/replay.js +123 -0
  111. package/plugins/kimi-codex/dist/commands/rescue.js +333 -0
  112. package/plugins/kimi-codex/dist/commands/result.js +58 -0
  113. package/plugins/kimi-codex/dist/commands/review-gate.js +393 -0
  114. package/plugins/kimi-codex/dist/commands/review.js +218 -0
  115. package/plugins/kimi-codex/dist/commands/setup.js +1132 -0
  116. package/plugins/kimi-codex/dist/commands/status.js +27 -0
  117. package/plugins/kimi-codex/dist/commands/swarm.js +576 -0
  118. package/plugins/kimi-codex/dist/commands/worker.js +31 -0
  119. package/plugins/kimi-codex/dist/companion.js +114 -0
  120. package/plugins/kimi-codex/dist/config.js +22 -0
  121. package/plugins/kimi-codex/dist/errors.js +40 -0
  122. package/plugins/kimi-codex/dist/git.js +215 -0
  123. package/plugins/kimi-codex/dist/hooks/approval-hook.js +112 -0
  124. package/plugins/kimi-codex/dist/hooks/approval-policy.js +254 -0
  125. package/plugins/kimi-codex/dist/hooks/config-safety.js +637 -0
  126. package/plugins/kimi-codex/dist/hooks/install-paths.js +504 -0
  127. package/plugins/kimi-codex/dist/hooks/install.js +281 -0
  128. package/plugins/kimi-codex/dist/hooks/managed-block.js +745 -0
  129. package/plugins/kimi-codex/dist/hooks/review-gate-stop.js +19 -0
  130. package/plugins/kimi-codex/dist/job-store.js +559 -0
  131. package/plugins/kimi-codex/dist/jobs.js +202 -0
  132. package/plugins/kimi-codex/dist/kimi-command.js +72 -0
  133. package/plugins/kimi-codex/dist/kimi-engine.js +624 -0
  134. package/plugins/kimi-codex/dist/kimi-errors.js +220 -0
  135. package/plugins/kimi-codex/dist/kimi-home.js +9 -0
  136. package/plugins/kimi-codex/dist/kimi-timeouts.js +68 -0
  137. package/plugins/kimi-codex/dist/kimi-version-probe.js +1410 -0
  138. package/plugins/kimi-codex/dist/logging.js +22 -0
  139. package/plugins/kimi-codex/dist/native-v2-preflight.js +417 -0
  140. package/plugins/kimi-codex/dist/package.json +1 -0
  141. package/plugins/kimi-codex/dist/parsing.js +553 -0
  142. package/plugins/kimi-codex/dist/paths.js +27 -0
  143. package/plugins/kimi-codex/dist/plugin-data.js +98 -0
  144. package/plugins/kimi-codex/dist/process-tree.js +448 -0
  145. package/plugins/kimi-codex/dist/render.js +159 -0
  146. package/plugins/kimi-codex/dist/rescue-approval.js +951 -0
  147. package/plugins/kimi-codex/dist/schemas/review-gate-output.js +43 -0
  148. package/plugins/kimi-codex/dist/session-title.js +293 -0
  149. package/plugins/kimi-codex/dist/stream-json.js +498 -0
  150. package/plugins/kimi-codex/dist/types.js +1 -0
  151. package/plugins/kimi-codex/dist/vendor/shell-quote/LICENSE +24 -0
  152. package/plugins/kimi-codex/dist/vendor/shell-quote/index.js +1 -0
  153. package/plugins/kimi-codex/dist/vendor/shell-quote/parse.js +229 -0
  154. package/plugins/kimi-codex/dist/vendor/smol-toml/LICENSE +24 -0
  155. package/plugins/kimi-codex/dist/vendor/smol-toml/date.js +127 -0
  156. package/plugins/kimi-codex/dist/vendor/smol-toml/error.js +63 -0
  157. package/plugins/kimi-codex/dist/vendor/smol-toml/extract.js +100 -0
  158. package/plugins/kimi-codex/dist/vendor/smol-toml/parse.js +148 -0
  159. package/plugins/kimi-codex/dist/vendor/smol-toml/primitive.js +179 -0
  160. package/plugins/kimi-codex/dist/vendor/smol-toml/struct.js +184 -0
  161. package/plugins/kimi-codex/dist/vendor/smol-toml/util.js +113 -0
  162. package/plugins/kimi-codex/dist/version.js +7 -0
  163. package/plugins/kimi-codex/scripts/companion.sh +37 -0
  164. package/plugins/kimi-codex/scripts/review-gate-hook.sh +32 -0
  165. package/plugins/kimi-codex/skills/kimi-ask/SKILL.md +31 -0
  166. package/plugins/kimi-codex/skills/kimi-ask/agents/openai.yaml +6 -0
  167. package/plugins/kimi-codex/skills/kimi-cancel/SKILL.md +25 -0
  168. package/plugins/kimi-codex/skills/kimi-cancel/agents/openai.yaml +6 -0
  169. package/plugins/kimi-codex/skills/kimi-challenge/SKILL.md +31 -0
  170. package/plugins/kimi-codex/skills/kimi-challenge/agents/openai.yaml +6 -0
  171. package/plugins/kimi-codex/skills/kimi-pursue/SKILL.md +30 -0
  172. package/plugins/kimi-codex/skills/kimi-pursue/agents/openai.yaml +6 -0
  173. package/plugins/kimi-codex/skills/kimi-replay/SKILL.md +25 -0
  174. package/plugins/kimi-codex/skills/kimi-replay/agents/openai.yaml +6 -0
  175. package/plugins/kimi-codex/skills/kimi-rescue/SKILL.md +30 -0
  176. package/plugins/kimi-codex/skills/kimi-rescue/agents/openai.yaml +6 -0
  177. package/plugins/kimi-codex/skills/kimi-result/SKILL.md +25 -0
  178. package/plugins/kimi-codex/skills/kimi-result/agents/openai.yaml +6 -0
  179. package/plugins/kimi-codex/skills/kimi-review/SKILL.md +31 -0
  180. package/plugins/kimi-codex/skills/kimi-review/agents/openai.yaml +6 -0
  181. package/plugins/kimi-codex/skills/kimi-setup/SKILL.md +32 -0
  182. package/plugins/kimi-codex/skills/kimi-setup/agents/openai.yaml +6 -0
  183. package/plugins/kimi-codex/skills/kimi-status/SKILL.md +25 -0
  184. package/plugins/kimi-codex/skills/kimi-status/agents/openai.yaml +6 -0
  185. package/plugins/kimi-codex/skills/kimi-swarm/SKILL.md +31 -0
  186. package/plugins/kimi-codex/skills/kimi-swarm/agents/openai.yaml +6 -0
  187. package/plugins/kimi-codex/skills/kimi-swarm-write/SKILL.md +32 -0
  188. package/plugins/kimi-codex/skills/kimi-swarm-write/agents/openai.yaml +6 -0
  189. package/scripts/companion.sh +37 -0
  190. package/scripts/review-gate-hook.sh +32 -0
@@ -0,0 +1,43 @@
1
+ import { RuntimeError } from "../errors.js";
2
+ const ALLOWED_DECISIONS = new Set(["ALLOW", "BLOCK"]);
3
+ const ALLOWED_SEVERITIES = new Set(["low", "medium", "high"]);
4
+ const ALLOWED_CONFIDENCE = new Set(["low", "medium", "high"]);
5
+ export function parseReviewGateOutput(text) {
6
+ let parsed;
7
+ try {
8
+ parsed = JSON.parse(text);
9
+ }
10
+ catch (error) {
11
+ throw new RuntimeError("REVIEW_GATE_PARSE_FAILED", `Review gate output is not valid JSON: ${error.message}`, "review_gate.parse", { cause: error });
12
+ }
13
+ if (!isObject(parsed)) {
14
+ throw new RuntimeError("REVIEW_GATE_PARSE_FAILED", "Review gate output must be a JSON object.", "review_gate.parse");
15
+ }
16
+ const { decision, confidence, summary, issues } = parsed;
17
+ if (!ALLOWED_DECISIONS.has(String(decision)) ||
18
+ !ALLOWED_CONFIDENCE.has(String(confidence)) ||
19
+ typeof summary !== "string" ||
20
+ !Array.isArray(issues)) {
21
+ throw new RuntimeError("REVIEW_GATE_PARSE_FAILED", "Review gate output must contain decision, confidence, summary, and issues.", "review_gate.parse");
22
+ }
23
+ return {
24
+ decision: decision,
25
+ confidence: confidence,
26
+ summary,
27
+ issues: issues.map((issue, index) => normalizeIssue(issue, index)),
28
+ };
29
+ }
30
+ function normalizeIssue(issue, index) {
31
+ if (!isObject(issue)) {
32
+ throw new RuntimeError("REVIEW_GATE_PARSE_FAILED", `Review gate issue ${index + 1} must be an object.`, "review_gate.parse");
33
+ }
34
+ if (typeof issue.title !== "string" ||
35
+ typeof issue.body !== "string" ||
36
+ !ALLOWED_SEVERITIES.has(String(issue.severity))) {
37
+ throw new RuntimeError("REVIEW_GATE_PARSE_FAILED", `Review gate issue ${index + 1} is missing a required field.`, "review_gate.parse");
38
+ }
39
+ return issue;
40
+ }
41
+ function isObject(value) {
42
+ return typeof value === "object" && value !== null && !Array.isArray(value);
43
+ }
@@ -0,0 +1,293 @@
1
+ import { basename, isAbsolute, relative, resolve } from "node:path";
2
+ import path from "node:path";
3
+ import { constants } from "node:fs";
4
+ import { randomUUID } from "node:crypto";
5
+ import { lstat, mkdir, open, realpath, rename, rm, writeFile } from "node:fs/promises";
6
+ import { resolveKimiHome } from "./kimi-home.js";
7
+ export const KIMI_SESSION_TITLE_MAX_LENGTH = 120;
8
+ const SESSION_INDEX_MAX_BYTES = 16 * 1024 * 1024;
9
+ const SESSION_INDEX_LINE_MAX_BYTES = 1024 * 1024;
10
+ const SESSION_STATE_MAX_BYTES = 1024 * 1024;
11
+ const DISPLAY_NAMES = {
12
+ ask: "Ask",
13
+ review: "Review",
14
+ challenge: "Challenge",
15
+ rescue: "Rescue",
16
+ pursue: "Pursue",
17
+ swarm: "Swarm",
18
+ "swarm-write": "Swarm Write",
19
+ };
20
+ export function buildKimiSessionTitle(command, summary) {
21
+ const prefix = `Kimi ${DISPLAY_NAMES[command] ?? "Session"}`;
22
+ const normalized = promptMetadataText(summary ?? "") ?? "";
23
+ return shortenForTitle(normalized ? `${prefix}: ${normalized}` : prefix, KIMI_SESSION_TITLE_MAX_LENGTH);
24
+ }
25
+ export function normalizeTitleFragment(text) {
26
+ return text
27
+ .replace(/[\u0000-\u001f\u007f]/g, " ")
28
+ .replace(/\s+/g, " ")
29
+ .trim();
30
+ }
31
+ /** Mirrors kimi-code 2.0.0 promptMetadataTextFromText: redact BEFORE truncating. */
32
+ export function promptMetadataText(text) {
33
+ const sanitized = text
34
+ .replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/gi, "[redacted]")
35
+ .replace(/\b(authorization)\s*:\s*bearer\s+\S+/gi, "$1: Bearer [redacted]")
36
+ .replace(/\b(api[_-]?key|token|secret|password|passwd|pwd)\b\s*[:=]\s*(?:"[^"]*"|'[^']*'|\S+)/gi, "$1=[redacted]")
37
+ .replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g, "[redacted]")
38
+ .replace(/\b[A-Za-z0-9][A-Za-z0-9+/=_-]{39,}\b/g, "[redacted]")
39
+ .replace(/\p{Cc}+/gu, " ")
40
+ .replace(/\s+/g, " ")
41
+ .trim();
42
+ return sanitized ? sanitized.slice(0, 4000) : undefined;
43
+ }
44
+ export function shortenForTitle(text, maxLength) {
45
+ const normalized = normalizeTitleFragment(text);
46
+ if (normalized.length <= maxLength) {
47
+ return normalized;
48
+ }
49
+ return `${normalized.slice(0, Math.max(0, maxLength - 1)).trimEnd()}…`;
50
+ }
51
+ export async function syncKimiSessionTitle(options) {
52
+ const sessionId = options.sessionId?.trim();
53
+ if (!sessionId) {
54
+ return "missing-session-id";
55
+ }
56
+ if (sessionId === "." || sessionId === ".." || /[/\\\p{Cc}]/u.test(sessionId)) {
57
+ warn(options.stderr, `session metadata sync skipped for ${formatSessionIdForLog(sessionId)}: unsafe session id`);
58
+ return "unsafe-entry";
59
+ }
60
+ const kimiHome = resolveKimiHome(options.env, options.cwd);
61
+ const sessionsRoot = path.join(kimiHome, "sessions");
62
+ const indexPath = path.join(kimiHome, "session_index.jsonl");
63
+ const indexRead = await readUtf8FileCapped(indexPath, SESSION_INDEX_MAX_BYTES);
64
+ if (!indexRead.ok) {
65
+ if (indexRead.reason === "too-large") {
66
+ warn(options.stderr, `session title sync skipped: session_index.jsonl is too large`);
67
+ }
68
+ return "missing-index";
69
+ }
70
+ const entry = findSessionIndexEntry(indexRead.text, sessionId, options.stderr);
71
+ if (!entry) {
72
+ return "missing-entry";
73
+ }
74
+ const safeSessionId = formatSessionIdForLog(sessionId);
75
+ const sessionDir = resolve(entry.sessionDir);
76
+ if (!isAbsolute(entry.sessionDir) ||
77
+ !isPathInside(sessionsRoot, sessionDir) ||
78
+ basename(sessionDir) !== sessionId) {
79
+ warn(options.stderr, `session title sync skipped for ${safeSessionId}: unsafe session index entry`);
80
+ return "unsafe-entry";
81
+ }
82
+ if (!(await isSafeSessionsRoot(sessionsRoot))) {
83
+ warn(options.stderr, `session title sync skipped for ${safeSessionId}: unsafe sessions root`);
84
+ return "unsafe-entry";
85
+ }
86
+ if (!(await isRealPathInside(sessionsRoot, sessionDir))) {
87
+ warn(options.stderr, `session title sync skipped for ${safeSessionId}: unsafe session index target`);
88
+ return "unsafe-entry";
89
+ }
90
+ const statePath = path.join(sessionDir, "state.json");
91
+ const stateFileMode = await readSafeStateFileMode(statePath, options.stderr, sessionId);
92
+ if (stateFileMode === null) {
93
+ return "unsafe-entry";
94
+ }
95
+ let parsed;
96
+ const stateRead = await readUtf8FileCapped(statePath, SESSION_STATE_MAX_BYTES);
97
+ if (!stateRead.ok) {
98
+ const reason = stateRead.reason === "too-large" ? "oversized state.json" : "missing or invalid state.json";
99
+ warn(options.stderr, `session title sync skipped for ${safeSessionId}: ${reason}`);
100
+ return "missing-state";
101
+ }
102
+ try {
103
+ parsed = JSON.parse(stateRead.text);
104
+ }
105
+ catch {
106
+ warn(options.stderr, `session title sync skipped for ${safeSessionId}: missing or invalid state.json`);
107
+ return "missing-state";
108
+ }
109
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
110
+ warn(options.stderr, `session title sync skipped for ${safeSessionId}: invalid state.json shape`);
111
+ return "invalid-state";
112
+ }
113
+ const state = parsed;
114
+ const nativeV2 = state.version === 2;
115
+ if (options.requireNativeV2 && !nativeV2)
116
+ return "unsupported-state";
117
+ if (nativeV2 && typeof state.id === "string" && state.id !== sessionId)
118
+ return "invalid-state";
119
+ // Custom-title normalization also recognizes titleKind and the older customTitle.
120
+ const customTitle = state.isCustomTitle === true || state.titleKind === "custom" ||
121
+ (typeof state.customTitle === "string" && state.customTitle.trim().length > 0);
122
+ const generatedTitle = state.titleKind === "generated";
123
+ const next = { ...state };
124
+ const preview = options.promptText === undefined ? undefined : promptMetadataText(options.promptText);
125
+ if (nativeV2 && preview && (typeof state.lastPrompt !== "string" || !state.lastPrompt.trim())) {
126
+ next.lastPrompt = preview;
127
+ }
128
+ if (!options.preserveTitle && !customTitle && !generatedTitle) {
129
+ next.title = promptMetadataText(options.title)?.slice(0, KIMI_SESSION_TITLE_MAX_LENGTH) ?? "Kimi Session";
130
+ // Native UI generation must remain eligible; a deterministic fallback is not
131
+ // a human rename. Legacy engines retain their existing custom-title behavior.
132
+ next.isCustomTitle = !nativeV2;
133
+ if (nativeV2)
134
+ next.titleKind = "replaceable";
135
+ }
136
+ const changed = JSON.stringify(next) !== JSON.stringify(state);
137
+ if (options.dryRun)
138
+ return changed ? "would-update" : "unchanged";
139
+ try {
140
+ if (changed && !(await writeStateFileAtomic(statePath, `${JSON.stringify(next, null, 2)}\n`, stateFileMode, stateRead.text))) {
141
+ warn(options.stderr, "session metadata sync skipped: state changed concurrently; retry after the session is idle");
142
+ return "state-changed";
143
+ }
144
+ }
145
+ catch {
146
+ warn(options.stderr, `session metadata sync skipped for ${safeSessionId}: failed to write state.json`);
147
+ return "write-failed";
148
+ }
149
+ if (nativeV2) {
150
+ try {
151
+ // Also re-mark unchanged metadata, so a previous invalidation failure is
152
+ // repairable without rewriting the state or changing a manual title.
153
+ await markSessionIndexDirty(sessionsRoot, sessionId);
154
+ }
155
+ catch {
156
+ warn(options.stderr, `session metadata saved for ${safeSessionId}, but index notification failed; retry repair-sessions --apply when idle`);
157
+ return "index-failed";
158
+ }
159
+ }
160
+ return changed ? "updated" : customTitle && !options.preserveTitle ? "custom-title" : "unchanged";
161
+ }
162
+ function findSessionIndexEntry(indexText, sessionId, stderr) {
163
+ for (const line of indexText.split(/\r?\n/)) {
164
+ const trimmed = line.trim();
165
+ if (!trimmed)
166
+ continue;
167
+ if (Buffer.byteLength(trimmed, "utf8") > SESSION_INDEX_LINE_MAX_BYTES) {
168
+ warn(stderr, `session title sync skipped oversized session index line`);
169
+ continue;
170
+ }
171
+ let parsed;
172
+ try {
173
+ parsed = JSON.parse(trimmed);
174
+ }
175
+ catch {
176
+ warn(stderr, `session title sync skipped malformed session index line`);
177
+ continue;
178
+ }
179
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
180
+ continue;
181
+ }
182
+ const entry = parsed;
183
+ if (entry.sessionId === sessionId &&
184
+ typeof entry.sessionDir === "string") {
185
+ return {
186
+ sessionId,
187
+ sessionDir: entry.sessionDir,
188
+ };
189
+ }
190
+ }
191
+ return null;
192
+ }
193
+ function isPathInside(parent, child) {
194
+ const rel = relative(resolve(parent), resolve(child));
195
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
196
+ }
197
+ async function isSafeSessionsRoot(sessionsRoot) {
198
+ try {
199
+ const stats = await lstat(sessionsRoot);
200
+ return stats.isDirectory() && !stats.isSymbolicLink();
201
+ }
202
+ catch {
203
+ return false;
204
+ }
205
+ }
206
+ async function isRealPathInside(parent, child) {
207
+ try {
208
+ let current = parent;
209
+ for (const part of relative(parent, child).split(path.sep)) {
210
+ current = path.join(current, part);
211
+ const info = await lstat(current);
212
+ if (!info.isDirectory() || info.isSymbolicLink())
213
+ return false;
214
+ }
215
+ const realParent = await realpath(parent);
216
+ const realChild = await realpath(child);
217
+ return isPathInside(realParent, realChild);
218
+ }
219
+ catch {
220
+ return false;
221
+ }
222
+ }
223
+ async function readSafeStateFileMode(statePath, stderr, sessionId) {
224
+ try {
225
+ const stats = await lstat(statePath);
226
+ if (stats.isSymbolicLink() || !stats.isFile()) {
227
+ warn(stderr, `session title sync skipped for ${formatSessionIdForLog(sessionId)}: unsafe state.json`);
228
+ return null;
229
+ }
230
+ return stats.mode & 0o777;
231
+ }
232
+ catch {
233
+ return 0o600;
234
+ }
235
+ }
236
+ async function writeStateFileAtomic(statePath, contents, mode, expected) {
237
+ const tmpPath = `${statePath}.${process.pid}.${randomUUID()}.tmp`;
238
+ try {
239
+ await writeFile(tmpPath, contents, { encoding: "utf8", mode, flag: "wx" });
240
+ const current = await readUtf8FileCapped(statePath, SESSION_STATE_MAX_BYTES);
241
+ if (!current.ok || current.text !== expected)
242
+ return false;
243
+ await rename(tmpPath, statePath);
244
+ return true;
245
+ }
246
+ finally {
247
+ await rm(tmpPath, { force: true }).catch(() => { });
248
+ }
249
+ }
250
+ async function markSessionIndexDirty(sessionsRoot, sessionId) {
251
+ if (!(await isSafeSessionsRoot(sessionsRoot)))
252
+ throw new Error("Unsafe sessions root");
253
+ const dir = path.join(sessionsRoot, ".index-dirty");
254
+ await mkdir(dir, { mode: 0o700 }).catch((error) => {
255
+ if (error.code !== "EEXIST")
256
+ throw error;
257
+ });
258
+ if (!(await isRealPathInside(sessionsRoot, dir)))
259
+ throw new Error("Unsafe dirty journal");
260
+ // Upstream splits at the LAST dot; the unique suffix must contain no dots.
261
+ const file = await open(path.join(dir, `${sessionId}.${Date.now()}-${randomUUID()}`), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
262
+ await file.close();
263
+ }
264
+ async function readUtf8FileCapped(filePath, maxBytes) {
265
+ let file;
266
+ try {
267
+ file = await open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
268
+ }
269
+ catch {
270
+ return { ok: false, reason: "missing" };
271
+ }
272
+ try {
273
+ const stats = await file.stat();
274
+ if (!stats.isFile()) {
275
+ return { ok: false, reason: "not-file" };
276
+ }
277
+ if (stats.size > maxBytes) {
278
+ return { ok: false, reason: "too-large" };
279
+ }
280
+ const buffer = Buffer.alloc(stats.size);
281
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
282
+ return { ok: true, text: buffer.subarray(0, bytesRead).toString("utf8") };
283
+ }
284
+ finally {
285
+ await file.close();
286
+ }
287
+ }
288
+ function formatSessionIdForLog(sessionId) {
289
+ return JSON.stringify(normalizeTitleFragment(sessionId));
290
+ }
291
+ function warn(stderr, message) {
292
+ stderr?.write(`[kimi-plugin-cc] ${message}.\n`);
293
+ }