mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 07:38:47 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A planning task runs a native Codex agent in read-only planning mode
before the user approves a Plan
> - On a Daytona sandbox, every Codex planning run failed before its
first turn: `error creating thread: failed to load AGENTS.md
instructions for environment 'local': fs sandbox helper failed ...
bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted`
> - Codex 0.160.0 reads files through a filesystem helper when the
permission profile restricts reads. That helper always runs bubblewrap
with `--unshare-net`. Daytona has no `CAP_NET_ADMIN`, so bubblewrap
cannot bring up loopback in the new network namespace
> - The planning profile must stay read-only. Codex's plan collaboration
mode is only a prompt, so the external-sandbox profile (#20808 tried it,
then reverted it) would let planning runs write files
> - This pull request keeps the read-only profile, but inside an
external sandbox it gives the profile full-disk read, no writes and
network. Codex then reads files directly and runs commands without a new
network namespace, and it still refuses writes
> - The benefit is that Codex planning works on Daytona and stays
read-only
## Linked Issues or Issue Description
Refs #20808
**What happened?**
A Codex planning task on a Daytona execution environment failed at
startup. The run ended with `provider_session_open_rejected` and the
Codex message `bwrap: loopback: Failed RTM_NEWADDR: Operation not
permitted`. Standard and ask runs on the same sandbox worked.
**Expected behavior**
A planning run on Daytona starts, writes its Plan and asks for approval.
Codex must still refuse file writes and mutating commands during
planning.
**Steps to reproduce**
1. Configure a native Codex agent with a Daytona execution environment.
2. Create a task in planning mode.
3. The first run fails before its first turn with the bubblewrap
loopback error.
## What Changed
- `createIsolatedCodexAppServerArgs`: when
`PAPERCLIP_RUNNER_EXTERNAL_SANDBOX=1`, the
`paperclip-runner-workspace-read-only` profile is now `{":root"="read"}`
(plus the brokered `GH_CONFIG_DIR` write that planning already had). Its
network still follows `PAPERCLIP_RUNNER_NETWORK_ACCESS`. It has no deny
entries, so Codex 0.160.0 treats it as full-disk read and skips its
filesystem helper, which always unshares the network. Local and SSH
planning keep the narrower profile unchanged.
- The Codex session context now records `rootAccess` `read` (planning)
or `write` (default) in an external sandbox, instead of always `none`.
- The Runner still sends `permissions:
"paperclip-runner-workspace-read-only"` and the plan collaboration mode
on `thread/start` and `turn/start` for planning. A new Rust test pins
that for an externally sandboxed read-only launch (no `sandbox:
danger-full-access`, no `externalSandbox` `sandboxPolicy`).
- A new Rust test proves that a launch saved with the previous planning
profile rules has the same stable launch identity as a launch with the
new rules, so saved sessions carry forward.
- New manual Product E2E suite `codex-planning-read-only`
(`runner-codex` on local and Daytona). The planning turn runs one shell
write, writes a Plan whose first line records the outcome, asks for
approval, and finishes after approval. A grader reads the run events and
fails if no write attempt was seen or if any write succeeded.
- `docs/codex-driver.md` describes the external-sandbox planning
profile, why it avoids the helper, and its read scope.
## Verification
- Red on Daytona, master `123ee31552`: [run
43029207500](https://github.com/paperclipai/paperclip/actions/runs/43029207500),
cell `core-compatibility.runner-codex.daytona.plan-revise-accept` failed
twice with `error creating thread: failed to load AGENTS.md instructions
for environment 'local': fs sandbox helper failed with status exit
status: 1: bwrap: loopback: Failed RTM_NEWADDR: Operation not
permitted`.
- Planning turn completes on Daytona: [run
43031462803](https://github.com/paperclipai/paperclip/actions/runs/43031462803),
cell `core-compatibility.runner-codex.daytona.plan-revise-accept`. The
planning run succeeded, saved a two-step Plan with the draft marker and
opened a confirmation for that revision (all API checks passed). The
cell then failed a later browser check: the Plan preview rendered as the
`task-chat-plan-preview-fallback` card, which the harness does not
accept. That is a separate UI placement gap.
- Write attempt on Daytona: [run
43038547892](https://github.com/paperclipai/paperclip/actions/runs/43038547892),
cell `codex-planning-read-only.runner-codex.daytona.plan-write-refused`
on `f30aeb3e72`. The planning run succeeded and ran the shell write
`printf probe > plan-write-probe-....txt || echo WRITE_REFUSED`. It
ended `failed` with exit 1 and no file, because bubblewrap could not
start the command (`bwrap: setting up uid map: Permission denied`). The
write was refused fail-closed by the sandbox launcher, not by a
read-only filesystem error. The stricter grader in a3d43b7bfd reports
this case as 'sandbox failed to start' rather than a pass. Shell
commands in Daytona planning therefore do not run on the current image;
the driver doc records this as a remaining gap.
- Red/green unit test: `npx vitest run
src/drivers/codex/codex-security-config.test.ts` (in
`packages/paperclip-runner`). The new test failed on the unfixed code
(the profile was `":root"="none"` with `CODEX_HOME` denied and network
off) and passes with the fix.
- `cargo test --locked -p paperclip-runner-core --test codex_provider --
external_sandbox` and `cargo test --locked -p paperclip-runner-core
--lib -- external_sandbox_planning_profile_rules
runtime_launch_rebinding`: pass.
- `npx vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/codex-planning-read-only.test.ts
tests/runner-e2e/catalog.test.ts`: pass. `pnpm
test:e2e:runner:typecheck`: pass.
- Real Codex 0.160.0 app-server probe (macOS) with the generated launch
arguments and `PAPERCLIP_RUNNER_EXTERNAL_SANDBOX=1`: `thread/start`
returned sandbox `{"type":"readOnly","networkAccess":true}` and loaded
the workspace `AGENTS.md`; `command/exec` with the planning profile
refused `printf x > plan-write-probe.txt` (exit 1, `Operation not
permitted`, no file) and allowed `cat AGENTS.md`. Trace logs showed 0
filesystem-helper invocations with the new profile and 336 with the
previous restricted profile.
- Codex 0.160.0 source: `exec-server/src/fs_sandbox.rs` always sets
`NetworkSandboxPolicy::Restricted` for the helper,
`core/src/agents_md.rs` uses the helper only without full-disk read, and
`linux-sandbox` adds `--unshare-net` only for a restricted or proxy-only
network.
## Risks
- Inside an external sandbox, planning commands can now read the whole
sandbox filesystem, including the isolated Codex home. Default-mode
turns in the same sandbox already have full read and write access, so
this does not widen what the sandbox exposes. Local and SSH planning are
unchanged.
- Inside an external sandbox, planning shell commands fail closed on the
current Daytona image because bubblewrap cannot map user IDs there.
Planning still reads files and writes the Plan through Codex and
Paperclip tools.
- If a future Codex release adds deny-read entries or makes the helper
mandatory, planning on Daytona could fail again. The new Daytona E2E
suite detects that.
- Upgrade safety: the profile filesystem and network keys are excluded
from the stable launch identity, so saved sessions resume with the new
rules (new Rust regression). No persisted schema, pack contract or ACPX
profile changes.
> 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
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, GitHub CLI) and extended
reasoning.
## 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>
1111 lines
45 KiB
TypeScript
1111 lines
45 KiB
TypeScript
import { usesPreconfiguredHome } from "../preconfigured-home.js";
|
|
import { codexProviderFailure } from "./provider-failure.js";
|
|
import { writeManagedCodexObservability, redactObservabilityDiagnostic } from "../agent-observability.js";
|
|
import { trustCodexStartupRoot } from "./codex-startup-trust.js";
|
|
import { readCodexThreadState, readCodexTurnMetadata } from "./codex-history.js";
|
|
import { codexExecutableReadOnlyRoots } from "./codex-security-config.js";
|
|
|
|
import type {
|
|
HarnessDriver,
|
|
HarnessDriverDescriptor,
|
|
HarnessRuntimeRequest,
|
|
HarnessSession,
|
|
HarnessSessionRecoveryOptions,
|
|
HarnessSessionRecoveryResult,
|
|
HarnessThreadGoal,
|
|
HarnessThreadLineageEntry,
|
|
OpenHarnessSessionInput,
|
|
PersistedHarnessSemanticResult,
|
|
PersistedHarnessSession,
|
|
PersistedHarnessTurnTerminal,
|
|
} from "../../contracts/harness-driver.js";
|
|
import { NativeSessionProtocolIntegrityError, nativeRestartInterruptedTurnId } from "../../contracts/native-session-backend.js";
|
|
import { HarnessReconciliationError, isRunnerResumeStateUnavailable, PROVIDER_SIDE_EFFECT_PENDING, PROVIDER_STATE_INCOMPATIBLE, runnerRecoveryFailureClass } from "../../contracts/harness-driver.js";
|
|
import {
|
|
CODEX_CODEX_PROTOCOL_VERSION,
|
|
CODEX_SKILLLESS_BASE_INSTRUCTIONS,
|
|
} from "../../contracts/codex.js";
|
|
import { providerFamilyCapabilities } from "../../provider-events.js";
|
|
import {
|
|
CodexRpcError,
|
|
ProcessCodexAppServerTransport,
|
|
createSanitizedCodexEnvironment,
|
|
isCodexMethodUnavailable,
|
|
redactCodexDiagnostic,
|
|
type CodexAppServerTransport,
|
|
type CodexTransportProcessInfo,
|
|
} from "./app-server-transport.js";
|
|
import {
|
|
boundedCodexValue,
|
|
codexThreadWorkingDirectory,
|
|
remoteRunnerWorkingDirectoryMoved,
|
|
validateCodexWorkingDirectory as validateWorkingDirectory,
|
|
} from "./codex-boundaries.js";
|
|
import {
|
|
codexCommandEnvironment,
|
|
createIsolatedCodexAppServerArgs,
|
|
codexNetworkAccess,
|
|
usesExternalRunnerSandbox,
|
|
createSecuredCodexThreadParams,
|
|
createSkilllessCodexThreadConfig,
|
|
} from "./codex-security-config.js";
|
|
import {
|
|
codexThreadLineage as lineageFromThread,
|
|
codexThreadStatus as threadStatus,
|
|
parseCodexThreadGoal as parseThreadGoal,
|
|
} from "./codex-thread-normalization.js";
|
|
import { CodexHarnessSession } from "./codex-harness-session.js";
|
|
import type {
|
|
CodexAppServerDriverOptions,
|
|
CodexCapabilities,
|
|
CodexGoalAvailability,
|
|
OpenedCodexThread,
|
|
} from "./codex-driver-types.js";
|
|
import {
|
|
boundedText,
|
|
canonicalJson,
|
|
codexSemanticToolSpecs,
|
|
differingJsonPaths,
|
|
parseProviderIdentity,
|
|
record,
|
|
text,
|
|
} from "./codex-driver-values.js";
|
|
|
|
const DRIVER_KIND = "codex_app_server";
|
|
const DRIVER_VERSION = "codex-v2";
|
|
|
|
interface BootstrapCancellation {
|
|
close(): Promise<void>;
|
|
detach(): void;
|
|
wait<T>(operation: Promise<T>): Promise<T>;
|
|
}
|
|
|
|
function bootstrapCancellation(
|
|
transport: CodexAppServerTransport,
|
|
signal: AbortSignal | undefined,
|
|
): BootstrapCancellation {
|
|
let closePromise: Promise<void> | null = null;
|
|
const close = (): Promise<void> => {
|
|
closePromise ??= transport.close();
|
|
return closePromise;
|
|
};
|
|
let rejectAborted!: (reason: unknown) => void;
|
|
const aborted = new Promise<never>((_resolve, reject) => {
|
|
rejectAborted = reject;
|
|
});
|
|
let abortStarted = false;
|
|
const onAbort = (): void => {
|
|
if (abortStarted) return;
|
|
abortStarted = true;
|
|
// Provider bootstrap owns a local process. Do not report cancellation
|
|
// until its pending RPCs have been rejected and TERM/KILL cleanup has
|
|
// completed. The cancellation reason remains authoritative if cleanup
|
|
// itself reports a secondary failure.
|
|
void close().then(
|
|
() =>
|
|
rejectAborted(signal?.reason ?? new Error("Codex bootstrap aborted")),
|
|
() =>
|
|
rejectAborted(signal?.reason ?? new Error("Codex bootstrap aborted")),
|
|
);
|
|
};
|
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
// Close the construction/listener race after the caller's preflight abort
|
|
// check without creating a provider for an already-aborted operation.
|
|
if (signal?.aborted) onAbort();
|
|
return {
|
|
close,
|
|
detach(): void {
|
|
signal?.removeEventListener("abort", onAbort);
|
|
},
|
|
async wait<T>(operation: Promise<T>): Promise<T> {
|
|
if (signal === undefined) return await operation;
|
|
const result = await Promise.race([operation, aborted]);
|
|
// An operation and abort cleanup may settle in the same microtask turn.
|
|
// Cancellation wins until session admission, and still awaits cleanup.
|
|
if (signal.aborted) return await aborted;
|
|
return result;
|
|
},
|
|
};
|
|
}
|
|
|
|
|
|
/** A saved turn or runtime request whose outcome is unknown. A crash can save a
|
|
* turn's terminal record before clearing its active marker; that turn finished
|
|
* and is not in flight. */
|
|
function persistedSessionInFlight(snapshot: PersistedHarnessSession): boolean {
|
|
const activeTurnIsTerminal = (snapshot.terminalTurns ?? []).some(
|
|
(terminal) => terminal.turnId === snapshot.activeTurnId,
|
|
);
|
|
return (Boolean(snapshot.activeTurnId) && !activeTurnIsTerminal)
|
|
|| Boolean(snapshot.pendingRuntimeRequests?.length);
|
|
}
|
|
|
|
export class CodexAppServerDriver implements HarnessDriver {
|
|
readonly #options: CodexAppServerDriverOptions;
|
|
readonly #caps: CodexCapabilities;
|
|
#goalAvailability: CodexGoalAvailability;
|
|
#goalReasonCode: string | null = null;
|
|
#goalReason: string | null = null;
|
|
readonly #goalCapability: NonNullable<
|
|
CodexAppServerDriverOptions["goalCapability"]
|
|
>;
|
|
readonly #persistedProcessIdentities = new WeakMap<object, string>();
|
|
|
|
constructor(options: CodexAppServerDriverOptions) {
|
|
this.#options = options;
|
|
this.#caps = {
|
|
resume: true,
|
|
read: true,
|
|
steering: true,
|
|
interruption: true,
|
|
usage: true,
|
|
reconciliation: true,
|
|
dynamicTools: true,
|
|
toolRefreshOnResume: true,
|
|
runtimeRequestResolution: true,
|
|
goals: true,
|
|
threadLineage: true,
|
|
...options.capabilities,
|
|
};
|
|
this.#goalAvailability = this.#caps.goals ? "available" : "unsupported";
|
|
this.#goalCapability = options.goalCapability ?? {
|
|
actions: ["set", "pause", "resume", "clear"],
|
|
autonomousUpdates: true,
|
|
persistentAcrossResume: true,
|
|
maxObjectiveChars: 4_000,
|
|
tokenBudgetControl: true,
|
|
usageReporting: true,
|
|
};
|
|
if (!this.#caps.goals) {
|
|
this.#goalReasonCode = "codex_goal_api_unavailable";
|
|
this.#goalReason = "This Codex app-server does not expose thread goals.";
|
|
}
|
|
if (!this.#caps.read) this.#caps.reconciliation = false;
|
|
}
|
|
|
|
#preparedLaunch(): boolean {
|
|
return this.#options.workingDirectoryAuthority === "runner_prepared_launch";
|
|
}
|
|
|
|
#direct(): boolean {
|
|
return this.#options.conversationMode === "direct";
|
|
}
|
|
|
|
#prepared(): boolean {
|
|
return this.#options.conversationMode === "prepared";
|
|
}
|
|
|
|
#providerDynamicTools(): readonly Readonly<Record<string, unknown>>[] {
|
|
if (!this.#caps.dynamicTools) return [];
|
|
const supplied = this.#options.dynamicTools ?? [];
|
|
if (this.#direct()) {
|
|
// Direct chat deliberately excludes the general semantic/governance
|
|
// catalog. Keep only the server-authorized question, file handoff, and
|
|
// current-wake tools so the harness can ask a structured provider
|
|
// question or return requested files without reopening general task
|
|
// authority.
|
|
return supplied.filter(
|
|
(tool) =>
|
|
text(tool.name) === "register_deliverable" ||
|
|
text(tool.name) === "request_human_input" ||
|
|
text(tool.name) === "read_current_wake_comments" ||
|
|
text(tool.name) === "list_chat_attachments" ||
|
|
text(tool.name) === "reuse_chat_attachment" ||
|
|
text(tool.name) === "read_chat_attachment",
|
|
);
|
|
}
|
|
return [...supplied, ...codexSemanticToolSpecs()];
|
|
}
|
|
|
|
#baseInstructions(): string {
|
|
return this.#options.baseInstructions ?? CODEX_SKILLLESS_BASE_INSTRUCTIONS;
|
|
}
|
|
|
|
#instructionParams(instructions = this.#baseInstructions()): Record<string, string> {
|
|
// baseInstructions replaces Codex's stock prompt. Other providers use this
|
|
// driver as a protocol facade and retain their existing instruction field.
|
|
return (this.#options.driverIdentity?.kind ?? DRIVER_KIND) === DRIVER_KIND
|
|
? { developerInstructions: instructions }
|
|
: { baseInstructions: instructions };
|
|
}
|
|
|
|
async descriptor(): Promise<HarnessDriverDescriptor> {
|
|
const unsupported = Object.entries(this.#caps)
|
|
.filter(([, supported]) => !supported)
|
|
.map(([operation]) => operation);
|
|
return {
|
|
kind: this.#options.driverIdentity?.kind ?? DRIVER_KIND,
|
|
displayName:
|
|
this.#options.driverIdentity?.displayName ?? "Codex app-server",
|
|
version: this.#options.driverIdentity?.version ?? DRIVER_VERSION,
|
|
protocolVersion: CODEX_CODEX_PROTOCOL_VERSION,
|
|
runtimeContextCapabilities: {
|
|
instructions: "native",
|
|
skills: "native",
|
|
mcp: "native",
|
|
},
|
|
capabilities: {
|
|
resume: this.#caps.resume,
|
|
typedEvents: true,
|
|
typedEventFamilies: providerFamilyCapabilities({
|
|
plan: "available",
|
|
tool_execution: "available",
|
|
research: "available",
|
|
delegation: "available",
|
|
model_identity: "available",
|
|
context: "available",
|
|
artifact: "policy_disabled",
|
|
review: "available",
|
|
hook: "available",
|
|
memory: "available",
|
|
safety: "available",
|
|
terminal: "available",
|
|
wait: "available",
|
|
provider_notice: "available",
|
|
}),
|
|
steering: this.#caps.steering,
|
|
interruption: this.#caps.interruption,
|
|
structuredResult: true,
|
|
read: this.#caps.read,
|
|
reconciliation: this.#caps.reconciliation,
|
|
usage: this.#caps.usage,
|
|
dynamicTools: this.#caps.dynamicTools,
|
|
toolRefreshOnResume: this.#caps.resume && this.#caps.dynamicTools && this.#caps.toolRefreshOnResume,
|
|
runtimeRequestResolution: this.#caps.runtimeRequestResolution,
|
|
runtimeRequestHandoff: this.#caps.runtimeRequestResolution,
|
|
goals: this.#caps.goals,
|
|
threadLineage: this.#caps.threadLineage,
|
|
collaborationModes: [
|
|
...(this.#options.collaborationModes ?? ["default", "plan"]),
|
|
],
|
|
unsupported,
|
|
},
|
|
};
|
|
}
|
|
|
|
async openSession(input: OpenHarnessSessionInput): Promise<HarnessSession> {
|
|
input.signal?.throwIfAborted();
|
|
// A prepared launch resolves its directory on the runner filesystem. The
|
|
// caller's directory is controller-local and never authorizes itself.
|
|
const workingDirectory = this.#preparedLaunch()
|
|
? null
|
|
: validateWorkingDirectory(
|
|
input.workingDirectory,
|
|
this.#options.environment,
|
|
this.#options.workingDirectoryAuthority,
|
|
);
|
|
const transport = this.#transport(
|
|
workingDirectory === null ? undefined : { workingDirectory },
|
|
);
|
|
const cancellation = bootstrapCancellation(transport, input.signal);
|
|
try {
|
|
await cancellation.wait(this.#persistProcessOwnership(transport));
|
|
const initialize = await cancellation.wait(this.#initialize(transport));
|
|
const requestedMode =
|
|
this.#options.requestedCollaborationMode ?? "default";
|
|
const threadParams = createSecuredCodexThreadParams(
|
|
workingDirectory ?? "",
|
|
requestedMode,
|
|
this.#options.includeCollaborationModeInstructions ?? true,
|
|
this.#options.includeSkillInstructions ?? false,
|
|
this.#options.environment,
|
|
);
|
|
if (workingDirectory === null) {
|
|
delete threadParams.cwd;
|
|
delete threadParams.runtimeWorkspaceRoots;
|
|
}
|
|
const response = await cancellation.wait(
|
|
transport.request("thread/start", {
|
|
...threadParams,
|
|
approvalPolicy: this.#options.approvalPolicy ?? "never",
|
|
...(this.#options.model ? { model: this.#options.model } : {}),
|
|
...(this.#direct()
|
|
? {}
|
|
: {
|
|
...this.#instructionParams(),
|
|
completionContract: {
|
|
revision:
|
|
this.#options.taskEnvelope.completionContract.revision,
|
|
criterionIds:
|
|
this.#options.taskEnvelope.completionContract.criteria.map(
|
|
(criterion) => criterion.id,
|
|
),
|
|
},
|
|
}),
|
|
dynamicTools: this.#providerDynamicTools(),
|
|
...(this.#prepared() ? { conversationMode: "prepared" } : {}),
|
|
experimentalRawEvents: false,
|
|
persistExtendedHistory: false,
|
|
}),
|
|
);
|
|
await cancellation.wait(this.#persistProcessOwnership(transport));
|
|
const collaborationMode = await cancellation.wait(
|
|
this.#negotiateCollaborationMode(transport, response, requestedMode),
|
|
);
|
|
const opened = this.#openedThread(
|
|
response,
|
|
initialize,
|
|
workingDirectory,
|
|
collaborationMode,
|
|
);
|
|
const goal = await cancellation.wait(
|
|
this.#discoverGoal(transport, opened.threadId),
|
|
);
|
|
if (opened.context.liveConsole)
|
|
opened.context.liveConsole.goals = this.#caps.goals;
|
|
return this.#session({
|
|
transport,
|
|
runId: input.runId,
|
|
normalizedSessionId: input.normalizedSessionId,
|
|
opened,
|
|
goal,
|
|
goalAvailability: this.#goalAvailability,
|
|
goalReasonCode: this.#goalReasonCode,
|
|
goalReason: this.#goalReason,
|
|
resumed: false,
|
|
sourceSequence: 0,
|
|
});
|
|
} catch (error) {
|
|
// Cleanup must never replace the provider/bootstrap failure that caused
|
|
// the session open to abort. Remote transports may perform checkpoint
|
|
// work during close; when no durable provider identity exists that
|
|
// cleanup can fail independently.
|
|
await cancellation.close().catch(() => {});
|
|
if (error instanceof NativeSessionProtocolIntegrityError) throw error;
|
|
if (input.signal?.aborted) input.signal.throwIfAborted();
|
|
if (error instanceof CodexRpcError && (this.#options.driverIdentity?.kind ?? DRIVER_KIND) === DRIVER_KIND) {
|
|
const providerFailure = codexProviderFailure(error, "startup", this.#options.environment);
|
|
if (providerFailure) Object.defineProperty(error, "providerFailure", { value: providerFailure, enumerable: false });
|
|
}
|
|
throw error;
|
|
} finally {
|
|
cancellation.detach();
|
|
}
|
|
}
|
|
|
|
async recoverSession(
|
|
snapshot: PersistedHarnessSession,
|
|
options: HarnessSessionRecoveryOptions = {
|
|
signal: new AbortController().signal,
|
|
},
|
|
): Promise<HarnessSessionRecoveryResult> {
|
|
options.signal.throwIfAborted();
|
|
if (!this.#caps.resume) {
|
|
return { recovered: false, reason: "resume capability is unavailable" };
|
|
}
|
|
if (!this.#caps.read) {
|
|
return {
|
|
recovered: false,
|
|
reason: "read capability is required for safe resume",
|
|
};
|
|
}
|
|
if (
|
|
!snapshot.runId ||
|
|
!snapshot.normalizedSessionId ||
|
|
!snapshot.driverSessionId
|
|
) {
|
|
return {
|
|
recovered: false,
|
|
reason: "persisted session identity is incomplete",
|
|
};
|
|
}
|
|
// A session saved under an abandoned remote workspace root cannot resume
|
|
// in the newly assigned root. When it holds no in-flight turn or runtime
|
|
// request (a follow-up's inherited checkpoint, for example), decline
|
|
// before any Runner or provider process starts, so the runtime's recovery
|
|
// policy decides: a replacement in the assigned workspace, or the
|
|
// permanent named refusal when the checkpoint requires the same session.
|
|
// Retrying cannot move the saved session, so this is incompatible state,
|
|
// not a transient failure. A session with an in-flight turn or runtime
|
|
// request may have an external effect nothing here can prove settled, so
|
|
// it is never replaced: it stops by name for an operator to reconcile.
|
|
if (
|
|
snapshot.workingDirectory &&
|
|
this.#options.workingDirectoryAuthority === "remote_runner" &&
|
|
remoteRunnerWorkingDirectoryMoved(snapshot.workingDirectory, this.#options.environment)
|
|
) {
|
|
return persistedSessionInFlight(snapshot)
|
|
? {
|
|
recovered: false,
|
|
reason: "persisted session working directory is not the assigned remote workspace, and a provider turn or runtime request was in flight",
|
|
failureClass: PROVIDER_SIDE_EFFECT_PENDING,
|
|
}
|
|
: {
|
|
recovered: false,
|
|
reason: "persisted session working directory is not the assigned remote workspace",
|
|
failureClass: PROVIDER_STATE_INCOMPATIBLE,
|
|
};
|
|
}
|
|
const transport = this.#transport({
|
|
workingDirectory: snapshot.workingDirectory
|
|
? validateWorkingDirectory(snapshot.workingDirectory, this.#options.environment, this.#options.workingDirectoryAuthority)
|
|
: undefined,
|
|
providerRecoveryPolicy: snapshot.providerRecoveryPolicy,
|
|
persistedSession: {
|
|
driverSessionId: snapshot.driverSessionId,
|
|
providerSessionId: snapshot.providerSessionId,
|
|
providerIdentity: snapshot.providerIdentity,
|
|
activeTurnId: snapshot.activeTurnId,
|
|
},
|
|
});
|
|
const cancellation = bootstrapCancellation(transport, options.signal);
|
|
try {
|
|
await cancellation.wait(this.#persistProcessOwnership(transport));
|
|
const initialize = await cancellation.wait(this.#initialize(transport));
|
|
if (transport.prepareConversationResume) {
|
|
const resumeDirectory = snapshot.workingDirectory
|
|
? validateWorkingDirectory(snapshot.workingDirectory, this.#options.environment, this.#options.workingDirectoryAuthority)
|
|
: undefined;
|
|
await cancellation.wait(transport.prepareConversationResume(resumeDirectory
|
|
? this.#resumeThreadParams(snapshot.driverSessionId, resumeDirectory)
|
|
: { threadId: snapshot.driverSessionId }));
|
|
}
|
|
const existing = await cancellation.wait(
|
|
readCodexThreadState(transport, snapshot.driverSessionId),
|
|
);
|
|
await cancellation.wait(this.#persistProcessOwnership(transport));
|
|
const existingThread = record(existing.thread);
|
|
existingThread.turns = await cancellation.wait(readCodexTurnMetadata(transport, snapshot.driverSessionId));
|
|
if (text(existingThread.id) !== snapshot.driverSessionId) {
|
|
await cancellation.wait(cancellation.close());
|
|
return {
|
|
recovered: false,
|
|
reason: "provider read a different session",
|
|
};
|
|
}
|
|
const workingDirectory = validateWorkingDirectory(
|
|
text(existingThread.cwd),
|
|
this.#options.environment,
|
|
this.#options.workingDirectoryAuthority,
|
|
);
|
|
if (
|
|
this.#preparedLaunch() &&
|
|
snapshot.workingDirectory !== undefined &&
|
|
snapshot.workingDirectory !== workingDirectory
|
|
) {
|
|
await cancellation.wait(cancellation.close());
|
|
return {
|
|
recovered: false,
|
|
reason: "provider read a different working directory",
|
|
};
|
|
}
|
|
const response = await cancellation.wait(
|
|
transport.request("thread/resume", this.#resumeThreadParams(snapshot.driverSessionId, workingDirectory)),
|
|
);
|
|
await cancellation.wait(this.#persistProcessOwnership(transport));
|
|
const collaborationMode = await cancellation.wait(
|
|
this.#negotiateCollaborationMode(
|
|
transport,
|
|
response,
|
|
this.#options.requestedCollaborationMode ?? "default",
|
|
),
|
|
);
|
|
const opened = this.#openedThread(
|
|
response,
|
|
initialize,
|
|
workingDirectory,
|
|
collaborationMode,
|
|
);
|
|
if (opened.threadId !== snapshot.driverSessionId) {
|
|
await cancellation.wait(cancellation.close());
|
|
return {
|
|
recovered: false,
|
|
reason: "provider resumed a different session",
|
|
};
|
|
}
|
|
if (
|
|
snapshot.providerSessionId &&
|
|
opened.providerSessionId !== snapshot.providerSessionId
|
|
) {
|
|
await cancellation.wait(cancellation.close());
|
|
return {
|
|
recovered: false,
|
|
reason: "provider resumed a different provider session",
|
|
};
|
|
}
|
|
if (
|
|
snapshot.providerIdentity !== undefined &&
|
|
canonicalJson(opened.providerIdentity) !==
|
|
canonicalJson(snapshot.providerIdentity)
|
|
) {
|
|
await cancellation.wait(cancellation.close());
|
|
return {
|
|
recovered: false,
|
|
reason: "provider resumed with a different tagged session identity",
|
|
};
|
|
}
|
|
const checkpointedActiveTurnId = snapshot.activeTurnId ?? null;
|
|
// A terminal fingerprint is the durable provider fact. A crash can
|
|
// persist it before the following active-turn clear reaches the same
|
|
// checkpoint, so never resurrect that already-terminal turn as active.
|
|
const checkpointedActiveTurnIsTerminal =
|
|
checkpointedActiveTurnId !== null &&
|
|
(snapshot.terminalTurns ?? []).some(
|
|
(terminal) => terminal.turnId === checkpointedActiveTurnId,
|
|
);
|
|
let recoveredActiveTurnId = checkpointedActiveTurnIsTerminal
|
|
? null
|
|
: checkpointedActiveTurnId;
|
|
let dispositionOnlyRecoveryConsumed =
|
|
snapshot.dispositionOnlyRecoveryConsumed ?? false;
|
|
let dispositionOnlyRecoveryTurnId =
|
|
snapshot.dispositionOnlyRecoveryTurnId ?? null;
|
|
let reconcileUncheckpointedDispositionTurn = false;
|
|
let providerTurnIds: Set<string> | null = null;
|
|
const goal = await cancellation.wait(
|
|
this.#discoverGoal(transport, opened.threadId),
|
|
);
|
|
const recoveringAutonomousGoal = snapshot.goal?.status === "active"
|
|
&& goal != null
|
|
&& goal.createdAt === snapshot.goal.createdAt;
|
|
if (recoveringAutonomousGoal) {
|
|
// Goal activation and continuation have no turn/start response. The
|
|
// provider can advance beyond the last controller checkpoint while
|
|
// disconnected, so bind the single live turn from the authenticated,
|
|
// identity-checked thread read before draining its notifications.
|
|
// Never infer a turn from an arbitrary notification or another goal.
|
|
const turns = Array.isArray(existingThread.turns)
|
|
? existingThread.turns.map(record)
|
|
: null;
|
|
const active = turns?.filter((turn) => text(turn.status) === "inProgress");
|
|
if (!active || active.length > 1 || (active.length === 1 && (
|
|
!text(active[0]?.id)
|
|
|| (snapshot.terminalTurns ?? []).some((turn) => turn.turnId === text(active[0]?.id))
|
|
))) {
|
|
await cancellation.wait(cancellation.close());
|
|
return { recovered: false, reason: "provider exposed ambiguous autonomous goal turn history" };
|
|
}
|
|
recoveredActiveTurnId = active.length === 1 ? text(active[0]?.id) : recoveredActiveTurnId;
|
|
}
|
|
if (
|
|
!recoveringAutonomousGoal &&
|
|
!this.#direct() &&
|
|
snapshot.semanticResult == null &&
|
|
recoveredActiveTurnId === null &&
|
|
(snapshot.terminalTurns?.length ?? 0) > 0
|
|
) {
|
|
const providerHistory = existingThread.turns;
|
|
const providerHistoryIsArray = Array.isArray(providerHistory);
|
|
const turns = providerHistoryIsArray ? providerHistory.map(record) : [];
|
|
const terminalIds = new Set(
|
|
(snapshot.terminalTurns ?? []).map((turn) => turn.turnId),
|
|
);
|
|
let lastKnownTerminalIndex = -1;
|
|
turns.forEach((turn, index) => {
|
|
if (terminalIds.has(text(turn.id))) lastKnownTerminalIndex = index;
|
|
});
|
|
if (nativeRestartInterruptedTurnId({
|
|
...snapshot, semanticResult: null,
|
|
}) && (!providerHistoryIsArray || lastKnownTerminalIndex < 0)) {
|
|
await cancellation.wait(cancellation.close());
|
|
return { recovered: false, reason: "restart interruption history is incomplete" };
|
|
}
|
|
// Releasing a consumed marker requires both an actual history array
|
|
// and a checkpointed terminal that anchors its ordering. An array that
|
|
// omits every durable terminal may be truncated or inconsistent, so
|
|
// absence from it is not proof that the provider rejected the turn.
|
|
if (providerHistoryIsArray && lastKnownTerminalIndex >= 0) {
|
|
providerTurnIds = new Set(
|
|
turns
|
|
.map((turn) => text(turn.id))
|
|
.filter((turnId) => turnId.length > 0),
|
|
);
|
|
}
|
|
const laterTurns =
|
|
lastKnownTerminalIndex < 0
|
|
? []
|
|
: turns.slice(lastKnownTerminalIndex + 1);
|
|
if (laterTurns.length > 1) {
|
|
await cancellation.wait(cancellation.close());
|
|
return {
|
|
recovered: false,
|
|
reason:
|
|
"provider exposed multiple uncheckpointed disposition recovery turns",
|
|
};
|
|
}
|
|
const uncheckpointedTurnId = text(laterTurns[0]?.id);
|
|
if (laterTurns.length === 1 && uncheckpointedTurnId.length === 0) {
|
|
await cancellation.wait(cancellation.close());
|
|
return {
|
|
recovered: false,
|
|
reason:
|
|
"provider exposed an unidentifiable disposition recovery turn",
|
|
};
|
|
}
|
|
if (uncheckpointedTurnId.length > 0) {
|
|
if (
|
|
dispositionOnlyRecoveryTurnId !== null &&
|
|
dispositionOnlyRecoveryTurnId !== uncheckpointedTurnId
|
|
) {
|
|
await cancellation.wait(cancellation.close());
|
|
return {
|
|
recovered: false,
|
|
reason: "provider changed the bound disposition recovery turn",
|
|
};
|
|
}
|
|
// A previous process reached the provider but crashed before it
|
|
// could checkpoint the accepted turn or durably append its terminal.
|
|
// Inspect provider history even when the one-shot submitted marker
|
|
// was checkpointed, and adopt the exact turn instead of waiting on a
|
|
// reconstructed terminal session or submitting a duplicate.
|
|
recoveredActiveTurnId = uncheckpointedTurnId;
|
|
dispositionOnlyRecoveryConsumed = true;
|
|
dispositionOnlyRecoveryTurnId = uncheckpointedTurnId;
|
|
reconcileUncheckpointedDispositionTurn = true;
|
|
}
|
|
}
|
|
if (
|
|
dispositionOnlyRecoveryConsumed &&
|
|
recoveredActiveTurnId === null &&
|
|
!reconcileUncheckpointedDispositionTurn &&
|
|
providerTurnIds !== null &&
|
|
(dispositionOnlyRecoveryTurnId === null ||
|
|
(!providerTurnIds.has(dispositionOnlyRecoveryTurnId) &&
|
|
!(snapshot.terminalTurns ?? []).some(
|
|
(terminal) => terminal.turnId === dispositionOnlyRecoveryTurnId,
|
|
)))
|
|
) {
|
|
// Older or crash-raced checkpoints could persist the pre-request
|
|
// one-shot marker, including a requested turn id, without an accepted
|
|
// provider turn. With no matching provider history or checkpointed
|
|
// terminal, the marker alone is not acceptance evidence. The native
|
|
// runtime still checks durable replay before allowing a retry, and the
|
|
// reconstructed session must retain disposition-only mode so that a
|
|
// safe retry cannot repeat the original task envelope.
|
|
dispositionOnlyRecoveryConsumed = false;
|
|
dispositionOnlyRecoveryTurnId = null;
|
|
}
|
|
// A controller can die after the runner accepted its turn/start but
|
|
// before it checkpointed the turn or emitted turn.accepted. The provider
|
|
// then keeps running that turn. Adopt it only when the runner's
|
|
// authenticated command result for this run's latest turn.start names
|
|
// that turn and no other turn is active; any other active turn stays
|
|
// foreign and fails closed when its notifications arrive.
|
|
let adoptedAcceptedTurnId: string | null = null;
|
|
// A turn this run's latest turn.start had the runner accept, which the
|
|
// restore neither adopted nor finds live (the provider lost it). Its
|
|
// undelivered reports, such as a turn/started the runner recorded after
|
|
// the previous controller detached, are earlier-generation history.
|
|
let lostAcceptedTurnId: string | null = null;
|
|
if (
|
|
!recoveringAutonomousGoal &&
|
|
recoveredActiveTurnId === null &&
|
|
!reconcileUncheckpointedDispositionTurn &&
|
|
snapshot.semanticResult == null
|
|
) {
|
|
const turns = Array.isArray(existingThread.turns)
|
|
? existingThread.turns.map(record)
|
|
: [];
|
|
const active = turns.filter((turn) => text(turn.status) === "inProgress");
|
|
// A Codex turn that finished while no controller was attached is no longer live;
|
|
// adopt it only when history shows that exact turn completed (a turn the runner
|
|
// reports lost on restore keeps the restart continuation).
|
|
const completedTurnId = transport.controllerAcceptedCompletedTurnId?.() ?? "";
|
|
const acceptedTurnId = transport.controllerAcceptedTurnId?.()
|
|
|| (completedTurnId.length > 0 && active.length === 0
|
|
&& turns.some((turn) => text(turn.id) === completedTurnId && text(turn.status) === "completed")
|
|
? completedTurnId : "");
|
|
// The accepted turn may still run, or it may have finished while no
|
|
// controller was attached. Either way it must be the only live turn.
|
|
if (
|
|
acceptedTurnId.length > 0 &&
|
|
turns.some((turn) => text(turn.id) === acceptedTurnId) &&
|
|
active.every((turn) => text(turn.id) === acceptedTurnId) &&
|
|
!(snapshot.terminalTurns ?? []).some((turn) => turn.turnId === acceptedTurnId)
|
|
) {
|
|
recoveredActiveTurnId = acceptedTurnId;
|
|
adoptedAcceptedTurnId = acceptedTurnId;
|
|
} else if (
|
|
completedTurnId.length > 0 &&
|
|
completedTurnId !== acceptedTurnId &&
|
|
!active.some((turn) => text(turn.id) === completedTurnId) &&
|
|
// A checkpointed terminal turn keeps the existing history behavior.
|
|
!(snapshot.terminalTurns ?? []).some((turn) => turn.turnId === completedTurnId)
|
|
) {
|
|
lostAcceptedTurnId = completedTurnId;
|
|
}
|
|
}
|
|
if (opened.context.liveConsole)
|
|
opened.context.liveConsole.goals = this.#caps.goals;
|
|
const session = this.#session({
|
|
transport,
|
|
runId: snapshot.runId,
|
|
normalizedSessionId: snapshot.normalizedSessionId,
|
|
opened,
|
|
goal,
|
|
goalAvailability: this.#goalAvailability,
|
|
goalReasonCode: this.#goalReasonCode,
|
|
goalReason: this.#goalReason,
|
|
resumed: true,
|
|
activeTurnId: recoveredActiveTurnId,
|
|
semanticResult: snapshot.semanticResult ?? null,
|
|
normalizeReplayPayload: options.normalizeReplayPayload,
|
|
terminalTurns: snapshot.terminalTurns ?? [],
|
|
codexUsageBaseline: snapshot.codexUsageBaseline,
|
|
dispositionOnlyRecoveryConsumed,
|
|
dispositionOnlyRecoveryTurnId,
|
|
adoptedAcceptedTurnId,
|
|
lostAcceptedTurnId,
|
|
stalePendingRuntimeRequests: snapshot.pendingRuntimeRequests ?? [],
|
|
lineage: snapshot.lineage,
|
|
sourceSequence: snapshot.lastSourceSequence ?? 0,
|
|
});
|
|
// A provider may settle the checkpointed turn while this controller is
|
|
// disconnected (including during timeout cleanup). Reopening a thread
|
|
// does not replay that terminal notification. Reconcile the exact turn
|
|
// before exposing the session so callers neither wait on a dead turn
|
|
// nor submit the original work again. Missing/conflicting history still
|
|
// fails closed in reconcile().
|
|
if (
|
|
recoveredActiveTurnId !== null ||
|
|
reconcileUncheckpointedDispositionTurn
|
|
) {
|
|
await cancellation.wait(session.reconcile?.() ?? Promise.resolve({}));
|
|
}
|
|
return {
|
|
recovered: true,
|
|
session,
|
|
};
|
|
} catch (error) {
|
|
await cancellation.close().catch(() => {});
|
|
if (error instanceof NativeSessionProtocolIntegrityError) throw error;
|
|
if (options.signal.aborted) options.signal.throwIfAborted();
|
|
// A Runner with no saved control-plane state for this session can never
|
|
// resume it here. With nothing in flight, the runtime's recovery policy
|
|
// decides, as for a moved workspace root. An in-flight session keeps the
|
|
// unclassified failure.
|
|
const classified = runnerRecoveryFailureClass(error);
|
|
const resumeStateUnavailable = !classified && isRunnerResumeStateUnavailable(error)
|
|
&& !persistedSessionInFlight(snapshot);
|
|
const failureClass = classified ?? (resumeStateUnavailable ? PROVIDER_STATE_INCOMPATIBLE : undefined);
|
|
return {
|
|
recovered: false,
|
|
reason: redactCodexDiagnostic(String(error)),
|
|
...(failureClass ? { failureClass } : {}),
|
|
...(resumeStateUnavailable ? { resumeStateUnavailable: true as const } : {}),
|
|
};
|
|
} finally {
|
|
cancellation.detach();
|
|
}
|
|
}
|
|
|
|
#resumeThreadParams(threadId: string, workingDirectory: string): Record<string, unknown> {
|
|
return {
|
|
excludeTurns: true, threadId,
|
|
...createSecuredCodexThreadParams(workingDirectory,
|
|
this.#options.requestedCollaborationMode ?? "default",
|
|
this.#options.includeCollaborationModeInstructions ?? true,
|
|
this.#options.includeSkillInstructions ?? false, this.#options.environment),
|
|
...this.#instructionParams(this.#direct() ? "" : this.#baseInstructions()),
|
|
approvalPolicy: this.#options.approvalPolicy ?? "never",
|
|
...(this.#options.model ? { model: this.#options.model } : {}),
|
|
dynamicTools: this.#providerDynamicTools(),
|
|
...(this.#prepared() ? { conversationMode: "prepared" } : {}),
|
|
persistExtendedHistory: false,
|
|
};
|
|
}
|
|
|
|
#transport(context?: {
|
|
workingDirectory?: string;
|
|
providerRecoveryPolicy?: PersistedHarnessSession["providerRecoveryPolicy"];
|
|
persistedSession?: Pick<
|
|
PersistedHarnessSession,
|
|
| "driverSessionId"
|
|
| "providerSessionId"
|
|
| "providerIdentity"
|
|
| "activeTurnId"
|
|
>;
|
|
}): CodexAppServerTransport {
|
|
const workingDirectory = context?.workingDirectory ?? this.#options.environment?.PAPERCLIP_WORKSPACE_CWD;
|
|
if (this.#options.observability?.otelConfig && !this.#options.transportFactory && !usesPreconfiguredHome(this.#options.environment)) {
|
|
const home = this.#options.environment?.CODEX_HOME;
|
|
if (home) writeManagedCodexObservability(home, this.#options.observability.otelConfig);
|
|
else this.#options.onDiagnostic?.("Company observability requires a managed Codex home");
|
|
}
|
|
if (!usesPreconfiguredHome(this.#options.environment) && !this.#options.transportFactory && this.#options.environment?.CODEX_HOME && workingDirectory) {
|
|
trustCodexStartupRoot(this.#options.environment.CODEX_HOME, workingDirectory);
|
|
}
|
|
return (
|
|
this.#options.transportFactory?.(context) ??
|
|
new ProcessCodexAppServerTransport({
|
|
workingDirectory,
|
|
args: createIsolatedCodexAppServerArgs(this.#options.environment, codexExecutableReadOnlyRoots(this.#options.environment ?? process.env), this.#options.instructionWorkingCopyRoot, [], this.#options.disableWebSearch),
|
|
environment: createSanitizedCodexEnvironment(this.#options.environment),
|
|
onDiagnostic: message => this.#options.onDiagnostic?.(redactObservabilityDiagnostic(message, this.#options.environment, this.#options.observability?.otelConfig)),
|
|
processGroup: true,
|
|
})
|
|
);
|
|
}
|
|
|
|
async #negotiateCollaborationMode(
|
|
transport: CodexAppServerTransport,
|
|
threadResponse: Record<string, unknown>,
|
|
requested: "default" | "plan",
|
|
): Promise<Record<string, unknown> | null> {
|
|
if (requested !== "plan") return null;
|
|
try {
|
|
const response = await transport.request("collaborationMode/list", {});
|
|
const preset = Array.isArray(response.data)
|
|
? response.data
|
|
.map(record)
|
|
.find((candidate) => text(candidate.mode) === "plan")
|
|
: undefined;
|
|
if (!preset) throw new Error("plan preset is absent");
|
|
const model = text(
|
|
preset.model,
|
|
text(threadResponse.model, text(record(threadResponse.thread).model)),
|
|
);
|
|
if (model.length === 0)
|
|
throw new Error("plan preset did not resolve a model");
|
|
return {
|
|
mode: "plan",
|
|
settings: {
|
|
model,
|
|
reasoning_effort: preset.reasoning_effort ?? null,
|
|
developer_instructions: null,
|
|
},
|
|
};
|
|
} catch (cause) {
|
|
if (cause instanceof NativeSessionProtocolIntegrityError) throw cause;
|
|
const error = new Error(
|
|
`planning_mode_unsupported: installed Codex app-server did not expose a usable native plan collaboration mode (${redactCodexDiagnostic(String(cause))})`,
|
|
);
|
|
error.name = "PlanningModeUnsupportedError";
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async #persistProcessOwnership(
|
|
transport: CodexAppServerTransport,
|
|
): Promise<void> {
|
|
if (!this.#options.onSpawn) return;
|
|
const processInfo: CodexTransportProcessInfo | undefined =
|
|
transport.processInfo?.();
|
|
if (!processInfo || processInfo.exited || processInfo.pid === null) return;
|
|
const identity = `${processInfo.pid}:${processInfo.processGroupId ?? ""}:${processInfo.startedAt}`;
|
|
if (this.#persistedProcessIdentities.get(transport) === identity) return;
|
|
await this.#options.onSpawn({
|
|
pid: processInfo.pid,
|
|
processGroupId: processInfo.processGroupId,
|
|
startedAt: processInfo.startedAt,
|
|
});
|
|
this.#persistedProcessIdentities.set(transport, identity);
|
|
}
|
|
|
|
async #initialize(
|
|
transport: CodexAppServerTransport,
|
|
): Promise<Record<string, unknown>> {
|
|
const initialized = await transport.request("initialize", {
|
|
clientInfo: {
|
|
name: "paperclip-runner",
|
|
title: "Paperclip Runner",
|
|
version: DRIVER_VERSION,
|
|
},
|
|
capabilities: { experimentalApi: true, requestAttestation: false },
|
|
});
|
|
transport.notify("initialized");
|
|
return initialized;
|
|
}
|
|
|
|
async #discoverGoal(
|
|
transport: CodexAppServerTransport,
|
|
threadId: string,
|
|
): Promise<HarnessThreadGoal | null | undefined> {
|
|
if (!this.#caps.goals) return undefined;
|
|
try {
|
|
const response = await transport.request("thread/goal/get", { threadId });
|
|
return parseThreadGoal(response.goal);
|
|
} catch (error) {
|
|
if (error instanceof NativeSessionProtocolIntegrityError) throw error;
|
|
const policyDisabled =
|
|
error instanceof CodexRpcError
|
|
&& (error.message.toLowerCase().includes("policy")
|
|
|| error.message.toLowerCase().includes("disabled"));
|
|
if (policyDisabled || isCodexMethodUnavailable(error)) {
|
|
// The provider answered, and its answer is that this build has no goal
|
|
// API. That is the only evidence that retires the capability.
|
|
this.#caps.goals = false;
|
|
if (policyDisabled) {
|
|
this.#goalAvailability = "policy_disabled";
|
|
this.#goalReasonCode = "codex_goal_policy_disabled";
|
|
this.#goalReason =
|
|
"Session goals are disabled by the Codex provider policy.";
|
|
} else {
|
|
this.#goalAvailability = "unsupported";
|
|
this.#goalReasonCode = "codex_goal_api_unavailable";
|
|
this.#goalReason =
|
|
"This Codex app-server does not expose thread goals.";
|
|
}
|
|
this.#options.onDiagnostic?.(
|
|
redactCodexDiagnostic(`thread goals unavailable: ${String(error)}`),
|
|
);
|
|
return undefined;
|
|
}
|
|
// A transport or protocol failure says nothing about what the provider
|
|
// supports, so the capability stays as advertised and the goal is merely
|
|
// unknown until the next call.
|
|
this.#options.onDiagnostic?.(
|
|
redactCodexDiagnostic(`thread goal probe failed: ${String(error)}`),
|
|
);
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
#openedThread(
|
|
response: Record<string, unknown>,
|
|
initialize: Record<string, unknown>,
|
|
expectedWorkingDirectory: string | null,
|
|
collaborationMode: Record<string, unknown> | null,
|
|
): OpenedCodexThread {
|
|
const thread = record(response.thread);
|
|
const threadId = text(thread.id);
|
|
if (threadId.length === 0)
|
|
throw new Error("Codex thread response omitted thread.id");
|
|
const providerSessionId = text(thread.sessionId) || null;
|
|
if (
|
|
this.#options.requireProviderSessionIdentity &&
|
|
providerSessionId === null
|
|
) {
|
|
throw new Error(
|
|
`provider_initialize_protocol_error: provider=${this.#options.driverIdentity?.kind ?? "codex"} stage=session.open omitted provider session identity`,
|
|
);
|
|
}
|
|
const workingDirectory = codexThreadWorkingDirectory(
|
|
response.cwd,
|
|
expectedWorkingDirectory,
|
|
this.#options.workingDirectoryAuthority,
|
|
);
|
|
const activePermissionProfile = record(thread.activePermissionProfile);
|
|
const permissionProfileId = text(activePermissionProfile.id);
|
|
const requestedMode = this.#options.requestedCollaborationMode ?? "default";
|
|
const requiredPermissionProfile =
|
|
text(createSecuredCodexThreadParams(workingDirectory, requestedMode, true, false, this.#options.environment).permissions);
|
|
if (
|
|
permissionProfileId.length > 0 &&
|
|
permissionProfileId !== requiredPermissionProfile
|
|
) {
|
|
throw new Error(
|
|
"Codex thread did not activate the required filesystem permission profile",
|
|
);
|
|
}
|
|
const configuredPermissionProfile = {
|
|
...activePermissionProfile,
|
|
id: requiredPermissionProfile,
|
|
};
|
|
const providerIdentity = parseProviderIdentity(thread.providerIdentity);
|
|
return {
|
|
threadId,
|
|
providerSessionId,
|
|
...(providerIdentity === undefined ? {} : { providerIdentity }),
|
|
collaborationMode,
|
|
context: {
|
|
protocolVersion: CODEX_CODEX_PROTOCOL_VERSION,
|
|
codexVersion: boundedText(initialize.userAgent),
|
|
clientInfo: {
|
|
name: "paperclip-runner",
|
|
title: "Paperclip Runner",
|
|
version: DRIVER_VERSION,
|
|
},
|
|
model: boundedText(response.model),
|
|
modelProvider: boundedText(
|
|
response.modelProvider,
|
|
boundedText(thread.modelProvider),
|
|
),
|
|
workingDirectory,
|
|
collaborationMode: collaborationMode === null ? "default" : "plan",
|
|
sandbox: {
|
|
permissionProfile: boundedCodexValue(configuredPermissionProfile),
|
|
legacyPolicy: boundedCodexValue(response.sandbox ?? null),
|
|
rootAccess: usesExternalRunnerSandbox(this.#options.environment ?? {}) ? (requestedMode === "plan" ? "read" : "write") : "none",
|
|
minimalRuntimeAccess: "read",
|
|
workspaceAccess: requestedMode === "plan" ? "read" : "write",
|
|
networkAccess: codexNetworkAccess(this.#options.environment),
|
|
githubAuthenticationMode: this.#options.environment?.PAPERCLIP_GITHUB_AUTH_MODE ?? "managed",
|
|
},
|
|
approvalPolicy: boundedCodexValue(
|
|
response.approvalPolicy ??
|
|
this.#options.approvalPolicy ??
|
|
"never",
|
|
),
|
|
baseInstructions: this.#baseInstructions(),
|
|
instructionSources: Array.isArray(response.instructionSources)
|
|
? response.instructionSources
|
|
.filter((value): value is string => typeof value === "string")
|
|
.slice(0, 32)
|
|
.map((value) => boundedText(value))
|
|
: [],
|
|
instructionPolicy: {
|
|
skillInstructions: this.#options.includeSkillInstructions ?? false,
|
|
appInstructions: false,
|
|
collaborationInstructions:
|
|
this.#options.includeCollaborationModeInstructions ?? true,
|
|
},
|
|
environmentKeys: Object.keys(
|
|
codexCommandEnvironment(this.#options.environment),
|
|
).sort(),
|
|
dynamicToolNames: this.#providerDynamicTools().map((tool) =>
|
|
text(tool.name),
|
|
),
|
|
modelInputKinds: ["text"],
|
|
liveConsole: {
|
|
conversationMode: this.#prepared()
|
|
? "prepared"
|
|
: this.#direct()
|
|
? "direct"
|
|
: "task",
|
|
runtimeRequestResolution: this.#caps.runtimeRequestResolution,
|
|
goals: this.#caps.goals,
|
|
threadLineage: this.#caps.threadLineage,
|
|
},
|
|
envelope: structuredClone(this.#options.taskEnvelope),
|
|
},
|
|
lineage: lineageFromThread(thread),
|
|
};
|
|
}
|
|
|
|
#session(input: {
|
|
transport: CodexAppServerTransport;
|
|
runId: string;
|
|
normalizedSessionId: string;
|
|
opened: OpenedCodexThread;
|
|
goal?: HarnessThreadGoal | null;
|
|
goalAvailability: CodexGoalAvailability;
|
|
goalReasonCode: string | null;
|
|
goalReason: string | null;
|
|
resumed: boolean;
|
|
activeTurnId?: string | null;
|
|
semanticResult?: PersistedHarnessSemanticResult | null;
|
|
normalizeReplayPayload?: HarnessSessionRecoveryOptions["normalizeReplayPayload"];
|
|
terminalTurns?: PersistedHarnessTurnTerminal[];
|
|
codexUsageBaseline?: PersistedHarnessSession["codexUsageBaseline"];
|
|
dispositionOnlyRecoveryConsumed?: boolean;
|
|
dispositionOnlyRecoveryTurnId?: string | null;
|
|
adoptedAcceptedTurnId?: string | null;
|
|
lostAcceptedTurnId?: string | null;
|
|
stalePendingRuntimeRequests?: HarnessRuntimeRequest[];
|
|
lineage?: HarnessThreadLineageEntry[];
|
|
sourceSequence: number;
|
|
}): CodexHarnessSession {
|
|
return new CodexHarnessSession({
|
|
...input,
|
|
taskEnvelope: this.#options.taskEnvelope,
|
|
conversationMode: this.#prepared()
|
|
? "prepared"
|
|
: this.#direct()
|
|
? "direct"
|
|
: "task",
|
|
now: this.#options.now ?? (() => new Date()),
|
|
runnerInstanceId: this.#options.runnerInstanceId ?? "runner-codex",
|
|
driverKind: this.#options.driverIdentity?.kind ?? DRIVER_KIND,
|
|
capabilities: this.#caps,
|
|
goalCapability: this.#goalCapability,
|
|
dynamicTools: this.#providerDynamicTools(),
|
|
skillInputs: this.#options.skillInputs,
|
|
reasoningEffort: this.#options.reasoningEffort,
|
|
diagnosticEnvironment: this.#options.environment,
|
|
dynamicToolHandler: this.#options.dynamicToolHandler,
|
|
completionFeedback: this.#options.completionFeedback,
|
|
});
|
|
}
|
|
}
|