@zortexhq/indra-v2.5 0.3.2 → 0.4.0
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.
- package/README.md +93 -152
- package/dist/auto-update.js +1 -1
- package/dist/bundled-handbook.js +1 -1
- package/dist/cli-run.js +1 -1
- package/dist/cli.js +1 -1
- package/dist/codex-install.js +1 -1
- package/dist/codex-setup.js +1 -1
- package/dist/gateway.js +1 -1
- package/dist/mcp.js +2 -2
- package/dist/onboard-cli.js +1 -0
- package/dist/onboard.js +1 -0
- package/dist/operation-telemetry.js +1 -1
- package/dist/public-tool.js +1 -1
- package/dist/recovery-resident-port.js +1 -0
- package/dist/resident-host.js +2 -2
- package/dist/resident-jobs.js +1 -1
- package/dist/resident-platform.js +3 -3
- package/dist/resident-runtime-identity.js +1 -1
- package/dist/resident-shutdown.js +1 -0
- package/dist/resident-startup-preference.js +1 -0
- package/dist/resident-telemetry.js +1 -1
- package/dist/update-cli.js +1 -1
- package/dist/update-command.js +1 -0
- package/dist/update-handover.js +1 -0
- package/dist/update-recovery.js +1 -1
- package/dist/update-tool.js +1 -1
- package/dist/web.js +1 -1
- package/dist/zortex-cli.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/operational-client.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-graph.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/service-sdk-matrix.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/portrait-producer.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/record-identity.js +6 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/snapshot.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/activity.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/northstar.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/measurement.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-call.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-methods.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/index.js +1 -1
- package/package.json +7 -7
- package/release-provenance.json +16 -16
- package/update-manifest.json +143 -95
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{supportsSavedReconnect}from"./saved-reconnect.js";import{validZendeskSelection}from"./zendesk-selection.js";import{HELP_MANUAL_SOURCES}from"./help-manual-sources.js";import{createPreparedDiscordSource}from"@zortexhq/plugin-connector-level1";import{validateJoplinSelection}from"./joplin-selection.js";import{validZulipSelection}from"./zulip-selection.js";import{validFreshRSSSelection}from"./freshrss-selection.js";import{validMinifluxSelection}from"./miniflux-selection.js";import{validMattermostSelection}from"./mattermost-selection.js";import{validWallabagSelection}from"./wallabag-selection.js";import{validCalcomSelection}from"./calcom-selection.js";import{validWakatimeSelection}from"./wakatime-selection.js";import{validNextcloudInstanceUrl}from"./nextcloud-url.js";import{createHash,randomBytes,timingSafeEqual}from"node:crypto";import{execFile,spawn}from"node:child_process";import{chmod,lstat,mkdir,readFile,realpath,rename,unlink,writeFile}from"node:fs/promises";import{homedir,tmpdir}from"node:os";import{dirname,isAbsolute,join,resolve}from"node:path";import{createConnection,createServer}from"node:net";import{promisify}from"node:util";import{DatabaseSync}from"node:sqlite";import{residentRuntimeIdentity}from"./resident-runtime-identity.js";import{preserveResidentStartupOrigin}from"./installation-origin.js";import{currentOperationalExecution,isOperationalContext,withOperationalContext,withoutOperationalContext}from"@zortexhq/plugin-telemetry/api";import{observeResidentHandlers,traceResidentControl}from"./resident-telemetry.js";const execute=promisify(execFile);const delay=ms=>new Promise(done=>setTimeout(done,ms));export const RESIDENT_IPC_PROTOCOL_VERSION=4;const REQUEST_BYTES=2*1024*1024,RESPONSE_BYTES=4*1024*1024;const RESIDENT_MANAGEMENT=new Set(["plugins","plugin.set-enabled","status","sources","onboarding","startup"]);export function isResidentGatewayRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value,args=request2.args;if(Object.keys(request2).some(key=>key!=="operation"&&key!=="args")||!args||typeof args!=="object"||Array.isArray(args))return false;const fields=args;return request2.operation==="action"&&fields.name==="connector.find"&&Object.keys(fields).every(key=>key==="name"||key==="params")&&!!fields.params&&typeof fields.params==="object"&&!Array.isArray(fields.params)||request2.operation==="actions"||request2.operation==="manage"&&RESIDENT_MANAGEMENT.has(String(fields.what))}function isLocalCloudControlRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value;return request2.action==="grants"&&Object.keys(request2).length===1||request2.action==="revoke"&&Object.keys(request2).length===2&&typeof request2.id==="string"&&/^[a-zA-Z0-9_-]{1,200}$/.test(request2.id)}async function unixEndpoint(hash){const name=`zortex-indra-${hash}.sock`,preferred=join(tmpdir(),name);if(Buffer.byteLength(preferred)<=103)return preferred;const unavailable=()=>Object.assign(new Error("Resident socket path is too long and no safe short system temporary directory is available"),{code:"RESIDENT_SOCKET_PATH_UNAVAILABLE"});try{const directory=await realpath("/tmp"),info=await lstat(directory),endpoint=join(directory,name);if(!info.isDirectory()||info.uid!==0||(info.mode&18)!==0&&(info.mode&512)===0||Buffer.byteLength(endpoint)>103)throw unavailable();return endpoint}catch{throw unavailable()}}async function identity(root){if(!isAbsolute(root))throw new Error("Resident Vault path must be absolute");const canonical=await realpath(root);const key=process.platform==="win32"?canonical.toLowerCase():canonical;const hash=createHash("sha256").update(key).digest("hex").slice(0,24);const directory=join(canonical,"host");return{root:canonical,directory,file:join(directory,"resident.json"),hash,endpoint:process.platform==="win32"?`\\\\.\\pipe\\zortex-indra-${hash}`:await unixEndpoint(hash)}}async function metadata(id){try{const item=JSON.parse(await readFile(id.file,"utf8"));if(item.endpoint!==id.endpoint||!Number.isSafeInteger(item.pid)||item.pid<1||typeof item.nonce!=="string"||!/^[a-f0-9]{64}$/.test(item.nonce)||typeof item.startedAt!=="string")return null;return item}catch{return null}}class ResidentStatusUnavailable extends Error{disconnected;constructor(disconnected){super("Resident status is unavailable; inspect the running host before retrying");this.disconnected=disconnected}}async function request(id,command,timeout=2e3){let item=await metadata(id);if(!item)return null;const deadline=Date.now()+Math.min(timeout,1e3);for(;;){try{return await requestOnce(id,item,command,timeout)}catch(error){if(!(error instanceof ResidentStatusUnavailable)||!error.disconnected||Date.now()>=deadline)throw error;await delay(20);item=await metadata(id)??item}}}function requestOnce(id,item,command,timeout){const operationalContext=currentOperationalExecution();return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="";let settled=false;let connected=false;const finish=(result,error,disconnected=false)=>{if(settled)return;if(result===null&&!error&&connected&&command==="status"){error=new ResidentStatusUnavailable(disconnected)}settled=true;socket.destroy();if(error)reject(error);else done(result)};const incompatible=()=>finish(null,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));socket.setTimeout(timeout,()=>finish(null));socket.on("error",error=>finish(null,!connected&&error.code!=="ENOENT"&&error.code!=="ECONNREFUSED"?error:void 0,true));socket.on("end",()=>finish(null,void 0,true));socket.on("connect",()=>{connected=true;if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();socket.write(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,command,nonce:item.nonce,...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n")});socket.on("data",chunk=>{text+=chunk.toString();if(text.length>65536)return finish(null);if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();finish(typeof value.running==="boolean"?value:null)}catch{finish(null)}})})}export async function residentStatus(root){return await request(await identity(root),"status")??{running:false}}async function residentRpc(root,message,signal){const operationalContext=currentOperationalExecution();const id=await identity(root),item=await metadata(id);if(!item)throw new Error("Resident is not running");return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="",settled=false;const finish=(value,error)=>{if(settled)return;settled=true;signal?.removeEventListener("abort",abort);socket.destroy();if(error)reject(error);else done(value)};const abort=()=>finish(void 0,new Error("Resident request was cancelled"));signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted)return abort();socket.setTimeout(11*6e4,()=>finish(void 0,new Error("Resident request timed out")));socket.on("error",error=>finish(void 0,error));socket.on("end",()=>finish(void 0,new Error("Resident sync ended without a result")));socket.on("connect",()=>{if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return finish(void 0,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));const payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,nonce:item.nonce,...message,...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n";if(Buffer.byteLength(payload)>REQUEST_BYTES)return finish(void 0,new Error("Resident request was too large"));socket.write(payload)});socket.on("data",chunk=>{text+=chunk.toString();if(Buffer.byteLength(text)>RESPONSE_BYTES)return finish(void 0,new Error("Resident response was too large"));if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||!value.result)return finish(void 0,new Error("Resident response was invalid"));finish(value.result)}catch{finish(void 0,new Error("Resident response was invalid"))}})})}export function residentLocalCloudControl(root,request2){if(!isLocalCloudControlRequest(request2))return Promise.reject(new Error("Invalid Local Cloud control request"));return residentRpc(root,{command:"local-cloud-control",request:request2})}export function residentSync(root,source,requestId,options={}){return residentRpc(root,{command:"sync",source,requestId,...options.bindingId?{bindingId:options.bindingId}:{}},options.signal)}export function residentGatewayCall(root,request2,signal){return residentRpc(root,{command:"gateway",request:request2},signal)}export function residentEnsureReady(root,source,signal){return residentRpc(root,{command:"ensure-ready",source},signal)}export function residentCheck(root,source,signal){return residentRpc(root,{command:"check",source},signal)}export function residentRead(root,source,request2={},signal){return residentRpc(root,{command:"read",source,request:request2},signal)}export function residentInvoke(root,request2,signal){return residentRpc(root,{command:"invoke",request:request2},signal)}export function residentConnect(root,source,requestId,signal,settings={automatic:false}){return residentRpc(root,{command:"connect",source,requestId,automatic:settings.automatic,...settings.manualPresentation?{manualPresentation:settings.manualPresentation}:{}},signal)}export function residentConnectJob(root,requestId,signal){return residentRpc(root,{command:"connect-job",requestId},signal)}export function residentPauseConnectionAutomation(root,signal){return residentRpc(root,{command:"pause-connection-automation"},signal)}export function residentResumeBackgroundSync(root,signal){return residentRpc(root,{command:"resume-background-sync"},signal)}export function residentConnectManual(root,source,requestId,signal){return residentRpc(root,{command:"connect-manual",source,requestId},signal)}export function residentReconnectSaved(root,source,signal){return residentRpc(root,{command:"reconnect-saved",source},signal)}export function residentConnectGmailWrite(root,requestId,signal){return residentRpc(root,{command:"connect-gmail-write",requestId},signal)}export function residentConnectReadwiseMcpWrite(root,requestId,signal){return residentRpc(root,{command:"connect-readwise-mcp-write",requestId},signal)}export function residentConnectReauthorize(root,source,requestId,signal){return residentRpc(root,{command:"connect-reauthorize",source,requestId},signal)}export function residentConnectRecovery(root,source,requestId,signal){return residentRpc(root,{command:"connect-recovery",source,requestId},signal)}export function residentConnectAutomatic(root,source,requestId,signal){return residentRpc(root,{command:"connect-automatic",source,requestId},signal)}export function residentConfigureWeChat(root,port,signal){return residentRpc(root,{command:"configure-wechat",port},signal)}export async function residentConfigureJoplin(root,selection,signal){validateJoplinSelection(selection);return residentRpc(root,{command:"configure-joplin",selection},signal)}export function residentConfigureThunderbird(root,port,signal){return residentRpc(root,{command:"configure-thunderbird",port},signal)}export function residentConfigureDiscord(root,selection,signal){return residentRpc(root,{command:"configure-discord",selection},signal)}export function residentConfigureProtonMail(root,port,signal){return residentRpc(root,{command:"configure-proton-mail",port},signal)}export function residentConfigureZulip(root,selection,signal){return residentRpc(root,{command:"configure-zulip",selection},signal)}export function residentConfigureFreshRSS(root,selection,signal){return residentRpc(root,{command:"configure-freshrss",selection},signal)}export function residentConfigureMiniflux(root,selection,signal){return residentRpc(root,{command:"configure-miniflux",selection},signal)}export function residentConfigureMattermost(root,selection,signal){return residentRpc(root,{command:"configure-mattermost",selection},signal)}export function residentConfigureWallabag(root,selection,signal){return residentRpc(root,{command:"configure-wallabag",selection},signal)}export function residentConfigureCalcom(root,selection,signal){return residentRpc(root,{command:"configure-calcom",selection},signal)}export function residentConfigureWakatime(root,selection,signal){return residentRpc(root,{command:"configure-wakatime",selection},signal)}export function residentConfigureNextcloud(root,instanceUrl,signal){return residentRpc(root,{command:"configure-nextcloud",instanceUrl},signal)}export function residentConfigureDropbox(root,selection,signal){return residentRpc(root,{command:"configure-dropbox",selection},signal)}export function residentConfigureBox(root,selection,signal){return residentRpc(root,{command:"configure-box",selection},signal)}export function residentConfigureFront(root,selection,signal){return residentRpc(root,{command:"configure-front",selection},signal)}export function residentConfigureHubSpot(root,selection,signal){return residentRpc(root,{command:"configure-hubspot",selection},signal)}export function residentConfigureGoogleContacts(root,selection,signal){return residentRpc(root,{command:"configure-google-contacts",selection},signal)}export function residentConfigureGoogleChat(root,selection,signal){return residentRpc(root,{command:"configure-google-chat",selection},signal)}export function residentConfigureSalesforce(root,selection,signal){return residentRpc(root,{command:"configure-salesforce",selection},signal)}export function residentConfigureZendesk(root,selection,signal){return residentRpc(root,{command:"configure-zendesk",selection},signal)}export function residentConfigureZoom(root,selection,signal){return residentRpc(root,{command:"configure-zoom",selection},signal)}export function residentConfigureSmartsheet(root,region,signal){return residentRpc(root,{command:"configure-smartsheet",region},signal)}export function residentConfigureFigma(root,mode,signal){return residentRpc(root,{command:"configure-figma",mode},signal)}export function residentConfigureFreshdesk(root,subdomain,signal){return residentRpc(root,{command:"configure-freshdesk",subdomain},signal)}export function residentConfigureCopyQ(root,executable,session,signal){return residentRpc(root,{command:"configure-copyq",executable,session},signal)}export function residentConfigureOwnTracks(root,port,signal){return residentRpc(root,{command:"configure-owntracks",port},signal)}export function residentConfigureZotero(root,libraryId,libraryType,signal){return residentRpc(root,{command:"configure-zotero",libraryId,libraryType},signal)}export function residentConfigureNativeFiles(root,source,roots,signal){return residentRpc(root,{command:"configure-native-files",source,roots},signal)}export function residentConnectorStatus(root,signal){return residentRpc(root,{command:"connector-status"},signal)}export function residentConnectorCheck(root,source,signal){return residentRpc(root,{command:"connector-check",source},signal)}export function residentConnectorRead(root,source,signal){return residentRpc(root,{command:"connector-read",source},signal)}export function residentCancelConnect(root,requestId,generation,challengeRef){if(!Number.isSafeInteger(generation)||generation<0||!challengeRef)return Promise.resolve({err:{code:"stale_job_generation"}});return residentRpc(root,{command:"connect-cancel",requestId,generation,challengeRef})}function listen(server,endpoint){return new Promise((done,reject)=>{const fail=error=>{server.off("listening",ready);reject(error)};const ready=()=>{server.off("error",fail);done()};server.once("error",fail);server.once("listening",ready);server.listen(endpoint)})}function unixOwnership(id){const lock=new DatabaseSync(join(id.directory,"resident-owner.sqlite"),{allowExtension:false,timeout:0});try{lock.exec("BEGIN EXCLUSIVE");return lock}catch(error){lock.close();if(error.errcode===5)return null;throw error}}async function recoverUnixEndpoint(endpoint){let before;try{before=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!before.isSocket())return false;const refused=await new Promise(done=>{const socket=createConnection(endpoint);let settled=false;const finish=value=>{if(!settled){settled=true;socket.destroy();done(value)}};socket.once("connect",()=>finish(false));socket.once("error",error=>finish(error.code==="ECONNREFUSED"));socket.setTimeout(2e3,()=>finish(false))});if(!refused)return false;let after;try{after=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!after.isSocket()||after.dev!==before.dev||after.ino!==before.ino)return false;await unlink(endpoint);return true}export async function runResidentServer(root,onStop,status=()=>({}),handlers={}){handlers=observeResidentHandlers(handlers);const id=await identity(root);await mkdir(id.directory,{recursive:true,mode:448});const ownership=process.platform==="win32"?void 0:unixOwnership(id);if(ownership===null)return null;const item={protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,operationalContextVersion:1,pid:process.pid,nonce:randomBytes(32).toString("hex"),endpoint:id.endpoint,startedAt:new Date().toISOString()};const runtime=await residentRuntimeIdentity();const sockets=new Set;let stopping;let closing;const server=createServer(socket=>{socket.setEncoding("utf8");const reply=result=>{if(socket.destroyed)return;let payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n";if(Buffer.byteLength(payload)>RESPONSE_BYTES)payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result:{err:{code:"resource_exhausted",message:"The source result exceeds the resident response limit."}}})+"\n";socket.end(payload)};const disconnected=new AbortController;sockets.add(socket);socket.on("close",()=>{sockets.delete(socket);disconnected.abort()});socket.on("error",()=>{});socket.setTimeout(2e3,()=>socket.destroy());let input="";let handled=false;socket.on("data",chunk=>{if(handled)return;input+=chunk.toString();if(Buffer.byteLength(input)>REQUEST_BYTES){handled=true;socket.destroy();return}if(!input.includes("\n"))return;handled=true;void(async()=>{try{const envelope=JSON.parse(input.split("\n")[0]);if(envelope.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||typeof envelope.nonce!=="string"||envelope.nonce.length!==item.nonce.length||!timingSafeEqual(Buffer.from(envelope.nonce),Buffer.from(item.nonce))){socket.destroy();return}const{operationalContext,...message}=envelope;if(operationalContext!==void 0&&!isOperationalContext(operationalContext)){socket.destroy();return}async function configureSelection(valid,configure){if(!configure||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!valid(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await configure(message.selection))}const dispatch=async()=>{if((stopping||closing)&&message.command!=="status"&&message.command!=="stop"){reply({err:{code:"unavailable",message:"The background host is stopping."}});return}if(message.command==="status"){const{nonce:_nonce,endpoint:_endpoint,...safe}=traceResidentControl(handlers.telemetry,{phase:"runtime",action:"status",operationId:"resident.status"},status,{plainResult:true});socket.end(JSON.stringify({...safe,runtime,protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:!stopping,pid:item.pid,startedAt:item.startedAt})+"\n")}else if(message.command==="sync"){if(!handlers.sync||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||message.bindingId!==void 0&&(typeof message.bindingId!=="string"||!message.bindingId||message.bindingId.length>200)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.sync(message.source,message.requestId,{signal:disconnected.signal,...message.bindingId?{bindingId:message.bindingId}:{}});reply(result)}else if(message.command==="local-cloud-control"){if(!isLocalCloudControlRequest(message.request)){socket.destroy();return}if(!handlers.localCloud){reply({err:{code:"unavailable",message:"This resident does not provide Local Cloud authorization controls."}});return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.localCloud(message.request))}else if(message.command==="gateway"){if(!handlers.gateway||!isResidentGatewayRequest(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.gateway(message.request,disconnected.signal))}else if(message.command==="ensure-ready"){if(!handlers.ensureReady||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());reply(await handlers.ensureReady(message.source,disconnected.signal))}else if(message.command==="check"){if(!handlers.check||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.check(message.source,disconnected.signal))}else if(message.command==="read"){if(!handlers.read||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||!message.request||typeof message.request!=="object"||Array.isArray(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());const result=await handlers.read(message.source,message.request,disconnected.signal);reply(result)}else if(message.command==="invoke"){const request2=message.request;if(!handlers.invoke||!request2||typeof request2!=="object"||Array.isArray(request2)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());const result=await handlers.invoke(request2,disconnected.signal);reply(result)}else if(message.command==="connect"){if(!handlers.connect||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||typeof message.automatic!=="boolean"){socket.destroy();return}const manualPresentation=message.manualPresentation==="return-url"?"return-url":message.manualPresentation==="open"?"open":void 0;socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connect(message.source,message.requestId,disconnected.signal,{automatic:message.automatic,...manualPresentation?{manualPresentation}:{}});reply(result)}else if(message.command==="connect-manual"){if(!handlers.connectManual||typeof message.source!=="string"||!HELP_MANUAL_SOURCES.has(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectManual(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="reconnect-saved"){if(!handlers.reconnectSaved||typeof message.source!=="string"||!supportsSavedReconnect(message.source)||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source"].includes(key))){socket.destroy();return}socket.setTimeout(9e4,()=>socket.destroy());const result=await handlers.reconnectSaved(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-gmail-write"){if(!handlers.connectGmailWrite||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectGmailWrite(message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-readwise-mcp-write"){if(!handlers.connectReadwiseMcpWrite||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectReadwiseMcpWrite(message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-reauthorize"){if(!handlers.connectReauthorize||typeof message.source!=="string"||!["todoist","linear"].includes(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectReauthorize(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-recovery"){if(!handlers.connectRecovery||typeof message.source!=="string"||!["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectRecovery(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-automatic"){if(!handlers.connectAutomatic||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectAutomatic(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-job"){if(!handlers.connectJob||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150){socket.destroy();return}const result=await handlers.connectJob(message.requestId);reply(result)}else if(message.command==="connect-cancel"){if(!handlers.cancelConnect||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||!Number.isSafeInteger(message.generation)||message.generation<0||typeof message.challengeRef!=="string"||!message.challengeRef||message.challengeRef.length>200){socket.destroy();return}const result=await handlers.cancelConnect(message.requestId,message.generation,message.challengeRef);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-wechat"){if(!handlers.configureWeChat||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureWeChat({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-joplin"){if(!handlers.configureJoplin||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))){socket.destroy();return}try{validateJoplinSelection(message.selection)}catch{socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureJoplin(message.selection,disconnected.signal);reply(result)}else if(message.command==="configure-thunderbird"){if(!handlers.configureThunderbird||Object.keys(message).some(key=>!["protocolVersion","nonce","command","port"].includes(key))||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureThunderbird({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-discord"){if(!handlers.configureDiscord||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))){socket.destroy();return}try{const selection=message.selection;if(!selection||typeof selection!=="object"||Array.isArray(selection)||Reflect.ownKeys(selection).some(key=>typeof key!=="string"||!["clientId","expectedSubject","ipcPath","channelIds"].includes(key)))throw Error("invalid");createPreparedDiscordSource("discord",{mode:"fields",...selection})}catch{socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureDiscord(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-proton-mail"){if(!handlers.configureProtonMail||Object.keys(message).some(key=>!["protocolVersion","nonce","command","port"].includes(key))||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureProtonMail({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zulip"){await configureSelection(validZulipSelection,handlers.configureZulip?.bind(handlers))}else if(message.command==="configure-freshrss"){await configureSelection(validFreshRSSSelection,handlers.configureFreshRSS?.bind(handlers))}else if(message.command==="configure-miniflux"){await configureSelection(validMinifluxSelection,handlers.configureMiniflux?.bind(handlers))}else if(message.command==="configure-mattermost"){await configureSelection(validMattermostSelection,handlers.configureMattermost?.bind(handlers))}else if(message.command==="configure-wallabag"){await configureSelection(validWallabagSelection,handlers.configureWallabag?.bind(handlers))}else if(message.command==="configure-calcom"){await configureSelection(validCalcomSelection,handlers.configureCalcom?.bind(handlers))}else if(message.command==="configure-wakatime"){await configureSelection(validWakatimeSelection,handlers.configureWakatime?.bind(handlers))}else if(message.command==="configure-nextcloud"){if(!handlers.configureNextcloud||Object.keys(message).some(key=>!["protocolVersion","nonce","command","instanceUrl"].includes(key))||!validNextcloudInstanceUrl(message.instanceUrl)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureNextcloud({instanceUrl:message.instanceUrl});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-dropbox"){const selection=message.selection;if(!handlers.configureDropbox||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureDropbox({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-box"){const selection=message.selection;if(!handlers.configureBox||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureBox({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-front"){const selection=message.selection;if(!handlers.configureFront||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFront({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-hubspot"){const selection=message.selection;if(!handlers.configureHubSpot||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureHubSpot({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-google-contacts"){const selection=message.selection;if(!handlers.configureGoogleContacts||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length<2||Object.keys(selection).length>3||Object.keys(selection).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key))||selection.developerPreview!==void 0&&typeof selection.developerPreview!=="boolean"||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureGoogleContacts({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-google-chat"){const selection=message.selection;if(!handlers.configureGoogleChat||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length<2||Object.keys(selection).length>3||Object.keys(selection).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key))||selection.developerPreview!==void 0&&typeof selection.developerPreview!=="boolean"||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureGoogleChat({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-salesforce"){const selection=message.selection;if(!handlers.configureSalesforce||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==3||Object.keys(selection).some(key=>!["environment","clientId","loopbackPort"].includes(key))||!["production","sandbox"].includes(selection.environment)||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureSalesforce({environment:selection.environment,clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zendesk"){const selection=message.selection;if(!handlers.configureZendesk||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validZendeskSelection(selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZendesk({subdomain:selection.subdomain,clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zoom"){const selection=message.selection;if(!handlers.configureZoom||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==1||Object.keys(selection).some(key=>key!=="clientId")||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZoom({clientId:selection.clientId});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-smartsheet"){if(!handlers.configureSmartsheet||Object.keys(message).some(key=>!["protocolVersion","nonce","command","region"].includes(key))||!["us","eu","au"].includes(message.region)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureSmartsheet({region:message.region});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-figma"){if(!handlers.configureFigma||Object.keys(message).some(key=>!["protocolVersion","nonce","command","mode"].includes(key))||!["fields","oauth"].includes(message.mode)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFigma(message.mode);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-freshdesk"){if(!handlers.configureFreshdesk||Object.keys(message).some(key=>!["protocolVersion","nonce","command","subdomain"].includes(key))||typeof message.subdomain!=="string"||message.subdomain.length>63||!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(message.subdomain)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFreshdesk({subdomain:message.subdomain});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-copyq"){if(!handlers.configureCopyQ||typeof message.executable!=="string"||message.executable.length<1||message.executable.length>512||typeof message.session!=="string"||!/^[\p{L}\p{N}_-]{0,16}$/u.test(message.session)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureCopyQ({executable:message.executable,session:message.session});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-owntracks"){if(!handlers.configureOwnTracks||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureOwnTracks({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zotero"){if(!handlers.configureZotero||typeof message.libraryId!=="string"||!["user","group"].includes(message.libraryType)||!/^[1-9][0-9]{0,19}$/.test(message.libraryId)&&!(message.libraryType==="user"&&message.libraryId==="0")){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZotero({libraryId:message.libraryId,libraryType:message.libraryType});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-native-files"){const sources=["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","local-audio","obsidian","logseq","computer-files"];if(!handlers.configureNativeFiles||!sources.includes(message.source)||!Array.isArray(message.roots)||message.roots.length<1||message.roots.length>16||!message.roots.every(root2=>typeof root2==="string"&&root2.length>0&&root2.length<=4096)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureNativeFiles({source:message.source,roots:message.roots});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-status"){if(!handlers.connectorStatus){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorStatus();if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-check"){if(!handlers.connectorCheck||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorCheck(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-read"){if(!handlers.connectorRead||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorRead(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="pause-connection-automation"){if(!handlers.pauseAutomation||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.pauseAutomation())}else if(message.command==="resume-background-sync"){if(!handlers.resumeBackgroundSync||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.resumeBackgroundSync())}else if(message.command==="stop"){socket.setTimeout(3e4,()=>socket.destroy());stopping??=Promise.resolve().then(()=>traceResidentControl(handlers.telemetry,{phase:"runtime",action:"cleanup",operationId:"resident.stop"},onStop,{plainResult:true}));try{await stopping}catch{stopping=void 0;socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,error:"resident_cleanup_failed"})+"\n");return}socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:false,stopped:true})+"\n");void close()}else socket.destroy()};if(operationalContext)await withOperationalContext(operationalContext,dispatch);else await withoutOperationalContext(dispatch)}catch{socket.destroy()}})()})});const close=()=>closing??=(async()=>{try{const closed=new Promise(done=>server.close(()=>done()));for(const socket of sockets)socket.end();await closed;if((await metadata(id))?.nonce===item.nonce)await unlink(id.file).catch(()=>{})}finally{ownership?.close()}})();try{try{await listen(server,id.endpoint)}catch(error){if(error.code!=="EADDRINUSE")throw error;if(process.platform==="win32"||!await recoverUnixEndpoint(id.endpoint)){await close();return null}try{await listen(server,id.endpoint)}catch(retryError){if(retryError.code!=="EADDRINUSE")throw retryError;await close();return null}}if(process.platform!=="win32")await chmod(id.endpoint,384);const temporary=`${id.file}.${item.nonce}.tmp`;try{await writeFile(temporary,JSON.stringify(item),{mode:384,flag:"wx"});await rename(temporary,id.file)}finally{await unlink(temporary).catch(()=>{})}}catch(error){await close();throw error}return{close}}function windowsQuote(value){return'"'+value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/g,"$1$1")+'"'}const xml=value=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'");export function residentStartupPlan(root,entrypoint,hash,platform=process.platform,executable=process.execPath,home=homedir(),environment=process.env){if(![root,entrypoint,executable].every(isAbsolute))throw new Error("Resident startup paths must be absolute");if(![root,entrypoint,executable].every(value=>!/[\r\n\0]/.test(value)))throw new Error("Invalid resident startup path");if(!/^[a-f0-9]{24}$/.test(hash))throw new Error("Invalid resident identity");const syncDisabled=/^(0|false|off|no)$/i.test((environment.ZORTEX_AUTO_SYNC??"").trim());const args=[entrypoint,"--root",root,"host","run",...syncDisabled?["--sync-disabled"]:[]];const command=[executable,...args].map(windowsQuote).join(" ");const launcherPath=join(root,"host","resident-startup.vbs");const launcher=`Option Explicit\r
|
|
1
|
+
import{supportsSavedReconnect}from"./saved-reconnect.js";import{validZendeskSelection}from"./zendesk-selection.js";import{HELP_MANUAL_SOURCES}from"./help-manual-sources.js";import{createPreparedDiscordSource}from"@zortexhq/plugin-connector-level1";import{validateJoplinSelection}from"./joplin-selection.js";import{validZulipSelection}from"./zulip-selection.js";import{validFreshRSSSelection}from"./freshrss-selection.js";import{validMinifluxSelection}from"./miniflux-selection.js";import{validMattermostSelection}from"./mattermost-selection.js";import{validWallabagSelection}from"./wallabag-selection.js";import{validCalcomSelection}from"./calcom-selection.js";import{validWakatimeSelection}from"./wakatime-selection.js";import{validNextcloudInstanceUrl}from"./nextcloud-url.js";import{createHash,randomBytes,timingSafeEqual}from"node:crypto";import{execFile,spawn}from"node:child_process";import{chmod,lstat,mkdir,readFile,realpath,rename,unlink,writeFile}from"node:fs/promises";import{homedir,tmpdir}from"node:os";import{dirname,isAbsolute,join,resolve}from"node:path";import{createConnection,createServer}from"node:net";import{promisify}from"node:util";import{DatabaseSync}from"node:sqlite";import{residentRuntimeIdentity,residentRuntimePolicy}from"./resident-runtime-identity.js";import{residentStartupDisabled,setResidentStartupDisabled}from"./resident-startup-preference.js";import{createUpdateRecovery,installedStartupVersion}from"./update-recovery.js";import{markResidentInterruption,residentInterruption}from"./update-handover.js";import{RESIDENT_STOP_TIMEOUT_MS}from"./resident-shutdown.js";import{preserveResidentStartupOrigin}from"./installation-origin.js";import{currentOperationalExecution,isOperationalContext,withOperationalContext,withoutOperationalContext}from"@zortexhq/plugin-telemetry/api";import{observeResidentHandlers,traceResidentControl}from"./resident-telemetry.js";const execute=promisify(execFile);const loadedRuntime=residentRuntimeIdentity().then(current=>{const version=installedStartupVersion();return version&&version!==current.version?{installationPath:current.installationPath,policy:current.policy,version}:current});const installationRecovery=createUpdateRecovery();const delay=ms=>new Promise(done=>setTimeout(done,ms));export const RESIDENT_IPC_PROTOCOL_VERSION=4;const REQUEST_BYTES=2*1024*1024,RESPONSE_BYTES=4*1024*1024;const RESIDENT_MANAGEMENT=new Set(["plugins","plugin.set-enabled","status","sources","onboarding","startup"]);export function isResidentGatewayRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value,args=request2.args;if(Object.keys(request2).some(key=>key!=="operation"&&key!=="args")||!args||typeof args!=="object"||Array.isArray(args))return false;const fields=args;return request2.operation==="action"&&fields.name==="connector.find"&&Object.keys(fields).every(key=>key==="name"||key==="params")&&!!fields.params&&typeof fields.params==="object"&&!Array.isArray(fields.params)||request2.operation==="actions"||request2.operation==="manage"&&RESIDENT_MANAGEMENT.has(String(fields.what))}function validUpdateOwner(value){if(!value||typeof value!=="object")return false;const owner=value;return Number.isSafeInteger(owner.pid)&&owner.pid>0&&typeof owner.startedAt==="string"&&owner.startedAt.length<100&&!!owner.runtime&&typeof owner.runtime.installationPath==="string"&&isAbsolute(owner.runtime.installationPath)&&typeof owner.runtime.version==="string"&&/^[0-9A-Za-z.+-]{1,80}$/.test(owner.runtime.version)}function isLocalCloudControlRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value;return request2.action==="grants"&&Object.keys(request2).length===1||request2.action==="revoke"&&Object.keys(request2).length===2&&typeof request2.id==="string"&&/^[a-zA-Z0-9_-]{1,200}$/.test(request2.id)}async function unixEndpoint(hash){const name=`zortex-indra-${hash}.sock`,preferred=join(tmpdir(),name);if(Buffer.byteLength(preferred)<=103)return preferred;const unavailable=()=>Object.assign(new Error("Resident socket path is too long and no safe short system temporary directory is available"),{code:"RESIDENT_SOCKET_PATH_UNAVAILABLE"});try{const directory=await realpath("/tmp"),info=await lstat(directory),endpoint=join(directory,name);if(!info.isDirectory()||info.uid!==0||(info.mode&18)!==0&&(info.mode&512)===0||Buffer.byteLength(endpoint)>103)throw unavailable();return endpoint}catch{throw unavailable()}}async function identity(root){if(!isAbsolute(root))throw new Error("Resident Vault path must be absolute");const canonical=await realpath(root);const key=process.platform==="win32"?canonical.toLowerCase():canonical;const hash=createHash("sha256").update(key).digest("hex").slice(0,24);const directory=join(canonical,"host");return{root:canonical,directory,file:join(directory,"resident.json"),hash,endpoint:process.platform==="win32"?`\\\\.\\pipe\\zortex-indra-${hash}`:await unixEndpoint(hash)}}async function metadata(id){try{const item=JSON.parse(await readFile(id.file,"utf8"));if(item.endpoint!==id.endpoint||!Number.isSafeInteger(item.pid)||item.pid<1||typeof item.nonce!=="string"||!/^[a-f0-9]{64}$/.test(item.nonce)||typeof item.startedAt!=="string")return null;return item}catch{return null}}class ResidentStatusUnavailable extends Error{disconnected;constructor(disconnected){super("Resident status is unavailable; inspect the running host before retrying");this.disconnected=disconnected}}async function request(id,command,timeout=2e3,guard){let item=await metadata(id);if(!item)return null;const deadline=Date.now()+Math.min(timeout,1e3);for(;;){if(guard&&(item.pid!==guard.pid||item.startedAt!==guard.startedAt))return{running:true,deferred:true,reason:"resident_changed"};try{return await requestOnce(id,item,command,timeout,guard)}catch(error){if(!(error instanceof ResidentStatusUnavailable)||!error.disconnected||Date.now()>=deadline)throw error;await delay(20);item=await metadata(id)??item}}}function requestOnce(id,item,command,timeout,guard){const operationalContext=currentOperationalExecution();return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="";let settled=false;let connected=false;const finish=(result,error,disconnected=false)=>{if(settled)return;if(result===null&&!error&&connected&&command==="status"){error=new ResidentStatusUnavailable(disconnected)}settled=true;socket.destroy();if(error)reject(error);else done(result)};const incompatible=()=>finish(null,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));socket.setTimeout(timeout,()=>finish(null));socket.on("error",error=>finish(null,!connected&&error.code!=="ENOENT"&&error.code!=="ECONNREFUSED"?error:void 0,true));socket.on("end",()=>finish(null,void 0,true));socket.on("connect",()=>{connected=true;if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();socket.write(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,command,nonce:item.nonce,...guard?{guard}:{},...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n")});socket.on("data",chunk=>{text+=chunk.toString();if(text.length>65536)return finish(null);if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();finish(typeof value.running==="boolean"?value:null)}catch{finish(null)}})})}export async function residentStatus(root){return await request(await identity(root),"status")??{running:false}}async function residentRpc(root,message,signal){const operationalContext=currentOperationalExecution();const id=await identity(root),item=await metadata(id);if(!item)throw new Error("Resident is not running");return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="",settled=false;const finish=(value,error)=>{if(settled)return;settled=true;signal?.removeEventListener("abort",abort);socket.destroy();if(error)reject(error);else done(value)};const abort=()=>finish(void 0,new Error("Resident request was cancelled"));signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted)return abort();socket.setTimeout(11*6e4,()=>finish(void 0,new Error("Resident request timed out")));socket.on("error",error=>finish(void 0,error));socket.on("end",()=>finish(void 0,new Error("Resident sync ended without a result")));socket.on("connect",()=>{if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return finish(void 0,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));const payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,nonce:item.nonce,...message,...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n";if(Buffer.byteLength(payload)>REQUEST_BYTES)return finish(void 0,new Error("Resident request was too large"));socket.write(payload)});socket.on("data",chunk=>{text+=chunk.toString();if(Buffer.byteLength(text)>RESPONSE_BYTES)return finish(void 0,new Error("Resident response was too large"));if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||!value.result)return finish(void 0,new Error("Resident response was invalid"));finish(value.result)}catch{finish(void 0,new Error("Resident response was invalid"))}})})}export function residentLocalCloudControl(root,request2){if(!isLocalCloudControlRequest(request2))return Promise.reject(new Error("Invalid Local Cloud control request"));return residentRpc(root,{command:"local-cloud-control",request:request2})}export function residentSync(root,source,requestId,options={}){return residentRpc(root,{command:"sync",source,requestId,...options.bindingId?{bindingId:options.bindingId}:{}},options.signal)}export function residentGatewayCall(root,request2,signal){return residentRpc(root,{command:"gateway",request:request2},signal)}export function residentEnsureReady(root,source,signal){return residentRpc(root,{command:"ensure-ready",source},signal)}export function residentCheck(root,source,signal){return residentRpc(root,{command:"check",source},signal)}export function residentRead(root,source,request2={},signal){return residentRpc(root,{command:"read",source,request:request2},signal)}export function residentInvoke(root,request2,signal){return residentRpc(root,{command:"invoke",request:request2},signal)}export function residentConnect(root,source,requestId,signal,settings={automatic:false}){return residentRpc(root,{command:"connect",source,requestId,automatic:settings.automatic,...settings.manualPresentation?{manualPresentation:settings.manualPresentation}:{}},signal)}export function residentConnectJob(root,requestId,signal){return residentRpc(root,{command:"connect-job",requestId},signal)}export function residentOnboard(root,signal){return residentRpc(root,{command:"onboard"},signal)}export async function residentPauseConnectionAutomation(root,signal){await markResidentInterruption(root,"pause");return residentRpc(root,{command:"pause-connection-automation"},signal)}export function residentResumeBackgroundSync(root,signal){return residentRpc(root,{command:"resume-background-sync"},signal)}export function residentConnectManual(root,source,requestId,signal){return residentRpc(root,{command:"connect-manual",source,requestId},signal)}export function residentReconnectSaved(root,source,signal){return residentRpc(root,{command:"reconnect-saved",source},signal)}export function residentConnectGmailWrite(root,requestId,signal){return residentRpc(root,{command:"connect-gmail-write",requestId},signal)}export function residentConnectReadwiseMcpWrite(root,requestId,signal){return residentRpc(root,{command:"connect-readwise-mcp-write",requestId},signal)}export function residentConnectReauthorize(root,source,requestId,signal){return residentRpc(root,{command:"connect-reauthorize",source,requestId},signal)}export function residentConnectRecovery(root,source,requestId,signal){return residentRpc(root,{command:"connect-recovery",source,requestId},signal)}export function residentConnectAutomatic(root,source,requestId,signal){return residentRpc(root,{command:"connect-automatic",source,requestId},signal)}export function residentConfigureWeChat(root,port,signal){return residentRpc(root,{command:"configure-wechat",port},signal)}export async function residentConfigureJoplin(root,selection,signal){validateJoplinSelection(selection);return residentRpc(root,{command:"configure-joplin",selection},signal)}export function residentConfigureThunderbird(root,port,signal){return residentRpc(root,{command:"configure-thunderbird",port},signal)}export function residentConfigureDiscord(root,selection,signal){return residentRpc(root,{command:"configure-discord",selection},signal)}export function residentConfigureProtonMail(root,port,signal){return residentRpc(root,{command:"configure-proton-mail",port},signal)}export function residentConfigureZulip(root,selection,signal){return residentRpc(root,{command:"configure-zulip",selection},signal)}export function residentConfigureFreshRSS(root,selection,signal){return residentRpc(root,{command:"configure-freshrss",selection},signal)}export function residentConfigureMiniflux(root,selection,signal){return residentRpc(root,{command:"configure-miniflux",selection},signal)}export function residentConfigureMattermost(root,selection,signal){return residentRpc(root,{command:"configure-mattermost",selection},signal)}export function residentConfigureWallabag(root,selection,signal){return residentRpc(root,{command:"configure-wallabag",selection},signal)}export function residentConfigureCalcom(root,selection,signal){return residentRpc(root,{command:"configure-calcom",selection},signal)}export function residentConfigureWakatime(root,selection,signal){return residentRpc(root,{command:"configure-wakatime",selection},signal)}export function residentConfigureNextcloud(root,instanceUrl,signal){return residentRpc(root,{command:"configure-nextcloud",instanceUrl},signal)}export function residentConfigureDropbox(root,selection,signal){return residentRpc(root,{command:"configure-dropbox",selection},signal)}export function residentConfigureBox(root,selection,signal){return residentRpc(root,{command:"configure-box",selection},signal)}export function residentConfigureFront(root,selection,signal){return residentRpc(root,{command:"configure-front",selection},signal)}export function residentConfigureHubSpot(root,selection,signal){return residentRpc(root,{command:"configure-hubspot",selection},signal)}export function residentConfigureGoogleContacts(root,selection,signal){return residentRpc(root,{command:"configure-google-contacts",selection},signal)}export function residentConfigureGoogleChat(root,selection,signal){return residentRpc(root,{command:"configure-google-chat",selection},signal)}export function residentConfigureSalesforce(root,selection,signal){return residentRpc(root,{command:"configure-salesforce",selection},signal)}export function residentConfigureZendesk(root,selection,signal){return residentRpc(root,{command:"configure-zendesk",selection},signal)}export function residentConfigureZoom(root,selection,signal){return residentRpc(root,{command:"configure-zoom",selection},signal)}export function residentConfigureSmartsheet(root,region,signal){return residentRpc(root,{command:"configure-smartsheet",region},signal)}export function residentConfigureFigma(root,mode,signal){return residentRpc(root,{command:"configure-figma",mode},signal)}export function residentConfigureFreshdesk(root,subdomain,signal){return residentRpc(root,{command:"configure-freshdesk",subdomain},signal)}export function residentConfigureCopyQ(root,executable,session,signal){return residentRpc(root,{command:"configure-copyq",executable,session},signal)}export function residentConfigureOwnTracks(root,port,signal){return residentRpc(root,{command:"configure-owntracks",port},signal)}export function residentConfigureZotero(root,libraryId,libraryType,signal){return residentRpc(root,{command:"configure-zotero",libraryId,libraryType},signal)}export function residentConfigureNativeFiles(root,source,roots,signal){return residentRpc(root,{command:"configure-native-files",source,roots},signal)}export function residentConnectorStatus(root,signal){return residentRpc(root,{command:"connector-status"},signal)}export function residentConnectorCheck(root,source,signal){return residentRpc(root,{command:"connector-check",source},signal)}export function residentConnectorRead(root,source,signal){return residentRpc(root,{command:"connector-read",source},signal)}export function residentCancelConnect(root,requestId,generation,challengeRef){if(!Number.isSafeInteger(generation)||generation<0||!challengeRef)return Promise.resolve({err:{code:"stale_job_generation"}});return residentRpc(root,{command:"connect-cancel",requestId,generation,challengeRef})}function listen(server,endpoint){return new Promise((done,reject)=>{const fail=error=>{server.off("listening",ready);reject(error)};const ready=()=>{server.off("error",fail);done()};server.once("error",fail);server.once("listening",ready);server.listen(endpoint)})}function unixOwnership(id){const lock=new DatabaseSync(join(id.directory,"resident-owner.sqlite"),{allowExtension:false,timeout:0});try{lock.exec("BEGIN EXCLUSIVE");return lock}catch(error){lock.close();if(error.errcode===5)return null;throw error}}async function recoverUnixEndpoint(endpoint){let before;try{before=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!before.isSocket())return false;const refused=await new Promise(done=>{const socket=createConnection(endpoint);let settled=false;const finish=value=>{if(!settled){settled=true;socket.destroy();done(value)}};socket.once("connect",()=>finish(false));socket.once("error",error=>finish(error.code==="ECONNREFUSED"));socket.setTimeout(2e3,()=>finish(false))});if(!refused)return false;let after;try{after=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!after.isSocket()||after.dev!==before.dev||after.ino!==before.ino)return false;await unlink(endpoint);return true}export async function runResidentServer(root,onStop,status=()=>({}),handlers={}){handlers=observeResidentHandlers(handlers);const id=await identity(root);await mkdir(id.directory,{recursive:true,mode:448});let ownership;const item={protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,operationalContextVersion:1,pid:process.pid,nonce:randomBytes(32).toString("hex"),endpoint:id.endpoint,startedAt:new Date().toISOString()};const runtime={...await loadedRuntime,policy:residentRuntimePolicy()};const sockets=new Set;let activeRequests=0;let stopping;let closing;const server=createServer(socket=>{socket.setEncoding("utf8");const reply=result=>{if(socket.destroyed)return;let payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n";if(Buffer.byteLength(payload)>RESPONSE_BYTES)payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result:{err:{code:"resource_exhausted",message:"The source result exceeds the resident response limit."}}})+"\n";socket.end(payload)};const disconnected=new AbortController;sockets.add(socket);socket.on("close",()=>{sockets.delete(socket);disconnected.abort()});socket.on("error",()=>{});socket.setTimeout(2e3,()=>socket.destroy());let input="";let handled=false;socket.on("data",chunk=>{if(handled)return;input+=chunk.toString();if(Buffer.byteLength(input)>REQUEST_BYTES){handled=true;socket.destroy();return}if(!input.includes("\n"))return;handled=true;void(async()=>{let active=false;try{const envelope=JSON.parse(input.split("\n")[0]);if(envelope.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||typeof envelope.nonce!=="string"||envelope.nonce.length!==item.nonce.length||!timingSafeEqual(Buffer.from(envelope.nonce),Buffer.from(item.nonce))){socket.destroy();return}const{operationalContext,...message}=envelope;if(operationalContext!==void 0&&!isOperationalContext(operationalContext)){socket.destroy();return}async function configureSelection(valid,configure){if(!configure||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!valid(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await configure(message.selection))}const dispatch=async()=>{if((stopping||closing)&&message.command!=="status"&&message.command!=="stop"){reply({err:{code:"unavailable",message:"The background host is stopping."}});return}if(message.command!=="status"&&message.command!=="stop"){active=true;activeRequests++}if(message.command==="status"){const{nonce:_nonce,endpoint:_endpoint,update,...safe}=traceResidentControl(handlers.telemetry,{phase:"runtime",action:"status",operationId:"resident.status"},status,{plainResult:true});const updateState=update;socket.end(JSON.stringify({...safe,update:{...typeof updateState?.idle==="boolean"&&typeof updateState.paused==="boolean"?{idle:updateState.idle&&activeRequests===0,paused:updateState.paused}:{},guardedStop:true},runtime,protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:!stopping,pid:item.pid,startedAt:item.startedAt})+"\n")}else if(message.command==="onboard"){if(!handlers.onboard||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.onboard(disconnected.signal))}else if(message.command==="sync"){if(!handlers.sync||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||message.bindingId!==void 0&&(typeof message.bindingId!=="string"||!message.bindingId||message.bindingId.length>200)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.sync(message.source,message.requestId,{signal:disconnected.signal,...message.bindingId?{bindingId:message.bindingId}:{}});reply(result)}else if(message.command==="local-cloud-control"){if(!isLocalCloudControlRequest(message.request)){socket.destroy();return}if(!handlers.localCloud){reply({err:{code:"unavailable",message:"This resident does not provide Local Cloud authorization controls."}});return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.localCloud(message.request))}else if(message.command==="gateway"){if(!handlers.gateway||!isResidentGatewayRequest(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.gateway(message.request,disconnected.signal))}else if(message.command==="ensure-ready"){if(!handlers.ensureReady||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());reply(await handlers.ensureReady(message.source,disconnected.signal))}else if(message.command==="check"){if(!handlers.check||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.check(message.source,disconnected.signal))}else if(message.command==="read"){if(!handlers.read||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||!message.request||typeof message.request!=="object"||Array.isArray(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());const result=await handlers.read(message.source,message.request,disconnected.signal);reply(result)}else if(message.command==="invoke"){const request2=message.request;if(!handlers.invoke||!request2||typeof request2!=="object"||Array.isArray(request2)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());const result=await handlers.invoke(request2,disconnected.signal);reply(result)}else if(message.command==="connect"){if(!handlers.connect||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||typeof message.automatic!=="boolean"){socket.destroy();return}const manualPresentation=message.manualPresentation==="return-url"?"return-url":message.manualPresentation==="open"?"open":void 0;socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connect(message.source,message.requestId,disconnected.signal,{automatic:message.automatic,...manualPresentation?{manualPresentation}:{}});reply(result)}else if(message.command==="connect-manual"){if(!handlers.connectManual||typeof message.source!=="string"||!HELP_MANUAL_SOURCES.has(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectManual(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="reconnect-saved"){if(!handlers.reconnectSaved||typeof message.source!=="string"||!supportsSavedReconnect(message.source)||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source"].includes(key))){socket.destroy();return}socket.setTimeout(9e4,()=>socket.destroy());const result=await handlers.reconnectSaved(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-gmail-write"){if(!handlers.connectGmailWrite||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectGmailWrite(message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-readwise-mcp-write"){if(!handlers.connectReadwiseMcpWrite||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectReadwiseMcpWrite(message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-reauthorize"){if(!handlers.connectReauthorize||typeof message.source!=="string"||!["todoist","linear"].includes(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectReauthorize(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-recovery"){if(!handlers.connectRecovery||typeof message.source!=="string"||!["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectRecovery(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-automatic"){if(!handlers.connectAutomatic||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectAutomatic(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-job"){if(!handlers.connectJob||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150){socket.destroy();return}const result=await handlers.connectJob(message.requestId);reply(result)}else if(message.command==="connect-cancel"){if(!handlers.cancelConnect||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||!Number.isSafeInteger(message.generation)||message.generation<0||typeof message.challengeRef!=="string"||!message.challengeRef||message.challengeRef.length>200){socket.destroy();return}const result=await handlers.cancelConnect(message.requestId,message.generation,message.challengeRef);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-wechat"){if(!handlers.configureWeChat||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureWeChat({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-joplin"){if(!handlers.configureJoplin||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))){socket.destroy();return}try{validateJoplinSelection(message.selection)}catch{socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureJoplin(message.selection,disconnected.signal);reply(result)}else if(message.command==="configure-thunderbird"){if(!handlers.configureThunderbird||Object.keys(message).some(key=>!["protocolVersion","nonce","command","port"].includes(key))||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureThunderbird({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-discord"){if(!handlers.configureDiscord||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))){socket.destroy();return}try{const selection=message.selection;if(!selection||typeof selection!=="object"||Array.isArray(selection)||Reflect.ownKeys(selection).some(key=>typeof key!=="string"||!["clientId","expectedSubject","ipcPath","channelIds"].includes(key)))throw Error("invalid");createPreparedDiscordSource("discord",{mode:"fields",...selection})}catch{socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureDiscord(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-proton-mail"){if(!handlers.configureProtonMail||Object.keys(message).some(key=>!["protocolVersion","nonce","command","port"].includes(key))||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureProtonMail({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zulip"){await configureSelection(validZulipSelection,handlers.configureZulip?.bind(handlers))}else if(message.command==="configure-freshrss"){await configureSelection(validFreshRSSSelection,handlers.configureFreshRSS?.bind(handlers))}else if(message.command==="configure-miniflux"){await configureSelection(validMinifluxSelection,handlers.configureMiniflux?.bind(handlers))}else if(message.command==="configure-mattermost"){await configureSelection(validMattermostSelection,handlers.configureMattermost?.bind(handlers))}else if(message.command==="configure-wallabag"){await configureSelection(validWallabagSelection,handlers.configureWallabag?.bind(handlers))}else if(message.command==="configure-calcom"){await configureSelection(validCalcomSelection,handlers.configureCalcom?.bind(handlers))}else if(message.command==="configure-wakatime"){await configureSelection(validWakatimeSelection,handlers.configureWakatime?.bind(handlers))}else if(message.command==="configure-nextcloud"){if(!handlers.configureNextcloud||Object.keys(message).some(key=>!["protocolVersion","nonce","command","instanceUrl"].includes(key))||!validNextcloudInstanceUrl(message.instanceUrl)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureNextcloud({instanceUrl:message.instanceUrl});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-dropbox"){const selection=message.selection;if(!handlers.configureDropbox||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureDropbox({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-box"){const selection=message.selection;if(!handlers.configureBox||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureBox({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-front"){const selection=message.selection;if(!handlers.configureFront||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFront({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-hubspot"){const selection=message.selection;if(!handlers.configureHubSpot||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureHubSpot({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-google-contacts"){const selection=message.selection;if(!handlers.configureGoogleContacts||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length<2||Object.keys(selection).length>3||Object.keys(selection).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key))||selection.developerPreview!==void 0&&typeof selection.developerPreview!=="boolean"||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureGoogleContacts({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-google-chat"){const selection=message.selection;if(!handlers.configureGoogleChat||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length<2||Object.keys(selection).length>3||Object.keys(selection).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key))||selection.developerPreview!==void 0&&typeof selection.developerPreview!=="boolean"||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureGoogleChat({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-salesforce"){const selection=message.selection;if(!handlers.configureSalesforce||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==3||Object.keys(selection).some(key=>!["environment","clientId","loopbackPort"].includes(key))||!["production","sandbox"].includes(selection.environment)||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureSalesforce({environment:selection.environment,clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zendesk"){const selection=message.selection;if(!handlers.configureZendesk||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validZendeskSelection(selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZendesk({subdomain:selection.subdomain,clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zoom"){const selection=message.selection;if(!handlers.configureZoom||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==1||Object.keys(selection).some(key=>key!=="clientId")||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZoom({clientId:selection.clientId});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-smartsheet"){if(!handlers.configureSmartsheet||Object.keys(message).some(key=>!["protocolVersion","nonce","command","region"].includes(key))||!["us","eu","au"].includes(message.region)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureSmartsheet({region:message.region});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-figma"){if(!handlers.configureFigma||Object.keys(message).some(key=>!["protocolVersion","nonce","command","mode"].includes(key))||!["fields","oauth"].includes(message.mode)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFigma(message.mode);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-freshdesk"){if(!handlers.configureFreshdesk||Object.keys(message).some(key=>!["protocolVersion","nonce","command","subdomain"].includes(key))||typeof message.subdomain!=="string"||message.subdomain.length>63||!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(message.subdomain)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFreshdesk({subdomain:message.subdomain});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-copyq"){if(!handlers.configureCopyQ||typeof message.executable!=="string"||message.executable.length<1||message.executable.length>512||typeof message.session!=="string"||!/^[\p{L}\p{N}_-]{0,16}$/u.test(message.session)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureCopyQ({executable:message.executable,session:message.session});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-owntracks"){if(!handlers.configureOwnTracks||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureOwnTracks({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zotero"){if(!handlers.configureZotero||typeof message.libraryId!=="string"||!["user","group"].includes(message.libraryType)||!/^[1-9][0-9]{0,19}$/.test(message.libraryId)&&!(message.libraryType==="user"&&message.libraryId==="0")){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZotero({libraryId:message.libraryId,libraryType:message.libraryType});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-native-files"){const sources=["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","local-audio","obsidian","logseq","computer-files"];if(!handlers.configureNativeFiles||!sources.includes(message.source)||!Array.isArray(message.roots)||message.roots.length<1||message.roots.length>16||!message.roots.every(root2=>typeof root2==="string"&&root2.length>0&&root2.length<=4096)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureNativeFiles({source:message.source,roots:message.roots});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-status"){if(!handlers.connectorStatus){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorStatus();if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-check"){if(!handlers.connectorCheck||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorCheck(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-read"){if(!handlers.connectorRead||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorRead(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="pause-connection-automation"){if(!handlers.pauseAutomation||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());await markResidentInterruption(id.root,"pause");reply(await handlers.pauseAutomation())}else if(message.command==="resume-background-sync"){if(!handlers.resumeBackgroundSync||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.resumeBackgroundSync())}else if(message.command==="stop"){if(message.guard!==void 0){if(!validUpdateOwner(message.guard)){socket.destroy();return}const guard=message.guard,path=value=>process.platform==="win32"?value.toLowerCase():value;const current=status().update;const reason=stopping||closing||guard.pid!==item.pid||guard.startedAt!==item.startedAt||guard.runtime.version!==runtime.version||path(guard.runtime.installationPath)!==path(runtime.installationPath)?"resident_changed":typeof current?.idle!=="boolean"||typeof current.paused!=="boolean"?"resident_guard_unavailable":current.paused?"resident_paused":!current.idle||activeRequests!==0?"resident_busy":void 0;if(reason){socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:!stopping,deferred:true,reason})+"\n");return}}else await markResidentInterruption(id.root,"stop");socket.setTimeout(RESIDENT_STOP_TIMEOUT_MS,()=>socket.destroy());stopping??=Promise.resolve().then(()=>traceResidentControl(handlers.telemetry,{phase:"runtime",action:"cleanup",operationId:"resident.stop"},onStop,{plainResult:true}));try{await stopping}catch{stopping=void 0;socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,error:"resident_cleanup_failed"})+"\n");return}socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:false,stopped:true})+"\n");void close()}else socket.destroy()};if(operationalContext)await withOperationalContext(operationalContext,dispatch);else await withoutOperationalContext(dispatch)}catch{socket.destroy()}finally{if(active)activeRequests--}})()})});const close=()=>closing??=(async()=>{try{const closed=new Promise(done=>server.close(()=>done()));for(const socket of sockets)socket.end();await closed;if((await metadata(id))?.nonce===item.nonce)await unlink(id.file).catch(()=>{})}finally{ownership?.close()}})();try{const claimed=await installationRecovery.withResidentClaim(async()=>{ownership=process.platform==="win32"?void 0:unixOwnership(id);if(ownership===null)return false;const intent=process.env.ZORTEX_UPDATE_INTENT;if(intent!==void 0&&await residentInterruption(id.root)!==intent)throw Error("The resident was stopped or paused after this update began.");try{await listen(server,id.endpoint)}catch(error){if(error.code!=="EADDRINUSE")throw error;if(process.platform==="win32"||!await recoverUnixEndpoint(id.endpoint)){await close();return false}try{await listen(server,id.endpoint)}catch(retryError){if(retryError.code!=="EADDRINUSE")throw retryError;await close();return false}}if(process.platform!=="win32")await chmod(id.endpoint,384);const temporary=`${id.file}.${item.nonce}.tmp`;try{await writeFile(temporary,JSON.stringify(item),{mode:384,flag:"wx"});await rename(temporary,id.file)}finally{await unlink(temporary).catch(()=>{})}if(intent!==void 0&&await residentInterruption(id.root)!==intent)throw Error("The resident was stopped or paused after this update began.");return true},runtime.version);if(!claimed)return null}catch(error){await close();throw error}return{close}}function windowsQuote(value){return'"'+value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/g,"$1$1")+'"'}const xml=value=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'");export function residentStartupPlan(root,entrypoint,hash,platform=process.platform,executable=process.execPath,home=homedir(),environment=process.env){if(![root,entrypoint,executable].every(isAbsolute))throw new Error("Resident startup paths must be absolute");if(![root,entrypoint,executable].every(value=>!/[\r\n\0]/.test(value)))throw new Error("Invalid resident startup path");if(!/^[a-f0-9]{24}$/.test(hash))throw new Error("Invalid resident identity");const syncDisabled=/^(0|false|off|no)$/i.test((environment.ZORTEX_AUTO_SYNC??"").trim());const connectDisabled=/^(0|false|off|no)$/i.test((environment.ZORTEX_AUTO_CONNECT??"").trim());const lookupPath=platform==="darwin"&&environment.PATH&&!/[\x00-\x1f]/.test(environment.PATH)?[...new Set(environment.PATH.split(":").filter(isAbsolute))].join(":"):void 0;const startupEnvironment={...syncDisabled?{ZORTEX_AUTO_SYNC:"0"}:{},...connectDisabled?{ZORTEX_AUTO_CONNECT:"0"}:{},...lookupPath?{PATH:lookupPath}:{}};const args=[entrypoint,"--root",root,"host","run",...syncDisabled?["--sync-disabled"]:[]];const command=[executable,...args].map(windowsQuote).join(" ");const launcherPath=join(root,"host","resident-startup.vbs");const launcher=`Option Explicit\r
|
|
2
2
|
CreateObject("WScript.Shell").Run "${command.replaceAll('"','""')}", 0, False\r
|
|
3
3
|
`;const registryCommand=[windowsQuote("%SystemRoot%\\System32\\wscript.exe"),"//B","//NoLogo",windowsQuote(launcherPath)].join(" ");const label=`com.zortex.indra.${hash}`;const plist=`<?xml version="1.0" encoding="UTF-8"?>
|
|
4
4
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
5
|
-
<plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array>${[executable,...args].map(v=>`<string>${xml(v)}</string>`).join("")}</array>${
|
|
6
|
-
`;return{platform,executable,args,command,launcherPath,launcher,registryCommand,registryType:"REG_EXPAND_SZ",registryKey:"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",registryName:`ZortexIndra-${hash}`,label,plistPath:join(home,"Library","LaunchAgents",`${label}.plist`),plist}}async function plan(root,entrypoint){const id=await identity(root);return{id,registration:residentStartupPlan(id.root,await realpath(resolve(entrypoint)),id.hash)}}export async function startResident(root,entrypoint){const{id,registration}=await plan(root,entrypoint);let current=await request(id,"status");if(current?.running&¤t.ready!==false)return current;let spawnError;if(!current?.running){const child=spawn(registration.executable,registration.args,{detached:true,windowsHide:true,stdio:"ignore",env:/^(0|false|off|no)$/i.test((process.env.ZORTEX_AUTO_SYNC??"").trim())?{...process.env,ZORTEX_AUTO_SYNC:"0"}:process.env});child.once("error",error=>{spawnError=error});child.unref()}const deadline=Date.now()+12e4;while(Date.now()<deadline){if(spawnError)throw spawnError;try{current=await request(id,"status",500)}catch(error){if(!(error instanceof Error)||error.message!=="Resident status is unavailable; inspect the running host before retrying")throw error;current=null}if(current?.running&¤t.ready!==false)return current;await delay(200)}throw new Error("Resident did not become ready within 120 seconds")}export async function stopResident(root){const id=await identity(root);const current=await request(id,"status");if(!current?.running)return{running:false};const stopped=await request(id,"stop",
|
|
5
|
+
<plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array>${[executable,...args].map(v=>`<string>${xml(v)}</string>`).join("")}</array>${Object.keys(startupEnvironment).length?"<key>EnvironmentVariables</key><dict>"+Object.entries(startupEnvironment).map(([key,value])=>`<key>${key}</key><string>${xml(value)}</string>`).join("")+"</dict>":""}<key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict><key>ThrottleInterval</key><integer>30</integer></dict></plist>
|
|
6
|
+
`;return{platform,executable,args,command,launcherPath,launcher,registryCommand,registryType:"REG_EXPAND_SZ",registryKey:"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",registryName:`ZortexIndra-${hash}`,label,plistPath:join(home,"Library","LaunchAgents",`${label}.plist`),plist}}async function plan(root,entrypoint){const id=await identity(root);return{id,registration:residentStartupPlan(id.root,await realpath(resolve(entrypoint)),id.hash)}}export async function startResident(root,entrypoint){await installationRecovery.recover();const{id,registration}=await plan(root,entrypoint);let current=await request(id,"status");if(current?.running&¤t.ready!==false)return current;let spawnError;if(!current?.running){const child=spawn(registration.executable,registration.args,{detached:true,windowsHide:true,stdio:"ignore",env:/^(0|false|off|no)$/i.test((process.env.ZORTEX_AUTO_SYNC??"").trim())?{...process.env,ZORTEX_AUTO_SYNC:"0"}:process.env});child.once("error",error=>{spawnError=error});child.unref()}const deadline=Date.now()+12e4;while(Date.now()<deadline){if(spawnError)throw spawnError;try{current=await request(id,"status",500)}catch(error){if(!(error instanceof Error)||error.message!=="Resident status is unavailable; inspect the running host before retrying")throw error;current=null}if(current?.running&¤t.ready!==false)return current;await delay(200)}throw new Error("Resident did not become ready within 120 seconds")}export async function stopResident(root){await markResidentInterruption(root,"stop");return stopOwnedResident(root)}export async function stopResidentIfIdle(root,expected){if(!validUpdateOwner(expected))throw Error("A complete resident owner identity is required.");return stopOwnedResident(root,expected)}async function stopOwnedResident(root,expected){const id=await identity(root);const current=await request(id,"status");if(!current?.running)return expected?{running:false,deferred:true,reason:"resident_changed"}:{running:false};if(expected&¤t.update?.guardedStop!==true)return{...current,deferred:true,reason:"resident_guard_unavailable"};const stopped=await request(id,"stop",RESIDENT_STOP_TIMEOUT_MS,expected);if(stopped?.deferred===true)return stopped;if(Number.isSafeInteger(current.pid)&¤t.pid!==process.pid){const deadline=Date.now()+5e3;for(;;){try{process.kill(current.pid,0)}catch(error){if(error.code==="ESRCH")return stopped??{running:false,stopped:true,cleanupAcknowledged:false};throw new Error("Cannot verify that the resident owner exited",{cause:error})}if(Date.now()>=deadline)break;await delay(20)}if(stopped&&!stopped.running)throw new Error("Resident cleanup was acknowledged but its owner did not exit")}if(!stopped||stopped.running)throw new Error("Resident cleanup was not acknowledged; inspect host status");return stopped}export async function enableResident(root,entrypoint){const{id,registration}=await plan(root,entrypoint);if(process.platform==="win32"){await preserveResidentStartupOrigin(root,registration.launcher);await mkdir(dirname(registration.launcherPath),{recursive:true});await writeFile(registration.launcherPath,registration.launcher,{mode:384});try{await execute("reg.exe",["add",registration.registryKey,"/v",registration.registryName,"/t",registration.registryType,"/d",registration.registryCommand,"/f"],{windowsHide:true,timeout:1e4})}catch(error){await unlink(registration.launcherPath).catch(()=>{});throw error}await setResidentStartupDisabled(id.root,false);return{enabled:true,mechanism:"HKCU Run"}}if(process.platform==="darwin"){await mkdir(join(registration.plistPath,".."),{recursive:true});await writeFile(registration.plistPath,registration.plist,{mode:384});await setResidentStartupDisabled(id.root,false);return{enabled:true,mechanism:"LaunchAgent (next login)"}}throw new Error("Resident login startup is supported on Windows and macOS only")}export async function disableResident(root){const id=await identity(root);await setResidentStartupDisabled(id.root,true);const registration=residentStartupPlan(id.root,process.execPath,id.hash);if(process.platform==="win32"){let registered=true;try{await execute("reg.exe",["query",registration.registryKey,"/v",registration.registryName],{windowsHide:true,timeout:1e4})}catch(error){if(error.code===1)registered=false;else throw error}if(registered)await execute("reg.exe",["delete",registration.registryKey,"/v",registration.registryName,"/f"],{windowsHide:true,timeout:1e4});await unlink(registration.launcherPath).catch(error=>{if(error.code!=="ENOENT")throw error})}else if(process.platform==="darwin"){await unlink(registration.plistPath).catch(error=>{if(error.code!=="ENOENT")throw error})}else throw new Error("Resident login startup is supported on Windows and macOS only");return{enabled:false}}export async function residentStartupStatus(root){const id=await identity(root);const preference=await residentStartupDisabled(id.root)?{disabled:true}:{};const registration=residentStartupPlan(id.root,process.execPath,id.hash);if(process.platform==="win32"){try{const{stdout}=await execute("reg.exe",["query",registration.registryKey,"/v",registration.registryName],{windowsHide:true,timeout:1e4});return{enabled:stdout.includes(registration.launcherPath)&&/wscript\.exe/i.test(stdout),mechanism:"HKCU Run",...preference}}catch(error){if(error.code===1)return{enabled:false,mechanism:"HKCU Run",...preference};throw error}}if(process.platform==="darwin"){const plist=await readFile(registration.plistPath,"utf8").catch(error=>{if(error.code==="ENOENT")return"";throw error});const enabled=plist.includes(`<string>${registration.label}</string>`);return{enabled,mechanism:"LaunchAgent (next login)",...preference,...enabled&&!plist.includes("<key>PATH</key>")?{needsRefresh:true}:{}}}return{enabled:false,mechanism:"unsupported",...preference}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile}from"node:fs/promises";export async function residentRuntimeIdentity(base=new URL("../",import.meta.url)){const read=async name=>{try{return JSON.parse(await readFile(new URL(name,base),"utf8"))}catch{return void 0}};const manifest=await read("package.json");const provenance=await read("release-provenance.json");const version=typeof manifest?.version==="string"&&/^[0-9A-Za-z.+-]{1,80}$/.test(manifest.version)?manifest.version:void 0;const commit=version&&provenance?.name==="@zortexhq/indra-v2.5"&&provenance.version===version&&typeof provenance.commit==="string"&&/^[a-f0-9]{40}$/.test(provenance.commit)?provenance.commit:void 0;return{
|
|
1
|
+
import{readFile,realpath}from"node:fs/promises";import{fileURLToPath}from"node:url";export function residentRuntimePolicy(env=process.env){const enabled=value=>!/^(0|false|off|no)$/i.test((value??"").trim());return{autoConnect:/^(1|true|on|yes)$/i.test((env.ZORTEX_AUTO_CONNECT??"").trim()),autoSync:enabled(env.ZORTEX_AUTO_SYNC)}}export async function residentRuntimeIdentity(base=new URL("../",import.meta.url),env=process.env){const installationPath=await realpath(fileURLToPath(base));const policy=residentRuntimePolicy(env);const read=async name=>{try{return JSON.parse(await readFile(new URL(name,base),"utf8"))}catch{return void 0}};const manifest=await read("package.json");const provenance=await read("release-provenance.json");const version=typeof manifest?.version==="string"&&/^[0-9A-Za-z.+-]{1,80}$/.test(manifest.version)?manifest.version:void 0;const commit=version&&provenance?.name==="@zortexhq/indra-v2.5"&&provenance.version===version&&typeof provenance.commit==="string"&&/^[a-f0-9]{40}$/.test(provenance.commit)?provenance.commit:void 0;return{installationPath,policy,...version?{version}:{},...commit?{commit}:{}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const RESIDENT_STOP_TIMEOUT_MS=12e4;export function createResidentShutdown(stopWork,cleanup){let releaseWork,finish;const workStopped=new Promise(resolve=>{releaseWork=resolve});const done=new Promise(resolve=>{finish=resolve});let requested=false,complete=false,pending;return{done,workStopped:()=>releaseWork(),request(){if(!requested){requested=true;stopWork()}if(complete)return Promise.resolve();if(pending)return pending;const attempt=(async()=>{await workStopped;await cleanup();complete=true;finish()})();pending=attempt;const settled=()=>{if(pending===attempt)pending=void 0};void attempt.then(settled,settled);return attempt}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID}from"node:crypto";import{lstat,mkdir,readFile,rename,unlink,writeFile}from"node:fs/promises";import{dirname,join}from"node:path";const marker=root=>join(root,"host","startup-disabled.json");export async function residentStartupDisabled(root){const file=marker(root);const info=await lstat(file).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(!info)return false;if(!info.isFile()||info.isSymbolicLink()||info.size>1024)throw Error("Resident startup preference is invalid.");let value;try{value=JSON.parse(await readFile(file,"utf8"))}catch{throw Error("Resident startup preference is invalid.")}if(!value||typeof value!=="object"||Array.isArray(value)||value.disabled!==true)throw Error("Resident startup preference is invalid.");return true}export async function setResidentStartupDisabled(root,disabled){const file=marker(root);if(!disabled){await unlink(file).catch(error=>{if(error.code!=="ENOENT")throw error});return}await mkdir(dirname(file),{recursive:true,mode:448});const temporary=file+"."+randomUUID()+".tmp";try{await writeFile(temporary,'{"disabled":true}\n',{flag:"wx",mode:384});await rename(temporary,file)}finally{await unlink(temporary).catch(()=>{})}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isPromise}from"node:util/types";import{startOperationalStep,usageOutcome}from"@zortexhq/plugin-telemetry/api";const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const connector=(operationId,action,source)=>({phase:"connector",action,...operationId?{operationId}:{},...typeof source==="string"?{source}:{}});const configure=source=>()=>connector("resident.configure","execute",source);const runtime=(operationId,action)=>({phase:"runtime",action,...operationId?{operationId}:{}});const metadata={localCloud:args=>runtime("resident.local_cloud",object(args[0])&&args[0].action==="grants"?"status":"cancel"),gateway:args=>{const operation=object(args[0])&&typeof args[0].operation==="string"?args[0].operation:"unknown";const ids={search:"tool.search",actions:"tool.actions",action:"tool.action",manage:"tool.manage",instruction:"tool.instruction",handbook:"tool.handbook"};return{phase:"tool",action:"execute",operationId:ids[operation]??"unknown"}},ensureReady:args=>connector("resident.check","observe",args[0]),check:args=>connector("resident.check","observe",args[0]),read:args=>connector("connector.read","read",args[0]),sync:args=>connector("connector.sync","execute",args[0]),invoke:args=>connector("connector.invoke","invoke",object(args[0])?args[0].source:void 0),connect:args=>connector("resident.connect","connect",args[0]),connectJob:()=>connector("resident.connect_job","status"),cancelConnect:()=>connector("resident.cancel_connect","cancel"),pauseAutomation:()=>runtime("resident.pause_automation","cancel"),resumeBackgroundSync:()=>runtime("resident.resume_sync","execute"),configureFreshRSS:configure("freshrss"),configureMiniflux:configure("miniflux"),configureMattermost:configure("mattermost"),configureWallabag:configure("wallabag"),configureCalcom:configure("calcom"),configureWakatime:configure("wakatime"),configureZulip:configure("zulip"),configureGoogleChat:configure("google-chat"),configureGoogleContacts:configure("google-contacts"),configureZendesk:configure("zendesk"),configureSalesforce:configure("salesforce"),configureBox:configure("box"),configureFront:configure("front"),configureHubSpot:configure("hubspot"),configureZoom:configure("zoom"),configureDropbox:configure("dropbox"),configureDiscord:configure("discord"),configureProtonMail:configure("proton-mail"),configureJoplin:configure("joplin"),configureThunderbird:configure("thunderbird"),configureNextcloud:configure("nextcloud"),configureFigma:configure("figma"),configureSmartsheet:configure("smartsheet"),configureFreshdesk:configure("freshdesk"),configureCopyQ:configure("copyq"),configureWeChat:configure("wechat"),configureOwnTracks:configure("owntracks"),configureZotero:configure("zotero"),connectManual:args=>connector("resident.connect_manual","connect",args[0]),reconnectSaved:args=>({...connector("resident.reconnect","connect",args[0]),selection:"saved"}),connectReadwiseMcpWrite:()=>connector("resident.connect_write","connect","readwise"),connectGmailWrite:()=>connector("resident.connect_write","connect","gmail"),connectReauthorize:args=>connector("resident.reauthorize","connect",args[0]),connectRecovery:args=>({...connector("resident.recover","connect",args[0]),selection:"recovery"}),connectAutomatic:args=>connector("resident.connect_automatic","connect",args[0]),connectorStatus:()=>connector("connector.status","status"),connectorRead:args=>connector("connector.read","read",args[0]),connectorCheck:args=>connector("resident.check","observe",args[0]),configureNativeFiles:args=>connector("resident.configure","execute",object(args[0])?args[0].source:void 0)};function signalFor(name,args){const index=["gateway","ensureReady","check","invoke","reconnectSaved","connectorRead","connectorCheck","configureJoplin","connectGmailWrite","connectReadwiseMcpWrite"].includes(name)?1:["read","connect","connectManual","connectReauthorize","connectRecovery","connectAutomatic"].includes(name)?2:void 0;const value=name==="sync"&&object(args[2])?args[2].signal:index===void 0?void 0:args[index];return value instanceof AbortSignal?value:void 0}export function traceResidentControl(metrics,input,run,options={}){let enabled=false;try{enabled=metrics?.()?.isEnabled?.()===true}catch{}if(!enabled)return run();const step=startOperationalStep(metrics,input);const cancelled=()=>{try{return options.signal?.()?.aborted===true}catch{return false}};const finish=result=>{try{if(cancelled()){step.finish({state:"cancelled"});return}if(options.plainResult){step.finish({state:"completed"});return}if(!object(result)||!("ok"in result||"err"in result||"empty"in result)){step.finish({state:"unknown"});return}const value=object(result.ok)?result.ok:void 0,state=value?.state??(object(value?.status)?value.status.state:value?.status);if(["pending","queued","running","waiting","waiting-user","needs-user","needs_user","needs_you","AUTH_BLOCKED"].includes(String(state))){step.mark({state:"waiting"});step.finish({state:"unknown"});return}const outcome=usageOutcome(result);step.finish({state:outcome==="cancelled"?"cancelled":["fault","auth-blocked","invalid"].includes(outcome)?"failed":outcome==="unknown"?"unknown":"completed"})}catch{step.finish({state:"unknown"})}};const failed=()=>step.finish({state:cancelled()?"cancelled":"failed",errorCategory:"unknown"});return step.run(()=>{try{const result=run();if(isPromise(result))return result.then(value=>{finish(value);return value},error=>{failed();throw error});finish(result);return result}catch(error){failed();throw error}})}export function observeResidentHandlers(handlers){const observed={...handlers};for(const name of Object.keys(metadata)){const handler=handlers[name];if(!handler)continue;const wrapped=(...args)=>traceResidentControl(handlers.telemetry,()=>metadata[name](args),()=>Reflect.apply(handler,handlers,args),{signal:()=>signalFor(name,args)});Object.assign(observed,{[name]:wrapped})}return observed}
|
|
1
|
+
import{isPromise}from"node:util/types";import{startOperationalStep,usageOutcome}from"@zortexhq/plugin-telemetry/api";const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const connector=(operationId,action,source)=>({phase:"connector",action,...operationId?{operationId}:{},...typeof source==="string"?{source}:{}});const configure=source=>()=>connector("resident.configure","execute",source);const runtime=(operationId,action)=>({phase:"runtime",action,...operationId?{operationId}:{}});const metadata={onboard:()=>({phase:"onboarding",action:"execute",operationId:"resident.startup"}),localCloud:args=>runtime("resident.local_cloud",object(args[0])&&args[0].action==="grants"?"status":"cancel"),gateway:args=>{const operation=object(args[0])&&typeof args[0].operation==="string"?args[0].operation:"unknown";const ids={search:"tool.search",actions:"tool.actions",action:"tool.action",manage:"tool.manage",instruction:"tool.instruction",handbook:"tool.handbook"};return{phase:"tool",action:"execute",operationId:ids[operation]??"unknown"}},ensureReady:args=>connector("resident.check","observe",args[0]),check:args=>connector("resident.check","observe",args[0]),read:args=>connector("connector.read","read",args[0]),sync:args=>connector("connector.sync","execute",args[0]),invoke:args=>connector("connector.invoke","invoke",object(args[0])?args[0].source:void 0),connect:args=>connector("resident.connect","connect",args[0]),connectJob:()=>connector("resident.connect_job","status"),cancelConnect:()=>connector("resident.cancel_connect","cancel"),pauseAutomation:()=>runtime("resident.pause_automation","cancel"),resumeBackgroundSync:()=>runtime("resident.resume_sync","execute"),configureFreshRSS:configure("freshrss"),configureMiniflux:configure("miniflux"),configureMattermost:configure("mattermost"),configureWallabag:configure("wallabag"),configureCalcom:configure("calcom"),configureWakatime:configure("wakatime"),configureZulip:configure("zulip"),configureGoogleChat:configure("google-chat"),configureGoogleContacts:configure("google-contacts"),configureZendesk:configure("zendesk"),configureSalesforce:configure("salesforce"),configureBox:configure("box"),configureFront:configure("front"),configureHubSpot:configure("hubspot"),configureZoom:configure("zoom"),configureDropbox:configure("dropbox"),configureDiscord:configure("discord"),configureProtonMail:configure("proton-mail"),configureJoplin:configure("joplin"),configureThunderbird:configure("thunderbird"),configureNextcloud:configure("nextcloud"),configureFigma:configure("figma"),configureSmartsheet:configure("smartsheet"),configureFreshdesk:configure("freshdesk"),configureCopyQ:configure("copyq"),configureWeChat:configure("wechat"),configureOwnTracks:configure("owntracks"),configureZotero:configure("zotero"),connectManual:args=>connector("resident.connect_manual","connect",args[0]),reconnectSaved:args=>({...connector("resident.reconnect","connect",args[0]),selection:"saved"}),connectReadwiseMcpWrite:()=>connector("resident.connect_write","connect","readwise"),connectGmailWrite:()=>connector("resident.connect_write","connect","gmail"),connectReauthorize:args=>connector("resident.reauthorize","connect",args[0]),connectRecovery:args=>({...connector("resident.recover","connect",args[0]),selection:"recovery"}),connectAutomatic:args=>connector("resident.connect_automatic","connect",args[0]),connectorStatus:()=>connector("connector.status","status"),connectorRead:args=>connector("connector.read","read",args[0]),connectorCheck:args=>connector("resident.check","observe",args[0]),configureNativeFiles:args=>connector("resident.configure","execute",object(args[0])?args[0].source:void 0)};function signalFor(name,args){const index=name==="onboard"?0:["gateway","ensureReady","check","invoke","reconnectSaved","connectorRead","connectorCheck","configureJoplin","connectGmailWrite","connectReadwiseMcpWrite"].includes(name)?1:["read","connect","connectManual","connectReauthorize","connectRecovery","connectAutomatic"].includes(name)?2:void 0;const value=name==="sync"&&object(args[2])?args[2].signal:index===void 0?void 0:args[index];return value instanceof AbortSignal?value:void 0}export function traceResidentControl(metrics,input,run,options={}){let enabled=false;try{enabled=metrics?.()?.isEnabled?.()===true}catch{}if(!enabled)return run();const step=startOperationalStep(metrics,input);const cancelled=()=>{try{return options.signal?.()?.aborted===true}catch{return false}};const finish=result=>{try{if(cancelled()){step.finish({state:"cancelled"});return}if(options.plainResult){step.finish({state:"completed"});return}if(!object(result)||!("ok"in result||"err"in result||"empty"in result)){step.finish({state:"unknown"});return}const value=object(result.ok)?result.ok:void 0,state=value?.state??(object(value?.status)?value.status.state:value?.status);if(["pending","queued","running","waiting","waiting-user","needs-user","needs_user","needs_you","AUTH_BLOCKED"].includes(String(state))){step.mark({state:"waiting"});step.finish({state:"unknown"});return}const outcome=usageOutcome(result);step.finish({state:outcome==="cancelled"?"cancelled":["fault","auth-blocked","invalid"].includes(outcome)?"failed":outcome==="unknown"?"unknown":"completed"})}catch{step.finish({state:"unknown"})}};const failed=()=>step.finish({state:cancelled()?"cancelled":"failed",errorCategory:"unknown"});return step.run(()=>{try{const result=run();if(isPromise(result))return result.then(value=>{finish(value);return value},error=>{failed();throw error});finish(result);return result}catch(error){failed();throw error}})}export function observeResidentHandlers(handlers){const observed={...handlers};for(const name of Object.keys(metadata)){const handler=handlers[name];if(!handler)continue;const wrapped=(...args)=>traceResidentControl(handlers.telemetry,()=>metadata[name](args),()=>Reflect.apply(handler,handlers,args),{signal:()=>signalFor(name,args)});Object.assign(observed,{[name]:wrapped})}return observed}
|
package/dist/update-cli.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn}from"node:child_process";import{fileURLToPath}from"node:url";import{productUpdater}from"./auto-update.js";const print=value=>process.stdout.write(JSON.stringify(value)+"\n");const enabled=()=>!/^(0|false|off)$/i.test(process.env.ZORTEX_UPDATES??"")&&process.env.ZORTEX_FEEDBACK_TRAFFIC_CLASS!=="internal_test";export async function bootstrapProductCli(argv){if(process.env.ZORTEX_UPDATE_VERIFY!=="1")await productUpdater.recover();const args=[...argv];const root=args.indexOf("--root");if(root>=0)args.splice(root,2);if(args[0]==="update"){const operation=args[1]
|
|
1
|
+
import{spawn}from"node:child_process";import{fileURLToPath}from"node:url";import{productUpdater}from"./auto-update.js";const print=value=>process.stdout.write(JSON.stringify(value)+"\n");const enabled=()=>!/^(0|false|off)$/i.test(process.env.ZORTEX_UPDATES??"")&&process.env.ZORTEX_FEEDBACK_TRAFFIC_CLASS!=="internal_test";export async function bootstrapProductCli(argv){if(process.env.ZORTEX_UPDATE_VERIFY!=="1")await productUpdater.recover();const args=[...argv];const root=args.indexOf("--root"),selectedRoot=root>=0?args[root+1]:void 0;if(root>=0)args.splice(root,2);if(args[0]==="update"){if(root>=0&&(!selectedRoot||selectedRoot.startsWith("--")))throw Error("Missing --root");if(args.length===1){const{updateInstalledProduct}=await import("./update-command.js");const result=await updateInstalledProduct(selectedRoot?{root:selectedRoot}:{});print(result);if(result.state==="failed"||"activation"in result&&result.activation.state==="failed"||"agent"in result&&["failed","unavailable"].includes(result.agent.state))process.exitCode=2;return true}const operation=args[1];if(operation==="--help"||operation==="help"){print({usage:"indra update",description:"Install the current release and hand over the existing background host when it is idle. Active work or an explicit pause defers activation. Your Vault and saved choices are preserved.",advanced:"indra update check reports the offer without installing. Exact-offer recovery: indra update apply --version <exact-version> --confirmation-token <token>. Existing MCP sessions may need reconnecting."});return true}if(operation==="check"&&args.length<=2){const result=await productUpdater.check({force:true});print(result);return true}if(operation==="apply"){const remaining=args.slice(2).filter(value=>value!=="--yes");const take=name=>{const at=remaining.indexOf(name);if(at<0)return void 0;const value=remaining[at+1];if(!value||value.startsWith("--"))throw Error("Missing "+name);remaining.splice(at,2);return value};const version=take("--version"),confirmationToken=take("--confirmation-token");if(!version||!confirmationToken||remaining.length)throw Error("Update requires --version and --confirmation-token from update check.");print(await productUpdater.apply({version,confirmationToken}));return true}throw Error("Use indra update. Run indra update --help for recovery options.")}if(enabled()&&!args.includes("mcp")&&!args.includes("--version")&&!args.includes("-v")&&!args.includes("--help")&&!args.includes("-h")&&!args.includes("help")&&args.length>0){const worker=spawn(process.execPath,[fileURLToPath(new URL("./update-check.js",import.meta.url))],{stdio:"ignore",detached:true,windowsHide:true,env:process.env});worker.on("error",()=>{});worker.unref()}return false}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{execFile}from"node:child_process";import{readFile,realpath}from"node:fs/promises";import{isAbsolute,join}from"node:path";import{promisify}from"node:util";import{productUpdater}from"./auto-update.js";import{configuredVaultRoot}from"./default-root.js";import{readPendingHandover,savePendingHandover,residentInterruption}from"./update-handover.js";import{RESIDENT_STOP_TIMEOUT_MS}from"./resident-shutdown.js";const execute=promisify(execFile);const samePath=(a,b)=>process.platform==="win32"?a.toLowerCase()===b.toLowerCase():a===b;class DeferredUpdate extends Error{reason;constructor(reason){super(reason);this.reason=reason}}function runtime(value){if(!value||typeof value!=="object")return;const item=value,policy=item.policy;if(typeof item.installationPath!=="string"||!isAbsolute(item.installationPath)||typeof item.version!=="string"||!policy||typeof policy.autoConnect!=="boolean"||typeof policy.autoSync!=="boolean")return;return item}function owner(status,installationPath,version){const current=runtime(status.runtime);if(!current||!Number.isSafeInteger(status.pid)||status.pid<1||typeof status.startedAt!=="string")throw new DeferredUpdate("resident_identity_unavailable");if(!samePath(current.installationPath,installationPath))throw new DeferredUpdate("resident_different_installation");if(current.version!==version)throw new DeferredUpdate("resident_version_mismatch");const update=status.update;if(update?.guardedStop!==true||typeof update.idle!=="boolean"||typeof update.paused!=="boolean")throw new DeferredUpdate("resident_guard_unavailable");if(update.paused)throw new DeferredUpdate("resident_paused");if(status.ready!==true||!update.idle)throw new DeferredUpdate("resident_busy");return{pid:status.pid,startedAt:status.startedAt,runtime:{installationPath:current.installationPath,version:current.version}}}function controls(lease,pending){const entrypoint=join(lease.installationPath,"dist/cli.js");const env={...process.env,...lease.environment,ZORTEX_UPDATES:"0",ZORTEX_ROOT:pending.root,ZORTEX_UPDATE_INTENT:pending.interruption,...pending.policy?{ZORTEX_AUTO_CONNECT:pending.policy.autoConnect?"1":"0",ZORTEX_AUTO_SYNC:pending.policy.autoSync?"1":"0"}:{}};const run=async(args,timeout)=>{const{stdout}=await execute(process.execPath,[entrypoint,...args],{cwd:lease.installationPath,env,windowsHide:true,timeout,maxBuffer:1024*1024});return JSON.parse(stdout)};const host=async command=>{const timeout=command[0]==="start"?27e4:command[0]==="stop"?RESIDENT_STOP_TIMEOUT_MS+15e3:45e3;const result=await run(["--root",pending.root,"host",...command],timeout);if(!result||typeof result.running!=="boolean")throw Error("Resident result could not be verified.");return result};return{host,stop:async expected=>{let stopped;try{stopped=await host(["stop","--if-idle","--expected-owner",JSON.stringify(expected)])}catch{throw new DeferredUpdate("resident_stop_unconfirmed")}if(stopped.running||stopped.stopped!==true||stopped.cleanupAcknowledged===false)throw new DeferredUpdate(typeof stopped.reason==="string"?stopped.reason:"resident_stop_unconfirmed")},refresh:async()=>{try{const result=(await run(["setup","codex","--refresh"],6e4))?.ok,state=result?.state==="disabled"?"disabled":result?.refresh?.state;if(typeof state!=="string"||!/^[a-z][a-z-]{0,79}$/.test(state)||["updated","current"].includes(state)&&result.registered!==true)throw Error("Codex refresh could not be confirmed.");return{state,reconnectRequired:["updated","current"].includes(state)}}catch{return{state:"unavailable",reconnectRequired:false,reason:"codex_refresh_unconfirmed"}}}}}async function finishHandover(lease,pending,mode){const version=JSON.parse(await readFile(join(lease.installationPath,"package.json"),"utf8")).version;if(![pending.fromVersion,pending.targetVersion].includes(version))throw new DeferredUpdate("installed_version_changed");const control=controls(lease,pending);let activation={state:"not-running",ready:false};if(pending.policy){try{let live=mode==="repair"?await control.host(["status"]):{running:false};const interrupted=await residentInterruption(pending.root)!==pending.interruption;if(interrupted)pending.restartPending=false;if(pending.restartPending){const identity2=runtime(live.runtime);if(live.running&&(!identity2||!samePath(identity2.installationPath,lease.installationPath)||identity2.version!==version)){if(identity2?.version!==pending.fromVersion)throw new DeferredUpdate("resident_version_mismatch");await control.stop(owner(live,lease.installationPath,pending.fromVersion));live={running:false}}if(!live.running){await control.host(["start"]);live=await control.host(["status"])}}const identity=runtime(live.runtime),paused=live.update?.paused===true;if(live.running){if(live.ready!==true||!identity||!samePath(identity.installationPath,lease.installationPath)||identity.version!==version||identity.policy.autoConnect!==pending.policy.autoConnect||identity.policy.autoSync!==pending.policy.autoSync)throw Error("Resident activation could not be verified.");activation={state:mode==="repair"?"running":mode,ready:true,runningVersion:version,...paused?{paused:true}:{}};pending.restartPending=false}else if(pending.restartPending)throw Error("Resident activation could not be verified.");else if(interrupted)activation={state:"not-running",ready:false,reason:"resident_control_changed"}}catch(error){activation={state:"failed",ready:false,reason:error instanceof DeferredUpdate?error.reason:"resident_restart_unconfirmed"}}}else if(mode==="repair"){try{const live=await control.host(["status"]),identity=runtime(live.runtime);if(live.running){if(live.ready!==true||!identity||!samePath(identity.installationPath,lease.installationPath)||identity.version!==version)throw Error("Resident activation could not be verified.");activation={state:"running",ready:true,runningVersion:version,...live.update?.paused===true?{paused:true}:{}}}}catch{activation={state:"failed",ready:false,reason:"resident_status_unconfirmed"}}}if(version===pending.fromVersion)pending.refreshPending=false;let agent=pending.agent??{state:"not-needed",reconnectRequired:false};if(pending.refreshPending){agent=await control.refresh();pending.agent=agent;if(!["failed","unavailable"].includes(agent.state))pending.refreshPending=false}const remaining=pending.restartPending||pending.refreshPending;await savePendingHandover(lease.installationPath,remaining?pending:void 0);return{activation,agent,pending:remaining,installedVersion:version}}export async function updateInstalledProduct(options={}){const updater=options.updater??productUpdater,local=await updater.status();if(!updater.updatesEnabled)return local;let currentVersion=local.currentVersion,targetVersion;const deferred=reason=>({state:"deferred",currentVersion,...targetVersion?{targetVersion}:{},reason});let prior;try{prior=await readPendingHandover(updater.installationPath)}catch{return{state:"failed",currentVersion,reason:"handover_state_unavailable"}}let repaired;if(prior){if(options.root!==void 0){const selected=await realpath(options.root).catch(()=>options.root);if(!samePath(selected,prior.root))return deferred("pending_handover_different_root")}try{repaired=await updater.withInstallationLock(async lease=>{const pending2=await readPendingHandover(lease.installationPath);return pending2?finishHandover(lease,pending2,"repair"):void 0});if(repaired){currentVersion=repaired.installedVersion;if(repaired.pending)return{...deferred("handover_pending"),root:prior.root,...repaired}}}catch(error){return{...deferred(error instanceof DeferredUpdate?error.reason:"handover_retry_failed"),root:prior.root,activation:{state:"failed",ready:false,reason:"resident_restart_unconfirmed"}}}}const offer=await updater.check({force:true});currentVersion=offer.currentVersion;targetVersion=offer.targetVersion;if(repaired&&prior&&offer.state!=="available")return{state:offer.state==="current"?"current":"repaired",currentVersion,root:prior.root,...repaired,...offer.state!=="current"?{update:offer}:{}};if(!["available","current"].includes(offer.state))return offer;if(offer.state!=="available")return{...offer,activation:{state:"not-checked",reason:"no_pending_handover"}};let root;try{if(options.root!==void 0)root=options.root;else{const{resolveInstalledVaultRoot}=await import("./codex-install.js");root=await resolveInstalledVaultRoot({output:join(offer.installationPath,"codex")})??await configuredVaultRoot({catalogFile:join(offer.installationPath,"codex/plugins/zortex/.mcp.json")})}if(!isAbsolute(root))throw Error("Vault path must be absolute.");root=await realpath(root).catch(error=>{if(error.code==="ENOENT")return root;throw error})}catch{return deferred("vault_binding_unavailable")}let pending,activation={state:"not-checked"},agent,remaining=false,stopUnconfirmed=false;try{const installed=await updater.apply({version:offer.targetVersion,confirmationToken:offer.confirmationToken},{before:async lease=>{if(await readPendingHandover(lease.installationPath))throw new DeferredUpdate("previous_handover_pending");const interruption=await residentInterruption(root),control=controls(lease,{root,interruption});let previous;try{const exists=await realpath(root).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error});previous=exists?await control.host(["status"]):{running:false}}catch{throw new DeferredUpdate("resident_unavailable")}const expected=previous.running?owner(previous,lease.installationPath,offer.currentVersion):void 0;pending={schemaVersion:1,root,fromVersion:offer.currentVersion,targetVersion:offer.targetVersion,interruption,...previous.running?{policy:runtime(previous.runtime).policy}:{},restartPending:previous.running,refreshPending:true};await savePendingHandover(lease.installationPath,pending);try{if(expected)await control.stop(expected)}catch(error){if(error instanceof DeferredUpdate&&error.reason==="resident_stop_unconfirmed")stopUnconfirmed=true;else{pending=void 0;await savePendingHandover(lease.installationPath)}throw error}},after:async(lease,outcome)=>{if(!pending)return;if(stopUnconfirmed){activation={state:"failed",ready:false,reason:"resident_stop_unconfirmed"};remaining=true;return}if(outcome==="recovery-required"){activation={state:"failed",ready:false,reason:"update_recovery_required"};remaining=true;return}try{const result=await finishHandover(lease,pending,outcome==="updated"?"restarted":"restored");activation=result.activation;agent=result.agent;remaining=result.pending}catch(error){activation={state:"failed",ready:false,reason:error instanceof DeferredUpdate?error.reason:"handover_state_unavailable"};remaining=true}}});return{...installed,root,activation,...agent?{agent}:{},pending:remaining}}catch(error){if(error instanceof DeferredUpdate)return{...deferred(error.reason),...remaining?{root,activation,pending:true}:{}};return{state:"failed",currentVersion:offer.currentVersion,targetVersion:offer.targetVersion,root,reason:"update_failed",message:error instanceof Error?error.message:"Update failed.",activation,pending:remaining}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID}from"node:crypto";import{lstat,mkdir,readFile,realpath,rm}from"node:fs/promises";import{isAbsolute,join}from"node:path";import{atomicWrite}from"./update-recovery.js";const handoverFile=installation=>join(installation,".zortex-update-handover.json");const interruptionFile=root=>join(root,"host","update-interruption.json");const version=value=>typeof value==="string"&&/^[0-9A-Za-z.+-]{1,80}$/.test(value);const revision=value=>value==="none"||typeof value==="string"&&/^[a-f0-9-]{36}$/.test(value);async function read(path){const info=await lstat(path).catch(error=>{if(error.code==="ENOENT")return;throw error});if(!info)return;if(!info.isFile()||info.isSymbolicLink()||info.size>16384)throw Error("Invalid update handover metadata.");return JSON.parse(await readFile(path,"utf8"))}export async function readPendingHandover(installation){const value=await read(handoverFile(installation));if(value===void 0)return;if(value.schemaVersion!==1||typeof value.root!=="string"||!isAbsolute(value.root)||!version(value.fromVersion)||!version(value.targetVersion)||!revision(value.interruption)||typeof value.restartPending!=="boolean"||typeof value.refreshPending!=="boolean"||value.restartPending&&!value.policy||value.policy!==void 0&&(!value.policy||typeof value.policy.autoConnect!=="boolean"||typeof value.policy.autoSync!=="boolean")||value.agent!==void 0&&(!value.agent||typeof value.agent.state!=="string"||!/^[a-z][a-z-]{0,79}$/.test(value.agent.state)||typeof value.agent.reconnectRequired!=="boolean"))throw Error("Invalid update handover metadata.");return value}export async function savePendingHandover(installation,value){if(!value){await rm(handoverFile(installation),{force:true});return}await atomicWrite(handoverFile(installation),Buffer.from(JSON.stringify(value)+"\n"))}export async function residentInterruption(root){const value=await read(interruptionFile(root));if(value===void 0)return"none";if(!revision(value.revision)||!["stop","pause"].includes(value.action))throw Error("Invalid resident interruption metadata.");return value.revision}export async function markResidentInterruption(root,action){if(!isAbsolute(root))throw Error("Resident Vault path must be absolute");root=await realpath(root);await mkdir(join(root,"host"),{recursive:true,mode:448});await atomicWrite(interruptionFile(root),Buffer.from(JSON.stringify({revision:randomUUID(),action})+"\n"))}
|
package/dist/update-recovery.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{readFile,mkdir,lstat,realpath,rename,cp,rm,open,link}from"node:fs/promises";import{resolve,join,dirname}from"node:path";import{fileURLToPath}from"node:url";const NAME="@zortexhq/indra-v2.5";export const JOURNAL=".zortex-update-state.json";export const RECOVERY_FILE="dist/update-recovery.js";const jsonBytes=value=>Buffer.from(JSON.stringify(value,null,2)+"\n");export function safePath(path){if(typeof path!=="string"||path.length>1023||!path||/[\\:<>"|?*\x00-\x1f\x7f]/.test(path)||path.startsWith("/")||path.split("/").some(p=>!p||p==="."||p===".."||/[. ]$/.test(p)||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p))||path.startsWith(".zortex-update"))throw Error("Unsafe update path.")}export async function safeFile(root,path){safePath(path);let current=root;for(const part of path.split("/")){current=join(current,part);const info=await lstat(current).catch(error=>{if(error.code==="ENOENT")return null;throw error});if(info?.isSymbolicLink())throw Error("Refusing a symlink in the update destination.")}return current}export async function optionalBytes(path){return readFile(path).catch(error=>{if(error.code==="ENOENT")return null;throw error})}export function dependencyPath(path){safePath(path);if(!/^node_modules\/(?:\.[b]in|(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+)$/i.test(path))throw Error("Invalid dependency update path.")}export async function atomicWrite(path,bytes,mode=384){const temporary=path+"."+randomUUID()+".tmp";try{const file=await open(temporary,"wx",384);try{await file.writeFile(bytes);await file.chmod(mode);await file.sync()}finally{await file.close()}await rename(temporary,path)}finally{await rm(temporary,{force:true})}}function processAlive(pid){if(!Number.isSafeInteger(pid)||pid<=0)throw Error("Invalid update lock owner.");try{process.kill(pid,0);return true}catch(error){return error.code!=="ESRCH"}}export function createUpdateRecovery(requestedPackageRoot=fileURLToPath(new URL("..",import.meta.url))){let packageRoot=resolve(requestedPackageRoot);const requestedRoot=packageRoot;let rootIsLinked=false,rootReady;const canonicalizeRoot=()=>rootReady??=(async()=>{rootIsLinked=(await lstat(requestedRoot)).isSymbolicLink();packageRoot=await realpath(requestedRoot)})();const pkg=async()=>JSON.parse(await readFile(join(packageRoot,"package.json"),"utf8"));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 rollback(journal){for(const directory of[join(packageRoot,journal.stage),join(packageRoot,journal.stage,"backup")]){if((await lstat(directory).catch(()=>void 0))?.isSymbolicLink())throw Error("Refusing a symlink in update recovery files.")}for(const file of[...journal.files].reverse()){const destination=await safeFile(packageRoot,file.path);const backup=await safeFile(join(packageRoot,journal.stage,"backup"),file.path);if(file.kind==="directory"){dependencyPath(file.path);if(file.existed&&!(await lstat(backup).catch(()=>void 0))?.isDirectory())throw Error("Update recovery backup is missing; recovery files were retained.");await rm(destination,{recursive:true,force:true});if(file.existed){await mkdir(dirname(destination),{recursive:true});await cp(backup,destination,{recursive:true,verbatimSymlinks:true})}continue}if(file.existed){const bytes=await optionalBytes(backup);if(!bytes)throw Error("Update recovery backup is missing; recovery files were retained.");await mkdir(dirname(destination),{recursive:true});await atomicWrite(destination,bytes,(await lstat(backup)).mode&511)}else{await rm(destination,{force:true})}}}async function publishLock(path){const bytes=Buffer.from(process.pid+"\n"+randomUUID());const temporary=path+"."+randomUUID()+".tmp";await atomicWrite(temporary,bytes);try{await link(temporary,path)}finally{await rm(temporary,{force:true})}return async()=>{const current=await optionalBytes(path);if(current?.equals(bytes))await rm(path,{force:true})}}const lockPid=bytes=>Number(bytes.toString("utf8").split("\n")[0]);async function withRecoveryLock(action){await canonicalizeRoot();const path=join(packageRoot,".zortex-update-recovery.lock");let release;for(let attempt=0;attempt<2&&!release;attempt++){try{release=await publishLock(path)}catch(error){if(error.code!=="EEXIST")throw error;const owner=await optionalBytes(path);if(!owner||processAlive(lockPid(owner)))throw Error("Update recovery is running. Retry when it finishes.")
|
|
1
|
+
import{randomUUID}from"node:crypto";import{readFileSync}from"node:fs";import{readFile,mkdir,lstat,realpath,rename,cp,rm,open,link}from"node:fs/promises";import{resolve,join,dirname}from"node:path";import{fileURLToPath}from"node:url";const NAME="@zortexhq/indra-v2.5";export const JOURNAL=".zortex-update-state.json";export const RECOVERY_FILE="dist/update-recovery.js";const jsonBytes=value=>Buffer.from(JSON.stringify(value,null,2)+"\n");let startupVersion;export const installedStartupVersion=()=>startupVersion;export function safePath(path){if(typeof path!=="string"||path.length>1023||!path||/[\\:<>"|?*\x00-\x1f\x7f]/.test(path)||path.startsWith("/")||path.split("/").some(p=>!p||p==="."||p===".."||/[. ]$/.test(p)||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p))||path.startsWith(".zortex-update"))throw Error("Unsafe update path.")}export async function safeFile(root,path){safePath(path);let current=root;for(const part of path.split("/")){current=join(current,part);const info=await lstat(current).catch(error=>{if(error.code==="ENOENT")return null;throw error});if(info?.isSymbolicLink())throw Error("Refusing a symlink in the update destination.")}return current}export async function optionalBytes(path){return readFile(path).catch(error=>{if(error.code==="ENOENT")return null;throw error})}export function dependencyPath(path){safePath(path);if(!/^node_modules\/(?:\.[b]in|(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+)$/i.test(path))throw Error("Invalid dependency update path.")}export async function atomicWrite(path,bytes,mode=384){const temporary=path+"."+randomUUID()+".tmp";try{const file=await open(temporary,"wx",384);try{await file.writeFile(bytes);await file.chmod(mode);await file.sync()}finally{await file.close()}await rename(temporary,path)}finally{await rm(temporary,{force:true})}}function processAlive(pid){if(!Number.isSafeInteger(pid)||pid<=0)throw Error("Invalid update lock owner.");try{process.kill(pid,0);return true}catch(error){return error.code!=="ESRCH"}}export function createUpdateRecovery(requestedPackageRoot=fileURLToPath(new URL("..",import.meta.url))){let packageRoot=resolve(requestedPackageRoot);const requestedRoot=packageRoot;let rootIsLinked=false,rootReady;const canonicalizeRoot=()=>rootReady??=(async()=>{rootIsLinked=(await lstat(requestedRoot)).isSymbolicLink();packageRoot=await realpath(requestedRoot)})();const pkg=async()=>JSON.parse(await readFile(join(packageRoot,"package.json"),"utf8"));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 rollback(journal){for(const directory of[join(packageRoot,journal.stage),join(packageRoot,journal.stage,"backup")]){if((await lstat(directory).catch(()=>void 0))?.isSymbolicLink())throw Error("Refusing a symlink in update recovery files.")}for(const file of[...journal.files].reverse()){const destination=await safeFile(packageRoot,file.path);const backup=await safeFile(join(packageRoot,journal.stage,"backup"),file.path);if(file.kind==="directory"){dependencyPath(file.path);if(file.existed&&!(await lstat(backup).catch(()=>void 0))?.isDirectory())throw Error("Update recovery backup is missing; recovery files were retained.");await rm(destination,{recursive:true,force:true});if(file.existed){await mkdir(dirname(destination),{recursive:true});await cp(backup,destination,{recursive:true,verbatimSymlinks:true})}continue}if(file.existed){const bytes=await optionalBytes(backup);if(!bytes)throw Error("Update recovery backup is missing; recovery files were retained.");await mkdir(dirname(destination),{recursive:true});await atomicWrite(destination,bytes,(await lstat(backup)).mode&511)}else{await rm(destination,{force:true})}}}async function publishLock(path){const bytes=Buffer.from(process.pid+"\n"+randomUUID());const temporary=path+"."+randomUUID()+".tmp";await atomicWrite(temporary,bytes);try{await link(temporary,path)}finally{await rm(temporary,{force:true})}return Object.assign(async()=>{const current=await optionalBytes(path);if(current?.equals(bytes))await rm(path,{force:true})},{token:bytes.toString("utf8")})}const lockPid=bytes=>Number(bytes.toString("utf8").split("\n")[0]);async function withRecoveryLock(action,allowReadOnly=false){await canonicalizeRoot();const path=join(packageRoot,".zortex-update-recovery.lock");let release;const claimDeadline=Date.now()+2e3;for(let attempt=0;attempt<2&&!release;attempt++){try{release=await publishLock(path)}catch(error){if(allowReadOnly&&["EACCES","EROFS"].includes(String(error.code))&&!await optionalBytes(join(packageRoot,".zortex-update.lock"))&&!await optionalBytes(join(packageRoot,JOURNAL)))return action();if(error.code!=="EEXIST")throw error;const owner=await optionalBytes(path);if(!owner||processAlive(lockPid(owner))){if(allowReadOnly&&Date.now()<claimDeadline){await new Promise(resolve2=>setTimeout(resolve2,20));attempt--;continue}throw Error("Update recovery is running. Retry when it finishes.")}if((await optionalBytes(path))?.equals(owner))await rm(path,{force:true})}}if(!release)throw Error("Update recovery holds the installation lock. Retry when it finishes.");try{return await action()}finally{await release()}}async function recoverLocked(permit){const lock=await optionalBytes(join(packageRoot,".zortex-update.lock"));const locked=lock&&processAlive(lockPid(lock));if(locked&&permit!==lock.toString("utf8"))throw Error("An update is running. Retry when it finishes.");const data=await optionalBytes(join(packageRoot,JOURNAL));if(!data){if(lock&&!locked)await rm(join(packageRoot,".zortex-update.lock"),{force:true});return}const journal=JSON.parse(data.toString("utf8"));if(journal.schemaVersion!==1||!/^\.zortex-update-[a-f0-9-]{36}$/.test(journal.stage)||!Array.isArray(journal.files)||journal.files.length>18004||!["applying","committed"].includes(journal.phase))throw Error("Invalid update recovery journal.");for(const file of journal.files){safePath(file.path);if(typeof file.existed!=="boolean"||file.kind!==void 0&&file.kind!=="directory")throw Error("Invalid update recovery entry.");if(file.kind==="directory")dependencyPath(file.path)}const alive=processAlive(journal.pid);if(alive&&journal.phase==="applying")throw Error("An update is being applied. Retry when it finishes.");if(alive)return;if(journal.phase==="applying"){await rollback(journal);await atomicWrite(join(packageRoot,JOURNAL),jsonBytes({...journal,phase:"committed"}))}await rm(join(packageRoot,journal.stage),{recursive:true,force:true});await rm(join(packageRoot,JOURNAL),{force:true});await rm(join(packageRoot,".zortex-update.lock"),{force:true})}async function recover(permit=process.env.ZORTEX_UPDATE_HANDOVER){await canonicalizeRoot();if(!await optionalBytes(join(packageRoot,JOURNAL))&&!await optionalBytes(join(packageRoot,".zortex-update.lock"))&&!await optionalBytes(join(packageRoot,".zortex-update-recovery.lock")))return;await writableInstallation();await withRecoveryLock(()=>recoverLocked(permit))}async function withResidentClaim(action,loadedVersion){return withRecoveryLock(async()=>{await recoverLocked(process.env.ZORTEX_UPDATE_HANDOVER);if(loadedVersion!==void 0&&(await pkg()).version!==loadedVersion)throw Error("The installed runtime changed. Start it again from the updated installation.");return action()},true)}return{recover,recoverLocked,withRecoveryLock,withResidentClaim,publishLock,rollback}}export async function recoverInstalledUpdate(){const recovery=createUpdateRecovery();const version=()=>{const value=JSON.parse(readFileSync(new URL("../package.json",import.meta.url),"utf8")).version;if(typeof value!=="string"||!/^[0-9A-Za-z.+-]{1,80}$/.test(value))throw Error("The installed runtime version is unavailable.");return value};if(startupVersion!==void 0){if(process.env.ZORTEX_UPDATE_VERIFY!=="1")await recovery.recover();return}for(let attempt=0;attempt<2;attempt++){const before=version();if(process.env.ZORTEX_UPDATE_VERIFY!=="1")await recovery.recover();if(version()===before){startupVersion=before;return}}throw Error("The installed runtime changed during startup. Start it again.")}
|
package/dist/update-tool.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{productUpdater}from"./auto-update.js";export const updateTool={name:"indra.update",description:"
|
|
1
|
+
import{productUpdater}from"./auto-update.js";async function update(updater,options={}){if(updater.update)return updater.update(options);if(updater!==productUpdater)throw Error("The installed update lifecycle is unavailable.");const{updateInstalledProduct}=await import("./update-command.js");return updateInstalledProduct(options)}export function bindProductUpdateRoot(updater,root){return{...updater,update:()=>update(updater,{root})}}export const updateTool={name:"indra.update",description:"Update Zortex in one call with no input. The product checks the current release, verifies and installs it, and hands over an idle background host while preserving the Vault and saved choices. Active work or an explicit pause defers activation. check and exact-offer apply remain recovery operations.",inputSchema:{type:"object",properties:{operation:{type:"string",enum:["update","check","apply"],default:"update"},version:{type:"string",description:"Exact target version returned by check."},confirmationToken:{type:"string",description:"Opaque release-offer identifier returned by check; binds the version and manifest, with no human confirmation step."}},additionalProperties:false},annotations:{readOnlyHint:false,destructiveHint:true,openWorldHint:true,idempotentHint:false}};export async function callUpdateTool(args,updater=productUpdater){try{if(Object.keys(args).some(key=>!["operation","version","confirmationToken","confirmed"].includes(key)))throw Error("Unknown update argument.");if(!Object.keys(args).length||args.operation==="update"&&Object.keys(args).length===1){return{ok:await update(updater)}}if(args.operation==="check"&&Object.keys(args).length===1)return{ok:await updater.check({force:true})};if(args.operation!=="apply"||typeof args.version!=="string"||typeof args.confirmationToken!=="string")throw Error("Call update without input. For recovery, use check or apply with its exact version and confirmationToken.");return{ok:await updater.apply({version:args.version,confirmationToken:args.confirmationToken})}}catch(error){return{err:{code:"failed_precondition",layer:"service",message:error instanceof Error?error.message:"Update failed."}}}}
|
package/dist/web.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{validateJoplinResult}from"./joplin-selection.js";import{lstat,readFile}from"node:fs/promises";import{isAbsolute,resolve}from"node:path";import*as galaxy from"@zortexhq/plugin-galaxy-ui";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{openProduct}from"./profile.js";import{readPublicActionProgress}from"./public-action-progress.js";import{provideAutoSync}from"./auto-sync.js";import{chooseWebPort}from"./web-port.js";import{residentStatus,startResident,residentConnect,residentConnectRecovery,residentConnectReauthorize,residentConnectReadwiseMcpWrite,residentConnectGmailWrite,residentConnectManual,residentReconnectSaved,residentConnectJob,residentCancelConnect,residentConnectorStatus,residentConfigureNativeFiles,residentConfigureZotero,residentConfigureOwnTracks,residentConfigureZoom,residentConfigureBox,residentConfigureFront,residentConfigureHubSpot,residentConfigureGoogleContacts,residentConfigureGoogleChat,residentConfigureSalesforce,residentConfigureZendesk,residentConfigureDropbox,residentConfigureDiscord,residentConfigureProtonMail,residentConfigureJoplin,residentConfigureThunderbird,residentConfigureWeChat,residentConfigureCopyQ,residentConfigureFreshdesk,residentConfigureFigma,residentConfigureSmartsheet,residentConfigureNextcloud,residentConfigureZulip,residentConfigureFreshRSS,residentConfigureMiniflux,residentConfigureMattermost,residentConfigureWallabag,residentConfigureCalcom,residentConfigureWakatime,residentGatewayCall,residentCheck,residentRead}from"./resident-platform.js";import{fileURLToPath}from"node:url";import{HELP_CATALOG}from"./source-catalog.js";import{startGuidedRecovery,validateNativeFileResult}from"./recovery.js";import{mergedRecoveryProgress}from"./recovery-progress.js";import{sourceSupport,recoverySetupFlags}from"./recovery-support.js";export const WEB_USAGE="Use indra web --root <absolute directory> [--port 8781] [--no-open].";const entrypoint=fileURLToPath(new URL("./cli.js",import.meta.url));export function parseWebArgs(argv){let root,port=8781,portChosen=false,noOpen=false;for(let i=0;i<argv.length;i++){const arg=argv[i];if(arg==="--root"){if(root||!argv[i+1])throw Error("Pass one --root.");root=argv[++i]}else if(arg==="--port"){const value=argv[++i];if(!value||!/^\d{1,5}$/.test(value)||Number(value)>65535)throw Error("Port must be 0-65535.");port=Number(value);portChosen=true}else if(arg==="--no-open")noOpen=true;else throw Error(WEB_USAGE)}if(!root||!isAbsolute(root))throw Error("An explicit absolute data root is required.");return{root:resolve(root),port,portChosen,noOpen}}export async function launchWeb(argv){const options=parseWebArgs(argv);const productVersion=JSON.parse(await readFile(new URL("../package.json",import.meta.url),"utf8")).version;if(await lstat(options.root).then(stat=>stat.isSymbolicLink(),error=>{if(error.code==="ENOENT")return false;throw error}))throw Error("Product root cannot be a link.");const chosen=await chooseWebPort(options.port,options.portChosen);const app=await openProduct(options.root);const stop=new AbortController;let connectionSession;let openingConnections;const residentReport=async()=>{const result=await residentGatewayCall(options.root,{operation:"manage",args:{what:"onboarding"}},stop.signal);if(!("ok"in result))throw Error("The background connection report is unavailable.");return result.ok};const authorization={reconnectSaved:(source,signal)=>residentReconnectSaved(options.root,source,signal),check:(source,signal)=>residentCheck(options.root,source,signal),status:signal=>residentConnectorStatus(options.root,signal),read:(source,request,signal)=>residentRead(options.root,source,request,signal),connect:async(source,requestId,signal,settings)=>{await startResident(options.root,entrypoint);return settings?.gmailWrite?residentConnectGmailWrite(options.root,requestId,signal):settings?.readwiseMcpWrite?residentConnectReadwiseMcpWrite(options.root,requestId,signal):settings?.selectAccount?residentConnectRecovery(options.root,source,requestId,signal):settings?.reauthorize?residentConnectReauthorize(options.root,source,requestId,signal):settings?.manualPresentation==="return-url"?residentConnectManual(options.root,source,requestId,signal):residentConnect(options.root,source,requestId,signal,{automatic:false})},job:async(requestId,signal)=>{await startResident(options.root,entrypoint);return residentConnectJob(options.root,requestId,signal)},cancel:(requestId,generation,challengeRef)=>residentCancelConnect(options.root,requestId,generation,challengeRef),configureWeChat:async(port,signal)=>validateNativeFileResult("wechat",await residentConfigureWeChat(options.root,port,signal)),configureJoplin:async(selection,signal)=>validateJoplinResult(await residentConfigureJoplin(options.root,selection,signal)),configureThunderbird:async(port,signal)=>validateNativeFileResult("thunderbird",await residentConfigureThunderbird(options.root,port,signal)),configureDiscord:async(selection,signal)=>validateNativeFileResult("discord",await residentConfigureDiscord(options.root,selection,signal)),configureProtonMail:async(port,signal)=>validateNativeFileResult("proton-mail",await residentConfigureProtonMail(options.root,port,signal)),configureZulip:async(selection,signal)=>validateNativeFileResult("zulip",await residentConfigureZulip(options.root,selection,signal)),configureFreshRSS:async(selection,signal)=>validateNativeFileResult("freshrss",await residentConfigureFreshRSS(options.root,selection,signal)),configureMiniflux:async(selection,signal)=>validateNativeFileResult("miniflux",await residentConfigureMiniflux(options.root,selection,signal)),configureMattermost:async(selection,signal)=>validateNativeFileResult("mattermost",await residentConfigureMattermost(options.root,selection,signal)),configureWallabag:async(selection,signal)=>validateNativeFileResult("wallabag",await residentConfigureWallabag(options.root,selection,signal)),configureCalcom:async(selection,signal)=>validateNativeFileResult("calcom",await residentConfigureCalcom(options.root,selection,signal)),configureWakatime:async(selection,signal)=>validateNativeFileResult("wakatime",await residentConfigureWakatime(options.root,selection,signal)),configureNextcloud:async(instanceUrl,signal)=>validateNativeFileResult("nextcloud",await residentConfigureNextcloud(options.root,instanceUrl,signal)),configureZoom:async(selection,signal)=>validateNativeFileResult("zoom",await residentConfigureZoom(options.root,selection,signal)),configureBox:async(selection,signal)=>validateNativeFileResult("box",await residentConfigureBox(options.root,selection,signal)),configureFront:async(selection,signal)=>validateNativeFileResult("front",await residentConfigureFront(options.root,selection,signal)),configureHubSpot:async(selection,signal)=>validateNativeFileResult("hubspot",await residentConfigureHubSpot(options.root,selection,signal)),configureGoogleContacts:async(selection,signal)=>validateNativeFileResult("google-contacts",await residentConfigureGoogleContacts(options.root,selection,signal)),configureGoogleChat:async(selection,signal)=>validateNativeFileResult("google-chat",await residentConfigureGoogleChat(options.root,selection,signal)),configureSalesforce:async(selection,signal)=>validateNativeFileResult("salesforce",await residentConfigureSalesforce(options.root,selection,signal)),configureZendesk:async(selection,signal)=>validateNativeFileResult("zendesk",await residentConfigureZendesk(options.root,selection,signal)),configureDropbox:async(selection,signal)=>validateNativeFileResult("dropbox",await residentConfigureDropbox(options.root,selection,signal)),configureFigma:async(mode,signal)=>validateNativeFileResult("figma",await residentConfigureFigma(options.root,mode,signal)),configureSmartsheet:async(region,signal)=>validateNativeFileResult("smartsheet",await residentConfigureSmartsheet(options.root,region,signal)),configureFreshdesk:async(subdomain,signal)=>validateNativeFileResult("freshdesk",await residentConfigureFreshdesk(options.root,subdomain,signal)),configureCopyQ:async(executable,session,signal)=>validateNativeFileResult("copyq",await residentConfigureCopyQ(options.root,executable,session,signal)),configureOwnTracks:async(port,signal)=>validateNativeFileResult("owntracks",await residentConfigureOwnTracks(options.root,port,signal)),configureZotero:async(libraryId,libraryType,signal)=>validateNativeFileResult("zotero",await residentConfigureZotero(options.root,libraryId,libraryType,signal)),configureNativeFiles:async(source,roots,signal)=>validateNativeFileResult(source,await residentConfigureNativeFiles(options.root,source,roots,signal))};const connectionRequest=async(input,signal)=>{if(!connectionSession||connectionSession.snapshot().state==="closed"){openingConnections??=residentReport().then(report=>startGuidedRecovery(app.context,{sources:report.sources,authorization}));try{connectionSession=await openingConnections}finally{openingConnections=void 0}}return connectionSession.request(input,signal)};try{await startResident(options.root,entrypoint);provideAutoSync(app.context,options.root,{residentStatus:async()=>{const value=(await residentStatus(options.root)).autoSync;return Array.isArray(value)?value:[]}});const page=app.context.plugin(galaxy,{productVersion,port:chosen.port,connectionRequest,directorySources:HELP_CATALOG.map(([source])=>source),sourceProgress:async()=>mergedRecoveryProgress(app.context),sourceSupport:async()=>{const result=await authorization.status(stop.signal);if(!("ok"in result))throw Error("Resident connector support unavailable");const listed=new Set(result.ok.map(row=>row.source));const states=[...result.ok,...(result.pending??[]).filter(row=>!listed.has(row.source)).map(row=>({source:row.source,state:"unavailable",registration:"deferred"}))];for(const row of states)listed.add(row.source);return[...states.map(row=>sourceSupport({...row,connection:row.state,...result.pending?.find(item=>item.source===row.source)?.reason?{setupReason:result.pending.find(item=>item.source===row.source).reason}:{}},Object.keys(recoverySetupFlags(row.source,authorization)).length>0)),...HELP_CATALOG.filter(([source])=>!listed.has(source)&&!(source==="teams"&&listed.has("microsoft-teams"))).map(([source])=>sourceSupport({source,catalogOnly:true},false))]},connectionStatus:async()=>{const result=await authorization.status(stop.signal);if(!("ok"in result))throw Error("Resident connector status unavailable");const report=await residentReport().catch(()=>null);const reads=new Map((report?.sources??[]).filter(row=>row.connection==="connected"&&!row.errorCode&&(row.availability==="read"||row.availability==="actions")&&row.operation==="succeeded"&&Number.isSafeInteger(row.returned)&&row.returned>=0&&(row.returned>0?row.read==="first-record":row.read==="empty")).map(row=>[row.source,row.returned]));const publicReads=new Map(readPublicActionProgress(app.context).map(item=>[item.source,item]));return result.ok.map(row=>{const publicRead=publicReads.get(row.source);return{...row,...row.state==="connected"&&reads.has(row.source)?{readEvidence:{state:"succeeded",returned:reads.get(row.source)}}:{},...publicRead?{publicRead}:{}}})}});await page.await();if(page.state!==2)throw Error("The Galaxy page did not start.");const{url,port}=app.context.zortexGalaxyPage;let opened=false;if(!options.noOpen)try{await openConnectionUrl(url);opened=true}catch{}process.stdout.write(JSON.stringify({port,version:productVersion,url,opened,...chosen.moved?{notice:`Port ${options.port} is used by another program, possibly an older Zortex window, so this version opened on port ${port}.`}:{}})+"\n");process.stdout.write(`zortex web: ${url}
|
|
1
|
+
import{lstat,readFile}from"node:fs/promises";import{isAbsolute,resolve}from"node:path";import*as galaxy from"@zortexhq/plugin-galaxy-ui";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{openProduct}from"./profile.js";import{readPublicActionProgress}from"./public-action-progress.js";import{provideAutoSync}from"./auto-sync.js";import{chooseWebPort}from"./web-port.js";import{residentStatus,startResident,residentGatewayCall}from"./resident-platform.js";import{fileURLToPath}from"node:url";import{HELP_CATALOG}from"./source-catalog.js";import{startGuidedRecovery}from"./recovery.js";import{residentRecoveryAuthorization}from"./recovery-resident-port.js";import{mergedRecoveryProgress}from"./recovery-progress.js";import{sourceSupport,recoverySetupFlags}from"./recovery-support.js";export const WEB_USAGE="Use indra web --root <absolute directory> [--port 8781] [--no-open].";const entrypoint=fileURLToPath(new URL("./cli.js",import.meta.url));export function parseWebArgs(argv){let root,port=8781,portChosen=false,noOpen=false;for(let i=0;i<argv.length;i++){const arg=argv[i];if(arg==="--root"){if(root||!argv[i+1])throw Error("Pass one --root.");root=argv[++i]}else if(arg==="--port"){const value=argv[++i];if(!value||!/^\d{1,5}$/.test(value)||Number(value)>65535)throw Error("Port must be 0-65535.");port=Number(value);portChosen=true}else if(arg==="--no-open")noOpen=true;else throw Error(WEB_USAGE)}if(!root||!isAbsolute(root))throw Error("An explicit absolute data root is required.");return{root:resolve(root),port,portChosen,noOpen}}export async function launchWeb(argv){const options=parseWebArgs(argv);const productVersion=JSON.parse(await readFile(new URL("../package.json",import.meta.url),"utf8")).version;if(await lstat(options.root).then(stat=>stat.isSymbolicLink(),error=>{if(error.code==="ENOENT")return false;throw error}))throw Error("Product root cannot be a link.");const chosen=await chooseWebPort(options.port,options.portChosen);const app=await openProduct(options.root);const stop=new AbortController;let connectionSession;let openingConnections;const residentReport=async()=>{const result=await residentGatewayCall(options.root,{operation:"manage",args:{what:"onboarding"}},stop.signal);if(!("ok"in result))throw Error("The background connection report is unavailable.");return result.ok};const authorization=residentRecoveryAuthorization(options.root);const connectionRequest=async(input,signal)=>{if(!connectionSession||connectionSession.snapshot().state==="closed"){openingConnections??=residentReport().then(report=>startGuidedRecovery(app.context,{sources:report.sources,authorization}));try{connectionSession=await openingConnections}finally{openingConnections=void 0}}return connectionSession.request(input,signal)};try{await startResident(options.root,entrypoint);provideAutoSync(app.context,options.root,{residentStatus:async()=>{const value=(await residentStatus(options.root)).autoSync;return Array.isArray(value)?value:[]}});const page=app.context.plugin(galaxy,{productVersion,port:chosen.port,connectionRequest,directorySources:HELP_CATALOG.map(([source])=>source),sourceProgress:async()=>mergedRecoveryProgress(app.context),sourceSupport:async()=>{const result=await authorization.status(stop.signal);if(!("ok"in result))throw Error("Resident connector support unavailable");const listed=new Set(result.ok.map(row=>row.source));const states=[...result.ok,...(result.pending??[]).filter(row=>!listed.has(row.source)).map(row=>({source:row.source,state:"unavailable",registration:"deferred"}))];for(const row of states)listed.add(row.source);return[...states.map(row=>sourceSupport({...row,connection:row.state,...result.pending?.find(item=>item.source===row.source)?.reason?{setupReason:result.pending.find(item=>item.source===row.source).reason}:{}},Object.keys(recoverySetupFlags(row.source,authorization)).length>0)),...HELP_CATALOG.filter(([source])=>!listed.has(source)&&!(source==="teams"&&listed.has("microsoft-teams"))).map(([source])=>sourceSupport({source,catalogOnly:true},false))]},connectionStatus:async()=>{const result=await authorization.status(stop.signal);if(!("ok"in result))throw Error("Resident connector status unavailable");const report=await residentReport().catch(()=>null);const reads=new Map((report?.sources??[]).filter(row=>row.connection==="connected"&&!row.errorCode&&(row.availability==="read"||row.availability==="actions")&&row.operation==="succeeded"&&Number.isSafeInteger(row.returned)&&row.returned>=0&&(row.returned>0?row.read==="first-record":row.read==="empty")).map(row=>[row.source,row.returned]));const publicReads=new Map(readPublicActionProgress(app.context).map(item=>[item.source,item]));return result.ok.map(row=>{const publicRead=publicReads.get(row.source);return{...row,...row.state==="connected"&&reads.has(row.source)?{readEvidence:{state:"succeeded",returned:reads.get(row.source)}}:{},...publicRead?{publicRead}:{}}})}});await page.await();if(page.state!==2)throw Error("The Galaxy page did not start.");const{url,port}=app.context.zortexGalaxyPage;let opened=false;if(!options.noOpen)try{await openConnectionUrl(url);opened=true}catch{}process.stdout.write(JSON.stringify({port,version:productVersion,url,opened,...chosen.moved?{notice:`Port ${options.port} is used by another program, possibly an older Zortex window, so this version opened on port ${port}.`}:{}})+"\n");process.stdout.write(`zortex web: ${url}
|
|
2
2
|
`);await new Promise(done=>{const stop2=()=>{process.removeListener("SIGINT",stop2);process.removeListener("SIGTERM",stop2);done()};process.once("SIGINT",stop2);process.once("SIGTERM",stop2)})}finally{stop.abort();try{await openingConnections?.catch(()=>void 0);await connectionSession?.close();await app.context.get("zortexConnectorHub")?.settleObservations?.({closing:true});const sent=await app.context.get("zortexPostHog")?.flush({wait:true});if(sent&&"err"in sent)process.stderr.write("indra feedback: delivery pending; retained for the next run.\n")}finally{await app.close()}}}
|
package/dist/zortex-cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{recoverInstalledUpdate}from"./update-recovery.js";recoverInstalledUpdate().then(async()=>process.argv.includes("feedback")&&await(await import("./product-feedback.js")).bootstrapProductFeedback(process.argv.slice(2),{defaultRoot:true})||await(await import("./update-cli.js")).bootstrapProductCli(process.argv.slice(2))).then(async handled=>{if(!handled){const{zortexArgs}=await import("./zortex-args.js");await(await import("./cli-run.js")).runIndraCli(await zortexArgs(process.argv.slice(2)))}}).catch(error=>{(process.argv.includes("mcp")?process.stderr:process.stdout).write(JSON.stringify({err:{code:"failed_precondition",layer:"service",message:error instanceof Error?error.message:"Zortex startup failed."}})+"\n");process.exitCode=2});
|
|
2
|
+
import{recoverInstalledUpdate}from"./update-recovery.js";recoverInstalledUpdate().then(async()=>(process.argv[2]==="onboard"||process.argv[2]==="--root"&&process.argv[4]==="onboard")&&await(await import("./onboard-cli.js")).bootstrapOnboardCli(process.argv.slice(2))||process.argv.includes("feedback")&&await(await import("./product-feedback.js")).bootstrapProductFeedback(process.argv.slice(2),{defaultRoot:true})||await(await import("./update-cli.js")).bootstrapProductCli(process.argv.slice(2))).then(async handled=>{if(!handled){const{zortexArgs}=await import("./zortex-args.js");await(await import("./cli-run.js")).runIndraCli(await zortexArgs(process.argv.slice(2)))}}).catch(error=>{(process.argv.includes("mcp")?process.stderr:process.stdout).write(JSON.stringify({err:{code:"failed_precondition",layer:"service",message:error instanceof Error?error.message:"Zortex startup failed."}})+"\n");process.exitCode=2});
|