feat: add bounded operator terminal command runner

This commit is contained in:
Mark McKeen
2026-04-08 14:50:57 -06:00
parent 52f1dedc5d
commit eb05dafd3f
5 changed files with 563 additions and 63 deletions
@@ -0,0 +1,131 @@
import { NextResponse } from 'next/server'
import { dockerExecInOpenShell, OPENSHELL_NAMESPACE, probeSandboxShell, validateSandboxId } from '../../../../lib/openshellHost'
interface PodSummary {
containers: string[]
images: string[]
runningStatuses: string[]
phase?: string
readyCondition?: string
}
const EMPTY_POD_SUMMARY: PodSummary = {
containers: [],
images: [],
runningStatuses: [],
}
async function inspectPod(sandboxId: string): Promise<PodSummary> {
const result = await dockerExecInOpenShell(
`kubectl -n ${OPENSHELL_NAMESPACE} get pod ${sandboxId} -o json`
)
if (result.exitCode !== 0) {
const failureText = `${result.stderr}\n${result.stdout}`.toLowerCase()
if (failureText.includes('(notfound)') || failureText.includes('not found')) {
return EMPTY_POD_SUMMARY
}
throw new Error(result.stderr.trim() || result.stdout.trim() || `kubectl get pod failed with exit code ${result.exitCode}`)
}
if (!result.stdout.trim()) {
throw new Error('kubectl get pod returned empty stdout')
}
const pod = JSON.parse(result.stdout)
return {
containers: Array.isArray(pod?.spec?.containers) ? pod.spec.containers.map((c: any) => c.name) : [],
images: Array.isArray(pod?.spec?.containers) ? pod.spec.containers.map((c: any) => c.image) : [],
runningStatuses: Array.isArray(pod?.status?.containerStatuses) ? pod.status.containerStatuses.map((c: any) => c.name) : [],
phase: pod?.status?.phase,
readyCondition: Array.isArray(pod?.status?.conditions)
? pod.status.conditions.find((c: any) => c.type === 'Ready')?.status
: undefined,
}
}
function buildAttachContract(sandboxId: string) {
const alias = `openshell-${sandboxId}`
return {
alias,
aliasCommand: `ssh ${alias}`,
fallbackCommand: `ssh -i ~/.ssh/id_ed25519_openclaw_labmac ${alias}`,
loginShellCommand: `env PATH=/opt/homebrew/bin:$PATH zsh -l -c 'ssh ${alias}'`,
shellHint: 'If a non-interactive shell misses Homebrew tooling, retry from a login shell or prepend PATH=/opt/homebrew/bin:$PATH before ssh.',
}
}
export async function GET(request: Request) {
try {
const { searchParams } = new URL(request.url)
const sandboxId = validateSandboxId(searchParams.get('sandboxId') || '')
const attach = buildAttachContract(sandboxId)
const pod = await inspectPod(sandboxId)
let shellProbe: {
ok: boolean
output?: string
stderr?: string
error?: string
} = { ok: false }
const podExists = Boolean(pod.containers.length || pod.images.length || pod.phase)
if (podExists) {
try {
const probe = await probeSandboxShell(sandboxId)
shellProbe = {
ok: true,
output: probe.stdout.trim(),
stderr: probe.stderr.trim(),
}
} catch (error) {
shellProbe = {
ok: false,
error: error instanceof Error ? error.message : 'Shell probe failed',
}
}
} else {
shellProbe = {
ok: false,
error: `Sandbox pod ${sandboxId} was not found in ${OPENSHELL_NAMESPACE}.`,
}
}
const podReady = pod.readyCondition === 'True' || pod.phase === 'Running'
const sshReachable = shellProbe.ok
return NextResponse.json({
ok: true,
sandboxId,
podExists,
podReady,
sshReachable,
degraded: podExists && !sshReachable,
attach,
pod,
shellProbe,
note: !podExists
? `Sandbox pod ${sandboxId} is not present in ${OPENSHELL_NAMESPACE}.`
: sshReachable
? 'Pod introspection and bounded shell probe both succeeded.'
: 'Pod introspection succeeded, but bounded shell probe did not. Treat this as degraded dashboard reachability until direct SSH is confirmed.',
})
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to build readiness contract'
const status = message === 'sandboxId is required'
|| message.includes('sandboxId must be a valid lowercase DNS-style identifier')
? 400
: 500
return NextResponse.json({
ok: false,
podExists: false,
podReady: false,
sshReachable: false,
degraded: false,
error: message,
}, { status })
}
}
+59 -2
View File
@@ -1,4 +1,5 @@
import { NextResponse } from 'next/server'
import { DEFAULT_EXEC_TIMEOUT_MS, MAX_COMMAND_LENGTH, runSandboxCommand, validateSandboxId, validateTerminalCommand } from '../../../lib/openshellHost'
export async function GET(request: Request) {
const { searchParams } = new URL(request.url)
@@ -8,7 +9,63 @@ export async function GET(request: Request) {
ok: true,
sandboxId,
attached: false,
note: 'Embedded terminal transport is not live yet. This route is the integration point for attaching to an OpenShell terminal session.',
suggestedCommand: `openshell sandbox exec ${sandboxId} -- /bin/sh`
interactive: false,
mode: 'bounded-command-runner',
note: 'Embedded PTY transport is still not live. This route now supports bounded one-shot command execution via POST while interactive terminal attach remains pending.',
suggestedCommand: `openshell sandbox exec ${sandboxId} -- /bin/sh`,
limits: {
timeoutMs: DEFAULT_EXEC_TIMEOUT_MS,
maxCommandLength: MAX_COMMAND_LENGTH,
},
})
}
export async function POST(request: Request) {
try {
const body = await request.json()
const sandboxInput = typeof body?.sandboxId === 'string' ? body.sandboxId : ''
const commandInput = typeof body?.command === 'string' ? body.command : ''
const sandboxId = validateSandboxId(sandboxInput)
const command = validateTerminalCommand(commandInput)
const result = await runSandboxCommand(sandboxId, command)
const ok = result.exitCode === 0
return NextResponse.json({
ok,
sandboxId,
interactive: false,
mode: 'bounded-command-runner',
executionMode: result.mode,
command,
exitCode: result.exitCode,
stdout: result.stdout.trim(),
stderr: result.stderr.trim(),
note: ok
? result.mode === 'shell'
? 'Bounded sandbox command execution succeeded. Interactive PTY transport is still pending.'
: 'Sandbox reachability fallback succeeded, but command execution still requires a shell-capable image.'
: `Bounded sandbox command exited non-zero (${result.exitCode}). Interactive PTY transport is still pending, but stderr/stdout below reflect the real sandbox response.`,
limits: {
timeoutMs: DEFAULT_EXEC_TIMEOUT_MS,
maxCommandLength: MAX_COMMAND_LENGTH,
},
}, { status: ok ? 200 : 502 })
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to run sandbox command'
const status = message === 'sandboxId is required'
|| message === 'command is required'
|| message.includes('sandboxId must be a valid lowercase DNS-style identifier')
|| message.includes('command exceeds')
? 400
: 500
return NextResponse.json({
ok: false,
interactive: false,
mode: 'bounded-command-runner',
error: message,
}, { status })
}
}
+133 -17
View File
@@ -1,4 +1,5 @@
import { execFile } from 'node:child_process'
import type { ExecFileException } from 'node:child_process'
import { promisify } from 'node:util'
const execFileAsync = promisify(execFile)
@@ -7,38 +8,153 @@ const DOCKER_BIN = '/Applications/Docker.app/Contents/Resources/bin/docker'
const OPENSHELL_CONTAINER = 'openshell-cluster-openshell'
const OPENSHELL_NAMESPACE = 'agent-sandbox-system'
const OPENCLAW_DASHBOARD_URL = 'http://127.0.0.1:18789/'
const DEFAULT_EXEC_TIMEOUT_MS = 10000
const MAX_COMMAND_LENGTH = 400
const SANDBOX_ID_PATTERN = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/
export async function dockerExecInOpenShell(command: string) {
const { stdout, stderr } = await execFileAsync(DOCKER_BIN, [
type ExecResult = {
stdout: string
stderr: string
exitCode: number
}
function normalizeExecError(error: unknown): ExecResult {
const execError = error as ExecFileException & { stdout?: string, stderr?: string, code?: number | string | null }
return {
stdout: typeof execError?.stdout === 'string' ? execError.stdout : '',
stderr: typeof execError?.stderr === 'string' ? execError.stderr : '',
exitCode: typeof execError?.code === 'number' ? execError.code : -1,
}
}
export async function dockerExecInOpenShell(command: string, timeoutMs = DEFAULT_EXEC_TIMEOUT_MS): Promise<ExecResult> {
try {
const { stdout, stderr } = await execFileAsync(
DOCKER_BIN,
[
'exec',
OPENSHELL_CONTAINER,
'sh',
'-lc',
command,
])
return { stdout, stderr }
],
{
timeout: timeoutMs,
maxBuffer: 1024 * 1024,
}
)
return { stdout, stderr, exitCode: 0 }
} catch (error) {
const normalized = normalizeExecError(error)
if (normalized.exitCode !== -1 || normalized.stdout || normalized.stderr) {
return normalized
}
throw error
}
}
type SandboxExecPlan = {
command: string
mode: 'shell' | 'env'
}
function buildSandboxExecPlans(podName: string, shellCommand: string, options?: { allowEnvFallback?: boolean }): SandboxExecPlan[] {
const escaped = quoteForSingleQuotedShell(shellCommand)
const attempts: SandboxExecPlan[] = [
{
command: `kubectl -n ${OPENSHELL_NAMESPACE} exec ${podName} -- /bin/sh -lc '${escaped}'`,
mode: 'shell',
},
{
command: `kubectl -n ${OPENSHELL_NAMESPACE} exec ${podName} -- /busybox/sh -lc '${escaped}'`,
mode: 'shell',
},
]
if (options?.allowEnvFallback) {
attempts.push({
command: `kubectl -n ${OPENSHELL_NAMESPACE} exec ${podName} -- env`,
mode: 'env',
})
}
return attempts
}
async function execInSandboxWithFallback(podName: string, shellCommand: string, options?: { allowEnvFallback?: boolean }) {
const attempts = buildSandboxExecPlans(podName, shellCommand, options)
let lastFailure: ({ mode: SandboxExecPlan['mode'] } & ExecResult) | undefined
for (const plan of attempts) {
const result = await dockerExecInOpenShell(plan.command)
if (result.exitCode === 0) {
return {
...result,
mode: plan.mode,
}
}
lastFailure = {
...result,
mode: plan.mode,
}
}
if (lastFailure) {
return lastFailure
}
throw new Error('Failed to probe sandbox shell')
}
export async function probeSandboxShell(podName: string) {
const attempts = [
`kubectl -n ${OPENSHELL_NAMESPACE} exec ${podName} -- /bin/sh -lc 'echo OPENSHELL_OK && pwd && whoami'`,
`kubectl -n ${OPENSHELL_NAMESPACE} exec ${podName} -- /busybox/sh -lc 'echo OPENSHELL_OK && pwd && whoami'`,
`kubectl -n ${OPENSHELL_NAMESPACE} exec ${podName} -- env`,
]
const result = await execInSandboxWithFallback(podName, 'echo OPENSHELL_OK && pwd && whoami', { allowEnvFallback: true })
if (result.exitCode !== 0) {
throw new Error(result.stderr.trim() || result.stdout.trim() || `Shell probe failed with exit code ${result.exitCode}`)
}
return result
}
let lastError: unknown
for (const command of attempts) {
try {
return await dockerExecInOpenShell(command)
} catch (error) {
lastError = error
function quoteForSingleQuotedShell(command: string) {
return command.replace(/'/g, `'"'"'`)
}
export function validateSandboxId(sandboxId: string) {
const trimmed = sandboxId.trim()
if (!trimmed) {
throw new Error('sandboxId is required')
}
if (!SANDBOX_ID_PATTERN.test(trimmed)) {
throw new Error('sandboxId must be a valid lowercase DNS-style identifier')
}
throw lastError instanceof Error ? lastError : new Error('Failed to probe sandbox shell')
return trimmed
}
export function validateTerminalCommand(command: string) {
const trimmed = command.trim()
if (!trimmed) {
throw new Error('command is required')
}
if (trimmed.length > MAX_COMMAND_LENGTH) {
throw new Error(`command exceeds ${MAX_COMMAND_LENGTH} characters`)
}
return trimmed
}
export async function runSandboxCommand(podName: string, command: string) {
const trimmed = validateTerminalCommand(command)
return await execInSandboxWithFallback(podName, trimmed)
}
export function getOpenClawDashboardUrl() {
return OPENCLAW_DASHBOARD_URL
}
export { DOCKER_BIN, OPENSHELL_CONTAINER, OPENSHELL_NAMESPACE }
export { DEFAULT_EXEC_TIMEOUT_MS, DOCKER_BIN, MAX_COMMAND_LENGTH, OPENSHELL_CONTAINER, OPENSHELL_NAMESPACE }
+218 -32
View File
@@ -4,29 +4,67 @@ import Link from 'next/link'
import { useSearchParams } from 'next/navigation'
import { useCallback, useEffect, useMemo, useState } from 'react'
interface IntrospectResponse {
ok: boolean
sandboxId?: string
interface ReadinessPodSummary {
containers?: string[]
images?: string[]
runningStatuses?: string[]
phase?: string
readyCondition?: string
}
interface ReadinessResponse {
ok: boolean
sandboxId?: string
podExists?: boolean
podReady?: boolean
sshReachable?: boolean
degraded?: boolean
attach?: {
alias?: string
aliasCommand?: string
fallbackCommand?: string
loginShellCommand?: string
shellHint?: string
}
pod?: ReadinessPodSummary
shellProbe?: {
ok?: boolean
output?: string
stderr?: string
error?: string
}
note?: string
error?: string
}
interface CommandRunResponse {
ok: boolean
command?: string
executionMode?: string
exitCode?: number
stdout?: string
stderr?: string
error?: string
note?: string
}
type LoadState = 'idle' | 'loading' | 'ready' | 'error'
const SSH_ALIAS = 'ssh openshell-my-assistant'
const SSH_FALLBACK = 'ssh -i ~/.ssh/id_ed25519_openclaw_labmac openshell-my-assistant'
const defaultAlias = (sandboxId: string | null) => `ssh openshell-${sandboxId || 'my-assistant'}`
const defaultFallback = (sandboxId: string | null) => `ssh -i ~/.ssh/id_ed25519_openclaw_labmac openshell-${sandboxId || 'my-assistant'}`
const defaultLoginShell = (sandboxId: string | null) => `env PATH=/opt/homebrew/bin:$PATH zsh -l -c 'ssh openshell-${sandboxId || 'my-assistant'}'`
const DEFAULT_SHELL_HINT = 'If your non-interactive shell misses Homebrew tooling, retry from a login shell or prepend PATH=/opt/homebrew/bin:$PATH before ssh.'
export default function OperatorTerminalPage() {
const searchParams = useSearchParams()
const sandboxId = searchParams.get('sandboxId')
const [state, setState] = useState<LoadState>(sandboxId ? 'loading' : 'idle')
const [data, setData] = useState<IntrospectResponse | null>(null)
const [data, setData] = useState<ReadinessResponse | null>(null)
const [lastCheckedAt, setLastCheckedAt] = useState<string | null>(null)
const [copyMessage, setCopyMessage] = useState<string>('')
const [commandInput, setCommandInput] = useState<string>('pwd && whoami')
const [commandState, setCommandState] = useState<'idle' | 'running' | 'done' | 'error'>('idle')
const [commandResult, setCommandResult] = useState<CommandRunResponse | null>(null)
const refreshReadiness = useCallback(async () => {
if (!sandboxId) {
@@ -39,10 +77,10 @@ export default function OperatorTerminalPage() {
setCopyMessage('')
try {
const response = await fetch(`/api/openshell/terminal/introspect?sandboxId=${encodeURIComponent(sandboxId)}`, {
const response = await fetch(`/api/openshell/terminal/readiness?sandboxId=${encodeURIComponent(sandboxId)}`, {
cache: 'no-store',
})
const result: IntrospectResponse = await response.json()
const result: ReadinessResponse = await response.json()
setData(result)
setState(response.ok && result.ok ? 'ready' : 'error')
setLastCheckedAt(new Date().toLocaleTimeString())
@@ -73,22 +111,38 @@ export default function OperatorTerminalPage() {
return {
tone: 'border-[var(--status-pending)] text-[var(--status-pending)]',
label: 'CHECKING READINESS',
detail: 'Verifying pod metadata so the page can show a truthful operator handoff.',
detail: 'Verifying pod metadata and bounded shell reachability so the page can report terminal truth in one pass.',
}
}
if (state === 'ready' && data?.ok) {
if (state === 'ready' && data?.ok && data?.podReady && data?.sshReachable) {
return {
tone: 'border-[var(--status-running)] text-[var(--status-running)]',
label: 'TERMINAL PATH VERIFIED',
detail: 'The dashboard confirmed the pod is ready and a bounded backend shell exec succeeded. Interactive PTY embedding is still not wired up, but this path now proves command execution reachability without requiring a second manual probe.',
}
}
if (state === 'ready' && data?.ok && data?.podExists && data?.degraded) {
return {
tone: 'border-[var(--status-pending)] text-[var(--status-pending)]',
label: 'DEGRADED: POD UP, SHELL UNCONFIRMED',
detail: 'The pod exists, but the bounded shell probe did not succeed from the dashboard backend. Treat the page as degraded and try the local SSH attach path.',
}
}
if (state === 'ready' && data?.ok && data?.podExists) {
return {
tone: 'border-[var(--status-running)] text-[var(--status-running)]',
label: 'READY FOR LOCAL SSH ATTACH',
detail: 'This page confirms the sandbox exists. Interactive PTY embedding is not wired up yet, so attach from your local terminal.',
detail: 'The dashboard confirmed pod metadata. Use the attach commands below while persistent PTY transport is still pending.',
}
}
return {
tone: 'border-[var(--status-stopped)] text-[var(--status-stopped)]',
label: 'READINESS CHECK FAILED',
detail: 'The dashboard could not confirm pod metadata. Use the recovery commands below, then retry.',
detail: 'The dashboard could not confirm pod metadata or shell reachability. Use the recovery commands below, then retry.',
}
}, [sandboxId, state, data])
@@ -101,6 +155,44 @@ export default function OperatorTerminalPage() {
}
}, [])
const runCommand = useCallback(async () => {
if (!sandboxId) {
setCommandState('error')
setCommandResult({ ok: false, error: 'Select a sandbox before running a command.' })
return
}
setCommandState('running')
setCommandResult(null)
try {
const response = await fetch('/api/openshell/terminal', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
sandboxId,
command: commandInput,
}),
})
const result: CommandRunResponse = await response.json()
setCommandResult(result)
setCommandState(response.ok && result.ok ? 'done' : 'error')
} catch (error) {
setCommandResult({
ok: false,
error: error instanceof Error ? error.message : 'Failed to run dashboard command.',
})
setCommandState('error')
}
}, [commandInput, sandboxId])
const aliasCommand = data?.attach?.aliasCommand || defaultAlias(sandboxId)
const fallbackCommand = data?.attach?.fallbackCommand || defaultFallback(sandboxId)
const loginShellCommand = data?.attach?.loginShellCommand || defaultLoginShell(sandboxId)
const shellHint = data?.attach?.shellHint || DEFAULT_SHELL_HINT
return (
<main className="min-h-screen bg-[var(--background)] text-[var(--foreground)] p-8">
<div className="mx-auto max-w-5xl space-y-6">
@@ -109,7 +201,7 @@ export default function OperatorTerminalPage() {
<p className="text-[10px] uppercase tracking-[0.25em] text-[var(--foreground-dim)] font-mono">Operator path</p>
<h1 className="text-2xl font-semibold uppercase tracking-wider mt-2">Operator Terminal</h1>
<p className="text-sm text-[var(--foreground-dim)] mt-3 max-w-2xl">
Truthful first render for the current terminal path. This page does not pretend to host an embedded shell; it verifies readiness and tells the operator exactly how to attach.
Truthful operator render for the current terminal path. This page still does not pretend to host an embedded PTY, but it now checks pod readiness and bounded shell reachability together before telling you how to attach.
</p>
</div>
<Link
@@ -141,42 +233,133 @@ export default function OperatorTerminalPage() {
<div>
<h3 className="text-sm font-semibold uppercase tracking-wider">Attach Instructions</h3>
<p className="text-xs text-[var(--foreground-dim)] mt-2">
Preferred path is the SSH alias. If your shell environment is missing the alias or key wiring, use the explicit fallback.
Preferred path is the SSH alias. If your shell environment is missing the alias or key wiring, use the explicit fallback. The readiness check below is now the page&apos;s single preflight source.
</p>
</div>
<button
onClick={refreshReadiness}
className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] border border-[var(--border-subtle)]"
>
Retry Readiness Check
Refresh Terminal Readiness
</button>
</div>
<div className="space-y-3">
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Preferred attach command</p>
<code className="block mt-2 text-sm font-mono text-[var(--nvidia-green)] break-all">{SSH_ALIAS}</code>
<code className="block mt-2 text-sm font-mono text-[var(--nvidia-green)] break-all">{aliasCommand}</code>
<button
onClick={() => copyCommand(SSH_ALIAS)}
onClick={() => copyCommand(aliasCommand)}
className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]"
>
Copy Alias Command
</button>
</div>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3">
<div>
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Fallback if alias or agent config is missing</p>
<code className="block mt-2 text-sm font-mono text-[var(--foreground)] break-all">{SSH_FALLBACK}</code>
<p className="text-xs text-[var(--foreground-dim)] mt-2">
If your non-interactive shell misses Homebrew tooling, retry from a login shell or prepend <span className="font-mono text-[var(--foreground)]">PATH=/opt/homebrew/bin:$PATH</span> before related helper commands.
</p>
<code className="block mt-2 text-sm font-mono text-[var(--foreground)] break-all">{fallbackCommand}</code>
<p className="text-xs text-[var(--foreground-dim)] mt-2">{shellHint}</p>
<button
onClick={() => copyCommand(SSH_FALLBACK)}
onClick={() => copyCommand(fallbackCommand)}
className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]"
>
Copy Fallback Command
</button>
</div>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3">
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Login-shell retry for Homebrew/path issues</p>
<code className="block mt-2 text-sm font-mono text-[var(--foreground)] break-all">{loginShellCommand}</code>
<button
onClick={() => copyCommand(loginShellCommand)}
className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]"
>
Copy Login-Shell Retry
</button>
</div>
</div>
</div>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3">
<div className="flex items-center justify-between gap-3 flex-wrap">
<div>
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Bounded shell reachability</p>
<p className="text-xs text-[var(--foreground-dim)] mt-2">
This is now captured as part of the readiness contract, so the page can show command execution reachability immediately on load.
</p>
</div>
<div className="text-[11px] text-[var(--foreground-dim)] font-mono">
{data?.shellProbe?.ok ? 'Probe passed' : 'Probe not confirmed'}
</div>
</div>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3">
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Probe stdout</p>
<pre className="mt-2 text-xs whitespace-pre-wrap break-words font-mono text-[var(--foreground)] min-h-16">{data?.shellProbe?.output || 'No backend shell output captured yet.'}</pre>
</div>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3">
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Probe stderr / status</p>
<pre className="mt-2 text-xs whitespace-pre-wrap break-words font-mono text-[var(--foreground)] min-h-16">{data?.shellProbe?.error || data?.shellProbe?.stderr || data?.note || 'No stderr.'}</pre>
</div>
</div>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-4">
<div className="flex items-center justify-between gap-3 flex-wrap">
<div>
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Bounded dashboard command runner</p>
<p className="text-xs text-[var(--foreground-dim)] mt-2">
Minimal in-dashboard execution while PTY transport is still pending. Runs a single bounded command through the dashboard backend against the selected sandbox.
</p>
</div>
<div className="text-[11px] text-[var(--foreground-dim)] font-mono">
{commandState === 'running' ? 'Running…' : commandState === 'done' ? 'Last run succeeded' : commandState === 'error' ? 'Last run failed' : 'Idle'}
</div>
</div>
<label className="block">
<span className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Command</span>
<textarea
value={commandInput}
onChange={(event) => setCommandInput(event.target.value)}
spellCheck={false}
rows={3}
className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-sm font-mono text-[var(--foreground)] focus:border-[var(--nvidia-green)] focus:outline-none"
placeholder="pwd && whoami"
/>
</label>
<div className="flex items-center gap-3 flex-wrap">
<button
onClick={runCommand}
disabled={commandState === 'running' || !sandboxId}
className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed"
>
{commandState === 'running' ? 'Running Command…' : 'Run Bounded Command'}
</button>
<p className="text-[11px] text-[var(--foreground-dim)] font-mono">One-shot only. No persistent PTY state yet.</p>
</div>
<div className="grid grid-cols-1 gap-3">
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3">
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Command stdout</p>
<pre className="mt-2 text-xs whitespace-pre-wrap break-words font-mono text-[var(--foreground)] min-h-16">{commandResult?.stdout || 'No command output yet.'}</pre>
</div>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 space-y-2">
<div className="flex items-center justify-between gap-3 flex-wrap">
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Command stderr / status</p>
{typeof commandResult?.exitCode === 'number' && (
<span className="text-[10px] font-mono text-[var(--foreground-dim)]">
exit {commandResult.exitCode}{commandResult.executionMode ? ` · ${commandResult.executionMode}` : ''}
</span>
)}
</div>
<pre className="mt-2 text-xs whitespace-pre-wrap break-words font-mono text-[var(--foreground)] min-h-16">{commandResult?.error || commandResult?.stderr || commandResult?.note || 'No stderr.'}</pre>
</div>
</div>
</div>
{copyMessage && (
@@ -190,39 +373,42 @@ export default function OperatorTerminalPage() {
<div>
<h3 className="text-sm font-semibold uppercase tracking-wider">Readiness Evidence</h3>
<p className="text-xs text-[var(--foreground-dim)] mt-2">
Live pod introspection from the dashboard backend. This is the page’s truth source until persistent PTY transport exists.
Live pod introspection and bounded shell evidence from the dashboard backend. This is the page&apos;s truth source until persistent PTY transport exists.
</p>
</div>
<div className="space-y-3 text-sm">
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Pod phase / ready</p>
<p className="mt-2 font-mono break-words">{data?.pod?.phase || 'Unknown'} / {data?.pod?.readyCondition || 'Unknown'}</p>
</div>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Containers</p>
<p className="mt-2 font-mono break-words">{data?.containers?.length ? data.containers.join(', ') : 'Unavailable'}</p>
<p className="mt-2 font-mono break-words">{data?.pod?.containers?.length ? data.pod.containers.join(', ') : 'Unavailable'}</p>
</div>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Images</p>
<p className="mt-2 font-mono break-words">{data?.images?.length ? data.images.join(', ') : 'Unavailable'}</p>
<p className="mt-2 font-mono break-words">{data?.pod?.images?.length ? data.pod.images.join(', ') : 'Unavailable'}</p>
</div>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Running statuses</p>
<p className="mt-2 font-mono break-words">{data?.runningStatuses?.length ? data.runningStatuses.join(', ') : 'Unavailable'}</p>
<p className="mt-2 font-mono break-words">{data?.pod?.runningStatuses?.length ? data.pod.runningStatuses.join(', ') : 'Unavailable'}</p>
</div>
</div>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Recovery notes</p>
<ul className="mt-2 space-y-2 text-xs text-[var(--foreground-dim)] list-disc pl-4">
<li>If readiness fails but SSH still works, use the local attach command and treat the dashboard as degraded, not authoritative.</li>
<li>If SSH fails, verify the host alias and key path on the Mac first.</li>
<li>If both fail, restart the dashboard/backend side and rerun the readiness check.</li>
<li>If the dashboard reports degraded but SSH still works, use the local attach command and treat the dashboard as degraded, not authoritative.</li>
<li>If SSH fails, verify the Mac host alias and key path first: <span className="font-mono text-[var(--foreground)]">~/.ssh/id_ed25519_openclaw_labmac</span>.</li>
<li>If helper commands miss Homebrew binaries in non-interactive mode, use a login shell or prepend <span className="font-mono text-[var(--foreground)]">PATH=/opt/homebrew/bin:$PATH</span>.</li>
</ul>
</div>
{(data?.note || data?.error || data?.stderr) && (
{(data?.note || data?.error) && (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)] space-y-2">
{data?.note && <p><span className="text-[var(--foreground)]">Note:</span> {data.note}</p>}
{data?.error && <p><span className="text-[var(--status-stopped)]">Error:</span> {data.error}</p>}
{data?.stderr && <p><span className="text-[var(--foreground)]">stderr:</span> {data.stderr}</p>}
</div>
)}
</div>
+11 -1
View File
@@ -20,5 +20,15 @@
- Full `tsc --noEmit` still fails on pre-existing unrelated type errors outside this slice.
- Linux-side direct `ssh openshell-my-assistant` validation blocked because alias is Mac-local here.
## Additional progress
- Hardened `/api/openshell/terminal/readiness` so a missing sandbox pod returns a truthful non-degraded readiness contract instead of collapsing into a generic 500.
- Shell probing now skips absent pods and reports an explicit not-found note for `my-assistant`-style operator checks.
- Added a bounded dashboard command runner: `/api/openshell/terminal` now accepts POST for one-shot sandbox commands with input validation, timeout/length limits, and real stdout/stderr/exit-code reporting.
- Updated `/operator-terminal` to consume the readiness contract, surface probe evidence, show resolved attach commands, and expose the bounded one-shot command runner while explicitly keeping PTY embedding marked as not-yet-live.
## Validation
- `npm run lint -- app/operator-terminal/page.tsx app/api/openshell/terminal/route.ts app/api/openshell/terminal/readiness/route.ts app/lib/openshellHost.ts` passed.
- Full live shell/SSH validation against the Mac/OpenShell runtime is still pending from a host that can actually reach the alias/path.
## Next milestone
- Add a backend operator-readiness contract that can distinguish pod existence, SSH reachability, and dashboard degradation, then optionally layer in streamed attach transport afterward.
- Validate the readiness + bounded-command contract against the live Mac/OpenShell path for `my-assistant`, then layer in streamed attach transport only after the route truth matches real runtime states.