@ouro.bot/cli 0.1.0-alpha.20 → 0.1.0-alpha.200

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 (204) hide show
  1. package/README.md +187 -191
  2. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +3 -2
  3. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +1 -1
  4. package/changelog.json +1248 -0
  5. package/dist/heart/active-work.js +832 -0
  6. package/dist/heart/bridges/manager.js +358 -0
  7. package/dist/heart/bridges/state-machine.js +135 -0
  8. package/dist/heart/bridges/store.js +123 -0
  9. package/dist/heart/cares.js +179 -0
  10. package/dist/heart/commitments.js +111 -0
  11. package/dist/heart/config.js +54 -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-config-check.js +149 -0
  15. package/dist/heart/daemon/agent-discovery.js +81 -0
  16. package/dist/heart/daemon/agent-service.js +360 -0
  17. package/dist/heart/daemon/auth-flow.js +477 -0
  18. package/dist/heart/daemon/cadence.js +70 -0
  19. package/dist/heart/daemon/daemon-cli.js +2443 -217
  20. package/dist/heart/daemon/daemon-entry.js +182 -4
  21. package/dist/heart/daemon/daemon-health.js +136 -0
  22. package/dist/heart/daemon/daemon-runtime-sync.js +231 -0
  23. package/dist/heart/daemon/daemon-tombstone.js +123 -0
  24. package/dist/heart/daemon/daemon.js +460 -18
  25. package/dist/heart/daemon/habit-migration.js +181 -0
  26. package/dist/heart/daemon/habit-parser.js +119 -0
  27. package/dist/heart/daemon/habit-scheduler.js +369 -0
  28. package/dist/heart/daemon/hatch-flow.js +31 -112
  29. package/dist/heart/daemon/hatch-specialist.js +3 -3
  30. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  31. package/dist/heart/daemon/hooks/bundle-meta.js +206 -0
  32. package/dist/heart/daemon/inner-status.js +89 -0
  33. package/dist/heart/daemon/launchd.js +165 -0
  34. package/dist/heart/daemon/log-tailer.js +4 -3
  35. package/dist/heart/daemon/mcp-server.js +591 -0
  36. package/dist/heart/daemon/message-router.js +17 -8
  37. package/dist/heart/daemon/os-cron-deps.js +134 -0
  38. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  39. package/dist/heart/daemon/ouro-path-installer.js +78 -34
  40. package/dist/heart/daemon/ouro-version-manager.js +171 -0
  41. package/dist/heart/daemon/outlook-http.js +439 -0
  42. package/dist/heart/daemon/outlook-read.js +1618 -0
  43. package/dist/heart/daemon/outlook-render.js +1032 -0
  44. package/dist/heart/daemon/outlook-types.js +7 -0
  45. package/dist/heart/daemon/outlook-view.js +194 -0
  46. package/dist/heart/daemon/process-manager.js +93 -0
  47. package/dist/heart/daemon/run-hooks.js +39 -0
  48. package/dist/heart/daemon/runtime-logging.js +58 -15
  49. package/dist/heart/daemon/runtime-metadata.js +101 -0
  50. package/dist/heart/daemon/runtime-mode.js +67 -0
  51. package/dist/heart/daemon/safe-mode.js +161 -0
  52. package/dist/heart/daemon/sense-manager.js +50 -2
  53. package/dist/heart/daemon/session-id-resolver.js +131 -0
  54. package/dist/heart/daemon/skill-management-installer.js +94 -0
  55. package/dist/heart/daemon/socket-client.js +202 -0
  56. package/dist/heart/daemon/specialist-prompt.js +10 -7
  57. package/dist/heart/daemon/specialist-tools.js +49 -3
  58. package/dist/heart/daemon/staged-restart.js +138 -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 +147 -55
  66. package/dist/heart/intentions.js +173 -0
  67. package/dist/heart/kicks.js +2 -20
  68. package/dist/heart/migrate-config.js +127 -0
  69. package/dist/heart/model-capabilities.js +48 -0
  70. package/dist/heart/obligations.js +225 -0
  71. package/dist/heart/presence.js +185 -0
  72. package/dist/heart/progress-story.js +42 -0
  73. package/dist/heart/provider-failover.js +88 -0
  74. package/dist/heart/provider-ping.js +178 -0
  75. package/dist/heart/providers/anthropic-token.js +163 -0
  76. package/dist/heart/providers/anthropic.js +187 -41
  77. package/dist/heart/providers/azure.js +116 -10
  78. package/dist/heart/providers/github-copilot.js +157 -0
  79. package/dist/heart/providers/minimax.js +33 -3
  80. package/dist/heart/providers/openai-codex.js +51 -16
  81. package/dist/heart/session-activity.js +172 -0
  82. package/dist/heart/session-recall.js +216 -0
  83. package/dist/heart/start-of-turn-packet.js +232 -0
  84. package/dist/heart/streaming.js +36 -27
  85. package/dist/heart/sync.js +217 -0
  86. package/dist/heart/target-resolution.js +127 -0
  87. package/dist/heart/tempo.js +93 -0
  88. package/dist/heart/temporal-view.js +41 -0
  89. package/dist/heart/tool-activity-callbacks.js +36 -0
  90. package/dist/heart/tool-description.js +135 -0
  91. package/dist/heart/tool-loop.js +200 -0
  92. package/dist/heart/turn-coordinator.js +28 -0
  93. package/dist/mind/associative-recall.js +122 -32
  94. package/dist/mind/bundle-manifest.js +19 -1
  95. package/dist/mind/context.js +125 -14
  96. package/dist/mind/{memory.js → diary.js} +69 -56
  97. package/dist/mind/episodes.js +119 -0
  98. package/dist/mind/file-state.js +179 -0
  99. package/dist/mind/first-impressions.js +16 -2
  100. package/dist/mind/friends/channel.js +56 -0
  101. package/dist/mind/friends/group-context.js +144 -0
  102. package/dist/mind/friends/store-file.js +36 -0
  103. package/dist/mind/friends/trust-explanation.js +74 -0
  104. package/dist/mind/friends/types.js +8 -0
  105. package/dist/mind/journal-index.js +161 -0
  106. package/dist/mind/obligation-steering.js +221 -0
  107. package/dist/mind/obligations.js +138 -0
  108. package/dist/mind/pending.js +76 -9
  109. package/dist/mind/phrases.js +1 -0
  110. package/dist/mind/prompt.js +785 -103
  111. package/dist/mind/scrutiny.js +173 -0
  112. package/dist/mind/token-estimate.js +8 -12
  113. package/dist/nerves/coverage/audit.js +1 -1
  114. package/dist/nerves/coverage/run-artifacts.js +1 -1
  115. package/dist/nerves/event-buffer.js +111 -0
  116. package/dist/nerves/index.js +63 -3
  117. package/dist/nerves/observation.js +20 -0
  118. package/dist/nerves/runtime.js +5 -1
  119. package/dist/outlook-ui/assets/index-Ck8agNeO.js +61 -0
  120. package/dist/outlook-ui/assets/index-LwChZTgL.css +1 -0
  121. package/dist/outlook-ui/index.html +15 -0
  122. package/dist/repertoire/ado-semantic.js +11 -5
  123. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  124. package/dist/repertoire/coding/context-pack.js +330 -0
  125. package/dist/repertoire/coding/feedback.js +197 -30
  126. package/dist/repertoire/coding/manager.js +149 -2
  127. package/dist/repertoire/coding/spawner.js +55 -9
  128. package/dist/repertoire/coding/tools.js +170 -7
  129. package/dist/repertoire/guardrails.js +291 -0
  130. package/dist/repertoire/mcp-client.js +254 -0
  131. package/dist/repertoire/mcp-manager.js +251 -0
  132. package/dist/repertoire/shell-sessions.js +133 -0
  133. package/dist/repertoire/skills.js +14 -23
  134. package/dist/repertoire/tasks/board.js +43 -5
  135. package/dist/repertoire/tasks/fix.js +182 -0
  136. package/dist/repertoire/tasks/index.js +28 -10
  137. package/dist/repertoire/tasks/lifecycle.js +2 -2
  138. package/dist/repertoire/tasks/parser.js +3 -2
  139. package/dist/repertoire/tasks/scanner.js +194 -37
  140. package/dist/repertoire/tasks/transitions.js +11 -28
  141. package/dist/repertoire/tools-base.js +1345 -320
  142. package/dist/repertoire/tools-bluebubbles.js +94 -0
  143. package/dist/repertoire/tools-github.js +1 -6
  144. package/dist/repertoire/tools-teams.js +12 -59
  145. package/dist/repertoire/tools.js +318 -124
  146. package/dist/scripts/claude-code-hook.js +41 -0
  147. package/dist/scripts/claude-code-stop-hook.js +47 -0
  148. package/dist/senses/attention-queue.js +97 -0
  149. package/dist/senses/bluebubbles-client.js +102 -3
  150. package/dist/senses/bluebubbles-entry.js +2 -0
  151. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  152. package/dist/senses/bluebubbles-media.js +118 -23
  153. package/dist/senses/bluebubbles-model.js +12 -4
  154. package/dist/senses/bluebubbles-mutation-log.js +45 -5
  155. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  156. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  157. package/dist/senses/bluebubbles.js +1008 -102
  158. package/dist/senses/cli/adapter.js +274 -0
  159. package/dist/senses/cli/ink-app.js +156 -0
  160. package/dist/senses/cli/inline-diff.js +64 -0
  161. package/dist/senses/cli/message-list.js +51 -0
  162. package/dist/senses/cli/ouro-tui.js +349 -0
  163. package/dist/senses/cli/spinner-imperative.js +135 -0
  164. package/dist/senses/cli/spinner.js +101 -0
  165. package/dist/senses/cli/status-line.js +60 -0
  166. package/dist/senses/cli/streaming-markdown.js +526 -0
  167. package/dist/senses/cli/tool-display.js +83 -0
  168. package/dist/senses/cli/tool-render.js +85 -0
  169. package/dist/senses/cli/tui-store.js +198 -0
  170. package/dist/senses/cli/virtual-list.js +35 -0
  171. package/dist/senses/cli-entry.js +1 -1
  172. package/dist/senses/cli-layout.js +187 -0
  173. package/dist/senses/cli.js +508 -243
  174. package/dist/senses/commands.js +65 -1
  175. package/dist/senses/continuity.js +94 -0
  176. package/dist/senses/habit-turn-message.js +108 -0
  177. package/dist/senses/inner-dialog-worker.js +112 -19
  178. package/dist/senses/inner-dialog.js +592 -84
  179. package/dist/senses/pipeline.js +693 -0
  180. package/dist/senses/shared-turn.js +196 -0
  181. package/dist/senses/surface-tool.js +95 -0
  182. package/dist/senses/teams.js +667 -120
  183. package/dist/senses/trust-gate.js +112 -2
  184. package/package.json +16 -6
  185. package/skills/configure-dev-tools.md +81 -0
  186. package/subagents/README.md +4 -70
  187. package/dist/heart/daemon/subagent-installer.js +0 -134
  188. package/dist/senses/debug-activity.js +0 -107
  189. package/subagents/work-doer.md +0 -235
  190. package/subagents/work-merger.md +0 -618
  191. package/subagents/work-planner.md +0 -382
  192. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  193. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  194. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  195. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  196. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  197. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  198. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  199. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  200. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  201. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  202. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  203. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +0 -0
  204. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
@@ -34,12 +34,107 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.OuroDaemon = void 0;
37
+ exports.killOrphanProcesses = killOrphanProcesses;
38
+ exports.writePidfile = writePidfile;
37
39
  const fs = __importStar(require("fs"));
38
40
  const net = __importStar(require("net"));
41
+ const os = __importStar(require("os"));
39
42
  const path = __importStar(require("path"));
40
43
  const identity_1 = require("../identity");
41
44
  const runtime_1 = require("../../nerves/runtime");
42
45
  const runtime_metadata_1 = require("./runtime-metadata");
46
+ const runtime_mode_1 = require("./runtime-mode");
47
+ const update_hooks_1 = require("./update-hooks");
48
+ const bundle_meta_1 = require("./hooks/bundle-meta");
49
+ const agent_config_v2_1 = require("./hooks/agent-config-v2");
50
+ const bundle_manifest_1 = require("../../mind/bundle-manifest");
51
+ const update_checker_1 = require("./update-checker");
52
+ const staged_restart_1 = require("./staged-restart");
53
+ const child_process_1 = require("child_process");
54
+ const pending_1 = require("../../mind/pending");
55
+ const agent_service_1 = require("./agent-service");
56
+ const channel_1 = require("../../mind/friends/channel");
57
+ const mcp_manager_1 = require("../../repertoire/mcp-manager");
58
+ const outlook_http_1 = require("./outlook-http");
59
+ const outlook_types_1 = require("./outlook-types");
60
+ const outlook_read_1 = require("./outlook-read");
61
+ const outlook_view_1 = require("./outlook-view");
62
+ const PIDFILE_PATH = path.join(os.homedir(), ".ouro-cli", "daemon.pids");
63
+ /**
64
+ * Kill all ouro processes from the previous daemon instance using the pidfile.
65
+ * On startup, reads PIDs from ~/.ouro-cli/daemon.pids, kills them all, then
66
+ * deletes the file. The new daemon writes its own PIDs after spawning.
67
+ *
68
+ * Falls back to ps-based scanning if the pidfile doesn't exist (first run
69
+ * or manual cleanup).
70
+ */
71
+ /* v8 ignore start -- process lifecycle: uses kill/ps, tested via deployment @preserve */
72
+ function killOrphanProcesses() {
73
+ try {
74
+ let pidsToKill = [];
75
+ // Primary: read pidfile from previous daemon
76
+ try {
77
+ const raw = fs.readFileSync(PIDFILE_PATH, "utf-8");
78
+ pidsToKill = raw.split("\n").map((s) => parseInt(s.trim(), 10)).filter((n) => !isNaN(n) && n !== process.pid);
79
+ fs.unlinkSync(PIDFILE_PATH);
80
+ }
81
+ catch {
82
+ // No pidfile — fall back to ps scan
83
+ }
84
+ // Fallback: scan ps for daemon-owned processes only (not MCP servers or external tools)
85
+ if (pidsToKill.length === 0) {
86
+ try {
87
+ const result = (0, child_process_1.execSync)("ps -eo pid,command", { encoding: "utf-8", timeout: 5000 });
88
+ for (const line of result.split("\n")) {
89
+ // Only match daemon-owned entry points, NOT mcp-serve or other external processes
90
+ if (line.includes("mcp-serve") || line.includes("mcp serve"))
91
+ continue;
92
+ if (!line.includes("agent-entry.js") && !line.includes("daemon-entry.js") && !line.includes("bluebubbles-entry.js") && !line.includes("teams-entry.js"))
93
+ continue;
94
+ const pid = parseInt(line.trim(), 10);
95
+ if (!isNaN(pid) && pid !== process.pid)
96
+ pidsToKill.push(pid);
97
+ }
98
+ }
99
+ catch { /* ps failed — best effort */ }
100
+ }
101
+ if (pidsToKill.length > 0) {
102
+ for (const pid of pidsToKill) {
103
+ try {
104
+ process.kill(pid, "SIGTERM");
105
+ }
106
+ catch { /* already exited */ }
107
+ }
108
+ (0, runtime_1.emitNervesEvent)({
109
+ component: "daemon",
110
+ event: "daemon.orphan_cleanup",
111
+ message: `killed ${pidsToKill.length} orphaned ouro processes`,
112
+ meta: { pids: pidsToKill },
113
+ });
114
+ }
115
+ }
116
+ catch (error) {
117
+ (0, runtime_1.emitNervesEvent)({
118
+ level: "warn",
119
+ component: "daemon",
120
+ event: "daemon.orphan_cleanup_error",
121
+ message: "failed to clean up orphaned ouro processes",
122
+ meta: { error: error instanceof Error ? error.message : String(error) },
123
+ });
124
+ }
125
+ }
126
+ /**
127
+ * Write all managed PIDs (daemon + children) to the pidfile.
128
+ * Called after all agents and senses are spawned.
129
+ */
130
+ function writePidfile(extraPids = []) {
131
+ try {
132
+ const pids = [process.pid, ...extraPids].filter(Boolean);
133
+ fs.mkdirSync(path.dirname(PIDFILE_PATH), { recursive: true });
134
+ fs.writeFileSync(PIDFILE_PATH, pids.join("\n") + "\n", "utf-8");
135
+ }
136
+ catch { /* best effort */ }
137
+ }
43
138
  function buildWorkerRows(snapshots) {
44
139
  return snapshots.map((snapshot) => ({
45
140
  agent: snapshot.name,
@@ -48,6 +143,8 @@ function buildWorkerRows(snapshots) {
48
143
  pid: snapshot.pid,
49
144
  restartCount: snapshot.restartCount,
50
145
  startedAt: snapshot.startedAt,
146
+ lastExitCode: snapshot.lastExitCode ?? null,
147
+ lastSignal: snapshot.lastSignal ?? null,
51
148
  }));
52
149
  }
53
150
  function formatStatusSummary(payload) {
@@ -88,7 +185,9 @@ class OuroDaemon {
88
185
  router;
89
186
  senseManager;
90
187
  bundlesRoot;
188
+ mode;
91
189
  server = null;
190
+ outlookServer = null;
92
191
  constructor(options) {
93
192
  this.socketPath = options.socketPath;
94
193
  this.processManager = options.processManager;
@@ -97,6 +196,28 @@ class OuroDaemon {
97
196
  this.router = options.router;
98
197
  this.senseManager = options.senseManager ?? null;
99
198
  this.bundlesRoot = options.bundlesRoot ?? (0, identity_1.getAgentBundlesRoot)();
199
+ this.mode = options.mode ?? "production";
200
+ }
201
+ buildStatusPayload() {
202
+ const snapshots = this.processManager.listAgentSnapshots();
203
+ const workers = buildWorkerRows(snapshots);
204
+ const senses = this.senseManager?.listSenseRows() ?? [];
205
+ const repoRoot = (0, identity_1.getRepoRoot)();
206
+ return {
207
+ overview: {
208
+ daemon: "running",
209
+ health: workers.every((worker) => worker.status === "running") ? "ok" : "warn",
210
+ socketPath: this.socketPath,
211
+ outlookUrl: this.outlookServer?.origin ?? "http://127.0.0.1:0",
212
+ ...(0, runtime_metadata_1.getRuntimeMetadata)(),
213
+ workerCount: workers.length,
214
+ senseCount: senses.length,
215
+ entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
216
+ mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
217
+ },
218
+ workers,
219
+ senses,
220
+ };
100
221
  }
101
222
  async start() {
102
223
  if (this.server)
@@ -107,23 +228,167 @@ class OuroDaemon {
107
228
  message: "starting daemon server",
108
229
  meta: { socketPath: this.socketPath },
109
230
  });
231
+ // Register update hooks and apply pending updates before starting agents
232
+ (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
233
+ (0, update_hooks_1.registerUpdateHook)(agent_config_v2_1.agentConfigV2Hook);
234
+ const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
235
+ await (0, update_hooks_1.applyPendingUpdates)(this.bundlesRoot, currentVersion);
236
+ // Start periodic update checker (polls npm registry every 30 minutes)
237
+ // Skip in dev mode — dev builds should not auto-update from npm
238
+ const bundlesRoot = this.bundlesRoot;
239
+ const daemonSocketPath = this.socketPath;
240
+ if (this.mode === "dev") {
241
+ (0, runtime_1.emitNervesEvent)({
242
+ component: "daemon",
243
+ event: "daemon.update_checker_skip",
244
+ message: "skipping update checker in dev mode",
245
+ meta: { reason: "dev mode" },
246
+ });
247
+ }
248
+ else {
249
+ const daemon = this;
250
+ (0, update_checker_1.startUpdateChecker)({
251
+ currentVersion,
252
+ deps: {
253
+ distTag: "alpha",
254
+ fetchRegistryJson: /* v8 ignore next -- integration: real HTTP fetch @preserve */ async () => {
255
+ const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
256
+ return res.json();
257
+ },
258
+ },
259
+ onUpdate: /* v8 ignore start -- integration: real npm install + process spawn @preserve */ async (result) => {
260
+ if (!result.latestVersion)
261
+ return;
262
+ await (0, staged_restart_1.performStagedRestart)(result.latestVersion, {
263
+ execSync: (cmd) => (0, child_process_1.execSync)(cmd, { stdio: "inherit" }),
264
+ spawnSync: child_process_1.spawnSync,
265
+ resolveNewCodePath: (_version) => {
266
+ try {
267
+ const resolved = (0, child_process_1.execSync)(`node -e "console.log(require.resolve('@ouro.bot/cli/package.json'))"`, { encoding: "utf-8" }).trim();
268
+ return resolved ? path.dirname(resolved) : null;
269
+ }
270
+ catch {
271
+ return null;
272
+ }
273
+ },
274
+ gracefulShutdown: () => daemon.stop(),
275
+ spawnNewDaemon: (entryPath, sock) => {
276
+ const outFd = fs.openSync(os.devNull, "w");
277
+ const errFd = fs.openSync(os.devNull, "w");
278
+ const child = (0, child_process_1.spawn)(process.execPath, [entryPath, "--socket", sock], {
279
+ detached: true,
280
+ stdio: ["ignore", outFd, errFd],
281
+ });
282
+ child.unref();
283
+ return { pid: child.pid ?? null };
284
+ },
285
+ nodePath: process.execPath,
286
+ bundlesRoot,
287
+ socketPath: daemonSocketPath,
288
+ });
289
+ },
290
+ /* v8 ignore stop */
291
+ });
292
+ }
293
+ // Pre-initialize MCP connections so they're ready for the first command (non-blocking)
294
+ /* v8 ignore next -- catch callback: getSharedMcpManager logs errors internally @preserve */
295
+ (0, mcp_manager_1.getSharedMcpManager)().catch(() => { });
296
+ /* v8 ignore start -- orphan cleanup + pidfile: calls process management functions @preserve */
297
+ killOrphanProcesses();
298
+ /* v8 ignore stop */
110
299
  await this.processManager.startAutoStartAgents();
111
300
  await this.senseManager?.startAutoStartSenses();
301
+ // Write all managed PIDs to disk so the next daemon can clean up
302
+ /* v8 ignore start -- pidfile write: collects PIDs from process managers @preserve */
303
+ const agentPids = this.processManager.listAgentSnapshots().map((s) => s.pid).filter((p) => p !== null);
304
+ const sensePids = this.senseManager?.listManagedPids?.() ?? [];
305
+ writePidfile([...agentPids, ...sensePids]);
306
+ /* v8 ignore stop */
112
307
  this.scheduler.start?.();
113
308
  await this.scheduler.reconcile?.();
114
309
  await this.drainPendingBundleMessages();
310
+ await this.drainPendingSenseMessages();
311
+ /* v8 ignore start — Outlook server startup, tested via outlook-http.test.ts */
312
+ if (!this.outlookServer) {
313
+ try {
314
+ this.outlookServer = await (0, outlook_http_1.startOutlookHttpServer)({
315
+ host: "127.0.0.1",
316
+ port: outlook_types_1.OUTLOOK_DEFAULT_PORT,
317
+ bundlesRoot: this.bundlesRoot,
318
+ readMachineState: () => (0, outlook_read_1.readOutlookMachineState)({ bundlesRoot: this.bundlesRoot }),
319
+ readMachineView: ({ machine }) => {
320
+ const overview = this.buildStatusPayload().overview;
321
+ return (0, outlook_view_1.buildOutlookMachineView)({
322
+ machine,
323
+ daemon: {
324
+ status: overview.daemon,
325
+ health: overview.health,
326
+ mode: overview.mode,
327
+ socketPath: overview.socketPath,
328
+ outlookUrl: overview.outlookUrl,
329
+ entryPath: overview.entryPath,
330
+ workerCount: overview.workerCount,
331
+ senseCount: overview.senseCount,
332
+ },
333
+ });
334
+ },
335
+ readAgentState: (agentName) => (0, outlook_read_1.readOutlookAgentState)(agentName, { bundlesRoot: this.bundlesRoot }),
336
+ readAgentView: (agentName) => {
337
+ const agent = (0, outlook_read_1.readOutlookAgentState)(agentName, { bundlesRoot: this.bundlesRoot });
338
+ return (0, outlook_view_1.buildOutlookAgentView)({
339
+ agent,
340
+ viewer: { kind: "human" },
341
+ });
342
+ },
343
+ });
344
+ }
345
+ catch (error) {
346
+ (0, runtime_1.emitNervesEvent)({
347
+ level: "warn",
348
+ component: "daemon",
349
+ event: "daemon.outlook_start_failed",
350
+ message: `Outlook server failed to start: ${String(error)}`,
351
+ meta: { port: outlook_types_1.OUTLOOK_DEFAULT_PORT },
352
+ });
353
+ }
354
+ }
355
+ /* v8 ignore stop */
115
356
  if (fs.existsSync(this.socketPath)) {
116
357
  fs.unlinkSync(this.socketPath);
117
358
  }
118
359
  this.server = net.createServer((connection) => {
119
360
  let raw = "";
120
361
  let responded = false;
362
+ /* v8 ignore start — connection error handler requires real socket error @preserve */
363
+ connection.on("error", (err) => {
364
+ (0, runtime_1.emitNervesEvent)({
365
+ level: "warn",
366
+ component: "daemon",
367
+ event: "daemon.connection_error",
368
+ message: "socket connection error",
369
+ meta: { error: err.message, code: err.code ?? null },
370
+ });
371
+ });
372
+ /* v8 ignore stop */
121
373
  const flushResponse = async () => {
122
374
  if (responded)
123
375
  return;
124
376
  responded = true;
125
377
  const response = await this.handleRawPayload(raw);
126
- connection.end(response);
378
+ try {
379
+ connection.end(response);
380
+ /* v8 ignore start — EPIPE catch requires real socket disconnect @preserve */
381
+ }
382
+ catch (err) {
383
+ (0, runtime_1.emitNervesEvent)({
384
+ level: "warn",
385
+ component: "daemon",
386
+ event: "daemon.connection_end_error",
387
+ message: "failed to send response to client (EPIPE)",
388
+ meta: { error: err instanceof Error ? err.message : String(err) },
389
+ });
390
+ }
391
+ /* v8 ignore stop */
127
392
  };
128
393
  connection.on("data", (chunk) => {
129
394
  raw += chunk.toString("utf-8");
@@ -136,7 +401,22 @@ class OuroDaemon {
136
401
  const server = this.server;
137
402
  await new Promise((resolve, reject) => {
138
403
  server.once("error", reject);
139
- server.listen(this.socketPath, () => resolve());
404
+ server.listen(this.socketPath, () => {
405
+ // Replace the one-time error listener with a persistent one after successful listen
406
+ server.removeAllListeners("error");
407
+ /* v8 ignore start — server error after listen requires real socket race condition @preserve */
408
+ server.on("error", (err) => {
409
+ (0, runtime_1.emitNervesEvent)({
410
+ level: "error",
411
+ component: "daemon",
412
+ event: "daemon.server_error",
413
+ message: "daemon server error after listen",
414
+ meta: { error: err.message, code: err.code ?? null },
415
+ });
416
+ });
417
+ /* v8 ignore stop */
418
+ resolve();
419
+ });
140
420
  });
141
421
  }
142
422
  async drainPendingBundleMessages() {
@@ -187,6 +467,93 @@ class OuroDaemon {
187
467
  fs.writeFileSync(pendingPath, next, "utf-8");
188
468
  }
189
469
  }
470
+ /** Drains per-sense pending dirs for always-on senses across all agents. */
471
+ static ALWAYS_ON_SENSES = new Set((0, channel_1.getAlwaysOnSenseNames)());
472
+ async drainPendingSenseMessages() {
473
+ if (!fs.existsSync(this.bundlesRoot))
474
+ return;
475
+ let bundleDirs;
476
+ try {
477
+ bundleDirs = fs.readdirSync(this.bundlesRoot, { withFileTypes: true });
478
+ }
479
+ catch {
480
+ return;
481
+ }
482
+ for (const bundleDir of bundleDirs) {
483
+ if (!bundleDir.isDirectory() || !bundleDir.name.endsWith(".ouro"))
484
+ continue;
485
+ const agentName = bundleDir.name.replace(/\.ouro$/, "");
486
+ const pendingRoot = path.join(this.bundlesRoot, bundleDir.name, "state", "pending");
487
+ if (!fs.existsSync(pendingRoot))
488
+ continue;
489
+ let friendDirs;
490
+ try {
491
+ friendDirs = fs.readdirSync(pendingRoot, { withFileTypes: true });
492
+ }
493
+ catch {
494
+ continue;
495
+ }
496
+ for (const friendDir of friendDirs) {
497
+ if (!friendDir.isDirectory())
498
+ continue;
499
+ const friendPath = path.join(pendingRoot, friendDir.name);
500
+ let channelDirs;
501
+ try {
502
+ channelDirs = fs.readdirSync(friendPath, { withFileTypes: true });
503
+ }
504
+ catch {
505
+ continue;
506
+ }
507
+ for (const channelDir of channelDirs) {
508
+ if (!channelDir.isDirectory())
509
+ continue;
510
+ if (!OuroDaemon.ALWAYS_ON_SENSES.has(channelDir.name))
511
+ continue;
512
+ const channelPath = path.join(friendPath, channelDir.name);
513
+ let keyDirs;
514
+ try {
515
+ keyDirs = fs.readdirSync(channelPath, { withFileTypes: true });
516
+ }
517
+ catch {
518
+ continue;
519
+ }
520
+ for (const keyDir of keyDirs) {
521
+ if (!keyDir.isDirectory())
522
+ continue;
523
+ const leafDir = path.join(channelPath, keyDir.name);
524
+ const messages = (0, pending_1.drainPending)(leafDir);
525
+ for (const msg of messages) {
526
+ try {
527
+ await this.router.send({
528
+ from: msg.from,
529
+ to: agentName,
530
+ content: msg.content,
531
+ priority: "normal",
532
+ });
533
+ }
534
+ catch {
535
+ // Best-effort delivery — log and continue
536
+ }
537
+ }
538
+ if (messages.length > 0) {
539
+ (0, runtime_1.emitNervesEvent)({
540
+ component: "daemon",
541
+ event: "daemon.startup_sense_drain",
542
+ message: "drained pending sense messages on startup",
543
+ meta: {
544
+ agent: agentName,
545
+ channel: channelDir.name,
546
+ friendId: friendDir.name,
547
+ key: keyDir.name,
548
+ count: messages.length,
549
+ },
550
+ });
551
+ }
552
+ }
553
+ }
554
+ }
555
+ }
556
+ }
190
557
  async stop() {
191
558
  (0, runtime_1.emitNervesEvent)({
192
559
  component: "daemon",
@@ -194,6 +561,8 @@ class OuroDaemon {
194
561
  message: "stopping daemon server",
195
562
  meta: { socketPath: this.socketPath },
196
563
  });
564
+ (0, update_checker_1.stopUpdateChecker)();
565
+ (0, mcp_manager_1.shutdownSharedMcpManager)();
197
566
  this.scheduler.stop?.();
198
567
  await this.processManager.stopAll();
199
568
  await this.senseManager?.stopAll();
@@ -203,6 +572,10 @@ class OuroDaemon {
203
572
  });
204
573
  this.server = null;
205
574
  }
575
+ if (this.outlookServer) {
576
+ await this.outlookServer.stop();
577
+ this.outlookServer = null;
578
+ }
206
579
  if (fs.existsSync(this.socketPath)) {
207
580
  fs.unlinkSync(this.socketPath);
208
581
  }
@@ -227,6 +600,27 @@ class OuroDaemon {
227
600
  message: "handling daemon command",
228
601
  meta: { kind: command.kind },
229
602
  });
603
+ try {
604
+ return await this.handleCommandInner(command);
605
+ /* v8 ignore start — command error catch tested in daemon-command-error.test; instanceof branches defensive @preserve */
606
+ }
607
+ catch (error) {
608
+ (0, runtime_1.emitNervesEvent)({
609
+ level: "error",
610
+ component: "daemon",
611
+ event: "daemon.command_error",
612
+ message: "unexpected error handling daemon command",
613
+ meta: {
614
+ kind: command.kind,
615
+ error: error instanceof Error ? error.message : String(error),
616
+ stack: error instanceof Error ? error.stack ?? null : null,
617
+ },
618
+ });
619
+ throw error;
620
+ }
621
+ /* v8 ignore stop */
622
+ }
623
+ async handleCommandInner(command) {
230
624
  switch (command.kind) {
231
625
  case "daemon.start":
232
626
  await this.start();
@@ -235,21 +629,7 @@ class OuroDaemon {
235
629
  await this.stop();
236
630
  return { ok: true, message: "daemon stopped" };
237
631
  case "daemon.status": {
238
- const snapshots = this.processManager.listAgentSnapshots();
239
- const workers = buildWorkerRows(snapshots);
240
- const senses = this.senseManager?.listSenseRows() ?? [];
241
- const data = {
242
- overview: {
243
- daemon: "running",
244
- health: workers.every((worker) => worker.status === "running") ? "ok" : "warn",
245
- socketPath: this.socketPath,
246
- ...(0, runtime_metadata_1.getRuntimeMetadata)(),
247
- workerCount: workers.length,
248
- senseCount: senses.length,
249
- },
250
- workers,
251
- senses,
252
- };
632
+ const data = this.buildStatusPayload();
253
633
  return {
254
634
  ok: true,
255
635
  summary: formatStatusSummary(data),
@@ -266,7 +646,7 @@ class OuroDaemon {
266
646
  ok: true,
267
647
  summary: "logs: use `ouro logs` to tail daemon and agent output",
268
648
  message: "log streaming available via ouro logs",
269
- data: { logDir: "~/.agentstate/daemon/logs" },
649
+ data: { logDir: "~/AgentBundles/<agent>.ouro/state/daemon/logs" },
270
650
  };
271
651
  case "agent.start":
272
652
  await this.processManager.startAgent(command.agent);
@@ -277,6 +657,32 @@ class OuroDaemon {
277
657
  case "agent.restart":
278
658
  await this.processManager.restartAgent?.(command.agent);
279
659
  return { ok: true, message: `restarted ${command.agent}` };
660
+ case "agent.ask":
661
+ return (0, agent_service_1.handleAgentAsk)(command);
662
+ case "agent.status":
663
+ return (0, agent_service_1.handleAgentStatus)(command);
664
+ case "agent.catchup":
665
+ return (0, agent_service_1.handleAgentCatchup)(command);
666
+ case "agent.delegate":
667
+ return (0, agent_service_1.handleAgentDelegate)(command);
668
+ case "agent.getContext":
669
+ return (0, agent_service_1.handleAgentGetContext)(command);
670
+ case "agent.searchMemory":
671
+ return (0, agent_service_1.handleAgentSearchMemory)(command);
672
+ case "agent.getTask":
673
+ return (0, agent_service_1.handleAgentGetTask)(command);
674
+ case "agent.checkScope":
675
+ return (0, agent_service_1.handleAgentCheckScope)(command);
676
+ case "agent.requestDecision":
677
+ return (0, agent_service_1.handleAgentRequestDecision)(command);
678
+ case "agent.checkGuidance":
679
+ return (0, agent_service_1.handleAgentCheckGuidance)(command);
680
+ case "agent.reportProgress":
681
+ return (0, agent_service_1.handleAgentReportProgress)(command);
682
+ case "agent.reportBlocker":
683
+ return (0, agent_service_1.handleAgentReportBlocker)(command);
684
+ case "agent.reportComplete":
685
+ return (0, agent_service_1.handleAgentReportComplete)(command);
280
686
  case "cron.list": {
281
687
  const jobs = this.scheduler.listJobs();
282
688
  const summary = jobs.length === 0
@@ -308,6 +714,13 @@ class OuroDaemon {
308
714
  data: messages,
309
715
  };
310
716
  }
717
+ case "inner.wake":
718
+ await this.processManager.startAgent(command.agent);
719
+ this.processManager.sendToAgent?.(command.agent, { type: "message" });
720
+ return {
721
+ ok: true,
722
+ message: `woke inner dialog for ${command.agent}`,
723
+ };
311
724
  case "chat.connect":
312
725
  await this.processManager.startAgent(command.agent);
313
726
  return {
@@ -330,6 +743,35 @@ class OuroDaemon {
330
743
  data: receipt,
331
744
  };
332
745
  }
746
+ case "habit.poke": {
747
+ this.processManager.sendToAgent?.(command.agent, { type: "habit", habitName: command.habitName });
748
+ return {
749
+ ok: true,
750
+ message: `poked habit ${command.habitName} for ${command.agent}`,
751
+ };
752
+ }
753
+ case "mcp.list": {
754
+ const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)();
755
+ if (!mcpManager) {
756
+ return { ok: true, data: [], message: "no MCP servers configured" };
757
+ }
758
+ return { ok: true, data: mcpManager.listAllTools() };
759
+ }
760
+ case "mcp.call": {
761
+ const mcpCallManager = await (0, mcp_manager_1.getSharedMcpManager)();
762
+ if (!mcpCallManager) {
763
+ return { ok: false, error: "no MCP servers configured" };
764
+ }
765
+ try {
766
+ const parsedArgs = command.args ? JSON.parse(command.args) : {};
767
+ const result = await mcpCallManager.callTool(command.server, command.tool, parsedArgs);
768
+ return { ok: true, data: result };
769
+ }
770
+ catch (error) {
771
+ /* v8 ignore next -- defensive: callTool errors are always Error instances @preserve */
772
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
773
+ }
774
+ }
333
775
  case "hatch.start":
334
776
  return {
335
777
  ok: true,