@ouro.bot/cli 0.1.0-alpha.1588 → 0.1.0-alpha.1589

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 CHANGED
@@ -1,6 +1,12 @@
1
1
  {
2
2
  "_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1589",
6
+ "changes": [
7
+ "When the channel you hear your agent on (iMessage, Telegram or Teams) has been down for more than 15 minutes, the daemon now tells you once over a channel that still works: the agent's other healthy owner channel first, then mail from the agent's own mailbox to your address. You get one more message once the channel has stayed back for two minutes. It sends at most one alert per channel an hour, treats a channel that flaps as one outage, doesn't count time the Mac was asleep, and keeps its state in the bundle so a daemon restart doesn't repeat it. Mail goes to the `email-address` id on your own friend record, else to the owner of the agent's delegated mail source; with neither, the daemon logs `daemon.owner_outage_alert_undelivered`. The alert never waits in Telegram's queue: if Telegram would hold it for quiet hours, a handoff or another agent, it is dropped there and goes by mail instead, so it never arrives late."
8
+ ]
9
+ },
4
10
  {
5
11
  "version": "0.1.0-alpha.1588",
6
12
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1588",
2
+ "runtimeVersion": "0.1.0-alpha.1589",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1588</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1589</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -43,6 +43,7 @@ const runtime_1 = require("../../nerves/runtime");
43
43
  const index_1 = require("../../nerves/index");
44
44
  const message_router_1 = require("./message-router");
45
45
  const health_monitor_1 = require("./health-monitor");
46
+ const owner_channel_outage_1 = require("./owner-channel-outage");
46
47
  const daemon_health_1 = require("./daemon-health");
47
48
  const daemon_rollup_1 = require("./daemon-rollup");
48
49
  const task_scheduler_1 = require("./task-scheduler");
@@ -406,7 +407,22 @@ const router = new message_router_1.FileMessageRouter();
406
407
  const senseManager = new sense_manager_1.DaemonSenseManager({
407
408
  agents: [...managedAgents],
408
409
  });
410
+ // Tells the owner over a working channel when the channel they hear the agent on stays down (owner-channel-outage.ts).
411
+ const ownerChannelOutageWatcher = new owner_channel_outage_1.OwnerChannelOutageWatcher({
412
+ agents: () => [...managedAgents],
413
+ listSenseRows: () => senseManager.listSenseRows(),
414
+ statePath: (agent) => path.join((0, identity_1.getAgentBundlesRoot)(), `${agent}.ouro`, "state", "owner-channel-outage.json"),
415
+ routes: (agent) => (0, owner_channel_outage_1.lazyOwnerAlertRoutes)(agent, path.join((0, identity_1.getAgentBundlesRoot)(), `${agent}.ouro`)),
416
+ /* v8 ignore next -- wiring: reads the agent's own config @preserve */
417
+ displayName: (agent) => { try {
418
+ return (0, identity_1.loadAgentConfig)({ agentName: agent, agentRoot: path.join((0, identity_1.getAgentBundlesRoot)(), `${agent}.ouro`) }).displayName ?? agent;
419
+ }
420
+ catch {
421
+ return agent;
422
+ } },
423
+ });
409
424
  const healthMonitor = new health_monitor_1.HealthMonitor({
425
+ afterChecks: (results) => ownerChannelOutageWatcher.check(results),
410
426
  processManager,
411
427
  scheduler,
412
428
  diskUsagePercent: () => (0, health_monitor_1.readDiskUsagePercent)((0, identity_1.getAgentBundlesRoot)()),
@@ -79,6 +79,7 @@ class HealthMonitor {
79
79
  onCriticalSense;
80
80
  senseProbes;
81
81
  senseProbeProvider;
82
+ afterChecks;
82
83
  intervalHandle = null;
83
84
  lastResults = [];
84
85
  constructor(options) {
@@ -93,6 +94,7 @@ class HealthMonitor {
93
94
  this.onCriticalSense = options.onCriticalSense ?? (() => undefined);
94
95
  this.senseProbes = options.senseProbes ?? [];
95
96
  this.senseProbeProvider = options.senseProbeProvider ?? (() => []);
97
+ this.afterChecks = options.afterChecks ?? (() => undefined);
96
98
  }
97
99
  triggerSenseRecovery(probe, detail) {
98
100
  if (!probe.managedName)
@@ -300,6 +302,18 @@ class HealthMonitor {
300
302
  await this.alertSink(`[critical] ${result.name}: ${result.message}`);
301
303
  }
302
304
  }
305
+ const handed = results.map((result) => ({ ...result }));
306
+ void Promise.resolve()
307
+ .then(() => this.afterChecks(handed))
308
+ .catch((error) => {
309
+ (0, runtime_1.emitNervesEvent)({
310
+ level: "warn",
311
+ component: "daemon",
312
+ event: "daemon.health_after_checks_failed",
313
+ message: "a step after the health checks failed",
314
+ meta: { error: error instanceof Error ? error.message : String(error) },
315
+ });
316
+ });
303
317
  return results;
304
318
  }
305
319
  getLastResults() {
@@ -0,0 +1,159 @@
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.resolveOwnerAlertAddress = resolveOwnerAlertAddress;
37
+ exports.createOwnerAlertMailSender = createOwnerAlertMailSender;
38
+ exports.createOwnerAlertTelegramSender = createOwnerAlertTelegramSender;
39
+ exports.ownerAlertRoutes = ownerAlertRoutes;
40
+ const path = __importStar(require("path"));
41
+ const friends_1 = require("@ouro.bot/friends");
42
+ const core_1 = require("../../mailroom/core");
43
+ const reader_1 = require("../../mailroom/reader");
44
+ const outbound_1 = require("../../mailroom/outbound");
45
+ const runtime_1 = require("../../nerves/runtime");
46
+ const SEND_TIMEOUT_MS = 30_000;
47
+ function errorText(error) {
48
+ return error instanceof Error ? error.message : String(error);
49
+ }
50
+ /* v8 ignore start -- the live defaults; tests inject each one @preserve */
51
+ const defaults = {
52
+ listFriends: (agentRoot) => new friends_1.FileFriendStore(path.join(agentRoot, "friends")).listAll(),
53
+ ownerUsername: friends_1.machineOwnerUsername,
54
+ resolveMailroom: reader_1.resolveMailroomReaderWithRefresh,
55
+ readRegistry: reader_1.readMailroomRegistry,
56
+ createDraft: outbound_1.createMailDraft,
57
+ confirmSend: outbound_1.confirmMailDraftSend,
58
+ resolveTransport: outbound_1.resolveOutboundTransport,
59
+ providerClient: async (agent, transport) => (await Promise.resolve().then(() => __importStar(require("../../repertoire/tools-mail")))).outboundProviderClientForTransport(agent, transport),
60
+ sendTelegram: async (agent, input) => (await Promise.resolve().then(() => __importStar(require("../../senses/telegram")))).sendTelegramOwnerNotice(agent, input),
61
+ };
62
+ /* v8 ignore stop */
63
+ function withDefaults(deps) {
64
+ return { ...defaults, ...deps };
65
+ }
66
+ function idsOf(friend) {
67
+ return Array.isArray(friend.externalIds) ? friend.externalIds : [];
68
+ }
69
+ function emailIds(friend) {
70
+ return idsOf(friend)
71
+ .filter((entry) => entry?.provider === "email-address" && typeof entry.externalId === "string" && entry.externalId.includes("@"))
72
+ .map((entry) => (0, core_1.normalizeMailAddress)(entry.externalId));
73
+ }
74
+ /** The owner's mail address, or null when the agent's records name none. */
75
+ async function resolveOwnerAlertAddress(agentRoot, config, deps = {}) {
76
+ const d = withDefaults(deps);
77
+ const username = d.ownerUsername();
78
+ let friends = [];
79
+ try {
80
+ friends = await d.listFriends(agentRoot);
81
+ }
82
+ catch (error) {
83
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "daemon.owner_alert_friends_unreadable", message: "could not read friends to find the owner's mail address", meta: { agentRoot, error: errorText(error) } });
84
+ }
85
+ const owners = friends.filter((friend) => friend.trustLevel === "family" && idsOf(friend)
86
+ .some((entry) => typeof entry?.provider === "string" && typeof entry.externalId === "string" && (0, friends_1.isLocalMachineOwnerIdentity)(entry.provider, entry.externalId, username)));
87
+ const fromFriend = owners.flatMap(emailIds).sort()[0];
88
+ if (fromFriend)
89
+ return fromFriend;
90
+ try {
91
+ const registry = await d.readRegistry(config);
92
+ const grants = (registry.sourceGrants ?? []).filter((grant) => grant.enabled && grant.ownerEmail?.includes("@"));
93
+ const fromGrant = grants.map((grant) => (0, core_1.normalizeMailAddress)(grant.ownerEmail)).sort()[0];
94
+ if (fromGrant)
95
+ return fromGrant;
96
+ }
97
+ catch (error) {
98
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "daemon.owner_alert_registry_unreadable", message: "could not read the mailroom registry to find the owner's mail address", meta: { agentRoot, error: errorText(error) } });
99
+ }
100
+ return null;
101
+ }
102
+ function createOwnerAlertMailSender(agent, agentRoot, deps = {}) {
103
+ const d = withDefaults(deps);
104
+ return async (message) => {
105
+ const resolved = await d.resolveMailroom(agent);
106
+ if (!resolved.ok)
107
+ throw new Error(`mail is not available: ${resolved.error}`);
108
+ if (resolved.config.autonomousSendPolicy?.killSwitch)
109
+ throw new Error("the mail autonomy kill switch is on");
110
+ const to = await resolveOwnerAlertAddress(agentRoot, resolved.config, deps);
111
+ if (!to)
112
+ throw new Error("no owner mail address: link the owner's email-address id on their friend record");
113
+ // Transport and provider first, so a send that can't go out leaves no draft behind.
114
+ const transport = d.resolveTransport(resolved.config);
115
+ const providerClient = await d.providerClient(agent, transport);
116
+ const reason = `harness owner-channel outage notice ${message.noticeId}`;
117
+ const actor = { kind: "system", agentId: agent };
118
+ const draft = await d.createDraft({
119
+ store: resolved.store,
120
+ agentId: resolved.agentName,
121
+ from: resolved.config.mailboxAddress,
122
+ to: [to],
123
+ subject: message.subject,
124
+ text: message.text,
125
+ actor,
126
+ reason,
127
+ });
128
+ await d.confirmSend({
129
+ store: resolved.store,
130
+ agentId: resolved.agentName,
131
+ draftId: draft.id,
132
+ transport,
133
+ confirmation: "CONFIRM_SEND",
134
+ autonomous: false,
135
+ autonomyPolicy: resolved.config.autonomousSendPolicy,
136
+ providerClient,
137
+ actor,
138
+ reason,
139
+ });
140
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.owner_alert_mail_sent", message: "mailed the owner a harness notice", meta: { agent, noticeId: message.noticeId, draftId: draft.id } });
141
+ };
142
+ }
143
+ function createOwnerAlertTelegramSender(agent, deps = {}) {
144
+ const d = withDefaults(deps);
145
+ return async (message) => {
146
+ const outcome = await d.sendTelegram(agent, { noticeId: message.noticeId, text: message.text, signal: AbortSignal.timeout(SEND_TIMEOUT_MS), nowOrNever: true });
147
+ // Quiet hours, a handoff, or an owner route (which may relay over the channel that is down): dropped, not held, so the
148
+ // owner never gets a stale copy later; the next route carries it.
149
+ if (outcome !== "sent")
150
+ throw new Error("Telegram couldn't send the notice to the owner's chat now");
151
+ };
152
+ }
153
+ /** Every route the daemon can send an agent's outage alert on; the watcher uses only those whose sense is healthy. */
154
+ function ownerAlertRoutes(agent, agentRoot, deps = {}) {
155
+ return {
156
+ telegram: createOwnerAlertTelegramSender(agent, deps),
157
+ mail: createOwnerAlertMailSender(agent, agentRoot, deps),
158
+ };
159
+ }
@@ -0,0 +1,386 @@
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.OwnerChannelOutageWatcher = exports.OWNER_OUTAGE_SEND_TIMEOUT_MS = exports.OWNER_OUTAGE_SIGHTING_GAP_MS = exports.OWNER_OUTAGE_RECOVERY_CONFIRM_MS = exports.OWNER_OUTAGE_RETRY_MS = exports.OWNER_OUTAGE_ALERT_MIN_INTERVAL_MS = exports.OWNER_OUTAGE_THRESHOLD_MS = exports.OWNER_CHANNEL_SENSES = void 0;
37
+ exports.formatOutageDuration = formatOutageDuration;
38
+ exports.outageAlertMessage = outageAlertMessage;
39
+ exports.outageRecoveredMessage = outageRecoveredMessage;
40
+ exports.lazyOwnerAlertRoutes = lazyOwnerAlertRoutes;
41
+ const fs = __importStar(require("fs"));
42
+ const path = __importStar(require("path"));
43
+ const runtime_1 = require("../../nerves/runtime");
44
+ /**
45
+ * Tells the owner when the channel they hear their agent on has been down for a while, over a channel that still works.
46
+ *
47
+ * On 2026-11-25 Slugger's iMessage (the BlueBubbles sense) was in error for 13 hours and nobody heard: the health alert
48
+ * only logged and restarted the sense, and the owner notice either went to Telegram (off for Slugger) or was queued for
49
+ * Slugger to relay over iMessage, the channel that was down. This watcher runs in the daemon after every health check.
50
+ * When an enabled owner channel has been in error for longer than `OWNER_OUTAGE_THRESHOLD_MS`, it sends one alert over
51
+ * the agent's other healthy owner channels, then its mail sense, and one "back" message when the channel recovers. Its
52
+ * state is kept in the bundle's `state/`, so a daemon restart neither re-sends nor forgets an outage.
53
+ */
54
+ /** Senses the owner hears their agent on, in the order a fallback alert tries them. */
55
+ exports.OWNER_CHANNEL_SENSES = ["bluebubbles", "telegram", "teams"];
56
+ /**
57
+ * How long a channel must stay down before the owner hears about it: 15 minutes, the same bar the Telegram sense uses
58
+ * before telling the owner its owner route is down (`OWNER_ROUTE_WATCH_FAILURES` x `OWNER_ROUTE_WATCH_INTERVAL_MS`).
59
+ * It is long enough that the daemon's own restart (the next 60-second health check) and the BlueBubbles proof watch's
60
+ * first restart (10 minutes of stale proof) get their chance first, and short enough that the owner hears within the
61
+ * quarter hour, not after 13 hours.
62
+ */
63
+ exports.OWNER_OUTAGE_THRESHOLD_MS = 15 * 60_000;
64
+ /** At most one outage alert per channel an hour, so a flapping channel never floods the fallback channel. */
65
+ exports.OWNER_OUTAGE_ALERT_MIN_INTERVAL_MS = 60 * 60_000;
66
+ /** After every route failed, wait this long before trying again. */
67
+ exports.OWNER_OUTAGE_RETRY_MS = 5 * 60_000;
68
+ /**
69
+ * A channel must read healthy this long before its outage ends, so a sense that crash-loops or flaps between health
70
+ * checks is still one outage, and the owner hears "back" only once it has stayed up (two more 60-second checks).
71
+ */
72
+ exports.OWNER_OUTAGE_RECOVERY_CONFIRM_MS = 2 * 60_000;
73
+ /**
74
+ * A gap this long between two sightings of an outage that hasn't been told yet means the daemon couldn't see (the Mac
75
+ * slept or the daemon was stopped), so the outage's clock starts again rather than counting time nobody watched.
76
+ */
77
+ exports.OWNER_OUTAGE_SIGHTING_GAP_MS = 10 * 60_000;
78
+ /** One route's send that takes longer than this counts as failed, so a hung network call never stops the watcher. */
79
+ exports.OWNER_OUTAGE_SEND_TIMEOUT_MS = 60_000;
80
+ /** Statuses a channel can carry an alert on. */
81
+ const HEALTHY_STATUSES = new Set(["running", "interactive", "ready"]);
82
+ /** Statuses that mean the channel itself is back (a process is running), so the owner hears "back". */
83
+ const RECOVERED_STATUSES = new Set(["running", "interactive"]);
84
+ const DETAIL_MAX = 300;
85
+ const CHANNEL_LABEL = { bluebubbles: "iMessage", telegram: "Telegram", teams: "Teams" };
86
+ function errorText(error) {
87
+ return error instanceof Error ? error.message : String(error);
88
+ }
89
+ function emptyState() {
90
+ return { schemaVersion: 1, outages: {}, lastAlertAt: {} };
91
+ }
92
+ function isRecord(value) {
93
+ return !!value && typeof value === "object" && !Array.isArray(value);
94
+ }
95
+ function readState(file) {
96
+ let parsed;
97
+ try {
98
+ parsed = JSON.parse(fs.readFileSync(file, "utf-8"));
99
+ }
100
+ catch {
101
+ return emptyState();
102
+ }
103
+ if (!isRecord(parsed) || parsed.schemaVersion !== 1 || !isRecord(parsed.outages) || !isRecord(parsed.lastAlertAt))
104
+ return emptyState();
105
+ return parsed;
106
+ }
107
+ function writeState(agent, file, state) {
108
+ try {
109
+ fs.mkdirSync(path.dirname(file), { recursive: true });
110
+ const temp = `${file}.${process.pid}.tmp`;
111
+ fs.writeFileSync(temp, `${JSON.stringify(state, null, 2)}\n`, "utf-8");
112
+ fs.renameSync(temp, file);
113
+ }
114
+ catch (error) {
115
+ (0, runtime_1.emitNervesEvent)({
116
+ level: "warn",
117
+ component: "daemon",
118
+ event: "daemon.owner_outage_state_write_failed",
119
+ message: "could not save the owner-channel outage state; a restart may repeat an alert",
120
+ meta: { agent, error: errorText(error) },
121
+ });
122
+ }
123
+ }
124
+ /** "4 min", "2 h 14 min", "13 h". */
125
+ function formatOutageDuration(ms) {
126
+ const minutes = Math.max(1, Math.round(ms / 60_000));
127
+ if (minutes < 60)
128
+ return `${minutes} min`;
129
+ const hours = Math.floor(minutes / 60);
130
+ const rest = minutes % 60;
131
+ return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`;
132
+ }
133
+ function plainDetail(detail) {
134
+ const flat = detail.replace(/\s+/g, " ").trim();
135
+ return flat.length <= DETAIL_MAX ? flat : `${flat.slice(0, DETAIL_MAX - 1).trimEnd()}…`;
136
+ }
137
+ function outageAlertMessage(input) {
138
+ const channel = CHANNEL_LABEL[input.sense];
139
+ const duration = formatOutageDuration(input.nowMs - Date.parse(input.downSince));
140
+ const detail = plainDetail(input.detail);
141
+ return {
142
+ noticeId: `owner-channel-outage:${input.agent}:${input.sense}:${input.downSince}:down`,
143
+ subject: `${input.name}: ${channel} has been down for ${duration}`,
144
+ text: [
145
+ `${input.name} can't reach you on ${channel}: it has been down for ${duration}.`,
146
+ ...(detail ? [`What the daemon sees: ${detail}`] : []),
147
+ `It keeps trying to bring ${channel} back, and you'll get one more message here when it is.`,
148
+ `Messages you send ${input.name} on ${channel} may not arrive until then.`,
149
+ ].join("\n"),
150
+ };
151
+ }
152
+ /** `nowMs` is when it first read healthy again. */
153
+ function outageRecoveredMessage(input) {
154
+ const channel = CHANNEL_LABEL[input.sense];
155
+ const duration = formatOutageDuration(input.nowMs - Date.parse(input.downSince));
156
+ return {
157
+ noticeId: `owner-channel-outage:${input.agent}:${input.sense}:${input.downSince}:back`,
158
+ subject: `${input.name}: ${channel} is back`,
159
+ text: `${input.name} can reach you on ${channel} again, after ${duration} down.`,
160
+ };
161
+ }
162
+ class OwnerChannelOutageWatcher {
163
+ options;
164
+ now;
165
+ thresholdMs;
166
+ minIntervalMs;
167
+ retryMs;
168
+ recoveryConfirmMs;
169
+ sightingGapMs;
170
+ sendTimeoutMs;
171
+ running = null;
172
+ /** Each agent's state, read from disk once; memory stays the authority when a write fails. */
173
+ states = new Map();
174
+ constructor(options) {
175
+ this.options = options;
176
+ this.now = options.now ?? Date.now;
177
+ this.thresholdMs = options.thresholdMs ?? exports.OWNER_OUTAGE_THRESHOLD_MS;
178
+ this.minIntervalMs = options.minIntervalMs ?? exports.OWNER_OUTAGE_ALERT_MIN_INTERVAL_MS;
179
+ this.retryMs = options.retryMs ?? exports.OWNER_OUTAGE_RETRY_MS;
180
+ this.recoveryConfirmMs = options.recoveryConfirmMs ?? exports.OWNER_OUTAGE_RECOVERY_CONFIRM_MS;
181
+ this.sightingGapMs = options.sightingGapMs ?? exports.OWNER_OUTAGE_SIGHTING_GAP_MS;
182
+ this.sendTimeoutMs = options.sendTimeoutMs ?? exports.OWNER_OUTAGE_SEND_TIMEOUT_MS;
183
+ }
184
+ /** One pass over every agent's owner channels. A pass still sending makes this one a no-op. */
185
+ check(results) {
186
+ if (this.running)
187
+ return this.running;
188
+ this.running = this.checkAll(results).finally(() => { this.running = null; });
189
+ return this.running;
190
+ }
191
+ async checkAll(results) {
192
+ const rows = this.options.listSenseRows();
193
+ for (const agent of this.options.agents()) {
194
+ try {
195
+ await this.checkAgent(agent, rows.filter((row) => row.agent === agent), results);
196
+ }
197
+ catch (error) {
198
+ (0, runtime_1.emitNervesEvent)({
199
+ level: "warn",
200
+ component: "daemon",
201
+ event: "daemon.owner_outage_check_failed",
202
+ message: "could not check this agent's owner channels",
203
+ meta: { agent, error: errorText(error) },
204
+ });
205
+ }
206
+ }
207
+ }
208
+ down(agent, row, results) {
209
+ if (row.status === "error")
210
+ return row.detail || row.lastFailure || "the sense is in error";
211
+ // The BlueBubbles proof watch: the listener is alive but its sync loop has stopped.
212
+ if (row.sense === "bluebubbles") {
213
+ const probe = results.find((result) => result.name === `sense-probe:bluebubbles-proof:${agent}` && result.status === "critical");
214
+ if (probe)
215
+ return probe.message;
216
+ // A listener that has never written proof never trips the proof watch's staleness check, so it reads "running".
217
+ if (row.status === "running" && !row.lastProofAt)
218
+ return "the iMessage listener is running but has never shown that it is connected to BlueBubbles";
219
+ }
220
+ return null;
221
+ }
222
+ async checkAgent(agent, rows, results) {
223
+ const file = this.options.statePath(agent);
224
+ let state = this.states.get(agent);
225
+ if (!state) {
226
+ state = readState(file);
227
+ this.states.set(agent, state);
228
+ }
229
+ const nowMs = this.now();
230
+ const nowIso = new Date(nowMs).toISOString();
231
+ const name = () => this.options.displayName?.(agent) ?? agent;
232
+ let changed = false;
233
+ const rowFor = (sense) => rows.find((row) => row.sense === sense && row.enabled);
234
+ const downNow = new Map();
235
+ for (const sense of exports.OWNER_CHANNEL_SENSES) {
236
+ const row = rowFor(sense);
237
+ const detail = row ? this.down(agent, row, results) : null;
238
+ if (detail !== null)
239
+ downNow.set(sense, detail);
240
+ }
241
+ // Routes that work now: another owner channel that is up, then mail.
242
+ const senders = this.options.routes(agent);
243
+ const workingRoutes = (except) => {
244
+ const list = [];
245
+ for (const sense of exports.OWNER_CHANNEL_SENSES) {
246
+ const row = rowFor(sense);
247
+ const send = senders[sense];
248
+ if (sense !== except && send && row && HEALTHY_STATUSES.has(row.status) && !downNow.has(sense))
249
+ list.push([sense, send]);
250
+ }
251
+ if (senders.mail && rowFor("mail"))
252
+ list.push(["mail", senders.mail]);
253
+ return list;
254
+ };
255
+ for (const sense of exports.OWNER_CHANNEL_SENSES) {
256
+ const detail = downNow.get(sense);
257
+ const outage = state.outages[sense];
258
+ if (detail !== undefined) {
259
+ const current = outage ?? { downSince: nowIso, detail };
260
+ if (!outage) {
261
+ state.outages[sense] = current;
262
+ changed = true;
263
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "daemon.owner_outage_started", message: "an owner channel is down; the owner hears if it stays down", meta: { agent, sense, thresholdMs: this.thresholdMs } });
264
+ }
265
+ if (current.detail !== detail)
266
+ current.detail = detail;
267
+ // Unseen time is not counted: the clock of an outage not yet told restarts after a gap in sightings.
268
+ if (!current.alertedAt && current.lastSeenDownAt && nowMs - Date.parse(current.lastSeenDownAt) > this.sightingGapMs)
269
+ current.downSince = nowIso;
270
+ current.lastSeenDownAt = nowIso;
271
+ delete current.healthySince;
272
+ changed = true;
273
+ if (current.alertedAt)
274
+ continue;
275
+ if (nowMs - Date.parse(current.downSince) < this.thresholdMs)
276
+ continue;
277
+ const lastAlert = state.lastAlertAt[sense];
278
+ if (lastAlert && nowMs - Date.parse(lastAlert) < this.minIntervalMs)
279
+ continue;
280
+ if (current.lastAttemptAt && nowMs - Date.parse(current.lastAttemptAt) < this.retryMs)
281
+ continue;
282
+ current.lastAttemptAt = nowIso;
283
+ changed = true;
284
+ const via = await this.deliver(agent, sense, "down", workingRoutes(sense), outageAlertMessage({ agent, name: name(), sense, downSince: current.downSince, detail, nowMs }));
285
+ if (via) {
286
+ current.alertedAt = nowIso;
287
+ current.alertedVia = via;
288
+ state.lastAlertAt[sense] = nowIso;
289
+ }
290
+ continue;
291
+ }
292
+ if (!outage)
293
+ continue;
294
+ const row = rowFor(sense);
295
+ const status = row?.status ?? "disabled";
296
+ // Turned off, moved to another machine, or waiting on setup rather than recovered: nothing to wait for.
297
+ const gone = !row || !HEALTHY_STATUSES.has(status);
298
+ if (!gone && (outage.alertedAt ? RECOVERED_STATUSES.has(status) : true)) {
299
+ if (!outage.healthySince) {
300
+ outage.healthySince = nowIso;
301
+ changed = true;
302
+ }
303
+ if (nowMs - Date.parse(outage.healthySince) < this.recoveryConfirmMs)
304
+ continue;
305
+ }
306
+ else if (!gone) {
307
+ // Told, and configured but with no process yet: "back" waits until it is running, for a fresh two minutes.
308
+ if (outage.healthySince) {
309
+ delete outage.healthySince;
310
+ changed = true;
311
+ }
312
+ continue;
313
+ }
314
+ if (!outage.alertedAt || gone) {
315
+ delete state.outages[sense];
316
+ changed = true;
317
+ (0, runtime_1.emitNervesEvent)({
318
+ level: outage.alertedAt ? "warn" : "info",
319
+ component: "daemon",
320
+ event: "daemon.owner_outage_cleared",
321
+ message: outage.alertedAt ? "an owner channel the owner was told is down stopped being watched before it came back" : "an owner channel outage ended before the owner needed to hear",
322
+ meta: { agent, sense, alerted: Boolean(outage.alertedAt), status },
323
+ });
324
+ continue;
325
+ }
326
+ // The alert's own attempt time no longer applies; the retry wait now spaces "back" attempts.
327
+ if (outage.lastAttemptAt && Date.parse(outage.lastAttemptAt) > Date.parse(outage.alertedAt) && nowMs - Date.parse(outage.lastAttemptAt) < this.retryMs)
328
+ continue;
329
+ outage.lastAttemptAt = nowIso;
330
+ changed = true;
331
+ // Where the owner heard about the outage goes first, so the alert and its close sit together; the recovered
332
+ // channel itself is the last resort.
333
+ const routes = workingRoutes(sense);
334
+ const own = senders[sense];
335
+ if (own)
336
+ routes.push([sense, own]);
337
+ routes.sort(([a], [b]) => Number(b === outage.alertedVia) - Number(a === outage.alertedVia));
338
+ // Kept until "back" is sent, so a failed send is tried again.
339
+ if (await this.deliver(agent, sense, "back", routes, outageRecoveredMessage({ agent, name: name(), sense, downSince: outage.downSince, nowMs: Date.parse(outage.healthySince) })))
340
+ delete state.outages[sense];
341
+ }
342
+ if (changed)
343
+ writeState(agent, file, state);
344
+ }
345
+ /** Tries each route in order; the route that sent it, or null. */
346
+ async deliver(agent, sense, kind, routes, message) {
347
+ const failures = [];
348
+ for (const [route, send] of routes) {
349
+ try {
350
+ let timer;
351
+ const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`timed out after ${this.sendTimeoutMs} ms`)), this.sendTimeoutMs); });
352
+ try {
353
+ await Promise.race([send(message), timeout]);
354
+ }
355
+ finally {
356
+ clearTimeout(timer);
357
+ }
358
+ (0, runtime_1.emitNervesEvent)({ level: kind === "down" ? "warn" : "info", component: "daemon", event: "daemon.owner_outage_alert_sent", message: kind === "down" ? "told the owner an owner channel is down" : "told the owner an owner channel is back", meta: { agent, sense, kind, route, failedRoutes: failures } });
359
+ return route;
360
+ }
361
+ catch (error) {
362
+ failures.push(`${route}: ${errorText(error)}`);
363
+ }
364
+ }
365
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "daemon", event: "daemon.owner_outage_alert_undelivered", message: routes.length === 0 ? "no working route to tell the owner an owner channel changed" : "every route failed to tell the owner an owner channel changed", meta: { agent, sense, kind, failures } });
366
+ return null;
367
+ }
368
+ }
369
+ exports.OwnerChannelOutageWatcher = OwnerChannelOutageWatcher;
370
+ /* v8 ignore start -- the live loader; tests inject one so nothing real is sent @preserve */
371
+ const loadOwnerAlertRoutes = () => Promise.resolve().then(() => __importStar(require("./owner-alert-routes")));
372
+ /* v8 ignore stop */
373
+ /**
374
+ * The daemon's routes for an agent, loaded only when an alert is about to send. The mail route pulls in the mailroom
375
+ * (core, reader and outbound) and the Telegram route the Telegram sense; loading them eagerly would cost every daemon
376
+ * start for an alert that is rarely sent, so the per-pass check sees only these thin senders.
377
+ */
378
+ function lazyOwnerAlertRoutes(agent, agentRoot, load = loadOwnerAlertRoutes) {
379
+ const sender = (route) => async (message) => {
380
+ const send = (await load()).ownerAlertRoutes(agent, agentRoot)[route];
381
+ if (!send)
382
+ throw new Error(`no ${route} route for ${agent}`);
383
+ await send(message);
384
+ };
385
+ return { telegram: sender("telegram"), mail: sender("mail") };
386
+ }
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.mailToolDefinitions = exports.__mailStatusTestOnly = void 0;
7
+ exports.outboundProviderClientForTransport = outboundProviderClientForTransport;
7
8
  exports.renderCachedMessageSummary = renderCachedMessageSummary;
8
9
  exports.mergeCachedMailSearchDocuments = mergeCachedMailSearchDocuments;
9
10
  exports.searchSuccessfulImportArchives = searchSuccessfulImportArchives;
@@ -152,6 +153,7 @@ function vaultItemSecretField(rawSecret, item, field) {
152
153
  throw new Error(`vault item ${item} is missing required secret field ${field}`);
153
154
  return value;
154
155
  }
156
+ /** The outbound provider client for an agent's mail transport, reading its secret from that agent's vault. */
155
157
  async function outboundProviderClientForTransport(agentName, transport) {
156
158
  return (0, outbound_1.resolveOutboundProviderClient)(transport, {
157
159
  readSecretField: async (item, field) => {
@@ -2348,10 +2348,17 @@ function createTelegramSenseApp(options) {
2348
2348
  const noticeId = requiredText(input.noticeId, "owner notice id");
2349
2349
  if (Buffer.byteLength(noticeId) > 512)
2350
2350
  throw new Error("Telegram owner notice id is invalid");
2351
- if (noticeId.startsWith("delegated:"))
2352
- return sendDelegatedAuditNotice({ ...input, noticeId });
2351
+ if (noticeId.startsWith("delegated:")) {
2352
+ await sendDelegatedAuditNotice({ ...input, noticeId });
2353
+ return "sent";
2354
+ }
2355
+ let outcome = "not_sent";
2353
2356
  await runWithAcceptanceAuditOwner(async () => {
2354
2357
  const text = requiredText(input.text, "owner notice");
2358
+ if (input.nowOrNever && (options.ownerRoute || ownerChatIsHandedOff() || (options.proactivePacing && !(0, telegram_handoff_1.isCriticalNoticeKey)(`owner-notice:${noticeId}`) && (0, telegram_handoff_1.proactiveHoldReason)(proactiveLedgerPath, new Date(), options.proactivePacing)))) {
2359
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_owner_notice_dropped", message: "an owner notice that had to go now couldn't, so it was dropped rather than held", meta: { agentName: options.agentName } });
2360
+ return;
2361
+ }
2355
2362
  const telegramText = await routeSelfStarted(text, `owner-notice:${noticeId}`, undefined, input.signal);
2356
2363
  if (telegramText === null)
2357
2364
  return;
@@ -2359,10 +2366,12 @@ function createTelegramSenseApp(options) {
2359
2366
  return;
2360
2367
  await releaseHeldNotices(input.signal);
2361
2368
  const effect = await deliverButlerEffect(telegramText, `owner-notice:${noticeId}`, input.signal);
2369
+ outcome = "sent";
2362
2370
  countProactiveSend();
2363
2371
  const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
2364
2372
  await recordAcceptedEffects(sessionPath, [effect]);
2365
2373
  });
2374
+ return outcome;
2366
2375
  },
2367
2376
  sendDelegatedAuditNotice,
2368
2377
  stop() {
@@ -2713,10 +2722,11 @@ async function sendTelegramDelegatedAuditNotice(agentName, input) {
2713
2722
  await app.stop();
2714
2723
  }
2715
2724
  }
2725
+ /** Sends an owner notice; "not_sent" when Telegram held it or handed it to the owner route instead of sending it now. */
2716
2726
  async function sendTelegramOwnerNotice(agentName, input) {
2717
2727
  const app = await startTelegramSenseApp(agentName);
2718
2728
  try {
2719
- await app.sendOwnerNotice(input);
2729
+ return await app.sendOwnerNotice(input);
2720
2730
  }
2721
2731
  finally {
2722
2732
  await app.stop();
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1588",
3
+ "version": "0.1.0-alpha.1589",
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.1588",
9
+ "version": "0.1.0-alpha.1589",
10
10
  "bundleDependencies": [
11
11
  "@ouro.bot/friends"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1588",
3
+ "version": "0.1.0-alpha.1589",
4
4
  "description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
5
5
  "homepage": "https://ouroboros.bot/",
6
6
  "engines": {