@ouro.bot/cli 0.1.0-alpha.1023 → 0.1.0-alpha.1025

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.
@@ -47,6 +47,7 @@ const machine_identity_1 = require("../machine-identity");
47
47
  const shepherd_config_1 = require("../shepherd-config");
48
48
  const store_1 = require("../../senses/app-sessions/store");
49
49
  const process_manager_1 = require("./process-manager");
50
+ const presence_1 = require("./presence");
50
51
  const config_1 = require("../../a2a/config");
51
52
  const DEFAULT_TEAMS_PORT = 3978;
52
53
  const DEFAULT_BLUEBUBBLES_PORT = 18790;
@@ -605,9 +606,27 @@ class DaemonSenseManager {
605
606
  bundlesRoot;
606
607
  quiescedShepherdOwners = new Set();
607
608
  initiallyUnmanagedShepherdOwners;
609
+ presenceOwner;
610
+ presenceFlagOn;
611
+ /** Shared senses skipped because another machine owns them; started here when ownership arrives. */
612
+ notOwnerSkipped = new Set();
608
613
  constructor(options) {
609
614
  const bundlesRoot = options.bundlesRoot ?? path.join(os.homedir(), "AgentBundles");
610
615
  this.bundlesRoot = bundlesRoot;
616
+ /* v8 ignore start -- production default reads the real roster and machine identity; tests inject presenceOwner @preserve */
617
+ this.presenceOwner = options.presenceOwner ?? ((agent, sense) => {
618
+ if (!(0, presence_1.isSharedSense)(sense))
619
+ return null;
620
+ const presence = (0, presence_1.readPresenceForAgent)(path.join(bundlesRoot, `${agent}.ouro`));
621
+ if (!presence)
622
+ return null;
623
+ const machineId = currentMachineId();
624
+ const owner = (0, presence_1.effectiveOwner)(presence, sense);
625
+ const owns = (0, presence_1.mayRunSense)(presence, machineId, sense);
626
+ return { owns, owner, ownerName: (0, presence_1.findRosterMachine)(presence, owner)?.name ?? owner, waiting: !owns && owner === machineId };
627
+ });
628
+ this.presenceFlagOn = options.presenceFlagOn ?? (() => (0, presence_1.readLocalPresenceSettings)().enabled);
629
+ /* v8 ignore stop */
611
630
  this.contexts = new Map(options.agents.map((agent) => {
612
631
  const { senses, workbenchHasStaleBundleEntry } = readAgentSenses(path.join(bundlesRoot, `${agent}.ouro`, "agent.json"));
613
632
  const facts = senseFactsFromRuntimeConfig(agent, senses, (0, runtime_credentials_1.readRuntimeCredentialConfig)(agent), (0, runtime_credentials_1.readMachineRuntimeCredentialConfig)(agent), workbenchHasStaleBundleEntry);
@@ -635,6 +654,12 @@ class DaemonSenseManager {
635
654
  return { ok: true };
636
655
  if (parsed.sense === "shepherd" && this.quiescedShepherdOwners.has(parsed.agent))
637
656
  return { ok: false, skip: true, error: "Shepherd is quiesced for maintenance until daemon restart" };
657
+ const ownership = this.presenceOwner(parsed.agent, parsed.sense);
658
+ if (ownership && !ownership.owns) {
659
+ this.notOwnerSkipped.add(name);
660
+ return { ok: false, skip: true, error: `${parsed.sense}: not owner; ${parsed.agent}'s presence roster gives it to ${ownership.owner ?? "another machine"}` };
661
+ }
662
+ this.notOwnerSkipped.delete(name);
638
663
  const context = this.contexts.get(parsed.agent);
639
664
  if (!context)
640
665
  return { ok: true };
@@ -787,6 +812,41 @@ class DaemonSenseManager {
787
812
  });
788
813
  await Promise.all(refreshes);
789
814
  }
815
+ /**
816
+ * Follow the presence roster: stop a shared sense another machine now owns,
817
+ * and start one this machine now owns. The daemon runs this every minute,
818
+ * so a handoff takes effect once each machine has pulled it.
819
+ */
820
+ async reconcilePresence() {
821
+ const snapshots = this.processManager.listAgentSnapshots();
822
+ for (const [agent, context] of this.contexts.entries()) {
823
+ for (const sense of ["teams", "bluebubbles", "mail", "voice", "a2a", "telegram"]) {
824
+ if (!context.senses[sense].enabled)
825
+ continue;
826
+ const ownership = this.presenceOwner(agent, sense);
827
+ const name = `${agent}:${sense}`;
828
+ if (!ownership) {
829
+ // The roster is gone: back to the home lease, so run what was held. A flag turned off here keeps
830
+ // holding until the daemon restarts, which publishes that this machine left before any sense starts.
831
+ if (this.presenceFlagOn() && this.notOwnerSkipped.delete(name))
832
+ await this.processManager.startAgent?.(name);
833
+ continue;
834
+ }
835
+ const snapshot = snapshots.find((row) => row.name === name);
836
+ const running = !!snapshot && (snapshot.pid ?? null) !== null;
837
+ if (!ownership.owns && running) {
838
+ (0, presence_1.emitOwnershipChange)(agent, sense, false, ownership.owner);
839
+ this.notOwnerSkipped.add(name);
840
+ await this.processManager.stopAgent?.(name);
841
+ }
842
+ else if (ownership.owns && !running && this.notOwnerSkipped.has(name)) {
843
+ (0, presence_1.emitOwnershipChange)(agent, sense, true, ownership.owner);
844
+ this.notOwnerSkipped.delete(name);
845
+ await this.processManager.startAgent?.(name);
846
+ }
847
+ }
848
+ }
849
+ }
790
850
  async startAutoStartSenses() {
791
851
  await this.refreshEnabledSenseConfigs();
792
852
  await this.processManager.startAutoStartAgents();
@@ -1007,41 +1067,57 @@ class DaemonSenseManager {
1007
1067
  },
1008
1068
  };
1009
1069
  const inventory = (0, sense_truth_1.getSenseInventory)({ senses: context.senses }, runtimeInfo);
1010
- return inventory.map((entry) => ({
1011
- agent,
1012
- sense: entry.sense,
1013
- label: entry.label,
1014
- enabled: entry.enabled,
1015
- status: entry.status,
1016
- detail: entry.enabled
1017
- ? entry.sense === "bluebubbles"
1018
- ? blueBubblesConfigured
1019
- ? blueBubblesRuntimeFacts.detail
1020
- ?? context.facts[entry.sense].detail
1021
- : context.facts[entry.sense].detail
1022
- : entry.sense === "app-sessions"
1023
- ? (0, store_1.snapshotSummary)((0, store_1.readSnapshot)(path.join(this.bundlesRoot, `${agent}.ouro`)), Date.now())
1024
- : context.facts[entry.sense].detail
1025
- : entry.sense === "workbench"
1026
- ? WORKBENCH_RUNTIME_INJECTION_DETAIL
1027
- : "not enabled in agent.json",
1028
- ...(entry.sense === "bluebubbles" && blueBubblesConfigured ? {
1029
- proofMethod: blueBubblesRuntimeFacts.proofMethod,
1030
- lastProofAt: blueBubblesRuntimeFacts.lastProofAt,
1031
- proofAgeMs: blueBubblesRuntimeFacts.proofAgeMs,
1032
- lastFailure: blueBubblesRuntimeFacts.lastFailure,
1033
- failureLayer: blueBubblesRuntimeFacts.failureLayer,
1034
- recoveryAction: blueBubblesRuntimeFacts.recoveryAction,
1035
- pendingRecoveryCount: blueBubblesRuntimeFacts.pendingRecoveryCount,
1036
- failedRecoveryCount: blueBubblesRuntimeFacts.failedRecoveryCount,
1037
- oldestPendingRecoveryAt: blueBubblesRuntimeFacts.oldestPendingRecoveryAt,
1038
- oldestPendingRecoveryAgeMs: blueBubblesRuntimeFacts.oldestPendingRecoveryAgeMs,
1039
- activeTurnCount: blueBubblesRuntimeFacts.activeTurnCount,
1040
- stalledTurnCount: blueBubblesRuntimeFacts.stalledTurnCount,
1041
- oldestActiveTurnStartedAt: blueBubblesRuntimeFacts.oldestActiveTurnStartedAt,
1042
- oldestActiveTurnAgeMs: blueBubblesRuntimeFacts.oldestActiveTurnAgeMs,
1043
- } : {}),
1044
- }));
1070
+ return inventory.map((entry) => {
1071
+ // A shared sense another machine runs under the presence roster is absent here by design, not broken.
1072
+ const ownership = entry.enabled && (0, presence_1.isSharedSense)(entry.sense) ? this.presenceOwner(agent, entry.sense) : null;
1073
+ if (ownership && !ownership.owns) {
1074
+ return {
1075
+ agent,
1076
+ sense: entry.sense,
1077
+ label: entry.label,
1078
+ enabled: true,
1079
+ status: "not_attached",
1080
+ detail: ownership.waiting
1081
+ ? "starts here once the previous owner lets go (presence handoff)"
1082
+ : `runs on ${ownership.ownerName ?? ownership.owner ?? "another machine"} (presence roster)`,
1083
+ };
1084
+ }
1085
+ return {
1086
+ agent,
1087
+ sense: entry.sense,
1088
+ label: entry.label,
1089
+ enabled: entry.enabled,
1090
+ status: entry.status,
1091
+ detail: entry.enabled
1092
+ ? entry.sense === "bluebubbles"
1093
+ ? blueBubblesConfigured
1094
+ ? blueBubblesRuntimeFacts.detail
1095
+ ?? context.facts[entry.sense].detail
1096
+ : context.facts[entry.sense].detail
1097
+ : entry.sense === "app-sessions"
1098
+ ? (0, store_1.snapshotSummary)((0, store_1.readSnapshot)(path.join(this.bundlesRoot, `${agent}.ouro`)), Date.now())
1099
+ : context.facts[entry.sense].detail
1100
+ : entry.sense === "workbench"
1101
+ ? WORKBENCH_RUNTIME_INJECTION_DETAIL
1102
+ : "not enabled in agent.json",
1103
+ ...(entry.sense === "bluebubbles" && blueBubblesConfigured ? {
1104
+ proofMethod: blueBubblesRuntimeFacts.proofMethod,
1105
+ lastProofAt: blueBubblesRuntimeFacts.lastProofAt,
1106
+ proofAgeMs: blueBubblesRuntimeFacts.proofAgeMs,
1107
+ lastFailure: blueBubblesRuntimeFacts.lastFailure,
1108
+ failureLayer: blueBubblesRuntimeFacts.failureLayer,
1109
+ recoveryAction: blueBubblesRuntimeFacts.recoveryAction,
1110
+ pendingRecoveryCount: blueBubblesRuntimeFacts.pendingRecoveryCount,
1111
+ failedRecoveryCount: blueBubblesRuntimeFacts.failedRecoveryCount,
1112
+ oldestPendingRecoveryAt: blueBubblesRuntimeFacts.oldestPendingRecoveryAt,
1113
+ oldestPendingRecoveryAgeMs: blueBubblesRuntimeFacts.oldestPendingRecoveryAgeMs,
1114
+ activeTurnCount: blueBubblesRuntimeFacts.activeTurnCount,
1115
+ stalledTurnCount: blueBubblesRuntimeFacts.stalledTurnCount,
1116
+ oldestActiveTurnStartedAt: blueBubblesRuntimeFacts.oldestActiveTurnStartedAt,
1117
+ oldestActiveTurnAgeMs: blueBubblesRuntimeFacts.oldestActiveTurnAgeMs,
1118
+ } : {}),
1119
+ };
1120
+ });
1045
1121
  });
1046
1122
  (0, runtime_1.emitNervesEvent)({
1047
1123
  component: "channels",
@@ -279,6 +279,46 @@ class AccountPool {
279
279
  throw new Error("an account pool needs at least one account");
280
280
  this.accounts = accounts;
281
281
  this.options = options;
282
+ this.loadSharedRefusals();
283
+ }
284
+ /** Take in refusals another of the agent's processes recorded; the later end wins. */
285
+ loadSharedRefusals() {
286
+ const file = this.options.refusalsFile;
287
+ if (!file)
288
+ return;
289
+ try {
290
+ const shared = JSON.parse(fs.readFileSync(file, "utf8"));
291
+ for (const [key, until] of Object.entries(shared)) {
292
+ if (typeof until === "number" && until > this.now() && !(this.refused[key] >= until))
293
+ this.refused[key] = until;
294
+ }
295
+ }
296
+ catch {
297
+ // No file yet, or another process is mid-write: nothing to take in.
298
+ }
299
+ }
300
+ saveSharedRefusals() {
301
+ const file = this.options.refusalsFile;
302
+ if (!file)
303
+ return;
304
+ this.loadSharedRefusals();
305
+ const live = Object.fromEntries(Object.entries(this.refused).filter(([, until]) => until > this.now()));
306
+ try {
307
+ fs.mkdirSync(path.dirname(file), { recursive: true });
308
+ const temp = `${file}.${process.pid}.tmp`;
309
+ fs.writeFileSync(temp, JSON.stringify(live));
310
+ fs.renameSync(temp, file);
311
+ }
312
+ catch (error) {
313
+ (0, runtime_1.emitNervesEvent)({
314
+ level: "warn",
315
+ component: "engine",
316
+ event: "engine.account_refusals_save_failed",
317
+ message: "could not share account refusals with the agent's other processes",
318
+ // fs only throws Errors.
319
+ meta: { agent: this.options.agent, error: error.message },
320
+ });
321
+ }
282
322
  }
283
323
  now() {
284
324
  return (this.options.now ?? Date.now)();
@@ -328,6 +368,7 @@ class AccountPool {
328
368
  /** Called between turns: stay on the current account until it reaches the tranche cap. */
329
369
  beforeTurn() {
330
370
  void this.refreshIfStale();
371
+ this.loadSharedRefusals();
331
372
  const previous = this.currentKey;
332
373
  const caps = this.options.caps ?? tranche_1.DEFAULT_TRANCHE_CAPS;
333
374
  const next = chooseAccount(this.accounts, this.readings, { current: previous, refused: this.refused, now: this.now(), caps })
@@ -348,6 +389,7 @@ class AccountPool {
348
389
  const reset = this.readings.find((reading) => reading.key === key)?.reset;
349
390
  const until = refusalUntil(status, error, reset, this.now());
350
391
  this.refused[key] = until;
392
+ this.saveSharedRefusals();
351
393
  const next = chooseAccount(this.accounts, this.readings, { current: null, refused: this.refused, now: this.now(), caps: this.options.caps });
352
394
  if (!next || (0, exports.accountKey)(next) === key) {
353
395
  (0, runtime_1.emitNervesEvent)({
@@ -85,6 +85,7 @@ function createGithubCopilotPooledCaller(config, owner) {
85
85
  machine: config.fleetMachine,
86
86
  switchLog: path.join(owner.agentRoot, "state", "account-switches.jsonl"),
87
87
  burnDir: path.join(owner.agentRoot, "state", "account-burn"),
88
+ refusalsFile: path.join(owner.agentRoot, "state", "account-refusals.json"),
88
89
  /* v8 ignore start -- network readers and publisher: each is tested in its own module @preserve */
89
90
  loadReadings: async () => (0, fleet_readings_1.mergeReadings)(await (0, fleet_readings_1.loadFleetQuota)(gist), await (0, account_pool_1.fetchDirectReadings)(accounts)),
90
91
  publishBurn: gist ? (burn) => (0, fleet_readings_1.publishAgentBurn)(gist, burn) : undefined,
@@ -82,6 +82,7 @@ const relationship_authorization_1 = require("../repertoire/relationship-authori
82
82
  const bundle_manifest_1 = require("./bundle-manifest");
83
83
  const first_impressions_1 = require("./first-impressions");
84
84
  const desk_section_1 = require("./desk-section");
85
+ const where_am_i_1 = require("./where-am-i");
85
86
  const session_activity_1 = require("../heart/session-activity");
86
87
  const active_work_1 = require("../heart/active-work");
87
88
  const commitments_1 = require("../heart/commitments");
@@ -1724,6 +1725,7 @@ async function buildSystem(channel = "cli", options, context) {
1724
1725
  // Volatile sections from Group 2 (date and rhythm change every turn)
1725
1726
  dateSection(),
1726
1727
  rhythmStatusSection(options?.daemonHealth),
1728
+ (0, where_am_i_1.whereAmISection)((0, identity_1.getAgentRoot)()),
1727
1729
  // Group 7: dynamic state for this turn
1728
1730
  "# dynamic state for this turn",
1729
1731
  delegatedCommandSection(options),
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ /**
3
+ * `## where i am`: which machine this presence runs on, its peers, and which
4
+ * shared senses it owns, so an agent present on several machines always
5
+ * knows where it is and who else it is.
6
+ */
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.renderWhereAmI = renderWhereAmI;
42
+ exports.whereAmISection = whereAmISection;
43
+ const os = __importStar(require("os"));
44
+ const path = __importStar(require("path"));
45
+ const runtime_1 = require("../nerves/runtime");
46
+ const machine_identity_1 = require("../heart/machine-identity");
47
+ const presence_daemon_1 = require("../heart/daemon/presence-daemon");
48
+ const presence_1 = require("../heart/daemon/presence");
49
+ function ago(seenAt, nowMs) {
50
+ const ms = nowMs - Date.parse(seenAt);
51
+ if (!Number.isFinite(ms))
52
+ return "at an unknown time";
53
+ const minutes = Math.round(ms / 60_000);
54
+ if (minutes < 1)
55
+ return "just now";
56
+ if (minutes < 90)
57
+ return `${minutes} min ago`;
58
+ const hours = Math.round(minutes / 60);
59
+ return hours < 48 ? `${hours} h ago` : `${Math.round(hours / 24)} days ago`;
60
+ }
61
+ function sessionCounts(record) {
62
+ const counts = record?.appSessions?.counts;
63
+ if (!counts)
64
+ return "";
65
+ const parts = Object.entries(counts).filter(([, count]) => typeof count === "number").map(([state, count]) => `${count} ${state}`);
66
+ return parts.length > 0 ? `; copilot app sessions: ${parts.join(", ")}` : "";
67
+ }
68
+ function renderWhereAmI(presence, self, nowMs = Date.now()) {
69
+ if (!presence)
70
+ return "";
71
+ const machineName = (id) => (0, presence_1.rosterMachine)(presence, id)?.name ?? id;
72
+ const peers = presence.block.machines.filter((machine) => machine.machineId !== self.machineId);
73
+ const lines = [
74
+ "## where i am",
75
+ `i am on ${self.name} (${self.role}), ${self.os}, at ${self.location}. i am one named agent present on ${presence.block.machines.length} machine${presence.block.machines.length === 1 ? "" : "s"}; each presence runs on its own machine and we share this bundle through git.`,
76
+ ];
77
+ if (peers.length === 0) {
78
+ lines.push("my peers: none; this is my only presence.");
79
+ }
80
+ else {
81
+ lines.push("my peers:");
82
+ for (const peer of peers) {
83
+ const record = presence.peers.find((candidate) => candidate.machineId === peer.machineId);
84
+ const facts = [peer.role, record?.os, record?.location].filter(Boolean).join(", ");
85
+ const seen = record ? `last seen ${ago(record.seenAt, nowMs)} on ${record.version}${sessionCounts(record)}` : "not seen yet (no presence record)";
86
+ lines.push(`- ${peer.name} (${facts}): ${seen}`);
87
+ }
88
+ }
89
+ const own = presence_1.SHARED_SENSES.filter((sense) => (0, presence_1.effectiveOwner)(presence, sense) === self.machineId);
90
+ const elsewhere = presence_1.SHARED_SENSES.filter((sense) => (0, presence_1.effectiveOwner)(presence, sense) !== self.machineId);
91
+ lines.push(`shared senses i own here: ${own.length > 0 ? own.join(", ") : "none"}.`);
92
+ if (elsewhere.length > 0) {
93
+ lines.push(`owned by a peer: ${elsewhere.map((sense) => `${sense} (${machineName((0, presence_1.effectiveOwner)(presence, sense))})`).join(", ")}.`);
94
+ }
95
+ lines.push("machine-scoped senses (cli, shepherd, app-sessions) run on every presence and see only their own machine.");
96
+ if (presence.legacy.length > 0) {
97
+ lines.push(`until ${presence.legacy.map((id) => machineName(id)).join(", ")} publish${presence.legacy.length === 1 ? "es" : ""} a current presence record, every shared sense stays with home.`);
98
+ }
99
+ return lines.join("\n");
100
+ }
101
+ /** The section for this turn, read from the bundle, the local flag and this machine's identity. */
102
+ function whereAmISection(agentRoot, homeDir = os.homedir()) {
103
+ const presence = (0, presence_1.readPresenceForAgent)(agentRoot, { homeDir });
104
+ if (!presence)
105
+ return "";
106
+ const identity = (0, machine_identity_1.readMachineIdentity)(homeDir);
107
+ if (!identity)
108
+ return "";
109
+ const machine = (0, presence_1.rosterMachine)(presence, identity.machineId);
110
+ if (!machine)
111
+ return "";
112
+ const settings = (0, presence_1.readLocalPresenceSettings)(homeDir);
113
+ const section = renderWhereAmI(presence, {
114
+ machineId: identity.machineId,
115
+ name: machine.name,
116
+ role: machine.role,
117
+ os: (0, presence_daemon_1.describeOs)(),
118
+ location: settings.location ?? (machine.role === "always-on" ? "home" : "an unknown location"),
119
+ });
120
+ (0, runtime_1.emitNervesEvent)({ component: "mind", event: "mind.where_am_i_rendered", message: "rendered where i am", meta: { agent: path.basename(agentRoot), machineId: identity.machineId } });
121
+ return section;
122
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1023",
3
+ "version": "0.1.0-alpha.1025",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1023",
9
+ "version": "0.1.0-alpha.1025",
10
10
  "dependencies": {
11
11
  "@anthropic-ai/sdk": "^0.78.0",
12
12
  "@ouro.bot/friends": "0.1.0-alpha.17",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1023",
3
+ "version": "0.1.0-alpha.1025",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },