@ouro.bot/cli 0.1.0-alpha.17 → 0.1.0-alpha.171

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