typeclaw 0.26.0 → 0.27.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.
@@ -16,8 +16,26 @@ export { replayJsonl } from './replay'
16
16
  export { streamLive } from './live'
17
17
  export { parseDuration, parseFilter } from './types'
18
18
  export type { InspectCategory, InspectEvent, InspectFilter } from './types'
19
- export { runInspectLoop } from './loop'
20
- export type { RunInspectLoopOptions } from './loop'
19
+ export { runInspectLoop, runViewerLoop } from './loop'
20
+ export type {
21
+ OpenItem,
22
+ OpenItemContext,
23
+ RunInspectLoopOptions,
24
+ RunViewerLoopOptions,
25
+ SelectItem,
26
+ TailController,
27
+ } from './loop'
28
+ export type { ViewerItem } from './item'
29
+ export { isWritable, itemKey } from './item'
30
+ export { listViewerItems } from './item-list'
31
+ export type { ListViewerItemsOptions, ViewerList } from './item-list'
32
+ export { openViewerItem } from './open-item'
33
+ export type { OpenViewerDeps } from './open-item'
34
+ export { runTuiViewer } from './tui-item'
35
+ export type { RunTuiViewerOptions } from './tui-item'
36
+ export { streamLogs } from './logs-item'
37
+ export { createTranscriptView } from './transcript-view'
38
+ export type { TranscriptViewOptions, TranscriptViewOutcome } from './transcript-view'
21
39
 
22
40
  export type RunInspectOptions = {
23
41
  agentDir: string
@@ -51,7 +69,7 @@ export type LiveSourceFactory = (opts: {
51
69
  }) => AsyncIterable<InspectEvent>
52
70
 
53
71
  export type RunInspectResult =
54
- | { ok: true; exitCode: 0; escToPicker?: boolean }
72
+ | { ok: true; exitCode: number; escToPicker?: boolean }
55
73
  | { ok: false; exitCode: number; reason: string }
56
74
 
57
75
  export type InspectTarget = {
@@ -164,51 +182,58 @@ async function chooseSession(
164
182
  return { ok: true, summary: picked }
165
183
  }
166
184
 
167
- async function streamSession(opts: {
185
+ // Lifecycle phases surfaced to a consumer so renderers can react (e.g. batch a
186
+ // pi-tui render at replay-end, announce a live divider). `sessionLive` on
187
+ // 'live-start' is the registry hit/miss from the live source's onSubscribed.
188
+ export type StreamPhase =
189
+ | { phase: 'replay-end' }
190
+ | { phase: 'replay-only-idle' }
191
+ | { phase: 'live-start'; sessionLive: boolean }
192
+ | { phase: 'end' }
193
+
194
+ export type StreamSessionEventsOptions = {
168
195
  summary: SessionSummary
169
196
  filter: InspectFilter
170
197
  sinceMs: number | undefined
171
- json: boolean
172
- color: boolean
173
- stdout: (line: string) => void
174
- stderr: (line: string) => void
198
+ onEvent: (event: InspectEvent) => void
199
+ onPhase?: (phase: StreamPhase) => void
200
+ onWarn?: (msg: string) => void
175
201
  liveSource?: LiveSourceFactory
176
202
  signal?: AbortSignal
177
- liveHint?: string
178
- interactive?: boolean
179
- }): Promise<{ escToPicker: boolean }> {
180
- if (!opts.json) writeHeader(opts.summary, opts.color, opts.stdout)
181
- const emit = (event: InspectEvent): void => {
203
+ // When true and replay-only with a signal, block until aborted instead of
204
+ // returning immediately — a stable interactive viewer that esc/q dismisses.
205
+ blockWhenReplayOnly?: boolean
206
+ }
207
+
208
+ // The read path shared by the line renderer and the pi-tui transcript view:
209
+ // replay the JSONL transcript, then optionally live-tail, applying since/filter
210
+ // and honoring signal.aborted (-> escToPicker). Knows nothing about rendering —
211
+ // it just delivers ordered, filtered InspectEvents to onEvent and announces
212
+ // phase transitions via onPhase.
213
+ export async function streamSessionEvents(opts: StreamSessionEventsOptions): Promise<{ escToPicker: boolean }> {
214
+ const aborted = (): boolean => opts.signal?.aborted === true
215
+ const deliver = (event: InspectEvent): void => {
182
216
  if (opts.sinceMs !== undefined && event.ts > 0 && event.ts < opts.sinceMs) return
183
217
  if (!matchesFilter(event, opts.filter)) return
184
- if (opts.json) {
185
- opts.stdout(JSON.stringify({ sessionId: opts.summary.sessionId, ...event }))
186
- } else {
187
- opts.stdout(renderEvent(event, { color: opts.color }))
188
- }
218
+ opts.onEvent(event)
189
219
  }
190
220
 
191
- const aborted = (): boolean => opts.signal?.aborted === true
192
-
193
- for await (const event of replayJsonl(opts.summary.sessionFile, { onWarn: opts.stderr })) {
221
+ for await (const event of replayJsonl(
222
+ opts.summary.sessionFile,
223
+ opts.onWarn !== undefined ? { onWarn: opts.onWarn } : {},
224
+ )) {
194
225
  if (aborted()) return { escToPicker: true }
195
- emit(event)
226
+ deliver(event)
196
227
  }
228
+ opts.onPhase?.({ phase: 'replay-end' })
197
229
 
198
230
  if (opts.liveSource === undefined) {
199
- if (!opts.json) opts.stdout('─── end of transcript ───')
200
- // Already aborted during replay (user pressed esc/q): honor it, don't lose the keystroke.
201
231
  if (aborted()) return { escToPicker: true }
202
- // Interactive replay-only: hold a stable viewer like `dreams` instead of
203
- // bouncing straight back to the picker. Block until the tail scope aborts
204
- // (esc → back, q/ctrl-c → exit). Never block without a signal (non-TTY has
205
- // no listener and would hang) or in json/non-interactive mode (scriptability).
206
- if (opts.interactive === true && !opts.json && opts.signal !== undefined) {
207
- if (opts.liveHint !== undefined && opts.liveHint !== '') {
208
- opts.stdout(divider(opts.color, opts.liveHint))
209
- }
232
+ if (opts.blockWhenReplayOnly === true && opts.signal !== undefined) {
233
+ opts.onPhase?.({ phase: 'replay-only-idle' })
210
234
  await waitForAbort(opts.signal)
211
235
  }
236
+ opts.onPhase?.({ phase: 'end' })
212
237
  return { escToPicker: aborted() }
213
238
  }
214
239
 
@@ -227,24 +252,85 @@ async function streamSession(opts: {
227
252
  let liveAnnounced = false
228
253
  try {
229
254
  for await (const event of liveIter) {
230
- if (!liveAnnounced && !opts.json) {
231
- opts.stdout(
232
- divider(opts.color, sessionLive ? '─── live ───' : '─── live (session not in registry; broadcasts only) ───'),
233
- )
234
- if (opts.liveHint !== undefined && opts.liveHint !== '') {
235
- opts.stdout(divider(opts.color, opts.liveHint))
236
- }
255
+ if (!liveAnnounced) {
256
+ opts.onPhase?.({ phase: 'live-start', sessionLive })
237
257
  liveAnnounced = true
238
258
  }
239
- emit(event)
259
+ deliver(event)
240
260
  }
241
261
  } catch (err) {
242
- opts.stderr(`live tail ended: ${err instanceof Error ? err.message : String(err)}`)
262
+ opts.onWarn?.(`live tail ended: ${err instanceof Error ? err.message : String(err)}`)
243
263
  }
244
- if (!opts.json) opts.stdout('─── end of transcript ───')
264
+ opts.onPhase?.({ phase: 'end' })
245
265
  return { escToPicker: aborted() }
246
266
  }
247
267
 
268
+ // Line/JSON renderer: the original streamSession behavior, now expressed as a
269
+ // streamSessionEvents consumer. Preserves the exact header/divider output and
270
+ // scriptable stdout/JSON contract.
271
+ async function streamSession(opts: {
272
+ summary: SessionSummary
273
+ filter: InspectFilter
274
+ sinceMs: number | undefined
275
+ json: boolean
276
+ color: boolean
277
+ stdout: (line: string) => void
278
+ stderr: (line: string) => void
279
+ liveSource?: LiveSourceFactory
280
+ signal?: AbortSignal
281
+ liveHint?: string
282
+ interactive?: boolean
283
+ }): Promise<{ escToPicker: boolean }> {
284
+ if (!opts.json) writeHeader(opts.summary, opts.color, opts.stdout)
285
+
286
+ const onEvent = (event: InspectEvent): void => {
287
+ if (opts.json) opts.stdout(JSON.stringify({ sessionId: opts.summary.sessionId, ...event }))
288
+ else opts.stdout(renderEvent(event, { color: opts.color }))
289
+ }
290
+
291
+ const emitHint = (): void => {
292
+ if (!opts.json && opts.liveHint !== undefined && opts.liveHint !== '') {
293
+ opts.stdout(divider(opts.color, opts.liveHint))
294
+ }
295
+ }
296
+
297
+ // Replay-only prints the end-of-transcript footer once at the idle point (the
298
+ // viewer then blocks); the terminal 'end' phase must not print it a second
299
+ // time. Live mode skips the idle phase and prints the footer only at 'end'.
300
+ let footerPrinted = false
301
+ const printFooter = (): void => {
302
+ opts.stdout('─── end of transcript ───')
303
+ footerPrinted = true
304
+ }
305
+
306
+ const onPhase = (p: StreamPhase): void => {
307
+ if (opts.json) return
308
+ if (p.phase === 'replay-only-idle') {
309
+ printFooter()
310
+ emitHint()
311
+ } else if (p.phase === 'live-start') {
312
+ opts.stdout(
313
+ divider(opts.color, p.sessionLive ? '─── live ───' : '─── live (session not in registry; broadcasts only) ───'),
314
+ )
315
+ emitHint()
316
+ } else if (p.phase === 'end' && !footerPrinted) {
317
+ printFooter()
318
+ }
319
+ }
320
+
321
+ return streamSessionEvents({
322
+ summary: opts.summary,
323
+ filter: opts.filter,
324
+ sinceMs: opts.sinceMs,
325
+ onEvent,
326
+ onPhase,
327
+ onWarn: opts.stderr,
328
+ ...(opts.liveSource !== undefined ? { liveSource: opts.liveSource } : {}),
329
+ ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
330
+ blockWhenReplayOnly: opts.interactive === true && !opts.json,
331
+ })
332
+ }
333
+
248
334
  function divider(color: boolean, text: string): string {
249
335
  if (color) return `\u001b[2m${text}\u001b[0m`
250
336
  return text
@@ -0,0 +1,44 @@
1
+ import type { ViewerItem } from './item'
2
+ import { listSessions, type ListSessionsOptions, type SessionSummary } from './session-list'
3
+
4
+ export type ListViewerItemsOptions = ListSessionsOptions & {
5
+ containerRunning: boolean
6
+ includeLogs?: boolean
7
+ // Defaults to true. The detach-to-list path (after `typeclaw tui` esc) sets
8
+ // this false: detaching ENDS the server-side session, so the just-killed
9
+ // (most-recent) tui transcript — and any older tui transcript the heuristic
10
+ // would otherwise promote — must NOT be offered as a writable live row.
11
+ allowWritable?: boolean
12
+ }
13
+
14
+ export type ViewerList = {
15
+ items: ViewerItem[]
16
+ writableSessionId: string | null
17
+ }
18
+
19
+ // Builds the session-viewer list. The writable TUI row is a heuristic, not an
20
+ // authoritative query: when the container is up, the single most-recent
21
+ // tui-origin session becomes the read+write `tui` item; every other session is
22
+ // read-only. With the container down there is no live session to drive, so all
23
+ // sessions are read-only. The `logs` row is appended last (container stdout,
24
+ // available offline) so it sits below the divider in the picker.
25
+ export async function listViewerItems(opts: ListViewerItemsOptions): Promise<ViewerList> {
26
+ const sessions = await listSessions(opts)
27
+ const allowWritable = opts.allowWritable !== false
28
+ const writableSessionId = opts.containerRunning && allowWritable ? pickWritableSession(sessions) : null
29
+
30
+ const items: ViewerItem[] = sessions.map((summary) =>
31
+ summary.sessionId === writableSessionId
32
+ ? { kind: 'tui', summary, writable: true }
33
+ : { kind: 'session', summary, writable: false },
34
+ )
35
+
36
+ if (opts.includeLogs !== false) items.push({ kind: 'logs' })
37
+
38
+ return { items, writableSessionId }
39
+ }
40
+
41
+ function pickWritableSession(sessions: SessionSummary[]): string | null {
42
+ const tuiSession = sessions.find((s) => s.origin?.kind === 'tui')
43
+ return tuiSession?.sessionId ?? null
44
+ }
@@ -0,0 +1,17 @@
1
+ import type { SessionSummary } from './session-list'
2
+
3
+ // At most one item is `writable` (the live TUI session); every other session is
4
+ // read-only. `logs` carries no session — it is container stdout, available even
5
+ // when the agent server is down.
6
+ export type ViewerItem =
7
+ | { kind: 'session'; summary: SessionSummary; writable: false }
8
+ | { kind: 'tui'; summary: SessionSummary; writable: true }
9
+ | { kind: 'logs' }
10
+
11
+ export function isWritable(item: ViewerItem): item is Extract<ViewerItem, { kind: 'tui' }> {
12
+ return item.kind === 'tui'
13
+ }
14
+
15
+ export function itemKey(item: ViewerItem): string {
16
+ return item.kind === 'logs' ? 'logs' : item.summary.sessionId
17
+ }
@@ -17,7 +17,7 @@ export function originLabel(origin: MinimalSessionOrigin): string {
17
17
  case 'cron':
18
18
  return `Cron ${origin.jobId} (${origin.jobKind})`
19
19
  case 'subagent':
20
- return `Subagent ${origin.subagent} ← ${shortSessionId(origin.parentSessionId)}`
20
+ return `Subagent ${origin.subagent}`
21
21
  case 'channel':
22
22
  return channelLabel(origin)
23
23
  case 'system':
@@ -0,0 +1,79 @@
1
+ import { logs } from '@/container'
2
+
3
+ export type StreamLogsOptions = {
4
+ cwd: string
5
+ color: boolean
6
+ stdout: (line: string) => void
7
+ stderr: (line: string) => void
8
+ signal?: AbortSignal
9
+ liveHint?: string
10
+ }
11
+
12
+ export type StreamLogsResult = { escToPicker: boolean }
13
+
14
+ // Interactive container-logs viewer for the session-viewer list. Unlike the raw
15
+ // `logs` pump (host-stage, used for `typeclaw logs | grep`), this one runs under
16
+ // the loop's tail scope: aborting the signal (esc/q/ctrl-c) kills `docker logs`
17
+ // and returns control to the picker. Works with the agent server down — it only
18
+ // needs the container to exist.
19
+ export async function streamLogs(opts: StreamLogsOptions): Promise<StreamLogsResult> {
20
+ const aborted = (): boolean => opts.signal?.aborted === true
21
+ if (aborted()) return { escToPicker: true }
22
+
23
+ opts.stdout(divider(opts.color, '─── container logs ───'))
24
+ if (opts.liveHint !== undefined && opts.liveHint !== '') {
25
+ opts.stdout(divider(opts.color, opts.liveHint))
26
+ }
27
+
28
+ const out = lineSink(opts.stdout)
29
+ const err = lineSink(opts.stderr)
30
+
31
+ const result = await logs({
32
+ cwd: opts.cwd,
33
+ follow: true,
34
+ out,
35
+ err,
36
+ useColor: opts.color,
37
+ ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
38
+ })
39
+
40
+ if (!result.ok) {
41
+ opts.stderr(result.reason)
42
+ return { escToPicker: aborted() }
43
+ }
44
+ return { escToPicker: aborted() }
45
+ }
46
+
47
+ function divider(color: boolean, text: string): string {
48
+ if (color) return `\u001b[2m${text}\u001b[0m`
49
+ return text
50
+ }
51
+
52
+ // `logs` writes pre-formatted chunks (already newline-terminated) to a
53
+ // WritableStream; the loop's sink wants newline-free lines. Buffer partial
54
+ // lines and forward complete ones so a chunk split mid-line never emits a
55
+ // truncated row.
56
+ function lineSink(emit: (line: string) => void): NodeJS.WritableStream {
57
+ let buffer = ''
58
+ const flushLines = (): void => {
59
+ let idx = buffer.indexOf('\n')
60
+ while (idx !== -1) {
61
+ emit(buffer.slice(0, idx))
62
+ buffer = buffer.slice(idx + 1)
63
+ idx = buffer.indexOf('\n')
64
+ }
65
+ }
66
+ return {
67
+ write(chunk: string | Uint8Array): boolean {
68
+ buffer += typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk)
69
+ flushLines()
70
+ return true
71
+ },
72
+ end(): void {
73
+ if (buffer.length > 0) {
74
+ emit(buffer)
75
+ buffer = ''
76
+ }
77
+ },
78
+ } as unknown as NodeJS.WritableStream
79
+ }
@@ -6,6 +6,80 @@ export type TailController = {
6
6
  dispose: () => void
7
7
  }
8
8
 
9
+ export type OpenItemContext = {
10
+ createTailScope: () => TailController
11
+ }
12
+
13
+ export type SelectItem<TItem> = (items: TItem[], opts: { initialKey?: string }) => Promise<TItem | null>
14
+
15
+ export type OpenItemResult = {
16
+ result: RunInspectResult
17
+ // True only when the viewer that just closed ended a writable (live TUI)
18
+ // session — i.e. a tui detach. Logs and read-only transcripts return
19
+ // escToPicker WITHOUT this, so they must not suppress the writable row.
20
+ endedWritableSession?: boolean
21
+ }
22
+
23
+ export type OpenItem<TItem> = (item: TItem, ctx: OpenItemContext) => Promise<OpenItemResult>
24
+
25
+ export type ListItemsContext = {
26
+ // False once the user has returned to the picker from any viewer: the prior
27
+ // viewer interaction ended, so there is no proof of a still-live writable
28
+ // session — a detached tui session must not be re-promoted as writable.
29
+ allowWritable: boolean
30
+ }
31
+
32
+ export type RunViewerLoopOptions<TItem> = {
33
+ listItems: (ctx: ListItemsContext) => Promise<TItem[]>
34
+ keyOf: (item: TItem) => string
35
+ preselectKey?: string
36
+ selectItem: SelectItem<TItem>
37
+ openItem: OpenItem<TItem>
38
+ createTailScope: () => TailController
39
+ onEmpty: () => RunInspectResult
40
+ }
41
+
42
+ // The session-viewer state machine: pick an item → open it → on back, re-open
43
+ // the picker; on exit, return. `openItem` owns the per-branch lifecycle and
44
+ // decides whether to request a tail scope (session/logs do; tui does not, since
45
+ // it owns its own raw-mode terminal). When used, the tail scope is created
46
+ // inside `openItem` AFTER the picker resolves and disposed before the picker
47
+ // re-opens, so clack always owns a clean cooked-mode stdin.
48
+ export async function runViewerLoop<TItem>(opts: RunViewerLoopOptions<TItem>): Promise<RunInspectResult> {
49
+ let preselectKey = opts.preselectKey
50
+ let lastPickedKey: string | undefined
51
+ // Writable is only safe on the very first list. Returning to the picker means
52
+ // a viewer was just opened and left — any writable session it might represent
53
+ // is gone (detach ends the live session), so subsequent refreshes are
54
+ // read-only.
55
+ let allowWritable = true
56
+
57
+ while (true) {
58
+ const items = await opts.listItems({ allowWritable })
59
+ if (items.length === 0) return opts.onEmpty()
60
+
61
+ let chosen: TItem | null
62
+ if (preselectKey !== undefined) {
63
+ chosen = items.find((i) => opts.keyOf(i) === preselectKey) ?? null
64
+ preselectKey = undefined
65
+ if (chosen === null) return opts.onEmpty()
66
+ } else {
67
+ const hint = lastPickedKey
68
+ chosen = await opts.selectItem(items, hint !== undefined ? { initialKey: hint } : {})
69
+ if (chosen === null) return { ok: false, exitCode: 130, reason: 'cancelled' }
70
+ lastPickedKey = opts.keyOf(chosen)
71
+ }
72
+
73
+ const opened = await opts.openItem(chosen, { createTailScope: opts.createTailScope })
74
+ const result = opened.result
75
+ if (!result.ok) return result
76
+ if (result.escToPicker !== true) return result
77
+ // Only a writable (tui) detach ends the live session; leaving logs or a
78
+ // read-only transcript leaves it untouched, so the writable row stays.
79
+ if (opened.endedWritableSession === true) allowWritable = false
80
+ }
81
+ }
82
+
9
83
  export type RunInspectLoopOptions = Omit<RunInspectOptions, 'signal'> & {
10
84
  // Builds a fresh interaction scope for ONE live-tail attempt: a new
11
85
  // AbortController plus a temporary raw-mode listener. The loop creates it
@@ -30,12 +104,9 @@ export async function runInspectLoop(opts: RunInspectLoopOptions): Promise<RunIn
30
104
  if (sessionArg !== undefined) resolveOpts.sessionIdOrPrefix = sessionArg
31
105
  else delete (resolveOpts as { sessionIdOrPrefix?: string }).sessionIdOrPrefix
32
106
 
33
- // Picker phase: cooked-mode stdin, no tail scope alive.
34
107
  const resolved = await resolveInspectTarget(resolveOpts)
35
108
  if (!resolved.ok) return resolved
36
109
 
37
- // Streaming phase: scope owns raw-mode stdin start-to-dispose, never
38
- // spanning the picker above or the next iteration's picker below.
39
110
  const scope = opts.createTailScope()
40
111
  let result: RunInspectResult
41
112
  try {
@@ -0,0 +1,100 @@
1
+ import type { LiveSourceFactory, RunInspectResult } from './index'
2
+ import { createTranscriptView, streamInspectTarget } from './index'
3
+ import type { ViewerItem } from './item'
4
+ import { streamLogs } from './logs-item'
5
+ import type { OpenItemContext, OpenItemResult, TailController } from './loop'
6
+ import { runTuiViewer } from './tui-item'
7
+ import type { InspectFilter } from './types'
8
+
9
+ export type OpenViewerDeps = {
10
+ cwd: string
11
+ filter: InspectFilter
12
+ sinceMs: number | undefined
13
+ json: boolean
14
+ color: boolean
15
+ interactive: boolean
16
+ stdout: (line: string) => void
17
+ stderr: (line: string) => void
18
+ liveSource?: LiveSourceFactory
19
+ liveHint?: string
20
+ resolveTuiUrl: () => Promise<string>
21
+ expectedVersion?: string
22
+ onVersionMismatch?: (info: { expected: string; actual: string }) => void
23
+ }
24
+
25
+ // Dispatches a selected list item to its viewer. The tui branch and the
26
+ // interactive read-only transcript view each own their own raw-mode pi-tui
27
+ // terminal, so they run WITHOUT the loop's tail scope (two raw-stdin owners
28
+ // would corrupt input). The line/JSON session path and logs run UNDER the tail
29
+ // scope, which owns the raw-mode esc/q/ctrl-c handling.
30
+ export function openViewerItem(deps: OpenViewerDeps) {
31
+ return async (item: ViewerItem, ctx: OpenItemContext): Promise<OpenItemResult> => {
32
+ if (item.kind === 'tui') {
33
+ const result = await runTuiViewer({
34
+ resolveUrl: deps.resolveTuiUrl,
35
+ stderr: deps.stderr,
36
+ ...(deps.expectedVersion !== undefined ? { expectedVersion: deps.expectedVersion } : {}),
37
+ ...(deps.onVersionMismatch !== undefined ? { onVersionMismatch: deps.onVersionMismatch } : {}),
38
+ })
39
+ // Detaching the writable tui viewer ends the live session — the only path
40
+ // that should suppress the writable row on the next list refresh.
41
+ return { result, endedWritableSession: result.ok && result.escToPicker === true }
42
+ }
43
+
44
+ // Interactive-TTY read-only session -> rich pi-tui transcript view. Owns its
45
+ // own terminal, so it bypasses the tail scope. JSON/non-TTY falls through to
46
+ // the scriptable line renderer below. Read-only: esc does NOT end a live
47
+ // session, so endedWritableSession stays unset.
48
+ if (item.kind === 'session' && deps.interactive && !deps.json) {
49
+ const view = createTranscriptView({
50
+ summary: item.summary,
51
+ filter: deps.filter,
52
+ sinceMs: deps.sinceMs,
53
+ ...(deps.liveSource !== undefined ? { liveSource: deps.liveSource } : {}),
54
+ })
55
+ const outcome = await view.run()
56
+ const result: RunInspectResult =
57
+ outcome.reason === 'back' ? { ok: true, exitCode: 0, escToPicker: true } : { ok: true, exitCode: 0 }
58
+ return { result }
59
+ }
60
+
61
+ const scope = ctx.createTailScope()
62
+ try {
63
+ if (item.kind === 'logs') {
64
+ const logsResult = await streamLogs({
65
+ cwd: deps.cwd,
66
+ color: deps.color,
67
+ stdout: deps.stdout,
68
+ stderr: deps.stderr,
69
+ signal: scope.signal,
70
+ ...(deps.liveHint !== undefined ? { liveHint: deps.liveHint } : {}),
71
+ })
72
+ // Logs esc does NOT touch the live session — no endedWritableSession.
73
+ return { result: toResult(logsResult.escToPicker, scope) }
74
+ }
75
+
76
+ const sessionResult = await streamInspectTarget({
77
+ agentDir: deps.cwd,
78
+ target: { summary: item.summary, filter: deps.filter, sinceMs: deps.sinceMs },
79
+ json: deps.json,
80
+ color: deps.color,
81
+ stdout: deps.stdout,
82
+ stderr: deps.stderr,
83
+ signal: scope.signal,
84
+ ...(deps.liveSource !== undefined ? { liveSource: deps.liveSource } : {}),
85
+ ...(deps.liveHint !== undefined ? { liveHint: deps.liveHint } : {}),
86
+ ...(deps.interactive ? { interactive: true } : {}),
87
+ })
88
+ const escToPicker = sessionResult.ok && sessionResult.escToPicker === true
89
+ return { result: toResult(escToPicker, scope) }
90
+ } finally {
91
+ scope.dispose()
92
+ }
93
+ }
94
+ }
95
+
96
+ function toResult(escToPicker: boolean, scope: TailController): RunInspectResult {
97
+ if (scope.intent() === 'exit') return { ok: true, exitCode: 0 }
98
+ if (escToPicker) return { ok: true, exitCode: 0, escToPicker: true }
99
+ return { ok: true, exitCode: 0 }
100
+ }
@@ -0,0 +1,106 @@
1
+ import type { MinimalSessionOrigin } from '@/agent/session-meta'
2
+
3
+ // Builds the one-line session-list hint from a session's first user turn.
4
+ // User turns are wrapped in runtime-injected preamble (<current-time>, role
5
+ // anchors, SYSTEM MESSAGE fences, channel context sections, …) that grows over
6
+ // time. Rather than chase every block, this keys off stable semantic
7
+ // boundaries and prefers null over a misleading hint — it is a cosmetic glance,
8
+ // not a faithful reconstruction.
9
+ export function previewForHint(origin: MinimalSessionOrigin | null, text: string): string | null {
10
+ // A subagent's first message is a machine payload (Parent session:, …) and
11
+ // the row label already names the subagent.
12
+ if (origin?.kind === 'subagent') return null
13
+ if (origin?.kind === 'channel') return channelPreview(text)
14
+ return structuralPreview(text)
15
+ }
16
+
17
+ // `[ISO] <@authorId> (authorName) [bot]: actual text` — the only line carrying
18
+ // human-typed text in a channel turn. The stamp is omitted when ts<=0, so it is
19
+ // optional here; name and bot tag are also optional.
20
+ const AUTHOR_LINE = /^(?:\[[^\]]+\]\s+)?<[^>]+>(?:\s+\([^)]+\))?(?:\s+\[bot\])?:\s*(.*)$/
21
+
22
+ const CURRENT_MESSAGE_HEADER = /^## Current messages? \(addressed to you\)\s*$/
23
+
24
+ // Channel preview: extract ONLY from the "## Current message(s) (addressed to
25
+ // you)" section — never the "## Recent context" section above it, which is other
26
+ // people's messages the agent was only made aware of. Returns null if no
27
+ // addressed message is found.
28
+ function channelPreview(text: string): string | null {
29
+ const lines = text.split('\n')
30
+ const headerIdx = lines.findIndex((l) => CURRENT_MESSAGE_HEADER.test(l))
31
+ if (headerIdx === -1) return null
32
+
33
+ for (let i = headerIdx + 1; i < lines.length; i++) {
34
+ const match = AUTHOR_LINE.exec(lines[i]!)
35
+ if (match === null) continue
36
+ const payload = collectMessage(match[1] ?? '', lines, i + 1)
37
+ const trimmed = payload.trim()
38
+ return trimmed.length > 0 ? trimmed : null
39
+ }
40
+ return null
41
+ }
42
+
43
+ // An author line's text plus any continuation lines (a multi-line message
44
+ // continues without the author prefix) until the next author line, a structural
45
+ // boundary (## / ---), or a quote anchor (>).
46
+ function collectMessage(first: string, lines: string[], start: number): string {
47
+ const parts = [first]
48
+ for (let i = start; i < lines.length; i++) {
49
+ const line = lines[i]!
50
+ if (AUTHOR_LINE.test(line) || line.startsWith('## ') || line.startsWith('---') || line.startsWith('>')) break
51
+ parts.push(line)
52
+ }
53
+ return parts.join(' ')
54
+ }
55
+
56
+ // Origin-agnostic fallback (TUI, cron, system, unknown): skip leading injected
57
+ // structure — XML-tag blocks, `--- … ---` SYSTEM MESSAGE fences, `## …`
58
+ // sections, and blank lines — then take the first remaining real line. This
59
+ // degrades gracefully as new runtime notices (which follow the same framing
60
+ // conventions) are added, without needing per-block updates.
61
+ function structuralPreview(text: string): string | null {
62
+ const lines = text.split('\n')
63
+ let i = 0
64
+ while (i < lines.length) {
65
+ const line = lines[i]!
66
+ const trimmed = line.trim()
67
+ if (trimmed === '') {
68
+ i++
69
+ } else if (trimmed.startsWith('<')) {
70
+ i = skipXmlOrTagLine(lines, i)
71
+ } else if (trimmed.startsWith('---')) {
72
+ i = skipFence(lines, i)
73
+ } else if (trimmed.startsWith('#')) {
74
+ i++
75
+ } else {
76
+ return looksInjected(trimmed) ? null : trimmed
77
+ }
78
+ }
79
+ return null
80
+ }
81
+
82
+ // Skips a leading XML block. If the opening tag closes on the same line or
83
+ // spans lines, advance past the matching close tag; otherwise skip just the one
84
+ // line (a stray `<…>` shouldn't swallow the rest).
85
+ function skipXmlOrTagLine(lines: string[], start: number): number {
86
+ const open = /^<([a-zA-Z][\w-]*)/.exec(lines[start]!.trim())
87
+ if (open === null) return start + 1
88
+ const close = `</${open[1]}>`
89
+ for (let i = start; i < lines.length; i++) {
90
+ if (lines[i]!.includes(close)) return i + 1
91
+ }
92
+ return start + 1
93
+ }
94
+
95
+ // Skips a `---` fenced block (SYSTEM MESSAGE framing): from the opening `---`
96
+ // to the next standalone `---`.
97
+ function skipFence(lines: string[], start: number): number {
98
+ for (let i = start + 1; i < lines.length; i++) {
99
+ if (lines[i]!.trim() === '---') return i + 1
100
+ }
101
+ return start + 1
102
+ }
103
+
104
+ function looksInjected(line: string): boolean {
105
+ return line.startsWith('**[SYSTEM') || line.startsWith('[security/')
106
+ }