Skip to content

[codex] Add agent run context - #91

Merged
delete-cloud merged 4 commits into
mainfrom
codex-run-context-pr2
May 2, 2026
Merged

delete-cloud merged 4 commits into
mainfrom
codex-run-context-pr2

Conversation

@delete-cloud

@delete-cloud delete-cloud commented May 2, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • add agentkit AgentRunContext and ContextBudget runtime primitives
  • attach AgentRunContext to PipelineContext and populate it from create_agent/create_child_pipeline
  • pass child agent identity and parent run linkage into subagent child pipeline creation while keeping provider/model metadata in existing config/session runtime fields

Verification

  • uv run pytest tests/agentkit tests/coding_agent/test_bootstrap.py tests/coding_agent/tools/test_subagent.py tests/coding_agent/plugins/test_core_tools.py tests/ui/test_session_manager_runtime.py tests/ui/test_execution_binding.py -q
  • uv run basedpyright src/agentkit/runtime src/coding_agent/app.py src/coding_agent/tools/subagent.py tests/agentkit/runtime/test_run_context.py tests/coding_agent/test_bootstrap.py tests/coding_agent/tools/test_subagent.py --level error
  • uv run python -m compileall -q src tests
  • git diff --check

Summary by CodeRabbit

  • New Features

    • Added per-run context: session/run/agent identity, immutable trace metadata, child-run derivation, and per-run token budget.
    • Pipeline and agent creation now accept and propagate run-context overrides and trace metadata; subagent tooling forwards child run identity and merged metadata.
  • Tests

    • Added extensive tests for run-context construction, defensive metadata handling, child derivation, bootstrap integration, and subagent behavior.

@coderabbitai

coderabbitai Bot commented May 2, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds immutable runtime dataclasses (ContextBudget, AgentRunContext) and re-exports them; threads an optional run_context into PipelineContext; extends pipeline creation to build/propagate AgentRunContext; forwards child run identity and merged trace_metadata during subagent dispatch; adds tests for these behaviours.

Changes

Runtime context + propagation

Layer / File(s) Summary
Data Shape
coding-agent/src/agentkit/runtime/context.py
Adds ContextBudget and AgentRunContext dataclasses with validation rules; AgentRunContext.derive_child(...) sets parent_run_id and merges trace_metadata.
Module Exports
coding-agent/src/agentkit/runtime/__init__.py
Imports and re-exports ContextBudget and AgentRunContext via __all__.
Pipeline Shape
coding-agent/src/agentkit/runtime/pipeline.py
Adds optional `run_context: AgentRunContext
Application Wiring
coding-agent/src/coding_agent/app.py
Extends create_child_pipeline/create_agent signatures with agent_id_override, parent_run_id_override, context_budget, trace_metadata; constructs AgentRunContext; sets PipelineContext.session_id and ctx.config["agent_id"].
Subagent Dispatch
coding-agent/src/coding_agent/tools/subagent.py
Computes parent_agent_id/child_agent_id, merges trace_metadata, passes agent_id_override/parent_run_id_override/context_budget/trace_metadata into child pipeline builder, and sets child_ctx.config["agent_id"] from resulting run_context.
Tests / Examples
coding-agent/tests/...
Adds tests covering AgentRunContext construction, validation, defensive trace_metadata copying, derive_child semantics, create_agent run_context population, and subagent forwarding of run identity and trace metadata.

Sequence Diagram

sequenceDiagram
    participant App as Application
    participant Pipeline as Pipeline
    participant Subagent as Subagent Tool
    participant Child as Child Pipeline

    App->>App: create_agent / create_child_pipeline(with overrides)
    App->>App: build AgentRunContext(session_id, run_id, agent_id, context_budget, trace_metadata)
    App->>Pipeline: create pipeline with PipelineContext.run_context
    Pipeline->>Subagent: call subagent tool (invocation)
    Subagent->>Subagent: derive parent_agent_id and child_agent_id
    Subagent->>Subagent: merge trace_metadata (parent + ids)
    Subagent->>Child: call child pipeline builder with agent_id_override, parent_run_id_override, context_budget, trace_metadata
    Child->>Child: build child AgentRunContext (inherits session_id, sets parent_run_id)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I bounded through sessions, runs aglow,

carrying budgets and metadata in tow.
Parent hops, child hops, IDs entwined,
traces stitched tight, immutable-lined.
A cheerful rabbit cheers — context passed just so!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title '[codex] Add agent run context' accurately describes the main change: introducing AgentRunContext and ContextBudget as new runtime primitives for the agentkit module.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex-run-context-pr2

Comment @coderabbitai help to get the list of available commands and usage tips.

@delete-cloud
delete-cloud marked this pull request as ready for review May 2, 2026 08:37

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (1)
coding-agent/src/agentkit/runtime/context.py (1)

55-79: 💤 Low value

Missing run_id validation in derive_child.

The method validates that agent_id is non-empty but doesn't validate run_id. Since AgentRunContext.__post_init__ validates run_id must be non-empty (line 45-46), an empty run_id passed to derive_child would fail in the constructor anyway, but the error message would be less clear than a dedicated validation here.

Consider adding explicit validation for consistency with agent_id:

🛡️ Suggested fix
     def derive_child(
         self,
         *,
         run_id: str,
         agent_id: str,
         environment: Environment | None = None,
         context_budget: ContextBudget | None = None,
         trace_metadata: Mapping[str, Any] | None = None,
     ) -> AgentRunContext:
+        if not run_id:
+            raise ValueError("child run_id must be non-empty")
         if not agent_id:
             raise ValueError("child agent_id must be non-empty")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@coding-agent/src/agentkit/runtime/context.py` around lines 55 - 79,
derive_child currently checks agent_id but not run_id; add an explicit non-empty
validation for the run_id parameter at the start of derive_child and raise
ValueError("child run_id must be non-empty") if empty, mirroring the agent_id
check and keeping behavior consistent with AgentRunContext.__post_init__; update
derive_child (function name) to validate run_id before constructing
AgentRunContext so error messages are clear and immediate.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@coding-agent/src/agentkit/runtime/context.py`:
- Around line 55-79: derive_child currently checks agent_id but not run_id; add
an explicit non-empty validation for the run_id parameter at the start of
derive_child and raise ValueError("child run_id must be non-empty") if empty,
mirroring the agent_id check and keeping behavior consistent with
AgentRunContext.__post_init__; update derive_child (function name) to validate
run_id before constructing AgentRunContext so error messages are clear and
immediate.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 46920492-fddb-4958-8d8a-7a03e5bfa49c

📥 Commits

Reviewing files that changed from the base of the PR and between 307fb8e and c7de058.

📒 Files selected for processing (8)
  • coding-agent/src/agentkit/runtime/__init__.py
  • coding-agent/src/agentkit/runtime/context.py
  • coding-agent/src/agentkit/runtime/pipeline.py
  • coding-agent/src/coding_agent/app.py
  • coding-agent/src/coding_agent/tools/subagent.py
  • coding-agent/tests/agentkit/runtime/test_run_context.py
  • coding-agent/tests/coding_agent/test_bootstrap.py
  • coding-agent/tests/coding_agent/tools/test_subagent.py

@delete-cloud
delete-cloud force-pushed the codex-run-context-pr2 branch from c7de058 to f50c711 Compare May 2, 2026 08:51
@delete-cloud
delete-cloud force-pushed the codex-run-context-pr2 branch from f50c711 to 755d257 Compare May 2, 2026 09:35

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@coding-agent/src/coding_agent/tools/subagent.py`:
- Around line 196-212: The child pipeline call drops the parent's ContextBudget
and any existing trace keys because it only forwards parent_run_id_override and
a fresh trace dict; fix by passing the parent's budget and merging existing
trace metadata into the child call: retrieve the parent budget from
__pipeline_ctx__.run_context (e.g. parent_budget =
__pipeline_ctx__.run_context.budget or similar) and pass it as budget_override
(or the parameter name expected by
child_pipeline_builder/create_child_pipeline), and merge any existing trace
metadata (e.g. parent_trace = getattr(__pipeline_ctx__, "trace_metadata", {}) or
__pipeline_ctx__.run_context.trace_metadata) with {"parent_agent_id":
parent_agent_id, "child_agent_id": child_agent_id} and pass that merged dict as
trace_metadata to child_pipeline_builder so trace keys and non-default budgeting
are preserved.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 835a4871-ef46-49d1-9ad1-663a8e36a845

📥 Commits

Reviewing files that changed from the base of the PR and between f50c711 and 755d257.

📒 Files selected for processing (9)
  • coding-agent/src/agentkit/runtime/__init__.py
  • coding-agent/src/agentkit/runtime/context.py
  • coding-agent/src/agentkit/runtime/pipeline.py
  • coding-agent/src/coding_agent/app.py
  • coding-agent/src/coding_agent/tools/subagent.py
  • coding-agent/tests/agentkit/runtime/test_run_context.py
  • coding-agent/tests/coding_agent/plugins/test_core_tools.py
  • coding-agent/tests/coding_agent/test_bootstrap.py
  • coding-agent/tests/coding_agent/tools/test_subagent.py
✅ Files skipped from review due to trivial changes (2)
  • coding-agent/tests/coding_agent/tools/test_subagent.py
  • coding-agent/src/agentkit/runtime/init.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • coding-agent/src/agentkit/runtime/context.py

CodeRabbit flagged that the child pipeline call dropped the parent's
ContextBudget and any existing trace keys. Pass parent_run_context.context_budget
through and merge parent trace_metadata with the parent/child agent_id keys so
non-default budgeting and upstream trace correlation survive into subagent runs.

Amp-Thread-ID: https://ampcode.com/threads/T-019de7f6-ebfd-742c-8223-6187e3784659
Co-authored-by: Amp <amp@ampcode.com>

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@coding-agent/src/coding_agent/tools/subagent.py`:
- Around line 97-100: The code currently does
str(pipeline_ctx.config.get("agent_id", "")) which turns None into "None";
change it to fetch agent_id = pipeline_ctx.config.get("agent_id") and treat None
as unset: if agent_id is None or agent_id == "" return None, otherwise return
str(agent_id); update the logic around legacy_agent_id (the variable created
there) so child IDs and trace metadata never receive the literal "None".
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 5a788025-8ef7-4c7e-93fb-2da868d93cee

📥 Commits

Reviewing files that changed from the base of the PR and between 755d257 and 3e055d2.

📒 Files selected for processing (1)
  • coding-agent/src/coding_agent/tools/subagent.py

delete-cloud and others added 2 commits May 2, 2026 18:41
CodeRabbit flagged that str(config.get("agent_id", "")) coerced None
into the literal "None", which could leak into child IDs and trace
metadata. Inspect the raw value first and return None when it is missing
or empty.

Amp-Thread-ID: https://ampcode.com/threads/T-019de7f6-ebfd-742c-8223-6187e3784659
Co-authored-by: Amp <amp@ampcode.com>
Oracle review follow-up — closes the remaining gaps in PR #91:

* fail fast on empty parent session_id in subagent dispatch and on empty
  session_id_override in create_child_pipeline; never silently mint a
  fresh uuid for the child run
* prefer parent_run_context.session_id over the legacy
  PipelineContext.session_id slot
* introduce coding_agent.agent_identity.effective_agent_id as the single
  resolution helper used by subagent dispatch, the metrics plugin, and
  the legacy config slot in app.py
* namespace the reserved subagent trace keys
  (subagent.parent_agent_id / subagent.child_agent_id) so caller-supplied
  metadata cannot collide with them
* tighten ContextBudget validation: reject bool token counts and reject
  reserved_output_tokens > max_output_tokens
* document that AgentRunContext.trace_metadata is shallow-frozen and
  callers must pass JSON-scalar values
* add focused regression tests for budget propagation, trace metadata
  merge, reserved-key collision, empty parent session_id, and the new
  ContextBudget validation
* loosen two over-constrained tests (exact-field-set equality and a
  TypeError substring match)

Amp-Thread-ID: https://ampcode.com/threads/T-019de7f6-ebfd-742c-8223-6187e3784659
Co-authored-by: Amp <amp@ampcode.com>
@delete-cloud
delete-cloud merged commit 1799df2 into main May 2, 2026
1 check passed
@delete-cloud
delete-cloud deleted the codex-run-context-pr2 branch May 2, 2026 11:17
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.

1 participant