@ouro.bot/cli 0.1.0-alpha.1021 → 0.1.0-alpha.1024

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/changelog.json +34 -0
  2. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
  3. package/deploy/unraid/sanctuary.xml +1 -1
  4. package/dist/heart/auth/auth-flow.js +17 -12
  5. package/dist/heart/core.js +19 -2
  6. package/dist/heart/daemon/agent-discovery.js +22 -5
  7. package/dist/heart/daemon/agent-home.js +101 -47
  8. package/dist/heart/daemon/cli-defaults.js +27 -6
  9. package/dist/heart/daemon/cli-exec.js +95 -1
  10. package/dist/heart/daemon/cli-help.js +7 -0
  11. package/dist/heart/daemon/cli-parse.js +38 -2
  12. package/dist/heart/daemon/daemon-entry.js +121 -1
  13. package/dist/heart/daemon/launchd.js +3 -0
  14. package/dist/heart/daemon/mcp-canary.js +2 -1
  15. package/dist/heart/daemon/os-cron-deps.js +4 -0
  16. package/dist/heart/daemon/presence-daemon.js +263 -0
  17. package/dist/heart/daemon/presence-roster.js +217 -0
  18. package/dist/heart/daemon/presence.js +380 -0
  19. package/dist/heart/daemon/provider-discovery.js +34 -0
  20. package/dist/heart/daemon/sense-manager.js +111 -35
  21. package/dist/heart/hatch/hatch-flow.js +3 -1
  22. package/dist/heart/hatch/specialist-prompt.js +1 -0
  23. package/dist/heart/hatch/specialist-tools.js +47 -2
  24. package/dist/heart/private-runtime/ledger.js +19 -28
  25. package/dist/heart/private-runtime/policy.js +13 -0
  26. package/dist/heart/providers/anthropic.js +24 -1
  27. package/dist/heart/providers/github-copilot.js +18 -1
  28. package/dist/heart/tool-images.js +42 -0
  29. package/dist/mind/prompt.js +2 -0
  30. package/dist/mind/where-am-i.js +122 -0
  31. package/dist/repertoire/mcp-tools.js +21 -5
  32. package/dist/repertoire/vault-setup.js +82 -30
  33. package/dist/repertoire/vault-unlock.js +18 -4
  34. package/dist/senses/cli/ouro-tui.js +2 -2
  35. package/dist/senses/cli/tui-store.js +11 -0
  36. package/dist/senses/cli.js +38 -9
  37. package/dist/senses/terminal-handoff.js +44 -0
  38. package/npm-shrinkwrap.json +2 -2
  39. package/package.json +1 -1
@@ -128,6 +128,8 @@ const provider_ping_1 = require("../provider-ping");
128
128
  const provider_readiness_cache_1 = require("../provider-readiness-cache");
129
129
  const agent_discovery_1 = require("./agent-discovery");
130
130
  const agent_home_1 = require("./agent-home");
131
+ const presence_roster_1 = require("./presence-roster");
132
+ const presence_1 = require("./presence");
131
133
  const prunable_bundle_1 = require("./prunable-bundle");
132
134
  const boot_sync_probe_1 = require("./boot-sync-probe");
133
135
  const connect_bay_1 = require("./connect-bay");
@@ -1857,6 +1859,7 @@ function rejectGeneratedVaultUnlockSecret(action) {
1857
1859
  throw new Error(`vault ${action} no longer supports --generate-unlock-secret. Re-run without that flag and enter a human-chosen unlock secret; Ouro will not print vault unlock secrets.`);
1858
1860
  }
1859
1861
  async function createRepairVaultForAgent(input) {
1862
+ (0, vault_unlock_1.resolveVaultUnlockStore)({ agentName: input.agentName, email: input.email, serverUrl: input.serverUrl }, { homeDir: input.deps.homeDir, store: input.store });
1860
1863
  const result = await runCommandProgressPhase(input.progress, "creating vault account", () => (0, vault_setup_1.createVaultAccount)("Ouro credential vault", input.serverUrl, input.email, input.unlockSecret), (created) => created.success ? "created" : "failed");
1861
1864
  if (!result.success) {
1862
1865
  const message = [
@@ -1947,6 +1950,8 @@ async function executeVaultCreate(command, deps) {
1947
1950
  const email = command.email ?? config.vault?.email ?? configuredVault.email;
1948
1951
  const promptSecret = ensureVaultSecretPrompt(deps.promptSecret, "create", command.secretFile);
1949
1952
  const serverUrl = command.serverUrl ?? config.vault?.serverUrl ?? configuredVault.serverUrl;
1953
+ // Fail before creating the account when this machine has nowhere to keep the unlock secret.
1954
+ (0, vault_unlock_1.resolveVaultUnlockStore)({ agentName: command.agent, email, serverUrl }, { homeDir: deps.homeDir, store: command.store });
1950
1955
  const unlockSecret = await (0, vault_unlock_1.promptConfirmedVaultUnlockSecret)({
1951
1956
  promptSecret,
1952
1957
  question: `Choose Ouro vault unlock secret for ${email}: `,
@@ -2349,6 +2354,65 @@ function currentMachineId(deps) {
2349
2354
  now: () => providerCliNow(deps),
2350
2355
  }).machineId;
2351
2356
  }
2357
+ async function executePresence(command, deps) {
2358
+ const homeDir = providerCliHomeDir(deps);
2359
+ if (command.kind === "presence.location") {
2360
+ (0, presence_1.writeLocalPresenceSettings)({ ...(0, presence_1.readLocalPresenceSettings)(homeDir, {}), location: command.location }, homeDir);
2361
+ const message = `this machine's location is now ${command.location}`;
2362
+ deps.writeStdout(message);
2363
+ return message;
2364
+ }
2365
+ const identity = (0, machine_identity_1.loadOrCreateMachineIdentity)({ homeDir, now: () => providerCliNow(deps) });
2366
+ /* v8 ignore next -- production default: uses real bundles root @preserve */
2367
+ const bundlesRoot = deps.bundlesRoot ?? (0, identity_1.getAgentBundlesRoot)();
2368
+ const agentRoot = path.join(bundlesRoot, `${command.agent}.ouro`);
2369
+ if (command.kind === "presence.status") {
2370
+ const settings = (0, presence_1.readLocalPresenceSettings)(homeDir);
2371
+ let agentJson = null;
2372
+ try {
2373
+ agentJson = JSON.parse(fs.readFileSync(path.join(agentRoot, "agent.json"), "utf-8"));
2374
+ }
2375
+ catch {
2376
+ return returnCliFailure(deps, `cannot read ${command.agent}'s agent.json in ${agentRoot}`);
2377
+ }
2378
+ const presence = (0, presence_1.readPresence)(agentJson, settings.enabled, (0, presence_1.readPeerRecords)(agentRoot));
2379
+ if (command.json) {
2380
+ const json = JSON.stringify((0, presence_roster_1.presenceStatusJson)({ presence, machineId: identity.machineId, settings }));
2381
+ deps.writeStdout(json);
2382
+ return json;
2383
+ }
2384
+ const message = (0, presence_roster_1.renderPresenceStatus)({
2385
+ agent: command.agent,
2386
+ presence,
2387
+ flagEnabled: settings.enabled,
2388
+ machineId: identity.machineId,
2389
+ now: new Date(providerCliNow(deps)),
2390
+ });
2391
+ deps.writeStdout(message);
2392
+ return message;
2393
+ }
2394
+ if (command.kind === "presence.handoff") {
2395
+ const result = await (0, presence_roster_1.handoffPresenceSense)({ agent: command.agent, bundlesRoot, sense: command.sense, target: command.machine });
2396
+ if (!result.ok)
2397
+ return returnCliFailure(deps, result.message);
2398
+ deps.writeStdout(result.message);
2399
+ return result.message;
2400
+ }
2401
+ const result = await (0, presence_roster_1.joinPresenceRoster)({
2402
+ agent: command.agent,
2403
+ bundlesRoot,
2404
+ machineId: identity.machineId,
2405
+ machineName: command.name ?? (0, agent_home_1.machineDisplayName)(os.hostname(), identity.machineId),
2406
+ role: command.role ?? "peer",
2407
+ minVersion: (0, bundle_manifest_1.getPackageVersion)(),
2408
+ });
2409
+ if (!result.ok)
2410
+ return returnCliFailure(deps, result.message);
2411
+ (0, presence_1.writeLocalPresenceSettings)({ ...(0, presence_1.readLocalPresenceSettings)(homeDir, {}), enabled: true }, homeDir);
2412
+ const message = `${result.message}\npresence is on for this machine (~/.ouro-cli/presence.json); restart the daemon with \`ouro up\` so it follows the roster.`;
2413
+ deps.writeStdout(message);
2414
+ return message;
2415
+ }
2352
2416
  async function executeAgentMove(command, deps) {
2353
2417
  const identity = (0, machine_identity_1.loadOrCreateMachineIdentity)({ homeDir: providerCliHomeDir(deps), now: () => providerCliNow(deps) });
2354
2418
  /* v8 ignore next -- production default: uses real bundles root @preserve */
@@ -7622,6 +7686,32 @@ async function runOuroCli(args, deps = (0, cli_defaults_1.createDefaultOuroCliDe
7622
7686
  }
7623
7687
  targetVersion = previousVersion;
7624
7688
  }
7689
+ // A daemon below presence knows only `home`: leave every roster first and publish it, so peers
7690
+ // fall back to home before this machine runs shared senses under the home lease.
7691
+ let leftPresence = [];
7692
+ if ((0, presence_1.compareVersions)(targetVersion, presence_1.PRESENCE_FIRST_VERSION) < 0) {
7693
+ const identity = (0, machine_identity_1.readMachineIdentity)(providerCliHomeDir(deps));
7694
+ /* v8 ignore next -- production default: uses real bundles root @preserve */
7695
+ const bundlesRoot = deps.bundlesRoot ?? (0, identity_1.getAgentBundlesRoot)();
7696
+ const unpublished = [];
7697
+ for (const agent of identity ? (0, agent_discovery_1.listAllBundleAgents)({ bundlesRoot, machineId: identity.machineId }).map((row) => row.name) : []) {
7698
+ const agentRoot = path.join(bundlesRoot, `${agent}.ouro`);
7699
+ if (!fs.existsSync(path.join(agentRoot, "presence", `${identity.machineId}.json`)))
7700
+ continue;
7701
+ const published = await (0, presence_1.leavePresence)(agentRoot, identity.machineId, async () => {
7702
+ const sync = readAgentSyncConfigForCliMutation(agent, deps);
7703
+ if (!sync.enabled)
7704
+ return true;
7705
+ return (await (0, sync_1.syncNow)(agentRoot, sync, agent, deps.syncLockWaitMs ?? CLI_SYNC_LOCK_WAIT_MS)).ok;
7706
+ });
7707
+ leftPresence.push(agent);
7708
+ if (!published)
7709
+ unpublished.push(agent);
7710
+ }
7711
+ if (unpublished.length > 0 && !command.force) {
7712
+ return returnCliFailure(deps, `could not publish that this machine left ${unpublished.join(", ")}'s presence roster, so nothing was rolled back: a daemon on ${targetVersion} would run their shared senses while a peer still does; fix bundle sync (\`ouro sync --agent <agent>\`) or rerun with --force`);
7713
+ }
7714
+ }
7625
7715
  writeVersionIntentWithRecoveryLauncher(deps, {
7626
7716
  schemaVersion: 1,
7627
7717
  mode: "pinned",
@@ -7637,7 +7727,7 @@ async function runOuroCli(args, deps = (0, cli_defaults_1.createDefaultOuroCliDe
7637
7727
  catch {
7638
7728
  // Daemon may not be running — that's fine
7639
7729
  }
7640
- const message = `rolled back to ${targetVersion} (was ${currentVersion})`;
7730
+ const message = `rolled back to ${targetVersion} (was ${currentVersion})${leftPresence.length > 0 ? `; this machine left the presence roster of ${leftPresence.join(", ")}, so their shared senses stay with home` : ""}`;
7641
7731
  deps.writeStdout(message);
7642
7732
  return message;
7643
7733
  }
@@ -8200,6 +8290,10 @@ async function runOuroCli(args, deps = (0, cli_defaults_1.createDefaultOuroCliDe
8200
8290
  if (command.kind === "desk.admin") {
8201
8291
  return (0, desk_admin_1.executeDeskAdminCommand)(command, deps);
8202
8292
  }
8293
+ // ── presence: one agent on several machines (local, no daemon needed) ──
8294
+ if (command.kind === "presence.join" || command.kind === "presence.handoff" || command.kind === "presence.status" || command.kind === "presence.location") {
8295
+ return executePresence(command, deps);
8296
+ }
8203
8297
  // ── move: make this machine the agent's home (local, no daemon needed) ──
8204
8298
  if (command.kind === "agent.move") {
8205
8299
  return executeAgentMove(command, deps);
@@ -118,6 +118,13 @@ exports.COMMAND_REGISTRY = {
118
118
  usage: "ouro move <agent> here",
119
119
  example: "ouro move my-agent here",
120
120
  },
121
+ presence: {
122
+ category: "Agents",
123
+ description: "Run one agent on several machines at once: join this machine to its roster, hand a shared sense (Teams, habits, …) to another machine, or see who owns what",
124
+ usage: "ouro presence join --agent <name> [--role <role>] [--name <machine name>] | ouro presence handoff <sense> <machine> --agent <name> | ouro presence status --agent <name> [--json] | ouro presence location <home|office|…>",
125
+ example: "ouro presence handoff teams aris-mac-mini --agent my-agent",
126
+ subcommands: ["join", "handoff", "status", "location"],
127
+ },
121
128
  whoami: {
122
129
  category: "Agents",
123
130
  description: "Show current agent identity info",
@@ -3235,10 +3235,46 @@ function parseOuroCommand(args) {
3235
3235
  }
3236
3236
  return { kind: "daemon.dev", repoPath, clone, clonePath };
3237
3237
  }
3238
- if (head === "rollback")
3239
- return { kind: "rollback", ...(second ? { version: second } : {}) };
3238
+ if (head === "rollback") {
3239
+ const rest = args.slice(1);
3240
+ const force = rest.includes("--force");
3241
+ const version = rest.find((arg) => arg !== "--force");
3242
+ return { kind: "rollback", ...(version ? { version } : {}), ...(force ? { force: true } : {}) };
3243
+ }
3240
3244
  if (head === "versions")
3241
3245
  return { kind: "versions" };
3246
+ if (head === "presence") {
3247
+ const usage = "Usage: ouro presence join --agent <name> [--role <role>] [--name <machine name>] | ouro presence handoff <sense> <machine> --agent <name> | ouro presence status --agent <name> [--json] | ouro presence location <home|office|…>";
3248
+ const { agent, rest } = extractAgentFlag(args.slice(1));
3249
+ const [sub, ...tail] = rest;
3250
+ if (sub === "location") {
3251
+ if (tail.length !== 1 || !tail[0])
3252
+ throw new Error(usage);
3253
+ return { kind: "presence.location", location: tail[0] };
3254
+ }
3255
+ if (!agent)
3256
+ throw new Error(usage);
3257
+ if (sub === "status" && tail.length === 0)
3258
+ return { kind: "presence.status", agent };
3259
+ if (sub === "status" && tail.length === 1 && tail[0] === "--json")
3260
+ return { kind: "presence.status", agent, json: true };
3261
+ if (sub === "handoff" && tail.length === 2)
3262
+ return { kind: "presence.handoff", agent, sense: tail[0], machine: tail[1] };
3263
+ if (sub === "join") {
3264
+ const command = { kind: "presence.join", agent };
3265
+ for (let i = 0; i < tail.length; i++) {
3266
+ const value = tail[i + 1];
3267
+ if ((tail[i] === "--role" || tail[i] === "--name") && value) {
3268
+ command[tail[i] === "--role" ? "role" : "name"] = value;
3269
+ i++;
3270
+ continue;
3271
+ }
3272
+ throw new Error(usage);
3273
+ }
3274
+ return command;
3275
+ }
3276
+ throw new Error(usage);
3277
+ }
3242
3278
  if (head === "move") {
3243
3279
  if (args.length !== 3 || !second || args[2] !== "here")
3244
3280
  throw new Error("Usage: ouro move <agent> here");
@@ -87,6 +87,8 @@ const sanctuary_scheduler_origin_1 = require("./sanctuary-scheduler-origin");
87
87
  const telegram_1 = require("../../senses/telegram");
88
88
  const sync_health_1 = require("../sync-health");
89
89
  const sync_1 = require("../sync");
90
+ const presence_daemon_1 = require("./presence-daemon");
91
+ const presence_1 = require("./presence");
90
92
  const sync_lock_1 = require("../sync-lock");
91
93
  function parseSocketPath(argv) {
92
94
  const socketIndex = argv.indexOf("--socket");
@@ -283,6 +285,75 @@ const taskScheduler = new task_scheduler_1.TaskDrivenScheduler({
283
285
  });
284
286
  const habitSchedulers = [];
285
287
  const awaitSchedulers = [];
288
+ /* v8 ignore start -- presence wiring: lambdas delegate to the schedulers and sync; PresenceTicker is unit-tested @preserve */
289
+ // Schedulers started per agent, so a presence handoff can stop exactly one agent's habits and awaits.
290
+ const agentSchedulers = new Map();
291
+ let startAgentSchedulers = null;
292
+ const presenceTicker = new presence_daemon_1.PresenceTicker({
293
+ agents: managedAgents,
294
+ bundlesRoot: (0, identity_1.getAgentBundlesRoot)(),
295
+ machineId: daemonMachineId,
296
+ version: (0, bundle_manifest_1.getPackageVersion)(),
297
+ sync: async (agent, agentRoot) => {
298
+ try {
299
+ const parsed = JSON.parse(fs.readFileSync(path.join(agentRoot, "agent.json"), "utf-8"));
300
+ if (parsed.sync?.enabled !== true)
301
+ return;
302
+ await (0, sync_1.syncNow)(agentRoot, {
303
+ enabled: true,
304
+ remote: typeof parsed.sync.remote === "string" && parsed.sync.remote.trim() ? parsed.sync.remote : "origin",
305
+ ...(typeof parsed.sync.branch === "string" && parsed.sync.branch.trim() ? { branch: parsed.sync.branch } : {}),
306
+ }, agent, 0);
307
+ }
308
+ catch {
309
+ // A busy lock or an unreachable remote only delays the roster; next minute retries.
310
+ }
311
+ },
312
+ startSchedulers: (agent) => { startAgentSchedulers?.(agent); },
313
+ stopSchedulers: (agent) => {
314
+ const started = agentSchedulers.get(agent);
315
+ if (!started)
316
+ return;
317
+ agentSchedulers.delete(agent);
318
+ for (const scheduler of [...started.habit, ...started.await]) {
319
+ try {
320
+ scheduler.stopWatching();
321
+ scheduler.stop();
322
+ }
323
+ catch { /* best-effort */ }
324
+ }
325
+ for (const scheduler of started.habit)
326
+ habitSchedulers.splice(habitSchedulers.indexOf(scheduler), 1);
327
+ for (const scheduler of started.await)
328
+ awaitSchedulers.splice(awaitSchedulers.indexOf(scheduler), 1);
329
+ },
330
+ schedulersRunning: (agent) => agentSchedulers.has(agent),
331
+ // This machine's Copilot app sessions, from the app-sessions sense's last snapshot, so peers see them too.
332
+ extraRecord: (agent) => {
333
+ try {
334
+ const snap = JSON.parse(fs.readFileSync(path.join((0, identity_1.getAgentBundlesRoot)(), `${agent}.ouro`, "state", "senses", "app-sessions", "snapshot.json"), "utf-8"));
335
+ if (!snap.at || !snap.counts || Date.now() - Date.parse(snap.at) > 10 * 60_000)
336
+ return {};
337
+ return { appSessions: { at: snap.at, counts: snap.counts, sessions: (snap.sessions ?? []).map(({ id, name, state }) => ({ id, name, state })) } };
338
+ }
339
+ catch {
340
+ return {};
341
+ }
342
+ },
343
+ notify: async (agent, text) => {
344
+ await (0, socket_client_1.sendDaemonCommand)(socketPath, { kind: "message.send", from: "presence", to: agent, content: text });
345
+ await (0, socket_client_1.sendDaemonCommand)(socketPath, {
346
+ kind: "private.wake",
347
+ agent,
348
+ reason: "presence arrival",
349
+ triggerSource: "presence-arrival",
350
+ budgetClass: "interactive",
351
+ idempotencyKey: `presence-arrival:${agent}:${new Date().toISOString().slice(0, 10)}`,
352
+ originRefs: [{ kind: "presence", id: "arrival" }],
353
+ });
354
+ },
355
+ });
356
+ /* v8 ignore stop */
286
357
  const containerRuntimePolicy = (0, container_runtime_1.readContainerRuntimePolicy)();
287
358
  const supercronicSupervisor = containerRuntimePolicy?.scheduler === "supercronic"
288
359
  ? new supercronic_supervisor_1.SupercronicSupervisor({
@@ -355,6 +426,9 @@ const healthMonitor = new health_monitor_1.HealthMonitor({
355
426
  for (const agent of homes.displaced) {
356
427
  void processManager.displaceAgent(agent, `${agent} is homed on another machine`).catch(() => undefined);
357
428
  }
429
+ // Presence: follow the roster's owners for shared senses, habits and awaits.
430
+ await presenceTicker.tick();
431
+ await senseManager.reconcilePresence?.();
358
432
  return [...sentinels, homes.health];
359
433
  },
360
434
  bundleSyncChecker: () => [(0, sync_health_1.checkBundleSyncHealth)((0, agent_discovery_1.listBundleSyncRows)({ bundlesRoot: (0, identity_1.getAgentBundlesRoot)() }).filter((row) => managedAgents.includes(row.agent)))],
@@ -708,7 +782,30 @@ void (0, daemon_bootstrap_startup_1.startDaemonAfterContainerCredentialBootstrap
708
782
  loadBootstrap: () => (0, container_credential_bootstrap_1.loadContainerCredentialBootstrap)(managedAgents),
709
783
  prepareManagedBundle: () => { (0, sanctuary_package_management_1.prepareSanctuaryPackageManagedBundle)(sanctuaryPackageManagement); },
710
784
  prepareDaemon: prepareProviderRuntime,
711
- startDaemon: () => daemon.start(),
785
+ startDaemon: async () => {
786
+ // Presence off here: publish that this machine left every roster before any sense starts under the home lease.
787
+ if (!(0, presence_1.readLocalPresenceSettings)().enabled) {
788
+ for (const agent of managedAgents) {
789
+ const agentRoot = path.join((0, identity_1.getAgentBundlesRoot)(), `${agent}.ouro`);
790
+ await (0, presence_1.leavePresence)(agentRoot, daemonMachineId, async (root) => {
791
+ try {
792
+ const parsed = JSON.parse(fs.readFileSync(path.join(root, "agent.json"), "utf-8"));
793
+ if (parsed.sync?.enabled !== true)
794
+ return true;
795
+ return (await (0, sync_1.syncNow)(root, {
796
+ enabled: true,
797
+ remote: typeof parsed.sync.remote === "string" && parsed.sync.remote.trim() ? parsed.sync.remote : "origin",
798
+ ...(typeof parsed.sync.branch === "string" && parsed.sync.branch.trim() ? { branch: parsed.sync.branch } : {}),
799
+ }, agent, 30_000)).ok;
800
+ }
801
+ catch {
802
+ return false;
803
+ }
804
+ }).catch(() => false);
805
+ }
806
+ }
807
+ await daemon.start();
808
+ },
712
809
  markStartupFailure: () => { _tombstoneWritten = true; },
713
810
  exit: (code) => process.exit(code),
714
811
  }).then(async (started) => {
@@ -738,8 +835,31 @@ void (0, daemon_bootstrap_startup_1.startDaemonAfterContainerCredentialBootstrap
738
835
  ? "/usr/local/bin/node /opt/ouro/dist/heart/daemon/ouro-entry.js"
739
836
  : (0, os_cron_deps_1.resolveOuroBinaryPath)();
740
837
  const osCronDeps = (0, os_cron_deps_1.createRealOsCronDeps)();
838
+ startAgentSchedulers = (agent) => {
839
+ const habitsBefore = habitSchedulers.length;
840
+ const awaitsBefore = awaitSchedulers.length;
841
+ startAgentSchedulersNow(agent);
842
+ agentSchedulers.set(agent, { habit: habitSchedulers.slice(habitsBefore), await: awaitSchedulers.slice(awaitsBefore) });
843
+ };
741
844
  for (const agent of managedAgents) {
742
845
  scheduleStartupSentinelAfterProviderPreload(agent, providerPreload);
846
+ // Under a presence roster, only the machine that owns `habits` runs this agent's habits and awaits.
847
+ if (!presenceTicker.shouldStartSchedulers(agent)) {
848
+ // Clear cron jobs a crash may have left behind, so they don't fire here while another machine owns habits.
849
+ for (const manager of [
850
+ supercronicSupervisor ? supercronicSupervisor.namespace(`habit:${agent}`) : new os_cron_1.LaunchdCronManager(osCronDeps, { ownsLabel: habitCronLabelOwner(agent) }),
851
+ supercronicSupervisor ? supercronicSupervisor.namespace(`await:${agent}`) : new os_cron_1.LaunchdCronManager(osCronDeps, { ownsLabel: awaitCronLabelOwner(agent) }),
852
+ ]) {
853
+ try {
854
+ manager.removeAll();
855
+ }
856
+ catch { /* best-effort */ }
857
+ }
858
+ continue;
859
+ }
860
+ startAgentSchedulers(agent);
861
+ }
862
+ function startAgentSchedulersNow(agent) {
743
863
  const bundleRoot = path.join(bundlesRoot, `${agent}.ouro`);
744
864
  const habitsDir = path.join(bundleRoot, "habits");
745
865
  const degradedComponent = `habits:${agent}`;
@@ -95,6 +95,9 @@ function generateDaemonPlist(options) {
95
95
  ` <key>KeepAlive</key>`,
96
96
  ` <true/>`,
97
97
  ];
98
+ if (options.nice !== undefined && Number.isInteger(options.nice) && options.nice !== 0) {
99
+ lines.push(` <key>Nice</key>`, ` <integer>${options.nice}</integer>`);
100
+ }
98
101
  if (options.envPath) {
99
102
  lines.push(` <key>EnvironmentVariables</key>`, ` <dict>`, ` <key>PATH</key>`, ` <string>${options.envPath}</string>`, ` </dict>`);
100
103
  }
@@ -228,7 +228,8 @@ function validateMcpStatus(parsed, requiredSenses, options = {}) {
228
228
  }
229
229
  if (!options.ignoreSenseHealth) {
230
230
  for (const [sense, row] of Object.entries(parsed.senses)) {
231
- if (row.status === "disabled")
231
+ // Absent by design on this machine (no hardware here, or the presence roster runs it on a peer).
232
+ if (row.status === "disabled" || row.status === "not_attached")
232
233
  continue;
233
234
  if (row.status === "running" || row.status === "interactive")
234
235
  continue;
@@ -114,6 +114,10 @@ function resolveOuroBinaryPath() {
114
114
  return repoOuro;
115
115
  }
116
116
  }
117
+ // The ouro.bot installer's wrapper. launchd's PATH never includes it, so a bare "ouro" in a habit plist cannot spawn.
118
+ const installerOuro = path.join(os.homedir(), ".ouro-cli", "bin", "ouro");
119
+ if (fs.existsSync(installerOuro))
120
+ return installerOuro;
117
121
  // Try which ouro
118
122
  try {
119
123
  const result = (0, child_process_1.execSync)("which ouro", { encoding: "utf-8" }).trim();
@@ -0,0 +1,263 @@
1
+ "use strict";
2
+ /**
3
+ * The daemon's per-minute presence work, for agents whose roster names this
4
+ * machine:
5
+ *
6
+ * - publish this machine's record (`presence/<machineId>.json`: version,
7
+ * last seen, name, role, OS, location, owned senses) every 15 minutes, and
8
+ * push it, so each peer can tell this presence is alive and up to date;
9
+ * - start the habit and await schedulers when this machine owns `habits`,
10
+ * and stop them when another machine does.
11
+ */
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
25
+ }) : function(o, v) {
26
+ o["default"] = v;
27
+ });
28
+ var __importStar = (this && this.__importStar) || (function () {
29
+ var ownKeys = function(o) {
30
+ ownKeys = Object.getOwnPropertyNames || function (o) {
31
+ var ar = [];
32
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
33
+ return ar;
34
+ };
35
+ return ownKeys(o);
36
+ };
37
+ return function (mod) {
38
+ if (mod && mod.__esModule) return mod;
39
+ var result = {};
40
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41
+ __setModuleDefault(result, mod);
42
+ return result;
43
+ };
44
+ })();
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.PresenceTicker = exports.PEER_RECORD_INTERVAL_MS = void 0;
47
+ exports.describeOs = describeOs;
48
+ exports.parseLocationOutput = parseLocationOutput;
49
+ exports.arrivalText = arrivalText;
50
+ const fs = __importStar(require("fs"));
51
+ const os = __importStar(require("os"));
52
+ const path = __importStar(require("path"));
53
+ const child_process_1 = require("child_process");
54
+ const runtime_1 = require("../../nerves/runtime");
55
+ const presence_1 = require("./presence");
56
+ exports.PEER_RECORD_INTERVAL_MS = 15 * 60_000;
57
+ function describeOs(platform = process.platform, release = os.release()) {
58
+ if (platform === "darwin") {
59
+ const major = Number(release.split(".")[0]);
60
+ // Darwin 25 is macOS 26, Darwin 24 is macOS 15, Darwin 20 is macOS 11.
61
+ const macos = major >= 25 ? major + 1 : major >= 20 ? major - 9 : null;
62
+ return macos ? `macOS ${macos}` : `macOS (Darwin ${release})`;
63
+ }
64
+ if (platform === "linux")
65
+ return `Linux ${release}`;
66
+ if (platform === "win32")
67
+ return `Windows ${release}`;
68
+ return `${platform} ${release}`;
69
+ }
70
+ /* v8 ignore start -- production default: a real child process; tests inject run @preserve */
71
+ function runCommand(argv, timeoutMs) {
72
+ return new Promise((resolve, reject) => {
73
+ (0, child_process_1.execFile)(argv[0], argv.slice(1), { timeout: timeoutMs, maxBuffer: 4 << 20 }, (error, stdout) => {
74
+ if (error)
75
+ reject(error);
76
+ else
77
+ resolve(String(stdout));
78
+ });
79
+ });
80
+ }
81
+ /* v8 ignore stop */
82
+ /** A location from a command's output: JSON `{ "location": … }`, or its first line. */
83
+ function parseLocationOutput(stdout) {
84
+ const textOut = stdout.trim();
85
+ if (!textOut)
86
+ return null;
87
+ try {
88
+ const parsed = JSON.parse(textOut);
89
+ return typeof parsed.location === "string" && parsed.location.trim() ? parsed.location.trim() : null;
90
+ }
91
+ catch {
92
+ const line = textOut.split("\n")[0].trim();
93
+ return /^[\w .-]{1,40}$/.test(line) ? line : null;
94
+ }
95
+ }
96
+ /** What an arrival command printed, for the agent to pass on: JSON `.teams` or `.text`, else the raw text. */
97
+ function arrivalText(stdout) {
98
+ try {
99
+ const parsed = JSON.parse(stdout);
100
+ if (typeof parsed.teams === "string" && parsed.teams.trim())
101
+ return parsed.teams.trim();
102
+ if (typeof parsed.text === "string" && parsed.text.trim())
103
+ return parsed.text.trim();
104
+ }
105
+ catch {
106
+ // Plain text.
107
+ }
108
+ return stdout.trim();
109
+ }
110
+ class PresenceTicker {
111
+ deps;
112
+ lastPublishedMs = new Map();
113
+ /** What each agent's last record said this machine owns; a change publishes at once. */
114
+ lastOwns = new Map();
115
+ /** Agents whose schedulers this machine holds back because another machine owns `habits`. */
116
+ held = new Set();
117
+ constructor(deps) {
118
+ this.deps = deps;
119
+ }
120
+ /** At daemon start: whether to start this agent's schedulers now. */
121
+ shouldStartSchedulers(agent) {
122
+ const presence = this.read(agent);
123
+ if (!presence || (0, presence_1.mayRunSense)(presence, this.deps.machineId, "habits"))
124
+ return true;
125
+ this.held.add(agent);
126
+ (0, presence_1.emitOwnershipChange)(agent, "habits", false, (0, presence_1.effectiveOwner)(presence, "habits"));
127
+ return false;
128
+ }
129
+ async tick() {
130
+ const arrived = await this.refreshLocation();
131
+ for (const agent of this.deps.agents) {
132
+ if (!this.read(agent)) {
133
+ // The roster is gone: back to the home lease, so run what was held. A flag turned off here keeps
134
+ // holding until the daemon restarts, which publishes that this machine left first.
135
+ if ((0, presence_1.readLocalPresenceSettings)(this.deps.homeDir).enabled && this.held.delete(agent))
136
+ this.deps.startSchedulers(agent);
137
+ continue;
138
+ }
139
+ try {
140
+ await this.deps.sync?.(agent, path.join(this.deps.bundlesRoot, `${agent}.ouro`));
141
+ const presence = this.read(agent);
142
+ if (!presence)
143
+ continue;
144
+ this.reconcileSchedulers(agent, presence);
145
+ if (arrived)
146
+ await this.announceArrival(agent, presence, arrived);
147
+ await this.publish(agent, presence);
148
+ }
149
+ catch (error) {
150
+ (0, runtime_1.emitNervesEvent)({
151
+ level: "warn",
152
+ component: "daemon",
153
+ event: "daemon.presence_tick_error",
154
+ message: "presence upkeep failed; retrying next minute",
155
+ meta: { agent, error: error instanceof Error ? error.message : String(error) },
156
+ });
157
+ }
158
+ }
159
+ }
160
+ /** Run the location command; returns the new location when it changed and an arrival command exists for it. */
161
+ async refreshLocation() {
162
+ const settings = (0, presence_1.readLocalPresenceSettings)(this.deps.homeDir, {});
163
+ if (!settings.locationCommand)
164
+ return null;
165
+ let location;
166
+ try {
167
+ location = parseLocationOutput(await (this.deps.run ?? runCommand)(settings.locationCommand, 15_000));
168
+ }
169
+ catch (error) {
170
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "daemon.presence_location_error", message: "location command failed; keeping the last location", meta: { error: error instanceof Error ? error.message : String(error) } });
171
+ return null;
172
+ }
173
+ if (!location || location === settings.location)
174
+ return null;
175
+ (0, presence_1.writeLocalPresenceSettings)({ ...settings, location }, this.deps.homeDir);
176
+ // Any record published from now on carries the new location.
177
+ this.lastPublishedMs.clear();
178
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.presence_location_changed", message: `this machine is now at ${location}`, meta: { from: settings.location ?? null, to: location } });
179
+ return settings.onArrive?.[location] ? location : null;
180
+ }
181
+ /** The first arrival at a location each day: run its command once (receipted) and hand the result to the agent. */
182
+ async announceArrival(agent, presence, location) {
183
+ const settings = (0, presence_1.readLocalPresenceSettings)(this.deps.homeDir, {});
184
+ const command = settings.onArrive?.[location];
185
+ if (!command || !(0, presence_1.rosterMachine)(presence, this.deps.machineId))
186
+ return;
187
+ const now = (this.deps.now ?? (() => new Date()))();
188
+ const day = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
189
+ const key = `${this.deps.machineId}:${location}:${day}`;
190
+ const receiptPath = path.join(this.deps.bundlesRoot, `${agent}.ouro`, "state", "presence-arrivals.json");
191
+ let receipts = {};
192
+ try {
193
+ receipts = JSON.parse(fs.readFileSync(receiptPath, "utf-8"));
194
+ }
195
+ catch {
196
+ // No arrivals yet.
197
+ }
198
+ if (receipts[key])
199
+ return;
200
+ // The receipt comes first, so a crash or restart never announces twice.
201
+ receipts[key] = now.toISOString();
202
+ fs.mkdirSync(path.dirname(receiptPath), { recursive: true });
203
+ fs.writeFileSync(receiptPath, `${JSON.stringify(receipts, null, 2)}\n`, "utf-8");
204
+ const machine = (0, presence_1.rosterMachine)(presence, this.deps.machineId);
205
+ let report;
206
+ try {
207
+ report = arrivalText(await (this.deps.run ?? runCommand)(command, 120_000));
208
+ }
209
+ catch (error) {
210
+ report = `the arrival check failed: ${error instanceof Error ? error.message : String(error)}`;
211
+ }
212
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.presence_arrival", message: `arrived at ${location}`, meta: { agent, machine: machine.name, location } });
213
+ await this.deps.notify?.(agent, `${machine.name} just arrived at ${location} for the first time today. Tell Ari on Teams now, once, with this arrival check as written:\n\n${report}`);
214
+ }
215
+ read(agent) {
216
+ const agentRoot = path.join(this.deps.bundlesRoot, `${agent}.ouro`);
217
+ /* v8 ignore next -- production default reads the bundle; tests inject readPresence @preserve */
218
+ return this.deps.readPresence ? this.deps.readPresence(agentRoot) : (0, presence_1.readPresenceForAgent)(agentRoot, { homeDir: this.deps.homeDir });
219
+ }
220
+ reconcileSchedulers(agent, presence) {
221
+ const running = this.deps.schedulersRunning(agent);
222
+ const owns = running ? (0, presence_1.ownsSense)(presence, this.deps.machineId, "habits") : (0, presence_1.mayRunSense)(presence, this.deps.machineId, "habits");
223
+ if (owns && !running && this.held.has(agent)) {
224
+ this.held.delete(agent);
225
+ (0, presence_1.emitOwnershipChange)(agent, "habits", true, this.deps.machineId);
226
+ this.deps.startSchedulers(agent);
227
+ }
228
+ else if (!owns && running) {
229
+ this.held.add(agent);
230
+ (0, presence_1.emitOwnershipChange)(agent, "habits", false, (0, presence_1.effectiveOwner)(presence, "habits"));
231
+ this.deps.stopSchedulers(agent);
232
+ }
233
+ }
234
+ async publish(agent, presence) {
235
+ const now = (this.deps.now ?? (() => new Date()))();
236
+ const owns = (0, presence_1.ownedSharedSenses)(presence, this.deps.machineId);
237
+ const last = this.lastPublishedMs.get(agent);
238
+ const ownsChanged = this.lastOwns.get(agent) !== owns.join(",");
239
+ if (!ownsChanged && last !== undefined && now.getTime() - last < exports.PEER_RECORD_INTERVAL_MS)
240
+ return;
241
+ const agentRoot = path.join(this.deps.bundlesRoot, `${agent}.ouro`);
242
+ const machine = (0, presence_1.rosterMachine)(presence, this.deps.machineId);
243
+ if (!machine)
244
+ return;
245
+ const settings = (0, presence_1.readLocalPresenceSettings)(this.deps.homeDir);
246
+ const record = {
247
+ machineId: this.deps.machineId,
248
+ version: this.deps.version,
249
+ seenAt: now.toISOString(),
250
+ name: machine.name,
251
+ role: machine.role,
252
+ os: describeOs(),
253
+ location: settings.location ?? (machine.role === "always-on" ? "home" : "unknown"),
254
+ owns,
255
+ ...this.deps.extraRecord?.(agent),
256
+ };
257
+ (0, presence_1.writePeerRecord)(agentRoot, record);
258
+ this.lastPublishedMs.set(agent, now.getTime());
259
+ this.lastOwns.set(agent, owns.join(","));
260
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.presence_record_published", message: "published this machine's presence record", meta: { agent, machineId: this.deps.machineId, version: this.deps.version } });
261
+ }
262
+ }
263
+ exports.PresenceTicker = PresenceTicker;