mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plugin environments (for example, an agent computer) run agents as plugin Runner tasks. Core sends each task one typed credential, and gets refreshed sign-ins back through the task's `credentials` snapshot. > - #22930 let a Google Antigravity task carry a Gemini API key. A Google subscription sign-in was still refused with "Google sign-in is not supported." > - The Cloud rollout plan (#22923) needs both routes. This is gaps G3 and G4 and work item 2: deliver the sign-in, and save a rotated refresh token safely, as Codex does. > - This pull request sends the saved, sanitized sign-in as the `antigravity` `provider-env` credential under `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`. It saves a refreshed token from the snapshot only after the generation, epoch and Google account checks. > - The benefit is that a plugin (for example, the Cloud agent computer) can run an Antigravity task with a person's Google sign-in, and token refreshes are not lost or saved to the wrong account. The picker, Test and save refusals for plugin targets (item 6) and the qualification flip (item 8) stay out of scope. ## Linked Issues or Issue Description Refs #22923 Refs #22930 **What problem does this solve?** A plugin Runner task cannot use a Google sign-in for Google Antigravity. Core refuses it at run start. There is also no path to save a refresh token that the Runner rotated on the plugin's computer. **Proposed solution** Add the sign-in variable as a second `antigravity` key set in `provider-env`. Core reads the sign-in from the run's private managed home, runs it through `sanitizeAntigravityCredential`, and sends that exact output. Core saves the write-back binding (grant, secret, session epoch, and a SHA-256 of the starting sign-in) on the lease. When the task stops, Core reads the snapshot and saves a new token only if all checks pass. **Alternatives considered** A new credential type for the sign-in. `provider-env` already has the exact-set check, the credential binding contract and the cross-check against the Runner's allowlists. The Cloud plan already describes the Launcher row as "`GEMINI_API_KEY` or the sign-in key". ## What Changed - `packages/plugins/sdk/src/environment-tasks.ts`: the `antigravity` key sets are now `GEMINI_API_KEY` or `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`. A mix of both stays rejected. - `server/src/services/native-runtime/plugin-runner-credentials.ts`: with no Gemini API key, Core reads `antigravity-acp/acp_token.json` from the selected managed home and sends the sanitizer's complete output (client ID, client secret, refresh token, token URI, `scopes`, and `project_id` when present). It never sends an access token or the account email. The task needs write-back authority. A sign-in supplied through the environment is refused. An unreadable or invalid saved sign-in fails with "The selected Google Antigravity account is unavailable. Reconnect the Google account, then retry." No error contains credential text. - `server/src/services/ai-connection-runtime.ts`: a Google subscription run now returns a write-back binding with `google.credentialSha256` of the starting sign-in. - `server/src/services/managed-ai-credential-writeback.ts`: new `syncManagedAntigravityCredential`. It requires an active grant, the same secret reference and session epoch, a Google subscription connection, and a saved sign-in that still hashes to the starting generation. It verifies a changed token with the existing account check (`prepareAntigravityCredentialWriteback`) in a private temporary home, then rechecks all of the above under the account lock before it rotates the secret. It writes `ai_connection.credential_refreshed` on save. For a different account, or a connection with no saved account, it saves nothing, writes `ai_connection.credential_refresh_refused` with a plain reason, and settles as `account_refused`. - `server/src/services/plugin-task-credential-writeback.ts`: a handoff with a Google binding takes the snapshot's `provider-env` `antigravity` sign-in and uses the Google write-back. Codex is unchanged. - `server/src/services/native-runtime/native-session-executor.ts`: a sign-in credential needs a Google write-back binding, and a Codex credential needs a non-Google one. - `server/src/services/native-runtime/antigravity-runner-credentials.ts`: the account mismatch is a typed error. The message is unchanged. - Docs: `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md` and `doc/plugins/PLUGIN_RUNNER_EXECUTION.md` describe the sign-in credential, where the Runner stages it, and the snapshot that the plugin must return. - `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the changed SDK source. ## Verification - Red first: with the source changes removed, 22 of the new and updated tests failed (the refusal, no write-back binding, no Google write-back). - Green after the change: - `cd server && npx vitest run src/__tests__/antigravity-plugin-task-credential-writeback.test.ts` (11 passed, embedded PostgreSQL): delivery of the exact sanitized sign-in; same-account rotation saved and logged; a second rotation during the account check saved; a different account refused and recorded in plain words; unchanged token with no Google call; reconnect (new generation and epoch) and a revoked grant discard the write-back without an export; a Google outage keeps the handoff pending and the next cleanup saves it; Codex, API-key and invalid snapshots refused. No token, client secret or access token in lease metadata, activity rows or errors. - `cd server && npx vitest run src/services/native-runtime/plugin-runner-credentials.test.ts src/__tests__/plugin-runner-credential-names.test.ts` (39 passed). The names test checks that the Runner forwards the sign-in variable to the sidecar and keeps it out of the provider process. - `cd packages/plugins/sdk && npx vitest run tests/environment-task-release-resume.test.ts tests/environment-tasks.test.ts` (104 passed) - `cd server && pnpm typecheck` (clean) - `pnpm verify` (see the CI run for broad coverage) - No live run, no Google login and no real token was used. All Google calls are fixtures. ## Risks - Low for current users. Plugin targets still refuse Antigravity in the picker, Test and save (item 6), so no existing agent reaches this path until item 6 merges. - The lease now stores a SHA-256 of the starting sign-in. It is a one-way digest of a high-entropy token, and it is the same kind of generation value that Core already derives for the local route. - If Google rotates the token during the account check and the database save then fails, the cleanup retries from the plugin's snapshot. Google does not normally rotate these refresh tokens, so this matches the local route's exposure without its recovery journal. - The Launcher must return the Runner's `auth-refresh.json` (or `acp_token.json` before lease close) in the snapshot. A Launcher that returns the starting sign-in only records `unchanged`, so no token is lost on the Core side, but a rotation on the computer would not be saved. > 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, in Claude Code with tool use (shell, file edits, test runs). Standard context window, 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
631 lines
36 KiB
Markdown
631 lines
36 KiB
Markdown
# Environment task API
|
||
|
||
An environment driver can provide a Runner task through a worker hook.
|
||
The task API has no shell command. Its optional file-read operation is scoped
|
||
to the active task workspace.
|
||
|
||
This API is a server and worker contract. The [native execution integration](PLUGIN_RUNNER_EXECUTION.md)
|
||
connects a task-capable environment to a Runner run.
|
||
|
||
## Declare the hook
|
||
|
||
Set `supportsTasks: true` on the environment driver in the plugin manifest.
|
||
Implement `onEnvironmentTask` with the SDK types:
|
||
|
||
```ts
|
||
import type {
|
||
PluginEnvironmentTaskParams,
|
||
PluginEnvironmentTaskResult,
|
||
} from "@paperclipai/plugin-sdk";
|
||
|
||
type TaskHook = (
|
||
params: PluginEnvironmentTaskParams,
|
||
) => Promise<PluginEnvironmentTaskResult>;
|
||
```
|
||
|
||
Core requires the `environment.drivers.register` capability, a ready plugin,
|
||
the manifest declaration, and the worker's `environmentTask` method.
|
||
The SDK validates each operation and its result before it returns the result.
|
||
See [the schemas](../../packages/plugins/sdk/src/environment-tasks.ts) for all fields.
|
||
|
||
## Operations
|
||
|
||
| Operation | Result | Required behavior |
|
||
| --- | --- | --- |
|
||
| `describe` | `description` | Return the installed Runner version and SHA-256 digest. |
|
||
| `prepare` | `prepared` | Prepare the provider configuration for the exact Core requirements. Do not start a process. |
|
||
| `submit` | `accepted` | Start the same opaque task at most once. Use the structured launch inputs. |
|
||
| `copilot_metadata` | `copilot_metadata` | Verify a Copilot account and model on a private setup lease. Send no prompt. |
|
||
| `connection` | `connection` | Return an authenticated WSS endpoint and its generation. |
|
||
| `status` | `status` | Report the phase and observed process termination. |
|
||
| `check_project_auth` | `project_auth` | Validate the prepared project configuration before managed credential transfer. |
|
||
| `read_file` | `file` | Read one bounded, task-scoped file from the active task. |
|
||
| `read_state` | `state` | Read the exact retained Runner checkpoint. |
|
||
| `archive_state` | `state` | Archive suspended authority with an idempotent archive key. Keep provider session files. |
|
||
| `credentials` | `credentials` | Return the selected account after process termination. |
|
||
| `stop` | `accepted` | Stop the task and its descendants. Fence a delayed submission. |
|
||
| `complete` | `accepted` | Release task resources after Core saves required results. |
|
||
| `release` | `released` | End active use of an exact, settled Runner session. Requires `releaseResumeVersion: 1`. |
|
||
| `resume` | `resume` | Request the same logical session with a fresh bootstrap ticket. Requires `releaseResumeVersion: 1`. |
|
||
|
||
For a refused `submit` with `resumeFrom`, a driver can throw an error with
|
||
`status: 409`, `code: "SESSION_STATE_UNAVAILABLE"`, and `reason` set to
|
||
`"unresolved_operation"` or `"source_state_unverified"`. The SDK worker and
|
||
Core preserve only these closed diagnostic fields. They replace the provider
|
||
message and omit provider identities and text. Read the validated RPC envelope
|
||
with `readEnvironmentTaskErrorDiagnostic`.
|
||
|
||
This diagnostic does not authorize a retry, replacement, cleanup or state
|
||
change. Other task failures keep the existing generic error. An older SDK
|
||
does not carry this diagnostic. Operation and call identities, when needed,
|
||
must come from Core's own retained records.
|
||
|
||
Each result must contain the task ID from the request. Core rejects a result
|
||
with a different ID or result kind. A WSS URL must have no user information,
|
||
query, or fragment. Return authentication in the secret headers.
|
||
|
||
`submit` contains the PRP version range, Runner identity, bootstrap ticket,
|
||
authorized project IDs, and optional launch limits. It can also contain a saved
|
||
task ID for session reuse and a typed credential. Core does not supply an
|
||
executable command or a guest path.
|
||
|
||
### Typed credentials
|
||
|
||
The `credential` field has one of these types:
|
||
|
||
| `type` | Contents | Harness |
|
||
| --- | --- | --- |
|
||
| `codex-auth-json` | `authJson`: the selected Codex `auth.json` | `codex` |
|
||
| `claude-env` | `environment`: exactly one of `CLAUDE_CODE_OAUTH_TOKEN` or `ANTHROPIC_API_KEY` | `claude` |
|
||
| `provider-env` | `provider` and `environment`: one complete variable set for that provider | `grok`, `copilot`, `opencode` or `antigravity` |
|
||
|
||
A `provider-env` credential contains exactly one of these variable sets and no
|
||
other variable:
|
||
|
||
| `provider` | Variable sets |
|
||
| --- | --- |
|
||
| `grok` | `XAI_API_KEY` |
|
||
| `copilot` | `COPILOT_GITHUB_TOKEN` |
|
||
| `opencode` | `OPENROUTER_API_KEY`, or `PAPERCLIP_AI_PROVIDER_URL` with `PAPERCLIP_AI_PROVIDER_KEY` |
|
||
| `antigravity` | `GEMINI_API_KEY`, or `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET` |
|
||
|
||
`ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS` exports this list. A server test
|
||
checks every set against the names that the Runner forwards to each provider. Every value
|
||
is non-empty and contains no NUL byte. The `provider` always matches the
|
||
Runner harness of the task. Set the variables in the environment of the Runner
|
||
process. The Runner gives each variable only to its provider.
|
||
|
||
For `copilot` and `antigravity`, also set `PAPERCLIP_ACPX_CREDENTIAL_BINDING`
|
||
in the Runner environment. Its value is this JSON object, with the provider as
|
||
`agent`, its variable names as `names`, and the normalized session ID of the
|
||
task's PRP identity:
|
||
|
||
```json
|
||
{"schema":"paperclip.acpx_credential_binding.v1","agent":"copilot","sessionId":"<normalizedSessionId>","names":["COPILOT_GITHUB_TOKEN"]}
|
||
```
|
||
|
||
The Runner refuses a Copilot token or a Gemini API key without a matching
|
||
binding. For `antigravity`, the Runner also removes every other `GOOGLE_*` and
|
||
`GEMINI_*` variable before it starts the provider, so a configured variable
|
||
cannot redirect the key.
|
||
Core does not send a Grok subscription login. A Grok agent must use an xAI API
|
||
key in a plugin environment.
|
||
|
||
For a Google Antigravity agent bound to a Google sign-in, the
|
||
`antigravity` credential carries `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`.
|
||
Its value is the saved sign-in as a JSON document: the client ID, client
|
||
secret, refresh token, token URI, the `scopes` list, and `project_id` when the
|
||
account has one. It never contains an access token or the account email. Set it
|
||
in the private environment of that task's Runner process only, and name it in
|
||
`PAPERCLIP_ACPX_CREDENTIAL_BINDING`. Never put it in a file, a log, a
|
||
configured environment, or the environment of another task. The Runner writes
|
||
it to `<runtime root>/antigravity-home/antigravity-acp/acp_token.json` (directory
|
||
0700, file 0600) and does not pass it to the provider process. When the provider
|
||
lease closes, the Runner writes the newest sign-in to `auth-refresh.json` in
|
||
the same directory and removes `acp_token.json`. See "Credential writeback".
|
||
|
||
## Configured environment
|
||
|
||
An agent can have environment variables from its execution environment, its
|
||
own configuration, its project, and its routine. Core resolves secret
|
||
references for each run. It sends the result only to a provider whose
|
||
`description` result has `configuredEnvironmentVersion: 1`. An older provider
|
||
gets no new fields, and the run continues without the variables. Core writes a
|
||
run log line that names the variables it did not set.
|
||
|
||
- `submit` has `configuredEnvironment`. Set the variables in the Runner's
|
||
process environment. Add their names to `PAPERCLIP_CONFIGURED_ENV_KEYS`. The
|
||
Runner then gives them to every provider process.
|
||
- If a variable has the same name as a variable that the provider sets for its
|
||
own launch, use the provider's value. Do not fail the task.
|
||
- The values are transient secret input. Do not save them in task state, lease
|
||
metadata, journals, or logs.
|
||
- A retained Runner keeps the environment that it started with. Core includes
|
||
the values in its process reuse key. When a value changes, Core starts a new
|
||
task. It does not resume the retained Runner.
|
||
- A session handoff starts a new Runner, so its `resume` has
|
||
`configuredEnvironment`.
|
||
- A provider that also returns `resumeLaunchInputsVersion: 1` gets
|
||
`configuredEnvironment` on every `resume`. See "Release and resume".
|
||
|
||
A driver can declare `protectedEnvironmentKeys` in the manifest. These are the
|
||
variables that the driver always sets on its tasks. Core rejects a protected
|
||
variable in the configuration of an agent or environment that uses the driver.
|
||
In other places, such as a project or routine, Core saves the variable and
|
||
returns a `protected_environment_variable` notice that names the environments.
|
||
|
||
## Release and resume
|
||
|
||
`release` ends Core's active use of an exact, settled Runner session. Core calls
|
||
it only after the turn, required events, journal writes, tool results and turn
|
||
cleanup have settled. The provider verifies the six-field `identity` and refuses
|
||
stale, busy or unsettled requests. `released` does not cancel work or replace
|
||
`stop`, `complete`, `archive_state` or the allocation's `environmentReleaseLease`.
|
||
Hosts should retain reusable resources when capacity allows, but can reclaim
|
||
them under retention and capacity policy. Release guarantees neither retention
|
||
nor physical termination. The same contract applies to Codex and ACPX, with no
|
||
same-process-ID guarantee.
|
||
|
||
`resume` requests that same logical session using the source `identity` and a
|
||
fresh `bootstrapTicket`. Both operations retain the outer request's authorized
|
||
company, environment, task, lease and run scope. Resume requires an authenticated
|
||
current claimant run and lease; reject a null `runId`. Verify the source, account,
|
||
workspace and current authority before installing the ticket or reserving reuse.
|
||
The ticket is bounded transient authentication input, as on submission. Never
|
||
copy its bytes into status, metadata, logs, results or durable replay records.
|
||
|
||
A provider can return `resumeLaunchInputsVersion: 1` from `describe`. Core then
|
||
adds the launch inputs of `submit` to every `resume`, with the same values and
|
||
rules as on `submit` for the claimant run:
|
||
|
||
- `credential`, when Core would add `credential` to `submit`. Core resolves it
|
||
for the claimant run's selected account, so the value can be newer than the
|
||
credential that started the Runner. When Core has no credential for the task,
|
||
`resume` has no `credential`.
|
||
- `configuredEnvironment`, when the provider also returns
|
||
`configuredEnvironmentVersion: 1`.
|
||
|
||
An older provider gets no new fields. A session handoff keeps its existing
|
||
fields.
|
||
|
||
- A provider that must start the Runner again to resume the session, for example
|
||
after it moved the session to a new sandbox or after a reboot, starts the
|
||
Runner with these inputs, as on `submit`.
|
||
- A provider with a live Runner ignores the fields. The running Runner keeps the
|
||
credential and environment that it started with.
|
||
- The values are transient secret input, as on `submit`. Do not save them in
|
||
task state, lease metadata, journals, logs, results or durable replay records.
|
||
|
||
A provider can return `resumeRelaunchedRunnerVersion: 1` from `describe`. Core
|
||
then adds `relaunchedRunnerVersion: 1` to every `resume`. With this field, a
|
||
provider that must start the Runner again can start it on a different Runner
|
||
build. Use a build whose version can read the parked Runner's state: the same
|
||
version, or a newer semantic version. A prerelease is older than its release.
|
||
Report that build as `runner: { version, digest }` on the `resumed` result.
|
||
Core accepts the build only when its version can read the parked state. Core
|
||
then expects that build when the Runner authenticates. Core treats any other
|
||
build as `unavailable`. Without `relaunchedRunnerVersion`, start the Runner
|
||
again only on the parked build, and do not add `runner` to the result. Older
|
||
strict Core schemas reject `resumeRelaunchedRunnerVersion` in a description, so
|
||
advertise it only to a Core version that supports it.
|
||
|
||
A provider can return `resumeIdentityVersion: 1` from `describe`. Use it only
|
||
for a provider that stops a released Runner, so that every `resume` starts the
|
||
Runner again. Core then rotates the session to the claimant run before it calls
|
||
`resume`, and adds `runner: { runId, turnId, itemId }` to `resume`. These are the
|
||
claimant run's identity fields. The other identity fields do not change. With
|
||
this field, the provider must:
|
||
|
||
- Move the source Runner state (`runner-state.json`) out of the Runner state
|
||
directory into an archive, so that the Runner creates new state.
|
||
- Start the Runner as the claimant identity with the fresh `bootstrapTicket`.
|
||
- Return `runner: { version, digest }` on the `resumed` result.
|
||
|
||
The provider is the authority on whether a park exists. It relaunches only from
|
||
the source's settled cut, and Core does not check that cut again. That cut is the
|
||
`suspended` lifecycle, or the `ready` lifecycle with an empty outbox, every event
|
||
acknowledged and no command in progress. Core resumes on the assumption that the
|
||
source parked. When the task has no park of that source, return `unavailable`
|
||
once nothing runs for the task, and Core starts a fresh task from the saved
|
||
session. Otherwise Core sends one ordinary `run.attach` with no authority
|
||
hand-off. A retry with the same source, ticket
|
||
and `runner` must return the original result and must not start a second
|
||
Runner. Without `runner` on `resume`, keep the claimant handover above.
|
||
|
||
Core prepares the claimant run before this `resume`: its `prepare` has
|
||
`priorIdentity` set to the released source, and the released task is not yet
|
||
claimed. Core also takes this path when it recovers a released task after a
|
||
Core restart, if it recorded the build the task was released on and the
|
||
session's process configuration has not changed. A provider must then accept
|
||
that `prepare` without state it kept in memory before the restart.
|
||
|
||
While a released task can still be resumed, its `status` must report
|
||
`executionStopped: false`, even when its Runner process is stopped. Core
|
||
replaces a reused task whose `status` reports a stop, and then cannot resume
|
||
the released session on it. Report the stop only when the task can no longer
|
||
resume.
|
||
|
||
The `resume` result has a closed `outcome`:
|
||
|
||
- `resumed`: the same logical session is exclusively reserved for this claimant,
|
||
atomically against eviction and competing claims. Core obtains `connection`,
|
||
authenticates with the fresh ticket and performs ordinary `run.attach` with its
|
||
new identity. No new turn is permitted before attachment succeeds.
|
||
- `unavailable`: the host knows reuse is impossible, for example after eviction.
|
||
Core may select ordinary recovery, preserving its authorization, credential,
|
||
workspace and stop checks. This is not proof of physical termination.
|
||
|
||
Source mismatches, authentication failures, conflicting claimants, transport
|
||
failures and ambiguous claims remain errors. They must not become `unavailable`,
|
||
authorize replacement, or silently create a new logical session.
|
||
|
||
One release episode is allowed per exact source identity; ordinary `run.attach`
|
||
rotates authority before a later release. Release retries replay the original
|
||
result without releasing a resumed owner again. Resume retries with the same
|
||
source, claimant and ticket reconcile the same claim and original outcome.
|
||
Changed claimants or tickets conflict. A lost reply requires reconciliation,
|
||
not a replacement ticket or an assumption of eviction. Preserve replay fencing
|
||
after reclamation so delayed requests cannot change a newer owner.
|
||
|
||
Advertise `releaseResumeVersion: 1` from `describe` only when both operations are
|
||
implemented. Core must check it before use. Absence keeps the existing lifecycle;
|
||
warm or source recovery capabilities do not imply support. Older strict Core
|
||
schemas reject this description field, so coordinate advertisement with a
|
||
compatible Core version.
|
||
|
||
Core uses this pair only for explicitly supported warm tasks with a selected
|
||
account. It releases after the turn's required events, tool results, journal
|
||
writes and cleanup have settled. It keeps the exact session busy until the host
|
||
confirms release and Core records that source. Existing tasks without the
|
||
capability retain their ordinary warm lifecycle.
|
||
|
||
Before release, Core stops connection pings and reconnect work while keeping the
|
||
existing receive/ACK path open. A confirmed release closes the route and stops
|
||
its idle polling. An ambiguous release stays with the original run for bounded
|
||
reconciliation. It cannot pass to a new run's task scope. Cancellation or an
|
||
expired reconciliation budget uses ordinary host stop and physical cleanup;
|
||
it does not change an already completed business result.
|
||
|
||
Resume first checks the new run's account, credential revision and project
|
||
scope. It uses one fresh transient ticket, preserving that exact ticket through
|
||
ambiguous replies. Core authenticates the source before warm readiness, provider
|
||
preparation and ordinary `run.attach`; no new turn can pass that handover.
|
||
Generic RPC errors do not prove refusal or permit a new ticket, reconnect or
|
||
turn replay. A known `unavailable` result still requires ordinary physical
|
||
cleanup. Transparent cold fallback remains a separate qualification requirement.
|
||
|
||
A normal Core cache timeout detaches only Core's quiet local owner. The host
|
||
keeps its retained resources under its own retention policy. Core keeps no
|
||
record of a release beyond that owner. The transport returns the exact source
|
||
after the host's release receipt. Core checks it against the attached run,
|
||
session, Runner and lease, and only then marks its owner released. An invalid
|
||
source receipt keeps cleanup under the same owner until physical retirement
|
||
finishes. A later run resumes the source Core restores from its controller
|
||
checkpoint, on the lease's current task only, and the provider answers from its
|
||
own park record. Raw tickets are never stored.
|
||
|
||
When graceful host eviction has saved a suspended session and Core has recorded
|
||
physical stop, a later allocation can use ordinary `resumeFrom` recovery. Core
|
||
checks the old task, source identity and current scope before detaching a cached
|
||
released controller. Cached and detached paths then use the same retained-state
|
||
checks. Missing state, a foreign identity or an unsettled checkpoint refuses
|
||
continuation; Core does not replace the provider session on that refusal. This
|
||
covers eviction before allocation and stopped-task inspection during `describe`.
|
||
A later loss during claim still needs reconciliation. Abrupt process death without
|
||
a suspended checkpoint remains a separate recovery path.
|
||
|
||
These Core paths do not advertise the capability or opt ordinary tasks into a
|
||
private host channel. Existing durable lease and plugin-worker idle checks still
|
||
apply; retaining a released Runner does not by itself make a tenant safe to sleep.
|
||
Provider recovery, bounded host retention and deployment qualification are still
|
||
required before activation. Recovery from a Core crash
|
||
between claim and source authentication is not qualified by this integration.
|
||
|
||
## Error codes
|
||
|
||
Core does not read the text of a task error. To report a failure that Core can
|
||
act on, throw `PluginEnvironmentTaskError` with a code from
|
||
`ENVIRONMENT_TASK_ERROR_CODES`. The SDK sends only the code as structured RPC
|
||
error data.
|
||
|
||
| Code | When to use it | Core behavior |
|
||
| --- | --- | --- |
|
||
| `runner_revision_mismatch` | The installed Runner does not match the revision that the plugin launches. Throw it from `describe` or `submit` before you prepare or start a task. | A run that has not started provider work is retried for up to 10 minutes. Agent verification checks again every minute. The task is not blocked during this wait. |
|
||
|
||
```ts
|
||
import { PluginEnvironmentTaskError } from "@paperclipai/plugin-sdk";
|
||
|
||
if (installed.revision !== expectedRevision) {
|
||
throw new PluginEnvironmentTaskError("runner_revision_mismatch");
|
||
}
|
||
```
|
||
|
||
Any other error stays an ordinary setup failure. The source refusal diagnostic above is separate: it uses its own envelope and does not authorize a retry.
|
||
|
||
## Launch preparation
|
||
|
||
A provider can return `launchPreparationVersion: 1` from `describe`.
|
||
Core can then send the `prepare` operation before `submit`.
|
||
|
||
The requirements contain the provider, model, policy, run identity, instructions,
|
||
and runtime context. They do not contain provider credentials or executable
|
||
choices. Resource paths identify source locations. The plugin must resolve them
|
||
for its execution environment.
|
||
|
||
The result contains a configuration ID, requirements digest, and provider
|
||
descriptor. The schema is `paperclip.runner.launch-requirements.v1`.
|
||
The digest is SHA-256 over the requirements JSON. Sort object keys in lexical
|
||
order at every level. Keep array order. Omit absent optional fields.
|
||
The execution owner must preserve Core policy and resource assignments.
|
||
|
||
Preparation must be idempotent for the task and requirements. The plugin owns
|
||
configuration storage and cleanup. A late preparation result must not authorize
|
||
execution after cancellation. The `submit` operation can reference the saved
|
||
configuration with `preparedLaunchId`.
|
||
|
||
Recovery can supply the prior prepared result. Recovery within the same run
|
||
must use the same configuration. A different run supplies its current
|
||
requirements. A saved task ID in `resumeFrom` requires the same retained-session
|
||
authority as submission.
|
||
|
||
Core requires preparation version 1 for native plugin execution. It validates
|
||
and saves the result before it submits its configuration ID.
|
||
|
||
### Stopped source reconciliation
|
||
|
||
A plugin’s `describe` response advertises `codexSourceRecoveryVersion: 1` for
|
||
Codex App Server and `acpxSourceRecoveryVersion: 1` for ACPX. It can advertise
|
||
either, both, or neither. Each field means the host can verify and restore a
|
||
stopped source for that provider without starting another turn. Core requires
|
||
the field for the selected provider and verifies the run’s eligibility.
|
||
|
||
Core admission recognizes native Codex and qualified Claude through ACPX. ACPX
|
||
Codex is a different provider and cannot use either attestation. Claude admission
|
||
checks both saved and current profiles against Runner’s qualified catalog;
|
||
decodable historical profiles do not authorize recovery. Preparation, submission
|
||
and attachment retain that provider binding. Runner’s launch factory normalizes
|
||
Claude’s model, mode, permissions, effort and runtime content before Core compares
|
||
them with the saved source or current owner. Core revalidates the claim and
|
||
profiles after worker replies. This admission does not activate executor recovery.
|
||
It grants no replacement authority or exception to deterministic recovery refusals.
|
||
|
||
The authenticated request belongs to
|
||
the current run while `prepare` and `submit` carry the predecessor Runner identity.
|
||
Core derives this relationship from its saved source-consumer claim; a mismatched
|
||
run ID alone never grants recovery. Both operations must name the same `resumeFrom`, exact source Runner identity, and current
|
||
`accountIdentity`. The request and lease still belong to the current run.
|
||
Preparation must save this source binding with its new configuration. Submission
|
||
must verify the same binding before it starts the source process.
|
||
|
||
Core requires the source run to have a committed successful result, an encrypted
|
||
PRP journal, confirmed physical termination, and no other source consumer. Core
|
||
claims the source under the current native controller lease. This does not change
|
||
the source run's status or result. A stale source controller cannot write its
|
||
journal after this claim. Workspace export and settlement holds still apply.
|
||
After source submission, the same current owner can prepare its attachment with
|
||
the exact source as `priorIdentity`. This does not grant ordinary warm reuse.
|
||
|
||
The provider must verify the original account, workspace, runtime, and source
|
||
ownership before launch. The provider must reject saved active goals, pending tools, ambiguous starts, and
|
||
uncertain work before launch. Runner verifies that a saved idle provider remains
|
||
idle when restored.
|
||
Until the existing authenticated `run.attach` operation changes authority, the
|
||
Core retains semantic inputs and sends no fresh predecessor business commands
|
||
while the restored source reconciles its journal and known cleanup. Ordinary suspended recovery and live attachment keep their existing
|
||
checks. Providers that omit the capability do not support predecessor recovery.
|
||
|
||
## Launch authentication validation
|
||
|
||
Declare `projectAuthCheckVersion: 1` in `describe` for each native task launch.
|
||
For a new task, Core reads this flag from the same description it uses to set up Runner.
|
||
Core calls `check_project_auth` after preparation and before credential transfer.
|
||
The request names the configuration ID, provider, and authorized project IDs.
|
||
It contains no credential.
|
||
|
||
A trusted provider can instead return `projectAuthCheckAtSubmit: true` in its
|
||
`prepared` result. Core then skips the separate check. This flag delegates the
|
||
check to submission; it does not claim that preparation checked authentication.
|
||
The provider must validate the effective configuration and current project grants
|
||
inside `submit`, before it installs credentials on the execution host or starts
|
||
the task. It must reject conflicts and changed preparation before those effects.
|
||
Core pins the configuration, provider, and project set on the lease and checks
|
||
them again at dispatch. A new preparation invalidates that scope. Providers that
|
||
omit the flag keep the separate check. The flag requires a Core version that
|
||
supports it; older strict result schemas reject it.
|
||
|
||
The plugin must check the effective configuration for that prepared launch.
|
||
Reject project settings, parent settings, helper commands, or environment routing
|
||
that can replace the selected account or redirect its credential.
|
||
Keep the checked configuration fixed until submission. If the configuration can
|
||
change, reject submission and require new preparation and validation.
|
||
|
||
Return `project_auth` with the same configuration ID and provider.
|
||
Set `allowed: true` only after the checks pass.
|
||
Core saves this result on the task lease. Core requires the exact configuration,
|
||
provider, and project set before each submission.
|
||
A new preparation or check removes the prior validation. A failed check does not
|
||
authorize credential transfer. The dispatch update also checks that validation
|
||
has not changed while Core waited for database work.
|
||
|
||
## Retained checkpoint operations
|
||
|
||
`read_state` supplies the exact durable identity and an optional `resumeFrom`.
|
||
`archive_state` supplies the prior identity, a 24-character lowercase hexadecimal
|
||
archive key, and `resumeFrom`. Both return `state` with the task ID and Runner
|
||
state object. They do not accept a filesystem path.
|
||
|
||
Core authorizes retained sources with the same checks as preparation and launch.
|
||
The plugin must read only that task's state. Archive must require process
|
||
termination and exact suspended identity. It must return the same archived state
|
||
on retry. It must keep the provider session files. Return an error when the state
|
||
is absent or its identity differs. Do not return credentials or environment values.
|
||
|
||
## Lease authority
|
||
|
||
Core calls `environmentRuntimeService.task` with a company ID, a saved lease ID,
|
||
and an operation. It derives the plugin and driver from the lease. A change to
|
||
the environment configuration cannot redirect cleanup to a new provider.
|
||
|
||
Before preparation or submission, Core checks the active lease, run, issue, and every project
|
||
in the company. It checks the submitting run ID separately from a retained PRP
|
||
identity. Session reuse requires the same agent, environment, workspace, and
|
||
provider. Checkpoint resumption also requires a retained source task and proof of termination.
|
||
Opt-in Codex warm reuse instead hands off the same retained process through an
|
||
atomic lease transition and an exact, authorized `priorIdentity` preparation.
|
||
|
||
An internal setup probe can use a private, time-limited lease without a run row.
|
||
Core checks the saved probe identity, rejects project mounts, and limits the
|
||
Runner lifetime to the remaining probe time.
|
||
|
||
## Failure and cleanup
|
||
|
||
A failed submission reply does not prove that the task failed to start.
|
||
Core saves the dispatch marker before it calls the worker. Retry against the
|
||
same task ID. Do not allocate another task to resolve an uncertain reply.
|
||
|
||
An accepted stop does not prove termination. Set `executionStopped: true`
|
||
only after the Runner and all descendants have stopped. A terminal phase alone
|
||
does not permit Core to release execution authority.
|
||
|
||
Core binds each Runner owner to the physical task ID returned by its description.
|
||
An old owner cannot follow a changed lease to stop or complete its replacement.
|
||
Late stopped-state, retained-session and credential-handoff writes must still
|
||
match that same physical task. A new owner can clean up the replacement.
|
||
|
||
Core fences new submissions when cleanup starts. It stops the saved task,
|
||
checks termination, saves credential results, and completes the task before it
|
||
releases or destroys the environment lease. An uncertain result leaves a saved
|
||
lease for the cleanup sweep. Cleanup can use that lease after the environment
|
||
or run row is deleted.
|
||
|
||
## Credential writeback
|
||
|
||
Account selection and credential revision have separate identities. Keep the
|
||
selected account fixed for the task. A credential result of `null` means that
|
||
cancellation prevented task admission. It must not mean that an export failed.
|
||
|
||
Core saves the account grant, secret reference, and session epoch on the lease.
|
||
It saves no credential bytes or temporary path in lease metadata. After process
|
||
termination, it can recover a Codex or Google sign-in refresh even if Core
|
||
restarted. It uses the existing account comparison and secret service. A
|
||
revoked grant, replaced account, or changed session epoch discards the old
|
||
refresh.
|
||
|
||
For a Google sign-in, `credentials` returns the same `provider-env` type with
|
||
`provider: "antigravity"` and only `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`,
|
||
set to the contents of the Runner's `auth-refresh.json` (or `acp_token.json`
|
||
if the lease has not closed). Core saves it only when the saved connection
|
||
still holds the exact sign-in that the task started with, and only after
|
||
Google confirms that the refreshed sign-in belongs to the connection's account.
|
||
A sign-in for another account is not saved; Core records that in the activity
|
||
log.
|
||
|
||
Keep file synchronization and backup outside this API. The provider must retain
|
||
recoverable credential state until task completion succeeds.
|
||
|
||
## Native environment test
|
||
|
||
The agent environment test can use a task-capable plugin environment. Core
|
||
creates a short-lived probe lease with a private run and session identity.
|
||
The probe has no project mounts or task tools. It prepares the launch, checks
|
||
authentication routing, and verifies the Runner and provider hello exchange.
|
||
A passing result requires confirmed cleanup. This test does not enable
|
||
heartbeat dispatch to plugin environments.
|
||
|
||
## Copilot account test
|
||
|
||
`copilot_metadata` accepts the selected token and an optional model ID. Core
|
||
permits it only on an active private setup lease. The provider must use the
|
||
verified Copilot metadata client. It must send no prompt and use no project
|
||
workspace or tool server. Return the metadata and `executionStopped: true` only
|
||
after the probe and its descendants stop. A lost reply keeps the task available
|
||
for `stop`, `status`, and `complete`. Core checks the profile and model before
|
||
it accepts the account. Do not store the token in task metadata or logs.
|
||
|
||
A native hello probe requires a managed AI connection and an isolated Runner home.
|
||
Without them, the probe fails the `ai_connection_required` check before Core
|
||
acquires a lease or calls a task operation. See
|
||
[Managed AI connection required](PLUGIN_RUNNER_EXECUTION.md#managed-ai-connection-required).
|
||
Only Core can supply the selected account identity and local credential home.
|
||
|
||
## Fresh attempts
|
||
|
||
A workspace provider opts in with `workspaceProvider.freshWorkspaceVersion: 1`.
|
||
A task environment also declares `environmentDrivers[].freshWorkspaceVersion: 1`
|
||
and returns `freshWorkspaceVersion: 1` from `describe`.
|
||
|
||
Core supplies a server-authorized `fresh` intent on workspace preparation and on
|
||
launch-related task calls. `attemptId` is stable across interrupted preparation.
|
||
`previousWorkspaceId` identifies retained storage; it is not permission to change
|
||
or remove it. The provider prepares a new working directory from the authorized
|
||
source and base. It may share repository objects or other immutable storage.
|
||
Core does not require a particular Git or filesystem layout.
|
||
|
||
`recoverySnapshots` contains verified, Core-staged archive and manifest files.
|
||
Each file descriptor contains a trusted host path, SHA-256, and byte size. These
|
||
paths are host-authored transfer sources, never user-supplied paths or URLs.
|
||
Providers verify the bytes and safely materialize each snapshot separately at
|
||
`.paperclip-recovered/<operationId>` beneath the new working directory. Preserve
|
||
file links safely and include provenance. Never overlay recovered files onto the
|
||
clean working tree or overwrite an earlier attachment. Core includes those
|
||
relative attachment paths in the new attempt's continuation context.
|
||
|
||
A provider reconciles the same attempt and workspace identity after an ambiguous
|
||
reply. It must not replace the failed workspace or allocate another workspace
|
||
when preparation is repeated. Providers without this version remain unavailable
|
||
for fresh attempts; ordinary preparation and reuse retain their existing contract.
|
||
|
||
Core keeps transfer files while preparation is uncertain. Confirmed task completion
|
||
and provider workspace removal release these disposable copies. The descriptors
|
||
remain stable: a later preparation downloads the same verified files again.
|
||
|
||
|
||
## Task workspace files
|
||
|
||
Core uses `read_file` for `call_api` file uploads and `register_deliverable`
|
||
when a plugin owns execution and advertises `workspaceFileReadVersion: 1` in
|
||
`describe`. The request includes the submitted Runner identity,
|
||
validated project IDs, a canonical relative or absolute path, and a byte limit (at most 10 MiB).
|
||
The provider resolves paths within locations granted to the active task. Relative
|
||
paths resolve from its prepared workspace. Absolute paths can select another
|
||
granted location such as agent home, but never a supervisor path or another
|
||
agent's files. Core does not prescribe provider filesystem layout.
|
||
|
||
The provider must reject inactive tasks, path escapes, symlinks, hard links,
|
||
non-regular files, protected credentials, oversized files, and files that change
|
||
while being read. Return canonical base64, byte size, and a SHA-256 digest in a
|
||
`file` result for the same task. Core validates the result and rechecks authority
|
||
before publishing it. Deliverables additionally verify the caller's expected
|
||
size and digest. Providers without this operation fail closed; Core never falls
|
||
back to reading remote paths on the server. Existing artifact uploads are unchanged.
|
||
|
||
## Login allocations on an existing computer
|
||
|
||
A login-capable environment driver can host authorization on a saved agent's
|
||
computer. Core checks the company, environment, agent lifecycle, manifest, and
|
||
live worker hooks before acquisition. Managed AI Connection requests can omit
|
||
the agent ID so Core selects an eligible agent from the company and environment.
|
||
Core uses that ID throughout the login. The chosen agent is a transport target
|
||
and the signed-in account retains its own owner and agent grants.
|
||
|
||
Core acquires this resource with `purpose: "login"`, the fixed command key, and
|
||
an absolute expiry. The returned lease must attest an expiry no later than that
|
||
deadline. Drivers must declare `creationOperationVersion: 1` and expose the live
|
||
`environmentAcquireLease`, `environmentInspectLease`, and `environmentReleaseLease`
|
||
hooks so Core can acquire, recover, and clean up the allocation.
|
||
Core does not submit a Runner task or mount project volumes.
|
||
The plugin keeps the computer binding in durable lease metadata. PTY close stops
|
||
and detaches the terminal while preserving its result. Lease release/destroy
|
||
removes only the login resources after Core commits the credential or ends the
|
||
attempt. It must preserve the computer and unrelated tasks.
|
||
|
||
The provider may assign a lease ID different from Core's creation operation ID.
|
||
Inspection by `creationOperation` must return that exact allocation as
|
||
`creationLease`, with its provider ID matching the observation envelope, so a
|
||
lost acquisition reply still reaches the existing cleanup path.
|
||
|
||
Claude uses the existing setup-token output parser. Codex uses the optional
|
||
`loginPtyReadCredential` hook to read its fixed auth artifact. Both retain the
|
||
existing owner-bound credential completion and durable cleanup. A restart
|
||
interrupts an unfinished login; it does not resume the terminal.
|