@ouro.bot/cli 0.1.0-alpha.28 → 0.1.0-alpha.280

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 (267) hide show
  1. package/README.md +187 -191
  2. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +3 -2
  3. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +1 -1
  4. package/changelog.json +1696 -0
  5. package/dist/arc/attention-types.js +8 -0
  6. package/dist/arc/cares.js +140 -0
  7. package/dist/arc/episodes.js +117 -0
  8. package/dist/arc/intentions.js +133 -0
  9. package/dist/arc/json-store.js +117 -0
  10. package/dist/arc/obligations.js +237 -0
  11. package/dist/arc/presence.js +185 -0
  12. package/dist/heart/active-work.js +832 -0
  13. package/dist/heart/agent-entry.js +37 -2
  14. package/dist/heart/auth/auth-flow.js +456 -0
  15. package/dist/heart/bridges/manager.js +358 -0
  16. package/dist/heart/bridges/state-machine.js +135 -0
  17. package/dist/heart/bridges/store.js +123 -0
  18. package/dist/heart/commitments.js +111 -0
  19. package/dist/heart/config-registry.js +304 -0
  20. package/dist/heart/config.js +63 -30
  21. package/dist/heart/core.js +644 -196
  22. package/dist/heart/cross-chat-delivery.js +131 -0
  23. package/dist/heart/daemon/agent-config-check.js +149 -0
  24. package/dist/heart/daemon/agent-discovery.js +79 -3
  25. package/dist/heart/daemon/agent-service.js +360 -0
  26. package/dist/heart/daemon/cadence.js +70 -0
  27. package/dist/heart/daemon/cli-defaults.js +574 -0
  28. package/dist/heart/daemon/cli-exec.js +1932 -0
  29. package/dist/heart/daemon/cli-parse.js +762 -0
  30. package/dist/heart/daemon/cli-render.js +503 -0
  31. package/dist/heart/daemon/cli-types.js +8 -0
  32. package/dist/heart/daemon/daemon-cli.js +29 -1155
  33. package/dist/heart/daemon/daemon-entry.js +234 -3
  34. package/dist/heart/daemon/daemon-health.js +136 -0
  35. package/dist/heart/daemon/daemon-runtime-sync.js +153 -12
  36. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  37. package/dist/heart/daemon/daemon.js +702 -57
  38. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  39. package/dist/heart/daemon/hooks/bundle-meta.js +115 -1
  40. package/dist/heart/daemon/inner-status.js +89 -0
  41. package/dist/heart/daemon/launchd.js +46 -9
  42. package/dist/heart/daemon/log-tailer.js +82 -12
  43. package/dist/heart/daemon/logs-prune.js +105 -0
  44. package/dist/heart/daemon/message-router.js +17 -8
  45. package/dist/heart/daemon/os-cron-deps.js +134 -0
  46. package/dist/heart/daemon/ouro-bot-entry.js +1 -1
  47. package/dist/heart/daemon/process-manager.js +180 -0
  48. package/dist/heart/daemon/pulse.js +463 -0
  49. package/dist/heart/daemon/run-hooks.js +2 -0
  50. package/dist/heart/daemon/runtime-logging.js +67 -16
  51. package/dist/heart/daemon/runtime-metadata.js +101 -0
  52. package/dist/heart/daemon/runtime-mode.js +67 -0
  53. package/dist/heart/daemon/safe-mode.js +161 -0
  54. package/dist/heart/daemon/sense-manager.js +72 -3
  55. package/dist/heart/daemon/session-id-resolver.js +131 -0
  56. package/dist/heart/daemon/skill-management-installer.js +94 -0
  57. package/dist/heart/daemon/socket-client.js +307 -0
  58. package/dist/heart/daemon/task-scheduler.js +3 -25
  59. package/dist/heart/daemon/thoughts.js +510 -0
  60. package/dist/heart/delegation.js +62 -0
  61. package/dist/heart/habits/habit-migration.js +181 -0
  62. package/dist/heart/habits/habit-parser.js +119 -0
  63. package/dist/heart/habits/habit-scheduler.js +371 -0
  64. package/dist/heart/{daemon → hatch}/hatch-flow.js +30 -120
  65. package/dist/heart/{daemon → hatch}/hatch-specialist.js +3 -3
  66. package/dist/heart/{daemon → hatch}/specialist-prompt.js +10 -7
  67. package/dist/heart/{daemon → hatch}/specialist-tools.js +49 -3
  68. package/dist/heart/identity.js +163 -60
  69. package/dist/heart/kicks.js +2 -20
  70. package/dist/heart/mcp/mcp-server.js +653 -0
  71. package/dist/heart/migrate-config.js +127 -0
  72. package/dist/heart/model-capabilities.js +59 -0
  73. package/dist/heart/outlook/outlook-http.js +439 -0
  74. package/dist/heart/outlook/outlook-read.js +1618 -0
  75. package/dist/heart/outlook/outlook-render.js +1032 -0
  76. package/dist/heart/outlook/outlook-types.js +7 -0
  77. package/dist/heart/outlook/outlook-view.js +194 -0
  78. package/dist/heart/progress-story.js +42 -0
  79. package/dist/heart/provider-failover.js +88 -0
  80. package/dist/heart/provider-ping.js +162 -0
  81. package/dist/heart/providers/anthropic-token.js +163 -0
  82. package/dist/heart/providers/anthropic.js +169 -46
  83. package/dist/heart/providers/azure.js +98 -11
  84. package/dist/heart/providers/error-classification.js +63 -0
  85. package/dist/heart/providers/github-copilot.js +136 -0
  86. package/dist/heart/providers/minimax-vlm.js +189 -0
  87. package/dist/heart/providers/minimax.js +23 -5
  88. package/dist/heart/providers/openai-codex.js +33 -22
  89. package/dist/heart/session-activity.js +172 -0
  90. package/dist/heart/session-recall.js +216 -0
  91. package/dist/heart/start-of-turn-packet.js +330 -0
  92. package/dist/heart/streaming.js +36 -27
  93. package/dist/heart/sync.js +277 -0
  94. package/dist/heart/target-resolution.js +127 -0
  95. package/dist/heart/tempo.js +93 -0
  96. package/dist/heart/temporal-view.js +41 -0
  97. package/dist/heart/tool-activity-callbacks.js +36 -0
  98. package/dist/heart/tool-description.js +135 -0
  99. package/dist/heart/tool-loop.js +200 -0
  100. package/dist/heart/turn-context.js +358 -0
  101. package/dist/heart/turn-coordinator.js +28 -0
  102. package/dist/heart/versioning/ouro-bot-global-installer.js +128 -0
  103. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  104. package/dist/heart/{daemon → versioning}/ouro-path-installer.js +78 -35
  105. package/dist/heart/versioning/ouro-version-manager.js +295 -0
  106. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  107. package/dist/heart/{daemon → versioning}/update-checker.js +12 -2
  108. package/dist/heart/{daemon → versioning}/update-hooks.js +63 -59
  109. package/dist/mind/associative-recall.js +126 -66
  110. package/dist/mind/bundle-manifest.js +8 -1
  111. package/dist/mind/context.js +125 -14
  112. package/dist/mind/{memory.js → diary.js} +68 -96
  113. package/dist/mind/embedding-provider.js +60 -0
  114. package/dist/mind/file-state.js +179 -0
  115. package/dist/mind/first-impressions.js +14 -1
  116. package/dist/mind/friends/channel.js +56 -0
  117. package/dist/mind/friends/group-context.js +144 -0
  118. package/dist/mind/friends/resolver.js +37 -0
  119. package/dist/mind/friends/store-file.js +58 -3
  120. package/dist/mind/friends/trust-explanation.js +74 -0
  121. package/dist/mind/friends/types.js +8 -0
  122. package/dist/mind/journal-index.js +161 -0
  123. package/dist/mind/obligation-steering.js +221 -0
  124. package/dist/mind/pending.js +76 -9
  125. package/dist/mind/prompt.js +874 -109
  126. package/dist/mind/scrutiny.js +173 -0
  127. package/dist/mind/token-estimate.js +8 -12
  128. package/dist/nerves/cli-logging.js +7 -1
  129. package/dist/nerves/coverage/audit.js +1 -1
  130. package/dist/nerves/coverage/file-completeness.js +50 -5
  131. package/dist/nerves/coverage/run-artifacts.js +1 -1
  132. package/dist/nerves/event-buffer.js +111 -0
  133. package/dist/nerves/index.js +220 -4
  134. package/dist/nerves/observation.js +20 -0
  135. package/dist/nerves/runtime.js +5 -1
  136. package/dist/outlook-ui/assets/index-Ck8agNeO.js +61 -0
  137. package/dist/outlook-ui/assets/index-LwChZTgL.css +1 -0
  138. package/dist/outlook-ui/index.html +15 -0
  139. package/dist/repertoire/ado-client.js +15 -56
  140. package/dist/repertoire/ado-semantic.js +11 -10
  141. package/dist/repertoire/api-client.js +97 -0
  142. package/dist/repertoire/bitwarden-store.js +319 -0
  143. package/dist/repertoire/bw-installer.js +79 -0
  144. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  145. package/dist/repertoire/coding/context-pack.js +330 -0
  146. package/dist/repertoire/coding/feedback.js +197 -30
  147. package/dist/repertoire/coding/manager.js +149 -2
  148. package/dist/repertoire/coding/spawner.js +55 -9
  149. package/dist/repertoire/coding/tools.js +170 -7
  150. package/dist/repertoire/commerce-errors.js +109 -0
  151. package/dist/repertoire/commerce-self-test.js +156 -0
  152. package/dist/repertoire/credential-access.js +515 -0
  153. package/dist/repertoire/duffel-client.js +185 -0
  154. package/dist/repertoire/github-client.js +14 -55
  155. package/dist/repertoire/graph-client.js +11 -52
  156. package/dist/repertoire/guardrails.js +369 -0
  157. package/dist/repertoire/mcp-client.js +255 -0
  158. package/dist/repertoire/mcp-manager.js +305 -0
  159. package/dist/repertoire/mcp-tools.js +63 -0
  160. package/dist/repertoire/shell-sessions.js +133 -0
  161. package/dist/repertoire/skills.js +14 -23
  162. package/dist/repertoire/stripe-client.js +131 -0
  163. package/dist/repertoire/tasks/board.js +43 -5
  164. package/dist/repertoire/tasks/fix.js +182 -0
  165. package/dist/repertoire/tasks/index.js +28 -10
  166. package/dist/repertoire/tasks/lifecycle.js +2 -2
  167. package/dist/repertoire/tasks/parser.js +3 -2
  168. package/dist/repertoire/tasks/scanner.js +194 -37
  169. package/dist/repertoire/tasks/transitions.js +11 -28
  170. package/dist/repertoire/tools-base.js +43 -771
  171. package/dist/repertoire/tools-bluebubbles.js +201 -0
  172. package/dist/repertoire/tools-bridge.js +141 -0
  173. package/dist/repertoire/tools-config.js +185 -0
  174. package/dist/repertoire/tools-continuity.js +248 -0
  175. package/dist/repertoire/tools-credential.js +182 -0
  176. package/dist/repertoire/tools-files.js +342 -0
  177. package/dist/repertoire/tools-flight.js +224 -0
  178. package/dist/repertoire/tools-flow.js +62 -0
  179. package/dist/repertoire/tools-github.js +1 -7
  180. package/dist/repertoire/tools-memory.js +347 -0
  181. package/dist/repertoire/tools-session.js +739 -0
  182. package/dist/repertoire/tools-shell.js +120 -0
  183. package/dist/repertoire/tools-stripe.js +180 -0
  184. package/dist/repertoire/tools-surface.js +243 -0
  185. package/dist/repertoire/tools-teams.js +12 -62
  186. package/dist/repertoire/tools-travel.js +125 -0
  187. package/dist/repertoire/tools-user-profile.js +144 -0
  188. package/dist/repertoire/tools-vault.js +110 -0
  189. package/dist/repertoire/tools.js +155 -130
  190. package/dist/repertoire/travel-api-client.js +360 -0
  191. package/dist/repertoire/user-profile.js +118 -0
  192. package/dist/repertoire/vault-setup.js +241 -0
  193. package/dist/scripts/claude-code-hook.js +41 -0
  194. package/dist/scripts/claude-code-stop-hook.js +47 -0
  195. package/dist/senses/attention-queue.js +97 -0
  196. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  197. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +143 -9
  198. package/dist/senses/bluebubbles/entry.js +13 -0
  199. package/dist/senses/bluebubbles/inbound-log.js +110 -0
  200. package/dist/senses/bluebubbles/index.js +1410 -0
  201. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +140 -23
  202. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +20 -5
  203. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +46 -6
  204. package/dist/senses/bluebubbles/runtime-state.js +109 -0
  205. package/dist/senses/bluebubbles/session-cleanup.js +72 -0
  206. package/dist/senses/cli/bracketed-paste.js +82 -0
  207. package/dist/senses/cli/image-paste.js +211 -0
  208. package/dist/senses/cli/image-ref-navigation.js +75 -0
  209. package/dist/senses/cli/ink-app.js +156 -0
  210. package/dist/senses/cli/inline-diff.js +64 -0
  211. package/dist/senses/cli/input-keys.js +174 -0
  212. package/dist/senses/cli/kill-ring.js +86 -0
  213. package/dist/senses/cli/message-list.js +51 -0
  214. package/dist/senses/cli/ouro-tui.js +595 -0
  215. package/dist/senses/cli/spinner-imperative.js +135 -0
  216. package/dist/senses/cli/spinner.js +101 -0
  217. package/dist/senses/cli/status-line.js +60 -0
  218. package/dist/senses/cli/streaming-markdown.js +526 -0
  219. package/dist/senses/cli/tool-display.js +83 -0
  220. package/dist/senses/cli/tool-render.js +85 -0
  221. package/dist/senses/cli/tui-store.js +240 -0
  222. package/dist/senses/cli/virtual-list.js +35 -0
  223. package/dist/senses/cli-entry.js +1 -1
  224. package/dist/senses/cli-layout.js +187 -0
  225. package/dist/senses/cli.js +569 -246
  226. package/dist/senses/commands.js +65 -1
  227. package/dist/senses/continuity.js +94 -0
  228. package/dist/senses/habit-turn-message.js +108 -0
  229. package/dist/senses/inner-dialog-worker.js +112 -19
  230. package/dist/senses/inner-dialog.js +593 -85
  231. package/dist/senses/pipeline.js +552 -0
  232. package/dist/senses/shared-turn.js +199 -0
  233. package/dist/senses/surface-tool.js +68 -0
  234. package/dist/senses/teams.js +664 -165
  235. package/dist/senses/trust-gate.js +112 -2
  236. package/package.json +14 -7
  237. package/skills/agent-commerce.md +106 -0
  238. package/skills/browser-navigation.md +110 -0
  239. package/skills/commerce-setup-guide.md +116 -0
  240. package/skills/commerce-setup.md +84 -0
  241. package/skills/configure-dev-tools.md +81 -0
  242. package/skills/travel-planning.md +138 -0
  243. package/dist/heart/daemon/subagent-installer.js +0 -134
  244. package/dist/senses/bluebubbles-entry.js +0 -11
  245. package/dist/senses/bluebubbles.js +0 -421
  246. package/dist/senses/debug-activity.js +0 -108
  247. package/subagents/README.md +0 -73
  248. package/subagents/work-doer.md +0 -235
  249. package/subagents/work-merger.md +0 -618
  250. package/subagents/work-planner.md +0 -382
  251. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  252. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  253. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  254. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  255. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  256. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  257. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  258. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  259. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  260. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  261. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  262. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +0 -0
  263. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  264. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  265. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  266. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  267. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -0,0 +1,552 @@
1
+ "use strict";
2
+ // Shared per-turn pipeline for all senses.
3
+ // Senses are thin transport adapters; this module owns the common lifecycle:
4
+ // resolve friend -> trust gate -> load session -> drain pending -> runAgent -> postTurn -> token accumulation.
5
+ //
6
+ // Transport-level concerns (BB API calls, Teams cards, readline) stay in sense adapters.
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.emitObligationTransitionEpisodes = emitObligationTransitionEpisodes;
42
+ exports.handleInboundTurn = handleInboundTurn;
43
+ const fs = __importStar(require("fs"));
44
+ const path = __importStar(require("path"));
45
+ const runtime_1 = require("../nerves/runtime");
46
+ const commands_1 = require("./commands");
47
+ const continuity_1 = require("./continuity");
48
+ const manager_1 = require("../heart/bridges/manager");
49
+ const identity_1 = require("../heart/identity");
50
+ const socket_client_1 = require("../heart/daemon/socket-client");
51
+ const active_work_1 = require("../heart/active-work");
52
+ const delegation_1 = require("../heart/delegation");
53
+ const obligations_1 = require("../arc/obligations");
54
+ const provider_failover_1 = require("../heart/provider-failover");
55
+ const provider_ping_1 = require("../heart/provider-ping");
56
+ const auth_flow_1 = require("../heart/auth/auth-flow");
57
+ const tempo_1 = require("../heart/tempo");
58
+ const temporal_view_1 = require("../heart/temporal-view");
59
+ const start_of_turn_packet_1 = require("../heart/start-of-turn-packet");
60
+ const sync_1 = require("../heart/sync");
61
+ const config_1 = require("../heart/config");
62
+ const presence_1 = require("../arc/presence");
63
+ const episodes_1 = require("../arc/episodes");
64
+ const turn_context_1 = require("../heart/turn-context");
65
+ /**
66
+ * Emit episodes for obligation state transitions detected during a turn.
67
+ * Exported for direct testability (avoids v8 coverage merge issues in multi-file test suites).
68
+ */
69
+ function emitObligationTransitionEpisodes(agentRoot, preTurnObligationIds, postTurnObligations, preTurnObligations) {
70
+ const postTurnObligationIds = new Set(postTurnObligations.map((ob) => `${ob.id}:${ob.status}`));
71
+ for (const key of preTurnObligationIds) {
72
+ if (!postTurnObligationIds.has(key)) {
73
+ const [obId] = key.split(":");
74
+ const matchedOb = postTurnObligations.find((ob) => ob.id === obId) ?? preTurnObligations.find((ob) => ob.id === obId);
75
+ (0, episodes_1.emitEpisode)(agentRoot, {
76
+ kind: "obligation_shift",
77
+ summary: `obligation "${matchedOb?.content ?? obId}" status changed`,
78
+ whyItMattered: "obligation state transition detected during turn",
79
+ relatedEntities: [`obligation:${obId}`],
80
+ salience: "medium",
81
+ });
82
+ }
83
+ }
84
+ }
85
+ function prependTurnSections(message, sections) {
86
+ /* v8 ignore next -- defensive: only user messages with non-empty sections reach here @preserve */
87
+ if (message.role !== "user" || sections.length === 0)
88
+ return message;
89
+ const prefix = sections.join("\n\n");
90
+ /* v8 ignore start -- defensive: multipart content branch; non-string user messages are rare @preserve */
91
+ if (typeof message.content === "string") {
92
+ return {
93
+ ...message,
94
+ content: `${prefix}\n\n${message.content}`,
95
+ };
96
+ }
97
+ return {
98
+ ...message,
99
+ content: [
100
+ { type: "text", text: `${prefix}\n\n` },
101
+ ...message.content,
102
+ ],
103
+ };
104
+ /* v8 ignore stop */
105
+ }
106
+ // ── Pipeline ──────────────────────────────────────────────────────
107
+ let _lastSessionKey = null;
108
+ async function handleInboundTurn(input) {
109
+ // Reset session-scoped state when the session changes
110
+ const sessionKey = `${input.channel}/${input.sessionKey ?? "session"}`;
111
+ if (sessionKey !== _lastSessionKey) {
112
+ _lastSessionKey = sessionKey;
113
+ // Reset file-state cache and scrutiny tracking for the new session
114
+ const { fileStateCache } = await Promise.resolve().then(() => __importStar(require("../mind/file-state")));
115
+ const { resetSessionModifiedFiles } = await Promise.resolve().then(() => __importStar(require("../mind/scrutiny")));
116
+ fileStateCache.clear();
117
+ resetSessionModifiedFiles();
118
+ }
119
+ // Step 0: Check for pending failover reply
120
+ if (input.failoverState?.pending) {
121
+ const userText = input.messages
122
+ .filter((m) => m.role === "user")
123
+ .map((m) => typeof m.content === "string" ? m.content : /* v8 ignore next -- defensive: multipart content fallback @preserve */ "")
124
+ .join(" ")
125
+ .trim();
126
+ const pendingContext = input.failoverState.pending;
127
+ const failoverAction = (0, provider_failover_1.handleFailoverReply)(userText, pendingContext);
128
+ const failoverAgentName = pendingContext.agentName;
129
+ input.failoverState.pending = null; // always clear before acting
130
+ if (failoverAction.action === "switch") {
131
+ let switchSucceeded = false;
132
+ try {
133
+ (0, auth_flow_1.writeAgentProviderSelection)(failoverAgentName, "human", failoverAction.provider);
134
+ (0, auth_flow_1.writeAgentProviderSelection)(failoverAgentName, "agent", failoverAction.provider);
135
+ switchSucceeded = true;
136
+ /* v8 ignore start -- defensive: write failure during provider switch @preserve */
137
+ }
138
+ catch (switchError) {
139
+ (0, runtime_1.emitNervesEvent)({
140
+ level: "error",
141
+ component: "senses",
142
+ event: "senses.failover_switch_error",
143
+ message: `failed to switch provider to ${failoverAction.provider}`,
144
+ meta: { agentName: failoverAgentName, provider: failoverAction.provider, error: switchError instanceof Error ? switchError.message : String(switchError) },
145
+ });
146
+ }
147
+ /* v8 ignore stop */
148
+ /* v8 ignore next -- false branch: write-failure fallthrough @preserve */
149
+ if (switchSucceeded) {
150
+ (0, runtime_1.emitNervesEvent)({
151
+ component: "senses",
152
+ event: "senses.failover_switch",
153
+ message: `switched provider to ${failoverAction.provider} via failover`,
154
+ meta: { agentName: failoverAgentName, provider: failoverAction.provider },
155
+ });
156
+ // Replace "switch to <provider>" with a context message for the agent.
157
+ // The session already has the user's original question from the failed turn.
158
+ // The agent needs to know what happened so it can respond appropriately.
159
+ const newProviderSecrets = (() => {
160
+ try {
161
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(failoverAgentName);
162
+ const cfg = secrets.providers[failoverAction.provider];
163
+ return cfg?.model ?? cfg?.modelName ?? "";
164
+ /* v8 ignore next 2 -- defensive: secrets read failure @preserve */
165
+ }
166
+ catch {
167
+ return "";
168
+ }
169
+ })();
170
+ const newProviderLabel = newProviderSecrets ? `${failoverAction.provider} (${newProviderSecrets})` : failoverAction.provider;
171
+ input.messages = [{
172
+ role: "user",
173
+ content: `[provider switch: ${pendingContext.errorSummary}. switched to ${newProviderLabel}. your conversation history is intact — respond to the user's last message.]`,
174
+ }];
175
+ input.switchedProvider = failoverAction.provider;
176
+ }
177
+ // Switch failed OR succeeded — either way, fall through to normal processing.
178
+ }
179
+ }
180
+ // Step 0b: Slash command interception (before friend resolution / agent turn)
181
+ {
182
+ const firstUserMsg = input.messages.find((m) => m.role === "user");
183
+ const userText = firstUserMsg
184
+ ? (typeof firstUserMsg.content === "string"
185
+ ? firstUserMsg.content
186
+ : Array.isArray(firstUserMsg.content)
187
+ ? firstUserMsg.content.find((p) => p.type === "text")?.text ?? ""
188
+ : /* v8 ignore next -- defensive: content is always string or array @preserve */ "")
189
+ : "";
190
+ const parsed = (0, commands_1.parseSlashCommand)(userText);
191
+ if (parsed) {
192
+ const registry = (0, commands_1.getSharedCommandRegistry)();
193
+ const dispatchResult = registry.dispatch(parsed.command, { channel: input.channel });
194
+ if (dispatchResult.handled && dispatchResult.result) {
195
+ (0, runtime_1.emitNervesEvent)({
196
+ component: "senses",
197
+ event: "senses.pipeline_command",
198
+ message: `slash command intercepted: /${parsed.command}`,
199
+ meta: { command: parsed.command, channel: input.channel },
200
+ });
201
+ if (dispatchResult.result.message) {
202
+ input.callbacks.onTextChunk(dispatchResult.result.message);
203
+ }
204
+ // Return a minimal result — no agent turn, no session write
205
+ const resolvedContext = await input.friendResolver.resolve();
206
+ return {
207
+ resolvedContext,
208
+ gateResult: { allowed: true },
209
+ turnOutcome: "command",
210
+ commandAction: dispatchResult.result.action,
211
+ };
212
+ }
213
+ }
214
+ }
215
+ // Step 1: Resolve friend
216
+ const resolvedContext = await input.friendResolver.resolve();
217
+ (0, runtime_1.emitNervesEvent)({
218
+ component: "senses",
219
+ event: "senses.pipeline_start",
220
+ message: "inbound turn pipeline started",
221
+ meta: {
222
+ channel: input.channel,
223
+ friendId: resolvedContext.friend.id,
224
+ senseType: input.capabilities.senseType,
225
+ },
226
+ });
227
+ // Step 2: Trust gate
228
+ const gateInput = {
229
+ friend: resolvedContext.friend,
230
+ provider: input.provider ?? "local",
231
+ externalId: input.externalId ?? "",
232
+ tenantId: input.tenantId,
233
+ channel: input.channel,
234
+ senseType: input.capabilities.senseType,
235
+ isGroupChat: input.isGroupChat ?? false,
236
+ groupHasFamilyMember: input.groupHasFamilyMember ?? false,
237
+ hasExistingGroupWithFamily: input.hasExistingGroupWithFamily ?? false,
238
+ };
239
+ const gateResult = input.enforceTrustGate(gateInput);
240
+ // Gate rejection: return early, no agent turn
241
+ if (!gateResult.allowed) {
242
+ (0, runtime_1.emitNervesEvent)({
243
+ component: "senses",
244
+ event: "senses.pipeline_gate_reject",
245
+ message: "trust gate rejected inbound turn",
246
+ meta: {
247
+ channel: input.channel,
248
+ friendId: resolvedContext.friend.id,
249
+ reason: gateResult.reason,
250
+ },
251
+ });
252
+ return {
253
+ resolvedContext,
254
+ gateResult,
255
+ };
256
+ }
257
+ // Step 3: Load/create session
258
+ const session = await input.sessionLoader.loadOrCreate();
259
+ const sessionMessages = session.messages;
260
+ let mustResolveBeforeHandoff = (0, continuity_1.resolveMustResolveBeforeHandoff)(session.state?.mustResolveBeforeHandoff === true, input.continuityIngressTexts);
261
+ const lastFriendActivityAt = input.channel === "inner"
262
+ ? session.state?.lastFriendActivityAt
263
+ : new Date().toISOString();
264
+ const currentObligation = input.continuityIngressTexts
265
+ ?.map((text) => text.trim())
266
+ .filter((text) => text.length > 0)
267
+ .at(-1);
268
+ const currentSession = {
269
+ friendId: resolvedContext.friend.id,
270
+ channel: input.channel,
271
+ key: input.sessionKey ?? "session",
272
+ sessionPath: session.sessionPath,
273
+ };
274
+ // Step 3b: Pre-turn sync pull (opt-in) — MUST happen before any continuity state reads
275
+ // so that obligations, episodes, cares, etc. reflect the latest remote state.
276
+ let syncFailure;
277
+ let syncConfig = { enabled: false, remote: "origin" };
278
+ try {
279
+ syncConfig = (0, config_1.getSyncConfig)();
280
+ }
281
+ catch { /* config not available */ }
282
+ // Wrap the turn body in try/finally so postTurnPush always runs — even on
283
+ // error or early-return failover paths.
284
+ try {
285
+ /* v8 ignore start -- sync-enabled branches tested in sync.test.ts, pipeline tests mock at module boundary @preserve */
286
+ if (syncConfig.enabled) {
287
+ const pullResult = (0, sync_1.preTurnPull)((0, identity_1.getAgentRoot)(), syncConfig);
288
+ if (!pullResult.ok) {
289
+ syncFailure = pullResult.error;
290
+ }
291
+ // Check for pending-sync from a prior failed push
292
+ if (!syncFailure) {
293
+ const pendingSyncPath = path.join((0, identity_1.getAgentRoot)(), "state", "pending-sync.json");
294
+ try {
295
+ if (fs.existsSync(pendingSyncPath)) {
296
+ const pendingSync = JSON.parse(fs.readFileSync(pendingSyncPath, "utf-8"));
297
+ syncFailure = `prior sync push failed: ${pendingSync.error ?? "unknown"}`;
298
+ fs.unlinkSync(pendingSyncPath);
299
+ }
300
+ }
301
+ catch {
302
+ // Ignore read errors for pending-sync
303
+ }
304
+ }
305
+ }
306
+ /* v8 ignore stop */
307
+ // Build the turn context snapshot — centralizes all state reads
308
+ const ctx = await (0, turn_context_1.buildTurnContext)({
309
+ currentSession,
310
+ channel: input.channel,
311
+ friendStore: input.friendStore,
312
+ });
313
+ // Propagate sync failure from pre-turn pull
314
+ ctx.syncFailure = syncFailure;
315
+ const { activeBridges, sessionActivity, pendingObligations, codingSessions, otherCodingSessions } = ctx;
316
+ const bridgeContext = (0, manager_1.formatBridgeContext)(activeBridges) || undefined;
317
+ const activeWorkFrame = (0, active_work_1.buildActiveWorkFrame)({
318
+ currentSession,
319
+ currentObligation,
320
+ mustResolveBeforeHandoff,
321
+ inner: ctx.innerWorkState,
322
+ bridges: activeBridges,
323
+ codingSessions,
324
+ otherCodingSessions,
325
+ pendingObligations,
326
+ taskBoard: ctx.taskBoard,
327
+ friendActivity: sessionActivity,
328
+ targetCandidates: ctx.targetCandidates,
329
+ innerReturnObligations: ctx.returnObligations,
330
+ });
331
+ const delegationDecision = (0, delegation_1.decideDelegation)({
332
+ channel: input.channel,
333
+ ingressTexts: input.continuityIngressTexts ?? [],
334
+ activeWork: activeWorkFrame,
335
+ mustResolveBeforeHandoff,
336
+ });
337
+ // Step 4: Drain deferred friend returns, then ordinary per-session pending.
338
+ const deferredReturns = input.channel === "inner"
339
+ ? []
340
+ : (input.drainDeferredReturns?.(resolvedContext.friend.id) ?? []);
341
+ const sessionPending = input.drainPending(input.pendingDir);
342
+ const pending = [...deferredReturns, ...sessionPending];
343
+ // Assemble messages: session messages + pending + inbound user messages
344
+ // NOTE: live world-state checkpoint and pending messages are rendered via buildSystem (system prompt sections)
345
+ const extraPrefixSections = input.onPendingDrained?.(pending) ?? [];
346
+ // extraPrefixSections from onPendingDrained still prepend to user message (e.g., inner dialog wakes)
347
+ if (extraPrefixSections.length > 0 && input.messages.length > 0) {
348
+ input.messages[0] = prependTurnSections(input.messages[0], extraPrefixSections);
349
+ }
350
+ // Append user messages from the inbound turn
351
+ for (const msg of input.messages) {
352
+ sessionMessages.push(msg);
353
+ }
354
+ // Step 4b: Continuity pipeline — derive tempo, build start-of-turn packet, snapshot obligations
355
+ let renderedStartOfTurnPacket;
356
+ const preTurnObligationIds = new Set(pendingObligations.map((ob) => `${ob.id}:${ob.status}`));
357
+ try {
358
+ const agentRoot = (0, identity_1.getAgentRoot)();
359
+ const agentName = (0, identity_1.getAgentName)();
360
+ const { recentEpisodes, activeCares } = ctx;
361
+ const tempoState = (0, tempo_1.deriveTempo)({
362
+ activeSessions: sessionActivity.length + 1,
363
+ openObligations: pendingObligations.length,
364
+ recentEpisodeCount: recentEpisodes.length,
365
+ lastActivityAgeMs: sessionActivity.length > 0
366
+ ? Date.now() - new Date(sessionActivity[0].lastActivityAt).getTime()
367
+ : 0,
368
+ hasBlockers: false, // obligations use specific statuses, not "blocked"
369
+ highSalienceEpisodes: recentEpisodes.filter((ep) => ep.salience === "high" || ep.salience === "critical").length,
370
+ activeCareCount: activeCares.length,
371
+ atRiskCareCount: activeCares.filter((c) => c.currentRisk != null).length,
372
+ });
373
+ const temporalView = (0, temporal_view_1.buildTemporalView)(agentRoot, {
374
+ tempo: tempoState.mode,
375
+ preloaded: {
376
+ recentEpisodes,
377
+ activeObligations: pendingObligations,
378
+ activeCares,
379
+ },
380
+ });
381
+ const startOfTurnPacket = (0, start_of_turn_packet_1.buildStartOfTurnPacket)(temporalView, {
382
+ canonicalObligations: {
383
+ primary: activeWorkFrame.primaryObligation,
384
+ all: activeWorkFrame.pendingObligations,
385
+ },
386
+ });
387
+ /* v8 ignore next 3 -- syncFailure propagation tested in sync.test.ts @preserve */
388
+ if (syncFailure) {
389
+ startOfTurnPacket.syncFailure = syncFailure;
390
+ }
391
+ const capabilities = (0, start_of_turn_packet_1.buildCapabilitiesSection)(agentRoot);
392
+ if (capabilities) {
393
+ startOfTurnPacket.capabilities = capabilities;
394
+ }
395
+ renderedStartOfTurnPacket = (0, start_of_turn_packet_1.renderStartOfTurnPacket)(startOfTurnPacket);
396
+ if (!renderedStartOfTurnPacket)
397
+ renderedStartOfTurnPacket = undefined;
398
+ // Update self-presence
399
+ const presence = (0, presence_1.derivePresence)(agentRoot, agentName, {
400
+ activeSessions: sessionActivity.length + 1,
401
+ openObligations: pendingObligations.length,
402
+ activeBridges: activeBridges.length,
403
+ codingLanes: codingSessions.length,
404
+ currentTempo: tempoState.mode,
405
+ });
406
+ (0, presence_1.writePresence)(agentRoot, agentName, presence);
407
+ }
408
+ catch (continuityError) {
409
+ (0, runtime_1.emitNervesEvent)({
410
+ level: "warn",
411
+ component: "senses",
412
+ event: "senses.continuity_error",
413
+ message: "continuity pipeline failed, continuing without start-of-turn packet",
414
+ meta: { error: continuityError instanceof Error ? continuityError.message : String(continuityError) },
415
+ });
416
+ }
417
+ // Step 5: runAgent
418
+ const existingToolContext = input.runAgentOptions?.toolContext;
419
+ const runAgentOptions = {
420
+ ...input.runAgentOptions,
421
+ bridgeContext,
422
+ activeWorkFrame,
423
+ delegationDecision,
424
+ startOfTurnPacket: renderedStartOfTurnPacket,
425
+ pendingMessages: pending.length > 0 ? pending.map((msg) => ({ from: msg.from, content: msg.content })) : undefined,
426
+ currentSessionKey: currentSession.key,
427
+ currentObligation,
428
+ mustResolveBeforeHandoff,
429
+ setMustResolveBeforeHandoff: (value) => {
430
+ mustResolveBeforeHandoff = value;
431
+ },
432
+ // Pre-read state from TurnContext for prompt assembly
433
+ daemonRunning: ctx.daemonRunning,
434
+ senseStatusLines: ctx.senseStatusLines,
435
+ bundleMeta: ctx.bundleMeta,
436
+ daemonHealth: ctx.daemonHealth,
437
+ journalFiles: ctx.journalFiles,
438
+ toolContext: {
439
+ /* v8 ignore next -- default no-op signin satisfies interface; real signin injected by sense adapter @preserve */
440
+ signin: async () => undefined,
441
+ ...existingToolContext,
442
+ context: resolvedContext,
443
+ friendStore: input.friendStore,
444
+ currentSession,
445
+ activeBridges,
446
+ },
447
+ };
448
+ const result = await input.runAgent(sessionMessages, input.callbacks, input.channel, input.signal, runAgentOptions);
449
+ // Step 5b: Failover on terminal error
450
+ if (result.outcome === "errored" && input.failoverState) {
451
+ try {
452
+ const agentName = (0, identity_1.getAgentName)();
453
+ const agentConfig = (0, identity_1.loadAgentConfig)();
454
+ const currentProvider = agentConfig.humanFacing.provider;
455
+ /* v8 ignore next -- defensive: errorClassification always set when errored @preserve */
456
+ const classification = result.errorClassification ?? "unknown";
457
+ const inventory = await (0, provider_ping_1.runHealthInventory)(agentName, currentProvider);
458
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(agentName);
459
+ const providerModels = {};
460
+ for (const [p, cfg] of Object.entries(secrets.providers)) {
461
+ const model = cfg.model ?? cfg.modelName;
462
+ if (typeof model === "string" && model)
463
+ providerModels[p] = model;
464
+ }
465
+ // Use agent.json model (source of truth), not secrets model (may be stale)
466
+ const currentModel = agentConfig.humanFacing.model;
467
+ const failoverContext = (0, provider_failover_1.buildFailoverContext)(
468
+ /* v8 ignore next -- defensive: error always set when errored @preserve */
469
+ result.error?.message ?? "unknown error", classification, currentProvider, currentModel, agentName, inventory, providerModels);
470
+ input.failoverState.pending = failoverContext;
471
+ input.postTurn(sessionMessages, session.sessionPath, result.usage);
472
+ return {
473
+ resolvedContext,
474
+ gateResult,
475
+ usage: result.usage,
476
+ turnOutcome: result.outcome,
477
+ sessionPath: session.sessionPath,
478
+ messages: sessionMessages,
479
+ drainedPending: pending,
480
+ failoverMessage: failoverContext.userMessage,
481
+ };
482
+ /* v8 ignore start -- failover catch: tested via pipeline failover sequence throws test but v8 under-reports catch coverage @preserve */
483
+ }
484
+ catch (failoverError) {
485
+ (0, runtime_1.emitNervesEvent)({
486
+ level: "warn",
487
+ component: "senses",
488
+ event: "senses.failover_error",
489
+ message: "failover sequence failed, falling through",
490
+ meta: { error: failoverError instanceof Error ? failoverError.message : String(failoverError) },
491
+ });
492
+ }
493
+ /* v8 ignore stop */
494
+ }
495
+ // Step 5c: Emit episodes for obligation state transitions
496
+ try {
497
+ const agentRoot = (0, identity_1.getAgentRoot)();
498
+ const postTurnObligations = (0, obligations_1.readPendingObligations)(agentRoot);
499
+ emitObligationTransitionEpisodes(agentRoot, preTurnObligationIds, postTurnObligations, pendingObligations);
500
+ }
501
+ catch {
502
+ // Episode emission is non-fatal
503
+ }
504
+ // Step 6: postTurn
505
+ const continuingState = {
506
+ ...(mustResolveBeforeHandoff ? { mustResolveBeforeHandoff: true } : {}),
507
+ ...(typeof lastFriendActivityAt === "string" ? { lastFriendActivityAt } : {}),
508
+ };
509
+ const nextState = result.outcome === "settled" || result.outcome === "blocked" || result.outcome === "superseded" || result.outcome === "observed"
510
+ ? (typeof lastFriendActivityAt === "string"
511
+ ? { lastFriendActivityAt }
512
+ : undefined)
513
+ : (Object.keys(continuingState).length > 0 ? continuingState : undefined);
514
+ input.postTurn(sessionMessages, session.sessionPath, result.usage, undefined, nextState);
515
+ // Step 7: Token accumulation
516
+ await input.accumulateFriendTokens(input.friendStore, resolvedContext.friend.id, result.usage);
517
+ (0, runtime_1.emitNervesEvent)({
518
+ component: "senses",
519
+ event: "senses.pipeline_end",
520
+ message: "inbound turn pipeline completed",
521
+ meta: {
522
+ channel: input.channel,
523
+ friendId: resolvedContext.friend.id,
524
+ },
525
+ });
526
+ // DRY cross-session awareness: notify inner dialog that activity happened on another channel
527
+ // Inner dialog's next checkpoint will include this session's state
528
+ if (input.channel !== "inner") {
529
+ try {
530
+ (0, socket_client_1.requestInnerWake)((0, identity_1.getAgentName)()).catch(/* v8 ignore next */ () => { });
531
+ }
532
+ catch { /* getAgentName may fail in test environments */ }
533
+ }
534
+ return {
535
+ resolvedContext,
536
+ gateResult,
537
+ usage: result.usage,
538
+ turnOutcome: result.outcome,
539
+ completion: result.completion,
540
+ sessionPath: session.sessionPath,
541
+ messages: sessionMessages,
542
+ drainedPending: pending,
543
+ ...(input.switchedProvider ? { switchedProvider: input.switchedProvider } : {}),
544
+ };
545
+ }
546
+ finally {
547
+ // Step 6b: Post-turn sync push (opt-in, git-status-based discovery).
548
+ if (syncConfig.enabled) {
549
+ (0, sync_1.postTurnPush)((0, identity_1.getAgentRoot)(), syncConfig);
550
+ }
551
+ }
552
+ }