@ouro.bot/cli 0.1.0-alpha.8 → 0.1.0-alpha.80

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 (127) hide show
  1. package/AdoptionSpecialist.ouro/agent.json +70 -9
  2. package/AdoptionSpecialist.ouro/psyche/SOUL.md +5 -2
  3. package/AdoptionSpecialist.ouro/psyche/identities/monty.md +2 -2
  4. package/README.md +147 -205
  5. package/assets/ouroboros.png +0 -0
  6. package/changelog.json +462 -0
  7. package/dist/heart/active-work.js +218 -0
  8. package/dist/heart/bridges/manager.js +358 -0
  9. package/dist/heart/bridges/state-machine.js +135 -0
  10. package/dist/heart/bridges/store.js +123 -0
  11. package/dist/heart/commitments.js +89 -0
  12. package/dist/heart/config.js +68 -23
  13. package/dist/heart/core.js +452 -93
  14. package/dist/heart/cross-chat-delivery.js +146 -0
  15. package/dist/heart/daemon/agent-discovery.js +81 -0
  16. package/dist/heart/daemon/auth-flow.js +430 -0
  17. package/dist/heart/daemon/daemon-cli.js +1746 -247
  18. package/dist/heart/daemon/daemon-entry.js +55 -6
  19. package/dist/heart/daemon/daemon-runtime-sync.js +212 -0
  20. package/dist/heart/daemon/daemon.js +216 -10
  21. package/dist/heart/daemon/hatch-animation.js +10 -3
  22. package/dist/heart/daemon/hatch-flow.js +7 -82
  23. package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
  24. package/dist/heart/daemon/launchd.js +159 -0
  25. package/dist/heart/daemon/log-tailer.js +4 -3
  26. package/dist/heart/daemon/message-router.js +17 -8
  27. package/dist/heart/daemon/ouro-bot-entry.js +0 -0
  28. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  29. package/dist/heart/daemon/ouro-entry.js +0 -0
  30. package/dist/heart/daemon/ouro-path-installer.js +260 -0
  31. package/dist/heart/daemon/ouro-uti.js +11 -2
  32. package/dist/heart/daemon/ouro-version-manager.js +164 -0
  33. package/dist/heart/daemon/process-manager.js +14 -1
  34. package/dist/heart/daemon/run-hooks.js +37 -0
  35. package/dist/heart/daemon/runtime-logging.js +58 -15
  36. package/dist/heart/daemon/runtime-metadata.js +219 -0
  37. package/dist/heart/daemon/runtime-mode.js +67 -0
  38. package/dist/heart/daemon/sense-manager.js +307 -0
  39. package/dist/heart/daemon/skill-management-installer.js +94 -0
  40. package/dist/heart/daemon/socket-client.js +202 -0
  41. package/dist/heart/daemon/specialist-orchestrator.js +53 -84
  42. package/dist/heart/daemon/specialist-prompt.js +63 -11
  43. package/dist/heart/daemon/specialist-tools.js +211 -60
  44. package/dist/heart/daemon/staged-restart.js +114 -0
  45. package/dist/heart/daemon/thoughts.js +507 -0
  46. package/dist/heart/daemon/update-checker.js +111 -0
  47. package/dist/heart/daemon/update-hooks.js +138 -0
  48. package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
  49. package/dist/heart/delegation.js +62 -0
  50. package/dist/heart/identity.js +126 -21
  51. package/dist/heart/kicks.js +1 -19
  52. package/dist/heart/model-capabilities.js +48 -0
  53. package/dist/heart/obligations.js +141 -0
  54. package/dist/heart/progress-story.js +42 -0
  55. package/dist/heart/providers/anthropic.js +74 -9
  56. package/dist/heart/providers/azure.js +86 -7
  57. package/dist/heart/providers/github-copilot.js +149 -0
  58. package/dist/heart/providers/minimax.js +4 -0
  59. package/dist/heart/providers/openai-codex.js +12 -3
  60. package/dist/heart/safe-workspace.js +228 -0
  61. package/dist/heart/sense-truth.js +61 -0
  62. package/dist/heart/session-activity.js +169 -0
  63. package/dist/heart/session-recall.js +116 -0
  64. package/dist/heart/streaming.js +100 -22
  65. package/dist/heart/target-resolution.js +123 -0
  66. package/dist/heart/turn-coordinator.js +28 -0
  67. package/dist/mind/associative-recall.js +14 -2
  68. package/dist/mind/bundle-manifest.js +70 -0
  69. package/dist/mind/context.js +27 -11
  70. package/dist/mind/first-impressions.js +16 -2
  71. package/dist/mind/friends/channel.js +35 -0
  72. package/dist/mind/friends/group-context.js +144 -0
  73. package/dist/mind/friends/store-file.js +19 -0
  74. package/dist/mind/friends/trust-explanation.js +74 -0
  75. package/dist/mind/friends/types.js +8 -0
  76. package/dist/mind/memory.js +27 -26
  77. package/dist/mind/pending.js +76 -9
  78. package/dist/mind/phrases.js +1 -0
  79. package/dist/mind/prompt.js +445 -77
  80. package/dist/mind/token-estimate.js +8 -12
  81. package/dist/nerves/cli-logging.js +15 -2
  82. package/dist/nerves/coverage/run-artifacts.js +1 -1
  83. package/dist/nerves/index.js +12 -0
  84. package/dist/repertoire/ado-client.js +4 -2
  85. package/dist/repertoire/coding/feedback.js +134 -0
  86. package/dist/repertoire/coding/index.js +4 -1
  87. package/dist/repertoire/coding/manager.js +62 -4
  88. package/dist/repertoire/coding/spawner.js +3 -3
  89. package/dist/repertoire/coding/tools.js +41 -2
  90. package/dist/repertoire/data/ado-endpoints.json +188 -0
  91. package/dist/repertoire/guardrails.js +290 -0
  92. package/dist/repertoire/mcp-client.js +254 -0
  93. package/dist/repertoire/mcp-manager.js +195 -0
  94. package/dist/repertoire/skills.js +3 -26
  95. package/dist/repertoire/tasks/board.js +12 -0
  96. package/dist/repertoire/tasks/index.js +23 -9
  97. package/dist/repertoire/tasks/transitions.js +1 -2
  98. package/dist/repertoire/tools-base.js +686 -251
  99. package/dist/repertoire/tools-bluebubbles.js +93 -0
  100. package/dist/repertoire/tools-teams.js +58 -25
  101. package/dist/repertoire/tools.js +95 -53
  102. package/dist/senses/bluebubbles-client.js +210 -5
  103. package/dist/senses/bluebubbles-entry.js +2 -0
  104. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  105. package/dist/senses/bluebubbles-media.js +339 -0
  106. package/dist/senses/bluebubbles-model.js +12 -4
  107. package/dist/senses/bluebubbles-mutation-log.js +45 -5
  108. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  109. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  110. package/dist/senses/bluebubbles.js +894 -45
  111. package/dist/senses/cli-layout.js +187 -0
  112. package/dist/senses/cli.js +405 -156
  113. package/dist/senses/continuity.js +94 -0
  114. package/dist/senses/debug-activity.js +154 -0
  115. package/dist/senses/inner-dialog-worker.js +47 -18
  116. package/dist/senses/inner-dialog.js +377 -83
  117. package/dist/senses/pipeline.js +307 -0
  118. package/dist/senses/teams.js +573 -129
  119. package/dist/senses/trust-gate.js +112 -2
  120. package/package.json +14 -3
  121. package/subagents/README.md +4 -70
  122. package/dist/heart/daemon/specialist-session.js +0 -142
  123. package/dist/heart/daemon/subagent-installer.js +0 -125
  124. package/dist/inner-worker-entry.js +0 -4
  125. package/subagents/work-doer.md +0 -233
  126. package/subagents/work-merger.md +0 -624
  127. package/subagents/work-planner.md +0 -373
@@ -37,8 +37,11 @@ exports.loadInnerDialogInstincts = loadInnerDialogInstincts;
37
37
  exports.buildInnerDialogBootstrapMessage = buildInnerDialogBootstrapMessage;
38
38
  exports.buildNonCanonicalCleanupNudge = buildNonCanonicalCleanupNudge;
39
39
  exports.buildInstinctUserMessage = buildInstinctUserMessage;
40
+ exports.readTaskFile = readTaskFile;
41
+ exports.buildTaskTriggeredMessage = buildTaskTriggeredMessage;
40
42
  exports.deriveResumeCheckpoint = deriveResumeCheckpoint;
41
43
  exports.innerDialogSessionPath = innerDialogSessionPath;
44
+ exports.enrichDelegatedFromWithBridge = enrichDelegatedFromWithBridge;
42
45
  exports.runInnerDialogTurn = runInnerDialogTurn;
43
46
  const fs = __importStar(require("fs"));
44
47
  const path = __importStar(require("path"));
@@ -47,13 +50,23 @@ const core_1 = require("../heart/core");
47
50
  const identity_1 = require("../heart/identity");
48
51
  const context_1 = require("../mind/context");
49
52
  const prompt_1 = require("../mind/prompt");
53
+ const mcp_manager_1 = require("../repertoire/mcp-manager");
50
54
  const bundle_manifest_1 = require("../mind/bundle-manifest");
55
+ const pending_1 = require("../mind/pending");
56
+ const channel_1 = require("../mind/friends/channel");
57
+ const trust_gate_1 = require("./trust-gate");
58
+ const tokens_1 = require("../mind/friends/tokens");
59
+ const pipeline_1 = require("./pipeline");
51
60
  const nerves_1 = require("../nerves");
52
61
  const runtime_1 = require("../nerves/runtime");
62
+ const manager_1 = require("../heart/bridges/manager");
63
+ const session_activity_1 = require("../heart/session-activity");
64
+ const bluebubbles_1 = require("./bluebubbles");
65
+ const obligations_1 = require("../heart/obligations");
53
66
  const DEFAULT_INNER_DIALOG_INSTINCTS = [
54
67
  {
55
68
  id: "heartbeat_checkin",
56
- prompt: "Heartbeat instinct: check what changed, review priorities, and decide whether to keep resting or act.",
69
+ prompt: "...time passing. anything stirring?",
57
70
  enabled: true,
58
71
  },
59
72
  ];
@@ -69,18 +82,15 @@ function loadInnerDialogInstincts() {
69
82
  return [...DEFAULT_INNER_DIALOG_INSTINCTS];
70
83
  }
71
84
  function buildInnerDialogBootstrapMessage(aspirations, stateSummary) {
72
- const aspirationText = aspirations || "No explicit aspirations file found. Reflect and define what matters next.";
73
- return [
74
- "Inner dialog boot.",
75
- "",
76
- "## aspirations",
77
- aspirationText,
78
- "",
79
- "## current state",
80
- stateSummary,
81
- "",
82
- "Orient yourself, decide what to do next, and make meaningful progress.",
83
- ].join("\n");
85
+ const lines = ["waking up."];
86
+ if (aspirations) {
87
+ lines.push("", "## what matters to me", aspirations);
88
+ }
89
+ if (stateSummary) {
90
+ lines.push("", "## what i know so far", stateSummary);
91
+ }
92
+ lines.push("", "what needs my attention?");
93
+ return lines.join("\n");
84
94
  }
85
95
  function buildNonCanonicalCleanupNudge(nonCanonicalPaths) {
86
96
  if (nonCanonicalPaths.length === 0)
@@ -95,17 +105,41 @@ function buildNonCanonicalCleanupNudge(nonCanonicalPaths) {
95
105
  ...listed,
96
106
  ].join("\n");
97
107
  }
98
- function buildInstinctUserMessage(instincts, reason, state) {
108
+ function buildInstinctUserMessage(instincts, _reason, state) {
99
109
  const active = instincts.find((instinct) => instinct.enabled !== false) ?? DEFAULT_INNER_DIALOG_INSTINCTS[0];
100
- const checkpoint = state.checkpoint?.trim() || "no prior checkpoint recorded";
101
- return [
102
- active.prompt,
103
- `reason: ${reason}`,
104
- `cycle: ${state.cycleCount}`,
105
- `resting: ${state.resting ? "yes" : "no"}`,
106
- `checkpoint: ${checkpoint}`,
107
- "resume_instruction: continue from the checkpoint if still valid; otherwise revise and proceed.",
108
- ].join("\n");
110
+ const checkpoint = state.checkpoint?.trim();
111
+ const lines = [active.prompt];
112
+ if (checkpoint) {
113
+ lines.push(`\nlast i remember: ${checkpoint}`);
114
+ }
115
+ return lines.join("\n");
116
+ }
117
+ function readTaskFile(agentRoot, taskId) {
118
+ // Task files live in collection subdirectories (one-shots, ongoing, habits).
119
+ // Try each collection, then fall back to root tasks/ for legacy layout.
120
+ const collections = ["one-shots", "ongoing", "habits", ""];
121
+ for (const collection of collections) {
122
+ try {
123
+ return fs.readFileSync(path.join(agentRoot, "tasks", collection, `${taskId}.md`), "utf8").trim();
124
+ }
125
+ catch {
126
+ // not in this collection — try next
127
+ }
128
+ }
129
+ return "";
130
+ }
131
+ function buildTaskTriggeredMessage(taskId, taskContent, checkpoint) {
132
+ const lines = ["a task needs my attention."];
133
+ if (taskContent) {
134
+ lines.push("", `## task: ${taskId}`, taskContent);
135
+ }
136
+ else {
137
+ lines.push("", `## task: ${taskId}`, "(task file not found)");
138
+ }
139
+ if (checkpoint) {
140
+ lines.push("", `last i remember: ${checkpoint}`);
141
+ }
142
+ return lines.join("\n");
109
143
  }
110
144
  function contentToText(content) {
111
145
  if (typeof content === "string")
@@ -144,11 +178,39 @@ function deriveResumeCheckpoint(messages) {
144
178
  const firstLine = assistantText
145
179
  .split("\n")
146
180
  .map((line) => line.trim())
147
- .filter((line) => line.length > 0)[0];
181
+ .find((line) => line.length > 0);
182
+ /* v8 ignore next -- unreachable: contentToText().trim() guarantees a non-empty line @preserve */
183
+ if (!firstLine)
184
+ return "no prior checkpoint recorded";
148
185
  if (firstLine.length <= 220)
149
186
  return firstLine;
150
187
  return `${firstLine.slice(0, 217)}...`;
151
188
  }
189
+ function extractAssistantPreview(messages, maxLength = 120) {
190
+ const lastAssistant = [...messages].reverse().find((m) => m.role === "assistant");
191
+ if (!lastAssistant)
192
+ return "";
193
+ const text = contentToText(lastAssistant.content);
194
+ if (!text)
195
+ return "";
196
+ /* v8 ignore next -- unreachable: contentToText().trim() guarantees a non-empty line @preserve */
197
+ const firstLine = text.split("\n").find((line) => line.trim().length > 0) ?? "";
198
+ if (firstLine.length <= maxLength)
199
+ return firstLine;
200
+ return `${firstLine.slice(0, maxLength - 3)}...`;
201
+ }
202
+ function extractToolCallNames(messages) {
203
+ const names = [];
204
+ for (const msg of messages) {
205
+ if (msg.role === "assistant" && "tool_calls" in msg && Array.isArray(msg.tool_calls)) {
206
+ for (const tc of msg.tool_calls) {
207
+ if ("function" in tc && tc.function?.name)
208
+ names.push(tc.function.name);
209
+ }
210
+ }
211
+ }
212
+ return [...new Set(names)];
213
+ }
152
214
  function createInnerDialogCallbacks() {
153
215
  return {
154
216
  onModelStart: () => { },
@@ -161,71 +223,303 @@ function createInnerDialogCallbacks() {
161
223
  };
162
224
  }
163
225
  function innerDialogSessionPath() {
164
- return (0, config_1.sessionPath)("self", "inner", "dialog");
226
+ return (0, config_1.sessionPath)(pending_1.INNER_DIALOG_PENDING.friendId, pending_1.INNER_DIALOG_PENDING.channel, pending_1.INNER_DIALOG_PENDING.key);
165
227
  }
166
- async function runInnerDialogTurn(options) {
167
- const now = options?.now ?? (() => new Date());
168
- const reason = options?.reason ?? "heartbeat";
169
- const sessionFilePath = innerDialogSessionPath();
170
- const loaded = (0, context_1.loadSession)(sessionFilePath);
171
- const messages = loaded?.messages ? [...loaded.messages] : [];
172
- const instincts = options?.instincts ?? loadInnerDialogInstincts();
173
- const state = {
174
- cycleCount: 1,
175
- resting: false,
176
- lastHeartbeatAt: now().toISOString(),
177
- };
178
- if (messages.length === 0) {
179
- const systemPrompt = await (0, prompt_1.buildSystem)("cli", { toolChoiceRequired: true });
180
- messages.push({ role: "system", content: systemPrompt });
181
- const aspirations = readAspirations((0, identity_1.getAgentRoot)());
182
- const nonCanonical = (0, bundle_manifest_1.findNonCanonicalBundlePaths)((0, identity_1.getAgentRoot)());
183
- const cleanupNudge = buildNonCanonicalCleanupNudge(nonCanonical);
184
- const bootstrapMessage = [
185
- buildInnerDialogBootstrapMessage(aspirations, "No prior inner dialog session found."),
186
- cleanupNudge,
187
- ].filter(Boolean).join("\n\n");
188
- messages.push({ role: "user", content: bootstrapMessage });
228
+ function innerDialogRuntimeStatePath(sessionFilePath) {
229
+ return path.join(path.dirname(sessionFilePath), "runtime.json");
230
+ }
231
+ function writeInnerDialogRuntimeState(sessionFilePath, state) {
232
+ const filePath = innerDialogRuntimeStatePath(sessionFilePath);
233
+ try {
234
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
235
+ fs.writeFileSync(filePath, JSON.stringify(state, null, 2) + "\n", "utf8");
189
236
  }
190
- else {
191
- const assistantTurns = messages.filter((message) => message.role === "assistant").length;
192
- state.cycleCount = assistantTurns + 1;
193
- state.checkpoint = deriveResumeCheckpoint(messages);
194
- const instinctPrompt = buildInstinctUserMessage(instincts, reason, state);
195
- messages.push({ role: "user", content: instinctPrompt });
196
- }
197
- const inboxMessages = options?.drainInbox?.() ?? [];
198
- if (inboxMessages.length > 0) {
199
- const lastUserIdx = messages.length - 1;
200
- const lastUser = messages[lastUserIdx];
201
- /* v8 ignore next -- defensive: all code paths push a user message before here @preserve */
202
- if (lastUser?.role === "user" && typeof lastUser.content === "string") {
203
- const section = inboxMessages
204
- .map((msg) => `- **${msg.from}**: ${msg.content}`)
205
- .join("\n");
206
- messages[lastUserIdx] = {
207
- ...lastUser,
208
- content: `${lastUser.content}\n\n## incoming messages\n${section}`,
209
- };
237
+ catch (error) {
238
+ (0, runtime_1.emitNervesEvent)({
239
+ level: "warn",
240
+ component: "senses",
241
+ event: "senses.inner_dialog_runtime_state_error",
242
+ message: "failed to write inner dialog runtime state",
243
+ meta: {
244
+ status: state.status,
245
+ reason: state.reason ?? null,
246
+ path: filePath,
247
+ /* v8 ignore next -- Node fs APIs throw Error objects for mkdirSync/writeFileSync failures @preserve */
248
+ error: error instanceof Error ? error.message : String(error),
249
+ },
250
+ });
251
+ }
252
+ }
253
+ function writePendingEnvelope(pendingDir, message) {
254
+ fs.mkdirSync(pendingDir, { recursive: true });
255
+ const fileName = `${message.timestamp}-${Math.random().toString(36).slice(2, 10)}.json`;
256
+ const filePath = path.join(pendingDir, fileName);
257
+ fs.writeFileSync(filePath, JSON.stringify(message, null, 2), "utf8");
258
+ }
259
+ function sessionMatchesActivity(activity, session) {
260
+ return activity.friendId === session.friendId
261
+ && activity.channel === session.channel
262
+ && activity.key === session.key;
263
+ }
264
+ function resolveBridgePreferredSession(delegatedFrom, sessionActivity) {
265
+ if (!delegatedFrom.bridgeId)
266
+ return null;
267
+ const bridge = (0, manager_1.createBridgeManager)().getBridge(delegatedFrom.bridgeId);
268
+ if (!bridge || bridge.lifecycle === "completed" || bridge.lifecycle === "cancelled") {
269
+ return null;
270
+ }
271
+ return sessionActivity.find((activity) => activity.friendId === delegatedFrom.friendId
272
+ && activity.channel !== "inner"
273
+ && bridge.attachedSessions.some((session) => sessionMatchesActivity(activity, session))) ?? null;
274
+ }
275
+ async function tryDeliverDelegatedCompletion(target, outboundEnvelope) {
276
+ if (target.channel !== "bluebubbles") {
277
+ return false;
278
+ }
279
+ const result = await (0, bluebubbles_1.sendProactiveBlueBubblesMessageToSession)({
280
+ friendId: target.friendId,
281
+ sessionKey: target.key,
282
+ text: outboundEnvelope.content,
283
+ });
284
+ return result.delivered;
285
+ }
286
+ function enrichDelegatedFromWithBridge(delegatedFrom) {
287
+ if (delegatedFrom.bridgeId) {
288
+ return delegatedFrom;
289
+ }
290
+ const bridgeManager = (0, manager_1.createBridgeManager)();
291
+ const originBridges = bridgeManager.findBridgesForSession({
292
+ friendId: delegatedFrom.friendId,
293
+ channel: delegatedFrom.channel,
294
+ key: delegatedFrom.key,
295
+ });
296
+ const activeBridge = originBridges.find((b) => b.lifecycle === "active");
297
+ if (activeBridge) {
298
+ return { ...delegatedFrom, bridgeId: activeBridge.id };
299
+ }
300
+ return delegatedFrom;
301
+ }
302
+ async function routeDelegatedCompletion(agentRoot, agentName, completion, drainedPending, timestamp) {
303
+ const delegated = (drainedPending ?? []).find((message) => message.delegatedFrom);
304
+ if (!delegated?.delegatedFrom || !completion?.answer?.trim()) {
305
+ return;
306
+ }
307
+ const delegatedFrom = enrichDelegatedFromWithBridge(delegated.delegatedFrom);
308
+ if (delegated.obligationStatus === "pending") {
309
+ // Fulfill the persistent obligation in the store
310
+ try {
311
+ const pending = (0, obligations_1.findPendingObligationForOrigin)(agentRoot, {
312
+ friendId: delegatedFrom.friendId,
313
+ channel: delegatedFrom.channel,
314
+ key: delegatedFrom.key,
315
+ });
316
+ /* v8 ignore next 2 -- obligation fulfillment tested via obligations.test.ts; integration requires real disk state @preserve */
317
+ if (pending) {
318
+ (0, obligations_1.fulfillObligation)(agentRoot, pending.id);
319
+ }
320
+ }
321
+ catch {
322
+ /* v8 ignore next -- defensive: obligation store read failure should not break delivery @preserve */
210
323
  }
324
+ (0, runtime_1.emitNervesEvent)({
325
+ event: "senses.obligation_fulfilled",
326
+ component: "senses",
327
+ message: "obligation fulfilled via delegated completion",
328
+ meta: {
329
+ friendId: delegatedFrom.friendId,
330
+ channel: delegatedFrom.channel,
331
+ key: delegatedFrom.key,
332
+ },
333
+ });
211
334
  }
212
- const callbacks = createInnerDialogCallbacks();
213
- const traceId = (0, nerves_1.createTraceId)();
214
- const result = await (0, core_1.runAgent)(messages, callbacks, "cli", options?.signal, {
215
- traceId,
216
- toolChoiceRequired: true,
217
- skipConfirmation: true,
335
+ const outboundEnvelope = {
336
+ from: agentName,
337
+ friendId: delegatedFrom.friendId,
338
+ channel: delegatedFrom.channel,
339
+ key: delegatedFrom.key,
340
+ content: completion.answer.trim(),
341
+ timestamp,
342
+ delegatedFrom,
343
+ };
344
+ const sessionActivity = (0, session_activity_1.listSessionActivity)({
345
+ sessionsDir: path.join(agentRoot, "state", "sessions"),
346
+ friendsDir: path.join(agentRoot, "friends"),
347
+ agentName,
218
348
  });
219
- (0, context_1.postTurn)(messages, sessionFilePath, result.usage);
220
- (0, runtime_1.emitNervesEvent)({
221
- component: "senses",
222
- event: "senses.inner_dialog_turn",
223
- message: "inner dialog turn completed",
224
- meta: { reason, session: sessionFilePath },
349
+ const bridgeTarget = resolveBridgePreferredSession(delegatedFrom, sessionActivity);
350
+ if (bridgeTarget) {
351
+ if (await tryDeliverDelegatedCompletion(bridgeTarget, outboundEnvelope)) {
352
+ return;
353
+ }
354
+ writePendingEnvelope((0, pending_1.getPendingDir)(agentName, bridgeTarget.friendId, bridgeTarget.channel, bridgeTarget.key), outboundEnvelope);
355
+ return;
356
+ }
357
+ const freshest = (0, session_activity_1.findFreshestFriendSession)({
358
+ sessionsDir: path.join(agentRoot, "state", "sessions"),
359
+ friendsDir: path.join(agentRoot, "friends"),
360
+ agentName,
361
+ friendId: delegatedFrom.friendId,
362
+ activeOnly: true,
225
363
  });
364
+ if (freshest && freshest.channel !== "inner") {
365
+ if (await tryDeliverDelegatedCompletion(freshest, outboundEnvelope)) {
366
+ return;
367
+ }
368
+ writePendingEnvelope((0, pending_1.getPendingDir)(agentName, freshest.friendId, freshest.channel, freshest.key), outboundEnvelope);
369
+ return;
370
+ }
371
+ writePendingEnvelope((0, pending_1.getDeferredReturnDir)(agentName, delegatedFrom.friendId), outboundEnvelope);
372
+ }
373
+ // Self-referencing friend record for inner dialog (agent talking to itself).
374
+ // No real friend to resolve -- this satisfies the pipeline's friend resolver contract.
375
+ function createSelfFriend(agentName) {
226
376
  return {
227
- messages,
228
- usage: result.usage,
229
- sessionPath: sessionFilePath,
377
+ id: "self",
378
+ name: agentName,
379
+ trustLevel: "family",
380
+ externalIds: [],
381
+ tenantMemberships: [],
382
+ toolPreferences: {},
383
+ notes: {},
384
+ totalTokens: 0,
385
+ createdAt: new Date().toISOString(),
386
+ updatedAt: new Date().toISOString(),
387
+ schemaVersion: 1,
230
388
  };
231
389
  }
390
+ // No-op friend store for inner dialog. Inner dialog doesn't track token usage per-friend.
391
+ function createNoOpFriendStore() {
392
+ return {
393
+ get: async () => null,
394
+ put: async () => { },
395
+ delete: async () => { },
396
+ findByExternalId: async () => null,
397
+ };
398
+ }
399
+ async function runInnerDialogTurn(options) {
400
+ const now = options?.now ?? (() => new Date());
401
+ const reason = options?.reason ?? "heartbeat";
402
+ const sessionFilePath = innerDialogSessionPath();
403
+ const agentName = (0, identity_1.getAgentName)();
404
+ const agentRoot = (0, identity_1.getAgentRoot)();
405
+ writeInnerDialogRuntimeState(sessionFilePath, {
406
+ status: "running",
407
+ reason,
408
+ startedAt: now().toISOString(),
409
+ });
410
+ try {
411
+ const loaded = (0, context_1.loadSession)(sessionFilePath);
412
+ const existingMessages = loaded?.messages ? [...loaded.messages] : [];
413
+ const instincts = options?.instincts ?? loadInnerDialogInstincts();
414
+ const state = {
415
+ cycleCount: 1,
416
+ resting: false,
417
+ lastHeartbeatAt: now().toISOString(),
418
+ };
419
+ // ── Adapter concern: build user message ──────────────────────────
420
+ let userContent;
421
+ if (existingMessages.length === 0) {
422
+ // Fresh session: bootstrap message with non-canonical cleanup nudge
423
+ const aspirations = readAspirations((0, identity_1.getAgentRoot)());
424
+ const nonCanonical = (0, bundle_manifest_1.findNonCanonicalBundlePaths)((0, identity_1.getAgentRoot)());
425
+ const cleanupNudge = buildNonCanonicalCleanupNudge(nonCanonical);
426
+ userContent = [
427
+ buildInnerDialogBootstrapMessage(aspirations, "No prior inner dialog session found."),
428
+ cleanupNudge,
429
+ ].filter(Boolean).join("\n\n");
430
+ }
431
+ else {
432
+ // Resumed session: task-triggered or instinct message with checkpoint context
433
+ const assistantTurns = existingMessages.filter((message) => message.role === "assistant").length;
434
+ state.cycleCount = assistantTurns + 1;
435
+ state.checkpoint = deriveResumeCheckpoint(existingMessages);
436
+ if (options?.taskId) {
437
+ const taskContent = readTaskFile((0, identity_1.getAgentRoot)(), options.taskId);
438
+ userContent = buildTaskTriggeredMessage(options.taskId, taskContent, state.checkpoint);
439
+ }
440
+ else {
441
+ userContent = buildInstinctUserMessage(instincts, reason, state);
442
+ }
443
+ }
444
+ const userMessage = { role: "user", content: userContent };
445
+ // ── Session loader: wraps existing session logic ──────────────────
446
+ const innerCapabilities = (0, channel_1.getChannelCapabilities)("inner");
447
+ const pendingDir = (0, pending_1.getInnerDialogPendingDir)(agentName);
448
+ const selfFriend = createSelfFriend(agentName);
449
+ const selfContext = { friend: selfFriend, channel: innerCapabilities };
450
+ const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)() ?? undefined;
451
+ const sessionLoader = {
452
+ loadOrCreate: async () => {
453
+ if (existingMessages.length > 0) {
454
+ return { messages: existingMessages, sessionPath: sessionFilePath };
455
+ }
456
+ // Fresh session: build system prompt
457
+ const systemPrompt = await (0, prompt_1.buildSystem)("inner", { toolChoiceRequired: true, mcpManager });
458
+ return {
459
+ messages: [{ role: "system", content: systemPrompt }],
460
+ sessionPath: sessionFilePath,
461
+ };
462
+ },
463
+ };
464
+ // ── Call shared pipeline ──────────────────────────────────────────
465
+ const callbacks = createInnerDialogCallbacks();
466
+ const traceId = (0, nerves_1.createTraceId)();
467
+ const result = await (0, pipeline_1.handleInboundTurn)({
468
+ channel: "inner",
469
+ sessionKey: "dialog",
470
+ capabilities: innerCapabilities,
471
+ messages: [userMessage],
472
+ continuityIngressTexts: [],
473
+ callbacks,
474
+ friendResolver: { resolve: () => Promise.resolve(selfContext) },
475
+ sessionLoader,
476
+ pendingDir,
477
+ friendStore: createNoOpFriendStore(),
478
+ enforceTrustGate: trust_gate_1.enforceTrustGate,
479
+ drainPending: pending_1.drainPending,
480
+ runAgent: core_1.runAgent,
481
+ postTurn: context_1.postTurn,
482
+ accumulateFriendTokens: tokens_1.accumulateFriendTokens,
483
+ signal: options?.signal,
484
+ runAgentOptions: {
485
+ traceId,
486
+ toolChoiceRequired: true,
487
+ skipConfirmation: true,
488
+ mcpManager,
489
+ },
490
+ });
491
+ await routeDelegatedCompletion(agentRoot, agentName, result.completion, result.drainedPending, now().getTime());
492
+ const resultMessages = result.messages ?? [];
493
+ const assistantPreview = extractAssistantPreview(resultMessages);
494
+ const toolCalls = extractToolCallNames(resultMessages);
495
+ (0, runtime_1.emitNervesEvent)({
496
+ component: "senses",
497
+ event: "senses.inner_dialog_turn",
498
+ message: "inner dialog turn completed",
499
+ meta: {
500
+ reason,
501
+ session: sessionFilePath,
502
+ ...(options?.taskId && { taskId: options.taskId }),
503
+ ...(assistantPreview && { assistantPreview }),
504
+ ...(toolCalls.length > 0 && { toolCalls }),
505
+ ...(result.usage && {
506
+ promptTokens: result.usage.input_tokens,
507
+ completionTokens: result.usage.output_tokens,
508
+ totalTokens: result.usage.total_tokens,
509
+ }),
510
+ },
511
+ });
512
+ return {
513
+ messages: resultMessages,
514
+ usage: result.usage,
515
+ sessionPath: result.sessionPath ?? sessionFilePath,
516
+ completion: result.completion,
517
+ };
518
+ }
519
+ finally {
520
+ writeInnerDialogRuntimeState(sessionFilePath, {
521
+ status: "idle",
522
+ lastCompletedAt: now().toISOString(),
523
+ });
524
+ }
525
+ }