@ouro.bot/cli 0.1.0-alpha.1137 → 0.1.0-alpha.1139

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": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1139",
6
+ "changes": [
7
+ "Root can now play the owner in the live Butler chat for tests: a root-only driver on the Sanctuary host injects an owner message, reply, edit, reaction or button tap into the authority's own update path and returns what the Butler really sent. Test updates use ids far above Telegram's, so they never move the real cursor, and their button taps are answered locally. The authority logs what the bot sends only while a driver run has armed it, and the driver records each run in its nerves log."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1138",
12
+ "changes": [
13
+ "Test data no longer carries a real phone number, family names or a real Telegram chat key; made-up values replace them."
14
+ ]
15
+ },
4
16
  {
5
17
  "version": "0.1.0-alpha.1137",
6
18
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1137",
2
+ "runtimeVersion": "0.1.0-alpha.1139",
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.1137</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1139</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -34,6 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  };
35
35
  })();
36
36
  Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.readPrivateFile = readPrivateFile;
37
38
  exports.loadSanctuaryTelegramAuthorityConfig = loadSanctuaryTelegramAuthorityConfig;
38
39
  exports.startSanctuaryTelegramAuthority = startSanctuaryTelegramAuthority;
39
40
  exports.runSanctuaryTelegramAuthorityCli = runSanctuaryTelegramAuthorityCli;
@@ -51,6 +52,7 @@ const sanctuary_host_executor_1 = require("./sanctuary-host-executor");
51
52
  const sanctuary_authority_installation_1 = require("./sanctuary-authority-installation");
52
53
  const sanctuary_authority_epoch_1 = require("./sanctuary-authority-epoch");
53
54
  const sanctuary_telegram_authority_service_1 = require("./sanctuary-telegram-authority-service");
55
+ const sanctuary_telegram_test_driver_1 = require("./sanctuary-telegram-test-driver");
54
56
  const MAX_PRIVATE_FILE_BYTES = 64 * 1024;
55
57
  const MAX_ATTACHMENT_BYTES = 20_000_000;
56
58
  function isObject(value) {
@@ -407,6 +409,7 @@ async function startSanctuaryTelegramAuthority(options) {
407
409
  gateway,
408
410
  hostAuthority,
409
411
  hostExecutor,
412
+ testLog: new sanctuary_telegram_test_driver_1.FileSanctuaryTelegramTestLog((0, sanctuary_telegram_test_driver_1.sanctuaryTelegramTestLogRoot)(config.agentRoot)),
410
413
  downloadFile: async (filePath) => readBoundedFileResponse(await fetchImpl(`https://api.telegram.org/file/bot${token}/${filePath}`, { signal: AbortSignal.timeout(30_000) })),
411
414
  });
412
415
  server = (options.createServer ?? ((value) => (0, sanctuary_telegram_authority_service_1.createSanctuaryTelegramAuthorityServer)({
@@ -273,73 +273,11 @@ class FileSanctuaryTelegramAuthorityGateway {
273
273
  if (!validUpdate(update)) {
274
274
  throw new Error("Sanctuary Telegram authority update is invalid");
275
275
  }
276
- const updateId = update.update_id;
277
- const digest = rawUpdateDigest(update);
278
- const existing = state.records[String(updateId)];
279
- if (existing) {
280
- if (existing.rawUpdateDigest !== digest) {
281
- throw new Error(`Sanctuary Telegram authority duplicate update ${updateId} changed`);
282
- }
283
- continue;
276
+ if ((0, telegram_client_1.isTelegramTestId)(update.update_id)) {
277
+ throw new Error(`Sanctuary Telegram authority update ${update.update_id} is in the root test range`);
284
278
  }
285
- if (updateId < state.cursor) {
286
- throw new Error(`Sanctuary Telegram authority update ${updateId} is stale`);
287
- }
288
- const coordinates = updateCoordinates(update);
289
- if (!coordinates) {
290
- state.records[String(updateId)] = {
291
- updateId,
292
- rawUpdateDigest: digest,
293
- rawUpdate: structuredClone(update),
294
- disposition: "ignored",
295
- settlement: "ignored",
296
- observation: null,
297
- };
279
+ if (this.#captureOne(state, update))
298
280
  changed = true;
299
- continue;
300
- }
301
- const observedAt = this.#options.now();
302
- if (!validTime(observedAt))
303
- throw new Error("Sanctuary Telegram authority clock is invalid");
304
- this.#pruneAuthorizedChats(state, observedAt);
305
- const admitted = state.authorizedChats[`${coordinates.userId}:${coordinates.chatId}`];
306
- if (admitted)
307
- admitted.lastObservedAt = observedAt;
308
- const nonce = this.#options.nonce();
309
- if (!NONCE.test(nonce))
310
- throw new Error("Sanctuary Telegram authority nonce is invalid");
311
- if (Object.values(state.records).some((record) => record.observation?.payload.nonce === nonce)) {
312
- throw new Error("Sanctuary Telegram authority nonce is already used");
313
- }
314
- const payload = {
315
- targetHost: this.#options.targetHost,
316
- botId: this.#options.botId,
317
- updateId,
318
- ...coordinates,
319
- ownerEligible: coordinates.userId === this.#options.ownerUserId
320
- && coordinates.chatId === this.#options.ownerChatId,
321
- rawUpdateDigest: digest,
322
- ...(rawUpdateDigest(residentUpdate(update)) !== digest ? { deliveryUpdateDigest: rawUpdateDigest(residentUpdate(update)) } : {}),
323
- observedAt,
324
- settlement: "pending",
325
- nonce,
326
- publicKeyDigest: this.#options.publicKeyDigest,
327
- };
328
- state.records[String(updateId)] = {
329
- updateId,
330
- rawUpdateDigest: digest,
331
- rawUpdate: structuredClone(update),
332
- disposition: "dispatch",
333
- settlement: "pending",
334
- observation: (0, sanctuary_authority_codec_1.signAuthorityPayload)({
335
- domain: OBSERVATION_DOMAIN,
336
- keyId: this.#options.keyId,
337
- payload,
338
- privateKey: this.#options.privateKey,
339
- }),
340
- ...(rawUpdateDigest(residentUpdate(update)) !== digest ? { deliveryUpdate: residentUpdate(update) } : {}),
341
- };
342
- changed = true;
343
281
  }
344
282
  this.#advanceCursor(state);
345
283
  if (changed)
@@ -347,6 +285,107 @@ class FileSanctuaryTelegramAuthorityGateway {
347
285
  (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.sanctuary_telegram_capture_settled", message: "Sanctuary Telegram ingress capture settled", meta: { changed } });
348
286
  });
349
287
  }
288
+ /**
289
+ * Records one owner update that the root injected for a live test, exactly as a real update from the owner would be
290
+ * recorded, so the resident receives and answers it through the ordinary poll. Its id sits in the test range above
291
+ * Telegram's own, so it never moves the real cursor; the record itself is the durable mark that it was test-injected.
292
+ */
293
+ injectTestUpdate(update) {
294
+ if (!validUpdate(update) || !(0, telegram_client_1.isTelegramTestId)(update.update_id)) {
295
+ throw new Error("Sanctuary Telegram test update id is outside the root test range");
296
+ }
297
+ const coordinates = updateCoordinates(update);
298
+ if (!coordinates || coordinates.userId !== this.#options.ownerUserId || coordinates.chatId !== this.#options.ownerChatId) {
299
+ throw new Error("Sanctuary Telegram test update must come from the owner's chat");
300
+ }
301
+ return (0, session_transaction_1.withImmediateSessionTurnLease)(this.#statePath, (lease) => {
302
+ const transaction = (0, session_transaction_1.readSessionTransaction)(this.#statePath, lease);
303
+ const state = transactionState(transaction);
304
+ if (state.records[String(update.update_id)])
305
+ throw new Error(`Sanctuary Telegram test update ${update.update_id} already exists`);
306
+ this.#captureOne(state, update);
307
+ this.#write(state, transaction.revision, lease);
308
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.sanctuary_telegram_test_update_injected", message: "Sanctuary root injected a test owner update", meta: { updateId: update.update_id, updateClass: coordinates.updateClass } });
309
+ return state.records[String(update.update_id)].observation;
310
+ });
311
+ }
312
+ /** The next free id in the root test range. */
313
+ nextTestUpdateId() {
314
+ return this.#read((state) => Object.values(state.records)
315
+ .reduce((next, record) => (0, telegram_client_1.isTelegramTestId)(record.updateId) ? Math.max(next, record.updateId + 1) : next, telegram_client_1.TELEGRAM_TEST_ID_FLOOR));
316
+ }
317
+ /** True when the callback query came from a root-injected test tap, which Telegram itself never saw. */
318
+ isTestCallbackQuery(callbackQueryId) {
319
+ return this.#read((state) => Object.values(state.records).some((record) => (0, telegram_client_1.isTelegramTestId)(record.updateId) && record.rawUpdate.callback_query?.id === callbackQueryId));
320
+ }
321
+ #captureOne(state, update) {
322
+ const updateId = update.update_id;
323
+ const digest = rawUpdateDigest(update);
324
+ const existing = state.records[String(updateId)];
325
+ if (existing) {
326
+ if (existing.rawUpdateDigest !== digest) {
327
+ throw new Error(`Sanctuary Telegram authority duplicate update ${updateId} changed`);
328
+ }
329
+ return false;
330
+ }
331
+ if (updateId < state.cursor) {
332
+ throw new Error(`Sanctuary Telegram authority update ${updateId} is stale`);
333
+ }
334
+ const coordinates = updateCoordinates(update);
335
+ if (!coordinates) {
336
+ state.records[String(updateId)] = {
337
+ updateId,
338
+ rawUpdateDigest: digest,
339
+ rawUpdate: structuredClone(update),
340
+ disposition: "ignored",
341
+ settlement: "ignored",
342
+ observation: null,
343
+ };
344
+ return true;
345
+ }
346
+ const observedAt = this.#options.now();
347
+ if (!validTime(observedAt))
348
+ throw new Error("Sanctuary Telegram authority clock is invalid");
349
+ this.#pruneAuthorizedChats(state, observedAt);
350
+ const admitted = state.authorizedChats[`${coordinates.userId}:${coordinates.chatId}`];
351
+ if (admitted)
352
+ admitted.lastObservedAt = observedAt;
353
+ const nonce = this.#options.nonce();
354
+ if (!NONCE.test(nonce))
355
+ throw new Error("Sanctuary Telegram authority nonce is invalid");
356
+ if (Object.values(state.records).some((record) => record.observation?.payload.nonce === nonce)) {
357
+ throw new Error("Sanctuary Telegram authority nonce is already used");
358
+ }
359
+ const payload = {
360
+ targetHost: this.#options.targetHost,
361
+ botId: this.#options.botId,
362
+ updateId,
363
+ ...coordinates,
364
+ ownerEligible: coordinates.userId === this.#options.ownerUserId
365
+ && coordinates.chatId === this.#options.ownerChatId,
366
+ rawUpdateDigest: digest,
367
+ ...(rawUpdateDigest(residentUpdate(update)) !== digest ? { deliveryUpdateDigest: rawUpdateDigest(residentUpdate(update)) } : {}),
368
+ observedAt,
369
+ settlement: "pending",
370
+ nonce,
371
+ publicKeyDigest: this.#options.publicKeyDigest,
372
+ };
373
+ state.records[String(updateId)] = {
374
+ updateId,
375
+ rawUpdateDigest: digest,
376
+ rawUpdate: structuredClone(update),
377
+ disposition: "dispatch",
378
+ settlement: "pending",
379
+ observation: (0, sanctuary_authority_codec_1.signAuthorityPayload)({
380
+ domain: OBSERVATION_DOMAIN,
381
+ keyId: this.#options.keyId,
382
+ payload,
383
+ privateKey: this.#options.privateKey,
384
+ }),
385
+ ...(rawUpdateDigest(residentUpdate(update)) !== digest ? { deliveryUpdate: residentUpdate(update) } : {}),
386
+ };
387
+ return true;
388
+ }
350
389
  poll() {
351
390
  return this.#read((state) => {
352
391
  const record = Object.values(state.records)
@@ -532,8 +571,9 @@ class FileSanctuaryTelegramAuthorityGateway {
532
571
  return this.#read((state) => state.records[String(updateId)] ?? null);
533
572
  }
534
573
  #advanceCursor(state) {
574
+ // Root-injected test updates live above Telegram's ids and never hold or move the real cursor.
535
575
  const records = Object.values(state.records)
536
- .filter((record) => record.updateId >= state.cursor)
576
+ .filter((record) => record.updateId >= state.cursor && !(0, telegram_client_1.isTelegramTestId)(record.updateId))
537
577
  .sort((left, right) => left.updateId - right.updateId);
538
578
  for (const record of records) {
539
579
  if (record.disposition === "dispatch" && record.settlement === "pending")
@@ -41,6 +41,7 @@ const path = __importStar(require("node:path"));
41
41
  const telegram_client_1 = require("../../senses/telegram-client");
42
42
  const telegram_effect_adapter_1 = require("../../senses/telegram-effect-adapter");
43
43
  const frontend_socket_client_1 = require("../frontend-socket-client");
44
+ const sanctuary_telegram_test_driver_1 = require("./sanctuary-telegram-test-driver");
44
45
  const sanctuary_authority_codec_1 = require("./sanctuary-authority-codec");
45
46
  const runtime_1 = require("../../nerves/runtime");
46
47
  const PROTOCOL_VERSION = 1;
@@ -104,6 +105,7 @@ class SanctuaryTelegramAuthorityService {
104
105
  #hostExecutions = new Map();
105
106
  #hostExecutionFailures = new Map();
106
107
  #hostMaintenanceFailures = new Map();
108
+ #testLog;
107
109
  constructor(options) {
108
110
  this.#api = {
109
111
  request: (method, body) => options.api.request(method, body, AbortSignal.timeout(method === "getUpdates" || method === "sendPhoto" || method === "sendDocument" ? 60_000 : 15_000)),
@@ -112,6 +114,7 @@ class SanctuaryTelegramAuthorityService {
112
114
  this.#hostAuthority = options.hostAuthority;
113
115
  this.#hostExecutor = options.hostExecutor;
114
116
  this.#downloadFile = options.downloadFile;
117
+ this.#testLog = options.testLog;
115
118
  this.#pollReclaimAttempts = options.pollReclaimAttempts ?? AUTHORITY_POLL_RECLAIM_ATTEMPTS;
116
119
  this.#pollReclaimDelayMs = options.pollReclaimDelayMs ?? AUTHORITY_POLL_RECLAIM_DELAY_MS;
117
120
  }
@@ -143,6 +146,17 @@ class SanctuaryTelegramAuthorityService {
143
146
  }
144
147
  }
145
148
  }
149
+ #recordTestOutbound(input) {
150
+ if (!this.#testLog?.armed())
151
+ return;
152
+ try {
153
+ this.#testLog.append((0, sanctuary_telegram_test_driver_1.sanctuaryTelegramOutboundEntry)(input));
154
+ }
155
+ catch {
156
+ // The test log is a side record; a failure to write it never fails the bot's own send.
157
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "daemon.sanctuary_telegram_test_log_failed", message: "Sanctuary test driver log write failed", meta: { method: input.method } });
158
+ }
159
+ }
146
160
  #hostReady() {
147
161
  return this.#hostExecutor !== undefined && (this.#hostExecutor.isHealthy?.() ?? true);
148
162
  }
@@ -345,7 +359,26 @@ class SanctuaryTelegramAuthorityService {
345
359
  else {
346
360
  throw new Error("Sanctuary Telegram request method is not available");
347
361
  }
348
- const result = await this.#api.request(requestMethod, upload ?? body);
362
+ const observationUpdateId = isObject(params.observation) && Number.isSafeInteger(params.observation.updateId)
363
+ ? params.observation.updateId
364
+ : undefined;
365
+ // Telegram never saw a root-injected test tap or test message, so their callbacks are answered here and a
366
+ // reaction to, or a reply quoting, a test message would only be refused; the reply goes out plainly instead.
367
+ const testReplyTo = isObject(body.reply_parameters) && (0, telegram_client_1.isTelegramTestId)(body.reply_parameters.message_id)
368
+ ? body.reply_parameters.message_id
369
+ : undefined;
370
+ if ((requestMethod === "answerCallbackQuery" && this.#gateway.isTestCallbackQuery(body.callback_query_id))
371
+ || (requestMethod === "setMessageReaction" && (0, telegram_client_1.isTelegramTestId)(body.message_id))) {
372
+ this.#recordTestOutbound({ method: requestMethod, body, result: true, observationUpdateId, local: true });
373
+ return true;
374
+ }
375
+ let sendBody = (upload ?? body);
376
+ if (testReplyTo !== undefined) {
377
+ const { reply_parameters: _dropped, ...plain } = sendBody;
378
+ sendBody = plain;
379
+ }
380
+ const result = await this.#api.request(requestMethod, sendBody);
381
+ this.#recordTestOutbound({ method: requestMethod, body: sendBody, result, observationUpdateId, replyToDropped: testReplyTo });
349
382
  if (requestMethod === "getFile") {
350
383
  if (!isObject(result)
351
384
  || typeof result.file_path !== "string"
@@ -376,6 +409,11 @@ class SanctuaryTelegramAuthorityService {
376
409
  if (!isObject(sent) || !Number.isSafeInteger(sent.message_id) || sent.message_id <= 0) {
377
410
  throw new Error("Sanctuary host approval message result is invalid");
378
411
  }
412
+ this.#recordTestOutbound({
413
+ method: "host.approval",
414
+ body: { chat_id: this.#gateway.identity().ownerChatId, text: prepared.prompt, reply_markup: prepared.replyMarkup },
415
+ result: sent,
416
+ });
379
417
  const registration = this.#hostAuthority.commit({
380
418
  registrationId: prepared.registrationId,
381
419
  telegramMessageId: sent.message_id,
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.runSanctuaryTelegramTestDriverCli = runSanctuaryTelegramTestDriverCli;
38
+ const node_crypto_1 = require("node:crypto");
39
+ const fs = __importStar(require("node:fs"));
40
+ const runtime_1 = require("../../nerves/runtime");
41
+ const telegram_client_1 = require("../../senses/telegram-client");
42
+ const sanctuary_telegram_authority_entry_1 = require("./sanctuary-telegram-authority-entry");
43
+ const sanctuary_telegram_authority_gateway_1 = require("./sanctuary-telegram-authority-gateway");
44
+ const sanctuary_telegram_test_driver_1 = require("./sanctuary-telegram-test-driver");
45
+ /**
46
+ * Root-only entry for the owner-turn test driver. It reads the live authority's own config and signing key, which
47
+ * only root can read, and talks to nothing but the authority's state files and, for the visible echo, Telegram.
48
+ */
49
+ async function runSanctuaryTelegramTestDriverCli(options = {}) {
50
+ const argv = options.argv ?? process.argv.slice(2);
51
+ const configIndex = argv.indexOf("--config");
52
+ const configPath = configIndex >= 0 ? argv[configIndex + 1] : undefined;
53
+ if (!configPath)
54
+ throw new Error(sanctuary_telegram_test_driver_1.SANCTUARY_TELEGRAM_TEST_DRIVER_USAGE);
55
+ const rest = [...argv.slice(0, configIndex), ...argv.slice(configIndex + 2)];
56
+ const expectedUid = options.expectedUid ?? 0;
57
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.sanctuary_telegram_test_driver_started", message: "Sanctuary owner-turn test driver started", meta: {} });
58
+ const config = (0, sanctuary_telegram_authority_entry_1.loadSanctuaryTelegramAuthorityConfig)(configPath, { expectedUid });
59
+ const gateway = new sanctuary_telegram_authority_gateway_1.FileSanctuaryTelegramAuthorityGateway(config.agentRoot, {
60
+ targetHost: config.targetHost,
61
+ botId: config.botId,
62
+ ownerUserId: config.ownerUserId,
63
+ ownerChatId: config.ownerChatId,
64
+ keyId: config.keyId,
65
+ publicKeyDigest: config.publicKeyDigest,
66
+ privateKey: (0, node_crypto_1.createPrivateKey)((0, sanctuary_telegram_authority_entry_1.readPrivateFile)(config.privateKeyPath, expectedUid)),
67
+ });
68
+ let api;
69
+ try {
70
+ return await (0, sanctuary_telegram_test_driver_1.runSanctuaryTelegramTestDriver)(rest, {
71
+ gateway,
72
+ log: new sanctuary_telegram_test_driver_1.FileSanctuaryTelegramTestLog((0, sanctuary_telegram_test_driver_1.sanctuaryTelegramTestLogRoot)(config.agentRoot)),
73
+ botId: config.botId,
74
+ ownerUserId: config.ownerUserId,
75
+ ownerChatId: config.ownerChatId,
76
+ echo: async (text) => {
77
+ api ??= (options.createApi ?? ((token) => (0, telegram_client_1.createTelegramBotApi)({ token })))((0, sanctuary_telegram_authority_entry_1.readPrivateFile)(config.tokenPath, expectedUid).trim());
78
+ return api.request("sendMessage", { chat_id: config.ownerChatId, text });
79
+ },
80
+ ...(options.write ? { write: options.write } : {}),
81
+ });
82
+ }
83
+ finally {
84
+ api?.stop();
85
+ }
86
+ }
87
+ /* v8 ignore start -- process entry wiring; runSanctuaryTelegramTestDriverCli is tested directly @preserve */
88
+ if (process.argv[1] && fs.existsSync(process.argv[1]) && fs.realpathSync(process.argv[1]) === __filename) {
89
+ void runSanctuaryTelegramTestDriverCli().catch((error) => {
90
+ process.stderr.write(`${error instanceof Error ? error.message : "Sanctuary test driver failed"}\n`);
91
+ process.exitCode = 1;
92
+ });
93
+ }
94
+ /* v8 ignore stop @preserve */
@@ -0,0 +1,272 @@
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.SANCTUARY_TELEGRAM_TEST_DRIVER_USAGE = exports.FileSanctuaryTelegramTestLog = exports.TEST_TEXT_PREFIX = void 0;
37
+ exports.sanctuaryTelegramTestLogRoot = sanctuaryTelegramTestLogRoot;
38
+ exports.sanctuaryTelegramOutboundEntry = sanctuaryTelegramOutboundEntry;
39
+ exports.runSanctuaryTelegramTestDriver = runSanctuaryTelegramTestDriver;
40
+ const fs = __importStar(require("node:fs"));
41
+ const path = __importStar(require("node:path"));
42
+ const runtime_1 = require("../../nerves/runtime");
43
+ const telegram_client_1 = require("../../senses/telegram-client");
44
+ /**
45
+ * The owner-turn test driver lets the root on the Sanctuary host play the owner in the live bot chat: it records a
46
+ * synthetic owner update (a message, a reply, an edit, a reaction or a button tap) in the authority's own update
47
+ * records, the resident answers it through its ordinary poll, and the driver returns what the bot really sent.
48
+ *
49
+ * It is off unless invoked: nothing listens, the only entry is a root-run command that needs the authority's
50
+ * root-only config and signing key, and the authority logs outbound traffic only while a driver run has armed the
51
+ * log's window. Every injected update keeps an id in the test range, which is its durable test-injected mark.
52
+ */
53
+ exports.TEST_TEXT_PREFIX = "[test] ";
54
+ const DEFAULT_WAIT_SECONDS = 240;
55
+ const DEFAULT_QUIET_SECONDS = 20;
56
+ const WINDOW_GRACE_MS = 120_000;
57
+ const MAX_LOG_TEXT = 4_096;
58
+ function sanctuaryTelegramTestLogRoot(agentRoot) {
59
+ return path.join(agentRoot, "authority", "test-driver");
60
+ }
61
+ /** The root-only record of injected updates and of what the bot sent while a driver run was watching. */
62
+ class FileSanctuaryTelegramTestLog {
63
+ #root;
64
+ #now;
65
+ constructor(root, now = Date.now) {
66
+ this.#root = root;
67
+ this.#now = now;
68
+ }
69
+ get logPath() {
70
+ return path.join(this.#root, "log.ndjson");
71
+ }
72
+ get #windowPath() {
73
+ return path.join(this.#root, "armed-until.json");
74
+ }
75
+ armed() {
76
+ try {
77
+ const value = JSON.parse(fs.readFileSync(this.#windowPath, "utf8"));
78
+ return typeof value.until === "string" && Date.parse(value.until) > this.#now();
79
+ }
80
+ catch {
81
+ return false;
82
+ }
83
+ }
84
+ arm(untilMs) {
85
+ this.#ensureRoot();
86
+ fs.writeFileSync(this.#windowPath, `${JSON.stringify({ until: new Date(untilMs).toISOString() })}\n`, { mode: 0o600 });
87
+ }
88
+ append(entry) {
89
+ this.#ensureRoot();
90
+ const seq = this.read().length + 1;
91
+ fs.appendFileSync(this.logPath, `${JSON.stringify({ seq, at: new Date(this.#now()).toISOString(), ...entry })}\n`, { mode: 0o600 });
92
+ return seq;
93
+ }
94
+ read() {
95
+ let raw;
96
+ try {
97
+ raw = fs.readFileSync(this.logPath, "utf8");
98
+ }
99
+ catch {
100
+ return [];
101
+ }
102
+ return raw.split("\n").filter((line) => line.length > 0).map((line) => JSON.parse(line));
103
+ }
104
+ #ensureRoot() {
105
+ fs.mkdirSync(this.#root, { recursive: true, mode: 0o700 });
106
+ fs.chmodSync(this.#root, 0o700);
107
+ }
108
+ }
109
+ exports.FileSanctuaryTelegramTestLog = FileSanctuaryTelegramTestLog;
110
+ function clip(value) {
111
+ return typeof value === "string" && value.length > MAX_LOG_TEXT ? `${value.slice(0, MAX_LOG_TEXT)}…` : value;
112
+ }
113
+ /** What the authority writes when the bot sends something while a driver run is watching. */
114
+ function sanctuaryTelegramOutboundEntry(input) {
115
+ const { body, result } = input;
116
+ const resultMessageId = typeof result === "object" && result !== null && !Array.isArray(result)
117
+ ? result.message_id
118
+ : undefined;
119
+ return {
120
+ kind: "outbound",
121
+ method: input.method,
122
+ ...(body.chat_id !== undefined ? { chatId: String(body.chat_id) } : {}),
123
+ ...(input.observationUpdateId !== undefined ? { observationUpdateId: input.observationUpdateId, testObservation: (0, telegram_client_1.isTelegramTestId)(input.observationUpdateId) } : {}),
124
+ ...(body.text !== undefined ? { text: clip(body.text) } : {}),
125
+ ...(body.caption !== undefined ? { caption: clip(body.caption) } : {}),
126
+ ...(body.reply_markup !== undefined ? { replyMarkup: body.reply_markup } : {}),
127
+ ...(body.message_id !== undefined ? { targetMessageId: body.message_id } : {}),
128
+ ...(body.reaction !== undefined ? { reaction: body.reaction } : {}),
129
+ ...(body.reply_parameters !== undefined ? { replyTo: body.reply_parameters.message_id } : {}),
130
+ ...(input.replyToDropped !== undefined ? { replyTo: input.replyToDropped, replyToDropped: true } : {}),
131
+ ...(body.callback_query_id !== undefined ? { callbackQueryId: body.callback_query_id } : {}),
132
+ ...(Number.isSafeInteger(resultMessageId) ? { messageId: resultMessageId } : {}),
133
+ ...(input.local ? { local: true } : {}),
134
+ };
135
+ }
136
+ const VALUE_FLAGS = new Set(["--text", "--reply-to", "--reply-to-text", "--message-id", "--emoji", "--data", "--wait", "--quiet", "--since"]);
137
+ const SWITCHES = new Set(["--no-echo", "--no-wait"]);
138
+ function parseArguments(argv) {
139
+ const [command = "", ...rest] = argv;
140
+ const flags = new Map();
141
+ const switches = new Set();
142
+ for (let index = 0; index < rest.length; index += 1) {
143
+ const flag = rest[index];
144
+ if (SWITCHES.has(flag)) {
145
+ switches.add(flag);
146
+ continue;
147
+ }
148
+ const value = rest[index + 1];
149
+ if (!VALUE_FLAGS.has(flag) || value === undefined)
150
+ throw new Error(`unknown or incomplete option ${flag}`);
151
+ flags.set(flag, value);
152
+ index += 1;
153
+ }
154
+ return { command, flags, switches };
155
+ }
156
+ function positiveInteger(value, label) {
157
+ if (value === undefined || !/^[1-9][0-9]*$/u.test(value) || !Number.isSafeInteger(Number(value)))
158
+ throw new Error(`${label} must be a positive integer`);
159
+ return Number(value);
160
+ }
161
+ function testText(value) {
162
+ if (value === undefined || !value.startsWith(exports.TEST_TEXT_PREFIX) || value.length > 4_096) {
163
+ throw new Error(`--text must start with "${exports.TEST_TEXT_PREFIX}" and fit in one Telegram message`);
164
+ }
165
+ return value;
166
+ }
167
+ exports.SANCTUARY_TELEGRAM_TEST_DRIVER_USAGE = `usage: sanctuary-telegram-test-driver --config <active.json> <command> [options]
168
+ send --text "[test] ..." [--reply-to <message id> [--reply-to-text <its text>]]
169
+ edit --message-id <id of an earlier injected message> --text "[test] ..."
170
+ react --message-id <bot message id> --emoji <emoji>
171
+ tap --message-id <bot message id> --data <button callback data>
172
+ log [--since <seq>]
173
+ options for send/edit/react/tap: --wait <seconds> (default ${DEFAULT_WAIT_SECONDS}), --quiet <seconds> (default ${DEFAULT_QUIET_SECONDS}), --no-wait, --no-echo`;
174
+ async function runSanctuaryTelegramTestDriver(argv, deps) {
175
+ const now = deps.now ?? Date.now;
176
+ const sleep = deps.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
177
+ const write = deps.write ?? ((text) => { process.stdout.write(text); });
178
+ const { command, flags, switches } = parseArguments(argv);
179
+ if (command === "log") {
180
+ const since = flags.has("--since") ? positiveInteger(flags.get("--since"), "--since") : 0;
181
+ const entries = deps.log.read().filter((entry) => entry.seq > since);
182
+ write(`${JSON.stringify(entries, null, 2)}\n`);
183
+ return entries;
184
+ }
185
+ const owner = Number(deps.ownerUserId);
186
+ const chat = { id: Number(deps.ownerChatId), type: "private" };
187
+ const from = { id: owner, is_bot: false, first_name: "Owner (test)" };
188
+ const date = Math.floor(now() / 1_000);
189
+ const updateId = deps.gateway.nextTestUpdateId();
190
+ let update;
191
+ let echo;
192
+ if (command === "send") {
193
+ const text = testText(flags.get("--text"));
194
+ const replyTo = flags.has("--reply-to") ? positiveInteger(flags.get("--reply-to"), "--reply-to") : undefined;
195
+ const replyToText = flags.get("--reply-to-text");
196
+ update = {
197
+ update_id: updateId,
198
+ message: {
199
+ message_id: updateId, from, chat, date, text,
200
+ ...(replyTo !== undefined ? { reply_to_message: { message_id: replyTo, from: { id: Number(deps.botId), is_bot: true }, ...(replyToText !== undefined ? { text: replyToText } : {}) } } : {}),
201
+ },
202
+ };
203
+ echo = `🧪 test driver, owner says${replyTo !== undefined ? ` (replying to message ${replyTo})` : ""}: ${text}`;
204
+ }
205
+ else if (command === "edit") {
206
+ const messageId = positiveInteger(flags.get("--message-id"), "--message-id");
207
+ if (!(0, telegram_client_1.isTelegramTestId)(messageId))
208
+ throw new Error("--message-id must name an earlier injected message; only those can be edited");
209
+ const text = testText(flags.get("--text"));
210
+ update = { update_id: updateId, edited_message: { message_id: messageId, from, chat, date, edit_date: date, text } };
211
+ echo = `🧪 test driver, owner edits message ${messageId} to: ${text}`;
212
+ }
213
+ else if (command === "react") {
214
+ const messageId = positiveInteger(flags.get("--message-id"), "--message-id");
215
+ const emoji = flags.get("--emoji");
216
+ if (!emoji || emoji.length > 16)
217
+ throw new Error("--emoji is required");
218
+ update = { update_id: updateId, message_reaction: { chat, message_id: messageId, user: { id: owner }, date, old_reaction: [], new_reaction: [{ type: "emoji", emoji }] } };
219
+ echo = `🧪 test driver, owner reacts ${emoji} to message ${messageId}`;
220
+ }
221
+ else if (command === "tap") {
222
+ const messageId = positiveInteger(flags.get("--message-id"), "--message-id");
223
+ const data = flags.get("--data");
224
+ if (!data || Buffer.byteLength(data) > 256)
225
+ throw new Error("--data is required");
226
+ update = { update_id: updateId, callback_query: { id: `ouro-test-${updateId}`, from, message: { message_id: messageId, chat, date }, chat_instance: "ouro-test", data } };
227
+ echo = `🧪 test driver, owner taps a button on message ${messageId}`;
228
+ }
229
+ else {
230
+ throw new Error(exports.SANCTUARY_TELEGRAM_TEST_DRIVER_USAGE);
231
+ }
232
+ const waitSeconds = flags.has("--wait") ? positiveInteger(flags.get("--wait"), "--wait") : DEFAULT_WAIT_SECONDS;
233
+ const quietSeconds = flags.has("--quiet") ? positiveInteger(flags.get("--quiet"), "--quiet") : DEFAULT_QUIET_SECONDS;
234
+ const startedAt = now();
235
+ deps.log.arm(startedAt + (waitSeconds * 1_000) + WINDOW_GRACE_MS);
236
+ if (!switches.has("--no-echo") && deps.echo)
237
+ await deps.echo(echo);
238
+ const seq = deps.log.append({ kind: "injected", command, updateId, update });
239
+ deps.gateway.injectTestUpdate(update);
240
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "daemon.sanctuary_telegram_test_driver_injected", message: "Sanctuary test driver injected an owner update", meta: { updateId, command } });
241
+ const injected = { updateId, ...(command === "send" ? { messageId: updateId } : {}), seq };
242
+ if (switches.has("--no-wait")) {
243
+ write(`${JSON.stringify(injected, null, 2)}\n`);
244
+ return injected;
245
+ }
246
+ // Wait until the resident has settled the update and the bot has been quiet for a while, or the deadline passes.
247
+ const deadline = startedAt + waitSeconds * 1_000;
248
+ let settlement = "pending";
249
+ let settledAt;
250
+ let lastReplyAt = startedAt;
251
+ let replies = [];
252
+ let timedOut = false;
253
+ for (;;) {
254
+ settlement = deps.gateway.record(updateId)?.settlement ?? "missing";
255
+ if (settlement !== "pending" && settledAt === undefined)
256
+ settledAt = now();
257
+ const current = deps.log.read().filter((entry) => entry.seq > seq && entry.kind === "outbound");
258
+ if (current.length !== replies.length)
259
+ lastReplyAt = now();
260
+ replies = current;
261
+ if (settledAt !== undefined && now() - Math.max(settledAt, lastReplyAt) >= quietSeconds * 1_000)
262
+ break;
263
+ if (now() >= deadline) {
264
+ timedOut = true;
265
+ break;
266
+ }
267
+ await sleep(1_000);
268
+ }
269
+ const transcript = { ...injected, settlement, timedOut, replies };
270
+ write(`${JSON.stringify(transcript, null, 2)}\n`);
271
+ return transcript;
272
+ }
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- 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_ALLOWED_UPDATES = exports.FileTelegramOffsetStore = exports.MAX_TELEGRAM_UPLOAD_BYTES = exports.TelegramApiError = void 0;
3
+ 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;
4
4
  exports.isTelegramInputFile = isTelegramInputFile;
5
+ exports.isTelegramTestId = isTelegramTestId;
5
6
  exports.telegramUpdateMessageCoordinates = telegramUpdateMessageCoordinates;
6
7
  exports.createTelegramLongPoll = createTelegramLongPoll;
7
8
  exports.classifyTelegramPersistedApprovalState = classifyTelegramPersistedApprovalState;
@@ -80,6 +81,14 @@ class FileTelegramOffsetStore {
80
81
  exports.FileTelegramOffsetStore = FileTelegramOffsetStore;
81
82
  /** Every update kind the bot asks Telegram for. The authority service, its transport check and the direct poller share it. */
82
83
  exports.TELEGRAM_ALLOWED_UPDATES = ["message", "edited_message", "message_reaction", "callback_query"];
84
+ /**
85
+ * Update and message ids at or above this floor belong to owner turns the Sanctuary root injects for live tests.
86
+ * Telegram's own ids stay far below it, so a test id never collides with a real one or moves a real offset.
87
+ */
88
+ exports.TELEGRAM_TEST_ID_FLOOR = 2 ** 40;
89
+ function isTelegramTestId(value) {
90
+ return Number.isSafeInteger(value) && value >= exports.TELEGRAM_TEST_ID_FLOOR;
91
+ }
83
92
  /** The person, chat and message an update is about: a message, an edit of one, or a reaction to one. */
84
93
  function telegramUpdateMessageCoordinates(update) {
85
94
  const message = update.message ?? update.edited_message;
@@ -682,7 +691,8 @@ function createTelegramLongPoll(options) {
682
691
  if (!update || !Number.isSafeInteger(update.update_id) || (update.update_id < nextUpdateId && !options.settleTransport))
683
692
  continue;
684
693
  options.onBeforeDispatch?.();
685
- const next = Math.max(nextUpdateId, update.update_id + 1);
694
+ // A root-injected test update sits far above Telegram's ids; it must never move the real offset.
695
+ const next = isTelegramTestId(update.update_id) ? nextUpdateId : Math.max(nextUpdateId, update.update_id + 1);
686
696
  const requiresDurableDispatch = Boolean(authorizedCallback(update) || authorizedMessage(update) || unknownMessage(update));
687
697
  const newlyCaptured = requiresDurableDispatch ? (options.inboxStore?.capture(update) ?? true) : true;
688
698
  if (newlyCaptured) {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1137",
3
+ "version": "0.1.0-alpha.1139",
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.1137",
9
+ "version": "0.1.0-alpha.1139",
10
10
  "dependencies": {
11
11
  "@anthropic-ai/sdk": "^0.78.0",
12
12
  "@ouro.bot/friends": "0.1.0-alpha.18",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1137",
3
+ "version": "0.1.0-alpha.1139",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },