@microvac/adapter-kimi-local 0.0.0-stage → 0.1.0-rc.14

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 +22 -0
  2. package/dist/cli/format-event.d.ts +2 -0
  3. package/dist/cli/format-event.d.ts.map +1 -0
  4. package/dist/cli/format-event.js +95 -0
  5. package/dist/cli/format-event.js.map +1 -0
  6. package/dist/cli/index.d.ts +2 -0
  7. package/dist/cli/index.d.ts.map +1 -0
  8. package/dist/cli/index.js +2 -0
  9. package/dist/cli/index.js.map +1 -0
  10. package/dist/index.d.ts +30 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +82 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/server/acp.d.ts +19 -0
  15. package/dist/server/acp.d.ts.map +1 -0
  16. package/dist/server/acp.js +318 -0
  17. package/dist/server/acp.js.map +1 -0
  18. package/dist/server/acp.test.d.ts +2 -0
  19. package/dist/server/acp.test.d.ts.map +1 -0
  20. package/dist/server/acp.test.js +57 -0
  21. package/dist/server/acp.test.js.map +1 -0
  22. package/dist/server/engine-availability.test.d.ts +2 -0
  23. package/dist/server/engine-availability.test.d.ts.map +1 -0
  24. package/dist/server/engine-availability.test.js +68 -0
  25. package/dist/server/engine-availability.test.js.map +1 -0
  26. package/dist/server/execute.acp-failure.test.d.ts +2 -0
  27. package/dist/server/execute.acp-failure.test.d.ts.map +1 -0
  28. package/dist/server/execute.acp-failure.test.js +22 -0
  29. package/dist/server/execute.acp-failure.test.js.map +1 -0
  30. package/dist/server/execute.d.ts +3 -0
  31. package/dist/server/execute.d.ts.map +1 -0
  32. package/dist/server/execute.js +653 -0
  33. package/dist/server/execute.js.map +1 -0
  34. package/dist/server/execute.test.d.ts +2 -0
  35. package/dist/server/execute.test.d.ts.map +1 -0
  36. package/dist/server/execute.test.js +388 -0
  37. package/dist/server/execute.test.js.map +1 -0
  38. package/dist/server/index.d.ts +8 -0
  39. package/dist/server/index.d.ts.map +1 -0
  40. package/dist/server/index.js +71 -0
  41. package/dist/server/index.js.map +1 -0
  42. package/dist/server/parse.d.ts +66 -0
  43. package/dist/server/parse.d.ts.map +1 -0
  44. package/dist/server/parse.js +194 -0
  45. package/dist/server/parse.js.map +1 -0
  46. package/dist/server/parse.test.d.ts +2 -0
  47. package/dist/server/parse.test.d.ts.map +1 -0
  48. package/dist/server/parse.test.js +155 -0
  49. package/dist/server/parse.test.js.map +1 -0
  50. package/dist/server/skills.d.ts +4 -0
  51. package/dist/server/skills.d.ts.map +1 -0
  52. package/dist/server/skills.js +73 -0
  53. package/dist/server/skills.js.map +1 -0
  54. package/dist/server/test.d.ts +3 -0
  55. package/dist/server/test.d.ts.map +1 -0
  56. package/dist/server/test.js +308 -0
  57. package/dist/server/test.js.map +1 -0
  58. package/dist/server/test.test.d.ts +2 -0
  59. package/dist/server/test.test.d.ts.map +1 -0
  60. package/dist/server/test.test.js +126 -0
  61. package/dist/server/test.test.js.map +1 -0
  62. package/dist/server/utils.d.ts +2 -0
  63. package/dist/server/utils.d.ts.map +1 -0
  64. package/dist/server/utils.js +7 -0
  65. package/dist/server/utils.js.map +1 -0
  66. package/dist/ui/build-config.d.ts +3 -0
  67. package/dist/ui/build-config.d.ts.map +1 -0
  68. package/dist/ui/build-config.js +79 -0
  69. package/dist/ui/build-config.js.map +1 -0
  70. package/dist/ui/build-config.test.d.ts +2 -0
  71. package/dist/ui/build-config.test.d.ts.map +1 -0
  72. package/dist/ui/build-config.test.js +73 -0
  73. package/dist/ui/build-config.test.js.map +1 -0
  74. package/dist/ui/index.d.ts +3 -0
  75. package/dist/ui/index.d.ts.map +1 -0
  76. package/dist/ui/index.js +3 -0
  77. package/dist/ui/index.js.map +1 -0
  78. package/dist/ui/parse-stdout.d.ts +9 -0
  79. package/dist/ui/parse-stdout.d.ts.map +1 -0
  80. package/dist/ui/parse-stdout.js +110 -0
  81. package/dist/ui/parse-stdout.js.map +1 -0
  82. package/dist/ui/parse-stdout.test.d.ts +2 -0
  83. package/dist/ui/parse-stdout.test.d.ts.map +1 -0
  84. package/dist/ui/parse-stdout.test.js +84 -0
  85. package/dist/ui/parse-stdout.test.js.map +1 -0
  86. package/package.json +51 -4
  87. package/README.md +0 -3
@@ -0,0 +1,653 @@
1
+ import { createProviderStoppedBoundary } from "@paperclipai/adapter-utils/provider-stopped-boundary";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { managedRemoteHomeEnvironment, adapterExecutionTargetIsRemote, adapterExecutionTargetRemoteCwd, overrideAdapterExecutionTargetRemoteCwd, adapterExecutionTargetSessionIdentity, adapterExecutionTargetSessionMatches, adapterExecutionTargetUsesManagedHome, adapterExecutionTargetUsesPaperclipBridge, describeAdapterExecutionTarget, ensureAdapterExecutionTargetCommandResolvable, ensureAdapterExecutionTargetLocalWorkspace, ensureAdapterExecutionTargetRuntimeCommandInstalled, prepareAdapterExecutionTargetRuntime, readAdapterExecutionTarget, resolveAdapterExecutionTargetTimeoutSec, resolveAdapterExecutionTargetCommandForLogs, runAdapterExecutionTargetProcess, startAdapterExecutionTargetPaperclipBridge, } from "@paperclipai/adapter-utils/execution-target";
7
+ import { asNumber, asString, asStringArray, buildPaperclipEnv, buildRuntimeToolsEnv, buildInvocationEnvForLogs, joinPromptSections, ensurePathInEnv, refreshPaperclipWorkspaceEnvForExecution, isPaperclipSkillSourceMissing, readPaperclipRuntimeSkillEntries, readPaperclipIssueWorkModeFromContext, resolveLegacyPaperclipDesiredSkillNames, parseObject, renderTemplate, hydrateFreshSessionHandoff, selectPaperclipPromptSections, selectInitialCommunicationGuidance, isPaperclipRecoveryWakePayload, DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE, DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE, } from "@paperclipai/adapter-utils/server-utils";
8
+ import { SANDBOX_INSTALL_COMMAND, modelSupportsEffort, resolveKimiThinkingEffort, } from "../index.js";
9
+ import { describeKimiFailure, detectKimiAuthRequired, extractKimiRuntimeEvents, isKimiSessionUnrecoverableError, isKimiTransientNetworkError, parseKimiJsonl, } from "./parse.js";
10
+ import { createKimiAcpExecutor, resolveKimiExecutionEngineForRun, } from "./acp.js";
11
+ import { firstNonEmptyLine } from "./utils.js";
12
+ const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
13
+ const executeKimiAcp = createKimiAcpExecutor();
14
+ /**
15
+ * Wrap `onLog` so each complete kimi stream-json stdout line is also mapped to
16
+ * `onEvent` runtime events (assistant snippet, tool name). This keeps the raw
17
+ * run log intact while lighting up the issue-thread activity indicator, which
18
+ * reads `currentToolName` / `lastAssistantSnippet` / `lastEventAt` derived from
19
+ * `onEvent` rather than from the raw log stream. Stdout arrives in arbitrary
20
+ * chunks, so lines are buffered and split on newlines. `flush` must be called
21
+ * once the process exits so the final line reaches `onEvent` even when kimi
22
+ * closes stdout without a trailing newline (otherwise the last assistant
23
+ * message or tool call would be missing from live status).
24
+ */
25
+ function createKimiEventForwardingLog(onLog, onEvent) {
26
+ if (!onEvent)
27
+ return { log: onLog, flush: async () => { } };
28
+ let buffer = "";
29
+ const emitLine = async (raw) => {
30
+ const line = raw.trim();
31
+ if (!line)
32
+ return;
33
+ for (const event of extractKimiRuntimeEvents(line)) {
34
+ await onEvent({ eventType: event.eventType, stream: "stdout", message: event.message, payload: event.payload });
35
+ }
36
+ };
37
+ return {
38
+ log: async (stream, chunk) => {
39
+ await onLog(stream, chunk);
40
+ if (stream !== "stdout")
41
+ return;
42
+ buffer += chunk;
43
+ let newlineIndex;
44
+ while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
45
+ const line = buffer.slice(0, newlineIndex);
46
+ buffer = buffer.slice(newlineIndex + 1);
47
+ await emitLine(line);
48
+ }
49
+ },
50
+ flush: async () => {
51
+ const remaining = buffer;
52
+ buffer = "";
53
+ await emitLine(remaining);
54
+ },
55
+ };
56
+ }
57
+ function hasNonEmptyEnvValue(env, key) {
58
+ const raw = env[key];
59
+ return typeof raw === "string" && raw.trim().length > 0;
60
+ }
61
+ function resolveKimiBillingType(env) {
62
+ return hasNonEmptyEnvValue(env, "KIMI_MODEL_API_KEY") ? "api" : "subscription";
63
+ }
64
+ /**
65
+ * Headless-safe environment for unattended `kimi -p` runs. CI=1 disables
66
+ * theme detection, NO_COLOR=1 keeps stdout parseable, and
67
+ * KIMI_CODE_NO_AUTO_UPDATE=1 skips the update preflight. User-configured
68
+ * values always win.
69
+ */
70
+ function buildKimiHeadlessEnv(env) {
71
+ const next = { ...env };
72
+ if (!next.CI?.trim())
73
+ next.CI = "1";
74
+ if (!next.NO_COLOR?.trim())
75
+ next.NO_COLOR = "1";
76
+ if (!next.KIMI_CODE_NO_AUTO_UPDATE?.trim())
77
+ next.KIMI_CODE_NO_AUTO_UPDATE = "1";
78
+ if (!next.TERM?.trim())
79
+ next.TERM = "dumb";
80
+ return next;
81
+ }
82
+ function buildKimiRuntimeEnv(env) {
83
+ return Object.fromEntries(Object.entries(ensurePathInEnv({ ...process.env, ...buildKimiHeadlessEnv(env) })).filter((entry) => typeof entry[1] === "string"));
84
+ }
85
+ function renderPaperclipEnvNote(env) {
86
+ const paperclipKeys = Object.keys(env)
87
+ .filter((key) => key.startsWith("PAPERCLIP_"))
88
+ .sort();
89
+ if (paperclipKeys.length === 0)
90
+ return "";
91
+ return [
92
+ "Paperclip runtime note:",
93
+ `The following PAPERCLIP_* environment variables are available in this run: ${paperclipKeys.join(", ")}`,
94
+ "Do not assume these variables are missing without checking your shell environment.",
95
+ "",
96
+ "",
97
+ ].join("\n");
98
+ }
99
+ function renderApiAccessNote(env) {
100
+ if (!hasNonEmptyEnvValue(env, "PAPERCLIP_API_URL") || !hasNonEmptyEnvValue(env, "PAPERCLIP_API_KEY"))
101
+ return "";
102
+ return [
103
+ "Paperclip API access note:",
104
+ "Use shell commands with curl to make Paperclip API requests when needed.",
105
+ "Include X-Paperclip-Run-Id on mutating requests.",
106
+ "",
107
+ "",
108
+ ].join("\n");
109
+ }
110
+ async function buildKimiSkillsDir(config) {
111
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-kimi-skills-"));
112
+ const target = path.join(tmp, "skills");
113
+ await fs.mkdir(target, { recursive: true });
114
+ const availableEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
115
+ const desiredNames = new Set(resolveLegacyPaperclipDesiredSkillNames(config, availableEntries));
116
+ for (const entry of availableEntries) {
117
+ if (!desiredNames.has(entry.key))
118
+ continue;
119
+ if (isPaperclipSkillSourceMissing(entry))
120
+ continue;
121
+ await fs.symlink(entry.source, path.join(target, entry.runtimeName));
122
+ }
123
+ return target;
124
+ }
125
+ export async function execute(ctx) {
126
+ const providerStop = createProviderStoppedBoundary(ctx.onProviderStopped);
127
+ const engineSelection = await resolveKimiExecutionEngineForRun(ctx);
128
+ if (engineSelection.unavailableReason) {
129
+ return {
130
+ exitCode: 1,
131
+ signal: null,
132
+ timedOut: false,
133
+ errorCode: "adapter_engine_unavailable",
134
+ errorMessage: engineSelection.unavailableReason,
135
+ resultJson: {
136
+ executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
137
+ },
138
+ };
139
+ }
140
+ if (engineSelection.engine === "acp") {
141
+ return executeKimiAcp(ctx);
142
+ }
143
+ const { runId, agent, runtime, config, context, onLog, onMeta, onEvent, onSpawn, authToken } = ctx;
144
+ const executionTarget = readAdapterExecutionTarget({
145
+ executionTarget: ctx.executionTarget,
146
+ legacyRemoteExecution: ctx.executionTransport?.remoteExecution,
147
+ });
148
+ const executionTargetIsRemote = adapterExecutionTargetIsRemote(executionTarget);
149
+ const promptTemplate = asString(config.promptTemplate, context.conversationMode === true
150
+ ? DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE
151
+ : DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE);
152
+ const command = asString(config.command, "kimi");
153
+ const model = asString(config.model, "").trim();
154
+ const workspaceContext = parseObject(context.paperclipWorkspace);
155
+ const workspaceCwd = asString(workspaceContext.cwd, "");
156
+ const workspaceSource = asString(workspaceContext.source, "");
157
+ const workspaceId = asString(workspaceContext.workspaceId, "");
158
+ const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
159
+ const workspaceRepoRef = asString(workspaceContext.repoRef, "");
160
+ const agentHome = asString(workspaceContext.agentHome, "");
161
+ const workspaceHints = Array.isArray(context.paperclipWorkspaces)
162
+ ? context.paperclipWorkspaces.filter((value) => typeof value === "object" && value !== null)
163
+ : [];
164
+ const configuredCwd = asString(config.cwd, "");
165
+ const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0;
166
+ const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd;
167
+ const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd();
168
+ let effectiveExecutionCwd = adapterExecutionTargetRemoteCwd(executionTarget, cwd);
169
+ await ensureAdapterExecutionTargetLocalWorkspace(executionTarget, cwd);
170
+ const kimiSkillEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
171
+ const desiredKimiSkillNames = resolveLegacyPaperclipDesiredSkillNames(config, kimiSkillEntries);
172
+ const envConfig = parseObject(config.env);
173
+ const hasExplicitApiKey = typeof envConfig.PAPERCLIP_API_KEY === "string" && envConfig.PAPERCLIP_API_KEY.trim().length > 0;
174
+ const env = {
175
+ ...buildPaperclipEnv(agent, ctx.agentIdentity),
176
+ ...buildRuntimeToolsEnv(ctx.runtimeTools),
177
+ };
178
+ env.PAPERCLIP_RUN_ID = runId;
179
+ const wakeTaskId = (typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim()) ||
180
+ (typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim()) ||
181
+ null;
182
+ const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0
183
+ ? context.wakeReason.trim()
184
+ : null;
185
+ const wakeCommentId = (typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim()) ||
186
+ (typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim()) ||
187
+ null;
188
+ const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0
189
+ ? context.approvalId.trim()
190
+ : null;
191
+ const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0
192
+ ? context.approvalStatus.trim()
193
+ : null;
194
+ const linkedIssueIds = Array.isArray(context.issueIds)
195
+ ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0)
196
+ : [];
197
+ const issueWorkMode = readPaperclipIssueWorkModeFromContext(context);
198
+ if (wakeTaskId)
199
+ env.PAPERCLIP_TASK_ID = wakeTaskId;
200
+ if (issueWorkMode)
201
+ env.PAPERCLIP_ISSUE_WORK_MODE = issueWorkMode;
202
+ if (wakeReason)
203
+ env.PAPERCLIP_WAKE_REASON = wakeReason;
204
+ if (wakeCommentId)
205
+ env.PAPERCLIP_WAKE_COMMENT_ID = wakeCommentId;
206
+ if (approvalId)
207
+ env.PAPERCLIP_APPROVAL_ID = approvalId;
208
+ if (approvalStatus)
209
+ env.PAPERCLIP_APPROVAL_STATUS = approvalStatus;
210
+ if (linkedIssueIds.length > 0)
211
+ env.PAPERCLIP_LINKED_ISSUE_IDS = linkedIssueIds.join(",");
212
+ refreshPaperclipWorkspaceEnvForExecution({
213
+ env,
214
+ envConfig,
215
+ workspaceCwd: effectiveWorkspaceCwd,
216
+ workspaceSource,
217
+ workspaceId,
218
+ workspaceRepoUrl,
219
+ workspaceRepoRef,
220
+ workspaceHints,
221
+ agentHome,
222
+ executionTargetIsRemote,
223
+ executionCwd: effectiveExecutionCwd,
224
+ });
225
+ if (!hasExplicitApiKey && authToken) {
226
+ env.PAPERCLIP_API_KEY = authToken;
227
+ }
228
+ // Forward configured thinking effort as KIMI_MODEL_THINKING_EFFORT. Kimi has
229
+ // no per-invocation effort flag; this env var is an operational override that
230
+ // applies to Kimi providers (managed OAuth models included). Only send it for
231
+ // models that advertise support_efforts, and never clobber an explicit value.
232
+ const configuredEffort = asString(config.effort, "").trim();
233
+ if (configuredEffort && modelSupportsEffort(model) && !hasNonEmptyEnvValue(env, "KIMI_MODEL_THINKING_EFFORT")) {
234
+ const kimiEffort = resolveKimiThinkingEffort(configuredEffort);
235
+ if (kimiEffort)
236
+ env.KIMI_MODEL_THINKING_EFFORT = kimiEffort;
237
+ }
238
+ const runtimeEnv = buildKimiRuntimeEnv(env);
239
+ const billingType = resolveKimiBillingType(runtimeEnv);
240
+ const timeoutSec = resolveAdapterExecutionTargetTimeoutSec(executionTarget, asNumber(config.timeoutSec, 0));
241
+ const graceSec = asNumber(config.graceSec, 20);
242
+ await ensureAdapterExecutionTargetRuntimeCommandInstalled({
243
+ runId,
244
+ target: executionTarget,
245
+ installCommand: ctx.runtimeCommandSpec?.installCommand,
246
+ detectCommand: ctx.runtimeCommandSpec?.detectCommand,
247
+ cwd,
248
+ env: runtimeEnv,
249
+ timeoutSec,
250
+ graceSec,
251
+ onLog,
252
+ });
253
+ await ensureAdapterExecutionTargetCommandResolvable(command, executionTarget, cwd, runtimeEnv, {
254
+ installCommand: SANDBOX_INSTALL_COMMAND,
255
+ timeoutSec,
256
+ });
257
+ const resolvedCommand = await resolveAdapterExecutionTargetCommandForLogs(command, executionTarget, cwd, runtimeEnv);
258
+ const extraArgs = (() => {
259
+ const fromExtraArgs = asStringArray(config.extraArgs);
260
+ if (fromExtraArgs.length > 0)
261
+ return fromExtraArgs;
262
+ return asStringArray(config.args);
263
+ })();
264
+ let restoreRemoteWorkspace = null;
265
+ let localSkillsDir = null;
266
+ let remoteSkillsDir = null;
267
+ let remoteRuntimeRootDir = null;
268
+ let paperclipBridge = null;
269
+ try {
270
+ if (executionTargetIsRemote) {
271
+ try {
272
+ localSkillsDir = await buildKimiSkillsDir(config);
273
+ await onLog("stdout", `[paperclip] Syncing workspace and Kimi runtime assets to ${describeAdapterExecutionTarget(executionTarget)}.\n`);
274
+ const preparedExecutionTargetRuntime = await prepareAdapterExecutionTargetRuntime({
275
+ privateRuntime: Boolean(config.managedAiConnection),
276
+ runId,
277
+ target: executionTarget,
278
+ adapterKey: "kimi",
279
+ timeoutSec,
280
+ workspaceLocalDir: cwd,
281
+ installCommand: SANDBOX_INSTALL_COMMAND,
282
+ detectCommand: command,
283
+ onProgress: (line) => onLog("stdout", line),
284
+ onRuntimeProgress: ctx.onRuntimeProgress,
285
+ assets: [{
286
+ key: "skills",
287
+ localDir: localSkillsDir,
288
+ followSymlinks: true,
289
+ }],
290
+ });
291
+ restoreRemoteWorkspace = () => preparedExecutionTargetRuntime.restoreWorkspace((line) => onLog("stdout", line));
292
+ effectiveExecutionCwd = preparedExecutionTargetRuntime.workspaceRemoteDir ?? effectiveExecutionCwd;
293
+ refreshPaperclipWorkspaceEnvForExecution({
294
+ env,
295
+ envConfig,
296
+ workspaceCwd: effectiveWorkspaceCwd,
297
+ workspaceSource,
298
+ workspaceId,
299
+ workspaceRepoUrl,
300
+ workspaceRepoRef,
301
+ workspaceHints,
302
+ agentHome,
303
+ executionTargetIsRemote,
304
+ executionCwd: effectiveExecutionCwd,
305
+ });
306
+ remoteRuntimeRootDir = preparedExecutionTargetRuntime.runtimeRootDir;
307
+ if (executionTarget?.kind === "remote" && executionTarget.transport === "ssh" && executionTarget.spec.useHostAuth === false && config.managedAiConnection && remoteRuntimeRootDir)
308
+ Object.assign(env, managedRemoteHomeEnvironment(remoteRuntimeRootDir));
309
+ const managedHome = adapterExecutionTargetUsesManagedHome(executionTarget, Boolean(config.managedAiConnection));
310
+ const managedRemoteHomeDir = managedHome && preparedExecutionTargetRuntime.runtimeRootDir
311
+ ? preparedExecutionTargetRuntime.runtimeRootDir
312
+ : null;
313
+ if (managedRemoteHomeDir) {
314
+ env.HOME = managedRemoteHomeDir;
315
+ }
316
+ // Deliver the synced skills snapshot via --skills-dir (see buildArgs)
317
+ // from its isolated per-run location instead of copying it over the
318
+ // shared $KIMI_CODE_HOME/skills home. Overwriting the shared home would
319
+ // delete Kimi skills installed by the operator or other agents that
320
+ // Paperclip does not own.
321
+ if (desiredKimiSkillNames.length > 0 && preparedExecutionTargetRuntime.assetDirs.skills) {
322
+ remoteSkillsDir = preparedExecutionTargetRuntime.assetDirs.skills;
323
+ }
324
+ }
325
+ catch (error) {
326
+ await Promise.allSettled([
327
+ restoreRemoteWorkspace?.(),
328
+ localSkillsDir ? fs.rm(path.dirname(localSkillsDir), { recursive: true, force: true }).catch(() => undefined) : Promise.resolve(),
329
+ ]);
330
+ restoreRemoteWorkspace = null;
331
+ throw error;
332
+ }
333
+ }
334
+ const runtimeExecutionTarget = overrideAdapterExecutionTargetRemoteCwd(executionTarget, effectiveExecutionCwd);
335
+ if (executionTargetIsRemote && adapterExecutionTargetUsesPaperclipBridge(executionTarget)) {
336
+ paperclipBridge = await startAdapterExecutionTargetPaperclipBridge({
337
+ runId,
338
+ target: runtimeExecutionTarget,
339
+ runtimeRootDir: remoteRuntimeRootDir,
340
+ adapterKey: "kimi",
341
+ timeoutSec,
342
+ hostApiToken: env.PAPERCLIP_API_KEY,
343
+ onLog,
344
+ });
345
+ if (paperclipBridge) {
346
+ Object.assign(env, paperclipBridge.env);
347
+ }
348
+ }
349
+ // Local runs deliver desired skills via `--skills-dir` (see buildArgs) from a
350
+ // dedicated per-run directory, rather than symlinking into the user's
351
+ // ~/.kimi-code/skills home. This keeps skill loading reliable and isolated
352
+ // without polluting the operator's Kimi install. Remote runs sync skills into
353
+ // the remote skills home above, so this only applies to local execution.
354
+ if (!executionTargetIsRemote && desiredKimiSkillNames.length > 0) {
355
+ localSkillsDir = await buildKimiSkillsDir(config);
356
+ await onLog("stderr", `[paperclip] Prepared ${desiredKimiSkillNames.length} Kimi skill(s) for --skills-dir delivery.\n`);
357
+ }
358
+ const runtimeSessionParams = parseObject(runtime.sessionParams);
359
+ const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? "");
360
+ const runtimeSessionCwd = asString(runtimeSessionParams.cwd, "");
361
+ const runtimeRemoteExecution = parseObject(runtimeSessionParams.remoteExecution);
362
+ const canResumeSession = runtimeSessionId.length > 0 &&
363
+ (runtimeSessionCwd.length === 0 || path.resolve(runtimeSessionCwd) === path.resolve(effectiveExecutionCwd)) &&
364
+ adapterExecutionTargetSessionMatches(runtimeRemoteExecution, runtimeExecutionTarget);
365
+ const sessionId = canResumeSession ? runtimeSessionId : null;
366
+ if (executionTargetIsRemote && runtimeSessionId && !canResumeSession) {
367
+ await onLog("stdout", `[paperclip] Kimi session "${runtimeSessionId}" does not match the current remote execution identity and will not be resumed in "${effectiveExecutionCwd}". Starting a fresh remote session.\n`);
368
+ }
369
+ else if (runtimeSessionId && !canResumeSession) {
370
+ await onLog("stdout", `[paperclip] Kimi session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${effectiveExecutionCwd}".\n`);
371
+ }
372
+ const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
373
+ const instructionsDir = instructionsFilePath ? `${path.dirname(instructionsFilePath)}/` : "";
374
+ let instructionsPrefix = "";
375
+ if (instructionsFilePath) {
376
+ try {
377
+ const instructionsContents = await fs.readFile(instructionsFilePath, "utf8");
378
+ instructionsPrefix =
379
+ `${instructionsContents}\n\n` +
380
+ `The above agent instructions were loaded from ${instructionsFilePath}. ` +
381
+ `Resolve any relative file references from ${instructionsDir}. ` +
382
+ `This base directory is authoritative for sibling instruction files such as ` +
383
+ `./HEARTBEAT.md, ./SOUL.md, and ./TOOLS.md; do not resolve those from the parent agent directory.\n\n`;
384
+ }
385
+ catch (err) {
386
+ const reason = err instanceof Error ? err.message : String(err);
387
+ await onLog("stdout", `[paperclip] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason}\n`);
388
+ }
389
+ }
390
+ const commandNotes = (() => {
391
+ const notes = ["Prompt is passed to Kimi via -p for non-interactive execution."];
392
+ notes.push("Added --output-format stream-json for structured headless output.");
393
+ notes.push("Set headless env (CI=1, NO_COLOR=1, KIMI_CODE_NO_AUTO_UPDATE=1) so unattended runs skip interactive prompts and update preflight.");
394
+ if (hasNonEmptyEnvValue(env, "KIMI_MODEL_THINKING_EFFORT")) {
395
+ notes.push(`Set KIMI_MODEL_THINKING_EFFORT=${env.KIMI_MODEL_THINKING_EFFORT} for model ${model}.`);
396
+ }
397
+ const effectiveSkillsDir = executionTargetIsRemote ? remoteSkillsDir : localSkillsDir;
398
+ if (effectiveSkillsDir) {
399
+ notes.push(`Loading ${desiredKimiSkillNames.length} desired skill(s) via --skills-dir ${effectiveSkillsDir}.`);
400
+ }
401
+ if (!executionTargetIsRemote && instructionsFilePath) {
402
+ notes.push(`Added --add-dir ${path.dirname(instructionsFilePath)} so sibling instruction files are readable.`);
403
+ }
404
+ if (!instructionsFilePath)
405
+ return notes;
406
+ if (instructionsPrefix.length > 0) {
407
+ notes.push(`Loaded agent instructions from ${instructionsFilePath}`, `Prepended instructions + path directive to prompt (relative references from ${instructionsDir}).`);
408
+ return notes;
409
+ }
410
+ notes.push(`Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.`);
411
+ return notes;
412
+ })();
413
+ const bootstrapPromptTemplate = asString(config.bootstrapPromptTemplate, "");
414
+ const templateData = {
415
+ agentId: agent.id,
416
+ companyId: agent.companyId,
417
+ runId,
418
+ company: { id: agent.companyId },
419
+ agent,
420
+ run: { id: runId, source: "on_demand" },
421
+ context,
422
+ };
423
+ const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
424
+ const paperclipEnvNote = renderPaperclipEnvNote(env);
425
+ const apiAccessNote = renderApiAccessNote(env);
426
+ const buildArgs = (resumeSessionId, prompt) => {
427
+ const args = ["--output-format", "stream-json"];
428
+ if (resumeSessionId)
429
+ args.push("-r", resumeSessionId);
430
+ if (model)
431
+ args.push("-m", model);
432
+ // Make the agent instructions directory readable so Kimi can open sibling
433
+ // instruction files (./HEARTBEAT.md, ./SOUL.md, ./TOOLS.md) referenced by
434
+ // the prepended entry file. Local-only: the directory is a host path that
435
+ // is not synced to remote execution targets.
436
+ if (!executionTargetIsRemote && instructionsFilePath) {
437
+ args.push("--add-dir", path.dirname(instructionsFilePath));
438
+ }
439
+ // Load desired Paperclip skills from the dedicated per-run directory
440
+ // (local snapshot, or the synced remote snapshot) instead of the shared
441
+ // skills home. Only passed when skills are desired so unconfigured agents
442
+ // keep Kimi's default skill discovery.
443
+ const effectiveSkillsDir = executionTargetIsRemote ? remoteSkillsDir : localSkillsDir;
444
+ if (effectiveSkillsDir) {
445
+ args.push("--skills-dir", effectiveSkillsDir);
446
+ }
447
+ if (extraArgs.length > 0)
448
+ args.push(...extraArgs);
449
+ args.push("-p", prompt);
450
+ return args;
451
+ };
452
+ const runAttempt = async (resumeSessionId) => {
453
+ await hydrateFreshSessionHandoff(ctx, { resumedSession: Boolean(resumeSessionId) });
454
+ const attemptSections = selectPaperclipPromptSections(context, {
455
+ resumedSession: Boolean(resumeSessionId),
456
+ includeCommunicationGuidance: false,
457
+ });
458
+ const attemptBootstrapPrompt = !resumeSessionId && bootstrapPromptTemplate.trim().length > 0
459
+ ? renderTemplate(bootstrapPromptTemplate, templateData).trim()
460
+ : "";
461
+ const attemptWakePrompt = attemptSections.wakePrompt;
462
+ const attemptRenderedPrompt = Boolean(resumeSessionId) && attemptWakePrompt.length > 0
463
+ || isPaperclipRecoveryWakePayload(context.paperclipWake)
464
+ ? ""
465
+ : renderTemplate(promptTemplate, templateData);
466
+ const attemptBasePrompt = joinPromptSections([
467
+ instructionsPrefix,
468
+ attemptBootstrapPrompt,
469
+ attemptWakePrompt,
470
+ attemptSections.taskContextNote,
471
+ sessionHandoffNote,
472
+ paperclipEnvNote,
473
+ apiAccessNote,
474
+ attemptRenderedPrompt,
475
+ ]);
476
+ const prompt = joinPromptSections([
477
+ selectInitialCommunicationGuidance(context, { resumedSession: Boolean(resumeSessionId) }),
478
+ attemptBasePrompt,
479
+ ]);
480
+ const promptMetrics = {
481
+ promptChars: prompt.length,
482
+ instructionsChars: instructionsPrefix.length,
483
+ bootstrapPromptChars: attemptBootstrapPrompt.length,
484
+ wakePromptChars: attemptWakePrompt.length,
485
+ taskContextChars: attemptSections.taskContextNote.length,
486
+ sessionHandoffChars: sessionHandoffNote.length,
487
+ runtimeNoteChars: paperclipEnvNote.length + apiAccessNote.length,
488
+ heartbeatPromptChars: attemptRenderedPrompt.length,
489
+ };
490
+ const args = buildArgs(resumeSessionId, prompt);
491
+ const invocationEnv = buildKimiHeadlessEnv(env);
492
+ const invocationRuntimeEnv = buildKimiRuntimeEnv(env);
493
+ const loggedEnv = buildInvocationEnvForLogs(invocationEnv, {
494
+ runtimeEnv: invocationRuntimeEnv,
495
+ includeRuntimeKeys: ["HOME"],
496
+ resolvedCommand,
497
+ });
498
+ if (onMeta) {
499
+ await onMeta({
500
+ adapterType: "kimi_local",
501
+ command: resolvedCommand,
502
+ cwd: effectiveExecutionCwd,
503
+ commandNotes,
504
+ commandArgs: args.map((value, index) => (index === args.length - 1 ? `<prompt ${prompt.length} chars>` : value)),
505
+ env: loggedEnv,
506
+ prompt,
507
+ promptMetrics: { ...promptMetrics, promptChars: prompt.length },
508
+ context,
509
+ });
510
+ }
511
+ const eventForwarder = createKimiEventForwardingLog(onLog, onEvent);
512
+ const proc = await runAdapterExecutionTargetProcess(runId, runtimeExecutionTarget, command, args, {
513
+ onProcessStopped: providerStop.beginInvocation(),
514
+ cwd,
515
+ env: invocationEnv,
516
+ timeoutSec,
517
+ graceSec,
518
+ onSpawn,
519
+ onRuntimeProgress: ctx.onRuntimeProgress,
520
+ onLog: eventForwarder.log,
521
+ runLogTail: paperclipBridge?.runLogTail,
522
+ settleRunDisposition: paperclipBridge?.settleRunDisposition,
523
+ });
524
+ await eventForwarder.flush();
525
+ return {
526
+ proc,
527
+ parsed: parseKimiJsonl(proc.stdout),
528
+ };
529
+ };
530
+ const toResult = (attempt, clearSessionOnMissingSession = false, isRetry = false) => {
531
+ const authMeta = detectKimiAuthRequired({
532
+ stdout: attempt.proc.stdout,
533
+ stderr: attempt.proc.stderr,
534
+ });
535
+ const networkUnavailable = isKimiTransientNetworkError(attempt.proc.stdout, attempt.proc.stderr);
536
+ if (attempt.proc.timedOut) {
537
+ return {
538
+ exitCode: attempt.proc.exitCode,
539
+ signal: attempt.proc.signal,
540
+ timedOut: true,
541
+ // This stream protocol has no usage receipt to recover after exit.
542
+ // Close collection with an explicitly unknown price, never a free run.
543
+ usageComplete: true,
544
+ costStatus: "unpriced",
545
+ usageBasis: "per_run",
546
+ provider: "moonshot",
547
+ biller: "moonshot",
548
+ model: model || null,
549
+ billingType,
550
+ costUsd: null,
551
+ errorMessage: `Timed out after ${timeoutSec}s`,
552
+ errorCode: authMeta.requiresAuth
553
+ ? "kimi_auth_required"
554
+ : networkUnavailable
555
+ ? "kimi_network_unavailable"
556
+ : null,
557
+ clearSession: clearSessionOnMissingSession,
558
+ };
559
+ }
560
+ const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : "";
561
+ const stderrLine = firstNonEmptyLine(attempt.proc.stderr);
562
+ const structuredFailure = describeKimiFailure({
563
+ errorMessage: attempt.parsed.errorMessage,
564
+ stderr: attempt.proc.stderr,
565
+ });
566
+ const fallbackErrorMessage = parsedError ||
567
+ structuredFailure ||
568
+ stderrLine ||
569
+ (attempt.proc.signal
570
+ ? `Kimi was terminated by signal ${attempt.proc.signal}`
571
+ : `Kimi exited with code ${attempt.proc.exitCode ?? -1}`);
572
+ // A null exit code means the process never exited normally (e.g. killed by
573
+ // a signal). Timeouts are handled earlier; treat any other non-zero or
574
+ // null exit as a failure so a signaled kill is never reported as success.
575
+ const failed = attempt.proc.exitCode === null || attempt.proc.exitCode !== 0;
576
+ // On retry, don't fall back to old session ID — the old session was stale
577
+ const canFallbackToRuntimeSession = !isRetry;
578
+ const resolvedSessionId = attempt.parsed.sessionId
579
+ ?? (canFallbackToRuntimeSession ? (runtimeSessionId ?? runtime.sessionId ?? null) : null);
580
+ const resolvedSessionParams = resolvedSessionId
581
+ ? {
582
+ sessionId: resolvedSessionId,
583
+ cwd: effectiveExecutionCwd,
584
+ ...(workspaceId ? { workspaceId } : {}),
585
+ ...(workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}),
586
+ ...(workspaceRepoRef ? { repoRef: workspaceRepoRef } : {}),
587
+ ...(executionTargetIsRemote
588
+ ? {
589
+ remoteExecution: adapterExecutionTargetSessionIdentity(runtimeExecutionTarget),
590
+ }
591
+ : {}),
592
+ }
593
+ : null;
594
+ const resultJson = {
595
+ toolCalls: attempt.parsed.toolCalls,
596
+ toolResults: attempt.parsed.toolResults,
597
+ ...(failed ? { stderr: attempt.proc.stderr } : {}),
598
+ };
599
+ return {
600
+ exitCode: attempt.proc.exitCode,
601
+ signal: attempt.proc.signal,
602
+ timedOut: false,
603
+ usageComplete: true,
604
+ costStatus: "unpriced",
605
+ usageBasis: "per_run",
606
+ errorMessage: failed ? fallbackErrorMessage : null,
607
+ // Forward the transport-level error code from the run-disposition seam
608
+ // first. A lost duplex control channel surfaces the typed
609
+ // `duplex_channel_lost` code before any provider classification.
610
+ errorCode: attempt.proc.errorCode
611
+ ? attempt.proc.errorCode
612
+ : failed && authMeta.requiresAuth
613
+ ? "kimi_auth_required"
614
+ : failed && networkUnavailable
615
+ ? "kimi_network_unavailable"
616
+ : null,
617
+ sessionId: resolvedSessionId,
618
+ sessionParams: resolvedSessionParams,
619
+ sessionDisplayId: resolvedSessionId,
620
+ provider: "moonshot",
621
+ biller: "moonshot",
622
+ model: model || null,
623
+ billingType,
624
+ resultJson,
625
+ summary: attempt.parsed.summary,
626
+ clearSession: Boolean(clearSessionOnMissingSession && !resolvedSessionId),
627
+ };
628
+ };
629
+ const initial = await runAttempt(sessionId);
630
+ if (sessionId &&
631
+ !initial.proc.timedOut &&
632
+ (initial.proc.exitCode ?? 0) !== 0 &&
633
+ isKimiSessionUnrecoverableError(initial.proc.stdout, initial.proc.stderr)) {
634
+ await onLog("stdout", `[paperclip] Kimi resume session "${sessionId}" is unavailable; retrying with a fresh session.\n`);
635
+ const retry = await runAttempt(null);
636
+ return toResult(retry, true, true);
637
+ }
638
+ return toResult(initial);
639
+ }
640
+ finally {
641
+ try {
642
+ await providerStop.collectBeforeRestore();
643
+ }
644
+ finally {
645
+ await Promise.all([
646
+ paperclipBridge?.stop(),
647
+ restoreRemoteWorkspace?.(),
648
+ localSkillsDir ? fs.rm(path.dirname(localSkillsDir), { recursive: true, force: true }).catch(() => undefined) : Promise.resolve(),
649
+ ]);
650
+ }
651
+ }
652
+ }
653
+ //# sourceMappingURL=execute.js.map