@ouro.bot/cli 0.1.0-alpha.1646 → 0.1.0-alpha.1648
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 +23 -2
- package/deploy/unraid/sanctuary-butler-upgrade.mjs +43 -1
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/heart/daemon/daemon-bootstrap-startup.js +8 -0
- package/dist/heart/daemon/daemon-entry.js +8 -1
- package/dist/heart/daemon/daemon.js +10 -4
- package/dist/heart/daemon/sanctuary-authority-root-lifecycle.js +35 -3
- package/dist/heart/external-events/router.js +173 -18
- package/dist/heart/letters/answered-note.js +4 -1
- package/dist/heart/letters/answering.js +4 -3
- package/dist/heart/letters/doors-tools.js +1 -0
- package/dist/heart/letters/doors.js +4 -1
- package/dist/heart/letters/return-to-session.js +99 -0
- package/dist/heart/letters/writer.js +77 -7
- package/dist/repertoire/tools-awaiting.js +8 -5
- package/dist/repertoire/tools-continuity.js +1 -1
- package/dist/senses/sanctuary-health-acceptance-probe.js +16 -5
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/changelog.json
CHANGED
|
@@ -1,17 +1,38 @@
|
|
|
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.1648",
|
|
6
|
+
"changes": [
|
|
7
|
+
"The Butler's host upgrade tells the bundle migration which Butler name the new image runs (`--butler-name`), so the bundle's own files (agent.json, the replay-client provisioning record, recent attachments, skills and HOUSE.md) name the container path that image mounts.",
|
|
8
|
+
"An await filed from an external event still resolves after the Butler's events folder moves to its other name, in either direction.",
|
|
9
|
+
"When the Butler starts and finds events saved under its other name, it merges them into its own folder even when both folders exist. It combines the privileged spool's replay manifests first, so no accepted envelope is accepted twice. A record both folders have keeps the running Butler's copy, and the other copy moves to `external-events/.adoption-conflicts/<other name>/<time>/`, with a warning; nothing is deleted and the start goes on. Only a move that fails stops the daemon from starting, with guidance naming the container and Unraid host paths. An other-name entry that is a symlink is left alone, with a warning.",
|
|
10
|
+
"An upgrade that would change the Butler's name is refused, before anything is paused or changed, unless the running release can take a rollback across the rename. Ship a release from after this change with the name unchanged first, then the release that renames it.",
|
|
11
|
+
"A held upgrade (`--hold-commit`) now says that a rollback puts the migrated bundle files back as they were before the migrate, so edits made to them during the hold are lost.",
|
|
12
|
+
"The health acceptance probe runs as the Butler whose bundle is on disk, and the privileged spool scan files envelopes under the Butler the daemon start set, so neither recreates the other name's events folder after the rename.",
|
|
13
|
+
"A letter filed from an agent's turn now remembers that turn's session. Once the person's answer is recorded, the daemon queues \"Ari answered L7: 2 Ouro — after lunch\" in that session, so the conversation that asked reads the answer on its next turn. A letter filed from the private runtime, the CLI or an MCP client has no session to return to. The agent's private runtime is told of every answer as before, and anyone waiting with `mailbox_wait` is released as before.",
|
|
14
|
+
"Each try to return an answer writes a `returned` event. A try that fails is tried again after a minute, then after a doubling wait of at most an hour, until it succeeds.",
|
|
15
|
+
"The session must be one the agent has really had turns in. A voice session gets no returned note, because a voice call drops notes older than a few minutes. The note comes from the mailbox, so Telegram's rule that drops an agent's own stale outreach doesn't remove it.",
|
|
16
|
+
"The agent's private runtime note about an answer now names the session that asked, so the agent can raise the answer there sooner than that session's next turn.",
|
|
17
|
+
"When another caller refiles a letter, the reply says the answer returns to the session that first filed it."
|
|
18
|
+
]
|
|
19
|
+
},
|
|
4
20
|
{
|
|
5
21
|
"version": "0.1.0-alpha.1646",
|
|
6
22
|
"changes": [
|
|
7
|
-
"A person can now answer a letter by texting its code and an option number, such as `L7 2`, in the iMessage chat the letter went to. When a one-to-one message in answer form arrives, the BlueBubbles sense hands the daemon only its GUID, and the daemon decides from the server's own copy. A recorded answer is not a chat turn. A message that already answered is handled the same when it is replayed. Anything else stays an ordinary chat turn, and so does a message the daemon doesn't answer for within 30 seconds: the daemon records nothing after 27 seconds, so a message is never both.",
|
|
8
|
-
"Once an answer is recorded, the person gets a one-line receipt in the same chat, naming the letter as its heading does, such as `Recorded L7 · Slugger asks: Which name? → 2 Ouro`, so a misread answer shows at once. The agent is told in its private runtime and woken; the private-runtime policy allows that wake only when it names the letter and comes from the daemon's answer command. A receipt or wake that fails is logged and never undoes the answer.",
|
|
9
23
|
"A letter now closes as expired once its `expiresAt` has passed with no answer. The daemon checks every minute and waits ten minutes past the expiry before closing a letter, so an answer the person sent in time still counts when it is read late. It then releases anyone waiting on the letter and wakes the agent that owns it with a note in its private runtime: \"letter L7 expired at … with no answer from my person\". An expired letter can't be answered or delivered. A new private-runtime policy rule allows that wake only when it names the letter and comes from the expiry pass.",
|
|
10
24
|
"A `now` letter whose sender sets no `expiresAt` now expires 24 hours after it is filed. Other letters still never expire unless their sender says so. Refiling a letter with the same `dedupeKey` doesn't extend its expiry, and once a letter is past its expiry the same `dedupeKey` files a new letter.",
|
|
11
25
|
"`mailbox_send` refuses an `expiresAt` that has already passed.",
|
|
12
26
|
"A daemon with no letters loads none of the mailbox's code for the expiry pass."
|
|
13
27
|
]
|
|
14
28
|
},
|
|
29
|
+
{
|
|
30
|
+
"version": "0.1.0-alpha.1645",
|
|
31
|
+
"changes": [
|
|
32
|
+
"A person can now answer a letter by texting its code and an option number, such as `L7 2`, in the iMessage chat the letter went to. When a one-to-one message in answer form arrives, the BlueBubbles sense hands the daemon only its GUID, and the daemon decides from the server's own copy. A recorded answer is not a chat turn. A message that already answered is handled the same when it is replayed. Anything else stays an ordinary chat turn, and so does a message the daemon doesn't answer for within 30 seconds: the daemon records nothing after 27 seconds, so a message is never both.",
|
|
33
|
+
"Once an answer is recorded, the person gets a one-line receipt in the same chat, naming the letter as its heading does, such as `Recorded L7 · Slugger asks: Which name? → 2 Ouro`, so a misread answer shows at once. The agent is told in its private runtime and woken; the private-runtime policy allows that wake only when it names the letter and comes from the daemon's answer command. A receipt or wake that fails is logged and never undoes the answer."
|
|
34
|
+
]
|
|
35
|
+
},
|
|
15
36
|
{
|
|
16
37
|
"version": "0.1.0-alpha.1644",
|
|
17
38
|
"changes": [
|
|
@@ -119,6 +119,33 @@ function liveButlerName() {
|
|
|
119
119
|
return imageButlerName(docker(["inspect", CONTAINER, "--format", "{{.Image}}"], { stdio: ["ignore", "pipe", "pipe"] }).trim())
|
|
120
120
|
}
|
|
121
121
|
|
|
122
|
+
// ---- a rename's predecessor ----------------------------------------------------
|
|
123
|
+
// What the running release must hold before an upgrade may change the Butler's name, as the root lifecycle has it
|
|
124
|
+
// (BUTLER_RENAME_PREDECESSOR_MARKERS): a rollback lands on that release, so it has to rewrite the bundle's container
|
|
125
|
+
// paths for a named Butler (#1983), and its daemon has to merge the other name's events and find an event Await's record
|
|
126
|
+
// under either name (M2 step 4b). Read as files, so a release is judged by what it can do, not by its version number.
|
|
127
|
+
export const BUTLER_RENAME_PREDECESSOR_MARKERS = [
|
|
128
|
+
["deploy/unraid/migrate-sanctuary-bundle.mjs", "--butler-name"],
|
|
129
|
+
["dist/heart/external-events/router.js", "externalEventAwaitRecordPath"],
|
|
130
|
+
]
|
|
131
|
+
/** Null when an upgrade from Butler name `running` to `target` may go ahead; otherwise why not. `read(file)` is the running release's file, or null. */
|
|
132
|
+
export function renamePredecessorProblem(running, target, read) {
|
|
133
|
+
if (running === target) return null
|
|
134
|
+
const missing = BUTLER_RENAME_PREDECESSOR_MARKERS.filter(([file, marker]) => !(read(file) ?? "").includes(marker)).map(([file]) => file)
|
|
135
|
+
if (missing.length === 0) return null
|
|
136
|
+
return `this upgrade renames the Butler from ${running} to ${target}, but the running release cannot take a rollback across that rename (its ${missing.join(" and ")} predate it). Ship a release from after M2 step 4b ("Butler: what the rename needs first") with the name unchanged first, then the release that renames it`
|
|
137
|
+
}
|
|
138
|
+
/** The running release's file: from the installed package, or from the running image when no authority is installed yet. */
|
|
139
|
+
function runningReleaseFile(runningImage, file) {
|
|
140
|
+
try {
|
|
141
|
+
return existsSync(`${ROOT}/active.json`) ? readFileSync(`${ROOT}/package/${file}`, "utf8")
|
|
142
|
+
: docker(["run", "--rm", "--entrypoint", "/bin/cat", runningImage, `/opt/ouro/${file}`], { stdio: ["ignore", "pipe", "ignore"] })
|
|
143
|
+
} catch { return null }
|
|
144
|
+
}
|
|
145
|
+
function renamePredecessorIssue(version, runningImage) {
|
|
146
|
+
return renamePredecessorProblem(imageButlerName(runningImage), imageButlerName(image(version)), (file) => runningReleaseFile(runningImage, file))
|
|
147
|
+
}
|
|
148
|
+
|
|
122
149
|
// Unraid's cgroup2-unraid daemon watches /sys/fs/cgroup via inotify and rmdir's any
|
|
123
150
|
// cgroup that reports `populated 0`. The authority install creates its cgroup empty and
|
|
124
151
|
// keeps it empty through staging/verification (which asserts cgroup.procs === ""), so the
|
|
@@ -228,6 +255,15 @@ function preflight(version, { fresh = false } = {}) {
|
|
|
228
255
|
dropped.length === 0 ? ok("every escalation holder in the bundle is already in the trusted file") : dropped.forEach((line) => bad(line))
|
|
229
256
|
}
|
|
230
257
|
|
|
258
|
+
say("a rollback can undo a change of the Butler's name")
|
|
259
|
+
if (id && runningImage) {
|
|
260
|
+
try {
|
|
261
|
+
const issue = renamePredecessorIssue(version, runningImage)
|
|
262
|
+
issue ? bad(issue) : ok("the name stays the same, or the running release can take a rollback across the rename")
|
|
263
|
+
} catch (e) { bad(`could not check the Butler's name: ${String(e.message).split("\n")[0]}`) }
|
|
264
|
+
} else if (!fresh) bad("skipped (no image or no running Butler)")
|
|
265
|
+
else ok("not needed: a fresh install has nothing to roll back to")
|
|
266
|
+
|
|
231
267
|
say("no credential handoff left for another Butler name")
|
|
232
268
|
if (id) {
|
|
233
269
|
try {
|
|
@@ -818,8 +854,9 @@ function migrateBundle(version, rollbackImage) {
|
|
|
818
854
|
sh("/usr/local/bin/node", [migrate, "--package-root", pkgBundle, "--agent-root", bundle, "--operation", "seed"])
|
|
819
855
|
ok("bundle seeded from the package (fresh install)")
|
|
820
856
|
} else {
|
|
857
|
+
// The host folder keeps its name, so the migrate is told the Butler the target image runs: the bundle's own files name its container path.
|
|
821
858
|
sh("/usr/local/bin/node", [migrate, "--package-root", pkgBundle, "--agent-root", bundle, "--operation", "migrate",
|
|
822
|
-
"--rollback-image-id", rollbackImage, "--target-image-id", imageId(version)])
|
|
859
|
+
"--rollback-image-id", rollbackImage, "--target-image-id", imageId(version), "--butler-name", imageButlerName(image(version))])
|
|
823
860
|
ok("bundle migrated (rollback retained)")
|
|
824
861
|
sh("/usr/local/bin/node", [migrate, "--package-root", pkgBundle, "--agent-root", bundle, "--operation", "commit"])
|
|
825
862
|
}
|
|
@@ -1023,6 +1060,8 @@ function install(version) {
|
|
|
1023
1060
|
if (fresh && containerExists(CONTAINER)) fail(`an ${CONTAINER} container already exists; a fresh install needs a host without one`)
|
|
1024
1061
|
const rollbackImage = fresh ? null : docker(["inspect", CONTAINER, "--format", "{{.Image}}"]).trim()
|
|
1025
1062
|
if (!targetImage || targetImage === rollbackImage) fail("target/rollback image identity invalid")
|
|
1063
|
+
const renameIssue = rollbackImage ? renamePredecessorIssue(version, rollbackImage) : null
|
|
1064
|
+
if (renameIssue) fail(`${renameIssue}; nothing was changed`)
|
|
1026
1065
|
const jellyfinBefore = jellyfinState()
|
|
1027
1066
|
const policyBefore = fresh ? policyState() : policyState() ?? fail(`steward policy missing`)
|
|
1028
1067
|
ok(`target ${targetImage.slice(0,19)}… rollback ${rollbackImage ? `${rollbackImage.slice(0,19)}…` : "none (fresh install)"} policy ${policyBefore ?? "none yet"}`)
|
|
@@ -1520,6 +1559,9 @@ async function upgrade(version, rehearse, { noGate = false, plant } = {}) {
|
|
|
1520
1559
|
const current = JSON.parse(readFileSync(`${ROOT}/request.json`, "utf8"))
|
|
1521
1560
|
if (existsSync(UPGRADE_JOURNAL)) console.log(" note: resuming the pending in-place upgrade with its staged package")
|
|
1522
1561
|
else {
|
|
1562
|
+
// The root lifecycle refuses this too when the upgrade begins; refusing here leaves nothing staged or paused.
|
|
1563
|
+
const renameIssue = renamePredecessorIssue(version, docker(["inspect", CONTAINER, "--format", "{{.Image}}"]).trim())
|
|
1564
|
+
if (renameIssue) fail(`${renameIssue}; nothing was paused or changed`)
|
|
1523
1565
|
const manifestBytes = stageIncomingPackage(version)
|
|
1524
1566
|
const pkgVersion = JSON.parse(readFileSync(`${ROOT}/incoming-package/deploy/unraid/sanctuary.ouro/bundle-meta.json`, "utf8")).runtimeVersion
|
|
1525
1567
|
if (pkgVersion !== version) fail(`staged package is ${pkgVersion}, not ${version}`)
|
|
@@ -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.
|
|
4
|
+
<Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1648</Repository>
|
|
5
5
|
<Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
|
|
6
6
|
<Network>host</Network>
|
|
7
7
|
<Shell>sh</Shell>
|
|
@@ -6,9 +6,11 @@ exports.createProviderReadinessPreparationFailure = createProviderReadinessPrepa
|
|
|
6
6
|
exports.createSanctuaryBundlePreparationFailure = createSanctuaryBundlePreparationFailure;
|
|
7
7
|
exports.failFastContainerCredentialBootstrapStartup = failFastContainerCredentialBootstrapStartup;
|
|
8
8
|
exports.failFastSanctuaryBundlePreparationStartup = failFastSanctuaryBundlePreparationStartup;
|
|
9
|
+
exports.failFastButlerExternalEventsStartup = failFastButlerExternalEventsStartup;
|
|
9
10
|
exports.startDaemonAfterContainerCredentialBootstrap = startDaemonAfterContainerCredentialBootstrap;
|
|
10
11
|
const runtime_1 = require("../../nerves/runtime");
|
|
11
12
|
const daemon_tombstone_1 = require("./daemon-tombstone");
|
|
13
|
+
const router_1 = require("../external-events/router");
|
|
12
14
|
const REDACTED_BOOTSTRAP_STARTUP_ERROR = "container credential bootstrap rejected; recoverable claim retained for reconciliation";
|
|
13
15
|
const SANCTUARY_BUNDLE_RECOVERY_GUIDANCE = {
|
|
14
16
|
restart_from_verified_release: "restart Ouro Butler from its verified release so the installed bundle can finish updating",
|
|
@@ -79,6 +81,12 @@ function failFastSanctuaryBundlePreparationStartup(input) {
|
|
|
79
81
|
const message = input.failure instanceof DaemonPreparationFailure ? input.failure.message : REDACTED_SANCTUARY_BUNDLE_PREPARATION_ERROR;
|
|
80
82
|
failFastDaemonStartup({ exit: input.exit, errorMessage: message, eventMessage: message });
|
|
81
83
|
}
|
|
84
|
+
const REDACTED_BUTLER_EXTERNAL_EVENTS_ERROR = "Butler external events need attention\n agent-runnable: read the daemon.external_events_adoption_failed event, fix the external-events folder it names, then restart the daemon";
|
|
85
|
+
/** The running Butler could not take over its other name's external events: stop the start, saying what to fix. */
|
|
86
|
+
function failFastButlerExternalEventsStartup(input) {
|
|
87
|
+
const message = input.failure instanceof router_1.ButlerExternalEventAdoptionError ? input.failure.message : REDACTED_BUTLER_EXTERNAL_EVENTS_ERROR;
|
|
88
|
+
failFastDaemonStartup({ exit: input.exit, errorMessage: message, eventMessage: message });
|
|
89
|
+
}
|
|
82
90
|
async function startDaemonAfterContainerCredentialBootstrap(input) {
|
|
83
91
|
try {
|
|
84
92
|
const preflight = input.preflight?.();
|
|
@@ -127,7 +127,14 @@ const managedAgents = (0, agent_discovery_1.listHomeBundleAgents)({ machineId: d
|
|
|
127
127
|
// The Butler under whichever name its bundle has; its container paths follow that name.
|
|
128
128
|
const butlerName = (0, butler_agent_1.managedButlerAgent)(managedAgents) ?? "sanctuary";
|
|
129
129
|
// Its saved external events follow that name too: a folder left under the other name (by the rename or a rollback) moves over.
|
|
130
|
-
|
|
130
|
+
// It must: records left under the other name can't be settled, so a failed move or merge stops the start.
|
|
131
|
+
try {
|
|
132
|
+
(0, router_1.prepareButlerExternalEvents)((0, router_1.getExternalEventRoot)(), managedAgents);
|
|
133
|
+
}
|
|
134
|
+
catch (failure) {
|
|
135
|
+
(0, daemon_bootstrap_startup_1.failFastButlerExternalEventsStartup)({ failure, exit: (code) => process.exit(code) });
|
|
136
|
+
throw failure;
|
|
137
|
+
}
|
|
131
138
|
const readinessAgents = (0, daemon_bootstrap_startup_1.providerReadinessAgents)(managedAgents, process.env.OURO_DAEMON_REQUIRED_AGENT);
|
|
132
139
|
const sanctuaryPackageManagement = (0, sanctuary_package_management_1.resolveSanctuaryPackageManagementActivation)({ mode, argv: process.argv, managedAgents, repoRoot: (0, identity_1.getRepoRoot)(), bundlesRoot: (0, identity_1.getAgentBundlesRoot)(), runtimePackageVersion: (0, bundle_manifest_1.getPackageVersion)() });
|
|
133
140
|
try {
|
|
@@ -1232,13 +1232,18 @@ class OuroDaemon {
|
|
|
1232
1232
|
}
|
|
1233
1233
|
}
|
|
1234
1234
|
/**
|
|
1235
|
-
* One expiry pass
|
|
1236
|
-
* Answers how many letters it closed.
|
|
1235
|
+
* One expiry pass, which also retries returning answers to the sessions that asked. It reads no letters code until
|
|
1236
|
+
* some bundle has letters, so a daemon without them loads nothing. Answers how many letters it closed.
|
|
1237
1237
|
*/
|
|
1238
1238
|
async expireLetters() {
|
|
1239
1239
|
try {
|
|
1240
1240
|
const any = !!this.lettersWriter || fs.readdirSync(this.bundlesRoot).some((name) => fs.existsSync(path.join(this.bundlesRoot, name, "state", "letters")));
|
|
1241
|
-
|
|
1241
|
+
if (!any)
|
|
1242
|
+
return 0;
|
|
1243
|
+
const writer = await this.letters();
|
|
1244
|
+
const expired = await writer.expireDue();
|
|
1245
|
+
await writer.returnAnswers();
|
|
1246
|
+
return expired;
|
|
1242
1247
|
}
|
|
1243
1248
|
catch (error) {
|
|
1244
1249
|
// No bundles folder yet means no letters, not a failure worth a warning every minute.
|
|
@@ -1833,7 +1838,8 @@ class OuroDaemon {
|
|
|
1833
1838
|
try {
|
|
1834
1839
|
const now = new Date().toISOString();
|
|
1835
1840
|
if (fs.existsSync(this.privilegedEventSpoolRoot)) {
|
|
1836
|
-
|
|
1841
|
+
// The Butler the daemon start adopted the event folders for, so envelopes are filed where it reads them.
|
|
1842
|
+
const butler = (0, router_1.runningButlerAgent)();
|
|
1837
1843
|
this.privilegedEventScanner({ spoolRoot: this.privilegedEventSpoolRoot, eventRoot: this.externalEventRootPath(), ...(butler ? { agent: butler } : {}) });
|
|
1838
1844
|
}
|
|
1839
1845
|
const scanned = this.externalEventScanCache.scan(this.externalEventRootPath());
|
|
@@ -34,7 +34,8 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
34
34
|
})();
|
|
35
35
|
var _a;
|
|
36
36
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
37
|
-
exports.SanctuaryAuthorityRootLifecycle = exports.SANCTUARY_UPGRADE_STEPS = exports.SANCTUARY_KEEPER_BOOT_LINES = void 0;
|
|
37
|
+
exports.SanctuaryAuthorityRootLifecycle = exports.BUTLER_RENAME_PREDECESSOR_MARKERS = exports.SANCTUARY_UPGRADE_STEPS = exports.SANCTUARY_KEEPER_BOOT_LINES = void 0;
|
|
38
|
+
exports.butlerRenamePredecessorRefusal = butlerRenamePredecessorRefusal;
|
|
38
39
|
exports.predecessorExpectsPsycheMount = predecessorExpectsPsycheMount;
|
|
39
40
|
exports.predecessorHasBundleSync = predecessorHasBundleSync;
|
|
40
41
|
exports.recordSanctuaryRootLifecycleFailure = recordSanctuaryRootLifecycleFailure;
|
|
@@ -108,7 +109,22 @@ const INCOMING_MANIFEST = `${ROOT}/incoming-package-manifest.json`;
|
|
|
108
109
|
const EVENTS = "/boot/config/custom/ouro-events/spool";
|
|
109
110
|
const ICON = "https://raw.githubusercontent.com/ourostack/ouroboros/main/assets/ouroboros.png";
|
|
110
111
|
const IMAGE_REFERENCE = /^ghcr\.io\/ourostack\/ouroboros-butler:[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/u;
|
|
112
|
+
// A rollback restores the bundle files the migrate rewrote from the copies it took before, so edits made while held go too.
|
|
113
|
+
const HELD_ROLLBACK_UNDOES = "a rollback puts agent.json, state/attachments/recent.json, state/replay-client/provision.json, skills/*.md and house/HOUSE.md back as they were before the migrate, so edits made to them during the hold are lost";
|
|
111
114
|
exports.SANCTUARY_UPGRADE_STEPS = ["stop", "switch", "resident", "migrate", "start"];
|
|
115
|
+
/**
|
|
116
|
+
* What an installed package must hold before an upgrade may change the Butler's name: a rollback lands on it, so it has to
|
|
117
|
+
* rewrite the bundle's container paths for a named Butler (#1983), and its daemon has to take over and merge the other
|
|
118
|
+
* name's events and find an event Await's record under either name (M2 step 4b). Read as files, so a release is judged
|
|
119
|
+
* by what it can do, not by its version number. sanctuary-butler-upgrade.mjs carries the same list.
|
|
120
|
+
*/
|
|
121
|
+
exports.BUTLER_RENAME_PREDECESSOR_MARKERS = [
|
|
122
|
+
["deploy/unraid/migrate-sanctuary-bundle.mjs", "--butler-name"],
|
|
123
|
+
["dist/heart/external-events/router.js", "externalEventAwaitRecordPath"],
|
|
124
|
+
];
|
|
125
|
+
function butlerRenamePredecessorRefusal(running, target) {
|
|
126
|
+
return `Sanctuary upgrade would rename the Butler from ${running} to ${target}, but the installed release cannot take a rollback across that rename. Ship a release from after M2 step 4b ("Butler: what the rename needs first") with the name unchanged first, then the release that renames it`;
|
|
127
|
+
}
|
|
112
128
|
const ROOT_RECORDS = [["request.json", 1024 * 1024], ["package-manifest.json", 8 * 1024 * 1024], ["active.json", 1024 * 1024], ["activation.json", 1024 * 1024]];
|
|
113
129
|
const EPOCH_RECORDS = ["migration.json", "stage.json", "configured.json"];
|
|
114
130
|
const digest = (value) => `sha256:${(0, node_crypto_1.createHash)("sha256").update(value).digest("hex")}`;
|
|
@@ -866,7 +882,8 @@ class SanctuaryAuthorityRootLifecycle {
|
|
|
866
882
|
stop: () => this.#halt(),
|
|
867
883
|
switch: async () => { await this.#halt(); this.#switchPackage(journal); },
|
|
868
884
|
resident: () => this.#recreateResident(journal.to.imageReference, journal.to.imageId, { psycheMount: false, syncMount: true }),
|
|
869
|
-
|
|
885
|
+
// The host folder keeps its name, so the migrate is told the Butler the target image runs: the bundle's own files name its container path.
|
|
886
|
+
migrate: () => target().#bundle(["--operation", "migrate", "--rollback-image-id", journal.from.imageId, "--target-image-id", journal.to.imageId, "--butler-name", this.#imageButler(journal.to.imageId)]),
|
|
870
887
|
start: () => target().#startUpgraded(),
|
|
871
888
|
};
|
|
872
889
|
for (const step of exports.SANCTUARY_UPGRADE_STEPS) {
|
|
@@ -954,6 +971,10 @@ class SanctuaryAuthorityRootLifecycle {
|
|
|
954
971
|
throw new Error("Sanctuary already runs the requested image");
|
|
955
972
|
if (this.#docker(["image", "inspect", "--format", "{{.Id}}", input.imageReference]).trim() !== input.targetImageId)
|
|
956
973
|
throw new Error("Sanctuary upgrade image identity does not match its reference");
|
|
974
|
+
const running = this.#imageButler(this.#transaction.targetImageId);
|
|
975
|
+
const renamed = this.#imageButler(input.targetImageId);
|
|
976
|
+
if (running !== renamed && !this.#packageTakesRename(`${ROOT}/package`))
|
|
977
|
+
throw new Error(butlerRenamePredecessorRefusal(running, renamed));
|
|
957
978
|
const request = validateRequest(JSON.parse(this.#private(INCOMING_REQUEST)));
|
|
958
979
|
if (["epochId", "botId", "ownerUserId", "ownerChatId", "predecessorContract"].some((key) => request[key] !== this.#request[key]))
|
|
959
980
|
throw new Error("Sanctuary upgrade would change the authority identity");
|
|
@@ -1154,6 +1175,17 @@ class SanctuaryAuthorityRootLifecycle {
|
|
|
1154
1175
|
return `${AGENT}/${(0, butler_agent_1.butlerOnDisk)(this.#p(AGENT), fs.existsSync) ?? "sanctuary"}.ouro`;
|
|
1155
1176
|
}
|
|
1156
1177
|
#offset() { return `${this.#hostBundle()}/${OFFSET}`; }
|
|
1178
|
+
/** Whether the package at `root` can be rolled back to across a change of the Butler's name (BUTLER_RENAME_PREDECESSOR_MARKERS). */
|
|
1179
|
+
#packageTakesRename(root) {
|
|
1180
|
+
return exports.BUTLER_RENAME_PREDECESSOR_MARKERS.every(([file, marker]) => {
|
|
1181
|
+
try {
|
|
1182
|
+
return fs.readFileSync(this.#p(`${root}/${file}`), "utf8").includes(marker);
|
|
1183
|
+
}
|
|
1184
|
+
catch {
|
|
1185
|
+
return false;
|
|
1186
|
+
}
|
|
1187
|
+
});
|
|
1188
|
+
}
|
|
1157
1189
|
/** The Butler an image runs, from its own ENTRYPOINT. */
|
|
1158
1190
|
#imageButler(imageId) {
|
|
1159
1191
|
return (0, butler_agent_1.butlerNameFromEntrypoint)(JSON.parse(this.#docker(["image", "inspect", "--format", "{{json .Config.Entrypoint}}", imageId])));
|
|
@@ -1372,7 +1404,7 @@ async function runSanctuaryAuthorityRootCli(argv, write = (text) => process.stdo
|
|
|
1372
1404
|
}
|
|
1373
1405
|
else if (upgrade) {
|
|
1374
1406
|
await lifecycle.upgrade({ targetImageId: argv[1], imageReference: argv[2], ...(argv[4] ? { failAfter: argv[4] } : {}), ...(holdCommit ? { holdCommit: true } : {}) });
|
|
1375
|
-
write(`${JSON.stringify({ upgraded: argv[2], ...(holdCommit ? { held: true } : {}) })}\n`);
|
|
1407
|
+
write(`${JSON.stringify({ upgraded: argv[2], ...(holdCommit ? { held: true, rollbackUndoes: HELD_ROLLBACK_UNDOES } : {}) })}\n`);
|
|
1376
1408
|
}
|
|
1377
1409
|
else if (rollback) {
|
|
1378
1410
|
write(`${JSON.stringify({ rolledBack: await lifecycle.rollbackUpgrade() })}\n`);
|
|
@@ -33,10 +33,12 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.ExternalEventScanCache = void 0;
|
|
36
|
+
exports.ExternalEventScanCache = exports.BUTLER_ADOPTION_CONFLICTS_FOLDER = exports.ButlerExternalEventAdoptionError = void 0;
|
|
37
37
|
exports.getExternalEventRoot = getExternalEventRoot;
|
|
38
38
|
exports.externalEventRecordPath = externalEventRecordPath;
|
|
39
39
|
exports.readExternalEventRecord = readExternalEventRecord;
|
|
40
|
+
exports.externalEventAwaitRecordPath = externalEventAwaitRecordPath;
|
|
41
|
+
exports.runningButlerAgent = runningButlerAgent;
|
|
40
42
|
exports.prepareButlerExternalEvents = prepareButlerExternalEvents;
|
|
41
43
|
exports.repairExternalEventsFromManifest = repairExternalEventsFromManifest;
|
|
42
44
|
exports.listExternalEventStatus = listExternalEventStatus;
|
|
@@ -356,49 +358,202 @@ function readStoredExternalEventRecord(recordPath) {
|
|
|
356
358
|
function readExternalEventRecord(recordPath) {
|
|
357
359
|
return normaliseButlerRecord(readStoredExternalEventRecord(recordPath), recordPath);
|
|
358
360
|
}
|
|
361
|
+
/**
|
|
362
|
+
* The record an external-event Await names. Its key is the record's absolute path when it was filed; once the running
|
|
363
|
+
* Butler has taken over its other name's event folder, the same record sits under the running name's folder instead.
|
|
364
|
+
* Only a Butler's Await, keyed under a Butler name's folder, is looked up again.
|
|
365
|
+
*/
|
|
366
|
+
function externalEventAwaitRecordPath(agentName, filedFromKey, root = getExternalEventRoot()) {
|
|
367
|
+
const resolvedRoot = path.resolve(root);
|
|
368
|
+
const [folder, ...rest] = path.relative(resolvedRoot, path.resolve(filedFromKey)).split(path.sep);
|
|
369
|
+
if (!(0, butler_agent_1.isButlerAgent)(agentName) || !(0, butler_agent_1.isButlerAgent)(folder) || folder === agentName || fs.existsSync(filedFromKey))
|
|
370
|
+
return filedFromKey;
|
|
371
|
+
return path.join(resolvedRoot, agentName, ...rest);
|
|
372
|
+
}
|
|
373
|
+
/** Why the running Butler could not take over its other name's event folder. The daemon does not start until it is fixed. */
|
|
374
|
+
class ButlerExternalEventAdoptionError extends Error {
|
|
375
|
+
name = "ButlerExternalEventAdoptionError";
|
|
376
|
+
}
|
|
377
|
+
exports.ButlerExternalEventAdoptionError = ButlerExternalEventAdoptionError;
|
|
378
|
+
/** Where adoption keeps the other name's copy of a record that differs from the running Butler's. It starts with `.`, so no scan reads it as an agent. */
|
|
379
|
+
exports.BUTLER_ADOPTION_CONFLICTS_FOLDER = ".adoption-conflicts";
|
|
380
|
+
/** The external-events folder as the Unraid host sees it, for guidance a person or agent follows from outside the container. */
|
|
381
|
+
const BUTLER_HOST_EXTERNAL_EVENT_ROOT = "/mnt/user/appdata/ouro-butler/runtime/.ouro-cli/daemon/external-events";
|
|
382
|
+
/** The running Butler, as the daemon start set it; null outside the daemon, or when it manages no Butler (or both). */
|
|
383
|
+
function runningButlerAgent() {
|
|
384
|
+
return runningButler;
|
|
385
|
+
}
|
|
386
|
+
/** The lock folders the event store makes: a record's `<id>.json.lock`, `.capacity.lock`, and `.privileged-replay.lock`. */
|
|
387
|
+
function isEventStoreLock(name) {
|
|
388
|
+
return name.endsWith(".json.lock") || name === ".capacity.lock" || name === ".privileged-replay.lock";
|
|
389
|
+
}
|
|
390
|
+
/** What merging `from` into `to` would do, worked out before anything moves. */
|
|
391
|
+
function planButlerEventFolderMerge(from, to, relative = "", plan = { moves: [], replays: [], conflicts: [] }) {
|
|
392
|
+
for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
|
|
393
|
+
const source = path.join(from, entry.name);
|
|
394
|
+
const target = path.join(to, entry.name);
|
|
395
|
+
const at = path.join(relative, entry.name);
|
|
396
|
+
// A lock left by the other name's daemon, which is not running: it is removed with the folder.
|
|
397
|
+
if (entry.isDirectory() && isEventStoreLock(entry.name))
|
|
398
|
+
continue;
|
|
399
|
+
let targetStat = null;
|
|
400
|
+
try {
|
|
401
|
+
targetStat = fs.lstatSync(target);
|
|
402
|
+
}
|
|
403
|
+
catch {
|
|
404
|
+
targetStat = null;
|
|
405
|
+
}
|
|
406
|
+
if (!targetStat)
|
|
407
|
+
plan.moves.push({ from: source, to: target });
|
|
408
|
+
else if (entry.isDirectory() && targetStat.isDirectory())
|
|
409
|
+
planButlerEventFolderMerge(source, target, at, plan);
|
|
410
|
+
else if (entry.isFile() && targetStat.isFile() && entry.name === PRIVILEGED_REPLAY_STATE_FILE)
|
|
411
|
+
plan.replays.push({ from: source, to: target });
|
|
412
|
+
// A byte-identical copy is dropped with the folder; anything else both folders have is a conflict.
|
|
413
|
+
else if (!entry.isFile() || !targetStat.isFile() || !fs.readFileSync(source).equals(fs.readFileSync(target)))
|
|
414
|
+
plan.conflicts.push({ from: source, relative: at });
|
|
415
|
+
}
|
|
416
|
+
return plan;
|
|
417
|
+
}
|
|
418
|
+
function readReplayStateForMerge(statePath) {
|
|
419
|
+
let parsed;
|
|
420
|
+
try {
|
|
421
|
+
parsed = JSON.parse(fs.readFileSync(statePath, "utf8"));
|
|
422
|
+
}
|
|
423
|
+
catch {
|
|
424
|
+
parsed = null;
|
|
425
|
+
}
|
|
426
|
+
return isReplayState(parsed) ? parsed : null;
|
|
427
|
+
}
|
|
428
|
+
/** The privileged ingress nonce a record about to be quarantined holds, so the combined manifest still refuses its envelope. */
|
|
429
|
+
function quarantinedNonce(recordPath) {
|
|
430
|
+
let parsed;
|
|
431
|
+
try {
|
|
432
|
+
parsed = JSON.parse(fs.readFileSync(recordPath, "utf8"));
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
return null;
|
|
436
|
+
}
|
|
437
|
+
const nonce = Object(parsed).privilegedIngressNonce;
|
|
438
|
+
return typeof nonce === "string" ? nonce : null;
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Merge the other name's event folder into the running Butler's. The privileged replay manifests are combined first, so no
|
|
442
|
+
* accepted envelope is accepted twice. Each record the running folder lacks moves over. A record both have that differs keeps
|
|
443
|
+
* the running folder's copy, and the other's moves to `quarantine`: never deleted, and never a reason not to start.
|
|
444
|
+
*/
|
|
445
|
+
function mergeButlerEventFolders(from, to, quarantine, butler, now) {
|
|
446
|
+
const plan = planButlerEventFolderMerge(from, to);
|
|
447
|
+
const privilegedSource = path.join(from, PRIVILEGED_EVENT_SOURCE);
|
|
448
|
+
const nonces = plan.conflicts.filter((conflict) => path.dirname(conflict.from) === privilegedSource).map((conflict) => quarantinedNonce(conflict.from)).filter((nonce) => nonce !== null);
|
|
449
|
+
for (const replay of plan.replays) {
|
|
450
|
+
const running = readReplayStateForMerge(replay.to);
|
|
451
|
+
const other = readReplayStateForMerge(replay.from);
|
|
452
|
+
if (!running || !other) {
|
|
453
|
+
// A manifest that cannot be read is not combined: the other's copy is kept in quarantine with the records that differ.
|
|
454
|
+
plan.conflicts.push({ from: replay.from, relative: path.relative(from, replay.from) });
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
let merged = mergeReplayManifests(running, other);
|
|
458
|
+
for (const nonce of nonces)
|
|
459
|
+
merged = replayAdd(merged, nonce);
|
|
460
|
+
atomicWriteJson(replay.to, replayStateFromManifest(merged, now, butler), "Privileged replay manifest");
|
|
461
|
+
// Gone at once, so a start interrupted after this point does not combine (and count) the same manifest again.
|
|
462
|
+
fs.unlinkSync(replay.from);
|
|
463
|
+
}
|
|
464
|
+
for (const conflict of plan.conflicts) {
|
|
465
|
+
const destination = path.join(quarantine, conflict.relative);
|
|
466
|
+
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
|
467
|
+
fs.renameSync(conflict.from, destination);
|
|
468
|
+
}
|
|
469
|
+
for (const move of plan.moves)
|
|
470
|
+
fs.renameSync(move.from, move.to);
|
|
471
|
+
removeMergedEventFolder(from);
|
|
472
|
+
return { moved: plan.moves.length, quarantined: plan.conflicts.length, quarantine };
|
|
473
|
+
}
|
|
474
|
+
/** What is left of a merged folder: byte-identical copies the running folder holds, and the store's stale locks. */
|
|
475
|
+
function removeMergedEventFolder(dir) {
|
|
476
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
477
|
+
const child = path.join(dir, entry.name);
|
|
478
|
+
if (entry.isDirectory())
|
|
479
|
+
removeMergedEventFolder(child);
|
|
480
|
+
else
|
|
481
|
+
fs.unlinkSync(child);
|
|
482
|
+
}
|
|
483
|
+
fs.rmdirSync(dir);
|
|
484
|
+
}
|
|
359
485
|
/**
|
|
360
486
|
* At daemon start, the running Butler takes over the event folder saved under its other name (from before the rename,
|
|
361
|
-
* or from the release a rollback left)
|
|
487
|
+
* or from the release a rollback left): a same-filesystem rename, or a merge when both folders exist. Records that
|
|
488
|
+
* differ are quarantined, not lost. Only a rename that fails stops the start: records left outside the running
|
|
489
|
+
* Butler's folder can't be settled. A symlinked other folder is left alone, with a warning.
|
|
362
490
|
*/
|
|
363
|
-
function prepareButlerExternalEvents(root, managedAgents) {
|
|
491
|
+
function prepareButlerExternalEvents(root, managedAgents, now = () => new Date().toISOString()) {
|
|
364
492
|
const butler = (0, butler_agent_1.managedButlerAgent)(managedAgents);
|
|
365
493
|
runningButler = butler;
|
|
366
494
|
if (!butler)
|
|
367
495
|
return "none";
|
|
496
|
+
const otherName = butler_agent_1.BUTLER_AGENT_NAMES.find((name) => name !== butler);
|
|
368
497
|
const own = path.join(root, butler);
|
|
369
|
-
const
|
|
370
|
-
|
|
498
|
+
const other = path.join(root, otherName);
|
|
499
|
+
let otherStat;
|
|
500
|
+
try {
|
|
501
|
+
otherStat = fs.lstatSync(other);
|
|
502
|
+
}
|
|
503
|
+
catch {
|
|
371
504
|
return "none";
|
|
372
|
-
|
|
505
|
+
}
|
|
506
|
+
if (otherStat.isSymbolicLink() || !otherStat.isDirectory()) {
|
|
373
507
|
(0, runtime_1.emitNervesEvent)({
|
|
374
508
|
level: "warn",
|
|
375
509
|
component: "daemon",
|
|
376
|
-
event: "daemon.
|
|
377
|
-
message: "
|
|
378
|
-
meta: { butler, own,
|
|
510
|
+
event: "daemon.external_events_adoption_skipped",
|
|
511
|
+
message: "left the Butler's other-name external-events entry alone: it is not a plain folder",
|
|
512
|
+
meta: { butler, from: other, to: own, symlink: otherStat.isSymbolicLink() },
|
|
379
513
|
});
|
|
380
|
-
return "
|
|
514
|
+
return "skipped";
|
|
381
515
|
}
|
|
516
|
+
const merging = fs.existsSync(own);
|
|
517
|
+
const at = now();
|
|
518
|
+
const quarantine = path.join(root, exports.BUTLER_ADOPTION_CONFLICTS_FOLDER, otherName, at);
|
|
519
|
+
let result = { moved: 0, quarantined: 0, quarantine };
|
|
382
520
|
try {
|
|
383
|
-
|
|
521
|
+
if (merging)
|
|
522
|
+
result = mergeButlerEventFolders(other, own, quarantine, butler, at);
|
|
523
|
+
else
|
|
524
|
+
fs.renameSync(other, own);
|
|
384
525
|
}
|
|
385
526
|
catch (error) {
|
|
527
|
+
const reason = error instanceof Error ? error.message : /* v8 ignore next -- fs throws Error objects @preserve */ String(error);
|
|
386
528
|
(0, runtime_1.emitNervesEvent)({
|
|
387
|
-
level: "
|
|
529
|
+
level: "error",
|
|
388
530
|
component: "daemon",
|
|
389
531
|
event: "daemon.external_events_adoption_failed",
|
|
390
|
-
message: "could not move the Butler's other-name external
|
|
391
|
-
meta: { butler, from:
|
|
532
|
+
message: "could not move the Butler's other-name external events to the running Butler",
|
|
533
|
+
meta: { butler, from: other, to: own, quarantine, merging, error: reason },
|
|
534
|
+
});
|
|
535
|
+
throw new ButlerExternalEventAdoptionError([
|
|
536
|
+
`Butler external events need attention: ${merging ? "merging" : "moving"} ${other} into ${own} failed: ${reason}`,
|
|
537
|
+
` agent-runnable: move what is left in ${other} into ${own}, putting any record ${own} already has into ${quarantine} instead, then restart the daemon`,
|
|
538
|
+
` on the Unraid host these are ${BUTLER_HOST_EXTERNAL_EVENT_ROOT}/${otherName}, ${BUTLER_HOST_EXTERNAL_EVENT_ROOT}/${butler} and ${BUTLER_HOST_EXTERNAL_EVENT_ROOT}/${path.relative(root, quarantine)}`,
|
|
539
|
+
].join("\n"));
|
|
540
|
+
}
|
|
541
|
+
if (result.quarantined > 0) {
|
|
542
|
+
(0, runtime_1.emitNervesEvent)({
|
|
543
|
+
level: "warn",
|
|
544
|
+
component: "daemon",
|
|
545
|
+
event: "daemon.external_events_adoption_quarantined",
|
|
546
|
+
message: "kept the running Butler's copy of records both event folders had, and quarantined the other name's copy",
|
|
547
|
+
meta: { butler, from: other, to: own, quarantined: result.quarantined, quarantine },
|
|
392
548
|
});
|
|
393
|
-
return "failed";
|
|
394
549
|
}
|
|
395
550
|
(0, runtime_1.emitNervesEvent)({
|
|
396
551
|
component: "daemon",
|
|
397
552
|
event: "daemon.external_events_adopted",
|
|
398
|
-
message: "moved the Butler's other-name external-event folder to the running Butler",
|
|
399
|
-
meta: { butler, from:
|
|
553
|
+
message: merging ? "merged the Butler's other-name external-event folder into the running Butler's" : "moved the Butler's other-name external-event folder to the running Butler",
|
|
554
|
+
meta: { butler, from: other, to: own, merging, moved: merging ? result.moved : null, quarantined: result.quarantined },
|
|
400
555
|
});
|
|
401
|
-
return "adopted";
|
|
556
|
+
return merging ? "merged" : "adopted";
|
|
402
557
|
}
|
|
403
558
|
const MAX_REPAIR_MANIFEST_BYTES = 1024 * 1024;
|
|
404
559
|
const MAX_REPAIR_ENTRIES = 512;
|
|
@@ -55,7 +55,10 @@ function answerReceipt(letter, answer) {
|
|
|
55
55
|
/** The agent's note; the subject, label and note are other people's words, so they are quoted as theirs. */
|
|
56
56
|
function letterAnsweredNote(letter, answer) {
|
|
57
57
|
const note = answer.note ? `, with the note ${JSON.stringify(answer.note)}` : "";
|
|
58
|
-
|
|
58
|
+
const session = letter.from.session;
|
|
59
|
+
// The session that asked reads the answer on its next turn; naming it lets me raise the answer there sooner.
|
|
60
|
+
const asked = session ? ` it was asked from my ${session.channel} session with ${session.friendId} (${JSON.stringify(session.key)}), where the answer is left too.` : "";
|
|
61
|
+
return `my person answered letter ${letter.code} (its sender's subject: ${JSON.stringify(letter.subject)}) with option ${answer.option}, ${JSON.stringify(answer.label)}${note}.${asked} mailbox_read shows it.`;
|
|
59
62
|
}
|
|
60
63
|
function letterAnsweredWake(agent, letter) {
|
|
61
64
|
return {
|
|
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.ANSWERING_FILE = void 0;
|
|
36
|
+
exports.listBundleFriends = exports.ANSWERING_FILE = void 0;
|
|
37
37
|
exports.ownerFriendIds = ownerFriendIds;
|
|
38
38
|
exports.normalizeAnsweringHandle = normalizeAnsweringHandle;
|
|
39
39
|
exports.readAnsweringHandles = readAnsweringHandles;
|
|
@@ -52,8 +52,9 @@ const friends_1 = require("@ouro.bot/friends");
|
|
|
52
52
|
const runtime_1 = require("../../nerves/runtime");
|
|
53
53
|
exports.ANSWERING_FILE = "answering.json";
|
|
54
54
|
const listBundleFriends = (root) => new friends_1.FileFriendStore(path.join(root, "friends")).listAll();
|
|
55
|
+
exports.listBundleFriends = listBundleFriends;
|
|
55
56
|
/** The family records in a bundle's friends folder that name this machine's owner, the rule `ouro friend link-code` uses. */
|
|
56
|
-
async function ownerFriendIds(bundleRoot, owner, list = listBundleFriends) {
|
|
57
|
+
async function ownerFriendIds(bundleRoot, owner, list = exports.listBundleFriends) {
|
|
57
58
|
const friends = await list(bundleRoot);
|
|
58
59
|
return friends
|
|
59
60
|
.filter((record) => record.trustLevel === "family" && record.externalIds.some((id) => (0, friends_1.isLocalMachineOwnerIdentity)(id.provider, id.externalId, owner)))
|
|
@@ -164,7 +165,7 @@ async function setAnsweringHandle(bundleRoot, person, rawHandle, deps = {}) {
|
|
|
164
165
|
const checked = normalizeAnsweringHandle(rawHandle);
|
|
165
166
|
if (!checked.ok)
|
|
166
167
|
throw refusal("bad-handle", checked.problem);
|
|
167
|
-
const list = deps.list ?? listBundleFriends;
|
|
168
|
+
const list = deps.list ?? exports.listBundleFriends;
|
|
168
169
|
const friends = await list(bundleRoot);
|
|
169
170
|
const byId = friends.find((record) => record.id === person);
|
|
170
171
|
const byName = friends.filter((record) => record.name.toLowerCase() === person.toLowerCase());
|
|
@@ -35,6 +35,7 @@ async function runMailboxTool(name, args, ctx) {
|
|
|
35
35
|
try {
|
|
36
36
|
return JSON.stringify(await (0, doors_1.runMailboxAction)(name, input, {
|
|
37
37
|
agent: ctx?.agentName ?? (0, identity_1.getAgentName)(),
|
|
38
|
+
...(ctx?.currentSession ? { session: { friendId: ctx.currentSession.friendId, channel: ctx.currentSession.channel, key: ctx.currentSession.key } } : {}),
|
|
38
39
|
...(ctx?.daemonSocketPath ? { socketPath: ctx.daemonSocketPath } : {}),
|
|
39
40
|
}));
|
|
40
41
|
}
|
|
@@ -218,7 +218,10 @@ async function runMailboxAction(action, input, caller) {
|
|
|
218
218
|
}
|
|
219
219
|
const send = caller.send ?? (await Promise.resolve().then(() => __importStar(require("../daemon/socket-client")))).sendDaemonCommand;
|
|
220
220
|
const socketPath = caller.socketPath ?? (await Promise.resolve().then(() => __importStar(require("../daemon/socket-client")))).DEFAULT_DAEMON_SOCKET_PATH;
|
|
221
|
-
const command = {
|
|
221
|
+
const command = {
|
|
222
|
+
kind: "letters.action", agent: caller.agent, action, input, ...(caller.dryRun ? { dryRun: true } : {}),
|
|
223
|
+
...(caller.session && action === "mailbox_send" ? { session: caller.session } : {}),
|
|
224
|
+
};
|
|
222
225
|
// A wait holds the socket for its own timeout, and a deliver for its chat send (the daemon answers within
|
|
223
226
|
// DELIVER_DEADLINE_MS of starting it, perhaps after another deliver ahead of it); anything else answers at once.
|
|
224
227
|
const waitSeconds = action === "mailbox_wait" ? Number(input.timeout ?? 60) : action === "mailbox_deliver" ? 60 : 0;
|
|
@@ -0,0 +1,99 @@
|
|
|
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.RETURN_BACKOFF_MAX_MS = void 0;
|
|
37
|
+
exports.returnSession = returnSession;
|
|
38
|
+
exports.answerReturnText = answerReturnText;
|
|
39
|
+
exports.queueAnswerReturn = queueAnswerReturn;
|
|
40
|
+
exports.returnDue = returnDue;
|
|
41
|
+
// Returning a person's answer to the session that asked (design §3.4, "Answer return"). A letter filed from an
|
|
42
|
+
// agent's turn remembers that turn's session; once the answer is recorded, the daemon queues a note in that session,
|
|
43
|
+
// so its next turn reads "Ari answered L7: Ouro". The agent's private runtime is told separately (answered-note.ts).
|
|
44
|
+
const fs = __importStar(require("fs"));
|
|
45
|
+
const config_1 = require("../config");
|
|
46
|
+
const pending_1 = require("../../mind/pending");
|
|
47
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
48
|
+
/**
|
|
49
|
+
* Channels a returned note can't serve: the private runtime is told of every answer anyway, and a voice session drops
|
|
50
|
+
* any note older than a few minutes unread.
|
|
51
|
+
*/
|
|
52
|
+
const NO_RETURN_CHANNELS = new Set(["inner", "voice"]);
|
|
53
|
+
/**
|
|
54
|
+
* The session a letter returns its answer to, or null when there is none to return to: a caller with no session
|
|
55
|
+
* (the CLI, an MCP client), a channel in NO_RETURN_CHANNELS, coordinates that would name a folder outside the
|
|
56
|
+
* agent's own, or a session the agent has never had. With `agentRoot`, the session must have its session file.
|
|
57
|
+
*/
|
|
58
|
+
function returnSession(value, agentRoot) {
|
|
59
|
+
if (typeof value !== "object" || value === null)
|
|
60
|
+
return null;
|
|
61
|
+
const { friendId, channel, key } = value;
|
|
62
|
+
if (![friendId, channel, key].every((part) => (0, config_1.isValidSessionCoordinate)(part) && part.length <= 300))
|
|
63
|
+
return null;
|
|
64
|
+
const session = { friendId: friendId, channel: channel, key: key };
|
|
65
|
+
if (NO_RETURN_CHANNELS.has(session.channel))
|
|
66
|
+
return null;
|
|
67
|
+
if (agentRoot !== undefined && !fs.existsSync((0, config_1.resolveSessionPath)(session.friendId, session.channel, session.key, { agentRoot })))
|
|
68
|
+
return null;
|
|
69
|
+
return session;
|
|
70
|
+
}
|
|
71
|
+
/** The note the asking session reads; the label and note are the person's words. */
|
|
72
|
+
function answerReturnText(person, letter, answer) {
|
|
73
|
+
return `${person} answered ${letter.code}: ${answer.option} ${answer.label}${answer.note ? ` — ${answer.note}` : ""}`;
|
|
74
|
+
}
|
|
75
|
+
/** Queues the note in the session's pending folder, once per letter. A failed write throws. */
|
|
76
|
+
function queueAnswerReturn(agent, agentRoot, session, text, letter, at) {
|
|
77
|
+
(0, pending_1.queuePendingMessageOnce)((0, pending_1.getPendingDir)(agent, session.friendId, session.channel, session.key, agentRoot), {
|
|
78
|
+
// From the mailbox, not the agent: a Telegram session drops the agent's own stale notes unread.
|
|
79
|
+
from: "mailbox", friendId: session.friendId, channel: session.channel, key: session.key, content: text, timestamp: Date.parse(at), packetId: `letter-returned:${letter.id}`,
|
|
80
|
+
});
|
|
81
|
+
(0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.answer_returned", message: "an answer was returned to the session that asked", meta: { code: letter.code, channel: session.channel } });
|
|
82
|
+
}
|
|
83
|
+
/** The longest wait between tries, so a session that can't be written is still tried every hour. */
|
|
84
|
+
exports.RETURN_BACKOFF_MAX_MS = 60 * 60_000;
|
|
85
|
+
/**
|
|
86
|
+
* Whether an answered letter's return is due now: it has a session, no try has succeeded, and the wait after the last
|
|
87
|
+
* failed try (one minute, doubling, at most an hour) has passed.
|
|
88
|
+
*/
|
|
89
|
+
function returnDue(letter, events, now) {
|
|
90
|
+
if (!returnSession(letter.from.session) || !events.some((event) => event.t === "answered"))
|
|
91
|
+
return false;
|
|
92
|
+
const tries = events.filter((event) => event.t === "returned" && event.to === "session");
|
|
93
|
+
if (tries.some((event) => event.ok))
|
|
94
|
+
return false;
|
|
95
|
+
if (tries.length === 0)
|
|
96
|
+
return true;
|
|
97
|
+
const wait = Math.min(60_000 * 2 ** (tries.length - 1), exports.RETURN_BACKOFF_MAX_MS);
|
|
98
|
+
return now >= Date.parse(tries[tries.length - 1].at) + wait;
|
|
99
|
+
}
|
|
@@ -46,6 +46,7 @@ const answer_reader_1 = require("./answer-reader");
|
|
|
46
46
|
const letter_1 = require("./letter");
|
|
47
47
|
const answering_1 = require("./answering");
|
|
48
48
|
Object.defineProperty(exports, "ownerFriendIds", { enumerable: true, get: function () { return answering_1.ownerFriendIds; } });
|
|
49
|
+
const return_to_session_1 = require("./return-to-session");
|
|
49
50
|
const render_1 = require("./render");
|
|
50
51
|
const letter_index_1 = require("./letter-index");
|
|
51
52
|
const store_1 = require("./store");
|
|
@@ -115,18 +116,19 @@ class LettersWriter {
|
|
|
115
116
|
if (typeof input !== "object" || input === null || Array.isArray(input))
|
|
116
117
|
throw new LetterRefusal("bad-input", "The action's input must be an object.");
|
|
117
118
|
const letters = this.open(agent, options.dryRun === true);
|
|
118
|
-
const
|
|
119
|
+
const session = action === "mailbox_send" ? (0, return_to_session_1.returnSession)(options.session, path.join(this.deps.bundlesRoot, `${agent}.ouro`)) : null;
|
|
120
|
+
const result = await this.dispatch(letters, action, input, options.dryRun === true, session);
|
|
119
121
|
(0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.action_done", message: "letters action done", meta: { action, outcome: result.outcome } });
|
|
120
122
|
return result;
|
|
121
123
|
}
|
|
122
|
-
dispatch(letters, action, input, dryRun) {
|
|
124
|
+
dispatch(letters, action, input, dryRun, session) {
|
|
123
125
|
switch (action) {
|
|
124
126
|
case "mailbox_send": return this.serial(letters, () => {
|
|
125
127
|
// Each send first rolls the letters closed long enough, so a daemon that runs for months still rolls them; a
|
|
126
128
|
// dry run writes nothing, so it doesn't roll.
|
|
127
129
|
if (!dryRun)
|
|
128
130
|
this.rollClosed(letters);
|
|
129
|
-
return this.send(letters, input, dryRun);
|
|
131
|
+
return this.send(letters, input, dryRun, session);
|
|
130
132
|
});
|
|
131
133
|
case "mailbox_list": return Promise.resolve(this.list(letters, input));
|
|
132
134
|
case "mailbox_read": return Promise.resolve(this.read(letters, input));
|
|
@@ -229,12 +231,12 @@ class LettersWriter {
|
|
|
229
231
|
? "No family friend record names this machine's owner, so Ouro can't tell who the letter is to."
|
|
230
232
|
: `${ids.length} family records name this machine's owner, so Ouro can't tell which one the letter is to.`);
|
|
231
233
|
}
|
|
232
|
-
async send(letters, input, dryRun) {
|
|
234
|
+
async send(letters, input, dryRun, session) {
|
|
233
235
|
const checked = (0, letter_1.checkLetterInput)(input);
|
|
234
236
|
if (!checked.ok)
|
|
235
237
|
throw new LetterRefusal("invalid-letter", checked.problem);
|
|
236
238
|
const { lane, ...draft } = checked.letter;
|
|
237
|
-
const from = { agent: letters.agent, ...(lane ? { lane } : {}) };
|
|
239
|
+
const from = { agent: letters.agent, ...(session ? { session } : {}), ...(lane ? { lane } : {}) };
|
|
238
240
|
const now = this.now();
|
|
239
241
|
if (draft.expiresAt && Date.parse(draft.expiresAt) <= now.getTime()) {
|
|
240
242
|
throw new LetterRefusal("invalid-letter", `expiresAt ${draft.expiresAt} has already passed. Fix: give a time in the future, or leave it out.`);
|
|
@@ -249,7 +251,8 @@ class LettersWriter {
|
|
|
249
251
|
return { outcome: "done", id: letter.id, code: letter.code, state: "answered", message: `${letter.code} was answered ${optionText(letter, answer.option)} in the last day, so the answer stands.` };
|
|
250
252
|
}
|
|
251
253
|
this.addEvent(letters, letter.id, { t: "refiled", at: now.toISOString(), by: letters.agent });
|
|
252
|
-
|
|
254
|
+
const elsewhere = letter.from.session && JSON.stringify(letter.from.session) !== JSON.stringify(session) ? " Its answer returns to the session that first filed it." : "";
|
|
255
|
+
return { outcome: "done", id: letter.id, code: letter.code, state: "waiting", message: `${letter.code} is already waiting with this dedupeKey, so it was refiled, not filed again.${elsewhere}` };
|
|
253
256
|
}
|
|
254
257
|
const to = await this.person(letters.agent);
|
|
255
258
|
if (dryRun)
|
|
@@ -332,9 +335,76 @@ class LettersWriter {
|
|
|
332
335
|
const label = letter.options.find((option) => option.id === answer.option).label;
|
|
333
336
|
(0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.answer_recorded", message: "a person's answer was recorded", meta: { code: letter.code, hostTrust } });
|
|
334
337
|
this.deps.onAnswered?.(letters.agent, letter, { option: answer.option, label, ...(answer.note ? { note: answer.note } : {}), messageGuid: message.guid, at }).catch(() => undefined);
|
|
338
|
+
// Its own step on the queue, so the person's answer is recorded and answered on whatever the return does.
|
|
339
|
+
void this.serial(letters, () => this.returnAnswer(letters, letter.id)).catch((error) => {
|
|
340
|
+
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.return_step_failed", message: "an answer's return step failed; the retry pass tries it again", meta: { code: letter.code, reason: error.message } });
|
|
341
|
+
});
|
|
335
342
|
return { recorded: true, id: letter.id, code: letter.code, subject: letter.subject, option: answer.option, label, ...(answer.note ? { note: answer.note } : {}) };
|
|
336
343
|
});
|
|
337
344
|
}
|
|
345
|
+
/**
|
|
346
|
+
* Returns an answered letter's answer to the session that asked, when that is due, and records the try as a
|
|
347
|
+
* `returned` event. A failed try is retried by returnAnswers; the answer stands either way.
|
|
348
|
+
*/
|
|
349
|
+
async returnAnswer(letters, id) {
|
|
350
|
+
const entry = letters.index.get(id);
|
|
351
|
+
const { letter } = entry;
|
|
352
|
+
if (!(0, return_to_session_1.returnDue)(letter, entry.events, this.now().getTime()))
|
|
353
|
+
return false;
|
|
354
|
+
const answer = entry.events.findLast((event) => event.t === "answered");
|
|
355
|
+
const label = letter.options.find((option) => option.id === answer.option).label;
|
|
356
|
+
const at = this.now().toISOString();
|
|
357
|
+
try {
|
|
358
|
+
const bundle = path.join(this.deps.bundlesRoot, `${letters.agent}.ouro`);
|
|
359
|
+
const friends = await (this.deps.listFriends ?? answering_1.listBundleFriends)(bundle).catch(() => []);
|
|
360
|
+
const person = friends.find((friend) => friend.id === letter.to)?.name || "my person";
|
|
361
|
+
(0, return_to_session_1.queueAnswerReturn)(letters.agent, bundle, letter.from.session, (0, return_to_session_1.answerReturnText)(person, letter, { option: answer.option, label, ...(answer.note ? { note: answer.note } : {}) }), letter, answer.at);
|
|
362
|
+
this.addEvent(letters, id, { t: "returned", at, to: "session", ok: true });
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
const detail = error.message;
|
|
366
|
+
this.addEvent(letters, id, { t: "returned", at, to: "session", ok: false, detail });
|
|
367
|
+
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.return_failed", message: "an answer couldn't be returned to the session that asked; it will be tried again", meta: { code: letter.code, detail } });
|
|
368
|
+
}
|
|
369
|
+
return true;
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Tries again every answer whose return to its session failed and is due, across the bundles that have letters.
|
|
373
|
+
* The daemon runs it on a timer; it answers how many it tried.
|
|
374
|
+
*/
|
|
375
|
+
async returnAnswers() {
|
|
376
|
+
let tried = 0;
|
|
377
|
+
let names = [];
|
|
378
|
+
try {
|
|
379
|
+
names = fs.readdirSync(this.deps.bundlesRoot);
|
|
380
|
+
}
|
|
381
|
+
catch (error) {
|
|
382
|
+
if (error.code !== "ENOENT")
|
|
383
|
+
throw error;
|
|
384
|
+
}
|
|
385
|
+
for (const name of names) {
|
|
386
|
+
const agent = name.endsWith(".ouro") ? name.slice(0, -".ouro".length) : "";
|
|
387
|
+
if (!AGENT_NAME.test(agent) || !fs.existsSync(path.join(this.deps.bundlesRoot, name, "state", "letters")))
|
|
388
|
+
continue;
|
|
389
|
+
try {
|
|
390
|
+
const letters = this.open(agent, false);
|
|
391
|
+
tried += await this.serial(letters, async () => {
|
|
392
|
+
const now = this.now().getTime();
|
|
393
|
+
let count = 0;
|
|
394
|
+
for (const entry of letters.index.list({ all: true }).filter((entry) => entry.state === "answered")) {
|
|
395
|
+
if ((0, return_to_session_1.returnDue)(entry.letter, entry.events, now) && await this.returnAnswer(letters, entry.letter.id))
|
|
396
|
+
count += 1;
|
|
397
|
+
}
|
|
398
|
+
return count;
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
catch (error) {
|
|
402
|
+
// One agent's letters that don't read leave the others' returns alone.
|
|
403
|
+
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.returns_failed", message: "an agent's answers could not be checked for return", meta: { agent, reason: error.message } });
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
return tried;
|
|
407
|
+
}
|
|
338
408
|
list(letters, input) {
|
|
339
409
|
const now = this.now().getTime();
|
|
340
410
|
const entries = letters.index.list({
|
|
@@ -456,7 +526,7 @@ function mayHaveSent(error) {
|
|
|
456
526
|
/** The daemon's answer to a `letters.action` command: the result, or the refusal's code and text. */
|
|
457
527
|
async function answerLettersCommand(writer, command) {
|
|
458
528
|
try {
|
|
459
|
-
return { ok: true, data: await writer.run(command.agent, command.action, command.input, { dryRun: command.dryRun === true }) };
|
|
529
|
+
return { ok: true, data: await writer.run(command.agent, command.action, command.input, { dryRun: command.dryRun === true, session: command.session }) };
|
|
460
530
|
}
|
|
461
531
|
catch (error) {
|
|
462
532
|
if (error instanceof LetterRefusal)
|
|
@@ -540,10 +540,12 @@ async function resolveAwaitTool(name, verdict, observation, agentRoot, agentName
|
|
|
540
540
|
}
|
|
541
541
|
const advancedEvents = existing.filed_from === "external-event" && existing.filed_from_key && existing.wake_at
|
|
542
542
|
? (() => {
|
|
543
|
-
|
|
543
|
+
// Filed before the running Butler took over its other name's event folder, the record now sits under the running name.
|
|
544
|
+
const recordPath = (0, router_1.externalEventAwaitRecordPath)(agentName, existing.filed_from_key);
|
|
545
|
+
if (!hasActiveExternalEventAwait(agentName, { recordPath, awaitName: name, wakeAt: existing.wake_at }))
|
|
544
546
|
throw new Error("External event await authority changed before resolution");
|
|
545
|
-
const record = (0, router_1.readExternalEventRecord)(
|
|
546
|
-
if (record.agent !== agentName || record.recordPath !==
|
|
547
|
+
const record = (0, router_1.readExternalEventRecord)(recordPath);
|
|
548
|
+
if (record.agent !== agentName || record.recordPath !== recordPath || record.executionState !== "handled"
|
|
547
549
|
|| record.disposition?.awaitId !== name || record.disposition.nextWake.kind !== "at" || record.disposition.nextWake.at !== existing.wake_at) {
|
|
548
550
|
throw new Error("External event await authority changed before resolution");
|
|
549
551
|
}
|
|
@@ -732,16 +734,17 @@ function inspectExternalEventAwait(agentName, input, root = (0, router_1.getExte
|
|
|
732
734
|
const relative = path.relative(path.resolve(root), path.resolve(input.recordPath));
|
|
733
735
|
if (relative.startsWith("..") || path.isAbsolute(relative))
|
|
734
736
|
throw new Error("External event await record is outside the event root");
|
|
737
|
+
const recordPath = (0, router_1.externalEventAwaitRecordPath)(agentName, input.recordPath, root);
|
|
735
738
|
let record;
|
|
736
739
|
try {
|
|
737
|
-
record = (0, router_1.readExternalEventRecord)(
|
|
740
|
+
record = (0, router_1.readExternalEventRecord)(recordPath);
|
|
738
741
|
}
|
|
739
742
|
catch (error) {
|
|
740
743
|
if (error.code === "ENOENT")
|
|
741
744
|
return { active: false, reason: "external event disposition is missing" };
|
|
742
745
|
throw error;
|
|
743
746
|
}
|
|
744
|
-
const active = record.agent === agentName && record.recordPath ===
|
|
747
|
+
const active = record.agent === agentName && record.recordPath === recordPath && record.executionState === "handled"
|
|
745
748
|
&& record.disposition?.awaitId === input.awaitName && record.disposition.nextWake.kind === "at" && record.disposition.nextWake.at === input.wakeAt;
|
|
746
749
|
return active ? { active: true } : { active: false, reason: "external event disposition is no longer active" };
|
|
747
750
|
}
|
|
@@ -170,7 +170,7 @@ function prepareExternalEventDisposition(a, ctx) {
|
|
|
170
170
|
throw new Error((0, tool_error_code_1.withCode)("External event timed disposition requires a current pending Await", "await-mismatch"));
|
|
171
171
|
}
|
|
172
172
|
const expectedOwnerId = ctx?.context?.friend.id;
|
|
173
|
-
if (pendingAwait.filed_from !== "external-event" || pendingAwait.filed_from_key !== record.recordPath
|
|
173
|
+
if (pendingAwait.filed_from !== "external-event" || (0, router_1.externalEventAwaitRecordPath)(agentName, pendingAwait.filed_from_key ?? "", (0, router_1.getExternalEventRoot)()) !== record.recordPath
|
|
174
174
|
|| (expectedOwnerId && pendingAwait.filed_for_friend_id !== expectedOwnerId)) {
|
|
175
175
|
throw new Error((0, tool_error_code_1.withCode)("External event timed disposition Await is not owned by this exact external event", "await-mismatch"));
|
|
176
176
|
}
|
|
@@ -36,6 +36,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
36
36
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
37
37
|
exports.SANCTUARY_HEALTH_ACCEPTANCE_PROBE_USAGE = void 0;
|
|
38
38
|
exports.acceptanceTargetEndpoint = acceptanceTargetEndpoint;
|
|
39
|
+
exports.probeButler = probeButler;
|
|
39
40
|
exports.registerSanctuaryHealthAcceptanceProbeProcess = registerSanctuaryHealthAcceptanceProbeProcess;
|
|
40
41
|
exports.createSanctuaryHealthAcceptanceProbeProcessHost = createSanctuaryHealthAcceptanceProbeProcessHost;
|
|
41
42
|
exports.createSanctuaryHealthAcceptanceProbeProcessDependencies = createSanctuaryHealthAcceptanceProbeProcessDependencies;
|
|
@@ -57,6 +58,7 @@ const node_http_1 = require("node:http");
|
|
|
57
58
|
const os = __importStar(require("node:os"));
|
|
58
59
|
const path = __importStar(require("node:path"));
|
|
59
60
|
const identity_1 = require("../heart/identity");
|
|
61
|
+
const butler_agent_1 = require("../heart/butler-agent");
|
|
60
62
|
const sanctuary_house_1 = require("./sanctuary-house");
|
|
61
63
|
const runtime_1 = require("../nerves/runtime");
|
|
62
64
|
const sanctuary_health_1 = require("./sanctuary-health");
|
|
@@ -77,6 +79,13 @@ const CRON_MARKER = "# ouro:habit:sanctuary:sanctuary:sanctuary-health";
|
|
|
77
79
|
const CRON_COMMAND = "*/15 * * * * /usr/local/bin/node /opt/ouro/dist/heart/daemon/ouro-entry.js poke sanctuary --habit sanctuary-health --trigger cron";
|
|
78
80
|
const PROCESS_ENTRY = "/opt/ouro/dist/senses/sanctuary-health-acceptance-probe-entry.js";
|
|
79
81
|
const LABELS = ["unit-16f-cron-fingerprint", "unit-16g-health-transition", "unit-16h-acceptance-delivery-probe"];
|
|
82
|
+
/**
|
|
83
|
+
* The Butler whose bundle is on disk. The probe runs as its own process, where no daemon start has said which name is
|
|
84
|
+
* running, so it asks the bundles folder; with neither bundle (or both) there it keeps `sanctuary`, the name from before the rename.
|
|
85
|
+
*/
|
|
86
|
+
function probeButler(bundlesRoot = (0, identity_1.getAgentBundlesRoot)(), exists = fs.existsSync) {
|
|
87
|
+
return (0, butler_agent_1.butlerOnDisk)(bundlesRoot, exists) ?? "sanctuary";
|
|
88
|
+
}
|
|
80
89
|
function digestBytes(value) {
|
|
81
90
|
return (0, node_crypto_1.createHash)("sha256").update(value).digest("hex");
|
|
82
91
|
}
|
|
@@ -161,7 +170,7 @@ function createSanctuaryHealthAcceptanceProbeProcessHost(raw = {
|
|
|
161
170
|
function createSanctuaryHealthAcceptanceProbeProcessDependencies(options = {}, host = createSanctuaryHealthAcceptanceProbeProcessHost()) {
|
|
162
171
|
const kill = options.kill ?? host.kill;
|
|
163
172
|
return {
|
|
164
|
-
agentRoot: options.agentRoot ?? (0, identity_1.getAgentRoot)(
|
|
173
|
+
agentRoot: options.agentRoot ?? (0, identity_1.getAgentRoot)(probeButler()),
|
|
165
174
|
listPids: () => (options.listProcEntries?.() ?? host.listProcEntries()).filter((entry) => /^[0-9]+$/u.test(entry)).map(Number),
|
|
166
175
|
processAlive: (pid) => {
|
|
167
176
|
try {
|
|
@@ -393,8 +402,10 @@ async function createSanctuaryHealthAcceptanceLoopbackFixture(statuses, ambientF
|
|
|
393
402
|
return { fetch: fixtureFetch, server, observed };
|
|
394
403
|
}
|
|
395
404
|
function createSanctuaryHealthAcceptanceProbeDependencies(overrides = {}, schedulerWait = {}) {
|
|
396
|
-
const
|
|
405
|
+
const butler = overrides.butler ?? probeButler();
|
|
406
|
+
const agentRoot = overrides.agentRoot ?? (0, identity_1.getAgentRoot)(butler);
|
|
397
407
|
const defaults = {
|
|
408
|
+
butler,
|
|
398
409
|
agentRoot,
|
|
399
410
|
runtimeRoot: overrides.runtimeRoot ?? path.join(os.homedir(), ".ouro-cli"),
|
|
400
411
|
ambientFetch: overrides.ambientFetch ?? fetch,
|
|
@@ -417,7 +428,7 @@ function createSanctuaryHealthAcceptanceProbeDependencies(overrides = {}, schedu
|
|
|
417
428
|
}
|
|
418
429
|
throw new Error("Sanctuary scheduler liveness receipt timed out");
|
|
419
430
|
}),
|
|
420
|
-
toolContext: overrides.toolContext ?? (0, sanctuary_runtime_1.createSanctuaryToolContext)(
|
|
431
|
+
toolContext: overrides.toolContext ?? (0, sanctuary_runtime_1.createSanctuaryToolContext)(butler),
|
|
421
432
|
acceptanceFs: overrides.acceptanceFs,
|
|
422
433
|
createLoopbackServer: overrides.createLoopbackServer,
|
|
423
434
|
house: overrides.house ?? (0, sanctuary_house_1.readSanctuaryHouse)(agentRoot),
|
|
@@ -565,7 +576,7 @@ async function runSanctuaryHealthAcceptanceProbe(input, dependencies = createSan
|
|
|
565
576
|
toolContext: dependencies.toolContext, house: dependencies.house, statePath, fetch: fetchImpl, now: () => now, lease, endpointDebounce: false,
|
|
566
577
|
acceptanceEventMeta: () => ({ scenarioHandleDigest: input.scenarioHandleDigest }),
|
|
567
578
|
});
|
|
568
|
-
await (0, sanctuary_health_runner_1.runSanctuaryHealthHabit)(
|
|
579
|
+
await (0, sanctuary_health_runner_1.runSanctuaryHealthHabit)(dependencies.butler ?? probeButler(), {
|
|
569
580
|
...dependencies.runnerOptions,
|
|
570
581
|
createSweep: () => sweep,
|
|
571
582
|
acceptanceMetrics: {
|
|
@@ -664,7 +675,7 @@ async function runSanctuaryHealthAcceptanceProbe(input, dependencies = createSan
|
|
|
664
675
|
throw error;
|
|
665
676
|
}
|
|
666
677
|
}
|
|
667
|
-
function finalizeSanctuaryHealthAcceptanceProbe(input, after, dependencies = { agentRoot: (0, identity_1.getAgentRoot)(
|
|
678
|
+
function finalizeSanctuaryHealthAcceptanceProbe(input, after, dependencies = { agentRoot: (0, identity_1.getAgentRoot)(probeButler()) }) {
|
|
668
679
|
canonicalInput(input);
|
|
669
680
|
if (!SHA256.test(after.ownerImageDigest) || !SHA256.test(after.ownerContainerDigest))
|
|
670
681
|
throw new Error("Sanctuary health acceptance final owner is invalid");
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ouro.bot/cli",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.1648",
|
|
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.
|
|
9
|
+
"version": "0.1.0-alpha.1648",
|
|
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.
|
|
3
|
+
"version": "0.1.0-alpha.1648",
|
|
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": {
|