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.

Backend: the Lead reads and types in an agent's terminal (#1643)

0xken15ad6c2ffbf30f
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 44ab418b3..6b2430e8d 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -15,7 +15,8 @@ import { errorHandler } from '../src/middlewares/errorHandler.js'
import type { Command } from '../src/superTabs/commands.js'
import { nextMachineShareGrants } from '../src/lib/machineSharePolicy.js'
import { DEFAULT_ROUTING_POLICY } from '../src/superTabs/routingPolicy.js'
-import { stableId } from '../src/superTabs/model.js'
+import { stableId, type SuperTabState } from '../src/superTabs/model.js'
+import { ensureTerminalExpiry, TERMINAL_EXPIRY_MS } from '../src/superTabs/terminal.js'
// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.
let replica: MongoMemoryReplSet
@@ -2091,3 +2092,114 @@ describe('Lead safety on the host roster', () => {
expect(await rows()).toEqual([])
})
})
+
+describe('the Lead reads and types in an agent terminal', () => {
+ async function terminalFixture() {
+ const { tab, lead } = await fixture()
+ const group = (await run(tab, { type: 'conversation.create', title: 'Terminal', brief: 'Answer the prompt', checks: [] })).result.conversationId as string
+ const harnessId = randomUUID()
+ const worker = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId,
+ name: 'Terminal Engineer', configuration: config, lead: false })).result.agentId as string
+ const claim = async (at = store) => (await at.hostTerminal(host, 'test-host')).filter(row => row.tabId === tab)
+ return { tab, lead, worker, group, harnessId, claim }
+ }
+ const later = (ms: number) => new SuperTabStore(db, () => Date.now() + ms)
+
+ it('relays a screen read to the owning host once and returns it only to the requester, outside history', async () => {
+ const { tab, lead, worker, group, harnessId, claim } = await terminalFixture()
+ const requestId = (await run(tab, { type: 'agent.screen', agentId: worker, scrollback: 20 }, host, lead)).result.requestId as string
+ await expect(store.hostTerminal(peer, 'test-host')).rejects.toThrow('unavailable')
+ expect(await claim()).toEqual([{ tabId: tab, agentId: worker, harnessId, request: { id: requestId, kind: 'screen', scrollback: 20 } }])
+ expect(await claim()).toEqual([])
+ expect(await store.terminalResult(host, tab, requestId, lead)).toEqual({ requestId, pending: true })
+ await expect(run(tab, { type: 'agent.screenResult', requestId, ok: true, text: 'x' }, host, lead)).rejects.toThrow('host')
+ await run(tab, { type: 'agent.screenResult', requestId, ok: true, text: 'TOKEN=fixture-secret' }, host, worker)
+ await expect(store.terminalResult(owner, tab, requestId)).rejects.toThrow('unavailable')
+ expect(await store.terminalResult(host, tab, requestId, lead)).toEqual({ requestId, ok: true, text: 'TOKEN=fixture-secret' })
+ await expect(store.terminalResult(host, tab, requestId, lead)).rejects.toThrow('unavailable')
+ const history = [...(await store.messages(owner, tab, 'lead', {})).messages, ...(await store.messages(owner, tab, group, {})).messages]
+ const receipts = await db.superTabOperation.findMany({ where: { tabId: tab } })
+ expect(JSON.stringify([history, receipts, await store.read(owner, tab)])).not.toContain('fixture-secret')
+ })
+
+ it('logs typed input in the agent group and hands the host the text and keys', async () => {
+ const { tab, worker, group, harnessId, claim } = await terminalFixture()
+ const requestId = (await run(tab, { type: 'agent.input', agentId: worker, text: '/model', keys: ['Enter'] })).result.requestId as string
+ expect(await claim()).toEqual([{ tabId: tab, agentId: worker, harnessId, request: { id: requestId, kind: 'input', text: '/model', keys: ['Enter'] } }])
+ const rows = (await store.messages(owner, tab, group, {})).messages.filter(m => (m.source as { kind?: string } | null)?.kind === 'terminal-input')
+ expect(rows.map(m => [m.text, m.recipientIds])).toEqual([[expect.stringMatching(/^owner typed `\/model` \+ Enter in .+'s terminal$/), []]])
+ await run(tab, { type: 'agent.inputResult', requestId, ok: true }, host, worker)
+ expect(await store.terminalResult(owner, tab, requestId)).toEqual({ requestId, ok: true })
+ })
+
+ it('fails with a plain reason when the host never picks up or never answers, and never types late', async () => {
+ const { tab, lead, worker, claim } = await terminalFixture()
+ const unseen = (await run(tab, { type: 'agent.screen', agentId: worker }, host, lead)).result.requestId as string
+ expect(await claim(later(11_000))).toEqual([])
+ expect(await store.terminalResult(host, tab, unseen, lead)).toEqual({ requestId: unseen, ok: false, error: expect.stringContaining('did not pick up') })
+ const typed = (await run(tab, { type: 'agent.input', agentId: worker, keys: ['Enter'] }, host, lead)).result.requestId as string
+ expect(await claim()).toHaveLength(1)
+ expect(await later(31_000).terminalResult(host, tab, typed, lead)).toEqual({ requestId: typed, ok: false, error: expect.stringContaining('did not answer') })
+ await expect(run(tab, { type: 'agent.inputResult', requestId: typed, ok: true }, host, worker)).rejects.toThrow('unavailable')
+ })
+
+ it('never hands the host a request for a terminal that was replaced', async () => {
+ const { tab, lead, worker, claim } = await terminalFixture()
+ const requestId = (await run(tab, { type: 'agent.input', agentId: worker, keys: ['Enter'] }, host, lead)).result.requestId as string
+ await db.superTabTerminalRequest.update({ where: { id: requestId }, data: { harnessId: 'replaced-terminal' } })
+ expect(await claim()).toEqual([])
+ expect(await store.terminalResult(host, tab, requestId, lead)).toEqual({ requestId, ok: false, error: expect.stringContaining('changed') })
+ })
+
+ // Neither demotion has a command (the Lead guard keeps a project's Lead), so the state is edited the way a future one would.
+ async function edit(tab: string, change: (state: SuperTabState) => void) {
+ const row = (await db.superTab.findUnique({ where: { id: tab } }))!
+ const state = structuredClone(row.state) as unknown as SuperTabState
+ change(state)
+ await db.superTab.update({ where: { id: tab }, data: { state: state as never, revision: row.revision + 1 } })
+ }
+ async function answered(tab: string, worker: string, requester: AuthUser = host, asAgentId?: string) {
+ const requestId = (await run(tab, { type: 'agent.screen', agentId: worker }, requester, asAgentId)).result.requestId as string
+ await store.hostTerminal(host, 'test-host')
+ await run(tab, { type: 'agent.screenResult', requestId, ok: true, text: 'TOKEN=fixture-secret' }, host, worker)
+ return requestId
+ }
+
+ it('gives a former Lead and a demoted person nothing, even for their own request', async () => {
+ const { tab, lead, worker } = await terminalFixture()
+ const asLead = await answered(tab, worker, host, lead)
+ await edit(tab, state => { state.conversations.find(c => c.id === 'lead')!.leadId = null })
+ await expect(store.terminalResult(host, tab, asLead, lead)).rejects.toThrow()
+ await invite(tab)
+ const asPeer = await answered(tab, worker, peer)
+ await edit(tab, state => { state.people.find(p => p.id === peer.sub)!.role = 'viewer' })
+ await expect(store.terminalResult(peer, tab, asPeer)).rejects.toThrow()
+ })
+
+ it('refuses a host answer after 30 seconds, even before the sender asked for it', async () => {
+ const { tab, lead, worker, claim } = await terminalFixture()
+ const requestId = (await run(tab, { type: 'agent.screen', agentId: worker }, host, lead)).result.requestId as string
+ expect(await claim()).toHaveLength(1)
+ await expect(later(31_000).execute(host, tab, { operationId: randomUUID(), command: { type: 'agent.screenResult', requestId, ok: true, text: 'late' } }, worker))
+ .rejects.toThrow('no longer waiting')
+ })
+
+ it('expires an unread answer after two minutes, without waiting for another request', async () => {
+ const { tab, lead, worker } = await terminalFixture()
+ const requestId = await answered(tab, worker, host, lead)
+ await expect(later(121_000).terminalResult(host, tab, requestId, lead)).rejects.toThrow('unavailable')
+ await ensureTerminalExpiry(db)
+ const indexes = await db.$runCommandRaw({ listIndexes: 'SuperTabTerminalRequest' }) as { cursor: { firstBatch: Array<{ key: object; expireAfterSeconds?: number }> } }
+ expect(indexes.cursor.firstBatch).toContainEqual(expect.objectContaining({ key: { createdAt: 1 }, expireAfterSeconds: TERMINAL_EXPIRY_MS / 1000 }))
+ })
+
+ it('serves the host and the requester over HTTP', async () => {
+ const { tab, lead, worker } = await terminalFixture()
+ const requestId = (await run(tab, { type: 'agent.screen', agentId: worker }, host, lead)).result.requestId as string
+ const claimed = await app.inject({ method: 'POST', url: '/api/super-tabs/hosts/test-host/terminal', headers: { authorization: `Bearer ${host.sub}` } })
+ expect(claimed.json().data.filter((row: { tabId: string }) => row.tabId === tab)).toHaveLength(1)
+ await run(tab, { type: 'agent.screenResult', requestId, ok: false, error: 'The pane closed.' }, host, worker)
+ const answer = await app.inject({ method: 'GET', url: `/api/super-tabs/${tab}/terminal/${requestId}?asAgentId=${lead}`, headers: { authorization: `Bearer ${host.sub}` } })
+ expect(answer.json().data).toEqual({ requestId, ok: false, error: 'The pane closed.' })
+ })
+})
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 14fbf9568..cf5ce414a 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1186,6 +1186,33 @@ model SuperTabConfiguration {
@@index([tabId, agentId, revision])
}
+// A Lead's read of, or input to, an agent's terminal, relayed to the host of the agent's machine
+// (backend/src/superTabs/terminal.ts). Outside the tab snapshot and history: a screen can show secrets,
+// so its text is kept only until the requester reads it.
+model SuperTabTerminalRequest {
+ id String @id @map("_id")
+ tabId String
+ agentId String
+ machineId String
+ machineOwnerId String
+ harnessId String
+ requesterKey String
+ kind String
+ scrollback Int?
+ text String?
+ keys String[] @default([])
+ /// pending -> claimed (handed to the host once) -> done
+ status String @default("pending")
+ ok Boolean?
+ result String?
+ error String?
+ createdAt DateTime
+ claimedAt DateTime?
+
+ @@index([machineId, status])
+ @@index([tabId, createdAt])
+}
+
model ExperimentalSettings {
id String @id @map("_id") @db.ObjectId
userId String
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 1854de551..2b118c6b6 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -28,6 +28,7 @@ const messageQuery = agentQuery.extend({ after: z.coerce.number().int().nonnegat
before: z.coerce.number().int().nonnegative().safe().optional(), messageId: id.optional() })
.refine(q => [q.after, q.before, q.messageId].filter(value => value !== undefined).length <= 1, 'Choose one message cursor or exact message.')
const decisionParams = tabParams.extend({ decisionId: id })
+const terminalParams = tabParams.extend({ requestId: id })
const hostParams = z.object({ machineId: id })
const hostStartParams = hostParams.extend({ tabId: id, startId: id })
const machineParams = hostParams.extend({ tabId: id })
@@ -99,6 +100,12 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
(req, reply) => respond(reply, () => store.join(req.user!, req.params.tabId, req.body)))
app.get<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId', { preHandler: validateParams(hostParams) },
(req, reply) => respond(reply, () => store.hostTabs(req.user!, req.params.machineId)))
+ app.post<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId/terminal', { preHandler: validateParams(hostParams) },
+ (req, reply) => respond(reply, () => store.hostTerminal(req.user!, req.params.machineId)))
+ // Long-polls about 20 seconds; a request still waiting then answers `pending` and is read again.
+ app.get<{ Params: z.infer<typeof terminalParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/terminal/:requestId',
+ { preHandler: [validateParams(terminalParams), validateQuery(agentQuery)] },
+ (req, reply) => respond(reply, () => store.terminalResult(req.user!, req.params.tabId, req.params.requestId, req.query.asAgentId, 20_000)))
app.get<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId/assignments', { preHandler: validateParams(hostParams) },
(req, reply) => respond(reply, () => store.hostAssignments(req.user!, req.params.machineId)))
app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId',
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 895a09d02..648419464 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -10,6 +10,7 @@ import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type Rou
import { routingOverrideSchema } from './routingPolicy.js'
import { agentTarget, askedInSchema, broken, MAX_RULES, RULE_MESSAGE_MS, ruleSchema, ruleTextSchema, startTarget, type RunTarget } from './rules.js'
import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'
+import { TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, type TerminalRequest } from './terminal.js'
import { agentProjectId, deleteProject, groupProject, inviteLanding, ledProject, manageProject, mutableProjects, placeRules, projectMembers, projectOf, projectRules, readAgent, readConversation, readProject, sameProject, SKILL_MODE_NAMES, skillModeOf, type SwarmProject } from './projects.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
@@ -110,6 +111,14 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('route.record'), conversationId: id, decision: routeRecordSchema }).strict(),
z.object({ type: z.literal('route.override'), decisionId: id, candidateId: z.string().regex(/^c\d{1,2}$/), reason }).strict(),
z.object({ type: z.literal('route.modelResult'), decisionId: id, startId: id, model: z.string().min(1).max(200), effort: z.string().min(1).max(80) }).strict(),
+ z.object({ type: z.literal('agent.screen'), agentId: id, scrollback: z.number().int().min(1).max(200).optional() }).strict(),
+ // Text is typed as is, so it carries no control characters; Enter, Esc and the rest are named keys.
+ z.object({ type: z.literal('agent.input'), agentId: id, text: z.string().min(1).max(4000).regex(/^[^\x00-\x1f\x7f]*$/, 'Send Enter and other keys as named keys.').optional(),
+ keys: z.array(z.enum(TERMINAL_KEYS)).min(1).max(32).optional() }).strict().refine(c => c.text !== undefined || c.keys !== undefined, 'Type text or keys.'),
+ ...(['agent.screenResult', 'agent.inputResult'] as const).map(type => z.object({ type: z.literal(type), requestId: id, ok: z.boolean(),
+ text: z.string().refine(value => Buffer.byteLength(value) <= 65_536, 'A screen is at most 64 KB.').optional(),
+ error: z.string().trim().min(1).max(500).optional() }).strict().refine(c => c.ok || c.error !== undefined, 'Say why the request failed.')),
+ z.object({ type: z.literal('agent.alert'), agentId: id, alert: z.enum(['prompt', 'limit']), active: z.boolean(), resetAt: z.iso.datetime().optional() }).strict(),
z.object({ type: z.literal('work.check'), conversationId: id, assignmentId: id, checkId: id, passed: z.boolean(), evidence: text }).strict(),
])
export type Command = z.infer<typeof commandSchema>
@@ -139,6 +148,8 @@ export interface CommandContext {
/** Starts on the machine being contributed that the store found abandoned: never contributed, never dispatched,
* and older than ABANDONED_START_MS by their operation receipt. */
abandonedStartIds?: string[]
+ /** The request an `agent.screenResult` / `agent.inputResult` answers, read from SuperTabTerminalRequest by the store. */
+ terminalRequest?: TerminalRequest
}
/** Messages in a row between the Lead and its worker after which the Lead's message is no longer delivered automatically. */
@@ -367,6 +378,22 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
switch (command.type) {
+ case 'agent.screen':
+ case 'agent.input': {
+ const { effect, message } = terminalRequest(state, actor, sender, operationId, context.now, command)
+ effects.terminal = effect
+ result.requestId = operationId
+ if (message) effects.messages.push(message)
+ break
+ }
+ case 'agent.screenResult':
+ case 'agent.inputResult':
+ effects.terminal = terminalResult(state, actor, context.terminalRequest, command)
+ break
+ case 'agent.alert': {
+ effects.messages.push(...terminalAlert(state, actor, sender, operationId, context.now, command))
+ break
+ }
case 'project.report': {
const project = readProject(state, actor, command.projectId)
const group = conversation(state, project.leadConversationId)
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index ce4a0ccb7..4a21b38b8 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -41,6 +41,10 @@ export interface Agent {
downSince?: string
/** The down time already named in the Lead's scheduled wake-up (projectUpdates.ts), so each time down is named once. */
downNamed?: string
+ /** A usage limit seen on its terminal; routing skips the agent until then. Shown as null once passed (terminal.ts). */
+ limitedUntil?: string | null
+ /** Terminal alert episodes in progress, so each one posts a single row (terminal.ts). */
+ alerting?: Array<'prompt' | 'limit'>
}
export type AgentRole = 'builder' | 'reviewer'
export const agentRole = (agent: Pick<Agent, 'role'>): AgentRole => agent.role ?? 'builder'
@@ -184,6 +188,8 @@ export interface CommandEffects {
previousAttempts: Array<{ conversationId: string; brief: string; checks: Check[]; assignment: Assignment }>
routeDecisions: RouteDecisionEffect[]
result: Record<string, unknown>
+ /** A terminal request or its answer, written outside the tab state by the store (terminal.ts). */
+ terminal?: import('./terminal.js').TerminalEffect
}
export class SuperTabError extends Error {
constructor(readonly code: string, message: string, readonly status = 409) {
@@ -287,6 +293,7 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
const since = downSince(state, target, now)
if (since) target.downSince = since
delete target.downNamed
+ if (target.limitedUntil && Date.parse(target.limitedUntil) <= now) target.limitedUntil = null
}
delete visible.sharing
delete visible.harnessReservations
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 954c05ac8..771072f96 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -19,6 +19,7 @@ import {
SuperTabError, type Actor, type Agent, type Assignment, type Author, type MessageDraft, type SuperTabState,
} from './model.js'
import { holdNoticeText, type HoldReason } from './holdNotice.js'
+import { mayDrive, TERMINAL_ANSWER_MS, TERMINAL_EXPIRY_MS, TERMINAL_PICKUP_MS, type TerminalEffect } from './terminal.js'
import { closeAssignment, readDecision, recentRoutes, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'
import { DEFAULT_ROUTING_POLICY, effectivePolicy, routingPolicySchema, type RoutingPolicy } from './routingPolicy.js'
import { authenticatedEmail, authorizeSwarmJoin, configureSharing, joinSwarmSchema, requireSharingOwner,
@@ -422,6 +423,18 @@ export class SuperTabStore {
}
if (command.type === 'message.send' && command.attachmentIds?.length) context.attachments = await this.sendable(tx, tabId, actor, command)
if (command.type === 'route.record') context.recentRoutes = await recentRoutes(tx, tabId, context.now)
+ if (command.type === 'agent.screen' || command.type === 'agent.input') {
+ // A machine that is gone or no longer shared refuses at once instead of leaving the request to time out.
+ await this.agentGrant(tx, original, agent(original, command.agentId))
+ const waiting = await tx.superTabTerminalRequest.count({ where: { tabId, agentId: command.agentId, status: { in: ['pending', 'claimed'] },
+ createdAt: { gte: new Date(context.now - TERMINAL_PICKUP_MS - TERMINAL_ANSWER_MS) } } })
+ if (waiting >= 10) fail('RATE_LIMITED', 'Ten requests to this terminal are still waiting. Wait for them to finish.', 429)
+ }
+ if (command.type === 'agent.screenResult' || command.type === 'agent.inputResult') {
+ const request = await tx.superTabTerminalRequest.findFirst({ where: { id: command.requestId, tabId } })
+ if (request) context.terminalRequest = { id: request.id, agentId: request.agentId, harnessId: request.harnessId,
+ kind: request.kind as 'screen' | 'input', status: request.status as 'pending' | 'claimed' | 'done' }
+ }
const decisionId = command.type === 'route.override' || command.type === 'route.modelResult' ? command.decisionId
: command.type === 'work.assign' || command.type === 'agent.start' ? command.routeDecisionId : undefined
if (decisionId) context.routeDecision = await readDecision(tx, tabId, decisionId) ?? fail('NOT_FOUND', 'This routing decision is unavailable.', 404)
@@ -539,6 +552,7 @@ export class SuperTabStore {
revision, state: json(effects.state), ...indexes(effects.state),
} })
await writeRouteEffects(tx, tabId, effects.routeDecisions, context.now)
+ if (effects.terminal) await this.writeTerminal(tx, tabId, effects.terminal, context.now)
if (command.type === 'work.cancel') {
await closeAssignment(tx, tabId, command.assignmentId, 'cancelled', context.now)
}
@@ -643,6 +657,98 @@ export class SuperTabStore {
})
}
+ private async writeTerminal(tx: Transaction, tabId: string, effect: TerminalEffect, now: number) {
+ if (effect.op === 'request') {
+ const { op: _op, id, ...request } = effect
+ await tx.superTabTerminalRequest.create({ data: { id, tabId, ...request, createdAt: new Date(now) } })
+ return
+ }
+ // The deadline holds whether or not the sender has asked for the answer yet.
+ const answered = await tx.superTabTerminalRequest.updateMany({ where: { id: effect.id, tabId, status: 'claimed', claimedAt: { gte: new Date(now - TERMINAL_ANSWER_MS) } },
+ data: { status: 'done', ok: effect.ok, result: effect.text, error: effect.error } })
+ if (!answered.count) fail('REQUEST_CLOSED', 'This terminal request is no longer waiting for an answer.')
+ }
+
+ /** The requester alone reads the answer, once: the screen text is deleted as it is returned. Waits up to `waitMs` for it. */
+ async terminalResult(user: AuthUser, tabId: string, requestId: string, asAgentId?: string, waitMs = 0) {
+ const deadline = Date.now() + waitMs
+ for (;;) {
+ const answer = await transaction(this.db, async tx => {
+ const state = stateOf(await this.row(tx, user, tabId))
+ const actor = await this.actor(tx, user, state, asAgentId)
+ author(state, actor)
+ const now = this.now()
+ const row = await tx.superTabTerminalRequest.findFirst({ where: { id: requestId, tabId, createdAt: { gte: new Date(now - TERMINAL_EXPIRY_MS) } } })
+ if (!row || row.requesterKey !== actorKey(actor)) fail('NOT_FOUND', 'This terminal request is unavailable.', 404)
+ // A sender who has since lost write access, or is no longer the agent's project Lead, gets nothing.
+ mayDrive(state, actor, agent(state, row.agentId))
+ const late = row.status === 'pending' && now - row.createdAt.getTime() > TERMINAL_PICKUP_MS
+ ? 'The agent’s machine did not pick up the request within 10 seconds. It may be offline or asleep.'
+ : row.status === 'claimed' && now - row.claimedAt!.getTime() > TERMINAL_ANSWER_MS
+ ? 'The agent’s machine picked up the request but did not answer within 30 seconds.' : null
+ if (row.status !== 'done' && !late) return null
+ await tx.superTabTerminalRequest.delete({ where: { id: row.id } })
+ if (late || !row.ok) return { requestId, ok: false, error: late ?? row.error }
+ return { requestId, ok: true, ...(row.result !== null ? { text: row.result } : {}) }
+ })
+ if (answer) return answer
+ if (Date.now() >= deadline) return { requestId, pending: true }
+ await new Promise(resolve => setTimeout(resolve, 250))
+ }
+ }
+
+ /** Each waiting request for this host's agents is handed over once. One that waited too long, or whose terminal, agent or
+ * requester changed, is answered with the reason instead, so input is never typed late or into another pane. */
+ async hostTerminal(user: AuthUser, machineId: string) {
+ return transaction(this.db, async tx => {
+ const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })
+ if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
+ const now = this.now()
+ const rows = await tx.superTabTerminalRequest.findMany({ where: { machineId, machineOwnerId: user.sub, status: 'pending' },
+ orderBy: { createdAt: 'asc' }, take: 100 })
+ const states = new Map<string, SuperTabState | null>()
+ const result = []
+ for (const row of rows) {
+ if (!states.has(row.tabId)) {
+ const tab = await tx.superTab.findFirst({ where: { id: row.tabId, autonomousEnv: user.autonomousEnv } })
+ states.set(row.tabId, tab && stateOf(tab))
+ }
+ const refusal = now - row.createdAt.getTime() > TERMINAL_PICKUP_MS
+ ? 'The agent’s machine did not pick up the request within 10 seconds. It may be offline or asleep.'
+ : await this.terminalRefusal(tx, states.get(row.tabId)!, row)
+ if (refusal) {
+ await tx.superTabTerminalRequest.updateMany({ where: { id: row.id, status: 'pending' }, data: { status: 'done', ok: false, error: refusal } })
+ continue
+ }
+ const claimed = await tx.superTabTerminalRequest.updateMany({ where: { id: row.id, status: 'pending' }, data: { status: 'claimed', claimedAt: new Date(now) } })
+ if (!claimed.count) continue
+ result.push({ tabId: row.tabId, agentId: row.agentId, harnessId: row.harnessId, request: { id: row.id, kind: row.kind,
+ ...(row.scrollback !== null ? { scrollback: row.scrollback } : {}), ...(row.text !== null ? { text: row.text } : {}),
+ ...(row.keys.length ? { keys: row.keys } : {}) } })
+ }
+ return result
+ })
+ }
+
+ private async terminalRefusal(tx: Transaction, state: SuperTabState | null,
+ row: { agentId: string; machineId: string; machineOwnerId: string; harnessId: string; requesterKey: string }): Promise<string | null> {
+ const target = state?.agents.find(a => a.id === row.agentId && a.machineId === row.machineId && a.machineOwnerId === row.machineOwnerId)
+ if (!state || !target) return 'The agent is no longer in the Swarm.'
+ if (target.harnessId !== row.harnessId) return 'The agent’s terminal changed since the request. Read it again.'
+ const [kind, id] = [row.requesterKey.slice(0, row.requesterKey.indexOf(':')), row.requesterKey.slice(row.requesterKey.indexOf(':') + 1)]
+ const requester: Actor = kind === 'person' ? { kind: 'person', userId: id, email: '' }
+ : { kind: 'agent', agentId: id, machineOwnerId: state.agents.find(a => a.id === id)?.machineOwnerId ?? '' }
+ try {
+ agent(state, target.id)
+ await this.agentGrant(tx, state, target)
+ mayDrive(state, requester, target)
+ } catch (error) {
+ if (error instanceof SuperTabError) return 'This request is no longer allowed.'
+ throw error
+ }
+ return null
+ }
+
/** Records committed messages and one delivery per recipient, at the tab revision that carried them. */
private async writeMessages(tx: Transaction, tabId: string, state: SuperTabState, messages: MessageDraft[], revision: number) {
for (const message of messages) {
diff --git a/backend/src/superTabs/terminal.test.ts b/backend/src/superTabs/terminal.test.ts
new file mode 100644
index 000000000..1a27edc14
--- /dev/null
+++ b/backend/src/superTabs/terminal.test.ts
@@ -0,0 +1,171 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, visibleState, type Actor, type AgentConfiguration, type SuperTabState } from './model.js'
+
+const owner: Actor = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const peer: Actor = { kind: 'person', userId: 'peer', email: '[email protected]' }
+const config: AgentConfiguration = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }
+const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
+
+function swarm(peerRole: 'collaborator' | 'viewer' = 'collaborator') {
+ let state: SuperTabState = createSuperTab('tab', 'Pilot', { id: 'owner', email: '[email protected]' }, 'prod')
+ let sequence = 0
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { now: 1_000_000, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const invited = run({ type: 'invite.create', email: '[email protected]', role: peerRole, conversationId: 'lead' })
+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)
+ const add = (harnessId: string, group: string, lead = false) => run({ type: 'agent.add', conversationId: group, machineId: 'host', harnessId,
+ name: harnessId, configuration: config, lead }, owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string
+ const lead = add('lead', 'lead', true)
+ const group = run({ type: 'conversation.create', title: 'Drafts', brief: 'Save drafts.', checks: [{ description: 'Saved', independent: false }] }).result.conversationId as string
+ run({ type: 'conversation.agent', conversationId: group, agentId: lead, present: true, lead: true })
+ const worker = add('worker', group)
+ const other = run({ type: 'project.create', name: 'Other', visibility: 'public', brief: '' }).result.conversationId as string
+ const otherLead = add('other-lead', other, true)
+ return { run, lead, worker, group, otherLead, get state() { return state } }
+}
+
+const name = (s: ReturnType<typeof swarm>, agentId: string) => { const a = s.state.agents.find(a => a.id === agentId)!; return a.displayName ?? a.name }
+
+describe('reading and typing in an agent terminal', () => {
+ it('lets the project Lead read a worker terminal, without writing to any group', () => {
+ const s = swarm()
+ const effects = s.run({ type: 'agent.screen', agentId: s.worker, scrollback: 200 }, as(s.lead))
+ expect(effects.result.requestId).toEqual(expect.any(String))
+ expect(effects.terminal).toEqual({ op: 'request', id: effects.result.requestId, kind: 'screen', agentId: s.worker, machineId: 'host',
+ machineOwnerId: 'host-owner', harnessId: 'worker', requesterKey: `agent:${s.lead}`, scrollback: 200 })
+ expect(effects.messages).toEqual([])
+ })
+
+ it('lets a person with write access read and type, and refuses a viewer', () => {
+ expect(swarm().run({ type: 'agent.screen', agentId: swarm().worker }, peer).terminal).toMatchObject({ requesterKey: 'person:peer' })
+ const s = swarm('viewer')
+ expect(() => s.run({ type: 'agent.screen', agentId: s.worker }, peer)).toThrow('read-only')
+ })
+
+ it('refuses the worker itself, another worker and another project\'s Lead', () => {
+ const s = swarm()
+ const second = s.run({ type: 'agent.add', conversationId: s.group, machineId: 'host', harnessId: 'second', name: 'second', configuration: config, lead: false },
+ owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string
+ for (const actor of [as(s.worker), as(second), as(s.otherLead)]) {
+ expect(() => s.run({ type: 'agent.screen', agentId: s.worker }, actor)).toThrow()
+ expect(() => s.run({ type: 'agent.input', agentId: s.worker, keys: ['Enter'] }, actor)).toThrow()
+ }
+ })
+
+ it('logs typed input as a terminal-input row in the agent\'s current group, delivered to nobody', () => {
+ const s = swarm()
+ s.run({ type: 'work.assign', conversationId: s.group, agentId: s.worker })
+ const effects = s.run({ type: 'agent.input', agentId: s.worker, text: 'y'.repeat(250), keys: ['Enter'] }, as(s.lead))
+ expect(effects.terminal).toMatchObject({ op: 'request', kind: 'input', text: 'y'.repeat(250), keys: ['Enter'] })
+ expect(effects.messages).toEqual([expect.objectContaining({ conversationId: s.group, recipients: [],
+ text: `${name(s, s.lead)} typed \`${'y'.repeat(199)}…\` + Enter in ${name(s, s.worker)}'s terminal`,
+ source: { kind: 'terminal-input', agentId: s.worker, requestId: effects.result.requestId } })])
+ })
+
+ it('logs input to the Lead in the project\'s Lead conversation', () => {
+ const s = swarm()
+ expect(s.run({ type: 'agent.input', agentId: s.lead, keys: ['Esc', '2'] }).messages[0])
+ .toMatchObject({ conversationId: 'lead', text: `owner typed Esc + 2 in ${name(s, s.lead)}'s terminal` })
+ })
+
+ it('accepts only printable text and named keys, and needs one of them', () => {
+ const input = (patch: Record<string, unknown>) => commandSchema.safeParse({ type: 'agent.input', agentId: 'a', ...patch }).success
+ expect(input({ text: 'continue' })).toBe(true)
+ expect(input({ keys: ['Enter', 'Esc', 'Tab', 'Up', 'Down', 'Left', 'Right', 'Ctrl-C', '0', '9'] })).toBe(true)
+ expect(input({})).toBe(false)
+ expect(input({ text: 'rm -rf /\n' })).toBe(false)
+ expect(input({ text: '\x1b[A' })).toBe(false)
+ expect(input({ keys: ['Ctrl-D'] })).toBe(false)
+ expect(commandSchema.safeParse({ type: 'agent.screen', agentId: 'a', scrollback: 201 }).success).toBe(false)
+ })
+
+ it('fails at once when the agent\'s terminal or machine is down', () => {
+ const s = swarm()
+ s.state.agents.find(a => a.id === s.worker)!.downSince = new Date(0).toISOString()
+ expect(() => s.run({ type: 'agent.screen', agentId: s.worker }, as(s.lead))).toThrow('offline')
+ })
+})
+
+describe('answering a terminal request', () => {
+ const claimed = (s: ReturnType<typeof swarm>, kind: 'screen' | 'input' = 'screen') =>
+ ({ terminalRequest: { id: 'req', agentId: s.worker, harnessId: 'worker', kind, status: 'claimed' } }) as Partial<CommandContext>
+
+ it('takes the screen from the agent\'s own host and writes nothing to a group', () => {
+ const s = swarm()
+ const effects = s.run({ type: 'agent.screenResult', requestId: 'req', ok: true, text: 'Allow edit? (y/n)' }, as(s.worker), claimed(s))
+ expect(effects.terminal).toEqual({ op: 'result', id: 'req', ok: true, text: 'Allow edit? (y/n)', error: null })
+ expect(effects.messages).toEqual([])
+ expect(s.run({ type: 'agent.inputResult', requestId: 'req', ok: false, error: 'No pane' }, as(s.worker), claimed(s, 'input')).terminal)
+ .toEqual({ op: 'result', id: 'req', ok: false, text: null, error: 'No pane' })
+ })
+
+ it('refuses another agent, a replaced terminal, a closed request and the wrong kind', () => {
+ const s = swarm()
+ const answer: Command = { type: 'agent.screenResult', requestId: 'req', ok: true, text: 'x' }
+ expect(() => s.run(answer, as(s.lead), claimed(s))).toThrow()
+ expect(() => s.run(answer, as(s.worker))).toThrow()
+ expect(() => s.run(answer, as(s.worker), { terminalRequest: { ...claimed(s).terminalRequest!, harnessId: 'old' } })).toThrow()
+ expect(() => s.run(answer, as(s.worker), { terminalRequest: { ...claimed(s).terminalRequest!, status: 'done' } })).toThrow()
+ expect(() => s.run(answer, as(s.worker), claimed(s, 'input'))).toThrow()
+ })
+
+ it('caps the screen at 64 KB and needs an error when it failed', () => {
+ const result = (patch: Record<string, unknown>) => commandSchema.safeParse({ type: 'agent.screenResult', requestId: 'r', ok: true, ...patch }).success
+ expect(result({ text: 'x'.repeat(65_536) })).toBe(true)
+ expect(result({ text: 'é'.repeat(40_000) })).toBe(false)
+ expect(result({ ok: false })).toBe(false)
+ expect(result({ ok: false, error: 'Pane closed' })).toBe(true)
+ })
+})
+
+describe('terminal alerts', () => {
+ it('posts one row per episode to the agent\'s group and delivers it to the Lead', () => {
+ const s = swarm()
+ s.run({ type: 'work.assign', conversationId: s.group, agentId: s.worker })
+ const prompt: Command = { type: 'agent.alert', agentId: s.worker, alert: 'prompt', active: true }
+ expect(s.run(prompt, as(s.worker)).messages).toEqual([expect.objectContaining({ conversationId: s.group, recipients: [s.lead],
+ text: `${name(s, s.worker)} is waiting at a prompt in its terminal.`, source: { kind: 'terminal-alert', agentId: s.worker, alert: 'prompt' } })])
+ expect(s.run(prompt, as(s.worker)).messages).toEqual([])
+ s.run({ ...prompt, active: false } as Command, as(s.worker))
+ expect(s.run(prompt, as(s.worker)).messages).toHaveLength(1)
+ })
+
+ it('delivers to the worker\'s project Lead, not the group\'s Lead, and through the Lead chat when the Lead is not in the group', () => {
+ const s = swarm()
+ const bare = s.run({ type: 'conversation.create', title: 'Bare', brief: 'No Lead here.', checks: [] }).result.conversationId as string
+ const room = s.state.conversations.find(c => c.id === bare)!
+ room.leadId = null
+ room.agentIds = room.agentIds.filter(id => id !== s.lead)
+ const other = s.run({ type: 'agent.add', conversationId: bare, machineId: 'host', harnessId: 'other-worker', name: 'other-worker', configuration: config, lead: false },
+ owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string
+ const rows = s.run({ type: 'agent.alert', agentId: other, alert: 'prompt', active: true }, as(other)).messages
+ expect(rows.map(r => [r.conversationId, r.recipients])).toEqual([[bare, []], ['lead', [s.lead]]])
+ s.state.conversations.find(c => c.id === s.group)!.leadId = other
+ expect(s.run({ type: 'agent.alert', agentId: s.worker, alert: 'prompt', active: true }, as(s.worker)).messages
+ .map(r => [r.conversationId, r.recipients])).toEqual([[s.group, [s.lead]]])
+ })
+
+ it('marks a limited agent until its reset time, or an hour, and shows null once it passed', () => {
+ const s = swarm()
+ const reset = new Date(1_000_000 + 600_000).toISOString()
+ const effects = s.run({ type: 'agent.alert', agentId: s.worker, alert: 'limit', active: true, resetAt: reset }, as(s.worker))
+ expect(effects.messages[0]).toMatchObject({ text: `${name(s, s.worker)} hit a usage limit. Routing skips it until 00:26 UTC.`,
+ source: { kind: 'terminal-alert', agentId: s.worker, alert: 'limit', limitedUntil: reset } })
+ expect(s.state.agents.find(a => a.id === s.worker)!.limitedUntil).toBe(reset)
+ expect(visibleState(s.state, owner, 1_000_000).agents.find(a => a.id === s.worker)!.limitedUntil).toBe(reset)
+ expect(visibleState(s.state, owner, 1_600_000).agents.find(a => a.id === s.worker)!.limitedUntil).toBeNull()
+ const lead = s.run({ type: 'agent.alert', agentId: s.lead, alert: 'limit', active: true }, as(s.lead))
+ expect(s.state.agents.find(a => a.id === s.lead)!.limitedUntil).toBe(new Date(1_000_000 + 3_600_000).toISOString())
+ expect(lead.messages[0]).toMatchObject({ conversationId: 'lead', recipients: [] })
+ })
+
+ it('takes alerts only from the agent\'s own host', () => {
+ const s = swarm()
+ expect(() => s.run({ type: 'agent.alert', agentId: s.worker, alert: 'prompt', active: true }, as(s.lead))).toThrow()
+ expect(() => s.run({ type: 'agent.alert', agentId: s.worker, alert: 'prompt', active: true })).toThrow()
+ })
+})
diff --git a/backend/src/superTabs/terminal.ts b/backend/src/superTabs/terminal.ts
new file mode 100644
index 000000000..cfe7a7a5a
--- /dev/null
+++ b/backend/src/superTabs/terminal.ts
@@ -0,0 +1,109 @@
+import type { PrismaClient } from '@prisma/client'
+import { activeWork, actorKey, agent, author, conversation, fail, stableId, type Actor, type Agent, type Author, type Conversation, type MessageDraft,
+ type SuperTabState } from './model.js'
+import { downSince } from './machines.js'
+import { agentProjectId, projectOf, readAgent } from './projects.js'
+
+/** The Lead reads and types in an agent's terminal through the host of the agent's machine (spec/2026-10-23-lead-sees-agent-terminal.md).
+ * The request and its answer live in SuperTabTerminalRequest, never in the tab state or group history, because a screen can show secrets. */
+export const TERMINAL_KEYS = ['Enter', 'Esc', 'Tab', 'Up', 'Down', 'Left', 'Right', 'Ctrl-C', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] as const
+/** The host has this long to pick a request up, then this long to answer it; after either, the request fails with a plain reason. */
+export const TERMINAL_PICKUP_MS = 10_000
+export const TERMINAL_ANSWER_MS = 30_000
+/** An unread answer, which can hold a screen's secrets, is gone after this long: refused on read, and removed by a TTL index. */
+export const TERMINAL_EXPIRY_MS = 120_000
+/** Run by the singleton worker at startup, like the product-usage expiry indexes. */
+export async function ensureTerminalExpiry(db: PrismaClient): Promise<void> {
+ await db.$runCommandRaw({ createIndexes: 'SuperTabTerminalRequest', indexes: [{ key: { createdAt: 1 }, name: 'terminal_request_expiry',
+ expireAfterSeconds: TERMINAL_EXPIRY_MS / 1000 }] })
+}
+/** A limited agent without a shown reset time is skipped by routing for this long. */
+export const LIMIT_FALLBACK_MS = 3_600_000
+
+export type TerminalKind = 'screen' | 'input'
+export type TerminalEffect =
+ | { op: 'request'; id: string; kind: TerminalKind; agentId: string; machineId: string; machineOwnerId: string; harnessId: string; requesterKey: string;
+ scrollback?: number; text?: string; keys?: string[] }
+ | { op: 'result'; id: string; ok: boolean; text: string | null; error: string | null }
+/** A stored request as the store reads it for an answer. */
+export interface TerminalRequest { id: string; agentId: string; harnessId: string; kind: TerminalKind; status: 'pending' | 'claimed' | 'done' }
+
+/** Only the Lead of the agent's project, or a person with write access who can see the agent, reads or types in its terminal. */
+export function mayDrive(state: SuperTabState, actor: Actor, target: Agent): void {
+ if (actor.kind === 'person') {
+ author(state, actor, true)
+ readAgent(state, actor, target.id)
+ return
+ }
+ if (conversation(state, projectOf(state, agentProjectId(state, target)).leadConversationId).leadId !== actor.agentId) {
+ fail('LEAD_REQUIRED', 'Only the Lead of this agent’s project, or a person with write access, can read or type in its terminal.', 403)
+ }
+}
+
+/** The group a terminal row belongs in: the agent's active work, else its newest open group as a member, else its project's Lead chat. */
+export function currentGroup(state: SuperTabState, target: Agent): Conversation {
+ return state.conversations.find(c => activeWork(c) && c.assignment!.agentId === target.id)
+ ?? state.conversations.findLast(c => !c.archived && c.agentIds.includes(target.id) && c.leadId !== target.id)
+ ?? conversation(state, projectOf(state, agentProjectId(state, target)).leadConversationId)
+}
+
+const nameOf = (target: Agent) => target.displayName ?? target.name
+
+export function terminalRequest(state: SuperTabState, actor: Actor, sender: Author, id: string, now: number,
+ command: { type: 'agent.screen' | 'agent.input'; agentId: string; scrollback?: number; text?: string; keys?: string[] }) {
+ const target = agent(state, command.agentId)
+ mayDrive(state, actor, target)
+ if (downSince(state, target, now)) fail('HOST_OFFLINE', `${nameOf(target)}’s terminal is not running or its machine is offline.`)
+ const { type: _type, agentId: _agentId, ...detail } = command
+ const effect: TerminalEffect = { op: 'request', id, kind: command.type === 'agent.screen' ? 'screen' : 'input', agentId: target.id,
+ machineId: target.machineId, machineOwnerId: target.machineOwnerId, harnessId: target.harnessId, requesterKey: actorKey(actor), ...detail }
+ if (command.type === 'agent.screen') return { effect, message: null }
+ const text = command.text && `\`${command.text.length > 200 ? `${command.text.slice(0, 199)}…` : command.text}\``
+ const typed = [text, ...command.keys ?? []].filter(Boolean).join(' + ')
+ const who = sender.displayName ?? (sender.kind === 'person' ? sender.name.split('@')[0]! : sender.name)
+ const message: MessageDraft = { id, conversationId: currentGroup(state, target).id, author: sender, replyTo: null, recipients: [],
+ text: `${who} typed ${typed} in ${nameOf(target)}'s terminal`, source: { kind: 'terminal-input', agentId: target.id, requestId: id } }
+ return { effect, message }
+}
+
+/** Only the host of the agent's current terminal answers, once, a request it claimed. */
+export function terminalResult(state: SuperTabState, actor: Actor, request: TerminalRequest | undefined,
+ command: { type: 'agent.screenResult' | 'agent.inputResult'; ok: boolean; text?: string; error?: string }): TerminalEffect {
+ if (!request) fail('NOT_FOUND', 'This terminal request is unavailable.', 404)
+ const target = agent(state, request.agentId)
+ if (actor.kind !== 'agent' || actor.agentId !== target.id || target.harnessId !== request.harnessId) {
+ fail('HOST_REQUIRED', 'Only the host of this agent’s terminal answers its requests.', 403)
+ }
+ if (request.kind !== (command.type === 'agent.screenResult' ? 'screen' : 'input')) fail('REQUEST_MISMATCH', 'Answer this request with its own kind of result.', 400)
+ if (request.status !== 'claimed') fail('REQUEST_CLOSED', 'This terminal request is no longer waiting for an answer.')
+ return { op: 'result', id: request.id, ok: command.ok, text: command.ok && request.kind === 'screen' ? command.text ?? '' : null,
+ error: command.ok ? null : command.error! }
+}
+
+/** One row per episode: a repeated observation adds nothing, and `active: false` ends the episode. No screen text goes in the row.
+ * It is delivered to the agent's project Lead, in the agent's group when the Lead is there, else by a second row in the Lead's chat. */
+export function terminalAlert(state: SuperTabState, actor: Actor, sender: Author, id: string, now: number,
+ command: { agentId: string; alert: 'prompt' | 'limit'; active: boolean; resetAt?: string }): MessageDraft[] {
+ const target = agent(state, command.agentId)
+ if (actor.kind !== 'agent' || actor.agentId !== target.id) fail('HOST_REQUIRED', 'Only the host of this agent’s terminal reports its alerts.', 403)
+ const alerting = target.alerting ?? []
+ if (!command.active) {
+ target.alerting = alerting.filter(a => a !== command.alert)
+ return []
+ }
+ if (alerting.includes(command.alert)) return []
+ target.alerting = [...alerting, command.alert]
+ const group = currentGroup(state, target)
+ const chat = conversation(state, projectOf(state, agentProjectId(state, target)).leadConversationId)
+ const lead = chat.leadId && chat.leadId !== target.id ? chat.leadId : null
+ let text = `${nameOf(target)} is waiting at a prompt in its terminal.`
+ const source: Record<string, unknown> = { kind: 'terminal-alert', agentId: target.id, alert: command.alert }
+ if (command.alert === 'limit') {
+ const reset = command.resetAt && Date.parse(command.resetAt) > now ? Date.parse(command.resetAt) : now + LIMIT_FALLBACK_MS
+ target.limitedUntil = source.limitedUntil = new Date(reset).toISOString()
+ text = `${nameOf(target)} hit a usage limit. Routing skips it until ${target.limitedUntil.slice(11, 16)} UTC.`
+ }
+ const here = !!lead && group.agentIds.includes(lead)
+ const row = { id, conversationId: group.id, author: sender, replyTo: null, recipients: here ? [lead] : [], text, source }
+ return here || !lead || !chat.agentIds.includes(lead) ? [row] : [row, { ...row, id: stableId(id, 'lead'), conversationId: chat.id, recipients: [lead] }]
+}
diff --git a/backend/src/worker.ts b/backend/src/worker.ts
index 51be5105c..069f4728b 100644
--- a/backend/src/worker.ts
+++ b/backend/src/worker.ts
@@ -15,6 +15,7 @@ import {
import { ensurePlans } from './lib/db/seed.js'
import { prisma } from './lib/prisma.js'
import { ensureProductUsageExpiry } from './lib/productUsage.js'
+import { ensureTerminalExpiry } from './superTabs/terminal.js'
import { machineBillingWorkerService } from './services/MachineBillingWorkerService.js'
import { productUsagePeopleRollupService } from './services/ProductUsagePeopleRollupService.js'
import { logger } from './utils/logger.js'
@@ -30,6 +31,7 @@ async function start(): Promise<void> {
await migrateUserPresencePerMachine()
ensureSchema()
await ensureProductUsageExpiry()
+ await ensureTerminalExpiry(prisma)
// AFTER the push: it creates the new collections + their unique indexes, and the copy uses $merge
// so those indexes survive. Copying first would leave the unique index build to fail silently.
await migrateMachineRename()