typeclaw 0.48.9 → 0.48.10

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.
@@ -362,6 +362,7 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
362
362
  )
363
363
  if (credentialsStore === null) return null
364
364
  return createInstagram({
365
+ agentDir: options.agentDir,
365
366
  router,
366
367
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
367
368
  logger,
@@ -114,6 +114,7 @@ import type {
114
114
  HistoryCallback,
115
115
  InboundAttachment,
116
116
  GithubReviewFollowupRound,
117
+ GithubReviewThreadCloseout,
117
118
  InboundMessage,
118
119
  InboundReferenceContext,
119
120
  ListCallback,
@@ -419,6 +420,8 @@ export const STRANDED_TOOLUSE_CONTINUATION_NUDGE = [
419
420
  // drop so the human is never left staring at dead air after a degenerate turn.
420
421
  export const EMPTY_TURN_FALLBACK_TEXT =
421
422
  "⚠️ I got stuck putting together a reply and couldn't finish. Could you rephrase or try again?"
423
+ export const GITHUB_REVIEW_THREAD_CLOSEOUT_FALLBACK_TEXT =
424
+ "I wasn't able to complete this follow-up. Leaving this thread open for manual review."
422
425
  // Distinct from EMPTY_TURN_RETRY_NUDGE: that one diagnoses budget exhaustion
423
426
  // ("ran out of output budget"), which is FALSE for a clean `stop` with empty
424
427
  // text. This nudge names the real failure — a turn that ended sending nothing
@@ -770,6 +773,7 @@ type QueuedInbound = {
770
773
  // prefix for those).
771
774
  ts: number
772
775
  githubReviewRound?: GithubReviewFollowupRound
776
+ githubReviewThreadCloseout?: GithubReviewThreadCloseout
773
777
  }
774
778
 
775
779
  type ObservedInbound = {
@@ -878,6 +882,15 @@ type LiveSession = {
878
882
  resolvedNames: ResolvedChannelNames
879
883
  originRef: { current: SessionOrigin | undefined }
880
884
  githubReviewRound: GithubReviewFollowupRound | null
885
+ // A real-user reply to one of this agent's own review-thread roots must end
886
+ // with a reply on that exact thread. This spans reminder-only retry iterations.
887
+ githubReviewThreadCloseout:
888
+ | (GithubReviewThreadCloseout & {
889
+ sendCountAtStart: number
890
+ startedAt: number
891
+ correctionAttempts: number
892
+ })
893
+ | null
881
894
  // Round key of a close-out that arrived while the round was still pending
882
895
  // completion. Replayed once the round completes; see replayPendingRoundCloseouts.
883
896
  pendingGithubReviewRoundCloseout: string | null
@@ -1584,6 +1597,7 @@ export type ChannelRouter = {
1584
1597
  prNumber: number
1585
1598
  state: ReviewOutputState
1586
1599
  }) => { kind: 'stamped' | 'no-live-session' }
1600
+ hasOutstandingGithubReviewThreadCloseout?: (sessionId: string) => boolean
1587
1601
  // Record that the agent invoked `skip_response` during the current turn
1588
1602
  // for the channel session identified by `parentSessionId`. The reason is
1589
1603
  // logged at INFO level inside `validateChannelTurn` (single log line per
@@ -2217,9 +2231,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2217
2231
  // still run. Session scope would let one long-running child silence every
2218
2232
  // subsequent turn, and a wedged child would strand them with nothing to revisit
2219
2233
  // them after the backstop expires.
2220
- const isAwaitingBackgroundChild = (live: LiveSession, label: string): boolean => {
2234
+ const isAwaitingBackgroundChild = (
2235
+ live: LiveSession,
2236
+ label: string,
2237
+ startedAt = live.logicalTurnStartedAt,
2238
+ ): boolean => {
2221
2239
  const childStartedAt = newestRunningChildSubagentStartedAt(live.sessionId)
2222
- if (childStartedAt === null || childStartedAt < live.logicalTurnStartedAt) return false
2240
+ if (childStartedAt === null || childStartedAt < startedAt) return false
2223
2241
  return isPinnedByRunningChild(live.sessionId, live.keyId, label)
2224
2242
  }
2225
2243
 
@@ -2660,6 +2678,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2660
2678
  resolvedNames,
2661
2679
  originRef,
2662
2680
  githubReviewRound: restoredRound,
2681
+ githubReviewThreadCloseout: null,
2663
2682
  pendingGithubReviewRoundCloseout: null,
2664
2683
  promptQueue: [],
2665
2684
  pendingSystemReminders: [],
@@ -3393,6 +3412,59 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3393
3412
  }
3394
3413
  }
3395
3414
 
3415
+ const postGithubReviewThreadCloseoutFallback = async (live: LiveSession): Promise<void> => {
3416
+ const obligation = live.githubReviewThreadCloseout
3417
+ if (obligation === null) return
3418
+ // Consume before sending so adapter failure cannot turn this one-shot
3419
+ // fallback into a reminder/fallback loop.
3420
+ live.githubReviewThreadCloseout = null
3421
+ logger.warn(
3422
+ `[channels] ${live.keyId} github_thread_closeout_fallback pr=${obligation.prNumber} root=${obligation.rootCommentId}`,
3423
+ )
3424
+ const result = await send(
3425
+ {
3426
+ adapter: 'github',
3427
+ workspace: obligation.workspace,
3428
+ chat: `pr:${obligation.prNumber}`,
3429
+ thread: obligation.rootCommentId,
3430
+ text: GITHUB_REVIEW_THREAD_CLOSEOUT_FALLBACK_TEXT,
3431
+ },
3432
+ { source: 'system', outputKind: 'meta' },
3433
+ )
3434
+ if (!result.ok) {
3435
+ logger.warn(`[channels] ${live.keyId}: github review-thread closeout fallback send failed: ${result.error}`)
3436
+ }
3437
+ }
3438
+
3439
+ const enforceGithubReviewThreadCloseout = async (live: LiveSession): Promise<void> => {
3440
+ const closeout = live.githubReviewThreadCloseout
3441
+ if (
3442
+ closeout === null ||
3443
+ live.successfulChannelSends !== closeout.sendCountAtStart ||
3444
+ isAwaitingBackgroundChild(live, 'github-thread-closeout', closeout.startedAt)
3445
+ ) {
3446
+ return
3447
+ }
3448
+ if (live.skippedTurn?.turnSeq === live.turnSeq) live.skippedTurn = null
3449
+ if (closeout.correctionAttempts === 0) {
3450
+ closeout.correctionAttempts++
3451
+ logger.warn(
3452
+ `[channels] ${live.keyId} github_thread_closeout_retry attempt=1/1 pr=${closeout.prNumber} root=${closeout.rootCommentId}`,
3453
+ )
3454
+ live.pendingSystemReminders.push(
3455
+ retryReminder(
3456
+ `<system-reminder>\nThis session still owes a close-out on GitHub PR #${closeout.prNumber}, ` +
3457
+ `review thread root comment ${closeout.rootCommentId}. Your previous turn sent no reply to that thread. ` +
3458
+ `Call channel_reply now with an explicit resolve_review_thread choice: true if the concern is addressed, ` +
3459
+ `or false to leave it open with an explanation. Do not treat a PR-level verdict stand-down as satisfying ` +
3460
+ `this thread-level obligation.\n</system-reminder>`,
3461
+ ),
3462
+ )
3463
+ return
3464
+ }
3465
+ await postGithubReviewThreadCloseoutFallback(live)
3466
+ }
3467
+
3396
3468
  // Resolve a fallback STAGED by a willingness-ack exhaustion path, run AFTER
3397
3469
  // maybeContinueTodosChannel so the idle/todo continuation has already had its
3398
3470
  // chance to queue a re-prompt (the mechanism that self-recovers the promised
@@ -3849,6 +3921,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3849
3921
  live.emptyStopAfterToolWorkArmed = false
3850
3922
  live.willingnessNudges = 0
3851
3923
  live.logicalTurnStartedAt = now()
3924
+ const stampedCloseout = batch.findLast((item) => item.githubReviewThreadCloseout !== undefined)
3925
+ live.githubReviewThreadCloseout =
3926
+ stampedCloseout?.githubReviewThreadCloseout !== undefined
3927
+ ? {
3928
+ ...stampedCloseout.githubReviewThreadCloseout,
3929
+ sendCountAtStart: live.successfulChannelSends,
3930
+ startedAt: live.logicalTurnStartedAt,
3931
+ correctionAttempts: 0,
3932
+ }
3933
+ : null
3852
3934
  // A fresh batch supersedes a still-pending staged fallback. That staged
3853
3935
  // turn produced no usable reply, so it must not leave the PRIOR turn's
3854
3936
  // committed lastQuestionSignal behind — otherwise the new question would
@@ -4076,6 +4158,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4076
4158
  sentReplyThisTurn && !live.promisedWorkOutstandingThisLogicalTurn,
4077
4159
  retryQueuedThisTurn,
4078
4160
  )
4161
+ // Provider notices own the first terminal output opportunity. A notice
4162
+ // that lands on the owed thread clears the obligation through send();
4163
+ // a suppressed or failed notice leaves it intact for this bounded net.
4164
+ await enforceGithubReviewThreadCloseout(live)
4079
4165
  await fireSessionTurnEnd(live)
4080
4166
  }
4081
4167
  await fireSessionIdle(live)
@@ -4609,6 +4695,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4609
4695
  isDm: event.isDm,
4610
4696
  ...(event.typingThread !== undefined ? { typingThread: event.typingThread } : {}),
4611
4697
  ...(event.githubReviewRound !== undefined ? { githubReviewRound: event.githubReviewRound } : {}),
4698
+ ...(event.githubReviewThreadCloseout !== undefined
4699
+ ? { githubReviewThreadCloseout: event.githubReviewThreadCloseout }
4700
+ : {}),
4612
4701
  receivedAt: now(),
4613
4702
  ts: event.ts,
4614
4703
  })
@@ -5459,6 +5548,21 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5459
5548
 
5460
5549
  if (live) {
5461
5550
  live.successfulChannelSends++
5551
+ const closeout = live.githubReviewThreadCloseout
5552
+ if (closeout !== null) {
5553
+ const landedOnOwedThread =
5554
+ msg.adapter === 'github' &&
5555
+ msg.workspace === closeout.workspace &&
5556
+ msg.chat === `pr:${closeout.prNumber}` &&
5557
+ (msg.thread ?? null) === closeout.rootCommentId
5558
+ if (landedOnOwedThread) {
5559
+ live.githubReviewThreadCloseout = null
5560
+ } else {
5561
+ // successfulChannelSends is session-wide. Advance the baseline for an
5562
+ // unrelated delivery so equality continues to mean no owed-thread send.
5563
+ closeout.sendCountAtStart++
5564
+ }
5565
+ }
5462
5566
  // Promise fulfillment follows OUTPUT KIND, never source:
5463
5567
  // (a) ordinary substantive tool output clears;
5464
5568
  // (b) multilingual continuation-willingness/status output preserves;
@@ -6910,6 +7014,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6910
7014
  candidate.key.chat === chat &&
6911
7015
  candidate.key.thread === args.thread,
6912
7016
  )
7017
+ if (live !== undefined) live.githubReviewThreadCloseout = null
6913
7018
  if (live?.githubReviewRound === null || live?.githubReviewRound === undefined) return
6914
7019
  const round = live.githubReviewRound
6915
7020
  if (!isGithubReviewRoundComplete(round)) {
@@ -6986,6 +7091,15 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6986
7091
  return { kind: 'no-live-session' }
6987
7092
  }
6988
7093
 
7094
+ const hasOutstandingGithubReviewThreadCloseout = (sessionId: string): boolean => {
7095
+ for (const live of liveSessions.values()) {
7096
+ if (live.destroyed || live.sessionId !== sessionId) continue
7097
+ const obligation = live.githubReviewThreadCloseout
7098
+ return obligation !== null && live.successfulChannelSends === obligation.sendCountAtStart
7099
+ }
7100
+ return false
7101
+ }
7102
+
6989
7103
  const clearSticky = (key: ChannelKey): { keyId: string; cleared: number } => {
6990
7104
  const keyId = channelKeyId(key)
6991
7105
  const cleared = stickyLedger.clear(keyId)
@@ -7227,6 +7341,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7227
7341
  completeGithubReviewRound: completeRoundForVerifiedVerdict,
7228
7342
  finishGithubReviewRoundCloseout,
7229
7343
  noteGithubReviewOutput,
7344
+ hasOutstandingGithubReviewThreadCloseout,
7230
7345
  markTurnSkipped,
7231
7346
  clearSticky,
7232
7347
  reserveRestartHandoff,
@@ -55,12 +55,22 @@ export type GithubReviewFollowupRound = {
55
55
  carrierThread: string | null
56
56
  }
57
57
 
58
+ export type GithubReviewThreadCloseout = {
59
+ workspace: string
60
+ prNumber: number
61
+ rootCommentId: string
62
+ }
63
+
58
64
  export type InboundMessage = {
59
65
  adapter: AdapterId
60
66
  workspace: string
61
67
  chat: string
62
68
  thread: string | null
63
69
  githubReviewRound?: GithubReviewFollowupRound
70
+ // Adapter-authoritative obligation created only for a non-self reply whose
71
+ // review-thread ROOT comment was authored by this agent. Kept separate from
72
+ // replyToBotMessageId, which describes only the immediate parent.
73
+ githubReviewThreadCloseout?: GithubReviewThreadCloseout
64
74
  // Structural "this message lives in a thread room" signal, kept SEPARATE
65
75
  // from `thread`. `thread` is a reply-routing field whose meaning differs per
66
76
  // platform: Slack puts the thread ts here (so `thread !== null` ⇒ thread
@@ -306,8 +306,11 @@ export const composeCommand = defineCommand({
306
306
  // Single clack spinner with a multi-line message body, one line per agent.
307
307
  // Concurrent clack spinners can't coexist: each one's render loop writes
308
308
  // cursor.to(0) + erase.down() to process.stdout, so they trample each other.
309
- // Multi-line redraw is safe — clack counts newlines in the previous message
310
- // and walks the cursor up before erasing (see @clack/prompts spinner.ts).
309
+ // Multi-line redraw is safe while this board owns the terminal — clack counts
310
+ // newlines in the previous message and walks the cursor up before erasing (see
311
+ // @clack/prompts spinner.ts). Compose start/restart therefore capture process
312
+ // output instead of letting child progress or warnings invalidate clack's
313
+ // cursor position.
311
314
  type Board = {
312
315
  add: (s: ReturnType<typeof spinner>, name: string, state: string) => void
313
316
  set: (s: ReturnType<typeof spinner>, name: string, state: string) => void
@@ -356,7 +359,7 @@ function makeBoard(header: string): Board {
356
359
  }
357
360
 
358
361
  function formatStartDone<T extends { alreadyRunning?: boolean; hostPort: number }>(result: AgentResult<T>): string {
359
- if (!result.ok) return `${c.red('✖')} ${c.red('failed:')} ${result.reason}`
362
+ if (!result.ok) return appendWarnings(`${c.red('✖')} ${c.red('failed:')} ${result.reason}`, result.warnings)
360
363
  const verb = result.data.alreadyRunning ? 'already running' : 'started'
361
364
  const head = `${c.green('✔')} ${verb} on host port ${c.cyan(String(result.data.hostPort))}`
362
365
  return appendWarnings(head, result.warnings)
@@ -369,7 +372,7 @@ function formatStopDone<T extends { running: boolean }>(result: AgentResult<T>):
369
372
  }
370
373
 
371
374
  function formatRestartDone<T extends { start: { hostPort: number } }>(result: AgentResult<T>): string {
372
- if (!result.ok) return `${c.red('✖')} ${c.red('failed:')} ${result.reason}`
375
+ if (!result.ok) return appendWarnings(`${c.red('✖')} ${c.red('failed:')} ${result.reason}`, result.warnings)
373
376
  const head = `${c.green('✔')} restarted on host port ${c.cyan(String(result.data.start.hostPort))}`
374
377
  return appendWarnings(head, result.warnings)
375
378
  }
@@ -1,5 +1,5 @@
1
1
  import { validateConfig } from '@/config'
2
- import { resolveController } from '@/container'
2
+ import { type Controller, resolveController } from '@/container'
3
3
 
4
4
  import { discoverAgents, type AgentEntry } from './discover'
5
5
  import type { AgentResult, StartSuccess } from './start'
@@ -20,25 +20,32 @@ export type ComposeRestartOptions = {
20
20
  onProgress?: (event: ComposeRestartEvent) => void
21
21
  }
22
22
 
23
+ export type ComposeRestartDeps = {
24
+ restart?: Controller['restart']
25
+ }
26
+
23
27
  export type ComposeRestartResult = {
24
28
  agents: AgentEntry[]
25
29
  results: AgentResult<RestartData>[]
26
30
  }
27
31
 
28
- export async function composeRestart({
29
- rootCwd,
30
- preferredHostPort,
31
- forceBuild = false,
32
- cliEntry,
33
- onProgress,
34
- }: ComposeRestartOptions): Promise<ComposeRestartResult> {
32
+ export async function composeRestart(
33
+ { rootCwd, preferredHostPort, forceBuild = false, cliEntry, onProgress }: ComposeRestartOptions,
34
+ { restart = (options) => resolveController().restart(options) }: ComposeRestartDeps = {},
35
+ ): Promise<ComposeRestartResult> {
35
36
  const agents = discoverAgents(rootCwd)
36
37
  const results = await Promise.all(
37
38
  agents.map(async (agent): Promise<AgentResult<RestartData>> => {
38
39
  onProgress?.({ kind: 'agent-start', name: agent.name })
39
- const result = await runOne(agent.name, agent.cwd, preferredHostPort, forceBuild, cliEntry, () => {
40
- onProgress?.({ kind: 'agent-stopped', name: agent.name })
41
- })
40
+ const result = await runOne(
41
+ agent.name,
42
+ agent.cwd,
43
+ preferredHostPort,
44
+ forceBuild,
45
+ cliEntry,
46
+ () => onProgress?.({ kind: 'agent-stopped', name: agent.name }),
47
+ restart,
48
+ )
42
49
  onProgress?.({ kind: 'agent-done', name: agent.name, result })
43
50
  return result
44
51
  }),
@@ -53,26 +60,29 @@ async function runOne(
53
60
  forceBuild: boolean,
54
61
  cliEntry: string | undefined,
55
62
  onStopped: () => void,
63
+ restart: Controller['restart'],
56
64
  ): Promise<AgentResult<RestartData>> {
57
65
  const validated = validateConfig(cwd)
58
66
  if (!validated.ok) return { name, ok: false, reason: validated.reason }
67
+ const warnings = [...(validated.warnings ?? [])]
59
68
  try {
60
- const controller = resolveController()
61
- const restarted = await controller.restart({
69
+ const restarted = await restart({
62
70
  cwd,
63
71
  preferredHostPort,
64
72
  forceBuild,
65
73
  cliEntry,
66
74
  onStopped,
75
+ streamOutput: false,
76
+ onWarning: (warning) => warnings.push(warning),
67
77
  })
68
- if (!restarted.ok) return { name, ok: false, reason: restarted.reason }
78
+ if (!restarted.ok) return { name, ok: false, reason: restarted.reason, warnings }
69
79
  return {
70
80
  name,
71
81
  ok: true,
72
82
  data: { stop: restarted.stop, start: restarted.start },
73
- warnings: validated.warnings,
83
+ warnings,
74
84
  }
75
85
  } catch (error) {
76
- return { name, ok: false, reason: error instanceof Error ? error.message : String(error) }
86
+ return { name, ok: false, reason: error instanceof Error ? error.message : String(error), warnings }
77
87
  }
78
88
  }
@@ -1,11 +1,11 @@
1
1
  import { validateConfig } from '@/config'
2
- import { resolveController, type StartResult } from '@/container'
2
+ import { type Controller, resolveController, type StartResult } from '@/container'
3
3
 
4
4
  import { discoverAgents, type AgentEntry } from './discover'
5
5
 
6
6
  export type AgentResult<T> =
7
7
  | { name: string; ok: true; data: T; warnings?: string[] }
8
- | { name: string; ok: false; reason: string }
8
+ | { name: string; ok: false; reason: string; warnings?: string[] }
9
9
 
10
10
  export type StartSuccess = Extract<StartResult, { ok: true }>
11
11
 
@@ -21,23 +21,24 @@ export type ComposeStartOptions = {
21
21
  onProgress?: (event: ComposeStartEvent) => void
22
22
  }
23
23
 
24
+ export type ComposeStartDeps = {
25
+ start?: Controller['start']
26
+ }
27
+
24
28
  export type ComposeStartResult = {
25
29
  agents: AgentEntry[]
26
30
  results: AgentResult<StartSuccess>[]
27
31
  }
28
32
 
29
- export async function composeStart({
30
- rootCwd,
31
- preferredHostPort,
32
- forceBuild = false,
33
- cliEntry,
34
- onProgress,
35
- }: ComposeStartOptions): Promise<ComposeStartResult> {
33
+ export async function composeStart(
34
+ { rootCwd, preferredHostPort, forceBuild = false, cliEntry, onProgress }: ComposeStartOptions,
35
+ { start = (options) => resolveController().start(options) }: ComposeStartDeps = {},
36
+ ): Promise<ComposeStartResult> {
36
37
  const agents = discoverAgents(rootCwd)
37
38
  const results = await Promise.all(
38
39
  agents.map(async (agent): Promise<AgentResult<StartSuccess>> => {
39
40
  onProgress?.({ kind: 'agent-start', name: agent.name })
40
- const result = await runOne(agent.name, agent.cwd, preferredHostPort, forceBuild, cliEntry)
41
+ const result = await runOne(agent.name, agent.cwd, preferredHostPort, forceBuild, cliEntry, start)
41
42
  onProgress?.({ kind: 'agent-done', name: agent.name, result })
42
43
  return result
43
44
  }),
@@ -51,14 +52,23 @@ async function runOne(
51
52
  preferredHostPort: number,
52
53
  forceBuild: boolean,
53
54
  cliEntry: string | undefined,
55
+ start: Controller['start'],
54
56
  ): Promise<AgentResult<StartSuccess>> {
55
57
  const validated = validateConfig(cwd)
56
58
  if (!validated.ok) return { name, ok: false, reason: validated.reason }
59
+ const warnings = [...(validated.warnings ?? [])]
57
60
  try {
58
- const data = await resolveController().start({ cwd, preferredHostPort, forceBuild, cliEntry })
59
- if (!data.ok) return { name, ok: false, reason: data.reason }
60
- return { name, ok: true, data, warnings: validated.warnings }
61
+ const data = await start({
62
+ cwd,
63
+ preferredHostPort,
64
+ forceBuild,
65
+ cliEntry,
66
+ streamOutput: false,
67
+ onWarning: (warning) => warnings.push(warning),
68
+ })
69
+ if (!data.ok) return { name, ok: false, reason: data.reason, warnings }
70
+ return { name, ok: true, data, warnings }
61
71
  } catch (error) {
62
- return { name, ok: false, reason: error instanceof Error ? error.message : String(error) }
72
+ return { name, ok: false, reason: error instanceof Error ? error.message : String(error), warnings }
63
73
  }
64
74
  }
@@ -6,6 +6,8 @@ export type RestartOptions = {
6
6
  cwd: string
7
7
  preferredHostPort: number
8
8
  forceBuild?: boolean
9
+ streamOutput?: boolean
10
+ onWarning?: (warning: string) => void
9
11
  cliEntry?: string
10
12
  reuseCurrentHostDaemon?: boolean
11
13
  currentHostDaemon?: CurrentHostDaemon
@@ -44,6 +46,8 @@ async function restartWithLease(
44
46
  cwd: options.cwd,
45
47
  preferredHostPort: options.preferredHostPort,
46
48
  forceBuild: options.forceBuild,
49
+ streamOutput: options.streamOutput,
50
+ onWarning: options.onWarning,
47
51
  cliEntry: options.cliEntry,
48
52
  reuseCurrentHostDaemon: options.reuseCurrentHostDaemon,
49
53
  currentHostDaemon: options.currentHostDaemon,
@@ -20,6 +20,10 @@ export type DockerExecOptions = {
20
20
  // stay visible to the user while start() still inspects stderr to detect the
21
21
  // missing-credential-helper failure and decide whether to retry.
22
22
  captureStderr?: boolean
23
+ // Piped commands normally retain complete output. Long-running callers can
24
+ // still drain without retaining stdout and keep only stderr's diagnostic tail.
25
+ captureStdout?: boolean
26
+ maxCapturedStderrBytes?: number
23
27
  }
24
28
 
25
29
  export type DockerExec = (args: string[], options?: DockerExecOptions) => Promise<DockerExecResult>
@@ -83,9 +87,9 @@ export const defaultDockerExec: DockerExec = async (args, options) => {
83
87
  signal: options?.signal,
84
88
  env,
85
89
  })
86
- const exitCode = await proc.exited
87
- const stdout = await new Response(proc.stdout).text()
88
- const stderr = await new Response(proc.stderr).text()
90
+ const stdoutPromise = readCapturedStream(proc.stdout, options?.captureStdout === false ? 0 : undefined)
91
+ const stderrPromise = readCapturedStream(proc.stderr, options?.maxCapturedStderrBytes)
92
+ const [exitCode, stdout, stderr] = await Promise.all([proc.exited, stdoutPromise, stderrPromise])
89
93
  return { exitCode, stdout, stderr }
90
94
  } catch (error) {
91
95
  if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') {
@@ -95,6 +99,29 @@ export const defaultDockerExec: DockerExec = async (args, options) => {
95
99
  }
96
100
  }
97
101
 
102
+ export async function readCapturedStream(stream: ReadableStream<Uint8Array>, maxBytes?: number): Promise<string> {
103
+ if (maxBytes === undefined) return await new Response(stream).text()
104
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw new RangeError('maxBytes must be a non-negative integer')
105
+
106
+ const reader = stream.getReader()
107
+ let tail = Buffer.alloc(0)
108
+ try {
109
+ for (;;) {
110
+ const { done, value } = await reader.read()
111
+ if (done) break
112
+ if (maxBytes === 0) continue
113
+ const chunk = Buffer.from(value)
114
+ tail =
115
+ chunk.length >= maxBytes
116
+ ? chunk.subarray(chunk.length - maxBytes)
117
+ : Buffer.concat([tail, chunk]).subarray(-maxBytes)
118
+ }
119
+ } finally {
120
+ reader.releaseLock()
121
+ }
122
+ return tail.toString('utf8')
123
+ }
124
+
98
125
  // Streams a docker child's stdout straight to the parent terminal while teeing
99
126
  // stderr to BOTH the terminal and a buffer. A plain `stderr: 'inherit'` would
100
127
  // keep the build output live but leave start() blind to the failure reason;