typeclaw 0.48.12 → 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 (213) hide show
  1. package/package.json +6 -3
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/attention-escalation.ts +8 -5
  4. package/src/agent/auth-reloadable.ts +2 -3
  5. package/src/agent/auth.ts +59 -79
  6. package/src/agent/compaction.ts +2 -2
  7. package/src/agent/index.ts +173 -85
  8. package/src/agent/live-sessions.ts +2 -2
  9. package/src/agent/live-subagents.ts +1 -0
  10. package/src/agent/llm-replay-sanitizer.ts +1 -1
  11. package/src/agent/model-overrides.ts +1 -1
  12. package/src/agent/multimodal/look-at.ts +3 -3
  13. package/src/agent/multimodal/read-redirect.ts +1 -1
  14. package/src/agent/plugin-tools.ts +76 -39
  15. package/src/agent/prompt-cache-key.ts +42 -0
  16. package/src/agent/provider-error.ts +179 -10
  17. package/src/agent/reload-tool.ts +1 -1
  18. package/src/agent/restart-handoff/index.ts +7 -14
  19. package/src/agent/reviewer-activity.ts +68 -0
  20. package/src/agent/session-origin.ts +33 -0
  21. package/src/agent/subagents.ts +14 -2
  22. package/src/agent/system-prompt.ts +68 -202
  23. package/src/agent/todo/continuation-policy.ts +12 -4
  24. package/src/agent/tool-error-remediation.ts +1 -1
  25. package/src/agent/tool-file-safety.ts +113 -14
  26. package/src/agent/tool-not-found-nudge.ts +1 -1
  27. package/src/agent/tool-result-budget.ts +2 -2
  28. package/src/agent/tools/channel-disengage.ts +2 -2
  29. package/src/agent/tools/channel-edit.ts +2 -2
  30. package/src/agent/tools/channel-fetch-attachment.ts +2 -2
  31. package/src/agent/tools/channel-history-render.ts +2 -1
  32. package/src/agent/tools/channel-history.ts +2 -2
  33. package/src/agent/tools/channel-react.ts +2 -2
  34. package/src/agent/tools/channel-read.ts +2 -2
  35. package/src/agent/tools/channel-reply.ts +25 -7
  36. package/src/agent/tools/channel-send.ts +51 -9
  37. package/src/agent/tools/curl-impersonate.ts +11 -2
  38. package/src/agent/tools/grant-role.ts +2 -2
  39. package/src/agent/tools/post-github-review.ts +79 -17
  40. package/src/agent/tools/restart.ts +2 -2
  41. package/src/agent/tools/skip-response.ts +4 -4
  42. package/src/agent/tools/spawn-subagent.ts +165 -14
  43. package/src/agent/tools/stream-snapshot.ts +2 -2
  44. package/src/agent/tools/subagent-cancel.ts +2 -2
  45. package/src/agent/tools/subagent-output.ts +10 -2
  46. package/src/agent/tools/todo/index.ts +2 -2
  47. package/src/agent/tools/webfetch/tool.ts +2 -2
  48. package/src/agent/tools/websearch.ts +2 -2
  49. package/src/bundled-plugins/backup/README.md +10 -9
  50. package/src/bundled-plugins/backup/runner.ts +140 -58
  51. package/src/bundled-plugins/backup/subagents.ts +58 -26
  52. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  53. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  54. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  55. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  56. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  57. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  58. package/src/bundled-plugins/operator/operator.ts +15 -4
  59. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  60. package/src/bundled-plugins/security/index.ts +50 -2
  61. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  62. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/discord-bot.ts +122 -67
  64. package/src/channels/adapters/discord-reactions.ts +18 -0
  65. package/src/channels/adapters/discord.ts +114 -8
  66. package/src/channels/adapters/github/inbound.ts +103 -8
  67. package/src/channels/adapters/github/index.ts +251 -19
  68. package/src/channels/adapters/github/last-alive.ts +27 -0
  69. package/src/channels/adapters/github/outbound.ts +54 -18
  70. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  71. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  72. package/src/channels/adapters/github/reactions.ts +100 -0
  73. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  74. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  75. package/src/channels/adapters/github/recovery.ts +106 -0
  76. package/src/channels/adapters/github/review-check.ts +510 -0
  77. package/src/channels/adapters/github/review-submitter.ts +34 -2
  78. package/src/channels/adapters/instagram.ts +32 -14
  79. package/src/channels/adapters/kakaotalk.ts +22 -7
  80. package/src/channels/adapters/line.ts +18 -3
  81. package/src/channels/adapters/outbound-account.ts +20 -0
  82. package/src/channels/adapters/own-reactions.ts +66 -0
  83. package/src/channels/adapters/recovery-correlation.ts +214 -0
  84. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  85. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  86. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  87. package/src/channels/adapters/slack-bot.ts +125 -57
  88. package/src/channels/adapters/slack-classify.ts +25 -4
  89. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  90. package/src/channels/adapters/slack-reactions.ts +18 -0
  91. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  92. package/src/channels/adapters/slack.ts +48 -3
  93. package/src/channels/adapters/teams.ts +14 -4
  94. package/src/channels/adapters/telegram-bot.ts +56 -10
  95. package/src/channels/adapters/webex-bot.ts +12 -2
  96. package/src/channels/adapters/webex.ts +12 -2
  97. package/src/channels/background-handoff.ts +434 -0
  98. package/src/channels/background-obligations.ts +893 -0
  99. package/src/channels/continuity-types.ts +271 -0
  100. package/src/channels/github-review-check.ts +598 -0
  101. package/src/channels/github-review-turn-ledger.ts +102 -28
  102. package/src/channels/github-review-verdict-coordinator.ts +96 -13
  103. package/src/channels/github-token-bridge.ts +11 -5
  104. package/src/channels/inbound-journal.ts +1738 -0
  105. package/src/channels/index.ts +6 -1
  106. package/src/channels/manager.ts +17 -7
  107. package/src/channels/recovery-dispatcher.ts +264 -0
  108. package/src/channels/recovery-notice.ts +94 -0
  109. package/src/channels/recovery-outbox.ts +459 -0
  110. package/src/channels/router.ts +2582 -633
  111. package/src/channels/schema.ts +8 -1
  112. package/src/channels/subagent-completion-bridge.ts +17 -14
  113. package/src/channels/types.ts +121 -16
  114. package/src/channels/waiting-reactions.ts +664 -0
  115. package/src/cli/compose.ts +7 -4
  116. package/src/cli/hostd.ts +49 -3
  117. package/src/cli/inspect.ts +11 -14
  118. package/src/cli/model.ts +7 -5
  119. package/src/cli/oauth-callbacks.ts +38 -23
  120. package/src/coding-agent/broker-body.ts +38 -0
  121. package/src/coding-agent/broker.ts +290 -0
  122. package/src/coding-agent/claude.ts +95 -0
  123. package/src/coding-agent/codex.ts +104 -0
  124. package/src/coding-agent/index.ts +506 -0
  125. package/src/coding-agent/omo-state.ts +69 -0
  126. package/src/coding-agent/omo-stream.ts +98 -0
  127. package/src/coding-agent/omo.ts +192 -0
  128. package/src/coding-agent/runner.ts +263 -0
  129. package/src/coding-agent/tool.ts +62 -0
  130. package/src/coding-agent/worktree.ts +355 -0
  131. package/src/compose/restart.ts +10 -3
  132. package/src/compose/start.ts +20 -3
  133. package/src/config/config.ts +70 -26
  134. package/src/config/providers.ts +278 -50
  135. package/src/container/exit-reason.ts +44 -0
  136. package/src/container/index.ts +5 -0
  137. package/src/container/log-archive.ts +51 -13
  138. package/src/container/memory-limit.ts +1 -1
  139. package/src/container/memory-oversubscription.ts +36 -6
  140. package/src/container/oom-events.ts +86 -0
  141. package/src/container/restart.ts +2 -0
  142. package/src/container/shared.ts +8 -1
  143. package/src/container/start.ts +25 -13
  144. package/src/container/stop.ts +6 -2
  145. package/src/container/tool-oom-priority.ts +32 -0
  146. package/src/cron/consumer.ts +10 -4
  147. package/src/cron/reloadable.ts +23 -2
  148. package/src/doctor/checks.ts +14 -2
  149. package/src/hostd/daemon.ts +20 -10
  150. package/src/hostd/spawn.ts +106 -5
  151. package/src/hostd/version.ts +20 -0
  152. package/src/hostd/watchdog.ts +241 -0
  153. package/src/init/dockerfile.ts +57 -592
  154. package/src/init/index.ts +6 -7
  155. package/src/init/oauth-login.ts +57 -17
  156. package/src/inspect/transcript-view.ts +6 -3
  157. package/src/mcp/client.ts +3 -1
  158. package/src/operations/classify-tool-outcome.ts +45 -1
  159. package/src/operations/incidents.ts +10 -5
  160. package/src/plugin/core-tool-names.ts +1 -1
  161. package/src/plugin/define.ts +1 -0
  162. package/src/plugin/index.ts +1 -0
  163. package/src/plugin/types.ts +6 -1
  164. package/src/run/background-handoff-boot.ts +86 -0
  165. package/src/run/channel-session-factory.ts +5 -4
  166. package/src/run/index.ts +93 -93
  167. package/src/run/resource-sample.ts +19 -0
  168. package/src/sandbox/build.ts +4 -0
  169. package/src/sandbox/coding-agent.ts +214 -0
  170. package/src/sandbox/policy.ts +1 -0
  171. package/src/sandbox/runtime-private.ts +4 -1
  172. package/src/secrets/coding-agent-auth.ts +97 -0
  173. package/src/secrets/index.ts +0 -16
  174. package/src/secrets/refresh-provider-oauth.ts +30 -76
  175. package/src/secrets/schema.ts +3 -4
  176. package/src/secrets/storage.ts +133 -234
  177. package/src/server/command-runner.ts +6 -2
  178. package/src/server/index.ts +102 -41
  179. package/src/sessions/index.ts +1 -1
  180. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  181. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  182. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  183. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  184. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  185. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  186. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  187. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  188. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  189. package/src/skills/typeclaw-config/SKILL.md +24 -24
  190. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  191. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  192. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  193. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  194. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  195. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  196. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  197. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  198. package/src/skills/typeclaw-plugins/SKILL.md +20 -20
  199. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  200. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  201. package/src/tui/index.ts +5 -3
  202. package/src/tui/theme.ts +1 -1
  203. package/typeclaw.schema.json +44 -2
  204. package/src/agent/adaptive-thinking-compat.ts +0 -79
  205. package/src/secrets/claude-credentials-json.ts +0 -129
  206. package/src/secrets/codex-auth-json.ts +0 -102
  207. package/src/secrets/export-claude-credentials-file.ts +0 -270
  208. package/src/secrets/export-codex-auth-file.ts +0 -250
  209. package/src/secrets/oauth-xai.ts +0 -348
  210. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  211. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  212. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  213. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -4,6 +4,7 @@ import { join, relative, sep } from 'node:path'
4
4
 
5
5
  import {
6
6
  createBashToolDefinition as piCreateBashToolDefinition,
7
+ createLocalBashOperations,
7
8
  createEditToolDefinition as piCreateEditToolDefinition,
8
9
  createFindToolDefinition as piCreateFindToolDefinition,
9
10
  createGrepToolDefinition as piCreateGrepToolDefinition,
@@ -11,14 +12,16 @@ import {
11
12
  createReadToolDefinition as piCreateReadToolDefinition,
12
13
  createWriteToolDefinition as piCreateWriteToolDefinition,
13
14
  defineTool as piDefineTool,
14
- } from '@mariozechner/pi-coding-agent'
15
- import type { BashSpawnContext, ToolDefinition } from '@mariozechner/pi-coding-agent'
15
+ } from '@earendil-works/pi-coding-agent'
16
+ import type { BashSpawnContext, ToolDefinition } from '@earendil-works/pi-coding-agent'
16
17
  import type { Static, TSchema } from 'typebox'
17
18
  import { Type } from 'typebox'
18
19
  import { z } from 'zod'
19
20
 
20
21
  import { ACKNOWLEDGE_GUARDS } from '@/bundled-plugins/guard/keys'
21
22
  import { config, getSandboxWritablePathSpecs } from '@/config/config'
23
+ import { readOomEvents, toolOomNote } from '@/container/oom-events'
24
+ import { withToolOomPriorityCommand } from '@/container/tool-oom-priority'
22
25
  import { readEnvFile } from '@/init/env-file'
23
26
  import {
24
27
  classifyToolOutcome,
@@ -136,6 +139,7 @@ type BashSpawnEnvContext = {
136
139
  // that appears in process.env between policy build and spawn stays out of the
137
140
  // sandbox (closes the inherit TOCTOU).
138
141
  sandboxSpawnEnv?: Record<string, string>
142
+ oomNote?: string
139
143
  }
140
144
 
141
145
  const bashEnvStore = new AsyncLocalStorage<BashSpawnEnvContext | undefined>()
@@ -164,8 +168,9 @@ function readBashPreparation(args: Record<string, unknown>): DeferredBashPrepara
164
168
 
165
169
  function bashSpawnHookWithOverlay(context: BashSpawnContext): BashSpawnContext {
166
170
  const store = bashEnvStore.getStore()
167
- if (store?.sandboxSpawnEnv !== undefined) return { ...context, env: { ...store.sandboxSpawnEnv } }
168
- return { ...context, env: sanitizeBashSpawnEnvironment(context.env, store?.overlay, store?.withhold) }
171
+ const command = withToolOomPriorityCommand(context.command)
172
+ if (store?.sandboxSpawnEnv !== undefined) return { ...context, command, env: { ...store.sandboxSpawnEnv } }
173
+ return { ...context, command, env: sanitizeBashSpawnEnvironment(context.env, store?.overlay, store?.withhold) }
169
174
  }
170
175
 
171
176
  export function sanitizeBashSpawnEnvironment(
@@ -182,22 +187,16 @@ export function sanitizeBashSpawnEnvironment(
182
187
  return env
183
188
  }
184
189
 
185
- // pi-coding-agent 0.73 contract (load-bearing for hook coverage):
190
+ // pi-coding-agent 0.87 contract (load-bearing for hook coverage):
186
191
  // - `createAgentSession({ tools: string[] })` is a name allowlist: only the
187
- // listed names stay active, and that allowlist gates BOTH builtins and
188
- // custom tools (see `allowedToolNames` in pi's `_refreshToolRegistry`).
189
- // - `noTools: "builtin"` drops pi's read/bash/edit/write from the INITIAL
190
- // active set; pi still registers its base builtins, so a same-named entry
191
- // in `customTools` is what overrides the implementation (registry
192
- // last-write-wins). Passing an explicit `tools:` allowlist plus shipping all
193
- // seven wrapped builtins is what makes the wrapped versions the only
194
- // callable ones.
192
+ // listed builtin and custom tool names are active (sdk.d.ts:35-47).
193
+ // - `noTools: "builtin"` disables Pi's default read/bash/edit/write tools but
194
+ // leaves custom tools eligible for that allowlist (sdk.d.ts:27-47).
195
195
  //
196
- // Consequence: every builtin enters as a `ToolDefinition` (pi now exposes
197
- // `create*ToolDefinition` factories), TypeClaw wraps each one with its hook +
198
- // guard + sandbox pipeline, and the call site routes them through `customTools`
199
- // while narrowing via `tools:` names. There is no longer an `AgentTool` vs
200
- // `ToolDefinition` split.
196
+ // Consequence: every builtin enters as a `ToolDefinition`, TypeClaw wraps each
197
+ // one with its hook + guard + sandbox pipeline, and the call site routes them
198
+ // through `customTools` while narrowing via `tools:` names. A named custom
199
+ // definition replaces the built-in implementation in the active registry.
201
200
  type TypeclawToolName = 'web_search' | 'web_fetch'
202
201
 
203
202
  // pi builtins resolve relative paths (and, for trusted/owner bash, the spawn
@@ -210,8 +209,33 @@ function createPiBuiltinToolDefinition(name: PiBuiltinToolName, cwd: string): To
210
209
  switch (name) {
211
210
  case 'read':
212
211
  return piCreateReadToolDefinition(cwd)
213
- case 'bash':
214
- return piCreateBashToolDefinition(cwd, { spawnHook: bashSpawnHookWithOverlay })
212
+ case 'bash': {
213
+ const operations = createLocalBashOperations()
214
+ return piCreateBashToolDefinition(cwd, {
215
+ // TypeClaw owns the bash environment boundary, so disable Pi session
216
+ // metadata rather than bypassing the spawn hook. Bracket the real
217
+ // process at the operation boundary: only there can memory.events be
218
+ // read before spawn and after exit (Pi 0.99 reports a signal-killed
219
+ // shell as 128+signal, so a SIGKILLed shell surfaces as 137 too).
220
+ exposeSessionEnvironment: false,
221
+ spawnHook: bashSpawnHookWithOverlay,
222
+ operations: {
223
+ async exec(command, dir, options) {
224
+ const before = readOomEvents()
225
+ const result = await operations.exec(command, dir, options)
226
+ const note =
227
+ result.exitCode === null
228
+ ? null
229
+ : toolOomNote(before, result.exitCode, 'bash', { log: (line) => console.warn(line) })
230
+ if (note !== null) {
231
+ const context = bashEnvStore.getStore()
232
+ if (context !== undefined) context.oomNote = note
233
+ }
234
+ return result
235
+ },
236
+ },
237
+ })
238
+ }
215
239
  case 'edit':
216
240
  return piCreateEditToolDefinition(cwd)
217
241
  case 'write':
@@ -249,11 +273,17 @@ function isTypeclawToolName(name: string): name is TypeclawToolName {
249
273
  return name in TYPECLAW_TOOL_DEFINITION_MAP
250
274
  }
251
275
 
252
- export function resolveBuiltinToolRefs(refs: BuiltinToolRef[], cwd: string): ToolDefinition<any, any, any>[] {
276
+ export function resolveBuiltinToolRefs(
277
+ refs: BuiltinToolRef[],
278
+ cwd: string,
279
+ contextTools: ReadonlyMap<string, ToolDefinition<any, any, any>> = new Map(),
280
+ ): ToolDefinition<any, any, any>[] {
253
281
  return refs.map((ref) => {
254
282
  const name = ref.__builtinTool
255
283
  if (isPiBuiltinToolName(name)) return createPiBuiltinToolDefinition(name, cwd)
256
284
  if (isTypeclawToolName(name)) return TYPECLAW_TOOL_DEFINITION_MAP[name]
285
+ const contextual = contextTools.get(name)
286
+ if (contextual) return contextual
257
287
  throw new Error(`unknown built-in tool ref: ${name}`)
258
288
  })
259
289
  }
@@ -326,20 +356,15 @@ export type WrapSystemToolOptions = {
326
356
  }
327
357
 
328
358
  // Zod 4 emits a top-level `"$schema": "https://json-schema.org/draft/2020-12/schema"`
329
- // pointer on every converted schema. Ajv v8 (used by pi-ai's runtime tool-argument
330
- // validator and by ModelRegistry's models.json validator) is configured for
331
- // Draft 7 and rejects unknown `$schema` URIs with:
332
- //
333
- // no schema with key or ref "https://json-schema.org/draft/2020-12/schema"
334
- //
335
- // That error is raised before the tool's execute is even invoked, so the model
336
- // sees the failure as a tool-call result and reacts by retrying or falling back
337
- // to other tools. In the memory-logger / dreaming subagents this meant the
338
- // `find_entry` tool was permanently broken: the subagent kept falling back to
339
- // `read(offset=1, limit=2000)` and chunked through entire multi-hundred-KB
340
- // transcripts on every channel turn. Stripping `$schema` is the minimal,
341
- // converter-version-independent fix; it leaves the actual JSON-schema body
342
- // untouched and lets Ajv use its default draft.
359
+ // pointer on every converted schema. It was first stripped because pi-ai's former
360
+ // Ajv (draft 7) validator rejected that URI before execute ran, which left the
361
+ // memory-logger and dreaming subagents without `find_entry` and made them read
362
+ // whole transcripts on every channel turn. pi 0.87 validates with TypeBox
363
+ // instead, but these parameter schemas are still forwarded verbatim to provider
364
+ // APIs, and pi strips JSON-Schema meta declarations itself only for Google
365
+ // (`sanitizeForOpenApi` in pi-ai dist/api/google-shared.js). Stripping the
366
+ // pointer keeps every provider's tool payload identical to earlier releases; it
367
+ // removes no constraint, since the schema body is untouched.
343
368
  export function zodToToolParameters(schema: z.ZodType<unknown>): TSchema {
344
369
  const json = z.toJSONSchema(schema, { io: 'input', reused: 'inline' }) as Record<string, unknown>
345
370
  delete json.$schema
@@ -644,6 +669,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
644
669
  cleanupError = undefined
645
670
  sandboxedRealProcSucceeded = false
646
671
  const attemptArgs = { ...originalArgs }
672
+ let spawnEnvContext: BashSpawnEnvContext | undefined
647
673
  try {
648
674
  if (tool.name === 'bash') {
649
675
  if (opts.permissions === undefined) {
@@ -683,7 +709,7 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
683
709
  signal,
684
710
  })
685
711
  await preparedSandboxRuntime?.verify()
686
- const spawnEnvContext: BashSpawnEnvContext | undefined =
712
+ spawnEnvContext =
687
713
  bashEnvOverlay !== undefined ||
688
714
  bashEnvWithhold !== undefined ||
689
715
  preparedSandboxRuntime?.spawnEnv !== undefined
@@ -694,17 +720,28 @@ export function wrapBuiltinToolDefinition<TParams extends TSchema, TDetails = un
694
720
  ? { sandboxSpawnEnv: preparedSandboxRuntime.spawnEnv }
695
721
  : {}),
696
722
  }
697
- : undefined
698
- rawResult = await bashEnvStore.run(spawnEnvContext, () =>
723
+ : tool.name === 'bash'
724
+ ? {}
725
+ : undefined
726
+ const executed = await bashEnvStore.run(spawnEnvContext, () =>
699
727
  tool.execute(toolCallId, attemptArgs as Static<TParams>, signal, onUpdate, ctx),
700
728
  )
729
+ // Pi 0.99 bash returns a nonzero exit as an `isError` result whose text
730
+ // is the message 0.87 threw (tools/bash.js). This wrapper returns only
731
+ // content/details, so rethrow to keep the failure on the error path
732
+ // (remediation, incident repair, sandbox note, model-facing isError).
733
+ if (executed.isError === true) {
734
+ throw new Error(executed.content.map((part) => (part.type === 'text' ? part.text : '')).join('\n'))
735
+ }
736
+ rawResult = executed
701
737
  const originalCommand = originalArgs.command
702
738
  sandboxedRealProcSucceeded =
703
739
  preparedSandboxRuntime !== undefined &&
704
740
  typeof originalCommand === 'string' &&
705
741
  (opts.realProcDependencyCheck ?? commandNeedsRealProc)(originalCommand)
706
742
  } catch (error) {
707
- executionError = error
743
+ executionError =
744
+ spawnEnvContext?.oomNote === undefined ? error : appendErrorText(error, spawnEnvContext.oomNote)
708
745
  } finally {
709
746
  const cleanup = [pinnedFiles?.cleanup(), preparedSandboxRuntime?.cleanup()].filter(
710
747
  (task): task is Promise<void> => task !== undefined,
@@ -0,0 +1,42 @@
1
+ import type { SessionOrigin } from './session-origin'
2
+
3
+ // Mirrors pi-ai's OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH, which pi applies before
4
+ // `onPayload` runs, so a replaced key must be bounded here too. Truncation can
5
+ // only merge two long-named origins into one cache bucket, which is harmless.
6
+ const PROMPT_CACHE_KEY_MAX_LENGTH = 64
7
+
8
+ // pi defaults OpenAI's `prompt_cache_key` to the session id, and OpenAI routes
9
+ // requests to cache machines by that key. Every new subagent/cron/channel
10
+ // session therefore landed on a cold machine and re-paid its whole ~10K-token
11
+ // system+tools prefix even though sibling sessions of the same kind had just
12
+ // sent the identical prefix. Keying by origin kind (and subagent/component
13
+ // name, whose prompts differ) lets those sessions share the warm prefix. Only
14
+ // the body key changes: pi still uses the session id for the Codex websocket
15
+ // session cache and request headers.
16
+ export function promptCacheKeyForOrigin(origin: SessionOrigin | undefined): string | undefined {
17
+ const key = unboundedPromptCacheKey(origin)
18
+ return key === undefined ? undefined : Array.from(key).slice(0, PROMPT_CACHE_KEY_MAX_LENGTH).join('')
19
+ }
20
+
21
+ function unboundedPromptCacheKey(origin: SessionOrigin | undefined): string | undefined {
22
+ if (origin === undefined) return undefined
23
+ switch (origin.kind) {
24
+ case 'subagent':
25
+ return `typeclaw:subagent:${origin.subagent}`
26
+ case 'system':
27
+ return `typeclaw:system:${origin.component}`
28
+ case 'tui':
29
+ case 'cron':
30
+ case 'channel':
31
+ return `typeclaw:${origin.kind}`
32
+ }
33
+ }
34
+
35
+ // Rewrites only payloads that already carry a string `prompt_cache_key`, so
36
+ // providers without the field and `cacheRetention: 'none'` (which omits it)
37
+ // are left untouched.
38
+ export function withPromptCacheKey(payload: unknown, key: string): unknown {
39
+ if (typeof payload !== 'object' || payload === null) return payload
40
+ if (typeof (payload as { prompt_cache_key?: unknown }).prompt_cache_key !== 'string') return payload
41
+ return { ...payload, prompt_cache_key: key }
42
+ }
@@ -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 =
@@ -1,4 +1,4 @@
1
- import { defineTool } from '@mariozechner/pi-coding-agent'
1
+ import { defineTool } from '@earendil-works/pi-coding-agent'
2
2
  import { Type } from 'typebox'
3
3
 
4
4
  import type { ReloadRegistry, ReloadResult } from '@/reload'
@@ -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
+ }