@ouro.bot/cli 0.1.0-alpha.18 → 0.1.0-alpha.180

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 (185) hide show
  1. package/AdoptionSpecialist.ouro/agent.json +3 -2
  2. package/AdoptionSpecialist.ouro/psyche/SOUL.md +3 -3
  3. package/AdoptionSpecialist.ouro/psyche/identities/monty.md +2 -2
  4. package/README.md +187 -191
  5. package/changelog.json +1210 -0
  6. package/dist/heart/active-work.js +633 -0
  7. package/dist/heart/bridges/manager.js +358 -0
  8. package/dist/heart/bridges/state-machine.js +135 -0
  9. package/dist/heart/bridges/store.js +123 -0
  10. package/dist/heart/commitments.js +105 -0
  11. package/dist/heart/config.js +40 -30
  12. package/dist/heart/core.js +620 -124
  13. package/dist/heart/cross-chat-delivery.js +146 -0
  14. package/dist/heart/daemon/agent-discovery.js +81 -0
  15. package/dist/heart/daemon/agent-service.js +360 -0
  16. package/dist/heart/daemon/auth-flow.js +477 -0
  17. package/dist/heart/daemon/cadence.js +70 -0
  18. package/dist/heart/daemon/daemon-cli.js +2476 -206
  19. package/dist/heart/daemon/daemon-entry.js +157 -4
  20. package/dist/heart/daemon/daemon-health.js +136 -0
  21. package/dist/heart/daemon/daemon-runtime-sync.js +212 -0
  22. package/dist/heart/daemon/daemon-tombstone.js +123 -0
  23. package/dist/heart/daemon/daemon.js +449 -17
  24. package/dist/heart/daemon/habit-migration.js +181 -0
  25. package/dist/heart/daemon/habit-parser.js +119 -0
  26. package/dist/heart/daemon/habit-scheduler.js +369 -0
  27. package/dist/heart/daemon/hatch-animation.js +10 -3
  28. package/dist/heart/daemon/hatch-flow.js +30 -111
  29. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  30. package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
  31. package/dist/heart/daemon/inner-status.js +89 -0
  32. package/dist/heart/daemon/launchd.js +165 -0
  33. package/dist/heart/daemon/log-tailer.js +4 -3
  34. package/dist/heart/daemon/mcp-server.js +591 -0
  35. package/dist/heart/daemon/message-router.js +17 -8
  36. package/dist/heart/daemon/os-cron-deps.js +134 -0
  37. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  38. package/dist/heart/daemon/ouro-path-installer.js +78 -34
  39. package/dist/heart/daemon/ouro-version-manager.js +171 -0
  40. package/dist/heart/daemon/outlook-http.js +399 -0
  41. package/dist/heart/daemon/outlook-read.js +1291 -0
  42. package/dist/heart/daemon/outlook-render.js +1032 -0
  43. package/dist/heart/daemon/outlook-types.js +7 -0
  44. package/dist/heart/daemon/outlook-view.js +194 -0
  45. package/dist/heart/daemon/process-manager.js +75 -0
  46. package/dist/heart/daemon/run-hooks.js +39 -0
  47. package/dist/heart/daemon/runtime-logging.js +58 -15
  48. package/dist/heart/daemon/runtime-metadata.js +219 -0
  49. package/dist/heart/daemon/runtime-mode.js +67 -0
  50. package/dist/heart/daemon/safe-mode.js +161 -0
  51. package/dist/heart/daemon/sense-manager.js +50 -2
  52. package/dist/heart/daemon/session-id-resolver.js +131 -0
  53. package/dist/heart/daemon/skill-management-installer.js +94 -0
  54. package/dist/heart/daemon/socket-client.js +202 -0
  55. package/dist/heart/daemon/specialist-orchestrator.js +2 -2
  56. package/dist/heart/daemon/specialist-prompt.js +13 -9
  57. package/dist/heart/daemon/specialist-tools.js +78 -9
  58. package/dist/heart/daemon/staged-restart.js +114 -0
  59. package/dist/heart/daemon/task-scheduler.js +3 -25
  60. package/dist/heart/daemon/thoughts.js +507 -0
  61. package/dist/heart/daemon/update-checker.js +111 -0
  62. package/dist/heart/daemon/update-hooks.js +138 -0
  63. package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
  64. package/dist/heart/delegation.js +62 -0
  65. package/dist/heart/identity.js +136 -55
  66. package/dist/heart/kicks.js +2 -20
  67. package/dist/heart/migrate-config.js +127 -0
  68. package/dist/heart/model-capabilities.js +48 -0
  69. package/dist/heart/obligations.js +197 -0
  70. package/dist/heart/progress-story.js +42 -0
  71. package/dist/heart/provider-failover.js +88 -0
  72. package/dist/heart/provider-ping.js +172 -0
  73. package/dist/heart/providers/anthropic-token.js +163 -0
  74. package/dist/heart/providers/anthropic.js +196 -36
  75. package/dist/heart/providers/azure.js +116 -10
  76. package/dist/heart/providers/github-copilot.js +157 -0
  77. package/dist/heart/providers/minimax.js +33 -3
  78. package/dist/heart/providers/openai-codex.js +51 -16
  79. package/dist/heart/session-activity.js +172 -0
  80. package/dist/heart/session-recall.js +216 -0
  81. package/dist/heart/streaming.js +62 -32
  82. package/dist/heart/target-resolution.js +127 -0
  83. package/dist/heart/tool-activity-callbacks.js +36 -0
  84. package/dist/heart/tool-description.js +135 -0
  85. package/dist/heart/tool-loop.js +200 -0
  86. package/dist/heart/turn-coordinator.js +28 -0
  87. package/dist/mind/associative-recall.js +122 -32
  88. package/dist/mind/bundle-manifest.js +14 -0
  89. package/dist/mind/context.js +125 -14
  90. package/dist/mind/{memory.js → diary.js} +70 -56
  91. package/dist/mind/file-state.js +179 -0
  92. package/dist/mind/first-impressions.js +16 -2
  93. package/dist/mind/friends/channel.js +56 -0
  94. package/dist/mind/friends/group-context.js +144 -0
  95. package/dist/mind/friends/store-file.js +19 -0
  96. package/dist/mind/friends/trust-explanation.js +74 -0
  97. package/dist/mind/friends/types.js +8 -0
  98. package/dist/mind/journal-index.js +161 -0
  99. package/dist/mind/obligation-steering.js +221 -0
  100. package/dist/mind/obligations.js +134 -0
  101. package/dist/mind/pending.js +76 -9
  102. package/dist/mind/phrases.js +1 -0
  103. package/dist/mind/prompt.js +721 -102
  104. package/dist/mind/scrutiny.js +173 -0
  105. package/dist/mind/token-estimate.js +8 -12
  106. package/dist/nerves/cli-logging.js +15 -2
  107. package/dist/nerves/coverage/audit.js +1 -1
  108. package/dist/nerves/coverage/run-artifacts.js +1 -1
  109. package/dist/nerves/event-buffer.js +111 -0
  110. package/dist/nerves/index.js +63 -3
  111. package/dist/nerves/observation.js +20 -0
  112. package/dist/nerves/runtime.js +5 -1
  113. package/dist/outlook-ui/assets/index-DN6vVYPm.css +1 -0
  114. package/dist/outlook-ui/assets/index-M1l1tDTX.js +61 -0
  115. package/dist/outlook-ui/index.html +15 -0
  116. package/dist/repertoire/ado-semantic.js +11 -5
  117. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  118. package/dist/repertoire/coding/context-pack.js +254 -0
  119. package/dist/repertoire/coding/feedback.js +197 -30
  120. package/dist/repertoire/coding/manager.js +149 -2
  121. package/dist/repertoire/coding/spawner.js +55 -9
  122. package/dist/repertoire/coding/tools.js +170 -7
  123. package/dist/repertoire/guardrails.js +291 -0
  124. package/dist/repertoire/mcp-client.js +254 -0
  125. package/dist/repertoire/mcp-manager.js +198 -0
  126. package/dist/repertoire/shell-sessions.js +133 -0
  127. package/dist/repertoire/skills.js +14 -23
  128. package/dist/repertoire/tasks/board.js +43 -5
  129. package/dist/repertoire/tasks/fix.js +182 -0
  130. package/dist/repertoire/tasks/index.js +28 -10
  131. package/dist/repertoire/tasks/lifecycle.js +2 -2
  132. package/dist/repertoire/tasks/parser.js +3 -2
  133. package/dist/repertoire/tasks/scanner.js +194 -37
  134. package/dist/repertoire/tasks/transitions.js +11 -28
  135. package/dist/repertoire/tools-base.js +1111 -327
  136. package/dist/repertoire/tools-bluebubbles.js +94 -0
  137. package/dist/repertoire/tools-github.js +1 -6
  138. package/dist/repertoire/tools-teams.js +12 -59
  139. package/dist/repertoire/tools.js +318 -124
  140. package/dist/scripts/claude-code-hook.js +41 -0
  141. package/dist/scripts/claude-code-stop-hook.js +47 -0
  142. package/dist/senses/attention-queue.js +97 -0
  143. package/dist/senses/bluebubbles-client.js +102 -3
  144. package/dist/senses/bluebubbles-entry.js +2 -0
  145. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  146. package/dist/senses/bluebubbles-media.js +118 -23
  147. package/dist/senses/bluebubbles-model.js +12 -4
  148. package/dist/senses/bluebubbles-mutation-log.js +45 -5
  149. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  150. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  151. package/dist/senses/bluebubbles.js +1008 -102
  152. package/dist/senses/cli/adapter.js +274 -0
  153. package/dist/senses/cli/ink-app.js +156 -0
  154. package/dist/senses/cli/inline-diff.js +64 -0
  155. package/dist/senses/cli/message-list.js +51 -0
  156. package/dist/senses/cli/ouro-tui.js +269 -0
  157. package/dist/senses/cli/spinner-imperative.js +135 -0
  158. package/dist/senses/cli/spinner.js +101 -0
  159. package/dist/senses/cli/status-line.js +60 -0
  160. package/dist/senses/cli/streaming-markdown.js +503 -0
  161. package/dist/senses/cli/tool-display.js +83 -0
  162. package/dist/senses/cli/tool-render.js +85 -0
  163. package/dist/senses/cli/tui-store.js +198 -0
  164. package/dist/senses/cli/virtual-list.js +35 -0
  165. package/dist/senses/cli-entry.js +1 -1
  166. package/dist/senses/cli-layout.js +187 -0
  167. package/dist/senses/cli.js +593 -240
  168. package/dist/senses/commands.js +38 -1
  169. package/dist/senses/continuity.js +94 -0
  170. package/dist/senses/habit-turn-message.js +108 -0
  171. package/dist/senses/inner-dialog-worker.js +112 -19
  172. package/dist/senses/inner-dialog.js +592 -84
  173. package/dist/senses/pipeline.js +545 -0
  174. package/dist/senses/shared-turn.js +196 -0
  175. package/dist/senses/surface-tool.js +95 -0
  176. package/dist/senses/teams.js +667 -120
  177. package/dist/senses/trust-gate.js +112 -2
  178. package/package.json +16 -5
  179. package/skills/configure-dev-tools.md +81 -0
  180. package/subagents/README.md +4 -70
  181. package/dist/heart/daemon/subagent-installer.js +0 -134
  182. package/dist/senses/debug-activity.js +0 -107
  183. package/subagents/work-doer.md +0 -235
  184. package/subagents/work-merger.md +0 -618
  185. package/subagents/work-planner.md +0 -382
@@ -0,0 +1,545 @@
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.handleInboundTurn = handleInboundTurn;
42
+ const runtime_1 = require("../nerves/runtime");
43
+ const commands_1 = require("./commands");
44
+ const continuity_1 = require("./continuity");
45
+ const manager_1 = require("../heart/bridges/manager");
46
+ const identity_1 = require("../heart/identity");
47
+ const tasks_1 = require("../repertoire/tasks");
48
+ const coding_1 = require("../repertoire/coding");
49
+ const session_activity_1 = require("../heart/session-activity");
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 target_resolution_1 = require("../heart/target-resolution");
54
+ const thoughts_1 = require("../heart/daemon/thoughts");
55
+ const pending_1 = require("../mind/pending");
56
+ const obligations_1 = require("../heart/obligations");
57
+ const obligations_2 = require("../mind/obligations");
58
+ const provider_failover_1 = require("../heart/provider-failover");
59
+ const provider_ping_1 = require("../heart/provider-ping");
60
+ const auth_flow_1 = require("../heart/daemon/auth-flow");
61
+ function emptyTaskBoard() {
62
+ return {
63
+ compact: "",
64
+ full: "",
65
+ byStatus: {
66
+ drafting: [],
67
+ processing: [],
68
+ validating: [],
69
+ collaborating: [],
70
+ paused: [],
71
+ blocked: [],
72
+ done: [],
73
+ cancelled: [],
74
+ },
75
+ issues: [],
76
+ actionRequired: [],
77
+ unresolvedDependencies: [],
78
+ activeSessions: [],
79
+ activeBridges: [],
80
+ };
81
+ }
82
+ function isLiveCodingSessionStatus(status) {
83
+ return status === "spawning"
84
+ || status === "running"
85
+ || status === "waiting_input"
86
+ || status === "stalled";
87
+ }
88
+ function prependTurnSections(message, sections) {
89
+ /* v8 ignore next -- defensive: only user messages with non-empty sections reach here @preserve */
90
+ if (message.role !== "user" || sections.length === 0)
91
+ return message;
92
+ const prefix = sections.join("\n\n");
93
+ /* v8 ignore start -- defensive: multipart content branch; non-string user messages are rare @preserve */
94
+ if (typeof message.content === "string") {
95
+ return {
96
+ ...message,
97
+ content: `${prefix}\n\n${message.content}`,
98
+ };
99
+ }
100
+ return {
101
+ ...message,
102
+ content: [
103
+ { type: "text", text: `${prefix}\n\n` },
104
+ ...message.content,
105
+ ],
106
+ };
107
+ /* v8 ignore stop */
108
+ }
109
+ function readInnerWorkState() {
110
+ const defaultJob = {
111
+ status: "idle",
112
+ content: null,
113
+ origin: null,
114
+ mode: "reflect",
115
+ obligationStatus: null,
116
+ surfacedResult: null,
117
+ queuedAt: null,
118
+ startedAt: null,
119
+ surfacedAt: null,
120
+ };
121
+ try {
122
+ const agentRoot = (0, identity_1.getAgentRoot)();
123
+ const pendingDir = (0, pending_1.getInnerDialogPendingDir)((0, identity_1.getAgentName)());
124
+ const sessionPath = (0, thoughts_1.getInnerDialogSessionPath)(agentRoot);
125
+ const { pendingMessages, turns, runtimeState } = (0, thoughts_1.readInnerDialogRawData)(sessionPath, pendingDir);
126
+ const dialogStatus = (0, thoughts_1.deriveInnerDialogStatus)(pendingMessages, turns, runtimeState);
127
+ const job = (0, thoughts_1.deriveInnerJob)(pendingMessages, turns, runtimeState);
128
+ // Derive obligationPending from both the pending message field and the obligation store
129
+ const storeObligationPending = (0, obligations_1.readPendingObligations)(agentRoot).length > 0;
130
+ return {
131
+ status: dialogStatus.processing === "started" ? "running" : "idle",
132
+ hasPending: dialogStatus.queue !== "clear",
133
+ origin: dialogStatus.origin,
134
+ contentSnippet: dialogStatus.contentSnippet,
135
+ obligationPending: dialogStatus.obligationPending || storeObligationPending,
136
+ job,
137
+ };
138
+ }
139
+ catch {
140
+ return {
141
+ status: "idle",
142
+ hasPending: false,
143
+ job: defaultJob,
144
+ };
145
+ }
146
+ }
147
+ // ── Pipeline ──────────────────────────────────────────────────────
148
+ let _lastSessionKey = null;
149
+ async function handleInboundTurn(input) {
150
+ // Reset session-scoped state when the session changes
151
+ const sessionKey = `${input.channel}/${input.sessionKey ?? "session"}`;
152
+ if (sessionKey !== _lastSessionKey) {
153
+ _lastSessionKey = sessionKey;
154
+ // Reset file-state cache and scrutiny tracking for the new session
155
+ const { fileStateCache } = await Promise.resolve().then(() => __importStar(require("../mind/file-state")));
156
+ const { resetSessionModifiedFiles } = await Promise.resolve().then(() => __importStar(require("../mind/scrutiny")));
157
+ fileStateCache.clear();
158
+ resetSessionModifiedFiles();
159
+ }
160
+ // Step 0: Check for pending failover reply
161
+ if (input.failoverState?.pending) {
162
+ const userText = input.messages
163
+ .filter((m) => m.role === "user")
164
+ .map((m) => typeof m.content === "string" ? m.content : /* v8 ignore next -- defensive: multipart content fallback @preserve */ "")
165
+ .join(" ")
166
+ .trim();
167
+ const pendingContext = input.failoverState.pending;
168
+ const failoverAction = (0, provider_failover_1.handleFailoverReply)(userText, pendingContext);
169
+ const failoverAgentName = pendingContext.agentName;
170
+ input.failoverState.pending = null; // always clear before acting
171
+ if (failoverAction.action === "switch") {
172
+ let switchSucceeded = false;
173
+ try {
174
+ (0, auth_flow_1.writeAgentProviderSelection)(failoverAgentName, "human", failoverAction.provider);
175
+ (0, auth_flow_1.writeAgentProviderSelection)(failoverAgentName, "agent", failoverAction.provider);
176
+ switchSucceeded = true;
177
+ /* v8 ignore start -- defensive: write failure during provider switch @preserve */
178
+ }
179
+ catch (switchError) {
180
+ (0, runtime_1.emitNervesEvent)({
181
+ level: "error",
182
+ component: "senses",
183
+ event: "senses.failover_switch_error",
184
+ message: `failed to switch provider to ${failoverAction.provider}`,
185
+ meta: { agentName: failoverAgentName, provider: failoverAction.provider, error: switchError instanceof Error ? switchError.message : String(switchError) },
186
+ });
187
+ }
188
+ /* v8 ignore stop */
189
+ /* v8 ignore next -- false branch: write-failure fallthrough @preserve */
190
+ if (switchSucceeded) {
191
+ (0, runtime_1.emitNervesEvent)({
192
+ component: "senses",
193
+ event: "senses.failover_switch",
194
+ message: `switched provider to ${failoverAction.provider} via failover`,
195
+ meta: { agentName: failoverAgentName, provider: failoverAction.provider },
196
+ });
197
+ // Replace "switch to <provider>" with a context message for the agent.
198
+ // The session already has the user's original question from the failed turn.
199
+ // The agent needs to know what happened so it can respond appropriately.
200
+ const newProviderSecrets = (() => {
201
+ try {
202
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(failoverAgentName);
203
+ const cfg = secrets.providers[failoverAction.provider];
204
+ return cfg?.model ?? cfg?.modelName ?? "";
205
+ /* v8 ignore next 2 -- defensive: secrets read failure @preserve */
206
+ }
207
+ catch {
208
+ return "";
209
+ }
210
+ })();
211
+ const newProviderLabel = newProviderSecrets ? `${failoverAction.provider} (${newProviderSecrets})` : failoverAction.provider;
212
+ input.messages = [{
213
+ role: "user",
214
+ content: `[provider switch: ${pendingContext.errorSummary}. switched to ${newProviderLabel}. your conversation history is intact — respond to the user's last message.]`,
215
+ }];
216
+ input.switchedProvider = failoverAction.provider;
217
+ }
218
+ // Switch failed OR succeeded — either way, fall through to normal processing.
219
+ }
220
+ }
221
+ // Step 0b: Slash command interception (before friend resolution / agent turn)
222
+ {
223
+ const firstUserMsg = input.messages.find((m) => m.role === "user");
224
+ const userText = firstUserMsg
225
+ ? (typeof firstUserMsg.content === "string"
226
+ ? firstUserMsg.content
227
+ : Array.isArray(firstUserMsg.content)
228
+ ? firstUserMsg.content.find((p) => p.type === "text")?.text ?? ""
229
+ : /* v8 ignore next -- defensive: content is always string or array @preserve */ "")
230
+ : "";
231
+ const parsed = (0, commands_1.parseSlashCommand)(userText);
232
+ if (parsed) {
233
+ const registry = (0, commands_1.getSharedCommandRegistry)();
234
+ const dispatchResult = registry.dispatch(parsed.command, { channel: input.channel });
235
+ if (dispatchResult.handled && dispatchResult.result) {
236
+ (0, runtime_1.emitNervesEvent)({
237
+ component: "senses",
238
+ event: "senses.pipeline_command",
239
+ message: `slash command intercepted: /${parsed.command}`,
240
+ meta: { command: parsed.command, channel: input.channel },
241
+ });
242
+ if (dispatchResult.result.message) {
243
+ input.callbacks.onTextChunk(dispatchResult.result.message);
244
+ }
245
+ // Return a minimal result — no agent turn, no session write
246
+ const resolvedContext = await input.friendResolver.resolve();
247
+ return {
248
+ resolvedContext,
249
+ gateResult: { allowed: true },
250
+ turnOutcome: "command",
251
+ commandAction: dispatchResult.result.action,
252
+ };
253
+ }
254
+ }
255
+ }
256
+ // Step 1: Resolve friend
257
+ const resolvedContext = await input.friendResolver.resolve();
258
+ (0, runtime_1.emitNervesEvent)({
259
+ component: "senses",
260
+ event: "senses.pipeline_start",
261
+ message: "inbound turn pipeline started",
262
+ meta: {
263
+ channel: input.channel,
264
+ friendId: resolvedContext.friend.id,
265
+ senseType: input.capabilities.senseType,
266
+ },
267
+ });
268
+ // Step 2: Trust gate
269
+ const gateInput = {
270
+ friend: resolvedContext.friend,
271
+ provider: input.provider ?? "local",
272
+ externalId: input.externalId ?? "",
273
+ tenantId: input.tenantId,
274
+ channel: input.channel,
275
+ senseType: input.capabilities.senseType,
276
+ isGroupChat: input.isGroupChat ?? false,
277
+ groupHasFamilyMember: input.groupHasFamilyMember ?? false,
278
+ hasExistingGroupWithFamily: input.hasExistingGroupWithFamily ?? false,
279
+ };
280
+ const gateResult = input.enforceTrustGate(gateInput);
281
+ // Gate rejection: return early, no agent turn
282
+ if (!gateResult.allowed) {
283
+ (0, runtime_1.emitNervesEvent)({
284
+ component: "senses",
285
+ event: "senses.pipeline_gate_reject",
286
+ message: "trust gate rejected inbound turn",
287
+ meta: {
288
+ channel: input.channel,
289
+ friendId: resolvedContext.friend.id,
290
+ reason: gateResult.reason,
291
+ },
292
+ });
293
+ return {
294
+ resolvedContext,
295
+ gateResult,
296
+ };
297
+ }
298
+ // Step 3: Load/create session
299
+ const session = await input.sessionLoader.loadOrCreate();
300
+ const sessionMessages = session.messages;
301
+ let mustResolveBeforeHandoff = (0, continuity_1.resolveMustResolveBeforeHandoff)(session.state?.mustResolveBeforeHandoff === true, input.continuityIngressTexts);
302
+ const lastFriendActivityAt = input.channel === "inner"
303
+ ? session.state?.lastFriendActivityAt
304
+ : new Date().toISOString();
305
+ const currentObligation = input.continuityIngressTexts
306
+ ?.map((text) => text.trim())
307
+ .filter((text) => text.length > 0)
308
+ .at(-1);
309
+ const currentSession = {
310
+ friendId: resolvedContext.friend.id,
311
+ channel: input.channel,
312
+ key: input.sessionKey ?? "session",
313
+ sessionPath: session.sessionPath,
314
+ };
315
+ const activeBridges = (0, manager_1.createBridgeManager)().findBridgesForSession({
316
+ friendId: currentSession.friendId,
317
+ channel: currentSession.channel,
318
+ key: currentSession.key,
319
+ });
320
+ const bridgeContext = (0, manager_1.formatBridgeContext)(activeBridges) || undefined;
321
+ let sessionActivity = [];
322
+ try {
323
+ const agentRoot = (0, identity_1.getAgentRoot)();
324
+ sessionActivity = (0, session_activity_1.listSessionActivity)({
325
+ sessionsDir: `${agentRoot}/state/sessions`,
326
+ friendsDir: `${agentRoot}/friends`,
327
+ agentName: (0, identity_1.getAgentName)(),
328
+ currentSession: {
329
+ friendId: currentSession.friendId,
330
+ channel: currentSession.channel,
331
+ key: currentSession.key,
332
+ },
333
+ });
334
+ }
335
+ catch {
336
+ sessionActivity = [];
337
+ }
338
+ let targetCandidates = [];
339
+ try {
340
+ if (input.channel !== "inner") {
341
+ const agentRoot = (0, identity_1.getAgentRoot)();
342
+ targetCandidates = await (0, target_resolution_1.listTargetSessionCandidates)({
343
+ sessionsDir: `${agentRoot}/state/sessions`,
344
+ friendsDir: `${agentRoot}/friends`,
345
+ agentName: (0, identity_1.getAgentName)(),
346
+ currentSession: {
347
+ friendId: currentSession.friendId,
348
+ channel: currentSession.channel,
349
+ key: currentSession.key,
350
+ },
351
+ friendStore: input.friendStore,
352
+ });
353
+ }
354
+ }
355
+ catch {
356
+ targetCandidates = [];
357
+ }
358
+ let pendingObligations = [];
359
+ try {
360
+ pendingObligations = (0, obligations_1.readPendingObligations)((0, identity_1.getAgentRoot)());
361
+ }
362
+ catch {
363
+ pendingObligations = [];
364
+ }
365
+ let codingSessions = [];
366
+ let otherCodingSessions = [];
367
+ try {
368
+ const liveCodingSessions = (0, coding_1.getCodingSessionManager)()
369
+ .listSessions()
370
+ .filter((session) => isLiveCodingSessionStatus(session.status) && Boolean(session.originSession));
371
+ codingSessions = liveCodingSessions.filter((session) => session.originSession?.friendId === currentSession.friendId
372
+ && session.originSession.channel === currentSession.channel
373
+ && session.originSession.key === currentSession.key);
374
+ otherCodingSessions = liveCodingSessions.filter((session) => !(session.originSession?.friendId === currentSession.friendId
375
+ && session.originSession.channel === currentSession.channel
376
+ && session.originSession.key === currentSession.key));
377
+ }
378
+ catch {
379
+ codingSessions = [];
380
+ otherCodingSessions = [];
381
+ }
382
+ const activeWorkFrame = (0, active_work_1.buildActiveWorkFrame)({
383
+ currentSession,
384
+ currentObligation,
385
+ mustResolveBeforeHandoff,
386
+ inner: readInnerWorkState(),
387
+ bridges: activeBridges,
388
+ codingSessions,
389
+ otherCodingSessions,
390
+ pendingObligations,
391
+ taskBoard: (() => {
392
+ try {
393
+ return (0, tasks_1.getTaskModule)().getBoard();
394
+ }
395
+ catch {
396
+ return emptyTaskBoard();
397
+ }
398
+ })(),
399
+ friendActivity: sessionActivity,
400
+ targetCandidates,
401
+ innerReturnObligations: (() => {
402
+ try {
403
+ return (0, obligations_2.listActiveObligations)((0, identity_1.getAgentName)());
404
+ }
405
+ catch {
406
+ return [];
407
+ }
408
+ })(),
409
+ });
410
+ const delegationDecision = (0, delegation_1.decideDelegation)({
411
+ channel: input.channel,
412
+ ingressTexts: input.continuityIngressTexts ?? [],
413
+ activeWork: activeWorkFrame,
414
+ mustResolveBeforeHandoff,
415
+ });
416
+ // Step 4: Drain deferred friend returns, then ordinary per-session pending.
417
+ const deferredReturns = input.channel === "inner"
418
+ ? []
419
+ : (input.drainDeferredReturns?.(resolvedContext.friend.id) ?? []);
420
+ const sessionPending = input.drainPending(input.pendingDir);
421
+ const pending = [...deferredReturns, ...sessionPending];
422
+ // Assemble messages: session messages + pending + inbound user messages
423
+ // NOTE: live world-state checkpoint and pending messages are rendered via buildSystem (system prompt sections)
424
+ const extraPrefixSections = input.onPendingDrained?.(pending) ?? [];
425
+ // extraPrefixSections from onPendingDrained still prepend to user message (e.g., inner dialog wakes)
426
+ if (extraPrefixSections.length > 0 && input.messages.length > 0) {
427
+ input.messages[0] = prependTurnSections(input.messages[0], extraPrefixSections);
428
+ }
429
+ // Append user messages from the inbound turn
430
+ for (const msg of input.messages) {
431
+ sessionMessages.push(msg);
432
+ }
433
+ // Step 5: runAgent
434
+ const existingToolContext = input.runAgentOptions?.toolContext;
435
+ const runAgentOptions = {
436
+ ...input.runAgentOptions,
437
+ bridgeContext,
438
+ activeWorkFrame,
439
+ delegationDecision,
440
+ pendingMessages: pending.length > 0 ? pending.map((msg) => ({ from: msg.from, content: msg.content })) : undefined,
441
+ currentSessionKey: currentSession.key,
442
+ currentObligation,
443
+ mustResolveBeforeHandoff,
444
+ setMustResolveBeforeHandoff: (value) => {
445
+ mustResolveBeforeHandoff = value;
446
+ },
447
+ toolContext: {
448
+ /* v8 ignore next -- default no-op signin satisfies interface; real signin injected by sense adapter @preserve */
449
+ signin: async () => undefined,
450
+ ...existingToolContext,
451
+ context: resolvedContext,
452
+ friendStore: input.friendStore,
453
+ currentSession,
454
+ activeBridges,
455
+ },
456
+ };
457
+ const result = await input.runAgent(sessionMessages, input.callbacks, input.channel, input.signal, runAgentOptions);
458
+ // Step 5b: Failover on terminal error
459
+ if (result.outcome === "errored" && input.failoverState) {
460
+ try {
461
+ const agentName = (0, identity_1.getAgentName)();
462
+ const agentConfig = (0, identity_1.loadAgentConfig)();
463
+ const currentProvider = agentConfig.humanFacing.provider;
464
+ /* v8 ignore next -- defensive: errorClassification always set when errored @preserve */
465
+ const classification = result.errorClassification ?? "unknown";
466
+ const inventory = await (0, provider_ping_1.runHealthInventory)(agentName, currentProvider);
467
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(agentName);
468
+ const providerModels = {};
469
+ for (const [p, cfg] of Object.entries(secrets.providers)) {
470
+ const model = cfg.model ?? cfg.modelName;
471
+ if (typeof model === "string" && model)
472
+ providerModels[p] = model;
473
+ }
474
+ /* v8 ignore next -- defensive: current provider always in secrets @preserve */
475
+ const currentModel = providerModels[currentProvider] ?? "";
476
+ const failoverContext = (0, provider_failover_1.buildFailoverContext)(
477
+ /* v8 ignore next -- defensive: error always set when errored @preserve */
478
+ result.error?.message ?? "unknown error", classification, currentProvider, currentModel, agentName, inventory, providerModels);
479
+ input.failoverState.pending = failoverContext;
480
+ input.postTurn(sessionMessages, session.sessionPath, result.usage);
481
+ return {
482
+ resolvedContext,
483
+ gateResult,
484
+ usage: result.usage,
485
+ turnOutcome: result.outcome,
486
+ sessionPath: session.sessionPath,
487
+ messages: sessionMessages,
488
+ drainedPending: pending,
489
+ failoverMessage: failoverContext.userMessage,
490
+ };
491
+ /* v8 ignore start -- failover catch: tested via pipeline failover sequence throws test but v8 under-reports catch coverage @preserve */
492
+ }
493
+ catch (failoverError) {
494
+ (0, runtime_1.emitNervesEvent)({
495
+ level: "warn",
496
+ component: "senses",
497
+ event: "senses.failover_error",
498
+ message: "failover sequence failed, falling through",
499
+ meta: { error: failoverError instanceof Error ? failoverError.message : String(failoverError) },
500
+ });
501
+ }
502
+ /* v8 ignore stop */
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
+ }