typeclaw 0.47.1 → 0.48.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 (113) hide show
  1. package/package.json +1 -1
  2. package/src/agent/index.ts +1 -2
  3. package/src/agent/loop-guard.ts +71 -41
  4. package/src/agent/plugin-tools.ts +167 -50
  5. package/src/agent/retry-same-ref.ts +89 -9
  6. package/src/agent/subagents.ts +88 -15
  7. package/src/agent/system-prompt.ts +1 -1
  8. package/src/agent/turn-runner.ts +60 -5
  9. package/src/bundled-plugins/agent-browser/index.ts +0 -35
  10. package/src/bundled-plugins/agent-browser/skills/agent-browser/SKILL.md +1 -1
  11. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +16 -1
  12. package/src/bundled-plugins/memory/append-tool.ts +75 -2
  13. package/src/bundled-plugins/memory/frontmatter.ts +13 -2
  14. package/src/bundled-plugins/memory/load-memory.ts +1 -1
  15. package/src/bundled-plugins/memory/memory-logger.ts +5 -1
  16. package/src/bundled-plugins/memory/secret-detector.ts +7 -0
  17. package/src/bundled-plugins/memory/vector/hybrid.ts +3 -1
  18. package/src/bundled-plugins/memory/vector/passages.ts +5 -1
  19. package/src/bundled-plugins/operator/operator.ts +9 -2
  20. package/src/bundled-plugins/researcher/researcher.ts +4 -6
  21. package/src/bundled-plugins/security/index.ts +148 -98
  22. package/src/bundled-plugins/security/policies/private-surface-read.ts +43 -28
  23. package/src/channels/adapters/discord-bot-edit.ts +3 -5
  24. package/src/channels/adapters/discord-bot-reactions.ts +4 -6
  25. package/src/channels/adapters/discord-bot-slash-commands.ts +3 -1
  26. package/src/channels/adapters/discord-bot.ts +20 -23
  27. package/src/channels/adapters/discord-edit.ts +3 -5
  28. package/src/channels/adapters/discord-reactions.ts +4 -6
  29. package/src/channels/adapters/discord.ts +1 -1
  30. package/src/channels/adapters/github/decoy-reviewer.ts +2 -1
  31. package/src/channels/adapters/github/history.ts +2 -1
  32. package/src/channels/adapters/github/inbound.ts +4 -11
  33. package/src/channels/adapters/github/index.ts +6 -9
  34. package/src/channels/adapters/github/outbound.ts +3 -6
  35. package/src/channels/adapters/github/reactions.ts +3 -2
  36. package/src/channels/adapters/github/reconcile-cooldown-store.ts +4 -6
  37. package/src/channels/adapters/github/reconcile-open-prs.ts +5 -4
  38. package/src/channels/adapters/github/recover-failed-deliveries.ts +2 -5
  39. package/src/channels/adapters/github/review-state.ts +3 -2
  40. package/src/channels/adapters/github/review-thread-resolver.ts +3 -2
  41. package/src/channels/adapters/github/webhook-register.ts +5 -8
  42. package/src/channels/adapters/instagram-channel-resolver.ts +3 -5
  43. package/src/channels/adapters/instagram.ts +1 -1
  44. package/src/channels/adapters/kakaotalk-author-resolver.ts +2 -5
  45. package/src/channels/adapters/kakaotalk-channel-resolver.ts +3 -5
  46. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +2 -1
  47. package/src/channels/adapters/kakaotalk-membership.ts +2 -5
  48. package/src/channels/adapters/kakaotalk-typing.ts +1 -1
  49. package/src/channels/adapters/kakaotalk.ts +1 -1
  50. package/src/channels/adapters/line-channel-resolver.ts +3 -5
  51. package/src/channels/adapters/line.ts +1 -1
  52. package/src/channels/adapters/slack-bot-edit.ts +1 -1
  53. package/src/channels/adapters/slack-bot-reactions.ts +4 -6
  54. package/src/channels/adapters/slack-bot.ts +8 -8
  55. package/src/channels/adapters/slack-edit.ts +3 -5
  56. package/src/channels/adapters/slack-reactions.ts +4 -6
  57. package/src/channels/adapters/slack.ts +1 -1
  58. package/src/channels/adapters/teams-edit.ts +2 -5
  59. package/src/channels/adapters/teams.ts +1 -1
  60. package/src/channels/adapters/telegram-bot-edit.ts +4 -7
  61. package/src/channels/adapters/telegram-bot.ts +1 -1
  62. package/src/channels/adapters/webex-bot.ts +1 -1
  63. package/src/channels/adapters/webex-edit.ts +3 -5
  64. package/src/channels/adapters/webex.ts +1 -1
  65. package/src/channels/github-review-claim.ts +89 -4
  66. package/src/channels/github-token-bridge.ts +2 -1
  67. package/src/channels/manager.ts +478 -64
  68. package/src/channels/membership-cache.ts +2 -5
  69. package/src/channels/persistence.ts +3 -6
  70. package/src/channels/reloadable.ts +23 -6
  71. package/src/channels/router.ts +134 -56
  72. package/src/channels/tunnel-bridge.ts +2 -1
  73. package/src/channels/types.ts +6 -3
  74. package/src/cli/hostd.ts +56 -28
  75. package/src/config/config.ts +10 -0
  76. package/src/config/providers.ts +179 -0
  77. package/src/dependencies/bin-resolver.ts +88 -0
  78. package/src/dependencies/bins.ts +227 -0
  79. package/src/dependencies/index.ts +17 -0
  80. package/src/doctor/checks.ts +2 -0
  81. package/src/doctor/operational-incidents.ts +32 -0
  82. package/src/hostd/credential-rotation-apply.ts +94 -0
  83. package/src/init/dockerfile.ts +36 -18
  84. package/src/init/index.ts +1 -1
  85. package/src/init/models-dev.ts +17 -3
  86. package/src/init/validate-api-key.ts +26 -4
  87. package/src/operations/classify-tool-outcome.ts +151 -0
  88. package/src/operations/incidents.ts +274 -0
  89. package/src/operations/index.ts +3 -0
  90. package/src/operations/remediations.ts +41 -0
  91. package/src/reload/client.ts +8 -2
  92. package/src/reload/docker-exec-client.ts +10 -2
  93. package/src/reload/index.ts +1 -1
  94. package/src/reload/recover.ts +5 -3
  95. package/src/reload/registry.ts +5 -5
  96. package/src/reload/types.ts +9 -1
  97. package/src/run/index.ts +5 -0
  98. package/src/sandbox/dependency-bins.ts +125 -0
  99. package/src/sandbox/errors.ts +32 -0
  100. package/src/sandbox/hidden-paths.ts +4 -1
  101. package/src/sandbox/index.ts +8 -0
  102. package/src/sandbox/policy.ts +1 -1
  103. package/src/sandbox/privileged-runtime.ts +88 -7
  104. package/src/sandbox/runtime-private.ts +4 -0
  105. package/src/sandbox/writable-zones.ts +4 -4
  106. package/src/server/index.ts +7 -5
  107. package/src/shared/protocol.ts +6 -1
  108. package/src/skills/typeclaw-monorepo/SKILL.md +1 -1
  109. package/src/skills/typeclaw-troubleshooting/SKILL.md +1 -1
  110. package/typeclaw.schema.json +35 -5
  111. package/src/bundled-plugins/agent-browser/shim-install.ts +0 -158
  112. package/src/bundled-plugins/agent-browser/shim.ts +0 -108
  113. /package/src/channels/{adapters/describe-error.ts → describe-error.ts} +0 -0
@@ -1,5 +1,5 @@
1
1
  import type { AgentSession } from './index'
2
- import { isRetryableSameRef, subscribeProviderErrors } from './provider-error'
2
+ import { isRetryableSameRef, isThrottleOrOverload, subscribeProviderErrors } from './provider-error'
3
3
 
4
4
  // Same-ref retry policy. Conservative on purpose: the pi-ai provider layer ALSO
5
5
  // retries transport/5xx blips underneath us (WebSocket→SSE fallback + its own
@@ -12,6 +12,45 @@ export const RETRIES_PER_REF = 1
12
12
  const BASE_DELAY_MS = 1_000
13
13
  const MAX_DELAY_MS = 5_000
14
14
 
15
+ // How much added latency a call site can absorb before the caller would rather
16
+ // see a failure. Deliberately NOT the model-profile name: the retry layer cares
17
+ // about latency tolerance, not which tier the operator configured. 'responsive'
18
+ // is every interactive path (channel chat, TUI, slash commands, cron) and keeps
19
+ // the historical fast-fail behavior; 'patient' is a background path where a
20
+ // human is already waiting minutes for a considered answer. Today the only
21
+ // producer is a subagent whose REQUESTED profile is `deep` (reviewer,
22
+ // researcher) — see resolveRetryPolicy in subagents.ts.
23
+ export type RetryPolicy = 'responsive' | 'patient'
24
+
25
+ // Capacity backoff, used ONLY for throttle/overload under the 'patient' policy.
26
+ // Kept separate from retryBackoffMs above on purpose: that curve (1–5s) is sized
27
+ // for a one-off socket blip, and widening it globally would add dead air to the
28
+ // TUI, slash commands, multimodal look-at, cron, and ordinary network errors.
29
+ // An overload is a capacity outage measured in minutes, not milliseconds — the
30
+ // incident that motivated this burned every retry in 4 seconds against a ~60s
31
+ // outage — so it gets its own, much longer curve.
32
+ //
33
+ // Nominal delays are 10s, 20s, 30s, 30s, 30s, 30s (±20% jitter), so six retries
34
+ // span roughly 120–180s of waiting and place the last attempt late enough to
35
+ // outlive a two-minute blip.
36
+ export const PATIENT_OVERLOAD_RETRIES = 6
37
+ const PATIENT_OVERLOAD_BASE_MS = 10_000
38
+ const PATIENT_OVERLOAD_CAP_MS = 30_000
39
+ // Ceiling on when the LAST retry may START, not a hard wall on total elapsed
40
+ // time: an attempt already in flight still runs to the observer's own 300s
41
+ // overall deadline. The pathological upper bound is therefore ~8m, comfortably
42
+ // inside the 30m reviewer/researcher spawn timeout.
43
+ export const PATIENT_OVERLOAD_WINDOW_MS = 180_000
44
+
45
+ // Proportional (±20%) rather than full jitter: full jitter can return ~0ms,
46
+ // which against a capacity outage means retrying instantly into the same wall.
47
+ // The floor keeps every wait meaningful while still decorrelating concurrent
48
+ // subagents recovering from one upstream blip.
49
+ export function patientOverloadBackoffMs(attempt: number, random: () => number = Math.random): number {
50
+ const nominal = Math.min(PATIENT_OVERLOAD_CAP_MS, PATIENT_OVERLOAD_BASE_MS * 2 ** attempt)
51
+ return Math.floor(nominal * (0.8 + random() * 0.4))
52
+ }
53
+
15
54
  // Full-jitter exponential backoff: random in [0, min(cap, base·2^attempt)].
16
55
  // Jitter decorrelates concurrent turns (multiple channels/subagents recovering
17
56
  // from the same upstream blip) so they don't retry in lockstep and re-collide.
@@ -58,7 +97,7 @@ type ContinuableAgent = {
58
97
  // no `agent.continue`) fails CLOSED — the caller falls back / surfaces instead.
59
98
  export async function retryTurnOnPersistentSession(
60
99
  session: AgentSession,
61
- opts: { attempt: number; signal?: AbortSignal; random?: () => number } = { attempt: 0 },
100
+ opts: { attempt: number; signal?: AbortSignal; random?: () => number; delayMs?: number } = { attempt: 0 },
62
101
  ): Promise<boolean> {
63
102
  const agent = (session as { agent?: ContinuableAgent }).agent
64
103
  if (!agent || typeof agent.continue !== 'function') return false
@@ -67,7 +106,7 @@ export async function retryTurnOnPersistentSession(
67
106
  const leafRole = (messages[messages.length - 1] as { role?: unknown }).role
68
107
  if (leafRole !== 'assistant' && leafRole !== 'user') return false
69
108
 
70
- await sleep(retryBackoffMs(opts.attempt, opts.random), opts.signal)
109
+ await sleep(opts.delayMs ?? retryBackoffMs(opts.attempt, opts.random), opts.signal)
71
110
  if (opts.signal?.aborted) return false
72
111
 
73
112
  // Drop only a trailing assistant error leaf; a trailing user message is already
@@ -153,11 +192,20 @@ function hasSameEntries(messages: unknown, expected: unknown[]): boolean {
153
192
  // WITHOUT the race (typeclaw owns the soft-error signal). On a non-retryable
154
193
  // failure it does exactly what a bare prompt() did: the throw propagates, or the
155
194
  // soft error stays on the leaf for the caller to read.
195
+ export type SameRefPromptResult = { success: boolean; lastError?: Error }
196
+
156
197
  export async function promptWithSameRefRetryOnly(
157
198
  session: AgentSession,
158
199
  text: string,
159
200
  promptOpts?: Parameters<AgentSession['prompt']>[1],
160
- ): Promise<void> {
201
+ opts: {
202
+ retryPolicy?: RetryPolicy
203
+ random?: () => number
204
+ now?: () => number
205
+ patientBackoffMs?: (attempt: number) => number
206
+ } = {},
207
+ ): Promise<SameRefPromptResult> {
208
+ const now = opts.now ?? (() => performance.now())
161
209
  let softError: Error | undefined
162
210
  // Feature-detect subscribe: some lightweight call sites / test fakes pass a
163
211
  // session without an event stream. Without it we simply can't observe soft
@@ -173,29 +221,61 @@ export async function promptWithSameRefRetryOnly(
173
221
  // transcript shape → retryTurnOnPersistentSession returns false) still
174
222
  // surfaces the original failure instead of resolving as a phantom success.
175
223
  let priorHardError: Error | undefined
224
+ let lastError: Error | undefined
225
+ let overloadRetries = 0
226
+ let patientWindowStartedAt: number | undefined
227
+ let nextDelayMs: number | undefined
176
228
  for (let attempt = 0; ; attempt++) {
177
229
  softError = undefined
178
230
  let hardError: Error | undefined
179
231
  try {
180
232
  if (attempt === 0) {
181
233
  await session.prompt(text, promptOpts)
182
- } else if (!(await retryTurnOnPersistentSession(session, { attempt: attempt - 1 }))) {
234
+ } else if (
235
+ !(await retryTurnOnPersistentSession(session, {
236
+ attempt: attempt - 1,
237
+ ...(nextDelayMs !== undefined ? { delayMs: nextDelayMs } : {}),
238
+ }))
239
+ ) {
183
240
  // Continue-recipe not applicable: replay never happened, so the prior
184
241
  // failure stands — re-throw a hard error, or return to leave a soft
185
242
  // error on the leaf (bare-prompt() semantics).
186
243
  if (priorHardError !== undefined) throw priorHardError
187
- return
244
+ return { success: false, ...(lastError !== undefined ? { lastError } : {}) }
188
245
  }
189
246
  } catch (err) {
190
247
  hardError = err instanceof Error ? err : new Error(String(err))
191
248
  }
192
249
  const error = hardError ?? softError
193
- if (error === undefined) return
194
- if (attempt >= RETRIES_PER_REF || !isRetryableSameRef(error.message)) {
250
+ if (error === undefined) return { success: true }
251
+ lastError = error
252
+ // A patient call site rides out a capacity outage on the same ref: there is
253
+ // no cross-ref failover on this path, so declining to retry an overload
254
+ // (isRetryableSameRef excludes it, expecting failover to handle it) would
255
+ // leave it with no recovery at all.
256
+ // The delay is budgeted BEFORE the retry is accepted: an elapsed-only check
257
+ // would let a retry taken just under the deadline sleep past it.
258
+ const nowMs = now()
259
+ const patientDelayMs =
260
+ opts.retryPolicy === 'patient' && isThrottleOrOverload(error.message)
261
+ ? (opts.patientBackoffMs ?? ((n: number) => patientOverloadBackoffMs(n, opts.random)))(overloadRetries)
262
+ : undefined
263
+ const patientElapsedMs = patientWindowStartedAt === undefined ? 0 : nowMs - patientWindowStartedAt
264
+ const patientOverload =
265
+ patientDelayMs !== undefined &&
266
+ overloadRetries < PATIENT_OVERLOAD_RETRIES &&
267
+ patientElapsedMs + patientDelayMs <= PATIENT_OVERLOAD_WINDOW_MS
268
+ if (patientOverload) {
269
+ patientWindowStartedAt ??= nowMs
270
+ nextDelayMs = patientDelayMs
271
+ overloadRetries++
272
+ } else if (attempt < RETRIES_PER_REF && isRetryableSameRef(error.message)) {
273
+ nextDelayMs = undefined
274
+ } else {
195
275
  // Out of budget or not retryable: preserve bare-prompt() semantics — a
196
276
  // hard error throws; a soft error stays on the leaf for the caller.
197
277
  if (hardError !== undefined) throw hardError
198
- return
278
+ return { success: false, lastError: error }
199
279
  }
200
280
  priorHardError = hardError
201
281
  }
@@ -10,8 +10,8 @@ import { applyTurnThinkingLevel } from './attention-escalation'
10
10
  import { type AgentSession, createSession, type PluginSessionWiring } from './index'
11
11
  import { resolveFallbackChain } from './model-fallback'
12
12
  import { applyModelRuntimeOverrides } from './model-overrides'
13
- import { isFailoverWorthy, subscribeProviderErrors } from './provider-error'
14
- import { promptWithSameRefRetryOnly } from './retry-same-ref'
13
+ import { detectHardProviderError, isFailoverWorthy, subscribeProviderErrors } from './provider-error'
14
+ import { promptWithSameRefRetryOnly, type RetryPolicy } from './retry-same-ref'
15
15
  import type { SubagentBashPolicy } from './reviewer-bash-policy'
16
16
  import type { SessionOrigin } from './session-origin'
17
17
  import {
@@ -300,8 +300,35 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
300
300
  normalizeSubagentSession(await createSessionForSubagent(subagent, sessionOptions))
301
301
  let aborted = false
302
302
  let activeModelRef = resolveFallbackChain(getConfig().models, resolveSubagentProfile(subagent, sessionOptions))[0]!
303
- let drainWatch: SubagentDrainWatch | undefined
303
+ // Latency tolerance is decided ONCE here, from the REQUESTED profile — not the
304
+ // one resolveProfile() landed on. A `deep` subagent whose operator never
305
+ // configured `models.deep` still runs on a background path nobody is watching
306
+ // live, so it stays patient; a spawn explicitly overridden onto `fast` is an
307
+ // explicit request for responsiveness and loses it.
308
+ const retryPolicy: RetryPolicy =
309
+ resolveSubagentProfile(subagent, sessionOptions) === 'deep' ? 'patient' : 'responsive'
310
+ // MUST be updated after every turn — initial, drain, and nudge — so a later
311
+ // success clears an earlier failure and the guard below reads the true state.
312
+ let latestTurnFailure: Error | undefined
304
313
  const requiredBlockTag = REQUIRED_FINAL_BLOCK[name]
314
+ // A provider failure reaches us as EITHER a soft leaf error or a hard throw
315
+ // (the turn runner rethrows a hard outcome once the chain is spent, and
316
+ // promptWithSameRefRetryOnly rethrows an exhausted hard error). Recording only
317
+ // the soft shape would let a thrown outage escape as a subagent crash and skip
318
+ // the required-block fallback entirely.
319
+ //
320
+ // Absorbing the throw is only safe where that fallback exists to turn it into
321
+ // an honest synthetic result. A subagent with no required block has no such
322
+ // surface, so swallowing there would report a clean ok:true for a turn that
323
+ // never ran. Those keep failing, as does anything unrecognized — loop-guard
324
+ // aborts, spawn timeouts, real bugs.
325
+ const recordHardProviderFailure = (err: unknown): void => {
326
+ if (requiredBlockTag === undefined) throw err
327
+ const detected = detectHardProviderError(err)
328
+ if (detected === null) throw err
329
+ latestTurnFailure = new Error(detected.message)
330
+ }
331
+ let drainWatch: SubagentDrainWatch | undefined
305
332
  const capture = attachFinalMessageCapture(session, requiredBlockTag, options.onFinalMessageCaptured ?? (() => {}))
306
333
  if (options.onSessionCreated !== undefined) {
307
334
  options.onSessionCreated({
@@ -346,6 +373,7 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
346
373
  refs: resolveFallbackChain(getConfig().models, resolveSubagentProfile(subagent, sessionOptions)),
347
374
  currentModelRef: activeModelRef,
348
375
  profile: resolveSubagentProfile(subagent, sessionOptions),
376
+ retryPolicy,
349
377
  session,
350
378
  text: turnText,
351
379
  skipProviderErrorSubscription: true,
@@ -367,7 +395,10 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
367
395
  },
368
396
  })
369
397
  if (result.success) activeModelRef = result.refUsed
398
+ latestTurnFailure = result.success ? undefined : result.lastError
370
399
  throwIfLoopGuardAborted(session)
400
+ } catch (err) {
401
+ recordHardProviderFailure(err)
371
402
  } finally {
372
403
  if (hooks && turnEvent !== undefined) {
373
404
  await hooks.runSessionTurnEnd(turnEvent)
@@ -377,7 +408,17 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
377
408
  await runSubagentDrain(drainWatch, {
378
409
  drain: backgroundDrain,
379
410
  prompt: async (text) => {
380
- await promptWithSameRefRetryOnly(session, `${renderTurnTimeAnchor()}\n\n${text}`)
411
+ try {
412
+ const drained = await promptWithSameRefRetryOnly(
413
+ session,
414
+ `${renderTurnTimeAnchor()}\n\n${text}`,
415
+ undefined,
416
+ { retryPolicy },
417
+ )
418
+ latestTurnFailure = drained.success ? undefined : drained.lastError
419
+ } catch (err) {
420
+ recordHardProviderFailure(err)
421
+ }
381
422
  throwIfLoopGuardAborted(session)
382
423
  },
383
424
  cancelled: () => aborted,
@@ -392,23 +433,39 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
392
433
  // final contract-repair pass, not another research phase; it deliberately
393
434
  // does NOT re-run the drain.
394
435
  if (requiredBlockTag !== undefined) {
436
+ // `latestTurnFailure` set means the last turn died on an upstream provider
437
+ // error rather than finishing without the block. Nudging is then pointless
438
+ // — the nudge is itself a model call, so it hits the same failing provider
439
+ // and returns in ms, burning the whole budget in seconds against an outage
440
+ // that outlives it. Skip straight to a fallback that names the real cause.
395
441
  for (
396
442
  let attempt = 1;
397
- !aborted && !capture.hasRequiredBlock() && attempt <= MAX_REQUIRED_BLOCK_RETRIES;
443
+ !aborted &&
444
+ !capture.hasRequiredBlock() &&
445
+ latestTurnFailure === undefined &&
446
+ attempt <= MAX_REQUIRED_BLOCK_RETRIES;
398
447
  attempt++
399
448
  ) {
400
449
  console.warn(
401
450
  `[subagent] ${name} required_block_retry attempt=${attempt}/${MAX_REQUIRED_BLOCK_RETRIES} tag=${requiredBlockTag}`,
402
451
  )
403
- await promptWithSameRefRetryOnly(
404
- session,
405
- `${renderTurnTimeAnchor()}\n\n${renderRequiredBlockRetryNudge(requiredBlockTag)}`,
406
- )
452
+ try {
453
+ const nudge = await promptWithSameRefRetryOnly(
454
+ session,
455
+ `${renderTurnTimeAnchor()}\n\n${renderRequiredBlockRetryNudge(requiredBlockTag)}`,
456
+ undefined,
457
+ { retryPolicy },
458
+ )
459
+ if (!nudge.success) latestTurnFailure = nudge.lastError
460
+ } catch (err) {
461
+ recordHardProviderFailure(err)
462
+ }
407
463
  throwIfLoopGuardAborted(session)
408
464
  }
409
465
  if (!aborted && !capture.hasRequiredBlock()) {
410
- console.warn(`[subagent] ${name} required_block_fallback tag=${requiredBlockTag}`)
411
- capture.setSyntheticFinalMessage(renderMissingRequiredBlockFallback(name, requiredBlockTag))
466
+ const reason: MissingBlockReason = latestTurnFailure !== undefined ? 'provider-failure' : 'missing-block'
467
+ console.warn(`[subagent] ${name} required_block_fallback tag=${requiredBlockTag} reason=${reason}`)
468
+ capture.setSyntheticFinalMessage(renderMissingRequiredBlockFallback(name, requiredBlockTag, reason))
412
469
  }
413
470
  }
414
471
  if (hooks && sessionId !== undefined) {
@@ -686,14 +743,26 @@ Output exactly one <${tag}> block and nothing else.`
686
743
  // src/skills/typeclaw-channel-github/SKILL.md.
687
744
  export const INCOMPLETE_REVIEW_VERDICT = 'incomplete-review-not-a-verdict'
688
745
 
746
+ // Why the block is missing. 'missing-block' is the model's own doing — it ended
747
+ // its turn without emitting the block. 'provider-failure' is an upstream outage:
748
+ // the turn never ran to completion at all. Both produce the SAME sentinel verdict
749
+ // (the downstream contract is identical — no analysis landed), but the prose must
750
+ // name the real cause, or an operator reading a capacity outage is told the
751
+ // subagent misbehaved and re-runs it straight into the same wall.
752
+ type MissingBlockReason = 'missing-block' | 'provider-failure'
753
+
689
754
  // The terminal graceful fallback when the nudges are exhausted. It fabricates NO
690
755
  // findings — only a structured "could not complete" notice — so the parent gets
691
756
  // a usable result instead of stale `<analysis>` or a hard error.
692
- function renderMissingRequiredBlockFallback(name: string, tag: FinalBlockTag): string {
757
+ function renderMissingRequiredBlockFallback(name: string, tag: FinalBlockTag, reason: MissingBlockReason): string {
758
+ const providerFailed = reason === 'provider-failure'
759
+ const cause = providerFailed
760
+ ? `the upstream model provider kept failing (capacity/outage), so the turn never completed`
761
+ : `it ended without emitting the required <${tag}> block`
693
762
  if (tag === 'report') {
694
763
  return `<report>
695
764
  <summary>
696
- The ${name} subagent could not complete a research report in this run: it ended without emitting the required <report> block (a known cause is the report tool not completing). Do not treat any earlier analysis text as findings — rerun the researcher or gather the sources directly if the answer is still needed.
765
+ The ${name} subagent could not complete a research report in this run: ${cause}${providerFailed ? '' : ' (a known cause is the report tool not completing)'}. Do not treat any earlier analysis text as findings — rerun the researcher or gather the sources directly if the answer is still needed.
697
766
  </summary>
698
767
  <report_file>
699
768
  none
@@ -707,16 +776,20 @@ The original research request remains unresolved; rerun the ${name} subagent or
707
776
  </report>`
708
777
  }
709
778
  if (tag === 'review') {
779
+ const headline = providerFailed ? 'UPSTREAM PROVIDER FAILURE — NOT A VERDICT' : 'INCOMPLETE REVIEW — NOT A VERDICT'
780
+ const remedy = providerFailed
781
+ ? 'This is an infrastructure failure, not a judgement on the code. Re-request the review once the provider recovers; do not report it as a review that found nothing.'
782
+ : 'Re-request the review; if it still cannot complete, post an honest "review could not be completed" note and leave existing review state unchanged.'
710
783
  return `<review>
711
784
  <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.
785
+ ${headline}. The ${name} subagent could not complete a review in this run: ${cause}. 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). ${remedy}
713
786
  </summary>
714
787
  <findings>
715
788
  </findings>
716
789
  <verdict>${INCOMPLETE_REVIEW_VERDICT}</verdict>
717
790
  </review>`
718
791
  }
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}>`
792
+ return `<${tag}>\nThe ${name} subagent could not produce the required <${tag}> block (${cause}) and could not recover; rerun it or inspect the transcript.\n</${tag}>`
720
793
  }
721
794
 
722
795
  type SubagentCapture = {
@@ -1,7 +1,7 @@
1
1
  import { formatLocalDateTime, formatLocalWeekday, resolveLocalTimezoneName } from '@/shared'
2
2
 
3
3
  const PACKAGE_JSON_INSTALL_RULE =
4
- "After editing `package.json` (adding, removing, or bumping dependencies/plugins), run the project's package manager to update the lockfile and installed dependency state — e.g. `bun install`, `npm install`, `pnpm install`, or `yarn install`, matching the existing lockfile. Commit the lockfile change alongside the `package.json` edit."
4
+ '`package.json` is operator-owned because direct dependencies define sandbox-visible commands. Do not edit it or install dependencies; tell the operator which package and command are needed.'
5
5
 
6
6
  // The orchestration roster (the `Briefly: ...` enumeration of public subagents)
7
7
  // is GENERATED from the registry by `renderPublicSubagentRoster` and threaded in
@@ -5,9 +5,18 @@ import {
5
5
  detectProviderError,
6
6
  isObserverTtfbTimeout,
7
7
  isRetryableSameRef,
8
+ isThrottleOrOverload,
8
9
  subscribeProviderErrors,
9
10
  } from './provider-error'
10
- import { RETRIES_PER_REF, retryTurnAfterCompletedToolResult, retryTurnOnPersistentSession } from './retry-same-ref'
11
+ import {
12
+ PATIENT_OVERLOAD_RETRIES,
13
+ PATIENT_OVERLOAD_WINDOW_MS,
14
+ patientOverloadBackoffMs,
15
+ RETRIES_PER_REF,
16
+ retryTurnAfterCompletedToolResult,
17
+ retryTurnOnPersistentSession,
18
+ type RetryPolicy,
19
+ } from './retry-same-ref'
11
20
  import { modelThrottleCircuit, type ThrottleCircuit } from './throttle-circuit'
12
21
 
13
22
  export type PersistentTurnAttempt = {
@@ -42,14 +51,20 @@ export async function promptPersistentTurnWithFallback(opts: {
42
51
  shouldFailover: (err: Error) => boolean
43
52
  setModelForRef: (ref: ModelRef) => Promise<void>
44
53
  profile?: string
54
+ retryPolicy?: RetryPolicy
45
55
  circuit?: ThrottleCircuit
46
56
  skipProviderErrorSubscription?: boolean
47
57
  detectSoftErrorFromLeaf?: boolean
48
58
  authorizeRetryAfterCompletedToolResult?: () => boolean
49
59
  retryRandom?: () => number
60
+ patientBackoffMs?: (attempt: number) => number
50
61
  onRetryBackoffStart?: () => void
51
62
  beforeAttempt?: (ref: ModelRef) => void
52
63
  onAttemptFailed?: (attempt: PersistentTurnAttempt) => void
64
+ // Fired the first time an attempt starts executing a tool. Callers use it to
65
+ // learn that the turn stopped being silent even when the turn ultimately
66
+ // fails — including the hard-throw path, where no result is ever returned.
67
+ onToolExecutionStarted?: () => void
53
68
  now?: () => number
54
69
  }): Promise<PersistentTurnResult> {
55
70
  if (opts.refs.length === 0) throw new Error('promptPersistentTurnWithFallback: refs[] must be non-empty')
@@ -95,7 +110,7 @@ export async function promptPersistentTurnWithFallback(opts: {
95
110
  // subagents. `skipProviderErrorSubscription` only suppresses the soft-error
96
111
  // listener (subagents capture their final message off the leaf instead, via
97
112
  // detectSoftErrorFromLeaf, so a second listener would race that capture).
98
- const unsubActivity = subscribeAttemptActivity(opts.session, activity)
113
+ const unsubActivity = subscribeAttemptActivity(opts.session, activity, opts.onToolExecutionStarted)
99
114
  const unsubProvider = opts.skipProviderErrorSubscription
100
115
  ? () => {}
101
116
  : subscribeProviderErrorsIfAvailable(opts.session, (err) => {
@@ -107,6 +122,9 @@ export async function promptPersistentTurnWithFallback(opts: {
107
122
  // later iterations resume via agent.continue() (no user-message re-append).
108
123
  let outcome: AttemptOutcome | undefined
109
124
  let retryAfterCompletedToolResult = false
125
+ let overloadRetries = 0
126
+ let patientWindowStartedAt: number | undefined
127
+ let nextDelayMs: number | undefined
110
128
  for (let retry = 0; ; retry++) {
111
129
  softError = undefined
112
130
  const attemptStartedAt = now()
@@ -119,10 +137,14 @@ export async function promptPersistentTurnWithFallback(opts: {
119
137
  ? await retryTurnAfterCompletedToolResult(opts.session, {
120
138
  attempt: retry - 1,
121
139
  authorize: () => opts.authorizeRetryAfterCompletedToolResult?.() === true,
140
+ ...(nextDelayMs !== undefined ? { delayMs: nextDelayMs } : {}),
122
141
  ...(opts.retryRandom !== undefined ? { random: opts.retryRandom } : {}),
123
142
  ...(opts.onRetryBackoffStart !== undefined ? { onBackoffStart: opts.onRetryBackoffStart } : {}),
124
143
  })
125
- : await retryTurnOnPersistentSession(opts.session, { attempt: retry - 1 })
144
+ : await retryTurnOnPersistentSession(opts.session, {
145
+ attempt: retry - 1,
146
+ ...(nextDelayMs !== undefined ? { delayMs: nextDelayMs } : {}),
147
+ })
126
148
  // The safe continue-recipe couldn't apply: keep the PREVIOUS failure
127
149
  // outcome (never cleared) and let it drive the advance/return below.
128
150
  if (!retried) break
@@ -145,7 +167,27 @@ export async function promptPersistentTurnWithFallback(opts: {
145
167
  // Retry within budget only when the failure is same-ref retryable and
146
168
  // either no visible/tool activity occurred, or the caller explicitly
147
169
  // authorizes the strict post-tool-result resume recipe.
148
- const retryableWithinBudget = retry < RETRIES_PER_REF && isRetryableSameRef(outcome.error.message)
170
+ // Overload means "this ref is out of capacity NOW", so the standing policy
171
+ // is to fail OVER rather than burn same-ref retries — which is why
172
+ // isRetryableSameRef excludes it. But on the LAST usable ref there is
173
+ // nothing to fail over to, and a single-ref chain is all last, so that
174
+ // policy leaves a capacity outage with no recovery whatsoever. A patient
175
+ // call site rides it out here instead; a responsive one still fails fast.
176
+ // Budget the delay BEFORE accepting the retry. Testing only the elapsed
177
+ // window lets a retry accepted just under the deadline sleep past it, so
178
+ // the next provider attempt would START after the window we advertise.
179
+ const nowMs = now()
180
+ const patientDelayMs =
181
+ opts.retryPolicy === 'patient' && isLast && isThrottleOrOverload(outcome.error.message)
182
+ ? (opts.patientBackoffMs ?? ((n: number) => patientOverloadBackoffMs(n, opts.retryRandom)))(overloadRetries)
183
+ : undefined
184
+ const patientElapsedMs = patientWindowStartedAt === undefined ? 0 : nowMs - patientWindowStartedAt
185
+ const patientOverload =
186
+ patientDelayMs !== undefined &&
187
+ overloadRetries < PATIENT_OVERLOAD_RETRIES &&
188
+ patientElapsedMs + patientDelayMs <= PATIENT_OVERLOAD_WINDOW_MS
189
+ const retryableWithinBudget =
190
+ patientOverload || (retry < RETRIES_PER_REF && isRetryableSameRef(outcome.error.message))
149
191
  const mayRetryWithoutActivity = !activity.producedAssistantOutput && !activity.startedToolExecution
150
192
  retryAfterCompletedToolResult =
151
193
  retryableWithinBudget &&
@@ -153,6 +195,13 @@ export async function promptPersistentTurnWithFallback(opts: {
153
195
  opts.authorizeRetryAfterCompletedToolResult?.() === true
154
196
  const mayRetry = retryableWithinBudget && (mayRetryWithoutActivity || retryAfterCompletedToolResult)
155
197
  if (!mayRetry) break
198
+ if (patientOverload) {
199
+ patientWindowStartedAt ??= nowMs
200
+ nextDelayMs = patientDelayMs
201
+ overloadRetries++
202
+ } else {
203
+ nextDelayMs = undefined
204
+ }
156
205
  }
157
206
 
158
207
  if (outcome === undefined) {
@@ -246,13 +295,19 @@ function isRefUsable(
246
295
  return !circuit.isProviderOpen({ profile, ref })
247
296
  }
248
297
 
249
- function subscribeAttemptActivity(session: AgentSession, activity: AttemptActivity): () => void {
298
+ function subscribeAttemptActivity(
299
+ session: AgentSession,
300
+ activity: AttemptActivity,
301
+ onToolExecutionStarted?: () => void,
302
+ ): () => void {
250
303
  const subscribe = (session as { subscribe?: unknown }).subscribe
251
304
  if (typeof subscribe !== 'function') return () => {}
252
305
  return session.subscribe((event: unknown) => {
253
306
  if (!isRecord(event)) return
254
307
  if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') {
308
+ const alreadyStarted = activity.startedToolExecution
255
309
  activity.startedToolExecution = true
310
+ if (!alreadyStarted) onToolExecutionStarted?.()
256
311
  return
257
312
  }
258
313
  if (event.type !== 'message_update') return
@@ -3,10 +3,6 @@ import { join } from 'node:path'
3
3
  import { definePlugin } from '@/plugin'
4
4
  import { publishForwardRequest, subscribeForwardResult } from '@/portbroker'
5
5
 
6
- import { installShim, KNOWN_BIN_PATHS, type InstallShimResult } from './shim-install'
7
-
8
- type SafeResult = InstallShimResult | { kind: 'error'; binPath: string; error: unknown }
9
-
10
6
  // Documented in skills/agent-browser/SKILL.md so the agent can discover which
11
7
  // host port the reserved dashboard forward actually bound. Moving or renaming
12
8
  // this path requires updating the skill in lockstep. The env override is an
@@ -27,10 +23,6 @@ let unsubscribeForwardResult: (() => void) | null = null
27
23
 
28
24
  export default definePlugin({
29
25
  plugin: async (ctx) => {
30
- for (const binPath of Object.values(KNOWN_BIN_PATHS)) {
31
- logInstallResult(ctx.logger, safeInstallShim(binPath))
32
- }
33
-
34
26
  requestDashboardForward(ctx.logger)
35
27
 
36
28
  return {
@@ -85,30 +77,3 @@ async function recordProxyPort(contents: string, logger: { warn: (msg: string) =
85
77
  logger.warn(`failed to write ${path}: ${String(error)}`)
86
78
  }
87
79
  }
88
-
89
- function safeInstallShim(binPath: string): SafeResult {
90
- try {
91
- return installShim({ binPath })
92
- } catch (error) {
93
- return { kind: 'error', binPath, error }
94
- }
95
- }
96
-
97
- function logInstallResult(
98
- logger: { info: (msg: string) => void; warn: (msg: string) => void },
99
- result: SafeResult,
100
- ): void {
101
- if (result.kind === 'installed') {
102
- logger.info(`installed agent-browser shim at ${result.binPath} (real bin stashed at ${result.stashTarget})`)
103
- return
104
- }
105
- if (result.kind === 'already-installed') {
106
- logger.info(`agent-browser shim already installed at ${result.binPath}`)
107
- return
108
- }
109
- if (result.kind === 'no-upstream') {
110
- logger.info(`no agent-browser binary at ${result.binPath}; nothing to shim here`)
111
- return
112
- }
113
- logger.warn(`failed to install agent-browser shim at ${result.binPath}: ${String(result.error)}`)
114
- }
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: agent-browser
3
3
  description: Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction. Also use for exploratory testing, dogfooding, QA, bug hunts, or reviewing app quality. Also use for automating Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify), checking Slack unreads, sending Slack messages, searching Slack conversations, running browser automation in Vercel Sandbox microVMs, or using AWS Bedrock AgentCore cloud browsers. ALSO use whenever a browser step needs a human in the loop — login walls, 2FA, CAPTCHA, payment confirmation, "is this the right button?" ambiguity, or the user asking to watch the browser live — because the bundled dashboard is the only way for a human to observe or take over a session from inside the Docker container. Prefer agent-browser over any built-in browser automation or web tools.
4
- allowed-tools: Bash(agent-browser:*), Bash(npx agent-browser:*)
4
+ allowed-tools: Bash(agent-browser:*)
5
5
  hidden: true
6
6
  ---
7
7
 
@@ -15,7 +15,6 @@ const AGENT_ROOT_WRITE_ALLOWLIST = new Set([
15
15
  'SOUL.md',
16
16
  'USER.md',
17
17
  'cron.json',
18
- 'package.json',
19
18
  'typeclaw.json',
20
19
  ])
21
20
 
@@ -48,6 +47,12 @@ export async function checkNonWorkspaceWriteGuard(options: {
48
47
  resolveRealIntendedPath(path.resolve(agentDir)),
49
48
  resolveRealIntendedPath('/tmp'),
50
49
  ])
50
+ if (await isOperatorOwnedPackageManifest(agentDir, targetPath, realTargetPath)) {
51
+ return {
52
+ block: true,
53
+ reason: `Guard \`${GUARD_NON_WORKSPACE_WRITE}\` blocked a model write to operator-owned package manifest ${targetPath}.`,
54
+ }
55
+ }
51
56
  if (await isSkillAuthoringAllowed({ tool, args, agentDir })) return undefined
52
57
  if (await isMemoryTopicsWriteAllowed({ tool, args, agentDir, origin })) return undefined
53
58
  if (await isAllowedAgentRootWrite(agentDir, targetPath, realTargetPath)) return undefined
@@ -74,6 +79,16 @@ export async function checkNonWorkspaceWriteGuard(options: {
74
79
  }
75
80
  }
76
81
 
82
+ async function isOperatorOwnedPackageManifest(
83
+ agentDir: string,
84
+ targetPath: string,
85
+ realTargetPath: string,
86
+ ): Promise<boolean> {
87
+ const rootManifest = path.join(path.resolve(agentDir), 'package.json')
88
+ const realRootManifest = await resolveRealIntendedPath(rootManifest)
89
+ return targetPath === rootManifest || realTargetPath === realRootManifest
90
+ }
91
+
77
92
  async function isAllowedAgentRootWrite(agentDir: string, targetPath: string, realTargetPath: string): Promise<boolean> {
78
93
  const resolvedAgentDir = path.resolve(agentDir)
79
94
  if (path.dirname(targetPath) === resolvedAgentDir && AGENT_ROOT_WRITE_ALLOWLIST.has(path.basename(targetPath))) {