Files
openclaw/extensions/active-memory/transcript.ts
Peter Steinberger fa03d9b913 refactor: consolidate coercion helpers (#121366)
* refactor: consolidate coercion helpers

* fix: remove duplicate coercion imports

* fix: preserve serialized coercion guard

* chore: ratchet coercion helper carve-outs

* fix(test): keep gauntlet subprocess startup lean

* fix: preserve imported session timestamp semantics

* fix: preserve catalog timestamp string semantics

* chore: align plugin SDK surface ratchet

* fix: preserve trajectory and SDK string contracts

* fix(test): preserve QA record assertion semantics

* fix: complete standalone record guard rename

* refactor(cron): use canonical string coercion

* fix(acpx): preserve Pi timestamp parsing

* test(channels): adapt custody test harnesses

* test(telegram): classify media harness as test support

* test(acpx): split timestamp contract coverage

* test(channels): support generated custody contracts

* chore: ban the full coercion helper name set

Extends the declaration guard to all eleven consolidated helper names and
renames the cron schedule-identity readNumber wrapper to readScheduleInteger
so the banned generic name cannot regrow.

* fix(scripts): repair release-validation guard drift and lint cause

Restores the renamed isJsonRecord guard in assertTrustedWorkflowHarness after
main added isRecord call sites in parallel, and attaches the caught YAML error
as the thrown error cause (preserve-caught-error was red on main).

* fix: preserve Claude timestamp string semantics

* fix: preserve persisted timestamp string semantics

* fix: preserve date-first timestamp contracts

* fix(openai): harden delegation failure formatting

* chore: close coercion helper guard gaps

* test(openai): model non-error delegation rejection

* chore: refresh plugin SDK API contract

* fix(tasks): use canonical string field reader

* fix(ai): use canonical provider error field coercion

* fix(browser): migrate native bootstrap coercion

* docs(plugin-sdk): clarify text record export compatibility

* fix(gateway): normalize approval execution identity

* test(outbound): isolate message action poll harness
2026-08-11 00:02:18 -07:00

411 lines
12 KiB
TypeScript

import fsSync from "node:fs";
import fs from "node:fs/promises";
import * as readline from "node:readline";
import { parseSqliteSessionFileMarker } from "openclaw/plugin-sdk/session-store-runtime";
import {
readSessionTranscriptRawDelta,
type SessionTranscriptTargetParams,
} from "openclaw/plugin-sdk/session-transcript-runtime";
import {
asOptionalRecord,
normalizeLowercaseStringOrEmpty,
normalizeOptionalString,
} from "openclaw/plugin-sdk/string-coerce-runtime";
import { clampInt } from "./config.js";
import {
readExplicitMemoryEvidence,
readStructuredMemoryEvidenceFromContent,
readStructuredMemoryFailure,
readStructuredMemoryFailureFromContent,
} from "./prompt.js";
import { extractTextContent } from "./query.js";
import {
DEFAULT_ACTIVE_MEMORY_TOOLS_ALLOW,
DEFAULT_PARTIAL_TRANSCRIPT_MAX_CHARS,
DEFAULT_TRANSCRIPT_READ_MAX_BYTES,
DEFAULT_TRANSCRIPT_READ_MAX_LINES,
LANCEDB_ACTIVE_MEMORY_TOOLS_ALLOW,
type ActiveMemorySearchDebug,
type ActiveMemoryTranscriptSource,
type TranscriptReadLimits,
} from "./types.js";
function isUnavailableMemorySearchDebug(debug?: ActiveMemorySearchDebug): boolean {
return Boolean(debug?.error);
}
function resolveTranscriptReadLimits(
limits?: TranscriptReadLimits,
): Required<TranscriptReadLimits> {
return {
maxChars: clampInt(
limits?.maxChars,
DEFAULT_PARTIAL_TRANSCRIPT_MAX_CHARS,
1,
DEFAULT_PARTIAL_TRANSCRIPT_MAX_CHARS,
),
maxLines: clampInt(
limits?.maxLines,
DEFAULT_TRANSCRIPT_READ_MAX_LINES,
1,
DEFAULT_TRANSCRIPT_READ_MAX_LINES,
),
maxBytes: clampInt(
limits?.maxBytes,
DEFAULT_TRANSCRIPT_READ_MAX_BYTES,
1,
DEFAULT_TRANSCRIPT_READ_MAX_BYTES,
),
};
}
async function streamBoundedTranscriptJsonl(params: {
sessionFile: string;
limits?: TranscriptReadLimits;
onRecord: (record: unknown) => boolean | void;
}): Promise<void> {
const limits = resolveTranscriptReadLimits(params.limits);
try {
const stats = await fs.stat(params.sessionFile);
if (!stats.isFile() || stats.size > limits.maxBytes) {
return;
}
} catch {
return;
}
const stream = fsSync.createReadStream(params.sessionFile, {
encoding: "utf8",
});
const rl = readline.createInterface({
input: stream,
crlfDelay: Infinity,
});
let seenLines = 0;
try {
for await (const line of rl) {
seenLines += 1;
if (seenLines > limits.maxLines) {
break;
}
const trimmed = line.trim();
if (!trimmed) {
continue;
}
try {
if (params.onRecord(JSON.parse(trimmed) as unknown)) {
break;
}
} catch {}
}
} catch {
// Treat transcript recovery as best-effort on timeout/abort paths.
} finally {
rl.close();
stream.destroy();
}
}
function fileTranscriptSource(sessionFile: string): ActiveMemoryTranscriptSource {
return { kind: "file", sessionFile };
}
function transcriptSourceFromReturnedSessionFile(params: {
sessionFile: string;
sessionKey: string;
}): ActiveMemoryTranscriptSource {
const marker = parseSqliteSessionFileMarker(normalizeOptionalString(params.sessionFile));
if (!marker) {
return fileTranscriptSource(params.sessionFile);
}
return {
kind: "runtime",
target: {
agentId: marker.agentId,
sessionId: marker.sessionId,
sessionKey: params.sessionKey,
storePath: marker.storePath,
},
};
}
async function streamRuntimeTranscriptEvents(params: {
target: SessionTranscriptTargetParams;
limits?: TranscriptReadLimits;
onRecord: (record: unknown) => boolean | void;
}): Promise<void> {
const limits = resolveTranscriptReadLimits(params.limits);
let page: Awaited<ReturnType<typeof readSessionTranscriptRawDelta>>;
try {
page = await readSessionTranscriptRawDelta({
...params.target,
maxBytes: limits.maxBytes,
maxEvents: limits.maxLines,
});
} catch {
return;
}
if (page.kind !== "page") {
return;
}
for (const { event } of page.events) {
try {
if (params.onRecord(event)) {
break;
}
} catch {}
}
}
async function streamActiveMemoryTranscriptRecords(params: {
source: ActiveMemoryTranscriptSource;
limits?: TranscriptReadLimits;
onRecord: (record: unknown) => boolean | void;
}): Promise<void> {
if (params.source.kind === "runtime") {
await streamRuntimeTranscriptEvents({
target: params.source.target,
limits: params.limits,
onRecord: params.onRecord,
});
return;
}
await streamBoundedTranscriptJsonl({
sessionFile: params.source.sessionFile,
limits: params.limits,
onRecord: params.onRecord,
});
}
function resolveToolResultMessage(value: unknown): Record<string, unknown> | undefined {
const record = asOptionalRecord(value);
const message =
asOptionalRecord(record?.message) ?? (record?.role === "toolResult" ? record : undefined);
return message && normalizeOptionalString(message.role) === "toolResult" ? message : undefined;
}
function extractActiveMemorySearchDebugFromSessionRecord(
value: unknown,
): ActiveMemorySearchDebug | undefined {
const message = resolveToolResultMessage(value);
if (!message) {
return undefined;
}
const toolName = normalizeLowercaseStringOrEmpty(message.toolName);
if (toolName !== "memory_search" && toolName !== "memory_recall") {
return undefined;
}
const details = asOptionalRecord(message.details);
const debug = asOptionalRecord(details?.debug);
const warning = normalizeOptionalString(details?.warning);
const action = normalizeOptionalString(details?.action);
const error = normalizeOptionalString(details?.error);
if (!debug && !warning && !action && !error) {
return undefined;
}
return {
backend: normalizeOptionalString(debug?.backend),
configuredMode: normalizeOptionalString(debug?.configuredMode),
effectiveMode: normalizeOptionalString(debug?.effectiveMode),
fallback: normalizeOptionalString(debug?.fallback),
searchMs:
typeof debug?.searchMs === "number" && Number.isFinite(debug.searchMs)
? debug.searchMs
: undefined,
hits: typeof debug?.hits === "number" && Number.isFinite(debug.hits) ? debug.hits : undefined,
warning,
action,
error,
};
}
function extractToolResultNameFromSessionRecord(value: unknown): string | undefined {
const message = resolveToolResultMessage(value);
if (!message) {
return undefined;
}
const toolName = normalizeLowercaseStringOrEmpty(message.toolName);
return toolName || undefined;
}
function hasUnavailableMemoryResultInSessionRecord(
value: unknown,
toolsAllow: readonly string[] = [
...DEFAULT_ACTIVE_MEMORY_TOOLS_ALLOW,
...LANCEDB_ACTIVE_MEMORY_TOOLS_ALLOW,
],
): boolean {
const message = resolveToolResultMessage(value);
if (!message) {
return false;
}
const toolName = normalizeLowercaseStringOrEmpty(message.toolName);
if (!toolName || !toolsAllow.includes(toolName)) {
return false;
}
const details = asOptionalRecord(message.details);
const unavailable = message.isError === true || readStructuredMemoryFailure(details) === true;
if (unavailable) {
return true;
}
return readStructuredMemoryFailureFromContent(message.content) === true;
}
function hasTerminalUnavailableMemoryResultInSessionRecord(
value: unknown,
toolsAllow: readonly string[],
): boolean {
const message = resolveToolResultMessage(value);
if (!message) {
return false;
}
const toolName = normalizeLowercaseStringOrEmpty(message.toolName);
if (!toolName || !toolsAllow.includes(toolName)) {
return false;
}
const details = asOptionalRecord(message.details);
if (details?.disabled === true || details?.unavailable === true) {
return true;
}
const status = normalizeOptionalString(details?.status)
?.toLowerCase()
.replace(/[\s-]+/g, "_");
if (status === "disabled" || status === "unavailable") {
return true;
}
if (toolName !== "memory_search" && toolName !== "memory_recall") {
return false;
}
const debug = extractActiveMemorySearchDebugFromSessionRecord(value);
return Boolean(debug?.error) || Boolean(details?.error);
}
type ActiveMemoryHookDeadline = {
arm: (timeoutMs: number, onTimeout: () => void) => void;
promise: Promise<symbol>;
stop: () => void;
};
function createActiveMemoryHookDeadline(): ActiveMemoryHookDeadline {
const timeoutSentinel = Symbol("active-memory-hook-timeout");
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let resolveTimeout: (value: symbol) => void = () => {};
const promise = new Promise<symbol>((resolve) => {
resolveTimeout = resolve;
});
const stop = () => {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = undefined;
}
};
const arm = (timeoutMs: number, onTimeout: () => void) => {
stop();
timeoutId = setTimeout(() => {
onTimeout();
resolveTimeout(timeoutSentinel);
}, timeoutMs);
timeoutId.unref?.();
};
return { arm, promise, stop };
}
function hasUsableMemoryResultInSessionRecord(
value: unknown,
toolsAllow: readonly string[] = [
...DEFAULT_ACTIVE_MEMORY_TOOLS_ALLOW,
...LANCEDB_ACTIVE_MEMORY_TOOLS_ALLOW,
],
): boolean {
const message = resolveToolResultMessage(value);
if (!message) {
return false;
}
const toolName = normalizeLowercaseStringOrEmpty(message.toolName);
if (!toolName || !toolsAllow.includes(toolName)) {
return false;
}
if (hasUnavailableMemoryResultInSessionRecord(value, toolsAllow)) {
return false;
}
const details = asOptionalRecord(message.details);
const content = extractTextContent(message.content);
if (toolName === "memory_search") {
if (Array.isArray(details?.results)) {
return details.results.length > 0;
}
// Oversized details are capped before transcript persistence, while the
// leading model-visible JSON still preserves whether results were present.
return /"results"\s*:\s*\[\s*([^\s\]])/.test(content);
}
if (toolName === "memory_recall") {
if (Array.isArray(details?.memories)) {
return details.memories.length > 0;
}
return /^Found [1-9]\d* memories:/.test(content);
}
if (toolName === "memory_get") {
const text = normalizeOptionalString(details?.text);
return text !== undefined ? text.length > 0 : /"text"\s*:\s*"(?!")/.test(content);
}
if (toolName === "lcm_grep") {
if (
typeof details?.totalMatches === "number" &&
Number.isFinite(details.totalMatches) &&
details.totalMatches > 0
) {
return true;
}
return /^## LCM Grep Results[\s\S]*^\*\*Total matches:\*\*\s+[1-9]\d*$/m.test(content);
}
if (toolName === "lcm_describe") {
const type = normalizeOptionalString(details?.type);
if (normalizeOptionalString(details?.id) && (type === "summary" || type === "file")) {
return true;
}
return /^LCM_SUMMARY \S+/m.test(content) || /^## LCM File: \S+/m.test(content);
}
if (toolName === "lcm_expand_query") {
if (
typeof details?.expandedSummaryCount === "number" &&
Number.isFinite(details.expandedSummaryCount) &&
details.expandedSummaryCount > 0 &&
Boolean(normalizeOptionalString(details?.answer))
) {
return true;
}
try {
const parsed = asOptionalRecord(JSON.parse(content));
return (
typeof parsed?.expandedSummaryCount === "number" &&
Number.isFinite(parsed.expandedSummaryCount) &&
parsed.expandedSummaryCount > 0 &&
Boolean(normalizeOptionalString(parsed?.answer))
);
} catch {
return false;
}
}
const normalizedContent = normalizeOptionalString(content);
const explicitEvidence = details ? readExplicitMemoryEvidence(details) : undefined;
const structuredEvidence = normalizedContent
? readStructuredMemoryEvidenceFromContent(message.content)
: undefined;
// Custom recall tools have a shipped native-output contract. Preserve
// non-empty model-visible results unless structured fields explicitly say
// the lookup was empty; explicit failures are rejected above.
return Boolean(normalizedContent) && explicitEvidence !== false && structuredEvidence !== false;
}
export {
createActiveMemoryHookDeadline,
extractActiveMemorySearchDebugFromSessionRecord,
extractToolResultNameFromSessionRecord,
fileTranscriptSource,
hasTerminalUnavailableMemoryResultInSessionRecord,
hasUnavailableMemoryResultInSessionRecord,
hasUsableMemoryResultInSessionRecord,
isUnavailableMemorySearchDebug,
resolveTranscriptReadLimits,
streamActiveMemoryTranscriptRecords,
transcriptSourceFromReturnedSessionFile,
};