UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2 lines • 38.4 kB
import{D as e,Q as t,Y as n,et as r,it as i,m as a,w as o,z as s}from"./disk-budget.worker-paths-DAFiPrD7.mjs";import"./disk-budget.worker-sqlite-readonly-worker-WKiVGIHU.mjs";import{C as c,S as l,b as u,p as d,x as f,y as p}from"./disk-budget.worker-worker-cpu-C96zaKF5.mjs";import{F as m,I as h,a as g,c as _,g as v,h as y,i as b,m as x,n as S,o as C,p as w,r as T,t as E,z as ee}from"./disk-budget.worker-sqlite-lifecycle-errors-BU4Ayp4j.mjs";import{Q as te,R as D}from"./disk-budget.worker-subsystem-BalNE4hU.mjs";import"./disk-budget.worker-path-existence-OmZIMgK8.mjs";import{F as O,Gt as ne,In as k,Jt as re,L as ie,Wt as A}from"./disk-budget.worker-sqlite-worker-operation-settlement-9_4LJ7KU.mjs";import{Ct as j,b as M,f as N,v as P}from"./disk-budget.worker-spawn-diagnostics-CmOy7s7V.mjs";import{o as ae}from"./disk-budget.worker-openclaw-state-db-contract-DiFTYPe3.mjs";import{n as F}from"./disk-budget.worker-openclaw-root-DjxJFdyT.mjs";import{n as oe,p as se}from"./disk-budget.worker-worker-task-pool-CyvplXuz.mjs";import{createRequire as I}from"node:module";import{MessageChannel as L,receiveMessageOnPort as ce,threadId as R}from"node:worker_threads";import"node:crypto";import z from"node:fs";import B from"node:path";import{fileURLToPath as V}from"node:url";import"@openclaw/fs-safe/path";import{readFileDescriptorBoundedSync as H,readFileWindowFullySync as U}from"@openclaw/fs-safe/advanced";import{isUtf8 as W}from"node:buffer";const G=i(Symbol.for(`openclaw.quarantineReadCleanupError`),()=>class extends AggregateError{constructor(e,t){super(e,`OpenClaw quarantine reader cleanup failed.`,{cause:e[0]}),this.quarantine=t,this.name=`OpenClawQuarantineReadCleanupError`}}),K=i(Symbol.for(`openclaw.stateDatabaseFailurePaths`),()=>/* @__PURE__ */ new WeakMap);function markOpenClawStateDatabaseFailure(e,t){K.set(e,t)}function readOpenClawStateDatabaseFailurePath(e){return K.get(e)}function findOpenClawStateDatabaseFailure(e,t){let n=[e],r=/* @__PURE__ */ new Set;for(let e of n)if(e instanceof Error&&!r.has(e)){if(r.add(e),K.get(e)===t)return e;n.push(e.cause),e instanceof AggregateError&&n.push(...e.errors)}}var DuplicateAgentError=class extends Error{};const q=`openclaw doctor --fix`;var AuthProfileStoreUnreadableError=class extends Error{constructor(e){super(`Auth profile store ${D(e)} is unreadable; run ${q}.`),this.databasePath=e,this.code=`AUTH_PROFILE_STORE_UNREADABLE`,this.action=q,this.name=`AuthProfileStoreUnreadableError`}},McpOAuthStoreCorruptionError=class extends Error{constructor(e,t,n){super(`MCP OAuth store ${e} is invalid: ${t}`,n),this.name=`McpOAuthStoreCorruptionError`}},SandboxStateOwnerRequiredError=class extends Error{constructor(e){super(`Sandbox workspace preparation cannot run alongside a foreign live owner of the selected state root, or when that ownership cannot be verified. Run this SDK call inside the owning Gateway plugin/runtime, or stop the Gateway through its service owner and wait for any embedded run to finish, then retry offline. Inspect openclaw gateway status; this call does not acquire ownership or route remotely.`,{cause:e}),this.code=`GATEWAY_STATE_OWNER_REQUIRED`,this.name=`SandboxStateOwnerRequiredError`}},WorkspaceAliasRepointedError=class extends Error{constructor(e){super(`workspace path alias points to a different current target: ${e.aliasPath} now resolves to ${e.currentWorkspacePath}, but its stored workspace state belongs to ${e.storedWorkspacePath}. Run \`openclaw doctor --fix\` and confirm the move, or use \`openclaw doctor --fix --force\`.`),this.code=`WORKSPACE_ALIAS_REPOINTED`,this.name=`WorkspaceAliasRepointedError`,this.aliasPath=e.aliasPath,this.storedWorkspacePath=e.storedWorkspacePath,this.currentWorkspacePath=e.currentWorkspacePath}},WorktreeRemovalContentionError=class extends Error{constructor(e,t,n){super(t),this.kind=e,this.blockedByRun=n,this.name=`WorktreeRemovalContentionError`}},WorktreeRemovalLockError=class extends Error{constructor(e,t){super(t),this.kind=e,this.name=`WorktreeRemovalLockError`}},SessionWorktreeSourceChangedError=class extends Error{},SessionWorktreeLifecycleError=class extends Error{constructor(e,t){super(e),this.reason=t}},SessionGoalOperationError=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SessionGoalOperationError`}},SessionCanonicalKeyMigrationRequiredError=class extends Error{constructor(e){super(`${e}; stop the Gateway and run openclaw doctor --fix`),this.code=`SESSION_CANONICAL_KEY_MIGRATION_REQUIRED`,this.name=`SessionCanonicalKeyMigrationRequiredError`}},SqliteSessionMutationConflictError=class extends Error{constructor(e){super(`SQLite session state changed while preparing ${e}`),this.operationLabel=e,this.name=`SqliteSessionMutationConflictError`}},SqliteTranscriptMutationConflictError=class extends Error{constructor(e){super(`SQLite transcript changed while preparing rewrite for ${e}`),this.sessionId=e,this.name=`SqliteTranscriptMutationConflictError`}},SessionEntryLifecycleUpsertConflictError=class extends Error{constructor(e){super(`SQLite session entry changed before lifecycle upsert for ${e}`),this.sessionKey=e,this.name=`SessionEntryLifecycleUpsertConflictError`}},SessionPendingInputCustodyError=class extends Error{},SessionTranscriptReadFenceError=class extends Error{constructor(e){super(e),this.name=`SessionTranscriptReadFenceError`}};function isRedactedIdentifier(e){return typeof e==`string`&&/^(?:-|sha256:[0-9a-f]{12})$/.test(e)}function parseTranscriptAppendRefusal(e){if(!t(e)||!isRedactedIdentifier(e.agentIdHash)||!isRedactedIdentifier(e.expectedSessionIdHash)||!isRedactedIdentifier(e.sessionKeyHash))return;let n={agentIdHash:e.agentIdHash,expectedSessionIdHash:e.expectedSessionIdHash,sessionKeyHash:e.sessionKeyHash};if(e.code===`session-entry-missing`)return{...n,code:e.code};if(e.code===`session-rebound`&&isRedactedIdentifier(e.actualSessionIdHash))return{...n,code:e.code,actualSessionIdHash:e.actualSessionIdHash}}var SessionTranscriptWriterClaimReboundError=class extends Error{constructor(e){super(`session writer claim changed before transcript persistence`,{cause:e}),this.name=`SessionTranscriptWriterClaimReboundError`}},ModelAccountConnectAuthorityError=class extends Error{constructor(){super(`This account action requires a current authorized connection; reconnect and try again.`)}},WorkerSessionAlreadyAttachedError=class extends Error{constructor(e,t){super(`Session ${e} is already attached to worker environment ${t}`),this.sessionId=e,this.environmentId=t}},SqliteJsonlReadBudgetExceededError=class extends Error{};const le=/^(?<year>\d{4})\.(?<month>[1-9]\d?)\.(?<patch>[1-9]\d*)(?:-(?:(?<channel>alpha|beta)\.(?<prerelease>[1-9]\d*)|(?<correction>[1-9]\d*)))?$/;function parseReleaseVersion(e){let t=e.trim(),n=le.exec(t)?.groups;if(!n)return null;let r=Number(n.year),i=Number(n.month),a=Number(n.patch),o=n.prerelease===void 0?void 0:Number(n.prerelease),s=n.correction===void 0?void 0:Number(n.correction);if(!Number.isSafeInteger(r)||!Number.isSafeInteger(i)||!Number.isSafeInteger(a)||i<1||i>12||a<1||o!==void 0&&!Number.isSafeInteger(o)||s!==void 0&&!Number.isSafeInteger(s))return null;let c=n.channel===`alpha`?`alpha`:n.channel===`beta`?`beta`:`stable`;return{version:t,baseVersion:`${r}.${i}.${a}`,channel:c,year:r,month:i,patch:a,alphaNumber:c===`alpha`?o:void 0,betaNumber:c===`beta`?o:void 0,...s===void 0?{}:{correctionNumber:s}}}function compareReleaseVersions(e,t){let n=parseReleaseVersion(e),r=parseReleaseVersion(t);if(n===null||r===null)return null;if(n.year!==r.year)return Math.sign(n.year-r.year);if(n.month!==r.month)return Math.sign(n.month-r.month);if(n.patch!==r.patch)return Math.sign(n.patch-r.patch);if(n.channel!==r.channel){let e={alpha:0,beta:1,stable:2};return Math.sign(e[n.channel]-e[r.channel])}return n.channel===`alpha`&&r.channel===`alpha`?Math.sign((n.alphaNumber??0)-(r.alphaNumber??0)):n.channel===`beta`&&r.channel===`beta`?Math.sign((n.betaNumber??0)-(r.betaNumber??0)):Math.sign((n.correctionNumber??0)-(r.correctionNumber??0))}function walkUpFrom(e,t,n){let r=B.resolve(e);for(let e=0;t.maxDepth===void 0||e<t.maxDepth;e+=1){let e=n(r);if(e!=null)return e;let t=B.dirname(r);if(t===r)break;r=t}return null}function readGitMetadataFile(e,t=1048576){let n=z.openSync(e,z.constants.O_RDONLY|(z.constants.O_NONBLOCK??0));try{let e=z.fstatSync(n);if(!e.isFile()||e.size>t)throw Error(`Git metadata is not a bounded regular file`);let r=H(n,Math.min(e.size,t));if(r.length!==e.size)throw Error(`Git metadata changed during its read`);return r}finally{z.closeSync(n)}}function readGitDirectoryPointerTarget(e,t=``){let n=readGitMetadataFile(e),r=n.toString(`utf8`).replace(/[\r\n]+$/u,``);if(!W(n)||!r.startsWith(t)||r.length===t.length||r.includes(`\0`))throw Error(`Git directory pointer is incomplete or malformed`);let i=r.slice(t.length);return B.isAbsolute(i)?i:`${B.dirname(e)}${B.sep}${i}`}function readGitDirectoryPointer(e,t=``){return z.realpathSync.native(readGitDirectoryPointerTarget(e,t))}function resolveGitDirFromMarker(e){let t=B.join(e,`.git`);try{let e=z.statSync(t);return e.isDirectory()?t:e.isFile()?readGitDirectoryPointer(t,`gitdir: `):null}catch{return null}}function resolveGitHeadPath(e,t={}){return walkUpFrom(e,t,e=>{let t=resolveGitDirFromMarker(e);return t?B.join(t,`HEAD`):null})}function readGitMetadataPrefix(e,t=256){let n=z.openSync(e,z.constants.O_RDONLY|(z.constants.O_NONBLOCK??0));try{if(!z.fstatSync(n).isFile())throw Error(`Git metadata is not a regular file`);let e=Buffer.alloc(t),r=U(n,e,0);return e.subarray(0,r).toString(`utf-8`)}finally{z.closeSync(n)}}function readGitHead(e,t={}){let n=resolveGitHeadPath(e,t);if(!n)return;let r=readGitMetadataFile(n).toString(`utf8`).trim();if(!r.startsWith(`ref:`))return{headPath:n,ref:null,value:r||null};let i=r.replace(/^ref:\s*/i,``).trim(),a=resolveGitRefsBase(n);return{headPath:n,ref:i,value:readGitRefs(a,[i]).get(i)??null,refsBase:a}}function resolveGitRefsBase(e){let t=B.dirname(e),n=B.join(t,`commondir`);try{return readGitDirectoryPointer(n)}catch(e){if(!s(e)||z.lstatSync(n,{throwIfNoEntry:!1}))throw e}return t}function readGitRefs(e,t){let n=new Map(t.map(e=>[e,null])),r=/* @__PURE__ */ new Set;for(let i of t){let t=resolveRefPath(e,i);if(t)try{n.set(i,readGitMetadataPrefix(t).trim())}catch(e){if(!s(e))throw e;r.add(i)}}if(r.size===0)return n;try{let t=readGitMetadataFile(B.join(e,`packed-refs`),2**53-1).toString(`utf8`),i=RegExp(`^(?![#^])[^\\S\\r\\n]*(\\S+)[^\\S\\r\\n]+(${[...r].map(te).join(`|`)})(?=\\s|$)`,`gm`);for(let[,e,a]of t.matchAll(i))r.delete(a)&&n.set(a,e)}catch(e){if(!s(e))throw e}return n}function resolveRefPath(e,t){if(!t.startsWith(`refs/`)||t.split(/[/]/).includes(`..`))return null;let n=B.resolve(e,t),r=B.relative(e,n);return!r||r.startsWith(`..`)||B.isAbsolute(r)?null:n}const formatCommit=e=>{let t=e?.match(/[0-9a-fA-F]{7,40}/);return t?o(t[0].slice(0,7)):null},J=new a(256),resolveCommitSearchDir=e=>{if(e.cwd)return B.resolve(e.cwd);if(e.moduleUrl)try{return B.dirname(V(e.moduleUrl))}catch{}return process.cwd()},cacheGitCommit=(e,t)=>(J.set(e,t),t),resolveGitLookupDepth=(e,t)=>{if(!t)return;let n=B.relative(t,e);if(!(n.startsWith(`..`)||B.isAbsolute(n)))return(n?n.split(B.sep).filter(Boolean).length:0)+1},readCommitFromGit=(e,t)=>{let n=readGitHead(e,{maxDepth:resolveGitLookupDepth(e,t)});return n===void 0?void 0:formatCommit(n.value)},readCommitFromPackageJson=()=>{try{let e=I(import.meta.url)(`../../package.json`);return formatCommit(e.gitHead??e.githead??null)}catch{return null}},readCommitProbe=(e,t,r)=>{try{for(let i of t){let t=V(new URL(i,e)),a;try{a=readGitMetadataPrefix(t,1024)}catch(e){if(s(e))continue;return null}try{let e=n(JSON.parse(a))?.[r];return typeof e==`string`?formatCommit(e):null}catch{return null}}}catch{}},readCommitFromBuildInfo=(e=import.meta.url)=>readCommitProbe(e,[`../build-info.json`,`./build-info.json`],`commit`)??null,readLoadedCommit=e=>{let t=readCommitProbe(e,[`../.buildstamp`,`./.buildstamp`],`head`),n=readCommitProbe(e,[`../.runtime-postbuildstamp`,`./.runtime-postbuildstamp`],`head`);return t!==void 0||n!==void 0?t||n?t&&t===n?t:null:readCommitFromBuildInfo(e):readCommitProbe(e,[`../build-info.json`,`./build-info.json`],`commit`)},resolveCommitHash=(e={})=>{let t=e.env??process.env,n=t.GIT_COMMIT?.trim()||t.GIT_SHA?.trim(),r=formatCommit(n);if(r)return r;let i=resolveCommitSearchDir(e),a=J.get(i);if(a!==void 0)return a;let o=F({cwd:e.cwd,moduleUrl:e.moduleUrl});try{let e=readCommitFromGit(i,o);if(e!==void 0)return cacheGitCommit(i,e)}catch{}let s=readCommitFromBuildInfo();if(s)return cacheGitCommit(i,s);let c=readCommitFromPackageJson();return c?cacheGitCommit(i,c):cacheGitCommit(i,null)};function resolveLoadedCommitHash(e={}){let t=e.moduleUrl??import.meta.url,n=readLoadedCommit(t);return n===void 0?resolveCommitHash({moduleUrl:t,...e.env?{env:e.env}:{}}):n}const ue=[`../package.json`,`../../package.json`,`../../../package.json`,`./package.json`],Y=[`../build-info.json`,`../../build-info.json`,`./build-info.json`];function readStringFromJsonCandidates(t,n,r,i=!1){try{let a=I(t);for(let t of n)try{let n=a(t),o=e(n[r]);if(!o||i&&n.name!==`openclaw`)continue;return o}catch{}return null}catch{return null}}function firstNonEmpty(...t){for(let n of t){let t=e(n);if(t&&t.toLowerCase()!==`undefined`&&t.toLowerCase()!==`null`)return t}}function readVersionFromPackageJsonForModuleUrl(e){return readStringFromJsonCandidates(e,ue,`version`,!0)}function readVersionFromBuildInfoForModuleUrl(e){return readStringFromJsonCandidates(e,Y,`version`)}function readBuildProvenanceForModuleUrl(t){try{let n=I(t);for(let t of Y)try{let r=n(t),i=e(r.buildId);if(i&&i.length<=96){let a={buildId:i};for(let t of[`version`,`commit`,`builtAt`]){let n=e(r[t]);n&&(a[t]=n)}try{a.buildInfoPath=n.resolve(t)}catch{}return a}}catch{}}catch{}return null}function resolveVersionFromModuleUrl(e){return readVersionFromBuildInfoForModuleUrl(e)||readVersionFromPackageJsonForModuleUrl(e)}function resolveBinaryVersion(e){return resolveVersionFromModuleUrl(e.moduleUrl)||firstNonEmpty(e.bundledVersion)||`0.0.0`}readBuildProvenanceForModuleUrl(import.meta.url);const de=resolveLoadedCommitHash({moduleUrl:import.meta.url});function resolveRuntimeServiceCommit(){return de}const X=resolveBinaryVersion({moduleUrl:import.meta.url,bundledVersion:process.env.OPENCLAW_BUNDLED_VERSION}),fe={"state-migrations":`state migration`,"newer-schema":`a newer OpenClaw build`,"agent-media":`offline media migration`,"audit-events-v2":`state database schema migration`,"legacy-workshop-review-index":`state database schema migration`,"legacy-cron-run-logs":`cron run history migration`,"legacy-workspace":`workspace setup state migration`,"legacy-session-store":`session store migration`};var StartupMaintenanceRequiredError=class extends Error{constructor(e,t,n){super(t,n),this.kind=e,this.code=`gateway.maintenance_required`,this.name=`StartupMaintenanceRequiredError`}get reason(){return fe[this.kind]}};const Z=`SqliteSchemaVersionError`;var SqliteSchemaVersionError=class extends StartupMaintenanceRequiredError{constructor(e){super(`newer-schema`,e),this.name=Z}};function isSqliteSchemaVersionError(e){return e instanceof SqliteSchemaVersionError||e instanceof Error&&e.name===Z}function readSqliteUserVersion(e){let t=j(e,`PRAGMA user_version`,[],e=>e.get());return Number(t?.user_version??0)}function readSqliteWriterAppVersion(e){try{let t=j(e,`SELECT app_version FROM schema_meta WHERE meta_key = 'primary' LIMIT 1`,[],e=>e.get());return typeof t?.app_version==`string`&&t.app_version.length>0?t.app_version:void 0}catch{return}}function writeSqliteUserVersion(e,t){if(!Number.isInteger(t)||t<0||t>2147483647)throw RangeError(`SQLite user_version must be an integer from 0 through 2147483647.`);e.exec(`PRAGMA user_version = ${t}`)}function describeRunningOpenClawBuild(){let e=resolveRuntimeServiceCommit(),t=F({moduleUrl:import.meta.url}),n=e?`OpenClaw ${X} (${e})`:`OpenClaw ${X}`;return t?`${n} installed at ${t}`:n}function isNewerSqliteWriterVersion(e){return(compareReleaseVersions(e??``,X)??0)>0}function createNewerSqliteSchemaVersionError(e,t,n,r,i,a=`runtime`){let o=isNewerSqliteWriterVersion(i),s=o?`; it is newer than this Gateway (${X}).`:a===`runtime`?`; run openclaw doctor --fix to inspect this database.`:`.`;return new SqliteSchemaVersionError(`This OpenClaw build cannot open your existing data. ${e} ${t} uses newer schema version ${n}; this build supports ${r}.\n`+(i&&(a===`runtime`||i!==X)?`It was written by OpenClaw ${i}${s}\n`:``)+`Refused by ${describeRunningOpenClawBuild()}.\n`+(o?`Use the newer install that supports schema ${n} or newer, or run openclaw update to update this Gateway service before restarting. To use an older build, restore your pre-update backup created with openclaw backup create.\n`:`Use a build that supports schema ${n} or newer with this state directory. To use an older build, restore your pre-update backup created with openclaw backup create.\n`)+`See ${ae}.`)}var PluginBlobStoreError=class extends Error{constructor(e,t){super(e,{cause:t.cause}),this.name=`PluginBlobStoreError`,this.code=t.code,this.operation=t.operation,t.path&&(this.path=t.path)}};function capturePluginStateErrorCause(e,t,n=/* @__PURE__ */ new Set){if(e===void 0)return;let r=t?.(e);if(r)return{canonical:r};if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return{name:`Error`,message:String(e)};if(typeof e!=`object`)return{name:`Error`,message:`Unknown SQLite error cause`};if(n.has(e)||n.size>=8)return{name:`Error`,message:`Additional SQLite error cause omitted`};n.add(e);let i=`name`in e&&typeof e.name==`string`?e.name:`Error`,a=`message`in e&&typeof e.message==`string`?e.message:i,o=`code`in e?e.code:void 0,s=`errcode`in e?e.errcode:void 0,c=`errno`in e?e.errno:void 0;return{name:i,message:a,...typeof o==`string`||typeof o==`number`?{errorCode:o}:{},...typeof s==`number`?{errcode:s}:{},...typeof c==`number`?{errno:c}:{},...`cause`in e?{cause:capturePluginStateErrorCause(e.cause,t,n)}:{},...e instanceof AggregateError?{errors:e.errors.slice(0,8).map(e=>capturePluginStateErrorCause(e,t,n))}:{}}}var PluginStateStoreError=class extends Error{constructor(e,t){super(e,{cause:t.cause}),this.name=`PluginStateStoreError`,this.code=t.code,this.operation=t.operation,this.owner=t.owner??{pid:process.pid,threadId:R,version:X},t.path&&(this.path=t.path)}toJSON(){return{name:this.name,message:this.message,code:this.code,operation:this.operation,path:this.path,owner:this.owner,cause:capturePluginStateErrorCause(this.cause)}}},SecretStoreValidationError=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SecretStoreValidationError`}},ModelSelectionLockedError=class extends Error{constructor(e=`Model selection is locked for this session.`){super(e),this.name=`ModelSelectionLockedError`}},SkillUploadRequestError=class extends Error{constructor(...e){super(...e),this.name=`SkillUploadRequestError`}},SkillLibraryError=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.currentRevision=n,this.name=`SkillLibraryError`}},OpenClawAgentDatabaseMediaMigrationRequiredError=class extends StartupMaintenanceRequiredError{constructor(e,t){super(`agent-media`,`OpenClaw agent database ${e} uses schema version ${t}; run openclaw doctor --fix to migrate persisted media before using it.`),this.pathname=e,this.schemaVersion=t,this.name=`OpenClawAgentDatabaseMediaMigrationRequiredError`}},OpenClawStateDatabaseSchemaMigrationRequiredError=class extends StartupMaintenanceRequiredError{constructor(e,t){super(e,`OpenClaw state database schema migration required (${e}) at ${t}; run openclaw doctor --fix to migrate it.`),this.kind=e,this.pathname=t,this.name=`OpenClawStateDatabaseSchemaMigrationRequiredError`}};function normalizeOpenClawStateSchemaReadError(e,t){if(e instanceof Error&&e.message.startsWith(`malformed database schema (idx_skill_workshop_collection_reviews_workspace_time)`)){let n=new OpenClawStateDatabaseSchemaMigrationRequiredError(`legacy-workshop-review-index`,t);return n.cause=e,n}return e}function annotateStartupStateInspectionFailure(e,t,n){return!n?.aborted&&e instanceof Error&&!e.message.includes(t)&&(e.message=`OpenClaw state database ${t} failed startup inspection: ${e.message}`),e}var OpenClawStateLeaseError=class extends Error{constructor(e,t){super(e,{cause:t.cause}),this.name=`OpenClawStateLeaseError`,this.code=t.code,this.loss=t.loss}},SessionMetadataUnavailableError=class extends Error{constructor(e,t,n=[]){super(`Session metadata unavailable (${[e,...n].join(`: `)}); retry after the agent store is ready.`,t),this.reason=e,this.missingTables=n,this.name=`SessionMetadataUnavailableError`}};const Q={"worktree-source-changed":SessionWorktreeSourceChangedError,"model-account-authority":ModelAccountConnectAuthorityError,"duplicate-agent":DuplicateAgentError,"model-selection-locked":ModelSelectionLockedError,"session-canonical-key-migration":SessionCanonicalKeyMigrationRequiredError,"session-pending-input-custody":SessionPendingInputCustodyError,"session-transcript-read-fence":SessionTranscriptReadFenceError,"skill-upload-request":SkillUploadRequestError,"state-database-access":u,coordinator:b,ownership:S,"newer-schema":SqliteSchemaVersionError,"jsonl-read-budget":SqliteJsonlReadBudgetExceededError,"range-error":RangeError,"syntax-error":SyntaxError,"type-error":TypeError};function isMessageOnlyErrorIdentity(e){return typeof e.type==`string`&&Object.hasOwn(Q,e.type)}function identifyError(e){if(e instanceof SandboxStateOwnerRequiredError)return{type:`sandbox-state-owner-required`};if(e instanceof AuthProfileStoreUnreadableError)return{type:`auth-profile-store-unreadable`,databasePath:e.databasePath};if(e instanceof SessionWorktreeLifecycleError&&e.reason===`owner-mismatch`)return{type:`session-worktree-owner-mismatch`};if(e instanceof WorktreeRemovalContentionError)return{type:`worktree-removal-contention`,kind:e.kind,...e.blockedByRun?{blockedByRun:{worktreeId:e.blockedByRun.worktreeId,pid:e.blockedByRun.pid}}:{}};if(e instanceof WorktreeRemovalLockError)return{type:`worktree-removal-lock`,kind:e.kind};if(e instanceof PluginStateStoreError)return{type:`plugin-state`,stateCode:e.code,operation:e.operation,path:e.path,owner:{pid:e.owner.pid,threadId:e.owner.threadId,version:e.owner.version}};if(e instanceof SkillLibraryError)return{type:`skill-library`,libraryCode:e.code,...e.currentRevision===void 0?{}:{currentRevision:e.currentRevision}};if(e instanceof SecretStoreValidationError)return{type:`secret-store-validation`,secretCode:e.code};if(e instanceof WorkerSessionAlreadyAttachedError)return{type:`worker-session-already-attached`,sessionId:e.sessionId,environmentId:e.environmentId};if(e instanceof PluginBlobStoreError)return{type:`plugin-blob`,blobCode:e.code,operation:e.operation,...e.path===void 0?{}:{path:e.path}};if(e instanceof WorkspaceAliasRepointedError)return{type:`workspace-alias-repointed`,aliasPath:e.aliasPath,storedWorkspacePath:e.storedWorkspacePath,currentWorkspacePath:e.currentWorkspacePath};if(e instanceof McpOAuthStoreCorruptionError)return{type:`mcp-oauth-corruption`};if(e instanceof SessionGoalOperationError)return{type:`session-goal-operation`,goalCode:e.code};if(e instanceof SessionEntryLifecycleUpsertConflictError)return{type:`session-lifecycle-upsert-conflict`,sessionKey:e.sessionKey};if(e instanceof SessionTranscriptWriterClaimReboundError){let t=parseTranscriptAppendRefusal(e.cause);return{type:`session-transcript-writer-claim-rebound`,...t?{refusal:t}:{}}}if(e instanceof SqliteSessionMutationConflictError)return{type:`session-mutation-conflict`,operationLabel:e.operationLabel};if(e instanceof SqliteTranscriptMutationConflictError)return{type:`session-transcript-mutation-conflict`,sessionId:e.sessionId};if(e instanceof SessionMetadataUnavailableError)return{type:`session-metadata`,reason:e.reason,missingTables:[...e.missingTables]};if(e instanceof p)return{type:`state-owner-contention`,databasePath:e.databasePath};if(e instanceof f)return{type:`state-admission-pending`,databasePath:e.databasePath};if(e instanceof c)return{type:`state-offline-maintenance`,databasePath:e.databasePath};if(e instanceof l)return{type:`state-maintenance-scope`};if(e instanceof OpenClawStateLeaseError)return{type:`state-lease`,leaseCode:e.code,leaseLoss:e.loss};if(e instanceof T)return{type:`ownership-metadata`,databasePath:e.databasePath};if(e instanceof E)return{type:`external-ownership`,databasePath:e.databasePath,managerId:e.managerId};if(e instanceof OpenClawStateDatabaseSchemaMigrationRequiredError)return{type:`state-migration`,kind:e.kind,pathname:e.pathname};if(e instanceof OpenClawAgentDatabaseMediaMigrationRequiredError)return{type:`agent-media-migration`,pathname:e.pathname,schemaVersion:e.schemaVersion};for(let[t,n]of Object.entries(Q))if(e instanceof n)return{type:t};return e instanceof StartupMaintenanceRequiredError?{type:`maintenance`,kind:e.kind}:{type:e instanceof AggregateError?`aggregate`:`error`}}function createError(e){if(isMessageOnlyErrorIdentity(e)){let t=Q[e.type];return new t(e.message)}switch(e.type){case`sandbox-state-owner-required`:return new SandboxStateOwnerRequiredError;case`session-worktree-owner-mismatch`:return new SessionWorktreeLifecycleError(e.message,`owner-mismatch`);case`worktree-removal-contention`:return new WorktreeRemovalContentionError(e.kind,e.message,e.blockedByRun);case`worktree-removal-lock`:return new WorktreeRemovalLockError(e.kind,e.message);case`plugin-state`:return new PluginStateStoreError(e.message,{code:e.stateCode,operation:e.operation,path:e.path,owner:e.owner});case`skill-library`:return new SkillLibraryError(e.libraryCode,e.message,e.currentRevision);case`secret-store-validation`:return new SecretStoreValidationError(e.secretCode,e.message);case`worker-session-already-attached`:return new WorkerSessionAlreadyAttachedError(e.sessionId,e.environmentId);case`workspace-alias-repointed`:return new WorkspaceAliasRepointedError(e);case`session-goal-operation`:return new SessionGoalOperationError(e.goalCode,e.message);case`session-lifecycle-upsert-conflict`:return new SessionEntryLifecycleUpsertConflictError(e.sessionKey);case`session-mutation-conflict`:return new SqliteSessionMutationConflictError(e.operationLabel);case`session-transcript-mutation-conflict`:return new SqliteTranscriptMutationConflictError(e.sessionId);case`session-transcript-writer-claim-rebound`:return new SessionTranscriptWriterClaimReboundError(e.refusal);case`session-metadata`:return new SessionMetadataUnavailableError(e.reason,void 0,e.missingTables);case`error`:return Error(e.message);case`mcp-oauth-corruption`:return new McpOAuthStoreCorruptionError(``,``);case`aggregate`:return AggregateError([],e.message);case`auth-profile-store-unreadable`:return new AuthProfileStoreUnreadableError(e.databasePath);case`state-owner-contention`:return new p(e.databasePath);case`state-admission-pending`:return new f(e.databasePath,e.message);case`state-offline-maintenance`:return new c(e.databasePath,e.message);case`state-maintenance-scope`:return new l(``);case`ownership-metadata`:return new T(e.databasePath,``);case`external-ownership`:return new E(e.databasePath,e.managerId);case`plugin-blob`:return new PluginBlobStoreError(e.message,{code:e.blobCode,operation:e.operation,...e.path===void 0?{}:{path:e.path}});case`state-lease`:return new OpenClawStateLeaseError(e.message,{code:e.leaseCode,loss:e.leaseLoss});case`maintenance`:return new StartupMaintenanceRequiredError(e.kind,e.message);case`state-migration`:return new OpenClawStateDatabaseSchemaMigrationRequiredError(e.kind,e.pathname)}return new OpenClawAgentDatabaseMediaMigrationRequiredError(e.pathname,e.schemaVersion)}function isScalar(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e)}function isNativeErrorCode(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=2147483647}function isWorkerOutcomeCode(e){return e===`outcome-unknown`||e===`unavailable`}function encodeOpenClawStateWorkerError(e,t={}){if(!(e instanceof Error))return;let n=[],r=[],i=/* @__PURE__ */ new Map,a=!1,encodeValue=e=>{if(!(e instanceof Error))return isScalar(e)?{value:e}:{undefined:!0};let t=i.get(e);if(t!==void 0)return{ref:t};let n=r.length;return i.set(e,n),r.push(e),{ref:n}};try{encodeValue(e);for(let e of r){let{name:t,message:r}=e;if(typeof t!=`string`||typeof r!=`string`)return;let i=identifyError(e);if(Object.entries(i).some(([e,t])=>(e===`owner`||e===`blockedByRun`||e===`refusal`||e===`leaseLoss`&&t!==void 0?Object.values(t):e===`missingTables`&&Array.isArray(t)?t:[t]).some(e=>e!==void 0&&!isScalar(e))))return;let o=ne(e),s=h(e,`outcome-unknown`)||h(e,`unavailable`),c=readOpenClawStateDatabaseFailurePath(e),l=`errcode`in e?e.errcode:void 0;a||=s||c!==void 0||o||isNativeErrorCode(l)||A(e)||e instanceof G||i.type!==`error`&&i.type!==`aggregate`;let u=`code`in e?e.code:void 0,d=`errno`in e?e.errno:void 0;n.push({...i,name:s?`SqliteWorkerError`:t===`SqliteWorkerError`&&isWorkerOutcomeCode(u)?`Error`:t,message:r,...typeof u==`string`||typeof u==`number`&&Number.isFinite(u)?{code:u}:{},...isNativeErrorCode(l)?{errcode:l}:{},...typeof d==`number`&&Number.isInteger(d)?{errno:d}:{},...o?{nativeOpen:!0}:{},...c===void 0?{}:{stateDatabasePath:c},...`cause`in e&&!(i.type===`session-transcript-writer-claim-rebound`&&i.refusal)?{cause:encodeValue(e.cause)}:{},...e instanceof AggregateError?{errors:e.errors.map(encodeValue)}:{}})}return a||t.includeOrdinary===!0?{version:1,root:0,nodes:n}:void 0}catch{return}}function decodeErrorGraph(e,t){try{if(e.version!==1)return;let n=e.nodes;if(t.includeOrdinary!==!0&&!n.some(e=>e.stateDatabasePath!==void 0||e.nativeOpen===!0||e.name===`SqliteWorkerError`&&isWorkerOutcomeCode(e.code)||isNativeErrorCode(e.errcode)||A(e)||e.type===`aggregate`&&e.name===`OpenClawQuarantineReadCleanupError`||e.type!==`error`&&e.type!==`aggregate`))return;let r=n.map(e=>{if(e.name===`SqliteWorkerError`&&isWorkerOutcomeCode(e.code)){let t=new m(e.message,e.code);return e.type===`error`?t:ee(createError(e),t)}return createError(e)}),decodeValue=e=>`ref`in e?r[e.ref]:`value`in e?e.value:void 0;for(let[e,t]of n.entries()){let n=r[e];n.name=t.name,n.message=t.message,t.nativeOpen&&re(n),t.stateDatabasePath!==void 0&&markOpenClawStateDatabaseFailure(n,t.stateDatabasePath);for(let[e,r]of Object.entries({...t.code===void 0?{}:{code:t.code},...t.errcode===void 0?{}:{errcode:t.errcode},...t.errno===void 0?{}:{errno:t.errno},...t.cause?{cause:decodeValue(t.cause)}:{}}))Object.defineProperty(n,e,{value:r,configurable:!0,writable:!0});n instanceof AggregateError&&(n.errors=(t.errors??[]).map(decodeValue))}return{errors:r,root:e.root}}catch{return}}const $=i(Symbol.for(`openclaw.sharedStateWorkerErrorPayloads`),()=>/* @__PURE__ */ new WeakMap);function retainOpenClawStateWorkerErrorPayload(e,t){t&&$.set(e,t)}function hydrateOpenClawStateWorkerError(e,t={}){if(!(e instanceof Error))return e;let n=/* @__PURE__ */ new Map,r=[{error:e,finish:!1}],replace=e=>e instanceof Error?n.get(e)??e:e;for(;r.length>0;){let e=r.pop(),{error:i}=e;if(!e.finish){if(n.has(i))continue;n.set(i,i);let e=$.get(i),a=e===void 0?void 0:decodeErrorGraph(e,t);if(a){n.set(i,a.errors[a.root]);continue}if(r.push({error:i,finish:!0}),i.cause instanceof Error&&r.push({error:i.cause,finish:!1}),i instanceof AggregateError)for(let e of i.errors)e instanceof Error&&r.push({error:e,finish:!1});continue}let a=replace(i.cause),o=i instanceof AggregateError?i.errors:void 0,s=o?.map(replace);if(a===i.cause&&(!s||s.every((e,t)=>e===o?.[t])))continue;let c=i instanceof AggregateError?AggregateError([],i.message):Error(i.message);Object.setPrototypeOf(c,Object.getPrototypeOf(i));let l=Object.getOwnPropertyDescriptors(i);`cause`in i&&(l.cause={configurable:!0,writable:!0,...l.cause,value:a}),s&&(l.errors={configurable:!0,writable:!0,...l.errors,value:s}),Object.defineProperties(c,l),n.set(i,c)}return n.get(e)}function createSqliteReadOnlyNativeResourceConnection(e){let{port1:t,port2:n}=new L,r=!1,receive=n=>{let r;try{e.receive(n),r={id:n.id,ok:!0}}catch(e){let t=encodeOpenClawStateWorkerError(e,{includeOrdinary:!0});if(!t)throw e;r={id:n.id,ok:!1,error:t}}t.postMessage(r)},fail=n=>{e.onFailure(n),t.close()};return t.on(`message`,e=>{try{receive(e)}catch(e){fail(e)}}),t.on(`messageerror`,fail),{port:n,service(){if(!r)for(;;){let e=ce(t);if(!e)return;try{receive(e.message)}catch(e){throw fail(e),e}}},decodeCloseError(e){let t=/* @__PURE__ */ Error(`SQLite snapshot staging failed`);retainOpenClawStateWorkerErrorPayload(t,e);let n=hydrateOpenClawStateWorkerError(t,{includeOrdinary:!0});return n instanceof AggregateError?n:new g(n.message,{cause:n})},dispose(){r=!0,t.removeAllListeners(),t.close(),n.close()}}}function decodeSqliteSnapshotStagingError(e){let t=/* @__PURE__ */ Error(`SQLite snapshot staging failed`);retainOpenClawStateWorkerErrorPayload(t,e);let n=hydrateOpenClawStateWorkerError(t,{includeOrdinary:!0});return n.name===`SqliteSnapshotDirectoryBusyError`?new C(n.message,{cause:n.cause}):n}function completed(){let e=w(()=>{});return e.resolve(void 0),e.operation}function createStagingOwner(e,t){let n=t.captureResource(k(`sqliteReadOnlyNativeResource`),`sqliteSnapshotNativeResource`,void 0,connectNativeResource),r=oe({workerUrl:e,workerClass:`writer`,idleTimeoutMs:0,maxPendingTasks:128,maxPendingBytes:O},{retainedTransport:!0,nativeSource:t,nativeResource:n,databaseAccess:`read-only`,decodeResourceError:e=>decodeSqliteSnapshotStagingError(e)}),i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=0,s=/* @__PURE__ */ new Set,c=!1,l=0,u=!1,f,p;function connectNativeResource(){return createSqliteReadOnlyNativeResourceConnection({receive(e){let t=e.directory;if(e.type===`allocated`){let n=a.get(e.preparationId);if(!n)throw new g(`SQLite snapshot preparation custody is unavailable`);n.directories.add(t),retainDirectory(t,e.preparationId)}else if(e.type===`retire`){if(!i.has(t))throw new g(`SQLite snapshot native custody is unavailable`);P(t,{requireRequested:!0})}},onFailure(e){p??={error:e}}})}let serviceRequests=()=>{if(!c){c=!0;try{for(let e of s)e.service();for(let e of Array.from(a.values()))e.serviceClose()}finally{c=!1}}},closeWhenIdle=()=>f?.read().status===`pending`?f:l>0||i.size>0?completed():f=v(y(r.startCloseResources(),()=>l>0||i.size>0?completed():r.startRotate()),()=>{p=void 0}),retainDirectory=(e,t)=>{let n=i.get(e);if(n)return n;let o,startRetire=()=>{if(o&&o.read().status!==`rejected`)return o;try{P(e)}catch(e){let t=w(()=>{});return t.reject(e),t.operation}return o=y(r.startCloseResources(e),()=>{if(i.delete(e),t!==void 0){let n=a.get(t);n?.directories.delete(e),n?.releaseIfComplete()}return closeWhenIdle()})},s={directory:e,startRetire};return i.set(e,s),N(e,startRetire),s},m={start:(e,t)=>{if(u)throw Error(`SQLite snapshot staging owner is closing`);let n=++o,i=Buffer.byteLength(JSON.stringify({...e,preparationId:n})),c=e.type===`prepare`?new L:void 0,abort=()=>{c&&(c.port1.postMessage({type:`abort`}),d(`resource`,`to_worker`))},f=e.type===`prepare`&&c?{...e,preparationId:n,abortPort:c.port2}:{...e,preparationId:n};l++;let m,h={directories:/* @__PURE__ */ new Set,abort(){y.read().status===`pending`&&abort()},startClose,serviceClose:()=>m?.service(),releaseIfComplete(){C?.read().status!==`pending`&&h.directories.size===0&&a.delete(n)}};a.set(n,h);let y=r.startTask(()=>{if(p!==void 0)throw p.error;return t?.throwIfAborted(),t?.addEventListener(`abort`,abort,{once:!0}),f},{inputBytes:i,transferList:()=>c?[c.port2]:[]}),b,S=v(y,e=>{if(e.type===`failed`){let t=decodeSqliteSnapshotStagingError(e.error);throw e.cleanupFailure&&!(t instanceof AggregateError)?new g(String(t),{cause:t}):t}return e}),C=x(S,()=>b=x(y.release(),()=>(t?.removeEventListener(`abort`,abort),c?.port1.close(),c?.port2.close(),l--,closeWhenIdle())),(e,t)=>_([e,t],`SQLite snapshot staging failed`,e));function startClose(){if(m?.read().status===`pending`)return m;let e,t=!1,n=w(()=>{if(!(t||n.operation.read().status!==`pending`)){t=!0;try{if(serviceRequests(),C.service(),C.read().status===`pending`)return;e??=[...h.directories].map(e=>{let t={},r=M(e,e=>{t.cause=e});return r.result.then(()=>n.operation.service(),()=>n.operation.service()),[e,r,t]});for(let[t,n,r]of e){n.service();let e=n.read();if(e.status===`pending`)return;if(e.status===`rejected`)throw e.error;if(!e.value)throw new g(`SQLite staging preparation cleanup failed: ${t}`,r)}let t=b?.read();if(t?.status===`rejected`)throw t.error;h.releaseIfComplete(),n.resolve(void 0)}catch(e){n.reject(e)}finally{t=!1}}});return m=n.operation,C.result.then(()=>n.operation.service(),()=>n.operation.service()),n.operation.service(),n.operation}let finish=()=>{s.delete(C),h.releaseIfComplete()};return C.result.then(finish,finish),C.read().status===`pending`?s.add(C):finish(),{...C,service:serviceRequests,startClose}},retainDirectory};return t.retain(m,async()=>{u=!0;for(let e of a.values())e.abort();await Promise.allSettled([...s].map(e=>e.result));let e=Array.from(a.values()).map(e=>e.startClose()),t=(await Promise.allSettled(e.map(e=>e.result))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(t.length)throw _(t,`SQLite snapshot generation cleanup failed`,t[0]);await closeWhenIdle().result,await r.close()}),m}function captureSqliteSnapshotStagingOwner(){let{moduleUrl:e,runtimeGeneration:t}=ie(k(`sqliteSnapshotStaging`)),n=se({runtimeGeneration:t}),a=i(Symbol.for(`openclaw.sqliteSnapshotStagingOwner`),()=>/* @__PURE__ */ new WeakMap),o=a.get(n);return o||(o=r(()=>createStagingOwner(e,n)),a.set(n,o)),o}export{SqliteJsonlReadBudgetExceededError as _,annotateStartupStateInspectionFailure as a,markOpenClawStateDatabaseFailure as b,createNewerSqliteSchemaVersionError as c,isSqliteSchemaVersionError as d,readSqliteUserVersion as f,X as g,StartupMaintenanceRequiredError as h,OpenClawStateDatabaseSchemaMigrationRequiredError as i,describeRunningOpenClawBuild as l,writeSqliteUserVersion as m,hydrateOpenClawStateWorkerError as n,normalizeOpenClawStateSchemaReadError as o,readSqliteWriterAppVersion as p,retainOpenClawStateWorkerErrorPayload as r,SqliteSchemaVersionError as s,captureSqliteSnapshotStagingOwner as t,isNewerSqliteWriterVersion as u,SessionTranscriptReadFenceError as v,G as x,findOpenClawStateDatabaseFailure as y};