@brimveyn/aimux 1.18.3 → 1.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/cli/commands/tab/list.ts +34 -3
- package/src/cli/commands/tab/prompt-io.ts +83 -0
- package/src/cli/commands/tab/run.ts +222 -0
- package/src/cli/commands/tab/send.ts +63 -30
- package/src/cli/index.ts +1 -0
- package/src/cli/output.ts +2 -0
- package/src/cli/registry.ts +2 -0
- package/src/daemon/daemon.ts +41 -0
- package/src/daemon/session-registry.ts +15 -1
- package/src/ipc/protocol.ts +84 -2
- package/src/pty/assistant-question-extractor.ts +124 -0
- package/src/pty/assistant-status-detection-loop.ts +80 -3
- package/src/pty/assistant-status-detector.ts +13 -2
- package/src/pty/last-line.ts +29 -0
- package/src/session-backend/remote-session-backend.ts +5 -0
- package/src/state/types.ts +8 -0
package/package.json
CHANGED
|
@@ -1,20 +1,51 @@
|
|
|
1
1
|
import type { CliCommand } from '../../registry'
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
IPC_CAPABILITY_LIST_TABS,
|
|
5
|
+
IPC_CAPABILITY_LIST_TABS_LAST_LINE,
|
|
6
|
+
IPC_CAPABILITY_THIN_ATTACH,
|
|
7
|
+
type TabSessionSummary,
|
|
8
|
+
} from '../../../ipc/protocol'
|
|
4
9
|
import { SHARED_FLAGS } from '../../flags'
|
|
5
10
|
import { EXIT_OK, writeJson } from '../../output'
|
|
6
11
|
|
|
12
|
+
/**
|
|
13
|
+
* The daemon always populates `lastLine` on `listTabs` summaries (it's cheap),
|
|
14
|
+
* but the field bloats the common poll, so we strip it unless `--verbose` was
|
|
15
|
+
* asked for. Keeping the default output byte-identical to pre-v13 avoids
|
|
16
|
+
* churning downstream consumers.
|
|
17
|
+
*/
|
|
18
|
+
function stripLastLine(tab: TabSessionSummary): TabSessionSummary {
|
|
19
|
+
const { lastLine: _lastLine, ...rest } = tab
|
|
20
|
+
return rest
|
|
21
|
+
}
|
|
22
|
+
|
|
7
23
|
export const tabList: CliCommand = {
|
|
8
24
|
args: [],
|
|
9
|
-
flags:
|
|
25
|
+
flags: [
|
|
26
|
+
...SHARED_FLAGS,
|
|
27
|
+
{
|
|
28
|
+
description: "include each tab's last non-blank rendered line",
|
|
29
|
+
kind: 'boolean',
|
|
30
|
+
name: 'verbose',
|
|
31
|
+
},
|
|
32
|
+
],
|
|
10
33
|
group: 'tab',
|
|
11
34
|
run: async (ctx) => {
|
|
12
35
|
const workspace = ctx.getWorkspace()
|
|
13
36
|
const daemon = await ctx.getDaemon()
|
|
37
|
+
const verbose = ctx.args.flags.verbose === true
|
|
38
|
+
|
|
39
|
+
if (verbose && !daemon.hasCapability(IPC_CAPABILITY_LIST_TABS_LAST_LINE)) {
|
|
40
|
+
throw new Error(
|
|
41
|
+
'daemon predates tab list --verbose (listTabsLastLine) — restart aimux to pick up the new daemon'
|
|
42
|
+
)
|
|
43
|
+
}
|
|
14
44
|
|
|
15
45
|
if (daemon.hasCapability(IPC_CAPABILITY_LIST_TABS)) {
|
|
16
46
|
const result = await daemon.listTabs(workspace.id)
|
|
17
|
-
|
|
47
|
+
const tabs = verbose ? result.tabs : result.tabs.map(stripLastLine)
|
|
48
|
+
writeJson({ activeTabId: result.activeTabId, tabs })
|
|
18
49
|
return EXIT_OK
|
|
19
50
|
}
|
|
20
51
|
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared prompt-write plumbing for `tab send` and `tab run`. Both need to lower
|
|
3
|
+
* a chord/paste buffer into the protocol's string form and submit it with the
|
|
4
|
+
* bracketed-paste `\r` deferral, so the logic lives here once.
|
|
5
|
+
*/
|
|
6
|
+
import type { DaemonClient } from '../../client/daemon-client'
|
|
7
|
+
|
|
8
|
+
import { bracketedPaste, notationToBytes } from '../../chord'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Gap between the bracketed-paste write and the trailing carriage return when
|
|
12
|
+
* submitting a pasted block. Claude Code (and other paste-aware TUIs) buffer
|
|
13
|
+
* every byte between the paste-start/paste-end markers; a `\r` that arrives in
|
|
14
|
+
* the same burst as the paste-end marker is folded into the paste buffer as
|
|
15
|
+
* literal content instead of being read as a submit keystroke. A short settle
|
|
16
|
+
* lets the receiver exit paste mode before the Enter lands.
|
|
17
|
+
*/
|
|
18
|
+
export const PASTE_SUBMIT_SETTLE_MS = 50
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Lower a chord/paste buffer of bytes into the string the protocol expects.
|
|
22
|
+
* Every byte we emit is < 0x80 (control chars or printable ASCII), so a
|
|
23
|
+
* Latin-1 decode is faithful — the receiving PTY's UTF-8 path treats each
|
|
24
|
+
* single byte as itself.
|
|
25
|
+
*/
|
|
26
|
+
function bytesToString(bytes: Buffer): string {
|
|
27
|
+
let out = ''
|
|
28
|
+
for (const byte of bytes) {
|
|
29
|
+
out += String.fromCharCode(byte)
|
|
30
|
+
}
|
|
31
|
+
return out
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface PromptPayload {
|
|
35
|
+
/** The protocol-ready string to write. */
|
|
36
|
+
data: string
|
|
37
|
+
/**
|
|
38
|
+
* Whether `data` is a bracketed-paste block. A trailing `\r` must be sent as
|
|
39
|
+
* a separate, settled write for these — see PASTE_SUBMIT_SETTLE_MS.
|
|
40
|
+
*/
|
|
41
|
+
bracketed: boolean
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Build the payload for a prompt. `asKeys` interprets the text as a vim-style
|
|
46
|
+
* chord (e.g. `<C-c>`); otherwise it's wrapped as a bracketed paste when
|
|
47
|
+
* multi-line.
|
|
48
|
+
*/
|
|
49
|
+
export function buildPromptPayload(text: string, asKeys: boolean): PromptPayload {
|
|
50
|
+
if (asKeys) {
|
|
51
|
+
return { bracketed: false, data: bytesToString(notationToBytes(text)) }
|
|
52
|
+
}
|
|
53
|
+
const data = bracketedPaste(text)
|
|
54
|
+
return { bracketed: data !== text, data }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Write a prompt payload to a tab, optionally appending a submit `\r`. The
|
|
59
|
+
* payload write and the Enter are always separate `write` requests; for a
|
|
60
|
+
* bracketed paste the Enter is deferred by PASTE_SUBMIT_SETTLE_MS so it isn't
|
|
61
|
+
* swallowed by the paste buffer. Returns the number of bytes written.
|
|
62
|
+
*/
|
|
63
|
+
export async function writePromptPayload(
|
|
64
|
+
daemon: DaemonClient,
|
|
65
|
+
tabId: string,
|
|
66
|
+
payload: PromptPayload,
|
|
67
|
+
appendEnter: boolean
|
|
68
|
+
): Promise<number> {
|
|
69
|
+
await daemon.expectOk('write', { data: payload.data, tabId })
|
|
70
|
+
let bytesWritten = Buffer.byteLength(payload.data, 'utf8')
|
|
71
|
+
if (appendEnter) {
|
|
72
|
+
// A bracketed paste swallows a same-burst `\r`, so settle first, then
|
|
73
|
+
// submit as an independent write. Plain text / key chords carry no paste
|
|
74
|
+
// markers, so the Enter can follow immediately — but still as its own
|
|
75
|
+
// write so the two paths stay uniform.
|
|
76
|
+
if (payload.bracketed) {
|
|
77
|
+
await Bun.sleep(PASTE_SUBMIT_SETTLE_MS)
|
|
78
|
+
}
|
|
79
|
+
await daemon.expectOk('write', { data: '\r', tabId })
|
|
80
|
+
bytesWritten += 1
|
|
81
|
+
}
|
|
82
|
+
return bytesWritten
|
|
83
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `aimux tab run <tabId>` — the one authoritative verb an orchestrator needs to
|
|
3
|
+
* drive a worker turn. It collapses the spawn→send→uptake→await→snapshot chain
|
|
4
|
+
* into a single event-driven call: stage the prompt, submit it, then block on
|
|
5
|
+
* the daemon's v13 turn-lifecycle events (`tabTurnComplete` / `tabQuestion`)
|
|
6
|
+
* until the turn ends, the worker asks something, the tab dies, or the overall
|
|
7
|
+
* timeout trips. Exactly one JSON object is emitted and the exit code encodes
|
|
8
|
+
* the outcome, so a driver can branch without re-snapshotting the screen.
|
|
9
|
+
*/
|
|
10
|
+
import type { QuestionKind } from '../../../state/types'
|
|
11
|
+
import type { CliCommand } from '../../registry'
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
IPC_CAPABILITY_QUESTION_EVENTS,
|
|
15
|
+
IPC_CAPABILITY_THIN_ATTACH,
|
|
16
|
+
IPC_CAPABILITY_TURN_LIFECYCLE,
|
|
17
|
+
} from '../../../ipc/protocol'
|
|
18
|
+
import { SHARED_FLAGS } from '../../flags'
|
|
19
|
+
import { EXIT_OK, EXIT_QUESTION, EXIT_RUNTIME, EXIT_TIMEOUT, writeJson } from '../../output'
|
|
20
|
+
import { buildPromptPayload, writePromptPayload } from './prompt-io'
|
|
21
|
+
|
|
22
|
+
/** Overall cap on a single turn — 15 min, long enough for a heavy build task. */
|
|
23
|
+
const DEFAULT_TIMEOUT_MS = 900_000
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The four terminal shapes of a `tab run`. Modelled as a discriminated union so
|
|
27
|
+
* the JSON we emit and the exit code we return are derived from one value, and
|
|
28
|
+
* so the outcome→exit mapping can be unit-tested without a live daemon.
|
|
29
|
+
* `durationMs` is measured from prompt submit, not attach, so it reflects the
|
|
30
|
+
* worker's think time rather than our connection overhead.
|
|
31
|
+
*/
|
|
32
|
+
export type RunOutcome =
|
|
33
|
+
| { durationMs: number; outcome: 'completed' }
|
|
34
|
+
| { durationMs: number; error: string; outcome: 'error' }
|
|
35
|
+
| {
|
|
36
|
+
durationMs: number
|
|
37
|
+
kind: QuestionKind
|
|
38
|
+
options?: string[]
|
|
39
|
+
outcome: 'question'
|
|
40
|
+
question: string
|
|
41
|
+
}
|
|
42
|
+
| { durationMs: number; outcome: 'timeout' }
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Map an outcome to its process exit code. Pure and total over the union so a
|
|
46
|
+
* driver's `case $?` stays exhaustive: 0 completed, 10 question/permission
|
|
47
|
+
* (worker is blocked and wants input), 3 the tab errored/exited, 124 we hit the
|
|
48
|
+
* overall cap.
|
|
49
|
+
*/
|
|
50
|
+
export function outcomeExitCode(outcome: RunOutcome): number {
|
|
51
|
+
switch (outcome.outcome) {
|
|
52
|
+
case 'completed':
|
|
53
|
+
return EXIT_OK
|
|
54
|
+
case 'question':
|
|
55
|
+
return EXIT_QUESTION
|
|
56
|
+
case 'error':
|
|
57
|
+
return EXIT_RUNTIME
|
|
58
|
+
case 'timeout':
|
|
59
|
+
return EXIT_TIMEOUT
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Resolve the prompt text from exactly one source. We require exactly one of
|
|
65
|
+
* `--prompt-file`, `--stdin`, or the positional `[text]` so an orchestrator
|
|
66
|
+
* never silently sends the wrong buffer when two sources are set (e.g. a stale
|
|
67
|
+
* positional plus a fresh `--prompt-file`).
|
|
68
|
+
*/
|
|
69
|
+
async function resolvePromptText(
|
|
70
|
+
promptFile: string | undefined,
|
|
71
|
+
fromStdin: boolean,
|
|
72
|
+
positionalText: string | undefined
|
|
73
|
+
): Promise<string> {
|
|
74
|
+
const sources = [promptFile !== undefined, fromStdin, positionalText !== undefined].filter(
|
|
75
|
+
(present) => present
|
|
76
|
+
).length
|
|
77
|
+
if (sources !== 1) {
|
|
78
|
+
throw new Error(
|
|
79
|
+
'provide exactly one prompt source: --prompt-file <f>, --stdin, or a [text] positional'
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
if (promptFile !== undefined) return Bun.file(promptFile).text()
|
|
83
|
+
if (fromStdin) return Bun.stdin.text()
|
|
84
|
+
return positionalText ?? ''
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export const tabRun: CliCommand = {
|
|
88
|
+
args: [{ name: 'tabId', required: true }, { name: 'text' }],
|
|
89
|
+
flags: [
|
|
90
|
+
...SHARED_FLAGS,
|
|
91
|
+
{ description: 'read the prompt from this file', kind: 'string', name: 'prompt-file' },
|
|
92
|
+
{ description: 'read the prompt from stdin', kind: 'boolean', name: 'stdin' },
|
|
93
|
+
{
|
|
94
|
+
description: 'overall turn cap in milliseconds (default 900000 = 15 min)',
|
|
95
|
+
kind: 'number',
|
|
96
|
+
name: 'timeout',
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
description: 'stage the prompt without submitting (still waits)',
|
|
100
|
+
kind: 'boolean',
|
|
101
|
+
name: 'no-enter',
|
|
102
|
+
},
|
|
103
|
+
],
|
|
104
|
+
group: 'tab',
|
|
105
|
+
run: async (ctx) => {
|
|
106
|
+
const tabId = ctx.args.positionals[0]
|
|
107
|
+
if (typeof tabId !== 'string' || tabId.length === 0) {
|
|
108
|
+
throw new Error('tabId is required')
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const promptFile =
|
|
112
|
+
typeof ctx.args.flags['prompt-file'] === 'string' ? ctx.args.flags['prompt-file'] : undefined
|
|
113
|
+
const fromStdin = ctx.args.flags.stdin === true
|
|
114
|
+
const text = await resolvePromptText(promptFile, fromStdin, ctx.args.positionals[1])
|
|
115
|
+
|
|
116
|
+
const timeoutMs =
|
|
117
|
+
typeof ctx.args.flags.timeout === 'number' ? ctx.args.flags.timeout : DEFAULT_TIMEOUT_MS
|
|
118
|
+
const appendEnter = ctx.args.flags['no-enter'] !== true
|
|
119
|
+
|
|
120
|
+
const workspace = ctx.getWorkspace()
|
|
121
|
+
const daemon = await ctx.getDaemon()
|
|
122
|
+
if (
|
|
123
|
+
!daemon.hasCapability(IPC_CAPABILITY_THIN_ATTACH) ||
|
|
124
|
+
!daemon.hasCapability(IPC_CAPABILITY_TURN_LIFECYCLE) ||
|
|
125
|
+
!daemon.hasCapability(IPC_CAPABILITY_QUESTION_EVENTS)
|
|
126
|
+
) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
'daemon predates tab run (turnLifecycle/questionEvents) — restart aimux to pick up the new daemon'
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const attach = await daemon.attach({ cols: 0, rows: 0, sessionId: workspace.id, thin: true })
|
|
133
|
+
if (!attach.tabs.some((t) => t.id === tabId)) {
|
|
134
|
+
throw new Error(`tab not found: ${tabId}`)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const payload = buildPromptPayload(text, false)
|
|
138
|
+
|
|
139
|
+
return new Promise<number>((resolve) => {
|
|
140
|
+
// Subscribe BEFORE writing: these events fire only on transitions, so a
|
|
141
|
+
// late subscription would race the worker starting its turn.
|
|
142
|
+
let start = Date.now()
|
|
143
|
+
// Uptake guard. The tab may sit `idle` from a prior turn; a stale
|
|
144
|
+
// `tabTurnComplete` (or the settle window closing on that old idle) must
|
|
145
|
+
// not read as "this turn completed". Only honour completion once we've
|
|
146
|
+
// seen the tab go `working` after our submit.
|
|
147
|
+
let sawWorking = false
|
|
148
|
+
|
|
149
|
+
const settle = (outcome: RunOutcome): void => {
|
|
150
|
+
cleanup()
|
|
151
|
+
writeJson(outcome)
|
|
152
|
+
resolve(outcomeExitCode(outcome))
|
|
153
|
+
}
|
|
154
|
+
const durationMs = (): number => Date.now() - start
|
|
155
|
+
|
|
156
|
+
const offStatus = daemon.on('tabStatus', (p) => {
|
|
157
|
+
if (p.tabId !== tabId) return
|
|
158
|
+
if (p.status === 'working') sawWorking = true
|
|
159
|
+
})
|
|
160
|
+
const offTurn = daemon.on('tabTurnComplete', (p) => {
|
|
161
|
+
if (p.tabId !== tabId) return
|
|
162
|
+
// Ignore end-of-turn until the worker actually started working, so a
|
|
163
|
+
// lingering pre-submit idle can't be mis-read as completion.
|
|
164
|
+
if (!sawWorking) return
|
|
165
|
+
settle({ durationMs: durationMs(), outcome: 'completed' })
|
|
166
|
+
})
|
|
167
|
+
const offQuestion = daemon.on('tabQuestion', (p) => {
|
|
168
|
+
if (p.tabId !== tabId) return
|
|
169
|
+
// A question is honoured immediately — it can legitimately arrive
|
|
170
|
+
// before `working` (the worker asks before doing anything).
|
|
171
|
+
settle({
|
|
172
|
+
durationMs: durationMs(),
|
|
173
|
+
kind: p.kind,
|
|
174
|
+
options: p.options,
|
|
175
|
+
outcome: 'question',
|
|
176
|
+
question: p.prompt,
|
|
177
|
+
})
|
|
178
|
+
})
|
|
179
|
+
const offExit = daemon.on('tabExit', (p) => {
|
|
180
|
+
if (p.tabId !== tabId) return
|
|
181
|
+
settle({ durationMs: durationMs(), error: `exit ${p.exitCode}`, outcome: 'error' })
|
|
182
|
+
})
|
|
183
|
+
const offError = daemon.on('tabError', (p) => {
|
|
184
|
+
if (p.tabId !== tabId) return
|
|
185
|
+
settle({ durationMs: durationMs(), error: p.message, outcome: 'error' })
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
const timer = setTimeout(() => {
|
|
189
|
+
settle({ durationMs: durationMs(), outcome: 'timeout' })
|
|
190
|
+
}, timeoutMs)
|
|
191
|
+
|
|
192
|
+
const cleanup = (): void => {
|
|
193
|
+
offStatus()
|
|
194
|
+
offTurn()
|
|
195
|
+
offQuestion()
|
|
196
|
+
offExit()
|
|
197
|
+
offError()
|
|
198
|
+
clearTimeout(timer)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Submit after subscribing, then reset the clock so `durationMs` measures
|
|
202
|
+
// the worker's turn rather than our attach/write overhead. On a write
|
|
203
|
+
// failure the tab likely died — surface it as an error outcome rather
|
|
204
|
+
// than sitting idle until the timeout.
|
|
205
|
+
const submit = async (): Promise<void> => {
|
|
206
|
+
try {
|
|
207
|
+
await writePromptPayload(daemon, tabId, payload, appendEnter)
|
|
208
|
+
start = Date.now()
|
|
209
|
+
} catch (error) {
|
|
210
|
+
settle({
|
|
211
|
+
durationMs: durationMs(),
|
|
212
|
+
error: error instanceof Error ? error.message : String(error),
|
|
213
|
+
outcome: 'error',
|
|
214
|
+
})
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
void submit()
|
|
218
|
+
})
|
|
219
|
+
},
|
|
220
|
+
summary: 'Submit a prompt and block until the turn completes or the worker asks',
|
|
221
|
+
verb: 'run',
|
|
222
|
+
}
|
|
@@ -1,23 +1,12 @@
|
|
|
1
1
|
import type { CliCommand } from '../../registry'
|
|
2
2
|
|
|
3
3
|
import { IPC_CAPABILITY_THIN_ATTACH } from '../../../ipc/protocol'
|
|
4
|
-
import { bracketedPaste, notationToBytes } from '../../chord'
|
|
5
4
|
import { SHARED_FLAGS } from '../../flags'
|
|
6
5
|
import { EXIT_OK, writeJson } from '../../output'
|
|
6
|
+
import { buildPromptPayload, writePromptPayload } from './prompt-io'
|
|
7
7
|
|
|
8
|
-
/**
|
|
9
|
-
|
|
10
|
-
* Every byte we emit is < 0x80 (control chars or printable ASCII), so a
|
|
11
|
-
* Latin-1 decode is faithful — the receiving PTY's UTF-8 path treats each
|
|
12
|
-
* single byte as itself.
|
|
13
|
-
*/
|
|
14
|
-
function bytesToString(bytes: Buffer): string {
|
|
15
|
-
let out = ''
|
|
16
|
-
for (const byte of bytes) {
|
|
17
|
-
out += String.fromCharCode(byte)
|
|
18
|
-
}
|
|
19
|
-
return out
|
|
20
|
-
}
|
|
8
|
+
/** Default ceiling for the submit→working transition under --await-submit. */
|
|
9
|
+
const DEFAULT_AWAIT_TIMEOUT_MS = 15_000
|
|
21
10
|
|
|
22
11
|
export const tabSend: CliCommand = {
|
|
23
12
|
args: [{ name: 'tabId', required: true }, { name: 'text' }],
|
|
@@ -34,6 +23,18 @@ export const tabSend: CliCommand = {
|
|
|
34
23
|
kind: 'boolean',
|
|
35
24
|
name: 'stdin',
|
|
36
25
|
},
|
|
26
|
+
{
|
|
27
|
+
description:
|
|
28
|
+
'after submitting, block until the tab transitions to working (uptake confirmed)',
|
|
29
|
+
kind: 'boolean',
|
|
30
|
+
name: 'await-submit',
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
description:
|
|
34
|
+
'milliseconds to wait for the working transition with --await-submit (default 15000)',
|
|
35
|
+
kind: 'number',
|
|
36
|
+
name: 'await-timeout',
|
|
37
|
+
},
|
|
37
38
|
],
|
|
38
39
|
group: 'tab',
|
|
39
40
|
run: async (ctx) => {
|
|
@@ -45,24 +46,25 @@ export const tabSend: CliCommand = {
|
|
|
45
46
|
const fromStdin = ctx.args.flags.stdin === true
|
|
46
47
|
const asKeys = ctx.args.flags.keys === true
|
|
47
48
|
const appendEnter = ctx.args.flags.enter === true
|
|
49
|
+
const awaitSubmit = ctx.args.flags['await-submit'] === true
|
|
50
|
+
const awaitTimeoutMs =
|
|
51
|
+
typeof ctx.args.flags['await-timeout'] === 'number'
|
|
52
|
+
? ctx.args.flags['await-timeout']
|
|
53
|
+
: DEFAULT_AWAIT_TIMEOUT_MS
|
|
48
54
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
if (asKeys) {
|
|
56
|
-
if (text === '') throw new Error('--keys requires the chord notation as <text>')
|
|
57
|
-
data = bytesToString(notationToBytes(text))
|
|
58
|
-
} else {
|
|
59
|
-
data = bracketedPaste(text)
|
|
60
|
-
}
|
|
55
|
+
// Uptake only means something once we actually submit the prompt: the
|
|
56
|
+
// working transition is the receiving CLI accepting the Enter. Without
|
|
57
|
+
// --enter there is nothing to confirm, so fail loudly rather than block
|
|
58
|
+
// forever on a transition that can't come.
|
|
59
|
+
if (awaitSubmit && !appendEnter) {
|
|
60
|
+
throw new Error('--await-submit requires --enter')
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
-
|
|
64
|
-
|
|
63
|
+
const text = fromStdin ? await Bun.stdin.text() : (ctx.args.positionals[1] ?? '')
|
|
64
|
+
if (asKeys && text === '') {
|
|
65
|
+
throw new Error('--keys requires the chord notation as <text>')
|
|
65
66
|
}
|
|
67
|
+
const payload = buildPromptPayload(text, asKeys)
|
|
66
68
|
|
|
67
69
|
const workspace = ctx.getWorkspace()
|
|
68
70
|
const daemon = await ctx.getDaemon()
|
|
@@ -73,9 +75,40 @@ export const tabSend: CliCommand = {
|
|
|
73
75
|
}
|
|
74
76
|
|
|
75
77
|
await daemon.attach({ cols: 0, rows: 0, sessionId: workspace.id, thin: true })
|
|
76
|
-
await daemon.expectOk('write', { data, tabId })
|
|
77
78
|
|
|
78
|
-
|
|
79
|
+
if (!awaitSubmit) {
|
|
80
|
+
const bytesWritten = await writePromptPayload(daemon, tabId, payload, appendEnter)
|
|
81
|
+
writeJson({ bytesWritten, ok: true })
|
|
82
|
+
return EXIT_OK
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// The daemon only emits tabStatus on TRANSITIONS, so we must be subscribed
|
|
86
|
+
// before the submit write lands — otherwise the working transition can fire
|
|
87
|
+
// between the write and our subscription and be lost forever. Arm the
|
|
88
|
+
// listener + a one-shot promise here, then start the clock right before the
|
|
89
|
+
// Enter so `ms` reflects submit→uptake latency, not setup overhead.
|
|
90
|
+
const uptake = new Promise<{ confirmed: true; ms: number } | { confirmed: false }>(
|
|
91
|
+
(resolve) => {
|
|
92
|
+
const off = daemon.on('tabStatus', (event) => {
|
|
93
|
+
if (event.tabId !== tabId || event.status !== 'working') return
|
|
94
|
+
off()
|
|
95
|
+
clearTimeout(timer)
|
|
96
|
+
resolve({ confirmed: true, ms: Date.now() - start })
|
|
97
|
+
})
|
|
98
|
+
const timer = setTimeout(() => {
|
|
99
|
+
off()
|
|
100
|
+
resolve({ confirmed: false })
|
|
101
|
+
}, awaitTimeoutMs)
|
|
102
|
+
}
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
const start = Date.now()
|
|
106
|
+
const bytesWritten = await writePromptPayload(daemon, tabId, payload, appendEnter)
|
|
107
|
+
const result = await uptake
|
|
108
|
+
|
|
109
|
+
// The bytes WERE written regardless of uptake — the working transition is
|
|
110
|
+
// advisory, so a missed transition is still EXIT_OK.
|
|
111
|
+
writeJson({ bytesWritten, ok: true, submitted: true, uptake: result })
|
|
79
112
|
return EXIT_OK
|
|
80
113
|
},
|
|
81
114
|
summary: 'Write text or a key chord to a tab',
|
package/src/cli/index.ts
CHANGED
|
@@ -20,6 +20,7 @@ const EXIT_CODES_BLOCK = [
|
|
|
20
20
|
' 2 usage error (bad flags, unknown command, missing argument)',
|
|
21
21
|
' 3 runtime error (server replied with error, command failed)',
|
|
22
22
|
' 4 daemon unreachable (socket missing and autostart failed)',
|
|
23
|
+
' 10 question (tab run: worker is blocked on a question/permission)',
|
|
23
24
|
' 124 timeout (tab wait, tab tail --timeout, workspace switch --wait)',
|
|
24
25
|
].join('\n')
|
|
25
26
|
|
package/src/cli/output.ts
CHANGED
|
@@ -22,9 +22,11 @@ export function writeError(message: string): void {
|
|
|
22
22
|
// 2 usage error (bad flags, unknown command, missing argument)
|
|
23
23
|
// 3 runtime error (server replied with `error`, command failed)
|
|
24
24
|
// 4 daemon unreachable (socket missing and autostart failed)
|
|
25
|
+
// 10 question (`tab run`: worker is blocked on a question/permission)
|
|
25
26
|
// 124 timeout (`tab wait`, `tab tail --timeout`, `workspace switch --wait`)
|
|
26
27
|
export const EXIT_OK = 0
|
|
27
28
|
export const EXIT_USAGE = 2
|
|
28
29
|
export const EXIT_RUNTIME = 3
|
|
29
30
|
export const EXIT_DAEMON_UNREACHABLE = 4
|
|
31
|
+
export const EXIT_QUESTION = 10
|
|
30
32
|
export const EXIT_TIMEOUT = 124
|
package/src/cli/registry.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { tabClose } from './commands/tab/close'
|
|
|
5
5
|
import { tabCreate } from './commands/tab/create'
|
|
6
6
|
import { tabFocus } from './commands/tab/focus'
|
|
7
7
|
import { tabList } from './commands/tab/list'
|
|
8
|
+
import { tabRun } from './commands/tab/run'
|
|
8
9
|
import { tabSend } from './commands/tab/send'
|
|
9
10
|
import { tabSnapshot } from './commands/tab/snapshot'
|
|
10
11
|
import { tabTail } from './commands/tab/tail'
|
|
@@ -31,6 +32,7 @@ export const COMMANDS: readonly CliCommand[] = [
|
|
|
31
32
|
tabList,
|
|
32
33
|
tabCreate,
|
|
33
34
|
tabSend,
|
|
35
|
+
tabRun,
|
|
34
36
|
tabFocus,
|
|
35
37
|
tabClose,
|
|
36
38
|
tabSnapshot,
|
package/src/daemon/daemon.ts
CHANGED
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
} from '../ipc/protocol'
|
|
22
22
|
import { findSocketProcessPid, spawnDetachedTerminalManager } from '../platform/daemon-control'
|
|
23
23
|
import { type LoopTabView, runStatusDetectionLoop } from '../pty/assistant-status-detection-loop'
|
|
24
|
+
import { lastNonBlankLine } from '../pty/last-line'
|
|
24
25
|
import { createDefaultTerminalModes } from '../state/terminal-modes'
|
|
25
26
|
import { TerminalManagerClient } from '../terminal-manager/manager-client'
|
|
26
27
|
import {
|
|
@@ -108,6 +109,18 @@ export function mergeTabRegistryEntry(
|
|
|
108
109
|
return entry
|
|
109
110
|
}
|
|
110
111
|
|
|
112
|
+
/**
|
|
113
|
+
* Turn-complete settle window for the status loop, overridable via
|
|
114
|
+
* `AIMUX_TURN_SETTLE_MS` for slow/loaded machines. Falls back to the loop's
|
|
115
|
+
* own default when unset or non-numeric.
|
|
116
|
+
*/
|
|
117
|
+
function turnCompleteSettleMs(): number | undefined {
|
|
118
|
+
const raw = process.env.AIMUX_TURN_SETTLE_MS
|
|
119
|
+
if (raw == null || raw === '') return undefined
|
|
120
|
+
const parsed = Number(raw)
|
|
121
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined
|
|
122
|
+
}
|
|
123
|
+
|
|
111
124
|
function send(socket: Socket, message: ServerResponse | ServerEvent): void {
|
|
112
125
|
socket.write(encodeMessage(message))
|
|
113
126
|
}
|
|
@@ -376,6 +389,20 @@ export async function runDaemon(): Promise<void> {
|
|
|
376
389
|
logDebug('daemon.status.session', { sessionId, status })
|
|
377
390
|
broadcastAll({ payload: { sessionId, status }, type: 'sessionStatus' })
|
|
378
391
|
},
|
|
392
|
+
onTabQuestion: (tabId, sessionId, detail) => {
|
|
393
|
+
logDebug('daemon.status.question', { kind: detail.kind, sessionId, tabId })
|
|
394
|
+
// v13 / capability `questionEvents`. Same v13 send-time gate as below.
|
|
395
|
+
broadcastAllVersioned(13, {
|
|
396
|
+
payload: {
|
|
397
|
+
kind: detail.kind,
|
|
398
|
+
options: detail.options,
|
|
399
|
+
prompt: detail.prompt,
|
|
400
|
+
sessionId,
|
|
401
|
+
tabId,
|
|
402
|
+
},
|
|
403
|
+
type: 'tabQuestion',
|
|
404
|
+
})
|
|
405
|
+
},
|
|
379
406
|
onTabStatus: (tabId, status, sessionId) => {
|
|
380
407
|
logDebug('daemon.status.tab', { sessionId, status, tabId })
|
|
381
408
|
// Broadcast to every client. Clients silently ignore events for tabIds
|
|
@@ -385,6 +412,14 @@ export async function runDaemon(): Promise<void> {
|
|
|
385
412
|
// client tears down its socket to switch sessions.
|
|
386
413
|
broadcastAll({ payload: { sessionId, status, tabId }, type: 'tabStatus' })
|
|
387
414
|
},
|
|
415
|
+
onTurnComplete: (tabId, sessionId, idleMs) => {
|
|
416
|
+
logDebug('daemon.status.turnComplete', { idleMs, sessionId, tabId })
|
|
417
|
+
// v13 / capability `turnLifecycle`. Gate at send time — pre-v13 parsers
|
|
418
|
+
// throw on unknown event types and would drop the connection. MIN stays
|
|
419
|
+
// at 10, so we fan this only to peers that negotiated at least v13.
|
|
420
|
+
broadcastAllVersioned(13, { payload: { idleMs, sessionId, tabId }, type: 'tabTurnComplete' })
|
|
421
|
+
},
|
|
422
|
+
turnSettleMs: turnCompleteSettleMs(),
|
|
388
423
|
})
|
|
389
424
|
|
|
390
425
|
// Local HTTP server that receives Claude Code hook callbacks for every PTY
|
|
@@ -789,6 +824,12 @@ export async function runDaemon(): Promise<void> {
|
|
|
789
824
|
assistant: entry.assistant,
|
|
790
825
|
command: entry.command,
|
|
791
826
|
id: tabId,
|
|
827
|
+
// Additive v13 field (capability `listTabsLastLine`): the
|
|
828
|
+
// tab's last non-blank rendered line, so a fleet poll can
|
|
829
|
+
// read "what each worker is doing" without a per-tab
|
|
830
|
+
// snapshot. Undefined when the tab has no viewport yet, in
|
|
831
|
+
// which case the field is omitted from the JSON wire.
|
|
832
|
+
lastLine: lastNonBlankLine(entry.viewport),
|
|
792
833
|
status: entry.status ?? 'running',
|
|
793
834
|
title: entry.title ?? '',
|
|
794
835
|
worktreeId: entry.worktreeId,
|
|
@@ -111,7 +111,21 @@ export class SessionRegistry extends EventEmitter<SessionRegistryEvents> {
|
|
|
111
111
|
const orderedSnapshotTabs = snapshot.tabs
|
|
112
112
|
.map((persistedTab) => this.tabs.get(persistedTab.id))
|
|
113
113
|
.filter((tab): tab is TabSession => tab !== undefined)
|
|
114
|
-
|
|
114
|
+
// The registry — not the snapshot — is the source of truth for *which*
|
|
115
|
+
// tabs exist. A tab spawned by a sibling CLI after this workspace's
|
|
116
|
+
// snapshot was last persisted lives in `this.tabs` but is absent from
|
|
117
|
+
// `snapshot.tabs`; ordering by the snapshot alone would silently drop it
|
|
118
|
+
// from the attach result, so the UI would render an empty/stale workspace
|
|
119
|
+
// on switch. Append any live tab the snapshot doesn't mention (in
|
|
120
|
+
// registry order) so membership stays authoritative while the snapshot
|
|
121
|
+
// still supplies ordering + layout for the tabs it captured.
|
|
122
|
+
const snapshotIds = new Set(snapshot.tabs.map((persistedTab) => persistedTab.id))
|
|
123
|
+
const extraLiveTabs = tabs.filter((tab) => !snapshotIds.has(tab.id))
|
|
124
|
+
const normalizedTabs = normalizeGroupedTabOrder(
|
|
125
|
+
[...orderedSnapshotTabs, ...extraLiveTabs],
|
|
126
|
+
layoutTrees,
|
|
127
|
+
tabGroupMap
|
|
128
|
+
)
|
|
115
129
|
|
|
116
130
|
return { activeTabId: this.activeTabId, tabs: normalizedTabs }
|
|
117
131
|
}
|
package/src/ipc/protocol.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
AssistantId,
|
|
3
|
+
QuestionKind,
|
|
3
4
|
SessionStatus,
|
|
4
5
|
TabActivity,
|
|
5
6
|
TabSession,
|
|
@@ -29,8 +30,15 @@ import { isWorkspaceSnapshotV1, isWorktreeRecord } from '../state/validation'
|
|
|
29
30
|
// `switchWorkspace`, `closeWorkspace`, `announceWorkspaceSwitched`) and
|
|
30
31
|
// worktree record requests (`addWorktreeRecord`, `removeWorktreeRecord`),
|
|
31
32
|
// plus matching broadcast events. All capability-gated; MIN stays at 10.
|
|
33
|
+
//
|
|
34
|
+
// v13: additive — agent-orchestration signals. Two new broadcast events,
|
|
35
|
+
// `tabTurnComplete` (a tab's `idle` held long enough to call the turn done)
|
|
36
|
+
// and `tabQuestion` (a tab entered `waiting-input`; carries the prompt text
|
|
37
|
+
// plus best-effort parsed options), and an additive `lastLine` field on
|
|
38
|
+
// `TabSessionSummary`. Gated behind `turnLifecycle`, `questionEvents`, and
|
|
39
|
+
// `listTabsLastLine` respectively; MIN stays at 10.
|
|
32
40
|
export const IPC_PROTOCOL_MIN_VERSION = 10
|
|
33
|
-
export const IPC_PROTOCOL_VERSION =
|
|
41
|
+
export const IPC_PROTOCOL_VERSION = 13
|
|
34
42
|
|
|
35
43
|
/**
|
|
36
44
|
* Capability advertised by a daemon that knows how to drain + handoff its
|
|
@@ -104,6 +112,31 @@ export const IPC_CAPABILITY_WORKTREE_LIFECYCLE_EVENTS = 'worktreeLifecycleEvents
|
|
|
104
112
|
*/
|
|
105
113
|
export const IPC_CAPABILITY_TAB_TAIL = 'tabTail'
|
|
106
114
|
|
|
115
|
+
/**
|
|
116
|
+
* v13 — capability gating the `tabTurnComplete` event. When advertised, the
|
|
117
|
+
* daemon broadcasts an authoritative end-of-turn signal once a tab's `idle`
|
|
118
|
+
* activity has held continuously for the settle window, so a driver need not
|
|
119
|
+
* poll `tabStatus` and re-confirm that idle held. Pre-cap peers never see the
|
|
120
|
+
* event and fall back to settle-polling `tabStatus`.
|
|
121
|
+
*/
|
|
122
|
+
export const IPC_CAPABILITY_TURN_LIFECYCLE = 'turnLifecycle'
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* v13 — capability gating the `tabQuestion` event. When advertised, the daemon
|
|
126
|
+
* broadcasts the captured prompt text (plus best-effort parsed options) when a
|
|
127
|
+
* tab transitions into `waiting-input`, so a driver need not re-`snapshot` the
|
|
128
|
+
* screen and substring-match to learn what the worker is asking.
|
|
129
|
+
*/
|
|
130
|
+
export const IPC_CAPABILITY_QUESTION_EVENTS = 'questionEvents'
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* v13 — capability gating the additive `lastLine` field on `listTabs`
|
|
134
|
+
* summaries. When advertised, each summary carries the tab's last non-blank
|
|
135
|
+
* rendered line so a fleet poll can read "what each worker is doing" without a
|
|
136
|
+
* `snapshot` round-trip per tab. Pre-cap daemons omit the field.
|
|
137
|
+
*/
|
|
138
|
+
export const IPC_CAPABILITY_LIST_TABS_LAST_LINE = 'listTabsLastLine'
|
|
139
|
+
|
|
107
140
|
/**
|
|
108
141
|
* Capabilities advertised by *this* process in its `helloResult`. Additive
|
|
109
142
|
* features should be introduced as new capability strings here rather than
|
|
@@ -124,6 +157,9 @@ export const IPC_PROTOCOL_CAPABILITIES: readonly string[] = [
|
|
|
124
157
|
IPC_CAPABILITY_WORKSPACE_LIFECYCLE,
|
|
125
158
|
IPC_CAPABILITY_WORKTREE_LIFECYCLE_EVENTS,
|
|
126
159
|
IPC_CAPABILITY_TAB_TAIL,
|
|
160
|
+
IPC_CAPABILITY_TURN_LIFECYCLE,
|
|
161
|
+
IPC_CAPABILITY_QUESTION_EVENTS,
|
|
162
|
+
IPC_CAPABILITY_LIST_TABS_LAST_LINE,
|
|
127
163
|
]
|
|
128
164
|
|
|
129
165
|
export interface ProtocolHelloRequest {
|
|
@@ -184,6 +220,12 @@ export interface TabSessionSummary {
|
|
|
184
220
|
activity?: TabActivity
|
|
185
221
|
command: string
|
|
186
222
|
worktreeId?: string
|
|
223
|
+
/**
|
|
224
|
+
* v13 / capability `listTabsLastLine`. The tab's last non-blank rendered
|
|
225
|
+
* line, trimmed. Present only when the daemon advertises the capability;
|
|
226
|
+
* omitted when the tab has produced no viewport yet.
|
|
227
|
+
*/
|
|
228
|
+
lastLine?: string
|
|
187
229
|
}
|
|
188
230
|
|
|
189
231
|
export interface ListTabsResult {
|
|
@@ -324,6 +366,26 @@ export type ServerEvent =
|
|
|
324
366
|
| { type: 'tabExit'; payload: { tabId: string; exitCode: number } }
|
|
325
367
|
| { type: 'tabError'; payload: { tabId: string; message: string } }
|
|
326
368
|
| { type: 'tabStatus'; payload: { sessionId: string; tabId: string; status: TabActivity } }
|
|
369
|
+
// v13 / capability `turnLifecycle`. Authoritative end-of-turn: broadcast
|
|
370
|
+
// once a tab's `idle` activity has held continuously for the settle window.
|
|
371
|
+
// Edge-triggered — re-armed only after the tab leaves `idle` again — so a
|
|
372
|
+
// driver gets exactly one per turn. `idleMs` is how long idle had held when
|
|
373
|
+
// the event fired.
|
|
374
|
+
| { type: 'tabTurnComplete'; payload: { sessionId: string; tabId: string; idleMs: number } }
|
|
375
|
+
// v13 / capability `questionEvents`. Broadcast when a tab transitions into
|
|
376
|
+
// `waiting-input`. `prompt` is the captured tail text (authoritative);
|
|
377
|
+
// `options` is a best-effort per-CLI parse of the choice list and may be
|
|
378
|
+
// absent even when the prompt clearly offers choices.
|
|
379
|
+
| {
|
|
380
|
+
type: 'tabQuestion'
|
|
381
|
+
payload: {
|
|
382
|
+
sessionId: string
|
|
383
|
+
tabId: string
|
|
384
|
+
kind: QuestionKind
|
|
385
|
+
prompt: string
|
|
386
|
+
options?: string[]
|
|
387
|
+
}
|
|
388
|
+
}
|
|
327
389
|
| { type: 'sessionStatus'; payload: { sessionId: string; status: SessionStatus } }
|
|
328
390
|
// Capability-gated on `tabLifecycleEvents`. Broadcast after a successful
|
|
329
391
|
// `createTab` so every UI/CLI client attached to the same session learns
|
|
@@ -510,10 +572,15 @@ function isTabSessionSummary(value: unknown): value is TabSessionSummary {
|
|
|
510
572
|
value.activity === 'waiting-input' ||
|
|
511
573
|
value.activity === 'idle') &&
|
|
512
574
|
isString(value.command) &&
|
|
513
|
-
(value.worktreeId === undefined || isString(value.worktreeId))
|
|
575
|
+
(value.worktreeId === undefined || isString(value.worktreeId)) &&
|
|
576
|
+
(value.lastLine === undefined || isString(value.lastLine))
|
|
514
577
|
)
|
|
515
578
|
}
|
|
516
579
|
|
|
580
|
+
function isQuestionKind(value: unknown): value is QuestionKind {
|
|
581
|
+
return value === 'question' || value === 'permission'
|
|
582
|
+
}
|
|
583
|
+
|
|
517
584
|
function isListTabsResult(value: unknown): value is ListTabsResult {
|
|
518
585
|
return (
|
|
519
586
|
isObjectRecord(value) &&
|
|
@@ -786,6 +853,21 @@ export function parseServerMessage(value: unknown): ServerResponse | ServerEvent
|
|
|
786
853
|
assert(isString(value.payload.tabId), 'tabStatus.tabId must be a string')
|
|
787
854
|
assert(isTabActivity(value.payload.status), 'tabStatus.status is invalid')
|
|
788
855
|
return value as ServerEvent
|
|
856
|
+
case 'tabTurnComplete':
|
|
857
|
+
assert(isString(value.payload.sessionId), 'tabTurnComplete.sessionId must be a string')
|
|
858
|
+
assert(isString(value.payload.tabId), 'tabTurnComplete.tabId must be a string')
|
|
859
|
+
assert(isFiniteNumber(value.payload.idleMs), 'tabTurnComplete.idleMs must be a number')
|
|
860
|
+
return value as ServerEvent
|
|
861
|
+
case 'tabQuestion':
|
|
862
|
+
assert(isString(value.payload.sessionId), 'tabQuestion.sessionId must be a string')
|
|
863
|
+
assert(isString(value.payload.tabId), 'tabQuestion.tabId must be a string')
|
|
864
|
+
assert(isQuestionKind(value.payload.kind), 'tabQuestion.kind is invalid')
|
|
865
|
+
assert(isString(value.payload.prompt), 'tabQuestion.prompt must be a string')
|
|
866
|
+
assert(
|
|
867
|
+
value.payload.options === undefined || isStringArray(value.payload.options),
|
|
868
|
+
'tabQuestion.options must be a string array when present'
|
|
869
|
+
)
|
|
870
|
+
return value as ServerEvent
|
|
789
871
|
case 'tabAdded':
|
|
790
872
|
assert(isString(value.payload.sessionId), 'tabAdded.sessionId must be a string')
|
|
791
873
|
assert(isTabSession(value.payload.tab), 'tabAdded.tab is invalid')
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Question / permission extraction.
|
|
3
|
+
*
|
|
4
|
+
* When a tab transitions into `waiting-input`, the status detection loop calls
|
|
5
|
+
* this to turn "the worker is blocked" into a structured event: what it's
|
|
6
|
+
* asking (the captured prompt text — authoritative) plus a best-effort parse
|
|
7
|
+
* of the choice list. It reuses the detector's tail extraction so both read
|
|
8
|
+
* the screen identically.
|
|
9
|
+
*
|
|
10
|
+
* Option parsing is explicitly best-effort and per-CLI: TUIs render menus in
|
|
11
|
+
* shapes that shift between versions. `prompt` is always populated; `options`
|
|
12
|
+
* may be absent even when the screen clearly offers choices. Consumers should
|
|
13
|
+
* treat `prompt` as the source of truth and `options` as a convenience.
|
|
14
|
+
*/
|
|
15
|
+
import type { AssistantId, QuestionKind, TerminalSnapshot } from '../state/types'
|
|
16
|
+
|
|
17
|
+
import { extractTailLines } from './assistant-status-detector'
|
|
18
|
+
|
|
19
|
+
/** How many trailing non-blank lines to capture as the prompt text. Wider than
|
|
20
|
+
* the 10-line classification tail so a multi-line permission block or a long
|
|
21
|
+
* question is captured whole. */
|
|
22
|
+
const PROMPT_TAIL_LINES = 20
|
|
23
|
+
|
|
24
|
+
export interface QuestionDetail {
|
|
25
|
+
kind: QuestionKind
|
|
26
|
+
/** The captured waiting-input tail, trailing-trimmed, joined with newlines. */
|
|
27
|
+
prompt: string
|
|
28
|
+
/** Best-effort parsed choice list; omitted when none could be recognised. */
|
|
29
|
+
options?: string[]
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Substrings that mark a blocked prompt as a permission / approval request
|
|
34
|
+
* rather than a free-form question. Lower-cased haystack match. Kept broad and
|
|
35
|
+
* shared across CLIs; per-CLI extras are folded in below.
|
|
36
|
+
*/
|
|
37
|
+
const PERMISSION_SIGNALS: readonly string[] = [
|
|
38
|
+
'do you want',
|
|
39
|
+
'permission required',
|
|
40
|
+
'permission to',
|
|
41
|
+
'△ permission',
|
|
42
|
+
'allow this',
|
|
43
|
+
'approve',
|
|
44
|
+
'grant',
|
|
45
|
+
'press enter to confirm',
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Extract the structured question for a tab already classified as
|
|
50
|
+
* `waiting-input`. Returns null only when there's no viewport / no text to
|
|
51
|
+
* report; otherwise `prompt` is always present.
|
|
52
|
+
*/
|
|
53
|
+
export function extractQuestion(
|
|
54
|
+
assistant: AssistantId,
|
|
55
|
+
viewport: TerminalSnapshot | undefined
|
|
56
|
+
): QuestionDetail | null {
|
|
57
|
+
if (!viewport) return null
|
|
58
|
+
const lines = extractTailLines(viewport, PROMPT_TAIL_LINES)
|
|
59
|
+
if (lines.length === 0) return null
|
|
60
|
+
|
|
61
|
+
const prompt = lines.join('\n')
|
|
62
|
+
const haystack = prompt.toLowerCase()
|
|
63
|
+
const kind = detectKind(assistant, haystack)
|
|
64
|
+
const options = parseOptions(lines, haystack)
|
|
65
|
+
return options ? { kind, options, prompt } : { kind, prompt }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function detectKind(assistant: AssistantId, haystack: string): QuestionKind {
|
|
69
|
+
for (const signal of PERMISSION_SIGNALS) {
|
|
70
|
+
if (haystack.includes(signal)) return 'permission'
|
|
71
|
+
}
|
|
72
|
+
// opencode surfaces tool approvals under a "permission" banner; codex uses an
|
|
73
|
+
// approval confirm. Both already covered by the shared signals, but keep the
|
|
74
|
+
// assistant param so future per-CLI divergence has a seam.
|
|
75
|
+
void assistant
|
|
76
|
+
return 'question'
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Matches a numbered menu row: an optional selection marker (❯ › > *), a digit,
|
|
81
|
+
* a `.`/`)` separator, then the option label. Capturing the label lets us strip
|
|
82
|
+
* the marker/number so consumers get clean text.
|
|
83
|
+
*/
|
|
84
|
+
const NUMBERED_OPTION = /^\s*[❯›>*]?\s*\d+[.)]\s+(\S.*)$/u
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Matches an arrow-selected label with no number, e.g. Claude's `❯ Yes` /
|
|
88
|
+
* ` No` yes-no menus.
|
|
89
|
+
*/
|
|
90
|
+
const MARKED_OPTION = /^\s*[❯›]\s+(\S.*)$/u
|
|
91
|
+
|
|
92
|
+
function parseOptions(lines: readonly string[], haystack: string): string[] | undefined {
|
|
93
|
+
const numbered: string[] = []
|
|
94
|
+
for (const line of lines) {
|
|
95
|
+
const captured = NUMBERED_OPTION.exec(line)?.[1]
|
|
96
|
+
if (captured != null && captured !== '') numbered.push(captured.trimEnd())
|
|
97
|
+
}
|
|
98
|
+
if (numbered.length >= 2) return numbered
|
|
99
|
+
|
|
100
|
+
// No numbered menu — look for a single arrow-marked choice paired with its
|
|
101
|
+
// siblings is unreliable, so fall back to explicit yes/no affordances.
|
|
102
|
+
if (
|
|
103
|
+
haystack.includes('[y/n]') ||
|
|
104
|
+
haystack.includes('(y/n)') ||
|
|
105
|
+
haystack.includes('yes/no') ||
|
|
106
|
+
haystack.includes('y/n?')
|
|
107
|
+
) {
|
|
108
|
+
return ['Yes', 'No']
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const marked = lines.map((line) => MARKED_OPTION.exec(line)?.[1]?.trimEnd()).filter(isNonEmpty)
|
|
112
|
+
if (marked.length >= 1 && numbered.length === 0) {
|
|
113
|
+
// A lone highlighted option (e.g. a confirm dialog defaulting to Yes) — only
|
|
114
|
+
// surface it when it's a short label, not a highlighted sentence.
|
|
115
|
+
const short = marked.filter((label) => label.length <= 40)
|
|
116
|
+
if (short.length >= 1) return short
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return undefined
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function isNonEmpty(value: string | undefined): value is string {
|
|
123
|
+
return value !== undefined && value.length > 0
|
|
124
|
+
}
|
|
@@ -17,6 +17,7 @@ import type { AssistantId, SessionStatus, TabActivity, TerminalSnapshot } from '
|
|
|
17
17
|
|
|
18
18
|
import { logDebug } from '../debug/input-log'
|
|
19
19
|
import { getLineText } from '../input/terminal-text-extraction'
|
|
20
|
+
import { extractQuestion } from './assistant-question-extractor'
|
|
20
21
|
import { AssistantStatusArbiter, type RecordHookEventInput } from './assistant-status-arbiter'
|
|
21
22
|
import { AssistantStatusDetector } from './assistant-status-detector'
|
|
22
23
|
|
|
@@ -35,6 +36,15 @@ function tailPreview(viewport: TerminalSnapshot | undefined): string {
|
|
|
35
36
|
/** Default polling interval. Cheap — detector is a handful of substring checks. */
|
|
36
37
|
const DEFAULT_TICK_MS = 500
|
|
37
38
|
|
|
39
|
+
/**
|
|
40
|
+
* How long a tab's `idle` activity must hold continuously before we call the
|
|
41
|
+
* turn complete. `idle` can flash for a fraction of a second between two tool
|
|
42
|
+
* calls, so an end-of-turn signal that fired on the first idle tick would catch
|
|
43
|
+
* the worker mid-turn. Requiring idle to *hold* this long is the authoritative
|
|
44
|
+
* replacement for a driver's settle-poll loop.
|
|
45
|
+
*/
|
|
46
|
+
const DEFAULT_TURN_SETTLE_MS = 1500
|
|
47
|
+
|
|
38
48
|
export interface LoopTabView {
|
|
39
49
|
id: string
|
|
40
50
|
assistant: AssistantId
|
|
@@ -49,7 +59,30 @@ export interface StatusDetectionLoopOptions {
|
|
|
49
59
|
onTabStatus: (tabId: string, status: TabActivity, sessionId: string) => void
|
|
50
60
|
/** Emitted when either flag on a session changes. */
|
|
51
61
|
onSessionStatus: (sessionId: string, status: SessionStatus) => void
|
|
62
|
+
/**
|
|
63
|
+
* Emitted once per turn, when a tab's `idle` activity has held continuously
|
|
64
|
+
* for `turnSettleMs`. Edge-triggered: re-armed only after the tab leaves
|
|
65
|
+
* `idle`, so a driver receives exactly one signal per turn. `idleMs` is how
|
|
66
|
+
* long idle had held when the signal fired.
|
|
67
|
+
*/
|
|
68
|
+
onTurnComplete?: (tabId: string, sessionId: string, idleMs: number) => void
|
|
69
|
+
/**
|
|
70
|
+
* Emitted when a tab transitions into `waiting-input`. Edge-triggered: fires
|
|
71
|
+
* once per transition, carrying the captured prompt text and any parsed
|
|
72
|
+
* options. Fires on both tick and attach replay so a client that attaches to
|
|
73
|
+
* an already-blocked tab still learns the question.
|
|
74
|
+
*/
|
|
75
|
+
onTabQuestion?: (
|
|
76
|
+
tabId: string,
|
|
77
|
+
sessionId: string,
|
|
78
|
+
detail: { kind: 'question' | 'permission'; prompt: string; options?: string[] }
|
|
79
|
+
) => void
|
|
52
80
|
tickMs?: number
|
|
81
|
+
/** Override the turn-complete settle window (default 1500ms). */
|
|
82
|
+
turnSettleMs?: number
|
|
83
|
+
/** Override the clock. Defaults to Date.now. Tests inject a logical clock so
|
|
84
|
+
* the wall-clock-driven turn-complete settle is deterministic. */
|
|
85
|
+
nowFn?: () => number
|
|
53
86
|
}
|
|
54
87
|
|
|
55
88
|
export interface StatusDetectionLoopHandle {
|
|
@@ -80,10 +113,18 @@ export function runStatusDetectionLoop(
|
|
|
80
113
|
options: StatusDetectionLoopOptions
|
|
81
114
|
): StatusDetectionLoopHandle {
|
|
82
115
|
const tickMs = options.tickMs ?? DEFAULT_TICK_MS
|
|
116
|
+
const turnSettleMs = options.turnSettleMs ?? DEFAULT_TURN_SETTLE_MS
|
|
117
|
+
const now = options.nowFn ?? Date.now
|
|
83
118
|
const detector = new AssistantStatusDetector()
|
|
84
119
|
const arbiter = new AssistantStatusArbiter()
|
|
85
120
|
const lastTabStatus = new Map<string, { status: TabActivity; sessionId: string }>()
|
|
86
121
|
const lastSessionStatus = new Map<string, SessionStatus>()
|
|
122
|
+
// Timestamp when a tab most recently entered `idle`. Cleared when it leaves
|
|
123
|
+
// idle. `turnEmitted` guards against re-firing `onTurnComplete` within the
|
|
124
|
+
// same idle episode; it's cleared alongside `idleSince` so the next turn
|
|
125
|
+
// re-arms.
|
|
126
|
+
const idleSince = new Map<string, number>()
|
|
127
|
+
const turnEmitted = new Set<string>()
|
|
87
128
|
|
|
88
129
|
const timer = setInterval(() => {
|
|
89
130
|
try {
|
|
@@ -134,6 +175,38 @@ export function runStatusDetectionLoop(
|
|
|
134
175
|
lastTabStatus.set(tab.id, { sessionId, status })
|
|
135
176
|
options.onTabStatus(tab.id, status, sessionId)
|
|
136
177
|
}
|
|
178
|
+
|
|
179
|
+
// Turn-complete bookkeeping. The emission itself is gated to `tick` so a
|
|
180
|
+
// synchronous attach replay (`classifyNow`) never fabricates an
|
|
181
|
+
// end-of-turn — only the wall-clock-driven poll does. The idleSince /
|
|
182
|
+
// turnEmitted maps are maintained on every call so state stays coherent
|
|
183
|
+
// regardless of source.
|
|
184
|
+
if (status === 'idle') {
|
|
185
|
+
let since = idleSince.get(tab.id)
|
|
186
|
+
if (since === undefined) {
|
|
187
|
+
since = now
|
|
188
|
+
idleSince.set(tab.id, since)
|
|
189
|
+
}
|
|
190
|
+
if (source === 'tick' && !turnEmitted.has(tab.id) && now - since >= turnSettleMs) {
|
|
191
|
+
turnEmitted.add(tab.id)
|
|
192
|
+
options.onTurnComplete?.(tab.id, sessionId, now - since)
|
|
193
|
+
}
|
|
194
|
+
} else {
|
|
195
|
+
idleSince.delete(tab.id)
|
|
196
|
+
turnEmitted.delete(tab.id)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Question extraction on the idle/working → waiting-input edge. `prev`
|
|
200
|
+
// still holds the pre-update status, so this fires exactly once per
|
|
201
|
+
// transition even though the loop broadcasts to every client.
|
|
202
|
+
if (
|
|
203
|
+
status === 'waiting-input' &&
|
|
204
|
+
(!prev || prev.status !== 'waiting-input') &&
|
|
205
|
+
options.onTabQuestion
|
|
206
|
+
) {
|
|
207
|
+
const detail = extractQuestion(tab.assistant, tab.viewport)
|
|
208
|
+
if (detail) options.onTabQuestion(tab.id, sessionId, detail)
|
|
209
|
+
}
|
|
137
210
|
}
|
|
138
211
|
const next: SessionStatus = { waiting, working }
|
|
139
212
|
const prevSession = lastSessionStatus.get(sessionId)
|
|
@@ -154,14 +227,14 @@ export function runStatusDetectionLoop(
|
|
|
154
227
|
}
|
|
155
228
|
|
|
156
229
|
function tick(): void {
|
|
157
|
-
const
|
|
230
|
+
const ts = now()
|
|
158
231
|
const sessionIds = options.listSessions()
|
|
159
232
|
const seenSessions = new Set<string>()
|
|
160
233
|
const seenTabs = new Set<string>()
|
|
161
234
|
|
|
162
235
|
for (const sessionId of sessionIds) {
|
|
163
236
|
seenSessions.add(sessionId)
|
|
164
|
-
classifySession(sessionId, options.listTabs(sessionId),
|
|
237
|
+
classifySession(sessionId, options.listTabs(sessionId), ts, 'tick', seenTabs)
|
|
165
238
|
}
|
|
166
239
|
|
|
167
240
|
for (const tabId of lastTabStatus.keys()) {
|
|
@@ -169,6 +242,8 @@ export function runStatusDetectionLoop(
|
|
|
169
242
|
detector.forget(tabId)
|
|
170
243
|
arbiter.forget(tabId)
|
|
171
244
|
lastTabStatus.delete(tabId)
|
|
245
|
+
idleSince.delete(tabId)
|
|
246
|
+
turnEmitted.delete(tabId)
|
|
172
247
|
}
|
|
173
248
|
}
|
|
174
249
|
for (const sessionId of lastSessionStatus.keys()) {
|
|
@@ -180,7 +255,7 @@ export function runStatusDetectionLoop(
|
|
|
180
255
|
|
|
181
256
|
return {
|
|
182
257
|
classifyNow: (sessionId, tabs) => {
|
|
183
|
-
classifySession(sessionId, tabs,
|
|
258
|
+
classifySession(sessionId, tabs, now(), 'classifyNow')
|
|
184
259
|
},
|
|
185
260
|
getSessionStatus: (sessionId) => lastSessionStatus.get(sessionId),
|
|
186
261
|
getTabStatus: (tabId) => lastTabStatus.get(tabId)?.status,
|
|
@@ -206,6 +281,8 @@ export function runStatusDetectionLoop(
|
|
|
206
281
|
arbiter.clear()
|
|
207
282
|
lastTabStatus.clear()
|
|
208
283
|
lastSessionStatus.clear()
|
|
284
|
+
idleSince.clear()
|
|
285
|
+
turnEmitted.clear()
|
|
209
286
|
},
|
|
210
287
|
}
|
|
211
288
|
}
|
|
@@ -85,7 +85,14 @@ export class AssistantStatusDetector {
|
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
-
|
|
88
|
+
/**
|
|
89
|
+
* Last `lineCount` non-blank rendered lines, trailing-trimmed, oldest-first.
|
|
90
|
+
* Shared by the status detector (10-line tail for classification) and the
|
|
91
|
+
* question extractor (larger tail for prompt capture) so both read the screen
|
|
92
|
+
* the same way. Prefers `tailLines` when the user has scrolled the viewport
|
|
93
|
+
* off the active screen.
|
|
94
|
+
*/
|
|
95
|
+
export function extractTailLines(viewport: TerminalSnapshot, lineCount: number): string[] {
|
|
89
96
|
const isScrolledToBottom = viewport.viewportY === viewport.baseY
|
|
90
97
|
const lines = isScrolledToBottom ? viewport.lines : (viewport.tailLines ?? viewport.lines)
|
|
91
98
|
// Full-screen TUIs (claude, opencode) paint in the alternate buffer and
|
|
@@ -112,7 +119,11 @@ function extractTailText(viewport: TerminalSnapshot, lineCount: number): string
|
|
|
112
119
|
if (!line) continue
|
|
113
120
|
parts.push(getLineText(line).replace(/\s+$/u, ''))
|
|
114
121
|
}
|
|
115
|
-
return parts
|
|
122
|
+
return parts
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function extractTailText(viewport: TerminalSnapshot, lineCount: number): string {
|
|
126
|
+
return extractTailLines(viewport, lineCount).join('\n')
|
|
116
127
|
}
|
|
117
128
|
|
|
118
129
|
function classifyBuiltin(
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extract a terminal viewport's last non-blank rendered line.
|
|
3
|
+
*
|
|
4
|
+
* Used by the daemon's `listTabs` handler to answer "what is this worker
|
|
5
|
+
* doing?" without a per-tab `snapshot` round-trip. Unlike the status loop's
|
|
6
|
+
* private `tailPreview`, this does NOT cap the width — the orchestrator wants
|
|
7
|
+
* the whole status line — and it returns `undefined` (rather than a sentinel)
|
|
8
|
+
* when there is nothing to show, so the field is simply omitted from the wire.
|
|
9
|
+
*/
|
|
10
|
+
import type { TerminalSnapshot } from '../state/types'
|
|
11
|
+
|
|
12
|
+
import { getLineText } from '../input/terminal-text-extraction'
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The last non-blank line of `viewport`, trimmed. Scans rows from the bottom so
|
|
16
|
+
* trailing blank rows are skipped. Returns `undefined` when the viewport is
|
|
17
|
+
* missing or entirely blank.
|
|
18
|
+
*/
|
|
19
|
+
export function lastNonBlankLine(viewport: TerminalSnapshot | undefined): string | undefined {
|
|
20
|
+
if (!viewport) return undefined
|
|
21
|
+
const lines = viewport.lines
|
|
22
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
23
|
+
const line = lines[i]
|
|
24
|
+
if (!line) continue
|
|
25
|
+
const text = getLineText(line).trim()
|
|
26
|
+
if (text.length > 0) return text
|
|
27
|
+
}
|
|
28
|
+
return undefined
|
|
29
|
+
}
|
|
@@ -192,6 +192,11 @@ export class RemoteSessionBackend
|
|
|
192
192
|
})
|
|
193
193
|
this.emit('tabActivity', message.payload.tabId, message.payload.status)
|
|
194
194
|
break
|
|
195
|
+
case 'tabTurnComplete':
|
|
196
|
+
case 'tabQuestion':
|
|
197
|
+
// v13 orchestration signals — consumed by the headless CLI, not the UI
|
|
198
|
+
// backend. Enumerated so the switch stays exhaustive; no UI wiring yet.
|
|
199
|
+
break
|
|
195
200
|
case 'sessionStatus':
|
|
196
201
|
logDebug('backend.remote.sessionStatus', {
|
|
197
202
|
sessionId: message.payload.sessionId,
|
package/src/state/types.ts
CHANGED
|
@@ -18,6 +18,14 @@ export type LegacyPersistedTabStatus = TabStatus | 'exited'
|
|
|
18
18
|
|
|
19
19
|
export type TabActivity = 'working' | 'waiting-input' | 'idle'
|
|
20
20
|
|
|
21
|
+
/**
|
|
22
|
+
* Classifies why a tab is blocked on user input. `permission` is a tool /
|
|
23
|
+
* command approval prompt; `question` is any other prompt the assistant is
|
|
24
|
+
* waiting on. Carried by the `tabQuestion` server event so an orchestrator can
|
|
25
|
+
* branch without re-scraping the screen.
|
|
26
|
+
*/
|
|
27
|
+
export type QuestionKind = 'question' | 'permission'
|
|
28
|
+
|
|
21
29
|
/**
|
|
22
30
|
* Per-session status flags. Both can be true at once (e.g. one tab working,
|
|
23
31
|
* another waiting for user input) so we keep them as independent booleans
|