Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(super-tab): a JSON action's - refuses a terminal stdin at once; one helper for both Buddy checks (#2384)

harness-for-autonomous[bot]4d6cc2432140
diff --git a/cli/src/superTabs/buddyPane.spec.ts b/cli/src/superTabs/buddyPane.spec.ts
index da1a43de0..d6b9c4cd4 100644
--- a/cli/src/superTabs/buddyPane.spec.ts
+++ b/cli/src/superTabs/buddyPane.spec.ts
@@ -1,5 +1,5 @@
import { expect, it, vi } from 'vitest'
-import { buddyRefusal, WINDOWS_BUDDY } from './buddyPane.js'
+import { buddyRefusal, paneBuddy, WINDOWS_BUDDY } from './buddyPane.js'
const where = { port: 14001, dataDir: '/fixture', machineId: 'machine' }
const BUDDY = 'A Buddy talks with its owner in its own chat: it may not send to, start, tell or close other sessions.'
@@ -99,3 +99,25 @@ it('refuses when the Swarm cannot say whether it is on, on every platform', asyn
expect(await buddyRefusal({ ...d.deps, env: { CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 's' } }, platform)).toBe(UNSURE)
}
})
+
+// Review of #2379: the CLI's usage wording repeated this guard's pane, harness and Buddy-check steps. Both now take them from
+// one helper; each keeps its own answer for what the helper cannot settle.
+it('finds the pane\'s harness and asks whether it is a Buddy, the one way the guard and the usage wording both ask', async () => {
+ const ancestors = [900, 700, 600, 1]
+ const asked = async (check: (payload: Record<string, unknown>) => Record<string, unknown>, pane = '%42', parents: number[] | 'none' = ancestors) => {
+ const d = daemon(check)
+ return { answer: await paneBuddy(d, pane, 'machine', parents === 'none' ? undefined : parents), requests: d.request.mock.calls.map(([type]) => type) }
+ }
+ expect(await asked(swarm(true))).toEqual({ answer: 'buddy', requests: ['agents_list', 'terminal_info', 'super_tabs'] })
+ expect(await asked(swarm(false))).toEqual({ answer: 'not a buddy', requests: ['agents_list', 'terminal_info', 'super_tabs'] })
+ // No harness of this computer's in the pane: nothing more is asked.
+ expect(await asked(swarm(true), '%7')).toEqual({ answer: 'no harness', requests: ['agents_list'] })
+ // Not the harness's own pane, as the daemon reads it: never asked about.
+ expect(await asked(swarm(true), '%42', [900, 1])).toEqual({ answer: 'not in its pane', requests: ['agents_list', 'terminal_info'] })
+ // Without the command's parents (the usage wording), its pane is not checked, as before.
+ expect(await asked(swarm(true), '%42', 'none')).toEqual({ answer: 'buddy', requests: ['agents_list', 'super_tabs'] })
+ // The Swarm is on but cannot say for this harness.
+ for (const failed of [{ error: 'SERVICE_FAILED' }, { ok: true }, { ok: true, buddy: 'yes' }]) expect((await asked(() => failed)).answer).toBe('unsure')
+ // A request that fails is the caller's to read: the guard refuses, the usage wording reads it as no Buddy.
+ await expect(paneBuddy(daemon(() => { throw new Error('daemon gone') }), '%42', 'machine', ancestors)).rejects.toThrow('daemon gone')
+})
diff --git a/cli/src/superTabs/buddyPane.ts b/cli/src/superTabs/buddyPane.ts
index c30185af4..6bfaafdcf 100644
--- a/cli/src/superTabs/buddyPane.ts
+++ b/cli/src/superTabs/buddyPane.ts
@@ -19,6 +19,8 @@ const UNSURE = 'Harness could not confirm whether this harness is a Buddy just n
export const WINDOWS_BUDDY = 'This Windows computer runs a Buddy, and Harness cannot tell its pane from this one, so an agent here may not do this '
+ 'while it runs. Run it from your own terminal.'
+type DaemonLike = { request: (type: string, payload?: Record<string, unknown>, ms?: number) => Promise<Record<string, unknown>> }
+
export const SWARM_UNSURE = 'Harness could not reach this computer\'s Swarm just now, so it did not run this. Try again in a moment.'
/**
@@ -27,13 +29,30 @@ export const SWARM_UNSURE = 'Harness could not reach this computer\'s Swarm just
* request without a Swarm: invalid). Anything else, a failure or no answer in time, throws [SWARM_UNSURE]: read as "off", it
* skipped the Buddy check and Windows' backstop (re-check 2 of #2093 at 0648a8690).
*/
-export async function buddiesHere(daemon: { request: (type: string, payload?: Record<string, unknown>, ms?: number) => Promise<Record<string, unknown>> }): Promise<boolean | null> {
+export async function buddiesHere(daemon: DaemonLike): Promise<boolean | null> {
const answer = await daemon.request('super_tabs', { action: 'buddyCheck' }, 10_000).catch(() => { throw new Error(SWARM_UNSURE) })
if (answer.ok === true) return answer.buddiesHere === true
if (answer.error === 'UNSUPPORTED' || answer.error === 'INVALID_REQUEST' || answer.error === 'SERVICE_UNAVAILABLE' && answer.retryable === false) return null
throw new Error(SWARM_UNSURE)
}
+/**
+ * Whether the harness running in [pane] is a Buddy, by this computer's launch record (service.ts `buddyCheck`, what turns its
+ * guard on): the one way this guard and the CLI's usage wording (command.ts `buddyHere`) ask it (review of #2379). With the
+ * command's [ancestors], a harness whose own pane, as the daemon reads it, is not among them is never asked about. A request
+ * that fails is thrown, for each caller to read as it does: this guard refuses, the wording takes it for no Buddy.
+ */
+export async function paneBuddy(daemon: DaemonLike, pane: string, machineId: string, ancestors?: number[])
+ : Promise<'buddy' | 'not a buddy' | 'no harness' | 'not in its pane' | 'unsure'> {
+ const listed = await daemon.request('agents_list')
+ const caller = callerOf(Array.isArray(listed.agents) ? listed.agents as Frame[] : [], pane, machineId)
+ if (!caller) return 'no harness'
+ if (!await inDaemonPane(daemon, caller.agentId, ancestors)) return 'not in its pane'
+ const answer = await daemon.request('super_tabs', { action: 'buddyCheck', harnessId: caller.agentId }, 10_000)
+ if (answer.ok !== true || typeof answer.buddy !== 'boolean') return 'unsure'
+ return answer.buddy ? 'buddy' : 'not a buddy'
+}
+
/** An agent's shell on Windows, as it marks itself: its Harness pane, or the engine's own variables (`outsideCaller`). */
export const agentShell = (env: NodeJS.ProcessEnv): boolean => !!sendPane(env) || !!outsideCaller(env, '')
@@ -53,13 +72,10 @@ export async function buddyRefusal(deps: {
if (running.refused) return running.refused
// Not shortcut on `buddies`: a harness an agent started with no Swarm record is asked about by itself (service.ts).
if (!running.pane) return null
- const listed = await daemon.request('agents_list')
- const caller = callerOf(Array.isArray(listed.agents) ? listed.agents as Frame[] : [], running.pane, where.machineId)
- if (!caller) return null
- if (!await inDaemonPane(daemon, caller.agentId, running.ancestors)) return NOT_IN_PANE
- const answer = await daemon.request('super_tabs', { action: 'buddyCheck', harnessId: caller.agentId }, 10_000)
+ const buddy = await paneBuddy(daemon, running.pane, where.machineId, running.ancestors)
+ if (buddy === 'not in its pane') return NOT_IN_PANE
// The Swarm answered it is on: one that then cannot say for this harness is no answer of "no Buddy" (re-check 1 of #2093).
- if (answer.ok !== true || typeof answer.buddy !== 'boolean') return UNSURE
- return answer.buddy ? BUDDY : null
+ if (buddy === 'unsure') return UNSURE
+ return buddy === 'buddy' ? BUDDY : null
} finally { daemon.close() }
}
diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.ts
index f5ec968eb..b63cbc52e 100644
--- a/cli/src/superTabs/command.spec.ts
+++ b/cli/src/superTabs/command.spec.ts
@@ -70,6 +70,25 @@ it('refuses a post\'s - with an empty or a terminal stdin, naming the fix, and p
expect(print.mock.calls.map(([line]) => JSON.parse(line).error)).toEqual([expect.stringContaining('read no message from stdin'), expect.stringContaining('stdin is a terminal')])
expect(request).not.toHaveBeenCalled()
})
+// Review of #2379: a JSON action's - with a terminal stdin waited 30 s and then said stdin was never closed; post refused it at once.
+it('refuses a JSON action\'s - with a terminal stdin at once, naming the fix, and sends nothing', async () => {
+ const stdin = vi.fn(() => 'never read')
+ for (const [action, id] of [['command', 'op-1'], ['propose', 'op-1'], ['start', 'op-1'], ['capacity', 'machine-2'], ['route', 'lead']]) {
+ expect(() => parseSuperTabArgs([...prefix, action, id, '-'], where, stdin, () => true))
+ .toThrow(`${action} - reads the JSON from stdin, but stdin is a terminal, so nothing was sent. Pass it as one argument, or send the JSON on stdin with - in its place: ${action} `)
+ }
+ expect(stdin).not.toHaveBeenCalled()
+ // Through the command: refused before stdin is read or anything is sent, and the error is the terminal's, not the idle one.
+ const print = vi.fn(), close = vi.fn(), request = vi.fn(async () => ({ ok: true }))
+ const deps = { where: () => where, pane: undefined, open: async () => ({ request, close, machineId: 'machine' }), print }
+ expect(await superTabCommand([...prefix, 'command', 'op', '-'], { ...deps, stdin, terminal: () => true })).toBe(1)
+ expect(JSON.parse(print.mock.calls.at(-1)![0]).error).toContain('command - reads the JSON from stdin, but stdin is a terminal, so nothing was sent.')
+ expect(stdin).not.toHaveBeenCalled()
+ expect(request).not.toHaveBeenCalled()
+ // A JSON in its place, or a stdin that is no terminal, goes on as before.
+ expect(parseSuperTabArgs([...prefix, 'command', 'op-1', '{"type":"x"}'], where, stdin, () => true).payload).toMatchObject({ command: { type: 'x' } })
+ expect(parseSuperTabArgs([...prefix, 'command', 'op-1', '-'], where, () => '{"type":"y"}', () => false).payload).toMatchObject({ command: { type: 'y' } })
+})
it('never reads stdin for a post whose TEXT is the message', () => {
const stdin = vi.fn(() => 'from stdin'), terminal = vi.fn(() => false)
for (const text of ['Ready', '--', '- ', ' -', '-x', '']) {
@@ -719,8 +738,8 @@ describe("a Buddy's usage line and JSON hints", () => {
})
const print = vi.fn()
const open = vi.fn(async (at: Where) => { opened.push(at); return { request, close: vi.fn(), machineId: 'machine' } })
- const run = async (argv: string[]) => {
- expect(await superTabCommand(['--tab', 'tab', ...argv], { where: () => where, pane: '%9', open, print, terminal: () => false })).toBe(1)
+ const run = async (argv: string[], terminal = false) => {
+ expect(await superTabCommand(['--tab', 'tab', ...argv], { where: () => where, pane: '%9', open, print, terminal: () => terminal })).toBe(1)
return JSON.parse(print.mock.calls.at(-1)![0]).error as string
}
return { run, asked, opened, request }
@@ -737,6 +756,8 @@ describe("a Buddy's usage line and JSON hints", () => {
const error = await run(argv)
expect(error, argv.join(' ')).not.toMatch(/stdin|TEXT\|-|<<| - /)
}
+ // A - that meets a terminal tells a Buddy to quote its JSON, not to send it on stdin.
+ expect(await run(['command', 'op-1', '-'], true)).toBe("command - reads the JSON from stdin, but stdin is a terminal, so nothing was sent. Pass it as one argument, with the JSON in single quotes: command OPERATION_ID '{...}' (an apostrophe inside it as \\u0027).")
})
it('keeps the stdin form for any other agent, and for a harness Harness cannot confirm is a Buddy', async () => {
@@ -752,6 +773,8 @@ describe("a Buddy's usage line and JSON hints", () => {
const { run, asked, opened } = buddyDeps(true)
await run(['propose', 'op-1', '{"goal":'])
expect(asked.find(([, payload]) => payload?.action === 'buddyCheck')?.[1]).toEqual({ action: 'buddyCheck', harnessId: 'buddy-h' })
+ // Through the guard's own steps (paneBuddy), without its pane check: a wording is no refusal.
+ expect(asked.map(([type]) => type)).toEqual(['agents_list', 'super_tabs'])
// Another machine named with --machine is never the one asked: the pane is this computer's.
expect(await run(['--port', '14002', '--machine', 'other', 'propose', 'op-1', '{"goal":'])).toContain('single quotes')
expect(opened).toEqual([where, where])
diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.ts
index 0601def5e..f908ba69c 100644
--- a/cli/src/superTabs/command.ts
+++ b/cli/src/superTabs/command.ts
@@ -14,7 +14,7 @@ import { isatty } from 'node:tty'
import { inDaemonPane, NOT_IN_PANE, runningPane, type PaneProbe } from './callerPane.js'
// cli.ts's way to it: this file is its door to the Swarm's code (architecture.spec.ts SWARM_DOORS).
export { buddyRefusal } from './buddyPane.js'
-import { agentShell, buddiesHere, WINDOWS_BUDDY } from './buddyPane.js'
+import { agentShell, buddiesHere, paneBuddy, WINDOWS_BUDDY } from './buddyPane.js'
import { sendPane } from '../messages/command.js'
/** A frame with its terminals, as agents_list sends them: a pty host pane is named by its instance and pane (Windows). */
@@ -89,6 +89,11 @@ function postStdin(stdin: (what: string) => string, terminal: () => boolean): st
if (!text.trim()) throw new Error(`post - read no message from stdin, so nothing was posted. Send the message on stdin: ${POST_STDIN}. A message that is only - goes on stdin too.`)
return text
}
+/** A JSON action's JSON on stdin, for its `-`; a terminal is refused as post's is, worded for a Buddy too (stdinHint). */
+function jsonStdin(action: string, stdin: (what: string) => string, terminal: () => boolean): string {
+ if (terminal()) throw new UsageError(buddy => `${action} - reads the JSON from stdin, but stdin is a terminal, so nothing was sent. Pass it as one argument, ${stdinHint(action, buddy)}.`)
+ return stdin(action)
+}
/** How long `-` waits on stdin while nothing arrives. #2355's review: `post GROUP - OPERATION_ID` from a pipe its writer left
* open (a tool that never closes it) read with no limit and waited for good. A heredoc or a pipe closes stdin at its end;
* every chunk starts the wait again, so a slow writer that keeps sending is never cut off. */
@@ -132,11 +137,8 @@ async function buddyHere(open: typeof openDaemon, local: Where, pane: string | u
const daemon = await open(local)
try {
if (platform === 'win32') return agentShell(env) && await buddiesHere(daemon) === true
- const listed = await daemon.request('agents_list')
- const caller = callerOf(Array.isArray(listed.agents) ? listed.agents as Frame[] : [], pane, local.machineId)
- if (!caller) return false
- const answer = await daemon.request('super_tabs', { action: 'buddyCheck', harnessId: caller.agentId }, 10_000)
- return answer.ok === true && answer.buddy === true
+ // The guard's own steps (buddyPane.ts paneBuddy), without its pane check: a wording, not a refusal.
+ return await paneBuddy(daemon, pane!, local.machineId) === 'buddy'
} finally { daemon.close() }
} catch { return false }
}
@@ -158,8 +160,9 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where, stdin:
else { positional.push(...argv.slice(i)); break }
}
if (!Number.isInteger(target.port) || target.port < 1 || target.port > 65535 || !identifier(target.machineId)) throw usageError()
- // `-` in the JSON's place reads it from stdin, where no shell quoting can split it.
- if (JSON_ACTIONS[positional[0]] && positional[2] === '-') positional[2] = stdin(positional[0])
+ // `-` in the JSON's place reads it from stdin, where no shell quoting can split it. A terminal is refused at once, as post's
+ // is: read, it waited 30 s for input that never comes and then said stdin was never closed (review of #2379).
+ if (JSON_ACTIONS[positional[0]] && positional[2] === '-') positional[2] = jsonStdin(positional[0], stdin, terminal)
const [action, first, second, third] = positional
if (action !== 'help' && (!identifier(tabId) || (agentId && !identifier(agentId)))) throw usageError()
const payload: Record<string, unknown> = { action, tabId, agentId }