typeclaw 0.25.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.
- package/package.json +1 -1
- package/src/agent/session-origin.ts +36 -5
- package/src/agent/subagent-completion-reminder.ts +16 -1
- package/src/agent/tools/channel-react.ts +11 -4
- package/src/bundled-plugins/reviewer/skills/code-review.ts +3 -1
- package/src/channels/adapters/discord-bot-classify.ts +3 -0
- package/src/channels/adapters/discord-bot-reactions.ts +164 -0
- package/src/channels/adapters/discord-bot.ts +23 -0
- package/src/channels/adapters/github/inbound.ts +60 -13
- package/src/channels/adapters/github/review-thread-resolver.ts +28 -3
- package/src/channels/adapters/slack-bot-classify.ts +2 -0
- package/src/channels/adapters/slack-bot-reactions.ts +167 -0
- package/src/channels/adapters/slack-bot.ts +24 -0
- package/src/channels/router.ts +191 -7
- package/src/channels/schema.ts +41 -0
- package/src/cli/inspect.ts +216 -36
- package/src/cli/logs.ts +15 -0
- package/src/cli/tui.ts +33 -39
- package/src/compose/logs.ts +1 -1
- package/src/config/config.ts +43 -2
- package/src/container/logs.ts +70 -22
- package/src/init/index.ts +3 -3
- package/src/inspect/index.ts +128 -42
- package/src/inspect/item-list.ts +44 -0
- package/src/inspect/item.ts +17 -0
- package/src/inspect/label.ts +1 -1
- package/src/inspect/logs-item.ts +79 -0
- package/src/inspect/loop.ts +74 -3
- package/src/inspect/open-item.ts +100 -0
- package/src/inspect/preview.ts +106 -0
- package/src/inspect/session-list.ts +15 -3
- package/src/inspect/transcript-view.ts +182 -0
- package/src/inspect/tui-item.ts +97 -0
- package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
- package/src/tui/index.ts +72 -32
- package/typeclaw.schema.json +1 -0
package/src/container/logs.ts
CHANGED
|
@@ -44,27 +44,48 @@ export async function logs({
|
|
|
44
44
|
return { ok: false, reason: `Container ${plan.containerName} not found. Run \`typeclaw start\` first.` }
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
// stdin:'ignore' — `docker logs` never reads stdin, and letting the child
|
|
48
|
+
// hold the TTY breaks the viewer's raw-mode keypress listener (esc/q/ctrl-c
|
|
49
|
+
// stop reaching it, freezing the logs view with no way out).
|
|
50
|
+
const proc = bun.spawn({ cmd: buildDockerLogsCmd(plan), cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' })
|
|
48
51
|
|
|
52
|
+
// `docker logs -f` never exits on its own; aborting the signal must kill it
|
|
53
|
+
// so the pumps' stream readers end. Escalate to SIGKILL if SIGTERM is
|
|
54
|
+
// ignored, otherwise Promise.all(pumps) could hang until the pipes close.
|
|
55
|
+
let killTimer: ReturnType<typeof setTimeout> | undefined
|
|
49
56
|
const onAbort = (): void => {
|
|
50
57
|
try {
|
|
51
58
|
proc.kill('SIGTERM')
|
|
59
|
+
killTimer = setTimeout(() => {
|
|
60
|
+
try {
|
|
61
|
+
proc.kill('SIGKILL')
|
|
62
|
+
} catch {
|
|
63
|
+
// already exited
|
|
64
|
+
}
|
|
65
|
+
}, 2_000)
|
|
52
66
|
} catch {
|
|
53
67
|
// already exited
|
|
54
68
|
}
|
|
55
69
|
}
|
|
56
70
|
signal?.addEventListener('abort', onAbort, { once: true })
|
|
71
|
+
// The signal may already be aborted before we attached the listener (esc
|
|
72
|
+
// pressed during container existence check); addEventListener would then
|
|
73
|
+
// never fire, leaving docker logs -f running forever.
|
|
74
|
+
if (signal?.aborted === true) onAbort()
|
|
57
75
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
76
|
+
try {
|
|
77
|
+
const colorOut = useColor ?? supportsColor(out)
|
|
78
|
+
const colorErr = useColor ?? supportsColor(err)
|
|
79
|
+
await Promise.all([
|
|
80
|
+
pumpWithTimestamps(proc.stdout, out, makeLogTimestampReformatter(undefined, { color: colorOut }), signal),
|
|
81
|
+
pumpWithTimestamps(proc.stderr, err, makeLogTimestampReformatter(undefined, { color: colorErr }), signal),
|
|
82
|
+
])
|
|
83
|
+
const exitCode = await proc.exited
|
|
84
|
+
return { ok: true, containerName: plan.containerName, exitCode }
|
|
85
|
+
} finally {
|
|
86
|
+
if (killTimer !== undefined) clearTimeout(killTimer)
|
|
87
|
+
signal?.removeEventListener('abort', onAbort)
|
|
88
|
+
}
|
|
68
89
|
} catch (error) {
|
|
69
90
|
return { ok: false, reason: error instanceof Error ? error.message : String(error) }
|
|
70
91
|
}
|
|
@@ -101,30 +122,57 @@ export function buildDockerLogsCmd(plan: LogsPlan): string[] {
|
|
|
101
122
|
|
|
102
123
|
// Exported for `compose/logs.ts` so the multi-agent path reuses the same
|
|
103
124
|
// reformatter and stays consistent with single-agent output.
|
|
125
|
+
//
|
|
126
|
+
// Abort handling is load-bearing for the interactive logs viewer: killing
|
|
127
|
+
// `docker logs -f` does NOT reliably make Bun's pending `reader.read()` resolve
|
|
128
|
+
// (the killed child may not promptly EOF its piped stdout — see the OrbStack
|
|
129
|
+
// /proc quirk). Without cancelling the reader on abort, esc would hang forever.
|
|
130
|
+
// So on abort we cancel the reader, which unblocks the pending read; the caller
|
|
131
|
+
// still kills the process for OS-side cleanup.
|
|
104
132
|
export async function pumpWithTimestamps(
|
|
105
133
|
stream: ReadableStream<Uint8Array>,
|
|
106
134
|
sink: NodeJS.WritableStream,
|
|
107
135
|
reformatter: TimestampReformatter = makeLogTimestampReformatter(),
|
|
136
|
+
signal?: AbortSignal,
|
|
108
137
|
): Promise<void> {
|
|
109
138
|
const decoder = new TextDecoder()
|
|
110
139
|
const reader = stream.getReader()
|
|
140
|
+
let aborted = signal?.aborted === true
|
|
141
|
+
const onAbort = (): void => {
|
|
142
|
+
aborted = true
|
|
143
|
+
void reader.cancel().catch(() => {})
|
|
144
|
+
}
|
|
145
|
+
if (aborted) onAbort()
|
|
146
|
+
else signal?.addEventListener('abort', onAbort, { once: true })
|
|
147
|
+
|
|
111
148
|
try {
|
|
112
149
|
while (true) {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
150
|
+
if (aborted) break
|
|
151
|
+
const chunk = await reader.read().catch((error: unknown) => {
|
|
152
|
+
if (aborted || signal?.aborted === true) return null
|
|
153
|
+
throw error
|
|
154
|
+
})
|
|
155
|
+
if (chunk === null || chunk.done || aborted) break
|
|
156
|
+
if (chunk.value && chunk.value.byteLength > 0) {
|
|
157
|
+
const out = reformatter.write(decoder.decode(chunk.value, { stream: true }))
|
|
117
158
|
if (out.length > 0) sink.write(out)
|
|
118
159
|
}
|
|
119
160
|
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
161
|
+
if (!aborted) {
|
|
162
|
+
const tail = decoder.decode()
|
|
163
|
+
if (tail.length > 0) {
|
|
164
|
+
const out = reformatter.write(tail)
|
|
165
|
+
if (out.length > 0) sink.write(out)
|
|
166
|
+
}
|
|
167
|
+
const flushed = reformatter.flush()
|
|
168
|
+
if (flushed.length > 0) sink.write(flushed)
|
|
124
169
|
}
|
|
125
|
-
const flushed = reformatter.flush()
|
|
126
|
-
if (flushed.length > 0) sink.write(flushed)
|
|
127
170
|
} finally {
|
|
128
|
-
|
|
171
|
+
signal?.removeEventListener('abort', onAbort)
|
|
172
|
+
try {
|
|
173
|
+
reader.releaseLock()
|
|
174
|
+
} catch {
|
|
175
|
+
// harmless if cancel/abort raced with stream teardown
|
|
176
|
+
}
|
|
129
177
|
}
|
|
130
178
|
}
|
package/src/init/index.ts
CHANGED
|
@@ -3,7 +3,6 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
|
3
3
|
import { basename, dirname, join, relative, resolve } from 'node:path'
|
|
4
4
|
import { fileURLToPath } from 'node:url'
|
|
5
5
|
|
|
6
|
-
import { DEFAULT_GITHUB_EVENT_ALLOWLIST } from '@/channels/schema'
|
|
7
6
|
import { config, configSchema, migrateLegacyConfigShape, type Config } from '@/config'
|
|
8
7
|
import {
|
|
9
8
|
DEFAULT_MODEL_REF,
|
|
@@ -1167,10 +1166,12 @@ async function mergeChannelIntoConfig(cwd: string, options: AddChannelOptions):
|
|
|
1167
1166
|
}
|
|
1168
1167
|
|
|
1169
1168
|
function buildGithubChannelConfig(options: Extract<AddChannelOptions, { channel: 'github' }>): Record<string, unknown> {
|
|
1169
|
+
// Do NOT write eventAllowlist: the schema defaults it at parse time, so
|
|
1170
|
+
// omitting it lets the user's config track the shipped default across
|
|
1171
|
+
// releases instead of freezing the list captured at `channel add` time.
|
|
1170
1172
|
return {
|
|
1171
1173
|
...(options.webhookUrl !== undefined ? { webhookUrl: options.webhookUrl } : {}),
|
|
1172
1174
|
webhookPort: options.webhookPort ?? 8975,
|
|
1173
|
-
eventAllowlist: [...DEFAULT_GITHUB_EVENT_ALLOWLIST],
|
|
1174
1175
|
repos: options.repos,
|
|
1175
1176
|
}
|
|
1176
1177
|
}
|
|
@@ -1246,7 +1247,6 @@ async function writeGithubChannelForInit(cwd: string, credentials: GithubInitCre
|
|
|
1246
1247
|
existingChannels.github = {
|
|
1247
1248
|
...(credentials.webhookUrl !== undefined ? { webhookUrl: credentials.webhookUrl } : {}),
|
|
1248
1249
|
webhookPort: credentials.webhookPort ?? 8975,
|
|
1249
|
-
eventAllowlist: [...DEFAULT_GITHUB_EVENT_ALLOWLIST],
|
|
1250
1250
|
repos: credentials.repos,
|
|
1251
1251
|
}
|
|
1252
1252
|
parsed.channels = existingChannels
|
package/src/inspect/index.ts
CHANGED
|
@@ -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 {
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
172
|
-
|
|
173
|
-
|
|
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
|
-
|
|
178
|
-
interactive
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
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
|
-
|
|
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
|
-
|
|
192
|
-
|
|
193
|
-
|
|
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
|
-
|
|
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
|
-
|
|
203
|
-
|
|
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
|
|
231
|
-
opts.
|
|
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
|
-
|
|
259
|
+
deliver(event)
|
|
240
260
|
}
|
|
241
261
|
} catch (err) {
|
|
242
|
-
opts.
|
|
262
|
+
opts.onWarn?.(`live tail ended: ${err instanceof Error ? err.message : String(err)}`)
|
|
243
263
|
}
|
|
244
|
-
|
|
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
|
+
}
|
package/src/inspect/label.ts
CHANGED
|
@@ -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}
|
|
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
|
+
}
|
package/src/inspect/loop.ts
CHANGED
|
@@ -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 {
|