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.

Super Tab: Lead reads and types into a worker's terminal (CLI) (#1646)

0xken15218f482b441d
diff --git a/cli/e2e/harness/realBackend.ts b/cli/e2e/harness/realBackend.ts
index a1d499898..8d1a0b6fb 100644
--- a/cli/e2e/harness/realBackend.ts
+++ b/cli/e2e/harness/realBackend.ts
@@ -149,6 +149,7 @@ export async function signIn(backend: RealBackend, a: Account, env: Record<strin
await before?.(daemon)
await daemon.start()
await untilDaemon('connected', async () => (await (await fetch(`http://127.0.0.1:${daemon.port}/api/status`,
- { headers: { 'x-adapter-local': '1' } })).json()).connected === true, 60_000, 200)
+ // Without the local credential the status is cut down to what says a daemon is here (hookServer.ts `publicStatus`).
+ { headers: daemon.localHeaders() })).json()).connected === true, 60_000, 200)
return { daemon, machineId, client: await LocalClient.connect(daemon, { machineId }) }
}
diff --git a/cli/e2e/superTabTerminal.e2e.ts b/cli/e2e/superTabTerminal.e2e.ts
new file mode 100644
index 000000000..cc1b019eb
--- /dev/null
+++ b/cli/e2e/superTabTerminal.e2e.ts
@@ -0,0 +1,122 @@
+/** A Lead reads and types into a worker's terminal (spec/2026-10-23-lead-sees-agent-terminal.md), end to end: the real
+ * backend, two isolated daemons of one account (the Lead's machine and the worker's), fake Claude Code engines and the
+ * `super-tab screen` and `type` commands an agent runs. The worker sits on a permission prompt; its host alerts the Lead
+ * once after 3 minutes, the Lead reads the screen and answers it, and the worker may not read the Lead's.
+ * Needs the backend's in-memory Mongo and Redis (HARNESS_E2E_SERVICES_DIR, see harness/realBackend.ts). */
+import { randomUUID } from 'node:crypto'
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
+import { superTabCommand } from '../src/superTabs/command.js'
+import { CLI_ROOT, until, type IsolatedDaemon } from './harness/daemon.js'
+import type { LocalClient } from './harness/client.js'
+import { account, signIn, startRealBackend, type RealBackend } from './harness/realBackend.js'
+
+const owner = account('owner')
+let backend: RealBackend
+interface Side { daemon: IsolatedDaemon; machineId: string; client: LocalClient }
+const FIXTURE_KEYS = { ANTHROPIC_API_KEY: 'fixture-not-a-credential', OPENAI_API_KEY: 'fixture-not-a-credential' }
+const CONFIG = { engine: 'claude', model: 'sonnet', effort: 'high', contextWindow: null, engineVersion: null }
+const tail = (text: string, lines: number) => text.split('\n').slice(-lines).join('\n')
+
+async function create(s: Side, folder: string): Promise<Record<string, any>> {
+ const cwd = join(s.daemon.projectsDir, folder)
+ mkdirSync(cwd, { recursive: true })
+ const created = await s.client.request('agent_create', { engine: 'claude', cwd, bypassPermission: false }, 90_000)
+ expect(created.error, `${folder}: ${JSON.stringify(created)}`).toBeUndefined()
+ return until(`${folder} to bind its conversation`, async () => {
+ const agents = (await s.client.request<{ agents: Array<Record<string, any>> }>('agents_list', {}, 30_000)).agents
+ const agent = agents.find(a => a.id === created.agent.id)
+ return agent?.sessionId && agent.status === 'active' ? agent : null
+ }, 60_000, 500)
+}
+
+/** What an agent on `s` runs: `harness super-tab --tab TAB --agent AGENT …`, its printed answer and exit code. */
+async function superTab(s: Side, tab: string, agent: string, args: string[]): Promise<{ code: number; out: string }> {
+ let out = ''
+ const code = await superTabCommand(['--tab', tab, '--agent', agent, ...args],
+ { where: () => ({ port: s.daemon.port, dataDir: s.daemon.dataDir, machineId: s.machineId }), print: text => { out = text } })
+ return { code, out }
+}
+
+describe.skipIf(!process.env.HARNESS_E2E_SERVICES_DIR)('a Lead driving a worker\'s terminal, real backend', () => {
+ beforeAll(async () => { backend = await startRealBackend([owner], () => {}) }, 180_000)
+ afterAll(async () => { await backend?.stop() })
+
+ it('reads the worker\'s screen, is alerted once to its waiting prompt, answers it, and the worker may not read the Lead\'s', async () => {
+ const sides: Side[] = []
+ for (let i = 0; i < 2; i++) {
+ const side = await signIn(backend, owner, FIXTURE_KEYS, daemon => {
+ writeFileSync(join(daemon.engineConfig.codexHome, 'models_cache.json'),
+ readFileSync(join(CLI_ROOT, 'src/lib/__fixtures__/codex-home-0.160/models_cache.json')))
+ })
+ sides.push(side)
+ }
+ const [L, W] = sides as [Side, Side]
+ onTestFailed(() => {
+ for (const [name, s] of [['Lead machine', L], ['worker machine', W]] as const) console.log(`---- ${name}\n${tail(s.daemon.log(), 120)}`)
+ console.log(`---- backend\n${tail(readFileSync(backend.logPath, 'utf8'), 80)}`)
+ })
+ const leadHarness = await create(L, 'lead'), workerHarness = await create(W, 'worker')
+
+ // The person makes the Swarm: its Lead on one machine, a worker in a group on the other.
+ const tab = (await backend.api(owner, '/api/super-tabs', 'POST', { operationId: randomUUID(), name: 'Terminal' })).body.data.id as string
+ const run = async (command: Record<string, unknown>) => {
+ const r = await backend.api(owner, `/api/super-tabs/${tab}/commands`, 'POST', { operationId: randomUUID(), command })
+ expect(r.status, JSON.stringify(r.body)).toBe(200)
+ return r.body.data.result as Record<string, any>
+ }
+ const lead = (await run({ type: 'agent.add', conversationId: 'lead', machineId: L.machineId, harnessId: leadHarness.id, name: 'Lead', configuration: CONFIG, lead: true })).agentId as string
+ const group = (await run({ type: 'conversation.create', title: 'Terminal', brief: 'Answer the prompt', checks: [] })).conversationId as string
+ const worker = (await run({ type: 'agent.add', conversationId: group, machineId: W.machineId, harnessId: workerHarness.id, name: 'Worker', configuration: CONFIG, lead: false })).agentId as string
+ const rows = async () => ((await backend.api(owner, `/api/super-tabs/${tab}/conversations/${group}/messages`)).body.data.messages as Array<Record<string, any>>)
+ // Each joins as a launched agent does, which starts its machine's host.
+ for (const [s, id] of [[L, lead], [W, worker]] as const) expect((await superTab(s, tab, id, ['status'])).code).toBe(0)
+
+ // The worker asks permission to run a command, and waits on it.
+ W.client.send('message', { agentId: workerHarness.id, content: '!permit printf terminal-check' })
+ const asked = Date.now()
+ let last = ''
+ const prompt = await until('the Lead to read the worker\'s prompt', async () => {
+ const read = await superTab(L, tab, lead, ['screen', worker])
+ last = read.out
+ return read.code === 0 && read.out.includes('Do you want to proceed?') ? read.out : null
+ }, 60_000, 1_000).catch(error => { throw new Error(`${(error as Error).message}; last read: ${last}`) })
+ expect(prompt).toContain('printf terminal-check')
+ expect(prompt).not.toMatch(/\x1b\[/)
+ const scrolled = await superTab(L, tab, lead, ['screen', worker, '--scrollback', '50'])
+ expect(scrolled.code, scrolled.out).toBe(0)
+ expect(scrolled.out).toContain('Do you want to proceed?')
+
+ // Only the Lead of the worker's project may: the worker cannot read the Lead's terminal.
+ const refused = await superTab(W, tab, worker, ['screen', lead])
+ expect(refused.code).toBe(1)
+ expect(JSON.parse(refused.out)).toMatchObject({ error: 'LEAD_REQUIRED' })
+
+ // After 3 minutes on the prompt, one alert, and no more while it still waits.
+ const alerts = async () => (await rows()).filter(m => m.source?.kind === 'terminal-alert')
+ const alert = await until('the prompt alert', async () => { const found = await alerts(); return found.length ? found : null }, 5 * 60_000, 5_000)
+ expect(Date.now() - asked).toBeGreaterThanOrEqual(3 * 60_000 - 15_000)
+ expect(alert).toHaveLength(1)
+ expect(alert[0]).toMatchObject({ source: { kind: 'terminal-alert', agentId: worker, alert: 'prompt' } })
+ expect(alert[0].text).not.toContain('printf')
+ await new Promise(resolve => setTimeout(resolve, 35_000))
+ expect(await alerts()).toHaveLength(1)
+
+ // The Lead answers Yes; the worker runs the command and the prompt is gone.
+ const typed = await superTab(L, tab, lead, ['type', worker, '--key', '1'])
+ expect(typed.code, typed.out).toBe(0)
+ expect(JSON.parse(typed.out)).toEqual({ requestId: expect.any(String), ok: true })
+ const after = await until('the worker to run the command', async () => {
+ const read = await superTab(L, tab, lead, ['screen', worker])
+ return read.out.includes('ran printf terminal-check') && !read.out.includes('Do you want to proceed?') ? read.out : null
+ }, 30_000, 1_000)
+ expect(after).toContain('ran printf terminal-check')
+ // The input is logged in the worker's group; the screens never are.
+ const history = await rows()
+ const inputs = history.filter(m => m.source?.kind === 'terminal-input')
+ expect(inputs).toHaveLength(1)
+ expect(inputs[0].text).toMatch(/typed 1 in .+'s terminal$/)
+ expect(history.some(m => String(m.text).includes('Do you want to proceed?'))).toBe(false)
+ }, 9 * 60_000)
+})
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index 63906622e..dbe22db12 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -196,7 +196,7 @@ describe('the core API services stand on', () => {
expect(createCoreApi({ ...deps, cloud }).cloud).toBe(cloud)
// The Super Tab service's door, the same way.
expect(core.superTabs).toBeUndefined()
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }
expect(createCoreApi({ ...deps, superTabs }).superTabs).toBe(superTabs)
// The devices' way to its card requests, the same way.
expect(core.superTabRequest).toBeUndefined()
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index d2c8761a3..4075d8f29 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -1,3 +1,4 @@
+import type { MessageHold } from '../engines/facets/screen.js'
import type { ProductUsageLaunchSignal } from '../lib/productUsageSignals.js'
import type { ProductUsageMetric } from '../lib/productUsageContract.js'
import type { PreparedHandoff, HandoffPermit, HandoffOutcome } from '../lib/handoffAuthority.js'
@@ -1186,7 +1187,14 @@ export interface SuperTabsCore {
* state wakes it only as the core starts, so a machine that joined a Swarm while running never invited anyone and
* each member's pane read "must be online" (River on a contributed machine, 2026-10-23). */
shareObservers(): void
-}
+ /** A member's terminal as plain text for its Lead (core/superTabTerminal.ts): the visible screen, with up to 200 lines
+ * of scrollback when asked, and what the screen reader says it waits on (a permission prompt, a question). */
+ screen(agentId: string, scrollback: number): Promise<SuperTabScreen>
+ /** Text, then each key by its tmux name, typed into a member's terminal under the pane's write lock. */
+ input(agentId: string, text: string, keys: string[]): Promise<SuperTabTyped>
+}
+export type SuperTabScreen = { ok: true; text: string; hold: MessageHold | null } | { ok: false; error: string }
+export type SuperTabTyped = { ok: true } | { ok: false; error: string }
/** What the cloud service answers the core: done, or why not, in words a person reads. */
export type CloudResult = { ok: true; detail?: string } | { ok: false; error: string; detail?: string }
diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.ts
index e5fadad49..0f193da7a 100644
--- a/cli/src/core/experimentQueries.spec.ts
+++ b/cli/src/core/experimentQueries.spec.ts
@@ -28,7 +28,7 @@ describe('the cloud agents\' doors', () => {
describe('the Super Tab service\'s door', () => {
it('is the Super Tab service\'s alone, and hands its members\' waits to the core whole', async () => {
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }
const core = fakeCore({ superTabs })
const both = new Set(['orchestrator', 'superTabs'])
const item = { agentId: 'a1', requestId: 'supertab:x:blocked', superTab: 'Pilot', attention: 'stuck', text: 'Stuck: no key' }
@@ -41,7 +41,7 @@ describe('the Super Tab service\'s door', () => {
})
it('hands it the Swarm cards and a Lead\'s recap the same way, to the Super Tab service alone', async () => {
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }
const core = fakeCore({ superTabs })
const both = new Set(['orchestrator', 'superTabs'])
const recap = { tabId: 't1', leadId: 'l1', text: 'Shipped', at: 1, none: false }
@@ -58,10 +58,31 @@ describe('the Super Tab service\'s door', () => {
})
it('asks for Share when a Swarm host here has members to show its agents to', async () => {
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }
expect(await answerExperimentQuery(fakeCore({ superTabs }), new Set(['superTabs']), 'superTabs', 'super_tab_observers', {})).toEqual({})
expect(superTabs.shareObservers).toHaveBeenCalledOnce()
})
+ it('reads and types a member\'s terminal for the Super Tab service alone, refusing what is not well formed', async () => {
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(),
+ screen: vi.fn(async () => ({ ok: true as const, text: 'Allow?', hold: null })), input: vi.fn(async () => ({ ok: true as const })) }
+ const core = fakeCore({ superTabs }), both = new Set(['orchestrator', 'superTabs'])
+ expect(await answerExperimentQuery(core, both, 'superTabs', 'super_tab_screen', { agentId: 'h1', scrollback: 40 })).toEqual({ ok: true, text: 'Allow?', hold: null })
+ expect(superTabs.screen).toHaveBeenLastCalledWith('h1', 40)
+ await answerExperimentQuery(core, both, 'superTabs', 'super_tab_screen', { agentId: 'h1' })
+ expect(superTabs.screen).toHaveBeenLastCalledWith('h1', 0)
+ expect(await answerExperimentQuery(core, both, 'superTabs', 'super_tab_input', { agentId: 'h1', text: 'yes', keys: ['Enter'] })).toEqual({ ok: true })
+ expect(superTabs.input).toHaveBeenLastCalledWith('h1', 'yes', ['Enter'])
+ await answerExperimentQuery(core, both, 'superTabs', 'super_tab_input', { agentId: 'h1', keys: ['1'] })
+ expect(superTabs.input).toHaveBeenLastCalledWith('h1', '', ['1'])
+ for (const [query, payload] of [['super_tab_screen', { agentId: 'bad id' }], ['super_tab_screen', { agentId: 'h1', scrollback: 'x' }],
+ ['super_tab_input', { agentId: 'h1', text: 7 }], ['super_tab_input', { agentId: 'h1', keys: [1] }], ['super_tab_input', { agentId: 'h1', keys: 'Enter' }]] as const) {
+ expect(await answerExperimentQuery(core, both, 'superTabs', query, payload)).toEqual({ ok: false, error: 'INVALID_REQUEST' })
+ }
+ for (const query of ['super_tab_screen', 'super_tab_input']) {
+ expect(await answerExperimentQuery(core, both, 'orchestrator', query, { agentId: 'h1' })).toEqual({ error: 'NOT_SUPER_TABS' })
+ expect(await answerExperimentQuery(fakeCore(), both, 'superTabs', query, { agentId: 'h1' })).toEqual({ error: 'NOT_SUPER_TABS' })
+ }
+ })
})
describe('what an experiment in its own process may ask of the core', () => {
diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.ts
index d967d35dd..a38a19560 100644
--- a/cli/src/core/experimentQueries.ts
+++ b/cli/src/core/experimentQueries.ts
@@ -24,7 +24,9 @@
* - `super_tab_cards`, `super_tab_card_recap`: the Swarms' cards and a Lead's last message for the Harness Pro
* (`core.superTabs`, core/superTabCards.ts), for the Super Tab service alone;
* - `super_tab_observers`: members may watch an agent here, so Share must run (`core.superTabs`), for the Super Tab
- * service alone.
+ * service alone;
+ * - `super_tab_screen`, `super_tab_input`: a member's terminal read as plain text and typed into for its Lead
+ * (`core.superTabs`, core/superTabTerminal.ts), for the Super Tab service alone.
* The core answers them only for the experiments (core/api.ts `EXPERIMENTS`): creating an agent or
* telling the windows something is no other process's to ask. The process's side is
* services/processCoreApi.ts. Agent Messages, an experiment until 2026-10-12, asks a few of the same and is
@@ -38,7 +40,7 @@ import { nativeTurnCursorIn } from '../lib/nativeTurnObservations.js'
type Payload = Record<string, unknown>
type Core = Pick<CoreApi, 'agents' | 'turns' | 'clients' | 'daemon' | 'account' | 'cloud' | 'superTabs' | 'transcripts'>
-const QUERIES: ReadonlySet<string> = new Set(['shown', 'close_swarm', 'stopped', 'gone', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention', 'super_tab_cards', 'super_tab_card_recap', 'super_tab_observers'])
+const QUERIES: ReadonlySet<string> = new Set(['shown', 'close_swarm', 'stopped', 'gone', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention', 'super_tab_cards', 'super_tab_card_recap', 'super_tab_observers', 'super_tab_screen', 'super_tab_input'])
const METHODS: ReadonlySet<string> = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
const text = (value: unknown): string => (typeof value === 'string' ? value : '')
@@ -156,6 +158,15 @@ export async function answerExperimentQuery(core: Core, experiments: ReadonlySet
if (service !== 'superTabs' || !core.superTabs) return { error: 'NOT_SUPER_TABS' }
core.superTabs.shareObservers()
return {}
+ case 'super_tab_screen':
+ case 'super_tab_input': {
+ if (service !== 'superTabs' || !core.superTabs) return { error: 'NOT_SUPER_TABS' }
+ const { agentId, scrollback = 0, text: typed = '', keys = [] } = payload
+ if (!/^[A-Za-z0-9_-]{1,160}$/.test(text(agentId)) || typeof scrollback !== 'number' || typeof typed !== 'string'
+ || !Array.isArray(keys) || !keys.every(key => typeof key === 'string')) return { ok: false, error: 'INVALID_REQUEST' }
+ return { ...query === 'super_tab_screen' ? await core.superTabs.screen(agentId as string, scrollback)
+ : await core.superTabs.input(agentId as string, typed, keys as string[]) }
+ }
case 'account': {
const known = await core.account.identity()
return known ? { ...known } : { error: 'ACCOUNT_UNAVAILABLE' }
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 9a3162d1d..56772e1f2 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -211,6 +211,7 @@ import { createSharingLink } from './sharingLink.js'
import { createAgentSettingsSync, createExperimentHooks, wakeExperiments } from './experiments.js'
import { answerExperimentQuery, createForExperiment, creationForExperiment } from './experimentQueries.js'
import { createSuperTabAttention } from './superTabAttention.js'
+import { createSuperTabTerminal } from './superTabTerminal.js'
import { createSuperTabCards } from './superTabCards.js'
import { answerConnectorsQuery } from './connectorsQueries.js'
import { answerSharedMachinesQuery } from './sharedMachinesQueries.js'
@@ -850,6 +851,16 @@ async function runForeground(session: AuthSession | null): Promise<void> {
send: (frame) => ports.devices?.card(frame),
asking: (agentId) => [...openQuestions.values()].some((asked) => asked.agentId === agentId),
})
+ // A member's terminal for its Lead (core/superTabTerminal.ts): read plain, typed under the pane's write lock, which is
+ // built below, after the inputs.
+ const superTabTerminal = createSuperTabTerminal({
+ resolve: (agentId) => registry.byAgent(agentId),
+ capture: (session, options) => terminals.capture(session, options),
+ read: (session, capture) => screens.read(session, capture),
+ type: typeTerminal,
+ key: keyTerminal,
+ locked: (agentId, write) => deviceInput.legacyWrite(agentId, write),
+ })
// The Swarms' cards and Leads' recaps for the Harness Pro, on the devices alone (core/superTabCards.ts): kept whole, and shown
// again to a dial that attaches.
const routeSuperTabs = (payload: Record<string, unknown>): Promise<Record<string, unknown>> => new Promise((resolve) => {
@@ -872,7 +883,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
cloud: cloudDoors,
superTabs: { attention: (items) => superTabWaits.attention(items), cards: (items) => superTabCards.cards(items), cardRecap: (recap) => superTabCards.recap(recap),
// In the core's own process Share was started with it; out of it, the master starts Share's process.
- shareObservers: () => { if (outOfProcess.has('sharing')) coreLink.want('sharing') } },
+ shareObservers: () => { if (outOfProcess.has('sharing')) coreLink.want('sharing') },
+ screen: (agentId, scrollback) => superTabTerminal.screen(agentId, scrollback),
+ input: (agentId, text, keys) => superTabTerminal.input(agentId, text, keys) },
// The devices' `cardsWanted`, `cardRecap` and `cardOpen`, and no other action of the Super Tab service (core/superTabCards.ts `ask`).
superTabRequest: (payload) => superTabCards.ask(payload),
cloudRows: () => (cloudAgents?.dialRows() ?? []) as unknown as RegisteredSession[],
diff --git a/cli/src/core/superTabTerminal.spec.ts b/cli/src/core/superTabTerminal.spec.ts
new file mode 100644
index 000000000..c12a09b91
--- /dev/null
+++ b/cli/src/core/superTabTerminal.spec.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../lib/registry.js'
+import type { ScreenReading } from '../engines/facets/screen.js'
+import { createSuperTabTerminal } from './superTabTerminal.js'
+
+const session = { agentId: 'h1', engine: 'claude' } as RegisteredSession
+const reading = (messageHold: ScreenReading['messageHold']) => ({ messageHold } as ScreenReading)
+
+function setup(over: { captured?: string | null; reading?: ScreenReading | null; typed?: boolean; keyed?: (key: string) => boolean } = {}) {
+ const writes: string[] = [], lockedFor: string[] = []
+ const deps = {
+ resolve: vi.fn((id: string) => id === 'h1' ? session : undefined),
+ capture: vi.fn(async () => over.captured === null ? { state: 'failed' as const, reason: 'pane gone' } : { state: 'succeeded' as const, value: over.captured ?? 'Allow? \u001b[1m1. Yes\u001b[0m' }),
+ read: vi.fn(async () => over.reading === undefined ? reading('permission_open') : over.reading),
+ type: vi.fn(async (_id: string, text: string) => { writes.push(`text:${text}`); return over.typed ?? true }),
+ key: vi.fn(async (_id: string, key: string) => { writes.push(`key:${key}`); return over.keyed?.(key) ?? true }),
+ locked: <T>(id: string, write: () => Promise<T>) => { lockedFor.push(id); return write() },
+ }
+ return { deps, writes, lockedFor, terminal: createSuperTabTerminal(deps) }
+}
+
+describe('a Lead reading and typing into a Swarm member\'s terminal', () => {
+ it('reads the visible screen as plain text, with what the screen reader says it waits on', async () => {
+ const { deps, terminal } = setup()
+ expect(await terminal.screen('h1', 0)).toEqual({ ok: true, text: 'Allow? 1. Yes', hold: 'permission_open' })
+ expect(deps.capture).toHaveBeenCalledWith(session, { mode: 'visible', ansi: false })
+ expect(deps.read).toHaveBeenCalledWith(session, 'Allow? 1. Yes')
+ })
+
+ it('adds scrollback on request, never more than 200 lines', async () => {
+ const { deps, terminal } = setup({ reading: null })
+ expect(await terminal.screen('h1', 50)).toEqual({ ok: true, text: 'Allow? 1. Yes', hold: null })
+ expect(deps.capture).toHaveBeenLastCalledWith(session, { mode: 'recent_unwrapped', historyLines: 50, ansi: false })
+ await terminal.screen('h1', 5_000)
+ expect(deps.capture).toHaveBeenLastCalledWith(session, { mode: 'recent_unwrapped', historyLines: 200, ansi: false })
+ })
+
+ it('says plainly when the agent or its screen is not there', async () => {
+ expect(await setup().terminal.screen('gone', 0)).toEqual({ ok: false, error: 'The agent is not running on this machine.' })
+ expect(await setup({ captured: null }).terminal.screen('h1', 0)).toEqual({ ok: false, error: 'Could not read the terminal: pane gone' })
+ })
+
+ it('types the text, then each key in order, under the pane\'s write lock', async () => {
+ const { lockedFor, writes, terminal } = setup()
+ expect(await terminal.input('h1', 'yes', ['Down', 'Enter'])).toEqual({ ok: true })
+ expect(writes).toEqual(['text:yes', 'key:Down', 'key:Enter'])
+ expect(lockedFor).toEqual(['h1'])
+ writes.length = 0
+ expect(await terminal.input('h1', '', ['1'])).toEqual({ ok: true })
+ expect(writes).toEqual(['key:1'])
+ })
+
+ it('stops at the first write the terminal refuses, and refuses an agent that is not here or nothing to type', async () => {
+ const refused = setup({ keyed: key => key !== 'Up' })
+ expect(await refused.terminal.input('h1', 'a', ['Up', 'Enter'])).toEqual({ ok: false, error: 'The terminal did not take the key Up.' })
+ expect(refused.writes).toEqual(['text:a', 'key:Up'])
+ const untyped = setup({ typed: false })
+ expect(await untyped.terminal.input('h1', 'a', ['Enter'])).toEqual({ ok: false, error: 'The terminal did not take the text.' })
+ expect(untyped.writes).toEqual(['text:a'])
+ expect(await setup().terminal.input('gone', 'a', [])).toEqual({ ok: false, error: 'The agent is not running on this machine.' })
+ expect(await setup().terminal.input('h1', '', [])).toEqual({ ok: false, error: 'Nothing to type.' })
+ })
+})
diff --git a/cli/src/core/superTabTerminal.ts b/cli/src/core/superTabTerminal.ts
new file mode 100644
index 000000000..56c5f31de
--- /dev/null
+++ b/cli/src/core/superTabTerminal.ts
@@ -0,0 +1,52 @@
+/**
+ * A Swarm member's terminal for its Lead (spec/2026-10-23-lead-sees-agent-terminal.md): the screen as plain text, and
+ * text and named keys typed into it. Workers got stuck on what only their terminal showed (a permission prompt, a
+ * usage-limit screen, a model picker) and only a person at that machine could clear it. The Super Tab service decides
+ * who may ask (only the backend's relay of the project's Lead or a person reaches it); the core reads and writes the
+ * pane as every other writer does, under the pane's write lock.
+ */
+import { stripVTControlCharacters } from 'node:util'
+import type { ScreenReading } from '../engines/facets/screen.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import type { TerminalCaptureOptions, TerminalReadResult } from '../lib/terminalTypes.js'
+import type { SuperTabScreen, SuperTabTyped } from './api.js'
+
+export interface SuperTabTerminalDeps {
+ resolve(agentId: string): RegisteredSession | undefined
+ capture(session: RegisteredSession, options: TerminalCaptureOptions): Promise<TerminalReadResult<string>>
+ read(session: RegisteredSession, capture: string | null): Promise<ScreenReading | null>
+ /** Literal text, never followed by Enter (`terminals/control.ts` `typeTerminal`). */
+ type(agentId: string, text: string): Promise<boolean>
+ /** One key by its tmux name (`Enter`, `C-c`), as `terminals/control.ts` `keyTerminal` takes it. */
+ key(agentId: string, key: string): Promise<boolean>
+ /** The pane's write lock (`deviceInput.ts` `legacyWrite`), so a device's write is never interleaved. */
+ locked<T>(agentId: string, write: () => Promise<T>): Promise<T>
+}
+
+/** The spec's cap; the tmux capture keeps at most 300 lines in any case. */
+const MAX_SCROLLBACK = 200
+const GONE = { ok: false as const, error: 'The agent is not running on this machine.' }
+
+export function createSuperTabTerminal({ resolve, capture, read, type, key, locked }: SuperTabTerminalDeps) {
+ return {
+ async screen(agentId: string, scrollback: number): Promise<SuperTabScreen> {
+ const session = resolve(agentId)
+ if (!session) return GONE
+ const lines = Math.min(MAX_SCROLLBACK, Math.max(0, Math.floor(scrollback)))
+ const captured = await capture(session, lines ? { mode: 'recent_unwrapped', historyLines: lines, ansi: false } : { mode: 'visible', ansi: false })
+ if (captured.state !== 'succeeded') return { ok: false, error: `Could not read the terminal: ${captured.reason}` }
+ // tmux without -e still leaves the odd escape (a title, a cursor move); the Lead reads words, never colours.
+ const text = stripVTControlCharacters(captured.value)
+ return { ok: true, text, hold: (await read(session, text))?.messageHold ?? null }
+ },
+ async input(agentId: string, text: string, keys: string[]): Promise<SuperTabTyped> {
+ if (!resolve(agentId)) return GONE
+ if (!text && !keys.length) return { ok: false, error: 'Nothing to type.' }
+ return locked(agentId, async () => {
+ if (text && !await type(agentId, text)) return { ok: false, error: 'The terminal did not take the text.' }
+ for (const name of keys) if (!await key(agentId, name)) return { ok: false, error: `The terminal did not take the key ${name}.` }
+ return { ok: true }
+ })
+ },
+ }
+}
diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.ts
index d890fc1cd..4350598be 100644
--- a/cli/src/lib/swarmSkills.spec.ts
+++ b/cli/src/lib/swarmSkills.spec.ts
@@ -41,6 +41,8 @@ describe('built-in Swarm skills', () => {
// The owner's approved text (2026-10-22, with the Lead recovery guidance of 2026-10-23), byte for byte; the Lead's gains only the approved 2-hour line (2026-10-23).
const sha = (text: string) => createHash('sha256').update(text).digest('hex')
+ // The approved terminal line (spec/2026-10-23-lead-sees-agent-terminal.md), the Lead's alone, in both modes.
+ const terminal = '- When a worker seems stuck, read its terminal; answer prompts within its task; ask the owner before approving anything risky.\n'
const twoHours = '- A Builder or Reviewer that has been down for 2 hours (machine offline, session gone or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).\n'
it.each([
['lead', '5fc83d8c43b66b44cdab27b48235dbc86b7ab11a57153edc1ae7e92831642a8e'],
@@ -54,12 +56,19 @@ describe('built-in Swarm skills', () => {
const text = readFileSync(prepared.file, 'utf8')
expect(text.startsWith(`---\nname: swarm-${role}\n`)).toBe(true)
expect(text.split(twoHours)).toHaveLength(role === 'lead' ? 2 : 1)
- expect(sha(text.replace(twoHours, ''))).toBe(sha256)
+ expect(text.split(terminal)).toHaveLength(role === 'lead' ? 2 : 1)
+ expect(sha(text.replace(twoHours, '').replace(terminal, ''))).toBe(sha256)
}
})
it('adds the 2-hour line to section 7 right after the 6-hour rule', () => {
const text = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session' }).file, 'utf8')
- expect(text).toContain(`reassign work that has not moved for 6 hours; report on-screen trust, sign-in or permission questions in chat, naming the machine owner who can answer.\n${twoHours}- Keep each worker supplied`)
+ expect(text).toContain(`reassign work that has not moved for 6 hours; report on-screen trust, sign-in or permission questions in chat, naming the machine owner who can answer.\n${twoHours}`)
+ })
+ it('adds the terminal line where each Lead skill keeps work moving, right after the silent-worker rule', () => {
+ const orchestration = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session' }).file, 'utf8')
+ expect(orchestration).toContain(`naming the machine owner who can answer.\n${twoHours}${terminal}- Keep each worker supplied`)
+ const plain = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode: 'default' }).file, 'utf8')
+ expect(plain).toContain(`- A worker with active work that has said nothing for 20 minutes: ask it.\n${terminal}- A Builder or Reviewer`)
})
// The owner's approved Default texts (attached to the spec, 2026-10-23), byte for byte.
it.each([
@@ -69,7 +78,9 @@ describe('built-in Swarm skills', () => {
] as const)('writes the owner\'s Default %s skill byte for byte, with a prompt line that fits it', (role, sha256) => {
expect(parseSwarmSkill({ role, key: 'session', mode: 'default' })).toEqual({ role, key: 'session', mode: 'default' })
const prepared = prepareSwarmSkill(fixture(), { role, key: 'session', mode: 'default' })
- expect(sha(readFileSync(prepared.file, 'utf8'))).toBe(sha256)
+ const text = readFileSync(prepared.file, 'utf8')
+ expect(text.split(terminal)).toHaveLength(role === 'lead' ? 2 : 1)
+ expect(sha(text.replace(terminal, ''))).toBe(sha256)
expect(prepared.instructions).toBe(`Use the swarm-${role} skill for this session: the team process; otherwise work your usual way. Before working, read ${JSON.stringify(prepared.file)} with your file or shell tool.`)
})
diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.ts
index 5c1730e5a..29086b950 100644
--- a/cli/src/lib/swarmSkills.ts
+++ b/cli/src/lib/swarmSkills.ts
@@ -117,6 +117,7 @@ For large work, post the group plan and get the owner's ok before assigning; onc
- Rulings, not stalls: when a Builder hits an ambiguity you can settle, settle it and record "Ruling: what — why — cost if wrong". Ask the person only what changes what gets built.
- Each time you are woken, look at active work. Ask a worker with active work that has said nothing for 20 minutes; reassign work that has not moved for 6 hours; report on-screen trust, sign-in or permission questions in chat, naming the machine owner who can answer.
- A Builder or Reviewer that has been down for 2 hours (machine offline, session gone or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).
+- When a worker seems stuck, read its terminal; answer prompts within its task; ask the owner before approving anything risky.
- Keep each worker supplied: have its next group ready before it finishes, so nobody waits for you.
- Cancel a duplicate, obsolete or wrong task with a reason.
- When a worker finishes: reuse, keep or stop. Prefer stop unless more work is coming soon.
@@ -385,6 +386,7 @@ Keep each Builder's list a few tasks deep; do the easy, self-contained parts fir
## 4. Keep work moving
- Each time you are woken, look at active work.
- A worker with active work that has said nothing for 20 minutes: ask it.
+- When a worker seems stuck, read its terminal; answer prompts within its task; ask the owner before approving anything risky.
- A Builder or Reviewer that has been down for 2 hours (its machine offline, its session gone, or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).
- Work with no progress for 6 hours goes back to you: reassign it or cut it smaller.
- Needs a person: get the decision now. Blocked: change something (context, model, size or plan); never resend the same thing.
diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.ts
index 3c8ccabe0..81610c0a0 100644
--- a/cli/src/services/processCoreApi.spec.ts
+++ b/cli/src/services/processCoreApi.spec.ts
@@ -234,6 +234,23 @@ describe('the core API a light service runs on in its own process', () => {
expect(ask).toHaveBeenCalledWith('super_tab_observers', {})
})
+ it('asks the core to read and type a member\'s terminal, and answers plainly when the core cannot be asked', async () => {
+ const ask = vi.fn(async (query: string, _payload: Record<string, unknown>): Promise<Record<string, unknown>> =>
+ query === 'super_tab_screen' ? { ok: true, text: 'Allow?', hold: 'permission_open' } : { ok: true })
+ const doors = processCoreApi('/data', 'superTabs', { ask }).superTabs!
+ expect(await doors.screen('h1', 20)).toEqual({ ok: true, text: 'Allow?', hold: 'permission_open' })
+ expect(ask).toHaveBeenLastCalledWith('super_tab_screen', { agentId: 'h1', scrollback: 20 })
+ expect(await doors.input('h1', 'yes', ['Enter'])).toEqual({ ok: true })
+ expect(ask).toHaveBeenLastCalledWith('super_tab_input', { agentId: 'h1', text: 'yes', keys: ['Enter'] })
+ ask.mockRejectedValue(new Error('gone'))
+ expect(await doors.screen('h1', 0)).toEqual({ ok: false, error: 'This machine\'s daemon could not be asked. Try again in a moment.' })
+ expect(await doors.input('h1', 'x', [])).toEqual({ ok: false, error: 'This machine\'s daemon could not be asked. Try again in a moment.' })
+ ask.mockResolvedValue({ error: 'NOT_SUPER_TABS' })
+ expect(await doors.input('h1', 'x', [])).toEqual({ ok: false, error: 'NOT_SUPER_TABS' })
+ ask.mockResolvedValue({})
+ expect(await doors.screen('h1', 0)).toEqual({ ok: false, error: 'The terminal could not be reached.' })
+ })
+
it('acts on the core for an experiment: agents made, turns stopped and delivered, windows told, each asked', async () => {
const answers: Record<string, Record<string, unknown> | Error> = {
create: { ok: true, agentId: 'made' }, stop_turn: {}, windows: {}, deliver: {}, cancel_delivery: { cancelled: true },
diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.ts
index ac3b1fceb..456a3cb38 100644
--- a/cli/src/services/processCoreApi.ts
+++ b/cli/src/services/processCoreApi.ts
@@ -14,7 +14,7 @@ import { usageTarget, usageTargetKey, usageSnapshot, validUsage, validUsageTarge
* each asked of the core over its link (`ask`). The agents it reads come as the apps are shown them (`service_query shown`): each with its
* name, whether its terminal is there and its harness's viewer.
*/
-import { CONNECTOR_VAULT_OFF, CONVERSATIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, LANE_OFF, OBSERVER_KEY_OFF, resolveAgent, TAB_KEY_OFF, TAB_RELAY_OFF, TERMINALS_OFF, WIFI_OFF, type CloudCore, type SuperTabsCore, type CoreApi, type DaemonAddress, type TerminalWatch } from '../core/api.js'
+import { CONNECTOR_VAULT_OFF, CONVERSATIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, LANE_OFF, OBSERVER_KEY_OFF, resolveAgent, TAB_KEY_OFF, TAB_RELAY_OFF, TERMINALS_OFF, WIFI_OFF, type CloudCore, type SuperTabsCore, type SuperTabScreen, type SuperTabTyped, type CoreApi, type DaemonAddress, type TerminalWatch } from '../core/api.js'
import type { AgentDshContext } from '../lib/agentFrame.js'
import type { RegisteredSession } from '../lib/registry.js'
import type { turnsLink } from './turnsLink.js'
@@ -92,6 +92,11 @@ export const UNASKED = {
lastTurn: CoreApi['transcripts']['lastTurn']
}
+/** The core's answer to a terminal read or write, or why there is none, in words the Lead reads. */
+const terminalAnswer = (asked: Promise<Record<string, unknown>>): Promise<SuperTabTyped | SuperTabScreen> => asked.then(
+ answer => answer.ok === true ? answer as SuperTabScreen : { ok: false, error: String(answer.error ?? 'The terminal could not be reached.') },
+ () => ({ ok: false, error: 'This machine\'s daemon could not be asked. Try again in a moment.' }))
+
export function processCoreApi(dataDir: string, service: string, view: AgentsView = {}): CoreApi {
const live = (): ShownAgent[] => view.live?.() ?? []
const ask = view.ask
@@ -244,6 +249,9 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie
cards: (items) => { void ask('super_tab_cards', { items }).catch(() => {}) },
cardRecap: (recap) => { void ask('super_tab_card_recap', { recap }).catch(() => {}) },
shareObservers: () => { void ask('super_tab_observers', {}).catch(() => {}) },
+ // A Lead's read of a member's terminal and its typing (core/superTabTerminal.ts), answered by the core.
+ screen: (agentId, scrollback) => terminalAnswer(ask('super_tab_screen', { agentId, scrollback })) as Promise<SuperTabScreen>,
+ input: (agentId, text, keys) => terminalAnswer(ask('super_tab_input', { agentId, text, keys })),
} satisfies SuperTabsCore,
} : {}),
}
diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.ts
index 722e1c8f0..978b9c7a4 100644
--- a/cli/src/superTabs/command.spec.ts
+++ b/cli/src/superTabs/command.spec.ts
@@ -130,3 +130,49 @@ it('uploads each --attach file to the daemon\'s local upload route as the agent,
expect(calls.map(c => c.step ?? c.action)).toEqual(['sent', 'sent'])
} finally { rmSync(dir, { recursive: true, force: true }) }
})
+it('parses screen AGENT [--scrollback N] and type AGENT [TEXT] [--key K]...', () => {
+ expect(parseSuperTabArgs([...prefix, 'screen', 'worker'], where).payload).toMatchObject({ action: 'screen', command: { type: 'agent.screen', agentId: 'worker' } })
+ expect(parseSuperTabArgs([...prefix, 'screen', 'worker', '--scrollback', '120'], where).payload).toMatchObject({ command: { type: 'agent.screen', agentId: 'worker', scrollback: 120 } })
+ expect(parseSuperTabArgs([...prefix, 'type', 'worker', '2', '--key', 'enter'], where).payload).toMatchObject({ action: 'type', command: { type: 'agent.input', agentId: 'worker', text: '2', keys: ['Enter'] } })
+ expect(parseSuperTabArgs([...prefix, 'type', 'worker', '--key', 'Esc', '--key', 'ctrl-c', '--key', '1'], where).payload.command).toEqual({ type: 'agent.input', agentId: 'worker', keys: ['Esc', 'Ctrl-C', '1'] })
+ for (const argv of [[...prefix, 'screen'], [...prefix, 'screen', '../x'], [...prefix, 'screen', 'worker', '--scrollback', '201'], [...prefix, 'screen', 'worker', '--scrollback', '-1'], [...prefix, 'screen', 'worker', '--scrollback', '0'],
+ [...prefix, 'type', 'worker'], [...prefix, 'type', 'worker', '--key', 'F1'], [...prefix, 'type', 'worker', 'a', 'b'], [...prefix, 'type', 'worker', '--key']]) {
+ expect(() => parseSuperTabArgs(argv, where)).toThrow('harness super-tab')
+ }
+})
+it('sends a terminal request, reads its result again while it is pending, and prints the screen as plain text', async () => {
+ const print = vi.fn(), close = vi.fn()
+ const results: Record<string, unknown>[] = [{ error: 'BACKEND_TIMEOUT', detail: 'slow' }, { ok: true, value: { requestId: 'r1', pending: true } }, { ok: true, value: { ok: true, text: 'Allow?\n1. Yes' } }]
+ const request = vi.fn(async (_type: string, payload: Record<string, any> = {}): Promise<Record<string, unknown>> => payload.action === 'command'
+ ? { ok: true, value: { result: { requestId: 'r1' } } } : results.shift()!)
+ const deps = { where: () => where, open: async () => ({ request, close, machineId: 'machine' }), print }
+ expect(await superTabCommand([...prefix, 'screen', 'worker'], deps)).toBe(0)
+ expect(request.mock.calls.map(([, payload]) => payload!.action)).toEqual(['command', 'terminalResult', 'terminalResult', 'terminalResult'])
+ expect(request.mock.calls[0]![1]).toMatchObject({ tabId: 'tab', agentId: 'agent', operationId: expect.stringMatching(/^terminal-/), command: { type: 'agent.screen', agentId: 'worker' } })
+ // Not `requestId`: the daemon's transport numbers each request under that name and would overwrite it.
+ expect(request.mock.calls[1]![1]).toEqual({ action: 'terminalResult', tabId: 'tab', agentId: 'agent', terminalRequestId: 'r1' })
+ expect(print).toHaveBeenLastCalledWith('Allow?\n1. Yes')
+ // Typing prints what became of it; a refusal from the host is a failure.
+ results.push({ ok: true, value: { ok: false, error: 'Unknown key: Home.' } })
+ expect(await superTabCommand([...prefix, 'type', 'worker', '--key', 'Enter'], deps)).toBe(1)
+ expect(JSON.parse(print.mock.calls.at(-1)![0])).toEqual({ ok: false, error: 'Unknown key: Home.' })
+ results.push({ ok: true, value: { ok: true } })
+ expect(await superTabCommand([...prefix, 'type', 'worker', 'y'], deps)).toBe(0)
+ expect(JSON.parse(print.mock.calls.at(-1)![0])).toEqual({ ok: true })
+})
+it('gives up after three pending reads, and passes on a refused request without reading', async () => {
+ const print = vi.fn(), close = vi.fn()
+ let refused = false
+ const request = vi.fn(async (_type: string, payload: Record<string, any> = {}): Promise<Record<string, unknown>> => payload.action === 'command'
+ ? refused ? { error: 'LEAD_REQUIRED', detail: 'Only the Lead of this agent\'s project may read its terminal.' } : { ok: true, value: { result: { requestId: 'r1' } } }
+ : { ok: true, value: { requestId: 'r1', pending: true } })
+ const deps = { where: () => where, open: async () => ({ request, close, machineId: 'machine' }), print }
+ expect(await superTabCommand([...prefix, 'screen', 'worker'], deps)).toBe(1)
+ expect(request).toHaveBeenCalledTimes(4)
+ expect(JSON.parse(print.mock.calls.at(-1)![0])).toEqual({ error: 'TERMINAL_PENDING', detail: 'The worker\'s machine has not answered yet. Try again in a moment.' })
+ refused = true
+ request.mockClear()
+ expect(await superTabCommand([...prefix, 'screen', 'worker'], deps)).toBe(1)
+ expect(request).toHaveBeenCalledOnce()
+ expect(JSON.parse(print.mock.calls.at(-1)![0])).toMatchObject({ error: 'LEAD_REQUIRED' })
+})
diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.ts
index 79722c6f6..0a8a0b3ce 100644
--- a/cli/src/superTabs/command.ts
+++ b/cli/src/superTabs/command.ts
@@ -6,8 +6,10 @@ import { callerOf, type Frame } from '../agentClient/model.js'
import { identifier } from './host.js'
import { resolve } from 'node:path'
import { uploadAttachments } from './attach.js'
+import { keyName } from './terminal.js'
+import { randomUUID } from 'node:crypto'
-const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status | messages GROUP | message GROUP MESSAGE_ID | post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... | command OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | help'
+const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status | messages GROUP | message GROUP MESSAGE_ID | post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... | command OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'
export function parseSuperTabArgs(argv: readonly string[], where: Where) {
const positional: string[] = []
let tabId = '', agentId = ''
@@ -50,6 +52,25 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where) {
Object.assign(payload, { targetMachineId: first, request: JSON.parse(second) })
} else if (action === 'route' && identifier(first) && second && positional.length === 3) {
Object.assign(payload, { conversationId: first, assessment: JSON.parse(second) })
+ } else if (action === 'screen' && identifier(first) && (positional.length === 2
+ || positional.length === 4 && second === '--scrollback' && /^[1-9]\d*$/.test(third ?? '') && Number(third) <= 200)) {
+ // The id names this one read; a read sent twice is only read twice.
+ Object.assign(payload, { operationId: `terminal-${randomUUID()}`,
+ command: { type: 'agent.screen', agentId: first, ...(positional.length === 4 ? { scrollback: Number(third) } : {}) } })
+ } else if (action === 'type' && identifier(first)) {
+ let text: string | undefined
+ const keys: string[] = []
+ for (let i = 2; i < positional.length; i++) {
+ if (positional[i] === '--key') {
+ const key = keyName(positional[++i] ?? '')
+ if (!key) throw new Error(USAGE)
+ keys.push(key)
+ } else if (text === undefined && !keys.length) text = positional[i]
+ else throw new Error(USAGE)
+ }
+ if (!text && !keys.length) throw new Error(USAGE)
+ 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(USAGE)
return { where: target, payload }
}
@@ -88,6 +109,13 @@ export async function superTabCommand(argv: readonly string[], deps: {
try { result = { ok: true, ...await inspectCapacity(target, object(request.payload.request)) } }
finally { target.close() }
}
+ } else if (request.payload.action === 'screen' || request.payload.action === 'type') {
+ const answer = await terminalRequest(request.payload, scoped)
+ const value = object(answer.value)
+ // The screen is printed as it is, for the Lead to read; anything else, and every failure, as JSON.
+ if (request.payload.action === 'screen' && value.ok === true && typeof value.text === 'string') print(value.text)
+ else print(JSON.stringify(answer.error ? answer : value))
+ return value.ok === true ? 0 : 1
} else if (request.payload.action === 'route') {
result = await routeTask({ tabId: String(request.payload.tabId), conversationId: String(request.payload.conversationId),
assessment: request.payload.assessment }, scoped, request.where, deps.open)
@@ -109,3 +137,21 @@ export async function superTabCommand(argv: readonly string[], deps: {
return 1
} finally { daemon?.close() }
}
+
+/** How often a terminal result is read: the backend holds each read about 20 s, and the worker's machine has 10 s to pick a
+ * request up and 30 s to answer it, after which the backend answers with the reason. */
+const TERMINAL_READS = 3
+async function terminalRequest(payload: Record<string, unknown>, scoped: (payload: Record<string, unknown>) => Promise<Record<string, unknown>>): Promise<Record<string, unknown>> {
+ const sent = await scoped({ action: 'command', operationId: payload.operationId, command: payload.command })
+ if (sent.error) return sent
+ const requestId = object(object(sent.value).result).requestId
+ if (!identifier(requestId)) return { error: 'TERMINAL_UNAVAILABLE', detail: 'This Swarm\'s server does not relay terminals yet.' }
+ for (let read = 0; read < TERMINAL_READS; read++) {
+ // Not `requestId`: the daemon's transport numbers each request under that name (agentClient/daemon.ts).
+ const answer = await scoped({ action: 'terminalResult', terminalRequestId: requestId })
+ // A read the backend held to its limit while the worker's machine was still answering is read again.
+ if (answer.error === 'BACKEND_TIMEOUT' || object(answer.value).pending === true) continue
+ return answer
+ }
+ return { error: 'TERMINAL_PENDING', detail: 'The worker\'s machine has not answered yet. Try again in a moment.' }
+}
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index a0370e5a5..b8e1c1bf9 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -556,7 +556,7 @@ describe('Super Tab waits for the Harness Pro', () => {
if (offline) throw new Error('Host offline')
return { status: 200, body: { success: true, data: path.includes('/hosts/') ? rows : [] } }
})
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }
const core = fakeCore({ dataDir: dir, superTabs, account: { backend: call },
agents: { creationStatus: vi.fn(async creationId => ({ creationId, state: 'created' as const, agentId: 'harness' })), byAgent: vi.fn(() => ({ agentId: 'harness' }) as never), terminalAvailable: vi.fn(() => true) } })
const open = () => { const host = new SuperTabHost(core, 'machine-1', { log: vi.fn() }); hosts.push(host); return host }
@@ -593,7 +593,7 @@ describe('Super Tab waits for the Harness Pro', () => {
agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1' } }]
const call: CoreApi['account']['backend'] = vi.fn(async (_method, path) => ({ status: 200, body: { success: true, data: path.includes('/hosts/') ? rows : [] } }))
let here = true, clock = 0
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }
const core = fakeCore({ dataDir: dir, superTabs, account: { backend: call },
agents: { byAgent: vi.fn(() => (here ? { agentId: 'harness' } : undefined) as never), terminalAvailable: vi.fn(() => true) } })
const host = new SuperTabHost(core, 'machine-1', { log: vi.fn(), now: () => clock }); hosts.push(host)
@@ -911,6 +911,21 @@ it('rechecks authoritative native absence before retrying a lost acknowledgement
expect(t.close).toHaveBeenLastCalledWith({ agentId: 'harness' })
})
+describe('a Lead\'s terminal requests', () => {
+ it('asks for its agents\' terminal requests with each roster read, and answers a screen read as the agent', async () => {
+ const t = setup()
+ Object.assign(t.core, { superTabs: { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), input: vi.fn(),
+ screen: vi.fn(async () => ({ ok: true as const, text: 'Allow? 1. Yes', hold: null })) } })
+ const roster = vi.mocked(t.call).getMockImplementation()!
+ vi.mocked(t.call).mockImplementation(async (method, path, body) => path === '/api/super-tabs/hosts/machine-1/terminal'
+ ? { status: 200, body: { success: true, data: [{ tabId: 'tab', agentId: 'agent', harnessId: 'harness', request: { id: 'r1', kind: 'screen' } }] } }
+ : roster(method, path, body))
+ await t.open().tick()
+ await vi.waitFor(() => expect(t.call).toHaveBeenCalledWith('POST', '/api/super-tabs/tab/commands',
+ { operationId: 'terminal-r1', asAgentId: 'agent', command: { type: 'agent.screenResult', requestId: 'r1', ok: true, text: 'Allow? 1. Yes' } }))
+ })
+})
+
describe('the members a host lets watch its agents', () => {
it('keeps them watching through a 3 s roster read, wakes Share once, and lets a removed member go at once', async () => {
const dir = mkdtempSync(join(tmpdir(), 'super-tab-host-')); roots.push(dir)
@@ -922,7 +937,7 @@ describe('the members a host lets watch its agents', () => {
if (path.includes('/hosts/') && answer === null) await new Promise<void>(resolve => { answer = resolve })
return { status: 200, body: { success: true, data: path.includes('/hosts/') ? rows : [] } }
})
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }
const core = fakeCore({ dataDir: dir, superTabs, account: { backend: call },
agents: { byAgent: vi.fn(() => ({ agentId: 'harness' }) as never), terminalAvailable: vi.fn(() => true) } })
const host = new SuperTabHost(core, 'machine-1', { log: vi.fn(), now: () => clock }); hosts.push(host)
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index 0c923083f..0e437a16b 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -17,6 +17,7 @@ import { attentionOf } from './attention.js'
import { prepareContribution } from './contribution.js'
import { hostname } from 'node:os'
import { replacementObservations } from './replacements.js'
+import { TerminalHost } from './terminal.js'
type Json = Record<string, unknown>
export class SuperTabHostError extends Error {
@@ -181,6 +182,8 @@ export class SuperTabHost {
private readonly skillModes = new Map<string, SwarmSkillMode>()
private skillsRunning: Promise<void> | null = null
private missing = new Map<string, number>()
+ /** A Lead's reads of and typing into this machine's agents' terminals, and the stuck and usage-limit alerts. */
+ private readonly terminal: TerminalHost
constructor(private readonly core: CoreApi, readonly machineId: string, options: SuperTabHostOptions = {}) {
if (!identifier(machineId)) throw new SuperTabHostError('MACHINE_UNAVAILABLE', 'This machine is not signed in.')
@@ -192,6 +195,7 @@ export class SuperTabHost {
this.now = options.now ?? Date.now
this.write = options.write ?? writeJournal
this.log = options.log ?? (message => console.warn(`[super-tabs] ${message}`))
+ this.terminal = new TerminalHost(core, machineId, { now: this.now, log: this.log })
this.journal = { version: 1, machineId, entries: {} }
if (existsSync(this.file)) {
const raw = readFileSync(this.file, 'utf8')
@@ -460,6 +464,8 @@ export class SuperTabHost {
this.wakeShare(data)
this.publishAttention(data)
this.joinSwarms(data)
+ // Off the poll: a screen read waits on the core, and never delays the input leases below.
+ if (this.core.superTabs) void this.terminal.tick(data)
// Recovery can wait on a native receipt. Run it beside leases, so another worker's input
// never expires while an old Change agent is being reconciled.
if (!this.replacementsRunning && this.now() >= this.nextReplacementsAt) {
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index 665855c67..002484f82 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -415,6 +415,17 @@ describe('routeTask', () => {
await routeTask(input, t, where as never, opener(id => daemon(id, { agents: id === 'm1' ? ['h1'] : [], usage: { providers: [] } })))
expect((recorded(t).command.decision.candidates as Array<{ title: string }>).some(c => c.title.startsWith('Multiply'))).toBe(true)
})
+ it('skips a member whose screen showed a usage limit until its reset time, and offers it again after', async () => {
+ const limited = (until: string | null) => { const t = tab(); t.state.agents = agents.map(a => a.id === 'a1' ? { ...a, limitedUntil: until } : a); return t }
+ const s = scoped({ tab: limited(new Date(Date.now() + 30 * 60_000).toISOString()) })
+ await routeTask(input, s, where as never, opener())
+ expect(recorded(s).command.decision.excluded).toEqual(expect.arrayContaining([{ title: 'Multiply · Claude sonnet medium · remote-1', reason: expect.stringContaining('usage limit') }]))
+ for (const until of [new Date(Date.now() - 60_000).toISOString(), null]) {
+ const t = scoped({ tab: limited(until) })
+ await routeTask(input, t, where as never, opener())
+ expect((recorded(t).command.decision.candidates as Array<{ title: string }>).some(c => c.title.startsWith('Multiply'))).toBe(true)
+ }
+ })
it('uses the real admission texts the member refusal filter keys on', () => {
const quota = quotaOf({ providers: [{ provider: 'claude', outcome: 'answered', httpStatus: 200, body: { five_hour: { utilization: 100 } } }] }, 'claude', false)
const requirements = { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: ['git'], devices: ['/dev/x'], quotaRequired: false }
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index 00d72ad50..26e1513f9 100644
--- a/cli/src/superTabs/routeCommand.ts
+++ b/cli/src/superTabs/routeCommand.ts
@@ -171,7 +171,14 @@ export async function routeTask(input: { tabId: string; conversationId: string;
const decisions = Array.isArray(past.decisions) ? list(past.decisions) : null
const attempts = Array.isArray(past.attempts) ? list(past.attempts) : null
const ended = endedWork(conversations, decisions, attempts, input.conversationId)
+ // The member's machine saw a usage-limit screen (superTabs/terminal.ts): it sits out until the reset, which the backend
+ // sets to an hour when the screen named none (spec/2026-10-23-lead-sees-agent-terminal.md).
+ const limited = (agentId: string | undefined) => {
+ const until = Date.parse(String(members.find(m => m.id === agentId)?.limitedUntil))
+ return until > Date.now() ? [`Its screen showed a usage limit until ${new Date(until).toISOString()}.`] : []
+ }
const probes = probed.flat().map(p => p.kind === 'member' ? { ...p, repo: repoMatch(folder, p.frame ?? null, p.machineId === where.machineId),
+ refusals: [...p.refusals, ...limited(p.agentId)],
earlier: ended.filter(e => e.agentId === p.agentId).reverse().slice(0, 3).map(e => ({ group: e.group, outcome: e.outcome })) } : p)
// Picks started or assigned and still at work hold part of their account's quota; the log, and so this, is per Swarm.
const working = (decisions ?? []).filter(d => d.final && d.outcome === null && typeof d.account === 'string')
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 5323337c4..d13db725b 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -502,7 +502,7 @@ it('documents finished worker decisions and explains an older backend without re
describe('the Swarm cards the devices ask for', () => {
function withCards() {
const cards = { want: vi.fn(), open: vi.fn(), recap: vi.fn(async (tabId: string, leadId: string) => ({ tabId, leadId, text: 'Shipped', at: 5, none: false })), onCards: undefined as unknown, onRecap: undefined as unknown }
- const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }
+ const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }
const core = fakeCore({ superTabs })
const make = vi.fn(() => cards as never)
const service = superTabService(core, { cards: make })
@@ -565,3 +565,15 @@ describe('the Swarm cards the devices ask for', () => {
expect(t.make).not.toHaveBeenCalled()
})
})
+
+describe('a Lead\'s terminal result', () => {
+ it('reads the result of its own terminal request as the calling agent, and nothing for a bad id', async () => {
+ const t = setup()
+ t.call.mockImplementation(async (_method, path) => ({ status: 200, body: { success: true, data: path.includes('/terminal/')
+ ? { ok: true, text: 'Allow? 1. Yes' } : { state: { agents: [t.agent] } } } }))
+ expect(await t.ask({ action: 'terminalResult', tabId: 'tab', agentId: t.agentId, terminalRequestId: 'r1', requestId: 'transport-1' }, owner))
+ .toEqual({ ok: true, value: { ok: true, text: 'Allow? 1. Yes' } })
+ expect(t.call.mock.calls.at(-1)!.slice(0, 2)).toEqual(['GET', `/api/super-tabs/tab/terminal/r1?asAgentId=${t.agentId}`])
+ expect(await t.ask({ action: 'terminalResult', tabId: 'tab', agentId: t.agentId, terminalRequestId: '../x' }, owner)).toEqual({ error: 'INVALID_REQUEST' })
+ })
+})
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 2ad72eef5..2ff81d140 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -20,6 +20,8 @@ const HELP = {
release: 'When a Builder finishes, decide reuse, keep or stop; prefer stop unless more work is coming soon. Reuse assigns new work; agent.release records keep or requests stop. Wait for the execution host to confirm a stop. A person can withdraw a stuck stop; the session cannot receive new work in that Swarm. Its native capacity stays reserved until its host confirms stopping. Other Swarms wait up to two minutes for an in-flight close, then may reuse it.',
resume: 'resume START_ID: finish a pending start without creating another agent.',
route: 'route GROUP JSON: before you start an agent or assign work to another agent, choose who does it. Work you do yourself is not routed. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","why":"one sentence","kind":"optional word such as ui or docs","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. size is how long the work runs: small about 20 minutes, medium about an hour, large about three hours. Candidates that break the owner\'s hard rules are left out; soft rules (a preferred engine for the kind, idle agents first) rank the rest. Start or assign the pick with its routeDecisionId; to choose otherwise, pass overrideReason. An agent\'s start or work.assign without a routeDecisionId is refused, so route first; a person can still start and assign by hand.',
+ screen: 'screen AGENT [--scrollback N]: read a worker\'s terminal as plain text, with up to 200 lines of scrollback. Only its project\'s Lead may. Use it when a worker seems stuck.',
+ type: 'type AGENT [TEXT] [--key K]...: type text, then keys (Enter, Esc, Tab, Up, Down, Left, Right, Ctrl-C, 0-9), into a worker\'s terminal. Answer prompts within its task; ask the owner before approving anything risky.',
capacity: 'capacity MACHINE_ID JSON: inspect machine, engine and quota headroom. JSON uses the start request fields below. Unknown allowances are not reported as free tokens.',
startRequest: { conversationId: 'GROUP', machineId: 'MACHINE', engine: 'codex', name: 'Builder', cwd: '/absolute/repo/on/that/machine', worktree: true, branchRef: 'refs/remotes/origin/BASE_BRANCH', requirements: START_REQUIREMENTS,
model: 'opus', effort: 'high', routeDecisionId: 'DECISION' },
@@ -206,6 +208,11 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
return { ok: true, value: await backend(core, 'GET', `${path}/starts/${payload.startId}?${identity}`) }
}
if (payload.action === 'status') return { ok: true, value: answer }
+ // A Lead's terminal read or typing (`screen`, `type`): the backend answers only the agent that asked.
+ if (payload.action === 'terminalResult') {
+ if (!identifier(payload.terminalRequestId)) return { error: 'INVALID_REQUEST' }
+ return { ok: true, value: await backend(core, 'GET', `${path}/terminal/${payload.terminalRequestId}?${identity}`) }
+ }
if (payload.action === 'routeContext') {
const [policy, machines] = await Promise.all([
backend(core, 'GET', `${path}/routing-policy?${identity}`),
diff --git a/cli/src/superTabs/terminal.spec.ts b/cli/src/superTabs/terminal.spec.ts
new file mode 100644
index 000000000..802df8bf0
--- /dev/null
+++ b/cli/src/superTabs/terminal.spec.ts
@@ -0,0 +1,219 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { CoreApi, SuperTabScreen } from '../core/api.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { capScreen, limitOf, TerminalHost, typedKeys } from './terminal.js'
+
+const row = (agentId = 'a1', harnessId = 'h1', over: Record<string, unknown> = {}) => ({ tabId: 'tab', agent: { id: agentId, harnessId, machineId: 'm1' }, ...over })
+type Sent = { path: string; body: Record<string, any> }
+
+function setup(options: { live?: string[]; screen?: (harnessId: string) => SuperTabScreen; requests?: unknown[] } = {}) {
+ let clock = 1_000_000
+ const sent: Sent[] = []
+ let pending = options.requests ?? []
+ const backend: CoreApi['account']['backend'] = vi.fn(async (method, path, body) => {
+ if (path === '/api/super-tabs/hosts/m1/terminal') { const rows = pending; pending = []; return { status: 200, body: { success: true, data: rows } } }
+ sent.push({ path, body: body as Record<string, any> })
+ return { status: 200, body: { success: true, data: { result: {} } } }
+ })
+ let screen = options.screen ?? (() => ({ ok: true as const, text: '> ', hold: null }))
+ const core = fakeCore({
+ account: { backend },
+ agents: { byAgent: vi.fn((id: string) => (options.live ?? ['h1']).includes(id) ? { agentId: id } as never : undefined) },
+ superTabs: { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(),
+ screen: vi.fn(async (harnessId: string) => screen(harnessId)), input: vi.fn(async () => ({ ok: true as const })) },
+ })
+ const host = new TerminalHost(core, 'm1', { now: () => clock, log: vi.fn() })
+ return { core, backend, sent, host,
+ wait: (ms: number) => { clock += ms },
+ request: (...rows: unknown[]) => { pending = rows },
+ showing: (next: (harnessId: string) => SuperTabScreen) => { screen = next },
+ polls: () => vi.mocked(backend).mock.calls.filter(([, path]) => path === '/api/super-tabs/hosts/m1/terminal').length,
+ alerts: () => sent.filter(s => s.body.command.type === 'agent.alert').map(s => s.body.command) }
+}
+const screenRequest = (over: Record<string, unknown> = {}) => ({ tabId: 'tab', agentId: 'a1', harnessId: 'h1', request: { id: 'r1', kind: 'screen' }, ...over })
+
+describe('a host serving its Lead\'s terminal requests', () => {
+ it('reads the screen of its own agent and answers as that agent', async () => {
+ const t = setup({ requests: [screenRequest({ request: { id: 'r1', kind: 'screen', scrollback: 50 } })],
+ screen: () => ({ ok: true, text: 'Allow edit? 1. Yes 2. No', hold: 'permission_open' }) })
+ await t.host.tick([row()])
+ expect(t.core.superTabs!.screen).toHaveBeenCalledWith('h1', 50)
+ expect(t.sent).toEqual([{ path: '/api/super-tabs/tab/commands', body: { operationId: 'terminal-r1', asAgentId: 'a1',
+ command: { type: 'agent.screenResult', requestId: 'r1', ok: true, text: 'Allow edit? 1. Yes 2. No' } } }])
+ })
+
+ it('refuses a request whose harness is not the one running here, and never reads or types for it', async () => {
+ const t = setup({ requests: [screenRequest({ harnessId: 'h-old' }),
+ { tabId: 'tab', agentId: 'a1', harnessId: 'h-old', request: { id: 'r2', kind: 'input', text: 'y' } }] })
+ await t.host.tick([row()])
+ // The one read is the alert watch's own.
+ expect(t.core.superTabs!.screen).toHaveBeenCalledOnce()
+ expect(t.core.superTabs!.input).not.toHaveBeenCalled()
+ expect(t.sent.map(s => s.body.command).sort((x, y) => x.requestId.localeCompare(y.requestId))).toEqual([
+ { type: 'agent.screenResult', requestId: 'r1', ok: false, error: 'This agent\'s terminal on this machine changed. Ask again.' },
+ { type: 'agent.inputResult', requestId: 'r2', ok: false, error: 'This agent\'s terminal on this machine changed. Ask again.' }])
+ })
+
+ it('never answers as another machine\'s agent, and tells at once that a stopping one or one not running here is not running', async () => {
+ const t = setup({ live: ['h1', 'h3'], requests: [screenRequest({ agentId: 'a9', harnessId: 'h9' }), screenRequest({ agentId: 'a2', harnessId: 'h2' }),
+ screenRequest({ agentId: 'a3', harnessId: 'h3', request: { id: 'r3', kind: 'screen' } }), screenRequest({ agentId: 'a4', harnessId: 'h4', request: { id: 'r4', kind: 'input', keys: ['Enter'] } })] })
+ await t.host.tick([row(), { tabId: 'tab', agent: { id: 'a2', harnessId: 'h2', machineId: 'm2' } }, row('a3', 'h3', { stopRequested: true }), row('a4', 'h4')])
+ expect(vi.mocked(t.core.superTabs!.screen).mock.calls).toEqual([['h1', 0]])
+ expect(t.core.superTabs!.input).not.toHaveBeenCalled()
+ expect(t.sent.map(s => [s.body.asAgentId, s.body.command]).sort()).toEqual([
+ ['a3', { type: 'agent.screenResult', requestId: 'r3', ok: false, error: 'This agent is not running on this machine.' }],
+ ['a4', { type: 'agent.inputResult', requestId: 'r4', ok: false, error: 'This agent is not running on this machine.' }]])
+ })
+
+ it('asks for requests while only a stopping agent is here, so its requests are answered', async () => {
+ const t = setup({ requests: [screenRequest({ agentId: 'a3', harnessId: 'h3' })] })
+ await t.host.tick([row('a3', 'h3', { stopRequested: true })])
+ expect(t.sent.map(s => s.body.command.error)).toEqual(['This agent is not running on this machine.'])
+ })
+
+ it('refuses typed text with a newline or another control character: those are keys, sent by name', async () => {
+ const t = setup({ requests: ['a\nrm -rf x', 'a\u001b[A', 'ok\u007f'].map((text, i) => ({ tabId: 'tab', agentId: 'a1', harnessId: 'h1', request: { id: `r${i}`, kind: 'input', text } })) })
+ await t.host.tick([row()])
+ expect(t.core.superTabs!.input).not.toHaveBeenCalled()
+ expect(t.sent.map(s => s.body.command.error)).toEqual(Array(3).fill('Send Enter and other keys as named keys, not in the text.'))
+ })
+
+ it('caps the screen at 64 KB, keeping its end and never splitting a character', async () => {
+ expect(capScreen('short')).toBe('short')
+ const long = `${'x'.repeat(70_000)}é${'y'.repeat(65_535)}`
+ const capped = capScreen(long)
+ expect(Buffer.byteLength(capped)).toBeLessThanOrEqual(65_536)
+ expect(capped).toBe('y'.repeat(65_535))
+ const t = setup({ requests: [screenRequest()], screen: () => ({ ok: true, text: 'z'.repeat(100_000), hold: null }) })
+ await t.host.tick([row()])
+ expect(Buffer.byteLength(t.sent[0].body.command.text)).toBe(65_536)
+ })
+
+ it('types the text and the named keys, mapped to the terminal\'s own key names', async () => {
+ expect(typedKeys(['Enter', 'Esc', 'Tab', 'Up', 'Down', 'Left', 'Right', 'Ctrl-C', '0', '9'])).toEqual(['Enter', 'Escape', 'Tab', 'Up', 'Down', 'Left', 'Right', 'C-c', '0', '9'])
+ expect(typedKeys(['esc', 'ctrl-c', 'ENTER'])).toEqual(['Escape', 'C-c', 'Enter'])
+ expect(typedKeys(['Enter', 'C-d'])).toBe('Unknown key: C-d.')
+ expect(typedKeys(['F1'])).toBe('Unknown key: F1.')
+ const t = setup({ requests: [{ tabId: 'tab', agentId: 'a1', harnessId: 'h1', request: { id: 'r1', kind: 'input', text: '2', keys: ['Enter'] } },
+ { tabId: 'tab', agentId: 'a1', harnessId: 'h1', request: { id: 'r2', kind: 'input', keys: ['Home'] } }] })
+ await t.host.tick([row()])
+ expect(t.core.superTabs!.input).toHaveBeenCalledOnce()
+ expect(t.core.superTabs!.input).toHaveBeenCalledWith('h1', '2', ['Enter'])
+ expect(t.sent.map(s => s.body.command).sort((x, y) => x.requestId.localeCompare(y.requestId))).toEqual([{ type: 'agent.inputResult', requestId: 'r1', ok: true },
+ { type: 'agent.inputResult', requestId: 'r2', ok: false, error: 'Unknown key: Home.' }])
+ })
+
+ it('passes on why the core could not read the screen', async () => {
+ const t = setup({ requests: [screenRequest()], screen: () => ({ ok: false, error: 'Could not read the terminal: pane gone' }) })
+ await t.host.tick([row()])
+ expect(t.sent[0].body.command).toEqual({ type: 'agent.screenResult', requestId: 'r1', ok: false, error: 'Could not read the terminal: pane gone' })
+ // The backend takes a reason of at most 500 characters.
+ t.showing(() => ({ ok: false, error: `Could not read the terminal: ${'x'.repeat(600)}` }))
+ t.request(screenRequest({ request: { id: 'r2', kind: 'screen' } }))
+ t.wait(3_000); await t.host.tick([row()])
+ expect(t.sent[1].body.command.error).toHaveLength(500)
+ })
+
+ it('asks for requests every 3 seconds, and not at all without a Swarm agent here', async () => {
+ const t = setup()
+ await t.host.tick([])
+ await t.host.tick([{ tabId: 'tab', agent: { id: 'a2', harnessId: 'h2', machineId: 'm2' } }])
+ expect(t.polls()).toBe(0)
+ await t.host.tick([row()])
+ expect(t.polls()).toBe(1)
+ t.wait(2_000)
+ await t.host.tick([row()])
+ expect(t.polls()).toBe(1)
+ t.wait(1_000)
+ await t.host.tick([row()])
+ expect(t.polls()).toBe(2)
+ })
+})
+
+describe('the stuck and usage-limit alerts', () => {
+ const prompt = (): SuperTabScreen => ({ ok: true, text: 'Do you want to proceed?\n❯ 1. Yes\n 2. No', hold: 'permission_open' })
+ const idle = (): SuperTabScreen => ({ ok: true, text: '> ', hold: null })
+
+ it('alerts once when a prompt has waited 3 minutes, and ends the episode when it is answered', async () => {
+ const t = setup({ screen: prompt })
+ await t.host.tick([row()])
+ t.wait(150_000); await t.host.tick([row()])
+ expect(t.alerts()).toEqual([])
+ t.wait(30_000); await t.host.tick([row()])
+ expect(t.alerts()).toEqual([{ type: 'agent.alert', agentId: 'a1', alert: 'prompt', active: true }])
+ for (let i = 0; i < 5; i++) { t.wait(15_000); await t.host.tick([row()]) }
+ expect(t.alerts()).toHaveLength(1)
+ t.showing(idle); t.wait(15_000); await t.host.tick([row()])
+ expect(t.alerts()).toEqual([{ type: 'agent.alert', agentId: 'a1', alert: 'prompt', active: true }, { type: 'agent.alert', agentId: 'a1', alert: 'prompt', active: false }])
+ // A new prompt is a new episode, with its own 3 minutes.
+ t.showing(prompt); t.wait(15_000); await t.host.tick([row()])
+ t.wait(150_000); await t.host.tick([row()])
+ expect(t.alerts()).toHaveLength(2)
+ t.wait(30_000); await t.host.tick([row()])
+ expect(t.alerts()).toHaveLength(3)
+ expect(new Set(t.sent.map(s => s.body.operationId)).size).toBe(3)
+ })
+
+ it('never alerts for a prompt answered within 3 minutes, nor ends an episode it never began', async () => {
+ const t = setup({ screen: prompt })
+ await t.host.tick([row()])
+ t.showing(idle); t.wait(120_000); await t.host.tick([row()])
+ t.showing(prompt); t.wait(120_000); await t.host.tick([row()])
+ expect(t.alerts()).toEqual([])
+ })
+
+ it('reads the screen only every 15 seconds', async () => {
+ const t = setup({ screen: idle })
+ await t.host.tick([row()])
+ t.wait(5_000); await t.host.tick([row()])
+ expect(t.core.superTabs!.screen).toHaveBeenCalledOnce()
+ t.wait(10_000); await t.host.tick([row()])
+ expect(t.core.superTabs!.screen).toHaveBeenCalledTimes(2)
+ })
+
+ it('alerts once for a usage-limit screen with its reset time, and ends it when the screen moves on', async () => {
+ const t = setup({ screen: () => ({ ok: true, text: 'Working on it\n\n■ You\'ve hit your usage limit. Upgrade to Pro or try again in 1 hour 30 minutes.\n> ', hold: null }) })
+ await t.host.tick([row()])
+ t.wait(15_000); await t.host.tick([row()])
+ expect(t.alerts()).toEqual([{ type: 'agent.alert', agentId: 'a1', alert: 'limit', active: true, resetAt: new Date(1_000_000 + 90 * 60_000).toISOString() }])
+ t.showing(idle); t.wait(15_000); await t.host.tick([row()])
+ expect(t.alerts()[1]).toEqual({ type: 'agent.alert', agentId: 'a1', alert: 'limit', active: false })
+ })
+
+ it('tries an alert the backend did not take again on the next read', async () => {
+ const t = setup({ screen: () => ({ ok: true, text: 'Claude usage limit reached. Your limit will reset at 3pm.', hold: null }) })
+ const real = vi.mocked(t.backend).getMockImplementation()!
+ let failed = false
+ vi.mocked(t.backend).mockImplementation(async (method, path, body) => {
+ if (!failed && path.endsWith('/commands')) { failed = true; return { status: 503, body: { success: false } } }
+ return real(method, path, body)
+ })
+ await t.host.tick([row()])
+ t.wait(15_000); await t.host.tick([row()])
+ expect(t.alerts()).toHaveLength(1)
+ })
+})
+
+describe('reading a usage limit off a screen', () => {
+ const now = new Date(2026, 9, 23, 14, 10).getTime()
+ it.each([
+ ['5-hour limit reached ∙ resets 3pm', new Date(2026, 9, 23, 15, 0)],
+ ['Claude usage limit reached. Your limit will reset at 3pm (Asia/Saigon).', new Date(2026, 9, 23, 15, 0)],
+ ['You\'ve hit your limit · resets 1:30pm (Asia/Saigon)', new Date(2026, 9, 24, 13, 30)],
+ ['Weekly limit reached ∙ resets Oct 25, 9am', new Date(2026, 9, 25, 9, 0)],
+ ['5-hour limit reached ∙ resets 15:00', new Date(2026, 9, 23, 15, 0)],
+ ['5-hour limit reached ∙ resets 0:30', new Date(2026, 9, 24, 0, 30)],
+ ['5-hour limit reached ∙ resets 12pm', new Date(2026, 9, 24, 12, 0)],
+ ['5-hour limit reached ∙ resets 12am', new Date(2026, 9, 24, 0, 0)],
+ ['■ You\'ve hit your usage limit. Try again at 4:05 PM.', new Date(2026, 9, 23, 16, 5)],
+ ['■ You\'ve hit your usage limit. Upgrade to Pro, or try again in 2 days 3 hours 1 minute.', new Date(now + ((2 * 24 + 3) * 60 + 1) * 60_000)],
+ ])('reads %s', (line, reset) => {
+ expect(limitOf(`some work\n${line}\n> `, now)).toEqual({ resetAt: reset.toISOString() })
+ })
+ it('knows a limit without a reset time, and ignores the words in an agent\'s own prose or far above the prompt', () => {
+ expect(limitOf('⎿ API Error: Usage limit reached\n> ', now)).toEqual({})
+ expect(limitOf('I will add a check for when the usage limit reached message shows.\n> ', now)).toBeNull()
+ expect(limitOf(`5-hour limit reached ∙ resets 3pm\n${'line\n'.repeat(30)}> `, now)).toBeNull()
+ expect(limitOf('> ', now)).toBeNull()
+ })
+})
diff --git a/cli/src/superTabs/terminal.ts b/cli/src/superTabs/terminal.ts
new file mode 100644
index 000000000..07a9e5d5d
--- /dev/null
+++ b/cli/src/superTabs/terminal.ts
@@ -0,0 +1,215 @@
+/**
+ * The host's side of a Lead reading and typing into a worker's terminal (spec/2026-10-23-lead-sees-agent-terminal.md).
+ * Workers got stuck on what only their terminal showed (a permission prompt, a usage-limit screen, a model picker) and
+ * only a person at that machine could see and clear it. The backend relays the Lead's request to the host of the agent's
+ * machine; the host reads or types with the core's own capture and input (core/superTabTerminal.ts) and answers as that
+ * agent. It also tells the Lead, once per episode, when a worker has sat on a prompt for 3 minutes or its screen shows
+ * a usage limit.
+ */
+import type { CoreApi } from '../core/api.js'
+import type { MessageHold } from '../engines/facets/screen.js'
+import { backend } from './host.js'
+import { identifier, object } from './wire.js'
+
+type Json = Record<string, unknown>
+interface Own { tabId: string; agentId: string; harnessId: string }
+
+/** Every host of every Swarm asks, so not every second (Lead, 2026-10-23); the backend gives up on a pickup after 10 s. */
+const SERVE_EVERY_MS = 3_000
+/** A screen read per agent; the 3-minute prompt wait does not need it finer. */
+const WATCH_EVERY_MS = 15_000
+const PROMPT_WAIT_MS = 3 * 60_000
+/** The spec's cap on what a screen read returns. */
+const MAX_SCREEN_BYTES = 64 * 1024
+/** What the screen reader says a prompt or a question is waiting on; a popup or a hidden prompt is not one. */
+const WAITING: ReadonlySet<MessageHold> = new Set(['permission_open', 'question_open', 'menu_open', 'trust_open', 'update_prompt_open', 'model_prompt_open', 'sign_in_open'])
+/** The spec's named keys, in any case: the name the Lead's request carries, and the terminal's own (core/superTabTerminal.ts).
+ * Ctrl-D and the like are left out: one closes an engine. */
+const KEYS: Record<string, [string, string]> = { enter: ['Enter', 'Enter'], esc: ['Esc', 'Escape'], escape: ['Esc', 'Escape'], tab: ['Tab', 'Tab'],
+ up: ['Up', 'Up'], down: ['Down', 'Down'], left: ['Left', 'Left'], right: ['Right', 'Right'], 'ctrl-c': ['Ctrl-C', 'C-c'],
+ ...Object.fromEntries([...'0123456789'].map(digit => [digit, [digit, digit]])) }
+/** A key as the Lead's request names it, or null for one it may not type. */
+export const keyName = (key: string): string | null => KEYS[key.toLowerCase()]?.[0] ?? null
+const CHANGED = 'This agent\'s terminal on this machine changed. Ask again.'
+const NOT_RUNNING = 'This agent is not running on this machine.'
+
+/** The end of the screen, at most 64 KB of UTF-8, cut on a character boundary: the prompt is at the bottom. */
+export function capScreen(text: string): string {
+ const bytes = Buffer.from(text)
+ if (bytes.length <= MAX_SCREEN_BYTES) return text
+ let start = bytes.length - MAX_SCREEN_BYTES
+ while ((bytes[start]! & 0xc0) === 0x80) start++
+ return bytes.subarray(start).toString()
+}
+
+/** The terminal's key names for the Lead's, or why one is not allowed. */
+export function typedKeys(keys: unknown[]): string[] | string {
+ const out: string[] = []
+ for (const key of keys) {
+ const name = typeof key === 'string' ? KEYS[key.toLowerCase()]?.[1] : undefined
+ if (!name) return `Unknown key: ${String(key)}.`
+ out.push(name)
+ }
+ return out
+}
+
+/** The engines' own limit lines, at the start of a line: Claude Code's "5-hour limit reached ∙ resets 3pm", "Claude usage
+ * limit reached. Your limit will reset at 3pm", "You've hit your limit · resets 3pm" and "API Error: Usage limit
+ * reached", and Codex's "You've hit your usage limit. … try again in 2 hours". Only near the prompt, so an agent writing
+ * about limits in its own words, or an old banner far up the screen, is not one. */
+const LIMIT_LINE = /^[^A-Za-z]*(?:api error:\s*)?(?:claude\s+)?(?:(?:usage|5-hour|weekly|session|opus|sonnet)\s+limit reached|you['’]ve hit your (?:usage )?limit|you['’]ve reached your usage limit)/i
+const LIMIT_NEAR_LINES = 15
+const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
+
+/** A usage limit on screen, with when it resets if the screen says; null for none. */
+export function limitOf(text: string, now: number): { resetAt?: string } | null {
+ const lines = text.split('\n')
+ const tail = lines.slice(-LIMIT_NEAR_LINES)
+ const at = tail.findIndex(line => LIMIT_LINE.test(line))
+ if (at < 0) return null
+ const said = tail.slice(at, at + 3).join(' ')
+ const reset = resetOf(said, now)
+ return reset === null ? {} : { resetAt: new Date(reset).toISOString() }
+}
+
+function resetOf(said: string, now: number): number | null {
+ const span = /try again in\s+([^.]*)/i.exec(said)
+ if (span) {
+ let ms = 0
+ for (const [, n, unit] of span[1]!.matchAll(/(\d+)\s*(day|hour|minute|min|h|m)/gi)) {
+ ms += Number(n) * ({ day: 86_400_000, hour: 3_600_000, h: 3_600_000 } as Record<string, number>)[unit!.toLowerCase()]! || Number(n) * 60_000
+ }
+ if (ms) return now + ms
+ }
+ // The engines say a local time ("3pm", "4:05 PM"), with a date when it is not today ("Oct 25, 9am").
+ const time = /(?:resets?(?: at)?|try again at)\s+(?:([a-z]{3})[a-z]*\s+(\d{1,2}),?\s+(?:at\s+)?)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)?/i.exec(said)
+ if (!time) return null
+ const [, month, day, hour, minute, half] = time
+ // "3pm" and "12am" are 12-hour; "15:00" and "0:30", with no am or pm, are 24-hour.
+ const h = half ? Number(hour) % 12 + (half.toLowerCase() === 'pm' ? 12 : 0) : Number(hour)
+ const date = new Date(now)
+ if (month && MONTHS.includes(month.toLowerCase())) date.setMonth(MONTHS.indexOf(month.toLowerCase()), Number(day))
+ date.setHours(h, Number(minute ?? 0), 0, 0)
+ // A time already past today is tomorrow's; a date already past is next year's.
+ if (date.getTime() <= now) month ? date.setFullYear(date.getFullYear() + 1) : date.setDate(date.getDate() + 1)
+ return date.getTime()
+}
+
+interface Watched { prompt: { since: number; alerted: boolean } | null; limit: { since: number; alerted: boolean } | null }
+
+export class TerminalHost {
+ private nextServeAt = 0
+ private nextWatchAt = 0
+ private serving: Promise<void> | null = null
+ private watching: Promise<void> | null = null
+ private readonly watched = new Map<string, Watched>()
+ private readonly now: () => number
+ private readonly log: (message: string) => void
+
+ constructor(private readonly core: CoreApi, private readonly machineId: string, options: { now?: () => number; log?: (message: string) => void } = {}) {
+ this.now = options.now ?? Date.now
+ this.log = options.log ?? (message => console.warn(`[super-tabs] ${message}`))
+ }
+
+ /** Each host roster read. Serving and watching run on their own cadence, and the returned promise is only for specs:
+ * the host never waits on it, so a slow screen read never delays deliveries. */
+ tick(rows: unknown[]): Promise<void> {
+ const here = this.here(rows)
+ if (!here.length) { this.watched.clear(); return Promise.resolve() }
+ const own = here.filter(agent => agent.running)
+ const now = this.now()
+ if (!this.serving && now >= this.nextServeAt) {
+ this.nextServeAt = now + SERVE_EVERY_MS
+ this.serving = this.serve(here).catch(error => this.log(error instanceof Error ? error.message : String(error))).finally(() => { this.serving = null })
+ }
+ if (!this.watching && now >= this.nextWatchAt) {
+ this.nextWatchAt = now + WATCH_EVERY_MS
+ this.watching = this.watch(own).catch(error => this.log(error instanceof Error ? error.message : String(error))).finally(() => { this.watching = null })
+ }
+ return Promise.all([this.serving, this.watching]).then(() => {})
+ }
+
+ /** This machine's Swarm agents, as the roster names them, and whether each runs here: a stopping one, or one whose
+ * session is gone, is no longer anyone's to drive, but its requests are still this host's to answer. */
+ private here(rows: unknown[]): Array<Own & { running: boolean }> {
+ return rows.map(object).flatMap(row => {
+ const agent = object(row.agent)
+ return identifier(row.tabId) && identifier(agent.id) && identifier(agent.harnessId) && agent.machineId === this.machineId
+ ? [{ tabId: row.tabId, agentId: agent.id, harnessId: agent.harnessId, running: row.stopRequested !== true && !!this.core.agents.byAgent(agent.harnessId) }] : []
+ })
+ }
+
+ private async serve(here: Array<Own & { running: boolean }>): Promise<void> {
+ const rows = await backend(this.core, 'POST', `/api/super-tabs/hosts/${this.machineId}/terminal`)
+ if (!Array.isArray(rows)) throw new Error('Invalid Super Tab terminal requests.')
+ await Promise.all(rows.map(object).map(async row => {
+ const request = object(row.request)
+ const kind = request.kind
+ if (!identifier(request.id) || (kind !== 'screen' && kind !== 'input')) return
+ const agent = here.find(a => a.tabId === row.tabId && a.agentId === row.agentId)
+ // Not an agent of this machine: the host may not answer as it.
+ if (!agent) return this.log(`terminal request ${request.id} names no agent of this machine`)
+ // Answered at once, so the Lead is not left waiting out the backend's 30 s (review of #1646).
+ const answer = !agent.running ? { ok: false, error: NOT_RUNNING }
+ // After a restart the agent may run in another terminal: never read or type into one the Lead did not ask about.
+ : row.harnessId !== agent.harnessId ? { ok: false, error: CHANGED }
+ : kind === 'screen' ? this.screen(agent, request) : this.input(agent, request)
+ await this.command(agent, `terminal-${request.id}`, { type: kind === 'screen' ? 'agent.screenResult' : 'agent.inputResult', requestId: request.id, ...await answer })
+ }))
+ }
+
+ private async screen(agent: Own, request: Json): Promise<Json> {
+ const scrollback = typeof request.scrollback === 'number' ? request.scrollback : 0
+ const read = await this.core.superTabs!.screen(agent.harnessId, scrollback)
+ // The backend keeps a reason to 500 characters.
+ return read.ok ? { ok: true, text: capScreen(read.text) } : { ok: false, error: read.error.slice(0, 500) }
+ }
+
+ private async input(agent: Own, request: Json): Promise<Json> {
+ const keys = typedKeys(Array.isArray(request.keys) ? request.keys : [])
+ if (typeof keys === 'string') return { ok: false, error: keys }
+ const text = typeof request.text === 'string' ? request.text : ''
+ // The text is typed literally, so a newline or an escape in it would act as a key the Lead never named (the backend
+ // refuses them too).
+ if (/[\x00-\x1f\x7f]/.test(text)) return { ok: false, error: 'Send Enter and other keys as named keys, not in the text.' }
+ return { ...await this.core.superTabs!.input(agent.harnessId, text, keys) }
+ }
+
+ private async command(agent: Own, operationId: string, command: Json): Promise<void> {
+ await backend(this.core, 'POST', `/api/super-tabs/${agent.tabId}/commands`, { operationId, asAgentId: agent.agentId, command })
+ }
+
+ /** One alert per episode: a prompt waiting 3 minutes, or a usage limit on screen; each ended once it is gone. An alert
+ * the backend did not take is tried again on the next read. */
+ private async watch(own: Own[]): Promise<void> {
+ const keys = new Set(own.map(a => `${a.tabId}:${a.agentId}`))
+ for (const key of this.watched.keys()) if (!keys.has(key)) this.watched.delete(key)
+ for (const agent of own) {
+ const key = `${agent.tabId}:${agent.agentId}`
+ const state = this.watched.get(key) ?? { prompt: null, limit: null }
+ this.watched.set(key, state)
+ // A screen that could not be read says nothing either way.
+ const read = await this.core.superTabs!.screen(agent.harnessId, 0).catch(() => null)
+ if (!read?.ok) continue
+ const now = this.now()
+ state.prompt = await this.episode(agent, 'prompt', state.prompt, read.hold !== null && WAITING.has(read.hold), now, since => now - since >= PROMPT_WAIT_MS, {})
+ const limit = limitOf(read.text, now)
+ state.limit = await this.episode(agent, 'limit', state.limit, limit !== null, now, () => true, limit ?? {})
+ }
+ }
+
+ private async episode(agent: Own, alert: 'prompt' | 'limit', current: Watched['prompt'], seen: boolean, now: number,
+ due: (since: number) => boolean, extra: Json): Promise<Watched['prompt']> {
+ const episode = seen ? current ?? { since: now, alerted: false } : current
+ if (!episode) return null
+ if (seen === episode.alerted || (seen && !due(episode.since))) return seen ? episode : null
+ try {
+ await this.command(agent, `terminal-alert-${agent.agentId}-${alert}-${episode.since}-${seen ? 'on' : 'off'}`,
+ { type: 'agent.alert', agentId: agent.agentId, alert, active: seen, ...(seen ? extra : {}) })
+ } catch (error) {
+ this.log(error instanceof Error ? error.message : String(error))
+ return episode
+ }
+ return seen ? { ...episode, alerted: true } : null
+ }
+}
diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.ts
index b354c10d7..0db2f11bf 100644
--- a/cli/src/testing/fakeCore.ts
+++ b/cli/src/testing/fakeCore.ts
@@ -94,6 +94,6 @@ export function fakeCore(over: Overrides = {}): CoreApi {
// Only a spec that gives the cloud agents doors has them, as only a core that offers them does.
...(over.cloud ? { cloud: Object.assign({ publish: vi.fn(), ask: vi.fn(), unask: vi.fn() }, over.cloud) } : {}),
// The Super Tab service's door, likewise.
- ...(over.superTabs ? { superTabs: Object.assign({ attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn() }, over.superTabs) } : {}),
+ ...(over.superTabs ? { superTabs: Object.assign({ attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn() }, over.superTabs) } : {}),
}
}