@ouro.bot/cli 0.1.0-alpha.7 → 0.1.0-alpha.70

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