typeclaw 0.50.0 → 0.51.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.
Files changed (90) hide show
  1. package/dist/types/agent/bash-sandbox-env.d.ts +15 -0
  2. package/dist/types/agent/bash-sandbox-proc.d.ts +8 -0
  3. package/dist/types/agent/bash-sandbox.d.ts +94 -0
  4. package/dist/types/agent/compaction.d.ts +4 -4
  5. package/dist/types/agent/idle-compaction.d.ts +1 -0
  6. package/dist/types/agent/index.d.ts +5 -17
  7. package/dist/types/agent/output-allowance.d.ts +4 -0
  8. package/dist/types/agent/plugin-tools.d.ts +4 -75
  9. package/dist/types/agent/system-prompt-composition.d.ts +17 -0
  10. package/dist/types/agent/tools/ddg.d.ts +9 -0
  11. package/dist/types/agent/tools/stream-snapshot.d.ts +1 -1
  12. package/dist/types/agent/tools/webfetch/tool.d.ts +1 -1
  13. package/dist/types/channels/github-review-check.d.ts +1 -1
  14. package/dist/types/channels/router.d.ts +11 -49
  15. package/dist/types/config/config.d.ts +24 -11
  16. package/dist/types/config/providers.d.ts +3 -1
  17. package/dist/types/container/start.d.ts +1 -0
  18. package/dist/types/eval/cell.d.ts +26 -0
  19. package/dist/types/eval/config.d.ts +19 -0
  20. package/dist/types/eval/dispatch.d.ts +7 -0
  21. package/dist/types/eval/kernel.d.ts +28 -0
  22. package/dist/types/eval/process.d.ts +23 -0
  23. package/dist/types/eval/protocol.d.ts +34 -0
  24. package/dist/types/eval/sandbox.d.ts +10 -0
  25. package/dist/types/eval/tool.d.ts +17 -0
  26. package/dist/types/eval/wire.d.ts +33 -0
  27. package/dist/types/sandbox/env-exposure.d.ts +2 -0
  28. package/package.json +5 -5
  29. package/src/agent/bash-sandbox-env.ts +104 -0
  30. package/src/agent/bash-sandbox-proc.ts +70 -0
  31. package/src/agent/bash-sandbox.ts +225 -0
  32. package/src/agent/compaction.ts +22 -10
  33. package/src/agent/idle-compaction.ts +7 -3
  34. package/src/agent/index.ts +66 -157
  35. package/src/agent/output-allowance.ts +7 -0
  36. package/src/agent/plugin-tools.ts +29 -379
  37. package/src/agent/session-origin.ts +2 -1
  38. package/src/agent/subagent-completion-reminder.ts +2 -2
  39. package/src/agent/system-prompt-composition.ts +141 -0
  40. package/src/agent/system-prompt.ts +4 -4
  41. package/src/agent/todo/scope.ts +1 -1
  42. package/src/agent/tools/ddg.ts +71 -11
  43. package/src/agent/tools-without-local-file-operands.ts +4 -0
  44. package/src/browser/fill-secret.ts +307 -0
  45. package/src/bundled-plugins/explorer/explorer.ts +1 -1
  46. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +40 -16
  47. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +12 -7
  48. package/src/bundled-plugins/github-cli-auth/index.ts +10 -1
  49. package/src/bundled-plugins/managed-browser/index.ts +107 -2
  50. package/src/bundled-plugins/memory/dreaming.ts +4 -1
  51. package/src/bundled-plugins/memory/load-memory.ts +2 -4
  52. package/src/bundled-plugins/memory/memory-logger.ts +74 -2
  53. package/src/bundled-plugins/memory/transcript-preload.ts +103 -0
  54. package/src/bundled-plugins/memory/vector/hybrid.ts +25 -14
  55. package/src/bundled-plugins/security/policies/private-surface-read.ts +166 -201
  56. package/src/channels/adapters/discord-bot-reference.ts +5 -4
  57. package/src/channels/adapters/discord-bot.ts +1 -0
  58. package/src/channels/adapters/discord-classify.ts +8 -3
  59. package/src/channels/adapters/discord.ts +29 -0
  60. package/src/channels/github-review-check.ts +5 -1
  61. package/src/channels/github-review-verdict-coordinator.ts +68 -2
  62. package/src/channels/router.ts +88 -107
  63. package/src/channels/subagent-completion-bridge.ts +3 -2
  64. package/src/cli/hostd.ts +3 -0
  65. package/src/config/config.ts +15 -0
  66. package/src/config/providers.ts +10 -4
  67. package/src/container/start.ts +37 -1
  68. package/src/doctor/checks.ts +25 -16
  69. package/src/doctor/index.ts +48 -12
  70. package/src/doctor/operational-incidents.ts +16 -1
  71. package/src/doctor/plugin-bridge.ts +14 -1
  72. package/src/doctor/stage.ts +14 -0
  73. package/src/doctor/types.ts +6 -0
  74. package/src/eval/cell.ts +93 -0
  75. package/src/eval/config.ts +32 -0
  76. package/src/eval/dispatch.ts +67 -0
  77. package/src/eval/entry.ts +261 -0
  78. package/src/eval/kernel.ts +154 -0
  79. package/src/eval/process.ts +113 -0
  80. package/src/eval/protocol.ts +26 -0
  81. package/src/eval/redeclare.ts +174 -0
  82. package/src/eval/sandbox.ts +114 -0
  83. package/src/eval/tool.ts +98 -0
  84. package/src/eval/wire.ts +93 -0
  85. package/src/operations/classify-tool-outcome.ts +1 -1
  86. package/src/plugin/core-tool-names.ts +6 -1
  87. package/src/sandbox/env-exposure.ts +20 -0
  88. package/src/server/index.ts +46 -11
  89. package/src/skills/typeclaw-config/SKILL.md +20 -2
  90. package/typeclaw.schema.json +52 -0
@@ -14,6 +14,7 @@ export type DiscordMessagePointer = {
14
14
  }
15
15
 
16
16
  export async function enrichDiscordMessageReferences(args: {
17
+ adapter: 'discord' | 'discord-bot'
17
18
  text: string
18
19
  reply?: DiscordMessagePointer
19
20
  fetchMessage: DiscordReferenceFetch
@@ -25,7 +26,7 @@ export async function enrichDiscordMessageReferences(args: {
25
26
  if (args.reply !== undefined) {
26
27
  const parent = await fetchSafely(args.fetchMessage, args.reply)
27
28
  if (parent !== null) {
28
- sources.push(toSource(parent))
29
+ sources.push(toSource(args.adapter, parent))
29
30
  hasReply = true
30
31
  }
31
32
  }
@@ -33,7 +34,7 @@ export async function enrichDiscordMessageReferences(args: {
33
34
  const links = extractDiscordMessageLinks(args.text).slice(0, args.linkLimit ?? 3)
34
35
  for (const link of links) {
35
36
  const message = await fetchSafely(args.fetchMessage, link)
36
- if (message !== null) sources.push(toSource(message))
37
+ if (message !== null) sources.push(toSource(args.adapter, message))
37
38
  }
38
39
 
39
40
  if (sources.length === 0) return { text: args.text }
@@ -68,9 +69,9 @@ async function fetchSafely(
68
69
  }
69
70
  }
70
71
 
71
- function toSource(message: DiscordResolvedReference): QuoteAnchorSource {
72
+ function toSource(adapter: 'discord' | 'discord-bot', message: DiscordResolvedReference): QuoteAnchorSource {
72
73
  return {
73
- adapter: 'discord-bot',
74
+ adapter,
74
75
  authorId: message.authorId,
75
76
  authorName: message.authorName,
76
77
  text: message.text,
@@ -1275,6 +1275,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
1275
1275
  const hintedText = addDiscordMentionHints(verdict.payload.text, mentionUserMap(event.mentions), { botUserId })
1276
1276
  const replyMessageId = event.message_reference?.message_id
1277
1277
  const referenceResult = await enrichDiscordMessageReferences({
1278
+ adapter: 'discord-bot',
1278
1279
  text: hintedText,
1279
1280
  ...(replyMessageId !== undefined
1280
1281
  ? { reply: { channelId: event.message_reference?.channel_id ?? event.channel_id, messageId: replyMessageId } }
@@ -8,13 +8,18 @@ import { encodeDiscordReactionRef } from './discord-reactions'
8
8
 
9
9
  export type DiscordInboundMessageEvent = DiscordGatewayMessageCreateEvent
10
10
 
11
- // WORKAROUND: the USER-token SDK type omits `author.bot` and
12
- // `message_reference`, but the listener spreads the raw Discord payload
13
- // (`{ ...d }`), so both fields exist at runtime. Narrow locally instead of
11
+ // WORKAROUND: the USER-token SDK type omits `author.bot`, `message_reference`,
12
+ // and `referenced_message`, but the listener spreads the raw Discord payload
13
+ // (`{ ...d }`), so they exist at runtime. Narrow locally instead of
14
14
  // augmenting the SDK type globally — do not "simplify" this away.
15
15
  export type RawDiscordMessageCreateEvent = DiscordGatewayMessageCreateEvent & {
16
16
  author: { bot?: boolean }
17
17
  message_reference?: { message_id?: string; channel_id?: string; guild_id?: string }
18
+ referenced_message?: {
19
+ id: string
20
+ content: string
21
+ author: { id: string; username: string; global_name?: string | null }
22
+ } | null
18
23
  }
19
24
 
20
25
  export type InboundDropReason = 'self_author' | 'no_user' | 'empty_content' | 'pre_connect'
@@ -40,11 +40,13 @@ import type { DiscordAccountRecord } from '@/secrets/schema'
40
40
 
41
41
  import { describeError } from '../describe-error'
42
42
  import { createDiscordAuthorResolver } from './discord-author-resolver'
43
+ import { enrichDiscordMessageReferences, type DiscordResolvedReference } from './discord-bot-reference'
43
44
  import { createDiscordChannelResolver } from './discord-channel-resolver'
44
45
  import {
45
46
  classifyInbound,
46
47
  type DiscordAttachmentCarrier,
47
48
  type InboundDropReason,
49
+ type RawDiscordMessageCreateEvent,
48
50
  splitDiscordAttachments,
49
51
  } from './discord-classify'
50
52
  import { createDiscordUserEditMessageCallback } from './discord-edit'
@@ -356,8 +358,24 @@ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAda
356
358
  mimetype: file.content_type,
357
359
  }))
358
360
  const room = verdict.payload.isDm ? undefined : await channelResolver.resolveRoom(verdict.payload.chat)
361
+ const raw = event as RawDiscordMessageCreateEvent
362
+ const replyMessageId = raw.message_reference?.message_id
363
+ const { referenceContext } = await enrichDiscordMessageReferences({
364
+ adapter: 'discord',
365
+ text: verdict.payload.text,
366
+ ...(replyMessageId !== undefined
367
+ ? { reply: { channelId: raw.message_reference?.channel_id ?? event.channel_id, messageId: replyMessageId } }
368
+ : {}),
369
+ // Reply gateway events already carry the parent inline; only links and
370
+ // replies Discord did not expand (deleted/inaccessible parents) cost a fetch.
371
+ fetchMessage: async (channelId, messageId) =>
372
+ raw.referenced_message?.id === messageId
373
+ ? toResolvedReference(raw.referenced_message)
374
+ : toResolvedReference(await client.getMessage(channelId, messageId)),
375
+ })
359
376
  const payload = {
360
377
  ...verdict.payload,
378
+ ...(referenceContext !== undefined ? { referenceContext } : {}),
361
379
  authorName: await authorResolver.resolve(verdict.payload.authorId),
362
380
  ...(room !== undefined ? { room } : {}),
363
381
  ...(attachments.length > 0 ? { attachments } : {}),
@@ -580,6 +598,17 @@ function parseDiscordTimestamp(timestamp: string): number {
580
598
  return Number.isFinite(millis) ? millis : 0
581
599
  }
582
600
 
601
+ function toResolvedReference(message: {
602
+ content: string
603
+ author: { id: string; username: string; global_name?: string | null }
604
+ }): DiscordResolvedReference {
605
+ return {
606
+ authorId: message.author.id,
607
+ authorName: message.author.global_name ?? message.author.username,
608
+ text: message.content,
609
+ }
610
+ }
611
+
583
612
  const DISCORD_ATTACHMENT_HOSTS = new Set(['cdn.discordapp.com', 'media.discordapp.net'])
584
613
 
585
614
  function clampLimit(requested: number, max: number): number {
@@ -301,18 +301,22 @@ export class GithubReviewCheckTracker {
301
301
 
302
302
  // For a verdict posted without the reviewed head: only reviews that already
303
303
  // finished on this PR can be the ones it reports.
304
+ // When a reviewed head is supplied, complete only that commit's posting reviews.
304
305
  async completePostingReviews(
305
306
  repo: string,
306
307
  pullRequest: number,
307
308
  state: 'APPROVED' | 'CHANGES_REQUESTED' | 'COMMENTED',
309
+ headSha?: string,
308
310
  ): Promise<void> {
309
311
  const canonical = canonicalGithubRepo(repo)
312
+ const normalizedHead = headSha?.toLocaleLowerCase()
310
313
  const matching = [...this.leases.values()].filter(
311
314
  (lease) =>
312
315
  lease.outcome === undefined &&
313
316
  lease.phase === 'posting' &&
314
317
  lease.key.repo === canonical &&
315
- lease.key.pullRequest === pullRequest,
318
+ lease.key.pullRequest === pullRequest &&
319
+ (normalizedHead === undefined || lease.key.headSha === normalizedHead),
316
320
  )
317
321
  await Promise.all(matching.map((lease) => this.finish(lease, { kind: 'verdict', state })))
318
322
  }
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
 
3
+ import { githubReviewChecks } from './github-review-check'
3
4
  import type { ReviewVerdict } from './github-review-turn-ledger'
4
5
  import type { GithubReviewFollowupRound } from './types'
5
6
 
@@ -131,6 +132,11 @@ const ROUND_HEAD_MOVED_REASON =
131
132
  'The pull request head moved past the commit this review round covers, so a verdict from this round would describe stale code. ' +
132
133
  'Do not submit it; the new push starts its own review round.'
133
134
 
135
+ const ROUND_SUPERSEDED_REASON =
136
+ 'A newer review round for this pull request replaced the one this session carries, at the same head commit. ' +
137
+ 'Its designated session submits the formal verdict, so do not submit one from this session and do not reply now: call `skip_response`. ' +
138
+ 'Once that verdict lands, close out only this thread with the technical outcome; never mention sessions, carriers, or review rounds on the PR.'
139
+
134
140
  function reviewedHeadRequiredReason(currentHead: string): string {
135
141
  return (
136
142
  `The pull request head moved to ${currentHead} after this review round opened. ` +
@@ -234,6 +240,11 @@ let reviewRounds = new Map<string, ReviewRoundState>()
234
240
  let expiredReviewRoundKeys = new Set<string>()
235
241
  type ReplyReviewRoundGeneration = { round: GithubReviewFollowupRound; createdAt: number }
236
242
  let replyReviewRoundGenerations = new Map<string, ReplyReviewRoundGeneration>()
243
+ // Round key -> key of the same-head counterpart it joined. Queued and persisted
244
+ // inbounds still carry the joiner's round and re-register it later; the alias
245
+ // keeps resolving to the canonical round after it completes, where the
246
+ // pending-only counterpart lookup would no longer find it.
247
+ let joinedRoundAliases = new Map<string, string>()
237
248
  let tokenSeq = 0
238
249
 
239
250
  export function githubReviewRoundKey(round: GithubReviewFollowupRound): string {
@@ -261,7 +272,7 @@ export function registerOrJoinReplyReviewRound(input: {
261
272
  replyReviewRoundGenerations.delete(correlationKey)
262
273
  }
263
274
 
264
- const round: GithubReviewFollowupRound = {
275
+ const candidate: GithubReviewFollowupRound = {
265
276
  kind: 'reply',
266
277
  roundId: (input.generateRoundId ?? randomUUID)(),
267
278
  workspace: input.workspace,
@@ -269,8 +280,8 @@ export function registerOrJoinReplyReviewRound(input: {
269
280
  headSha: input.headSha,
270
281
  carrierThread: input.thread,
271
282
  }
283
+ const round = registerGithubReviewRound(candidate, currentTime, now) ?? candidate
272
284
  replyReviewRoundGenerations.set(correlationKey, { round, createdAt: currentTime })
273
- registerGithubReviewRound(round, currentTime, now)
274
285
  return round
275
286
  }
276
287
 
@@ -281,6 +292,25 @@ export function registerGithubReviewRound(
281
292
  ): GithubReviewFollowupRound | null {
282
293
  const key = githubReviewRoundKey(round)
283
294
  if (expiredReviewRoundKeys.has(key)) return null
295
+ // A push round and a reply round on the same head ask for the same fresh
296
+ // verdict. A push re-check and a reply to the blocking review routinely land
297
+ // together, and evicting one for the other split sibling threads across
298
+ // rounds: the evicted carrier's verdict was then refused as superseded while
299
+ // the surviving round's carrier never owned the blocking obligation. Join the
300
+ // pending counterpart instead so one carrier answers for the head.
301
+ if (activeReviewRoundState(key, now) === undefined) {
302
+ const aliasKey = joinedRoundAliases.get(key)
303
+ if (aliasKey !== undefined) {
304
+ const canonical = activeReviewRoundState(aliasKey, now)
305
+ if (canonical !== undefined) return canonical.round
306
+ joinedRoundAliases.delete(key)
307
+ }
308
+ const counterpart = pendingSameHeadCounterpart(round, now)
309
+ if (counterpart !== undefined) {
310
+ joinedRoundAliases.set(key, githubReviewRoundKey(counterpart.round))
311
+ return counterpart.round
312
+ }
313
+ }
284
314
  for (const [candidateKey, state] of reviewRounds) {
285
315
  if (activeReviewRoundState(candidateKey, now) === undefined) continue
286
316
  if (candidateKey !== key && state.round.workspace === round.workspace && state.round.prNumber === round.prNumber) {
@@ -316,6 +346,9 @@ export function restoreGithubReviewRound(
316
346
  const registered = registerGithubReviewRound(round, createdAt, now)
317
347
  if (registered === null) return null
318
348
  const key = githubReviewRoundKey(registered)
349
+ // Joined a same-head counterpart: its live state is authoritative, and this
350
+ // record's persisted status describes a different round.
351
+ if (key !== githubReviewRoundKey(round)) return registered
319
352
  // Restoration is monotonic: a persisted `pending` record must never overwrite
320
353
  // an unexpired round this process already completed. A sibling session that
321
354
  // was idle-GC'd before completion still carries the stale status, and letting
@@ -459,6 +492,18 @@ export function isGithubReviewRoundSuperseded(round: GithubReviewFollowupRound,
459
492
  )
460
493
  }
461
494
 
495
+ function pendingSameHeadCounterpart(round: GithubReviewFollowupRound, now: () => number): ReviewRoundState | undefined {
496
+ expireReviewRounds(now)
497
+ return Array.from(reviewRounds.values()).find(
498
+ (state) =>
499
+ state.status === 'pending' &&
500
+ state.round.kind !== round.kind &&
501
+ state.round.workspace === round.workspace &&
502
+ state.round.prNumber === round.prNumber &&
503
+ state.round.headSha === round.headSha,
504
+ )
505
+ }
506
+
462
507
  function pendingPushRoundForPr(
463
508
  target: { workspace: string; prNumber: number },
464
509
  now: () => number = Date.now,
@@ -596,6 +641,9 @@ export function abortGithubReviewStateForPr(
596
641
  if (generation.round.workspace !== workspace || generation.round.prNumber !== prNumber) continue
597
642
  replyReviewRoundGenerations.delete(generationKey)
598
643
  }
644
+ for (const aliasKey of joinedRoundAliases.keys()) {
645
+ if (aliasKey.startsWith(`${key}#`)) joinedRoundAliases.delete(aliasKey)
646
+ }
599
647
 
600
648
  // A draft abort abandons local work, not output already observed on GitHub.
601
649
  // Keeping recentLandedByPr prevents a later ready event from duplicating it.
@@ -711,6 +759,17 @@ export function createApproveIdempotencyGuard(deps: {
711
759
  remote.ok &&
712
760
  remote.effective === 'CHANGES_REQUESTED'
713
761
 
762
+ const reviewedHeadSha = args.reviewedHeadSha ?? args.round?.headSha
763
+ if (
764
+ args.verdict === 'APPROVE' &&
765
+ remote.ok &&
766
+ remote.effective === 'APPROVED' &&
767
+ headSha !== null &&
768
+ (reviewedHeadSha === undefined || sameSha(reviewedHeadSha, headSha))
769
+ ) {
770
+ void githubReviewChecks.completePostingReviews(args.workspace, args.prNumber, 'APPROVED', headSha)
771
+ }
772
+
714
773
  // Layer 3 — duplicate-review cooldown. A recently-landed SAME verdict on the
715
774
  // SAME (or uncertain) head blocks a redundant re-publication for the window. It
716
775
  // fires on a bare NONE (read-after-write lag, the original shield) AND on the
@@ -869,6 +928,12 @@ async function evaluateRoundEligibility(
869
928
  // Re-read ownership after the await: a round registered meanwhile evicted this
870
929
  // one, and the registration below would evict it right back.
871
930
  const superseded = isGithubReviewRoundSuperseded(activeRound, now)
931
+ if (superseded && currentRoundHead === activeRound.headSha) {
932
+ logger.warn(
933
+ `[github] review round superseded at unchanged head pr=${activeRound.workspace}#${activeRound.prNumber} round=${activeRound.roundId} head=${currentRoundHead}`,
934
+ )
935
+ return { block: true, kind: 'round-ineligible', reason: ROUND_SUPERSEDED_REASON }
936
+ }
872
937
  if (superseded || (currentRoundHead !== activeRound.headSha && activeRound.kind === 'push')) {
873
938
  logger.warn(
874
939
  `[github] review round head moved pr=${activeRound.workspace}#${activeRound.prNumber} round=${activeRound.roundId} round_head=${activeRound.headSha} current_head=${currentRoundHead}${superseded ? ' superseded=true' : ''}`,
@@ -1022,6 +1087,7 @@ export function __resetReviewVerdictGuardForTest(): void {
1022
1087
  reviewRounds = new Map<string, ReviewRoundState>()
1023
1088
  expiredReviewRoundKeys = new Set<string>()
1024
1089
  replyReviewRoundGenerations = new Map<string, ReplyReviewRoundGeneration>()
1090
+ joinedRoundAliases = new Map<string, string>()
1025
1091
  tokenSeq = 0
1026
1092
  processEffectiveResolver = async () => ({ ok: false })
1027
1093
  processHeadShaResolver = async () => null
@@ -1,5 +1,4 @@
1
1
  import { randomUUID } from 'node:crypto'
2
- import { statSync } from 'node:fs'
3
2
  import { basename } from 'node:path'
4
3
 
5
4
  import { createAssistantMessageEventStream, type AssistantMessage, type ToolResultMessage } from '@earendil-works/pi-ai'
@@ -561,38 +560,16 @@ export const SEND_RATE_WARN_THRESHOLD = 3
561
560
  export const OUTBOUND_FLOOD_ERROR = 'outbound message denied: content looks like a repeated-character flood'
562
561
 
563
562
  /**
564
- * Soft freshness boundary: the age of the last engaged inbound past which the
565
- * provider's server-side KV prompt-cache for this session's prefix is assumed
566
- * cold. Set to the LLM provider's KV-cache TTL (5 min) so a session reused
567
- * WITHIN this window is guaranteed a cache hit on the provider side.
563
+ * Roll over only after more than 60 minutes without an engaged inbound.
564
+ * Continuity of an active conversation outweighs one cold prefix resend;
565
+ * compaction bounds the transcript carried by that resend.
568
566
  *
569
- * Reaching this boundary no longer forces an immediate rollover. Between the
570
- * soft boundary and SESSION_GRACE_HARD_TTL_MS, the live path defers to a
571
- * cost-aware grace decision (see `isGraceWorthReusing`): a session whose fixed
572
- * base context (rendered system prompt + injected memory + prefetched channel
573
- * context) still costs more to rebuild than its accumulated transcript is
574
- * reused for one more turn rather than torn down. This targets the common
575
- * channel shape — a human replying a few minutes past the cache TTL — where a
576
- * full cold-start rebuild of a large memory/index-mode base context dominates
577
- * the cost of carrying a modest transcript forward.
578
- *
579
- * Unlike SESSION_IDLE_MS (which evicts the in-memory entry without rollover), a
580
- * rollover triggers a full tearDownLive + recreate on the next engaged inbound.
581
- * The old session's transcript is preserved on disk; only the in-memory live
582
- * entry and sessions.json pointer are replaced.
583
- */
584
- export const SESSION_FRESHNESS_TTL_MS = 5 * 60 * 1000
585
-
586
- /**
587
- * Hard ceiling on the cost-aware grace window. Past this age the live session is
588
- * rolled over unconditionally regardless of base-vs-transcript cost: the grace
589
- * decision only defers rollover, it never makes the session immortal. Bounding
590
- * grace at 2x the soft TTL keeps a never-quite-idle session from accumulating an
591
- * ever-growing, fully-uncached prefix (every turn past the soft boundary re-sends
592
- * the whole prefix at no provider-cache discount) and prevents grace from
593
- * silently becoming an unbounded TTL increase.
567
+ * SESSION_IDLE_MS (30 minutes) only evicts the in-memory entry: the next inbound
568
+ * within this freshness window rehydrates the same session file without rollover.
569
+ * A rollover tears down the live entry and replaces the sessions.json pointer;
570
+ * the old transcript remains on disk.
594
571
  */
595
- export const SESSION_GRACE_HARD_TTL_MS = 10 * 60 * 1000
572
+ export const SESSION_FRESHNESS_TTL_MS = 60 * 60 * 1000
596
573
 
597
574
  /**
598
575
  * Leak guard — NOT a freshness cap. A running background subagent pins its parent
@@ -616,37 +593,6 @@ export const SESSION_GRACE_HARD_TTL_MS = 10 * 60 * 1000
616
593
  */
617
594
  export const SESSION_CHILD_STUCK_BACKSTOP_MS = 6 * 60 * 60 * 1000
618
595
 
619
- /**
620
- * Cost-aware grace decision for the soft→hard TTL band. Returns true when reusing
621
- * the (now cache-cold) live session is cheaper than a fresh cold-start.
622
- *
623
- * After the soft TTL the provider prefix is cold either way, so the choice is:
624
- * - rollover: pay to rebuild the fixed base context (system prompt + memory +
625
- * prefetched context) plus a fresh first model call, OR
626
- * - reuse: re-send the cold base context PLUS the accumulated transcript.
627
- *
628
- * Rollover only wins once the transcript a reused session would carry forward
629
- * exceeds the base context a rollover would rebuild. We approximate both with the
630
- * session transcript file: `baseContextBytes` is its size captured right after
631
- * cold-start (the rendered prompt before any user turn), and the live delta is
632
- * the growth since. While `baseContextBytes > transcriptDeltaBytes`, the fixed
633
- * rebuild is the larger cost and grace is worth it. A `baseContextBytes` of 0
634
- * (no transcript path available) disables grace — fail closed to the prior
635
- * roll-over-at-soft-TTL behavior.
636
- */
637
- export function isGraceWorthReusing(baseContextBytes: number, transcriptDeltaBytes: number): boolean {
638
- if (baseContextBytes <= 0) return false
639
- return baseContextBytes > transcriptDeltaBytes
640
- }
641
-
642
- function defaultMeasureTranscriptBytes(path: string): number {
643
- try {
644
- return statSync(path).size
645
- } catch {
646
- return 0
647
- }
648
- }
649
-
650
596
  // Watchdog ceiling for ensureLive's full async chain (resolve names →
651
597
  // fetch membership → open session manager → persist mapping → prefetch
652
598
  // history). A legitimate cold-start completes in well under a second;
@@ -957,6 +903,10 @@ type LiveSession = {
957
903
  })
958
904
  | null
959
905
  githubReviewThreadCloseoutDecisionTurn: number | null
906
+ // When this session last resolved its review thread. A reply written before
907
+ // that resolution was already answered by it, so it must not re-arm the
908
+ // close-out obligation and force a duplicate reply or the canned fallback.
909
+ githubReviewThreadResolvedAt: { rootCommentId: string; at: number } | null
960
910
  // Round key of a close-out that arrived while the round was still pending
961
911
  // completion. Replayed once the round completes; see replayPendingRoundCloseouts.
962
912
  pendingGithubReviewRoundCloseout: string | null
@@ -999,12 +949,6 @@ type LiveSession = {
999
949
  promptInFlight: boolean
1000
950
  lastInboundAt: number
1001
951
  recentMessages: SessionActivity[]
1002
- // Transcript-file size (bytes) captured immediately after cold-start, before
1003
- // any user turn — a proxy for the fixed base-context rebuild cost (rendered
1004
- // system prompt + injected memory + prefetched channel context). Read by the
1005
- // soft-TTL grace decision against the current transcript size to weigh reuse
1006
- // vs rollover. 0 when no transcript path is available, which disables grace.
1007
- baseContextBytes: number
1008
952
  firstUnprocessedAt: number
1009
953
  currentTurnAuthorId: string | null
1010
954
  currentTurnAuthorAdapter: AdapterId
@@ -1880,10 +1824,6 @@ export type CreateChannelRouterOptions = {
1880
1824
  // random/timer mutation. Production defaults remain Math.random and no hook.
1881
1825
  retryRandom?: () => number
1882
1826
  onRetryBackoffStart?: () => void
1883
- // Test seam: measure a transcript file's byte size for the soft-TTL grace
1884
- // decision. Defaults to a stat()-based reader returning 0 for a missing or
1885
- // unreadable file (grace then fails closed to roll-over-at-soft-TTL).
1886
- measureTranscriptBytes?: (path: string) => number
1887
1827
  // Test seam: the idle/todo continuation driver, invoked from
1888
1828
  // maybeContinueTodosChannel AFTER validateChannelTurn. Defaults to the real
1889
1829
  // runIdleContinuation. Injecting it lets a test deliver the continuation at the
@@ -2029,7 +1969,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2029
1969
  const recoveryOutbox =
2030
1970
  options.recoveryOutbox ?? new RecoveryOutbox(options.agentDir, { epoch: backgroundObligations.epoch })
2031
1971
  void ready.catch((error) => logger.error(`[channels] inbound journal initialization failed: ${describeError(error)}`))
2032
- const measureTranscriptBytes = options.measureTranscriptBytes ?? defaultMeasureTranscriptBytes
2033
1972
  const ensureLiveTimeoutMs = options.ensureLiveTimeoutMs ?? ENSURE_LIVE_TIMEOUT_MS
2034
1973
  const handoffRetryRetentionMs = options.handoffRetryRetentionMs ?? RELOAD_HANDOFF_RETENTION_MS
2035
1974
  const handoffRetryItemLimit = options.handoffRetryItemLimit ?? MAX_PENDING_RELOAD_HANDOFF_ITEMS_PER_KEY
@@ -2457,22 +2396,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2457
2396
  if (live.draining) return false
2458
2397
  if (isPinnedByRunningChild(live.sessionId, live.keyId, 'stale-rollover')) return false
2459
2398
  if (idleMs <= SESSION_FRESHNESS_TTL_MS) return false
2460
- if (idleMs > SESSION_GRACE_HARD_TTL_MS) {
2461
- logger.info(`[channels] ${live.keyId}: stale-rollover (live: ${idleMs}ms idle, past grace cap)`)
2462
- return true
2463
- }
2464
- const transcriptPath = live.getTranscriptPath?.()
2465
- const transcriptBytes = transcriptPath !== undefined ? measureTranscriptBytes(transcriptPath) : 0
2466
- const transcriptDeltaBytes = Math.max(0, transcriptBytes - live.baseContextBytes)
2467
- if (isGraceWorthReusing(live.baseContextBytes, transcriptDeltaBytes)) {
2468
- logger.info(
2469
- `[channels] ${live.keyId}: grace-reuse (live: ${idleMs}ms idle, base=${live.baseContextBytes}B delta=${transcriptDeltaBytes}B)`,
2470
- )
2471
- return false
2472
- }
2473
- logger.info(
2474
- `[channels] ${live.keyId}: stale-rollover (live: ${idleMs}ms idle, base=${live.baseContextBytes}B delta=${transcriptDeltaBytes}B)`,
2475
- )
2399
+ logger.info(`[channels] ${live.keyId}: stale-rollover (live: ${idleMs}ms idle)`)
2476
2400
  return true
2477
2401
  }
2478
2402
 
@@ -3000,7 +2924,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3000
2924
  // Restart-resume only: force rehydration of this exact (sessionId,
3001
2925
  // sessionFile) and bypass stale-rollover, so the originating session's
3002
2926
  // `typeclaw.restart-self` entry is reopened rather than rolled into a fresh
3003
- // session (a restart easily outlasts SESSION_FRESHNESS_TTL_MS). The mapping
2927
+ // session, even if the restart outlasts SESSION_FRESHNESS_TTL_MS. The mapping
3004
2928
  // is persisted only through the normal success path below — no pre-mutation
3005
2929
  // — so a reopen failure leaves the durable mapping untouched.
3006
2930
  resumeTarget?: { sessionId: string; sessionFile: string },
@@ -3022,7 +2946,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3022
2946
  adoptPendingReloadHandoff(existing)
3023
2947
  return existing
3024
2948
  }
3025
- // Rollover decision (soft TTL → cost-aware grace → hard cap) lives in
2949
+ // The 60-minute idle rollover decision lives in
3026
2950
  // shouldRolloverLive, which also skips draining sessions so a mid-prompt
3027
2951
  // turn is never aborted by a follow-up's idle check (PR #359 incident).
3028
2952
  const idleMs = now() - existing.lastInboundAt
@@ -3289,6 +3213,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3289
3213
  deferred: true,
3290
3214
  },
3291
3215
  githubReviewThreadCloseoutDecisionTurn: null,
3216
+ githubReviewThreadResolvedAt: null,
3292
3217
  pendingGithubReviewRoundCloseout: null,
3293
3218
  promptQueue: [],
3294
3219
  pendingSystemReminders: [],
@@ -3311,7 +3236,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3311
3236
  typingEpoch: 0,
3312
3237
  promptInFlight: false,
3313
3238
  lastInboundAt: now(),
3314
- baseContextBytes: 0,
3315
3239
  firstUnprocessedAt: 0,
3316
3240
  currentTurnAuthorId: null,
3317
3241
  recentMessages: [],
@@ -3509,15 +3433,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3509
3433
  liveSessions.set(keyId, live)
3510
3434
  }
3511
3435
 
3512
- // Snapshot the rendered base context size now, after prefetch and before
3513
- // any user turn, so the soft-TTL grace decision can later compare it
3514
- // against transcript growth. Only meaningful on cold-start (a rehydrated
3515
- // session's file already holds prior conversation, not a clean base).
3516
- const transcriptPathForBase = live.getTranscriptPath?.()
3517
- if (isColdStart && transcriptPathForBase !== undefined) {
3518
- live.baseContextBytes = measureTranscriptBytes(transcriptPathForBase)
3519
- }
3520
-
3521
3436
  if (!isLatestCreation()) {
3522
3437
  await unwindInstalledLive(keyId, live)
3523
3438
  throw new Error(`[channels] ${keyId}: superseded live session creation discarded`)
@@ -5537,18 +5452,43 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5537
5452
  live.emptyStopAfterToolWorkArmed = false
5538
5453
  live.willingnessNudges = 0
5539
5454
  live.logicalTurnStartedAt = now()
5540
- const stampedCloseout = batch.findLast((item) => item.githubReviewThreadCloseout !== undefined)
5455
+ const latestStampedCloseout = batch.findLast((item) => item.githubReviewThreadCloseout !== undefined)
5456
+ const resolvedAt = live.githubReviewThreadResolvedAt
5457
+ const alreadyResolved =
5458
+ latestStampedCloseout?.githubReviewThreadCloseout !== undefined &&
5459
+ resolvedAt !== null &&
5460
+ resolvedAt.rootCommentId === latestStampedCloseout.githubReviewThreadCloseout.rootCommentId &&
5461
+ latestStampedCloseout.ts > 0 &&
5462
+ latestStampedCloseout.ts <= resolvedAt.at
5463
+ if (alreadyResolved) {
5464
+ logger.info(
5465
+ `[channels] ${live.keyId} github_thread_closeout_already_resolved root=${resolvedAt?.rootCommentId} reply_ts=${latestStampedCloseout?.ts} resolved_at=${resolvedAt?.at}`,
5466
+ )
5467
+ }
5468
+ const stampedCloseout = alreadyResolved ? undefined : latestStampedCloseout
5541
5469
  const deferredCloseout =
5542
5470
  stampedCloseout?.githubReviewThreadCloseout === undefined &&
5543
5471
  live.githubReviewThreadCloseout !== null &&
5544
5472
  live.githubReviewThreadCloseout.deferred
5545
5473
  ? live.githubReviewThreadCloseout
5546
5474
  : null
5475
+ // A follow-up on a thread whose close-out is still open continues the
5476
+ // same obligation. Keep its start so a reviewer spawned for it before
5477
+ // this batch still holds the close-out instead of being treated as an
5478
+ // earlier turn's child and letting the canned fallback race its verdict.
5479
+ const openCloseout = live.githubReviewThreadCloseout
5480
+ const continuedStartedAt = (next: GithubReviewThreadCloseout): number =>
5481
+ openCloseout !== null &&
5482
+ openCloseout.workspace === next.workspace &&
5483
+ openCloseout.prNumber === next.prNumber &&
5484
+ openCloseout.rootCommentId === next.rootCommentId
5485
+ ? openCloseout.startedAt
5486
+ : live.logicalTurnStartedAt
5547
5487
  live.githubReviewThreadCloseout =
5548
5488
  stampedCloseout?.githubReviewThreadCloseout !== undefined
5549
5489
  ? {
5550
5490
  ...stampedCloseout.githubReviewThreadCloseout,
5551
- startedAt: live.logicalTurnStartedAt,
5491
+ startedAt: continuedStartedAt(stampedCloseout.githubReviewThreadCloseout),
5552
5492
  correctionAttempts: 0,
5553
5493
  deferred: false,
5554
5494
  }
@@ -5556,7 +5496,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5556
5496
  ? null
5557
5497
  : {
5558
5498
  ...deferredCloseout,
5559
- startedAt: live.logicalTurnStartedAt,
5499
+ startedAt: continuedStartedAt(deferredCloseout),
5560
5500
  correctionAttempts: 0,
5561
5501
  }
5562
5502
  if (stampedCloseout?.githubReviewThreadCloseout !== undefined) {
@@ -7757,6 +7697,30 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7757
7697
  live.skippedTurn = null
7758
7698
  armRetainedOutputAckIfEligible(live, successfulSendsBeforePrompt, true)
7759
7699
  logger.info(`[channels] ${live.keyId} skipped_by_tool reason=${JSON.stringify(reason)}`)
7700
+ // The model decided this turn owes the user nothing, so a provider failure
7701
+ // on the request after that decision lost nothing the user was waiting for.
7702
+ // A notice here would be a false alarm, typically stranded under the real
7703
+ // reply an earlier pass of the same logical turn already delivered.
7704
+ const pendingError = live.pendingProviderError
7705
+ if (pendingError !== null && pendingError.turnSeq === live.turnSeq) {
7706
+ live.pendingProviderError = null
7707
+ logger.warn(
7708
+ `[channels] ${live.keyId}: provider_error_notice_suppressed reason=explicit_skip_response notice="${pendingError.safeMessage}"`,
7709
+ )
7710
+ }
7711
+ // This session already resolved the thread and the model read the newer
7712
+ // reply and deliberately skipped it. Leaving a resolved thread resolved is
7713
+ // a close-out decision, so neither the reminder nor the "leaving it open"
7714
+ // fallback applies. A turn that ends silent without skip_response still owes one.
7715
+ const closeout = live.githubReviewThreadCloseout
7716
+ const resolvedAt = live.githubReviewThreadResolvedAt
7717
+ if (closeout !== null && resolvedAt !== null && resolvedAt.rootCommentId === closeout.rootCommentId) {
7718
+ clearGithubReviewThreadCloseout(live)
7719
+ live.githubReviewThreadCloseoutDecisionTurn = live.turnSeq
7720
+ logger.info(
7721
+ `[channels] ${live.keyId} github_thread_closeout_skipped_already_resolved pr=${closeout.prNumber} root=${closeout.rootCommentId}`,
7722
+ )
7723
+ }
7760
7724
  void dropContinuationReactions(live)
7761
7725
  return
7762
7726
  }
@@ -8303,6 +8267,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
8303
8267
  // missing formal review on the model's behalf, and posting the unguarded ack
8304
8268
  // is worse than dropping it — the next inbound re-prompts the model, which
8305
8269
  // can then land the verdict properly.
8270
+ // Real leftover prose is still recovered while a background child runs (an
8271
+ // answer the model already wrote should land), but a lone identifier-shaped
8272
+ // ASCII token is model degeneration, not an answer: a bare `_RGCTX` once
8273
+ // landed as a public PR comment right after a reviewer spawn. The child's
8274
+ // completion turn owns the real reply, so drop it. Scoped to the awaiting
8275
+ // turn so ordinary recovery is untouched; non-Latin short replies never match.
8276
+ if (/^[A-Za-z0-9_]+$/.test(assistantText.trim()) && isAwaitingBackgroundChild(live, 'recovery_leaf')) {
8277
+ logger.info(
8278
+ `[channels] ${live.keyId} recovery_suppressed cause=awaiting_background_child text_len=${assistantText.length}`,
8279
+ )
8280
+ armSilentTurnAck(live, 'awaiting_background_child')
8281
+ return
8282
+ }
8283
+
8306
8284
  const recoveryBlock = await evaluateRecoveryReviewGuards(live, assistantText)
8307
8285
  if (recoveryBlock !== null) {
8308
8286
  logger.warn(
@@ -9164,9 +9142,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9164
9142
  }
9165
9143
  // The exact parent session is gone. If the subagent was spawned from a
9166
9144
  // channel session, the conversation may have rolled over
9167
- // (SESSION_FRESHNESS_TTL_MS) or been idle-evicted onto a fresh sessionId
9168
- // for the same channel key while the subagent ran. Fall back to the live
9169
- // successor for that key so a finished review/result still surfaces
9145
+ // after 60 minutes idle (SESSION_FRESHNESS_TTL_MS), or been idle-evicted
9146
+ // and rehydrated for the same channel key while the subagent ran. Fall back
9147
+ // to the live successor for that key so a finished review/result still surfaces
9170
9148
  // instead of being silently dropped.
9171
9149
  if (args.channelKey !== undefined) {
9172
9150
  const targetKeyId = channelKeyId(args.channelKey)
@@ -9424,6 +9402,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
9424
9402
  )
9425
9403
  if (live !== undefined) {
9426
9404
  live.githubReviewThreadCloseoutDecisionTurn = live.turnSeq
9405
+ if (args.decision === 'resolved' && args.thread !== null) {
9406
+ live.githubReviewThreadResolvedAt = { rootCommentId: args.thread, at: now() }
9407
+ }
9427
9408
  clearGithubReviewThreadCloseout(live)
9428
9409
  logger.info(
9429
9410
  `[channels] ${live.keyId} github_thread_closeout_decided decision=${args.decision} turn=${live.turnSeq}`,
@@ -56,8 +56,9 @@ const consoleLogger: SubagentCompletionBridgeLogger = {
56
56
  //
57
57
  // - The parent session was GC'd by the idle-eviction tick
58
58
  // (SESSION_IDLE_MS) while the subagent was running.
59
- // - The parent session rolled over (SESSION_FRESHNESS_TTL_MS) when a
60
- // new inbound arrived during a long-running subagent.
59
+ // - The parent session rolled over after 60 minutes idle
60
+ // (SESSION_FRESHNESS_TTL_MS) when a new inbound arrived during a
61
+ // long-running subagent.
61
62
  //
62
63
  // A reminder still reaching this branch means there is no live session
63
64
  // for the key at all (the whole conversation went idle), or the parent
package/src/cli/hostd.ts CHANGED
@@ -191,6 +191,9 @@ export function buildHostdRestart(
191
191
  cliEntry,
192
192
  reuseCurrentHostDaemon: true,
193
193
  operationLease,
194
+ // No terminal is attached to an agent-requested restart, so the hostd log
195
+ // is the only place its start warnings can reach the operator.
196
+ onWarning: (warning) => writeLogLine(`[hostd] restart ${containerName}: ${warning}`),
194
197
  ...(currentHostDaemon ? { currentHostDaemon } : {}),
195
198
  })
196
199
  if (!restartResult.ok) return restartResult