@zortexhq/indra-v2.5 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{createHash,randomUUID}from"node:crypto";import{readFile,writeFile,mkdir,lstat,realpath,rename,copyFile,cp,rm,chmod}from"node:fs/promises";import{resolve,join,dirname,relative,isAbsolute,sep}from"node:path";import{homedir}from"node:os";import{fileURLToPath}from"node:url";import{execFile}from"node:child_process";import{promisify}from"node:util";import{prepareDependencyUpdate}from"./update-dependencies.js";import{createUpdateTelemetry}from"./update-telemetry.js";import{createUpdateRecovery,safePath,safeFile,optionalBytes,dependencyPath,atomicWrite,JOURNAL,RECOVERY_FILE}from"./update-recovery.js";const execute=promisify(execFile);const NAME="@zortexhq/indra-v2.5";const MANIFEST="update-manifest.json";const MAX_BYTES=12e7;const hash=bytes=>createHash("sha256").update(bytes).digest("hex");const jsonBytes=value=>Buffer.from(JSON.stringify(value,null,2)+"\n");function metadataDigest(pkg){const update=pkg.zortexUpdate;if(update?.schemaVersion!==1||update.manifest!==MANIFEST||!/^[a-f0-9]{64}$/.test(update.sha256??""))return void 0;return update.sha256}function validateManifest(bytes,digest,version){if(hash(bytes)!==digest)throw Error("Update manifest integrity check failed.");const value=JSON.parse(bytes.toString("utf8"));if(value.schemaVersion!==1||value.package?.name!==NAME||value.package.version!==version||value.package.zortexUpdate||!Array.isArray(value.files)||value.files.length>8e3)throw Error("Invalid update manifest.");let total=0;const paths=new Set;for(const file of value.files){safePath(file.path);const key=file.path.toLowerCase();if(paths.has(key)||[MANIFEST,"package.json","release-provenance.json"].includes(key)||!/^[a-f0-9]{64}$/.test(file.sha256)||!Number.isSafeInteger(file.size)||file.size<0||file.mode!==void 0&&![420,493,420,493].includes(file.mode))throw Error("Invalid update file entry.");paths.add(key);total+=file.size}if(total>MAX_BYTES)throw Error("Update exceeds the installed product size limit.");return value}function dependencyShape(pkg){const bundled=new Set(pkg.bundledDependencies??[]);return JSON.stringify(["dependencies","optionalDependencies","peerDependencies","peerDependenciesMeta"].map(field=>[field,Object.entries(pkg[field]??{}).filter(([name])=>!bundled.has(name)).sort(([a],[b])=>a.localeCompare(b))]))}function binShape(pkg){const bins=typeof pkg.bin==="string"?{[pkg.name.split("/").at(-1)]:pkg.bin}:pkg.bin??{};return JSON.stringify(Object.entries(bins).map(([name,path])=>[name,typeof path==="string"?path.replace(/^\.\//,""):path]).sort(([a],[b])=>String(a).localeCompare(String(b))))}function versionParts(version){const match=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(version);if(!match)throw Error("Invalid registry version.");return[Number(match[1]),Number(match[2]),Number(match[3]),match[4]]}function newer(current,target,times={}){if(current===target)return false;const a=versionParts(current),b=versionParts(target);for(const i of[0,1,2])if(a[i]!==b[i])return b[i]>a[i];if(!a[3])return false;if(!b[3])return true;const oldTime=Date.parse(times[current]??""),newTime=Date.parse(times[target]??"");if(Number.isFinite(oldTime)&&Number.isFinite(newTime))return newTime>oldTime;const left=a[3].split("."),right=b[3].split(".");for(let i=0;i<Math.max(left.length,right.length);i++){if(left[i]===right[i])continue;if(left[i]===void 0)return true;if(right[i]===void 0)return false;return/^\d+$/.test(left[i])&&/^\d+$/.test(right[i])?Number(right[i])>Number(left[i]):right[i]>left[i]}return false}function manual(version,installationPath){return`Use the package manager that installed ${installationPath} to upgrade ${NAME} to exactly ${version} at that installation path.`}export function createUpdater(options={}){let packageRoot=resolve(options.packageRoot??fileURLToPath(new URL("..",import.meta.url)));const requestedRoot=packageRoot;const{recover,recoverLocked,withRecoveryLock,publishLock,rollback}=createUpdateRecovery(requestedRoot);let rootIsLinked=false,rootReady;const canonicalizeRoot=()=>rootReady??=(async()=>{rootIsLinked=(await lstat(requestedRoot)).isSymbolicLink();packageRoot=await realpath(requestedRoot)})();const cacheRoot=resolve(options.cacheRoot??join(homedir(),".zortex","updates",hash(packageRoot).slice(0,24)));const registry=(options.registryUrl??"https://registry.npmjs.org").replace(/\/$/,"");const content=(options.contentBaseUrl??"https://cdn.jsdelivr.net/npm").replace(/\/$/,"");const fetcher=options.fetch??globalThis.fetch,now=options.now??Date.now;const env=options.env??process.env;const outcomes=createUpdateTelemetry({cacheRoot,env,now});const disabled=()=>/^(0|false|off)$/i.test(env.ZORTEX_UPDATES??"");const offerPath=join(cacheRoot,"offer.json"),statusPath=join(cacheRoot,"status.json");const pkg=async()=>{await canonicalizeRoot();return JSON.parse(await readFile(join(packageRoot,"package.json"),"utf8"))};async function get(url,limit,timeout=5e3){const response=await fetcher(url,{signal:AbortSignal.timeout(timeout),redirect:"error"});if(!response.ok||!response.body)throw Error(`Update download unavailable (${response.status}).`);if(Number(response.headers.get("content-length")??0)>limit)throw Error("Update response exceeds its size limit.");const chunks=[];let size=0;for await(const chunk of response.body){size+=chunk.length;if(size>limit)throw Error("Update response exceeds its size limit.");chunks.push(chunk)}return Buffer.concat(chunks)}const fileUrl=(version,path)=>`${content}/${NAME}@${encodeURIComponent(version)}/${path.split("/").map(encodeURIComponent).join("/")}`;async function savedOffer(){await canonicalizeRoot();const bytes=await optionalBytes(offerPath);const parsed=bytes?JSON.parse(bytes.toString("utf8")):void 0;const offered=parsed?(({confirmationRequired:_legacy,...offer})=>offer)(parsed):void 0;return offered?.installationPath===packageRoot?offered:void 0}async function savedStatus(version){try{const bytes=await optionalBytes(statusPath);const cached=bytes?JSON.parse(bytes.toString("utf8")):void 0;if(cached?.status?.currentVersion===version&&cached.expiresAt>now())return cached.status}catch{}return void 0}async function remember(status2,ttl){await rm(offerPath,{force:true});await mkdir(cacheRoot,{recursive:true});await atomicWrite(statusPath,jsonBytes({status:status2,checkedAt:now(),expiresAt:now()+ttl}));return status2}async function writableInstallation(){await canonicalizeRoot();if(rootIsLinked||/[\\/](?:\.pnpm|\.yarn|_npx)[\\/]/i.test(packageRoot)||/[\\/](?:\.pnpm|\.yarn|_npx)[\\/]/i.test(requestedRoot)||await optionalBytes(join(packageRoot,"tsconfig.json")))throw Error("This installation is managed by a workspace or another package manager. Use its original upgrade command.");if((await pkg()).name!==NAME)throw Error("The running installation is not the Zortex package.")}async function check({force=false}={}){const installed=await pkg();if(disabled())return{state:"unavailable",currentVersion:installed.version,message:"Update checks are disabled."};try{const cached=await savedOffer();if(!force&&cached?.currentVersion===installed.version&&cached.expiresAt>now())return cached;if(!force){const cachedStatus=await savedStatus(installed.version);if(cachedStatus)return cachedStatus}const packument=JSON.parse((await get(`${registry}/${encodeURIComponent(NAME)}`,16e6)).toString("utf8"));const channel="next";const target=packument["dist-tags"]?.[channel];if(typeof target!=="string")throw Error("The update channel is unavailable.");if(!newer(installed.version,target,packument.time))return await remember({state:"current",currentVersion:installed.version},6*60*6e4);const targetPackage=packument.versions?.[target];if(targetPackage?.name!==NAME||targetPackage.version!==target)throw Error("Invalid registry package identity.");const digest=metadataDigest(targetPackage);if(!digest)return await remember({state:"unsupported",currentVersion:installed.version,targetVersion:target,message:"This release does not publish verified incremental updates. No package was downloaded.",manualCommand:manual(target,packageRoot)},6*60*6e4);if(binShape(installed)!==binShape(targetPackage))return await remember({state:"unsupported",currentVersion:installed.version,targetVersion:target,message:"This release changes installed command links and requires its original package manager.",manualCommand:manual(target,packageRoot)},6*60*6e4);await writableInstallation();const offer={state:"available",currentVersion:installed.version,targetVersion:target,installationPath:packageRoot,confirmationToken:randomUUID(),manifestSha256:digest,checkedAt:now(),expiresAt:now()+15*6e4,channel};await mkdir(cacheRoot,{recursive:true});await atomicWrite(offerPath,jsonBytes(offer));await rm(statusPath,{force:true});return offer}catch(error){const unavailable={state:"unavailable",currentVersion:installed.version,message:error instanceof Error?error.message:"Update check failed."};try{await remember(unavailable,15*6e4)}catch{}return unavailable}}async function status(){const installed=await pkg();if(disabled())return{state:"unavailable",currentVersion:installed.version,message:"Update checks are disabled."};try{const cached=await savedOffer();if(cached?.currentVersion===installed.version&&cached.expiresAt>now())return cached}catch{}return await savedStatus(installed.version)??{state:"unavailable",currentVersion:installed.version,message:"No current update result is cached. Use update check to check the registry."}}async function reconstruct(manifest,bytes,digest){const packageBytes=jsonBytes({...manifest.package,zortexUpdate:{schemaVersion:1,manifest:MANIFEST,sha256:digest}});const generated=new Map([["package.json",packageBytes],[MANIFEST,bytes]]);if(manifest.provenance){const provenance=structuredClone(manifest.provenance);const own=manifest.files.filter(file=>!file.path.startsWith("node_modules/")).map(file=>({path:file.path,sha256:file.sha256}));own.push({path:"package.json",sha256:hash(packageBytes)},{path:MANIFEST,sha256:hash(bytes)});const root=provenance.packages?.find(row=>row.target==="");if(!root||root.filesSha256!==null)throw Error("Invalid update provenance template.");root.filesSha256=hash(own.map(file=>file.path+"\0"+file.sha256).sort().join("\n"));generated.set("release-provenance.json",jsonBytes(provenance))}return generated}async function smoke(version){if(options.smokeTest)return options.smokeTest(packageRoot,version);const cli=join(packageRoot,"dist","cli.js");const verificationEnv={...env,ZORTEX_UPDATES:"0",ZORTEX_UPDATE_VERIFY:"1",ZORTEX_AUTO_SYNC:"0",ZORTEX_CODEX_SETUP:"0",ZORTEX_TELEMETRY:"0",ZORTEX_FEEDBACK_TRAFFIC_CLASS:"internal_test"};const result=await execute(process.execPath,[cli,"--version"],{env:verificationEnv,timeout:3e4,windowsHide:true,maxBuffer:1024*1024});if(JSON.parse(result.stdout).version!==version)throw Error("The updated command still runs a different version.");await execute(process.execPath,[cli,"--help"],{env:verificationEnv,timeout:3e4,windowsHide:true,maxBuffer:1024*1024})}async function apply({version,confirmationToken}){if(disabled())throw Error("Updates are disabled by ZORTEX_UPDATES.");const offered=await savedOffer();if(!confirmationToken||!offered||offered.confirmationToken!==confirmationToken||offered.targetVersion!==version||offered.expiresAt<=now())throw Error("The release offer is missing, expired or mismatched. Run check again and retry with its version and token.");const confirmedAt=performance.now();const attempt=await outcomes.confirmed(offered.currentVersion,version).catch(()=>void 0);try{const result=await applyConfirmed(offered,version);const durationMs=Math.round(performance.now()-confirmedAt);await outcomes.installed(attempt,durationMs).catch(()=>{});return{...result,durationMs}}catch(error){await outcomes.failed(attempt,performance.now()-confirmedAt).catch(()=>{});throw error}}async function applyConfirmed(offered,version){await writableInstallation();await recover();const installed=await pkg();if(installed.version!==offered.currentVersion)throw Error("The installed version changed. Check again before updating.");await mkdir(cacheRoot,{recursive:true});let unlock;try{unlock=await withRecoveryLock(async()=>{await recoverLocked();return publishLock(join(packageRoot,".zortex-update.lock"))})}catch(error){if(error.code==="EEXIST")throw Error("Another update holds the installation lock.");throw error}const started=performance.now();const stageName=".zortex-update-"+randomUUID(),stage=join(packageRoot,stageName);let journal,retainRecovery=false;try{const target=JSON.parse((await get(`${registry}/${encodeURIComponent(NAME)}/${encodeURIComponent(version)}`,2e6)).toString("utf8"));if(target.name!==NAME||target.version!==version||metadataDigest(target)!==offered.manifestSha256)throw Error("The release changed. Run check again and retry with the current version and token.");const manifestBytes=await get(fileUrl(version,MANIFEST),4e6,15e3);const manifest=validateManifest(manifestBytes,offered.manifestSha256,version);if(!manifest.files.some(file=>file.path===RECOVERY_FILE))throw Error("This release removes the standalone update recovery module. "+manual(version,packageRoot));if(binShape(installed)!==binShape(manifest.package))throw Error("This release changes installed command links. "+manual(version,packageRoot));const dependencyChange=dependencyShape(installed)!==dependencyShape(manifest.package);const oldDigest=metadataDigest(installed),oldBytes=await optionalBytes(join(packageRoot,MANIFEST));if(!oldDigest||!oldBytes)throw Error(`This installation predates the incremental updater. One package-manager upgrade is required to install the baseline. ${manual(version,packageRoot)}`);const old=validateManifest(oldBytes,oldDigest,installed.version);const oldSpelling=new Map(old.files.map(file=>[file.path.toLowerCase(),file.path]));if(manifest.files.some(file=>oldSpelling.has(file.path.toLowerCase())&&oldSpelling.get(file.path.toLowerCase())!==file.path))throw Error("This release renames files only by letter case. "+manual(version,packageRoot));const generated=await reconstruct(manifest,manifestBytes,offered.manifestSha256);const nextPaths=new Set(manifest.files.map(file=>file.path));const removed=old.files.filter(file=>!nextPaths.has(file.path)).map(file=>file.path);let dependencies;if(dependencyChange){const dependencyStage=join(stage,"dependencies");dependencies=await(options.prepareDependencies??prepareDependencyUpdate)({packageRoot,stageRoot:dependencyStage,installedPackage:installed,targetPackage:manifest.package,env,registryUrl:registry});if(dependencies.replacements.length+dependencies.removals.length>2e3)throw Error("Too many dependency changes.");const seen=new Set,owned=[...old.files,...manifest.files].map(file=>file.path.toLowerCase());for(const path of[...dependencies.removals,...dependencies.replacements.map(row=>row.path)]){dependencyPath(path);const key=path.toLowerCase();if(seen.has(key)||owned.some(file=>file===key||file.startsWith(key+"/")))throw Error("Dependency update overlaps bundled product files.");seen.add(key);const existing=await lstat(await safeFile(packageRoot,path)).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(existing&&!existing.isDirectory())throw Error("Dependency update destination is not a directory.")}for(const replacement of dependencies.replacements){const source=await realpath(replacement.source),rel=relative(dependencyStage,source);if(!rel||isAbsolute(rel)||rel===".."||rel.startsWith(".."+sep)||!(await lstat(source)).isDirectory()||(await lstat(replacement.source)).isSymbolicLink())throw Error("Dependency update source is outside the staging directory.");replacement.source=source}const hiddenLock="node_modules/.package-lock.json";if(await optionalBytes(await safeFile(packageRoot,hiddenLock)))removed.push(hiddenLock)}const changes=[];const binPaths=new Set((typeof manifest.package.bin==="string"?[manifest.package.bin]:Object.values(manifest.package.bin??{})).map(path=>path.replace(/^\.\//,"")));let downloadedBytes=manifestBytes.length,reusedBytes=0;let cursor=0;await Promise.all(Array.from({length:8},async()=>{while(cursor<manifest.files.length){const file=manifest.files[cursor++];const destination=await safeFile(packageRoot,file.path);const existing=await optionalBytes(destination);const existingMode=existing===null?void 0:(await lstat(destination)).mode&511;const mode=file.mode??(binPaths.has(file.path)?493:existingMode);if(existing?.length===file.size&&hash(existing)===file.sha256){reusedBytes+=file.size;if(process.platform!=="win32"&&mode!==void 0&&mode!==existingMode)changes.push({path:file.path,bytes:existing,mode});continue}const bytes=await get(fileUrl(version,file.path),file.size,3e4);if(bytes.length!==file.size||hash(bytes)!==file.sha256)throw Error("Updated file integrity check failed: "+file.path);downloadedBytes+=bytes.length;changes.push({path:file.path,bytes,...mode===void 0?{}:{mode}})}}));for(const[path,bytes]of generated)changes.push({path,bytes});changes.sort((a,b)=>a.path===RECOVERY_FILE?-1:b.path===RECOVERY_FILE?1:a.path==="package.json"?1:b.path==="package.json"?-1:a.path.localeCompare(b.path));await mkdir(join(stage,"backup"),{recursive:true});const files=[];for(const path of[...dependencies?.removals??[],...dependencies?.replacements.map(row=>row.path)??[]]){const destination=await safeFile(packageRoot,path),existing=await lstat(destination).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});files.push({path,existed:!!existing,kind:"directory"});if(existing){const backup=join(stage,"backup",path);await mkdir(dirname(backup),{recursive:true});await cp(destination,backup,{recursive:true,verbatimSymlinks:true})}}for(const path of[...removed,...changes.map(file=>file.path)]){const destination=await safeFile(packageRoot,path),existing=await optionalBytes(destination);files.push({path,existed:existing!==null});if(existing){const backup=join(stage,"backup",path);await mkdir(dirname(backup),{recursive:true});await copyFile(destination,backup)}}for(const file of changes){const staged=join(stage,"new",file.path);await mkdir(dirname(staged),{recursive:true});await writeFile(staged,file.bytes);if(file.mode!==void 0)await chmod(staged,file.mode)}journal={schemaVersion:1,pid:process.pid,stage:stageName,phase:"applying",files};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(journal));for(const path of removed)await rm(await safeFile(packageRoot,path),{force:true});for(const path of dependencies?.removals??[])await rm(await safeFile(packageRoot,path),{recursive:true,force:true});for(const replacement of dependencies?.replacements??[]){const destination=await safeFile(packageRoot,replacement.path);await rm(destination,{recursive:true,force:true});await mkdir(dirname(destination),{recursive:true});await rename(replacement.source,destination)}for(const file of changes){const destination=await safeFile(packageRoot,file.path);await mkdir(dirname(destination),{recursive:true});await rename(join(stage,"new",file.path),destination)}await smoke(version);const committed={...journal,phase:"committed"};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(committed));journal=committed;await rm(offerPath,{force:true}).catch(()=>{});await rm(statusPath,{force:true}).catch(()=>{});return{state:"updated",currentVersion:installed.version,targetVersion:version,installationPath:packageRoot,downloadedBytes,reusedBytes,byteScope:"product-files",...dependencies?{dependencyUpdate:{reusedPackages:dependencies.reusedPackages,changedPackages:dependencies.changedPackages,durationMs:dependencies.durationMs}}:{},changedFiles:changes.length,removedFiles:removed.length,durationMs:Math.round(performance.now()-started),restartRequired:true}}catch(error){if(journal?.phase==="applying"){try{await rollback(journal);const restored={...journal,phase:"committed"};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(restored));journal=restored}catch(recoveryError){retainRecovery=true;throw recoveryError}}throw error}finally{try{if(!retainRecovery){try{await rm(stage,{recursive:true,force:true});await rm(join(packageRoot,JOURNAL),{force:true})}catch(cleanupError){if(journal?.phase!=="committed")throw cleanupError}}}finally{await unlock()}}}return{check,status,apply,recover,observe:outcomes.observe}}export const productUpdater=createUpdater();
1
+ import{createHash,randomUUID}from"node:crypto";import{readFile,writeFile,mkdir,lstat,realpath,rename,copyFile,cp,rm,chmod}from"node:fs/promises";import{resolve,join,dirname,relative,isAbsolute,sep}from"node:path";import{homedir}from"node:os";import{fileURLToPath}from"node:url";import{execFile}from"node:child_process";import{promisify}from"node:util";import{prepareDependencyUpdate}from"./update-dependencies.js";import{createUpdateTelemetry}from"./update-telemetry.js";import{createUpdateRecovery,safePath,safeFile,optionalBytes,dependencyPath,atomicWrite,JOURNAL,RECOVERY_FILE}from"./update-recovery.js";const execute=promisify(execFile);const NAME="@zortexhq/indra-v2.5";const MANIFEST="update-manifest.json";const MAX_BYTES=12e7;const hash=bytes=>createHash("sha256").update(bytes).digest("hex");const jsonBytes=value=>Buffer.from(JSON.stringify(value,null,2)+"\n");function metadataDigest(pkg){const update=pkg.zortexUpdate;if(update?.schemaVersion!==1||update.manifest!==MANIFEST||!/^[a-f0-9]{64}$/.test(update.sha256??""))return void 0;return update.sha256}function validateManifest(bytes,digest,version){if(hash(bytes)!==digest)throw Error("Update manifest integrity check failed.");const value=JSON.parse(bytes.toString("utf8"));if(value.schemaVersion!==1||value.package?.name!==NAME||value.package.version!==version||value.package.zortexUpdate||!Array.isArray(value.files)||value.files.length>8e3)throw Error("Invalid update manifest.");let total=0;const paths=new Set;for(const file of value.files){safePath(file.path);const key=file.path.toLowerCase();if(paths.has(key)||[MANIFEST,"package.json","release-provenance.json"].includes(key)||!/^[a-f0-9]{64}$/.test(file.sha256)||!Number.isSafeInteger(file.size)||file.size<0||file.mode!==void 0&&![420,493,420,493].includes(file.mode))throw Error("Invalid update file entry.");paths.add(key);total+=file.size}if(total>MAX_BYTES)throw Error("Update exceeds the installed product size limit.");return value}function dependencyShape(pkg){const bundled=new Set(pkg.bundledDependencies??[]);return JSON.stringify(["dependencies","optionalDependencies","peerDependencies","peerDependenciesMeta"].map(field=>[field,Object.entries(pkg[field]??{}).filter(([name])=>!bundled.has(name)).sort(([a],[b])=>a.localeCompare(b))]))}function binShape(pkg){const bins=typeof pkg.bin==="string"?{[pkg.name.split("/").at(-1)]:pkg.bin}:pkg.bin??{};return JSON.stringify(Object.entries(bins).map(([name,path])=>[name,typeof path==="string"?path.replace(/^\.\//,""):path]).sort(([a],[b])=>String(a).localeCompare(String(b))))}function versionParts(version){const match=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(version);if(!match)throw Error("Invalid registry version.");return[Number(match[1]),Number(match[2]),Number(match[3]),match[4]]}function newer(current,target,times={}){if(current===target)return false;const a=versionParts(current),b=versionParts(target);for(const i of[0,1,2])if(a[i]!==b[i])return b[i]>a[i];if(!a[3])return false;if(!b[3])return true;const oldTime=Date.parse(times[current]??""),newTime=Date.parse(times[target]??"");if(Number.isFinite(oldTime)&&Number.isFinite(newTime))return newTime>oldTime;const left=a[3].split("."),right=b[3].split(".");for(let i=0;i<Math.max(left.length,right.length);i++){if(left[i]===right[i])continue;if(left[i]===void 0)return true;if(right[i]===void 0)return false;return/^\d+$/.test(left[i])&&/^\d+$/.test(right[i])?Number(right[i])>Number(left[i]):right[i]>left[i]}return false}function manual(version,installationPath){return`Use the package manager that installed ${installationPath} to upgrade ${NAME} to exactly ${version} at that installation path.`}export function createUpdater(options={}){let packageRoot=resolve(options.packageRoot??fileURLToPath(new URL("..",import.meta.url)));const requestedRoot=packageRoot;const{recover,recoverLocked,withRecoveryLock,publishLock,rollback}=createUpdateRecovery(requestedRoot);let rootIsLinked=false,rootReady;const canonicalizeRoot=()=>rootReady??=(async()=>{rootIsLinked=(await lstat(requestedRoot)).isSymbolicLink();packageRoot=await realpath(requestedRoot)})();const cacheRoot=resolve(options.cacheRoot??join(homedir(),".zortex","updates",hash(packageRoot).slice(0,24)));const registry=(options.registryUrl??"https://registry.npmjs.org").replace(/\/$/,"");const content=(options.contentBaseUrl??"https://cdn.jsdelivr.net/npm").replace(/\/$/,"");const fetcher=options.fetch??globalThis.fetch,now=options.now??Date.now;const env=options.env??process.env;const outcomes=createUpdateTelemetry({cacheRoot,env,now});const disabled=()=>/^(0|false|off)$/i.test(env.ZORTEX_UPDATES??"");const offerPath=join(cacheRoot,"offer.json"),statusPath=join(cacheRoot,"status.json");const pkg=async()=>{await canonicalizeRoot();return JSON.parse(await readFile(join(packageRoot,"package.json"),"utf8"))};async function get(url,limit,timeout=5e3){const response=await fetcher(url,{signal:AbortSignal.timeout(timeout),redirect:"error"});if(!response.ok||!response.body)throw Error(`Update download unavailable (${response.status}).`);if(Number(response.headers.get("content-length")??0)>limit)throw Error("Update response exceeds its size limit.");const chunks=[];let size=0;for await(const chunk of response.body){size+=chunk.length;if(size>limit)throw Error("Update response exceeds its size limit.");chunks.push(chunk)}return Buffer.concat(chunks)}const fileUrl=(version,path)=>`${content}/${NAME}@${encodeURIComponent(version)}/${path.split("/").map(encodeURIComponent).join("/")}`;async function savedOffer(){await canonicalizeRoot();const bytes=await optionalBytes(offerPath);const parsed=bytes?JSON.parse(bytes.toString("utf8")):void 0;const offered=parsed?(({confirmationRequired:_legacy,...offer})=>offer)(parsed):void 0;return offered?.installationPath===packageRoot?offered:void 0}async function savedStatus(version){try{const bytes=await optionalBytes(statusPath);const cached=bytes?JSON.parse(bytes.toString("utf8")):void 0;if(cached?.status?.currentVersion===version&&cached.expiresAt>now())return cached.status}catch{}return void 0}async function remember(status2,ttl){await rm(offerPath,{force:true});await mkdir(cacheRoot,{recursive:true});await atomicWrite(statusPath,jsonBytes({status:status2,checkedAt:now(),expiresAt:now()+ttl}));return status2}async function writableInstallation(){await canonicalizeRoot();if(rootIsLinked||/[\\/](?:\.pnpm|\.yarn|_npx)[\\/]/i.test(packageRoot)||/[\\/](?:\.pnpm|\.yarn|_npx)[\\/]/i.test(requestedRoot)||await optionalBytes(join(packageRoot,"tsconfig.json")))throw Error("This installation is managed by a workspace or another package manager. Use its original upgrade command.");if((await pkg()).name!==NAME)throw Error("The running installation is not the Zortex package.")}async function check({force=false}={}){const installed=await pkg();if(disabled())return{state:"unavailable",currentVersion:installed.version,message:"Update checks are disabled."};try{const cached=await savedOffer();if(!force&&cached?.currentVersion===installed.version&&cached.expiresAt>now())return cached;if(!force){const cachedStatus=await savedStatus(installed.version);if(cachedStatus)return cachedStatus}const packument=JSON.parse((await get(`${registry}/${encodeURIComponent(NAME)}`,16e6)).toString("utf8"));const channel="next";const target=packument["dist-tags"]?.[channel];if(typeof target!=="string")throw Error("The update channel is unavailable.");if(!newer(installed.version,target,packument.time))return await remember({state:"current",currentVersion:installed.version},6*60*6e4);const targetPackage=packument.versions?.[target];if(targetPackage?.name!==NAME||targetPackage.version!==target)throw Error("Invalid registry package identity.");const digest=metadataDigest(targetPackage);if(!digest)return await remember({state:"unsupported",currentVersion:installed.version,targetVersion:target,message:"This release does not publish verified incremental updates. No package was downloaded.",manualCommand:manual(target,packageRoot)},6*60*6e4);if(binShape(installed)!==binShape(targetPackage))return await remember({state:"unsupported",currentVersion:installed.version,targetVersion:target,message:"This release changes installed command links and requires its original package manager.",manualCommand:manual(target,packageRoot)},6*60*6e4);await writableInstallation();let expectedDownloadBytes,expectedChangedFiles;try{const manifestBytes=await get(fileUrl(target,MANIFEST),4e6,15e3);const manifest=validateManifest(manifestBytes,digest,target);const oldDigest=metadataDigest(installed),oldBytes=oldDigest?await optionalBytes(join(packageRoot,MANIFEST)):void 0;if(oldDigest&&oldBytes){const old=validateManifest(oldBytes,oldDigest,installed.version);const oldByPath=new Map(old.files.map(file=>[file.path,file.sha256]));const generated=await reconstruct(manifest,manifestBytes,digest);for(const[path,bytes]of generated){if(oldByPath.get(path)===hash(bytes))continue;expectedDownloadBytes=(expectedDownloadBytes??0)+bytes.length;expectedChangedFiles=(expectedChangedFiles??0)+1}for(const file of manifest.files){if(oldByPath.get(file.path)===file.sha256)continue;expectedDownloadBytes=(expectedDownloadBytes??0)+file.size;expectedChangedFiles=(expectedChangedFiles??0)+1}}}catch{}const offer={state:"available",currentVersion:installed.version,targetVersion:target,installationPath:packageRoot,confirmationToken:randomUUID(),manifestSha256:digest,checkedAt:now(),expiresAt:now()+15*6e4,channel,...expectedDownloadBytes!==void 0&&expectedChangedFiles!==void 0?{expectedDownloadBytes,expectedChangedFiles}:{}};await mkdir(cacheRoot,{recursive:true});await atomicWrite(offerPath,jsonBytes(offer));await rm(statusPath,{force:true});return offer}catch(error){const unavailable={state:"unavailable",currentVersion:installed.version,message:error instanceof Error?error.message:"Update check failed."};try{await remember(unavailable,15*6e4)}catch{}return unavailable}}async function status(){const installed=await pkg();if(disabled())return{state:"unavailable",currentVersion:installed.version,message:"Update checks are disabled."};try{const cached=await savedOffer();if(cached?.currentVersion===installed.version&&cached.expiresAt>now())return cached}catch{}return await savedStatus(installed.version)??{state:"unavailable",currentVersion:installed.version,message:"No current update result is cached. Use update check to check the registry."}}async function reconstruct(manifest,bytes,digest){const packageBytes=jsonBytes({...manifest.package,zortexUpdate:{schemaVersion:1,manifest:MANIFEST,sha256:digest}});const generated=new Map([["package.json",packageBytes],[MANIFEST,bytes]]);if(manifest.provenance){const provenance=structuredClone(manifest.provenance);const own=manifest.files.filter(file=>!file.path.startsWith("node_modules/")).map(file=>({path:file.path,sha256:file.sha256}));own.push({path:"package.json",sha256:hash(packageBytes)},{path:MANIFEST,sha256:hash(bytes)});const root=provenance.packages?.find(row=>row.target==="");if(!root||root.filesSha256!==null)throw Error("Invalid update provenance template.");root.filesSha256=hash(own.map(file=>file.path+"\0"+file.sha256).sort().join("\n"));generated.set("release-provenance.json",jsonBytes(provenance))}return generated}async function smoke(version){if(options.smokeTest)return options.smokeTest(packageRoot,version);const cli=join(packageRoot,"dist","cli.js");const verificationEnv={...env,ZORTEX_UPDATES:"0",ZORTEX_UPDATE_VERIFY:"1",ZORTEX_AUTO_SYNC:"0",ZORTEX_CODEX_SETUP:"0",ZORTEX_TELEMETRY:"0",ZORTEX_FEEDBACK_TRAFFIC_CLASS:"internal_test"};const result=await execute(process.execPath,[cli,"--version"],{env:verificationEnv,timeout:3e4,windowsHide:true,maxBuffer:1024*1024});if(JSON.parse(result.stdout).version!==version)throw Error("The updated command still runs a different version.");await execute(process.execPath,[cli,"--help"],{env:verificationEnv,timeout:3e4,windowsHide:true,maxBuffer:1024*1024})}async function apply({version,confirmationToken}){if(disabled())throw Error("Updates are disabled by ZORTEX_UPDATES.");const offered=await savedOffer();if(!confirmationToken||!offered||offered.confirmationToken!==confirmationToken||offered.targetVersion!==version||offered.expiresAt<=now())throw Error("The release offer is missing, expired or mismatched. Run check again and retry with its version and token.");const confirmedAt=performance.now();const attempt=await outcomes.confirmed(offered.currentVersion,version).catch(()=>void 0);try{const result=await applyConfirmed(offered,version);const durationMs=Math.round(performance.now()-confirmedAt);await outcomes.installed(attempt,durationMs).catch(()=>{});return{...result,durationMs}}catch(error){await outcomes.failed(attempt,performance.now()-confirmedAt).catch(()=>{});throw error}}async function applyConfirmed(offered,version){await writableInstallation();await recover();const installed=await pkg();if(installed.version!==offered.currentVersion)throw Error("The installed version changed. Check again before updating.");await mkdir(cacheRoot,{recursive:true});let unlock;try{unlock=await withRecoveryLock(async()=>{await recoverLocked();return publishLock(join(packageRoot,".zortex-update.lock"))})}catch(error){if(error.code==="EEXIST")throw Error("Another update holds the installation lock.");throw error}const started=performance.now();const stageName=".zortex-update-"+randomUUID(),stage=join(packageRoot,stageName);let journal,retainRecovery=false;try{const target=JSON.parse((await get(`${registry}/${encodeURIComponent(NAME)}/${encodeURIComponent(version)}`,2e6)).toString("utf8"));if(target.name!==NAME||target.version!==version||metadataDigest(target)!==offered.manifestSha256)throw Error("The release changed. Run check again and retry with the current version and token.");const manifestBytes=await get(fileUrl(version,MANIFEST),4e6,15e3);const manifest=validateManifest(manifestBytes,offered.manifestSha256,version);if(!manifest.files.some(file=>file.path===RECOVERY_FILE))throw Error("This release removes the standalone update recovery module. "+manual(version,packageRoot));if(binShape(installed)!==binShape(manifest.package))throw Error("This release changes installed command links. "+manual(version,packageRoot));const dependencyChange=dependencyShape(installed)!==dependencyShape(manifest.package);const oldDigest=metadataDigest(installed),oldBytes=await optionalBytes(join(packageRoot,MANIFEST));if(!oldDigest||!oldBytes)throw Error(`This installation predates the incremental updater. One package-manager upgrade is required to install the baseline. ${manual(version,packageRoot)}`);const old=validateManifest(oldBytes,oldDigest,installed.version);const oldSpelling=new Map(old.files.map(file=>[file.path.toLowerCase(),file.path]));if(manifest.files.some(file=>oldSpelling.has(file.path.toLowerCase())&&oldSpelling.get(file.path.toLowerCase())!==file.path))throw Error("This release renames files only by letter case. "+manual(version,packageRoot));const generated=await reconstruct(manifest,manifestBytes,offered.manifestSha256);const nextPaths=new Set(manifest.files.map(file=>file.path));const removed=old.files.filter(file=>!nextPaths.has(file.path)).map(file=>file.path);let dependencies;if(dependencyChange){const dependencyStage=join(stage,"dependencies");dependencies=await(options.prepareDependencies??prepareDependencyUpdate)({packageRoot,stageRoot:dependencyStage,installedPackage:installed,targetPackage:manifest.package,env,registryUrl:registry});if(dependencies.replacements.length+dependencies.removals.length>2e3)throw Error("Too many dependency changes.");const seen=new Set,owned=[...old.files,...manifest.files].map(file=>file.path.toLowerCase());for(const path of[...dependencies.removals,...dependencies.replacements.map(row=>row.path)]){dependencyPath(path);const key=path.toLowerCase();if(seen.has(key)||owned.some(file=>file===key||file.startsWith(key+"/")))throw Error("Dependency update overlaps bundled product files.");seen.add(key);const existing=await lstat(await safeFile(packageRoot,path)).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(existing&&!existing.isDirectory())throw Error("Dependency update destination is not a directory.")}for(const replacement of dependencies.replacements){const source=await realpath(replacement.source),rel=relative(dependencyStage,source);if(!rel||isAbsolute(rel)||rel===".."||rel.startsWith(".."+sep)||!(await lstat(source)).isDirectory()||(await lstat(replacement.source)).isSymbolicLink())throw Error("Dependency update source is outside the staging directory.");replacement.source=source}const hiddenLock="node_modules/.package-lock.json";if(await optionalBytes(await safeFile(packageRoot,hiddenLock)))removed.push(hiddenLock)}const changes=[];const binPaths=new Set((typeof manifest.package.bin==="string"?[manifest.package.bin]:Object.values(manifest.package.bin??{})).map(path=>path.replace(/^\.\//,"")));let downloadedBytes=manifestBytes.length,reusedBytes=0;let cursor=0;await Promise.all(Array.from({length:8},async()=>{while(cursor<manifest.files.length){const file=manifest.files[cursor++];const destination=await safeFile(packageRoot,file.path);const existing=await optionalBytes(destination);const existingMode=existing===null?void 0:(await lstat(destination)).mode&511;const mode=file.mode??(binPaths.has(file.path)?493:existingMode);if(existing?.length===file.size&&hash(existing)===file.sha256){reusedBytes+=file.size;if(process.platform!=="win32"&&mode!==void 0&&mode!==existingMode)changes.push({path:file.path,bytes:existing,mode});continue}const bytes=await get(fileUrl(version,file.path),file.size,3e4);if(bytes.length!==file.size||hash(bytes)!==file.sha256)throw Error("Updated file integrity check failed: "+file.path);downloadedBytes+=bytes.length;changes.push({path:file.path,bytes,...mode===void 0?{}:{mode}})}}));for(const[path,bytes]of generated)changes.push({path,bytes});changes.sort((a,b)=>a.path===RECOVERY_FILE?-1:b.path===RECOVERY_FILE?1:a.path==="package.json"?1:b.path==="package.json"?-1:a.path.localeCompare(b.path));await mkdir(join(stage,"backup"),{recursive:true});const files=[];for(const path of[...dependencies?.removals??[],...dependencies?.replacements.map(row=>row.path)??[]]){const destination=await safeFile(packageRoot,path),existing=await lstat(destination).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});files.push({path,existed:!!existing,kind:"directory"});if(existing){const backup=join(stage,"backup",path);await mkdir(dirname(backup),{recursive:true});await cp(destination,backup,{recursive:true,verbatimSymlinks:true})}}for(const path of[...removed,...changes.map(file=>file.path)]){const destination=await safeFile(packageRoot,path),existing=await optionalBytes(destination);files.push({path,existed:existing!==null});if(existing){const backup=join(stage,"backup",path);await mkdir(dirname(backup),{recursive:true});await copyFile(destination,backup)}}for(const file of changes){const staged=join(stage,"new",file.path);await mkdir(dirname(staged),{recursive:true});await writeFile(staged,file.bytes);if(file.mode!==void 0)await chmod(staged,file.mode)}journal={schemaVersion:1,pid:process.pid,stage:stageName,phase:"applying",files};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(journal));for(const path of removed)await rm(await safeFile(packageRoot,path),{force:true});for(const path of dependencies?.removals??[])await rm(await safeFile(packageRoot,path),{recursive:true,force:true});for(const replacement of dependencies?.replacements??[]){const destination=await safeFile(packageRoot,replacement.path);await rm(destination,{recursive:true,force:true});await mkdir(dirname(destination),{recursive:true});await rename(replacement.source,destination)}for(const file of changes){const destination=await safeFile(packageRoot,file.path);await mkdir(dirname(destination),{recursive:true});await rename(join(stage,"new",file.path),destination)}await smoke(version);const committed={...journal,phase:"committed"};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(committed));journal=committed;await rm(offerPath,{force:true}).catch(()=>{});await rm(statusPath,{force:true}).catch(()=>{});return{state:"updated",currentVersion:installed.version,targetVersion:version,installationPath:packageRoot,downloadedBytes,reusedBytes,byteScope:"product-files",...dependencies?{dependencyUpdate:{reusedPackages:dependencies.reusedPackages,changedPackages:dependencies.changedPackages,durationMs:dependencies.durationMs}}:{},changedFiles:changes.length,removedFiles:removed.length,durationMs:Math.round(performance.now()-started),restartRequired:true}}catch(error){if(journal?.phase==="applying"){try{await rollback(journal);const restored={...journal,phase:"committed"};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(restored));journal=restored}catch(recoveryError){retainRecovery=true;throw recoveryError}}throw error}finally{try{if(!retainRecovery){try{await rm(stage,{recursive:true,force:true});await rm(join(packageRoot,JOURNAL),{force:true})}catch(cleanupError){if(journal?.phase!=="committed")throw cleanupError}}}finally{await unlock()}}}return{check,status,apply,recover,observe:outcomes.observe}}export const productUpdater=createUpdater();
package/dist/mcp.js CHANGED
@@ -1,3 +1,3 @@
1
- import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";import{businessError}from"@zortexhq/plugin-connector-framework/api";import{withUsageInvocation,currentUsageInvocation,USAGE_TOOL_NAMES,usageOutcome,usageResultSummary,usageErrorCategory}from"@zortexhq/plugin-telemetry/api";import{toolSpecs}from"./tools.js";import{randomUUID}from"node:crypto";import{productUpdater}from"./auto-update.js";import{callUpdateTool,updateTool}from"./update-tool.js";const invocationTool=operation=>operation&&USAGE_TOOL_NAMES.includes(operation)?operation:"unknown";function boundedSqlError(args,maxMs){if(!args||typeof args!=="object"||Array.isArray(args))return"Pass a SQL argument object.";const request=args;if(Object.keys(request).some(key=>!["sql","params","timeoutMs"].includes(key)))return"Only sql, params and timeoutMs are accepted.";if(typeof request.sql!=="string"||!request.sql.trim()||Buffer.byteLength(request.sql)>65536)return"sql must be a nonempty string of at most 65536 bytes.";if("params"in request&&(!Array.isArray(request.params)||request.params.length>100||request.params.some(value=>value!==null&&typeof value!=="boolean"&&(typeof value!=="number"||!Number.isFinite(value))&&(typeof value!=="string"||Buffer.byteLength(value)>16384))))return"params must be an array of at most 100 bounded scalar values; omit params when unused.";if("timeoutMs"in request&&(!Number.isSafeInteger(request.timeoutMs)||Number(request.timeoutMs)<50||Number(request.timeoutMs)>maxMs))return`timeoutMs must be an integer from 50 to ${maxMs}; omit timeoutMs to use the default.`}const surfacedVersions=new Set;export function createMcp(gateway,options={}){const localUpdates=!options.remote&&!options.operations;const updater=options.updater??productUpdater;if(localUpdates&&process.env.ZORTEX_FEEDBACK_TRAFFIC_CLASS!=="internal_test")void updater.check().catch(()=>{});const specs=options.operations?toolSpecs.filter(spec=>options.operations.includes(spec.operation)):toolSpecs.filter(spec=>spec.operation!=="read");const server=new Server({name:"indra-v2",version:"0.1.0-dev.3"},{capabilities:{tools:{}}});const tools=specs.map(spec=>{let properties=Object.fromEntries(Object.entries(spec.parameters).map(([key,value])=>[key,{type:"type"in value?value.type==="json"?"object":value.type:"object"}]));const bounded=spec.operation==="search"&&options.sqlTimeoutMaxMs;if(bounded){properties.sql={type:"string",minLength:1,maxLength:65536};properties.params={type:"array",maxItems:100,items:{type:["string","number","boolean","null"]},description:"Omit when SQL has no placeholders; do not send null."};properties.timeoutMs={type:"integer",minimum:50,maximum:bounded,description:`Omit to use the server default of ${bounded} ms.`}}const remoteDescription=options.remote&&spec.operation==="action"?"Invoke a discovered product action using name and params, including browser, computer control and connector setup. Product use supplies authorization; continue through available tools.":spec.description;return{name:"indra."+spec.operation,description:bounded?`${remoteDescription} Omit timeoutMs to use the ${bounded} ms default; omit params when unused.`:remoteDescription,inputSchema:{type:"object",properties,required:Object.entries(spec.parameters).filter(([,value])=>value.required).map(([key])=>key),additionalProperties:false},...options.operations?{annotations:{readOnlyHint:spec.operation!=="action",destructiveHint:spec.operation==="action",openWorldHint:["action","actions","read"].includes(spec.operation)}}:{}}});if(localUpdates)tools.push(updateTool);server.setRequestHandler("tools/list",()=>({tools}));server.setRequestHandler("tools/call",async(request,context)=>{const name=request.params.name,spec=specs.find(spec2=>"indra."+spec2.operation===name);const args=request.params.arguments??{};const tool=invocationTool(spec?.operation??(localUpdates&&name===updateTool.name?"update":void 0));return withUsageInvocation({entrypoint:options.remote?"local_cloud":"mcp",tool,owner:options.remote||options.telemetry?"transport":"gateway"},async()=>{const started=performance.now();let result;const signal=options.requestSignal?AbortSignal.any([context.mcpReq.signal,options.requestSignal]):context.mcpReq.signal;try{const sqlError=spec?.operation==="search"&&options.sqlTimeoutMaxMs?boundedSqlError(args,options.sqlTimeoutMaxMs):void 0;result=localUpdates&&name===updateTool.name?await callUpdateTool(args,updater):sqlError?businessError("invalid_argument",sqlError,"plugin"):spec?await gateway.call(spec.operation,args,{signal}):{err:{code:"not_found",layer:"plugin",message:"Unknown indra tool."}};if(localUpdates&&options.onUpdateObservation){await options.onUpdateObservation(!!spec&&!!result&&typeof result==="object"&&"ok"in result).catch(()=>{})}let updateNotice;if(localUpdates&&spec&&!(result&&typeof result==="object"&&"err"in result)){try{const offer=await updater.status();if(offer?.state==="available"&&typeof offer.targetVersion==="string"&&!surfacedVersions.has(offer.targetVersion)){surfacedVersions.add(offer.targetVersion);updateNotice=`
1
+ import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";import{businessError}from"@zortexhq/plugin-connector-framework/api";import{withUsageInvocation,currentUsageInvocation,USAGE_TOOL_NAMES,usageOutcome,usageResultSummary,usageErrorCategory}from"@zortexhq/plugin-telemetry/api";import{toolSpecs}from"./tools.js";import{randomUUID}from"node:crypto";import{productUpdater}from"./auto-update.js";import{callUpdateTool,updateTool}from"./update-tool.js";const invocationTool=operation=>operation&&USAGE_TOOL_NAMES.includes(operation)?operation:"unknown";function boundedSqlError(args,maxMs){if(!args||typeof args!=="object"||Array.isArray(args))return"Pass a SQL argument object.";const request=args;if(Object.keys(request).some(key=>!["sql","params","timeoutMs"].includes(key)))return"Only sql, params and timeoutMs are accepted.";if(typeof request.sql!=="string"||!request.sql.trim()||Buffer.byteLength(request.sql)>65536)return"sql must be a nonempty string of at most 65536 bytes.";if("params"in request&&(!Array.isArray(request.params)||request.params.length>100||request.params.some(value=>value!==null&&typeof value!=="boolean"&&(typeof value!=="number"||!Number.isFinite(value))&&(typeof value!=="string"||Buffer.byteLength(value)>16384))))return"params must be an array of at most 100 bounded scalar values; omit params when unused.";if("timeoutMs"in request&&(!Number.isSafeInteger(request.timeoutMs)||Number(request.timeoutMs)<50||Number(request.timeoutMs)>maxMs))return`timeoutMs must be an integer from 50 to ${maxMs}; omit timeoutMs to use the default.`}const surfacedVersions=new Set;const formatBytes=bytes=>bytes<1024?`${bytes} B`:bytes<1048576?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/1048576).toFixed(1)} MB`;export function createMcp(gateway,options={}){const localUpdates=!options.remote&&!options.operations;const updater=options.updater??productUpdater;if(localUpdates&&process.env.ZORTEX_FEEDBACK_TRAFFIC_CLASS!=="internal_test")void updater.check().catch(()=>{});const specs=options.operations?toolSpecs.filter(spec=>options.operations.includes(spec.operation)):toolSpecs.filter(spec=>spec.operation!=="read");const server=new Server({name:"indra-v2",version:"0.1.0-dev.3"},{capabilities:{tools:{}}});const tools=specs.map(spec=>{let properties=Object.fromEntries(Object.entries(spec.parameters).map(([key,value])=>[key,{type:"type"in value?value.type==="json"?"object":value.type:"object"}]));const bounded=spec.operation==="search"&&options.sqlTimeoutMaxMs;if(bounded){properties.sql={type:"string",minLength:1,maxLength:65536};properties.params={type:"array",maxItems:100,items:{type:["string","number","boolean","null"]},description:"Omit when SQL has no placeholders; do not send null."};properties.timeoutMs={type:"integer",minimum:50,maximum:bounded,description:`Omit to use the server default of ${bounded} ms.`}}const remoteDescription=options.remote&&spec.operation==="action"?"Invoke a discovered product action using name and params, including browser, computer control and connector setup. Product use supplies authorization; continue through available tools.":spec.description;return{name:"indra."+spec.operation,description:bounded?`${remoteDescription} Omit timeoutMs to use the ${bounded} ms default; omit params when unused.`:remoteDescription,inputSchema:{type:"object",properties,required:Object.entries(spec.parameters).filter(([,value])=>value.required).map(([key])=>key),additionalProperties:false},...options.operations?{annotations:{readOnlyHint:spec.operation!=="action",destructiveHint:spec.operation==="action",openWorldHint:["action","actions","read"].includes(spec.operation)}}:{}}});if(localUpdates)tools.push(updateTool);server.setRequestHandler("tools/list",()=>({tools}));server.setRequestHandler("tools/call",async(request,context)=>{const name=request.params.name,spec=specs.find(spec2=>"indra."+spec2.operation===name);const args=request.params.arguments??{};const tool=invocationTool(spec?.operation??(localUpdates&&name===updateTool.name?"update":void 0));return withUsageInvocation({entrypoint:options.remote?"local_cloud":"mcp",tool,owner:options.remote||options.telemetry?"transport":"gateway"},async()=>{const started=performance.now();let result;const signal=options.requestSignal?AbortSignal.any([context.mcpReq.signal,options.requestSignal]):context.mcpReq.signal;try{const sqlError=spec?.operation==="search"&&options.sqlTimeoutMaxMs?boundedSqlError(args,options.sqlTimeoutMaxMs):void 0;result=localUpdates&&name===updateTool.name?await callUpdateTool(args,updater):sqlError?businessError("invalid_argument",sqlError,"plugin"):spec?await gateway.call(spec.operation,args,{signal}):{err:{code:"not_found",layer:"plugin",message:"Unknown indra tool."}};if(localUpdates&&options.onUpdateObservation){await options.onUpdateObservation(!!spec&&!!result&&typeof result==="object"&&"ok"in result).catch(()=>{})}let updateNotice;if(localUpdates&&spec&&!(result&&typeof result==="object"&&"err"in result)){try{const offer=await updater.status();if(offer?.state==="available"&&typeof offer.targetVersion==="string"&&!surfacedVersions.has(offer.targetVersion)){surfacedVersions.add(offer.targetVersion);const estimate=typeof offer.expectedDownloadBytes==="number"&&typeof offer.expectedChangedFiles==="number"?`; about ${formatBytes(offer.expectedDownloadBytes)} across ${offer.expectedChangedFiles} changed files`:"";updateNotice=`
2
2
 
3
- [Zortex update] Version ${offer.targetVersion} is available (installed ${offer.currentVersion}). Use the indra.update tool: operation check to review the offer, then operation apply with its version and confirmationToken. Only changed files are downloaded; the new version takes effect after the host and MCP session restart.`}}catch{}}return{content:[{type:"text",text:JSON.stringify(result)+(updateNotice??"")}],structuredContent:result,isError:!!result&&typeof result==="object"&&"err"in result}}finally{try{const reply=result&&typeof result==="object"&&("ok"in result||"err"in result||"empty"in result)?result:businessError(signal.aborted?"aborted":"unavailable","Operation did not return.","plugin");const outcome=usageOutcome(reply),durationMs=Math.min(864e5,Math.max(0,Math.round(performance.now()-started)));if(!options.remote&&options.telemetry)try{const resultSummary=usageResultSummary(reply),errorCategory=usageErrorCategory(reply);const operation=["search","context","sql","actions","action","manage","instruction","handbook"].includes(tool)?tool:"mcp.call";const saved=await options.telemetry()?.record({operation,outcome,durationMs,...resultSummary?{result:resultSummary}:{},...errorCategory?{errorCategory}:{},...tool==="action"&&args.name==="connector.invoke"?{code:"effective_invoke"}:{}});if(saved&&"err"in saved)process.stderr.write("indra feedback: local observation was not recorded.\n")}catch{process.stderr.write("indra feedback: local observation failed.\n")}if(options.onCall)try{await options.onCall({id:currentUsageInvocation()?.id??randomUUID(),at:new Date().toISOString(),operation:tool,outcome,success:!!result&&typeof result==="object"&&"ok"in result,durationMs,paramsState:!("params"in args)?"omitted":Array.isArray(args.params)?"array":args.params===null?"null":"invalid",timeoutState:!("timeoutMs"in args)?"omitted":Number.isSafeInteger(args.timeoutMs)&&Number(args.timeoutMs)>=50&&Number(args.timeoutMs)<=(options.sqlTimeoutMaxMs??3e3)?"valid":"invalid"})}catch{process.stderr.write("local cloud: CALL_OBSERVATION_FAILED\n")}}catch{process.stderr.write("indra feedback: terminal observation failed.\n")}}})});return server}export function startMcp(gateway,options={}){return serveStdio(()=>createMcp(gateway,options),{onerror:()=>process.stderr.write("indra MCP request failed.\n")})}
3
+ [Zortex update] Version ${offer.targetVersion} is available (installed ${offer.currentVersion}${estimate}). Use the indra.update tool: operation check to review the offer, then operation apply with its version and confirmationToken. Only changed files are downloaded; the new version takes effect after the host and MCP session restart.`}}catch{}}return{content:[{type:"text",text:JSON.stringify(result)+(updateNotice??"")}],structuredContent:result,isError:!!result&&typeof result==="object"&&"err"in result}}finally{try{const reply=result&&typeof result==="object"&&("ok"in result||"err"in result||"empty"in result)?result:businessError(signal.aborted?"aborted":"unavailable","Operation did not return.","plugin");const outcome=usageOutcome(reply),durationMs=Math.min(864e5,Math.max(0,Math.round(performance.now()-started)));if(!options.remote&&options.telemetry)try{const resultSummary=usageResultSummary(reply),errorCategory=usageErrorCategory(reply);const operation=["search","context","sql","actions","action","manage","instruction","handbook"].includes(tool)?tool:"mcp.call";const saved=await options.telemetry()?.record({operation,outcome,durationMs,...resultSummary?{result:resultSummary}:{},...errorCategory?{errorCategory}:{},...tool==="action"&&args.name==="connector.invoke"?{code:"effective_invoke"}:{}});if(saved&&"err"in saved)process.stderr.write("indra feedback: local observation was not recorded.\n")}catch{process.stderr.write("indra feedback: local observation failed.\n")}if(options.onCall)try{await options.onCall({id:currentUsageInvocation()?.id??randomUUID(),at:new Date().toISOString(),operation:tool,outcome,success:!!result&&typeof result==="object"&&"ok"in result,durationMs,paramsState:!("params"in args)?"omitted":Array.isArray(args.params)?"array":args.params===null?"null":"invalid",timeoutState:!("timeoutMs"in args)?"omitted":Number.isSafeInteger(args.timeoutMs)&&Number(args.timeoutMs)>=50&&Number(args.timeoutMs)<=(options.sqlTimeoutMaxMs??3e3)?"valid":"invalid"})}catch{process.stderr.write("local cloud: CALL_OBSERVATION_FAILED\n")}}catch{process.stderr.write("indra feedback: terminal observation failed.\n")}}})});return server}export function startMcp(gateway,options={}){return serveStdio(()=>createMcp(gateway,options),{onerror:()=>process.stderr.write("indra MCP request failed.\n")})}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zortexhq/indra-v2.5",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "private": false,
5
5
  "license": "UNLICENSED",
6
6
  "publishConfig": {
@@ -1027,9 +1027,9 @@
1027
1027
  "zortexRelease": {
1028
1028
  "schemaVersion": 1,
1029
1029
  "sourceVersion": "0.2.0",
1030
- "sourceSha": "c3d3356f270d8d066d34a2e681af3afa5fb313a3",
1031
- "sourceDate": "2026-11-20T05:03:05.000Z",
1032
- "version": "0.2.0"
1030
+ "sourceSha": "50417b0e49acbfb971a2538dc82ef3fbbdf81098",
1031
+ "sourceDate": "2026-11-20T06:39:25.000Z",
1032
+ "version": "0.2.1"
1033
1033
  },
1034
1034
  "zortex": {
1035
1035
  "role": "app"
@@ -1040,6 +1040,6 @@
1040
1040
  "zortexUpdate": {
1041
1041
  "schemaVersion": 1,
1042
1042
  "manifest": "update-manifest.json",
1043
- "sha256": "56b44a003b705090f4abd1f76b5fd401ca9154ba6207345d2534d23f388c00be"
1043
+ "sha256": "23e77e89a5d1a7febc501d3ab8257b5792a9d986dc42c43d44162fa7168193ac"
1044
1044
  }
1045
1045
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 3,
3
3
  "name": "@zortexhq/indra-v2.5",
4
- "version": "0.2.0",
4
+ "version": "0.2.1",
5
5
  "platforms": [
6
6
  "win32-x64",
7
7
  "win32-arm64",
@@ -15,16 +15,16 @@
15
15
  "sharp"
16
16
  ]
17
17
  },
18
- "commit": "c3d3356f270d8d066d34a2e681af3afa5fb313a3",
18
+ "commit": "50417b0e49acbfb971a2538dc82ef3fbbdf81098",
19
19
  "lockSha256": "ef1532a71ad1cb969ee98b81d0eb95a053b9a4295c9e647a9721742c46fcf46c",
20
20
  "platform": "linux",
21
21
  "arch": "x64",
22
22
  "zortexRelease": {
23
23
  "schemaVersion": 1,
24
24
  "sourceVersion": "0.2.0",
25
- "sourceSha": "c3d3356f270d8d066d34a2e681af3afa5fb313a3",
26
- "sourceDate": "2026-11-20T05:03:05.000Z",
27
- "version": "0.2.0"
25
+ "sourceSha": "50417b0e49acbfb971a2538dc82ef3fbbdf81098",
26
+ "sourceDate": "2026-11-20T06:39:25.000Z",
27
+ "version": "0.2.1"
28
28
  },
29
29
  "npm": {
30
30
  "externalDependencies": {
@@ -907,10 +907,10 @@
907
907
  "packages": [
908
908
  {
909
909
  "name": "@zortexhq/indra-v2.5",
910
- "version": "0.2.0",
910
+ "version": "0.2.1",
911
911
  "target": "",
912
912
  "fileCount": 130,
913
- "filesSha256": "80d2842dafcd78716b6f284b100c58f20aa7c40d236f020750c2dc4b4dde68b7"
913
+ "filesSha256": "309858189429b0fd251676ba12fd419013170068c95c2e14f4e0d275196caa81"
914
914
  },
915
915
  {
916
916
  "name": "@abd-enterprises/zendesk-mcp",
@@ -2,7 +2,7 @@
2
2
  "schemaVersion": 1,
3
3
  "package": {
4
4
  "name": "@zortexhq/indra-v2.5",
5
- "version": "0.2.0",
5
+ "version": "0.2.1",
6
6
  "private": false,
7
7
  "license": "UNLICENSED",
8
8
  "publishConfig": {
@@ -1029,9 +1029,9 @@
1029
1029
  "zortexRelease": {
1030
1030
  "schemaVersion": 1,
1031
1031
  "sourceVersion": "0.2.0",
1032
- "sourceSha": "c3d3356f270d8d066d34a2e681af3afa5fb313a3",
1033
- "sourceDate": "2026-11-20T05:03:05.000Z",
1034
- "version": "0.2.0"
1032
+ "sourceSha": "50417b0e49acbfb971a2538dc82ef3fbbdf81098",
1033
+ "sourceDate": "2026-11-20T06:39:25.000Z",
1034
+ "version": "0.2.1"
1035
1035
  },
1036
1036
  "zortex": {
1037
1037
  "role": "app"
@@ -1043,7 +1043,7 @@
1043
1043
  "provenance": {
1044
1044
  "schemaVersion": 3,
1045
1045
  "name": "@zortexhq/indra-v2.5",
1046
- "version": "0.2.0",
1046
+ "version": "0.2.1",
1047
1047
  "platforms": [
1048
1048
  "win32-x64",
1049
1049
  "win32-arm64",
@@ -1057,16 +1057,16 @@
1057
1057
  "sharp"
1058
1058
  ]
1059
1059
  },
1060
- "commit": "c3d3356f270d8d066d34a2e681af3afa5fb313a3",
1060
+ "commit": "50417b0e49acbfb971a2538dc82ef3fbbdf81098",
1061
1061
  "lockSha256": "ef1532a71ad1cb969ee98b81d0eb95a053b9a4295c9e647a9721742c46fcf46c",
1062
1062
  "platform": "linux",
1063
1063
  "arch": "x64",
1064
1064
  "zortexRelease": {
1065
1065
  "schemaVersion": 1,
1066
1066
  "sourceVersion": "0.2.0",
1067
- "sourceSha": "c3d3356f270d8d066d34a2e681af3afa5fb313a3",
1068
- "sourceDate": "2026-11-20T05:03:05.000Z",
1069
- "version": "0.2.0"
1067
+ "sourceSha": "50417b0e49acbfb971a2538dc82ef3fbbdf81098",
1068
+ "sourceDate": "2026-11-20T06:39:25.000Z",
1069
+ "version": "0.2.1"
1070
1070
  },
1071
1071
  "npm": {
1072
1072
  "externalDependencies": {
@@ -1949,7 +1949,7 @@
1949
1949
  "packages": [
1950
1950
  {
1951
1951
  "name": "@zortexhq/indra-v2.5",
1952
- "version": "0.2.0",
1952
+ "version": "0.2.1",
1953
1953
  "target": "",
1954
1954
  "fileCount": 130,
1955
1955
  "filesSha256": null
@@ -2399,8 +2399,8 @@
2399
2399
  },
2400
2400
  {
2401
2401
  "path": "dist/auto-update.js",
2402
- "sha256": "ab6230386379f5b948bce3cbc32f85b0512d8d846970dcefb1fda231b1525aa6",
2403
- "size": 20233,
2402
+ "sha256": "5f84a3bbb77cc1cb2c227c0a1137cac465dee74b9d123816e7de299521b53b6e",
2403
+ "size": 21257,
2404
2404
  "mode": 420
2405
2405
  },
2406
2406
  {
@@ -2699,8 +2699,8 @@
2699
2699
  },
2700
2700
  {
2701
2701
  "path": "dist/mcp.js",
2702
- "sha256": "d1b1d2a36f46eefde236ae630ed1059ef5371de19ac9638253f260d0a50d5310",
2703
- "size": 7420,
2702
+ "sha256": "2a920d95e4c40323332ee05faeb35926055ff09f48cfe19c7b35ee8784ab7e2c",
2703
+ "size": 7776,
2704
2704
  "mode": 420
2705
2705
  },
2706
2706
  {