UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 12.9 kB
import{n as readProcessMachineIdentity}from"./current-machine-identity-DvsOGL6Z.mjs";import{Et as _enum,Fn as object,Jn as string,Nt as array,Pn as number,Yt as discriminatedUnion,or as union,qn as strictObject,xn as literal}from"./schemas-DuCQi-Qb.mjs";import{t as safeParseJsonWithSchema}from"./zod-parse-sJYjlHYu.mjs";import{t as isContainerEnvironment}from"./container-environment-C0Hd9WfF.mjs";import"./stale-lock-file-BYuveJm1.mjs";import fs from"node:fs";import path from"node:path";import os from"node:os";import{execFile,spawnSync}from"node:child_process"; //!src/infra/update-managed-service-handoff-schema.ts const text=string().min(1).max(4096);const nativeProcessIdentityShape={pid:number().int().positive(),startIdentity:text.max(128)};const processIdentitySchema=strictObject({...nativeProcessIdentityShape,startIdentitySource:literal(`argv-sha256`).nullable().optional()}).refine(({startIdentity:e,startIdentitySource:t})=>t===`argv-sha256`?/^win32-argv-sha256:[a-f0-9]{64}$/.test(e):!e.startsWith(`win32-argv-sha256:`));const managedHandoffBootSchema=union([strictObject({platform:_enum([`linux`,`darwin`]),identity:string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i)}),strictObject({platform:literal(`win32`),identity:string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}Z$/)}),strictObject({platform:literal(`freebsd`),identity:string().regex(/^[a-f0-9]{32}$/)})]);const nativeLifetimeSchema=strictObject({kind:literal(`native`),unit:text,scope:text,placement:discriminatedUnion(`kind`,[strictObject({kind:literal(`pending`)}),strictObject({kind:literal(`attached`),invocation:string().regex(/^[a-f0-9]{32}$/i)})])});const cancellationProtocol=literal(`original-cancellation-v1`);const updateAction=strictObject({kind:literal(`update`),mutationProtocol:cancellationProtocol}).extend({mutationProtocol:cancellationProtocol.optional(),custody:_enum([`reserved`,`bound`]).optional()});const actionSchema=discriminatedUnion(`kind`,[updateAction,strictObject({kind:literal(`triage`),phase:_enum([`reserved`,`running`,`closing`,`closed`,`uncertain`]),lifetime:discriminatedUnion(`kind`,[strictObject({kind:literal(`foreground`),boot:managedHandoffBootSchema}),nativeLifetimeSchema])}).refine(e=>e.phase!==`running`||e.lifetime.kind!==`native`||e.lifetime.placement.kind===`attached`)]);const sourcePath=text.refine(path.isAbsolute,`Native source path must be absolute`);const digest=string().regex(/^[a-f0-9]{64}$/);const nativeBorrowerSourceSchema=strictObject({runId:text,transactionId:text,claimId:text,revision:number().int().nonnegative(),recordSha256:digest,serviceKey:sourcePath,configPaths:array(sourcePath).min(1).max(512),lifetimeId:text});const nativeBorrowerSchema=strictObject({id:string().uuid(),phase:_enum([`reserved`,`admitted`]),source:nativeBorrowerSourceSchema});const commonPayload={executor:processIdentitySchema,helper:processIdentitySchema,action:actionSchema};const originalUpdateSchema=strictObject({version:literal(2),executor:processIdentitySchema,helper:processIdentitySchema,action:updateAction});const originalGenerationSchema=strictObject({key:text,owner:text,payload:string().min(1),updatedAt:number().int().nonnegative()});const cancellingPayloadSchema=strictObject({version:literal(4),executor:processIdentitySchema,helper:processIdentitySchema,action:updateAction,cancellation:originalGenerationSchema}).refine(e=>{const t=safeParseJsonWithSchema(originalUpdateSchema,e.cancellation.payload);return t!==null&&JSON.stringify(t.helper)===JSON.stringify(e.helper)&&JSON.stringify(t.executor)===JSON.stringify(e.executor)&&JSON.stringify(t.action)===JSON.stringify(e.action)&&(JSON.stringify(e.helper)===JSON.stringify(e.executor)||t.action.mutationProtocol===`original-cancellation-v1`)});const currentPayloadSchema=strictObject({version:literal(2),...commonPayload,mutationOriginal:originalGenerationSchema.optional()}).refine(e=>{if(!e.mutationOriginal)return true;const t=safeParseJsonWithSchema(originalUpdateSchema,e.mutationOriginal.payload);return t!==null&&!e.mutationOriginal.key.includes(`/.openclaw-update-child-`)&&t.action.mutationProtocol===`original-cancellation-v1`});const payloadSchema=discriminatedUnion(`version`,[cancellingPayloadSchema,currentPayloadSchema,strictObject({version:literal(3),...commonPayload,action:strictObject({kind:literal(`update`)}),nativeBorrower:nativeBorrowerSchema})]);function isHandoffProcessIdentity(e){return processIdentitySchema.safeParse(e).success}function isManagedHandoffLeasePayload(e){return payloadSchema.safeParse(e).success}const retiredPayloadSchema=strictObject({version:literal(1),...nativeProcessIdentityShape});function parseManagedHandoffLeasePayload(e){return safeParseJsonWithSchema(payloadSchema,e)}function parseRetiredManagedHandoffLeasePayload(e){return safeParseJsonWithSchema(retiredPayloadSchema,e)}function isRetiredManagedHandoffLeasePayload(e){return parseRetiredManagedHandoffLeasePayload(e)!==null} //!src/infra/update-managed-service-handoff-boot.ts const windowsBootIdentityArgs=[`-NoProfile`,`-NonInteractive`,`-Command`,`(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o')`];const windowsBootIdentityTimeoutMs=5e3;function readWindowsBootIdentityAsync(e){return new Promise(t=>{execFile(`powershell.exe`,windowsBootIdentityArgs,{env:e,windowsHide:true,timeout:windowsBootIdentityTimeoutMs,killSignal:`SIGKILL`},(e,n)=>{const r=managedHandoffBootSchema.safeParse({platform:`win32`,identity:e?void 0:n.trim()});t(r.success?r.data.identity:null)})})}function predatesCurrentBoot(e,t){return e<(t?.platform===`win32`?Date.parse(t.identity):NaN)-3e5}function createManagedHandoffBootIdentityReader(e){return function bootIdentity(){let t;const n=process.platform===`android`?`linux`:process.platform;if(n===`linux`)t=fs.readFileSync(`/proc/sys/kernel/random/boot_id`,`utf8`).trim();else if([`freebsd`,`darwin`,`win32`].includes(process.platform)){const n=process.platform===`freebsd`;const r=process.platform===`win32`;const i=spawnSync(r?`powershell.exe`:n?`/sbin/sysctl`:`/usr/sbin/sysctl`,r?windowsBootIdentityArgs:n?[`-b`,`kern.boot_id`]:[`-n`,`kern.bootsessionuuid`],{env:e,...n?{maxBuffer:16}:{encoding:`utf8`,windowsHide:true},timeout:r?windowsBootIdentityTimeoutMs:1e3,killSignal:`SIGKILL`,stdio:[`ignore`,`pipe`,`ignore`]});if(!i.error&&i.status===0)t=n?Buffer.isBuffer(i.stdout)&&i.stdout.length===16?i.stdout.toString(`hex`):void 0:i.stdout.toString().trim()}const r={platform:n,identity:n===`win32`?t:t?.toLowerCase()};const i=managedHandoffBootSchema.safeParse(r);if(!i.success)throw new Error(`OS boot identity unavailable; run openclaw triage manually`);return i.data}} //!src/infra/gateway-lock-payload.ts const GATEWAY_OWNER_HEARTBEAT_MS=15e3;const GATEWAY_OWNER_HEARTBEAT_STALE_MS=9e4;const LEGACY_GATEWAY_OWNER_LEASE_TTL_MS=3e5;const[uuidBoot,windowsBoot,freebsdBoot]=managedHandoffBootSchema.options;const host=string().min(1);const MachineIdentitySchema=string().regex(/^[a-f0-9]{64}$/u);const GatewayProcessNamespaceSchema=discriminatedUnion(`platform`,[uuidBoot.extend({host,platform:literal(`linux`),pidNsInode:string().min(1)}),uuidBoot.extend({host,platform:literal(`darwin`)}),windowsBoot.extend({host,identity:windowsBoot.shape.identity.optional()}),freebsdBoot.extend({host})]);let processNamespace;function readGatewayLockProcessNamespace(){if(processNamespace?.platform===process.platform&&(processNamespace.value!==null||process.platform!==`linux`&&process.platform!==`android`))return processNamespace.value;try{const e=process.platform===`win32`?{platform:`win32`}:createManagedHandoffBootIdentityReader(process.env)();const t=GatewayProcessNamespaceSchema.parse({host:os.hostname(),...e,...e.platform===`linux`?{pidNsInode:fs.readlinkSync(`/proc/self/ns/pid`).match(/^pid:\[(\d+)\]$/u)?.[1]}:{}});processNamespace={platform:process.platform,value:t};return t}catch{processNamespace={platform:process.platform,value:null};return null}}function isLegacyGatewayLeaseLock(e){return process.platform===`linux`&&e.processNamespace===void 0&&e.role===`gateway`&&typeof e.ownerId===`string`&&e.ownerId.length>0&&typeof e.createdAt===`string`}function readLockHeartbeat(e){try{return fs.statSync(e).mtimeMs}catch{return}}function isForeignLinuxNamespace(e,t){return e?.platform===`linux`&&t?.platform===`linux`&&(e.host!==t.host||e.pidNsInode!==t.pidNsInode)}function describeGatewayLockHolder(e,t,n){const r=GatewayProcessNamespaceSchema.safeParse(e.processNamespace).data;const i=(t?readLockHeartbeat(t):void 0)??e.heartbeatAt;const a=i===void 0?void 0:Date.now()-i;const o=`${r?.host??e.host??`unknown host`}${r?.platform===`linux`?`/pid-ns ${r.pidNsInode}`:``}`;const s=n===`live`?`The holder ${e.pid} is alive on this host, stop it first`:n===`unknown`?`Stop the holder before retrying`:`Run this command inside the Gateway container or with a shared PID namespace`;return`holder ${e.pid??`unknown`} at ${o}, last renewed ${a===void 0?`at an unknown time`:`${Math.max(0,Math.floor(a/1e3))} s ago`}. ${s}.`}var GatewayLockNamespaceError=class extends Error{constructor(e,t){const n=process.platform===`linux`&&e.processNamespace===void 0;super(`cannot verify Gateway ownership from this process${t?` at ${t}`:``}. ${n?`Legacy holder ${e.pid??`unknown`} has no PID namespace evidence. It may already have stopped. Independently verify that no Gateway using this state is running on this host or in any sharing container. With a current OpenClaw CLI using the same state and profile, run \`openclaw gateway recover-lock --json\`, then \`openclaw gateway recover-lock --confirm <confirmation> --json\` with the returned confirmation. Retry Doctor afterward.`:describeGatewayLockHolder(e,t)}`);this.name=`GatewayLockNamespaceError`;this.legacyLock=n;this.legacyLease=isLegacyGatewayLeaseLock(e)||n&&typeof e.expiresAt===`number`;const r=GatewayProcessNamespaceSchema.safeParse(e.processNamespace).data;if(isForeignLinuxNamespace(r,readGatewayLockProcessNamespace())){const n=t?readLockHeartbeat(t):e.heartbeatAt;if(n!==void 0)this.heartbeatAgeMs=Math.max(0,Date.now()-n)}}};function classifyGatewayOwnerProcessNamespace(e,t={}){const n=GatewayProcessNamespaceSchema.safeParse(e).data;if(!n||t.ownerHost!==void 0&&t.ownerHost!==n.host)return`unknown`;const r=readGatewayLockProcessNamespace();if(!r)return`unknown`;if(n.platform!==r.platform)return`unknown`;if(t.readGatewayHeartbeat&&isForeignLinuxNamespace(n,r)){if(n.host===r.host&&/^[a-f0-9]{12}$/u.test(r.host)&&isContainerEnvironment())return`dead`;const e=t.readGatewayHeartbeat();if(e!==void 0&&Date.now()-e>9e4)return`dead`}if(n.platform===`darwin`&&t.machineIdentity!==void 0){const e=MachineIdentitySchema.safeParse(t.machineIdentity).data;const i=readProcessMachineIdentity();if(e&&i){if(e!==i)return`unknown`;if(n.identity!==r.identity)return`dead`}}const i=n.platform===`darwin`&&r.platform===`darwin`&&n.identity===r.identity;if(n.host!==r.host&&!i)return`unknown`;if(n.platform===`win32`)return`same`;if(n.identity!==r.identity)return`dead`;if(n.platform!==`linux`||r.platform===`linux`&&n.pidNsInode===r.pidNsInode)return`same`;return`unknown`}const LockPayloadSchema=object({pid:number(),ownerId:string().min(1).optional(),stateOwnerKind:literal(`schema`).optional(),cronOwnerProjection:literal(`dynamic-default-v1`).optional(),createdAt:string(),startupPhase:literal(`starting`).optional(),configPath:string(),port:number().int().min(1).max(65535).optional(),role:_enum([`gateway`,`agent-embedded`,`skill-workshop-apply`,`sqlite-maintenance`]).optional(),stateDir:string().optional(),startTime:number().optional(),parentPid:number().int().positive().optional(),parentStartTime:number().optional(),processNamespace:GatewayProcessNamespaceSchema.nullable().optional(),machineIdentity:MachineIdentitySchema.nullable().optional()});function isSameGatewayLockIdentity(e,t){if(e.ownerId&&t.ownerId)return e.ownerId===t.ownerId;return e.pid===t.pid&&e.createdAt===t.createdAt&&e.startTime===t.startTime}function parseGatewayLockPayload(e){return safeParseJsonWithSchema(LockPayloadSchema,e)}export{parseRetiredManagedHandoffLeasePayload as C,parseManagedHandoffLeasePayload as S,readWindowsBootIdentityAsync as _,LEGACY_GATEWAY_OWNER_LEASE_TTL_MS as a,isRetiredManagedHandoffLeasePayload as b,classifyGatewayOwnerProcessNamespace as c,isSameGatewayLockIdentity as d,parseGatewayLockPayload as f,predatesCurrentBoot as g,createManagedHandoffBootIdentityReader as h,GatewayProcessNamespaceSchema as i,describeGatewayLockHolder as l,readLockHeartbeat as m,GATEWAY_OWNER_HEARTBEAT_STALE_MS as n,LockPayloadSchema as o,readGatewayLockProcessNamespace as p,GatewayLockNamespaceError as r,MachineIdentitySchema as s,GATEWAY_OWNER_HEARTBEAT_MS as t,isLegacyGatewayLeaseLock as u,isHandoffProcessIdentity as v,processIdentitySchema as w,managedHandoffBootSchema as x,isManagedHandoffLeasePayload as y};