mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-06 10:48:12 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents run through coding-agent adapters and the native runner. Both use the same installed provider CLIs, model catalogs, and reasoning controls. > - OpenAI released GPT-6.1 Sol (`gpt-6.1-sol`) in Codex. Anthropic released Claude Sonnet 5.5. The static Codex, Bedrock, and OpenCode catalogs do not list these IDs. > - The shared provider pack pins Codex 0.156.0 and OpenCode 1.18.32. The evaluation image pins older Grok, Gemini, Kimi, Cursor, and GitHub CLI releases. Codex 0.156.0 has no bundled metadata for GPT-6.1 Sol. > - A model entry without a current harness, or a harness pin without its runner integrity checks, fails at run time. > - This pull request adds the verified model IDs and moves the harness pins, executable digests, controller checks, and image pins together. > - The benefit is that operators can select the current models, and the native and local adapters share one current CLI installation. ## Linked Issues or Issue Description Refs #13829 and #13838 (the September 22, 2026 model and harness refresh). Related pull requests: #14993 (merged October 5, 2026, superseding #14816) added the direct Claude Sonnet 5.5 entry and refreshed the Claude runtime to Agent SDK 0.3.286 / Claude Code 2.1.286. This pull request does not change the Claude runtime or the direct Claude model list; it keeps the #14993 pins and adds only the Bedrock Sonnet 5.5 ID. After #14993 merged, this branch was rebased onto `master` (October 5, 2026). The six overlapping pin regions (`docker/daytona-runner/Dockerfile`, `docker/daytona-runner/README.md`, `package.json`, `pnpm-workspace.yaml`, `packages/adapters/claude-local/src/index.test.ts`, `packages/paperclip-runner/src/backends/native-backend-factory.test.ts`) were resolved by keeping this pull request's Codex 0.160.0 and OpenCode 1.18.34 pins next to #14993's Claude 0.3.286 / 2.1.286 pins, taking the union of the Sonnet 5.5 model IDs in the Claude test, and merging both README paragraphs. The Sonnet 5.5 effort and CLI-gate lines in the Claude adapter were identical in both pull requests and merged without a diff. #14917 and #14918 reordered the Claude and Codex model lists earlier; the new entries sit where those ordering rules put them. Sources checked on 2026-10-02: - [OpenAI Codex models](https://learn.chatgpt.com/docs/models): GPT-6.1 Sol uses `gpt-6.1-sol`, supports reasoning efforts from Light to Ultra, and has Standard and Fast modes at launch. The page also records that `gpt-5.4` and `gpt-5.4-mini` retired from Codex with ChatGPT sign-in on August 31, 2026, and that `gpt-5.5` retires on October 14, 2026. Neither retirement applies to the OpenAI API. - [Codex CLI releases](https://github.com/openai/codex/releases) 0.157.0 through 0.160.0. The bundled model metadata in the 0.160.0 Linux binary contains `gpt-6.1-sol`. - [Claude Sonnet 5.5](https://platform.claude.com/docs/en/models/sonnet-5-5/overview): Bedrock ID `anthropic.claude-sonnet-5-5`, released September 28, 2026. - [OpenCode releases](https://github.com/anomalyco/opencode/releases) 1.18.33 and 1.18.34 (fixes only). The OpenCode model registry lists both added provider-qualified IDs. - npm `latest` tags for `@xai-official/grok` 1.0.46, `@google/gemini-cli` 0.62.0, and `@moonshot-ai/kimi-code` 2.1.1. [xAI](https://docs.x.ai/docs/models), [Google](https://ai.google.dev/gemini-api/docs/models), and [Kimi](https://www.kimi.com/code/docs/en/kimi-code/models.html) list no newer coding models. - Cursor CLI 2026.10.01-e373342 is the version the official installer resolves. The pinned digest is the SHA-256 of the versioned Linux x64 archive. - [GitHub CLI 2.102.0](https://github.com/cli/cli/releases/tag/v2.102.0) (security fixes). The pinned digest matches the release `checksums.txt`. ## What Changed - Codex adapter: add `gpt-6.1-sol` to the model list, the Fast mode list, and the Ultra effort set. It is the first entry: #14918 orders the list newest version first, and its description notes the ChatGPT app lists GPT-6.1 Sol first. Update the adapter documentation text. - Claude adapter: add `us.anthropic.claude-sonnet-5-5` (Bedrock Sonnet 5.5) to the Bedrock catalog in the newest-Sonnet slot after Opus 5.5; `us.anthropic.claude-sonnet-5` moves into the older-Sonnet group, matching what `sortClaudeModels` from #14917 produces at runtime. Any Sonnet 5.5 ID (direct or Bedrock-qualified) now gets the documented `xhigh` and `max` efforts and requires Claude Code 2.1.284 or later on the CLI lane (the Claude Code changelog entry for 2.1.284 adds `claude-sonnet-5-5`). These two lines are identical to the ones #14993 merged, so the branch carries no diff for them. - OpenCode adapter: add `openai/gpt-6.1-sol` and `anthropic/claude-sonnet-5-5` to the static fallback catalog. - Codex runtime pin 0.156.0 → 0.160.0 in the root and workspace overrides, the runner package, the Codex ACP package patch, the qualified ACPX profiles, the Linux x64 executable digest, the Rust provider backend and its tests, the provider-pack manifest pins, the remote controller pins, the sandbox npm install spec, and the opt-in qualification scripts. - Remote Codex compatibility window: upper bound 0.157.0 → 0.161.0. The minimum stays at 0.149.0. - OpenCode runtime pin 1.18.32 → 1.18.34 in the runner package, the materialization script, the server and Rust qualified versions, the eval and live-session labels, fixtures, and the configuration label. - Evaluation image (`docker/daytona-runner/Dockerfile`): Grok CLI 1.0.46, Gemini CLI 0.62.0, Kimi Code 2.1.1, Cursor CLI 2026.10.01-e373342 with its digest, GitHub CLI 2.102.0 with its digest, Codex and OpenCode version probes, and the refreshed lockfile digest. The Claude Code 2.1.286 probe comes from #14993 and is unchanged here. - `pnpm-lock.yaml` is not part of this pull request. The repository's pull request gate rejects lockfile edits, and the refresh bot regenerates the lockfile on master (the same flow #13838 used). The Dockerfile `PAPERCLIP_RUNNER_LOCK_SHA256` default is the digest of the lockfile that `pnpm install --resolution-only --ignore-scripts --no-frozen-lockfile` (the refresh workflow's command) produces for the combined pins on the rebased branch (`e1856797…`); that lockfile differs from master only in the `@openai/codex` 0.160.0 platform packages, the `@anthropic-ai/claude-agent-sdk` 0.3.286 override that #14993 introduced (the open refresh-bot pull request #14872 carries that part), `opencode-ai` 1.18.34 with its Linux x64 baseline, and the `codex-acp` patch hash. - Documentation: runner README, runner compatibility doc, environment variable example, and a new `doc/adapter-model-audit-2026-10-02.md` with sources and deferred items. - Tests: Codex adapter catalog, server adapter models, Codex compatibility window, native session executor pins, runner package contract, OpenCode materialization, and UI effort options. Unchanged on purpose: Claude Agent SDK 0.3.286 / Claude Code 2.1.286 (already on `master` from #14993), ACP bridges (`acpx` 0.13.1, `claude-agent-acp` 0.73.0, `codex-acp` 1.6.2; newer upstream releases need a separate qualification), the native Grok runtime 1.0.13, Pi 0.84.2 / 0.87.1 (the Pi 1.0 runner stack covers it), and Hermes 0.19.0 (current). `gpt-5.4` and `gpt-5.4-mini` stay in the picker because the OpenAI API still serves them. ## Verification Run on Linux x64 with Node 25.9.0 and pnpm 9.15.4 after `pnpm install --no-frozen-lockfile` (the refreshed lockfile stays local; see above). The results below were re-run on the rebased head (October 5, 2026) for the suites the conflict resolution touches; the other rows are from the original run and are covered by CI on every push: - Rebased head: `packages/adapters/codex-local` 482 passed; `packages/adapters/claude-local` 340 passed, 4 failed (`execute.remote`, `test.probe`, `execute.acp-fallback`, `acp` spawn/env-hardening cases that fail identically on unchanged `master` in this host environment); `server` adapter-models + codex-runtime-compatibility + native-session-executor + adapter-registry 607 passed, 1 failed (the same adapter-registry override-pause case as before, also failing on `master` here); `packages/paperclip-runner` native-backend-factory + qualified-profiles 36 passed; `ui` codex-reasoning-effort + config-fields + model-utils 19 passed. Rust, full typecheck, build, and the Docker image are left to CI as before. - `vitest run` in `packages/adapters/codex-local`: 13 passed. `vitest run` in `packages/adapters/claude-local` (whole package, including the new Sonnet 5.5 gate and effort tests): see the latest CI run and the comment below. `vitest run` in `packages/adapters/opencode-local`: 48 passed, 1 failed (`runtime-config.test.ts` reads the host `PAPERCLIP_OPENCODE_PROVIDERS` variable; it fails the same way on the unchanged base). - `vitest run src/__tests__/adapter-models.test.ts src/services/native-runtime/codex-runtime-compatibility.test.ts src/__tests__/adapter-registry.test.ts` in `server`: 84 passed, 1 failed (`adapter-registry.test.ts` override pause test; it fails the same way on the unchanged base). - `vitest run` in `ui` for `codex-reasoning-effort`, `agent-setup-fields`, `config-fields`, and `ComposerRunSettingsPicker`: 25 passed. - `node --test test/acpx-codex-package-contract.test.mjs scripts/materialize-opencode-binary.test.mjs scripts/runner-protocol-eval-campaign.test.mjs` in `packages/paperclip-runner`: 23 passed. The package contract test verifies the installed Codex ACP executable digest and the 0.160.0 patch pin. - `vitest run src/drivers/acpx src/backends src/drivers/opencode src/live/live-session.test.ts` in `packages/paperclip-runner`: 626 passed, 5 failed, 1 skipped. The 5 failures (`installation-integrity.test.ts` `/proc/self/fd` module loading and one OpenCode answer-selection test) also fail on the unchanged base under Node 25; Linux CI runs Node 24. - `pnpm run test:opencode:qualification` in `packages/paperclip-runner` against the installed OpenCode 1.18.34 executable: passed. - `codex --version` from the installed pack prints `codex-cli 0.160.0`. The Linux x64 executable digest `12eb3e81…652aad` was computed from the `@openai/codex@0.160.0-linux-x64` archive after checking its registry `dist.integrity`. - `pnpm check:token-gates`: all gates clean. - `pnpm run typecheck:typescript` in `packages/paperclip-runner`: passed. Package typechecks ran one at a time; see the comment below for the server and UI results. Not run here, and needed from CI: - Rust tests and `pnpm -r typecheck` / `pnpm build` for the server (no `cargo` in this environment; the server typecheck prepares the runner vendor build). - The Docker evaluation image build and the real-binary Codex startup and session-resume probes (no Docker; the probes need the compiled `paperclip-runnerd`). The trusted CI runner workflow covers them. - Authenticated inference with any new model. This change is metadata and startup validation only. ## Risks - Codex 0.160.0 changes the bundled model catalog and app-server behaviour (authoritative provider catalogs, incremental running-turn tracking). The patched `codex-acp` 1.6.2 bridge is unchanged and declares `^0.148.0`; it worked with 0.156.0 under the same override. If CI probes show a protocol change, the pin can return to 0.156.0 by reverting this pull request. - The compatibility window upper bound moves to `<0.161.0`. Remote images with Codex 0.157 to 0.160 become accepted. Older images stay accepted down to 0.149.0. - Until the refresh bot lands the regenerated lockfile on master, the Dockerfile lockfile digest default does not match the committed lockfile. The trusted CI workflow computes the digest from its own resolution at build time, so this affects only a local build that passes no digest. - Existing saved model selections and effort settings are not changed. Agents on `gpt-5.4` or `gpt-5.5` with ChatGPT sign-in need a model change before the OpenAI retirement dates; that is documented, not enforced. - Rollout order: deploy the controller and runner from this change before promoting a sandbox image that carries these pins. Older controllers reject the new provider-pack pins. ## Model Used - Claude Fable 5.1 (Anthropic, model ID `claude-fable-5-1`), 1M context window, adaptive thinking, tool use. The model ran as a Paperclip agent through the Claude Code harness, performed the web research, edited the code, and ran the tests listed above. ## 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: Bender (Fable) <noreply@paperclip.ing> Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
223 lines
18 KiB
TypeScript
223 lines
18 KiB
TypeScript
import { AGENT_CHAT_DIRECTIVE } from "../server/src/services/agent-conversations.js";
|
||
/** JSONL worker for the companion paperclip-evals API suite. Never selects cases or retries. */
|
||
import { createHash, randomUUID } from "node:crypto";
|
||
import { createReadStream, realpathSync } from "node:fs";
|
||
import { execFileSync } from "node:child_process";
|
||
import { mkdir, writeFile, readFile } from "node:fs/promises";
|
||
import { join, resolve } from "node:path";
|
||
import { createInterface } from "node:readline";
|
||
import { homedir } from "node:os";
|
||
import { runnerApiCatalog } from "../server/src/services/native-runtime/runner-api-catalog.js";
|
||
import { startRunnerApiTestServer } from "../server/src/__tests__/helpers/runner-api-server.js";
|
||
import { registerRunnerPrpAuthority } from "../server/src/realtime/runner-prp-ws.js";
|
||
import { createRunnerdCodexTransport, defaultCapabilityRunnerdBinary } from "../packages/paperclip-runner/src/live/runnerd-codex-transport.js";
|
||
import { createSkilllessCodexThreadConfig } from "../packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.js";
|
||
import { AttemptJournal } from "../packages/paperclip-runner/src/evals/attempt-journal.js";
|
||
import { estimateModelCostNanodollars } from "../packages/paperclip-runner/src/evals/model-pricing.js";
|
||
import { CONNECTION_INTENT_AGENT_GUIDANCE } from "../packages/shared/src/connection-intent-guidance.js";
|
||
|
||
if (process.argv.includes("--catalog")) {
|
||
process.stdout.write(JSON.stringify(runnerApiCatalog()) + "\n");
|
||
process.exit(0);
|
||
}
|
||
if (!process.argv.includes("--jsonl")) throw new Error("Use --catalog or --jsonl; there is no default campaign");
|
||
process.env.PAPERCLIP_AGENT_JWT_SECRET = randomUUID() + randomUUID();
|
||
const output = (value: unknown) => process.stdout.write("RUNNER_API_EVAL " + JSON.stringify(value) + "\n");
|
||
const OPENROUTER_MODELS = new Set(["openrouter/anthropic/claude-sonnet-5", "openrouter/deepseek/deepseek-v4-flash-0731", "openrouter/google/gemini-3.8-flash"]);
|
||
// The controller selects and injects one provider credential. The worker never
|
||
// reads ambient home credential files or desktop keychains.
|
||
function openRouterEnvironment() {
|
||
const key = process.env.OPENROUTER_API_KEY;
|
||
if (!key || /\s/.test(key)) throw new Error("Controller must inject OPENROUTER_API_KEY");
|
||
return { PATH: process.env.PATH, OPENROUTER_API_KEY: key };
|
||
}
|
||
const server = await startRunnerApiTestServer();
|
||
const fileDigests = new Map<string, Promise<string | null>>();
|
||
function fileDigest(path: string): Promise<string | null> {
|
||
let digest = fileDigests.get(path);
|
||
if (!digest) {
|
||
digest = (async () => {
|
||
const hash = createHash("sha256");
|
||
for await (const chunk of createReadStream(path)) hash.update(chunk);
|
||
return hash.digest("hex");
|
||
})().catch(() => null);
|
||
fileDigests.set(path, digest);
|
||
}
|
||
return digest;
|
||
}
|
||
const runtimeBuild = {
|
||
runnerBinarySha256: await fileDigest(defaultCapabilityRunnerdBinary()),
|
||
workerSourceSha256: await fileDigest(resolve("scripts/runner-api-eval-worker.ts")),
|
||
lockfileSha256: await fileDigest(resolve("pnpm-lock.yaml")),
|
||
};
|
||
output({ ready: true });
|
||
const record = (value: unknown): Record<string, any> => value && typeof value === "object" ? value as Record<string, any> : {};
|
||
|
||
try {
|
||
for await (const line of createInterface({ input: process.stdin })) {
|
||
const request = JSON.parse(line);
|
||
if (request.shutdown) break;
|
||
const directory = resolve(request.outputDirectory);
|
||
await mkdir(directory, { recursive: true, mode: 0o700 });
|
||
const journal = new AttemptJournal(join(directory, "journal.jsonl"));
|
||
const startedAt = new Date().toISOString();
|
||
journal.append({ kind: "attempt_started", attemptId: request.attemptId, model: request.model, startedAt });
|
||
const started = performance.now();
|
||
const isOpenRouter = OPENROUTER_MODELS.has(request.model);
|
||
const provider = isOpenRouter ? "opencode" : request.model === "claude-sonnet-5" ? "acpx" : "codex";
|
||
let providerVersion: string | null = null;
|
||
const fixture = await server.fixture({ mode: request.mode, apiToolsEnabled: request.arm !== "baseline", reset: true, conversation: request.conversation === true, connectionScenario: request.connectionScenario });
|
||
const initialState = await fixture.snapshot();
|
||
const substitutions = Object.fromEntries(Object.entries(fixture).filter(([, value]) => typeof value === "string"));
|
||
const expand = (value: any): any => typeof value === "string" ? value.replace(/\{\{(\w+)\}\}/g, (_, key) => String(substitutions[key] ?? (() => { throw new Error(`Unknown fixture variable ${key}`); })())) : Array.isArray(value) ? value.map(expand) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, expand(entry)])) : value;
|
||
const calls: Record<string, any>[] = [], notifications: unknown[] = [];
|
||
const observedToolCallIds = new Set<string>();
|
||
const definitions = await fixture.authority.definitions();
|
||
const prompt = expand(request.prompt ?? "");
|
||
let error: string | null = null, evidence: unknown = null, thread: Record<string, any> = {}, usage: Record<string, any> | null = null;
|
||
let usageUpdates = 0, lastUsageFingerprint = "", terminalSeen = false, providerTurnStarted = false;
|
||
let diagnosticTail: string | null = null;
|
||
let bundle: ReturnType<typeof createRunnerdCodexTransport> | undefined;
|
||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||
const invoke = async (tool: string, args: unknown, callId: string) => {
|
||
observedToolCallIds.add(callId);
|
||
if (observedToolCallIds.size > 12) throw new Error("Attempt tool-call ceiling reached");
|
||
const call: Record<string, any> = { tool, arguments: args, callId, startedMs: performance.now() - started };
|
||
calls.push(call);
|
||
journal.append({ kind: "tool_dispatch", ...call });
|
||
try { call.result = await fixture.authority.execute({ tool, arguments: args, callId }); }
|
||
catch (caught) { call.error = caught instanceof Error ? caught.message : String(caught); call.status = record(caught).status; }
|
||
call.durationMs = performance.now() - started - call.startedMs;
|
||
journal.append({ kind: "tool_result", ...call });
|
||
return call;
|
||
};
|
||
try {
|
||
if (request.calls) {
|
||
for (const [i, call] of request.calls.entries()) await invoke(call.tool, expand(call.arguments), call.callId ?? `direct-${i}`);
|
||
usage = { inputTokens: 0, outputTokens: 0, cachedInputTokens: 0, estimatedCostNanodollars: 0, providerRequests: 0, accountingProvenance: "Provider-free direct authority contract; no provider or runnerd dispatched" };
|
||
} else {
|
||
if (request.model === "claude-sonnet-5" && (process.platform !== "linux" || process.arch !== "x64")) throw new Error("Qualified ACPX Claude requires Linux x64; no provider turn was dispatched");
|
||
if (!request.reservationId || request.maxCostUsd !== 0.5 || !["gpt-5.6-luna", "claude-sonnet-5", ...OPENROUTER_MODELS].includes(request.model)) throw new Error("Paid attempt requires ledger reservation and qualified model");
|
||
if (isOpenRouter) {
|
||
providerVersion = execFileSync(resolve("packages/paperclip-runner/node_modules/opencode-ai/bin/opencode.exe"), ["--version"], { encoding: "utf8" }).trim();
|
||
if (providerVersion !== "1.18.34") throw new Error("OpenCode profile requires version 1.18.34");
|
||
}
|
||
const providerEnvironment = isOpenRouter ? openRouterEnvironment() : request.model === "claude-sonnet-5" ? (() => {
|
||
const token = process.env.CLAUDE_CODE_OAUTH_TOKEN;
|
||
if (!token) throw new Error("Controller must inject CLAUDE_CODE_OAUTH_TOKEN");
|
||
return { PATH: process.env.PATH, CLAUDE_CODE_OAUTH_TOKEN: token };
|
||
})() : undefined;
|
||
bundle = createRunnerdCodexTransport({
|
||
provider, acpxAgent: "claude", acpxPermissionMode: "approve-reads",
|
||
environment: { ...providerEnvironment, PAPERCLIP_PROVIDER_TRACE_PATH: join(directory, "provider-trace.jsonl"), PAPERCLIP_PROVIDER_TRACE_MAX_BYTES: String(32 * 1024 * 1024) },
|
||
codexCommand: request.model === "gpt-5.6-luna" ? realpathSync(execFileSync("which", ["codex"], { encoding: "utf8" }).trim()) : undefined,
|
||
sourceCodexHome: process.env.CODEX_HOME ?? join(homedir(), ".codex"),
|
||
runnerBinary: defaultCapabilityRunnerdBinary(), stateDirectory: join(server.root, `runner-${request.attemptId}`),
|
||
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
|
||
prpIdentity: { runnerInstanceId: `runner-${fixture.runId}`, environmentLeaseId: `lease-${fixture.runId}`, runId: fixture.runId, normalizedSessionId: `session-${fixture.runId}`, turnId: `turn-${fixture.runId}`, itemId: `item-${fixture.runId}` },
|
||
controlPlaneRegistration: (prp) => registerRunnerPrpAuthority({ companyId: fixture.companyId, runId: fixture.runId, authority: prp }),
|
||
});
|
||
const active = bundle;
|
||
timer = setTimeout(() => { error = "Attempt exceeded 120 seconds"; void active.transport.close(error); }, 120_000);
|
||
bundle.transport.setServerRequestHandler(async (request) => {
|
||
const params = record(request.params);
|
||
const result = await invoke(String(params.tool), params.arguments, String(params.callId));
|
||
return { success: !result.error, contentItems: [{ type: "inputText", text: JSON.stringify(result.error ? { ok: false, error: result.error, status: result.status } : { ok: true, result: result.result }) }] };
|
||
});
|
||
await bundle.transport.request("initialize", {});
|
||
thread = await bundle.transport.request("thread/start", {
|
||
cwd: fixture.workspace, model: request.model,
|
||
completionContract: { revision: "runner-api-eval-v1", criterionIds: ["objective"] },
|
||
config: { ...createSkilllessCodexThreadConfig(fixture.workspace), model_reasoning_effort: "low" },
|
||
permissions: "paperclip-runner-workspace-only", runtimeWorkspaceRoots: [fixture.workspace], approvalPolicy: "never",
|
||
baseInstructions: "You are operating a disposable real Paperclip company. Use the provided tools to do the user's task. Do not use shell, network, skills, or credentials. Stop when the requested work is verified. " + (request.arm === "baseline" ? "" : "Prefer available dedicated tools. Only use search_api and call_api when no dedicated tool supports the required operation or parameters. Do not search before ordinary dedicated tool use.") + "\n" + CONNECTION_INTENT_AGENT_GUIDANCE + (request.conversation ? "\n" + AGENT_CHAT_DIRECTIVE : ""),
|
||
dynamicTools: definitions, experimentalRawEvents: true, persistExtendedHistory: true,
|
||
});
|
||
if (request.preflight) {
|
||
terminalSeen = true;
|
||
usage = { inputTokens: 0, outputTokens: 0, cachedInputTokens: 0, estimatedCostNanodollars: 0, providerRequests: 0, preflight: true };
|
||
} else {
|
||
journal.append({ kind: "provider_turn_dispatch", thread, at: new Date().toISOString() });
|
||
providerTurnStarted = true;
|
||
await bundle.transport.request("turn/start", { input: [{ type: "text", text: prompt }] });
|
||
for await (const notification of bundle.transport.notifications()) {
|
||
const retained = { ...notification, observedAt: new Date().toISOString() };
|
||
journal.append({ kind: "notification", ...retained });
|
||
notifications.push(retained);
|
||
const item = record(record(notification.params).item);
|
||
if (["dynamicToolCall", "tool_call", "tool_result"].includes(item.type) && typeof item.id === "string") {
|
||
observedToolCallIds.add(item.id);
|
||
if (observedToolCallIds.size > 12) { error = "Attempt tool-call ceiling reached, including provider-rejected calls"; break; }
|
||
}
|
||
if (notification.method === "thread/tokenUsage/updated") {
|
||
const params = record(notification.params);
|
||
const tokenUsage = record(params.tokenUsage);
|
||
const cumulative = record(tokenUsage.total ?? tokenUsage.totalTokenUsage ?? tokenUsage.total_token_usage ?? tokenUsage);
|
||
if (request.model === "claude-sonnet-5" && params.runDeltaAvailable !== true) continue;
|
||
const total = request.model === "claude-sonnet-5" ? record(tokenUsage.runDelta) : cumulative;
|
||
const cacheWriteTokens = total.cacheWriteTokens ?? 0;
|
||
const inputTokens = (total.inputTokens ?? total.input_tokens) + (request.model === "claude-sonnet-5" ? (total.cacheReadTokens ?? 0) : isOpenRouter ? (total.cacheReadTokens ?? total.cachedInputTokens ?? 0) : 0);
|
||
const outputTokens = total.outputTokens ?? total.output_tokens;
|
||
const cachedInputTokens = total.cacheReadTokens ?? total.cachedInputTokens ?? total.cache_read_input_tokens ?? 0;
|
||
if ([inputTokens, outputTokens, cachedInputTokens, cacheWriteTokens].every(value => Number.isSafeInteger(value) && value >= 0)) {
|
||
const fingerprint = `${inputTokens}:${outputTokens}:${cachedInputTokens}`;
|
||
if (fingerprint !== lastUsageFingerprint) { usageUpdates++; lastUsageFingerprint = fingerprint; }
|
||
usage = { inputTokens, outputTokens, cachedInputTokens, cacheWriteTokens, providerRequests: (total.requests ?? total.providerRequests ?? 0) > 0 ? total.requests ?? total.providerRequests : null, providerUsageUpdateCount: usageUpdates, providerRequestCountSource: (total.requests ?? total.providerRequests ?? 0) > 0 ? "provider" : "not reported; providerUsageUpdateCount is a proxy", providerReportedCostNanodollars: cumulative.providerCostUsd > 0 ? Math.round(cumulative.providerCostUsd * 1e9) : null, ...estimateModelCostNanodollars(request.model, { inputTokens, outputTokens, cachedInputTokens }) };
|
||
// A conservative one-hour cache-write ceiling (2× standard input)
|
||
// covers either cache duration when the runtime omits its TTL.
|
||
if (request.model === "claude-sonnet-5" || request.model === "openrouter/anthropic/claude-sonnet-5") {
|
||
usage.estimatedCostNanodollars += cacheWriteTokens * 4_000;
|
||
usage.cacheWriteUsdPerMillionTokens = 4;
|
||
usage.cacheWritePricing = "Conservative one-hour cache-write rate; TTL not exposed";
|
||
}
|
||
if (Math.max(usage.estimatedCostNanodollars, usage.providerReportedCostNanodollars ?? 0) >= 500_000_000) { error = "Attempt cost ceiling reached"; break; }
|
||
}
|
||
}
|
||
if (notification.method === "turn/completed") {
|
||
terminalSeen = true;
|
||
const params = record(notification.params);
|
||
const terminal = record(params.turn);
|
||
if ((params.status ?? terminal.status) === "failed") error = String(record(params.error ?? terminal.error).message ?? "Provider turn failed");
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
evidence = bundle.evidence();
|
||
if (!request.preflight && (!usage || usage.inputTokens + usage.outputTokens === 0)) {
|
||
usage = null;
|
||
error ??= "Missing provider accounting; block further paid attempts";
|
||
}
|
||
}
|
||
} catch (caught) { error ??= caught instanceof Error ? caught.message : String(caught); }
|
||
finally {
|
||
if (timer) clearTimeout(timer);
|
||
if (bundle) {
|
||
evidence = bundle.evidence();
|
||
diagnosticTail = await readFile(join(server.root, `runner-${request.attemptId}`, "diagnostics", "runnerd.stderr.log"), "utf8").then(text => text.slice(-16000).replace(/sk-(?:ant-|or-v1-)[A-Za-z0-9_-]+/g, "[redacted]").replace(/Bearer\s+[^\s"']+/gi, "Bearer [redacted]").replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "[redacted JWT]")).catch(() => null);
|
||
}
|
||
await bundle?.transport.close();
|
||
}
|
||
if (!providerTurnStarted && !request.calls) {
|
||
usage = { inputTokens: 0, outputTokens: 0, cachedInputTokens: 0, estimatedCostNanodollars: 0, providerRequests: 0, accountingProvenance: "No provider turn/start was dispatched" };
|
||
}
|
||
const artifact = {
|
||
schema: "paperclip-runner/eval-session-artifact/v1", attemptId: request.attemptId,
|
||
requestedModel: request.calls ? "provider-free" : request.model ?? "provider-free", provider: request.calls ? "none" : provider, driver: request.calls ? "direct-authority-contract" : "real-server-api-tools",
|
||
evidenceMode: request.calls ? "provider-free-contract" : "live-provider",
|
||
providerSessionId: record(thread.thread).id ?? null, effectiveModel: record(thread.thread).model ?? null,
|
||
providerVersion: request.calls ? null : request.model === "gpt-5.6-luna" ? execFileSync("codex", ["--version"], { encoding: "utf8" }).trim() : providerVersion ?? record(evidence).providerVersion ?? null,
|
||
runtimeVersions: { node: process.versions.node, acpx: record(evidence).providerVersion, agentServer: record(evidence).agentServerVersion, agentRuntime: record(evidence).agentRuntimeVersion },
|
||
runtimeBuild,
|
||
timing: { startedAt, finishedAt: new Date().toISOString(), durationMs: performance.now() - started },
|
||
usage, accountingComplete: Boolean(request.calls) || !providerTurnStarted || terminalSeen, providerTurnStarted, observedProviderToolCalls: observedToolCallIds.size, diagnosticTail, error, calls, notifications, evidence, thread, prompt, arm: request.arm ?? "treatment",
|
||
fixture: substitutions, initialState, state: await fixture.snapshot(),
|
||
toolSchemaBytes: Buffer.byteLength(JSON.stringify(definitions)), definitions,
|
||
};
|
||
// The controller supplies a unique retained attempt directory; never overwrite evidence.
|
||
journal.append({ kind: "attempt_finished", error, usage, terminalSeen, at: new Date().toISOString() });
|
||
journal.close();
|
||
await writeFile(join(directory, "artifact.json"), JSON.stringify(artifact, null, 2), { flag: "wx", mode: 0o600 });
|
||
output({ attemptId: request.attemptId, artifactPath: join(directory, "artifact.json"), error, usage });
|
||
}
|
||
} finally { await server.close(); }
|