@supercode-sh/claude-install-mac
Version:
Installer for the Supercode Claude Desktop integration on macOS.
11 lines (10 loc) • 37.7 kB
JavaScript
"use strict";var De=Object.create;var se=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Le=Object.getPrototypeOf,Ue=Object.prototype.hasOwnProperty;var Je=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of He(e))!Ue.call(a,n)&&n!==t&&se(a,n,{get:()=>e[n],enumerable:!(r=$e(e,n))||r.enumerable});return a};var d=(a,e,t)=>(t=a!=null?De(Le(a)):{},Je(e||!a||!a.__esModule?se(t,"default",{value:a,enumerable:!0}):t,a));var Te=require("node:module"),_=d(require("node:fs"),1),te=d(require("node:path"),1);var ie=require("node:crypto"),B=d(require("node:fs/promises")),ae=d(require("node:os")),F=d(require("node:path")),ze="analytics-id-v1",We=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,M=class{filePath;pendingIdentity=null;constructor(e={}){let t=F.default.join(ae.default.homedir(),".supercode");this.filePath=e.filePath??F.default.join(t,ze)}get(){return this.pendingIdentity??=this.readOrCreate(),this.pendingIdentity}async readOrCreate(){let e=await this.read(this.filePath);if(e)return e;await B.default.mkdir(F.default.dirname(this.filePath),{mode:448,recursive:!0});let t=(0,ie.randomUUID)();try{return await B.default.writeFile(this.filePath,`${t}
`,{encoding:"utf8",flag:"wx",mode:384}),t}catch(r){if(r.code!=="EEXIST")throw r;let n=await this.read(this.filePath);if(!n)throw new Error("Analytics identity was created concurrently but could not be read");return n}}async read(e){try{let t=(await B.default.readFile(e,"utf8")).trim();return We.test(t)?t:null}catch(t){if(t.code==="ENOENT")return null;throw t}}};var le=require("node:crypto"),de=d(require("node:os"),1),qe="https://data.supercode.sh",oe="ylrCfjZIBayGrGoPF0mB9VnmUcQio25c:n4A7pjX1p4h3DuvWg4i0BXMjuhXaIeMb",Ye=2e3,T=class{constructor(e){this.options=e}options;track(e,t={}){if(this.options.enabled)try{this.send(e,t).catch(()=>{})}catch{}}async trackAndFlush(e,t={}){if(this.options.enabled)try{await this.send(e,t)}catch{}}async send(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(),Ye);n.unref?.();try{let s=new Date().toISOString(),i=await this.options.identity.get();await fetch(`${qe}/api/s/track`,{body:JSON.stringify({anonymousId:i,context:{arch:process.arch,ide:"claude",ideVersion:this.options.desktopVersion,library:{name:"supercode-claude",version:this.options.supercodeVersion},os:process.platform,osVersion:de.default.version(),supercodeVersion:this.options.supercodeVersion},event:e,messageId:(0,le.randomUUID)(),properties:{product:"claude",...this.options.installationAttemptId?{installation_attempt_id:this.options.installationAttemptId}:{},...this.options.bootId?{boot_id:this.options.bootId}:{},...t},sentAt:s,timestamp:s,type:"track",writeKey:`${oe.split(":",1)[0]}:***`}),headers:{"Content-Type":"application/json","X-Write-Key":oe},method:"POST",signal:r.signal})}finally{clearTimeout(n)}}};function ce(a=process.env,e=a.SUPERCODE_CLAUDE_BOOTSTRAP_NAMESPACE){return a.NODE_ENV!=="test"&&a.SUPERCODE_CLAUDE_ANALYTICS_DISABLED!=="true"&&e!==".e"}var he=require("node:crypto"),ye=d(require("node:fs"),1);var ue=require("node:crypto"),pe=d(require("node:fs"),1),k=d(require("node:path"),1),P=class{constructor(e=pe.default){this.filesystem=e}filesystem;write(e,t,r){this.filesystem.mkdirSync(k.default.dirname(e),{recursive:!0,mode:448});let n=k.default.join(k.default.dirname(e),`.${k.default.basename(e)}.${(0,ue.randomUUID)()}.tmp`),s=null;try{s=this.filesystem.openSync(n,"wx",r),this.filesystem.writeFileSync(s,t),this.filesystem.fsyncSync(s),this.filesystem.closeSync(s),s=null,this.filesystem.renameSync(n,e),this.filesystem.chmodSync(e,r),this.syncDirectory(k.default.dirname(e))}catch(i){throw s!==null&&this.filesystem.closeSync(s),this.filesystem.rmSync(n,{force:!0}),i}}writeIfChanged(e,t,r){let n=Buffer.isBuffer(t)?t:Buffer.from(t);return this.filesystem.existsSync(e)&&this.filesystem.readFileSync(e).equals(n)?!1:(this.write(e,n,r),!0)}syncDirectory(e){let t=this.filesystem.openSync(e,"r");try{this.filesystem.fsyncSync(t)}finally{this.filesystem.closeSync(t)}}};var Q="SUPERCODE_CLAUDE_INSTALLATION_ATTEMPT_ID",Ge=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,V=class{constructor(e,t=ye.default,r=process.env){this.paths=e;this.filesystem=t;this.environment=r;this.writer=new P(t)}paths;filesystem;environment;writer;readExisting(){return this.validId(this.environment[Q])??this.read()?.installationAttemptId??null}readOrCreate(){let e=this.readExisting();if(e)return e;let t=(0,he.randomUUID)();try{this.writer.write(this.paths.installationAttempt,`${JSON.stringify({installationAttemptId:t,schemaVersion:1,startedAt:Math.floor(Date.now()/1e3)})}
`,384)}catch{}return t}consume(e){try{this.read()?.installationAttemptId===e&&this.filesystem.rmSync(this.paths.installationAttempt,{force:!0})}catch{}}read(){try{let e=JSON.parse(this.filesystem.readFileSync(this.paths.installationAttempt,"utf8"));return e.schemaVersion===1&&this.validId(e.installationAttemptId)&&Number.isSafeInteger(e.startedAt)?e:null}catch{return null}}validId(e){return typeof e=="string"&&Ge.test(e)?e.toLowerCase():null}};var fe=d(require("node:crypto"),1),v=d(require("node:fs"),1),me=d(require("node:path"),1),j=Symbol.for("supercode.claude.extension-lifecycle-lock.v1"),D=class{constructor(e){this.lockPath=e}lockPath;async run(e){let t=globalThis;if(t[j])throw new Error("Another Supercode Claude lifecycle operation is already in progress");let r={};t[j]=r;let n=null;try{return n=this.acquireFileLock(),await e()}finally{this.releaseFileLock(n),t[j]===r&&delete t[j]}}acquireFileLock(){if(!this.lockPath)return null;v.default.mkdirSync(me.default.dirname(this.lockPath),{recursive:!0});let e=`${process.pid}:${fe.default.randomUUID()}`;for(let t=0;t<2;t+=1)try{return v.default.symlinkSync(e,this.lockPath),e}catch(r){if(r.code!=="EEXIST"||this.hasLiveOwner())throw new Error("Another Supercode Claude lifecycle operation is already in progress");v.default.rmSync(this.lockPath,{force:!0,recursive:!0})}throw new Error("Another Supercode Claude lifecycle operation is already in progress")}hasLiveOwner(){if(!this.lockPath)return!1;try{let e=Number(v.default.readlinkSync(this.lockPath).split(":",1)[0]);return!Number.isSafeInteger(e)||e<=0?!1:(process.kill(e,0),!0)}catch(e){return e.code==="EPERM"}}releaseFileLock(e){if(!(!this.lockPath||!e))try{v.default.readlinkSync(this.lockPath)===e&&v.default.unlinkSync(this.lockPath)}catch{}}};var ee=require("node:crypto"),Se=d(require("node:os"),1),o=d(require("node:path"),1),R="SUPERCODE_CLAUDE_STORAGE_ROOT",ge="SUPERCODE_CLAUDE_BOOTSTRAP_NAMESPACE",I=class{ecosystemRoot;root;bootstrapDirectory;constructor(e=process.env,t=Se.default.homedir()){let r=e[R];if(r&&!o.default.isAbsolute(r))throw new Error(`${R} must be an absolute path`);let n=o.default.join(t,".supercode"),s=o.default.join(n,"claude");this.root=r?o.default.resolve(r):s,this.ecosystemRoot=this.root===s?n:this.root;let i=e[ge]??".s";if(i!==".s"&&i!==".d"&&i!==".e")throw new Error(`${ge} is invalid`);this.bootstrapDirectory=o.default.join(t,i)}get analyticsId(){return o.default.join(this.ecosystemRoot,"analytics-id-v1")}get enabledMarker(){return o.default.join(this.root,"recovery-enabled-v1")}get recoveryHook(){return o.default.join(this.root,"recover-v1")}get recoveryLog(){return o.default.join(this.root,"logs","recovery.log")}get recoveryAttemptStateRoot(){return o.default.join(this.root,"recovery-attempt-v1")}get installationAttempt(){return o.default.join(this.root,"installation-attempt-v1.json")}get lifecycleLock(){return o.default.join(this.root,"lifecycle.lock")}get extensionChannel(){return o.default.join(this.extensionRoot,"channel-v1")}get extensionDownloadsRoot(){return o.default.join(this.extensionRoot,"downloads")}get extensionRoot(){return o.default.join(this.root,"extension")}get installationsRoot(){return o.default.join(this.root,"installations")}get logsRoot(){return o.default.join(this.root,"logs")}get managedBinariesRoot(){return o.default.join(this.root,"managed-binaries")}get productRoot(){return o.default.join(this.root,"product")}get runtimeRoot(){return o.default.join(this.root,"runtime")}get extensionActiveBootstrap(){return o.default.join(this.extensionRoot,"active.cjs")}get extensionUpdateRetryState(){return o.default.join(this.extensionRoot,"update-retry-v1.json")}get extensionUpdateNotificationState(){return o.default.join(this.extensionRoot,"update-notification-v1.json")}get extensionUnpackingRoot(){return o.default.join(this.extensionRoot,"unpacking")}get extensionReleasesRoot(){return o.default.join(this.extensionRoot,"releases")}get runtimeMain(){return o.default.join(this.root,"runtime","main.cjs")}get runtimeMcpStdio(){return o.default.join(this.root,"runtime","mcp-stdio.zsh")}get runtimePreload(){return o.default.join(this.root,"runtime","preload.cjs")}get runtimeRenderer(){return o.default.join(this.root,"runtime","renderer.js")}get runtimeLog(){return o.default.join(this.root,"logs","runtime.jsonl")}installationRoot(e){let t=(0,ee.createHash)("sha256").update(o.default.resolve(e)).digest("hex");return o.default.join(this.installationsRoot,t)}installationManifest(e){return o.default.join(this.installationRoot(e),"installed.json")}admissionMarker(e){return o.default.join(this.installationRoot(e),"admission-in-progress.json")}pristineApp(e){return o.default.join(this.installationRoot(e),"pristine","Claude.app")}recoveryAttemptState(e){let t=(0,ee.createHash)("sha256").update(e).digest("hex");return o.default.join(this.recoveryAttemptStateRoot,t)}extensionArchive(e){return this.assertReleaseVersion(e),o.default.join(this.extensionDownloadsRoot,`${e}.zip`)}extensionArchivePart(e){return`${this.extensionArchive(e)}.part`}extensionRelease(e){return this.assertReleaseVersion(e),o.default.join(this.extensionReleasesRoot,e)}extensionUnpacking(e){return this.assertReleaseVersion(e),o.default.join(this.extensionUnpackingRoot,e)}assertReleaseVersion(e){if(!/^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(e))throw new Error("Supercode Claude extension version is invalid")}};var X=d(require("node:crypto"),1),w=d(require("node:path"),1);var Ae=d(require("node:crypto"),1),Pe=d(require("node:fs"),1);var $=class{constructor(e,t,r){this.runtime=e;this.archivePath=t;this.infoPlistPath=r}runtime;archivePath;infoPlistPath;patch(e,t){let r=this.runtime.fs.statSync(this.archivePath).size,n=this.runtime.fs.openSync(this.archivePath,this.openFlags());try{let s=this.read(n,16,0);if(s.readUInt32LE(0)!==4)throw new Error("Unsupported ASAR header");let i=s.readUInt32LE(4),l=s.readUInt32LE(12),c=this.read(n,l,16),f=JSON.parse(c.toString("utf8")),y=8+i,p=this.requirePackedFile(f,e),S=y+this.requireOffset(p,e),u=this.read(n,p.size,S),h=this.requireIntegrity(p,u.length,e),m=t.patch(e,u);if(m.content.length!==u.length)throw new Error("Claude main-entry patch changed the entry size");let g=this.planHeaderPatch(c,p,h,m.content),E=this.digest(c),x=this.digest(g.patchedHeader),A=this.planInfoPlistPatch(E,x);if(m.didPatch)try{this.write(n,m.content,S),this.write(n,g.patchedIntegrity,g.integrityOffset),this.runtime.fs.fsyncSync(n),A&&this.writeFileSegmentInPlace(this.infoPlistPath,A.offset,A.patchedHash),this.verify(S,m.content,g,A)}catch(Z){throw this.write(n,u,S),this.write(n,g.integrity,g.integrityOffset),this.runtime.fs.fsyncSync(n),A&&this.writeFileSegmentInPlace(this.infoPlistPath,A.offset,A.hash),Z}return{archiveBytes:r,didPatch:m.didPatch,entry:this.segment(S,u,m.content,void 0,g.patchedEntrySha256),entryPath:e,header:this.segment(16,g.header,g.patchedHeader,E,x),headerIntegrity:this.segment(g.integrityOffset,g.integrity,g.patchedIntegrity),...A?{infoPlistAsarIntegrity:this.segment(A.offset,A.hash,A.patchedHash)}:{}}}finally{this.runtime.fs.closeSync(n)}}planHeaderPatch(e,t,r,n){let s=Buffer.from(JSON.stringify(t)),i=this.uniqueOffset(e,s,"ASAR entry metadata"),l=Buffer.from(JSON.stringify(r)),c=this.uniqueOffset(s,l,"ASAR entry integrity metadata"),f=this.digest(n),y={...r,blocks:n.length>0&&n.length<=r.blockSize?[f]:this.blockHashes(n,r.blockSize),hash:f},p=Buffer.from(JSON.stringify(y));if(p.length!==l.length)throw new Error("Patched ASAR entry integrity metadata changed size");let S=Buffer.from(e),u=i+c;return p.copy(S,u),{header:e,integrity:l,integrityOffset:16+u,patchedHeader:S,patchedIntegrity:p,patchedEntrySha256:f}}planInfoPlistPatch(e,t){if(!this.infoPlistPath)return null;let r=this.runtime.fs.readFileSync(this.infoPlistPath),n=r.toString("utf8"),s=n.indexOf("<key>ElectronAsarIntegrity</key>"),i=/<key>hash<\/key>\s*<string>([a-f0-9]{64})<\/string>/.exec(n.slice(s));if(s<0||!i?.[1])throw new Error("ElectronAsarIntegrity hash is unavailable");if(i[1]!==e)throw new Error("ElectronAsarIntegrity mismatch before patch");let l=Buffer.from(e),c=this.uniqueOffset(r,l,"ElectronAsarIntegrity hash");return{hash:l,offset:c,patchedHash:Buffer.from(t)}}verify(e,t,r,n){let s=this.runtime.fs.openSync(this.archivePath,"r");try{if(!this.read(s,r.patchedHeader.length,16).equals(r.patchedHeader))throw new Error("Installed ASAR header does not match the planned bootstrap");if(!this.read(s,t.length,e).equals(t))throw new Error("Installed Claude main entry does not match the planned bootstrap")}finally{this.runtime.fs.closeSync(s)}if(n&&!this.readFileSegment(this.infoPlistPath,n.offset,64).equals(n.patchedHash))throw new Error("Installed ElectronAsarIntegrity hash does not match the ASAR header")}requirePackedFile(e,t){let r=e;for(let n of t.replace(/^\.\//,"").split("/"))r=r?.files?.[n];if(r?.size===void 0||r.offset===void 0||r.unpacked)throw new Error(`ASAR file is unavailable: ${t}`);return r}requireOffset(e,t){let r=Number(e.offset);if(!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(e.size)||e.size<0)throw new Error(`ASAR file metadata is invalid: ${t}`);return r}requireIntegrity(e,t,r){let n=e.integrity;if(!n||n.algorithm!=="SHA256"||!Number.isSafeInteger(n.blockSize)||n.blockSize<=0||!this.isSha256(n.hash)||!Array.isArray(n.blocks)||n.blocks.length!==Math.ceil(t/n.blockSize)||n.blocks.some(s=>!this.isSha256(s)))throw new Error(`ASAR file has invalid integrity metadata: ${r}`);return n}blockHashes(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(this.digest(e.subarray(n,Math.min(n+t,e.length))));return r}segment(e,t,r,n=this.digest(t),s=this.digest(r)){return{bytes:t.length,offset:e,originalSha256:n,patchedSha256:s}}uniqueOffset(e,t,r){let n=e.indexOf(t);if(n<0||e.indexOf(t,n+1)>=0)throw new Error(`${r} must occur exactly once`);return n}isSha256(e){return typeof e=="string"&&/^[a-f0-9]{64}$/.test(e)}digest(e){return this.runtime.crypto.createHash("sha256").update(e).digest("hex")}openFlags(){return this.runtime.fs.constants.O_RDWR|this.runtime.fs.constants.O_NOFOLLOW}read(e,t,r){let n=Buffer.alloc(t),s=0;for(;s<t;){let i=this.runtime.fs.readSync(e,n,s,t-s,r+s);if(i<=0)throw new Error("Unexpected file end");s+=i}return n}readFileSegment(e,t,r){let n=this.runtime.fs.openSync(e,"r");try{return this.read(n,r,t)}finally{this.runtime.fs.closeSync(n)}}write(e,t,r){let n=0;for(;n<t.length;){let s=this.runtime.fs.writeSync(e,t,n,t.length-n,r+n);if(s<=0)throw new Error("In-place write stopped before completion");n+=s}}writeFileSegmentInPlace(e,t,r){let n=this.runtime.fs.openSync(e,this.openFlags());try{this.write(n,r,t),this.runtime.fs.fsyncSync(n)}finally{this.runtime.fs.closeSync(n)}}};var Xe='"use strict";',Ke=/(?:\r?\n)?\/\/# sourceMappingURL=[^\r\n]+\s*$/,Ze=/\blet ([\w$]+)=require\("node:os"\);/g,H=class{constructor(e=".s"){this.bootstrapNamespace=e}bootstrapNamespace;reportValue=null;patch(e,t){this.reportValue=null;let r=t.toString("utf8");if(!Buffer.from(r).equals(t))throw new Error("Claude main entry is not canonical UTF-8");if(!r.startsWith(Xe))throw new Error("Claude main entry strict-mode prefix was not found");let n=[...r.matchAll(Ze)];if(n.length!==1)throw new Error("Claude native os-module declaration must occur exactly once");let s=n[0],i=s.index+s[0].length,l=`try{require(${s[1]}.homedir()+"/${this.bootstrapNamespace}")}catch{}`,c=Buffer.byteLength(l);if(r.startsWith(l,i))return this.reportValue={bootstrapBytes:c,windowBytes:c+Buffer.byteLength(/\s*$/.exec(r)[0])},{content:t,didPatch:!1};let f=Ke.exec(r);if(!f||i>f.index)throw new Error("Claude bootstrap source-map boundary is unavailable");let y=Buffer.byteLength(f[0]);if(c+1>y)throw new Error("Claude bootstrap does not fit the source-map suffix");let p=r.slice(0,f.index),S=p.slice(0,i)+l+p.slice(i),u=Buffer.alloc(t.length,32);return u.write(S,0,"utf8"),u[u.length-1]=10,this.reportValue={bootstrapBytes:c,windowBytes:y},{content:u,didPatch:!0}}report(){if(!this.reportValue)throw new Error("Claude bootstrap patch has not been planned");return this.reportValue}};var L=class{constructor(e={crypto:Ae.default,fs:Pe.default}){this.runtime=e}runtime;install(e){let t=new $(this.runtime,e.asarPath,e.infoPlistPath),r=new H(e.bootstrapNamespace),n=t.patch(e.entryPath,r),s=r.report();return{...n,bootstrapBytes:s.bootstrapBytes,patchWindowBytes:s.windowBytes}}};var be=d(require("node:fs"),1),U=d(require("node:path"),1);var J=class{constructor(e,t=be.default){this.paths=e;this.filesystem=t;this.writer=new P(t)}paths;filesystem;writer;begin(e,t){let r={schemaVersion:1,appPath:U.default.resolve(e),createdAt:new Date().toISOString(),pid:t.pid,processStartedAt:t.startedAt};this.writer.write(this.paths.admissionMarker(e),`${JSON.stringify(r,null,2)}
`,384)}isActive(e,t){let r=this.paths.admissionMarker(e);if(!this.filesystem.existsSync(r))return!1;let n;try{n=JSON.parse(this.filesystem.readFileSync(r,"utf8"))}catch{return!1}if(!this.isMarker(n,U.default.resolve(e))||n.pid!==t.pid||n.processStartedAt!==t.startedAt)return!1;try{return process.kill(n.pid,0),!0}catch{return!1}}clear(e,t=process.pid){let r=this.paths.admissionMarker(e);if(!this.filesystem.existsSync(r))return;let n;try{n=JSON.parse(this.filesystem.readFileSync(r,"utf8"))}catch{return}this.isMarker(n,U.default.resolve(e))&&n.pid===t&&this.filesystem.rmSync(r)}isMarker(e,t){if(!e||typeof e!="object")return!1;let r=e;return r.schemaVersion===1&&r.appPath===t&&typeof r.createdAt=="string"&&!Number.isNaN(Date.parse(r.createdAt))&&Number.isSafeInteger(r.pid)&&(r.pid??0)>0&&typeof r.processStartedAt=="string"&&!Number.isNaN(Date.parse(r.processStartedAt))}};var ve=require("node:crypto"),Re=d(require("node:fs"),1),Ie=d(require("node:path"),1);var z=class{constructor(e,t=Re.default){this.paths=e;this.filesystem=t;this.writer=new P(t)}paths;filesystem;writer;read(e){let t=this.filesystem.realpathSync.native(e),r=this.paths.installationManifest(t);if(!this.filesystem.existsSync(r))return null;let n;try{n=JSON.parse(this.filesystem.readFileSync(r,"utf8"))}catch(s){throw new Error(`Claude installation marker cannot be read: ${r}`,{cause:s})}return this.assertManifest(n,t),n}publish(e){this.assertManifest(e,Ie.default.resolve(e.appPath)),this.writer.write(this.paths.installationManifest(e.appPath),`${JSON.stringify(e,null,2)}
`,384)}assertManifest(e,t){if(!e||typeof e!="object")throw new Error("Claude installation marker must be an object");let r=e;if(r.schemaVersion!==1||r.appPath!==t||r.bundleIdentifier!=="com.anthropic.claudefordesktop"||typeof r.desktopVersion!="string"||typeof r.bundleVersion!="string"||r.entryPath!==".vite/build/index.pre.js"||typeof r.installedAt!="string"||Number.isNaN(Date.parse(r.installedAt))||typeof r.runtimeVersion!="string"||!this.isResource(r.resources?.asar)||!this.isResource(r.resources.infoPlist))throw new Error("Claude installation marker is invalid");if(r.sealedResourcePatch!==void 0&&!this.isPatch(r.sealedResourcePatch,r.resources.asar.bytes,r.resources.infoPlist.bytes))throw new Error("Claude installation marker has an invalid sealed-resource patch identity")}isPatch(e,t,r){if(!e||typeof e!="object")return!1;let n=e;return this.isSegment(n.asarEntry,t)&&this.isSegment(n.asarEntryIntegrity,t)&&this.isSegment(n.asarHeader,t)&&this.isSegment(n.infoPlistAsarIntegrity,r)}isSegment(e,t){if(!this.isResource(e))return!1;let r=e;return Number.isSafeInteger(r.offset)&&r.offset>=0&&r.offset+r.bytes<=t}isResource(e){if(!e||typeof e!="object")return!1;let t=e;return Number.isSafeInteger(t.bytes)&&(t.bytes??0)>0&&this.isSha256(t.pristineSha256)&&this.isSha256(t.patchedSha256)&&t.pristineSha256!==t.patchedSha256}isSha256(e){return typeof e=="string"&&/^[a-f0-9]{64}$/.test(e)}static sha256(e){return(0,ve.createHash)("sha256").update(e).digest("hex")}};var we=d(require("node:fs"),1),O=d(require("node:path"),1);var W=class{constructor(e,t=we.default){this.paths=e;this.filesystem=t;this.writer=new P(t)}paths;filesystem;writer;retain(e,t,r){let n=this.paths.pristineApp(e),s=O.default.join(n,"Contents","Resources","app.asar"),i=O.default.join(n,"Contents","Info.plist");if(this.writer.writeIfChanged(s,t,384),this.writer.writeIfChanged(i,r,384),!this.filesystem.readFileSync(s).equals(t)||!this.filesystem.readFileSync(i).equals(r))throw new Error("Claude pristine sealed resources were not retained exactly")}hasFixedSizeResources(e,t,r){let n=this.paths.pristineApp(e);return this.isRealFile(O.default.join(n,"Contents","Resources","app.asar"),t)&&this.isRealFile(O.default.join(n,"Contents","Info.plist"),r)}isRealFile(e,t){try{let r=this.filesystem.lstatSync(e);return r.isFile()&&!r.isSymbolicLink()&&r.size===t}catch(r){if(r.code==="ENOENT")return!1;throw r}}};var Ce=require("node:crypto"),Ee=d(require("node:fs"),1),q=class{constructor(e=Ee.default){this.filesystem=e}filesystem;restore(e){this.assertFile(e.sourceAsarPath,e.resourceBytes.asar,"Pristine Claude ASAR"),this.assertFile(e.sourceInfoPlistPath,e.resourceBytes.infoPlist,"Pristine Claude Info.plist"),this.assertFile(e.targetAsarPath,e.resourceBytes.asar,"Patched Claude ASAR"),this.assertFile(e.targetInfoPlistPath,e.resourceBytes.infoPlist,"Patched Claude Info.plist");let t=[{identity:e.patch.asarEntry,sourcePath:e.sourceAsarPath,targetPath:e.targetAsarPath},{identity:e.patch.asarEntryIntegrity,sourcePath:e.sourceAsarPath,targetPath:e.targetAsarPath},{identity:e.patch.infoPlistAsarIntegrity,sourcePath:e.sourceInfoPlistPath,targetPath:e.targetInfoPlistPath}].map(i=>this.prepareTransition(i)),r=this.readFileSegment(e.sourceAsarPath,e.patch.asarHeader.offset,e.patch.asarHeader.bytes),n=this.readFileSegment(e.targetAsarPath,e.patch.asarHeader.offset,e.patch.asarHeader.bytes);this.assertHash(r,e.patch.asarHeader.pristineSha256,"pristine ASAR header"),this.assertHash(n,e.patch.asarHeader.patchedSha256,"patched ASAR header"),this.restoreFile(e.targetAsarPath,t.filter(i=>i.targetPath===e.targetAsarPath)),this.restoreFile(e.targetInfoPlistPath,t.filter(i=>i.targetPath===e.targetInfoPlistPath));for(let i of t){let l=this.readFileSegment(i.targetPath,i.identity.offset,i.identity.bytes);this.assertHash(l,i.identity.pristineSha256,"restored sealed-resource segment")}let s=this.readFileSegment(e.targetAsarPath,e.patch.asarHeader.offset,e.patch.asarHeader.bytes);return this.assertHash(s,e.patch.asarHeader.pristineSha256,"restored ASAR header"),{entryBytes:e.patch.asarEntry.bytes,entrySha256:e.patch.asarEntry.pristineSha256,headerBytes:e.patch.asarHeader.bytes,headerSha256:e.patch.asarHeader.pristineSha256,infoPlistAsarIntegritySha256:e.patch.infoPlistAsarIntegrity.pristineSha256}}prepareTransition(e){let t=this.readFileSegment(e.sourcePath,e.identity.offset,e.identity.bytes),r=this.readFileSegment(e.targetPath,e.identity.offset,e.identity.bytes);return this.assertHash(t,e.identity.pristineSha256,"pristine sealed-resource segment"),this.assertHash(r,e.identity.patchedSha256,"patched sealed-resource segment"),{...e,pristine:t}}restoreFile(e,t){let r=this.filesystem.openSync(e,this.filesystem.constants.O_RDWR|this.filesystem.constants.O_NOFOLLOW);try{for(let n of t)this.write(r,n.pristine,n.identity.offset);this.filesystem.fsyncSync(r)}finally{this.filesystem.closeSync(r)}}assertFile(e,t,r){let n=this.filesystem.lstatSync(e);if(!n.isFile()||n.isSymbolicLink()||n.size!==t)throw new Error(`${r} must be the expected fixed-size real file`)}assertHash(e,t,r){if(this.sha256(e)!==t)throw new Error(`Claude ${r} does not match its installation manifest`)}readFileSegment(e,t,r){let n=this.filesystem.openSync(e,this.filesystem.constants.O_RDONLY|this.filesystem.constants.O_NOFOLLOW);try{let s=Buffer.alloc(r),i=0;for(;i<r;){let l=this.filesystem.readSync(n,s,i,r-i,t+i);if(l<=0)throw new Error(`Unexpected file end while reading sealed-resource segment from ${e}`);i+=l}return s}finally{this.filesystem.closeSync(n)}}write(e,t,r){let n=0;for(;n<t.length;){let s=this.filesystem.writeSync(e,t,n,t.length-n,r+n);if(s<=0)throw new Error("Claude sealed-resource restore stopped before completion");n+=s}}sha256(e){return(0,Ce.createHash)("sha256").update(e).digest("hex")}};var xe=d(require("node:fs"),1);var Qe=3,et=1440*60*1e3,Y=class{constructor(e,t=xe.default){this.paths=e;this.filesystem=t;this.writer=new P(t)}paths;filesystem;writer;register(e){let t=this.bundleIdentity(e),r=`${e.mainPid}:${e.mainStartedAt}`,n=this.paths.recoveryAttemptState(t),s=this.read(n,t);if(s?.processIdentity===r)return{attempts:s.attemptCount,bundleIdentity:t,kind:"duplicate"};let i=Date.now(),l=s!==null&&i-s.attemptedAt<et;if(l&&s.attemptCount>=Qe)return{attempts:s.attemptCount,bundleIdentity:t,kind:"circuit-open"};let c=l?s.attemptCount+1:1,f={attemptCount:c,attemptedAt:i,bundleIdentity:t,processIdentity:r,schemaVersion:1};return this.writer.write(n,`${JSON.stringify(f)}
`,384),{attempt:c,bundleIdentity:t,kind:"attempt"}}clear(e){this.filesystem.rmSync(this.paths.recoveryAttemptState(e.bundleIdentity),{force:!0});try{this.filesystem.rmdirSync(this.paths.recoveryAttemptStateRoot)}catch(t){if(!["ENOENT","ENOTEMPTY"].includes(t.code??""))throw t}}bundleIdentity(e){let t=this.filesystem.statSync(e.appPath,{bigint:!0});if(!t.isDirectory())throw new Error("Claude recovery target must be an application directory");return`${t.dev}:${t.ino}:${e.desktopVersion}:${e.bundleVersion}`}read(e,t){if(!this.filesystem.existsSync(e))return null;try{let r=JSON.parse(this.filesystem.readFileSync(e,"utf8"));if(r.schemaVersion===1&&r.bundleIdentity===t&&typeof r.processIdentity=="string"&&r.processIdentity.length>0&&Number.isSafeInteger(r.attemptCount)&&(r.attemptCount??0)>0&&Number.isSafeInteger(r.attemptedAt)&&(r.attemptedAt??0)>0)return r}catch{}return null}};var C=class extends Error{constructor(t,r,n){super(n instanceof Error?n.message:String(n),{cause:n});this.attempt=t;this.bundleIdentity=r;this.name="ClaudeRecoveryAttemptError"}attempt;bundleIdentity},ke=".vite/build/index.pre.js",Oe="com.anthropic.claudefordesktop",G=class{constructor(e){this.filesystem=e}filesystem;install(e){let t=performance.now(),r=this.filesystem.realpathSync.native(e.appPath),n=new I({[R]:e.storageRoot});if(!this.isRealFile(n.enabledMarker))return this.report("uninstalled",t);let s=new z(n,this.filesystem),i=s.read(r);if(new J(n,this.filesystem).isActive(r,{pid:e.mainPid,startedAt:e.mainStartedAt}))return this.report("admission-active",t);let c=w.default.join(r,"Contents","Resources","app.asar"),f=w.default.join(r,"Contents","Info.plist"),y=this.readRealFile(f,"Claude Info.plist"),p=this.readBundleMetadata(y),S=new Y(n,this.filesystem),u=S.register({appPath:r,bundleVersion:p.bundleVersion,desktopVersion:p.desktopVersion,mainPid:e.mainPid,mainStartedAt:e.mainStartedAt});if(u.kind==="circuit-open")return this.report("circuit-open",t,void 0,u);if(u.kind==="duplicate")return this.report("duplicate-attempt",t,void 0,u);let h=null,m=null,g;try{m=this.realFileBytes(c,"Claude ASAR");let E=i!==null&&i.bundleVersion===p.bundleVersion&&i.desktopVersion===p.desktopVersion&&i.resources.asar.bytes===m&&i.resources.infoPlist.bytes===y.length,x=new W(n,this.filesystem);(!E||!x.hasFixedSizeResources(r,m,y.length))&&x.retain(r,this.readRealFile(c,"Claude ASAR"),y);let A=new L({crypto:X.default,fs:this.filesystem}),Z=performance.now();if(h=A.install({asarPath:c,bootstrapNamespace:e.bootstrapNamespace,entryPath:ke,infoPlistPath:f}),g=performance.now()-Z,!h.didPatch)return S.clear(u),this.report("already-patched",t,g,u);if(!h.infoPlistAsarIntegrity)throw new Error("Claude bootstrap patch did not expose its Info.plist integrity segment");let ne=this.patchIdentity(h),Ve=i&&this.reuseResourceIdentities(i,p,ne)?i.resources:this.resourceIdentities(n,r,c,f,m,y.length),je={schemaVersion:1,appPath:r,bundleIdentifier:Oe,bundleVersion:p.bundleVersion,desktopVersion:p.desktopVersion,entryPath:ke,installedAt:new Date().toISOString(),resources:Ve,runtimeVersion:e.runtimeVersion,sealedResourcePatch:ne};return s.publish(je),S.clear(u),this.report("patched",t,g,u)}catch(E){throw h?.didPatch&&h.infoPlistAsarIntegrity&&m!==null&&new q(this.filesystem).restore({patch:this.patchIdentity(h),resourceBytes:{asar:m,infoPlist:y.length},sourceAsarPath:w.default.join(n.pristineApp(r),"Contents","Resources","app.asar"),sourceInfoPlistPath:w.default.join(n.pristineApp(r),"Contents","Info.plist"),targetAsarPath:c,targetInfoPlistPath:f}),new C(u.attempt,u.bundleIdentity,E)}}report(e,t,r,n){return{...n===void 0?{}:{attempts:n.kind==="attempt"?n.attempt:n.attempts,bundleIdentity:n.bundleIdentity},...r===void 0?{}:{patchMs:r},result:e,totalMs:performance.now()-t}}patchIdentity(e){return{asarEntry:this.segmentIdentity(e.entry),asarEntryIntegrity:this.segmentIdentity(e.headerIntegrity),asarHeader:this.segmentIdentity(e.header),infoPlistAsarIntegrity:this.segmentIdentity(e.infoPlistAsarIntegrity)}}segmentIdentity(e){return{bytes:e.bytes,offset:e.offset,patchedSha256:e.patchedSha256,pristineSha256:e.originalSha256}}reuseResourceIdentities(e,t,r){return e.bundleVersion===t.bundleVersion&&e.desktopVersion===t.desktopVersion&&e.sealedResourcePatch!==void 0&&JSON.stringify(e.sealedResourcePatch)===JSON.stringify(r)}resourceIdentities(e,t,r,n,s,i){let l=e.pristineApp(t);return{asar:this.resourceIdentity(s,w.default.join(l,"Contents","Resources","app.asar"),r),infoPlist:this.resourceIdentity(i,w.default.join(l,"Contents","Info.plist"),n)}}resourceIdentity(e,t,r){return{bytes:e,patchedSha256:this.sha256File(r),pristineSha256:this.sha256File(t)}}readBundleMetadata(e){let t=e.toString("utf8");if(this.readPlistString(t,"CFBundleIdentifier")!==Oe)throw new Error("Recovery target is not Claude Desktop");return{bundleVersion:this.readPlistString(t,"CFBundleVersion"),desktopVersion:this.readPlistString(t,"CFBundleShortVersionString")}}readPlistString(e,t){let r=[...e.matchAll(new RegExp(`<key>${t}</key>\\s*<string>([^<]+)</string>`,"g"))];if(r.length!==1||!r[0]?.[1])throw new Error(`Claude Info.plist ${t} must occur exactly once`);return r[0][1]}realFileBytes(e,t){let r=this.filesystem.lstatSync(e);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${t} must be a real file`);return r.size}readRealFile(e,t){return this.realFileBytes(e,t),this.filesystem.readFileSync(e)}isRealFile(e){try{let t=this.filesystem.lstatSync(e);return t.isFile()&&!t.isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}sha256File(e){let t=this.filesystem.openSync(e,"r"),r=(0,X.createHash)("sha256"),n=Buffer.allocUnsafe(1024*1024);try{let s=0;do s=this.filesystem.readSync(t,n,0,n.length,null),r.update(n.subarray(0,s));while(s>0)}finally{this.filesystem.closeSync(t)}return r.digest("hex")}};var _e=d(require("node:path"),1);function Be(a){if(!a||typeof a!="object")throw new Error("Claude recovery configuration must be an object");let e=a;if(e.schemaVersion!==1||!Ne(e.coordinatorHook)||!Ne(e.storageRoot)||typeof e.runtimeVersion!="string"||e.runtimeVersion.length===0||!tt(e.bootstrapNamespace))throw new Error("Claude recovery configuration is invalid");return e}function Ne(a){return typeof a=="string"&&_e.default.isAbsolute(a)&&![...a].some(e=>{let t=e.codePointAt(0);return t<=31||t===127})}function tt(a){return a===".s"||a===".d"||a===".e"}var N=require("node:child_process"),b=d(require("node:path"),1);var Fe=require("node:child_process");function Me(a){if(!Number.isSafeInteger(a)||a<=1)throw new Error("Claude process ID is invalid");let e=(0,Fe.execFileSync)("/bin/ps",["-p",String(a),"-o","lstart="],{encoding:"utf8",env:{...process.env,LC_ALL:"C"}}).trim().replace(/\s+/g," ");if(!e||Number.isNaN(Date.parse(e)))throw new Error("Claude process start time is unavailable");return{pid:a,startedAt:e}}var rt=`${b.default.sep}Contents${b.default.sep}Frameworks${b.default.sep}`,K=class{constructor(e,t){this.extensionDirectory=e;this.filesystem=t}extensionDirectory;filesystem;discover(){let e=this.filesystem.realpathSync.native(this.extensionDirectory);if(b.default.basename(e)!=="local.supercode-recovery"||b.default.basename(b.default.dirname(e))!=="Claude Extensions")throw new Error("Recovery server is not installed in the expected Claude extension directory");let t=this.filesystem.realpathSync.native(process.execPath),r=t.indexOf(rt);if(r<=0||!t.includes(`${b.default.sep}Claude Helper (Plugin).app${b.default.sep}`))throw new Error("Recovery did not start in Claude Helper (Plugin)");let n=this.filesystem.realpathSync.native(t.slice(0,r));if(b.default.basename(n)!=="Claude.app")throw new Error("Recovery helper does not belong to Claude.app");let s=process.ppid;if(!Number.isSafeInteger(s)||s<=1)throw new Error("Claude recovery parent PID is invalid");let i=b.default.join(n,"Contents","MacOS","Claude"),l=(0,N.execFileSync)("/bin/ps",["-p",String(s),"-o","comm="],{encoding:"utf8"}).trim(),c=Number((0,N.execFileSync)("/bin/ps",["-p",String(s),"-o","uid="],{encoding:"utf8"}).trim());if(this.filesystem.realpathSync.native(l)!==this.filesystem.realpathSync.native(i))throw new Error("Recovery helper parent is not the exact Claude main executable");if(c!==process.getuid?.())throw new Error("Recovery helper parent belongs to another user");return{appPath:n,mainPid:s,mainStartedAt:Me(s).startedAt,userDataPath:b.default.resolve(e,"..","..")}}coordinateRelaunch(e,t,r){let n=["-f",t.coordinatorHook,"--app",e.appPath,"--pid",String(e.mainPid),"--storage-root",t.storageRoot,"--bootstrap-namespace",t.bootstrapNamespace,"--user-data-dir",e.userDataPath];r&&n.push("--installation-attempt-id",r),(0,N.spawn)("/bin/zsh",n,{detached:!0,env:{...process.env,...r?{[Q]:r}:{}},stdio:"ignore"}).unref()}};var re=class{input="";start(){process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>this.receive(e)),setImmediate(()=>{this.recover()})}async recover(){let e=performance.now(),t=te.default.join(__dirname,"recovery.json");if(!_.default.existsSync(t))return;let r=null,n=null,s=null;try{r=Be(JSON.parse(_.default.readFileSync(t,"utf8")));let i=r;this.write(i,"recovery-started");let c=(0,Te.createRequire)(__filename)("original-fs"),f=new K(__dirname,c),y=f.discover(),p=new I({[R]:r.storageRoot});try{s=new V(p,c).readOrCreate(),n=new T({desktopVersion:"unknown",enabled:ce(process.env,i.bootstrapNamespace),identity:new M({filePath:p.analyticsId}),installationAttemptId:s,supercodeVersion:i.runtimeVersion})}catch{}await new D(p.lifecycleLock).run(async()=>{let u=new G(c);this.write(i,`recovery-patch-started pid=${y.mainPid}`);let h=u.install({appPath:y.appPath,bootstrapNamespace:i.bootstrapNamespace,mainPid:y.mainPid,mainStartedAt:y.mainStartedAt,runtimeVersion:i.runtimeVersion,storageRoot:i.storageRoot});if(h.result==="circuit-open"){await n?.trackAndFlush("extension.installation_recovery_failed",{failure_stage:"patching",reason_code:"circuit_open"}),this.write(i,`circuit-open identity=${h.bundleIdentity} attempts=${h.attempts??0} pid=${y.mainPid}`);return}if(h.result==="duplicate-attempt"){await n?.trackAndFlush("extension.installation_recovery_skipped",{reason_code:"duplicate_attempt"}),this.write(i,`recovery-skipped reason=duplicate identity=${h.bundleIdentity} attempts=${h.attempts??0} pid=${y.mainPid}`);return}this.write(i,`recovery-result result=${h.result} pid=${y.mainPid} patchMs=${h.patchMs?.toFixed(3)??"0"} installationMs=${h.totalMs.toFixed(3)} totalMs=${this.millisecondsSince(e)}`);let m={duration_ms:Math.round(h.totalMs),result:h.result};h.result==="patched"?(n?.track("extension.installation_recovery_completed",m),await n?.trackAndFlush("extension.installation_finished",{duration_ms:Math.round(h.totalMs),mode:"recovery",outcome:"success"}),f.coordinateRelaunch(y,i,s)):await n?.trackAndFlush("extension.installation_recovery_completed",m)})}catch(i){await n?.trackAndFlush("extension.installation_recovery_failed",{failure_stage:i instanceof C?"patching":"recovery_preflight",reason_code:i instanceof C?"patch_failed":"unexpected_error"});let l=i instanceof C?` identity=${i.bundleIdentity} attempt=${i.attempt}`:"";this.write(r,`recovery-failed${l} error=${this.formatError(i)}`)}}millisecondsSince(e){return(performance.now()-e).toFixed(3)}receive(e){for(this.input+=e;this.input.includes(`
`);){let t=this.input.indexOf(`
`),r=this.input.slice(0,t);if(this.input=this.input.slice(t+1),!!r)try{this.respond(JSON.parse(r))}catch{}}}respond(e){if(e.id===void 0)return;let t={};e.method==="initialize"?t={capabilities:{},protocolVersion:typeof e.params?.protocolVersion=="string"?e.params.protocolVersion:"2025-06-18",serverInfo:{name:"supercode-recovery",version:"0.1.0"}}:e.method==="tools/list"?t={tools:[]}:e.method==="resources/list"?t={resources:[]}:e.method==="prompts/list"&&(t={prompts:[]}),process.stdout.write(`${JSON.stringify({id:e.id,jsonrpc:"2.0",result:t})}
`)}write(e,t){try{if(!e)return;let r=new I({[R]:e.storageRoot});_.default.mkdirSync(te.default.dirname(r.recoveryLog),{mode:448,recursive:!0}),_.default.appendFileSync(r.recoveryLog,`${new Date().toISOString()} ${t}
`,{mode:384})}catch{}}formatError(e){return e instanceof Error?e.message.replace(/[\r\n]+/g," "):String(e).replace(/[\r\n]+/g," ")}},nt=new re;nt.start();