@ouro.bot/cli 0.1.0-alpha.1402 → 0.1.0-alpha.1404

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,18 @@
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.1404",
6
+ "changes": [
7
+ "The Ouro AX census runs ouro-ui v1.3.465's census, which adds the declared-tools walker for bundles that ship a tools.json; the harness's own counts don't change."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1403",
12
+ "changes": [
13
+ "The Telegram sense can decide a deny relayed through Ari's primary agent, over a private local socket. It stays off until the trust-folder switch is set."
14
+ ]
15
+ },
4
16
  {
5
17
  "version": "0.1.0-alpha.1402",
6
18
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1402",
2
+ "runtimeVersion": "0.1.0-alpha.1404",
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.1402</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1404</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.EMPTY_CHAT_REPLY = void 0;
4
4
  exports.sealChatMessage = sealChatMessage;
5
5
  exports.openChatMessage = openChatMessage;
6
+ exports.openApprovalAnswer = openApprovalAnswer;
6
7
  /**
7
8
  * Sealed agent-to-agent chat over A2A (friends `message` kind).
8
9
  *
@@ -62,11 +63,11 @@ class MemorySeenLedger {
62
63
  function unreachableStore(name) {
63
64
  return new Proxy({}, { get() { throw new Error(`sealed chat must not touch the ${name}`); } });
64
65
  }
65
- /** Open a sealed chat message from an expected sender through `receiveShare`. */
66
- async function openChatMessage(input) {
66
+ /** Unseal and verify through `receiveShare`, pinned to the expected sender. Both openers below share this one path. */
67
+ async function receiveSealedMessage(input) {
67
68
  const pinStore = new a2a_client_1.MemoryPinStore();
68
69
  (0, a2a_client_1.pinOnFirstContact)({ pinStore, fromAgentId: input.senderDid, did: input.senderDid, ed25519Pub: input.senderEd25519Pub });
69
- const result = await (0, a2a_client_1.receiveShare)({
70
+ return (0, a2a_client_1.receiveShare)({
70
71
  sodium: input.sodium,
71
72
  store: unreachableStore("friend store"),
72
73
  missionStore: unreachableStore("mission store"),
@@ -86,6 +87,10 @@ async function openChatMessage(input) {
86
87
  trustOfSource: "family",
87
88
  options: { rejectUnboundEnvelopes: true, ...(input.now !== undefined ? { now: input.now } : {}) },
88
89
  });
90
+ }
91
+ /** Open a sealed chat message from an expected sender through `receiveShare`. */
92
+ async function openChatMessage(input) {
93
+ const result = await receiveSealedMessage(input);
89
94
  if (result.state === "rejected") {
90
95
  (0, runtime_1.emitNervesEvent)({
91
96
  level: "warn",
@@ -112,3 +117,26 @@ async function openChatMessage(input) {
112
117
  issuedAt: result.message.issuedAt,
113
118
  };
114
119
  }
120
+ /**
121
+ * Open a sealed approval answer from the expected sender. friends checks the signed field (deny only, a well-formed
122
+ * relay token, never with `onBehalfOf`, bound and at most 10 minutes old) and refuses it from a sender it can't
123
+ * verify. A sealed message without the field is refused here: only the field answers, never the text.
124
+ */
125
+ async function openApprovalAnswer(input) {
126
+ const result = await receiveSealedMessage(input);
127
+ const refuse = (reason) => {
128
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "channels", event: "channel.a2a_approval_answer_refused", message: "refused a sealed approval answer", meta: { senderDid: input.senderDid, reason } });
129
+ return { ok: false, reason };
130
+ };
131
+ if (result.state === "rejected")
132
+ return refuse(result.reason);
133
+ // Only a message receipt carries `message`: any other kind reaches a store, and these stores throw.
134
+ const answer = result.message?.approvalAnswer;
135
+ if (!answer)
136
+ return refuse("not_an_approval_answer");
137
+ /* v8 ignore next -- rejectUnboundEnvelopes is forced on, so a completed receipt always has its binding id @preserve */
138
+ if (!result.bindingId)
139
+ return refuse("unbound_approval_answer");
140
+ (0, runtime_1.emitNervesEvent)({ component: "channels", event: "channel.a2a_approval_answer_opened", message: "opened a verified approval answer", meta: { senderDid: input.senderDid } });
141
+ return { ok: true, approvalAnswer: { ...answer }, envelopeBindingId: result.bindingId, issuedAt: result.message.issuedAt };
142
+ }
@@ -84,8 +84,10 @@ class FileA2ASeenLedger {
84
84
  cache = new Map();
85
85
  now;
86
86
  lastPrunedAt;
87
+ /** `folder`: where under the bundle the ledger lives, `state/a2a/seen` by default. A process that opens envelopes of its
88
+ * own (the Telegram sense's approval relay) keeps its own ledger, so two processes never write one. */
87
89
  constructor(agentRoot, options = {}) {
88
- this.dir = path.join(agentRoot, "state", "a2a", "seen");
90
+ this.dir = path.join(agentRoot, ...(options.folder ?? ["state", "a2a", "seen"]));
89
91
  this.now = options.now ?? Date.now;
90
92
  fs.mkdirSync(this.dir, { recursive: true });
91
93
  this.lastPrunedAt = this.now();
@@ -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.RELAY_SOCKET_IDLE_TIMEOUT_MS = exports.MAX_RELAY_CONNECTIONS = exports.MAX_SOCKET_PATH_BYTES = void 0;
37
+ exports.relayAnswerSeenLedger = relayAnswerSeenLedger;
38
+ exports.handleRelayedApprovalAnswer = handleRelayedApprovalAnswer;
39
+ exports.approvalRelaySocketPath = approvalRelaySocketPath;
40
+ exports.startApprovalRelaySocket = startApprovalRelaySocket;
41
+ exports.createApprovalRelayDoor = createApprovalRelayDoor;
42
+ /**
43
+ * The Telegram sense's door for a relayed approval answer. The A2A process forwards the raw sealed message here,
44
+ * over `state/approvals/relay/sock`, without opening it. This process opens it and checks it, then decides it under
45
+ * the same lock as a tap, because this is the process that owns the approval cards (security review H3).
46
+ *
47
+ * Every answer re-reads the switch, so revoking or letting it expire takes effect on the next one. The checks, in order:
48
+ * 1. The trust-folder switch is on.
49
+ * 2. It names the same DID as the owner route in `agent.json`.
50
+ * 3. The envelope is sealed to us and signed by that DID. It is bound, fresh and unseen in this process's own ledger,
51
+ * and it carries the signed `approvalAnswer` field.
52
+ * 4. Its decision is deny (v1).
53
+ * 5. The relay token matches a card the Butler sent and is still waiting, found under the card's lock.
54
+ *
55
+ * Design: desk sanctuary-server/butler-productionization/ouroboros/2026-11-23-signed-relay-design-v3.md.
56
+ */
57
+ const fs = __importStar(require("node:fs"));
58
+ const net = __importStar(require("node:net"));
59
+ const path = __importStar(require("node:path"));
60
+ const a2a_client_1 = require("@ouro.bot/friends/a2a-client");
61
+ const approval_relay_1 = require("../a2a/approval-relay");
62
+ const identity_1 = require("../a2a/identity");
63
+ const operator_trust_1 = require("../a2a/operator-trust");
64
+ const identity_2 = require("../heart/identity");
65
+ const sealed_chat_1 = require("../a2a/sealed-chat");
66
+ const seen_ledger_1 = require("../a2a/seen-ledger");
67
+ const runtime_1 = require("../nerves/runtime");
68
+ /** The Telegram process's own replay ledger for relayed answers, at `state/approvals/relay-seen`. */
69
+ function relayAnswerSeenLedger(agentRoot) {
70
+ return new seen_ledger_1.FileA2ASeenLedger(agentRoot, { folder: ["state", "approvals", "relay-seen"] });
71
+ }
72
+ async function handleRelayedApprovalAnswer(deps, message) {
73
+ const now = deps.now?.() ?? new Date();
74
+ const refuse = (reply, detail) => {
75
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.telegram_relay_answer_refused", message: "refused a relayed approval answer", meta: { reply, detail } });
76
+ return reply;
77
+ };
78
+ const relaySwitch = (0, approval_relay_1.readApprovalRelaySwitch)(deps.agentRoot, now);
79
+ if (!relaySwitch.on)
80
+ return refuse("refused:switch_off", relaySwitch.reason);
81
+ const routeDid = deps.routeDid();
82
+ if (routeDid !== relaySwitch.did)
83
+ return refuse("refused:route_mismatch", routeDid === undefined ? "no owner route" : "switch and owner route name different DIDs");
84
+ const sender = (0, a2a_client_1.parseDidKey)(relaySwitch.did);
85
+ if (!sender)
86
+ return refuse("refused:route_mismatch", "the switch DID is not a did:key");
87
+ const self = typeof deps.self === "function" ? await deps.self() : deps.self;
88
+ const opened = await (0, sealed_chat_1.openApprovalAnswer)({
89
+ sodium: deps.sodium, self, message, senderDid: relaySwitch.did, senderEd25519Pub: sender.ed25519Pub, seen: deps.seen, now,
90
+ });
91
+ if (!opened.ok)
92
+ return refuse("refused:not_verified", opened.reason);
93
+ const decision = (0, approval_relay_1.checkRelayedDecision)(opened.approvalAnswer.decision);
94
+ /* v8 ignore next -- friends alpha.30 refuses any decision but deny before we see it; kept for when it allows more @preserve */
95
+ if (!decision.ok)
96
+ return refuse(`refused:${decision.reason}`, "decision");
97
+ return deps.runtime.relayDeny({
98
+ relayToken: opened.approvalAnswer.relayToken,
99
+ routeDid,
100
+ senderDid: relaySwitch.did,
101
+ envelopeBindingId: opened.envelopeBindingId,
102
+ });
103
+ }
104
+ /** The socket the A2A process forwards tagged envelopes to, alone in a folder only this agent's user can enter. */
105
+ function approvalRelaySocketPath(agentRoot) {
106
+ return path.join(agentRoot, "state", "approvals", "relay", "sock");
107
+ }
108
+ const MAX_REQUEST_BYTES = 256 * 1024;
109
+ /** macOS takes a socket path of at most 104 bytes and mishandles a longer one, so a longer path is refused instead. */
110
+ exports.MAX_SOCKET_PATH_BYTES = 104;
111
+ /** Answers come one at a time from one peer; a few slots are plenty, and a client that holds one can't hold them all. */
112
+ exports.MAX_RELAY_CONNECTIONS = 4;
113
+ /**
114
+ * Makes the socket's folder 0700 and owned by this user, so no other user can reach the socket whatever its own mode
115
+ * is while listen() creates it. A symlink or another user's folder there is refused rather than used.
116
+ */
117
+ function makePrivateFolder(dir) {
118
+ fs.mkdirSync(path.dirname(dir), { recursive: true });
119
+ try {
120
+ fs.mkdirSync(dir, { mode: 0o700 });
121
+ }
122
+ catch (error) {
123
+ /* v8 ignore next -- only an existing folder is expected here; anything else is a real fault @preserve */
124
+ if (error.code !== "EEXIST")
125
+ throw error;
126
+ }
127
+ const stat = fs.lstatSync(dir);
128
+ if (!stat.isDirectory() || stat.uid !== process.getuid()) {
129
+ throw new Error(`the relay socket's folder ${dir} isn't a folder this user owns`);
130
+ }
131
+ fs.chmodSync(dir, 0o700);
132
+ }
133
+ /** A connection that sends no byte for this long before its request line is in is dropped. */
134
+ exports.RELAY_SOCKET_IDLE_TIMEOUT_MS = 10_000;
135
+ /**
136
+ * Listens on `relay/sock` inside a 0700 folder, so only this agent's own user can connect, with at most
137
+ * MAX_RELAY_CONNECTIONS connections open at once. Each connection sends one JSON line `{"message": <A2A message>}` and gets back one line `{"reply": "<RelayReply>"}`.
138
+ */
139
+ async function startApprovalRelaySocket(input) {
140
+ if (Buffer.byteLength(input.socketPath) > exports.MAX_SOCKET_PATH_BYTES) {
141
+ throw new Error(`the relay socket path is over ${exports.MAX_SOCKET_PATH_BYTES} bytes: ${input.socketPath}`);
142
+ }
143
+ makePrivateFolder(path.dirname(input.socketPath));
144
+ try {
145
+ if (fs.lstatSync(input.socketPath).isSocket())
146
+ fs.rmSync(input.socketPath);
147
+ }
148
+ catch (error) {
149
+ /* v8 ignore next -- only a missing file is expected here; anything else is a real fault @preserve */
150
+ if (error.code !== "ENOENT")
151
+ throw error;
152
+ }
153
+ const server = net.createServer((socket) => {
154
+ const chunks = [];
155
+ let bytes = 0;
156
+ /** Stop reading: a request is answered once, and nothing after its first line is ever read. */
157
+ const stopReading = () => {
158
+ socket.setTimeout(0);
159
+ socket.removeAllListeners("data");
160
+ socket.pause();
161
+ };
162
+ const refuse = () => {
163
+ stopReading();
164
+ socket.end(`${JSON.stringify({ reply: "refused:malformed_request" })}\n`, () => socket.destroy());
165
+ };
166
+ // A client that connects and sends nothing, or dribbles, is dropped; the wait while an answer is decided isn't idle.
167
+ socket.setTimeout(input.idleTimeoutMs ?? exports.RELAY_SOCKET_IDLE_TIMEOUT_MS, () => socket.destroy());
168
+ socket.on("data", (chunk) => {
169
+ const newline = chunk.indexOf(0x0a);
170
+ const take = newline < 0 ? chunk : chunk.subarray(0, newline);
171
+ bytes += take.length;
172
+ if (bytes > MAX_REQUEST_BYTES)
173
+ return refuse();
174
+ chunks.push(take);
175
+ if (newline < 0)
176
+ return;
177
+ stopReading();
178
+ let message;
179
+ try {
180
+ message = JSON.parse(Buffer.concat(chunks).toString("utf8")).message;
181
+ }
182
+ catch {
183
+ return refuse();
184
+ }
185
+ if (!message || typeof message !== "object" || Array.isArray(message))
186
+ return refuse();
187
+ input.handle(message).then(
188
+ // Reading is paused, so the client's close would never be seen: close this side once the reply is flushed.
189
+ (reply) => socket.end(`${JSON.stringify({ reply })}\n`, () => socket.destroy()), (error) => {
190
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "senses", event: "senses.telegram_relay_socket_error", message: "a relayed approval answer failed while it was being decided", meta: { error: String(error) } });
191
+ socket.destroy();
192
+ });
193
+ });
194
+ /* v8 ignore next -- a client that resets mid-request; whether that surfaces as an error is up to the OS @preserve */
195
+ socket.on("error", () => socket.destroy());
196
+ });
197
+ // Node closes a connection past this limit as soon as it arrives.
198
+ server.maxConnections = exports.MAX_RELAY_CONNECTIONS;
199
+ await new Promise((resolve, reject) => {
200
+ server.once("error", reject);
201
+ server.listen(input.socketPath, () => resolve());
202
+ });
203
+ fs.chmodSync(input.socketPath, 0o600);
204
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_relay_socket_listening", message: "listening for relayed approval answers", meta: { socketPath: input.socketPath } });
205
+ return {
206
+ close: () => new Promise((resolve) => server.close(() => resolve())),
207
+ };
208
+ }
209
+ /**
210
+ * The door as the Telegram sense runs it. It listens only when the switch file is in the trust folder at startup, so a
211
+ * Butler without the grant has no socket at all; each answer still re-reads the switch. Failing to start is logged and
212
+ * leaves Telegram running: the relay is an extra way to answer, never the only one.
213
+ */
214
+ function createApprovalRelayDoor(input) {
215
+ let server;
216
+ return {
217
+ async start() {
218
+ if (server || !fs.existsSync((0, operator_trust_1.operatorTrustFile)(input.agentRoot, approval_relay_1.APPROVAL_RELAY_FILE)))
219
+ return;
220
+ try {
221
+ const sodium = await (0, a2a_client_1.ready)();
222
+ let identity;
223
+ /* v8 ignore next 2 -- the default identity load reads machine config and the vault; tests pass their own @preserve */
224
+ const loadIdentity = input.loadIdentity ?? (() => (0, identity_1.loadSelfA2AIdentity)({ agentName: input.agentName, sodium }));
225
+ const deps = {
226
+ agentRoot: input.agentRoot,
227
+ sodium,
228
+ // A failed load is forgotten, so the next answer tries again instead of failing forever.
229
+ self: () => (identity ??= loadIdentity().catch((error) => { identity = undefined; throw error; })),
230
+ routeDid: () => (0, identity_2.loadAgentConfig)({ agentName: input.agentName, agentRoot: input.agentRoot }).senses?.telegram.ownerNoticesTo?.did,
231
+ runtime: input.runtime,
232
+ seen: relayAnswerSeenLedger(input.agentRoot),
233
+ };
234
+ server = await startApprovalRelaySocket({
235
+ socketPath: input.socketPath ?? approvalRelaySocketPath(input.agentRoot),
236
+ handle: (message) => handleRelayedApprovalAnswer(deps, message),
237
+ });
238
+ }
239
+ catch (error) {
240
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "senses", event: "senses.telegram_relay_door_start_error", message: "the approval relay door could not start; taps still work", meta: { agentName: input.agentName, error: String(error) } });
241
+ }
242
+ },
243
+ async stop() {
244
+ const current = server;
245
+ server = undefined;
246
+ await current?.close();
247
+ },
248
+ };
249
+ }
@@ -531,7 +531,25 @@ function createTelegramApprovalRuntime(options) {
531
531
  if (!existing)
532
532
  return { accepted: false, terminalText: "⚠️ Approval is no longer valid" };
533
533
  let record;
534
- if (existing.state === "claimed") {
534
+ if (decision.relay) {
535
+ if (existing.state === "proposed") {
536
+ effectBarrier();
537
+ record = store.decideRelayed({
538
+ approvalId: existing.approvalId,
539
+ decisionToken: decision.decisionToken,
540
+ decision: "deny",
541
+ senderDid: decision.relay.senderDid,
542
+ envelopeBindingId: decision.relay.envelopeBindingId,
543
+ });
544
+ }
545
+ else if (existing.state === "denied" || existing.state === "expired") {
546
+ record = existing;
547
+ }
548
+ else {
549
+ return { accepted: false, terminalText: "⚠️ Approval was already decided" };
550
+ }
551
+ }
552
+ else if (existing.state === "claimed") {
535
553
  effectBarrier();
536
554
  record = (0, tool_approval_1.recoverClaimedApproval)({ approvalStore: store, approvalId: existing.approvalId, reason: "decision interrupted before action attempt; action was not executed" });
537
555
  }
@@ -635,7 +653,10 @@ function createTelegramApprovalRuntime(options) {
635
653
  message: "Telegram approval reached a terminal decision state",
636
654
  meta: { state: record.state, ...(decisionScenarioDigest ? { scenarioHandleDigest: decisionScenarioDigest } : {}) },
637
655
  });
638
- return continueTerminalRecord(record, decision.acceptanceBinding);
656
+ const terminal = await continueTerminalRecord(record, decision.acceptanceBinding);
657
+ if (!decision.relay)
658
+ return terminal;
659
+ return { ...terminal, relayApplied: record.state === "denied" && record.relayDecision?.envelopeBindingId === decision.relay.envelopeBindingId };
639
660
  },
640
661
  });
641
662
  const recover = async () => {
@@ -792,5 +813,19 @@ function createTelegramApprovalRuntime(options) {
792
813
  }
793
814
  return false;
794
815
  };
795
- return { transport, coordinator, legacySubjects, migrateIdentity, recover, isPendingTerminalControl, close: () => store.close() };
816
+ const relayDeny = async (input) => {
817
+ const result = await transport.relayDeny(input);
818
+ let answer;
819
+ if (result.status !== "settled")
820
+ answer = result.status;
821
+ else {
822
+ const record = store.read(result.approvalId);
823
+ answer = record?.state === "denied" && record.relayDecision?.envelopeBindingId === input.envelopeBindingId ? "denied"
824
+ : record?.state === "expired" ? "expired"
825
+ : "already_decided";
826
+ }
827
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_approval_relay_answered", message: "answered a relayed approval decision", meta: { agentName: options.agentName, answer } });
828
+ return answer;
829
+ };
830
+ return { transport, coordinator, legacySubjects, migrateIdentity, recover, isPendingTerminalControl, relayDeny, close: () => store.close() };
796
831
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.splitTelegramText = exports.escapeTelegramHtml = exports.TELEGRAM_APPROVAL_TOMBSTONE_TTL_MS = exports.TELEGRAM_APPROVAL_TERMINAL_EDIT_TIMEOUT_MS = exports.TELEGRAM_APPROVAL_EXPIRED_TEXT = exports.TELEGRAM_APPROVAL_TTL_MS = exports.FileTelegramPendingApprovalStore = exports.FileTelegramUpdateInboxStore = exports.TELEGRAM_TEST_ID_FLOOR = exports.TELEGRAM_ALLOWED_UPDATES = exports.FileTelegramOffsetStore = exports.MAX_TELEGRAM_UPLOAD_BYTES = exports.TelegramApiError = void 0;
3
+ exports.splitTelegramText = exports.escapeTelegramHtml = exports.TELEGRAM_APPROVAL_TOMBSTONE_TTL_MS = exports.TELEGRAM_APPROVAL_TERMINAL_EDIT_TIMEOUT_MS = exports.TELEGRAM_APPROVAL_EXPIRED_TEXT = exports.TELEGRAM_APPROVAL_TTL_MS = exports.TELEGRAM_APPROVAL_RELAYED_UNAPPLIED_NOTE = exports.TELEGRAM_APPROVAL_RELAYED_NOTE = exports.FileTelegramPendingApprovalStore = exports.FileTelegramUpdateInboxStore = exports.TELEGRAM_TEST_ID_FLOOR = exports.TELEGRAM_ALLOWED_UPDATES = exports.FileTelegramOffsetStore = exports.MAX_TELEGRAM_UPLOAD_BYTES = exports.TelegramApiError = void 0;
4
4
  exports.isTelegramInputFile = isTelegramInputFile;
5
5
  exports.isTelegramTestId = isTelegramTestId;
6
6
  exports.telegramUpdateMessageCoordinates = telegramUpdateMessageCoordinates;
@@ -13,6 +13,7 @@ const telegram_markdown_1 = require("./telegram-markdown");
13
13
  Object.defineProperty(exports, "escapeTelegramHtml", { enumerable: true, get: function () { return telegram_markdown_1.escapeTelegramHtml; } });
14
14
  Object.defineProperty(exports, "splitTelegramText", { enumerable: true, get: function () { return telegram_markdown_1.splitTelegramText; } });
15
15
  const runtime_1 = require("../nerves/runtime");
16
+ const approval_relay_1 = require("../a2a/approval-relay");
16
17
  const node_fs_1 = require("node:fs");
17
18
  const node_crypto_1 = require("node:crypto");
18
19
  const atomic_file_1 = require("../heart/atomic-file");
@@ -892,6 +893,10 @@ class FileTelegramPendingApprovalStore {
892
893
  }
893
894
  }
894
895
  exports.FileTelegramPendingApprovalStore = FileTelegramPendingApprovalStore;
896
+ /** The line a relayed answer adds to its card, before the decision and in the final state. */
897
+ exports.TELEGRAM_APPROVAL_RELAYED_NOTE = "↪️ Answered through Slugger: Deny";
898
+ /** When the relayed deny didn't take effect (the store had already decided), the card says so instead. */
899
+ exports.TELEGRAM_APPROVAL_RELAYED_UNAPPLIED_NOTE = "↪️ A Deny came through Slugger, but this was already decided";
895
900
  exports.TELEGRAM_APPROVAL_TTL_MS = 300_000;
896
901
  exports.TELEGRAM_APPROVAL_EXPIRED_TEXT = "⚠️ Approval expired";
897
902
  exports.TELEGRAM_APPROVAL_TERMINAL_EDIT_TIMEOUT_MS = 30_000;
@@ -901,6 +906,22 @@ function assertTelegramCallbackData(value) {
901
906
  if (bytes < 1 || bytes > 64)
902
907
  throw new Error("Telegram callback_data must be 1 to 64 bytes");
903
908
  }
909
+ function validRelayOrigin(value) {
910
+ if (!value || typeof value !== "object" || Array.isArray(value))
911
+ return false;
912
+ const origin = value;
913
+ return Object.keys(origin).sort().join(",") === "envelopeBindingId,senderDid"
914
+ && typeof origin.senderDid === "string" && origin.senderDid.length > 0
915
+ && typeof origin.envelopeBindingId === "string" && origin.envelopeBindingId.length > 0;
916
+ }
917
+ /** A relayed answer has no callback query; its attempt is keyed by the envelope it came in. */
918
+ function relayQueryIdDigest(relay) {
919
+ return (0, node_crypto_1.createHash)("sha256").update(`relay\0${relay.envelopeBindingId}`).digest("hex");
920
+ }
921
+ function withRelayedNote(text, applied) {
922
+ const note = `\n\n${applied ? exports.TELEGRAM_APPROVAL_RELAYED_NOTE : exports.TELEGRAM_APPROVAL_RELAYED_UNAPPLIED_NOTE}`;
923
+ return `${text.slice(0, 4_096 - note.length)}${note}`;
924
+ }
904
925
  function createTelegramApprovalTransport(options) {
905
926
  const now = options.now ?? Date.now;
906
927
  const effectBarrier = options.effectBarrier ?? (() => undefined);
@@ -998,6 +1019,7 @@ function createTelegramApprovalTransport(options) {
998
1019
  decision: attempt.decision,
999
1020
  queryIdDigest: attempt.queryIdDigest,
1000
1021
  attemptedAt: attempt.attemptedAt,
1022
+ ...(attempt.relay === undefined ? {} : { relay: attempt.relay }),
1001
1023
  });
1002
1024
  const decisionAttemptMac = (decisionToken, pending, attempt) => (0, node_crypto_1.createHmac)("sha256", decisionToken).update(JSON.stringify(decisionAttemptPayload(pending, attempt))).digest("hex");
1003
1025
  const resolveDecisionToken = async (pending) => {
@@ -1009,7 +1031,12 @@ function createTelegramApprovalTransport(options) {
1009
1031
  const validateDecisionAttempt = async (pending, expected) => {
1010
1032
  const attempt = pending.decisionAttempt;
1011
1033
  const lowerBound = pending.acceptanceBinding?.boundAt ?? pending.expiresAt - exports.TELEGRAM_APPROVAL_TTL_MS;
1012
- const unsigned = { schemaVersion: attempt.schemaVersion, decision: attempt.decision, queryIdDigest: attempt.queryIdDigest, attemptedAt: attempt.attemptedAt };
1034
+ const unsigned = {
1035
+ schemaVersion: attempt.schemaVersion, decision: attempt.decision, queryIdDigest: attempt.queryIdDigest, attemptedAt: attempt.attemptedAt,
1036
+ ...(attempt.relay === undefined ? {} : { relay: attempt.relay }),
1037
+ };
1038
+ const relayValid = attempt.relay === undefined || (validRelayOrigin(attempt.relay) && attempt.decision === "deny"
1039
+ && attempt.queryIdDigest === relayQueryIdDigest(attempt.relay));
1013
1040
  const token = pending.decisionToken ?? await options.resolveDecisionToken?.(pending.approvalId);
1014
1041
  const expectedMac = token ? decisionAttemptMac(token, pending, unsigned) : null;
1015
1042
  const suppliedMac = typeof attempt.evidenceMac === "string" ? Buffer.from(attempt.evidenceMac, "hex") : Buffer.alloc(0);
@@ -1023,7 +1050,9 @@ function createTelegramApprovalTransport(options) {
1023
1050
  || !/^[0-9a-f]{64}$/u.test(attempt.queryIdDigest)
1024
1051
  || !Number.isSafeInteger(attempt.attemptedAt) || attempt.attemptedAt < lowerBound || attempt.attemptedAt >= pending.expiresAt
1025
1052
  || (!tokenMacValid && !recoveryMacValid)
1026
- || (expected !== undefined && (attempt.decision !== expected.decision || attempt.queryIdDigest !== expected.queryIdDigest))) {
1053
+ || !relayValid
1054
+ || (expected !== undefined && (attempt.decision !== expected.decision || attempt.queryIdDigest !== expected.queryIdDigest
1055
+ || (attempt.relay === undefined) !== (expected.relay === undefined)))) {
1027
1056
  throw new Error("Telegram persisted decision attempt is invalid");
1028
1057
  }
1029
1058
  return attempt;
@@ -1059,7 +1088,9 @@ function createTelegramApprovalTransport(options) {
1059
1088
  || !Number.isSafeInteger(receipt.callbackAt)
1060
1089
  || typeof receipt.accepted !== "boolean"
1061
1090
  || receipt.reason !== (receipt.accepted ? "accepted" : "decision_refused")
1062
- || (receipt.kind === "live" ? !["acknowledged", "rejected_as_stale"].includes(receipt.acknowledgementState) : receipt.acknowledgementState !== "indeterminate_after_restart")
1091
+ || (receipt.kind === "live"
1092
+ ? !(pending.decisionAttempt.relay ? ["relayed"] : ["acknowledged", "rejected_as_stale"]).includes(receipt.acknowledgementState)
1093
+ : receipt.acknowledgementState !== "indeterminate_after_restart")
1063
1094
  || (receipt.kind === "live" ? receipt.recoveredAt !== null : !Number.isSafeInteger(receipt.recoveredAt))
1064
1095
  || receipt.callbackAt !== pending.decisionAttempt.attemptedAt
1065
1096
  || !/^[0-9a-f]{64}$/u.test(receipt.decisionAttemptDigest) || receipt.decisionAttemptDigest !== decisionAttemptDigest
@@ -1223,6 +1254,7 @@ function createTelegramApprovalTransport(options) {
1223
1254
  decision: observed.decision,
1224
1255
  queryIdDigest: observed.queryIdDigest,
1225
1256
  attemptedAt: observed.observedAt,
1257
+ ...(observed.relay === undefined ? {} : { relay: { senderDid: observed.relay.senderDid, envelopeBindingId: observed.relay.envelopeBindingId } }),
1226
1258
  };
1227
1259
  if (unsigned.attemptedAt < (pending.acceptanceBinding?.boundAt ?? pending.expiresAt - exports.TELEGRAM_APPROVAL_TTL_MS)
1228
1260
  || unsigned.attemptedAt >= pending.expiresAt)
@@ -1241,7 +1273,7 @@ function createTelegramApprovalTransport(options) {
1241
1273
  validateTerminalOutcome(pending);
1242
1274
  else {
1243
1275
  decisionToken ??= await resolveDecisionToken(pending);
1244
- outcome = await options.onDecision({
1276
+ const decided = await options.onDecision({
1245
1277
  approvalId: pending.approvalId,
1246
1278
  decisionToken,
1247
1279
  decision: attempt.decision,
@@ -1251,13 +1283,17 @@ function createTelegramApprovalTransport(options) {
1251
1283
  transportChatId: options.expectedChatId,
1252
1284
  transportMessageId: pending.messageId,
1253
1285
  ...(pending.acceptanceBinding ? { acceptanceBinding: pending.acceptanceBinding } : {}),
1286
+ ...(attempt.relay ? { relay: { ...attempt.relay } } : {}),
1254
1287
  });
1288
+ outcome = attempt.relay ? { accepted: decided.accepted, terminalText: withRelayedNote(decided.terminalText, decided.relayApplied === true) } : decided;
1255
1289
  persistMutation(pending, () => {
1256
1290
  pending.terminal = outcome;
1257
1291
  pending.terminalMac = signState("telegram.approval_terminal_outcome_state", pending, terminalOutcomeFields(pending));
1258
1292
  });
1259
1293
  }
1260
- const acknowledgementState = expected ? await acknowledge(expected.callbackQueryId, false) : "indeterminate_after_restart";
1294
+ const acknowledgementState = !expected ? "indeterminate_after_restart"
1295
+ : attempt.relay ? "relayed"
1296
+ : await acknowledge(expected.callbackQueryId, false);
1261
1297
  await editTerminal(pending, outcome.terminalText);
1262
1298
  const reason = outcome.accepted ? "accepted" : "decision_refused";
1263
1299
  persistMutation(pending, () => {
@@ -1430,6 +1466,36 @@ function createTelegramApprovalTransport(options) {
1430
1466
  return handleUpdateUnlocked(update, observedAt);
1431
1467
  },
1432
1468
  reconcileExpired,
1469
+ async relayDeny(input) {
1470
+ const receivedAt = now();
1471
+ const matches = async (candidate) => {
1472
+ if (candidate.deliveryState !== "bound" || candidate.messageId === null)
1473
+ return false;
1474
+ const decisionToken = candidate.decisionToken ?? await options.resolveDecisionToken?.(candidate.approvalId);
1475
+ if (!decisionToken || decisionToken.length < approval_relay_1.MIN_RELAY_KEY_LENGTH)
1476
+ return false;
1477
+ return (0, approval_relay_1.relayTokensEqual)((0, approval_relay_1.approvalRelayToken)({ decisionToken, approvalId: candidate.approvalId, routeDid: input.routeDid }), input.relayToken);
1478
+ };
1479
+ let match;
1480
+ for (const candidate of uniquePending())
1481
+ if (await matches(candidate))
1482
+ match = candidate;
1483
+ const result = match === undefined ? undefined : await withApprovalExclusive(match.approvalId, true, async () => {
1484
+ // Looked up again under the lock: a tap may have settled it, or its token may be gone, while we waited.
1485
+ const pending = uniquePending().find((record) => record.approvalId === match.approvalId);
1486
+ if (!pending || !await matches(pending) || classifyTelegramPersistedApprovalState(pending) !== "ordinary")
1487
+ return { status: "not_pending" };
1488
+ const lowerBound = pending.acceptanceBinding?.boundAt ?? pending.expiresAt - exports.TELEGRAM_APPROVAL_TTL_MS;
1489
+ if (receivedAt >= pending.expiresAt || receivedAt < lowerBound)
1490
+ return { status: "expired" };
1491
+ // Deny only, so nothing runs: the card is edited once, after the decision settles, with what actually happened.
1492
+ const relay = { senderDid: input.senderDid, envelopeBindingId: input.envelopeBindingId };
1493
+ await settleDecisionAttempt(pending, { decision: "deny", queryIdDigest: relayQueryIdDigest(relay), callbackQueryId: "", observedAt: receivedAt, relay });
1494
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "telegram.approval_relay_settled", message: "a relayed deny was decided", meta: { senderDid: input.senderDid } });
1495
+ return { status: "settled", approvalId: pending.approvalId };
1496
+ });
1497
+ return result ?? { status: "not_pending" };
1498
+ },
1433
1499
  async recoverDecisionAttempt(approvalId) {
1434
1500
  const result = await withApprovalExclusive(approvalId, true, async () => {
1435
1501
  const pending = uniquePending().find((record) => record.approvalId === approvalId);
@@ -1528,6 +1594,8 @@ function createTelegramApprovalTransport(options) {
1528
1594
  invalidReason = "prompt_not_bound";
1529
1595
  else if (messageId !== pending.messageId)
1530
1596
  invalidReason = "foreign_message";
1597
+ else if (pending.decisionAttempt?.relay !== undefined)
1598
+ invalidReason = "already_relayed";
1531
1599
  else if (persistedState === "expiry_observed")
1532
1600
  invalidReason = "expired";
1533
1601
  else {
@@ -71,6 +71,7 @@ const runtime_1 = require("../nerves/runtime");
71
71
  const chat_interaction_1 = require("../heart/chat-interaction");
72
72
  const nerves_1 = require("../nerves");
73
73
  const sanctuary_interactive_control_1 = require("./sanctuary-interactive-control");
74
+ const telegram_approval_relay_1 = require("./telegram-approval-relay");
74
75
  const sanctuary_runtime_1 = require("./sanctuary-runtime");
75
76
  const sanctuary_sab_1 = require("./sanctuary-sab");
76
77
  const sanctuary_download_credit_presentation_1 = require("./sanctuary-download-credit-presentation");
@@ -866,6 +867,7 @@ function createTelegramSenseApp(options) {
866
867
  let toolContext;
867
868
  let approvalTransport;
868
869
  let interactiveControl;
870
+ let approvalRelayDoor;
869
871
  try {
870
872
  toolContext = useSanctuaryRuntime ? (options._toolContext ?? (0, sanctuary_runtime_2.createSanctuaryToolContext)(options.agentName)) : undefined;
871
873
  if (toolContext && options.telegramContactManager)
@@ -967,6 +969,10 @@ function createTelegramSenseApp(options) {
967
969
  runRequest: runWithAcceptanceAuditOwner,
968
970
  })
969
971
  : undefined;
972
+ // Ari's deny relayed through his primary agent is decided here, beside the taps, under the same lock.
973
+ approvalRelayDoor = useSanctuaryRuntime && approvalRuntime
974
+ ? (options._createApprovalRelayDoor ?? telegram_approval_relay_1.createApprovalRelayDoor)({ agentName: options.agentName, agentRoot, runtime: approvalRuntime })
975
+ : undefined;
970
976
  }
971
977
  catch (error) {
972
978
  releaseAcceptanceAudit(error);
@@ -1911,6 +1917,7 @@ function createTelegramSenseApp(options) {
1911
1917
  async () => { await runPromise?.catch(() => undefined); },
1912
1918
  async () => { await Promise.all([...approvalReconciliationsInFlight]); },
1913
1919
  async () => { await interactiveControl?.stop(); },
1920
+ async () => { await approvalRelayDoor?.stop(); },
1914
1921
  () => api.stop(),
1915
1922
  () => approvalRuntime?.close(),
1916
1923
  () => effectJournal?.close(),
@@ -1946,6 +1953,7 @@ function createTelegramSenseApp(options) {
1946
1953
  await runWithAcceptanceAuditOwner(async () => { await approvalRuntime?.recover(); });
1947
1954
  await runWithAcceptanceAuditOwner(async () => { await rootHostRuntime?.recover(); });
1948
1955
  await runWithAcceptanceAuditOwner(async () => { await interactiveControl?.start(); });
1956
+ await runWithAcceptanceAuditOwner(async () => { await approvalRelayDoor?.start(); });
1949
1957
  try {
1950
1958
  await runWithAcceptanceAuditOwner(async () => { await approvalTransport?.reconcileExpired(); });
1951
1959
  }
@@ -1996,6 +2004,7 @@ function createTelegramSenseApp(options) {
1996
2004
  });
1997
2005
  }
1998
2006
  await interactiveControl?.stop();
2007
+ await approvalRelayDoor?.stop();
1999
2008
  }
2000
2009
  })();
2001
2010
  return runPromise;
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1402",
3
+ "version": "0.1.0-alpha.1404",
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.1402",
9
+ "version": "0.1.0-alpha.1404",
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.1402",
3
+ "version": "0.1.0-alpha.1404",
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": {