@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.
@@ -0,0 +1,217 @@
1
+ "use strict";
2
+ /**
3
+ * Roster changes in the synced agent.json, published by the same
4
+ * compare-and-swap `ouro move` uses (agent-home.ts):
5
+ *
6
+ * - `ouro presence join` adds this machine to the agent's roster;
7
+ * - `ouro presence handoff <sense> <machine>` names a shared sense's owner;
8
+ * - `ouro presence status` shows the roster as this machine sees it.
9
+ */
10
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ var desc = Object.getOwnPropertyDescriptor(m, k);
13
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14
+ desc = { enumerable: true, get: function() { return m[k]; } };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }) : (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ o[k2] = m[k];
20
+ }));
21
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
22
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
23
+ }) : function(o, v) {
24
+ o["default"] = v;
25
+ });
26
+ var __importStar = (this && this.__importStar) || (function () {
27
+ var ownKeys = function(o) {
28
+ ownKeys = Object.getOwnPropertyNames || function (o) {
29
+ var ar = [];
30
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
31
+ return ar;
32
+ };
33
+ return ownKeys(o);
34
+ };
35
+ return function (mod) {
36
+ if (mod && mod.__esModule) return mod;
37
+ var result = {};
38
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
39
+ __setModuleDefault(result, mod);
40
+ return result;
41
+ };
42
+ })();
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.joinPresenceRoster = joinPresenceRoster;
45
+ exports.handoffPresenceSense = handoffPresenceSense;
46
+ exports.presenceStatusJson = presenceStatusJson;
47
+ exports.renderPresenceStatus = renderPresenceStatus;
48
+ const path = __importStar(require("path"));
49
+ const runtime_1 = require("../../nerves/runtime");
50
+ const agent_discovery_1 = require("./agent-discovery");
51
+ const agent_home_1 = require("./agent-home");
52
+ const presence_1 = require("./presence");
53
+ /** Add (or rename) this machine in the agent's roster. Creating a roster keeps every shared sense with `home`. */
54
+ async function joinPresenceRoster(options) {
55
+ const { agent, machineId, machineName, role } = options;
56
+ return (0, agent_home_1.updateSyncedAgentJson)({
57
+ agent,
58
+ bundlesRoot: options.bundlesRoot,
59
+ retryCommand: `ouro presence join --agent ${agent}`,
60
+ events: "daemon.presence_join",
61
+ meta: { machineId },
62
+ noun: "join",
63
+ verb: "add this machine to",
64
+ execFileSync: options.execFileSync,
65
+ lockWaitMs: options.lockWaitMs,
66
+ network: options.network,
67
+ stamp: (parsed) => JSON.stringify(parsed.presence ?? null),
68
+ lostRace: () => ({ field: "presence roster", now: "run `ouro presence status` to see it" }),
69
+ decide: (parsed) => {
70
+ const existing = (0, presence_1.parsePresenceBlock)(parsed.presence);
71
+ const block = existing ?? { schema: 1, minVersion: options.minVersion, machines: [], owners: {} };
72
+ const current = block.machines.find((machine) => machine.machineId === machineId);
73
+ if (current && current.name === machineName && current.role === role) {
74
+ return { kind: "noop", message: `${machineName} is already on ${agent}'s roster as ${role}` };
75
+ }
76
+ const machines = current
77
+ ? block.machines.map((machine) => (machine.machineId === machineId ? { machineId, name: machineName, role } : machine))
78
+ : [...block.machines, { machineId, name: machineName, role }];
79
+ const owners = { ...block.owners };
80
+ if (!existing) {
81
+ const ownerId = (0, agent_discovery_1.parseAgentHome)(parsed.home)?.machineId ?? machineId;
82
+ for (const sense of presence_1.SHARED_SENSES)
83
+ owners[sense] = ownerId;
84
+ }
85
+ const next = { ...block, machines, owners };
86
+ return {
87
+ kind: "write",
88
+ next: { ...parsed, presence: next },
89
+ commitMessage: `presence: ${machineName} joins ${agent}`,
90
+ message: `${machineName} (${role}) is on ${agent}'s roster with ${machines.filter((machine) => machine.machineId !== machineId).map((machine) => machine.name).join(", ") || "no other machine"}`,
91
+ };
92
+ },
93
+ });
94
+ }
95
+ /**
96
+ * Name a shared sense's owner. Refused while any roster machine may still run
97
+ * a daemon that knows only `home`, because that daemon would run the sense too.
98
+ */
99
+ async function handoffPresenceSense(options) {
100
+ const { agent, sense, target } = options;
101
+ const agentRoot = path.join(options.bundlesRoot, `${agent}.ouro`);
102
+ return (0, agent_home_1.updateSyncedAgentJson)({
103
+ agent,
104
+ bundlesRoot: options.bundlesRoot,
105
+ retryCommand: `ouro presence handoff ${sense} ${target} --agent ${agent}`,
106
+ events: "daemon.presence_handoff",
107
+ meta: { sense, target },
108
+ noun: "handoff",
109
+ verb: "hand off a sense of",
110
+ execFileSync: options.execFileSync,
111
+ lockWaitMs: options.lockWaitMs,
112
+ network: options.network,
113
+ stamp: (parsed) => JSON.stringify((0, presence_1.parsePresenceBlock)(parsed.presence)?.owners[sense] ?? null),
114
+ lostRace: (parsed) => {
115
+ const block = (0, presence_1.parsePresenceBlock)(parsed.presence);
116
+ const owner = block?.owners[sense];
117
+ const name = owner ? block?.machines.find((machine) => machine.machineId === owner)?.name ?? owner : "no machine";
118
+ return { field: `${sense} owner`, now: `it now names ${name}` };
119
+ },
120
+ decide: (parsed) => {
121
+ if (!(0, presence_1.isSharedSense)(sense)) {
122
+ return { kind: "refuse", message: `${sense} runs on every machine in the roster, so it has no owner to hand off; shared senses are ${presence_1.SHARED_SENSES.join(", ")}` };
123
+ }
124
+ const presence = (0, presence_1.readPresence)(parsed, true, (0, presence_1.readPeerRecords)(agentRoot));
125
+ if (!presence) {
126
+ return { kind: "refuse", message: `${agent} has no presence roster, so nothing changed; run \`ouro presence join --agent ${agent}\` on each machine first` };
127
+ }
128
+ const machine = (0, presence_1.findRosterMachine)(presence, target);
129
+ if (!machine) {
130
+ return { kind: "refuse", message: `${target} is not on ${agent}'s roster (${presence.block.machines.map((entry) => entry.name).join(", ")}), so nothing changed` };
131
+ }
132
+ if (presence.legacy.length > 0) {
133
+ const names = presence.legacy.map((id) => presence.block.machines.find((entry) => entry.machineId === id)?.name ?? id);
134
+ return {
135
+ kind: "refuse",
136
+ message: `${names.join(", ")} may still run a daemon that only knows \`home\` (no current presence record${presence.block.minVersion ? ` at ${presence.block.minVersion} or later` : ""}), so every shared sense stays with home and nothing changed; start a presence-aware daemon there first`,
137
+ };
138
+ }
139
+ if (presence.block.owners[sense] === machine.machineId) {
140
+ return { kind: "noop", message: `${machine.name} already owns ${agent}'s ${sense}` };
141
+ }
142
+ const previous = (0, presence_1.effectiveOwner)(presence, sense);
143
+ const previousName = presence.block.machines.find((entry) => entry.machineId === previous)?.name ?? previous;
144
+ return {
145
+ kind: "write",
146
+ next: { ...parsed, presence: { ...parsed.presence, owners: { ...presence.block.owners, [sense]: machine.machineId } } },
147
+ commitMessage: `presence: ${agent}'s ${sense} moves to ${machine.name}`,
148
+ message: `${machine.name} now owns ${agent}'s ${sense} (from ${previousName}); ${previousName} stops it and ${machine.name} starts it within about a minute of each pulling the change`,
149
+ };
150
+ },
151
+ });
152
+ }
153
+ /** `ouro presence status --json`: this machine, its peers and what it owns, for tools such as an arrival check. */
154
+ function presenceStatusJson(options) {
155
+ const { presence, machineId, settings } = options;
156
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.presence_status_json", message: "rendered presence status as json", meta: { active: presence !== null } });
157
+ if (!presence)
158
+ return { enabled: settings.enabled, machine: null, peers: [], owns: [], owners: {}, legacy: [] };
159
+ const me = presence.block.machines.find((machine) => machine.machineId === machineId);
160
+ const owners = {};
161
+ for (const sense of presence_1.SHARED_SENSES) {
162
+ const owner = (0, presence_1.effectiveOwner)(presence, sense);
163
+ owners[sense] = presence.block.machines.find((machine) => machine.machineId === owner)?.name ?? owner;
164
+ }
165
+ return {
166
+ enabled: settings.enabled,
167
+ machine: me
168
+ ? { machineId, name: me.name, role: me.role, location: settings.location ?? (me.role === "always-on" ? "home" : null) }
169
+ : { machineId, name: null, role: null, location: settings.location ?? null },
170
+ peers: presence.block.machines.filter((machine) => machine.machineId !== machineId).map((machine) => {
171
+ const record = presence.peers.find((peer) => peer.machineId === machine.machineId);
172
+ return { machineId: machine.machineId, name: machine.name, role: machine.role, seenAt: record?.seenAt ?? null, version: record?.version ?? null, location: record?.location ?? null };
173
+ }),
174
+ owns: presence_1.SHARED_SENSES.filter((sense) => (0, presence_1.effectiveOwner)(presence, sense) === machineId),
175
+ owners,
176
+ legacy: presence.legacy.map((id) => presence.block.machines.find((machine) => machine.machineId === id)?.name ?? id),
177
+ };
178
+ }
179
+ function ago(seenAt, now) {
180
+ const ms = now.getTime() - Date.parse(seenAt);
181
+ if (!Number.isFinite(ms))
182
+ return "unknown";
183
+ const minutes = Math.round(ms / 60_000);
184
+ if (minutes < 1)
185
+ return "just now";
186
+ if (minutes < 90)
187
+ return `${minutes} min ago`;
188
+ const hours = Math.round(minutes / 60);
189
+ return hours < 48 ? `${hours} h ago` : `${Math.round(hours / 24)} d ago`;
190
+ }
191
+ /** A person-readable view of the roster as this machine sees it. */
192
+ function renderPresenceStatus(options) {
193
+ const { agent, presence, machineId } = options;
194
+ const now = options.now ?? new Date();
195
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.presence_status_rendered", message: "rendered presence status", meta: { agent, active: presence !== null } });
196
+ if (!options.flagEnabled)
197
+ return `presence is off on this machine, so ${agent} follows its home lease here; turn it on with \`ouro presence join --agent ${agent}\``;
198
+ if (!presence)
199
+ return `${agent} has no presence roster, so it follows its home lease; run \`ouro presence join --agent ${agent}\` on each machine`;
200
+ const lines = [`${agent} is present on ${presence.block.machines.length} machine${presence.block.machines.length === 1 ? "" : "s"}:`];
201
+ for (const machine of presence.block.machines) {
202
+ const record = presence.peers.find((peer) => peer.machineId === machine.machineId);
203
+ const me = machine.machineId === machineId ? " (this machine)" : "";
204
+ const seen = record ? `${record.version}, seen ${ago(record.seenAt, now)}` : "no presence record yet";
205
+ const legacy = presence.legacy.includes(machine.machineId) ? "; may run a home-only daemon" : "";
206
+ lines.push(`- ${machine.name}${me}: ${machine.role}; ${seen}${legacy}`);
207
+ }
208
+ lines.push("owners:");
209
+ for (const sense of presence_1.SHARED_SENSES) {
210
+ const owner = (0, presence_1.effectiveOwner)(presence, sense);
211
+ const name = presence.block.machines.find((machine) => machine.machineId === owner)?.name ?? owner;
212
+ const declared = presence.block.owners[sense];
213
+ const held = declared && declared !== owner ? ` (roster names ${presence.block.machines.find((machine) => machine.machineId === declared)?.name ?? declared}; held by home until every machine runs presence)` : "";
214
+ lines.push(`- ${sense}: ${name}${held}`);
215
+ }
216
+ return lines.join("\n");
217
+ }
@@ -0,0 +1,380 @@
1
+ "use strict";
2
+ /**
3
+ * Presence: one named agent, present on several machines at once.
4
+ *
5
+ * A bundle opts in with a versioned `presence` block in its synced agent.json:
6
+ *
7
+ * { "presence": { "schema": 1, "minVersion": "0.1.0-alpha.1003",
8
+ * "machines": [{ "machineId": "machine_…", "name": "aris-mac-mini", "role": "always-on" }, …],
9
+ * "owners": { "teams": "machine_…", "habits": "machine_…" } } }
10
+ *
11
+ * and each machine opts in locally with `~/.ouro-cli/presence.json`
12
+ * (`{ "enabled": true }`, never synced) or `OURO_PRESENCE=1`. With the flag
13
+ * off, or the block missing, the one-machine `home` lease applies unchanged.
14
+ *
15
+ * Every presence on a roster machine runs the agent. Machine-scoped senses
16
+ * (cli, shepherd, app-sessions, …) run on every presence; each shared sense
17
+ * (Teams, Telegram, mail, …) and the habits run only on the machine the roster
18
+ * names as its owner.
19
+ *
20
+ * Mixed versions: each presence writes `presence/<machineId>.json` in the
21
+ * bundle (`{ version, seenAt, … }`). A roster machine with no record, or one
22
+ * whose version is below `minVersion`, may run a daemon that knows only
23
+ * `home`, which would run every shared sense itself. Until every roster
24
+ * machine is past that, every shared sense is owned by `home` and handoffs
25
+ * refuse, so one Teams message is never answered twice.
26
+ */
27
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
28
+ if (k2 === undefined) k2 = k;
29
+ var desc = Object.getOwnPropertyDescriptor(m, k);
30
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
31
+ desc = { enumerable: true, get: function() { return m[k]; } };
32
+ }
33
+ Object.defineProperty(o, k2, desc);
34
+ }) : (function(o, m, k, k2) {
35
+ if (k2 === undefined) k2 = k;
36
+ o[k2] = m[k];
37
+ }));
38
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
39
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
40
+ }) : function(o, v) {
41
+ o["default"] = v;
42
+ });
43
+ var __importStar = (this && this.__importStar) || (function () {
44
+ var ownKeys = function(o) {
45
+ ownKeys = Object.getOwnPropertyNames || function (o) {
46
+ var ar = [];
47
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
48
+ return ar;
49
+ };
50
+ return ownKeys(o);
51
+ };
52
+ return function (mod) {
53
+ if (mod && mod.__esModule) return mod;
54
+ var result = {};
55
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
56
+ __setModuleDefault(result, mod);
57
+ return result;
58
+ };
59
+ })();
60
+ Object.defineProperty(exports, "__esModule", { value: true });
61
+ exports.SHARED_SENSES = exports.PRESENCE_FIRST_VERSION = exports.PRESENCE_SCHEMA = void 0;
62
+ exports.isSharedSense = isSharedSense;
63
+ exports.parsePresenceBlock = parsePresenceBlock;
64
+ exports.compareVersions = compareVersions;
65
+ exports.parsePeerRecord = parsePeerRecord;
66
+ exports.peerRecordsDir = peerRecordsDir;
67
+ exports.readPeerRecords = readPeerRecords;
68
+ exports.removePeerRecord = removePeerRecord;
69
+ exports.leavePresence = leavePresence;
70
+ exports.writePeerRecord = writePeerRecord;
71
+ exports.presenceSettingsPath = presenceSettingsPath;
72
+ exports.readLocalPresenceSettings = readLocalPresenceSettings;
73
+ exports.writeLocalPresenceSettings = writeLocalPresenceSettings;
74
+ exports.readPresence = readPresence;
75
+ exports.mayRunSense = mayRunSense;
76
+ exports.readPresenceForAgent = readPresenceForAgent;
77
+ exports.isRosterMember = isRosterMember;
78
+ exports.rosterMachine = rosterMachine;
79
+ exports.effectiveOwner = effectiveOwner;
80
+ exports.ownsSense = ownsSense;
81
+ exports.ownedSharedSenses = ownedSharedSenses;
82
+ exports.findRosterMachine = findRosterMachine;
83
+ exports.emitOwnershipChange = emitOwnershipChange;
84
+ const fs = __importStar(require("fs"));
85
+ const os = __importStar(require("os"));
86
+ const path = __importStar(require("path"));
87
+ const runtime_1 = require("../../nerves/runtime");
88
+ const agent_discovery_1 = require("./agent-discovery");
89
+ exports.PRESENCE_SCHEMA = 1;
90
+ /** The first harness version that knows presence; a rollback below it leaves the roster (see leavePresence). */
91
+ exports.PRESENCE_FIRST_VERSION = "0.1.0-alpha.1024";
92
+ /** Senses that exist once per agent: exactly one machine runs each. */
93
+ exports.SHARED_SENSES = ["teams", "telegram", "mail", "bluebubbles", "voice", "a2a", "habits"];
94
+ function isSharedSense(sense) {
95
+ return exports.SHARED_SENSES.includes(sense);
96
+ }
97
+ function isRecord(value) {
98
+ return !!value && typeof value === "object" && !Array.isArray(value);
99
+ }
100
+ function text(value) {
101
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
102
+ }
103
+ /** Parse agent.json's `presence` block; null when absent, of another schema, or unusable. */
104
+ function parsePresenceBlock(value) {
105
+ if (!isRecord(value) || value.schema !== exports.PRESENCE_SCHEMA || !Array.isArray(value.machines))
106
+ return null;
107
+ const machines = [];
108
+ for (const entry of value.machines) {
109
+ if (!isRecord(entry))
110
+ continue;
111
+ const machineId = text(entry.machineId);
112
+ if (!machineId || machines.some((machine) => machine.machineId === machineId))
113
+ continue;
114
+ machines.push({ machineId, name: text(entry.name) ?? machineId, role: text(entry.role) ?? "peer" });
115
+ }
116
+ if (machines.length === 0)
117
+ return null;
118
+ const owners = {};
119
+ if (isRecord(value.owners)) {
120
+ for (const [sense, owner] of Object.entries(value.owners)) {
121
+ const machineId = text(owner);
122
+ if (machineId)
123
+ owners[sense] = machineId;
124
+ }
125
+ }
126
+ const block = { schema: 1, machines, owners };
127
+ const minVersion = text(value.minVersion);
128
+ if (minVersion)
129
+ block.minVersion = minVersion;
130
+ return block;
131
+ }
132
+ /**
133
+ * Compare two harness versions (`0.1.0-alpha.1003`). Numeric parts compare as
134
+ * numbers; a release sorts after its prereleases.
135
+ */
136
+ function compareVersions(left, right) {
137
+ const split = (version) => {
138
+ const [core, ...pre] = version.trim().replace(/^v/, "").split("-");
139
+ return { core: core.split(".").map((part) => Number(part) || 0), pre: pre.join("-").split(".").filter(Boolean) };
140
+ };
141
+ const a = split(left);
142
+ const b = split(right);
143
+ for (let i = 0; i < Math.max(a.core.length, b.core.length); i++) {
144
+ const diff = (a.core[i] ?? 0) - (b.core[i] ?? 0);
145
+ if (diff !== 0)
146
+ return Math.sign(diff);
147
+ }
148
+ if (a.pre.length === 0 || b.pre.length === 0)
149
+ return Math.sign(b.pre.length - a.pre.length);
150
+ for (let i = 0; i < Math.max(a.pre.length, b.pre.length); i++) {
151
+ const x = a.pre[i];
152
+ const y = b.pre[i];
153
+ if (x === undefined)
154
+ return -1;
155
+ if (y === undefined)
156
+ return 1;
157
+ const nx = Number(x);
158
+ const ny = Number(y);
159
+ const bothNumeric = Number.isFinite(nx) && Number.isFinite(ny);
160
+ const diff = bothNumeric ? nx - ny : x.localeCompare(y);
161
+ if (diff !== 0)
162
+ return Math.sign(diff);
163
+ }
164
+ return 0;
165
+ }
166
+ function parsePeerRecord(value) {
167
+ if (!isRecord(value))
168
+ return null;
169
+ const machineId = text(value.machineId);
170
+ const version = text(value.version);
171
+ const seenAt = text(value.seenAt);
172
+ if (!machineId || !version || !seenAt)
173
+ return null;
174
+ const record = { machineId, version, seenAt };
175
+ for (const key of ["name", "role", "os", "location"]) {
176
+ const field = text(value[key]);
177
+ if (field)
178
+ record[key] = field;
179
+ }
180
+ if (Array.isArray(value.owns))
181
+ record.owns = value.owns.filter((sense) => typeof sense === "string");
182
+ if (isRecord(value.appSessions))
183
+ record.appSessions = value.appSessions;
184
+ return record;
185
+ }
186
+ function peerRecordsDir(agentRoot) {
187
+ return path.join(agentRoot, "presence");
188
+ }
189
+ /** Every presence record in the bundle; unreadable ones are skipped. */
190
+ function readPeerRecords(agentRoot) {
191
+ let names;
192
+ try {
193
+ names = fs.readdirSync(peerRecordsDir(agentRoot));
194
+ }
195
+ catch {
196
+ return [];
197
+ }
198
+ const records = [];
199
+ for (const name of names.filter((entry) => entry.endsWith(".json")).sort()) {
200
+ try {
201
+ const record = parsePeerRecord(JSON.parse(fs.readFileSync(path.join(peerRecordsDir(agentRoot), name), "utf-8")));
202
+ if (record && `${record.machineId}.json` === name)
203
+ records.push(record);
204
+ }
205
+ catch {
206
+ // Skip a record that is mid-write or malformed; the next read sees it.
207
+ }
208
+ }
209
+ return records;
210
+ }
211
+ /** Remove this machine's record (presence turned off here), so peers stop counting it as presence-aware. */
212
+ function removePeerRecord(agentRoot, machineId) {
213
+ const target = path.join(peerRecordsDir(agentRoot), `${machineId}.json`);
214
+ if (!fs.existsSync(target))
215
+ return false;
216
+ fs.rmSync(target, { force: true });
217
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.presence_record_removed", message: "presence is off here; removed this machine's record", meta: { agentRoot, machineId } });
218
+ return true;
219
+ }
220
+ /**
221
+ * Leave presence in a bundle: remove this machine's record and publish the
222
+ * removal, so peers fall back to `home` before this machine runs shared senses
223
+ * under the home lease. True when the bundle no longer holds this machine's
224
+ * record on its remote (or never did, or does not sync).
225
+ */
226
+ async function leavePresence(agentRoot, machineId, publish) {
227
+ if (!removePeerRecord(agentRoot, machineId))
228
+ return true;
229
+ return publish(agentRoot);
230
+ }
231
+ /** Write this machine's own record. Each machine writes only its own file, so two presences never edit one file. */
232
+ function writePeerRecord(agentRoot, record) {
233
+ const dir = peerRecordsDir(agentRoot);
234
+ fs.mkdirSync(dir, { recursive: true });
235
+ const target = path.join(dir, `${record.machineId}.json`);
236
+ const temp = `${target}.${process.pid}.tmp`;
237
+ fs.writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`, "utf-8");
238
+ fs.renameSync(temp, target);
239
+ return target;
240
+ }
241
+ function presenceSettingsPath(homeDir = os.homedir()) {
242
+ return path.join(homeDir, ".ouro-cli", "presence.json");
243
+ }
244
+ /** This machine's local opt-in. `OURO_PRESENCE=1|0` overrides the file. */
245
+ function readLocalPresenceSettings(homeDir = os.homedir(), env = process.env) {
246
+ let settings = { enabled: false };
247
+ try {
248
+ const parsed = JSON.parse(fs.readFileSync(presenceSettingsPath(homeDir), "utf-8"));
249
+ if (isRecord(parsed)) {
250
+ settings = { enabled: parsed.enabled === true };
251
+ const location = text(parsed.location);
252
+ if (location)
253
+ settings.location = location;
254
+ if (typeof parsed.nice === "number" && Number.isInteger(parsed.nice) && parsed.nice >= -20 && parsed.nice <= 20)
255
+ settings.nice = parsed.nice;
256
+ const argv = (value) => (Array.isArray(value) && value.length > 0 && value.every((part) => typeof part === "string") ? value : null);
257
+ const locationCommand = argv(parsed.locationCommand);
258
+ if (locationCommand)
259
+ settings.locationCommand = locationCommand;
260
+ if (isRecord(parsed.onArrive)) {
261
+ const onArrive = {};
262
+ for (const [place, command] of Object.entries(parsed.onArrive)) {
263
+ const parsedCommand = argv(command);
264
+ if (parsedCommand)
265
+ onArrive[place] = parsedCommand;
266
+ }
267
+ if (Object.keys(onArrive).length > 0)
268
+ settings.onArrive = onArrive;
269
+ }
270
+ }
271
+ }
272
+ catch {
273
+ // No file: presence is off on this machine.
274
+ }
275
+ if (env.OURO_PRESENCE === "1")
276
+ settings.enabled = true;
277
+ if (env.OURO_PRESENCE === "0")
278
+ settings.enabled = false;
279
+ return settings;
280
+ }
281
+ function writeLocalPresenceSettings(settings, homeDir = os.homedir()) {
282
+ const target = presenceSettingsPath(homeDir);
283
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
284
+ fs.writeFileSync(target, `${JSON.stringify(settings, null, 2)}\n`, "utf-8");
285
+ }
286
+ /**
287
+ * The presence this machine should follow, or null for today's one-home lease
288
+ * (flag off, or no usable block).
289
+ */
290
+ function readPresence(agentJson, localFlag, peerRecords) {
291
+ if (!localFlag || !isRecord(agentJson))
292
+ return null;
293
+ const block = parsePresenceBlock(agentJson.presence);
294
+ if (!block)
295
+ return null;
296
+ const home = (0, agent_discovery_1.parseAgentHome)(agentJson.home);
297
+ const current = (machineId) => {
298
+ const record = peerRecords.find((peer) => peer.machineId === machineId);
299
+ if (!record)
300
+ return false;
301
+ return block.minVersion === undefined || compareVersions(record.version, block.minVersion) >= 0;
302
+ };
303
+ const legacy = block.machines.filter((machine) => !current(machine.machineId)).map((machine) => machine.machineId);
304
+ // A home off the roster runs every shared sense under the home lease.
305
+ if (home && !block.machines.some((machine) => machine.machineId === home.machineId))
306
+ legacy.push(home.machineId);
307
+ return { block, home, legacy, peers: peerRecords };
308
+ }
309
+ /**
310
+ * Whether this machine may run a sense now: it owns it, and, for a shared
311
+ * sense, no other roster machine's record still says it runs it. A new owner
312
+ * waits for the old owner to publish that it let go, so a handoff never runs
313
+ * a sense on two machines. Ownership is static: a silent old owner keeps its
314
+ * claim until it publishes again or leaves the roster (no timeout, because a
315
+ * sleeping laptop and a machine whose sync broke look the same as a dead one).
316
+ */
317
+ function mayRunSense(presence, machineId, sense) {
318
+ if (!ownsSense(presence, machineId, sense))
319
+ return false;
320
+ if (!isSharedSense(sense))
321
+ return true;
322
+ return !presence.peers.some((peer) => peer.machineId !== machineId && isRosterMember(presence, peer.machineId) && peer.owns?.includes(sense));
323
+ }
324
+ /** Read the bundle's agent.json, the local flag and the peer records together. */
325
+ function readPresenceForAgent(agentRoot, options = {}) {
326
+ const settings = readLocalPresenceSettings(options.homeDir, options.env);
327
+ if (!settings.enabled)
328
+ return null;
329
+ let agentJson;
330
+ try {
331
+ agentJson = JSON.parse(fs.readFileSync(path.join(agentRoot, "agent.json"), "utf-8"));
332
+ }
333
+ catch {
334
+ return null;
335
+ }
336
+ return readPresence(agentJson, true, readPeerRecords(agentRoot));
337
+ }
338
+ function isRosterMember(presence, machineId) {
339
+ return presence.block.machines.some((machine) => machine.machineId === machineId);
340
+ }
341
+ function rosterMachine(presence, machineId) {
342
+ return presence.block.machines.find((machine) => machine.machineId === machineId);
343
+ }
344
+ /**
345
+ * The machine that runs a shared sense. While any roster machine may run a
346
+ * daemon that knows only `home`, that is `home`, whatever the roster says.
347
+ */
348
+ function effectiveOwner(presence, sense) {
349
+ if (presence.legacy.length > 0 && presence.home)
350
+ return presence.home.machineId;
351
+ return presence.block.owners[sense] ?? presence.home?.machineId ?? presence.block.machines[0].machineId;
352
+ }
353
+ /** Whether this machine runs this sense under the roster. Machine-scoped senses run on every roster machine. */
354
+ function ownsSense(presence, machineId, sense) {
355
+ if (!isRosterMember(presence, machineId))
356
+ return false;
357
+ if (!isSharedSense(sense))
358
+ return true;
359
+ return effectiveOwner(presence, sense) === machineId;
360
+ }
361
+ function ownedSharedSenses(presence, machineId) {
362
+ return exports.SHARED_SENSES.filter((sense) => ownsSense(presence, machineId, sense));
363
+ }
364
+ /** A machine name a person would type: case-insensitive, `.local` ignored; ids match too. */
365
+ function findRosterMachine(presence, nameOrId) {
366
+ const wanted = nameOrId.trim().replace(/\.local$/i, "").toLowerCase();
367
+ return presence.block.machines.find((machine) => machine.machineId.toLowerCase() === wanted || machine.name.toLowerCase() === wanted);
368
+ }
369
+ /**
370
+ * Whether a shared sense this machine owns is currently being handed to
371
+ * another machine: used by the daemon to log the moment ownership changes.
372
+ */
373
+ function emitOwnershipChange(agent, sense, owns, owner) {
374
+ (0, runtime_1.emitNervesEvent)({
375
+ component: "daemon",
376
+ event: owns ? "daemon.presence_sense_owned" : "daemon.presence_sense_released",
377
+ message: owns ? `${sense} is owned by this machine` : `${sense} is owned by another machine`,
378
+ meta: { agent, sense, owner },
379
+ });
380
+ }