UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

599 lines (598 loc) • 24.8 kB
import "./redact-BDinS1q9.js"; import "./errors-BxyFnvP3.js"; import "./unhandled-rejections-CDJ8dOVP.js"; import "./logger-kwZIqwuw.js"; import "./paths-ViKUYWUK.js"; import "./tmp-openclaw-dir-idKIOMmb.js"; import { n as isRich, r as theme } from "./theme-CdOoMzRk.js"; import { s as setVerbose } from "./globals-DBUMOBZ8.js"; import { h as writeRuntimeJson, m as defaultRuntime } from "./subsystem-DISldKSB.js"; import "./ansi-BEJF8NKS.js"; import "./boolean-C3GkJetE.js"; import "./env-Dnra1IpT.js"; import "./warning-filter-CBhOcgHd.js"; import "./utils-CS0Ikux6.js"; import { t as formatDocsLink } from "./links-8xRhWBQL.js"; import "./paths-C4Oy7wjk.js"; import "./auth-profiles-DRuJBw5y.js"; import "./agent-scope-bjWqU22i.js"; import "./boundary-path-Dm0QJ7-y.js"; import "./boundary-file-read-DcZxlWD8.js"; import "./logger-BmpSCz93.js"; import "./exec-B5_AYfQG.js"; import "./workspace-D4K6QX9X.js"; import "./model-selection-BnFtDmP7.js"; import { s as loadConfig } from "./io-y3Az_Onx.js"; import "./shell-env-BOu7XeT_.js"; import "./safe-text-yavot2qw.js"; import "./version-CD3oP1-d.js"; import "./env-substitution-O6uabUmO.js"; import "./includes-Bj3eLUWH.js"; import "./zod-schema.providers-core-COy5nBQ0.js"; import "./legacy-web-search-BB-ZHEhz.js"; import "./registry-C5UkPpaO.js"; import "./config-state-Br0ucqMb.js"; import "./min-host-version-RMBWtIAR.js"; import "./manifest-registry-B5JNQdOM.js"; import "./runtime-guard-PhQ6PwQa.js"; import "./avatar-policy-B5nOfso_.js"; import "./ip-Ce8EDTBZ.js"; import "./zod-schema.agent-runtime-Dtg4Jy6G.js"; import "./zod-schema.core-BuVz8Rk7.js"; import "./config-D4zN4BRl.js"; import "./file-lock-DEiVq2ow.js"; import "./audit-fs-DTQIjp2r.js"; import "./resolve-B7S4PlnO.js"; import "./profiles-COPO-hHI.js"; import "./tailscale-CxY-91GZ.js"; import "./tailnet-DHiKSG7V.js"; import "./net-JAg9zL0G.js"; import "./auth-Buq0Niri.js"; import "./credentials-D8pfRimu.js"; import "./message-channel-BliByQBl.js"; import { d as capEntryCount, f as pruneStaleEntries, l as updateSessionStore, m as enforceSessionDiskBudget, n as loadSessionStore, p as resolveMaintenanceConfig } from "./store-C5UK26Ce.js"; import "./runtime-Iz8uZ7EU.js"; import "./plugins-B09-vgme.js"; import "./sessions-D9ZgHCHb.js"; import { i as resolveSessionFilePathOptions, r as resolveSessionFilePath } from "./paths-rhN9LKM_.js"; import "./session-write-lock-va3qZE6f.js"; import "./method-scopes-BiEi0X2g.js"; import "./call-CQbSO4Fr.js"; import "./control-ui-shared-BBhZvISc.js"; import "./onboard-helpers-D5cfC-Ra.js"; import "./prompt-style-C4CV4Y_p.js"; import "./ports-lsof-BLEgL_Gn.js"; import "./restart-stale-pids-BsPvlGJd.js"; import "./runtime-parse-BUn1nl6s.js"; import "./launchd-yOx8f787.js"; import "./service-DdJ2Qk7P.js"; import "./ports-FldL_Lhq.js"; import "./systemd-bGhJCG6J.js"; import "./logging-CznuqaMu.js"; import "./commands-C6oAw_H-.js"; import "./probe-BPU90Y9V.js"; import "./issue-format-BtLIwOtN.js"; import "./diagnostics-CwDNepDU.js"; import "./probe-auth-dhNhn0B4.js"; import "./progress-C78aA91n.js"; import { t as formatHelpExamples } from "./help-format-C_5MeE_w.js"; import "./identity-Dp-UIak4.js"; import "./heartbeat-Bdfr_onc.js"; import "./pi-embedded-CbCYZxIb.js"; import "./internal-hooks-CIUghoK4.js"; import "./multimodal-B8yEZcl5.js"; import "./memory-search-B_aq08y5.js"; import "./provider-catalog-rVN7ZbR5.js"; import "./secret-input-DXoOLNgb.js"; import "./bindings-CFudGB9Z.js"; import "./resolve-route-DwFWP4JW.js"; import "./routing-zOQ0wwtV.js"; import "./identity-file-DVLib087.js"; import "./outbound-runtime-m-y0nd6F.js"; import "./provider-env-vars-CpUJqT5v.js"; import "./provider-auth-input-Bus9W_qh.js"; import "./provider-model-minimax-DSmX4BNO.js"; import "./provider-models-BKjzpTsb.js"; import "./anthropic-vertex-provider-B2x4YywE.js"; import "./provider-catalog-BTgF8VyO.js"; import "./provider-catalog-D0IlX18O.js"; import "./provider-catalog-BTmUX0Mp.js"; import "./provider-catalog-sph_Rl63.js"; import "./provider-catalog-C7tUyBwV.js"; import "./provider-catalog-C8dPZpHW.js"; import "./provider-catalog-BJNff1VI.js"; import "./provider-catalog-IAdymoqT.js"; import "./provider-catalog-Bjc7evzh.js"; import "./models-config.providers.discovery-CjkO08q6.js"; import "./text-runtime-DVXt5xhi.js"; import "./tool-catalog-BjSY4C4F.js"; import "./docker-Bhjg8g2t.js"; import "./sandbox-DTlKNieF.js"; import "./common-zReYuoMM.js"; import "./image-ops-By4YfyWa.js"; import "./thinking-CJoSRIGR.js"; import "./path-alias-guards-CwRM04O1.js"; import "./sandbox-paths-Cn8i8Jxm.js"; import "./channel-actions-fV93bLjV.js"; import "./mime-CsUtzcn2.js"; import "./ssrf-0bPJMoZR.js"; import "./fetch-guard-CYl1q2XH.js"; import "./provider-web-search-COZNygbd.js"; import "./manager-Bw8JrihM.js"; import "./config-schema-CPzP2Ds6.js"; import "./channel-plugin-common-ClptUZHU.js"; import "./status-helpers-Cflmo90d.js"; import "./conversation-runtime-nmWgJSXS.js"; import "./runtime-whatsapp-boundary-XjdkYMz_.js"; import "./pairing-store-BGKLrjo6.js"; import "./json-store--JDX3zNL.js"; import "./secret-file-Bif7RlZ-.js"; import "./channel-config-schema-CgpS17zB.js"; import "./setup-binary-C2MYZTCc.js"; import "./archive-pOxyr9r4.js"; import "./fs-safe-DZyOgpPN.js"; import "./signal-cli-install-fVOL9FvX.js"; import "./setup-wizard-proxy-DoOpOF8S.js"; import "./setup-BI3ohdrT.js"; import "./dm-policy-shared-DtcQProI.js"; import "./runtime-env-DQOYrXVl.js"; import "./temp-path-B91lt0LF.js"; import "./diagnostic-CDTtMQBT.js"; import "./logging-CCTKg_fh.js"; import "./config-runtime-BYNizC50.js"; import "./level-overrides-DzIzQ3ZY.js"; import "./exec-approvals-BF_Qfdq8.js"; import "./webhook-ingress-D-H5frou.js"; import "./system-events-BU_NYynX.js"; import "./ssrf-policy-DYINyIKC.js"; import "./hook-runtime-BUYmDbaA.js"; import "./templating-BDXRiJUh.js"; import "./channel-reply-pipeline-BxH4-AP2.js"; import "./reply-history-n7nOPLta.js"; import "./commands-registry.data-BFXJWoqi.js"; import "./commands-registry-Bh9pJ817.js"; import "./frontmatter-CP5371Rm.js"; import "./env-overrides-BNSo89u5.js"; import "./skills-M0AZJeXx.js"; import "./skills-remote-BHxDA4Jw.js"; import "./workspace-dirs-DqDLiRvZ.js"; import "./pairing-token-DAszGmwD.js"; import "./skill-commands-D73dGR_l.js"; import "./config-CLRQPUSt.js"; import "./routes-XT2JfvT-.js"; import "./ssh-tunnel-LM52qY6N.js"; import "./server-middleware-BP59C6FL.js"; import "./provider-auth-ref-CQEp9sp3.js"; import "./provider-auth-helpers-Do3RFvdi.js"; import "./provider-api-key-auth-BEeRW3dq.js"; import "./pairing-labels-D27Y4Vv6.js"; import "./directory-runtime-D9Y42mW-.js"; import "./read-only-account-inspect-CJPRBFj7.js"; import "./src-BoNU6eQs.js"; import "./web-media-PKy3RbRG.js"; import "./media-understanding-BDOSvuM9.js"; import "./web-media-CiSbdGPs.js"; import "./state-paths-Dvb3Mfl3.js"; import "./llm-task-Br6Ixjlh.js"; import "./pi-model-discovery-DO3tFksS.js"; import "./exec-inline-eval-CpmxWJsW.js"; import "./target-registry-9OUOvlxj.js"; import "./external-content-DZI9vlJn.js"; import "./brave-onFD06fq.js"; import "./duckduckgo-CZuAOfiQ.js"; import "./exa-5bwgY04k.js"; import "./security-runtime-xlw0Fxx2.js"; import "./provider-usage-ClxTGn5c.js"; import "./provider-models-Bjv0V4OP.js"; import "./media-understanding-provider-DllGbg-v.js"; import "./media-understanding-provider-BDq4rFL-.js"; import "./provider-onboard-CSnPvkMM.js"; import "./onboard-BU8aRvq7.js"; import "./perplexity-web-search-provider-CI38RNUU.js"; import "./perplexity-CMZbsreI.js"; import "./model-definitions-CLagLj0g.js"; import "./onboard-0P7GBI2D.js"; import "./provider-catalog-CKHo9CRM.js"; import "./provider-models-Dmjtw6kn.js"; import "./stream-C-KGzzT0.js"; import "./web-search-CO1hvu_l.js"; import "./stagger-CFqdtCYL.js"; import "./command-secret-targets-DLs8jC2H.js"; import "./delivery-queue-DHURMSqX.js"; import "./channel-summary-Ctrv7moa.js"; import "./follow-redirects-CVAaqIk4.js"; import "./tool-policy-match-DQWWRSN4.js"; import "./runtime-CAdCdG-M.js"; import "./channel-status-BfM90KqH.js"; import "./discord-core-DLbIyXWy.js"; import "./cli-runtime-Cx1v7N7v.js"; import "./config-presence-DA3j8Nmi.js"; import "./query-expansion-BOJBTXsp.js"; import "./search-manager-DNBHwaee.js"; import "./acp-runtime-BHZj-SLU.js"; import "./telegram-core-DD8gCuaX.js"; import "./audit-BI48Fi3j.js"; import "./gateway-runtime-Dn2qAGY7.js"; import "./connection-auth-Nl2a3tDb.js"; import "./mcp-config-CDIWSqVk.js"; import "./skills-status-BhDjqqQc.js"; import "./status-DI5hmNdJ.js"; import { n as runCommandWithRuntime } from "./cli-utils-C5ijQCJ_.js"; import { n as parsePositiveIntOrUndefined } from "./helpers-CvoyfQ8F.js"; import "./table-7g_hocqO.js"; import "./status.summary-BK0AMFlQ.js"; import "./heartbeat-summary-B-oiNNxm.js"; import { r as healthCommand } from "./health-CSjz5K7z.js"; import "./update-check-PKXwMGZy.js"; import { t as statusCommand } from "./status-DjCnca8z.js"; import "./node-service-D4mvvQIK.js"; import "./channels-status-issues-DweHoyQa.js"; import "./channels-CRlN6PtH.js"; import "./status.update-k-L_a4xK.js"; import { a as formatSessionModelCell, c as toSessionDisplayRows, i as formatSessionKeyCell, l as resolveSessionStoreTargetsOrExit, n as formatSessionAgeCell, o as resolveSessionDisplayDefaults, r as formatSessionFlagsCell, s as resolveSessionDisplayModel, t as sessionsCommand } from "./sessions-CuRSqfRp.js"; import fs from "node:fs"; //#region src/commands/sessions-cleanup.ts const ACTION_PAD = 12; function resolveSessionCleanupAction(params) { if (params.missingKeys.has(params.key)) return "prune-missing"; if (params.staleKeys.has(params.key)) return "prune-stale"; if (params.cappedKeys.has(params.key)) return "cap-overflow"; if (params.budgetEvictedKeys.has(params.key)) return "evict-budget"; return "keep"; } function formatCleanupActionCell(action, rich) { const label = action.padEnd(ACTION_PAD); if (!rich) return label; if (action === "keep") return theme.muted(label); if (action === "prune-missing") return theme.error(label); if (action === "prune-stale") return theme.warn(label); if (action === "cap-overflow") return theme.accentBright(label); return theme.error(label); } function buildActionRows(params) { return toSessionDisplayRows(params.beforeStore).map((row) => ({ ...row, action: resolveSessionCleanupAction({ key: row.key, missingKeys: params.missingKeys, staleKeys: params.staleKeys, cappedKeys: params.cappedKeys, budgetEvictedKeys: params.budgetEvictedKeys }) })); } function pruneMissingTranscriptEntries(params) { const sessionPathOpts = resolveSessionFilePathOptions({ storePath: params.storePath }); let removed = 0; for (const [key, entry] of Object.entries(params.store)) { if (!entry?.sessionId) continue; const transcriptPath = resolveSessionFilePath(entry.sessionId, entry, sessionPathOpts); if (!fs.existsSync(transcriptPath)) { delete params.store[key]; removed += 1; params.onPruned?.(key); } } return removed; } async function previewStoreCleanup(params) { const maintenance = resolveMaintenanceConfig(); const beforeStore = loadSessionStore(params.target.storePath, { skipCache: true }); const previewStore = structuredClone(beforeStore); const staleKeys = /* @__PURE__ */ new Set(); const cappedKeys = /* @__PURE__ */ new Set(); const missingKeys = /* @__PURE__ */ new Set(); const missing = params.fixMissing === true ? pruneMissingTranscriptEntries({ store: previewStore, storePath: params.target.storePath, onPruned: (key) => { missingKeys.add(key); } }) : 0; const pruned = pruneStaleEntries(previewStore, maintenance.pruneAfterMs, { log: false, onPruned: ({ key }) => { staleKeys.add(key); } }); const capped = capEntryCount(previewStore, maintenance.maxEntries, { log: false, onCapped: ({ key }) => { cappedKeys.add(key); } }); const beforeBudgetStore = structuredClone(previewStore); const diskBudget = await enforceSessionDiskBudget({ store: previewStore, storePath: params.target.storePath, activeSessionKey: params.activeKey, maintenance, warnOnly: false, dryRun: true }); const budgetEvictedKeys = /* @__PURE__ */ new Set(); for (const key of Object.keys(beforeBudgetStore)) if (!Object.hasOwn(previewStore, key)) budgetEvictedKeys.add(key); const beforeCount = Object.keys(beforeStore).length; const afterPreviewCount = Object.keys(previewStore).length; const wouldMutate = missing > 0 || pruned > 0 || capped > 0 || Boolean((diskBudget?.removedEntries ?? 0) > 0 || (diskBudget?.removedFiles ?? 0) > 0); return { summary: { agentId: params.target.agentId, storePath: params.target.storePath, mode: params.mode, dryRun: params.dryRun, beforeCount, afterCount: afterPreviewCount, missing, pruned, capped, diskBudget, wouldMutate }, actionRows: buildActionRows({ beforeStore, staleKeys, cappedKeys, budgetEvictedKeys, missingKeys }) }; } function renderStoreDryRunPlan(params) { const rich = isRich(); if (params.showAgentHeader) params.runtime.log(`Agent: ${params.summary.agentId}`); params.runtime.log(`Session store: ${params.summary.storePath}`); params.runtime.log(`Maintenance mode: ${params.summary.mode}`); params.runtime.log(`Entries: ${params.summary.beforeCount} -> ${params.summary.afterCount} (remove ${params.summary.beforeCount - params.summary.afterCount})`); params.runtime.log(`Would prune missing transcripts: ${params.summary.missing}`); params.runtime.log(`Would prune stale: ${params.summary.pruned}`); params.runtime.log(`Would cap overflow: ${params.summary.capped}`); if (params.summary.diskBudget) params.runtime.log(`Would enforce disk budget: ${params.summary.diskBudget.totalBytesBefore} -> ${params.summary.diskBudget.totalBytesAfter} bytes (files ${params.summary.diskBudget.removedFiles}, entries ${params.summary.diskBudget.removedEntries})`); if (params.actionRows.length === 0) return; params.runtime.log(""); params.runtime.log("Planned session actions:"); const header = [ "Action".padEnd(ACTION_PAD), "Key".padEnd(26), "Age".padEnd(9), "Model".padEnd(14), "Flags" ].join(" "); params.runtime.log(rich ? theme.heading(header) : header); for (const actionRow of params.actionRows) { const model = resolveSessionDisplayModel(params.cfg, actionRow, params.displayDefaults); const line = [ formatCleanupActionCell(actionRow.action, rich), formatSessionKeyCell(actionRow.key, rich), formatSessionAgeCell(actionRow.updatedAt, rich), formatSessionModelCell(model, rich), formatSessionFlagsCell(actionRow, rich) ].join(" "); params.runtime.log(line.trimEnd()); } } async function sessionsCleanupCommand(opts, runtime) { const cfg = loadConfig(); const displayDefaults = resolveSessionDisplayDefaults(cfg); const mode = opts.enforce ? "enforce" : resolveMaintenanceConfig().mode; const targets = resolveSessionStoreTargetsOrExit({ cfg, opts: { store: opts.store, agent: opts.agent, allAgents: opts.allAgents }, runtime }); if (!targets) return; const previewResults = []; for (const target of targets) { const result = await previewStoreCleanup({ target, mode, dryRun: Boolean(opts.dryRun), activeKey: opts.activeKey, fixMissing: Boolean(opts.fixMissing) }); previewResults.push(result); } if (opts.dryRun) { if (opts.json) { if (previewResults.length === 1) { writeRuntimeJson(runtime, previewResults[0]?.summary ?? {}); return; } writeRuntimeJson(runtime, { allAgents: true, mode, dryRun: true, stores: previewResults.map((result) => result.summary) }); return; } for (let i = 0; i < previewResults.length; i += 1) { const result = previewResults[i]; if (i > 0) runtime.log(""); renderStoreDryRunPlan({ cfg, summary: result.summary, actionRows: result.actionRows, displayDefaults, runtime, showAgentHeader: previewResults.length > 1 }); } return; } const appliedSummaries = []; for (const target of targets) { const appliedReportRef = { current: null }; const missingApplied = await updateSessionStore(target.storePath, async (store) => { if (!opts.fixMissing) return 0; return pruneMissingTranscriptEntries({ store, storePath: target.storePath }); }, { activeSessionKey: opts.activeKey, maintenanceOverride: { mode }, onMaintenanceApplied: (report) => { appliedReportRef.current = report; } }); const afterStore = loadSessionStore(target.storePath, { skipCache: true }); const preview = previewResults.find((result) => result.summary.storePath === target.storePath); const appliedReport = appliedReportRef.current; const summary = appliedReport === null ? { ...preview?.summary ?? { agentId: target.agentId, storePath: target.storePath, mode, dryRun: false, beforeCount: 0, afterCount: 0, missing: 0, pruned: 0, capped: 0, diskBudget: null, wouldMutate: false }, dryRun: false, applied: true, appliedCount: Object.keys(afterStore).length } : { agentId: target.agentId, storePath: target.storePath, mode: appliedReport.mode, dryRun: false, beforeCount: appliedReport.beforeCount, afterCount: appliedReport.afterCount, missing: missingApplied, pruned: appliedReport.pruned, capped: appliedReport.capped, diskBudget: appliedReport.diskBudget, wouldMutate: missingApplied > 0 || appliedReport.pruned > 0 || appliedReport.capped > 0 || Boolean((appliedReport.diskBudget?.removedEntries ?? 0) > 0 || (appliedReport.diskBudget?.removedFiles ?? 0) > 0), applied: true, appliedCount: Object.keys(afterStore).length }; appliedSummaries.push(summary); } if (opts.json) { if (appliedSummaries.length === 1) { writeRuntimeJson(runtime, appliedSummaries[0] ?? {}); return; } writeRuntimeJson(runtime, { allAgents: true, mode, dryRun: false, stores: appliedSummaries }); return; } for (let i = 0; i < appliedSummaries.length; i += 1) { const summary = appliedSummaries[i]; if (i > 0) runtime.log(""); if (appliedSummaries.length > 1) runtime.log(`Agent: ${summary.agentId}`); runtime.log(`Session store: ${summary.storePath}`); runtime.log(`Applied maintenance. Current entries: ${summary.appliedCount ?? 0}`); } } //#endregion //#region src/cli/program/register.status-health-sessions.ts function resolveVerbose(opts) { return Boolean(opts.verbose || opts.debug); } function parseTimeoutMs(timeout) { const parsed = parsePositiveIntOrUndefined(timeout); if (timeout !== void 0 && parsed === void 0) { defaultRuntime.error("--timeout must be a positive integer (milliseconds)"); defaultRuntime.exit(1); return null; } return parsed; } async function runWithVerboseAndTimeout(opts, action) { const verbose = resolveVerbose(opts); setVerbose(verbose); const timeoutMs = parseTimeoutMs(opts.timeout); if (timeoutMs === null) return; await runCommandWithRuntime(defaultRuntime, async () => { await action({ verbose, timeoutMs }); }); } function registerStatusHealthSessionsCommands(program) { program.command("status").description("Show channel health and recent session recipients").option("--json", "Output JSON instead of text", false).option("--all", "Full diagnosis (read-only, pasteable)", false).option("--usage", "Show model provider usage/quota snapshots", false).option("--deep", "Probe channels (WhatsApp Web + Telegram + Discord + Slack + Signal)", false).option("--timeout <ms>", "Probe timeout in milliseconds", "10000").option("--verbose", "Verbose logging", false).option("--debug", "Alias for --verbose", false).addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([ ["openclaw status", "Show channel health + session summary."], ["openclaw status --all", "Full diagnosis (read-only)."], ["openclaw status --json", "Machine-readable output."], ["openclaw status --usage", "Show model provider usage/quota snapshots."], ["openclaw status --deep", "Run channel probes (WA + Telegram + Discord + Slack + Signal)."], ["openclaw status --deep --timeout 5000", "Tighten probe timeout."] ])}`).addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/status", "docs.openclaw.ai/cli/status")}\n`).action(async (opts) => { await runWithVerboseAndTimeout(opts, async ({ verbose, timeoutMs }) => { await statusCommand({ json: Boolean(opts.json), all: Boolean(opts.all), deep: Boolean(opts.deep), usage: Boolean(opts.usage), timeoutMs, verbose }, defaultRuntime); }); }); program.command("health").description("Fetch health from the running gateway").option("--json", "Output JSON instead of text", false).option("--timeout <ms>", "Connection timeout in milliseconds", "10000").option("--verbose", "Verbose logging", false).option("--debug", "Alias for --verbose", false).addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/health", "docs.openclaw.ai/cli/health")}\n`).action(async (opts) => { await runWithVerboseAndTimeout(opts, async ({ verbose, timeoutMs }) => { await healthCommand({ json: Boolean(opts.json), timeoutMs, verbose }, defaultRuntime); }); }); const sessionsCmd = program.command("sessions").description("List stored conversation sessions").option("--json", "Output as JSON", false).option("--verbose", "Verbose logging", false).option("--store <path>", "Path to session store (default: resolved from config)").option("--agent <id>", "Agent id to inspect (default: configured default agent)").option("--all-agents", "Aggregate sessions across all configured agents", false).option("--active <minutes>", "Only show sessions updated within the past N minutes").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([ ["openclaw sessions", "List all sessions."], ["openclaw sessions --agent work", "List sessions for one agent."], ["openclaw sessions --all-agents", "Aggregate sessions across agents."], ["openclaw sessions --active 120", "Only last 2 hours."], ["openclaw sessions --json", "Machine-readable output."], ["openclaw sessions --store ./tmp/sessions.json", "Use a specific session store."] ])}\n\n${theme.muted("Shows token usage per session when the agent reports it; set agents.defaults.contextTokens to cap the window and show %.")}`).addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/sessions", "docs.openclaw.ai/cli/sessions")}\n`).action(async (opts) => { setVerbose(Boolean(opts.verbose)); await sessionsCommand({ json: Boolean(opts.json), store: opts.store, agent: opts.agent, allAgents: Boolean(opts.allAgents), active: opts.active }, defaultRuntime); }); sessionsCmd.enablePositionalOptions(); sessionsCmd.command("cleanup").description("Run session-store maintenance now").option("--store <path>", "Path to session store (default: resolved from config)").option("--agent <id>", "Agent id to maintain (default: configured default agent)").option("--all-agents", "Run maintenance across all configured agents", false).option("--dry-run", "Preview maintenance actions without writing", false).option("--enforce", "Apply maintenance even when configured mode is warn", false).option("--fix-missing", "Remove store entries whose transcript files are missing (bypasses age/count retention)", false).option("--active-key <key>", "Protect this session key from budget-eviction").option("--json", "Output JSON", false).addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([ ["openclaw sessions cleanup --dry-run", "Preview stale/cap cleanup."], ["openclaw sessions cleanup --dry-run --fix-missing", "Also preview pruning entries with missing transcript files."], ["openclaw sessions cleanup --enforce", "Apply maintenance now."], ["openclaw sessions cleanup --agent work --dry-run", "Preview one agent store."], ["openclaw sessions cleanup --all-agents --dry-run", "Preview all agent stores."], ["openclaw sessions cleanup --enforce --store ./tmp/sessions.json", "Use a specific store."] ])}`).action(async (opts, command) => { const parentOpts = command.parent?.opts(); await runCommandWithRuntime(defaultRuntime, async () => { await sessionsCleanupCommand({ store: opts.store ?? parentOpts?.store, agent: opts.agent ?? parentOpts?.agent, allAgents: Boolean(opts.allAgents || parentOpts?.allAgents), dryRun: Boolean(opts.dryRun), enforce: Boolean(opts.enforce), fixMissing: Boolean(opts.fixMissing), activeKey: opts.activeKey, json: Boolean(opts.json || parentOpts?.json) }, defaultRuntime); }); }); } //#endregion export { registerStatusHealthSessionsCommands };