Files
openclaw/extensions/telegram/src/sent-message-cache.legacy-state.ts
T
Peter Steinberger 081a565cba perf(doctor): restore telegram doctor repairs dropped on source-run hosts (#120954)
* perf(doctor): keep telegram doctor enumeration off the runtime graph

Telegram's built doctor artifact reached execa through dist chunking, so a
source-run host (pnpm dev, tsx CLI, vitest) could not require it and silently
dropped all 9 telegram legacy config rules plus its state migration. The
artifact also pulled telegram's runtime stores, making it a 674-chunk outlier
that dominated doctor enumeration.

Root cause: `src/token.ts` took the broad `plugin-sdk/provider-auth` barrel for
`resolveDefaultSecretProviderAlias`, dragging the auth-profile store, provider
runtime, and plugin install graph (execa, kysely, commander) into the closure.
The alias now has a narrow `plugin-sdk/secret-provider-alias` leaf, and
provider-auth re-exports it so its runtime surface is unchanged.

Thread-binding, sent-message, and sticker-cache row shapes, keys, and legacy
sidecar readers move to `*.legacy-state.ts` leaves. The doctor closure keeps
the rows and drops the ACP, session-binding, send, logger, and plugin-runtime
graphs the stores also load.

The postbuild control-plane verifier only required each artifact in a plain
Node child, the one host where these graphs resolve fine, so it proved nothing
about the invariant that broke. It now also walks each built doctor artifact's
static import closure and fails when it reaches the process-spawn graph, which
is the dist-level analogue of the source closure guard.

Guard rules added for provider-auth, acp-runtime, and conversation-runtime; the
telegram boundary test became a real closure assertion instead of a string grep.

* fix(doctor): drop dead export surface from the telegram legacy-state split

Knip and oxlint caught leftovers from the split: the leaves exported helpers
only they use, the store modules re-exported constants nobody imports from them
anymore, and thread-bindings kept a `testing` barrel whose last production
caller was the migration path that now reads the leaf directly. Tests import the
constants from the leaf that owns them, and the reset helper directly.

The closure gate's failure message still interpolated a `host` field left over
from a probe-host approach that was reverted before commit; the existing verifier
test caught it. The gate now has its own coverage: a transitive chunk edge to a
forbidden dependency is reported, while dynamic imports and non-doctor contract
surfaces are not.

* fix(doctor): adopt the upstream telegram thread-binding store split

`main` landed an equivalent thread-binding leaf as `thread-bindings-store.ts`
while this branch was open, so the branch-local `thread-bindings.legacy-state.ts`
is dropped rather than kept as a second path for the same rows.

`state-migrations.ts` now reaches token.js through the lazy import `main` added,
so `token.ts` is no longer in the doctor closure at all. The narrow
`secret-provider-alias` leaf still matters: telegram's contract-api closure
reaches `provider-auth` through `token.ts` on current `main`, which is the same
execa/kysely/commander graph, so the barrel is repaired at its source instead of
being deferred a second time.

* fix(scripts): type the built doctor closure gate for the TypeScript migration

The gate was authored against the `.mjs` script and landed in the `.mts` file
`main` migrated to, so its parameters were implicitly `any` and `check:test-types`
failed. Adds the explicit signatures plus the violation type.

Regenerates the plugin-sdk API baseline: `provider-auth` re-exports the default
secret-provider alias from the new leaf, so its module hash moves while its
runtime export surface stays identical.
2026-08-09 08:50:03 -07:00

113 lines
4.2 KiB
TypeScript

// Telegram sent-message cache row shape, keys, and legacy sidecar reader.
//
// Split from `sent-message-cache.ts`, which also value-loads the plugin runtime
// slot and the logger graph. Doctor enumeration cold-loads this module to plan the
// legacy-state import, so it stays a leaf.
import { createHash } from "node:crypto";
import fs from "node:fs";
import { resolveDefaultAgentId } from "openclaw/plugin-sdk/agent-scope-runtime";
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
import { resolveStorePath } from "openclaw/plugin-sdk/session-store-paths";
export const TTL_MS = 24 * 60 * 60 * 1000;
export const TELEGRAM_SENT_MESSAGE_CACHE_NAMESPACE = "telegram.sent-messages";
export const TELEGRAM_SENT_MESSAGE_CACHE_MAX_ENTRIES = 10_000;
export type PersistedSentMessage = {
scopeKey: string;
chatId: string;
messageId: string;
timestamp: number;
};
export type SentMessageConfig = Pick<OpenClawConfig, "agents" | "session">;
function resolveSentMessageAgentId(cfg?: SentMessageConfig, agentId?: string): string {
return agentId?.trim() || (cfg?.agents ? resolveDefaultAgentId(cfg as OpenClawConfig) : "main");
}
function sentMessageScopeKeyForStorePath(storePath: string): string {
return createHash("sha256").update(storePath, "utf8").digest("hex").slice(0, 24);
}
export function resolveSentMessageScopeKey(cfg?: SentMessageConfig, agentId?: string): string {
// This 24-hour cache follows the current agent owner. Do not revive a prior owner's
// transient bucket when the configured default changes.
return sentMessageScopeKeyForStorePath(
resolveStorePath(cfg?.session?.store, {
agentId: resolveSentMessageAgentId(cfg, agentId),
}),
);
}
export function sentMessageEntryKey(scopeKey: string, chatId: string, messageId: string): string {
return createHash("sha256")
.update(`${scopeKey}\0${chatId}\0${messageId}`, "utf8")
.digest("hex")
.slice(0, 32);
}
function resolveSentMessageStorePath(cfg?: SentMessageConfig, agentId?: string): string {
return `${resolveStorePath(cfg?.session?.store, {
agentId: resolveSentMessageAgentId(cfg, agentId),
})}.telegram-sent-messages.json`;
}
// A torn or foreign sidecar yields no entries, exactly as a missing file does; the
// runtime store is authoritative once doctor has migrated.
function readLegacySentMessages(filePath: string): Map<string, Map<string, number>> {
const store = new Map<string, Map<string, number>>();
let parsed: Record<string, Record<string, number>>;
try {
parsed = JSON.parse(fs.readFileSync(filePath, "utf-8")) as Record<
string,
Record<string, number>
>;
} catch {
return store;
}
const now = Date.now();
for (const [chatId, entry] of Object.entries(parsed)) {
const messages = new Map<string, number>();
for (const [messageId, timestamp] of Object.entries(entry)) {
if (typeof timestamp === "number" && Number.isFinite(timestamp) && now - timestamp < TTL_MS) {
messages.set(messageId, timestamp);
}
}
if (messages.size > 0) {
store.set(chatId, messages);
}
}
return store;
}
export function listTelegramLegacySentMessageCacheEntries(params: {
cfg?: SentMessageConfig;
agentId?: string;
persistedPath?: string;
targetStorePath?: string;
}): Array<{ key: string; value: PersistedSentMessage; ttlMs?: number; timestamp?: number }> {
const scopeKey = params.targetStorePath
? sentMessageScopeKeyForStorePath(params.targetStorePath)
: resolveSentMessageScopeKey(params.cfg, params.agentId);
const filePath = params.persistedPath ?? resolveSentMessageStorePath(params.cfg, params.agentId);
const legacy = fs.existsSync(filePath)
? readLegacySentMessages(filePath)
: new Map<string, Map<string, number>>();
return [...legacy.entries()].flatMap(([chatId, messages]) =>
[...messages.entries()].flatMap(([messageId, timestamp]) => {
const ttlMs = TTL_MS - Math.max(0, Date.now() - timestamp);
return ttlMs > 0
? [
{
key: sentMessageEntryKey(scopeKey, chatId, messageId),
value: { scopeKey, chatId, messageId, timestamp },
ttlMs,
timestamp,
},
]
: [];
}),
);
}