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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/AdoptionSpecialist.ouro/agent.json +70 -9
  2. package/AdoptionSpecialist.ouro/psyche/SOUL.md +5 -2
  3. package/AdoptionSpecialist.ouro/psyche/identities/monty.md +2 -2
  4. package/README.md +147 -205
  5. package/assets/ouroboros.png +0 -0
  6. package/changelog.json +468 -0
  7. package/dist/heart/active-work.js +218 -0
  8. package/dist/heart/bridges/manager.js +358 -0
  9. package/dist/heart/bridges/state-machine.js +135 -0
  10. package/dist/heart/bridges/store.js +123 -0
  11. package/dist/heart/commitments.js +89 -0
  12. package/dist/heart/config.js +68 -23
  13. package/dist/heart/core.js +452 -93
  14. package/dist/heart/cross-chat-delivery.js +146 -0
  15. package/dist/heart/daemon/agent-discovery.js +81 -0
  16. package/dist/heart/daemon/auth-flow.js +430 -0
  17. package/dist/heart/daemon/daemon-cli.js +1779 -247
  18. package/dist/heart/daemon/daemon-entry.js +55 -6
  19. package/dist/heart/daemon/daemon-runtime-sync.js +212 -0
  20. package/dist/heart/daemon/daemon.js +216 -10
  21. package/dist/heart/daemon/hatch-animation.js +10 -3
  22. package/dist/heart/daemon/hatch-flow.js +7 -82
  23. package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
  24. package/dist/heart/daemon/launchd.js +159 -0
  25. package/dist/heart/daemon/log-tailer.js +4 -3
  26. package/dist/heart/daemon/message-router.js +17 -8
  27. package/dist/heart/daemon/ouro-bot-entry.js +0 -0
  28. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  29. package/dist/heart/daemon/ouro-entry.js +0 -0
  30. package/dist/heart/daemon/ouro-path-installer.js +260 -0
  31. package/dist/heart/daemon/ouro-uti.js +11 -2
  32. package/dist/heart/daemon/ouro-version-manager.js +164 -0
  33. package/dist/heart/daemon/process-manager.js +14 -1
  34. package/dist/heart/daemon/run-hooks.js +37 -0
  35. package/dist/heart/daemon/runtime-logging.js +58 -15
  36. package/dist/heart/daemon/runtime-metadata.js +219 -0
  37. package/dist/heart/daemon/runtime-mode.js +67 -0
  38. package/dist/heart/daemon/sense-manager.js +307 -0
  39. package/dist/heart/daemon/skill-management-installer.js +94 -0
  40. package/dist/heart/daemon/socket-client.js +202 -0
  41. package/dist/heart/daemon/specialist-orchestrator.js +53 -84
  42. package/dist/heart/daemon/specialist-prompt.js +63 -11
  43. package/dist/heart/daemon/specialist-tools.js +211 -60
  44. package/dist/heart/daemon/staged-restart.js +114 -0
  45. package/dist/heart/daemon/thoughts.js +507 -0
  46. package/dist/heart/daemon/update-checker.js +111 -0
  47. package/dist/heart/daemon/update-hooks.js +138 -0
  48. package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
  49. package/dist/heart/delegation.js +62 -0
  50. package/dist/heart/identity.js +126 -21
  51. package/dist/heart/kicks.js +1 -19
  52. package/dist/heart/model-capabilities.js +48 -0
  53. package/dist/heart/obligations.js +141 -0
  54. package/dist/heart/progress-story.js +42 -0
  55. package/dist/heart/providers/anthropic.js +74 -9
  56. package/dist/heart/providers/azure.js +86 -7
  57. package/dist/heart/providers/github-copilot.js +149 -0
  58. package/dist/heart/providers/minimax.js +4 -0
  59. package/dist/heart/providers/openai-codex.js +12 -3
  60. package/dist/heart/safe-workspace.js +228 -0
  61. package/dist/heart/sense-truth.js +61 -0
  62. package/dist/heart/session-activity.js +169 -0
  63. package/dist/heart/session-recall.js +116 -0
  64. package/dist/heart/streaming.js +100 -22
  65. package/dist/heart/target-resolution.js +123 -0
  66. package/dist/heart/turn-coordinator.js +28 -0
  67. package/dist/mind/associative-recall.js +14 -2
  68. package/dist/mind/bundle-manifest.js +70 -0
  69. package/dist/mind/context.js +27 -11
  70. package/dist/mind/first-impressions.js +16 -2
  71. package/dist/mind/friends/channel.js +35 -0
  72. package/dist/mind/friends/group-context.js +144 -0
  73. package/dist/mind/friends/store-file.js +19 -0
  74. package/dist/mind/friends/trust-explanation.js +74 -0
  75. package/dist/mind/friends/types.js +8 -0
  76. package/dist/mind/memory.js +27 -26
  77. package/dist/mind/pending.js +76 -9
  78. package/dist/mind/phrases.js +1 -0
  79. package/dist/mind/prompt.js +445 -77
  80. package/dist/mind/token-estimate.js +8 -12
  81. package/dist/nerves/cli-logging.js +15 -2
  82. package/dist/nerves/coverage/run-artifacts.js +1 -1
  83. package/dist/nerves/index.js +12 -0
  84. package/dist/repertoire/ado-client.js +4 -2
  85. package/dist/repertoire/coding/feedback.js +134 -0
  86. package/dist/repertoire/coding/index.js +4 -1
  87. package/dist/repertoire/coding/manager.js +62 -4
  88. package/dist/repertoire/coding/spawner.js +3 -3
  89. package/dist/repertoire/coding/tools.js +41 -2
  90. package/dist/repertoire/data/ado-endpoints.json +188 -0
  91. package/dist/repertoire/guardrails.js +290 -0
  92. package/dist/repertoire/mcp-client.js +254 -0
  93. package/dist/repertoire/mcp-manager.js +195 -0
  94. package/dist/repertoire/skills.js +3 -26
  95. package/dist/repertoire/tasks/board.js +12 -0
  96. package/dist/repertoire/tasks/index.js +23 -9
  97. package/dist/repertoire/tasks/transitions.js +1 -2
  98. package/dist/repertoire/tools-base.js +686 -251
  99. package/dist/repertoire/tools-bluebubbles.js +93 -0
  100. package/dist/repertoire/tools-teams.js +58 -25
  101. package/dist/repertoire/tools.js +95 -53
  102. package/dist/senses/bluebubbles-client.js +210 -5
  103. package/dist/senses/bluebubbles-entry.js +2 -0
  104. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  105. package/dist/senses/bluebubbles-media.js +339 -0
  106. package/dist/senses/bluebubbles-model.js +12 -4
  107. package/dist/senses/bluebubbles-mutation-log.js +45 -5
  108. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  109. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  110. package/dist/senses/bluebubbles.js +894 -45
  111. package/dist/senses/cli-layout.js +187 -0
  112. package/dist/senses/cli.js +405 -156
  113. package/dist/senses/continuity.js +94 -0
  114. package/dist/senses/debug-activity.js +154 -0
  115. package/dist/senses/inner-dialog-worker.js +47 -18
  116. package/dist/senses/inner-dialog.js +377 -83
  117. package/dist/senses/pipeline.js +307 -0
  118. package/dist/senses/teams.js +573 -129
  119. package/dist/senses/trust-gate.js +112 -2
  120. package/package.json +14 -3
  121. package/subagents/README.md +4 -70
  122. package/dist/heart/daemon/specialist-session.js +0 -142
  123. package/dist/heart/daemon/subagent-installer.js +0 -125
  124. package/dist/inner-worker-entry.js +0 -4
  125. package/subagents/work-doer.md +0 -233
  126. package/subagents/work-merger.md +0 -624
  127. package/subagents/work-planner.md +0 -373
@@ -34,12 +34,16 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.ensureDaemonRunning = ensureDaemonRunning;
37
+ exports.listGithubCopilotModels = listGithubCopilotModels;
38
+ exports.pingGithubCopilotModel = pingGithubCopilotModel;
37
39
  exports.parseOuroCommand = parseOuroCommand;
40
+ exports.readFirstBundleMetaVersion = readFirstBundleMetaVersion;
41
+ exports.discoverExistingCredentials = discoverExistingCredentials;
38
42
  exports.createDefaultOuroCliDeps = createDefaultOuroCliDeps;
39
43
  exports.runOuroCli = runOuroCli;
40
44
  const child_process_1 = require("child_process");
45
+ const crypto_1 = require("crypto");
41
46
  const fs = __importStar(require("fs"));
42
- const net = __importStar(require("net"));
43
47
  const os = __importStar(require("os"));
44
48
  const path = __importStar(require("path"));
45
49
  const identity_1 = require("../identity");
@@ -47,16 +51,202 @@ const runtime_1 = require("../../nerves/runtime");
47
51
  const store_file_1 = require("../../mind/friends/store-file");
48
52
  const types_1 = require("../../mind/friends/types");
49
53
  const ouro_uti_1 = require("./ouro-uti");
50
- const subagent_installer_1 = require("./subagent-installer");
54
+ const ouro_path_installer_1 = require("./ouro-path-installer");
55
+ const ouro_version_manager_1 = require("./ouro-version-manager");
56
+ const skill_management_installer_1 = require("./skill-management-installer");
51
57
  const hatch_flow_1 = require("./hatch-flow");
52
58
  const specialist_orchestrator_1 = require("./specialist-orchestrator");
59
+ const specialist_prompt_1 = require("./specialist-prompt");
60
+ const specialist_tools_1 = require("./specialist-tools");
61
+ const runtime_metadata_1 = require("./runtime-metadata");
62
+ const runtime_mode_1 = require("./runtime-mode");
63
+ const daemon_runtime_sync_1 = require("./daemon-runtime-sync");
64
+ const agent_discovery_1 = require("./agent-discovery");
65
+ const update_hooks_1 = require("./update-hooks");
66
+ const bundle_meta_1 = require("./hooks/bundle-meta");
67
+ const bundle_manifest_1 = require("../../mind/bundle-manifest");
68
+ const tasks_1 = require("../../repertoire/tasks");
69
+ const thoughts_1 = require("./thoughts");
70
+ const ouro_bot_global_installer_1 = require("./ouro-bot-global-installer");
71
+ const launchd_1 = require("./launchd");
72
+ const socket_client_1 = require("./socket-client");
73
+ const session_activity_1 = require("../session-activity");
74
+ const auth_flow_1 = require("./auth-flow");
75
+ function stringField(value) {
76
+ return typeof value === "string" ? value : null;
77
+ }
78
+ function numberField(value) {
79
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
80
+ }
81
+ function booleanField(value) {
82
+ return typeof value === "boolean" ? value : null;
83
+ }
84
+ function parseStatusPayload(data) {
85
+ if (!data || typeof data !== "object" || Array.isArray(data))
86
+ return null;
87
+ const raw = data;
88
+ const overview = raw.overview;
89
+ const senses = raw.senses;
90
+ const workers = raw.workers;
91
+ if (!overview || typeof overview !== "object" || Array.isArray(overview))
92
+ return null;
93
+ if (!Array.isArray(senses) || !Array.isArray(workers))
94
+ return null;
95
+ const parsedOverview = {
96
+ daemon: stringField(overview.daemon) ?? "unknown",
97
+ health: stringField(overview.health) ?? "unknown",
98
+ socketPath: stringField(overview.socketPath) ?? "unknown",
99
+ version: stringField(overview.version) ?? "unknown",
100
+ lastUpdated: stringField(overview.lastUpdated) ?? "unknown",
101
+ repoRoot: stringField(overview.repoRoot) ?? "unknown",
102
+ configFingerprint: stringField(overview.configFingerprint) ?? "unknown",
103
+ workerCount: numberField(overview.workerCount) ?? 0,
104
+ senseCount: numberField(overview.senseCount) ?? 0,
105
+ entryPath: stringField(overview.entryPath) ?? "unknown",
106
+ mode: stringField(overview.mode) ?? "unknown",
107
+ };
108
+ const parsedSenses = senses.map((entry) => {
109
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
110
+ return null;
111
+ const row = entry;
112
+ const agent = stringField(row.agent);
113
+ const sense = stringField(row.sense);
114
+ const status = stringField(row.status);
115
+ const detail = stringField(row.detail);
116
+ const enabled = booleanField(row.enabled);
117
+ if (!agent || !sense || !status || detail === null || enabled === null)
118
+ return null;
119
+ return {
120
+ agent,
121
+ sense,
122
+ label: stringField(row.label) ?? undefined,
123
+ enabled,
124
+ status,
125
+ detail,
126
+ };
127
+ });
128
+ const parsedWorkers = workers.map((entry) => {
129
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
130
+ return null;
131
+ const row = entry;
132
+ const agent = stringField(row.agent);
133
+ const worker = stringField(row.worker);
134
+ const status = stringField(row.status);
135
+ const restartCount = numberField(row.restartCount);
136
+ const hasPid = Object.prototype.hasOwnProperty.call(row, "pid");
137
+ const pid = row.pid === null ? null : numberField(row.pid);
138
+ const pidInvalid = !hasPid || (row.pid !== null && pid === null);
139
+ if (!agent || !worker || !status || restartCount === null || pidInvalid)
140
+ return null;
141
+ return {
142
+ agent,
143
+ worker,
144
+ status,
145
+ pid,
146
+ restartCount,
147
+ };
148
+ });
149
+ if (parsedSenses.some((row) => row === null) || parsedWorkers.some((row) => row === null))
150
+ return null;
151
+ return {
152
+ overview: parsedOverview,
153
+ senses: parsedSenses,
154
+ workers: parsedWorkers,
155
+ };
156
+ }
157
+ function humanizeSenseName(sense, label) {
158
+ if (label)
159
+ return label;
160
+ if (sense === "cli")
161
+ return "CLI";
162
+ if (sense === "bluebubbles")
163
+ return "BlueBubbles";
164
+ if (sense === "teams")
165
+ return "Teams";
166
+ return sense;
167
+ }
168
+ function formatTable(headers, rows) {
169
+ const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => row[index].length)));
170
+ const renderRow = (row) => `| ${row.map((cell, index) => cell.padEnd(widths[index])).join(" | ")} |`;
171
+ const divider = `|-${widths.map((width) => "-".repeat(width)).join("-|-")}-|`;
172
+ return [
173
+ renderRow(headers),
174
+ divider,
175
+ ...rows.map(renderRow),
176
+ ].join("\n");
177
+ }
178
+ function formatDaemonStatusOutput(response, fallback) {
179
+ const payload = parseStatusPayload(response.data);
180
+ if (!payload)
181
+ return fallback;
182
+ const overviewRows = [
183
+ ["Daemon", payload.overview.daemon],
184
+ ["Socket", payload.overview.socketPath],
185
+ ["Version", payload.overview.version],
186
+ ["Last Updated", payload.overview.lastUpdated],
187
+ ["Entry Path", payload.overview.entryPath],
188
+ ["Mode", payload.overview.mode],
189
+ ["Workers", String(payload.overview.workerCount)],
190
+ ["Senses", String(payload.overview.senseCount)],
191
+ ["Health", payload.overview.health],
192
+ ];
193
+ const senseRows = payload.senses.map((row) => [
194
+ row.agent,
195
+ humanizeSenseName(row.sense, row.label),
196
+ row.enabled ? "ON" : "OFF",
197
+ row.status,
198
+ row.detail,
199
+ ]);
200
+ const workerRows = payload.workers.map((row) => [
201
+ row.agent,
202
+ row.worker,
203
+ row.status,
204
+ row.pid === null ? "n/a" : String(row.pid),
205
+ String(row.restartCount),
206
+ ]);
207
+ return [
208
+ "Overview",
209
+ formatTable(["Item", "Value"], overviewRows),
210
+ "",
211
+ "Senses",
212
+ formatTable(["Agent", "Sense", "Enabled", "State", "Detail"], senseRows),
213
+ "",
214
+ "Workers",
215
+ formatTable(["Agent", "Worker", "State", "PID", "Restarts"], workerRows),
216
+ ].join("\n");
217
+ }
53
218
  async function ensureDaemonRunning(deps) {
54
219
  const alive = await deps.checkSocketAlive(deps.socketPath);
55
220
  if (alive) {
56
- return {
57
- alreadyRunning: true,
58
- message: `daemon already running (${deps.socketPath})`,
221
+ const localRuntime = (0, runtime_metadata_1.getRuntimeMetadata)();
222
+ let runningRuntimePromise = null;
223
+ const fetchRunningRuntimeMetadata = async () => {
224
+ runningRuntimePromise ??= (async () => {
225
+ const status = await deps.sendCommand(deps.socketPath, { kind: "daemon.status" });
226
+ const payload = parseStatusPayload(status.data);
227
+ return {
228
+ version: payload?.overview.version ?? "unknown",
229
+ lastUpdated: payload?.overview.lastUpdated ?? "unknown",
230
+ repoRoot: payload?.overview.repoRoot ?? "unknown",
231
+ configFingerprint: payload?.overview.configFingerprint ?? "unknown",
232
+ };
233
+ })();
234
+ return runningRuntimePromise;
59
235
  };
236
+ return (0, daemon_runtime_sync_1.ensureCurrentDaemonRuntime)({
237
+ socketPath: deps.socketPath,
238
+ localVersion: localRuntime.version,
239
+ localLastUpdated: localRuntime.lastUpdated,
240
+ localRepoRoot: localRuntime.repoRoot,
241
+ localConfigFingerprint: localRuntime.configFingerprint,
242
+ fetchRunningVersion: async () => (await fetchRunningRuntimeMetadata()).version,
243
+ fetchRunningRuntimeMetadata,
244
+ stopDaemon: async () => {
245
+ await deps.sendCommand(deps.socketPath, { kind: "daemon.stop" });
246
+ },
247
+ cleanupStaleSocket: deps.cleanupStaleSocket,
248
+ startDaemonProcess: deps.startDaemonProcess,
249
+ });
60
250
  }
61
251
  deps.cleanupStaleSocket(deps.socketPath);
62
252
  const started = await deps.startDaemonProcess(deps.socketPath);
@@ -65,17 +255,95 @@ async function ensureDaemonRunning(deps) {
65
255
  message: `daemon started (pid ${started.pid ?? "unknown"})`,
66
256
  };
67
257
  }
258
+ /**
259
+ * Extract `--agent <name>` from an args array, returning the agent name and
260
+ * the remaining args with the flag pair removed.
261
+ */
262
+ function extractAgentFlag(args) {
263
+ const idx = args.indexOf("--agent");
264
+ if (idx === -1 || idx + 1 >= args.length)
265
+ return { rest: args };
266
+ const agent = args[idx + 1];
267
+ const rest = [...args.slice(0, idx), ...args.slice(idx + 2)];
268
+ return { agent, rest };
269
+ }
68
270
  function usage() {
69
271
  return [
70
272
  "Usage:",
71
273
  " ouro [up]",
72
- " ouro stop|status|logs|hatch",
274
+ " ouro stop|down|status|logs|hatch",
275
+ " ouro -v|--version",
276
+ " ouro config model --agent <name> <model-name>",
277
+ " ouro config models --agent <name>",
278
+ " ouro auth --agent <name> [--provider <provider>]",
279
+ " ouro auth verify --agent <name> [--provider <provider>]",
280
+ " ouro auth switch --agent <name> --provider <provider>",
73
281
  " ouro chat <agent>",
74
282
  " ouro msg --to <agent> [--session <id>] [--task <ref>] <message>",
75
283
  " ouro poke <agent> --task <task-id>",
76
284
  " ouro link <agent> --friend <id> --provider <provider> --external-id <external-id>",
285
+ " ouro task board [<status>] [--agent <name>]",
286
+ " ouro task create <title> [--type <type>] [--agent <name>]",
287
+ " ouro task update <id> <status> [--agent <name>]",
288
+ " ouro task show <id> [--agent <name>]",
289
+ " ouro task actionable|deps|sessions [--agent <name>]",
290
+ " ouro reminder create <title> --body <body> [--at <iso>] [--cadence <interval>] [--category <category>] [--agent <name>]",
291
+ " ouro friend list [--agent <name>]",
292
+ " ouro friend show <id> [--agent <name>]",
293
+ " ouro friend create --name <name> [--trust <level>] [--agent <name>]",
294
+ " ouro friend update <id> --trust <level> [--agent <name>]",
295
+ " ouro thoughts [--last <n>] [--json] [--follow] [--agent <name>]",
296
+ " ouro friend link <agent> --friend <id> --provider <p> --external-id <eid>",
297
+ " ouro friend unlink <agent> --friend <id> --provider <p> --external-id <eid>",
298
+ " ouro whoami [--agent <name>]",
299
+ " ouro session list [--agent <name>]",
300
+ " ouro mcp list",
301
+ " ouro mcp call <server> <tool> [--args '{...}']",
302
+ " ouro rollback [<version>]",
303
+ " ouro versions",
77
304
  ].join("\n");
78
305
  }
306
+ function formatVersionOutput() {
307
+ return (0, runtime_metadata_1.getRuntimeMetadata)().version;
308
+ }
309
+ function buildStoppedStatusPayload(socketPath) {
310
+ const metadata = (0, runtime_metadata_1.getRuntimeMetadata)();
311
+ const repoRoot = (0, identity_1.getRepoRoot)();
312
+ return {
313
+ overview: {
314
+ daemon: "stopped",
315
+ health: "warn",
316
+ socketPath,
317
+ version: metadata.version,
318
+ lastUpdated: metadata.lastUpdated,
319
+ repoRoot: metadata.repoRoot,
320
+ configFingerprint: metadata.configFingerprint,
321
+ workerCount: 0,
322
+ senseCount: 0,
323
+ entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
324
+ mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
325
+ },
326
+ senses: [],
327
+ workers: [],
328
+ };
329
+ }
330
+ function daemonUnavailableStatusOutput(socketPath) {
331
+ return [
332
+ formatDaemonStatusOutput({
333
+ ok: true,
334
+ summary: "daemon not running",
335
+ data: buildStoppedStatusPayload(socketPath),
336
+ }, "daemon not running"),
337
+ "",
338
+ "daemon not running; run `ouro up`",
339
+ ].join("\n");
340
+ }
341
+ function isDaemonUnavailableError(error) {
342
+ const code = typeof error === "object" && error !== null && "code" in error
343
+ ? String(error.code ?? "")
344
+ : "";
345
+ return code === "ENOENT" || code === "ECONNREFUSED";
346
+ }
79
347
  function parseMessageCommand(args) {
80
348
  let to;
81
349
  let sessionId;
@@ -127,7 +395,7 @@ function parsePokeCommand(args) {
127
395
  throw new Error(`Usage\n${usage()}`);
128
396
  return { kind: "task.poke", agent, taskId };
129
397
  }
130
- function parseLinkCommand(args) {
398
+ function parseLinkCommand(args, kind = "friend.link") {
131
399
  const agent = args[0];
132
400
  if (!agent)
133
401
  throw new Error(`Usage\n${usage()}`);
@@ -159,7 +427,7 @@ function parseLinkCommand(args) {
159
427
  throw new Error(`Unknown identity provider '${providerRaw}'. Use aad|local|teams-conversation.`);
160
428
  }
161
429
  return {
162
- kind: "friend.link",
430
+ kind,
163
431
  agent,
164
432
  friendId,
165
433
  provider: providerRaw,
@@ -167,7 +435,132 @@ function parseLinkCommand(args) {
167
435
  };
168
436
  }
169
437
  function isAgentProvider(value) {
170
- return value === "azure" || value === "anthropic" || value === "minimax" || value === "openai-codex";
438
+ return value === "azure" || value === "anthropic" || value === "minimax" || value === "openai-codex" || value === "github-copilot";
439
+ }
440
+ /* v8 ignore start -- hasStoredCredentials: per-provider branches tested via auth switch tests @preserve */
441
+ function hasStoredCredentials(provider, providerSecrets) {
442
+ if (provider === "anthropic")
443
+ return !!providerSecrets.setupToken;
444
+ if (provider === "openai-codex")
445
+ return !!providerSecrets.oauthAccessToken;
446
+ if (provider === "github-copilot")
447
+ return !!providerSecrets.githubToken;
448
+ if (provider === "minimax")
449
+ return !!providerSecrets.apiKey;
450
+ // azure
451
+ return !!providerSecrets.endpoint && !!providerSecrets.apiKey;
452
+ }
453
+ /* v8 ignore stop */
454
+ /* v8 ignore start -- verifyProviderCredentials: per-provider branches tested via auth verify tests @preserve */
455
+ async function verifyProviderCredentials(provider, providers, fetchImpl = fetch) {
456
+ const p = providers[provider];
457
+ if (!p)
458
+ return "not configured";
459
+ if (provider === "anthropic") {
460
+ const token = p.setupToken || "";
461
+ if (!token)
462
+ return "failed (no token)";
463
+ if (token.startsWith("sk-ant-"))
464
+ return "ok";
465
+ return "failed (invalid token format)";
466
+ }
467
+ if (provider === "openai-codex") {
468
+ const token = p.oauthAccessToken || "";
469
+ return token ? "ok" : "failed (no token)";
470
+ }
471
+ if (provider === "github-copilot") {
472
+ const token = p.githubToken || "";
473
+ if (!token)
474
+ return "failed (no token)";
475
+ try {
476
+ const response = await fetchImpl("https://api.github.com/copilot_internal/user", {
477
+ headers: { Authorization: `Bearer ${token}` },
478
+ });
479
+ return response.ok ? "ok" : `failed (HTTP ${response.status})`;
480
+ }
481
+ catch (error) {
482
+ return `failed (${error.message})`;
483
+ }
484
+ }
485
+ if (provider === "minimax") {
486
+ const apiKey = p.apiKey || "";
487
+ return apiKey ? "ok" : "failed (no api key)";
488
+ }
489
+ // azure
490
+ const endpoint = p.endpoint || "";
491
+ const apiKey = p.apiKey || "";
492
+ if (!endpoint)
493
+ return "failed (no endpoint)";
494
+ if (!apiKey)
495
+ return "failed (no api key)";
496
+ return "ok";
497
+ }
498
+ async function listGithubCopilotModels(baseUrl, token, fetchImpl = fetch) {
499
+ const url = `${baseUrl.replace(/\/+$/, "")}/models`;
500
+ const response = await fetchImpl(url, {
501
+ headers: { Authorization: `Bearer ${token}` },
502
+ });
503
+ if (!response.ok) {
504
+ throw new Error(`model listing failed (HTTP ${response.status})`);
505
+ }
506
+ const body = await response.json();
507
+ /* v8 ignore start -- response shape handling: tested via config-models.test.ts @preserve */
508
+ const items = Array.isArray(body) ? body : (body?.data ?? []);
509
+ return items.map((item) => {
510
+ const rec = item;
511
+ const capabilities = Array.isArray(rec.capabilities)
512
+ ? rec.capabilities.filter((c) => typeof c === "string")
513
+ : undefined;
514
+ return {
515
+ id: String(rec.id ?? rec.name ?? ""),
516
+ name: String(rec.name ?? rec.id ?? ""),
517
+ ...(capabilities ? { capabilities } : {}),
518
+ };
519
+ });
520
+ /* v8 ignore stop */
521
+ }
522
+ async function pingGithubCopilotModel(baseUrl, token, model, fetchImpl = fetch) {
523
+ const base = baseUrl.replace(/\/+$/, "");
524
+ const isClaude = model.startsWith("claude");
525
+ const url = isClaude ? `${base}/chat/completions` : `${base}/responses`;
526
+ const body = isClaude
527
+ ? JSON.stringify({ model, messages: [{ role: "user", content: "ping" }], max_tokens: 1 })
528
+ : JSON.stringify({ model, input: "ping", max_output_tokens: 16 });
529
+ try {
530
+ const response = await fetchImpl(url, {
531
+ method: "POST",
532
+ headers: {
533
+ Authorization: `Bearer ${token}`,
534
+ "Content-Type": "application/json",
535
+ },
536
+ body,
537
+ });
538
+ if (response.ok)
539
+ return { ok: true };
540
+ let detail = `HTTP ${response.status}`;
541
+ try {
542
+ const json = await response.json();
543
+ /* v8 ignore start -- error format parsing: all branches tested via config-models.test.ts @preserve */
544
+ if (typeof json.error === "string")
545
+ detail = json.error;
546
+ else if (typeof json.error === "object" && json.error !== null) {
547
+ const errObj = json.error;
548
+ if (typeof errObj.message === "string")
549
+ detail = errObj.message;
550
+ }
551
+ else if (typeof json.message === "string")
552
+ detail = json.message;
553
+ /* v8 ignore stop */
554
+ }
555
+ catch {
556
+ // response body not JSON — keep HTTP status
557
+ }
558
+ return { ok: false, error: detail };
559
+ }
560
+ catch (err) {
561
+ /* v8 ignore next -- defensive: fetch errors are always Error instances @preserve */
562
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
563
+ }
171
564
  }
172
565
  function parseHatchCommand(args) {
173
566
  let agentName;
@@ -224,7 +617,7 @@ function parseHatchCommand(args) {
224
617
  }
225
618
  }
226
619
  if (providerRaw && !isAgentProvider(providerRaw)) {
227
- throw new Error("Unknown provider. Use azure|anthropic|minimax|openai-codex.");
620
+ throw new Error("Unknown provider. Use azure|anthropic|minimax|openai-codex|github-copilot.");
228
621
  }
229
622
  const provider = providerRaw && isAgentProvider(providerRaw) ? providerRaw : undefined;
230
623
  return {
@@ -236,13 +629,293 @@ function parseHatchCommand(args) {
236
629
  migrationPath,
237
630
  };
238
631
  }
632
+ function parseTaskCommand(args) {
633
+ const { agent, rest: cleaned } = extractAgentFlag(args);
634
+ const [sub, ...rest] = cleaned;
635
+ if (!sub)
636
+ throw new Error(`Usage\n${usage()}`);
637
+ if (sub === "board") {
638
+ const status = rest[0];
639
+ return status
640
+ ? { kind: "task.board", status, ...(agent ? { agent } : {}) }
641
+ : { kind: "task.board", ...(agent ? { agent } : {}) };
642
+ }
643
+ if (sub === "create") {
644
+ const title = rest[0];
645
+ if (!title)
646
+ throw new Error(`Usage\n${usage()}`);
647
+ let type;
648
+ for (let i = 1; i < rest.length; i++) {
649
+ if (rest[i] === "--type" && rest[i + 1]) {
650
+ type = rest[i + 1];
651
+ i += 1;
652
+ }
653
+ }
654
+ return type
655
+ ? { kind: "task.create", title, type, ...(agent ? { agent } : {}) }
656
+ : { kind: "task.create", title, ...(agent ? { agent } : {}) };
657
+ }
658
+ if (sub === "update") {
659
+ const id = rest[0];
660
+ const status = rest[1];
661
+ if (!id || !status)
662
+ throw new Error(`Usage\n${usage()}`);
663
+ return { kind: "task.update", id, status, ...(agent ? { agent } : {}) };
664
+ }
665
+ if (sub === "show") {
666
+ const id = rest[0];
667
+ if (!id)
668
+ throw new Error(`Usage\n${usage()}`);
669
+ return { kind: "task.show", id, ...(agent ? { agent } : {}) };
670
+ }
671
+ if (sub === "actionable")
672
+ return { kind: "task.actionable", ...(agent ? { agent } : {}) };
673
+ if (sub === "deps")
674
+ return { kind: "task.deps", ...(agent ? { agent } : {}) };
675
+ if (sub === "sessions")
676
+ return { kind: "task.sessions", ...(agent ? { agent } : {}) };
677
+ throw new Error(`Usage\n${usage()}`);
678
+ }
679
+ function parseAuthCommand(args) {
680
+ const first = args[0];
681
+ // Support both positional (`auth switch`) and flag (`auth --switch`) forms
682
+ if (first === "verify" || first === "switch" || first === "--verify" || first === "--switch") {
683
+ const subcommand = first.replace(/^--/, "");
684
+ const { agent, rest } = extractAgentFlag(args.slice(1));
685
+ let provider;
686
+ /* v8 ignore start -- provider flag parsing: branches tested via CLI parsing tests @preserve */
687
+ for (let i = 0; i < rest.length; i += 1) {
688
+ if (rest[i] === "--provider") {
689
+ const value = rest[i + 1];
690
+ if (!isAgentProvider(value))
691
+ throw new Error(`Usage\n${usage()}`);
692
+ provider = value;
693
+ i += 1;
694
+ continue;
695
+ }
696
+ }
697
+ /* v8 ignore stop */
698
+ /* v8 ignore next -- defensive: agent always provided in tests @preserve */
699
+ if (!agent)
700
+ throw new Error(`Usage\n${usage()}`);
701
+ if (subcommand === "switch") {
702
+ if (!provider)
703
+ throw new Error(`auth switch requires --provider.\n${usage()}`);
704
+ return { kind: "auth.switch", agent, provider };
705
+ }
706
+ return provider ? { kind: "auth.verify", agent, provider } : { kind: "auth.verify", agent };
707
+ }
708
+ const { agent, rest } = extractAgentFlag(args);
709
+ let provider;
710
+ for (let i = 0; i < rest.length; i += 1) {
711
+ if (rest[i] === "--provider") {
712
+ const value = rest[i + 1];
713
+ if (!isAgentProvider(value))
714
+ throw new Error(`Usage\n${usage()}`);
715
+ provider = value;
716
+ i += 1;
717
+ continue;
718
+ }
719
+ }
720
+ if (!agent)
721
+ throw new Error(`Usage\n${usage()}`);
722
+ return provider ? { kind: "auth.run", agent, provider } : { kind: "auth.run", agent };
723
+ }
724
+ function parseReminderCommand(args) {
725
+ const { agent, rest: cleaned } = extractAgentFlag(args);
726
+ const [sub, ...rest] = cleaned;
727
+ if (!sub)
728
+ throw new Error(`Usage\n${usage()}`);
729
+ if (sub === "create") {
730
+ const title = rest[0];
731
+ if (!title)
732
+ throw new Error(`Usage\n${usage()}`);
733
+ let body;
734
+ let scheduledAt;
735
+ let cadence;
736
+ let category;
737
+ let requester;
738
+ for (let i = 1; i < rest.length; i++) {
739
+ if (rest[i] === "--body" && rest[i + 1]) {
740
+ body = rest[i + 1];
741
+ i += 1;
742
+ }
743
+ else if (rest[i] === "--at" && rest[i + 1]) {
744
+ scheduledAt = rest[i + 1];
745
+ i += 1;
746
+ }
747
+ else if (rest[i] === "--cadence" && rest[i + 1]) {
748
+ cadence = rest[i + 1];
749
+ i += 1;
750
+ }
751
+ else if (rest[i] === "--category" && rest[i + 1]) {
752
+ category = rest[i + 1];
753
+ i += 1;
754
+ }
755
+ else if (rest[i] === "--requester" && rest[i + 1]) {
756
+ requester = rest[i + 1];
757
+ i += 1;
758
+ }
759
+ }
760
+ if (!body)
761
+ throw new Error(`Usage\n${usage()}`);
762
+ if (!scheduledAt && !cadence)
763
+ throw new Error(`Usage\n${usage()}`);
764
+ return {
765
+ kind: "reminder.create",
766
+ title,
767
+ body,
768
+ ...(scheduledAt ? { scheduledAt } : {}),
769
+ ...(cadence ? { cadence } : {}),
770
+ ...(category ? { category } : {}),
771
+ ...(requester ? { requester } : {}),
772
+ ...(agent ? { agent } : {}),
773
+ };
774
+ }
775
+ throw new Error(`Usage\n${usage()}`);
776
+ }
777
+ function parseSessionCommand(args) {
778
+ const { agent, rest: cleaned } = extractAgentFlag(args);
779
+ const [sub] = cleaned;
780
+ if (!sub)
781
+ throw new Error(`Usage\n${usage()}`);
782
+ if (sub === "list")
783
+ return { kind: "session.list", ...(agent ? { agent } : {}) };
784
+ throw new Error(`Usage\n${usage()}`);
785
+ }
786
+ function parseThoughtsCommand(args) {
787
+ const { agent, rest: cleaned } = extractAgentFlag(args);
788
+ let last;
789
+ let json = false;
790
+ let follow = false;
791
+ for (let i = 0; i < cleaned.length; i++) {
792
+ if (cleaned[i] === "--last" && i + 1 < cleaned.length) {
793
+ last = Number.parseInt(cleaned[i + 1], 10);
794
+ i++;
795
+ }
796
+ if (cleaned[i] === "--json")
797
+ json = true;
798
+ if (cleaned[i] === "--follow" || cleaned[i] === "-f")
799
+ follow = true;
800
+ }
801
+ return { kind: "thoughts", ...(agent ? { agent } : {}), ...(last ? { last } : {}), ...(json ? { json } : {}), ...(follow ? { follow } : {}) };
802
+ }
803
+ function parseFriendCommand(args) {
804
+ const { agent, rest: cleaned } = extractAgentFlag(args);
805
+ const [sub, ...rest] = cleaned;
806
+ if (!sub)
807
+ throw new Error(`Usage\n${usage()}`);
808
+ if (sub === "list")
809
+ return { kind: "friend.list", ...(agent ? { agent } : {}) };
810
+ if (sub === "show") {
811
+ const friendId = rest[0];
812
+ if (!friendId)
813
+ throw new Error(`Usage\n${usage()}`);
814
+ return { kind: "friend.show", friendId, ...(agent ? { agent } : {}) };
815
+ }
816
+ if (sub === "create") {
817
+ let name;
818
+ let trustLevel;
819
+ for (let i = 0; i < rest.length; i++) {
820
+ if (rest[i] === "--name" && rest[i + 1]) {
821
+ name = rest[i + 1];
822
+ i += 1;
823
+ }
824
+ else if (rest[i] === "--trust" && rest[i + 1]) {
825
+ trustLevel = rest[i + 1];
826
+ i += 1;
827
+ }
828
+ }
829
+ if (!name)
830
+ throw new Error(`Usage\n${usage()}`);
831
+ return {
832
+ kind: "friend.create",
833
+ name,
834
+ ...(trustLevel ? { trustLevel } : {}),
835
+ ...(agent ? { agent } : {}),
836
+ };
837
+ }
838
+ if (sub === "update") {
839
+ const friendId = rest[0];
840
+ if (!friendId)
841
+ throw new Error(`Usage: ouro friend update <id> --trust <level>`);
842
+ let trustLevel;
843
+ /* v8 ignore start -- flag parsing loop: tested via CLI parsing tests @preserve */
844
+ for (let i = 1; i < rest.length; i++) {
845
+ if (rest[i] === "--trust" && rest[i + 1]) {
846
+ trustLevel = rest[i + 1];
847
+ i += 1;
848
+ }
849
+ }
850
+ /* v8 ignore stop */
851
+ const VALID_TRUST_LEVELS = new Set(["stranger", "acquaintance", "friend", "family"]);
852
+ if (!trustLevel || !VALID_TRUST_LEVELS.has(trustLevel)) {
853
+ throw new Error(`Usage: ouro friend update <id> --trust <stranger|acquaintance|friend|family>`);
854
+ }
855
+ return {
856
+ kind: "friend.update",
857
+ friendId,
858
+ trustLevel: trustLevel,
859
+ ...(agent ? { agent } : {}),
860
+ };
861
+ }
862
+ if (sub === "link")
863
+ return parseLinkCommand(rest, "friend.link");
864
+ if (sub === "unlink")
865
+ return parseLinkCommand(rest, "friend.unlink");
866
+ throw new Error(`Usage\n${usage()}`);
867
+ }
868
+ function parseConfigCommand(args) {
869
+ const { agent, rest: cleaned } = extractAgentFlag(args);
870
+ const [sub, ...rest] = cleaned;
871
+ if (!sub)
872
+ throw new Error(`Usage\n${usage()}`);
873
+ if (sub === "model") {
874
+ if (!agent)
875
+ throw new Error("--agent is required for config model");
876
+ const modelName = rest[0];
877
+ if (!modelName)
878
+ throw new Error(`Usage: ouro config model --agent <name> <model-name>`);
879
+ return { kind: "config.model", agent, modelName };
880
+ }
881
+ if (sub === "models") {
882
+ if (!agent)
883
+ throw new Error("--agent is required for config models");
884
+ return { kind: "config.models", agent };
885
+ }
886
+ throw new Error(`Usage\n${usage()}`);
887
+ }
888
+ function parseMcpCommand(args) {
889
+ const [sub, ...rest] = args;
890
+ if (!sub)
891
+ throw new Error(`Usage\n${usage()}`);
892
+ if (sub === "list")
893
+ return { kind: "mcp.list" };
894
+ if (sub === "call") {
895
+ const server = rest[0];
896
+ const tool = rest[1];
897
+ if (!server || !tool)
898
+ throw new Error(`Usage\n${usage()}`);
899
+ const argsIdx = rest.indexOf("--args");
900
+ const mcpArgs = argsIdx !== -1 && rest[argsIdx + 1] ? rest[argsIdx + 1] : undefined;
901
+ return { kind: "mcp.call", server, tool, ...(mcpArgs ? { args: mcpArgs } : {}) };
902
+ }
903
+ throw new Error(`Usage\n${usage()}`);
904
+ }
239
905
  function parseOuroCommand(args) {
240
906
  const [head, second] = args;
241
907
  if (!head)
242
908
  return { kind: "daemon.up" };
909
+ if (head === "--agent" && second) {
910
+ return parseOuroCommand(args.slice(2));
911
+ }
243
912
  if (head === "up")
244
913
  return { kind: "daemon.up" };
245
- if (head === "stop")
914
+ if (head === "rollback")
915
+ return { kind: "rollback", ...(second ? { version: second } : {}) };
916
+ if (head === "versions")
917
+ return { kind: "versions" };
918
+ if (head === "stop" || head === "down")
246
919
  return { kind: "daemon.stop" };
247
920
  if (head === "status")
248
921
  return { kind: "daemon.status" };
@@ -250,6 +923,36 @@ function parseOuroCommand(args) {
250
923
  return { kind: "daemon.logs" };
251
924
  if (head === "hatch")
252
925
  return parseHatchCommand(args.slice(1));
926
+ if (head === "auth")
927
+ return parseAuthCommand(args.slice(1));
928
+ if (head === "task")
929
+ return parseTaskCommand(args.slice(1));
930
+ if (head === "reminder")
931
+ return parseReminderCommand(args.slice(1));
932
+ if (head === "friend")
933
+ return parseFriendCommand(args.slice(1));
934
+ if (head === "config")
935
+ return parseConfigCommand(args.slice(1));
936
+ if (head === "mcp")
937
+ return parseMcpCommand(args.slice(1));
938
+ if (head === "whoami") {
939
+ const { agent } = extractAgentFlag(args.slice(1));
940
+ return { kind: "whoami", ...(agent ? { agent } : {}) };
941
+ }
942
+ if (head === "session")
943
+ return parseSessionCommand(args.slice(1));
944
+ if (head === "changelog") {
945
+ const sliced = args.slice(1);
946
+ const { agent, rest: remaining } = extractAgentFlag(sliced);
947
+ let from;
948
+ const fromIdx = remaining.indexOf("--from");
949
+ if (fromIdx !== -1 && remaining[fromIdx + 1]) {
950
+ from = remaining[fromIdx + 1];
951
+ }
952
+ return { kind: "changelog", ...(from ? { from } : {}), ...(agent ? { agent } : {}) };
953
+ }
954
+ if (head === "thoughts")
955
+ return parseThoughtsCommand(args.slice(1));
253
956
  if (head === "chat") {
254
957
  if (!second)
255
958
  throw new Error(`Usage\n${usage()}`);
@@ -263,38 +966,6 @@ function parseOuroCommand(args) {
263
966
  return parseLinkCommand(args.slice(1));
264
967
  throw new Error(`Unknown command '${args.join(" ")}'.\n${usage()}`);
265
968
  }
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
969
  function defaultStartDaemonProcess(socketPath) {
299
970
  const entry = path.join((0, identity_1.getRepoRoot)(), "dist", "heart", "daemon", "daemon-entry.js");
300
971
  const child = (0, child_process_1.spawn)("node", [entry, "--socket", socketPath], {
@@ -308,45 +979,32 @@ function defaultWriteStdout(text) {
308
979
  // eslint-disable-next-line no-console -- terminal UX: CLI command output
309
980
  console.log(text);
310
981
  }
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
- });
982
+ /**
983
+ * Read the runtimeVersion from the first .ouro bundle's bundle-meta.json.
984
+ * Returns undefined if none found or unreadable.
985
+ */
986
+ function readFirstBundleMetaVersion(bundlesRoot) {
987
+ try {
988
+ if (!fs.existsSync(bundlesRoot))
989
+ return undefined;
990
+ const entries = fs.readdirSync(bundlesRoot, { withFileTypes: true });
991
+ for (const entry of entries) {
992
+ /* v8 ignore next -- skip non-.ouro dirs: tested via version-detect tests @preserve */
993
+ if (!entry.isDirectory() || !entry.name.endsWith(".ouro"))
994
+ continue;
995
+ const metaPath = path.join(bundlesRoot, entry.name, "bundle-meta.json");
996
+ if (!fs.existsSync(metaPath))
997
+ continue;
998
+ const raw = fs.readFileSync(metaPath, "utf-8");
999
+ const meta = JSON.parse(raw);
1000
+ if (meta.runtimeVersion)
1001
+ return meta.runtimeVersion;
327
1002
  }
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
- });
1003
+ }
1004
+ catch {
1005
+ // Best effort — return undefined on any error
1006
+ }
1007
+ return undefined;
350
1008
  }
351
1009
  function defaultCleanupStaleSocket(socketPath) {
352
1010
  if (fs.existsSync(socketPath)) {
@@ -382,9 +1040,38 @@ function defaultFallbackPendingMessage(command) {
382
1040
  });
383
1041
  return pendingPath;
384
1042
  }
385
- async function defaultInstallSubagents() {
386
- return (0, subagent_installer_1.installSubagentsForAvailableCli)({
387
- repoRoot: (0, identity_1.getRepoRoot)(),
1043
+ function defaultEnsureDaemonBootPersistence(socketPath) {
1044
+ if (process.platform !== "darwin") {
1045
+ return;
1046
+ }
1047
+ const homeDir = os.homedir();
1048
+ const launchdDeps = {
1049
+ exec: (cmd) => { (0, child_process_1.execSync)(cmd, { stdio: "ignore" }); },
1050
+ writeFile: (filePath, content) => fs.writeFileSync(filePath, content, "utf-8"),
1051
+ removeFile: (filePath) => fs.rmSync(filePath, { force: true }),
1052
+ existsFile: (filePath) => fs.existsSync(filePath),
1053
+ mkdirp: (dir) => fs.mkdirSync(dir, { recursive: true }),
1054
+ homeDir,
1055
+ userUid: process.getuid?.() ?? 0,
1056
+ };
1057
+ const entryPath = path.join((0, identity_1.getRepoRoot)(), "dist", "heart", "daemon", "daemon-entry.js");
1058
+ /* 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 */
1059
+ if (!fs.existsSync(entryPath)) {
1060
+ (0, runtime_1.emitNervesEvent)({
1061
+ level: "warn",
1062
+ component: "daemon",
1063
+ event: "daemon.entry_path_missing",
1064
+ message: "entryPath does not exist on disk — plist may point to a stale location. Run 'ouro daemon install' from the correct location.",
1065
+ meta: { entryPath },
1066
+ });
1067
+ }
1068
+ const logDir = (0, identity_1.getAgentDaemonLogsDir)();
1069
+ (0, launchd_1.installLaunchAgent)(launchdDeps, {
1070
+ nodePath: process.execPath,
1071
+ entryPath,
1072
+ socketPath,
1073
+ logDir,
1074
+ envPath: process.env.PATH,
388
1075
  });
389
1076
  }
390
1077
  async function defaultPromptInput(question) {
@@ -402,146 +1089,331 @@ async function defaultPromptInput(question) {
402
1089
  }
403
1090
  }
404
1091
  function defaultListDiscoveredAgents() {
405
- const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
1092
+ return (0, agent_discovery_1.listEnabledBundleAgents)({
1093
+ bundlesRoot: (0, identity_1.getAgentBundlesRoot)(),
1094
+ readdirSync: fs.readdirSync,
1095
+ readFileSync: fs.readFileSync,
1096
+ });
1097
+ }
1098
+ function discoverExistingCredentials(secretsRoot) {
1099
+ const found = [];
406
1100
  let entries;
407
1101
  try {
408
- entries = fs.readdirSync(bundlesRoot, { withFileTypes: true });
1102
+ entries = fs.readdirSync(secretsRoot, { withFileTypes: true });
409
1103
  }
410
1104
  catch {
411
- return [];
1105
+ return found;
412
1106
  }
413
- const discovered = [];
414
1107
  for (const entry of entries) {
415
- if (!entry.isDirectory() || !entry.name.endsWith(".ouro"))
1108
+ if (!entry.isDirectory())
416
1109
  continue;
417
- const agentName = entry.name.slice(0, -5);
418
- const configPath = path.join(bundlesRoot, entry.name, "agent.json");
419
- let enabled = true;
1110
+ const secretsPath = path.join(secretsRoot, entry.name, "secrets.json");
1111
+ let raw;
420
1112
  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
- }
1113
+ raw = fs.readFileSync(secretsPath, "utf-8");
426
1114
  }
427
1115
  catch {
428
1116
  continue;
429
1117
  }
430
- if (enabled) {
431
- discovered.push(agentName);
1118
+ let parsed;
1119
+ try {
1120
+ parsed = JSON.parse(raw);
1121
+ }
1122
+ catch {
1123
+ continue;
1124
+ }
1125
+ if (!parsed.providers)
1126
+ continue;
1127
+ for (const [provName, provConfig] of Object.entries(parsed.providers)) {
1128
+ if (provName === "anthropic" && provConfig.setupToken) {
1129
+ found.push({ agentName: entry.name, provider: "anthropic", credentials: { setupToken: provConfig.setupToken }, providerConfig: { ...provConfig } });
1130
+ }
1131
+ else if (provName === "openai-codex" && provConfig.oauthAccessToken) {
1132
+ found.push({ agentName: entry.name, provider: "openai-codex", credentials: { oauthAccessToken: provConfig.oauthAccessToken }, providerConfig: { ...provConfig } });
1133
+ }
1134
+ else if (provName === "minimax" && provConfig.apiKey) {
1135
+ found.push({ agentName: entry.name, provider: "minimax", credentials: { apiKey: provConfig.apiKey }, providerConfig: { ...provConfig } });
1136
+ }
1137
+ else if (provName === "azure" && provConfig.apiKey && provConfig.endpoint && provConfig.deployment) {
1138
+ found.push({ agentName: entry.name, provider: "azure", credentials: { apiKey: provConfig.apiKey, endpoint: provConfig.endpoint, deployment: provConfig.deployment }, providerConfig: { ...provConfig } });
1139
+ }
432
1140
  }
433
1141
  }
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,
1142
+ // Deduplicate by provider+credential value (keep first seen)
1143
+ const seen = new Set();
1144
+ return found.filter((cred) => {
1145
+ const key = `${cred.provider}:${JSON.stringify(cred.credentials)}`;
1146
+ if (seen.has(key))
1147
+ return false;
1148
+ seen.add(key);
1149
+ return true;
458
1150
  });
459
- return `linked ${command.provider}:${command.externalId} to ${command.friendId}`;
460
1151
  }
461
- /* v8 ignore next 49 -- integration: interactive terminal specialist session @preserve */
1152
+ /* v8 ignore start -- integration: interactive terminal specialist session @preserve */
462
1153
  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);
1154
+ const { runCliSession } = await Promise.resolve().then(() => __importStar(require("../../senses/cli")));
1155
+ const { patchRuntimeConfig } = await Promise.resolve().then(() => __importStar(require("../config")));
1156
+ const { setAgentName, setAgentConfigOverride } = await Promise.resolve().then(() => __importStar(require("../identity")));
1157
+ const readlinePromises = await Promise.resolve().then(() => __importStar(require("readline/promises")));
1158
+ const crypto = await Promise.resolve().then(() => __importStar(require("crypto")));
1159
+ // Phase 1: cold CLI — collect provider/credentials with a simple readline
1160
+ const coldRl = readlinePromises.createInterface({ input: process.stdin, output: process.stdout });
1161
+ const coldPrompt = async (q) => {
1162
+ const answer = await coldRl.question(q);
467
1163
  return answer.trim();
468
1164
  };
1165
+ let providerRaw;
1166
+ let credentials = {};
1167
+ let providerConfig = {};
1168
+ const tempDir = path.join(os.tmpdir(), `ouro-hatch-${crypto.randomUUID()}`);
469
1169
  try {
470
- process.stdout.write("\nwelcome to ouro. let's get you set up.\n");
471
- process.stdout.write("i need an API key to power our conversation.\n\n");
472
- const providerRaw = await prompt("provider (anthropic/azure/minimax/openai-codex): ");
473
- if (!isAgentProvider(providerRaw)) {
474
- process.stdout.write("unknown provider. run `ouro hatch` to try again.\n");
475
- return null;
1170
+ const secretsRoot = path.join(os.homedir(), ".agentsecrets");
1171
+ const discovered = discoverExistingCredentials(secretsRoot);
1172
+ const existingBundleCount = (0, specialist_orchestrator_1.listExistingBundles)((0, identity_1.getAgentBundlesRoot)()).length;
1173
+ const hatchVerb = existingBundleCount > 0 ? "let's hatch a new agent." : "let's hatch your first agent.";
1174
+ // Default models per provider (used when entering new credentials)
1175
+ const defaultModels = {
1176
+ anthropic: "claude-opus-4-6",
1177
+ minimax: "MiniMax-Text-01",
1178
+ "openai-codex": "gpt-5.4",
1179
+ "github-copilot": "claude-sonnet-4.6",
1180
+ azure: "",
1181
+ };
1182
+ if (discovered.length > 0) {
1183
+ process.stdout.write(`\n\ud83d\udc0d welcome to ouroboros! ${hatchVerb}\n`);
1184
+ process.stdout.write("i found existing API credentials:\n\n");
1185
+ const unique = [...new Map(discovered.map((d) => [`${d.provider}`, d])).values()];
1186
+ for (let i = 0; i < unique.length; i++) {
1187
+ const model = unique[i].providerConfig.model || unique[i].providerConfig.deployment || "";
1188
+ const modelLabel = model ? `, ${model}` : "";
1189
+ process.stdout.write(` ${i + 1}. ${unique[i].provider}${modelLabel} (from ${unique[i].agentName})\n`);
1190
+ }
1191
+ process.stdout.write("\n");
1192
+ const choice = await coldPrompt("use one of these? enter number, or 'new' for a different key: ");
1193
+ const idx = parseInt(choice, 10) - 1;
1194
+ if (idx >= 0 && idx < unique.length) {
1195
+ providerRaw = unique[idx].provider;
1196
+ credentials = unique[idx].credentials;
1197
+ providerConfig = unique[idx].providerConfig;
1198
+ }
1199
+ else {
1200
+ const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex/github-copilot): ");
1201
+ if (!isAgentProvider(pRaw)) {
1202
+ process.stdout.write("unknown provider. run `ouro hatch` to try again.\n");
1203
+ coldRl.close();
1204
+ return null;
1205
+ }
1206
+ providerRaw = pRaw;
1207
+ providerConfig = { model: defaultModels[providerRaw] };
1208
+ if (providerRaw === "anthropic")
1209
+ credentials.setupToken = await coldPrompt("API key: ");
1210
+ if (providerRaw === "openai-codex")
1211
+ credentials.oauthAccessToken = await coldPrompt("OAuth token: ");
1212
+ if (providerRaw === "minimax")
1213
+ credentials.apiKey = await coldPrompt("API key: ");
1214
+ if (providerRaw === "azure") {
1215
+ credentials.apiKey = await coldPrompt("API key: ");
1216
+ credentials.endpoint = await coldPrompt("endpoint: ");
1217
+ credentials.deployment = await coldPrompt("deployment: ");
1218
+ }
1219
+ }
476
1220
  }
477
- const credentials = {};
478
- if (providerRaw === "anthropic")
479
- credentials.setupToken = await prompt("API key: ");
480
- if (providerRaw === "openai-codex")
481
- credentials.oauthAccessToken = await prompt("OAuth token: ");
482
- if (providerRaw === "minimax")
483
- credentials.apiKey = await prompt("API key: ");
484
- if (providerRaw === "azure") {
485
- credentials.apiKey = await prompt("API key: ");
486
- credentials.endpoint = await prompt("endpoint: ");
487
- credentials.deployment = await prompt("deployment: ");
1221
+ else {
1222
+ process.stdout.write(`\n\ud83d\udc0d welcome to ouroboros! ${hatchVerb}\n`);
1223
+ process.stdout.write("i need an API key to power our conversation.\n\n");
1224
+ const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex/github-copilot): ");
1225
+ if (!isAgentProvider(pRaw)) {
1226
+ process.stdout.write("unknown provider. run `ouro hatch` to try again.\n");
1227
+ coldRl.close();
1228
+ return null;
1229
+ }
1230
+ providerRaw = pRaw;
1231
+ providerConfig = { model: defaultModels[providerRaw] };
1232
+ if (providerRaw === "anthropic")
1233
+ credentials.setupToken = await coldPrompt("API key: ");
1234
+ if (providerRaw === "openai-codex")
1235
+ credentials.oauthAccessToken = await coldPrompt("OAuth token: ");
1236
+ if (providerRaw === "minimax")
1237
+ credentials.apiKey = await coldPrompt("API key: ");
1238
+ if (providerRaw === "azure") {
1239
+ credentials.apiKey = await coldPrompt("API key: ");
1240
+ credentials.endpoint = await coldPrompt("endpoint: ");
1241
+ credentials.deployment = await coldPrompt("deployment: ");
1242
+ }
488
1243
  }
489
- rl.close();
1244
+ coldRl.close();
490
1245
  process.stdout.write("\n");
491
- // Locate the bundled AdoptionSpecialist.ouro shipped with the npm package
1246
+ // Phase 2: configure runtime for adoption specialist
492
1247
  const bundleSourceDir = path.resolve(__dirname, "..", "..", "..", "AdoptionSpecialist.ouro");
493
1248
  const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
494
- const secretsRoot = path.join(os.homedir(), ".agentsecrets");
495
- return await (0, specialist_orchestrator_1.runAdoptionSpecialist)({
496
- bundleSourceDir,
497
- bundlesRoot,
498
- secretsRoot,
1249
+ const secretsRoot2 = path.join(os.homedir(), ".agentsecrets");
1250
+ // Suppress non-critical log noise during adoption (no secrets.json, etc.)
1251
+ const { setRuntimeLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves/runtime")));
1252
+ const { createLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves")));
1253
+ setRuntimeLogger(createLogger({ level: "error" }));
1254
+ // Configure runtime: set agent identity + config override so runAgent
1255
+ // doesn't try to read from ~/AgentBundles/AdoptionSpecialist.ouro/
1256
+ setAgentName("AdoptionSpecialist");
1257
+ // Build specialist system prompt
1258
+ const soulText = (0, specialist_orchestrator_1.loadSoulText)(bundleSourceDir);
1259
+ const identitiesDir = path.join(bundleSourceDir, "psyche", "identities");
1260
+ const identity = (0, specialist_orchestrator_1.pickRandomIdentity)(identitiesDir);
1261
+ // Load identity-specific spinner phrases (falls back to DEFAULT_AGENT_PHRASES)
1262
+ const { loadIdentityPhrases } = await Promise.resolve().then(() => __importStar(require("./specialist-orchestrator")));
1263
+ const phrases = loadIdentityPhrases(bundleSourceDir, identity.fileName);
1264
+ setAgentConfigOverride({
1265
+ version: 1,
1266
+ enabled: true,
499
1267
  provider: providerRaw,
500
- credentials,
501
- humanName: os.userInfo().username,
502
- createReadline: () => {
503
- const rl2 = readline.createInterface({ input: process.stdin, output: process.stdout });
504
- return { question: (q) => rl2.question(q), close: () => rl2.close() };
505
- },
506
- callbacks: {
507
- onModelStart: () => { },
508
- onModelStreamStart: () => { },
509
- onTextChunk: (text) => process.stdout.write(text),
510
- onReasoningChunk: () => { },
511
- onToolStart: () => { },
512
- onToolEnd: () => { },
513
- onError: (err) => process.stderr.write(`error: ${err.message}\n`),
1268
+ phrases,
1269
+ });
1270
+ patchRuntimeConfig({
1271
+ providers: {
1272
+ [providerRaw]: { ...providerConfig, ...credentials },
514
1273
  },
515
1274
  });
1275
+ const existingBundles = (0, specialist_orchestrator_1.listExistingBundles)(bundlesRoot);
1276
+ const systemPrompt = (0, specialist_prompt_1.buildSpecialistSystemPrompt)(soulText, identity.content, existingBundles, {
1277
+ tempDir,
1278
+ provider: providerRaw,
1279
+ });
1280
+ // Build specialist tools
1281
+ const specialistTools = (0, specialist_tools_1.getSpecialistTools)();
1282
+ const specialistExecTool = (0, specialist_tools_1.createSpecialistExecTool)({
1283
+ tempDir,
1284
+ credentials,
1285
+ provider: providerRaw,
1286
+ bundlesRoot,
1287
+ secretsRoot: secretsRoot2,
1288
+ animationWriter: (text) => process.stdout.write(text),
1289
+ });
1290
+ // Run the adoption specialist session via runCliSession
1291
+ const result = await runCliSession({
1292
+ agentName: "AdoptionSpecialist",
1293
+ tools: specialistTools,
1294
+ execTool: specialistExecTool,
1295
+ exitOnToolCall: "complete_adoption",
1296
+ autoFirstTurn: true,
1297
+ banner: false,
1298
+ disableCommands: true,
1299
+ skipSystemPromptRefresh: true,
1300
+ messages: [
1301
+ { role: "system", content: systemPrompt },
1302
+ { role: "user", content: "hi" },
1303
+ ],
1304
+ });
1305
+ if (result.exitReason === "tool_exit" && result.toolResult) {
1306
+ const parsed = typeof result.toolResult === "string" ? JSON.parse(result.toolResult) : result.toolResult;
1307
+ if (parsed.success && parsed.agentName) {
1308
+ return parsed.agentName;
1309
+ }
1310
+ }
1311
+ return null;
516
1312
  }
517
- catch {
518
- rl.close();
1313
+ catch (err) {
1314
+ process.stderr.write(`\nouro adoption error: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
1315
+ coldRl.close();
519
1316
  return null;
520
1317
  }
1318
+ finally {
1319
+ // Clear specialist config/identity so the hatched agent gets its own
1320
+ setAgentConfigOverride(null);
1321
+ const { resetProviderRuntime } = await Promise.resolve().then(() => __importStar(require("../core")));
1322
+ resetProviderRuntime();
1323
+ const { resetConfigCache } = await Promise.resolve().then(() => __importStar(require("../config")));
1324
+ resetConfigCache();
1325
+ // Restore default logging
1326
+ const { setRuntimeLogger: restoreLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves/runtime")));
1327
+ restoreLogger(null);
1328
+ // Clean up temp dir if it still exists
1329
+ try {
1330
+ if (fs.existsSync(tempDir)) {
1331
+ fs.rmSync(tempDir, { recursive: true, force: true });
1332
+ }
1333
+ }
1334
+ catch {
1335
+ // Best effort cleanup
1336
+ }
1337
+ }
521
1338
  }
522
- function createDefaultOuroCliDeps(socketPath = "/tmp/ouroboros-daemon.sock") {
1339
+ /* v8 ignore stop */
1340
+ function createDefaultOuroCliDeps(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
523
1341
  return {
524
1342
  socketPath,
525
- sendCommand: defaultSendCommand,
1343
+ sendCommand: socket_client_1.sendDaemonCommand,
526
1344
  startDaemonProcess: defaultStartDaemonProcess,
527
1345
  writeStdout: defaultWriteStdout,
528
- checkSocketAlive: defaultCheckSocketAlive,
1346
+ checkSocketAlive: socket_client_1.checkDaemonSocketAlive,
529
1347
  cleanupStaleSocket: defaultCleanupStaleSocket,
530
1348
  fallbackPendingMessage: defaultFallbackPendingMessage,
531
- installSubagents: defaultInstallSubagents,
532
- linkFriendIdentity: defaultLinkFriendIdentity,
533
1349
  listDiscoveredAgents: defaultListDiscoveredAgents,
534
1350
  runHatchFlow: hatch_flow_1.runHatchFlow,
535
1351
  promptInput: defaultPromptInput,
536
1352
  runAdoptionSpecialist: defaultRunAdoptionSpecialist,
1353
+ runAuthFlow: auth_flow_1.runRuntimeAuthFlow,
537
1354
  registerOuroBundleType: ouro_uti_1.registerOuroBundleUti,
1355
+ installOuroCommand: ouro_path_installer_1.installOuroCommand,
1356
+ /* v8 ignore start -- self-healing: ensures versioned layout has current version installed @preserve */
1357
+ ensureCurrentVersionInstalled: () => {
1358
+ const currentVersion = (0, ouro_version_manager_1.getCurrentVersion)({});
1359
+ if (currentVersion)
1360
+ return; // Already installed and linked
1361
+ const version = (0, bundle_manifest_1.getPackageVersion)();
1362
+ (0, ouro_version_manager_1.ensureLayout)({});
1363
+ const cliHome = (0, ouro_version_manager_1.getOuroCliHome)();
1364
+ const versionEntry = path.join(cliHome, "versions", version, "node_modules", "@ouro.bot", "cli", "dist", "heart", "daemon", "ouro-entry.js");
1365
+ if (!fs.existsSync(versionEntry)) {
1366
+ (0, ouro_version_manager_1.installVersion)(version, {});
1367
+ }
1368
+ (0, ouro_version_manager_1.activateVersion)(version, {});
1369
+ },
1370
+ /* v8 ignore stop */
1371
+ syncGlobalOuroBotWrapper: ouro_bot_global_installer_1.syncGlobalOuroBotWrapper,
1372
+ ensureSkillManagement: skill_management_installer_1.ensureSkillManagement,
1373
+ ensureDaemonBootPersistence: defaultEnsureDaemonBootPersistence,
538
1374
  /* v8 ignore next 3 -- integration: launches interactive CLI session @preserve */
539
1375
  startChat: async (agentName) => {
540
1376
  const { main } = await Promise.resolve().then(() => __importStar(require("../../senses/cli")));
541
1377
  await main(agentName);
542
1378
  },
1379
+ scanSessions: async () => {
1380
+ const agentName = (0, identity_1.getAgentName)();
1381
+ const agentRoot = (0, identity_1.getAgentRoot)(agentName);
1382
+ return (0, session_activity_1.listSessionActivity)({
1383
+ sessionsDir: path.join(agentRoot, "state", "sessions"),
1384
+ friendsDir: path.join(agentRoot, "friends"),
1385
+ agentName,
1386
+ }).map((entry) => ({
1387
+ friendId: entry.friendId,
1388
+ friendName: entry.friendName,
1389
+ channel: entry.channel,
1390
+ lastActivity: entry.lastActivityAt,
1391
+ }));
1392
+ },
543
1393
  };
544
1394
  }
1395
+ function formatMcpResponse(command, response) {
1396
+ if (command.kind === "mcp.list") {
1397
+ const allTools = response.data;
1398
+ if (!allTools || allTools.length === 0) {
1399
+ return response.message ?? "no tools available from connected MCP servers";
1400
+ }
1401
+ const lines = [];
1402
+ for (const entry of allTools) {
1403
+ lines.push(`[${entry.server}]`);
1404
+ for (const tool of entry.tools) {
1405
+ lines.push(` ${tool.name}: ${tool.description}`);
1406
+ }
1407
+ }
1408
+ return lines.join("\n");
1409
+ }
1410
+ // mcp.call
1411
+ const result = response.data;
1412
+ if (!result) {
1413
+ return response.message ?? "no result";
1414
+ }
1415
+ return result.content.map((c) => c.text).join("\n");
1416
+ }
545
1417
  function toDaemonCommand(command) {
546
1418
  return command;
547
1419
  }
@@ -549,28 +1421,17 @@ async function resolveHatchInput(command, deps) {
549
1421
  const prompt = deps.promptInput;
550
1422
  const agentName = command.agentName ?? (prompt ? await prompt("Hatchling name: ") : "");
551
1423
  const humanName = command.humanName ?? (prompt ? await prompt("Your name: ") : os.userInfo().username);
552
- const providerRaw = command.provider ?? (prompt ? await prompt("Provider (azure|anthropic|minimax|openai-codex): ") : "");
1424
+ const providerRaw = command.provider ?? (prompt ? await prompt("Provider (azure|anthropic|minimax|openai-codex|github-copilot): ") : "");
553
1425
  if (!agentName || !humanName || !isAgentProvider(providerRaw)) {
554
1426
  throw new Error(`Usage\n${usage()}`);
555
1427
  }
556
- const credentials = { ...(command.credentials ?? {}) };
557
- if (providerRaw === "anthropic" && !credentials.setupToken && prompt) {
558
- credentials.setupToken = await prompt("Anthropic setup-token: ");
559
- }
560
- if (providerRaw === "openai-codex" && !credentials.oauthAccessToken && prompt) {
561
- credentials.oauthAccessToken = await prompt("OpenAI Codex OAuth token: ");
562
- }
563
- if (providerRaw === "minimax" && !credentials.apiKey && prompt) {
564
- credentials.apiKey = await prompt("MiniMax API key: ");
565
- }
566
- if (providerRaw === "azure") {
567
- if (!credentials.apiKey && prompt)
568
- credentials.apiKey = await prompt("Azure API key: ");
569
- if (!credentials.endpoint && prompt)
570
- credentials.endpoint = await prompt("Azure endpoint: ");
571
- if (!credentials.deployment && prompt)
572
- credentials.deployment = await prompt("Azure deployment: ");
573
- }
1428
+ const credentials = await (0, auth_flow_1.resolveHatchCredentials)({
1429
+ agentName,
1430
+ provider: providerRaw,
1431
+ credentials: command.credentials,
1432
+ promptInput: prompt,
1433
+ runAuthFlow: deps.runAuthFlow,
1434
+ });
574
1435
  return {
575
1436
  agentName,
576
1437
  humanName,
@@ -596,12 +1457,274 @@ async function registerOuroBundleTypeNonBlocking(deps) {
596
1457
  });
597
1458
  }
598
1459
  }
1460
+ async function performSystemSetup(deps) {
1461
+ // Install ouro command to PATH (non-blocking)
1462
+ if (deps.installOuroCommand) {
1463
+ try {
1464
+ const installResult = deps.installOuroCommand();
1465
+ /* v8 ignore next -- migration hint: only fires once during old→new layout migration @preserve */
1466
+ if (installResult.migratedFromOldPath) {
1467
+ deps.writeStdout("migrated ouro to ~/.ouro-cli/ — open a new terminal or run: source ~/.zshrc");
1468
+ }
1469
+ }
1470
+ catch (error) {
1471
+ (0, runtime_1.emitNervesEvent)({
1472
+ level: "warn",
1473
+ component: "daemon",
1474
+ event: "daemon.system_setup_ouro_cmd_error",
1475
+ message: "failed to install ouro command to PATH",
1476
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
1477
+ });
1478
+ }
1479
+ }
1480
+ // Self-healing: ensure current version is installed in ~/.ouro-cli/ layout.
1481
+ // Handles the case where the wrapper exists but CurrentVersion is missing
1482
+ // (e.g., first run after migration from old npx wrapper).
1483
+ if (deps.ensureCurrentVersionInstalled) {
1484
+ try {
1485
+ deps.ensureCurrentVersionInstalled();
1486
+ }
1487
+ catch (error) {
1488
+ (0, runtime_1.emitNervesEvent)({
1489
+ level: "warn",
1490
+ component: "daemon",
1491
+ event: "daemon.system_setup_version_install_error",
1492
+ message: "failed to ensure current version installed",
1493
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive @preserve */ String(error) },
1494
+ });
1495
+ }
1496
+ }
1497
+ if (deps.syncGlobalOuroBotWrapper) {
1498
+ try {
1499
+ await Promise.resolve(deps.syncGlobalOuroBotWrapper());
1500
+ }
1501
+ catch (error) {
1502
+ (0, runtime_1.emitNervesEvent)({
1503
+ level: "warn",
1504
+ component: "daemon",
1505
+ event: "daemon.system_setup_ouro_bot_wrapper_error",
1506
+ message: "failed to sync global ouro.bot wrapper",
1507
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
1508
+ });
1509
+ }
1510
+ }
1511
+ // Ensure skill-management skill is available
1512
+ if (deps.ensureSkillManagement) {
1513
+ try {
1514
+ await deps.ensureSkillManagement();
1515
+ /* v8 ignore start -- defensive: ensureSkillManagement handles its own errors internally @preserve */
1516
+ }
1517
+ catch (error) {
1518
+ (0, runtime_1.emitNervesEvent)({
1519
+ level: "warn",
1520
+ component: "daemon",
1521
+ event: "daemon.system_setup_skill_management_error",
1522
+ message: "failed to ensure skill-management skill",
1523
+ meta: { error: error instanceof Error ? error.message : String(error) },
1524
+ });
1525
+ }
1526
+ /* v8 ignore stop */
1527
+ }
1528
+ // Register .ouro bundle type (UTI on macOS)
1529
+ await registerOuroBundleTypeNonBlocking(deps);
1530
+ }
1531
+ function executeTaskCommand(command, taskMod) {
1532
+ if (command.kind === "task.board") {
1533
+ if (command.status) {
1534
+ const lines = taskMod.boardStatus(command.status);
1535
+ return lines.length > 0 ? lines.join("\n") : "no tasks in that status";
1536
+ }
1537
+ const board = taskMod.getBoard();
1538
+ return board.full || board.compact || "no tasks found";
1539
+ }
1540
+ if (command.kind === "task.create") {
1541
+ try {
1542
+ const created = taskMod.createTask({
1543
+ title: command.title,
1544
+ type: command.type ?? "one-shot",
1545
+ category: "general",
1546
+ body: "",
1547
+ });
1548
+ return `created: ${created}`;
1549
+ }
1550
+ catch (error) {
1551
+ return `error: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
1552
+ }
1553
+ }
1554
+ if (command.kind === "task.update") {
1555
+ const result = taskMod.updateStatus(command.id, command.status);
1556
+ if (!result.ok) {
1557
+ return `error: ${result.reason ?? "status update failed"}`;
1558
+ }
1559
+ const archivedSuffix = result.archived && result.archived.length > 0
1560
+ ? ` | archived: ${result.archived.join(", ")}`
1561
+ : "";
1562
+ return `updated: ${command.id} -> ${result.to}${archivedSuffix}`;
1563
+ }
1564
+ if (command.kind === "task.show") {
1565
+ const task = taskMod.getTask(command.id);
1566
+ if (!task)
1567
+ return `task not found: ${command.id}`;
1568
+ return [
1569
+ `title: ${task.title}`,
1570
+ `type: ${task.type}`,
1571
+ `status: ${task.status}`,
1572
+ `category: ${task.category}`,
1573
+ `created: ${task.created}`,
1574
+ `updated: ${task.updated}`,
1575
+ `path: ${task.path}`,
1576
+ task.body ? `\n${task.body}` : "",
1577
+ ].filter(Boolean).join("\n");
1578
+ }
1579
+ if (command.kind === "task.actionable") {
1580
+ const lines = taskMod.boardAction();
1581
+ return lines.length > 0 ? lines.join("\n") : "no action required";
1582
+ }
1583
+ if (command.kind === "task.deps") {
1584
+ const lines = taskMod.boardDeps();
1585
+ return lines.length > 0 ? lines.join("\n") : "no unresolved dependencies";
1586
+ }
1587
+ // command.kind === "task.sessions"
1588
+ const lines = taskMod.boardSessions();
1589
+ return lines.length > 0 ? lines.join("\n") : "no active sessions";
1590
+ }
1591
+ const TRUST_RANK = { family: 4, friend: 3, acquaintance: 2, stranger: 1 };
1592
+ /* v8 ignore start -- defensive: ?? fallbacks are unreachable when inputs are valid TrustLevel values @preserve */
1593
+ function higherTrust(a, b) {
1594
+ const rankA = TRUST_RANK[a ?? "stranger"] ?? 1;
1595
+ const rankB = TRUST_RANK[b ?? "stranger"] ?? 1;
1596
+ return rankA >= rankB ? (a ?? "stranger") : (b ?? "stranger");
1597
+ }
1598
+ /* v8 ignore stop */
1599
+ async function executeFriendCommand(command, store) {
1600
+ if (command.kind === "friend.list") {
1601
+ const listAll = store.listAll;
1602
+ if (!listAll)
1603
+ return "friend store does not support listing";
1604
+ const friends = await listAll.call(store);
1605
+ if (friends.length === 0)
1606
+ return "no friends found";
1607
+ const lines = friends.map((f) => {
1608
+ const trust = f.trustLevel ?? "unknown";
1609
+ return `${f.id} ${f.name} ${trust}`;
1610
+ });
1611
+ return lines.join("\n");
1612
+ }
1613
+ if (command.kind === "friend.show") {
1614
+ const record = await store.get(command.friendId);
1615
+ if (!record)
1616
+ return `friend not found: ${command.friendId}`;
1617
+ return JSON.stringify(record, null, 2);
1618
+ }
1619
+ if (command.kind === "friend.create") {
1620
+ const now = new Date().toISOString();
1621
+ const id = (0, crypto_1.randomUUID)();
1622
+ const trustLevel = (command.trustLevel ?? "acquaintance");
1623
+ await store.put(id, {
1624
+ id,
1625
+ name: command.name,
1626
+ trustLevel,
1627
+ externalIds: [],
1628
+ tenantMemberships: [],
1629
+ toolPreferences: {},
1630
+ notes: {},
1631
+ totalTokens: 0,
1632
+ createdAt: now,
1633
+ updatedAt: now,
1634
+ schemaVersion: 1,
1635
+ });
1636
+ return `created: ${id} (${command.name}, ${trustLevel})`;
1637
+ }
1638
+ if (command.kind === "friend.update") {
1639
+ const current = await store.get(command.friendId);
1640
+ if (!current)
1641
+ return `friend not found: ${command.friendId}`;
1642
+ const now = new Date().toISOString();
1643
+ await store.put(command.friendId, {
1644
+ ...current,
1645
+ trustLevel: command.trustLevel,
1646
+ role: command.trustLevel,
1647
+ updatedAt: now,
1648
+ });
1649
+ return `updated: ${command.friendId} → trust=${command.trustLevel}`;
1650
+ }
1651
+ if (command.kind === "friend.link") {
1652
+ const current = await store.get(command.friendId);
1653
+ if (!current)
1654
+ return `friend not found: ${command.friendId}`;
1655
+ const alreadyLinked = current.externalIds.some((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
1656
+ if (alreadyLinked)
1657
+ return `identity already linked: ${command.provider}:${command.externalId}`;
1658
+ const now = new Date().toISOString();
1659
+ const newExternalIds = [
1660
+ ...current.externalIds,
1661
+ { provider: command.provider, externalId: command.externalId, linkedAt: now },
1662
+ ];
1663
+ // Orphan cleanup: check if another friend has this externalId
1664
+ const orphan = await store.findByExternalId(command.provider, command.externalId);
1665
+ let mergeMessage = "";
1666
+ let mergedNotes = { ...current.notes };
1667
+ let mergedTrust = current.trustLevel;
1668
+ let orphanExternalIds = [];
1669
+ if (orphan && orphan.id !== command.friendId) {
1670
+ // Merge orphan's notes (target's notes take priority)
1671
+ mergedNotes = { ...orphan.notes, ...current.notes };
1672
+ // Keep higher trust level
1673
+ mergedTrust = higherTrust(current.trustLevel, orphan.trustLevel);
1674
+ // Collect orphan's other externalIds (excluding the one being linked)
1675
+ orphanExternalIds = orphan.externalIds.filter((ext) => !(ext.provider === command.provider && ext.externalId === command.externalId));
1676
+ await store.delete(orphan.id);
1677
+ mergeMessage = ` (merged orphan ${orphan.id})`;
1678
+ }
1679
+ await store.put(command.friendId, {
1680
+ ...current,
1681
+ externalIds: [...newExternalIds, ...orphanExternalIds],
1682
+ notes: mergedNotes,
1683
+ trustLevel: mergedTrust,
1684
+ updatedAt: now,
1685
+ });
1686
+ return `linked ${command.provider}:${command.externalId} to ${command.friendId}${mergeMessage}`;
1687
+ }
1688
+ // command.kind === "friend.unlink"
1689
+ const current = await store.get(command.friendId);
1690
+ if (!current)
1691
+ return `friend not found: ${command.friendId}`;
1692
+ const idx = current.externalIds.findIndex((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
1693
+ if (idx === -1)
1694
+ return `identity not linked: ${command.provider}:${command.externalId}`;
1695
+ const now = new Date().toISOString();
1696
+ const filtered = current.externalIds.filter((_, i) => i !== idx);
1697
+ await store.put(command.friendId, { ...current, externalIds: filtered, updatedAt: now });
1698
+ return `unlinked ${command.provider}:${command.externalId} from ${command.friendId}`;
1699
+ }
1700
+ function executeReminderCommand(command, taskMod) {
1701
+ try {
1702
+ const created = taskMod.createTask({
1703
+ title: command.title,
1704
+ type: command.cadence ? "habit" : "one-shot",
1705
+ category: command.category ?? "reminder",
1706
+ body: command.body,
1707
+ scheduledAt: command.scheduledAt,
1708
+ cadence: command.cadence,
1709
+ requester: command.requester,
1710
+ });
1711
+ return `created: ${created}`;
1712
+ }
1713
+ catch (error) {
1714
+ return `error: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
1715
+ }
1716
+ }
599
1717
  async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
600
1718
  if (args.includes("--help") || args.includes("-h")) {
601
1719
  const text = usage();
602
1720
  deps.writeStdout(text);
603
1721
  return text;
604
1722
  }
1723
+ if (args.length === 1 && (args[0] === "-v" || args[0] === "--version")) {
1724
+ const text = formatVersionOutput();
1725
+ deps.writeStdout(text);
1726
+ return text;
1727
+ }
605
1728
  let command;
606
1729
  try {
607
1730
  command = parseOuroCommand(args);
@@ -620,23 +1743,12 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
620
1743
  if (args.length === 0) {
621
1744
  const discovered = await Promise.resolve(deps.listDiscoveredAgents ? deps.listDiscoveredAgents() : defaultListDiscoveredAgents());
622
1745
  if (discovered.length === 0 && deps.runAdoptionSpecialist) {
1746
+ // System setup first — ouro command, subagents, UTI — before the interactive specialist
1747
+ await performSystemSetup(deps);
623
1748
  const hatchlingName = await deps.runAdoptionSpecialist();
624
1749
  if (!hatchlingName) {
625
1750
  return "";
626
1751
  }
627
- try {
628
- await deps.installSubagents();
629
- }
630
- catch (error) {
631
- (0, runtime_1.emitNervesEvent)({
632
- level: "warn",
633
- component: "daemon",
634
- event: "daemon.subagent_install_error",
635
- message: "subagent auto-install failed",
636
- meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
637
- });
638
- }
639
- await registerOuroBundleTypeNonBlocking(deps);
640
1752
  await ensureDaemonRunning(deps);
641
1753
  if (deps.startChat) {
642
1754
  await deps.startChat(hatchlingName);
@@ -683,54 +1795,473 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
683
1795
  meta: { kind: command.kind },
684
1796
  });
685
1797
  if (command.kind === "daemon.up") {
686
- try {
687
- await deps.installSubagents();
1798
+ // ── versioned CLI update check ──
1799
+ if (deps.checkForCliUpdate) {
1800
+ let pendingReExec = false;
1801
+ try {
1802
+ const updateResult = await deps.checkForCliUpdate();
1803
+ if (updateResult.available && updateResult.latestVersion) {
1804
+ /* v8 ignore next -- fallback: getCurrentCliVersion always injected in tests @preserve */
1805
+ const currentVersion = deps.getCurrentCliVersion?.() ?? "unknown";
1806
+ await deps.installCliVersion(updateResult.latestVersion);
1807
+ deps.activateCliVersion(updateResult.latestVersion);
1808
+ deps.writeStdout(`ouro updated to ${updateResult.latestVersion} (was ${currentVersion})`);
1809
+ pendingReExec = true;
1810
+ }
1811
+ /* v8 ignore start -- update check error: tested via daemon-cli-update-flow.test.ts @preserve */
1812
+ }
1813
+ catch (error) {
1814
+ (0, runtime_1.emitNervesEvent)({
1815
+ level: "warn",
1816
+ component: "daemon",
1817
+ event: "daemon.cli_update_check_error",
1818
+ message: "CLI update check failed",
1819
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
1820
+ });
1821
+ }
1822
+ /* v8 ignore stop */
1823
+ if (pendingReExec) {
1824
+ deps.reExecFromNewVersion(args);
1825
+ }
688
1826
  }
689
- catch (error) {
690
- (0, runtime_1.emitNervesEvent)({
691
- level: "warn",
692
- component: "daemon",
693
- event: "daemon.subagent_install_error",
694
- message: "subagent auto-install failed",
695
- meta: { error: error instanceof Error ? error.message : String(error) },
696
- });
1827
+ await performSystemSetup(deps);
1828
+ if (deps.ensureDaemonBootPersistence) {
1829
+ try {
1830
+ await Promise.resolve(deps.ensureDaemonBootPersistence(deps.socketPath));
1831
+ }
1832
+ catch (error) {
1833
+ (0, runtime_1.emitNervesEvent)({
1834
+ level: "warn",
1835
+ component: "daemon",
1836
+ event: "daemon.system_setup_launchd_error",
1837
+ message: "failed to persist daemon boot startup",
1838
+ meta: { error: error instanceof Error ? error.message : String(error), socketPath: deps.socketPath },
1839
+ });
1840
+ }
1841
+ }
1842
+ // Run update hooks before starting daemon so user sees the output
1843
+ (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
1844
+ const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
1845
+ const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
1846
+ // Snapshot the previous CLI version from the first bundle-meta before
1847
+ // hooks overwrite it. This detects when npx downloaded a newer CLI.
1848
+ const previousCliVersion = readFirstBundleMetaVersion(bundlesRoot);
1849
+ const updateSummary = await (0, update_hooks_1.applyPendingUpdates)(bundlesRoot, currentVersion);
1850
+ // Notify about CLI binary update (npx downloaded a new version)
1851
+ /* v8 ignore start -- CLI update detection: tested via daemon-cli-version-detect.test.ts @preserve */
1852
+ if (previousCliVersion && previousCliVersion !== currentVersion) {
1853
+ deps.writeStdout(`ouro updated to ${currentVersion} (was ${previousCliVersion})`);
1854
+ }
1855
+ /* v8 ignore stop */
1856
+ if (updateSummary.updated.length > 0) {
1857
+ const agents = updateSummary.updated.map((e) => e.agent);
1858
+ const from = updateSummary.updated[0].from;
1859
+ const to = updateSummary.updated[0].to;
1860
+ const fromStr = from ? ` (was ${from})` : "";
1861
+ const count = agents.length;
1862
+ deps.writeStdout(`updated ${count} agent${count === 1 ? "" : "s"} to runtime ${to}${fromStr}`);
697
1863
  }
698
- await registerOuroBundleTypeNonBlocking(deps);
699
1864
  const daemonResult = await ensureDaemonRunning(deps);
700
1865
  deps.writeStdout(daemonResult.message);
701
1866
  return daemonResult.message;
702
1867
  }
1868
+ // ── rollback command (local, no daemon socket needed for symlinks) ──
1869
+ /* v8 ignore start -- rollback/versions: tested via daemon-cli-rollback/versions tests @preserve */
1870
+ if (command.kind === "rollback") {
1871
+ const currentVersion = deps.getCurrentCliVersion?.() ?? "unknown";
1872
+ if (command.version) {
1873
+ // Rollback to a specific version
1874
+ const installed = deps.listCliVersions?.() ?? [];
1875
+ if (!installed.includes(command.version)) {
1876
+ try {
1877
+ await deps.installCliVersion(command.version);
1878
+ }
1879
+ catch (error) {
1880
+ const message = `failed to install version ${command.version}: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
1881
+ deps.writeStdout(message);
1882
+ return message;
1883
+ }
1884
+ }
1885
+ deps.activateCliVersion(command.version);
1886
+ }
1887
+ else {
1888
+ // Rollback to previous version
1889
+ const previousVersion = deps.getPreviousCliVersion?.();
1890
+ if (!previousVersion) {
1891
+ const message = "no previous version to roll back to";
1892
+ deps.writeStdout(message);
1893
+ return message;
1894
+ }
1895
+ deps.activateCliVersion(previousVersion);
1896
+ command = { ...command, version: previousVersion };
1897
+ }
1898
+ // Stop daemon (non-fatal if not running)
1899
+ try {
1900
+ await deps.sendCommand(deps.socketPath, { kind: "daemon.stop" });
1901
+ }
1902
+ catch {
1903
+ // Daemon may not be running — that's fine
1904
+ }
1905
+ const message = `rolled back to ${command.version} (was ${currentVersion})`;
1906
+ deps.writeStdout(message);
1907
+ return message;
1908
+ }
1909
+ // ── versions command (local, no daemon socket needed) ──
1910
+ if (command.kind === "versions") {
1911
+ const versions = deps.listCliVersions?.() ?? [];
1912
+ if (versions.length === 0) {
1913
+ const message = "no versions installed";
1914
+ deps.writeStdout(message);
1915
+ return message;
1916
+ }
1917
+ const current = deps.getCurrentCliVersion?.();
1918
+ const previous = deps.getPreviousCliVersion?.();
1919
+ const lines = versions.map((v) => {
1920
+ let line = v;
1921
+ if (v === current)
1922
+ line += " * current";
1923
+ if (v === previous)
1924
+ line += " (previous)";
1925
+ return line;
1926
+ });
1927
+ const message = lines.join("\n");
1928
+ deps.writeStdout(message);
1929
+ return message;
1930
+ }
1931
+ /* v8 ignore stop */
703
1932
  if (command.kind === "daemon.logs" && deps.tailLogs) {
704
1933
  deps.tailLogs();
705
1934
  return "";
706
1935
  }
707
- if (command.kind === "friend.link") {
708
- const linker = deps.linkFriendIdentity ?? defaultLinkFriendIdentity;
709
- const message = await linker(command);
1936
+ // ── mcp subcommands (routed through daemon socket) ──
1937
+ if (command.kind === "mcp.list" || command.kind === "mcp.call") {
1938
+ const daemonCommand = toDaemonCommand(command);
1939
+ let response;
1940
+ try {
1941
+ response = await deps.sendCommand(deps.socketPath, daemonCommand);
1942
+ }
1943
+ catch {
1944
+ const message = "daemon unavailable — start with `ouro up` first";
1945
+ deps.writeStdout(message);
1946
+ return message;
1947
+ }
1948
+ if (!response.ok) {
1949
+ const message = response.error ?? "unknown error";
1950
+ deps.writeStdout(message);
1951
+ return message;
1952
+ }
1953
+ const message = formatMcpResponse(command, response);
1954
+ deps.writeStdout(message);
1955
+ return message;
1956
+ }
1957
+ // ── task subcommands (local, no daemon socket needed) ──
1958
+ if (command.kind === "task.board" || command.kind === "task.create" || command.kind === "task.update" ||
1959
+ command.kind === "task.show" || command.kind === "task.actionable" || command.kind === "task.deps" ||
1960
+ command.kind === "task.sessions") {
1961
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
1962
+ const taskMod = deps.taskModule ?? (0, tasks_1.getTaskModule)();
1963
+ /* v8 ignore stop */
1964
+ const message = executeTaskCommand(command, taskMod);
1965
+ deps.writeStdout(message);
1966
+ return message;
1967
+ }
1968
+ // ── reminder subcommands (local, no daemon socket needed) ──
1969
+ if (command.kind === "reminder.create") {
1970
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
1971
+ const taskMod = deps.taskModule ?? (0, tasks_1.getTaskModule)();
1972
+ /* v8 ignore stop */
1973
+ const message = executeReminderCommand(command, taskMod);
1974
+ deps.writeStdout(message);
1975
+ return message;
1976
+ }
1977
+ // ── friend subcommands (local, no daemon socket needed) ──
1978
+ if (command.kind === "friend.list" || command.kind === "friend.show" || command.kind === "friend.create" ||
1979
+ command.kind === "friend.update" || command.kind === "friend.link" || command.kind === "friend.unlink") {
1980
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
1981
+ let store = deps.friendStore;
1982
+ if (!store) {
1983
+ // Derive agent-scoped friends dir from --agent flag or link/unlink's agent field
1984
+ const agentName = ("agent" in command && command.agent) ? command.agent : undefined;
1985
+ const friendsDir = agentName
1986
+ ? path.join((0, identity_1.getAgentBundlesRoot)(), `${agentName}.ouro`, "friends")
1987
+ : path.join((0, identity_1.getAgentBundlesRoot)(), "friends");
1988
+ store = new store_file_1.FileFriendStore(friendsDir);
1989
+ }
1990
+ /* v8 ignore stop */
1991
+ const message = await executeFriendCommand(command, store);
710
1992
  deps.writeStdout(message);
711
1993
  return message;
712
1994
  }
1995
+ // ── auth (local, no daemon socket needed) ──
1996
+ if (command.kind === "auth.run") {
1997
+ const provider = command.provider ?? (0, auth_flow_1.readAgentConfigForAgent)(command.agent).config.provider;
1998
+ /* v8 ignore next -- tests always inject runAuthFlow; default is for production @preserve */
1999
+ const authRunner = deps.runAuthFlow ?? auth_flow_1.runRuntimeAuthFlow;
2000
+ const result = await authRunner({
2001
+ agentName: command.agent,
2002
+ provider,
2003
+ promptInput: deps.promptInput,
2004
+ });
2005
+ // Behavior: ouro auth stores credentials only — does NOT switch provider.
2006
+ // Use `ouro auth switch` to change the active provider.
2007
+ deps.writeStdout(result.message);
2008
+ return result.message;
2009
+ }
2010
+ // ── auth verify (local, no daemon socket needed) ──
2011
+ /* v8 ignore start -- auth verify/switch: tested in daemon-cli.test.ts but v8 traces differ in CI @preserve */
2012
+ if (command.kind === "auth.verify") {
2013
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2014
+ const providers = secrets.providers;
2015
+ const fetchFn = deps.fetchImpl ?? fetch;
2016
+ if (command.provider) {
2017
+ const status = await verifyProviderCredentials(command.provider, providers, fetchFn);
2018
+ const message = `${command.provider}: ${status}`;
2019
+ deps.writeStdout(message);
2020
+ return message;
2021
+ }
2022
+ const lines = [];
2023
+ for (const p of Object.keys(providers)) {
2024
+ const status = await verifyProviderCredentials(p, providers, fetchFn);
2025
+ lines.push(`${p}: ${status}`);
2026
+ }
2027
+ const message = lines.join("\n");
2028
+ deps.writeStdout(message);
2029
+ return message;
2030
+ }
2031
+ // ── auth switch (local, no daemon socket needed) ──
2032
+ if (command.kind === "auth.switch") {
2033
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2034
+ const providerSecrets = secrets.providers[command.provider];
2035
+ if (!providerSecrets || !hasStoredCredentials(command.provider, providerSecrets)) {
2036
+ const message = `no credentials stored for ${command.provider}. Run \`ouro auth --agent ${command.agent} --provider ${command.provider}\` first.`;
2037
+ deps.writeStdout(message);
2038
+ return message;
2039
+ }
2040
+ (0, auth_flow_1.writeAgentProviderSelection)(command.agent, command.provider);
2041
+ const message = `switched ${command.agent} to ${command.provider}`;
2042
+ deps.writeStdout(message);
2043
+ return message;
2044
+ }
2045
+ /* v8 ignore stop */
2046
+ // ── config models (local, no daemon socket needed) ──
2047
+ /* v8 ignore start -- config models: tested via daemon-cli.test.ts @preserve */
2048
+ if (command.kind === "config.models") {
2049
+ const { config } = (0, auth_flow_1.readAgentConfigForAgent)(command.agent);
2050
+ const provider = config.provider;
2051
+ if (provider !== "github-copilot") {
2052
+ const message = `model listing not available for ${provider} — check provider documentation.`;
2053
+ deps.writeStdout(message);
2054
+ return message;
2055
+ }
2056
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2057
+ const ghConfig = secrets.providers["github-copilot"];
2058
+ if (!ghConfig.githubToken || !ghConfig.baseUrl) {
2059
+ throw new Error(`github-copilot credentials not configured. Run \`ouro auth --agent ${command.agent} --provider github-copilot\` first.`);
2060
+ }
2061
+ const fetchFn = deps.fetchImpl ?? fetch;
2062
+ const models = await listGithubCopilotModels(ghConfig.baseUrl, ghConfig.githubToken, fetchFn);
2063
+ if (models.length === 0) {
2064
+ const message = "no models found";
2065
+ deps.writeStdout(message);
2066
+ return message;
2067
+ }
2068
+ const lines = ["available models:"];
2069
+ for (const m of models) {
2070
+ const caps = m.capabilities?.length ? ` (${m.capabilities.join(", ")})` : "";
2071
+ lines.push(` ${m.id}${caps}`);
2072
+ }
2073
+ const message = lines.join("\n");
2074
+ deps.writeStdout(message);
2075
+ return message;
2076
+ }
2077
+ /* v8 ignore stop */
2078
+ // ── config model (local, no daemon socket needed) ──
2079
+ /* v8 ignore start -- config model: tested via daemon-cli.test.ts @preserve */
2080
+ if (command.kind === "config.model") {
2081
+ // Validate model availability for github-copilot before writing
2082
+ const { config } = (0, auth_flow_1.readAgentConfigForAgent)(command.agent);
2083
+ if (config.provider === "github-copilot") {
2084
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2085
+ const ghConfig = secrets.providers["github-copilot"];
2086
+ if (ghConfig.githubToken && ghConfig.baseUrl) {
2087
+ const fetchFn = deps.fetchImpl ?? fetch;
2088
+ try {
2089
+ const models = await listGithubCopilotModels(ghConfig.baseUrl, ghConfig.githubToken, fetchFn);
2090
+ const available = models.map((m) => m.id);
2091
+ if (available.length > 0 && !available.includes(command.modelName)) {
2092
+ const message = `model '${command.modelName}' not found. available models:\n${available.map((id) => ` ${id}`).join("\n")}`;
2093
+ deps.writeStdout(message);
2094
+ return message;
2095
+ }
2096
+ }
2097
+ catch {
2098
+ // Catalog validation failed — fall through to ping test
2099
+ }
2100
+ // Ping test: verify the model actually works before switching
2101
+ const pingResult = await pingGithubCopilotModel(ghConfig.baseUrl, ghConfig.githubToken, command.modelName, fetchFn);
2102
+ if (!pingResult.ok) {
2103
+ const message = `model '${command.modelName}' ping failed: ${pingResult.error}\nrun \`ouro config models --agent ${command.agent}\` to see available models.`;
2104
+ deps.writeStdout(message);
2105
+ return message;
2106
+ }
2107
+ }
2108
+ }
2109
+ const { provider, previousModel } = (0, auth_flow_1.writeAgentModel)(command.agent, command.modelName);
2110
+ const message = previousModel
2111
+ ? `updated ${command.agent} model on ${provider}: ${previousModel} → ${command.modelName}`
2112
+ : `set ${command.agent} model on ${provider}: ${command.modelName}`;
2113
+ deps.writeStdout(message);
2114
+ return message;
2115
+ }
2116
+ /* v8 ignore stop */
2117
+ // ── whoami (local, no daemon socket needed) ──
2118
+ if (command.kind === "whoami") {
2119
+ if (command.agent) {
2120
+ const agentRoot = path.join((0, identity_1.getAgentBundlesRoot)(), `${command.agent}.ouro`);
2121
+ const message = [
2122
+ `agent: ${command.agent}`,
2123
+ `home: ${agentRoot}`,
2124
+ `bones: ${(0, runtime_metadata_1.getRuntimeMetadata)().version}`,
2125
+ ].join("\n");
2126
+ deps.writeStdout(message);
2127
+ return message;
2128
+ }
2129
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
2130
+ try {
2131
+ const info = deps.whoamiInfo
2132
+ ? deps.whoamiInfo()
2133
+ : {
2134
+ agentName: (0, identity_1.getAgentName)(),
2135
+ homePath: path.join((0, identity_1.getAgentBundlesRoot)(), `${(0, identity_1.getAgentName)()}.ouro`),
2136
+ bonesVersion: (0, runtime_metadata_1.getRuntimeMetadata)().version,
2137
+ };
2138
+ const message = [
2139
+ `agent: ${info.agentName}`,
2140
+ `home: ${info.homePath}`,
2141
+ `bones: ${info.bonesVersion}`,
2142
+ ].join("\n");
2143
+ deps.writeStdout(message);
2144
+ return message;
2145
+ }
2146
+ catch {
2147
+ const message = "error: no agent context — use --agent <name> to specify";
2148
+ deps.writeStdout(message);
2149
+ return message;
2150
+ }
2151
+ /* v8 ignore stop */
2152
+ }
2153
+ // ── changelog (local, no daemon socket needed) ──
2154
+ if (command.kind === "changelog") {
2155
+ try {
2156
+ const changelogPath = deps.getChangelogPath
2157
+ ? deps.getChangelogPath()
2158
+ : (0, bundle_manifest_1.getChangelogPath)();
2159
+ const raw = fs.readFileSync(changelogPath, "utf-8");
2160
+ const entries = JSON.parse(raw);
2161
+ let filtered = entries;
2162
+ if (command.from) {
2163
+ const fromVersion = command.from;
2164
+ filtered = entries.filter((e) => e.version > fromVersion);
2165
+ }
2166
+ if (filtered.length === 0) {
2167
+ const message = "no changelog entries found.";
2168
+ deps.writeStdout(message);
2169
+ return message;
2170
+ }
2171
+ const lines = [];
2172
+ for (const entry of filtered) {
2173
+ lines.push(`## ${entry.version}${entry.date ? ` (${entry.date})` : ""}`);
2174
+ if (entry.changes) {
2175
+ for (const change of entry.changes) {
2176
+ lines.push(`- ${change}`);
2177
+ }
2178
+ }
2179
+ lines.push("");
2180
+ }
2181
+ const message = lines.join("\n").trim();
2182
+ deps.writeStdout(message);
2183
+ return message;
2184
+ }
2185
+ catch {
2186
+ const message = "no changelog entries found.";
2187
+ deps.writeStdout(message);
2188
+ return message;
2189
+ }
2190
+ }
2191
+ // ── thoughts (local, no daemon socket needed) ──
2192
+ if (command.kind === "thoughts") {
2193
+ try {
2194
+ const agentName = command.agent ?? (0, identity_1.getAgentName)();
2195
+ const agentRoot = path.join((0, identity_1.getAgentBundlesRoot)(), `${agentName}.ouro`);
2196
+ const sessionFilePath = (0, thoughts_1.getInnerDialogSessionPath)(agentRoot);
2197
+ if (command.json) {
2198
+ try {
2199
+ const raw = fs.readFileSync(sessionFilePath, "utf-8");
2200
+ deps.writeStdout(raw);
2201
+ return raw;
2202
+ }
2203
+ catch {
2204
+ const message = "no inner dialog session found";
2205
+ deps.writeStdout(message);
2206
+ return message;
2207
+ }
2208
+ }
2209
+ const turns = (0, thoughts_1.parseInnerDialogSession)(sessionFilePath);
2210
+ const message = (0, thoughts_1.formatThoughtTurns)(turns, command.last ?? 10);
2211
+ deps.writeStdout(message);
2212
+ if (command.follow) {
2213
+ deps.writeStdout("\n\n--- following (ctrl+c to stop) ---\n");
2214
+ /* v8 ignore start -- callback tested via followThoughts unit tests @preserve */
2215
+ const stop = (0, thoughts_1.followThoughts)(sessionFilePath, (formatted) => {
2216
+ deps.writeStdout("\n" + formatted);
2217
+ });
2218
+ /* v8 ignore stop */
2219
+ // Block until process exit; cleanup watcher on SIGINT/SIGTERM
2220
+ return new Promise((resolve) => {
2221
+ const cleanup = () => { stop(); resolve(message); };
2222
+ process.once("SIGINT", cleanup);
2223
+ process.once("SIGTERM", cleanup);
2224
+ });
2225
+ }
2226
+ return message;
2227
+ }
2228
+ catch {
2229
+ const message = "error: no agent context — use --agent <name> to specify";
2230
+ deps.writeStdout(message);
2231
+ return message;
2232
+ }
2233
+ }
2234
+ // ── session list (local, no daemon socket needed) ──
2235
+ if (command.kind === "session.list") {
2236
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
2237
+ const scanner = deps.scanSessions ?? (async () => []);
2238
+ /* v8 ignore stop */
2239
+ const sessions = await scanner();
2240
+ if (sessions.length === 0) {
2241
+ const message = "no active sessions";
2242
+ deps.writeStdout(message);
2243
+ return message;
2244
+ }
2245
+ const lines = sessions.map((s) => `${s.friendId} ${s.friendName} ${s.channel} ${s.lastActivity}`);
2246
+ const message = lines.join("\n");
2247
+ deps.writeStdout(message);
2248
+ return message;
2249
+ }
2250
+ if (command.kind === "chat.connect" && deps.startChat) {
2251
+ await ensureDaemonRunning(deps);
2252
+ await deps.startChat(command.agent);
2253
+ return "";
2254
+ }
713
2255
  if (command.kind === "hatch.start") {
714
2256
  // Route through adoption specialist when no explicit hatch args were provided
715
2257
  const hasExplicitHatchArgs = !!(command.agentName || command.humanName || command.provider || command.credentials);
716
2258
  if (deps.runAdoptionSpecialist && !hasExplicitHatchArgs) {
2259
+ // System setup first — ouro command, subagents, UTI — before the interactive specialist
2260
+ await performSystemSetup(deps);
717
2261
  const hatchlingName = await deps.runAdoptionSpecialist();
718
2262
  if (!hatchlingName) {
719
2263
  return "";
720
2264
  }
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 : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
731
- });
732
- }
733
- await registerOuroBundleTypeNonBlocking(deps);
734
2265
  await ensureDaemonRunning(deps);
735
2266
  if (deps.startChat) {
736
2267
  await deps.startChat(hatchlingName);
@@ -746,19 +2277,7 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
746
2277
  }
747
2278
  const hatchInput = await resolveHatchInput(command, deps);
748
2279
  const result = await hatchRunner(hatchInput);
749
- try {
750
- await deps.installSubagents();
751
- }
752
- catch (error) {
753
- (0, runtime_1.emitNervesEvent)({
754
- level: "warn",
755
- component: "daemon",
756
- event: "daemon.subagent_install_error",
757
- message: "subagent auto-install failed",
758
- meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
759
- });
760
- }
761
- await registerOuroBundleTypeNonBlocking(deps);
2280
+ await performSystemSetup(deps);
762
2281
  const daemonResult = await ensureDaemonRunning(deps);
763
2282
  if (deps.startChat) {
764
2283
  await deps.startChat(hatchInput.agentName);
@@ -780,9 +2299,22 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
780
2299
  deps.writeStdout(message);
781
2300
  return message;
782
2301
  }
2302
+ if (command.kind === "daemon.status" && isDaemonUnavailableError(error)) {
2303
+ const message = daemonUnavailableStatusOutput(deps.socketPath);
2304
+ deps.writeStdout(message);
2305
+ return message;
2306
+ }
2307
+ if (command.kind === "daemon.stop" && isDaemonUnavailableError(error)) {
2308
+ const message = "daemon not running";
2309
+ deps.writeStdout(message);
2310
+ return message;
2311
+ }
783
2312
  throw error;
784
2313
  }
785
- const message = response.summary ?? response.message ?? (response.ok ? "ok" : `error: ${response.error ?? "unknown error"}`);
2314
+ const fallbackMessage = response.summary ?? response.message ?? (response.ok ? "ok" : `error: ${response.error ?? "unknown error"}`);
2315
+ const message = command.kind === "daemon.status"
2316
+ ? formatDaemonStatusOutput(response, fallbackMessage)
2317
+ : fallbackMessage;
786
2318
  deps.writeStdout(message);
787
2319
  return message;
788
2320
  }