opencode-prompt-logger 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +105 -525
- package/dist/core.d.ts +7 -46
- package/dist/detail-lines.d.ts +17 -0
- package/dist/gui-experimental.cjs +29 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2282 -71
- package/dist/index.js.map +15 -5
- package/dist/log/body.d.ts +41 -0
- package/dist/log/errors.d.ts +5 -0
- package/dist/log/limits.d.ts +30 -0
- package/dist/log/paths.d.ts +42 -0
- package/dist/log/sanitize.d.ts +16 -0
- package/dist/log/summary.d.ts +3 -0
- package/dist/log/types.d.ts +58 -0
- package/dist/log/v2.d.ts +155 -0
- package/dist/logging-indicator.d.ts +31 -0
- package/dist/rpc-client.d.ts +27 -0
- package/dist/rpc-client.js +585 -0
- package/dist/rpc-client.js.map +14 -0
- package/dist/rpc.d.ts +1437 -0
- package/dist/rpc.js +446 -0
- package/dist/rpc.js.map +12 -0
- package/dist/runtime-state.d.ts +35 -0
- package/dist/session-scope-client.d.ts +8 -0
- package/dist/session-scope.d.ts +65 -0
- package/dist/settings.d.ts +46 -0
- package/dist/tui-panel/detail.d.ts +28 -0
- package/dist/tui-panel/panel.d.ts +21 -0
- package/dist/tui-status.d.ts +25 -0
- package/dist/tui.d.ts +15 -0
- package/dist/tui.js +2571 -0
- package/dist/tui.js.map +25 -0
- package/dist/ui-support.d.ts +3 -0
- package/dist/view-model.d.ts +76 -0
- package/package.json +53 -10
package/dist/index.js.map
CHANGED
|
@@ -1,11 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/index.ts", "../src/core.ts"],
|
|
3
|
+
"sources": ["../src/index.ts", "../src/core.ts", "../src/log/limits.ts", "../src/log/errors.ts", "../src/log/paths.ts", "../src/log/v2.ts", "../src/log/body.ts", "../src/log/summary.ts", "../src/rpc.ts", "../src/settings.ts", "../src/session-scope.ts", "../src/runtime-state.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import { Plugin } from \"@opencode/plugin\"\nimport {\n CONTEXT_KINDS,\n assembledRecord,\n createWriter,\n httpRecord,\n isEnabled,\n resolveFile,\n resolveRotateBytes,\n shouldLogHttp,\n type Options,\n} from \"./core\"\n\n/**\n * Capture what is actually sent to the model: `event.system` is the fully\n * assembled system prompt (agent prompt + environment + AGENTS.md + skills),\n * and the `http.request` body is the provider-level payload after lowering.\n * Both are read-only observations; nothing is rewritten.\n */\nexport default Plugin.define({\n id: \"prompt-logger\",\n async setup(ctx) {\n const options = (ctx.options ?? {}) as Options\n\n // Disabled means idle: no hooks and no output file.\n if (!isEnabled(options)) return\n\n const write = createWriter(resolveFile(options), resolveRotateBytes(options))\n\n for (const kind of CONTEXT_KINDS) {\n await ctx.session.hook(kind, (event) => {\n write(assembledRecord(kind, event))\n })\n }\n\n if (shouldLogHttp(options)) {\n await ctx.session.hook(\"http.request\", async (event) => {\n write(await httpRecord(event))\n })\n }\n },\n})\n",
|
|
6
|
-
"
|
|
5
|
+
"import { statSync } from \"node:fs\"\nimport { Plugin } from \"@opencode/plugin\"\nimport {\n CONTEXT_KINDS,\n type WriteError,\n} from \"./core\"\nimport { EVENT_COALESCE_MS } from \"./log/limits\"\nimport { LogError } from \"./log/errors\"\nimport { inspectPath, resolveLogDirectory } from \"./log/paths\"\nimport {\n createV2Writer,\n disarmV2,\n invalidateV2,\n isV2Armed,\n resolveRetention,\n v2Delete,\n v2List,\n v2Prune,\n v2Read,\n v2Search,\n v2Status,\n} from \"./log/v2\"\nimport {\n CONTRACT_VERSION,\n PromptLogger,\n type ChangedEvent,\n type ChangedReason,\n type ListRequest,\n type ListResponse,\n type ReadRequest,\n type ReadResponse,\n type SearchRequest,\n type SearchResponse,\n type SettingsResponse,\n type StatusResponse,\n type TruncateRequest,\n type TruncateResponse,\n type UpdateSessionScopeRequest,\n type UpdateSessionScopeResponse,\n} from \"./rpc\"\nimport {\n SETTINGS_KEY,\n defaultSettings,\n isValidSettings,\n sanitizeSettings,\n type Settings,\n} from \"./settings\"\nimport {\n SESSION_SCOPE_KEY,\n changeSessionScope,\n emptySessionScope,\n sessionAllowed,\n} from \"./session-scope\"\nimport { createRuntimeState } from \"./runtime-state\"\n\ntype Registration = { dispose: () => Promise<void> }\ntype EventSink = {\n emit(name: \"changed\", data: ChangedEvent): Promise<void>\n emit(name: \"settingsChanged\", data: SettingsResponse): Promise<void>\n}\ntype ErrorContext = {\n error: (type: \"io\" | \"not_found\" | \"bad_request\" | \"forbidden\", message: string, data: {}) => unknown\n}\n\nfunction rpcFailure(context: ErrorContext, error: unknown): never {\n if (error instanceof LogError) {\n return context.error(error.code, error.message, {}) as never\n }\n return context.error(\"io\", \"the prompt store is unavailable\", {}) as never\n}\n\n/**\n * A scope change is one of three actions or one of two modes. Mixing both is\n * ambiguous, and selecting a session needs a real ID.\n */\nfunction validSessionScopeInput(input: UpdateSessionScopeRequest): boolean {\n if (input.mode !== undefined && input.mode !== \"all\" && input.mode !== \"only\") return false\n if (input.action !== undefined && input.action !== \"only\" && input.action !== \"disarm\" && input.action !== \"clear\") {\n return false\n }\n if (input.mode !== undefined && input.action !== undefined) return false\n if (input.mode === undefined && input.action === undefined) return false\n if (input.sessionID !== undefined) {\n if (typeof input.sessionID !== \"string\" || input.sessionID.length > 200) return false\n }\n if (input.action === \"only\" || input.action === \"disarm\") {\n if (typeof input.sessionID !== \"string\" || input.sessionID.trim() === \"\") return false\n }\n return true\n}\n\n/**\n * Capture what is actually sent to the model: `event.system` is the fully\n * assembled system prompt (agent prompt + environment + AGENTS.md + skills),\n * and the `http.request` body is the provider-level payload after lowering.\n * Both are read-only observations; nothing is rewritten.\n *\n * The store is per session: message and system dedupe, one request line per\n * model call and the raw HTTP body as a gzip/binary blob. The viewer RPC is\n * registered even when logging is disabled.\n */\nexport default Plugin.define({\n id: \"prompt-logger\",\n async setup(ctx) {\n // The server storage is the only source of truth. The configuration file\n // registers the plugin; it does not carry settings.\n let initialSettings: Settings\n try {\n const stored = await ctx.storage.get(SETTINGS_KEY)\n initialSettings = sanitizeSettings(stored)\n if (stored === undefined || !isValidSettings(stored)) {\n try {\n await ctx.storage.set(SETTINGS_KEY, initialSettings)\n } catch (error) {\n console.error(`prompt-logger: could not persist the initial settings: ${String(error)}`)\n }\n }\n } catch (error) {\n console.error(`prompt-logger: could not read settings: ${String(error)}`)\n initialSettings = sanitizeSettings(undefined)\n }\n\n const root = resolveLogDirectory(\n initialSettings.directory === \"\" ? undefined : initialSettings.directory,\n ctx.location?.directory,\n )\n\n const runtime = createRuntimeState(\n initialSettings,\n {\n settings: async () => {\n const stored = await ctx.storage.get(SETTINGS_KEY)\n if (stored !== undefined) return stored\n // If the first-run write failed, keep the defaults instead of\n // dropping the runtime to an empty value.\n return initialSettings\n },\n scope: () => ctx.storage.get(SESSION_SCOPE_KEY),\n },\n {\n onError: (source, error) => {\n const label = source === \"settings\" ? \"settings\" : \"the session scope\"\n console.error(`prompt-logger: could not read ${label}: ${String(error)}`)\n },\n },\n )\n await runtime.refresh(true)\n\n let lastWriteAt: string | null = null\n let lastWriteError: WriteError | null = null\n let events: EventSink | null = null\n let notifyTimer: ReturnType<typeof setTimeout> | null = null\n let pendingReason: ChangedReason | null = null\n\n const notify = (reason: ChangedReason): void => {\n // Without a viewer there is nobody to notify; the first viewer builds\n // its page from disk and does not need a replay of past writes.\n if (!isV2Armed(root)) return\n pendingReason = reason\n if (notifyTimer !== null) return\n notifyTimer = setTimeout(() => {\n notifyTimer = null\n const pending = pendingReason\n pendingReason = null\n if (events === null || pending === null) return\n void events\n .emit(\"changed\", { store: root, reason: pending, at: new Date().toISOString() })\n .catch(() => {})\n }, EVENT_COALESCE_MS)\n ;(notifyTimer as { unref?: () => void }).unref?.()\n }\n\n const emitSettings = async (): Promise<void> => {\n if (events === null) return\n try {\n await events.emit(\"settingsChanged\", {\n settings: runtime.settings,\n sessionScope: runtime.scope,\n })\n } catch {\n // The event stream is best-effort; clients also read the settings.\n }\n }\n\n const reportError = (error: unknown): void => {\n lastWriteError = {\n at: new Date().toISOString(),\n message: error instanceof Error ? error.message : String(error),\n }\n notify(\"error\")\n }\n\n const writer = createV2Writer(root, {\n onWrite: (written) => {\n lastWriteAt = written.at\n lastWriteError = null\n notify(\"append\")\n },\n onError: reportError,\n })\n\n const registrations: Registration[] = []\n for (const kind of CONTEXT_KINDS) {\n registrations.push(\n await ctx.session.hook(kind, async (event) => {\n await runtime.refresh()\n if (!runtime.settings.enabled) return\n if (!sessionAllowed(runtime.scope, event.sessionID)) return\n writer.writeAssembled(kind, event)\n }),\n )\n }\n registrations.push(\n await ctx.session.hook(\"http.request\", async (event) => {\n await runtime.refresh()\n if (!runtime.settings.enabled || !runtime.settings.http) return\n if (!sessionAllowed(runtime.scope, event.sessionID)) return\n await writer.writeHttp(event)\n }),\n )\n\n const retentionPolicy = () => resolveRetention(runtime.settings)\n\n const prune = async (): Promise<void> => {\n await runtime.refresh()\n if (!runtime.settings.enabled) return\n try {\n v2Prune(root, retentionPolicy(), writer.active)\n } catch (error) {\n console.error(`prompt-logger: retention failed: ${String(error)}`)\n }\n }\n const initialPrune = setTimeout(() => void prune(), 5_000)\n ;(initialPrune as { unref?: () => void }).unref?.()\n const pruneTimer = setInterval(() => void prune(), 60 * 60 * 1000)\n ;(pruneTimer as { unref?: () => void }).unref?.()\n\n const registration = await ctx.rpc\n .register(PromptLogger, {\n status: async (): Promise<StatusResponse> => {\n await runtime.refresh(true)\n const settings = runtime.settings\n const info = v2Status(root)\n const policy = retentionPolicy()\n const state = inspectPath(root)\n const stats = (() => {\n try {\n return statSync(root)\n } catch {\n return null\n }\n })()\n return {\n version: CONTRACT_VERSION,\n store: {\n path: root,\n exists: stats !== null,\n bytes: info.bytes,\n mtimeMs: stats?.mtimeMs ?? null,\n directory: stats?.isDirectory() ?? false,\n symlink: state.symlink,\n mode: state.mode,\n directoryMode: state.directoryMode,\n warnings: info.warnings,\n },\n settings: {\n ...settings,\n retention: {\n maxTotalBytes: Number.isFinite(policy.maxTotalBytes) ? policy.maxTotalBytes : null,\n maxAgeDays: policy.maxAgeDays,\n maxSessions: Number.isFinite(policy.maxSessions) ? policy.maxSessions : null,\n },\n },\n sessionScope: runtime.scope,\n cache: {\n requests: info.requests,\n requestBytes: info.requestBytes,\n lastScanMs: info.lastScanMs,\n error: info.error,\n },\n lastWriteAt,\n lastWriteError,\n }\n },\n\n list: async (input): Promise<ListResponse> => {\n return v2List(root, input as ListRequest)\n },\n\n read: async (input, context): Promise<ReadResponse> => {\n try {\n const key = (input as ReadRequest).key\n if (key === undefined) {\n return context.error(\"bad_request\", \"a read needs a key\", {}) as never\n }\n const result = v2Read(root, key, (input as ReadRequest).maxBytes)\n if (result.notFound) return context.error(\"not_found\", \"log entry not found\", {}) as never\n return {\n record: result.record,\n bytes: result.bytes,\n truncated: result.truncated,\n moreAvailable: result.moreAvailable,\n fullBytes: result.fullBytes,\n paths: result.paths,\n }\n } catch (error) {\n return rpcFailure(context, error)\n }\n },\n\n search: async (input, context): Promise<SearchResponse> => {\n try {\n return await v2Search(root, input as SearchRequest, context.signal)\n } catch (error) {\n return rpcFailure(context, error)\n }\n },\n\n truncate: async (input, context): Promise<TruncateResponse> => {\n if (!runtime.settings.maintenance) {\n return context.error(\"forbidden\", \"delete actions are disabled\", {}) as never\n }\n try {\n const request = input as TruncateRequest\n if (request.target === \"current\" && request.sessionID === undefined) {\n return context.error(\"bad_request\", \"sessionID is required to delete one session\", {}) as never\n }\n const bytesFreed = v2Delete(root, request.target, request.sessionID)\n invalidateV2(root)\n notify(\"truncate\")\n return { target: request.target, bytesFreed }\n } catch (error) {\n return rpcFailure(context, error)\n }\n },\n\n getSettings: async (): Promise<SettingsResponse> => {\n await runtime.refresh(true)\n return { settings: runtime.settings, sessionScope: runtime.scope }\n },\n\n setSettings: async (input, context): Promise<SettingsResponse> => {\n const request = (input as { settings?: unknown }).settings\n if (!isValidSettings(request)) return context.error(\"bad_request\", \"invalid settings\", {}) as never\n const next = sanitizeSettings(request)\n // Another location may have changed the master switch since this\n // location last read it; use the current value for the prune decision.\n await runtime.refresh(true)\n try {\n await ctx.storage.set(SETTINGS_KEY, next)\n } catch (error) {\n console.error(`prompt-logger: could not persist settings: ${String(error)}`)\n return context.error(\"io\", \"could not persist settings\", {}) as never\n }\n const wasEnabled = runtime.settings.enabled\n runtime.applySettings(next)\n if (!wasEnabled && next.enabled) void prune()\n await emitSettings()\n return { settings: runtime.settings, sessionScope: runtime.scope }\n },\n\n resetSettings: async (_input, context): Promise<SettingsResponse> => {\n const next = defaultSettings()\n try {\n await ctx.storage.set(SETTINGS_KEY, next)\n await ctx.storage.remove(SESSION_SCOPE_KEY)\n } catch (error) {\n console.error(`prompt-logger: could not reset settings: ${String(error)}`)\n return context.error(\"io\", \"could not reset settings\", {}) as never\n }\n const wasEnabled = runtime.settings.enabled\n runtime.applySettings(next)\n runtime.applyScope(emptySessionScope())\n if (!wasEnabled && next.enabled) void prune()\n await emitSettings()\n return { settings: runtime.settings, sessionScope: runtime.scope }\n },\n\n updateSessionScope: async (input, context): Promise<UpdateSessionScopeResponse> => {\n const request = input as UpdateSessionScopeRequest\n if (!validSessionScopeInput(request)) {\n return context.error(\"bad_request\", \"invalid session scope\", {}) as never\n }\n // The scope and the master switch may have been changed elsewhere;\n // compute the transition from the current state, not a stale copy.\n await runtime.refresh(true)\n const next = changeSessionScope(runtime.scope, request)\n\n // Persist the limited scope before enabling logging: if the settings\n // write fails, logging stays off instead of falling back to all.\n try {\n await ctx.storage.set(SESSION_SCOPE_KEY, { mode: next.mode, sessions: next.sessions })\n } catch (error) {\n console.error(`prompt-logger: could not persist the session scope: ${String(error)}`)\n return context.error(\"io\", \"could not persist the session scope\", {}) as never\n }\n runtime.applyScope(next)\n\n const wasEnabled = runtime.settings.enabled\n if (request.action === \"only\" && !runtime.settings.enabled) {\n const nextSettings = { ...runtime.settings, enabled: true }\n try {\n await ctx.storage.set(SETTINGS_KEY, nextSettings)\n } catch (error) {\n console.error(`prompt-logger: could not persist settings: ${String(error)}`)\n return context.error(\"io\", \"could not persist settings\", {}) as never\n }\n runtime.applySettings(nextSettings)\n }\n if (!wasEnabled && runtime.settings.enabled) void prune()\n await emitSettings()\n return { sessionScope: runtime.scope, settings: runtime.settings }\n },\n })\n .catch((error: unknown) => {\n console.error(`prompt-logger: could not register the viewer rpc: ${String(error)}`)\n return null\n })\n\n if (registration !== null) events = registration.events as unknown as EventSink\n\n return async () => {\n if (notifyTimer !== null) {\n clearTimeout(notifyTimer)\n notifyTimer = null\n }\n clearInterval(pruneTimer)\n clearTimeout(initialPrune)\n invalidateV2(root)\n disarmV2(root)\n await registration?.dispose()\n for (const hook of registrations) await hook.dispose()\n }\n },\n})\n",
|
|
6
|
+
"/** Default disk budget when no setting is configured: 256 MiB. */\nexport const DEFAULT_DISK_BUDGET = 256 * 1024 * 1024\n\n/** Model request kinds captured through one hook each. */\nexport const CONTEXT_KINDS = [\"context\", \"compaction\", \"generate\", \"title\"] as const\n\nexport type ContextKind = (typeof CONTEXT_KINDS)[number]\n\n/**\n * Structural view of the `context`, `compaction`, `generate` and `title` hook\n * events. `agent` and `tools` are only present on the kinds that carry them\n * (`title` has neither), so every field accepts the shape of the event it\n * actually receives.\n */\nexport type AssembledEvent = {\n readonly sessionID: string\n readonly model?: unknown\n readonly system?: unknown\n readonly messages?: unknown\n readonly agent?: unknown\n readonly tools?: Record<string, unknown>\n}\n\n/** Structural view of the `http.request` hook event. */\nexport type HttpEvent = {\n readonly sessionID: string\n readonly agent: unknown\n readonly model: unknown\n readonly kind: string\n readonly request: Request\n}\n\nexport type WriteError = {\n readonly at: string\n readonly code?: string\n readonly message: string\n}\n",
|
|
7
|
+
"/** Entries returned by one `list` call. */\nexport const DEFAULT_PAGE = 50\nexport const MAX_PAGE = 200\n\n/** One request returned by `read`, before the viewer asks for more. */\nexport const MAX_RECORD_BYTES = 2 * 1024 * 1024\n\n/** Hard ceiling for an explicit \"load complete entry\" read. */\nexport const MAX_FULL_RECORD_BYTES = 16 * 1024 * 1024\n\n/** A full-text search stops at whichever budget expires first. */\nexport const MAX_SEARCH_BYTES = 128 * 1024 * 1024\nexport const MAX_SEARCH_MS = 2_000\nexport const MAX_SEARCH_QUERY = 500\nexport const MAX_SEARCH_RESULTS = 100\n\n/** One `changed` event per second at most, however busy the store is. */\nexport const EVENT_COALESCE_MS = 1_000\n\n/**\n * Bench ceilings. They are intentionally loose: a regression that parses a\n * whole request or rescans a session file is orders of magnitude slower.\n */\nexport const BENCH_BUDGETS = {\n listMs: 20,\n readMs: 100,\n searchMs: 2_000,\n heapMb: 256,\n} as const\n\nexport function clampInteger(value: unknown, min: number, max: number, fallback: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return fallback\n return Math.min(max, Math.max(min, Math.round(value)))\n}\n\nexport function clampPage(value: unknown): number {\n return clampInteger(value, 1, MAX_PAGE, DEFAULT_PAGE)\n}\n\nexport function clampReadBytes(value: unknown): number {\n return clampInteger(value, 1024, MAX_FULL_RECORD_BYTES, MAX_RECORD_BYTES)\n}\n\nexport function clampSearchBytes(value: unknown): number {\n return clampInteger(value, 1024 * 1024, MAX_SEARCH_BYTES, MAX_SEARCH_BYTES)\n}\n\nexport function clampSearchMs(value: unknown): number {\n return clampInteger(value, 100, MAX_SEARCH_MS, MAX_SEARCH_MS)\n}\n\nexport function boundedString(value: unknown, maxLength: number): string | undefined {\n if (typeof value !== \"string\") return undefined\n const trimmed = value.trim()\n if (trimmed === \"\") return undefined\n return trimmed.length > maxLength ? trimmed.slice(0, maxLength) : trimmed\n}\n",
|
|
8
|
+
"export type LogErrorCode = \"bad_request\" | \"not_found\" | \"io\"\n\nexport class LogError extends Error {\n readonly code: LogErrorCode\n\n constructor(code: LogErrorCode, message: string) {\n super(message)\n this.name = \"LogError\"\n this.code = code\n }\n}\n",
|
|
9
|
+
"import { chmodSync, lstatSync, statSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { dirname, isAbsolute, join, resolve } from \"node:path\"\n\n/**\n * The store lives in its own directory, never directly in the shared `opencode`\n * tree. That lets the plugin keep the directory private (`0700`) without\n * touching a directory OpenCode and every other plugin also write to.\n *\n * - Windows: `%LOCALAPPDATA%\\opencode\\prompt-logger`\n * - macOS: `~/Library/Application Support/opencode/prompt-logger`\n * - Linux/other: `$XDG_STATE_HOME/opencode/prompt-logger`,\n * falling back to `~/.local/state/opencode/prompt-logger`\n *\n * Pure by design so every OS can be asserted from any machine.\n */\nexport function defaultDir(\n env: Record<string, string | undefined> = process.env,\n platform: string = process.platform,\n): string {\n const name = join(\"opencode\", \"prompt-logger\")\n if (platform === \"win32\") {\n return join(env.LOCALAPPDATA ?? join(homedir(), \"AppData\", \"Local\"), name)\n }\n if (platform === \"darwin\") {\n return join(homedir(), \"Library\", \"Application Support\", name)\n }\n return join(env.XDG_STATE_HOME ?? join(homedir(), \".local\", \"state\"), name)\n}\n\n/** Expand a leading `~` or `~/` the way every shell does. */\nexport function expandHome(path: string, home: string = homedir()): string {\n if (path === \"~\") return home\n if (path.startsWith(\"~/\") || path.startsWith(\"~\\\\\")) return join(home, path.slice(2))\n return path\n}\n\n/**\n * Resolve the effective store root. A configured path may be absolute, start\n * with `~`, or be relative to the project location. The result is always an\n * absolute path, so the writer, the reader and the UI act on the same store.\n */\nexport function resolveLogDirectory(\n configured: string | undefined,\n base?: string,\n env: Record<string, string | undefined> = process.env,\n platform: string = process.platform,\n): string {\n if (configured === undefined || configured === \"\") return resolve(defaultDir(env, platform))\n const expanded = expandHome(configured)\n return isAbsolute(expanded) ? resolve(expanded) : resolve(base ?? process.cwd(), expanded)\n}\n\nconst POSIX = process.platform !== \"win32\"\n\n/**\n * Keep the plugin's own directory private. A configured root is not ours to\n * chmod, but the per-session directories created inside it are.\n */\nexport function hardenDirectory(dir: string): void {\n if (!POSIX) return\n try {\n chmodSync(dir, 0o700)\n } catch {\n // A read-only or foreign directory: the file mode still protects it.\n }\n}\n\n/** The store carries unredacted prompts, so every file is owner-only on POSIX. */\nexport function hardenFile(file: string): void {\n if (!POSIX) return\n try {\n if (statSync(file).isFile()) chmodSync(file, 0o600)\n } catch {\n // Missing file or a directory at the path: the caller reports the error.\n }\n}\n\nexport type PathState = {\n readonly exists: boolean\n readonly regular: boolean\n readonly symlink: boolean\n readonly mode: number | null\n readonly directoryMode: number | null\n}\n\n/**\n * The filesystem facts the UI needs: whether the path exists, its mode and\n * whether it is a symlink. It never changes anything. The store-specific\n * warnings are built by the v2 status, because they depend on it being a\n * directory rather than a file.\n */\nexport function inspectPath(file: string): PathState {\n let stats\n try {\n stats = statSync(file)\n } catch {\n return {\n exists: false,\n regular: false,\n symlink: false,\n mode: null,\n directoryMode: null,\n }\n }\n\n let symlink = false\n try {\n symlink = lstatSync(file).isSymbolicLink()\n } catch {\n // The path disappeared between stat and lstat: report what stat saw.\n }\n\n let directoryMode: number | null = null\n try {\n directoryMode = statSync(dirname(file)).mode & 0o777\n } catch {\n // The parent is gone: no mode to judge.\n }\n\n return {\n exists: true,\n regular: stats.isFile(),\n symlink,\n mode: stats.mode & 0o777,\n directoryMode,\n }\n}\n",
|
|
10
|
+
"import { createHash, randomUUID } from \"node:crypto\"\nimport {\n appendFileSync,\n closeSync,\n existsSync,\n mkdirSync,\n openSync,\n readFileSync,\n readdirSync,\n readSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\"\nimport { join } from \"node:path\"\nimport type { AssembledEvent, HttpEvent } from \"../core\"\nimport { captureBodyBytes, decodeStoredBody, sliceUtf8, type BodyEncoding } from \"./body\"\nimport {\n MAX_FULL_RECORD_BYTES,\n MAX_RECORD_BYTES,\n MAX_SEARCH_QUERY,\n MAX_SEARCH_RESULTS,\n boundedString,\n clampInteger,\n clampPage,\n clampReadBytes,\n clampSearchBytes,\n clampSearchMs,\n} from \"./limits\"\nimport { LogError } from \"./errors\"\nimport { hardenDirectory, hardenFile, inspectPath } from \"./paths\"\nimport { modelRef } from \"./summary\"\nimport type {\n LogFilters,\n LogSummary,\n ModelRef,\n SearchInput,\n SearchMatch,\n SearchOutput,\n} from \"./types\"\n\nconst V2 = 2\nconst SESSION_DIR = \"sessions\"\nconst MESSAGES_FILE = \"messages.ndjson\"\nconst SYSTEMS_FILE = \"systems.ndjson\"\nconst REQUESTS_FILE = \"requests.ndjson\"\nconst BODIES_DIR = \"bodies\"\n\nexport type V2Retention = {\n readonly maxTotalBytes: number\n readonly maxAgeDays: number\n readonly maxSessions: number\n}\n\n/** The retention policy derived from the effective settings. */\nexport function resolveRetention(settings: {\n readonly diskBudget: number\n readonly retentionMaxAgeDays: number\n readonly retentionMaxSessions: number\n}): V2Retention {\n return {\n maxTotalBytes: settings.diskBudget > 0 ? settings.diskBudget : Number.POSITIVE_INFINITY,\n maxAgeDays: settings.retentionMaxAgeDays,\n maxSessions: settings.retentionMaxSessions > 0 ? settings.retentionMaxSessions : Number.POSITIVE_INFINITY,\n }\n}\n\ntype V2AssembledLine = {\n readonly v: number\n readonly type: \"assembled\"\n readonly requestID: string\n readonly at: string\n readonly kind: string\n readonly sessionID: string\n readonly agent?: string\n readonly model?: unknown\n readonly systemHash: string\n readonly messageHashes: readonly string[]\n readonly tools: readonly string[]\n readonly messages: number\n readonly bytes: number\n}\n\ntype V2HttpLine = {\n readonly v: number\n readonly type: \"http\"\n readonly requestID: string\n readonly at: string\n readonly kind: string\n readonly sessionID: string\n readonly agent?: string\n readonly model?: unknown\n readonly url: string\n readonly bodyHash: string\n readonly bodyEncoding: BodyEncoding\n readonly contentType?: string | null\n readonly bodyBytes: number\n readonly decodedBytes?: number | null\n readonly truncated?: true\n readonly bytes: number\n}\n\ntype V2Entry = {\n readonly key: string\n readonly cursor: string\n readonly sessionDir: string\n readonly sessionID: string\n readonly requestID: string\n at: string\n kind: string\n type: \"assembled\" | \"http\"\n agent: string | null\n model: ModelRef | null\n bytes: number\n messages: number | null\n hasBody: boolean\n bodyBytes: number | null\n assembled: V2AssembledLine | null\n http: V2HttpLine | null\n}\n\ntype SessionCache = {\n readonly dir: string\n readonly file: string\n size: number\n entries: Map<string, V2Entry>\n}\n\ntype Cache = {\n readonly root: string\n sessions: Map<string, SessionCache>\n byKey: Map<string, V2Entry>\n sorted: V2Entry[]\n requestBytes: number\n lastScanMs: number\n error: string | null\n}\n\nconst caches = new Map<string, Cache>()\nconst readCaches = new Map<string, MapCache>()\nconst searchCaches = new Map<string, { at: number; output: SearchOutput }>()\nconst armedV2 = new Set<string>()\n\n/** A viewer has read from this store; writes may now emit change events. */\nexport function armV2(root: string): void {\n armedV2.add(root)\n}\n\nexport function isV2Armed(root: string): boolean {\n return armedV2.has(root)\n}\n\nexport function disarmV2(root: string): void {\n armedV2.delete(root)\n}\n\nconst MAX_READ_CACHES = 8\nconst MAX_READ_CACHE_BYTES = 64 * 1024 * 1024\nconst MAX_SESSION_MAP_BYTES = 64 * 1024 * 1024\nconst STREAM_CHUNK_BYTES = 1024 * 1024\n\ntype MapCache = {\n readonly key: string\n readonly systemsFile: string\n readonly messagesFile: string\n systemsSize: number\n messagesSize: number\n systems: Map<string, unknown> | null\n messages: Map<string, unknown> | null\n bytes: number\n}\n\nfunction sha256(value: string | Buffer): string {\n return createHash(\"sha256\").update(value).digest(\"hex\")\n}\n\nfunction safeDirName(sessionID: string): string {\n const safe = sessionID.replace(/[^A-Za-z0-9._-]/g, \"_\").slice(0, 80)\n const suffix = sha256(sessionID).slice(0, 16)\n return `${safe === \"\" || safe === \".\" || safe === \"..\" ? \"session\" : safe}-${suffix}`\n}\n\nfunction sessionsRoot(root: string): string {\n return join(root, SESSION_DIR)\n}\n\nfunction sessionDir(root: string, sessionDirName: string): string {\n return join(sessionsRoot(root), sessionDirName)\n}\n\nfunction line(value: unknown): string {\n return `${JSON.stringify(value)}\\n`\n}\n\nfunction hashSet(file: string): Set<string> {\n try {\n const text = readFileSync(file, \"utf8\")\n const set = new Set<string>()\n for (const entry of text.split(\"\\n\")) {\n const match = /^\\{\"v\":2,\"hash\":\"([^\"]+)\"/.exec(entry)\n if (match?.[1] !== undefined) set.add(match[1])\n }\n return set\n } catch {\n return new Set()\n }\n}\n\nconst hardenedFiles = new Set<string>()\n\nfunction appendLines(file: string, lines: readonly string[]): void {\n if (lines.length === 0) return\n appendFileSync(file, lines.join(\"\\n\") + \"\\n\", { mode: 0o600 })\n // The mode is applied when the file is created. Only a pre-existing file\n // needs a chmod, and doing it once keeps the model-request path free of\n // extra syscalls.\n if (!hardenedFiles.has(file)) {\n hardenFile(file)\n hardenedFiles.add(file)\n }\n}\n\nfunction ensureSessionRoot(root: string): string {\n mkdirSync(root, { recursive: true, mode: 0o700 })\n hardenDirectory(root)\n const dir = sessionsRoot(root)\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n hardenDirectory(dir)\n return dir\n}\n\nfunction ensureSessionDir(root: string, sessionID: string): string {\n ensureSessionRoot(root)\n const dir = join(sessionsRoot(root), safeDirName(sessionID))\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n hardenDirectory(dir)\n return dir\n}\n\nconst PENDING_TTL_MS = 5 * 60 * 1000\n\ntype SessionWriter = {\n readonly dir: string\n readonly requestsFile: string\n readonly systemsFile: string\n readonly messagesFile: string\n readonly bodiesDir: string\n knownSystems: Set<string> | null\n knownMessages: Set<string> | null\n readonly pending: Map<string, Array<{ readonly id: string; readonly at: number }>>\n}\n\nexport type V2Writer = {\n readonly writeAssembled: (kind: string, event: AssembledEvent) => void\n readonly writeHttp: (event: HttpEvent) => Promise<void>\n readonly active: Set<string>\n}\n\nexport type V2WriterOptions = {\n readonly onWrite?: (written: { readonly at: string }) => void\n readonly onError?: (error: unknown) => void\n}\n\n/** The HTTP kind an assembled kind belongs to. */\nfunction httpKind(kind: string): string {\n return kind === \"context\" ? \"primary\" : kind\n}\n\nexport function createV2Writer(root: string, options: V2WriterOptions = {}): V2Writer {\n const sessions = new Map<string, SessionWriter>()\n const active = new Set<string>()\n // Keep the hot per-session hash sets bounded. A long-running server can see\n // thousands of sessions; reloading a missing session from disk is cheap and\n // only happens when that session is written again.\n const MAX_CACHED_SESSIONS = 32\n\n const fail = (error: unknown): void => {\n try {\n options.onError?.(error)\n } catch {\n // Reporting an error must not raise another one.\n }\n }\n\n const evict = (): void => {\n if (sessions.size <= MAX_CACHED_SESSIONS) return\n const now = Date.now()\n for (const [id, writer] of sessions) {\n let live = false\n for (const [kind, queue] of writer.pending) {\n while (queue.length > 0 && now - queue[0]!.at > PENDING_TTL_MS) queue.shift()\n if (queue.length === 0) writer.pending.delete(kind)\n else live = true\n }\n if (live) continue\n sessions.delete(id)\n return\n }\n // Every cached session has a request waiting for its HTTP body. Keep them;\n // the map will shrink once those requests finish.\n }\n\n const session = (sessionID: string): SessionWriter => {\n const existing = sessions.get(sessionID)\n if (existing !== undefined) {\n // A viewer can delete a session, and retention can prune one, while this\n // writer still holds its directory and hash sets. Recreate it instead of\n // appending to a path that no longer exists.\n if (!existsSync(existing.dir)) {\n sessions.delete(sessionID)\n } else {\n // Map insertion order doubles as an LRU.\n sessions.delete(sessionID)\n sessions.set(sessionID, existing)\n return existing\n }\n }\n const dir = ensureSessionDir(root, sessionID)\n active.add(safeDirName(sessionID))\n const next: SessionWriter = {\n dir,\n requestsFile: join(dir, REQUESTS_FILE),\n systemsFile: join(dir, SYSTEMS_FILE),\n messagesFile: join(dir, MESSAGES_FILE),\n bodiesDir: join(dir, BODIES_DIR),\n knownSystems: null,\n knownMessages: null,\n pending: new Map(),\n }\n sessions.set(sessionID, next)\n evict()\n return next\n }\n\n const writeAssembled = (kind: string, event: AssembledEvent): void => {\n try {\n const current = session(event.sessionID)\n current.knownSystems ??= hashSet(current.systemsFile)\n current.knownMessages ??= hashSet(current.messagesFile)\n\n const systemJson = JSON.stringify(event.system ?? [])\n const systemHash = sha256(systemJson)\n const systemLines: string[] = []\n if (!current.knownSystems.has(systemHash)) {\n systemLines.push(`{\"v\":2,\"hash\":\"${systemHash}\",\"system\":${systemJson}}`)\n current.knownSystems.add(systemHash)\n }\n\n const messages = Array.isArray(event.messages) ? event.messages : []\n const messageHashes: string[] = []\n const messageLines: string[] = []\n let messageBytes = 0\n for (const message of messages) {\n const json = JSON.stringify(message) ?? \"null\"\n const hash = sha256(json)\n messageHashes.push(hash)\n messageBytes += Buffer.byteLength(json, \"utf8\")\n if (!current.knownMessages.has(hash)) {\n messageLines.push(`{\"v\":2,\"hash\":\"${hash}\",\"message\":${json}}`)\n current.knownMessages.add(hash)\n }\n }\n\n const tools = event.tools === undefined ? [] : Object.keys(event.tools)\n const bytes =\n Buffer.byteLength(systemJson, \"utf8\") +\n messageBytes +\n tools.reduce((total, tool) => total + Buffer.byteLength(tool, \"utf8\"), 0)\n\n appendLines(current.systemsFile, systemLines)\n appendLines(current.messagesFile, messageLines)\n\n const requestID = randomUUID()\n const at = new Date().toISOString()\n const request: V2AssembledLine = {\n v: V2,\n type: \"assembled\",\n requestID,\n at,\n kind,\n sessionID: event.sessionID,\n ...(typeof event.agent === \"string\" ? { agent: event.agent } : {}),\n ...(event.model === undefined ? {} : { model: event.model }),\n systemHash,\n messageHashes,\n tools,\n messages: messages.length,\n bytes,\n }\n appendLines(current.requestsFile, [line(request)])\n\n const queue = current.pending.get(httpKind(kind)) ?? []\n queue.push({ id: requestID, at: Date.now() })\n // A provider error can leave a request without an HTTP counterpart. Keep\n // the queue bounded instead of retaining IDs for the process lifetime.\n if (queue.length > 16) queue.shift()\n current.pending.set(httpKind(kind), queue)\n options.onWrite?.({ at })\n } catch (error) {\n fail(error)\n }\n }\n\n const writeHttp = async (event: HttpEvent): Promise<void> => {\n try {\n const current = session(event.sessionID)\n const captured = await captureBodyBytes(event.request)\n mkdirSync(current.bodiesDir, { recursive: true, mode: 0o700 })\n hardenDirectory(current.bodiesDir)\n const bodyFile = join(current.bodiesDir, `${captured.hash}.bin`)\n if (!existsSync(bodyFile)) {\n const temporary = join(current.bodiesDir, `${captured.hash}.${randomUUID()}.tmp`)\n writeFileSync(temporary, captured.bytes, { mode: 0o600 })\n renameSync(temporary, bodyFile)\n hardenFile(bodyFile)\n }\n\n const queue = current.pending.get(event.kind) ?? []\n const now = Date.now()\n // A failed request can leave an assembled ID behind. Do not pair a new\n // body with a stale request from minutes ago.\n while (queue.length > 0 && now - queue[0]!.at > PENDING_TTL_MS) queue.shift()\n const requestID = queue.shift()?.id ?? randomUUID()\n if (queue.length === 0) current.pending.delete(event.kind)\n else current.pending.set(event.kind, queue)\n const at = new Date().toISOString()\n const request: V2HttpLine = {\n v: V2,\n type: \"http\",\n requestID,\n at,\n kind: event.kind,\n sessionID: event.sessionID,\n ...(typeof event.agent === \"string\" ? { agent: event.agent } : {}),\n ...(event.model === undefined ? {} : { model: event.model }),\n url: event.request.url,\n bodyHash: captured.hash,\n bodyEncoding: captured.encoding,\n contentType: captured.contentType,\n bodyBytes: captured.bodyBytes,\n decodedBytes: null,\n ...(captured.truncated ? { truncated: true as const } : {}),\n bytes: captured.bodyBytes,\n }\n appendLines(current.requestsFile, [line(request)])\n options.onWrite?.({ at })\n } catch (error) {\n fail(error)\n }\n }\n\n return { writeAssembled, writeHttp, active }\n}\n\nfunction emptyCache(root: string): Cache {\n return {\n root,\n sessions: new Map(),\n byKey: new Map(),\n sorted: [],\n requestBytes: 0,\n lastScanMs: 0,\n error: null,\n }\n}\n\nfunction parseRequestFile(file: string, sessionDirName: string): Map<string, V2Entry> {\n const entries = new Map<string, V2Entry>()\n let text: string\n try {\n text = readFileSync(file, \"utf8\")\n } catch {\n return entries\n }\n for (const raw of text.split(\"\\n\")) {\n if (raw === \"\") continue\n let parsed: Record<string, unknown>\n try {\n parsed = JSON.parse(raw) as Record<string, unknown>\n } catch {\n continue\n }\n if (parsed.v !== V2) continue\n if (parsed.type === \"assembled\") {\n const assembled = parsed as unknown as V2AssembledLine\n if (typeof assembled.requestID !== \"string\" || typeof assembled.at !== \"string\") {\n continue\n }\n const key = `v2:${sessionDirName}:${assembled.requestID}`\n const existing = entries.get(assembled.requestID)\n const entry: V2Entry = {\n key,\n cursor: `${assembled.at}|${assembled.requestID}`,\n sessionDir: sessionDirName,\n sessionID: assembled.sessionID,\n requestID: assembled.requestID,\n at: assembled.at,\n kind: assembled.kind,\n type: \"assembled\",\n agent: typeof assembled.agent === \"string\" ? assembled.agent : null,\n model: modelRef(assembled.model),\n bytes: assembled.bytes,\n messages: assembled.messages,\n hasBody: existing?.http != null,\n bodyBytes: existing?.bodyBytes ?? null,\n assembled,\n http: existing?.http ?? null,\n }\n entries.set(assembled.requestID, entry)\n } else if (parsed.type === \"http\") {\n const http = parsed as unknown as V2HttpLine\n if (typeof http.requestID !== \"string\" || typeof http.at !== \"string\") {\n continue\n }\n const existing = entries.get(http.requestID)\n const key = existing?.key ?? `v2:${sessionDirName}:${http.requestID}`\n const entry: V2Entry = {\n key,\n cursor: `${http.at}|${http.requestID}`,\n sessionDir: sessionDirName,\n sessionID: http.sessionID,\n requestID: http.requestID,\n at: existing?.assembled === null || existing?.assembled === undefined ? http.at : existing.at,\n kind: existing?.assembled === null || existing?.assembled === undefined ? http.kind : existing.kind,\n type: existing?.assembled === null || existing?.assembled === undefined ? \"http\" : \"assembled\",\n agent:\n existing?.assembled === null || existing?.assembled === undefined\n ? typeof http.agent === \"string\"\n ? http.agent\n : null\n : existing.agent,\n model:\n existing?.assembled === null || existing?.assembled === undefined ? modelRef(http.model) : existing.model,\n bytes:\n existing?.assembled === null || existing?.assembled === undefined\n ? http.bytes\n : existing.bytes,\n messages: existing?.messages ?? null,\n hasBody: true,\n bodyBytes: http.bodyBytes,\n assembled: existing?.assembled ?? null,\n http,\n }\n entries.set(http.requestID, entry)\n }\n }\n return entries\n}\n\nexport function invalidateV2(root: string): void {\n caches.delete(root)\n const prefix = join(root, \"\")\n for (const key of readCaches.keys()) {\n if (key.startsWith(prefix)) readCaches.delete(key)\n }\n for (const key of searchCaches.keys()) {\n if (key.startsWith(`${root}|`)) searchCaches.delete(key)\n }\n}\n\nexport function ensureV2(root: string): Cache {\n let cache = caches.get(root)\n if (cache === undefined) {\n cache = emptyCache(root)\n caches.set(root, cache)\n }\n\n const started = performance.now()\n const next = new Map<string, SessionCache>()\n let changed = false\n let requestBytes = 0\n\n let directories: string[] = []\n try {\n directories = readdirSync(sessionsRoot(root), { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n } catch {\n directories = []\n }\n\n for (const dirName of directories) {\n const file = join(sessionsRoot(root), dirName, REQUESTS_FILE)\n let stats\n try {\n stats = statSync(file)\n } catch {\n continue\n }\n if (!stats.isFile()) continue\n requestBytes += stats.size\n const existing = cache.sessions.get(dirName)\n if (existing !== undefined && existing.size === stats.size) {\n next.set(dirName, existing)\n continue\n }\n next.set(dirName, {\n dir: dirName,\n file,\n size: stats.size,\n entries: parseRequestFile(file, dirName),\n })\n changed = true\n }\n\n if (next.size !== cache.sessions.size) changed = true\n if (!changed) {\n cache.requestBytes = requestBytes\n cache.lastScanMs = Math.round(performance.now() - started)\n return cache\n }\n\n const byKey = new Map<string, V2Entry>()\n const sorted: V2Entry[] = []\n for (const session of next.values()) {\n for (const entry of session.entries.values()) {\n byKey.set(entry.key, entry)\n sorted.push(entry)\n }\n }\n sorted.sort((left, right) => {\n if (left.at !== right.at) return left.at < right.at ? 1 : -1\n return left.requestID < right.requestID ? 1 : left.requestID > right.requestID ? -1 : 0\n })\n\n cache.sessions = next\n cache.byKey = byKey\n cache.sorted = sorted\n cache.requestBytes = requestBytes\n cache.error = null\n cache.lastScanMs = Math.round(performance.now() - started)\n return cache\n}\n\nfunction matches(entry: V2Entry, filters: LogFilters): boolean {\n if (filters.sessionID !== undefined && entry.sessionID !== filters.sessionID) return false\n if (filters.kind !== undefined && entry.kind !== filters.kind) return false\n if (filters.agent !== undefined && entry.agent !== filters.agent) return false\n if (filters.type === \"assembled\" && entry.assembled === null) return false\n if (filters.type === \"http\" && !entry.hasBody) return false\n const modelLabel = entry.model === null ? \"\" : [entry.model.providerID, entry.model.id, entry.model.variant].filter(Boolean).join(\"/\")\n if (filters.model !== undefined && !modelLabel.toLowerCase().includes(filters.model.toLowerCase())) return false\n if (filters.query !== undefined) {\n const haystack = [entry.at, entry.type, entry.kind, entry.sessionID, entry.agent, modelLabel, entry.http?.url]\n .filter((value) => typeof value === \"string\")\n .join(\" \")\n .toLowerCase()\n if (!haystack.includes(filters.query.toLowerCase())) return false\n }\n return true\n}\n\nexport type V2ListInput = LogFilters & {\n readonly limit?: number\n readonly cursor?: string\n}\n\nexport type V2ListOutput = {\n readonly entries: readonly LogSummary[]\n readonly hasMore: boolean\n readonly records: number\n readonly error: string | null\n}\n\nfunction summaryOf(entry: V2Entry): LogSummary {\n return {\n key: entry.key,\n cursor: entry.cursor,\n bytes: entry.bytes,\n at: entry.at,\n type: entry.type,\n kind: entry.kind,\n sessionID: entry.sessionID,\n agent: entry.agent,\n model: entry.model,\n url: entry.http?.url ?? null,\n ...(entry.messages === null ? {} : { messages: entry.messages }),\n ...(entry.bodyBytes === null ? {} : { bodyBytes: entry.bodyBytes }),\n hasBody: entry.hasBody,\n }\n}\n\nexport function v2List(root: string, input: V2ListInput): V2ListOutput {\n armV2(root)\n const cache = ensureV2(root)\n const limit = clampPage(input.limit)\n const entries: LogSummary[] = []\n let hasMore = false\n for (const entry of cache.sorted) {\n if (input.cursor !== undefined && entry.cursor >= input.cursor) continue\n if (!matches(entry, input)) continue\n entries.push(summaryOf(entry))\n if (entries.length > limit) {\n hasMore = true\n entries.pop()\n break\n }\n }\n\n return {\n entries,\n hasMore,\n records: cache.sorted.length,\n error: cache.error,\n }\n}\n\nfunction snippetOf(text: string, needle: string, ignoreCase: boolean): string {\n const haystack = ignoreCase ? text.toLowerCase() : text\n const at = haystack.indexOf(ignoreCase ? needle.toLowerCase() : needle)\n if (at < 0) return \"\"\n const start = Math.max(0, at - 60)\n const end = Math.min(text.length, at + needle.length + 80)\n const body = text.slice(start, end).replace(/\\s+/g, \" \").trim()\n return `${start > 0 ? \"…\" : \"\"}${body}${end < text.length ? \"…\" : \"\"}`\n}\n\nfunction metadataText(entry: V2Entry): string {\n const model = entry.model === null ? \"\" : [entry.model.providerID, entry.model.id, entry.model.variant].filter(Boolean).join(\"/\")\n return [entry.at, entry.type, entry.kind, entry.sessionID, entry.agent, model, entry.http?.url]\n .filter((value): value is string => typeof value === \"string\" && value !== \"\")\n .join(\" \")\n}\n\n/**\n * Bounded content search over the v2 store. Metadata is checked first, then the\n * system prompt, the message bodies and finally the raw HTTP body. Body blobs\n * are decoded only when their entry is reached, and both a byte and a time\n * budget stop the scan early.\n */\nexport function v2Search(root: string, input: SearchInput, signal?: AbortSignal): SearchOutput {\n armV2(root)\n const cache = ensureV2(root)\n const query = boundedString(input.query, MAX_SEARCH_QUERY)\n if (query === undefined) throw new LogError(\"bad_request\", \"query must not be empty\")\n\n const cacheKey = [\n root,\n cache.requestBytes,\n input.sessionID ?? \"\",\n input.type ?? \"\",\n input.kind ?? \"\",\n input.agent ?? \"\",\n input.model ?? \"\",\n input.limit ?? \"\",\n input.budgetBytes ?? \"\",\n input.budgetMs ?? \"\",\n input.ignoreCase === true ? \"i\" : \"s\",\n query,\n ].join(\"|\")\n const cached = searchCaches.get(cacheKey)\n if (cached !== undefined && Date.now() - cached.at < 5_000) return cached.output\n\n const limit = clampInteger(input.limit, 1, MAX_SEARCH_RESULTS, 50)\n const budgetBytes = clampSearchBytes(input.budgetBytes)\n const budgetMs = clampSearchMs(input.budgetMs)\n const filters = { ...input, query: undefined }\n const ignoreCase = input.ignoreCase === true\n const needle = ignoreCase ? query.toLowerCase() : query\n const matchesOut: SearchMatch[] = []\n let scannedBytes = 0\n let skipped = 0\n let partial = false\n const started = performance.now()\n const sessionMaps = new Map<string, ValueMaps | null>()\n\n for (const entry of cache.sorted) {\n if (signal?.aborted === true || performance.now() - started >= budgetMs || scannedBytes >= budgetBytes) {\n partial = true\n break\n }\n if (!matches(entry, filters)) continue\n\n const metadata = metadataText(entry)\n const metadataHaystack = ignoreCase ? metadata.toLowerCase() : metadata\n if (metadataHaystack.includes(needle)) {\n matchesOut.push({ entry: summaryOf(entry), snippet: snippetOf(metadata, query, ignoreCase) })\n if (matchesOut.length >= limit) {\n partial = true\n break\n }\n continue\n }\n\n let snippet = \"\"\n if (entry.assembled !== null) {\n let maps = sessionMaps.get(entry.sessionDir)\n if (maps === undefined) {\n maps =\n sessionMapBytes(root, entry.sessionDir) <= MAX_SESSION_MAP_BYTES ? mapsFor(root, entry.sessionDir) : null\n sessionMaps.set(entry.sessionDir, maps)\n }\n if (maps === null) {\n // A very large session is not loaded into memory for a content scan;\n // metadata and the HTTP body are still searched below.\n skipped += 1\n } else {\n const system = maps.systems.get(entry.assembled.systemHash)\n if (system !== undefined) {\n const text = JSON.stringify(system) ?? \"\"\n scannedBytes += Buffer.byteLength(text, \"utf8\")\n snippet = snippetOf(text, query, ignoreCase)\n } else {\n skipped += 1\n }\n if (snippet === \"\") {\n for (const hash of entry.assembled.messageHashes) {\n const message = maps.messages.get(hash)\n if (message === undefined) {\n skipped += 1\n continue\n }\n const text = JSON.stringify(message) ?? \"\"\n scannedBytes += Buffer.byteLength(text, \"utf8\")\n snippet = snippetOf(text, query, ignoreCase)\n if (snippet !== \"\") break\n if (scannedBytes >= budgetBytes || performance.now() - started >= budgetMs) break\n }\n }\n }\n }\n if (snippet === \"\" && entry.http !== null) {\n const stored = readBody(root, entry.sessionDir, entry.http.bodyHash)\n if (stored === null) {\n skipped += 1\n } else {\n const decoded = decodeStoredBody(stored, entry.http.bodyEncoding)\n if (decoded.text === null) {\n skipped += 1\n } else {\n scannedBytes += Buffer.byteLength(decoded.text, \"utf8\")\n snippet = snippetOf(decoded.text, query, ignoreCase)\n }\n }\n }\n\n if (snippet !== \"\") {\n matchesOut.push({ entry: summaryOf(entry), snippet })\n if (matchesOut.length >= limit) {\n partial = true\n break\n }\n }\n }\n\n const output: SearchOutput = {\n matches: matchesOut,\n partial,\n scannedBytes,\n skipped,\n error: cache.error,\n }\n searchCaches.set(cacheKey, { at: Date.now(), output })\n while (searchCaches.size > 8) {\n const oldest = searchCaches.keys().next().value\n if (oldest === undefined) break\n searchCaches.delete(oldest)\n }\n return output\n}\n\nfunction mapCache(root: string, sessionDirName: string): MapCache {\n const key = join(root, sessionDirName)\n const existing = readCaches.get(key)\n if (existing !== undefined) {\n // Map insertion order doubles as an LRU.\n readCaches.delete(key)\n readCaches.set(key, existing)\n return existing\n }\n const cache: MapCache = {\n key,\n systemsFile: join(sessionDir(root, sessionDirName), SYSTEMS_FILE),\n messagesFile: join(sessionDir(root, sessionDirName), MESSAGES_FILE),\n systemsSize: -1,\n messagesSize: -1,\n systems: null,\n messages: null,\n bytes: 0,\n }\n readCaches.set(key, cache)\n // Message and system maps can be large. Keep only the sessions the viewer is\n // actively reading; the next read reloads from disk.\n while (readCaches.size > MAX_READ_CACHES) {\n const oldest = readCaches.keys().next().value\n if (oldest === undefined) break\n readCaches.delete(oldest)\n }\n return cache\n}\n\n/** Keep the parsed-map cache within a byte budget, not only a session count. */\nfunction trimReadCaches(protect: string): void {\n let total = 0\n for (const cache of readCaches.values()) total += cache.bytes\n for (const [key, cache] of readCaches) {\n if (readCaches.size <= 1 || total <= MAX_READ_CACHE_BYTES) break\n if (key === protect) continue\n readCaches.delete(key)\n total -= cache.bytes\n }\n}\n\nfunction loadMap(file: string, field: \"system\" | \"message\"): Map<string, unknown> {\n const map = new Map<string, unknown>()\n let text: string\n try {\n text = readFileSync(file, \"utf8\")\n } catch {\n return map\n }\n for (const entry of text.split(\"\\n\")) {\n if (entry === \"\") continue\n try {\n const parsed = JSON.parse(entry) as Record<string, unknown>\n if (parsed.v !== V2 || typeof parsed.hash !== \"string\") continue\n map.set(parsed.hash, parsed[field])\n } catch {\n // A partial trailing line from a crash is ignored.\n }\n }\n return map\n}\n\nfunction mapsFor(root: string, sessionDirName: string): { systems: Map<string, unknown>; messages: Map<string, unknown> } {\n const cache = mapCache(root, sessionDirName)\n let systemsSize = -1\n let messagesSize = -1\n try {\n systemsSize = statSync(cache.systemsFile).size\n messagesSize = statSync(cache.messagesFile).size\n } catch {\n // Missing files are empty maps.\n }\n if (cache.systems === null || cache.systemsSize !== systemsSize) {\n cache.systems = loadMap(cache.systemsFile, \"system\")\n cache.systemsSize = systemsSize\n }\n if (cache.messages === null || cache.messagesSize !== messagesSize) {\n cache.messages = loadMap(cache.messagesFile, \"message\")\n cache.messagesSize = messagesSize\n }\n cache.bytes = Math.max(0, systemsSize) + Math.max(0, messagesSize)\n trimReadCaches(cache.key)\n return { systems: cache.systems, messages: cache.messages }\n}\n\nfunction readBody(root: string, sessionDirName: string, bodyHash: string): Buffer | null {\n if (!/^[a-f0-9]{64}$/.test(bodyHash)) return null\n try {\n return readFileSync(join(sessionDir(root, sessionDirName), BODIES_DIR, `${bodyHash}.bin`))\n } catch {\n return null\n }\n}\n\nexport type V2ReadOutput = {\n readonly record: Record<string, unknown> | null\n readonly bytes: number\n readonly truncated: boolean\n /** A larger `maxBytes` could return more of the same request. */\n readonly moreAvailable: boolean\n /** Logical size of the complete request, including the decoded body. */\n readonly fullBytes: number\n readonly notFound: boolean\n readonly paths?: {\n readonly session: string\n readonly requests: string\n readonly body?: string\n }\n}\n\ntype ValueMaps = {\n readonly systems: Map<string, unknown>\n readonly messages: Map<string, unknown>\n}\n\n/** Read only the requested hashes, streaming the NDJSON file instead of loading it. */\nfunction readValuesFromDisk(file: string, field: \"system\" | \"message\", wanted: ReadonlySet<string>): Map<string, unknown> {\n const found = new Map<string, unknown>()\n if (wanted.size === 0) return found\n let fd: number | undefined\n try {\n fd = openSync(file, \"r\")\n const buffer = Buffer.allocUnsafe(STREAM_CHUNK_BYTES)\n let carry = Buffer.alloc(0)\n while (true) {\n const bytesRead = readSync(fd, buffer, 0, buffer.length, null)\n if (bytesRead === 0) break\n const chunk =\n carry.length === 0\n ? buffer.subarray(0, bytesRead)\n : Buffer.concat([carry, buffer.subarray(0, bytesRead)])\n let start = 0\n while (true) {\n const newline = chunk.indexOf(0x0a, start)\n if (newline === -1) break\n const line = chunk.toString(\"utf8\", start, newline)\n const hash = /^\\{\"v\":2,\"hash\":\"([a-f0-9]{64})\"/.exec(line)?.[1]\n if (hash !== undefined && wanted.has(hash) && !found.has(hash)) {\n try {\n const parsed = JSON.parse(line) as Record<string, unknown>\n if (parsed.v === V2) found.set(hash, parsed[field])\n } catch {\n // A partial or malformed line is treated as missing.\n }\n if (found.size === wanted.size) return found\n }\n start = newline + 1\n }\n carry = Buffer.from(chunk.subarray(start))\n }\n if (carry.length > 0) {\n const line = carry.toString(\"utf8\")\n const hash = /^\\{\"v\":2,\"hash\":\"([a-f0-9]{64})\"/.exec(line)?.[1]\n if (hash !== undefined && wanted.has(hash) && !found.has(hash)) {\n try {\n const parsed = JSON.parse(line) as Record<string, unknown>\n if (parsed.v === V2) found.set(hash, parsed[field])\n } catch {\n // Ignore the partial trailing line from a crash.\n }\n }\n }\n } catch {\n // Missing or unreadable file: every requested hash stays missing.\n } finally {\n if (fd !== undefined) closeSync(fd)\n }\n return found\n}\n\nfunction sessionMapBytes(root: string, sessionDirName: string): number {\n let total = 0\n try {\n total += statSync(join(sessionDir(root, sessionDirName), SYSTEMS_FILE)).size\n } catch {\n // Missing systems file.\n }\n try {\n total += statSync(join(sessionDir(root, sessionDirName), MESSAGES_FILE)).size\n } catch {\n // Missing messages file.\n }\n return total\n}\n\nfunction mapsForRead(root: string, entry: V2Entry, maxMapBytes: number): ValueMaps | null {\n if (entry.assembled === null) return null\n if (sessionMapBytes(root, entry.sessionDir) <= maxMapBytes) {\n return mapsFor(root, entry.sessionDir)\n }\n const systems = readValuesFromDisk(\n join(sessionDir(root, entry.sessionDir), SYSTEMS_FILE),\n \"system\",\n new Set([entry.assembled.systemHash]),\n )\n const messages = readValuesFromDisk(\n join(sessionDir(root, entry.sessionDir), MESSAGES_FILE),\n \"message\",\n new Set(entry.assembled.messageHashes),\n )\n return { systems, messages }\n}\n\ntype SystemPart = {\n readonly system: unknown\n readonly used: number\n readonly truncated: boolean\n readonly budgetTruncated: boolean\n}\n\ntype MessagePart = {\n readonly messages: unknown[]\n readonly used: number\n readonly truncated: boolean\n readonly budgetTruncated: boolean\n}\n\ntype HttpPart = {\n readonly http: Record<string, unknown> | null\n readonly used: number\n readonly truncated: boolean\n readonly budgetTruncated: boolean\n readonly bodyLogicalBytes: number | null\n}\n\nfunction assembleSystem(entry: V2Entry, maps: ValueMaps | null, max: number): SystemPart {\n const stored = entry.assembled === null || maps === null ? undefined : maps.systems.get(entry.assembled.systemHash)\n let system: unknown = stored ?? []\n let used = Buffer.byteLength(JSON.stringify(system), \"utf8\")\n if (used <= max) return { system, used, truncated: false, budgetTruncated: false }\n\n // A pathological system prompt must still respect the record cap. Keep its\n // serialized prefix so the viewer can show what the model received.\n const text = sliceUtf8(JSON.stringify(system), Math.max(0, max - 64))\n system = [{ type: \"text\", text }]\n used = Buffer.byteLength(text, \"utf8\")\n return { system, used, truncated: true, budgetTruncated: true }\n}\n\nfunction assembleMessages(entry: V2Entry, maps: ValueMaps | null, max: number, used: number): MessagePart {\n const messages: unknown[] = []\n let truncated = false\n let budgetTruncated = false\n if (entry.assembled === null || maps === null) {\n return { messages, used, truncated, budgetTruncated }\n }\n\n for (const hash of entry.assembled.messageHashes) {\n const message = maps.messages.get(hash)\n if (message === undefined) {\n // A message line can be missing after a crash or a partial prune; the\n // request is still readable, but it is incomplete.\n truncated = true\n continue\n }\n const size = Buffer.byteLength(JSON.stringify(message), \"utf8\")\n if (used + size > max) {\n truncated = true\n budgetTruncated = true\n break\n }\n messages.push(message)\n used += size\n }\n return { messages, used, truncated, budgetTruncated }\n}\n\nfunction assembleHttp(entry: V2Entry, root: string, max: number, used: number): HttpPart {\n if (entry.http === null) {\n return { http: null, used, truncated: false, budgetTruncated: false, bodyLogicalBytes: null }\n }\n\n const stored = readBody(root, entry.sessionDir, entry.http.bodyHash)\n if (stored === null) {\n return {\n http: {\n url: entry.http.url,\n bodyUnavailable: true,\n bodyEncoding: entry.http.bodyEncoding,\n bodyBytes: entry.http.bodyBytes,\n },\n used,\n truncated: false,\n budgetTruncated: false,\n bodyLogicalBytes: null,\n }\n }\n\n const decoded = decodeStoredBody(stored, entry.http.bodyEncoding)\n // The line records the wire size; the decoded size is what the viewer budget\n // actually counts. Compute it before slicing the body.\n const decodedBodyBytes =\n decoded.decodedBytes ??\n (decoded.text !== null ? Buffer.byteLength(decoded.text, \"utf8\") : (decoded.base64?.length ?? 0))\n const bodyLogicalBytes = entry.http.truncated === true ? entry.http.bodyBytes : decodedBodyBytes\n let body = decoded.text\n let bodyBase64 = decoded.base64\n const bodyCapped = entry.http.truncated === true\n let bodyTruncated = bodyCapped\n let budgetTruncated = false\n const remaining = Math.max(0, max - used)\n if (body !== null) {\n const bodyBytes = Buffer.byteLength(body, \"utf8\")\n if (bodyBytes > remaining) {\n body = sliceUtf8(body, remaining)\n bodyTruncated = true\n budgetTruncated = true\n }\n } else if (bodyBase64 !== null) {\n const kept = Math.min(bodyBase64.length, remaining)\n if (kept < bodyBase64.length) {\n bodyBase64 = bodyBase64.slice(0, kept)\n bodyTruncated = true\n budgetTruncated = true\n }\n }\n const http: Record<string, unknown> = {\n url: entry.http.url,\n ...(body === null ? {} : { body }),\n ...(bodyBase64 === null ? {} : { bodyBase64 }),\n bodyEncoding: entry.http.bodyEncoding,\n ...(entry.http.contentType === undefined ? {} : { contentType: entry.http.contentType }),\n bodyBytes: entry.http.bodyBytes,\n ...(decoded.decodedBytes === null ? {} : { decodedBytes: decoded.decodedBytes }),\n ...(bodyCapped ? { bodyCapped: true } : {}),\n ...(bodyTruncated ? { bodyTruncated: true } : {}),\n }\n return {\n http,\n used: used + (body === null ? (bodyBase64?.length ?? 0) : Buffer.byteLength(body, \"utf8\")),\n truncated: bodyTruncated,\n budgetTruncated,\n bodyLogicalBytes,\n }\n}\n\nfunction buildRecord(\n entry: V2Entry,\n system: unknown,\n messages: unknown[],\n http: Record<string, unknown> | null,\n): Record<string, unknown> {\n return {\n type: entry.assembled === null ? \"http\" : \"assembled\",\n at: entry.at,\n kind: entry.kind,\n sessionID: entry.sessionID,\n ...(entry.agent === null ? {} : { agent: entry.agent }),\n ...(entry.model === null ? {} : { model: entry.model }),\n ...(entry.assembled === null\n ? {}\n : {\n system,\n messages,\n tools: entry.assembled.tools,\n messageCount: entry.assembled.messages,\n bytes: entry.assembled.bytes,\n }),\n ...(entry.http === null ? {} : { url: entry.http.url }),\n ...(entry.assembled === null && http !== null ? http : {}),\n ...(entry.assembled !== null && http !== null ? { http } : {}),\n }\n}\n\nfunction fullBytesOf(entry: V2Entry, bodyLogicalBytes: number | null): number {\n const httpBytes = entry.http === null ? 0 : (bodyLogicalBytes ?? entry.http.bodyBytes)\n return entry.assembled === null ? (entry.http === null ? entry.bytes : httpBytes) : entry.bytes + httpBytes\n}\n\nexport type V2ReadOptions = {\n /** Test hook: force the streaming path with a value below the session size. */\n readonly maxMapBytes?: number\n}\n\nexport function v2Read(\n root: string,\n key: string,\n maxBytes: number = MAX_RECORD_BYTES,\n options: V2ReadOptions = {},\n): V2ReadOutput {\n armV2(root)\n const cache = ensureV2(root)\n const entry = cache.byKey.get(key)\n if (entry === undefined) {\n return { record: null, bytes: 0, truncated: false, moreAvailable: false, fullBytes: 0, notFound: true }\n }\n\n const max = clampReadBytes(maxBytes)\n const maps = mapsForRead(root, entry, options.maxMapBytes ?? MAX_SESSION_MAP_BYTES)\n const system = assembleSystem(entry, maps, max)\n const messages = assembleMessages(entry, maps, max, system.used)\n const http = assembleHttp(entry, root, max, messages.used)\n const record = buildRecord(entry, system.system, messages.messages, http.http)\n const budgetTruncated = system.budgetTruncated || messages.budgetTruncated || http.budgetTruncated\n\n return {\n record,\n bytes: entry.bytes,\n truncated: system.truncated || messages.truncated || http.truncated,\n moreAvailable: budgetTruncated && max < MAX_FULL_RECORD_BYTES,\n fullBytes: fullBytesOf(entry, http.bodyLogicalBytes),\n notFound: false,\n paths: {\n session: sessionDir(root, entry.sessionDir),\n requests: join(sessionDir(root, entry.sessionDir), REQUESTS_FILE),\n ...(entry.http === null\n ? {}\n : { body: join(sessionDir(root, entry.sessionDir), BODIES_DIR, `${entry.http.bodyHash}.bin`) }),\n },\n }\n}\n\nfunction storageBytes(root: string): number {\n const now = Date.now()\n const key = `storage:${root}`\n const previous = storageCache.get(key)\n if (previous !== undefined && now - previous.at < 30_000) return previous.bytes\n let total = 0\n try {\n for (const session of readdirSync(sessionsRoot(root), { withFileTypes: true })) {\n if (!session.isDirectory()) continue\n const dir = join(sessionsRoot(root), session.name)\n for (const file of readdirSync(dir, { withFileTypes: true })) {\n if (file.isFile()) {\n try {\n total += statSync(join(dir, file.name)).size\n } catch {\n // A file removed by retention while scanning.\n }\n } else if (file.isDirectory()) {\n for (const child of readdirSync(join(dir, file.name), { withFileTypes: true })) {\n if (!child.isFile()) continue\n try {\n total += statSync(join(dir, file.name, child.name)).size\n } catch {\n // A file removed by retention while scanning.\n }\n }\n }\n }\n }\n } catch {\n total = 0\n }\n storageCache.set(key, { at: now, bytes: total })\n return total\n}\n\nconst storageCache = new Map<string, { at: number; bytes: number }>()\n\nexport type V2Status = {\n readonly bytes: number\n readonly sessions: number\n readonly requests: number\n readonly requestBytes: number\n readonly lastScanMs: number\n readonly error: string | null\n readonly warnings: readonly string[]\n}\n\nexport function v2Status(root: string): V2Status {\n const cache = ensureV2(root)\n const bytes = storageBytes(root)\n const path = inspectPath(root)\n const warnings: string[] = []\n let directory = false\n try {\n directory = statSync(root).isDirectory()\n } catch {\n // Missing root: the writer will create it on the next enabled request.\n }\n if (process.platform !== \"win32\" && path.mode !== null && (path.mode & 0o077) !== 0) warnings.push(\"directory-permissions\")\n if (path.symlink) warnings.push(\"symlink\")\n if (path.exists && !directory) warnings.push(\"not-regular\")\n return {\n bytes,\n sessions: cache.sessions.size,\n requests: cache.sorted.length,\n requestBytes: cache.requestBytes,\n lastScanMs: cache.lastScanMs,\n error: cache.error,\n warnings,\n }\n}\n\nexport function v2Delete(root: string, target: \"current\" | \"all\", sessionID?: string): number {\n let freed = 0\n const remove = (dir: string): void => {\n try {\n for (const file of readdirSync(dir, { withFileTypes: true })) {\n if (file.isFile()) {\n try {\n freed += statSync(join(dir, file.name)).size\n } catch {\n // Missing file.\n }\n } else if (file.isDirectory()) {\n for (const child of readdirSync(join(dir, file.name), { withFileTypes: true })) {\n if (!child.isFile()) continue\n try {\n freed += statSync(join(dir, file.name, child.name)).size\n } catch {\n // Missing file.\n }\n }\n }\n }\n rmSync(dir, { recursive: true, force: true })\n } catch {\n // A session already removed.\n }\n }\n\n if (target === \"all\") {\n try {\n for (const entry of readdirSync(sessionsRoot(root), { withFileTypes: true })) {\n if (entry.isDirectory()) remove(join(sessionsRoot(root), entry.name))\n }\n } catch {\n // No sessions directory.\n }\n } else if (sessionID !== undefined) {\n remove(join(sessionsRoot(root), safeDirName(sessionID)))\n }\n invalidateV2(root)\n storageCache.delete(`storage:${root}`)\n return freed\n}\n\nexport type V2PruneResult = { readonly removed: number; readonly bytesFreed: number }\n\n/**\n * A session that is still being written is left alone, but only for a grace\n * period. The writer's `active` set lives for the whole process, so treating it\n * as permanently pinned would make retention stop pruning every session that\n * was used since startup.\n */\nconst ACTIVE_GRACE_MS = 15 * 60 * 1000\n\nexport function v2Prune(root: string, retention: V2Retention, active: ReadonlySet<string>): V2PruneResult {\n let directories: string[] = []\n try {\n directories = readdirSync(sessionsRoot(root), { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n } catch {\n return { removed: 0, bytesFreed: 0 }\n }\n\n const sessions: Array<{ name: string; dir: string; mtime: number; bytes: number }> = []\n for (const name of directories) {\n const dir = join(sessionsRoot(root), name)\n let mtime = 0\n let bytes = 0\n try {\n mtime = statSync(dir).mtimeMs\n for (const file of readdirSync(dir, { withFileTypes: true })) {\n if (file.isFile()) {\n const stats = statSync(join(dir, file.name))\n bytes += stats.size\n mtime = Math.max(mtime, stats.mtimeMs)\n } else if (file.isDirectory()) {\n for (const child of readdirSync(join(dir, file.name), { withFileTypes: true })) {\n if (!child.isFile()) continue\n const stats = statSync(join(dir, file.name, child.name))\n bytes += stats.size\n mtime = Math.max(mtime, stats.mtimeMs)\n }\n }\n }\n } catch {\n continue\n }\n sessions.push({ name, dir, mtime, bytes })\n }\n\n sessions.sort((left, right) => left.mtime - right.mtime)\n const now = Date.now()\n const maxAge = retention.maxAgeDays * 24 * 60 * 60 * 1000\n let total = sessions.reduce((sum, session) => sum + session.bytes, 0)\n let remaining = sessions.length\n let removed = 0\n let bytesFreed = 0\n\n for (const session of sessions) {\n const tooOld = maxAge > 0 && now - session.mtime > maxAge\n const tooMany = remaining > retention.maxSessions\n const tooLarge = total > retention.maxTotalBytes\n if (!tooOld && !tooMany && !tooLarge) break\n if (active.has(session.name) && now - session.mtime < ACTIVE_GRACE_MS) continue\n rmSync(session.dir, { recursive: true, force: true })\n total -= session.bytes\n remaining -= 1\n bytesFreed += session.bytes\n removed += 1\n }\n\n if (removed > 0) {\n invalidateV2(root)\n storageCache.delete(`storage:${root}`)\n }\n return { removed, bytesFreed }\n}\n\n/** Exposed for tests. */\nexport function v2SessionDir(root: string, sessionID: string): string {\n return join(sessionsRoot(root), safeDirName(sessionID))\n}\n",
|
|
11
|
+
"import { createHash } from \"node:crypto\"\nimport { brotliDecompressSync, gunzipSync, inflateSync } from \"node:zlib\"\n\n/** How the bytes on the wire were encoded. */\nexport type BodyEncoding = \"identity\" | \"gzip\" | \"deflate\" | \"br\" | \"zstd\" | \"unknown\"\n\nexport type CapturedBodyBytes = {\n /** The bytes kept in the log (possibly a prefix when the body is huge). */\n readonly bytes: Buffer\n readonly encoding: BodyEncoding\n readonly contentType: string | null\n /** Length of the complete body before any capture cap. */\n readonly bodyBytes: number\n readonly truncated: boolean\n /** SHA-256 of the complete body. */\n readonly hash: string\n}\n\n/** A single body is capped so one request cannot exhaust the server memory. */\nexport const MAX_BODY_BYTES = 32 * 1024 * 1024\n\n/** A decompressed body is capped too: a small gzip stream can expand hugely. */\nexport const MAX_DECODED_BYTES = 64 * 1024 * 1024\n\nfunction hasMagic(bytes: Buffer, magic: readonly number[]): boolean {\n if (bytes.length < magic.length) return false\n for (let index = 0; index < magic.length; index += 1) {\n if (bytes[index] !== magic[index]) return false\n }\n return true\n}\n\nfunction normalizeEncoding(header: string | null, bytes: Buffer): BodyEncoding {\n const value = header?.toLowerCase().trim()\n // The body in the wild is often gzip even when a proxy or SDK did not\n // forward the header; trust the magic bytes first.\n if (hasMagic(bytes, [0x1f, 0x8b])) return \"gzip\"\n if (hasMagic(bytes, [0x28, 0xb5, 0x2f, 0xfd])) return \"zstd\"\n if (value === \"gzip\" || value === \"x-gzip\") return \"gzip\"\n if (value === \"deflate\") return \"deflate\"\n if (value === \"br\" || value === \"brotli\") return \"br\"\n if (value === \"zstd\") return \"zstd\"\n if (value === \"identity\" || value === undefined || value === \"\") return \"identity\"\n return \"unknown\"\n}\n\nfunction zstdDecompress(bytes: Buffer): Buffer | null {\n const bun = globalThis as typeof globalThis & {\n Bun?: { zstdDecompressSync?: (input: Uint8Array) => Uint8Array }\n }\n const decompress = bun.Bun?.zstdDecompressSync\n if (decompress === undefined) return null\n return Buffer.from(decompress(bytes))\n}\n\nfunction decompress(bytes: Buffer, encoding: BodyEncoding): Buffer | null {\n const options = { maxOutputLength: MAX_DECODED_BYTES }\n switch (encoding) {\n case \"identity\":\n return bytes\n case \"gzip\":\n return gunzipSync(bytes, options)\n case \"deflate\":\n return inflateSync(bytes, options)\n case \"br\":\n return brotliDecompressSync(bytes, options)\n case \"zstd\":\n return zstdDecompress(bytes)\n default:\n return null\n }\n}\n\nfunction decodeUtf8(bytes: Buffer): string | null {\n try {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes)\n } catch {\n return null\n }\n}\n\n/**\n * Read the request body as bytes, detect compression, and keep a lossless\n * representation. Decoding the bytes with `Request.text()` destroyed gzip\n * bodies: every 0x8b became U+FFFD and the payload was no longer recoverable.\n *\n * The returned `bytes` are the raw wire bytes (a prefix only when the body\n * exceeds the cap).\n */\nexport type DecodedBody = {\n readonly text: string | null\n readonly base64: string | null\n readonly decodedBytes: number | null\n}\n\n/** Decode bytes that were stored in a v2 body blob. */\nexport function decodeStoredBody(bytes: Buffer, encoding: BodyEncoding): DecodedBody {\n let decoded: Buffer | null = null\n try {\n decoded = decompress(bytes, encoding)\n } catch {\n decoded = null\n }\n if (decoded === null) {\n return { text: null, base64: bytes.toString(\"base64\"), decodedBytes: null }\n }\n const text = decodeUtf8(decoded)\n return {\n text,\n base64: text === null ? decoded.toString(\"base64\") : null,\n decodedBytes: decoded.length,\n }\n}\n\n/** Keep the longest prefix of `text` that fits in `maxBytes` of UTF-8. */\nexport function sliceUtf8(text: string, maxBytes: number): string {\n if (maxBytes <= 0) return \"\"\n const bytes = Buffer.from(text, \"utf8\")\n if (bytes.length <= maxBytes) return text\n let end = maxBytes\n // Do not cut in the middle of a multi-byte sequence.\n while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end -= 1\n return bytes.subarray(0, end).toString(\"utf8\")\n}\n\n/**\n * Read the request body as raw wire bytes, without decompressing or encoding\n * it. The v2 writer stores the bytes as a blob and decodes only when a viewer\n * opens the record, so the model-request path does not pay for a body it will\n * not render.\n */\nexport async function captureBodyBytes(request: Request): Promise<CapturedBodyBytes> {\n let complete: Buffer\n try {\n const clone = request.clone()\n // A Request normally exposes arrayBuffer; the text fallback keeps small\n // test doubles and older runtimes working.\n if (typeof clone.arrayBuffer === \"function\") {\n complete = Buffer.from(await clone.arrayBuffer())\n } else {\n complete = Buffer.from(await clone.text(), \"utf8\")\n }\n } catch (error) {\n throw new Error(`unreadable request body: ${error instanceof Error ? error.message : String(error)}`)\n }\n\n const encoding = normalizeEncoding(request.headers.get(\"content-encoding\"), complete)\n const truncated = complete.length > MAX_BODY_BYTES\n const bytes = truncated ? complete.subarray(0, MAX_BODY_BYTES) : complete\n const hash = createHash(\"sha256\").update(complete).digest(\"hex\")\n\n return {\n bytes,\n encoding,\n contentType: request.headers.get(\"content-type\"),\n bodyBytes: complete.length,\n truncated,\n hash,\n }\n}\n",
|
|
12
|
+
"import type { ModelRef } from \"./types\"\n\n/** Keep only the small, stable fields of a model reference. */\nexport function modelRef(value: unknown): ModelRef | null {\n if (value === null || typeof value !== \"object\") return null\n const record = value as Record<string, unknown>\n const model: { providerID?: string; id?: string; variant?: string } = {}\n if (typeof record.providerID === \"string\") model.providerID = record.providerID\n if (typeof record.id === \"string\") model.id = record.id\n if (typeof record.variant === \"string\") model.variant = record.variant\n return Object.keys(model).length === 0 ? null : model\n}\n\n\n",
|
|
13
|
+
"import { Rpc } from \"@opencode/plugin/rpc\"\nimport type { SessionScope, SessionScopeChange } from \"./session-scope\"\nimport {\n MAX_SETTINGS_DIRECTORY,\n MAX_SETTINGS_DISK_BUDGET,\n MAX_SETTINGS_RETENTION_DAYS,\n MAX_SETTINGS_RETENTION_SESSIONS,\n type Settings,\n} from \"./settings\"\nimport type { LogSummary, SearchMatch } from \"./log/types\"\n\nexport const CONTRACT_VERSION = 6\n\nexport type StoreStatusView = {\n readonly path: string\n readonly exists: boolean\n readonly bytes: number\n readonly mtimeMs: number | null\n /** True when the store root is a directory. */\n readonly directory: boolean\n readonly symlink: boolean\n readonly mode: number | null\n readonly directoryMode: number | null\n readonly warnings: readonly string[]\n}\n\nexport type CacheView = {\n readonly requests: number\n readonly requestBytes: number\n readonly lastScanMs: number\n readonly error: string | null\n}\n\n/** Settings plus the computed retention policy. */\nexport type StatusSettings = Settings & {\n /** Effective retention policy. `null` means unlimited. */\n readonly retention: {\n readonly maxTotalBytes: number | null\n readonly maxAgeDays: number\n readonly maxSessions: number | null\n }\n}\n\nexport type StatusResponse = {\n readonly version: number\n readonly store: StoreStatusView\n readonly settings: StatusSettings\n /** Which sessions are written while logging is enabled. */\n readonly sessionScope: SessionScope\n readonly cache: CacheView\n readonly lastWriteAt: string | null\n readonly lastWriteError: { readonly at: string; readonly code?: string; readonly message: string } | null\n}\n\nexport type ListRequest = {\n readonly sessionID?: string\n readonly type?: string\n readonly kind?: string\n readonly agent?: string\n readonly model?: string\n readonly query?: string\n readonly limit?: number\n readonly cursor?: string\n}\n\nexport type ListResponse = {\n readonly entries: readonly LogSummary[]\n readonly hasMore: boolean\n readonly records: number\n readonly error: string | null\n}\n\nexport type ReadRequest = {\n /** Opaque v2 request key from the list. */\n readonly key: string\n /**\n * Read budget in bytes. Omit for the preview budget; an explicit\n * \"load complete entry\" may ask for up to `MAX_FULL_RECORD_BYTES`.\n */\n readonly maxBytes?: number\n}\n\nexport type ReadResponse = {\n readonly record: unknown\n readonly bytes: number\n readonly truncated: boolean\n /** A larger `maxBytes` could return more of the same request. */\n readonly moreAvailable?: boolean\n /** Logical size of the complete request, including the decoded body. */\n readonly fullBytes?: number\n /** Concrete files backing this record, for \"Reveal\" actions. */\n readonly paths?: {\n readonly session?: string\n readonly requests?: string\n readonly body?: string\n }\n}\n\nexport type SearchRequest = {\n readonly sessionID?: string\n readonly type?: string\n readonly kind?: string\n readonly agent?: string\n readonly model?: string\n readonly query: string\n readonly limit?: number\n readonly ignoreCase?: boolean\n readonly budgetBytes?: number\n readonly budgetMs?: number\n}\n\nexport type SearchResponse = {\n readonly matches: readonly SearchMatch[]\n readonly partial: boolean\n readonly scannedBytes: number\n readonly skipped: number\n readonly error: string | null\n}\n\nexport type TruncateTarget = \"current\" | \"all\"\n\nexport type TruncateRequest = {\n readonly target: TruncateTarget\n /** The session whose directory is deleted by `current`. */\n readonly sessionID?: string\n readonly confirm: true\n}\n\nexport type TruncateResponse = {\n readonly target: TruncateTarget\n readonly bytesFreed: number\n}\n\nexport type SettingsResponse = {\n readonly settings: Settings\n readonly sessionScope: SessionScope\n}\n\nexport type SetSettingsRequest = {\n readonly settings: Settings\n}\n\n/** The scope transition accepted by `updateSessionScope`. */\nexport type UpdateSessionScopeRequest = SessionScopeChange\n\nexport type UpdateSessionScopeResponse = {\n readonly sessionScope: SessionScope\n /** Selecting a session while logging is off turns the master switch on. */\n readonly settings: Settings\n}\n\nexport type SettingsChangedEvent = SettingsResponse\n\nexport type ChangedReason = \"append\" | \"truncate\" | \"error\"\n\nexport type ChangedEvent = {\n /** The store root, not a single file. */\n readonly store: string\n readonly reason: ChangedReason\n readonly at: string\n}\n\nconst nullableString = { type: [\"string\", \"null\"] } as const\nconst modelSchema = {\n anyOf: [\n { type: \"null\" },\n {\n type: \"object\",\n properties: {\n providerID: { type: \"string\" },\n id: { type: \"string\" },\n variant: { type: \"string\" },\n },\n additionalProperties: false,\n },\n ],\n} as const\n\nconst summarySchema = {\n type: \"object\",\n properties: {\n key: { type: \"string\" },\n cursor: { type: \"string\" },\n bytes: { type: \"number\" },\n at: nullableString,\n type: nullableString,\n kind: nullableString,\n sessionID: nullableString,\n agent: nullableString,\n model: modelSchema,\n url: nullableString,\n messages: { type: \"number\" },\n bodyBytes: { type: \"number\" },\n hasBody: { type: \"boolean\" },\n },\n required: [\"key\", \"cursor\", \"bytes\", \"at\", \"type\", \"kind\", \"sessionID\", \"agent\", \"model\", \"url\"],\n additionalProperties: false,\n} as const\n\nconst storeStatusSchema = {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n exists: { type: \"boolean\" },\n bytes: { type: \"number\" },\n mtimeMs: { anyOf: [{ type: \"number\" }, { type: \"null\" }] },\n directory: { type: \"boolean\" },\n symlink: { type: \"boolean\" },\n mode: { anyOf: [{ type: \"number\" }, { type: \"null\" }] },\n directoryMode: { anyOf: [{ type: \"number\" }, { type: \"null\" }] },\n warnings: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"path\", \"exists\", \"bytes\", \"mtimeMs\", \"directory\", \"symlink\", \"mode\", \"directoryMode\", \"warnings\"],\n additionalProperties: false,\n} as const\n\nconst cacheSchema = {\n type: \"object\",\n properties: {\n requests: { type: \"number\" },\n requestBytes: { type: \"number\" },\n lastScanMs: { type: \"number\" },\n error: nullableString,\n },\n required: [\"requests\", \"requestBytes\", \"lastScanMs\", \"error\"],\n additionalProperties: false,\n} as const\n\nconst settingsSchema = {\n type: \"object\",\n properties: {\n enabled: { type: \"boolean\" },\n http: { type: \"boolean\" },\n diskBudget: { type: \"number\", minimum: 0, maximum: MAX_SETTINGS_DISK_BUDGET },\n retentionMaxAgeDays: { type: \"number\", minimum: 0, maximum: MAX_SETTINGS_RETENTION_DAYS },\n retentionMaxSessions: { type: \"number\", minimum: 0, maximum: MAX_SETTINGS_RETENTION_SESSIONS },\n directory: { type: \"string\", maxLength: MAX_SETTINGS_DIRECTORY },\n maintenance: { type: \"boolean\" },\n },\n required: [\n \"enabled\",\n \"http\",\n \"diskBudget\",\n \"retentionMaxAgeDays\",\n \"retentionMaxSessions\",\n \"directory\",\n \"maintenance\",\n ],\n additionalProperties: false,\n} as const\n\nconst statusSettingsSchema = {\n type: \"object\",\n properties: {\n ...settingsSchema.properties,\n retention: {\n type: \"object\",\n properties: {\n maxTotalBytes: { anyOf: [{ type: \"number\" }, { type: \"null\" }] },\n maxAgeDays: { type: \"number\" },\n maxSessions: { anyOf: [{ type: \"number\" }, { type: \"null\" }] },\n },\n required: [\"maxTotalBytes\", \"maxAgeDays\", \"maxSessions\"],\n additionalProperties: false,\n },\n },\n required: [...settingsSchema.required, \"retention\"],\n additionalProperties: false,\n} as const\n\nconst sessionScopeSchema = {\n type: \"object\",\n properties: {\n mode: { type: \"string\", enum: [\"all\", \"only\"] },\n sessions: { type: \"array\", items: { type: \"string\", maxLength: 200 } },\n max: { type: \"number\" },\n },\n required: [\"mode\", \"sessions\", \"max\"],\n additionalProperties: false,\n} as const\n\nconst settingsResponseSchema = {\n type: \"object\",\n properties: {\n settings: settingsSchema,\n sessionScope: sessionScopeSchema,\n },\n required: [\"settings\", \"sessionScope\"],\n additionalProperties: false,\n} as const\n\nconst errorSchema = {\n type: \"object\",\n properties: { message: { type: \"string\" } },\n additionalProperties: false,\n} as const\n\nconst errors = {\n io: errorSchema,\n not_found: errorSchema,\n bad_request: errorSchema,\n forbidden: errorSchema,\n} as const\n\nconst filtersSchema = {\n sessionID: { type: \"string\", maxLength: 200 },\n type: { type: \"string\", maxLength: 80 },\n kind: { type: \"string\", maxLength: 80 },\n agent: { type: \"string\", maxLength: 200 },\n model: { type: \"string\", maxLength: 200 },\n query: { type: \"string\", maxLength: 200 },\n} as const\n\nexport const PromptLogger = Rpc.define({\n id: \"prompt-logger\",\n methods: {\n status: {\n input: { type: \"object\", properties: {}, additionalProperties: false },\n output: {\n type: \"object\",\n properties: {\n version: { type: \"number\" },\n store: storeStatusSchema,\n settings: statusSettingsSchema,\n sessionScope: sessionScopeSchema,\n cache: cacheSchema,\n lastWriteAt: { anyOf: [{ type: \"string\" }, { type: \"null\" }] },\n lastWriteError: {\n anyOf: [\n { type: \"null\" },\n {\n type: \"object\",\n properties: {\n at: { type: \"string\" },\n code: { type: \"string\" },\n message: { type: \"string\" },\n },\n required: [\"at\", \"message\"],\n additionalProperties: false,\n },\n ],\n },\n },\n required: [\"version\", \"store\", \"settings\", \"sessionScope\", \"cache\", \"lastWriteAt\", \"lastWriteError\"],\n additionalProperties: false,\n },\n errors,\n },\n list: {\n input: {\n type: \"object\",\n properties: {\n ...filtersSchema,\n limit: { type: \"number\" },\n cursor: { type: \"string\" },\n },\n additionalProperties: false,\n },\n output: {\n type: \"object\",\n properties: {\n entries: { type: \"array\", items: summarySchema },\n hasMore: { type: \"boolean\" },\n records: { type: \"number\" },\n error: nullableString,\n },\n required: [\"entries\", \"hasMore\", \"records\", \"error\"],\n additionalProperties: false,\n },\n errors,\n },\n read: {\n input: {\n type: \"object\",\n properties: {\n key: { type: \"string\", maxLength: 300 },\n maxBytes: { type: \"number\" },\n },\n required: [\"key\"],\n additionalProperties: false,\n },\n output: {\n type: \"object\",\n properties: {\n record: {},\n bytes: { type: \"number\" },\n truncated: { type: \"boolean\" },\n moreAvailable: { type: \"boolean\" },\n fullBytes: { type: \"number\" },\n paths: {\n type: \"object\",\n properties: {\n session: { type: \"string\" },\n requests: { type: \"string\" },\n body: { type: \"string\" },\n },\n additionalProperties: false,\n },\n },\n required: [\"record\", \"bytes\", \"truncated\"],\n additionalProperties: false,\n },\n errors,\n },\n search: {\n input: {\n type: \"object\",\n properties: {\n ...filtersSchema,\n query: { type: \"string\", minLength: 1, maxLength: 500 },\n limit: { type: \"number\" },\n ignoreCase: { type: \"boolean\" },\n budgetBytes: { type: \"number\" },\n budgetMs: { type: \"number\" },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n output: {\n type: \"object\",\n properties: {\n matches: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: { entry: summarySchema, snippet: { type: \"string\" } },\n required: [\"entry\", \"snippet\"],\n additionalProperties: false,\n },\n },\n partial: { type: \"boolean\" },\n scannedBytes: { type: \"number\" },\n skipped: { type: \"number\" },\n error: nullableString,\n },\n required: [\"matches\", \"partial\", \"scannedBytes\", \"skipped\", \"error\"],\n additionalProperties: false,\n },\n errors,\n },\n truncate: {\n input: {\n type: \"object\",\n properties: {\n target: { type: \"string\", enum: [\"current\", \"all\"] },\n sessionID: { type: \"string\", maxLength: 200 },\n confirm: { type: \"boolean\", enum: [true] },\n },\n required: [\"target\", \"confirm\"],\n additionalProperties: false,\n },\n output: {\n type: \"object\",\n properties: {\n target: { type: \"string\", enum: [\"current\", \"all\"] },\n bytesFreed: { type: \"number\" },\n },\n required: [\"target\", \"bytesFreed\"],\n additionalProperties: false,\n },\n errors,\n },\n getSettings: {\n input: { type: \"object\", properties: {}, additionalProperties: false },\n output: settingsResponseSchema,\n errors,\n },\n setSettings: {\n input: {\n type: \"object\",\n properties: { settings: settingsSchema },\n required: [\"settings\"],\n additionalProperties: false,\n },\n output: settingsResponseSchema,\n errors,\n },\n resetSettings: {\n input: { type: \"object\", properties: {}, additionalProperties: false },\n output: settingsResponseSchema,\n errors,\n },\n updateSessionScope: {\n input: {\n type: \"object\",\n properties: {\n mode: { type: \"string\", enum: [\"all\", \"only\"] },\n action: { type: \"string\", enum: [\"only\", \"disarm\", \"clear\"] },\n sessionID: { type: \"string\", maxLength: 200 },\n },\n additionalProperties: false,\n },\n output: {\n type: \"object\",\n properties: {\n sessionScope: sessionScopeSchema,\n settings: settingsSchema,\n },\n required: [\"sessionScope\", \"settings\"],\n additionalProperties: false,\n },\n errors,\n },\n },\n events: {\n changed: {\n schema: {\n type: \"object\",\n properties: {\n store: { type: \"string\" },\n reason: { type: \"string\", enum: [\"append\", \"truncate\", \"error\"] },\n at: { type: \"string\" },\n },\n required: [\"store\", \"reason\", \"at\"],\n additionalProperties: false,\n },\n },\n settingsChanged: {\n schema: settingsResponseSchema,\n },\n },\n})\n",
|
|
14
|
+
"import { DEFAULT_DISK_BUDGET } from \"./core\"\n\n/**\n * Every setting. The plugin's server storage is the only source of truth: the\n * configuration file registers the plugin, but it never carries settings.\n */\nexport type Settings = {\n readonly enabled: boolean\n readonly http: boolean\n /** Total store budget in bytes. Zero means no byte budget. */\n readonly diskBudget: number\n /** Remove sessions inactive for longer than this. Zero means unlimited. */\n readonly retentionMaxAgeDays: number\n /** Keep at most this many sessions. Zero means unlimited. */\n readonly retentionMaxSessions: number\n /** Store root. Empty means the platform default. */\n readonly directory: string\n /** Allow destructive actions from the viewer. */\n readonly maintenance: boolean\n}\n\n/** Settings live under this key. */\nexport const SETTINGS_KEY = \"settings\"\n\n/** A setting must stay sane; the UI offers presets well below these limits. */\nexport const MAX_SETTINGS_DISK_BUDGET = 8 * 1024 * 1024 * 1024\nexport const MAX_SETTINGS_RETENTION_DAYS = 3650\nexport const MAX_SETTINGS_RETENTION_SESSIONS = 10_000\nexport const MAX_SETTINGS_DIRECTORY = 4096\n\nexport const DEFAULT_SETTINGS: Settings = {\n enabled: true,\n http: false,\n diskBudget: DEFAULT_DISK_BUDGET,\n retentionMaxAgeDays: 30,\n retentionMaxSessions: 200,\n directory: \"\",\n maintenance: true,\n}\n\n/** A fresh copy of the built-in settings, safe for an editor to mutate. */\nexport function defaultSettings(): Settings {\n return { ...DEFAULT_SETTINGS }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n}\n\nfunction isBoundedInteger(value: unknown, max: number): value is number {\n return (\n typeof value === \"number\" &&\n Number.isFinite(value) &&\n value >= 0 &&\n Math.floor(value) === value &&\n value <= max\n )\n}\n\nfunction boundedInteger(value: unknown, max: number, fallback: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) return fallback\n return Math.min(max, Math.floor(value))\n}\n\nfunction directoryValue(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined\n return value.trim().slice(0, MAX_SETTINGS_DIRECTORY)\n}\n\nfunction overlay(target: Settings, value: unknown): Settings {\n if (!isRecord(value)) return target\n const next: { -readonly [K in keyof Settings]: Settings[K] } = { ...target }\n if (typeof value.enabled === \"boolean\") next.enabled = value.enabled\n if (typeof value.http === \"boolean\") next.http = value.http\n next.diskBudget = boundedInteger(value.diskBudget, MAX_SETTINGS_DISK_BUDGET, next.diskBudget)\n next.retentionMaxAgeDays = boundedInteger(\n value.retentionMaxAgeDays,\n MAX_SETTINGS_RETENTION_DAYS,\n next.retentionMaxAgeDays,\n )\n next.retentionMaxSessions = boundedInteger(\n value.retentionMaxSessions,\n MAX_SETTINGS_RETENTION_SESSIONS,\n next.retentionMaxSessions,\n )\n const directory = directoryValue(value.directory)\n if (directory !== undefined) next.directory = directory\n if (typeof value.maintenance === \"boolean\") next.maintenance = value.maintenance\n return next\n}\n\n/**\n * Read a stored value defensively. A value written by a newer version, a\n * manual edit or a corrupted store is replaced field by field with a default\n * instead of breaking logging.\n */\nexport function sanitizeSettings(value: unknown): Settings {\n return overlay(defaultSettings(), value)\n}\n\n/**\n * Strict validation for a user action. Unlike `sanitizeSettings`, a malformed\n * request fails loudly instead of being silently repaired.\n */\nexport function isValidSettings(value: unknown): value is Settings {\n if (!isRecord(value)) return false\n if (typeof value.enabled !== \"boolean\" || typeof value.http !== \"boolean\") return false\n if (typeof value.maintenance !== \"boolean\") return false\n if (typeof value.directory !== \"string\" || value.directory.length > MAX_SETTINGS_DIRECTORY) return false\n return (\n isBoundedInteger(value.diskBudget, MAX_SETTINGS_DISK_BUDGET) &&\n isBoundedInteger(value.retentionMaxAgeDays, MAX_SETTINGS_RETENTION_DAYS) &&\n isBoundedInteger(value.retentionMaxSessions, MAX_SETTINGS_RETENTION_SESSIONS)\n )\n}\n\n/** Reads the `{ settings }` envelope used by the RPC methods and event. */\nexport function settingsFromEnvelope(value: unknown): Settings {\n return sanitizeSettings(isRecord(value) ? value.settings : undefined)\n}\n\n/**\n * Strip the computed `retention` policy that only exists in the status view\n * before writing a settings object back over the RPC.\n */\nexport function pickSettings(value: Settings): Settings {\n return {\n enabled: value.enabled,\n http: value.http,\n diskBudget: value.diskBudget,\n retentionMaxAgeDays: value.retentionMaxAgeDays,\n retentionMaxSessions: value.retentionMaxSessions,\n directory: value.directory,\n maintenance: value.maintenance,\n }\n}\n",
|
|
15
|
+
"/**\n * Session-scoped logging. `enabled` stays the master switch; this scope only\n * decides which sessions are written while it is on.\n *\n * The scope is runtime state, persisted in the plugin's server storage next to\n * the settings. `mode: \"all\"` keeps the historical behaviour.\n * `mode: \"only\"` writes the listed sessions and nothing else; an empty list is\n * a deliberate pause, not a fallback to every session.\n */\nexport type SessionMode = \"all\" | \"only\"\n\nexport type SessionScope = {\n readonly mode: SessionMode\n readonly sessions: readonly string[]\n readonly max: number\n}\n\n/**\n * A validated transition request. `mode` and `action` are mutually exclusive:\n * a mode switches the whole scope, an action changes the selected session.\n */\nexport type SessionScopeChange = {\n /** Switch every session back on, or keep the current selection limited. */\n readonly mode?: SessionMode\n /**\n * `only` records exactly this session and pauses the others; `disarm` drops\n * this session from the selection (the scope stays limited); `clear` drops\n * every selection and pauses logging.\n */\n readonly action?: \"only\" | \"disarm\" | \"clear\"\n readonly sessionID?: string\n}\n\n/** Runtime key. The settings key is \"settings\"; this is the same kind of state. */\nexport const SESSION_SCOPE_KEY = \"sessionScope\"\n\n/** A bounded allowlist keeps stale session IDs from accumulating forever. */\nexport const MAX_SESSION_SCOPE = 50\n\nexport function emptySessionScope(): SessionScope {\n return { mode: \"all\", sessions: [], max: MAX_SESSION_SCOPE }\n}\n\n/**\n * Read a stored scope defensively. A value written by a newer version, a\n * manual edit or a corrupted store falls back to the default (all sessions)\n * instead of breaking logging. Session IDs are bounded and deduplicated.\n */\nexport function parseSessionScope(value: unknown): SessionScope {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return emptySessionScope()\n }\n const record = value as Record<string, unknown>\n const sessions: string[] = []\n const seen = new Set<string>()\n if (Array.isArray(record.sessions)) {\n for (const entry of record.sessions) {\n if (typeof entry !== \"string\") continue\n const sessionID = entry.trim()\n if (sessionID === \"\" || sessionID.length > 200 || seen.has(sessionID)) continue\n seen.add(sessionID)\n sessions.push(sessionID)\n if (sessions.length >= MAX_SESSION_SCOPE) break\n }\n }\n return {\n mode: record.mode === \"only\" ? \"only\" : \"all\",\n sessions,\n max: MAX_SESSION_SCOPE,\n }\n}\n\n/**\n * What the hook gate asks: is this session written at all? Unlike\n * `isSelected`, a session in `mode: \"all\"` is allowed even though it is not in\n * the list.\n */\nexport function sessionAllowed(scope: SessionScope, sessionID: string | undefined): boolean {\n if (sessionID === undefined || sessionID === \"\") return false\n return scope.mode === \"all\" || scope.sessions.includes(sessionID)\n}\n\n/** Whether the user explicitly selected this session in the limited scope. */\nexport function isSelected(scope: SessionScope | undefined, sessionID: string | undefined): boolean {\n if (scope === undefined || scope.mode !== \"only\" || sessionID === undefined) return false\n return scope.sessions.includes(sessionID)\n}\n\n/** Short label shared by the TUI header, the desktop subtitle and toasts. */\nexport function scopeLabel(scope: SessionScope | undefined, enabled: boolean, sessionID?: string): string {\n if (!enabled) return \"off\"\n if (scope === undefined) return \"unavailable\"\n if (scope.mode === \"all\") return \"all sessions\"\n if (scope.sessions.length === 0) return \"paused\"\n if (sessionID !== undefined && isSelected(scope, sessionID)) return \"this session\"\n return scope.sessions.length === 1 ? \"1 session\" : `${scope.sessions.length} sessions`\n}\n\n/** \"Log only this session\": an exclusive selection. */\nexport function onlySession(scope: SessionScope, sessionID: string): SessionScope {\n return { mode: \"only\", sessions: [sessionID], max: scope.max }\n}\n\n/** Remove one selected session; the scope stays limited, possibly paused. */\nexport function removeSession(scope: SessionScope, sessionID: string): SessionScope {\n return {\n mode: scope.mode,\n sessions: scope.sessions.filter((entry) => entry !== sessionID),\n max: scope.max,\n }\n}\n\n/** Keep the limited scope but select nothing: logging is paused. */\nexport function clearSessions(scope: SessionScope): SessionScope {\n return { mode: \"only\", sessions: [], max: scope.max }\n}\n\n/** Back to the historical behaviour: every session is written. */\nexport function allSessions(scope: SessionScope): SessionScope {\n return { mode: \"all\", sessions: [], max: scope.max }\n}\n\n/**\n * Apply a validated change. The handler rejects unknown or incomplete\n * requests first; an empty ID here is a defensive no-op, never a selection\n * with an empty string.\n */\nexport function changeSessionScope(scope: SessionScope, change: SessionScopeChange): SessionScope {\n const sessionID = change.sessionID?.trim() ?? \"\"\n if (change.action === \"only\") return sessionID === \"\" ? scope : onlySession(scope, sessionID)\n if (change.action === \"disarm\") return sessionID === \"\" ? scope : removeSession(scope, sessionID)\n if (change.action === \"clear\") return clearSessions(scope)\n if (change.mode === \"all\") return allSessions(scope)\n return { ...scope, mode: \"only\" }\n}\n",
|
|
16
|
+
"import { sanitizeSettings, type Settings } from \"./settings\"\nimport {\n emptySessionScope,\n parseSessionScope,\n type SessionScope,\n} from \"./session-scope\"\n\n/**\n * How often a running location re-reads the global runtime state. Settings and\n * the session scope can be changed from any location (or another process\n * sharing the same storage), so a cached value must expire eventually. A\n * second keeps the hot path free of storage reads while a change still reaches\n * every active session promptly.\n */\nexport const RUNTIME_REFRESH_MS = 1_000\n\nexport type RuntimeReader = {\n readonly settings: () => Promise<unknown>\n readonly scope: () => Promise<unknown>\n}\n\nexport type RuntimeStateOptions = {\n readonly ttlMs?: number\n readonly now?: () => number\n readonly onError?: (source: \"settings\" | \"scope\", error: unknown) => void\n}\n\nexport type RuntimeState = {\n readonly settings: Settings\n readonly scope: SessionScope\n refresh(force?: boolean): Promise<void>\n applySettings(settings: Settings): void\n applyScope(scope: SessionScope): void\n /** Back to the values this instance started with, not the built-in defaults. */\n reset(): void\n}\n\ntype Slot<T> = {\n readonly value: T\n refresh(force?: boolean): Promise<void>\n set(value: T): void\n reset(): void\n}\n\ntype SlotOptions = {\n readonly ttlMs: number\n readonly now: () => number\n readonly onError?: (error: unknown) => void\n}\n\n/**\n * A small read-through cache for one stored value. It never reads on the hot\n * path while the value is fresh, deduplicates concurrent reads, and lets a\n * local update win over a read that was already in flight.\n */\nfunction createSlot<T>(\n initial: T,\n read: () => Promise<unknown>,\n parse: (raw: unknown) => T,\n options: SlotOptions,\n): Slot<T> {\n let value = initial\n let readAt = Number.NEGATIVE_INFINITY\n let revision = 0\n let inFlight: Promise<void> | null = null\n let inFlightId = 0\n let callSeq = 0\n let lastReadStart = 0\n let lastError: string | null = null\n\n const apply = (next: T): void => {\n value = next\n }\n\n const refresh = async (force = false): Promise<void> => {\n if (!force && options.now() - readAt < options.ttlMs) return\n\n const call = ++callSeq\n if (inFlight !== null) {\n await inFlight.catch(() => {})\n // A non-forced caller is satisfied by the read that just finished. A\n // forced caller reuses it only when it started after this call began.\n if (!force) return\n if (lastReadStart > call) return\n }\n if (!force && options.now() - readAt < options.ttlMs) return\n\n const startedRevision = revision\n const id = ++callSeq\n lastReadStart = id\n inFlightId = id\n // Mark the attempt now: a failed read backs off for one TTL instead of\n // hammering storage on every model request.\n readAt = options.now()\n\n const pending = (async () => {\n try {\n const next = parse(await read())\n lastError = null\n if (startedRevision !== revision) return\n apply(next)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (message !== lastError) {\n lastError = message\n options.onError?.(error)\n }\n } finally {\n if (inFlightId === id) {\n inFlight = null\n inFlightId = 0\n }\n }\n })()\n\n inFlight = pending\n return pending\n }\n\n const set = (next: T): void => {\n revision += 1\n readAt = options.now()\n lastError = null\n apply(next)\n }\n\n return {\n get value() {\n return value\n },\n refresh,\n set,\n reset: () => set(initial),\n }\n}\n\n/**\n * The runtime state shared by every hook: the settings and the session scope.\n * Both are global (stored in the plugin's server-side storage), but each\n * location loads its own copy. The TTL is what lets a running location observe\n * a change made by another one without reading storage on every request.\n */\nexport function createRuntimeState(\n initial: Settings,\n read: RuntimeReader,\n state: RuntimeStateOptions = {},\n): RuntimeState {\n const ttlMs = state.ttlMs ?? RUNTIME_REFRESH_MS\n const now = state.now ?? Date.now\n\n const settings = createSlot<Settings>(initial, read.settings, sanitizeSettings, {\n ttlMs,\n now,\n onError: (error) => state.onError?.(\"settings\", error),\n })\n\n const scope = createSlot<SessionScope>(\n emptySessionScope(),\n read.scope,\n parseSessionScope,\n {\n ttlMs,\n now,\n onError: (error) => state.onError?.(\"scope\", error),\n },\n )\n\n return {\n get settings() {\n return settings.value\n },\n get scope() {\n return scope.value\n },\n async refresh(force = false) {\n await Promise.all([settings.refresh(force), scope.refresh(force)])\n },\n applySettings(next) {\n settings.set(next)\n },\n applyScope(next) {\n scope.set(next)\n },\n reset() {\n settings.reset()\n scope.reset()\n },\n }\n}\n"
|
|
7
17
|
],
|
|
8
|
-
"mappings": ";;AAAA;;;ACAA;AACA;AACA;AA6BO,SAAS,WAAW,CACzB,MAA0C,QAAQ,KAClD,WAAmB,QAAQ,UACnB;AAAA,EACR,MAAM,OAAO,KAAK,YAAY,gBAAgB;AAAA,EAC9C,IAAI,aAAa,SAAS;AAAA,IACxB,OAAO,KAAK,IAAI,gBAAgB,KAAK,QAAQ,GAAG,WAAW,OAAO,GAAG,IAAI;AAAA,EAC3E;AAAA,EACA,IAAI,aAAa,UAAU;AAAA,IACzB,OAAO,KAAK,QAAQ,GAAG,WAAW,uBAAuB,IAAI;AAAA,EAC/D;AAAA,EACA,OAAO,KAAK,IAAI,kBAAkB,KAAK,QAAQ,GAAG,UAAU,OAAO,GAAG,IAAI;AAAA;AAIrE,IAAM,uBAAuB,MAAM,OAAO;AAG1C,IAAM,gBAAgB,CAAC,WAAW,cAAc,YAAY,OAAO;AA8BnE,SAAS,WAAW,CAAC,SAA0B;AAAA,EACpD,OAAO,QAAQ,QAAQ,YAAY;AAAA;AAG9B,SAAS,SAAS,CAAC,SAA2B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YAAY;AAAA,QACpC;AAAA,QACA,IAAI,CAAC,cAAc,QAAQ,SAAS;AAAA,UAAc,MAAM;AAAA,QACxD,MAAM,aAAa;AAAA,QACnB,OAAO,EAAE,cAAc,QAAQ,OAAO,UAAU,QAAQ,SAAS;AAAA;AAAA,IAErE,CAAC,EACA,MAAM,CAAC,UAAmB;AAAA,MACzB,QAAQ,MAAM,qDAAqD,OAAO,KAAK,GAAG;AAAA,MAClF,OAAO;AAAA,KACR;AAAA,IAEH,IAAI,iBAAiB;AAAA,MAAM,SAAS,aAAa;AAAA,IAEjD,OAAO,YAAY;AAAA,MACjB,IAAI,gBAAgB,MAAM;AAAA,QACxB,aAAa,WAAW;AAAA,QACxB,cAAc;AAAA,MAChB;AAAA,MACA,cAAc,UAAU;AAAA,MACxB,aAAa,YAAY;AAAA,MACzB,aAAa,IAAI;AAAA,MACjB,SAAS,IAAI;AAAA,MACb,MAAM,cAAc,QAAQ;AAAA,MAC5B,WAAW,QAAQ;AAAA,QAAe,MAAM,KAAK,QAAQ;AAAA;AAAA;AAG3D,CAAC;",
|
|
19
|
+
"debugId": "917613547F8D31BB64756E2164756E21",
|
|
10
20
|
"names": []
|
|
11
21
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** How the bytes on the wire were encoded. */
|
|
2
|
+
export type BodyEncoding = "identity" | "gzip" | "deflate" | "br" | "zstd" | "unknown";
|
|
3
|
+
export type CapturedBodyBytes = {
|
|
4
|
+
/** The bytes kept in the log (possibly a prefix when the body is huge). */
|
|
5
|
+
readonly bytes: Buffer;
|
|
6
|
+
readonly encoding: BodyEncoding;
|
|
7
|
+
readonly contentType: string | null;
|
|
8
|
+
/** Length of the complete body before any capture cap. */
|
|
9
|
+
readonly bodyBytes: number;
|
|
10
|
+
readonly truncated: boolean;
|
|
11
|
+
/** SHA-256 of the complete body. */
|
|
12
|
+
readonly hash: string;
|
|
13
|
+
};
|
|
14
|
+
/** A single body is capped so one request cannot exhaust the server memory. */
|
|
15
|
+
export declare const MAX_BODY_BYTES: number;
|
|
16
|
+
/** A decompressed body is capped too: a small gzip stream can expand hugely. */
|
|
17
|
+
export declare const MAX_DECODED_BYTES: number;
|
|
18
|
+
/**
|
|
19
|
+
* Read the request body as bytes, detect compression, and keep a lossless
|
|
20
|
+
* representation. Decoding the bytes with `Request.text()` destroyed gzip
|
|
21
|
+
* bodies: every 0x8b became U+FFFD and the payload was no longer recoverable.
|
|
22
|
+
*
|
|
23
|
+
* The returned `bytes` are the raw wire bytes (a prefix only when the body
|
|
24
|
+
* exceeds the cap).
|
|
25
|
+
*/
|
|
26
|
+
export type DecodedBody = {
|
|
27
|
+
readonly text: string | null;
|
|
28
|
+
readonly base64: string | null;
|
|
29
|
+
readonly decodedBytes: number | null;
|
|
30
|
+
};
|
|
31
|
+
/** Decode bytes that were stored in a v2 body blob. */
|
|
32
|
+
export declare function decodeStoredBody(bytes: Buffer, encoding: BodyEncoding): DecodedBody;
|
|
33
|
+
/** Keep the longest prefix of `text` that fits in `maxBytes` of UTF-8. */
|
|
34
|
+
export declare function sliceUtf8(text: string, maxBytes: number): string;
|
|
35
|
+
/**
|
|
36
|
+
* Read the request body as raw wire bytes, without decompressing or encoding
|
|
37
|
+
* it. The v2 writer stores the bytes as a blob and decodes only when a viewer
|
|
38
|
+
* opens the record, so the model-request path does not pay for a body it will
|
|
39
|
+
* not render.
|
|
40
|
+
*/
|
|
41
|
+
export declare function captureBodyBytes(request: Request): Promise<CapturedBodyBytes>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Entries returned by one `list` call. */
|
|
2
|
+
export declare const DEFAULT_PAGE = 50;
|
|
3
|
+
export declare const MAX_PAGE = 200;
|
|
4
|
+
/** One request returned by `read`, before the viewer asks for more. */
|
|
5
|
+
export declare const MAX_RECORD_BYTES: number;
|
|
6
|
+
/** Hard ceiling for an explicit "load complete entry" read. */
|
|
7
|
+
export declare const MAX_FULL_RECORD_BYTES: number;
|
|
8
|
+
/** A full-text search stops at whichever budget expires first. */
|
|
9
|
+
export declare const MAX_SEARCH_BYTES: number;
|
|
10
|
+
export declare const MAX_SEARCH_MS = 2000;
|
|
11
|
+
export declare const MAX_SEARCH_QUERY = 500;
|
|
12
|
+
export declare const MAX_SEARCH_RESULTS = 100;
|
|
13
|
+
/** One `changed` event per second at most, however busy the store is. */
|
|
14
|
+
export declare const EVENT_COALESCE_MS = 1000;
|
|
15
|
+
/**
|
|
16
|
+
* Bench ceilings. They are intentionally loose: a regression that parses a
|
|
17
|
+
* whole request or rescans a session file is orders of magnitude slower.
|
|
18
|
+
*/
|
|
19
|
+
export declare const BENCH_BUDGETS: {
|
|
20
|
+
readonly listMs: 20;
|
|
21
|
+
readonly readMs: 100;
|
|
22
|
+
readonly searchMs: 2000;
|
|
23
|
+
readonly heapMb: 256;
|
|
24
|
+
};
|
|
25
|
+
export declare function clampInteger(value: unknown, min: number, max: number, fallback: number): number;
|
|
26
|
+
export declare function clampPage(value: unknown): number;
|
|
27
|
+
export declare function clampReadBytes(value: unknown): number;
|
|
28
|
+
export declare function clampSearchBytes(value: unknown): number;
|
|
29
|
+
export declare function clampSearchMs(value: unknown): number;
|
|
30
|
+
export declare function boundedString(value: unknown, maxLength: number): string | undefined;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The store lives in its own directory, never directly in the shared `opencode`
|
|
3
|
+
* tree. That lets the plugin keep the directory private (`0700`) without
|
|
4
|
+
* touching a directory OpenCode and every other plugin also write to.
|
|
5
|
+
*
|
|
6
|
+
* - Windows: `%LOCALAPPDATA%\opencode\prompt-logger`
|
|
7
|
+
* - macOS: `~/Library/Application Support/opencode/prompt-logger`
|
|
8
|
+
* - Linux/other: `$XDG_STATE_HOME/opencode/prompt-logger`,
|
|
9
|
+
* falling back to `~/.local/state/opencode/prompt-logger`
|
|
10
|
+
*
|
|
11
|
+
* Pure by design so every OS can be asserted from any machine.
|
|
12
|
+
*/
|
|
13
|
+
export declare function defaultDir(env?: Record<string, string | undefined>, platform?: string): string;
|
|
14
|
+
/** Expand a leading `~` or `~/` the way every shell does. */
|
|
15
|
+
export declare function expandHome(path: string, home?: string): string;
|
|
16
|
+
/**
|
|
17
|
+
* Resolve the effective store root. A configured path may be absolute, start
|
|
18
|
+
* with `~`, or be relative to the project location. The result is always an
|
|
19
|
+
* absolute path, so the writer, the reader and the UI act on the same store.
|
|
20
|
+
*/
|
|
21
|
+
export declare function resolveLogDirectory(configured: string | undefined, base?: string, env?: Record<string, string | undefined>, platform?: string): string;
|
|
22
|
+
/**
|
|
23
|
+
* Keep the plugin's own directory private. A configured root is not ours to
|
|
24
|
+
* chmod, but the per-session directories created inside it are.
|
|
25
|
+
*/
|
|
26
|
+
export declare function hardenDirectory(dir: string): void;
|
|
27
|
+
/** The store carries unredacted prompts, so every file is owner-only on POSIX. */
|
|
28
|
+
export declare function hardenFile(file: string): void;
|
|
29
|
+
export type PathState = {
|
|
30
|
+
readonly exists: boolean;
|
|
31
|
+
readonly regular: boolean;
|
|
32
|
+
readonly symlink: boolean;
|
|
33
|
+
readonly mode: number | null;
|
|
34
|
+
readonly directoryMode: number | null;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* The filesystem facts the UI needs: whether the path exists, its mode and
|
|
38
|
+
* whether it is a symlink. It never changes anything. The store-specific
|
|
39
|
+
* warnings are built by the v2 status, because they depend on it being a
|
|
40
|
+
* directory rather than a file.
|
|
41
|
+
*/
|
|
42
|
+
export declare function inspectPath(file: string): PathState;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Untrusted log content is rendered as plain text. Prompts and tool output can
|
|
3
|
+
* contain terminal control sequences: an escape sequence could clear the TUI,
|
|
4
|
+
* move the cursor, spoof a prompt, or set the window title. The viewer strips
|
|
5
|
+
* them before rendering, and caps the result so one record cannot freeze the
|
|
6
|
+
* layout.
|
|
7
|
+
*
|
|
8
|
+
* The raw record is never modified; this is a display-only transformation.
|
|
9
|
+
*/
|
|
10
|
+
export type SanitizedText = {
|
|
11
|
+
readonly text: string;
|
|
12
|
+
/** True when `limit` cut the input; the text carries a visible marker. */
|
|
13
|
+
readonly truncated: boolean;
|
|
14
|
+
};
|
|
15
|
+
export declare function sanitizeTerminalInfo(input: string, limit?: number): SanitizedText;
|
|
16
|
+
export declare function sanitizeTerminal(input: string, limit?: number): string;
|