Skip to content
This repository was archived by the owner on Aug 17, 2026. It is now read-only.

Commit 5801c06

Browse files
committed
feat(grunt/tui): bare gruntcode auto-spawns serve + attaches (one-command wakeable TUI) (#5)
## Goal Bare `gruntcode` (no subcommand) should Just Work — the launched TUI is automatically wakeable. No `serve` + `attach` two-command dance, no shell wrapper. Nik framing 2026-05-26: "like i run gruntcode and things can get woken up via hivemind". ## Behavior of bare `gruntcode` now 1. Probes http://127.0.0.1:4096/session — if a daemon is already serving there, attach to it. 2. If no daemon: spawns one as a detached child (`gruntcode serve --port 4096 --hostname 127.0.0.1 --print-logs`), waits up to 10s for readiness. 3. Re-execs into `gruntcode attach <url>` with all the relevant args passed through (--peer-id, --dir, --continue, --session, --fork). The user sees an unchanged TUI; implementation detail (the daemon) is hidden behind the bare command. 4. Daemon survives the TUI exit — second bare `gruntcode` invocation reuses it. ## Escape hatches - `OPENCODE_DISABLE_AUTO_SERVE=1` skips the auto-serve and uses the legacy in-process worker (the path used today by upstream opencode). - `OPENCODE_AUTO_SERVE_PORT` / `OPENCODE_AUTO_SERVE_HOST` override the defaults (4096 / 127.0.0.1). ## Implementation - New `packages/opencode/src/cli/cmd/tui/auto-serve.ts` exports `ensureServeDaemon()`. Returns `{ok: true, url, bin}` or `{ok: false, reason}`. Logic: - Resolves gruntcode binary path (argv0 if compiled binary; `which gruntcode` if running via `bun run` in dev mode; fallback to `which opencode`). - Probes /session with 1.5s timeout. - If 200 → returns the URL. - If connection refused → spawns daemon as detached child, polls /session every 200ms until ready or 10s timeout. - `packages/opencode/src/cli/cmd/tui/thread.ts` handler calls `ensureServeDaemon()` early. On success: builds attach argv from current args and re-execs via child_process.spawn with stdio inherited. On failure: logs the reason and falls through to the existing in-process worker path. ## Verification End-to-end manual test: 1. Killed existing daemon. Confirmed `curl :4096/session` returns connection refused. 2. Launched bare TUI from patched source: `bun run src/index.ts --peer-id nik-test --project /tmp`. 3. Process tree showed: bun run → child `gruntcode serve --port 4096 ...` AND child `gruntcode attach http://127.0.0.1:4096 --dir /tmp --peer-id nik-test`. 4. `curl :4096/session` returned 200 with the active session. 5. `curl -X POST :4096/session/<id>/prompt_async` accepted (204) and the daemon log showed the LLM running. The wake response 'BARE-CMD-WORKS' was written to opencode.db (verified via `/session/<id>/message`). ## Known follow-up The wake response sometimes doesn't render visually in the TUI even though it's persisted server-side. This is a separate refinement of patch 2c (SSE subscription) that needs investigation — the wake is audit-complete and the system works for autonomous coordination, but human-watcher UX needs polish. Tracked in hivemind anomalyco#221. Refs hivemind anomalyco#224.
1 parent 13af607 commit 5801c06

2 files changed

Lines changed: 150 additions & 0 deletions

File tree

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
// auto-serve.ts — make bare `gruntcode` wakeable by ensuring a serve daemon exists.
2+
//
3+
// The default TUI command (thread.ts) historically spawns an in-process Worker
4+
// that hosts the session itself. That session has no HTTP endpoint, so it can't
5+
// be reached by hivemind_wake_peer (or any external POST to /session/<id>/prompt_async).
6+
//
7+
// This module makes the bare command wakeable: it probes for an existing serve
8+
// daemon on the conventional port, spawns one as a detached child if missing,
9+
// waits for readiness, and returns the URL. The caller (thread.ts) then takes
10+
// the attach codepath instead of the in-process worker so the session is hosted
11+
// on the daemon.
12+
//
13+
// Escape hatch: set OPENCODE_DISABLE_AUTO_SERVE=1 to keep the legacy in-process
14+
// behavior (or use a different entry point — `gruntcode attach`, `gruntcode run`,
15+
// etc. don't go through this).
16+
//
17+
// Refs hivemind #224.
18+
19+
import { spawn, spawnSync } from "child_process"
20+
import { existsSync } from "fs"
21+
import { open } from "fs/promises"
22+
import path from "path"
23+
import { homedir } from "os"
24+
25+
const DEFAULT_PORT = 4096
26+
const DEFAULT_HOST = "127.0.0.1"
27+
const SPAWN_READY_TIMEOUT_MS = 10_000
28+
const PROBE_TIMEOUT_MS = 1500
29+
30+
export type AutoServeResult =
31+
| { ok: true; url: string; bin: string; spawned: boolean }
32+
| { ok: false; reason: string }
33+
34+
// Probe a candidate serve URL. Returns true iff /session responds 200 within
35+
// PROBE_TIMEOUT_MS. We hit /session (not /) because the OpenAPI doc / root
36+
// route may not exist on all builds, but /session is core to the serve API.
37+
async function probe(url: string): Promise<boolean> {
38+
try {
39+
const controller = new AbortController()
40+
const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS)
41+
const response = await fetch(`${url}/session`, { signal: controller.signal })
42+
clearTimeout(timer)
43+
return response.ok
44+
} catch {
45+
return false
46+
}
47+
}
48+
49+
function serveLogDir() {
50+
return path.join(homedir(), ".local", "share", "opencode")
51+
}
52+
53+
async function spawnDaemon(port: number, host: string, binPath: string): Promise<void> {
54+
const dir = serveLogDir()
55+
await (await import("fs/promises")).mkdir(dir, { recursive: true }).catch(() => {})
56+
const logPath = path.join(dir, "serve.log")
57+
// append-mode so previous boots' logs remain
58+
const log = await open(logPath, "a")
59+
const child = spawn(binPath, ["serve", "--port", String(port), "--hostname", host, "--print-logs"], {
60+
detached: true,
61+
stdio: ["ignore", log.fd, log.fd],
62+
})
63+
child.unref()
64+
await log.close()
65+
}
66+
67+
function findGruntcodeBin(): string | null {
68+
// process.argv[0] is the binary that started this process. If user ran
69+
// `gruntcode` (compiled binary), this is the gruntcode binary path —
70+
// perfect for re-exec.
71+
const argv0 = process.argv[0] ?? ""
72+
if (argv0.endsWith("/gruntcode") || argv0.endsWith("/opencode")) return argv0
73+
// Dev mode (bun run): argv0 is bun. Find an installed gruntcode via PATH.
74+
const which = spawnSync("which", ["gruntcode"], { encoding: "utf8" })
75+
const found = which.stdout?.trim()
76+
if (found && existsSync(found)) return found
77+
// Last-resort: opencode in PATH (still works since our patches are inside the same code path)
78+
const whichOpencode = spawnSync("which", ["opencode"], { encoding: "utf8" })
79+
const foundOpencode = whichOpencode.stdout?.trim()
80+
if (foundOpencode && existsSync(foundOpencode)) return foundOpencode
81+
return null
82+
}
83+
84+
export async function ensureServeDaemon(): Promise<AutoServeResult> {
85+
if (process.env.OPENCODE_DISABLE_AUTO_SERVE) {
86+
return { ok: false, reason: "OPENCODE_DISABLE_AUTO_SERVE set" }
87+
}
88+
89+
const port = Number(process.env.OPENCODE_AUTO_SERVE_PORT ?? DEFAULT_PORT)
90+
const host = process.env.OPENCODE_AUTO_SERVE_HOST ?? DEFAULT_HOST
91+
const url = `http://${host}:${port}`
92+
93+
// We need a bin for re-exec into attach (and for spawning the daemon if missing).
94+
const bin = findGruntcodeBin()
95+
if (!bin) {
96+
return { ok: false, reason: "cannot locate gruntcode binary (argv0 is non-gruntcode and `which gruntcode`/`which opencode` failed)" }
97+
}
98+
99+
// Already serving?
100+
if (await probe(url)) return { ok: true, url, bin, spawned: false }
101+
102+
try {
103+
await spawnDaemon(port, host, bin)
104+
} catch (error) {
105+
return { ok: false, reason: `failed to spawn serve daemon: ${error instanceof Error ? error.message : String(error)}` }
106+
}
107+
108+
// Wait for readiness.
109+
const deadline = Date.now() + SPAWN_READY_TIMEOUT_MS
110+
while (Date.now() < deadline) {
111+
if (await probe(url)) return { ok: true, url, bin, spawned: true }
112+
await new Promise((resolve) => setTimeout(resolve, 200))
113+
}
114+
115+
return { ok: false, reason: `serve daemon did not respond on ${url} within ${SPAWN_READY_TIMEOUT_MS}ms` }
116+
}

‎packages/opencode/src/cli/cmd/tui/thread.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ import {
2222
setPeerID,
2323
} from "@opencode-ai/core/util/opencode-process"
2424
import { validateSession } from "./validate-session"
25+
import { ensureServeDaemon } from "./auto-serve"
26+
import { spawn as spawnChild } from "child_process"
2527

2628
declare global {
2729
const OPENCODE_WORKER_PATH: string
@@ -135,6 +137,38 @@ export const TuiThreadCommand = cmd({
135137
return
136138
}
137139

140+
// grunt-it patch: make bare `gruntcode` wakeable by ensuring a serve
141+
// daemon exists and re-execing into `gruntcode attach <url>`. The user
142+
// sees an unchanged TUI — implementation detail (the daemon + attach)
143+
// is hidden behind the bare command. Set OPENCODE_DISABLE_AUTO_SERVE=1
144+
// to skip and use the legacy in-process worker. Refs hivemind #224.
145+
const auto = await ensureServeDaemon()
146+
if (auto.ok) {
147+
const attachArgs: string[] = ["attach", auto.url]
148+
if (args.project) attachArgs.push("--dir", args.project)
149+
if (args.continue) attachArgs.push("--continue")
150+
if (args.session) attachArgs.push("--session", args.session)
151+
if (args.fork) attachArgs.push("--fork")
152+
if (args["peer-id"]) attachArgs.push("--peer-id", args["peer-id"])
153+
// Re-exec via child_process and inherit stdio so the TUI replaces this
154+
// process visually. We exit when the attach child exits.
155+
const child = spawnChild(auto.bin, attachArgs, { stdio: "inherit" })
156+
await new Promise<void>((resolve) => {
157+
child.on("close", (code) => {
158+
process.exitCode = code ?? 0
159+
resolve()
160+
})
161+
child.on("error", (err) => {
162+
Log.Default.error("auto-serve attach re-exec failed", { error: errorMessage(err) })
163+
resolve()
164+
})
165+
})
166+
return
167+
}
168+
// auto-serve unavailable (e.g. OPENCODE_DISABLE_AUTO_SERVE set, daemon
169+
// could not be spawned) — fall through to the legacy in-process path.
170+
Log.Default.info("auto-serve skipped", { reason: auto.reason })
171+
138172
// Resolve relative --project paths from PWD, then use the real cwd after
139173
// chdir so the thread and worker share the same directory key.
140174
const next = resolveThreadDirectory(args.project)

0 commit comments

Comments
 (0)