The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix(opencode): report timeouts without claiming deadline expiry (#15789)
Devin Foleycaa7895f9a0c
diff --git a/doc/observability.md b/doc/observability.mdindex 021c26ec87..7d17a9f564 100644--- a/doc/observability.md+++ b/doc/observability.md@@ -628,7 +628,7 @@ pending. Recent events do not prove useful progress. These fields contain onlynumbers and a boolean, never tool names, IDs, arguments, or event content, anddo not change the execution timeout, cancellation, or recovery policy.-ACP results retain the adapter's resolved wall-clock timeout as+ACP and legacy OpenCode results retain the adapter's resolved wall-clock timeout as`adapterExecutionTimeout` in the instance run result. Finalization uses it for`effectiveTimeoutSec`, `timeoutSource`, and `timeoutConfigured`. Sources are`configured`, `sandbox_default`, or `unlimited`; `timeoutConfigured` identifies an@@ -636,6 +636,12 @@ explicit override, including a negative value that disables the timer. An untoucsandbox value of zero reports the four-hour default, while a local zero reportsunlimited. Older adapters without a valid resolution retain the config-basedmetadata fallback. This does not change timers, Stop acknowledgement, or recovery.+Legacy OpenCode reports a generic timeout message because a provider or output+observation timeout can occur before the configured execution deadline. The+resolved policy describes the configured limit, not proof that its timer fired;+`timeoutFired` retains the existing terminal timeout classification. Provider+stderr remains in the instance run log and is not used as the timeout exception+message. An earlier provider timeout does not establish its upstream cause.When settlement records a workspace restore failure, `run_execution` alsoincludes `workspaceRestoreFailure` with one of the shared, path-free codes:diff --git a/packages/adapters/opencode-local/src/server/execute.timeout.test.ts b/packages/adapters/opencode-local/src/server/execute.timeout.test.tsnew file mode 100644index 0000000000..748e88d5c1--- /dev/null+++ b/packages/adapters/opencode-local/src/server/execute.timeout.test.ts@@ -0,0 +1,97 @@+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { AdapterExecutionContext } from "@paperclipai/adapter-utils";+import type { RunProcessResult } from "@paperclipai/adapter-utils/server-utils";++const mocks = vi.hoisted(() => ({+ process: vi.fn(), restore: vi.fn(), stop: vi.fn(),+}));+vi.mock("@paperclipai/adapter-utils/execution-target", async (importOriginal) => ({+ ...await importOriginal<typeof import("@paperclipai/adapter-utils/execution-target")>(),+ ensureAdapterExecutionTargetRuntimeCommandInstalled: vi.fn(),+ ensureAdapterExecutionTargetCommandResolvable: vi.fn(),+ prepareAdapterExecutionTargetRuntime: vi.fn(async () => ({+ runtimeRootDir: "/workspace/runtime", workspaceRemoteDir: "/workspace",+ assetDirs: {}, restoreWorkspace: mocks.restore,+ })),+ readAdapterExecutionTargetHomeDir: vi.fn(async () => "/home/fixture"),+ startAdapterExecutionTargetPaperclipBridge: vi.fn(async () => ({ env: {}, stop: mocks.stop })),+ runAdapterExecutionTargetProcess: mocks.process,+}));+import { execute } from "./execute.js";++const rawOutput = "private-output-canary";+const rawError = "<html>504 Gateway Time-out private-provider-token-canary</html>";+const failed: RunProcessResult = {+ timedOut: true, exitCode: null, signal: null, stdout: rawOutput, stderr: rawError,+ pid: null, startedAt: "2020-01-01T00:00:00.000Z", durationMs: 100,+};++describe("OpenCode timeout reporting", () => {+ let dir: string;+ beforeEach(async () => {+ dir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-timeout-"));+ vi.stubEnv("XDG_CONFIG_HOME", dir);+ mocks.process.mockReset().mockResolvedValue(failed);+ mocks.restore.mockReset().mockResolvedValue(undefined);+ mocks.stop.mockReset().mockResolvedValue(undefined);+ });+ afterEach(async () => {+ vi.unstubAllEnvs();+ await fs.rm(dir, { recursive: true, force: true });+ });+ const context = (timeoutSec: number, remote = true): AdapterExecutionContext => ({+ runId: "run-fixture",+ agent: { id: "agent-fixture", companyId: "company-fixture", name: "Fixture", adapterType: "opencode_local", adapterConfig: {} },+ runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },+ config: { command: "opencode", model: "openai/fixture", cwd: dir, timeoutSec,+ env: { OPENCODE_ALLOW_ALL_MODELS: "1" } },+ context: {}, onLog: async () => {},+ ...(remote ? { executionTarget: { kind: "remote", transport: "sandbox", remoteCwd: "/workspace" } } : {}),+ });++ it.each([+ [0, true, 14400, "sandbox_default"], [12, true, 12, "configured"],+ [-1, true, 0, "configured"], [0, false, 0, "unlimited"], [12, false, 12, "configured"],+ ] as const)("keeps policy separate from an opaque timeout (%s, remote=%s)", async (configured, remote, resolved, source) => {+ const result = await execute(context(configured, remote));+ expect(result).toMatchObject({ timedOut: true, exitCode: null, signal: null,+ errorMessage: "OpenCode execution timed out",+ resultJson: { adapterExecutionTimeout: { timeoutSec: resolved, source } } });+ expect(JSON.stringify(result)).not.toContain("private-");+ expect(result.errorMessage).not.toContain(String(resolved));+ expect(mocks.process).toHaveBeenCalledTimes(1);+ expect(mocks.process.mock.calls[0]![4]).toMatchObject({ timeoutSec: resolved, graceSec: 20 });+ expect(mocks.restore).toHaveBeenCalledTimes(remote ? 1 : 0);+ expect(mocks.stop).toHaveBeenCalledTimes(remote ? 1 : 0);+ });++ it.each([0, 7])("retains output and completion semantics for a non-timeout exit %s", async (exitCode) => {+ mocks.process.mockResolvedValue({ ...failed, timedOut: false, exitCode, stderr: "fixture failure" });+ const result = await execute(context(0));+ expect(result).toMatchObject({ timedOut: false, exitCode, signal: null,+ errorMessage: exitCode === 0 ? null : "fixture failure",+ resultJson: { stdout: rawOutput, stderr: "fixture failure",+ adapterExecutionTimeout: { timeoutSec: 14400, source: "sandbox_default" } } });+ expect(mocks.process).toHaveBeenCalledTimes(1);+ expect(mocks.restore).toHaveBeenCalledTimes(1);+ expect(mocks.stop).toHaveBeenCalledTimes(1);+ });++ it("retains real local deadline and termination behavior without claiming provider origin", async () => {+ const actual = await vi.importActual<typeof import("@paperclipai/adapter-utils/execution-target")>("@paperclipai/adapter-utils/execution-target");+ mocks.process.mockImplementation(actual.runAdapterExecutionTargetProcess);+ const command = path.join(dir, "fixture-opencode");+ await fs.writeFile(command, "#!/usr/bin/env node\nsetInterval(() => {}, 1000);\n", { mode: 0o755 });+ const ctx = context(0.1, false);+ ctx.config.command = command;+ ctx.config.graceSec = 0.1;+ const result = await execute(ctx);+ expect(result).toMatchObject({ timedOut: true, exitCode: null, signal: "SIGTERM",+ errorMessage: "OpenCode execution timed out",+ resultJson: { adapterExecutionTimeout: { timeoutSec: 0.1, source: "configured" } } });+ expect(mocks.process).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/adapters/opencode-local/src/server/execute.ts b/packages/adapters/opencode-local/src/server/execute.tsindex abd105704e..a7458fd3d9 100644--- a/packages/adapters/opencode-local/src/server/execute.ts+++ b/packages/adapters/opencode-local/src/server/execute.ts@@ -21,7 +21,7 @@ import {adapterExecutionTargetEnablesSandboxDuplexBridge,readAdapterExecutionTarget,readAdapterExecutionTargetHomeDir,- resolveAdapterExecutionTargetTimeoutSec,+ resolveAdapterExecutionTargetTimeout,resolveAdapterExecutionTargetCommandForLogs,runAdapterExecutionTargetProcess,runAdapterExecutionTargetShellCommand,@@ -338,10 +338,11 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec(entry): entry is [string, string] => typeof entry[1] === "string",),);- const timeoutSec = resolveAdapterExecutionTargetTimeoutSec(+ const adapterExecutionTimeout = resolveAdapterExecutionTargetTimeout(executionTarget,asNumber(config.timeoutSec, 0),);+ const timeoutSec = adapterExecutionTimeout.timeoutSec;const graceSec = asNumber(config.graceSec, 20);await ensureAdapterExecutionTargetRuntimeCommandInstalled({runId,@@ -710,7 +711,11 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExecbillingType: "unknown",costUsd: attempt.parsed.costUsd,costStatus: attempt.parsed.usageComplete || attempt.parsed.costUsd != null ? undefined : "unpriced",- errorMessage: `Timed out after ${timeoutSec}s`,+ // A provider or output-observation timeout can arrive before the+ // configured execution deadline. The boolean does not prove which+ // timer fired, and provider stderr is not safe exception text.+ errorMessage: "OpenCode execution timed out",+ resultJson: { adapterExecutionTimeout },clearSession: clearSessionOnMissingSession,};}@@ -766,6 +771,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExeccostUsd: attempt.parsed.costUsd,costStatus: attempt.parsed.usageComplete || attempt.parsed.costUsd != null ? undefined : "unpriced",resultJson: {+ adapterExecutionTimeout,stdout: attempt.proc.stdout,stderr: attempt.proc.stderr,},diff --git a/server/src/__tests__/run-failure-sentry-real-sdk.test.ts b/server/src/__tests__/run-failure-sentry-real-sdk.test.tsindex 2c87920508..63ccef13bf 100644--- a/server/src/__tests__/run-failure-sentry-real-sdk.test.ts+++ b/server/src/__tests__/run-failure-sentry-real-sdk.test.ts@@ -1,5 +1,9 @@import { captureEnvironmentAcquisitionDiagnostic } from "../services/environment-acquisition-diagnostics.js";import { createRequire } from "node:module";+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { buildHeartbeatRunStopMetadata, mergeHeartbeatRunStopMetadata } from "../services/heartbeat-stop-metadata.js";import { afterEach, describe, expect, it, vi } from "vitest";import { collectRunFailureDiagnostics, sanitizeRunFailureDiagnostics } from "../services/run-failure-diagnostics.js";import type { heartbeatRuns } from "@paperclipai/db";@@ -39,10 +43,90 @@ afterEach(async () => {vi.unstubAllEnvs();vi.doUnmock("@sentry/node");vi.doUnmock("../peer-version-check.js");+ vi.doUnmock("@paperclipai/adapter-utils/execution-target");vi.resetModules();});describe.skipIf(!sentryPackage)("run failure context with the real Sentry SDK", () => {+ it("captures an early OpenCode timeout without inventing a deadline or exporting provider output", async () => {+ const Sentry = sentryPackage!;+ const events: Array<Record<string, unknown>> = [];+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-sentry-"));+ const restore = vi.fn(async () => {});+ const stop = vi.fn(async () => {});+ const processResult = {+ exitCode: null, signal: null, timedOut: true, pid: null,+ startedAt: "2020-01-01T00:00:00.000Z", durationMs: 100,+ stdout: "private-timeout-output-canary",+ stderr: "<html>504 Gateway Time-out private-timeout-credential-canary</html>",+ };+ const runProcess = vi.fn(async () => processResult);+ vi.stubEnv("XDG_CONFIG_HOME", root);+ vi.stubEnv("SENTRY_DSN_BACKEND", "https://[email protected]/1");+ vi.doMock("../peer-version-check.js", () => ({ checkExactPeerVersions: () => ({ ok: true }) }));+ vi.doMock("@sentry/node", () => ({ ...Sentry,+ init: (options: Record<string, unknown>) => Sentry.init({ ...options,+ transport: () => ({ send: async (envelope: [unknown, Array<[{ type: string }, Record<string, unknown>]>]) => {+ for (const [header, payload] of envelope[1]) if (header.type === "event") events.push(payload);+ return {};+ }, flush: async () => true }),+ }),+ }));+ // Only external execution/setup seams are replaced. The real adapter owns+ // the message/policy, and the real finalization/collector/SDK send the event.+ vi.doMock("@paperclipai/adapter-utils/execution-target", async (importOriginal) => ({+ ...await importOriginal<typeof import("@paperclipai/adapter-utils/execution-target")>(),+ ensureAdapterExecutionTargetRuntimeCommandInstalled: vi.fn(),+ ensureAdapterExecutionTargetCommandResolvable: vi.fn(),+ prepareAdapterExecutionTargetRuntime: vi.fn(async () => ({+ runtimeRootDir: "/workspace/runtime", workspaceRemoteDir: "/workspace",+ assetDirs: {}, restoreWorkspace: restore,+ })),+ readAdapterExecutionTargetHomeDir: vi.fn(async () => "/home/fixture"),+ startAdapterExecutionTargetPaperclipBridge: vi.fn(async () => ({ env: {}, stop })),+ runAdapterExecutionTargetProcess: runProcess,+ }));+ vi.resetModules();+ try {+ const { execute } = await import("@paperclipai/adapter-opencode-local/server");+ const { sentryReady, captureRunFailure, captureException } = await import("../sentry.js");+ await sentryReady;+ const result = await execute({+ runId: "22222222-2222-4222-8222-222222222222",+ agent: { id: "agent-fixture", companyId: "company-fixture", name: "Fixture", adapterType: "opencode_local", adapterConfig: {} },+ runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },+ config: { command: "opencode", model: "openai/fixture", cwd: root, timeoutSec: 0,+ env: { OPENCODE_ALLOW_ALL_MODELS: "1" } },+ context: {}, onLog: async () => {},+ executionTarget: { kind: "remote", transport: "sandbox", remoteCwd: "/workspace" },+ });+ expect(result).toMatchObject({ timedOut: true, exitCode: null, signal: null });+ expect(runProcess).toHaveBeenCalledTimes(1);+ expect(restore).toHaveBeenCalledTimes(1);+ expect(stop).toHaveBeenCalledTimes(1);+ const resultJson = mergeHeartbeatRunStopMetadata(result.resultJson,+ buildHeartbeatRunStopMetadata({ adapterType: "opencode_local", adapterConfig: { timeoutSec: 0 }, outcome: "timed_out" }));+ const diagnostics = sanitizeRunFailureDiagnostics(collectRunFailureDiagnostics({+ errorCode: "timeout", resultJson,+ startedAt: new Date("2020-01-01T00:00:00.000Z"), finishedAt: new Date("2020-01-01T00:00:00.100Z"),+ } as typeof heartbeatRuns.$inferSelect, { phase: "execute" }));+ captureRunFailure({ taskId: "11111111-1111-4111-8111-111111111111", runId: "22222222-2222-4222-8222-222222222222",+ errorMessage: result.errorMessage!, errorCode: "timeout", agentAdapter: "opencode_local",+ runStatus: "timed_out", exitCode: result.exitCode, signal: result.signal, diagnostics });+ captureException(new Error("Unrelated timeout fixture"));+ await Sentry.flush(2000);+ expect(events).toHaveLength(2);+ const event = events.find(entry => (entry.tags as Record<string, unknown>)?.error_code === "timeout");+ expect(event).toMatchObject({ exception: { values: [{ value: "OpenCode execution timed out" }] },+ contexts: { run_execution: { durationMs: 100, effectiveTimeoutSec: 14400,+ timeoutSource: "sandbox_default", timeoutConfigured: false, timeoutFired: true, stopReason: "timeout" } } });+ expect(JSON.stringify(events)).not.toMatch(/private-timeout-|<html>|504|Timed out after/);+ expect(events.find(entry => entry !== event)).not.toHaveProperty("contexts.run_execution");+ } finally {+ await fs.rm(root, { recursive: true, force: true });+ }+ });+it("sends only owned acquisition observations and isolates unrelated captures", async () => {const Sentry = sentryPackage!;const events: Array<Record<string, unknown>> = [];