typeclaw 0.48.8 → 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.
@@ -289,6 +289,8 @@ export type SlackBotAdapterOptions = {
289
289
  // tests and ad-hoc adapter constructions stay backwards-compatible.
290
290
  selfAliasesRef?: () => readonly string[]
291
291
  fetchImpl?: typeof fetch
292
+ createClient?: () => SlackBotClient
293
+ createListener?: (client: SlackBotClient, appToken: string) => SlackBotListener
292
294
  }
293
295
 
294
296
  export type SlackBotAdapter = {
@@ -1146,11 +1148,12 @@ function stringField(record: Record<string, unknown>, key: string): string | nul
1146
1148
 
1147
1149
  export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBotAdapter {
1148
1150
  const logger = options.logger ?? consoleLogger
1149
- const client = new SlackBotClient()
1151
+ const client = options.createClient?.() ?? new SlackBotClient()
1150
1152
  const fetchImpl = options.fetchImpl ?? fetch
1151
1153
  let listener: SlackBotListener | null = null
1152
1154
  let botUserId: string | null = null
1153
1155
  let teamId: string | null = null
1156
+ let socketConnected = false
1154
1157
  let started = false
1155
1158
  let inflightInbounds = 0
1156
1159
  let stopWaiters: Array<() => void> = []
@@ -1376,14 +1379,19 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1376
1379
  throw err
1377
1380
  }
1378
1381
 
1379
- listener = new SlackBotListener(client, { appToken: options.appToken })
1382
+ listener =
1383
+ options.createListener?.(client, options.appToken) ??
1384
+ new SlackBotListener(client, { appToken: options.appToken })
1380
1385
  listener.on('connected', (info) => {
1386
+ socketConnected = started
1381
1387
  logger.info(`[slack-bot] connected (app_id=${info.app_id ?? 'unknown'})`)
1382
1388
  })
1383
1389
  listener.on('disconnected', () => {
1390
+ socketConnected = false
1384
1391
  logger.warn('[slack-bot] disconnected; SDK will reconnect with backoff')
1385
1392
  })
1386
1393
  listener.on('error', (err) => {
1394
+ if (recordValue(err)?.code === 'disconnect_terminal') socketConnected = false
1387
1395
  logger.error(`[slack-bot] socket-mode error: ${describeError(err)}`)
1388
1396
  })
1389
1397
  listener.on('message', ({ ack, event }) => {
@@ -1461,6 +1469,7 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1461
1469
  listener = null
1462
1470
  botUserId = null
1463
1471
  teamId = null
1472
+ socketConnected = false
1464
1473
  started = false
1465
1474
  logger.error(`[slack-bot] listener start failed: ${describeError(err)}`)
1466
1475
  throw err
@@ -1470,6 +1479,7 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1470
1479
  async stop(): Promise<void> {
1471
1480
  if (!started) return
1472
1481
  started = false
1482
+ socketConnected = false
1473
1483
  options.router.unregisterOutbound('slack-bot', outboundCallback)
1474
1484
  options.router.unregisterReaction('slack-bot', reactionCallback)
1475
1485
  options.router.unregisterRemoveReaction('slack-bot', removeReactionCallback)
@@ -1495,7 +1505,7 @@ export function createSlackBotAdapter(options: SlackBotAdapterOptions): SlackBot
1495
1505
  },
1496
1506
 
1497
1507
  isConnected(): boolean {
1498
- return botUserId !== null && teamId !== null
1508
+ return started && socketConnected
1499
1509
  },
1500
1510
  }
1501
1511
  }
@@ -160,6 +160,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
160
160
  let channelTeamMap = new Map<string, string>()
161
161
  let sentEchoes: SentEcho[] = []
162
162
  let started = false
163
+ let realtimeConnected = false
163
164
  let inflightInbounds = 0
164
165
  let stopWaiters: Array<() => void> = []
165
166
 
@@ -270,6 +271,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
270
271
  async start(): Promise<void> {
271
272
  if (started) return
272
273
  started = true
274
+ realtimeConnected = false
273
275
  try {
274
276
  const account = await (options.credentialsStore ?? null)?.getAccount()
275
277
  if (account === null || account === undefined) {
@@ -296,6 +298,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
296
298
  logger.info(`[teams] authenticated as ${self.displayName}, ${chatsById.size} chats`)
297
299
  } catch (err) {
298
300
  started = false
301
+ realtimeConnected = false
299
302
  self = null
300
303
  loadedAccount = null
301
304
  chatsById = new Map()
@@ -327,6 +330,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
327
330
  // just don't get proactively woken by inbound Teams messages.
328
331
  const degradeToRestOnly = (cause: Error): void => {
329
332
  if (listener !== activeListener) return
333
+ realtimeConnected = false
330
334
  listener?.stop()
331
335
  listener = null
332
336
  logger.warn(
@@ -336,10 +340,12 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
336
340
 
337
341
  listener.on('connected', () => {
338
342
  if (!isActive()) return
343
+ realtimeConnected = true
339
344
  logger.info('[teams] connected')
340
345
  })
341
346
  listener.on('disconnected', () => {
342
347
  if (!isActive()) return
348
+ realtimeConnected = false
343
349
  logger.warn('[teams] disconnected')
344
350
  })
345
351
  // A post-connect `error` for the unrecoverable id_token failure would
@@ -380,6 +386,7 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
380
386
  async stop(): Promise<void> {
381
387
  if (!started) return
382
388
  started = false
389
+ realtimeConnected = false
383
390
  options.router.unregisterOutbound('teams', outboundCallback)
384
391
  options.router.unregisterSelfIdentity('teams', selfIdentityResolver)
385
392
  options.router.unregisterHistory('teams', historyCallback)
@@ -397,13 +404,8 @@ export function createTeamsAdapter(options: TeamsAdapterOptions): TeamsAdapter {
397
404
  sentEchoes = []
398
405
  },
399
406
 
400
- // REST auth being live is what makes the adapter usable (send/read); the
401
- // realtime listener is a best-effort add-on. Returning true here even in
402
- // REST-only mode is deliberate: the channel manager restarts any adapter
403
- // whose isConnected() is false, which would pointlessly churn a healthy
404
- // REST-only Teams adapter that can never get a realtime listener.
405
407
  isConnected(): boolean {
406
- return started && self !== null
408
+ return started && self !== null && realtimeConnected
407
409
  },
408
410
  }
409
411
  }
@@ -61,9 +61,11 @@ export function renderPrVerdictStandDownReminder(args: { prNumber: number; verdi
61
61
  return (
62
62
  `<system-reminder>\n` +
63
63
  `Another session in this agent has already posted a formal ${args.verdict} review for PR #${args.prNumber}. ` +
64
- `Do not submit your own ${args.verdict} (or any redundant verdict) for this PR this turn unless new ` +
64
+ `This notice applies ONLY to formal PR-level verdicts. Do not submit your own ${args.verdict} (or any redundant ` +
65
+ `verdict) for this PR this turn unless new ` +
65
66
  `information genuinely invalidates that result (e.g. new commits, or a different verdict warranted by ` +
66
- `fresh evidence). You may still reply to inline review comments / threads as normal.\n` +
67
+ `fresh evidence). It does NOT discharge this session's inline review-thread close-out: you must still reply to ` +
68
+ `the inline thread as normal, resolving it if addressed or leaving it open with an explanation.\n` +
67
69
  `</system-reminder>`
68
70
  )
69
71
  }
@@ -192,6 +192,8 @@ type AdapterEntry = {
192
192
  adapter: AnyAdapter
193
193
  credentialSignature: string
194
194
  disconnectedSinceMs: number | null
195
+ nextRecoveryRestartAtMs: number | null
196
+ recoveryRestartAttempts: number
195
197
  recoveryRestartQueued: boolean
196
198
  }
197
199
 
@@ -360,6 +362,7 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
360
362
  )
361
363
  if (credentialsStore === null) return null
362
364
  return createInstagram({
365
+ agentDir: options.agentDir,
363
366
  router,
364
367
  configRef: () => options.channelsConfigRef()[name] ?? cfg,
365
368
  logger,
@@ -512,6 +515,8 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
512
515
  adapter,
513
516
  credentialSignature: signature,
514
517
  disconnectedSinceMs: adapter.isConnected() ? null : recoveryNow(),
518
+ nextRecoveryRestartAtMs: null,
519
+ recoveryRestartAttempts: 0,
515
520
  recoveryRestartQueued: false,
516
521
  })
517
522
  return { status: 'started' }
@@ -722,6 +727,8 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
722
727
  for (const [name, entry] of live) {
723
728
  if (entry.adapter.isConnected()) {
724
729
  entry.disconnectedSinceMs = null
730
+ entry.nextRecoveryRestartAtMs = null
731
+ entry.recoveryRestartAttempts = 0
725
732
  entry.recoveryRestartQueued = false
726
733
  continue
727
734
  }
@@ -731,7 +738,11 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
731
738
  continue
732
739
  }
733
740
  const disconnectedForMs = now - entry.disconnectedSinceMs
734
- if (disconnectedForMs < recoveryDisconnectedGraceMs || entry.recoveryRestartQueued) continue
741
+ const nextRestartAtMs = Math.max(
742
+ entry.disconnectedSinceMs + recoveryDisconnectedGraceMs,
743
+ entry.nextRecoveryRestartAtMs ?? Number.NEGATIVE_INFINITY,
744
+ )
745
+ if (now < nextRestartAtMs || entry.recoveryRestartQueued) continue
735
746
  entry.recoveryRestartQueued = true
736
747
  logger.warn(
737
748
  `[channels] adapter "${name}" disconnected for ${Math.round(disconnectedForMs)}ms; restarting adapter`,
@@ -756,6 +767,12 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
756
767
  return running && queuedEpoch === lifecycleEpoch && cfg !== undefined && cfg.enabled !== false
757
768
  })
758
769
  applyStartResult(name, latestCfg, result)
770
+ const replacement = live.get(name)
771
+ if (replacement !== undefined && !replacement.adapter.isConnected()) {
772
+ const attempts = entry.recoveryRestartAttempts + 1
773
+ replacement.recoveryRestartAttempts = attempts
774
+ replacement.nextRecoveryRestartAtMs = recoveryNow() + retryDelayMs(attempts)
775
+ }
759
776
  } catch (err) {
760
777
  const cfg = options.channelsConfigRef()[name]
761
778
  if (running && queuedEpoch === lifecycleEpoch && cfg !== undefined && cfg.enabled !== false) {
@@ -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,