@caupulican/pi-adaptative 0.81.29 → 0.81.31

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 (147) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/bundled-resources/skills/harness-self-adaptation/SKILL.md +327 -0
  3. package/dist/bundled-resources/skills/harness-self-adaptation/references/adaptation-layers.md +89 -0
  4. package/dist/core/agent-session.d.ts +11 -1
  5. package/dist/core/agent-session.d.ts.map +1 -1
  6. package/dist/core/agent-session.js +16 -14
  7. package/dist/core/agent-session.js.map +1 -1
  8. package/dist/core/autonomy/approval-gate.d.ts +1 -1
  9. package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
  10. package/dist/core/autonomy/approval-gate.js +5 -1
  11. package/dist/core/autonomy/approval-gate.js.map +1 -1
  12. package/dist/core/autonomy/lane-tool-surface.d.ts +4 -0
  13. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  14. package/dist/core/autonomy/lane-tool-surface.js +31 -4
  15. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  16. package/dist/core/autonomy/lane-tracker.d.ts +1 -0
  17. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  18. package/dist/core/autonomy/lane-tracker.js +11 -0
  19. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  20. package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
  21. package/dist/core/autonomy/risk-assessment.js +1 -1
  22. package/dist/core/autonomy/risk-assessment.js.map +1 -1
  23. package/dist/core/background-lane-controller.d.ts +12 -0
  24. package/dist/core/background-lane-controller.d.ts.map +1 -1
  25. package/dist/core/background-lane-controller.js +114 -19
  26. package/dist/core/background-lane-controller.js.map +1 -1
  27. package/dist/core/context/context-artifacts.d.ts.map +1 -1
  28. package/dist/core/context/context-artifacts.js +7 -6
  29. package/dist/core/context/context-artifacts.js.map +1 -1
  30. package/dist/core/context/context-store-retention.d.ts +12 -0
  31. package/dist/core/context/context-store-retention.d.ts.map +1 -0
  32. package/dist/core/context/context-store-retention.js +161 -0
  33. package/dist/core/context/context-store-retention.js.map +1 -0
  34. package/dist/core/context-gc.d.ts.map +1 -1
  35. package/dist/core/context-gc.js +19 -4
  36. package/dist/core/context-gc.js.map +1 -1
  37. package/dist/core/context-pipeline.d.ts +13 -12
  38. package/dist/core/context-pipeline.d.ts.map +1 -1
  39. package/dist/core/context-pipeline.js +128 -33
  40. package/dist/core/context-pipeline.js.map +1 -1
  41. package/dist/core/cost/cost-summary.d.ts +7 -1
  42. package/dist/core/cost/cost-summary.d.ts.map +1 -1
  43. package/dist/core/cost/cost-summary.js +28 -17
  44. package/dist/core/cost/cost-summary.js.map +1 -1
  45. package/dist/core/cost/daily-usage.d.ts +7 -3
  46. package/dist/core/cost/daily-usage.d.ts.map +1 -1
  47. package/dist/core/cost/daily-usage.js +10 -5
  48. package/dist/core/cost/daily-usage.js.map +1 -1
  49. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  50. package/dist/core/delegation/worker-runner.js +25 -9
  51. package/dist/core/delegation/worker-runner.js.map +1 -1
  52. package/dist/core/export-html/template.js +2 -1
  53. package/dist/core/extensions/loader.d.ts.map +1 -1
  54. package/dist/core/extensions/loader.js +52 -2
  55. package/dist/core/extensions/loader.js.map +1 -1
  56. package/dist/core/extensions/runner.d.ts.map +1 -1
  57. package/dist/core/extensions/runner.js +21 -19
  58. package/dist/core/extensions/runner.js.map +1 -1
  59. package/dist/core/extensions/types.d.ts +5 -0
  60. package/dist/core/extensions/types.d.ts.map +1 -1
  61. package/dist/core/extensions/types.js.map +1 -1
  62. package/dist/core/failure-corpus.d.ts.map +1 -1
  63. package/dist/core/failure-corpus.js +36 -13
  64. package/dist/core/failure-corpus.js.map +1 -1
  65. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  66. package/dist/core/local-runtime-controller.js +20 -2
  67. package/dist/core/local-runtime-controller.js.map +1 -1
  68. package/dist/core/memory-controller.d.ts +2 -0
  69. package/dist/core/memory-controller.d.ts.map +1 -1
  70. package/dist/core/memory-controller.js +18 -0
  71. package/dist/core/memory-controller.js.map +1 -1
  72. package/dist/core/models/local-runtime.d.ts.map +1 -1
  73. package/dist/core/models/local-runtime.js +15 -10
  74. package/dist/core/models/local-runtime.js.map +1 -1
  75. package/dist/core/reflection-controller.d.ts +3 -1
  76. package/dist/core/reflection-controller.d.ts.map +1 -1
  77. package/dist/core/reflection-controller.js +8 -5
  78. package/dist/core/reflection-controller.js.map +1 -1
  79. package/dist/core/runtime-builder.d.ts +2 -0
  80. package/dist/core/runtime-builder.d.ts.map +1 -1
  81. package/dist/core/runtime-builder.js.map +1 -1
  82. package/dist/core/sdk.d.ts.map +1 -1
  83. package/dist/core/sdk.js +1 -1
  84. package/dist/core/sdk.js.map +1 -1
  85. package/dist/core/session-analytics.d.ts +13 -7
  86. package/dist/core/session-analytics.d.ts.map +1 -1
  87. package/dist/core/session-analytics.js +155 -112
  88. package/dist/core/session-analytics.js.map +1 -1
  89. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  90. package/dist/core/tool-recovery-log-records.js +54 -9
  91. package/dist/core/tool-recovery-log-records.js.map +1 -1
  92. package/dist/core/tool-recovery-logger.d.ts +2 -0
  93. package/dist/core/tool-recovery-logger.d.ts.map +1 -1
  94. package/dist/core/tool-recovery-logger.js +32 -13
  95. package/dist/core/tool-recovery-logger.js.map +1 -1
  96. package/dist/core/tool-recovery-stats.d.ts +15 -0
  97. package/dist/core/tool-recovery-stats.d.ts.map +1 -0
  98. package/dist/core/tool-recovery-stats.js +206 -0
  99. package/dist/core/tool-recovery-stats.js.map +1 -0
  100. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  101. package/dist/core/tools/delegate-status.js +15 -6
  102. package/dist/core/tools/delegate-status.js.map +1 -1
  103. package/dist/core/tools/delegate.d.ts +3 -0
  104. package/dist/core/tools/delegate.d.ts.map +1 -1
  105. package/dist/core/tools/delegate.js +7 -2
  106. package/dist/core/tools/delegate.js.map +1 -1
  107. package/dist/main.d.ts.map +1 -1
  108. package/dist/main.js +1 -1
  109. package/dist/main.js.map +1 -1
  110. package/dist/modes/interactive/components/bash-execution.d.ts +2 -1
  111. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  112. package/dist/modes/interactive/components/bash-execution.js +12 -1
  113. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  114. package/dist/modes/interactive/components/footer.d.ts +1 -0
  115. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  116. package/dist/modes/interactive/components/footer.js +19 -9
  117. package/dist/modes/interactive/components/footer.js.map +1 -1
  118. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  119. package/dist/modes/interactive/components/tool-execution.js +12 -2
  120. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  121. package/dist/modes/interactive/components/tool-panel-registry.d.ts +1 -0
  122. package/dist/modes/interactive/components/tool-panel-registry.d.ts.map +1 -1
  123. package/dist/modes/interactive/components/tool-panel-registry.js +18 -2
  124. package/dist/modes/interactive/components/tool-panel-registry.js.map +1 -1
  125. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  126. package/dist/modes/interactive/interactive-mode.js +9 -3
  127. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  128. package/dist/modes/rpc/jsonl.d.ts.map +1 -1
  129. package/dist/modes/rpc/jsonl.js +9 -28
  130. package/dist/modes/rpc/jsonl.js.map +1 -1
  131. package/dist/utils/streaming-lines.d.ts +20 -0
  132. package/dist/utils/streaming-lines.d.ts.map +1 -0
  133. package/dist/utils/streaming-lines.js +79 -0
  134. package/dist/utils/streaming-lines.js.map +1 -0
  135. package/docs/extensions.md +2 -0
  136. package/docs/index.md +1 -1
  137. package/docs/self-adaptation.md +7 -0
  138. package/docs/settings.md +5 -1
  139. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  140. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  141. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  142. package/examples/extensions/sandbox/package-lock.json +2 -2
  143. package/examples/extensions/sandbox/package.json +1 -1
  144. package/examples/extensions/with-deps/package-lock.json +2 -2
  145. package/examples/extensions/with-deps/package.json +1 -1
  146. package/npm-shrinkwrap.json +12 -12
  147. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAqB,YAAY,EAAsB,MAAM,2BAA2B,CAAC;AACvG,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAA4B,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAC/F,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAEpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,yBAAyB,EAAE,MAAM,8BAA8B,CAAC;AAMzE,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc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QACL,cAAc;QACd,eAAe;QACf,GAAG;QACH,QAAQ;QACR,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,cAAc;QACd,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,aAAa;QACb,sBAAsB;QACtB,gBAAgB;QAChB,iBAAiB;QACjB,kBAAkB;QAClB,iBAAiB;QACjB,eAAe,EAAE,OAAO,CAAC,eAAe,IAAI,OAAO,CAAC,KAAK,IAAI,IAAI;QACjE,kBAAkB,EAAE,OAAO,CAAC,kBAAkB,IAAI,OAAO,CAAC,aAAa,KAAK,SAAS;QACrF,cAAc,EAAE,OAAO,CAAC,cAAc,IAAI,OAAO,CAAC,GAAG,CAAC,gBAAgB,KAAK,GAAG;QAC9E,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;IACH,IAAI,CAAC;QACJ,8FAA8F;QAC9F,8FAA8F;QAC9F,MAAM,OAAO,CAAC,iCAAiC,EAAE,CAAC;QAClD,IAAI,oBAAoB,EAAE,UAAU,CAAC,iCAAiC,CAAC,EAAE,CAAC;YACzE,oBAAoB,GAAG,SAAS,CAAC;QAClC,CAAC;IACF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,wFAAwF;QACxF,IAAI,CAAC,oBAAoB,EAAE,UAAU,CAAC,iCAAiC,CAAC,EAAE,CAAC;YAC1E,OAAO,CAAC,OAAO,EAAE,CAAC;YAClB,MAAM,KAAK,CAAC;QACb,CAAC;IACF,CAAC;IACD,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, convertToLlm, type ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { getDefaultSessionDir, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@caupulican/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_ACTIVE_TOOL_NAMES } from \"./default-tool-surface.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { parseResourceProfileInput } from \"./resource-profile-blocks.ts\";\nimport type {\n\tProfileDefinitionInput,\n\tResourceProfileFilterSettings,\n\tResourceProfileSettings,\n} from \"./settings-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, then the model's declared default, else 'medium'. */\n\tthinkingLevel?: ThinkingLevel;\n\t/**\n\t * Whether `model` came from an explicit CLI/SDK flag (vs. profile/settings resolution).\n\t * When false (default), the active profile's model is re-applied on reload so live profile\n\t * edits take effect; when true, the explicit launch-time model is preserved across reloads.\n\t */\n\tisExplicitModel?: boolean;\n\t/** Whether `thinkingLevel` came from an explicit flag (see isExplicitModel). */\n\tisExplicitThinking?: boolean;\n\t/** True when this session is a spawned subagent/child — gates durable memory writes. */\n\tisChildSession?: boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write, context_audit,\n\t * goal, delegate, and run_toolkit_script)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the shared default built-in tool surface and leaves extension/custom\n\t * tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Optional resource-profile allow/block filters for tool names. */\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Optional one-shot resource filters or complete situation profiles. Never persisted to disk. */\n\tresourceProfileDefinitions?: Record<string, ResourceProfileSettings | ProfileDefinitionInput>;\n\t/** Optional one-shot profile definitions as JSON or <resource-profile> tag text. Never persisted to disk. */\n\tresourceProfileJson?: string | string[];\n\t/** Optional runtime profile selection. Never persisted to disk. */\n\tresourceProfiles?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir)) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n\tsessionId?: string,\n): Record<string, string> | undefined {\n\tif (\n\t\tsessionId &&\n\t\t(model.provider === \"opencode\" || model.provider === \"opencode-go\" || model.baseUrl.includes(\"opencode.ai\"))\n\t) {\n\t\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n\t}\n\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@caupulican/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst needsProfileReload =\n\t\toptions.resourceProfileDefinitions !== undefined ||\n\t\toptions.resourceProfileJson !== undefined ||\n\t\toptions.resourceProfiles !== undefined;\n\tif (options.resourceProfileDefinitions) {\n\t\tsettingsManager.addInlineResourceProfileDefinitions(options.resourceProfileDefinitions);\n\t}\n\tif (options.resourceProfileJson) {\n\t\tconst inputs = Array.isArray(options.resourceProfileJson)\n\t\t\t? options.resourceProfileJson\n\t\t\t: [options.resourceProfileJson];\n\t\tfor (const input of inputs) {\n\t\t\tsettingsManager.addInlineResourceProfileDefinitions(parseResourceProfileInput(input).profiles);\n\t\t}\n\t}\n\tif (options.resourceProfiles !== undefined) {\n\t\tsettingsManager.setRuntimeResourceProfiles(options.resourceProfiles);\n\t}\n\tconst sessionManager =\n\t\toptions.sessionManager ?? SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t} else if (needsProfileReload) {\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\tif (activeProfileNames.length > 0) {\n\t\tconst profileSettings = resolveProfileModelSettings({\n\t\t\tactiveProfileNames,\n\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\tmodelRegistry,\n\t\t\tcwd,\n\t\t});\n\t\tif (profileSettings.error) {\n\t\t\tmodelFallbackMessage = `Profile model resolution error: ${profileSettings.error}`;\n\t\t}\n\t\tif (!model && profileSettings.model) {\n\t\t\tmodel = profileSettings.model;\n\t\t}\n\t\tif (thinkingLevel === undefined && profileSettings.thinkingLevel) {\n\t\t\tthinkingLevel = profileSettings.thinkingLevel;\n\t\t}\n\t}\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (thinkingLevel === undefined && !(hasExistingSession && hasThinkingEntry)) {\n\t\t\tthinkingLevel = result.thinkingLevel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? model?.defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to the user's default, then the selected model's own default.\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel =\n\t\t\tsettingsManager.getDefaultThinkingLevel() ?? model?.defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames = [\n\t\t...DEFAULT_ACTIVE_TOOL_NAMES,\n\t\t...(settingsManager.getScoutSettings().enabled ? [\"context_scout\"] : []),\n\t];\n\tconst toolProfileFilter = options.toolProfileFilter ?? settingsManager.getResourceProfileFilter(\"tools\");\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\tonAuthRejection:\n\t\t\t\t\tauth.apiKey && model.provider === \"openai-codex-responses\"\n\t\t\t\t\t\t? async () => modelRegistry.recoverRejectedOAuthApiKey(model.provider, auth.apiKey as string)\n\t\t\t\t\t\t: options?.onAuthRejection,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\tmaxStallTurns: settingsManager.getAutonomySettings().maxStallTurns,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tagentDir,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\ttoolProfileFilter,\n\t\tisExplicitModel: options.isExplicitModel ?? options.model != null,\n\t\tisExplicitThinking: options.isExplicitThinking ?? options.thinkingLevel !== undefined,\n\t\tisChildSession: options.isChildSession ?? process.env.PI_CHILD_SESSION === \"1\",\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\ttry {\n\t\t// The initial runtime has now bound providers from profile-granted extensions. Re-resolve the\n\t\t// profile model against that authoritative registry generation, then resync model capability.\n\t\tawait session.reapplyActiveProfileModelSettings();\n\t\tif (modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tmodelFallbackMessage = undefined;\n\t\t}\n\t} catch (error) {\n\t\t// Preserve the established non-fatal fallback for a genuinely unresolved profile model.\n\t\tif (!modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tsession.dispose();\n\t\t\tthrow error;\n\t\t}\n\t}\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
1
+ {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAqB,YAAY,EAAsB,MAAM,2BAA2B,CAAC;AACvG,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAA4B,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAC/F,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAEvD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAEpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,yBAAyB,EAAE,MAAM,8BAA8B,CAAC;AAMzE,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAA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AAc;QACd,eAAe;QACf,GAAG;QACH,QAAQ;QACR,YAAY,EAAE,OAAO,CAAC,YAAY;QAClC,cAAc;QACd,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,aAAa;QACb,sBAAsB;QACtB,gBAAgB;QAChB,iBAAiB;QACjB,kBAAkB;QAClB,iBAAiB;QACjB,eAAe,EAAE,OAAO,CAAC,eAAe,IAAI,OAAO,CAAC,KAAK,IAAI,IAAI;QACjE,kBAAkB,EAAE,OAAO,CAAC,kBAAkB,IAAI,OAAO,CAAC,aAAa,KAAK,SAAS;QACrF,cAAc,EAAE,OAAO,CAAC,cAAc,IAAI,OAAO,CAAC,GAAG,CAAC,gBAAgB,KAAK,GAAG;QAC9E,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC5C,CAAC,CAAC;IACH,IAAI,CAAC;QACJ,8FAA8F;QAC9F,8FAA8F;QAC9F,MAAM,OAAO,CAAC,iCAAiC,EAAE,CAAC;QAClD,IAAI,oBAAoB,EAAE,UAAU,CAAC,iCAAiC,CAAC,EAAE,CAAC;YACzE,oBAAoB,GAAG,SAAS,CAAC;QAClC,CAAC;IACF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,wFAAwF;QACxF,IAAI,CAAC,oBAAoB,EAAE,UAAU,CAAC,iCAAiC,CAAC,EAAE,CAAC;YAC1E,OAAO,CAAC,OAAO,EAAE,CAAC;YAClB,MAAM,KAAK,CAAC;QACb,CAAC;IACF,CAAC;IACD,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, convertToLlm, type ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { getDefaultSessionDir, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@caupulican/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_ACTIVE_TOOL_NAMES } from \"./default-tool-surface.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { parseResourceProfileInput } from \"./resource-profile-blocks.ts\";\nimport type {\n\tProfileDefinitionInput,\n\tResourceProfileFilterSettings,\n\tResourceProfileSettings,\n} from \"./settings-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, then the model's declared default, else 'medium'. */\n\tthinkingLevel?: ThinkingLevel;\n\t/**\n\t * Whether `model` came from an explicit CLI/SDK flag (vs. profile/settings resolution).\n\t * When false (default), the active profile's model is re-applied on reload so live profile\n\t * edits take effect; when true, the explicit launch-time model is preserved across reloads.\n\t */\n\tisExplicitModel?: boolean;\n\t/** Whether `thinkingLevel` came from an explicit flag (see isExplicitModel). */\n\tisExplicitThinking?: boolean;\n\t/** True when this session is a spawned subagent/child — gates durable memory writes. */\n\tisChildSession?: boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write, context_audit,\n\t * goal, delegate, and run_toolkit_script)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the shared default built-in tool surface and leaves extension/custom\n\t * tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Optional resource-profile allow/block filters for tool names. */\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Optional one-shot resource filters or complete situation profiles. Never persisted to disk. */\n\tresourceProfileDefinitions?: Record<string, ResourceProfileSettings | ProfileDefinitionInput>;\n\t/** Optional one-shot profile definitions as JSON or <resource-profile> tag text. Never persisted to disk. */\n\tresourceProfileJson?: string | string[];\n\t/** Optional runtime profile selection. Never persisted to disk. */\n\tresourceProfiles?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir)) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n\tsessionId?: string,\n): Record<string, string> | undefined {\n\tif (\n\t\tsessionId &&\n\t\t(model.provider === \"opencode\" || model.provider === \"opencode-go\" || model.baseUrl.includes(\"opencode.ai\"))\n\t) {\n\t\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n\t}\n\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@caupulican/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst needsProfileReload =\n\t\toptions.resourceProfileDefinitions !== undefined ||\n\t\toptions.resourceProfileJson !== undefined ||\n\t\toptions.resourceProfiles !== undefined;\n\tif (options.resourceProfileDefinitions) {\n\t\tsettingsManager.addInlineResourceProfileDefinitions(options.resourceProfileDefinitions);\n\t}\n\tif (options.resourceProfileJson) {\n\t\tconst inputs = Array.isArray(options.resourceProfileJson)\n\t\t\t? options.resourceProfileJson\n\t\t\t: [options.resourceProfileJson];\n\t\tfor (const input of inputs) {\n\t\t\tsettingsManager.addInlineResourceProfileDefinitions(parseResourceProfileInput(input).profiles);\n\t\t}\n\t}\n\tif (options.resourceProfiles !== undefined) {\n\t\tsettingsManager.setRuntimeResourceProfiles(options.resourceProfiles);\n\t}\n\tconst sessionManager =\n\t\toptions.sessionManager ?? SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t} else if (needsProfileReload) {\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\tif (activeProfileNames.length > 0) {\n\t\tconst profileSettings = resolveProfileModelSettings({\n\t\t\tactiveProfileNames,\n\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\tmodelRegistry,\n\t\t\tcwd,\n\t\t});\n\t\tif (profileSettings.error) {\n\t\t\tmodelFallbackMessage = `Profile model resolution error: ${profileSettings.error}`;\n\t\t}\n\t\tif (!model && profileSettings.model) {\n\t\t\tmodel = profileSettings.model;\n\t\t}\n\t\tif (thinkingLevel === undefined && profileSettings.thinkingLevel) {\n\t\t\tthinkingLevel = profileSettings.thinkingLevel;\n\t\t}\n\t}\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (thinkingLevel === undefined && !(hasExistingSession && hasThinkingEntry)) {\n\t\t\tthinkingLevel = result.thinkingLevel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? model?.defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to the user's default, then the selected model's own default.\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel =\n\t\t\tsettingsManager.getDefaultThinkingLevel() ?? model?.defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames = [\n\t\t...DEFAULT_ACTIVE_TOOL_NAMES,\n\t\t...(settingsManager.getScoutSettings().enabled ? [\"context_scout\"] : []),\n\t];\n\tconst toolProfileFilter = options.toolProfileFilter ?? settingsManager.getResourceProfileFilter(\"tools\");\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\tonAuthRejection:\n\t\t\t\t\tauth.apiKey && model.provider === \"openai-codex\"\n\t\t\t\t\t\t? async () => modelRegistry.recoverRejectedOAuthApiKey(model.provider, auth.apiKey as string)\n\t\t\t\t\t\t: options?.onAuthRejection,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\tmaxStallTurns: settingsManager.getAutonomySettings().maxStallTurns,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tagentDir,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\ttoolProfileFilter,\n\t\tisExplicitModel: options.isExplicitModel ?? options.model != null,\n\t\tisExplicitThinking: options.isExplicitThinking ?? options.thinkingLevel !== undefined,\n\t\tisChildSession: options.isChildSession ?? process.env.PI_CHILD_SESSION === \"1\",\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\ttry {\n\t\t// The initial runtime has now bound providers from profile-granted extensions. Re-resolve the\n\t\t// profile model against that authoritative registry generation, then resync model capability.\n\t\tawait session.reapplyActiveProfileModelSettings();\n\t\tif (modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tmodelFallbackMessage = undefined;\n\t\t}\n\t} catch (error) {\n\t\t// Preserve the established non-fatal fallback for a genuinely unresolved profile model.\n\t\tif (!modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tsession.dispose();\n\t\t\tthrow error;\n\t\t}\n\t}\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
@@ -54,12 +54,17 @@ export interface SessionAnalyticsDeps {
54
54
  getToolRecoveryEventLogPath(): string;
55
55
  }
56
56
  export declare class SessionAnalytics {
57
- /** Memoized spawned-usage totals, keyed by session entry count (Bug #22: O(1) between turns). */
58
- private _spawnedUsageCache?;
57
+ /** Incremental aggregate over append-ordered session entries. */
58
+ private _currentSessionCostCache?;
59
59
  /** Memoized daily usage totals with a short TTL, keyed by the resolved scope dir and local-day window. */
60
60
  private _dailyUsageCache?;
61
- /** Live recovery telemetry records already snapshotted for the worker; keyed to dedupe sidecar reads. */
62
- private readonly _toolArgumentValidationRecords;
61
+ /** Memoized full cost summary. The footer renders on every streamed delta and keystroke, so
62
+ * rescanning a long session log there turns redraw into O(entries) work per frame. */
63
+ private _costSummaryCache?;
64
+ /** Cumulative stats initialized once from persisted telemetry, then updated without retaining record details. */
65
+ private _toolArgumentValidationStats;
66
+ /** Incremental context-usage state keyed by the append-only branch leaf. */
67
+ private _postCompactionUsageCache?;
63
68
  private readonly deps;
64
69
  constructor(deps: SessionAnalyticsDeps);
65
70
  getSessionStats(): SessionStats;
@@ -95,15 +100,16 @@ export declare class SessionAnalytics {
95
100
  sourceSessionId?: string;
96
101
  reportId?: string;
97
102
  }): string | undefined;
103
+ private getCurrentSessionCostTotals;
98
104
  /**
99
- * Aggregate all recorded spawned-usage reports (see {@link addSpawnedUsage}). Cached by the session
100
- * entry count so the interactive footer (which calls this every render frame) is O(1) between turns
101
- * instead of an O(N) scan on every keystroke (Bug #22). Recomputes only when entries change.
105
+ * Aggregate all recorded spawned-usage reports (see {@link addSpawnedUsage}). The append-ordered
106
+ * accumulator processes only new entries, so repeated turns do not rescan the full session.
102
107
  */
103
108
  getSpawnedUsage(): SpawnedUsageTotals;
104
109
  getCostSummary(now?: Date): SessionCostSummary;
105
110
  getDailyUsageTotals(now?: Date): DailyUsageTotals;
106
111
  getDailyUsageBreakdown(formatLabel?: (label: string) => string, now?: Date): string;
112
+ private getPostCompactionUsageState;
107
113
  getContextUsage(): ContextUsage | undefined;
108
114
  /**
109
115
  * Export session to HTML.
@@ -1 +1 @@
1
- {"version":3,"file":"session-analytics.d.ts","sourceRoot":"","sources":["../../src/core/session-analytics.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC1E,OAAO,EAMN,KAAK,cAAc,EACnB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAEX,KAAK,EACL,4BAA4B,EAC5B,sBAAsB,EACtB,oCAAoC,EACpC,KAAK,EACL,MAAM,mBAAmB,CAAC;AAI3B,OAAO,EACN,KAAK,YAAY,EAGjB,KAAK,kBAAkB,EACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAGN,KAAK,kBAAkB,EACvB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAGN,KAAK,gBAAgB,EAGrB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC1E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAEN,KAAK,+BAA+B,EACpC,MAAM,gCAAgC,CAAC;AAExC,eAAO,MAAM,oCAAoC,6BAA6B,CAAC;AAE/E,MAAM,WAAW,mCAAmC;IACnD,gBAAgB,EAAE,MAAM,CAAC;IACzB,eAAe,EAAE,MAAM,CAAC;IACxB,qBAAqB,EAAE,MAAM,CAAC;IAC9B,kBAAkB,EAAE,MAAM,CAAC;IAC3B,kBAAkB,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,2BAA2B;IAC3C,KAAK,E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AAY,CAAC,iBAAiB,CAAC,CAkBxD;IAED,4BAA4B,CAAC,MAAM,EAAE,+BAA+B,GAAG,IAAI,CAE1E;IAED,OAAO,CAAC,wCAAwC;IAkBhD,8BAA8B,IAAI,2BAA2B,CAwE5D;IAED;;;;;;;;;OASG;IACH,kBAAkB,IAAI,KAAK,CAuD1B;IAED;;;;;;;;;;;OAWG;IACH,eAAe,CACd,KAAK,EAAE,KAAK,EACZ,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,eAAe,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,GACpE,MAAM,GAAG,SAAS,CAoBpB;IAED;;;;OAIG;IACH,eAAe,IAAI,kBAAkB,CAQpC;IAED,cAAc,CAAC,GAAG,OAAa,GAAG,kBAAkB,CAOnD;IAED,mBAAmB,CAAC,GAAG,OAAa,GAAG,gBAAgB,CAyBtD;IAED,sBAAsB,CAAC,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,EAAE,GAAG,OAAa,GAAG,MAAM,CAExF;IAED,eAAe,IAAI,YAAY,GAAG,SAAS,CA4C1C;IAED;;;;OAIG;IACG,YAAY,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAgBvD;IAED;;;;;OAKG;IACH,aAAa,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,CAgCzC;IAED;;;;OAIG;IACH,oBAAoB,IAAI,MAAM,GAAG,SAAS,CAuBzC;CACD","sourcesContent":["/**\n * Session usage / cost / stats accounting, context-window usage, and session export.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Read-only over the session\n * except for its two owned memo caches (`_spawnedUsageCache`, `_dailyUsageCache`) — it never mutates\n * agent or session state. Single source of truth for \"how much did this session and its spawned\n * subtree spend\" (footer roll-up, print-mode child reporting), the daily cross-session totals, the\n * /context window estimate, and HTML/JSONL export of the current branch.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport type { AgentMessage, AgentState } from \"@caupulican/pi-agent-core\";\nimport {\n\tCURRENT_SESSION_VERSION,\n\tcalculateContextTokens,\n\testimateContextTokens,\n\tgetLatestCompactionEntry,\n\ttype SessionHeader,\n\ttype SessionManager,\n} from \"@caupulican/pi-agent-core/node\";\nimport type {\n\tAssistantMessage,\n\tModel,\n\tToolArgumentExecutionOutcome,\n\tToolArgumentTeachState,\n\tToolArgumentValidationTelemetryEvent,\n\tUsage,\n} from \"@caupulican/pi-ai\";\nimport { getSessionsDir } from \"../config.ts\";\nimport { theme } from \"../modes/interactive/theme/theme.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport {\n\ttype SessionStats,\n\tSPAWNED_USAGE_CUSTOM_TYPE,\n\ttype SpawnedUsageReport,\n\ttype SpawnedUsageTotals,\n} from \"./agent-session.ts\";\nimport {\n\taggregateCurrentSessionCostsFromEntries,\n\tcreateSessionCostSummary,\n\ttype SessionCostSummary,\n} from \"./cost/cost-summary.ts\";\nimport {\n\taggregateDailyUsageFromSessionFiles,\n\taggregateDailyUsageFromSessionRoot,\n\ttype DailyUsageTotals,\n\tformatDailyUsageBreakdown,\n\tgetLocalDayWindow,\n} from \"./cost/daily-usage.ts\";\nimport { exportSessionToHtml, type ToolHtmlRenderer } from \"./export-html/index.ts\";\nimport { createToolHtmlRenderer } from \"./export-html/tool-renderer.ts\";\nimport type { ContextUsage, ToolDefinition } from \"./extensions/index.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport {\n\tisToolArgumentValidationLogRecord,\n\ttype ToolArgumentValidationLogRecord,\n} from \"./tool-recovery-log-records.ts\";\n\nexport const TOOL_ARGUMENT_VALIDATION_CUSTOM_TYPE = \"tool_argument_validation\";\n\nexport interface ToolArgumentValidationTeachEfficacy {\n\trecurrenceBefore: number;\n\trecurrenceAfter: number;\n\trepairedThenSucceeded: number;\n\trepairedThenFailed: number;\n\trepairedThenNotRun: number;\n}\n\nexport interface ToolArgumentValidationStats {\n\tclean: number;\n\trepaired: number;\n\tbounced: number;\n\tfailureModes: Record<string, number>;\n\trepairsApplied: Record<string, number>;\n\ttaught: Record<ToolArgumentTeachState, number>;\n\texecutionOutcome: Record<ToolArgumentExecutionOutcome, number>;\n\tteachEfficacy: Record<string, ToolArgumentValidationTeachEfficacy>;\n}\n\nexport interface ToolArgumentValidationRecord extends ToolArgumentValidationTelemetryEvent {\n\tversion: 1;\n}\n\nexport interface SessionAnalyticsDeps {\n\t/** Live agent state — assistant-message usage and message counts are read from here. */\n\tgetState(): AgentState;\n\t/** All messages (agent state view) — used for context-window estimation and last-assistant text. */\n\tgetMessages(): AgentMessage[];\n\t/** Current session model — its context window bounds the /context estimate. */\n\tgetModel(): Model<any> | undefined;\n\t/** Session log — entries feed spawned-usage roll-up, daily totals, branch export. */\n\tgetSessionManager(): SessionManager;\n\t/** Settings — the export theme is read here. */\n\tgetSettingsManager(): SettingsManager;\n\t/** Resolve a tool definition for the HTML export's custom-tool renderer. */\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\t/** Sidecar recovery telemetry log; read on demand so turn handling never writes session custom entries. */\n\tgetToolRecoveryEventLogPath(): string;\n}\n\nexport class SessionAnalytics {\n\t/** Memoized spawned-usage totals, keyed by session entry count (Bug #22: O(1) between turns). */\n\tprivate _spawnedUsageCache?: { entryCount: number; totals: SpawnedUsageTotals };\n\t/** Memoized daily usage totals with a short TTL, keyed by the resolved scope dir and local-day window. */\n\tprivate _dailyUsageCache?: {\n\t\tsessionDir: string;\n\t\twindowStartMs: number;\n\t\twindowEndMs: number;\n\t\texpiresAt: number;\n\t\ttotals: DailyUsageTotals;\n\t};\n\t/** Live recovery telemetry records already snapshotted for the worker; keyed to dedupe sidecar reads. */\n\tprivate readonly _toolArgumentValidationRecords = new Map<string, ToolArgumentValidationLogRecord>();\n\n\tprivate readonly deps: SessionAnalyticsDeps;\n\n\tconstructor(deps: SessionAnalyticsDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tgetSessionStats(): SessionStats {\n\t\tconst state = this.deps.getState();\n\t\tconst userMessages = state.messages.filter((m) => m.role === \"user\").length;\n\t\tconst assistantMessages = state.messages.filter((m) => m.role === \"assistant\").length;\n\t\tconst toolResults = state.messages.filter((m) => m.role === \"toolResult\").length;\n\n\t\tlet toolCalls = 0;\n\t\tlet totalInput = 0;\n\t\tlet totalOutput = 0;\n\t\tlet totalCacheRead = 0;\n\t\tlet totalCacheWrite = 0;\n\t\tlet totalCost = 0;\n\n\t\tfor (const message of state.messages) {\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\ttoolCalls += assistantMsg.content.filter((c) => c.type === \"toolCall\").length;\n\t\t\t\ttotalInput += assistantMsg.usage.input;\n\t\t\t\ttotalOutput += assistantMsg.usage.output;\n\t\t\t\ttotalCacheRead += assistantMsg.usage.cacheRead;\n\t\t\t\ttotalCacheWrite += assistantMsg.usage.cacheWrite;\n\t\t\t\ttotalCost += assistantMsg.usage.cost.total;\n\t\t\t}\n\t\t}\n\n\t\tconst toolArgumentValidation = this.getToolArgumentValidationStats();\n\t\tconst compactionGates = this.getCompactionGateStats();\n\n\t\treturn {\n\t\t\tsessionFile: this.deps.getSessionManager().getSessionFile(),\n\t\t\tsessionId: this.deps.getSessionManager().getSessionId(),\n\t\t\tuserMessages,\n\t\t\tassistantMessages,\n\t\t\ttoolCalls,\n\t\t\ttoolResults,\n\t\t\ttotalMessages: state.messages.length,\n\t\t\ttokens: {\n\t\t\t\tinput: totalInput,\n\t\t\t\toutput: totalOutput,\n\t\t\t\tcacheRead: totalCacheRead,\n\t\t\t\tcacheWrite: totalCacheWrite,\n\t\t\t\ttotal: totalInput + totalOutput + totalCacheRead + totalCacheWrite,\n\t\t\t},\n\t\t\tcost: totalCost,\n\t\t\tcontextUsage: this.getContextUsage(),\n\t\t\ttoolArgumentValidation,\n\t\t\tcompactionGates,\n\t\t};\n\t}\n\n\tgetCompactionGateStats(): SessionStats[\"compactionGates\"] {\n\t\tlet gateFailures = 0;\n\t\tlet deterministicGapFills = 0;\n\t\tlet compactionsWithGateFailures = 0;\n\t\tfor (const entry of this.deps.getSessionManager().getEntries()) {\n\t\t\tif (entry.type !== \"compaction\") continue;\n\t\t\tconst details = entry.details;\n\t\t\tif (!details || typeof details !== \"object\") continue;\n\t\t\tconst rawGateFailures = (details as { verificationGateFailures?: unknown }).verificationGateFailures;\n\t\t\tconst rawGapFills = (details as { deterministicGapFills?: unknown }).deterministicGapFills;\n\t\t\tconst entryGateFailures =\n\t\t\t\ttypeof rawGateFailures === \"number\" && Number.isFinite(rawGateFailures) ? rawGateFailures : 0;\n\t\t\tconst entryGapFills = typeof rawGapFills === \"number\" && Number.isFinite(rawGapFills) ? rawGapFills : 0;\n\t\t\tgateFailures += entryGateFailures;\n\t\t\tdeterministicGapFills += entryGapFills;\n\t\t\tif (entryGateFailures > 0) compactionsWithGateFailures++;\n\t\t}\n\t\treturn { gateFailures, deterministicGapFills, compactionsWithGateFailures };\n\t}\n\n\trecordToolArgumentValidation(record: ToolArgumentValidationLogRecord): void {\n\t\tthis._toolArgumentValidationRecords.set(record.recordId, record);\n\t}\n\n\tprivate readToolArgumentValidationSidecarRecords(): ToolArgumentValidationLogRecord[] {\n\t\tconst filePath = this.deps.getToolRecoveryEventLogPath();\n\t\tif (!existsSync(filePath)) return [];\n\t\tconst records: ToolArgumentValidationLogRecord[] = [];\n\t\ttry {\n\t\t\tconst sessionId = this.deps.getSessionManager().getSessionId();\n\t\t\tfor (const line of readFileSync(filePath, \"utf-8\").split(\"\\n\")) {\n\t\t\t\tif (line.trim().length === 0) continue;\n\t\t\t\tconst parsed = JSON.parse(line) as unknown;\n\t\t\t\tif (!isToolArgumentValidationLogRecord(parsed) || parsed.sessionId !== sessionId) continue;\n\t\t\t\trecords.push(parsed);\n\t\t\t}\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t\treturn records;\n\t}\n\n\tgetToolArgumentValidationStats(): ToolArgumentValidationStats {\n\t\tconst stats: ToolArgumentValidationStats = {\n\t\t\tclean: 0,\n\t\t\trepaired: 0,\n\t\t\tbounced: 0,\n\t\t\tfailureModes: {},\n\t\t\trepairsApplied: {},\n\t\t\ttaught: { none: 0, note: 0, rule: 0 },\n\t\t\texecutionOutcome: { not_run: 0, succeeded: 0, failed: 0 },\n\t\t\tteachEfficacy: {},\n\t\t};\n\n\t\tconst getEfficacy = (record: ToolArgumentValidationRecord, mode: string): ToolArgumentValidationTeachEfficacy => {\n\t\t\tconst key = `${record.provider ?? \"unknown\"}/${record.model ?? \"unknown\"}:${mode}`;\n\t\t\tstats.teachEfficacy[key] ??= {\n\t\t\t\trecurrenceBefore: 0,\n\t\t\t\trecurrenceAfter: 0,\n\t\t\t\trepairedThenSucceeded: 0,\n\t\t\t\trepairedThenFailed: 0,\n\t\t\t\trepairedThenNotRun: 0,\n\t\t\t};\n\t\t\treturn stats.teachEfficacy[key];\n\t\t};\n\n\t\tconst seen = new Set<string>();\n\t\tconst consume = (record: ToolArgumentValidationRecord, key: string): void => {\n\t\t\tif (seen.has(key)) return;\n\t\t\tseen.add(key);\n\t\t\tstats[record.outcome] += 1;\n\t\t\tconst taught = record.taught ?? \"none\";\n\t\t\tconst executionOutcome = record.executionOutcome ?? \"not_run\";\n\t\t\tstats.taught[taught] += 1;\n\t\t\tstats.executionOutcome[executionOutcome] += 1;\n\t\t\tconst modes = new Set([...record.failureModes, ...record.repairsApplied]);\n\t\t\tfor (const mode of record.failureModes) {\n\t\t\t\tstats.failureModes[mode] = (stats.failureModes[mode] ?? 0) + 1;\n\t\t\t}\n\t\t\tfor (const repair of record.repairsApplied) {\n\t\t\t\tstats.repairsApplied[repair] = (stats.repairsApplied[repair] ?? 0) + 1;\n\t\t\t}\n\t\t\tfor (const mode of modes) {\n\t\t\t\tconst efficacy = getEfficacy(record, mode);\n\t\t\t\tif (taught === \"none\") {\n\t\t\t\t\tefficacy.recurrenceBefore++;\n\t\t\t\t} else {\n\t\t\t\t\tefficacy.recurrenceAfter++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (record.outcome === \"repaired\") {\n\t\t\t\tfor (const repair of record.repairsApplied) {\n\t\t\t\t\tconst efficacy = getEfficacy(record, repair);\n\t\t\t\t\tif (executionOutcome === \"succeeded\") efficacy.repairedThenSucceeded++;\n\t\t\t\t\tif (executionOutcome === \"failed\") efficacy.repairedThenFailed++;\n\t\t\t\t\tif (executionOutcome === \"not_run\") efficacy.repairedThenNotRun++;\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tfor (const entry of this.deps.getSessionManager().getEntries()) {\n\t\t\tif (entry.type !== \"custom\" || entry.customType !== TOOL_ARGUMENT_VALIDATION_CUSTOM_TYPE) continue;\n\t\t\tconst record = entry.data as ToolArgumentValidationRecord | undefined;\n\t\t\tif (!record || record.version !== 1) continue;\n\t\t\tconsume(record, `legacy:${entry.id}`);\n\t\t}\n\t\tfor (const record of this.readToolArgumentValidationSidecarRecords()) {\n\t\t\tconsume(record, record.recordId);\n\t\t}\n\t\tfor (const record of this._toolArgumentValidationRecords.values()) {\n\t\t\tconsume(record, record.recordId);\n\t\t}\n\n\t\treturn stats;\n\t}\n\n\t/**\n\t * Cumulative usage (full breakdown) for this session's entire spawn subtree: its own\n\t * assistant messages PLUS every `spawned_usage` report it has rolled up. Single source of\n\t * truth for \"how much did this session and everything it spawned spend\" — used by print-mode\n\t * to emit a child's total so a spawner can roll it up via {@link addSpawnedUsage}.\n\t *\n\t * Including the `spawned_usage` reports is what keeps the single-hop invariant intact: a child\n\t * that itself spawned grandchildren must report own + sub-usage in one number, or the parent\n\t * silently under-counts the grandchildren.\n\t */\n\tgetCumulativeUsage(): Usage {\n\t\tlet input = 0;\n\t\tlet output = 0;\n\t\tlet cacheRead = 0;\n\t\tlet cacheWrite = 0;\n\t\tlet totalTokens = 0;\n\t\tlet costInput = 0;\n\t\tlet costOutput = 0;\n\t\tlet costCacheRead = 0;\n\t\tlet costCacheWrite = 0;\n\t\tlet costTotal = 0;\n\t\tconst add = (usage: Usage) => {\n\t\t\tinput += usage.input;\n\t\t\toutput += usage.output;\n\t\t\tcacheRead += usage.cacheRead;\n\t\t\tcacheWrite += usage.cacheWrite;\n\t\t\ttotalTokens += usage.totalTokens;\n\t\t\tcostInput += usage.cost.input;\n\t\t\tcostOutput += usage.cost.output;\n\t\t\tcostCacheRead += usage.cost.cacheRead;\n\t\t\tcostCacheWrite += usage.cost.cacheWrite;\n\t\t\tcostTotal += usage.cost.total;\n\t\t};\n\t\tfor (const message of this.deps.getState().messages) {\n\t\t\tif (message.role !== \"assistant\") continue;\n\t\t\tconst usage = (message as AssistantMessage).usage;\n\t\t\tif (!usage) continue;\n\t\t\tadd(usage);\n\t\t}\n\t\t// Roll up usage this session attributed to its own spawned children (single-hop).\n\t\tconst seenSpawnedReportIds = new Set<string>();\n\t\tfor (const entry of this.deps.getSessionManager().getEntries()) {\n\t\t\tif (entry.type !== \"custom\" || entry.customType !== SPAWNED_USAGE_CUSTOM_TYPE) continue;\n\t\t\tconst data = entry.data as SpawnedUsageReport | undefined;\n\t\t\tif (!data?.usage) continue;\n\t\t\tif (data.reportId) {\n\t\t\t\tif (seenSpawnedReportIds.has(data.reportId)) continue;\n\t\t\t\tseenSpawnedReportIds.add(data.reportId);\n\t\t\t}\n\t\t\tadd(data.usage);\n\t\t}\n\t\treturn {\n\t\t\tinput,\n\t\t\toutput,\n\t\t\tcacheRead,\n\t\t\tcacheWrite,\n\t\t\ttotalTokens,\n\t\t\tcost: {\n\t\t\t\tinput: costInput,\n\t\t\t\toutput: costOutput,\n\t\t\t\tcacheRead: costCacheRead,\n\t\t\t\tcacheWrite: costCacheWrite,\n\t\t\t\ttotal: costTotal,\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Record usage spent by a spawned/subagent session so the footer can roll it into the\n\t * displayed cost. Persisted as a `CustomEntry` (`customType: \"spawned_usage\"`, Model A) so\n\t * it survives reload and is reconstructed exactly like main usage; a new/forked session\n\t * starts fresh because it owns a new log file.\n\t *\n\t * Idempotent on `opts.reportId`: a re-report (retry, duplicate `agent_end`) with a\n\t * previously-seen id is ignored, so cost cannot be double-counted. Honors the single-hop\n\t * invariant documented on {@link SpawnedUsageReport}.\n\t *\n\t * @returns the id of the appended entry, or `undefined` if the report was a duplicate.\n\t */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined {\n\t\tconst reportId = opts?.reportId;\n\t\tif (reportId) {\n\t\t\tfor (const entry of this.deps.getSessionManager().getEntries()) {\n\t\t\t\tif (\n\t\t\t\t\tentry.type === \"custom\" &&\n\t\t\t\t\tentry.customType === SPAWNED_USAGE_CUSTOM_TYPE &&\n\t\t\t\t\t(entry.data as SpawnedUsageReport | undefined)?.reportId === reportId\n\t\t\t\t) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst report: SpawnedUsageReport = {\n\t\t\tusage,\n\t\t\tlabel: opts?.label,\n\t\t\tsourceSessionId: opts?.sourceSessionId,\n\t\t\treportId,\n\t\t};\n\t\treturn this.deps.getSessionManager().appendCustomEntry(SPAWNED_USAGE_CUSTOM_TYPE, report);\n\t}\n\n\t/**\n\t * Aggregate all recorded spawned-usage reports (see {@link addSpawnedUsage}). Cached by the session\n\t * entry count so the interactive footer (which calls this every render frame) is O(1) between turns\n\t * instead of an O(N) scan on every keystroke (Bug #22). Recomputes only when entries change.\n\t */\n\tgetSpawnedUsage(): SpawnedUsageTotals {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst entryCount = sessionManager.getEntryCount?.() ?? sessionManager.getEntries().length;\n\t\tif (this._spawnedUsageCache?.entryCount === entryCount) return this._spawnedUsageCache.totals;\n\t\tconst current = aggregateCurrentSessionCostsFromEntries(sessionManager.getEntries());\n\t\tconst totals: SpawnedUsageTotals = { cost: current.subagentCost, reports: current.subagentReports };\n\t\tthis._spawnedUsageCache = { entryCount, totals };\n\t\treturn totals;\n\t}\n\n\tgetCostSummary(now = new Date()): SessionCostSummary {\n\t\tconst window = getLocalDayWindow(now);\n\t\treturn createSessionCostSummary({\n\t\t\tentries: this.deps.getSessionManager().getEntries(),\n\t\t\tdailyTotals: this.getDailyUsageTotals(now),\n\t\t\ttodayWindow: window,\n\t\t});\n\t}\n\n\tgetDailyUsageTotals(now = new Date()): DailyUsageTotals {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst sessionDir = sessionManager.getSessionDir();\n\t\tconst scope = sessionManager.usesDefaultSessionDir() ? getSessionsDir() : sessionDir;\n\t\tconst nowMs = now.getTime();\n\t\tconst window = getLocalDayWindow(now);\n\t\tif (\n\t\t\tthis._dailyUsageCache?.sessionDir === scope &&\n\t\t\tthis._dailyUsageCache.windowStartMs === window.startMs &&\n\t\t\tthis._dailyUsageCache.windowEndMs === window.endMs &&\n\t\t\tthis._dailyUsageCache.expiresAt > nowMs\n\t\t) {\n\t\t\treturn this._dailyUsageCache.totals;\n\t\t}\n\t\tconst totals = sessionManager.usesDefaultSessionDir()\n\t\t\t? aggregateDailyUsageFromSessionRoot(scope, window)\n\t\t\t: aggregateDailyUsageFromSessionFiles(sessionDir, window);\n\t\tthis._dailyUsageCache = {\n\t\t\tsessionDir: scope,\n\t\t\twindowStartMs: window.startMs,\n\t\t\twindowEndMs: window.endMs,\n\t\t\texpiresAt: Math.min(nowMs + 10_000, window.endMs),\n\t\t\ttotals,\n\t\t};\n\t\treturn totals;\n\t}\n\n\tgetDailyUsageBreakdown(formatLabel?: (label: string) => string, now = new Date()): string {\n\t\treturn formatDailyUsageBreakdown(this.getDailyUsageTotals(now), formatLabel);\n\t}\n\n\tgetContextUsage(): ContextUsage | undefined {\n\t\tconst model = this.deps.getModel();\n\t\tif (!model) return undefined;\n\n\t\tconst contextWindow = model.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return undefined;\n\n\t\t// After compaction, the last assistant usage reflects pre-compaction context size.\n\t\t// We can only trust usage from an assistant that responded after the latest compaction.\n\t\t// If no such assistant exists, context token count is unknown until the next LLM response.\n\t\tconst branchEntries = this.deps.getSessionManager().getBranch();\n\t\tconst latestCompaction = getLatestCompactionEntry(branchEntries);\n\n\t\tif (latestCompaction) {\n\t\t\t// Check if there's a valid assistant usage after the compaction boundary\n\t\t\tconst compactionIndex = branchEntries.lastIndexOf(latestCompaction);\n\t\t\tlet hasPostCompactionUsage = false;\n\t\t\tfor (let i = branchEntries.length - 1; i > compactionIndex; i--) {\n\t\t\t\tconst entry = branchEntries[i];\n\t\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\t\tconst assistant = entry.message;\n\t\t\t\t\tif (assistant.stopReason !== \"aborted\" && assistant.stopReason !== \"error\") {\n\t\t\t\t\t\tconst contextTokens = calculateContextTokens(assistant.usage);\n\t\t\t\t\t\tif (contextTokens > 0) {\n\t\t\t\t\t\t\thasPostCompactionUsage = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!hasPostCompactionUsage) {\n\t\t\t\treturn { tokens: null, contextWindow, percent: null };\n\t\t\t}\n\t\t}\n\n\t\tconst estimate = estimateContextTokens(this.deps.getMessages());\n\t\tconst percent = (estimate.tokens / contextWindow) * 100;\n\n\t\treturn {\n\t\t\ttokens: estimate.tokens,\n\t\t\tcontextWindow,\n\t\t\tpercent,\n\t\t};\n\t}\n\n\t/**\n\t * Export session to HTML.\n\t * @param outputPath Optional output path (defaults to session directory)\n\t * @returns Path to exported file\n\t */\n\tasync exportToHtml(outputPath?: string): Promise<string> {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst themeName = this.deps.getSettingsManager().getTheme();\n\n\t\t// Create tool renderer if we have an extension runner (for custom tool HTML rendering)\n\t\tconst toolRenderer: ToolHtmlRenderer = createToolHtmlRenderer({\n\t\t\tgetToolDefinition: (name) => this.deps.getToolDefinition(name),\n\t\t\ttheme,\n\t\t\tcwd: sessionManager.getCwd(),\n\t\t});\n\n\t\treturn await exportSessionToHtml(sessionManager, this.deps.getState(), {\n\t\t\toutputPath,\n\t\t\tthemeName,\n\t\t\ttoolRenderer,\n\t\t});\n\t}\n\n\t/**\n\t * Export the current session branch to a JSONL file.\n\t * Writes the session header followed by all entries on the current branch path.\n\t * @param outputPath Target file path. If omitted, generates a timestamped file in cwd.\n\t * @returns The resolved output file path.\n\t */\n\texportToJsonl(outputPath?: string): string {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst filePath = resolvePath(\n\t\t\toutputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, \"-\")}.jsonl`,\n\t\t\tprocess.cwd(),\n\t\t);\n\t\tconst dir = dirname(filePath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t}\n\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: sessionManager.getSessionId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcwd: sessionManager.getCwd(),\n\t\t};\n\n\t\tconst branchEntries = sessionManager.getBranch();\n\t\tconst lines = [JSON.stringify(header)];\n\n\t\t// Re-chain parentIds to form a linear sequence\n\t\tlet prevId: string | null = null;\n\t\tfor (const entry of branchEntries) {\n\t\t\tconst linear = { ...entry, parentId: prevId };\n\t\t\tlines.push(JSON.stringify(linear));\n\t\t\tprevId = entry.id;\n\t\t}\n\n\t\twriteFileSync(filePath, `${lines.join(\"\\n\")}\\n`);\n\t\treturn filePath;\n\t}\n\n\t/**\n\t * Get text content of last assistant message.\n\t * Useful for /copy command.\n\t * @returns Text content, or undefined if no assistant message exists\n\t */\n\tgetLastAssistantText(): string | undefined {\n\t\tconst lastAssistant = this.deps\n\t\t\t.getMessages()\n\t\t\t.slice()\n\t\t\t.reverse()\n\t\t\t.find((m) => {\n\t\t\t\tif (m.role !== \"assistant\") return false;\n\t\t\t\tconst msg = m as AssistantMessage;\n\t\t\t\t// Skip aborted messages with no content\n\t\t\t\tif (msg.stopReason === \"aborted\" && msg.content.length === 0) return false;\n\t\t\t\treturn true;\n\t\t\t});\n\n\t\tif (!lastAssistant) return undefined;\n\n\t\tlet text = \"\";\n\t\tfor (const content of (lastAssistant as AssistantMessage).content) {\n\t\t\tif (content.type === \"text\") {\n\t\t\t\ttext += content.text;\n\t\t\t}\n\t\t}\n\n\t\treturn text.trim() || undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"session-analytics.d.ts","sourceRoot":"","sources":["../../src/core/session-analytics.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC1E,OAAO,EAON,KAAK,cAAc,EACnB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAEX,KAAK,EACL,4BAA4B,EAC5B,sBAAsB,EACtB,oCAAoC,EACpC,KAAK,EACL,MAAM,mBAAmB,CAAC;AAI3B,OAAO,EACN,KAAK,YAAY,EAGjB,KAAK,kBAAkB,EACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAKN,KAAK,kBAAkB,EACvB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAGN,KAAK,gBAAgB,EAGrB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC1E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAEN,KAAK,+BAA+B,EACpC,MAAM,gCAAgC,CAAC;AAQxC,eAAO,MAAM,oCAAoC,6BAA6B,CAAC;AAE/E,MAAM,WAAW,mCAAmC;IACnD,gBAAgB,EAAE,MAAM,CAAC;IACzB,eAAe,EAAE,MAAM,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IACH,oBAAoB,IAAI,MAAM,GAAG,SAAS,CAuBzC;CACD","sourcesContent":["/**\n * Session usage / cost / stats accounting, context-window usage, and session export.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Read-only over the session\n * except for its two owned memo caches (`_spawnedUsageCache`, `_dailyUsageCache`) — it never mutates\n * agent or session state. Single source of truth for \"how much did this session and its spawned\n * subtree spend\" (footer roll-up, print-mode child reporting), the daily cross-session totals, the\n * /context window estimate, and HTML/JSONL export of the current branch.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport type { AgentMessage, AgentState } from \"@caupulican/pi-agent-core\";\nimport {\n\tCURRENT_SESSION_VERSION,\n\tcalculateContextTokens,\n\testimateContextTokens,\n\tgetLatestCompactionEntry,\n\ttype SessionEntry,\n\ttype SessionHeader,\n\ttype SessionManager,\n} from \"@caupulican/pi-agent-core/node\";\nimport type {\n\tAssistantMessage,\n\tModel,\n\tToolArgumentExecutionOutcome,\n\tToolArgumentTeachState,\n\tToolArgumentValidationTelemetryEvent,\n\tUsage,\n} from \"@caupulican/pi-ai\";\nimport { getSessionsDir } from \"../config.ts\";\nimport { theme } from \"../modes/interactive/theme/theme.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport {\n\ttype SessionStats,\n\tSPAWNED_USAGE_CUSTOM_TYPE,\n\ttype SpawnedUsageReport,\n\ttype SpawnedUsageTotals,\n} from \"./agent-session.ts\";\nimport {\n\taccumulateCurrentSessionCostsFromEntries,\n\ttype CurrentSessionCostAccumulator,\n\tcreateCurrentSessionCostAccumulator,\n\tcreateSessionCostSummary,\n\ttype SessionCostSummary,\n} from \"./cost/cost-summary.ts\";\nimport {\n\taggregateDailyUsageFromSessionFiles,\n\taggregateDailyUsageFromSessionRoot,\n\ttype DailyUsageTotals,\n\tformatDailyUsageBreakdown,\n\tgetLocalDayWindow,\n} from \"./cost/daily-usage.ts\";\nimport { exportSessionToHtml, type ToolHtmlRenderer } from \"./export-html/index.ts\";\nimport { createToolHtmlRenderer } from \"./export-html/tool-renderer.ts\";\nimport type { ContextUsage, ToolDefinition } from \"./extensions/index.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport {\n\tisToolArgumentValidationLogRecord,\n\ttype ToolArgumentValidationLogRecord,\n} from \"./tool-recovery-log-records.ts\";\nimport {\n\tconsumeToolArgumentValidationRecord,\n\tcreateEmptyToolArgumentValidationStats,\n\tgetToolRecoveryRecordSequence,\n\treadPersistedToolRecoveryStats,\n} from \"./tool-recovery-stats.ts\";\n\nexport const TOOL_ARGUMENT_VALIDATION_CUSTOM_TYPE = \"tool_argument_validation\";\n\nexport interface ToolArgumentValidationTeachEfficacy {\n\trecurrenceBefore: number;\n\trecurrenceAfter: number;\n\trepairedThenSucceeded: number;\n\trepairedThenFailed: number;\n\trepairedThenNotRun: number;\n}\n\nexport interface ToolArgumentValidationStats {\n\tclean: number;\n\trepaired: number;\n\tbounced: number;\n\tfailureModes: Record<string, number>;\n\trepairsApplied: Record<string, number>;\n\ttaught: Record<ToolArgumentTeachState, number>;\n\texecutionOutcome: Record<ToolArgumentExecutionOutcome, number>;\n\tteachEfficacy: Record<string, ToolArgumentValidationTeachEfficacy>;\n}\n\nexport interface ToolArgumentValidationRecord extends ToolArgumentValidationTelemetryEvent {\n\tversion: 1;\n}\n\nexport interface SessionAnalyticsDeps {\n\t/** Live agent state — assistant-message usage and message counts are read from here. */\n\tgetState(): AgentState;\n\t/** All messages (agent state view) — used for context-window estimation and last-assistant text. */\n\tgetMessages(): AgentMessage[];\n\t/** Current session model — its context window bounds the /context estimate. */\n\tgetModel(): Model<any> | undefined;\n\t/** Session log — entries feed spawned-usage roll-up, daily totals, branch export. */\n\tgetSessionManager(): SessionManager;\n\t/** Settings — the export theme is read here. */\n\tgetSettingsManager(): SettingsManager;\n\t/** Resolve a tool definition for the HTML export's custom-tool renderer. */\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\t/** Sidecar recovery telemetry log; read on demand so turn handling never writes session custom entries. */\n\tgetToolRecoveryEventLogPath(): string;\n}\n\nexport class SessionAnalytics {\n\t/** Incremental aggregate over append-ordered session entries. */\n\tprivate _currentSessionCostCache?: {\n\t\tentryCount: number;\n\t\taccumulator: CurrentSessionCostAccumulator;\n\t};\n\t/** Memoized daily usage totals with a short TTL, keyed by the resolved scope dir and local-day window. */\n\tprivate _dailyUsageCache?: {\n\t\tsessionDir: string;\n\t\twindowStartMs: number;\n\t\twindowEndMs: number;\n\t\texpiresAt: number;\n\t\ttotals: DailyUsageTotals;\n\t};\n\t/** Memoized full cost summary. The footer renders on every streamed delta and keystroke, so\n\t * rescanning a long session log there turns redraw into O(entries) work per frame. */\n\tprivate _costSummaryCache?: {\n\t\tentryCount: number;\n\t\tdailyTotals: DailyUsageTotals;\n\t\twindowStartMs: number;\n\t\twindowEndMs: number;\n\t\tsummary: SessionCostSummary;\n\t};\n\t/** Cumulative stats initialized once from persisted telemetry, then updated without retaining record details. */\n\tprivate _toolArgumentValidationStats: ToolArgumentValidationStats | undefined;\n\t/** Incremental context-usage state keyed by the append-only branch leaf. */\n\tprivate _postCompactionUsageCache?: {\n\t\tleafId: string | null;\n\t\thasCompaction: boolean;\n\t\thasPostCompactionUsage: boolean;\n\t};\n\n\tprivate readonly deps: SessionAnalyticsDeps;\n\n\tconstructor(deps: SessionAnalyticsDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tgetSessionStats(): SessionStats {\n\t\tconst state = this.deps.getState();\n\t\tconst userMessages = state.messages.filter((m) => m.role === \"user\").length;\n\t\tconst assistantMessages = state.messages.filter((m) => m.role === \"assistant\").length;\n\t\tconst toolResults = state.messages.filter((m) => m.role === \"toolResult\").length;\n\n\t\tlet toolCalls = 0;\n\t\tlet totalInput = 0;\n\t\tlet totalOutput = 0;\n\t\tlet totalCacheRead = 0;\n\t\tlet totalCacheWrite = 0;\n\t\tlet totalCost = 0;\n\n\t\tfor (const message of state.messages) {\n\t\t\tif (message.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = message as AssistantMessage;\n\t\t\t\ttoolCalls += assistantMsg.content.filter((c) => c.type === \"toolCall\").length;\n\t\t\t\ttotalInput += assistantMsg.usage.input;\n\t\t\t\ttotalOutput += assistantMsg.usage.output;\n\t\t\t\ttotalCacheRead += assistantMsg.usage.cacheRead;\n\t\t\t\ttotalCacheWrite += assistantMsg.usage.cacheWrite;\n\t\t\t\ttotalCost += assistantMsg.usage.cost.total;\n\t\t\t}\n\t\t}\n\n\t\tconst toolArgumentValidation = this.getToolArgumentValidationStats();\n\t\tconst compactionGates = this.getCompactionGateStats();\n\n\t\treturn {\n\t\t\tsessionFile: this.deps.getSessionManager().getSessionFile(),\n\t\t\tsessionId: this.deps.getSessionManager().getSessionId(),\n\t\t\tuserMessages,\n\t\t\tassistantMessages,\n\t\t\ttoolCalls,\n\t\t\ttoolResults,\n\t\t\ttotalMessages: state.messages.length,\n\t\t\ttokens: {\n\t\t\t\tinput: totalInput,\n\t\t\t\toutput: totalOutput,\n\t\t\t\tcacheRead: totalCacheRead,\n\t\t\t\tcacheWrite: totalCacheWrite,\n\t\t\t\ttotal: totalInput + totalOutput + totalCacheRead + totalCacheWrite,\n\t\t\t},\n\t\t\tcost: totalCost,\n\t\t\tcontextUsage: this.getContextUsage(),\n\t\t\ttoolArgumentValidation,\n\t\t\tcompactionGates,\n\t\t};\n\t}\n\n\tgetCompactionGateStats(): SessionStats[\"compactionGates\"] {\n\t\tlet gateFailures = 0;\n\t\tlet deterministicGapFills = 0;\n\t\tlet compactionsWithGateFailures = 0;\n\t\tfor (const entry of this.deps.getSessionManager().getEntries()) {\n\t\t\tif (entry.type !== \"compaction\") continue;\n\t\t\tconst details = entry.details;\n\t\t\tif (!details || typeof details !== \"object\") continue;\n\t\t\tconst rawGateFailures = (details as { verificationGateFailures?: unknown }).verificationGateFailures;\n\t\t\tconst rawGapFills = (details as { deterministicGapFills?: unknown }).deterministicGapFills;\n\t\t\tconst entryGateFailures =\n\t\t\t\ttypeof rawGateFailures === \"number\" && Number.isFinite(rawGateFailures) ? rawGateFailures : 0;\n\t\t\tconst entryGapFills = typeof rawGapFills === \"number\" && Number.isFinite(rawGapFills) ? rawGapFills : 0;\n\t\t\tgateFailures += entryGateFailures;\n\t\t\tdeterministicGapFills += entryGapFills;\n\t\t\tif (entryGateFailures > 0) compactionsWithGateFailures++;\n\t\t}\n\t\treturn { gateFailures, deterministicGapFills, compactionsWithGateFailures };\n\t}\n\n\trecordToolArgumentValidation(record: ToolArgumentValidationLogRecord): void {\n\t\tconst stats = this.getToolArgumentValidationStats();\n\t\tconsumeToolArgumentValidationRecord(stats, record);\n\t\tthis._toolArgumentValidationStats = stats;\n\t}\n\n\tprivate readToolArgumentValidationSidecarRecords(): ToolArgumentValidationLogRecord[] {\n\t\tconst filePath = this.deps.getToolRecoveryEventLogPath();\n\t\tif (!existsSync(filePath)) return [];\n\t\tconst records: ToolArgumentValidationLogRecord[] = [];\n\t\ttry {\n\t\t\tconst sessionId = this.deps.getSessionManager().getSessionId();\n\t\t\tfor (const line of readFileSync(filePath, \"utf-8\").split(\"\\n\")) {\n\t\t\t\tif (line.trim().length === 0) continue;\n\t\t\t\tconst parsed = JSON.parse(line) as unknown;\n\t\t\t\tif (!isToolArgumentValidationLogRecord(parsed) || parsed.sessionId !== sessionId) continue;\n\t\t\t\trecords.push(parsed);\n\t\t\t}\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t\treturn records;\n\t}\n\n\tgetToolArgumentValidationStats(): ToolArgumentValidationStats {\n\t\tif (this._toolArgumentValidationStats) return structuredClone(this._toolArgumentValidationStats);\n\t\tconst eventLogPath = this.deps.getToolRecoveryEventLogPath();\n\t\tconst sessionId = this.deps.getSessionManager().getSessionId();\n\t\tconst persisted = readPersistedToolRecoveryStats(eventLogPath, sessionId);\n\t\tconst stats = persisted ? structuredClone(persisted.stats) : createEmptyToolArgumentValidationStats();\n\t\tconst seen = new Set<string>();\n\t\tconst consume = (record: ToolArgumentValidationRecord, key: string): void => {\n\t\t\tif (seen.has(key)) return;\n\t\t\tseen.add(key);\n\t\t\tconsumeToolArgumentValidationRecord(stats, record);\n\t\t};\n\n\t\tfor (const entry of this.deps.getSessionManager().getEntries()) {\n\t\t\tif (entry.type !== \"custom\" || entry.customType !== TOOL_ARGUMENT_VALIDATION_CUSTOM_TYPE) continue;\n\t\t\tconst record = entry.data as ToolArgumentValidationRecord | undefined;\n\t\t\tif (!record || record.version !== 1) continue;\n\t\t\tconsume(record, `legacy:${entry.id}`);\n\t\t}\n\t\tfor (const record of this.readToolArgumentValidationSidecarRecords()) {\n\t\t\tif (\n\t\t\t\tpersisted &&\n\t\t\t\trecord.sessionId === sessionId &&\n\t\t\t\tgetToolRecoveryRecordSequence(record) <= persisted.lastRecordSequence\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconsume(record, record.recordId);\n\t\t}\n\n\t\tthis._toolArgumentValidationStats = stats;\n\t\treturn structuredClone(stats);\n\t}\n\n\t/**\n\t * Cumulative usage (full breakdown) for this session's entire spawn subtree: its own\n\t * assistant messages PLUS every `spawned_usage` report it has rolled up. Single source of\n\t * truth for \"how much did this session and everything it spawned spend\" — used by print-mode\n\t * to emit a child's total so a spawner can roll it up via {@link addSpawnedUsage}.\n\t *\n\t * Including the `spawned_usage` reports is what keeps the single-hop invariant intact: a child\n\t * that itself spawned grandchildren must report own + sub-usage in one number, or the parent\n\t * silently under-counts the grandchildren.\n\t */\n\tgetCumulativeUsage(): Usage {\n\t\tlet input = 0;\n\t\tlet output = 0;\n\t\tlet cacheRead = 0;\n\t\tlet cacheWrite = 0;\n\t\tlet totalTokens = 0;\n\t\tlet costInput = 0;\n\t\tlet costOutput = 0;\n\t\tlet costCacheRead = 0;\n\t\tlet costCacheWrite = 0;\n\t\tlet costTotal = 0;\n\t\tconst add = (usage: Usage) => {\n\t\t\tinput += usage.input;\n\t\t\toutput += usage.output;\n\t\t\tcacheRead += usage.cacheRead;\n\t\t\tcacheWrite += usage.cacheWrite;\n\t\t\ttotalTokens += usage.totalTokens;\n\t\t\tcostInput += usage.cost.input;\n\t\t\tcostOutput += usage.cost.output;\n\t\t\tcostCacheRead += usage.cost.cacheRead;\n\t\t\tcostCacheWrite += usage.cost.cacheWrite;\n\t\t\tcostTotal += usage.cost.total;\n\t\t};\n\t\tfor (const message of this.deps.getState().messages) {\n\t\t\tif (message.role !== \"assistant\") continue;\n\t\t\tconst usage = (message as AssistantMessage).usage;\n\t\t\tif (!usage) continue;\n\t\t\tadd(usage);\n\t\t}\n\t\t// Roll up usage this session attributed to its own spawned children (single-hop).\n\t\tconst seenSpawnedReportIds = new Set<string>();\n\t\tfor (const entry of this.deps.getSessionManager().getEntries()) {\n\t\t\tif (entry.type !== \"custom\" || entry.customType !== SPAWNED_USAGE_CUSTOM_TYPE) continue;\n\t\t\tconst data = entry.data as SpawnedUsageReport | undefined;\n\t\t\tif (!data?.usage) continue;\n\t\t\tif (data.reportId) {\n\t\t\t\tif (seenSpawnedReportIds.has(data.reportId)) continue;\n\t\t\t\tseenSpawnedReportIds.add(data.reportId);\n\t\t\t}\n\t\t\tadd(data.usage);\n\t\t}\n\t\treturn {\n\t\t\tinput,\n\t\t\toutput,\n\t\t\tcacheRead,\n\t\t\tcacheWrite,\n\t\t\ttotalTokens,\n\t\t\tcost: {\n\t\t\t\tinput: costInput,\n\t\t\t\toutput: costOutput,\n\t\t\t\tcacheRead: costCacheRead,\n\t\t\t\tcacheWrite: costCacheWrite,\n\t\t\t\ttotal: costTotal,\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * Record usage spent by a spawned/subagent session so the footer can roll it into the\n\t * displayed cost. Persisted as a `CustomEntry` (`customType: \"spawned_usage\"`, Model A) so\n\t * it survives reload and is reconstructed exactly like main usage; a new/forked session\n\t * starts fresh because it owns a new log file.\n\t *\n\t * Idempotent on `opts.reportId`: a re-report (retry, duplicate `agent_end`) with a\n\t * previously-seen id is ignored, so cost cannot be double-counted. Honors the single-hop\n\t * invariant documented on {@link SpawnedUsageReport}.\n\t *\n\t * @returns the id of the appended entry, or `undefined` if the report was a duplicate.\n\t */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined {\n\t\tconst reportId = opts?.reportId;\n\t\tif (reportId && this.getCurrentSessionCostTotals().seenSubagentReportIds.has(reportId)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst report: SpawnedUsageReport = {\n\t\t\tusage,\n\t\t\tlabel: opts?.label,\n\t\t\tsourceSessionId: opts?.sourceSessionId,\n\t\t\treportId,\n\t\t};\n\t\tconst entryId = this.deps.getSessionManager().appendCustomEntry(SPAWNED_USAGE_CUSTOM_TYPE, report);\n\t\tif (reportId) this.getCurrentSessionCostTotals();\n\t\treturn entryId;\n\t}\n\n\tprivate getCurrentSessionCostTotals(): CurrentSessionCostAccumulator {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst entryCount = sessionManager.getEntryCount?.() ?? sessionManager.getEntries().length;\n\t\tlet cache = this._currentSessionCostCache;\n\t\tconst getEntriesSince = sessionManager.getEntriesSince?.bind(sessionManager);\n\t\tif (!cache || entryCount < cache.entryCount || !getEntriesSince) {\n\t\t\tcache = {\n\t\t\t\tentryCount,\n\t\t\t\taccumulator: accumulateCurrentSessionCostsFromEntries(\n\t\t\t\t\tcreateCurrentSessionCostAccumulator(),\n\t\t\t\t\tsessionManager.getEntries(),\n\t\t\t\t),\n\t\t\t};\n\t\t\tthis._currentSessionCostCache = cache;\n\t\t} else if (entryCount > cache.entryCount) {\n\t\t\taccumulateCurrentSessionCostsFromEntries(cache.accumulator, getEntriesSince(cache.entryCount));\n\t\t\tcache.entryCount = entryCount;\n\t\t}\n\t\treturn cache.accumulator;\n\t}\n\n\t/**\n\t * Aggregate all recorded spawned-usage reports (see {@link addSpawnedUsage}). The append-ordered\n\t * accumulator processes only new entries, so repeated turns do not rescan the full session.\n\t */\n\tgetSpawnedUsage(): SpawnedUsageTotals {\n\t\tconst current = this.getCurrentSessionCostTotals();\n\t\treturn { cost: current.subagentCost, reports: current.subagentReports };\n\t}\n\n\tgetCostSummary(now = new Date()): SessionCostSummary {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst entryCount = sessionManager.getEntryCount?.() ?? sessionManager.getEntries().length;\n\t\tconst window = getLocalDayWindow(now);\n\t\tconst dailyTotals = this.getDailyUsageTotals(now);\n\t\tconst cached = this._costSummaryCache;\n\t\tif (\n\t\t\tcached?.entryCount === entryCount &&\n\t\t\tcached.dailyTotals === dailyTotals &&\n\t\t\tcached.windowStartMs === window.startMs &&\n\t\t\tcached.windowEndMs === window.endMs\n\t\t) {\n\t\t\treturn cached.summary;\n\t\t}\n\t\tconst summary = createSessionCostSummary({\n\t\t\tcurrentTotals: this.getCurrentSessionCostTotals(),\n\t\t\tdailyTotals,\n\t\t\ttodayWindow: window,\n\t\t});\n\t\tthis._costSummaryCache = {\n\t\t\tentryCount,\n\t\t\tdailyTotals,\n\t\t\twindowStartMs: window.startMs,\n\t\t\twindowEndMs: window.endMs,\n\t\t\tsummary,\n\t\t};\n\t\treturn summary;\n\t}\n\n\tgetDailyUsageTotals(now = new Date()): DailyUsageTotals {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst sessionDir = sessionManager.getSessionDir();\n\t\tconst scope = sessionManager.usesDefaultSessionDir() ? getSessionsDir() : sessionDir;\n\t\tconst nowMs = now.getTime();\n\t\tconst window = getLocalDayWindow(now);\n\t\tif (\n\t\t\tthis._dailyUsageCache?.sessionDir === scope &&\n\t\t\tthis._dailyUsageCache.windowStartMs === window.startMs &&\n\t\t\tthis._dailyUsageCache.windowEndMs === window.endMs &&\n\t\t\tthis._dailyUsageCache.expiresAt > nowMs\n\t\t) {\n\t\t\treturn this._dailyUsageCache.totals;\n\t\t}\n\t\tconst sessionFile = sessionManager.getSessionFile();\n\t\tconst liveSession = sessionFile ? { filePath: sessionFile, entries: sessionManager.getEntries() } : undefined;\n\t\tconst totals = sessionManager.usesDefaultSessionDir()\n\t\t\t? aggregateDailyUsageFromSessionRoot(scope, window, liveSession)\n\t\t\t: aggregateDailyUsageFromSessionFiles(sessionDir, window, liveSession);\n\t\tthis._dailyUsageCache = {\n\t\t\tsessionDir: scope,\n\t\t\twindowStartMs: window.startMs,\n\t\t\twindowEndMs: window.endMs,\n\t\t\texpiresAt: Math.min(nowMs + 10_000, window.endMs),\n\t\t\ttotals,\n\t\t};\n\t\treturn totals;\n\t}\n\n\tgetDailyUsageBreakdown(formatLabel?: (label: string) => string, now = new Date()): string {\n\t\treturn formatDailyUsageBreakdown(this.getDailyUsageTotals(now), formatLabel);\n\t}\n\n\tprivate getPostCompactionUsageState(): { hasCompaction: boolean; hasPostCompactionUsage: boolean } {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst indexedSessionManager = sessionManager as unknown as {\n\t\t\tgetLeafId?: () => string | null;\n\t\t\tgetEntry?: (id: string) => SessionEntry | undefined;\n\t\t};\n\t\tconst getLeafId = indexedSessionManager.getLeafId?.bind(sessionManager);\n\t\tconst getEntry = indexedSessionManager.getEntry?.bind(sessionManager);\n\t\tconst leafId = getLeafId?.();\n\t\tif (getLeafId && getEntry && leafId !== undefined) {\n\t\t\tif (this._postCompactionUsageCache?.leafId === leafId) {\n\t\t\t\treturn { ...this._postCompactionUsageCache };\n\t\t\t}\n\t\t\tconst appended: SessionEntry[] = [];\n\t\t\tconst cachedLeafId = this._postCompactionUsageCache?.leafId;\n\t\t\tlet currentId = leafId;\n\t\t\tconst seen = new Set<string>();\n\t\t\twhile (currentId !== null && currentId !== cachedLeafId && !seen.has(currentId)) {\n\t\t\t\tseen.add(currentId);\n\t\t\t\tconst entry = getEntry(currentId);\n\t\t\t\tif (!entry) break;\n\t\t\t\tappended.push(entry);\n\t\t\t\tcurrentId = entry.parentId;\n\t\t\t}\n\t\t\tconst extendsCachedBranch = this._postCompactionUsageCache !== undefined && currentId === cachedLeafId;\n\t\t\tconst state = extendsCachedBranch\n\t\t\t\t? { ...this._postCompactionUsageCache! }\n\t\t\t\t: { leafId: null, hasCompaction: false, hasPostCompactionUsage: false };\n\t\t\tif (!extendsCachedBranch && currentId !== null) {\n\t\t\t\twhile (currentId !== null && !seen.has(currentId)) {\n\t\t\t\t\tseen.add(currentId);\n\t\t\t\t\tconst entry = getEntry(currentId);\n\t\t\t\t\tif (!entry) break;\n\t\t\t\t\tappended.push(entry);\n\t\t\t\t\tcurrentId = entry.parentId;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (let index = appended.length - 1; index >= 0; index--) {\n\t\t\t\tconst entry = appended[index];\n\t\t\t\tif (entry.type === \"compaction\") {\n\t\t\t\t\tstate.hasCompaction = true;\n\t\t\t\t\tstate.hasPostCompactionUsage = false;\n\t\t\t\t} else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\t\tconst assistant = entry.message;\n\t\t\t\t\tif (assistant.stopReason !== \"aborted\" && assistant.stopReason !== \"error\" && state.hasCompaction) {\n\t\t\t\t\t\tstate.hasPostCompactionUsage = calculateContextTokens(assistant.usage) > 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tstate.leafId = leafId;\n\t\t\tthis._postCompactionUsageCache = state;\n\t\t\treturn { ...state };\n\t\t}\n\n\t\tconst branchEntries = sessionManager.getBranch();\n\t\tconst latestCompaction = getLatestCompactionEntry(branchEntries);\n\t\tif (!latestCompaction) return { hasCompaction: false, hasPostCompactionUsage: false };\n\t\tconst compactionIndex = branchEntries.lastIndexOf(latestCompaction);\n\t\tfor (let index = branchEntries.length - 1; index > compactionIndex; index--) {\n\t\t\tconst entry = branchEntries[index];\n\t\t\tif (entry.type !== \"message\" || entry.message.role !== \"assistant\") continue;\n\t\t\tconst assistant = entry.message;\n\t\t\tif (assistant.stopReason === \"aborted\" || assistant.stopReason === \"error\") continue;\n\t\t\treturn { hasCompaction: true, hasPostCompactionUsage: calculateContextTokens(assistant.usage) > 0 };\n\t\t}\n\t\treturn { hasCompaction: true, hasPostCompactionUsage: false };\n\t}\n\n\tgetContextUsage(): ContextUsage | undefined {\n\t\tconst model = this.deps.getModel();\n\t\tif (!model) return undefined;\n\n\t\tconst contextWindow = model.contextWindow ?? 0;\n\t\tif (contextWindow <= 0) return undefined;\n\n\t\t// After compaction, the last assistant usage reflects pre-compaction context size.\n\t\t// Walk backward only to the nearest compaction instead of rebuilding the whole branch on\n\t\t// every footer invalidation; the distance is bounded by the live post-compaction context.\n\t\tconst compactionState = this.getPostCompactionUsageState();\n\t\tif (compactionState.hasCompaction && !compactionState.hasPostCompactionUsage) {\n\t\t\treturn { tokens: null, contextWindow, percent: null };\n\t\t}\n\n\t\tconst estimate = estimateContextTokens(this.deps.getMessages());\n\t\tconst percent = (estimate.tokens / contextWindow) * 100;\n\n\t\treturn {\n\t\t\ttokens: estimate.tokens,\n\t\t\tcontextWindow,\n\t\t\tpercent,\n\t\t};\n\t}\n\n\t/**\n\t * Export session to HTML.\n\t * @param outputPath Optional output path (defaults to session directory)\n\t * @returns Path to exported file\n\t */\n\tasync exportToHtml(outputPath?: string): Promise<string> {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst themeName = this.deps.getSettingsManager().getTheme();\n\n\t\t// Create tool renderer if we have an extension runner (for custom tool HTML rendering)\n\t\tconst toolRenderer: ToolHtmlRenderer = createToolHtmlRenderer({\n\t\t\tgetToolDefinition: (name) => this.deps.getToolDefinition(name),\n\t\t\ttheme,\n\t\t\tcwd: sessionManager.getCwd(),\n\t\t});\n\n\t\treturn await exportSessionToHtml(sessionManager, this.deps.getState(), {\n\t\t\toutputPath,\n\t\t\tthemeName,\n\t\t\ttoolRenderer,\n\t\t});\n\t}\n\n\t/**\n\t * Export the current session branch to a JSONL file.\n\t * Writes the session header followed by all entries on the current branch path.\n\t * @param outputPath Target file path. If omitted, generates a timestamped file in cwd.\n\t * @returns The resolved output file path.\n\t */\n\texportToJsonl(outputPath?: string): string {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst filePath = resolvePath(\n\t\t\toutputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, \"-\")}.jsonl`,\n\t\t\tprocess.cwd(),\n\t\t);\n\t\tconst dir = dirname(filePath);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t}\n\n\t\tconst header: SessionHeader = {\n\t\t\ttype: \"session\",\n\t\t\tversion: CURRENT_SESSION_VERSION,\n\t\t\tid: sessionManager.getSessionId(),\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcwd: sessionManager.getCwd(),\n\t\t};\n\n\t\tconst branchEntries = sessionManager.getBranch();\n\t\tconst lines = [JSON.stringify(header)];\n\n\t\t// Re-chain parentIds to form a linear sequence\n\t\tlet prevId: string | null = null;\n\t\tfor (const entry of branchEntries) {\n\t\t\tconst linear = { ...entry, parentId: prevId };\n\t\t\tlines.push(JSON.stringify(linear));\n\t\t\tprevId = entry.id;\n\t\t}\n\n\t\twriteFileSync(filePath, `${lines.join(\"\\n\")}\\n`);\n\t\treturn filePath;\n\t}\n\n\t/**\n\t * Get text content of last assistant message.\n\t * Useful for /copy command.\n\t * @returns Text content, or undefined if no assistant message exists\n\t */\n\tgetLastAssistantText(): string | undefined {\n\t\tconst lastAssistant = this.deps\n\t\t\t.getMessages()\n\t\t\t.slice()\n\t\t\t.reverse()\n\t\t\t.find((m) => {\n\t\t\t\tif (m.role !== \"assistant\") return false;\n\t\t\t\tconst msg = m as AssistantMessage;\n\t\t\t\t// Skip aborted messages with no content\n\t\t\t\tif (msg.stopReason === \"aborted\" && msg.content.length === 0) return false;\n\t\t\t\treturn true;\n\t\t\t});\n\n\t\tif (!lastAssistant) return undefined;\n\n\t\tlet text = \"\";\n\t\tfor (const content of (lastAssistant as AssistantMessage).content) {\n\t\t\tif (content.type === \"text\") {\n\t\t\t\ttext += content.text;\n\t\t\t}\n\t\t}\n\n\t\treturn text.trim() || undefined;\n\t}\n}\n"]}