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