Skip to content

Commit 0d9a424

Browse files
authored
refactor: dedupe session-catalog cursor paging and sleep helper clones (#124569)
* refactor(plugin-sdk): dedupe session-catalog cursor paging into session-catalog-runtime The acpx Pi and opencode session catalogs carried byte-identical boundedLimit/encodeCursor/decodeCursor/optionalRawCursor/transcriptPage scaffolding (~114 duplicated lines each). Move one canonical copy into the private-local session-catalog-runtime SDK subpath both plugins already may import, and keep the plugin-named cursor guards as direct aliases. Net -87 production LOC; no behavior change (error strings, cursor canonical form, and byte budgets are unchanged). * refactor(core): replace private sleep() clones with canonical sleep helpers managed-linux readiness polling now uses @openclaw/retry sleepWithAbort with ref:false (preserving the clone's timer.unref behavior), and the embedded agent runner's async-task wait uses src/utils/sleep.ts. Both clones matched canonical semantics on real inputs (positive integer poll intervals). The update-managed-service-handoff copy stays: it lives inside a serialized standalone handoff script (String.raw template) that cannot import repo modules.
1 parent a118bfb commit 0d9a424

5 files changed

Lines changed: 160 additions & 256 deletions

File tree

‎extensions/acpx/src/pi-session-catalog.ts‎

Lines changed: 17 additions & 121 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,14 @@ import type {
44
SessionCatalogTranscriptItem,
55
SessionsCatalogReadResult,
66
} from "openclaw/plugin-sdk/session-catalog";
7+
import {
8+
boundSessionCatalogTranscriptPage,
9+
boundedSessionCatalogLimit,
10+
decodeSessionCatalogCursor,
11+
encodeSessionCatalogCursor,
12+
isExactSessionCatalogCursor,
13+
optionalSessionCatalogCursor,
14+
} from "openclaw/plugin-sdk/session-catalog-runtime";
715
import {
816
isRecord,
917
normalizeBoundedOptionalString as optionalPiString,
@@ -14,124 +22,12 @@ import { parsePiSessionTimestampMs } from "./pi-session-timestamp.js";
1422

1523
const LOCAL_HOST_ID = "gateway";
1624
const DEFAULT_PAGE_LIMIT = 20;
17-
const MAX_PAGE_LIMIT = 100;
1825
const MAX_SEARCH_LENGTH = 500;
19-
const MAX_CURSOR_LENGTH = 128;
20-
const MAX_TRANSCRIPT_ITEM_BYTES = 512 * 1024;
21-
const MAX_TRANSCRIPT_PAGE_BYTES = 20 * 1024 * 1024;
2226
const SESSION_ID_PATTERN = /^(?!-)[A-Za-z0-9._:-]{1,256}$/u;
2327

2428
export type PiSessionPage = { sessions: SessionCatalogSession[]; nextCursor?: string };
2529

26-
function boundedLimit(value: unknown, fallback = DEFAULT_PAGE_LIMIT): number {
27-
if (value === undefined) {
28-
return fallback;
29-
}
30-
if (!Number.isInteger(value) || Number(value) < 1 || Number(value) > MAX_PAGE_LIMIT) {
31-
throw new Error(`limit must be an integer between 1 and ${String(MAX_PAGE_LIMIT)}`);
32-
}
33-
return Number(value);
34-
}
35-
36-
function encodeCursor(offset: number): string {
37-
return Buffer.from(JSON.stringify({ offset }), "utf8").toString("base64url");
38-
}
39-
40-
function optionalRawCursor(value: unknown): string | undefined {
41-
if (value === undefined) {
42-
return undefined;
43-
}
44-
if (typeof value !== "string" || value.length === 0 || value.length > MAX_CURSOR_LENGTH) {
45-
throw new Error("cursor is invalid");
46-
}
47-
return value;
48-
}
49-
50-
function decodeCursor(value: unknown): number {
51-
const cursor = optionalRawCursor(value);
52-
if (cursor === undefined) {
53-
return 0;
54-
}
55-
try {
56-
const bytes = Buffer.from(cursor, "base64url");
57-
if (bytes.toString("base64url") !== cursor) {
58-
throw new Error("non-canonical base64url");
59-
}
60-
const parsed = JSON.parse(bytes.toString("utf8")) as unknown;
61-
if (!isRecord(parsed) || !Number.isSafeInteger(parsed.offset) || Number(parsed.offset) < 0) {
62-
throw new Error("invalid offset");
63-
}
64-
const offset = Number(parsed.offset);
65-
if (encodeCursor(offset) !== cursor) {
66-
throw new Error("non-canonical cursor payload");
67-
}
68-
return offset;
69-
} catch (error) {
70-
throw new Error("cursor is invalid", { cause: error });
71-
}
72-
}
73-
74-
export function isExactPiSessionCursor(value: unknown): value is string {
75-
if (typeof value !== "string") {
76-
return false;
77-
}
78-
try {
79-
decodeCursor(value);
80-
return true;
81-
} catch {
82-
return false;
83-
}
84-
}
85-
86-
function truncateUtf8(text: string, maxBytes: number): string {
87-
if (Buffer.byteLength(text, "utf8") <= maxBytes) {
88-
return text;
89-
}
90-
let low = 0;
91-
let high = text.length;
92-
while (low < high) {
93-
const middle = Math.ceil((low + high) / 2);
94-
if (Buffer.byteLength(text.slice(0, middle), "utf8") <= maxBytes - 3) {
95-
low = middle;
96-
} else {
97-
high = middle - 1;
98-
}
99-
}
100-
const end = low > 0 && /[\uD800-\uDBFF]/u.test(text.charAt(low - 1)) ? low - 1 : low;
101-
return `${text.slice(0, end)}…`;
102-
}
103-
104-
function transcriptPage(
105-
items: SessionCatalogTranscriptItem[],
106-
limit: number,
107-
offset: number,
108-
): { items: SessionCatalogTranscriptItem[]; nextCursor?: string } {
109-
const end = Math.max(0, items.length - offset);
110-
const start = Math.max(0, end - limit);
111-
const page: SessionCatalogTranscriptItem[] = [];
112-
let pageBytes = 2;
113-
for (let index = end - 1; index >= start; index -= 1) {
114-
const item = items[index];
115-
if (!item) {
116-
continue;
117-
}
118-
const bounded: SessionCatalogTranscriptItem = {
119-
...item,
120-
text: truncateUtf8(item.text ?? "", MAX_TRANSCRIPT_ITEM_BYTES),
121-
};
122-
const itemBytes = Buffer.byteLength(JSON.stringify(bounded), "utf8") + 1;
123-
if (page.length > 0 && pageBytes + itemBytes > MAX_TRANSCRIPT_PAGE_BYTES) {
124-
break;
125-
}
126-
page.unshift(bounded);
127-
pageBytes += itemBytes;
128-
}
129-
const consumed = offset + page.length;
130-
return {
131-
items: page,
132-
...(consumed < items.length ? { nextCursor: encodeCursor(consumed) } : {}),
133-
};
134-
}
30+
export const isExactPiSessionCursor = isExactSessionCatalogCursor;
13531

13632
function textFromContent(content: unknown): string {
13733
if (typeof content === "string") {
@@ -174,9 +70,9 @@ function parseListParams(value: unknown): { searchTerm?: string; limit: number;
17470
if (value.searchTerm !== undefined && !searchTerm) {
17571
throw new Error("searchTerm is invalid");
17672
}
177-
const cursor = optionalRawCursor(value.cursor);
73+
const cursor = optionalSessionCatalogCursor(value.cursor);
17874
return {
179-
limit: boundedLimit(value.limit),
75+
limit: boundedSessionCatalogLimit(value.limit),
18076
...(searchTerm ? { searchTerm } : {}),
18177
...(cursor ? { cursor } : {}),
18278
};
@@ -194,17 +90,17 @@ function parseReadParams(value: unknown): { threadId: string; limit: number; cur
19490
if (!threadId || !SESSION_ID_PATTERN.test(threadId)) {
19591
throw new Error("threadId is invalid");
19692
}
197-
const cursor = optionalRawCursor(value.cursor);
93+
const cursor = optionalSessionCatalogCursor(value.cursor);
19894
return {
19995
threadId,
200-
limit: boundedLimit(value.limit),
96+
limit: boundedSessionCatalogLimit(value.limit),
20197
...(cursor ? { cursor } : {}),
20298
};
20399
}
204100

205101
export async function listLocalPiSessionPage(value?: unknown): Promise<PiSessionPage> {
206102
const params = parseListParams(value);
207-
const offset = decodeCursor(params.cursor);
103+
const offset = decodeSessionCatalogCursor(params.cursor);
208104
const { summaries, hasMore } = await listPiSummaryPage(process.env, {
209105
offset,
210106
limit: params.limit,
@@ -213,7 +109,7 @@ export async function listLocalPiSessionPage(value?: unknown): Promise<PiSession
213109
const page = summaries.map(({ file: _file, version: _version, ...session }) => session);
214110
return {
215111
sessions: page,
216-
...(hasMore ? { nextCursor: encodeCursor(offset + page.length) } : {}),
112+
...(hasMore ? { nextCursor: encodeSessionCatalogCursor(offset + page.length) } : {}),
217113
};
218114
}
219115

@@ -369,9 +265,9 @@ export async function readLocalPiTranscriptPage(
369265
value: unknown,
370266
): Promise<SessionsCatalogReadResult> {
371267
const params = parseReadParams(value);
372-
const offset = decodeCursor(params.cursor);
268+
const offset = decodeSessionCatalogCursor(params.cursor);
373269
const items = piTranscriptItems(await readPiSessionById(params.threadId, process.env));
374-
const page = transcriptPage(items, params.limit, offset);
270+
const page = boundSessionCatalogTranscriptPage(items, params.limit, offset);
375271
return {
376272
hostId: LOCAL_HOST_ID,
377273
label: "Local Pi",

‎extensions/opencode/session-catalog.ts‎

Lines changed: 17 additions & 121 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,14 @@ import type {
55
SessionCatalogTranscriptItem,
66
SessionsCatalogReadResult,
77
} from "openclaw/plugin-sdk/session-catalog";
8+
import {
9+
boundSessionCatalogTranscriptPage,
10+
boundedSessionCatalogLimit,
11+
decodeSessionCatalogCursor,
12+
encodeSessionCatalogCursor,
13+
isExactSessionCatalogCursor,
14+
optionalSessionCatalogCursor,
15+
} from "openclaw/plugin-sdk/session-catalog-runtime";
816
import {
917
isRecord,
1018
normalizeBoundedOptionalString as optionalOpenCodeString,
@@ -17,13 +25,9 @@ import {
1725

1826
const LOCAL_HOST_ID = "gateway";
1927
const DEFAULT_PAGE_LIMIT = 20;
20-
const MAX_PAGE_LIMIT = 100;
2128
const MAX_SEARCH_LENGTH = 500;
22-
const MAX_CURSOR_LENGTH = 128;
2329
const MAX_CLI_LIST_SESSIONS = 10_000;
2430
const MAX_CLI_OUTPUT_BYTES = 32 * 1024 * 1024;
25-
const MAX_TRANSCRIPT_ITEM_BYTES = 512 * 1024;
26-
const MAX_TRANSCRIPT_PAGE_BYTES = 20 * 1024 * 1024;
2731
const CLI_TIMEOUT_MS = 30_000;
2832
const OPENCODE_QUERY_CACHE_TTL_MS = 32_000;
2933
const OPENCODE_QUERY_CACHE_MAX_ENTRIES = 32;
@@ -96,115 +100,7 @@ type OpenCodeReadParams = {
96100
cursor?: string;
97101
};
98102

99-
function boundedLimit(value: unknown, fallback = DEFAULT_PAGE_LIMIT): number {
100-
if (value === undefined) {
101-
return fallback;
102-
}
103-
if (!Number.isInteger(value) || Number(value) < 1 || Number(value) > MAX_PAGE_LIMIT) {
104-
throw new Error(`limit must be an integer between 1 and ${String(MAX_PAGE_LIMIT)}`);
105-
}
106-
return Number(value);
107-
}
108-
109-
function encodeCursor(offset: number): string {
110-
return Buffer.from(JSON.stringify({ offset }), "utf8").toString("base64url");
111-
}
112-
113-
function optionalRawCursor(value: unknown): string | undefined {
114-
if (value === undefined) {
115-
return undefined;
116-
}
117-
if (typeof value !== "string" || value.length === 0 || value.length > MAX_CURSOR_LENGTH) {
118-
throw new Error("cursor is invalid");
119-
}
120-
return value;
121-
}
122-
123-
function decodeCursor(value: unknown): number {
124-
const cursor = optionalRawCursor(value);
125-
if (cursor === undefined) {
126-
return 0;
127-
}
128-
try {
129-
const bytes = Buffer.from(cursor, "base64url");
130-
if (bytes.toString("base64url") !== cursor) {
131-
throw new Error("non-canonical base64url");
132-
}
133-
const parsed = JSON.parse(bytes.toString("utf8")) as unknown;
134-
if (!isRecord(parsed) || !Number.isSafeInteger(parsed.offset) || Number(parsed.offset) < 0) {
135-
throw new Error("invalid offset");
136-
}
137-
const offset = Number(parsed.offset);
138-
if (encodeCursor(offset) !== cursor) {
139-
throw new Error("non-canonical cursor payload");
140-
}
141-
return offset;
142-
} catch (error) {
143-
throw new Error("cursor is invalid", { cause: error });
144-
}
145-
}
146-
147-
export function isExactOpenCodeSessionCursor(value: unknown): value is string {
148-
if (typeof value !== "string") {
149-
return false;
150-
}
151-
try {
152-
decodeCursor(value);
153-
return true;
154-
} catch {
155-
return false;
156-
}
157-
}
158-
159-
function truncateUtf8(text: string, maxBytes: number): string {
160-
if (Buffer.byteLength(text, "utf8") <= maxBytes) {
161-
return text;
162-
}
163-
let low = 0;
164-
let high = text.length;
165-
while (low < high) {
166-
const middle = Math.ceil((low + high) / 2);
167-
if (Buffer.byteLength(text.slice(0, middle), "utf8") <= maxBytes - 3) {
168-
low = middle;
169-
} else {
170-
high = middle - 1;
171-
}
172-
}
173-
const end = low > 0 && /[\uD800-\uDBFF]/u.test(text.charAt(low - 1)) ? low - 1 : low;
174-
return `${text.slice(0, end)}…`;
175-
}
176-
177-
function transcriptPage(
178-
items: SessionCatalogTranscriptItem[],
179-
limit: number,
180-
offset: number,
181-
): { items: SessionCatalogTranscriptItem[]; nextCursor?: string } {
182-
const end = Math.max(0, items.length - offset);
183-
const start = Math.max(0, end - limit);
184-
const page: SessionCatalogTranscriptItem[] = [];
185-
let pageBytes = 2;
186-
for (let index = end - 1; index >= start; index -= 1) {
187-
const item = items[index];
188-
if (!item) {
189-
continue;
190-
}
191-
const bounded: SessionCatalogTranscriptItem = {
192-
...item,
193-
text: truncateUtf8(item.text ?? "", MAX_TRANSCRIPT_ITEM_BYTES),
194-
};
195-
const itemBytes = Buffer.byteLength(JSON.stringify(bounded), "utf8") + 1;
196-
if (page.length > 0 && pageBytes + itemBytes > MAX_TRANSCRIPT_PAGE_BYTES) {
197-
break;
198-
}
199-
page.unshift(bounded);
200-
pageBytes += itemBytes;
201-
}
202-
const consumed = offset + page.length;
203-
return {
204-
items: page,
205-
...(consumed < items.length ? { nextCursor: encodeCursor(consumed) } : {}),
206-
};
207-
}
103+
export const isExactOpenCodeSessionCursor = isExactSessionCatalogCursor;
208104

209105
function parseListParams(
210106
value: unknown,
@@ -225,9 +121,9 @@ function parseListParams(
225121
if (value.searchTerm !== undefined && !searchTerm) {
226122
throw new Error("searchTerm is invalid");
227123
}
228-
const cursor = optionalRawCursor(value.cursor);
124+
const cursor = optionalSessionCatalogCursor(value.cursor);
229125
return {
230-
limit: boundedLimit(value.limit),
126+
limit: boundedSessionCatalogLimit(value.limit),
231127
...(searchTerm ? { searchTerm } : {}),
232128
...(cursor ? { cursor } : {}),
233129
};
@@ -247,10 +143,10 @@ function parseReadParams(
247143
if (!threadId || !SESSION_ID_PATTERN.test(threadId)) {
248144
throw new Error("threadId is invalid");
249145
}
250-
const cursor = optionalRawCursor(value.cursor);
146+
const cursor = optionalSessionCatalogCursor(value.cursor);
251147
return {
252148
threadId,
253-
limit: boundedLimit(value.limit),
149+
limit: boundedSessionCatalogLimit(value.limit),
254150
...(cursor ? { cursor } : {}),
255151
};
256152
}
@@ -414,7 +310,7 @@ export async function listLocalOpenCodeSessionPage(
414310
options: OpenCodeQueryCacheOptions = {},
415311
): Promise<OpenCodeSessionPage> {
416312
const params = parseListParams(value);
417-
const offset = decodeCursor(params.cursor);
313+
const offset = decodeSessionCatalogCursor(params.cursor);
418314
const requestedCount = params.searchTerm
419315
? MAX_CLI_LIST_SESSIONS
420316
: Math.min(MAX_CLI_LIST_SESSIONS, offset + params.limit + 1);
@@ -446,7 +342,7 @@ export async function listLocalOpenCodeSessionPage(
446342
return {
447343
sessions: page,
448344
...(offset + page.length < sessions.length
449-
? { nextCursor: encodeCursor(offset + page.length) }
345+
? { nextCursor: encodeSessionCatalogCursor(offset + page.length) }
450346
: {}),
451347
};
452348
}
@@ -557,9 +453,9 @@ export async function readLocalOpenCodeTranscriptPage(
557453
value: unknown,
558454
): Promise<SessionsCatalogReadResult> {
559455
const params = parseReadParams(value);
560-
const offset = decodeCursor(params.cursor);
456+
const offset = decodeSessionCatalogCursor(params.cursor);
561457
const items = openCodeTranscriptItems(await exportOpenCodeSession(params.threadId));
562-
const page = transcriptPage(items, params.limit, offset);
458+
const page = boundSessionCatalogTranscriptPage(items, params.limit, offset);
563459
return {
564460
hostId: LOCAL_HOST_ID,
565461
label: "Local OpenCode",

0 commit comments

Comments
 (0)