kimi-plugin-cc 2.4.4 → 2.5.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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +21 -0
- package/README.md +50 -34
- package/dist/commands/swarm.js +1 -1
- package/dist/dsh/companion.js +174 -0
- package/dist/dsh/index.js +156 -0
- package/dist/hooks/config-safety.js +3 -2
- package/dist/hooks/install-paths.js +2 -2
- package/dist/kimi-engine.js +1 -0
- package/dist/swarm-activation.js +1 -1
- package/dist/version.js +1 -1
- package/docs/migration.md +4 -4
- package/docs/models.md +5 -1
- package/docs/registry-releases.md +20 -17
- package/docs/safety.md +28 -15
- package/docs/swarm-recovery.md +1 -1
- package/docs/upstream-2.4.1-certification.md +54 -0
- package/package.json +41 -6
- package/plugins/kimi-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/kimi-codex/dist/commands/swarm.js +1 -1
- package/plugins/kimi-codex/dist/dsh/companion.js +174 -0
- package/plugins/kimi-codex/dist/dsh/index.js +156 -0
- package/plugins/kimi-codex/dist/hooks/config-safety.js +3 -2
- package/plugins/kimi-codex/dist/hooks/install-paths.js +2 -2
- package/plugins/kimi-codex/dist/kimi-engine.js +1 -0
- package/plugins/kimi-codex/dist/swarm-activation.js +1 -1
- package/plugins/kimi-codex/dist/version.js +1 -1
- package/plugins/kimi-dsh/LICENSE +201 -0
- package/plugins/kimi-dsh/README.md +80 -0
- package/plugins/kimi-dsh/cordis.patch.yml +45 -0
- package/plugins/kimi-dsh/dist/background-spawn.js +216 -0
- package/plugins/kimi-dsh/dist/cli-cancellation.js +43 -0
- package/plugins/kimi-dsh/dist/cli-client.js +876 -0
- package/plugins/kimi-dsh/dist/commands/ask.js +336 -0
- package/plugins/kimi-dsh/dist/commands/cancel.js +216 -0
- package/plugins/kimi-dsh/dist/commands/cli-helpers.js +201 -0
- package/plugins/kimi-dsh/dist/commands/models.js +140 -0
- package/plugins/kimi-dsh/dist/commands/not-implemented.js +4 -0
- package/plugins/kimi-dsh/dist/commands/pursue.js +307 -0
- package/plugins/kimi-dsh/dist/commands/recover-swarm.js +135 -0
- package/plugins/kimi-dsh/dist/commands/registry.js +74 -0
- package/plugins/kimi-dsh/dist/commands/repair-sessions.js +160 -0
- package/plugins/kimi-dsh/dist/commands/replay.js +124 -0
- package/plugins/kimi-dsh/dist/commands/rescue.js +347 -0
- package/plugins/kimi-dsh/dist/commands/result.js +66 -0
- package/plugins/kimi-dsh/dist/commands/review-gate.js +390 -0
- package/plugins/kimi-dsh/dist/commands/review.js +220 -0
- package/plugins/kimi-dsh/dist/commands/setup.js +1047 -0
- package/plugins/kimi-dsh/dist/commands/status.js +27 -0
- package/plugins/kimi-dsh/dist/commands/swarm.js +754 -0
- package/plugins/kimi-dsh/dist/commands/worker.js +25 -0
- package/plugins/kimi-dsh/dist/companion.js +97 -0
- package/plugins/kimi-dsh/dist/config.js +22 -0
- package/plugins/kimi-dsh/dist/dsh/companion.js +174 -0
- package/plugins/kimi-dsh/dist/dsh/index.js +156 -0
- package/plugins/kimi-dsh/dist/errors.js +40 -0
- package/plugins/kimi-dsh/dist/git.js +224 -0
- package/plugins/kimi-dsh/dist/help.js +43 -0
- package/plugins/kimi-dsh/dist/hook-escape.js +71 -0
- package/plugins/kimi-dsh/dist/hooks/approval-hook.js +101 -0
- package/plugins/kimi-dsh/dist/hooks/approval-policy.js +211 -0
- package/plugins/kimi-dsh/dist/hooks/config-safety.js +653 -0
- package/plugins/kimi-dsh/dist/hooks/install-paths.js +428 -0
- package/plugins/kimi-dsh/dist/hooks/install.js +210 -0
- package/plugins/kimi-dsh/dist/hooks/managed-block.js +619 -0
- package/plugins/kimi-dsh/dist/hooks/review-gate-stop.js +19 -0
- package/plugins/kimi-dsh/dist/job-id.js +12 -0
- package/plugins/kimi-dsh/dist/job-store.js +659 -0
- package/plugins/kimi-dsh/dist/jobs.js +217 -0
- package/plugins/kimi-dsh/dist/kimi-command.js +70 -0
- package/plugins/kimi-dsh/dist/kimi-engine.js +632 -0
- package/plugins/kimi-dsh/dist/kimi-errors.js +260 -0
- package/plugins/kimi-dsh/dist/kimi-home.js +9 -0
- package/plugins/kimi-dsh/dist/kimi-timeouts.js +52 -0
- package/plugins/kimi-dsh/dist/kimi-version-probe.js +216 -0
- package/plugins/kimi-dsh/dist/logging.js +22 -0
- package/plugins/kimi-dsh/dist/mcp/binding.js +58 -0
- package/plugins/kimi-dsh/dist/mcp/job-control.js +345 -0
- package/plugins/kimi-dsh/dist/mcp/launcher.js +257 -0
- package/plugins/kimi-dsh/dist/mcp/operations.js +301 -0
- package/plugins/kimi-dsh/dist/mcp/protocol.js +275 -0
- package/plugins/kimi-dsh/dist/mcp/server.js +8 -0
- package/plugins/kimi-dsh/dist/mcp/stdio.js +78 -0
- package/plugins/kimi-dsh/dist/mcp/supervised-child.js +15 -0
- package/plugins/kimi-dsh/dist/mcp/tool-result.js +7 -0
- package/plugins/kimi-dsh/dist/mcp/workspace.js +34 -0
- package/plugins/kimi-dsh/dist/model-command.js +32 -0
- package/plugins/kimi-dsh/dist/native-v2-preflight.js +417 -0
- package/plugins/kimi-dsh/dist/package.json +1 -0
- package/plugins/kimi-dsh/dist/parsing.js +620 -0
- package/plugins/kimi-dsh/dist/paths.js +27 -0
- package/plugins/kimi-dsh/dist/plugin-data.js +98 -0
- package/plugins/kimi-dsh/dist/process-tree.js +479 -0
- package/plugins/kimi-dsh/dist/prompt-size.js +18 -0
- package/plugins/kimi-dsh/dist/render.js +177 -0
- package/plugins/kimi-dsh/dist/rescue-approval.js +865 -0
- package/plugins/kimi-dsh/dist/schemas/review-gate-output.js +43 -0
- package/plugins/kimi-dsh/dist/session-recovery.js +200 -0
- package/plugins/kimi-dsh/dist/session-title.js +293 -0
- package/plugins/kimi-dsh/dist/stream-json.js +346 -0
- package/plugins/kimi-dsh/dist/swarm-activation.js +834 -0
- package/plugins/kimi-dsh/dist/swarm-recovery.js +134 -0
- package/plugins/kimi-dsh/dist/types.js +1 -0
- package/plugins/kimi-dsh/dist/vendor/shell-quote/LICENSE +24 -0
- package/plugins/kimi-dsh/dist/vendor/shell-quote/index.js +1 -0
- package/plugins/kimi-dsh/dist/vendor/shell-quote/parse.js +229 -0
- package/plugins/kimi-dsh/dist/vendor/smol-toml/LICENSE +24 -0
- package/plugins/kimi-dsh/dist/vendor/smol-toml/date.js +156 -0
- package/plugins/kimi-dsh/dist/vendor/smol-toml/error.js +67 -0
- package/plugins/kimi-dsh/dist/vendor/smol-toml/extract.js +293 -0
- package/plugins/kimi-dsh/dist/vendor/smol-toml/parse.js +164 -0
- package/plugins/kimi-dsh/dist/vendor/smol-toml/primitive.js +151 -0
- package/plugins/kimi-dsh/dist/vendor/smol-toml/struct.js +156 -0
- package/plugins/kimi-dsh/dist/vendor/smol-toml/util.js +57 -0
- package/plugins/kimi-dsh/dist/version.js +7 -0
- package/plugins/kimi-dsh/package.json +48 -0
- package/plugins/kimi-dsh/scripts/companion.sh +37 -0
- package/plugins/kimi-dsh/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,200 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { lstat, open, opendir, realpath } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { digestPrompt } from "./jobs.js";
|
|
5
|
+
// Total entries visited across both enumeration levels. The cap guards against
|
|
6
|
+
// a pathological tree rather than budgeting normal store size. opendir streams,
|
|
7
|
+
// so entries are not buffered. Dot-entries (`.index-dirty`, `.index-cache`) are
|
|
8
|
+
// upstream index state, never workspaces, and are skipped without being counted.
|
|
9
|
+
// Directories whose mtime predates the spawn cannot have been created by this
|
|
10
|
+
// run and are skipped before any read, so the byte budget scales with concurrent
|
|
11
|
+
// activity, not with store size.
|
|
12
|
+
const DIR_ENUM_CAP = 65_536;
|
|
13
|
+
const STATE_MAX_BYTES = 1024 * 1024;
|
|
14
|
+
const JOURNAL_PREFIX_BYTES = 4 * 1024 * 1024; // The prompt is argv-bounded (< 1 MiB); the first user message follows a few config records.
|
|
15
|
+
const SCAN_MAX_BYTES = 64 * 1024 * 1024;
|
|
16
|
+
const MTIME_SLACK_MS = 1000; // Filesystems with coarse mtime granularity.
|
|
17
|
+
const SESSION_ID = /^session_[0-9a-f-]{36}$/;
|
|
18
|
+
/** Metadata recovery only, never a substitute for resume lineage/plan scans.
|
|
19
|
+
* A capped or unreadable enumeration cannot establish uniqueness and refuses;
|
|
20
|
+
* skipping symlinked or dot entries is not partial — neither can be a session
|
|
21
|
+
* the child created.
|
|
22
|
+
*
|
|
23
|
+
* A candidate is bound to THIS job by content, not only by time: the first
|
|
24
|
+
* user message in the session's main journal must carry a text item whose
|
|
25
|
+
* sha256 equals the job's `prompt_digest` (the exact `-p` argument). Time and
|
|
26
|
+
* cwd alone would admit a concurrent TUI session, another host's finished job
|
|
27
|
+
* (host-local stores cannot see each other's session ids), or a `state.json`
|
|
28
|
+
* planted by repository code running under rescue. The digest is not unique
|
|
29
|
+
* on its own either (the same prompt can run twice), so the window and the
|
|
30
|
+
* exactly-one rule stay in force. */
|
|
31
|
+
export async function recoverSessionIdFromStore(options) {
|
|
32
|
+
const entryCap = options.entryCap ?? DIR_ENUM_CAP;
|
|
33
|
+
let entries = 0;
|
|
34
|
+
let bytes = 0;
|
|
35
|
+
let digestMismatches = 0;
|
|
36
|
+
let missingJournals = 0;
|
|
37
|
+
const candidates = [];
|
|
38
|
+
const capped = new Error("enumeration_capped");
|
|
39
|
+
async function* directories(dir) {
|
|
40
|
+
if ((await lstat(dir)).isSymbolicLink())
|
|
41
|
+
throw new Error("unreadable");
|
|
42
|
+
const handle = await opendir(dir);
|
|
43
|
+
for await (const entry of handle) {
|
|
44
|
+
if (entry.name.startsWith("."))
|
|
45
|
+
continue;
|
|
46
|
+
if (++entries > entryCap)
|
|
47
|
+
throw capped;
|
|
48
|
+
// A symlinked entry is never a session the child created; skipping it
|
|
49
|
+
// keeps one stray link from disabling recovery host-wide. Directories
|
|
50
|
+
// we descend are still lstat-anchored above.
|
|
51
|
+
if (entry.isSymbolicLink())
|
|
52
|
+
continue;
|
|
53
|
+
if (entry.isDirectory())
|
|
54
|
+
yield entry.name;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
// Bounded no-follow read of a regular file. Returns undefined when the file
|
|
58
|
+
// is absent; throws "unreadable" for anything that is not a plain file. With
|
|
59
|
+
// `prefix`, a larger file yields its first `maxBytes` instead of refusing.
|
|
60
|
+
async function readBounded(file, maxBytes, prefix = false) {
|
|
61
|
+
let handle;
|
|
62
|
+
try {
|
|
63
|
+
handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (error.code === "ENOENT")
|
|
67
|
+
return undefined;
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
const stat = await handle.stat();
|
|
72
|
+
if (!stat.isFile() || (stat.size > maxBytes && !prefix))
|
|
73
|
+
throw new Error("unreadable");
|
|
74
|
+
const size = Math.min(stat.size, maxBytes);
|
|
75
|
+
bytes += size;
|
|
76
|
+
if (bytes > SCAN_MAX_BYTES)
|
|
77
|
+
throw capped;
|
|
78
|
+
const buffer = Buffer.alloc(size);
|
|
79
|
+
let offset = 0;
|
|
80
|
+
while (offset < buffer.length) {
|
|
81
|
+
const read = await handle.read(buffer, offset, buffer.length - offset, offset);
|
|
82
|
+
if (!read.bytesRead)
|
|
83
|
+
break;
|
|
84
|
+
offset += read.bytesRead;
|
|
85
|
+
}
|
|
86
|
+
return buffer.subarray(0, offset);
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
await handle.close();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
if (!Number.isFinite(options.spawnedAt) || !Number.isFinite(options.settledAt) ||
|
|
94
|
+
options.settledAt < options.spawnedAt || !/^[0-9a-f]{64}$/.test(options.promptDigest)) {
|
|
95
|
+
return { reason: "none" };
|
|
96
|
+
}
|
|
97
|
+
const cwd = await realpath(options.cwd);
|
|
98
|
+
const sessions = path.join(options.kimiHome, "sessions");
|
|
99
|
+
// Missing nested dirs mean an incomplete scan; only a missing root is normal.
|
|
100
|
+
try {
|
|
101
|
+
await lstat(sessions);
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
if (error.code === "ENOENT")
|
|
105
|
+
return { reason: "none" };
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
for await (const workspace of directories(sessions)) {
|
|
109
|
+
const workspacePath = path.join(sessions, workspace);
|
|
110
|
+
for await (const session of directories(workspacePath)) {
|
|
111
|
+
if (!SESSION_ID.test(session))
|
|
112
|
+
continue;
|
|
113
|
+
const sessionPath = path.join(workspacePath, session);
|
|
114
|
+
// A directory this run created was modified at or after the spawn.
|
|
115
|
+
if ((await lstat(sessionPath)).mtimeMs < options.spawnedAt - MTIME_SLACK_MS)
|
|
116
|
+
continue;
|
|
117
|
+
const raw = await readBounded(path.join(sessionPath, "state.json"), STATE_MAX_BYTES);
|
|
118
|
+
if (!raw)
|
|
119
|
+
continue;
|
|
120
|
+
let state;
|
|
121
|
+
try {
|
|
122
|
+
state = JSON.parse(raw.toString("utf8"));
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (!state || typeof state !== "object")
|
|
128
|
+
continue;
|
|
129
|
+
const value = state;
|
|
130
|
+
// The child writes createdAt after the parent stamped spawnedAt on the
|
|
131
|
+
// same clock, so causality orders them; no pre-spawn slack is justified.
|
|
132
|
+
if (value.version !== 2 || typeof value.cwd !== "string" || !path.isAbsolute(value.cwd) ||
|
|
133
|
+
typeof value.id !== "string" || !SESSION_ID.test(value.id) || value.id !== session ||
|
|
134
|
+
typeof value.createdAt !== "number" || !Number.isFinite(value.createdAt) ||
|
|
135
|
+
value.createdAt < options.spawnedAt || value.createdAt > options.settledAt)
|
|
136
|
+
continue;
|
|
137
|
+
let stateCwd;
|
|
138
|
+
try {
|
|
139
|
+
stateCwd = await realpath(value.cwd);
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (stateCwd !== cwd || options.store.hasSessionId(value.id, options.jobId))
|
|
145
|
+
continue;
|
|
146
|
+
const journal = await readBounded(path.join(sessionPath, "agents", "main", "wire.jsonl"), JOURNAL_PREFIX_BYTES, true);
|
|
147
|
+
if (!journal) {
|
|
148
|
+
missingJournals += 1;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
// A prefix cut mid-record must never be parsed as a complete line.
|
|
152
|
+
const text = journal.length === JOURNAL_PREFIX_BYTES
|
|
153
|
+
? journal.subarray(0, journal.lastIndexOf(0x0a) + 1).toString("utf8") : journal.toString("utf8");
|
|
154
|
+
if (!firstUserMessageMatches(text, options.promptDigest)) {
|
|
155
|
+
digestMismatches += 1;
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
candidates.push(value.id);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (candidates.length === 1)
|
|
162
|
+
return { sessionId: candidates[0] };
|
|
163
|
+
if (candidates.length > 1)
|
|
164
|
+
return { reason: `ambiguous:${candidates.length}` };
|
|
165
|
+
if (digestMismatches > 0)
|
|
166
|
+
return { reason: `digest_mismatch:${digestMismatches}` };
|
|
167
|
+
return { reason: missingJournals > 0 ? `journal_missing:${missingJournals}` : "none" };
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
return { reason: error === capped ? "enumeration_capped" : "unreadable" };
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/** True when the FIRST user message in a native-v2 main journal carries a
|
|
174
|
+
* text item equal to the prompt the job spawned with. Later user turns are
|
|
175
|
+
* never consulted: only the opening prompt binds a session to its spawn. */
|
|
176
|
+
export function firstUserMessageMatches(journal, promptDigest) {
|
|
177
|
+
for (const line of journal.split("\n")) {
|
|
178
|
+
if (!line.trim())
|
|
179
|
+
continue;
|
|
180
|
+
let record;
|
|
181
|
+
try {
|
|
182
|
+
record = JSON.parse(line);
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (!record || typeof record !== "object")
|
|
188
|
+
continue;
|
|
189
|
+
const message = record.message;
|
|
190
|
+
if (!message || typeof message !== "object" || message.role !== "user")
|
|
191
|
+
continue;
|
|
192
|
+
const content = message.content;
|
|
193
|
+
if (!Array.isArray(content))
|
|
194
|
+
return false;
|
|
195
|
+
return content.some((item) => item && typeof item === "object" && item.type === "text" &&
|
|
196
|
+
typeof item.text === "string" &&
|
|
197
|
+
digestPrompt(item.text) === promptDigest);
|
|
198
|
+
}
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
@@ -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
|
+
}
|