mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 22:49:00 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - OpenCode agents can use models through OpenRouter, and the Runner proxies those model calls > - OpenRouter routes one model across many hosts, and these hosts use different quantizations (fp4, mxfp4, fp8) > - Chat evaluations with identical prompts behave very differently between runs, but the run log does not record which host served a call > - The run usage shows `provider: "deepseek"` and `biller: "openrouter"`, and `providerRequestId` is always `null` > - This pull request records the serving host and the OpenRouter generation ID for each model call in the run log > - The benefit is that we can compare evaluation cohorts by host, and the cost event names a real OpenRouter generation ## Linked Issues or Issue Description **Subsystem affected** Runner OpenCode provider proxy, runnerd usage normalization, and native run usage accounting. **Problem or motivation** OpenRouter's default routing sends a request to one of many hosts. Each host can use a different quantization. Chat evaluation results change a lot between runs with identical prompts. Paperclip does not record which host served a call, so we cannot compare results by host. `usageJson.providerRequestId` is always `null` for OpenCode runs. **Proposed solution** Every OpenRouter completion response has a top-level `provider` field and an `id` (the generation ID). Each streamed chunk has them too. The Runner proxy reads them from the first chunk after it forwards the bytes. The Runner attaches them to the usage of that call. The values go to the run log, and the run's first generation ID goes to `usageJson.providerRequestId`. **Alternatives considered** A new PRP event type such as `provider.upstream.served` would need a new event enum value. An older control plane rejects an unknown event type. A `harness.diagnostic` event shows in the task chat as a diagnostic. The usage payload already flows to every consumer, and older consumers ignore extra fields. Thus this change uses the usage payload. **Additional context** Run-log change only (AGENTS.md section 7). The data stays in `heartbeat_run_events` and `heartbeat_runs.usageJson`. It does not touch `packages/shared/src/telemetry/` or OpenTelemetry. ## What Changed - New `createUpstreamServedTap` (`packages/paperclip-runner/src/drivers/opencode/upstream-served.ts`). It is a pass-through stream. It pushes each chunk downstream first, then it reads `provider` and `id` from the first SSE `data:` event (or from a JSON body at its end). It scans at most 64 KiB of a stream and 1 MiB of a JSON body. It skips encoded bodies and unknown content types. Any parse problem or recorder error stops the scan and leaves the response unchanged. - `startOpenCodeProviderProxy` uses the tap only for 2xx responses. The OpenCode session keeps the most recent served call. Each `item.completed` usage payload and `session.usage()` now carry `upstreamProvider` and `providerRequestId`. The usage dedupe fingerprint does not include these fields, so the number of usage events does not change. - The OpenCode app-server proxy adds the two fields to `thread/tokenUsage/updated`. Rust `usage.reported` now fills its existing `providerRequestId` field and adds an optional `upstreamProvider`. The TypeScript runnerd transport keeps both fields when it rehydrates the usage notification. `usage.schema.json` documents `upstreamProvider` (the protocol manifest and schema bundle are regenerated). - Server native turn accounting keeps the first generation ID the run reports. The usage checkpoint and the native adapter result carry it as `providerRequestId`, so `usageJson.providerRequestId` and the final cost event name it. - `doc/run-log-events.md` documents the fields in a new "OpenRouter serving host" section. ## Verification - Red/green: `opencode-server-driver.test.ts` "passes OpenRouter's stream through unchanged and records the host that served it on the turn's usage". The test sends a streamed fixture with a comment line, a host chunk, a malformed chunk, and `[DONE]` through the proxy. It checks that the bytes are identical and that the turn's usage names `Novita` and the generation ID. The test fails without the proxy wiring. - `upstream-served.test.ts`: streamed fixture, chunk split inside a multibyte character, non-streamed JSON, malformed chunks, a truncated JSON body, an encoded body, the 64 KiB limit, and a recorder that throws. - `opencode-proxy-usage.test.ts`, `runnerd-codex-transport.test.ts` (rehydration), Rust `provider_events::tests::carries_the_serving_host_and_generation_on_proxy_usage`, and server `native-usage-accounting.test.ts` (first generation ID stays stable across turns). - Local: OpenCode driver, OpenCode proxy, and runnerd transport suites (31 files, 596 tests) pass. `cargo test -p paperclip-runner-core` passes (one timing test failed once under load and passed alone). Runner and server `tsc --noEmit` pass. Protocol manifest, type, and coverage checks pass. - Latency: a local benchmark proxied a 400-chunk SSE stream 200 times with the tap and 200 times without it. The median time to first byte was 292 µs with the tap and 259 µs without it (+33 µs, which is the extra stream stage). The total stream time changed from 491.4 ms to 492.5 ms. The tap spends about 5.5 µs of CPU to inspect the first chunk, after it has forwarded that chunk. OpenRouter time to first token is hundreds of milliseconds. - Paid evidence: one single-case run of `chat-features.runner-opencode.local.skills.fork-read-only` on this branch. The result is in a comment on this pull request. ## Risks - Low risk. All new fields are optional and additive. An older control plane ignores the extra usage fields. `usage.schema.json` is not bound by the event schema, and no validator enforces it on `usage.reported`. - Saved state from the previous release: this change adds no persisted run, session, checkpoint, or launch state. A saved session resumes unchanged. A run that is in flight during a deploy reports usage without the new fields until its Runner is new. `usageJson.providerRequestId` then stays `null`, as before. - `providerRequestId` on the run and its cost event is the run's first generation ID, not each call's ID. The value is stable, so a late usage receipt still matches the posted charge. Per-call IDs and hosts are in the run log. - If OpenCode starts a new model call before it reports the usage of the previous call, a usage event can name the newer call. OpenCode reports a message's usage when its step ends, so this is not expected. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code as an agent with tool use (shell, file edits, test runs). Extended reasoning was on. ## 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 - [x] All Paperclip CI gates are green - [x] 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: Claude Opus 5.5 <noreply@anthropic.com>
524 lines
19 KiB
JavaScript
524 lines
19 KiB
JavaScript
#!/usr/bin/env node
|
|
import { parseOpenCodeReasoningMode } from "../drivers/opencode/reasoning-mode.js";
|
|
import { createInterface } from "node:readline";
|
|
import { readFileSync } from "node:fs";
|
|
import { resolve } from "node:path";
|
|
|
|
import type {
|
|
HarnessRuntimeRequestResolution,
|
|
HarnessSession,
|
|
PersistedHarnessSession,
|
|
} from "../contracts/harness-driver.js";
|
|
import { OpenCodeServerDriver } from "../drivers/opencode/opencode-server-driver.js";
|
|
import { parseNativeRuntimeContext } from "../contracts/runtime-context.js";
|
|
import {
|
|
openCodeProxyCompletionContract,
|
|
openCodeProxyTaskEnvelope,
|
|
sameOpenCodeProxyCompletionContract,
|
|
} from "./opencode-proxy-task-envelope.js";
|
|
import {
|
|
openCodeProxyItemNotification,
|
|
openCodeProxyToolNotification,
|
|
openCodeProxyTerminalNotification,
|
|
shouldAnnounceOpenCodeProxyTurn,
|
|
shouldForwardOpenCodeProxyItem,
|
|
} from "./opencode-proxy-events.js";
|
|
import { enqueueOpenCodeProxyInput, openCodeProxyCompletionFeedback } from "./opencode-proxy-input.js";
|
|
import { createOpenCodeFinishDiagnosticForwarder } from "./opencode-proxy-finish-diagnostics.js";
|
|
import { createBackpressuredFrameWriter, createOpenCodeProxyOutput } from "./opencode-proxy-output.js";
|
|
import { createOpenCodeProxyControllerRequests } from "./opencode-proxy-controller.js";
|
|
import {
|
|
assertOpenCodeProxyCollaborationMode,
|
|
openCodeProxyCollaborationModes,
|
|
} from "./opencode-proxy-collaboration-mode.js";
|
|
import { parseOpenCodeProxyPermissionMode } from "./opencode-proxy-permission-mode.js";
|
|
import {
|
|
trustedOpenCodeLaunchBinding,
|
|
withoutAmbientOpenCodeCommand,
|
|
} from "./opencode-proxy-command.js";
|
|
import { OpenCodeProxyUsageLedger, openCodeProxyUpstreamUsage } from "./opencode-proxy-usage.js";
|
|
import { parseProviderPerformanceSpans, PROVIDER_PERFORMANCE_DIAGNOSTIC } from "../contracts/provider-performance.js";
|
|
|
|
type RpcMessage = {
|
|
id?: string | number;
|
|
method?: string;
|
|
params?: unknown;
|
|
result?: unknown;
|
|
error?: unknown;
|
|
};
|
|
|
|
const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
let driver: OpenCodeServerDriver | null = null;
|
|
let session: HarnessSession | null = null;
|
|
let eventPump: Promise<void> | null = null;
|
|
let cwd = "";
|
|
let activeModel = "";
|
|
let activeTurnId: string | null = null;
|
|
let activeRunId = process.env.PAPERCLIP_RUN_ID ?? "runnerd-run";
|
|
// The contract the open session checks finish claims against. The launch
|
|
// environment and the launch parameters can belong to different runs: runnerd
|
|
// restores a saved session with its saved contract while its environment
|
|
// already names the run being attached.
|
|
let activeCompletionContract: ReturnType<typeof openCodeProxyCompletionContract> = undefined;
|
|
const announcedTurnIds = new Set<string>();
|
|
const launchBinding = trustedOpenCodeLaunchBinding(process.argv.slice(2));
|
|
const usageLedger = new OpenCodeProxyUsageLedger();
|
|
|
|
// runnerd reads this stream only after its controller acknowledges earlier
|
|
// events. Keep that backlog in a queue we control so an abandoned tool call
|
|
// can still be withdrawn before runnerd dispatches it.
|
|
const stdoutFrames = createBackpressuredFrameWriter(process.stdout);
|
|
const output = createOpenCodeProxyOutput((value, options) => stdoutFrames.write(value, options));
|
|
const send = output.send;
|
|
|
|
const controller = createOpenCodeProxyControllerRequests(send);
|
|
const requestController = controller.request;
|
|
|
|
function record(value: unknown): Record<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
? (value as Record<string, unknown>)
|
|
: {};
|
|
}
|
|
|
|
function text(value: unknown, fallback = ""): string {
|
|
return typeof value === "string" ? value : fallback;
|
|
}
|
|
|
|
function runtimeDirectory(): string {
|
|
const configured = process.env.PAPERCLIP_OPENCODE_RUNTIME_DIR?.trim();
|
|
if (!configured)
|
|
throw new Error("PAPERCLIP_OPENCODE_RUNTIME_DIR is required");
|
|
return resolve(configured);
|
|
}
|
|
|
|
async function open(
|
|
params: Record<string, unknown>,
|
|
resume: boolean,
|
|
): Promise<Record<string, unknown>> {
|
|
if (session)
|
|
return threadResponse(
|
|
session.ids().providerSessionId ?? session.ids().driverSessionId,
|
|
);
|
|
cwd = resolve(text(params.cwd, process.cwd()));
|
|
const model = text(params.model);
|
|
if (!model.includes("/"))
|
|
throw new Error("OpenCode proxy requires model in provider/model form");
|
|
activeModel = model;
|
|
const dynamicTools = Array.isArray(params.dynamicTools)
|
|
? params.dynamicTools.map(record)
|
|
: [];
|
|
const runtimeContextPath =
|
|
process.env.PAPERCLIP_NATIVE_RUNTIME_CONTEXT_PATH?.trim();
|
|
const runtimeContext = runtimeContextPath
|
|
? parseNativeRuntimeContext(
|
|
JSON.parse(readFileSync(runtimeContextPath, "utf8")),
|
|
)
|
|
: null;
|
|
const finishDiagnostics = createOpenCodeFinishDiagnosticForwarder(send);
|
|
driver = new OpenCodeServerDriver({
|
|
model,
|
|
permissionMode: parseOpenCodeProxyPermissionMode(
|
|
process.env.PAPERCLIP_OPENCODE_PERMISSION_MODE,
|
|
),
|
|
command: launchBinding.command,
|
|
commandFd: launchBinding.commandFd,
|
|
commandLifecycle: launchBinding.commandLifecycle,
|
|
runtimeDirectory: runtimeDirectory(),
|
|
environment: withoutAmbientOpenCodeCommand(process.env),
|
|
runnerInstanceId:
|
|
process.env.PAPERCLIP_RUNNER_INSTANCE_ID ?? "paperclip-runnerd-opencode",
|
|
taskEnvelope: openCodeProxyTaskEnvelope(params),
|
|
conversationMode:
|
|
params.conversationMode === "prepared" ? "prepared" : "task",
|
|
systemInstructions: text(
|
|
params.baseInstructions,
|
|
"Complete only the supplied task.",
|
|
),
|
|
runtimeContext,
|
|
dynamicTools,
|
|
// Runner owns these calls until a durable result, cancellation, or lease
|
|
// expiry. A shorter MCP deadline would leave an unknown effect pending.
|
|
durableToolRequests: true,
|
|
completionFeedback: openCodeProxyCompletionFeedback((method, params, signal) => requestController(method, params, true, signal)),
|
|
dynamicToolHandler: async (call) =>
|
|
requestController("item/tool/call", {
|
|
threadId: session?.ids().driverSessionId ?? "opening",
|
|
turnId: call.turnId,
|
|
callId: call.callId,
|
|
tool: call.tool,
|
|
arguments: call.arguments,
|
|
}, false, call.signal),
|
|
onDiagnostic: (message) => {
|
|
process.stderr.write(`[opencode] ${message}\n`);
|
|
finishDiagnostics.diagnostic(message);
|
|
},
|
|
// runnerd gives this proxy its own process group. Keep `opencode serve` in
|
|
// that same group so runnerd's TERM/KILL fallback cannot orphan it.
|
|
isolateProcessGroup: false,
|
|
});
|
|
if (resume) {
|
|
const threadId = text(params.threadId);
|
|
const snapshot: PersistedHarnessSession = {
|
|
driverKind: "opencode_server",
|
|
driverSessionId: threadId,
|
|
providerSessionId: threadId,
|
|
runId: activeRunId,
|
|
normalizedSessionId:
|
|
process.env.PAPERCLIP_NORMALIZED_SESSION_ID ?? threadId,
|
|
activeTurnId: null,
|
|
lastSourceSequence: 0,
|
|
};
|
|
const recovered = await driver.recoverSession(snapshot);
|
|
if (!recovered.recovered || !recovered.session)
|
|
throw new Error(recovered.reason ?? "OpenCode recovery failed");
|
|
session = recovered.session;
|
|
} else {
|
|
session = await driver.openSession({
|
|
runId: activeRunId,
|
|
normalizedSessionId:
|
|
process.env.PAPERCLIP_NORMALIZED_SESSION_ID ?? `runnerd-${Date.now()}`,
|
|
workingDirectory: cwd,
|
|
});
|
|
}
|
|
finishDiagnostics.bind(session.ids().driverSessionId);
|
|
activeCompletionContract = openCodeProxyCompletionContract(params.completionContract);
|
|
eventPump = pumpEvents(session);
|
|
void eventPump.catch((error) => failProxy(error));
|
|
return threadResponse(
|
|
session.ids().providerSessionId ?? session.ids().driverSessionId,
|
|
);
|
|
}
|
|
|
|
function threadResponse(id: string): Record<string, unknown> {
|
|
return { thread: { id, sessionId: id, cwd }, model: activeModel };
|
|
}
|
|
|
|
function announceTurnStarted(opened: HarnessSession, turnId: string): void {
|
|
if (!shouldAnnounceOpenCodeProxyTurn(announcedTurnIds, turnId)) return;
|
|
send({
|
|
method: "turn/started",
|
|
params: {
|
|
threadId: opened.ids().driverSessionId,
|
|
turnId,
|
|
turn: { id: turnId, status: "inProgress" },
|
|
},
|
|
});
|
|
}
|
|
|
|
async function pumpEvents(opened: HarnessSession): Promise<void> {
|
|
for await (const event of opened.events()) {
|
|
const payload = record(event.payload);
|
|
const toolActivity = openCodeProxyToolNotification({ eventType: event.eventType,
|
|
threadId: opened.ids().driverSessionId, turnId: event.turnId, payload });
|
|
if (toolActivity) {
|
|
send(toolActivity);
|
|
} else if (event.eventType === "turn.started") {
|
|
if (typeof event.turnId === "string")
|
|
announceTurnStarted(opened, event.turnId);
|
|
} else if (
|
|
event.eventType === "item.started" ||
|
|
event.eventType === "item.delta" ||
|
|
event.eventType === "item.completed"
|
|
) {
|
|
// The inner OpenCode driver publishes session-scoped model metadata as
|
|
// an item before any turn exists. The outer Codex protocol facade emits
|
|
// its own model item, so forwarding this unbound duplicate would quite
|
|
// correctly trip the facade's strict turn-binding validator.
|
|
if (
|
|
!shouldForwardOpenCodeProxyItem({
|
|
eventType: event.eventType,
|
|
turnId: event.turnId,
|
|
payload,
|
|
})
|
|
)
|
|
continue;
|
|
send(
|
|
openCodeProxyItemNotification({
|
|
eventType: event.eventType,
|
|
threadId: opened.ids().driverSessionId,
|
|
turnId: event.turnId,
|
|
itemId: event.itemId,
|
|
payload,
|
|
}),
|
|
);
|
|
if (payload.kind === "usage") {
|
|
const usage = {
|
|
...usageLedger.update({
|
|
turnId: text(event.turnId),
|
|
messageId: text(payload.usageMessageId),
|
|
usage: payload.usage,
|
|
}),
|
|
...openCodeProxyUpstreamUsage(payload.usage),
|
|
};
|
|
send({
|
|
method: "thread/tokenUsage/updated",
|
|
params: {
|
|
threadId: opened.ids().driverSessionId,
|
|
turnId: event.turnId,
|
|
tokenUsage: usage,
|
|
},
|
|
});
|
|
}
|
|
} else if (event.eventType === "run.result.proposed") {
|
|
send({
|
|
method: "paperclip/runResult",
|
|
params: {
|
|
threadId: opened.ids().driverSessionId,
|
|
turnId: event.turnId,
|
|
itemId: event.itemId ?? "semantic-result",
|
|
result: payload,
|
|
},
|
|
});
|
|
} else if (event.eventType === "runtime_request.created") {
|
|
const request = record(payload.request);
|
|
const requestId = text(request.requestId);
|
|
const turnId = text(
|
|
request.turnId,
|
|
text(event.turnId, activeTurnId ?? ""),
|
|
);
|
|
if (!requestId || !turnId || !opened.resolveRuntimeRequest) {
|
|
throw new Error("OpenCode runtime request is not resolvable");
|
|
}
|
|
// Keep consuming OpenCode SSE while the controller waits for the user.
|
|
// If the underlying provider disappears, the stream can then fail the
|
|
// proxy and runnerd will expire the still-pending canonical request.
|
|
void (async () => {
|
|
const controllerResponse = record(
|
|
await requestController("paperclip/runtimeRequest", {
|
|
request,
|
|
}),
|
|
);
|
|
await opened.resolveRuntimeRequest!({
|
|
requestId,
|
|
turnId,
|
|
resolution: record(
|
|
controllerResponse.resolution,
|
|
) as HarnessRuntimeRequestResolution,
|
|
});
|
|
})().catch((error) => failProxy(error));
|
|
} else if (event.eventType === "run.attached") {
|
|
// OpenCode can retain one provider session across governed runs. Usage
|
|
// totals are run-scoped, so a new attachment must not inherit the prior
|
|
// run's completed-turn ledger.
|
|
usageLedger.reset();
|
|
} else if (
|
|
[
|
|
"turn.completed",
|
|
"turn.failed",
|
|
"turn.interrupted",
|
|
"turn.cancelled",
|
|
].includes(event.eventType)
|
|
) {
|
|
if (typeof event.turnId === "string")
|
|
usageLedger.completeTurn(event.turnId);
|
|
send(
|
|
openCodeProxyTerminalNotification({
|
|
eventType: event.eventType as
|
|
| "turn.completed"
|
|
| "turn.failed"
|
|
| "turn.interrupted"
|
|
| "turn.cancelled",
|
|
threadId: opened.ids().driverSessionId,
|
|
turnId: event.turnId,
|
|
payload,
|
|
}),
|
|
);
|
|
activeTurnId = null;
|
|
} else if (event.eventType === "harness.diagnostic") {
|
|
if (payload.code === PROVIDER_PERFORMANCE_DIAGNOSTIC) {
|
|
send({method: "paperclip/providerPerformance", params: {
|
|
threadId: opened.ids().driverSessionId, turnId: event.turnId,
|
|
spans: parseProviderPerformanceSpans(payload, Date.now()),
|
|
}});
|
|
continue;
|
|
}
|
|
send({
|
|
method: "warning",
|
|
params: {
|
|
threadId: opened.ids().driverSessionId,
|
|
message: payload.message ?? payload.code,
|
|
},
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
async function handle(message: RpcMessage): Promise<void> {
|
|
if (message.method === undefined && message.id !== undefined) {
|
|
controller.respond({ id: message.id, result: message.result, error: message.error });
|
|
return;
|
|
}
|
|
if (!message.method || message.id === undefined) return;
|
|
const params = record(message.params);
|
|
let result: unknown;
|
|
switch (message.method) {
|
|
case "initialize":
|
|
result = {
|
|
user: { sessionId: "opencode" },
|
|
serverInfo: { name: "opencode", version: "1.18.34" },
|
|
};
|
|
break;
|
|
case "thread/start":
|
|
result = await open(params, false);
|
|
break;
|
|
case "thread/resume":
|
|
result = await open(params, true);
|
|
break;
|
|
case "collaborationMode/list":
|
|
result = openCodeProxyCollaborationModes(activeModel);
|
|
break;
|
|
case "turn/start": {
|
|
if (!session) throw new Error("OpenCode thread is not open");
|
|
assertOpenCodeProxyCollaborationMode(params);
|
|
if (params.paperclipRunId !== undefined) {
|
|
const runId = params.paperclipRunId;
|
|
if (typeof runId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(runId))
|
|
throw new Error("Invalid Paperclip run identity");
|
|
// Runnerd sends the attached run's contract with its run identity;
|
|
// the launch parameters may still name an earlier run's contract,
|
|
// even when the launch environment already names this run.
|
|
const contract = openCodeProxyCompletionContract(params.paperclipCompletionContract);
|
|
if (runId !== activeRunId
|
|
|| (contract !== undefined && !sameOpenCodeProxyCompletionContract(contract, activeCompletionContract))) {
|
|
if (!session.attachRun) throw new Error("OpenCode run attachment unavailable");
|
|
await session.attachRun({ runId, ...(contract ? { completionContract: contract } : {}) });
|
|
activeRunId = runId;
|
|
if (contract !== undefined) activeCompletionContract = contract;
|
|
}
|
|
}
|
|
const inputItems = Array.isArray(params.input)
|
|
? params.input.map(record)
|
|
: [];
|
|
const messageText = inputItems
|
|
.map((entry) => text(entry.text))
|
|
.filter(Boolean)
|
|
.join("\n");
|
|
const turn = await session.startTurn({
|
|
message: { role: "user", text: messageText },
|
|
...(params.reasoningMode === undefined ? {} : { reasoningMode: parseOpenCodeReasoningMode(params.reasoningMode) }),
|
|
});
|
|
activeTurnId = turn.turnId;
|
|
// OpenCode normally publishes session/turn startup over SSE, but a fast
|
|
// completion can make the synchronous prompt response the only place the
|
|
// authoritative turn id is observed. Emit the normalized notification
|
|
// after this request's JSON-RPC response when SSE did not already announce
|
|
// it. runnerd buffers notifications received while awaiting a response,
|
|
// so replaying an earlier SSE announcement would violate strict turn
|
|
// binding at the outer driver.
|
|
queueMicrotask(() => {
|
|
announceTurnStarted(session!, turn.turnId);
|
|
});
|
|
result = { turn: { id: turn.turnId, status: "inProgress" } };
|
|
break;
|
|
}
|
|
case "turn/interrupt":
|
|
if (!session?.interrupt)
|
|
throw new Error("OpenCode interruption is unavailable");
|
|
await session.interrupt({
|
|
turnId: text(params.turnId, activeTurnId ?? ""),
|
|
});
|
|
result = true;
|
|
break;
|
|
case "thread/read":
|
|
if (!session) throw new Error("OpenCode thread is not open");
|
|
// runnerd reads only turn metadata after resume. Hydrating the retained
|
|
// OpenCode message history here grows with the session and can exceed
|
|
// runnerd's bounded stdout frame, which permanently blocks resume.
|
|
result = {
|
|
thread: {
|
|
id: session.ids().driverSessionId,
|
|
cwd,
|
|
turns: activeTurnId
|
|
? [{ id: activeTurnId, status: "inProgress" }]
|
|
: [],
|
|
},
|
|
};
|
|
break;
|
|
default:
|
|
throw new Error(`Unsupported OpenCode proxy method ${message.method}`);
|
|
}
|
|
send({ id: message.id, result });
|
|
}
|
|
|
|
let pendingInput = Promise.resolve();
|
|
let bootstrapFailure: Error | null = null;
|
|
input.on("line", (line) => {
|
|
if (!line.trim()) return;
|
|
let message: RpcMessage;
|
|
try {
|
|
message = JSON.parse(line) as RpcMessage;
|
|
} catch (error) {
|
|
process.stderr.write(`Invalid JSON-RPC input: ${String(error)}\n`);
|
|
return;
|
|
}
|
|
if (message.method === undefined && message.id !== undefined) {
|
|
// A command may await this bound response. Queueing the response behind
|
|
// that command would deadlock completion, interruption and shutdown.
|
|
void handle(message).catch(failProxy);
|
|
return;
|
|
}
|
|
pendingInput = enqueueOpenCodeProxyInput(
|
|
pendingInput,
|
|
async () => {
|
|
if (bootstrapFailure) {
|
|
throw new Error(
|
|
`OpenCode provider bootstrap failed before ${message.method ?? "the dependent command"}: ${bootstrapFailure.message}`,
|
|
);
|
|
}
|
|
await handle(message);
|
|
},
|
|
(error) => {
|
|
const normalized =
|
|
error instanceof Error ? error : new Error(String(error));
|
|
if (
|
|
message.method === "initialize" ||
|
|
message.method === "thread/start" ||
|
|
message.method === "thread/resume"
|
|
) {
|
|
bootstrapFailure ??= normalized;
|
|
}
|
|
send({
|
|
id: message.id,
|
|
error: { code: -32000, message: normalized.message },
|
|
});
|
|
},
|
|
);
|
|
});
|
|
|
|
let shutdownPromise: Promise<void> | null = null;
|
|
function failProxy(error: unknown): void {
|
|
process.stderr.write(
|
|
`[opencode] fatal proxy error: ${error instanceof Error ? error.message : String(error)}\n`,
|
|
);
|
|
void shutdown(1);
|
|
}
|
|
|
|
function shutdown(exitCode = 0): Promise<void> {
|
|
shutdownPromise ??= (async () => {
|
|
controller.rejectAll(new Error("OpenCode proxy is shutting down"));
|
|
await session
|
|
?.close({ reason: "proxy_shutdown", force: true })
|
|
.catch(() => {});
|
|
await eventPump?.catch(() => {});
|
|
output.flush();
|
|
stdoutFrames.drain();
|
|
// A failed turn can be the last frame before a fatal exit. Pipe writes
|
|
// are asynchronous on some platforms, so let it reach runnerd first.
|
|
await new Promise<void>((resolve) => process.stdout.write("", () => resolve()));
|
|
})().finally(() => process.exit(exitCode));
|
|
return shutdownPromise;
|
|
}
|
|
|
|
input.on("close", () => {
|
|
controller.closeInput(new Error("OpenCode controller input closed before its response"));
|
|
// Preserve command order and the bootstrap drain. A queued command cannot
|
|
// create a new unanswered controller request after EOF.
|
|
void pendingInput.then(() => shutdown());
|
|
});
|
|
process.on("SIGTERM", () => {
|
|
void shutdown();
|
|
});
|
|
process.on("SIGINT", () => {
|
|
void shutdown();
|
|
});
|