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
@@ -1,5 +1,5 @@
1
- import type { ThinkingLevel } from '@mariozechner/pi-agent-core'
2
- import type { KnownApi, Model } from '@mariozechner/pi-ai'
1
+ import type { ThinkingLevel } from '@earendil-works/pi-agent-core'
2
+ import type { KnownApi, Model } from '@earendil-works/pi-ai'
3
3
 
4
4
  // Authentication mechanism a provider supports. `api-key` reads a static key
5
5
  // from .env (the original path); `oauth` runs a browser flow at init time and
@@ -29,16 +29,16 @@ type KnownProvider = {
29
29
  //
30
30
  // Adding a new model: append it to the matching provider's `models` map. Each
31
31
  // model object is the literal `Model<...>` that pi-ai consumes — keep it
32
- // faithful to https://github.com/mariozechner/pi-ai (the readme's "Custom
33
- // Models" section). `setRuntimeApiKey(provider, key)` keys off the `provider`
34
- // field, so it MUST match the outer provider id.
32
+ // faithful to pi-ai's "Custom Providers" README section
33
+ // (https://github.com/earendil-works/pi/tree/main/packages/ai#custom-providers).
34
+ // `setRuntimeApiKey(provider, key)` keys off the `provider` field, so it MUST
35
+ // match the outer provider id.
35
36
  //
36
37
  // Adding a new provider: add a top-level entry. Set `auth` to the supported
37
38
  // methods. For `api-key` providers, `apiKeyEnv` is the .env var typeclaw
38
39
  // writes at init and reads at boot (match the upstream provider's standard,
39
40
  // e.g. `OPENAI_API_KEY`). For `oauth` providers, `oauthProviderId` MUST match
40
- // a pi-ai OAuth provider id exactly, otherwise `authStorage.login()` will
41
- // throw "Unknown OAuth provider".
41
+ // a pi-ai OAuth provider id exactly, otherwise the provider login lookup fails.
42
42
  //
43
43
  // Granularity rule (split vs merge): a provider id is the runtime API surface,
44
44
  // not the brand. Different API call => different provider id; same API call =>
@@ -61,9 +61,14 @@ export const KNOWN_PROVIDERS = {
61
61
  auth: ['api-key'],
62
62
  apiKeyEnv: 'OPENAI_API_KEY',
63
63
  oauthProviderId: null,
64
- // Costs and context windows mirror models.dev as of 2026-05-10. When
65
- // refreshing, also rerun `scripts/generate-schema.ts` so typeclaw.schema.json
66
- // picks up new enum values.
64
+ // Costs and context windows mirror models.dev as of 2026-05-10; the GPT-6
65
+ // Sol/Luna records mirror OpenAI's model docs as of 2026-09-22.
66
+ // GPT-6 bills cache writes at 1.25x input; pi 0.87's Responses transport
67
+ // reads cache_write_tokens (openai-responses-shared.js), so that rate is
68
+ // applied. The >272K-input 2x/1.5x tier is not expressible in TypeClaw's
69
+ // flat cost shape, so these records use the standard rate. When
70
+ // refreshing, also rerun `scripts/generate-schema.ts` so
71
+ // typeclaw.schema.json picks up new enum values.
67
72
  models: {
68
73
  // Default. Cheapest tool-calling reasoning model in the family;
69
74
  // available on every paid OpenAI account tier.
@@ -115,6 +120,67 @@ export const KNOWN_PROVIDERS = {
115
120
  contextWindow: 1050000,
116
121
  maxTokens: 128000,
117
122
  },
123
+ // GPT-6 Sol and Luna use Responses because Chat Completions accepts tools
124
+ // only at effort `none`. The full map and compat are pi-ai 0.87.1's
125
+ // catalog values, preserving every documented effort through `max`.
126
+ 'gpt-6-sol': {
127
+ id: 'gpt-6-sol',
128
+ name: 'GPT-6 Sol',
129
+ api: 'openai-responses',
130
+ provider: 'openai',
131
+ baseUrl: 'https://api.openai.com/v1',
132
+ reasoning: true,
133
+ input: ['text', 'image'],
134
+ cost: { input: 2, output: 10, cacheRead: 0.2, cacheWrite: 2.5 },
135
+ contextWindow: 1050000,
136
+ maxTokens: 128000,
137
+ thinkingLevelMap: {
138
+ off: 'none',
139
+ minimal: null,
140
+ low: 'low',
141
+ medium: 'medium',
142
+ high: 'high',
143
+ xhigh: 'xhigh',
144
+ max: 'max',
145
+ },
146
+ compat: {
147
+ supportsStrictMode: true,
148
+ supportsOpenAIGrammarTools: true,
149
+ supportsAdditionalTools: true,
150
+ supportsToolSearch: true,
151
+ supportsMidConvoSystemMessages: true,
152
+ supportsExplicitPromptCacheMode: true,
153
+ },
154
+ },
155
+ 'gpt-6-luna': {
156
+ id: 'gpt-6-luna',
157
+ name: 'GPT-6 Luna',
158
+ api: 'openai-responses',
159
+ provider: 'openai',
160
+ baseUrl: 'https://api.openai.com/v1',
161
+ reasoning: true,
162
+ input: ['text', 'image'],
163
+ cost: { input: 0.1, output: 0.5, cacheRead: 0.01, cacheWrite: 0.125 },
164
+ contextWindow: 1050000,
165
+ maxTokens: 128000,
166
+ thinkingLevelMap: {
167
+ off: 'none',
168
+ minimal: null,
169
+ low: 'low',
170
+ medium: 'medium',
171
+ high: 'high',
172
+ xhigh: 'xhigh',
173
+ max: 'max',
174
+ },
175
+ compat: {
176
+ supportsStrictMode: true,
177
+ supportsOpenAIGrammarTools: true,
178
+ supportsAdditionalTools: true,
179
+ supportsToolSearch: true,
180
+ supportsMidConvoSystemMessages: true,
181
+ supportsExplicitPromptCacheMode: true,
182
+ },
183
+ },
118
184
  },
119
185
  },
120
186
  // ChatGPT Plus/Pro subscription via the OAuth Codex backend. No API key
@@ -177,6 +243,63 @@ export const KNOWN_PROVIDERS = {
177
243
  contextWindow: 272000,
178
244
  maxTokens: 128000,
179
245
  },
246
+ // GPT-6 Sol and Luna use the documented Codex backend limits. Their
247
+ // 0.87.1 maps preserve all valid efforts through `max`; Codex floors
248
+ // unsupported `minimal` at `low`.
249
+ 'gpt-6-sol': {
250
+ id: 'gpt-6-sol',
251
+ name: 'GPT-6 Sol',
252
+ api: 'openai-codex-responses',
253
+ provider: 'openai-codex',
254
+ baseUrl: 'https://chatgpt.com/backend-api',
255
+ reasoning: true,
256
+ input: ['text', 'image'],
257
+ cost: { input: 2, output: 10, cacheRead: 0.2, cacheWrite: 2.5 },
258
+ contextWindow: 272000,
259
+ maxTokens: 128000,
260
+ thinkingLevelMap: {
261
+ off: 'none',
262
+ minimal: 'low',
263
+ low: 'low',
264
+ medium: 'medium',
265
+ high: 'high',
266
+ xhigh: 'xhigh',
267
+ max: 'max',
268
+ },
269
+ compat: {
270
+ supportsOpenAIGrammarTools: true,
271
+ supportsAdditionalTools: true,
272
+ supportsToolSearch: true,
273
+ supportsMidConvoSystemMessages: true,
274
+ },
275
+ },
276
+ 'gpt-6-luna': {
277
+ id: 'gpt-6-luna',
278
+ name: 'GPT-6 Luna',
279
+ api: 'openai-codex-responses',
280
+ provider: 'openai-codex',
281
+ baseUrl: 'https://chatgpt.com/backend-api',
282
+ reasoning: true,
283
+ input: ['text', 'image'],
284
+ cost: { input: 0.1, output: 0.5, cacheRead: 0.01, cacheWrite: 0.125 },
285
+ contextWindow: 272000,
286
+ maxTokens: 128000,
287
+ thinkingLevelMap: {
288
+ off: 'none',
289
+ minimal: 'low',
290
+ low: 'low',
291
+ medium: 'medium',
292
+ high: 'high',
293
+ xhigh: 'xhigh',
294
+ max: 'max',
295
+ },
296
+ compat: {
297
+ supportsOpenAIGrammarTools: true,
298
+ supportsAdditionalTools: true,
299
+ supportsToolSearch: true,
300
+ supportsMidConvoSystemMessages: true,
301
+ },
302
+ },
180
303
  },
181
304
  },
182
305
  // Anthropic Claude — both the Anthropic Console API (ANTHROPIC_API_KEY)
@@ -189,9 +312,8 @@ export const KNOWN_PROVIDERS = {
189
312
  // subscriber's `claude setup-token` credential authorizes. The OAuth dance
190
313
  // itself is authorization-code + PKCE against `claude.ai/oauth/authorize`
191
314
  // with a localhost callback server (not device-code); the existing
192
- // `typeclaw-claude-code` skill documents the user-side flow for getting
193
- // a subscription credential onto the agent when the in-container browser
194
- // callback can't reach the user's machine.
315
+ // host provider setup owns login. coding_agent delegates inference through
316
+ // a fixed-upstream broker; it never exports a provider token to the CLI.
195
317
  //
196
318
  // anthropic is the FIRST provider in the registry where both auth modes
197
319
  // coexist on one entry. The runtime in src/agent/auth.ts has a load-bearing
@@ -215,7 +337,8 @@ export const KNOWN_PROVIDERS = {
215
337
  // not the recommended path. Claude Mythos 5 (Fable 5's classifier-free
216
338
  // sibling, limited availability via Project Glasswing) is intentionally
217
339
  // NOT listed — access is gated per-org and a registry entry would fail for
218
- // everyone else.
340
+ // everyone else. Opus 5.5 (Sep 22 2026) was added on its own; Claude Opus 5
341
+ // and Fable 5.1 are not registered yet.
219
342
  //
220
343
  // ID semantics differ across the lineup and matter for forward-compat:
221
344
  // - `claude-haiku-4-5` is a 4.5-generation CONVENIENCE ALIAS that
@@ -238,8 +361,8 @@ export const KNOWN_PROVIDERS = {
238
361
  // vs Opus 4.6, but total cost on identical workloads can rise meaningfully.
239
362
  // - 1M token context window (vs 200k on Haiku) and 128k max output (vs
240
363
  // 64k on Sonnet/Haiku). 1M context is at standard pricing — no surcharge.
241
- // - New `xhigh` effort level between `high` and `max` (pi-ai 0.67.x may
242
- // not surface this knob yet; check before relying on it).
364
+ // - `xhigh` effort level between `high` and `max`; each record's
365
+ // `thinkingLevelMap` declares whether the model exposes it.
243
366
  //
244
367
  // Pricing mirrors Anthropic's official table as of 2026-05; cacheWrite is
245
368
  // the 5m-TTL rate (1.25x input). 1h TTL is ~2x input (not modeled here —
@@ -264,6 +387,18 @@ export const KNOWN_PROVIDERS = {
264
387
  contextWindow: 200000,
265
388
  maxTokens: 64000,
266
389
  },
390
+ // pi-ai 0.73 inferred adaptive thinking from the 4.6/4.7 ids; 0.87 reads
391
+ // only `compat.forceAdaptiveThinking` (anthropic-messages.js). Without
392
+ // these catalog fields Sonnet 4.6 and Opus 4.7 fall back to budget
393
+ // thinking, which Anthropic deprecates on 4.6 and rejects with a 400 on
394
+ // 4.7+ (platform.claude.com/docs/en/build-with-claude/extended-thinking).
395
+ //
396
+ // No Anthropic record sets `compat.supportsStrictTools`. With it, pi sends
397
+ // its strict-preferring built-ins (read/write/edit/bash) as strict tools,
398
+ // turning each optional param into a nullable union. Together with our
399
+ // own enum-union tool params that exceeds Anthropic's 16-union-param
400
+ // request cap, and every channel turn 400s. Guarded by
401
+ // anthropic-payload.test.ts.
267
402
  'claude-sonnet-4-6': {
268
403
  id: 'claude-sonnet-4-6',
269
404
  name: 'Claude Sonnet 4.6',
@@ -275,6 +410,8 @@ export const KNOWN_PROVIDERS = {
275
410
  cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
276
411
  contextWindow: 1000000,
277
412
  maxTokens: 64000,
413
+ thinkingLevelMap: { max: 'max' },
414
+ compat: { forceAdaptiveThinking: true },
278
415
  },
279
416
  // Sonnet 5 (Jul 1 2026) is the drop-in successor to Sonnet 4.6 with a
280
417
  // caveat set that affects consumers of this record:
@@ -282,17 +419,12 @@ export const KNOWN_PROVIDERS = {
282
419
  // Per-token price is unchanged, so equivalent requests cost more.
283
420
  // - Adaptive thinking only: manual extended thinking
284
421
  // (`thinking: {type: "enabled"}` with `budget_tokens`) returns a
285
- // 400. The pinned pi-ai 0.73.x DOES send that payload for this id
286
- // (its supportsAdaptiveThinking() only matches 4.6-generation ids,
287
- // and thinking defaults to "medium"), so registering this record
288
- // with `reasoning: true` depends on the rewrite shim in
289
- // src/agent/adaptive-thinking-compat.ts. Don't wire a
290
- // thinking-budget knob to this id.
422
+ // 400. `compat.forceAdaptiveThinking` makes pi-ai's Anthropic
423
+ // transport send adaptive thinking on every path, compaction included.
291
424
  // - Cost encodes the STANDARD rate (in effect Sep 1 2026+).
292
- // Introductory pricing ($2/$10, cacheRead 0.2, cacheWrite 2.5) runs
293
- // through Aug 31 2026, so `typeclaw usage` over-reports Sonnet 5
294
- // spend until then. Chosen so the record doesn't silently go stale
295
- // two months after landing.
425
+ // Introductory pricing ($2/$10, cacheRead 0.2, cacheWrite 2.5) ran
426
+ // through Aug 31 2026. It was chosen so the record doesn't silently
427
+ // go stale two months after landing.
296
428
  'claude-sonnet-5': {
297
429
  id: 'claude-sonnet-5',
298
430
  name: 'Claude Sonnet 5',
@@ -304,6 +436,8 @@ export const KNOWN_PROVIDERS = {
304
436
  cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
305
437
  contextWindow: 1000000,
306
438
  maxTokens: 128000,
439
+ thinkingLevelMap: { xhigh: 'xhigh', max: 'max' },
440
+ compat: { forceAdaptiveThinking: true },
307
441
  },
308
442
  'claude-opus-4-7': {
309
443
  id: 'claude-opus-4-7',
@@ -316,7 +450,12 @@ export const KNOWN_PROVIDERS = {
316
450
  cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
317
451
  contextWindow: 1000000,
318
452
  maxTokens: 128000,
453
+ thinkingLevelMap: { xhigh: 'xhigh', max: 'max' },
454
+ compat: { forceAdaptiveThinking: true, supportsTemperature: false },
319
455
  },
456
+ // Opus 4.8 was never in pi 0.73's adaptive id list, so it already got
457
+ // budget thinking (a 400 on 4.7+) before this migration. The catalog
458
+ // compat fixes it the same way.
320
459
  'claude-opus-4-8': {
321
460
  id: 'claude-opus-4-8',
322
461
  name: 'Claude Opus 4.8',
@@ -328,15 +467,60 @@ export const KNOWN_PROVIDERS = {
328
467
  cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 },
329
468
  contextWindow: 1000000,
330
469
  maxTokens: 128000,
470
+ thinkingLevelMap: { xhigh: 'xhigh', max: 'max' },
471
+ compat: {
472
+ supportsMidConvoSystemMessages: true,
473
+ supportsMidConvoToolChanges: true,
474
+ forceAdaptiveThinking: true,
475
+ supportsTemperature: false,
476
+ },
477
+ },
478
+ // Opus 5.5 (Sep 22 2026) keeps adaptive thinking permanently on: both
479
+ // manual and disabled thinking return 400, which `forceAdaptiveThinking`
480
+ // plus `off`/`minimal: null` rule out. `supportsMidConvoEffort` routes the
481
+ // thinking level through the mid-conversation output-config control and
482
+ // sends `thinking-binding-controls-2026-08-01` with `drop_block`. Without
483
+ // that, a replayed thinking block whose prefix changed (for example after
484
+ // compaction) returns 400 on accounts created on or after 2026-08-31.
485
+ // Forced tool use is unsupported; typeclaw never sets toolChoice.
486
+ 'claude-opus-5-5': {
487
+ id: 'claude-opus-5-5',
488
+ name: 'Claude Opus 5.5',
489
+ api: 'anthropic-messages',
490
+ provider: 'anthropic',
491
+ baseUrl: 'https://api.anthropic.com',
492
+ reasoning: true,
493
+ input: ['text', 'image'],
494
+ cost: { input: 4, output: 20, cacheRead: 0.2, cacheWrite: 5 },
495
+ contextWindow: 1000000,
496
+ maxTokens: 128000,
497
+ thinkingLevelMap: {
498
+ off: null,
499
+ minimal: null,
500
+ low: 'low',
501
+ medium: 'medium',
502
+ high: 'high',
503
+ xhigh: 'xhigh',
504
+ max: 'max',
505
+ },
506
+ compat: {
507
+ supportsMidConvoEffort: true,
508
+ supportsMidConvoSystemMessages: true,
509
+ supportsMidConvoToolChanges: true,
510
+ forceAdaptiveThinking: true,
511
+ supportsTemperature: false,
512
+ },
331
513
  },
332
514
  // Fable 5 (Jun 2026) is a NEW TIER above Opus — Anthropic's most
333
515
  // capable widely released model, aimed at long-horizon agentic work.
334
516
  // Ships the 5-generation tokenizer: ~1.3x token counts for the same
335
517
  // text vs pre-5 models, so equivalent requests cost more than the
336
518
  // per-token rates alone suggest. Adaptive thinking only, same as
337
- // Sonnet 5 above: `reasoning: true` here depends on the rewrite shim
338
- // in src/agent/adaptive-thinking-compat.ts (pinned pi-ai 0.73.x would
339
- // otherwise send budget-based `thinking`, a hard 400 on this id).
519
+ // Sonnet 5 above, via `compat.forceAdaptiveThinking`. Upstream's catalog
520
+ // also sets `allowedFallbackModels` (Anthropic server-side fallback to
521
+ // Opus 4.8 / Opus 5). That is deliberately NOT adopted: pi would send
522
+ // `fallbacks`, and a refused request would silently be served, and
523
+ // billed, by a different model than the one the operator configured.
340
524
  'claude-fable-5': {
341
525
  id: 'claude-fable-5',
342
526
  name: 'Claude Fable 5',
@@ -348,6 +532,12 @@ export const KNOWN_PROVIDERS = {
348
532
  cost: { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 },
349
533
  contextWindow: 1000000,
350
534
  maxTokens: 128000,
535
+ thinkingLevelMap: { off: null, xhigh: 'xhigh', max: 'max' },
536
+ compat: {
537
+ supportsMidConvoSystemMessages: true,
538
+ supportsMidConvoToolChanges: true,
539
+ forceAdaptiveThinking: true,
540
+ },
351
541
  },
352
542
  },
353
543
  },
@@ -521,24 +711,23 @@ export const KNOWN_PROVIDERS = {
521
711
  },
522
712
  },
523
713
  },
524
- // xAI (Grok). The native developer API at api.x.ai/v1 is OpenAI-compatible
525
- // (Bearer auth + /chat/completions shape), so models go through pi-ai's
526
- // `openai-completions` adapter with a custom baseUrl — same trick as
527
- // Fireworks and Z.AI. This is a DUAL-AUTH provider like `anthropic`:
528
- // * api-key — XAI_API_KEY (the standard xAI env var), a plain Bearer token.
529
- // * oauth — Grok subscription login via xAI's OIDC server (auth.x.ai),
530
- // authorization-code + PKCE. pi-ai ships no built-in xAI OAuth provider,
531
- // so `oauthProviderId: 'xai'` resolves to the custom provider registered
532
- // in src/secrets/oauth-xai.ts (registered from createSecretsStoreForAgent
533
- // so both init-login and runtime-refresh see it). The dual-auth runtime
534
- // rule in src/agent/auth.ts applies: an OAuth credential on disk wins over
535
- // XAI_API_KEY in .env — remove it (`typeclaw provider remove xai`) to fall
536
- // back to the key.
714
+ // xAI (Grok) is a dual-auth provider: api-key requests use XAI_API_KEY and
715
+ // OAuth requests use the xAI OIDC credential. Grok 4.7 and 4.3 use
716
+ // `openai-responses` with pi-ai 0.87.1's catalog metadata, as upstream's
717
+ // built-in xAI provider does: Responses carries encrypted reasoning and the
718
+ // documented effort values. The grok-4.20 snapshots and grok-build-0.1 are
719
+ // not in that catalog, so they stay on `openai-completions`, where pi-ai
720
+ // sends no xAI reasoning_effort. That is their 0.73 wire behavior, unchanged.
721
+ // The built-in pi-ai xAI provider owns its device-code OAuth flow, including
722
+ // refresh. An OAuth credential on disk takes precedence over XAI_API_KEY in
723
+ // .env; remove it (`typeclaw provider remove xai`) to use the key instead.
537
724
  //
538
725
  // Costs and context windows mirror docs.x.ai/developers/models and the raw
539
726
  // /v1/models price fields as of 2026-06-08 (xAI quotes prices in cents per
540
- // 100M tokens; e.g. grok-4.3 prompt 12500 = $1.25/1M). grok-4.3 is the
541
- // flagship default; grok-build-0.1 is the coding-tuned model. The
727
+ // 100M tokens; e.g. grok-4.3 prompt 12500 = $1.25/1M); grok-4.7 mirrors
728
+ // docs.x.ai/developers/grok-4-7 and /pricing as of 2026-09-21. grok-4.7 is
729
+ // the flagship; grok-4.3 stays first as the template record for uncurated
730
+ // refs; grok-build-0.1 is the coding-tuned model. The
542
731
  // grok-4.20-0309 snapshots are pinned weights for reproducible runs.
543
732
  //
544
733
  // The earlier grok-4 / grok-4-fast / grok-code-fast-1 ids were RETIRED on
@@ -546,10 +735,10 @@ export const KNOWN_PROVIDERS = {
546
735
  // grok-4.3 / grok-build-0.1 rates, so they are intentionally NOT listed.
547
736
  //
548
737
  // cacheWrite is 0: xAI publishes no cache-write price (caching is implicit,
549
- // billed only at the cacheRead rate). Models 1-4 also carry a long-context
550
- // tier (2x rates above a 200k-token request); pi-ai's Model shape can't
551
- // express tiered pricing, so the standard rate is used and the breakpoint is
552
- // noted here. When refreshing, rerun `scripts/generate-schema.ts`.
738
+ // billed only at the cacheRead rate). Every model here also carries a
739
+ // long-context tier (2x rates above a 200k-token request); the flat cost
740
+ // shape can't express tiered pricing, so the standard rate is used and the
741
+ // breakpoint is noted here. When refreshing, rerun `scripts/generate-schema.ts`.
553
742
  xai: {
554
743
  id: 'xai',
555
744
  name: 'xAI (Grok)',
@@ -558,17 +747,56 @@ export const KNOWN_PROVIDERS = {
558
747
  apiKeyEnv: 'XAI_API_KEY',
559
748
  oauthProviderId: 'xai',
560
749
  models: {
750
+ // pi-ai 0.87.1's xAI catalog caps Grok 4.3 at 30K and maps its efforts;
751
+ // `minimal` is not an xAI effort, so it clamps to `low`. The current
752
+ // transport sends model.maxTokens by default, so keep that vendor-safe cap.
561
753
  'grok-4.3': {
562
754
  id: 'grok-4.3',
563
755
  name: 'Grok 4.3',
564
- api: 'openai-completions',
756
+ api: 'openai-responses',
565
757
  provider: 'xai',
566
758
  baseUrl: 'https://api.x.ai/v1',
567
759
  reasoning: true,
568
760
  input: ['text', 'image'],
569
761
  cost: { input: 1.25, output: 2.5, cacheRead: 0.2, cacheWrite: 0 },
570
762
  contextWindow: 1000000,
571
- maxTokens: 64000,
763
+ maxTokens: 30000,
764
+ thinkingLevelMap: {
765
+ off: 'none',
766
+ minimal: null,
767
+ low: 'low',
768
+ medium: 'medium',
769
+ high: 'high',
770
+ xhigh: null,
771
+ max: null,
772
+ },
773
+ compat: { supportsLongCacheRetention: false },
774
+ },
775
+ // Responses is required for Grok 4.7's encrypted reasoning and maps
776
+ // the documented low/medium/high/xhigh effort values on pi-ai 0.87.1.
777
+ 'grok-4.7': {
778
+ id: 'grok-4.7',
779
+ name: 'Grok 4.7',
780
+ api: 'openai-responses',
781
+ provider: 'xai',
782
+ baseUrl: 'https://api.x.ai/v1',
783
+ reasoning: true,
784
+ input: ['text', 'image'],
785
+ cost: { input: 2, output: 6, cacheRead: 0.5, cacheWrite: 0 },
786
+ // xAI documents no text-output ceiling. Use the 500K context window;
787
+ // pi-ai clamps it to remaining context before the Responses request.
788
+ contextWindow: 500000,
789
+ maxTokens: 500000,
790
+ thinkingLevelMap: {
791
+ off: null,
792
+ minimal: null,
793
+ low: 'low',
794
+ medium: 'medium',
795
+ high: 'high',
796
+ xhigh: 'xhigh',
797
+ max: null,
798
+ },
799
+ compat: { supportsLongCacheRetention: false },
572
800
  },
573
801
  'grok-4.20-0309-reasoning': {
574
802
  id: 'grok-4.20-0309-reasoning',
@@ -0,0 +1,44 @@
1
+ import type { DockerExec } from './shared'
2
+
3
+ // OOMKilled is container-wide: a killed subprocess can set it even when the runtime survives.
4
+ // `finishedAt` identifies one stop of a container: Docker keeps the container ID across
5
+ // restarts, so ID alone cannot tell a repeated observation of the same exit from a new one.
6
+ export async function inspectContainerExit(
7
+ exec: DockerExec,
8
+ name: string,
9
+ ): Promise<
10
+ | { kind: 'running'; containerId: string }
11
+ | { kind: 'stopped'; containerId: string; finishedAt: string; reason: string | null }
12
+ | null
13
+ > {
14
+ try {
15
+ const result = await exec([
16
+ 'inspect',
17
+ '--format',
18
+ '{{.Id}}|{{.State.Running}}|{{.State.OOMKilled}}|{{.State.ExitCode}}|{{.HostConfig.Memory}}|{{.State.FinishedAt}}',
19
+ name,
20
+ ])
21
+ if (result.exitCode !== 0) return null
22
+ const match = /^([0-9a-f]{64})\|(true|false)\|(true|false)\|(\d+)\|(\d+)\|(\S+)$/.exec(result.stdout.trim())
23
+ if (!match) return null
24
+ const containerId = match[1]!
25
+ if (match[2] === 'true') return { kind: 'running', containerId }
26
+ const limitBytes = Number(match[5])
27
+ const limit =
28
+ Number.isSafeInteger(limitBytes) && limitBytes > 0
29
+ ? ` (likely container memory limit ${Math.ceil(limitBytes / (1024 * 1024))} MiB)`
30
+ : ''
31
+ const exitCode = Number(match[4])
32
+ const reason =
33
+ match[3] === 'true'
34
+ ? exitCode === 137
35
+ ? `agent runtime was SIGKILLed (137) and the container recorded an OOM kill during this run${limit}. Restart the agent and reduce memory-heavy parallel work.`
36
+ : `agent runtime exited with code ${exitCode}; an OOM kill occurred in the container earlier in this run${limit}; a subprocess may have been killed. Restart the agent and reduce memory-heavy parallel work.`
37
+ : exitCode === 137
38
+ ? 'agent runtime exited with SIGKILL (137); Docker did not report an OOM kill.'
39
+ : null
40
+ return { kind: 'stopped', containerId, finishedAt: match[6]!, reason }
41
+ } catch {
42
+ return null
43
+ }
44
+ }
@@ -62,3 +62,8 @@ export {
62
62
  type WithAgentOperationLock,
63
63
  withAgentOperationLock,
64
64
  } from './agent-operation-lock'
65
+ export {
66
+ formatOversubscriptionWarning,
67
+ readFleetMemoryOversubscription,
68
+ type OversubscriptionWarning,
69
+ } from './memory-oversubscription'
@@ -4,7 +4,7 @@ import { join } from 'node:path'
4
4
 
5
5
  import { DEFAULT_LOG_RETENTION_DAYS, MAX_LOG_RETENTION_DAYS } from '@/config'
6
6
 
7
- import { resolveDockerBinary, sanitizeDockerStderr } from './shared'
7
+ import { defaultDockerExec, resolveDockerBinary, sanitizeDockerStderr, type DockerExecResult } from './shared'
8
8
 
9
9
  export type DockerLogArchiveResult =
10
10
  | { ok: true; status: 'archived'; path: string }
@@ -49,6 +49,7 @@ export type StreamCaptureResult = {
49
49
 
50
50
  export type DockerLogArchiveRuntime = {
51
51
  capture?: (input: StreamCaptureInput) => Promise<StreamCaptureResult>
52
+ inspectLogConfig?: (args: string[], options: { cwd: string; signal: AbortSignal }) => Promise<DockerExecResult>
52
53
  nonce?: () => string
53
54
  now?: () => Date
54
55
  resolveDockerBinary?: () => string | null
@@ -74,6 +75,43 @@ const CONTAINER_ID_PATTERN = /^[a-f0-9]{64}$/
74
75
  const NONCE_PATTERN = /^[a-f0-9]{32}$/
75
76
  const ARCHIVE_FILENAME_PATTERN = /^[a-f0-9]{64}-(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z-[a-f0-9]{32}\.log$/
76
77
  const PARTIAL_FILENAME_PATTERN = /^\.[a-f0-9]{64}-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-[a-f0-9]{32}\.partial$/
78
+ const DOCKER_LOG_INSPECT_TIMEOUT_MS = 10_000
79
+
80
+ async function archiveByteLimit(
81
+ agentDir: string,
82
+ containerId: string,
83
+ inspect: NonNullable<DockerLogArchiveRuntime['inspectLogConfig']>,
84
+ ): Promise<number> {
85
+ try {
86
+ const result = await inspect(['inspect', '--format', '{{json .HostConfig.LogConfig}}', containerId], {
87
+ cwd: agentDir,
88
+ signal: AbortSignal.timeout(DOCKER_LOG_INSPECT_TIMEOUT_MS),
89
+ })
90
+ if (result.exitCode !== 0) return MAX_DOCKER_LOG_ARCHIVE_BYTES
91
+ const config: unknown = JSON.parse(result.stdout)
92
+ if (typeof config !== 'object' || config === null || !('Type' in config) || config.Type !== 'json-file')
93
+ return MAX_DOCKER_LOG_ARCHIVE_BYTES
94
+ if (!('Config' in config) || typeof config.Config !== 'object' || config.Config === null)
95
+ return MAX_DOCKER_LOG_ARCHIVE_BYTES
96
+ const opts = config.Config
97
+ if (!('max-size' in opts) || typeof opts['max-size'] !== 'string') return MAX_DOCKER_LOG_ARCHIVE_BYTES
98
+ const maxFiles = 'max-file' in opts ? opts['max-file'] : '1'
99
+ // Docker parses max-file with strconv.Atoi, so "05" is 5; only positive counts are bounded.
100
+ if (typeof maxFiles !== 'string' || !/^\+?\d+$/.test(maxFiles) || Number(maxFiles) < 1)
101
+ return MAX_DOCKER_LOG_ARCHIVE_BYTES
102
+ // Docker json-file uses go-units FromHumanSize: decimal powers even for "MiB".
103
+ const sizeMatch = /^(\+?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)(?: ?(b|[kmgtp](?:i?b)?))?$/i.exec(opts['max-size'])
104
+ if (!sizeMatch) return MAX_DOCKER_LOG_ARCHIVE_BYTES
105
+ const prefix = sizeMatch[2]?.toLowerCase()[0]
106
+ const multiplier = prefix && prefix !== 'b' ? 1000 ** ('kmgtp'.indexOf(prefix) + 1) : 1
107
+ const size = Math.trunc(Number(sizeMatch[1]) * multiplier)
108
+ const capacity = size * Number(maxFiles)
109
+ if (size <= 0 || !Number.isSafeInteger(capacity)) return MAX_DOCKER_LOG_ARCHIVE_BYTES
110
+ return Math.min(MAX_DOCKER_LOG_ARCHIVE_TOTAL_BYTES, Math.max(MAX_DOCKER_LOG_ARCHIVE_BYTES, capacity))
111
+ } catch {
112
+ return MAX_DOCKER_LOG_ARCHIVE_BYTES
113
+ }
114
+ }
77
115
 
78
116
  export async function archiveContainerLogs(
79
117
  { agentDir, containerId, retentionDays = DEFAULT_LOG_RETENTION_DAYS }: Parameters<DockerLogArchiver>[0],
@@ -106,18 +144,21 @@ export async function archiveContainerLogs(
106
144
  if (binary === null) throw new Error('Docker binary could not be resolved for log archival')
107
145
 
108
146
  const capture = runtime.capture ?? streamProcessOutput
147
+ const maxBytes = await archiveByteLimit(agentDir, containerId, runtime.inspectLogConfig ?? defaultDockerExec)
109
148
  const captured = await capture({
110
149
  args: ['logs', '--timestamps', containerId],
111
150
  binary,
112
151
  cwd: agentDir,
113
- maxBytes: MAX_DOCKER_LOG_ARCHIVE_BYTES,
152
+ maxBytes,
114
153
  output,
115
154
  timeoutMs: DOCKER_LOG_ARCHIVE_TIMEOUT_MS,
116
155
  })
117
156
  if (captured.terminationBoundExceeded) throw new Error('docker logs did not settle after SIGKILL')
118
157
  if (captured.timedOut) throw new Error(`docker logs timed out after ${DOCKER_LOG_ARCHIVE_TIMEOUT_MS}ms`)
119
158
  if (captured.overflowed) {
120
- throw new Error(`docker logs exceeded the ${MAX_DOCKER_LOG_ARCHIVE_BYTES}-byte archive limit`)
159
+ throw new Error(
160
+ `docker logs exceeded the ${maxBytes}-byte archive limit. Container ${containerId} was preserved; export both log streams with docker logs --timestamps ${containerId} > private-log-file 2>&1 (choose a private destination); confirm the export succeeded before removing it with docker rm ${containerId} and retrying.`,
161
+ )
121
162
  }
122
163
  if (captured.exitCode !== 0) {
123
164
  const detail = sanitizeDockerStderr(captured.stderrExcerpt)
@@ -128,13 +169,16 @@ export async function archiveContainerLogs(
128
169
 
129
170
  await output.chmod(0o600)
130
171
  const incomingSize = (await output.stat()).size
131
- await pruneToCapacity(logsDir, incomingSize)
172
+ if (incomingSize > MAX_DOCKER_LOG_ARCHIVE_TOTAL_BYTES) {
173
+ throw new Error('Docker log archive exceeds total archive capacity')
174
+ }
132
175
  await output.close()
133
176
  output = null
134
177
 
135
178
  await rename(temporaryPath, allocation.finalPath)
136
179
  temporaryPath = null
137
180
  await chmod(allocation.finalPath, 0o600)
181
+ await pruneToCapacity(logsDir, allocation.finalPath)
138
182
  return { ok: true, status: 'archived', path: allocation.finalPath }
139
183
  } catch (error) {
140
184
  const cleanupErrors = await cleanupTemp(output, temporaryPath)
@@ -334,10 +378,7 @@ async function pruneByAgeAndRemoveStalePartials(logsDir: string, ageCutoff: numb
334
378
  }
335
379
  }
336
380
 
337
- async function pruneToCapacity(logsDir: string, incomingSize: number): Promise<void> {
338
- if (incomingSize > MAX_DOCKER_LOG_ARCHIVE_TOTAL_BYTES) {
339
- throw new Error('Docker log archive exceeds total archive capacity')
340
- }
381
+ async function pruneToCapacity(logsDir: string, publishedPath: string): Promise<void> {
341
382
  const snapshots: Array<{ name: string; path: string; size: number; timestamp: number }> = []
342
383
  for (const entry of await collectDirectoryEntries(logsDir)) {
343
384
  if (!entry.isFile()) continue
@@ -351,11 +392,8 @@ async function pruneToCapacity(logsDir: string, incomingSize: number): Promise<v
351
392
  let totalBytes = snapshots.reduce((total, snapshot) => total + snapshot.size, 0)
352
393
  let count = snapshots.length
353
394
  for (const snapshot of snapshots) {
354
- if (
355
- count + 1 <= MAX_DOCKER_LOG_ARCHIVE_SNAPSHOTS &&
356
- totalBytes + incomingSize <= MAX_DOCKER_LOG_ARCHIVE_TOTAL_BYTES
357
- )
358
- break
395
+ if (count <= MAX_DOCKER_LOG_ARCHIVE_SNAPSHOTS && totalBytes <= MAX_DOCKER_LOG_ARCHIVE_TOTAL_BYTES) break
396
+ if (snapshot.path === publishedPath) continue
359
397
  await removeRaceSafe(snapshot.path)
360
398
  count -= 1
361
399
  totalBytes -= snapshot.size