feat(grok): start the in-container SDK server + budget feed (Claude parity)

The keystone of the Grok parity work (CEO's "take Claude as baseline, create
what's missing" call): the one-shot Grok container now starts the same SDK
server the Claude path runs, so the per-verb circuit breaker (the flow/do MCP
servers already POST /verb/attempted to it), the per-session budget/loop
counters, the terminal-verb tracking, and the SessionEnd post-mortem all work
on Grok instead of being silently absent.

- entrypoint: launch roboco.agent_sdk.server (bare venv python, not `uv run`
  which would re-sync the drifted clone lock and stall), wait for /health,
  reset counters; run opencode WITHOUT exec so the script regains control to
  run the post-mortem and the silent-exit substitute after the run returns.
- budget-feed.js: opencode plugin that gates on /budget/status in
  tool.execute.before (halt/loop deny — the only place to stop a runaway
  one-shot run; opencode has no PostToolUse-deny) and records the executed
  tool + args-hash in tool.execute.after. Fail-open; bare-verb normalization
  for MCP-namespaced terminal verbs.
- silent-exit substitute: on a graceful exit with no terminal verb the
  entrypoint posts /terminal/force_substitute so the task isn't left stuck
  claimed/in_progress (Stop-hook parity at the boundary).
- opencode_config: wire budget-feed into the plugin array; add
  ROBOCO_OPENCODE_EXTRA_PLUGINS so per-image role tool plugins load scoped to
  one role; read the per-role ROBOCO_GROK_EDIT_PERMISSION.

Targeted gate green (ruff/mypy/xenon + opencode_config tests; node --check on
the plugins; bash -n on the entrypoint).
This commit is contained in:
Renn F
2026-06-18 19:53:22 +02:00
parent e0caccb5dc
commit 82945ae023
5 changed files with 280 additions and 38 deletions
+6 -2
View File
@@ -21,9 +21,13 @@ RUN npm install -g opencode-ai @ai-sdk/openai \
&& npm cache clean --force \
&& rm -rf /root/.npm /tmp/*
# Command guard / secret-scrub plugin (bash-guard parity for the opencode runtime).
# Referenced from the generated opencode.json `plugin:` array.
# opencode plugins (referenced from the generated opencode.json `plugin:` array):
# secret-scrub — bash-guard parity (PAT/credential deny on tool.execute.before)
# budget-feed — POSTs budget/loop/terminal counters to the in-container SDK
# server (tool.execute.{before,after}); the entrypoint starts
# that server (roboco.agent_sdk.server) for Claude-parity.
COPY docker/grok/secret-scrub.js /app/opencode-plugins/secret-scrub.js
COPY docker/grok/budget-feed.js /app/opencode-plugins/budget-feed.js
# Entrypoint: render opencode.json, then run opencode (overrides base's `claude`).
COPY docker/scripts/grok-agent-entrypoint.sh /app/scripts/grok-agent-entrypoint.sh
+108
View File
@@ -0,0 +1,108 @@
// opencode plugin — budget / loop / terminal feed for one-shot RoboCo Grok agents.
//
// Ports the Claude PostToolUse budget hook (docker/scripts/post-tool-budget-hook.sh)
// and the Stop hook's terminal-tool tracking (docker/scripts/stop-hook.sh) to
// opencode's tool.execute.{before,after}. The in-container SDK server
// (roboco.agent_sdk.server, :9000) is the same long-lived process the Claude
// path runs — the grok entrypoint starts it before `opencode run`. The flow/do
// MCP servers already POST /verb/attempted to it for the per-verb circuit
// breaker, so starting it + this feed restores the budget/loop/terminal cluster
// on Grok (Claude-parity, the CEO's "create what's missing" call).
//
// before: read /budget/status and DENY (throw) on a hard halt, or a loop with
// loop_action=halt. opencode has no PostToolUse-deny, so the pre-exec
// gate is the only place to stop a runaway one-shot run from burning
// the cost cap mid-turn. The loop trips one call later than Claude
// (record is in `after`) but still halts the burn.
// after: record the executed tool on /terminal/tool_recorded (so a graceful
// terminal verb is recognized) and /budget/tool_called (advances the
// breaker/loop counters and feeds the post-exit post-mortem).
//
// Fail-open everywhere: a missing / slow / non-2xx SDK never blocks the agent.
// The interactive serve images (intake / secretary) own :9000 for the human-turn
// receiver and run NO SDK server, so these POSTs 404 there and are ignored —
// those roles don't claim tasks or loop on verbs, so they need no budget feed.
const SDK_URL = process.env.ROBOCO_SDK_URL || "http://localhost:9000";
async function sdk(method, path, body) {
try {
const res = await fetch(`${SDK_URL}${path}`, {
method,
headers: body ? { "Content-Type": "application/json" } : undefined,
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(2000),
});
if (!res.ok) return null;
return await res.json();
} catch {
return null; // fail-open — never block the agent on SDK reachability
}
}
// Canonical, dependency-free serialization (sorted keys) so the SDK's loop
// detector sees identical (tool, args) calls as identical. Need NOT match the
// Claude hook's sha256 — only be stable within one session.
function canonical(value) {
if (value === null || typeof value !== "object") return JSON.stringify(value);
if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]";
const keys = Object.keys(value).sort();
return (
"{" +
keys.map((k) => JSON.stringify(k) + ":" + canonical(value[k])).join(",") +
"}"
);
}
function argsHash(args) {
const s = canonical(args ?? {});
let h = 0x811c9dc5; // FNV-1a, 32-bit
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
return (h >>> 0).toString(16).padStart(8, "0");
}
// opencode namespaces an MCP tool as "<server>_<verb>" (or "<server>.<verb>");
// the Claude path's verbs arrive bare. Strip a known roboco-* server prefix so
// the SDK recognizes a terminal verb (i_am_idle / i_am_done / ...) — the SDK's
// own "__"-split is a no-op on the already-bare verb this returns.
// UNVERIFIED-LIVE: opencode's exact MCP tool-name shape; the strip is defensive.
function bareVerb(tool) {
const mcp = tool.match(/^mcp__[a-z0-9-]+__(.+)$/);
if (mcp) return mcp[1];
const pref = tool.match(/^roboco-[a-z-]+[_.](.+)$/);
if (pref) return pref[1];
return tool;
}
export default async () => {
return {
"tool.execute.before": async (input) => {
const status = await sdk("GET", "/budget/status", null);
if (!status) return; // fail-open
if (status.halt) {
throw new Error(
`[Halt] tool budget exhausted (${status.total}/${status.halt_threshold}). ` +
"Stop now — release the task with unclaim() or i_am_idle().",
);
}
if (status.loop && status.loop_action === "halt") {
throw new Error(
"[Loop] same tool+args repeated in window — halting. " +
"Release the task with unclaim() or stop with i_am_idle().",
);
}
},
"tool.execute.after": async (input) => {
const raw = String(input?.tool || "");
if (!raw) return;
await sdk("POST", "/terminal/tool_recorded", { tool: bareVerb(raw) });
await sdk("POST", "/budget/tool_called", {
tool: bareVerb(raw),
args_hash: argsHash(input?.args),
});
},
};
};
+72 -21
View File
@@ -1,33 +1,37 @@
#!/usr/bin/env bash
# Entrypoint for the roboco-agent-grok image.
# Entrypoint for the roboco-agent-grok image (one-shot delivery roles).
#
# Renders opencode.json from the RoboCo spawn env (OPENAI_* + ROBOCO_*, set by
# GrokProvider) plus the mounted Claude Code mcp-config.json, then runs opencode
# non-interactively. opencode speaks the OpenAI protocol, so grok-build-0.1 runs
# natively against api.x.ai/v1 with no shim, while still reaching the RoboCo MCP
# gateway (roboco-flow / roboco-do / ...) translated into opencode's mcp config.
# GrokProvider) plus the mounted Claude Code mcp-config.json, starts the
# in-container SDK server (parity with the Claude SessionStart sdk-startup-hook),
# then runs opencode non-interactively. opencode speaks the OpenAI protocol, so
# grok-build-0.1 runs natively against api.x.ai/v1 with no shim, while still
# reaching the RoboCo MCP gateway (roboco-flow / roboco-do / ...) translated into
# opencode's mcp config.
set -euo pipefail
SDK_PORT="${ROBOCO_SDK_PORT:-9000}"
SDK_URL="http://localhost:${SDK_PORT}"
# Generate opencode.json (provider + model + MCP gateway + permissions +
# instructions). Writes to opencode's global config dir by default.
python -m roboco.llm.providers.opencode_config
# Run the agent. The prompt comes from an env var (never an untrusted argv
# positional); `--` separates it from flags so a prompt starting with `--`
# cannot be parsed as CLI options. The model also comes from the rendered
# config; --model is passed explicitly as belt-and-suspenders.
#
# `< /dev/null` is REQUIRED: without a closed stdin, `opencode run` hangs after
# init in a headless / no-TTY environment (it blocks waiting on stdin). Verified
# live — closing stdin lets the run proceed to the model call and exit cleanly.
#
# Reasoning effort: GrokProvider sets ROBOCO_GROK_VARIANT per role (e.g.
# "minimal" for coordination/docs roles to cut reasoning cost). Absent =
# opencode default (full reasoning).
variant_arg=()
if [ -n "${ROBOCO_GROK_VARIANT:-}" ]; then
variant_arg=(--variant "$ROBOCO_GROK_VARIANT")
# --- SDK server bring-up (Claude-parity) ----------------------------------
# The flow/do MCP servers POST /verb/attempted here for the per-verb circuit
# breaker; the budget-feed opencode plugin POSTs /budget/* + /terminal/* here;
# the post-exit hook below reads /terminal/status and writes the post-mortem.
# Bare `python` (the baked venv) — NOT `uv run`, which would re-sync the clone's
# drifted lock and stall (the #179 fix the Claude hook needs `--no-sync` for).
if ! curl -sf -m 2 "${SDK_URL}/health" >/dev/null 2>&1; then
nohup python -m roboco.agent_sdk.server >/tmp/sdk-server.log 2>&1 &
for _ in 1 2 3 4 5 6 7 8 9 10; do
if curl -sf -m 2 "${SDK_URL}/health" >/dev/null 2>&1; then break; fi
sleep 0.5
done
fi
# Zero the budget/terminal counters at the start of the session.
curl -sf -m 2 -X POST "${SDK_URL}/budget/reset" >/dev/null 2>&1 || true
# Prompt-injection guard (parity with the Claude UserPromptSubmit hook): the
# task prompt is DATA, not instructions — refuse a poisoned one before it
@@ -37,7 +41,54 @@ if ! python -m roboco.agent_sdk.prompt_guard "${ROBOCO_INITIAL_PROMPT:-}"; then
exit 1
fi
exec opencode run \
# Reasoning effort: GrokProvider sets ROBOCO_GROK_VARIANT per role (e.g.
# "minimal" for coordination/docs roles to cut reasoning cost). Absent =
# opencode default (full reasoning).
variant_arg=()
if [ -n "${ROBOCO_GROK_VARIANT:-}" ]; then
variant_arg=(--variant "$ROBOCO_GROK_VARIANT")
fi
# Run the agent. The prompt comes from an env var (never an untrusted argv
# positional); `--` separates it from flags so a prompt starting with `--`
# cannot be parsed as CLI options. `< /dev/null` is REQUIRED: without a closed
# stdin, `opencode run` hangs after init in a headless / no-TTY environment.
#
# We do NOT `exec`: the script must regain control after opencode exits to run
# the post-mortem + silent-exit substitute below (the Claude SessionEnd / Stop
# hooks have no opencode equivalent, so the boundary handles them). `set +e`
# around the run so a non-zero opencode exit doesn't abort before the post-run
# hooks; PIPESTATUS preserves opencode's real code through the `tee`.
set +e
opencode run \
--model "xai/${ROBOCO_AGENT_MODEL:-grok-build-0.1}" \
"${variant_arg[@]}" \
-- "${ROBOCO_INITIAL_PROMPT:-}" < /dev/null
run_rc=$?
set -e
# --- Post-run hooks (Claude SessionEnd + Stop parity) ----------------------
# Read terminal state once, then (a) write a post-mortem journal entry and
# (b) if the agent exited WITHOUT a terminal verb (i_am_idle / i_am_done /
# pass / fail / ...), auto-substitute the task so it is not left stuck in
# claimed/in_progress for a human to hand-unstick. Best-effort; never change
# the exit code the orchestrator observes.
terminal=$(curl -sf -m 2 "${SDK_URL}/terminal/status" 2>/dev/null || echo "")
last_tool="null"
had_terminal="false"
if [ -n "$terminal" ]; then
last_tool=$(echo "$terminal" | jq -r '.last_tool // "null"' 2>/dev/null || echo "null")
had_terminal=$(echo "$terminal" | jq -r '.had_terminal_recently // false' 2>/dev/null || echo "false")
fi
curl -sf -m 3 -X POST "${SDK_URL}/journal/post_mortem" \
-H "Content-Type: application/json" \
-d "{\"terminal_tool\":\"${last_tool}\",\"reason\":\"session_end\"}" \
>/dev/null 2>&1 || true
if [ "$had_terminal" != "true" ]; then
curl -sf -m 3 -X POST "${SDK_URL}/terminal/force_substitute" >/dev/null 2>&1 || true
echo "[grok] exited without a terminal verb (last tool: ${last_tool}) — auto-substituted." >&2
fi
exit "$run_rc"