typeclaw 0.47.1 → 0.47.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.47.1",
3
+ "version": "0.47.2",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -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 = {
@@ -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,11 +51,13 @@ 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
@@ -107,6 +118,9 @@ export async function promptPersistentTurnWithFallback(opts: {
107
118
  // later iterations resume via agent.continue() (no user-message re-append).
108
119
  let outcome: AttemptOutcome | undefined
109
120
  let retryAfterCompletedToolResult = false
121
+ let overloadRetries = 0
122
+ let patientWindowStartedAt: number | undefined
123
+ let nextDelayMs: number | undefined
110
124
  for (let retry = 0; ; retry++) {
111
125
  softError = undefined
112
126
  const attemptStartedAt = now()
@@ -119,10 +133,14 @@ export async function promptPersistentTurnWithFallback(opts: {
119
133
  ? await retryTurnAfterCompletedToolResult(opts.session, {
120
134
  attempt: retry - 1,
121
135
  authorize: () => opts.authorizeRetryAfterCompletedToolResult?.() === true,
136
+ ...(nextDelayMs !== undefined ? { delayMs: nextDelayMs } : {}),
122
137
  ...(opts.retryRandom !== undefined ? { random: opts.retryRandom } : {}),
123
138
  ...(opts.onRetryBackoffStart !== undefined ? { onBackoffStart: opts.onRetryBackoffStart } : {}),
124
139
  })
125
- : await retryTurnOnPersistentSession(opts.session, { attempt: retry - 1 })
140
+ : await retryTurnOnPersistentSession(opts.session, {
141
+ attempt: retry - 1,
142
+ ...(nextDelayMs !== undefined ? { delayMs: nextDelayMs } : {}),
143
+ })
126
144
  // The safe continue-recipe couldn't apply: keep the PREVIOUS failure
127
145
  // outcome (never cleared) and let it drive the advance/return below.
128
146
  if (!retried) break
@@ -145,7 +163,27 @@ export async function promptPersistentTurnWithFallback(opts: {
145
163
  // Retry within budget only when the failure is same-ref retryable and
146
164
  // either no visible/tool activity occurred, or the caller explicitly
147
165
  // authorizes the strict post-tool-result resume recipe.
148
- const retryableWithinBudget = retry < RETRIES_PER_REF && isRetryableSameRef(outcome.error.message)
166
+ // Overload means "this ref is out of capacity NOW", so the standing policy
167
+ // is to fail OVER rather than burn same-ref retries — which is why
168
+ // isRetryableSameRef excludes it. But on the LAST usable ref there is
169
+ // nothing to fail over to, and a single-ref chain is all last, so that
170
+ // policy leaves a capacity outage with no recovery whatsoever. A patient
171
+ // call site rides it out here instead; a responsive one still fails fast.
172
+ // Budget the delay BEFORE accepting the retry. Testing only the elapsed
173
+ // window lets a retry accepted just under the deadline sleep past it, so
174
+ // the next provider attempt would START after the window we advertise.
175
+ const nowMs = now()
176
+ const patientDelayMs =
177
+ opts.retryPolicy === 'patient' && isLast && isThrottleOrOverload(outcome.error.message)
178
+ ? (opts.patientBackoffMs ?? ((n: number) => patientOverloadBackoffMs(n, opts.retryRandom)))(overloadRetries)
179
+ : undefined
180
+ const patientElapsedMs = patientWindowStartedAt === undefined ? 0 : nowMs - patientWindowStartedAt
181
+ const patientOverload =
182
+ patientDelayMs !== undefined &&
183
+ overloadRetries < PATIENT_OVERLOAD_RETRIES &&
184
+ patientElapsedMs + patientDelayMs <= PATIENT_OVERLOAD_WINDOW_MS
185
+ const retryableWithinBudget =
186
+ patientOverload || (retry < RETRIES_PER_REF && isRetryableSameRef(outcome.error.message))
149
187
  const mayRetryWithoutActivity = !activity.producedAssistantOutput && !activity.startedToolExecution
150
188
  retryAfterCompletedToolResult =
151
189
  retryableWithinBudget &&
@@ -153,6 +191,13 @@ export async function promptPersistentTurnWithFallback(opts: {
153
191
  opts.authorizeRetryAfterCompletedToolResult?.() === true
154
192
  const mayRetry = retryableWithinBudget && (mayRetryWithoutActivity || retryAfterCompletedToolResult)
155
193
  if (!mayRetry) break
194
+ if (patientOverload) {
195
+ patientWindowStartedAt ??= nowMs
196
+ nextDelayMs = patientDelayMs
197
+ overloadRetries++
198
+ } else {
199
+ nextDelayMs = undefined
200
+ }
156
201
  }
157
202
 
158
203
  if (outcome === undefined) {
@@ -27,9 +27,8 @@ let unsubscribeForwardResult: (() => void) | null = null
27
27
 
28
28
  export default definePlugin({
29
29
  plugin: async (ctx) => {
30
- for (const binPath of Object.values(KNOWN_BIN_PATHS)) {
31
- logInstallResult(ctx.logger, safeInstallShim(binPath))
32
- }
30
+ logInstallResult(ctx.logger, safeInstallShim(KNOWN_BIN_PATHS.global))
31
+ logInstallResult(ctx.logger, safeInstallShim(KNOWN_BIN_PATHS.local, KNOWN_BIN_PATHS.global))
33
32
 
34
33
  requestDashboardForward(ctx.logger)
35
34
 
@@ -86,9 +85,9 @@ async function recordProxyPort(contents: string, logger: { warn: (msg: string) =
86
85
  }
87
86
  }
88
87
 
89
- function safeInstallShim(binPath: string): SafeResult {
88
+ function safeInstallShim(binPath: string, delegateTarget?: string): SafeResult {
90
89
  try {
91
- return installShim({ binPath })
90
+ return installShim({ binPath, delegateTarget })
92
91
  } catch (error) {
93
92
  return { kind: 'error', binPath, error }
94
93
  }
@@ -102,6 +101,10 @@ function logInstallResult(
102
101
  logger.info(`installed agent-browser shim at ${result.binPath} (real bin stashed at ${result.stashTarget})`)
103
102
  return
104
103
  }
104
+ if (result.kind === 'delegated') {
105
+ logger.info(`installed agent-browser alias at ${result.binPath} (delegates to ${result.delegateTarget})`)
106
+ return
107
+ }
105
108
  if (result.kind === 'already-installed') {
106
109
  logger.info(`agent-browser shim already installed at ${result.binPath}`)
107
110
  return
@@ -16,11 +16,14 @@ const DEFAULT_GLOBAL_BIN_PATH = '/usr/local/bin/agent-browser'
16
16
  const DEFAULT_LOCAL_BIN_PATH = '/agent/node_modules/.bin/agent-browser'
17
17
  const STASH_ROOT = '/usr/local/lib/typeclaw-agent-browser'
18
18
  const SHIM_MARKER = '# typeclaw-agent-browser-shim'
19
+ const IMAGE_WRAPPER_MARKER = '# typeclaw-agent-browser-image-wrapper'
20
+ const LOCAL_ALIAS_MARKER = '# typeclaw-agent-browser-local-alias'
19
21
 
20
22
  export type InstallShimOptions = {
21
23
  binPath?: string
22
24
  stashDir?: string
23
25
  shimEntry?: string
26
+ delegateTarget?: string
24
27
  fs?: ShimFs
25
28
  }
26
29
 
@@ -42,6 +45,7 @@ export type ShimFs = {
42
45
 
43
46
  export type InstallShimResult =
44
47
  | { kind: 'installed'; realBin: string; binPath: string; stashTarget: string }
48
+ | { kind: 'delegated'; binPath: string; delegateTarget: string }
45
49
  | { kind: 'already-installed'; binPath: string }
46
50
  | { kind: 'no-upstream'; binPath: string }
47
51
 
@@ -55,13 +59,15 @@ export function installShim(opts: InstallShimOptions = {}): InstallShimResult {
55
59
  const stat = fs.lstat(binPath)
56
60
  if (stat === null) return { kind: 'no-upstream', binPath }
57
61
 
58
- if (isAlreadyShim(binPath, fs)) {
62
+ const wrapperKind = getWrapperKind(binPath, fs)
63
+ if (wrapperKind === 'image' || wrapperKind === 'local-alias') {
64
+ return { kind: 'already-installed', binPath }
65
+ }
66
+ if (wrapperKind === 'runtime' && opts.delegateTarget === undefined) {
59
67
  if (fs.statExists(stashTarget)) return { kind: 'already-installed', binPath }
60
- // Wrapper survived a container restart but the image-owned stash did not
61
- // (STASH_ROOT lives outside the bind-mount). The wrapper now points at a
62
- // non-existent stashTarget, so executing it would ENOENT. Drop it and
63
- // report no-upstream — there is nothing valid here to preserve, and the
64
- // global-path shim (if it exists) stands on its own.
68
+ // The stash this wrapper points at is gone (STASH_ROOT lives outside the
69
+ // bind-mount), so executing it would ENOENT. Nothing here is worth
70
+ // preserving; drop it and report no-upstream.
65
71
  fs.unlink(binPath)
66
72
  return { kind: 'no-upstream', binPath }
67
73
  }
@@ -72,6 +78,11 @@ export function installShim(opts: InstallShimOptions = {}): InstallShimResult {
72
78
  // anything — otherwise we'd stash a broken symlink and write a wrapper
73
79
  // pointing at a target that never resolves.
74
80
  if (!fs.statExists(binPath)) return { kind: 'no-upstream', binPath }
81
+ if (opts.delegateTarget !== undefined) {
82
+ fs.unlink(binPath)
83
+ fs.writeFile(binPath, renderDelegatingWrapper(opts.delegateTarget), 0o755)
84
+ return { kind: 'delegated', binPath, delegateTarget: opts.delegateTarget }
85
+ }
75
86
 
76
87
  const realBin = resolveCurrentTarget(binPath, stat, fs)
77
88
  fs.mkdirp(stashDir)
@@ -102,11 +113,14 @@ function defaultStashDir(binPath: string): string {
102
113
  return join(STASH_ROOT, slug)
103
114
  }
104
115
 
105
- function isAlreadyShim(binPath: string, fs: ShimFs): boolean {
116
+ function getWrapperKind(binPath: string, fs: ShimFs): 'image' | 'local-alias' | 'runtime' | null {
106
117
  try {
107
- return fs.readFile(binPath).includes(SHIM_MARKER)
118
+ const contents = fs.readFile(binPath)
119
+ if (contents.includes(IMAGE_WRAPPER_MARKER)) return 'image'
120
+ if (contents.includes(LOCAL_ALIAS_MARKER)) return 'local-alias'
121
+ return contents.includes(SHIM_MARKER) ? 'runtime' : null
108
122
  } catch {
109
- return false
123
+ return null
110
124
  }
111
125
  }
112
126
 
@@ -124,6 +138,13 @@ exec bun run ${shimEntry} "$@"
124
138
  `
125
139
  }
126
140
 
141
+ function renderDelegatingWrapper(delegateTarget: string): string {
142
+ return `#!/bin/sh
143
+ ${LOCAL_ALIAS_MARKER}
144
+ exec "${delegateTarget}" "$@"
145
+ `
146
+ }
147
+
127
148
  function defaultShimEntry(): string {
128
149
  return resolvePath(import.meta.dir, 'shim.ts')
129
150
  }
@@ -71,8 +71,15 @@ export function createOperatorSubagent(): Subagent<OperatorPayload> {
71
71
  payloadSchema: operatorPayloadSchema,
72
72
  visibility: 'public',
73
73
  rosterDescription:
74
- 'write-capable: bash-with-side-effects, write, edit — for browser sessions, refactors, deploys, batch ops, and Claude Code / Codex CLI driving; gated by `subagent.spawn.operator`, owner/trusted only — on denial, do the work yourself',
75
- requiresSpecificPermission: true,
74
+ 'write-capable: bash-with-side-effects, write, edit — for browser sessions, refactors, deploys, batch ops, and Claude Code / Codex CLI driving; runs at YOUR role, so it can do nothing here you could not already do inline',
75
+ // No `requiresSpecificPermission`: a subagent inherits `spawnedByRole`, and
76
+ // main sessions are never narrowed to a subset of the builtin tools, so a
77
+ // caller already holds every tool listed above. Gating the spawn bought no
78
+ // authorization — it only forced the same mutations to happen inline, in a
79
+ // dirtier context, and (unlike this subagent) with `channel_reply` in reach.
80
+ // The real boundaries are the non-ackable escalation guards, hidden-path
81
+ // masking, and the github-cli-auth token overlay, all of which bind parent
82
+ // and child identically.
76
83
  canSpawnSubagents: true,
77
84
  inFlightKey: (payload) => payload?.requestId ?? `anon-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
78
85
  toolResultBudget: {
@@ -212,12 +212,10 @@ If none of the listed skills fit the question, load \`general\`. Keep the skill-
212
212
  visibility: 'public',
213
213
  rosterDescription:
214
214
  'deep multi-source investigation in a fresh context — decomposes a fuzzy question, gathers from many sources, cross-validates, and returns a citation-backed report; the quality-over-speed counterpart to `scout`, for any research that needs more than one lookup',
215
- // No `requiresSpecificPermission`: unlike `operator` (generic write/edit +
216
- // side-effecting bash), the researcher's only write goes through the
217
- // `write_report` tool, which enforces "one report file under
218
- // workspace/public" in code. That narrow, code-enforced capability does not
219
- // warrant operator's owner/trusted-only gate; any caller that can spawn a
220
- // subagent can spawn the researcher.
215
+ // No `requiresSpecificPermission`: the researcher's only write goes through
216
+ // the `write_report` tool, which enforces "one report file under
217
+ // workspace/public" in code. Any caller that can spawn a subagent can spawn
218
+ // the researcher.
221
219
  canSpawnSubagents: true,
222
220
  canBackgroundSpawnSubagents: true,
223
221
  timeoutMs: RESEARCHER_SPAWN_TIMEOUT_MS,
@@ -1265,14 +1265,14 @@ RUN chmod +x ${TYPECLAW_CX_SESSION_START_HOOK_PATH} ${TYPECLAW_CX_STOP_HOOK_PATH
1265
1265
  }
1266
1266
 
1267
1267
  // Shared-library runtime deps Chrome for Testing needs to launch on amd64
1268
- // Debian trixie (base of `oven/bun:1-slim`). `agent-browser install
1269
- // --with-deps` (v0.27.0) is supposed to install these but silently no-ops:
1270
- // its hardcoded list omits `libglib2.0-0t64`, so Chrome dies on launch
1271
- // with `libglib-2.0.so.0: cannot open shared object file` even though the
1272
- // binary download and `--with-deps` both exit 0. We install the full
1273
- // Playwright-tested chromium dep set here in Layer 2 so the bug doesn't
1274
- // recur if upstream omits another package; Layer 5 still calls
1275
- // `--with-deps` as a no-op-on-cache-hit backstop for future deps.
1268
+ // Debian trixie (base of `oven/bun:1-slim`). This layer is the ONLY thing
1269
+ // that installs them. `agent-browser install --with-deps` looks like it
1270
+ // would, but it cannot: it shells out to `sudo apt-get` and there is no
1271
+ // sudo in the image. Its hardcoded list also omits `libglib2.0-0t64`
1272
+ // (still true at 0.33.0), so even where apt worked Chrome would die on
1273
+ // launch with `libglib-2.0.so.0: cannot open shared object file`. We
1274
+ // install the full Playwright-tested chromium dep set here so the bug
1275
+ // doesn't recur if upstream omits another package.
1276
1276
  //
1277
1277
  // Package list mirrors Playwright's `debian13-x64` chromium deps in
1278
1278
  // nativeDeps.ts (https://github.com/microsoft/playwright). t64-suffixed
@@ -1488,7 +1488,7 @@ ${renderAgentBrowserInstallLayer(buildKit)}
1488
1488
 
1489
1489
  ${LAYER_4_5_AGENT_BROWSER_HEADED_WRAPPER}
1490
1490
 
1491
- ${renderChromeForTestingLayer(buildKit)}
1491
+ ${renderChromeForTestingLayer()}
1492
1492
 
1493
1493
  ${cloudflaredBlock}${claudeCodeBlock}${codexCliBlock}${renderEntrypointShimLayer()}
1494
1494
  ${renderGitAskPassLayer()}
@@ -1566,7 +1566,7 @@ ${renderAgentBrowserInstallLayer(true)}
1566
1566
 
1567
1567
  ${LAYER_4_5_AGENT_BROWSER_HEADED_WRAPPER}
1568
1568
 
1569
- ${renderChromeForTestingLayer(true)}
1569
+ ${renderChromeForTestingLayer()}
1570
1570
 
1571
1571
  ${renderEntrypointShimLayer()}
1572
1572
  ${renderGitAskPassLayer()}
@@ -1641,7 +1641,7 @@ RUN if [ "$TARGETARCH" = "arm64" ]; then \\
1641
1641
  const renderAgentBrowserInstallLayer = (buildKit: boolean): string =>
1642
1642
  `# Layer 4 (volatile): install agent-browser globally so it survives the
1643
1643
  # runtime bind-mount over /agent/node_modules.
1644
- RUN ${bunCacheMount(buildKit)}bun install -g agent-browser@^0.27.0`
1644
+ RUN ${bunCacheMount(buildKit)}bun install -g agent-browser@^0.33.0`
1645
1645
 
1646
1646
  // Layer 4.5: shim the agent-browser binary with a wrapper that calls
1647
1647
  // \`agent-browser close\` before \`open\`/\`goto\`/\`navigate\` when headed
@@ -1692,6 +1692,7 @@ RUN mv /usr/local/bin/agent-browser /usr/local/bin/agent-browser.real \\
1692
1692
  && cat > /usr/local/bin/agent-browser <<'TYPECLAW_AGENT_BROWSER_WRAPPER_EOF' \\
1693
1693
  && chmod +x /usr/local/bin/agent-browser
1694
1694
  #!/bin/sh
1695
+ # typeclaw-agent-browser-image-wrapper
1695
1696
  # typeclaw wrapper for agent-browser — see src/init/dockerfile.ts.
1696
1697
  set -e
1697
1698
  real="\${TYPECLAW_AGENT_BROWSER_REAL:-/usr/local/bin/agent-browser.real}"
@@ -1701,6 +1702,17 @@ real="\${TYPECLAW_AGENT_BROWSER_REAL:-/usr/local/bin/agent-browser.real}"
1701
1702
  if [ "\${_TYPECLAW_AGENT_BROWSER_HEADED_HANDLED:-}" = "1" ]; then
1702
1703
  exec "$real" "$@"
1703
1704
  fi
1705
+ # Match upstream precedence: an explicit --user-agent flag or non-empty
1706
+ # AGENT_BROWSER_USER_AGENT wins; otherwise use a current desktop Linux UA.
1707
+ has_user_agent=0
1708
+ for arg in "$@"; do
1709
+ case "$arg" in
1710
+ --user-agent|--user-agent=*) has_user_agent=1; break ;;
1711
+ esac
1712
+ done
1713
+ if [ -z "\${AGENT_BROWSER_USER_AGENT:-}" ] && [ "$has_user_agent" = "0" ]; then
1714
+ export AGENT_BROWSER_USER_AGENT='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
1715
+ fi
1704
1716
  # Pre-close is only needed when the caller is requesting headed mode.
1705
1717
  # Match upstream's env_var_is_truthy contract (cli/src/flags.rs:183):
1706
1718
  # truthy = any non-empty value except case-insensitive "0", "false", "no".
@@ -1753,14 +1765,20 @@ TYPECLAW_AGENT_BROWSER_WRAPPER_EOF`
1753
1765
 
1754
1766
  // Layer 5: download the pinned Chrome for Testing build into
1755
1767
  // ~/.agent-browser/browsers/. NO cache mount on that path because the
1756
- // runtime needs the binary in the image. System shared libraries are
1757
- // already installed in Layer 2; --with-deps is a defense-in-depth backstop
1758
- // so a future agent-browser bump that adds new deps installs them
1759
- // automatically (near-no-op when Layer 2 already covers them).
1760
- const renderChromeForTestingLayer = (buildKit: boolean): string =>
1768
+ // runtime needs the binary in the image, and no apt cache mount either
1769
+ // because nothing in this layer runs apt.
1770
+ //
1771
+ // Deliberately NOT `--with-deps`. That flag shells out to `sudo apt-get`
1772
+ // and there is no sudo in the image, so it could never install anything
1773
+ // here. Through 0.27.x it failed silently and still exited 0, which is
1774
+ // why it looked like a working backstop; 0.33.0 made it fail-closed
1775
+ // ("fails if deps fail" in its own --help) and turned that dead no-op
1776
+ // into a hard build failure. Chrome's shared libraries are installed for
1777
+ // real in Layer 2.
1778
+ const renderChromeForTestingLayer = (): string =>
1761
1779
  `# Layer 5 (heavy, amd64 only): Chrome for Testing download.
1762
- RUN ${aptCacheMount(buildKit)}if [ "$TARGETARCH" != "arm64" ]; then \\
1763
- agent-browser install --with-deps; \\
1780
+ RUN if [ "$TARGETARCH" != "arm64" ]; then \\
1781
+ agent-browser install; \\
1764
1782
  fi`
1765
1783
 
1766
1784
  function defaultConfig(): DockerfileConfig {
package/src/init/index.ts CHANGED
@@ -769,7 +769,7 @@ function addCustomModel(
769
769
  // Must match the Dockerfile Layer 4 global install (dockerfile.ts); they are
770
770
  // two installs of the same CLI and a skew is silent. Enforced by a guard test
771
771
  // in packagejson.test.ts.
772
- export const AGENT_BROWSER_VERSION = '^0.27.0'
772
+ export const AGENT_BROWSER_VERSION = '^0.33.0'
773
773
  function buildPackageJson(root: string, name: string, platform: NodeJS.Platform): Record<string, unknown> {
774
774
  return {
775
775
  name,
@@ -89,7 +89,7 @@ To depend on a workspace package from the **agent root** (e.g. so cron `exec` jo
89
89
  {
90
90
  "dependencies": {
91
91
  "typeclaw": "file:../typeclaw",
92
- "agent-browser": "^0.26.0",
92
+ "agent-browser": "^0.33.0",
93
93
  "my-utility": "workspace:*"
94
94
  }
95
95
  }
@@ -43,7 +43,7 @@ State the success condition as something operator can check with `bash` — file
43
43
 
44
44
  Then stay responsive. When the completion `<system-reminder>` lands, weave operator's report into your next reply (in a channel session, surface it via `channel_reply`/`channel_send` — plain text is invisible there).
45
45
 
46
- If the `subagent.spawn.operator` gate denies (you're not owner/trusted tier), you can't delegate — fall back to doing the loop yourself, but apply the mechanics below to do it cleanly.
46
+ If the spawn is denied (no `subagent.spawn` grant at all), you can't delegate — fall back to doing the loop yourself, but apply the mechanics below to do it cleanly.
47
47
 
48
48
  ## Mechanics operator should use (and you, if you can't delegate)
49
49