@ouro.bot/cli 0.1.0-alpha.40 → 0.1.0-alpha.401

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 (333) hide show
  1. package/README.md +109 -14
  2. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +3 -2
  3. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +2 -2
  4. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  5. package/changelog.json +2465 -6
  6. package/dist/arc/attention-types.js +8 -0
  7. package/dist/arc/cares.js +140 -0
  8. package/dist/arc/episodes.js +117 -0
  9. package/dist/arc/intentions.js +133 -0
  10. package/dist/arc/json-store.js +117 -0
  11. package/dist/arc/obligations.js +237 -0
  12. package/dist/arc/packets.js +193 -0
  13. package/dist/arc/presence.js +185 -0
  14. package/dist/arc/task-lifecycle.js +65 -0
  15. package/dist/heart/active-work.js +832 -0
  16. package/dist/heart/agent-entry.js +58 -3
  17. package/dist/heart/attachments/image-normalize.js +194 -0
  18. package/dist/heart/attachments/materialize.js +97 -0
  19. package/dist/heart/attachments/originals.js +88 -0
  20. package/dist/heart/attachments/render.js +29 -0
  21. package/dist/heart/attachments/sources/adapter.js +2 -0
  22. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  23. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  24. package/dist/heart/attachments/sources/index.js +16 -0
  25. package/dist/heart/attachments/store.js +103 -0
  26. package/dist/heart/attachments/types.js +93 -0
  27. package/dist/heart/auth/auth-flow.js +417 -0
  28. package/dist/heart/bridges/manager.js +358 -0
  29. package/dist/heart/bridges/state-machine.js +135 -0
  30. package/dist/heart/bridges/store.js +123 -0
  31. package/dist/heart/bundle-state.js +168 -0
  32. package/dist/heart/commitments.js +111 -0
  33. package/dist/heart/config-registry.js +304 -0
  34. package/dist/heart/config.js +101 -128
  35. package/dist/heart/core.js +801 -217
  36. package/dist/heart/cross-chat-delivery.js +131 -0
  37. package/dist/heart/daemon/agent-config-check.js +397 -0
  38. package/dist/heart/daemon/agent-discovery.js +79 -3
  39. package/dist/heart/daemon/agent-service.js +360 -0
  40. package/dist/heart/daemon/agentic-repair.js +213 -0
  41. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  42. package/dist/heart/daemon/cadence.js +70 -0
  43. package/dist/heart/daemon/cli-defaults.js +599 -0
  44. package/dist/heart/daemon/cli-exec.js +3616 -0
  45. package/dist/heart/daemon/cli-help.js +396 -0
  46. package/dist/heart/daemon/cli-parse.js +1118 -0
  47. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  48. package/dist/heart/daemon/cli-render.js +560 -0
  49. package/dist/heart/daemon/cli-types.js +8 -0
  50. package/dist/heart/daemon/daemon-cli.js +28 -1582
  51. package/dist/heart/daemon/daemon-entry.js +356 -3
  52. package/dist/heart/daemon/daemon-health.js +141 -0
  53. package/dist/heart/daemon/daemon-runtime-sync.js +157 -12
  54. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  55. package/dist/heart/daemon/daemon.js +684 -58
  56. package/dist/heart/daemon/doctor-types.js +8 -0
  57. package/dist/heart/daemon/doctor.js +419 -0
  58. package/dist/heart/daemon/health-monitor.js +79 -1
  59. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  60. package/dist/heart/daemon/hooks/bundle-meta.js +115 -1
  61. package/dist/heart/daemon/http-health-probe.js +80 -0
  62. package/dist/heart/daemon/inner-status.js +89 -0
  63. package/dist/heart/daemon/interactive-repair.js +209 -0
  64. package/dist/heart/daemon/launchd.js +46 -9
  65. package/dist/heart/daemon/log-tailer.js +82 -12
  66. package/dist/heart/daemon/logs-prune.js +105 -0
  67. package/dist/heart/daemon/message-router.js +17 -8
  68. package/dist/heart/daemon/os-cron-deps.js +134 -0
  69. package/dist/heart/daemon/ouro-bot-entry.js +4 -2
  70. package/dist/heart/daemon/ouro-entry.js +3 -1
  71. package/dist/heart/daemon/process-manager.js +201 -0
  72. package/dist/heart/daemon/provider-discovery.js +137 -0
  73. package/dist/heart/daemon/pulse.js +475 -0
  74. package/dist/heart/daemon/readiness-repair.js +216 -0
  75. package/dist/heart/daemon/run-hooks.js +2 -0
  76. package/dist/heart/daemon/runtime-logging.js +67 -16
  77. package/dist/heart/daemon/runtime-metadata.js +73 -0
  78. package/dist/heart/daemon/runtime-mode.js +67 -0
  79. package/dist/heart/daemon/safe-mode.js +161 -0
  80. package/dist/heart/daemon/sense-manager.js +119 -30
  81. package/dist/heart/daemon/session-id-resolver.js +131 -0
  82. package/dist/heart/daemon/skill-management-installer.js +94 -0
  83. package/dist/heart/daemon/socket-client.js +307 -0
  84. package/dist/heart/daemon/stale-bundle-prune.js +96 -0
  85. package/dist/heart/daemon/startup-tui.js +237 -0
  86. package/dist/heart/daemon/task-scheduler.js +3 -25
  87. package/dist/heart/daemon/thoughts.js +510 -0
  88. package/dist/heart/daemon/up-progress.js +135 -0
  89. package/dist/heart/delegation.js +62 -0
  90. package/dist/heart/habits/habit-migration.js +181 -0
  91. package/dist/heart/habits/habit-parser.js +140 -0
  92. package/dist/heart/habits/habit-scheduler.js +371 -0
  93. package/dist/heart/{daemon → hatch}/hatch-flow.js +53 -117
  94. package/dist/heart/{daemon → hatch}/hatch-specialist.js +3 -3
  95. package/dist/heart/{daemon → hatch}/specialist-prompt.js +12 -9
  96. package/dist/heart/{daemon → hatch}/specialist-tools.js +33 -12
  97. package/dist/heart/identity.js +161 -65
  98. package/dist/heart/kept-notes.js +357 -0
  99. package/dist/heart/kicks.js +1 -1
  100. package/dist/heart/machine-identity.js +161 -0
  101. package/dist/heart/mcp/mcp-server.js +653 -0
  102. package/dist/heart/migrate-config.js +100 -0
  103. package/dist/heart/model-capabilities.js +59 -0
  104. package/dist/heart/outlook/outlook-http-hooks.js +64 -0
  105. package/dist/heart/outlook/outlook-http-response.js +7 -0
  106. package/dist/heart/outlook/outlook-http-routes.js +232 -0
  107. package/dist/heart/outlook/outlook-http-static.js +99 -0
  108. package/dist/heart/outlook/outlook-http-transport.js +116 -0
  109. package/dist/heart/outlook/outlook-http.js +99 -0
  110. package/dist/heart/outlook/outlook-read.js +28 -0
  111. package/dist/heart/outlook/outlook-types.js +27 -0
  112. package/dist/heart/outlook/outlook-view.js +195 -0
  113. package/dist/heart/outlook/readers/agent-machine.js +359 -0
  114. package/dist/heart/outlook/readers/continuity-readers.js +332 -0
  115. package/dist/heart/outlook/readers/runtime-readers.js +660 -0
  116. package/dist/heart/outlook/readers/sessions.js +232 -0
  117. package/dist/heart/outlook/readers/shared.js +111 -0
  118. package/dist/heart/platform.js +81 -0
  119. package/dist/heart/progress-story.js +42 -0
  120. package/dist/heart/provider-attempt.js +133 -0
  121. package/dist/heart/provider-binding-resolver.js +239 -0
  122. package/dist/heart/provider-credentials.js +383 -0
  123. package/dist/heart/provider-failover.js +266 -0
  124. package/dist/heart/provider-models.js +81 -0
  125. package/dist/heart/provider-ping.js +237 -0
  126. package/dist/heart/provider-state.js +216 -0
  127. package/dist/heart/provider-visibility.js +186 -0
  128. package/dist/heart/providers/anthropic-token.js +131 -0
  129. package/dist/heart/providers/anthropic.js +193 -55
  130. package/dist/heart/providers/azure.js +103 -12
  131. package/dist/heart/providers/error-classification.js +63 -0
  132. package/dist/heart/providers/github-copilot.js +145 -0
  133. package/dist/heart/providers/minimax-vlm.js +189 -0
  134. package/dist/heart/providers/minimax.js +29 -7
  135. package/dist/heart/providers/openai-codex.js +39 -29
  136. package/dist/heart/runtime-credentials.js +181 -0
  137. package/dist/heart/session-activity.js +190 -0
  138. package/dist/heart/session-events.js +855 -0
  139. package/dist/heart/session-transcript.js +167 -0
  140. package/dist/heart/start-of-turn-packet.js +345 -0
  141. package/dist/heart/streaming.js +36 -27
  142. package/dist/heart/sync.js +332 -0
  143. package/dist/heart/target-resolution.js +127 -0
  144. package/dist/heart/tempo.js +93 -0
  145. package/dist/heart/temporal-view.js +41 -0
  146. package/dist/heart/tool-activity-callbacks.js +36 -0
  147. package/dist/heart/tool-description.js +135 -0
  148. package/dist/heart/tool-friction.js +55 -0
  149. package/dist/heart/tool-loop.js +200 -0
  150. package/dist/heart/turn-context.js +351 -0
  151. package/dist/heart/turn-coordinator.js +28 -0
  152. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +1 -1
  153. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  154. package/dist/heart/versioning/ouro-path-installer.js +301 -0
  155. package/dist/heart/versioning/ouro-version-manager.js +295 -0
  156. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  157. package/dist/heart/{daemon → versioning}/update-checker.js +12 -2
  158. package/dist/heart/{daemon → versioning}/update-hooks.js +63 -59
  159. package/dist/mind/bundle-manifest.js +7 -1
  160. package/dist/mind/context.js +134 -87
  161. package/dist/mind/diary-integrity.js +60 -0
  162. package/dist/mind/{memory.js → diary.js} +84 -96
  163. package/dist/mind/embedding-provider.js +60 -0
  164. package/dist/mind/file-state.js +179 -0
  165. package/dist/mind/first-impressions.js +14 -1
  166. package/dist/mind/friends/channel.js +21 -0
  167. package/dist/mind/friends/group-context.js +144 -0
  168. package/dist/mind/friends/resolver.js +38 -1
  169. package/dist/mind/friends/store-file.js +39 -3
  170. package/dist/mind/friends/trust-explanation.js +74 -0
  171. package/dist/mind/friends/types.js +1 -1
  172. package/dist/mind/journal-index.js +161 -0
  173. package/dist/mind/note-search.js +268 -0
  174. package/dist/mind/obligation-steering.js +221 -0
  175. package/dist/mind/pending.js +66 -7
  176. package/dist/mind/prompt-refresh.js +3 -2
  177. package/dist/mind/prompt.js +946 -167
  178. package/dist/mind/provenance-trust.js +26 -0
  179. package/dist/mind/scrutiny.js +173 -0
  180. package/dist/nerves/cli-logging.js +7 -1
  181. package/dist/nerves/coverage/audit-rules.js +15 -6
  182. package/dist/nerves/coverage/audit.js +28 -2
  183. package/dist/nerves/coverage/cli.js +1 -1
  184. package/dist/nerves/coverage/contract.js +5 -5
  185. package/dist/nerves/coverage/file-completeness.js +83 -5
  186. package/dist/nerves/coverage/run-artifacts.js +1 -1
  187. package/dist/nerves/event-buffer.js +111 -0
  188. package/dist/nerves/index.js +224 -4
  189. package/dist/nerves/observation.js +20 -0
  190. package/dist/nerves/redact.js +79 -0
  191. package/dist/nerves/runtime.js +5 -1
  192. package/dist/outlook-ui/assets/index-BAcU08c-.css +1 -0
  193. package/dist/outlook-ui/assets/index-D7l3l4vY.js +61 -0
  194. package/dist/outlook-ui/index.html +15 -0
  195. package/dist/repertoire/ado-client.js +15 -56
  196. package/dist/repertoire/ado-semantic.js +11 -10
  197. package/dist/repertoire/api-client.js +97 -0
  198. package/dist/repertoire/bitwarden-store.js +519 -0
  199. package/dist/repertoire/bundle-templates.js +72 -0
  200. package/dist/repertoire/bw-installer.js +79 -0
  201. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  202. package/dist/repertoire/coding/context-pack.js +330 -0
  203. package/dist/repertoire/coding/feedback.js +197 -30
  204. package/dist/repertoire/coding/manager.js +158 -9
  205. package/dist/repertoire/coding/spawner.js +55 -9
  206. package/dist/repertoire/coding/tools.js +170 -7
  207. package/dist/repertoire/commerce-errors.js +109 -0
  208. package/dist/repertoire/commerce-self-test.js +156 -0
  209. package/dist/repertoire/credential-access.js +107 -0
  210. package/dist/repertoire/duffel-client.js +185 -0
  211. package/dist/repertoire/github-client.js +14 -55
  212. package/dist/repertoire/graph-client.js +11 -52
  213. package/dist/repertoire/guardrails.js +371 -0
  214. package/dist/repertoire/mcp-client.js +255 -0
  215. package/dist/repertoire/mcp-manager.js +305 -0
  216. package/dist/repertoire/mcp-tools.js +63 -0
  217. package/dist/repertoire/shell-sessions.js +133 -0
  218. package/dist/repertoire/skills.js +15 -24
  219. package/dist/repertoire/stripe-client.js +131 -0
  220. package/dist/repertoire/tasks/board.js +43 -5
  221. package/dist/repertoire/tasks/fix.js +182 -0
  222. package/dist/repertoire/tasks/index.js +26 -1
  223. package/dist/repertoire/tasks/lifecycle.js +2 -2
  224. package/dist/repertoire/tasks/parser.js +3 -2
  225. package/dist/repertoire/tasks/scanner.js +194 -37
  226. package/dist/repertoire/tasks/transitions.js +16 -78
  227. package/dist/repertoire/tool-results.js +29 -0
  228. package/dist/repertoire/tools-attachments.js +317 -0
  229. package/dist/repertoire/tools-base.js +42 -687
  230. package/dist/repertoire/tools-bluebubbles.js +1 -0
  231. package/dist/repertoire/tools-bridge.js +141 -0
  232. package/dist/repertoire/tools-bundle.js +984 -0
  233. package/dist/repertoire/tools-config.js +185 -0
  234. package/dist/repertoire/tools-continuity.js +248 -0
  235. package/dist/repertoire/tools-credential.js +182 -0
  236. package/dist/repertoire/tools-files.js +342 -0
  237. package/dist/repertoire/tools-flight.js +224 -0
  238. package/dist/repertoire/tools-flow.js +105 -0
  239. package/dist/repertoire/tools-github.js +1 -7
  240. package/dist/repertoire/tools-notes.js +376 -0
  241. package/dist/repertoire/tools-session.js +739 -0
  242. package/dist/repertoire/tools-shell.js +120 -0
  243. package/dist/repertoire/tools-stripe.js +180 -0
  244. package/dist/repertoire/tools-surface.js +243 -0
  245. package/dist/repertoire/tools-teams.js +9 -39
  246. package/dist/repertoire/tools-travel.js +125 -0
  247. package/dist/repertoire/tools-user-profile.js +144 -0
  248. package/dist/repertoire/tools-vault.js +40 -0
  249. package/dist/repertoire/tools.js +144 -113
  250. package/dist/repertoire/travel-api-client.js +360 -0
  251. package/dist/repertoire/user-profile.js +118 -0
  252. package/dist/repertoire/vault-setup.js +246 -0
  253. package/dist/repertoire/vault-unlock.js +382 -0
  254. package/dist/scripts/claude-code-hook.js +41 -0
  255. package/dist/scripts/claude-code-stop-hook.js +47 -0
  256. package/dist/senses/attention-queue.js +116 -0
  257. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  258. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  259. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +260 -9
  260. package/dist/senses/bluebubbles/entry.js +70 -0
  261. package/dist/senses/bluebubbles/inbound-log.js +113 -0
  262. package/dist/senses/bluebubbles/index.js +1620 -0
  263. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +121 -70
  264. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +33 -12
  265. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +45 -3
  266. package/dist/senses/bluebubbles/replay.js +129 -0
  267. package/dist/senses/bluebubbles/runtime-state.js +109 -0
  268. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  269. package/dist/senses/cli/bracketed-paste.js +82 -0
  270. package/dist/senses/cli/image-paste.js +287 -0
  271. package/dist/senses/cli/image-ref-navigation.js +75 -0
  272. package/dist/senses/cli/ink-app.js +156 -0
  273. package/dist/senses/cli/inline-diff.js +64 -0
  274. package/dist/senses/cli/input-keys.js +174 -0
  275. package/dist/senses/cli/kill-ring.js +86 -0
  276. package/dist/senses/cli/message-list.js +51 -0
  277. package/dist/senses/cli/ouro-tui.js +605 -0
  278. package/dist/senses/cli/spinner-imperative.js +135 -0
  279. package/dist/senses/cli/spinner.js +101 -0
  280. package/dist/senses/cli/status-line.js +60 -0
  281. package/dist/senses/cli/streaming-markdown.js +526 -0
  282. package/dist/senses/cli/tool-display.js +83 -0
  283. package/dist/senses/cli/tool-render.js +85 -0
  284. package/dist/senses/cli/tui-store.js +240 -0
  285. package/dist/senses/cli/virtual-list.js +35 -0
  286. package/dist/senses/cli-entry.js +60 -8
  287. package/dist/senses/cli-layout.js +187 -0
  288. package/dist/senses/cli.js +526 -211
  289. package/dist/senses/commands.js +66 -3
  290. package/dist/senses/continuity.js +94 -0
  291. package/dist/senses/habit-turn-message.js +108 -0
  292. package/dist/senses/inner-dialog-worker.js +112 -19
  293. package/dist/senses/inner-dialog.js +600 -95
  294. package/dist/senses/pipeline.js +539 -61
  295. package/dist/senses/proactive-content-guard.js +51 -0
  296. package/dist/senses/shared-turn.js +205 -0
  297. package/dist/senses/surface-tool.js +68 -0
  298. package/dist/senses/teams-entry.js +60 -8
  299. package/dist/senses/teams.js +569 -237
  300. package/dist/senses/trust-gate.js +5 -5
  301. package/package.json +28 -7
  302. package/skills/agent-commerce.md +106 -0
  303. package/skills/browser-navigation.md +110 -0
  304. package/skills/commerce-setup-guide.md +116 -0
  305. package/skills/commerce-setup.md +84 -0
  306. package/skills/configure-dev-tools.md +101 -0
  307. package/skills/travel-planning.md +134 -0
  308. package/dist/heart/daemon/ouro-path-installer.js +0 -178
  309. package/dist/heart/daemon/subagent-installer.js +0 -134
  310. package/dist/mind/associative-recall.js +0 -197
  311. package/dist/senses/bluebubbles-entry.js +0 -11
  312. package/dist/senses/bluebubbles.js +0 -832
  313. package/dist/senses/debug-activity.js +0 -127
  314. package/subagents/README.md +0 -60
  315. package/subagents/work-doer.md +0 -235
  316. package/subagents/work-merger.md +0 -618
  317. package/subagents/work-planner.md +0 -382
  318. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  319. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  320. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  321. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  322. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  323. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  324. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  325. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  326. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  327. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  328. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  329. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  330. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  331. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  332. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  333. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -37,8 +37,13 @@ exports.loadInnerDialogInstincts = loadInnerDialogInstincts;
37
37
  exports.buildInnerDialogBootstrapMessage = buildInnerDialogBootstrapMessage;
38
38
  exports.buildNonCanonicalCleanupNudge = buildNonCanonicalCleanupNudge;
39
39
  exports.buildInstinctUserMessage = buildInstinctUserMessage;
40
+ exports.readTaskFile = readTaskFile;
41
+ exports.buildTaskTriggeredMessage = buildTaskTriggeredMessage;
40
42
  exports.deriveResumeCheckpoint = deriveResumeCheckpoint;
41
43
  exports.innerDialogSessionPath = innerDialogSessionPath;
44
+ exports.enrichDelegatedFromWithBridge = enrichDelegatedFromWithBridge;
45
+ exports.routeDelegatedCompletion = routeDelegatedCompletion;
46
+ exports.buildParseErrorNudge = buildParseErrorNudge;
42
47
  exports.runInnerDialogTurn = runInnerDialogTurn;
43
48
  const fs = __importStar(require("fs"));
44
49
  const path = __importStar(require("path"));
@@ -47,14 +52,27 @@ const core_1 = require("../heart/core");
47
52
  const identity_1 = require("../heart/identity");
48
53
  const context_1 = require("../mind/context");
49
54
  const prompt_1 = require("../mind/prompt");
55
+ const mcp_manager_1 = require("../repertoire/mcp-manager");
56
+ const tools_1 = require("../repertoire/tools");
50
57
  const bundle_manifest_1 = require("../mind/bundle-manifest");
51
58
  const pending_1 = require("../mind/pending");
59
+ const obligations_1 = require("../arc/obligations");
60
+ const attention_queue_1 = require("./attention-queue");
61
+ const packets_1 = require("../arc/packets");
52
62
  const channel_1 = require("../mind/friends/channel");
53
63
  const trust_gate_1 = require("./trust-gate");
54
64
  const tokens_1 = require("../mind/friends/tokens");
55
65
  const pipeline_1 = require("./pipeline");
56
66
  const nerves_1 = require("../nerves");
57
67
  const runtime_1 = require("../nerves/runtime");
68
+ const manager_1 = require("../heart/bridges/manager");
69
+ const session_activity_1 = require("../heart/session-activity");
70
+ const bluebubbles_1 = require("./bluebubbles");
71
+ const habit_turn_message_1 = require("./habit-turn-message");
72
+ const journal_index_1 = require("../mind/journal-index");
73
+ const habit_parser_1 = require("../heart/habits/habit-parser");
74
+ const cadence_1 = require("../heart/daemon/cadence");
75
+ const daemon_health_1 = require("../heart/daemon/daemon-health");
58
76
  const DEFAULT_INNER_DIALOG_INSTINCTS = [
59
77
  {
60
78
  id: "heartbeat_checkin",
@@ -73,8 +91,16 @@ function readAspirations(agentRoot) {
73
91
  function loadInnerDialogInstincts() {
74
92
  return [...DEFAULT_INNER_DIALOG_INSTINCTS];
75
93
  }
76
- function buildInnerDialogBootstrapMessage(_aspirations, _stateSummary) {
77
- return "waking up. settling in.\n\nwhat needs my attention?";
94
+ function buildInnerDialogBootstrapMessage(aspirations, stateSummary) {
95
+ const lines = ["waking up."];
96
+ if (aspirations) {
97
+ lines.push("", "## what matters to me", aspirations);
98
+ }
99
+ if (stateSummary) {
100
+ lines.push("", "## what i know so far", stateSummary);
101
+ }
102
+ lines.push("", "what needs my attention?");
103
+ return lines.join("\n");
78
104
  }
79
105
  function buildNonCanonicalCleanupNudge(nonCanonicalPaths) {
80
106
  if (nonCanonicalPaths.length === 0)
@@ -85,16 +111,52 @@ function buildNonCanonicalCleanupNudge(nonCanonicalPaths) {
85
111
  }
86
112
  return [
87
113
  "## canonical cleanup nudge",
88
- "I found non-canonical files in my bundle. I should distill anything valuable into your memory system and remove these files.",
114
+ "I found non-canonical files in my bundle. I should distill anything valuable into my diary and remove these files.",
89
115
  ...listed,
90
116
  ].join("\n");
91
117
  }
118
+ function displayCheckpoint(checkpoint) {
119
+ const trimmed = checkpoint?.trim();
120
+ if (!trimmed || trimmed === "no prior checkpoint recorded") {
121
+ return undefined;
122
+ }
123
+ return trimmed;
124
+ }
92
125
  function buildInstinctUserMessage(instincts, _reason, state) {
93
126
  const active = instincts.find((instinct) => instinct.enabled !== false) ?? DEFAULT_INNER_DIALOG_INSTINCTS[0];
94
- const checkpoint = state.checkpoint?.trim();
127
+ const checkpoint = displayCheckpoint(state.checkpoint);
95
128
  const lines = [active.prompt];
96
129
  if (checkpoint) {
97
- lines.push(`\nlast i remember: ${checkpoint}`);
130
+ lines.push(`\nlast checkpoint: ${checkpoint}`);
131
+ }
132
+ return lines.join("\n");
133
+ }
134
+ function readTaskFile(agentRoot, taskId) {
135
+ // Task files live in collection subdirectories (one-shots, ongoing).
136
+ // Try each collection, then fall back to root tasks/ for legacy layout.
137
+ // Habits are no longer in tasks/ — they live at bundle root habits/.
138
+ const collections = ["one-shots", "ongoing", ""];
139
+ for (const collection of collections) {
140
+ try {
141
+ return fs.readFileSync(path.join(agentRoot, "tasks", collection, `${taskId}.md`), "utf8").trim();
142
+ }
143
+ catch {
144
+ // not in this collection — try next
145
+ }
146
+ }
147
+ return "";
148
+ }
149
+ function buildTaskTriggeredMessage(taskId, taskContent, checkpoint) {
150
+ const lines = ["a task needs my attention."];
151
+ if (taskContent) {
152
+ lines.push("", `## task: ${taskId}`, taskContent);
153
+ }
154
+ else {
155
+ lines.push("", `## task: ${taskId}`, "(task file not found)");
156
+ }
157
+ const renderedCheckpoint = displayCheckpoint(checkpoint);
158
+ if (renderedCheckpoint) {
159
+ lines.push("", `last checkpoint: ${renderedCheckpoint}`);
98
160
  }
99
161
  return lines.join("\n");
100
162
  }
@@ -135,11 +197,39 @@ function deriveResumeCheckpoint(messages) {
135
197
  const firstLine = assistantText
136
198
  .split("\n")
137
199
  .map((line) => line.trim())
138
- .filter((line) => line.length > 0)[0];
200
+ .find((line) => line.length > 0);
201
+ /* v8 ignore next -- unreachable: contentToText().trim() guarantees a non-empty line @preserve */
202
+ if (!firstLine)
203
+ return "no prior checkpoint recorded";
139
204
  if (firstLine.length <= 220)
140
205
  return firstLine;
141
206
  return `${firstLine.slice(0, 217)}...`;
142
207
  }
208
+ function extractAssistantPreview(messages, maxLength = 120) {
209
+ const lastAssistant = [...messages].reverse().find((m) => m.role === "assistant");
210
+ if (!lastAssistant)
211
+ return "";
212
+ const text = contentToText(lastAssistant.content);
213
+ if (!text)
214
+ return "";
215
+ /* v8 ignore next -- unreachable: contentToText().trim() guarantees a non-empty line @preserve */
216
+ const firstLine = text.split("\n").find((line) => line.trim().length > 0) ?? "";
217
+ if (firstLine.length <= maxLength)
218
+ return firstLine;
219
+ return `${firstLine.slice(0, maxLength - 3)}...`;
220
+ }
221
+ function extractToolCallNames(messages) {
222
+ const names = [];
223
+ for (const msg of messages) {
224
+ if (msg.role === "assistant" && "tool_calls" in msg && Array.isArray(msg.tool_calls)) {
225
+ for (const tc of msg.tool_calls) {
226
+ if ("function" in tc && tc.function?.name)
227
+ names.push(tc.function.name);
228
+ }
229
+ }
230
+ }
231
+ return [...new Set(names)];
232
+ }
143
233
  function createInnerDialogCallbacks() {
144
234
  return {
145
235
  onModelStart: () => { },
@@ -154,6 +244,204 @@ function createInnerDialogCallbacks() {
154
244
  function innerDialogSessionPath() {
155
245
  return (0, config_1.sessionPath)(pending_1.INNER_DIALOG_PENDING.friendId, pending_1.INNER_DIALOG_PENDING.channel, pending_1.INNER_DIALOG_PENDING.key);
156
246
  }
247
+ function innerDialogRuntimeStatePath(sessionFilePath) {
248
+ return path.join(path.dirname(sessionFilePath), "runtime.json");
249
+ }
250
+ function writeInnerDialogRuntimeState(sessionFilePath, state) {
251
+ const filePath = innerDialogRuntimeStatePath(sessionFilePath);
252
+ try {
253
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
254
+ fs.writeFileSync(filePath, JSON.stringify(state, null, 2) + "\n", "utf8");
255
+ }
256
+ catch (error) {
257
+ (0, runtime_1.emitNervesEvent)({
258
+ level: "warn",
259
+ component: "senses",
260
+ event: "senses.inner_dialog_runtime_state_error",
261
+ message: "failed to write inner dialog runtime state",
262
+ meta: {
263
+ status: state.status,
264
+ reason: state.reason ?? null,
265
+ path: filePath,
266
+ /* v8 ignore next -- Node fs APIs throw Error objects for mkdirSync/writeFileSync failures @preserve */
267
+ error: error instanceof Error ? error.message : String(error),
268
+ },
269
+ });
270
+ }
271
+ }
272
+ /* v8 ignore start -- routing helpers: called from routing functions which are integration paths @preserve */
273
+ function writePendingEnvelope(pendingDir, message) {
274
+ fs.mkdirSync(pendingDir, { recursive: true });
275
+ const fileName = `${message.timestamp}-${Math.random().toString(36).slice(2, 10)}.json`;
276
+ const filePath = path.join(pendingDir, fileName);
277
+ fs.writeFileSync(filePath, JSON.stringify(message, null, 2), "utf8");
278
+ }
279
+ function sessionMatchesActivity(activity, session) {
280
+ return activity.friendId === session.friendId
281
+ && activity.channel === session.channel
282
+ && activity.key === session.key;
283
+ }
284
+ /* v8 ignore stop */
285
+ /* v8 ignore start -- routing: delivery now inline via surface tool; routing functions preserved for reuse @preserve */
286
+ function resolveBridgePreferredSession(delegatedFrom, sessionActivity) {
287
+ if (!delegatedFrom.bridgeId)
288
+ return null;
289
+ const bridge = (0, manager_1.createBridgeManager)().getBridge(delegatedFrom.bridgeId);
290
+ if (!bridge || bridge.lifecycle === "completed" || bridge.lifecycle === "cancelled") {
291
+ return null;
292
+ }
293
+ return sessionActivity.find((activity) => activity.friendId === delegatedFrom.friendId
294
+ && activity.channel !== "inner"
295
+ && bridge.attachedSessions.some((session) => sessionMatchesActivity(activity, session))) ?? null;
296
+ }
297
+ async function tryDeliverDelegatedCompletion(target, outboundEnvelope) {
298
+ if (target.channel !== "bluebubbles") {
299
+ return false;
300
+ }
301
+ const result = await (0, bluebubbles_1.sendProactiveBlueBubblesMessageToSession)({
302
+ friendId: target.friendId,
303
+ sessionKey: target.key,
304
+ text: outboundEnvelope.content,
305
+ intent: "explicit_cross_chat",
306
+ });
307
+ return result.delivered;
308
+ }
309
+ function enrichDelegatedFromWithBridge(delegatedFrom) {
310
+ if (delegatedFrom.bridgeId) {
311
+ return delegatedFrom;
312
+ }
313
+ const bridgeManager = (0, manager_1.createBridgeManager)();
314
+ const originBridges = bridgeManager.findBridgesForSession({
315
+ friendId: delegatedFrom.friendId,
316
+ channel: delegatedFrom.channel,
317
+ key: delegatedFrom.key,
318
+ });
319
+ const activeBridge = originBridges.find((b) => b.lifecycle === "active");
320
+ if (activeBridge) {
321
+ return { ...delegatedFrom, bridgeId: activeBridge.id };
322
+ }
323
+ return delegatedFrom;
324
+ }
325
+ function advanceObligationQuietly(agentName, obligationId, update) {
326
+ if (!obligationId)
327
+ return;
328
+ try {
329
+ (0, obligations_1.advanceReturnObligation)(agentName, obligationId, update);
330
+ /* v8 ignore start -- best-effort: obligation fs errors must never block return routing @preserve */
331
+ }
332
+ catch {
333
+ // swallowed
334
+ }
335
+ /* v8 ignore stop */
336
+ }
337
+ async function routeDelegatedCompletion(agentRoot, agentName, completion, drainedPending, timestamp) {
338
+ const delegated = (drainedPending ?? []).find((message) => message.delegatedFrom);
339
+ if (!delegated?.delegatedFrom || !completion?.answer?.trim()) {
340
+ return;
341
+ }
342
+ const delegatedFrom = enrichDelegatedFromWithBridge(delegated.delegatedFrom);
343
+ const obligationId = delegated.obligationId;
344
+ // Advance any inner return obligations from queued -> running (they were drained this turn).
345
+ // drainedPending is guaranteed non-null here (we found delegated above).
346
+ for (const msg of drainedPending) {
347
+ if (msg.obligationId) {
348
+ advanceObligationQuietly(agentName, msg.obligationId, {
349
+ status: "running",
350
+ startedAt: timestamp,
351
+ });
352
+ }
353
+ }
354
+ if (delegated.obligationStatus === "pending") {
355
+ // Fulfill the persistent obligation in the store
356
+ try {
357
+ const pending = (0, obligations_1.findPendingObligationForOrigin)(agentRoot, {
358
+ friendId: delegatedFrom.friendId,
359
+ channel: delegatedFrom.channel,
360
+ key: delegatedFrom.key,
361
+ });
362
+ /* v8 ignore next 2 -- obligation fulfillment tested via obligations.test.ts; integration requires real disk state @preserve */
363
+ if (pending) {
364
+ (0, obligations_1.fulfillObligation)(agentRoot, pending.id);
365
+ }
366
+ }
367
+ catch {
368
+ /* v8 ignore next -- defensive: obligation store read failure should not break delivery @preserve */
369
+ }
370
+ (0, runtime_1.emitNervesEvent)({
371
+ event: "senses.obligation_fulfilled",
372
+ component: "senses",
373
+ message: "obligation fulfilled via delegated completion",
374
+ meta: {
375
+ friendId: delegatedFrom.friendId,
376
+ channel: delegatedFrom.channel,
377
+ key: delegatedFrom.key,
378
+ },
379
+ });
380
+ }
381
+ const outboundEnvelope = {
382
+ from: agentName,
383
+ friendId: delegatedFrom.friendId,
384
+ channel: delegatedFrom.channel,
385
+ key: delegatedFrom.key,
386
+ content: completion.answer.trim(),
387
+ timestamp,
388
+ delegatedFrom,
389
+ ...(obligationId ? { obligationId } : {}),
390
+ };
391
+ const sessionActivity = (0, session_activity_1.listSessionActivity)({
392
+ sessionsDir: path.join(agentRoot, "state", "sessions"),
393
+ friendsDir: path.join(agentRoot, "friends"),
394
+ agentName,
395
+ });
396
+ // Priority 1: Bridge-preferred session (if delegation was within a bridge).
397
+ const bridgeTarget = resolveBridgePreferredSession(delegatedFrom, sessionActivity);
398
+ if (bridgeTarget) {
399
+ if (await tryDeliverDelegatedCompletion(bridgeTarget, outboundEnvelope)) {
400
+ advanceObligationQuietly(agentName, obligationId, { status: "returned", returnedAt: timestamp, returnTarget: "bridge-session" });
401
+ return;
402
+ }
403
+ writePendingEnvelope((0, pending_1.getPendingDir)(agentName, bridgeTarget.friendId, bridgeTarget.channel, bridgeTarget.key), outboundEnvelope);
404
+ advanceObligationQuietly(agentName, obligationId, { status: "returned", returnedAt: timestamp, returnTarget: "bridge-session" });
405
+ return;
406
+ }
407
+ // Priority 1.5: Direct return to originating session (ponder without bridge).
408
+ // When delegatedFrom has specific channel+key, route directly there instead of searching for freshest.
409
+ if (delegatedFrom.channel && delegatedFrom.key && delegatedFrom.channel !== "inner") {
410
+ const directTarget = sessionActivity.find((a) => a.friendId === delegatedFrom.friendId && a.channel === delegatedFrom.channel && a.key === delegatedFrom.key);
411
+ if (directTarget) {
412
+ if (await tryDeliverDelegatedCompletion(directTarget, outboundEnvelope)) {
413
+ advanceObligationQuietly(agentName, obligationId, { status: "returned", returnedAt: timestamp, returnTarget: "direct-originator" });
414
+ return;
415
+ }
416
+ }
417
+ // Even if session isn't in activity list (might have ended), queue to its pending dir
418
+ writePendingEnvelope((0, pending_1.getPendingDir)(agentName, delegatedFrom.friendId, delegatedFrom.channel, delegatedFrom.key), outboundEnvelope);
419
+ advanceObligationQuietly(agentName, obligationId, { status: "returned", returnedAt: timestamp, returnTarget: "direct-originator" });
420
+ return;
421
+ }
422
+ // Priority 2: Freshest active friend session.
423
+ // For BB, prefer DM sessions (;-;) over group chats (;+;) — proactive outreach should never land in groups.
424
+ const allFriendSessions = (0, session_activity_1.listSessionActivity)({
425
+ sessionsDir: path.join(agentRoot, "state", "sessions"),
426
+ friendsDir: path.join(agentRoot, "friends"),
427
+ agentName,
428
+ }).filter((s) => s.friendId === delegatedFrom.friendId && s.channel !== "inner");
429
+ const bbDm = allFriendSessions.find((s) => s.channel === "bluebubbles" && s.key.includes(";-;"));
430
+ const freshest = bbDm ?? allFriendSessions.find((s) => s.channel !== "bluebubbles" || s.key.includes(";-;")) ?? allFriendSessions[0];
431
+ if (freshest) {
432
+ if (await tryDeliverDelegatedCompletion(freshest, outboundEnvelope)) {
433
+ advanceObligationQuietly(agentName, obligationId, { status: "returned", returnedAt: timestamp, returnTarget: "freshest-session" });
434
+ return;
435
+ }
436
+ writePendingEnvelope((0, pending_1.getPendingDir)(agentName, freshest.friendId, freshest.channel, freshest.key), outboundEnvelope);
437
+ advanceObligationQuietly(agentName, obligationId, { status: "returned", returnedAt: timestamp, returnTarget: "freshest-session" });
438
+ return;
439
+ }
440
+ // Priority 3: Deferred return queue.
441
+ writePendingEnvelope((0, pending_1.getDeferredReturnDir)(agentName, delegatedFrom.friendId), outboundEnvelope);
442
+ advanceObligationQuietly(agentName, obligationId, { status: "deferred", returnedAt: timestamp, returnTarget: "deferred" });
443
+ }
444
+ /* v8 ignore stop */
157
445
  // Self-referencing friend record for inner dialog (agent talking to itself).
158
446
  // No real friend to resolve -- this satisfies the pipeline's friend resolver contract.
159
447
  function createSelfFriend(agentName) {
@@ -180,97 +468,314 @@ function createNoOpFriendStore() {
180
468
  findByExternalId: async () => null,
181
469
  };
182
470
  }
471
+ function buildParseErrorNudge(parseErrors) {
472
+ if (parseErrors.length === 0)
473
+ return "";
474
+ const lines = parseErrors.map((e) => `I noticed my habit file \`${e.file}\` has invalid frontmatter — I should fix it. (${e.error})`);
475
+ return lines.join("\n");
476
+ }
477
+ function buildAlsoDueLine(agentRoot, currentHabitName, now) {
478
+ const habitsDir = path.join(agentRoot, "habits");
479
+ let files;
480
+ try {
481
+ files = fs.readdirSync(habitsDir);
482
+ }
483
+ catch {
484
+ return "";
485
+ }
486
+ const nowMs = now().getTime();
487
+ const alsoDue = [];
488
+ for (const file of files) {
489
+ if (!file.endsWith(".md"))
490
+ continue;
491
+ const stem = file.replace(/\.md$/, "");
492
+ if (stem === currentHabitName)
493
+ continue;
494
+ try {
495
+ const content = fs.readFileSync(path.join(habitsDir, file), "utf-8");
496
+ const habit = (0, habit_parser_1.parseHabitFile)(content, path.join(habitsDir, file));
497
+ if (habit.status !== "active" || !habit.cadence)
498
+ continue;
499
+ const cadenceMs = (0, cadence_1.parseCadenceToMs)(habit.cadence);
500
+ if (cadenceMs === null)
501
+ continue;
502
+ if (habit.lastRun === null) {
503
+ alsoDue.push(stem);
504
+ continue;
505
+ }
506
+ const lastRunMs = new Date(habit.lastRun).getTime();
507
+ if (nowMs - lastRunMs >= cadenceMs) {
508
+ alsoDue.push(stem);
509
+ }
510
+ }
511
+ catch {
512
+ // skip unreadable habits
513
+ }
514
+ }
515
+ if (alsoDue.length === 0)
516
+ return "";
517
+ return `also due: ${alsoDue.join(", ")}`;
518
+ }
183
519
  async function runInnerDialogTurn(options) {
184
520
  const now = options?.now ?? (() => new Date());
185
- const reason = options?.reason ?? "heartbeat";
521
+ const reason = options?.reason ?? "instinct";
186
522
  const sessionFilePath = innerDialogSessionPath();
187
- const loaded = (0, context_1.loadSession)(sessionFilePath);
188
- const existingMessages = loaded?.messages ? [...loaded.messages] : [];
189
- const instincts = options?.instincts ?? loadInnerDialogInstincts();
190
- const state = {
191
- cycleCount: 1,
192
- resting: false,
193
- lastHeartbeatAt: now().toISOString(),
194
- };
195
- // ── Adapter concern: build user message ──────────────────────────
196
- let userContent;
197
- if (existingMessages.length === 0) {
198
- // Fresh session: bootstrap message with non-canonical cleanup nudge
199
- const aspirations = readAspirations((0, identity_1.getAgentRoot)());
200
- const nonCanonical = (0, bundle_manifest_1.findNonCanonicalBundlePaths)((0, identity_1.getAgentRoot)());
201
- const cleanupNudge = buildNonCanonicalCleanupNudge(nonCanonical);
202
- userContent = [
203
- buildInnerDialogBootstrapMessage(aspirations, "No prior inner dialog session found."),
204
- cleanupNudge,
205
- ].filter(Boolean).join("\n\n");
206
- }
207
- else {
208
- // Resumed session: instinct message with checkpoint context
209
- const assistantTurns = existingMessages.filter((message) => message.role === "assistant").length;
210
- state.cycleCount = assistantTurns + 1;
211
- state.checkpoint = deriveResumeCheckpoint(existingMessages);
212
- userContent = buildInstinctUserMessage(instincts, reason, state);
213
- }
214
- // ── Adapter concern: inbox drain (inner-dialog-specific) ─────────
215
- const inboxMessages = options?.drainInbox?.() ?? [];
216
- if (inboxMessages.length > 0) {
217
- const section = inboxMessages
218
- .map((msg) => `- **${msg.from}**: ${msg.content}`)
219
- .join("\n");
220
- userContent = `${userContent}\n\n## incoming messages\n${section}`;
221
- }
222
- const userMessage = { role: "user", content: userContent };
223
- // ── Session loader: wraps existing session logic ──────────────────
224
- const innerCapabilities = (0, channel_1.getChannelCapabilities)("inner");
225
- const pendingDir = (0, pending_1.getInnerDialogPendingDir)((0, identity_1.getAgentName)());
226
- const selfFriend = createSelfFriend((0, identity_1.getAgentName)());
227
- const selfContext = { friend: selfFriend, channel: innerCapabilities };
228
- const sessionLoader = {
229
- loadOrCreate: async () => {
230
- if (existingMessages.length > 0) {
231
- return { messages: existingMessages, sessionPath: sessionFilePath };
232
- }
233
- // Fresh session: build system prompt
234
- const systemPrompt = await (0, prompt_1.buildSystem)("inner", { toolChoiceRequired: true });
235
- return {
236
- messages: [{ role: "system", content: systemPrompt }],
237
- sessionPath: sessionFilePath,
238
- };
239
- },
240
- };
241
- // ── Call shared pipeline ──────────────────────────────────────────
242
- const callbacks = createInnerDialogCallbacks();
243
- const traceId = (0, nerves_1.createTraceId)();
244
- const result = await (0, pipeline_1.handleInboundTurn)({
245
- channel: "inner",
246
- capabilities: innerCapabilities,
247
- messages: [userMessage],
248
- callbacks,
249
- friendResolver: { resolve: () => Promise.resolve(selfContext) },
250
- sessionLoader,
251
- pendingDir,
252
- friendStore: createNoOpFriendStore(),
253
- enforceTrustGate: trust_gate_1.enforceTrustGate,
254
- drainPending: pending_1.drainPending,
255
- runAgent: core_1.runAgent,
256
- postTurn: context_1.postTurn,
257
- accumulateFriendTokens: tokens_1.accumulateFriendTokens,
258
- signal: options?.signal,
259
- runAgentOptions: {
260
- traceId,
261
- toolChoiceRequired: true,
262
- skipConfirmation: true,
263
- },
264
- });
265
- (0, runtime_1.emitNervesEvent)({
266
- component: "senses",
267
- event: "senses.inner_dialog_turn",
268
- message: "inner dialog turn completed",
269
- meta: { reason, session: sessionFilePath },
523
+ const agentName = (0, identity_1.getAgentName)();
524
+ writeInnerDialogRuntimeState(sessionFilePath, {
525
+ status: "running",
526
+ reason,
527
+ startedAt: now().toISOString(),
270
528
  });
271
- return {
272
- messages: result.messages ?? [],
273
- usage: result.usage,
274
- sessionPath: result.sessionPath ?? sessionFilePath,
275
- };
529
+ try {
530
+ const loaded = (0, context_1.loadSession)(sessionFilePath);
531
+ const existingMessages = loaded?.messages ? [...loaded.messages] : [];
532
+ const instincts = options?.instincts ?? loadInnerDialogInstincts();
533
+ const state = {
534
+ cycleCount: 1,
535
+ resting: false,
536
+ lastHeartbeatAt: now().toISOString(),
537
+ };
538
+ // ── Adapter concern: build user message ──────────────────────────
539
+ let userContent;
540
+ let habitTools;
541
+ let habitParsedSuccessfully = false;
542
+ if (existingMessages.length === 0) {
543
+ // Fresh session: bootstrap message with non-canonical cleanup nudge
544
+ const aspirations = readAspirations((0, identity_1.getAgentRoot)());
545
+ const nonCanonical = (0, bundle_manifest_1.findNonCanonicalBundlePaths)((0, identity_1.getAgentRoot)());
546
+ const cleanupNudge = buildNonCanonicalCleanupNudge(nonCanonical);
547
+ userContent = [
548
+ buildInnerDialogBootstrapMessage(aspirations, "No prior inner dialog session found."),
549
+ cleanupNudge,
550
+ ].filter(Boolean).join("\n\n");
551
+ }
552
+ else {
553
+ // Resumed session: task-triggered or instinct message with checkpoint context
554
+ const assistantTurns = existingMessages.filter((message) => message.role === "assistant").length;
555
+ state.cycleCount = assistantTurns + 1;
556
+ state.checkpoint = deriveResumeCheckpoint(existingMessages);
557
+ if (options?.taskId) {
558
+ const taskContent = readTaskFile((0, identity_1.getAgentRoot)(), options.taskId);
559
+ userContent = buildTaskTriggeredMessage(options.taskId, taskContent, state.checkpoint);
560
+ }
561
+ else if (reason === "habit" && options?.habitName) {
562
+ const agentRoot = (0, identity_1.getAgentRoot)();
563
+ const habitName = options.habitName;
564
+ const habitFilePath = path.join(agentRoot, "habits", `${habitName}.md`);
565
+ // Read and parse the habit file
566
+ let habitBody;
567
+ let habitTitle = habitName;
568
+ let habitLastRun = null;
569
+ try {
570
+ const habitContent = fs.readFileSync(habitFilePath, "utf-8");
571
+ const parsed = (0, habit_parser_1.parseHabitFile)(habitContent, habitFilePath);
572
+ habitBody = parsed.body || undefined;
573
+ habitTitle = parsed.title || habitName;
574
+ habitLastRun = parsed.lastRun;
575
+ habitTools = parsed.tools;
576
+ }
577
+ catch {
578
+ // Habit file missing or unreadable
579
+ }
580
+ // If the habit file couldn't be read at all (no body, no title parsed), error message
581
+ if (habitBody === undefined && habitTitle === habitName) {
582
+ userContent = `habit "${habitName}" could not be read (file not found or unreadable). check habits/${habitName}.md exists.`;
583
+ }
584
+ else {
585
+ habitParsedSuccessfully = true;
586
+ // Unified path: gather context for ALL habits (heartbeat included)
587
+ const obligations = (0, obligations_1.listActiveReturnObligations)(agentName);
588
+ const nowMs = now().getTime();
589
+ const staleObligations = obligations.map((o) => ({
590
+ friendName: o.origin.friendId,
591
+ content: o.delegatedContent,
592
+ stalenessMs: nowMs - o.createdAt,
593
+ }));
594
+ const alsoDue = buildAlsoDueLine(agentRoot, habitName, now);
595
+ // Degraded state (best-effort: never crash)
596
+ let degradedComponents = [];
597
+ try {
598
+ const health = (0, daemon_health_1.readHealth)((0, daemon_health_1.getDefaultHealthPath)());
599
+ if (health && health.degraded.length > 0) {
600
+ degradedComponents = health.degraded.map((d) => ({ component: d.component, reason: d.reason }));
601
+ }
602
+ }
603
+ catch {
604
+ // Best-effort: missing file or parse error -> empty array, no crash
605
+ }
606
+ userContent = (0, habit_turn_message_1.buildHabitTurnMessage)({
607
+ habitName,
608
+ habitTitle,
609
+ habitBody,
610
+ lastRun: habitLastRun,
611
+ checkpoint: displayCheckpoint(state.checkpoint),
612
+ alsoDue: alsoDue || undefined,
613
+ staleObligations,
614
+ parseErrors: options?.parseErrors ?? [],
615
+ degradedComponents,
616
+ now,
617
+ });
618
+ // Piggyback journal embedding indexing (best-effort, fire-and-forget)
619
+ const journalDir = path.join(agentRoot, "journal");
620
+ /* v8 ignore start -- journal indexing piggyback: embedding provider may not be available; tested via journal-index unit tests @preserve */
621
+ void (0, journal_index_1.indexJournalFiles)(journalDir, path.join(journalDir, ".index.json"), {
622
+ embed: async () => [],
623
+ }).catch(() => {
624
+ // swallowed: indexing failure must never block habit turn
625
+ });
626
+ /* v8 ignore stop */
627
+ }
628
+ }
629
+ else {
630
+ userContent = buildInstinctUserMessage(instincts, reason, state);
631
+ }
632
+ }
633
+ const userMessage = { role: "user", content: userContent };
634
+ // ── Session loader: wraps existing session logic ──────────────────
635
+ const innerCapabilities = (0, channel_1.getChannelCapabilities)("inner");
636
+ const pendingDir = (0, pending_1.getInnerDialogPendingDir)(agentName);
637
+ const selfFriend = createSelfFriend(agentName);
638
+ const selfContext = { friend: selfFriend, channel: innerCapabilities };
639
+ const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)() ?? undefined;
640
+ // ── Habit tool enforcement ───────────────────────────────────────
641
+ let habitToolsResolved;
642
+ if (habitTools !== undefined) {
643
+ const fullTools = (0, tools_1.getToolsForChannel)(innerCapabilities);
644
+ habitToolsResolved = fullTools.filter((t) => habitTools.includes(t.function.name));
645
+ (0, runtime_1.emitNervesEvent)({
646
+ event: "habit.tools_restricted",
647
+ component: "senses",
648
+ message: "habit running with restricted tools",
649
+ meta: {
650
+ habitName: options?.habitName,
651
+ declared: habitTools,
652
+ resolved: habitToolsResolved.map((t) => t.function.name),
653
+ },
654
+ });
655
+ }
656
+ else if (reason === "habit" && options?.habitName && habitParsedSuccessfully) {
657
+ (0, runtime_1.emitNervesEvent)({
658
+ event: "habit.tools_unrestricted",
659
+ component: "senses",
660
+ message: "habit running with full tool repertoire",
661
+ meta: { habitName: options.habitName },
662
+ });
663
+ }
664
+ const sessionLoader = {
665
+ loadOrCreate: async () => {
666
+ if (existingMessages.length > 0) {
667
+ return {
668
+ messages: existingMessages,
669
+ sessionPath: sessionFilePath,
670
+ };
671
+ }
672
+ // Fresh session: build system prompt
673
+ const systemPrompt = await (0, prompt_1.buildSystem)("inner", { toolChoiceRequired: true });
674
+ return {
675
+ messages: [{ role: "system", content: (0, prompt_1.flattenSystemPrompt)(systemPrompt) }],
676
+ sessionPath: sessionFilePath,
677
+ };
678
+ },
679
+ };
680
+ // ── Call shared pipeline ──────────────────────────────────────────
681
+ const callbacks = createInnerDialogCallbacks();
682
+ const traceId = (0, nerves_1.createTraceId)();
683
+ // Attention queue: built when pending messages are drained, shared with tool context
684
+ let attentionQueue = [];
685
+ const result = await (0, pipeline_1.handleInboundTurn)({
686
+ channel: "inner",
687
+ sessionKey: "dialog",
688
+ capabilities: innerCapabilities,
689
+ messages: [userMessage],
690
+ continuityIngressTexts: [],
691
+ callbacks,
692
+ friendResolver: { resolve: () => Promise.resolve(selfContext) },
693
+ sessionLoader,
694
+ pendingDir,
695
+ friendStore: createNoOpFriendStore(),
696
+ enforceTrustGate: trust_gate_1.enforceTrustGate,
697
+ drainPending: pending_1.drainPending,
698
+ runAgent: core_1.runAgent,
699
+ postTurn: (turnMessages, sessionPathArg, usage, hooks, state) => {
700
+ const prepared = (0, context_1.postTurnTrim)(turnMessages, usage, hooks);
701
+ (0, context_1.deferPostTurnPersist)(sessionPathArg, prepared, usage, state);
702
+ },
703
+ accumulateFriendTokens: tokens_1.accumulateFriendTokens,
704
+ signal: options?.signal,
705
+ /* v8 ignore start -- attention queue: callback invoked by pipeline during pending drain; tested via attention-queue unit tests @preserve */
706
+ onPendingDrained: (drained) => {
707
+ const outstandingObligations = (0, obligations_1.listActiveReturnObligations)(agentName);
708
+ attentionQueue = (0, attention_queue_1.buildAttentionQueue)({
709
+ drainedPending: drained,
710
+ outstandingObligations,
711
+ friendNameResolver: (friendId) => {
712
+ try {
713
+ const raw = fs.readFileSync(path.join((0, identity_1.getAgentRoot)(agentName), "friends", friendId + ".json"), "utf-8");
714
+ const parsed = JSON.parse(raw);
715
+ return typeof parsed.name === "string" ? parsed.name : null;
716
+ }
717
+ catch {
718
+ return null;
719
+ }
720
+ },
721
+ packetResolver: (packetId) => {
722
+ try {
723
+ return (0, packets_1.readPonderPacket)((0, identity_1.getAgentRoot)(agentName), packetId);
724
+ }
725
+ catch {
726
+ return null;
727
+ }
728
+ },
729
+ });
730
+ const summary = (0, attention_queue_1.buildAttentionQueueSummary)(attentionQueue);
731
+ return summary ? [summary] : [];
732
+ },
733
+ /* v8 ignore stop */
734
+ runAgentOptions: {
735
+ traceId,
736
+ toolChoiceRequired: true,
737
+ mcpManager,
738
+ ...(habitToolsResolved !== undefined && { tools: habitToolsResolved }),
739
+ toolContext: {
740
+ signin: async () => undefined,
741
+ delegatedOrigins: attentionQueue,
742
+ },
743
+ },
744
+ });
745
+ // Post-turn routeDelegatedCompletion removed: delivery is now inline via surface tool.
746
+ // settle in inner dialog produces no CompletionMetadata, so routeDelegatedCompletion
747
+ // would be a no-op. The routing infrastructure is reused by the surface handler.
748
+ const resultMessages = result.messages ?? [];
749
+ const assistantPreview = extractAssistantPreview(resultMessages);
750
+ const toolCalls = extractToolCallNames(resultMessages);
751
+ (0, runtime_1.emitNervesEvent)({
752
+ component: "senses",
753
+ event: "senses.inner_dialog_turn",
754
+ message: "inner dialog turn completed",
755
+ meta: {
756
+ reason,
757
+ session: sessionFilePath,
758
+ ...(options?.taskId && { taskId: options.taskId }),
759
+ ...(assistantPreview && { assistantPreview }),
760
+ ...(toolCalls.length > 0 && { toolCalls }),
761
+ ...(result.usage && {
762
+ promptTokens: result.usage.input_tokens,
763
+ completionTokens: result.usage.output_tokens,
764
+ totalTokens: result.usage.total_tokens,
765
+ }),
766
+ },
767
+ });
768
+ return {
769
+ messages: resultMessages,
770
+ usage: result.usage,
771
+ sessionPath: result.sessionPath ?? sessionFilePath,
772
+ completion: result.completion,
773
+ };
774
+ }
775
+ finally {
776
+ writeInnerDialogRuntimeState(sessionFilePath, {
777
+ status: "idle",
778
+ lastCompletedAt: now().toISOString(),
779
+ });
780
+ }
276
781
  }