mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-06 23:20:53 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Legacy sandbox runs copy the agent's workspace files back to the host when the run settles. > - When this copy-back fails one time, the server keeps the sandbox and puts a board-owned repair hold on the task. > - The hold blocks new messages. Only an operator API runbook can clear it. The board shows that runbook text, so users do not know what to do. > - Many copy-back failures are transient: a dropped transfer, a provider error, or a merge lock that another restore holds. > - This pull request retries those failures automatically while the run still has its merge baseline and before any host file changes. > - The benefit is that most failures repair themselves, and the remaining holds explain the situation in plain language. ## Linked Issues or Issue Description Refs #14590 (related: no-replay recovery holds) **What happened?** A legacy sandbox run finished its work, but one workspace copy-back attempt failed. The task then showed "Recovery needed" with operator-only steps ("verify its exact stop receipt … record workspaceRepairEvidence"). Messages from the user stayed saved and were not delivered. **What did you expect?** Paperclip retries a transient copy-back failure automatically. If a repair is still necessary, the task says clearly what happened and who must act. **Steps to reproduce** 1. Run an agent in a legacy sandbox environment. 2. Make the workspace copy-back fail one time, for example with a dropped transfer or a held merge lock. 3. Open the task. It is blocked behind a repair hold, and new messages wait. **Additional context** Separately, distinct live events can render toasts with the same title and body (for example, two runs of the same agent that both succeed). The toast list showed both, and the desktop app forwards each one as a notification. ## What Changed - `packages/adapter-utils/src/sandbox-managed-runtime.ts`: retry the workspace copy-back up to three times in total, with a 2 s and then a 5 s backoff. A retry occurs only when the failure is `restore_failed` or `restore_lock_timeout` and no host workspace file was written. The merge now marks the first host write in `beforeApply`, which runs under the merge lock before any write. - Unsafe archives, permission failures, and failures after the merge started writing are never retried. Each retry uses a new temp directory and a new imported Git ref. - New optional `workspaceRestoreRetryDelaysMs` input, so tests can shorten the backoff. Nested repository restores receive the same value. - `ui/src/components/ExecutionBlockerNotice.tsx`: for a workspace repair hold, the notice now says what happened in plain language. The stored operator runbook text moves under "Technical details". - `ui/src/context/ToastContext.tsx`: also dedupe toasts on their visible tone, title, and body inside the existing 3.5 s window. - `doc/workspace-restore-locks.md`: document the automatic retry. ## Verification - `pnpm --filter @paperclipai/adapter-utils exec vitest run src/sandbox-managed-runtime.test.ts src/workspace-restore` (218 tests pass). New tests cover: - a retry after a dropped transfer, - a retry after a merge-lock timeout, - a stop after three attempts, - no retry for an unsafe archive, a permission failure, or a failure after the merge started writing. - The existing step-diagnostic test now uses failures that persist across retries. It still expects one diagnostic per failed step. - `pnpm --filter @paperclipai/ui exec vitest run src/context/ToastContext.test.tsx src/components/ExecutionBlockerNotice.test.tsx src/context/LiveUpdatesProvider` (120 tests pass). - `tsc --noEmit` for adapter-utils passes. `node scripts/check-token-gates.mjs` is clean. - Not fully run: the full adapter-utils suite has two failures in `github-launcher*.test.ts`. They read the managed GitHub credentials of the local sandbox environment and do not touch restore code. UI `tsc -b` reports five errors in `PluginOrganizationSwitcher.tsx`, which is not changed here, because the plugin SDK is not built in a fresh install. ## Risks - A copy-back that fails before the merge can take about 7 s longer before it reports a failure. Lock timeouts can take up to about 97 s in total (three 30 s lock waits plus backoff). Settlement already waits for the copy-back. - The retry logic depends on `beforeApply` running before the first host write in `mergeDirectoryWithBaseline`. That is true today, and a comment marks it. - A Git bundle import before the merge can leave unreferenced Git objects after a retry. They are harmless, and the existing ref cleanup still runs on each attempt. - Content-based toast dedupe can hide a second toast with identical text inside 3.5 s. That is the intended behavior. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`, Anthropic) in the Claude Agent SDK, with tool use (shell, file edit, code search) and a subagent for code exploration. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Paperclip Agent <agent@paperclip.ing> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
479 lines
19 KiB
TypeScript
479 lines
19 KiB
TypeScript
import fs from "node:fs/promises";
|
||
import os from "node:os";
|
||
import path from "node:path";
|
||
import type {
|
||
AdapterEnvironmentCheck,
|
||
AdapterEnvironmentTestContext,
|
||
AdapterEnvironmentTestResult,
|
||
} from "@paperclipai/adapter-utils";
|
||
import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
|
||
import {
|
||
asBoolean,
|
||
asNumber,
|
||
asString,
|
||
asStringArray,
|
||
parseObject,
|
||
ensurePathInEnv,
|
||
} from "@paperclipai/adapter-utils/server-utils";
|
||
import {
|
||
ensureAdapterExecutionTargetCommandResolvable,
|
||
maybeRunSandboxInstallCommand,
|
||
ensureAdapterExecutionTargetDirectory,
|
||
runAdapterExecutionTargetProcess,
|
||
describeAdapterExecutionTarget,
|
||
resolveAdapterExecutionTargetCwd,
|
||
prepareAdapterExecutionTargetRuntime,
|
||
overrideAdapterExecutionTargetRemoteCwd,
|
||
} from "@paperclipai/adapter-utils/execution-target";
|
||
import { discoverOpenCodeModels, ensureOpenCodeModelConfiguredAndAvailable, requireOpenCodeModelId } from "./models.js";
|
||
import { parseOpenCodeJsonl } from "./parse.js";
|
||
import { SANDBOX_INSTALL_COMMAND } from "../index.js";
|
||
import { prepareOpenCodeRuntimeConfig, prepareManagedOpenCodeRemoteHomes } from "./runtime-config.js";
|
||
|
||
function summarizeStatus(checks: AdapterEnvironmentCheck[]): AdapterEnvironmentTestResult["status"] {
|
||
if (checks.some((check) => check.level === "error")) return "fail";
|
||
if (checks.some((check) => check.level === "warn")) return "warn";
|
||
return "pass";
|
||
}
|
||
|
||
function firstNonEmptyLine(text: string): string {
|
||
return (
|
||
text
|
||
.split(/\r?\n/)
|
||
.map((line) => line.trim())
|
||
.find(Boolean) ?? ""
|
||
);
|
||
}
|
||
|
||
function summarizeProbeDetail(stdout: string, stderr: string, parsedError: string | null): string | null {
|
||
const raw = parsedError?.trim() || firstNonEmptyLine(stderr) || firstNonEmptyLine(stdout);
|
||
if (!raw) return null;
|
||
const clean = raw.replace(/\s+/g, " ").trim();
|
||
const max = 240;
|
||
return clean.length > max ? `${clean.slice(0, max - 1)}...` : clean;
|
||
}
|
||
|
||
function normalizeEnv(input: unknown): Record<string, string> {
|
||
if (typeof input !== "object" || input === null || Array.isArray(input)) return {};
|
||
const env: Record<string, string> = {};
|
||
for (const [key, value] of Object.entries(input as Record<string, unknown>)) {
|
||
if (typeof value === "string") env[key] = value;
|
||
}
|
||
return env;
|
||
}
|
||
|
||
const OPENCODE_AUTH_REQUIRED_RE =
|
||
/(?:auth(?:entication)?\s+required|api\s*key|invalid\s*api\s*key|not\s+logged\s+in|opencode\s+auth\s+login|free\s+usage\s+exceeded)/i;
|
||
|
||
export async function testEnvironment(
|
||
ctx: AdapterEnvironmentTestContext,
|
||
): Promise<AdapterEnvironmentTestResult> {
|
||
const checks: AdapterEnvironmentCheck[] = [];
|
||
const config = parseObject(ctx.config);
|
||
const command = asString(config.command, "opencode");
|
||
const target = ctx.executionTarget ?? null;
|
||
const targetIsRemote = target?.kind === "remote";
|
||
const targetIsSandbox = target?.kind === "remote" && target.transport === "sandbox";
|
||
const cwd = resolveAdapterExecutionTargetCwd(target, asString(config.cwd, ""), process.cwd());
|
||
const targetLabel = targetIsRemote
|
||
? ctx.environmentName ?? describeAdapterExecutionTarget(target)
|
||
: null;
|
||
const runId = `opencode-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||
|
||
if (targetLabel) {
|
||
checks.push({
|
||
code: "opencode_environment_target",
|
||
level: "info",
|
||
message: `Probing inside environment: ${targetLabel}`,
|
||
});
|
||
}
|
||
|
||
try {
|
||
await ensureAdapterExecutionTargetDirectory(runId, target, cwd, {
|
||
cwd,
|
||
env: {},
|
||
createIfMissing: false,
|
||
});
|
||
checks.push({
|
||
code: "opencode_cwd_valid",
|
||
level: "info",
|
||
message: `Working directory is valid: ${cwd}`,
|
||
});
|
||
} catch (err) {
|
||
checks.push({
|
||
code: "opencode_cwd_invalid",
|
||
level: "error",
|
||
message: err instanceof Error ? err.message : "Invalid working directory",
|
||
detail: cwd,
|
||
});
|
||
}
|
||
|
||
const envConfig = parseObject(config.env);
|
||
const env: Record<string, string> = {};
|
||
for (const [key, value] of Object.entries(envConfig)) {
|
||
if (typeof value === "string") env[key] = value;
|
||
}
|
||
|
||
const openaiKeyOverride = "OPENAI_API_KEY" in envConfig ? asString(envConfig.OPENAI_API_KEY, "") : null;
|
||
if (!config.managedAiConnection && openaiKeyOverride !== null && openaiKeyOverride.trim() === "") {
|
||
checks.push({
|
||
code: "opencode_openai_api_key_missing",
|
||
level: "warn",
|
||
message: "OPENAI_API_KEY override is empty.",
|
||
hint: "The OPENAI_API_KEY override is empty. Set a valid key or remove the override.",
|
||
});
|
||
}
|
||
|
||
// Prevent OpenCode from writing an opencode.json into the working directory.
|
||
env.OPENCODE_DISABLE_PROJECT_CONFIG = "true";
|
||
const preparedRuntimeConfig = await prepareOpenCodeRuntimeConfig({ env, config });
|
||
const localRuntimeConfigHome =
|
||
preparedRuntimeConfig.notes.length > 0 ? preparedRuntimeConfig.env.XDG_CONFIG_HOME : "";
|
||
if (asBoolean(config.dangerouslySkipPermissions, true)) {
|
||
checks.push({
|
||
code: "opencode_headless_permissions_enabled",
|
||
level: "info",
|
||
message: "Headless OpenCode permissions are auto-approved for all tools and connections.",
|
||
});
|
||
}
|
||
let restoreWorkspace: (() => Promise<void>) | null = null;
|
||
// Declared outside `try` so a failure inside `prepareAdapterExecutionTargetRuntime`
|
||
// still has the path available for cleanup in `finally` — otherwise the
|
||
// `fs.mkdtemp` directory leaks on the early-throw path.
|
||
let preparedRuntimeWorkspaceLocalDir: string | null = null;
|
||
let nativeProbeWorkspaceLocalDir: string | null = null;
|
||
try {
|
||
let runtimeTarget: AdapterExecutionTarget | null = target ?? null;
|
||
let runtimeCwd = cwd;
|
||
// Native workspaces are assigned at execution time. A configuration probe
|
||
// without an explicit workspace must not run in the server's checkout.
|
||
if (!targetIsRemote && ctx.adapterType === "paperclip_runner" && !asString(config.cwd, "").trim()) {
|
||
nativeProbeWorkspaceLocalDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-native-probe-"));
|
||
runtimeCwd = nativeProbeWorkspaceLocalDir;
|
||
}
|
||
if (targetIsRemote) {
|
||
preparedRuntimeWorkspaceLocalDir = await fs.mkdtemp(path.join(os.tmpdir(), `paperclip-opencode-envtest-${runId}-`));
|
||
const preparedExecutionTargetRuntime = await prepareAdapterExecutionTargetRuntime({
|
||
runId,
|
||
target,
|
||
adapterKey: "opencode",
|
||
workspaceLocalDir: preparedRuntimeWorkspaceLocalDir,
|
||
workspaceRemoteDir: cwd,
|
||
installCommand: SANDBOX_INSTALL_COMMAND,
|
||
detectCommand: command,
|
||
// The probe workspace is a throwaway temp dir; never wait on copy-back retries.
|
||
workspaceRestoreRetryDelaysMs: [],
|
||
assets: localRuntimeConfigHome
|
||
? [{
|
||
key: "xdgConfig",
|
||
localDir: localRuntimeConfigHome,
|
||
}]
|
||
: [],
|
||
});
|
||
restoreWorkspace = async () => {
|
||
await preparedExecutionTargetRuntime.restoreWorkspace().catch(() => {});
|
||
if (preparedRuntimeWorkspaceLocalDir) {
|
||
await fs.rm(preparedRuntimeWorkspaceLocalDir, { recursive: true, force: true }).catch(() => {});
|
||
}
|
||
};
|
||
runtimeCwd = preparedExecutionTargetRuntime.workspaceRemoteDir ?? runtimeCwd;
|
||
runtimeTarget = overrideAdapterExecutionTargetRemoteCwd(target ?? null, runtimeCwd) ?? null;
|
||
if (localRuntimeConfigHome && preparedExecutionTargetRuntime.assetDirs.xdgConfig) {
|
||
preparedRuntimeConfig.env.XDG_CONFIG_HOME = preparedExecutionTargetRuntime.assetDirs.xdgConfig;
|
||
}
|
||
prepareManagedOpenCodeRemoteHomes({
|
||
env: preparedRuntimeConfig.env,
|
||
config,
|
||
runtimeRootDir: preparedExecutionTargetRuntime.runtimeRootDir,
|
||
runId,
|
||
configDir: preparedExecutionTargetRuntime.assetDirs.xdgConfig,
|
||
});
|
||
}
|
||
const runtimeEnv = normalizeEnv(ensurePathInEnv({ ...process.env, ...preparedRuntimeConfig.env }));
|
||
|
||
const cwdInvalid = checks.some((check) => check.code === "opencode_cwd_invalid");
|
||
if (cwdInvalid) {
|
||
checks.push({
|
||
code: "opencode_command_skipped",
|
||
level: "warn",
|
||
message: "Skipped command check because working directory validation failed.",
|
||
detail: command,
|
||
});
|
||
} else {
|
||
const installCheck = await maybeRunSandboxInstallCommand({
|
||
runId,
|
||
target,
|
||
adapterKey: "opencode",
|
||
installCommand: SANDBOX_INSTALL_COMMAND,
|
||
detectCommand: command,
|
||
env,
|
||
});
|
||
if (installCheck) checks.push(installCheck);
|
||
try {
|
||
await ensureAdapterExecutionTargetCommandResolvable(command, runtimeTarget, runtimeCwd, runtimeEnv);
|
||
checks.push({
|
||
code: "opencode_command_resolvable",
|
||
level: "info",
|
||
message: `Command is executable: ${command}`,
|
||
});
|
||
} catch (err) {
|
||
checks.push({
|
||
code: "opencode_command_unresolvable",
|
||
level: "error",
|
||
message: err instanceof Error ? err.message : "Command is not executable",
|
||
detail: command,
|
||
});
|
||
}
|
||
}
|
||
|
||
const canRunProbe =
|
||
checks.every((check) => check.code !== "opencode_cwd_invalid" && check.code !== "opencode_command_unresolvable");
|
||
|
||
let modelValidationPassed = false;
|
||
const configuredModel = asString(config.model, "").trim();
|
||
|
||
// The native runner already selects a concrete model. Its real hello probe
|
||
// verifies model access and credentials; a full catalog scan adds another
|
||
// cold CLI launch (and discovery retries) without verifying that request.
|
||
const nativeModelProbe = ctx.adapterType === "paperclip_runner" && Boolean(configuredModel);
|
||
|
||
// Model discovery and validation use local child processes against
|
||
// OpenCode's `models` subcommand and JSON config; these are not yet
|
||
// wired through the execution target. When probing a remote env, skip
|
||
// discovery/validation and rely on the remote hello probe to surface
|
||
// model/auth issues directly.
|
||
if (nativeModelProbe) {
|
||
try {
|
||
requireOpenCodeModelId(configuredModel);
|
||
modelValidationPassed = true;
|
||
checks.push({
|
||
code: "opencode_model_validation_via_probe",
|
||
level: "info",
|
||
message: "The configured native-runner model will be validated by the hello probe.",
|
||
});
|
||
} catch (error) {
|
||
checks.push({ code: "opencode_model_invalid", level: "error",
|
||
message: error instanceof Error ? error.message : "Configured model is invalid." });
|
||
}
|
||
} else if (targetIsRemote && configuredModel) {
|
||
checks.push({
|
||
code: "opencode_model_validation_skipped_remote",
|
||
level: "info",
|
||
message: `Skipped local model validation; will be validated by the hello probe inside ${targetLabel}.`,
|
||
});
|
||
modelValidationPassed = true;
|
||
} else if (canRunProbe && configuredModel) {
|
||
try {
|
||
const discovered = await discoverOpenCodeModels({ command, cwd, env: runtimeEnv });
|
||
if (discovered.length > 0) {
|
||
checks.push({
|
||
code: "opencode_models_discovered",
|
||
level: "info",
|
||
message: `Discovered ${discovered.length} model(s) from OpenCode providers.`,
|
||
});
|
||
} else {
|
||
checks.push({
|
||
code: "opencode_models_empty",
|
||
level: "error",
|
||
message: "OpenCode returned no models.",
|
||
hint: "Run `opencode models` and verify provider authentication.",
|
||
});
|
||
}
|
||
} catch (err) {
|
||
const errMsg = err instanceof Error ? err.message : String(err);
|
||
if (/ProviderModelNotFoundError/i.test(errMsg)) {
|
||
checks.push({
|
||
code: "opencode_hello_probe_model_unavailable",
|
||
level: "warn",
|
||
message: "The configured model was not found by the provider.",
|
||
detail: errMsg,
|
||
hint: "Run `opencode models` and choose an available provider/model ID.",
|
||
});
|
||
} else {
|
||
checks.push({
|
||
code: "opencode_models_discovery_failed",
|
||
level: "error",
|
||
message: errMsg || "OpenCode model discovery failed.",
|
||
hint: "Run `opencode models` manually to verify provider auth and config.",
|
||
});
|
||
}
|
||
}
|
||
} else if (!targetIsRemote && canRunProbe && !configuredModel) {
|
||
try {
|
||
const discovered = await discoverOpenCodeModels({ command, cwd, env: runtimeEnv });
|
||
if (discovered.length > 0) {
|
||
checks.push({
|
||
code: "opencode_models_discovered",
|
||
level: "info",
|
||
message: `Discovered ${discovered.length} model(s) from OpenCode providers.`,
|
||
});
|
||
}
|
||
} catch (err) {
|
||
const errMsg = err instanceof Error ? err.message : String(err);
|
||
if (/ProviderModelNotFoundError/i.test(errMsg)) {
|
||
checks.push({
|
||
code: "opencode_hello_probe_model_unavailable",
|
||
level: "warn",
|
||
message: "The configured model was not found by the provider.",
|
||
detail: errMsg,
|
||
hint: "Run `opencode models` and choose an available provider/model ID.",
|
||
});
|
||
} else {
|
||
checks.push({
|
||
code: "opencode_models_discovery_failed",
|
||
level: "warn",
|
||
message: errMsg || "OpenCode model discovery failed (best-effort, no model configured).",
|
||
hint: "Run `opencode models` manually to verify provider auth and config.",
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
const modelUnavailable = checks.some((check) => check.code === "opencode_hello_probe_model_unavailable");
|
||
if (!configuredModel && !modelUnavailable) {
|
||
// No model configured – skip model requirement if no model-related checks exist
|
||
} else if (!nativeModelProbe && !targetIsRemote && configuredModel && canRunProbe) {
|
||
try {
|
||
await ensureOpenCodeModelConfiguredAndAvailable({
|
||
model: configuredModel,
|
||
command,
|
||
cwd,
|
||
env: runtimeEnv,
|
||
});
|
||
checks.push({
|
||
code: "opencode_model_configured",
|
||
level: "info",
|
||
message: `Configured model: ${configuredModel}`,
|
||
});
|
||
modelValidationPassed = true;
|
||
} catch (err) {
|
||
checks.push({
|
||
code: "opencode_model_invalid",
|
||
level: "error",
|
||
message: err instanceof Error ? err.message : "Configured model is unavailable.",
|
||
hint: "Run `opencode models` and choose a currently available provider/model ID.",
|
||
});
|
||
}
|
||
}
|
||
|
||
if (canRunProbe && modelValidationPassed) {
|
||
const extraArgs = (() => {
|
||
const fromExtraArgs = asStringArray(config.extraArgs);
|
||
if (fromExtraArgs.length > 0) return fromExtraArgs;
|
||
return asStringArray(config.args);
|
||
})();
|
||
const variant = asString(config.variant, "").trim();
|
||
const probeModel = configuredModel;
|
||
|
||
const args = ["run", "--format", "json"];
|
||
args.push("--model", probeModel);
|
||
if (variant) args.push("--variant", variant);
|
||
if (extraArgs.length > 0) args.push(...extraArgs);
|
||
|
||
// Sandbox bridges still add cold-start and transport overhead, but the
|
||
// standard-2 Cloudflare tier now probes quickly enough that 90s keeps
|
||
// useful headroom without letting slow hangs linger.
|
||
const helloProbeTimeoutSec = Math.max(
|
||
1,
|
||
asNumber(config.helloProbeTimeoutSec, targetIsSandbox ? 90 : 60),
|
||
);
|
||
|
||
try {
|
||
const probe = await runAdapterExecutionTargetProcess(
|
||
runId,
|
||
runtimeTarget,
|
||
command,
|
||
args,
|
||
{
|
||
cwd: runtimeCwd,
|
||
env: runtimeEnv,
|
||
timeoutSec: helloProbeTimeoutSec,
|
||
graceSec: 5,
|
||
stdin: "Respond with hello.",
|
||
onLog: async () => {},
|
||
},
|
||
);
|
||
|
||
const parsed = parseOpenCodeJsonl(probe.stdout);
|
||
const detail = summarizeProbeDetail(probe.stdout, probe.stderr, parsed.errorMessage);
|
||
const authEvidence = `${parsed.errorMessage ?? ""}\n${probe.stdout}\n${probe.stderr}`.trim();
|
||
|
||
if (probe.timedOut) {
|
||
checks.push({
|
||
code: "opencode_hello_probe_timed_out",
|
||
level: "warn",
|
||
message: "OpenCode hello probe timed out.",
|
||
hint: "Retry the probe. If this persists, run OpenCode manually in this working directory.",
|
||
});
|
||
} else if ((probe.exitCode ?? 1) === 0 && !parsed.errorMessage) {
|
||
const summary = parsed.summary.trim();
|
||
const hasHello = /\bhello\b/i.test(summary);
|
||
checks.push({
|
||
code: hasHello ? "opencode_hello_probe_passed" : "opencode_hello_probe_unexpected_output",
|
||
level: hasHello ? "info" : "warn",
|
||
message: hasHello
|
||
? "OpenCode hello probe succeeded."
|
||
: "OpenCode probe ran but did not return `hello` as expected.",
|
||
...(summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}),
|
||
...(hasHello
|
||
? {}
|
||
: {
|
||
hint: "Run `opencode run --format json` manually and prompt `Respond with hello` to inspect output.",
|
||
}),
|
||
});
|
||
} else if (/ProviderModelNotFoundError/i.test(authEvidence)) {
|
||
checks.push({
|
||
code: "opencode_hello_probe_model_unavailable",
|
||
level: "warn",
|
||
message: "The configured model was not found by the provider.",
|
||
...(detail ? { detail } : {}),
|
||
hint: "Run `opencode models` and choose an available provider/model ID.",
|
||
});
|
||
} else if (OPENCODE_AUTH_REQUIRED_RE.test(authEvidence)) {
|
||
checks.push({
|
||
code: "opencode_hello_probe_auth_required",
|
||
level: "warn",
|
||
message: "OpenCode is installed, but provider authentication is not ready.",
|
||
...(detail ? { detail } : {}),
|
||
hint: "Run `opencode auth login` or set provider credentials, then retry the probe.",
|
||
});
|
||
} else {
|
||
checks.push({
|
||
code: "opencode_hello_probe_failed",
|
||
level: "error",
|
||
message: "OpenCode hello probe failed.",
|
||
...(detail ? { detail } : {}),
|
||
hint: "Run `opencode run --format json` manually in this working directory to debug.",
|
||
});
|
||
}
|
||
} catch (err) {
|
||
checks.push({
|
||
code: "opencode_hello_probe_failed",
|
||
level: "error",
|
||
message: "OpenCode hello probe failed.",
|
||
detail: err instanceof Error ? err.message : String(err),
|
||
hint: "Run `opencode run --format json` manually in this working directory to debug.",
|
||
});
|
||
}
|
||
}
|
||
} finally {
|
||
if (nativeProbeWorkspaceLocalDir) {
|
||
await fs.rm(nativeProbeWorkspaceLocalDir, { recursive: true, force: true }).catch(() => {});
|
||
}
|
||
await restoreWorkspace?.();
|
||
if (!restoreWorkspace && preparedRuntimeWorkspaceLocalDir) {
|
||
// Reached when `prepareAdapterExecutionTargetRuntime` threw before
|
||
// assigning `restoreWorkspace`: clean up the temp dir directly.
|
||
await fs.rm(preparedRuntimeWorkspaceLocalDir, { recursive: true, force: true }).catch(() => {});
|
||
}
|
||
await preparedRuntimeConfig.cleanup();
|
||
}
|
||
|
||
return {
|
||
adapterType: ctx.adapterType,
|
||
status: summarizeStatus(checks),
|
||
checks,
|
||
testedAt: new Date().toISOString(),
|
||
};
|
||
}
|