@ouro.bot/cli 0.1.0-alpha.6 → 0.1.0-alpha.60

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 (117) 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 +325 -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 +57 -23
  12. package/dist/heart/core.js +236 -90
  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 +351 -0
  16. package/dist/heart/daemon/daemon-cli.js +1173 -227
  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 +189 -10
  20. package/dist/heart/daemon/hatch-animation.js +10 -3
  21. package/dist/heart/daemon/hatch-flow.js +4 -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/socket-client.js +202 -0
  38. package/dist/heart/daemon/specialist-orchestrator.js +53 -84
  39. package/dist/heart/daemon/specialist-prompt.js +64 -5
  40. package/dist/heart/daemon/specialist-tools.js +213 -58
  41. package/dist/heart/daemon/staged-restart.js +114 -0
  42. package/dist/heart/daemon/subagent-installer.js +48 -7
  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 +122 -19
  49. package/dist/heart/kicks.js +1 -19
  50. package/dist/heart/model-capabilities.js +40 -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/minimax.js +4 -0
  55. package/dist/heart/providers/openai-codex.js +12 -3
  56. package/dist/heart/safe-workspace.js +228 -0
  57. package/dist/heart/sense-truth.js +61 -0
  58. package/dist/heart/session-activity.js +169 -0
  59. package/dist/heart/session-recall.js +116 -0
  60. package/dist/heart/streaming.js +100 -22
  61. package/dist/heart/target-resolution.js +123 -0
  62. package/dist/heart/turn-coordinator.js +28 -0
  63. package/dist/mind/associative-recall.js +14 -2
  64. package/dist/mind/bundle-manifest.js +70 -0
  65. package/dist/mind/context.js +27 -11
  66. package/dist/mind/first-impressions.js +16 -2
  67. package/dist/mind/friends/channel.js +35 -0
  68. package/dist/mind/friends/group-context.js +144 -0
  69. package/dist/mind/friends/store-file.js +19 -0
  70. package/dist/mind/friends/trust-explanation.js +74 -0
  71. package/dist/mind/friends/types.js +8 -0
  72. package/dist/mind/memory.js +27 -26
  73. package/dist/mind/pending.js +72 -9
  74. package/dist/mind/phrases.js +1 -0
  75. package/dist/mind/prompt.js +299 -77
  76. package/dist/mind/token-estimate.js +8 -12
  77. package/dist/nerves/cli-logging.js +15 -2
  78. package/dist/nerves/coverage/run-artifacts.js +1 -1
  79. package/dist/repertoire/ado-client.js +4 -2
  80. package/dist/repertoire/coding/feedback.js +134 -0
  81. package/dist/repertoire/coding/index.js +4 -1
  82. package/dist/repertoire/coding/manager.js +62 -4
  83. package/dist/repertoire/coding/spawner.js +3 -3
  84. package/dist/repertoire/coding/tools.js +41 -2
  85. package/dist/repertoire/data/ado-endpoints.json +188 -0
  86. package/dist/repertoire/tasks/board.js +12 -0
  87. package/dist/repertoire/tasks/index.js +23 -9
  88. package/dist/repertoire/tasks/transitions.js +1 -2
  89. package/dist/repertoire/tools-base.js +629 -251
  90. package/dist/repertoire/tools-bluebubbles.js +93 -0
  91. package/dist/repertoire/tools-teams.js +58 -25
  92. package/dist/repertoire/tools.js +92 -48
  93. package/dist/senses/bluebubbles-client.js +210 -5
  94. package/dist/senses/bluebubbles-entry.js +2 -0
  95. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  96. package/dist/senses/bluebubbles-media.js +339 -0
  97. package/dist/senses/bluebubbles-model.js +12 -4
  98. package/dist/senses/bluebubbles-mutation-log.js +45 -5
  99. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  100. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  101. package/dist/senses/bluebubbles.js +890 -45
  102. package/dist/senses/cli-layout.js +87 -0
  103. package/dist/senses/cli.js +345 -144
  104. package/dist/senses/continuity.js +94 -0
  105. package/dist/senses/debug-activity.js +148 -0
  106. package/dist/senses/inner-dialog-worker.js +47 -18
  107. package/dist/senses/inner-dialog.js +330 -84
  108. package/dist/senses/pipeline.js +278 -0
  109. package/dist/senses/teams.js +570 -129
  110. package/dist/senses/trust-gate.js +112 -2
  111. package/package.json +14 -3
  112. package/subagents/README.md +46 -33
  113. package/subagents/work-doer.md +28 -24
  114. package/subagents/work-merger.md +24 -30
  115. package/subagents/work-planner.md +44 -27
  116. package/dist/heart/daemon/specialist-session.js +0 -142
  117. package/dist/inner-worker-entry.js +0 -4
@@ -35,11 +35,12 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.ensureDaemonRunning = ensureDaemonRunning;
37
37
  exports.parseOuroCommand = parseOuroCommand;
38
+ exports.discoverExistingCredentials = discoverExistingCredentials;
38
39
  exports.createDefaultOuroCliDeps = createDefaultOuroCliDeps;
39
40
  exports.runOuroCli = runOuroCli;
40
41
  const child_process_1 = require("child_process");
42
+ const crypto_1 = require("crypto");
41
43
  const fs = __importStar(require("fs"));
42
- const net = __importStar(require("net"));
43
44
  const os = __importStar(require("os"));
44
45
  const path = __importStar(require("path"));
45
46
  const identity_1 = require("../identity");
@@ -47,16 +48,201 @@ const runtime_1 = require("../../nerves/runtime");
47
48
  const store_file_1 = require("../../mind/friends/store-file");
48
49
  const types_1 = require("../../mind/friends/types");
49
50
  const ouro_uti_1 = require("./ouro-uti");
51
+ const ouro_path_installer_1 = require("./ouro-path-installer");
50
52
  const subagent_installer_1 = require("./subagent-installer");
51
53
  const hatch_flow_1 = require("./hatch-flow");
52
54
  const specialist_orchestrator_1 = require("./specialist-orchestrator");
55
+ const specialist_prompt_1 = require("./specialist-prompt");
56
+ const specialist_tools_1 = require("./specialist-tools");
57
+ const runtime_metadata_1 = require("./runtime-metadata");
58
+ const runtime_mode_1 = require("./runtime-mode");
59
+ const daemon_runtime_sync_1 = require("./daemon-runtime-sync");
60
+ const agent_discovery_1 = require("./agent-discovery");
61
+ const update_hooks_1 = require("./update-hooks");
62
+ const bundle_meta_1 = require("./hooks/bundle-meta");
63
+ const bundle_manifest_1 = require("../../mind/bundle-manifest");
64
+ const tasks_1 = require("../../repertoire/tasks");
65
+ const thoughts_1 = require("./thoughts");
66
+ const ouro_bot_global_installer_1 = require("./ouro-bot-global-installer");
67
+ const launchd_1 = require("./launchd");
68
+ const socket_client_1 = require("./socket-client");
69
+ const session_activity_1 = require("../session-activity");
70
+ const auth_flow_1 = require("./auth-flow");
71
+ function stringField(value) {
72
+ return typeof value === "string" ? value : null;
73
+ }
74
+ function numberField(value) {
75
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
76
+ }
77
+ function booleanField(value) {
78
+ return typeof value === "boolean" ? value : null;
79
+ }
80
+ function parseStatusPayload(data) {
81
+ if (!data || typeof data !== "object" || Array.isArray(data))
82
+ return null;
83
+ const raw = data;
84
+ const overview = raw.overview;
85
+ const senses = raw.senses;
86
+ const workers = raw.workers;
87
+ if (!overview || typeof overview !== "object" || Array.isArray(overview))
88
+ return null;
89
+ if (!Array.isArray(senses) || !Array.isArray(workers))
90
+ return null;
91
+ const parsedOverview = {
92
+ daemon: stringField(overview.daemon) ?? "unknown",
93
+ health: stringField(overview.health) ?? "unknown",
94
+ socketPath: stringField(overview.socketPath) ?? "unknown",
95
+ version: stringField(overview.version) ?? "unknown",
96
+ lastUpdated: stringField(overview.lastUpdated) ?? "unknown",
97
+ repoRoot: stringField(overview.repoRoot) ?? "unknown",
98
+ configFingerprint: stringField(overview.configFingerprint) ?? "unknown",
99
+ workerCount: numberField(overview.workerCount) ?? 0,
100
+ senseCount: numberField(overview.senseCount) ?? 0,
101
+ entryPath: stringField(overview.entryPath) ?? "unknown",
102
+ mode: stringField(overview.mode) ?? "unknown",
103
+ };
104
+ const parsedSenses = senses.map((entry) => {
105
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
106
+ return null;
107
+ const row = entry;
108
+ const agent = stringField(row.agent);
109
+ const sense = stringField(row.sense);
110
+ const status = stringField(row.status);
111
+ const detail = stringField(row.detail);
112
+ const enabled = booleanField(row.enabled);
113
+ if (!agent || !sense || !status || detail === null || enabled === null)
114
+ return null;
115
+ return {
116
+ agent,
117
+ sense,
118
+ label: stringField(row.label) ?? undefined,
119
+ enabled,
120
+ status,
121
+ detail,
122
+ };
123
+ });
124
+ const parsedWorkers = workers.map((entry) => {
125
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
126
+ return null;
127
+ const row = entry;
128
+ const agent = stringField(row.agent);
129
+ const worker = stringField(row.worker);
130
+ const status = stringField(row.status);
131
+ const restartCount = numberField(row.restartCount);
132
+ const hasPid = Object.prototype.hasOwnProperty.call(row, "pid");
133
+ const pid = row.pid === null ? null : numberField(row.pid);
134
+ const pidInvalid = !hasPid || (row.pid !== null && pid === null);
135
+ if (!agent || !worker || !status || restartCount === null || pidInvalid)
136
+ return null;
137
+ return {
138
+ agent,
139
+ worker,
140
+ status,
141
+ pid,
142
+ restartCount,
143
+ };
144
+ });
145
+ if (parsedSenses.some((row) => row === null) || parsedWorkers.some((row) => row === null))
146
+ return null;
147
+ return {
148
+ overview: parsedOverview,
149
+ senses: parsedSenses,
150
+ workers: parsedWorkers,
151
+ };
152
+ }
153
+ function humanizeSenseName(sense, label) {
154
+ if (label)
155
+ return label;
156
+ if (sense === "cli")
157
+ return "CLI";
158
+ if (sense === "bluebubbles")
159
+ return "BlueBubbles";
160
+ if (sense === "teams")
161
+ return "Teams";
162
+ return sense;
163
+ }
164
+ function formatTable(headers, rows) {
165
+ const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => row[index].length)));
166
+ const renderRow = (row) => `| ${row.map((cell, index) => cell.padEnd(widths[index])).join(" | ")} |`;
167
+ const divider = `|-${widths.map((width) => "-".repeat(width)).join("-|-")}-|`;
168
+ return [
169
+ renderRow(headers),
170
+ divider,
171
+ ...rows.map(renderRow),
172
+ ].join("\n");
173
+ }
174
+ function formatDaemonStatusOutput(response, fallback) {
175
+ const payload = parseStatusPayload(response.data);
176
+ if (!payload)
177
+ return fallback;
178
+ const overviewRows = [
179
+ ["Daemon", payload.overview.daemon],
180
+ ["Socket", payload.overview.socketPath],
181
+ ["Version", payload.overview.version],
182
+ ["Last Updated", payload.overview.lastUpdated],
183
+ ["Entry Path", payload.overview.entryPath],
184
+ ["Mode", payload.overview.mode],
185
+ ["Workers", String(payload.overview.workerCount)],
186
+ ["Senses", String(payload.overview.senseCount)],
187
+ ["Health", payload.overview.health],
188
+ ];
189
+ const senseRows = payload.senses.map((row) => [
190
+ row.agent,
191
+ humanizeSenseName(row.sense, row.label),
192
+ row.enabled ? "ON" : "OFF",
193
+ row.status,
194
+ row.detail,
195
+ ]);
196
+ const workerRows = payload.workers.map((row) => [
197
+ row.agent,
198
+ row.worker,
199
+ row.status,
200
+ row.pid === null ? "n/a" : String(row.pid),
201
+ String(row.restartCount),
202
+ ]);
203
+ return [
204
+ "Overview",
205
+ formatTable(["Item", "Value"], overviewRows),
206
+ "",
207
+ "Senses",
208
+ formatTable(["Agent", "Sense", "Enabled", "State", "Detail"], senseRows),
209
+ "",
210
+ "Workers",
211
+ formatTable(["Agent", "Worker", "State", "PID", "Restarts"], workerRows),
212
+ ].join("\n");
213
+ }
53
214
  async function ensureDaemonRunning(deps) {
54
215
  const alive = await deps.checkSocketAlive(deps.socketPath);
55
216
  if (alive) {
56
- return {
57
- alreadyRunning: true,
58
- message: `daemon already running (${deps.socketPath})`,
217
+ const localRuntime = (0, runtime_metadata_1.getRuntimeMetadata)();
218
+ let runningRuntimePromise = null;
219
+ const fetchRunningRuntimeMetadata = async () => {
220
+ runningRuntimePromise ??= (async () => {
221
+ const status = await deps.sendCommand(deps.socketPath, { kind: "daemon.status" });
222
+ const payload = parseStatusPayload(status.data);
223
+ return {
224
+ version: payload?.overview.version ?? "unknown",
225
+ lastUpdated: payload?.overview.lastUpdated ?? "unknown",
226
+ repoRoot: payload?.overview.repoRoot ?? "unknown",
227
+ configFingerprint: payload?.overview.configFingerprint ?? "unknown",
228
+ };
229
+ })();
230
+ return runningRuntimePromise;
59
231
  };
232
+ return (0, daemon_runtime_sync_1.ensureCurrentDaemonRuntime)({
233
+ socketPath: deps.socketPath,
234
+ localVersion: localRuntime.version,
235
+ localLastUpdated: localRuntime.lastUpdated,
236
+ localRepoRoot: localRuntime.repoRoot,
237
+ localConfigFingerprint: localRuntime.configFingerprint,
238
+ fetchRunningVersion: async () => (await fetchRunningRuntimeMetadata()).version,
239
+ fetchRunningRuntimeMetadata,
240
+ stopDaemon: async () => {
241
+ await deps.sendCommand(deps.socketPath, { kind: "daemon.stop" });
242
+ },
243
+ cleanupStaleSocket: deps.cleanupStaleSocket,
244
+ startDaemonProcess: deps.startDaemonProcess,
245
+ });
60
246
  }
61
247
  deps.cleanupStaleSocket(deps.socketPath);
62
248
  const started = await deps.startDaemonProcess(deps.socketPath);
@@ -65,17 +251,86 @@ async function ensureDaemonRunning(deps) {
65
251
  message: `daemon started (pid ${started.pid ?? "unknown"})`,
66
252
  };
67
253
  }
254
+ /**
255
+ * Extract `--agent <name>` from an args array, returning the agent name and
256
+ * the remaining args with the flag pair removed.
257
+ */
258
+ function extractAgentFlag(args) {
259
+ const idx = args.indexOf("--agent");
260
+ if (idx === -1 || idx + 1 >= args.length)
261
+ return { rest: args };
262
+ const agent = args[idx + 1];
263
+ const rest = [...args.slice(0, idx), ...args.slice(idx + 2)];
264
+ return { agent, rest };
265
+ }
68
266
  function usage() {
69
267
  return [
70
268
  "Usage:",
71
269
  " ouro [up]",
72
- " ouro stop|status|logs|hatch",
270
+ " ouro stop|down|status|logs|hatch",
271
+ " ouro -v|--version",
272
+ " ouro auth --agent <name> [--provider <provider>]",
73
273
  " ouro chat <agent>",
74
274
  " ouro msg --to <agent> [--session <id>] [--task <ref>] <message>",
75
275
  " ouro poke <agent> --task <task-id>",
76
276
  " ouro link <agent> --friend <id> --provider <provider> --external-id <external-id>",
277
+ " ouro task board [<status>] [--agent <name>]",
278
+ " ouro task create <title> [--type <type>] [--agent <name>]",
279
+ " ouro task update <id> <status> [--agent <name>]",
280
+ " ouro task show <id> [--agent <name>]",
281
+ " ouro task actionable|deps|sessions [--agent <name>]",
282
+ " ouro reminder create <title> --body <body> [--at <iso>] [--cadence <interval>] [--category <category>] [--agent <name>]",
283
+ " ouro friend list [--agent <name>]",
284
+ " ouro friend show <id> [--agent <name>]",
285
+ " ouro friend create --name <name> [--trust <level>] [--agent <name>]",
286
+ " ouro thoughts [--last <n>] [--json] [--follow] [--agent <name>]",
287
+ " ouro friend link <agent> --friend <id> --provider <p> --external-id <eid>",
288
+ " ouro friend unlink <agent> --friend <id> --provider <p> --external-id <eid>",
289
+ " ouro whoami [--agent <name>]",
290
+ " ouro session list [--agent <name>]",
77
291
  ].join("\n");
78
292
  }
293
+ function formatVersionOutput() {
294
+ return (0, runtime_metadata_1.getRuntimeMetadata)().version;
295
+ }
296
+ function buildStoppedStatusPayload(socketPath) {
297
+ const metadata = (0, runtime_metadata_1.getRuntimeMetadata)();
298
+ const repoRoot = (0, identity_1.getRepoRoot)();
299
+ return {
300
+ overview: {
301
+ daemon: "stopped",
302
+ health: "warn",
303
+ socketPath,
304
+ version: metadata.version,
305
+ lastUpdated: metadata.lastUpdated,
306
+ repoRoot: metadata.repoRoot,
307
+ configFingerprint: metadata.configFingerprint,
308
+ workerCount: 0,
309
+ senseCount: 0,
310
+ entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
311
+ mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
312
+ },
313
+ senses: [],
314
+ workers: [],
315
+ };
316
+ }
317
+ function daemonUnavailableStatusOutput(socketPath) {
318
+ return [
319
+ formatDaemonStatusOutput({
320
+ ok: true,
321
+ summary: "daemon not running",
322
+ data: buildStoppedStatusPayload(socketPath),
323
+ }, "daemon not running"),
324
+ "",
325
+ "daemon not running; run `ouro up`",
326
+ ].join("\n");
327
+ }
328
+ function isDaemonUnavailableError(error) {
329
+ const code = typeof error === "object" && error !== null && "code" in error
330
+ ? String(error.code ?? "")
331
+ : "";
332
+ return code === "ENOENT" || code === "ECONNREFUSED";
333
+ }
79
334
  function parseMessageCommand(args) {
80
335
  let to;
81
336
  let sessionId;
@@ -127,7 +382,7 @@ function parsePokeCommand(args) {
127
382
  throw new Error(`Usage\n${usage()}`);
128
383
  return { kind: "task.poke", agent, taskId };
129
384
  }
130
- function parseLinkCommand(args) {
385
+ function parseLinkCommand(args, kind = "friend.link") {
131
386
  const agent = args[0];
132
387
  if (!agent)
133
388
  throw new Error(`Usage\n${usage()}`);
@@ -159,7 +414,7 @@ function parseLinkCommand(args) {
159
414
  throw new Error(`Unknown identity provider '${providerRaw}'. Use aad|local|teams-conversation.`);
160
415
  }
161
416
  return {
162
- kind: "friend.link",
417
+ kind,
163
418
  agent,
164
419
  friendId,
165
420
  provider: providerRaw,
@@ -236,13 +491,197 @@ function parseHatchCommand(args) {
236
491
  migrationPath,
237
492
  };
238
493
  }
494
+ function parseTaskCommand(args) {
495
+ const { agent, rest: cleaned } = extractAgentFlag(args);
496
+ const [sub, ...rest] = cleaned;
497
+ if (!sub)
498
+ throw new Error(`Usage\n${usage()}`);
499
+ if (sub === "board") {
500
+ const status = rest[0];
501
+ return status
502
+ ? { kind: "task.board", status, ...(agent ? { agent } : {}) }
503
+ : { kind: "task.board", ...(agent ? { agent } : {}) };
504
+ }
505
+ if (sub === "create") {
506
+ const title = rest[0];
507
+ if (!title)
508
+ throw new Error(`Usage\n${usage()}`);
509
+ let type;
510
+ for (let i = 1; i < rest.length; i++) {
511
+ if (rest[i] === "--type" && rest[i + 1]) {
512
+ type = rest[i + 1];
513
+ i += 1;
514
+ }
515
+ }
516
+ return type
517
+ ? { kind: "task.create", title, type, ...(agent ? { agent } : {}) }
518
+ : { kind: "task.create", title, ...(agent ? { agent } : {}) };
519
+ }
520
+ if (sub === "update") {
521
+ const id = rest[0];
522
+ const status = rest[1];
523
+ if (!id || !status)
524
+ throw new Error(`Usage\n${usage()}`);
525
+ return { kind: "task.update", id, status, ...(agent ? { agent } : {}) };
526
+ }
527
+ if (sub === "show") {
528
+ const id = rest[0];
529
+ if (!id)
530
+ throw new Error(`Usage\n${usage()}`);
531
+ return { kind: "task.show", id, ...(agent ? { agent } : {}) };
532
+ }
533
+ if (sub === "actionable")
534
+ return { kind: "task.actionable", ...(agent ? { agent } : {}) };
535
+ if (sub === "deps")
536
+ return { kind: "task.deps", ...(agent ? { agent } : {}) };
537
+ if (sub === "sessions")
538
+ return { kind: "task.sessions", ...(agent ? { agent } : {}) };
539
+ throw new Error(`Usage\n${usage()}`);
540
+ }
541
+ function parseAuthCommand(args) {
542
+ const { agent, rest } = extractAgentFlag(args);
543
+ let provider;
544
+ for (let i = 0; i < rest.length; i += 1) {
545
+ if (rest[i] === "--provider") {
546
+ const value = rest[i + 1];
547
+ if (!isAgentProvider(value))
548
+ throw new Error(`Usage\n${usage()}`);
549
+ provider = value;
550
+ i += 1;
551
+ continue;
552
+ }
553
+ }
554
+ if (!agent)
555
+ throw new Error(`Usage\n${usage()}`);
556
+ return provider ? { kind: "auth.run", agent, provider } : { kind: "auth.run", agent };
557
+ }
558
+ function parseReminderCommand(args) {
559
+ const { agent, rest: cleaned } = extractAgentFlag(args);
560
+ const [sub, ...rest] = cleaned;
561
+ if (!sub)
562
+ throw new Error(`Usage\n${usage()}`);
563
+ if (sub === "create") {
564
+ const title = rest[0];
565
+ if (!title)
566
+ throw new Error(`Usage\n${usage()}`);
567
+ let body;
568
+ let scheduledAt;
569
+ let cadence;
570
+ let category;
571
+ let requester;
572
+ for (let i = 1; i < rest.length; i++) {
573
+ if (rest[i] === "--body" && rest[i + 1]) {
574
+ body = rest[i + 1];
575
+ i += 1;
576
+ }
577
+ else if (rest[i] === "--at" && rest[i + 1]) {
578
+ scheduledAt = rest[i + 1];
579
+ i += 1;
580
+ }
581
+ else if (rest[i] === "--cadence" && rest[i + 1]) {
582
+ cadence = rest[i + 1];
583
+ i += 1;
584
+ }
585
+ else if (rest[i] === "--category" && rest[i + 1]) {
586
+ category = rest[i + 1];
587
+ i += 1;
588
+ }
589
+ else if (rest[i] === "--requester" && rest[i + 1]) {
590
+ requester = rest[i + 1];
591
+ i += 1;
592
+ }
593
+ }
594
+ if (!body)
595
+ throw new Error(`Usage\n${usage()}`);
596
+ if (!scheduledAt && !cadence)
597
+ throw new Error(`Usage\n${usage()}`);
598
+ return {
599
+ kind: "reminder.create",
600
+ title,
601
+ body,
602
+ ...(scheduledAt ? { scheduledAt } : {}),
603
+ ...(cadence ? { cadence } : {}),
604
+ ...(category ? { category } : {}),
605
+ ...(requester ? { requester } : {}),
606
+ ...(agent ? { agent } : {}),
607
+ };
608
+ }
609
+ throw new Error(`Usage\n${usage()}`);
610
+ }
611
+ function parseSessionCommand(args) {
612
+ const { agent, rest: cleaned } = extractAgentFlag(args);
613
+ const [sub] = cleaned;
614
+ if (!sub)
615
+ throw new Error(`Usage\n${usage()}`);
616
+ if (sub === "list")
617
+ return { kind: "session.list", ...(agent ? { agent } : {}) };
618
+ throw new Error(`Usage\n${usage()}`);
619
+ }
620
+ function parseThoughtsCommand(args) {
621
+ const { agent, rest: cleaned } = extractAgentFlag(args);
622
+ let last;
623
+ let json = false;
624
+ let follow = false;
625
+ for (let i = 0; i < cleaned.length; i++) {
626
+ if (cleaned[i] === "--last" && i + 1 < cleaned.length) {
627
+ last = Number.parseInt(cleaned[i + 1], 10);
628
+ i++;
629
+ }
630
+ if (cleaned[i] === "--json")
631
+ json = true;
632
+ if (cleaned[i] === "--follow" || cleaned[i] === "-f")
633
+ follow = true;
634
+ }
635
+ return { kind: "thoughts", ...(agent ? { agent } : {}), ...(last ? { last } : {}), ...(json ? { json } : {}), ...(follow ? { follow } : {}) };
636
+ }
637
+ function parseFriendCommand(args) {
638
+ const { agent, rest: cleaned } = extractAgentFlag(args);
639
+ const [sub, ...rest] = cleaned;
640
+ if (!sub)
641
+ throw new Error(`Usage\n${usage()}`);
642
+ if (sub === "list")
643
+ return { kind: "friend.list", ...(agent ? { agent } : {}) };
644
+ if (sub === "show") {
645
+ const friendId = rest[0];
646
+ if (!friendId)
647
+ throw new Error(`Usage\n${usage()}`);
648
+ return { kind: "friend.show", friendId, ...(agent ? { agent } : {}) };
649
+ }
650
+ if (sub === "create") {
651
+ let name;
652
+ let trustLevel;
653
+ for (let i = 0; i < rest.length; i++) {
654
+ if (rest[i] === "--name" && rest[i + 1]) {
655
+ name = rest[i + 1];
656
+ i += 1;
657
+ }
658
+ else if (rest[i] === "--trust" && rest[i + 1]) {
659
+ trustLevel = rest[i + 1];
660
+ i += 1;
661
+ }
662
+ }
663
+ if (!name)
664
+ throw new Error(`Usage\n${usage()}`);
665
+ return {
666
+ kind: "friend.create",
667
+ name,
668
+ ...(trustLevel ? { trustLevel } : {}),
669
+ ...(agent ? { agent } : {}),
670
+ };
671
+ }
672
+ if (sub === "link")
673
+ return parseLinkCommand(rest, "friend.link");
674
+ if (sub === "unlink")
675
+ return parseLinkCommand(rest, "friend.unlink");
676
+ throw new Error(`Usage\n${usage()}`);
677
+ }
239
678
  function parseOuroCommand(args) {
240
679
  const [head, second] = args;
241
680
  if (!head)
242
681
  return { kind: "daemon.up" };
243
682
  if (head === "up")
244
683
  return { kind: "daemon.up" };
245
- if (head === "stop")
684
+ if (head === "stop" || head === "down")
246
685
  return { kind: "daemon.stop" };
247
686
  if (head === "status")
248
687
  return { kind: "daemon.status" };
@@ -250,6 +689,22 @@ function parseOuroCommand(args) {
250
689
  return { kind: "daemon.logs" };
251
690
  if (head === "hatch")
252
691
  return parseHatchCommand(args.slice(1));
692
+ if (head === "auth")
693
+ return parseAuthCommand(args.slice(1));
694
+ if (head === "task")
695
+ return parseTaskCommand(args.slice(1));
696
+ if (head === "reminder")
697
+ return parseReminderCommand(args.slice(1));
698
+ if (head === "friend")
699
+ return parseFriendCommand(args.slice(1));
700
+ if (head === "whoami") {
701
+ const { agent } = extractAgentFlag(args.slice(1));
702
+ return { kind: "whoami", ...(agent ? { agent } : {}) };
703
+ }
704
+ if (head === "session")
705
+ return parseSessionCommand(args.slice(1));
706
+ if (head === "thoughts")
707
+ return parseThoughtsCommand(args.slice(1));
253
708
  if (head === "chat") {
254
709
  if (!second)
255
710
  throw new Error(`Usage\n${usage()}`);
@@ -263,38 +718,6 @@ function parseOuroCommand(args) {
263
718
  return parseLinkCommand(args.slice(1));
264
719
  throw new Error(`Unknown command '${args.join(" ")}'.\n${usage()}`);
265
720
  }
266
- function defaultSendCommand(socketPath, command) {
267
- return new Promise((resolve, reject) => {
268
- const client = net.createConnection(socketPath);
269
- let raw = "";
270
- client.on("connect", () => {
271
- client.write(JSON.stringify(command));
272
- client.end();
273
- });
274
- client.on("data", (chunk) => {
275
- raw += chunk.toString("utf-8");
276
- });
277
- client.on("error", reject);
278
- client.on("end", () => {
279
- const trimmed = raw.trim();
280
- if (trimmed.length === 0 && command.kind === "daemon.stop") {
281
- resolve({ ok: true, message: "daemon stopped" });
282
- return;
283
- }
284
- if (trimmed.length === 0) {
285
- reject(new Error("Daemon returned empty response."));
286
- return;
287
- }
288
- try {
289
- const parsed = JSON.parse(trimmed);
290
- resolve(parsed);
291
- }
292
- catch (error) {
293
- reject(error);
294
- }
295
- });
296
- });
297
- }
298
721
  function defaultStartDaemonProcess(socketPath) {
299
722
  const entry = path.join((0, identity_1.getRepoRoot)(), "dist", "heart", "daemon", "daemon-entry.js");
300
723
  const child = (0, child_process_1.spawn)("node", [entry, "--socket", socketPath], {
@@ -308,46 +731,6 @@ function defaultWriteStdout(text) {
308
731
  // eslint-disable-next-line no-console -- terminal UX: CLI command output
309
732
  console.log(text);
310
733
  }
311
- function defaultCheckSocketAlive(socketPath) {
312
- return new Promise((resolve) => {
313
- const client = net.createConnection(socketPath);
314
- let raw = "";
315
- let done = false;
316
- const finalize = (alive) => {
317
- if (done)
318
- return;
319
- done = true;
320
- resolve(alive);
321
- };
322
- if ("setTimeout" in client && typeof client.setTimeout === "function") {
323
- client.setTimeout(800, () => {
324
- client.destroy();
325
- finalize(false);
326
- });
327
- }
328
- client.on("connect", () => {
329
- client.write(JSON.stringify({ kind: "daemon.status" }));
330
- client.end();
331
- });
332
- client.on("data", (chunk) => {
333
- raw += chunk.toString("utf-8");
334
- });
335
- client.on("error", () => finalize(false));
336
- client.on("end", () => {
337
- if (raw.trim().length === 0) {
338
- finalize(false);
339
- return;
340
- }
341
- try {
342
- JSON.parse(raw);
343
- finalize(true);
344
- }
345
- catch {
346
- finalize(false);
347
- }
348
- });
349
- });
350
- }
351
734
  function defaultCleanupStaleSocket(socketPath) {
352
735
  if (fs.existsSync(socketPath)) {
353
736
  fs.unlinkSync(socketPath);
@@ -382,6 +765,40 @@ function defaultFallbackPendingMessage(command) {
382
765
  });
383
766
  return pendingPath;
384
767
  }
768
+ function defaultEnsureDaemonBootPersistence(socketPath) {
769
+ if (process.platform !== "darwin") {
770
+ return;
771
+ }
772
+ const homeDir = os.homedir();
773
+ const launchdDeps = {
774
+ exec: (cmd) => { (0, child_process_1.execSync)(cmd, { stdio: "ignore" }); },
775
+ writeFile: (filePath, content) => fs.writeFileSync(filePath, content, "utf-8"),
776
+ removeFile: (filePath) => fs.rmSync(filePath, { force: true }),
777
+ existsFile: (filePath) => fs.existsSync(filePath),
778
+ mkdirp: (dir) => fs.mkdirSync(dir, { recursive: true }),
779
+ homeDir,
780
+ userUid: process.getuid?.() ?? 0,
781
+ };
782
+ const entryPath = path.join((0, identity_1.getRepoRoot)(), "dist", "heart", "daemon", "daemon-entry.js");
783
+ /* v8 ignore next -- covered via mock in daemon-cli-defaults.test.ts; v8 on CI attributes the real fs.existsSync branch to the non-mock load @preserve */
784
+ if (!fs.existsSync(entryPath)) {
785
+ (0, runtime_1.emitNervesEvent)({
786
+ level: "warn",
787
+ component: "daemon",
788
+ event: "daemon.entry_path_missing",
789
+ message: "entryPath does not exist on disk — plist may point to a stale location. Run 'ouro daemon install' from the correct location.",
790
+ meta: { entryPath },
791
+ });
792
+ }
793
+ const logDir = (0, identity_1.getAgentDaemonLogsDir)();
794
+ (0, launchd_1.installLaunchAgent)(launchdDeps, {
795
+ nodePath: process.execPath,
796
+ entryPath,
797
+ socketPath,
798
+ logDir,
799
+ envPath: process.env.PATH,
800
+ });
801
+ }
385
802
  async function defaultInstallSubagents() {
386
803
  return (0, subagent_installer_1.installSubagentsForAvailableCli)({
387
804
  repoRoot: (0, identity_1.getRepoRoot)(),
@@ -402,142 +819,291 @@ async function defaultPromptInput(question) {
402
819
  }
403
820
  }
404
821
  function defaultListDiscoveredAgents() {
405
- const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
822
+ return (0, agent_discovery_1.listEnabledBundleAgents)({
823
+ bundlesRoot: (0, identity_1.getAgentBundlesRoot)(),
824
+ readdirSync: fs.readdirSync,
825
+ readFileSync: fs.readFileSync,
826
+ });
827
+ }
828
+ function discoverExistingCredentials(secretsRoot) {
829
+ const found = [];
406
830
  let entries;
407
831
  try {
408
- entries = fs.readdirSync(bundlesRoot, { withFileTypes: true });
832
+ entries = fs.readdirSync(secretsRoot, { withFileTypes: true });
409
833
  }
410
834
  catch {
411
- return [];
835
+ return found;
412
836
  }
413
- const discovered = [];
414
837
  for (const entry of entries) {
415
- if (!entry.isDirectory() || !entry.name.endsWith(".ouro"))
838
+ if (!entry.isDirectory())
416
839
  continue;
417
- const agentName = entry.name.slice(0, -5);
418
- const configPath = path.join(bundlesRoot, entry.name, "agent.json");
419
- let enabled = true;
840
+ const secretsPath = path.join(secretsRoot, entry.name, "secrets.json");
841
+ let raw;
420
842
  try {
421
- const raw = fs.readFileSync(configPath, "utf-8");
422
- const parsed = JSON.parse(raw);
423
- if (typeof parsed.enabled === "boolean") {
424
- enabled = parsed.enabled;
425
- }
843
+ raw = fs.readFileSync(secretsPath, "utf-8");
426
844
  }
427
845
  catch {
428
846
  continue;
429
847
  }
430
- if (enabled) {
431
- discovered.push(agentName);
848
+ let parsed;
849
+ try {
850
+ parsed = JSON.parse(raw);
851
+ }
852
+ catch {
853
+ continue;
854
+ }
855
+ if (!parsed.providers)
856
+ continue;
857
+ for (const [provName, provConfig] of Object.entries(parsed.providers)) {
858
+ if (provName === "anthropic" && provConfig.setupToken) {
859
+ found.push({ agentName: entry.name, provider: "anthropic", credentials: { setupToken: provConfig.setupToken }, providerConfig: { ...provConfig } });
860
+ }
861
+ else if (provName === "openai-codex" && provConfig.oauthAccessToken) {
862
+ found.push({ agentName: entry.name, provider: "openai-codex", credentials: { oauthAccessToken: provConfig.oauthAccessToken }, providerConfig: { ...provConfig } });
863
+ }
864
+ else if (provName === "minimax" && provConfig.apiKey) {
865
+ found.push({ agentName: entry.name, provider: "minimax", credentials: { apiKey: provConfig.apiKey }, providerConfig: { ...provConfig } });
866
+ }
867
+ else if (provName === "azure" && provConfig.apiKey && provConfig.endpoint && provConfig.deployment) {
868
+ found.push({ agentName: entry.name, provider: "azure", credentials: { apiKey: provConfig.apiKey, endpoint: provConfig.endpoint, deployment: provConfig.deployment }, providerConfig: { ...provConfig } });
869
+ }
432
870
  }
433
871
  }
434
- return discovered.sort((left, right) => left.localeCompare(right));
435
- }
436
- async function defaultLinkFriendIdentity(command) {
437
- const friendStore = new store_file_1.FileFriendStore(path.join((0, identity_1.getAgentBundlesRoot)(), `${command.agent}.ouro`, "friends"));
438
- const current = await friendStore.get(command.friendId);
439
- if (!current) {
440
- return `friend not found: ${command.friendId}`;
441
- }
442
- const alreadyLinked = current.externalIds.some((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
443
- if (alreadyLinked) {
444
- return `identity already linked: ${command.provider}:${command.externalId}`;
445
- }
446
- const now = new Date().toISOString();
447
- await friendStore.put(command.friendId, {
448
- ...current,
449
- externalIds: [
450
- ...current.externalIds,
451
- {
452
- provider: command.provider,
453
- externalId: command.externalId,
454
- linkedAt: now,
455
- },
456
- ],
457
- updatedAt: now,
872
+ // Deduplicate by provider+credential value (keep first seen)
873
+ const seen = new Set();
874
+ return found.filter((cred) => {
875
+ const key = `${cred.provider}:${JSON.stringify(cred.credentials)}`;
876
+ if (seen.has(key))
877
+ return false;
878
+ seen.add(key);
879
+ return true;
458
880
  });
459
- return `linked ${command.provider}:${command.externalId} to ${command.friendId}`;
460
881
  }
461
- /* v8 ignore next 49 -- integration: interactive terminal specialist session @preserve */
882
+ /* v8 ignore start -- integration: interactive terminal specialist session @preserve */
462
883
  async function defaultRunAdoptionSpecialist() {
463
- const readline = await Promise.resolve().then(() => __importStar(require("readline/promises")));
464
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
465
- const prompt = async (q) => {
466
- const answer = await rl.question(q);
884
+ const { runCliSession } = await Promise.resolve().then(() => __importStar(require("../../senses/cli")));
885
+ const { patchRuntimeConfig } = await Promise.resolve().then(() => __importStar(require("../config")));
886
+ const { setAgentName, setAgentConfigOverride } = await Promise.resolve().then(() => __importStar(require("../identity")));
887
+ const readlinePromises = await Promise.resolve().then(() => __importStar(require("readline/promises")));
888
+ const crypto = await Promise.resolve().then(() => __importStar(require("crypto")));
889
+ // Phase 1: cold CLI — collect provider/credentials with a simple readline
890
+ const coldRl = readlinePromises.createInterface({ input: process.stdin, output: process.stdout });
891
+ const coldPrompt = async (q) => {
892
+ const answer = await coldRl.question(q);
467
893
  return answer.trim();
468
894
  };
895
+ let providerRaw;
896
+ let credentials = {};
897
+ let providerConfig = {};
898
+ const tempDir = path.join(os.tmpdir(), `ouro-hatch-${crypto.randomUUID()}`);
469
899
  try {
470
- const humanName = await prompt("Your name: ");
471
- const providerRaw = await prompt("Provider (azure|anthropic|minimax|openai-codex): ");
472
- if (!humanName || !isAgentProvider(providerRaw)) {
473
- process.stdout.write("Invalid input. Run `ouro hatch` to try again.\n");
474
- return null;
900
+ const secretsRoot = path.join(os.homedir(), ".agentsecrets");
901
+ const discovered = discoverExistingCredentials(secretsRoot);
902
+ const existingBundleCount = (0, specialist_orchestrator_1.listExistingBundles)((0, identity_1.getAgentBundlesRoot)()).length;
903
+ const hatchVerb = existingBundleCount > 0 ? "let's hatch a new agent." : "let's hatch your first agent.";
904
+ // Default models per provider (used when entering new credentials)
905
+ const defaultModels = {
906
+ anthropic: "claude-opus-4-6",
907
+ minimax: "MiniMax-Text-01",
908
+ "openai-codex": "gpt-5.4",
909
+ azure: "",
910
+ };
911
+ if (discovered.length > 0) {
912
+ process.stdout.write(`\n\ud83d\udc0d welcome to ouroboros! ${hatchVerb}\n`);
913
+ process.stdout.write("i found existing API credentials:\n\n");
914
+ const unique = [...new Map(discovered.map((d) => [`${d.provider}`, d])).values()];
915
+ for (let i = 0; i < unique.length; i++) {
916
+ const model = unique[i].providerConfig.model || unique[i].providerConfig.deployment || "";
917
+ const modelLabel = model ? `, ${model}` : "";
918
+ process.stdout.write(` ${i + 1}. ${unique[i].provider}${modelLabel} (from ${unique[i].agentName})\n`);
919
+ }
920
+ process.stdout.write("\n");
921
+ const choice = await coldPrompt("use one of these? enter number, or 'new' for a different key: ");
922
+ const idx = parseInt(choice, 10) - 1;
923
+ if (idx >= 0 && idx < unique.length) {
924
+ providerRaw = unique[idx].provider;
925
+ credentials = unique[idx].credentials;
926
+ providerConfig = unique[idx].providerConfig;
927
+ }
928
+ else {
929
+ const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex): ");
930
+ if (!isAgentProvider(pRaw)) {
931
+ process.stdout.write("unknown provider. run `ouro hatch` to try again.\n");
932
+ coldRl.close();
933
+ return null;
934
+ }
935
+ providerRaw = pRaw;
936
+ providerConfig = { model: defaultModels[providerRaw] };
937
+ if (providerRaw === "anthropic")
938
+ credentials.setupToken = await coldPrompt("API key: ");
939
+ if (providerRaw === "openai-codex")
940
+ credentials.oauthAccessToken = await coldPrompt("OAuth token: ");
941
+ if (providerRaw === "minimax")
942
+ credentials.apiKey = await coldPrompt("API key: ");
943
+ if (providerRaw === "azure") {
944
+ credentials.apiKey = await coldPrompt("API key: ");
945
+ credentials.endpoint = await coldPrompt("endpoint: ");
946
+ credentials.deployment = await coldPrompt("deployment: ");
947
+ }
948
+ }
475
949
  }
476
- const credentials = {};
477
- if (providerRaw === "anthropic")
478
- credentials.setupToken = await prompt("Anthropic API key: ");
479
- if (providerRaw === "openai-codex")
480
- credentials.oauthAccessToken = await prompt("OpenAI Codex OAuth token: ");
481
- if (providerRaw === "minimax")
482
- credentials.apiKey = await prompt("MiniMax API key: ");
483
- if (providerRaw === "azure") {
484
- credentials.apiKey = await prompt("Azure API key: ");
485
- credentials.endpoint = await prompt("Azure endpoint: ");
486
- credentials.deployment = await prompt("Azure deployment: ");
950
+ else {
951
+ process.stdout.write(`\n\ud83d\udc0d welcome to ouroboros! ${hatchVerb}\n`);
952
+ process.stdout.write("i need an API key to power our conversation.\n\n");
953
+ const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex): ");
954
+ if (!isAgentProvider(pRaw)) {
955
+ process.stdout.write("unknown provider. run `ouro hatch` to try again.\n");
956
+ coldRl.close();
957
+ return null;
958
+ }
959
+ providerRaw = pRaw;
960
+ providerConfig = { model: defaultModels[providerRaw] };
961
+ if (providerRaw === "anthropic")
962
+ credentials.setupToken = await coldPrompt("API key: ");
963
+ if (providerRaw === "openai-codex")
964
+ credentials.oauthAccessToken = await coldPrompt("OAuth token: ");
965
+ if (providerRaw === "minimax")
966
+ credentials.apiKey = await coldPrompt("API key: ");
967
+ if (providerRaw === "azure") {
968
+ credentials.apiKey = await coldPrompt("API key: ");
969
+ credentials.endpoint = await coldPrompt("endpoint: ");
970
+ credentials.deployment = await coldPrompt("deployment: ");
971
+ }
487
972
  }
488
- rl.close();
489
- // Locate the bundled AdoptionSpecialist.ouro shipped with the npm package
973
+ coldRl.close();
974
+ process.stdout.write("\n");
975
+ // Phase 2: configure runtime for adoption specialist
490
976
  const bundleSourceDir = path.resolve(__dirname, "..", "..", "..", "AdoptionSpecialist.ouro");
491
977
  const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
492
- const secretsRoot = path.join(os.homedir(), ".agentsecrets");
493
- return await (0, specialist_orchestrator_1.runAdoptionSpecialist)({
494
- bundleSourceDir,
495
- bundlesRoot,
496
- secretsRoot,
978
+ const secretsRoot2 = path.join(os.homedir(), ".agentsecrets");
979
+ // Suppress non-critical log noise during adoption (no secrets.json, etc.)
980
+ const { setRuntimeLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves/runtime")));
981
+ const { createLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves")));
982
+ setRuntimeLogger(createLogger({ level: "error" }));
983
+ // Configure runtime: set agent identity + config override so runAgent
984
+ // doesn't try to read from ~/AgentBundles/AdoptionSpecialist.ouro/
985
+ setAgentName("AdoptionSpecialist");
986
+ // Build specialist system prompt
987
+ const soulText = (0, specialist_orchestrator_1.loadSoulText)(bundleSourceDir);
988
+ const identitiesDir = path.join(bundleSourceDir, "psyche", "identities");
989
+ const identity = (0, specialist_orchestrator_1.pickRandomIdentity)(identitiesDir);
990
+ // Load identity-specific spinner phrases (falls back to DEFAULT_AGENT_PHRASES)
991
+ const { loadIdentityPhrases } = await Promise.resolve().then(() => __importStar(require("./specialist-orchestrator")));
992
+ const phrases = loadIdentityPhrases(bundleSourceDir, identity.fileName);
993
+ setAgentConfigOverride({
994
+ version: 1,
995
+ enabled: true,
497
996
  provider: providerRaw,
498
- credentials,
499
- humanName,
500
- createReadline: () => {
501
- const rl2 = readline.createInterface({ input: process.stdin, output: process.stdout });
502
- return { question: (q) => rl2.question(q), close: () => rl2.close() };
503
- },
504
- callbacks: {
505
- onModelStart: () => { },
506
- onModelStreamStart: () => { },
507
- onTextChunk: (text) => process.stdout.write(text),
508
- onReasoningChunk: () => { },
509
- onToolStart: () => { },
510
- onToolEnd: () => { },
511
- onError: (err) => process.stderr.write(`error: ${err.message}\n`),
997
+ phrases,
998
+ });
999
+ patchRuntimeConfig({
1000
+ providers: {
1001
+ [providerRaw]: { ...providerConfig, ...credentials },
512
1002
  },
513
1003
  });
1004
+ const existingBundles = (0, specialist_orchestrator_1.listExistingBundles)(bundlesRoot);
1005
+ const systemPrompt = (0, specialist_prompt_1.buildSpecialistSystemPrompt)(soulText, identity.content, existingBundles, {
1006
+ tempDir,
1007
+ provider: providerRaw,
1008
+ });
1009
+ // Build specialist tools
1010
+ const specialistTools = (0, specialist_tools_1.getSpecialistTools)();
1011
+ const specialistExecTool = (0, specialist_tools_1.createSpecialistExecTool)({
1012
+ tempDir,
1013
+ credentials,
1014
+ provider: providerRaw,
1015
+ bundlesRoot,
1016
+ secretsRoot: secretsRoot2,
1017
+ animationWriter: (text) => process.stdout.write(text),
1018
+ });
1019
+ // Run the adoption specialist session via runCliSession
1020
+ const result = await runCliSession({
1021
+ agentName: "AdoptionSpecialist",
1022
+ tools: specialistTools,
1023
+ execTool: specialistExecTool,
1024
+ exitOnToolCall: "complete_adoption",
1025
+ autoFirstTurn: true,
1026
+ banner: false,
1027
+ disableCommands: true,
1028
+ skipSystemPromptRefresh: true,
1029
+ messages: [
1030
+ { role: "system", content: systemPrompt },
1031
+ { role: "user", content: "hi" },
1032
+ ],
1033
+ });
1034
+ if (result.exitReason === "tool_exit" && result.toolResult) {
1035
+ const parsed = typeof result.toolResult === "string" ? JSON.parse(result.toolResult) : result.toolResult;
1036
+ if (parsed.success && parsed.agentName) {
1037
+ return parsed.agentName;
1038
+ }
1039
+ }
1040
+ return null;
514
1041
  }
515
- catch {
516
- rl.close();
1042
+ catch (err) {
1043
+ process.stderr.write(`\nouro adoption error: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
1044
+ coldRl.close();
517
1045
  return null;
518
1046
  }
1047
+ finally {
1048
+ // Clear specialist config/identity so the hatched agent gets its own
1049
+ setAgentConfigOverride(null);
1050
+ const { resetProviderRuntime } = await Promise.resolve().then(() => __importStar(require("../core")));
1051
+ resetProviderRuntime();
1052
+ const { resetConfigCache } = await Promise.resolve().then(() => __importStar(require("../config")));
1053
+ resetConfigCache();
1054
+ // Restore default logging
1055
+ const { setRuntimeLogger: restoreLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves/runtime")));
1056
+ restoreLogger(null);
1057
+ // Clean up temp dir if it still exists
1058
+ try {
1059
+ if (fs.existsSync(tempDir)) {
1060
+ fs.rmSync(tempDir, { recursive: true, force: true });
1061
+ }
1062
+ }
1063
+ catch {
1064
+ // Best effort cleanup
1065
+ }
1066
+ }
519
1067
  }
520
- function createDefaultOuroCliDeps(socketPath = "/tmp/ouroboros-daemon.sock") {
1068
+ /* v8 ignore stop */
1069
+ function createDefaultOuroCliDeps(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
521
1070
  return {
522
1071
  socketPath,
523
- sendCommand: defaultSendCommand,
1072
+ sendCommand: socket_client_1.sendDaemonCommand,
524
1073
  startDaemonProcess: defaultStartDaemonProcess,
525
1074
  writeStdout: defaultWriteStdout,
526
- checkSocketAlive: defaultCheckSocketAlive,
1075
+ checkSocketAlive: socket_client_1.checkDaemonSocketAlive,
527
1076
  cleanupStaleSocket: defaultCleanupStaleSocket,
528
1077
  fallbackPendingMessage: defaultFallbackPendingMessage,
529
1078
  installSubagents: defaultInstallSubagents,
530
- linkFriendIdentity: defaultLinkFriendIdentity,
531
1079
  listDiscoveredAgents: defaultListDiscoveredAgents,
532
1080
  runHatchFlow: hatch_flow_1.runHatchFlow,
533
1081
  promptInput: defaultPromptInput,
534
1082
  runAdoptionSpecialist: defaultRunAdoptionSpecialist,
1083
+ runAuthFlow: auth_flow_1.runRuntimeAuthFlow,
535
1084
  registerOuroBundleType: ouro_uti_1.registerOuroBundleUti,
1085
+ installOuroCommand: ouro_path_installer_1.installOuroCommand,
1086
+ syncGlobalOuroBotWrapper: ouro_bot_global_installer_1.syncGlobalOuroBotWrapper,
1087
+ ensureDaemonBootPersistence: defaultEnsureDaemonBootPersistence,
536
1088
  /* v8 ignore next 3 -- integration: launches interactive CLI session @preserve */
537
1089
  startChat: async (agentName) => {
538
1090
  const { main } = await Promise.resolve().then(() => __importStar(require("../../senses/cli")));
539
1091
  await main(agentName);
540
1092
  },
1093
+ scanSessions: async () => {
1094
+ const agentName = (0, identity_1.getAgentName)();
1095
+ const agentRoot = (0, identity_1.getAgentRoot)(agentName);
1096
+ return (0, session_activity_1.listSessionActivity)({
1097
+ sessionsDir: path.join(agentRoot, "state", "sessions"),
1098
+ friendsDir: path.join(agentRoot, "friends"),
1099
+ agentName,
1100
+ }).map((entry) => ({
1101
+ friendId: entry.friendId,
1102
+ friendName: entry.friendName,
1103
+ channel: entry.channel,
1104
+ lastActivity: entry.lastActivityAt,
1105
+ }));
1106
+ },
541
1107
  };
542
1108
  }
543
1109
  function toDaemonCommand(command) {
@@ -551,24 +1117,13 @@ async function resolveHatchInput(command, deps) {
551
1117
  if (!agentName || !humanName || !isAgentProvider(providerRaw)) {
552
1118
  throw new Error(`Usage\n${usage()}`);
553
1119
  }
554
- const credentials = { ...(command.credentials ?? {}) };
555
- if (providerRaw === "anthropic" && !credentials.setupToken && prompt) {
556
- credentials.setupToken = await prompt("Anthropic setup-token: ");
557
- }
558
- if (providerRaw === "openai-codex" && !credentials.oauthAccessToken && prompt) {
559
- credentials.oauthAccessToken = await prompt("OpenAI Codex OAuth token: ");
560
- }
561
- if (providerRaw === "minimax" && !credentials.apiKey && prompt) {
562
- credentials.apiKey = await prompt("MiniMax API key: ");
563
- }
564
- if (providerRaw === "azure") {
565
- if (!credentials.apiKey && prompt)
566
- credentials.apiKey = await prompt("Azure API key: ");
567
- if (!credentials.endpoint && prompt)
568
- credentials.endpoint = await prompt("Azure endpoint: ");
569
- if (!credentials.deployment && prompt)
570
- credentials.deployment = await prompt("Azure deployment: ");
571
- }
1120
+ const credentials = await (0, auth_flow_1.resolveHatchCredentials)({
1121
+ agentName,
1122
+ provider: providerRaw,
1123
+ credentials: command.credentials,
1124
+ promptInput: prompt,
1125
+ runAuthFlow: deps.runAuthFlow,
1126
+ });
572
1127
  return {
573
1128
  agentName,
574
1129
  humanName,
@@ -594,12 +1149,236 @@ async function registerOuroBundleTypeNonBlocking(deps) {
594
1149
  });
595
1150
  }
596
1151
  }
1152
+ async function performSystemSetup(deps) {
1153
+ // Install ouro command to PATH (non-blocking)
1154
+ if (deps.installOuroCommand) {
1155
+ try {
1156
+ deps.installOuroCommand();
1157
+ }
1158
+ catch (error) {
1159
+ (0, runtime_1.emitNervesEvent)({
1160
+ level: "warn",
1161
+ component: "daemon",
1162
+ event: "daemon.system_setup_ouro_cmd_error",
1163
+ message: "failed to install ouro command to PATH",
1164
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
1165
+ });
1166
+ }
1167
+ }
1168
+ if (deps.syncGlobalOuroBotWrapper) {
1169
+ try {
1170
+ await Promise.resolve(deps.syncGlobalOuroBotWrapper());
1171
+ }
1172
+ catch (error) {
1173
+ (0, runtime_1.emitNervesEvent)({
1174
+ level: "warn",
1175
+ component: "daemon",
1176
+ event: "daemon.system_setup_ouro_bot_wrapper_error",
1177
+ message: "failed to sync global ouro.bot wrapper",
1178
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
1179
+ });
1180
+ }
1181
+ }
1182
+ // Install subagents (claude/codex skills)
1183
+ try {
1184
+ await deps.installSubagents();
1185
+ }
1186
+ catch (error) {
1187
+ (0, runtime_1.emitNervesEvent)({
1188
+ level: "warn",
1189
+ component: "daemon",
1190
+ event: "daemon.subagent_install_error",
1191
+ message: "subagent auto-install failed",
1192
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
1193
+ });
1194
+ }
1195
+ // Register .ouro bundle type (UTI on macOS)
1196
+ await registerOuroBundleTypeNonBlocking(deps);
1197
+ }
1198
+ function executeTaskCommand(command, taskMod) {
1199
+ if (command.kind === "task.board") {
1200
+ if (command.status) {
1201
+ const lines = taskMod.boardStatus(command.status);
1202
+ return lines.length > 0 ? lines.join("\n") : "no tasks in that status";
1203
+ }
1204
+ const board = taskMod.getBoard();
1205
+ return board.full || board.compact || "no tasks found";
1206
+ }
1207
+ if (command.kind === "task.create") {
1208
+ try {
1209
+ const created = taskMod.createTask({
1210
+ title: command.title,
1211
+ type: command.type ?? "one-shot",
1212
+ category: "general",
1213
+ body: "",
1214
+ });
1215
+ return `created: ${created}`;
1216
+ }
1217
+ catch (error) {
1218
+ return `error: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
1219
+ }
1220
+ }
1221
+ if (command.kind === "task.update") {
1222
+ const result = taskMod.updateStatus(command.id, command.status);
1223
+ if (!result.ok) {
1224
+ return `error: ${result.reason ?? "status update failed"}`;
1225
+ }
1226
+ const archivedSuffix = result.archived && result.archived.length > 0
1227
+ ? ` | archived: ${result.archived.join(", ")}`
1228
+ : "";
1229
+ return `updated: ${command.id} -> ${result.to}${archivedSuffix}`;
1230
+ }
1231
+ if (command.kind === "task.show") {
1232
+ const task = taskMod.getTask(command.id);
1233
+ if (!task)
1234
+ return `task not found: ${command.id}`;
1235
+ return [
1236
+ `title: ${task.title}`,
1237
+ `type: ${task.type}`,
1238
+ `status: ${task.status}`,
1239
+ `category: ${task.category}`,
1240
+ `created: ${task.created}`,
1241
+ `updated: ${task.updated}`,
1242
+ `path: ${task.path}`,
1243
+ task.body ? `\n${task.body}` : "",
1244
+ ].filter(Boolean).join("\n");
1245
+ }
1246
+ if (command.kind === "task.actionable") {
1247
+ const lines = taskMod.boardAction();
1248
+ return lines.length > 0 ? lines.join("\n") : "no action required";
1249
+ }
1250
+ if (command.kind === "task.deps") {
1251
+ const lines = taskMod.boardDeps();
1252
+ return lines.length > 0 ? lines.join("\n") : "no unresolved dependencies";
1253
+ }
1254
+ // command.kind === "task.sessions"
1255
+ const lines = taskMod.boardSessions();
1256
+ return lines.length > 0 ? lines.join("\n") : "no active sessions";
1257
+ }
1258
+ const TRUST_RANK = { family: 4, friend: 3, acquaintance: 2, stranger: 1 };
1259
+ /* v8 ignore start -- defensive: ?? fallbacks are unreachable when inputs are valid TrustLevel values @preserve */
1260
+ function higherTrust(a, b) {
1261
+ const rankA = TRUST_RANK[a ?? "stranger"] ?? 1;
1262
+ const rankB = TRUST_RANK[b ?? "stranger"] ?? 1;
1263
+ return rankA >= rankB ? (a ?? "stranger") : (b ?? "stranger");
1264
+ }
1265
+ /* v8 ignore stop */
1266
+ async function executeFriendCommand(command, store) {
1267
+ if (command.kind === "friend.list") {
1268
+ const listAll = store.listAll;
1269
+ if (!listAll)
1270
+ return "friend store does not support listing";
1271
+ const friends = await listAll.call(store);
1272
+ if (friends.length === 0)
1273
+ return "no friends found";
1274
+ const lines = friends.map((f) => {
1275
+ const trust = f.trustLevel ?? "unknown";
1276
+ return `${f.id} ${f.name} ${trust}`;
1277
+ });
1278
+ return lines.join("\n");
1279
+ }
1280
+ if (command.kind === "friend.show") {
1281
+ const record = await store.get(command.friendId);
1282
+ if (!record)
1283
+ return `friend not found: ${command.friendId}`;
1284
+ return JSON.stringify(record, null, 2);
1285
+ }
1286
+ if (command.kind === "friend.create") {
1287
+ const now = new Date().toISOString();
1288
+ const id = (0, crypto_1.randomUUID)();
1289
+ const trustLevel = (command.trustLevel ?? "acquaintance");
1290
+ await store.put(id, {
1291
+ id,
1292
+ name: command.name,
1293
+ trustLevel,
1294
+ externalIds: [],
1295
+ tenantMemberships: [],
1296
+ toolPreferences: {},
1297
+ notes: {},
1298
+ totalTokens: 0,
1299
+ createdAt: now,
1300
+ updatedAt: now,
1301
+ schemaVersion: 1,
1302
+ });
1303
+ return `created: ${id} (${command.name}, ${trustLevel})`;
1304
+ }
1305
+ if (command.kind === "friend.link") {
1306
+ const current = await store.get(command.friendId);
1307
+ if (!current)
1308
+ return `friend not found: ${command.friendId}`;
1309
+ const alreadyLinked = current.externalIds.some((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
1310
+ if (alreadyLinked)
1311
+ return `identity already linked: ${command.provider}:${command.externalId}`;
1312
+ const now = new Date().toISOString();
1313
+ const newExternalIds = [
1314
+ ...current.externalIds,
1315
+ { provider: command.provider, externalId: command.externalId, linkedAt: now },
1316
+ ];
1317
+ // Orphan cleanup: check if another friend has this externalId
1318
+ const orphan = await store.findByExternalId(command.provider, command.externalId);
1319
+ let mergeMessage = "";
1320
+ let mergedNotes = { ...current.notes };
1321
+ let mergedTrust = current.trustLevel;
1322
+ let orphanExternalIds = [];
1323
+ if (orphan && orphan.id !== command.friendId) {
1324
+ // Merge orphan's notes (target's notes take priority)
1325
+ mergedNotes = { ...orphan.notes, ...current.notes };
1326
+ // Keep higher trust level
1327
+ mergedTrust = higherTrust(current.trustLevel, orphan.trustLevel);
1328
+ // Collect orphan's other externalIds (excluding the one being linked)
1329
+ orphanExternalIds = orphan.externalIds.filter((ext) => !(ext.provider === command.provider && ext.externalId === command.externalId));
1330
+ await store.delete(orphan.id);
1331
+ mergeMessage = ` (merged orphan ${orphan.id})`;
1332
+ }
1333
+ await store.put(command.friendId, {
1334
+ ...current,
1335
+ externalIds: [...newExternalIds, ...orphanExternalIds],
1336
+ notes: mergedNotes,
1337
+ trustLevel: mergedTrust,
1338
+ updatedAt: now,
1339
+ });
1340
+ return `linked ${command.provider}:${command.externalId} to ${command.friendId}${mergeMessage}`;
1341
+ }
1342
+ // command.kind === "friend.unlink"
1343
+ const current = await store.get(command.friendId);
1344
+ if (!current)
1345
+ return `friend not found: ${command.friendId}`;
1346
+ const idx = current.externalIds.findIndex((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
1347
+ if (idx === -1)
1348
+ return `identity not linked: ${command.provider}:${command.externalId}`;
1349
+ const now = new Date().toISOString();
1350
+ const filtered = current.externalIds.filter((_, i) => i !== idx);
1351
+ await store.put(command.friendId, { ...current, externalIds: filtered, updatedAt: now });
1352
+ return `unlinked ${command.provider}:${command.externalId} from ${command.friendId}`;
1353
+ }
1354
+ function executeReminderCommand(command, taskMod) {
1355
+ try {
1356
+ const created = taskMod.createTask({
1357
+ title: command.title,
1358
+ type: command.cadence ? "habit" : "one-shot",
1359
+ category: command.category ?? "reminder",
1360
+ body: command.body,
1361
+ scheduledAt: command.scheduledAt,
1362
+ cadence: command.cadence,
1363
+ requester: command.requester,
1364
+ });
1365
+ return `created: ${created}`;
1366
+ }
1367
+ catch (error) {
1368
+ return `error: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
1369
+ }
1370
+ }
597
1371
  async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
598
1372
  if (args.includes("--help") || args.includes("-h")) {
599
1373
  const text = usage();
600
1374
  deps.writeStdout(text);
601
1375
  return text;
602
1376
  }
1377
+ if (args.length === 1 && (args[0] === "-v" || args[0] === "--version")) {
1378
+ const text = formatVersionOutput();
1379
+ deps.writeStdout(text);
1380
+ return text;
1381
+ }
603
1382
  let command;
604
1383
  try {
605
1384
  command = parseOuroCommand(args);
@@ -618,23 +1397,12 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
618
1397
  if (args.length === 0) {
619
1398
  const discovered = await Promise.resolve(deps.listDiscoveredAgents ? deps.listDiscoveredAgents() : defaultListDiscoveredAgents());
620
1399
  if (discovered.length === 0 && deps.runAdoptionSpecialist) {
1400
+ // System setup first — ouro command, subagents, UTI — before the interactive specialist
1401
+ await performSystemSetup(deps);
621
1402
  const hatchlingName = await deps.runAdoptionSpecialist();
622
1403
  if (!hatchlingName) {
623
1404
  return "";
624
1405
  }
625
- try {
626
- await deps.installSubagents();
627
- }
628
- catch (error) {
629
- (0, runtime_1.emitNervesEvent)({
630
- level: "warn",
631
- component: "daemon",
632
- event: "daemon.subagent_install_error",
633
- message: "subagent auto-install failed",
634
- meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
635
- });
636
- }
637
- await registerOuroBundleTypeNonBlocking(deps);
638
1406
  await ensureDaemonRunning(deps);
639
1407
  if (deps.startChat) {
640
1408
  await deps.startChat(hatchlingName);
@@ -681,19 +1449,34 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
681
1449
  meta: { kind: command.kind },
682
1450
  });
683
1451
  if (command.kind === "daemon.up") {
684
- try {
685
- await deps.installSubagents();
1452
+ await performSystemSetup(deps);
1453
+ if (deps.ensureDaemonBootPersistence) {
1454
+ try {
1455
+ await Promise.resolve(deps.ensureDaemonBootPersistence(deps.socketPath));
1456
+ }
1457
+ catch (error) {
1458
+ (0, runtime_1.emitNervesEvent)({
1459
+ level: "warn",
1460
+ component: "daemon",
1461
+ event: "daemon.system_setup_launchd_error",
1462
+ message: "failed to persist daemon boot startup",
1463
+ meta: { error: error instanceof Error ? error.message : String(error), socketPath: deps.socketPath },
1464
+ });
1465
+ }
686
1466
  }
687
- catch (error) {
688
- (0, runtime_1.emitNervesEvent)({
689
- level: "warn",
690
- component: "daemon",
691
- event: "daemon.subagent_install_error",
692
- message: "subagent auto-install failed",
693
- meta: { error: error instanceof Error ? error.message : String(error) },
694
- });
1467
+ // Run update hooks before starting daemon so user sees the output
1468
+ (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
1469
+ const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
1470
+ const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
1471
+ const updateSummary = await (0, update_hooks_1.applyPendingUpdates)(bundlesRoot, currentVersion);
1472
+ if (updateSummary.updated.length > 0) {
1473
+ const agents = updateSummary.updated.map((e) => e.agent);
1474
+ const from = updateSummary.updated[0].from;
1475
+ const to = updateSummary.updated[0].to;
1476
+ const fromStr = from ? ` (was ${from})` : "";
1477
+ const count = agents.length;
1478
+ deps.writeStdout(`updated ${count} agent${count === 1 ? "" : "s"} to runtime ${to}${fromStr}`);
695
1479
  }
696
- await registerOuroBundleTypeNonBlocking(deps);
697
1480
  const daemonResult = await ensureDaemonRunning(deps);
698
1481
  deps.writeStdout(daemonResult.message);
699
1482
  return daemonResult.message;
@@ -702,13 +1485,175 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
702
1485
  deps.tailLogs();
703
1486
  return "";
704
1487
  }
705
- if (command.kind === "friend.link") {
706
- const linker = deps.linkFriendIdentity ?? defaultLinkFriendIdentity;
707
- const message = await linker(command);
1488
+ // ── task subcommands (local, no daemon socket needed) ──
1489
+ if (command.kind === "task.board" || command.kind === "task.create" || command.kind === "task.update" ||
1490
+ command.kind === "task.show" || command.kind === "task.actionable" || command.kind === "task.deps" ||
1491
+ command.kind === "task.sessions") {
1492
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
1493
+ const taskMod = deps.taskModule ?? (0, tasks_1.getTaskModule)();
1494
+ /* v8 ignore stop */
1495
+ const message = executeTaskCommand(command, taskMod);
708
1496
  deps.writeStdout(message);
709
1497
  return message;
710
1498
  }
1499
+ // ── reminder subcommands (local, no daemon socket needed) ──
1500
+ if (command.kind === "reminder.create") {
1501
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
1502
+ const taskMod = deps.taskModule ?? (0, tasks_1.getTaskModule)();
1503
+ /* v8 ignore stop */
1504
+ const message = executeReminderCommand(command, taskMod);
1505
+ deps.writeStdout(message);
1506
+ return message;
1507
+ }
1508
+ // ── friend subcommands (local, no daemon socket needed) ──
1509
+ if (command.kind === "friend.list" || command.kind === "friend.show" || command.kind === "friend.create" ||
1510
+ command.kind === "friend.link" || command.kind === "friend.unlink") {
1511
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
1512
+ let store = deps.friendStore;
1513
+ if (!store) {
1514
+ // Derive agent-scoped friends dir from --agent flag or link/unlink's agent field
1515
+ const agentName = ("agent" in command && command.agent) ? command.agent : undefined;
1516
+ const friendsDir = agentName
1517
+ ? path.join((0, identity_1.getAgentBundlesRoot)(), `${agentName}.ouro`, "friends")
1518
+ : path.join((0, identity_1.getAgentBundlesRoot)(), "friends");
1519
+ store = new store_file_1.FileFriendStore(friendsDir);
1520
+ }
1521
+ /* v8 ignore stop */
1522
+ const message = await executeFriendCommand(command, store);
1523
+ deps.writeStdout(message);
1524
+ return message;
1525
+ }
1526
+ // ── auth (local, no daemon socket needed) ──
1527
+ if (command.kind === "auth.run") {
1528
+ const provider = command.provider ?? (0, auth_flow_1.readAgentConfigForAgent)(command.agent).config.provider;
1529
+ const authRunner = deps.runAuthFlow ?? auth_flow_1.runRuntimeAuthFlow;
1530
+ const result = await authRunner({
1531
+ agentName: command.agent,
1532
+ provider,
1533
+ promptInput: deps.promptInput,
1534
+ });
1535
+ if (command.provider) {
1536
+ (0, auth_flow_1.writeAgentProviderSelection)(command.agent, command.provider);
1537
+ }
1538
+ deps.writeStdout(result.message);
1539
+ return result.message;
1540
+ }
1541
+ // ── whoami (local, no daemon socket needed) ──
1542
+ if (command.kind === "whoami") {
1543
+ if (command.agent) {
1544
+ const agentRoot = path.join((0, identity_1.getAgentBundlesRoot)(), `${command.agent}.ouro`);
1545
+ const message = [
1546
+ `agent: ${command.agent}`,
1547
+ `home: ${agentRoot}`,
1548
+ `bones: ${(0, runtime_metadata_1.getRuntimeMetadata)().version}`,
1549
+ ].join("\n");
1550
+ deps.writeStdout(message);
1551
+ return message;
1552
+ }
1553
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
1554
+ try {
1555
+ const info = deps.whoamiInfo
1556
+ ? deps.whoamiInfo()
1557
+ : {
1558
+ agentName: (0, identity_1.getAgentName)(),
1559
+ homePath: path.join((0, identity_1.getAgentBundlesRoot)(), `${(0, identity_1.getAgentName)()}.ouro`),
1560
+ bonesVersion: (0, runtime_metadata_1.getRuntimeMetadata)().version,
1561
+ };
1562
+ const message = [
1563
+ `agent: ${info.agentName}`,
1564
+ `home: ${info.homePath}`,
1565
+ `bones: ${info.bonesVersion}`,
1566
+ ].join("\n");
1567
+ deps.writeStdout(message);
1568
+ return message;
1569
+ }
1570
+ catch {
1571
+ const message = "error: no agent context — use --agent <name> to specify";
1572
+ deps.writeStdout(message);
1573
+ return message;
1574
+ }
1575
+ /* v8 ignore stop */
1576
+ }
1577
+ // ── thoughts (local, no daemon socket needed) ──
1578
+ if (command.kind === "thoughts") {
1579
+ try {
1580
+ const agentName = command.agent ?? (0, identity_1.getAgentName)();
1581
+ const agentRoot = path.join((0, identity_1.getAgentBundlesRoot)(), `${agentName}.ouro`);
1582
+ const sessionFilePath = (0, thoughts_1.getInnerDialogSessionPath)(agentRoot);
1583
+ if (command.json) {
1584
+ try {
1585
+ const raw = fs.readFileSync(sessionFilePath, "utf-8");
1586
+ deps.writeStdout(raw);
1587
+ return raw;
1588
+ }
1589
+ catch {
1590
+ const message = "no inner dialog session found";
1591
+ deps.writeStdout(message);
1592
+ return message;
1593
+ }
1594
+ }
1595
+ const turns = (0, thoughts_1.parseInnerDialogSession)(sessionFilePath);
1596
+ const message = (0, thoughts_1.formatThoughtTurns)(turns, command.last ?? 10);
1597
+ deps.writeStdout(message);
1598
+ if (command.follow) {
1599
+ deps.writeStdout("\n\n--- following (ctrl+c to stop) ---\n");
1600
+ /* v8 ignore start -- callback tested via followThoughts unit tests @preserve */
1601
+ const stop = (0, thoughts_1.followThoughts)(sessionFilePath, (formatted) => {
1602
+ deps.writeStdout("\n" + formatted);
1603
+ });
1604
+ /* v8 ignore stop */
1605
+ // Block until process exit; cleanup watcher on SIGINT/SIGTERM
1606
+ return new Promise((resolve) => {
1607
+ const cleanup = () => { stop(); resolve(message); };
1608
+ process.once("SIGINT", cleanup);
1609
+ process.once("SIGTERM", cleanup);
1610
+ });
1611
+ }
1612
+ return message;
1613
+ }
1614
+ catch {
1615
+ const message = "error: no agent context — use --agent <name> to specify";
1616
+ deps.writeStdout(message);
1617
+ return message;
1618
+ }
1619
+ }
1620
+ // ── session list (local, no daemon socket needed) ──
1621
+ if (command.kind === "session.list") {
1622
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
1623
+ const scanner = deps.scanSessions ?? (async () => []);
1624
+ /* v8 ignore stop */
1625
+ const sessions = await scanner();
1626
+ if (sessions.length === 0) {
1627
+ const message = "no active sessions";
1628
+ deps.writeStdout(message);
1629
+ return message;
1630
+ }
1631
+ const lines = sessions.map((s) => `${s.friendId} ${s.friendName} ${s.channel} ${s.lastActivity}`);
1632
+ const message = lines.join("\n");
1633
+ deps.writeStdout(message);
1634
+ return message;
1635
+ }
1636
+ if (command.kind === "chat.connect" && deps.startChat) {
1637
+ await ensureDaemonRunning(deps);
1638
+ await deps.startChat(command.agent);
1639
+ return "";
1640
+ }
711
1641
  if (command.kind === "hatch.start") {
1642
+ // Route through adoption specialist when no explicit hatch args were provided
1643
+ const hasExplicitHatchArgs = !!(command.agentName || command.humanName || command.provider || command.credentials);
1644
+ if (deps.runAdoptionSpecialist && !hasExplicitHatchArgs) {
1645
+ // System setup first — ouro command, subagents, UTI — before the interactive specialist
1646
+ await performSystemSetup(deps);
1647
+ const hatchlingName = await deps.runAdoptionSpecialist();
1648
+ if (!hatchlingName) {
1649
+ return "";
1650
+ }
1651
+ await ensureDaemonRunning(deps);
1652
+ if (deps.startChat) {
1653
+ await deps.startChat(hatchlingName);
1654
+ }
1655
+ return "";
1656
+ }
712
1657
  const hatchRunner = deps.runHatchFlow;
713
1658
  if (!hatchRunner) {
714
1659
  const response = await deps.sendCommand(deps.socketPath, { kind: "hatch.start" });
@@ -718,19 +1663,7 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
718
1663
  }
719
1664
  const hatchInput = await resolveHatchInput(command, deps);
720
1665
  const result = await hatchRunner(hatchInput);
721
- try {
722
- await deps.installSubagents();
723
- }
724
- catch (error) {
725
- (0, runtime_1.emitNervesEvent)({
726
- level: "warn",
727
- component: "daemon",
728
- event: "daemon.subagent_install_error",
729
- message: "subagent auto-install failed",
730
- meta: { error: error instanceof Error ? error.message : String(error) },
731
- });
732
- }
733
- await registerOuroBundleTypeNonBlocking(deps);
1666
+ await performSystemSetup(deps);
734
1667
  const daemonResult = await ensureDaemonRunning(deps);
735
1668
  if (deps.startChat) {
736
1669
  await deps.startChat(hatchInput.agentName);
@@ -752,9 +1685,22 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
752
1685
  deps.writeStdout(message);
753
1686
  return message;
754
1687
  }
1688
+ if (command.kind === "daemon.status" && isDaemonUnavailableError(error)) {
1689
+ const message = daemonUnavailableStatusOutput(deps.socketPath);
1690
+ deps.writeStdout(message);
1691
+ return message;
1692
+ }
1693
+ if (command.kind === "daemon.stop" && isDaemonUnavailableError(error)) {
1694
+ const message = "daemon not running";
1695
+ deps.writeStdout(message);
1696
+ return message;
1697
+ }
755
1698
  throw error;
756
1699
  }
757
- const message = response.summary ?? response.message ?? (response.ok ? "ok" : `error: ${response.error ?? "unknown error"}`);
1700
+ const fallbackMessage = response.summary ?? response.message ?? (response.ok ? "ok" : `error: ${response.error ?? "unknown error"}`);
1701
+ const message = command.kind === "daemon.status"
1702
+ ? formatDaemonStatusOutput(response, fallbackMessage)
1703
+ : fallbackMessage;
758
1704
  deps.writeStdout(message);
759
1705
  return message;
760
1706
  }