@ouro.bot/cli 0.1.0-alpha.16 → 0.1.0-alpha.160
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.
- package/AdoptionSpecialist.ouro/agent.json +3 -2
- package/AdoptionSpecialist.ouro/psyche/SOUL.md +3 -3
- package/AdoptionSpecialist.ouro/psyche/identities/monty.md +2 -2
- package/README.md +186 -191
- package/changelog.json +1081 -0
- package/dist/heart/active-work.js +633 -0
- package/dist/heart/bridges/manager.js +358 -0
- package/dist/heart/bridges/state-machine.js +135 -0
- package/dist/heart/bridges/store.js +123 -0
- package/dist/heart/commitments.js +105 -0
- package/dist/heart/config.js +40 -30
- package/dist/heart/core.js +608 -123
- package/dist/heart/cross-chat-delivery.js +146 -0
- package/dist/heart/daemon/agent-discovery.js +81 -0
- package/dist/heart/daemon/agent-service.js +360 -0
- package/dist/heart/daemon/auth-flow.js +477 -0
- package/dist/heart/daemon/cadence.js +70 -0
- package/dist/heart/daemon/daemon-cli.js +2467 -205
- package/dist/heart/daemon/daemon-entry.js +131 -4
- package/dist/heart/daemon/daemon-health.js +136 -0
- package/dist/heart/daemon/daemon-runtime-sync.js +212 -0
- package/dist/heart/daemon/daemon-tombstone.js +123 -0
- package/dist/heart/daemon/daemon.js +434 -17
- package/dist/heart/daemon/habit-migration.js +181 -0
- package/dist/heart/daemon/habit-parser.js +119 -0
- package/dist/heart/daemon/habit-scheduler.js +369 -0
- package/dist/heart/daemon/hatch-animation.js +10 -3
- package/dist/heart/daemon/hatch-flow.js +30 -111
- package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
- package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
- package/dist/heart/daemon/inner-status.js +89 -0
- package/dist/heart/daemon/launchd.js +159 -0
- package/dist/heart/daemon/log-tailer.js +4 -3
- package/dist/heart/daemon/mcp-server.js +591 -0
- package/dist/heart/daemon/message-router.js +17 -8
- package/dist/heart/daemon/os-cron-deps.js +134 -0
- package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
- package/dist/heart/daemon/ouro-path-installer.js +78 -34
- package/dist/heart/daemon/ouro-version-manager.js +171 -0
- package/dist/heart/daemon/outlook-http.js +307 -0
- package/dist/heart/daemon/outlook-read.js +1281 -0
- package/dist/heart/daemon/outlook-render.js +1032 -0
- package/dist/heart/daemon/outlook-types.js +7 -0
- package/dist/heart/daemon/outlook-view.js +194 -0
- package/dist/heart/daemon/process-manager.js +75 -0
- package/dist/heart/daemon/run-hooks.js +39 -0
- package/dist/heart/daemon/runtime-logging.js +58 -15
- package/dist/heart/daemon/runtime-metadata.js +219 -0
- package/dist/heart/daemon/runtime-mode.js +67 -0
- package/dist/heart/daemon/safe-mode.js +161 -0
- package/dist/heart/daemon/sense-manager.js +50 -2
- package/dist/heart/daemon/session-id-resolver.js +131 -0
- package/dist/heart/daemon/skill-management-installer.js +94 -0
- package/dist/heart/daemon/socket-client.js +202 -0
- package/dist/heart/daemon/specialist-orchestrator.js +2 -2
- package/dist/heart/daemon/specialist-prompt.js +13 -8
- package/dist/heart/daemon/specialist-tools.js +53 -4
- package/dist/heart/daemon/staged-restart.js +114 -0
- package/dist/heart/daemon/task-scheduler.js +3 -25
- package/dist/heart/daemon/thoughts.js +507 -0
- package/dist/heart/daemon/update-checker.js +111 -0
- package/dist/heart/daemon/update-hooks.js +138 -0
- package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
- package/dist/heart/delegation.js +62 -0
- package/dist/heart/identity.js +136 -55
- package/dist/heart/kicks.js +2 -20
- package/dist/heart/migrate-config.js +127 -0
- package/dist/heart/model-capabilities.js +48 -0
- package/dist/heart/obligations.js +197 -0
- package/dist/heart/progress-story.js +42 -0
- package/dist/heart/provider-failover.js +88 -0
- package/dist/heart/provider-ping.js +172 -0
- package/dist/heart/providers/anthropic-token.js +163 -0
- package/dist/heart/providers/anthropic.js +196 -36
- package/dist/heart/providers/azure.js +116 -10
- package/dist/heart/providers/github-copilot.js +157 -0
- package/dist/heart/providers/minimax.js +33 -3
- package/dist/heart/providers/openai-codex.js +51 -16
- package/dist/heart/session-activity.js +172 -0
- package/dist/heart/session-recall.js +216 -0
- package/dist/heart/streaming.js +117 -33
- package/dist/heart/target-resolution.js +127 -0
- package/dist/heart/tool-activity-callbacks.js +36 -0
- package/dist/heart/tool-description.js +135 -0
- package/dist/heart/tool-loop.js +200 -0
- package/dist/heart/turn-coordinator.js +28 -0
- package/dist/mind/associative-recall.js +122 -32
- package/dist/mind/bundle-manifest.js +14 -0
- package/dist/mind/context.js +125 -14
- package/dist/mind/{memory.js → diary.js} +70 -56
- package/dist/mind/first-impressions.js +16 -2
- package/dist/mind/friends/channel.js +56 -0
- package/dist/mind/friends/group-context.js +144 -0
- package/dist/mind/friends/store-file.js +19 -0
- package/dist/mind/friends/trust-explanation.js +74 -0
- package/dist/mind/friends/types.js +8 -0
- package/dist/mind/journal-index.js +161 -0
- package/dist/mind/obligation-steering.js +221 -0
- package/dist/mind/obligations.js +134 -0
- package/dist/mind/pending.js +76 -9
- package/dist/mind/phrases.js +1 -0
- package/dist/mind/prompt.js +651 -91
- package/dist/mind/token-estimate.js +8 -12
- package/dist/nerves/cli-logging.js +15 -2
- package/dist/nerves/coverage/run-artifacts.js +1 -1
- package/dist/nerves/event-buffer.js +111 -0
- package/dist/nerves/index.js +63 -3
- package/dist/nerves/observation.js +20 -0
- package/dist/nerves/runtime.js +5 -1
- package/dist/repertoire/ado-semantic.js +6 -0
- package/dist/repertoire/coding/codex-jsonl.js +64 -0
- package/dist/repertoire/coding/context-pack.js +254 -0
- package/dist/repertoire/coding/feedback.js +301 -0
- package/dist/repertoire/coding/index.js +4 -1
- package/dist/repertoire/coding/manager.js +210 -4
- package/dist/repertoire/coding/spawner.js +58 -12
- package/dist/repertoire/coding/tools.js +176 -4
- package/dist/repertoire/guardrails.js +291 -0
- package/dist/repertoire/mcp-client.js +254 -0
- package/dist/repertoire/mcp-manager.js +198 -0
- package/dist/repertoire/skills.js +14 -23
- package/dist/repertoire/tasks/board.js +43 -5
- package/dist/repertoire/tasks/fix.js +182 -0
- package/dist/repertoire/tasks/index.js +28 -10
- package/dist/repertoire/tasks/lifecycle.js +2 -2
- package/dist/repertoire/tasks/parser.js +3 -2
- package/dist/repertoire/tasks/scanner.js +194 -37
- package/dist/repertoire/tasks/transitions.js +11 -28
- package/dist/repertoire/tools-base.js +992 -273
- package/dist/repertoire/tools-bluebubbles.js +94 -0
- package/dist/repertoire/tools-github.js +1 -6
- package/dist/repertoire/tools-teams.js +12 -59
- package/dist/repertoire/tools.js +281 -101
- package/dist/scripts/claude-code-hook.js +41 -0
- package/dist/scripts/claude-code-stop-hook.js +47 -0
- package/dist/senses/attention-queue.js +97 -0
- package/dist/senses/bluebubbles-client.js +258 -5
- package/dist/senses/bluebubbles-entry.js +2 -0
- package/dist/senses/bluebubbles-inbound-log.js +109 -0
- package/dist/senses/bluebubbles-media.js +339 -0
- package/dist/senses/bluebubbles-model.js +12 -4
- package/dist/senses/bluebubbles-mutation-log.js +45 -5
- package/dist/senses/bluebubbles-runtime-state.js +109 -0
- package/dist/senses/bluebubbles-session-cleanup.js +72 -0
- package/dist/senses/bluebubbles.js +1040 -45
- package/dist/senses/cli-entry.js +1 -1
- package/dist/senses/cli-layout.js +187 -0
- package/dist/senses/cli.js +419 -152
- package/dist/senses/commands.js +38 -1
- package/dist/senses/continuity.js +94 -0
- package/dist/senses/habit-turn-message.js +108 -0
- package/dist/senses/inner-dialog-worker.js +112 -19
- package/dist/senses/inner-dialog.js +592 -84
- package/dist/senses/pipeline.js +502 -0
- package/dist/senses/shared-turn.js +196 -0
- package/dist/senses/surface-tool.js +95 -0
- package/dist/senses/teams.js +667 -120
- package/dist/senses/trust-gate.js +112 -2
- package/package.json +12 -4
- package/skills/configure-dev-tools.md +81 -0
- package/subagents/README.md +4 -70
- package/dist/heart/daemon/subagent-installer.js +0 -134
- package/subagents/work-doer.md +0 -233
- package/subagents/work-merger.md +0 -624
- package/subagents/work-planner.md +0 -373
|
@@ -34,26 +34,48 @@ 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;
|
|
38
41
|
exports.discoverExistingCredentials = discoverExistingCredentials;
|
|
39
42
|
exports.createDefaultOuroCliDeps = createDefaultOuroCliDeps;
|
|
40
43
|
exports.runOuroCli = runOuroCli;
|
|
41
44
|
const child_process_1 = require("child_process");
|
|
45
|
+
const crypto_1 = require("crypto");
|
|
42
46
|
const fs = __importStar(require("fs"));
|
|
43
|
-
const net = __importStar(require("net"));
|
|
44
47
|
const os = __importStar(require("os"));
|
|
45
48
|
const path = __importStar(require("path"));
|
|
49
|
+
const semver = __importStar(require("semver"));
|
|
46
50
|
const identity_1 = require("../identity");
|
|
47
51
|
const runtime_1 = require("../../nerves/runtime");
|
|
48
52
|
const store_file_1 = require("../../mind/friends/store-file");
|
|
49
53
|
const types_1 = require("../../mind/friends/types");
|
|
50
54
|
const ouro_uti_1 = require("./ouro-uti");
|
|
51
55
|
const ouro_path_installer_1 = require("./ouro-path-installer");
|
|
52
|
-
const
|
|
56
|
+
const ouro_version_manager_1 = require("./ouro-version-manager");
|
|
57
|
+
const skill_management_installer_1 = require("./skill-management-installer");
|
|
53
58
|
const hatch_flow_1 = require("./hatch-flow");
|
|
54
59
|
const specialist_orchestrator_1 = require("./specialist-orchestrator");
|
|
55
60
|
const specialist_prompt_1 = require("./specialist-prompt");
|
|
56
61
|
const specialist_tools_1 = require("./specialist-tools");
|
|
62
|
+
const runtime_metadata_1 = require("./runtime-metadata");
|
|
63
|
+
const runtime_mode_1 = require("./runtime-mode");
|
|
64
|
+
const daemon_runtime_sync_1 = require("./daemon-runtime-sync");
|
|
65
|
+
const agent_discovery_1 = require("./agent-discovery");
|
|
66
|
+
const update_hooks_1 = require("./update-hooks");
|
|
67
|
+
const bundle_meta_1 = require("./hooks/bundle-meta");
|
|
68
|
+
const agent_config_v2_1 = require("./hooks/agent-config-v2");
|
|
69
|
+
const bundle_manifest_1 = require("../../mind/bundle-manifest");
|
|
70
|
+
const tasks_1 = require("../../repertoire/tasks");
|
|
71
|
+
const thoughts_1 = require("./thoughts");
|
|
72
|
+
const ouro_bot_global_installer_1 = require("./ouro-bot-global-installer");
|
|
73
|
+
const launchd_1 = require("./launchd");
|
|
74
|
+
const socket_client_1 = require("./socket-client");
|
|
75
|
+
const daemon_tombstone_1 = require("./daemon-tombstone");
|
|
76
|
+
const daemon_health_1 = require("./daemon-health");
|
|
77
|
+
const session_activity_1 = require("../session-activity");
|
|
78
|
+
const auth_flow_1 = require("./auth-flow");
|
|
57
79
|
function stringField(value) {
|
|
58
80
|
return typeof value === "string" ? value : null;
|
|
59
81
|
}
|
|
@@ -78,8 +100,15 @@ function parseStatusPayload(data) {
|
|
|
78
100
|
daemon: stringField(overview.daemon) ?? "unknown",
|
|
79
101
|
health: stringField(overview.health) ?? "unknown",
|
|
80
102
|
socketPath: stringField(overview.socketPath) ?? "unknown",
|
|
103
|
+
outlookUrl: stringField(overview.outlookUrl) ?? "unavailable",
|
|
104
|
+
version: stringField(overview.version) ?? "unknown",
|
|
105
|
+
lastUpdated: stringField(overview.lastUpdated) ?? "unknown",
|
|
106
|
+
repoRoot: stringField(overview.repoRoot) ?? "unknown",
|
|
107
|
+
configFingerprint: stringField(overview.configFingerprint) ?? "unknown",
|
|
81
108
|
workerCount: numberField(overview.workerCount) ?? 0,
|
|
82
109
|
senseCount: numberField(overview.senseCount) ?? 0,
|
|
110
|
+
entryPath: stringField(overview.entryPath) ?? "unknown",
|
|
111
|
+
mode: stringField(overview.mode) ?? "unknown",
|
|
83
112
|
};
|
|
84
113
|
const parsedSenses = senses.map((entry) => {
|
|
85
114
|
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
@@ -120,6 +149,8 @@ function parseStatusPayload(data) {
|
|
|
120
149
|
status,
|
|
121
150
|
pid,
|
|
122
151
|
restartCount,
|
|
152
|
+
lastExitCode: numberField(row.lastExitCode) ?? null,
|
|
153
|
+
lastSignal: stringField(row.lastSignal) ?? null,
|
|
123
154
|
};
|
|
124
155
|
});
|
|
125
156
|
if (parsedSenses.some((row) => row === null) || parsedWorkers.some((row) => row === null))
|
|
@@ -143,7 +174,9 @@ function humanizeSenseName(sense, label) {
|
|
|
143
174
|
}
|
|
144
175
|
function formatTable(headers, rows) {
|
|
145
176
|
const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => row[index].length)));
|
|
146
|
-
const renderRow = (row) => `| ${row.map((cell, index) =>
|
|
177
|
+
const renderRow = (row) => `| ${row.map((cell, index) => (index === row.length - 1
|
|
178
|
+
? cell
|
|
179
|
+
: cell.padEnd(widths[index]))).join(" | ")} |`;
|
|
147
180
|
const divider = `|-${widths.map((width) => "-".repeat(width)).join("-|-")}-|`;
|
|
148
181
|
return [
|
|
149
182
|
renderRow(headers),
|
|
@@ -158,6 +191,11 @@ function formatDaemonStatusOutput(response, fallback) {
|
|
|
158
191
|
const overviewRows = [
|
|
159
192
|
["Daemon", payload.overview.daemon],
|
|
160
193
|
["Socket", payload.overview.socketPath],
|
|
194
|
+
["Version", payload.overview.version],
|
|
195
|
+
["Last Updated", payload.overview.lastUpdated],
|
|
196
|
+
["Outlook", payload.overview.outlookUrl],
|
|
197
|
+
["Entry Path", payload.overview.entryPath],
|
|
198
|
+
["Mode", payload.overview.mode],
|
|
161
199
|
["Workers", String(payload.overview.workerCount)],
|
|
162
200
|
["Senses", String(payload.overview.senseCount)],
|
|
163
201
|
["Health", payload.overview.health],
|
|
@@ -169,13 +207,23 @@ function formatDaemonStatusOutput(response, fallback) {
|
|
|
169
207
|
row.status,
|
|
170
208
|
row.detail,
|
|
171
209
|
]);
|
|
172
|
-
const workerRows = payload.workers.map((row) =>
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
row.
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
210
|
+
const workerRows = payload.workers.map((row) => {
|
|
211
|
+
/* v8 ignore start — exit info branches tested via daemon-crash-context; v8 misreports conditional chains @preserve */
|
|
212
|
+
let exitInfo = "n/a";
|
|
213
|
+
if (row.lastExitCode !== null)
|
|
214
|
+
exitInfo = `code=${row.lastExitCode}`;
|
|
215
|
+
if (row.lastSignal !== null)
|
|
216
|
+
exitInfo = row.lastExitCode !== null ? `code=${row.lastExitCode} sig=${row.lastSignal}` : `sig=${row.lastSignal}`;
|
|
217
|
+
/* v8 ignore stop */
|
|
218
|
+
return [
|
|
219
|
+
row.agent,
|
|
220
|
+
row.worker,
|
|
221
|
+
row.status,
|
|
222
|
+
row.pid === null ? "n/a" : String(row.pid),
|
|
223
|
+
String(row.restartCount),
|
|
224
|
+
exitInfo,
|
|
225
|
+
];
|
|
226
|
+
});
|
|
179
227
|
return [
|
|
180
228
|
"Overview",
|
|
181
229
|
formatTable(["Item", "Value"], overviewRows),
|
|
@@ -184,16 +232,41 @@ function formatDaemonStatusOutput(response, fallback) {
|
|
|
184
232
|
formatTable(["Agent", "Sense", "Enabled", "State", "Detail"], senseRows),
|
|
185
233
|
"",
|
|
186
234
|
"Workers",
|
|
187
|
-
formatTable(["Agent", "Worker", "State", "PID", "Restarts"], workerRows),
|
|
235
|
+
formatTable(["Agent", "Worker", "State", "PID", "Restarts", "Last Exit"], workerRows),
|
|
188
236
|
].join("\n");
|
|
189
237
|
}
|
|
190
238
|
async function ensureDaemonRunning(deps) {
|
|
191
239
|
const alive = await deps.checkSocketAlive(deps.socketPath);
|
|
192
240
|
if (alive) {
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
241
|
+
const localRuntime = (0, runtime_metadata_1.getRuntimeMetadata)();
|
|
242
|
+
let runningRuntimePromise = null;
|
|
243
|
+
const fetchRunningRuntimeMetadata = async () => {
|
|
244
|
+
runningRuntimePromise ??= (async () => {
|
|
245
|
+
const status = await deps.sendCommand(deps.socketPath, { kind: "daemon.status" });
|
|
246
|
+
const payload = parseStatusPayload(status.data);
|
|
247
|
+
return {
|
|
248
|
+
version: payload?.overview.version ?? "unknown",
|
|
249
|
+
lastUpdated: payload?.overview.lastUpdated ?? "unknown",
|
|
250
|
+
repoRoot: payload?.overview.repoRoot ?? "unknown",
|
|
251
|
+
configFingerprint: payload?.overview.configFingerprint ?? "unknown",
|
|
252
|
+
};
|
|
253
|
+
})();
|
|
254
|
+
return runningRuntimePromise;
|
|
196
255
|
};
|
|
256
|
+
return (0, daemon_runtime_sync_1.ensureCurrentDaemonRuntime)({
|
|
257
|
+
socketPath: deps.socketPath,
|
|
258
|
+
localVersion: localRuntime.version,
|
|
259
|
+
localLastUpdated: localRuntime.lastUpdated,
|
|
260
|
+
localRepoRoot: localRuntime.repoRoot,
|
|
261
|
+
localConfigFingerprint: localRuntime.configFingerprint,
|
|
262
|
+
fetchRunningVersion: async () => (await fetchRunningRuntimeMetadata()).version,
|
|
263
|
+
fetchRunningRuntimeMetadata,
|
|
264
|
+
stopDaemon: async () => {
|
|
265
|
+
await deps.sendCommand(deps.socketPath, { kind: "daemon.stop" });
|
|
266
|
+
},
|
|
267
|
+
cleanupStaleSocket: deps.cleanupStaleSocket,
|
|
268
|
+
startDaemonProcess: deps.startDaemonProcess,
|
|
269
|
+
});
|
|
197
270
|
}
|
|
198
271
|
deps.cleanupStaleSocket(deps.socketPath);
|
|
199
272
|
const started = await deps.startDaemonProcess(deps.socketPath);
|
|
@@ -202,17 +275,137 @@ async function ensureDaemonRunning(deps) {
|
|
|
202
275
|
message: `daemon started (pid ${started.pid ?? "unknown"})`,
|
|
203
276
|
};
|
|
204
277
|
}
|
|
278
|
+
/**
|
|
279
|
+
* Extract `--agent <name>` from an args array, returning the agent name and
|
|
280
|
+
* the remaining args with the flag pair removed.
|
|
281
|
+
*/
|
|
282
|
+
function extractAgentFlag(args) {
|
|
283
|
+
const idx = args.indexOf("--agent");
|
|
284
|
+
if (idx === -1 || idx + 1 >= args.length)
|
|
285
|
+
return { rest: args };
|
|
286
|
+
const agent = args[idx + 1];
|
|
287
|
+
const rest = [...args.slice(0, idx), ...args.slice(idx + 2)];
|
|
288
|
+
return { agent, rest };
|
|
289
|
+
}
|
|
205
290
|
function usage() {
|
|
206
291
|
return [
|
|
207
292
|
"Usage:",
|
|
208
293
|
" ouro [up]",
|
|
209
|
-
" ouro
|
|
294
|
+
" ouro dev [--repo-path <path>] [--clone [--clone-path <path>]]",
|
|
295
|
+
" ouro stop|down|status|logs|hatch",
|
|
296
|
+
" ouro outlook [--json]",
|
|
297
|
+
" ouro -v|--version",
|
|
298
|
+
" ouro config model --agent <name> <model-name>",
|
|
299
|
+
" ouro config models --agent <name>",
|
|
300
|
+
" ouro auth --agent <name> [--provider <provider>]",
|
|
301
|
+
" ouro auth verify --agent <name> [--provider <provider>]",
|
|
302
|
+
" ouro auth switch --agent <name> --provider <provider>",
|
|
210
303
|
" ouro chat <agent>",
|
|
211
304
|
" ouro msg --to <agent> [--session <id>] [--task <ref>] <message>",
|
|
212
305
|
" ouro poke <agent> --task <task-id>",
|
|
306
|
+
" ouro poke <agent> --habit <name>",
|
|
307
|
+
" ouro habit list [--agent <name>]",
|
|
308
|
+
" ouro habit create [--agent <name>] <name> [--cadence <interval>]",
|
|
213
309
|
" ouro link <agent> --friend <id> --provider <provider> --external-id <external-id>",
|
|
310
|
+
" ouro task board [<status>] [--agent <name>]",
|
|
311
|
+
" ouro task create <title> [--type <type>] [--agent <name>]",
|
|
312
|
+
" ouro task update <id> <status> [--agent <name>]",
|
|
313
|
+
" ouro task show <id> [--agent <name>]",
|
|
314
|
+
" ouro task fix [--safe|--all] [<id> [--option <N>]] [--agent <name>]",
|
|
315
|
+
" ouro task actionable|deps|sessions [--agent <name>]",
|
|
316
|
+
" ouro reminder create <title> --body <body> [--at <iso>] [--cadence <interval>] [--category <category>] [--agent <name>]",
|
|
317
|
+
" ouro friend list [--agent <name>]",
|
|
318
|
+
" ouro friend show <id> [--agent <name>]",
|
|
319
|
+
" ouro friend create --name <name> [--trust <level>] [--agent <name>]",
|
|
320
|
+
" ouro friend update <id> --trust <level> [--agent <name>]",
|
|
321
|
+
" ouro thoughts [--last <n>] [--json] [--follow] [--agent <name>]",
|
|
322
|
+
" ouro inner [--agent <name>]",
|
|
323
|
+
" ouro friend link <agent> --friend <id> --provider <p> --external-id <eid>",
|
|
324
|
+
" ouro friend unlink <agent> --friend <id> --provider <p> --external-id <eid>",
|
|
325
|
+
" ouro whoami [--agent <name>]",
|
|
326
|
+
" ouro session list [--agent <name>]",
|
|
327
|
+
" ouro mcp list",
|
|
328
|
+
" ouro mcp call <server> <tool> [--args '{...}']",
|
|
329
|
+
" ouro rollback [<version>]",
|
|
330
|
+
" ouro versions",
|
|
214
331
|
].join("\n");
|
|
215
332
|
}
|
|
333
|
+
function formatVersionOutput() {
|
|
334
|
+
const version = (0, runtime_metadata_1.getRuntimeMetadata)().version;
|
|
335
|
+
const mode = (0, runtime_mode_1.detectRuntimeMode)((0, identity_1.getRepoRoot)());
|
|
336
|
+
/* v8 ignore start — cosmetic display toggle; dev mode always true in test env */
|
|
337
|
+
return mode === "dev" ? `${version} (dev)` : version;
|
|
338
|
+
/* v8 ignore stop */
|
|
339
|
+
}
|
|
340
|
+
function buildStoppedStatusPayload(socketPath) {
|
|
341
|
+
const metadata = (0, runtime_metadata_1.getRuntimeMetadata)();
|
|
342
|
+
const repoRoot = (0, identity_1.getRepoRoot)();
|
|
343
|
+
return {
|
|
344
|
+
overview: {
|
|
345
|
+
daemon: "stopped",
|
|
346
|
+
health: "warn",
|
|
347
|
+
socketPath,
|
|
348
|
+
outlookUrl: "unavailable",
|
|
349
|
+
version: metadata.version,
|
|
350
|
+
lastUpdated: metadata.lastUpdated,
|
|
351
|
+
repoRoot: metadata.repoRoot,
|
|
352
|
+
configFingerprint: metadata.configFingerprint,
|
|
353
|
+
workerCount: 0,
|
|
354
|
+
senseCount: 0,
|
|
355
|
+
entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
|
|
356
|
+
mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
|
|
357
|
+
},
|
|
358
|
+
senses: [],
|
|
359
|
+
workers: [],
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
function daemonUnavailableStatusOutput(socketPath, healthFilePath) {
|
|
363
|
+
/* v8 ignore start — tombstone read tested in daemon-status-tombstone.test; branch misreported @preserve */
|
|
364
|
+
const tombstone = (0, daemon_tombstone_1.readDaemonTombstone)();
|
|
365
|
+
const deathLine = tombstone
|
|
366
|
+
? `Last death: ${tombstone.timestamp} -- ${tombstone.reason}: ${tombstone.message}`
|
|
367
|
+
: null;
|
|
368
|
+
/* v8 ignore stop */
|
|
369
|
+
const lines = [
|
|
370
|
+
formatDaemonStatusOutput({
|
|
371
|
+
ok: true,
|
|
372
|
+
summary: "daemon not running",
|
|
373
|
+
data: buildStoppedStatusPayload(socketPath),
|
|
374
|
+
}, "daemon not running"),
|
|
375
|
+
"",
|
|
376
|
+
];
|
|
377
|
+
/* v8 ignore start — tombstone presence requires real daemon crash @preserve */
|
|
378
|
+
if (deathLine) {
|
|
379
|
+
lines.push(deathLine);
|
|
380
|
+
lines.push("");
|
|
381
|
+
/* v8 ignore stop */
|
|
382
|
+
}
|
|
383
|
+
// Read health file for last-known state (best-effort)
|
|
384
|
+
const resolvedHealthPath = healthFilePath ?? (0, daemon_health_1.getDefaultHealthPath)();
|
|
385
|
+
const health = (0, daemon_health_1.readHealth)(resolvedHealthPath);
|
|
386
|
+
if (health) {
|
|
387
|
+
lines.push(`Last known status: ${health.status} (pid ${health.pid}, uptime ${health.uptimeSeconds}s)`);
|
|
388
|
+
if (health.safeMode?.active) {
|
|
389
|
+
lines.push(`SAFE MODE: ${health.safeMode.reason}`);
|
|
390
|
+
}
|
|
391
|
+
if (health.degraded.length > 0) {
|
|
392
|
+
lines.push("");
|
|
393
|
+
lines.push("Degraded:");
|
|
394
|
+
for (const d of health.degraded) {
|
|
395
|
+
lines.push(` ${d.component}: ${d.reason} (since ${d.since})`);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
lines.push("");
|
|
399
|
+
}
|
|
400
|
+
lines.push("daemon not running; run `ouro up`");
|
|
401
|
+
return lines.join("\n");
|
|
402
|
+
}
|
|
403
|
+
function isDaemonUnavailableError(error) {
|
|
404
|
+
const code = typeof error === "object" && error !== null && "code" in error
|
|
405
|
+
? String(error.code ?? "")
|
|
406
|
+
: "";
|
|
407
|
+
return code === "ENOENT" || code === "ECONNREFUSED";
|
|
408
|
+
}
|
|
216
409
|
function parseMessageCommand(args) {
|
|
217
410
|
let to;
|
|
218
411
|
let sessionId;
|
|
@@ -254,17 +447,56 @@ function parsePokeCommand(args) {
|
|
|
254
447
|
if (!agent)
|
|
255
448
|
throw new Error(`Usage\n${usage()}`);
|
|
256
449
|
let taskId;
|
|
450
|
+
let habitName;
|
|
257
451
|
for (let i = 1; i < args.length; i += 1) {
|
|
258
452
|
if (args[i] === "--task") {
|
|
259
453
|
taskId = args[i + 1];
|
|
260
454
|
i += 1;
|
|
261
455
|
}
|
|
456
|
+
if (args[i] === "--habit") {
|
|
457
|
+
habitName = args[i + 1];
|
|
458
|
+
i += 1;
|
|
459
|
+
}
|
|
262
460
|
}
|
|
461
|
+
// --habit takes priority over --task
|
|
462
|
+
if (habitName)
|
|
463
|
+
return { kind: "habit.poke", agent, habitName };
|
|
263
464
|
if (!taskId)
|
|
264
465
|
throw new Error(`Usage\n${usage()}`);
|
|
265
466
|
return { kind: "task.poke", agent, taskId };
|
|
266
467
|
}
|
|
267
|
-
function
|
|
468
|
+
function parseHabitCommand(args) {
|
|
469
|
+
const { agent, rest } = extractAgentFlag(args);
|
|
470
|
+
const sub = rest[0];
|
|
471
|
+
if (sub === "list") {
|
|
472
|
+
return { kind: "habit.list", ...(agent ? { agent } : {}) };
|
|
473
|
+
}
|
|
474
|
+
if (sub === "create") {
|
|
475
|
+
const nameArgs = rest.slice(1);
|
|
476
|
+
let name;
|
|
477
|
+
let cadence;
|
|
478
|
+
const positional = [];
|
|
479
|
+
for (let i = 0; i < nameArgs.length; i++) {
|
|
480
|
+
if (nameArgs[i] === "--cadence" && nameArgs[i + 1]) {
|
|
481
|
+
cadence = nameArgs[++i];
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
/* v8 ignore start -- defensive: --agent already extracted by extractAgentFlag; guard prevents regression if parsing flow changes @preserve */
|
|
485
|
+
if (nameArgs[i] === "--agent" && nameArgs[i + 1]) {
|
|
486
|
+
i++; // skip --agent value (already extracted)
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
489
|
+
/* v8 ignore stop */
|
|
490
|
+
positional.push(nameArgs[i]);
|
|
491
|
+
}
|
|
492
|
+
name = positional[0];
|
|
493
|
+
if (!name)
|
|
494
|
+
throw new Error(`Usage\n${usage()}`);
|
|
495
|
+
return { kind: "habit.create", name, ...(agent ? { agent } : {}), ...(cadence ? { cadence } : {}) };
|
|
496
|
+
}
|
|
497
|
+
throw new Error(`Usage\n${usage()}`);
|
|
498
|
+
}
|
|
499
|
+
function parseLinkCommand(args, kind = "friend.link") {
|
|
268
500
|
const agent = args[0];
|
|
269
501
|
if (!agent)
|
|
270
502
|
throw new Error(`Usage\n${usage()}`);
|
|
@@ -296,7 +528,7 @@ function parseLinkCommand(args) {
|
|
|
296
528
|
throw new Error(`Unknown identity provider '${providerRaw}'. Use aad|local|teams-conversation.`);
|
|
297
529
|
}
|
|
298
530
|
return {
|
|
299
|
-
kind
|
|
531
|
+
kind,
|
|
300
532
|
agent,
|
|
301
533
|
friendId,
|
|
302
534
|
provider: providerRaw,
|
|
@@ -304,7 +536,102 @@ function parseLinkCommand(args) {
|
|
|
304
536
|
};
|
|
305
537
|
}
|
|
306
538
|
function isAgentProvider(value) {
|
|
307
|
-
return value === "azure" || value === "anthropic" || value === "minimax" || value === "openai-codex";
|
|
539
|
+
return value === "azure" || value === "anthropic" || value === "minimax" || value === "openai-codex" || value === "github-copilot";
|
|
540
|
+
}
|
|
541
|
+
/* v8 ignore start -- hasStoredCredentials: per-provider branches tested via auth switch tests @preserve */
|
|
542
|
+
function hasStoredCredentials(provider, providerSecrets) {
|
|
543
|
+
if (provider === "anthropic")
|
|
544
|
+
return !!providerSecrets.setupToken;
|
|
545
|
+
if (provider === "openai-codex")
|
|
546
|
+
return !!providerSecrets.oauthAccessToken;
|
|
547
|
+
if (provider === "github-copilot")
|
|
548
|
+
return !!providerSecrets.githubToken;
|
|
549
|
+
if (provider === "minimax")
|
|
550
|
+
return !!providerSecrets.apiKey;
|
|
551
|
+
// azure
|
|
552
|
+
return !!providerSecrets.endpoint && !!providerSecrets.apiKey;
|
|
553
|
+
}
|
|
554
|
+
/* v8 ignore stop */
|
|
555
|
+
/* v8 ignore start -- verifyProviderCredentials: delegates to pingProvider @preserve */
|
|
556
|
+
async function verifyProviderCredentials(provider, providers) {
|
|
557
|
+
const config = providers[provider];
|
|
558
|
+
if (!config)
|
|
559
|
+
return "not configured";
|
|
560
|
+
try {
|
|
561
|
+
const { pingProvider } = await Promise.resolve().then(() => __importStar(require("../../heart/provider-ping")));
|
|
562
|
+
const result = await pingProvider(provider, config);
|
|
563
|
+
return result.ok ? "ok" : `failed (${result.message})`;
|
|
564
|
+
}
|
|
565
|
+
catch (error) {
|
|
566
|
+
return `failed (${error instanceof Error ? error.message : String(error)})`;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
async function listGithubCopilotModels(baseUrl, token, fetchImpl = fetch) {
|
|
570
|
+
const url = `${baseUrl.replace(/\/+$/, "")}/models`;
|
|
571
|
+
const response = await fetchImpl(url, {
|
|
572
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
573
|
+
});
|
|
574
|
+
if (!response.ok) {
|
|
575
|
+
throw new Error(`model listing failed (HTTP ${response.status})`);
|
|
576
|
+
}
|
|
577
|
+
const body = await response.json();
|
|
578
|
+
/* v8 ignore start -- response shape handling: tested via config-models.test.ts @preserve */
|
|
579
|
+
const items = Array.isArray(body) ? body : (body?.data ?? []);
|
|
580
|
+
return items.map((item) => {
|
|
581
|
+
const rec = item;
|
|
582
|
+
const capabilities = Array.isArray(rec.capabilities)
|
|
583
|
+
? rec.capabilities.filter((c) => typeof c === "string")
|
|
584
|
+
: undefined;
|
|
585
|
+
return {
|
|
586
|
+
id: String(rec.id ?? rec.name ?? ""),
|
|
587
|
+
name: String(rec.name ?? rec.id ?? ""),
|
|
588
|
+
...(capabilities ? { capabilities } : {}),
|
|
589
|
+
};
|
|
590
|
+
});
|
|
591
|
+
/* v8 ignore stop */
|
|
592
|
+
}
|
|
593
|
+
async function pingGithubCopilotModel(baseUrl, token, model, fetchImpl = fetch) {
|
|
594
|
+
const base = baseUrl.replace(/\/+$/, "");
|
|
595
|
+
const isClaude = model.startsWith("claude");
|
|
596
|
+
const url = isClaude ? `${base}/chat/completions` : `${base}/responses`;
|
|
597
|
+
const body = isClaude
|
|
598
|
+
? JSON.stringify({ model, messages: [{ role: "user", content: "ping" }], max_tokens: 1 })
|
|
599
|
+
: JSON.stringify({ model, input: "ping", max_output_tokens: 16 });
|
|
600
|
+
try {
|
|
601
|
+
const response = await fetchImpl(url, {
|
|
602
|
+
method: "POST",
|
|
603
|
+
headers: {
|
|
604
|
+
Authorization: `Bearer ${token}`,
|
|
605
|
+
"Content-Type": "application/json",
|
|
606
|
+
},
|
|
607
|
+
body,
|
|
608
|
+
});
|
|
609
|
+
if (response.ok)
|
|
610
|
+
return { ok: true };
|
|
611
|
+
let detail = `HTTP ${response.status}`;
|
|
612
|
+
try {
|
|
613
|
+
const json = await response.json();
|
|
614
|
+
/* v8 ignore start -- error format parsing: all branches tested via config-models.test.ts @preserve */
|
|
615
|
+
if (typeof json.error === "string")
|
|
616
|
+
detail = json.error;
|
|
617
|
+
else if (typeof json.error === "object" && json.error !== null) {
|
|
618
|
+
const errObj = json.error;
|
|
619
|
+
if (typeof errObj.message === "string")
|
|
620
|
+
detail = errObj.message;
|
|
621
|
+
}
|
|
622
|
+
else if (typeof json.message === "string")
|
|
623
|
+
detail = json.message;
|
|
624
|
+
/* v8 ignore stop */
|
|
625
|
+
}
|
|
626
|
+
catch {
|
|
627
|
+
// response body not JSON — keep HTTP status
|
|
628
|
+
}
|
|
629
|
+
return { ok: false, error: detail };
|
|
630
|
+
}
|
|
631
|
+
catch (err) {
|
|
632
|
+
/* v8 ignore next -- defensive: fetch errors are always Error instances @preserve */
|
|
633
|
+
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
634
|
+
}
|
|
308
635
|
}
|
|
309
636
|
function parseHatchCommand(args) {
|
|
310
637
|
let agentName;
|
|
@@ -361,7 +688,7 @@ function parseHatchCommand(args) {
|
|
|
361
688
|
}
|
|
362
689
|
}
|
|
363
690
|
if (providerRaw && !isAgentProvider(providerRaw)) {
|
|
364
|
-
throw new Error("Unknown provider. Use azure|anthropic|minimax|openai-codex.");
|
|
691
|
+
throw new Error("Unknown provider. Use azure|anthropic|minimax|openai-codex|github-copilot.");
|
|
365
692
|
}
|
|
366
693
|
const provider = providerRaw && isAgentProvider(providerRaw) ? providerRaw : undefined;
|
|
367
694
|
return {
|
|
@@ -373,20 +700,480 @@ function parseHatchCommand(args) {
|
|
|
373
700
|
migrationPath,
|
|
374
701
|
};
|
|
375
702
|
}
|
|
703
|
+
function parseTaskCommand(args) {
|
|
704
|
+
const { agent, rest: cleaned } = extractAgentFlag(args);
|
|
705
|
+
const [sub, ...rest] = cleaned;
|
|
706
|
+
if (!sub)
|
|
707
|
+
throw new Error(`Usage\n${usage()}`);
|
|
708
|
+
if (sub === "board") {
|
|
709
|
+
const status = rest[0];
|
|
710
|
+
return status
|
|
711
|
+
? { kind: "task.board", status, ...(agent ? { agent } : {}) }
|
|
712
|
+
: { kind: "task.board", ...(agent ? { agent } : {}) };
|
|
713
|
+
}
|
|
714
|
+
if (sub === "create") {
|
|
715
|
+
const title = rest[0];
|
|
716
|
+
if (!title)
|
|
717
|
+
throw new Error(`Usage\n${usage()}`);
|
|
718
|
+
let type;
|
|
719
|
+
for (let i = 1; i < rest.length; i++) {
|
|
720
|
+
if (rest[i] === "--type" && rest[i + 1]) {
|
|
721
|
+
type = rest[i + 1];
|
|
722
|
+
i += 1;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
return type
|
|
726
|
+
? { kind: "task.create", title, type, ...(agent ? { agent } : {}) }
|
|
727
|
+
: { kind: "task.create", title, ...(agent ? { agent } : {}) };
|
|
728
|
+
}
|
|
729
|
+
if (sub === "update") {
|
|
730
|
+
const id = rest[0];
|
|
731
|
+
const status = rest[1];
|
|
732
|
+
if (!id || !status)
|
|
733
|
+
throw new Error(`Usage\n${usage()}`);
|
|
734
|
+
return { kind: "task.update", id, status, ...(agent ? { agent } : {}) };
|
|
735
|
+
}
|
|
736
|
+
if (sub === "show") {
|
|
737
|
+
const id = rest[0];
|
|
738
|
+
if (!id)
|
|
739
|
+
throw new Error(`Usage\n${usage()}`);
|
|
740
|
+
return { kind: "task.show", id, ...(agent ? { agent } : {}) };
|
|
741
|
+
}
|
|
742
|
+
if (sub === "actionable")
|
|
743
|
+
return { kind: "task.actionable", ...(agent ? { agent } : {}) };
|
|
744
|
+
if (sub === "deps")
|
|
745
|
+
return { kind: "task.deps", ...(agent ? { agent } : {}) };
|
|
746
|
+
if (sub === "sessions")
|
|
747
|
+
return { kind: "task.sessions", ...(agent ? { agent } : {}) };
|
|
748
|
+
if (sub === "fix") {
|
|
749
|
+
// fix --safe | fix --all | fix <id> [--option N] | fix (dry-run)
|
|
750
|
+
if (rest.length === 0)
|
|
751
|
+
return { kind: "task.fix", mode: "dry-run", ...(agent ? { agent } : {}) };
|
|
752
|
+
const first = rest[0];
|
|
753
|
+
if (first === "--safe" || first === "--all") {
|
|
754
|
+
return { kind: "task.fix", mode: "safe", ...(agent ? { agent } : {}) };
|
|
755
|
+
}
|
|
756
|
+
// first arg is an issue ID (contains a colon, e.g. schema-missing-kind:one-shots/foo.md)
|
|
757
|
+
const issueId = first;
|
|
758
|
+
let option;
|
|
759
|
+
for (let i = 1; i < rest.length; i++) {
|
|
760
|
+
if (rest[i] === "--option" && rest[i + 1]) {
|
|
761
|
+
option = parseInt(rest[i + 1], 10);
|
|
762
|
+
i += 1;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
return {
|
|
766
|
+
kind: "task.fix",
|
|
767
|
+
mode: "single",
|
|
768
|
+
issueId,
|
|
769
|
+
...(option !== undefined ? { option } : {}),
|
|
770
|
+
...(agent ? { agent } : {}),
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
throw new Error(`Usage\n${usage()}`);
|
|
774
|
+
}
|
|
775
|
+
function extractFacingFlag(args) {
|
|
776
|
+
const idx = args.indexOf("--facing");
|
|
777
|
+
if (idx === -1 || idx + 1 >= args.length)
|
|
778
|
+
return { rest: args };
|
|
779
|
+
const value = args[idx + 1];
|
|
780
|
+
if (value !== "human" && value !== "agent") {
|
|
781
|
+
throw new Error(`--facing must be 'human' or 'agent'`);
|
|
782
|
+
}
|
|
783
|
+
const rest = [...args.slice(0, idx), ...args.slice(idx + 2)];
|
|
784
|
+
return { facing: value, rest };
|
|
785
|
+
}
|
|
786
|
+
function parseAuthCommand(args) {
|
|
787
|
+
const first = args[0];
|
|
788
|
+
// Support both positional (`auth switch`) and flag (`auth --switch`) forms
|
|
789
|
+
if (first === "verify" || first === "switch" || first === "--verify" || first === "--switch") {
|
|
790
|
+
const subcommand = first.replace(/^--/, "");
|
|
791
|
+
const { agent, rest: afterAgent } = extractAgentFlag(args.slice(1));
|
|
792
|
+
const { facing, rest } = extractFacingFlag(afterAgent);
|
|
793
|
+
let provider;
|
|
794
|
+
/* v8 ignore start -- provider flag parsing: branches tested via CLI parsing tests @preserve */
|
|
795
|
+
for (let i = 0; i < rest.length; i += 1) {
|
|
796
|
+
if (rest[i] === "--provider") {
|
|
797
|
+
const value = rest[i + 1];
|
|
798
|
+
if (!isAgentProvider(value))
|
|
799
|
+
throw new Error(`Usage\n${usage()}`);
|
|
800
|
+
provider = value;
|
|
801
|
+
i += 1;
|
|
802
|
+
continue;
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
/* v8 ignore stop */
|
|
806
|
+
/* v8 ignore next -- defensive: agent always provided in tests @preserve */
|
|
807
|
+
if (!agent)
|
|
808
|
+
throw new Error(`Usage\n${usage()}`);
|
|
809
|
+
if (subcommand === "switch") {
|
|
810
|
+
if (!provider)
|
|
811
|
+
throw new Error(`auth switch requires --provider.\n${usage()}`);
|
|
812
|
+
return facing ? { kind: "auth.switch", agent, provider, facing } : { kind: "auth.switch", agent, provider };
|
|
813
|
+
}
|
|
814
|
+
return provider ? { kind: "auth.verify", agent, provider } : { kind: "auth.verify", agent };
|
|
815
|
+
}
|
|
816
|
+
const { agent, rest } = extractAgentFlag(args);
|
|
817
|
+
let provider;
|
|
818
|
+
for (let i = 0; i < rest.length; i += 1) {
|
|
819
|
+
if (rest[i] === "--provider") {
|
|
820
|
+
const value = rest[i + 1];
|
|
821
|
+
if (!isAgentProvider(value))
|
|
822
|
+
throw new Error(`Usage\n${usage()}`);
|
|
823
|
+
provider = value;
|
|
824
|
+
i += 1;
|
|
825
|
+
continue;
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
if (!agent) {
|
|
829
|
+
throw new Error([
|
|
830
|
+
"Usage:",
|
|
831
|
+
" ouro auth --agent <name> [--provider <provider>] Set up credentials",
|
|
832
|
+
" ouro auth verify --agent <name> [--provider <p>] Verify credentials work",
|
|
833
|
+
" ouro auth switch --agent <name> --provider <p> Switch active provider",
|
|
834
|
+
].join("\n"));
|
|
835
|
+
}
|
|
836
|
+
return provider ? { kind: "auth.run", agent, provider } : { kind: "auth.run", agent };
|
|
837
|
+
}
|
|
838
|
+
function parseReminderCommand(args) {
|
|
839
|
+
const { agent, rest: cleaned } = extractAgentFlag(args);
|
|
840
|
+
const [sub, ...rest] = cleaned;
|
|
841
|
+
if (!sub)
|
|
842
|
+
throw new Error(`Usage\n${usage()}`);
|
|
843
|
+
if (sub === "create") {
|
|
844
|
+
const title = rest[0];
|
|
845
|
+
if (!title)
|
|
846
|
+
throw new Error(`Usage\n${usage()}`);
|
|
847
|
+
let body;
|
|
848
|
+
let scheduledAt;
|
|
849
|
+
let cadence;
|
|
850
|
+
let category;
|
|
851
|
+
let requester;
|
|
852
|
+
for (let i = 1; i < rest.length; i++) {
|
|
853
|
+
if (rest[i] === "--body" && rest[i + 1]) {
|
|
854
|
+
body = rest[i + 1];
|
|
855
|
+
i += 1;
|
|
856
|
+
}
|
|
857
|
+
else if (rest[i] === "--at" && rest[i + 1]) {
|
|
858
|
+
scheduledAt = rest[i + 1];
|
|
859
|
+
i += 1;
|
|
860
|
+
}
|
|
861
|
+
else if (rest[i] === "--cadence" && rest[i + 1]) {
|
|
862
|
+
cadence = rest[i + 1];
|
|
863
|
+
i += 1;
|
|
864
|
+
}
|
|
865
|
+
else if (rest[i] === "--category" && rest[i + 1]) {
|
|
866
|
+
category = rest[i + 1];
|
|
867
|
+
i += 1;
|
|
868
|
+
}
|
|
869
|
+
else if (rest[i] === "--requester" && rest[i + 1]) {
|
|
870
|
+
requester = rest[i + 1];
|
|
871
|
+
i += 1;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
if (!body)
|
|
875
|
+
throw new Error(`Usage\n${usage()}`);
|
|
876
|
+
if (!scheduledAt && !cadence)
|
|
877
|
+
throw new Error(`Usage\n${usage()}`);
|
|
878
|
+
return {
|
|
879
|
+
kind: "reminder.create",
|
|
880
|
+
title,
|
|
881
|
+
body,
|
|
882
|
+
...(scheduledAt ? { scheduledAt } : {}),
|
|
883
|
+
...(cadence ? { cadence } : {}),
|
|
884
|
+
...(category ? { category } : {}),
|
|
885
|
+
...(requester ? { requester } : {}),
|
|
886
|
+
...(agent ? { agent } : {}),
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
throw new Error(`Usage\n${usage()}`);
|
|
890
|
+
}
|
|
891
|
+
function parseSessionCommand(args) {
|
|
892
|
+
const { agent, rest: cleaned } = extractAgentFlag(args);
|
|
893
|
+
const [sub] = cleaned;
|
|
894
|
+
if (!sub)
|
|
895
|
+
throw new Error(`Usage\n${usage()}`);
|
|
896
|
+
if (sub === "list")
|
|
897
|
+
return { kind: "session.list", ...(agent ? { agent } : {}) };
|
|
898
|
+
throw new Error(`Usage\n${usage()}`);
|
|
899
|
+
}
|
|
900
|
+
function parseAttentionCommand(args) {
|
|
901
|
+
const { agent, rest: cleaned } = extractAgentFlag(args);
|
|
902
|
+
const sub = cleaned[0];
|
|
903
|
+
if (sub === "show" && cleaned[1]) {
|
|
904
|
+
return { kind: "attention.show", id: cleaned[1], ...(agent ? { agent } : {}) };
|
|
905
|
+
}
|
|
906
|
+
if (sub === "history") {
|
|
907
|
+
return { kind: "attention.history", ...(agent ? { agent } : {}) };
|
|
908
|
+
}
|
|
909
|
+
return { kind: "attention.list", ...(agent ? { agent } : {}) };
|
|
910
|
+
}
|
|
911
|
+
function parseThoughtsCommand(args) {
|
|
912
|
+
const { agent, rest: cleaned } = extractAgentFlag(args);
|
|
913
|
+
let last;
|
|
914
|
+
let json = false;
|
|
915
|
+
let follow = false;
|
|
916
|
+
for (let i = 0; i < cleaned.length; i++) {
|
|
917
|
+
if (cleaned[i] === "--last" && i + 1 < cleaned.length) {
|
|
918
|
+
last = Number.parseInt(cleaned[i + 1], 10);
|
|
919
|
+
i++;
|
|
920
|
+
}
|
|
921
|
+
if (cleaned[i] === "--json")
|
|
922
|
+
json = true;
|
|
923
|
+
if (cleaned[i] === "--follow" || cleaned[i] === "-f")
|
|
924
|
+
follow = true;
|
|
925
|
+
}
|
|
926
|
+
return { kind: "thoughts", ...(agent ? { agent } : {}), ...(last ? { last } : {}), ...(json ? { json } : {}), ...(follow ? { follow } : {}) };
|
|
927
|
+
}
|
|
928
|
+
function parseFriendCommand(args) {
|
|
929
|
+
const { agent, rest: cleaned } = extractAgentFlag(args);
|
|
930
|
+
const [sub, ...rest] = cleaned;
|
|
931
|
+
if (!sub)
|
|
932
|
+
throw new Error(`Usage\n${usage()}`);
|
|
933
|
+
if (sub === "list")
|
|
934
|
+
return { kind: "friend.list", ...(agent ? { agent } : {}) };
|
|
935
|
+
if (sub === "show") {
|
|
936
|
+
const friendId = rest[0];
|
|
937
|
+
if (!friendId)
|
|
938
|
+
throw new Error(`Usage\n${usage()}`);
|
|
939
|
+
return { kind: "friend.show", friendId, ...(agent ? { agent } : {}) };
|
|
940
|
+
}
|
|
941
|
+
if (sub === "create") {
|
|
942
|
+
let name;
|
|
943
|
+
let trustLevel;
|
|
944
|
+
for (let i = 0; i < rest.length; i++) {
|
|
945
|
+
if (rest[i] === "--name" && rest[i + 1]) {
|
|
946
|
+
name = rest[i + 1];
|
|
947
|
+
i += 1;
|
|
948
|
+
}
|
|
949
|
+
else if (rest[i] === "--trust" && rest[i + 1]) {
|
|
950
|
+
trustLevel = rest[i + 1];
|
|
951
|
+
i += 1;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
if (!name)
|
|
955
|
+
throw new Error(`Usage\n${usage()}`);
|
|
956
|
+
return {
|
|
957
|
+
kind: "friend.create",
|
|
958
|
+
name,
|
|
959
|
+
...(trustLevel ? { trustLevel } : {}),
|
|
960
|
+
...(agent ? { agent } : {}),
|
|
961
|
+
};
|
|
962
|
+
}
|
|
963
|
+
if (sub === "update") {
|
|
964
|
+
const friendId = rest[0];
|
|
965
|
+
if (!friendId)
|
|
966
|
+
throw new Error(`Usage: ouro friend update <id> --trust <level>`);
|
|
967
|
+
let trustLevel;
|
|
968
|
+
/* v8 ignore start -- flag parsing loop: tested via CLI parsing tests @preserve */
|
|
969
|
+
for (let i = 1; i < rest.length; i++) {
|
|
970
|
+
if (rest[i] === "--trust" && rest[i + 1]) {
|
|
971
|
+
trustLevel = rest[i + 1];
|
|
972
|
+
i += 1;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
/* v8 ignore stop */
|
|
976
|
+
const VALID_TRUST_LEVELS = new Set(["stranger", "acquaintance", "friend", "family"]);
|
|
977
|
+
if (!trustLevel || !VALID_TRUST_LEVELS.has(trustLevel)) {
|
|
978
|
+
throw new Error(`Usage: ouro friend update <id> --trust <stranger|acquaintance|friend|family>`);
|
|
979
|
+
}
|
|
980
|
+
return {
|
|
981
|
+
kind: "friend.update",
|
|
982
|
+
friendId,
|
|
983
|
+
trustLevel: trustLevel,
|
|
984
|
+
...(agent ? { agent } : {}),
|
|
985
|
+
};
|
|
986
|
+
}
|
|
987
|
+
if (sub === "link")
|
|
988
|
+
return parseLinkCommand(rest, "friend.link");
|
|
989
|
+
if (sub === "unlink")
|
|
990
|
+
return parseLinkCommand(rest, "friend.unlink");
|
|
991
|
+
throw new Error(`Usage\n${usage()}`);
|
|
992
|
+
}
|
|
993
|
+
function parseConfigCommand(args) {
|
|
994
|
+
const { agent, rest: afterAgent } = extractAgentFlag(args);
|
|
995
|
+
const { facing, rest: cleaned } = extractFacingFlag(afterAgent);
|
|
996
|
+
const [sub, ...rest] = cleaned;
|
|
997
|
+
if (!sub)
|
|
998
|
+
throw new Error(`Usage\n${usage()}`);
|
|
999
|
+
if (sub === "model") {
|
|
1000
|
+
if (!agent)
|
|
1001
|
+
throw new Error("--agent is required for config model");
|
|
1002
|
+
const modelName = rest[0];
|
|
1003
|
+
if (!modelName)
|
|
1004
|
+
throw new Error(`Usage: ouro config model --agent <name> <model-name>`);
|
|
1005
|
+
return facing ? { kind: "config.model", agent, modelName, facing } : { kind: "config.model", agent, modelName };
|
|
1006
|
+
}
|
|
1007
|
+
if (sub === "models") {
|
|
1008
|
+
if (!agent)
|
|
1009
|
+
throw new Error("--agent is required for config models");
|
|
1010
|
+
return { kind: "config.models", agent };
|
|
1011
|
+
}
|
|
1012
|
+
throw new Error(`Usage\n${usage()}`);
|
|
1013
|
+
}
|
|
1014
|
+
function parseMcpCommand(args) {
|
|
1015
|
+
const [sub, ...rest] = args;
|
|
1016
|
+
if (!sub)
|
|
1017
|
+
throw new Error(`Usage\n${usage()}`);
|
|
1018
|
+
if (sub === "list")
|
|
1019
|
+
return { kind: "mcp.list" };
|
|
1020
|
+
if (sub === "call") {
|
|
1021
|
+
const server = rest[0];
|
|
1022
|
+
const tool = rest[1];
|
|
1023
|
+
if (!server || !tool)
|
|
1024
|
+
throw new Error(`Usage\n${usage()}`);
|
|
1025
|
+
const argsIdx = rest.indexOf("--args");
|
|
1026
|
+
const mcpArgs = argsIdx !== -1 && rest[argsIdx + 1] ? rest[argsIdx + 1] : undefined;
|
|
1027
|
+
return { kind: "mcp.call", server, tool, ...(mcpArgs ? { args: mcpArgs } : {}) };
|
|
1028
|
+
}
|
|
1029
|
+
throw new Error(`Usage\n${usage()}`);
|
|
1030
|
+
}
|
|
1031
|
+
function parseMcpServeCommand(args) {
|
|
1032
|
+
let agent;
|
|
1033
|
+
let friendId;
|
|
1034
|
+
let socketOverride;
|
|
1035
|
+
for (let i = 0; i < args.length; i++) {
|
|
1036
|
+
if (args[i] === "--agent" && args[i + 1]) {
|
|
1037
|
+
agent = args[++i];
|
|
1038
|
+
continue;
|
|
1039
|
+
}
|
|
1040
|
+
if (args[i] === "--friend" && args[i + 1]) {
|
|
1041
|
+
friendId = args[++i];
|
|
1042
|
+
continue;
|
|
1043
|
+
}
|
|
1044
|
+
if (args[i] === "--socket" && args[i + 1]) {
|
|
1045
|
+
socketOverride = args[++i];
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
if (!agent)
|
|
1050
|
+
throw new Error("mcp-serve requires --agent <name>");
|
|
1051
|
+
return { kind: "mcp-serve", agent, ...(friendId ? { friendId } : {}), ...(socketOverride ? { socketOverride } : {}) };
|
|
1052
|
+
}
|
|
1053
|
+
function parseSetupCommand(args) {
|
|
1054
|
+
let tool;
|
|
1055
|
+
let agent;
|
|
1056
|
+
for (let i = 0; i < args.length; i++) {
|
|
1057
|
+
if (args[i] === "--tool" && args[i + 1]) {
|
|
1058
|
+
tool = args[++i];
|
|
1059
|
+
continue;
|
|
1060
|
+
}
|
|
1061
|
+
if (args[i] === "--agent" && args[i + 1]) {
|
|
1062
|
+
agent = args[++i];
|
|
1063
|
+
continue;
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
if (!tool)
|
|
1067
|
+
throw new Error("setup requires --tool (claude-code | codex)");
|
|
1068
|
+
if (tool !== "claude-code" && tool !== "codex")
|
|
1069
|
+
throw new Error(`Unknown tool: ${tool}. Supported: claude-code, codex`);
|
|
1070
|
+
if (!agent)
|
|
1071
|
+
throw new Error("setup requires --agent <name>");
|
|
1072
|
+
return { kind: "setup", tool, agent };
|
|
1073
|
+
}
|
|
376
1074
|
function parseOuroCommand(args) {
|
|
377
1075
|
const [head, second] = args;
|
|
378
1076
|
if (!head)
|
|
379
1077
|
return { kind: "daemon.up" };
|
|
1078
|
+
if (head === "--agent" && second) {
|
|
1079
|
+
return parseOuroCommand(args.slice(2));
|
|
1080
|
+
}
|
|
1081
|
+
if (head === "hook") {
|
|
1082
|
+
const hookArgs = args.slice(1);
|
|
1083
|
+
let event;
|
|
1084
|
+
let hookAgent;
|
|
1085
|
+
for (let i = 0; i < hookArgs.length; i++) {
|
|
1086
|
+
if (hookArgs[i] === "--agent" && hookArgs[i + 1]) {
|
|
1087
|
+
hookAgent = hookArgs[++i];
|
|
1088
|
+
continue;
|
|
1089
|
+
}
|
|
1090
|
+
/* v8 ignore start -- false branch: extra positional args after event are ignored */
|
|
1091
|
+
if (!event) {
|
|
1092
|
+
event = hookArgs[i];
|
|
1093
|
+
}
|
|
1094
|
+
/* v8 ignore stop */
|
|
1095
|
+
}
|
|
1096
|
+
if (!event)
|
|
1097
|
+
throw new Error("hook requires an event name (session-start, stop, post-tool-use)");
|
|
1098
|
+
if (!hookAgent)
|
|
1099
|
+
throw new Error("hook requires --agent <name>");
|
|
1100
|
+
return { kind: "hook", event, agent: hookAgent };
|
|
1101
|
+
}
|
|
380
1102
|
if (head === "up")
|
|
381
1103
|
return { kind: "daemon.up" };
|
|
382
|
-
if (head === "
|
|
1104
|
+
if (head === "dev") {
|
|
1105
|
+
const devArgs = args.slice(1);
|
|
1106
|
+
let repoPath;
|
|
1107
|
+
let clone = false;
|
|
1108
|
+
let clonePath;
|
|
1109
|
+
for (let i = 0; i < devArgs.length; i++) {
|
|
1110
|
+
if (devArgs[i] === "--repo-path" && devArgs[i + 1]) {
|
|
1111
|
+
repoPath = devArgs[++i];
|
|
1112
|
+
continue;
|
|
1113
|
+
}
|
|
1114
|
+
if (devArgs[i] === "--clone") {
|
|
1115
|
+
clone = true;
|
|
1116
|
+
continue;
|
|
1117
|
+
}
|
|
1118
|
+
if (devArgs[i] === "--clone-path" && devArgs[i + 1]) {
|
|
1119
|
+
clonePath = devArgs[++i];
|
|
1120
|
+
continue;
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
return { kind: "daemon.dev", repoPath, clone, clonePath };
|
|
1124
|
+
}
|
|
1125
|
+
if (head === "rollback")
|
|
1126
|
+
return { kind: "rollback", ...(second ? { version: second } : {}) };
|
|
1127
|
+
if (head === "versions")
|
|
1128
|
+
return { kind: "versions" };
|
|
1129
|
+
if (head === "stop" || head === "down")
|
|
383
1130
|
return { kind: "daemon.stop" };
|
|
384
1131
|
if (head === "status")
|
|
385
1132
|
return { kind: "daemon.status" };
|
|
386
1133
|
if (head === "logs")
|
|
387
1134
|
return { kind: "daemon.logs" };
|
|
1135
|
+
if (head === "outlook")
|
|
1136
|
+
return { kind: "outlook", ...(args.includes("--json") ? { json: true } : {}) };
|
|
388
1137
|
if (head === "hatch")
|
|
389
1138
|
return parseHatchCommand(args.slice(1));
|
|
1139
|
+
if (head === "auth")
|
|
1140
|
+
return parseAuthCommand(args.slice(1));
|
|
1141
|
+
if (head === "task")
|
|
1142
|
+
return parseTaskCommand(args.slice(1));
|
|
1143
|
+
if (head === "reminder")
|
|
1144
|
+
return parseReminderCommand(args.slice(1));
|
|
1145
|
+
if (head === "habit")
|
|
1146
|
+
return parseHabitCommand(args.slice(1));
|
|
1147
|
+
if (head === "friend")
|
|
1148
|
+
return parseFriendCommand(args.slice(1));
|
|
1149
|
+
if (head === "config")
|
|
1150
|
+
return parseConfigCommand(args.slice(1));
|
|
1151
|
+
if (head === "mcp")
|
|
1152
|
+
return parseMcpCommand(args.slice(1));
|
|
1153
|
+
if (head === "whoami") {
|
|
1154
|
+
const { agent } = extractAgentFlag(args.slice(1));
|
|
1155
|
+
return { kind: "whoami", ...(agent ? { agent } : {}) };
|
|
1156
|
+
}
|
|
1157
|
+
if (head === "session")
|
|
1158
|
+
return parseSessionCommand(args.slice(1));
|
|
1159
|
+
if (head === "changelog") {
|
|
1160
|
+
const sliced = args.slice(1);
|
|
1161
|
+
const { agent, rest: remaining } = extractAgentFlag(sliced);
|
|
1162
|
+
let from;
|
|
1163
|
+
const fromIdx = remaining.indexOf("--from");
|
|
1164
|
+
if (fromIdx !== -1 && remaining[fromIdx + 1]) {
|
|
1165
|
+
from = remaining[fromIdx + 1];
|
|
1166
|
+
}
|
|
1167
|
+
return { kind: "changelog", ...(from ? { from } : {}), ...(agent ? { agent } : {}) };
|
|
1168
|
+
}
|
|
1169
|
+
if (head === "thoughts")
|
|
1170
|
+
return parseThoughtsCommand(args.slice(1));
|
|
1171
|
+
if (head === "attention")
|
|
1172
|
+
return parseAttentionCommand(args.slice(1));
|
|
1173
|
+
if (head === "inner") {
|
|
1174
|
+
const { agent } = extractAgentFlag(args.slice(1));
|
|
1175
|
+
return { kind: "inner.status", ...(agent ? { agent } : {}) };
|
|
1176
|
+
}
|
|
390
1177
|
if (head === "chat") {
|
|
391
1178
|
if (!second)
|
|
392
1179
|
throw new Error(`Usage\n${usage()}`);
|
|
@@ -398,40 +1185,12 @@ function parseOuroCommand(args) {
|
|
|
398
1185
|
return parsePokeCommand(args.slice(1));
|
|
399
1186
|
if (head === "link")
|
|
400
1187
|
return parseLinkCommand(args.slice(1));
|
|
1188
|
+
if (head === "mcp-serve")
|
|
1189
|
+
return parseMcpServeCommand(args.slice(1));
|
|
1190
|
+
if (head === "setup")
|
|
1191
|
+
return parseSetupCommand(args.slice(1));
|
|
401
1192
|
throw new Error(`Unknown command '${args.join(" ")}'.\n${usage()}`);
|
|
402
1193
|
}
|
|
403
|
-
function defaultSendCommand(socketPath, command) {
|
|
404
|
-
return new Promise((resolve, reject) => {
|
|
405
|
-
const client = net.createConnection(socketPath);
|
|
406
|
-
let raw = "";
|
|
407
|
-
client.on("connect", () => {
|
|
408
|
-
client.write(JSON.stringify(command));
|
|
409
|
-
client.end();
|
|
410
|
-
});
|
|
411
|
-
client.on("data", (chunk) => {
|
|
412
|
-
raw += chunk.toString("utf-8");
|
|
413
|
-
});
|
|
414
|
-
client.on("error", reject);
|
|
415
|
-
client.on("end", () => {
|
|
416
|
-
const trimmed = raw.trim();
|
|
417
|
-
if (trimmed.length === 0 && command.kind === "daemon.stop") {
|
|
418
|
-
resolve({ ok: true, message: "daemon stopped" });
|
|
419
|
-
return;
|
|
420
|
-
}
|
|
421
|
-
if (trimmed.length === 0) {
|
|
422
|
-
reject(new Error("Daemon returned empty response."));
|
|
423
|
-
return;
|
|
424
|
-
}
|
|
425
|
-
try {
|
|
426
|
-
const parsed = JSON.parse(trimmed);
|
|
427
|
-
resolve(parsed);
|
|
428
|
-
}
|
|
429
|
-
catch (error) {
|
|
430
|
-
reject(error);
|
|
431
|
-
}
|
|
432
|
-
});
|
|
433
|
-
});
|
|
434
|
-
}
|
|
435
1194
|
function defaultStartDaemonProcess(socketPath) {
|
|
436
1195
|
const entry = path.join((0, identity_1.getRepoRoot)(), "dist", "heart", "daemon", "daemon-entry.js");
|
|
437
1196
|
const child = (0, child_process_1.spawn)("node", [entry, "--socket", socketPath], {
|
|
@@ -445,45 +1204,32 @@ function defaultWriteStdout(text) {
|
|
|
445
1204
|
// eslint-disable-next-line no-console -- terminal UX: CLI command output
|
|
446
1205
|
console.log(text);
|
|
447
1206
|
}
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
1207
|
+
/**
|
|
1208
|
+
* Read the runtimeVersion from the first .ouro bundle's bundle-meta.json.
|
|
1209
|
+
* Returns undefined if none found or unreadable.
|
|
1210
|
+
*/
|
|
1211
|
+
function readFirstBundleMetaVersion(bundlesRoot) {
|
|
1212
|
+
try {
|
|
1213
|
+
if (!fs.existsSync(bundlesRoot))
|
|
1214
|
+
return undefined;
|
|
1215
|
+
const entries = fs.readdirSync(bundlesRoot, { withFileTypes: true });
|
|
1216
|
+
for (const entry of entries) {
|
|
1217
|
+
/* v8 ignore next -- skip non-.ouro dirs: tested via version-detect tests @preserve */
|
|
1218
|
+
if (!entry.isDirectory() || !entry.name.endsWith(".ouro"))
|
|
1219
|
+
continue;
|
|
1220
|
+
const metaPath = path.join(bundlesRoot, entry.name, "bundle-meta.json");
|
|
1221
|
+
if (!fs.existsSync(metaPath))
|
|
1222
|
+
continue;
|
|
1223
|
+
const raw = fs.readFileSync(metaPath, "utf-8");
|
|
1224
|
+
const meta = JSON.parse(raw);
|
|
1225
|
+
if (meta.runtimeVersion)
|
|
1226
|
+
return meta.runtimeVersion;
|
|
464
1227
|
}
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
raw += chunk.toString("utf-8");
|
|
471
|
-
});
|
|
472
|
-
client.on("error", () => finalize(false));
|
|
473
|
-
client.on("end", () => {
|
|
474
|
-
if (raw.trim().length === 0) {
|
|
475
|
-
finalize(false);
|
|
476
|
-
return;
|
|
477
|
-
}
|
|
478
|
-
try {
|
|
479
|
-
JSON.parse(raw);
|
|
480
|
-
finalize(true);
|
|
481
|
-
}
|
|
482
|
-
catch {
|
|
483
|
-
finalize(false);
|
|
484
|
-
}
|
|
485
|
-
});
|
|
486
|
-
});
|
|
1228
|
+
}
|
|
1229
|
+
catch {
|
|
1230
|
+
// Best effort — return undefined on any error
|
|
1231
|
+
}
|
|
1232
|
+
return undefined;
|
|
487
1233
|
}
|
|
488
1234
|
function defaultCleanupStaleSocket(socketPath) {
|
|
489
1235
|
if (fs.existsSync(socketPath)) {
|
|
@@ -519,9 +1265,38 @@ function defaultFallbackPendingMessage(command) {
|
|
|
519
1265
|
});
|
|
520
1266
|
return pendingPath;
|
|
521
1267
|
}
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
1268
|
+
function defaultEnsureDaemonBootPersistence(socketPath) {
|
|
1269
|
+
if (process.platform !== "darwin") {
|
|
1270
|
+
return;
|
|
1271
|
+
}
|
|
1272
|
+
const homeDir = os.homedir();
|
|
1273
|
+
const launchdDeps = {
|
|
1274
|
+
exec: (cmd) => { (0, child_process_1.execSync)(cmd, { stdio: "ignore" }); },
|
|
1275
|
+
writeFile: (filePath, content) => fs.writeFileSync(filePath, content, "utf-8"),
|
|
1276
|
+
removeFile: (filePath) => fs.rmSync(filePath, { force: true }),
|
|
1277
|
+
existsFile: (filePath) => fs.existsSync(filePath),
|
|
1278
|
+
mkdirp: (dir) => fs.mkdirSync(dir, { recursive: true }),
|
|
1279
|
+
homeDir,
|
|
1280
|
+
userUid: process.getuid?.() ?? 0,
|
|
1281
|
+
};
|
|
1282
|
+
const entryPath = path.join((0, identity_1.getRepoRoot)(), "dist", "heart", "daemon", "daemon-entry.js");
|
|
1283
|
+
/* 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 */
|
|
1284
|
+
if (!fs.existsSync(entryPath)) {
|
|
1285
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1286
|
+
level: "warn",
|
|
1287
|
+
component: "daemon",
|
|
1288
|
+
event: "daemon.entry_path_missing",
|
|
1289
|
+
message: "entryPath does not exist on disk — plist may point to a stale location. Run 'ouro daemon install' from the correct location.",
|
|
1290
|
+
meta: { entryPath },
|
|
1291
|
+
});
|
|
1292
|
+
}
|
|
1293
|
+
const logDir = (0, identity_1.getAgentDaemonLogsDir)();
|
|
1294
|
+
(0, launchd_1.installLaunchAgent)(launchdDeps, {
|
|
1295
|
+
nodePath: process.execPath,
|
|
1296
|
+
entryPath,
|
|
1297
|
+
socketPath,
|
|
1298
|
+
logDir,
|
|
1299
|
+
envPath: process.env.PATH,
|
|
525
1300
|
});
|
|
526
1301
|
}
|
|
527
1302
|
async function defaultPromptInput(question) {
|
|
@@ -539,62 +1314,11 @@ async function defaultPromptInput(question) {
|
|
|
539
1314
|
}
|
|
540
1315
|
}
|
|
541
1316
|
function defaultListDiscoveredAgents() {
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
}
|
|
547
|
-
catch {
|
|
548
|
-
return [];
|
|
549
|
-
}
|
|
550
|
-
const discovered = [];
|
|
551
|
-
for (const entry of entries) {
|
|
552
|
-
if (!entry.isDirectory() || !entry.name.endsWith(".ouro"))
|
|
553
|
-
continue;
|
|
554
|
-
const agentName = entry.name.slice(0, -5);
|
|
555
|
-
const configPath = path.join(bundlesRoot, entry.name, "agent.json");
|
|
556
|
-
let enabled = true;
|
|
557
|
-
try {
|
|
558
|
-
const raw = fs.readFileSync(configPath, "utf-8");
|
|
559
|
-
const parsed = JSON.parse(raw);
|
|
560
|
-
if (typeof parsed.enabled === "boolean") {
|
|
561
|
-
enabled = parsed.enabled;
|
|
562
|
-
}
|
|
563
|
-
}
|
|
564
|
-
catch {
|
|
565
|
-
continue;
|
|
566
|
-
}
|
|
567
|
-
if (enabled) {
|
|
568
|
-
discovered.push(agentName);
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
return discovered.sort((left, right) => left.localeCompare(right));
|
|
572
|
-
}
|
|
573
|
-
async function defaultLinkFriendIdentity(command) {
|
|
574
|
-
const fp = path.join((0, identity_1.getAgentBundlesRoot)(), `${command.agent}.ouro`, "friends");
|
|
575
|
-
const friendStore = new store_file_1.FileFriendStore(fp);
|
|
576
|
-
const current = await friendStore.get(command.friendId);
|
|
577
|
-
if (!current) {
|
|
578
|
-
return `friend not found: ${command.friendId}`;
|
|
579
|
-
}
|
|
580
|
-
const alreadyLinked = current.externalIds.some((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
|
|
581
|
-
if (alreadyLinked) {
|
|
582
|
-
return `identity already linked: ${command.provider}:${command.externalId}`;
|
|
583
|
-
}
|
|
584
|
-
const now = new Date().toISOString();
|
|
585
|
-
await friendStore.put(command.friendId, {
|
|
586
|
-
...current,
|
|
587
|
-
externalIds: [
|
|
588
|
-
...current.externalIds,
|
|
589
|
-
{
|
|
590
|
-
provider: command.provider,
|
|
591
|
-
externalId: command.externalId,
|
|
592
|
-
linkedAt: now,
|
|
593
|
-
},
|
|
594
|
-
],
|
|
595
|
-
updatedAt: now,
|
|
1317
|
+
return (0, agent_discovery_1.listEnabledBundleAgents)({
|
|
1318
|
+
bundlesRoot: (0, identity_1.getAgentBundlesRoot)(),
|
|
1319
|
+
readdirSync: fs.readdirSync,
|
|
1320
|
+
readFileSync: fs.readFileSync,
|
|
596
1321
|
});
|
|
597
|
-
return `linked ${command.provider}:${command.externalId} to ${command.friendId}`;
|
|
598
1322
|
}
|
|
599
1323
|
function discoverExistingCredentials(secretsRoot) {
|
|
600
1324
|
const found = [];
|
|
@@ -627,16 +1351,16 @@ function discoverExistingCredentials(secretsRoot) {
|
|
|
627
1351
|
continue;
|
|
628
1352
|
for (const [provName, provConfig] of Object.entries(parsed.providers)) {
|
|
629
1353
|
if (provName === "anthropic" && provConfig.setupToken) {
|
|
630
|
-
found.push({ agentName: entry.name, provider: "anthropic", credentials: { setupToken: provConfig.setupToken } });
|
|
1354
|
+
found.push({ agentName: entry.name, provider: "anthropic", credentials: { setupToken: provConfig.setupToken }, providerConfig: { ...provConfig } });
|
|
631
1355
|
}
|
|
632
1356
|
else if (provName === "openai-codex" && provConfig.oauthAccessToken) {
|
|
633
|
-
found.push({ agentName: entry.name, provider: "openai-codex", credentials: { oauthAccessToken: provConfig.oauthAccessToken } });
|
|
1357
|
+
found.push({ agentName: entry.name, provider: "openai-codex", credentials: { oauthAccessToken: provConfig.oauthAccessToken }, providerConfig: { ...provConfig } });
|
|
634
1358
|
}
|
|
635
1359
|
else if (provName === "minimax" && provConfig.apiKey) {
|
|
636
|
-
found.push({ agentName: entry.name, provider: "minimax", credentials: { apiKey: provConfig.apiKey } });
|
|
1360
|
+
found.push({ agentName: entry.name, provider: "minimax", credentials: { apiKey: provConfig.apiKey }, providerConfig: { ...provConfig } });
|
|
637
1361
|
}
|
|
638
1362
|
else if (provName === "azure" && provConfig.apiKey && provConfig.endpoint && provConfig.deployment) {
|
|
639
|
-
found.push({ agentName: entry.name, provider: "azure", credentials: { apiKey: provConfig.apiKey, endpoint: provConfig.endpoint, deployment: provConfig.deployment } });
|
|
1363
|
+
found.push({ agentName: entry.name, provider: "azure", credentials: { apiKey: provConfig.apiKey, endpoint: provConfig.endpoint, deployment: provConfig.deployment }, providerConfig: { ...provConfig } });
|
|
640
1364
|
}
|
|
641
1365
|
}
|
|
642
1366
|
}
|
|
@@ -654,7 +1378,7 @@ function discoverExistingCredentials(secretsRoot) {
|
|
|
654
1378
|
async function defaultRunAdoptionSpecialist() {
|
|
655
1379
|
const { runCliSession } = await Promise.resolve().then(() => __importStar(require("../../senses/cli")));
|
|
656
1380
|
const { patchRuntimeConfig } = await Promise.resolve().then(() => __importStar(require("../config")));
|
|
657
|
-
const { setAgentName } = await Promise.resolve().then(() => __importStar(require("../identity")));
|
|
1381
|
+
const { setAgentName, setAgentConfigOverride } = await Promise.resolve().then(() => __importStar(require("../identity")));
|
|
658
1382
|
const readlinePromises = await Promise.resolve().then(() => __importStar(require("readline/promises")));
|
|
659
1383
|
const crypto = await Promise.resolve().then(() => __importStar(require("crypto")));
|
|
660
1384
|
// Phase 1: cold CLI — collect provider/credentials with a simple readline
|
|
@@ -665,16 +1389,29 @@ async function defaultRunAdoptionSpecialist() {
|
|
|
665
1389
|
};
|
|
666
1390
|
let providerRaw;
|
|
667
1391
|
let credentials = {};
|
|
1392
|
+
let providerConfig = {};
|
|
668
1393
|
const tempDir = path.join(os.tmpdir(), `ouro-hatch-${crypto.randomUUID()}`);
|
|
669
1394
|
try {
|
|
670
1395
|
const secretsRoot = path.join(os.homedir(), ".agentsecrets");
|
|
671
1396
|
const discovered = discoverExistingCredentials(secretsRoot);
|
|
1397
|
+
const existingBundleCount = (0, specialist_orchestrator_1.listExistingBundles)((0, identity_1.getAgentBundlesRoot)()).length;
|
|
1398
|
+
const hatchVerb = existingBundleCount > 0 ? "let's hatch a new agent." : "let's hatch your first agent.";
|
|
1399
|
+
// Default models per provider (used when entering new credentials)
|
|
1400
|
+
const defaultModels = {
|
|
1401
|
+
anthropic: "claude-opus-4-6",
|
|
1402
|
+
minimax: "MiniMax-Text-01",
|
|
1403
|
+
"openai-codex": "gpt-5.4",
|
|
1404
|
+
"github-copilot": "claude-sonnet-4.6",
|
|
1405
|
+
azure: "",
|
|
1406
|
+
};
|
|
672
1407
|
if (discovered.length > 0) {
|
|
673
|
-
process.stdout.write(
|
|
1408
|
+
process.stdout.write(`\n\ud83d\udc0d welcome to ouroboros! ${hatchVerb}\n`);
|
|
674
1409
|
process.stdout.write("i found existing API credentials:\n\n");
|
|
675
1410
|
const unique = [...new Map(discovered.map((d) => [`${d.provider}`, d])).values()];
|
|
676
1411
|
for (let i = 0; i < unique.length; i++) {
|
|
677
|
-
|
|
1412
|
+
const model = unique[i].providerConfig.model || unique[i].providerConfig.deployment || "";
|
|
1413
|
+
const modelLabel = model ? `, ${model}` : "";
|
|
1414
|
+
process.stdout.write(` ${i + 1}. ${unique[i].provider}${modelLabel} (from ${unique[i].agentName})\n`);
|
|
678
1415
|
}
|
|
679
1416
|
process.stdout.write("\n");
|
|
680
1417
|
const choice = await coldPrompt("use one of these? enter number, or 'new' for a different key: ");
|
|
@@ -682,15 +1419,17 @@ async function defaultRunAdoptionSpecialist() {
|
|
|
682
1419
|
if (idx >= 0 && idx < unique.length) {
|
|
683
1420
|
providerRaw = unique[idx].provider;
|
|
684
1421
|
credentials = unique[idx].credentials;
|
|
1422
|
+
providerConfig = unique[idx].providerConfig;
|
|
685
1423
|
}
|
|
686
1424
|
else {
|
|
687
|
-
const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex): ");
|
|
1425
|
+
const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex/github-copilot): ");
|
|
688
1426
|
if (!isAgentProvider(pRaw)) {
|
|
689
1427
|
process.stdout.write("unknown provider. run `ouro hatch` to try again.\n");
|
|
690
1428
|
coldRl.close();
|
|
691
1429
|
return null;
|
|
692
1430
|
}
|
|
693
1431
|
providerRaw = pRaw;
|
|
1432
|
+
providerConfig = { model: defaultModels[providerRaw] };
|
|
694
1433
|
if (providerRaw === "anthropic")
|
|
695
1434
|
credentials.setupToken = await coldPrompt("API key: ");
|
|
696
1435
|
if (providerRaw === "openai-codex")
|
|
@@ -705,15 +1444,16 @@ async function defaultRunAdoptionSpecialist() {
|
|
|
705
1444
|
}
|
|
706
1445
|
}
|
|
707
1446
|
else {
|
|
708
|
-
process.stdout.write(
|
|
1447
|
+
process.stdout.write(`\n\ud83d\udc0d welcome to ouroboros! ${hatchVerb}\n`);
|
|
709
1448
|
process.stdout.write("i need an API key to power our conversation.\n\n");
|
|
710
|
-
const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex): ");
|
|
1449
|
+
const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex/github-copilot): ");
|
|
711
1450
|
if (!isAgentProvider(pRaw)) {
|
|
712
1451
|
process.stdout.write("unknown provider. run `ouro hatch` to try again.\n");
|
|
713
1452
|
coldRl.close();
|
|
714
1453
|
return null;
|
|
715
1454
|
}
|
|
716
1455
|
providerRaw = pRaw;
|
|
1456
|
+
providerConfig = { model: defaultModels[providerRaw] };
|
|
717
1457
|
if (providerRaw === "anthropic")
|
|
718
1458
|
credentials.setupToken = await coldPrompt("API key: ");
|
|
719
1459
|
if (providerRaw === "openai-codex")
|
|
@@ -732,21 +1472,38 @@ async function defaultRunAdoptionSpecialist() {
|
|
|
732
1472
|
const bundleSourceDir = path.resolve(__dirname, "..", "..", "..", "AdoptionSpecialist.ouro");
|
|
733
1473
|
const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
|
|
734
1474
|
const secretsRoot2 = path.join(os.homedir(), ".agentsecrets");
|
|
735
|
-
//
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
1475
|
+
// Suppress non-critical log noise during adoption (no secrets.json, etc.)
|
|
1476
|
+
const { setRuntimeLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves/runtime")));
|
|
1477
|
+
const { createLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves")));
|
|
1478
|
+
setRuntimeLogger(createLogger({ level: "error" }));
|
|
1479
|
+
// Configure runtime: set agent identity + config override so runAgent
|
|
1480
|
+
// doesn't try to read from ~/AgentBundles/AdoptionSpecialist.ouro/
|
|
741
1481
|
setAgentName("AdoptionSpecialist");
|
|
742
1482
|
// Build specialist system prompt
|
|
743
1483
|
const soulText = (0, specialist_orchestrator_1.loadSoulText)(bundleSourceDir);
|
|
744
1484
|
const identitiesDir = path.join(bundleSourceDir, "psyche", "identities");
|
|
745
1485
|
const identity = (0, specialist_orchestrator_1.pickRandomIdentity)(identitiesDir);
|
|
1486
|
+
// Load identity-specific spinner phrases (falls back to DEFAULT_AGENT_PHRASES)
|
|
1487
|
+
const { loadIdentityPhrases } = await Promise.resolve().then(() => __importStar(require("./specialist-orchestrator")));
|
|
1488
|
+
const phrases = loadIdentityPhrases(bundleSourceDir, identity.fileName);
|
|
1489
|
+
setAgentConfigOverride({
|
|
1490
|
+
version: 2,
|
|
1491
|
+
enabled: true,
|
|
1492
|
+
provider: providerRaw,
|
|
1493
|
+
humanFacing: { provider: providerRaw, model: "" },
|
|
1494
|
+
agentFacing: { provider: providerRaw, model: "" },
|
|
1495
|
+
phrases,
|
|
1496
|
+
});
|
|
1497
|
+
patchRuntimeConfig({
|
|
1498
|
+
providers: {
|
|
1499
|
+
[providerRaw]: { ...providerConfig, ...credentials },
|
|
1500
|
+
},
|
|
1501
|
+
});
|
|
746
1502
|
const existingBundles = (0, specialist_orchestrator_1.listExistingBundles)(bundlesRoot);
|
|
747
1503
|
const systemPrompt = (0, specialist_prompt_1.buildSpecialistSystemPrompt)(soulText, identity.content, existingBundles, {
|
|
748
1504
|
tempDir,
|
|
749
1505
|
provider: providerRaw,
|
|
1506
|
+
model: providerConfig.model ?? "",
|
|
750
1507
|
});
|
|
751
1508
|
// Build specialist tools
|
|
752
1509
|
const specialistTools = (0, specialist_tools_1.getSpecialistTools)();
|
|
@@ -764,6 +1521,10 @@ async function defaultRunAdoptionSpecialist() {
|
|
|
764
1521
|
tools: specialistTools,
|
|
765
1522
|
execTool: specialistExecTool,
|
|
766
1523
|
exitOnToolCall: "complete_adoption",
|
|
1524
|
+
autoFirstTurn: true,
|
|
1525
|
+
banner: false,
|
|
1526
|
+
disableCommands: true,
|
|
1527
|
+
skipSystemPromptRefresh: true,
|
|
767
1528
|
messages: [
|
|
768
1529
|
{ role: "system", content: systemPrompt },
|
|
769
1530
|
{ role: "user", content: "hi" },
|
|
@@ -777,11 +1538,21 @@ async function defaultRunAdoptionSpecialist() {
|
|
|
777
1538
|
}
|
|
778
1539
|
return null;
|
|
779
1540
|
}
|
|
780
|
-
catch {
|
|
1541
|
+
catch (err) {
|
|
1542
|
+
process.stderr.write(`\nouro adoption error: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
|
|
781
1543
|
coldRl.close();
|
|
782
1544
|
return null;
|
|
783
1545
|
}
|
|
784
1546
|
finally {
|
|
1547
|
+
// Clear specialist config/identity so the hatched agent gets its own
|
|
1548
|
+
setAgentConfigOverride(null);
|
|
1549
|
+
const { resetProviderRuntime } = await Promise.resolve().then(() => __importStar(require("../core")));
|
|
1550
|
+
resetProviderRuntime();
|
|
1551
|
+
const { resetConfigCache } = await Promise.resolve().then(() => __importStar(require("../config")));
|
|
1552
|
+
resetConfigCache();
|
|
1553
|
+
// Restore default logging
|
|
1554
|
+
const { setRuntimeLogger: restoreLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves/runtime")));
|
|
1555
|
+
restoreLogger(null);
|
|
785
1556
|
// Clean up temp dir if it still exists
|
|
786
1557
|
try {
|
|
787
1558
|
if (fs.existsSync(tempDir)) {
|
|
@@ -794,30 +1565,118 @@ async function defaultRunAdoptionSpecialist() {
|
|
|
794
1565
|
}
|
|
795
1566
|
}
|
|
796
1567
|
/* v8 ignore stop */
|
|
797
|
-
function createDefaultOuroCliDeps(socketPath =
|
|
1568
|
+
function createDefaultOuroCliDeps(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
|
|
798
1569
|
return {
|
|
799
1570
|
socketPath,
|
|
800
|
-
sendCommand:
|
|
1571
|
+
sendCommand: socket_client_1.sendDaemonCommand,
|
|
801
1572
|
startDaemonProcess: defaultStartDaemonProcess,
|
|
802
1573
|
writeStdout: defaultWriteStdout,
|
|
803
|
-
checkSocketAlive:
|
|
1574
|
+
checkSocketAlive: socket_client_1.checkDaemonSocketAlive,
|
|
804
1575
|
cleanupStaleSocket: defaultCleanupStaleSocket,
|
|
805
1576
|
fallbackPendingMessage: defaultFallbackPendingMessage,
|
|
806
|
-
installSubagents: defaultInstallSubagents,
|
|
807
|
-
linkFriendIdentity: defaultLinkFriendIdentity,
|
|
808
1577
|
listDiscoveredAgents: defaultListDiscoveredAgents,
|
|
809
1578
|
runHatchFlow: hatch_flow_1.runHatchFlow,
|
|
810
1579
|
promptInput: defaultPromptInput,
|
|
811
1580
|
runAdoptionSpecialist: defaultRunAdoptionSpecialist,
|
|
1581
|
+
runAuthFlow: auth_flow_1.runRuntimeAuthFlow,
|
|
812
1582
|
registerOuroBundleType: ouro_uti_1.registerOuroBundleUti,
|
|
813
1583
|
installOuroCommand: ouro_path_installer_1.installOuroCommand,
|
|
1584
|
+
/* v8 ignore start -- self-healing: ensures active symlink matches running runtime version @preserve */
|
|
1585
|
+
ensureCurrentVersionInstalled: () => {
|
|
1586
|
+
const linkedVersion = (0, ouro_version_manager_1.getCurrentVersion)({});
|
|
1587
|
+
const version = (0, bundle_manifest_1.getPackageVersion)();
|
|
1588
|
+
if (linkedVersion === version)
|
|
1589
|
+
return;
|
|
1590
|
+
(0, ouro_version_manager_1.ensureLayout)({});
|
|
1591
|
+
const cliHome = (0, ouro_version_manager_1.getOuroCliHome)();
|
|
1592
|
+
const versionEntry = path.join(cliHome, "versions", version, "node_modules", "@ouro.bot", "cli", "dist", "heart", "daemon", "ouro-entry.js");
|
|
1593
|
+
if (!fs.existsSync(versionEntry)) {
|
|
1594
|
+
(0, ouro_version_manager_1.installVersion)(version, {});
|
|
1595
|
+
}
|
|
1596
|
+
(0, ouro_version_manager_1.activateVersion)(version, {});
|
|
1597
|
+
},
|
|
1598
|
+
/* v8 ignore stop */
|
|
1599
|
+
/* v8 ignore start -- CLI version management defaults: integration code @preserve */
|
|
1600
|
+
checkForCliUpdate: async () => {
|
|
1601
|
+
const { checkForUpdate } = await Promise.resolve().then(() => __importStar(require("./update-checker")));
|
|
1602
|
+
return checkForUpdate((0, bundle_manifest_1.getPackageVersion)(), {
|
|
1603
|
+
fetchRegistryJson: async () => {
|
|
1604
|
+
const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
|
|
1605
|
+
return res.json();
|
|
1606
|
+
},
|
|
1607
|
+
distTag: "alpha",
|
|
1608
|
+
});
|
|
1609
|
+
},
|
|
1610
|
+
installCliVersion: async (version) => { (0, ouro_version_manager_1.installVersion)(version, {}); },
|
|
1611
|
+
activateCliVersion: (version) => { (0, ouro_version_manager_1.activateVersion)(version, {}); },
|
|
1612
|
+
getCurrentCliVersion: () => (0, ouro_version_manager_1.getCurrentVersion)({}),
|
|
1613
|
+
getPreviousCliVersion: () => (0, ouro_version_manager_1.getPreviousVersion)({}),
|
|
1614
|
+
listCliVersions: () => (0, ouro_version_manager_1.listInstalledVersions)({}),
|
|
1615
|
+
reExecFromNewVersion: (reArgs) => {
|
|
1616
|
+
const entry = path.join((0, ouro_version_manager_1.getOuroCliHome)(), "CurrentVersion", "node_modules", "@ouro.bot", "cli", "dist", "heart", "daemon", "ouro-entry.js");
|
|
1617
|
+
require("child_process").execFileSync("node", [entry, ...reArgs], { stdio: "inherit" });
|
|
1618
|
+
process.exit(0);
|
|
1619
|
+
},
|
|
1620
|
+
/* v8 ignore stop */
|
|
1621
|
+
syncGlobalOuroBotWrapper: ouro_bot_global_installer_1.syncGlobalOuroBotWrapper,
|
|
1622
|
+
ensureSkillManagement: skill_management_installer_1.ensureSkillManagement,
|
|
1623
|
+
ensureDaemonBootPersistence: defaultEnsureDaemonBootPersistence,
|
|
1624
|
+
/* v8 ignore start -- dev-mode defaults: tests inject mocks for mode detection and binary resolution @preserve */
|
|
1625
|
+
detectMode: () => (0, runtime_mode_1.detectRuntimeMode)((0, identity_1.getRepoRoot)()),
|
|
1626
|
+
getInstalledBinaryPath: () => {
|
|
1627
|
+
const cliHome = (0, ouro_version_manager_1.getOuroCliHome)();
|
|
1628
|
+
const binaryPath = path.join(cliHome, "bin", "ouro");
|
|
1629
|
+
return fs.existsSync(binaryPath) ? binaryPath : null;
|
|
1630
|
+
},
|
|
1631
|
+
execInstalledBinary: (binaryPath, binArgs) => {
|
|
1632
|
+
const { execFileSync } = require("child_process");
|
|
1633
|
+
execFileSync(binaryPath, binArgs, { stdio: "inherit" });
|
|
1634
|
+
process.exit(0);
|
|
1635
|
+
},
|
|
1636
|
+
/* v8 ignore stop */
|
|
814
1637
|
/* v8 ignore next 3 -- integration: launches interactive CLI session @preserve */
|
|
815
1638
|
startChat: async (agentName) => {
|
|
816
1639
|
const { main } = await Promise.resolve().then(() => __importStar(require("../../senses/cli")));
|
|
817
1640
|
await main(agentName);
|
|
818
1641
|
},
|
|
1642
|
+
scanSessions: async () => {
|
|
1643
|
+
const agentName = (0, identity_1.getAgentName)();
|
|
1644
|
+
const agentRoot = (0, identity_1.getAgentRoot)(agentName);
|
|
1645
|
+
return (0, session_activity_1.listSessionActivity)({
|
|
1646
|
+
sessionsDir: path.join(agentRoot, "state", "sessions"),
|
|
1647
|
+
friendsDir: path.join(agentRoot, "friends"),
|
|
1648
|
+
agentName,
|
|
1649
|
+
}).map((entry) => ({
|
|
1650
|
+
friendId: entry.friendId,
|
|
1651
|
+
friendName: entry.friendName,
|
|
1652
|
+
channel: entry.channel,
|
|
1653
|
+
lastActivity: entry.lastActivityAt,
|
|
1654
|
+
}));
|
|
1655
|
+
},
|
|
819
1656
|
};
|
|
820
1657
|
}
|
|
1658
|
+
function formatMcpResponse(command, response) {
|
|
1659
|
+
if (command.kind === "mcp.list") {
|
|
1660
|
+
const allTools = response.data;
|
|
1661
|
+
if (!allTools || allTools.length === 0) {
|
|
1662
|
+
return response.message ?? "no tools available from connected MCP servers";
|
|
1663
|
+
}
|
|
1664
|
+
const lines = [];
|
|
1665
|
+
for (const entry of allTools) {
|
|
1666
|
+
lines.push(`[${entry.server}]`);
|
|
1667
|
+
for (const tool of entry.tools) {
|
|
1668
|
+
lines.push(` ${tool.name}: ${tool.description}`);
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
return lines.join("\n");
|
|
1672
|
+
}
|
|
1673
|
+
// mcp.call
|
|
1674
|
+
const result = response.data;
|
|
1675
|
+
if (!result) {
|
|
1676
|
+
return response.message ?? "no result";
|
|
1677
|
+
}
|
|
1678
|
+
return result.content.map((c) => c.text).join("\n");
|
|
1679
|
+
}
|
|
821
1680
|
function toDaemonCommand(command) {
|
|
822
1681
|
return command;
|
|
823
1682
|
}
|
|
@@ -825,28 +1684,17 @@ async function resolveHatchInput(command, deps) {
|
|
|
825
1684
|
const prompt = deps.promptInput;
|
|
826
1685
|
const agentName = command.agentName ?? (prompt ? await prompt("Hatchling name: ") : "");
|
|
827
1686
|
const humanName = command.humanName ?? (prompt ? await prompt("Your name: ") : os.userInfo().username);
|
|
828
|
-
const providerRaw = command.provider ?? (prompt ? await prompt("Provider (azure|anthropic|minimax|openai-codex): ") : "");
|
|
1687
|
+
const providerRaw = command.provider ?? (prompt ? await prompt("Provider (azure|anthropic|minimax|openai-codex|github-copilot): ") : "");
|
|
829
1688
|
if (!agentName || !humanName || !isAgentProvider(providerRaw)) {
|
|
830
1689
|
throw new Error(`Usage\n${usage()}`);
|
|
831
1690
|
}
|
|
832
|
-
const credentials =
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
}
|
|
839
|
-
if (providerRaw === "minimax" && !credentials.apiKey && prompt) {
|
|
840
|
-
credentials.apiKey = await prompt("MiniMax API key: ");
|
|
841
|
-
}
|
|
842
|
-
if (providerRaw === "azure") {
|
|
843
|
-
if (!credentials.apiKey && prompt)
|
|
844
|
-
credentials.apiKey = await prompt("Azure API key: ");
|
|
845
|
-
if (!credentials.endpoint && prompt)
|
|
846
|
-
credentials.endpoint = await prompt("Azure endpoint: ");
|
|
847
|
-
if (!credentials.deployment && prompt)
|
|
848
|
-
credentials.deployment = await prompt("Azure deployment: ");
|
|
849
|
-
}
|
|
1691
|
+
const credentials = await (0, auth_flow_1.resolveHatchCredentials)({
|
|
1692
|
+
agentName,
|
|
1693
|
+
provider: providerRaw,
|
|
1694
|
+
credentials: command.credentials,
|
|
1695
|
+
promptInput: prompt,
|
|
1696
|
+
runAuthFlow: deps.runAuthFlow,
|
|
1697
|
+
});
|
|
850
1698
|
return {
|
|
851
1699
|
agentName,
|
|
852
1700
|
humanName,
|
|
@@ -876,7 +1724,11 @@ async function performSystemSetup(deps) {
|
|
|
876
1724
|
// Install ouro command to PATH (non-blocking)
|
|
877
1725
|
if (deps.installOuroCommand) {
|
|
878
1726
|
try {
|
|
879
|
-
deps.installOuroCommand();
|
|
1727
|
+
const installResult = deps.installOuroCommand();
|
|
1728
|
+
/* v8 ignore next -- old-launcher repair hint: fires when stale ~/.local/bin/ouro is fixed @preserve */
|
|
1729
|
+
if (installResult.repairedOldLauncher) {
|
|
1730
|
+
deps.writeStdout("repaired stale ouro launcher at ~/.local/bin/ouro");
|
|
1731
|
+
}
|
|
880
1732
|
}
|
|
881
1733
|
catch (error) {
|
|
882
1734
|
(0, runtime_1.emitNervesEvent)({
|
|
@@ -888,28 +1740,391 @@ async function performSystemSetup(deps) {
|
|
|
888
1740
|
});
|
|
889
1741
|
}
|
|
890
1742
|
}
|
|
891
|
-
//
|
|
892
|
-
|
|
893
|
-
|
|
1743
|
+
// Self-healing: ensure current version is installed in ~/.ouro-cli/ layout.
|
|
1744
|
+
// Handles the case where the wrapper exists but CurrentVersion is missing
|
|
1745
|
+
// (e.g., first run after migration from old npx wrapper).
|
|
1746
|
+
if (deps.ensureCurrentVersionInstalled) {
|
|
1747
|
+
try {
|
|
1748
|
+
deps.ensureCurrentVersionInstalled();
|
|
1749
|
+
}
|
|
1750
|
+
catch (error) {
|
|
1751
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1752
|
+
level: "warn",
|
|
1753
|
+
component: "daemon",
|
|
1754
|
+
event: "daemon.system_setup_version_install_error",
|
|
1755
|
+
message: "failed to ensure current version installed",
|
|
1756
|
+
meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive @preserve */ String(error) },
|
|
1757
|
+
});
|
|
1758
|
+
}
|
|
894
1759
|
}
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
1760
|
+
if (deps.syncGlobalOuroBotWrapper) {
|
|
1761
|
+
try {
|
|
1762
|
+
await Promise.resolve(deps.syncGlobalOuroBotWrapper());
|
|
1763
|
+
}
|
|
1764
|
+
catch (error) {
|
|
1765
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1766
|
+
level: "warn",
|
|
1767
|
+
component: "daemon",
|
|
1768
|
+
event: "daemon.system_setup_ouro_bot_wrapper_error",
|
|
1769
|
+
message: "failed to sync global ouro.bot wrapper",
|
|
1770
|
+
meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
|
|
1771
|
+
});
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
// Ensure skill-management skill is available
|
|
1775
|
+
if (deps.ensureSkillManagement) {
|
|
1776
|
+
try {
|
|
1777
|
+
await deps.ensureSkillManagement();
|
|
1778
|
+
/* v8 ignore start -- defensive: ensureSkillManagement handles its own errors internally @preserve */
|
|
1779
|
+
}
|
|
1780
|
+
catch (error) {
|
|
1781
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1782
|
+
level: "warn",
|
|
1783
|
+
component: "daemon",
|
|
1784
|
+
event: "daemon.system_setup_skill_management_error",
|
|
1785
|
+
message: "failed to ensure skill-management skill",
|
|
1786
|
+
meta: { error: error instanceof Error ? error.message : String(error) },
|
|
1787
|
+
});
|
|
1788
|
+
}
|
|
1789
|
+
/* v8 ignore stop */
|
|
903
1790
|
}
|
|
904
1791
|
// Register .ouro bundle type (UTI on macOS)
|
|
905
1792
|
await registerOuroBundleTypeNonBlocking(deps);
|
|
906
1793
|
}
|
|
1794
|
+
function executeTaskCommand(command, taskMod) {
|
|
1795
|
+
if (command.kind === "task.board") {
|
|
1796
|
+
if (command.status) {
|
|
1797
|
+
const lines = taskMod.boardStatus(command.status);
|
|
1798
|
+
return lines.length > 0 ? lines.join("\n") : "no tasks in that status";
|
|
1799
|
+
}
|
|
1800
|
+
const board = taskMod.getBoard();
|
|
1801
|
+
return board.full || board.compact || "no tasks found";
|
|
1802
|
+
}
|
|
1803
|
+
if (command.kind === "task.create") {
|
|
1804
|
+
try {
|
|
1805
|
+
const created = taskMod.createTask({
|
|
1806
|
+
title: command.title,
|
|
1807
|
+
type: command.type ?? "one-shot",
|
|
1808
|
+
category: "general",
|
|
1809
|
+
body: "",
|
|
1810
|
+
});
|
|
1811
|
+
return `created: ${created}`;
|
|
1812
|
+
}
|
|
1813
|
+
catch (error) {
|
|
1814
|
+
return `error: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
if (command.kind === "task.update") {
|
|
1818
|
+
const result = taskMod.updateStatus(command.id, command.status);
|
|
1819
|
+
if (!result.ok) {
|
|
1820
|
+
return `error: ${result.reason ?? "status update failed"}`;
|
|
1821
|
+
}
|
|
1822
|
+
const archivedSuffix = result.archived && result.archived.length > 0
|
|
1823
|
+
? ` | archived: ${result.archived.join(", ")}`
|
|
1824
|
+
: "";
|
|
1825
|
+
return `updated: ${command.id} -> ${result.to}${archivedSuffix}`;
|
|
1826
|
+
}
|
|
1827
|
+
if (command.kind === "task.show") {
|
|
1828
|
+
const task = taskMod.getTask(command.id);
|
|
1829
|
+
if (!task)
|
|
1830
|
+
return `task not found: ${command.id}`;
|
|
1831
|
+
return [
|
|
1832
|
+
`title: ${task.title}`,
|
|
1833
|
+
`type: ${task.type}`,
|
|
1834
|
+
`status: ${task.status}`,
|
|
1835
|
+
`category: ${task.category}`,
|
|
1836
|
+
`created: ${task.created}`,
|
|
1837
|
+
`updated: ${task.updated}`,
|
|
1838
|
+
`path: ${task.path}`,
|
|
1839
|
+
task.body ? `\n${task.body}` : "",
|
|
1840
|
+
].filter(Boolean).join("\n");
|
|
1841
|
+
}
|
|
1842
|
+
if (command.kind === "task.actionable") {
|
|
1843
|
+
const lines = taskMod.boardAction();
|
|
1844
|
+
return lines.length > 0 ? lines.join("\n") : "no action required";
|
|
1845
|
+
}
|
|
1846
|
+
if (command.kind === "task.deps") {
|
|
1847
|
+
const lines = taskMod.boardDeps();
|
|
1848
|
+
return lines.length > 0 ? lines.join("\n") : "no unresolved dependencies";
|
|
1849
|
+
}
|
|
1850
|
+
if (command.kind === "task.fix") {
|
|
1851
|
+
try {
|
|
1852
|
+
const fixOptions = {
|
|
1853
|
+
mode: command.mode,
|
|
1854
|
+
...(command.issueId ? { issueId: command.issueId } : {}),
|
|
1855
|
+
...(command.option !== undefined ? { option: command.option } : {}),
|
|
1856
|
+
};
|
|
1857
|
+
const result = taskMod.fix(fixOptions);
|
|
1858
|
+
if (command.mode === "dry-run") {
|
|
1859
|
+
if (result.remaining.length === 0) {
|
|
1860
|
+
return `task health: clean`;
|
|
1861
|
+
}
|
|
1862
|
+
const safeIssues = result.remaining.filter((i) => i.confidence === "safe");
|
|
1863
|
+
const reviewIssues = result.remaining.filter((i) => i.confidence === "needs_review");
|
|
1864
|
+
const lines = [`${result.remaining.length} issues found`];
|
|
1865
|
+
if (safeIssues.length > 0) {
|
|
1866
|
+
lines.push("", `safe fixes (${safeIssues.length}):`);
|
|
1867
|
+
for (const issue of safeIssues) {
|
|
1868
|
+
lines.push(` ${issue.code}:${issue.target} -- ${issue.description}`);
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
if (reviewIssues.length > 0) {
|
|
1872
|
+
lines.push("", `needs review (${reviewIssues.length}):`);
|
|
1873
|
+
for (const issue of reviewIssues) {
|
|
1874
|
+
lines.push(` ${issue.code}:${issue.target} -- ${issue.description}`);
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
lines.push("", `task health: ${result.health}`);
|
|
1878
|
+
return lines.join("\n");
|
|
1879
|
+
}
|
|
1880
|
+
// safe, single, or --all modes: show what was done
|
|
1881
|
+
const lines = [];
|
|
1882
|
+
if (result.applied.length > 0) {
|
|
1883
|
+
lines.push(`${result.applied.length} applied:`);
|
|
1884
|
+
for (const issue of result.applied) {
|
|
1885
|
+
lines.push(` ${issue.code}:${issue.target}`);
|
|
1886
|
+
}
|
|
1887
|
+
}
|
|
1888
|
+
if (result.remaining.length > 0) {
|
|
1889
|
+
lines.push(`${result.remaining.length} remaining:`);
|
|
1890
|
+
for (const issue of result.remaining) {
|
|
1891
|
+
lines.push(` ${issue.code}:${issue.target} -- ${issue.description}`);
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
if (result.applied.length === 0 && result.remaining.length === 0) {
|
|
1895
|
+
lines.push("no issues");
|
|
1896
|
+
}
|
|
1897
|
+
lines.push(`task health: ${result.health}`);
|
|
1898
|
+
return lines.join("\n");
|
|
1899
|
+
}
|
|
1900
|
+
catch (error) {
|
|
1901
|
+
return `error: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
// command.kind === "task.sessions"
|
|
1905
|
+
const lines = taskMod.boardSessions();
|
|
1906
|
+
return lines.length > 0 ? lines.join("\n") : "no active sessions";
|
|
1907
|
+
}
|
|
1908
|
+
const TRUST_RANK = { family: 4, friend: 3, acquaintance: 2, stranger: 1 };
|
|
1909
|
+
/* v8 ignore start -- defensive: ?? fallbacks are unreachable when inputs are valid TrustLevel values @preserve */
|
|
1910
|
+
function higherTrust(a, b) {
|
|
1911
|
+
const rankA = TRUST_RANK[a ?? "stranger"] ?? 1;
|
|
1912
|
+
const rankB = TRUST_RANK[b ?? "stranger"] ?? 1;
|
|
1913
|
+
return rankA >= rankB ? (a ?? "stranger") : (b ?? "stranger");
|
|
1914
|
+
}
|
|
1915
|
+
/* v8 ignore stop */
|
|
1916
|
+
async function executeFriendCommand(command, store) {
|
|
1917
|
+
if (command.kind === "friend.list") {
|
|
1918
|
+
const listAll = store.listAll;
|
|
1919
|
+
if (!listAll)
|
|
1920
|
+
return "friend store does not support listing";
|
|
1921
|
+
const friends = await listAll.call(store);
|
|
1922
|
+
if (friends.length === 0)
|
|
1923
|
+
return "no friends found";
|
|
1924
|
+
const lines = friends.map((f) => {
|
|
1925
|
+
const trust = f.trustLevel ?? "unknown";
|
|
1926
|
+
return `${f.id} ${f.name} ${trust}`;
|
|
1927
|
+
});
|
|
1928
|
+
return lines.join("\n");
|
|
1929
|
+
}
|
|
1930
|
+
if (command.kind === "friend.show") {
|
|
1931
|
+
const record = await store.get(command.friendId);
|
|
1932
|
+
if (!record)
|
|
1933
|
+
return `friend not found: ${command.friendId}`;
|
|
1934
|
+
return JSON.stringify(record, null, 2);
|
|
1935
|
+
}
|
|
1936
|
+
if (command.kind === "friend.create") {
|
|
1937
|
+
const now = new Date().toISOString();
|
|
1938
|
+
const id = (0, crypto_1.randomUUID)();
|
|
1939
|
+
const trustLevel = (command.trustLevel ?? "acquaintance");
|
|
1940
|
+
await store.put(id, {
|
|
1941
|
+
id,
|
|
1942
|
+
name: command.name,
|
|
1943
|
+
trustLevel,
|
|
1944
|
+
externalIds: [],
|
|
1945
|
+
tenantMemberships: [],
|
|
1946
|
+
toolPreferences: {},
|
|
1947
|
+
notes: {},
|
|
1948
|
+
totalTokens: 0,
|
|
1949
|
+
createdAt: now,
|
|
1950
|
+
updatedAt: now,
|
|
1951
|
+
schemaVersion: 1,
|
|
1952
|
+
});
|
|
1953
|
+
return `created: ${id} (${command.name}, ${trustLevel})`;
|
|
1954
|
+
}
|
|
1955
|
+
if (command.kind === "friend.update") {
|
|
1956
|
+
const current = await store.get(command.friendId);
|
|
1957
|
+
if (!current)
|
|
1958
|
+
return `friend not found: ${command.friendId}`;
|
|
1959
|
+
const now = new Date().toISOString();
|
|
1960
|
+
await store.put(command.friendId, {
|
|
1961
|
+
...current,
|
|
1962
|
+
trustLevel: command.trustLevel,
|
|
1963
|
+
role: command.trustLevel,
|
|
1964
|
+
updatedAt: now,
|
|
1965
|
+
});
|
|
1966
|
+
return `updated: ${command.friendId} → trust=${command.trustLevel}`;
|
|
1967
|
+
}
|
|
1968
|
+
if (command.kind === "friend.link") {
|
|
1969
|
+
const current = await store.get(command.friendId);
|
|
1970
|
+
if (!current)
|
|
1971
|
+
return `friend not found: ${command.friendId}`;
|
|
1972
|
+
const alreadyLinked = current.externalIds.some((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
|
|
1973
|
+
if (alreadyLinked)
|
|
1974
|
+
return `identity already linked: ${command.provider}:${command.externalId}`;
|
|
1975
|
+
const now = new Date().toISOString();
|
|
1976
|
+
const newExternalIds = [
|
|
1977
|
+
...current.externalIds,
|
|
1978
|
+
{ provider: command.provider, externalId: command.externalId, linkedAt: now },
|
|
1979
|
+
];
|
|
1980
|
+
// Orphan cleanup: check if another friend has this externalId
|
|
1981
|
+
const orphan = await store.findByExternalId(command.provider, command.externalId);
|
|
1982
|
+
let mergeMessage = "";
|
|
1983
|
+
let mergedNotes = { ...current.notes };
|
|
1984
|
+
let mergedTrust = current.trustLevel;
|
|
1985
|
+
let orphanExternalIds = [];
|
|
1986
|
+
if (orphan && orphan.id !== command.friendId) {
|
|
1987
|
+
// Merge orphan's notes (target's notes take priority)
|
|
1988
|
+
mergedNotes = { ...orphan.notes, ...current.notes };
|
|
1989
|
+
// Keep higher trust level
|
|
1990
|
+
mergedTrust = higherTrust(current.trustLevel, orphan.trustLevel);
|
|
1991
|
+
// Collect orphan's other externalIds (excluding the one being linked)
|
|
1992
|
+
orphanExternalIds = orphan.externalIds.filter((ext) => !(ext.provider === command.provider && ext.externalId === command.externalId));
|
|
1993
|
+
await store.delete(orphan.id);
|
|
1994
|
+
mergeMessage = ` (merged orphan ${orphan.id})`;
|
|
1995
|
+
}
|
|
1996
|
+
await store.put(command.friendId, {
|
|
1997
|
+
...current,
|
|
1998
|
+
externalIds: [...newExternalIds, ...orphanExternalIds],
|
|
1999
|
+
notes: mergedNotes,
|
|
2000
|
+
trustLevel: mergedTrust,
|
|
2001
|
+
updatedAt: now,
|
|
2002
|
+
});
|
|
2003
|
+
return `linked ${command.provider}:${command.externalId} to ${command.friendId}${mergeMessage}`;
|
|
2004
|
+
}
|
|
2005
|
+
// command.kind === "friend.unlink"
|
|
2006
|
+
const current = await store.get(command.friendId);
|
|
2007
|
+
if (!current)
|
|
2008
|
+
return `friend not found: ${command.friendId}`;
|
|
2009
|
+
const idx = current.externalIds.findIndex((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
|
|
2010
|
+
if (idx === -1)
|
|
2011
|
+
return `identity not linked: ${command.provider}:${command.externalId}`;
|
|
2012
|
+
const now = new Date().toISOString();
|
|
2013
|
+
const filtered = current.externalIds.filter((_, i) => i !== idx);
|
|
2014
|
+
await store.put(command.friendId, { ...current, externalIds: filtered, updatedAt: now });
|
|
2015
|
+
return `unlinked ${command.provider}:${command.externalId} from ${command.friendId}`;
|
|
2016
|
+
}
|
|
2017
|
+
function executeReminderCommand(command, taskMod) {
|
|
2018
|
+
try {
|
|
2019
|
+
const created = taskMod.createTask({
|
|
2020
|
+
title: command.title,
|
|
2021
|
+
type: command.cadence ? "ongoing" : "one-shot",
|
|
2022
|
+
category: command.category ?? "reminder",
|
|
2023
|
+
body: command.body,
|
|
2024
|
+
scheduledAt: command.scheduledAt,
|
|
2025
|
+
cadence: command.cadence,
|
|
2026
|
+
requester: command.requester,
|
|
2027
|
+
});
|
|
2028
|
+
return `created: ${created}`;
|
|
2029
|
+
}
|
|
2030
|
+
catch (error) {
|
|
2031
|
+
return `error: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
/* v8 ignore start -- repo resolution for ouro dev: repoPath branch tested via daemon-cli-dev; clone requires real git/npm @preserve */
|
|
2035
|
+
function getDevConfigPath() {
|
|
2036
|
+
return path.join((0, ouro_version_manager_1.getOuroCliHome)(), "dev-config.json");
|
|
2037
|
+
}
|
|
2038
|
+
function readPersistedDevPath() {
|
|
2039
|
+
try {
|
|
2040
|
+
const data = JSON.parse(fs.readFileSync(getDevConfigPath(), "utf-8"));
|
|
2041
|
+
return typeof data.repoPath === "string" ? data.repoPath : null;
|
|
2042
|
+
}
|
|
2043
|
+
catch {
|
|
2044
|
+
return null;
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
function persistDevPath(repoPath) {
|
|
2048
|
+
try {
|
|
2049
|
+
fs.mkdirSync(path.dirname(getDevConfigPath()), { recursive: true });
|
|
2050
|
+
fs.writeFileSync(getDevConfigPath(), JSON.stringify({ repoPath }, null, 2));
|
|
2051
|
+
}
|
|
2052
|
+
catch { /* best effort */ }
|
|
2053
|
+
}
|
|
2054
|
+
function resolveDevRepoCwd(command, checkExists, deps) {
|
|
2055
|
+
// 1. Explicit --repo-path: use it and persist for next time
|
|
2056
|
+
if (command.repoPath) {
|
|
2057
|
+
const resolved = path.resolve(command.repoPath);
|
|
2058
|
+
persistDevPath(resolved);
|
|
2059
|
+
return resolved;
|
|
2060
|
+
}
|
|
2061
|
+
// 2. Clone request
|
|
2062
|
+
if (command.clone)
|
|
2063
|
+
return resolveClonePath(command, checkExists, deps);
|
|
2064
|
+
// 3. If test/internal deps provide getRepoCwd, use it directly
|
|
2065
|
+
if (deps.getRepoCwd) {
|
|
2066
|
+
return deps.getRepoCwd();
|
|
2067
|
+
}
|
|
2068
|
+
// 4. Check CWD — if we're inside a harness repo, use it
|
|
2069
|
+
const cwd = process.cwd();
|
|
2070
|
+
if (checkExists(path.join(cwd, ".git")) && checkExists(path.join(cwd, "src", "heart", "daemon"))) {
|
|
2071
|
+
persistDevPath(cwd);
|
|
2072
|
+
return cwd;
|
|
2073
|
+
}
|
|
2074
|
+
// 5. Read persisted path from last --repo-path
|
|
2075
|
+
const persisted = readPersistedDevPath();
|
|
2076
|
+
if (persisted && checkExists(path.join(persisted, ".git"))) {
|
|
2077
|
+
deps.writeStdout(`using remembered dev path: ${persisted}`);
|
|
2078
|
+
return persisted;
|
|
2079
|
+
}
|
|
2080
|
+
// 6. Fall back to getRepoRoot (works when running from installed binary → resolves to npm package)
|
|
2081
|
+
return (0, identity_1.getRepoRoot)();
|
|
2082
|
+
}
|
|
2083
|
+
/* v8 ignore stop */
|
|
2084
|
+
/* v8 ignore start -- clone/build: requires real git clone + npm install on disk @preserve */
|
|
2085
|
+
function resolveClonePath(command, checkExists, deps) {
|
|
2086
|
+
const cloneTarget = command.clonePath
|
|
2087
|
+
? path.resolve(command.clonePath)
|
|
2088
|
+
: path.join(os.homedir(), "Projects", "ouroboros");
|
|
2089
|
+
if (!checkExists(path.join(cloneTarget, ".git"))) {
|
|
2090
|
+
deps.writeStdout(`cloning ouroboros to ${cloneTarget}...`);
|
|
2091
|
+
try {
|
|
2092
|
+
(0, child_process_1.execSync)(`git clone ${identity_1.HARNESS_CANONICAL_REPO_URL} "${cloneTarget}"`, { stdio: "inherit" });
|
|
2093
|
+
}
|
|
2094
|
+
catch {
|
|
2095
|
+
throw new Error(`clone failed. check your network and try again, or clone manually and use --repo-path.`);
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
else {
|
|
2099
|
+
deps.writeStdout(`repo already exists at ${cloneTarget}, pulling latest...`);
|
|
2100
|
+
try {
|
|
2101
|
+
(0, child_process_1.execSync)("git pull --ff-only", { cwd: cloneTarget, stdio: "inherit" });
|
|
2102
|
+
}
|
|
2103
|
+
catch {
|
|
2104
|
+
deps.writeStdout("pull failed (may have local changes). continuing with existing code.");
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
deps.writeStdout("building...");
|
|
2108
|
+
try {
|
|
2109
|
+
(0, child_process_1.execSync)("npm install && npm run build", { cwd: cloneTarget, stdio: "inherit" });
|
|
2110
|
+
}
|
|
2111
|
+
catch {
|
|
2112
|
+
throw new Error(`build failed in ${cloneTarget}. check the output above.`);
|
|
2113
|
+
}
|
|
2114
|
+
return cloneTarget;
|
|
2115
|
+
}
|
|
2116
|
+
/* v8 ignore stop */
|
|
907
2117
|
async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
|
|
908
|
-
if (args.
|
|
2118
|
+
if (args.length === 1 && (args[0] === "--help" || args[0] === "-h")) {
|
|
909
2119
|
const text = usage();
|
|
910
2120
|
deps.writeStdout(text);
|
|
911
2121
|
return text;
|
|
912
2122
|
}
|
|
2123
|
+
if (args.length === 1 && (args[0] === "-v" || args[0] === "--version")) {
|
|
2124
|
+
const text = formatVersionOutput();
|
|
2125
|
+
deps.writeStdout(text);
|
|
2126
|
+
return text;
|
|
2127
|
+
}
|
|
913
2128
|
let command;
|
|
914
2129
|
try {
|
|
915
2130
|
command = parseOuroCommand(args);
|
|
@@ -980,21 +2195,1058 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
|
|
|
980
2195
|
meta: { kind: command.kind },
|
|
981
2196
|
});
|
|
982
2197
|
if (command.kind === "daemon.up") {
|
|
2198
|
+
// ── dev mode cleanup: delete dev-config.json so the wrapper stops dispatching to dev repo ──
|
|
2199
|
+
/* v8 ignore start -- dev-config cleanup: requires real filesystem state @preserve */
|
|
2200
|
+
try {
|
|
2201
|
+
const devConfigPath = getDevConfigPath();
|
|
2202
|
+
if (fs.existsSync(devConfigPath)) {
|
|
2203
|
+
fs.unlinkSync(devConfigPath);
|
|
2204
|
+
}
|
|
2205
|
+
}
|
|
2206
|
+
catch { /* best effort */ }
|
|
2207
|
+
/* v8 ignore stop */
|
|
2208
|
+
// ── dev mode delegation: ouro up from a dev repo delegates to installed binary ──
|
|
2209
|
+
// Only runs when detectMode is explicitly injected (via createDefaultOuroCliDeps or tests)
|
|
2210
|
+
if (deps.detectMode) {
|
|
2211
|
+
const runtimeMode = deps.detectMode();
|
|
2212
|
+
if (runtimeMode === "dev") {
|
|
2213
|
+
/* v8 ignore next -- defensive: getInstalledBinaryPath always injected in tests @preserve */
|
|
2214
|
+
const installedBinary = deps.getInstalledBinaryPath ? deps.getInstalledBinaryPath() : null;
|
|
2215
|
+
if (installedBinary) {
|
|
2216
|
+
deps.writeStdout("delegating to installed ouro...");
|
|
2217
|
+
/* v8 ignore next 3 -- defensive: execInstalledBinary always injected; missing branch unreachable @preserve */
|
|
2218
|
+
if (deps.execInstalledBinary) {
|
|
2219
|
+
deps.execInstalledBinary(installedBinary, args);
|
|
2220
|
+
}
|
|
2221
|
+
/* v8 ignore next 2 -- unreachable after exec replaces process @preserve */
|
|
2222
|
+
return "";
|
|
2223
|
+
}
|
|
2224
|
+
const message = "no installed version found. run: npx @ouro.bot/cli@alpha";
|
|
2225
|
+
deps.writeStdout(message);
|
|
2226
|
+
return message;
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
const linkedVersionBeforeUp = deps.getCurrentCliVersion?.() ?? null;
|
|
2230
|
+
// ── versioned CLI update check ──
|
|
2231
|
+
if (deps.checkForCliUpdate) {
|
|
2232
|
+
let pendingReExec = false;
|
|
2233
|
+
try {
|
|
2234
|
+
const updateResult = await deps.checkForCliUpdate();
|
|
2235
|
+
if (updateResult.available && updateResult.latestVersion) {
|
|
2236
|
+
/* v8 ignore next -- fallback: getCurrentCliVersion always injected in tests @preserve */
|
|
2237
|
+
const currentVersion = linkedVersionBeforeUp ?? "unknown";
|
|
2238
|
+
await deps.installCliVersion(updateResult.latestVersion);
|
|
2239
|
+
deps.activateCliVersion(updateResult.latestVersion);
|
|
2240
|
+
deps.writeStdout(`ouro updated to ${updateResult.latestVersion} (was ${currentVersion})`);
|
|
2241
|
+
const changelogCommand = (0, ouro_version_manager_1.buildChangelogCommand)(currentVersion, updateResult.latestVersion);
|
|
2242
|
+
/* v8 ignore next -- buildChangelogCommand is non-null when an actual newer version is installed @preserve */
|
|
2243
|
+
if (changelogCommand) {
|
|
2244
|
+
deps.writeStdout(`review changes with: ${changelogCommand}`);
|
|
2245
|
+
}
|
|
2246
|
+
pendingReExec = true;
|
|
2247
|
+
}
|
|
2248
|
+
/* v8 ignore start -- update check error: tested via daemon-cli-update-flow.test.ts @preserve */
|
|
2249
|
+
}
|
|
2250
|
+
catch (error) {
|
|
2251
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2252
|
+
level: "warn",
|
|
2253
|
+
component: "daemon",
|
|
2254
|
+
event: "daemon.cli_update_check_error",
|
|
2255
|
+
message: "CLI update check failed",
|
|
2256
|
+
meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
|
|
2257
|
+
});
|
|
2258
|
+
}
|
|
2259
|
+
/* v8 ignore stop */
|
|
2260
|
+
if (pendingReExec) {
|
|
2261
|
+
deps.reExecFromNewVersion(args);
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
983
2264
|
await performSystemSetup(deps);
|
|
2265
|
+
const linkedVersionAfterSetup = deps.getCurrentCliVersion?.() ?? null;
|
|
2266
|
+
const runtimeVersion = (0, bundle_manifest_1.getPackageVersion)();
|
|
2267
|
+
if (linkedVersionBeforeUp && linkedVersionBeforeUp !== runtimeVersion && linkedVersionAfterSetup === runtimeVersion) {
|
|
2268
|
+
deps.writeStdout(`ouro updated to ${runtimeVersion} (was ${linkedVersionBeforeUp})`);
|
|
2269
|
+
const changelogCommand = (0, ouro_version_manager_1.buildChangelogCommand)(linkedVersionBeforeUp, runtimeVersion);
|
|
2270
|
+
if (changelogCommand) {
|
|
2271
|
+
deps.writeStdout(`review changes with: ${changelogCommand}`);
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
if (deps.ensureDaemonBootPersistence) {
|
|
2275
|
+
try {
|
|
2276
|
+
await Promise.resolve(deps.ensureDaemonBootPersistence(deps.socketPath));
|
|
2277
|
+
}
|
|
2278
|
+
catch (error) {
|
|
2279
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2280
|
+
level: "warn",
|
|
2281
|
+
component: "daemon",
|
|
2282
|
+
event: "daemon.system_setup_launchd_error",
|
|
2283
|
+
message: "failed to persist daemon boot startup",
|
|
2284
|
+
meta: { error: error instanceof Error ? error.message : String(error), socketPath: deps.socketPath },
|
|
2285
|
+
});
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
// Run update hooks before starting daemon so user sees the output
|
|
2289
|
+
(0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
|
|
2290
|
+
(0, update_hooks_1.registerUpdateHook)(agent_config_v2_1.agentConfigV2Hook);
|
|
2291
|
+
const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
|
|
2292
|
+
const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
|
|
2293
|
+
// Snapshot the previous CLI version from the first bundle-meta before
|
|
2294
|
+
// hooks overwrite it. This detects when npx downloaded a newer CLI.
|
|
2295
|
+
const previousCliVersion = readFirstBundleMetaVersion(bundlesRoot);
|
|
2296
|
+
const updateSummary = await (0, update_hooks_1.applyPendingUpdates)(bundlesRoot, currentVersion);
|
|
2297
|
+
// Notify about CLI binary update (npx downloaded a new version).
|
|
2298
|
+
// Skip when the symlink already points to the running version — that
|
|
2299
|
+
// means path 1 (checkForCliUpdate + reExecFromNewVersion) already
|
|
2300
|
+
// printed the update message before re-exec.
|
|
2301
|
+
/* v8 ignore start -- CLI update detection: tested via daemon-cli-version-detect.test.ts @preserve */
|
|
2302
|
+
if (previousCliVersion && previousCliVersion !== currentVersion && linkedVersionBeforeUp !== currentVersion) {
|
|
2303
|
+
deps.writeStdout(`ouro updated to ${currentVersion} (was ${previousCliVersion})`);
|
|
2304
|
+
const changelogCommand = (0, ouro_version_manager_1.buildChangelogCommand)(previousCliVersion, currentVersion);
|
|
2305
|
+
/* v8 ignore next -- buildChangelogCommand is non-null when previous/current runtime versions differ @preserve */
|
|
2306
|
+
if (changelogCommand) {
|
|
2307
|
+
deps.writeStdout(`review changes with: ${changelogCommand}`);
|
|
2308
|
+
}
|
|
2309
|
+
}
|
|
2310
|
+
/* v8 ignore stop */
|
|
2311
|
+
if (updateSummary.updated.length > 0) {
|
|
2312
|
+
const agents = updateSummary.updated.map((e) => e.agent);
|
|
2313
|
+
const from = updateSummary.updated[0].from;
|
|
2314
|
+
const to = updateSummary.updated[0].to;
|
|
2315
|
+
const fromStr = from ? ` (was ${from})` : "";
|
|
2316
|
+
const count = agents.length;
|
|
2317
|
+
deps.writeStdout(`updated ${count} agent${count === 1 ? "" : "s"} to runtime ${to}${fromStr}`);
|
|
2318
|
+
}
|
|
984
2319
|
const daemonResult = await ensureDaemonRunning(deps);
|
|
985
2320
|
deps.writeStdout(daemonResult.message);
|
|
986
2321
|
return daemonResult.message;
|
|
987
2322
|
}
|
|
2323
|
+
if (command.kind === "daemon.dev") {
|
|
2324
|
+
/* v8 ignore next -- defensive: existsSync always injected in tests @preserve */
|
|
2325
|
+
const checkExists = deps.existsSync ?? fs.existsSync;
|
|
2326
|
+
/* v8 ignore next -- repo resolution dispatched to v8-ignored helper @preserve */
|
|
2327
|
+
let repoCwd = resolveDevRepoCwd(command, checkExists, deps);
|
|
2328
|
+
let entryPath = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
|
|
2329
|
+
if (!checkExists(entryPath) || !checkExists(path.join(repoCwd, ".git"))) {
|
|
2330
|
+
if (command.repoPath) {
|
|
2331
|
+
// Explicit --repo-path didn't have a valid repo — error
|
|
2332
|
+
const message = `no harness repo found at ${repoCwd}. run npm run build first.`;
|
|
2333
|
+
deps.writeStdout(message);
|
|
2334
|
+
return message;
|
|
2335
|
+
}
|
|
2336
|
+
/* v8 ignore start -- auto-clone: interactive prompt + existing repo discovery + real git/npm @preserve */
|
|
2337
|
+
const defaultClonePath = path.join(os.homedir(), "Projects", "ouroboros");
|
|
2338
|
+
if (checkExists(path.join(defaultClonePath, ".git"))) {
|
|
2339
|
+
deps.writeStdout(`found existing repo at ${defaultClonePath}`);
|
|
2340
|
+
try {
|
|
2341
|
+
repoCwd = resolveClonePath({ clonePath: defaultClonePath }, checkExists, deps);
|
|
2342
|
+
entryPath = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
|
|
2343
|
+
}
|
|
2344
|
+
catch (err) {
|
|
2345
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2346
|
+
deps.writeStdout(message);
|
|
2347
|
+
return message;
|
|
2348
|
+
}
|
|
2349
|
+
}
|
|
2350
|
+
else if (deps.promptInput) {
|
|
2351
|
+
deps.writeStdout("no harness repo found.");
|
|
2352
|
+
const answer = await deps.promptInput(`already have a checkout? enter its path, or press enter to clone to ${defaultClonePath}: `);
|
|
2353
|
+
const cloneTarget = answer.trim() || defaultClonePath;
|
|
2354
|
+
try {
|
|
2355
|
+
repoCwd = resolveClonePath({ clonePath: cloneTarget }, checkExists, deps);
|
|
2356
|
+
entryPath = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
|
|
2357
|
+
}
|
|
2358
|
+
catch (err) {
|
|
2359
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2360
|
+
deps.writeStdout(message);
|
|
2361
|
+
return message;
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2364
|
+
else {
|
|
2365
|
+
const message = `no harness repo found. run: ouro dev --repo-path /path/to/ouroboros`;
|
|
2366
|
+
deps.writeStdout(message);
|
|
2367
|
+
return message;
|
|
2368
|
+
}
|
|
2369
|
+
/* v8 ignore stop */
|
|
2370
|
+
}
|
|
2371
|
+
// Auto-build: always rebuild in dev mode so dist/ matches source
|
|
2372
|
+
/* v8 ignore start -- dev auto-build: execSync in repo cwd, tested manually @preserve */
|
|
2373
|
+
deps.writeStdout(`building from ${repoCwd}...`);
|
|
2374
|
+
try {
|
|
2375
|
+
(0, child_process_1.execSync)("npm run build", { cwd: repoCwd, stdio: "inherit" });
|
|
2376
|
+
entryPath = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
|
|
2377
|
+
}
|
|
2378
|
+
catch {
|
|
2379
|
+
const message = `build failed in ${repoCwd}. fix compilation errors and retry.`;
|
|
2380
|
+
deps.writeStdout(message);
|
|
2381
|
+
return message;
|
|
2382
|
+
}
|
|
2383
|
+
/* v8 ignore stop */
|
|
2384
|
+
/* v8 ignore start -- defensive: ensureDaemonBootPersistence always injected in tests @preserve */
|
|
2385
|
+
if (deps.ensureDaemonBootPersistence) {
|
|
2386
|
+
try {
|
|
2387
|
+
await Promise.resolve(deps.ensureDaemonBootPersistence(deps.socketPath));
|
|
2388
|
+
/* v8 ignore next -- defensive: boot persistence error should not block dev mode @preserve */
|
|
2389
|
+
}
|
|
2390
|
+
catch (error) {
|
|
2391
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2392
|
+
level: "warn",
|
|
2393
|
+
component: "daemon",
|
|
2394
|
+
event: "daemon.dev_boot_persistence_error",
|
|
2395
|
+
message: "failed to persist daemon boot startup in dev mode",
|
|
2396
|
+
meta: { error: error instanceof Error ? error.message : String(error), socketPath: deps.socketPath },
|
|
2397
|
+
});
|
|
2398
|
+
}
|
|
2399
|
+
/* v8 ignore stop */
|
|
2400
|
+
}
|
|
2401
|
+
// Disable launchd KeepAlive before killing — prevents the installed daemon from respawning
|
|
2402
|
+
/* v8 ignore start -- dev launchd disable: requires real launchctl + plist on disk @preserve */
|
|
2403
|
+
const launchdDevDeps = {
|
|
2404
|
+
exec: (cmd) => { (0, child_process_1.execSync)(cmd); },
|
|
2405
|
+
existsFile: (p) => fs.existsSync(p),
|
|
2406
|
+
removeFile: (p) => { try {
|
|
2407
|
+
fs.unlinkSync(p);
|
|
2408
|
+
}
|
|
2409
|
+
catch { /* best effort */ } },
|
|
2410
|
+
homeDir: os.homedir(),
|
|
2411
|
+
userUid: process.getuid?.() ?? 0,
|
|
2412
|
+
};
|
|
2413
|
+
if ((0, launchd_1.isDaemonInstalled)(launchdDevDeps)) {
|
|
2414
|
+
(0, launchd_1.uninstallLaunchAgent)(launchdDevDeps);
|
|
2415
|
+
deps.writeStdout("disabled launchd auto-restart for dev mode");
|
|
2416
|
+
}
|
|
2417
|
+
/* v8 ignore stop */
|
|
2418
|
+
// Always force-restart in dev mode — you rebuilt, you want this code running
|
|
2419
|
+
/* v8 ignore start -- dev force-restart: socket alive/stop/spawn tested via integration; tests inject mocks @preserve */
|
|
2420
|
+
const alive = await deps.checkSocketAlive(deps.socketPath);
|
|
2421
|
+
if (alive) {
|
|
2422
|
+
try {
|
|
2423
|
+
await deps.sendCommand(deps.socketPath, { kind: "daemon.stop" });
|
|
2424
|
+
}
|
|
2425
|
+
catch { /* already stopping */ }
|
|
2426
|
+
}
|
|
2427
|
+
deps.cleanupStaleSocket(deps.socketPath);
|
|
2428
|
+
const devEntry = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
|
|
2429
|
+
const startDevDaemon = deps.startDaemonProcess === defaultStartDaemonProcess
|
|
2430
|
+
? async (sp) => {
|
|
2431
|
+
const child = (0, child_process_1.spawn)("node", [devEntry, "--socket", sp], { detached: true, stdio: "ignore" });
|
|
2432
|
+
child.unref();
|
|
2433
|
+
return { pid: child.pid ?? null };
|
|
2434
|
+
}
|
|
2435
|
+
: deps.startDaemonProcess;
|
|
2436
|
+
/* v8 ignore stop */
|
|
2437
|
+
const started = await startDevDaemon(deps.socketPath);
|
|
2438
|
+
/* v8 ignore next -- defensive: pid is null only when spawn fails silently @preserve */
|
|
2439
|
+
const message = `daemon running in dev mode from ${repoCwd} (pid ${started.pid ?? "unknown"})\nrun 'ouro up' to return to production mode`;
|
|
2440
|
+
deps.writeStdout(message);
|
|
2441
|
+
return message;
|
|
2442
|
+
}
|
|
2443
|
+
// ── rollback command (local, no daemon socket needed for symlinks) ──
|
|
2444
|
+
/* v8 ignore start -- rollback/versions: tested via daemon-cli-rollback/versions tests @preserve */
|
|
2445
|
+
if (command.kind === "rollback") {
|
|
2446
|
+
const currentVersion = deps.getCurrentCliVersion?.() ?? "unknown";
|
|
2447
|
+
if (command.version) {
|
|
2448
|
+
// Rollback to a specific version
|
|
2449
|
+
const installed = deps.listCliVersions?.() ?? [];
|
|
2450
|
+
if (!installed.includes(command.version)) {
|
|
2451
|
+
try {
|
|
2452
|
+
await deps.installCliVersion(command.version);
|
|
2453
|
+
}
|
|
2454
|
+
catch (error) {
|
|
2455
|
+
const message = `failed to install version ${command.version}: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
|
|
2456
|
+
deps.writeStdout(message);
|
|
2457
|
+
return message;
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
deps.activateCliVersion(command.version);
|
|
2461
|
+
}
|
|
2462
|
+
else {
|
|
2463
|
+
// Rollback to previous version
|
|
2464
|
+
const previousVersion = deps.getPreviousCliVersion?.();
|
|
2465
|
+
if (!previousVersion) {
|
|
2466
|
+
const message = "no previous version to roll back to";
|
|
2467
|
+
deps.writeStdout(message);
|
|
2468
|
+
return message;
|
|
2469
|
+
}
|
|
2470
|
+
deps.activateCliVersion(previousVersion);
|
|
2471
|
+
command = { ...command, version: previousVersion };
|
|
2472
|
+
}
|
|
2473
|
+
// Stop daemon (non-fatal if not running)
|
|
2474
|
+
try {
|
|
2475
|
+
await deps.sendCommand(deps.socketPath, { kind: "daemon.stop" });
|
|
2476
|
+
}
|
|
2477
|
+
catch {
|
|
2478
|
+
// Daemon may not be running — that's fine
|
|
2479
|
+
}
|
|
2480
|
+
const message = `rolled back to ${command.version} (was ${currentVersion})`;
|
|
2481
|
+
deps.writeStdout(message);
|
|
2482
|
+
return message;
|
|
2483
|
+
}
|
|
2484
|
+
// ── versions command (local install list + published update truth, no daemon socket needed) ──
|
|
2485
|
+
if (command.kind === "versions") {
|
|
2486
|
+
const versions = deps.listCliVersions?.() ?? [];
|
|
2487
|
+
const current = deps.getCurrentCliVersion?.();
|
|
2488
|
+
const previous = deps.getPreviousCliVersion?.();
|
|
2489
|
+
const localSection = versions.length === 0
|
|
2490
|
+
? "no versions installed"
|
|
2491
|
+
: versions.map((v) => {
|
|
2492
|
+
let line = v;
|
|
2493
|
+
if (v === current)
|
|
2494
|
+
line += " * current";
|
|
2495
|
+
if (v === previous)
|
|
2496
|
+
line += " (previous)";
|
|
2497
|
+
return line;
|
|
2498
|
+
}).join("\n");
|
|
2499
|
+
const sections = [localSection];
|
|
2500
|
+
if (deps.checkForCliUpdate) {
|
|
2501
|
+
try {
|
|
2502
|
+
const updateResult = await deps.checkForCliUpdate();
|
|
2503
|
+
if (updateResult.latestVersion) {
|
|
2504
|
+
sections.push(`published alpha: ${updateResult.latestVersion} (${updateResult.available ? "update available" : "up to date"})`);
|
|
2505
|
+
}
|
|
2506
|
+
else if (updateResult.error) {
|
|
2507
|
+
sections.push(`published alpha: unavailable (${updateResult.error})`);
|
|
2508
|
+
}
|
|
2509
|
+
}
|
|
2510
|
+
catch (err) {
|
|
2511
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
2512
|
+
sections.push(`published alpha: unavailable (${reason})`);
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
2515
|
+
const message = sections.join("\n\n");
|
|
2516
|
+
deps.writeStdout(message);
|
|
2517
|
+
return message;
|
|
2518
|
+
}
|
|
2519
|
+
/* v8 ignore stop */
|
|
988
2520
|
if (command.kind === "daemon.logs" && deps.tailLogs) {
|
|
989
2521
|
deps.tailLogs();
|
|
990
2522
|
return "";
|
|
991
2523
|
}
|
|
992
|
-
if (command.kind === "
|
|
993
|
-
|
|
994
|
-
|
|
2524
|
+
if (command.kind === "outlook") {
|
|
2525
|
+
let status;
|
|
2526
|
+
try {
|
|
2527
|
+
status = await deps.sendCommand(deps.socketPath, { kind: "daemon.status" });
|
|
2528
|
+
/* v8 ignore start — error path: daemon not running */
|
|
2529
|
+
}
|
|
2530
|
+
catch {
|
|
2531
|
+
const message = "daemon unavailable — start with `ouro up` first";
|
|
2532
|
+
deps.writeStdout(message);
|
|
2533
|
+
return message;
|
|
2534
|
+
}
|
|
2535
|
+
/* v8 ignore stop */
|
|
2536
|
+
const payload = parseStatusPayload(status.data);
|
|
2537
|
+
/* v8 ignore start -- ?? branch: outlookUrl always present in test fixtures */
|
|
2538
|
+
const outlookUrl = payload?.overview.outlookUrl ?? "unavailable";
|
|
2539
|
+
/* v8 ignore stop */
|
|
2540
|
+
if (!command.json) {
|
|
2541
|
+
deps.writeStdout(outlookUrl);
|
|
2542
|
+
return outlookUrl;
|
|
2543
|
+
}
|
|
2544
|
+
/* v8 ignore start — error path: outlook URL not available */
|
|
2545
|
+
if (outlookUrl === "unavailable") {
|
|
2546
|
+
deps.writeStdout(outlookUrl);
|
|
2547
|
+
return outlookUrl;
|
|
2548
|
+
}
|
|
2549
|
+
/* v8 ignore stop */
|
|
2550
|
+
/* v8 ignore start -- ?? branch: tests always inject fetchImpl */
|
|
2551
|
+
const fetchImpl = deps.fetchImpl ?? fetch;
|
|
2552
|
+
/* v8 ignore stop */
|
|
2553
|
+
const response = await fetchImpl(`${outlookUrl}/api/machine`);
|
|
2554
|
+
const data = await response.json();
|
|
2555
|
+
const text = JSON.stringify(data, null, 2);
|
|
2556
|
+
deps.writeStdout(text);
|
|
2557
|
+
return text;
|
|
2558
|
+
}
|
|
2559
|
+
// ── hook: handle Claude Code lifecycle hooks ──
|
|
2560
|
+
/* v8 ignore start -- hook handler: reads real stdin, sends to real daemon @preserve */
|
|
2561
|
+
if (command.kind === "hook") {
|
|
2562
|
+
let stdinData = "";
|
|
2563
|
+
try {
|
|
2564
|
+
stdinData = require("fs").readFileSync(0, "utf-8");
|
|
2565
|
+
}
|
|
2566
|
+
catch { /* no stdin */ }
|
|
2567
|
+
let event = {};
|
|
2568
|
+
try {
|
|
2569
|
+
event = JSON.parse(stdinData);
|
|
2570
|
+
}
|
|
2571
|
+
catch { /* malformed */ }
|
|
2572
|
+
const eventType = command.event;
|
|
2573
|
+
const sessionId = event.session_id ?? "unknown";
|
|
2574
|
+
const cwd = event.cwd ?? "";
|
|
2575
|
+
// Build notification content based on event type
|
|
2576
|
+
let content;
|
|
2577
|
+
if (eventType === "session-start") {
|
|
2578
|
+
const model = event.model ?? "";
|
|
2579
|
+
const source = event.source ?? "";
|
|
2580
|
+
content = `[Claude Code session started: ${sessionId}, cwd: ${cwd}${model ? `, model: ${model}` : ""}${source ? `, source: ${source}` : ""}]`;
|
|
2581
|
+
}
|
|
2582
|
+
else if (eventType === "stop") {
|
|
2583
|
+
const lastMsg = event.last_assistant_message ?? "";
|
|
2584
|
+
content = `[Claude Code session ended: ${sessionId}${lastMsg ? `, last: ${lastMsg.slice(0, 200)}` : ""}]`;
|
|
2585
|
+
}
|
|
2586
|
+
else if (eventType === "post-tool-use") {
|
|
2587
|
+
const toolName = event.tool_name ?? "";
|
|
2588
|
+
content = `[Claude Code used ${toolName} in session ${sessionId}]`;
|
|
2589
|
+
}
|
|
2590
|
+
else {
|
|
2591
|
+
content = `[Claude Code hook: ${eventType} in session ${sessionId}]`;
|
|
2592
|
+
}
|
|
2593
|
+
// Send to the specific agent configured for this hook
|
|
2594
|
+
try {
|
|
2595
|
+
await deps.sendCommand(deps.socketPath, { kind: "message.send", from: `claude-code:${sessionId}`, to: command.agent, content }).catch(() => { });
|
|
2596
|
+
await deps.sendCommand(deps.socketPath, { kind: "inner.wake", agent: command.agent }).catch(() => { });
|
|
2597
|
+
}
|
|
2598
|
+
catch { /* daemon not running — silent */ }
|
|
2599
|
+
// Output for Claude Code hook system
|
|
2600
|
+
deps.writeStdout(JSON.stringify({ continue: true }));
|
|
2601
|
+
return JSON.stringify({ continue: true });
|
|
2602
|
+
}
|
|
2603
|
+
/* v8 ignore stop */
|
|
2604
|
+
// ── setup: configure dev tool integration ──
|
|
2605
|
+
if (command.kind === "setup") {
|
|
2606
|
+
const { tool, agent: setupAgent } = command;
|
|
2607
|
+
const sourceRoot = (0, identity_1.getRepoRoot)();
|
|
2608
|
+
const runtimeMode = (0, runtime_mode_1.detectRuntimeMode)(sourceRoot);
|
|
2609
|
+
const mcpServeCommand = runtimeMode === "dev"
|
|
2610
|
+
? `node ${path.join(sourceRoot, "dist", "heart", "daemon", "ouro-bot-entry.js")} mcp-serve --agent ${setupAgent}`
|
|
2611
|
+
: `ouro mcp-serve --agent ${setupAgent}`;
|
|
2612
|
+
if (tool === "claude-code") {
|
|
2613
|
+
// 1. Register MCP server with Claude Code
|
|
2614
|
+
const mcpAddCmd = `claude mcp add ouro-${setupAgent} -s user -- ${mcpServeCommand}`;
|
|
2615
|
+
(0, child_process_1.execSync)(mcpAddCmd, { stdio: "pipe" });
|
|
2616
|
+
// 2. Write hooks config to ~/.claude/settings.json
|
|
2617
|
+
const settingsPath = path.join(os.homedir(), ".claude", "settings.json");
|
|
2618
|
+
let settings = {};
|
|
2619
|
+
if (fs.existsSync(settingsPath)) {
|
|
2620
|
+
try {
|
|
2621
|
+
settings = JSON.parse(fs.readFileSync(settingsPath, "utf-8"));
|
|
2622
|
+
}
|
|
2623
|
+
catch { /* start fresh */ }
|
|
2624
|
+
}
|
|
2625
|
+
// Use `ouro hook <event>` — resolves the right code based on dev vs installed mode.
|
|
2626
|
+
// Bare `ouro` works because ouro is on PATH via ~/.ouro-cli/bin/.
|
|
2627
|
+
settings.hooks = {
|
|
2628
|
+
...(settings.hooks ?? {}),
|
|
2629
|
+
SessionStart: [{ hooks: [{ type: "command", command: `ouro hook session-start --agent ${setupAgent}`, timeout: 5 }] }],
|
|
2630
|
+
Stop: [{ hooks: [{ type: "command", command: `ouro hook stop --agent ${setupAgent}`, timeout: 5 }] }],
|
|
2631
|
+
PostToolUse: [{ matcher: "Bash|Edit|Write", hooks: [{ type: "command", command: `ouro hook post-tool-use --agent ${setupAgent}`, timeout: 5 }] }],
|
|
2632
|
+
};
|
|
2633
|
+
fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
|
|
2634
|
+
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
|
|
2635
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2636
|
+
component: "daemon",
|
|
2637
|
+
event: "daemon.setup_complete",
|
|
2638
|
+
message: "dev tool setup complete",
|
|
2639
|
+
meta: { tool, agent: setupAgent, runtimeMode },
|
|
2640
|
+
});
|
|
2641
|
+
// 3. Write conversation formatting instructions to ~/.claude/CLAUDE.md
|
|
2642
|
+
const claudeMdPath = path.join(os.homedir(), ".claude", "CLAUDE.md");
|
|
2643
|
+
const agentInstructions = `\n## Agent conversations (ouro)\nWhen using MCP \`send_message\` to talk to an ouro agent, format the exchange clearly:\n- Before the tool call, briefly say what you're asking/telling the agent\n- After the response, quote the agent's reply in a blockquote, then add your reaction\n- Example: **Me → Agent:** "question" / > **Agent:** "response" / Your synthesis here\n`;
|
|
2644
|
+
let existingClaudeMd = "";
|
|
2645
|
+
if (fs.existsSync(claudeMdPath)) {
|
|
2646
|
+
existingClaudeMd = fs.readFileSync(claudeMdPath, "utf-8");
|
|
2647
|
+
}
|
|
2648
|
+
if (!existingClaudeMd.includes("Agent conversations (ouro)")) {
|
|
2649
|
+
fs.writeFileSync(claudeMdPath, existingClaudeMd + agentInstructions);
|
|
2650
|
+
}
|
|
2651
|
+
const message = `setup complete: claude-code + ${setupAgent}\n MCP server registered\n hooks configured\n conversation formatting instructions added`;
|
|
2652
|
+
deps.writeStdout(message);
|
|
2653
|
+
return message;
|
|
2654
|
+
}
|
|
2655
|
+
else {
|
|
2656
|
+
// tool === "codex" (parseSetupCommand validates tool, so this is the only remaining option)
|
|
2657
|
+
const mcpAddCmd = `codex mcp add ouro-${setupAgent} -- ${mcpServeCommand}`;
|
|
2658
|
+
(0, child_process_1.execSync)(mcpAddCmd, { stdio: "pipe" });
|
|
2659
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2660
|
+
component: "daemon",
|
|
2661
|
+
event: "daemon.setup_complete",
|
|
2662
|
+
message: "dev tool setup complete",
|
|
2663
|
+
meta: { tool, agent: setupAgent, runtimeMode },
|
|
2664
|
+
});
|
|
2665
|
+
const message = `setup complete: codex + ${setupAgent}\n MCP server registered`;
|
|
2666
|
+
deps.writeStdout(message);
|
|
2667
|
+
return message;
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
/* v8 ignore start — mcp-serve block binds to process.stdin/stdout; tested via mcp-server unit tests */
|
|
2671
|
+
// ── mcp-serve: start MCP server in-process on stdin/stdout ──
|
|
2672
|
+
if (command.kind === "mcp-serve") {
|
|
2673
|
+
const { createMcpServer } = await Promise.resolve().then(() => __importStar(require("./mcp-server")));
|
|
2674
|
+
const friendId = command.friendId ?? `local-${os.userInfo().username}`;
|
|
2675
|
+
const mcpSocketPath = command.socketOverride ?? deps.socketPath;
|
|
2676
|
+
const server = createMcpServer({
|
|
2677
|
+
agent: command.agent,
|
|
2678
|
+
friendId,
|
|
2679
|
+
socketPath: mcpSocketPath,
|
|
2680
|
+
stdin: process.stdin,
|
|
2681
|
+
stdout: process.stdout,
|
|
2682
|
+
});
|
|
2683
|
+
server.start();
|
|
2684
|
+
(0, runtime_1.emitNervesEvent)({
|
|
2685
|
+
component: "daemon",
|
|
2686
|
+
event: "daemon.mcp_serve_started",
|
|
2687
|
+
message: "MCP server started via CLI",
|
|
2688
|
+
meta: { agent: command.agent, friendId },
|
|
2689
|
+
});
|
|
2690
|
+
// Keep process alive until stdin closes
|
|
2691
|
+
await new Promise((resolve) => {
|
|
2692
|
+
process.stdin.on("end", () => {
|
|
2693
|
+
server.stop();
|
|
2694
|
+
resolve();
|
|
2695
|
+
});
|
|
2696
|
+
});
|
|
2697
|
+
return "";
|
|
2698
|
+
}
|
|
2699
|
+
/* v8 ignore stop */
|
|
2700
|
+
// ── mcp subcommands (routed through daemon socket) ──
|
|
2701
|
+
if (command.kind === "mcp.list" || command.kind === "mcp.call") {
|
|
2702
|
+
const daemonCommand = toDaemonCommand(command);
|
|
2703
|
+
let response;
|
|
2704
|
+
try {
|
|
2705
|
+
response = await deps.sendCommand(deps.socketPath, daemonCommand);
|
|
2706
|
+
}
|
|
2707
|
+
catch {
|
|
2708
|
+
const message = "daemon unavailable — start with `ouro up` first";
|
|
2709
|
+
deps.writeStdout(message);
|
|
2710
|
+
return message;
|
|
2711
|
+
}
|
|
2712
|
+
if (!response.ok) {
|
|
2713
|
+
const message = response.error ?? "unknown error";
|
|
2714
|
+
deps.writeStdout(message);
|
|
2715
|
+
return message;
|
|
2716
|
+
}
|
|
2717
|
+
const message = formatMcpResponse(command, response);
|
|
2718
|
+
deps.writeStdout(message);
|
|
2719
|
+
return message;
|
|
2720
|
+
}
|
|
2721
|
+
// ── task subcommands (local, no daemon socket needed) ──
|
|
2722
|
+
if (command.kind === "task.board" || command.kind === "task.create" || command.kind === "task.update" ||
|
|
2723
|
+
command.kind === "task.show" || command.kind === "task.actionable" || command.kind === "task.deps" ||
|
|
2724
|
+
command.kind === "task.sessions" || command.kind === "task.fix") {
|
|
2725
|
+
/* v8 ignore start -- production default: requires full identity setup @preserve */
|
|
2726
|
+
const taskMod = deps.taskModule ?? (0, tasks_1.getTaskModule)();
|
|
2727
|
+
/* v8 ignore stop */
|
|
2728
|
+
const message = executeTaskCommand(command, taskMod);
|
|
995
2729
|
deps.writeStdout(message);
|
|
996
2730
|
return message;
|
|
997
2731
|
}
|
|
2732
|
+
// ── reminder subcommands (local, no daemon socket needed) ──
|
|
2733
|
+
if (command.kind === "reminder.create") {
|
|
2734
|
+
/* v8 ignore start -- production default: requires full identity setup @preserve */
|
|
2735
|
+
const taskMod = deps.taskModule ?? (0, tasks_1.getTaskModule)();
|
|
2736
|
+
/* v8 ignore stop */
|
|
2737
|
+
const message = executeReminderCommand(command, taskMod);
|
|
2738
|
+
deps.writeStdout(message);
|
|
2739
|
+
return message;
|
|
2740
|
+
}
|
|
2741
|
+
// ── habit subcommands (local, no daemon socket needed) ──
|
|
2742
|
+
if (command.kind === "habit.list" || command.kind === "habit.create") {
|
|
2743
|
+
const { parseHabitFile, renderHabitFile } = await Promise.resolve().then(() => __importStar(require("./habit-parser")));
|
|
2744
|
+
/* v8 ignore start -- production default: uses real bundle root @preserve */
|
|
2745
|
+
const agentName = command.agent ?? (0, identity_1.getAgentName)();
|
|
2746
|
+
const bundleRoot = deps.agentBundleRoot ?? path.join((0, identity_1.getAgentBundlesRoot)(), `${agentName}.ouro`);
|
|
2747
|
+
/* v8 ignore stop */
|
|
2748
|
+
const habitsDir = path.join(bundleRoot, "habits");
|
|
2749
|
+
if (command.kind === "habit.list") {
|
|
2750
|
+
let files;
|
|
2751
|
+
try {
|
|
2752
|
+
files = fs.readdirSync(habitsDir).filter((f) => f.endsWith(".md") && f !== "README.md");
|
|
2753
|
+
}
|
|
2754
|
+
catch {
|
|
2755
|
+
const message = "no habits found";
|
|
2756
|
+
deps.writeStdout(message);
|
|
2757
|
+
return message;
|
|
2758
|
+
}
|
|
2759
|
+
if (files.length === 0) {
|
|
2760
|
+
const message = "no habits found";
|
|
2761
|
+
deps.writeStdout(message);
|
|
2762
|
+
return message;
|
|
2763
|
+
}
|
|
2764
|
+
const lines = [];
|
|
2765
|
+
for (const file of files) {
|
|
2766
|
+
const content = fs.readFileSync(path.join(habitsDir, file), "utf-8");
|
|
2767
|
+
const habit = parseHabitFile(content, path.join(habitsDir, file));
|
|
2768
|
+
const lastRunStr = habit.lastRun ?? "never";
|
|
2769
|
+
lines.push(`${habit.name} cadence=${habit.cadence ?? "none"} status=${habit.status} lastRun=${lastRunStr}`);
|
|
2770
|
+
}
|
|
2771
|
+
const message = lines.join("\n");
|
|
2772
|
+
deps.writeStdout(message);
|
|
2773
|
+
return message;
|
|
2774
|
+
}
|
|
2775
|
+
// habit.create
|
|
2776
|
+
const filePath = path.join(habitsDir, `${command.name}.md`);
|
|
2777
|
+
if (fs.existsSync(filePath)) {
|
|
2778
|
+
const message = `error: habit '${command.name}' already exists`;
|
|
2779
|
+
deps.writeStdout(message);
|
|
2780
|
+
return message;
|
|
2781
|
+
}
|
|
2782
|
+
fs.mkdirSync(habitsDir, { recursive: true });
|
|
2783
|
+
const now = new Date().toISOString();
|
|
2784
|
+
const content = renderHabitFile({
|
|
2785
|
+
title: command.name,
|
|
2786
|
+
cadence: command.cadence ?? "null",
|
|
2787
|
+
status: "active",
|
|
2788
|
+
lastRun: now,
|
|
2789
|
+
created: now,
|
|
2790
|
+
}, `Habit: ${command.name}`);
|
|
2791
|
+
fs.writeFileSync(filePath, content, "utf-8");
|
|
2792
|
+
const message = `created: ${filePath}`;
|
|
2793
|
+
deps.writeStdout(message);
|
|
2794
|
+
return message;
|
|
2795
|
+
}
|
|
2796
|
+
// ── friend subcommands (local, no daemon socket needed) ──
|
|
2797
|
+
if (command.kind === "friend.list" || command.kind === "friend.show" || command.kind === "friend.create" ||
|
|
2798
|
+
command.kind === "friend.update" || command.kind === "friend.link" || command.kind === "friend.unlink") {
|
|
2799
|
+
/* v8 ignore start -- production default: requires full identity setup @preserve */
|
|
2800
|
+
let store = deps.friendStore;
|
|
2801
|
+
if (!store) {
|
|
2802
|
+
// Derive agent-scoped friends dir from --agent flag or link/unlink's agent field
|
|
2803
|
+
const agentName = ("agent" in command && command.agent) ? command.agent : undefined;
|
|
2804
|
+
const friendsDir = agentName
|
|
2805
|
+
? path.join((0, identity_1.getAgentBundlesRoot)(), `${agentName}.ouro`, "friends")
|
|
2806
|
+
: path.join((0, identity_1.getAgentBundlesRoot)(), "friends");
|
|
2807
|
+
store = new store_file_1.FileFriendStore(friendsDir);
|
|
2808
|
+
}
|
|
2809
|
+
/* v8 ignore stop */
|
|
2810
|
+
const message = await executeFriendCommand(command, store);
|
|
2811
|
+
deps.writeStdout(message);
|
|
2812
|
+
return message;
|
|
2813
|
+
}
|
|
2814
|
+
// ── auth (local, no daemon socket needed) ──
|
|
2815
|
+
if (command.kind === "auth.run") {
|
|
2816
|
+
const provider = command.provider ?? (0, auth_flow_1.readAgentConfigForAgent)(command.agent).config.humanFacing.provider;
|
|
2817
|
+
/* v8 ignore next -- tests always inject runAuthFlow; default is for production @preserve */
|
|
2818
|
+
const authRunner = deps.runAuthFlow ?? auth_flow_1.runRuntimeAuthFlow;
|
|
2819
|
+
const result = await authRunner({
|
|
2820
|
+
agentName: command.agent,
|
|
2821
|
+
provider,
|
|
2822
|
+
promptInput: deps.promptInput,
|
|
2823
|
+
});
|
|
2824
|
+
// Behavior: ouro auth stores credentials only — does NOT switch provider.
|
|
2825
|
+
// Use `ouro auth switch` to change the active provider.
|
|
2826
|
+
deps.writeStdout(result.message);
|
|
2827
|
+
// Verify the credentials actually work by pinging the provider
|
|
2828
|
+
/* v8 ignore start -- integration: real API ping after auth @preserve */
|
|
2829
|
+
try {
|
|
2830
|
+
const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
|
|
2831
|
+
const status = await verifyProviderCredentials(provider, secrets.providers);
|
|
2832
|
+
deps.writeStdout(`${provider}: ${status}`);
|
|
2833
|
+
}
|
|
2834
|
+
catch {
|
|
2835
|
+
// Verification failure is non-blocking — credentials were saved regardless
|
|
2836
|
+
}
|
|
2837
|
+
/* v8 ignore stop */
|
|
2838
|
+
return result.message;
|
|
2839
|
+
}
|
|
2840
|
+
// ── auth verify (local, no daemon socket needed) ──
|
|
2841
|
+
/* v8 ignore start -- auth verify/switch: tested in daemon-cli.test.ts but v8 traces differ in CI @preserve */
|
|
2842
|
+
if (command.kind === "auth.verify") {
|
|
2843
|
+
const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
|
|
2844
|
+
const providers = secrets.providers;
|
|
2845
|
+
if (command.provider) {
|
|
2846
|
+
const status = await verifyProviderCredentials(command.provider, providers);
|
|
2847
|
+
const message = `${command.provider}: ${status}`;
|
|
2848
|
+
deps.writeStdout(message);
|
|
2849
|
+
return message;
|
|
2850
|
+
}
|
|
2851
|
+
const lines = [];
|
|
2852
|
+
for (const p of Object.keys(providers)) {
|
|
2853
|
+
const status = await verifyProviderCredentials(p, providers);
|
|
2854
|
+
lines.push(`${p}: ${status}`);
|
|
2855
|
+
}
|
|
2856
|
+
const message = lines.join("\n");
|
|
2857
|
+
deps.writeStdout(message);
|
|
2858
|
+
return message;
|
|
2859
|
+
}
|
|
2860
|
+
// ── auth switch (local, no daemon socket needed) ──
|
|
2861
|
+
if (command.kind === "auth.switch") {
|
|
2862
|
+
const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
|
|
2863
|
+
const providerSecrets = secrets.providers[command.provider];
|
|
2864
|
+
if (!providerSecrets || !hasStoredCredentials(command.provider, providerSecrets)) {
|
|
2865
|
+
const message = `no credentials stored for ${command.provider}. Run \`ouro auth --agent ${command.agent} --provider ${command.provider}\` first.`;
|
|
2866
|
+
deps.writeStdout(message);
|
|
2867
|
+
return message;
|
|
2868
|
+
}
|
|
2869
|
+
// Verify credentials actually work before switching
|
|
2870
|
+
const status = await verifyProviderCredentials(command.provider, secrets.providers);
|
|
2871
|
+
if (!status.startsWith("ok")) {
|
|
2872
|
+
const message = `${command.provider}: ${status}. fix credentials with \`ouro auth --agent ${command.agent} --provider ${command.provider}\` before switching.`;
|
|
2873
|
+
deps.writeStdout(message);
|
|
2874
|
+
return message;
|
|
2875
|
+
}
|
|
2876
|
+
if (command.facing) {
|
|
2877
|
+
(0, auth_flow_1.writeAgentProviderSelection)(command.agent, command.facing, command.provider);
|
|
2878
|
+
}
|
|
2879
|
+
else {
|
|
2880
|
+
(0, auth_flow_1.writeAgentProviderSelection)(command.agent, "human", command.provider);
|
|
2881
|
+
(0, auth_flow_1.writeAgentProviderSelection)(command.agent, "agent", command.provider);
|
|
2882
|
+
}
|
|
2883
|
+
const message = `switched ${command.agent} to ${command.provider} (verified working)`;
|
|
2884
|
+
deps.writeStdout(message);
|
|
2885
|
+
return message;
|
|
2886
|
+
}
|
|
2887
|
+
/* v8 ignore stop */
|
|
2888
|
+
// ── config models (local, no daemon socket needed) ──
|
|
2889
|
+
/* v8 ignore start -- config models: tested via daemon-cli.test.ts @preserve */
|
|
2890
|
+
if (command.kind === "config.models") {
|
|
2891
|
+
const { config } = (0, auth_flow_1.readAgentConfigForAgent)(command.agent);
|
|
2892
|
+
const provider = config.humanFacing.provider;
|
|
2893
|
+
if (provider !== "github-copilot") {
|
|
2894
|
+
const message = `model listing not available for ${provider} — check provider documentation.`;
|
|
2895
|
+
deps.writeStdout(message);
|
|
2896
|
+
return message;
|
|
2897
|
+
}
|
|
2898
|
+
const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
|
|
2899
|
+
const ghConfig = secrets.providers["github-copilot"];
|
|
2900
|
+
if (!ghConfig.githubToken || !ghConfig.baseUrl) {
|
|
2901
|
+
throw new Error(`github-copilot credentials not configured. Run \`ouro auth --agent ${command.agent} --provider github-copilot\` first.`);
|
|
2902
|
+
}
|
|
2903
|
+
const fetchFn = deps.fetchImpl ?? fetch;
|
|
2904
|
+
const models = await listGithubCopilotModels(ghConfig.baseUrl, ghConfig.githubToken, fetchFn);
|
|
2905
|
+
if (models.length === 0) {
|
|
2906
|
+
const message = "no models found";
|
|
2907
|
+
deps.writeStdout(message);
|
|
2908
|
+
return message;
|
|
2909
|
+
}
|
|
2910
|
+
const lines = ["available models:"];
|
|
2911
|
+
for (const m of models) {
|
|
2912
|
+
const caps = m.capabilities?.length ? ` (${m.capabilities.join(", ")})` : "";
|
|
2913
|
+
lines.push(` ${m.id}${caps}`);
|
|
2914
|
+
}
|
|
2915
|
+
const message = lines.join("\n");
|
|
2916
|
+
deps.writeStdout(message);
|
|
2917
|
+
return message;
|
|
2918
|
+
}
|
|
2919
|
+
/* v8 ignore stop */
|
|
2920
|
+
// ── config model (local, no daemon socket needed) ──
|
|
2921
|
+
/* v8 ignore start -- config model: tested via daemon-cli.test.ts @preserve */
|
|
2922
|
+
if (command.kind === "config.model") {
|
|
2923
|
+
const facing = command.facing ?? "human";
|
|
2924
|
+
// Validate model availability for github-copilot before writing
|
|
2925
|
+
const { config } = (0, auth_flow_1.readAgentConfigForAgent)(command.agent);
|
|
2926
|
+
const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
|
|
2927
|
+
if (facingConfig.provider === "github-copilot") {
|
|
2928
|
+
const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
|
|
2929
|
+
const ghConfig = secrets.providers["github-copilot"];
|
|
2930
|
+
if (ghConfig.githubToken && ghConfig.baseUrl) {
|
|
2931
|
+
const fetchFn = deps.fetchImpl ?? fetch;
|
|
2932
|
+
try {
|
|
2933
|
+
const models = await listGithubCopilotModels(ghConfig.baseUrl, ghConfig.githubToken, fetchFn);
|
|
2934
|
+
const available = models.map((m) => m.id);
|
|
2935
|
+
if (available.length > 0 && !available.includes(command.modelName)) {
|
|
2936
|
+
const message = `model '${command.modelName}' not found. available models:\n${available.map((id) => ` ${id}`).join("\n")}`;
|
|
2937
|
+
deps.writeStdout(message);
|
|
2938
|
+
return message;
|
|
2939
|
+
}
|
|
2940
|
+
}
|
|
2941
|
+
catch {
|
|
2942
|
+
// Catalog validation failed — fall through to ping test
|
|
2943
|
+
}
|
|
2944
|
+
// Ping test: verify the model actually works before switching
|
|
2945
|
+
const pingResult = await pingGithubCopilotModel(ghConfig.baseUrl, ghConfig.githubToken, command.modelName, fetchFn);
|
|
2946
|
+
if (!pingResult.ok) {
|
|
2947
|
+
const message = `model '${command.modelName}' ping failed: ${pingResult.error}\nrun \`ouro config models --agent ${command.agent}\` to see available models.`;
|
|
2948
|
+
deps.writeStdout(message);
|
|
2949
|
+
return message;
|
|
2950
|
+
}
|
|
2951
|
+
}
|
|
2952
|
+
}
|
|
2953
|
+
const { provider, previousModel } = (0, auth_flow_1.writeAgentModel)(command.agent, facing, command.modelName);
|
|
2954
|
+
const message = previousModel
|
|
2955
|
+
? `updated ${command.agent} model on ${provider}: ${previousModel} → ${command.modelName}`
|
|
2956
|
+
: `set ${command.agent} model on ${provider}: ${command.modelName}`;
|
|
2957
|
+
deps.writeStdout(message);
|
|
2958
|
+
return message;
|
|
2959
|
+
}
|
|
2960
|
+
/* v8 ignore stop */
|
|
2961
|
+
// ── whoami (local, no daemon socket needed) ──
|
|
2962
|
+
if (command.kind === "whoami") {
|
|
2963
|
+
if (command.agent) {
|
|
2964
|
+
const agentRoot = path.join((0, identity_1.getAgentBundlesRoot)(), `${command.agent}.ouro`);
|
|
2965
|
+
const message = [
|
|
2966
|
+
`agent: ${command.agent}`,
|
|
2967
|
+
`home: ${agentRoot}`,
|
|
2968
|
+
`bones: ${(0, runtime_metadata_1.getRuntimeMetadata)().version}`,
|
|
2969
|
+
].join("\n");
|
|
2970
|
+
deps.writeStdout(message);
|
|
2971
|
+
return message;
|
|
2972
|
+
}
|
|
2973
|
+
/* v8 ignore start -- production default: requires full identity setup @preserve */
|
|
2974
|
+
try {
|
|
2975
|
+
const info = deps.whoamiInfo
|
|
2976
|
+
? deps.whoamiInfo()
|
|
2977
|
+
: {
|
|
2978
|
+
agentName: (0, identity_1.getAgentName)(),
|
|
2979
|
+
homePath: path.join((0, identity_1.getAgentBundlesRoot)(), `${(0, identity_1.getAgentName)()}.ouro`),
|
|
2980
|
+
bonesVersion: (0, runtime_metadata_1.getRuntimeMetadata)().version,
|
|
2981
|
+
};
|
|
2982
|
+
const message = [
|
|
2983
|
+
`agent: ${info.agentName}`,
|
|
2984
|
+
`home: ${info.homePath}`,
|
|
2985
|
+
`bones: ${info.bonesVersion}`,
|
|
2986
|
+
].join("\n");
|
|
2987
|
+
deps.writeStdout(message);
|
|
2988
|
+
return message;
|
|
2989
|
+
}
|
|
2990
|
+
catch {
|
|
2991
|
+
const message = "error: no agent context — use --agent <name> to specify";
|
|
2992
|
+
deps.writeStdout(message);
|
|
2993
|
+
return message;
|
|
2994
|
+
}
|
|
2995
|
+
/* v8 ignore stop */
|
|
2996
|
+
}
|
|
2997
|
+
// ── changelog (local, no daemon socket needed) ──
|
|
2998
|
+
if (command.kind === "changelog") {
|
|
2999
|
+
try {
|
|
3000
|
+
const changelogPath = deps.getChangelogPath
|
|
3001
|
+
? deps.getChangelogPath()
|
|
3002
|
+
: (0, bundle_manifest_1.getChangelogPath)();
|
|
3003
|
+
const raw = fs.readFileSync(changelogPath, "utf-8");
|
|
3004
|
+
const parsed = JSON.parse(raw);
|
|
3005
|
+
const entries = Array.isArray(parsed) ? parsed : (parsed.versions ?? []);
|
|
3006
|
+
let filtered = entries;
|
|
3007
|
+
if (command.from) {
|
|
3008
|
+
const fromVersion = command.from;
|
|
3009
|
+
filtered = entries.filter((e) => semver.valid(e.version) && semver.gt(e.version, fromVersion));
|
|
3010
|
+
}
|
|
3011
|
+
if (filtered.length === 0) {
|
|
3012
|
+
const message = "no changelog entries found.";
|
|
3013
|
+
deps.writeStdout(message);
|
|
3014
|
+
return message;
|
|
3015
|
+
}
|
|
3016
|
+
const lines = [];
|
|
3017
|
+
for (const entry of filtered) {
|
|
3018
|
+
lines.push(`## ${entry.version}${entry.date ? ` (${entry.date})` : ""}`);
|
|
3019
|
+
if (entry.changes) {
|
|
3020
|
+
for (const change of entry.changes) {
|
|
3021
|
+
lines.push(`- ${change}`);
|
|
3022
|
+
}
|
|
3023
|
+
}
|
|
3024
|
+
lines.push("");
|
|
3025
|
+
}
|
|
3026
|
+
const message = lines.join("\n").trim();
|
|
3027
|
+
deps.writeStdout(message);
|
|
3028
|
+
return message;
|
|
3029
|
+
}
|
|
3030
|
+
catch {
|
|
3031
|
+
const message = "no changelog entries found.";
|
|
3032
|
+
deps.writeStdout(message);
|
|
3033
|
+
return message;
|
|
3034
|
+
}
|
|
3035
|
+
}
|
|
3036
|
+
// ── thoughts (local, no daemon socket needed) ──
|
|
3037
|
+
if (command.kind === "thoughts") {
|
|
3038
|
+
try {
|
|
3039
|
+
const agentName = command.agent ?? (0, identity_1.getAgentName)();
|
|
3040
|
+
const agentRoot = path.join((0, identity_1.getAgentBundlesRoot)(), `${agentName}.ouro`);
|
|
3041
|
+
const sessionFilePath = (0, thoughts_1.getInnerDialogSessionPath)(agentRoot);
|
|
3042
|
+
if (command.json) {
|
|
3043
|
+
try {
|
|
3044
|
+
const raw = fs.readFileSync(sessionFilePath, "utf-8");
|
|
3045
|
+
deps.writeStdout(raw);
|
|
3046
|
+
return raw;
|
|
3047
|
+
}
|
|
3048
|
+
catch {
|
|
3049
|
+
const message = "no inner dialog session found";
|
|
3050
|
+
deps.writeStdout(message);
|
|
3051
|
+
return message;
|
|
3052
|
+
}
|
|
3053
|
+
}
|
|
3054
|
+
const turns = (0, thoughts_1.parseInnerDialogSession)(sessionFilePath);
|
|
3055
|
+
const message = (0, thoughts_1.formatThoughtTurns)(turns, command.last ?? 10);
|
|
3056
|
+
deps.writeStdout(message);
|
|
3057
|
+
if (command.follow) {
|
|
3058
|
+
deps.writeStdout("\n\n--- following (ctrl+c to stop) ---\n");
|
|
3059
|
+
/* v8 ignore start -- callback tested via followThoughts unit tests @preserve */
|
|
3060
|
+
const stop = (0, thoughts_1.followThoughts)(sessionFilePath, (formatted) => {
|
|
3061
|
+
deps.writeStdout("\n" + formatted);
|
|
3062
|
+
});
|
|
3063
|
+
/* v8 ignore stop */
|
|
3064
|
+
// Block until process exit; cleanup watcher on SIGINT/SIGTERM
|
|
3065
|
+
return new Promise((resolve) => {
|
|
3066
|
+
const cleanup = () => { stop(); resolve(message); };
|
|
3067
|
+
process.once("SIGINT", cleanup);
|
|
3068
|
+
process.once("SIGTERM", cleanup);
|
|
3069
|
+
});
|
|
3070
|
+
}
|
|
3071
|
+
return message;
|
|
3072
|
+
}
|
|
3073
|
+
catch {
|
|
3074
|
+
const message = "error: no agent context — use --agent <name> to specify";
|
|
3075
|
+
deps.writeStdout(message);
|
|
3076
|
+
return message;
|
|
3077
|
+
}
|
|
3078
|
+
}
|
|
3079
|
+
// ── attention queue (local, no daemon socket needed) ──
|
|
3080
|
+
/* v8 ignore start -- CLI attention handler: requires real obligation store on disk @preserve */
|
|
3081
|
+
if (command.kind === "attention.list" || command.kind === "attention.show" || command.kind === "attention.history") {
|
|
3082
|
+
try {
|
|
3083
|
+
const agentName = command.agent ?? (0, identity_1.getAgentName)();
|
|
3084
|
+
const { listActiveObligations, readObligation } = await Promise.resolve().then(() => __importStar(require("../../mind/obligations")));
|
|
3085
|
+
if (command.kind === "attention.list") {
|
|
3086
|
+
const obligations = listActiveObligations(agentName);
|
|
3087
|
+
if (obligations.length === 0) {
|
|
3088
|
+
const message = "nothing held — attention queue is empty";
|
|
3089
|
+
deps.writeStdout(message);
|
|
3090
|
+
return message;
|
|
3091
|
+
}
|
|
3092
|
+
const lines = obligations.map((o) => `[${o.id}] ${o.origin.friendId} via ${o.origin.channel}/${o.origin.key} — ${o.delegatedContent.slice(0, 60)}${o.delegatedContent.length > 60 ? "..." : ""} (${o.status})`);
|
|
3093
|
+
const message = lines.join("\n");
|
|
3094
|
+
deps.writeStdout(message);
|
|
3095
|
+
return message;
|
|
3096
|
+
}
|
|
3097
|
+
if (command.kind === "attention.show") {
|
|
3098
|
+
const obligation = readObligation(agentName, command.id);
|
|
3099
|
+
if (!obligation) {
|
|
3100
|
+
const message = `no obligation found with id ${command.id}`;
|
|
3101
|
+
deps.writeStdout(message);
|
|
3102
|
+
return message;
|
|
3103
|
+
}
|
|
3104
|
+
const message = JSON.stringify(obligation, null, 2);
|
|
3105
|
+
deps.writeStdout(message);
|
|
3106
|
+
return message;
|
|
3107
|
+
}
|
|
3108
|
+
// attention.history: show returned obligations
|
|
3109
|
+
const { getObligationsDir } = await Promise.resolve().then(() => __importStar(require("../../mind/obligations")));
|
|
3110
|
+
const obligationsDir = getObligationsDir(agentName);
|
|
3111
|
+
let entries = [];
|
|
3112
|
+
try {
|
|
3113
|
+
entries = fs.readdirSync(obligationsDir);
|
|
3114
|
+
}
|
|
3115
|
+
catch { /* empty */ }
|
|
3116
|
+
const returned = entries
|
|
3117
|
+
.filter((e) => e.endsWith(".json"))
|
|
3118
|
+
.map((e) => { try {
|
|
3119
|
+
return JSON.parse(fs.readFileSync(path.join(obligationsDir, e), "utf-8"));
|
|
3120
|
+
}
|
|
3121
|
+
catch {
|
|
3122
|
+
return null;
|
|
3123
|
+
} })
|
|
3124
|
+
.filter((o) => o?.status === "returned")
|
|
3125
|
+
.sort((a, b) => (b.returnedAt ?? 0) - (a.returnedAt ?? 0))
|
|
3126
|
+
.slice(0, 20);
|
|
3127
|
+
if (returned.length === 0) {
|
|
3128
|
+
const message = "no surfacing history yet";
|
|
3129
|
+
deps.writeStdout(message);
|
|
3130
|
+
return message;
|
|
3131
|
+
}
|
|
3132
|
+
const lines = returned.map((o) => {
|
|
3133
|
+
const when = o.returnedAt ? new Date(o.returnedAt).toISOString() : "unknown";
|
|
3134
|
+
return `[${o.id}] → ${o.origin.friendId} via ${o.returnTarget ?? "unknown"} at ${when}`;
|
|
3135
|
+
});
|
|
3136
|
+
const message = lines.join("\n");
|
|
3137
|
+
deps.writeStdout(message);
|
|
3138
|
+
return message;
|
|
3139
|
+
}
|
|
3140
|
+
catch {
|
|
3141
|
+
const message = "error: no agent context — use --agent <name> to specify";
|
|
3142
|
+
deps.writeStdout(message);
|
|
3143
|
+
return message;
|
|
3144
|
+
}
|
|
3145
|
+
}
|
|
3146
|
+
/* v8 ignore stop */
|
|
3147
|
+
// ── inner dialog status (local, no daemon socket needed) ──
|
|
3148
|
+
/* v8 ignore start -- inner status handler: requires real agent state on disk @preserve */
|
|
3149
|
+
if (command.kind === "inner.status") {
|
|
3150
|
+
try {
|
|
3151
|
+
const agentName = command.agent ?? (0, identity_1.getAgentName)();
|
|
3152
|
+
const agentRoot = (0, identity_1.getAgentRoot)(agentName);
|
|
3153
|
+
const { buildInnerStatusOutput } = await Promise.resolve().then(() => __importStar(require("./inner-status")));
|
|
3154
|
+
const { sessionPath: getSessionPath } = await Promise.resolve().then(() => __importStar(require("../config")));
|
|
3155
|
+
const { parseCadenceToMs: parseCadenceMs, DEFAULT_CADENCE_MS } = await Promise.resolve().then(() => __importStar(require("./cadence")));
|
|
3156
|
+
const { parseFrontmatter } = await Promise.resolve().then(() => __importStar(require("../../repertoire/tasks/parser")));
|
|
3157
|
+
const { listActiveObligations } = await Promise.resolve().then(() => __importStar(require("../../mind/obligations")));
|
|
3158
|
+
// Read runtime state
|
|
3159
|
+
const innerSessionPath = getSessionPath("inner-dialog", "inner", "session");
|
|
3160
|
+
const runtimeJsonPath = path.join(path.dirname(innerSessionPath), "runtime.json");
|
|
3161
|
+
let runtimeState = null;
|
|
3162
|
+
try {
|
|
3163
|
+
const raw = fs.readFileSync(runtimeJsonPath, "utf-8");
|
|
3164
|
+
runtimeState = JSON.parse(raw);
|
|
3165
|
+
}
|
|
3166
|
+
catch { /* missing or corrupt — will show "unknown" */ }
|
|
3167
|
+
// Read journal files
|
|
3168
|
+
const journalDir = path.join(agentRoot, "journal");
|
|
3169
|
+
let journalFiles = [];
|
|
3170
|
+
try {
|
|
3171
|
+
const entries = fs.readdirSync(journalDir, { withFileTypes: true });
|
|
3172
|
+
journalFiles = entries
|
|
3173
|
+
.filter((e) => e.isFile() && !e.name.startsWith("."))
|
|
3174
|
+
.map((e) => {
|
|
3175
|
+
const stat = fs.statSync(path.join(journalDir, e.name));
|
|
3176
|
+
return { name: e.name, mtimeMs: stat.mtimeMs };
|
|
3177
|
+
});
|
|
3178
|
+
}
|
|
3179
|
+
catch { /* missing dir — will show (empty) */ }
|
|
3180
|
+
// Read heartbeat cadence
|
|
3181
|
+
let heartbeat = null;
|
|
3182
|
+
try {
|
|
3183
|
+
const habitsDir = path.join(agentRoot, "habits");
|
|
3184
|
+
const heartbeatPath = path.join(habitsDir, "heartbeat.md");
|
|
3185
|
+
let cadenceMs = DEFAULT_CADENCE_MS;
|
|
3186
|
+
if (fs.existsSync(heartbeatPath)) {
|
|
3187
|
+
const content = fs.readFileSync(heartbeatPath, "utf-8");
|
|
3188
|
+
const lines = content.split(/\r?\n/);
|
|
3189
|
+
if (lines[0]?.trim() === "---") {
|
|
3190
|
+
const closing = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
|
|
3191
|
+
if (closing !== -1) {
|
|
3192
|
+
const rawFrontmatter = lines.slice(1, closing).join("\n");
|
|
3193
|
+
const frontmatter = parseFrontmatter(rawFrontmatter);
|
|
3194
|
+
const parsed = parseCadenceMs(frontmatter.cadence);
|
|
3195
|
+
if (parsed !== null)
|
|
3196
|
+
cadenceMs = parsed;
|
|
3197
|
+
}
|
|
3198
|
+
}
|
|
3199
|
+
}
|
|
3200
|
+
let lastCompletedAt = null;
|
|
3201
|
+
if (runtimeState?.lastCompletedAt) {
|
|
3202
|
+
const ms = new Date(runtimeState.lastCompletedAt).getTime();
|
|
3203
|
+
if (!Number.isNaN(ms))
|
|
3204
|
+
lastCompletedAt = ms;
|
|
3205
|
+
}
|
|
3206
|
+
heartbeat = { cadenceMs, lastCompletedAt };
|
|
3207
|
+
}
|
|
3208
|
+
catch { /* no habits — heartbeat unknown */ }
|
|
3209
|
+
// Attention count
|
|
3210
|
+
const activeObligations = listActiveObligations(agentName);
|
|
3211
|
+
const message = buildInnerStatusOutput({
|
|
3212
|
+
agentName,
|
|
3213
|
+
runtimeState,
|
|
3214
|
+
journalFiles,
|
|
3215
|
+
heartbeat,
|
|
3216
|
+
attentionCount: activeObligations.length,
|
|
3217
|
+
now: Date.now(),
|
|
3218
|
+
});
|
|
3219
|
+
deps.writeStdout(message);
|
|
3220
|
+
return message;
|
|
3221
|
+
}
|
|
3222
|
+
catch {
|
|
3223
|
+
const message = "error: no agent context — use --agent <name> to specify";
|
|
3224
|
+
deps.writeStdout(message);
|
|
3225
|
+
return message;
|
|
3226
|
+
}
|
|
3227
|
+
}
|
|
3228
|
+
/* v8 ignore stop */
|
|
3229
|
+
// ── session list (local, no daemon socket needed) ──
|
|
3230
|
+
if (command.kind === "session.list") {
|
|
3231
|
+
/* v8 ignore start -- production default: requires full identity setup @preserve */
|
|
3232
|
+
const scanner = deps.scanSessions ?? (async () => []);
|
|
3233
|
+
/* v8 ignore stop */
|
|
3234
|
+
const sessions = await scanner();
|
|
3235
|
+
if (sessions.length === 0) {
|
|
3236
|
+
const message = "no active sessions";
|
|
3237
|
+
deps.writeStdout(message);
|
|
3238
|
+
return message;
|
|
3239
|
+
}
|
|
3240
|
+
const lines = sessions.map((s) => `${s.friendId} ${s.friendName} ${s.channel} ${s.lastActivity}`);
|
|
3241
|
+
const message = lines.join("\n");
|
|
3242
|
+
deps.writeStdout(message);
|
|
3243
|
+
return message;
|
|
3244
|
+
}
|
|
3245
|
+
if (command.kind === "chat.connect" && deps.startChat) {
|
|
3246
|
+
await ensureDaemonRunning(deps);
|
|
3247
|
+
await deps.startChat(command.agent);
|
|
3248
|
+
return "";
|
|
3249
|
+
}
|
|
998
3250
|
if (command.kind === "hatch.start") {
|
|
999
3251
|
// Route through adoption specialist when no explicit hatch args were provided
|
|
1000
3252
|
const hasExplicitHatchArgs = !!(command.agentName || command.humanName || command.provider || command.credentials);
|
|
@@ -1042,6 +3294,16 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
|
|
|
1042
3294
|
deps.writeStdout(message);
|
|
1043
3295
|
return message;
|
|
1044
3296
|
}
|
|
3297
|
+
if (command.kind === "daemon.status" && isDaemonUnavailableError(error)) {
|
|
3298
|
+
const message = daemonUnavailableStatusOutput(deps.socketPath, deps.healthFilePath);
|
|
3299
|
+
deps.writeStdout(message);
|
|
3300
|
+
return message;
|
|
3301
|
+
}
|
|
3302
|
+
if (command.kind === "daemon.stop" && isDaemonUnavailableError(error)) {
|
|
3303
|
+
const message = "daemon not running";
|
|
3304
|
+
deps.writeStdout(message);
|
|
3305
|
+
return message;
|
|
3306
|
+
}
|
|
1045
3307
|
throw error;
|
|
1046
3308
|
}
|
|
1047
3309
|
const fallbackMessage = response.summary ?? response.message ?? (response.ok ? "ok" : `error: ${response.error ?? "unknown error"}`);
|