Skip to content

Commit dbcd06b

Browse files
committed
refactor(sessions): consolidate transcript and state helpers
1 parent 8f2850d commit dbcd06b

12 files changed

Lines changed: 117 additions & 223 deletions

‎src/context-engine/quarantine-health.ts‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Persists context-engine runtime quarantines so health surfaces can see
22
// failures recorded in sibling runtime processes.
3+
import { hasNonEmptyString } from "@openclaw/normalization-core/string-coerce";
34
import {
45
createRuntimeHealthRecordEnvelope,
56
createRuntimeHealthStore,
@@ -17,10 +18,6 @@ type PersistedContextEngineRuntimeQuarantine = {
1718
type PersistedContextEngineQuarantineRecord = RuntimeHealthRecordEnvelope &
1819
Omit<PersistedContextEngineRuntimeQuarantine, "failedAt">;
1920

20-
function isNonEmptyString(value: unknown): value is string {
21-
return typeof value === "string" && value.trim().length > 0;
22-
}
23-
2421
// No TTL: a quarantine is recorded once per failure and stays valid for the
2522
// recorder's lifetime, so process liveness alone owns expiry here.
2623
const quarantineStore = createRuntimeHealthStore<PersistedContextEngineQuarantineRecord>({
@@ -29,9 +26,9 @@ const quarantineStore = createRuntimeHealthStore<PersistedContextEngineQuarantin
2926
maxEntries: 64,
3027
normalizeRecord: (value) => {
3128
if (
32-
!isNonEmptyString(value.engineId) ||
33-
!isNonEmptyString(value.operation) ||
34-
!isNonEmptyString(value.reason)
29+
!hasNonEmptyString(value.engineId) ||
30+
!hasNonEmptyString(value.operation) ||
31+
!hasNonEmptyString(value.reason)
3532
) {
3633
return undefined;
3734
}
@@ -43,7 +40,7 @@ const quarantineStore = createRuntimeHealthStore<PersistedContextEngineQuarantin
4340
processId: value.processId,
4441
processToken: value.processToken,
4542
processStartTime: value.processStartTime,
46-
...(isNonEmptyString(value.owner) ? { owner: value.owner } : {}),
43+
...(hasNonEmptyString(value.owner) ? { owner: value.owner } : {}),
4744
};
4845
},
4946
displayKey: (record) => record.engineId,

‎src/sessions/conversation-turns.ts‎

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import crypto from "node:crypto";
2+
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
23
import { resolveGlobalSingleton } from "../shared/global-singleton.js";
34

45
type ConversationTurnReply = {
@@ -54,11 +55,6 @@ const pendingTurns = resolveGlobalSingleton(
5455
}
5556
},
5657
);
57-
function normalize(value: string | undefined): string | undefined {
58-
const normalized = value?.trim();
59-
return normalized || undefined;
60-
}
61-
6258
function pendingTurnKey(agentId: string, id: string): string {
6359
return JSON.stringify([agentId, id]);
6460
}
@@ -73,11 +69,11 @@ export function registerPendingConversationTurn(params: {
7369
timeoutMs: number;
7470
signal?: AbortSignal;
7571
}): PendingConversationTurnHandle {
76-
const agentId = normalize(params.agentId);
72+
const agentId = normalizeOptionalString(params.agentId);
7773
if (!agentId) {
7874
throw new Error("conversation turn requires an agent id");
7975
}
80-
const id = normalize(params.id) ?? crypto.randomUUID();
76+
const id = normalizeOptionalString(params.id) ?? crypto.randomUUID();
8177
const key = pendingTurnKey(agentId, id);
8278
if (pendingTurns.has(key)) {
8379
throw new Error(`conversation turn already pending for ${agentId}: ${id}`);
@@ -128,7 +124,7 @@ export function registerPendingConversationTurn(params: {
128124
id,
129125
conversationRef: params.conversationRef,
130126
sessionId: params.sessionId,
131-
threadId: normalize(params.threadId),
127+
threadId: normalizeOptionalString(params.threadId),
132128
createdAt,
133129
correlationReady,
134130
markCorrelationReady,
@@ -149,7 +145,7 @@ export function registerPendingConversationTurn(params: {
149145
if (pendingTurns.get(key) !== pending) {
150146
return;
151147
}
152-
pending.outboundMessageId = normalize(messageId);
148+
pending.outboundMessageId = normalizeOptionalString(messageId);
153149
if (!pending.outboundMessageId) {
154150
pending.settle(undefined);
155151
}
@@ -171,8 +167,8 @@ export function registerPendingConversationTurn(params: {
171167

172168
/** Cancels one Gateway-owned turn so a late reply follows ordinary inbound dispatch. */
173169
export function cancelPendingConversationTurn(params: { agentId: string; id: string }): boolean {
174-
const agentId = normalize(params.agentId);
175-
const id = normalize(params.id);
170+
const agentId = normalizeOptionalString(params.agentId);
171+
const id = normalizeOptionalString(params.id);
176172
const pending = agentId && id ? pendingTurns.get(pendingTurnKey(agentId, id)) : undefined;
177173
if (!pending) {
178174
return false;
@@ -193,13 +189,13 @@ export async function claimPendingConversationTurnReply(params: {
193189
text: string;
194190
timestamp?: number;
195191
}): Promise<ConversationTurnReplyClaim | undefined> {
196-
const replyToId = normalize(params.replyToId);
192+
const replyToId = normalizeOptionalString(params.replyToId);
197193
if (!replyToId) {
198194
return undefined;
199195
}
200-
const threadId = normalize(params.threadId);
201-
const parentConversationRef = normalize(params.parentConversationRef);
202-
const agentId = normalize(params.agentId);
196+
const threadId = normalizeOptionalString(params.threadId);
197+
const parentConversationRef = normalizeOptionalString(params.parentConversationRef);
198+
const agentId = normalizeOptionalString(params.agentId);
203199
if (!agentId) {
204200
return undefined;
205201
}

‎src/sessions/session-chat-type.ts‎

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,6 @@ import { parseAgentSessionKey } from "./session-key-utils.js";
99

1010
// Session chat-type derivation first uses generic key parsing, then falls back
1111
// to bootstrap channel plugins for legacy platform-specific session keys.
12-
type LegacySessionChatTypeDeriver = NonNullable<
13-
NonNullable<ReturnType<typeof getBootstrapChannelPlugin>>["messaging"]
14-
>["deriveLegacySessionChatType"];
15-
1612
function resolveScopedSessionKey(sessionKey: string | undefined | null): string {
1713
const raw = normalizeLowercaseStringOrEmpty(sessionKey);
1814
if (!raw) {
@@ -34,16 +30,6 @@ function collectLegacyChatTypeCandidatePluginIds(scopedSessionKey: string): stri
3430
return Array.from(ids);
3531
}
3632

37-
function derivePluginLegacySessionChatType(
38-
scopedSessionKey: string,
39-
deriveLegacySessionChatType: LegacySessionChatTypeDeriver,
40-
): SessionKeyChatType | undefined {
41-
if (!deriveLegacySessionChatType) {
42-
return undefined;
43-
}
44-
return deriveLegacySessionChatType(scopedSessionKey);
45-
}
46-
4733
export function deriveSessionChatType(sessionKey: string | undefined | null): SessionKeyChatType {
4834
const builtInType = deriveSessionChatTypeFromKey(sessionKey);
4935
if (builtInType !== "unknown") {
@@ -52,10 +38,9 @@ export function deriveSessionChatType(sessionKey: string | undefined | null): Se
5238

5339
const scopedSessionKey = resolveScopedSessionKey(sessionKey);
5440
for (const pluginId of collectLegacyChatTypeCandidatePluginIds(scopedSessionKey)) {
55-
const derived = derivePluginLegacySessionChatType(
56-
scopedSessionKey,
57-
getBootstrapChannelPlugin(pluginId)?.messaging?.deriveLegacySessionChatType,
58-
);
41+
const deriveLegacySessionChatType =
42+
getBootstrapChannelPlugin(pluginId)?.messaging?.deriveLegacySessionChatType;
43+
const derived = deriveLegacySessionChatType?.(scopedSessionKey);
5944
if (derived) {
6045
return derived;
6146
}

‎src/sessions/transcript-events.ts‎

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ export function onInternalSessionTranscriptUpdate(
6868

6969
/** Emits a normalized transcript update to all registered listeners. */
7070
export function emitSessionTranscriptUpdate(update: InternalSessionTranscriptUpdate): void {
71-
const nextUpdate = normalizeSessionTranscriptUpdate(update, { allowIdentityOnly: true });
71+
const nextUpdate = normalizeSessionTranscriptUpdate(update);
7272
if (!nextUpdate) {
7373
return;
7474
}
@@ -81,40 +81,27 @@ export function emitSessionTranscriptUpdate(update: InternalSessionTranscriptUpd
8181

8282
function normalizeSessionTranscriptUpdate(
8383
update: InternalSessionTranscriptUpdate,
84-
options: { allowIdentityOnly: boolean },
8584
): InternalSessionTranscriptUpdate | undefined {
86-
const normalized = {
87-
sessionFile: update.sessionFile,
88-
target: update.target,
89-
sessionKey: update.sessionKey,
90-
agentId: update.agentId,
91-
sessionId: update.sessionId,
92-
lifecycleRevision: update.lifecycleRevision,
93-
message: update.message,
94-
messageId: update.messageId,
95-
messageSeq: update.messageSeq,
96-
};
97-
const trimmed = normalizeOptionalString(normalized.sessionFile);
98-
const target = normalizeUpdateTarget(normalized);
99-
if (!trimmed && (!options.allowIdentityOnly || !target)) {
85+
const trimmed = normalizeOptionalString(update.sessionFile);
86+
const target = normalizeUpdateTarget(update);
87+
if (!trimmed && !target) {
10088
return undefined;
10189
}
102-
const messageSeq = asPositiveSafeInteger(normalized.messageSeq);
103-
const sessionKey = normalizeOptionalString(normalized.sessionKey) ?? target?.sessionKey;
104-
const agentId = normalizeOptionalString(normalized.agentId) ?? target?.agentId;
105-
const sessionId = normalizeOptionalString(normalized.sessionId) ?? target?.sessionId;
106-
const lifecycleRevision = normalizeOptionalString(normalized.lifecycleRevision);
90+
const messageSeq = asPositiveSafeInteger(update.messageSeq);
91+
const sessionKey = normalizeOptionalString(update.sessionKey) ?? target?.sessionKey;
92+
const agentId = normalizeOptionalString(update.agentId) ?? target?.agentId;
93+
const sessionId = normalizeOptionalString(update.sessionId) ?? target?.sessionId;
94+
const lifecycleRevision = normalizeOptionalString(update.lifecycleRevision);
95+
const messageId = normalizeOptionalString(update.messageId);
10796
return {
10897
...(trimmed ? { sessionFile: trimmed } : {}),
10998
...(target ? { target } : {}),
11099
...(sessionKey ? { sessionKey } : {}),
111100
...(agentId ? { agentId } : {}),
112101
...(sessionId ? { sessionId } : {}),
113102
...(lifecycleRevision ? { lifecycleRevision } : {}),
114-
...(normalized.message !== undefined ? { message: normalized.message } : {}),
115-
...(normalizeOptionalString(normalized.messageId)
116-
? { messageId: normalizeOptionalString(normalized.messageId) }
117-
: {}),
103+
...(update.message !== undefined ? { message: update.message } : {}),
104+
...(messageId ? { messageId } : {}),
118105
...(messageSeq !== undefined ? { messageSeq } : {}),
119106
};
120107
}

‎src/sessions/user-turn-transcript.media-normalize.ts‎

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import path from "node:path";
22
import { mimeTypeFromFilePath } from "@openclaw/media-core/mime";
3+
import {
4+
asFiniteNumberInRange,
5+
asPositiveSafeInteger,
6+
} from "@openclaw/normalization-core/number-coercion";
7+
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
38
import type { MediaFactInput } from "../media/media-facts.js";
49
import type { PersistedUserTurnMediaInput } from "./user-turn-transcript.types.js";
510

@@ -14,26 +19,13 @@ const STRUCTURED_MEDIA_KINDS = new Set<NonNullable<MediaFactInput["kind"]>>([
1419
]);
1520
const MIME_TYPE_PATTERN = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/iu;
1621

17-
function normalizeOptionalText(value: string | null | undefined): string | undefined {
18-
const normalized = value?.trim();
19-
return normalized ? normalized : undefined;
20-
}
21-
22-
function normalizeNonNegativeNumber(value: number | null | undefined): number | undefined {
23-
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
24-
}
25-
2622
function normalizeStructuredMediaKind(value: string | null | undefined): MediaFactInput["kind"] {
27-
const kind = normalizeOptionalText(value);
23+
const kind = normalizeOptionalString(value);
2824
return kind && STRUCTURED_MEDIA_KINDS.has(kind as NonNullable<MediaFactInput["kind"]>)
2925
? (kind as NonNullable<MediaFactInput["kind"]>)
3026
: undefined;
3127
}
3228

33-
function normalizePositiveInteger(value: number | null | undefined): number | undefined {
34-
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
35-
}
36-
3729
export function resolveTranscriptMediaPath(
3830
pathValue: string,
3931
workspaceDir: string | undefined,
@@ -49,21 +41,21 @@ export function resolveTranscriptMediaPath(
4941
export function normalizeStructuredMediaEntryForTranscript(
5042
media: PersistedUserTurnMediaInput,
5143
): MediaFactInput {
52-
const workspaceDir = normalizeOptionalText(media.workspaceDir);
53-
const mediaPath = normalizeOptionalText(media.path);
54-
const mediaUrl = normalizeOptionalText(media.url);
44+
const workspaceDir = normalizeOptionalString(media.workspaceDir);
45+
const mediaPath = normalizeOptionalString(media.path);
46+
const mediaUrl = normalizeOptionalString(media.url);
5547
const kind = normalizeStructuredMediaKind(media.kind);
56-
const legacyKind = normalizeOptionalText(media.kind);
57-
const messageId = normalizeOptionalText(media.messageId);
48+
const legacyKind = normalizeOptionalString(media.kind);
49+
const messageId = normalizeOptionalString(media.messageId);
5850
const contentType =
59-
normalizeOptionalText(media.contentType) ??
51+
normalizeOptionalString(media.contentType) ??
6052
(kind || !legacyKind || !MIME_TYPE_PATTERN.test(legacyKind) ? undefined : legacyKind) ??
6153
mimeTypeFromFilePath(mediaPath ?? mediaUrl);
62-
const durationMs = normalizePositiveInteger(media.durationMs);
63-
const width = normalizePositiveInteger(media.width);
64-
const height = normalizePositiveInteger(media.height);
65-
const fileName = normalizeOptionalText(media.fileName);
66-
const sizeBytes = normalizeNonNegativeNumber(media.sizeBytes);
54+
const durationMs = asPositiveSafeInteger(media.durationMs);
55+
const width = asPositiveSafeInteger(media.width);
56+
const height = asPositiveSafeInteger(media.height);
57+
const fileName = normalizeOptionalString(media.fileName);
58+
const sizeBytes = asFiniteNumberInRange(media.sizeBytes, { min: 0 });
6759
return {
6860
...(mediaPath ? { path: resolveTranscriptMediaPath(mediaPath, workspaceDir) } : {}),
6961
...(mediaUrl ? { url: mediaUrl } : {}),

‎src/sessions/user-turn-transcript.ts‎

Lines changed: 14 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// User turn transcript helpers extract user-turn text from session transcripts.
22
import { mimeTypeFromFilePath } from "@openclaw/media-core/mime";
3+
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
4+
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
35
import type { AgentMessage } from "../../packages/agent-core/src/types.js";
46
import {
57
persistSessionTranscriptTurn,
@@ -35,22 +37,9 @@ export function buildRunUserTurnIdempotencyKey(runId: string): string {
3537
return `${runId}:user`;
3638
}
3739

38-
function normalizeOptionalText(value: string | null | undefined): string | undefined {
39-
const normalized = value?.trim();
40-
return normalized ? normalized : undefined;
41-
}
42-
43-
function normalizeTranscriptText(value: string | null | undefined): string {
44-
return value ?? "";
45-
}
46-
4740
// Select normalized text for persisted user turns.
4841
export function resolvePersistedUserTurnText(value: string | null | undefined): string | undefined {
49-
const normalized = normalizeOptionalText(value);
50-
if (!normalized) {
51-
return undefined;
52-
}
53-
return normalized;
42+
return normalizeOptionalString(value);
5443
}
5544

5645
function resolveTranscriptMediaType(params: {
@@ -70,16 +59,16 @@ export function buildPersistedUserTurnMediaInputsFromFields(
7059

7160
const facts = readPersistedMediaFacts(fields) ?? [];
7261
const normalizedMedia = facts.map((fact) => {
73-
const rawPath = normalizeOptionalText(fact.path);
62+
const rawPath = normalizeOptionalString(fact.path);
7463
const mediaPath = rawPath
75-
? resolveTranscriptMediaPath(rawPath, normalizeOptionalText(fact.workspaceDir))
64+
? resolveTranscriptMediaPath(rawPath, normalizeOptionalString(fact.workspaceDir))
7665
: undefined;
77-
const url = normalizeOptionalText(fact.url);
66+
const url = normalizeOptionalString(fact.url);
7867
if (!mediaPath && !url) {
7968
return {};
8069
}
8170
const contentType = resolveTranscriptMediaType({
82-
explicitType: normalizeOptionalText(fact.contentType),
71+
explicitType: normalizeOptionalString(fact.contentType),
8372
mediaPath,
8473
mediaUrl: url,
8574
});
@@ -131,9 +120,9 @@ export function buildLateMediaAttachedProjection(message: AgentMessage): {
131120
function buildUserTurnSenderMeta(
132121
sender: UserTurnInput["sender"],
133122
): Record<string, string> | undefined {
134-
const senderId = normalizeOptionalText(sender?.id);
135-
const senderName = normalizeOptionalText(sender?.name);
136-
const senderUsername = normalizeOptionalText(sender?.username);
123+
const senderId = normalizeOptionalString(sender?.id);
124+
const senderName = normalizeOptionalString(sender?.name);
125+
const senderUsername = normalizeOptionalString(sender?.username);
137126
if (!senderId && !senderName && !senderUsername) {
138127
return undefined;
139128
}
@@ -145,15 +134,12 @@ function buildUserTurnSenderMeta(
145134
}
146135

147136
function readOpenClawMessageMeta(message: AgentMessage): Record<string, unknown> | undefined {
148-
const meta = (message as unknown as Record<string, unknown>)["__openclaw"];
149-
return meta && typeof meta === "object" && !Array.isArray(meta)
150-
? (meta as Record<string, unknown>)
151-
: undefined;
137+
return asOptionalRecord((message as unknown as Record<string, unknown>)["__openclaw"]);
152138
}
153139

154140
export function buildPersistedUserTurnMessage(params: UserTurnInput): PersistedUserTurnMessage {
155141
const normalizedMedia = (params.media ?? []).map(normalizeStructuredMediaEntryForTranscript);
156-
const text = normalizeTranscriptText(params.text);
142+
const text = params.text ?? "";
157143
// Storage is BARE (no timestamp prefix). The per-message timestamp is added
158144
// at the single LLM-boundary stamping site (normalizeMessagesForLlmBoundary),
159145
// derived from each message's own `timestamp` field, so the current turn and
@@ -338,10 +324,8 @@ export function preparePersistedUserTurnMessageForTranscriptWrite(
338324
originalMediaImageLayout === undefined ? undefined : structuredClone(originalMediaImageLayout);
339325
// Hooks receive the original message object and may mutate nested metadata in
340326
// place. Snapshot transport correlation before handing them that reference.
341-
const transport =
342-
originalTransport && typeof originalTransport === "object" && !Array.isArray(originalTransport)
343-
? { ...originalTransport }
344-
: undefined;
327+
const originalTransportRecord = asOptionalRecord(originalTransport);
328+
const transport = originalTransportRecord ? { ...originalTransportRecord } : undefined;
345329
const nextMessage = params.beforeMessageWrite({
346330
message,
347331
...(params.agentId ? { agentId: params.agentId } : {}),

0 commit comments

Comments
 (0)