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(cli): super-tab's usage and JSON hints offer a Buddy no stdin, and - stops waiting on an idle open stdin (#2379)

harness-for-autonomous[bot]96c318c9b146
diff --git a/cli/e2e/superTabBuddyUsage.e2e.ts b/cli/e2e/superTabBuddyUsage.e2e.ts
new file mode 100644
index 000000000..223f9be21
--- /dev/null
+++ b/cli/e2e/superTabBuddyUsage.e2e.ts
@@ -0,0 +1,43 @@
+/** A Buddy's usage line and JSON hints, from its own pane, through the real daemon: private tmux, throwaway homes and fake
+ * engines. Its guard refuses a post or a proposal read from stdin (#2358), so neither offers it the stdin form; a Builder's
+ * keep it. */
+import { mkdirSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, expect, it, onTestFailed } from 'vitest'
+import { superTabCommand } from '../src/superTabs/command.js'
+import { LocalClient } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+let daemon: IsolatedDaemon | undefined, client: LocalClient | undefined
+afterEach(async () => { client?.close(); await daemon?.close(); client = undefined; daemon = undefined })
+
+it("words a refused command for the Buddy in the pane, without stdin, and for a Builder with it", async () => {
+ const d = await IsolatedDaemon.create({ env: { ANTHROPIC_API_KEY: 'fixture-not-a-credential' } })
+ daemon = d
+ onTestFailed(() => console.log(d.log().split('\n').slice(-100).join('\n')))
+ await d.start()
+ const c = await LocalClient.connect(d); client = c
+ const cwd = join(d.projectsDir, 'chat'); mkdirSync(cwd)
+ const panes: Record<string, string> = {}
+ for (const role of ['buddy', 'dev']) {
+ const created = await c.request('agent_create', { engine: 'claude', cwd, swarmRole: role, prompt: 'hello' }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ panes[role] = await until(`${role} pane`, async () => {
+ const listed = await c.request('agents_list', {})
+ return listed.agents?.find((row: Record<string, any>) => row.id === created.agent.id && row.tmuxPane)?.tmuxPane ?? null
+ }, 30_000)
+ }
+ // Not signed in, the daemon is this computer's own id, as whereFor reads it.
+ const where = { port: d.port, dataDir: d.dataDir, machineId: d.computerId }
+ const refused = async (role: string, args: string[]) => {
+ let error = ''
+ const code = await superTabCommand(['--tab', 'tab', ...args], { where: () => where, pane: panes[role], print: text => { error = JSON.parse(text).error } })
+ expect(code).toBe(1)
+ return error
+ }
+ expect(await refused('buddy', ['post', 'chat', 'Ready'])).toContain('post GROUP TEXT OPERATION_ID [--reply-to')
+ expect(await refused('buddy', ['propose', 'op-1', '{"goal":'])).toContain("Pass it as one argument, with the JSON in single quotes: propose OPERATION_ID '{...}'")
+ for (const args of [['post', 'chat', 'Ready'], ['propose', 'op-1', '{"goal":']]) expect(await refused('buddy', args)).not.toMatch(/stdin|TEXT\|-|<</)
+ expect(await refused('dev', ['post', 'chat', 'Ready'])).toContain('post GROUP TEXT|- OPERATION_ID')
+ expect(await refused('dev', ['propose', 'op-1', '{"goal":'])).toContain("or send the JSON on stdin with - in its place: propose OPERATION_ID - <<'JSON'")
+})
diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.ts
index 61fb6ca69..f5ec968eb 100644
--- a/cli/src/superTabs/command.spec.ts
+++ b/cli/src/superTabs/command.spec.ts
@@ -1,6 +1,7 @@
-import { expect, it, vi } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { PassThrough } from 'node:stream'
import { resolve } from 'node:path'
-import { parseSuperTabArgs, superTabCommand } from './command.js'
+import { parseSuperTabArgs, readStdin, StdinIdle, superTabCommand } from './command.js'
import type { Where } from '../agentClient/daemon.js'
const where = { port: 14001, dataDir: '/fixture', machineId: 'machine' }
const prefix = ['--tab', 'tab', '--agent', 'agent']
@@ -701,3 +702,123 @@ it('reads the cost summary of the last 7 days, or of --days N up to 90', () => {
for (const argv of [[...prefix, 'costs', '--days'], [...prefix, 'costs', '--days', '0'], [...prefix, 'costs', '--days', '91'],
[...prefix, 'costs', '--days', '7x'], [...prefix, 'costs', 'extra']]) expect(() => parseSuperTabArgs(argv, where), argv.join(' ')).toThrow('harness super-tab')
})
+
+// #2360 took the stdin form out of a Buddy's help, as its guard refuses a post or proposal read from stdin (#2358). The usage
+// line and the JSON hints still offered it, so a Buddy that followed them was refused and tried again.
+describe("a Buddy's usage line and JSON hints", () => {
+ const buddyDeps = (buddy: boolean | 'fails') => {
+ const asked: Array<[string, Record<string, unknown> | undefined, number]> = [], opened: Where[] = []
+ const request = vi.fn(async (type: string, payload?: Record<string, unknown>) => {
+ asked.push([type, payload, opened.length])
+ if (type === 'agents_list') return { agents: [{ id: 'buddy-h', engine: 'claude', tmuxPane: '%9', status: 'active' }] }
+ if (payload?.action === 'buddyCheck') {
+ if (buddy === 'fails') throw new Error('daemon gone')
+ return { ok: true, buddy }
+ }
+ return { ok: true }
+ })
+ 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)
+ return JSON.parse(print.mock.calls.at(-1)![0]).error as string
+ }
+ return { run, asked, opened, request }
+ }
+ const BAD = [['post', 'lead', 'Ready'], ['propose', 'op-1', '{"goal":'], ['propose'], ['propose', 'op-1'], ['command', 'op-1', '{"a":"b', 'c"}']]
+
+ it('has no stdin form for a Buddy: its post line takes TEXT, and its JSON goes in single quotes', async () => {
+ const { run } = buddyDeps(true)
+ expect(await run(['post', 'lead', 'Ready'])).toContain('post GROUP TEXT OPERATION_ID [--reply-to')
+ expect(await run(['propose', 'op-1', '{"goal":'])).toMatch(/^The propose JSON is not valid \(.*\)\. Pass it as one argument, with the JSON in single quotes: propose OPERATION_ID '\{\.\.\.\}' \(an apostrophe inside it as \\u0027\)\.$/)
+ expect(await run(['propose'])).toContain("A line break without \\ before it ends the command; send it again with the JSON in single quotes: propose OPERATION_ID '{...}'")
+ expect(await run(['propose', 'op-1'])).toBe("propose needs its JSON after OPERATION_ID: propose op-1 JSON, with the JSON in single quotes: propose OPERATION_ID '{...}' (an apostrophe inside it as \\u0027).")
+ for (const argv of BAD) {
+ const error = await run(argv)
+ expect(error, argv.join(' ')).not.toMatch(/stdin|TEXT\|-|<<| - /)
+ }
+ })
+
+ it('keeps the stdin form for any other agent, and for a harness Harness cannot confirm is a Buddy', async () => {
+ for (const buddy of [false, 'fails'] as const) {
+ const { run } = buddyDeps(buddy)
+ expect(await run(['post', 'lead', 'Ready'])).toContain('post GROUP TEXT|- OPERATION_ID')
+ expect(await run(['propose', 'op-1', '{"goal":'])).toContain("or send the JSON on stdin with - in its place: propose OPERATION_ID - <<'JSON'")
+ expect(await run(['command', 'op-1', '{"a":"b', 'c"}'])).toContain("or send the JSON on stdin with - in its place: command OPERATION_ID - <<'JSON'")
+ }
+ })
+
+ it("asks this computer's daemon about the pane's own harness, only when the command is refused", async () => {
+ 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' })
+ // 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])
+ // A command that parses never asks.
+ const ok = buddyDeps(true)
+ await superTabCommand(['--tab', 'tab', 'post', 'lead', 'Ready', 'op-1'], { where: () => where, pane: '%9', open: async () => ({ request: ok.request, close: vi.fn(), machineId: 'machine' }), print: vi.fn() })
+ expect(ok.request).toHaveBeenCalled()
+ expect(ok.asked.some(([, payload]) => payload?.action === 'buddyCheck')).toBe(false)
+ })
+ // Windows cannot check a pty host pane (buddyPane.ts): an agent's shell on a computer running a Buddy gets a Buddy's words.
+ it('words it for a Buddy on Windows from an agent\'s shell while this computer runs one', async () => {
+ const wording = async (buddiesHere: boolean, env: NodeJS.ProcessEnv) => {
+ const print = vi.fn(), request = vi.fn(async (_type: string, payload?: Record<string, unknown>) =>
+ payload?.action === 'buddyCheck' ? { ok: true, buddiesHere } : { agents: [] })
+ await superTabCommand(['--tab', 'tab', 'post', 'lead', 'Ready'], { where: () => where, print, platform: 'win32', env, pane: undefined,
+ open: async () => ({ request, close: vi.fn(), machineId: 'machine' }) })
+ return JSON.parse(print.mock.calls.at(-1)![0]).error as string
+ }
+ expect(await wording(true, { HARNESS_PANE: 'p1:%3' })).toContain('post GROUP TEXT OPERATION_ID')
+ expect(await wording(false, { HARNESS_PANE: 'p1:%3' })).toContain('post GROUP TEXT|- OPERATION_ID')
+ expect(await wording(true, {})).toContain('post GROUP TEXT|- OPERATION_ID')
+ })
+})
+
+// #2355: post - (and command JSON -) read stdin with no limit, so a pipe left open and idle waited for good.
+describe('stdin for -', () => {
+ afterEach(() => { vi.useRealTimers() })
+ it('refuses an open stdin that sends nothing for 30 s, and lets go of it', async () => {
+ vi.useFakeTimers()
+ const stream = new PassThrough()
+ const read = readStdin(stream).catch((error: Error) => error)
+ await vi.advanceTimersByTimeAsync(29_999)
+ expect(stream.destroyed).toBe(false)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(await read).toBeInstanceOf(StdinIdle)
+ expect(stream.destroyed).toBe(true)
+ })
+
+ it('reads a slow, steady stream whole, however long it takes, and refuses one that stalls part way', async () => {
+ vi.useFakeTimers()
+ const stream = new PassThrough()
+ const read = readStdin(stream)
+ for (let line = 0; line < 20; line++) { stream.write(`line ${line}\n`); await vi.advanceTimersByTimeAsync(29_000) }
+ stream.end('last')
+ expect(await read).toBe(Array.from({ length: 20 }, (_, line) => `line ${line}\n`).join('') + 'last')
+ const stalled = new PassThrough()
+ const partial = readStdin(stalled).catch((error: Error) => error)
+ stalled.write('{"type":')
+ await vi.advanceTimersByTimeAsync(30_000)
+ expect(await partial).toBeInstanceOf(StdinIdle)
+ })
+
+ it('says how to end stdin for a post or a JSON, and sends nothing', async () => {
+ const print = vi.fn(), request = vi.fn(async () => ({ ok: true }))
+ const deps = { where: () => where, pane: undefined, open: async () => ({ request, close: vi.fn(), machineId: 'machine' }), print, terminal: () => false,
+ stdin: () => Promise.reject(new StdinIdle()) }
+ expect(await superTabCommand([...prefix, 'post', 'lead', '-', 'op-1'], deps)).toBe(1)
+ expect(JSON.parse(print.mock.calls.at(-1)![0]).error).toBe("post - read stdin until nothing more came for 30 s, but stdin was never closed, so nothing was posted. "
+ + "Close stdin after the message, as a heredoc does: post GROUP - OPERATION_ID <<'MSG' (the message on the next lines, then MSG alone on a line), or pass it as TEXT.")
+ expect(await superTabCommand([...prefix, 'command', 'op-2', '-'], deps)).toBe(1)
+ expect(JSON.parse(print.mock.calls.at(-1)![0]).error).toBe("command - read stdin until nothing more came for 30 s, but stdin was never closed, so nothing was sent. "
+ + "Close stdin after the JSON, as a heredoc does: command OPERATION_ID - <<'JSON' (the JSON on the next lines, then JSON alone on a line), or pass it as one argument.")
+ expect(request).not.toHaveBeenCalled()
+ // What arrives in time is used as before, read once.
+ const stdin = vi.fn(async () => '{"type":"work.status"}\n')
+ expect(await superTabCommand([...prefix, 'command', 'op-3', '-'], { ...deps, stdin })).toBe(0)
+ expect(stdin).toHaveBeenCalledOnce()
+ expect(request).toHaveBeenLastCalledWith('super_tabs', expect.objectContaining({ operationId: 'op-3', command: { type: 'work.status' } }), 30_000)
+ })
+})
diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.ts
index cc5d4347e..0601def5e 100644
--- a/cli/src/superTabs/command.ts
+++ b/cli/src/superTabs/command.ts
@@ -29,9 +29,22 @@ function harnessIn(frames: PaneFrame[], pane: string, machineId: string): boolea
const ELSEWHERE = 'From a harness, Swarm commands go to this computer\'s own Harness only: leave out --machine and --port, or give this computer\'s own.'
const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status [--archived [PAGE]] | messages GROUP [--thread ROOT] [--before SEQUENCE MESSAGE_ID] | message GROUP MESSAGE_ID | decisions [--answered] | costs [--days N] | post GROUP TEXT|- OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]... | react GROUP MESSAGE_ID EMOJI OPERATION_ID [--off] | command OPERATION_ID JSON | propose OPERATION_ID JSON [--attach PATH]... | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | plan [JSON] | remove-machine MACHINE_ID [--yes] | set-agents MACHINE_ID COUNT | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'
+/** A Buddy's guard refuses a post or a proposal read from stdin (#2358): there its words would skip the secret check. A Buddy
+ * that followed the stdin form here was refused and tried again (#2360 took it out of a Buddy's help), so a Buddy's usage
+ * line and JSON hints never offer it. */
+const BUDDY_USAGE = USAGE.replace('post GROUP TEXT|- OPERATION_ID', 'post GROUP TEXT OPERATION_ID')
/** The actions that take an id and then one JSON argument, and what that id names. */
const JSON_ACTIONS: Readonly<Record<string, string>> = { command: 'OPERATION_ID', propose: 'OPERATION_ID', start: 'OPERATION_ID', capacity: 'MACHINE_ID', route: 'GROUP' }
-const stdinHint = (action: string) => `or send the JSON on stdin with - in its place: ${action} ${JSON_ACTIONS[action]} - <<'JSON' (the JSON on the next lines, then JSON alone on a line)`
+const JSON_STDIN = (action: string) => `${action} ${JSON_ACTIONS[action]} - <<'JSON' (the JSON on the next lines, then JSON alone on a line)`
+const stdinHint = (action: string, buddy: boolean) => buddy
+ ? `with the JSON in single quotes: ${action} ${JSON_ACTIONS[action]} '{...}' (an apostrophe inside it as \\u0027)`
+ : `or send the JSON on stdin with - in its place: ${JSON_STDIN(action)}`
+
+/** A refusal worded for any caller, and for a Buddy (BUDDY_USAGE): which one it is is asked only once the command is refused. */
+class UsageError extends Error {
+ constructor(readonly words: (buddy: boolean) => string) { super(words(false)) }
+}
+const usageError = () => new UsageError(buddy => buddy ? BUDDY_USAGE : USAGE)
/** The JSON argument, or why it is not one.
*
@@ -40,17 +53,17 @@ const stdinHint = (action: string) => `or send the JSON on stdin with - in its p
* the shell split it into several arguments. Neither could tell what to fix, and the finished task stayed open. */
function jsonArgument(action: string, text: string): unknown {
try { return JSON.parse(text) } catch (error) {
- throw new Error(`The ${action} JSON is not valid (${(error as Error).message}). Pass it as one argument, ${stdinHint(action)}.`)
+ throw new UsageError(buddy => `The ${action} JSON is not valid (${(error as Error).message}). Pass it as one argument, ${stdinHint(action, buddy)}.`)
}
}
/** Why [positional] is not `ACTION ID JSON`, in words an agent can act on; null to leave it to the usage line. */
-function jsonShapeError(positional: readonly string[]): string | null {
+function jsonShapeError(positional: readonly string[], buddy: boolean): string | null {
const [action, first = ''] = positional
const id = JSON_ACTIONS[action]
if (!id) return null
- const hint = stdinHint(action)
+ const hint = stdinHint(action, buddy)
// Nothing after the action: the id and JSON went on the next lines, which the shell ran as commands of their own.
- if (positional.length === 1) return `${action} needs ${id} and the JSON on the same command line: ${action} ${id} JSON. A line break without \\ before it ends the command; ${hint}.`
+ if (positional.length === 1) return `${action} needs ${id} and the JSON on the same command line: ${action} ${id} JSON. A line break without \\ before it ends the command; ${buddy ? 'send it again ' : ''}${hint}.`
if (!identifier(first)) {
return (first as string).trim().startsWith('{')
? `${action} needs ${id} before the JSON: ${action} ${id} JSON. ${id === 'OPERATION_ID' ? 'Use a new unique id of letters, digits, - or _ (reuse it only to repeat an interrupted request).' : ''}`.trim()
@@ -69,16 +82,69 @@ function jsonShapeError(positional: readonly string[]): string | null {
* arrived as "-". So `-` reads the message from stdin, once, before anything is sent, and an empty or a terminal stdin is
* refused: nothing is posted, and nothing waits on a terminal for input that never comes. */
const POST_STDIN = "post GROUP - OPERATION_ID <<'MSG' (the message on the next lines, then MSG alone on a line)"
-function postStdin(stdin: () => string, terminal: () => boolean): string {
+function postStdin(stdin: (what: string) => string, terminal: () => boolean): string {
if (terminal()) throw new Error(`post - reads the message from stdin, but stdin is a terminal, so nothing was posted. Send the message on stdin: ${POST_STDIN}, or pass it as TEXT.`)
// A heredoc ends the message with one line break, which is not part of it.
- const text = stdin().replace(/\r?\n$/, '')
+ const text = stdin('post').replace(/\r?\n$/, '')
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
}
+/** 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. */
+const STDIN_IDLE_MS = 30_000
+export class StdinIdle extends Error {
+ constructor() { super(`Nothing more came on stdin for ${STDIN_IDLE_MS / 1000} s, and it was never closed.`) }
+}
+/** All of [stream], until it ends; StdinIdle once nothing has come for [idleMs], and the stream is let go, so the command can
+ * exit while its writer still holds the pipe open. */
+export function readStdin(stream: NodeJS.ReadableStream & { destroy(): void }, idleMs = STDIN_IDLE_MS): Promise<string> {
+ return new Promise((resolve, reject) => {
+ let text = '', timer: ReturnType<typeof setTimeout> | undefined
+ const wait = () => {
+ clearTimeout(timer)
+ timer = setTimeout(() => { stream.destroy(); reject(new StdinIdle()) }, idleMs)
+ }
+ stream.setEncoding('utf8')
+ stream.on('data', (chunk: string) => { text += chunk; wait() })
+ stream.once('end', () => { clearTimeout(timer); resolve(text) })
+ stream.once('error', error => { clearTimeout(timer); reject(error) })
+ wait()
+ })
+}
+/** Why `-` read nothing usable from a stdin left open, and how to end it. */
+function idleRefusal(what: string): string {
+ const waited = `${what} - read stdin until nothing more came for ${STDIN_IDLE_MS / 1000} s, but stdin was never closed`
+ return what === 'post'
+ ? `${waited}, so nothing was posted. Close stdin after the message, as a heredoc does: ${POST_STDIN}, or pass it as TEXT.`
+ : `${waited}, so nothing was sent. Close stdin after the JSON, as a heredoc does: ${JSON_STDIN(what)}, or pass it as one argument.`
+}
+/** Stands in for stdin while the arguments are parsed the first time: stdin is read only for a command that wants it. */
+class WantsStdin { constructor(readonly what: string) {} }
+
+/** Whether the harness in this pane is a Buddy, by this computer's launch record (service.ts `buddyCheck`, what turns its
+ * guard on), for a refusal's wording alone. Asked of this computer's daemon, never one named with --machine. Anything it
+ * cannot tell is no Buddy: the guard still refuses what a Buddy may not send. */
+async function buddyHere(open: typeof openDaemon, local: Where, pane: string | undefined, env: NodeJS.ProcessEnv, platform: NodeJS.Platform): Promise<boolean> {
+ // Windows has no cheap check of a pty host pane (buddyPane.ts): an agent's shell on a computer that runs a Buddy.
+ if (platform !== 'win32' && !pane) return false
+ try {
+ 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
+ } finally { daemon.close() }
+ } catch { return false }
+}
+
/** The files one proposal may carry (backend buddies.ts MAX_PROPOSAL_ATTACHMENTS). */
const MAX_PROPOSAL_FILES = 5
-export function parseSuperTabArgs(argv: readonly string[], where: Where, stdin: () => string = () => readFileSync(0, 'utf8'),
+/** [stdin] is asked for what `-` stands for: `post`'s message, or the JSON of the action it names. */
+export function parseSuperTabArgs(argv: readonly string[], where: Where, stdin: (what: string) => string = () => readFileSync(0, 'utf8'),
terminal: () => boolean = () => isatty(0)) {
const positional: string[] = []
let tabId = '', agentId = ''
@@ -91,11 +157,11 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where, stdin:
else if (flag === '--machine') target.machineId = argv[++i] ?? ''
else { positional.push(...argv.slice(i)); break }
}
- if (!Number.isInteger(target.port) || target.port < 1 || target.port > 65535 || !identifier(target.machineId)) throw new Error(USAGE)
+ 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()
+ if (JSON_ACTIONS[positional[0]] && positional[2] === '-') positional[2] = stdin(positional[0])
const [action, first, second, third] = positional
- if (action !== 'help' && (!identifier(tabId) || (agentId && !identifier(agentId)))) throw new Error(USAGE)
+ if (action !== 'help' && (!identifier(tabId) || (agentId && !identifier(agentId)))) throw usageError()
const payload: Record<string, unknown> = { action, tabId, agentId }
if (action === 'messages' && identifier(first) && positional.length === 2) payload.conversationId = first
// Older messages, a page before the cursor the last page named: its sequence and message id together, as messages may
@@ -132,12 +198,12 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where, stdin:
else if (flag === '--attach' && value && attach.length < 10) attach.push(resolve(value))
// A person's id or email, as written; the service maps it to the person (spec 2026-10-24-lead-mentions).
else if (flag === '--mention' && value?.trim()) mentions.push(value.trim())
- else throw new Error(USAGE)
+ else throw usageError()
}
// TEXT `-` is the message on stdin; any other TEXT is the message itself, and stdin is never read.
const text = second === '-' ? postStdin(stdin, terminal) : second
// A screenshot or a log may go without words.
- if (!text.trim() && !attach.length) throw new Error(USAGE)
+ if (!text.trim() && !attach.length) throw usageError()
Object.assign(payload, { action: 'command', operationId: third, ...(attach.length ? { attach } : {}),
command: { type: 'message.send', conversationId: first, text, replyTo, recipientIds: [], ...(mentions.length ? { mentions } : {}) } })
} else if (action === 'react' && identifier(first) && identifier(second) && identifier(third) && identifier(positional[4])
@@ -152,7 +218,7 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where, stdin:
for (let i = 3; i < positional.length; i += 2) {
const [flag, value] = [positional[i], positional[i + 1]]
if (flag === '--attach' && value) attach.push(resolve(value))
- else throw new Error(USAGE)
+ else throw usageError()
}
if (attach.length > MAX_PROPOSAL_FILES) throw new Error(`Attach at most ${MAX_PROPOSAL_FILES} files to a proposal.`)
// A Buddy's proposal for its owner (backend buddies.ts): only ever that command, whatever the JSON says it is.
@@ -188,21 +254,36 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where, stdin:
for (let i = 2; i < positional.length; i++) {
if (positional[i] === '--key') {
const key = keyName(positional[++i] ?? '')
- if (!key) throw new Error(USAGE)
+ if (!key) throw usageError()
keys.push(key)
} else if (text === undefined && !keys.length) text = positional[i]
- else throw new Error(USAGE)
+ else throw usageError()
}
- if (!text && !keys.length) throw new Error(USAGE)
+ if (!text && !keys.length) throw usageError()
Object.assign(payload, { operationId: `terminal-${randomUUID()}`,
command: { type: 'agent.input', agentId: first, ...(text ? { text } : {}), ...(keys.length ? { keys } : {}) } })
- } else if (!['status', 'help'].includes(action) || positional.length !== 1) throw new Error(jsonShapeError(positional) ?? USAGE)
+ } else if (!['status', 'help'].includes(action) || positional.length !== 1) {
+ throw new UsageError(buddy => jsonShapeError(positional, buddy) ?? (buddy ? BUDDY_USAGE : USAGE))
+ }
return { where: target, payload }
}
+/** The arguments, with stdin read for `-` only when they want it, and then at most until it idles (readStdin). */
+async function parse(argv: readonly string[], local: Where, stdin: () => string | Promise<string>, terminal?: () => boolean) {
+ try {
+ return parseSuperTabArgs(argv, local, what => { throw new WantsStdin(what) }, terminal)
+ } catch (error) {
+ if (!(error instanceof WantsStdin)) throw error
+ const text = await Promise.resolve().then(stdin).catch(failure => {
+ throw failure instanceof StdinIdle ? new Error(idleRefusal(error.what)) : failure
+ })
+ return parseSuperTabArgs(argv, local, () => text, terminal)
+ }
+}
+
export async function superTabCommand(argv: readonly string[], deps: {
where?: () => Where; open?: typeof openDaemon; print?: (text: string) => void; pane?: string; probe?: PaneProbe; fetch?: typeof fetch; env?: NodeJS.ProcessEnv
- platform?: NodeJS.Platform; stdin?: () => string; terminal?: () => boolean
+ platform?: NodeJS.Platform; stdin?: () => string | Promise<string>; terminal?: () => boolean
} = {}): Promise<number> {
let daemon: Daemon | null = null
let operationId: unknown
@@ -214,7 +295,11 @@ export async function superTabCommand(argv: readonly string[], deps: {
if (running.refused) throw new Error(running.refused)
const pane = running.pane
const local = (deps.where ?? (() => whereFor(pane)))()
- const request = parseSuperTabArgs(argv, local, deps.stdin, deps.terminal)
+ const request = await parse(argv, local, deps.stdin ?? (() => readStdin(process.stdin)), deps.terminal)
+ .catch(async error => {
+ if (error instanceof UsageError && await buddyHere(open, local, pane, env, platform)) throw new Error(error.words(true))
+ throw error
+ })
operationId = request.payload.operationId
// A harness reaches the Swarm through this computer's Harness alone (second review of #2087: a Buddy's --machine reached
// the owner's other Mac, which knew no pane there). The daemon refuses an agent's request from another computer as well.