@zortexhq/indra-v2.5 0.4.0 → 0.4.2
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 +5 -5
- package/bin/codex-postinstall.mjs +1 -1
- package/dist/action-effect.js +1 -0
- package/dist/action-read-progress.js +1 -1
- package/dist/actions-catalog.js +1 -0
- package/dist/auto-sync.js +1 -1
- package/dist/auto-update.js +1 -1
- package/dist/automatic-updates.js +1 -0
- 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/computer-use-setup.js +1 -0
- package/dist/default-root.js +1 -1
- package/dist/documentation-action.js +1 -0
- package/dist/gateway.js +1 -1
- package/dist/imessage-sync.js +1 -1
- package/dist/local-cloud-policy.js +1 -1
- package/dist/local-cloud.js +1 -1
- package/dist/mcp.js +1 -3
- package/dist/native-connect.js +1 -1
- package/dist/native-level1-setup.js +1 -1
- package/dist/native-ollama-discovery.js +1 -0
- package/dist/native-vault-discovery.js +1 -1
- package/dist/onboard-cli.js +1 -1
- package/dist/onboard.js +1 -1
- package/dist/onboarding.js +1 -1
- package/dist/profile.js +1 -1
- package/dist/public-tool.js +4 -1
- package/dist/read-route.js +1 -1
- package/dist/recovery-authorization-url.js +1 -1
- package/dist/recovery-progress.js +1 -1
- package/dist/recovery.js +1 -1
- package/dist/resident-autopilot.js +1 -0
- package/dist/resident-ensure-ready.js +1 -1
- package/dist/resident-host.js +2 -2
- package/dist/resident-jobs.js +1 -1
- package/dist/resident-platform.js +2 -2
- package/dist/resident-runtime-identity.js +1 -1
- package/dist/resident-startup-state.js +1 -0
- package/dist/resident-telemetry.js +1 -1
- package/dist/shared-action-schemas.js +1 -0
- package/dist/source-data.js +1 -1
- package/dist/storage-compatibility.js +1 -0
- package/dist/supervised-sync.js +1 -1
- package/dist/tools.js +1 -1
- package/dist/update-check.js +1 -1
- package/dist/update-cli.js +1 -1
- package/dist/update-command.js +1 -1
- package/dist/update-recovery.js +1 -1
- package/node_modules/@zortexhq/plugin-auto-connect/dist/api/durable-dispatcher.js +1 -1
- package/node_modules/@zortexhq/plugin-auto-connect/dist/api/job-contract.js +1 -1
- package/node_modules/@zortexhq/plugin-autopilot/dist/api.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/cua.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/feedback.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/index.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/python-runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/service.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/worker.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/package.json +23 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/LICENSE +21 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/PROVENANCE.json +38 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/__init__.py +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/agent.py +178 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/browser.py +13 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/indra.patch +57 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/model.py +180 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/questions.py +26 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/transport.py +70 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/strategies.py +154 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/worker.py +260 -0
- package/node_modules/@zortexhq/plugin-connector-activitywatch/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-calendar/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-computer-files/dist/catalog.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/action-outcome.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/connectors.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/authorization-metrics.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/native-principal.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/package.json +2 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/connector.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/package.json +2 -1
- package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/compounds.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/action-content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-server.js +6 -6
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-native-process.mjs +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-server.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-server.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/macos-contacts-server.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-apple-native.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/provisioning.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/specs.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-netease/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-notion/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/mail-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-steam/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-teams/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-teams/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/auth-state.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/full-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/api/action-schemas.js +1 -0
- package/node_modules/@zortexhq/plugin-context-share/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/share.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-catalog.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/account.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -1
- package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/api/execution-scope.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/api/stdio-transport.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/windows-job.js +1 -1
- package/node_modules/@zortexhq/plugin-product-account/dist/index.js +4 -1
- package/node_modules/@zortexhq/plugin-product-account/dist/session-store.js +10 -0
- package/node_modules/@zortexhq/plugin-product-account/dist/storage.js +1 -0
- package/node_modules/@zortexhq/plugin-product-account/package.json +5 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/public-result-visibility.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/credentials.js +3 -3
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/keychain.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/public-visibility.js +7 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/recovery-guard.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +2 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-worker.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +2 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql.js +1 -1
- package/package.json +13 -7
- package/profiles/core.yml +2 -0
- package/release-provenance.json +48 -41
- package/update-manifest.json +573 -296
- package/dist/content-find.js +0 -2
- package/dist/find-snapshots.js +0 -1
- package/dist/match-excerpt.js +0 -1
|
@@ -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,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
|
|
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{assertVaultRuntime,validatePublicReadResult}from"@zortexhq/plugin-vault-sqlite/api";import{chmod,lstat,mkdir,readFile,realpath,rename,unlink,writeFile}from"node:fs/promises";import{homedir,tmpdir}from"node:os";import{basename,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{atomicWrite,createUpdateRecovery,installedStartupVersion}from"./update-recovery.js";import{markResidentInterruption,readPendingHandover,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;export const RESIDENT_BUSINESS_CONTRACT_VERSION=2;const REQUEST_BYTES=2*1024*1024,RESPONSE_BYTES=4*1024*1024;const RESIDENT_MANAGEMENT=new Set(["plugins","plugin.set-enabled","status","sources","onboarding","startup","accounts","vault","execution"]);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=>!["operation","args","operationId","authorizeSource"].includes(key))||!args||typeof args!=="object"||Array.isArray(args))return false;if(request2.operationId!==void 0&&(request2.operation!=="action"||typeof request2.operationId!=="string"||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(request2.operationId)))return false;if(request2.authorizeSource!==void 0&&typeof request2.authorizeSource!=="boolean")return false;const fields=args;return["search","actions","action","settings"].includes(String(request2.operation))||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 businessContractFailure(reason){return{err:{code:"failed_precondition",reason,layer:"kernel",retryability:"non-retryable",message:reason==="front_contract_obsolete"?"This loaded front predates the current business contract. Continue through the current installed CLI or the host's supported MCP reload capability.":"The running Resident has not adopted the current business contract. Its installed runtime owner must replace it before this call can dispatch."},effectDisposition:"not_applied",continuation:{kind:"front-transition",requiredBusinessContract:RESIDENT_BUSINESS_CONTRACT_VERSION,routes:[{kind:"host-mcp-reload",requires:"host-capability"},{kind:"current-installed-cli",command:"indra",preserveOperationId:true}]}}}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)}function isResidentInvokeRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value,input=request2.input;if(Object.keys(request2).some(key=>!["source","method","input","operationId"].includes(key))||typeof request2.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(request2.source)||typeof request2.method!=="string"||!request2.method)return false;if(Object.hasOwn(request2,"operationId")&&(typeof request2.operationId!=="string"||!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(request2.operationId)))return false;if(!input||typeof input!=="object"||Array.isArray(input))return false;const params=input.params;return!!params&&typeof params==="object"&&!Array.isArray(params)}async function unixEndpoint(hash){const name=`zortex-indra-${hash}.sock`,preferred=join(await realpath(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"));const endpoint=process.platform==="win32"?item.endpoint:typeof item.endpoint==="string"&&isAbsolute(item.endpoint)?join(await realpath(dirname(item.endpoint)),basename(item.endpoint)):void 0;if(process.platform==="win32"){if(endpoint!==id.endpoint)return null}else{if(!endpoint||basename(endpoint)!==`zortex-indra-${id.hash}.sock`)return null;const parent=await lstat(dirname(endpoint));const socket=await lstat(endpoint).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});const uid=process.getuid();const safeParent=parent.isDirectory()&&(parent.uid===uid&&(parent.mode&18)===0||parent.uid===0&&(parent.mode&512)!==0);if(!safeParent||socket&&(!socket.isSocket()||socket.isSymbolicLink()||socket.uid!==uid))return null}if(!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,endpoint}}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,absoluteDeadline){const remaining=()=>absoluteDeadline===void 0?timeout:Math.min(timeout,absoluteDeadline-Date.now());if(remaining()<=0)throw new ResidentStatusUnavailable(false);let item=await metadata(id);if(remaining()<=0)throw new ResidentStatusUnavailable(false);if(!item)return null;const deadline=Math.min(Date.now()+Math.min(timeout,1e3),absoluteDeadline??Infinity);for(;;){if(guard&&(item.pid!==guard.pid||item.startedAt!==guard.startedAt))return{running:true,deferred:true,reason:"resident_changed"};const attemptTimeout=remaining();if(attemptTimeout<=0)throw new ResidentStatusUnavailable(false);try{return await requestOnce(item,command,attemptTimeout,guard,absoluteDeadline)}catch(error){if(!(error instanceof ResidentStatusUnavailable)||!error.disconnected||Date.now()>=deadline)throw error;await delay(Math.min(20,Math.max(0,deadline-Date.now())));item=await metadata(id)??item}}}function requestOnce(item,command,timeout,guard,absoluteDeadline){const operationalContext=currentOperationalExecution();return new Promise((done,reject)=>{const socket=createConnection(item.endpoint);socket.setEncoding("utf8");let text="";let settled=false;let connected=false;let deadlineTimer;const finish=(result,error,disconnected=false)=>{if(settled)return;if(absoluteDeadline!==void 0&&Date.now()>=absoluteDeadline){result=null;error=new ResidentStatusUnavailable(false)}if(result===null&&!error&&connected&&command==="status"){error=new ResidentStatusUnavailable(disconnected)}settled=true;clearTimeout(deadlineTimer);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"));if(absoluteDeadline!==void 0)deadlineTimer=setTimeout(()=>finish(null,new ResidentStatusUnavailable(false)),Math.max(0,absoluteDeadline-Date.now()));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,expectedOwner){const operationalContext=currentOperationalExecution();const id=await identity(root),item=await metadata(id);if(!item)throw new Error("Resident is not running");const control=message.command==="resume-background-sync"||message.command==="pause-connection-automation";if(!control&&item.businessContractVersion!==RESIDENT_BUSINESS_CONTRACT_VERSION)return businessContractFailure("resident_contract_incompatible");if(expectedOwner&&(!validUpdateOwner(expectedOwner)||item.pid!==expectedOwner.pid||item.startedAt!==expectedOwner.startedAt))return{err:{code:"resident_changed"}};return new Promise((done,reject)=>{const socket=createConnection(item.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,...!control?{businessContractVersion:RESIDENT_BUSINESS_CONTRACT_VERSION}:{},...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){if(!isResidentInvokeRequest(request2))return Promise.reject(new Error("Invalid resident action request"));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,expectedOwner){return residentRpc(root,{command:"resume-background-sync"},signal,expectedOwner)}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,businessContractVersion:RESIDENT_BUSINESS_CONTRACT_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:validatePublicReadResult(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,businessContractVersion,...message}=envelope;if(operationalContext!==void 0&&!isOperationalContext(operationalContext)){socket.destroy();return}if(!["status","stop","pause-connection-automation","resume-background-sync"].includes(message.command)&&businessContractVersion!==RESIDENT_BUSINESS_CONTRACT_VERSION){reply(businessContractFailure("front_contract_obsolete"));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||!isResidentInvokeRequest(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 permit=await installationRecovery.residentLaunchPermit();const pending=permit?await readPendingHandover(runtime.installationPath):void 0;if(permit&&(!pending?.restartPending||await realpath(pending.root)!==id.root))throw Error("Resident handover cannot be confirmed.");const intent=permit?pending.interruption: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,executionOwnership:"exclusive"}}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 lookupPath=platform==="darwin"&&environment.PATH&&!/[\x00-\x1f]/.test(environment.PATH)?[...new Set(environment.PATH.split(":").filter(isAbsolute))].join(":"):void 0;if(platform==="darwin"&&(!isAbsolute(home)||/[\x00-\x1f]/.test(home)))throw new Error("Invalid resident home");const startupEnvironment={...platform==="darwin"?{HOME:home}:{},...lookupPath?{PATH:lookupPath}:{}};const args=[entrypoint,"--root",root,"host","run"];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
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}}
|
|
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)}}const ignoreDetachedError=()=>{};function startupEndpoint(id,deadline){const remaining=deadline-Date.now();if(remaining<=0)return Promise.resolve("unknown");return new Promise(resolve2=>{const socket=createConnection(id.endpoint);let settled=false;const finish=result=>{if(settled)return;settled=true;socket.on("error",ignoreDetachedError);socket.off("connect",connected);socket.off("error",failed);socket.off("timeout",timedOut);socket.setTimeout(0);socket.destroy();resolve2(Date.now()>=deadline?"unknown":result)};const connected=()=>finish("unknown");const failed=error=>finish(error.code==="ENOENT"||error.code==="ECONNREFUSED"?"absent":"unknown");const timedOut=()=>finish("unknown");socket.once("connect",connected);socket.once("error",failed);socket.once("timeout",timedOut);socket.setTimeout(remaining)})}export async function startResident(root,entrypoint){assertVaultRuntime();await installationRecovery.recover();const{id,registration}=await plan(root,entrypoint);const deadline=Date.now()+12e4;let current=await request(id,"status",2e3,void 0,Math.min(deadline,Date.now()+2e3));if(current?.running&¤t.ready!==false)return(await import("./update-command.js")).reconcileInstalledResident(id.root,current);let child,failure,reconciledOwner=false;let lastObservation="unknown";const exited=(exitCode,signal)=>{if(!failure&&!reconciledOwner)failure={at:Date.now(),kind:"exit",exitCode,signal}};const failed=error=>{const code=error.code;const errno=typeof code==="string"&&/^E[A-Z0-9_]{1,31}$/.test(code)?code:"UNKNOWN";if(!failure&&!reconciledOwner)failure={at:Date.now(),kind:"spawn-error",errno}};try{if(!current?.running){try{if(process.platform==="darwin"){const permit=await installationRecovery.residentLaunchPermit();if(permit){const runtime=await loadedRuntime,pending=await readPendingHandover(runtime.installationPath);if(!pending?.restartPending||await realpath(pending.root)!==id.root||pending.interruption!==await residentInterruption(id.root))throw Error("Resident handover cannot be confirmed.");await mkdir(dirname(registration.plistPath),{recursive:true});await activateHandoverLaunchAgent(registration,permit,()=>startupEndpoint(id,Date.now()+2e3).then(state=>state==="absent"));await setResidentStartupDisabled(id.root,false)}else await enableResident(id.root,entrypoint);await execute("launchctl",["kickstart",launchAgentTarget(registration.label)],{timeout:1e4})}else{const environment={...process.env};delete environment.ZORTEX_AUTO_SYNC;delete environment.ZORTEX_AUTO_CONNECT;child=spawn(registration.executable,registration.args,{detached:true,windowsHide:true,stdio:"ignore",env:environment});child.once("error",failed);child.once("exit",exited);child.unref()}}catch(error){failed(error instanceof Error?error:new Error)}}for(;;){const observedFailure=failure;const observationDeadline=observedFailure?Math.min(deadline,observedFailure.at+1e3):deadline;if(Date.now()>=observationDeadline){if(!observedFailure)throw new Error("Resident did not become ready within 120 seconds");if(lastObservation!=="absent")throw new ResidentStatusUnavailable(false);if(observedFailure.kind==="spawn-error")throw Object.assign(new Error("Resident could not be started."),{code:"RESIDENT_SPAWN_FAILED",errno:observedFailure.errno});throw Object.assign(new Error("Resident exited before becoming ready."),{code:"RESIDENT_EXITED_BEFORE_READY",exitCode:observedFailure.exitCode,signal:observedFailure.signal})}let unavailable=false;if(observedFailure)lastObservation="unknown";try{current=await request(id,"status",500,void 0,Math.min(observationDeadline,Date.now()+500))}catch(error){if(error instanceof Error&&error.message==="Resident IPC protocol is incompatible; stop it using its installed version before upgrading")throw error;if(!observedFailure&&!failure&&!(error instanceof ResidentStatusUnavailable))throw error;current=null;unavailable=true}if(failure!==observedFailure)continue;if(observedFailure&&Date.now()>=observationDeadline){lastObservation="unknown";continue}if(current?.running){if(current.ready!==false)return current;if(observedFailure){failure=void 0;reconciledOwner=true}}else if(observedFailure&&!unavailable){lastObservation=await startupEndpoint(id,observationDeadline)}const remaining=(failure?observationDeadline:deadline)-Date.now();if(remaining>0)await delay(Math.min(200,remaining))}}finally{if(child){child.on("error",ignoreDetachedError);child.off("error",failed);child.off("exit",exited)}}}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}function launchAgentTarget(label,uid=process.getuid?.()){if(!Number.isSafeInteger(uid)||uid<0)throw Error("A macOS user session is required for Resident startup.");return`gui/${uid}/${label}`}export async function activateLaunchAgent(registration,run=args=>execute("launchctl",args,{timeout:1e4}),uid=process.getuid?.()){const target=launchAgentTarget(registration.label,uid),domain=target.slice(0,target.lastIndexOf("/"));try{await run(["bootstrap",domain,registration.plistPath])}catch(error){try{await run(["print",target])}catch{throw error}}}export async function activateHandoverLaunchAgent(registration,permit,absent,run=args=>execute("launchctl",args,{timeout:1e4}),write=text=>atomicWrite(registration.plistPath,Buffer.from(text),384),uid=process.getuid?.()){if(!/^[1-9]\d*\n[0-9a-f-]{36}$/.test(permit)||!await absent())throw Error("Resident handover cannot be confirmed.");const target=launchAgentTarget(registration.label,uid),domain=target.slice(0,target.lastIndexOf("/"));const variable="<key>ZORTEX_UPDATE_HANDOVER</key><string>"+xml(permit).replaceAll("\n"," ")+"</string>";const marker="<key>EnvironmentVariables</key><dict>";const temporary=registration.plist.includes(marker)?registration.plist.replace(marker,marker+variable):registration.plist.replace("<key>RunAtLoad</key>",marker+variable+"</dict><key>RunAtLoad</key>");try{await write(temporary);try{await run(["bootstrap",domain,registration.plistPath])}catch(error){let status;try{status=await run(["print",target])}catch{throw error}if(typeof status.stdout!=="string"||/\bpid\s*=\s*[1-9]\d*/.test(status.stdout)||!await absent())throw Error("A running launch agent cannot be replaced.");await run(["bootout",target]);await run(["bootstrap",domain,registration.plistPath])}}finally{await write(registration.plist)}}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 atomicWrite(registration.plistPath,Buffer.from(registration.plist),384);await activateLaunchAgent(registration);await setResidentStartupDisabled(id.root,false);return{enabled:true,mechanism:"LaunchAgent"}}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 registered=plist.includes(`<string>${registration.label}</string>`);let loaded=false;if(registered)try{await execute("launchctl",["print",launchAgentTarget(registration.label)],{timeout:1e4});loaded=true}catch{}return{enabled:registered&&loaded,mechanism:"LaunchAgent",...preference,...registered&&(!loaded||!plist.includes("<key>PATH</key>")||plist.includes("ZORTEX_AUTO_SYNC")||plist.includes("ZORTEX_AUTO_CONNECT"))?{needsRefresh:true}:{}}}return{enabled:false,mechanism:"unsupported",...preference}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile,realpath}from"node:fs/promises";import{fileURLToPath}from"node:url";export function residentRuntimePolicy(
|
|
1
|
+
import{readFile,realpath}from"node:fs/promises";import{fileURLToPath}from"node:url";export function residentRuntimePolicy(_env=process.env){return{autoConnect:true,autoSync:true}}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
|
+
import{randomBytes}from"node:crypto";import{mkdir,readFile,rename,unlink,writeFile}from"node:fs/promises";import{join}from"node:path";import{setTimeout as delay}from"node:timers/promises";export function residentStartupStateFile(root){return join(root,"host","startup-state.json")}function sanitizeMessage(message){if(typeof message!=="string")return void 0;const trimmed=message.replace(/[\r\n\t]+/g," ").trim().slice(0,400);return trimmed||void 0}export async function clearResidentStartupState(root){await unlink(residentStartupStateFile(root)).catch(()=>{})}export async function writeResidentStartupState(root,input){const dir=join(root,"host");await mkdir(dir,{recursive:true,mode:448});const file=residentStartupStateFile(root);const sanitizedMessage=sanitizeMessage(input.message);const record={version:1,pid:input.pid,phase:input.phase,startedAt:input.startedAt,updatedAt:input.updatedAt??new Date().toISOString(),...input.errorCode?{errorCode:input.errorCode.slice(0,80)}:{},...sanitizedMessage?{message:sanitizedMessage}:{}};const temp=`${file}.${randomBytes(8).toString("hex")}.tmp`;try{await writeFile(temp,JSON.stringify(record)+"\n",{mode:384,flag:"wx"});await rename(temp,file)}finally{await unlink(temp).catch(()=>{})}return record}export async function readResidentStartupState(root){try{const raw=JSON.parse(await readFile(residentStartupStateFile(root),"utf8"));if(raw?.version!==1||typeof raw.pid!=="number"||!Number.isSafeInteger(raw.pid)||typeof raw.phase!=="string"||typeof raw.startedAt!=="string"||typeof raw.updatedAt!=="string"){return null}return{version:1,pid:raw.pid,phase:raw.phase,startedAt:raw.startedAt,updatedAt:raw.updatedAt,...typeof raw.errorCode==="string"?{errorCode:raw.errorCode}:{},...typeof raw.message==="string"?{message:raw.message}:{}}}catch{return null}}function defaultIsPidAlive(pid){try{process.kill(pid,0);return true}catch(error){return error.code==="EPERM"}}export async function superviseResidentStart(root,start,options={}){const pollMs=options.pollMs??150;const isPidAlive=options.isPidAlive??defaultIsPidAlive;const startedAfterMs=Date.now()-50;await clearResidentStartupState(root);let settled=false;const monitor=(async()=>{while(!settled){await delay(pollMs);if(settled)break;const state=await readResidentStartupState(root);if(!state)continue;const updatedMs=Date.parse(state.updatedAt);if(Number.isFinite(updatedMs)&&updatedMs<startedAfterMs)continue;if(state.phase==="failed"){const detail=state.message??state.errorCode??"startup failed";throw Error(`Resident failed to start (${state.errorCode??"startup_failed"}): ${detail}`)}if(state.phase!=="ready"&&!isPidAlive(state.pid)){const runningElsewhere=options.isRunning?await options.isRunning().catch(()=>false):false;if(!runningElsewhere){const detail=state.message??`process ${state.pid} exited during ${state.phase}`;throw Error(`Resident exited prematurely before becoming ready: ${detail}`)}}}return new Promise(()=>{})})();try{const host=await Promise.race([start(),monitor]);settled=true;if(host.running&&host.ready!==false&&typeof host.pid==="number"){const now=new Date().toISOString();await writeResidentStartupState(root,{pid:host.pid,phase:"ready",startedAt:now,updatedAt:now}).catch(()=>{})}return host}finally{settled=true}}
|
|
@@ -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={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}
|
|
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",settings:"tool.manage",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}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{shareActionSchemas}from"@zortexhq/plugin-context-share/api";import{AUTOPILOT_MODES}from"@zortexhq/plugin-autopilot/api";const source={type:"string",pattern:"^[a-z][a-z0-9-]{0,63}$"};const object=(properties,required=[])=>({type:"object",properties,required,additionalProperties:false});const request=object({query:{type:"string",maxLength:4096},fileId:{type:"string",minLength:1,maxLength:4096},since:{type:"string"},until:{type:"string"},limit:{type:"integer",minimum:1,maximum:100}});export const sharedActionSchemas=[{name:"autopilot",effect:"write",description:'Connect eligible installed sources in the background with action name="autopilot", params={} or {sources:[source]}. The resident owns the run after the call returns. Use operation="status" without runId, or settings what="status", to find current/recent work. Claim a source with operation="takeover", runId and source before controlling its existing authorization; continue with the returned provider or CUA instructions, then use operation="resume" for that same source/run. Use operation="skip" to cancel one pending source or "cancel" for the whole run. Advanced mode: jev, hybrid (default), llm.',inputSchema:{oneOf:[{type:"object",additionalProperties:false,properties:{operation:{const:"start",default:"start"},runId:{type:"string",pattern:"^[a-zA-Z0-9_-]{1,100}$"},sources:{type:"array",minItems:1,maxItems:200,items:{type:"string",pattern:"^[a-z][a-z0-9-]{0,63}$"}},mode:{type:"string",enum:[...AUTOPILOT_MODES],default:"hybrid"}}},{type:"object",additionalProperties:false,required:["operation"],properties:{operation:{const:"status"},runId:{type:"string",pattern:"^[a-zA-Z0-9_-]{1,100}$",description:"Omit to find current or most recent work."}}},{type:"object",additionalProperties:false,required:["operation","runId"],properties:{operation:{const:"takeover"},runId:{type:"string",pattern:"^[a-zA-Z0-9_-]{1,100}$"},source:{type:"string",pattern:"^[a-z][a-z0-9-]{0,63}$",description:"Required when more than one source needs assistance."}}},{type:"object",additionalProperties:false,required:["operation","runId"],properties:{operation:{const:"resume"},runId:{type:"string",pattern:"^[a-zA-Z0-9_-]{1,100}$"},source:{type:"string",pattern:"^[a-z][a-z0-9-]{0,63}$"},target:{oneOf:[{type:"object",additionalProperties:false,required:["route","pid","windowId","targetId","tabId"],properties:{route:{const:"browser"},pid:{type:"integer",minimum:1},windowId:{type:"integer",minimum:1},targetId:{type:"string",minLength:1,maxLength:200},tabId:{type:"string",minLength:1,maxLength:200}}},{type:"object",additionalProperties:false,required:["route","pid","windowId"],properties:{route:{const:"native"},pid:{type:"integer",minimum:1},windowId:{type:"integer",minimum:1}}}],description:"An exact live target observed through installed CUA tools, reserved for this source. Never guess identifiers or select an unrelated active tab."}}},{type:"object",additionalProperties:false,required:["operation","runId","source"],properties:{operation:{const:"skip"},runId:{type:"string",pattern:"^[a-zA-Z0-9_-]{1,100}$"},source:{type:"string",pattern:"^[a-z][a-z0-9-]{0,63}$"}}},{type:"object",additionalProperties:false,required:["operation","runId"],properties:{operation:{const:"cancel"},runId:{type:"string",pattern:"^[a-zA-Z0-9_-]{1,100}$"}}}]}},{name:"vault.read-evidence",effect:"read",description:"Read one exact cited source event with original payload and explicit current/superseded status. Erased or unauthorized acquired evidence is unavailable.",inputSchema:object({id:{type:"string",pattern:"^[0-9A-HJKMNP-TV-Z]{26}$"}},["id"])},{name:"documentation.read",effect:"read",description:"Read the verified canonical product handbook with version and freshness, using its cache or bundled fallback offline; save its current text to the Vault.",inputSchema:object({})},{name:"connector.read",effect:"read",description:"Read one bounded page from a known source using the current provider authority. Returned data is transient unless the provider explicitly supports retained reads.",inputSchema:object({source,request},["source"])},{name:"connector.acquire",effect:"read",description:"Explicitly acquire one complete bounded content page under current selected account authority; does not imply complete account sync.",inputSchema:{...object({source,query:{type:"string",minLength:1,maxLength:4096},fileId:{type:"string",minLength:1,maxLength:4096},limit:{type:"integer",minimum:1,maximum:100},action:object({name:{type:"string",minLength:1},params:{type:"object"}},["name","params"])},["source"]),description:"Supply a declared readonly action or query/fileId. The action form cannot be combined with query or fileId."}},{name:"connector.invoke",effect:"write",description:"Compatibility adapter for an exact provider method. Direct provider action names with source also execute without a prior discovery call.",inputSchema:object({source,method:{type:"string",minLength:1},input:object({params:{type:"object"},body:{},media:object({content:{type:"string"},mime:{type:"string"}},["content","mime"])},["params"])},["source","method","input"])},{name:"connector.ensure-ready",effect:"write",description:"Initiate source readiness only when required by the current task; ordinary operations use existing automatic readiness and recovery.",inputSchema:object({source},["source"])},{name:"connector.disconnect",effect:"write",description:"Disconnect one explicitly selected source and retain its saved data.",inputSchema:object({source},["source"])},{name:"connector.status",effect:"read",description:"Read current source states.",inputSchema:object({})},{name:"fleet.receipt",effect:"read",description:"Read an exact existing operation receipt.",inputSchema:object({requestId:{type:"string",minLength:1}},["requestId"])},...shareActionSchemas.filter(row=>row.name!=="share.preview")];
|
package/dist/source-data.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{businessError}from"@zortexhq/plugin-connector-framework/api";import{createHash}from"node:crypto";import{isBrowserSource,locateBrowserProfile}from"@zortexhq/plugin-connector-chrome-history";export function createSourceData(ctx,now=Date.now){const store=ctx.get("zortexSqliteVault")?.createSourceSyncStore?.();async function authority(source,bindingId){if(!bindingId&&isBrowserSource(source)){const root=source==="google-chrome"?process.env.INDRA_CHROME_READ_ROOT??process.env.ZORTEX_CHROME_HISTORY_ROOT:process.env.INDRA_EDGE_READ_ROOT??process.env.ZORTEX_EDGE_HISTORY_ROOT;const profile=locateBrowserProfile(source,root?{root}:{});if(!("ok"in profile))return;return{source,account:createHash("sha256").update(profile.ok.userDataDir).digest("hex"),revision:"local-profile-v1",scopes:["history"]}}const custody=ctx.get("zortexVaultStore")?.bindingCustody;if(!custody)return;const selected=await custody.
|
|
1
|
+
import{businessError}from"@zortexhq/plugin-connector-framework/api";import{createHash}from"node:crypto";import{isBrowserSource,locateBrowserProfile}from"@zortexhq/plugin-connector-chrome-history";export function sourceRetry(error,at,failures=0){const due=/backoff not due until (\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z)/.exec(error.message??"")?.[1];if(due&&Number.isFinite(Date.parse(due)))return{nextAt:Math.max(at,Date.parse(due)),failures};if(error.code==="authorization_pending"||error.code==="connection_in_progress")return{nextAt:at+1e3,failures};if(error.code==="deadline_exceeded"||error.code==="aborted")return{nextAt:at,failures};if(error.code==="resource_exhausted")return{nextAt:at+6e4,failures};if(error.code==="unauthenticated"||error.code==="permission_denied"||error.code==="failed_precondition")return{nextAt:at+30*6e4,failures};const count=Math.min(20,failures+1);return{nextAt:at+Math.min(30*6e4,6e4*2**(count-1)),failures:count}}export function createSourceData(ctx,now=Date.now){const store=ctx.get("zortexSqliteVault")?.createSourceSyncStore?.();async function authority(source,bindingId){if(!bindingId&&isBrowserSource(source)){const root=source==="google-chrome"?process.env.INDRA_CHROME_READ_ROOT??process.env.ZORTEX_CHROME_HISTORY_ROOT:process.env.INDRA_EDGE_READ_ROOT??process.env.ZORTEX_EDGE_HISTORY_ROOT;const profile=locateBrowserProfile(source,root?{root}:{});if(!("ok"in profile))return;return{source,account:createHash("sha256").update(profile.ok.userDataDir).digest("hex"),revision:"local-profile-v1",scopes:["history"]}}const custody=ctx.get("zortexVaultStore")?.bindingCustody;if(!custody?.authoritySnapshot)return;const selected=await custody.authoritySnapshot(bindingId?{kind:"binding",bindingId}:{kind:"selected-source",source});if(!("ok"in selected)||!selected.ok.inventory)return;const{binding,grants}=selected.ok.inventory;if(binding.state!=="connected"||binding.identity.source!==source)return;const eligible=grants.filter(grant2=>grant2.purpose==="L1"&&grant2.audience===(binding.authority?.resource??binding.provider));if(eligible.length!==1||eligible[0].state!=="active")return;const grant=eligible[0];return{source,account:binding.identity.subject??binding.id,bindingId:binding.id,revision:`${binding.revision}:${grant.id}:${grant.revision}${bindingId?"":":"+(selected.ok.selection?.revision??"none")}`,scopes:grant.scopes,scopeEpoch:grant.scopeEpoch}}async function read(source,bindingId){const selected=await authority(source,bindingId);if(!store||!selected)return void 0;const found=store.read(selected);return"ok"in found?found.ok?.state:void 0}async function run(source,signal,action,bindingId){if(signal.aborted)return businessError("aborted","Source sync was cancelled.","connector");if(!store)return action();const selected=await authority(source,bindingId);const previous=selected?store.read(selected):void 0;if(previous&&"err"in previous)return previous;const snapshot=previous&&"ok"in previous?previous.ok:null;const before=snapshot?.state??{source,phase:"pending",coverage:{status:"unknown",resources:[],limitations:[]},appended:0};let revision=snapshot?.revision??0;const started=new Date(now()).toISOString();const running={...before,phase:"syncing",lastAttemptAt:started};delete running.nextAt;delete running.errorCode;if(selected){const saved2=store.write(selected,running,revision);if(!("ok"in saved2))return saved2;revision=saved2.ok.revision}let result;try{result=await action()}catch{result={err:{code:signal.aborted?"aborted":"unavailable"}}}if(signal.aborted)result={err:{code:"aborted"}};const after=await authority(source,bindingId);if(!after)return selected?businessError("permission_denied","Source authority changed during sync.","storage"):result;if(selected&&JSON.stringify(after)!==JSON.stringify(selected))return businessError("permission_denied","Source authority changed during sync.","storage");if(!selected){const found=store.read(after);if(!("ok"in found))return found;revision=found.ok?.revision??0}const finished=new Date(now()).toISOString();const data=await Promise.resolve().then(()=>ctx.get("zortexConnectorHub")?.describe?.(source)?.data).catch(()=>void 0);const value="ok"in result?result.ok:void 0;const complete=value?.complete===true;const limitations=[...data?.limitations??[]];if(!data||data.history!=="sync")limitations.push("coverage_not_declared");if(Array.isArray(value?.warnings)&&value.warnings.length)limitations.push("provider_warnings");const ready=complete&&limitations.length===0;const count=typeof value?.appended==="number"&&Number.isSafeInteger(value.appended)&&value.appended>=0?value.appended:0;const retry=sourceRetry("err"in result?result.err:{code:"unavailable"},now(),before.retryCount??0);const state=value?{...before,phase:ready?"ready":"partial",coverage:{status:ready?"complete":"partial",resources:[...data?.resources??[]],limitations},appended:before.appended+count,lastAttemptAt:started,lastSuccessAt:finished,...complete?{initialCompletedAt:before.initialCompletedAt??finished,checkedAt:finished}:{},nextAt:new Date(now()+(complete?15*6e4:0)).toISOString(),retryCount:0}:{...before,phase:signal.aborted?"paused":"blocked",lastAttemptAt:started,errorCode:"err"in result?result.err.code:"unavailable",nextAt:new Date(retry.nextAt).toISOString(),retryCount:retry.failures};if(value)delete state.errorCode;const saved=store.write(after,state,revision);return"ok"in saved?result:saved}async function generation(source){const selected=source?await authority(source):void 0;if(selected)return createHash("sha256").update(JSON.stringify(selected)).digest("hex");const rows=await ctx.get("zortexVaultStore")?.connections();const connections=rows&&"ok"in rows?rows.ok.filter(row=>!source||row.source===source).sort((a,b)=>a.source.localeCompare(b.source)):[];const authorities=await Promise.all(connections.map(row=>authority(row.source)));return createHash("sha256").update(JSON.stringify({connections,authorities})).digest("hex")}return{read,run,generation}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readFileSync,lstatSync,mkdirSync,openSync,writeFileSync,fsyncSync,closeSync,renameSync,unlinkSync}from"node:fs";import{lstat}from"node:fs/promises";import{join,isAbsolute}from"node:path";import{randomUUID}from"node:crypto";const defaults={actionReceipts:1,accountSession:1};export class StorageCompatibilityError extends Error{reason="storage_format_incompatible";constructor(){super("The target runtime cannot read this installation\u2019s retained storage formats. Its data and current runtime are preserved.")}}const location=root=>{if(!isAbsolute(root))throw Error("Storage root must be absolute.");return join(root,"host","storage-formats.json")};function actionFormat(root){const file=location(root);let stat;try{stat=lstatSync(file)}catch(error){if(error.code==="ENOENT")return 1;throw error}if(!stat.isFile()||stat.isSymbolicLink()||stat.size>4096)throw Error("Storage compatibility metadata is invalid.");const value=JSON.parse(readFileSync(file,"utf8"));if(value?.schemaVersion!==1||!Number.isSafeInteger(value.actionReceipts)||Number(value.actionReceipts)<1)throw Error("Storage compatibility metadata is invalid.");return Number(value.actionReceipts)}export function recordActionStorageFormat(root){if(actionFormat(root)>=2)return;const directory=join(root,"host");mkdirSync(directory,{recursive:true,mode:448});const stat=lstatSync(directory);if(!stat.isDirectory()||stat.isSymbolicLink())throw Error("Storage compatibility directory is invalid.");const temporary=join(directory,".storage-formats-"+randomUUID()+".tmp");let descriptor;try{descriptor=openSync(temporary,"wx",384);writeFileSync(descriptor,JSON.stringify({schemaVersion:1,actionReceipts:2})+"\n");fsyncSync(descriptor);closeSync(descriptor);descriptor=void 0;renameSync(temporary,location(root))}finally{if(descriptor!==void 0)closeSync(descriptor);try{unlinkSync(temporary)}catch(error){if(error.code!=="ENOENT")throw error}}}export async function requiredStorageFormats(root){let accountSession=1;try{await lstat(join(root,"account","account.sqlite"));accountSession=await(await import("@zortexhq/plugin-product-account/storage")).accountStorageFormat(join(root,"account"))}catch(error){if(error.code!=="ENOENT")throw error}return{actionReceipts:actionFormat(root),accountSession}}export async function assertStorageCompatibility(root,target){const required=await requiredStorageFormats(root),declared=target&&typeof target==="object"?target.zortexStorage:void 0;let supported=defaults;if(declared!==void 0){if(!declared||typeof declared!=="object")throw new StorageCompatibilityError;const value=declared;if(!Number.isSafeInteger(value.actionReceipts)||Number(value.actionReceipts)<1||!Number.isSafeInteger(value.accountSession)||Number(value.accountSession)<1)throw new StorageCompatibilityError;supported=value}if(required.actionReceipts>supported.actionReceipts||required.accountSession>supported.accountSession)throw new StorageCompatibilityError}
|
package/dist/supervised-sync.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SYNC_WORKERS as WORKERS}from"./sync-sources.js";import{isBrowserSource,locateBrowserProfile}from"@zortexhq/plugin-connector-chrome-history";import{Original}from"@zortexhq/plugin-connector-framework/api";import{join,resolve}from"node:path";import{createHash}from"node:crypto";import{fileURLToPath}from"node:url";import{createTraceRecorder,withFeedbackFlow}from"@zortexhq/plugin-telemetry/api";import{imessageNativeIdentity}from"./imessage-sync.js";import{createSyncObservation}from"./operational-observation.js";const error=(code,message,layer="connector")=>Original.errResult({code,layer,retryability:"non-retryable",message});async function executeChrome(ctx,root,requestId,observation,options={}){const access=ctx.get("zortexLocalSourceAccess"),supervisor=ctx.get("zortexConnectorSupervisor"),journal=ctx.get("zortexConnectorProcessJournal");if(!access||!supervisor||!journal)return error("failed_precondition","Original synchronization services are unavailable.","kernel");const selected=access.resolve("chrome-history");if(!Original.isOk(selected))return selected;let outcome;try{outcome=await supervisor.execute({requestId,stateDir:join(root,"sync-state","chrome-history",selected.ok.grant.id),argv:[process.execPath,fileURLToPath(new URL("./connector-worker.js",import.meta.url)),resolve(root),fileURLToPath(new URL("../profiles/chrome-worker.yml",import.meta.url)),"chrome-history"],cwd:resolve(root),env:{ZORTEX_SELECTED_LOCAL_SOURCE_DIRECTORY:selected.ok.location}},options)}catch{return error("failed_precondition","Connector service did not admit or execute this request.","kernel")}let business;try{business=journal.readBusiness(outcome.runId)}catch(fault){await observation.admitted(outcome,null);throw fault}await observation.admitted(outcome,business);if(!outcome.cleanupConfirmed)return error("failed_precondition","Process cleanup remains unverified.");if(outcome.phase==="cancelled")return error("aborted","Connector sync was cancelled.");if(outcome.phase==="timed-out")return error("deadline_exceeded","Connector sync exceeded its execution budget.");if(!business||business.source!=="chrome-history")return error("data_loss","Worker has no committed source business receipt.");if(!Original.isOk(business.result))return business.result;if(business.result.ok.error!==void 0){const fault=Original.validateStructuredError(business.result.ok.error);return Original.isOk(fault)?Original.errResult(fault.ok):error("data_loss","Invalid structured worker error.")}if(outcome.phase!=="completed"||business.result.ok.runFailed===true||business.result.ok.stopped===true||business.result.ok.state!=="IDLE")return error("unavailable","Connector worker did not complete the source operation.");return Original.ok({...business.result.ok,executionId:outcome.runId,codeVersion:business.codeVersion})}export const WORKER_SYNC_SOURCES=Object.keys(WORKERS);export const isWorkerSyncSource=source=>typeof source==="string"&&Object.hasOwn(WORKERS,source);const browserLocator=source=>{const root=source==="google-chrome"?process.env.INDRA_CHROME_READ_ROOT??process.env.ZORTEX_CHROME_HISTORY_ROOT:process.env.INDRA_EDGE_READ_ROOT??process.env.ZORTEX_EDGE_HISTORY_ROOT;return root?{root}:{}};export function browserReady(source){return WORKERS[source].provider==="local"&&isBrowserSource(source)&&Original.isOk(locateBrowserProfile(source,browserLocator(source)))}export function sourceActive(ctx,source){const id=source==="imessage"?"indra-level1-connectors":"indra-source-"+source,row=[...ctx.loader.entries()].find(entry=>entry.options.id===id);return!!row&&!row.disabled&&row.fiber?.state===2}const SYNC_HARD_LIMIT_MS=6e5,SYNC_BUDGET_MS=54e4;async function executeWorkerSource(ctx,root,source,requestId,observation,options={}){const vault=ctx.get("zortexVaultStore"),supervisor=ctx.get("zortexConnectorSupervisor"),journal=ctx.get("zortexConnectorProcessJournal");if(!vault||!supervisor||!journal)return error("failed_precondition","Source sync services are unavailable.","kernel");const worker=WORKERS[source];let key,browserRoot;if(source==="imessage"){if(!sourceActive(ctx,source))return error("unavailable","The iMessage connector is disabled.","plugin");if(options.bindingId)return error("invalid_argument","iMessage sync uses the signed-in macOS user.");const native=await imessageNativeIdentity();if(!Original.isOk(native))return native;key=native.ok.key}else if(worker.provider==="local"){if(!isBrowserSource(source))return error("invalid_argument","Unknown browser source.");const found=locateBrowserProfile(source,browserLocator(source));if(!Original.isOk(found))return found;browserRoot=found.ok.userDataDir;key=createHash("sha256").update(JSON.stringify({source,account:"local"})).digest("hex").slice(0,32)}else if(options.bindingId){const selected=await vault.bindingCustody.resolve({kind:"binding",bindingId:options.bindingId});if(!Original.isOk(selected))return selected;if(selected.ok.kind!=="resolved")return error("failed_precondition","Select one connected account binding before full sync.","auth");const binding=selected.ok.binding;if(binding.identity.source!==source||binding.state!=="connected"||binding.provider!==worker.provider)return error("unauthenticated","Connect and verify this account before full sync.","auth");const grant=await vault.bindingCustody.grantForBinding(binding.id,"L1",binding.provider);if(!Original.isOk(grant))return grant;if(!grant.ok||grant.ok.state!=="active"||options.grantId&&grant.ok.id!==options.grantId||options.scopeEpoch!==void 0&&grant.ok.scopeEpoch!==options.scopeEpoch)return error("permission_denied","Selected account authority changed before full sync.","auth");key=createHash("sha256").update(JSON.stringify({source,binding:binding.id,account:binding.identity.subject,epoch:binding.updatedAt,grant:grant.ok.id,scopeEpoch:grant.ok.scopeEpoch})).digest("hex").slice(0,32);options={...options,bindingId:binding.id,grantId:grant.ok.id,scopeEpoch:grant.ok.scopeEpoch}}else{const selected=await vault.connection(source);if(!Original.isOk(selected))return selected;const connection=selected.ok,account=connection?.accountId??connection?.account;if(!connection||connection.state!=="connected"||connection.provider!==worker.provider||!account||!connection.updatedAt)return error("unauthenticated","Connect and verify this account before full sync.","auth");key=createHash("sha256").update(JSON.stringify({source,account,epoch:connection.updatedAt})).digest("hex").slice(0,32)}let outcome;try{outcome=await supervisor.execute({requestId,stateDir:join(root,"sync-state",source,key),argv:[process.execPath,fileURLToPath(new URL("./connector-worker.js",import.meta.url)),resolve(root),fileURLToPath(new URL("../profiles/"+worker.profile,import.meta.url)),source],cwd:resolve(root),env:{ZORTEX_PROCESS_CODE_VERSION:"indra-v2/"+source+"@0.1.0+full-sync",...worker.provider==="local"?{ZORTEX_BROWSER_SOURCE:source,ZORTEX_BROWSER_READ_ROOT:browserRoot}:{},...options.bindingId?{ZORTEX_SELECTED_BINDING_ID:options.bindingId}:{},...options.grantId?{ZORTEX_SELECTED_GRANT_ID:options.grantId}:{},...options.scopeEpoch!==void 0?{ZORTEX_SELECTED_SCOPE_EPOCH:String(options.scopeEpoch)}:{},ZORTEX_SYNC_BUDGET_MS:String(SYNC_BUDGET_MS),ZORTEX_SYNC_USER_RETRY:options.userRetry?"1":"0"}},{...options.signal?{signal:options.signal}:{},runMs:SYNC_HARD_LIMIT_MS})}catch{return Original.errResult({code:"resource_exhausted",layer:"kernel",retryability:"transient",message:"Another sync of this source is running, or its previous worker was not confirmed stopped; try again later."})}let receipt;try{receipt=journal.readBusiness(outcome.runId)}catch(fault){await observation.admitted(outcome,null,options.bindingId);throw fault}await observation.admitted(outcome,receipt,options.bindingId);if(!outcome.cleanupConfirmed)return error("failed_precondition","Process cleanup remains unverified.","kernel");if(outcome.phase==="cancelled")return error("aborted","Sync was cancelled.");if(outcome.phase==="timed-out")return error("deadline_exceeded","Sync reached its execution limit; the next run resumes from the saved cursor.");if(!receipt||receipt.source!==source)return error("data_loss","Sync worker has no committed source business receipt.");if(!Original.isOk(receipt.result))return receipt.result;if(receipt.result.ok.error!==void 0){const fault=Original.validateStructuredError(receipt.result.ok.error);return Original.isOk(fault)?Original.errResult(fault.ok):error("data_loss","Invalid sync worker error.")}if(receipt.result.ok.ran===false&&receipt.result.ok.state==="RETRY_WAIT"&&typeof receipt.result.ok.skipped==="string")return Original.errResult({code:"unavailable",layer:"connector",retryability:"transient",message:`Sync is waiting to retry after an earlier provider failure; run it again later (${receipt.result.ok.skipped.slice(0,300)}).`});if(outcome.phase!=="completed"||receipt.result.ok.runFailed===true)return error("unavailable","Sync worker did not finish its source operation.");return Original.ok({...receipt.result.ok,executionId:outcome.runId,codeVersion:receipt.codeVersion,complete:receipt.result.ok.state==="IDLE"&&receipt.result.ok.stopped!==true})}async function observeSync(ctx,source,requestId,action){const run=()=>withFeedbackFlow(source,async()=>{const observation=createSyncObservation(ctx,source,requestId);const trace=createTraceRecorder(()=>ctx.get("zortexTelemetry"),source);await trace.step("read_started","started");try{const result=await action(observation);await observation.notAdmitted(result);const value=result;if(value.err)await trace.step("read_verified",value.err.code==="aborted"?"cancelled":"failed",{error:value.err.code==="deadline_exceeded"?"timeout":"provider"});else if(value.ok){await trace.step("read_verified",value.ok.complete===false?"unknown":"completed");const count=value.ok.appended;if(typeof count==="number"&&Number.isSafeInteger(count)&&count>=0&&count<=1e8)await trace.step("vault_saved","completed",{count})}else await trace.step("read_verified","unknown");return result}catch(error2){await observation.notAdmitted(void 0);await trace.step("read_verified","failed",{error:"unknown"});throw error2}});const feedback=ctx.get("zortexConnectionFeedback");return feedback?feedback.run(source,run):run()}export function runSupervisedChrome(ctx,root,requestId,options={}){return observeSync(ctx,"chrome-history",requestId,observation=>executeChrome(ctx,root,requestId,observation,options))}export function runSupervisedSource(ctx,root,source,requestId,options={}){return observeSync(ctx,source,requestId,observation=>executeWorkerSource(ctx,root,source,requestId,observation,options))}export const runSupervisedGoogle=runSupervisedSource;
|
|
1
|
+
import{SYNC_WORKERS as WORKERS}from"./sync-sources.js";import{isBrowserSource,locateBrowserProfile}from"@zortexhq/plugin-connector-chrome-history";import{Original}from"@zortexhq/plugin-connector-framework/api";import{join,resolve}from"node:path";import{createHash}from"node:crypto";import{fileURLToPath}from"node:url";import{createTraceRecorder,withFeedbackFlow}from"@zortexhq/plugin-telemetry/api";import{readLevel1Configuration}from"@zortexhq/plugin-connector-level1";import{imessageNativeIdentity}from"./imessage-sync.js";import{createSyncObservation}from"./operational-observation.js";const error=(code,message,layer="connector")=>Original.errResult({code,layer,retryability:"non-retryable",message});async function executeChrome(ctx,root,requestId,observation,options={}){const access=ctx.get("zortexLocalSourceAccess"),supervisor=ctx.get("zortexConnectorSupervisor"),journal=ctx.get("zortexConnectorProcessJournal");if(!access||!supervisor||!journal)return error("failed_precondition","Original synchronization services are unavailable.","kernel");const selected=access.resolve("chrome-history");if(!Original.isOk(selected))return selected;let outcome;try{outcome=await supervisor.execute({requestId,stateDir:join(root,"sync-state","chrome-history",selected.ok.grant.id),argv:[process.execPath,fileURLToPath(new URL("./connector-worker.js",import.meta.url)),resolve(root),fileURLToPath(new URL("../profiles/chrome-worker.yml",import.meta.url)),"chrome-history"],cwd:resolve(root),env:{ZORTEX_SELECTED_LOCAL_SOURCE_DIRECTORY:selected.ok.location}},options)}catch{return error("failed_precondition","Connector service did not admit or execute this request.","kernel")}let business;try{business=journal.readBusiness(outcome.runId)}catch(fault){await observation.admitted(outcome,null);throw fault}await observation.admitted(outcome,business);if(!outcome.cleanupConfirmed)return error("failed_precondition","Process cleanup remains unverified.");if(outcome.phase==="cancelled")return error("aborted","Connector sync was cancelled.");if(outcome.phase==="timed-out")return error("deadline_exceeded","Connector sync exceeded its execution budget.");if(!business||business.source!=="chrome-history")return error("data_loss","Worker has no committed source business receipt.");if(!Original.isOk(business.result))return business.result;if(business.result.ok.error!==void 0){const fault=Original.validateStructuredError(business.result.ok.error);return Original.isOk(fault)?Original.errResult(fault.ok):error("data_loss","Invalid structured worker error.")}if(outcome.phase!=="completed"||business.result.ok.runFailed===true||business.result.ok.stopped===true||business.result.ok.state!=="IDLE")return error("unavailable","Connector worker did not complete the source operation.");return Original.ok({...business.result.ok,executionId:outcome.runId,codeVersion:business.codeVersion})}export const WORKER_SYNC_SOURCES=Object.keys(WORKERS);export const isWorkerSyncSource=source=>typeof source==="string"&&Object.hasOwn(WORKERS,source);const browserLocator=source=>{const root=source==="google-chrome"?process.env.INDRA_CHROME_READ_ROOT??process.env.ZORTEX_CHROME_HISTORY_ROOT:process.env.INDRA_EDGE_READ_ROOT??process.env.ZORTEX_EDGE_HISTORY_ROOT;return root?{root}:{}};export function browserReady(source){return WORKERS[source].provider==="local"&&isBrowserSource(source)&&Original.isOk(locateBrowserProfile(source,browserLocator(source)))}export function sourceActive(ctx,source){const id=source==="imessage"?"indra-level1-connectors":"indra-source-"+source,row=[...(ctx.get("loader")??ctx.loader)?.entries?.()??[]].find(entry=>entry.options.id===id);return!!row&&!row.disabled&&row.fiber?.state===2&&(source!=="imessage"||!Array.isArray(row.fiber.config?.sources)||row.fiber.config.sources.includes(source))}export async function imessageSyncAllowed(ctx){if(process.platform!=="darwin"||!sourceActive(ctx,"imessage"))return false;const entry=[...(ctx.get("loader")??ctx.loader)?.entries?.()??[]].find(row=>row.options.id==="indra-level1-connectors");const configuration=entry?.fiber?.config;if(configuration?.sources===void 0&&configuration?.provisioningFile){try{const saved=await readLevel1Configuration(configuration.provisioningFile),desired=saved?.requestedSources??saved?.sources;if(desired&&!desired.includes("imessage"))return false}catch{return false}}const vault=ctx.get("zortexVaultStore");if(!vault)return false;const connection=await vault.connection("imessage");if(!Original.isOk(connection)||connection.ok&&connection.ok.state!=="connected")return false;const bindings=await vault.bindingCustody?.bindings("imessage");if(bindings){if(!Original.isOk(bindings))return false;for(const binding of bindings.ok){if(binding.state!=="connected")return false;const inventory=await vault.bindingCustody.bindingInventory(binding.id);if(!Original.isOk(inventory)||!inventory.ok)return false;const grants=inventory.ok.grants.filter(grant=>grant.purpose==="L1");if(!grants.length||grants.some(grant=>grant.state!=="active")||!grants.some(grant=>grant.scopes.includes("messages.read")))return false}}return true}const SYNC_HARD_LIMIT_MS=6e5,SYNC_BUDGET_MS=54e4;async function executeWorkerSource(ctx,root,source,requestId,observation,options={}){const vault=ctx.get("zortexVaultStore"),supervisor=ctx.get("zortexConnectorSupervisor"),journal=ctx.get("zortexConnectorProcessJournal");if(!vault||!supervisor||!journal)return error("failed_precondition","Source sync services are unavailable.","kernel");const worker=WORKERS[source];let key,browserRoot;if(source==="imessage"){if(!await imessageSyncAllowed(ctx))return error("unavailable","The iMessage connector is disabled, disconnected, or its native read permission was revoked.","plugin");if(options.bindingId)return error("invalid_argument","iMessage sync uses the signed-in macOS user.");const native=await imessageNativeIdentity();if(!Original.isOk(native))return native;key=native.ok.key}else if(worker.provider==="local"){if(!isBrowserSource(source))return error("invalid_argument","Unknown browser source.");const found=locateBrowserProfile(source,browserLocator(source));if(!Original.isOk(found))return found;browserRoot=found.ok.userDataDir;key=createHash("sha256").update(JSON.stringify({source,account:"local"})).digest("hex").slice(0,32)}else if(options.bindingId){const selected=await vault.bindingCustody.resolve({kind:"binding",bindingId:options.bindingId});if(!Original.isOk(selected))return selected;if(selected.ok.kind!=="resolved")return error("failed_precondition","Select one connected account binding before full sync.","auth");const binding=selected.ok.binding;if(binding.identity.source!==source||binding.state!=="connected"||binding.provider!==worker.provider)return error("unauthenticated","Connect and verify this account before full sync.","auth");const grant=await vault.bindingCustody.grantForBinding(binding.id,"L1",binding.provider);if(!Original.isOk(grant))return grant;if(!grant.ok||grant.ok.state!=="active"||options.grantId&&grant.ok.id!==options.grantId||options.scopeEpoch!==void 0&&grant.ok.scopeEpoch!==options.scopeEpoch)return error("permission_denied","Selected account authority changed before full sync.","auth");key=createHash("sha256").update(JSON.stringify({source,binding:binding.id,account:binding.identity.subject,epoch:binding.updatedAt,grant:grant.ok.id,scopeEpoch:grant.ok.scopeEpoch})).digest("hex").slice(0,32);options={...options,bindingId:binding.id,grantId:grant.ok.id,scopeEpoch:grant.ok.scopeEpoch}}else{const selected=await vault.connection(source);if(!Original.isOk(selected))return selected;const connection=selected.ok,account=connection?.accountId??connection?.account;if(!connection||connection.state!=="connected"||connection.provider!==worker.provider||!account||!connection.updatedAt)return error("unauthenticated","Connect and verify this account before full sync.","auth");key=createHash("sha256").update(JSON.stringify({source,account,epoch:connection.updatedAt})).digest("hex").slice(0,32)}let outcome;try{outcome=await supervisor.execute({requestId,stateDir:join(root,"sync-state",source,key),argv:[process.execPath,fileURLToPath(new URL("./connector-worker.js",import.meta.url)),resolve(root),fileURLToPath(new URL("../profiles/"+worker.profile,import.meta.url)),source],cwd:resolve(root),env:{ZORTEX_PROCESS_CODE_VERSION:"indra-v2/"+source+"@0.1.0+full-sync",...worker.provider==="local"?{ZORTEX_BROWSER_SOURCE:source,ZORTEX_BROWSER_READ_ROOT:browserRoot}:{},...options.bindingId?{ZORTEX_SELECTED_BINDING_ID:options.bindingId}:{},...options.grantId?{ZORTEX_SELECTED_GRANT_ID:options.grantId}:{},...options.scopeEpoch!==void 0?{ZORTEX_SELECTED_SCOPE_EPOCH:String(options.scopeEpoch)}:{},ZORTEX_SYNC_BUDGET_MS:String(SYNC_BUDGET_MS),ZORTEX_SYNC_USER_RETRY:options.userRetry?"1":"0"}},{...options.signal?{signal:options.signal}:{},runMs:SYNC_HARD_LIMIT_MS})}catch{return Original.errResult({code:"resource_exhausted",layer:"kernel",retryability:"transient",message:"Another sync of this source is running, or its previous worker was not confirmed stopped; try again later."})}let receipt;try{receipt=journal.readBusiness(outcome.runId)}catch(fault){await observation.admitted(outcome,null,options.bindingId);throw fault}await observation.admitted(outcome,receipt,options.bindingId);if(!outcome.cleanupConfirmed)return error("failed_precondition","Process cleanup remains unverified.","kernel");if(outcome.phase==="cancelled")return error("aborted","Sync was cancelled.");if(outcome.phase==="timed-out")return error("deadline_exceeded","Sync reached its execution limit; the next run resumes from the saved cursor.");if(!receipt||receipt.source!==source)return error("data_loss","Sync worker has no committed source business receipt.");if(!Original.isOk(receipt.result))return receipt.result;if(receipt.result.ok.error!==void 0){const fault=Original.validateStructuredError(receipt.result.ok.error);return Original.isOk(fault)?Original.errResult(fault.ok):error("data_loss","Invalid sync worker error.")}if(receipt.result.ok.ran===false&&receipt.result.ok.state==="RETRY_WAIT"&&typeof receipt.result.ok.skipped==="string")return Original.errResult({code:"unavailable",layer:"connector",retryability:"transient",message:`Sync is waiting to retry after an earlier provider failure; run it again later (${receipt.result.ok.skipped.slice(0,300)}).`});if(outcome.phase!=="completed"||receipt.result.ok.runFailed===true)return error("unavailable","Sync worker did not finish its source operation.");return Original.ok({...receipt.result.ok,executionId:outcome.runId,codeVersion:receipt.codeVersion,complete:receipt.result.ok.state==="IDLE"&&receipt.result.ok.stopped!==true})}async function observeSync(ctx,source,requestId,action){const run=()=>withFeedbackFlow(source,async()=>{const observation=createSyncObservation(ctx,source,requestId);const trace=createTraceRecorder(()=>ctx.get("zortexTelemetry"),source);await trace.step("read_started","started");try{const result=await action(observation);await observation.notAdmitted(result);const value=result;if(value.err)await trace.step("read_verified",value.err.code==="aborted"?"cancelled":"failed",{error:value.err.code==="deadline_exceeded"?"timeout":"provider"});else if(value.ok){await trace.step("read_verified",value.ok.complete===false?"unknown":"completed");const count=value.ok.appended;if(typeof count==="number"&&Number.isSafeInteger(count)&&count>=0&&count<=1e8)await trace.step("vault_saved","completed",{count})}else await trace.step("read_verified","unknown");return result}catch(error2){await observation.notAdmitted(void 0);await trace.step("read_verified","failed",{error:"unknown"});throw error2}});const feedback=ctx.get("zortexConnectionFeedback");return feedback?feedback.run(source,run):run()}export function runSupervisedChrome(ctx,root,requestId,options={}){return observeSync(ctx,"chrome-history",requestId,observation=>executeChrome(ctx,root,requestId,observation,options))}export function runSupervisedSource(ctx,root,source,requestId,options={}){return observeSync(ctx,source,requestId,observation=>executeWorkerSource(ctx,root,source,requestId,observation,options))}export const runSupervisedGoogle=runSupervisedSource;
|
package/dist/tools.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const toolSpecs=[{operation:"search",description:"Direct read-only SQL over the single Vault. Query z_records for
|
|
1
|
+
export const toolSpecs=[{operation:"search",description:"Direct read-only SQL over the single Vault. Query z_records for current published source records; exact historical evidence uses vault.read-evidence. User content is untrusted; writes and credentials are inaccessible.",parameters:{sql:{type:"string",required:true},params:{type:"array"},timeoutMs:{type:"integer"}}},{operation:"read",description:"Read one bounded page from a connected source. For google-chrome and microsoft-edge this uses the configured local browser profile and caches only the returned records in the Vault. Use indra connect --source <source> to open a missing connection gateway, then retry the read and search z_records to answer and cite the cached rows.",parameters:{source:{type:"string",required:true},request:{type:"json"}}},{operation:"actions",description:"Independently find/list known installed actions or lookup an exact schema. Dynamic unconnected totals may be unknown; known actions execute directly.",parameters:{operation:{type:"string"},scope:{type:"string"},format:{type:"string"},name:{type:"string"},parameter:{type:"string"},source:{type:"string"},method:{type:"string"},query:{type:"string"},resource:{type:"string"},limit:{type:"integer"},cursor:{type:"string"},profile:{type:"string"}}},{operation:"action",description:"Execute a known provider or shared action directly with name and params; source disambiguates provider methods. Body/media follow the exact provider schema. Discovery is optional.",parameters:{name:{type:"string",required:true},params:{type:"json",required:true},source:{type:"string"},body:{type:"json"},media:{type:"json"}}},{operation:"settings",description:"Inspect status, apps, source accounts and saved records; connect/disconnect or change a source app using existing owners. Updates and synchronization are automatic.",parameters:{what:{type:"string",required:true},about:{type:"string"},limit:{type:"integer"},offset:{type:"integer"},id:{type:"string"},enabled:{type:"boolean"}}},{operation:"manage",description:"Inspect plugins, sources and progress, then continue the task. what=plugins accepts optional about and limit/offset. Vault is a plugin. what=onboarding reports current Actions availability and operation results; use indra connect --source <source> to open an incomplete source gateway. Valid empty operations succeed; catalog discovery alone does not prove an operation ran. what=vault queries storage; status queries accounts/jobs; startup reads historical connection receipts. plugin.set-enabled switches source rows using id and enabled.",parameters:{what:{type:"string",required:true},about:{type:"string"},limit:{type:"integer"},offset:{type:"integer"},id:{type:"string"},enabled:{type:"boolean"}}}];
|
package/dist/update-check.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{productUpdater}from"./auto-update.js";await productUpdater.check().catch(()=>{});
|
|
1
|
+
import{productUpdater}from"./auto-update.js";import{isAbsolute,resolve}from"node:path";import{installationVaultRoot}from"./default-root.js";import{automaticUpdateResult}from"./automatic-updates.js";const args=process.argv.slice(2);if(args.length===3&&args[0]==="--apply"&&args[1]==="--root"&&isAbsolute(args[2])){let result;try{const selected=await installationVaultRoot(),requested=resolve(args[2]);const mismatch=selected&&(process.platform==="win32"?resolve(selected).toLowerCase()!==requested.toLowerCase():resolve(selected)!==requested);if(mismatch)result={state:"deferred",reason:"installation_vault_mismatch"};else result=await(await import("./update-command.js")).updateInstalledProduct({root:requested,forceCheck:false})}catch{result={state:"failed",reason:"automatic_update_unavailable"}}if(process.connected)process.send?.(automaticUpdateResult(result),()=>{if(process.connected)process.disconnect?.()})}else if(!args.length)await productUpdater.check().catch(()=>{});else process.exitCode=2;
|
package/dist/update-cli.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{productUpdater}from"./auto-update.js";const print=value=>process.stdout.write(JSON.stringify(value)+"\n");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 verified release and hand over the existing background host when it is idle. Active work defers activation. Your Vault and source permissions are preserved.",advanced:"indra update check reports the available release without installing. It is optional; indra update checks and installs in one call. Repeat indra update to repair an interrupted handover. Existing MCP sessions may need reconnecting."});return true}if(operation==="check"&&args.length<=2){const result=await productUpdater.check({force:true});if("confirmationToken"in result){const{confirmationToken:_offer,...visible}=result;print(visible)}else print(result);return true}throw Error("Use indra update. Run indra update --help for recovery options.")}return false}
|