@microvac/adapter-opencode-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/README.md +12 -2
  3. package/dist/cli/format-event.d.ts +2 -0
  4. package/dist/cli/format-event.d.ts.map +1 -0
  5. package/dist/cli/format-event.js +115 -0
  6. package/dist/cli/format-event.js.map +1 -0
  7. package/dist/cli/index.d.ts +2 -0
  8. package/dist/cli/index.d.ts.map +1 -0
  9. package/dist/cli/index.js +2 -0
  10. package/dist/cli/index.js.map +1 -0
  11. package/dist/index.d.ts +11 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +123 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/server/execute.d.ts +13 -0
  16. package/dist/server/execute.d.ts.map +1 -0
  17. package/dist/server/execute.js +664 -0
  18. package/dist/server/execute.js.map +1 -0
  19. package/dist/server/execute.remote.test.d.ts +2 -0
  20. package/dist/server/execute.remote.test.d.ts.map +1 -0
  21. package/dist/server/execute.remote.test.js +386 -0
  22. package/dist/server/execute.remote.test.js.map +1 -0
  23. package/dist/server/execute.test.d.ts +2 -0
  24. package/dist/server/execute.test.d.ts.map +1 -0
  25. package/dist/server/execute.test.js +322 -0
  26. package/dist/server/execute.test.js.map +1 -0
  27. package/dist/server/execute.timeout.test.d.ts +2 -0
  28. package/dist/server/execute.timeout.test.d.ts.map +1 -0
  29. package/dist/server/execute.timeout.test.js +138 -0
  30. package/dist/server/execute.timeout.test.js.map +1 -0
  31. package/dist/server/index.d.ts +8 -0
  32. package/dist/server/index.d.ts.map +1 -0
  33. package/dist/server/index.js +68 -0
  34. package/dist/server/index.js.map +1 -0
  35. package/dist/server/models.d.ts +24 -0
  36. package/dist/server/models.d.ts.map +1 -0
  37. package/dist/server/models.js +281 -0
  38. package/dist/server/models.js.map +1 -0
  39. package/dist/server/models.test.d.ts +2 -0
  40. package/dist/server/models.test.d.ts.map +1 -0
  41. package/dist/server/models.test.js +258 -0
  42. package/dist/server/models.test.js.map +1 -0
  43. package/dist/server/parse.d.ts +32 -0
  44. package/dist/server/parse.d.ts.map +1 -0
  45. package/dist/server/parse.js +136 -0
  46. package/dist/server/parse.js.map +1 -0
  47. package/dist/server/parse.test.d.ts +2 -0
  48. package/dist/server/parse.test.d.ts.map +1 -0
  49. package/dist/server/parse.test.js +91 -0
  50. package/dist/server/parse.test.js.map +1 -0
  51. package/dist/server/runtime-config.d.ts +20 -0
  52. package/dist/server/runtime-config.d.ts.map +1 -0
  53. package/dist/server/runtime-config.js +248 -0
  54. package/dist/server/runtime-config.js.map +1 -0
  55. package/dist/server/runtime-config.test.d.ts +2 -0
  56. package/dist/server/runtime-config.test.d.ts.map +1 -0
  57. package/dist/server/runtime-config.test.js +408 -0
  58. package/dist/server/runtime-config.test.js.map +1 -0
  59. package/dist/server/sandbox-tool-memory.d.ts +2 -0
  60. package/dist/server/sandbox-tool-memory.d.ts.map +1 -0
  61. package/dist/server/sandbox-tool-memory.js +55 -0
  62. package/dist/server/sandbox-tool-memory.js.map +1 -0
  63. package/dist/server/skills.d.ts +8 -0
  64. package/dist/server/skills.d.ts.map +1 -0
  65. package/dist/server/skills.js +73 -0
  66. package/dist/server/skills.js.map +1 -0
  67. package/dist/server/test.d.ts +3 -0
  68. package/dist/server/test.d.ts.map +1 -0
  69. package/dist/server/test.js +469 -0
  70. package/dist/server/test.js.map +1 -0
  71. package/dist/server/test.remote.test.d.ts +2 -0
  72. package/dist/server/test.remote.test.d.ts.map +1 -0
  73. package/dist/server/test.remote.test.js +227 -0
  74. package/dist/server/test.remote.test.js.map +1 -0
  75. package/dist/ui/build-config.d.ts +3 -0
  76. package/dist/ui/build-config.d.ts.map +1 -0
  77. package/dist/ui/build-config.js +42 -0
  78. package/dist/ui/build-config.js.map +1 -0
  79. package/dist/ui/index.d.ts +3 -0
  80. package/dist/ui/index.d.ts.map +1 -0
  81. package/dist/ui/index.js +3 -0
  82. package/dist/ui/index.js.map +1 -0
  83. package/dist/ui/parse-stdout.d.ts +3 -0
  84. package/dist/ui/parse-stdout.d.ts.map +1 -0
  85. package/dist/ui/parse-stdout.js +141 -0
  86. package/dist/ui/parse-stdout.js.map +1 -0
  87. package/package.json +52 -4
@@ -0,0 +1,664 @@
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, ensureAdapterExecutionTargetRuntimeCommandInstalled, prepareAdapterExecutionTargetRuntime, adapterExecutionTargetDuplexObservabilityRecorder, adapterExecutionTargetEnablesSandboxDuplexBridge, readAdapterExecutionTarget, readAdapterExecutionTargetHomeDir, resolveAdapterExecutionTargetTimeout, resolveAdapterExecutionTargetCommandForLogs, runAdapterExecutionTargetProcess, runAdapterExecutionTargetShellCommand, startAdapterExecutionTargetPaperclipBridge, } from "@paperclipai/adapter-utils/execution-target";
9
+ import { asString, asNumber, asStringArray, parseObject, buildPaperclipEnv, buildRuntimeToolsEnv, joinPromptSections, buildInvocationEnvForLogs, ensurePaperclipSkillSymlink, ensurePathInEnv, refreshPaperclipWorkspaceEnvForExecution, renderTemplate, hydrateFreshSessionHandoff, selectPaperclipPromptSections, selectInitialCommunicationGuidance, isPaperclipRecoveryWakePayload, DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE, DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE, isPaperclipSkillSourceMissing, readPaperclipRuntimeSkillEntries, readPaperclipIssueWorkModeFromContext, resolveLegacyPaperclipDesiredSkillNames, } from "@paperclipai/adapter-utils/server-utils";
10
+ import { isOpenCodeUnknownSessionError, parseOpenCodeJsonl, createOpenCodeJsonlParser } from "./parse.js";
11
+ import { ensureOpenCodeModelConfiguredAndAvailable, isTruthyEnvFlag, parseOpenCodeModelsOutput, requireOpenCodeModelId, } from "./models.js";
12
+ import { removeMaintainerOnlySkillSymlinks } from "@paperclipai/adapter-utils/server-utils";
13
+ import { apiKeyBillingType } from "@paperclipai/adapter-utils/api-billing-type";
14
+ import { prepareOpenCodeRuntimeConfig, prepareManagedOpenCodeRemoteHomes } from "./runtime-config.js";
15
+ import { SANDBOX_INSTALL_COMMAND } from "../index.js";
16
+ import { resolveOpenCodeSkillsHome } from "./skills.js";
17
+ const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
18
+ function firstNonEmptyLine(text) {
19
+ return (text
20
+ .split(/\r?\n/)
21
+ .map((line) => line.trim())
22
+ .find(Boolean) ?? "");
23
+ }
24
+ function parseModelProvider(model) {
25
+ if (!model)
26
+ return null;
27
+ const trimmed = model.trim();
28
+ if (!trimmed.includes("/"))
29
+ return null;
30
+ return trimmed.slice(0, trimmed.indexOf("/")).trim() || null;
31
+ }
32
+ function resolveOpenCodeBiller(env, provider) {
33
+ return provider === "openai" ? inferOpenAiCompatibleBiller(env, "openai") ?? "unknown" : provider ?? "unknown";
34
+ }
35
+ const REMOTE_OPENCODE_MODELS_PROBE_DEFAULT_TIMEOUT_SEC = 20;
36
+ const REMOTE_OPENCODE_MODELS_PROBE_SANDBOX_TIMEOUT_SEC = 120;
37
+ export async function ensureRemoteOpenCodeModelConfiguredAndAvailable(input) {
38
+ const model = requireOpenCodeModelId(input.model);
39
+ // When the caller opts into OPENCODE_ALLOW_ALL_MODELS, OpenCode accepts any
40
+ // provider/model at run time (e.g. gateway-routed models that never appear in
41
+ // `opencode models` output). Honour that on the REMOTE path too by skipping the
42
+ // remote availability probe; we still enforce the provider/model format above.
43
+ // Mirrors the local ensureOpenCodeModelConfiguredAndAvailable bypass. Prefer the
44
+ // explicit run env, then the process env.
45
+ if (isTruthyEnvFlag(input.env.OPENCODE_ALLOW_ALL_MODELS ?? process.env.OPENCODE_ALLOW_ALL_MODELS)) {
46
+ return;
47
+ }
48
+ const defaultProbeTimeoutSec = input.executionTarget.kind === "remote" && input.executionTarget.transport === "sandbox"
49
+ ? REMOTE_OPENCODE_MODELS_PROBE_SANDBOX_TIMEOUT_SEC
50
+ : REMOTE_OPENCODE_MODELS_PROBE_DEFAULT_TIMEOUT_SEC;
51
+ const probeTimeoutSec = input.timeoutSec > 0
52
+ ? Math.min(input.timeoutSec, defaultProbeTimeoutSec)
53
+ : defaultProbeTimeoutSec;
54
+ const probe = await runAdapterExecutionTargetProcess(input.runId, input.executionTarget, input.command, ["models"], {
55
+ cwd: input.cwd,
56
+ env: input.env,
57
+ timeoutSec: probeTimeoutSec,
58
+ graceSec: input.graceSec,
59
+ onLog: async () => { },
60
+ });
61
+ // The remote availability probe is a best-effort pre-flight guard, not a gate.
62
+ // If `opencode models` itself cannot run on the target — timeout, transient CLI
63
+ // error, provider hiccup — do NOT abort the run. The real invocation is
64
+ // authoritative, so a probe that can't execute must never be fatal. (Previously
65
+ // these threw and crashed runs mid-flight, losing the agent's work + disposition.)
66
+ if (probe.timedOut) {
67
+ console.warn(`[opencode-local] Remote model availability probe for "${model}" timed out after ${probeTimeoutSec}s; proceeding with the configured model.`);
68
+ return;
69
+ }
70
+ if ((probe.exitCode ?? 1) !== 0) {
71
+ const detail = firstNonEmptyLine(probe.stderr) || firstNonEmptyLine(probe.stdout);
72
+ console.warn(`[opencode-local] Remote \`opencode models\` could not run for "${model}"${detail ? ` (${detail})` : ""}; proceeding with the configured model.`);
73
+ return;
74
+ }
75
+ const models = parseOpenCodeModelsOutput(probe.stdout);
76
+ if (models.length === 0) {
77
+ console.warn(`[opencode-local] Remote \`opencode models\` returned no models; proceeding with the configured model "${model}".`);
78
+ return;
79
+ }
80
+ if (!models.some((entry) => entry.id === model)) {
81
+ const sample = models.slice(0, 12).map((entry) => entry.id).join(", ");
82
+ throw new Error(`Configured OpenCode model is unavailable on the remote execution target: ${model}. Available models: ${sample}${models.length > 12 ? ", ..." : ""}`);
83
+ }
84
+ }
85
+ async function ensureOpenCodeSkillsInjected(onLog, skillsEntries, desiredSkillNames, skillsHome = resolveOpenCodeSkillsHome({})) {
86
+ await fs.mkdir(skillsHome, { recursive: true });
87
+ const desiredSet = new Set(desiredSkillNames ?? skillsEntries.map((entry) => entry.key));
88
+ const selectedEntries = skillsEntries.filter((entry) => desiredSet.has(entry.key));
89
+ const removedSkills = await removeMaintainerOnlySkillSymlinks(skillsHome, selectedEntries.map((entry) => entry.runtimeName));
90
+ for (const skillName of removedSkills) {
91
+ await onLog("stderr", `[paperclip] Removed maintainer-only OpenCode skill "${skillName}" from ${skillsHome}\n`);
92
+ }
93
+ for (const entry of selectedEntries) {
94
+ const target = path.join(skillsHome, entry.runtimeName);
95
+ try {
96
+ const result = await ensurePaperclipSkillSymlink(entry.source, target);
97
+ if (result === "skipped")
98
+ continue;
99
+ await onLog("stderr", `[paperclip] ${result === "repaired" ? "Repaired" : "Injected"} OpenCode skill "${entry.key}" into ${skillsHome}\n`);
100
+ }
101
+ catch (err) {
102
+ await onLog("stderr", `[paperclip] Failed to inject OpenCode skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)}\n`);
103
+ }
104
+ }
105
+ }
106
+ async function buildOpenCodeSkillsDir(config) {
107
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-skills-"));
108
+ const target = path.join(tmp, "skills");
109
+ await fs.mkdir(target, { recursive: true });
110
+ const availableEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
111
+ const desiredNames = new Set(resolveLegacyPaperclipDesiredSkillNames(config, availableEntries));
112
+ for (const entry of availableEntries) {
113
+ if (!desiredNames.has(entry.key))
114
+ continue;
115
+ if (isPaperclipSkillSourceMissing(entry))
116
+ continue;
117
+ await fs.symlink(entry.source, path.join(target, entry.runtimeName));
118
+ }
119
+ return target;
120
+ }
121
+ export async function execute(ctx) {
122
+ const providerStop = createProviderStoppedBoundary(ctx.onProviderStopped);
123
+ const { runId, agent, runtime, config, context, onLog, onMeta, onSpawn, authToken } = ctx;
124
+ const executionTarget = readAdapterExecutionTarget({
125
+ executionTarget: ctx.executionTarget,
126
+ legacyRemoteExecution: ctx.executionTransport?.remoteExecution,
127
+ });
128
+ const executionTargetIsRemote = adapterExecutionTargetIsRemote(executionTarget);
129
+ const promptTemplate = asString(config.promptTemplate, context.conversationMode === true
130
+ ? DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE
131
+ : DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE);
132
+ const command = asString(config.command, "opencode");
133
+ const model = asString(config.model, "").trim();
134
+ const variant = asString(config.variant, "").trim();
135
+ const workspaceContext = parseObject(context.paperclipWorkspace);
136
+ const workspaceCwd = asString(workspaceContext.cwd, "");
137
+ const workspaceSource = asString(workspaceContext.source, "");
138
+ const workspaceId = asString(workspaceContext.workspaceId, "");
139
+ const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
140
+ const workspaceRepoRef = asString(workspaceContext.repoRef, "");
141
+ const agentHome = asString(workspaceContext.agentHome, "");
142
+ const workspaceHints = Array.isArray(context.paperclipWorkspaces)
143
+ ? context.paperclipWorkspaces.filter((value) => typeof value === "object" && value !== null)
144
+ : [];
145
+ const configuredCwd = asString(config.cwd, "");
146
+ const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0;
147
+ const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd;
148
+ const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd();
149
+ let effectiveExecutionCwd = adapterExecutionTargetRemoteCwd(executionTarget, cwd);
150
+ await ensureAdapterExecutionTargetLocalWorkspace(executionTarget, cwd);
151
+ const openCodeSkillEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
152
+ const desiredOpenCodeSkillNames = resolveLegacyPaperclipDesiredSkillNames(config, openCodeSkillEntries);
153
+ if (!executionTargetIsRemote) {
154
+ await ensureOpenCodeSkillsInjected(onLog, openCodeSkillEntries, desiredOpenCodeSkillNames, resolveOpenCodeSkillsHome(config));
155
+ }
156
+ const envConfig = parseObject(config.env);
157
+ const env = {
158
+ ...buildPaperclipEnv(agent, ctx.agentIdentity),
159
+ ...buildRuntimeToolsEnv(ctx.runtimeTools),
160
+ };
161
+ env.PAPERCLIP_RUN_ID = runId;
162
+ const wakeTaskId = (typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim()) ||
163
+ (typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim()) ||
164
+ null;
165
+ const wakeReason = typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0
166
+ ? context.wakeReason.trim()
167
+ : null;
168
+ const wakeCommentId = (typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim()) ||
169
+ (typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim()) ||
170
+ null;
171
+ const approvalId = typeof context.approvalId === "string" && context.approvalId.trim().length > 0
172
+ ? context.approvalId.trim()
173
+ : null;
174
+ const approvalStatus = typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0
175
+ ? context.approvalStatus.trim()
176
+ : null;
177
+ const linkedIssueIds = Array.isArray(context.issueIds)
178
+ ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0)
179
+ : [];
180
+ const issueWorkMode = readPaperclipIssueWorkModeFromContext(context);
181
+ if (wakeTaskId)
182
+ env.PAPERCLIP_TASK_ID = wakeTaskId;
183
+ if (issueWorkMode)
184
+ env.PAPERCLIP_ISSUE_WORK_MODE = issueWorkMode;
185
+ if (wakeReason)
186
+ env.PAPERCLIP_WAKE_REASON = wakeReason;
187
+ if (wakeCommentId)
188
+ env.PAPERCLIP_WAKE_COMMENT_ID = wakeCommentId;
189
+ if (approvalId)
190
+ env.PAPERCLIP_APPROVAL_ID = approvalId;
191
+ if (approvalStatus)
192
+ env.PAPERCLIP_APPROVAL_STATUS = approvalStatus;
193
+ if (linkedIssueIds.length > 0)
194
+ env.PAPERCLIP_LINKED_ISSUE_IDS = linkedIssueIds.join(",");
195
+ refreshPaperclipWorkspaceEnvForExecution({
196
+ env,
197
+ envConfig,
198
+ workspaceCwd: effectiveWorkspaceCwd,
199
+ workspaceSource,
200
+ workspaceId,
201
+ workspaceRepoUrl,
202
+ workspaceRepoRef,
203
+ workspaceHints,
204
+ agentHome,
205
+ executionTargetIsRemote,
206
+ executionCwd: effectiveExecutionCwd,
207
+ });
208
+ // Prevent OpenCode from writing an opencode.json config file into the
209
+ // project working directory (which would pollute the git repo). Model
210
+ // selection is already handled via the --model CLI flag. Set after the
211
+ // envConfig loop so user overrides cannot disable this guard.
212
+ env.OPENCODE_DISABLE_PROJECT_CONFIG = "true";
213
+ if (authToken) {
214
+ env.PAPERCLIP_API_KEY = authToken;
215
+ }
216
+ const preparedRuntimeConfig = await prepareOpenCodeRuntimeConfig({
217
+ env, config,
218
+ sandboxToolOomPreference: executionTarget?.kind === "remote" && executionTarget.transport === "sandbox",
219
+ });
220
+ const localRuntimeConfigHome = preparedRuntimeConfig.notes.length > 0 ? preparedRuntimeConfig.env.XDG_CONFIG_HOME : "";
221
+ try {
222
+ const runtimeEnv = Object.fromEntries(Object.entries(ensurePathInEnv({ ...process.env, ...preparedRuntimeConfig.env })).filter((entry) => typeof entry[1] === "string"));
223
+ const adapterExecutionTimeout = resolveAdapterExecutionTargetTimeout(executionTarget, asNumber(config.timeoutSec, 0));
224
+ const timeoutSec = adapterExecutionTimeout.timeoutSec;
225
+ const graceSec = asNumber(config.graceSec, 20);
226
+ await ensureAdapterExecutionTargetRuntimeCommandInstalled({
227
+ runId,
228
+ target: executionTarget,
229
+ installCommand: ctx.runtimeCommandSpec?.installCommand,
230
+ detectCommand: ctx.runtimeCommandSpec?.detectCommand,
231
+ cwd,
232
+ env: runtimeEnv,
233
+ timeoutSec,
234
+ graceSec,
235
+ onLog,
236
+ });
237
+ await ensureAdapterExecutionTargetCommandResolvable(command, executionTarget, cwd, runtimeEnv, {
238
+ installCommand: SANDBOX_INSTALL_COMMAND,
239
+ timeoutSec,
240
+ });
241
+ const resolvedCommand = await resolveAdapterExecutionTargetCommandForLogs(command, executionTarget, cwd, runtimeEnv);
242
+ let loggedEnv = buildInvocationEnvForLogs(preparedRuntimeConfig.env, {
243
+ runtimeEnv,
244
+ includeRuntimeKeys: ["HOME"],
245
+ resolvedCommand,
246
+ });
247
+ if (!executionTargetIsRemote) {
248
+ await ensureOpenCodeModelConfiguredAndAvailable({
249
+ model,
250
+ command,
251
+ cwd,
252
+ env: runtimeEnv,
253
+ });
254
+ }
255
+ const extraArgs = (() => {
256
+ const fromExtraArgs = asStringArray(config.extraArgs);
257
+ if (fromExtraArgs.length > 0)
258
+ return fromExtraArgs;
259
+ return asStringArray(config.args);
260
+ })();
261
+ let restoreRemoteWorkspace = null;
262
+ let localSkillsDir = null;
263
+ let remoteRuntimeRootDir = null;
264
+ let paperclipBridge = null;
265
+ try {
266
+ if (executionTarget?.kind === "remote") {
267
+ localSkillsDir = await buildOpenCodeSkillsDir(config);
268
+ await onLog("stdout", `[paperclip] Syncing workspace and OpenCode runtime assets to ${describeAdapterExecutionTarget(executionTarget)}.\n`);
269
+ const preparedExecutionTargetRuntime = await prepareAdapterExecutionTargetRuntime({
270
+ privateRuntime: Boolean(config.managedAiConnection),
271
+ runId,
272
+ target: executionTarget,
273
+ adapterKey: "opencode",
274
+ timeoutSec,
275
+ workspaceLocalDir: cwd,
276
+ installCommand: SANDBOX_INSTALL_COMMAND,
277
+ detectCommand: command,
278
+ onProgress: (line) => onLog("stdout", line),
279
+ onRuntimeProgress: ctx.onRuntimeProgress,
280
+ assets: [
281
+ {
282
+ key: "skills",
283
+ localDir: localSkillsDir,
284
+ followSymlinks: true,
285
+ },
286
+ ...(localRuntimeConfigHome
287
+ ? [{
288
+ key: "xdgConfig",
289
+ localDir: localRuntimeConfigHome,
290
+ }]
291
+ : []),
292
+ ],
293
+ });
294
+ restoreRemoteWorkspace = () => preparedExecutionTargetRuntime.restoreWorkspace((line) => onLog("stdout", line));
295
+ effectiveExecutionCwd = preparedExecutionTargetRuntime.workspaceRemoteDir ?? effectiveExecutionCwd;
296
+ refreshPaperclipWorkspaceEnvForExecution({
297
+ env: preparedRuntimeConfig.env,
298
+ envConfig,
299
+ workspaceCwd: effectiveWorkspaceCwd,
300
+ workspaceSource,
301
+ workspaceId,
302
+ workspaceRepoUrl,
303
+ workspaceRepoRef,
304
+ workspaceHints,
305
+ agentHome,
306
+ executionTargetIsRemote,
307
+ executionCwd: effectiveExecutionCwd,
308
+ });
309
+ remoteRuntimeRootDir = preparedExecutionTargetRuntime.runtimeRootDir;
310
+ if (executionTarget?.kind === "remote" && executionTarget.transport === "ssh" && executionTarget.spec.useHostAuth === false && config.managedAiConnection && remoteRuntimeRootDir)
311
+ Object.assign(preparedRuntimeConfig.env, managedRemoteHomeEnvironment(remoteRuntimeRootDir));
312
+ const managedHome = adapterExecutionTargetUsesManagedHome(executionTarget, Boolean(config.managedAiConnection));
313
+ if (managedHome && preparedExecutionTargetRuntime.runtimeRootDir) {
314
+ preparedRuntimeConfig.env.HOME = preparedExecutionTargetRuntime.runtimeRootDir;
315
+ }
316
+ if (localRuntimeConfigHome && preparedExecutionTargetRuntime.assetDirs.xdgConfig) {
317
+ preparedRuntimeConfig.env.XDG_CONFIG_HOME = preparedExecutionTargetRuntime.assetDirs.xdgConfig;
318
+ }
319
+ prepareManagedOpenCodeRemoteHomes({
320
+ env: preparedRuntimeConfig.env,
321
+ config,
322
+ runtimeRootDir: preparedExecutionTargetRuntime.runtimeRootDir,
323
+ runId,
324
+ configDir: preparedExecutionTargetRuntime.assetDirs.xdgConfig,
325
+ });
326
+ const remoteHomeDir = config.managedAiConnection
327
+ ? preparedRuntimeConfig.env.HOME
328
+ : managedHome && preparedExecutionTargetRuntime.runtimeRootDir
329
+ ? preparedExecutionTargetRuntime.runtimeRootDir
330
+ : await readAdapterExecutionTargetHomeDir(runId, executionTarget, {
331
+ cwd,
332
+ env: preparedRuntimeConfig.env,
333
+ timeoutSec,
334
+ graceSec,
335
+ onLog,
336
+ });
337
+ if (remoteHomeDir && preparedExecutionTargetRuntime.assetDirs.skills) {
338
+ const remoteSkillsDir = path.posix.join(remoteHomeDir, ".claude", "skills");
339
+ await runAdapterExecutionTargetShellCommand(runId, executionTarget, `mkdir -p ${JSON.stringify(path.posix.dirname(remoteSkillsDir))} && rm -rf ${JSON.stringify(remoteSkillsDir)} && cp -a ${JSON.stringify(preparedExecutionTargetRuntime.assetDirs.skills)} ${JSON.stringify(remoteSkillsDir)}`, { cwd, env: preparedRuntimeConfig.env, timeoutSec, graceSec, onLog });
340
+ }
341
+ await ensureRemoteOpenCodeModelConfiguredAndAvailable({
342
+ runId,
343
+ executionTarget,
344
+ command,
345
+ model,
346
+ cwd,
347
+ env: preparedRuntimeConfig.env,
348
+ timeoutSec,
349
+ graceSec,
350
+ });
351
+ }
352
+ const runtimeExecutionTarget = overrideAdapterExecutionTargetRemoteCwd(executionTarget, effectiveExecutionCwd);
353
+ if (executionTargetIsRemote && adapterExecutionTargetUsesPaperclipBridge(runtimeExecutionTarget)) {
354
+ paperclipBridge = await startAdapterExecutionTargetPaperclipBridge({
355
+ runId,
356
+ target: runtimeExecutionTarget,
357
+ enableSandboxDuplexBridge: adapterExecutionTargetEnablesSandboxDuplexBridge(runtimeExecutionTarget),
358
+ duplexObservabilityRecorder: adapterExecutionTargetDuplexObservabilityRecorder(runtimeExecutionTarget),
359
+ runtimeRootDir: remoteRuntimeRootDir,
360
+ adapterKey: "opencode",
361
+ timeoutSec,
362
+ hostApiToken: preparedRuntimeConfig.env.PAPERCLIP_API_KEY,
363
+ onLog,
364
+ });
365
+ if (paperclipBridge) {
366
+ Object.assign(preparedRuntimeConfig.env, paperclipBridge.env);
367
+ loggedEnv = buildInvocationEnvForLogs(preparedRuntimeConfig.env, {
368
+ runtimeEnv: Object.fromEntries(Object.entries(ensurePathInEnv({ ...process.env, ...preparedRuntimeConfig.env })).filter((entry) => typeof entry[1] === "string")),
369
+ includeRuntimeKeys: ["HOME"],
370
+ resolvedCommand,
371
+ });
372
+ }
373
+ }
374
+ const runtimeSessionParams = parseObject(runtime.sessionParams);
375
+ const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? "");
376
+ const runtimeSessionCwd = asString(runtimeSessionParams.cwd, "");
377
+ const runtimeRemoteExecution = parseObject(runtimeSessionParams.remoteExecution);
378
+ const canResumeSession = runtimeSessionId.length > 0 &&
379
+ (runtimeSessionCwd.length === 0 || path.resolve(runtimeSessionCwd) === path.resolve(effectiveExecutionCwd)) &&
380
+ adapterExecutionTargetSessionMatches(runtimeRemoteExecution, runtimeExecutionTarget);
381
+ const sessionId = canResumeSession ? runtimeSessionId : null;
382
+ if (executionTargetIsRemote && runtimeSessionId && !canResumeSession) {
383
+ await onLog("stdout", `[paperclip] OpenCode session "${runtimeSessionId}" does not match the current remote execution identity and will not be resumed in "${effectiveExecutionCwd}". Starting a fresh remote session.\n`);
384
+ }
385
+ else if (runtimeSessionId && !canResumeSession) {
386
+ await onLog("stdout", `[paperclip] OpenCode session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${effectiveExecutionCwd}".\n`);
387
+ }
388
+ const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
389
+ const resolvedInstructionsFilePath = instructionsFilePath
390
+ ? path.resolve(cwd, instructionsFilePath)
391
+ : "";
392
+ const instructionsDir = resolvedInstructionsFilePath ? `${path.dirname(resolvedInstructionsFilePath)}/` : "";
393
+ let instructionsPrefix = "";
394
+ if (resolvedInstructionsFilePath) {
395
+ try {
396
+ const instructionsContents = await fs.readFile(resolvedInstructionsFilePath, "utf8");
397
+ instructionsPrefix =
398
+ `${instructionsContents}\n\n` +
399
+ `The above agent instructions were loaded from ${resolvedInstructionsFilePath}. ` +
400
+ `Resolve any relative file references from ${instructionsDir}.\n\n`;
401
+ }
402
+ catch (err) {
403
+ const reason = err instanceof Error ? err.message : String(err);
404
+ await onLog("stdout", `[paperclip] Warning: could not read agent instructions file "${resolvedInstructionsFilePath}": ${reason}\n`);
405
+ }
406
+ }
407
+ const commandNotes = (() => {
408
+ const notes = [...preparedRuntimeConfig.notes];
409
+ if (!resolvedInstructionsFilePath)
410
+ return notes;
411
+ if (instructionsPrefix.length > 0) {
412
+ notes.push(`Loaded agent instructions from ${resolvedInstructionsFilePath}`);
413
+ notes.push(`Prepended instructions + path directive to stdin prompt (relative references from ${instructionsDir}).`);
414
+ return notes;
415
+ }
416
+ notes.push(`Configured instructionsFilePath ${resolvedInstructionsFilePath}, but file could not be read; continuing without injected instructions.`);
417
+ return notes;
418
+ })();
419
+ const bootstrapPromptTemplate = asString(config.bootstrapPromptTemplate, "");
420
+ const templateData = {
421
+ agentId: agent.id,
422
+ companyId: agent.companyId,
423
+ runId,
424
+ company: { id: agent.companyId },
425
+ agent,
426
+ run: { id: runId, source: "on_demand" },
427
+ context,
428
+ };
429
+ const buildPrompt = (resumedSession) => {
430
+ const renderedBootstrapPrompt = !resumedSession && bootstrapPromptTemplate.trim().length > 0
431
+ ? renderTemplate(bootstrapPromptTemplate, templateData).trim()
432
+ : "";
433
+ const { taskContextNote, wakePrompt } = selectPaperclipPromptSections(context, {
434
+ resumedSession,
435
+ includeCommunicationGuidance: false,
436
+ });
437
+ const shouldUseResumeDeltaPrompt = resumedSession && wakePrompt.length > 0;
438
+ const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
439
+ ? ""
440
+ : renderTemplate(promptTemplate, templateData);
441
+ const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
442
+ const basePrompt = joinPromptSections([
443
+ instructionsPrefix,
444
+ renderedBootstrapPrompt,
445
+ wakePrompt,
446
+ taskContextNote,
447
+ sessionHandoffNote,
448
+ renderedPrompt,
449
+ ]);
450
+ return {
451
+ basePrompt,
452
+ promptMetrics: {
453
+ promptChars: basePrompt.length,
454
+ instructionsChars: instructionsPrefix.length,
455
+ bootstrapPromptChars: renderedBootstrapPrompt.length,
456
+ wakePromptChars: wakePrompt.length,
457
+ taskContextChars: taskContextNote.length,
458
+ sessionHandoffChars: sessionHandoffNote.length,
459
+ heartbeatPromptChars: renderedPrompt.length,
460
+ },
461
+ };
462
+ };
463
+ // Optional diagnostic: surface OpenCode's own logs on stderr (captured into the
464
+ // run result) so failures that OpenCode otherwise wraps as an opaque
465
+ // "Unexpected server error" can be diagnosed in remote/sandbox runs where the
466
+ // log file is unreachable. Toggle via PAPERCLIP_OPENCODE_PRINT_LOGS (run env,
467
+ // then process env).
468
+ const printLogs = isTruthyEnvFlag(env.PAPERCLIP_OPENCODE_PRINT_LOGS ?? process.env.PAPERCLIP_OPENCODE_PRINT_LOGS);
469
+ const buildArgs = (resumeSessionId) => {
470
+ const args = ["run", "--format", "json"];
471
+ if (printLogs)
472
+ args.push("--print-logs");
473
+ if (resumeSessionId)
474
+ args.push("--session", resumeSessionId);
475
+ if (model)
476
+ args.push("--model", model);
477
+ if (variant)
478
+ args.push("--variant", variant);
479
+ // OpenCode prefers the inherited PWD over process.cwd(). Use the realized
480
+ // workspace unless the operator already selected a directory explicitly.
481
+ const optionTerminator = extraArgs.indexOf("--");
482
+ const extraOptionArgs = optionTerminator === -1 ? extraArgs : extraArgs.slice(0, optionTerminator);
483
+ if (!extraOptionArgs.some((arg) => arg === "--dir" || arg.startsWith("--dir="))) {
484
+ args.push("--dir", effectiveExecutionCwd);
485
+ }
486
+ if (extraArgs.length > 0)
487
+ args.push(...extraArgs);
488
+ return args;
489
+ };
490
+ // Remote targets receive only the prepared environment, never host keys.
491
+ const accountingEnv = executionTargetIsRemote ? preparedRuntimeConfig.env : runtimeEnv;
492
+ const runAttempt = async (resumeSessionId) => {
493
+ await hydrateFreshSessionHandoff(ctx, { resumedSession: Boolean(resumeSessionId) });
494
+ const { basePrompt, promptMetrics } = buildPrompt(Boolean(resumeSessionId));
495
+ const prompt = joinPromptSections([
496
+ selectInitialCommunicationGuidance(context, { resumedSession: Boolean(resumeSessionId) }),
497
+ basePrompt,
498
+ ]);
499
+ const args = buildArgs(resumeSessionId);
500
+ if (onMeta) {
501
+ await onMeta({
502
+ adapterType: "opencode_local",
503
+ command: resolvedCommand,
504
+ cwd: effectiveExecutionCwd,
505
+ commandNotes,
506
+ commandArgs: [...args, `<stdin prompt ${prompt.length} chars>`],
507
+ env: loggedEnv,
508
+ prompt,
509
+ promptMetrics: { ...promptMetrics, promptChars: prompt.length },
510
+ context,
511
+ });
512
+ }
513
+ const consumeAccounting = createOpenCodeJsonlParser();
514
+ let hasAccounting = false;
515
+ const accountingLog = createUsageCheckpointLog(onLog, ctx.onUsage ?? (async () => { }), stdout => {
516
+ hasAccounting = true;
517
+ const parsed = consumeAccounting(stdout);
518
+ const provider = parseModelProvider(model || null);
519
+ return { usage: parsed.usageReported ? parsed.usage : undefined, costUsd: parsed.costUsd,
520
+ costStatus: parsed.usageComplete || parsed.costUsd != null ? undefined : "unpriced",
521
+ usageBasis: "per_run", provider, biller: resolveOpenCodeBiller(accountingEnv, provider), billingType: apiKeyBillingType(provider, accountingEnv), model, complete: false };
522
+ });
523
+ const proc = await runAdapterExecutionTargetProcess(runId, runtimeExecutionTarget, command, args, {
524
+ onProcessStopped: providerStop.beginInvocation(),
525
+ // Keep a long sandbox run off the synchronous command HTTP request.
526
+ // Probes and preparation keep their existing execution paths.
527
+ ...(runtimeExecutionTarget?.kind === "remote" && runtimeExecutionTarget.transport === "sandbox"
528
+ && runtimeExecutionTarget.providerKey === "daytona" ? { useSession: true } : {}),
529
+ cwd,
530
+ env: preparedRuntimeConfig.env,
531
+ stdin: prompt,
532
+ timeoutSec,
533
+ graceSec,
534
+ onSpawn,
535
+ onRuntimeProgress: ctx.onRuntimeProgress,
536
+ onLog: accountingLog,
537
+ runLogTail: paperclipBridge?.runLogTail,
538
+ settleRunDisposition: paperclipBridge?.settleRunDisposition,
539
+ });
540
+ // Parse any unterminated final record before deciding whether its usage
541
+ // is complete. A clean exit alone cannot turn absent counters into zero.
542
+ await accountingLog.flush();
543
+ const retainedAccounting = consumeAccounting("");
544
+ await accountingLog.flush({ complete: proc.exitCode === 0 && !proc.timedOut && !proc.signal
545
+ && (retainedAccounting.usageComplete || retainedAccounting.costUsd != null) });
546
+ // Display output is capped by the process transport. Keep accounting
547
+ // from the full stream, including when no checkpoint callback is installed.
548
+ const parsed = parseOpenCodeJsonl(proc.stdout);
549
+ if (hasAccounting) {
550
+ const retained = consumeAccounting("");
551
+ parsed.usage = retained.usage;
552
+ parsed.usageReported = retained.usageReported;
553
+ parsed.usageComplete = retained.usageComplete;
554
+ parsed.costUsd = retained.costUsd;
555
+ }
556
+ return { proc, rawStderr: proc.stderr, parsed };
557
+ };
558
+ const toResult = (attempt, clearSessionOnMissingSession = false) => {
559
+ if (attempt.proc.timedOut) {
560
+ return {
561
+ exitCode: attempt.proc.exitCode,
562
+ signal: attempt.proc.signal,
563
+ timedOut: true,
564
+ usageComplete: false,
565
+ usage: attempt.parsed.usageReported ? attempt.parsed.usage : undefined,
566
+ usageBasis: "per_run",
567
+ provider: parseModelProvider(model || null),
568
+ biller: resolveOpenCodeBiller(accountingEnv, parseModelProvider(model || null)),
569
+ model,
570
+ billingType: apiKeyBillingType(parseModelProvider(model || null), accountingEnv),
571
+ costUsd: attempt.parsed.costUsd,
572
+ costStatus: attempt.parsed.usageComplete || attempt.parsed.costUsd != null ? undefined : "unpriced",
573
+ // A provider or output-observation timeout can arrive before the
574
+ // configured execution deadline. The boolean does not prove which
575
+ // timer fired, and provider stderr is not safe exception text.
576
+ errorMessage: "OpenCode execution timed out",
577
+ resultJson: { adapterExecutionTimeout },
578
+ clearSession: clearSessionOnMissingSession,
579
+ };
580
+ }
581
+ const resolvedSessionId = attempt.parsed.sessionId ??
582
+ (clearSessionOnMissingSession ? null : runtimeSessionId ?? runtime.sessionId ?? null);
583
+ const resolvedSessionParams = resolvedSessionId
584
+ ? {
585
+ sessionId: resolvedSessionId,
586
+ cwd: effectiveExecutionCwd,
587
+ ...(workspaceId ? { workspaceId } : {}),
588
+ ...(workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}),
589
+ ...(workspaceRepoRef ? { repoRef: workspaceRepoRef } : {}),
590
+ ...(executionTargetIsRemote
591
+ ? {
592
+ remoteExecution: adapterExecutionTargetSessionIdentity(runtimeExecutionTarget),
593
+ }
594
+ : {}),
595
+ }
596
+ : null;
597
+ const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : "";
598
+ const stderrLine = firstNonEmptyLine(attempt.proc.stderr);
599
+ const rawExitCode = attempt.proc.exitCode;
600
+ const synthesizedExitCode = parsedError && (rawExitCode ?? 0) === 0 ? 1 : rawExitCode;
601
+ const fallbackErrorMessage = parsedError ||
602
+ stderrLine ||
603
+ `OpenCode exited with code ${synthesizedExitCode ?? -1}`;
604
+ const modelId = model || null;
605
+ return {
606
+ exitCode: synthesizedExitCode,
607
+ signal: attempt.proc.signal,
608
+ timedOut: false,
609
+ usageComplete: attempt.proc.exitCode === 0 && !attempt.proc.signal
610
+ && (attempt.parsed.usageComplete || attempt.parsed.costUsd != null),
611
+ usageBasis: "per_run",
612
+ errorMessage: (synthesizedExitCode ?? 0) === 0 ? null : fallbackErrorMessage,
613
+ // Forward the transport-level error code from the run-disposition seam.
614
+ // A lost duplex control channel surfaces the typed `duplex_channel_lost`
615
+ // code; every other result carries no code here.
616
+ errorCode: attempt.proc.errorCode ?? null,
617
+ usage: attempt.parsed.usageReported ? attempt.parsed.usage : undefined,
618
+ sessionId: resolvedSessionId,
619
+ sessionParams: resolvedSessionParams,
620
+ sessionDisplayId: resolvedSessionId,
621
+ provider: parseModelProvider(modelId),
622
+ biller: resolveOpenCodeBiller(accountingEnv, parseModelProvider(modelId)),
623
+ model: modelId,
624
+ billingType: apiKeyBillingType(parseModelProvider(modelId), accountingEnv),
625
+ costUsd: attempt.parsed.costUsd,
626
+ costStatus: attempt.parsed.usageComplete || attempt.parsed.costUsd != null ? undefined : "unpriced",
627
+ resultJson: {
628
+ adapterExecutionTimeout,
629
+ stdout: attempt.proc.stdout,
630
+ stderr: attempt.proc.stderr,
631
+ },
632
+ summary: attempt.parsed.summary,
633
+ clearSession: Boolean(clearSessionOnMissingSession && !attempt.parsed.sessionId),
634
+ };
635
+ };
636
+ const initial = await runAttempt(sessionId);
637
+ const initialFailed = !initial.proc.timedOut && ((initial.proc.exitCode ?? 0) !== 0 || Boolean(initial.parsed.errorMessage));
638
+ if (sessionId &&
639
+ initialFailed &&
640
+ isOpenCodeUnknownSessionError(initial.proc.stdout, initial.rawStderr)) {
641
+ await onLog("stdout", `[paperclip] OpenCode session "${sessionId}" is unavailable; retrying with a fresh session.\n`);
642
+ const retry = await runAttempt(null);
643
+ return toResult(retry, true);
644
+ }
645
+ return toResult(initial);
646
+ }
647
+ finally {
648
+ try {
649
+ await providerStop.collectBeforeRestore();
650
+ }
651
+ finally {
652
+ await Promise.all([
653
+ paperclipBridge?.stop(),
654
+ restoreRemoteWorkspace?.(),
655
+ localSkillsDir ? fs.rm(path.dirname(localSkillsDir), { recursive: true, force: true }).catch(() => undefined) : Promise.resolve(),
656
+ ]);
657
+ }
658
+ }
659
+ }
660
+ finally {
661
+ await preparedRuntimeConfig.cleanup();
662
+ }
663
+ }
664
+ //# sourceMappingURL=execute.js.map