-
-
Notifications
You must be signed in to change notification settings - Fork 76.2k
Expand file tree
/
Copy pathsession-utils.ts
More file actions
1889 lines (1796 loc) · 58.2 KB
/
session-utils.ts
File metadata and controls
1889 lines (1796 loc) · 58.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from "node:fs";
import path from "node:path";
import { resolveAgentRuntimeMetadata } from "../agents/agent-runtime-metadata.js";
import {
listAgentIds,
resolveAgentConfig,
resolveAgentEffectiveModelPrimary,
resolveAgentModelFallbacksOverride,
resolveAgentWorkspaceDir,
resolveDefaultAgentId,
} from "../agents/agent-scope.js";
import { lookupContextTokens, resolveContextTokensForModel } from "../agents/context.js";
import { DEFAULT_CONTEXT_TOKENS, DEFAULT_MODEL, DEFAULT_PROVIDER } from "../agents/defaults.js";
import {
findModelCatalogEntry,
modelSupportsInput,
type ModelCatalogEntry,
} from "../agents/model-catalog.js";
import {
inferUniqueProviderFromConfiguredModels,
isCliProvider,
normalizeStoredOverrideModel,
parseModelRef,
resolveConfiguredModelRef,
resolveDefaultModelForAgent,
resolvePersistedSelectedModelRef,
resolveThinkingDefault,
} from "../agents/model-selection.js";
import {
countActiveDescendantRuns,
getSessionDisplaySubagentRunByChildSessionKey,
getSubagentSessionRuntimeMs,
getSubagentSessionStartedAt,
isSubagentRunLive,
listSubagentRunsForController,
resolveSubagentSessionStatus,
} from "../agents/subagent-registry-read.js";
import {
RECENT_ENDED_SUBAGENT_CHILD_SESSION_MS,
shouldKeepSubagentRunChildLink,
} from "../agents/subagent-run-liveness.js";
import { listThinkingLevelOptions } from "../auto-reply/thinking.js";
import { getRuntimeConfig } from "../config/io.js";
import { resolveAgentModelFallbackValues } from "../config/model-input.js";
import { resolveStateDir } from "../config/paths.js";
import {
buildGroupDisplayName,
loadSessionStore,
resolveAllAgentSessionStoreTargetsSync,
resolveAgentMainSessionKey,
resolveFreshSessionTotalTokens,
resolveStorePath,
type SessionEntry,
type SessionStoreTarget,
type SessionScope,
} from "../config/sessions.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { openBoundaryFileSync } from "../infra/boundary-file-read.js";
import { projectPluginSessionExtensionsSync } from "../plugins/host-hook-state.js";
import {
DEFAULT_AGENT_ID,
normalizeAgentId,
normalizeMainKey,
parseAgentSessionKey,
} from "../routing/session-key.js";
import { isCronRunSessionKey } from "../sessions/session-key-utils.js";
import {
AVATAR_MAX_BYTES,
isAvatarDataUrl,
isAvatarHttpUrl,
isPathWithinRoot,
isWorkspaceRelativeAvatarPath,
resolveAvatarMime,
} from "../shared/avatar-policy.js";
import {
normalizeLowercaseStringOrEmpty,
normalizeOptionalString,
normalizeOptionalLowercaseString,
} from "../shared/string-coerce.js";
import { normalizeSessionDeliveryFields } from "../utils/delivery-context.shared.js";
import { estimateUsageCost, resolveModelCostConfig } from "../utils/usage-format.js";
import {
canonicalizeSpawnedByForAgent,
resolveSessionStoreAgentId,
resolveSessionStoreKey,
resolveStoredSessionKeyForAgentStore,
} from "./session-store-key.js";
import {
readLatestSessionUsageFromTranscript,
readRecentSessionUsageFromTranscript,
readSessionTitleFieldsFromTranscript,
} from "./session-utils.fs.js";
import type {
GatewayAgentRow,
GatewaySessionRow,
GatewaySessionsDefaults,
SessionRunStatus,
SessionsListResult,
} from "./session-utils.types.js";
export {
archiveFileOnDisk,
archiveSessionTranscripts,
attachOpenClawTranscriptMeta,
capArrayByJsonBytes,
readFirstUserMessageFromTranscript,
readLastMessagePreviewFromTranscript,
readLatestSessionUsageFromTranscript,
readRecentSessionUsageFromTranscript,
readRecentSessionMessages,
readSessionTitleFieldsFromTranscript,
readSessionPreviewItemsFromTranscript,
readSessionMessages,
resolveSessionTranscriptCandidates,
} from "./session-utils.fs.js";
export { canonicalizeSpawnedByForAgent, resolveSessionStoreKey } from "./session-store-key.js";
export type {
GatewayAgentRow,
GatewaySessionRow,
GatewaySessionsDefaults,
SessionsListResult,
SessionsPatchResult,
SessionsPreviewEntry,
SessionsPreviewResult,
} from "./session-utils.types.js";
const DERIVED_TITLE_MAX_LEN = 60;
function tryResolveExistingPath(value: string): string | null {
try {
return fs.realpathSync(value);
} catch {
return null;
}
}
function resolveIdentityAvatarUrl(
cfg: OpenClawConfig,
agentId: string,
avatar: string | undefined,
): string | undefined {
if (!avatar) {
return undefined;
}
const trimmed = normalizeOptionalString(avatar) ?? "";
if (!trimmed) {
return undefined;
}
if (isAvatarDataUrl(trimmed) || isAvatarHttpUrl(trimmed)) {
return trimmed;
}
if (!isWorkspaceRelativeAvatarPath(trimmed)) {
return undefined;
}
const workspaceDir = resolveAgentWorkspaceDir(cfg, agentId);
const workspaceRoot = tryResolveExistingPath(workspaceDir) ?? path.resolve(workspaceDir);
const resolvedCandidate = path.resolve(workspaceRoot, trimmed);
if (!isPathWithinRoot(workspaceRoot, resolvedCandidate)) {
return undefined;
}
try {
const opened = openBoundaryFileSync({
absolutePath: resolvedCandidate,
rootPath: workspaceRoot,
rootRealPath: workspaceRoot,
boundaryLabel: "workspace root",
maxBytes: AVATAR_MAX_BYTES,
skipLexicalRootCheck: true,
});
if (!opened.ok) {
return undefined;
}
try {
const buffer = fs.readFileSync(opened.fd);
const mime = resolveAvatarMime(resolvedCandidate);
return `data:${mime};base64,${buffer.toString("base64")}`;
} finally {
fs.closeSync(opened.fd);
}
} catch {
return undefined;
}
}
function formatSessionIdPrefix(sessionId: string, updatedAt?: number | null): string {
const prefix = sessionId.slice(0, 8);
if (updatedAt && updatedAt > 0) {
const d = new Date(updatedAt);
const date = d.toISOString().slice(0, 10);
return `${prefix} (${date})`;
}
return prefix;
}
function truncateTitle(text: string, maxLen: number): string {
if (text.length <= maxLen) {
return text;
}
const cut = text.slice(0, maxLen - 1);
const lastSpace = cut.lastIndexOf(" ");
if (lastSpace > maxLen * 0.6) {
return cut.slice(0, lastSpace) + "…";
}
return cut + "…";
}
export function deriveSessionTitle(
entry: SessionEntry | undefined,
firstUserMessage?: string | null,
): string | undefined {
if (!entry) {
return undefined;
}
if (normalizeOptionalString(entry.displayName)) {
return normalizeOptionalString(entry.displayName);
}
if (normalizeOptionalString(entry.subject)) {
return normalizeOptionalString(entry.subject);
}
if (firstUserMessage?.trim()) {
const normalized = firstUserMessage.replace(/\s+/g, " ").trim();
return truncateTitle(normalized, DERIVED_TITLE_MAX_LEN);
}
if (entry.sessionId) {
return formatSessionIdPrefix(entry.sessionId, entry.updatedAt);
}
return undefined;
}
function resolveSessionRuntimeMs(
run: { startedAt?: number; endedAt?: number; accumulatedRuntimeMs?: number } | null,
now: number,
) {
return getSubagentSessionRuntimeMs(run, now);
}
function resolvePositiveNumber(value: number | null | undefined): number | undefined {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
}
function resolveNonNegativeNumber(value: number | null | undefined): number | undefined {
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
}
function resolveLatestCompactionCheckpoint(
entry?: Pick<SessionEntry, "compactionCheckpoints"> | null,
): NonNullable<SessionEntry["compactionCheckpoints"]>[number] | undefined {
const checkpoints = entry?.compactionCheckpoints;
if (!Array.isArray(checkpoints) || checkpoints.length === 0) {
return undefined;
}
return checkpoints.reduce((latest, checkpoint) =>
!latest || checkpoint.createdAt > latest.createdAt ? checkpoint : latest,
);
}
function resolveEstimatedSessionCostUsd(params: {
cfg: OpenClawConfig;
provider?: string;
model?: string;
entry?: Pick<
SessionEntry,
"estimatedCostUsd" | "inputTokens" | "outputTokens" | "cacheRead" | "cacheWrite"
>;
explicitCostUsd?: number;
}): number | undefined {
const explicitCostUsd = resolveNonNegativeNumber(
params.explicitCostUsd ?? params.entry?.estimatedCostUsd,
);
if (explicitCostUsd !== undefined) {
return explicitCostUsd;
}
const input = resolvePositiveNumber(params.entry?.inputTokens);
const output = resolvePositiveNumber(params.entry?.outputTokens);
const cacheRead = resolvePositiveNumber(params.entry?.cacheRead);
const cacheWrite = resolvePositiveNumber(params.entry?.cacheWrite);
if (
input === undefined &&
output === undefined &&
cacheRead === undefined &&
cacheWrite === undefined
) {
return undefined;
}
const cost = resolveModelCostConfig({
provider: params.provider,
model: params.model,
config: params.cfg,
});
if (!cost) {
return undefined;
}
const estimated = estimateUsageCost({
usage: {
...(input !== undefined ? { input } : {}),
...(output !== undefined ? { output } : {}),
...(cacheRead !== undefined ? { cacheRead } : {}),
...(cacheWrite !== undefined ? { cacheWrite } : {}),
},
cost,
});
return resolveNonNegativeNumber(estimated);
}
const STALE_STORE_ONLY_CHILD_LINK_MS = 60 * 60 * 1_000;
function isFinitePositiveTimestamp(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value) && value > 0;
}
function isTerminalSessionStatus(status: unknown): status is Exclude<SessionRunStatus, "running"> {
return status === "done" || status === "failed" || status === "killed" || status === "timeout";
}
function shouldKeepStoreOnlyChildLink(entry: SessionEntry, now: number): boolean {
if (isTerminalSessionStatus(entry.status) || isFinitePositiveTimestamp(entry.endedAt)) {
const endedAt = isFinitePositiveTimestamp(entry.endedAt) ? entry.endedAt : entry.updatedAt;
return (
isFinitePositiveTimestamp(endedAt) && now - endedAt <= RECENT_ENDED_SUBAGENT_CHILD_SESSION_MS
);
}
if (entry.status === "running" || isFinitePositiveTimestamp(entry.startedAt)) {
return true;
}
return (
isFinitePositiveTimestamp(entry.updatedAt) &&
now - entry.updatedAt <= STALE_STORE_ONLY_CHILD_LINK_MS
);
}
function resolveRuntimeChildSessionKeys(
controllerSessionKey: string,
now = Date.now(),
): string[] | undefined {
const childSessionKeys = new Set<string>();
for (const entry of listSubagentRunsForController(controllerSessionKey)) {
const childSessionKey = normalizeOptionalString(entry.childSessionKey);
if (!childSessionKey) {
continue;
}
const latest = getSessionDisplaySubagentRunByChildSessionKey(childSessionKey);
if (!latest) {
continue;
}
const latestControllerSessionKey =
normalizeOptionalString(latest?.controllerSessionKey) ||
normalizeOptionalString(latest?.requesterSessionKey);
if (latestControllerSessionKey !== controllerSessionKey) {
continue;
}
if (
!shouldKeepSubagentRunChildLink(latest, {
activeDescendants: countActiveDescendantRuns(childSessionKey),
now,
})
) {
continue;
}
childSessionKeys.add(childSessionKey);
}
const childSessions = Array.from(childSessionKeys);
return childSessions.length > 0 ? childSessions : undefined;
}
function addChildSessionKey(
childSessionsByKey: Map<string, string[]>,
parentKey: string,
childKey: string,
) {
const current = childSessionsByKey.get(parentKey);
if (current) {
if (!current.includes(childKey)) {
current.push(childKey);
}
return;
}
childSessionsByKey.set(parentKey, [childKey]);
}
function buildStoreChildSessionIndex(
store: Record<string, SessionEntry>,
now = Date.now(),
): Map<string, string[]> {
const childSessionsByKey = new Map<string, string[]>();
for (const [key, entry] of Object.entries(store)) {
if (!entry) {
continue;
}
const parentKeys = [
normalizeOptionalString(entry.spawnedBy),
normalizeOptionalString(entry.parentSessionKey),
].filter((value): value is string => Boolean(value) && value !== key);
if (parentKeys.length === 0) {
continue;
}
const latest = getSessionDisplaySubagentRunByChildSessionKey(key);
let latestControllerSessionKey: string | undefined;
if (latest) {
latestControllerSessionKey =
normalizeOptionalString(latest.controllerSessionKey) ||
normalizeOptionalString(latest.requesterSessionKey);
if (
!shouldKeepSubagentRunChildLink(latest, {
activeDescendants: countActiveDescendantRuns(key),
now,
})
) {
continue;
}
} else if (!shouldKeepStoreOnlyChildLink(entry, now)) {
continue;
}
for (const parentKey of parentKeys) {
if (latestControllerSessionKey && latestControllerSessionKey !== parentKey) {
continue;
}
addChildSessionKey(childSessionsByKey, parentKey, key);
}
}
return childSessionsByKey;
}
function mergeChildSessionKeys(
runtimeChildSessions: string[] | undefined,
storeChildSessions: string[] | undefined,
): string[] | undefined {
if (!runtimeChildSessions?.length) {
return storeChildSessions?.length ? storeChildSessions : undefined;
}
if (!storeChildSessions?.length) {
return runtimeChildSessions;
}
return Array.from(new Set([...runtimeChildSessions, ...storeChildSessions]));
}
function resolveChildSessionKeys(
controllerSessionKey: string,
store: Record<string, SessionEntry>,
now = Date.now(),
): string[] | undefined {
const runtimeChildSessions = resolveRuntimeChildSessionKeys(controllerSessionKey, now);
const storeChildSessions = buildStoreChildSessionIndex(store, now).get(controllerSessionKey);
return mergeChildSessionKeys(runtimeChildSessions, storeChildSessions);
}
function resolveTranscriptUsageFallback(params: {
cfg: OpenClawConfig;
key: string;
entry?: SessionEntry;
storePath: string;
fallbackProvider?: string;
fallbackModel?: string;
maxTranscriptBytes?: number;
}): {
estimatedCostUsd?: number;
totalTokens?: number;
totalTokensFresh?: boolean;
contextTokens?: number;
modelProvider?: string;
model?: string;
} | null {
const entry = params.entry;
if (!entry?.sessionId) {
return null;
}
const parsed = parseAgentSessionKey(params.key);
const agentId = parsed?.agentId
? normalizeAgentId(parsed.agentId)
: resolveDefaultAgentId(params.cfg);
const snapshot =
typeof params.maxTranscriptBytes === "number"
? readRecentSessionUsageFromTranscript(
entry.sessionId,
params.storePath,
entry.sessionFile,
agentId,
params.maxTranscriptBytes,
)
: readLatestSessionUsageFromTranscript(
entry.sessionId,
params.storePath,
entry.sessionFile,
agentId,
);
if (!snapshot) {
return null;
}
const modelProvider = snapshot.modelProvider ?? params.fallbackProvider;
const model = snapshot.model ?? params.fallbackModel;
const contextTokens = resolveContextTokensForModel({
cfg: params.cfg,
provider: modelProvider,
model,
// Gateway/session listing is read-only; don't start async model discovery.
allowAsyncLoad: false,
});
const estimatedCostUsd = resolveEstimatedSessionCostUsd({
cfg: params.cfg,
provider: modelProvider,
model,
explicitCostUsd: snapshot.costUsd,
entry: {
inputTokens: snapshot.inputTokens,
outputTokens: snapshot.outputTokens,
cacheRead: snapshot.cacheRead,
cacheWrite: snapshot.cacheWrite,
},
});
return {
modelProvider,
model,
totalTokens: resolvePositiveNumber(snapshot.totalTokens),
totalTokensFresh: snapshot.totalTokensFresh === true,
contextTokens: resolvePositiveNumber(contextTokens),
estimatedCostUsd,
};
}
/**
* Returns the owning agent id if the session key belongs to an agent that is no
* longer present in config (deleted). Returns null for non-agent legacy/global
* keys, or when the owning agent still exists (#65524).
*/
export function resolveDeletedAgentIdFromSessionKey(
cfg: OpenClawConfig,
sessionKey: string,
): string | null {
const parsed = parseAgentSessionKey(sessionKey);
if (!parsed) {
return null;
}
const agentId = normalizeAgentId(parsed.agentId);
if (listAgentIds(cfg).includes(agentId)) {
return null;
}
return agentId;
}
export function loadSessionEntry(sessionKey: string) {
const cfg = getRuntimeConfig();
const key = normalizeOptionalString(sessionKey) ?? "";
const target = resolveGatewaySessionStoreTarget({
cfg,
key,
});
const storePath = target.storePath;
const store = loadSessionStore(storePath);
const freshestMatch = resolveFreshestSessionStoreMatchFromStoreKeys(store, target.storeKeys);
const legacyKey = freshestMatch?.key !== target.canonicalKey ? freshestMatch?.key : undefined;
return {
cfg,
storePath,
store,
entry: freshestMatch?.entry,
canonicalKey: target.canonicalKey,
legacyKey,
};
}
export function resolveFreshestSessionStoreMatchFromStoreKeys(
store: Record<string, SessionEntry>,
storeKeys: string[],
): { key: string; entry: SessionEntry } | undefined {
let freshest: { key: string; entry: SessionEntry } | undefined;
for (const key of storeKeys) {
const entry = store[key];
if (!entry) {
continue;
}
const match = { key, entry };
if (!freshest || (match.entry.updatedAt ?? 0) > (freshest.entry.updatedAt ?? 0)) {
freshest = match;
}
}
return freshest;
}
export function resolveFreshestSessionEntryFromStoreKeys(
store: Record<string, SessionEntry>,
storeKeys: string[],
): SessionEntry | undefined {
return resolveFreshestSessionStoreMatchFromStoreKeys(store, storeKeys)?.entry;
}
function findFreshestStoreMatch(
store: Record<string, SessionEntry>,
...candidates: string[]
): { entry: SessionEntry; key: string } | undefined {
const matches = new Map<string, { entry: SessionEntry; key: string }>();
for (const candidate of candidates) {
const trimmed = normalizeOptionalString(candidate) ?? "";
if (!trimmed) {
continue;
}
const exact = store[trimmed];
if (exact) {
matches.set(trimmed, { entry: exact, key: trimmed });
}
for (const key of findStoreKeysIgnoreCase(store, trimmed)) {
const entry = store[key];
if (entry) {
matches.set(key, { entry, key });
}
}
}
if (matches.size === 0) {
return undefined;
}
let freshest: { entry: SessionEntry; key: string } | undefined;
for (const match of matches.values()) {
if (!freshest || (match.entry.updatedAt ?? 0) > (freshest.entry.updatedAt ?? 0)) {
freshest = match;
}
}
return freshest;
}
/**
* Find all on-disk store keys that match the given key case-insensitively.
* Returns every key from the store whose lowercased form equals the target's lowercased form.
*/
export function findStoreKeysIgnoreCase(
store: Record<string, unknown>,
targetKey: string,
): string[] {
const lowered = normalizeLowercaseStringOrEmpty(targetKey);
const matches: string[] = [];
for (const key of Object.keys(store)) {
if (normalizeLowercaseStringOrEmpty(key) === lowered) {
matches.push(key);
}
}
return matches;
}
/**
* Remove legacy key variants for one canonical session key.
* Candidates can include aliases (for example, "agent:ops:main" when canonical is "agent:ops:work").
*/
export function pruneLegacyStoreKeys(params: {
store: Record<string, unknown>;
canonicalKey: string;
candidates: Iterable<string>;
}) {
const keysToDelete = new Set<string>();
for (const candidate of params.candidates) {
const trimmed = normalizeOptionalString(candidate ?? "") ?? "";
if (!trimmed) {
continue;
}
if (trimmed !== params.canonicalKey) {
keysToDelete.add(trimmed);
}
for (const match of findStoreKeysIgnoreCase(params.store, trimmed)) {
if (match !== params.canonicalKey) {
keysToDelete.add(match);
}
}
}
for (const key of keysToDelete) {
delete params.store[key];
}
}
export function migrateAndPruneGatewaySessionStoreKey(params: {
cfg: OpenClawConfig;
key: string;
store: Record<string, SessionEntry>;
}) {
const target = resolveGatewaySessionStoreTarget({
cfg: params.cfg,
key: params.key,
store: params.store,
});
const primaryKey = target.canonicalKey;
const freshestMatch = resolveFreshestSessionStoreMatchFromStoreKeys(
params.store,
target.storeKeys,
);
if (freshestMatch) {
const currentPrimary = params.store[primaryKey];
if (!currentPrimary || (freshestMatch.entry.updatedAt ?? 0) > (currentPrimary.updatedAt ?? 0)) {
params.store[primaryKey] = freshestMatch.entry;
}
}
pruneLegacyStoreKeys({
store: params.store,
canonicalKey: primaryKey,
candidates: target.storeKeys,
});
return { target, primaryKey, entry: params.store[primaryKey] };
}
export function classifySessionKey(key: string, entry?: SessionEntry): GatewaySessionRow["kind"] {
if (key === "global") {
return "global";
}
if (key === "unknown") {
return "unknown";
}
if (entry?.chatType === "group" || entry?.chatType === "channel") {
return "group";
}
if (key.includes(":group:") || key.includes(":channel:")) {
return "group";
}
return "direct";
}
export function parseGroupKey(
key: string,
): { channel?: string; kind?: "group" | "channel"; id?: string } | null {
const agentParsed = parseAgentSessionKey(key);
const rawKey = agentParsed?.rest ?? key;
const parts = rawKey.split(":").filter(Boolean);
if (parts.length >= 3) {
const [channel, kind, ...rest] = parts;
if (kind === "group" || kind === "channel") {
const id = rest.join(":");
return { channel, kind, id };
}
}
return null;
}
function isStorePathTemplate(store?: string): boolean {
return typeof store === "string" && store.includes("{agentId}");
}
function listExistingAgentIdsFromDisk(): string[] {
const root = resolveStateDir();
const agentsDir = path.join(root, "agents");
try {
const entries = fs.readdirSync(agentsDir, { withFileTypes: true });
return entries
.filter((entry) => entry.isDirectory())
.map((entry) => normalizeAgentId(entry.name))
.filter(Boolean);
} catch {
return [];
}
}
function listConfiguredAgentIds(cfg: OpenClawConfig): string[] {
const ids = new Set<string>();
const defaultId = normalizeAgentId(resolveDefaultAgentId(cfg));
ids.add(defaultId);
for (const entry of cfg.agents?.list ?? []) {
if (entry?.id) {
ids.add(normalizeAgentId(entry.id));
}
}
for (const id of listExistingAgentIdsFromDisk()) {
ids.add(id);
}
const sorted = Array.from(ids).filter(Boolean);
sorted.sort((a, b) => a.localeCompare(b));
return sorted.includes(defaultId)
? [defaultId, ...sorted.filter((id) => id !== defaultId)]
: sorted;
}
function normalizeFallbackList(values: readonly string[]): string[] {
const out: string[] = [];
const seen = new Set<string>();
for (const value of values) {
const trimmed = value.trim();
if (!trimmed) {
continue;
}
const key = normalizeLowercaseStringOrEmpty(trimmed);
if (seen.has(key)) {
continue;
}
seen.add(key);
out.push(trimmed);
}
return out;
}
function resolveGatewayAgentModel(
cfg: OpenClawConfig,
agentId: string,
): GatewayAgentRow["model"] | undefined {
const primary = resolveAgentEffectiveModelPrimary(cfg, agentId)?.trim();
const fallbackOverride = resolveAgentModelFallbacksOverride(cfg, agentId);
const defaultFallbacks = resolveAgentModelFallbackValues(cfg.agents?.defaults?.model);
const fallbacks = normalizeFallbackList(fallbackOverride ?? defaultFallbacks);
if (!primary && fallbacks.length === 0) {
return undefined;
}
return {
...(primary ? { primary } : {}),
...(fallbacks.length > 0 ? { fallbacks } : {}),
};
}
export function listAgentsForGateway(cfg: OpenClawConfig): {
defaultId: string;
mainKey: string;
scope: SessionScope;
agents: GatewayAgentRow[];
} {
const defaultId = normalizeAgentId(resolveDefaultAgentId(cfg));
const mainKey = normalizeMainKey(cfg.session?.mainKey);
const scope = cfg.session?.scope ?? "per-sender";
const configuredById = new Map<
string,
{ name?: string; identity?: GatewayAgentRow["identity"] }
>();
for (const entry of cfg.agents?.list ?? []) {
if (!entry?.id) {
continue;
}
const identity = entry.identity
? {
name: normalizeOptionalString(entry.identity.name),
theme: normalizeOptionalString(entry.identity.theme),
emoji: normalizeOptionalString(entry.identity.emoji),
avatar: normalizeOptionalString(entry.identity.avatar),
avatarUrl: resolveIdentityAvatarUrl(
cfg,
normalizeAgentId(entry.id),
normalizeOptionalString(entry.identity.avatar),
),
}
: undefined;
configuredById.set(normalizeAgentId(entry.id), {
name: normalizeOptionalString(entry.name),
identity,
});
}
const explicitIds = new Set(
(cfg.agents?.list ?? [])
.map((entry) => (entry?.id ? normalizeAgentId(entry.id) : ""))
.filter(Boolean),
);
const allowedIds = explicitIds.size > 0 ? new Set([...explicitIds, defaultId]) : null;
let agentIds = listConfiguredAgentIds(cfg).filter((id) =>
allowedIds ? allowedIds.has(id) : true,
);
if (mainKey && !agentIds.includes(mainKey) && (!allowedIds || allowedIds.has(mainKey))) {
agentIds = [...agentIds, mainKey];
}
const agents = agentIds.map((id) => {
const meta = configuredById.get(id);
const model = resolveGatewayAgentModel(cfg, id);
return Object.assign(
{
id,
name: meta?.name,
identity: meta?.identity,
workspace: resolveAgentWorkspaceDir(cfg, id),
agentRuntime: resolveAgentRuntimeMetadata(cfg, id),
},
model ? { model } : {},
);
});
return { defaultId, mainKey, scope, agents };
}
function buildGatewaySessionStoreScanTargets(params: {
cfg: OpenClawConfig;
key: string;
canonicalKey: string;
agentId: string;
}): string[] {
const targets = new Set<string>();
if (params.canonicalKey) {
targets.add(params.canonicalKey);
}
if (params.key && params.key !== params.canonicalKey) {
targets.add(params.key);
}
if (params.canonicalKey === "global" || params.canonicalKey === "unknown") {
return [...targets];
}
const agentMainKey = resolveAgentMainSessionKey({ cfg: params.cfg, agentId: params.agentId });
if (params.canonicalKey === agentMainKey) {
targets.add(`agent:${params.agentId}:main`);
}
return [...targets];
}
function resolveGatewaySessionStoreCandidates(
cfg: OpenClawConfig,
agentId: string,
): SessionStoreTarget[] {
const storeConfig = cfg.session?.store;
const defaultTarget = {
agentId,
storePath: resolveStorePath(storeConfig, { agentId }),
};
if (!isStorePathTemplate(storeConfig)) {
return [defaultTarget];
}
const targets = new Map<string, SessionStoreTarget>();
targets.set(defaultTarget.storePath, defaultTarget);
for (const target of resolveAllAgentSessionStoreTargetsSync(cfg)) {
if (target.agentId === agentId) {
targets.set(target.storePath, target);
}
}
return [...targets.values()];
}
function resolveGatewaySessionStoreLookup(params: {
cfg: OpenClawConfig;
key: string;
canonicalKey: string;
agentId: string;
initialStore?: Record<string, SessionEntry>;
}): {
storePath: string;
store: Record<string, SessionEntry>;
match: { entry: SessionEntry; key: string } | undefined;
} {
const scanTargets = buildGatewaySessionStoreScanTargets(params);
const candidates = resolveGatewaySessionStoreCandidates(params.cfg, params.agentId);
const fallback = candidates[0] ?? {
agentId: params.agentId,
storePath: resolveStorePath(params.cfg.session?.store, { agentId: params.agentId }),
};
let selectedStorePath = fallback.storePath;
let selectedStore = params.initialStore ?? loadSessionStore(fallback.storePath);
let selectedMatch = findFreshestStoreMatch(selectedStore, ...scanTargets);
let selectedUpdatedAt = selectedMatch?.entry.updatedAt ?? Number.NEGATIVE_INFINITY;
for (let index = 1; index < candidates.length; index += 1) {
const candidate = candidates[index];
if (!candidate) {
continue;
}
const store = loadSessionStore(candidate.storePath);
const match = findFreshestStoreMatch(store, ...scanTargets);
if (!match) {
continue;
}
const updatedAt = match.entry.updatedAt ?? 0;
// Mirror combined-store merge behavior so follow-up mutations target the
// same backing store that won the listing merge when ids collide.
if (!selectedMatch || updatedAt >= selectedUpdatedAt) {
selectedStorePath = candidate.storePath;
selectedStore = store;
selectedMatch = match;
selectedUpdatedAt = updatedAt;
}
}
return {
storePath: selectedStorePath,
store: selectedStore,
match: selectedMatch,
};
}
function resolveExplicitDeletedLegacyMainStoreTarget(params: {
cfg: OpenClawConfig;
key: string;
scanLegacyKeys?: boolean;
}): {
agentId: string;
storePath: string;
canonicalKey: string;
storeKeys: string[];
} | null {
const parsed = parseAgentSessionKey(params.key);
const legacyAgentId = normalizeAgentId(parsed?.agentId);
if (
!parsed ||
legacyAgentId !== DEFAULT_AGENT_ID ||
listAgentIds(params.cfg).includes(legacyAgentId)
) {
return null;
}
// Only preserve agent:main:* when it is backed by a discovered deleted-main store.
// Shared-store legacy aliases should continue remapping to the configured default agent.
const canonicalKey = resolveStoredSessionKeyForAgentStore({
cfg: params.cfg,
agentId: legacyAgentId,
sessionKey: params.key,
});
const agentMainKey = resolveAgentMainSessionKey({ cfg: params.cfg, agentId: legacyAgentId });
const legacyAgentMainKey = `agent:${legacyAgentId}:main`;
const lookupSeeds = Array.from(
new Set([params.key, canonicalKey, agentMainKey, legacyAgentMainKey]),
);
let best:
| {
storePath: string;
store: Record<string, SessionEntry>;