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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.48.13",
3
+ "version": "0.49.0",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -45,10 +45,10 @@
45
45
  "dependencies": {
46
46
  "@clack/core": "^1.2.0",
47
47
  "@clack/prompts": "^1.2.0",
48
- "@earendil-works/pi-agent-core": "^0.87.1",
49
- "@earendil-works/pi-ai": "^0.87.1",
50
- "@earendil-works/pi-coding-agent": "^0.87.1",
51
- "@earendil-works/pi-tui": "^0.87.1",
48
+ "@earendil-works/pi-agent-core": "^0.99.2",
49
+ "@earendil-works/pi-ai": "^0.99.2",
50
+ "@earendil-works/pi-coding-agent": "^0.99.2",
51
+ "@earendil-works/pi-tui": "^0.99.2",
52
52
  "@huggingface/transformers": "4.2.0",
53
53
  "@modelcontextprotocol/sdk": "^1.29.0",
54
54
  "@mozilla/readability": "^0.6.0",
@@ -1,9 +1,20 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
+ // Debug dump of the TypeClaw-composed system-prompt preamble for each standard
4
+ // session origin, with placeholder inputs. Every origin — including the
5
+ // default subagent — goes through the real `composeSystemPrompt`, so the
6
+ // sections and their order are exactly what `createResourceLoader` produces.
7
+ //
8
+ // This is the preamble only. pi appends project context (AGENTS.md), the skill
9
+ // catalog, and the cwd when it assembles the final system message; capture a
10
+ // real session's `session.systemPrompt` for that. Sessions created with an
11
+ // explicit `systemPromptOverride` do not use this composer and are not dumped.
12
+
3
13
  import { parseArgs } from 'node:util'
4
14
 
5
- import { composeSystemPrompt, deriveSystemPromptMode, renderTurnTimeAnchor, type SystemPromptMode } from '@/agent'
6
- import type { SessionOrigin, SessionRoleContext } from '@/agent/session-origin'
15
+ import { composeSystemPrompt, deriveSystemPromptMode, renderTurnTimeAnchor } from '@/agent'
16
+ import { renderInteractiveSessionContext, type SessionOrigin, type SessionRoleContext } from '@/agent/session-origin'
17
+ import { buildSystemPolicy, DEFAULT_SUBAGENT_ROSTER, renderRuntimeBlock } from '@/agent/system-prompt'
7
18
  import { renderRetrievedMemorySection, type RetrievedMemoryItem } from '@/bundled-plugins/memory/load-memory'
8
19
  import { composeTurnPrompt } from '@/channels/router'
9
20
 
@@ -178,10 +189,10 @@ export type DumpResult = {
178
189
  totalTokens: number
179
190
  }
180
191
 
181
- // Heuristic: ~4 chars per token. Industry rule-of-thumb (e.g. OpenAI tokenizer
182
- // docs); accurate to ~15% for English prose / markdown, model-agnostic across
183
- // Claude / GPT / Gemini families. Exposed so tests can assert the methodology.
184
- export const TOKENS_PER_CHAR = 0.25
192
+ // Rough size estimate: ~4 chars per token. A model-agnostic rule of thumb for
193
+ // English prose/markdown, NOT a tokenizer count — use a real tokenizer for any
194
+ // measurement you report.
195
+ const TOKENS_PER_CHAR = 0.25
185
196
 
186
197
  export function estimateTokens(text: string): number {
187
198
  return Math.round(text.length * TOKENS_PER_CHAR)
@@ -198,12 +209,6 @@ export function byteLength(text: string): number {
198
209
  return encoder.encode(text).length
199
210
  }
200
211
 
201
- const PLACEHOLDER_SUBAGENT_OVERRIDE = [
202
- 'You are typeclaw <PLACEHOLDER: subagent name>, a narrow worker subagent.',
203
- '',
204
- '<PLACEHOLDER: contents of the subagent-specific system prompt — owned by the plugin/bundled subagent that declared this worker. Real examples: memory-logger (~1000 tok), dreaming (~2200 tok). The prompt is opaque to the runtime; it teaches the subagent its job, its tools, and its termination contract.>',
205
- ].join('\n')
206
-
207
212
  const mkSection = (name: string, body: string): SectionBreakdown => ({
208
213
  name,
209
214
  bytes: byteLength(body),
@@ -211,87 +216,32 @@ const mkSection = (name: string, body: string): SectionBreakdown => ({
211
216
  tokens: estimateTokens(body),
212
217
  })
213
218
 
219
+ // Each section row runs from its marker to the next one, so it includes the
220
+ // `\n\n` separator that follows it and the rows sum exactly to the totals.
214
221
  export function dumpSystemPromptWithBreakdown(
215
222
  kind: OriginKind,
216
223
  options: { gitNudge: boolean } = { gitNudge: true },
217
224
  ): DumpResult {
218
- if (kind === 'subagent') return dumpSubagentOverridePrompt()
219
- return dumpDefaultLoaderPrompt(kind, options)
220
- }
221
-
222
- // Subagent sessions in production go through `defaultCreateSessionForSubagent`
223
- // (and the plugin-subagent path in run/index.ts), both of which set
224
- // `systemPromptOverride: subagent.systemPrompt`. That routes through
225
- // `createOverrideResourceLoader`, which emits only:
226
- // <override string> + runtime block + origin (with role)
227
- // No DEFAULT/SLIM base, no IDENTITY/SOUL, no git-nudge.
228
- //
229
- // Without this branch, the dumper would report a misleadingly large slim
230
- // breakdown for the subagent case and contradict AGENTS.md's "the section
231
- // order it prints is the section order an agent actually sees" contract.
232
- function dumpSubagentOverridePrompt(): DumpResult {
233
- const fixture = buildFixture('subagent')
234
- const runtimeBlock = `## Runtime\n\nTypeClaw runtime version: ${PLACEHOLDER_RUNTIME_VERSION}.`
235
- const originBlock = `## Session origin\n\nYou are a \`${(fixture.origin as { subagent: string }).subagent}\` subagent spawned by parent session\n\`${(fixture.origin as { parentSessionId: string }).parentSessionId}\`. Stay narrowly within the task you were given.\nReturn cleanly when done; do not sprawl into unrelated work.\n\n## Your role in this session\n\nRole: \`${fixture.roleContext.role}\`. Permissions: ${fixture.roleContext.permissions.map((p) => `\`${p}\``).join(', ')}.\n\nThis is the role the runtime resolved at session creation. Tool calls\nand channel admission are gated by these permissions; a \`blocked:\` or\n"denied by permissions" message means the current actor lacks the\npermission the guard was looking for. See the \`typeclaw-permissions\`\nskill for what each role can do and how to grant access.`
236
-
237
- const prompt = `${PLACEHOLDER_SUBAGENT_OVERRIDE}\n\n${runtimeBlock}\n\n${originBlock}`
238
- const sections: SectionBreakdown[] = [
239
- mkSection('Subagent override prompt', PLACEHOLDER_SUBAGENT_OVERRIDE),
240
- mkSection('Runtime block', runtimeBlock),
241
- mkSection('Session origin + role', originBlock),
242
- ]
243
- return {
244
- prompt,
245
- sections,
246
- totalBytes: byteLength(prompt),
247
- totalChars: prompt.length,
248
- totalTokens: estimateTokens(prompt),
249
- }
250
- }
251
-
252
- function dumpDefaultLoaderPrompt(kind: Exclude<OriginKind, 'subagent'>, options: { gitNudge: boolean }): DumpResult {
253
225
  const fixture = buildFixture(kind)
254
- const mode: SystemPromptMode = deriveSystemPromptMode(fixture.origin)
255
- const wantGitNudge = options.gitNudge && mode === 'full'
256
- const parts = {
226
+ const mode = deriveSystemPromptMode(fixture.origin)
227
+ const gitNudge = options.gitNudge && mode === 'full' ? PLACEHOLDER_GIT_NUDGE : ''
228
+ const prompt = composeSystemPrompt({
257
229
  mode,
258
230
  self: PLACEHOLDER_SELF,
259
231
  runtimeVersion: PLACEHOLDER_RUNTIME_VERSION,
260
232
  origin: fixture.origin,
261
233
  roleContext: fixture.roleContext,
262
- gitNudge: wantGitNudge ? PLACEHOLDER_GIT_NUDGE : '',
263
- } as const
264
-
265
- const prompt = composeSystemPrompt(parts)
266
-
267
- const baseEnd = prompt.indexOf(`\n\n${parts.self}`)
268
- const base = baseEnd > 0 ? prompt.slice(0, baseEnd) : ''
269
- const baseLabel = mode === 'slim' ? 'SLIM_SYSTEM_PROMPT (base)' : 'DEFAULT_SYSTEM_PROMPT (base)'
270
- const sections: SectionBreakdown[] = [
271
- mkSection(baseLabel, base),
272
- mkSection('Identity (IDENTITY.md + SOUL.md)', parts.self),
273
- mkSection('Runtime block', `## Runtime\n\nTypeClaw runtime version: ${parts.runtimeVersion}.`),
274
- mkSection('Session origin', extractSection(prompt, '## Session origin', '## Your role in this session')),
275
- mkSection(
276
- 'Role context',
277
- extractSection(
278
- prompt,
279
- '## Your role in this session',
280
- parts.gitNudge !== '' ? '## Uncommitted changes at session start' : undefined,
281
- ),
282
- ),
234
+ gitNudge,
235
+ })
236
+ const markers: Array<readonly [string, string]> = [
237
+ ['Shared policy', buildSystemPolicy()],
238
+ ['Identity (IDENTITY.md + SOUL.md)', PLACEHOLDER_SELF],
239
+ ['Runtime block', renderRuntimeBlock(PLACEHOLDER_RUNTIME_VERSION)],
283
240
  ]
284
- if (parts.gitNudge !== '') {
285
- sections.push(mkSection('Git nudge', parts.gitNudge))
286
- }
287
-
288
- return {
289
- prompt,
290
- sections,
291
- totalBytes: byteLength(prompt),
292
- totalChars: prompt.length,
293
- totalTokens: estimateTokens(prompt),
294
- }
241
+ if (mode === 'full') markers.push(['Interactive context', renderInteractiveSessionContext(DEFAULT_SUBAGENT_ROSTER)])
242
+ markers.push(['Session origin', '## Session origin\n'], ['Role context', '## Your role in this session\n'])
243
+ if (gitNudge !== '') markers.push(['Git nudge', gitNudge])
244
+ return buildDumpResultFromMarkers(prompt, markers)
295
245
  }
296
246
 
297
247
  export function dumpSystemPrompt(kind: OriginKind, options: { gitNudge: boolean } = { gitNudge: true }): string {
@@ -334,6 +284,7 @@ export function dumpTurnPromptWithBreakdown(kind: OriginKind): DumpResult {
334
284
  ]
335
285
  const batch = [
336
286
  {
287
+ inputId: 'system-prompt-preview',
337
288
  text: PLACEHOLDER_TURN_TEXT.channel,
338
289
  authorId: 'U<PLACEHOLDER-AUTHOR>',
339
290
  authorName: '<PLACEHOLDER: current speaker name>',
@@ -372,7 +323,7 @@ export function dumpTurnPrompt(kind: OriginKind): string {
372
323
 
373
324
  function buildDumpResult(prompt: string, parts: ReadonlyArray<readonly [string, string]>): DumpResult {
374
325
  if (parts.map(([, body]) => body).join('') !== prompt) {
375
- throw new Error('turn-prompt breakdown does not cover the rendered prompt exactly')
326
+ throw new Error('prompt breakdown does not cover the rendered prompt exactly')
376
327
  }
377
328
  return {
378
329
  prompt,
@@ -383,37 +334,26 @@ function buildDumpResult(prompt: string, parts: ReadonlyArray<readonly [string,
383
334
  }
384
335
  }
385
336
 
337
+ // Locates each marker after the previous one, so a marker string that also
338
+ // occurs earlier (inside policy prose, say) cannot be mistaken for its section.
386
339
  function buildDumpResultFromMarkers(prompt: string, markers: ReadonlyArray<readonly [string, string]>): DumpResult {
387
- const starts = markers.map(([name, marker], index) => {
388
- const start = prompt.indexOf(marker, index === 0 ? 0 : 1)
389
- if (start < 0) throw new Error(`turn-prompt section marker not found: ${name}`)
390
- return { name, start }
391
- })
392
- if (starts[0]?.start !== 0 || starts.some((part, index) => index > 0 && part.start <= starts[index - 1]!.start)) {
393
- throw new Error('turn-prompt section markers are not in rendered order')
340
+ const starts: Array<{ name: string; start: number }> = []
341
+ for (const [name, marker] of markers) {
342
+ const previous = starts.at(-1)
343
+ const start = prompt.indexOf(marker, previous === undefined ? 0 : previous.start + 1)
344
+ if (start < 0) throw new Error(`prompt section marker not found in rendered order: ${name}`)
345
+ starts.push({ name, start })
394
346
  }
347
+ if (starts[0]?.start !== 0) throw new Error('the first prompt section marker does not start the prompt')
395
348
  return buildDumpResult(
396
349
  prompt,
397
350
  starts.map((part, index) => [part.name, prompt.slice(part.start, starts[index + 1]?.start)] as const),
398
351
  )
399
352
  }
400
353
 
401
- // Slice between two unique headers in the rendered prompt. Both anchors are
402
- // guaranteed unique by `composeSystemPrompt`'s contract (each section's
403
- // header appears exactly once). Used by the breakdown so we attribute each
404
- // section's chars precisely instead of guessing from input fixtures.
405
- function extractSection(prompt: string, startHeader: string, endHeader: string | undefined): string {
406
- const start = prompt.lastIndexOf(`\n\n${startHeader}`)
407
- if (start < 0) return ''
408
- const afterStart = start + 2
409
- if (endHeader === undefined) return prompt.slice(afterStart)
410
- const end = prompt.indexOf(`\n\n${endHeader}`, afterStart)
411
- return end < 0 ? prompt.slice(afterStart) : prompt.slice(afterStart, end)
412
- }
413
-
414
354
  function header(kind: OriginKind, result: DumpResult, label: 'SYSTEM PROMPT' | 'USER TURN'): string {
415
355
  const bar = '═'.repeat(78)
416
- const summary = `~${result.totalTokens} tok / ${result.totalChars} chars / ${result.totalBytes} bytes (tok est. chars/4)`
356
+ const summary = `${result.totalChars} chars / ${result.totalBytes} bytes / ~${result.totalTokens} tok (chars/4 estimate, not a tokenizer count)`
417
357
  return `\n${bar}\n ${label} — origin: ${kind} — ${summary}\n${bar}\n`
418
358
  }
419
359
 
@@ -429,7 +369,7 @@ function renderBreakdownTable(result: DumpResult): string {
429
369
  const sep = ` ${'─'.repeat(nameW)} ${'─'.repeat(tokW)} ${'─'.repeat(charW)} ${'─'.repeat(byteW)}`
430
370
 
431
371
  const lines = [
432
- row('Section', 'Tokens', 'Chars', 'Bytes'),
372
+ row('Section', '~Tok', 'Chars', 'Bytes'),
433
373
  sep,
434
374
  ...result.sections.map((s) => row(s.name, `~${s.tokens}`, String(s.chars), String(s.bytes))),
435
375
  sep,
@@ -455,11 +395,13 @@ function main(): void {
455
395
  [
456
396
  'Usage: bun run debug:prompt [--turn] [--origin <kind>] [--no-git-nudge]',
457
397
  '',
458
- 'Dump the rendered system prompt, or the per-turn user message with --turn,',
459
- 'for one or all session-origin kinds,',
460
- 'using placeholder values for every dynamic field. Each dump is prefixed',
461
- 'with a per-section breakdown showing approximate tokens (chars/4),',
462
- 'character count, and UTF-8 byte length.',
398
+ 'Dump the TypeClaw-composed system-prompt preamble, or the per-turn user',
399
+ 'message with --turn, for one or all session-origin kinds, using',
400
+ 'placeholder values for every dynamic field. pi appends project context,',
401
+ 'the skill catalog, and the cwd to the preamble at session creation.',
402
+ 'Each dump is prefixed with a per-section breakdown of character count,',
403
+ 'UTF-8 byte length, and a rough chars/4 token estimate (not a tokenizer',
404
+ 'count); rows include their trailing separator and sum to the totals.',
463
405
  '',
464
406
  'Options:',
465
407
  ' -o, --origin <kind> tui | cron | channel | subagent | all (default: all)',