typeclaw 0.45.0 → 0.46.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 (147) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -2
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +67 -25
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/loop-guard.ts +208 -10
  7. package/src/agent/multimodal/index.ts +1 -1
  8. package/src/agent/multimodal/look-at.ts +78 -44
  9. package/src/agent/multimodal/looker.ts +151 -39
  10. package/src/agent/network/response-body.ts +26 -0
  11. package/src/agent/network/safe-http.ts +198 -0
  12. package/src/agent/plugin-tools.ts +438 -162
  13. package/src/agent/provider-error.ts +62 -4
  14. package/src/agent/restart/index.ts +61 -40
  15. package/src/agent/restart-handoff/index.ts +73 -4
  16. package/src/agent/retry-same-ref.ts +66 -0
  17. package/src/agent/reviewer-bash-policy.ts +42 -1
  18. package/src/agent/session-origin.ts +2 -0
  19. package/src/agent/subagent-drain.ts +117 -7
  20. package/src/agent/subagents.ts +77 -18
  21. package/src/agent/throttle-circuit.ts +25 -5
  22. package/src/agent/tool-error-remediation.ts +72 -0
  23. package/src/agent/tool-file-safety.ts +1050 -0
  24. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  25. package/src/agent/tools/channel-reply.ts +15 -1
  26. package/src/agent/tools/channel-send.ts +17 -1
  27. package/src/agent/tools/ddg.ts +16 -2
  28. package/src/agent/tools/post-github-review.ts +199 -0
  29. package/src/agent/tools/spawn-subagent.ts +21 -18
  30. package/src/agent/tools/webfetch/fetch.ts +143 -183
  31. package/src/agent/tools/webfetch/tool.ts +2 -3
  32. package/src/agent/tools/websearch.ts +23 -2
  33. package/src/agent/tools-without-local-file-operands.ts +27 -0
  34. package/src/agent/turn-runner.ts +109 -15
  35. package/src/bundled-plugins/backup/index.ts +2 -1
  36. package/src/bundled-plugins/backup/runner.ts +2 -1
  37. package/src/bundled-plugins/doc-render/render.ts +93 -12
  38. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  39. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  40. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  41. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  42. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  43. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  44. package/src/bundled-plugins/memory/README.md +23 -11
  45. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  46. package/src/bundled-plugins/memory/citations.ts +22 -9
  47. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  48. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  49. package/src/bundled-plugins/memory/index.ts +0 -4
  50. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  51. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  52. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  53. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  54. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  55. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  56. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  57. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  58. package/src/bundled-plugins/reviewer/index.ts +2 -2
  59. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  60. package/src/bundled-plugins/reviewer/skills/code-review.ts +24 -9
  61. package/src/bundled-plugins/scout/scout.ts +8 -0
  62. package/src/bundled-plugins/security/index.ts +4 -4
  63. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  64. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  65. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  66. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  67. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  68. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  69. package/src/channels/adapters/discord-bot.ts +91 -10
  70. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  71. package/src/channels/adapters/discord-id.ts +4 -0
  72. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  73. package/src/channels/adapters/discord.ts +57 -7
  74. package/src/channels/adapters/github/auth-app.ts +41 -12
  75. package/src/channels/adapters/github/index.ts +23 -11
  76. package/src/channels/adapters/github/review-submitter.ts +302 -0
  77. package/src/channels/adapters/kakaotalk-channel-resolver.ts +12 -1
  78. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  79. package/src/channels/adapters/kakaotalk-typing.ts +127 -0
  80. package/src/channels/adapters/kakaotalk.ts +19 -0
  81. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  82. package/src/channels/adapters/slack-bot.ts +19 -8
  83. package/src/channels/adapters/slack-classify.ts +21 -2
  84. package/src/channels/adapters/slack.ts +59 -7
  85. package/src/channels/adapters/telegram-bot.ts +18 -5
  86. package/src/channels/adapters/webex-bot.ts +8 -3
  87. package/src/channels/adapters/webex.ts +8 -3
  88. package/src/channels/fetch-attachment.ts +43 -0
  89. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  90. package/src/channels/github-token-bridge.ts +10 -3
  91. package/src/channels/manager.ts +9 -0
  92. package/src/channels/router.ts +568 -12
  93. package/src/channels/types.ts +28 -1
  94. package/src/cli/channel.ts +1 -1
  95. package/src/cli/init.ts +1 -1
  96. package/src/cli/model.ts +57 -7
  97. package/src/compose/stop.ts +17 -5
  98. package/src/config/config.ts +6 -6
  99. package/src/config/models-mutation.ts +13 -1
  100. package/src/config/providers.ts +176 -0
  101. package/src/container/start.ts +49 -10
  102. package/src/doctor/checks.ts +3 -1
  103. package/src/doctor/commit.ts +2 -1
  104. package/src/doctor/file-ownership.ts +52 -0
  105. package/src/dreams/git.ts +2 -1
  106. package/src/git/hookless.ts +5 -0
  107. package/src/git/reconcile-ignored.ts +18 -5
  108. package/src/git/secret-history.ts +371 -0
  109. package/src/git/system-commit.ts +12 -6
  110. package/src/init/dockerfile.ts +86 -5
  111. package/src/init/index.ts +17 -5
  112. package/src/init/models-dev.ts +4 -0
  113. package/src/init/validate-api-key.ts +2 -0
  114. package/src/mcp/tools.ts +16 -3
  115. package/src/permissions/builtins.ts +3 -1
  116. package/src/plugin/context.ts +2 -0
  117. package/src/plugin/index.ts +1 -0
  118. package/src/plugin/manager.ts +4 -0
  119. package/src/plugin/types.ts +21 -0
  120. package/src/run/index.ts +40 -0
  121. package/src/run/llm-fetch-observer.ts +188 -13
  122. package/src/sandbox/build.ts +37 -15
  123. package/src/sandbox/canonical-secrets.ts +18 -0
  124. package/src/sandbox/env-exposure.ts +80 -0
  125. package/src/sandbox/errors.ts +13 -6
  126. package/src/sandbox/hidden-paths.ts +102 -44
  127. package/src/sandbox/index.ts +22 -4
  128. package/src/sandbox/package-install.ts +3 -27
  129. package/src/sandbox/policy.ts +11 -25
  130. package/src/sandbox/privileged-runtime.ts +255 -0
  131. package/src/sandbox/session-tmp.ts +8 -2
  132. package/src/sandbox/writable-zones.ts +204 -140
  133. package/src/secrets/index.ts +8 -0
  134. package/src/secrets/refresh-provider-oauth.ts +128 -0
  135. package/src/server/command-runner.ts +48 -4
  136. package/src/server/index.ts +4 -0
  137. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  138. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  139. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  140. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  141. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  142. package/src/skills/typeclaw-config/SKILL.md +5 -5
  143. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  144. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  145. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  146. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  147. package/typeclaw.schema.json +20 -0
@@ -22,6 +22,16 @@ export type RunSubagentDrainOptions = {
22
22
  // Cooperative cancellation: when this returns true the loop stops re-prompting
23
23
  // and returns, letting the caller's timeout/abort path dispose the session.
24
24
  cancelled?: () => boolean
25
+ // Wall-clock ceiling on how long a single background child may stay `running`
26
+ // before the drain gives up on it. A child without its own `timeoutMs` can
27
+ // wedge forever (a hung `session.prompt`), and the drain would otherwise wait
28
+ // on it indefinitely — stranding the parent's whole report. When a child
29
+ // exceeds this, we abort it and record a timeout completion so its reminder is
30
+ // delivered and the loop can reach its fixed point with partial results.
31
+ // Undefined keeps the legacy unbounded behavior.
32
+ maxChildWaitMs?: number
33
+ // Injectable clock + abort-await seam for tests; production uses real time.
34
+ now?: () => number
25
35
  }
26
36
 
27
37
  // Re-prompts a subagent with its children's completion reminders until a fixed
@@ -35,16 +45,22 @@ export type RunSubagentDrainOptions = {
35
45
  // "spawned nothing" flag is needed. The watch MUST have been started before the
36
46
  // initial prompt (see `beginSubagentDrainWatch`) to close the lost-wakeup race.
37
47
  export async function runSubagentDrain(watch: SubagentDrainWatch, options: RunSubagentDrainOptions): Promise<void> {
38
- const { drain, prompt, cancelled } = options
48
+ const { drain, prompt, cancelled, maxChildWaitMs, now = Date.now } = options
39
49
  const delivered = new Set<string>()
40
50
  try {
41
51
  while (cancelled === undefined || !cancelled()) {
52
+ expireOverdueChildren(drain, maxChildWaitMs, now)
42
53
  const pending = collectPendingReminders(drain, delivered)
43
54
  if (pending.length === 0) {
44
55
  if (!hasRunningChildren(drain)) return
45
56
  // Children still running but none newly completed: wait for the next
46
- // wakeup, then re-derive from the registry.
47
- const woke = await watch.waitForWakeup()
57
+ // wakeup, then re-derive. A `maxChildWaitMs` bounds this wait (via a
58
+ // timer) so a child that never broadcasts still gets expired next
59
+ // iteration. `waitForWakeup` returns true on a completion OR a timer
60
+ // expiry, and false ONLY when the watch is stopped — which must always
61
+ // terminate the loop, else a stopped watch with a still-running child
62
+ // spins synchronously forever.
63
+ const woke = await watch.waitForWakeup(nextExpiryDelayMs(drain, maxChildWaitMs, now))
48
64
  if (!woke) return
49
65
  continue
50
66
  }
@@ -59,6 +75,64 @@ export async function runSubagentDrain(watch: SubagentDrainWatch, options: RunSu
59
75
  }
60
76
  }
61
77
 
78
+ // Records a timeout completion (then fires abort) for any background child that
79
+ // has been `running` past the ceiling. Recording a (failed) completion is what
80
+ // lets the child surface as a delivered reminder and drop out of
81
+ // `hasRunningChildren`, so the loop reaches its fixed point with partial results
82
+ // rather than hanging on a wedged child. Synchronous by design — see the
83
+ // record-before-abort note inside.
84
+ function expireOverdueChildren(
85
+ drain: SubagentBackgroundDrain,
86
+ maxChildWaitMs: number | undefined,
87
+ now: () => number,
88
+ ): void {
89
+ if (maxChildWaitMs === undefined) return
90
+ const deadline = now() - maxChildWaitMs
91
+ for (const child of drain.liveRegistry.list({ parentSessionId: drain.sessionId })) {
92
+ if (child.background !== true || child.status !== 'running') continue
93
+ if (child.startedAt > deadline) continue
94
+ const durationMs = now() - child.startedAt
95
+ const error = `subagent ${child.subagentName} exceeded the ${maxChildWaitMs}ms drain wait and was abandoned`
96
+ // Claim the settlement BEFORE aborting. If the child's real completion
97
+ // already won, skip — no double-settle, no broadcast. Awaiting abort here
98
+ // would be the bug the ceiling exists to prevent: a wedged `session.abort()`
99
+ // that never reaches idle would hang the drain, so fire-and-forget instead.
100
+ // Logical settlement can precede physical teardown; startSubagent still
101
+ // disposes the session when its own work settles.
102
+ if (!drain.liveRegistry.recordCompletionIfRunning(child.taskId, { ok: false, durationMs, error })) continue
103
+ drain.stream.publish({
104
+ target: { kind: 'broadcast' },
105
+ payload: {
106
+ kind: 'subagent.completed',
107
+ taskId: child.taskId,
108
+ subagent: child.subagentName,
109
+ parentSessionId: drain.sessionId,
110
+ ok: false,
111
+ durationMs,
112
+ error,
113
+ },
114
+ })
115
+ void child.abort().catch(() => {})
116
+ }
117
+ }
118
+
119
+ // The soonest a still-running child will cross the ceiling, so waitForWakeup can
120
+ // wake the loop to expire it even if no completion broadcast ever arrives.
121
+ // Undefined when there is no ceiling or no running child (wait indefinitely).
122
+ function nextExpiryDelayMs(
123
+ drain: SubagentBackgroundDrain,
124
+ maxChildWaitMs: number | undefined,
125
+ now: () => number,
126
+ ): number | undefined {
127
+ if (maxChildWaitMs === undefined) return undefined
128
+ const running = drain.liveRegistry
129
+ .list({ parentSessionId: drain.sessionId })
130
+ .filter((c) => c.background === true && c.status === 'running')
131
+ if (running.length === 0) return undefined
132
+ const oldestStart = Math.min(...running.map((c) => c.startedAt))
133
+ return Math.max(0, oldestStart + maxChildWaitMs - now())
134
+ }
135
+
62
136
  type PendingReminder = { taskId: string; text: string }
63
137
 
64
138
  function collectPendingReminders(drain: SubagentBackgroundDrain, delivered: Set<string>): PendingReminder[] {
@@ -97,20 +171,47 @@ function hasRunningChildren(drain: SubagentBackgroundDrain): boolean {
97
171
  export type SubagentDrainWatch = {
98
172
  // Resolves true on a child-completion wakeup, false once stopped. A wakeup
99
173
  // that arrives before anyone waits is latched (pendingWake), so a completion
100
- // during the subagent's prompt is not lost.
101
- waitForWakeup: () => Promise<boolean>
174
+ // during the subagent's prompt is not lost. An optional `timeoutMs` resolves
175
+ // true when it elapses (a spurious wake) so the loop re-derives and can expire
176
+ // a child that never broadcast a completion.
177
+ waitForWakeup: (timeoutMs?: number) => Promise<boolean>
102
178
  stop: () => void
103
179
  }
104
180
 
105
- export function beginSubagentDrainWatch(drain: SubagentBackgroundDrain): SubagentDrainWatch {
181
+ // Injectable timer seam so tests can assert timer cancellation deterministically
182
+ // (a real setTimeout cancellation is invisible without racing the clock). `set`
183
+ // returns an opaque handle; `clear` cancels it. Production uses node timers.
184
+ export type TimerScheduler = {
185
+ set: (fn: () => void, ms: number) => unknown
186
+ clear: (handle: unknown) => void
187
+ }
188
+
189
+ const realTimerScheduler: TimerScheduler = {
190
+ set: (fn, ms) => setTimeout(fn, ms),
191
+ clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
192
+ }
193
+
194
+ export function beginSubagentDrainWatch(
195
+ drain: SubagentBackgroundDrain,
196
+ scheduler: TimerScheduler = realTimerScheduler,
197
+ ): SubagentDrainWatch {
106
198
  let stopped = false
107
199
  let pendingWake = false
108
200
  let resolveWaiter: ((woke: boolean) => void) | null = null
201
+ let waiterTimer: unknown = null
202
+
203
+ const clearWaiterTimer = (): void => {
204
+ if (waiterTimer !== null) {
205
+ scheduler.clear(waiterTimer)
206
+ waiterTimer = null
207
+ }
208
+ }
109
209
 
110
210
  const wake = (): void => {
111
211
  if (resolveWaiter !== null) {
112
212
  const r = resolveWaiter
113
213
  resolveWaiter = null
214
+ clearWaiterTimer()
114
215
  r(true)
115
216
  return
116
217
  }
@@ -125,7 +226,7 @@ export function beginSubagentDrainWatch(drain: SubagentBackgroundDrain): Subagen
125
226
  })
126
227
 
127
228
  return {
128
- waitForWakeup: () =>
229
+ waitForWakeup: (timeoutMs?: number) =>
129
230
  new Promise<boolean>((resolve) => {
130
231
  if (stopped) {
131
232
  resolve(false)
@@ -137,11 +238,20 @@ export function beginSubagentDrainWatch(drain: SubagentBackgroundDrain): Subagen
137
238
  return
138
239
  }
139
240
  resolveWaiter = resolve
241
+ if (timeoutMs !== undefined) {
242
+ waiterTimer = scheduler.set(() => {
243
+ if (resolveWaiter === null) return
244
+ resolveWaiter = null
245
+ waiterTimer = null
246
+ resolve(true)
247
+ }, timeoutMs)
248
+ }
140
249
  }),
141
250
  stop: () => {
142
251
  if (stopped) return
143
252
  stopped = true
144
253
  unsubscribe()
254
+ clearWaiterTimer()
145
255
  if (resolveWaiter !== null) {
146
256
  const r = resolveWaiter
147
257
  resolveWaiter = null
@@ -367,6 +367,7 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
367
367
  },
368
368
  })
369
369
  if (result.success) activeModelRef = result.refUsed
370
+ throwIfLoopGuardAborted(session)
370
371
  } finally {
371
372
  if (hooks && turnEvent !== undefined) {
372
373
  await hooks.runSessionTurnEnd(turnEvent)
@@ -377,10 +378,13 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
377
378
  drain: backgroundDrain,
378
379
  prompt: async (text) => {
379
380
  await promptWithSameRefRetryOnly(session, `${renderTurnTimeAnchor()}\n\n${text}`)
381
+ throwIfLoopGuardAborted(session)
380
382
  },
381
383
  cancelled: () => aborted,
384
+ maxChildWaitMs: DRAIN_MAX_CHILD_WAIT_MS,
382
385
  })
383
386
  }
387
+ throwIfLoopGuardAborted(session)
384
388
  // Required-block guard (mirrors the channel empty-response guard): a subagent
385
389
  // that owes a result block but ended without one gets a bounded re-prompt to
386
390
  // emit it as text, then an honest fallback — never a silent stale-preamble
@@ -400,6 +404,7 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
400
404
  session,
401
405
  `${renderTurnTimeAnchor()}\n\n${renderRequiredBlockRetryNudge(requiredBlockTag)}`,
402
406
  )
407
+ throwIfLoopGuardAborted(session)
403
408
  }
404
409
  if (!aborted && !capture.hasRequiredBlock()) {
405
410
  console.warn(`[subagent] ${name} required_block_fallback tag=${requiredBlockTag}`)
@@ -448,6 +453,19 @@ export class SubagentTimeoutError extends Error {
448
453
  }
449
454
  }
450
455
 
456
+ class SubagentLoopGuardAbortError extends Error {
457
+ override readonly name = 'SubagentLoopGuardAbortError'
458
+
459
+ constructor(readonly reason: string) {
460
+ super(`subagent aborted by loop guard (${reason})`)
461
+ }
462
+ }
463
+
464
+ function throwIfLoopGuardAborted(session: AgentSession): void {
465
+ const reason = (session as AgentSession & { getAbortReason?: () => string | undefined }).getAbortReason?.()
466
+ if (reason?.startsWith('loop_guard:') === true) throw new SubagentLoopGuardAbortError(reason)
467
+ }
468
+
451
469
  export function isSubagentTimeoutError(err: unknown): err is SubagentTimeoutError {
452
470
  return err instanceof SubagentTimeoutError
453
471
  }
@@ -544,7 +562,7 @@ export function startSubagent(name: string, options: StartSubagentOptions): Star
544
562
  if (!handleSettled) {
545
563
  rejectHandle(err instanceof Error ? err : new Error(error))
546
564
  }
547
- return { ok: false as const, error }
565
+ return { ok: false as const, error, ...(finalMessage !== undefined ? { finalMessage } : {}) }
548
566
  })
549
567
 
550
568
  const timeoutMs = options.registry[name]?.timeoutMs
@@ -613,16 +631,25 @@ function lastTaggedBlock(text: string, tag: FinalBlockTag): string | null {
613
631
  }
614
632
 
615
633
  // Subagents whose result IS a REQUIRED tagged block — the parent must receive
616
- // that block or a loud failure, never a stale earlier turn. The researcher's
617
- // contract (src/bundled-plugins/researcher/researcher.ts) mandates a closing
618
- // `<report>` block; when an upstream provider retry loop ends the run on
619
- // unexecuted `write_report` tool calls, the researcher never emits it, and
620
- // without this gate the capture would silently return its earlier `<analysis>`
621
- // preamble as a "successful" result — the production regression this guards.
622
- // Keyed by the stable bundled-subagent registry name. This is STRICTER than the
623
- // reviewer's `<review>` (preferred, but falls back to free-form text): only the
624
- // subagents listed here fail loud when their block is absent.
625
- const REQUIRED_FINAL_BLOCK: Readonly<Record<string, FinalBlockTag>> = { researcher: 'report' }
634
+ // that block or a structured "could not complete" fallback, never a stale
635
+ // earlier turn and never a silent empty completion. Keyed by registry name.
636
+ //
637
+ // Both entries share one failure mode on the `deep`/openai-codex profile: a run
638
+ // that ends on tool-call-only turns emits no closing block, so `finalMessage`
639
+ // stays undefined and `spawn_subagent`/`subagent_output` synthesize "completed …
640
+ // with no final message" as an `ok: true` success. For the researcher that
641
+ // surfaced the earlier `<analysis>` preamble as findings (guarded by ae5014e5);
642
+ // for the reviewer the GitHub flow has no `<review>` to post and silently
643
+ // `skip_response`s — the stranded-review bug. This gate gives both a bounded
644
+ // re-prompt then an honest low-confidence fallback instead of the silent drop.
645
+ // Backstop ceiling for the background drain: a running child that never settles
646
+ // is abandoned after this so the parent can synthesize partial results instead
647
+ // of hanging forever. Deliberately larger than the per-child `timeoutMs`
648
+ // (scout = 5 min) so that a child's own timeout is the primary release and this
649
+ // only catches children that declare none.
650
+ const DRAIN_MAX_CHILD_WAIT_MS = 600_000
651
+
652
+ const REQUIRED_FINAL_BLOCK: Readonly<Record<string, FinalBlockTag>> = { researcher: 'report', reviewer: 'review' }
626
653
 
627
654
  // Bounded re-prompt budget for the required-block guard, mirroring the channel
628
655
  // empty-response guard's MAX_EMPTY_TURN_RETRIES. A subagent that owes a result
@@ -631,24 +658,37 @@ const REQUIRED_FINAL_BLOCK: Readonly<Record<string, FinalBlockTag>> = { research
631
658
  const MAX_REQUIRED_BLOCK_RETRIES = 2
632
659
 
633
660
  // The recovery nudge. It MUST forbid tools: the known failure mode is a provider
634
- // retry loop on the report-writing tool call, so re-driving the tool path would
661
+ // retry loop on a block-producing tool call, so re-driving the tool path would
635
662
  // just re-trigger the loop. Asking for the block as plain text is the repair.
663
+ // The tail is tag-specific: each block has different mandatory child fields.
636
664
  function renderRequiredBlockRetryNudge(tag: FinalBlockTag): string {
665
+ const tail =
666
+ tag === 'report'
667
+ ? 'in particular do NOT call write_report. Do NOT continue researching or spawn more subagents.\n\nIf the report file was not successfully written, still emit the block: set <report_file>none</report_file>, <confidence>low</confidence> (explain the report artifact was not completed), and note in <open_questions> that the run should be retried.'
668
+ : `Do NOT re-run gh, diff reads, or spawn more subagents.\n\nEmit the block from the analysis you have already done: include your <summary>, whatever <finding> items you can support with evidence, and a <verdict> (approve | request-changes | comment). Only use a real verdict if you actually reached one. If you could NOT analyze enough to decide, do NOT invent a verdict — set <verdict>${INCOMPLETE_REVIEW_VERDICT}</verdict> exactly (this signals an incomplete review; the parent will not treat it as approve/request-changes/comment, even on a re-review).`
637
669
  return `---
638
670
  **[SYSTEM MESSAGE — not from a human]**
639
671
 
640
672
  Your previous turn ended without the required <${tag}> block. This is an automated runtime recovery signal, not a human message.
641
673
 
642
- Emit the final <${tag}>...</${tag}> block NOW as plain assistant text. Do NOT call any tools — in particular do NOT call write_report. Do NOT continue researching or spawn more subagents.
643
-
644
- If the report file was not successfully written, still emit the block: set <report_file>none</report_file>, <confidence>low</confidence> (explain the report artifact was not completed), and note in <open_questions> that the run should be retried.
674
+ Emit the final <${tag}>...</${tag}> block NOW as plain assistant text. Do NOT call any tools — ${tail}
645
675
 
646
676
  Output exactly one <${tag}> block and nothing else.`
647
677
  }
648
678
 
679
+ // Unambiguous marker on a synthesized incomplete-review fallback. The parent's
680
+ // GitHub re-review flow overrides a `comment` verdict into a decisive APPROVE /
681
+ // REQUEST_CHANGES when prior blockers look resolved — which would let a review
682
+ // that NEVER RAN post a formal verdict. So the fallback carries no real verdict:
683
+ // it uses this sentinel in place of approve|request-changes|comment, and the
684
+ // GitHub skill keys off it to post only an honest failure comment and leave
685
+ // review state untouched. Kept in sync with the exemption in
686
+ // src/skills/typeclaw-channel-github/SKILL.md.
687
+ export const INCOMPLETE_REVIEW_VERDICT = 'incomplete-review-not-a-verdict'
688
+
649
689
  // The terminal graceful fallback when the nudges are exhausted. It fabricates NO
650
- // findings — only a structured, low-confidence "could not complete" notice — so
651
- // the parent gets a usable result instead of stale `<analysis>` or a hard error.
690
+ // findings — only a structured "could not complete" notice — so the parent gets
691
+ // a usable result instead of stale `<analysis>` or a hard error.
652
692
  function renderMissingRequiredBlockFallback(name: string, tag: FinalBlockTag): string {
653
693
  if (tag === 'report') {
654
694
  return `<report>
@@ -665,6 +705,16 @@ low — no complete research report artifact was produced.
665
705
  The original research request remains unresolved; rerun the ${name} subagent or gather the sources directly.
666
706
  </open_questions>
667
707
  </report>`
708
+ }
709
+ if (tag === 'review') {
710
+ return `<review>
711
+ <summary>
712
+ INCOMPLETE REVIEW — NOT A VERDICT. The ${name} subagent could not complete a review in this run: it ended without emitting the required <review> block. No findings were produced and no verdict was reached — do not treat any earlier text as a verdict, and do NOT map this to APPROVE/REQUEST_CHANGES/COMMENT (including on a re-review). Re-request the review; if it still cannot complete, post an honest "review could not be completed" note and leave existing review state unchanged.
713
+ </summary>
714
+ <findings>
715
+ </findings>
716
+ <verdict>${INCOMPLETE_REVIEW_VERDICT}</verdict>
717
+ </review>`
668
718
  }
669
719
  return `<${tag}>\nThe ${name} subagent ended without emitting the required <${tag}> block and could not recover; rerun it or inspect the transcript.\n</${tag}>`
670
720
  }
@@ -688,7 +738,7 @@ function attachFinalMessageCapture(
688
738
  let lastReview: string | null = null
689
739
  let lastRequired: string | null = null
690
740
  try {
691
- session.subscribe((event: unknown) => {
741
+ subscribeToAwaitedAgentEvents(session, (event: unknown) => {
692
742
  const ev = event as { type?: string; message?: { role?: string; content?: unknown } }
693
743
  if (ev?.type !== 'message_end') return
694
744
  // Real assistant messages carry role 'assistant'; older test doubles omit
@@ -731,6 +781,15 @@ function attachFinalMessageCapture(
731
781
  }
732
782
  }
733
783
 
784
+ function subscribeToAwaitedAgentEvents(session: AgentSession, listener: (event: unknown) => void): () => void {
785
+ const agent = (
786
+ session as AgentSession & {
787
+ agent?: { subscribe?: (listener: (event: unknown) => void) => () => void }
788
+ }
789
+ ).agent
790
+ return agent?.subscribe?.(listener) ?? session.subscribe(listener)
791
+ }
792
+
734
793
  function extractFinalMessageText(content: unknown): string | null {
735
794
  if (typeof content === 'string') {
736
795
  const trimmed = content.trim()
@@ -23,13 +23,33 @@ export class ThrottleCircuit {
23
23
  }
24
24
 
25
25
  isOpen(key: ThrottleCircuitKey): boolean {
26
- const entry = this.entries.get(this.keyId(key))
26
+ return this.isEntryOpen(this.keyId(key))
27
+ }
28
+
29
+ isProviderOpen(key: ThrottleCircuitKey): boolean {
30
+ return this.isEntryOpen(this.providerKeyId(key))
31
+ }
32
+
33
+ recordThrottle(key: ThrottleCircuitKey): void {
34
+ this.recordFailure(this.keyId(key))
35
+ }
36
+
37
+ recordProviderTrip(key: ThrottleCircuitKey): void {
38
+ this.recordFailure(this.providerKeyId(key))
39
+ }
40
+
41
+ recordSuccess(key: ThrottleCircuitKey): void {
42
+ this.entries.delete(this.keyId(key))
43
+ this.entries.delete(this.providerKeyId(key))
44
+ }
45
+
46
+ private isEntryOpen(id: string): boolean {
47
+ const entry = this.entries.get(id)
27
48
  if (entry === undefined) return false
28
49
  return this.now() < entry.openUntil
29
50
  }
30
51
 
31
- recordThrottle(key: ThrottleCircuitKey): void {
32
- const id = this.keyId(key)
52
+ private recordFailure(id: string): void {
33
53
  const now = this.now()
34
54
  const entry = this.entries.get(id) ?? { failures: [], openUntil: 0 }
35
55
  entry.failures = entry.failures.filter((ts) => now - ts <= THROTTLE_WINDOW_MS)
@@ -38,8 +58,8 @@ export class ThrottleCircuit {
38
58
  this.entries.set(id, entry)
39
59
  }
40
60
 
41
- recordSuccess(key: ThrottleCircuitKey): void {
42
- this.entries.delete(this.keyId(key))
61
+ private providerKeyId(key: ThrottleCircuitKey): string {
62
+ return `${key.profile ?? 'default'}:${providerForModelRef(key.ref)}`
43
63
  }
44
64
 
45
65
  private keyId(key: ThrottleCircuitKey): string {
@@ -0,0 +1,72 @@
1
+ // SECURITY/CORRECTNESS: rules are gated on BOTH the emitting tool name and a
2
+ // verbatim upstream pi-coding-agent error substring. `bash` (the only tool that
3
+ // raises sandbox/subagent-policy errors) is never in a rule's tool set, and
4
+ // abort/cleanup/guard failures never match any pattern, so internal control
5
+ // errors are never decorated with a nonsensical "read the file first" hint. A
6
+ // wording drift upstream simply stops decorating (fails safe) rather than
7
+ // mis-firing on the wrong error class.
8
+
9
+ const HINT_PREFIX = 'Hint:'
10
+
11
+ type RemediationRule = {
12
+ // Built-in tool names whose thrown errors this rule may decorate.
13
+ tools: readonly string[]
14
+ // `upstream` is the exact substring the matching pi tool emits, kept next to
15
+ // the pattern so the regex can be re-verified against the dependency on bumps.
16
+ upstream: string
17
+ test: RegExp
18
+ hint: string
19
+ }
20
+
21
+ // First matching rule wins; keep the most specific patterns first. Upstream
22
+ // sources: node_modules/@mariozechner/pi-coding-agent/dist/core/tools/{edit,read,ls,grep}.js
23
+ const RULES: readonly RemediationRule[] = [
24
+ {
25
+ tools: ['edit'],
26
+ upstream: 'Could not find edits[0] in <path>. / Could not find the exact text in <path>.',
27
+ test: /Could not find (the exact text|edits\[\d+\]) in /i,
28
+ hint: `${HINT_PREFIX} the oldText must match the file byte-for-byte. Re-read the file with the \`read\` tool to copy the exact current text — including all whitespace, indentation, and newlines — then retry \`edit\` with that exact oldText. Do not hand-type or reformat it.`,
29
+ },
30
+ {
31
+ tools: ['edit'],
32
+ upstream: 'No changes made to <path>. The replacement(s) produced identical content',
33
+ test: /No changes made to .+\. The replacements? produced identical content/i,
34
+ hint: `${HINT_PREFIX} the newText is identical to the oldText, so the edit is a no-op. If you intended a change, make oldText and newText differ; if the file is already correct, do not retry this edit.`,
35
+ },
36
+ {
37
+ tools: ['read'],
38
+ upstream: 'Offset N is beyond end of file (M lines total)',
39
+ test: /Offset \d+ is beyond end of file/i,
40
+ hint: `${HINT_PREFIX} the file has fewer lines than the offset you requested. Read from a smaller offset, or read the whole file without an offset first to see its length.`,
41
+ },
42
+ {
43
+ // typeclaw-owned: enforceAndPinToolFiles (src/agent/tool-file-safety.ts,
44
+ // throws at :95 and :451) runs BEFORE tool.execute inside the builtin
45
+ // wrapper, so a missing input path surfaces THIS string — not the upstream
46
+ // `File not found:` — for every input-pinning tool. This is the common
47
+ // missing-path case for read/grep/find/ls.
48
+ tools: ['read', 'ls', 'grep', 'find'],
49
+ upstream: 'tool input did not exist while being authorized: <path>',
50
+ test: /tool input did not exist while being authorized: /i,
51
+ hint: `${HINT_PREFIX} the path does not exist. Verify it before retrying — use \`ls\` on the parent directory or \`find\` to locate the file. Paths are relative to the agent root unless absolute.`,
52
+ },
53
+ {
54
+ // Fallback for the raw upstream not-found strings some tools still emit when
55
+ // a path resolves at pin time but disappears before the tool reads it.
56
+ tools: ['read', 'ls', 'grep', 'find'],
57
+ upstream: 'File not found: <path> / Path not found: <path>',
58
+ test: /(File|Path) not found: /i,
59
+ hint: `${HINT_PREFIX} verify the path before retrying — use \`ls\` on the parent directory or \`find\` to locate the file. Paths are relative to the agent root unless absolute.`,
60
+ },
61
+ ]
62
+
63
+ export function remediateToolErrorMessage(toolName: string, message: string): string {
64
+ if (typeof message !== 'string' || message.length === 0) return message
65
+ for (const rule of RULES) {
66
+ if (!rule.tools.includes(toolName)) continue
67
+ if (!rule.test.test(message)) continue
68
+ if (message.includes(rule.hint)) return message
69
+ return `${message}\n\n${rule.hint}`
70
+ }
71
+ return message
72
+ }