mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 23:06:17 +01:00
feat(runner): expose credential updates through PRP (#16463)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The Runner uses PRP to send harness events to the host. > - A harness can replace its stored OAuth tokens during a run. > - The host has no PRP signal that tells it to read the updated credential. > - This pull request adds a durable credential update event and observers for supported stores. > - The host can react before it acknowledges the event. Token values stay outside PRP. ## Linked Issues or Issue Description **Subsystem affected** `packages/paperclip-runner`: native provider execution, PRP schemas, and host event delivery. **Problem or motivation** A Paperclip host that consumes PRP needs to react when a harness changes its refresh-token credential. Existing credential copy-back paths do not provide a common event during a warm session. **Proposed solution** Add `auth.credentials.updated` as a P0 runner event. Include only the provider, binding ID, revision, and detection method. Observe native Codex and Codex/Grok ACPX credential files. Retain each pending event across runner restart until the durable outbox accepts it. Raw PRP consumers opt in with `observeCredentials: true` before session open. The bundled transport opts in for fresh sessions. **Alternatives considered** `harness.diagnostic` would mix a runner observation with harness diagnostics. Sending token values through PRP would expose credentials to event logs. Both approaches are unnecessary. **Roadmap alignment** I checked `ROADMAP.md`. This change extends the existing Runner protocol and does not duplicate a planned core feature. **Additional context** Refs: #11094, #14056, #12696. These describe credential copy-back and staging work. This PR adds the notification contract. It does not replace those private credential channels or claim to fix their full scope. ## What Changed - Add strict credential update payload validation to PRP v1, v2, and v3. Regenerate validators, the manifest, and the event catalog. - Watch supported credential directories with `notify`. Add a periodic read as a fallback and check at terminal and close boundaries. - Persist a private baseline and pending event together. Notify on account identity changes and retain the new baseline for later refreshes. Ignore incomplete files, unsafe files, and metadata changes. - Forward the event through the host transport. Test commit-before-ACK delivery and replay. - Commit pending runner observations before suspend and shutdown commands complete. Preserve the provider event backlog. - Create the private ACPX runtime directory before configuring observation. Cover fresh session startup with observation enabled. - Fence asynchronous PRP commits to the current authenticated connection and run authority. Ignore replaced callbacks while preserving the maintenance drain of admitted work. - Deliver observations found during final provider cleanup before clearing terminal recovery state. Retain the outbox and recovery state when the host ACK is lost. - Advance the pending Copilot candidate profile to v19 for the changed shared PRP source hashes. Preserve its v18 history and pending qualification status. Include the current fixture in the Docker build context. - Commit credential updates through an awaited host callback before PRP ACK, including during idle and close. Persist them in a separate run-log source namespace with company, agent, session, and runner checks. - Preserve public event metadata through server redaction. Register the event in task run details. - Document opt-in behavior, supported stores, event semantics, and the local run-log path. ## Verification - All 45 durable runner control tests and 24 native executor integration tests pass. - Ten Rust credential observer tests pass. They cover atomic replacement, polling, recovery, account-only changes and later refreshes for Codex and Grok, unsafe files, fresh runtime creation, and the Grok close handoff. Account identity stays private. - The full Runner TypeScript suite passes: 3,565 tests in 221 files. An additional 12 tests are skipped by the suite. - All 214 focused tests pass for the contract, Codex event routing, catalog, and durable host delivery. - All 13 Node protocol contract tests pass. - The exact Docker context integrity command passes: `docker buildx build --file .github/docker-context-checks.Dockerfile .`. - Rust formatting and generated protocol checks pass. - `pnpm -r typecheck` and `pnpm build` pass. The full local `pnpm test:run` was attempted with CI-compatible `init.defaultBranch=master`, then stopped after a reproducible failure outside this change: `git-workspace-expiration.test.ts` expects one re-expired workspace but gets zero. The same case fails in isolation on this macOS checkout. Full repository validation is provided by CI; the focused Runner and host tests pass locally. - All 253 native transport and restart tests pass against the final release binary. - All 3 durable recovery tests and 139 candidate profile and native admission tests pass. - All 41 host redaction and task protocol surface tests pass. `pnpm check:token-gates` passes. - All 467 CI policy tests pass, including the 15 CI profiling tests. The upstream secret-reference test fix is retained from master. No workflow changes are included. - The Apex host-delivery fix passes 381 targeted Runner tests, six host database tests, repository typecheck, and the production build. The Runner tests cover commit-before-ACK, retry after a rejected host commit, warm attachment, and close after the turn queue ends. - Prior head `2f125cfcb` passed CI, standard Greptile 5/5, and Apex 5/5. One CI shard was interrupted by GitHub runner shutdown; its single rerun passed. Both Apex findings are addressed: idle/cleanup host delivery and late callback reconnect fencing. Current head `5db78f082` passes CI (56 successful statuses and four optional skips) and standard Greptile 5/5. Apex review of the account-change update is 5/5 on this exact head, with no actionable issues. - All 121 durable control-plane and credential callback tests pass, including account-only change delivery, subsequent refresh on the new account during close, host commit retry, late success/failure races, forward cursor delivery on a replacement connection, and the existing maintenance retirement contract. All 27 native provider and durable recovery integration tests pass after the account-change update. ## Risks - File changes signal a stored credential update. They do not prove that an OAuth refresh succeeded. Changes between reads can be combined. - Unix Codex and Codex/Grok ACPX stores are supported. Other harnesses and credentials held only in memory need their own integration. - Hosts must update their event schemas before opting in. Older hosts omit the flag and receive no new event. Older runners ignore the flag. - The host must use its existing private credential channel and account checks to read or copy the token. Account switches trigger notification but do not authorize accepting the new account. The event grants no credential access. - Tests use synthetic credentials. No live OAuth refresh has been forced. ## Model Used OpenAI Codex, exact model ID `gpt-6.1-sol`, with high reasoning effort, repository inspection, tool use, and code execution. The session does not expose its context window size. ## 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>
This commit is contained in:
1 parent
23e7ee9a2d
commit
ec3eb1968b
49 files changed
+2071
-52
No files matched your search
+1
-1
@@ -43,7 +43,7 @@ packages/paperclip-runner/test/**
|
||||
!packages/paperclip-runner/test/fixtures
|
||||
packages/paperclip-runner/test/fixtures/**
|
||||
!packages/paperclip-runner/test/fixtures/copilot-profile-v16-identity.json
|
||||
!packages/paperclip-runner/test/fixtures/copilot-profile-v18-identity.json
|
||||
!packages/paperclip-runner/test/fixtures/copilot-profile-v19-identity.json
|
||||
!packages/paperclip-runner/test-fixtures
|
||||
packages/paperclip-runner/test-fixtures/**
|
||||
!packages/paperclip-runner/test-fixtures/pi-acp
|
||||
|
||||
@@ -21,6 +21,20 @@ They also become native Observability spans only with an operator OTLP endpoint.
|
||||
|
||||
## Native PRP Run-Log Events
|
||||
|
||||
`auth.credentials.updated` is a runner-produced PRP event for a change to a
|
||||
supported credential store, including account identity changes and later token
|
||||
refreshes on the new account. The bundled transport awaits a host commit callback
|
||||
before acknowledging delivery, including during warm idle and provider cleanup.
|
||||
The callback writes directly to the bound run through the shared run-log writer.
|
||||
Its separate credential source namespace avoids collisions with driver-normalized
|
||||
source sequences and deduplicates retries using the original PRP event identity.
|
||||
The original envelope is retained in `prpEvent`. Its payload contains only a
|
||||
provider, an opaque binding ID, a revision, and a detection method. It contains
|
||||
no credentials, account identity, file path, or credential fingerprint. The
|
||||
consumer can use the event to read the updated credentials through its existing
|
||||
private credential channel. This run-log event stays in the instance database.
|
||||
|
||||
|
||||
`native.recovery.execution_reclaimed` records an atomic same-run recovery claim
|
||||
that restores a released task execution binding. The claim locks the task,
|
||||
coordinator, and original run in that order. It preserves the assignee and checks
|
||||
|
||||
@@ -32,12 +32,12 @@
|
||||
"requiresProviderPolicy": true
|
||||
},
|
||||
"copilot": {
|
||||
"agentProfileVersion": 18,
|
||||
"agentProfileVersion": 19,
|
||||
"agentServerPackage": "@github/copilot",
|
||||
"agentServerVersion": "1.0.88",
|
||||
"agentRuntimePackage": null,
|
||||
"agentRuntimeVersion": null,
|
||||
"commandDigest": "sha256:2ec904f44218f51058fa83d7437b26c4551e1c65e6f2c55f5a6386fa4061e96d",
|
||||
"commandDigest": "sha256:38abf359adeef43f1f19230245c6e2051c55fdd79571882ef6f00b7cb2958d93",
|
||||
"requiresProviderPolicy": true,
|
||||
"qualificationStatus": "pending"
|
||||
},
|
||||
|
||||
@@ -47,6 +47,69 @@ goal can be idle between autonomous turns. A runner emits the full capability
|
||||
and authoritative snapshot after every session open or resume. Missing v1
|
||||
capability is unsupported; clients do not infer support from an adapter name.
|
||||
|
||||
## Harness credential updates
|
||||
|
||||
`auth.credentials.updated` is a P0 runner event available in the v1, v2, and v3 event
|
||||
schemas. Its payload uses `paperclip.auth.credentials.updated.v1` and contains
|
||||
only `provider`, `bindingId`, `revision`, and `detection`. No tokens, account
|
||||
identifiers, credential paths, or credential fingerprints are permitted.
|
||||
|
||||
An updated consumer opts in with `observeCredentials: true` in `run.prepare`,
|
||||
before `session.open`. The bundled runner transport opts in for fresh sessions;
|
||||
set its `observeCredentials` option to `false` to disable observation for a
|
||||
fresh session. Older hosts that omit the field receive no new event. Consumers
|
||||
must update their schemas before opting in: an event-enum addition is not an
|
||||
unknown optional property. Existing runner binaries ignore the optional flag
|
||||
and do not provide observation; absence of an event does not establish support.
|
||||
|
||||
The current Unix runner observes native Codex's managed `CODEX_HOME/auth.json`
|
||||
and the Codex/Grok ACPX session homes. It uses a non-recursive directory watch
|
||||
plus a one-second polling fallback, so atomic file replacement is handled.
|
||||
Grok's initial inline subscription credential is the baseline, allowing a
|
||||
refresh during launcher startup to be detected. A first valid credential file
|
||||
without a prior baseline establishes the baseline without claiming a refresh.
|
||||
Account identity changes also emit updates, even when token values stay the
|
||||
same, and establish the baseline for later refreshes on the new account.
|
||||
Hosts must evaluate the current credential through their private credential
|
||||
channel and account checks; the event does not authorize an account switch.
|
||||
Metadata-only changes, partial writes, and deletion do not emit updates.
|
||||
Unsupported harnesses and refreshes retained only in memory need
|
||||
their own observer or native-hook integration; adding this event does not make
|
||||
them observable.
|
||||
|
||||
`bindingId: "harness-auth"` identifies the selected harness authentication
|
||||
within the envelope's normalized session. Revisions increase for that binding
|
||||
and survive runner restarts and warm run attachments. The baseline fingerprint
|
||||
and pending event are persisted together in a private runner state file. Source
|
||||
retries retain the same event identity until the durable PRP outbox accepts it.
|
||||
Hosts should commit an idempotent reaction or durable work item through
|
||||
`onCommittedEvent` before returning and advancing the cumulative ACK.
|
||||
The bundled transport exposes `onCredentialsUpdated(event)` for this commit.
|
||||
It awaits the callback before ACK, including during warm idle, attachment, and
|
||||
provider cleanup. Callback failures leave delivery unacknowledged for retry;
|
||||
callbacks must therefore deduplicate by the original source event identity.
|
||||
When configured, credential updates bypass the turn notification queue.
|
||||
Paperclip commits them directly to the run log in a separate credential source
|
||||
namespace, preserving the original PRP envelope and avoiding collisions with
|
||||
the driver's normalized event sequence. A turn-only notification consumer
|
||||
cannot reliably handle idle or cleanup updates; use this callback instead.
|
||||
|
||||
`detection: "credential_store"` reports an observed credential change, not proof
|
||||
that an OAuth refresh succeeded. Multiple changes between observations can be
|
||||
coalesced; this is not an audit of every refresh exchange. The schema also
|
||||
allows `native_hook` for integrations with an explicit signal. Observation
|
||||
continues during warm idle and checks at turn terminal and close boundaries,
|
||||
including Grok's private refresh handoff after live-store cleanup. Retained
|
||||
runner observations enter the durable outbox before a suspend or shutdown
|
||||
command completes, without draining the provider backlog. A final check after
|
||||
provider cleanup also enters the outbox and waits for the host ACK. The runner
|
||||
retains its terminal recovery fence if that delivery fails.
|
||||
|
||||
The event authorizes no credential access or write on its own. A host that
|
||||
needs rotated token values must use a separately authorized handoff with its
|
||||
existing account-identity and freshness safeguards. The default Paperclip
|
||||
credential copy-back behavior remains in place.
|
||||
|
||||
## Scope
|
||||
|
||||
The first provider descriptor and adapter fixture cover Codex only. The schemas
|
||||
|
||||
@@ -7,6 +7,11 @@
|
||||
"protocol/fixtures"
|
||||
],
|
||||
"schemas": [
|
||||
{
|
||||
"path": "schemas/auth-credentials.schema.json",
|
||||
"id": "https://paperclip.dev/schemas/prp/v1/auth-credentials.schema.json",
|
||||
"sha256": "b31c8dc400eb50ef1f81f7acf2c73d2412f6c92dc408c3ee04bf346501a9b680"
|
||||
},
|
||||
{
|
||||
"path": "schemas/capabilities-v2.schema.json",
|
||||
"id": "https://paperclip.dev/schemas/prp/v2/capabilities.schema.json",
|
||||
@@ -50,17 +55,17 @@
|
||||
{
|
||||
"path": "schemas/event-v2.schema.json",
|
||||
"id": "https://paperclip.dev/schemas/prp/v2/event.schema.json",
|
||||
"sha256": "9dcf149bdb8e10041ca2212037231e7ceff11be08a0b8ee5dbd0f21974daa294"
|
||||
"sha256": "f9e1f36e08aafe8c28218cb3b032423be4d59d3720e26d10dcfb45bc624cdb48"
|
||||
},
|
||||
{
|
||||
"path": "schemas/event-v3.schema.json",
|
||||
"id": "https://paperclip.dev/schemas/prp/v3/event.schema.json",
|
||||
"sha256": "d308f826097b5b923e6ab2a4893bc125aa9e3cc14a306eef152400093db7b5f3"
|
||||
"sha256": "a2d1969a7636108a1d4759cd5af4d554a155f3e147099d67c955ee0da5948ddf"
|
||||
},
|
||||
{
|
||||
"path": "schemas/event.schema.json",
|
||||
"id": "https://paperclip.dev/schemas/prp/v1/event.schema.json",
|
||||
"sha256": "d48916630976ff7e850b6e2d7d94131761fda322f5d8a05212651ec46b0db19d"
|
||||
"sha256": "a21661fbb7094fb36df235031bddac582785f368981912cf23e86af3d6f9d57f"
|
||||
},
|
||||
{
|
||||
"path": "schemas/fixture.schema.json",
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://paperclip.dev/schemas/prp/v1/auth-credentials.schema.json",
|
||||
"title": "PRP credential update notification",
|
||||
"description": "Content-free evidence of changed credentials for the harness-auth binding in this normalized session. Credential-store detection does not prove an OAuth refresh succeeded.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schema",
|
||||
"provider",
|
||||
"bindingId",
|
||||
"revision",
|
||||
"detection"
|
||||
],
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "paperclip.auth.credentials.updated.v1"
|
||||
},
|
||||
"provider": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 160,
|
||||
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
|
||||
},
|
||||
"bindingId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 160,
|
||||
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
|
||||
},
|
||||
"revision": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"detection": {
|
||||
"enum": [
|
||||
"credential_store",
|
||||
"native_hook"
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -21,6 +21,7 @@
|
||||
"enum": [
|
||||
"runner.connected", "runner.reconnected", "runner.reconciled", "runner.disconnected", "runner.draining", "runner.suspending", "runner.suspended", "runner.stopped", "runner.diagnostic",
|
||||
"runtime.phase.changed", "sandbox.metric", "workspace.ready", "workspace.change.updated", "workspace.diff.recorded", "workspace.file.referenced",
|
||||
"auth.credentials.updated",
|
||||
"harness.starting", "harness.ready", "harness.exited", "harness.diagnostic", "plan.updated",
|
||||
"tool.execution.started", "tool.execution.progressed", "tool.execution.completed", "research.started", "research.progressed", "research.completed",
|
||||
"delegation.started", "delegation.updated", "delegation.completed", "model.route.changed", "model.verification.updated", "context.compacted",
|
||||
@@ -46,6 +47,7 @@
|
||||
"debug": { "type": "object", "additionalProperties": true }
|
||||
},
|
||||
"allOf": [
|
||||
{ "if": { "properties": { "eventType": { "const": "auth.credentials.updated" } } }, "then": { "properties": { "sourceKind": { "const": "runner" }, "priority": { "const": 0 }, "payload": { "$ref": "https://paperclip.dev/schemas/prp/v1/auth-credentials.schema.json" } } } },
|
||||
{
|
||||
"if": { "properties": { "eventType": { "enum": ["session.goal.snapshot", "session.goal.updated"] } } },
|
||||
"then": {
|
||||
|
||||
@@ -171,7 +171,8 @@
|
||||
"issue.status.decision.superseded",
|
||||
"run.terminal",
|
||||
"external_provider.dispatch_requested",
|
||||
"external_provider.operation_settled"
|
||||
"external_provider.operation_settled",
|
||||
"auth.credentials.updated"
|
||||
]
|
||||
},
|
||||
"schemaVersion": {
|
||||
@@ -566,6 +567,28 @@
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"eventType": {
|
||||
"const": "auth.credentials.updated"
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"sourceKind": {
|
||||
"const": "runner"
|
||||
},
|
||||
"priority": {
|
||||
"const": 0
|
||||
},
|
||||
"payload": {
|
||||
"$ref": "https://paperclip.dev/schemas/prp/v1/auth-credentials.schema.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"additionalProperties": true
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
"enum": [
|
||||
"runner.connected", "runner.reconnected", "runner.reconciled", "runner.disconnected", "runner.draining", "runner.backpressure", "runner.suspending", "runner.suspended", "runner.stopped", "runner.diagnostic",
|
||||
"runtime.phase.changed", "sandbox.metric", "workspace.ready", "workspace.change.updated", "workspace.diff.recorded", "workspace.file.referenced",
|
||||
"auth.credentials.updated",
|
||||
"harness.starting", "harness.ready", "harness.exited", "harness.diagnostic",
|
||||
"plan.updated",
|
||||
"tool.execution.started", "tool.execution.progressed", "tool.execution.completed",
|
||||
@@ -69,6 +70,7 @@
|
||||
"debug": { "type": "object", "additionalProperties": true }
|
||||
},
|
||||
"allOf": [
|
||||
{ "if": { "properties": { "eventType": { "const": "auth.credentials.updated" } } }, "then": { "properties": { "sourceKind": { "const": "runner" }, "priority": { "const": 0 }, "payload": { "$ref": "https://paperclip.dev/schemas/prp/v1/auth-credentials.schema.json" } } } },
|
||||
{ "if": { "properties": { "eventType": { "const": "plan.updated" } } }, "then": { "properties": { "payload": { "$ref": "https://paperclip.dev/schemas/prp/v1/provider-event.schema.json#/$defs/plan" } } } },
|
||||
{ "if": { "properties": { "eventType": { "enum": ["tool.execution.started", "tool.execution.progressed", "tool.execution.completed"] } } }, "then": { "properties": { "payload": { "$ref": "https://paperclip.dev/schemas/prp/v1/provider-event.schema.json#/$defs/toolExecution" } } } },
|
||||
{ "if": { "properties": { "eventType": { "enum": ["research.started", "research.progressed", "research.completed"] } } }, "then": { "properties": { "payload": { "$ref": "https://paperclip.dev/schemas/prp/v1/provider-event.schema.json#/$defs/research" } } } },
|
||||
|
||||
+189
-9
@@ -1021,6 +1021,15 @@ version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
|
||||
|
||||
[[package]]
|
||||
name = "fsevent-sys"
|
||||
version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-channel"
|
||||
version = "0.3.34"
|
||||
@@ -1448,6 +1457,26 @@ dependencies = [
|
||||
"hashbrown",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inotify"
|
||||
version = "0.11.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"inotify-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inotify-sys"
|
||||
version = "0.1.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
@@ -1542,6 +1571,26 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kqueue"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea"
|
||||
dependencies = [
|
||||
"kqueue-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kqueue-sys"
|
||||
version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.189"
|
||||
@@ -1619,10 +1668,38 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"wasi",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "notify"
|
||||
version = "8.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"fsevent-sys",
|
||||
"inotify",
|
||||
"kqueue",
|
||||
"libc",
|
||||
"log",
|
||||
"mio",
|
||||
"notify-types",
|
||||
"walkdir",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "notify-types"
|
||||
version = "2.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num"
|
||||
version = "0.4.3"
|
||||
@@ -1758,6 +1835,7 @@ dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"hmac 0.12.1",
|
||||
"jsonschema",
|
||||
"notify",
|
||||
"num-bigint",
|
||||
"num-traits",
|
||||
"reqwest",
|
||||
@@ -2279,6 +2357,15 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
|
||||
dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schannel"
|
||||
version = "0.1.29"
|
||||
@@ -2901,6 +2988,16 @@ version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64"
|
||||
|
||||
[[package]]
|
||||
name = "walkdir"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
|
||||
dependencies = [
|
||||
"same-file",
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "want"
|
||||
version = "0.3.1"
|
||||
@@ -3009,6 +3106,15 @@ dependencies = [
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi-util"
|
||||
version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
@@ -3021,7 +3127,16 @@ version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
|
||||
dependencies = [
|
||||
"windows-targets",
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
|
||||
dependencies = [
|
||||
"windows-targets 0.53.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3039,14 +3154,31 @@ version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm",
|
||||
"windows_aarch64_msvc",
|
||||
"windows_i686_gnu",
|
||||
"windows_i686_gnullvm",
|
||||
"windows_i686_msvc",
|
||||
"windows_x86_64_gnu",
|
||||
"windows_x86_64_gnullvm",
|
||||
"windows_x86_64_msvc",
|
||||
"windows_aarch64_gnullvm 0.52.6",
|
||||
"windows_aarch64_msvc 0.52.6",
|
||||
"windows_i686_gnu 0.52.6",
|
||||
"windows_i686_gnullvm 0.52.6",
|
||||
"windows_i686_msvc 0.52.6",
|
||||
"windows_x86_64_gnu 0.52.6",
|
||||
"windows_x86_64_gnullvm 0.52.6",
|
||||
"windows_x86_64_msvc 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.53.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
"windows_aarch64_gnullvm 0.53.1",
|
||||
"windows_aarch64_msvc 0.53.1",
|
||||
"windows_i686_gnu 0.53.1",
|
||||
"windows_i686_gnullvm 0.53.1",
|
||||
"windows_i686_msvc 0.53.1",
|
||||
"windows_x86_64_gnu 0.53.1",
|
||||
"windows_x86_64_gnullvm 0.53.1",
|
||||
"windows_x86_64_msvc 0.53.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3055,48 +3187,96 @@ version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnullvm"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "0.7.15"
|
||||
|
||||
@@ -22,6 +22,7 @@ hmac = "0.12"
|
||||
jsonschema = { version = "0.50", default-features = false }
|
||||
num-bigint = "0.4"
|
||||
num-traits = "0.2"
|
||||
notify = "8.2"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
sha2 = "0.10"
|
||||
|
||||
@@ -19,6 +19,7 @@ hmac.workspace = true
|
||||
jsonschema.workspace = true
|
||||
num-bigint.workspace = true
|
||||
num-traits.workspace = true
|
||||
notify.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
|
||||
@@ -2378,7 +2378,7 @@ fn replacement_continuity_payload(
|
||||
})
|
||||
}
|
||||
|
||||
fn secure_directory(path: &Path, label: &str) -> Result<(), DurableRunnerError> {
|
||||
pub(crate) fn secure_directory(path: &Path, label: &str) -> Result<(), DurableRunnerError> {
|
||||
let mut builder = DirBuilder::new();
|
||||
#[cfg(unix)]
|
||||
builder.mode(0o700);
|
||||
|
||||
@@ -0,0 +1,740 @@
|
||||
use std::fs::{self, File};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::durable::{
|
||||
create_private_temporary_file, open_private_regular_file, verify_private_directory,
|
||||
DurableRunnerError, EventPriority, PolledEvent,
|
||||
};
|
||||
|
||||
const STATE_FILE: &str = "credential-observer-state.json";
|
||||
const SCHEMA: &str = "paperclip.runner.credential-observer.v1";
|
||||
const MAX_BYTES: u64 = 256 * 1024;
|
||||
const MAX_REVISION: u64 = 9_007_199_254_740_991;
|
||||
const SCAN_INTERVAL: Duration = Duration::from_secs(1);
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Snapshot {
|
||||
identity: String,
|
||||
fingerprint: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct State {
|
||||
schema: String,
|
||||
session_id: String,
|
||||
provider: String,
|
||||
path: PathBuf,
|
||||
snapshot: Option<Snapshot>,
|
||||
revision: u64,
|
||||
armed: bool,
|
||||
pending: Option<PolledEvent>,
|
||||
}
|
||||
|
||||
pub(crate) struct CredentialObserver {
|
||||
state_path: PathBuf,
|
||||
session_id: String,
|
||||
state: Option<State>,
|
||||
loaded: bool,
|
||||
watcher: Option<RecommendedWatcher>,
|
||||
dirty: Arc<AtomicBool>,
|
||||
last_scan: Instant,
|
||||
}
|
||||
|
||||
impl CredentialObserver {
|
||||
pub(crate) fn new(state_dir: &Path, session_id: &str) -> Self {
|
||||
Self {
|
||||
state_path: state_dir.join(STATE_FILE),
|
||||
session_id: session_id.to_owned(),
|
||||
state: None,
|
||||
loaded: false,
|
||||
watcher: None,
|
||||
dirty: Arc::new(AtomicBool::new(true)),
|
||||
last_scan: Instant::now() - SCAN_INTERVAL,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn restore(&mut self) -> Result<(), DurableRunnerError> {
|
||||
if self.loaded {
|
||||
return Ok(());
|
||||
}
|
||||
let file = match open_private_regular_file(&self.state_path) {
|
||||
Ok(file) => file,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
self.loaded = true;
|
||||
return Ok(());
|
||||
}
|
||||
Err(_) => return Err(observer_error("state is unavailable")),
|
||||
};
|
||||
if file
|
||||
.metadata()
|
||||
.map_err(|_| observer_error("state is unavailable"))?
|
||||
.len()
|
||||
> MAX_BYTES
|
||||
{
|
||||
return Err(observer_error("state exceeds its bound"));
|
||||
}
|
||||
let state: State = serde_json::from_reader(file.take(MAX_BYTES + 1))
|
||||
.map_err(|_| observer_error("state is malformed"))?;
|
||||
let valid_digest =
|
||||
|value: &str| value.len() == 64 && value.bytes().all(|b| b.is_ascii_hexdigit());
|
||||
if state.schema != SCHEMA
|
||||
|| state.session_id != self.session_id
|
||||
|| !matches!(state.provider.as_str(), "codex" | "grok")
|
||||
|| !state.path.is_absolute()
|
||||
|| state
|
||||
.path
|
||||
.file_name()
|
||||
.is_none_or(|name| name != "auth.json")
|
||||
|| state.revision > MAX_REVISION
|
||||
|| state
|
||||
.snapshot
|
||||
.as_ref()
|
||||
.is_some_and(|s| !valid_digest(&s.identity) || !valid_digest(&s.fingerprint))
|
||||
|| state.pending.as_ref().is_some_and(|event| {
|
||||
event != &update_event(&state.provider, state.revision) || state.revision == 0
|
||||
})
|
||||
{
|
||||
return Err(observer_error("state has an invalid session binding"));
|
||||
}
|
||||
self.state = Some(state);
|
||||
self.loaded = true;
|
||||
self.watch_directory();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn configure(&mut self, payload: &Value) -> Result<(), DurableRunnerError> {
|
||||
self.restore()?;
|
||||
if self.state.is_some() || payload.get("observeCredentials") != Some(&Value::Bool(true)) {
|
||||
return Ok(());
|
||||
}
|
||||
let provider = &payload["provider"];
|
||||
let kind = provider
|
||||
.get("kind")
|
||||
.or_else(|| provider.get("provider"))
|
||||
.and_then(Value::as_str);
|
||||
let (name, path, seed) = match kind {
|
||||
Some("codex") => {
|
||||
let Some(home) = std::env::var_os("CODEX_HOME") else {
|
||||
return Ok(());
|
||||
};
|
||||
let home = PathBuf::from(home);
|
||||
if !home.is_absolute() {
|
||||
return Err(observer_error("credential home is not absolute"));
|
||||
}
|
||||
let home = fs::canonicalize(home)
|
||||
.map_err(|_| observer_error("credential home is unavailable"))?;
|
||||
("codex", home.join("auth.json"), None)
|
||||
}
|
||||
Some("acpx") if provider["agent"] == "grok" || provider["agent"] == "codex" => {
|
||||
let Some(root) = provider["runtimeDirectory"].as_str() else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(session) = provider["normalizedSessionId"].as_str() else {
|
||||
return Ok(());
|
||||
};
|
||||
if session != self.session_id {
|
||||
return Err(observer_error("descriptor session mismatch"));
|
||||
}
|
||||
let name = provider["agent"].as_str().expect("matched agent");
|
||||
crate::acpx_provider_backend::secure_directory(Path::new(root), "ACPX runtime")
|
||||
.map_err(|_| observer_error("runtime home is unavailable"))?;
|
||||
let root = fs::canonicalize(root)
|
||||
.map_err(|_| observer_error("runtime home is unavailable"))?;
|
||||
let path = root
|
||||
.join("acpx")
|
||||
.join(acpx_session_directory(session))
|
||||
.join(format!("{name}-home"))
|
||||
.join("auth.json");
|
||||
let seed = if name == "grok" {
|
||||
std::env::var("PAPERCLIP_ACPX_GROK_AUTH_JSON_SECRET").ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(name, path, seed)
|
||||
}
|
||||
_ => return Ok(()),
|
||||
};
|
||||
if !path.is_absolute() {
|
||||
return Err(observer_error("credential home is not absolute"));
|
||||
}
|
||||
let mut seed = seed.map(String::into_bytes);
|
||||
let snapshot = seed
|
||||
.as_ref()
|
||||
.and_then(|bytes| parse_snapshot(name, bytes))
|
||||
.or_else(|| read_snapshot(name, &path));
|
||||
if let Some(bytes) = seed.as_mut() {
|
||||
bytes.fill(0);
|
||||
}
|
||||
let state = State {
|
||||
schema: SCHEMA.to_owned(),
|
||||
session_id: self.session_id.clone(),
|
||||
provider: name.to_owned(),
|
||||
path,
|
||||
snapshot,
|
||||
revision: 0,
|
||||
armed: false,
|
||||
pending: None,
|
||||
};
|
||||
self.save(&state)?;
|
||||
self.state = Some(state);
|
||||
self.watch_directory();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn watch_directory(&mut self) {
|
||||
if self.watcher.is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(parent) = self.state.as_ref().and_then(|s| s.path.parent()) else {
|
||||
return;
|
||||
};
|
||||
let dirty = Arc::clone(&self.dirty);
|
||||
if let Ok(mut watcher) = notify::recommended_watcher(move |_| {
|
||||
dirty.store(true, Ordering::Relaxed);
|
||||
}) {
|
||||
if watcher.watch(parent, RecursiveMode::NonRecursive).is_ok() {
|
||||
self.watcher = Some(watcher);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn poll(&mut self, force: bool) -> Result<(), DurableRunnerError> {
|
||||
self.restore()?;
|
||||
if self
|
||||
.state
|
||||
.as_ref()
|
||||
.is_none_or(|state| !state.armed || state.pending.is_some())
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if !force
|
||||
&& !self.dirty.swap(false, Ordering::Relaxed)
|
||||
&& self.last_scan.elapsed() < SCAN_INTERVAL
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
self.last_scan = Instant::now();
|
||||
self.watch_directory();
|
||||
let state = self.state.as_ref().expect("configured observer");
|
||||
let snapshot = read_snapshot(&state.provider, &state.path).or_else(|| {
|
||||
(state.provider == "grok"
|
||||
&& fs::symlink_metadata(&state.path)
|
||||
.is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound))
|
||||
.then(|| read_snapshot("grok", &state.path.with_file_name("auth-refresh.json")))
|
||||
.flatten()
|
||||
});
|
||||
let Some(snapshot) = snapshot else {
|
||||
return Ok(());
|
||||
};
|
||||
if state.snapshot.as_ref() == Some(&snapshot) {
|
||||
return Ok(());
|
||||
}
|
||||
let mut next = state.clone();
|
||||
if next.snapshot.is_some() {
|
||||
next.revision = next
|
||||
.revision
|
||||
.checked_add(1)
|
||||
.filter(|n| *n <= MAX_REVISION)
|
||||
.ok_or_else(|| observer_error("revision exhausted"))?;
|
||||
next.pending = Some(update_event(&next.provider, next.revision));
|
||||
}
|
||||
next.snapshot = Some(snapshot);
|
||||
self.save(&next)?;
|
||||
self.state = Some(next);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn pending(&self) -> Option<PolledEvent> {
|
||||
self.state.as_ref().and_then(|state| state.pending.clone())
|
||||
}
|
||||
|
||||
pub(crate) fn activate(&mut self) -> Result<(), DurableRunnerError> {
|
||||
if let Some(state) = self.state.as_ref().filter(|state| !state.armed) {
|
||||
let mut next = state.clone();
|
||||
next.armed = true;
|
||||
self.save(&next)?;
|
||||
self.state = Some(next);
|
||||
}
|
||||
self.poll(true)
|
||||
}
|
||||
|
||||
pub(crate) fn acknowledge(&mut self, count: usize) -> Result<(), DurableRunnerError> {
|
||||
if count != 1 || self.pending().is_none() {
|
||||
return Err(observer_error("invalid event acknowledgement"));
|
||||
}
|
||||
let mut next = self.state.clone().expect("pending observer");
|
||||
next.pending = None;
|
||||
self.save(&next)?;
|
||||
self.state = Some(next);
|
||||
self.dirty.store(true, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save(&self, state: &State) -> Result<(), DurableRunnerError> {
|
||||
let parent = self.state_path.parent().expect("state directory");
|
||||
verify_private_directory(parent)?;
|
||||
let (temporary, mut file) = create_private_temporary_file(&self.state_path)?;
|
||||
let result = (|| -> std::io::Result<()> {
|
||||
file.write_all(&serde_json::to_vec(state)?)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
fs::rename(&temporary, &self.state_path)?;
|
||||
File::open(parent)?.sync_all()?;
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(temporary);
|
||||
}
|
||||
result.map_err(|_| observer_error("state could not be persisted"))
|
||||
}
|
||||
}
|
||||
|
||||
fn observer_error(message: &str) -> DurableRunnerError {
|
||||
DurableRunnerError::invalid(format!("credential observer {message}"))
|
||||
}
|
||||
|
||||
fn update_event(provider: &str, revision: u64) -> PolledEvent {
|
||||
PolledEvent {
|
||||
executor_event_id: format!("credential_update_{revision:016}"),
|
||||
event_type: "auth.credentials.updated".to_owned(),
|
||||
priority: EventPriority::P0,
|
||||
payload: json!({ "schema": "paperclip.auth.credentials.updated.v1", "provider": provider,
|
||||
"bindingId": "harness-auth", "revision": revision, "detection": "credential_store" }),
|
||||
}
|
||||
}
|
||||
|
||||
fn acpx_session_directory(session: &str) -> String {
|
||||
let readable: String = session
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() || "._-".contains(c) {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let readable = if readable.chars().all(|c| c == '.') {
|
||||
"session"
|
||||
} else {
|
||||
&readable
|
||||
};
|
||||
let readable: String = readable.chars().take(80).collect();
|
||||
let suffix = format!("{:x}", Sha256::digest(session.as_bytes()));
|
||||
format!(
|
||||
"{}-{}",
|
||||
if readable.is_empty() {
|
||||
"session"
|
||||
} else {
|
||||
&readable
|
||||
},
|
||||
&suffix[..16]
|
||||
)
|
||||
}
|
||||
|
||||
fn parse_snapshot(provider: &str, bytes: &[u8]) -> Option<Snapshot> {
|
||||
if bytes.len() as u64 > MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
let value: Value = serde_json::from_slice(bytes).ok()?;
|
||||
let nonempty = |v: &Value| {
|
||||
v.as_str()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.map(str::to_owned)
|
||||
};
|
||||
let (identity, credentials) = match provider {
|
||||
"codex" => {
|
||||
let tokens = &value["tokens"];
|
||||
let account = nonempty(&tokens["account_id"])?;
|
||||
let access = nonempty(&tokens["access_token"])?;
|
||||
let refresh = nonempty(&tokens["refresh_token"])?;
|
||||
(account, json!([access, refresh, tokens.get("id_token")]))
|
||||
}
|
||||
"grok" => {
|
||||
let object = value.as_object()?;
|
||||
if object.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
let (identity, auth) = object.iter().next()?;
|
||||
let (issuer, account) = identity.rsplit_once("::")?;
|
||||
if issuer.is_empty() || uuid::Uuid::parse_str(account).is_err() {
|
||||
return None;
|
||||
}
|
||||
(
|
||||
identity.clone(),
|
||||
json!([nonempty(&auth["key"])?, nonempty(&auth["refresh_token"])?]),
|
||||
)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let mut fingerprint = Sha256::new();
|
||||
fingerprint.update(provider.as_bytes());
|
||||
fingerprint.update(serde_json::to_vec(&credentials).ok()?);
|
||||
Some(Snapshot {
|
||||
identity: format!("{:x}", Sha256::digest(identity.as_bytes())),
|
||||
fingerprint: format!("{:x}", fingerprint.finalize()),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn read_snapshot(provider: &str, path: &Path) -> Option<Snapshot> {
|
||||
use rustix::fs::{open, openat, Mode, OFlags};
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let parent = path.parent()?;
|
||||
if !parent.is_absolute() {
|
||||
return None;
|
||||
}
|
||||
let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
|
||||
let mut directory = open("/", flags, Mode::empty()).ok()?;
|
||||
for component in parent.components() {
|
||||
match component {
|
||||
Component::RootDir => {}
|
||||
Component::Normal(name) => {
|
||||
directory = openat(&directory, name, flags, Mode::empty()).ok()?;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
let owner = File::from(directory.try_clone().ok()?)
|
||||
.metadata()
|
||||
.ok()?
|
||||
.uid();
|
||||
let fd = openat(
|
||||
&directory,
|
||||
path.file_name()?,
|
||||
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
|
||||
Mode::empty(),
|
||||
)
|
||||
.ok()?;
|
||||
let mut file = File::from(fd);
|
||||
let before = file.metadata().ok()?;
|
||||
if !before.is_file()
|
||||
|| before.uid() != owner
|
||||
|| before.mode() & 0o777 != 0o600
|
||||
|| before.len() > MAX_BYTES
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
let read = (&mut file).take(MAX_BYTES + 1).read_to_end(&mut bytes);
|
||||
let after = file.metadata().ok();
|
||||
let stable = after.is_some_and(|after| {
|
||||
before.len() == after.len()
|
||||
&& before.mtime() == after.mtime()
|
||||
&& before.mtime_nsec() == after.mtime_nsec()
|
||||
});
|
||||
let snapshot = if read.is_ok() && stable {
|
||||
parse_snapshot(provider, &bytes)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
bytes.fill(0);
|
||||
snapshot
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn read_snapshot(_provider: &str, _path: &Path) -> Option<Snapshot> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::os::unix::fs::{symlink, PermissionsExt};
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
observer: CredentialObserver,
|
||||
}
|
||||
impl Fixture {
|
||||
fn new(provider: &str, seed: &Value) -> Self {
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("credential-observer-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir(&root).unwrap();
|
||||
fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let root = fs::canonicalize(root).unwrap();
|
||||
let mut observer = CredentialObserver::new(&root, "session");
|
||||
observer.loaded = true;
|
||||
observer.state = Some(State {
|
||||
schema: SCHEMA.to_owned(),
|
||||
session_id: "session".to_owned(),
|
||||
provider: provider.to_owned(),
|
||||
path: root.join("auth.json"),
|
||||
snapshot: parse_snapshot(provider, &serde_json::to_vec(seed).unwrap()),
|
||||
revision: 0,
|
||||
armed: false,
|
||||
pending: None,
|
||||
});
|
||||
observer.save(observer.state.as_ref().unwrap()).unwrap();
|
||||
Self { root, observer }
|
||||
}
|
||||
fn write(&self, name: &str, value: &Value) {
|
||||
let path = self.root.join(name);
|
||||
fs::write(&path, serde_json::to_vec(value).unwrap()).unwrap();
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
self.observer.watcher = None;
|
||||
let _ = fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
|
||||
fn codex(marker: &str) -> Value {
|
||||
json!({"tokens":{"account_id":"account-1", "access_token":format!("access-{marker}"),
|
||||
"refresh_token":format!("refresh-{marker}"), "id_token":format!("identity-{marker}")}, "last_refresh":"metadata"})
|
||||
}
|
||||
fn grok(marker: &str) -> Value {
|
||||
json!({"https://issuer.example::12345678-1234-1234-1234-123456789abc":{
|
||||
"key":format!("access-{marker}"), "refresh_token":format!("refresh-{marker}"), "expires_at":1234}})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_is_durable_replayable_content_free_and_monotonic() {
|
||||
let mut f = Fixture::new("codex", &codex("before"));
|
||||
f.write("auth.json", &codex("before"));
|
||||
f.observer.activate().unwrap();
|
||||
assert!(f.observer.pending().is_none());
|
||||
f.write("auth.json", &codex("after"));
|
||||
f.observer.poll(true).unwrap();
|
||||
let event = f.observer.pending().unwrap();
|
||||
assert_eq!(event, update_event("codex", 1));
|
||||
let persisted = fs::read_to_string(f.root.join(STATE_FILE)).unwrap();
|
||||
for secret in [
|
||||
"access-before",
|
||||
"refresh-before",
|
||||
"identity-before",
|
||||
"access-after",
|
||||
"refresh-after",
|
||||
"identity-after",
|
||||
] {
|
||||
assert!(!persisted.contains(secret));
|
||||
assert!(!event.payload.to_string().contains(secret));
|
||||
}
|
||||
let mut recovered = CredentialObserver::new(&f.root, "session");
|
||||
recovered.restore().unwrap();
|
||||
assert_eq!(recovered.pending(), Some(event));
|
||||
f.write("auth.json", &codex("newest"));
|
||||
recovered.poll(true).unwrap();
|
||||
assert_eq!(recovered.pending(), Some(update_event("codex", 1)));
|
||||
recovered.acknowledge(1).unwrap();
|
||||
recovered.poll(true).unwrap();
|
||||
assert_eq!(recovered.pending(), Some(update_event("codex", 2)));
|
||||
recovered.acknowledge(1).unwrap();
|
||||
recovered.poll(true).unwrap();
|
||||
assert!(recovered.pending().is_none());
|
||||
assert_eq!(recovered.state.as_ref().unwrap().revision, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_watch_handles_atomic_replacement() {
|
||||
let mut f = Fixture::new("codex", &codex("before"));
|
||||
f.write("auth.json", &codex("before"));
|
||||
f.observer.activate().unwrap();
|
||||
f.observer.dirty.store(false, Ordering::Relaxed);
|
||||
f.write("auth.tmp", &codex("after"));
|
||||
fs::rename(f.root.join("auth.tmp"), f.root.join("auth.json")).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
while f.observer.pending().is_none() && Instant::now() < deadline {
|
||||
f.observer.poll(false).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
assert_eq!(f.observer.pending(), Some(update_event("codex", 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn periodic_reread_works_without_native_notifications() {
|
||||
let mut f = Fixture::new("codex", &codex("before"));
|
||||
f.write("auth.json", &codex("before"));
|
||||
f.observer.activate().unwrap();
|
||||
f.write("auth.json", &codex("after"));
|
||||
f.observer.watcher = None;
|
||||
f.observer.dirty.store(false, Ordering::Relaxed);
|
||||
f.observer.last_scan = Instant::now() - SCAN_INTERVAL;
|
||||
f.observer.poll(false).unwrap();
|
||||
assert_eq!(f.observer.pending(), Some(update_event("codex", 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_metadata_partial_writes_and_deletion() {
|
||||
let mut f = Fixture::new("codex", &codex("before"));
|
||||
f.write("auth.json", &codex("before"));
|
||||
f.observer.activate().unwrap();
|
||||
let mut metadata = codex("before");
|
||||
metadata["last_refresh"] = json!("new metadata");
|
||||
f.write("auth.json", &metadata);
|
||||
f.observer.poll(true).unwrap();
|
||||
assert!(f.observer.pending().is_none());
|
||||
fs::write(f.root.join("auth.json"), "{partial").unwrap();
|
||||
f.observer.poll(true).unwrap();
|
||||
assert!(f.observer.pending().is_none());
|
||||
fs::remove_file(f.root.join("auth.json")).unwrap();
|
||||
f.observer.poll(true).unwrap();
|
||||
f.write("auth.json", &codex("after"));
|
||||
f.observer.poll(true).unwrap();
|
||||
assert_eq!(f.observer.pending(), Some(update_event("codex", 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_changes_and_later_refreshes_survive_recovery_without_exposing_identity() {
|
||||
for provider in ["codex", "grok"] {
|
||||
let original = if provider == "codex" {
|
||||
codex("before")
|
||||
} else {
|
||||
grok("before")
|
||||
};
|
||||
let mut f = Fixture::new(provider, &original);
|
||||
f.write("auth.json", &original);
|
||||
f.observer.activate().unwrap();
|
||||
let mut changed = original.clone();
|
||||
let account = if provider == "codex" {
|
||||
changed["tokens"]["account_id"] = json!("different-account");
|
||||
"different-account"
|
||||
} else {
|
||||
let auth = changed
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.values()
|
||||
.next()
|
||||
.unwrap()
|
||||
.clone();
|
||||
changed =
|
||||
json!({"https://issuer.example::87654321-4321-4321-4321-cba987654321": auth});
|
||||
"87654321-4321-4321-4321-cba987654321"
|
||||
};
|
||||
f.write("auth.json", &changed);
|
||||
f.observer.poll(true).unwrap();
|
||||
assert_eq!(f.observer.pending(), Some(update_event(provider, 1)));
|
||||
let persisted = fs::read_to_string(f.root.join(STATE_FILE)).unwrap();
|
||||
assert!(!persisted.contains(account));
|
||||
assert!(!f
|
||||
.observer
|
||||
.pending()
|
||||
.unwrap()
|
||||
.payload
|
||||
.to_string()
|
||||
.contains(account));
|
||||
let mut recovered = CredentialObserver::new(&f.root, "session");
|
||||
recovered.restore().unwrap();
|
||||
assert_eq!(recovered.pending(), Some(update_event(provider, 1)));
|
||||
if provider == "codex" {
|
||||
changed["tokens"]["access_token"] = json!("refreshed-access");
|
||||
} else {
|
||||
changed
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.values_mut()
|
||||
.next()
|
||||
.unwrap()["key"] = json!("refreshed-access");
|
||||
}
|
||||
f.write("auth.json", &changed);
|
||||
recovered.poll(true).unwrap();
|
||||
assert_eq!(recovered.pending(), Some(update_event(provider, 1)));
|
||||
recovered.acknowledge(1).unwrap();
|
||||
recovered.poll(true).unwrap();
|
||||
assert_eq!(recovered.pending(), Some(update_event(provider, 2)));
|
||||
recovered.acknowledge(1).unwrap();
|
||||
recovered.poll(true).unwrap();
|
||||
assert!(recovered.pending().is_none());
|
||||
f.write("auth.json", &original);
|
||||
recovered.poll(true).unwrap();
|
||||
assert_eq!(recovered.pending(), Some(update_event(provider, 3)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grok_seed_catches_pre_start_refresh_and_close_handoff() {
|
||||
let mut f = Fixture::new("grok", &grok("seed"));
|
||||
f.observer.poll(true).unwrap();
|
||||
assert!(f.observer.pending().is_none());
|
||||
f.write("auth.json", &grok("startup"));
|
||||
f.observer.activate().unwrap();
|
||||
assert_eq!(f.observer.pending(), Some(update_event("grok", 1)));
|
||||
f.observer.acknowledge(1).unwrap();
|
||||
f.write("auth-refresh.json", &grok("close"));
|
||||
fs::remove_file(f.root.join("auth.json")).unwrap();
|
||||
f.observer.poll(true).unwrap();
|
||||
assert_eq!(f.observer.pending(), Some(update_event("grok", 2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_symlinks_unsafe_permissions_and_oversized_stores() {
|
||||
let f = Fixture::new("codex", &codex("seed"));
|
||||
f.write("auth.json", &codex("seed"));
|
||||
symlink(f.root.join("auth.json"), f.root.join("symlink.json")).unwrap();
|
||||
assert!(read_snapshot("codex", &f.root.join("symlink.json")).is_none());
|
||||
symlink(&f.root, f.root.join("parent-link")).unwrap();
|
||||
assert!(read_snapshot("codex", &f.root.join("parent-link/auth.json")).is_none());
|
||||
fs::set_permissions(f.root.join("auth.json"), fs::Permissions::from_mode(0o644)).unwrap();
|
||||
assert!(read_snapshot("codex", &f.root.join("auth.json")).is_none());
|
||||
fs::set_permissions(f.root.join("auth.json"), fs::Permissions::from_mode(0o600)).unwrap();
|
||||
fs::write(f.root.join("auth.json"), vec![b' '; MAX_BYTES as usize + 1]).unwrap();
|
||||
assert!(read_snapshot("codex", &f.root.join("auth.json")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observer_requires_opt_in_and_rejects_cross_session_recovery() {
|
||||
let f = Fixture::new("codex", &codex("seed"));
|
||||
let mut wrong_session = CredentialObserver::new(&f.root, "different-session");
|
||||
assert!(wrong_session.restore().is_err());
|
||||
let path = f.root.join("unused");
|
||||
fs::create_dir(&path).unwrap();
|
||||
let mut disabled = CredentialObserver::new(&path, "session");
|
||||
disabled
|
||||
.configure(&json!({"provider":{"kind":"codex"}}))
|
||||
.unwrap();
|
||||
assert!(disabled.state.is_none());
|
||||
disabled
|
||||
.configure(&json!({"observeCredentials":true,"provider":{"kind":"opencode"}}))
|
||||
.unwrap();
|
||||
assert!(disabled.state.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fresh_acpx_observers_create_a_private_runtime_directory() {
|
||||
let f = Fixture::new("codex", &codex("seed"));
|
||||
for provider in ["codex", "grok"] {
|
||||
let state_dir = f.root.join(provider);
|
||||
fs::create_dir(&state_dir).unwrap();
|
||||
fs::set_permissions(&state_dir, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let runtime = state_dir.join("runtime");
|
||||
assert!(!runtime.exists());
|
||||
let mut observer = CredentialObserver::new(&state_dir, "session");
|
||||
observer.configure(&json!({"observeCredentials":true,"provider":{
|
||||
"kind":"acpx", "agent":provider, "runtimeDirectory":runtime, "normalizedSessionId":"session"
|
||||
}})).unwrap();
|
||||
assert_eq!(
|
||||
fs::metadata(&runtime).unwrap().permissions().mode() & 0o777,
|
||||
0o700
|
||||
);
|
||||
assert_eq!(observer.state.as_ref().unwrap().provider, provider);
|
||||
assert!(observer.pending().is_none());
|
||||
observer.activate().unwrap();
|
||||
assert!(observer.pending().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acpx_directory_matches_the_typescript_session_layout() {
|
||||
assert_eq!(
|
||||
acpx_session_directory("session-1"),
|
||||
"session-1-84097828fc31a8c8"
|
||||
);
|
||||
let session = "...";
|
||||
assert!(acpx_session_directory(session).starts_with("session-"));
|
||||
}
|
||||
}
|
||||
@@ -267,6 +267,10 @@ pub trait CommandExecutor {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
fn retained_runner_events(&mut self) -> Result<Vec<PolledEvent>, DurableRunnerError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// Returns only already-retained evidence, without polling, restoration,
|
||||
/// launch, or provider RPCs. The runner commits and ACKs this FIFO before
|
||||
/// recording a command failure or completing an authority attachment.
|
||||
@@ -745,7 +749,21 @@ pub fn run_durable_runner<E: CommandExecutor>(
|
||||
.filter(|_| !disconnected)
|
||||
{
|
||||
debug_assert_eq!(state.lifecycle, durable_lifecycle);
|
||||
return finish_terminal_transition_after_ack(&mut state, &store, &mut executor);
|
||||
return finish_terminal_transition_after_ack(
|
||||
&mut state,
|
||||
&store,
|
||||
&config,
|
||||
&mut executor,
|
||||
|state| {
|
||||
wait_for_old_authority_outbox_ack(
|
||||
&mut transport,
|
||||
state,
|
||||
&store,
|
||||
&connection,
|
||||
&mut sent_source_seq,
|
||||
)
|
||||
},
|
||||
);
|
||||
}
|
||||
if disconnected {
|
||||
disconnected_since.get_or_insert_with(Instant::now);
|
||||
@@ -989,7 +1007,17 @@ pub fn run_durable_runner<E: CommandExecutor>(
|
||||
return finish_terminal_transition_after_ack(
|
||||
&mut state,
|
||||
&store,
|
||||
&config,
|
||||
&mut executor,
|
||||
|state| {
|
||||
wait_for_old_authority_outbox_ack(
|
||||
&mut transport,
|
||||
state,
|
||||
&store,
|
||||
&connection,
|
||||
&mut sent_source_seq,
|
||||
)
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1135,22 +1163,26 @@ fn complete_terminal_delivery_after_cleanup(
|
||||
fn finish_terminal_transition_after_ack<E: CommandExecutor>(
|
||||
state: &mut DurableState,
|
||||
store: &DurableStateStore,
|
||||
config: &DurableRunnerConfig,
|
||||
executor: &mut E,
|
||||
deliver: impl FnOnce(&mut DurableState) -> Result<(), DurableRunnerError>,
|
||||
) -> Result<(), DurableRunnerError> {
|
||||
// Keep the durable fence through provider cleanup. If cleanup fails, a
|
||||
// replacement may authenticate only to retry terminal reconciliation and
|
||||
// cannot restore the suspended runner to ready.
|
||||
if state.pending_provider_cleanup.is_some() {
|
||||
return finish_terminal_reconciliation(state, store, executor);
|
||||
return finish_terminal_reconciliation(state, store, config, executor, deliver);
|
||||
}
|
||||
executor.shutdown()?;
|
||||
complete_terminal_delivery_after_cleanup(state, store)
|
||||
finish_terminal_observations(state, store, config, executor, deliver)
|
||||
}
|
||||
|
||||
fn finish_terminal_reconciliation<E: CommandExecutor>(
|
||||
state: &mut DurableState,
|
||||
store: &DurableStateStore,
|
||||
config: &DurableRunnerConfig,
|
||||
executor: &mut E,
|
||||
deliver: impl FnOnce(&mut DurableState) -> Result<(), DurableRunnerError>,
|
||||
) -> Result<(), DurableRunnerError> {
|
||||
let outcome = executor.reconcile_terminal_delivery()?;
|
||||
if outcome == TerminalDeliveryReconciliation::ProviderCleanupPending
|
||||
@@ -1165,6 +1197,24 @@ fn finish_terminal_reconciliation<E: CommandExecutor>(
|
||||
}
|
||||
// Clearing delivery never clears a pre-existing physical cleanup fence.
|
||||
// Only a new successful turn.stop may do that.
|
||||
finish_terminal_observations(state, store, config, executor, deliver)
|
||||
}
|
||||
|
||||
fn finish_terminal_observations<E: CommandExecutor>(
|
||||
state: &mut DurableState,
|
||||
store: &DurableStateStore,
|
||||
config: &DurableRunnerConfig,
|
||||
executor: &mut E,
|
||||
deliver: impl FnOnce(&mut DurableState) -> Result<(), DurableRunnerError>,
|
||||
) -> Result<(), DurableRunnerError> {
|
||||
let events = executor.retained_runner_events()?;
|
||||
commit_executor_events(state, store, config, executor, events)?;
|
||||
deliver(state)?;
|
||||
if !state.outbox.is_empty() {
|
||||
return Err(DurableRunnerError::invalid(
|
||||
"terminal observations remain unacknowledged",
|
||||
));
|
||||
}
|
||||
complete_terminal_delivery_after_cleanup(state, store)
|
||||
}
|
||||
|
||||
@@ -1545,7 +1595,9 @@ fn reconcile_pending_terminal_delivery<E: CommandExecutor>(
|
||||
let _ = shutdown_preserving_cleanup(state, executor);
|
||||
return Err(error);
|
||||
}
|
||||
finish_terminal_reconciliation(state, store, executor)
|
||||
finish_terminal_reconciliation(state, store, config, executor, |state| {
|
||||
wait_for_old_authority_outbox_ack(transport, state, store, connection, &mut sent_source_seq)
|
||||
})
|
||||
}
|
||||
|
||||
fn stop_after_terminal_result_delivery_failure<E: CommandExecutor>(
|
||||
@@ -1793,6 +1845,13 @@ fn process_command<E: CommandExecutor>(
|
||||
return Ok((result, CommandLifecycle::for_terminal(command)));
|
||||
}
|
||||
};
|
||||
if matches!(
|
||||
command.command_type.as_str(),
|
||||
"runner.suspend" | "runner.shutdown"
|
||||
) {
|
||||
let events = executor.retained_runner_events()?;
|
||||
commit_executor_events(state, store, config, executor, events)?;
|
||||
}
|
||||
if command.command_type == "runner.drain" {
|
||||
// An explicit drain must make progress even while control traffic
|
||||
// prevents idle polling. Only move one already-retained prefix under
|
||||
@@ -2016,6 +2075,65 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_commands_commit_runner_events_without_draining_the_provider() {
|
||||
struct ObserverExecutor {
|
||||
pending: Vec<PolledEvent>,
|
||||
calls: usize,
|
||||
}
|
||||
impl CommandExecutor for ObserverExecutor {
|
||||
fn execute(&mut self, _: &Command) -> Result<CommandExecution, DurableRunnerError> {
|
||||
self.calls += 1;
|
||||
Ok(CommandExecution::result(json!({"status":"completed"})))
|
||||
}
|
||||
fn retained_runner_events(&mut self) -> Result<Vec<PolledEvent>, DurableRunnerError> {
|
||||
Ok(self.pending.clone())
|
||||
}
|
||||
fn retained_events(&mut self) -> Result<Vec<PolledEvent>, DurableRunnerError> {
|
||||
panic!("terminal command must preserve the provider backlog")
|
||||
}
|
||||
fn poll_events(&mut self) -> Result<Vec<PolledEvent>, DurableRunnerError> {
|
||||
panic!("terminal command must not poll or launch a provider")
|
||||
}
|
||||
fn acknowledge_events(&mut self, count: usize) -> Result<(), DurableRunnerError> {
|
||||
assert_eq!(count, 1);
|
||||
self.pending.clear();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
for kind in ["runner.suspend", "runner.shutdown"] {
|
||||
let directory = std::env::temp_dir()
|
||||
.join(format!("runner-observer-terminal-{}", uuid::Uuid::new_v4()));
|
||||
let config = config(directory.clone());
|
||||
let store = DurableStateStore::new(&directory).unwrap();
|
||||
let (mut state, _) = store.load_or_create(&config).unwrap();
|
||||
let mut executor = ObserverExecutor {
|
||||
pending: vec![PolledEvent {
|
||||
executor_event_id: "credential_update_0000000000000001".to_owned(),
|
||||
event_type: "auth.credentials.updated".to_owned(),
|
||||
priority: EventPriority::P0,
|
||||
payload: json!({"schema":"paperclip.auth.credentials.updated.v1", "provider":"codex",
|
||||
"bindingId":"harness-auth", "revision":1, "detection":"credential_store"}),
|
||||
}],
|
||||
calls: 0,
|
||||
};
|
||||
let command = command(kind);
|
||||
process_command(&mut state, &store, &config, &mut executor, &command).unwrap();
|
||||
assert!(executor.pending.is_empty());
|
||||
let (mut recovered, _) = store.load_or_create(&config).unwrap();
|
||||
assert_eq!(recovered.outbox.len(), 1);
|
||||
assert_eq!(recovered.outbox[0].event_type, "auth.credentials.updated");
|
||||
assert_eq!(
|
||||
recovered.processed_commands[&command.command_id].status,
|
||||
"completed"
|
||||
);
|
||||
process_command(&mut recovered, &store, &config, &mut executor, &command).unwrap();
|
||||
assert_eq!(executor.calls, 1);
|
||||
assert_eq!(recovered.outbox.len(), 1);
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_persistence_failure_with_blocked_drain_remains_indeterminate_on_replay() {
|
||||
struct PersistenceFailedResponseExecutor {
|
||||
@@ -2627,7 +2745,8 @@ mod tests {
|
||||
// Failed/expired terminal delivery cleanup must also remain cold.
|
||||
shutdown_preserving_cleanup(&state, &mut executor).unwrap();
|
||||
assert!(state.pending_terminal_delivery.is_some());
|
||||
finish_terminal_reconciliation(&mut state, &store, &mut executor).unwrap();
|
||||
finish_terminal_reconciliation(&mut state, &store, &config, &mut executor, |_| Ok(()))
|
||||
.unwrap();
|
||||
let (mut state, _) = store.load_or_create(&config).unwrap();
|
||||
assert!(state.pending_terminal_delivery.is_none());
|
||||
assert_eq!(
|
||||
@@ -3524,6 +3643,109 @@ mod tests {
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn final_shutdown_observations_keep_recovery_fenced_until_host_ack() {
|
||||
struct LateObserver {
|
||||
pending: Vec<PolledEvent>,
|
||||
observed: bool,
|
||||
}
|
||||
impl CommandExecutor for LateObserver {
|
||||
fn execute(&mut self, _: &Command) -> Result<CommandExecution, DurableRunnerError> {
|
||||
Ok(CommandExecution::result(json!({"status":"completed"})))
|
||||
}
|
||||
fn shutdown(&mut self) -> Result<(), DurableRunnerError> {
|
||||
if !self.observed {
|
||||
self.observed = true;
|
||||
self.pending.push(PolledEvent {
|
||||
executor_event_id: "final-credential-update".to_owned(),
|
||||
event_type: "auth.credentials.updated".to_owned(), priority: EventPriority::P0,
|
||||
payload: json!({"schema":"paperclip.auth.credentials.updated.v1", "provider":"codex",
|
||||
"bindingId":"harness-auth", "revision":1, "detection":"credential_store"}),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn retained_runner_events(&mut self) -> Result<Vec<PolledEvent>, DurableRunnerError> {
|
||||
Ok(self.pending.clone())
|
||||
}
|
||||
fn acknowledge_events(&mut self, count: usize) -> Result<(), DurableRunnerError> {
|
||||
assert_eq!(count, 1);
|
||||
self.pending.clear();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
for fail_delivery in [false, true] {
|
||||
let directory = std::env::temp_dir()
|
||||
.join(format!("runner-final-observation-{}", uuid::Uuid::new_v4()));
|
||||
let config = config(directory.clone());
|
||||
let store = DurableStateStore::new(&directory).unwrap();
|
||||
let (mut state, _) = store.load_or_create(&config).unwrap();
|
||||
let mut executor = LateObserver {
|
||||
pending: vec![],
|
||||
observed: false,
|
||||
};
|
||||
let terminal = command("runner.shutdown");
|
||||
let (result, lifecycle) =
|
||||
process_command(&mut state, &store, &config, &mut executor, &terminal).unwrap();
|
||||
persist_lifecycle_before_command_delivery(
|
||||
&mut state,
|
||||
&store,
|
||||
lifecycle.durable_state().unwrap(),
|
||||
&result,
|
||||
)
|
||||
.unwrap();
|
||||
let outcome = finish_terminal_transition_after_ack(
|
||||
&mut state,
|
||||
&store,
|
||||
&config,
|
||||
&mut executor,
|
||||
|state| {
|
||||
let (saved, _) = store.load_or_create(&config).unwrap();
|
||||
assert!(saved.pending_terminal_delivery.is_some());
|
||||
assert_eq!(saved.outbox.len(), 1);
|
||||
assert_eq!(saved.outbox[0].event_type, "auth.credentials.updated");
|
||||
if fail_delivery {
|
||||
return Err(DurableRunnerError::invalid("final host ACK lost"));
|
||||
}
|
||||
state.apply_ack(state.highest_source_seq(), 1)?;
|
||||
store.save(state)
|
||||
},
|
||||
);
|
||||
assert_eq!(outcome.is_err(), fail_delivery);
|
||||
assert!(executor.pending.is_empty());
|
||||
let (mut recovered, _) = store.load_or_create(&config).unwrap();
|
||||
assert_eq!(recovered.pending_terminal_delivery.is_some(), fail_delivery);
|
||||
if fail_delivery {
|
||||
let event_id = recovered.outbox[0].envelope["payload"]["sourceEventId"].clone();
|
||||
let mut replacement = LateObserver {
|
||||
pending: vec![],
|
||||
observed: true,
|
||||
};
|
||||
finish_terminal_reconciliation(
|
||||
&mut recovered,
|
||||
&store,
|
||||
&config,
|
||||
&mut replacement,
|
||||
|state| {
|
||||
assert_eq!(state.outbox.len(), 1);
|
||||
assert_eq!(
|
||||
state.outbox[0].envelope["payload"]["sourceEventId"],
|
||||
event_id
|
||||
);
|
||||
state.apply_ack(state.highest_source_seq(), 1)?;
|
||||
store.save(state)
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let (saved, _) = store.load_or_create(&config).unwrap();
|
||||
assert!(saved.pending_terminal_delivery.is_none());
|
||||
assert!(saved.outbox.is_empty());
|
||||
assert_eq!(saved.lifecycle, "stopped");
|
||||
}
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_terminal_cleanup_keeps_the_recovery_fence() {
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
@@ -3546,8 +3768,14 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let error = finish_terminal_transition_after_ack(&mut state, &store, &mut executor)
|
||||
.expect_err("cleanup failure remains fenced");
|
||||
let error = finish_terminal_transition_after_ack(
|
||||
&mut state,
|
||||
&store,
|
||||
&config,
|
||||
&mut executor,
|
||||
|_| Ok(()),
|
||||
)
|
||||
.expect_err("cleanup failure remains fenced");
|
||||
let (recovered, existed) = store.load_or_create(&config).unwrap();
|
||||
|
||||
assert!(error.to_string().contains("terminal cleanup failure"));
|
||||
|
||||
@@ -47,7 +47,7 @@ pub(crate) fn acpx_release_profile(agent: &str) -> Option<AcpxReleaseProfile> {
|
||||
agent_runtime_package: None,
|
||||
agent_runtime_version: None,
|
||||
command_digest:
|
||||
"sha256:2ec904f44218f51058fa83d7437b26c4551e1c65e6f2c55f5a6386fa4061e96d",
|
||||
"sha256:38abf359adeef43f1f19230245c6e2051c55fdd79571882ef6f00b7cb2958d93",
|
||||
requires_provider_policy: true,
|
||||
},
|
||||
"claude" => AcpxReleaseProfile {
|
||||
|
||||
@@ -13,6 +13,7 @@ pub mod claude_managed_provider;
|
||||
pub mod codex_provider;
|
||||
mod codex_startup_trust;
|
||||
mod configured_environment;
|
||||
mod credential_observer;
|
||||
pub mod dot_provider_backend;
|
||||
pub mod durable;
|
||||
pub mod fake_harness;
|
||||
|
||||
@@ -3,6 +3,7 @@ use std::path::PathBuf;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::acpx_provider_backend::{AcpxCommandExecutor, ACPX_PROVIDER_STATE_FILE};
|
||||
use crate::credential_observer::CredentialObserver;
|
||||
use crate::dot_provider_backend::{DotCommandExecutor, DOT_PROVIDER_STATE_FILE};
|
||||
use crate::durable::{
|
||||
Command, CommandExecution, CommandExecutor, DurableRunnerConfig, DurableRunnerError,
|
||||
@@ -112,19 +113,24 @@ pub struct NativeProviderCommandExecutor {
|
||||
config: DurableRunnerConfig,
|
||||
selected: Option<SelectedExecutor>,
|
||||
recovery_checked: bool,
|
||||
credentials: CredentialObserver,
|
||||
}
|
||||
|
||||
impl NativeProviderCommandExecutor {
|
||||
pub fn with_runner_config(state_dir: impl Into<PathBuf>, config: &DurableRunnerConfig) -> Self {
|
||||
let state_dir = state_dir.into();
|
||||
let credentials = CredentialObserver::new(&state_dir, &config.normalized_session_id);
|
||||
Self {
|
||||
state_dir: state_dir.into(),
|
||||
state_dir,
|
||||
config: config.clone(),
|
||||
selected: None,
|
||||
recovery_checked: false,
|
||||
credentials,
|
||||
}
|
||||
}
|
||||
|
||||
fn select_recovery(&mut self) -> Result<(), DurableRunnerError> {
|
||||
self.credentials.restore()?;
|
||||
if self.recovery_checked {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -207,10 +213,18 @@ impl CommandExecutor for NativeProviderCommandExecutor {
|
||||
}
|
||||
|
||||
fn retained_events(&mut self) -> Result<Vec<PolledEvent>, DurableRunnerError> {
|
||||
self.credentials.restore()?;
|
||||
if let Some(event) = self.credentials.pending() {
|
||||
return Ok(vec![event]);
|
||||
}
|
||||
self.selected
|
||||
.as_mut()
|
||||
.map_or_else(|| Ok(Vec::new()), CommandExecutor::retained_events)
|
||||
}
|
||||
fn retained_runner_events(&mut self) -> Result<Vec<PolledEvent>, DurableRunnerError> {
|
||||
self.credentials.restore()?;
|
||||
Ok(self.credentials.pending().into_iter().collect())
|
||||
}
|
||||
fn execute(&mut self, command: &Command) -> Result<CommandExecution, DurableRunnerError> {
|
||||
self.select_recovery()?;
|
||||
if self.selected.is_none()
|
||||
@@ -218,21 +232,63 @@ impl CommandExecutor for NativeProviderCommandExecutor {
|
||||
{
|
||||
self.select_from_payload(&command.payload)?;
|
||||
}
|
||||
self.selected
|
||||
if matches!(
|
||||
command.command_type.as_str(),
|
||||
"session.close"
|
||||
| "session.destroy"
|
||||
| "runner.suspend"
|
||||
| "runner.shutdown"
|
||||
| "turn.stop"
|
||||
| "run.cancel"
|
||||
) {
|
||||
self.credentials.poll(true)?;
|
||||
}
|
||||
let result = self
|
||||
.selected
|
||||
.as_mut()
|
||||
.ok_or_else(|| {
|
||||
DurableRunnerError::invalid(
|
||||
"run.prepare must select a provider before provider commands execute",
|
||||
)
|
||||
})?
|
||||
.execute(command)
|
||||
.execute(command);
|
||||
if result.is_ok() && matches!(command.command_type.as_str(), "run.prepare" | "run.attach") {
|
||||
self.credentials.configure(&command.payload)?;
|
||||
}
|
||||
if matches!(command.command_type.as_str(), "session.open" | "run.attach") {
|
||||
self.credentials.activate()?;
|
||||
}
|
||||
if !matches!(command.command_type.as_str(), "run.prepare") {
|
||||
self.credentials.poll(true)?;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn poll_events(&mut self) -> Result<Vec<PolledEvent>, DurableRunnerError> {
|
||||
self.select_recovery()?;
|
||||
self.selected
|
||||
self.credentials.poll(false)?;
|
||||
if let Some(event) = self.credentials.pending() {
|
||||
return Ok(vec![event]);
|
||||
}
|
||||
let events = self
|
||||
.selected
|
||||
.as_mut()
|
||||
.map_or_else(|| Ok(Vec::new()), CommandExecutor::poll_events)
|
||||
.map_or_else(|| Ok(Vec::new()), CommandExecutor::poll_events)?;
|
||||
let terminal = events.iter().any(|event| {
|
||||
matches!(
|
||||
event.event_type.as_str(),
|
||||
"turn.completed"
|
||||
| "turn.failed"
|
||||
| "turn.interrupted"
|
||||
| "turn.cancelled"
|
||||
| "harness.exited"
|
||||
)
|
||||
});
|
||||
self.credentials.poll(terminal)?;
|
||||
Ok(self
|
||||
.credentials
|
||||
.pending()
|
||||
.map_or(events, |event| vec![event]))
|
||||
}
|
||||
|
||||
fn maintain_backpressured_provider(&mut self) -> Result<(), DurableRunnerError> {
|
||||
@@ -252,6 +308,9 @@ impl CommandExecutor for NativeProviderCommandExecutor {
|
||||
|
||||
fn acknowledge_events(&mut self, count: usize) -> Result<(), DurableRunnerError> {
|
||||
self.select_recovery()?;
|
||||
if count > 0 && self.credentials.pending().is_some() {
|
||||
return self.credentials.acknowledge(count);
|
||||
}
|
||||
if let Some(executor) = self.selected.as_mut() {
|
||||
executor.acknowledge_events(count)
|
||||
} else if count == 0 {
|
||||
@@ -269,10 +328,12 @@ impl CommandExecutor for NativeProviderCommandExecutor {
|
||||
// Selection only loads the provider authority. The selected executor
|
||||
// decides whether terminal delivery can settle without a cold launch.
|
||||
self.select_recovery()?;
|
||||
self.selected.as_mut().map_or_else(
|
||||
let outcome = self.selected.as_mut().map_or_else(
|
||||
|| Ok(TerminalDeliveryReconciliation::CleanupCompleted),
|
||||
CommandExecutor::reconcile_terminal_delivery,
|
||||
)
|
||||
)?;
|
||||
self.credentials.poll(true)?;
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
fn shutdown(&mut self) -> Result<(), DurableRunnerError> {
|
||||
@@ -281,10 +342,11 @@ impl CommandExecutor for NativeProviderCommandExecutor {
|
||||
// provider authority before cleanup so an absent in-memory selection
|
||||
// can never turn the cleanup fence into a successful no-op.
|
||||
self.select_recovery()?;
|
||||
if let Some(executor) = self.selected.as_mut() {
|
||||
let cleanup = if let Some(executor) = self.selected.as_mut() {
|
||||
executor.shutdown()
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
cleanup.and(self.credentials.poll(true))
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,86 @@ fn temporary_directory(label: &str) -> PathBuf {
|
||||
directory
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn credential_observation_allows_fresh_acpx_session_startup() {
|
||||
let directory = temporary_directory("fresh-observed-acpx");
|
||||
let config = acpx_config(&directory, "turns-reserved-result-terminal");
|
||||
let mut prepare = prepare_payload(&directory, "codex");
|
||||
prepare["observeCredentials"] = json!(true);
|
||||
let runtime = directory.join("acpx-runtime");
|
||||
assert!(!runtime.exists());
|
||||
let mut executor = NativeProviderCommandExecutor::with_runner_config(&directory, &config);
|
||||
let prepared = executor
|
||||
.execute(&command(1, "run.prepare", prepare))
|
||||
.unwrap();
|
||||
assert_eq!(prepared.result["status"], "prepared");
|
||||
assert_eq!(
|
||||
fs::metadata(&runtime).unwrap().permissions().mode() & 0o777,
|
||||
0o700
|
||||
);
|
||||
executor
|
||||
.execute(&command(2, "session.open", json!({})))
|
||||
.unwrap();
|
||||
executor.shutdown().unwrap();
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn credential_updates_replay_through_the_native_executor_until_durable_ack() {
|
||||
let root = temporary_directory("credential-updates");
|
||||
let root = fs::canonicalize(root).unwrap();
|
||||
let auth = root.join("auth.json");
|
||||
let write_auth = |marker: &str| {
|
||||
fs::write(
|
||||
&auth,
|
||||
serde_json::to_vec(&json!({"tokens":{
|
||||
"account_id":"account", "access_token":format!("access-{marker}"),
|
||||
"refresh_token":format!("refresh-{marker}")
|
||||
}}))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&auth, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
};
|
||||
let state_path = root.join("credential-observer-state.json");
|
||||
fs::write(&state_path, serde_json::to_vec(&json!({
|
||||
"schema":"paperclip.runner.credential-observer.v1", "sessionId":"session-1",
|
||||
"provider":"codex", "path":auth, "snapshot":null, "revision":0, "armed":true, "pending":null
|
||||
})).unwrap()).unwrap();
|
||||
fs::set_permissions(&state_path, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
let runner_config = config(&root);
|
||||
write_auth("initial");
|
||||
let mut executor = NativeProviderCommandExecutor::with_runner_config(&root, &runner_config);
|
||||
assert!(executor.poll_events().unwrap().is_empty());
|
||||
write_auth("refreshed");
|
||||
let _ = executor.execute(&Command {
|
||||
schema: "paperclip.prp.command.v1".to_owned(),
|
||||
command_id: "close-unselected".to_owned(),
|
||||
controller_seq: 1,
|
||||
command_type: "session.close".to_owned(),
|
||||
issued_at: "2026-10-15T12:00:00.000Z".to_owned(),
|
||||
deadline_at: None,
|
||||
precondition: None,
|
||||
payload: json!({}),
|
||||
});
|
||||
let updates = executor.retained_events().unwrap();
|
||||
assert_eq!(updates.len(), 1);
|
||||
assert_eq!(updates[0].event_type, "auth.credentials.updated");
|
||||
assert_eq!(
|
||||
updates[0].priority,
|
||||
paperclip_runner_core::durable::EventPriority::P0
|
||||
);
|
||||
drop(executor);
|
||||
let mut resumed = NativeProviderCommandExecutor::with_runner_config(&root, &runner_config);
|
||||
assert_eq!(resumed.poll_events().unwrap(), updates);
|
||||
assert_eq!(resumed.retained_runner_events().unwrap(), updates);
|
||||
resumed.acknowledge_events(1).unwrap();
|
||||
assert!(resumed.poll_events().unwrap().is_empty());
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
fn config(state_dir: &Path) -> DurableRunnerConfig {
|
||||
DurableRunnerConfig {
|
||||
connect_url: "ws://127.0.0.1/runner".to_owned(),
|
||||
|
||||
@@ -39,7 +39,7 @@ const { commandDigest, ...attestation } = contract;
|
||||
assert.equal(commandDigest, `sha256:${createHash("sha256").update(canonicalJson(attestation)).digest("hex")}`);
|
||||
assert.equal(contract.acpxPatchSha256, createHash("sha256")
|
||||
.update(await readFile(new URL("../../patches/acpx@0.13.1.patch", root))).digest("hex"));
|
||||
for (const [agent, path] of [["pi", "test-fixtures/pi-acp/profile-v22-identity.json"], ["copilot", "test/fixtures/copilot-profile-v18-identity.json"]]) {
|
||||
for (const [agent, path] of [["pi", "test-fixtures/pi-acp/profile-v22-identity.json"], ["copilot", "test/fixtures/copilot-profile-v19-identity.json"]]) {
|
||||
const identity = await readJson(path);
|
||||
assert.equal(manifest.profiles[agent].agentProfileVersion, identity.declaration.agentProfileVersion);
|
||||
assert.equal(manifest.profiles[agent].commandDigest, identity.commandDigest);
|
||||
|
||||
@@ -13,6 +13,7 @@ const validatorsOutputPath = resolve(
|
||||
"src/protocol/generated/standalone-validators.ts",
|
||||
);
|
||||
const schemaNames = [
|
||||
"auth-credentials",
|
||||
"identity",
|
||||
"capabilities",
|
||||
"capabilities-v2",
|
||||
@@ -66,6 +67,7 @@ const ajv = new Ajv2020({
|
||||
});
|
||||
for (const { value } of schemas) ajv.addSchema(value);
|
||||
const standaloneValidators = standaloneCode(ajv, {
|
||||
authCredentialsValidator: schemaByName["auth-credentials"].$id,
|
||||
fixtureValidator: schemaByName.fixture.$id,
|
||||
eventValidator: schemaByName.event.$id,
|
||||
eventV2Validator: schemaByName["event-v2"].$id,
|
||||
@@ -87,9 +89,9 @@ const validatorsWithRuntimeImports = standaloneValidators.replace(
|
||||
equalRuntimePattern,
|
||||
"const $1 = typeof equalModule === \"function\" ? equalModule : equalModule.default;",
|
||||
);
|
||||
const validatorExportPattern = /export const (fixtureValidator|eventValidator|resultValidator) =/g;
|
||||
const validatorExportPattern = /export const (authCredentialsValidator|fixtureValidator|eventValidator|resultValidator) =/g;
|
||||
const validatorExports = [...validatorsWithRuntimeImports.matchAll(validatorExportPattern)];
|
||||
if (validatorExports.length !== 3) {
|
||||
if (validatorExports.length !== 4) {
|
||||
throw new Error("Ajv standalone output no longer has the expected validator exports");
|
||||
}
|
||||
// Ajv's generated functions are intentionally unchecked runtime JavaScript.
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
"sandbox": "Sandbox resource measurements.",
|
||||
"workspace": "Workspace readiness.",
|
||||
"harness": "Provider harness startup, readiness, exit, and diagnostics.",
|
||||
"auth": "Content-free harness credential changes observed by the runner.",
|
||||
"session": "Provider-neutral session open, resume, reconciliation, close, and failure.",
|
||||
"turn": "Model turn submission through terminal turn disposition.",
|
||||
"item": "Provider-neutral model/tool item lifecycle.",
|
||||
|
||||
@@ -6,7 +6,7 @@ Status: canonical explanatory contract for the Paperclip runner V1 surface.
|
||||
|
||||
This document keeps three independent meanings of **group** separate. PRP families describe wire evidence and controller commands; capability placement decides who owns an operation; behavioral eval groups organize the 106 scenario corpus. None of the three axes can be used as a substitute for another.
|
||||
|
||||
The generated totals are **105 PRP events in 31 event families**, **18 controller commands in 7 command families**, **10 control-plane operations**, **61 reconciled semantic operations** (18 always, 43 optional), and **106 scenarios in 16 behavior groups**.
|
||||
The generated totals are **106 PRP events in 32 event families**, **18 controller commands in 7 command families**, **10 control-plane operations**, **61 reconciled semantic operations** (18 always, 43 optional), and **106 scenarios in 16 behavior groups**.
|
||||
|
||||
## Axis 1: PRP v1 event and command families
|
||||
|
||||
@@ -20,6 +20,7 @@ PRP records ordered, replayable execution evidence. It is not the model's Paperc
|
||||
| `runtime` | Runner phase transitions. | `runtime.phase.changed` | 1 |
|
||||
| `sandbox` | Sandbox resource measurements. | `sandbox.metric` | 1 |
|
||||
| `workspace` | Workspace readiness. | `workspace.ready`<br>`workspace.change.updated`<br>`workspace.diff.recorded`<br>`workspace.file.referenced` | 4 |
|
||||
| `auth` | Content-free harness credential changes observed by the runner. | `auth.credentials.updated` | 1 |
|
||||
| `harness` | Provider harness startup, readiness, exit, and diagnostics. | `harness.starting`<br>`harness.ready`<br>`harness.exited`<br>`harness.diagnostic` | 4 |
|
||||
| `plan` | Complete provider-authored within-turn checklist snapshots, separate from durable Paperclip Plan documents. | `plan.updated` | 1 |
|
||||
| `tool` | Provider-neutral process, MCP, dynamic, and built-in execution activity. | `tool.execution.started`<br>`tool.execution.progressed`<br>`tool.execution.completed` | 3 |
|
||||
|
||||
@@ -68,7 +68,7 @@ describe("canonical operation-groups specification", () => {
|
||||
expect(input.source.behaviorGroups).toHaveLength(16);
|
||||
expect(input.scenarios).toHaveLength(106);
|
||||
expect(new Set(input.scenarios.map((scenario) => scenario.id)).size).toBe(106);
|
||||
expect(input.eventTypes).toHaveLength(105);
|
||||
expect(input.eventTypes).toHaveLength(106);
|
||||
expect(input.commandTypes).toHaveLength(18);
|
||||
});
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ export interface OperationGroupsInput {
|
||||
catalogIndexSource: string;
|
||||
}
|
||||
|
||||
const EXPECTED_EVENT_COUNT = 105;
|
||||
const EXPECTED_EVENT_COUNT = 106;
|
||||
const EXPECTED_COMMAND_COUNT = 18;
|
||||
const EXPECTED_SCENARIO_COUNT = 106;
|
||||
const EXPECTED_BEHAVIOR_GROUP_COUNT = 16;
|
||||
|
||||
@@ -46,6 +46,96 @@ const identity: DurableRecoveryIdentity = {
|
||||
const expectedRunnerVersion = "0.3.0";
|
||||
const expectedRunnerDigest = `sha256:${"a".repeat(64)}`;
|
||||
|
||||
it("commits credential updates before ACK and preserves replay identity", async () => {
|
||||
const root = mkdtempSync(resolve(tmpdir(), "runner-credential-update-"));
|
||||
let release!: () => void;
|
||||
const barrier = new Promise<void>(resolveCommit => { release = resolveCommit; });
|
||||
const commits = vi.fn(async () => barrier);
|
||||
const core = new DurablePrpControlPlane({ stateDirectory: root, identity,
|
||||
expectedRunnerVersion, expectedRunnerDigest, onCommittedEvent: commits });
|
||||
try {
|
||||
await core.start();
|
||||
const client = (await authenticate(core, core.issueBootstrapTicket()))!;
|
||||
const frame = semanticInputEvent();
|
||||
const event = frame.payload as Record<string, unknown>;
|
||||
event.sourceEventId = "credential-update-1";
|
||||
event.eventType = "auth.credentials.updated";
|
||||
event.payload = { schema: "paperclip.auth.credentials.updated.v1", provider: "codex",
|
||||
bindingId: "harness-auth", revision: 1, detection: "credential_store" };
|
||||
sendSecure(client, frame);
|
||||
await vi.waitFor(() => expect(commits).toHaveBeenCalledTimes(1));
|
||||
expect(core.store.state.ackedSourceSeq).toBe(0);
|
||||
release();
|
||||
const ack = (await receiveSecure(client))!;
|
||||
expect(ack.kind).toBe("ack");
|
||||
expect(core.store.state.ackedSourceSeq).toBe(1);
|
||||
expect(commits).toHaveBeenCalledWith(expect.objectContaining({
|
||||
eventType: "auth.credentials.updated", payload: event.payload,
|
||||
}));
|
||||
sendSecure(client, frame);
|
||||
expect((await receiveSecure(client))!.kind).toBe("ack");
|
||||
expect(core.store.state.committedEvents).toHaveLength(1);
|
||||
expect(core.store.state.committedEvents[0].deliveryCount).toBe(2);
|
||||
expect(core.store.state.committedEvents[0].logicalEffectCount).toBe(1);
|
||||
client.socket.destroy();
|
||||
} finally {
|
||||
release();
|
||||
await core.stop();
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["success", "integrity_failure"] as const)("ignores a replaced connection's late credential commit %s", async outcome => {
|
||||
const root = mkdtempSync(resolve(tmpdir(), "runner-credential-reconnect-"));
|
||||
let release!: () => void;
|
||||
const barrier = new Promise<void>(resolveCommit => { release = resolveCommit; });
|
||||
let first = true;
|
||||
const commits = vi.fn(async () => {
|
||||
if (!first) return;
|
||||
first = false;
|
||||
await barrier;
|
||||
if (outcome === "integrity_failure") throw new NativeSessionProtocolIntegrityError("source_event_replay_conflict");
|
||||
});
|
||||
const onProtocolIntegrityError = vi.fn();
|
||||
const core = new DurablePrpControlPlane({ stateDirectory: root, identity,
|
||||
expectedRunnerVersion, expectedRunnerDigest, onCommittedEvent: commits, onProtocolIntegrityError });
|
||||
const frame = (seq: number) => {
|
||||
const envelope = semanticInputEvent(seq);
|
||||
const event = envelope.payload as Record<string, unknown>;
|
||||
event.sourceEventId = `credential-reconnect-${seq}`;
|
||||
event.eventType = "auth.credentials.updated";
|
||||
event.payload = { schema: "paperclip.auth.credentials.updated.v1", provider: "codex",
|
||||
bindingId: "harness-auth", revision: seq, detection: "credential_store" };
|
||||
return envelope;
|
||||
};
|
||||
try {
|
||||
await core.start();
|
||||
const old = (await authenticate(core, core.issueBootstrapTicket()))!;
|
||||
sendSecure(old, frame(1));
|
||||
await vi.waitFor(() => expect(commits).toHaveBeenCalledTimes(1));
|
||||
const replacement = (await authenticate(core, old.leaseToken!))!;
|
||||
for (const seq of [1, 2]) {
|
||||
sendSecure(replacement, frame(seq));
|
||||
expect(await receiveSecure(replacement)).toMatchObject({ kind: "ack", payload: { ackedSourceSeq: seq } });
|
||||
}
|
||||
release();
|
||||
await new Promise<void>(resolveTurn => setImmediate(resolveTurn));
|
||||
expect(core.store.state.ackedSourceSeq).toBe(2);
|
||||
expect(core.store.state.committedEvents.map(event => event.sourceSeq)).toEqual([1, 2]);
|
||||
expect(onProtocolIntegrityError).not.toHaveBeenCalled();
|
||||
sendSecure(replacement, frame(3));
|
||||
expect(await receiveSecure(replacement)).toMatchObject({ kind: "ack", payload: { ackedSourceSeq: 3 } });
|
||||
const saved = JSON.parse(readFileSync(core.store.path, "utf8"));
|
||||
expect(saved.ackedSourceSeq).toBe(3);
|
||||
expect(saved.committedEvents.map((event: { sourceSeq: number }) => event.sourceSeq)).toEqual([1, 2, 3]);
|
||||
replacement.socket.destroy();
|
||||
} finally {
|
||||
release();
|
||||
await core.stop();
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function renewalRequest(client: AuthenticatedClient, expiresAt: number): Record<string, unknown> {
|
||||
return {
|
||||
protocol: "paperclip.runner", version: client.welcome.version,
|
||||
|
||||
@@ -1492,6 +1492,7 @@ export class DurablePrpControlPlane {
|
||||
#expectedRunnerDigest: string;
|
||||
#server: Server | null = null;
|
||||
#connections = new Set<AuthorityConnection>();
|
||||
#eventOwner: AuthorityConnection | null = null;
|
||||
// Set when the last authenticated Runner connection closes; cleared on the
|
||||
// next authentication. Diagnostic only: it never gates authority.
|
||||
#runnerDisconnectedAt: number | null = null;
|
||||
@@ -2763,6 +2764,7 @@ export class DurablePrpControlPlane {
|
||||
clientProof,
|
||||
);
|
||||
this.#runnerDisconnectedAt = null;
|
||||
this.#eventOwner = connection;
|
||||
for (const active of this.#connections) {
|
||||
if (active !== connection && active.secureChannel !== null)
|
||||
active.close();
|
||||
@@ -3103,6 +3105,8 @@ export class DurablePrpControlPlane {
|
||||
connection: AuthorityConnection,
|
||||
envelope: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
if (this.#eventOwner !== connection) return;
|
||||
const identity = this.#identity;
|
||||
if (this.#protocolIntegrityError !== null) {
|
||||
connection.close();
|
||||
return;
|
||||
@@ -3235,6 +3239,7 @@ export class DurablePrpControlPlane {
|
||||
try {
|
||||
await this.#onCommittedEvent?.(event);
|
||||
} catch (error) {
|
||||
if (this.#eventOwner !== connection || this.#identity !== identity) return;
|
||||
if (error instanceof NativeSessionProtocolIntegrityError) {
|
||||
this.#failProtocolIntegrity(connection, error);
|
||||
} else {
|
||||
@@ -3242,6 +3247,7 @@ export class DurablePrpControlPlane {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.#eventOwner !== connection || this.#identity !== identity) return;
|
||||
// Another authenticated connection can replace this one while its commit
|
||||
// is in flight. Once that exact owner has faulted, even a prior successful
|
||||
// commit cannot reopen delivery or invoke a new business operation.
|
||||
|
||||
@@ -95,8 +95,17 @@ describe("Copilot build-owned installation", () => {
|
||||
expect(current.commandDigest).not.toBe(prior.commandDigest);
|
||||
expect(QUALIFIED_ACPX_PROFILES.copilot.qualificationStatus).toBe("pending");
|
||||
});
|
||||
it("admits the current v18 declaration and binds its source policy, receipts and patch hashes", () => {
|
||||
const identity = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v18-identity.json", import.meta.url), "utf8"));
|
||||
it("preserves v18 history while binding the credential update protocol sources", () => {
|
||||
const prior = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v18-identity.json", import.meta.url), "utf8"));
|
||||
const current = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v19-identity.json", import.meta.url), "utf8"));
|
||||
expect(Object.keys(current.declaration).filter(key => current.declaration[key] !== prior.declaration[key]).sort())
|
||||
.toEqual(["agentProfileVersion", "semanticSchemaBundleSourceSha256", "semanticValidationSourceSha256", "semanticValidatorsSourceSha256"]);
|
||||
expect(Object.keys(current.declaration).sort()).toEqual(Object.keys(prior.declaration).sort());
|
||||
expect(current.commandDigest).not.toBe(prior.commandDigest);
|
||||
expect(QUALIFIED_ACPX_PROFILES.copilot.qualificationStatus).toBe("pending");
|
||||
});
|
||||
it("admits the current v19 declaration and binds its source policy, receipts and patch hashes", () => {
|
||||
const identity = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v19-identity.json", import.meta.url), "utf8"));
|
||||
expect(identity.declaration.systemInstructionDelivery).toBe(COPILOT_SYSTEM_INSTRUCTION_DELIVERY);
|
||||
expect(identity.declaration.sharedRuntimeContract).toBe("paperclip.acpx-runtime-contract.v1");
|
||||
expect(identity.declaration.permissionContextContract).toBe(COPILOT_PERMISSION_CONTEXT_CONTRACT);
|
||||
@@ -127,7 +136,7 @@ describe("Copilot build-owned installation", () => {
|
||||
expect([...closure].filter(path => !bound.has(path))).toEqual(["negative-control:unbound-policy"]);
|
||||
});
|
||||
it.each([...PERMISSION_POLICY_SOURCES, ...SEMANTIC_RECEIPT_SOURCES])("changing %s changes the candidate identity", (_path, field) => {
|
||||
const identity = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v18-identity.json", import.meta.url), "utf8"));
|
||||
const identity = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v19-identity.json", import.meta.url), "utf8"));
|
||||
identity.declaration[field] = "0".repeat(64);
|
||||
const sorted = Object.fromEntries(Object.entries(identity.declaration).sort(([a], [b]) => a.localeCompare(b)));
|
||||
expect(`sha256:${createHash("sha256").update(JSON.stringify(sorted)).digest("hex")}`).not.toBe(identity.commandDigest);
|
||||
|
||||
@@ -48,12 +48,12 @@ export const QUALIFIED_ACPX_PROFILE_DATA = {
|
||||
"protocolVersion": 1,
|
||||
"acpxVersion": "0.13.1",
|
||||
"agent": "copilot",
|
||||
"agentProfileVersion": 18,
|
||||
"agentProfileVersion": 19,
|
||||
"agentServerPackage": "@github/copilot",
|
||||
"agentServerVersion": "1.0.88",
|
||||
"agentRuntimePackage": null,
|
||||
"agentRuntimeVersion": null,
|
||||
"commandDigest": "sha256:2ec904f44218f51058fa83d7437b26c4551e1c65e6f2c55f5a6386fa4061e96d",
|
||||
"commandDigest": "sha256:38abf359adeef43f1f19230245c6e2051c55fdd79571882ef6f00b7cb2958d93",
|
||||
"qualificationStatus": "pending",
|
||||
"permissionPolicy": "interactive"
|
||||
},
|
||||
|
||||
@@ -44,6 +44,41 @@ import {
|
||||
} from "./codex-app-server-driver.test-support.js";
|
||||
|
||||
describe("Codex app-server Codex driver", () => {
|
||||
it("forwards credential updates before a turn with P0 priority", async () => {
|
||||
const transport = new FakeCodexTransport();
|
||||
const session = await makeDriver([transport]).openSession({
|
||||
runId: "run-credential-update", normalizedSessionId: "session-credential-update", workingDirectory: WORKSPACE,
|
||||
});
|
||||
const payload = { schema: "paperclip.auth.credentials.updated.v1", provider: "codex",
|
||||
bindingId: "harness-auth", revision: 1, detection: "credential_store" };
|
||||
transport.push("paperclip/canonicalProviderEvent", { eventType: "auth.credentials.updated", payload });
|
||||
const turn = await session.startTurn({ message: { role: "user", text: "Finish." } });
|
||||
transport.push("turn/started", { threadId: "thread-1", turn: { id: turn.turnId, status: "inProgress" } });
|
||||
transport.push("paperclip/runResult", { threadId: "thread-1", turnId: turn.turnId, result });
|
||||
transport.push("turn/completed", { threadId: "thread-1", turn: { id: turn.turnId, status: "completed", items: [] } });
|
||||
const events = await collectUntilTerminal(session.events());
|
||||
const updates = events.filter(event => event.eventType === "auth.credentials.updated");
|
||||
expect(updates).toHaveLength(1);
|
||||
expect(updates[0]).toMatchObject({ priority: 0, payload });
|
||||
expect(validatePrpEvent(updates[0]).ok).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects credential payloads containing secret fields before emitting them", async () => {
|
||||
const transport = new FakeCodexTransport();
|
||||
const session = await makeDriver([transport]).openSession({
|
||||
runId: "run-invalid-credential-update", normalizedSessionId: "session-invalid-credential-update", workingDirectory: WORKSPACE,
|
||||
});
|
||||
transport.push("paperclip/canonicalProviderEvent", { eventType: "auth.credentials.updated", payload: {
|
||||
schema: "paperclip.auth.credentials.updated.v1", provider: "codex", bindingId: "harness-auth",
|
||||
revision: 1, detection: "credential_store", access_token: "credential-secret-sentinel",
|
||||
} });
|
||||
const events = await collectUntilTerminal(session.events());
|
||||
expect(events.some(event => event.eventType === "auth.credentials.updated")).toBe(false);
|
||||
expect(JSON.stringify(events)).not.toContain("credential-secret-sentinel");
|
||||
expect(events).toContainEqual(expect.objectContaining({ eventType: "session.failed",
|
||||
payload: expect.objectContaining({ code: "credential_update_invalid" }) }));
|
||||
});
|
||||
|
||||
it("admits a strictly bound semantic result from the durable runner", async () => {
|
||||
const transport = new FakeCodexTransport();
|
||||
const session = await makeDriver([transport]).openSession({
|
||||
|
||||
@@ -14,6 +14,8 @@ describe("provider notification authority", () => {
|
||||
it.each([
|
||||
["warning", { message: "buffered before replacement rejection" }, "root"],
|
||||
["paperclip/canonicalProviderEvent", { threadId: null, eventType: "provider.notice.recorded" }, "root"],
|
||||
["paperclip/canonicalProviderEvent", { threadId: null, eventType: "auth.credentials.updated" }, "root"],
|
||||
["paperclip/canonicalProviderEvent", { threadId: "child", eventType: "auth.credentials.updated" }, "invalid_authority"],
|
||||
["paperclip/canonicalProviderEvent", { threadId: null, eventType: "tool.execution.started" }, "invalid_authority"],
|
||||
["item/started", { threadId: "root", turnId: "active" }, "root"],
|
||||
["turn/completed", { threadId: "root", turnId: "old" }, "stale_turn"],
|
||||
|
||||
@@ -40,7 +40,7 @@ export function classifyCodexNotification(input: {
|
||||
const { params, method } = input;
|
||||
const isInformation = informational.has(method) ||
|
||||
(method === "paperclip/canonicalProviderEvent" &&
|
||||
["provider.notice.recorded", "harness.diagnostic"].includes(String(params.eventType)));
|
||||
["provider.notice.recorded", "harness.diagnostic", "auth.credentials.updated"].includes(String(params.eventType)));
|
||||
const threads = [
|
||||
params.threadId,
|
||||
record(params.thread).id,
|
||||
|
||||
@@ -4,7 +4,7 @@ import { paperclipWorkspaceFileReferencesFromText } from "../../live/workspace-f
|
||||
import { canonicalProviderEventsFromCodex, isCanonicalProviderEventType } from "../../provider-events.js";
|
||||
import { harnessRuntimeRequestOutcome } from "../../contracts/harness-driver.js";
|
||||
import { NativeSessionProtocolIntegrityError } from "../../contracts/native-session-backend.js";
|
||||
import { validatePrpStructuredRunResult } from "../../protocol/replay-contract.js";
|
||||
import { isPrpAuthCredentialsUpdated, validatePrpStructuredRunResult } from "../../protocol/replay-contract.js";
|
||||
import type { CodexRpcNotification, CodexTraceInterpretation } from "./app-server-transport.js";
|
||||
import { redactCodexDiagnostic } from "./app-server-transport.js";
|
||||
import { boundedCodexPayload as boundedPayload, boundedCodexValue, isRetainableCodexPayload } from "./codex-boundaries.js";
|
||||
@@ -156,6 +156,14 @@ async function mapNotificationBody(state: CodexSessionState, notification: Codex
|
||||
return;
|
||||
}
|
||||
const canonicalPayload = record(params.payload);
|
||||
if (params.eventType === "auth.credentials.updated") {
|
||||
if (!isPrpAuthCredentialsUpdated(canonicalPayload)) {
|
||||
state.failProtocol("credential_update_invalid", "Invalid credential update notification.");
|
||||
return;
|
||||
}
|
||||
state.emit(params.eventType, canonicalPayload, { turnId: turnId || undefined, itemId: itemId || undefined });
|
||||
return;
|
||||
}
|
||||
if (params.eventType === "harness.diagnostic" && canonicalPayload.code === "codex_resume_usage_snapshot") {
|
||||
state.codexUsageBaseline = observeCodexUsage(state.codexUsageBaseline, canonicalPayload.cumulative, true);
|
||||
state.usageSnapshot = codexRunUsage(state.codexUsageBaseline);
|
||||
|
||||
@@ -451,7 +451,7 @@ export class CodexSessionState {
|
||||
...(refs.itemId ? { itemId: refs.itemId } : {}),
|
||||
eventType,
|
||||
schemaVersion: 1,
|
||||
priority: eventType === "run.result.proposed" ? 0 : 1,
|
||||
priority: eventType === "run.result.proposed" || eventType === "auth.credentials.updated" ? 0 : 1,
|
||||
emittedAt: this.now().toISOString(),
|
||||
payload,
|
||||
});
|
||||
|
||||
@@ -1231,6 +1231,8 @@ export interface CapabilityRunnerdProcessEvidence {
|
||||
|
||||
export interface CapabilityRunnerdCodexTransportOptions extends RunnerExecutionDriver {
|
||||
provider?: "codex" | "opencode" | "claude_managed" | "aws_agentcore" | "acpx";
|
||||
observeCredentials?: boolean;
|
||||
onCredentialsUpdated?: (event: PrpEvent) => Promise<void>;
|
||||
opencodePermissionMode?: NativeOpenCodePermissionMode;
|
||||
acpxAgent?: QualifiedAcpxAgent;
|
||||
/** Explicit evaluation-only candidate selection, never derived from persisted session input. */
|
||||
@@ -4723,6 +4725,11 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
expectedRunnerDigest: runnerArtifact.digest,
|
||||
onProtocolIntegrityError: (error) => this.#failTransport(error),
|
||||
onSemanticToolInput: (call) => this.#handleSemanticToolInput(call),
|
||||
onCommittedEvent: async (event) => {
|
||||
if (event.eventType === "auth.credentials.updated") {
|
||||
await this.options.onCredentialsUpdated?.(event);
|
||||
}
|
||||
},
|
||||
connectionLeaseTtlMs: 60 * 60 * 1_000,
|
||||
});
|
||||
this.#core = core;
|
||||
@@ -4905,6 +4912,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
? resolveAcpxProviderMode(acpxProfile!.agent, this.options.acpxMode) : undefined;
|
||||
const completionContract = record(params.completionContract);
|
||||
const runAttachTemplate = {
|
||||
observeCredentials: this.options.observeCredentials !== false,
|
||||
authorizedTools: this.#authorizedTools,
|
||||
...(completionContract.revision &&
|
||||
Array.isArray(completionContract.criterionIds)
|
||||
@@ -5460,6 +5468,11 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
expectedRunnerDigest: runnerArtifact.digest,
|
||||
onProtocolIntegrityError: (error) => this.#failTransport(error),
|
||||
onSemanticToolInput: (call) => this.#handleSemanticToolInput(call),
|
||||
onCommittedEvent: async (event) => {
|
||||
if (event.eventType === "auth.credentials.updated") {
|
||||
await this.options.onCredentialsUpdated?.(event);
|
||||
}
|
||||
},
|
||||
...(warmRecovery
|
||||
? {
|
||||
beforeAuthenticatedConnection: async (admission) => {
|
||||
@@ -6340,6 +6353,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
// full, new events replace its prefix without increasing its length.
|
||||
if (fromDeferredQueue) this.#deferredTurnStartEvents.shift();
|
||||
else this.#eventSourceSeq = event.sourceSeq;
|
||||
if (event.eventType === "auth.credentials.updated" && this.options.onCredentialsUpdated) continue;
|
||||
if (
|
||||
event.eventType === "harness.ready" ||
|
||||
event.eventType === "session.started" ||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { mkdtemp, mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { CodexAppServerDriver } from "../drivers/codex/codex-app-server-driver.js";
|
||||
import type { PrpEvent } from "../protocol/replay-contract.js";
|
||||
import { createRunnerdCodexTransport, defaultCapabilityRunnerdBinary } from "./runnerd-codex-transport.js";
|
||||
|
||||
it.each([false, true])("commits idle account switches and close refreshes before ACK (retry: %s)", async retry => {
|
||||
const root = await realpath(await mkdtemp(join(tmpdir(), "runnerd-credential-host-")));
|
||||
const sourceHome = join(root, "seed");
|
||||
await mkdir(sourceHome, { mode: 0o700 });
|
||||
const credential = (revision: number, account = "synthetic-account") => JSON.stringify({ tokens: {
|
||||
account_id: account, access_token: `synthetic-access-${revision}`,
|
||||
refresh_token: `synthetic-refresh-${revision}`, id_token: "synthetic-identity",
|
||||
} });
|
||||
await writeFile(join(sourceHome, "auth.json"), credential(0), { mode: 0o600 });
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>(resolveGate => { release = resolveGate; });
|
||||
const committed: PrpEvent[] = [];
|
||||
const onCredentialsUpdated = vi.fn(async (event: PrpEvent) => {
|
||||
if (event.payload.revision === 1) await gate;
|
||||
if (retry && onCredentialsUpdated.mock.calls.length === 1) throw new Error("synthetic host commit failure");
|
||||
committed.push(structuredClone(event));
|
||||
});
|
||||
const bundle = createRunnerdCodexTransport({
|
||||
runnerBinary: defaultCapabilityRunnerdBinary(),
|
||||
codexCommand: resolve(import.meta.dirname, "../../runner/target/debug/fake-codex-app-server"),
|
||||
codexArgs: ["--state-file", join(root, "provider.json")],
|
||||
stateDirectory: root,
|
||||
sourceCodexHome: sourceHome,
|
||||
environment: { PATH: process.env.PATH },
|
||||
lifecyclePolicy: { mode: "warm", idleTimeoutMs: 60_000 },
|
||||
onCredentialsUpdated,
|
||||
});
|
||||
const driver = new CodexAppServerDriver({
|
||||
taskEnvelope: { schema: "paperclip.skillless_task.v1", objective: "Observe credential delivery.",
|
||||
completionContract: { revision: "test-v1", criteria: [{ id: "done", requirement: "Done." }] },
|
||||
constraints: [], expectedResultSchema: "paperclip.run_result.v1" },
|
||||
approvalPolicy: "never", includeCollaborationModeInstructions: false,
|
||||
transportFactory: () => bundle.transport,
|
||||
});
|
||||
const session = await driver.openSession({ runId: "credential-run", normalizedSessionId: "credential-session", workingDirectory: root });
|
||||
const journal = async () => JSON.parse(await readFile(join(root, "control-plane", "control-plane-state.json"), "utf8"));
|
||||
try {
|
||||
await session.startTurn({ message: { role: "user", text: "Finish." } });
|
||||
for await (const event of session.events()) {
|
||||
if (["turn.completed", "turn.failed", "turn.interrupted", "turn.cancelled"].includes(event.eventType)) break;
|
||||
}
|
||||
const auth = join(root, "codex-home", "auth.json");
|
||||
await writeFile(auth, credential(0, "synthetic-next-account"), { mode: 0o600 });
|
||||
await vi.waitFor(() => expect(onCredentialsUpdated).toHaveBeenCalled(), { timeout: 5_000 });
|
||||
const first = onCredentialsUpdated.mock.calls[0]![0];
|
||||
expect((await journal()).ackedSourceSeq).toBeLessThan(first.sourceSeq);
|
||||
expect(committed).toHaveLength(0);
|
||||
release();
|
||||
await vi.waitFor(async () => expect((await journal()).ackedSourceSeq).toBeGreaterThanOrEqual(first.sourceSeq));
|
||||
if (retry) expect(onCredentialsUpdated.mock.calls[1]![0]).toEqual(first);
|
||||
await session.attachRun!({ runId: "credential-next-run" });
|
||||
expect(committed).toHaveLength(1);
|
||||
await writeFile(auth, credential(1, "synthetic-next-account"), { mode: 0o600 });
|
||||
await session.close({ reason: "credential-cleanup-test" });
|
||||
expect(committed.map(event => event.payload.revision)).toEqual([1, 2]);
|
||||
expect(JSON.stringify(committed)).not.toContain("synthetic-next-account");
|
||||
expect(committed[1]!.runId).toBe("credential-next-run");
|
||||
expect((await journal()).ackedSourceSeq).toBeGreaterThanOrEqual(committed[1]!.sourceSeq);
|
||||
} finally {
|
||||
release();
|
||||
await bundle.transport.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isCanonicalProviderEventType } from "../provider-events.js";
|
||||
import { validatePrpEvent, type PrpAuthCredentialsUpdated, type PrpEvent } from "./replay-contract.js";
|
||||
|
||||
const payload: PrpAuthCredentialsUpdated = {
|
||||
schema: "paperclip.auth.credentials.updated.v1", provider: "grok", bindingId: "harness-auth",
|
||||
revision: 1, detection: "credential_store",
|
||||
};
|
||||
|
||||
function event(version: 1 | 2 | 3): PrpEvent {
|
||||
return {
|
||||
schema: `paperclip.prp.event.v${version}`,
|
||||
schemaVersion: version, sourceEventId: "credential-update-1", sourceSeq: 1,
|
||||
sourceInstanceId: "runner", sourceKind: "runner", runId: "run", normalizedSessionId: "session",
|
||||
eventType: "auth.credentials.updated", priority: 0, emittedAt: "2026-10-15T12:00:00.000Z", payload,
|
||||
};
|
||||
}
|
||||
|
||||
describe.each([1, 2, 3] as const)("PRP v%s credential updates", (version) => {
|
||||
it("accepts content-free store and native-hook notifications", () => {
|
||||
expect(isCanonicalProviderEventType("auth.credentials.updated")).toBe(true);
|
||||
expect(validatePrpEvent(event(version)).ok).toBe(true);
|
||||
expect(validatePrpEvent({ ...event(version), payload: { ...payload, detection: "native_hook" } }).ok).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects secret material, missing fields, invalid revisions, and downgraded priority", () => {
|
||||
const invalid = [
|
||||
{ ...payload, access_token: "secret-sentinel" }, { ...payload, refresh_token: "secret-sentinel" },
|
||||
{ ...payload, path: "/private/auth.json" }, { ...payload, fingerprint: "secret-digest" },
|
||||
{ ...payload, revision: 0 }, { ...payload, revision: 1.5 }, { ...payload, revision: Number.MAX_SAFE_INTEGER + 1 },
|
||||
{ ...payload, detection: "inferred_from_account_notification" }, { ...payload, bindingId: "" },
|
||||
{ ...payload, schema: "paperclip.auth.credentials.updated.v2" },
|
||||
Object.fromEntries(Object.entries(payload).filter(([key]) => key !== "provider")),
|
||||
];
|
||||
for (const candidate of invalid) {
|
||||
expect(validatePrpEvent({ ...event(version), payload: candidate }).ok, JSON.stringify(candidate)).toBe(false);
|
||||
}
|
||||
expect(validatePrpEvent({ ...event(version), priority: 1 }).ok).toBe(false);
|
||||
expect(validatePrpEvent({ ...event(version), sourceKind: "control_plane" }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,49 @@
|
||||
// Generated by scripts/generate-protocol-schema-module.mjs. Do not edit.
|
||||
|
||||
export const authCredentialsSchema = {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://paperclip.dev/schemas/prp/v1/auth-credentials.schema.json",
|
||||
"title": "PRP credential update notification",
|
||||
"description": "Content-free evidence of changed credentials for the harness-auth binding in this normalized session. Credential-store detection does not prove an OAuth refresh succeeded.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schema",
|
||||
"provider",
|
||||
"bindingId",
|
||||
"revision",
|
||||
"detection"
|
||||
],
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "paperclip.auth.credentials.updated.v1"
|
||||
},
|
||||
"provider": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 160,
|
||||
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
|
||||
},
|
||||
"bindingId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 160,
|
||||
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
|
||||
},
|
||||
"revision": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"detection": {
|
||||
"enum": [
|
||||
"credential_store",
|
||||
"native_hook"
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
} as const;
|
||||
|
||||
export const identitySchema = {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://paperclip.dev/schemas/prp/v1/identity.schema.json",
|
||||
@@ -4370,6 +4414,7 @@ export const eventSchema = {
|
||||
"workspace.change.updated",
|
||||
"workspace.diff.recorded",
|
||||
"workspace.file.referenced",
|
||||
"auth.credentials.updated",
|
||||
"harness.starting",
|
||||
"harness.ready",
|
||||
"harness.exited",
|
||||
@@ -4506,6 +4551,28 @@ export const eventSchema = {
|
||||
}
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"eventType": {
|
||||
"const": "auth.credentials.updated"
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"sourceKind": {
|
||||
"const": "runner"
|
||||
},
|
||||
"priority": {
|
||||
"const": 0
|
||||
},
|
||||
"payload": {
|
||||
"$ref": "https://paperclip.dev/schemas/prp/v1/auth-credentials.schema.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
@@ -5070,6 +5137,7 @@ export const eventV2Schema = {
|
||||
"workspace.change.updated",
|
||||
"workspace.diff.recorded",
|
||||
"workspace.file.referenced",
|
||||
"auth.credentials.updated",
|
||||
"harness.starting",
|
||||
"harness.ready",
|
||||
"harness.exited",
|
||||
@@ -5192,6 +5260,28 @@ export const eventV2Schema = {
|
||||
}
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"eventType": {
|
||||
"const": "auth.credentials.updated"
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"sourceKind": {
|
||||
"const": "runner"
|
||||
},
|
||||
"priority": {
|
||||
"const": 0
|
||||
},
|
||||
"payload": {
|
||||
"$ref": "https://paperclip.dev/schemas/prp/v1/auth-credentials.schema.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
@@ -5432,7 +5522,8 @@ export const eventV3Schema = {
|
||||
"issue.status.decision.superseded",
|
||||
"run.terminal",
|
||||
"external_provider.dispatch_requested",
|
||||
"external_provider.operation_settled"
|
||||
"external_provider.operation_settled",
|
||||
"auth.credentials.updated"
|
||||
]
|
||||
},
|
||||
"schemaVersion": {
|
||||
@@ -5827,6 +5918,28 @@ export const eventV3Schema = {
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"eventType": {
|
||||
"const": "auth.credentials.updated"
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"sourceKind": {
|
||||
"const": "runner"
|
||||
},
|
||||
"priority": {
|
||||
"const": 0
|
||||
},
|
||||
"payload": {
|
||||
"$ref": "https://paperclip.dev/schemas/prp/v1/auth-credentials.schema.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"additionalProperties": true
|
||||
@@ -6099,6 +6212,7 @@ export const fixtureSchema = {
|
||||
} as const;
|
||||
|
||||
export const prpSchemaBundle = {
|
||||
"auth-credentials": authCredentialsSchema,
|
||||
"identity": identitySchema,
|
||||
"capabilities": capabilitiesSchema,
|
||||
"capabilities-v2": capabilitiesV2Schema,
|
||||
|
||||
@@ -4,4 +4,4 @@
|
||||
import equalModule from "ajv/dist/runtime/equal.js";
|
||||
import ucs2LengthModule from "ajv/dist/runtime/ucs2length.js";
|
||||
|
||||
"use strict";export const fixtureValidator: unknown = validate20;const schema31 = {"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://paperclip.dev/schemas/prp/v1/fixture.schema.json","title":"PRP scripted replay fixture","type":"object","required":["schema","fixtureVersion","protocolVersion","name","description","identity","capabilities","commands","events","result"],"properties":{"schema":{"const":"paperclip.prp.fixture.v1"},"fixtureVersion":{"const":1},"protocolVersion":{"enum":[1,2,3]},"name":{"type":"string","minLength":1,"maxLength":120},"description":{"type":"string","minLength":1,"maxLength":1000},"identity":{"$ref":"https://paperclip.dev/schemas/prp/v1/identity.schema.json"},"capabilities":{"oneOf":[{"$ref":"https://paperclip.dev/schemas/prp/v1/capabilities.schema.json"},{"$ref":"https://paperclip.dev/schemas/prp/v2/capabilities.schema.json"},{"$ref":"https://paperclip.dev/schemas/prp/v3/capabilities.schema.json"}]},"commands":{"type":"array","items":{"oneOf":[{"$ref":"https://paperclip.dev/schemas/prp/v1/command.schema.json"},{"$ref":"https://paperclip.dev/schemas/prp/v2/command.schema.json"},{"$ref":"https://paperclip.dev/schemas/prp/v3/command.schema.json"}]}},"events":{"type":"array","minItems":1,"items":{"oneOf":[{"$ref":"https://paperclip.dev/schemas/prp/v1/event.schema.json"},{"$ref":"https://paperclip.dev/schemas/prp/v2/event.schema.json"},{"$ref":"https://paperclip.dev/schemas/prp/v3/event.schema.json"}]}},"requests":{"type":"array","items":{"$ref":"https://paperclip.dev/schemas/prp/v1/request.schema.json"}},"result":{"$ref":"https://paperclip.dev/schemas/prp/v1/result.schema.json"}},"additionalProperties":true};const schema41 = {"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://paperclip.dev/schemas/prp/v1/capabilities.schema.json","title":"PRP negotiated capabilities","type":"object","required":["schema","sessionReusePolicy","driver","steer","interrupt","resume","runtimeRequests","structuredResult","typedEvents"],"properties":{"schema":{"const":"paperclip.prp.capabilities.v1"},"sessionReusePolicy":{"enum":["new_per_run","reuse_per_issue","reuse_per_workspace"]},"driver":{"type":"object","required":["kind","version"],"properties":{"kind":{"type":"string","minLength":1,"maxLength":80},"version":{"type":"string","minLength":1,"maxLength":80}},"additionalProperties":true},"steer":{"type":"boolean"},"interrupt":{"type":"boolean"},"resume":{"type":"boolean"},"runtimeRequests":{"type":"boolean"},"structuredResult":{"type":"boolean"},"typedEvents":{"type":"boolean"},"typedEventFamilies":{"type":"array","maxItems":64,"items":{"type":"object","required":["family","version","availability","detailLevel"],"properties":{"family":{"type":"string","minLength":1,"maxLength":160,"pattern":"^[a-z][a-z0-9_.-]*$"},"version":{"const":1},"availability":{"enum":["available","unsupported","policy_disabled"]},"detailLevel":{"enum":["summary","structured"]}},"additionalProperties":false}},"semanticTools":{"type":"object","required":["schema","schemaVersion","operations"],"properties":{"schema":{"const":"paperclip.prp.semantic_tools.v1"},"schemaVersion":{"const":1},"operations":{"type":"array","items":{"type":"object","required":["operationId","version","availability","redactionDisposition"],"properties":{"operationId":{"type":"string","minLength":1,"maxLength":160,"pattern":"^[A-Za-z0-9][A-Za-z0-9._:-]*$"},"version":{"const":1},"availability":{"enum":["available","denied","unsupported"]},"redactionDisposition":{"const":"digest_only"},"requiredClaims":{"type":"array","items":{"type":"string","minLength":1,"maxLength":160},"uniqueItems":true},"reasonCode":{"type":"string","minLength":1,"maxLength":160,"pattern":"^[a-z][a-z0-9_.:-]*$"}},"additionalProperties":true}}},"additionalProperties":true},"unsupported":{"type":"array","items":{"type":"string","minLength":1},"uniqueItems":true}},"additionalProperties":true};const schema47 = {"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://paperclip.dev/schemas/prp/v1/command.schema.json","title":"PRP runner command","type":"object","required":["schema","commandId","controllerSeq","type","issuedAt","payload"],"properties":{"schema":{"const":"paperclip.prp.command.v1"},"commandId":{"type":"string","minLength":1,"maxLength":160},"controllerSeq":{"type":"integer","minimum":1},"type":{"enum":["run.prepare","run.attach","session.open","turn.start","turn.steer","turn.interrupt","turn.stop","request.resolve","interaction.receipt","semantic_tool.result","session.snapshot","session.close","session.budget.increase","session.destroy","run.cancel","runner.drain","runner.suspend","runner.shutdown"]},"issuedAt":{"type":"string","format":"date-time"},"deadlineAt":{"type":"string","format":"date-time"},"precondition":{"type":"object","properties":{"runnerState":{"type":"array","items":{"type":"string"}},"runState":{"type":"array","items":{"type":"string"}},"sessionState":{"type":"array","items":{"type":"string"}},"activeTurnId"Line truncated
|
||||
"use strict";export const authCredentialsValidator: unknown = validate20;const schema31 = {"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://paperclip.dev/schemas/prp/v1/auth-credentials.schema.json","title":"PRP credential update notification","description":"Content-free evidence of changed credentials for the harness-auth binding in this normalized session. Credential-store detection does not prove an OAuth refresh succeeded.","type":"object","required":["schema","provider","bindingId","revision","detection"],"properties":{"schema":{"const":"paperclip.auth.credentials.updated.v1"},"provider":{"type":"string","minLength":1,"maxLength":160,"pattern":"^[A-Za-z0-9][A-Za-z0-9._:-]*$"},"bindingId":{"type":"string","minLength":1,"maxLength":160,"pattern":"^[A-Za-z0-9][A-Za-z0-9._:-]*$"},"revision":{"type":"integer","minimum":1,"maximum":9007199254740991},"detection":{"enum":["credential_store","native_hook"]}},"additionalProperties":false};const func1 = typeof ucs2LengthModule === "function" ? ucs2LengthModule : ucs2LengthModule.default;const pattern4 = new RegExp("^[A-Za-z0-9][A-Za-z0-9._:-]*$", "u");function validate20(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){/*# sourceURL="https://paperclip.dev/schemas/prp/v1/auth-credentials.schema.json" */;let vErrors = null;let errors = 0;const evaluated0 = validate20.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}if(data && typeof data == "object" && !Array.isArray(data)){if(data.schema === undefined){const err0 = {instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: "schema"},message:"must have required property '"+"schema"+"'"};if(vErrors === null){vErrors = [err0];}else {vErrors.push(err0);}errors++;}if(data.provider === undefined){const err1 = {instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: "provider"},message:"must have required property '"+"provider"+"'"};if(vErrors === null){vErrors = [err1];}else {vErrors.push(err1);}errors++;}if(data.bindingId === undefined){const err2 = {instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: "bindingId"},message:"must have required property '"+"bindingId"+"'"};if(vErrors === null){vErrors = [err2];}else {vErrors.push(err2);}errors++;}if(data.revision === undefined){const err3 = {instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: "revision"},message:"must have required property '"+"revision"+"'"};if(vErrors === null){vErrors = [err3];}else {vErrors.push(err3);}errors++;}if(data.detection === undefined){const err4 = {instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: "detection"},message:"must have required property '"+"detection"+"'"};if(vErrors === null){vErrors = [err4];}else {vErrors.push(err4);}errors++;}for(const key0 in data){if(!(((((key0 === "schema") || (key0 === "provider")) || (key0 === "bindingId")) || (key0 === "revision")) || (key0 === "detection"))){const err5 = {instancePath,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty: key0},message:"must NOT have additional properties"};if(vErrors === null){vErrors = [err5];}else {vErrors.push(err5);}errors++;}}if(data.schema !== undefined){if("paperclip.auth.credentials.updated.v1" !== data.schema){const err6 = {instancePath:instancePath+"/schema",schemaPath:"#/properties/schema/const",keyword:"const",params:{allowedValue: "paperclip.auth.credentials.updated.v1"},message:"must be equal to constant"};if(vErrors === null){vErrors = [err6];}else {vErrors.push(err6);}errors++;}}if(data.provider !== undefined){let data1 = data.provider;if(typeof data1 === "string"){if(func1(data1) > 160){const err7 = {instancePath:instancePath+"/provider",schemaPath:"#/properties/provider/maxLength",keyword:"maxLength",params:{limit: 160},message:"must NOT have more than 160 characters"};if(vErrors === null){vErrors = [err7];}else {vErrors.push(err7);}errors++;}if(func1(data1) < 1){const err8 = {instancePath:instancePath+"/provider",schemaPath:"#/properties/provider/minLength",keyword:"minLength",params:{limit: 1},message:"must NOT have fewer than 1 characters"};if(vErrors === null){vErrors = [err8];}else {vErrors.push(err8);}errors++;}if(!pattern4.test(data1)){const err9 = {instancePath:instancePath+"/provider",schemaPath:"#/properties/provider/pattern",keyword:"pattern",params:{pattern: "^[A-Za-z0-9][A-Za-z0-9._:-]*$"},message:"must match pattern \""+"^[A-Za-z0-9][A-Za-z0-9._:-]*$"+"\""};if(vErrors === null){vErrors = [err9];}else {vErrors.push(err9);}errors++;}}else {const err10 = {instancePath:instancePath+"/provider",schemaPath:"#/properties/provider/type",keyword:"type",params:{type: "string"},message:"must be string"};if(vErrors === null){vErrors = [err10];}else {vErrors.push(err10);}errors++;}}if(data.bindingId !== undefined){let data2 = data.binLine truncated
|
||||
@@ -2,6 +2,7 @@ import type { ErrorObject, ValidateFunction } from "ajv/dist/2020.js";
|
||||
import type { FromSchema } from "json-schema-to-ts";
|
||||
|
||||
import {
|
||||
authCredentialsSchema,
|
||||
capabilitiesSchema,
|
||||
capabilitiesV2Schema,
|
||||
capabilitiesV3Schema,
|
||||
@@ -21,6 +22,7 @@ import {
|
||||
terminalSchema,
|
||||
} from "./generated/schema-bundle.js";
|
||||
import {
|
||||
authCredentialsValidator as standaloneAuthCredentialsValidator,
|
||||
eventValidator as standaloneEventV1Validator,
|
||||
eventV2Validator as standaloneEventV2Validator,
|
||||
eventV3Validator as standaloneEventV3Validator,
|
||||
@@ -36,13 +38,18 @@ export const PRP_FIXTURE_SCHEMA = "paperclip.prp.fixture.v1";
|
||||
|
||||
type TerminalReferences = [typeof stopReasonSchema];
|
||||
type EventReferences = [
|
||||
typeof authCredentialsSchema,
|
||||
typeof semanticToolSchema,
|
||||
typeof stopReasonSchema,
|
||||
typeof terminalSchema,
|
||||
typeof resultSchema,
|
||||
];
|
||||
type EventV2References = [typeof sessionGoalSchema];
|
||||
type EventV2References = [typeof sessionGoalSchema, typeof authCredentialsSchema];
|
||||
type CapabilitiesV2References = [typeof sessionGoalSchema];
|
||||
export type PrpAuthCredentialsUpdated = FromSchema<typeof authCredentialsSchema>;
|
||||
export function isPrpAuthCredentialsUpdated(value: unknown): value is PrpAuthCredentialsUpdated {
|
||||
return (standaloneAuthCredentialsValidator as ValidateFunction<PrpAuthCredentialsUpdated>)(value);
|
||||
}
|
||||
export type PrpIdentity = FromSchema<typeof identitySchema>;
|
||||
export type PrpCapabilities = FromSchema<typeof capabilitiesSchema>;
|
||||
export type PrpCapabilitiesV2 = FromSchema<
|
||||
|
||||
@@ -79,6 +79,7 @@ export interface TypedEventFamilyCapability {
|
||||
}
|
||||
|
||||
export const CANONICAL_PROVIDER_EVENT_TYPES = [
|
||||
"auth.credentials.updated",
|
||||
"harness.diagnostic",
|
||||
"plan.updated",
|
||||
"tool.execution.started",
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"commandDigest": "sha256:38abf359adeef43f1f19230245c6e2051c55fdd79571882ef6f00b7cb2958d93",
|
||||
"declaration": {
|
||||
"schema": "paperclip.acpx_profile_declaration.v1",
|
||||
"agent": "copilot",
|
||||
"agentProfileVersion": 19,
|
||||
"acpxVersion": "0.13.1",
|
||||
"agentServerVersion": "1.0.88",
|
||||
"protocolPolicyRevision": "copilot-agent-manual-v1",
|
||||
"acpxPatchSha256": "00d6af17216cb0cad902b48633eb19bf0ec6b05837a984cb24661fca593f09c1",
|
||||
"policySha256": "a4be69be43db84052560420a3ca546a665c9165573c24d543eb33d144ba138a3",
|
||||
"distributionSourceSha256": "c0a65e247fc47b263bd369a3d5ab505c4b323d4e6493be8a9ecbeb0e9dbb9107",
|
||||
"agentFilesBinding": "registered-runtime-context-v1",
|
||||
"systemInstructionDelivery": "COPILOT_HOME/copilot-instructions.md:replace-under-lifetime-lease-before-launch:v1",
|
||||
"sharedRuntimeContract": "paperclip.acpx-runtime-contract.v1",
|
||||
"innerDistributionSourceSha256": "9bb08347eed01f1ab44e065c8b06ead9be3a25973d6e6329dc4c0a099096279a",
|
||||
"upstreamAppSha256": "7b48282a19b5b0814a0c96ad5e3a125173d792cc55f9525b2effea962f6063c0",
|
||||
"patchedAppSha256": "61f8eebe0c30cc03b311c6818b2acb158a6d16ca58c8bfac5ebd42db095c2679",
|
||||
"messageIdentityContract": "copilot-native-message-id-v1",
|
||||
"ownedDistributionDelivery": "COPILOT_CLI_DIST_DIR:lease-owned-guarded-inner-distribution:v1",
|
||||
"permissionContextContract": "copilot-edit-permission-context-v1",
|
||||
"permissionContextSourceSha256": "fe1bb611bea289d81b1c7c973fbb01b93de133a7caa8fe78b7ff4ee1f485b224",
|
||||
"permissionAdapterSourceSha256": "49421a779c76e286ce65d75052026eab9630b1995af9ccf045a2d43d284633ce",
|
||||
"permissionLocationsSourceSha256": "f39a81da395b6e23aa2a1a45572a28846e5e81bfd3d764d9a456f74a79c752e9",
|
||||
"permissionRedactionSourceSha256": "ad6770c69269087951790e2e87e22ac088e3d432769adf17ebc865ed512e6c4f",
|
||||
"permissionClassifierSourceSha256": "1161eabd82e26133e3b3db3ab567f65d52808b03f176e93497e02c8330349fb4",
|
||||
"permissionIdentitySourceSha256": "770b47305e571a81f344883057d0e4a482a1cd59ac77d045836593a8e739deb1",
|
||||
"semanticToolReceiptContract": "paperclip.semantic_tool_receipt.v2",
|
||||
"semanticReceiptSourceSha256": "b2795726b2234a663fec1a6ca11f0551ae69882fe9e82aa39686e952d036e791",
|
||||
"semanticBridgeSourceSha256": "cf136da18e2cdbefae8e01d23d2c93f64eb7aebccaec938e84c2887c888f87ee",
|
||||
"toolEvidenceSourceSha256": "49d7d09eb6957e596a173b0afd763544afe582f0c1f05cc0992fe51916a8fdb3",
|
||||
"semanticNormalizedInputContract": "validated-forwarded-input-commit-v1",
|
||||
"semanticSidecarSourceSha256": "91629734a80f0d32295cbce2c573b32af9e345f45302ff4525c269f66811aa06",
|
||||
"semanticDirectDriverSourceSha256": "2b7b7eaadee658312816ecdcbcb311ce491521fedf39e2ecb571036c36ff7b8e",
|
||||
"semanticValidationSourceSha256": "02fbb92681c78c5de5d2f1aae25aabc25a0e5df6b0ff4baccac652192a8da975",
|
||||
"semanticNormalizationSourceSha256": "8b628b82e8eacc91cdcc6fdca2210ba4cf282f01e9c6f74e95ff271655b5047e",
|
||||
"semanticCompletionContractSourceSha256": "fa2b0c81cb9a62965839c905db81b930794774d8d557a01bce077dae5830b594",
|
||||
"semanticValidatorsSourceSha256": "0703401404effcd5d431b5178bde78e9f63f797a39389add22add7c33986f75c",
|
||||
"semanticSchemaBundleSourceSha256": "95551282468ec16bec4c3ddd0a77a9b2b0e044d7ff018354d4229c3f26e3e228",
|
||||
"semanticSidecarProtocolSourceSha256": "334b67857bd81e9924186890258cb2ad41f92b1ef68ec60fa5c5d9fbb277673c",
|
||||
"semanticSidecarReceiptCommitContract": "correlated-tool-resolve-v1"
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ async function fixture(relativePath) {
|
||||
|
||||
test("all schema IDs are unique and all external references resolve", async () => {
|
||||
const schemas = await loadSchemaCatalog(resolve(protocolRoot, "schemas"));
|
||||
assert.equal(schemas.length, 28);
|
||||
assert.equal(schemas.length, 29);
|
||||
assert.doesNotThrow(() => compileProtocolValidators(schemas));
|
||||
});
|
||||
|
||||
|
||||
@@ -41,6 +41,15 @@ function receiptNotice(version: 1 | 2 = 1): Record<string, any> {
|
||||
const receiptSchemaValue = (notice: Record<string, any>) => notice.details.find((detail: any) => detail.name === "schema").value;
|
||||
|
||||
describe("redaction", () => {
|
||||
it.each([1, 2, 3] as const)("preserves credential update metadata and masks adjacent secrets in PRP v%s", version => {
|
||||
const event = { schema: `paperclip.prp.event.v${version}`, schemaVersion: version,
|
||||
eventType: "auth.credentials.updated", payload: { schema: "paperclip.auth.credentials.updated.v1",
|
||||
provider: "codex", bindingId: "harness-auth", revision: 1, detection: "credential_store" } };
|
||||
expect(redactEventPayload({ prpEvent: event })).toEqual({ prpEvent: event });
|
||||
expect(redactEventPayload({ prpEvent: { ...event, payload: { ...event.payload, refresh_token: "secret-sentinel" } } }))
|
||||
.toEqual({ prpEvent: { ...event, payload: { ...event.payload, refresh_token: REDACTED_EVENT_VALUE } } });
|
||||
});
|
||||
|
||||
it("preserves the actual Copilot receipt producer discriminator through nested durable redaction", () => {
|
||||
const events: Array<Record<string, any>> = [];
|
||||
const projector = createCopilotToolEvidence({ sessionId: "session", turnId: "turn", workingDirectory: "/workspace",
|
||||
|
||||
@@ -50,6 +50,7 @@ const PAPERCLIP_SCHEMA_FIELDS = new Set(["schema", "runtimeSchema"]);
|
||||
export const PAPERCLIP_PUBLIC_SCHEMA_IDS = new Set([
|
||||
"paperclip.artifact.generated.v1",
|
||||
"paperclip.artifact.viewed.v1",
|
||||
"paperclip.auth.credentials.updated.v1",
|
||||
"paperclip.capability-discovery.v1",
|
||||
"paperclip.capability.authorization-record.v1",
|
||||
"paperclip.capability.control-plane.v1",
|
||||
@@ -213,6 +214,7 @@ export const PRP_V1_EVENT_TYPES = new Set([
|
||||
"workspace.change.updated",
|
||||
"workspace.diff.recorded",
|
||||
"workspace.file.referenced",
|
||||
"auth.credentials.updated",
|
||||
"harness.starting",
|
||||
"harness.ready",
|
||||
"harness.exited",
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { afterAll, beforeAll, expect, it } from "vitest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { agents, companies, createDb, heartbeatRunEvents, heartbeatRuns } from "@paperclipai/db";
|
||||
import type { PrpEvent } from "../../vendor/paperclip-runner/index.js";
|
||||
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
|
||||
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
|
||||
import { appendNativeCredentialUpdate } from "./native-credential-updates.js";
|
||||
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID();
|
||||
const runnerInstanceId = randomUUID(), normalizedSessionId = randomUUID();
|
||||
const event: PrpEvent = {
|
||||
schema: "paperclip.prp.event.v3", schemaVersion: 3, eventType: "auth.credentials.updated",
|
||||
sourceKind: "runner", sourceInstanceId: runnerInstanceId, sourceEventId: "credential_update_1", sourceSeq: 9,
|
||||
runId, normalizedSessionId, priority: 0, emittedAt: "2026-10-15T19:00:00.000Z",
|
||||
payload: { schema: "paperclip.auth.credentials.updated.v1", provider: "codex",
|
||||
bindingId: "harness-auth", revision: 1, detection: "credential_store" },
|
||||
};
|
||||
const binding = { companyId, agentId, runnerInstanceId, normalizedSessionId };
|
||||
beforeAll(async () => {
|
||||
database = await startEmbeddedPostgresTestDatabase("paperclip-credential-updates-");
|
||||
db = createDb(database.connectionString);
|
||||
await db.insert(companies).values({ id: companyId, name: "Credential delivery", issuePrefix: "CRED" });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Observer", adapterType: "codex_local" });
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "succeeded", runtimeMode: "native",
|
||||
nativeSessionId: normalizedSessionId, runnerInstanceId });
|
||||
}, 60_000);
|
||||
afterAll(async () => { await db?.$client.end(); await database?.cleanup(); });
|
||||
|
||||
it("persists idle updates idempotently without colliding with normalized events", async () => {
|
||||
await appendHeartbeatRunEvent(db, { companyId, agentId, runId, eventType: "item.completed", nativeSource: {
|
||||
sourceInstanceId: runnerInstanceId, sourceEventId: "normalized-event", sourceSeq: event.sourceSeq,
|
||||
protocolSchemaVersion: 3, canonicalPayload: { normalized: true },
|
||||
} });
|
||||
await appendNativeCredentialUpdate(db, { ...binding, event });
|
||||
await appendNativeCredentialUpdate(db, { ...binding, event: structuredClone(event) });
|
||||
const rows = await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, runId));
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows.find(row => row.eventType === event.eventType)).toMatchObject({
|
||||
sourceInstanceId: `${runnerInstanceId}:credentials`, sourceEventId: `credentials:${event.sourceEventId}`,
|
||||
payload: { prpEvent: event },
|
||||
});
|
||||
await expect(appendNativeCredentialUpdate(db, { ...binding, event: {
|
||||
...event, payload: { ...event.payload, revision: 2 },
|
||||
} })).rejects.toThrow("native_event_replay_conflict");
|
||||
});
|
||||
|
||||
it.each(["companyId", "agentId", "runnerInstanceId", "normalizedSessionId"] as const)(
|
||||
"rejects credential updates outside the bound %s", async field => {
|
||||
await expect(appendNativeCredentialUpdate(db, { ...binding, [field]: randomUUID(), event }))
|
||||
.rejects.toThrow("native_credential_update_binding_mismatch");
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects unbound runs and credential payloads with secret fields", async () => {
|
||||
await expect(appendNativeCredentialUpdate(db, { ...binding, event: { ...event, runId: randomUUID() } }))
|
||||
.rejects.toThrow("native_credential_update_binding_mismatch");
|
||||
await expect(appendNativeCredentialUpdate(db, { ...binding, event: { ...event,
|
||||
payload: { ...event.payload, access_token: "synthetic-secret" },
|
||||
} })).rejects.toThrow("native_credential_update_binding_mismatch");
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { heartbeatRuns, type Db } from "@paperclipai/db";
|
||||
import { validatePrpEvent, type PrpEvent } from "../../vendor/paperclip-runner/index.js";
|
||||
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
|
||||
|
||||
export async function appendNativeCredentialUpdate(db: Db, input: {
|
||||
companyId: string;
|
||||
agentId: string;
|
||||
normalizedSessionId: string;
|
||||
runnerInstanceId: string;
|
||||
event: PrpEvent;
|
||||
}): Promise<void> {
|
||||
const parsed = validatePrpEvent(input.event);
|
||||
if (!parsed.ok || parsed.event.eventType !== "auth.credentials.updated"
|
||||
|| parsed.event.sourceKind !== "runner"
|
||||
|| parsed.event.sourceInstanceId !== input.runnerInstanceId
|
||||
|| parsed.event.normalizedSessionId !== input.normalizedSessionId) {
|
||||
throw new Error("native_credential_update_binding_mismatch");
|
||||
}
|
||||
const event = parsed.event;
|
||||
await db.transaction(async tx => {
|
||||
const [run] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns)
|
||||
.where(and(eq(heartbeatRuns.id, event.runId), eq(heartbeatRuns.companyId, input.companyId),
|
||||
eq(heartbeatRuns.agentId, input.agentId), eq(heartbeatRuns.nativeSessionId, input.normalizedSessionId),
|
||||
eq(heartbeatRuns.runnerInstanceId, input.runnerInstanceId)))
|
||||
.for("update").limit(1);
|
||||
if (!run) throw new Error("native_credential_update_binding_mismatch");
|
||||
await appendHeartbeatRunEvent(tx as unknown as Db, {
|
||||
companyId: input.companyId,
|
||||
agentId: input.agentId,
|
||||
runId: event.runId,
|
||||
eventType: event.eventType,
|
||||
stream: "system",
|
||||
level: "info",
|
||||
payload: { prpEvent: event as unknown as Record<string, unknown> },
|
||||
nativeSource: {
|
||||
sourceInstanceId: `${event.sourceInstanceId}:credentials`,
|
||||
sourceEventId: `credentials:${event.sourceEventId}`,
|
||||
sourceSeq: event.sourceSeq,
|
||||
protocolSchemaVersion: event.schemaVersion,
|
||||
canonicalPayload: event as unknown as Record<string, unknown>,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -140,6 +140,7 @@ import {
|
||||
} from "@paperclipai/db";
|
||||
import { PaperclipControlPlanePort } from "./paperclip-control-plane-port.js";
|
||||
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
|
||||
import { appendNativeCredentialUpdate } from "./native-credential-updates.js";
|
||||
import { nativeSha256 } from "./canonical.js";
|
||||
import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
|
||||
import { createAssignedMcpTools, getAssignedMcpGateway } from "./assigned-mcp-tools.js";
|
||||
@@ -12945,6 +12946,13 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
codexTransportFactory: (recoveryContext) =>
|
||||
createRunnerdCodexTransport({
|
||||
onSpawn: input.onSpawn,
|
||||
onCredentialsUpdated: (event) => appendNativeCredentialUpdate(input.db, {
|
||||
companyId: input.execution.binding.companyId,
|
||||
agentId: input.execution.binding.agentId,
|
||||
normalizedSessionId: nativeSessionKey(input.execution),
|
||||
runnerInstanceId: effectiveRunnerInstanceId,
|
||||
event,
|
||||
}),
|
||||
provider:
|
||||
input.execution.provider.kind === "codex"
|
||||
? "codex"
|
||||
|
||||
@@ -107,6 +107,7 @@ export const TASK_PROTOCOL_EVENT_SURFACE_REGISTRY: Readonly<Record<string, TaskP
|
||||
...Object.fromEntries(runnerLifecycleEvents.map((eventType) => [eventType, folded("turn", "Routine lifecycle transitions are summarized by the run turn and composer state.")])),
|
||||
...Object.fromEntries(diagnosticEvents.map((eventType) => [eventType, folded("system_notice", "Actionable failure text is folded into the run or system notice.")])),
|
||||
...Object.fromEntries(itemEvents.map((eventType) => [eventType, folded("conversation_or_tool", "Item payloads normalize into messages, reasoning, tools, diffs, or usage." )])),
|
||||
"auth.credentials.updated": debugOnly("run_debug", "Credential updates notify the host and remain in run details."),
|
||||
"sandbox.metric": debugOnly("run_debug", "Sandbox telemetry is available in run details, not the primary task thread."),
|
||||
...Object.fromEntries(mcpLifecycleEvents.map((eventType) => [eventType, debugOnly("run_debug", "MCP application transport lifecycle remains in run details unless it produces an actionable failure.")])),
|
||||
...Object.fromEntries(governanceEvents.map((eventType) => [eventType, folded("governance", "Authoritative task status, attention, and interaction records own this state." )])),
|
||||
|
||||
Reference in new issue
Block a user