@oyasmi/pipiclaw 0.9.3 → 0.9.4-beta.2

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 (336) hide show
  1. package/dist/agent/builtin-commands.d.ts +19 -0
  2. package/dist/agent/builtin-commands.js +80 -0
  3. package/dist/agent/channel-runner.d.ts +20 -208
  4. package/dist/agent/channel-runner.js +167 -1188
  5. package/dist/agent/maintenance-context.d.ts +1 -1
  6. package/dist/agent/maintenance-context.js +1 -1
  7. package/dist/agent/prompt/manifest.d.ts +6 -1
  8. package/dist/agent/prompt/manifest.js +45 -64
  9. package/dist/agent/prompt/resources.d.ts +3 -0
  10. package/dist/agent/prompt/resources.js +11 -2
  11. package/dist/agent/runner-factory.d.ts +1 -43
  12. package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
  13. package/dist/agent/{command-extension.js → session/command-extension.js} +48 -35
  14. package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
  15. package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
  16. package/dist/agent/session/model-selection.d.ts +47 -0
  17. package/dist/agent/session/model-selection.js +99 -0
  18. package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
  19. package/dist/agent/session/session-adapter.js +159 -0
  20. package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
  21. package/dist/agent/{session-events.js → session/session-events.js} +24 -13
  22. package/dist/agent/session/session-host.d.ts +200 -0
  23. package/dist/agent/session/session-host.js +621 -0
  24. package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +5 -3
  25. package/dist/agent/status-render.d.ts +0 -1
  26. package/dist/agent/status-render.js +4 -16
  27. package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
  28. package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
  29. package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
  30. package/dist/agent/{run-queue.js → turn/run-queue.js} +10 -5
  31. package/dist/{memory → agent/turn}/task-digest.js +4 -4
  32. package/dist/agent/turn/turn-context.d.ts +14 -0
  33. package/dist/agent/turn/turn-context.js +64 -0
  34. package/dist/agent/turn/turn-error.d.ts +31 -0
  35. package/dist/agent/turn/turn-error.js +68 -0
  36. package/dist/agent/turn/turn-finish.d.ts +50 -0
  37. package/dist/agent/turn/turn-finish.js +188 -0
  38. package/dist/agent/turn/turn-input.d.ts +43 -0
  39. package/dist/agent/turn/turn-input.js +79 -0
  40. package/dist/agent/turn/turn-pipeline.d.ts +68 -0
  41. package/dist/agent/turn/turn-pipeline.js +257 -0
  42. package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
  43. package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
  44. package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
  45. package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
  46. package/dist/agent/types.d.ts +43 -2
  47. package/dist/agent/types.js +1 -1
  48. package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
  49. package/dist/{models/auth-cli.js → app/auth-command.js} +14 -10
  50. package/dist/{runtime/app-home.d.ts → app/home.d.ts} +6 -2
  51. package/dist/{runtime/app-home.js → app/home.js} +22 -75
  52. package/dist/{runtime → app}/proxy.js +4 -2
  53. package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
  54. package/dist/{app-services.js → app/services.js} +17 -14
  55. package/dist/channel/channel-context.d.ts +12 -2
  56. package/dist/channel/channel-context.js +29 -2
  57. package/dist/channel/channel-event.d.ts +10 -2
  58. package/dist/channel/channel-event.js +1 -1
  59. package/dist/channel/channel-index.js +4 -1
  60. package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
  61. package/dist/{runtime/project-commands.js → channel/commands.js} +17 -16
  62. package/dist/channel/project-scope-store.js +1 -1
  63. package/dist/channel/store.js +4 -0
  64. package/dist/commands/catalog.d.ts +24 -7
  65. package/dist/commands/catalog.js +91 -44
  66. package/dist/commands/reply-limits.d.ts +6 -0
  67. package/dist/commands/reply-limits.js +24 -0
  68. package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
  69. package/dist/{runtime/report-commands.js → commands/router.js} +6 -6
  70. package/dist/{settings.d.ts → config/settings.d.ts} +10 -10
  71. package/dist/{settings.js → config/settings.js} +11 -11
  72. package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
  73. package/dist/{tools/config.js → config/tools.js} +5 -2
  74. package/dist/dingtalk/access-token.d.ts +12 -0
  75. package/dist/dingtalk/access-token.js +51 -0
  76. package/dist/dingtalk/api.d.ts +19 -0
  77. package/dist/dingtalk/api.js +67 -0
  78. package/dist/dingtalk/bot.d.ts +97 -0
  79. package/dist/dingtalk/bot.js +389 -0
  80. package/dist/dingtalk/cards.d.ts +56 -0
  81. package/dist/dingtalk/cards.js +318 -0
  82. package/dist/{runtime → dingtalk}/channel-queue.js +4 -1
  83. package/dist/dingtalk/config.d.ts +19 -0
  84. package/dist/dingtalk/config.js +95 -0
  85. package/dist/dingtalk/connection.d.ts +57 -0
  86. package/dist/dingtalk/connection.js +356 -0
  87. package/dist/dingtalk/conversation-meta.d.ts +16 -0
  88. package/dist/dingtalk/conversation-meta.js +77 -0
  89. package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
  90. package/dist/{runtime → dingtalk}/delivery.js +29 -15
  91. package/dist/dingtalk/handler.d.ts +90 -0
  92. package/dist/dingtalk/handler.js +1 -0
  93. package/dist/dingtalk/inbound.d.ts +66 -0
  94. package/dist/dingtalk/inbound.js +137 -0
  95. package/dist/dingtalk/media.d.ts +66 -0
  96. package/dist/dingtalk/media.js +214 -0
  97. package/dist/events/{event-commands.js → commands.js} +99 -45
  98. package/dist/events/parse.d.ts +14 -0
  99. package/dist/events/parse.js +114 -0
  100. package/dist/events/types.d.ts +93 -0
  101. package/dist/events/types.js +1 -0
  102. package/dist/events/{event-validation.d.ts → validation.d.ts} +14 -3
  103. package/dist/events/{event-validation.js → validation.js} +17 -9
  104. package/dist/events/watcher.d.ts +67 -0
  105. package/dist/events/{events.js → watcher.js} +63 -121
  106. package/dist/executor.js +2 -2
  107. package/dist/index.d.ts +6 -4
  108. package/dist/index.js +2 -2
  109. package/dist/jobs/launch.d.ts +42 -0
  110. package/dist/jobs/launch.js +118 -0
  111. package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
  112. package/dist/{agent/job-manager.js → jobs/manager.js} +34 -157
  113. package/dist/jobs/record.d.ts +55 -0
  114. package/dist/jobs/record.js +36 -0
  115. package/dist/log.d.ts +12 -2
  116. package/dist/log.js +26 -34
  117. package/dist/main.js +3 -3
  118. package/dist/memory/commands.js +29 -23
  119. package/dist/memory/lifecycle.js +26 -5
  120. package/dist/memory/maintenance-gates.d.ts +2 -2
  121. package/dist/memory/maintenance-state.js +4 -1
  122. package/dist/memory/maintenance-tuning.d.ts +15 -0
  123. package/dist/memory/maintenance-tuning.js +3 -0
  124. package/dist/memory/reflect-job.d.ts +2 -2
  125. package/dist/memory/reflect-job.js +4 -2
  126. package/dist/memory/scheduler.d.ts +3 -3
  127. package/dist/memory/scheduler.js +5 -2
  128. package/dist/memory/sidecar-worker.js +1 -1
  129. package/dist/memory/transcript.js +1 -1
  130. package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
  131. package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
  132. package/dist/models/login-identity.d.ts +2 -0
  133. package/dist/models/login-identity.js +83 -0
  134. package/dist/models/provider-login.d.ts +3 -1
  135. package/dist/models/provider-login.js +8 -2
  136. package/dist/models/reference.d.ts +20 -0
  137. package/dist/models/{utils.js → reference.js} +0 -48
  138. package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
  139. package/dist/models/runtime.js +52 -0
  140. package/dist/paths.d.ts +2 -0
  141. package/dist/paths.js +9 -0
  142. package/dist/playbooks/agent-delegation.md +2 -2
  143. package/dist/playbooks/catalog.d.ts +6 -2
  144. package/dist/playbooks/catalog.js +9 -6
  145. package/dist/runtime/bootstrap.d.ts +7 -17
  146. package/dist/runtime/bootstrap.js +70 -659
  147. package/dist/runtime/durable-dispatch.d.ts +43 -4
  148. package/dist/runtime/durable-dispatch.js +153 -3
  149. package/dist/runtime/inbound-images.d.ts +18 -0
  150. package/dist/runtime/inbound-images.js +51 -0
  151. package/dist/runtime/shutdown.d.ts +39 -0
  152. package/dist/runtime/shutdown.js +120 -0
  153. package/dist/runtime/stop-watchdog.d.ts +16 -0
  154. package/dist/runtime/stop-watchdog.js +32 -0
  155. package/dist/runtime/task-driver.d.ts +6 -4
  156. package/dist/runtime/task-driver.js +58 -23
  157. package/dist/runtime/task-migration.js +25 -8
  158. package/dist/runtime/task-spawn.d.ts +1 -1
  159. package/dist/runtime/task-spawn.js +13 -6
  160. package/dist/runtime/turn-handler.d.ts +47 -0
  161. package/dist/runtime/turn-handler.js +318 -0
  162. package/dist/runtime/turn-run.d.ts +52 -0
  163. package/dist/runtime/turn-run.js +318 -0
  164. package/dist/runtime/wake-coalescing.d.ts +18 -0
  165. package/dist/runtime/wake-coalescing.js +29 -0
  166. package/dist/security/block-message.d.ts +22 -1
  167. package/dist/security/block-message.js +66 -1
  168. package/dist/security/command-guard.js +4 -0
  169. package/dist/security/network.d.ts +2 -1
  170. package/dist/security/network.js +7 -2
  171. package/dist/security/path-guard-check.js +2 -2
  172. package/dist/security/path-guard.js +4 -0
  173. package/dist/security/types.d.ts +1 -2
  174. package/dist/security/types.js +1 -2
  175. package/dist/shared/exact-keys.d.ts +1 -1
  176. package/dist/shared/format.d.ts +12 -0
  177. package/dist/shared/format.js +37 -0
  178. package/dist/shared/host-process.js +16 -4
  179. package/dist/shared/wake-claim.d.ts +1 -1
  180. package/dist/shared/with-timeout.d.ts +3 -2
  181. package/dist/shared/with-timeout.js +14 -3
  182. package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
  183. package/dist/{runtime/skill-commands.js → skills/commands.js} +18 -11
  184. package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
  185. package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
  186. package/dist/skills/workspace.d.ts +33 -0
  187. package/dist/skills/workspace.js +116 -0
  188. package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +9 -7
  189. package/dist/{runtime/subagent-commands.js → subagents/commands.js} +116 -77
  190. package/dist/subagents/completion-wake.d.ts +17 -0
  191. package/dist/subagents/completion-wake.js +76 -0
  192. package/dist/subagents/detached-discovery.js +1 -1
  193. package/dist/subagents/discovery.d.ts +1 -1
  194. package/dist/subagents/discovery.js +2 -2
  195. package/dist/subagents/dispatch.d.ts +33 -0
  196. package/dist/subagents/dispatch.js +190 -0
  197. package/dist/subagents/external/claude-code.js +23 -1
  198. package/dist/subagents/external/dispatch.d.ts +25 -0
  199. package/dist/subagents/external/dispatch.js +90 -0
  200. package/dist/subagents/external/harness.d.ts +1 -1
  201. package/dist/subagents/external/progress-tail.d.ts +18 -1
  202. package/dist/subagents/external/progress-tail.js +64 -17
  203. package/dist/subagents/external/run.d.ts +5 -1
  204. package/dist/subagents/external/run.js +23 -9
  205. package/dist/subagents/external/settlement.d.ts +4 -1
  206. package/dist/subagents/external/settlement.js +1 -1
  207. package/dist/subagents/format.d.ts +1 -1
  208. package/dist/subagents/grace.d.ts +24 -0
  209. package/dist/subagents/grace.js +57 -0
  210. package/dist/subagents/internal/outcome.d.ts +24 -0
  211. package/dist/subagents/internal/outcome.js +149 -0
  212. package/dist/subagents/internal/provider-retry.d.ts +19 -0
  213. package/dist/subagents/internal/provider-retry.js +83 -0
  214. package/dist/subagents/internal/run.d.ts +31 -0
  215. package/dist/subagents/internal/run.js +240 -0
  216. package/dist/subagents/internal/state.d.ts +43 -0
  217. package/dist/subagents/internal/state.js +48 -0
  218. package/dist/subagents/internal/worker.d.ts +51 -0
  219. package/dist/subagents/internal/worker.js +167 -0
  220. package/dist/subagents/result.d.ts +62 -0
  221. package/dist/subagents/result.js +103 -0
  222. package/dist/subagents/run-record.d.ts +222 -0
  223. package/dist/subagents/run-record.js +101 -0
  224. package/dist/subagents/run-registry.d.ts +9 -0
  225. package/dist/subagents/run-registry.js +125 -0
  226. package/dist/subagents/runs.d.ts +16 -232
  227. package/dist/subagents/runs.js +132 -310
  228. package/dist/subagents/task-envelope.d.ts +36 -0
  229. package/dist/subagents/task-envelope.js +168 -0
  230. package/dist/subagents/types.d.ts +154 -0
  231. package/dist/subagents/types.js +1 -0
  232. package/dist/subagents/verification-outcome.d.ts +1 -1
  233. package/dist/subagents/workspace-summary.d.ts +16 -4
  234. package/dist/subagents/workspace-summary.js +74 -18
  235. package/dist/tasks/board.d.ts +10 -3
  236. package/dist/tasks/board.js +38 -3
  237. package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
  238. package/dist/tasks/{work-log.js → bound-work.js} +1 -1
  239. package/dist/tasks/brief.js +1 -1
  240. package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
  241. package/dist/{runtime/task-commands.js → tasks/commands.js} +117 -67
  242. package/dist/tasks/contract-input.d.ts +1 -1
  243. package/dist/tasks/contract-input.js +1 -1
  244. package/dist/tasks/create.js +1 -1
  245. package/dist/tasks/frontmatter.d.ts +5 -0
  246. package/dist/tasks/frontmatter.js +8 -0
  247. package/dist/tasks/{log.d.ts → loop-log.d.ts} +11 -1
  248. package/dist/tasks/{log.js → loop-log.js} +59 -3
  249. package/dist/tasks/mutation-lock.js +1 -1
  250. package/dist/tasks/session-path.js +1 -1
  251. package/dist/tasks/steer.js +1 -1
  252. package/dist/tasks/store.js +6 -4
  253. package/dist/tasks/ticket.d.ts +3 -1
  254. package/dist/tasks/ticket.js +19 -1
  255. package/dist/tools/bash.d.ts +1 -1
  256. package/dist/tools/bash.js +2 -2
  257. package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +11 -3
  258. package/dist/tools/{tool-details.js → contract/details.js} +42 -5
  259. package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
  260. package/dist/tools/event-manage.d.ts +1 -1
  261. package/dist/tools/event-manage.js +4 -4
  262. package/dist/tools/index.d.ts +5 -3
  263. package/dist/tools/index.js +8 -6
  264. package/dist/tools/job.d.ts +1 -1
  265. package/dist/tools/memory-manage.js +4 -1
  266. package/dist/tools/registry.d.ts +7 -7
  267. package/dist/tools/registry.js +6 -6
  268. package/dist/tools/session-search.d.ts +1 -1
  269. package/dist/tools/skill.d.ts +2 -34
  270. package/dist/tools/skill.js +8 -116
  271. package/dist/tools/subagent-manage.d.ts +1 -1
  272. package/dist/tools/subagent-manage.js +19 -13
  273. package/dist/tools/subagent.d.ts +46 -0
  274. package/dist/tools/subagent.js +127 -0
  275. package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
  276. package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
  277. package/dist/tools/task-manage/lifecycle.js +2 -2
  278. package/dist/tools/task-manage/log-view.js +2 -2
  279. package/dist/tools/task-manage/shared.js +3 -3
  280. package/dist/tools/task-manage/step-end.js +7 -4
  281. package/dist/tools/task-manage/types.d.ts +1 -1
  282. package/dist/tools/web-fetch.d.ts +1 -1
  283. package/dist/tools/web-search.d.ts +1 -1
  284. package/dist/tui/app.d.ts +1 -1
  285. package/dist/tui/app.js +6 -6
  286. package/dist/tui/cli.d.ts +1 -1
  287. package/dist/tui/cli.js +3 -3
  288. package/dist/tui/commands.js +4 -4
  289. package/dist/tui/frontend.d.ts +44 -0
  290. package/dist/tui/frontend.js +13 -0
  291. package/dist/tui/pitui-frontend.d.ts +1 -1
  292. package/dist/tui/pitui-frontend.js +1 -1
  293. package/dist/tui/plain-frontend.d.ts +1 -1
  294. package/dist/tui/renderer.d.ts +3 -42
  295. package/dist/tui/renderer.js +3 -2
  296. package/dist/tui/terminal-context.d.ts +2 -2
  297. package/dist/tui/terminal-media-sender.d.ts +1 -1
  298. package/dist/tui/turn-controller.d.ts +3 -1
  299. package/dist/tui/turn-controller.js +36 -21
  300. package/dist/usage/ledger.js +7 -1
  301. package/dist/usage/render.js +3 -1
  302. package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
  303. package/dist/web/client.d.ts +5 -1
  304. package/dist/web/client.js +4 -0
  305. package/dist/web/config.d.ts +1 -1
  306. package/dist/web/fetch.d.ts +1 -1
  307. package/dist/web/search-providers.d.ts +1 -1
  308. package/dist/web/search.d.ts +1 -1
  309. package/package.json +9 -7
  310. package/dist/agent/session-adapter.js +0 -77
  311. package/dist/events/events.d.ts +0 -159
  312. package/dist/runtime/dingtalk.d.ts +0 -272
  313. package/dist/runtime/dingtalk.js +0 -1416
  314. package/dist/subagents/tool.d.ts +0 -206
  315. package/dist/subagents/tool.js +0 -1088
  316. /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
  317. /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
  318. /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
  319. /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
  320. /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
  321. /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
  322. /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
  323. /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
  324. /package/dist/{runtime → app}/proxy.d.ts +0 -0
  325. /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
  326. /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
  327. /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
  328. /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
  329. /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
  330. /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
  331. /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
  332. /package/dist/tasks/{ledger.js → contract.js} +0 -0
  333. /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
  334. /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
  335. /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
  336. /package/dist/{shared/types.js → usage/totals.js} +0 -0
@@ -0,0 +1,621 @@
1
+ /**
2
+ * The SDK session of one channel: building and rebuilding it (resource loader, tools, system prompt,
3
+ * extensions), subscribing to its events, binding it to a task's own session or back to the chat
4
+ * session, and tearing it down. Owns the session-side state — the session itself, the model
5
+ * runtime and registry, the current tools and skills, the last prompt build — and nothing about
6
+ * turns; `ChannelRunner` drives turns through it.
7
+ */
8
+ import { Agent } from "@earendil-works/pi-agent-core";
9
+ import { streamSimple } from "@earendil-works/pi-ai/compat";
10
+ import { AgentSession, AgentSessionRuntime, convertToLlm, DefaultResourceLoader, } from "@earendil-works/pi-coding-agent";
11
+ import { mkdir } from "fs/promises";
12
+ import { dirname, join } from "path";
13
+ import { commitActiveSessionRef, resolveActiveSessionFile } from "../../channel/active-session-store.js";
14
+ import { loadToolsConfigWithDiagnostics } from "../../config/tools.js";
15
+ import * as log from "../../log.js";
16
+ import { handleMemoryCommand } from "../../memory/commands.js";
17
+ import { hasMemoryBootstrapBlock } from "../../memory/render.js";
18
+ import { getApiKeyForModel } from "../../models/api-keys.js";
19
+ import { findExactModelReferenceMatch, hasKnownModelPricing } from "../../models/reference.js";
20
+ import { createModelRuntime, resolveInitialModel, wrapModelRegistry } from "../../models/runtime.js";
21
+ import { formatConfigDiagnostic } from "../../shared/config-diagnostic.js";
22
+ import { errorMessage } from "../../shared/text-utils.js";
23
+ import { isRecord } from "../../shared/type-guards.js";
24
+ import { withTimeout } from "../../shared/with-timeout.js";
25
+ import { loadPipiclawSkills, resolvePipiclawSkills } from "../../skills/loader.js";
26
+ import { discoverSubAgents } from "../../subagents/discovery.js";
27
+ import { TASK_SESSIONS_DIRNAME, taskSessionPath } from "../../tasks/session-path.js";
28
+ import { createPipiclawTools } from "../../tools/index.js";
29
+ import { buildPipiclawSystemPrompt } from "../prompt/builder.js";
30
+ import { createPromptBoundaryExtension } from "../prompt/extension.js";
31
+ import { measureToolSchemas, TOOL_SCHEMA_TARGET_UNITS, toolSchemaBudgetWarning } from "../prompt/manifest.js";
32
+ import { loadPlaybooks, loadWorkspacePromptResources } from "../prompt/resources.js";
33
+ import { createCommandExtension } from "./command-extension.js";
34
+ import { getLastAssistantUsage, isAutoCompactionEndEvent } from "./event-guards.js";
35
+ import { asSdkSettingsManager, DEFAULT_MAIN_THINKING_LEVEL, initializeThinkingLevelCompat, setSessionBaseToolsOverride, } from "./session-adapter.js";
36
+ import { handleSessionEvent } from "./session-events.js";
37
+ import { SessionResourceGate } from "./session-resource-gate.js";
38
+ const MODEL_REGISTRY_REFRESH_TIMEOUT_MS = 15_000;
39
+ const SESSION_RELOAD_TIMEOUT_MS = 30_000;
40
+ const CONTEXT_FAULT_MESSAGE = "会话上下文保存失败。请让部署者检查服务器存储后发送 /new 重新开启会话。";
41
+ /** The text of a message's `content`, whether it is a bare string or a multimodal part array. */
42
+ function plainTextOf(content) {
43
+ if (typeof content === "string")
44
+ return content;
45
+ if (!Array.isArray(content))
46
+ return "";
47
+ return content
48
+ .map((part) => (isRecord(part) && part.type === "text" && typeof part.text === "string" ? part.text : ""))
49
+ .join("\n");
50
+ }
51
+ /** Task sessions live under `<channelDir>/tasks/.sessions/`; nothing else may be mistaken for one. */
52
+ function isTaskSessionPath(sessionFile) {
53
+ return sessionFile?.replace(/\\/g, "/").includes(`/${TASK_SESSIONS_DIRNAME}/`) === true;
54
+ }
55
+ /** Surface settings.json load errors (once drained) as warnings; shared by construction and reload. */
56
+ export function reportSettingsDiagnostics(settingsManager, channelId, appHomeDir) {
57
+ for (const { scope, error } of settingsManager.drainErrors()) {
58
+ log.logWarn("config.settings.load_failed", "Settings load failed", {
59
+ channelId,
60
+ reason: error.message,
61
+ fields: { scope, path: join(appHomeDir, "settings.json") },
62
+ });
63
+ }
64
+ }
65
+ export class SessionHost {
66
+ constructor(deps) {
67
+ this.deps = deps;
68
+ /**
69
+ * Flips true only once `initializeSession` has fully assigned `this.session`
70
+ * and loaded its resources. Synchronous dispatch-path callers (`isKnownSlashCommand`)
71
+ * must not touch `this.session` before this — the model runtime takes hundreds
72
+ * of ms to build and the first message can arrive first (spec 048 F2).
73
+ */
74
+ this.sessionInitialized = false;
75
+ this.currentTools = [];
76
+ this.firstTurnMemoryBootstrapPending = true;
77
+ /** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
78
+ this.tasksEnabled = true;
79
+ this.contextFaults = new WeakSet();
80
+ this.channelId = deps.channelId;
81
+ this.channelDir = deps.channelDir;
82
+ this.workspaceDir = deps.workspaceDir;
83
+ this.appHomeDir = deps.appHomeDir;
84
+ this.authConfigPath = deps.authConfigPath;
85
+ this.modelsConfigPath = deps.modelsConfigPath;
86
+ this.onSessionEvent = deps.onSessionEvent;
87
+ this.mediaSender = deps.mediaSender;
88
+ this.projectScope = deps.projectScope;
89
+ this.settingsManager = deps.settingsManager;
90
+ this.loadSecurityConfig = deps.loadSecurityConfig;
91
+ this.executor = deps.executor;
92
+ this.fileStore = deps.fileStore;
93
+ this.jobManager = deps.jobManager;
94
+ this.runManager = deps.runManager;
95
+ this.memoryLifecycle = deps.memoryLifecycle;
96
+ this.models = deps.models;
97
+ this.ledger = deps.ledger;
98
+ this.currentSkills = deps.initialSkills;
99
+ this.sessionResourceGate = new SessionResourceGate(async () => {
100
+ await this.reloadSessionResources();
101
+ });
102
+ }
103
+ get runState() {
104
+ return this.deps.getRunState();
105
+ }
106
+ get agent() {
107
+ return this.session.agent;
108
+ }
109
+ get sessionManager() {
110
+ return this.session.sessionManager;
111
+ }
112
+ /** Kick off asynchronous session construction. The first message can arrive before it settles. */
113
+ start(sessionManager) {
114
+ this.sessionReady = this.initializeSession(sessionManager);
115
+ }
116
+ markContextFault(session, error) {
117
+ this.contextFaults.add(session);
118
+ log.logWarn("agent.session.context_failed", "Session context persistence failed", {
119
+ channelId: this.channelId,
120
+ reason: errorMessage(error),
121
+ fields: { sessionId: session.sessionManager.getSessionId(), stage: "fallback-context-edit" },
122
+ });
123
+ return new Error(CONTEXT_FAULT_MESSAGE, { cause: error });
124
+ }
125
+ assertContextHealthy() {
126
+ if (this.contextFaults.has(this.session))
127
+ throw new Error(CONTEXT_FAULT_MESSAGE);
128
+ }
129
+ /** Run a prompt (or steer) with the resource gate and the context-fault guard. */
130
+ runPrompt(fn) {
131
+ return this.sessionResourceGate.runPrompt(async () => {
132
+ this.assertContextHealthy();
133
+ return fn();
134
+ });
135
+ }
136
+ /** Stop listening to the live session and dispose it (no-op error handling is the caller's). */
137
+ retireLiveSession() {
138
+ this.sessionUnsubscribe?.();
139
+ this.sessionUnsubscribe = undefined;
140
+ this.session.dispose();
141
+ }
142
+ /**
143
+ * Release the session once idle. Guards a dispose() racing construction: initializeSession
144
+ * assigns `this.session` asynchronously, so a runner disposed the instant after creation may
145
+ * not have one yet.
146
+ */
147
+ async disposeSession() {
148
+ await this.sessionReady;
149
+ this.sessionUnsubscribe?.();
150
+ this.sessionUnsubscribe = undefined;
151
+ try {
152
+ this.session.dispose();
153
+ }
154
+ catch (error) {
155
+ log.logWarn("agent.session.dispose_failed", "Session dispose failed", {
156
+ channelId: this.channelId,
157
+ reason: errorMessage(error),
158
+ });
159
+ }
160
+ }
161
+ async refreshSessionResources() {
162
+ await this.ensureSessionReady();
163
+ await this.sessionResourceGate.requestRefresh();
164
+ }
165
+ async initializeSession(sessionManager) {
166
+ // Build the canonical async model/auth runtime and its synchronous read shell.
167
+ this.modelRuntime = await createModelRuntime({
168
+ authConfigPath: this.authConfigPath,
169
+ modelsConfigPath: this.modelsConfigPath,
170
+ });
171
+ this.modelRegistry = wrapModelRegistry(this.modelRuntime);
172
+ // Resolve model: prefer saved global default, fall back to first available model.
173
+ this.models.activeModel = resolveInitialModel(this.modelRegistry, this.settingsManager);
174
+ log.logInfo(`Using model: ${this.models.activeModel.provider}/${this.models.activeModel.id} (${this.models.activeModel.name})`);
175
+ this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
176
+ const initial = await this.createSessionRuntime(sessionManager);
177
+ this.session = initial.session;
178
+ this.sessionRuntime = new AgentSessionRuntime(this.session, this.createAgentSessionServices(initial.resourceLoader), async ({ sessionManager, sessionStartEvent }) => {
179
+ // `/new`, fork, and switch already wrote the target session's durable header by
180
+ // this point (the SDK does it synchronously before invoking this callback); commit
181
+ // the pointer before we rebuild and rebind to it, so a crash between "SDK created
182
+ // session" and "we finished rebinding" leaves the old ref (and old session)
183
+ // authoritative rather than an orphaned new file (spec 043, D1.3).
184
+ // A task session is not the channel's chat session: never repoint the active-session
185
+ // ref at it, or `/new` and restart recovery would adopt a task's transcript as the
186
+ // conversation (spec 051, D3).
187
+ if (!isTaskSessionPath(sessionManager.getSessionFile())) {
188
+ await commitActiveSessionRef(this.channelDir, sessionManager);
189
+ }
190
+ const next = await this.createSessionRuntime(sessionManager, sessionStartEvent);
191
+ return {
192
+ session: next.session,
193
+ extensionsResult: next.resourceLoader.getExtensions(),
194
+ services: this.createAgentSessionServices(next.resourceLoader),
195
+ diagnostics: [],
196
+ };
197
+ });
198
+ this.sessionRuntime.setRebindSession(async (session) => {
199
+ this.session = session;
200
+ await this.bindSessionExtensions();
201
+ this.subscribeToSessionEvents();
202
+ });
203
+ // Subscribe to session events
204
+ this.subscribeToSessionEvents();
205
+ await this.bindSessionExtensions();
206
+ // A restart resumes an existing transcript: if that session was already handed its
207
+ // bootstrap before the daemon went down, the first turn after recovery must not inject a
208
+ // second copy just because a process-local field starts out `true`.
209
+ this.syncMemoryBootstrapPendingFromSession();
210
+ this.sessionInitialized = true;
211
+ }
212
+ async reloadSessionResources() {
213
+ this.settingsManager.reload();
214
+ this.reportSettingsDiagnostics();
215
+ const skills = loadPipiclawSkills(this.channelDir);
216
+ this.currentSkills = skills;
217
+ this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
218
+ this.rebuildSessionTools();
219
+ try {
220
+ await withTimeout(`[${this.channelId}] session reload`, SESSION_RELOAD_TIMEOUT_MS, () => this.session.reload());
221
+ }
222
+ catch (error) {
223
+ log.logWarn("agent.session.reload_unsettled", "Session reload did not settle", {
224
+ channelId: this.channelId,
225
+ reason: errorMessage(error),
226
+ });
227
+ }
228
+ }
229
+ async bindSessionExtensions() {
230
+ await this.session.bindExtensions({
231
+ commandContextActions: {
232
+ waitForIdle: () => this.session.agent.waitForIdle(),
233
+ newSession: async (options) => {
234
+ return await this.sessionRuntime.newSession(options);
235
+ },
236
+ fork: async (entryId, options) => {
237
+ const result = await this.sessionRuntime.fork(entryId, options);
238
+ this.syncMemoryBootstrapPendingFromSession();
239
+ return { cancelled: result.cancelled };
240
+ },
241
+ navigateTree: async (targetId, options) => {
242
+ const result = await this.session.navigateTree(targetId, options);
243
+ this.syncMemoryBootstrapPendingFromSession();
244
+ return { cancelled: result.cancelled };
245
+ },
246
+ switchSession: async (sessionPath, options) => {
247
+ const result = await this.sessionRuntime.switchSession(sessionPath, options);
248
+ this.syncMemoryBootstrapPendingFromSession();
249
+ return result;
250
+ },
251
+ reload: async () => {
252
+ await this.refreshSessionResources();
253
+ },
254
+ },
255
+ });
256
+ }
257
+ async ensureSessionReady() {
258
+ await this.sessionReady;
259
+ }
260
+ async refreshSubAgentDiscovery() {
261
+ // Re-resolves models.json *and* every provider's auth, which for an OAuth
262
+ // provider is a network call. Failing open keeps the last known model
263
+ // snapshot — stale availability is a far smaller problem than a reload
264
+ // (and, through it, a `/new` turn) that never returns.
265
+ try {
266
+ await withTimeout(`[${this.channelId}] model registry refresh`, MODEL_REGISTRY_REFRESH_TIMEOUT_MS, () => this.modelRegistry.refresh());
267
+ }
268
+ catch (error) {
269
+ log.logWarn("agent.models.refresh_unsettled", "Model registry refresh did not settle; using the previous snapshot", { channelId: this.channelId, reason: errorMessage(error) });
270
+ }
271
+ const discovery = discoverSubAgents(this.workspaceDir, this.modelRegistry.getAvailable());
272
+ for (const warning of discovery.warnings) {
273
+ log.logWarn("config.subagents.warning", "Sub-agent config warning", {
274
+ channelId: this.channelId,
275
+ reason: warning,
276
+ });
277
+ }
278
+ return discovery;
279
+ }
280
+ reportSettingsDiagnostics() {
281
+ reportSettingsDiagnostics(this.settingsManager, this.channelId, this.appHomeDir);
282
+ }
283
+ reportConfigDiagnostics(diagnostics) {
284
+ for (const diagnostic of diagnostics) {
285
+ log.logWarn("config.diagnostic", formatConfigDiagnostic(diagnostic), {
286
+ channelId: this.channelId,
287
+ fields: { path: diagnostic.path },
288
+ });
289
+ }
290
+ }
291
+ /**
292
+ * Build the Pipiclaw-owned system prompt (spec 025). This replaces pi's default
293
+ * base prompt entirely: identity, execution contract, hard invariants, the tool
294
+ * catalog and the workspace files are ours. pi still appends its tail (skills,
295
+ * date, cwd), and the boundary footer is appended after that by the prompt
296
+ * extension.
297
+ *
298
+ * Nothing channel-specific enters this text — that is what lets two channels in
299
+ * one workspace share a cached prompt prefix. Channel facts ride the turn.
300
+ */
301
+ buildSystemPrompt() {
302
+ const toolNames = this.currentTools.map((tool) => tool.name);
303
+ const resources = loadWorkspacePromptResources(this.workspaceDir);
304
+ this.lastWorkspaceResources = resources;
305
+ const build = buildPipiclawSystemPrompt({
306
+ tools: this.currentTools.map((tool) => ({
307
+ name: tool.name,
308
+ description: tool.description,
309
+ })),
310
+ soul: resources.soul,
311
+ agents: resources.agents,
312
+ playbooks: loadPlaybooks(toolNames),
313
+ subAgents: this.subAgentDiscovery.agents.map((agent) => ({
314
+ name: agent.name,
315
+ description: agent.description,
316
+ runtime: agent.runtime,
317
+ harness: agent.harness,
318
+ workload: agent.workload ?? (agent.runtime === "external" ? "heavy" : "light"),
319
+ mutates: agent.mutates,
320
+ unavailable: agent.unavailable,
321
+ })),
322
+ });
323
+ for (const diagnostic of [...resources.diagnostics, ...build.diagnostics]) {
324
+ if (diagnostic.level === "info")
325
+ continue;
326
+ log.logWarn("agent.prompt.diagnostic", "Prompt section diagnostic", {
327
+ channelId: this.channelId,
328
+ reason: diagnostic.message,
329
+ fields: { level: diagnostic.level, section: diagnostic.sectionId },
330
+ });
331
+ }
332
+ // Only a real change is worth a line: a reload that produced the same bytes is noise.
333
+ if (this.lastPromptBuild?.fingerprint !== build.fingerprint) {
334
+ log.logInfo(`[${this.channelId}] System prompt rebuilt: ${build.totalChars} chars, ~${build.estimatedTokens} tokens, sha256:${build.fingerprint.slice(0, 12)} (was ${this.lastPromptBuild ? `sha256:${this.lastPromptBuild.fingerprint.slice(0, 12)}` : "none"})`);
335
+ }
336
+ this.lastPromptBuild = build;
337
+ return build;
338
+ }
339
+ createResourceLoader() {
340
+ return new DefaultResourceLoader({
341
+ cwd: this.projectScope.projectRoot,
342
+ agentDir: this.appHomeDir,
343
+ settingsManager: asSdkSettingsManager(this.settingsManager),
344
+ extensionFactories: [
345
+ this.memoryLifecycle.createExtensionFactory(),
346
+ createPromptBoundaryExtension({
347
+ getFooter: () => this.lastPromptBuild?.footer ?? "",
348
+ onFinalPrompt: (systemPrompt) => {
349
+ this.lastFinalPrompt = systemPrompt;
350
+ },
351
+ }),
352
+ createCommandExtension({
353
+ getCurrentModel: () => this.session.model ?? this.models.activeModel,
354
+ getAvailableModels: async () => {
355
+ await this.modelRegistry.refresh();
356
+ return this.modelRegistry.getAvailable();
357
+ },
358
+ getSessionStats: () => this.session.getSessionStats(),
359
+ getThinkingLevel: () => this.session.thinkingLevel,
360
+ getAvailableThinkingLevels: () => this.session.getAvailableThinkingLevels(),
361
+ setThinkingLevel: (level) => this.models.setThinkingLevelCompat(level),
362
+ cycleThinkingLevel: () => this.models.cycleThinkingLevelCompat(),
363
+ getLastResponseModel: () => getLastAssistantUsage(this.session.messages)?.responseModel,
364
+ switchModel: async (model) => {
365
+ await this.models.setModelWithThinkingPreservation(model);
366
+ this.models.activeModel = model;
367
+ // Manual /model switch redefines the preferred model and clears fallback state.
368
+ this.models.clearFallbackState();
369
+ },
370
+ refreshSessionResources: async () => {
371
+ await this.refreshSessionResources();
372
+ },
373
+ runMemoryCommand: async (args) => handleMemoryCommand({
374
+ channelId: this.channelId,
375
+ channelDir: this.channelDir,
376
+ appHomeDir: this.appHomeDir,
377
+ args,
378
+ }),
379
+ }),
380
+ ],
381
+ // Pipiclaw owns the base prompt: with a custom prompt present, pi emits no
382
+ // default identity, no pi docs index and no `Available tools: (none)` block.
383
+ systemPromptOverride: () => this.buildSystemPrompt().text,
384
+ // Nothing may slip in behind the section pipeline — not pi's app-level
385
+ // APPEND_SYSTEM.md, not a base append. SOUL/AGENTS are rendered as sections.
386
+ appendSystemPromptOverride: () => [],
387
+ agentsFilesOverride: () => ({ agentsFiles: [] }),
388
+ // Skills stay in the ResourceLoader: they drive `/skill:name` and pi's
389
+ // `<available_skills>` index together. Only the merge policy is ours.
390
+ skillsOverride: (base) => {
391
+ const merged = resolvePipiclawSkills(base, this.currentSkills);
392
+ for (const diagnostic of merged.diagnostics) {
393
+ log.logWarn("agent.skills.diagnostic", "Skill diagnostic", {
394
+ channelId: this.channelId,
395
+ reason: diagnostic.message,
396
+ fields: { type: diagnostic.type, path: diagnostic.path },
397
+ });
398
+ }
399
+ return merged;
400
+ },
401
+ });
402
+ }
403
+ createAgentSessionServices(resourceLoader) {
404
+ return {
405
+ cwd: this.projectScope.projectRoot,
406
+ agentDir: this.appHomeDir,
407
+ settingsManager: asSdkSettingsManager(this.settingsManager),
408
+ modelRuntime: this.modelRuntime,
409
+ resourceLoader,
410
+ diagnostics: [],
411
+ };
412
+ }
413
+ /**
414
+ * Load a freshly constructed ResourceLoader before an `AgentSession` is built on top of it.
415
+ *
416
+ * `AgentSession` reads `resourceLoader.getExtensions()` in its constructor, and a loader that
417
+ * has never been loaded answers with an *empty* set. Skipping this leaves a replacement session
418
+ * with no extensions at all — no command extension (so `/model`, `/thinking`, `/session`,
419
+ * `/compact` and `/memory` fall through to the model as plain text), no memory lifecycle, no
420
+ * prompt-boundary footer, and no prompt templates. Tolerated on failure the same way
421
+ * `reloadSessionResources` tolerates a stuck reload: a degraded session still answers chat.
422
+ */
423
+ async loadSessionResources(resourceLoader) {
424
+ try {
425
+ await withTimeout(`[${this.channelId}] session resource load`, SESSION_RELOAD_TIMEOUT_MS, () => resourceLoader.reload());
426
+ }
427
+ catch (error) {
428
+ log.logWarn("agent.session.resources_failed", "Session resources did not load", {
429
+ channelId: this.channelId,
430
+ reason: errorMessage(error),
431
+ });
432
+ }
433
+ }
434
+ /**
435
+ * Resolve the initial thinking level using the same precedence as pi's SDK:
436
+ * session history, configured default, then medium. The effective value is
437
+ * clamped to the selected model before the session starts.
438
+ */
439
+ initializeThinkingLevel(agent, model, sessionManager) {
440
+ initializeThinkingLevelCompat(agent, model, sessionManager, this.settingsManager.getDefaultThinkingLevel());
441
+ }
442
+ async createSessionRuntime(sessionManager, sessionStartEvent) {
443
+ const tools = this.buildRuntimeTools();
444
+ const agent = new Agent({
445
+ initialState: {
446
+ systemPrompt: "",
447
+ model: this.models.activeModel,
448
+ thinkingLevel: DEFAULT_MAIN_THINKING_LEVEL,
449
+ tools: [],
450
+ messages: sessionManager.buildSessionContext().messages,
451
+ },
452
+ convertToLlm,
453
+ getApiKey: async () => getApiKeyForModel(this.modelRegistry, this.models.activeModel),
454
+ streamFn: streamSimple,
455
+ });
456
+ this.initializeThinkingLevel(agent, this.models.activeModel, sessionManager);
457
+ const resourceLoader = this.createResourceLoader();
458
+ // Must precede `new AgentSession`: the session snapshots the loader's extensions in its
459
+ // constructor (see `loadSessionResources`).
460
+ await this.loadSessionResources(resourceLoader);
461
+ const sessionSettingsManager = asSdkSettingsManager(this.settingsManager);
462
+ const session = new AgentSession({
463
+ agent,
464
+ sessionManager,
465
+ settingsManager: sessionSettingsManager,
466
+ cwd: this.projectScope.projectRoot,
467
+ modelRuntime: this.modelRuntime,
468
+ resourceLoader,
469
+ baseToolsOverride: Object.fromEntries(tools.map((tool) => [tool.name, tool])),
470
+ initialActiveToolNames: tools.map((tool) => tool.name),
471
+ sessionStartEvent,
472
+ });
473
+ this.sessionSettingsManager = sessionSettingsManager;
474
+ return { session, resourceLoader };
475
+ }
476
+ /**
477
+ * Bind this runner to a task cycle's own session (spec 051, D3/INV-5).
478
+ *
479
+ * Task work must not accumulate in the channel's chat transcript: the one real channel on the
480
+ * author's machine had grown to 7.4 MB and been compacted six times because chat and two daily
481
+ * tasks shared it, so every compaction damaged all three at once. Swapping the bound session
482
+ * per turn gives each task its own bounded context while leaving turn state, `/stop`, and
483
+ * delivery exactly where they already are.
484
+ */
485
+ async bindTaskSession(taskId) {
486
+ await this.sessionReady;
487
+ const path = taskSessionPath(this.channelDir, taskId);
488
+ await mkdir(dirname(path), { recursive: true });
489
+ this.taskLoop = { taskId };
490
+ await this.sessionRuntime.switchSession(path);
491
+ this.syncMemoryBootstrapPendingFromSession();
492
+ }
493
+ /** Return to the channel's chat session after a task step. Safe to call when already bound. */
494
+ async bindChatSession() {
495
+ if (!this.taskLoop)
496
+ return;
497
+ this.taskLoop = undefined;
498
+ await this.sessionRuntime.switchSession(join(this.channelDir, resolveActiveSessionFile(this.channelDir)));
499
+ this.syncMemoryBootstrapPendingFromSession();
500
+ }
501
+ /** Bootstrap presence follows canonical context, including omissions and compaction.
502
+ * Returning from a task or restarting must neither duplicate a visible bootstrap nor
503
+ * mistake an omitted failed input for one. Raw messages remain available to memory/recovery.
504
+ */
505
+ syncMemoryBootstrapPendingFromSession() {
506
+ const injected = this.sessionManager.buildSessionContext().messages.some((value) => {
507
+ const message = value;
508
+ if (!isRecord(message))
509
+ return false;
510
+ return message.role === "user" && hasMemoryBootstrapBlock(plainTextOf(message.content));
511
+ });
512
+ this.firstTurnMemoryBootstrapPending = !injected;
513
+ }
514
+ /** Which task loop this runner is currently bound to, if any. */
515
+ getTaskLoop() {
516
+ return this.taskLoop;
517
+ }
518
+ buildRuntimeTools() {
519
+ const securityLoad = this.loadSecurityConfig();
520
+ const toolsLoad = loadToolsConfigWithDiagnostics(this.appHomeDir);
521
+ this.reportConfigDiagnostics([...securityLoad.diagnostics, ...toolsLoad.diagnostics]);
522
+ this.tasksEnabled = toolsLoad.config.tools.tasks.enabled;
523
+ const tools = createPipiclawTools({
524
+ jobManager: this.jobManager,
525
+ runManager: this.runManager,
526
+ executor: this.executor,
527
+ fileStore: this.fileStore,
528
+ getCurrentModel: () => this.models.activeModel,
529
+ getAvailableModels: () => this.modelRegistry.getAvailable(),
530
+ resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
531
+ workspaceDir: this.workspaceDir,
532
+ projectScope: this.projectScope,
533
+ channelDir: this.channelDir,
534
+ channelId: this.channelId,
535
+ getSubAgentDiscovery: () => this.subAgentDiscovery,
536
+ getSubAgentModelReference: () => this.settingsManager.getSubAgentModelReference(),
537
+ resolveFallbackModel: () => this.models.resolveFallbackModel(),
538
+ getSessionSearchSettings: () => this.settingsManager.getSessionSearchSettings(),
539
+ securityConfig: securityLoad.config,
540
+ toolsConfig: toolsLoad.config,
541
+ mediaSender: this.mediaSender,
542
+ taskLoop: this.taskLoop,
543
+ getToolsUsed: () => this.runState.toolsUsed,
544
+ // Assistant usage only: an internal sub-agent's cost is also in `totalUsage`, and a bound
545
+ // one is already credited to the task when it settles.
546
+ getStepCost: () => ({ usd: this.runState.assistantUsage.cost.total, estimated: !this.runState.costKnown }),
547
+ });
548
+ this.currentTools = tools;
549
+ // Tool schemas are billed with the system prompt and, unlike it, nothing trims them.
550
+ // Warn where the prompt's own budget diagnostics are reported, once per tool rebuild.
551
+ const schemas = measureToolSchemas(tools);
552
+ if (schemas.units > TOOL_SCHEMA_TARGET_UNITS) {
553
+ log.logWarn("agent.tools.schema_over_budget", "Tool schemas over budget", {
554
+ channelId: this.channelId,
555
+ reason: toolSchemaBudgetWarning(schemas),
556
+ });
557
+ }
558
+ return tools;
559
+ }
560
+ rebuildSessionTools() {
561
+ const tools = this.buildRuntimeTools();
562
+ setSessionBaseToolsOverride(this.session, tools, this.channelId);
563
+ this.agent.state.tools = tools;
564
+ this.session.setActiveToolsByName(tools.map((tool) => tool.name));
565
+ }
566
+ // === Session event subscription ===
567
+ subscribeToSessionEvents() {
568
+ this.sessionUnsubscribe?.();
569
+ this.sessionUnsubscribe = this.session.subscribe((event) => {
570
+ // Observation is deliberately before our consumer and must never alter a turn.
571
+ try {
572
+ this.onSessionEvent?.(event, this.channelId);
573
+ }
574
+ catch (err) {
575
+ log.logWarn("agent.session.observer_failed", "Session observer failed", {
576
+ channelId: this.channelId,
577
+ reason: errorMessage(err),
578
+ });
579
+ }
580
+ if (isRecord(event) && event.type === "message_start") {
581
+ this.deps.markStreaming();
582
+ }
583
+ if (isRecord(event) && "reason" in event && event.reason === "new") {
584
+ this.firstTurnMemoryBootstrapPending = true;
585
+ }
586
+ // Spec 050, D1: compaction rewrites the first-turn bootstrap into a summary; re-inject
587
+ // the authoritative index on the next turn so memory does not decay with the transcript.
588
+ if (isAutoCompactionEndEvent(event) && !event.aborted && !event.errorMessage) {
589
+ this.firstTurnMemoryBootstrapPending = true;
590
+ }
591
+ if (!this.runState.ctx || !this.runState.logCtx || !this.runState.queue)
592
+ return;
593
+ // The SDK listener signature is `(event) => void`, so the promise below is fire-and-forget.
594
+ // Without this catch, a rejection inside handleSessionEvent becomes an unhandled rejection
595
+ // that terminates the daemon under Node's default policy.
596
+ handleSessionEvent(event, {
597
+ ctx: this.runState.ctx,
598
+ logCtx: this.runState.logCtx,
599
+ queue: this.runState.queue,
600
+ pendingTools: this.runState.pendingTools,
601
+ store: this.runState.store,
602
+ runState: this.runState,
603
+ memoryLifecycle: this.memoryLifecycle,
604
+ ledger: this.ledger,
605
+ isModelCostKnown: (reference) => {
606
+ const model = findExactModelReferenceMatch(reference, this.modelRegistry.getAvailable()).match;
607
+ return model ? hasKnownModelPricing(model) : false;
608
+ },
609
+ refreshSessionResources: async () => {
610
+ await this.refreshSessionResources();
611
+ },
612
+ skillsDir: join(this.workspaceDir, "skills"),
613
+ }).catch((err) => {
614
+ log.logWarn("agent.session.handler_failed", "Session event handler failed", {
615
+ channelId: this.channelId,
616
+ reason: errorMessage(err),
617
+ });
618
+ });
619
+ });
620
+ }
621
+ }
@@ -1,5 +1,5 @@
1
- import * as log from "../log.js";
2
- import { errorMessage } from "../shared/text-utils.js";
1
+ import * as log from "../../log.js";
2
+ import { errorMessage } from "../../shared/text-utils.js";
3
3
  /**
4
4
  * Serializes session-resource reloads against prompts.
5
5
  *
@@ -63,7 +63,9 @@ export class SessionResourceGate {
63
63
  catch (error) {
64
64
  // The chain is awaited by the next prompt and by detached callers, so a
65
65
  // failed reload must never reject it: log and carry the previous resources.
66
- log.logWarning("Session resource reload failed", errorMessage(error));
66
+ log.logWarn("agent.session.resources_reload_failed", "Session resource reload failed", {
67
+ reason: errorMessage(error),
68
+ });
67
69
  }
68
70
  };
69
71
  this.reloadChain = this.reloadChain.then(runReload, runReload);
@@ -7,5 +7,4 @@ export interface RenderStatusOptions {
7
7
  uptimeMs: number;
8
8
  }
9
9
  export declare function formatTokenCount(count: number): string;
10
- export declare function formatUptime(ms: number): string;
11
10
  export declare function renderStatus(options: RenderStatusOptions): string;