Repository navigation
feat: add runtime context injection so agent is sandbox-aware - #373
jacobtomlinson wants to merge 5 commits into
Conversation
Ports runtime-context from the openshell-openclaw-plugin branch. Registers a before_agent_start hook that queries openshell for the current sandbox phase and policy, then prepends a <nemoclaw-runtime> block to each agent turn so the agent knows it is running inside an OpenShell sandbox with deny-by-default network access. Sends a delta update block when sandbox state changes between turns. Includes tests covering context injection, caching, delta detection, and error fallback. Co-Authored-By: Vincent Koc <[email protected]> Co-Authored-By: Peter Steinberger <[email protected]> Co-Authored-By: Jacob Tomlinson <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds a new runtime-context module that queries OpenShell for sandbox and policy data, generates full and delta human-readable runtime summaries, keeps a per-session cache with TTL/eviction, and registers a before-agent-start hook; index.ts now registers this runtime context during plugin initialization. Changes
Sequence Diagram(s)sequenceDiagram
participant Agent as Agent/Plugin
participant Hook as Hook Handler
participant RuntimeCtx as Runtime Context
participant OpenShell as OpenShell (execFile)
participant Cache as Session Cache
Agent->>Hook: registerRuntimeContext(api, pluginConfig)
Hook->>Hook: register before_agent_start hook
Agent->>Hook: before_agent_start(hookContext)
Hook->>RuntimeCtx: getRuntimeSummary(pluginConfig, hookContext)
RuntimeCtx->>Cache: lookup by sessionKey
RuntimeCtx->>OpenShell: runs "sandbox get ..." / "policy get --full"
OpenShell-->>RuntimeCtx: sandbox metadata / policy YAML or errors
RuntimeCtx->>RuntimeCtx: parse YAML, compute fingerprint & summaries
alt New or changed fingerprint
RuntimeCtx->>Cache: store/update fingerprint + summary
RuntimeCtx-->>Hook: return full `<nemoclaw-runtime>` block
else Unchanged fingerprint
RuntimeCtx-->>Hook: return `<nemoclaw-runtime-update>` delta or undefined
end
Hook->>Agent: prepend returned runtime context to agent session
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@nemoclaw/src/runtime-context.ts`:
- Line 36: The global Map sessionRuntimeCache (holding SessionCacheEntry) needs
eviction to prevent unbounded growth; modify its usage and initialization to
implement a bounded cache (e.g., LRU or TTL-based eviction) so entries are
removed when stale or when the cache exceeds a max size; update the code paths
that add entries to sessionRuntimeCache (places that create/assign by sessionKey
and any functions that read/update entries) to call the eviction policy on
insert (or schedule periodic cleanup) and ensure SessionCacheEntry includes a
lastAccess/created timestamp if using TTL; keep the Map interface but wrap it in
a small cache helper or utility to encapsulate add/get/remove and eviction logic
so existing consumers of sessionRuntimeCache (including the code around where
entries are created) need minimal changes.
- Around line 42-50: The current execOpenShell swallows errors (returns null)
which lets getRuntimeFingerprint succeed while loadPolicyDoc treats the null as
a valid degraded policy and writes a deny-by-default summary into
sessionRuntimeCache; change execOpenShell to surface failures (either throw the
caught error or return an explicit failure result) and update loadPolicyDoc to
treat a non-success result as a hard failure (do not populate
sessionRuntimeCache or treat it as a valid policy) so only successful full
openshell outputs are cached under the fingerprint; apply the same
failure-propagation and caching-guard logic to the other occurrences noted
(lines ~160-175, ~262-271, ~293-303) that currently flatten openshell errors
into null/summary values.
- Around line 241-259: buildRuntimeDeltaText currently only emits network policy
lines when runtime changes; add filesystem policy info so agents receive updated
writable/read-only paths. In buildRuntimeDeltaText (using symbols
SessionCacheEntry, RuntimeFingerprint, RuntimeSummary), detect changes by
comparing previous.summary.filesystem_policy to
nextFingerprint.filesystem_policy and, when different, push a descriptive header
and the filesystem policy lines from nextSummary (e.g.,
nextSummary.filesystemLines or equivalent) into the lines array so the delta
republishes the authoritative filesystem restrictions alongside network rules.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 5a36d3bc-f902-4bc4-ab99-a542d5b9946f
⛔ Files ignored due to path filters (7)
nemoclaw/dist/index.d.ts.mapis excluded by!**/dist/**,!**/*.mapnemoclaw/dist/index.jsis excluded by!**/dist/**nemoclaw/dist/index.js.mapis excluded by!**/dist/**,!**/*.mapnemoclaw/dist/runtime-context.d.tsis excluded by!**/dist/**nemoclaw/dist/runtime-context.d.ts.mapis excluded by!**/dist/**,!**/*.mapnemoclaw/dist/runtime-context.jsis excluded by!**/dist/**nemoclaw/dist/runtime-context.js.mapis excluded by!**/dist/**,!**/*.map
📒 Files selected for processing (3)
nemoclaw/src/index.tsnemoclaw/src/runtime-context.test.tsnemoclaw/src/runtime-context.ts
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
nemoclaw/src/runtime-context.ts (1)
212-228:⚠️ Potential issue | 🟠 MajorTreat empty or unparsable
policy get --fulloutput as a hard failure.
loadPolicyDoc()still flattens those cases tonull.getRuntimeSummaryFromFingerprint()then builds the generic deny-by-default summary, andgetCachedRuntimeInjection()caches it under the live fingerprint. Subsequent turns with that fingerprint will skip reinjection instead of taking the warn/static-fallback path once--fullrecovers.💡 One way to keep degraded full-policy reads out of the cache
-async function loadPolicyDoc(sandboxName: string): Promise<Record<string, unknown> | null> { +async function loadPolicyDoc(sandboxName: string): Promise<Record<string, unknown>> { // Intentionally does not catch execOpenShell errors — propagate to caller so // that only successful policy loads are written to sessionRuntimeCache. const output = await execOpenShell(["policy", "get", sandboxName, "--full"]); const yamlText = normalizePolicyYaml(output); if (!yamlText) { - return null; + throw new Error(`openshell policy get --full returned no YAML for sandbox "${sandboxName}"`); } try { const parsed: unknown = yaml.parse(yamlText); if (!parsed || typeof parsed !== "object") { - return null; + throw new Error("openshell policy get --full returned a non-object document"); } return parsed as Record<string, unknown>; - } catch { - return null; + } catch (error) { + throw new Error(`failed to parse openshell policy document: ${String(error)}`); } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nemoclaw/src/runtime-context.ts` around lines 212 - 228, loadPolicyDoc currently returns null on empty or unparsable output, allowing callers like getRuntimeSummaryFromFingerprint/getCachedRuntimeInjection to cache a degraded generic summary; change loadPolicyDoc to treat empty or unparseable `policy get --full` output as a hard failure by throwing an Error (or rethrowing) instead of returning null so the failure propagates to the caller and prevents caching of degraded summaries. Modify loadPolicyDoc (the function performing execOpenShell, normalizePolicyYaml and yaml.parse) to throw with a clear message when yamlText is falsy or when parsing fails so upstream logic can take the warn/static-fallback path rather than storing a bad runtime injection.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@nemoclaw/src/runtime-context.ts`:
- Around line 447-455: The fallback uses pluginConfig.sandboxName which can be
stale; resolve the current sandbox name once from loadState().sandboxName (e.g.,
const activeSandbox = loadState().sandboxName) at the start of the routine and
then use that variable in the fallback message and anywhere else in this
function instead of pluginConfig.sandboxName so the injected text always
reflects the active sandbox at time of failure.
- Around line 287-296: The current getSessionCacheKey returns a sandbox-scoped
key when hookContext.sessionKey is missing, causing different conversations to
share the same cache entry; modify getSessionCacheKey (and callers that expect a
string) so that if there is no valid per-session id it returns a sentinel that
disables shared caching (e.g., undefined or null) instead of
`nemoclaw:${getSandboxName(pluginConfig)}`; update any logic that consumes
getSessionCacheKey to treat this sentinel as "do not cache" so runtime blocks
are emitted per-request. Ensure you reference getSessionCacheKey,
getSandboxName, and NemoClawConfig when locating the change.
- Around line 390-402: The cache eviction runs too late and allows stale entries
and size overflow; update getCachedRuntimeInjection to call evictCache() before
reading sessionRuntimeCache (before sessionRuntimeCache.get(cacheKey)) and then
again after sessionRuntimeCache.set(...) to prune expired entries and enforce
CACHE_MAX_SIZE, or alternatively modify evictCache() to accept an optional
pendingWrite flag/key so it accounts for the upcoming set when deciding which
entries to remove; refer to getCachedRuntimeInjection, evictCache,
sessionRuntimeCache.get, and sessionRuntimeCache.set to implement the change.
---
Duplicate comments:
In `@nemoclaw/src/runtime-context.ts`:
- Around line 212-228: loadPolicyDoc currently returns null on empty or
unparsable output, allowing callers like
getRuntimeSummaryFromFingerprint/getCachedRuntimeInjection to cache a degraded
generic summary; change loadPolicyDoc to treat empty or unparseable `policy get
--full` output as a hard failure by throwing an Error (or rethrowing) instead of
returning null so the failure propagates to the caller and prevents caching of
degraded summaries. Modify loadPolicyDoc (the function performing execOpenShell,
normalizePolicyYaml and yaml.parse) to throw with a clear message when yamlText
is falsy or when parsing fails so upstream logic can take the
warn/static-fallback path rather than storing a bad runtime injection.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: e90aafbc-6b97-42d6-83e3-8eeb76407635
⛔ Files ignored due to path filters (4)
nemoclaw/dist/runtime-context.d.tsis excluded by!**/dist/**nemoclaw/dist/runtime-context.d.ts.mapis excluded by!**/dist/**,!**/*.mapnemoclaw/dist/runtime-context.jsis excluded by!**/dist/**nemoclaw/dist/runtime-context.js.mapis excluded by!**/dist/**,!**/*.map
📒 Files selected for processing (1)
nemoclaw/src/runtime-context.ts
There was a problem hiding this comment.
did you mean to bring dist/**.ts files back?
|
Thanks for porting the runtime context work. The codebase has evolved significantly since March — onboarding is now in TypeScript and the sandbox bootstrap was refactored. Before we review further, could you check whether the context injection approach here still aligns with the current architecture and rebase against main? Want to make sure we're not duplicating work that landed in the refactor. |
|
Thanks for porting this — runtime context injection is a meaningful capability and the TypeScript implementation looks well-structured. This PR has merge conflicts against |
|
Hey @jacobtomlinson — any chance you can rebase this one? Would love to get it in. |
|
Closing due to inactivity |
> Supersedes #373 (rebased onto main and resolved conflicts) ## Summary - Ports `runtime-context` from the `openshell-openclaw-plugin` branch (authored by @vincentkoc and @steipete) and integrates it with the current codebase - Registers a `before_agent_start` hook that queries `openshell` for the current sandbox phase and active policy, then prepends a `<nemoclaw-runtime>` block to each agent turn so the agent knows it is operating inside an OpenShell sandbox with deny-by-default network access - Sends a `<nemoclaw-runtime-update>` delta block when sandbox state (phase or policy hash) changes between turns, avoiding redundant full re-injection - Falls back to a minimal static context block if `openshell` is unavailable or throws ## Test plan - [x] 31 new unit tests covering: full context injection, caching (no re-inject on same session + fingerprint), delta update on phase/policy change, network rule summarisation (named rules, host:port, binary annotation, cap + omission note), filesystem policy lines (writable/read-only/workdir), error fallback (warn log + static block), session key resolution (explicit key, fallback to sandbox name, null context) - [x] Full suite (53 tests) passes with no regressions cc @wscurran @cv for review 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Runtime context is injected earlier during plugin registration, showing sandbox, network and filesystem summaries and incremental delta updates when runtime state changes. * Session-scoped caching reduces redundant policy lookups within a session; caching is disabled when no session key is present. * Hook API now accepts additional runtime return shapes and async results to support injected context and updates. * Graceful fallback provides a minimal context when infrastructure commands fail; registration logs a warning if injection fails. * **Tests** * Comprehensive tests cover context generation, caching, delta behavior, truncation, failure handling, and subprocess mocks. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Vincent Koc <[email protected]> Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]> Co-authored-by: Carlos Villela <[email protected]> Co-authored-by: Aaron Erickson 🦞 <[email protected]>
Summary
runtime-contextfrom theopenshell-openclaw-pluginbranch (authored by @vincentkoc and @steipete) and integrates it with the current codebasebefore_agent_starthook that queriesopenshellfor the current sandbox phase and active policy, then prepends a<nemoclaw-runtime>block to each agent turn so the agent knows it is operating inside an OpenShell sandbox with deny-by-default network access<nemoclaw-runtime-update>delta block when sandbox state (phase or policy hash) changes between turns, avoiding redundant full re-injectionopenshellis unavailable or throwsTest plan
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Improvements
Tests