@microvac/adapter-pi-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 +99 -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 +9 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +54 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/server/execute.d.ts +3 -0
  15. package/dist/server/execute.d.ts.map +1 -0
  16. package/dist/server/execute.js +784 -0
  17. package/dist/server/execute.js.map +1 -0
  18. package/dist/server/execute.remote.test.d.ts +2 -0
  19. package/dist/server/execute.remote.test.d.ts.map +1 -0
  20. package/dist/server/execute.remote.test.js +814 -0
  21. package/dist/server/execute.remote.test.js.map +1 -0
  22. package/dist/server/index.d.ts +8 -0
  23. package/dist/server/index.d.ts.map +1 -0
  24. package/dist/server/index.js +56 -0
  25. package/dist/server/index.js.map +1 -0
  26. package/dist/server/models.d.ts +20 -0
  27. package/dist/server/models.d.ts.map +1 -0
  28. package/dist/server/models.js +162 -0
  29. package/dist/server/models.js.map +1 -0
  30. package/dist/server/models.test.d.ts +2 -0
  31. package/dist/server/models.test.d.ts.map +1 -0
  32. package/dist/server/models.test.js +48 -0
  33. package/dist/server/models.test.js.map +1 -0
  34. package/dist/server/openrouter-extension.d.ts +7 -0
  35. package/dist/server/openrouter-extension.d.ts.map +1 -0
  36. package/dist/server/openrouter-extension.js +66 -0
  37. package/dist/server/openrouter-extension.js.map +1 -0
  38. package/dist/server/openrouter-extension.test.d.ts +2 -0
  39. package/dist/server/openrouter-extension.test.d.ts.map +1 -0
  40. package/dist/server/openrouter-extension.test.js +74 -0
  41. package/dist/server/openrouter-extension.test.js.map +1 -0
  42. package/dist/server/parse.d.ts +43 -0
  43. package/dist/server/parse.d.ts.map +1 -0
  44. package/dist/server/parse.js +220 -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 +272 -0
  49. package/dist/server/parse.test.js.map +1 -0
  50. package/dist/server/runtime-config.d.ts +12 -0
  51. package/dist/server/runtime-config.d.ts.map +1 -0
  52. package/dist/server/runtime-config.js +142 -0
  53. package/dist/server/runtime-config.js.map +1 -0
  54. package/dist/server/runtime-config.test.d.ts +2 -0
  55. package/dist/server/runtime-config.test.d.ts.map +1 -0
  56. package/dist/server/runtime-config.test.js +216 -0
  57. package/dist/server/runtime-config.test.js.map +1 -0
  58. package/dist/server/skills.d.ts +7 -0
  59. package/dist/server/skills.d.ts.map +1 -0
  60. package/dist/server/skills.js +69 -0
  61. package/dist/server/skills.js.map +1 -0
  62. package/dist/server/stdout-compaction.d.ts +27 -0
  63. package/dist/server/stdout-compaction.d.ts.map +1 -0
  64. package/dist/server/stdout-compaction.js +107 -0
  65. package/dist/server/stdout-compaction.js.map +1 -0
  66. package/dist/server/stdout-compaction.test.d.ts +2 -0
  67. package/dist/server/stdout-compaction.test.d.ts.map +1 -0
  68. package/dist/server/stdout-compaction.test.js +333 -0
  69. package/dist/server/stdout-compaction.test.js.map +1 -0
  70. package/dist/server/test.d.ts +3 -0
  71. package/dist/server/test.d.ts.map +1 -0
  72. package/dist/server/test.js +311 -0
  73. package/dist/server/test.js.map +1 -0
  74. package/dist/ui/build-config.d.ts +3 -0
  75. package/dist/ui/build-config.d.ts.map +1 -0
  76. package/dist/ui/build-config.js +39 -0
  77. package/dist/ui/build-config.js.map +1 -0
  78. package/dist/ui/index.d.ts +3 -0
  79. package/dist/ui/index.d.ts.map +1 -0
  80. package/dist/ui/index.js +3 -0
  81. package/dist/ui/index.js.map +1 -0
  82. package/dist/ui/parse-stdout.d.ts +4 -0
  83. package/dist/ui/parse-stdout.d.ts.map +1 -0
  84. package/dist/ui/parse-stdout.js +276 -0
  85. package/dist/ui/parse-stdout.js.map +1 -0
  86. package/package.json +51 -4
  87. package/README.md +0 -3
@@ -0,0 +1,784 @@
1
+ import { createProviderStoppedBoundary } from "@paperclipai/adapter-utils/provider-stopped-boundary";
2
+ import { createUsageCheckpointLog } from "@paperclipai/adapter-utils/usage-checkpoint";
3
+ import fs from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { inferOpenAiCompatibleBiller } from "@paperclipai/adapter-utils";
8
+ import { managedRemoteHomeEnvironment, adapterExecutionTargetIsRemote, adapterExecutionTargetRemoteCwd, overrideAdapterExecutionTargetRemoteCwd, adapterExecutionTargetSessionIdentity, adapterExecutionTargetSessionMatches, adapterExecutionTargetUsesManagedHome, adapterExecutionTargetUsesPaperclipBridge, describeAdapterExecutionTarget, ensureAdapterExecutionTargetCommandResolvable, ensureAdapterExecutionTargetLocalWorkspace, ensureAdapterExecutionTargetFile, ensureAdapterExecutionTargetRuntimeCommandInstalled, prepareAdapterExecutionTargetRuntime, adapterExecutionTargetDuplexObservabilityRecorder, adapterExecutionTargetEnablesSandboxDuplexBridge, readAdapterExecutionTarget, resolveAdapterExecutionTargetTimeoutSec, resolveAdapterExecutionTargetCommandForLogs, runAdapterExecutionTargetProcess, runAdapterExecutionTargetShellCommand, startAdapterExecutionTargetPaperclipBridge, } from "@paperclipai/adapter-utils/execution-target";
9
+ import { asString, asNumber, asStringArray, parseObject, buildPaperclipEnv, buildRuntimeToolsEnv, joinPromptSections, buildInvocationEnvForLogs, ensurePaperclipSkillSymlink, ensurePathInEnv, refreshPaperclipWorkspaceEnvForExecution, isPaperclipSkillSourceMissing, readPaperclipRuntimeSkillEntries, readPaperclipIssueWorkModeFromContext, resolveLegacyPaperclipDesiredSkillNames, removeMaintainerOnlySkillSymlinks, renderTemplate, hydrateFreshSessionHandoff, selectPaperclipPromptSections, selectInitialCommunicationGuidance, isPaperclipRecoveryWakePayload, DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE, DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE, sanitizeInheritedPaperclipEnv, } from "@paperclipai/adapter-utils/server-utils";
10
+ import { shellQuote } from "@paperclipai/adapter-utils/ssh";
11
+ import { isPiUnknownSessionError, parsePiJsonl, createPiJsonlParser } from "./parse.js";
12
+ import { createPiStdoutCompactor, resolvePiStdoutLogMode } from "./stdout-compaction.js";
13
+ import { ensurePiModelConfiguredAndAvailable } from "./models.js";
14
+ import { preparePiRuntimeConfig } from "./runtime-config.js";
15
+ import { preparePiOpenRouterExtension } from "./openrouter-extension.js";
16
+ import { SANDBOX_INSTALL_COMMAND } from "../index.js";
17
+ const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
18
+ const PAPERCLIP_SESSIONS_DIR = path.join(os.homedir(), ".pi", "paperclips");
19
+ const PI_AGENT_SKILLS_DIR = path.join(os.homedir(), ".pi", "agent", "skills");
20
+ function firstNonEmptyLine(text) {
21
+ return (text
22
+ .split(/\r?\n/)
23
+ .map((line) => line.trim())
24
+ .find(Boolean) ?? "");
25
+ }
26
+ function parseModelProvider(model) {
27
+ if (!model)
28
+ return null;
29
+ const trimmed = model.trim();
30
+ if (!trimmed.includes("/"))
31
+ return null;
32
+ return trimmed.slice(0, trimmed.indexOf("/")).trim() || null;
33
+ }
34
+ function parseModelId(model) {
35
+ if (!model)
36
+ return null;
37
+ const trimmed = model.trim();
38
+ if (!trimmed.includes("/"))
39
+ return trimmed || null;
40
+ return trimmed.slice(trimmed.indexOf("/") + 1).trim() || null;
41
+ }
42
+ async function ensurePiSkillsInjected(onLog, skillsEntries, desiredSkillNames) {
43
+ const desiredSet = new Set(desiredSkillNames ?? skillsEntries.map((entry) => entry.key));
44
+ const selectedEntries = skillsEntries.filter((entry) => desiredSet.has(entry.key));
45
+ if (selectedEntries.length === 0)
46
+ return;
47
+ await fs.mkdir(PI_AGENT_SKILLS_DIR, { recursive: true });
48
+ const removedSkills = await removeMaintainerOnlySkillSymlinks(PI_AGENT_SKILLS_DIR, selectedEntries.map((entry) => entry.runtimeName));
49
+ for (const skillName of removedSkills) {
50
+ await onLog("stderr", `[paperclip] Removed maintainer-only Pi skill "${skillName}" from ${PI_AGENT_SKILLS_DIR}\n`);
51
+ }
52
+ for (const entry of selectedEntries) {
53
+ const target = path.join(PI_AGENT_SKILLS_DIR, entry.runtimeName);
54
+ try {
55
+ const result = await ensurePaperclipSkillSymlink(entry.source, target);
56
+ if (result === "skipped")
57
+ continue;
58
+ await onLog("stderr", `[paperclip] ${result === "repaired" ? "Repaired" : "Injected"} Pi skill "${entry.runtimeName}" into ${PI_AGENT_SKILLS_DIR}\n`);
59
+ }
60
+ catch (err) {
61
+ await onLog("stderr", `[paperclip] Failed to inject Pi skill "${entry.runtimeName}" into ${PI_AGENT_SKILLS_DIR}: ${err instanceof Error ? err.message : String(err)}\n`);
62
+ }
63
+ }
64
+ }
65
+ async function buildPiSkillsDir(config) {
66
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-pi-skills-"));
67
+ const target = path.join(tmp, "skills");
68
+ await fs.mkdir(target, { recursive: true });
69
+ const availableEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
70
+ const desiredNames = new Set(resolveLegacyPaperclipDesiredSkillNames(config, availableEntries));
71
+ for (const entry of availableEntries) {
72
+ if (!desiredNames.has(entry.key))
73
+ continue;
74
+ if (isPaperclipSkillSourceMissing(entry))
75
+ continue;
76
+ await fs.symlink(entry.source, path.join(target, entry.runtimeName));
77
+ }
78
+ return target;
79
+ }
80
+ function resolvePiBiller(env, provider) {
81
+ return provider === "openai" ? inferOpenAiCompatibleBiller(env, "openai") ?? "unknown" : provider ?? "unknown";
82
+ }
83
+ async function ensureSessionsDir() {
84
+ await fs.mkdir(PAPERCLIP_SESSIONS_DIR, { recursive: true });
85
+ return PAPERCLIP_SESSIONS_DIR;
86
+ }
87
+ function buildSessionPath(agentId, timestamp) {
88
+ const safeTimestamp = timestamp.replace(/[:.]/g, "-");
89
+ return path.join(PAPERCLIP_SESSIONS_DIR, `${safeTimestamp}-${agentId}.jsonl`);
90
+ }
91
+ function buildRemoteSessionPath(sessionRootDir, agentId, timestamp) {
92
+ const safeTimestamp = timestamp.replace(/[:.]/g, "-");
93
+ return path.posix.join(sessionRootDir, "sessions", `${safeTimestamp}-${agentId}.jsonl`);
94
+ }
95
+ function normalizeExecutionCwd(candidate, remote) {
96
+ return remote ? path.posix.normalize(candidate) : path.resolve(candidate);
97
+ }
98
+ function executionCwdsMatch(saved, current, remote) {
99
+ return normalizeExecutionCwd(saved, remote) === normalizeExecutionCwd(current, remote);
100
+ }
101
+ function readSessionHeaderCwd(raw) {
102
+ const headerLine = raw
103
+ .split(/\r?\n/)
104
+ .map((line) => line.trim())
105
+ .find(Boolean);
106
+ if (!headerLine)
107
+ return null;
108
+ try {
109
+ const parsed = JSON.parse(headerLine);
110
+ if (parsed.type !== "session")
111
+ return null;
112
+ const cwd = typeof parsed.cwd === "string" ? parsed.cwd.trim() : "";
113
+ return cwd.length > 0 ? cwd : null;
114
+ }
115
+ catch {
116
+ return null;
117
+ }
118
+ }
119
+ async function readSavedSessionCwd(input) {
120
+ if (!input.sessionPath.trim())
121
+ return null;
122
+ if (!adapterExecutionTargetIsRemote(input.executionTarget)) {
123
+ try {
124
+ return readSessionHeaderCwd(await fs.readFile(input.sessionPath, "utf8"));
125
+ }
126
+ catch {
127
+ return null;
128
+ }
129
+ }
130
+ try {
131
+ const sessionHeader = await runAdapterExecutionTargetShellCommand(input.runId, input.executionTarget, `if [ -f ${shellQuote(input.sessionPath)} ]; then head -n 1 ${shellQuote(input.sessionPath)}; fi`, {
132
+ cwd: input.cwd,
133
+ env: input.env,
134
+ timeoutSec: input.timeoutSec > 0 ? Math.min(input.timeoutSec, 15) : 15,
135
+ graceSec: input.graceSec,
136
+ });
137
+ if (sessionHeader.timedOut || (sessionHeader.exitCode ?? 0) !== 0)
138
+ return null;
139
+ return readSessionHeaderCwd(sessionHeader.stdout);
140
+ }
141
+ catch {
142
+ return null;
143
+ }
144
+ }
145
+ export async function execute(ctx) {
146
+ const providerStop = createProviderStoppedBoundary(ctx.onProviderStopped);
147
+ const { runId, agent, runtime, config, context, onLog, onMeta, onSpawn, authToken } = ctx;
148
+ const executionTarget = readAdapterExecutionTarget({
149
+ executionTarget: ctx.executionTarget,
150
+ legacyRemoteExecution: ctx.executionTransport?.remoteExecution,
151
+ });
152
+ const executionTargetIsRemote = adapterExecutionTargetIsRemote(executionTarget);
153
+ const promptTemplate = asString(config.promptTemplate, context.conversationMode === true
154
+ ? DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE
155
+ : DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE);
156
+ const hasCustomPromptTemplate = asString(config.promptTemplate, "").trim().length > 0;
157
+ const command = asString(config.command, "pi");
158
+ const model = asString(config.model, "").trim();
159
+ const thinking = asString(config.thinking, "").trim();
160
+ const stdoutLogMode = resolvePiStdoutLogMode(config);
161
+ // Parse model into provider and model id
162
+ const provider = parseModelProvider(model);
163
+ const modelId = parseModelId(model);
164
+ const workspaceContext = parseObject(context.paperclipWorkspace);
165
+ const workspaceCwd = asString(workspaceContext.cwd, "");
166
+ const workspaceSource = asString(workspaceContext.source, "");
167
+ const workspaceId = asString(workspaceContext.workspaceId, "");
168
+ const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
169
+ const workspaceRepoRef = asString(workspaceContext.repoRef, "");
170
+ const agentHome = asString(workspaceContext.agentHome, "");
171
+ const workspaceHints = Array.isArray(context.paperclipWorkspaces)
172
+ ? context.paperclipWorkspaces.filter((value) => typeof value === "object" && value !== null)
173
+ : [];
174
+ const configuredCwd = asString(config.cwd, "");
175
+ const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0;
176
+ const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd;
177
+ const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd();
178
+ let effectiveExecutionCwd = adapterExecutionTargetRemoteCwd(executionTarget, cwd);
179
+ await ensureAdapterExecutionTargetLocalWorkspace(executionTarget, cwd);
180
+ if (!executionTargetIsRemote) {
181
+ await ensureSessionsDir();
182
+ }
183
+ const piSkillEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
184
+ const desiredPiSkillNames = resolveLegacyPaperclipDesiredSkillNames(config, piSkillEntries);
185
+ if (!executionTargetIsRemote) {
186
+ await ensurePiSkillsInjected(onLog, piSkillEntries, desiredPiSkillNames);
187
+ }
188
+ // Build environment
189
+ const envConfig = parseObject(config.env);
190
+ const env = {
191
+ ...buildPaperclipEnv(agent, ctx.agentIdentity),
192
+ ...buildRuntimeToolsEnv(ctx.runtimeTools),
193
+ };
194
+ env.PAPERCLIP_RUN_ID = runId;
195
+ const wakeTaskId = (typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim()) ||
196
+ (typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim()) ||
197
+ null;
198
+ const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0
199
+ ? context.wakeReason.trim()
200
+ : null;
201
+ const wakeCommentId = (typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim()) ||
202
+ (typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim()) ||
203
+ null;
204
+ const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0
205
+ ? context.approvalId.trim()
206
+ : null;
207
+ const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0
208
+ ? context.approvalStatus.trim()
209
+ : null;
210
+ const linkedIssueIds = Array.isArray(context.issueIds)
211
+ ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0)
212
+ : [];
213
+ const issueWorkMode = readPaperclipIssueWorkModeFromContext(context);
214
+ if (wakeTaskId)
215
+ env.PAPERCLIP_TASK_ID = wakeTaskId;
216
+ if (issueWorkMode)
217
+ env.PAPERCLIP_ISSUE_WORK_MODE = issueWorkMode;
218
+ if (wakeReason)
219
+ env.PAPERCLIP_WAKE_REASON = wakeReason;
220
+ if (wakeCommentId)
221
+ env.PAPERCLIP_WAKE_COMMENT_ID = wakeCommentId;
222
+ if (approvalId)
223
+ env.PAPERCLIP_APPROVAL_ID = approvalId;
224
+ if (approvalStatus)
225
+ env.PAPERCLIP_APPROVAL_STATUS = approvalStatus;
226
+ if (linkedIssueIds.length > 0)
227
+ env.PAPERCLIP_LINKED_ISSUE_IDS = linkedIssueIds.join(",");
228
+ refreshPaperclipWorkspaceEnvForExecution({
229
+ env,
230
+ envConfig,
231
+ workspaceCwd: effectiveWorkspaceCwd,
232
+ workspaceSource,
233
+ workspaceId,
234
+ workspaceRepoUrl,
235
+ workspaceRepoRef,
236
+ workspaceHints,
237
+ agentHome,
238
+ executionTargetIsRemote,
239
+ executionCwd: effectiveExecutionCwd,
240
+ });
241
+ if (authToken) {
242
+ env.PAPERCLIP_API_KEY = authToken;
243
+ }
244
+ // Materialize custom Pi providers (PAPERCLIP_PI_PROVIDERS) into a managed
245
+ // PI_CODING_AGENT_DIR before runtimeEnv is computed, so both local validation
246
+ // and the spawned Pi process resolve models against the managed models.json.
247
+ const preparedRuntimeConfig = await preparePiRuntimeConfig({ env });
248
+ const localAgentConfigDir = preparedRuntimeConfig.agentConfigDir ?? "";
249
+ if (localAgentConfigDir) {
250
+ env.PI_CODING_AGENT_DIR = localAgentConfigDir;
251
+ }
252
+ let attributionExtension;
253
+ try {
254
+ attributionExtension = await preparePiOpenRouterExtension();
255
+ let attributionExtensionPath = attributionExtension.extensionPath;
256
+ // Prepend installed skill `bin/` dirs to PATH so an agent's bash tool can
257
+ // invoke skill binaries (e.g. `paperclip-get-issue`) by name. Without this,
258
+ // any pi_local agent whose AGENTS.md calls a skill command via bash hits
259
+ // exit 127 "command not found". Only include skills that ensurePiSkillsInjected
260
+ // actually linked — otherwise non-injected skills' binaries would be reachable
261
+ // to the agent.
262
+ const injectedSkillKeys = new Set(desiredPiSkillNames);
263
+ const skillBinDirs = piSkillEntries
264
+ .filter((entry) => injectedSkillKeys.has(entry.key) && entry.source.length > 0)
265
+ .map((entry) => path.join(entry.source, "bin"));
266
+ const mergedEnv = ensurePathInEnv({ ...sanitizeInheritedPaperclipEnv(process.env), ...env });
267
+ const pathKey = typeof mergedEnv.Path === "string" && mergedEnv.Path.length > 0 && !mergedEnv.PATH
268
+ ? "Path"
269
+ : "PATH";
270
+ const basePath = mergedEnv[pathKey] ?? "";
271
+ if (skillBinDirs.length > 0) {
272
+ const existing = basePath.split(path.delimiter).filter(Boolean);
273
+ const additions = skillBinDirs.filter((dir) => !existing.includes(dir));
274
+ if (additions.length > 0) {
275
+ mergedEnv[pathKey] = [...additions, basePath].filter(Boolean).join(path.delimiter);
276
+ }
277
+ }
278
+ const runtimeEnv = Object.fromEntries(Object.entries(mergedEnv).filter((entry) => typeof entry[1] === "string"));
279
+ const timeoutSec = resolveAdapterExecutionTargetTimeoutSec(executionTarget, asNumber(config.timeoutSec, 0));
280
+ const graceSec = asNumber(config.graceSec, 20);
281
+ await ensureAdapterExecutionTargetRuntimeCommandInstalled({
282
+ runId,
283
+ target: executionTarget,
284
+ installCommand: ctx.runtimeCommandSpec?.installCommand,
285
+ detectCommand: ctx.runtimeCommandSpec?.detectCommand,
286
+ cwd,
287
+ env: runtimeEnv,
288
+ timeoutSec,
289
+ graceSec,
290
+ onLog,
291
+ });
292
+ await ensureAdapterExecutionTargetCommandResolvable(command, executionTarget, cwd, runtimeEnv, {
293
+ installCommand: SANDBOX_INSTALL_COMMAND,
294
+ timeoutSec,
295
+ });
296
+ const resolvedCommand = await resolveAdapterExecutionTargetCommandForLogs(command, executionTarget, cwd, runtimeEnv);
297
+ let loggedEnv = buildInvocationEnvForLogs(env, {
298
+ runtimeEnv,
299
+ includeRuntimeKeys: ["HOME"],
300
+ resolvedCommand,
301
+ });
302
+ if (!executionTargetIsRemote) {
303
+ await ensurePiModelConfiguredAndAvailable({
304
+ model,
305
+ command,
306
+ cwd,
307
+ env: runtimeEnv,
308
+ });
309
+ }
310
+ const extraArgs = (() => {
311
+ const fromExtraArgs = asStringArray(config.extraArgs);
312
+ if (fromExtraArgs.length > 0)
313
+ return fromExtraArgs;
314
+ return asStringArray(config.args);
315
+ })();
316
+ let restoreRemoteWorkspace = null;
317
+ let remoteRuntimeRootDir = null;
318
+ let localSkillsDir = null;
319
+ let remoteSkillsDir = null;
320
+ let paperclipBridge = null;
321
+ try {
322
+ if (executionTargetIsRemote) {
323
+ try {
324
+ localSkillsDir = await buildPiSkillsDir(config);
325
+ await onLog("stdout", `[paperclip] Syncing workspace and Pi runtime assets to ${describeAdapterExecutionTarget(executionTarget)}.\n`);
326
+ const preparedRemoteRuntime = await prepareAdapterExecutionTargetRuntime({
327
+ privateRuntime: Boolean(config.managedAiConnection),
328
+ runId,
329
+ target: executionTarget,
330
+ adapterKey: "pi",
331
+ timeoutSec,
332
+ workspaceLocalDir: cwd,
333
+ installCommand: SANDBOX_INSTALL_COMMAND,
334
+ detectCommand: command,
335
+ onProgress: (line) => onLog("stdout", line),
336
+ onRuntimeProgress: ctx.onRuntimeProgress,
337
+ assets: [
338
+ {
339
+ key: "attribution",
340
+ localDir: attributionExtension.directory,
341
+ },
342
+ {
343
+ key: "skills",
344
+ localDir: localSkillsDir,
345
+ followSymlinks: true,
346
+ },
347
+ ...(localAgentConfigDir
348
+ ? [{
349
+ key: "agentConfig",
350
+ localDir: localAgentConfigDir,
351
+ }]
352
+ : []),
353
+ ],
354
+ });
355
+ restoreRemoteWorkspace = () => preparedRemoteRuntime.restoreWorkspace((line) => onLog("stdout", line));
356
+ effectiveExecutionCwd = preparedRemoteRuntime.workspaceRemoteDir ?? effectiveExecutionCwd;
357
+ refreshPaperclipWorkspaceEnvForExecution({
358
+ env,
359
+ envConfig,
360
+ workspaceCwd: effectiveWorkspaceCwd,
361
+ workspaceSource,
362
+ workspaceId,
363
+ workspaceRepoUrl,
364
+ workspaceRepoRef,
365
+ workspaceHints,
366
+ agentHome,
367
+ executionTargetIsRemote,
368
+ executionCwd: effectiveExecutionCwd,
369
+ });
370
+ if (executionTarget?.kind === "remote" && executionTarget.transport === "ssh" && executionTarget.spec.useHostAuth === false && config.managedAiConnection && preparedRemoteRuntime.runtimeRootDir)
371
+ Object.assign(env, managedRemoteHomeEnvironment(preparedRemoteRuntime.runtimeRootDir));
372
+ if (adapterExecutionTargetUsesManagedHome(executionTarget, Boolean(config.managedAiConnection)) && preparedRemoteRuntime.runtimeRootDir) {
373
+ env.HOME = preparedRemoteRuntime.runtimeRootDir;
374
+ }
375
+ remoteRuntimeRootDir = preparedRemoteRuntime.runtimeRootDir;
376
+ remoteSkillsDir = preparedRemoteRuntime.assetDirs.skills ?? null;
377
+ const remoteAttributionDir = preparedRemoteRuntime.assetDirs.attribution;
378
+ if (!remoteAttributionDir)
379
+ throw new Error("Pi attribution extension was not staged to the execution target.");
380
+ attributionExtensionPath = path.posix.join(remoteAttributionDir, "openrouter-attribution.mjs");
381
+ if (localAgentConfigDir && preparedRemoteRuntime.assetDirs.agentConfig) {
382
+ env.PI_CODING_AGENT_DIR = preparedRemoteRuntime.assetDirs.agentConfig;
383
+ }
384
+ }
385
+ catch (error) {
386
+ await Promise.allSettled([
387
+ restoreRemoteWorkspace?.(),
388
+ localSkillsDir ? fs.rm(path.dirname(localSkillsDir), { recursive: true, force: true }).catch(() => undefined) : Promise.resolve(),
389
+ ]);
390
+ restoreRemoteWorkspace = null;
391
+ throw error;
392
+ }
393
+ }
394
+ const runtimeExecutionTarget = overrideAdapterExecutionTargetRemoteCwd(executionTarget, effectiveExecutionCwd);
395
+ const remoteSessionRootDir = executionTarget?.kind === "remote" && executionTarget.transport === "ssh"
396
+ && executionTarget.workspaceRealization?.mode === "in_place"
397
+ ? path.posix.join(effectiveExecutionCwd, ".paperclip", "pi") : remoteRuntimeRootDir;
398
+ if (executionTargetIsRemote && adapterExecutionTargetUsesPaperclipBridge(runtimeExecutionTarget)) {
399
+ paperclipBridge = await startAdapterExecutionTargetPaperclipBridge({
400
+ runId,
401
+ target: runtimeExecutionTarget,
402
+ enableSandboxDuplexBridge: adapterExecutionTargetEnablesSandboxDuplexBridge(runtimeExecutionTarget),
403
+ duplexObservabilityRecorder: adapterExecutionTargetDuplexObservabilityRecorder(runtimeExecutionTarget),
404
+ runtimeRootDir: remoteRuntimeRootDir,
405
+ adapterKey: "pi",
406
+ timeoutSec,
407
+ hostApiToken: env.PAPERCLIP_API_KEY,
408
+ onLog,
409
+ });
410
+ if (paperclipBridge) {
411
+ Object.assign(env, paperclipBridge.env);
412
+ loggedEnv = buildInvocationEnvForLogs(env, {
413
+ runtimeEnv: Object.fromEntries(Object.entries(ensurePathInEnv({ ...sanitizeInheritedPaperclipEnv(process.env), ...env })).filter((entry) => typeof entry[1] === "string")),
414
+ includeRuntimeKeys: ["HOME"],
415
+ resolvedCommand,
416
+ });
417
+ }
418
+ }
419
+ const runtimeSessionParams = parseObject(runtime.sessionParams);
420
+ const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? "");
421
+ const runtimeSessionCwd = asString(runtimeSessionParams.cwd, "");
422
+ const runtimeRemoteExecution = parseObject(runtimeSessionParams.remoteExecution);
423
+ const sessionTargetMatches = adapterExecutionTargetSessionMatches(runtimeRemoteExecution, runtimeExecutionTarget);
424
+ const sessionParamsCwdMatches = runtimeSessionCwd.length === 0 ||
425
+ executionCwdsMatch(runtimeSessionCwd, effectiveExecutionCwd, executionTargetIsRemote);
426
+ const savedSessionCwd = runtimeSessionId.length > 0
427
+ ? await readSavedSessionCwd({
428
+ runId,
429
+ sessionPath: runtimeSessionId,
430
+ executionTarget: runtimeExecutionTarget ?? null,
431
+ cwd,
432
+ env,
433
+ timeoutSec,
434
+ graceSec,
435
+ })
436
+ : null;
437
+ const sessionHeaderCwdMatches = runtimeSessionId.length === 0 ||
438
+ (savedSessionCwd !== null &&
439
+ executionCwdsMatch(savedSessionCwd, effectiveExecutionCwd, executionTargetIsRemote));
440
+ const canResumeSession = runtimeSessionId.length > 0 &&
441
+ sessionTargetMatches &&
442
+ sessionParamsCwdMatches &&
443
+ sessionHeaderCwdMatches;
444
+ const sessionPath = canResumeSession
445
+ ? runtimeSessionId
446
+ : executionTargetIsRemote && remoteSessionRootDir
447
+ ? buildRemoteSessionPath(remoteSessionRootDir, agent.id, new Date().toISOString())
448
+ : buildSessionPath(agent.id, new Date().toISOString());
449
+ if (runtimeSessionId && !canResumeSession) {
450
+ const staleSessionCwdNote = savedSessionCwd !== null && !sessionHeaderCwdMatches
451
+ ? ` Pi stored cwd "${savedSessionCwd}" in the session header, so Paperclip will start a fresh session for "${effectiveExecutionCwd}".`
452
+ : "";
453
+ await onLog("stdout", executionTargetIsRemote
454
+ ? `[paperclip] Pi session "${runtimeSessionId}" does not match the current remote execution state and will not be resumed in "${effectiveExecutionCwd}".${staleSessionCwdNote} Starting a fresh remote session.\n`
455
+ : `[paperclip] Pi session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${effectiveExecutionCwd}".${staleSessionCwdNote}\n`);
456
+ }
457
+ if (!canResumeSession) {
458
+ if (executionTargetIsRemote) {
459
+ await ensureAdapterExecutionTargetFile(runId, runtimeExecutionTarget, sessionPath, {
460
+ cwd,
461
+ env,
462
+ timeoutSec: 15,
463
+ graceSec: 5,
464
+ onLog,
465
+ });
466
+ }
467
+ else {
468
+ try {
469
+ await fs.writeFile(sessionPath, "", { flag: "wx" });
470
+ }
471
+ catch (err) {
472
+ if (err.code !== "EEXIST") {
473
+ throw err;
474
+ }
475
+ }
476
+ }
477
+ }
478
+ // Handle instructions file and build system prompt extension
479
+ const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
480
+ const resolvedInstructionsFilePath = instructionsFilePath
481
+ ? path.resolve(cwd, instructionsFilePath)
482
+ : "";
483
+ const instructionsFileDir = instructionsFilePath ? `${path.dirname(instructionsFilePath)}/` : "";
484
+ let systemPromptExtension = "";
485
+ let instructionsReadFailed = false;
486
+ if (resolvedInstructionsFilePath) {
487
+ try {
488
+ const instructionsContents = await fs.readFile(resolvedInstructionsFilePath, "utf8");
489
+ systemPromptExtension =
490
+ `${instructionsContents}\n\n` +
491
+ `The above agent instructions were loaded from ${resolvedInstructionsFilePath}. ` +
492
+ `Resolve any relative file references from ${instructionsFileDir}.\n\n` +
493
+ (context.conversationMode === true
494
+ ? DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE
495
+ : DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE);
496
+ }
497
+ catch (err) {
498
+ instructionsReadFailed = true;
499
+ const reason = err instanceof Error ? err.message : String(err);
500
+ await onLog("stdout", `[paperclip] Warning: could not read agent instructions file "${resolvedInstructionsFilePath}": ${reason}\n`);
501
+ // Fall back to base prompt template
502
+ systemPromptExtension = promptTemplate;
503
+ }
504
+ }
505
+ else {
506
+ systemPromptExtension = promptTemplate;
507
+ }
508
+ const bootstrapPromptTemplate = asString(config.bootstrapPromptTemplate, "");
509
+ const templateData = {
510
+ agentId: agent.id,
511
+ companyId: agent.companyId,
512
+ runId,
513
+ company: { id: agent.companyId },
514
+ agent,
515
+ run: { id: runId, source: "on_demand" },
516
+ context,
517
+ };
518
+ const renderedSystemPromptExtension = renderTemplate(systemPromptExtension, templateData);
519
+ const systemOwnsDefaultPolicy = !hasCustomPromptTemplate || Boolean(resolvedInstructionsFilePath && !instructionsReadFailed);
520
+ const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
521
+ const commandNotes = (() => {
522
+ const notes = [...preparedRuntimeConfig.notes];
523
+ if (stdoutLogMode !== "raw") {
524
+ notes.push(`Pi stdout run-log compaction mode: ${stdoutLogMode}`);
525
+ }
526
+ if (!resolvedInstructionsFilePath)
527
+ return notes;
528
+ if (instructionsReadFailed) {
529
+ notes.push(`Configured instructionsFilePath ${resolvedInstructionsFilePath}, but file could not be read; continuing without injected instructions.`);
530
+ return notes;
531
+ }
532
+ notes.push(`Loaded agent instructions from ${resolvedInstructionsFilePath}`);
533
+ notes.push(`Appended instructions + path directive to system prompt (relative references from ${instructionsFileDir}).`);
534
+ return notes;
535
+ })();
536
+ const buildArgs = (sessionFile, userPrompt) => {
537
+ const args = [];
538
+ // Use JSON mode for structured output with print mode (non-interactive)
539
+ args.push("--mode", "json");
540
+ args.push("-p"); // Non-interactive mode: process prompt and exit
541
+ // Use --append-system-prompt to extend Pi's default system prompt
542
+ args.push("--append-system-prompt", renderedSystemPromptExtension);
543
+ if (provider)
544
+ args.push("--provider", provider);
545
+ if (modelId)
546
+ args.push("--model", modelId);
547
+ if (thinking)
548
+ args.push("--thinking", thinking);
549
+ args.push("--tools", "read,bash,edit,write,grep,find,ls");
550
+ args.push("--session", sessionFile);
551
+ args.push("--skill", remoteSkillsDir ?? PI_AGENT_SKILLS_DIR);
552
+ if (extraArgs.length > 0)
553
+ args.push(...extraArgs);
554
+ args.push("--extension", attributionExtensionPath);
555
+ // Add the user prompt as the last argument
556
+ args.push(userPrompt);
557
+ return args;
558
+ };
559
+ const runAttempt = async (sessionFile) => {
560
+ const attemptResumedSession = canResumeSession && sessionFile === sessionPath;
561
+ await hydrateFreshSessionHandoff(ctx, { resumedSession: attemptResumedSession });
562
+ const attemptSections = selectPaperclipPromptSections(context, {
563
+ resumedSession: attemptResumedSession,
564
+ includeCommunicationGuidance: false,
565
+ includeExecutionContract: systemOwnsDefaultPolicy ? false : undefined,
566
+ });
567
+ const attemptBootstrapPrompt = !attemptResumedSession && bootstrapPromptTemplate.trim().length > 0
568
+ ? renderTemplate(bootstrapPromptTemplate, templateData).trim()
569
+ : "";
570
+ const attemptWakePrompt = attemptSections.wakePrompt;
571
+ const attemptRenderedHeartbeatPrompt = attemptResumedSession && attemptWakePrompt.length > 0
572
+ || isPaperclipRecoveryWakePayload(context.paperclipWake)
573
+ || !hasCustomPromptTemplate
574
+ ? ""
575
+ : renderTemplate(promptTemplate, templateData);
576
+ const attemptBaseUserPrompt = joinPromptSections([
577
+ attemptBootstrapPrompt,
578
+ attemptWakePrompt,
579
+ attemptSections.taskContextNote,
580
+ sessionHandoffNote,
581
+ attemptRenderedHeartbeatPrompt,
582
+ ]);
583
+ const userPrompt = joinPromptSections([
584
+ selectInitialCommunicationGuidance(context, { resumedSession: attemptResumedSession }),
585
+ attemptBaseUserPrompt,
586
+ ]);
587
+ const promptMetrics = {
588
+ systemPromptChars: renderedSystemPromptExtension.length,
589
+ promptChars: userPrompt.length,
590
+ bootstrapPromptChars: attemptBootstrapPrompt.length,
591
+ wakePromptChars: attemptWakePrompt.length,
592
+ taskContextChars: attemptSections.taskContextNote.length,
593
+ sessionHandoffChars: sessionHandoffNote.length,
594
+ heartbeatPromptChars: attemptRenderedHeartbeatPrompt.length,
595
+ };
596
+ const args = buildArgs(sessionFile, userPrompt);
597
+ if (onMeta) {
598
+ await onMeta({
599
+ adapterType: "pi_local",
600
+ command: resolvedCommand,
601
+ cwd: effectiveExecutionCwd,
602
+ commandNotes,
603
+ commandArgs: args,
604
+ env: loggedEnv,
605
+ prompt: userPrompt,
606
+ promptMetrics: { ...promptMetrics, promptChars: userPrompt.length },
607
+ context,
608
+ });
609
+ }
610
+ // Buffer stdout by lines to handle partial JSON chunks
611
+ let stdoutBuffer = "";
612
+ const compactStdoutLine = createPiStdoutCompactor(stdoutLogMode);
613
+ // Compaction only affects the persisted run log; parsePiJsonl reads the unfiltered proc.stdout.
614
+ const emitCompacted = async (line, suffix) => {
615
+ const compacted = compactStdoutLine(line);
616
+ if (compacted !== null) {
617
+ await onLog("stdout", compacted + suffix);
618
+ }
619
+ };
620
+ const bufferedOnLog = async (stream, chunk) => {
621
+ if (stream === "stderr") {
622
+ // Pass stderr through immediately (not JSONL)
623
+ await onLog(stream, chunk);
624
+ return;
625
+ }
626
+ stdoutBuffer += chunk;
627
+ const lines = stdoutBuffer.split("\n");
628
+ // Keep the last (potentially incomplete) line in the buffer
629
+ stdoutBuffer = lines.pop() || "";
630
+ for (const line of lines) {
631
+ if (line) {
632
+ await emitCompacted(line, "\n");
633
+ }
634
+ }
635
+ };
636
+ const consumeAccounting = createPiJsonlParser();
637
+ let hasAccounting = false;
638
+ const accountingLog = createUsageCheckpointLog(bufferedOnLog, ctx.onUsage ?? (async () => { }), stdout => {
639
+ hasAccounting = true;
640
+ const parsed = consumeAccounting(stdout);
641
+ return { usage: parsed.usage, costUsd: parsed.usage.costUsd, usageBasis: "per_run", provider, biller: resolvePiBiller(runtimeEnv, provider), billingType: "unknown", model, complete: parsed.sawAgentEnd };
642
+ });
643
+ const proc = await runAdapterExecutionTargetProcess(runId, runtimeExecutionTarget, command, args, {
644
+ onProcessStopped: providerStop.beginInvocation(),
645
+ cwd,
646
+ env: executionTargetIsRemote ? env : runtimeEnv,
647
+ timeoutSec,
648
+ graceSec,
649
+ onSpawn,
650
+ onRuntimeProgress: ctx.onRuntimeProgress,
651
+ onLog: accountingLog,
652
+ runLogTail: paperclipBridge?.runLogTail,
653
+ settleRunDisposition: paperclipBridge?.settleRunDisposition,
654
+ });
655
+ await accountingLog.flush();
656
+ // Flush any remaining buffer content
657
+ if (stdoutBuffer) {
658
+ await emitCompacted(stdoutBuffer, "");
659
+ }
660
+ // Display output is capped by the process transport. Keep accounting
661
+ // from the full stream, including when no checkpoint callback is installed.
662
+ const parsed = parsePiJsonl(proc.stdout);
663
+ if (hasAccounting) {
664
+ const retained = consumeAccounting("");
665
+ parsed.usage = retained.usage;
666
+ parsed.sawAgentEnd = retained.sawAgentEnd;
667
+ }
668
+ return { proc, rawStderr: proc.stderr, parsed };
669
+ };
670
+ const toResult = (attempt, clearSessionOnMissingSession = false) => {
671
+ if (attempt.proc.timedOut) {
672
+ return {
673
+ exitCode: attempt.proc.exitCode,
674
+ signal: attempt.proc.signal,
675
+ timedOut: true,
676
+ usageComplete: attempt.parsed.sawAgentEnd,
677
+ usage: attempt.parsed.usage, usageBasis: "per_run", provider, biller: resolvePiBiller(runtimeEnv, provider), model, billingType: "unknown", costUsd: attempt.parsed.usage.costUsd,
678
+ errorMessage: `Timed out after ${timeoutSec}s`,
679
+ clearSession: clearSessionOnMissingSession,
680
+ };
681
+ }
682
+ const resolvedSessionId = clearSessionOnMissingSession ? null : sessionPath;
683
+ const resolvedSessionParams = resolvedSessionId
684
+ ? {
685
+ sessionId: resolvedSessionId,
686
+ cwd: effectiveExecutionCwd,
687
+ ...(workspaceId ? { workspaceId } : {}),
688
+ ...(workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}),
689
+ ...(workspaceRepoRef ? { repoRef: workspaceRepoRef } : {}),
690
+ ...(executionTargetIsRemote
691
+ ? {
692
+ remoteExecution: adapterExecutionTargetSessionIdentity(runtimeExecutionTarget),
693
+ }
694
+ : {}),
695
+ }
696
+ : null;
697
+ const stderrLine = firstNonEmptyLine(attempt.proc.stderr);
698
+ const rawExitCode = attempt.proc.exitCode;
699
+ const parsedError = attempt.parsed.errors.find((error) => error.trim().length > 0) ?? "";
700
+ const effectiveExitCode = (rawExitCode ?? 0) === 0 && parsedError ? 1 : rawExitCode;
701
+ const fallbackErrorMessage = parsedError || stderrLine || `Pi exited with code ${rawExitCode ?? -1}`;
702
+ return {
703
+ exitCode: effectiveExitCode,
704
+ signal: attempt.proc.signal,
705
+ timedOut: false,
706
+ usageComplete: attempt.parsed.sawAgentEnd,
707
+ usageBasis: "per_run",
708
+ errorMessage: (effectiveExitCode ?? 0) === 0 ? null : fallbackErrorMessage,
709
+ // Forward the transport-level error code from the run-disposition seam.
710
+ // A lost duplex control channel surfaces the typed `duplex_channel_lost`
711
+ // code; every other result carries no code here.
712
+ errorCode: attempt.proc.errorCode ?? null,
713
+ usage: {
714
+ inputTokens: attempt.parsed.usage.inputTokens,
715
+ outputTokens: attempt.parsed.usage.outputTokens,
716
+ cachedInputTokens: attempt.parsed.usage.cachedInputTokens,
717
+ },
718
+ sessionId: resolvedSessionId,
719
+ sessionParams: resolvedSessionParams,
720
+ sessionDisplayId: resolvedSessionId,
721
+ provider: provider,
722
+ biller: resolvePiBiller(runtimeEnv, provider),
723
+ model: model,
724
+ billingType: "unknown",
725
+ costUsd: attempt.parsed.usage.costUsd,
726
+ resultJson: {
727
+ stdout: attempt.proc.stdout,
728
+ stderr: attempt.proc.stderr,
729
+ },
730
+ summary: attempt.parsed.finalMessage ?? attempt.parsed.messages.join("\n\n").trim(),
731
+ clearSession: Boolean(clearSessionOnMissingSession),
732
+ };
733
+ };
734
+ const initial = await runAttempt(sessionPath);
735
+ const initialFailed = !initial.proc.timedOut && ((initial.proc.exitCode ?? 0) !== 0 || initial.parsed.errors.length > 0);
736
+ if (canResumeSession &&
737
+ initialFailed &&
738
+ isPiUnknownSessionError(initial.proc.stdout, initial.rawStderr)) {
739
+ await onLog("stdout", `[paperclip] Pi session "${runtimeSessionId}" is unavailable; retrying with a fresh session.\n`);
740
+ const newSessionPath = executionTargetIsRemote && remoteSessionRootDir
741
+ ? buildRemoteSessionPath(remoteSessionRootDir, agent.id, new Date().toISOString())
742
+ : buildSessionPath(agent.id, new Date().toISOString());
743
+ if (executionTargetIsRemote) {
744
+ await ensureAdapterExecutionTargetFile(runId, executionTarget, newSessionPath, {
745
+ cwd,
746
+ env,
747
+ timeoutSec: 15,
748
+ graceSec: 5,
749
+ onLog,
750
+ });
751
+ }
752
+ else {
753
+ try {
754
+ await fs.writeFile(newSessionPath, "", { flag: "wx" });
755
+ }
756
+ catch (err) {
757
+ if (err.code !== "EEXIST") {
758
+ throw err;
759
+ }
760
+ }
761
+ }
762
+ const retry = await runAttempt(newSessionPath);
763
+ return toResult(retry, true);
764
+ }
765
+ return toResult(initial);
766
+ }
767
+ finally {
768
+ try {
769
+ await providerStop.collectBeforeRestore();
770
+ }
771
+ finally {
772
+ await Promise.all([
773
+ paperclipBridge?.stop(),
774
+ restoreRemoteWorkspace?.(),
775
+ localSkillsDir ? fs.rm(path.dirname(localSkillsDir), { recursive: true, force: true }).catch(() => undefined) : Promise.resolve(),
776
+ ]);
777
+ }
778
+ }
779
+ }
780
+ finally {
781
+ await Promise.all([preparedRuntimeConfig.cleanup(), attributionExtension?.cleanup()]);
782
+ }
783
+ }
784
+ //# sourceMappingURL=execute.js.map