Skip to content

The agent that grows with you

feat: attach Ink local transport through canonical gateway bootstrap

Teknium08f628f9f5b0
diff --git a/ui-tui/scripts/gateway_bootstrap.py b/ui-tui/scripts/gateway_bootstrap.py
new file mode 100644
index 00000000000..8379608a25a
--- /dev/null
+++ b/ui-tui/scripts/gateway_bootstrap.py
@@ -0,0 +1,60 @@
+"""Ink's private pipe bootstrap; the child is a client, never an agent owner."""
+import contextlib
+import json
+import os
+from pathlib import Path
+import socket
+import sys
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+
+
+def bootstrap(start: bool) -> dict:
+ from hermes_constants import get_hermes_home
+ from hermes_cli.gateway_runtime import discover_gateway_endpoint, ensure_gateway_runtime
+ from hermes_cli.gateway_runtime_discovery import _socket_path
+
+ home = get_hermes_home().resolve()
+ # Launch policy travels in session.create, not into daemon-wide defaults.
+ for key in ("HERMES_MODEL", "HERMES_INFERENCE_MODEL", "HERMES_TUI_PROVIDER",
+ "HERMES_INFERENCE_PROVIDER", "HERMES_TUI_TOOLSETS", "HERMES_TUI_SKILLS",
+ "HERMES_CWD", "TERMINAL_CWD", "HERMES_YOLO", "HERMES_ACCEPT_HOOKS"):
+ os.environ.pop(key, None)
+ receipt = (ensure_gateway_runtime(home, timeout=30) if start
+ else discover_gateway_endpoint(home, timeout=5))
+ if receipt.state != "ready" or receipt.endpoint is None:
+ raise RuntimeError(f"gateway {receipt.state}: {receipt.reason_code or 'not ready'}")
+ endpoint = receipt.endpoint
+ request = json.dumps({"protocol": 1, "id": 1, "verb": "session-ticket", "params": {
+ "profile_id": endpoint.profile_id, "instance_id": endpoint.instance_id,
+ "purpose": "interactive"}}).encode() + b"\n"
+ if os.name == "nt":
+ from gateway.runtime_bootstrap_windows import query_runtime_control
+ raw = query_runtime_control(home, request, 5)
+ else:
+ with socket.socket(socket.AF_UNIX) as peer:
+ peer.settimeout(5)
+ peer.connect(str(_socket_path(home)))
+ peer.sendall(request)
+ with peer.makefile("rb") as stream:
+ raw = stream.readline(65537)
+ result = json.loads(raw)
+ grant = result.get("result", {})
+ if (result.get("ok") is not True or result.get("id") != 1
+ or grant.get("instance_id") != endpoint.instance_id
+ or grant.get("profile_id") != endpoint.profile_id
+ or not isinstance(grant.get("ticket"), str)):
+ raise RuntimeError("gateway private bootstrap rejected")
+ return {"url": endpoint.api_origin.replace("http", "ws", 1) + "/api/ws",
+ "protocols": ["hermes-gateway-v1", "hermes-gateway-ticket." + grant["ticket"]],
+ "profile_id": endpoint.profile_id, "instance_id": endpoint.instance_id}
+
+
+if __name__ == "__main__":
+ try:
+ with contextlib.redirect_stdout(sys.stderr):
+ result = bootstrap("--start" in sys.argv)
+ print(json.dumps(result))
+ except Exception as exc:
+ print(str(exc), file=sys.stderr)
+ raise SystemExit(1)
diff --git a/ui-tui/src/__tests__/gatewayLocalLaunch.test.ts b/ui-tui/src/__tests__/gatewayLocalLaunch.test.ts
new file mode 100644
index 00000000000..8a04727eb66
--- /dev/null
+++ b/ui-tui/src/__tests__/gatewayLocalLaunch.test.ts
@@ -0,0 +1,25 @@
+import { afterEach, expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+vi.mock('node:child_process', () => ({ execFile: vi.fn(), spawn: vi.fn(() => { throw new Error('independent owner forbidden') }) }))
+import { GatewayClient } from '../gatewayClient.js'
+
+const home = mkdtempSync(join(tmpdir(), 'ink-bootstrap-test-'))
+afterEach(() => { vi.unstubAllEnvs(); rmSync(home, { recursive: true, force: true }) })
+
+it('reports failed canonical bootstrap without creating an independent owner or retrying ensure', async () => {
+ vi.stubEnv('HERMES_HOME', home)
+ vi.stubEnv('HERMES_TUI_GATEWAY_URL', '')
+ const bootstrap = vi.fn().mockRejectedValue(new Error('gateway draining: update_paused'))
+ const gw = new GatewayClient(bootstrap)
+ const events: any[] = []
+ gw.on('event', e => events.push(e))
+ gw.start()
+ gw.drain()
+ await vi.waitFor(() => expect(events.some(e => e.type === 'gateway.start_timeout' && e.payload.stderr_tail.includes('update_paused'))).toBe(true))
+ await expect(gw.request('session.create')).rejects.toThrow('update_paused')
+ expect(bootstrap).toHaveBeenCalledTimes(1)
+ gw.kill()
+})
diff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.ts
index 8b30d0e7f9c..b0c560a4ba5 100644
--- a/ui-tui/src/gatewayClient.ts
+++ b/ui-tui/src/gatewayClient.ts
@@ -1,8 +1,8 @@
-import { type ChildProcess, spawn } from 'node:child_process'
+import { execFile } from 'node:child_process'
import { EventEmitter } from 'node:events'
import { existsSync } from 'node:fs'
-import { delimiter, resolve } from 'node:path'
-import { createInterface } from 'node:readline'
+import { resolve } from 'node:path'
+import { promisify } from 'node:util'
import { WebSocket as UndiciWebSocket } from 'undici'
@@ -39,14 +39,6 @@ const getWebSocketCtor = (): typeof WebSocket =>
const truncateLine = (line: string) =>
line.length > MAX_LOG_LINE_BYTES ? `${line.slice(0, MAX_LOG_LINE_BYTES)}… [truncated ${line.length} bytes]` : line
-const describeChild = (proc: ChildProcess | null) => {
- if (!proc) {
- return 'pid=none'
- }
-
- return `pid=${proc.pid ?? 'unknown'} killed=${proc.killed} exitCode=${proc.exitCode ?? 'null'} signal=${proc.signalCode ?? 'null'}`
-}
-
const resolveGatewayAttachUrl = () => {
const raw = process.env.HERMES_TUI_GATEWAY_URL?.trim()
@@ -143,8 +135,17 @@ interface Pending {
timeout: ReturnType<typeof setTimeout>
}
+export interface LocalGatewayGrant { url: string; protocols: string[]; profile_id: string; instance_id: string }
+
+const bootstrapLocalGateway = async (start: boolean): Promise<LocalGatewayGrant> => {
+ const root = process.env.HERMES_PYTHON_SRC_ROOT ?? resolve(import.meta.dirname, '../../')
+ const { stdout } = await promisify(execFile)(resolvePython(root),
+ [resolve(root, 'ui-tui/scripts/gateway_bootstrap.py'), ...(start ? ['--start'] : [])],
+ { cwd: root, env: { ...process.env, PYTHONPATH: root }, timeout: 40_000, maxBuffer: 1024 * 1024 })
+ return JSON.parse(stdout) as LocalGatewayGrant
+}
+
export class GatewayClient extends EventEmitter {
- private proc: ChildProcess | null = null
private ws: WebSocket | null = null
private wsConnectPromise: Promise<void> | null = null
private sidecarWs: WebSocket | null = null
@@ -159,8 +160,6 @@ export class GatewayClient extends EventEmitter {
private readyTimer: ReturnType<typeof setTimeout> | null = null
private subscribed = false
private drainGeneration = 0
- private stdoutRl: ReturnType<typeof createInterface> | null = null
- private stderrRl: ReturnType<typeof createInterface> | null = null
private heartbeatTimer: ReturnType<typeof setInterval> | null = null
private reconnectTimer: ReturnType<typeof setTimeout> | null = null
private reconnectAttempts = 0
@@ -171,7 +170,13 @@ export class GatewayClient extends EventEmitter {
// Set on kill() so we never auto-reconnect after an intentional shutdown.
private disposed = false
- constructor() {
+ private bootstrapFlight: Promise<void> | null = null
+ private bootstrapError: Error | null = null
+ private localStarted = false
+ private localGeneration = 0
+ isCanonical = false
+
+ constructor(private bootstrap: (start: boolean) => Promise<LocalGatewayGrant> = bootstrapLocalGateway) {
super()
// useInput / createGatewayEventHandler can legitimately attach many
// listeners. Default 10-cap triggers spurious warnings.
@@ -346,10 +351,6 @@ export class GatewayClient extends EventEmitter {
this.drainGeneration += 1
this.bufferedEvents.clear()
this.pendingExit = undefined
- this.stdoutRl?.close()
- this.stderrRl?.close()
- this.stdoutRl = null
- this.stderrRl = null
this.clearReadyTimer()
}
@@ -473,87 +474,28 @@ export class GatewayClient extends EventEmitter {
}
}
- private startSpawnedGateway(root: string) {
- const python = resolvePython(root)
- const cwd = process.env.HERMES_CWD || root
- const env = { ...process.env }
- const pyPath = env.PYTHONPATH?.trim()
-
- env.PYTHONPATH = pyPath ? `${root}${delimiter}${pyPath}` : root
- // Tell the gateway child where the Hermes source root is so its import
- // guard can force it ahead of any same-named package in the launch cwd.
- env.HERMES_PYTHON_SRC_ROOT = root
- this.startReadyTimer(python, cwd)
- this.proc = spawn(python, ['-m', 'tui_gateway.entry'], { cwd, env, stdio: ['pipe', 'pipe', 'pipe'] })
- this.lifecycle(`[lifecycle] spawned gateway child ${describeChild(this.proc)} python=${python} cwd=${cwd}`)
-
- this.stdoutRl = createInterface({ input: this.proc.stdout! })
- this.stdoutRl.on('line', raw => {
- try {
- this.dispatch(JSON.parse(raw))
- } catch {
- const preview = raw.trim().slice(0, MAX_LOG_PREVIEW) || '(empty line)'
-
- this.pushLog(`[protocol] malformed stdout: ${preview}`)
- this.publish({ type: 'gateway.protocol_error', payload: { preview } })
- }
- })
-
- this.stderrRl = createInterface({ input: this.proc.stderr! })
- this.stderrRl.on('line', raw => {
- const line = truncateLine(raw.trim())
-
- if (!line) {
- return
- }
-
- this.pushLog(line)
- this.publish({ type: 'gateway.stderr', payload: { line } })
- })
-
- const ownedProc = this.proc
- this.proc.on('error', err => {
- // Skip stale errors on an already-replaced child.
- if (this.proc !== ownedProc) {
- this.pushLog(`[lifecycle] stale child error ignored ${describeChild(ownedProc)} message=${err.message}`)
-
- return
- }
-
- const line = `[spawn] ${err.message}`
-
- this.lifecycle(`[lifecycle] child error ${describeChild(ownedProc)} message=${err.message}`)
- this.pushLog(line)
- this.publish({ type: 'gateway.stderr', payload: { line } })
- // Detach the reference up front so the late `exit` event for
- // this same child is identity-skipped (we don't want to emit
- // 'exit' twice). Then run the full teardown — clears the
- // startup timer so we don't fire a misleading
- // `gateway.start_timeout`, rejects pending RPCs, and emits or
- // queues a single `exit`.
- this.proc = null
- this.handleTransportExit(1, `gateway error: ${err.message}`)
- })
- this.proc.on('exit', (code, signal) => {
- // start() can replace `this.proc` while an old child is still
- // tearing down. Skip stale exits so we don't clear the new
- // startup timer or reject newly-issued pending requests.
- if (this.proc !== ownedProc) {
- this.pushLog(
- `[lifecycle] stale child exit ignored ${describeChild(ownedProc)} code=${code ?? 'null'} signal=${signal ?? 'null'}`
- )
-
- return
- }
-
- this.lifecycle(
- `[lifecycle] child exit ${describeChild(ownedProc)} code=${code ?? 'null'} signal=${signal ?? 'null'}`
- )
- this.handleTransportExit(code)
+ private startLocalGateway() {
+ const generation = ++this.localGeneration
+ const start = !this.localStarted
+ this.localStarted = true
+ this.bootstrapError = null
+ this.bootstrapFlight = this.bootstrap(start).then(grant => {
+ if (this.disposed || generation !== this.localGeneration) { return }
+ this.attachUrl = grant.url
+ this.isCanonical = true
+ this.startAttachedGateway(grant.url, grant.protocols)
+ }).catch(error => {
+ if (this.disposed || generation !== this.localGeneration) { return }
+ this.bootstrapError = error instanceof Error ? error : new Error(String(error))
+ this.clearReadyTimer()
+ this.publish({ type: 'gateway.start_timeout', payload: {
+ python: 'gateway ensure', cwd: '', stderr_tail: this.bootstrapError.message
+ } })
+ this.rejectPending(this.bootstrapError)
})
}
- private startAttachedGateway(attachUrl: string) {
+ private startAttachedGateway(attachUrl: string, protocols?: string[]) {
const safeAttachUrl = redactUrl(attachUrl)
this.startReadyTimer('websocket', safeAttachUrl)
@@ -570,7 +512,7 @@ export class GatewayClient extends EventEmitter {
}
try {
- const ws = new WebSocketCtor(attachUrl)
+ const ws = new WebSocketCtor(attachUrl, protocols)
let settled = false
this.ws = ws
@@ -587,6 +529,15 @@ export class GatewayClient extends EventEmitter {
this.lastActivityAt = Date.now()
this.clearReconnect()
this.connectSidecarMirror()
+ if (this.isCanonical) {
+ void this.requestOverWebSocket('runtime.describe').then(() => {
+ if (this.ws === ws) { this.publish({ type: 'gateway.ready', payload: {} }) }
+ }).catch(error => {
+ this.publish({ type: 'gateway.start_timeout', payload: {
+ python: 'runtime.describe', cwd: '', stderr_tail: String(error)
+ } })
+ })
+ }
},
{ once: true }
)
@@ -658,7 +609,6 @@ export class GatewayClient extends EventEmitter {
this.disposed = false
this.clearReconnect()
- const root = process.env.HERMES_PYTHON_SRC_ROOT ?? resolve(import.meta.dirname, '../../')
const attachUrl = resolveGatewayAttachUrl()
const sidecarUrl = resolveSidecarUrl()
@@ -668,12 +618,6 @@ export class GatewayClient extends EventEmitter {
this.clearReconnect()
this.stopHeartbeat()
- if (this.proc && !this.proc.killed && this.proc.exitCode === null) {
- this.lifecycle(`[lifecycle] replacing live gateway child ${describeChild(this.proc)}`)
- this.proc.kill()
- }
-
- this.proc = null
this.closeGatewaySocket()
this.closeSidecarSocket()
@@ -683,7 +627,7 @@ export class GatewayClient extends EventEmitter {
return
}
- this.startSpawnedGateway(root)
+ this.startLocalGateway()
}
private dispatch(msg: Record<string, unknown>) {
@@ -884,54 +828,19 @@ export class GatewayClient extends EventEmitter {
return this.requestOverWebSocket<T>(method, params)
}
- if (!this.proc?.stdin || this.proc.killed || this.proc.exitCode !== null) {
- this.start()
- }
-
- if (!this.proc?.stdin) {
- return Promise.reject(new Error('gateway not running'))
- }
-
- const id = `r${++this.reqId}`
-
- return new Promise<T>((resolve, reject) => {
- const timeout = setTimeout(this.onTimeout, REQUEST_TIMEOUT_MS, id)
-
- timeout.unref?.()
-
- this.pending.set(id, {
- id,
- method,
- reject,
- resolve: v => resolve(v as T),
- timeout
- })
-
- try {
- this.proc!.stdin!.write(JSON.stringify({ id, jsonrpc: '2.0', method, params }) + '\n')
- } catch (e) {
- const pending = this.pending.get(id)
-
- if (pending) {
- clearTimeout(pending.timeout)
- this.pending.delete(id)
- }
-
- reject(e instanceof Error ? e : new Error(String(e)))
- }
+ if (!this.bootstrapFlight) { this.start() }
+ return this.bootstrapFlight!.then(() => {
+ if (this.bootstrapError) { throw this.bootstrapError }
+ return this.requestOverWebSocket<T>(method, params)
})
}
kill(reason = 'requested') {
this.disposed = true
+ this.localGeneration++
this.clearReconnect()
this.stopHeartbeat()
- const proc = this.proc
- const killed = proc?.kill()
-
- this.lifecycle(
- `[lifecycle] GatewayClient.kill reason=${reason} ${describeChild(proc)} killResult=${killed ?? 'none'}`
- )
+ this.lifecycle(`[lifecycle] GatewayClient.kill reason=${reason} (detach only)`)
this.closeGatewaySocket()
this.closeSidecarSocket()
this.clearReadyTimer()