@ouro.bot/cli 0.1.0-alpha.1692 → 0.1.0-alpha.1696

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,20 @@
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.1696",
6
+ "changes": [
7
+ "Update the Ouro UI files to Ouro UI v1.3.627.",
8
+ "The Butler's scheduled house check (`sanctuary-health`) and the readiness check for its house and Usenet events now come from the Butler's product registration, so the daemon no longer calls Butler code for them. On the Butler's image they behave as before. Only Supercronic can fire the house check on its cron schedule, and a cron poke without that proof is still refused, now with the message `cron habit 'sanctuary-health' requires authenticated Supercronic provenance`. The proof itself, scheduler attestation, is now part of the harness, and its one-use claims are kept under `state/scheduler/fire-claims` instead of `state/scheduler/sanctuary-fire-claims`. Agents no product runs are unaffected: their habits and events go the usual route and wait for no Butler credentials.",
9
+ "Update the Ouro UI files to Ouro UI v1.3.628."
10
+ ]
11
+ },
12
+ {
13
+ "version": "0.1.0-alpha.1693",
14
+ "changes": [
15
+ "Update the Ouro UI files to Ouro UI v1.3.626."
16
+ ]
17
+ },
4
18
  {
5
19
  "version": "0.1.0-alpha.1692",
6
20
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1692",
2
+ "runtimeVersion": "0.1.0-alpha.1696",
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.1692</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1696</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -193,7 +193,7 @@ Promise.resolve().then(() => __importStar(require("./runtime-credentials"))).the
193
193
  attachProcessListeners: false,
194
194
  bufferedMessages: [],
195
195
  });
196
- const { ensureSanctuarySourceRuntimeReady } = await Promise.resolve().then(() => __importStar(require("../senses/sanctuary-runtime")));
196
+ const { productEventSource } = await Promise.resolve().then(() => __importStar(require("./product/active")));
197
197
  const readinessPendingDispatchIds = new Set();
198
198
  const cancelledReadinessDispatchIds = new Set();
199
199
  const handleWorkerMessage = async (message) => {
@@ -211,7 +211,7 @@ Promise.resolve().then(() => __importStar(require("./runtime-credentials"))).the
211
211
  if (typeof envelope?.externalEvent?.source === "string") {
212
212
  if (dispatchId)
213
213
  readinessPendingDispatchIds.add(dispatchId);
214
- await ensureSanctuarySourceRuntimeReady(agentName, envelope.externalEvent.source);
214
+ await productEventSource(agentName, envelope.externalEvent.source)?.ready(agentName);
215
215
  if (dispatchId)
216
216
  readinessPendingDispatchIds.delete(dispatchId);
217
217
  if (dispatchId && cancelledReadinessDispatchIds.delete(dispatchId))
@@ -108,7 +108,7 @@ const background_operations_1 = require("../background-operations");
108
108
  const mail_import_discovery_1 = require("../mail-import-discovery");
109
109
  const session_activity_1 = require("../session-activity");
110
110
  const target_resolution_1 = require("../target-resolution");
111
- const sanctuary_scheduler_origin_1 = require("./sanctuary-scheduler-origin");
111
+ const scheduler_attestation_1 = require("./scheduler-attestation");
112
112
  const cli_parse_1 = require("./cli-parse");
113
113
  const cli_parse_2 = require("./cli-parse");
114
114
  const cli_help_1 = require("./cli-help");
@@ -1626,7 +1626,7 @@ function toDaemonCommand(command) {
1626
1626
  };
1627
1627
  }
1628
1628
  if (command.kind === "habit.poke")
1629
- return (0, sanctuary_scheduler_origin_1.createSanctuarySchedulerFireCommand)(command) ?? command;
1629
+ return (0, scheduler_attestation_1.createSchedulerFireCommand)(command) ?? command;
1630
1630
  return command;
1631
1631
  }
1632
1632
  function habitProbeJsonResponse(response) {
@@ -85,9 +85,7 @@ const machine_identity_1 = require("../machine-identity");
85
85
  const vault_outage_1 = require("./vault-outage");
86
86
  const container_credential_bootstrap_1 = require("./container-credential-bootstrap");
87
87
  const daemon_bootstrap_startup_1 = require("./daemon-bootstrap-startup");
88
- const sanctuary_acceptance_marker_1 = require("./sanctuary-acceptance-marker");
89
- const sanctuary_scheduler_liveness_1 = require("./sanctuary-scheduler-liveness");
90
- const sanctuary_scheduler_origin_1 = require("./sanctuary-scheduler-origin");
88
+ const scheduler_attestation_1 = require("./scheduler-attestation");
91
89
  const telegram_identity_key_1 = require("../../senses/telegram-identity-key");
92
90
  const sync_health_1 = require("../sync-health");
93
91
  const sync_1 = require("../sync");
@@ -378,7 +376,7 @@ const containerRuntimePolicy = (0, container_runtime_1.readContainerRuntimePolic
378
376
  const supercronicSupervisor = containerRuntimePolicy?.scheduler === "supercronic"
379
377
  ? new supercronic_supervisor_1.SupercronicSupervisor({
380
378
  binaryPath: "/usr/local/bin/supercronic",
381
- crontabPath: path.join((0, identity_1.getAgentBundlesRoot)(), "..", ".ouro-cli", "scheduler", `${butlerName}.crontab`),
379
+ crontabPath: (0, scheduler_attestation_1.schedulerCrontabPath)(butlerName),
382
380
  onFatal: (error) => {
383
381
  (0, runtime_1.emitNervesEvent)({ level: "error", component: "daemon", event: "daemon.supercronic_state", message: "Supercronic restart budget exhausted", meta: { error: error.message } });
384
382
  process.exit(1);
@@ -550,60 +548,32 @@ const daemon = new daemon_1.OuroDaemon({
550
548
  schedulerFireVerifier: (command) => {
551
549
  if (!supercronicSupervisor)
552
550
  throw new Error("Supercronic scheduler is unavailable");
553
- const marker = (0, sanctuary_acceptance_marker_1.readSanctuaryAcceptanceMarker)(butlerName);
554
- return (0, sanctuary_scheduler_origin_1.verifySanctuarySchedulerFireCommand)(command, {
551
+ return (0, scheduler_attestation_1.verifySchedulerFireCommand)(command, {
555
552
  childPid: supercronicSupervisor.authenticatedSnapshot(`habit:${butlerName}`).childPid,
553
+ crontabPath: (0, scheduler_attestation_1.schedulerCrontabPath)(command.agent),
556
554
  identityKey: (0, telegram_identity_key_1.readOrCreateTelegramIdentityKey)(path.join((0, identity_1.getAgentBundlesRoot)(), `${butlerName}.ouro`)),
557
- scenarioHandleDigest: marker?.label === "unit-16f-cron-fingerprint" ? marker.scenarioHandleDigest : null, now: () => new Date(),
555
+ scenarioHandleDigest: (0, active_1.productHabit)(command.agent, command.habitName)?.attestationScenario?.(butlerName) ?? null, now: () => new Date(),
558
556
  readFile: (target) => fs.readFileSync(target, "utf8"), readLink: (target) => fs.readlinkSync(target),
559
557
  });
560
558
  },
561
- schedulerFireConsumer: (origin) => (0, sanctuary_scheduler_liveness_1.consumeSanctuarySchedulerFire)(path.join((0, identity_1.getAgentBundlesRoot)(), `${butlerName}.ouro`), origin),
562
- nativeHabitRunner: async ({ agent, habitName, trigger, occurrenceId, runnerId, schedulerOrigin }) => {
563
- if (!(0, active_1.productFor)(agent) || habitName !== "sanctuary-health")
559
+ schedulerFireConsumer: (origin, fire) => (0, scheduler_attestation_1.consumeSchedulerFire)(path.join((0, identity_1.getAgentBundlesRoot)(), `${butlerName}.ouro`), fire.habitName, origin),
560
+ // A habit the agent's product runs itself; every other habit wakes the agent as usual.
561
+ nativeHabitRunner: async (input) => {
562
+ const habit = (0, active_1.productHabit)(input.agent, input.habitName);
563
+ if (!habit)
564
564
  return null;
565
- const marker = (0, sanctuary_acceptance_marker_1.readSanctuaryAcceptanceMarker)(agent);
566
- const schedulerScenario = marker?.label === "unit-16f-cron-fingerprint" ? marker : null;
567
- const agentRoot = path.join((0, identity_1.getAgentBundlesRoot)(), `${agent}.ouro`);
568
- const before = schedulerScenario ? (0, sanctuary_scheduler_liveness_1.readSanctuaryHealthCursor)(agentRoot) : null;
569
- let providerInvocationCount = 0;
570
- let privateTurnCount = 0;
571
- // Loaded here, not at startup: it imports Sanctuary's tool registry.
572
- const { runSanctuaryHealthHabit } = await Promise.resolve().then(() => __importStar(require("../../senses/sanctuary-health-runner")));
573
- const result = await runSanctuaryHealthHabit(agent, {
574
- submitEvidence: async (input) => {
575
- const response = await daemon.handleCommand({ kind: "external.event.submit", ...input });
565
+ return habit.run({
566
+ ...input,
567
+ schedulerSnapshot: () => supercronicSupervisor ? supercronicSupervisor.authenticatedSnapshot(`habit:${input.agent}`) : null,
568
+ submitExternalEvent: async (event) => {
569
+ const response = await daemon.handleCommand({ kind: "external.event.submit", ...event });
576
570
  if (!response.ok)
577
- throw new Error(response.error ?? "Sanctuary health evidence submission failed");
571
+ throw new Error(response.error ?? `${input.habitName} could not submit its external event`);
578
572
  return response.data.event;
579
573
  },
580
- ...(schedulerScenario ? {
581
- acceptanceMetrics: {
582
- onPrivateTurnStart: () => { privateTurnCount += 1; },
583
- onProviderInvocation: () => { providerInvocationCount += 1; },
584
- },
585
- } : {}),
586
574
  });
587
- if (schedulerScenario) {
588
- if (!supercronicSupervisor || !before || !occurrenceId || !schedulerOrigin)
589
- throw new Error("Sanctuary scheduler liveness supervisor provenance is unavailable");
590
- (0, sanctuary_scheduler_liveness_1.recordSanctuarySchedulerLivenessReceipt)({
591
- agentRoot,
592
- trigger,
593
- occurrenceId,
594
- runnerId,
595
- scenario: schedulerScenario,
596
- supervisor: supercronicSupervisor.authenticatedSnapshot(`habit:${agent}`),
597
- before,
598
- providerInvocationCount,
599
- privateTurnCount,
600
- schedulerOrigin,
601
- identityKey: (0, telegram_identity_key_1.readOrCreateTelegramIdentityKey)(agentRoot),
602
- });
603
- }
604
- return result;
605
575
  },
606
- nativeHabitMatch: (agent, habitName) => (0, active_1.productFor)(agent) !== null && habitName === "sanctuary-health",
576
+ nativeHabitMatch: (agent, habitName) => (0, active_1.productHabit)(agent, habitName) !== null,
607
577
  mode,
608
578
  onStopCommandComplete: async () => {
609
579
  await stopEntryRuntime();
@@ -920,7 +890,7 @@ void (0, daemon_bootstrap_startup_1.startDaemonAfterContainerCredentialBootstrap
920
890
  habitsDir,
921
891
  osCronManager,
922
892
  onHabitFire: (habitName, trigger, context) => {
923
- if ((0, habit_policy_1.isRsvpHabitName)(habitName) || ((0, active_1.productFor)(agent) !== null && habitName === "sanctuary-health")) {
893
+ if ((0, habit_policy_1.isRsvpHabitName)(habitName) || (0, active_1.productHabit)(agent, habitName) !== null) {
924
894
  (0, socket_client_1.sendDaemonCommand)(socketPath, {
925
895
  kind: "habit.poke",
926
896
  agent,
@@ -53,7 +53,6 @@ const path = __importStar(require("path"));
53
53
  const node_crypto_1 = require("node:crypto");
54
54
  const node_string_decoder_1 = require("node:string_decoder");
55
55
  const identity_1 = require("../identity");
56
- const butler_agent_1 = require("../butler-agent");
57
56
  const state_retention_1 = require("./state-retention");
58
57
  const agent_discovery_1 = require("./agent-discovery");
59
58
  const runtime_1 = require("../../nerves/runtime");
@@ -83,6 +82,8 @@ const router_1 = require("../external-events/router");
83
82
  const habit_policy_1 = require("../../rsvp/habit-policy");
84
83
  const container_runtime_1 = require("./container-runtime");
85
84
  const habit_session_1 = require("../habits/habit-session");
85
+ const scheduler_attestation_1 = require("./scheduler-attestation");
86
+ const active_1 = require("../product/active");
86
87
  const turn_execution_lease_1 = require("../turn-execution-lease");
87
88
  const frontend_session_service_1 = require("../frontend-session-service");
88
89
  const frontend_socket_1 = require("../frontend-socket");
@@ -734,8 +735,7 @@ class OuroDaemon {
734
735
  this.socketAnswering = options.socketAnswering ?? socket_client_1.checkDaemonSocketAlive;
735
736
  this.selfUpdateLauncher = options.selfUpdateLauncher !== undefined ? options.selfUpdateLauncher : defaultSelfUpdateLauncher();
736
737
  this.externalEventSourceReadiness = options.externalEventSourceReadiness ?? (async (agent, source) => {
737
- const { ensureSanctuarySourceRuntimeReady } = await Promise.resolve().then(() => __importStar(require("../../senses/sanctuary-runtime")));
738
- await ensureSanctuarySourceRuntimeReady(agent, source);
738
+ await (0, active_1.productEventSource)(agent, source)?.ready(agent);
739
739
  });
740
740
  }
741
741
  buildStatusPayload() {
@@ -1855,7 +1855,7 @@ class OuroDaemon {
1855
1855
  && (0, router_1.externalEventRecoveryFailure)(candidate) !== null
1856
1856
  && candidate.recoveryGrant?.generation !== candidate.generation;
1857
1857
  const dispatchable = candidate.executionState === "received" || candidate.executionState === "queued" || retryDue || leaseExpired || recoverableDeadLetter;
1858
- if (dispatchable && (candidate.source === "sanctuary-health" || candidate.source === "sanctuary-usenet"))
1858
+ if (dispatchable && (0, active_1.productEventSource)(candidate.agent, candidate.source))
1859
1859
  readinessKeys.add(`${candidate.agent}\0${candidate.source}`);
1860
1860
  }
1861
1861
  const blockedReadinessKeys = new Set();
@@ -2426,7 +2426,7 @@ class OuroDaemon {
2426
2426
  let origin;
2427
2427
  try {
2428
2428
  origin = this.schedulerFireVerifier(command);
2429
- this.schedulerFireConsumer(origin);
2429
+ this.schedulerFireConsumer(origin, { agent: command.agent, habitName: command.habitName });
2430
2430
  }
2431
2431
  catch (error) {
2432
2432
  return { ok: false, error: error instanceof Error ? error.message : String(error) };
@@ -2452,8 +2452,8 @@ class OuroDaemon {
2452
2452
  return { ok: false, error: `invalid habit trigger: ${String(trigger)}` };
2453
2453
  }
2454
2454
  const schedulerOrigin = this.authenticatedSchedulerPokes.get(command);
2455
- if ((0, butler_agent_1.isButlerAgent)(command.agent) && command.habitName === "sanctuary-health" && trigger === "cron" && !schedulerOrigin) {
2456
- return { ok: false, error: "Sanctuary cron habit requires authenticated Supercronic provenance" };
2455
+ if (trigger === "cron" && !schedulerOrigin && (0, scheduler_attestation_1.attestedHabit)(command.agent, command.habitName)) {
2456
+ return { ok: false, error: `cron habit '${command.habitName}' requires authenticated Supercronic provenance` };
2457
2457
  }
2458
2458
  if (!(0, habit_policy_1.isRsvpHabitName)(command.habitName) && !this.hasManagedPrivateRuntime(command.agent)) {
2459
2459
  return {
@@ -34,8 +34,6 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.readSanctuaryHealthCursor = readSanctuaryHealthCursor;
37
- exports.durableExclusiveJson = durableExclusiveJson;
38
- exports.consumeSanctuarySchedulerFire = consumeSanctuarySchedulerFire;
39
37
  exports.publishSanctuarySchedulerReceipt = publishSanctuarySchedulerReceipt;
40
38
  exports.sanctuarySchedulerLivenessReceiptMac = sanctuarySchedulerLivenessReceiptMac;
41
39
  exports.verifySanctuarySchedulerLivenessReceiptMac = verifySanctuarySchedulerLivenessReceiptMac;
@@ -44,6 +42,7 @@ const node_crypto_1 = require("node:crypto");
44
42
  const fs = __importStar(require("node:fs"));
45
43
  const path = __importStar(require("node:path"));
46
44
  const runtime_1 = require("../../nerves/runtime");
45
+ const scheduler_attestation_1 = require("./scheduler-attestation");
47
46
  const butler_agent_1 = require("../butler-agent");
48
47
  const SHA256 = /^[0-9a-f]{64}$/u;
49
48
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
@@ -53,92 +52,9 @@ function readSanctuaryHealthCursor(agentRoot) {
53
52
  throw new Error("Sanctuary health cursor state is invalid");
54
53
  return { sweepCount: state.sweepReceipts.length, deliveryCount: state.deliveredReceipts.length };
55
54
  }
56
- function fsyncDirectory(directory, deps) {
57
- const descriptor = deps.openSync(directory, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
58
- try {
59
- deps.fsyncSync(descriptor);
60
- }
61
- finally {
62
- deps.closeSync(descriptor);
63
- }
64
- }
65
- function ensureDurableDirectory(directory, deps) {
66
- try {
67
- deps.mkdirSync(directory, { mode: 0o700 });
68
- }
69
- catch (error) {
70
- const code = error.code;
71
- if (code === "EEXIST") {
72
- fsyncDirectory(directory, deps);
73
- fsyncDirectory(path.dirname(directory), deps);
74
- return;
75
- }
76
- if (code !== "ENOENT")
77
- throw error;
78
- const parent = path.dirname(directory);
79
- if (parent === directory)
80
- throw error;
81
- ensureDurableDirectory(parent, deps);
82
- try {
83
- deps.mkdirSync(directory, { mode: 0o700 });
84
- }
85
- catch (retryError) {
86
- if (retryError.code !== "EEXIST")
87
- throw retryError;
88
- }
89
- }
90
- fsyncDirectory(directory, deps);
91
- fsyncDirectory(path.dirname(directory), deps);
92
- }
93
- function durableExclusiveJson(filePath, value, deps = fs) {
94
- const directory = path.dirname(filePath);
95
- ensureDurableDirectory(directory, deps);
96
- const temporary = `${filePath}.tmp-${process.pid}-${(0, node_crypto_1.randomUUID)()}`;
97
- let handle = null;
98
- try {
99
- handle = deps.openSync(temporary, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | fs.constants.O_NOFOLLOW, 0o600);
100
- deps.writeFileSync(handle, `${JSON.stringify(value)}\n`, "utf8");
101
- deps.fsyncSync(handle);
102
- deps.closeSync(handle);
103
- handle = null;
104
- deps.linkSync(temporary, filePath);
105
- fsyncDirectory(directory, deps);
106
- }
107
- finally {
108
- if (handle !== null)
109
- deps.closeSync(handle);
110
- try {
111
- deps.unlinkSync(temporary);
112
- }
113
- catch (error) {
114
- if (error.code !== "ENOENT")
115
- throw error;
116
- }
117
- finally {
118
- fsyncDirectory(directory, deps);
119
- }
120
- }
121
- }
122
- function consumeSanctuarySchedulerFire(agentRoot, origin) {
123
- if (!UUID.test(origin.schedulerRunId) || origin.occurrenceId !== `cron:${origin.slot}`)
124
- throw new Error("Sanctuary scheduler fire claim is invalid");
125
- const claimId = (0, node_crypto_1.createHash)("sha256").update(`sanctuary\0sanctuary-health\0${origin.slot}\0${origin.occurrenceId}`).digest("hex");
126
- const claimPath = path.join(agentRoot, "state", "scheduler", "sanctuary-fire-claims", `${claimId}.json`);
127
- try {
128
- durableExclusiveJson(claimPath, { schemaVersion: "sanctuary-scheduler-fire-claim-v1", ...origin });
129
- }
130
- catch (error) {
131
- if (error.code === "EEXIST") {
132
- (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "daemon.sanctuary_scheduler_fire_rejected", message: "Rejected replayed Sanctuary scheduler fire", meta: { occurrenceId: origin.occurrenceId, schedulerRunId: origin.schedulerRunId } });
133
- throw new Error("Sanctuary scheduler fire replay rejected");
134
- }
135
- throw error;
136
- }
137
- (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.sanctuary_scheduler_fire_consumed", message: "Consumed Sanctuary scheduler fire before execution", meta: { occurrenceId: origin.occurrenceId, schedulerRunId: origin.schedulerRunId } });
138
- }
139
55
  function publishSanctuarySchedulerReceipt(filePath, value, deps = fs) {
140
56
  try {
141
- durableExclusiveJson(filePath, value, deps);
57
+ (0, scheduler_attestation_1.durableExclusiveJson)(filePath, value, deps);
142
58
  }
143
59
  catch (error) {
144
60
  if (error.code === "EEXIST")
@@ -0,0 +1,249 @@
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.schedulerCrontabPath = schedulerCrontabPath;
37
+ exports.attestedHabit = attestedHabit;
38
+ exports.defaultSchedulerAttestationDeps = defaultSchedulerAttestationDeps;
39
+ exports.createSchedulerFireCommand = createSchedulerFireCommand;
40
+ exports.verifySchedulerFireCommand = verifySchedulerFireCommand;
41
+ exports.durableExclusiveJson = durableExclusiveJson;
42
+ exports.consumeSchedulerFire = consumeSchedulerFire;
43
+ const node_crypto_1 = require("node:crypto");
44
+ const fs = __importStar(require("node:fs"));
45
+ const path = __importStar(require("node:path"));
46
+ const identity_1 = require("../identity");
47
+ const active_1 = require("../product/active");
48
+ const runtime_1 = require("../../nerves/runtime");
49
+ const telegram_identity_key_1 = require("../../senses/telegram-identity-key");
50
+ /**
51
+ * Scheduler attestation: proof that a cron `ouro poke` came from the container's own scheduler (Supercronic), not from a
52
+ * person or process that typed the same command. A product marks a habit `requiresSchedulerAttestation`; the cron poke's
53
+ * CLI process then signs its process ancestry, the daemon checks it against the Supercronic child it supervises, consumes the
54
+ * fire once, and refuses an unattested cron poke of that habit.
55
+ */
56
+ const SUPERCRONIC = "/usr/local/bin/supercronic";
57
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
58
+ const SHA256 = /^[0-9a-f]{64}$/u;
59
+ const SLOT_MS = 15 * 60 * 1_000;
60
+ /** The crontab the daemon's Supercronic supervisor writes for this agent's habits. */
61
+ function schedulerCrontabPath(agent) {
62
+ return path.join((0, identity_1.getAgentBundlesRoot)(), "..", ".ouro-cli", "scheduler", `${agent}.crontab`);
63
+ }
64
+ /** The product habit a cron fire of `habitName` must prove came from the scheduler, or null when none needs to. */
65
+ function attestedHabit(agent, habitName) {
66
+ const habit = (0, active_1.productHabit)(agent, habitName);
67
+ return habit?.requiresSchedulerAttestation ? habit : null;
68
+ }
69
+ function processIdentity(stat) {
70
+ const close = stat.lastIndexOf(")");
71
+ if (close < 1)
72
+ throw new Error("scheduler process identity is invalid");
73
+ const fields = stat.slice(close + 2).trim().split(/\s+/u);
74
+ const parentPid = Number(fields[1]);
75
+ const startTime = fields[19];
76
+ if (!Number.isSafeInteger(parentPid) || parentPid < 0 || !startTime || !/^[0-9]+$/u.test(startTime))
77
+ throw new Error("scheduler process identity is invalid");
78
+ return { parentPid, startTime };
79
+ }
80
+ function slotFor(now) {
81
+ return new Date(Math.floor(now.getTime() / SLOT_MS) * SLOT_MS).toISOString();
82
+ }
83
+ function unsigned(command) {
84
+ return Object.fromEntries(Object.entries(command).filter(([key]) => key !== "proofMac"));
85
+ }
86
+ function mac(key, command) {
87
+ return (0, node_crypto_1.createHmac)("sha256", key).update(JSON.stringify(unsigned(command))).digest("hex");
88
+ }
89
+ function safeEqual(left, right) {
90
+ if (!SHA256.test(left) || !SHA256.test(right))
91
+ return false;
92
+ return (0, node_crypto_1.timingSafeEqual)(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
93
+ }
94
+ function isSupercronicProcess(crontabPath, pid, deps) {
95
+ const cmdline = `${SUPERCRONIC}\0-split-logs\0-inotify\0${crontabPath}\0`;
96
+ return deps.readLink(`/proc/${pid}/exe`) === SUPERCRONIC && deps.readFile(`/proc/${pid}/cmdline`) === cmdline;
97
+ }
98
+ function defaultSchedulerAttestationDeps(agent, habit, agentRoot = (0, identity_1.getAgentRoot)(agent)) {
99
+ return {
100
+ platform: process.platform, pid: process.pid, ppid: process.ppid, crontabPath: schedulerCrontabPath(agent), now: () => new Date(),
101
+ readFile: (target) => fs.readFileSync(target, "utf8"), readLink: (target) => fs.readlinkSync(target),
102
+ identityKey: () => (0, telegram_identity_key_1.readOrCreateTelegramIdentityKey)(agentRoot), scenario: () => habit.attestationScenario?.(agent) ?? null, randomId: () => (0, node_crypto_1.randomUUID)(),
103
+ };
104
+ }
105
+ /**
106
+ * Turns a cron poke of an attested habit into a signed scheduler fire when this process is a live Supercronic job. Anything
107
+ * else (another habit, another trigger, off Linux, or a parent that is not Supercronic) stays the plain poke, which the daemon
108
+ * then refuses for an attested habit.
109
+ */
110
+ function createSchedulerFireCommand(command, given) {
111
+ if (command.trigger !== "cron")
112
+ return null;
113
+ const habit = attestedHabit(command.agent, command.habitName);
114
+ if (!habit)
115
+ return null;
116
+ const deps = given ?? defaultSchedulerAttestationDeps(command.agent, habit);
117
+ if (deps.platform !== "linux")
118
+ return null;
119
+ try {
120
+ const invocation = processIdentity(deps.readFile(`/proc/${deps.pid}/stat`));
121
+ const parent = processIdentity(deps.readFile(`/proc/${deps.ppid}/stat`));
122
+ if (!isSupercronicProcess(deps.crontabPath, deps.ppid, deps) && !isSupercronicProcess(deps.crontabPath, parent.parentPid, deps))
123
+ return null;
124
+ const scenarioHandleDigest = deps.scenario();
125
+ if (invocation.parentPid !== deps.ppid)
126
+ return null;
127
+ const slot = slotFor(deps.now());
128
+ const value = {
129
+ kind: "habit.scheduler-fire", agent: command.agent, habitName: command.habitName, trigger: "cron",
130
+ slot, occurrenceId: `cron:${slot}`, schedulerRunId: deps.randomId(), invocationPid: deps.pid, parentPid: deps.ppid,
131
+ parentStartTime: parent.startTime, invocationStartTime: invocation.startTime,
132
+ scenarioHandleDigest,
133
+ };
134
+ return { ...value, proofMac: mac(deps.identityKey(), value) };
135
+ }
136
+ catch {
137
+ return null;
138
+ }
139
+ }
140
+ /** Checks a scheduler fire's signature, slot and process ancestry against the Supercronic child the daemon supervises. */
141
+ function verifySchedulerFireCommand(command, deps) {
142
+ if (!command || command.kind !== "habit.scheduler-fire" || typeof command.agent !== "string" || typeof command.habitName !== "string"
143
+ || !attestedHabit(command.agent, command.habitName) || command.trigger !== "cron"
144
+ || !UUID.test(command.schedulerRunId) || (command.scenarioHandleDigest !== null && !SHA256.test(command.scenarioHandleDigest)) || command.scenarioHandleDigest !== deps.scenarioHandleDigest
145
+ || command.slot !== slotFor(deps.now()) || command.occurrenceId !== `cron:${command.slot}`)
146
+ throw new Error("scheduler fire slot or binding is invalid");
147
+ if (!safeEqual(command.proofMac, mac(deps.identityKey, command)))
148
+ throw new Error("scheduler fire authentication failed");
149
+ const invocation = processIdentity(deps.readFile(`/proc/${command.invocationPid}/stat`));
150
+ const parent = processIdentity(deps.readFile(`/proc/${command.parentPid}/stat`));
151
+ if (invocation.parentPid !== command.parentPid || invocation.startTime !== command.invocationStartTime
152
+ || parent.startTime !== command.parentStartTime)
153
+ throw new Error("scheduler fire ancestry is invalid");
154
+ if (command.parentPid !== deps.childPid && parent.parentPid !== deps.childPid)
155
+ throw new Error("scheduler fire ancestry is invalid");
156
+ if (command.parentPid === deps.childPid ? !isSupercronicProcess(deps.crontabPath, command.parentPid, deps) : !isSupercronicProcess(deps.crontabPath, parent.parentPid, deps))
157
+ throw new Error("scheduler fire ancestry is invalid");
158
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.scheduler_fire_authenticated", message: "Scheduler fire authenticated", meta: { agent: command.agent, habitName: command.habitName, schedulerRunId: command.schedulerRunId, slot: command.slot } });
159
+ return {
160
+ slot: command.slot, schedulerRunId: command.schedulerRunId, invocationPid: command.invocationPid, parentPid: command.parentPid,
161
+ parentStartTime: command.parentStartTime, invocationStartTime: command.invocationStartTime, proofMac: command.proofMac,
162
+ scenarioHandleDigest: command.scenarioHandleDigest, occurrenceId: command.occurrenceId,
163
+ };
164
+ }
165
+ function fsyncDirectory(directory, deps) {
166
+ const descriptor = deps.openSync(directory, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
167
+ try {
168
+ deps.fsyncSync(descriptor);
169
+ }
170
+ finally {
171
+ deps.closeSync(descriptor);
172
+ }
173
+ }
174
+ function ensureDurableDirectory(directory, deps) {
175
+ try {
176
+ deps.mkdirSync(directory, { mode: 0o700 });
177
+ }
178
+ catch (error) {
179
+ const code = error.code;
180
+ if (code === "EEXIST") {
181
+ fsyncDirectory(directory, deps);
182
+ fsyncDirectory(path.dirname(directory), deps);
183
+ return;
184
+ }
185
+ if (code !== "ENOENT")
186
+ throw error;
187
+ const parent = path.dirname(directory);
188
+ if (parent === directory)
189
+ throw error;
190
+ ensureDurableDirectory(parent, deps);
191
+ try {
192
+ deps.mkdirSync(directory, { mode: 0o700 });
193
+ }
194
+ catch (retryError) {
195
+ if (retryError.code !== "EEXIST")
196
+ throw retryError;
197
+ }
198
+ }
199
+ fsyncDirectory(directory, deps);
200
+ fsyncDirectory(path.dirname(directory), deps);
201
+ }
202
+ /** Writes JSON to a new file durably and exactly once: a file already at the path makes it throw EEXIST. */
203
+ function durableExclusiveJson(filePath, value, deps = fs) {
204
+ const directory = path.dirname(filePath);
205
+ ensureDurableDirectory(directory, deps);
206
+ const temporary = `${filePath}.tmp-${process.pid}-${(0, node_crypto_1.randomUUID)()}`;
207
+ let handle = null;
208
+ try {
209
+ handle = deps.openSync(temporary, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | fs.constants.O_NOFOLLOW, 0o600);
210
+ deps.writeFileSync(handle, `${JSON.stringify(value)}\n`, "utf8");
211
+ deps.fsyncSync(handle);
212
+ deps.closeSync(handle);
213
+ handle = null;
214
+ deps.linkSync(temporary, filePath);
215
+ fsyncDirectory(directory, deps);
216
+ }
217
+ finally {
218
+ if (handle !== null)
219
+ deps.closeSync(handle);
220
+ try {
221
+ deps.unlinkSync(temporary);
222
+ }
223
+ catch (error) {
224
+ if (error.code !== "ENOENT")
225
+ throw error;
226
+ }
227
+ finally {
228
+ fsyncDirectory(directory, deps);
229
+ }
230
+ }
231
+ }
232
+ /** Claims an authenticated fire durably before the habit runs, so the same habit's occurrence never runs twice, even across restarts. */
233
+ function consumeSchedulerFire(agentRoot, habitName, origin) {
234
+ if (!UUID.test(origin.schedulerRunId) || origin.occurrenceId !== `cron:${origin.slot}`)
235
+ throw new Error("scheduler fire claim is invalid");
236
+ const claimId = (0, node_crypto_1.createHash)("sha256").update(`${habitName}\0${origin.slot}\0${origin.occurrenceId}`).digest("hex");
237
+ const claimPath = path.join(agentRoot, "state", "scheduler", "fire-claims", `${claimId}.json`);
238
+ try {
239
+ durableExclusiveJson(claimPath, { schemaVersion: "scheduler-fire-claim-v1", habitName, ...origin });
240
+ }
241
+ catch (error) {
242
+ if (error.code === "EEXIST") {
243
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "daemon.scheduler_fire_rejected", message: "Rejected replayed scheduler fire", meta: { habitName, occurrenceId: origin.occurrenceId, schedulerRunId: origin.schedulerRunId } });
244
+ throw new Error("scheduler fire replay rejected");
245
+ }
246
+ throw error;
247
+ }
248
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.scheduler_fire_consumed", message: "Consumed scheduler fire before execution", meta: { habitName, occurrenceId: origin.occurrenceId, schedulerRunId: origin.schedulerRunId } });
249
+ }
@@ -5,6 +5,8 @@ exports.loadProduct = loadProduct;
5
5
  exports.loadImageProduct = loadImageProduct;
6
6
  exports.productFor = productFor;
7
7
  exports.productAgentAmong = productAgentAmong;
8
+ exports.productHabit = productHabit;
9
+ exports.productEventSource = productEventSource;
8
10
  const runtime_1 = require("../../nerves/runtime");
9
11
  const container_runtime_1 = require("../daemon/container-runtime");
10
12
  /** The seam version this harness runs. A product built for another stops the start. */
@@ -88,3 +90,13 @@ function productAgentAmong(agents) {
88
90
  const owned = agents.filter((agent) => productFor(agent) !== null);
89
91
  return owned.length === 1 ? owned[0] : null;
90
92
  }
93
+ /** The habit the product runs for this agent under this name, or null. Habit names come from bundle files, so only the product's own entries count. */
94
+ function productHabit(agentName, habitName) {
95
+ const habits = productFor(agentName)?.habits;
96
+ return habits && Object.hasOwn(habits, habitName) ? habits[habitName] : null;
97
+ }
98
+ /** The event source the product declares for this agent under this name, or null. Source names come from event records, so only the product's own entries count. */
99
+ function productEventSource(agentName, source) {
100
+ const sources = productFor(agentName)?.eventSources;
101
+ return sources && Object.hasOwn(sources, source) ? sources[source] : null;
102
+ }
@@ -1,9 +1,102 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  exports.product = void 0;
37
+ const path = __importStar(require("node:path"));
4
38
  const butler_agent_1 = require("../heart/butler-agent");
39
+ const identity_1 = require("../heart/identity");
40
+ const sanctuary_acceptance_marker_1 = require("../heart/daemon/sanctuary-acceptance-marker");
41
+ const sanctuary_scheduler_liveness_1 = require("../heart/daemon/sanctuary-scheduler-liveness");
5
42
  const sanctuary_package_management_1 = require("../heart/daemon/sanctuary-package-management");
6
43
  const runtime_1 = require("../nerves/runtime");
44
+ const telegram_identity_key_1 = require("../senses/telegram-identity-key");
45
+ async function sanctuarySourceReady(agent, source) {
46
+ // Loaded here, not with the product: it imports Sanctuary's tool registry.
47
+ const { ensureSanctuarySourceRuntimeReady } = await Promise.resolve().then(() => __importStar(require("../senses/sanctuary-runtime")));
48
+ await ensureSanctuarySourceRuntimeReady(agent, source);
49
+ }
50
+ /** The acceptance run that proves a cron fire reaches the health sweep (Unit 16f), when one is running. */
51
+ function cronFingerprintScenario(agent) {
52
+ const marker = (0, sanctuary_acceptance_marker_1.readSanctuaryAcceptanceMarker)(agent);
53
+ return marker?.label === "unit-16f-cron-fingerprint" ? marker : null;
54
+ }
55
+ /**
56
+ * The house check on its schedule: sweep the house, and file what changed as `sanctuary-health` events, which wake the
57
+ * Butler. During the cron-fingerprint acceptance run it also records the liveness receipt that proves the fire was the
58
+ * scheduler's and did no paid work.
59
+ */
60
+ async function runSanctuaryHealth(input) {
61
+ const schedulerScenario = cronFingerprintScenario(input.agent);
62
+ const agentRoot = path.join((0, identity_1.getAgentBundlesRoot)(), `${input.agent}.ouro`);
63
+ const before = schedulerScenario ? (0, sanctuary_scheduler_liveness_1.readSanctuaryHealthCursor)(agentRoot) : null;
64
+ let providerInvocationCount = 0;
65
+ let privateTurnCount = 0;
66
+ // Loaded here, not with the product: it imports Sanctuary's tool registry.
67
+ const { runSanctuaryHealthHabit } = await Promise.resolve().then(() => __importStar(require("../senses/sanctuary-health-runner")));
68
+ const result = await runSanctuaryHealthHabit(input.agent, {
69
+ submitEvidence: input.submitExternalEvent,
70
+ ...(schedulerScenario ? {
71
+ acceptanceMetrics: {
72
+ onPrivateTurnStart: () => { privateTurnCount += 1; },
73
+ onProviderInvocation: () => { providerInvocationCount += 1; },
74
+ },
75
+ } : {}),
76
+ });
77
+ if (schedulerScenario) {
78
+ const unavailable = "Sanctuary scheduler liveness supervisor provenance is unavailable";
79
+ if (!before || !input.occurrenceId || !input.schedulerOrigin)
80
+ throw new Error(unavailable);
81
+ const supervisor = input.schedulerSnapshot();
82
+ if (!supervisor)
83
+ throw new Error(unavailable);
84
+ (0, sanctuary_scheduler_liveness_1.recordSanctuarySchedulerLivenessReceipt)({
85
+ agentRoot,
86
+ trigger: input.trigger,
87
+ occurrenceId: input.occurrenceId,
88
+ runnerId: input.runnerId,
89
+ scenario: schedulerScenario,
90
+ supervisor,
91
+ before,
92
+ providerInvocationCount,
93
+ privateTurnCount,
94
+ schedulerOrigin: input.schedulerOrigin,
95
+ identityKey: (0, telegram_identity_key_1.readOrCreateTelegramIdentityKey)(agentRoot),
96
+ });
97
+ }
98
+ return result;
99
+ }
7
100
  /**
8
101
  * The Butler, registered with the harness through the product seam. The Unraid image names this module in
9
102
  * /opt/ouro/container-runtime.json, so core loads it at runtime and never imports it. Each of the Butler's jobs gets its
@@ -21,5 +114,18 @@ exports.product = {
21
114
  prepareManagedBundle: () => { (0, sanctuary_package_management_1.prepareSanctuaryPackageManagedBundle)(decision); },
22
115
  };
23
116
  },
117
+ // J5: events from the house check and the Usenet watch wake the Butler only once its machine credentials are complete.
118
+ eventSources: {
119
+ "sanctuary-health": { ready: (agent) => sanctuarySourceReady(agent, "sanctuary-health") },
120
+ "sanctuary-usenet": { ready: (agent) => sanctuarySourceReady(agent, "sanctuary-usenet") },
121
+ },
122
+ // J5: the house check runs in the daemon, and only Supercronic may fire it on its cron schedule.
123
+ habits: {
124
+ "sanctuary-health": {
125
+ run: runSanctuaryHealth,
126
+ requiresSchedulerAttestation: true,
127
+ attestationScenario: (agent) => cronFingerprintScenario(agent)?.scenarioHandleDigest ?? null,
128
+ },
129
+ },
24
130
  };
25
131
  (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.butler_product_registered", message: "Butler product registered", meta: { agents: [...exports.product.agents] } });
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1692",
3
+ "version": "0.1.0-alpha.1696",
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.1692",
9
+ "version": "0.1.0-alpha.1696",
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.1692",
3
+ "version": "0.1.0-alpha.1696",
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": {
@@ -1,135 +0,0 @@
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.defaultSanctuarySchedulerOriginDeps = defaultSanctuarySchedulerOriginDeps;
37
- exports.createSanctuarySchedulerFireCommand = createSanctuarySchedulerFireCommand;
38
- exports.verifySanctuarySchedulerFireCommand = verifySanctuarySchedulerFireCommand;
39
- const node_crypto_1 = require("node:crypto");
40
- const fs = __importStar(require("node:fs"));
41
- const identity_1 = require("../identity");
42
- const runtime_1 = require("../../nerves/runtime");
43
- const telegram_identity_key_1 = require("../../senses/telegram-identity-key");
44
- const sanctuary_acceptance_marker_1 = require("./sanctuary-acceptance-marker");
45
- const butler_agent_1 = require("../butler-agent");
46
- const SUPERCRONIC = "/usr/local/bin/supercronic";
47
- const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
48
- const SHA256 = /^[0-9a-f]{64}$/u;
49
- const SLOT_MS = 15 * 60 * 1_000;
50
- function processIdentity(stat) {
51
- const close = stat.lastIndexOf(")");
52
- if (close < 1)
53
- throw new Error("scheduler process identity is invalid");
54
- const fields = stat.slice(close + 2).trim().split(/\s+/u);
55
- const parentPid = Number(fields[1]);
56
- const startTime = fields[19];
57
- if (!Number.isSafeInteger(parentPid) || parentPid < 0 || !startTime || !/^[0-9]+$/u.test(startTime))
58
- throw new Error("scheduler process identity is invalid");
59
- return { parentPid, startTime };
60
- }
61
- function slotFor(now) {
62
- return new Date(Math.floor(now.getTime() / SLOT_MS) * SLOT_MS).toISOString();
63
- }
64
- function unsigned(command) {
65
- return Object.fromEntries(Object.entries(command).filter(([key]) => key !== "proofMac"));
66
- }
67
- function mac(key, command) {
68
- return (0, node_crypto_1.createHmac)("sha256", key).update(JSON.stringify(unsigned(command))).digest("hex");
69
- }
70
- function safeEqual(left, right) {
71
- if (!SHA256.test(left) || !SHA256.test(right))
72
- return false;
73
- return (0, node_crypto_1.timingSafeEqual)(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
74
- }
75
- function isSupercronicProcess(agent, pid, deps) {
76
- const cmdline = `${SUPERCRONIC}\0-split-logs\0-inotify\0${(0, butler_agent_1.butlerContainerPaths)(agent).crontabPath}\0`;
77
- return deps.readLink(`/proc/${pid}/exe`) === SUPERCRONIC && deps.readFile(`/proc/${pid}/cmdline`) === cmdline;
78
- }
79
- function defaultSanctuarySchedulerOriginDeps(agent = "sanctuary", agentRoot = (0, identity_1.getAgentRoot)(agent), markerReader = () => (0, sanctuary_acceptance_marker_1.readSanctuaryAcceptanceMarker)(agent)) {
80
- return {
81
- platform: process.platform, pid: process.pid, ppid: process.ppid, now: () => new Date(),
82
- readFile: (target) => fs.readFileSync(target, "utf8"), readLink: (target) => fs.readlinkSync(target),
83
- identityKey: () => (0, telegram_identity_key_1.readOrCreateTelegramIdentityKey)(agentRoot), marker: markerReader, randomId: () => (0, node_crypto_1.randomUUID)(),
84
- };
85
- }
86
- function createSanctuarySchedulerFireCommand(command, given) {
87
- if (!(0, butler_agent_1.isButlerAgent)(command.agent) || command.habitName !== "sanctuary-health" || command.trigger !== "cron")
88
- return null;
89
- const deps = given ?? defaultSanctuarySchedulerOriginDeps(command.agent);
90
- if (deps.platform !== "linux")
91
- return null;
92
- try {
93
- const invocation = processIdentity(deps.readFile(`/proc/${deps.pid}/stat`));
94
- const parent = processIdentity(deps.readFile(`/proc/${deps.ppid}/stat`));
95
- if (!isSupercronicProcess(command.agent, deps.ppid, deps) && !isSupercronicProcess(command.agent, parent.parentPid, deps))
96
- return null;
97
- const marker = deps.marker();
98
- if (invocation.parentPid !== deps.ppid)
99
- return null;
100
- const slot = slotFor(deps.now());
101
- const value = {
102
- kind: "habit.scheduler-fire", agent: command.agent, habitName: "sanctuary-health", trigger: "cron",
103
- slot, occurrenceId: `cron:${slot}`, schedulerRunId: deps.randomId(), invocationPid: deps.pid, parentPid: deps.ppid,
104
- parentStartTime: parent.startTime, invocationStartTime: invocation.startTime,
105
- scenarioHandleDigest: marker?.label === "unit-16f-cron-fingerprint" ? marker.scenarioHandleDigest : null,
106
- };
107
- return { ...value, proofMac: mac(deps.identityKey(), value) };
108
- }
109
- catch {
110
- return null;
111
- }
112
- }
113
- function verifySanctuarySchedulerFireCommand(command, deps) {
114
- if (!command || command.kind !== "habit.scheduler-fire" || !(0, butler_agent_1.isButlerAgent)(command.agent) || command.habitName !== "sanctuary-health" || command.trigger !== "cron"
115
- || !UUID.test(command.schedulerRunId) || (command.scenarioHandleDigest !== null && !SHA256.test(command.scenarioHandleDigest)) || command.scenarioHandleDigest !== deps.scenarioHandleDigest
116
- || command.slot !== slotFor(deps.now()) || command.occurrenceId !== `cron:${command.slot}`)
117
- throw new Error("scheduler fire slot or binding is invalid");
118
- if (!safeEqual(command.proofMac, mac(deps.identityKey, command)))
119
- throw new Error("scheduler fire authentication failed");
120
- const invocation = processIdentity(deps.readFile(`/proc/${command.invocationPid}/stat`));
121
- const parent = processIdentity(deps.readFile(`/proc/${command.parentPid}/stat`));
122
- if (invocation.parentPid !== command.parentPid || invocation.startTime !== command.invocationStartTime
123
- || parent.startTime !== command.parentStartTime)
124
- throw new Error("scheduler fire ancestry is invalid");
125
- if (command.parentPid !== deps.childPid && parent.parentPid !== deps.childPid)
126
- throw new Error("scheduler fire ancestry is invalid");
127
- if (command.parentPid === deps.childPid ? !isSupercronicProcess(command.agent, command.parentPid, deps) : !isSupercronicProcess(command.agent, parent.parentPid, deps))
128
- throw new Error("scheduler fire ancestry is invalid");
129
- (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.sanctuary_scheduler_origin_authenticated", message: "Sanctuary scheduler origin authenticated", meta: { schedulerRunId: command.schedulerRunId, slot: command.slot } });
130
- return {
131
- slot: command.slot, schedulerRunId: command.schedulerRunId, invocationPid: command.invocationPid, parentPid: command.parentPid,
132
- parentStartTime: command.parentStartTime, invocationStartTime: command.invocationStartTime, proofMac: command.proofMac,
133
- scenarioHandleDigest: command.scenarioHandleDigest, occurrenceId: command.occurrenceId,
134
- };
135
- }