mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-08 12:33:05 +01:00
## Thinking Path > - Paperclip helps people manage AI agents at work. > - Cursor Cloud hosts execution behind its API. > - Product setup still expected a Paperclip Computer. > - Managed-only tenants therefore rejected valid setup. > - This admits the validated API-owned controller. > - Authority, Stop proof, budgets and cleanup remain enforced. ## Linked Issues or Issue Description Refs #18068 and #18069; both dependencies have merged. **What happened?** Managed-only setup still requested a Computer. Live tests exposed missing Cursor Stop proof and duplicate replay. **Expected behavior** Use Cursor’s API controller. Verify provider/controller termination and replay each log identity once. **Steps to reproduce** Enable native Runner/managed-only. Configure Cursor model/repository/key without a Computer, then Test, finish setup, run and Stop. ## What Changed - Derive API-only placement from validated native Cursor configuration; reject placement/command/workspace/home overrides and keep Kubernetes-only execution closed. - Skip Computers/checkout/workspace realization. Keep scoped tools, completion, private staging, budgets, leases and recovery. Persist placement; reject contradictions. - Align Cloud cards, Test, Save and Finish setup; hold unready drafts. Legacy keeps its Computer, credential and policy checks. - Verify Stop from exact API ownership, audited intent, provider-terminal proof, no Computer/process ownership and controller retirement. Recheck immediate/deferred retirement; wake existing recovery on durable evidence. - Clear warnings when the actual stopped target later has authoritative confirmation. Keep missing/other-run negatives and the existing predicate. - Publish safe status refresh after full-proof ACK. Retain bounded native/physical cancellation history; add no poller or weaker proof path. ## Verification Core merged as `3910352c923a`; Product merged as `27d35314be8e`. Public branch `5f86eb66b081` has tree `67344151d303`. Its exact-head Greptile summary is 5/5; the fresh audit found zero unresolved threads and complete pagination. The controlled workspace retry and required summary passed. All 59 current-head contexts are terminal and clean. Prior green-36 evidence keeps its identity. [Current CI](https://github.com/paperclipai/paperclip/actions/runs/41680511731) first failed workspaces-a 1/2: the CLI company-import/export beforeAll 30-second runtime-info/child-PID/HTTP readiness wait expired. All 431 UI files/4,714 tests and 285 other CLI tests passed (one skip). The cause remains UNKNOWN. Child output records startup recovery complete, but buffered CI prefixes do not establish its relation to the waiter deadline; runtime-file/PID/last-health state was not captured. Both unchanged local probes were RED. The second observed dependency preflight still pending at the deadline; observer overhead was not quantified. Neither proves the CI cause. After all functional jobs finished, only the queued metadata summary was cancelled; the other 48 records stayed unchanged. Attempt 1 retains 46 successes, the original failure, one skip and the cancelled summary. One same-head debug retry was admitted at 18:42 UTC on November 3. Its workspace job passed at 19:23 UTC on the same checkout: UI 431 files/4,714 tests and CLI 33 files/286 tests, including company import/export. Test caching was disabled. The new `ci / verify` summary passed; workflow attempt 2 completed SUCCESS. Required `ci / e2e` also passed. The final check at 19:53 UTC on November 3 found all 59 current-head contexts terminal and clean: zero pending and zero failing. The 47 inherited completed/skipped rows are not new executions. No code, assertion or timeout changed; success does not explain the original failure or erase the local REDs. CI checkout is `1ea9d8608ced`/tree `78cb1ec13d59` (parents `2e37c73c05fe`, 5f86); both workflows use 2e37. Its 20 extra paths add low-memory build/Rust task-memory. Scripts cohere; later matrix changes only labels, with no newer debug-cache steps. Static audit found no blocker. Supported API arguments omit the memory flag: no default monitor/instruction changes. Flagged external launchers can change Cursor instructions/digests and remain unqualified. The merge added 41 master-identical paths, retained the green-36 inbox hunk and found UI fixtures matching upstream. Startup/backup, recovery projection, sleep diagnostics and binary backup change production. Static audit found eight Stop/ACK owner blobs and 37 sleep-work SQL templates unchanged, with sleep fences/single-flight accounting intact. Exact precommit tree: 416/416 across eight server files, binary backup 1/1, server types PASS; repeated scopes are not summed. The deferred-retirement P1 reproduced three real-DB/owned-process failures; missing proof stayed unverified. Recovery passed 47 process cases/33 proof negatives. Warning repair binds actual targets to same-run proof. Validation passed 729 scoped UI cases, a separate 359-case thread run, 111 backend cases (84 CAS, 6 assembled, 21 activity/privacy), types/tokens. Proof validators/predicate are unchanged; no new poller or increased timeout. The d8d3 attempt stays FAILED: 45 passes, two workspaces-a failures, derived verify failure and one skip. Both shards shared three failures: two successful mocks omitted the account guard’s required userId. The two-line fixture repair changed no guard, assertion or timeout. Three failures reproduced; 54 access/auth tests then passed, including account-change/denial negatives, plus UI types/tokens. The 69285 attempt stays FAILED: 49 jobs, 46 passed, serialized shard 9 failed, its verify aggregate failed and one selection job skipped. The shard passed 575/576 cases. Its aborted-snapshot case expected nine computes but saw eight: a final HTTP 200 coalesced while seven ordinary reads had not proved the aborted compute settled. Earlier CI and the unmodified local baseline passed with a miss; no local RED is claimed. The repair awaits the snapshot, allows exactly one extra GET if coalesced, then requires a miss and retains nine computes/all HTTP429 assertions. No production code, hook, loop, sleep or timeout changed. Six inbox and seven cache/admission cases passed locally, plus server types; 30 unrelated cases were filtered. Green 36 passed 576/576 without taking the extra-GET branch; local runs also missed that schedule. Current CI event merge 1ea9 now passed 576/576 and naturally exercised the former failure: coalesced (count 2, 1ms), then exactly one fresh miss (count 1, 16ms), with strict nine-compute/HTTP429 assertions intact. No instrumentation or retry was added. Earlier compatibility passed scoped remote/inbox, routine, API-placement and UI tests, plus types/migrations/snapshots/maps/tokens. The 89-path adoption restored fleet routing without workflow overrides or added skips. Each result retains its source identity. Live qualification remains actual `9af1a5de42a2`: unchanged Artifact grader PASSED 17/17 and active-Stop grader PASSED 21/21. All three provider test resources were deleted canonically with GET404; post-delete download returned the exact 27 bytes. Histories stayed stable (Artifact 121 and Stop 67 canonical identities), with 21 company runs, zero active work and no accounting/cancellation/reservation debt or integrity findings. Saved settings reopened; no-prompt Test/Linux admission passed with `claude-sonnet-4-5`. No new Save is claimed. The first Stop sampling case stays FAILED on a 10.373-second gap. Unchanged retry kept all 24 samples: 35.076 seconds quiet, maximum gap 4.584 seconds, plus a separate CANCELLED/artifact-absent read after 180 seconds. Initial grading rejected locator spelling before functional checks; metadata changed only after same-file/inode/byte proof, with raw evidence/oracles unchanged. Original Question/Plan/reconnect and historical deleted-artifact results keep their identities. Git trees verified 11 history-only conflicts and six earlier mainline paths. Hosted 9af to the public BRANCH differs in 222 paths; 13,500 other mode/blob leaves match. Runner runtime implementations and six observer/driver pins match 9af on that branch only; inherited `drivers/acpx/runtime-host.test.ts` differs. No all-Runner/src, CI/latest-master runtime or image equality is claimed. Later static audits through `8ab89f41e499` found no concrete API-only blocker. That base adds completed-history sleep proofs and an MCP cleanup migration; protected Stop/ACK owners are unchanged. These later changes are outside this CI and have no live qualification here. Host duplicate-card and later recovery/UI repairs retain separate proof, not deployed 9af identity. Direct-key coverage requires absent aiConnection; API-only placement skips inherited remote-workspace disk-full paths, and config-read gates match their parent. Other retained failures: stale fixture 132/133; E8 48/135 with 87 reset-hook failures; Mac 17 SQL failures/skips; title/startup/custody/Stop/deletion unknown causes and bounded recoveries; superseded warning/50 duplicate identities; pre-repair ACK/Core CI failures. Fixture RED/GREEN passed 7/7 browser and 121/121 shutdown tests with a failing broken-unsubscribe control; stable WSP wrapper passed 128 after physical teardown failure. No full local-suite pass is inferred. All paid attempts remain recorded; vendor dollar cost is UNKNOWN. ## Risks Experimental: Cursor independently acknowledges neither the effective model nor instruction digest before the first prompt. Explicit values are submitted and behavior checked live; unpriced provider dollar cost stays UNKNOWN. The placement exception applies only to validated native Cursor API execution. Other local work remains denied under managed-only policy. Missing/stale Stop or cleanup proof stays pending; damaged archives remain failed. Explicit Legacy keeps its existing policy owners. ## Model Used OpenAI Codex/GPT-6 family: tools, execution, browser checks, delegated review. API ID/context window unavailable. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used and the limits of available model metadata - [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 linked public issues or described the issue in this PR - [x] I have not referenced internal or instance-local Paperclip issues or links - [x] My branch describes the change and contains no internal ticket ID - [x] I have run the scoped local tests reported above; retained failures are stated separately - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented the risks - [x] All required CI gates pass on the current head - [x] Fresh Greptile is 5/5 with no unresolved findings on the current head - [x] I will address all reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
930 lines
42 KiB
TypeScript
930 lines
42 KiB
TypeScript
import { resolveGrokDisableWebSearch } from "../../vendor/paperclip-runner/index.js";
|
|
import { agentHarnessType, normalizeClaudeRunnerOptions } from "@paperclipai/shared";
|
|
import { resolveClaudeEffort, resolveGrokEffort, resolveQualifiedAcpxProfile } from "../../vendor/paperclip-runner/index.js";
|
|
import {
|
|
isPaperclipRunnerProvider,
|
|
PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES,
|
|
PAPERCLIP_RUNNER_ACPX_PROFILES,
|
|
resolvePaperclipRunnerPermissionMode,
|
|
resolvePaperclipRunnerCursorMode,
|
|
resolvePaperclipRunnerPiThinkingLevel,
|
|
type PaperclipRunnerProvider,
|
|
} from "@paperclipai/adapter-utils";
|
|
import {
|
|
codexLocalReasoningEffortsForModel,
|
|
isCodexLocalKnownModel,
|
|
} from "@paperclipai/adapter-codex-local";
|
|
import {
|
|
AGENTCORE_QUALIFIED_MODEL,
|
|
CLAUDE_MANAGED_QUALIFIED_MODEL,
|
|
} from "../provider-profile-qualification.js";
|
|
import { resolveAcpxQualification, resolveAntigravityCandidateAdmission, resolveKimiCandidateAdmission, type AcpxQualificationCandidate } from "./acpx-qualification.js";
|
|
import { compatibleCodexModel } from "./codex-model-fallback.js";
|
|
import { parseNativeCursorCloudConfig, type NativeCursorCloudConfig } from "../../vendor/paperclip-runner/index.js";
|
|
|
|
export const QUALIFIED_OPENCODE_RUNNER_VERSION = "1.18.34" as const;
|
|
export const DEFAULT_OPENCODE_RUNNER_MODEL =
|
|
"openrouter/deepseek/deepseek-v4-flash-0731" as const;
|
|
export const CLAUDE_MANAGED_BETA_VERSION = "managed-agents-2026-04-01" as const;
|
|
|
|
export const DEFAULT_ACPX_RUNNER_MODELS = {
|
|
grok: "grok-4.7",
|
|
claude: "claude-opus-5-5",
|
|
// These profiles require explicit configuration. Admission belongs to the runner.
|
|
codex: null,
|
|
cursor: null,
|
|
copilot: null,
|
|
pi: null,
|
|
kimi: null,
|
|
} as const;
|
|
|
|
export type QualifiedPaperclipRunnerAcpxAgent =
|
|
keyof typeof DEFAULT_ACPX_RUNNER_MODELS;
|
|
type AdmittedPaperclipRunnerAcpxAgent = QualifiedPaperclipRunnerAcpxAgent | AcpxQualificationCandidate | "antigravity";
|
|
|
|
export type PaperclipRunnerProviderProfile =
|
|
| { provider: "cursor_cloud"; backend: "cursor_cloud_api"; model: string }
|
|
| { provider: "muse"; backend: "muse_external"; model: null; museBindingId: string }
|
|
| { provider: "grok_bot"; backend: "grok_bot_mcp"; model: null; externalBindingId: string }
|
|
| { provider: "openai_dot"; backend: "openai_dot_mcp"; model: null; dotBindingId: string }
|
|
| {
|
|
provider: "codex";
|
|
backend: "codex_app_server";
|
|
model: string | null;
|
|
}
|
|
| {
|
|
provider: "opencode";
|
|
backend: "opencode_server";
|
|
model: string;
|
|
}
|
|
| {
|
|
provider: "claude_managed";
|
|
backend: "claude_managed_agents_api";
|
|
managedProfileId: string;
|
|
model: string | null;
|
|
maxSessionListCostUsd: number | null;
|
|
}
|
|
| {
|
|
provider: "aws_agentcore";
|
|
backend: "aws_agentcore_harness_api";
|
|
agentCoreProfileId: string;
|
|
model: string | null;
|
|
maxEstimatedSessionCostUsd: number | null;
|
|
}
|
|
| {
|
|
provider: "acpx";
|
|
backend: "acpx_runtime";
|
|
model: string;
|
|
acpxAgent: AdmittedPaperclipRunnerAcpxAgent;
|
|
};
|
|
|
|
export type PaperclipRunnerNativeProviderInput =
|
|
| { provider: "cursor_cloud"; model: string; cursorCloud: NativeCursorCloudConfig }
|
|
| { provider: "muse"; model: null; museBinding: import("../../vendor/paperclip-runner/index.js").MuseBindingSnapshot }
|
|
| { provider: "grok_bot"; model: null; dotBinding: import("../../vendor/paperclip-runner/index.js").DotBindingSnapshot }
|
|
| { provider: "openai_dot"; model: null; dotBinding: import("../../vendor/paperclip-runner/index.js").DotBindingSnapshot }
|
|
| {
|
|
provider: "codex";
|
|
model: string | null;
|
|
homeMode?: "isolated" | "preconfigured";
|
|
codexApprovalPolicy: "never" | "on-request" | "untrusted";
|
|
codexReasoningEffort?: string;
|
|
codexWebSearch?: "disabled";
|
|
}
|
|
| {
|
|
provider: "opencode";
|
|
model: string;
|
|
opencodePermissionMode: "allow" | "ask" | "deny";
|
|
}
|
|
| {
|
|
provider: "claude_managed";
|
|
model: string;
|
|
managedProfile: {
|
|
profileId: string;
|
|
anthropicAgentId: string;
|
|
agentVersion: string;
|
|
environmentId: string;
|
|
betaVersion: typeof CLAUDE_MANAGED_BETA_VERSION;
|
|
};
|
|
maxSessionListCostUsd: number;
|
|
}
|
|
| {
|
|
provider: "aws_agentcore";
|
|
model: string;
|
|
agentCoreProfile: {
|
|
profileId: string;
|
|
region: string;
|
|
accountId: string;
|
|
harnessArn: string;
|
|
harnessVersion: string;
|
|
endpointArn: string;
|
|
endpointQualifier: string;
|
|
agentRuntimeArn: string;
|
|
memoryArn: string;
|
|
memoryId: string;
|
|
invocationRoleArn: string;
|
|
contextBucket: string;
|
|
contextPrefix: string;
|
|
contextKmsKeyArn: string;
|
|
qualificationRevision: string;
|
|
eventExpiryDays: 90;
|
|
};
|
|
maxEstimatedSessionCostUsd: number;
|
|
invocationLimits: {
|
|
maxIterations: number;
|
|
maxOutputTokens: number;
|
|
timeoutSeconds: number;
|
|
};
|
|
}
|
|
| {
|
|
provider: "acpx";
|
|
model: string;
|
|
acpxAgent: AdmittedPaperclipRunnerAcpxAgent;
|
|
homeMode?: "isolated" | "preconfigured";
|
|
acpxPermissionMode: "approve-all" | "approve-paperclip" | "approve-reads" | "deny-all";
|
|
acpxSessionMode?: "agent" | "plan" | "ask";
|
|
piThinkingLevel?: "off" | "low" | "high" | "max";
|
|
claudeEffort?: "low" | "medium" | "high" | "xhigh" | "max";
|
|
grokEffort?: "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
grokDisableWebSearch?: boolean;
|
|
};
|
|
|
|
export class PaperclipRunnerProviderProfileError extends Error {
|
|
constructor(
|
|
readonly code: string,
|
|
message: string,
|
|
) {
|
|
super(message);
|
|
this.name = "PaperclipRunnerProviderProfileError";
|
|
}
|
|
}
|
|
|
|
function asRecord(value: unknown): Record<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
? value as Record<string, unknown>
|
|
: {};
|
|
}
|
|
|
|
function optionalString(value: unknown): string | null {
|
|
return typeof value === "string" && value.trim().length > 0
|
|
? value.trim()
|
|
: null;
|
|
}
|
|
|
|
export function resolvePaperclipRunnerCursorCloudConfig(config: Record<string, unknown>): NativeCursorCloudConfig {
|
|
const unsupportedEnvironment = Object.keys(asRecord(config.env)).filter(key => key !== "CURSOR_API_KEY");
|
|
if (unsupportedEnvironment.length) {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_cursor_cloud_config_invalid",
|
|
`Cursor Cloud with Paperclip Runner only supports CURSOR_API_KEY in agent environment settings. Configure hosted secrets in your Cursor Cloud environment instead of ${unsupportedEnvironment.join(", ")}.`);
|
|
}
|
|
for (const [current, legacy] of [["cloudEnvType", "runtimeEnvType"], ["cloudEnvName", "runtimeEnvName"], ["repoRef", "repoStartingRef"], ["prUrl", "repoPullRequestUrl"]]) {
|
|
if (config[current] !== undefined && config[legacy] !== undefined && config[current] !== config[legacy]) {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_cursor_cloud_config_invalid", `Choose one matching value for ${current} and ${legacy}.`);
|
|
}
|
|
}
|
|
const unsupported = ["codexPermissionMode", "opencodePermissionMode", "acpxPermissionMode", "acpxSessionMode", "command", "extraArgs", "promptTemplate", "bootstrapPromptTemplate", "modelReasoningEffort", "reasoningEffort", "effort", "modelParams", "executionPlacement", "providerApiPlacement", "controllerPlacement", "apiOnly", "cwd", "workspaceRuntime", "workspaceStrategy"]
|
|
.filter(key => config[key] !== undefined && config[key] !== "" && !(Array.isArray(config[key]) && config[key].length === 0));
|
|
if (config.lifecycleMode !== undefined && config.lifecycleMode !== "per_turn") unsupported.push("lifecycleMode");
|
|
if (config.homeMode === "preconfigured") unsupported.push("homeMode");
|
|
if (unsupported.length) throw new PaperclipRunnerProviderProfileError("paperclip_runner_cursor_cloud_config_invalid", `Cursor Cloud cannot honor these settings: ${unsupported.join(", ")}.`);
|
|
const repoUrl = optionalString(config.repoUrl);
|
|
const startingRef = optionalString(config.repoRef ?? config.repoStartingRef);
|
|
const prUrl = optionalString(config.prUrl ?? config.repoPullRequestUrl);
|
|
const envName = optionalString(config.cloudEnvName ?? config.runtimeEnvName);
|
|
try {
|
|
return parseNativeCursorCloudConfig({
|
|
schema: "paperclip.cursor-cloud.config.v1",
|
|
repos: repoUrl ? [{ url: repoUrl, ...(startingRef ? { startingRef } : {}), ...(prUrl ? { prUrl } : {}) }] : [],
|
|
env: { type: config.cloudEnvType ?? config.runtimeEnvType ?? "cloud", ...(envName ? { name: envName } : {}) },
|
|
...Object.fromEntries(["workOnCurrentBranch", "autoCreatePR", "skipReviewerRequest"].filter(key => config[key] !== undefined).map(key => [key, config[key]])),
|
|
...(config.cursorCloudTimeoutMs !== undefined ? { timeoutMs: config.cursorCloudTimeoutMs } : {}),
|
|
});
|
|
} catch {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_cursor_cloud_config_invalid", "Cursor Cloud requires an HTTPS repository or named Cursor cloud environment, cloud-hosted execution, and supported settings. Its timeout must be between 1 second and 1 hour.");
|
|
}
|
|
}
|
|
|
|
/** Configuration can be saved before pairing; task admission requires a binding. */
|
|
export function validatePaperclipRunnerDotConfig(config: Record<string, unknown>, requireBinding = true): string | null {
|
|
const bindingId = optionalString(config.dotBindingId);
|
|
if ((requireBinding && !bindingId) || (bindingId && !/^[0-9a-f-]{36}$/i.test(bindingId))
|
|
|| config.allowUnmeteredProvider !== true || (config.lifecycleMode && config.lifecycleMode !== "per_turn")
|
|
|| optionalString(config.model)) {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_dot_config_invalid", "Dot requires per-turn lifecycle and explicit externally billed, unmetered-provider acknowledgement. Pair a binding before assigning work.");
|
|
}
|
|
return bindingId;
|
|
}
|
|
|
|
/** Closed personal runtime configuration; model and workspace grants are excluded. */
|
|
export function validatePaperclipRunnerMuseConfig(config: Record<string, unknown>, requireBinding = true): string | null {
|
|
const bindingId = optionalString(config.museBindingId);
|
|
if ((requireBinding && !bindingId) || (bindingId && !/^[0-9a-f-]{36}$/i.test(bindingId))
|
|
|| config.allowUnmeteredProvider !== true || (config.lifecycleMode && config.lifecycleMode !== "per_turn")
|
|
|| optionalString(config.model) || config.dotWorkspaceAccess === true || config.dotAttachmentAccess === true) {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_muse_config_invalid", "Muse requires a paired personal-agent binding, per-turn lifecycle and unavailable-usage acknowledgement.");
|
|
}
|
|
return bindingId;
|
|
}
|
|
|
|
export function validatePaperclipRunnerGrokConfig(config: Record<string, unknown>, requireBinding = true): string | null {
|
|
const bindingId = optionalString(config.externalBindingId);
|
|
if ((requireBinding && !bindingId) || (bindingId && !/^[0-9a-f-]{36}$/i.test(bindingId))
|
|
|| config.allowUnmeteredProvider !== true || (config.lifecycleMode && config.lifecycleMode !== "per_turn")
|
|
|| optionalString(config.model) || config.dotWorkspaceAccess === true || config.dotAttachmentAccess === true
|
|
|| optionalString(config.cwd) || optionalString(config.command)) {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_grok_config_invalid", "Grok Bot requires a bound per-turn work session and an explicit acknowledgement of unreported provider spending. Paperclip workspace, shell and third-party app tools are unavailable.");
|
|
}
|
|
return bindingId;
|
|
}
|
|
|
|
/** A task may change a Runner model (and supported effort), but not provider identity. */
|
|
export function projectPaperclipRunnerTaskConfig(
|
|
backend: "codex_app_server" | "opencode_server" | "acpx_runtime" | "cursor_cloud_api",
|
|
agentConfig: unknown,
|
|
taskOverrides: unknown,
|
|
managedModel?: string,
|
|
): Record<string, unknown> {
|
|
const base = asRecord(agentConfig);
|
|
const task = asRecord(taskOverrides);
|
|
const config = { ...base };
|
|
// The server resolves a connection's model namespace after task overrides.
|
|
// Carry that model into durable input without allowing routing to change the harness.
|
|
const model = optionalString(managedModel) ?? optionalString(task.model);
|
|
const grok = backend === "acpx_runtime" && agentHarnessType("paperclip_runner", base) === "grok_local";
|
|
const supportsEffort = backend === "codex_app_server" || grok || (backend === "acpx_runtime" && agentHarnessType("paperclip_runner", base) === "claude_local");
|
|
const effortKey = supportsEffort
|
|
? ["modelReasoningEffort", "reasoningEffort", "effort"].find((key) => key in task)
|
|
: undefined;
|
|
if (supportsEffort && ((model !== null && model !== optionalString(base.model)) || effortKey !== undefined)) {
|
|
delete config.modelReasoningEffort;
|
|
delete config.reasoningEffort;
|
|
delete config.effort;
|
|
}
|
|
if (model !== null) config.model = model;
|
|
if (effortKey !== undefined) config[grok ? "reasoningEffort" : "modelReasoningEffort"] = task[effortKey];
|
|
return config;
|
|
}
|
|
|
|
function positiveNumberOrNull(
|
|
value: unknown,
|
|
code: string,
|
|
message: string,
|
|
): number | null {
|
|
if (value === undefined || value === null || value === "") return null;
|
|
const parsed = Number(value);
|
|
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
throw new PaperclipRunnerProviderProfileError(code, message);
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
function boundedPositiveInteger(
|
|
value: unknown,
|
|
fallback: number,
|
|
maximum: number,
|
|
code: string,
|
|
label: string,
|
|
): number {
|
|
if (value === undefined || value === null || value === "") return fallback;
|
|
if (
|
|
typeof value !== "number"
|
|
|| !Number.isSafeInteger(value)
|
|
|| value <= 0
|
|
|| value > maximum
|
|
) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
code,
|
|
`${label} must be an integer between 1 and ${maximum}.`,
|
|
);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function assertPermissionMode(
|
|
provider: PaperclipRunnerProvider,
|
|
config: Record<string, unknown>,
|
|
): void {
|
|
const capability = PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES[provider];
|
|
if (!capability.configurable) return;
|
|
const configured = config[capability.configKey];
|
|
if (
|
|
configured !== undefined
|
|
&& resolvePaperclipRunnerPermissionMode(provider, configured) !== configured
|
|
) {
|
|
if (provider === "codex") {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_codex_permission_mode_unqualified",
|
|
"Paperclip Runner currently supports Codex only with codexPermissionMode set to never. Update the agent configuration before starting a new native run.",
|
|
);
|
|
}
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"runner_permission_mode_invalid",
|
|
`${capability.configKey} is not supported by ${provider}.`,
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Rebind a persisted Claude Managed run only to the still-qualified profile
|
|
* and the profile's current company secret. The secret itself may rotate, but
|
|
* the agent configuration must rotate its binding to the same profile-owned
|
|
* secret before recovery can continue.
|
|
*/
|
|
export function assertManagedProfileRecoveryBinding(input: {
|
|
adapterConfig: unknown;
|
|
snapshot: {
|
|
profileId: string;
|
|
anthropicAgentId: string;
|
|
agentVersion: string;
|
|
environmentId: string;
|
|
betaVersion: string;
|
|
};
|
|
stored: {
|
|
id: string;
|
|
anthropicAgentId: string;
|
|
agentVersion: string;
|
|
environmentId: string;
|
|
betaVersion: string;
|
|
apiKeySecretId: string;
|
|
};
|
|
}): void {
|
|
const { snapshot, stored } = input;
|
|
if (
|
|
snapshot.profileId !== stored.id
|
|
|| snapshot.anthropicAgentId !== stored.anthropicAgentId
|
|
|| snapshot.agentVersion !== stored.agentVersion
|
|
|| snapshot.environmentId !== stored.environmentId
|
|
|| snapshot.betaVersion !== stored.betaVersion
|
|
) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_claude_managed_recovery_identity_mismatch",
|
|
"The persisted Claude Managed identity no longer matches its qualified profile.",
|
|
);
|
|
}
|
|
const rawBinding = asRecord(asRecord(input.adapterConfig).env).ANTHROPIC_API_KEY;
|
|
const boundSecretId = asRecord(rawBinding).secretId;
|
|
if (boundSecretId !== stored.apiKeySecretId) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_claude_managed_recovery_secret_mismatch",
|
|
"The persisted Claude Managed run is not bound to its profile's current API-key secret.",
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Revalidate the operator's AWS profile revocation and immutable identity on recovery. */
|
|
export function assertAgentCoreProfileRecoveryBinding(input: {
|
|
snapshot: {
|
|
profileId: string;
|
|
region: string;
|
|
accountId: string;
|
|
harnessArn: string;
|
|
harnessVersion: string;
|
|
endpointArn: string;
|
|
endpointQualifier: string;
|
|
agentRuntimeArn: string;
|
|
memoryArn: string;
|
|
memoryId: string;
|
|
invocationRoleArn: string;
|
|
contextBucket: string;
|
|
contextPrefix: string;
|
|
contextKmsKeyArn: string;
|
|
qualificationRevision: string;
|
|
eventExpiryDays: number;
|
|
};
|
|
stored: {
|
|
id: string;
|
|
configuration: Record<string, unknown>;
|
|
};
|
|
}): void {
|
|
const { snapshot, stored } = input;
|
|
const configuration = asRecord(stored.configuration);
|
|
const fields = [
|
|
"region",
|
|
"accountId",
|
|
"harnessArn",
|
|
"harnessVersion",
|
|
"endpointArn",
|
|
"endpointQualifier",
|
|
"agentRuntimeArn",
|
|
"memoryArn",
|
|
"memoryId",
|
|
"invocationRoleArn",
|
|
"contextBucket",
|
|
"contextPrefix",
|
|
"contextKmsKeyArn",
|
|
"qualificationRevision",
|
|
"eventExpiryDays",
|
|
] as const;
|
|
if (
|
|
snapshot.profileId !== stored.id
|
|
|| fields.some((field) => snapshot[field] !== configuration[field])
|
|
) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_aws_agentcore_recovery_identity_mismatch",
|
|
"The persisted AWS AgentCore identity no longer matches its qualified profile.",
|
|
);
|
|
}
|
|
}
|
|
|
|
export function claudeRunnerUnsupportedSettings(config: Record<string, unknown>): string[] {
|
|
config = normalizeClaudeRunnerOptions(config).config;
|
|
const unsupported = ["chrome", "agentCommand", "acpAgentCommand", "stateDir", "acpStateDir", "warmHandleIdleMs", "acpWarmHandleIdleMs", "extraArgs", "args", "filesystemScope", "filesystemExtraPaths", "filesystemSandboxCommand", "networkScope", "networkAllowlist", "maxTurnsPerRun", "permissionMode", "acpPermissionMode"]
|
|
.filter(key => config[key] !== undefined && config[key] !== false && config[key] !== "" && config[key] !== 0 && !(Array.isArray(config[key]) && config[key].length === 0));
|
|
if (config.command && config.command !== "claude") unsupported.push("command");
|
|
if (config.mode && config.mode !== "persistent") unsupported.push("mode");
|
|
if (config.acpMode && config.acpMode !== "persistent") unsupported.push("acpMode");
|
|
if (config.engine && !["auto", "cli", "acp"].includes(String(config.engine))) unsupported.push("engine");
|
|
if (config.nonInteractivePermissions && config.nonInteractivePermissions !== "deny") unsupported.push("nonInteractivePermissions");
|
|
if (config.acpNonInteractivePermissions && config.acpNonInteractivePermissions !== "deny") unsupported.push("acpNonInteractivePermissions");
|
|
if (config.dangerouslySkipPermissions === false) unsupported.push("dangerouslySkipPermissions");
|
|
return unsupported;
|
|
}
|
|
|
|
/**
|
|
* Resolve the immutable provider identity used for a fresh Paperclip Runner
|
|
* selection. The persisted adapterConfig is the authority; runtimeConfig is
|
|
* deliberately not consulted so model-profile or migration metadata cannot
|
|
* silently switch the harness selected for a run.
|
|
*/
|
|
export function resolvePaperclipRunnerProviderProfile(
|
|
adapterConfig: unknown,
|
|
context: { companyId?: string } = {},
|
|
): PaperclipRunnerProviderProfile {
|
|
const config = asRecord(adapterConfig);
|
|
const candidate = config.provider ?? "codex";
|
|
if (!isPaperclipRunnerProvider(candidate)) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_provider_unsupported",
|
|
"Paperclip Runner provider must be Codex, OpenCode, Claude Managed, AWS AgentCore, or ACPX.",
|
|
);
|
|
}
|
|
|
|
if (candidate === "cursor_cloud") {
|
|
const model = optionalString(config.model);
|
|
if (!model) throw new PaperclipRunnerProviderProfileError("paperclip_runner_cursor_cloud_model_required", "Cursor Cloud requires an explicit model. Select a model before testing or assigning work.");
|
|
resolvePaperclipRunnerCursorCloudConfig(config);
|
|
return { provider: "cursor_cloud", backend: "cursor_cloud_api", model };
|
|
}
|
|
|
|
if (candidate === "muse") {
|
|
const bindingId = validatePaperclipRunnerMuseConfig(config)!;
|
|
return { provider: "muse", backend: "muse_external", model: null, museBindingId: bindingId };
|
|
}
|
|
if (candidate === "grok_bot") {
|
|
return { provider: "grok_bot", backend: "grok_bot_mcp", model: null, externalBindingId: validatePaperclipRunnerGrokConfig(config)! };
|
|
}
|
|
if (candidate === "openai_dot") {
|
|
const bindingId = validatePaperclipRunnerDotConfig(config)!;
|
|
return { provider: "openai_dot", backend: "openai_dot_mcp", model: null, dotBindingId: bindingId };
|
|
}
|
|
if (candidate === "acpx" && agentHarnessType("paperclip_runner", config) === "claude_local") {
|
|
const unsupported = claudeRunnerUnsupportedSettings(config);
|
|
if (unsupported.length) throw new PaperclipRunnerProviderProfileError("agent_runner_config_incompatible",
|
|
`Paperclip Runner cannot honor these settings: ${unsupported.join(", ")}. Remove them or select Legacy runner in Advanced.`);
|
|
}
|
|
assertPermissionMode(candidate, config);
|
|
try {
|
|
resolvePaperclipRunnerCursorMode(candidate, config.acpxAgent, config.acpxSessionMode);
|
|
} catch (error) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_mode_invalid",
|
|
error instanceof Error ? error.message : "Invalid Cursor session mode",
|
|
);
|
|
}
|
|
try { if (candidate === "acpx" && agentHarnessType("paperclip_runner", config) === "claude_local") resolveClaudeEffort("claude", config.modelReasoningEffort ?? config.reasoningEffort ?? config.effort); } catch (error) {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_claude_effort_invalid", error instanceof Error ? error.message : "Invalid Claude effort");
|
|
}
|
|
try { if (candidate === "acpx" && config.acpxAgent === "grok") resolveGrokEffort("grok", config.modelReasoningEffort ?? config.reasoningEffort ?? config.effort); } catch (error) {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_grok_effort_invalid", error instanceof Error ? error.message : "Invalid Grok effort");
|
|
}
|
|
try { if (candidate === "acpx" && config.acpxAgent === "grok") resolveGrokDisableWebSearch("grok", config.disableWebSearch); } catch (error) {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_grok_search_invalid", error instanceof Error ? error.message : "Invalid Grok search policy");
|
|
}
|
|
try { resolvePaperclipRunnerPiThinkingLevel(candidate, config.acpxAgent, config.piThinkingLevel); } catch (error) {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_pi_thinking_invalid", error instanceof Error ? error.message : "Invalid Pi thinking level");
|
|
}
|
|
const model = optionalString(config.model);
|
|
if (candidate === "codex") {
|
|
return {
|
|
provider: "codex",
|
|
backend: "codex_app_server",
|
|
model,
|
|
};
|
|
}
|
|
|
|
if (candidate === "opencode") {
|
|
if (!model || !model.includes("/") || model.endsWith("/")) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_opencode_model_invalid",
|
|
"Paperclip Runner OpenCode requires model in provider/model form.",
|
|
);
|
|
}
|
|
return {
|
|
provider: "opencode",
|
|
backend: "opencode_server",
|
|
model,
|
|
};
|
|
}
|
|
|
|
if (candidate === "claude_managed") {
|
|
const managedProfileId = optionalString(config.managedProfileId);
|
|
if (!managedProfileId) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_claude_managed_profile_required",
|
|
"Paperclip Runner Claude Managed requires a company managed-agent profile.",
|
|
);
|
|
}
|
|
if (config.managedAgentsRetentionAcknowledged !== true) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_claude_managed_retention_required",
|
|
"Paperclip Runner Claude Managed requires acknowledgement of stateful beta retention.",
|
|
);
|
|
}
|
|
if (model !== null && model !== CLAUDE_MANAGED_QUALIFIED_MODEL) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_claude_managed_model_unqualified",
|
|
`The Claude Managed profile requires exact model ${CLAUDE_MANAGED_QUALIFIED_MODEL}.`,
|
|
);
|
|
}
|
|
return {
|
|
provider: "claude_managed",
|
|
backend: "claude_managed_agents_api",
|
|
managedProfileId,
|
|
model,
|
|
maxSessionListCostUsd: positiveNumberOrNull(
|
|
config.maxSessionListCostUsd,
|
|
"paperclip_runner_claude_managed_spend_cap_invalid",
|
|
"Paperclip Runner Claude Managed requires a positive session spend ceiling when overridden.",
|
|
),
|
|
};
|
|
}
|
|
|
|
if (candidate === "aws_agentcore") {
|
|
const agentCoreProfileId = optionalString(config.agentCoreProfileId);
|
|
if (!agentCoreProfileId) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_aws_agentcore_profile_required",
|
|
"Paperclip Runner AWS AgentCore requires a company remote-agent profile.",
|
|
);
|
|
}
|
|
if (config.agentCoreRetentionAcknowledged !== true) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_aws_agentcore_retention_required",
|
|
"Paperclip Runner AWS AgentCore requires acknowledgement of 90-day Memory retention.",
|
|
);
|
|
}
|
|
if (model !== null && model !== AGENTCORE_QUALIFIED_MODEL) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_aws_agentcore_model_unqualified",
|
|
`The AWS AgentCore profile requires exact model ${AGENTCORE_QUALIFIED_MODEL}.`,
|
|
);
|
|
}
|
|
return {
|
|
provider: "aws_agentcore",
|
|
backend: "aws_agentcore_harness_api",
|
|
agentCoreProfileId,
|
|
model,
|
|
maxEstimatedSessionCostUsd: positiveNumberOrNull(
|
|
config.maxEstimatedSessionCostUsd,
|
|
"paperclip_runner_aws_agentcore_spend_cap_invalid",
|
|
"Paperclip Runner AWS AgentCore requires a positive estimated session spend ceiling when overridden.",
|
|
),
|
|
};
|
|
}
|
|
|
|
const acpxAgent = config.acpxAgent ?? "claude";
|
|
if (acpxAgent === "copilot" && (!model || ["auto", "default"].includes(model.toLowerCase()))) {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_model_required", "GitHub Copilot requires an explicit model ID; there is no default model.");
|
|
}
|
|
const pendingAcpxProfile = PAPERCLIP_RUNNER_ACPX_PROFILES.find(profile => profile.value === acpxAgent && !profile.qualified);
|
|
if (pendingAcpxProfile) {
|
|
if (!model) throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_model_required", `${pendingAcpxProfile.label} requires an explicit model ID; there is no default model.`);
|
|
if (pendingAcpxProfile.value === "antigravity") {
|
|
try {
|
|
if (resolveAntigravityCandidateAdmission({ companyId: context.companyId, model }, process.env)) {
|
|
return { provider: "acpx", backend: "acpx_runtime", model, acpxAgent: "antigravity" };
|
|
}
|
|
} catch {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_qualification_invalid", "Antigravity candidate admission requires the authorized company, exact model and runtime identity.");
|
|
}
|
|
}
|
|
if (pendingAcpxProfile.value === "kimi") {
|
|
try {
|
|
if (resolveKimiCandidateAdmission({ companyId: context.companyId, model }, process.env)) {
|
|
return { provider: "acpx", backend: "acpx_runtime", model, acpxAgent: "kimi" };
|
|
}
|
|
} catch {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_qualification_invalid", "Kimi candidate admission requires the authorized company, exact model, target and runtime identity.");
|
|
}
|
|
}
|
|
// Qualification authority belongs to the isolated server operator. Never
|
|
// read this allowlist from adapter config, credential refs, or run env.
|
|
let qualification: AcpxQualificationCandidate | undefined;
|
|
try {
|
|
qualification = resolveAcpxQualification({ kind: "acpx", agent: pendingAcpxProfile.value, model }, process.env);
|
|
} catch {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_qualification_invalid", "ACPX qualification requires an exact host-authorized candidate and model.");
|
|
}
|
|
if (qualification) {
|
|
return { provider: "acpx", backend: "acpx_runtime", model, acpxAgent: qualification };
|
|
}
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_agent_unavailable", `${pendingAcpxProfile.label} is awaiting native Runner acceptance. Its profile is not enabled for production runs.`);
|
|
}
|
|
if ((acpxAgent === "cursor" || acpxAgent === "pi" || acpxAgent === "kimi") && !model) {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_model_required", "This ACPX agent requires an explicit model ID; there is no default model.");
|
|
}
|
|
if (acpxAgent !== "claude" && acpxAgent !== "codex" && acpxAgent !== "grok" && acpxAgent !== "cursor" && acpxAgent !== "copilot" && acpxAgent !== "pi" && acpxAgent !== "kimi") {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_acpx_agent_unavailable",
|
|
"Paperclip Runner ACPX requires a qualified agent profile.",
|
|
);
|
|
}
|
|
const selectedModel = acpxAgent === "grok" && model === "grok-build"
|
|
? DEFAULT_ACPX_RUNNER_MODELS.grok
|
|
: model || DEFAULT_ACPX_RUNNER_MODELS[acpxAgent] || "";
|
|
try {
|
|
resolveQualifiedAcpxProfile(acpxAgent, selectedModel);
|
|
} catch (error) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_acpx_model_unqualified",
|
|
error instanceof Error ? error.message : "Paperclip Runner ACPX requires an admitted model.",
|
|
);
|
|
}
|
|
return {
|
|
provider: "acpx",
|
|
backend: "acpx_runtime",
|
|
model: selectedModel,
|
|
acpxAgent,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Project the operator-owned adapter configuration and a qualified stored
|
|
* profile into the closed native execution descriptor. Editable adapter
|
|
* configuration can select a stored profile, but it cannot replace that
|
|
* profile's immutable remote resource identity.
|
|
*/
|
|
export function resolvePaperclipRunnerNativeProviderInput(input: {
|
|
companyId?: string;
|
|
backend: PaperclipRunnerProviderProfile["backend"];
|
|
adapterConfig: unknown;
|
|
/** Verified image CLI version for a fresh remote Codex run only. */
|
|
codexCliVersion?: string | null;
|
|
museBinding?: import("../../vendor/paperclip-runner/index.js").MuseBindingSnapshot;
|
|
dotBinding?: import("../../vendor/paperclip-runner/index.js").DotBindingSnapshot;
|
|
managedProfile?: {
|
|
id: string;
|
|
profileKey: string;
|
|
anthropicAgentId: string;
|
|
agentVersion: string;
|
|
environmentId: string;
|
|
betaVersion: string;
|
|
defaultModel: string;
|
|
defaultMaxListCostCents: number;
|
|
} | null;
|
|
agentCoreProfile?: {
|
|
id: string;
|
|
profileKey: string;
|
|
configuration: Record<string, unknown>;
|
|
} | null;
|
|
}): PaperclipRunnerNativeProviderInput {
|
|
const config = asRecord(input.adapterConfig);
|
|
const profile = resolvePaperclipRunnerProviderProfile(config, { companyId: input.companyId });
|
|
if (config.homeMode !== undefined && config.homeMode !== "isolated" && config.homeMode !== "preconfigured") {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_home_mode_invalid", "homeMode must be isolated or preconfigured");
|
|
}
|
|
const preconfigured = config.homeMode === "preconfigured";
|
|
if (preconfigured && profile.provider !== "codex" && !(profile.provider === "acpx" && ["claude", "codex"].includes(profile.acpxAgent))) {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_home_mode_unsupported", "Preconfigured home supports native Codex and ACPX Claude only");
|
|
}
|
|
if (preconfigured && profile.provider === "acpx" && config.acpxPermissionMode !== undefined && config.acpxPermissionMode !== "approve-all") {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_home_permission_mode_unsupported", "Preconfigured home currently requires ACPX approve-all; local permission rules still apply");
|
|
}
|
|
if (preconfigured && profile.provider === "acpx" && profile.acpxAgent === "codex") {
|
|
throw new PaperclipRunnerProviderProfileError("paperclip_runner_home_state_boundary_unsupported", "preconfigured ACPX Codex cannot protect Runner state; use native Codex or isolated mode");
|
|
}
|
|
if (profile.backend !== input.backend) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_provider_changed",
|
|
"Paperclip Runner provider changed after this run selected its native backend.",
|
|
);
|
|
}
|
|
if (profile.provider === "cursor_cloud") {
|
|
return { provider: "cursor_cloud", model: profile.model, cursorCloud: resolvePaperclipRunnerCursorCloudConfig(config) };
|
|
}
|
|
if (profile.provider === "muse") {
|
|
if (!input.museBinding || input.museBinding.bindingId !== profile.museBindingId) throw new PaperclipRunnerProviderProfileError("paperclip_runner_muse_binding_unavailable", "Muse binding must be resolved by the server after normal admission.");
|
|
return { provider: "muse", model: null, museBinding: input.museBinding };
|
|
}
|
|
if (profile.provider === "grok_bot") {
|
|
if (!input.dotBinding || input.dotBinding.bindingId !== profile.externalBindingId) throw new PaperclipRunnerProviderProfileError("paperclip_runner_grok_binding_unavailable", "The Grok binding must be resolved by the server after normal admission.");
|
|
return { provider: "grok_bot", model: null, dotBinding: input.dotBinding };
|
|
}
|
|
if (profile.provider === "openai_dot") {
|
|
if (!input.dotBinding || input.dotBinding.bindingId !== profile.dotBindingId) throw new PaperclipRunnerProviderProfileError("paperclip_runner_dot_binding_unavailable", "Dot binding must be resolved by the server after normal admission.");
|
|
return { provider: "openai_dot", model: null, dotBinding: input.dotBinding };
|
|
}
|
|
if (profile.provider === "opencode") {
|
|
return {
|
|
provider: "opencode",
|
|
model: profile.model,
|
|
opencodePermissionMode: resolvePaperclipRunnerPermissionMode(
|
|
"opencode",
|
|
config.opencodePermissionMode,
|
|
) as "allow" | "ask" | "deny",
|
|
};
|
|
}
|
|
if (profile.provider === "acpx") {
|
|
return {
|
|
provider: "acpx",
|
|
model: profile.model,
|
|
acpxAgent: profile.acpxAgent,
|
|
...(profile.acpxAgent === "claude" ? { claudeEffort: resolveClaudeEffort("claude", config.modelReasoningEffort ?? config.reasoningEffort ?? config.effort) } : {}),
|
|
...(profile.acpxAgent === "grok" ? { grokEffort: resolveGrokEffort("grok", config.modelReasoningEffort ?? config.reasoningEffort ?? config.effort), grokDisableWebSearch: resolveGrokDisableWebSearch("grok", config.disableWebSearch) } : {}),
|
|
...(profile.acpxAgent === "pi" ? { piThinkingLevel: resolvePaperclipRunnerPiThinkingLevel("acpx", "pi", config.piThinkingLevel) } : {}),
|
|
...(profile.acpxAgent === "cursor" ? {
|
|
acpxSessionMode: resolvePaperclipRunnerCursorMode("acpx", "cursor", config.acpxSessionMode),
|
|
} : {}),
|
|
...(preconfigured ? { homeMode: "preconfigured" as const } : {}),
|
|
acpxPermissionMode: resolvePaperclipRunnerPermissionMode(
|
|
"acpx",
|
|
config.acpxPermissionMode,
|
|
) as "approve-all" | "approve-paperclip" | "approve-reads" | "deny-all",
|
|
};
|
|
}
|
|
if (profile.provider === "claude_managed") {
|
|
const stored = input.managedProfile;
|
|
if (
|
|
!stored
|
|
|| (
|
|
profile.managedProfileId !== stored.id
|
|
&& profile.managedProfileId !== stored.profileKey
|
|
)
|
|
) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_claude_managed_profile_mismatch",
|
|
"The qualified Claude Managed profile does not match the adapter selection.",
|
|
);
|
|
}
|
|
if (stored.betaVersion !== CLAUDE_MANAGED_BETA_VERSION) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_claude_managed_beta_unqualified",
|
|
"The Claude Managed profile beta version is not qualified.",
|
|
);
|
|
}
|
|
const model = profile.model ?? optionalString(stored.defaultModel);
|
|
const maxSessionListCostUsd = profile.maxSessionListCostUsd
|
|
?? stored.defaultMaxListCostCents / 100;
|
|
if (!model) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_claude_managed_model_invalid",
|
|
"The Claude Managed profile requires a model.",
|
|
);
|
|
}
|
|
if (model !== CLAUDE_MANAGED_QUALIFIED_MODEL) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_claude_managed_model_unqualified",
|
|
`The Claude Managed profile requires exact model ${CLAUDE_MANAGED_QUALIFIED_MODEL}.`,
|
|
);
|
|
}
|
|
if (!Number.isFinite(maxSessionListCostUsd) || maxSessionListCostUsd <= 0) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_claude_managed_spend_cap_invalid",
|
|
"The Claude Managed profile requires a positive session spend ceiling.",
|
|
);
|
|
}
|
|
return {
|
|
provider: "claude_managed",
|
|
model,
|
|
managedProfile: {
|
|
profileId: stored.id,
|
|
anthropicAgentId: stored.anthropicAgentId,
|
|
agentVersion: stored.agentVersion,
|
|
environmentId: stored.environmentId,
|
|
betaVersion: CLAUDE_MANAGED_BETA_VERSION,
|
|
},
|
|
maxSessionListCostUsd,
|
|
};
|
|
}
|
|
if (profile.provider === "aws_agentcore") {
|
|
const stored = input.agentCoreProfile;
|
|
if (
|
|
!stored
|
|
|| (
|
|
profile.agentCoreProfileId !== stored.id
|
|
&& profile.agentCoreProfileId !== stored.profileKey
|
|
)
|
|
) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_aws_agentcore_profile_mismatch",
|
|
"The qualified AWS AgentCore profile does not match the adapter selection.",
|
|
);
|
|
}
|
|
const remote = asRecord(stored.configuration);
|
|
const required = (key: string): string => {
|
|
const value = optionalString(remote[key]);
|
|
if (!value) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_aws_agentcore_profile_invalid",
|
|
`The qualified AWS AgentCore profile is missing ${key}.`,
|
|
);
|
|
}
|
|
return value;
|
|
};
|
|
if (remote.eventExpiryDays !== 90) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_aws_agentcore_retention_unqualified",
|
|
"The qualified AWS AgentCore profile must retain Memory events for exactly 90 days.",
|
|
);
|
|
}
|
|
const maxEstimatedSessionCostUsd = profile.maxEstimatedSessionCostUsd
|
|
?? positiveNumberOrNull(
|
|
remote.defaultMaxEstimatedSessionCostUsd,
|
|
"paperclip_runner_aws_agentcore_spend_cap_invalid",
|
|
"The AWS AgentCore profile requires a positive estimated session spend ceiling.",
|
|
);
|
|
if (maxEstimatedSessionCostUsd === null) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_aws_agentcore_spend_cap_invalid",
|
|
"The AWS AgentCore profile requires a positive estimated session spend ceiling.",
|
|
);
|
|
}
|
|
const model = profile.model ?? required("defaultModel");
|
|
if (model !== AGENTCORE_QUALIFIED_MODEL) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_aws_agentcore_model_unqualified",
|
|
`The AWS AgentCore profile requires exact model ${AGENTCORE_QUALIFIED_MODEL}.`,
|
|
);
|
|
}
|
|
return {
|
|
provider: "aws_agentcore",
|
|
model,
|
|
agentCoreProfile: {
|
|
profileId: stored.id,
|
|
region: required("region"),
|
|
accountId: required("accountId"),
|
|
harnessArn: required("harnessArn"),
|
|
harnessVersion: required("harnessVersion"),
|
|
endpointArn: required("endpointArn"),
|
|
endpointQualifier: required("endpointQualifier"),
|
|
agentRuntimeArn: required("agentRuntimeArn"),
|
|
memoryArn: required("memoryArn"),
|
|
memoryId: required("memoryId"),
|
|
invocationRoleArn: required("invocationRoleArn"),
|
|
contextBucket: required("contextBucket"),
|
|
contextPrefix: required("contextPrefix"),
|
|
contextKmsKeyArn: required("contextKmsKeyArn"),
|
|
qualificationRevision: required("qualificationRevision"),
|
|
eventExpiryDays: 90,
|
|
},
|
|
maxEstimatedSessionCostUsd,
|
|
invocationLimits: {
|
|
maxIterations: boundedPositiveInteger(
|
|
config.maxIterations,
|
|
8,
|
|
8,
|
|
"paperclip_runner_aws_agentcore_max_iterations_invalid",
|
|
"AWS AgentCore maxIterations",
|
|
),
|
|
maxOutputTokens: boundedPositiveInteger(
|
|
config.maxOutputTokens,
|
|
4_096,
|
|
4_096,
|
|
"paperclip_runner_aws_agentcore_max_output_tokens_invalid",
|
|
"AWS AgentCore maxOutputTokens",
|
|
),
|
|
timeoutSeconds: boundedPositiveInteger(
|
|
config.timeoutSeconds,
|
|
300,
|
|
300,
|
|
"paperclip_runner_aws_agentcore_timeout_invalid",
|
|
"AWS AgentCore timeoutSeconds",
|
|
),
|
|
},
|
|
};
|
|
}
|
|
const effort = config.modelReasoningEffort ?? config.reasoningEffort ?? config.effort;
|
|
const allowedEfforts = ["minimal", "low", "medium", "high", "xhigh", "max", "ultra"];
|
|
if (effort !== undefined && effort !== null && effort !== "" && (
|
|
typeof effort !== "string" || !allowedEfforts.includes(effort)
|
|
|| (profile.model && isCodexLocalKnownModel(profile.model)
|
|
&& !codexLocalReasoningEffortsForModel(profile.model).includes(effort as "minimal" | "low" | "medium" | "high" | "xhigh" | "max" | "ultra"))
|
|
)) {
|
|
throw new PaperclipRunnerProviderProfileError(
|
|
"paperclip_runner_codex_effort_invalid",
|
|
"Paperclip Runner Codex reasoning effort is not supported for this model.",
|
|
);
|
|
}
|
|
return {
|
|
provider: "codex",
|
|
model: compatibleCodexModel(profile.model, input.codexCliVersion ?? null),
|
|
...(preconfigured ? { homeMode: "preconfigured" as const } : {}),
|
|
codexApprovalPolicy: resolvePaperclipRunnerPermissionMode(
|
|
"codex",
|
|
config.codexPermissionMode,
|
|
) as "never" | "on-request" | "untrusted",
|
|
...(typeof effort === "string" && effort ? { codexReasoningEffort: effort } : {}),
|
|
...(config.search === false ? { codexWebSearch: "disabled" as const } : {}),
|
|
};
|
|
}
|