typeclaw 0.48.13 → 0.49.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 (176) hide show
  1. package/package.json +5 -5
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/index.ts +144 -72
  4. package/src/agent/live-sessions.ts +2 -2
  5. package/src/agent/live-subagents.ts +1 -0
  6. package/src/agent/plugin-tools.ts +53 -11
  7. package/src/agent/prompt-cache-key.ts +42 -0
  8. package/src/agent/provider-error.ts +179 -10
  9. package/src/agent/restart-handoff/index.ts +7 -14
  10. package/src/agent/reviewer-activity.ts +68 -0
  11. package/src/agent/session-origin.ts +33 -0
  12. package/src/agent/subagents.ts +13 -1
  13. package/src/agent/system-prompt.ts +68 -202
  14. package/src/agent/todo/continuation-policy.ts +12 -4
  15. package/src/agent/tool-file-safety.ts +113 -14
  16. package/src/agent/tool-not-found-nudge.ts +1 -1
  17. package/src/agent/tools/channel-history-render.ts +2 -1
  18. package/src/agent/tools/channel-reply.ts +23 -5
  19. package/src/agent/tools/channel-send.ts +49 -7
  20. package/src/agent/tools/curl-impersonate.ts +11 -2
  21. package/src/agent/tools/post-github-review.ts +77 -15
  22. package/src/agent/tools/skip-response.ts +2 -2
  23. package/src/agent/tools/spawn-subagent.ts +163 -12
  24. package/src/agent/tools/subagent-output.ts +8 -0
  25. package/src/bundled-plugins/backup/README.md +10 -9
  26. package/src/bundled-plugins/backup/runner.ts +140 -58
  27. package/src/bundled-plugins/backup/subagents.ts +58 -26
  28. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  29. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  30. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  31. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  32. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  33. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  34. package/src/bundled-plugins/operator/operator.ts +15 -4
  35. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  36. package/src/bundled-plugins/security/index.ts +50 -2
  37. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  38. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  39. package/src/channels/adapters/discord-bot.ts +122 -67
  40. package/src/channels/adapters/discord-reactions.ts +18 -0
  41. package/src/channels/adapters/discord.ts +114 -8
  42. package/src/channels/adapters/github/inbound.ts +103 -8
  43. package/src/channels/adapters/github/index.ts +251 -19
  44. package/src/channels/adapters/github/last-alive.ts +27 -0
  45. package/src/channels/adapters/github/outbound.ts +54 -18
  46. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  47. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  48. package/src/channels/adapters/github/reactions.ts +100 -0
  49. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  50. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  51. package/src/channels/adapters/github/recovery.ts +106 -0
  52. package/src/channels/adapters/github/review-check.ts +510 -0
  53. package/src/channels/adapters/github/review-submitter.ts +34 -2
  54. package/src/channels/adapters/instagram.ts +32 -14
  55. package/src/channels/adapters/kakaotalk.ts +22 -7
  56. package/src/channels/adapters/line.ts +18 -3
  57. package/src/channels/adapters/outbound-account.ts +20 -0
  58. package/src/channels/adapters/own-reactions.ts +66 -0
  59. package/src/channels/adapters/recovery-correlation.ts +214 -0
  60. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  61. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  62. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/slack-bot.ts +125 -57
  64. package/src/channels/adapters/slack-classify.ts +25 -4
  65. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  66. package/src/channels/adapters/slack-reactions.ts +18 -0
  67. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  68. package/src/channels/adapters/slack.ts +48 -3
  69. package/src/channels/adapters/teams.ts +14 -4
  70. package/src/channels/adapters/telegram-bot.ts +56 -10
  71. package/src/channels/adapters/webex-bot.ts +12 -2
  72. package/src/channels/adapters/webex.ts +12 -2
  73. package/src/channels/background-handoff.ts +434 -0
  74. package/src/channels/background-obligations.ts +893 -0
  75. package/src/channels/continuity-types.ts +271 -0
  76. package/src/channels/github-review-check.ts +598 -0
  77. package/src/channels/github-review-turn-ledger.ts +102 -28
  78. package/src/channels/github-review-verdict-coordinator.ts +72 -12
  79. package/src/channels/github-token-bridge.ts +11 -5
  80. package/src/channels/inbound-journal.ts +1738 -0
  81. package/src/channels/index.ts +6 -1
  82. package/src/channels/manager.ts +17 -7
  83. package/src/channels/recovery-dispatcher.ts +264 -0
  84. package/src/channels/recovery-notice.ts +94 -0
  85. package/src/channels/recovery-outbox.ts +459 -0
  86. package/src/channels/router.ts +2539 -615
  87. package/src/channels/schema.ts +8 -1
  88. package/src/channels/subagent-completion-bridge.ts +17 -14
  89. package/src/channels/types.ts +121 -16
  90. package/src/channels/waiting-reactions.ts +664 -0
  91. package/src/cli/compose.ts +7 -4
  92. package/src/cli/hostd.ts +49 -3
  93. package/src/cli/inspect.ts +11 -14
  94. package/src/coding-agent/broker-body.ts +38 -0
  95. package/src/coding-agent/broker.ts +290 -0
  96. package/src/coding-agent/claude.ts +95 -0
  97. package/src/coding-agent/codex.ts +104 -0
  98. package/src/coding-agent/index.ts +506 -0
  99. package/src/coding-agent/omo-state.ts +69 -0
  100. package/src/coding-agent/omo-stream.ts +98 -0
  101. package/src/coding-agent/omo.ts +192 -0
  102. package/src/coding-agent/runner.ts +263 -0
  103. package/src/coding-agent/tool.ts +62 -0
  104. package/src/coding-agent/worktree.ts +355 -0
  105. package/src/compose/restart.ts +10 -3
  106. package/src/compose/start.ts +20 -3
  107. package/src/config/config.ts +10 -3
  108. package/src/config/providers.ts +12 -9
  109. package/src/container/exit-reason.ts +44 -0
  110. package/src/container/index.ts +5 -0
  111. package/src/container/log-archive.ts +51 -13
  112. package/src/container/memory-limit.ts +1 -1
  113. package/src/container/memory-oversubscription.ts +36 -6
  114. package/src/container/oom-events.ts +86 -0
  115. package/src/container/restart.ts +2 -0
  116. package/src/container/shared.ts +8 -1
  117. package/src/container/start.ts +25 -13
  118. package/src/container/stop.ts +6 -2
  119. package/src/container/tool-oom-priority.ts +32 -0
  120. package/src/cron/consumer.ts +10 -4
  121. package/src/cron/reloadable.ts +23 -2
  122. package/src/doctor/checks.ts +14 -2
  123. package/src/hostd/daemon.ts +20 -10
  124. package/src/hostd/spawn.ts +106 -5
  125. package/src/hostd/version.ts +20 -0
  126. package/src/hostd/watchdog.ts +241 -0
  127. package/src/init/dockerfile.ts +57 -592
  128. package/src/init/index.ts +2 -3
  129. package/src/mcp/client.ts +3 -1
  130. package/src/operations/classify-tool-outcome.ts +45 -1
  131. package/src/operations/incidents.ts +10 -5
  132. package/src/plugin/core-tool-names.ts +1 -1
  133. package/src/plugin/define.ts +1 -0
  134. package/src/plugin/index.ts +1 -0
  135. package/src/plugin/types.ts +6 -1
  136. package/src/run/background-handoff-boot.ts +86 -0
  137. package/src/run/index.ts +83 -83
  138. package/src/run/resource-sample.ts +19 -0
  139. package/src/sandbox/build.ts +4 -0
  140. package/src/sandbox/coding-agent.ts +214 -0
  141. package/src/sandbox/policy.ts +1 -0
  142. package/src/sandbox/runtime-private.ts +4 -1
  143. package/src/secrets/coding-agent-auth.ts +97 -0
  144. package/src/secrets/index.ts +0 -16
  145. package/src/server/command-runner.ts +6 -2
  146. package/src/server/index.ts +101 -40
  147. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  148. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  149. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  150. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  151. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  152. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  153. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  154. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  155. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  156. package/src/skills/typeclaw-config/SKILL.md +21 -21
  157. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  158. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  159. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  160. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  161. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  162. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  163. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  164. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  165. package/src/skills/typeclaw-plugins/SKILL.md +15 -15
  166. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  167. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  168. package/typeclaw.schema.json +12 -1
  169. package/src/secrets/claude-credentials-json.ts +0 -129
  170. package/src/secrets/codex-auth-json.ts +0 -102
  171. package/src/secrets/export-claude-credentials-file.ts +0 -270
  172. package/src/secrets/export-codex-auth-file.ts +0 -250
  173. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  174. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  175. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  176. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -1,3 +1,5 @@
1
+ import { isContextOverflow, type AssistantMessage } from '@earendil-works/pi-ai'
2
+
1
3
  import type { AgentSession } from './index'
2
4
 
3
5
  // pi-coding-agent encodes upstream LLM failures (billing, rate limit, network,
@@ -24,14 +26,138 @@ export type DetectedProviderError = {
24
26
  safeMessage: string
25
27
  }
26
28
 
27
- const GENERIC_SAFE_NOTICE = 'The upstream LLM provider failed. Operators can check `typeclaw logs` for details.'
29
+ // Origin-neutral on purpose: an unclassified failure may come from the
30
+ // provider, the network, or TypeClaw itself, and the raw text alone can't say
31
+ // which. Naming the provider here blamed it for local bugs.
32
+ const GENERIC_SAFE_NOTICE = 'The assistant turn failed. Operators can check `typeclaw logs` for details.'
33
+
34
+ // pi-agent-core turns ANY throw inside its loop into the same
35
+ // `stopReason: 'error'` assistant message a provider failure produces, keeping
36
+ // only `errorMessage` (agent.js handleRunFailure) — the error's name, cause and
37
+ // throw site are dropped. So origin must be stamped into the message at the
38
+ // throw site: `wrapTransformContextWithLocalFailureMarker` appends this marker
39
+ // when the context-preparation step that runs before the next provider request
40
+ // throws. It covers only that request; earlier requests in the same run may
41
+ // have reached the provider. Anchored at the end so provider text echoed
42
+ // mid-message can't impersonate it. System token — English by design, like
43
+ // OBSERVER_TIMEOUT.
44
+ const LOCAL_FAILURE_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/
45
+ const LOCAL_PRE_REQUEST_FAILURE = /\(typeclaw local failure before provider request: [A-Za-z][A-Za-z0-9_]{0,63}\)$/
46
+
47
+ type TransformContext = NonNullable<AgentSession['agent']['transformContext']>
48
+
49
+ function readOr<T>(read: () => T, fallback: T): T {
50
+ try {
51
+ return read()
52
+ } catch {
53
+ return fallback
54
+ }
55
+ }
56
+
57
+ export type LocalFailureMarkerOptions = {
58
+ // Provider of the model pi stamps on the failure message. Pi's overflow
59
+ // check has a provider-specific branch, so the same text can trip it for one
60
+ // provider and not another.
61
+ getProvider?: () => string | undefined
62
+ // Receives the raw text when it is withheld from the transcript (see
63
+ // markLocalPreRequestFailure). Defaults to console.error.
64
+ logWithheld?: (line: string) => void
65
+ }
66
+
67
+ const WITHHELD_LOCAL_TEXT =
68
+ 'local error text withheld from the transcript; it resembled provider context-overflow wording and is in typeclaw logs'
69
+
70
+ const NO_USAGE: AssistantMessage['usage'] = {
71
+ input: 0,
72
+ output: 0,
73
+ cacheRead: 0,
74
+ cacheWrite: 0,
75
+ totalTokens: 0,
76
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
77
+ }
78
+
79
+ // Pi's auto-compaction takes any `stopReason:'error'` message its public
80
+ // `isContextOverflow` accepts as a provider context overflow, then compacts and
81
+ // retries the turn (AgentSession._checkCompaction `explicitOverflow`). Called
82
+ // without a context window, this is that exact check, so pattern updates in Pi
83
+ // apply here too.
84
+ function wouldTripPiOverflow(errorMessage: string, provider: string | undefined): boolean {
85
+ return isContextOverflow({
86
+ role: 'assistant',
87
+ content: [],
88
+ api: '',
89
+ provider: provider ?? '',
90
+ model: '',
91
+ usage: NO_USAGE,
92
+ stopReason: 'error',
93
+ errorMessage,
94
+ timestamp: 0,
95
+ })
96
+ }
97
+
98
+ // Only an identifier-shaped `Error.name` is embedded, so a hostile or odd name
99
+ // can't inject parentheses/newlines into the marker. The raw text normally
100
+ // stays on the message for logs and operator surfaces; channels only ever see
101
+ // the fixed LOCAL sentence, never this text. One exception: when the marked
102
+ // text (raw text or name) would trip Pi's overflow check, pi would compact the
103
+ // session and replay a turn that never reached the provider. Then the
104
+ // transcript gets a fixed placeholder and the raw text moves to one
105
+ // `logWithheld` line instead. Reading a throwing getter/`toString`, or a
106
+ // throwing log sink, must not replace the original failure with a new one.
107
+ function markLocalPreRequestFailure(err: unknown, options: LocalFailureMarkerOptions): Error {
108
+ const provider = readOr(() => options.getProvider?.(), undefined)
109
+ const isError = readOr(() => err instanceof Error, false)
110
+ const text = readOr(() => String(isError ? (err as Error).message : err), 'unprintable thrown value')
111
+ if (isError && LOCAL_PRE_REQUEST_FAILURE.test(text) && !wouldTripPiOverflow(text, provider)) return err as Error
112
+ const rawName = readOr(() => (isError ? (err as Error).name : undefined), undefined)
113
+ const name = typeof rawName === 'string' && LOCAL_FAILURE_NAME.test(rawName) ? rawName : 'Error'
114
+ const marked = `${text} (typeclaw local failure before provider request: ${name})`
115
+ if (!wouldTripPiOverflow(marked, provider)) return new Error(marked, { cause: err })
116
+ try {
117
+ ;(options.logWithheld ?? console.error)(`local failure text withheld from the transcript (${name}): ${text}`)
118
+ } catch {
119
+ // The failure being reported matters more than its log line.
120
+ }
121
+ const withheld = `${WITHHELD_LOCAL_TEXT} (typeclaw local failure before provider request: ${name})`
122
+ if (!wouldTripPiOverflow(withheld, provider)) return new Error(withheld, { cause: err })
123
+ // The name itself trips the check (e.g. `request_too_large`).
124
+ return new Error(`${WITHHELD_LOCAL_TEXT} (typeclaw local failure before provider request: Error)`, { cause: err })
125
+ }
126
+
127
+ // Wraps an agent's `transformContext` (the step pi runs right before
128
+ // `convertToLlm`/`getApiKey`/`streamFunction` on every request) so a throw from
129
+ // it — sync or async — is re-thrown with the local-origin marker. An abort is
130
+ // re-thrown untouched: it's a cancellation, and pi reports it as `aborted`.
131
+ export function wrapTransformContextWithLocalFailureMarker(
132
+ inner: TransformContext | undefined,
133
+ options: LocalFailureMarkerOptions = {},
134
+ ): TransformContext {
135
+ return async (messages, signal) => {
136
+ if (!inner) return messages
137
+ try {
138
+ return await inner(messages, signal)
139
+ } catch (err) {
140
+ if (signal?.aborted) throw err
141
+ throw markLocalPreRequestFailure(err, options)
142
+ }
143
+ }
144
+ }
28
145
 
29
146
  // The fetch observer (`llm-fetch-observer`) aborts a stalled provider stream
30
147
  // with a message ending in this marker (TTFB / idle / overall deadline). Such a
31
148
  // stall is a hard throw, not a `stopReason: 'error'` soft error, so it never
32
149
  // reaches `detectProviderError`; the marker lets the hard-throw path recognize
33
150
  // and surface it. The literal is the system's own token — English by design.
34
- const OBSERVER_TIMEOUT = /\(typeclaw observer timeout\)/i
151
+ //
152
+ // The OpenAI and Anthropic SDKs don't let the marker through for the TTFB case:
153
+ // any fetch rejection that mentions "timed out" is replaced by a bare
154
+ // `APIConnectionTimeoutError('Request timed out.')` with no cause. That error is
155
+ // only raised when fetch itself rejects, i.e. before response headers, so it is
156
+ // the same pre-headers stall and must classify like the marked one. Matched as
157
+ // the whole message so the sentence echoed inside other text can't claim it.
158
+ const MARKED_OBSERVER_TIMEOUT = /\(typeclaw observer timeout\)/i
159
+ const SDK_CONNECTION_TIMEOUT = /^Request timed out\.$/
160
+ const OBSERVER_TIMEOUT = new RegExp(`${MARKED_OBSERVER_TIMEOUT.source}|${SDK_CONNECTION_TIMEOUT.source}`, 'i')
35
161
  const OBSERVER_TTFB_TIMEOUT = /timed out before response headers/i
36
162
 
37
163
  // Transport-layer failure: the request died at the connection/session before a
@@ -91,8 +217,14 @@ const INVALID_REQUEST = /\binvalid_request_error\b/i
91
217
  // text, so adding a new class is opt-in and never widens what we expose.
92
218
  const SAFE_CLASSES: ReadonlyArray<{ match: RegExp; safe: string }> = [
93
219
  {
94
- // Matched first because a 401 body can also mention "account", which would
95
- // otherwise fall into the billing class below.
220
+ // First, so provider-looking text inside a local error (a `401` or `429`
221
+ // echoed by a tool, a `quota` word) can't pull it into a provider class.
222
+ match: LOCAL_PRE_REQUEST_FAILURE,
223
+ safe: 'TypeClaw could not prepare the conversation for the LLM request. Operators can check `typeclaw logs` for details.',
224
+ },
225
+ {
226
+ // Matched before billing because a 401 body can also mention "account",
227
+ // which would otherwise fall into the billing class below.
96
228
  match: AUTH_FAULT,
97
229
  safe: 'The upstream LLM provider rejected the request as unauthorized. Operators should check the provider API key configuration and `typeclaw logs`.',
98
230
  },
@@ -141,6 +273,12 @@ const SAFE_CLASSES: ReadonlyArray<{ match: RegExp; safe: string }> = [
141
273
  },
142
274
  ]
143
275
 
276
+ // An unclassified failure names no cause the chat user can act on, so channels
277
+ // treat it as retry-and-see rather than posting the generic notice.
278
+ export function isUnclassifiedProviderNotice(safeMessage: string): boolean {
279
+ return safeMessage === GENERIC_SAFE_NOTICE
280
+ }
281
+
144
282
  function toSafeMessage(raw: string): string {
145
283
  for (const { match, safe } of SAFE_CLASSES) {
146
284
  if (match.test(raw)) return safe
@@ -162,8 +300,11 @@ const THROTTLE_OR_OVERLOAD =
162
300
  // status with a quota/billing/auth reason (e.g. `429 insufficient quota`) — the
163
301
  // status code alone must not force a pointless failover. The auth arm reuses the
164
302
  // shared `AUTH_FAULT` source so it stays in lockstep with the safe-message class.
303
+ // A local pre-request failure is in the same bucket: preparing the context is
304
+ // model-independent, so every ref (and a same-ref replay) would fail the same
305
+ // way — and it must never count as provider throttling.
165
306
  const NON_FAILOVER_FAULT = new RegExp(
166
- `${INVALID_MODEL.source}|${INVALID_REQUEST.source}|\\bcyber_policy\\b|insufficient.*(?:quota|credit|fund|balance)|\\bquota\\b|billing|payment|account is not active|${AUTH_FAULT.source}`,
307
+ `${LOCAL_PRE_REQUEST_FAILURE.source}|${INVALID_MODEL.source}|${INVALID_REQUEST.source}|\\bcyber_policy\\b|insufficient.*(?:quota|credit|fund|balance)|\\bquota\\b|billing|payment|account is not active|${AUTH_FAULT.source}`,
167
308
  'i',
168
309
  )
169
310
 
@@ -177,8 +318,12 @@ export function isThrottleOrOverload(raw: string): boolean {
177
318
  return THROTTLE_OR_OVERLOAD.test(raw)
178
319
  }
179
320
 
321
+ // A local pre-request failure can carry observer text it merely echoes; the
322
+ // request it was preparing was never sent, so it must not count toward the
323
+ // no-progress envelope or trip the codex provider circuit.
180
324
  export function isObserverTtfbTimeout(raw: string): boolean {
181
- return OBSERVER_TIMEOUT.test(raw) && OBSERVER_TTFB_TIMEOUT.test(raw)
325
+ if (LOCAL_PRE_REQUEST_FAILURE.test(raw)) return false
326
+ return (MARKED_OBSERVER_TIMEOUT.test(raw) && OBSERVER_TTFB_TIMEOUT.test(raw)) || SDK_CONNECTION_TIMEOUT.test(raw)
182
327
  }
183
328
 
184
329
  // Failover predicate for turn-drivers' `shouldFailover`: rotate to the next model
@@ -199,10 +344,16 @@ export function isFailoverWorthy(raw: string): boolean {
199
344
  // means the model is out of capacity NOW, so the right move is to fail OVER to a
200
345
  // different ref, not hammer the same one — whereas a socket hang-up or a 500 is a
201
346
  // one-off blip a replay against the SAME ref often fixes. `\b` anchors the 5xx
202
- // codes so they don't match digit runs in prose. Provider protocol tokens —
203
- // English by design (the system-token exception to the multi-language rule).
347
+ // codes so they don't match digit runs in prose. Streaming APIs often report a
348
+ // provider-side 500 inside the event stream with no status code at all, only
349
+ // the provider's own name for it: OpenAI/Codex `server_error` ("An error
350
+ // occurred while processing your request"), Anthropic `api_error`, Gemini
351
+ // `INTERNAL` ("An internal error has occurred"), and the generic "internal
352
+ // server error" / "bad gateway" / "gateway timeout" wording proxies use.
353
+ // Provider protocol tokens — English by design (the system-token exception to
354
+ // the multi-language rule).
204
355
  const NETWORK_OR_5XX =
205
- /econnreset|econnrefused|etimedout|enetunreach|socket hang up|network.?error|connection.?(?:error|refused|reset|lost)|fetch failed|other side closed|reset before headers|http2 request did not get a response|\b(?:500|502|504)\b/i
356
+ /econnreset|econnrefused|etimedout|enetunreach|socket hang up|network.?error|connection.?(?:error|refused|reset|lost)|fetch failed|other side closed|reset before headers|http2 request did not get a response|\b(?:server_error|api_error)\b|"INTERNAL"|an error occurred while processing your request|an internal error has occurred|internal server error|bad gateway|gateway time-?out|\b(?:500|502|504)\b/i
206
357
 
207
358
  // Retry predicate for typeclaw-owned SAME-REF retry: replay the SAME model ref
208
359
  // before advancing the chain. Deliberately NARROWER than `isFailoverWorthy` —
@@ -225,6 +376,22 @@ export function isRetryableSameRef(raw: string): boolean {
225
376
  return TRANSPORT_FAILURE.test(raw) || OBSERVER_TIMEOUT.test(raw) || NETWORK_OR_5XX.test(raw)
226
377
  }
227
378
 
379
+ // Failures a user can only answer with "try again": a dropped transport, an
380
+ // observer stall, a network/5xx blip, or a provider overload. Channels mark
381
+ // these with a reaction instead of posting a notice. Rate/usage limits are
382
+ // excluded even though they say "try again shortly": they can last hours, and
383
+ // a bare reaction on every message would hide why the agent stopped
384
+ // answering. Account-wide faults stay out via `isRetryableSameRef` and
385
+ // NON_FAILOVER_FAULT.
386
+ const OVERLOAD = /overloaded|service.?unavailable|\b503\b/i
387
+ const RATE_OR_USAGE_LIMIT = /usage.?limit|rate.?limit|too many requests|\b429\b/i
388
+
389
+ export function isTransientProviderFailure(raw: string): boolean {
390
+ if (RATE_OR_USAGE_LIMIT.test(raw)) return false
391
+ if (isRetryableSameRef(raw)) return true
392
+ return !NON_FAILOVER_FAULT.test(raw) && !CONTEXT_OVERFLOW.test(raw) && OVERLOAD.test(raw)
393
+ }
394
+
228
395
  export function detectProviderError(message: unknown): DetectedProviderError | null {
229
396
  if (typeof message !== 'object' || message === null) return null
230
397
  const m = message as { role?: unknown; stopReason?: unknown; errorMessage?: unknown }
@@ -243,7 +410,9 @@ export function detectProviderError(message: unknown): DetectedProviderError | n
243
410
  // NOT an operator-actionable provider failure (internal bugs, network blips),
244
411
  // so the caller stays silent-with-log rather than spamming channels. The three
245
412
  // recognized classes are: failover-worthy throttle/overload, account-wide faults
246
- // (billing/quota/auth) that must surface, and observer stall timeouts.
413
+ // (billing/quota/auth) that must surface, and observer stall timeouts. A throw
414
+ // carrying the local pre-request marker surfaces too (via NON_FAILOVER_FAULT)
415
+ // with the LOCAL notice; an unmarked internal error still returns `null`.
247
416
  export function detectHardProviderError(err: unknown): DetectedProviderError | null {
248
417
  const message = err instanceof Error ? err.message : String(err)
249
418
  const isProviderFailure =
@@ -10,15 +10,10 @@ export { restartHandoffPath } from './paths'
10
10
 
11
11
  export const RESTART_HANDOFF_TTL_MS = 60_000
12
12
 
13
- // Process-local serialization of the two same-process handoff producers that
14
- // race during a restart: the in-session `/restart` tool (which writes the
15
- // originating handoff post-ACK) and the SIGTERM writer (which peek-augments it).
16
- // hostd fires `docker stop` → SIGTERM before its ACK reaches the container, so
17
- // without this the SIGTERM read-modify-write can interleave with `/restart`'s
18
- // write and drop the originating session's origin/author or its interrupted
19
- // children. This is NOT a cross-process lock — both producers live in this one
20
- // container process; the event loop yields at every await, so a promise-chain
21
- // mutex is all that's needed. Keyed by handoff path so distinct agent dirs
13
+ // Serialize ordinary restart-handoff reads and writes within one process.
14
+ // This is not a cross-process lock. Background launch inventory transfers
15
+ // non-TTL interrupted work to the runtime outbox; it neither augments this
16
+ // greeting nor relies on a SIGTERM sampler. Key by path so distinct agent dirs
22
17
  // (tests) never contend.
23
18
  const handoffLocks = new Map<string, Promise<void>>()
24
19
 
@@ -76,11 +71,9 @@ export type RestartHandoff = {
76
71
  // whatever bare-channel rule matches on every "I'm back" turn. Optional and
77
72
  // additive: pre-field v2 handoffs and tui handoffs omit it.
78
73
  triggeringAuthorId?: string
79
- // Names of background subagents still running when the restart fired, so the
80
- // resumed session can tell the thread its promised result was lost. Absent
81
- // (never an empty array) when nothing was in flight. Rides the handoff's 60s
82
- // TTL, so a stop→idle-for-hours→start drops it instead of replaying a stale
83
- // notice into a moved-on conversation.
74
+ // Lost-work names accepted from older handoffs. Channel boot excludes these
75
+ // from model greetings: covered launch recovery belongs to the outbox.
76
+ // Ordinary handoffs retain the greeting's 60s TTL.
84
77
  interruptedSubagents?: string[]
85
78
  }
86
79
 
@@ -0,0 +1,68 @@
1
+ import type { ReviewerActivity } from '@/channels/github-review-check'
2
+
3
+ import type { AgentSession } from './index'
4
+
5
+ const READING_TOOLS = new Set(['read', 'grep', 'find', 'ls'])
6
+ const COMMAND_TOOLS = new Set(['bash'])
7
+
8
+ type SessionEvent = { type: string; toolName?: unknown; args?: unknown; message?: unknown }
9
+
10
+ // Folds a reviewer session's events into the plain categories the review check
11
+ // shows. Only counts and categories leave this function: file paths, commands,
12
+ // and model text never reach the check page.
13
+ export function attachReviewerActivityCapture(
14
+ session: Pick<AgentSession, 'subscribe'>,
15
+ report: (activity: ReviewerActivity) => void,
16
+ now: () => number = Date.now,
17
+ ): () => void {
18
+ const files = new Set<string>()
19
+ const activity: ReviewerActivity = {
20
+ started: false,
21
+ filesRead: 0,
22
+ commandsRun: 0,
23
+ current: null,
24
+ lastActivityAt: null,
25
+ }
26
+ const unsubscribe = session.subscribe((raw: unknown) => {
27
+ const event = raw as SessionEvent
28
+ if (event.type === 'tool_execution_start' && typeof event.toolName === 'string') {
29
+ activity.started = true
30
+ if (READING_TOOLS.has(event.toolName)) {
31
+ activity.current = 'reading'
32
+ const path = (event.args as { path?: unknown } | undefined)?.path
33
+ if (event.toolName === 'read' && typeof path === 'string') files.add(path)
34
+ activity.filesRead = files.size
35
+ } else if (COMMAND_TOOLS.has(event.toolName)) {
36
+ activity.current = 'commands'
37
+ activity.commandsRun += 1
38
+ }
39
+ } else if (event.type === 'message_end' && hasText(event.message)) {
40
+ activity.current = 'writing'
41
+ } else if (event.type !== 'tool_execution_end') {
42
+ return
43
+ }
44
+ activity.lastActivityAt = now()
45
+ report({ ...activity })
46
+ })
47
+ return () => {
48
+ if (typeof unsubscribe === 'function') unsubscribe()
49
+ }
50
+ }
51
+
52
+ function hasText(message: unknown): boolean {
53
+ if (typeof message !== 'object' || message === null) return false
54
+ const { role, content } = message as { role?: unknown; content?: unknown }
55
+ if (role !== undefined && role !== 'assistant') return false
56
+ if (typeof content === 'string') return content.trim() !== ''
57
+ return (
58
+ Array.isArray(content) &&
59
+ content.some(
60
+ (part: unknown) =>
61
+ typeof part === 'object' &&
62
+ part !== null &&
63
+ (part as { type?: unknown }).type === 'text' &&
64
+ typeof (part as { text?: unknown }).text === 'string' &&
65
+ (part as { text: string }).text.trim() !== '',
66
+ )
67
+ )
68
+ }
@@ -276,6 +276,39 @@ export function renderSessionOrigin(
276
276
  }
277
277
  }
278
278
 
279
+ // Optional context for interactive sessions (TUI, channel, and origin-less
280
+ // sessions), appended by `composeSystemPrompt` in full mode only. It holds how
281
+ // to stay responsive and delegate — never permission, honesty, or filesystem
282
+ // rules, which live once in the shared policy every standard session gets.
283
+ // Deliberately separate from `renderSessionOrigin`: override loaders render
284
+ // origins too and must not inherit this context. The `spawn_subagent`
285
+ // parameter descriptions point at this heading and the
286
+ // [CONTEXT]/[GOAL]/[REQUEST] structure.
287
+ export function renderInteractiveSessionContext(subagentRoster: string): string {
288
+ return [
289
+ '## Subagent orchestration',
290
+ '',
291
+ 'Keep the conversation responsive. Answer quick, single-shot requests inline. Delegate heavy, side-effectful, long-running, or multi-step work — installs, builds, `docker`, long test runs, refactors, a bug that resisted a quick fix — to a subagent (usually `operator`) instead of grinding through it here; use `tmux` only for long work that belongs in this session.',
292
+ '',
293
+ `Delegate with \`spawn_subagent\`, \`subagent_output\`, and \`subagent_cancel\`; each subagent has its own context and tools, and the tool description has the mechanics. Briefly: ${subagentRoster}.`,
294
+ '',
295
+ '- Spawns run in the background by default: a `<system-reminder>` arrives when the subagent completes — do not poll `subagent_output`. Pass `run_in_foreground: true` for a quick result you need this turn; deep-profile subagents always run in the background from here. In channel sessions a completion reminder is not a user message: surface the result via `channel_reply`/`channel_send`.',
296
+ '- Broad search: spawn 2-5 `explorer`/`scout` workers in parallel, end your response, then collect each completion once. Use `scout` for narrow lookups and `researcher` for decomposed, multi-source, cross-validated synthesis. When the user *explicitly* asks to research or investigate, you MUST spawn `researcher`: answering from training memory or one inline `web_search` does not satisfy the request, and `scout`/`explorer` fan-out does not replace `researcher`.',
297
+ '- Delegate-and-converse: for side-effectful or noisy work over ~30s, spawn one background subagent and stay responsive — `operator` for side effects, `scout` for a quick lookup, `researcher` for deep investigation, `planner` for risk-aware sequencing. Pass `profile: "deep"` only when the work needs stronger reasoning than the default tier.',
298
+ '- Troubleshooting: after ~3 non-converging attempts at the same failure, stop and hand the loop to `operator` (background; `profile: "deep"` when genuinely hard) with the symptom, attempts, and success condition. Read `typeclaw-troubleshooting` before spawning.',
299
+ "- Status: when asked about a running subagent, call `subagent_output({ task_id })` and report its `status_summary` — don't guess.",
300
+ "- Don't fire more than 5 subagents per turn, spawn for known answers or single-file lookups, poll output in a loop, or ask research subagents to decide: they report; you decide. Most subagents are leaves; only `operator` and `reviewer` may delegate one level deeper.",
301
+ '',
302
+ 'Spawn prompt structure (mandatory — the subagent does not see this conversation):',
303
+ '',
304
+ '```',
305
+ "[CONTEXT]: What I'm working on, which files/modules are involved, what approach.",
306
+ '[GOAL]: The specific decision or output I need to unlock.',
307
+ '[REQUEST]: Concrete instructions — what to find/do/produce, what format, what to SKIP.',
308
+ '```',
309
+ ].join('\n')
310
+ }
311
+
279
312
  function withRoleContext(block: string, ctx: SessionRoleContext | undefined, kind: SessionOrigin['kind']): string {
280
313
  if (ctx === undefined) return block
281
314
  const roleBlock = kind === 'channel' ? renderChannelRolePolicy() : renderRoleContext(ctx)
@@ -32,7 +32,13 @@ export type SubagentContext<P = unknown> = {
32
32
  payload: P
33
33
  }
34
34
 
35
- export type RunSession = (override?: { userPrompt?: string }) => Promise<void>
35
+ // onFinalMessage receives the terminal assistant message's text after the
36
+ // completed run (or null for an empty terminal message/provider failure).
37
+ // Unlike orchestration output, it never projects <review>/<report> blocks.
38
+ export type RunSession = (override?: {
39
+ userPrompt?: string
40
+ onFinalMessage?: (message: string | null) => void
41
+ }) => Promise<void>
36
42
 
37
43
  // Fields shared verbatim between the plugin-author-facing `Subagent` in
38
44
  // `@/plugin/types` and the runtime-internal `Subagent` below. Every consumer
@@ -480,6 +486,7 @@ export async function invokeSubagent(name: string, options: InvokeSubagentOption
480
486
  ...(origin !== undefined ? { origin } : {}),
481
487
  })
482
488
  }
489
+ override?.onFinalMessage?.(latestTurnFailure === undefined ? capture.getTerminalAssistantText() : null)
483
490
  } finally {
484
491
  unsubProviderErrors?.()
485
492
  if (hooks && sessionId !== undefined) {
@@ -801,6 +808,8 @@ type SubagentCapture = {
801
808
  // True once a required-block subagent (researcher) has emitted its `<report>`
802
809
  // block; always false for subagents without a required block.
803
810
  hasRequiredBlock: () => boolean
811
+ // Raw terminal assistant text, independent of the orchestrator's block projection.
812
+ getTerminalAssistantText: () => string | null
804
813
  // Install a captured final message directly — used by the required-block guard
805
814
  // to set an honest fallback when the block was never emitted, so the parent
806
815
  // gets a structured result rather than stale preamble.
@@ -812,6 +821,7 @@ function attachFinalMessageCapture(
812
821
  requiredBlockTag: FinalBlockTag | undefined,
813
822
  onFinalMessage: (msg: string) => void,
814
823
  ): SubagentCapture {
824
+ let terminalAssistantText: string | null = null
815
825
  let lastAssistant: string | null = null
816
826
  let lastReview: string | null = null
817
827
  let lastRequired: string | null = null
@@ -824,6 +834,7 @@ function attachFinalMessageCapture(
824
834
  const role = ev.message?.role
825
835
  if (role !== undefined && role !== 'assistant') return
826
836
  const text = extractFinalMessageText(ev.message?.content)
837
+ terminalAssistantText = text
827
838
  if (text === null) return
828
839
  lastAssistant = text
829
840
 
@@ -851,6 +862,7 @@ function attachFinalMessageCapture(
851
862
  // doubles that don't implement it.
852
863
  }
853
864
  return {
865
+ getTerminalAssistantText: () => terminalAssistantText,
854
866
  hasRequiredBlock: () => lastRequired !== null,
855
867
  setSyntheticFinalMessage: (msg) => {
856
868
  lastRequired = msg