Skip to content

🧑‍✈️ refactor: Establish Execution Context at Run Entry - #18255

Merged
danny-avila merged 2 commits into
devfrom
danny-avila/execution-context
Nov 18, 2026
Merged

danny-avila merged 2 commits into
devfrom
danny-avila/execution-context

Conversation

@danny-avila

@danny-avila danny-avila commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

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 unattended flag 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_id is 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-string agent_id is likewise treated as absent everywhere, where the authority check used to refuse it outright for an unenrolled schedule. The trigger host copies agent_id from an envelope field validated as a string (requireString in agents/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

packages/api/src/agents/authority/
└── context.ts
    ├── createScheduleExecutionContext(req)       # fresh occurrence, from the verified trigger
    ├── restoreExecutionContext(req, jobMetadata)  # resumed run, from the saved job
    ├── createRemoteExecutionContext({...})        # chat completions and Responses
    └── toScheduledTokenContext(context)           # identity the schedule hosts bind to
export interface ExecutionContext {
  readonly principal: ExecutionPrincipal; // userId, tenantId?, role?
  readonly agentId?: string;              // root agent the run was admitted for
  readonly source: ExecutionSource;       // schedule { id, manual, resumed } | remote_api { protocol, background }
  readonly unattended: boolean;           // a remote run with no stream to follow; false for a schedule
}

Each entry point builds it and hands it on:

AgentController (fresh fire)   createScheduleExecutionContext(req)
ResumeAgentController          restoreExecutionContext(req, job.metadata)
  initializeClient({ executionContext })
    createScheduleUpstreamTokenProviderResolver   # was: read trigger body, or restoredContext
    initializeWithScheduleMCPExecution            # was: read trigger body, restoredContext, restoredJob
    initializeWithScheduledMCPBearer              # was: read trigger body, or restoredContext

OpenAIChatCompletionController createRemoteExecutionContext({ background: false })
executeResponse                createRemoteExecutionContext({ background: responseRuntime.background })
  loadAgentTools / loadToolsForExecution({ unattended: executionContext.unattended })
                                                  # was: `unattended: true`, or the Responses runtime's own answer

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 unattended boolean. They do not need to know why a run is unattended, so neither imports the agents-layer type, and api/server/services/ToolService.js is 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

  • Refactor

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, unattended for 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 is background, 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 answer false and 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 --noEmit in packages/api is 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.

@danny-avila
danny-avila added this pull request to stack #18263 November 17, 2026 15:27
@lia-by-librechat lia-by-librechat Bot changed the title 🧭 refactor: Build One Execution Context Where a Run Enters 🧑‍✈️ refactor: Establish Execution Context at Run Entry Nov 17, 2026
@danny-avila
danny-avila marked this pull request as ready for review November 18, 2026 11:06
Copilot AI balanced review requested due to automatic review settings November 18, 2026 11:06
@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review 3ab668a

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 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 unattended flags 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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T12:10:03.007437Z 8b00f40 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread api/server/services/ToolService.js Outdated
upstreamTokenProvider: suppliedUpstreamTokenProvider,
upstreamTokenProviderResolver,
}) {
const unattended = isUnattended(executionContext);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@danny-avila
danny-avila force-pushed the danny-avila/execution-context branch from 3ab668a to 8b00f40 Compare November 18, 2026 12:07
@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review 8b00f40

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 8b00f40b86

ℹ️ 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".

@danny-avila

Copy link
Copy Markdown
Collaborator Author

/quality risk scopes=api

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Quality report

Gate: open. The selected checks completed. Scores and risk levels are advisory.

Status: completed (success). Actions run, attempt 1.

  • Commit: 8b00f40b86fd1ed3fd57aa032ff8e5cdbcfc74ab
  • Requested by: @danny-avila
  • Check: risk
  • Scopes: api
  • Static mutants: off (not used by change risk)
  • Change risk: api
  • Mutation testing (experimental, data-schemas only): none

Change risk

Takeaway: Every changed line has a test. Highest CRAP among changed functions: (anonymous) at packages/api/src/schedules/authorization/runtime.ts:131, CRAP 70.9 with 84% coverage.

Workspace Files measured Incomplete Unavailable Changed lines with no test Highest CRAP
api 8 of 8 0 0 0 70.9

Refactor hints (highest CRAP first)

Function Complexity Coverage CRAP Location
(anonymous) 57 84% 70.9 packages/api/src/schedules/authorization/runtime.ts:131
prepareScheduledMCPBearer 32 95% 32.1 packages/api/src/schedules/bearer.ts:494
createResponseExecutionRuntime 21 90% 21.4 packages/api/src/agents/responses/runtime.ts:157
restoreExecutionContext 10 100% 10.0 packages/api/src/agents/authority/context.ts:93
toScheduledTokenContext 6 100% 6.0 packages/api/src/agents/authority/context.ts:159
createScheduleExecutionContext 5 100% 5.0 packages/api/src/agents/authority/context.ts:60
createRemoteExecutionContext 4 100% 4.0 packages/api/src/agents/authority/context.ts:123
getScheduleSource 3 100% 3.0 packages/api/src/agents/authority/context.ts:147
principalOf 2 100% 2.0 packages/api/src/agents/authority/context.ts:52
toolContext 2 100% 2.0 packages/api/src/agents/responses/runtime.ts:818

2 more functions below the threshold (or cut for size) are in report.md.

CRAP = complexity² × (1 − coverage)³ + complexity

Jobs (1)
Check Result
Change risk (api) success

All data (quality-report artifact) · Run page

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 api/ source-alias suite, does not close the gate.

@danny-avila
danny-avila merged commit ff522e0 into dev Nov 18, 2026
58 checks passed
@danny-avila
danny-avila deleted the danny-avila/execution-context branch November 18, 2026 12:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants