Files
PaperClipAI/packages/adapter-utils/src/acpx-engine/turn-sequence.ts
T
Nicky LeachandPaperclip b446ff59bf refactor(acpx-engine): coordinator-owned ACP run lifecycle with a typed resource ledger (#11576)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agent adapters run agent sessions through the ACPX engine
> - The ACPX engine handled one run attempt as a long implicit procedure
> - That shape made resource ownership, cleanup order, and failure
behavior hard to verify
> - This pull request gives the attempt a coordinator, a typed resource
ledger, separate run sites, and explicit turn and settlement sequences
> - The benefit is clear ownership, one cleanup path, safer session
reuse, and testable failure behavior

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The ACPX engine manages startup, turn execution, session reuse, and
cleanup inside one large run procedure.

**Current behavior**

The run procedure owns several resources through implicit control flow.
Cleanup and session reuse behavior depend on lane-specific branches and
error paths.

**Proposed behavior**

The coordinator owns the run attempt. A typed ledger records six
resources and their states. Host and sandbox run sites own lane-specific
acquisition. Turn and settlement sequences expose typed outcomes. The
engine emits allowlisted phase telemetry.

**Reason and benefit**

Explicit ownership makes cleanup and failure behavior easier to inspect.
The fault matrix and characterization tests protect the external result
while the refactor reduces hidden control flow.

**Breaking changes**

None to the public adapter contract. The host warm-save path now closes
and relaunches the runtime because a transferred runtime could retain a
run-scoped credential. A cold session-handshake failure now closes the
created runtime.

**Additional context**

This pull request contains the ACPX engine lifecycle refactor, its
tests, and the lifecycle document.

## What Changed

- Add a run coordinator for startup, turn execution, settlement, and
result reproduction.
- Add a typed resource ledger with open, sealed, and consumed states.
- Add host and sandbox run sites for lane-specific resource acquisition.
- Replace separate runtime maps with a generic session reuse store.
- Split session fingerprint identity from the outer session key.
- Add typed turn and settlement sequences with one cleanup owner.
- Add a closed allowlist for phase telemetry.
- Add characterization tests and a 17-case fault matrix.
- Add `doc/acp-run-lifecycle.md`.

## Verification

- `npx vitest run packages/adapter-utils/src/acpx-engine/` passes 18
files and 286 tests at the submitted commit.
- `pnpm --filter @paperclipai/adapter-utils typecheck` reports 0 errors
at the submitted commit.
- Run the full pull request checks after GitHub starts CI.
- Run Greptile review after the pull request opens.

## Risks

- The refactor changes internal control flow across the ACPX engine.
- Host warm-save behavior now closes and relaunches the runtime.
- Settlement changes the handling of a cold session-handshake failure
from a leak to a close.
- The characterization baselines and fault matrix reduce the risk of an
external behavior change.

> Paperclip is the open source app people use to manage AI agents for
work
> The adapter layer runs agent sessions through the ACPX engine
> The engine needs explicit lifecycle ownership for reliable cleanup
> This pull request adds coordinator-owned phases and a typed resource
ledger
> The result makes lifecycle behavior easier to test and review

## Model Used

OpenAI GPT-5 Codex. Exact model ID: GPT-5. The model used tool
execution, repository inspection, and code review support. The
implementation author supplied the submitted code.

## 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-08-17 22:02:16 -07:00

101 lines
4.5 KiB
TypeScript

// The turn sequence.
//
// `runTurn(steps)` is a plain sequence. It runs five steps in a fixed order:
// promptBuild, preTurnUsage, turnStart, eventRelay, turnFinalize. It never
// rejects: every step error becomes a typed `TurnCompletion` through the
// `turnFinalize` step. The sequence owns the wall-clock timer and the abort
// controller. It borrows the run resources; it finalizes no resource. The
// coordinator (Phase 20) settles the resources after the turn.
//
// The sequence is data, not a graph and not a state machine. The engine supplies
// each step; the sequence owns only the order, the timer, and the abort signal.
// This keeps the sequence free of the engine's private run state.
import type { TurnCompletion } from "./run-contracts.js";
/**
* A turn the site started. The sequence borrows it to cancel it on a timeout; it
* releases nothing. The engine's `eventRelay` step reads the events and the
* terminal result.
*/
export interface StartedTurn {
cancel(reason: string): Promise<void>;
}
/**
* The input the sequence hands to the one `turnFinalize` step. A `terminal`
* input carries the turn's terminal result; an `error` input carries the step
* error and the phase it failed in. Both carry the wall-clock timeout flag.
*/
export type TurnFinalizeInput<TTerminal> =
| { readonly kind: "terminal"; readonly terminal: TTerminal; readonly timedOut: boolean }
| {
readonly kind: "error";
readonly error: unknown;
readonly phase: "prepare_turn" | "turn";
readonly timedOut: boolean;
};
/**
* The five steps the sequence runs, plus the timer inputs. The engine implements
* each step over its own run state. `turnFinalize` maps a terminal result or a
* step error to a `TurnCompletion`; it must not reject, so the sequence never
* rejects.
*/
export interface TurnSteps<TTerminal> {
/** The wall-clock timeout, in milliseconds, or undefined for no timeout. */
readonly timeoutMs: number | undefined;
/** The message the timeout cancel carries. */
readonly timeoutMessage: string;
/** Build the prompt and emit the run metadata. A failure here is `prepare_turn`. */
promptBuild(signal: AbortSignal): Promise<void>;
/** Snapshot the pre-turn usage, so this run's cost excludes earlier runs. */
preTurnUsage(): Promise<void>;
/** Start the turn with the run's six inputs. The sequence adds the signal and the timeout. */
turnStart(signal: AbortSignal, timeoutMs: number | undefined): StartedTurn;
/** Relay the turn events and return the terminal result. */
eventRelay(turn: StartedTurn): Promise<TTerminal>;
/** Map a terminal result or a step error to a `TurnCompletion`. Must not reject. */
turnFinalize(input: TurnFinalizeInput<TTerminal>): Promise<TurnCompletion>;
}
/**
* Run the turn sequence. It returns a `TurnCompletion` on every path and never
* rejects. A failure before `turnStart` returns is a `prepare_turn` failure; a
* failure after it is a `turn` failure. Only the reported phase differs.
*/
export async function runTurn<TTerminal>(steps: TurnSteps<TTerminal>): Promise<TurnCompletion> {
const controller = new AbortController();
let timeout: ReturnType<typeof setTimeout> | null = null;
let timedOut = false;
let started: StartedTurn | null = null;
// `turnStarted` separates a pre-turn preparation failure from a running-turn
// failure, so `turnFinalize` reports the right phase.
let turnStarted = false;
try {
// Build the prompt and snapshot the pre-turn usage inside the failure
// boundary. A failure here is a `prepare_turn` failure.
await steps.promptBuild(controller.signal);
await steps.preTurnUsage();
// The sequence owns the wall-clock timer. On a timeout it marks the run timed
// out, aborts the shared signal, and cancels the started turn. The cancel
// no-ops before `turnStart` returns, because `started` is still null.
if (steps.timeoutMs !== undefined) {
timeout = setTimeout(() => {
timedOut = true;
controller.abort();
void started?.cancel(steps.timeoutMessage).catch(() => {});
}, steps.timeoutMs);
}
started = steps.turnStart(controller.signal, steps.timeoutMs);
turnStarted = true;
const terminal = await steps.eventRelay(started);
if (timeout) clearTimeout(timeout);
return await steps.turnFinalize({ kind: "terminal", terminal, timedOut });
} catch (error) {
if (timeout) clearTimeout(timeout);
const phase: "prepare_turn" | "turn" = turnStarted ? "turn" : "prepare_turn";
return await steps.turnFinalize({ kind: "error", error, phase, timedOut });
}
}