@ouro.bot/cli 0.1.0-alpha.1434 → 0.1.0-alpha.1435
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 +6 -0
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/eval/transport/telegram-turn.js +3 -0
- package/dist/senses/telegram-chat-actions.js +5 -2
- package/dist/senses/telegram-client.js +65 -11
- package/dist/senses/telegram-effect-adapter.js +16 -1
- package/dist/senses/telegram.js +268 -30
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/changelog.json
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
|
|
3
3
|
"versions": [
|
|
4
|
+
{
|
|
5
|
+
"version": "0.1.0-alpha.1435",
|
|
6
|
+
"changes": [
|
|
7
|
+
"Every Telegram message the Butler takes in, from the owner or a household Friend, now ends with a recorded outcome: answered, silent or failed. If the Butler's process dies partway through a turn, Telegram sends the message again and the Butler runs it again, but only if nothing had gone out for it yet and it has used fewer than three tries. Otherwise it is recorded as failed, so the person never gets the same reply twice. Replies, reactions, files and approval cards all count as something that went out, and each is noted before it is sent. If that note cannot be written, nothing is sent, and the outbox does not send it later. A message whose turn was cut off before it was recorded runs again unless a reply had already been prepared for it. A message that runs again is logged as being replayed rather than as dropped. Before this, a message whose turn was cut off was dropped with only a warning in the log."
|
|
8
|
+
]
|
|
9
|
+
},
|
|
4
10
|
{
|
|
5
11
|
"version": "0.1.0-alpha.1434",
|
|
6
12
|
"changes": [
|
|
@@ -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.1435</Repository>
|
|
5
5
|
<Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
|
|
6
6
|
<Network>host</Network>
|
|
7
7
|
<Shell>sh</Shell>
|
|
@@ -183,6 +183,9 @@ async function runTelegramTurn(input) {
|
|
|
183
183
|
}
|
|
184
184
|
if (turnError)
|
|
185
185
|
throw turnError;
|
|
186
|
+
// A bundle that already answered this message has its outcome recorded, and the sense does not run it again.
|
|
187
|
+
if (!turn)
|
|
188
|
+
throw new Error("the sense did not run the turn: this bundle already has an outcome for its message, so use a fresh bundle");
|
|
186
189
|
// The answer is every message sent after the model's last tool call: Telegram splits a long one into several.
|
|
187
190
|
const lastCall = timeline.findLastIndex((entry) => entry.kind === "call");
|
|
188
191
|
const result = {
|
|
@@ -11,9 +11,10 @@ function telegramMessageId(value) {
|
|
|
11
11
|
}
|
|
12
12
|
/**
|
|
13
13
|
* Telegram turns here are one-to-one chats, where a reply reads plainly without quoting, so the default posts plainly.
|
|
14
|
-
* The agent can still reply to a specific message.
|
|
14
|
+
* The agent can still reply to a specific message. `beforeSend` runs just before a reaction or file goes out, and
|
|
15
|
+
* nothing is sent when it throws.
|
|
15
16
|
*/
|
|
16
|
-
function createTelegramChatActions(api, chatId, inboundMessageId) {
|
|
17
|
+
function createTelegramChatActions(api, chatId, inboundMessageId, beforeSend = () => undefined) {
|
|
17
18
|
let selection = { target: "current_lane" };
|
|
18
19
|
const replyToMessageId = () => selection.target === "thread" ? telegramMessageId(selection.messageId) : undefined;
|
|
19
20
|
return {
|
|
@@ -22,6 +23,7 @@ function createTelegramChatActions(api, chatId, inboundMessageId) {
|
|
|
22
23
|
const id = telegramMessageId(messageId);
|
|
23
24
|
if (id === undefined)
|
|
24
25
|
return `${messageId} is not a Telegram message id.`;
|
|
26
|
+
beforeSend();
|
|
25
27
|
await api.request("setMessageReaction", { chat_id: chatId, message_id: id, reaction: [{ type: "emoji", emoji }] });
|
|
26
28
|
(0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.telegram_reaction_sent", message: "sent a Telegram reaction", meta: {} });
|
|
27
29
|
return `reacted with ${emoji}`;
|
|
@@ -40,6 +42,7 @@ function createTelegramChatActions(api, chatId, inboundMessageId) {
|
|
|
40
42
|
const file = await (0, chat_file_1.readChatFile)(filePath, telegram_client_1.MAX_TELEGRAM_UPLOAD_BYTES);
|
|
41
43
|
const field = TELEGRAM_PHOTO_TYPES.has(file.contentType) ? "photo" : "document";
|
|
42
44
|
const replyTo = replyToMessageId();
|
|
45
|
+
beforeSend();
|
|
43
46
|
await api.request(field === "photo" ? "sendPhoto" : "sendDocument", {
|
|
44
47
|
chat_id: chatId,
|
|
45
48
|
[field]: { kind: "telegram_input_file", ...file },
|
|
@@ -389,6 +389,17 @@ class FileTelegramUpdateInboxStore {
|
|
|
389
389
|
this.write(state);
|
|
390
390
|
return true;
|
|
391
391
|
}
|
|
392
|
+
reclaimIndeterminate(update) {
|
|
393
|
+
const state = this.read();
|
|
394
|
+
const receipt = updateReceipt(update);
|
|
395
|
+
const index = state.indeterminate.findIndex((candidate) => sameReceipt(candidate, receipt));
|
|
396
|
+
if (index < 0)
|
|
397
|
+
return false;
|
|
398
|
+
state.indeterminate.splice(index, 1);
|
|
399
|
+
state.dispatching.push(receipt);
|
|
400
|
+
this.write(state);
|
|
401
|
+
return true;
|
|
402
|
+
}
|
|
392
403
|
complete(update) {
|
|
393
404
|
const state = this.read();
|
|
394
405
|
const receipt = updateReceipt(update);
|
|
@@ -665,22 +676,55 @@ function createTelegramLongPoll(options) {
|
|
|
665
676
|
},
|
|
666
677
|
});
|
|
667
678
|
};
|
|
679
|
+
const canReplay = Boolean(options.replayIndeterminate && options.inboxStore?.reclaimIndeterminate);
|
|
680
|
+
// Only an update already in the inbox reaches here, so the inbox exists.
|
|
681
|
+
const replayable = async (update) => {
|
|
682
|
+
const inbox = options.inboxStore;
|
|
683
|
+
if (!canReplay || !inbox.loadIndeterminate().some((receipt) => sameReceipt(receipt, updateReceipt(update))))
|
|
684
|
+
return false;
|
|
685
|
+
let reclaimed = false;
|
|
686
|
+
try {
|
|
687
|
+
const decided = await options.replayIndeterminate(update, () => {
|
|
688
|
+
reclaimed = inbox.reclaimIndeterminate(update);
|
|
689
|
+
return reclaimed;
|
|
690
|
+
});
|
|
691
|
+
return decided && reclaimed;
|
|
692
|
+
}
|
|
693
|
+
catch (error) {
|
|
694
|
+
// One update the sense could not decide about must not hold up the rest of the batch.
|
|
695
|
+
(0, runtime_1.emitNervesEvent)({
|
|
696
|
+
level: "error",
|
|
697
|
+
component: "senses",
|
|
698
|
+
event: "telegram.update_replay_failed",
|
|
699
|
+
message: "could not decide whether to run a redelivered Telegram update again; it is not run",
|
|
700
|
+
meta: { error: error instanceof Error ? error.name : "unknown" },
|
|
701
|
+
});
|
|
702
|
+
return false;
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
const warnIndeterminate = (receipt) => {
|
|
706
|
+
(0, runtime_1.emitNervesEvent)({
|
|
707
|
+
level: "warn",
|
|
708
|
+
component: "senses",
|
|
709
|
+
event: "telegram.update_dropped",
|
|
710
|
+
message: "Telegram update dispatch outcome is indeterminate after restart",
|
|
711
|
+
meta: { updateClass: receipt.updateClass, reason: "dispatch_indeterminate", ...options.acceptanceEventMeta?.() },
|
|
712
|
+
});
|
|
713
|
+
options.onDispatchSettled?.();
|
|
714
|
+
options.inboxStore?.acknowledgeIndeterminateWarning(receipt);
|
|
715
|
+
};
|
|
668
716
|
const pollOnce = async (signal) => {
|
|
669
717
|
const requestSignal = signal ? AbortSignal.any([shutdown.signal, signal]) : shutdown.signal;
|
|
670
718
|
if (requestSignal.aborted)
|
|
671
719
|
throw new Error("Telegram long poll stopped");
|
|
672
720
|
options.onBeforeDispatch?.();
|
|
673
721
|
const stranded = options.inboxStore?.quarantineStranded?.() ?? options.inboxStore?.loadIndeterminate() ?? [];
|
|
722
|
+
// A stranded message may be about to run again: Telegram redelivers it in this batch, because the offset
|
|
723
|
+
// never moved past it. Its warning waits for that, so a message that runs again is not reported as dropped.
|
|
724
|
+
const awaitingRedelivery = stranded.filter((receipt) => canReplay && receipt.updateClass === "message");
|
|
674
725
|
for (const indeterminate of stranded) {
|
|
675
|
-
(
|
|
676
|
-
|
|
677
|
-
component: "senses",
|
|
678
|
-
event: "telegram.update_dropped",
|
|
679
|
-
message: "Telegram update dispatch outcome is indeterminate after restart",
|
|
680
|
-
meta: { updateClass: indeterminate.updateClass, reason: "dispatch_indeterminate", ...options.acceptanceEventMeta?.() },
|
|
681
|
-
});
|
|
682
|
-
options.onDispatchSettled?.();
|
|
683
|
-
options.inboxStore?.acknowledgeIndeterminateWarning(indeterminate);
|
|
726
|
+
if (!awaitingRedelivery.includes(indeterminate))
|
|
727
|
+
warnIndeterminate(indeterminate);
|
|
684
728
|
}
|
|
685
729
|
const updates = await options.api.request("getUpdates", {
|
|
686
730
|
offset: nextUpdateId,
|
|
@@ -697,8 +741,16 @@ function createTelegramLongPoll(options) {
|
|
|
697
741
|
const next = isTelegramTestId(update.update_id) ? nextUpdateId : Math.max(nextUpdateId, update.update_id + 1);
|
|
698
742
|
const requiresDurableDispatch = Boolean(authorizedCallback(update) || authorizedMessage(update) || unknownMessage(update));
|
|
699
743
|
const newlyCaptured = requiresDurableDispatch ? (options.inboxStore?.capture(update) ?? true) : true;
|
|
700
|
-
|
|
701
|
-
|
|
744
|
+
const replay = !newlyCaptured && await replayable(update);
|
|
745
|
+
const awaited = awaitingRedelivery.findIndex((receipt) => sameReceipt(receipt, updateReceipt(update)));
|
|
746
|
+
if (awaited >= 0) {
|
|
747
|
+
// A message that runs again left the quarantine, so it has no warning to give unless it is stranded again.
|
|
748
|
+
const [receipt] = awaitingRedelivery.splice(awaited, 1);
|
|
749
|
+
if (!replay)
|
|
750
|
+
warnIndeterminate(receipt);
|
|
751
|
+
}
|
|
752
|
+
if (newlyCaptured || replay) {
|
|
753
|
+
if (newlyCaptured && requiresDurableDispatch && options.inboxStore && !options.inboxStore.claim(update)) {
|
|
702
754
|
options.onDispatchSettled?.();
|
|
703
755
|
const indeterminate = options.inboxStore.loadIndeterminate()
|
|
704
756
|
.some((receipt) => sameReceipt(receipt, updateReceipt(update)));
|
|
@@ -753,6 +805,8 @@ function createTelegramLongPoll(options) {
|
|
|
753
805
|
if (requiresDurableDispatch)
|
|
754
806
|
options.inboxStore?.commit?.(update);
|
|
755
807
|
}
|
|
808
|
+
for (const receipt of awaitingRedelivery)
|
|
809
|
+
warnIndeterminate(receipt);
|
|
756
810
|
return nextUpdateId;
|
|
757
811
|
};
|
|
758
812
|
return {
|
|
@@ -39,6 +39,7 @@ exports.executeTelegramEffect = executeTelegramEffect;
|
|
|
39
39
|
exports.createTelegramAuthorizedEffectExecutor = createTelegramAuthorizedEffectExecutor;
|
|
40
40
|
exports.reconcileTelegramSystemFailsafe = reconcileTelegramSystemFailsafe;
|
|
41
41
|
exports.sweepTelegramSystemFailsafes = sweepTelegramSystemFailsafes;
|
|
42
|
+
exports.abandonTelegramEffect = abandonTelegramEffect;
|
|
42
43
|
exports.recoverTelegramEffectOutbox = recoverTelegramEffectOutbox;
|
|
43
44
|
exports.createTelegramApprovalEffectPort = createTelegramApprovalEffectPort;
|
|
44
45
|
exports.recordTelegramEffectInSession = recordTelegramEffectInSession;
|
|
@@ -596,12 +597,26 @@ async function sweepTelegramSystemFailsafes(input) {
|
|
|
596
597
|
}
|
|
597
598
|
return { inspected: records.length, sent };
|
|
598
599
|
}
|
|
600
|
+
/** How many sends the outbox makes of one part before it stops trying. */
|
|
601
|
+
const TELEGRAM_EFFECT_RECOVERY_ATTEMPTS = 3;
|
|
602
|
+
/** Make sure the outbox never sends what is left of an effect that was stopped before it went out. */
|
|
603
|
+
function abandonTelegramEffect(store, artifact) {
|
|
604
|
+
const now = new Date().toISOString();
|
|
605
|
+
for (const part of artifact.parts) {
|
|
606
|
+
if (part.state !== "prepared")
|
|
607
|
+
continue;
|
|
608
|
+
part.attempts = Math.max(part.attempts ?? 0, TELEGRAM_EFFECT_RECOVERY_ATTEMPTS);
|
|
609
|
+
part.updatedAt = now;
|
|
610
|
+
}
|
|
611
|
+
artifact.updatedAt = now;
|
|
612
|
+
store.write(artifact);
|
|
613
|
+
}
|
|
599
614
|
async function recoverTelegramEffectOutbox(input) {
|
|
600
615
|
const limit = Math.min(Math.max(input.maxArtifacts ?? 20, 1), 100);
|
|
601
616
|
const candidates = input.store.listRecoverable()
|
|
602
617
|
.filter((artifact) => (!input.matches || input.matches(artifact))
|
|
603
618
|
&& !artifact.parts.some((part) => part.state === "attempting" || part.state === "indeterminate")
|
|
604
|
-
&& artifact.parts.some((part) => part.state === "prepared" && (part.attempts ?? 0) <
|
|
619
|
+
&& artifact.parts.some((part) => part.state === "prepared" && (part.attempts ?? 0) < TELEGRAM_EFFECT_RECOVERY_ATTEMPTS))
|
|
605
620
|
.sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id))
|
|
606
621
|
.slice(0, limit);
|
|
607
622
|
let accepted = 0;
|
package/dist/senses/telegram.js
CHANGED
|
@@ -81,6 +81,7 @@ const telegram_identity_key_1 = require("./telegram-identity-key");
|
|
|
81
81
|
var telegram_identity_key_2 = require("./telegram-identity-key");
|
|
82
82
|
Object.defineProperty(exports, "readOrCreateTelegramIdentityKey", { enumerable: true, get: function () { return telegram_identity_key_2.readOrCreateTelegramIdentityKey; } });
|
|
83
83
|
const telegram_client_1 = require("./telegram-client");
|
|
84
|
+
const inbound_journal_1 = require("./inbound-journal");
|
|
84
85
|
const sanctuary_authority_resident_1 = require("./sanctuary-authority-resident");
|
|
85
86
|
const root_host_approval_runtime_1 = require("./root-host-approval-runtime");
|
|
86
87
|
const tools_sanctuary_host_1 = require("../repertoire/tools-sanctuary-host");
|
|
@@ -163,6 +164,21 @@ const TELEGRAM_ACCEPTANCE_AUDIT_EVENTS = new Set([
|
|
|
163
164
|
const telegramAcceptanceAuditOwner = new node_async_hooks_1.AsyncLocalStorage();
|
|
164
165
|
const telegramAcceptanceAuditScenario = new node_async_hooks_1.AsyncLocalStorage();
|
|
165
166
|
const telegramAcceptanceAuditExplicitCommit = new node_async_hooks_1.AsyncLocalStorage();
|
|
167
|
+
/** The opaque reference a household Friend's message is known by in its session and its delivery keys. */
|
|
168
|
+
function telegramHouseholdReference(identityKey, botId, userId, updateId, messageId) {
|
|
169
|
+
return `telegram-inbound:${(0, node_crypto_1.createHmac)("sha256", identityKey).update(`${botId}\0${userId}\0${updateId}\0${messageId}`).digest("hex")}`;
|
|
170
|
+
}
|
|
171
|
+
const telegramInboundTurn = new node_async_hooks_1.AsyncLocalStorage();
|
|
172
|
+
/** Telegram keeps an update it has not been told was handled for at most a day (https://core.telegram.org/bots/api#getting-updates). */
|
|
173
|
+
const TELEGRAM_REDELIVERY_WINDOW_MS = 24 * 60 * 60_000;
|
|
174
|
+
/** Why a message a stopped process left must not run again, or null when it may. */
|
|
175
|
+
function telegramReplayRefusal(entry) {
|
|
176
|
+
if (entry.spoke)
|
|
177
|
+
return "the turn stopped after a reply went out, so it is not run again";
|
|
178
|
+
if (entry.attempts >= inbound_journal_1.MAX_INBOUND_ATTEMPTS)
|
|
179
|
+
return `the turn did not finish in ${entry.attempts} attempts`;
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
166
182
|
const telegramAcceptanceAudits = new Map();
|
|
167
183
|
const TELEGRAM_TURN_RECEIPT_DOMAINS = {
|
|
168
184
|
"sanctuary-telegram-turn-receipt-v3": "ouroboros.telegram.turn-receipt.v3",
|
|
@@ -831,13 +847,83 @@ function createTelegramSenseApp(options) {
|
|
|
831
847
|
return { allowed: true, receiptId: `configured-owner:${subject}`, expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(), transport: { chatId: authorizedChatId } };
|
|
832
848
|
};
|
|
833
849
|
const authorizeEffect = options.authorizeEffect ?? defaultEffectAuthorization;
|
|
850
|
+
let inboundJournal;
|
|
851
|
+
const getInboundJournal = () => {
|
|
852
|
+
inboundJournal ??= (0, inbound_journal_1.openInboundJournal)(agentRoot, "telegram");
|
|
853
|
+
return inboundJournal;
|
|
854
|
+
};
|
|
855
|
+
const inboundJournalFailed = (error) => {
|
|
856
|
+
(0, runtime_1.emitNervesEvent)({
|
|
857
|
+
level: "error",
|
|
858
|
+
component: "senses",
|
|
859
|
+
event: "senses.telegram_inbound_record_failed",
|
|
860
|
+
message: "could not use the Telegram outcome records; turns still run, but a crash during one goes unrecorded",
|
|
861
|
+
meta: { agentName: options.agentName, error: redactTelegramPrivateValues(error, transportPrivateValues) },
|
|
862
|
+
});
|
|
863
|
+
};
|
|
864
|
+
const inboundIdFor = (updateId) => `telegram-update:${(0, node_crypto_1.createHmac)("sha256", identityKey).update(`ouroboros.telegram.inbound-journal.v1\0${subject}\0${updateId}`).digest("hex")}`;
|
|
865
|
+
const settleInbound = (id, outcome, detail) => {
|
|
866
|
+
try {
|
|
867
|
+
getInboundJournal().settle(id, outcome, detail);
|
|
868
|
+
}
|
|
869
|
+
catch (error) {
|
|
870
|
+
inboundJournalFailed(error);
|
|
871
|
+
}
|
|
872
|
+
};
|
|
873
|
+
const householdInboundIdFor = (reference) => `telegram-household:${(0, node_crypto_1.createHash)("sha256").update(reference).digest("hex")}`;
|
|
874
|
+
/**
|
|
875
|
+
* Note, inside a turn, that something is about to go out for its message, before it is sent. When the note
|
|
876
|
+
* cannot be written this throws and nothing is sent, so a replay can never repeat what the person received.
|
|
877
|
+
*/
|
|
878
|
+
const noteTurnSpoke = () => {
|
|
879
|
+
const turn = telegramInboundTurn.getStore();
|
|
880
|
+
if (!turn)
|
|
881
|
+
return;
|
|
882
|
+
if (turn.id)
|
|
883
|
+
getInboundJournal().markSpoke(turn.id);
|
|
884
|
+
turn.spoke = true;
|
|
885
|
+
};
|
|
886
|
+
/**
|
|
887
|
+
* Note that something is about to go out for a message. Inside a turn that is the turn's message. Outside one,
|
|
888
|
+
* a delivery key names the message, which covers a reply the outbox sends after a crash.
|
|
889
|
+
*/
|
|
890
|
+
const noteInboundSpoke = (idempotencyKey) => {
|
|
891
|
+
if (telegramInboundTurn.getStore()) {
|
|
892
|
+
noteTurnSpoke();
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
const owner = idempotencyKey.startsWith(`turn:${subject}:`) ? idempotencyKey.slice(`turn:${subject}:`.length).split(":")[0] : null;
|
|
896
|
+
const household = /^relationship-turn:(telegram-inbound:[0-9a-f]{64}):/u.exec(idempotencyKey)?.[1];
|
|
897
|
+
if (owner === null && !household)
|
|
898
|
+
return;
|
|
899
|
+
try {
|
|
900
|
+
getInboundJournal().markSpoke(owner !== null ? inboundIdFor(owner) : householdInboundIdFor(household));
|
|
901
|
+
}
|
|
902
|
+
catch (error) {
|
|
903
|
+
inboundJournalFailed(error);
|
|
904
|
+
}
|
|
905
|
+
};
|
|
906
|
+
const authorizeAndNoteSpoke = async (input) => {
|
|
907
|
+
const authorization = await authorizeEffect(input);
|
|
908
|
+
if (input.phase !== "send" || !authorization.allowed)
|
|
909
|
+
return authorization;
|
|
910
|
+
try {
|
|
911
|
+
noteInboundSpoke(input.idempotencyKey);
|
|
912
|
+
}
|
|
913
|
+
catch (error) {
|
|
914
|
+
// The send does not happen, so the outbox must not send it later for a message already recorded failed.
|
|
915
|
+
(0, telegram_effect_adapter_1.abandonTelegramEffect)(getEffectJournal(), input.artifact);
|
|
916
|
+
throw error;
|
|
917
|
+
}
|
|
918
|
+
return authorization;
|
|
919
|
+
};
|
|
834
920
|
let recordAcceptedEffects;
|
|
835
921
|
const configuredOwnerTarget = () => ({ kind: "approved_relationship", friendId: configuredOwnerFriendId, sessionKey: configuredOwnerSessionKey });
|
|
836
922
|
const fallbackText = (text) => `${telegram_owner_route_1.OWNER_ROUTE_FALLBACK_PREFIX}\n\n${text}`;
|
|
837
923
|
const executeOnTelegram = (0, telegram_effect_adapter_1.createTelegramAuthorizedEffectExecutor)({
|
|
838
924
|
store: getEffectJournal,
|
|
839
925
|
api,
|
|
840
|
-
authorize:
|
|
926
|
+
authorize: authorizeAndNoteSpoke,
|
|
841
927
|
barrier: acceptanceAuditBarrier,
|
|
842
928
|
});
|
|
843
929
|
/**
|
|
@@ -940,8 +1026,22 @@ function createTelegramSenseApp(options) {
|
|
|
940
1026
|
const port = authorityTransport?.hostApproval;
|
|
941
1027
|
if (useSanctuaryRuntime && port?.pins.expectedBotId === botId
|
|
942
1028
|
&& port.pins.expectedOwnerUserId === authorizedUserId && port.pins.expectedOwnerChatId === authorizedChatId) {
|
|
1029
|
+
// The root host sends the approval card when a proposal is registered, so that counts as a send for the message.
|
|
1030
|
+
const notingPort = {
|
|
1031
|
+
pins: port.pins,
|
|
1032
|
+
refresh: () => port.refresh(),
|
|
1033
|
+
isHealthy: () => port.isHealthy(),
|
|
1034
|
+
acceptsObservation: (metadata) => port.acceptsObservation(metadata),
|
|
1035
|
+
register: async (proposal) => {
|
|
1036
|
+
noteTurnSpoke();
|
|
1037
|
+
return port.register(proposal);
|
|
1038
|
+
},
|
|
1039
|
+
status: (registration) => port.status(registration),
|
|
1040
|
+
execute: (correlation) => port.execute(correlation),
|
|
1041
|
+
callbackForUpdate: (update) => port.callbackForUpdate(update),
|
|
1042
|
+
};
|
|
943
1043
|
rootHostRuntime = (0, root_host_approval_runtime_1.createRootHostApprovalRuntime)({
|
|
944
|
-
agentRoot, port, effectBarrier: acceptanceAuditBarrier, approvalCoordinatorFactory,
|
|
1044
|
+
agentRoot, port: notingPort, effectBarrier: acceptanceAuditBarrier, approvalCoordinatorFactory,
|
|
945
1045
|
resolveContext: async (binding) => {
|
|
946
1046
|
const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, configuredOwnerFriendId, "telegram", configuredOwnerSessionKey, agentRoot);
|
|
947
1047
|
if (binding.agentRoot !== agentRoot || binding.friendId !== configuredOwnerFriendId
|
|
@@ -1398,7 +1498,7 @@ function createTelegramSenseApp(options) {
|
|
|
1398
1498
|
const dispatchResolvedRelationshipTurn = async (input) => {
|
|
1399
1499
|
const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, input.friendId, "telegram", input.sessionKey, agentRoot);
|
|
1400
1500
|
const effects = [];
|
|
1401
|
-
const chat = (0, telegram_chat_actions_1.createTelegramChatActions)(api, input.chatId, input.messageId);
|
|
1501
|
+
const chat = (0, telegram_chat_actions_1.createTelegramChatActions)(api, input.chatId, input.messageId, noteTurnSpoke);
|
|
1402
1502
|
let ordinal = 0;
|
|
1403
1503
|
const deliver = async (text, terminalReturn = false) => {
|
|
1404
1504
|
const obligation = terminalReturn ? (0, obligations_1.findPendingObligationForRequest)(agentRoot, {
|
|
@@ -1519,8 +1619,10 @@ function createTelegramSenseApp(options) {
|
|
|
1519
1619
|
if (!event || typeof event.content !== "string")
|
|
1520
1620
|
throw new Error("Telegram admitted work ingress is unavailable");
|
|
1521
1621
|
const record = admissionStore.read(input.admissionId);
|
|
1522
|
-
|
|
1523
|
-
|
|
1622
|
+
const text = event.content;
|
|
1623
|
+
// The newly admitted Friend's first turn answers their message, not the owner's decision that let it run.
|
|
1624
|
+
await telegramInboundTurn.exit(() => dispatchResolvedRelationshipTurn({ friendId: input.friendId, sessionKey: input.sessionKey, requestId: input.admissionId,
|
|
1625
|
+
eventId: input.eventId, reference: input.reference, text, userId: record.userId, chatId: record.chatId, orientation: input.orientation }));
|
|
1524
1626
|
inboxStore.completeAdmittedWork(input.admissionId);
|
|
1525
1627
|
return "settled";
|
|
1526
1628
|
}
|
|
@@ -1613,8 +1715,11 @@ function createTelegramSenseApp(options) {
|
|
|
1613
1715
|
const bufferedGroundedDeliveries = [];
|
|
1614
1716
|
const turnEffects = [];
|
|
1615
1717
|
let deliveryOrdinal = 0;
|
|
1616
|
-
|
|
1617
|
-
await
|
|
1718
|
+
// What these send belongs to other turns and notices, not to this message.
|
|
1719
|
+
await telegramInboundTurn.exit(async () => {
|
|
1720
|
+
await recoverEffectOutbox();
|
|
1721
|
+
await releaseHeldNoticesQuietly();
|
|
1722
|
+
});
|
|
1618
1723
|
let ingressRelations = { replyToEventId: null, threadRootEventId: null, references: [inboundReference] };
|
|
1619
1724
|
if (message.replyToMessageId && /^[1-9][0-9]*$/u.test(message.replyToMessageId)) {
|
|
1620
1725
|
const replyMessageId = Number(message.replyToMessageId);
|
|
@@ -1638,7 +1743,7 @@ function createTelegramSenseApp(options) {
|
|
|
1638
1743
|
})
|
|
1639
1744
|
: null;
|
|
1640
1745
|
const fullVisibility = createFullVisibilityProgress();
|
|
1641
|
-
const chat = (0, telegram_chat_actions_1.createTelegramChatActions)(api, message.chatId, message.messageId);
|
|
1746
|
+
const chat = (0, telegram_chat_actions_1.createTelegramChatActions)(api, message.chatId, message.messageId, noteTurnSpoke);
|
|
1642
1747
|
const collected = await collectToolReceipts(() => runTurn({
|
|
1643
1748
|
agentName: options.agentName,
|
|
1644
1749
|
channel: "telegram",
|
|
@@ -1741,6 +1846,8 @@ function createTelegramSenseApp(options) {
|
|
|
1741
1846
|
} : { error: redactTelegramPrivateValues(error, [...transportPrivateValues, String(message.updateId), message.messageId]) }),
|
|
1742
1847
|
}, Math.max(Date.now(), lifecycleStartedAt + 1)),
|
|
1743
1848
|
});
|
|
1849
|
+
// Every owner message runs inside its inbound turn.
|
|
1850
|
+
telegramInboundTurn.getStore().failure = `the turn failed (${errorCategory})`;
|
|
1744
1851
|
const fallback = "I couldn't complete that turn. The failure was recorded; please try again.";
|
|
1745
1852
|
if (deliveredMessageIds.length === 0)
|
|
1746
1853
|
turnEffects.push(await deliverButlerEffect(fallback, `turn:${subject}:${message.updateId}:fallback`, undefined, (messageId, chunk) => { deliveredMessageIds.push(messageId); deliveredChunks.push(chunk); }, exactDownloadCreditQuestion));
|
|
@@ -1797,8 +1904,132 @@ function createTelegramSenseApp(options) {
|
|
|
1797
1904
|
const named = { ...interaction, target: { ...interaction.target, text: sent.text, fromAgent: true } };
|
|
1798
1905
|
return { ...message, interaction: named, text: (0, chat_interaction_1.renderChatInteraction)(named) };
|
|
1799
1906
|
};
|
|
1907
|
+
/** Write a message's entry before its turn, or null when it must not run: it has an outcome, or a stopped turn left it unsafe to run again. */
|
|
1908
|
+
const beginInbound = (id) => {
|
|
1909
|
+
let entry;
|
|
1910
|
+
try {
|
|
1911
|
+
entry = getInboundJournal().record(id, { updateClass: "message" });
|
|
1912
|
+
}
|
|
1913
|
+
catch (error) {
|
|
1914
|
+
inboundJournalFailed(error);
|
|
1915
|
+
return { id: null, spoke: false, failure: null };
|
|
1916
|
+
}
|
|
1917
|
+
if (!entry)
|
|
1918
|
+
return null;
|
|
1919
|
+
const refusal = telegramReplayRefusal(entry);
|
|
1920
|
+
if (refusal) {
|
|
1921
|
+
settleInbound(id, "failed", refusal);
|
|
1922
|
+
return null;
|
|
1923
|
+
}
|
|
1924
|
+
getInboundJournal().beginAttempt(id);
|
|
1925
|
+
return { id, spoke: false, failure: null };
|
|
1926
|
+
};
|
|
1927
|
+
/** Run a message's turn and record its one outcome. A turn that throws is recorded as failed and the error goes on. */
|
|
1928
|
+
const runInboundTurn = async (turn, body) => {
|
|
1929
|
+
await telegramInboundTurn.run(turn, async () => {
|
|
1930
|
+
try {
|
|
1931
|
+
await body();
|
|
1932
|
+
}
|
|
1933
|
+
catch (error) {
|
|
1934
|
+
const stopped = `the turn stopped with an error (${error instanceof Error ? error.name : "unknown"})`;
|
|
1935
|
+
if (turn.id)
|
|
1936
|
+
settleInbound(turn.id, "failed", turn.spoke ? `${stopped} after a reply may have gone out` : `${stopped}, and no reply reached them`);
|
|
1937
|
+
throw error;
|
|
1938
|
+
}
|
|
1939
|
+
if (turn.id)
|
|
1940
|
+
settleInbound(turn.id, turn.failure ? "failed" : turn.spoke ? "answered" : "silent", turn.failure ?? undefined);
|
|
1941
|
+
});
|
|
1942
|
+
};
|
|
1943
|
+
/** Record a message a stopped process left as failed, writing its entry first when it has none. */
|
|
1944
|
+
const failInbound = (id, reason) => {
|
|
1945
|
+
try {
|
|
1946
|
+
getInboundJournal().record(id, { updateClass: "message" });
|
|
1947
|
+
}
|
|
1948
|
+
catch (error) {
|
|
1949
|
+
inboundJournalFailed(error);
|
|
1950
|
+
return;
|
|
1951
|
+
}
|
|
1952
|
+
settleInbound(id, "failed", reason);
|
|
1953
|
+
};
|
|
1954
|
+
/**
|
|
1955
|
+
* Telegram redelivered a message a stopped process left. It runs again only when nothing went out for it and it
|
|
1956
|
+
* has tries left; otherwise it is recorded as failed, so no message is left pending. A household Friend's message is
|
|
1957
|
+
* known by its reference. Callbacks and strangers' messages never get an entry and keep their own recovery.
|
|
1958
|
+
*/
|
|
1959
|
+
const replayIndeterminate = async (update, reclaim) => {
|
|
1960
|
+
const coordinates = (0, telegram_client_1.telegramUpdateMessageCoordinates)(update);
|
|
1961
|
+
if (!coordinates || coordinates.chatType !== "private")
|
|
1962
|
+
return false;
|
|
1963
|
+
const owner = coordinates.userId === authorizedUserId && coordinates.chatId === authorizedChatId;
|
|
1964
|
+
// Only a new message reaches a household Friend's turn; their edits and reactions are not run.
|
|
1965
|
+
if (!owner && (!update.message || !botId || !options.admission))
|
|
1966
|
+
return false;
|
|
1967
|
+
const reference = owner ? null : telegramHouseholdReference(identityKey, botId, coordinates.userId, update.update_id, coordinates.messageId);
|
|
1968
|
+
const id = reference ? householdInboundIdFor(reference) : inboundIdFor(update.update_id);
|
|
1969
|
+
let entry = null;
|
|
1970
|
+
try {
|
|
1971
|
+
entry = getInboundJournal().get(id);
|
|
1972
|
+
if (!entry && (0, inbound_journal_1.readInboundOutcome)(agentRoot, "telegram", id))
|
|
1973
|
+
return false;
|
|
1974
|
+
if (reference && !await options.admission.resolveApprovedFriend({ botId: botId, userId: coordinates.userId, chatId: coordinates.chatId })) {
|
|
1975
|
+
if (entry)
|
|
1976
|
+
failInbound(id, "they are no longer a household Friend, so it is not run again");
|
|
1977
|
+
return false;
|
|
1978
|
+
}
|
|
1979
|
+
// With no entry the turn never started, or its entry could not be written; a reply it prepared shows which.
|
|
1980
|
+
const preparedKeys = reference ? [`relationship-turn:${reference}:delivery:0`]
|
|
1981
|
+
: [`turn:${subject}:${update.update_id}:delivery:0`, `turn:${subject}:${update.update_id}:fallback`];
|
|
1982
|
+
const refusal = entry ? telegramReplayRefusal(entry)
|
|
1983
|
+
: preparedKeys.some((key) => getEffectJournal().readByIdempotencyKey(key))
|
|
1984
|
+
? "a reply was prepared before it stopped, but its record could not be written, so it is not run again"
|
|
1985
|
+
: null;
|
|
1986
|
+
if (refusal) {
|
|
1987
|
+
failInbound(id, refusal);
|
|
1988
|
+
return false;
|
|
1989
|
+
}
|
|
1990
|
+
if (!reclaim()) {
|
|
1991
|
+
failInbound(id, "it could not be taken back from the update inbox to run again");
|
|
1992
|
+
return false;
|
|
1993
|
+
}
|
|
1994
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1995
|
+
level: "warn",
|
|
1996
|
+
component: "senses",
|
|
1997
|
+
event: "senses.telegram_inbound_replaying",
|
|
1998
|
+
message: "running a Telegram message again: its turn stopped before anything went out",
|
|
1999
|
+
meta: { agentName: options.agentName, attempts: entry?.attempts ?? 0 },
|
|
2000
|
+
});
|
|
2001
|
+
return true;
|
|
2002
|
+
}
|
|
2003
|
+
catch (error) {
|
|
2004
|
+
// A message with no entry from someone who is not the owner may be a stranger's, which never gets a record.
|
|
2005
|
+
if (entry || owner)
|
|
2006
|
+
failInbound(id, `deciding whether to run it again failed (${error instanceof Error ? error.name : "unknown"})`);
|
|
2007
|
+
else
|
|
2008
|
+
inboundJournalFailed(error);
|
|
2009
|
+
return false;
|
|
2010
|
+
}
|
|
2011
|
+
};
|
|
2012
|
+
/** A message whose update Telegram no longer redelivers can never be answered now, so it is recorded as failed. */
|
|
2013
|
+
const failInboundsPastRedelivery = () => {
|
|
2014
|
+
try {
|
|
2015
|
+
const cutoff = Date.now() - TELEGRAM_REDELIVERY_WINDOW_MS;
|
|
2016
|
+
for (const entry of getInboundJournal().pending()) {
|
|
2017
|
+
if (Date.parse(entry.receivedAt) < cutoff)
|
|
2018
|
+
settleInbound(entry.id, "failed", "Telegram stopped redelivering it after a day, so it was never answered");
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
catch (error) {
|
|
2022
|
+
inboundJournalFailed(error);
|
|
2023
|
+
}
|
|
2024
|
+
};
|
|
1800
2025
|
const onMessage = (inbound) => runWithAcceptanceAuditOwner(async () => {
|
|
1801
2026
|
const message = nameReactionTarget(inbound);
|
|
2027
|
+
const turn = beginInbound(inboundIdFor(message.updateId));
|
|
2028
|
+
if (!turn)
|
|
2029
|
+
return;
|
|
2030
|
+
await runInboundTurn(turn, () => handleAuthorizedMessage(message));
|
|
2031
|
+
});
|
|
2032
|
+
const handleAuthorizedMessage = async (message) => {
|
|
1802
2033
|
const ownerDecision = !message.interaction && !message.attachments?.length && !message.attachmentNotices?.length ? admissionController?.parseOwnerDecision({
|
|
1803
2034
|
text: message.text,
|
|
1804
2035
|
...(message.replyToMessageId ? { replyToMessageId: Number(message.replyToMessageId) } : {}),
|
|
@@ -1820,35 +2051,40 @@ function createTelegramSenseApp(options) {
|
|
|
1820
2051
|
// it degrades to silence instead of failing, and message-delivery assertions
|
|
1821
2052
|
// stay about messages.
|
|
1822
2053
|
await withTelegramTypingIndicator(() => sendTypingIndicator(message.chatId), () => onMessageBody(message));
|
|
1823
|
-
}
|
|
2054
|
+
};
|
|
1824
2055
|
const onUnknownMessage = admissionController && options.admission ? async (message) => {
|
|
1825
2056
|
const approved = await options.admission.resolveApprovedFriend(message);
|
|
1826
2057
|
if (!approved) {
|
|
1827
2058
|
await admissionController.handleUnknown(message);
|
|
1828
2059
|
return;
|
|
1829
2060
|
}
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
2061
|
+
const reference = telegramHouseholdReference(identityKey, message.botId, message.userId, message.updateId, message.messageId);
|
|
2062
|
+
const turn = beginInbound(householdInboundIdFor(reference));
|
|
2063
|
+
if (!turn)
|
|
2064
|
+
return;
|
|
2065
|
+
await runInboundTurn(turn, async () => {
|
|
2066
|
+
// Existing household Friends need a root-observed communication binding after gateway migration.
|
|
2067
|
+
await authorityTransport?.admitChat({
|
|
2068
|
+
admissionId: (0, node_crypto_1.createHash)("sha256").update(`telegram-communication-v1\0${message.botId}\0${message.userId}\0${message.chatId}`).digest("hex").slice(0, 20),
|
|
2069
|
+
updateId: message.updateId,
|
|
2070
|
+
userId: message.userId,
|
|
2071
|
+
chatId: message.chatId,
|
|
2072
|
+
});
|
|
2073
|
+
const hydrated = await hydrateAuthorizedMessage({
|
|
2074
|
+
updateId: message.updateId,
|
|
2075
|
+
messageId: String(message.messageId),
|
|
2076
|
+
userId: message.userId,
|
|
2077
|
+
chatId: message.chatId,
|
|
2078
|
+
text: message.text,
|
|
2079
|
+
attachments: message.attachments,
|
|
2080
|
+
attachmentNotices: message.attachmentNotices,
|
|
2081
|
+
});
|
|
2082
|
+
const sessionKey = `telegram:${message.botId}:${message.userId}`;
|
|
2083
|
+
const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, approved.friendId, "telegram", sessionKey, agentRoot);
|
|
2084
|
+
const receipt = await (0, telegram_effect_adapter_1.recordTelegramEffectsInSession)({ store: getEffectJournal(), sessionPath, artifacts: [], inbound: { text: hydrated.text, reference, attachmentIds: hydrated.attachmentIds } });
|
|
2085
|
+
await dispatchResolvedRelationshipTurn({ friendId: approved.friendId, sessionKey, requestId: reference, eventId: receipt.eventId,
|
|
2086
|
+
reference, text: hydrated.text, attachmentIds: hydrated.attachmentIds, userId: message.userId, chatId: message.chatId, messageId: String(message.messageId) });
|
|
1845
2087
|
});
|
|
1846
|
-
const sessionKey = `telegram:${message.botId}:${message.userId}`;
|
|
1847
|
-
const reference = `telegram-inbound:${(0, node_crypto_1.createHmac)("sha256", identityKey).update(`${message.botId}\0${message.userId}\0${message.updateId}\0${message.messageId}`).digest("hex")}`;
|
|
1848
|
-
const sessionPath = (0, shared_turn_1.getSenseSessionPath)(options.agentName, approved.friendId, "telegram", sessionKey, agentRoot);
|
|
1849
|
-
const receipt = await (0, telegram_effect_adapter_1.recordTelegramEffectsInSession)({ store: getEffectJournal(), sessionPath, artifacts: [], inbound: { text: hydrated.text, reference, attachmentIds: hydrated.attachmentIds } });
|
|
1850
|
-
await dispatchResolvedRelationshipTurn({ friendId: approved.friendId, sessionKey, requestId: reference, eventId: receipt.eventId,
|
|
1851
|
-
reference, text: hydrated.text, attachmentIds: hydrated.attachmentIds, userId: message.userId, chatId: message.chatId, messageId: String(message.messageId) });
|
|
1852
2088
|
} : undefined;
|
|
1853
2089
|
const onUpdate = async (update) => {
|
|
1854
2090
|
const callback = update.callback_query;
|
|
@@ -1887,6 +2123,7 @@ function createTelegramSenseApp(options) {
|
|
|
1887
2123
|
inboxStore,
|
|
1888
2124
|
onMessage,
|
|
1889
2125
|
onUpdate,
|
|
2126
|
+
replayIndeterminate,
|
|
1890
2127
|
...(authorityTransport ? {
|
|
1891
2128
|
settleTransport: authorityTransport.settleTransport,
|
|
1892
2129
|
transportMetadata: authorityTransport.metadataForUpdate,
|
|
@@ -1954,6 +2191,7 @@ function createTelegramSenseApp(options) {
|
|
|
1954
2191
|
inboxStore.quarantineStrandedAdmittedWork?.();
|
|
1955
2192
|
await runWithAcceptanceAuditOwner(async () => { await admissionController?.recover(); });
|
|
1956
2193
|
await runWithAcceptanceAuditOwner(recoverEffectOutbox);
|
|
2194
|
+
failInboundsPastRedelivery();
|
|
1957
2195
|
await runWithAcceptanceAuditOwner(reconcileSystemFailsafes);
|
|
1958
2196
|
try {
|
|
1959
2197
|
await runWithAcceptanceAuditOwner(async () => { await toolContext?.sanctuary?.recoverRoutineActions?.(); });
|
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.1435",
|
|
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.1435",
|
|
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.1435",
|
|
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": {
|