Repository navigation
🧑✈️ refactor: Establish Execution Context at Run Entry - #18255
Conversation
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues block approval of the execution-context refactor.
No open issues 🎉
What changed in this PR
This PR centralizes run identity and origin in a frozen ExecutionContext, built at entry points and passed to schedule authorization and tool loading. It builds on the remote API sign-in safeguards in #18058 and supports the broader autonomous-agent authority work in #13824 without changing stored data or API contracts.
Changes:
- Add context builders for fresh schedules, resumed jobs, and remote API runs.
- Replace repeated schedule identity extraction and propagated
unattendedflags with context-based decisions. - Update documentation and tests for context propagation, trusted identity, legacy jobs, and background-worker admission.
| File | Description |
|---|---|
| packages/api/src/schedules/README.md | Document context creation, propagation, and restoration. |
| packages/api/src/schedules/mcp.ts | Project schedule token identity from execution context. |
| packages/api/src/schedules/context.ts | Remove the replaced schedule restoration helper. |
| packages/api/src/schedules/context.spec.ts | Adapt token identity tests to context builders. |
| packages/api/src/schedules/bearer.ts | Derive bearer identity and execution stage from context. |
| packages/api/src/schedules/bearer.spec.ts | Update resumed bearer tests to pass context. |
| packages/api/src/schedules/authorization/runtime.ts | Consume execution context for schedule authorization. |
| packages/api/src/schedules/authorization/runtime.spec.ts | Update authorization fixtures and resume coverage. |
| packages/api/src/schedules/authorization/receipt.spec.ts | Pass context in preparation-failure coverage. |
| packages/api/src/agents/responses/worker.runtime.spec.ts | Test trusted background-worker classification. |
| packages/api/src/agents/responses/runtime.ts | Expose background admission instead of unattended state. |
| packages/api/src/agents/index.ts | Export the authority module. |
| packages/api/src/agents/authority/index.ts | Export execution-context helpers. |
| packages/api/src/agents/authority/context.ts | Define immutable contexts, builders, and projections. |
| packages/api/src/agents/authority/context.spec.ts | Test builders, identity checks, and context projections. |
| api/server/services/ToolService.js | Derive unattended behavior at tool-loading boundaries. |
| api/server/services/Endpoints/agents/initialize.spec.js | Supply execution context in initializer tests. |
| api/server/services/Endpoints/agents/initialize.js | Forward context to schedule consumers. |
| api/server/services/__tests__/ToolService.spec.js | Use remote context in unattended sign-in tests. |
| api/server/controllers/agents/resume.js | Restore context from saved job metadata. |
| api/server/controllers/agents/responses.js | Build and propagate remote Responses context. |
| api/server/controllers/agents/request.js | Build schedule context before initialization. |
| api/server/controllers/agents/openai.js | Build and propagate chat-completions context. |
| api/server/controllers/agents/__tests__/resume.spec.js | Assert restored context reaches initialization. |
| api/server/controllers/agents/__tests__/responses.unit.spec.js | Assert Responses context reaches tool loading. |
| api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js | Test verified versus copied schedule metadata. |
| api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js | Add the context-builder mock. |
| api/server/controllers/agents/__tests__/openai.spec.js | Assert chat-completions context reaches tool loading. |
Review effort: Balanced
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3ab668a930
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| upstreamTokenProvider: suppliedUpstreamTokenProvider, | ||
| upstreamTokenProviderResolver, | ||
| }) { | ||
| const unattended = isUnattended(executionContext); |
There was a problem hiding this comment.
Keep unattended-policy derivation out of legacy CJS
Deriving unattended inside loadToolDefinitionsWrapper and loadToolsForExecution adds new backend policy orchestration to legacy CJS. The root AGENTS.md explicitly prohibits adding logic, including service calls, to existing /api CJS modules and requires those modules to remain thin wiring into TypeScript. Move the execution-context-aware tool-loading boundary into packages/api and have these adapters delegate to it, rather than introducing the derivation independently in both legacy functions.
AGENTS.md reference: AGENTS.md:L80-L84
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 8b00f40.
api/server/services/ToolService.js and its spec are no longer changed by this PR: both are back to what dev has, and the tool-loading functions keep taking the plain unattended argument they took before.
Whether a run is unattended is now decided in TypeScript, in the context builders (packages/api/src/agents/authority/context.ts): ExecutionContext.unattended is !background for a remote run and false for a schedule. isUnattended is gone. The two remote controllers pass executionContext.unattended to tool loading where they used to pass the literal true (chat completions) or the Responses runtime's answer.
Evidence: context.spec.ts covers the value for each source, including a resumed schedule. openai.spec.js and responses.unit.spec.js each make the builder answer false and check that false is what reaches loadAgentTools; both fail if the controller passes a fixed value.
Each consumer of a scheduled run's identity (the host token resolver, the scheduled MCP authority and the resource-bearer host) read the trigger body and the restored job for itself, and the remote agent API carried a separate `unattended` flag through tool loading. The entry point now builds one frozen ExecutionContext: the chat controller from the verified schedule trigger, the resume host from the saved job, and the remote controllers from the run envelope. The initializer and tool loading receive it as an argument. The schedule consumers project their identity from it, and `unattended` is derived from it at the tool-loading boundary. No client or model input sets any field.
3ab668a to
8b00f40
Compare
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
/quality risk scopes=api |
Quality reportGate: open. The selected checks completed. Scores and risk levels are advisory. Status: completed (success). Actions run, attempt 1.
Change riskTakeaway: Every changed line has a test. Highest CRAP among changed functions:
Refactor hints (highest CRAP first)
2 more functions below the threshold (or cut for size) are in report.md. CRAP = complexity² × (1 − coverage)³ + complexity Jobs (1)
All data ( The gate opens only when the workflow, source selection, tooling verification, and every report job succeed. A report job fails on a failed test in its workspace's own Jest run, a tool error, a job timeout, or an incomplete mutation report, including a mutation shard that reaches its execution budget. A cancelled workflow keeps the gate closed. Scores are advisory. A change-risk file marked incomplete or unavailable, for example by a failed |
Summary
Who a run acts for, and why it exists, was worked out separately by each piece of code that needed it. Three schedule consumers (the host token resolver, the scheduled MCP authority and the resource-bearer host) each read the trigger body and the restored job for themselves, with slightly different rules. The remote agent API carried its own
unattendedflag through tool loading, added in #18058.This PR builds that answer once, where the run enters, as a frozen
ExecutionContext, and passes it down as an argument. The chat controller builds it from the verified schedule trigger, the resume host from the saved job, and the remote controllers from the run envelope. The schedule consumers project their identity from it. The context also says whether the run is unattended, decided once in the builder; the remote controllers pass that answer to tool loading where they used to pass their own.Behaviour is unchanged, with one deliberate unification: a schedule trigger whose
agent_idis a blank string now yields no schedule identity in all three consumers. Before, the resource-bearer host accepted any string while the token resolver required a non-blank one. A non-stringagent_idis likewise treated as absent everywhere, where the authority check used to refuse it outright for an unenrolled schedule. The trigger host copiesagent_idfrom an envelope field validated as a string (requireStringinagents/triggers/envelope.ts), so no real fire takes either path.This is the second step of giving scheduled chats and API-triggered agents one explicit authority model, after #18058. Related to #13824.
How it works
Each entry point builds it and hands it on:
The schedule consumers no longer read identity from the request. A caller that passes no context gets no schedule identity, and the authority check then refuses with
binding_mismatch. The trigger is still read in exactly one place,createScheduleExecutionContext, and still only from a request the trigger host verified.Tool loading and the MCP layer keep taking the narrow
unattendedboolean. They do not need to know why a run is unattended, so neither imports the agents-layer type, andapi/server/services/ToolService.jsis not changed by this PR.ScheduledTokenContext, the type host credential providers receive, is unchanged; it is now a projection of the execution context. A resumed legacy job that cannot prove both its root agent and its tenant still restores, without an agent, and so still cannot claim a minting identity.The context holds only what code reads today. Caller identity, run and idempotency ids and delegation references are left for the slices that consume them. The owning-tool agent id from #18113 is a different value (it changes per subagent) and stays where it is.
Type of change
Testing
Tested environments/configuration: WSL2, Node.js 24. No external services.
Automated tests:
packages/api/src/agents/authority/context.spec.ts(new): each builder, the forged-body and wrong-owner refusals, the legacy-job case,unattendedfor each source, and the schedule projection.packages/api/src/schedules/context.spec.ts,bearer.spec.ts,authorization/runtime.spec.ts,authorization/receipt.spec.ts: the existing schedule identity tests now pass the context the way the controller and resume host do. Their expectations are unchanged.packages/api/src/agents/responses/worker.runtime.spec.ts: only a worker-admitted Responses run isbackground, whatever the caller sends.api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js: the chat controller passes the schedule context for a verified trigger and none for an ordinary request that copies the trigger body.api/server/controllers/agents/__tests__/resume.spec.js,api/server/services/Endpoints/agents/initialize.spec.js: each entry point and consumer receives the expected context.api/server/controllers/agents/__tests__/openai.spec.js,responses.unit.spec.js: tool loading is told the run is unattended, and is told what the context says, not a fixed answer (the builder is made to answerfalseand that is what reaches tool loading).Each wiring point was broken in turn and a test confirmed to fail before it was restored.
npx tsc --noEmitinpackages/apiis clean.Risk / compatibility
The identity a scheduled run binds to is security-relevant, so the risk is a path that used to derive it from the request and now receives nothing. The only production callers of the three schedule consumers are in
createInitializeClient, which is reached from the chat and resume controllers, and both now pass the context. A missed caller fails closed.Scheduled execution end to end is covered by the mock e2e lane (
e2e/specs/mock/schedules-execution.spec.ts), which I did not run locally.No config, schema, stored-data or wire change. Saved jobs restore from the same metadata fields as before.