Repository navigation
feat: add runtime context injection so agent is sandbox-aware - #2751
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]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
f1ddcfb to
a85138c
Compare
…ontext # Conflicts: # nemoclaw/src/index.ts
📝 WalkthroughWalkthroughAdds a runtime-context feature that queries OpenShell for sandbox and policy data, summarizes network and filesystem rules, computes per-session fingerprints with caching and TTL, and injects Changes
Sequence DiagramsequenceDiagram
participant Agent as Agent
participant Hook as before_agent_start Hook
participant RCM as Runtime Context Module
participant OpenShell as OpenShell CLI
participant Cache as Session Cache
participant Parser as YAML Parser
Agent->>Hook: trigger before_agent_start
Hook->>RCM: request runtime summary (sessionKey)
RCM->>Cache: lookup sessionKey
alt cache hit & fingerprint unchanged
Cache-->>RCM: cached context (no inject)
else cache miss or stale
RCM->>OpenShell: exec `openshell sandbox get`
OpenShell-->>RCM: sandbox metadata (or null)
RCM->>OpenShell: exec `openshell policy get --full`
OpenShell-->>RCM: policy YAML (or null)
RCM->>Parser: normalize & parse YAML
Parser-->>RCM: parsed policy
RCM->>RCM: compute fingerprint & summaries
RCM->>Cache: store context + fingerprint
end
RCM->>Hook: return `<nemoclaw-runtime>` or `<nemoclaw-runtime-update>` (or undefined)
Hook->>Agent: agent receives injected context
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Review rate limit: 8/10 reviews remaining, refill in 11 minutes and 1 second. Comment |
The beforeAgentStart hook in runtime-context.ts is async but the type definition only accepted synchronous returns, causing TS2345 in CI. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The prior fix allowed async handlers but the return shape
{ prependContext: string } still didn't match BeforeToolCallResult.
Adds a dedicated BeforeAgentStartResult interface and a HookResult
union so api.on() accepts both hook types.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
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.test.ts`:
- Line 5: The import for the NemoClawState type is using the wrong relative path
("../blueprint/state.js"); update the import statement that references
NemoClawState to use the correct local module path ("./blueprint/state.js") so
it matches the actual module location and the other imports in the file.
In `@nemoclaw/src/runtime-context.ts`:
- Around line 440-443: In getRuntimeSummary's catch block avoid calling
getSandboxName(pluginConfig) because it can rethrow (it calls loadState());
instead return a safe fallback by either reading the sandbox name directly from
pluginConfig (e.g. pluginConfig?.sandbox?.name) or by invoking getSandboxName
inside its own try/catch and defaulting to null; update the catch in
getRuntimeSummary to set sandboxName to that non-throwing value and keep
sandboxPhase null so the error path no longer can throw again.
- Around line 457-459: Create a small union type that includes the existing
BeforeToolCallResult and the custom shape with prependContext (e.g., type
BeforeToolCallResultWithPrepend = BeforeToolCallResult | { prependContext:
string }), export it from wherever your plugin types live (suggested in
nemoclaw/src/index.ts), and then update the handler registration in
registerRuntimeContext to use that union for the "before_agent_start" callback
return type (or cast the handler's return to that union) so the api.on call and
the handler returning { prependContext } are type-compatible with
OpenClawPluginApi and BeforeToolCallResult.
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: e052a053-7069-4ce0-ab2e-e3489f12cf56
📒 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: 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 `@nemoclaw/src/index.ts`:
- Around line 351-354: The call to registerRuntimeContext(api, pluginConfig)
must be protected against SDK contract changes because registerRuntimeContext
internally registers an api.on("before_agent_start", ...) hook; wrap the
registerRuntimeContext(...) invocation in a try/catch so that if the SDK hook
API has changed the plugin still loads. Specifically, surround the call to
registerRuntimeContext(api, pluginConfig) (immediately after
getPluginConfig(api)) with a try block and log or swallow the error in the catch
(using the same processLogger or logging pattern used elsewhere) to mirror the
existing defensive wrapper used for before_tool_call.
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 40d7ea5e-137a-4f54-8145-5ff79d08e415
📒 Files selected for processing (1)
nemoclaw/src/index.ts
runtime-context.ts imports execFile from node:child_process, so the existing mock in register.test.ts needs to export it too. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Add missing NemoClawState fields to blankState() in runtime-context.test.ts - Wrap number in String() for template literal expression - Add void prefix to floating promise in register.test.ts Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The dynamic import of the mocked module loses its type, making loadState effectively `any`. Cast the import to the correct signature so vi.mocked(loadState).mockReturnValue() passes ESLint. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
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.test.ts`:
- Around line 382-389: The test assertion in the "includes Behavior section with
internet access instruction" case must match the exact case-sensitive wording in
runtime-context.ts; update the expect(result.prependContext).toContain(...) call
in the test (located near registerRuntimeContext, makeMockApi, defaultConfig,
nextSessionKey, and api._trigger) to use the exact string from
runtime-context.ts (including the missing "host or" and exact capitalization) so
the assertion matches the runtime string exactly.
- Around line 141-167: The mock API object includes a property named registerCli
which is not part of the OpenClawPluginApi interface; remove the registerCli
property from the MockApi object in the test (the object assigned to api) so the
mock matches the interface contract, leaving other methods (registerCommand,
registerProvider, registerService, etc.) unchanged and keeping the logger and
on/_trigger implementations intact.
- Around line 432-464: The tests currently only assert the presence of
prependContext but not that it is a delta update; in the "sends update when
policy hash changes" and "update includes current network policy lines" test
cases (the it blocks with those exact descriptions) add an assertion that
result.prependContext contains the delta marker string
"<nemoclaw-runtime-update>" (e.g.,
expect(result.prependContext).toContain("<nemoclaw-runtime-update>")) so the
tests fail if a full runtime block is emitted instead of a delta update.
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: ecf6e8af-e367-4e74-9959-445294ed2547
📒 Files selected for processing (1)
nemoclaw/src/runtime-context.test.ts
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Formatter line-length wrapping and redundant type assertion removal that the CI hooks apply automatically. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
ESLint removed the `as string` casts but left the wrapping parens, which Prettier then strips. Applying Prettier to fix the mismatch. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
nemoclaw/src/index.ts (1)
349-349: 💤 Low valueComment numbering is out of order.
Steps are numbered
4then3in the comments. Consider fixing for clarity.Proposed fix
- // 4. Register runtime context injection (sandbox-awareness hook) + // 3. Register runtime context injection (sandbox-awareness hook) const pluginConfig = getPluginConfig(api); ... - // 3. Register before_tool_call hook to block secrets in memory writes (`#1233`) + // 4. Register before_tool_call hook to block secrets in memory writes (`#1233`)Also applies to: 376-376
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@nemoclaw/src/index.ts` at line 349, Two inline comment headings are misnumbered (they show "4." then later "3.") around the runtime registration area—update the comment text to use a consistent, sequential step number. Locate the comment containing "Register runtime context injection (sandbox-awareness hook)" and the subsequent comment at the later block (the one currently labeled "3") and renumber them so ordering is correct (e.g., change the later "3" to "5" or reorder to maintain numeric sequence). Ensure both comments use the same numbering scheme to avoid confusion in nemoclaw/src/index.ts.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@nemoclaw/src/index.ts`:
- Line 349: Two inline comment headings are misnumbered (they show "4." then
later "3.") around the runtime registration area—update the comment text to use
a consistent, sequential step number. Locate the comment containing "Register
runtime context injection (sandbox-awareness hook)" and the subsequent comment
at the later block (the one currently labeled "3") and renumber them so ordering
is correct (e.g., change the later "3" to "5" or reorder to maintain numeric
sequence). Ensure both comments use the same numbering scheme to avoid confusion
in nemoclaw/src/index.ts.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 8163a736-8b20-48d1-be4b-7aed48c9d68b
📒 Files selected for processing (4)
nemoclaw/src/index.tsnemoclaw/src/register.test.tsnemoclaw/src/runtime-context.test.tsnemoclaw/src/runtime-context.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- nemoclaw/src/register.test.ts
Automated PR review summaryReviewed PR #2751: feat: add runtime context injection so agent is sandbox-aware Recommendation
Installation and setup findings
What was validated
Failing tests and unresolved impact
Passing tests and why they matteredPassing test 1: Runtime hook injects once and emits delta updates on sandbox changes
Passing test 2: Fallback remains non-throwing when openshell or state access fails
Passing test 3: Plugin registration survives unsupported before_agent_start hook
Passing test 4: Installed OpenShell sandbox was independently reachable for runtime-context inspection
Bottom line
|
## Summary Updates NemoClaw documentation for the v0.0.32 release candidate, covering user-facing changes that landed since v0.0.31 and promoting the docs version switcher to 0.0.32. ## Changes - Document Windows-host Ollama support from WSL, including HTTP model pulls and avoiding duplicate Ollama instances on port 11434. Matches dev PR #2768. - Add Ollama GPU memory cleanup behavior for provider switches, service stops, and sandbox destroy. Matches dev PR #2651. - Document Hugging Face token forwarding for remote deploy workflows that pull gated model repositories. Matches dev PR #2729. - Add runtime sandbox and policy context injection to the architecture reference. Matches dev PR #2751. - Bump `docs/versions1.json` and regenerated `docs/project.json` to 0.0.32 for release prep. No separate dev PR. ## Type of Change - [ ] Code change (feature, bug fix, or refactor) - [ ] Code change with doc updates - [ ] Doc only (prose changes, no code sample modifications) - [x] Doc only (includes code sample changes) ## Verification - [ ] `npx prek run --all-files` passes - [ ] `npm test` passes - [ ] Tests added or updated for new or changed behavior - [x] No secrets, API keys, or credentials committed - [x] Docs updated for user-facing behavior changes - [ ] `make docs` builds without warnings (doc changes only) - [x] Doc pages follow the [style guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md) (doc changes only) - [ ] New doc pages include SPDX header and frontmatter (new pages only) ## AI Disclosure - [x] AI-assisted — tool: Cursor --- Signed-off-by: Miyoung Choi <[email protected]> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Documentation** * Added guidance for deploying with Hugging Face gated models * Improved Windows/WSL Ollama configuration instructions * Documented GPU memory cleanup behavior during model transitions * Enhanced architecture and command reference documentation * Version bumped to 0.0.32 <!-- end of auto-generated comment: release notes by coderabbit.ai -->
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
cc @wscurran @cv for review
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Tests