@zortexhq/indra-v2.5 0.2.2 → 0.2.3

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.
Files changed (111) hide show
  1. package/dist/box-level1-setup.js +1 -1
  2. package/dist/calcom-level1-setup.js +1 -1
  3. package/dist/cli-run.js +1 -1
  4. package/dist/connector-worker.js +1 -1
  5. package/dist/discord-level1-setup.js +1 -1
  6. package/dist/dropbox-level1-setup.js +1 -1
  7. package/dist/figma-level1-setup.js +1 -1
  8. package/dist/freshdesk-level1-setup.js +1 -1
  9. package/dist/freshrss-level1-setup.js +1 -1
  10. package/dist/front-level1-setup.js +1 -1
  11. package/dist/gateway.js +1 -1
  12. package/dist/google-chat-level1-setup.js +1 -1
  13. package/dist/google-contacts-level1-setup.js +1 -1
  14. package/dist/hubspot-level1-setup.js +1 -1
  15. package/dist/joplin-selection.js +1 -1
  16. package/dist/local-cloud.js +1 -1
  17. package/dist/mattermost-level1-setup.js +1 -1
  18. package/dist/mcp.js +2 -2
  19. package/dist/measurement-context.js +1 -1
  20. package/dist/miniflux-level1-setup.js +1 -1
  21. package/dist/nextcloud-level1-setup.js +1 -1
  22. package/dist/operation-telemetry.js +1 -0
  23. package/dist/prepared-level1-setup.js +1 -0
  24. package/dist/profile.js +1 -1
  25. package/dist/proton-mail-level1-setup.js +1 -1
  26. package/dist/recovery-launch.js +10 -0
  27. package/dist/recovery-support.js +1 -1
  28. package/dist/recovery-surface.js +1 -0
  29. package/dist/recovery.js +1 -1
  30. package/dist/resident-host.js +2 -2
  31. package/dist/resident-jobs.js +1 -1
  32. package/dist/resident-platform.js +1 -1
  33. package/dist/resident-telemetry.js +1 -0
  34. package/dist/resource-telemetry.js +1 -0
  35. package/dist/salesforce-level1-setup.js +1 -1
  36. package/dist/smartsheet-level1-setup.js +1 -1
  37. package/dist/startup.js +2 -2
  38. package/dist/thunderbird-level1-setup.js +1 -1
  39. package/dist/wakatime-level1-setup.js +1 -1
  40. package/dist/wallabag-level1-setup.js +1 -1
  41. package/dist/web.js +2 -2
  42. package/dist/zendesk-level1-setup.js +1 -1
  43. package/dist/zoom-level1-setup.js +1 -1
  44. package/dist/zulip-level1-setup.js +1 -1
  45. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  46. package/node_modules/@zortexhq/plugin-connector-core/dist/operational-hub.js +1 -0
  47. package/node_modules/@zortexhq/plugin-connector-level1/dist/chatgpt.js +1 -1
  48. package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
  49. package/node_modules/@zortexhq/plugin-connector-level1/dist/mcp-feedback.js +1 -0
  50. package/node_modules/@zortexhq/plugin-connector-level1/dist/operational-client.js +1 -0
  51. package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
  52. package/node_modules/@zortexhq/plugin-connector-level1/package.json +2 -0
  53. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
  54. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/routes.js +1 -1
  55. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/server.js +1 -1
  56. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-catalog.js +1 -0
  57. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -0
  58. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -0
  59. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -0
  60. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app.html +42 -0
  61. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-client.js +1 -0
  62. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-forms.js +1 -0
  63. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/demo.js +1 -0
  64. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.css +47 -6
  65. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.js +1 -1
  66. package/node_modules/@zortexhq/plugin-galaxy-ui/src/original/fonts/LICENSE.txt +92 -0
  67. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/feedback.js +1 -1
  68. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/google-oauth-bridge.js +1 -1
  69. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/index.js +1 -1
  70. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/browser-actions.js +1 -1
  71. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/driver.js +1 -1
  72. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/index.js +1 -1
  73. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/operational-browser.js +1 -0
  74. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/session-routes.js +1 -1
  75. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/shared-session.js +1 -1
  76. package/node_modules/@zortexhq/plugin-posthog/dist/collection-status.js +1 -0
  77. package/node_modules/@zortexhq/plugin-posthog/dist/index.js +1 -1
  78. package/node_modules/@zortexhq/plugin-posthog/dist/indra.js +1 -1
  79. package/node_modules/@zortexhq/plugin-posthog/dist/local-cloud.js +1 -1
  80. package/node_modules/@zortexhq/plugin-posthog/dist/northstar.js +1 -1
  81. package/node_modules/@zortexhq/plugin-posthog/dist/observations.js +1 -1
  82. package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -0
  83. package/node_modules/@zortexhq/plugin-posthog/dist/resources.js +1 -0
  84. package/node_modules/@zortexhq/plugin-posthog/dist/source-ids.js +1 -1
  85. package/node_modules/@zortexhq/plugin-process-local/dist/api/resources.js +1 -0
  86. package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
  87. package/node_modules/@zortexhq/plugin-process-local/dist/resource-sampler.js +1 -0
  88. package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
  89. package/node_modules/@zortexhq/plugin-process-local/package.json +3 -0
  90. package/node_modules/@zortexhq/plugin-telemetry/dist/api/collection.js +1 -0
  91. package/node_modules/@zortexhq/plugin-telemetry/dist/api/index.js +1 -1
  92. package/node_modules/@zortexhq/plugin-telemetry/dist/api/measurement.js +1 -1
  93. package/node_modules/@zortexhq/plugin-telemetry/dist/api/observations.js +1 -1
  94. package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -0
  95. package/node_modules/@zortexhq/plugin-telemetry/dist/api/resources.js +1 -0
  96. package/node_modules/@zortexhq/plugin-telemetry/dist/api/source-ids.js +1 -0
  97. package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
  98. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-call.js +1 -0
  99. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-methods.js +1 -0
  100. package/node_modules/@zortexhq/plugin-telemetry/dist/api/upstream-tools.js +1 -0
  101. package/node_modules/@zortexhq/plugin-telemetry/dist/index.js +1 -1
  102. package/node_modules/@zortexhq/plugin-telemetry/dist/resources.js +1 -0
  103. package/node_modules/@zortexhq/plugin-telemetry/package.json +3 -0
  104. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
  105. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/storage-metadata.js +1 -0
  106. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  107. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/storage-metadata.js +1 -0
  108. package/package.json +6 -6
  109. package/release-provenance.json +26 -26
  110. package/update-manifest.json +377 -179
  111. package/dist/recovery-page.js +0 -215
@@ -1,4 +1,4 @@
1
- import{supportsSavedReconnect}from"./saved-reconnect.js";import{validZendeskSelection}from"./zendesk-selection.js";import{HELP_MANUAL_SOURCES}from"./help-manual-sources.js";import{createPreparedDiscordSource}from"@zortexhq/plugin-connector-level1";import{validateJoplinSelection}from"./joplin-selection.js";import{validZulipSelection}from"./zulip-selection.js";import{validFreshRSSSelection}from"./freshrss-selection.js";import{validMinifluxSelection}from"./miniflux-selection.js";import{validMattermostSelection}from"./mattermost-selection.js";import{validWallabagSelection}from"./wallabag-selection.js";import{validCalcomSelection}from"./calcom-selection.js";import{validWakatimeSelection}from"./wakatime-selection.js";import{validNextcloudInstanceUrl}from"./nextcloud-url.js";import{createHash,randomBytes,timingSafeEqual}from"node:crypto";import{execFile,spawn}from"node:child_process";import{chmod,lstat,mkdir,readFile,realpath,rename,unlink,writeFile}from"node:fs/promises";import{homedir,tmpdir}from"node:os";import{dirname,isAbsolute,join,resolve}from"node:path";import{createConnection,createServer}from"node:net";import{promisify}from"node:util";import{DatabaseSync}from"node:sqlite";import{residentRuntimeIdentity}from"./resident-runtime-identity.js";import{preserveResidentStartupOrigin}from"./installation-origin.js";const execute=promisify(execFile);const delay=ms=>new Promise(done=>setTimeout(done,ms));export const RESIDENT_IPC_PROTOCOL_VERSION=3;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;return request2.operation==="actions"||request2.operation==="manage"&&RESIDENT_MANAGEMENT.has(String(args.what))}function isLocalCloudControlRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value;return request2.action==="grants"&&Object.keys(request2).length===1||request2.action==="revoke"&&Object.keys(request2).length===2&&typeof request2.id==="string"&&/^[a-zA-Z0-9_-]{1,200}$/.test(request2.id)}async function unixEndpoint(hash){const name=`zortex-indra-${hash}.sock`,preferred=join(tmpdir(),name);if(Buffer.byteLength(preferred)<=103)return preferred;const unavailable=()=>Object.assign(new Error("Resident socket path is too long and no safe short system temporary directory is available"),{code:"RESIDENT_SOCKET_PATH_UNAVAILABLE"});try{const directory=await realpath("/tmp"),info=await lstat(directory),endpoint=join(directory,name);if(!info.isDirectory()||info.uid!==0||(info.mode&18)!==0&&(info.mode&512)===0||Buffer.byteLength(endpoint)>103)throw unavailable();return endpoint}catch{throw unavailable()}}async function identity(root){if(!isAbsolute(root))throw new Error("Resident Vault path must be absolute");const canonical=await realpath(root);const key=process.platform==="win32"?canonical.toLowerCase():canonical;const hash=createHash("sha256").update(key).digest("hex").slice(0,24);const directory=join(canonical,"host");return{root:canonical,directory,file:join(directory,"resident.json"),hash,endpoint:process.platform==="win32"?`\\\\.\\pipe\\zortex-indra-${hash}`:await unixEndpoint(hash)}}async function metadata(id){try{const item=JSON.parse(await readFile(id.file,"utf8"));if(item.endpoint!==id.endpoint||!Number.isSafeInteger(item.pid)||item.pid<1||typeof item.nonce!=="string"||!/^[a-f0-9]{64}$/.test(item.nonce)||typeof item.startedAt!=="string")return null;return item}catch{return null}}class ResidentStatusUnavailable extends Error{disconnected;constructor(disconnected){super("Resident status is unavailable; inspect the running host before retrying");this.disconnected=disconnected}}async function request(id,command,timeout=2e3){let item=await metadata(id);if(!item)return null;const deadline=Date.now()+Math.min(timeout,1e3);for(;;){try{return await requestOnce(id,item,command,timeout)}catch(error){if(!(error instanceof ResidentStatusUnavailable)||!error.disconnected||Date.now()>=deadline)throw error;await delay(20);item=await metadata(id)??item}}}function requestOnce(id,item,command,timeout){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})+"\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 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})+"\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 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:true}){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 residentInitialConnections(root,signal,options={}){const waitMs=options.waitMs??3e4;if(!Number.isSafeInteger(waitMs)||waitMs<1||waitMs>3e4)return Promise.reject(new Error("Startup wait must be between one and thirty thousand milliseconds."));return residentRpc(root,{command:"startup-connections",waitMs},signal)}export function residentPauseConnectionAutomation(root,signal){return residentRpc(root,{command:"pause-connection-automation"},signal)}export function residentResumeBackgroundSync(root,signal){return residentRpc(root,{command:"resume-background-sync"},signal)}export function residentConnectManual(root,source,requestId,signal){return residentRpc(root,{command:"connect-manual",source,requestId},signal)}export function residentReconnectSaved(root,source,signal){return residentRpc(root,{command:"reconnect-saved",source},signal)}export function residentConnectGmailWrite(root,requestId,signal){return residentRpc(root,{command:"connect-gmail-write",requestId},signal)}export function residentConnectReadwiseMcpWrite(root,requestId,signal){return residentRpc(root,{command:"connect-readwise-mcp-write",requestId},signal)}export function residentConnectReauthorize(root,source,requestId,signal){return residentRpc(root,{command:"connect-reauthorize",source,requestId},signal)}export function residentConnectRecovery(root,source,requestId,signal){return residentRpc(root,{command:"connect-recovery",source,requestId},signal)}export function residentConnectAutomatic(root,source,requestId,signal){return residentRpc(root,{command:"connect-automatic",source,requestId},signal)}export function residentConfigureWeChat(root,port,signal){return residentRpc(root,{command:"configure-wechat",port},signal)}export async function residentConfigureJoplin(root,selection,signal){validateJoplinSelection(selection);return residentRpc(root,{command:"configure-joplin",selection},signal)}export function residentConfigureThunderbird(root,port,signal){return residentRpc(root,{command:"configure-thunderbird",port},signal)}export function residentConfigureDiscord(root,selection,signal){return residentRpc(root,{command:"configure-discord",selection},signal)}export function residentConfigureProtonMail(root,port,signal){return residentRpc(root,{command:"configure-proton-mail",port},signal)}export function residentConfigureZulip(root,selection,signal){return residentRpc(root,{command:"configure-zulip",selection},signal)}export function residentConfigureFreshRSS(root,selection,signal){return residentRpc(root,{command:"configure-freshrss",selection},signal)}export function residentConfigureMiniflux(root,selection,signal){return residentRpc(root,{command:"configure-miniflux",selection},signal)}export function residentConfigureMattermost(root,selection,signal){return residentRpc(root,{command:"configure-mattermost",selection},signal)}export function residentConfigureWallabag(root,selection,signal){return residentRpc(root,{command:"configure-wallabag",selection},signal)}export function residentConfigureCalcom(root,selection,signal){return residentRpc(root,{command:"configure-calcom",selection},signal)}export function residentConfigureWakatime(root,selection,signal){return residentRpc(root,{command:"configure-wakatime",selection},signal)}export function residentConfigureNextcloud(root,instanceUrl,signal){return residentRpc(root,{command:"configure-nextcloud",instanceUrl},signal)}export function residentConfigureDropbox(root,selection,signal){return residentRpc(root,{command:"configure-dropbox",selection},signal)}export function residentConfigureBox(root,selection,signal){return residentRpc(root,{command:"configure-box",selection},signal)}export function residentConfigureFront(root,selection,signal){return residentRpc(root,{command:"configure-front",selection},signal)}export function residentConfigureHubSpot(root,selection,signal){return residentRpc(root,{command:"configure-hubspot",selection},signal)}export function residentConfigureGoogleContacts(root,selection,signal){return residentRpc(root,{command:"configure-google-contacts",selection},signal)}export function residentConfigureGoogleChat(root,selection,signal){return residentRpc(root,{command:"configure-google-chat",selection},signal)}export function residentConfigureSalesforce(root,selection,signal){return residentRpc(root,{command:"configure-salesforce",selection},signal)}export function residentConfigureZendesk(root,selection,signal){return residentRpc(root,{command:"configure-zendesk",selection},signal)}export function residentConfigureZoom(root,selection,signal){return residentRpc(root,{command:"configure-zoom",selection},signal)}export function residentConfigureSmartsheet(root,region,signal){return residentRpc(root,{command:"configure-smartsheet",region},signal)}export function residentConfigureFigma(root,mode,signal){return residentRpc(root,{command:"configure-figma",mode},signal)}export function residentConfigureFreshdesk(root,subdomain,signal){return residentRpc(root,{command:"configure-freshdesk",subdomain},signal)}export function residentConfigureCopyQ(root,executable,session,signal){return residentRpc(root,{command:"configure-copyq",executable,session},signal)}export function residentConfigureOwnTracks(root,port,signal){return residentRpc(root,{command:"configure-owntracks",port},signal)}export function residentConfigureZotero(root,libraryId,libraryType,signal){return residentRpc(root,{command:"configure-zotero",libraryId,libraryType},signal)}export function residentConfigureNativeFiles(root,source,roots,signal){return residentRpc(root,{command:"configure-native-files",source,roots},signal)}export function residentConnectorStatus(root,signal){return residentRpc(root,{command:"connector-status"},signal)}export function residentConnectorCheck(root,source,signal){return residentRpc(root,{command:"connector-check",source},signal)}export function residentConnectorRead(root,source,signal){return residentRpc(root,{command:"connector-read",source},signal)}export function residentCancelConnect(root,requestId,generation,challengeRef){if(!Number.isSafeInteger(generation)||generation<0||!challengeRef)return Promise.resolve({err:{code:"stale_job_generation"}});return residentRpc(root,{command:"connect-cancel",requestId,generation,challengeRef})}function listen(server,endpoint){return new Promise((done,reject)=>{const fail=error=>{server.off("listening",ready);reject(error)};const ready=()=>{server.off("error",fail);done()};server.once("error",fail);server.once("listening",ready);server.listen(endpoint)})}function unixOwnership(id){const lock=new DatabaseSync(join(id.directory,"resident-owner.sqlite"),{allowExtension:false,timeout:0});try{lock.exec("BEGIN EXCLUSIVE");return lock}catch(error){lock.close();if(error.errcode===5)return null;throw error}}async function recoverUnixEndpoint(endpoint){let before;try{before=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!before.isSocket())return false;const refused=await new Promise(done=>{const socket=createConnection(endpoint);let settled=false;const finish=value=>{if(!settled){settled=true;socket.destroy();done(value)}};socket.once("connect",()=>finish(false));socket.once("error",error=>finish(error.code==="ECONNREFUSED"));socket.setTimeout(2e3,()=>finish(false))});if(!refused)return false;let after;try{after=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!after.isSocket()||after.dev!==before.dev||after.ino!==before.ino)return false;await unlink(endpoint);return true}export async function runResidentServer(root,onStop,status=()=>({}),handlers={}){const id=await identity(root);await mkdir(id.directory,{recursive:true,mode:448});const ownership=process.platform==="win32"?void 0:unixOwnership(id);if(ownership===null)return null;const item={protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,pid:process.pid,nonce:randomBytes(32).toString("hex"),endpoint:id.endpoint,startedAt:new Date().toISOString()};const runtime=await residentRuntimeIdentity();const sockets=new Set;let stopping;let closing;const server=createServer(socket=>{socket.setEncoding("utf8");const reply=result=>{if(socket.destroyed)return;let payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n";if(Buffer.byteLength(payload)>RESPONSE_BYTES)payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result:{err:{code:"resource_exhausted",message:"The source result exceeds the resident response limit."}}})+"\n";socket.end(payload)};const disconnected=new AbortController;sockets.add(socket);socket.on("close",()=>{sockets.delete(socket);disconnected.abort()});socket.on("error",()=>{});socket.setTimeout(2e3,()=>socket.destroy());let input="";let handled=false;socket.on("data",chunk=>{if(handled)return;input+=chunk.toString();if(Buffer.byteLength(input)>REQUEST_BYTES){handled=true;socket.destroy();return}if(!input.includes("\n"))return;handled=true;void(async()=>{try{const message=JSON.parse(input.split("\n")[0]);if(message.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||typeof message.nonce!=="string"||message.nonce.length!==item.nonce.length||!timingSafeEqual(Buffer.from(message.nonce),Buffer.from(item.nonce))){socket.destroy();return}if((stopping||closing)&&message.command!=="status"&&message.command!=="stop"){reply({err:{code:"unavailable",message:"The background host is stopping."}});return}if(message.command==="status"){const{nonce:_nonce,endpoint:_endpoint,...safe}=status();socket.end(JSON.stringify({...safe,runtime,protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:!stopping,pid:item.pid,startedAt:item.startedAt})+"\n")}else if(message.command==="sync"){if(!handlers.sync||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||message.bindingId!==void 0&&(typeof message.bindingId!=="string"||!message.bindingId||message.bindingId.length>200)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.sync(message.source,message.requestId,{signal:disconnected.signal,...message.bindingId?{bindingId:message.bindingId}:{}});reply(result)}else if(message.command==="local-cloud-control"){if(!isLocalCloudControlRequest(message.request)){socket.destroy();return}if(!handlers.localCloud){reply({err:{code:"unavailable",message:"This resident does not provide Local Cloud authorization controls."}});return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.localCloud(message.request))}else if(message.command==="gateway"){if(!handlers.gateway||!isResidentGatewayRequest(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.gateway(message.request,disconnected.signal))}else if(message.command==="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"){if(!handlers.configureZulip||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validZulipSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZulip(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-freshrss"){if(!handlers.configureFreshRSS||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validFreshRSSSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFreshRSS(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-miniflux"){if(!handlers.configureMiniflux||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validMinifluxSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureMiniflux(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-mattermost"){if(!handlers.configureMattermost||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validMattermostSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureMattermost(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-wallabag"){if(!handlers.configureWallabag||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validWallabagSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureWallabag(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-calcom"){if(!handlers.configureCalcom||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validCalcomSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureCalcom(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-wakatime"){if(!handlers.configureWakatime||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validWakatimeSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureWakatime(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}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==="startup-connections"){const waitMs=message.waitMs??3e4;if(!handlers.startup||!Number.isSafeInteger(waitMs)||waitMs<1||waitMs>3e4){socket.destroy();return}socket.setTimeout(waitMs+2e3,()=>socket.destroy());const result=await handlers.startup(disconnected.signal,waitMs);reply(result)}else if(message.command==="pause-connection-automation"){if(!handlers.pauseAutomation||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.pauseAutomation())}else if(message.command==="resume-background-sync"){if(!handlers.resumeBackgroundSync||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.resumeBackgroundSync())}else if(message.command==="stop"){socket.setTimeout(3e4,()=>socket.destroy());stopping??=Promise.resolve().then(onStop);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()}catch{socket.destroy()}})()})});const close=()=>closing??=(async()=>{try{const closed=new Promise(done=>server.close(()=>done()));for(const socket of sockets)socket.end();await closed;if((await metadata(id))?.nonce===item.nonce)await unlink(id.file).catch(()=>{})}finally{ownership?.close()}})();try{try{await listen(server,id.endpoint)}catch(error){if(error.code!=="EADDRINUSE")throw error;if(process.platform==="win32"||!await recoverUnixEndpoint(id.endpoint)){await close();return null}try{await listen(server,id.endpoint)}catch(retryError){if(retryError.code!=="EADDRINUSE")throw retryError;await close();return null}}if(process.platform!=="win32")await chmod(id.endpoint,384);const temporary=`${id.file}.${item.nonce}.tmp`;try{await writeFile(temporary,JSON.stringify(item),{mode:384,flag:"wx"});await rename(temporary,id.file)}finally{await unlink(temporary).catch(()=>{})}}catch(error){await close();throw error}return{close}}function windowsQuote(value){return'"'+value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/g,"$1$1")+'"'}const xml=value=>value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;");export function residentStartupPlan(root,entrypoint,hash,platform=process.platform,executable=process.execPath,home=homedir(),environment=process.env){if(![root,entrypoint,executable].every(isAbsolute))throw new Error("Resident startup paths must be absolute");if(![root,entrypoint,executable].every(value=>!/[\r\n\0]/.test(value)))throw new Error("Invalid resident startup path");if(!/^[a-f0-9]{24}$/.test(hash))throw new Error("Invalid resident identity");const syncDisabled=/^(0|false|off|no)$/i.test((environment.ZORTEX_AUTO_SYNC??"").trim());const args=[entrypoint,"--root",root,"host","run",...syncDisabled?["--sync-disabled"]:[]];const command=[executable,...args].map(windowsQuote).join(" ");const launcherPath=join(root,"host","resident-startup.vbs");const launcher=`Option Explicit\r
1
+ import{supportsSavedReconnect}from"./saved-reconnect.js";import{validZendeskSelection}from"./zendesk-selection.js";import{HELP_MANUAL_SOURCES}from"./help-manual-sources.js";import{createPreparedDiscordSource}from"@zortexhq/plugin-connector-level1";import{validateJoplinSelection}from"./joplin-selection.js";import{validZulipSelection}from"./zulip-selection.js";import{validFreshRSSSelection}from"./freshrss-selection.js";import{validMinifluxSelection}from"./miniflux-selection.js";import{validMattermostSelection}from"./mattermost-selection.js";import{validWallabagSelection}from"./wallabag-selection.js";import{validCalcomSelection}from"./calcom-selection.js";import{validWakatimeSelection}from"./wakatime-selection.js";import{validNextcloudInstanceUrl}from"./nextcloud-url.js";import{createHash,randomBytes,timingSafeEqual}from"node:crypto";import{execFile,spawn}from"node:child_process";import{chmod,lstat,mkdir,readFile,realpath,rename,unlink,writeFile}from"node:fs/promises";import{homedir,tmpdir}from"node:os";import{dirname,isAbsolute,join,resolve}from"node:path";import{createConnection,createServer}from"node:net";import{promisify}from"node:util";import{DatabaseSync}from"node:sqlite";import{residentRuntimeIdentity}from"./resident-runtime-identity.js";import{preserveResidentStartupOrigin}from"./installation-origin.js";import{currentOperationalExecution,isOperationalContext,withOperationalContext,withoutOperationalContext}from"@zortexhq/plugin-telemetry/api";import{observeResidentHandlers,traceResidentControl}from"./resident-telemetry.js";const execute=promisify(execFile);const delay=ms=>new Promise(done=>setTimeout(done,ms));export const RESIDENT_IPC_PROTOCOL_VERSION=3;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;return request2.operation==="actions"||request2.operation==="manage"&&RESIDENT_MANAGEMENT.has(String(args.what))}function isLocalCloudControlRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value;return request2.action==="grants"&&Object.keys(request2).length===1||request2.action==="revoke"&&Object.keys(request2).length===2&&typeof request2.id==="string"&&/^[a-zA-Z0-9_-]{1,200}$/.test(request2.id)}async function unixEndpoint(hash){const name=`zortex-indra-${hash}.sock`,preferred=join(tmpdir(),name);if(Buffer.byteLength(preferred)<=103)return preferred;const unavailable=()=>Object.assign(new Error("Resident socket path is too long and no safe short system temporary directory is available"),{code:"RESIDENT_SOCKET_PATH_UNAVAILABLE"});try{const directory=await realpath("/tmp"),info=await lstat(directory),endpoint=join(directory,name);if(!info.isDirectory()||info.uid!==0||(info.mode&18)!==0&&(info.mode&512)===0||Buffer.byteLength(endpoint)>103)throw unavailable();return endpoint}catch{throw unavailable()}}async function identity(root){if(!isAbsolute(root))throw new Error("Resident Vault path must be absolute");const canonical=await realpath(root);const key=process.platform==="win32"?canonical.toLowerCase():canonical;const hash=createHash("sha256").update(key).digest("hex").slice(0,24);const directory=join(canonical,"host");return{root:canonical,directory,file:join(directory,"resident.json"),hash,endpoint:process.platform==="win32"?`\\\\.\\pipe\\zortex-indra-${hash}`:await unixEndpoint(hash)}}async function metadata(id){try{const item=JSON.parse(await readFile(id.file,"utf8"));if(item.endpoint!==id.endpoint||!Number.isSafeInteger(item.pid)||item.pid<1||typeof item.nonce!=="string"||!/^[a-f0-9]{64}$/.test(item.nonce)||typeof item.startedAt!=="string")return null;return item}catch{return null}}class ResidentStatusUnavailable extends Error{disconnected;constructor(disconnected){super("Resident status is unavailable; inspect the running host before retrying");this.disconnected=disconnected}}async function request(id,command,timeout=2e3){let item=await metadata(id);if(!item)return null;const deadline=Date.now()+Math.min(timeout,1e3);for(;;){try{return await requestOnce(id,item,command,timeout)}catch(error){if(!(error instanceof ResidentStatusUnavailable)||!error.disconnected||Date.now()>=deadline)throw error;await delay(20);item=await metadata(id)??item}}}function requestOnce(id,item,command,timeout){const operationalContext=currentOperationalExecution();return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="";let settled=false;let connected=false;const finish=(result,error,disconnected=false)=>{if(settled)return;if(result===null&&!error&&connected&&command==="status"){error=new ResidentStatusUnavailable(disconnected)}settled=true;socket.destroy();if(error)reject(error);else done(result)};const incompatible=()=>finish(null,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));socket.setTimeout(timeout,()=>finish(null));socket.on("error",error=>finish(null,!connected&&error.code!=="ENOENT"&&error.code!=="ECONNREFUSED"?error:void 0,true));socket.on("end",()=>finish(null,void 0,true));socket.on("connect",()=>{connected=true;if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();socket.write(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,command,nonce:item.nonce,...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n")});socket.on("data",chunk=>{text+=chunk.toString();if(text.length>65536)return finish(null);if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();finish(typeof value.running==="boolean"?value:null)}catch{finish(null)}})})}export async function residentStatus(root){return await request(await identity(root),"status")??{running:false}}async function residentRpc(root,message,signal){const operationalContext=currentOperationalExecution();const id=await identity(root),item=await metadata(id);if(!item)throw new Error("Resident is not running");return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="",settled=false;const finish=(value,error)=>{if(settled)return;settled=true;signal?.removeEventListener("abort",abort);socket.destroy();if(error)reject(error);else done(value)};const abort=()=>finish(void 0,new Error("Resident request was cancelled"));signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted)return abort();socket.setTimeout(11*6e4,()=>finish(void 0,new Error("Resident request timed out")));socket.on("error",error=>finish(void 0,error));socket.on("end",()=>finish(void 0,new Error("Resident sync ended without a result")));socket.on("connect",()=>{if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return finish(void 0,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));const payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,nonce:item.nonce,...message,...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n";if(Buffer.byteLength(payload)>REQUEST_BYTES)return finish(void 0,new Error("Resident request was too large"));socket.write(payload)});socket.on("data",chunk=>{text+=chunk.toString();if(Buffer.byteLength(text)>RESPONSE_BYTES)return finish(void 0,new Error("Resident response was too large"));if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||!value.result)return finish(void 0,new Error("Resident response was invalid"));finish(value.result)}catch{finish(void 0,new Error("Resident response was invalid"))}})})}export function residentLocalCloudControl(root,request2){if(!isLocalCloudControlRequest(request2))return Promise.reject(new Error("Invalid Local Cloud control request"));return residentRpc(root,{command:"local-cloud-control",request:request2})}export function residentSync(root,source,requestId,options={}){return residentRpc(root,{command:"sync",source,requestId,...options.bindingId?{bindingId:options.bindingId}:{}},options.signal)}export function residentGatewayCall(root,request2,signal){return residentRpc(root,{command:"gateway",request:request2},signal)}export function 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:true}){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 residentInitialConnections(root,signal,options={}){const waitMs=options.waitMs??3e4;if(!Number.isSafeInteger(waitMs)||waitMs<1||waitMs>3e4)return Promise.reject(new Error("Startup wait must be between one and thirty thousand milliseconds."));return residentRpc(root,{command:"startup-connections",waitMs},signal)}export function residentPauseConnectionAutomation(root,signal){return residentRpc(root,{command:"pause-connection-automation"},signal)}export function residentResumeBackgroundSync(root,signal){return residentRpc(root,{command:"resume-background-sync"},signal)}export function residentConnectManual(root,source,requestId,signal){return residentRpc(root,{command:"connect-manual",source,requestId},signal)}export function residentReconnectSaved(root,source,signal){return residentRpc(root,{command:"reconnect-saved",source},signal)}export function residentConnectGmailWrite(root,requestId,signal){return residentRpc(root,{command:"connect-gmail-write",requestId},signal)}export function residentConnectReadwiseMcpWrite(root,requestId,signal){return residentRpc(root,{command:"connect-readwise-mcp-write",requestId},signal)}export function residentConnectReauthorize(root,source,requestId,signal){return residentRpc(root,{command:"connect-reauthorize",source,requestId},signal)}export function residentConnectRecovery(root,source,requestId,signal){return residentRpc(root,{command:"connect-recovery",source,requestId},signal)}export function residentConnectAutomatic(root,source,requestId,signal){return residentRpc(root,{command:"connect-automatic",source,requestId},signal)}export function residentConfigureWeChat(root,port,signal){return residentRpc(root,{command:"configure-wechat",port},signal)}export async function residentConfigureJoplin(root,selection,signal){validateJoplinSelection(selection);return residentRpc(root,{command:"configure-joplin",selection},signal)}export function residentConfigureThunderbird(root,port,signal){return residentRpc(root,{command:"configure-thunderbird",port},signal)}export function residentConfigureDiscord(root,selection,signal){return residentRpc(root,{command:"configure-discord",selection},signal)}export function residentConfigureProtonMail(root,port,signal){return residentRpc(root,{command:"configure-proton-mail",port},signal)}export function residentConfigureZulip(root,selection,signal){return residentRpc(root,{command:"configure-zulip",selection},signal)}export function residentConfigureFreshRSS(root,selection,signal){return residentRpc(root,{command:"configure-freshrss",selection},signal)}export function residentConfigureMiniflux(root,selection,signal){return residentRpc(root,{command:"configure-miniflux",selection},signal)}export function residentConfigureMattermost(root,selection,signal){return residentRpc(root,{command:"configure-mattermost",selection},signal)}export function residentConfigureWallabag(root,selection,signal){return residentRpc(root,{command:"configure-wallabag",selection},signal)}export function residentConfigureCalcom(root,selection,signal){return residentRpc(root,{command:"configure-calcom",selection},signal)}export function residentConfigureWakatime(root,selection,signal){return residentRpc(root,{command:"configure-wakatime",selection},signal)}export function residentConfigureNextcloud(root,instanceUrl,signal){return residentRpc(root,{command:"configure-nextcloud",instanceUrl},signal)}export function residentConfigureDropbox(root,selection,signal){return residentRpc(root,{command:"configure-dropbox",selection},signal)}export function residentConfigureBox(root,selection,signal){return residentRpc(root,{command:"configure-box",selection},signal)}export function residentConfigureFront(root,selection,signal){return residentRpc(root,{command:"configure-front",selection},signal)}export function residentConfigureHubSpot(root,selection,signal){return residentRpc(root,{command:"configure-hubspot",selection},signal)}export function residentConfigureGoogleContacts(root,selection,signal){return residentRpc(root,{command:"configure-google-contacts",selection},signal)}export function residentConfigureGoogleChat(root,selection,signal){return residentRpc(root,{command:"configure-google-chat",selection},signal)}export function residentConfigureSalesforce(root,selection,signal){return residentRpc(root,{command:"configure-salesforce",selection},signal)}export function residentConfigureZendesk(root,selection,signal){return residentRpc(root,{command:"configure-zendesk",selection},signal)}export function residentConfigureZoom(root,selection,signal){return residentRpc(root,{command:"configure-zoom",selection},signal)}export function residentConfigureSmartsheet(root,region,signal){return residentRpc(root,{command:"configure-smartsheet",region},signal)}export function residentConfigureFigma(root,mode,signal){return residentRpc(root,{command:"configure-figma",mode},signal)}export function residentConfigureFreshdesk(root,subdomain,signal){return residentRpc(root,{command:"configure-freshdesk",subdomain},signal)}export function residentConfigureCopyQ(root,executable,session,signal){return residentRpc(root,{command:"configure-copyq",executable,session},signal)}export function residentConfigureOwnTracks(root,port,signal){return residentRpc(root,{command:"configure-owntracks",port},signal)}export function residentConfigureZotero(root,libraryId,libraryType,signal){return residentRpc(root,{command:"configure-zotero",libraryId,libraryType},signal)}export function residentConfigureNativeFiles(root,source,roots,signal){return residentRpc(root,{command:"configure-native-files",source,roots},signal)}export function residentConnectorStatus(root,signal){return residentRpc(root,{command:"connector-status"},signal)}export function residentConnectorCheck(root,source,signal){return residentRpc(root,{command:"connector-check",source},signal)}export function residentConnectorRead(root,source,signal){return residentRpc(root,{command:"connector-read",source},signal)}export function residentCancelConnect(root,requestId,generation,challengeRef){if(!Number.isSafeInteger(generation)||generation<0||!challengeRef)return Promise.resolve({err:{code:"stale_job_generation"}});return residentRpc(root,{command:"connect-cancel",requestId,generation,challengeRef})}function listen(server,endpoint){return new Promise((done,reject)=>{const fail=error=>{server.off("listening",ready);reject(error)};const ready=()=>{server.off("error",fail);done()};server.once("error",fail);server.once("listening",ready);server.listen(endpoint)})}function unixOwnership(id){const lock=new DatabaseSync(join(id.directory,"resident-owner.sqlite"),{allowExtension:false,timeout:0});try{lock.exec("BEGIN EXCLUSIVE");return lock}catch(error){lock.close();if(error.errcode===5)return null;throw error}}async function recoverUnixEndpoint(endpoint){let before;try{before=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!before.isSocket())return false;const refused=await new Promise(done=>{const socket=createConnection(endpoint);let settled=false;const finish=value=>{if(!settled){settled=true;socket.destroy();done(value)}};socket.once("connect",()=>finish(false));socket.once("error",error=>finish(error.code==="ECONNREFUSED"));socket.setTimeout(2e3,()=>finish(false))});if(!refused)return false;let after;try{after=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!after.isSocket()||after.dev!==before.dev||after.ino!==before.ino)return false;await unlink(endpoint);return true}export async function runResidentServer(root,onStop,status=()=>({}),handlers={}){handlers=observeResidentHandlers(handlers);const id=await identity(root);await mkdir(id.directory,{recursive:true,mode:448});const ownership=process.platform==="win32"?void 0:unixOwnership(id);if(ownership===null)return null;const item={protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,operationalContextVersion:1,pid:process.pid,nonce:randomBytes(32).toString("hex"),endpoint:id.endpoint,startedAt:new Date().toISOString()};const runtime=await residentRuntimeIdentity();const sockets=new Set;let stopping;let closing;const server=createServer(socket=>{socket.setEncoding("utf8");const reply=result=>{if(socket.destroyed)return;let payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n";if(Buffer.byteLength(payload)>RESPONSE_BYTES)payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result:{err:{code:"resource_exhausted",message:"The source result exceeds the resident response limit."}}})+"\n";socket.end(payload)};const disconnected=new AbortController;sockets.add(socket);socket.on("close",()=>{sockets.delete(socket);disconnected.abort()});socket.on("error",()=>{});socket.setTimeout(2e3,()=>socket.destroy());let input="";let handled=false;socket.on("data",chunk=>{if(handled)return;input+=chunk.toString();if(Buffer.byteLength(input)>REQUEST_BYTES){handled=true;socket.destroy();return}if(!input.includes("\n"))return;handled=true;void(async()=>{try{const envelope=JSON.parse(input.split("\n")[0]);if(envelope.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||typeof envelope.nonce!=="string"||envelope.nonce.length!==item.nonce.length||!timingSafeEqual(Buffer.from(envelope.nonce),Buffer.from(item.nonce))){socket.destroy();return}const{operationalContext,...message}=envelope;if(operationalContext!==void 0&&!isOperationalContext(operationalContext)){socket.destroy();return}const dispatch=async()=>{if((stopping||closing)&&message.command!=="status"&&message.command!=="stop"){reply({err:{code:"unavailable",message:"The background host is stopping."}});return}if(message.command==="status"){const{nonce:_nonce,endpoint:_endpoint,...safe}=traceResidentControl(handlers.telemetry,{phase:"runtime",action:"status",operationId:"resident.status"},status,{plainResult:true});socket.end(JSON.stringify({...safe,runtime,protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:!stopping,pid:item.pid,startedAt:item.startedAt})+"\n")}else if(message.command==="sync"){if(!handlers.sync||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||message.bindingId!==void 0&&(typeof message.bindingId!=="string"||!message.bindingId||message.bindingId.length>200)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.sync(message.source,message.requestId,{signal:disconnected.signal,...message.bindingId?{bindingId:message.bindingId}:{}});reply(result)}else if(message.command==="local-cloud-control"){if(!isLocalCloudControlRequest(message.request)){socket.destroy();return}if(!handlers.localCloud){reply({err:{code:"unavailable",message:"This resident does not provide Local Cloud authorization controls."}});return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.localCloud(message.request))}else if(message.command==="gateway"){if(!handlers.gateway||!isResidentGatewayRequest(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.gateway(message.request,disconnected.signal))}else if(message.command==="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"){if(!handlers.configureZulip||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validZulipSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZulip(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-freshrss"){if(!handlers.configureFreshRSS||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validFreshRSSSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFreshRSS(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-miniflux"){if(!handlers.configureMiniflux||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validMinifluxSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureMiniflux(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-mattermost"){if(!handlers.configureMattermost||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validMattermostSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureMattermost(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-wallabag"){if(!handlers.configureWallabag||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validWallabagSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureWallabag(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-calcom"){if(!handlers.configureCalcom||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validCalcomSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureCalcom(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-wakatime"){if(!handlers.configureWakatime||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validWakatimeSelection(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureWakatime(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}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==="startup-connections"){const waitMs=message.waitMs??3e4;if(!handlers.startup||!Number.isSafeInteger(waitMs)||waitMs<1||waitMs>3e4){socket.destroy();return}socket.setTimeout(waitMs+2e3,()=>socket.destroy());const result=await handlers.startup(disconnected.signal,waitMs);reply(result)}else if(message.command==="pause-connection-automation"){if(!handlers.pauseAutomation||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.pauseAutomation())}else if(message.command==="resume-background-sync"){if(!handlers.resumeBackgroundSync||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.resumeBackgroundSync())}else if(message.command==="stop"){socket.setTimeout(3e4,()=>socket.destroy());stopping??=Promise.resolve().then(()=>traceResidentControl(handlers.telemetry,{phase:"runtime",action:"cleanup",operationId:"resident.stop"},onStop,{plainResult:true}));try{await stopping}catch{stopping=void 0;socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,error:"resident_cleanup_failed"})+"\n");return}socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:false,stopped:true})+"\n");void close()}else socket.destroy()};if(operationalContext)await withOperationalContext(operationalContext,dispatch);else await withoutOperationalContext(dispatch)}catch{socket.destroy()}})()})});const close=()=>closing??=(async()=>{try{const closed=new Promise(done=>server.close(()=>done()));for(const socket of sockets)socket.end();await closed;if((await metadata(id))?.nonce===item.nonce)await unlink(id.file).catch(()=>{})}finally{ownership?.close()}})();try{try{await listen(server,id.endpoint)}catch(error){if(error.code!=="EADDRINUSE")throw error;if(process.platform==="win32"||!await recoverUnixEndpoint(id.endpoint)){await close();return null}try{await listen(server,id.endpoint)}catch(retryError){if(retryError.code!=="EADDRINUSE")throw retryError;await close();return null}}if(process.platform!=="win32")await chmod(id.endpoint,384);const temporary=`${id.file}.${item.nonce}.tmp`;try{await writeFile(temporary,JSON.stringify(item),{mode:384,flag:"wx"});await rename(temporary,id.file)}finally{await unlink(temporary).catch(()=>{})}}catch(error){await close();throw error}return{close}}function windowsQuote(value){return'"'+value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/g,"$1$1")+'"'}const xml=value=>value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;");export function residentStartupPlan(root,entrypoint,hash,platform=process.platform,executable=process.execPath,home=homedir(),environment=process.env){if(![root,entrypoint,executable].every(isAbsolute))throw new Error("Resident startup paths must be absolute");if(![root,entrypoint,executable].every(value=>!/[\r\n\0]/.test(value)))throw new Error("Invalid resident startup path");if(!/^[a-f0-9]{24}$/.test(hash))throw new Error("Invalid resident identity");const syncDisabled=/^(0|false|off|no)$/i.test((environment.ZORTEX_AUTO_SYNC??"").trim());const args=[entrypoint,"--root",root,"host","run",...syncDisabled?["--sync-disabled"]:[]];const command=[executable,...args].map(windowsQuote).join(" ");const launcherPath=join(root,"host","resident-startup.vbs");const launcher=`Option Explicit\r
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">
@@ -0,0 +1 @@
1
+ import{isPromise}from"node:util/types";import{startOperationalStep,usageOutcome}from"@zortexhq/plugin-telemetry/api";const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const connector=(operationId,action,source)=>({phase:"connector",action,...operationId?{operationId}:{},...typeof source==="string"?{source}:{}});const configure=source=>()=>connector("resident.configure","execute",source);const runtime=(operationId,action)=>({phase:"runtime",action,...operationId?{operationId}:{}});const metadata={localCloud:args=>runtime("resident.local_cloud",object(args[0])&&args[0].action==="grants"?"status":"cancel"),gateway:args=>({phase:"tool",action:"execute",operationId:object(args[0])&&args[0].operation==="actions"?"tool.actions":"tool.manage"}),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"),startup:()=>runtime("resident.startup","execute"),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==="startup"?0:["gateway","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{randomUUID}from"node:crypto";import{isUsageCaptureStats,isUsageCollection,isUsageCollectionStatus,isUsageResourceSamplerStats}from"@zortexhq/plugin-telemetry/api";import{createResourceSampler}from"@zortexhq/plugin-telemetry/resources";export function createCollectionStatusRecorder(telemetry,role,samplerStats,now=Date.now){let next=0,busy=false,stopped=false;const record=async()=>{let service;try{service=telemetry();if(stopped||service?.isEnabled()!==true||busy||now()<next)return}catch{return}busy=true;next=now()+3e5;try{const status={schemaVersion:1,snapshotId:randomUUID(),asOf:new Date(now()).toISOString(),role,coverage:"unavailable"};try{const capture=service.collectionStats?.();if(isUsageCaptureStats(capture))status.capture={...capture}}catch{}try{const sampler=samplerStats();if(isUsageResourceSamplerStats(sampler))status.sampler={...sampler}}catch{}try{const batch=await service.readBatch({limit:1});if("ok"in batch&&batch.ok.enabled&&isUsageCollection(batch.ok.collection))status.queue={...batch.ok.collection,...batch.ok.collection.observations?{observations:{...batch.ok.collection.observations}}:{}}}catch{}const known=[status.capture,status.queue,status.sampler].filter(value=>value!==void 0).length;status.coverage=known===3?"complete":known?"partial":"unavailable";if(!stopped&&service.isEnabled()&&isUsageCollectionStatus(status))await service.record({operation:"product.collection",internal:true,outcome:status.coverage==="unavailable"?"unknown":"ok",durationMs:0,collectionStatus:status})}catch{}finally{busy=false}};return{record,stop(){stopped=true}}}export function attachResourceTelemetry(ctx,role="unknown"){try{const telemetry=()=>ctx.get("zortexTelemetry");if(telemetry()?.isEnabled()!==true)return()=>{};const sampler=createResourceSampler({role,enabled:()=>telemetry()?.isEnabled()===true,record:async resource=>{const result=await telemetry()?.record({operation:"product.resources",internal:true,outcome:resource.coverage==="unavailable"?"unknown":"ok",durationMs:resource.sampleDurationMs,resource});if(resource.kind==="process")void status.record();return result},storageSnapshot:async()=>ctx.get("zortexSqliteVault")?.storageSnapshot?.()});const status=createCollectionStatusRecorder(telemetry,role,()=>sampler.stats());sampler.start();return()=>{status.stop();sampler.stop()}}catch{return()=>{}}}
@@ -1 +1 @@
1
- import{interpolate}from"@deepseek-ai/cordis-plugin-loader";import{prepareLevel1Configuration,updateLevel1Configuration,createPreparedWorkSource}from"@zortexhq/plugin-connector-level1";import{isAbsolute}from"node:path";export async function configureSalesforceLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Salesforce selection.");const keys=Reflect.ownKeys(input),client=Object.getOwnPropertyDescriptor(input,"clientId"),port=Object.getOwnPropertyDescriptor(input,"loopbackPort"),env=Object.getOwnPropertyDescriptor(input,"environment");if(keys.length!==3||keys.some(key=>key!=="clientId"&&key!=="loopbackPort"&&key!=="environment")||!client?.enumerable||!("value"in client)||!port?.enumerable||!("value"in port)||typeof client.value!=="string"||typeof port.value!=="number"||!env?.enumerable||!("value"in env)||!["production","sandbox"].includes(env.value))throw Error("Invalid Salesforce selection.");createPreparedWorkSource("salesforce",{mode:"oauth",environment:env.value,clientId:client.value,loopbackPort:port.value});const source="salesforce",base={source,reloadRequired:false};const loader=ctx.get("loader"),vault=ctx.get("zortexVaultStore");if(!loader||!vault)return{...base,state:"unavailable",next:"The resident loader or secure Vault is unavailable."};const entries=[...loader.entries()].filter(row=>row.options.publicModule==="@zortexhq/plugin-connector-level1"||row.options.name==="@zortexhq/plugin-connector-level1");if(entries.length!==1)return{...base,state:"unavailable",next:"Load exactly one Level1 connector plugin before setup."};const entry=entries[0];let config;try{config=entry.fiber?.config??interpolate(entry.context,entry.options.config)}catch{return{...base,state:"configuration-required",next:"Check the Level1 plugin configuration."}}if(!config?.provisioningFile||!isAbsolute(config.provisioningFile))return{...base,state:"configuration-required",next:"Configure an absolute Level1 setup file."};try{const setupConfig=config;await updateLevel1Configuration(config.provisioningFile,async current=>{const saved=current??(await prepareLevel1Configuration(vault,{},setupConfig.runtimeDirectory?{runtimeDirectory:setupConfig.runtimeDirectory}:{})).configuration;const selected=[...new Set([...saved.sources??[],source])],requested=[...new Set([...saved.requestedSources??saved.sources??[],...selected])];return{configuration:{...saved,sources:selected,requestedSources:requested,prepared:{...saved.prepared,[source]:{mode:"oauth",environment:env.value,clientId:client.value,loopbackPort:port.value}}},value:void 0}});const enabled=!entry.disabled&&(config.sources===void 0||config.sources.includes(source));return{source,state:"configured",enabled,reloadRequired:true,next:enabled?"Restart the resident to register Salesforce, then choose Connect to begin OAuth authorization.":"The selection was saved; the existing disabled or explicit source setting still applies."}}catch{return{...base,state:"configuration-required",next:"Check the Level1 settings; no unrelated source was enabled."}}}
1
+ import{configurePreparedLevel1}from"./prepared-level1-setup.js";import{createPreparedWorkSource}from"@zortexhq/plugin-connector-level1";export async function configureSalesforceLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Salesforce selection.");const keys=Reflect.ownKeys(input),client=Object.getOwnPropertyDescriptor(input,"clientId"),port=Object.getOwnPropertyDescriptor(input,"loopbackPort"),env=Object.getOwnPropertyDescriptor(input,"environment");if(keys.length!==3||keys.some(key=>key!=="clientId"&&key!=="loopbackPort"&&key!=="environment")||!client?.enumerable||!("value"in client)||!port?.enumerable||!("value"in port)||typeof client.value!=="string"||typeof port.value!=="number"||!env?.enumerable||!("value"in env)||!["production","sandbox"].includes(env.value))throw Error("Invalid Salesforce selection.");createPreparedWorkSource("salesforce",{mode:"oauth",environment:env.value,clientId:client.value,loopbackPort:port.value});return configurePreparedLevel1(ctx,"salesforce",()=>({mode:"oauth",environment:env.value,clientId:client.value,loopbackPort:port.value}),"Restart the resident to register Salesforce, then choose Connect to begin OAuth authorization.")}
@@ -1 +1 @@
1
- import{interpolate}from"@deepseek-ai/cordis-plugin-loader";import{prepareLevel1Configuration,updateLevel1Configuration}from"@zortexhq/plugin-connector-level1";import{isAbsolute}from"node:path";export async function configureSmartsheetLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Smartsheet selection.");const keys=Reflect.ownKeys(input),descriptor=Object.getOwnPropertyDescriptor(input,"region");if(keys.length!==1||keys[0]!=="region"||!descriptor?.enumerable||!("value"in descriptor)||typeof descriptor.value!=="string"||!["us","eu","au"].includes(descriptor.value))throw Error("Invalid Smartsheet selection.");const source="smartsheet",base={source,reloadRequired:false};const loader=ctx.get("loader"),vault=ctx.get("zortexVaultStore");if(!loader||!vault)return{...base,state:"unavailable",next:"The resident loader or secure Vault is unavailable."};const entries=[...loader.entries()].filter(row=>row.options.publicModule==="@zortexhq/plugin-connector-level1"||row.options.name==="@zortexhq/plugin-connector-level1");if(entries.length!==1)return{...base,state:"unavailable",next:"Load exactly one Level1 connector plugin before setup."};const entry=entries[0];let config;try{config=entry.fiber?.config??interpolate(entry.context,entry.options.config)}catch{return{...base,state:"configuration-required",next:"Check the Level1 plugin configuration."}}if(!config?.provisioningFile||!isAbsolute(config.provisioningFile))return{...base,state:"configuration-required",next:"Configure an absolute Level1 setup file."};try{const setupConfig=config;await updateLevel1Configuration(config.provisioningFile,async current=>{const saved=current??(await prepareLevel1Configuration(vault,{},setupConfig.runtimeDirectory?{runtimeDirectory:setupConfig.runtimeDirectory}:{})).configuration;const selected=[...new Set([...saved.sources??[],source])],requested=[...new Set([...saved.requestedSources??saved.sources??[],...selected])];return{configuration:{...saved,sources:selected,requestedSources:requested,prepared:{...saved.prepared,[source]:{mode:"fields",region:descriptor.value}}},value:void 0}});const enabled=!entry.disabled&&(config.sources===void 0||config.sources.includes(source));return{source,state:"configured",enabled,reloadRequired:true,next:enabled?"Restart the resident to register Smartsheet, then connect using its protected credential form.":"The region was saved; the existing disabled or explicit source setting still applies."}}catch{return{...base,state:"configuration-required",next:"Check the Level1 settings; no unrelated source was enabled."}}}
1
+ import{configurePreparedLevel1}from"./prepared-level1-setup.js";export async function configureSmartsheetLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Smartsheet selection.");const keys=Reflect.ownKeys(input),descriptor=Object.getOwnPropertyDescriptor(input,"region");if(keys.length!==1||keys[0]!=="region"||!descriptor?.enumerable||!("value"in descriptor)||typeof descriptor.value!=="string"||!["us","eu","au"].includes(descriptor.value))throw Error("Invalid Smartsheet selection.");return configurePreparedLevel1(ctx,"smartsheet",()=>({mode:"fields",region:descriptor.value}),"Restart the resident to register Smartsheet, then connect using its protected credential form.","The region was saved; the existing disabled or explicit source setting still applies.")}
package/dist/startup.js CHANGED
@@ -1,2 +1,2 @@
1
- import{AUTOMATIC_ATTEMPTS,isTransientAutomatic}from"@zortexhq/plugin-auto-connect/api";import{createTraceRecorder,withStartupFeedbackFlow}from"@zortexhq/plugin-telemetry/api";import{configureNativeLevel1}from"./native-level1-setup.js";import{readRecoveryEvidence,readConnectionTimes,readinessTime,readinessAfterConnection}from"./recovery-evidence.js";import{randomUUID}from"node:crypto";import{setTimeout as delay}from"node:timers/promises";import{runningProductVersion}from"./update-telemetry.js";export const STARTUP_REQUEST_ID="initial-connect-v1";export const STARTUP_SOURCES=["google-chrome","microsoft-edge","gmail","google-drive","google-calendar","youtube","notion","slack","outlook","x","instagram","linkedin","whatsapp-web"];export const STARTUP_EXTRA_SOURCES=["steam","reddit","spotify","stripe","openrouter","netease-mail","shopify","calendly","activitywatch","cua"];export function startupSourceIds(installed){const ids=new Set(installed.map(row=>row.source));return[...new Set([...STARTUP_SOURCES,...STARTUP_EXTRA_SOURCES,...ids])].filter(source=>ids.has(source))}const MAX_FLEET_SOURCES=50;const sources=[...STARTUP_SOURCES,...STARTUP_EXTRA_SOURCES];const prioritizedSources=new Set(sources);const MAX_STARTUP_HISTORY=1e4;const startupRequestId=attempt=>attempt===0?STARTUP_REQUEST_ID:`${STARTUP_REQUEST_ID}-retry-${attempt}`;function selectedStartupSources(raw=process.env.ZORTEX_AUTO_CONNECT_SOURCES){if(raw===void 0||raw.trim()==="")return void 0;const values=raw.split(",").map(value=>value.trim());if(!values.length||values.some(value=>!/^[a-z][a-z0-9._-]{0,95}$/i.test(value)))throw Error("Invalid ZORTEX_AUTO_CONNECT_SOURCES.");return new Set(values)}export function isStartupRequestId(value){if(value===STARTUP_REQUEST_ID)return true;if(typeof value!=="string"||!value.startsWith(`${STARTUP_REQUEST_ID}-retry-`))return false;const attempt=Number(value.slice(`${STARTUP_REQUEST_ID}-retry-`.length));return Number.isSafeInteger(attempt)&&attempt>0&&attempt<MAX_STARTUP_HISTORY&&value===startupRequestId(attempt)}export function startupHistory(fleet){const receipts=[];let latest=fleet.receipt(STARTUP_REQUEST_ID);for(let attempt=0;attempt<MAX_STARTUP_HISTORY;attempt++){const result=attempt===0?latest:fleet.receipt(startupRequestId(attempt));if(!("ok"in result)){if(!("err"in result)||result.err.code!=="not_found")latest=result;break}latest=result;receipts.push(result.ok);if(result.ok.state==="running")break}if(receipts.length===MAX_STARTUP_HISTORY&&receipts.at(-1)?.state!=="running")latest={err:{code:"resource_exhausted",layer:"plugin",retryability:"non-retryable",message:"Startup receipt history requires explicit maintenance."}};return{latest,receipts}}export function latestStartupReceipt(fleet){return startupHistory(fleet).latest}export function selectStartupBatch(states,receipts,recoveredCompleted=new Set,recoveredFailed=new Set,connectionTimes=new Map){const latest=new Map;const connected=new Set(states.filter(row=>row.state==="connected").map(row=>row.source));const current=(receipt,row)=>{const time=readinessTime(row.progress?.endedAt)??readinessTime(receipt.endedAt);return time===void 0&&row.state!=="completed"||readinessAfterConnection(time,connected.has(row.source)?connectionTimes.get(row.source):void 0)};for(const receipt of receipts)for(const row of receipt.sources)if(current(receipt,row))latest.set(row.source,row);const completed=new Set([...latest.values()].filter(row=>row.state==="completed"&&connected.has(row.source)&&(Number.isSafeInteger(row.returned)&&row.returned>=0||row.readiness?.basis==="actions"&&Number.isSafeInteger(row.readiness.actions)&&row.readiness.actions>0)).map(row=>row.source));for(const source of recoveredCompleted)completed.add(source);for(const source of recoveredFailed)completed.delete(source);const attempts=new Map;for(const receipt of receipts)for(const source of new Set(receipt.sources.filter(row=>current(receipt,row)).map(row=>row.source)))attempts.set(source,(attempts.get(source)??0)+1);const eligible=new Set(states.filter(row=>row.state!=="unavailable"&&row.source!=="chrome-history"&&(prioritizedSources.has(row.source)||row.actions===true)).map(row=>row.source));const installed=[...new Set([...sources,...eligible])].filter(source=>eligible.has(source)&&!completed.has(source));installed.sort((a,b)=>Number(attempts.has(a))-Number(attempts.has(b))||Number(!connected.has(a))-Number(!connected.has(b)));return installed.slice(0,MAX_FLEET_SOURCES)}const hosts=new WeakMap;export function startInitialConnections(ctx,options={}){const enabled=options.enabled??!/^(0|false|off|no)$/i.test((process.env.ZORTEX_AUTO_CONNECT??"").trim());const existing=hosts.get(ctx);if(enabled&&existing)return existing;const lifetime=new AbortController;const runPass=resumeSource=>{const stop=new AbortController;const feedbackId=randomUUID(),startedAt=new Date().toISOString();let feedbackStarted=false,failed=false;const posthog=ctx.get("zortexPostHog");let feedbackQueue=Promise.resolve();let feedbackRoster,feedbackStart;const observe=async phase=>{if(!posthog)return;const task=feedbackQueue.then(async()=>{const{readOnboardingReport,onboardingCounts}=await import("./onboarding.js");const capture=async()=>{const signal=AbortSignal.timeout(750),statuses=await ctx.get("zortexConnectorHub")?.status({signal});if(!statuses||!("ok"in statuses))return;const installed=new Set([...statuses.ok.map(row=>row.source),...(ctx.get("zortexLevel1Connectors")?.pending??[]).map(row=>row.source)]);const selected=selectedStartupSources(),report=await readOnboardingReport(ctx,{enabled,signal});if(signal.aborted||report.state==="unavailable"||report.state==="cancelled")return;return report.sources.filter(row=>row.source!=="chrome-history"&&installed.has(row.source)&&(!selected||selected.has(row.source))&&(resumeSource===void 0||row.source===resumeSource))};let snapshotTimer;const snapshot=await Promise.race([capture().catch(()=>void 0),new Promise(resolve=>{snapshotTimer=setTimeout(()=>resolve(void 0),750)})]);clearTimeout(snapshotTimer);feedbackRoster??=snapshot?.map(row=>row.source)??[];const rows=feedbackRoster.map(source=>snapshot?.find(row=>row.source===source)??{source,connection:"unknown",read:"unknown"});const counts=onboardingCounts(rows),pending2=counts.setupRequired+counts.waiting+counts.needsUser+counts.notAttempted;const platform=["darwin","win32","linux"].includes(process.platform)?process.platform:"other";feedbackStart??={id:feedbackId,phase:"started",startedAt,observedAt:startedAt,version:await runningProductVersion??"unknown",platform,scope:resumeSource===void 0?"initial":"resume",requested:counts.total,connected:counts.ready,pending:pending2,failed:counts.failed+counts.unavailable,userActionRequired:counts.needsUser};await posthog.recordOnboardingAttempt(feedbackStart);if(phase==="started")return;const final=failed||!snapshot?"failed":counts.total>0&&counts.ready===counts.total?"completed":pending2>0?"blocked":"failed";await posthog.recordOnboardingAttempt({...feedbackStart,phase:final,observedAt:new Date(Math.max(Date.now(),Date.parse(startedAt))).toISOString(),connected:counts.ready,pending:pending2,failed:counts.failed+counts.unavailable,userActionRequired:counts.needsUser,durationMs:Math.max(0,Math.min(864e5,Date.now()-Date.parse(startedAt)))})});feedbackQueue=task.catch(()=>{});let timer;try{await Promise.race([feedbackQueue,new Promise(resolve=>{timer=setTimeout(resolve,1e3)})])}finally{clearTimeout(timer)}};const close=()=>stop.abort();lifetime.signal.addEventListener("abort",close,{once:true});if(lifetime.signal.aborted)close();return(async()=>{if(!enabled||stop.signal.aborted)return;let cancel=()=>{};const cancelled=new Promise(resolve=>{cancel=resolve;stop.signal.addEventListener("abort",cancel,{once:true})});try{await Promise.race([ctx.get("loader")?.await(),cancelled])}finally{stop.signal.removeEventListener("abort",cancel)}if(stop.signal.aborted)return;feedbackStarted=true;await observe("started");const selected=selectedStartupSources();const nativeSources=["google-chrome","microsoft-edge","activitywatch"].filter(source=>(resumeSource===void 0||resumeSource===source)&&(!selected||selected.has(source)));const loader=ctx.get("loader"),vault=ctx.get("zortexVaultStore");const prepareNative=options.prepareNative??(loader&&vault?sources2=>configureNativeLevel1(ctx,{sources:sources2}):void 0);if(prepareNative)for(const source of nativeSources){if(stop.signal.aborted)return;try{await prepareNative([source])}catch{process.stderr.write(`indra: native setup source=${source} did not complete; continuing other sources.
2
- `)}}if(stop.signal.aborted)return;const fleet=ctx.get("indraFleet"),hub=ctx.get("zortexConnectorHub");if(!fleet||!hub)return;let{latest:prior,receipts}=startupHistory(fleet);if(!("ok"in prior)&&(!("err"in prior)||prior.err.code!=="not_found"))throw Error("Startup receipt unavailable.");if("ok"in prior&&prior.ok.state==="running")return prior;const states=await hub.status({signal:stop.signal});if(stop.signal.aborted)return;if(!("ok"in states))throw Error("Source status unavailable.");const connectedSources=new Set(states.ok.filter(row=>row.state==="connected").map(row=>row.source));const connectionTimes=await readConnectionTimes(ctx,[...connectedSources]);if(stop.signal.aborted)return;const latestAttemptTimes=new Map;for(const receipt of receipts)for(const row of receipt.sources){const time=readinessTime(row.progress?.endedAt)??readinessTime(receipt.endedAt);if(time!==void 0)latestAttemptTimes.set(row.source,Math.max(time,latestAttemptTimes.get(row.source)??-Infinity))}const recoveredCompleted=new Set,recoveredFailed=new Set;for(const[source,saved]of readRecoveryEvidence(ctx,states.ok.map(row=>row.source))){const time=readinessTime(saved.updatedAt);if(time!==void 0&&(latestAttemptTimes.get(source)??-Infinity)>time)continue;if(!(time===void 0&&saved.read==="failed")&&!readinessAfterConnection(time,connectionTimes.get(source)))continue;if(saved.read==="failed")recoveredFailed.add(source);else if(connectedSources.has(source))recoveredCompleted.add(source)}const attempted=new Set;let previousAttempt=-1;let result;while(!stop.signal.aborted){const batch=selectStartupBatch(states.ok.filter(row=>!attempted.has(row.source)&&(!selected||selected.has(row.source))&&(resumeSource===void 0||row.source===resumeSource&&row.state==="connected")),receipts,recoveredCompleted,recoveredFailed,connectionTimes);if(!batch.length)return result??("ok"in prior?prior:void 0);const stateBySource=new Map(states.ok.map(row=>[row.source,row]));batch.sort((a,b)=>Number(stateBySource.get(a)?.state!=="connected"&&stateBySource.get(a)?.auth!=="none")-Number(stateBySource.get(b)?.state!=="connected"&&stateBySource.get(b)?.auth!=="none"));if(receipts.length<=previousAttempt)throw Error("Startup receipt did not advance.");if(!options.connect)throw Error("resident_connect_port_required");previousAttempt=receipts.length;const attemptId=startupRequestId(receipts.length);result=await fleet.run({requestId:attemptId,sources:batch,connect:false,read:{limit:1}},{signal:stop.signal,origin:"startup",mode:"readiness",retention:"transient",stopOnPrepareFailure:false,prepare:async(source,signal)=>{if(connectedSources.has(source))return{ok:void 0};for(let attempt=0;attempt<AUTOMATIC_ATTEMPTS;attempt++){const requestId=`${attemptId}:connect:${source}${attempt?`:attempt-${attempt+1}`:""}`;let connected;try{connected=await options.connect(source,requestId,signal,{automatic:true});while("ok"in connected&&connected.ok.state==="waiting-user"&&connected.ok.automationActive&&options.job){await delay(100,void 0,{signal});connected=await options.job(requestId,signal)}}catch{return{err:{code:signal.aborted?"aborted":"unavailable",message:"Source authorization did not complete."}}}if("ok"in connected&&connected.ok.state==="connected")return{ok:void 0,connectionState:"connected",newlyConnected:true};if(!signal.aborted){const refreshed=await hub.status({signal});if("ok"in refreshed&&refreshed.ok.some(row=>row.source===source&&row.state==="connected"))return{ok:void 0,connectionState:"connected",newlyConnected:true}}const code="err"in connected?connected.err.code:connected.ok.error?.code??(connected.ok.state==="cancelled"?"aborted":connected.ok.state==="waiting-user"?"login_required":"unavailable");if("ok"in connected&&connected.ok.state==="waiting-user")return{err:{code,message:"The existing source authorization remains available for continuation."}};if(signal.aborted||attempt+1>=AUTOMATIC_ATTEMPTS||!isTransientAutomatic(code))return{err:{code,message:"Source authorization did not complete."}}}return{err:{code:"unavailable",message:"Source authorization did not complete."}}}});if(!("ok"in result)||result.ok.state==="running"||result.ok.state==="cancelled")return result;const observed=result.ok.sources.filter(row=>batch.includes(row.source));if(!observed.length)throw Error("Startup receipt made no source progress.");for(const row of observed)attempted.add(row.source);({latest:prior,receipts}=startupHistory(fleet));if(!("ok"in prior)&&(!("err"in prior)||prior.err.code!=="not_found"))throw Error("Startup receipt unavailable.");if("ok"in prior&&prior.ok.state==="running")return prior}return result})().catch(async()=>{failed=true;process.stderr.write("indra: initial connection pass could not complete; inspect startup status.\n");await withStartupFeedbackFlow("other",()=>createTraceRecorder(()=>ctx.get("zortexTelemetry"),"other").step("startup_failed","failed",{reason:"job_unavailable"}))}).finally(async()=>{lifetime.signal.removeEventListener("abort",close);if(feedbackStarted)await observe("terminal")})};let tail=runPass();const pending=new Map;const handle={get done(){return tail},wait(options2={}){const timeoutMs=options2.timeoutMs??3e4;if(!Number.isSafeInteger(timeoutMs)||timeoutMs<1||timeoutMs>3e4)return Promise.resolve({err:{code:"invalid_argument"}});if(options2.signal?.aborted)return Promise.resolve({err:{code:"aborted"}});return new Promise(resolve=>{let finished=false;const finish=value=>{if(finished)return;finished=true;clearTimeout(timer);options2.signal?.removeEventListener("abort",cancel);resolve(value)};const cancel=()=>finish({err:{code:"aborted"}}),timer=setTimeout(()=>finish({ok:{state:"running"}}),timeoutMs);options2.signal?.addEventListener("abort",cancel,{once:true});void(async()=>{let current,result;do{current=tail;result=await current}while(current!==tail);finish(result)})().catch(()=>finish({err:{code:"unavailable"}}))})},resume(source){if(!enabled||lifetime.signal.aborted||typeof source!=="string"||!/^[a-z][a-z0-9._-]{0,95}$/i.test(source))return Promise.resolve();const queued=pending.get(source);if(queued)return queued;const task=tail.then(()=>runPass(source));pending.set(source,task);tail=task;void task.then(()=>pending.delete(source),()=>pending.delete(source));return task},async close(){lifetime.abort();await tail;if(hosts.get(ctx)===handle)hosts.delete(ctx)}};if(enabled)hosts.set(ctx,handle);return handle}
1
+ import{AUTOMATIC_ATTEMPTS,isTransientAutomatic}from"@zortexhq/plugin-auto-connect/api";import{createTraceRecorder,withStartupFeedbackFlow,startOperationalRun,startOperationalStep,operationalReason}from"@zortexhq/plugin-telemetry/api";import{configureNativeLevel1}from"./native-level1-setup.js";import{readRecoveryEvidence,readConnectionTimes,readinessTime,readinessAfterConnection}from"./recovery-evidence.js";import{randomUUID}from"node:crypto";import{setTimeout as delay}from"node:timers/promises";import{runningProductVersion}from"./update-telemetry.js";export const STARTUP_REQUEST_ID="initial-connect-v1";export const STARTUP_SOURCES=["google-chrome","microsoft-edge","gmail","google-drive","google-calendar","youtube","notion","slack","outlook","x","instagram","linkedin","whatsapp-web"];export const STARTUP_EXTRA_SOURCES=["steam","reddit","spotify","stripe","openrouter","netease-mail","shopify","calendly","activitywatch","cua"];export function startupSourceIds(installed){const ids=new Set(installed.map(row=>row.source));return[...new Set([...STARTUP_SOURCES,...STARTUP_EXTRA_SOURCES,...ids])].filter(source=>ids.has(source))}const MAX_FLEET_SOURCES=50;const sources=[...STARTUP_SOURCES,...STARTUP_EXTRA_SOURCES];const prioritizedSources=new Set(sources);const MAX_STARTUP_HISTORY=1e4;const startupRequestId=attempt=>attempt===0?STARTUP_REQUEST_ID:`${STARTUP_REQUEST_ID}-retry-${attempt}`;function selectedStartupSources(raw=process.env.ZORTEX_AUTO_CONNECT_SOURCES){if(raw===void 0||raw.trim()==="")return void 0;const values=raw.split(",").map(value=>value.trim());if(!values.length||values.some(value=>!/^[a-z][a-z0-9._-]{0,95}$/i.test(value)))throw Error("Invalid ZORTEX_AUTO_CONNECT_SOURCES.");return new Set(values)}export function isStartupRequestId(value){if(value===STARTUP_REQUEST_ID)return true;if(typeof value!=="string"||!value.startsWith(`${STARTUP_REQUEST_ID}-retry-`))return false;const attempt=Number(value.slice(`${STARTUP_REQUEST_ID}-retry-`.length));return Number.isSafeInteger(attempt)&&attempt>0&&attempt<MAX_STARTUP_HISTORY&&value===startupRequestId(attempt)}export function startupHistory(fleet){const receipts=[];let latest=fleet.receipt(STARTUP_REQUEST_ID);for(let attempt=0;attempt<MAX_STARTUP_HISTORY;attempt++){const result=attempt===0?latest:fleet.receipt(startupRequestId(attempt));if(!("ok"in result)){if(!("err"in result)||result.err.code!=="not_found")latest=result;break}latest=result;receipts.push(result.ok);if(result.ok.state==="running")break}if(receipts.length===MAX_STARTUP_HISTORY&&receipts.at(-1)?.state!=="running")latest={err:{code:"resource_exhausted",layer:"plugin",retryability:"non-retryable",message:"Startup receipt history requires explicit maintenance."}};return{latest,receipts}}export function latestStartupReceipt(fleet){return startupHistory(fleet).latest}export function selectStartupBatch(states,receipts,recoveredCompleted=new Set,recoveredFailed=new Set,connectionTimes=new Map){const latest=new Map;const connected=new Set(states.filter(row=>row.state==="connected").map(row=>row.source));const current=(receipt,row)=>{const time=readinessTime(row.progress?.endedAt)??readinessTime(receipt.endedAt);return time===void 0&&row.state!=="completed"||readinessAfterConnection(time,connected.has(row.source)?connectionTimes.get(row.source):void 0)};for(const receipt of receipts)for(const row of receipt.sources)if(current(receipt,row))latest.set(row.source,row);const completed=new Set([...latest.values()].filter(row=>row.state==="completed"&&connected.has(row.source)&&(Number.isSafeInteger(row.returned)&&row.returned>=0||row.readiness?.basis==="actions"&&Number.isSafeInteger(row.readiness.actions)&&row.readiness.actions>0)).map(row=>row.source));for(const source of recoveredCompleted)completed.add(source);for(const source of recoveredFailed)completed.delete(source);const attempts=new Map;for(const receipt of receipts)for(const source of new Set(receipt.sources.filter(row=>current(receipt,row)).map(row=>row.source)))attempts.set(source,(attempts.get(source)??0)+1);const eligible=new Set(states.filter(row=>row.state!=="unavailable"&&row.source!=="chrome-history"&&(prioritizedSources.has(row.source)||row.actions===true)).map(row=>row.source));const installed=[...new Set([...sources,...eligible])].filter(source=>eligible.has(source)&&!completed.has(source));installed.sort((a,b)=>Number(attempts.has(a))-Number(attempts.has(b))||Number(!connected.has(a))-Number(!connected.has(b)));return installed.slice(0,MAX_FLEET_SOURCES)}const hosts=new WeakMap;export function startInitialConnections(ctx,options={}){const enabled=options.enabled??!/^(0|false|off|no)$/i.test((process.env.ZORTEX_AUTO_CONNECT??"").trim());const existing=hosts.get(ctx);if(enabled&&existing)return existing;const lifetime=new AbortController;const runPass=resumeSource=>{const stop=new AbortController;const feedbackId=randomUUID(),startedAt=new Date().toISOString();let feedbackStarted=false,failed=false;let operational;const posthog=ctx.get("zortexPostHog");let feedbackQueue=Promise.resolve();let feedbackRoster,feedbackStart;const observe=async phase=>{if(!posthog)return;const task=feedbackQueue.then(async()=>{const{readOnboardingReport,onboardingCounts}=await import("./onboarding.js");const capture=async()=>{const signal=AbortSignal.timeout(750),statuses=await ctx.get("zortexConnectorHub")?.status({signal});if(!statuses||!("ok"in statuses))return;const installed=new Set([...statuses.ok.map(row=>row.source),...(ctx.get("zortexLevel1Connectors")?.pending??[]).map(row=>row.source)]);const selected=selectedStartupSources(),report=await readOnboardingReport(ctx,{enabled,signal});if(signal.aborted||report.state==="unavailable"||report.state==="cancelled")return;return report.sources.filter(row=>row.source!=="chrome-history"&&installed.has(row.source)&&(!selected||selected.has(row.source))&&(resumeSource===void 0||row.source===resumeSource))};let snapshotTimer;const snapshot=await Promise.race([capture().catch(()=>void 0),new Promise(resolve=>{snapshotTimer=setTimeout(()=>resolve(void 0),750)})]);clearTimeout(snapshotTimer);feedbackRoster??=snapshot?.map(row=>row.source)??[];const rows=feedbackRoster.map(source=>snapshot?.find(row=>row.source===source)??{source,connection:"unknown",read:"unknown"});const counts=onboardingCounts(rows),pending2=counts.setupRequired+counts.waiting+counts.needsUser+counts.notAttempted;const platform=["darwin","win32","linux"].includes(process.platform)?process.platform:"other";feedbackStart??={id:feedbackId,phase:"started",startedAt,observedAt:startedAt,version:await runningProductVersion??"unknown",platform,scope:resumeSource===void 0?"initial":"resume",requested:counts.total,connected:counts.ready,pending:pending2,failed:counts.failed+counts.unavailable,userActionRequired:counts.needsUser};await posthog.recordOnboardingAttempt(feedbackStart);if(phase==="started")return;const final=failed||!snapshot?"failed":counts.total>0&&counts.ready===counts.total?"completed":pending2>0?"blocked":"failed";await posthog.recordOnboardingAttempt({...feedbackStart,phase:final,observedAt:new Date(Math.max(Date.now(),Date.parse(startedAt))).toISOString(),connected:counts.ready,pending:pending2,failed:counts.failed+counts.unavailable,userActionRequired:counts.needsUser,durationMs:Math.max(0,Math.min(864e5,Date.now()-Date.parse(startedAt)))})});feedbackQueue=task.catch(()=>{});let timer;try{await Promise.race([feedbackQueue,new Promise(resolve=>{timer=setTimeout(resolve,1e3)})])}finally{clearTimeout(timer)}};const close=()=>stop.abort();lifetime.signal.addEventListener("abort",close,{once:true});if(lifetime.signal.aborted)close();return(async()=>{if(!enabled||stop.signal.aborted)return;let cancel=()=>{};const cancelled=new Promise(resolve=>{cancel=resolve;stop.signal.addEventListener("abort",cancel,{once:true})});try{await Promise.race([ctx.get("loader")?.await(),cancelled])}finally{stop.signal.removeEventListener("abort",cancel)}if(stop.signal.aborted)return;operational=startOperationalRun(()=>ctx.get("zortexTelemetry"),{runId:feedbackId,source:"autopilot",phase:"onboarding",action:"execute",...resumeSource===void 0?{}:{selection:"recovery"},trigger:resumeSource===void 0?"automatic_startup":"recovery"});return operational.run(async()=>{feedbackStarted=true;await observe("started");const selected=selectedStartupSources();const nativeSources=["google-chrome","microsoft-edge","activitywatch"].filter(source=>(resumeSource===void 0||resumeSource===source)&&(!selected||selected.has(source)));const loader=ctx.get("loader"),vault=ctx.get("zortexVaultStore");const prepareNative=options.prepareNative??(loader&&vault?sources2=>configureNativeLevel1(ctx,{sources:sources2}):void 0);if(prepareNative)for(const source of nativeSources){if(stop.signal.aborted)return;try{await prepareNative([source])}catch{process.stderr.write(`indra: native setup source=${source} did not complete; continuing other sources.
2
+ `)}}if(stop.signal.aborted)return;const fleet=ctx.get("indraFleet"),hub=ctx.get("zortexConnectorHub");if(!fleet||!hub)return;let{latest:prior,receipts}=startupHistory(fleet);if(!("ok"in prior)&&(!("err"in prior)||prior.err.code!=="not_found"))throw Error("Startup receipt unavailable.");if("ok"in prior&&prior.ok.state==="running")return prior;const states=await hub.status({signal:stop.signal});if(stop.signal.aborted)return;if(!("ok"in states))throw Error("Source status unavailable.");const connectedSources=new Set(states.ok.filter(row=>row.state==="connected").map(row=>row.source));const connectionTimes=await readConnectionTimes(ctx,[...connectedSources]);if(stop.signal.aborted)return;const latestAttemptTimes=new Map;for(const receipt of receipts)for(const row of receipt.sources){const time=readinessTime(row.progress?.endedAt)??readinessTime(receipt.endedAt);if(time!==void 0)latestAttemptTimes.set(row.source,Math.max(time,latestAttemptTimes.get(row.source)??-Infinity))}const recoveredCompleted=new Set,recoveredFailed=new Set;for(const[source,saved]of readRecoveryEvidence(ctx,states.ok.map(row=>row.source))){const time=readinessTime(saved.updatedAt);if(time!==void 0&&(latestAttemptTimes.get(source)??-Infinity)>time)continue;if(!(time===void 0&&saved.read==="failed")&&!readinessAfterConnection(time,connectionTimes.get(source)))continue;if(saved.read==="failed")recoveredFailed.add(source);else if(connectedSources.has(source))recoveredCompleted.add(source)}const attempted=new Set;let previousAttempt=-1;let result;while(!stop.signal.aborted){const batch=selectStartupBatch(states.ok.filter(row=>!attempted.has(row.source)&&(!selected||selected.has(row.source))&&(resumeSource===void 0||row.source===resumeSource&&row.state==="connected")),receipts,recoveredCompleted,recoveredFailed,connectionTimes);if(!batch.length)return result??("ok"in prior?prior:void 0);const stateBySource=new Map(states.ok.map(row=>[row.source,row]));batch.sort((a,b)=>Number(stateBySource.get(a)?.state!=="connected"&&stateBySource.get(a)?.auth!=="none")-Number(stateBySource.get(b)?.state!=="connected"&&stateBySource.get(b)?.auth!=="none"));if(receipts.length<=previousAttempt)throw Error("Startup receipt did not advance.");if(!options.connect)throw Error("resident_connect_port_required");previousAttempt=receipts.length;const attemptId=startupRequestId(receipts.length);result=await fleet.run({requestId:attemptId,sources:batch,connect:false,read:{limit:1}},{signal:stop.signal,origin:"startup",mode:"readiness",retention:"transient",stopOnPrepareFailure:false,prepare:async(source,signal)=>{const selection=startOperationalStep(()=>ctx.get("zortexTelemetry"),{source,phase:"onboarding",action:"source_selection",selection:resumeSource!==void 0?"recovery":selected?"requested":"default_roster",trigger:resumeSource===void 0?"automatic_startup":"recovery"});selection.finish({state:"completed"});return selection.run(async()=>{if(connectedSources.has(source))return{ok:void 0};for(let attempt=0;attempt<AUTOMATIC_ATTEMPTS;attempt++){const requestId=`${attemptId}:connect:${source}${attempt?`:attempt-${attempt+1}`:""}`;const connection=startOperationalStep(()=>ctx.get("zortexTelemetry"),{source,phase:"onboarding",action:"connect",attempt:attempt+1,trigger:resumeSource===void 0?"automatic_startup":"recovery"});let connected;try{connected=await connection.run(()=>options.connect(source,requestId,signal,{automatic:true}));while("ok"in connected&&connected.ok.state==="waiting-user"&&connected.ok.automationActive&&options.job){await delay(100,void 0,{signal});connected=await options.job(requestId,signal)}if("ok"in connected&&connected.ok.state==="waiting-user")connection.mark({state:"waiting",reason:operationalReason(connected.ok.error?.code??"login_required")});connection.finish({state:"ok"in connected&&connected.ok.state==="connected"?"completed":signal.aborted||"ok"in connected&&connected.ok.state==="cancelled"?"cancelled":"ok"in connected&&connected.ok.state==="waiting-user"?"unknown":"failed",..."ok"in connected&&connected.ok.state==="connected"?{}:{reason:operationalReason("err"in connected?connected.err.code:connected.ok.error?.code)}})}catch{connection.finish({state:signal.aborted?"cancelled":"failed",reason:signal.aborted?"cancelled":"provider_failure"});return{err:{code:signal.aborted?"aborted":"unavailable",message:"Source authorization did not complete."}}}if("ok"in connected&&connected.ok.state==="connected")return{ok:void 0,connectionState:"connected",newlyConnected:true};if(!signal.aborted){const refreshed=await hub.status({signal});if("ok"in refreshed&&refreshed.ok.some(row=>row.source===source&&row.state==="connected"))return{ok:void 0,connectionState:"connected",newlyConnected:true}}const code="err"in connected?connected.err.code:connected.ok.error?.code??(connected.ok.state==="cancelled"?"aborted":connected.ok.state==="waiting-user"?"login_required":"unavailable");if("ok"in connected&&connected.ok.state==="waiting-user")return{err:{code,message:"The existing source authorization remains available for continuation."}};if(signal.aborted||attempt+1>=AUTOMATIC_ATTEMPTS||!isTransientAutomatic(code))return{err:{code,message:"Source authorization did not complete."}}}return{err:{code:"unavailable",message:"Source authorization did not complete."}}})}});if(!("ok"in result)||result.ok.state==="running"||result.ok.state==="cancelled")return result;const observed=result.ok.sources.filter(row=>batch.includes(row.source));if(!observed.length)throw Error("Startup receipt made no source progress.");for(const row of observed)attempted.add(row.source);({latest:prior,receipts}=startupHistory(fleet));if(!("ok"in prior)&&(!("err"in prior)||prior.err.code!=="not_found"))throw Error("Startup receipt unavailable.");if("ok"in prior&&prior.ok.state==="running")return prior}return result})})().then(result=>{if(stop.signal.aborted)operational?.finish({state:"cancelled",reason:"cancelled"});else if(result&&"ok"in result)operational?.finish({state:result.ok.state==="completed"?"completed":result.ok.state==="cancelled"?"cancelled":result.ok.state==="running"?"unknown":"failed"});else operational?.finish({state:feedbackStarted?"unknown":"cancelled",...feedbackStarted?{}:{reason:"cancelled"}});return result}).catch(async()=>{failed=true;operational?.finish({state:"failed",reason:"job_unavailable"});process.stderr.write("indra: initial connection pass could not complete; inspect startup status.\n");await withStartupFeedbackFlow("other",()=>createTraceRecorder(()=>ctx.get("zortexTelemetry"),"other").step("startup_failed","failed",{reason:"job_unavailable"}))}).finally(async()=>{lifetime.signal.removeEventListener("abort",close);if(feedbackStarted)await observe("terminal")})};let tail=runPass();const pending=new Map;const handle={get done(){return tail},wait(options2={}){const timeoutMs=options2.timeoutMs??3e4;if(!Number.isSafeInteger(timeoutMs)||timeoutMs<1||timeoutMs>3e4)return Promise.resolve({err:{code:"invalid_argument"}});if(options2.signal?.aborted)return Promise.resolve({err:{code:"aborted"}});return new Promise(resolve=>{let finished=false;const finish=value=>{if(finished)return;finished=true;clearTimeout(timer);options2.signal?.removeEventListener("abort",cancel);resolve(value)};const cancel=()=>finish({err:{code:"aborted"}}),timer=setTimeout(()=>finish({ok:{state:"running"}}),timeoutMs);options2.signal?.addEventListener("abort",cancel,{once:true});void(async()=>{let current,result;do{current=tail;result=await current}while(current!==tail);finish(result)})().catch(()=>finish({err:{code:"unavailable"}}))})},resume(source){if(!enabled||lifetime.signal.aborted||typeof source!=="string"||!/^[a-z][a-z0-9._-]{0,95}$/i.test(source))return Promise.resolve();const queued=pending.get(source);if(queued)return queued;const task=tail.then(()=>runPass(source));pending.set(source,task);tail=task;void task.then(()=>pending.delete(source),()=>pending.delete(source));return task},async close(){lifetime.abort();await tail;if(hosts.get(ctx)===handle)hosts.delete(ctx)}};if(enabled)hosts.set(ctx,handle);return handle}
@@ -1 +1 @@
1
- import{interpolate}from"@deepseek-ai/cordis-plugin-loader";import{prepareLevel1Configuration,updateLevel1Configuration}from"@zortexhq/plugin-connector-level1";import{isAbsolute}from"node:path";export async function configureThunderbirdLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Thunderbird selection.");const keys=Reflect.ownKeys(input),descriptor=Object.getOwnPropertyDescriptor(input,"port");if(keys.length!==1||keys[0]!=="port"||!descriptor?.enumerable||!("value"in descriptor)||!Number.isInteger(descriptor.value)||descriptor.value<1024||descriptor.value>65535)throw Error("Invalid Thunderbird selection.");const source="thunderbird",base={source,reloadRequired:false};const loader=ctx.get("loader"),vault=ctx.get("zortexVaultStore");if(!loader||!vault)return{...base,state:"unavailable",next:"The resident loader or secure Vault is unavailable."};const entries=[...loader.entries()].filter(row=>row.options.publicModule==="@zortexhq/plugin-connector-level1"||row.options.name==="@zortexhq/plugin-connector-level1");if(entries.length!==1)return{...base,state:"unavailable",next:"Load exactly one Level1 connector plugin before setup."};const entry=entries[0];let config;try{config=entry.fiber?.config??interpolate(entry.context,entry.options.config)}catch{return{...base,state:"configuration-required",next:"Check the Level1 plugin configuration."}}if(!config?.provisioningFile||!isAbsolute(config.provisioningFile))return{...base,state:"configuration-required",next:"Configure an absolute Level1 setup file."};try{const setupConfig=config;await updateLevel1Configuration(config.provisioningFile,async current=>{const saved=current??(await prepareLevel1Configuration(vault,{},setupConfig.runtimeDirectory?{runtimeDirectory:setupConfig.runtimeDirectory}:{})).configuration;const selected=[...new Set([...saved.sources??[],source])],requested=[...new Set([...saved.requestedSources??saved.sources??[],...selected])];return{configuration:{...saved,sources:selected,requestedSources:requested,prepared:{...saved.prepared,[source]:{mode:"fields",port:descriptor.value}}},value:void 0}});const enabled=!entry.disabled&&(config.sources===void 0||config.sources.includes(source));return{source,state:"configured",enabled,reloadRequired:true,next:enabled?"Restart the resident to register Thunderbird, then connect using its protected credential form.":"The port was saved; the existing disabled or explicit source setting still applies."}}catch{return{...base,state:"configuration-required",next:"Check the Level1 settings; no unrelated source was enabled."}}}
1
+ import{configurePreparedLevel1}from"./prepared-level1-setup.js";export async function configureThunderbirdLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Thunderbird selection.");const keys=Reflect.ownKeys(input),descriptor=Object.getOwnPropertyDescriptor(input,"port");if(keys.length!==1||keys[0]!=="port"||!descriptor?.enumerable||!("value"in descriptor)||!Number.isInteger(descriptor.value)||descriptor.value<1024||descriptor.value>65535)throw Error("Invalid Thunderbird selection.");return configurePreparedLevel1(ctx,"thunderbird",()=>({mode:"fields",port:descriptor.value}),"Restart the resident to register Thunderbird, then connect using its protected credential form.","The port was saved; the existing disabled or explicit source setting still applies.")}
@@ -1 +1 @@
1
- import{interpolate}from"@deepseek-ai/cordis-plugin-loader";import{prepareLevel1Configuration,updateLevel1Configuration}from"@zortexhq/plugin-connector-level1";import{isAbsolute}from"node:path";import{validWakatimeSelection}from"./wakatime-selection.js";export async function configureWakatimeLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Wakatime selection.");if(!validWakatimeSelection(input))throw Error("Invalid Wakatime selection.");const source="wakatime",base={source,reloadRequired:false};const loader=ctx.get("loader"),vault=ctx.get("zortexVaultStore");if(!loader||!vault)return{...base,state:"unavailable",next:"The resident loader or secure Vault is unavailable."};const entries=[...loader.entries()].filter(row=>row.options.publicModule==="@zortexhq/plugin-connector-level1"||row.options.name==="@zortexhq/plugin-connector-level1");if(entries.length!==1)return{...base,state:"unavailable",next:"Load exactly one Level1 connector plugin before setup."};const entry=entries[0];let config;try{config=entry.fiber?.config??interpolate(entry.context,entry.options.config)}catch{return{...base,state:"configuration-required",next:"Check the Level1 plugin configuration."}}if(!config?.provisioningFile||!isAbsolute(config.provisioningFile))return{...base,state:"configuration-required",next:"Configure an absolute Level1 setup file."};try{const setupConfig=config;await updateLevel1Configuration(config.provisioningFile,async current=>{const saved=current??(await prepareLevel1Configuration(vault,{},setupConfig.runtimeDirectory?{runtimeDirectory:setupConfig.runtimeDirectory}:{})).configuration;const selected=[...new Set([...saved.sources??[],source])],requested=[...new Set([...saved.requestedSources??saved.sources??[],...selected])];return{configuration:{...saved,sources:selected,requestedSources:requested,prepared:{...saved.prepared,[source]:{mode:"fields",username:input.username}}},value:void 0}});const enabled=!entry.disabled&&(config.sources===void 0||config.sources.includes(source));return{source,state:"configured",enabled,reloadRequired:true,next:enabled?"Restart the resident to register Wakatime, then connect using its protected OAuth access token form.":"The username was saved; the existing disabled or explicit source setting still applies."}}catch{return{...base,state:"configuration-required",next:"Check the Level1 settings; no unrelated source was enabled."}}}
1
+ import{configurePreparedLevel1}from"./prepared-level1-setup.js";import{validWakatimeSelection}from"./wakatime-selection.js";export async function configureWakatimeLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Wakatime selection.");if(!validWakatimeSelection(input))throw Error("Invalid Wakatime selection.");return configurePreparedLevel1(ctx,"wakatime",()=>({mode:"fields",username:input.username}),"Restart the resident to register Wakatime, then connect using its protected OAuth access token form.","The username was saved; the existing disabled or explicit source setting still applies.")}
@@ -1 +1 @@
1
- import{interpolate}from"@deepseek-ai/cordis-plugin-loader";import{prepareLevel1Configuration,updateLevel1Configuration}from"@zortexhq/plugin-connector-level1";import{isAbsolute}from"node:path";import{validWallabagSelection}from"./wallabag-selection.js";export async function configureWallabagLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Wallabag selection.");if(!validWallabagSelection(input))throw Error("Invalid Wallabag selection.");const source="wallabag",base={source,reloadRequired:false};const loader=ctx.get("loader"),vault=ctx.get("zortexVaultStore");if(!loader||!vault)return{...base,state:"unavailable",next:"The resident loader or secure Vault is unavailable."};const entries=[...loader.entries()].filter(row=>row.options.publicModule==="@zortexhq/plugin-connector-level1"||row.options.name==="@zortexhq/plugin-connector-level1");if(entries.length!==1)return{...base,state:"unavailable",next:"Load exactly one Level1 connector plugin before setup."};const entry=entries[0];let config;try{config=entry.fiber?.config??interpolate(entry.context,entry.options.config)}catch{return{...base,state:"configuration-required",next:"Check the Level1 plugin configuration."}}if(!config?.provisioningFile||!isAbsolute(config.provisioningFile))return{...base,state:"configuration-required",next:"Configure an absolute Level1 setup file."};try{const setupConfig=config;await updateLevel1Configuration(config.provisioningFile,async current=>{const saved=current??(await prepareLevel1Configuration(vault,{},setupConfig.runtimeDirectory?{runtimeDirectory:setupConfig.runtimeDirectory}:{})).configuration;const selected=[...new Set([...saved.sources??[],source])],requested=[...new Set([...saved.requestedSources??saved.sources??[],...selected])];return{configuration:{...saved,sources:selected,requestedSources:requested,prepared:{...saved.prepared,[source]:{mode:"fields",instanceUrl:input.instanceUrl,username:input.username}}},value:void 0}});const enabled=!entry.disabled&&(config.sources===void 0||config.sources.includes(source));return{source,state:"configured",enabled,reloadRequired:true,next:enabled?"Restart the resident to register Wallabag, then connect using its protected access token form.":"The instance URL was saved; the existing disabled or explicit source setting still applies."}}catch{return{...base,state:"configuration-required",next:"Check the Level1 settings; no unrelated source was enabled."}}}
1
+ import{configurePreparedLevel1}from"./prepared-level1-setup.js";import{validWallabagSelection}from"./wallabag-selection.js";export async function configureWallabagLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Wallabag selection.");if(!validWallabagSelection(input))throw Error("Invalid Wallabag selection.");return configurePreparedLevel1(ctx,"wallabag",()=>({mode:"fields",instanceUrl:input.instanceUrl,username:input.username}),"Restart the resident to register Wallabag, then connect using its protected access token form.","The instance URL was saved; the existing disabled or explicit source setting still applies.")}
package/dist/web.js CHANGED
@@ -1,2 +1,2 @@
1
- import{validateJoplinResult}from"./joplin-selection.js";import{lstat,readFile}from"node:fs/promises";import{isAbsolute,resolve}from"node:path";import*as galaxy from"@zortexhq/plugin-galaxy-ui";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{openProduct}from"./profile.js";import{readPublicActionProgress}from"./public-action-progress.js";import{provideAutoSync}from"./auto-sync.js";import{chooseWebPort}from"./web-port.js";import{residentStatus,startResident,residentInitialConnections,residentConnect,residentConnectRecovery,residentConnectReauthorize,residentConnectReadwiseMcpWrite,residentConnectGmailWrite,residentConnectManual,residentConnectJob,residentCancelConnect,residentConnectorStatus,residentConfigureNativeFiles,residentConfigureZotero,residentConfigureOwnTracks,residentConfigureZoom,residentConfigureBox,residentConfigureFront,residentConfigureHubSpot,residentConfigureGoogleContacts,residentConfigureGoogleChat,residentConfigureSalesforce,residentConfigureZendesk,residentConfigureDropbox,residentConfigureDiscord,residentConfigureProtonMail,residentConfigureJoplin,residentConfigureThunderbird,residentConfigureWeChat,residentConfigureCopyQ,residentConfigureFreshdesk,residentConfigureFigma,residentConfigureSmartsheet,residentConfigureNextcloud,residentConfigureZulip,residentConfigureFreshRSS,residentConfigureMiniflux,residentConfigureMattermost,residentConfigureWallabag,residentConfigureCalcom,residentConfigureWakatime,residentGatewayCall,residentCheck,residentRead}from"./resident-platform.js";import{fileURLToPath}from"node:url";import{openHelpAfterStartup}from"./help-launch.js";import{HELP_CATALOG}from"./source-catalog.js";import{validateNativeFileResult}from"./recovery.js";import{mergedRecoveryProgress}from"./recovery-progress.js";import{sourceSupport,recoverySetupFlags}from"./recovery-support.js";export const WEB_USAGE="Use indra web --root <absolute directory> [--port 8781] [--no-open].";const entrypoint=fileURLToPath(new URL("./cli.js",import.meta.url));export function parseWebArgs(argv){let root,port=8781,portChosen=false,noOpen=false;for(let i=0;i<argv.length;i++){const arg=argv[i];if(arg==="--root"){if(root||!argv[i+1])throw Error("Pass one --root.");root=argv[++i]}else if(arg==="--port"){const value=argv[++i];if(!value||!/^\d{1,5}$/.test(value)||Number(value)>65535)throw Error("Port must be 0-65535.");port=Number(value);portChosen=true}else if(arg==="--no-open")noOpen=true;else throw Error(WEB_USAGE)}if(!root||!isAbsolute(root))throw Error("An explicit absolute data root is required.");return{root:resolve(root),port,portChosen,noOpen}}export async function launchWeb(argv){const options=parseWebArgs(argv);const productVersion=JSON.parse(await readFile(new URL("../package.json",import.meta.url),"utf8")).version;if(await lstat(options.root).then(stat=>stat.isSymbolicLink(),error=>{if(error.code==="ENOENT")return false;throw error}))throw Error("Product root cannot be a link.");const chosen=await chooseWebPort(options.port,options.portChosen);const app=await openProduct(options.root);const stop=new AbortController;let finishing;let help;let closing=false;const residentReport=async()=>{const result=await residentGatewayCall(options.root,{operation:"manage",args:{what:"onboarding"}},stop.signal);if(!("ok"in result))throw Error("The background connection report is unavailable.");return result.ok};const authorization={check:(source,signal)=>residentCheck(options.root,source,signal),status:signal=>residentConnectorStatus(options.root,signal),read:(source,request,signal)=>residentRead(options.root,source,request,signal),connect:async(source,requestId,signal,settings)=>{await startResident(options.root,entrypoint);return settings?.gmailWrite?residentConnectGmailWrite(options.root,requestId,signal):settings?.readwiseMcpWrite?residentConnectReadwiseMcpWrite(options.root,requestId,signal):settings?.selectAccount?residentConnectRecovery(options.root,source,requestId,signal):settings?.reauthorize?residentConnectReauthorize(options.root,source,requestId,signal):settings?.manualPresentation==="return-url"?residentConnectManual(options.root,source,requestId,signal):residentConnect(options.root,source,requestId,signal,{automatic:false})},job:async(requestId,signal)=>{await startResident(options.root,entrypoint);return residentConnectJob(options.root,requestId,signal)},cancel:(requestId,generation,challengeRef)=>residentCancelConnect(options.root,requestId,generation,challengeRef),configureWeChat:async(port,signal)=>validateNativeFileResult("wechat",await residentConfigureWeChat(options.root,port,signal)),configureJoplin:async(selection,signal)=>validateJoplinResult(await residentConfigureJoplin(options.root,selection,signal)),configureThunderbird:async(port,signal)=>validateNativeFileResult("thunderbird",await residentConfigureThunderbird(options.root,port,signal)),configureDiscord:async(selection,signal)=>validateNativeFileResult("discord",await residentConfigureDiscord(options.root,selection,signal)),configureProtonMail:async(port,signal)=>validateNativeFileResult("proton-mail",await residentConfigureProtonMail(options.root,port,signal)),configureZulip:async(selection,signal)=>validateNativeFileResult("zulip",await residentConfigureZulip(options.root,selection,signal)),configureFreshRSS:async(selection,signal)=>validateNativeFileResult("freshrss",await residentConfigureFreshRSS(options.root,selection,signal)),configureMiniflux:async(selection,signal)=>validateNativeFileResult("miniflux",await residentConfigureMiniflux(options.root,selection,signal)),configureMattermost:async(selection,signal)=>validateNativeFileResult("mattermost",await residentConfigureMattermost(options.root,selection,signal)),configureWallabag:async(selection,signal)=>validateNativeFileResult("wallabag",await residentConfigureWallabag(options.root,selection,signal)),configureCalcom:async(selection,signal)=>validateNativeFileResult("calcom",await residentConfigureCalcom(options.root,selection,signal)),configureWakatime:async(selection,signal)=>validateNativeFileResult("wakatime",await residentConfigureWakatime(options.root,selection,signal)),configureNextcloud:async(instanceUrl,signal)=>validateNativeFileResult("nextcloud",await residentConfigureNextcloud(options.root,instanceUrl,signal)),configureZoom:async(selection,signal)=>validateNativeFileResult("zoom",await residentConfigureZoom(options.root,selection,signal)),configureBox:async(selection,signal)=>validateNativeFileResult("box",await residentConfigureBox(options.root,selection,signal)),configureFront:async(selection,signal)=>validateNativeFileResult("front",await residentConfigureFront(options.root,selection,signal)),configureHubSpot:async(selection,signal)=>validateNativeFileResult("hubspot",await residentConfigureHubSpot(options.root,selection,signal)),configureGoogleContacts:async(selection,signal)=>validateNativeFileResult("google-contacts",await residentConfigureGoogleContacts(options.root,selection,signal)),configureGoogleChat:async(selection,signal)=>validateNativeFileResult("google-chat",await residentConfigureGoogleChat(options.root,selection,signal)),configureSalesforce:async(selection,signal)=>validateNativeFileResult("salesforce",await residentConfigureSalesforce(options.root,selection,signal)),configureZendesk:async(selection,signal)=>validateNativeFileResult("zendesk",await residentConfigureZendesk(options.root,selection,signal)),configureDropbox:async(selection,signal)=>validateNativeFileResult("dropbox",await residentConfigureDropbox(options.root,selection,signal)),configureFigma:async(mode,signal)=>validateNativeFileResult("figma",await residentConfigureFigma(options.root,mode,signal)),configureSmartsheet:async(region,signal)=>validateNativeFileResult("smartsheet",await residentConfigureSmartsheet(options.root,region,signal)),configureFreshdesk:async(subdomain,signal)=>validateNativeFileResult("freshdesk",await residentConfigureFreshdesk(options.root,subdomain,signal)),configureCopyQ:async(executable,session,signal)=>validateNativeFileResult("copyq",await residentConfigureCopyQ(options.root,executable,session,signal)),configureOwnTracks:async(port,signal)=>validateNativeFileResult("owntracks",await residentConfigureOwnTracks(options.root,port,signal)),configureZotero:async(libraryId,libraryType,signal)=>validateNativeFileResult("zotero",await residentConfigureZotero(options.root,libraryId,libraryType,signal)),configureNativeFiles:async(source,roots,signal)=>validateNativeFileResult(source,await residentConfigureNativeFiles(options.root,source,roots,signal))};try{await startResident(options.root,entrypoint);const startup={done:residentInitialConnections(options.root,stop.signal)};void startup.done.catch(()=>{});provideAutoSync(app.context,options.root,{residentStatus:async()=>{const value=(await residentStatus(options.root)).autoSync;return Array.isArray(value)?value:[]}});const page=app.context.plugin(galaxy,{productVersion,port:chosen.port,directorySources:HELP_CATALOG.map(([source])=>source),sourceProgress:async()=>mergedRecoveryProgress(app.context),sourceSupport:async()=>{const result=await authorization.status(stop.signal);if(!("ok"in result))throw Error("Resident connector support unavailable");const listed=new Set(result.ok.map(row=>row.source));const states=[...result.ok,...(result.pending??[]).filter(row=>!listed.has(row.source)).map(row=>({source:row.source,state:"unavailable",registration:"deferred"}))];for(const row of states)listed.add(row.source);return[...states.map(row=>sourceSupport({...row,connection:row.state,...result.pending?.find(item=>item.source===row.source)?.reason?{setupReason:result.pending.find(item=>item.source===row.source).reason}:{}},Object.keys(recoverySetupFlags(row.source,authorization)).length>0)),...HELP_CATALOG.filter(([source])=>!listed.has(source)&&!(source==="teams"&&listed.has("microsoft-teams"))).map(([source])=>sourceSupport({source,catalogOnly:true},false))]},connectionStatus:async()=>{const result=await authorization.status(stop.signal);if(!("ok"in result))throw Error("Resident connector status unavailable");const report=await residentReport().catch(()=>null);const reads=new Map((report?.sources??[]).filter(row=>row.connection==="connected"&&!row.errorCode&&(row.availability==="read"||row.availability==="actions")&&row.operation==="succeeded"&&Number.isSafeInteger(row.returned)&&row.returned>=0&&(row.returned>0?row.read==="first-record":row.read==="empty")).map(row=>[row.source,row.returned]));const publicReads=new Map(readPublicActionProgress(app.context).map(item=>[item.source,item]));return result.ok.map(row=>{const publicRead=publicReads.get(row.source);return{...row,...row.state==="connected"&&reads.has(row.source)?{readEvidence:{state:"succeeded",returned:reads.get(row.source)}}:{},...publicRead?{publicRead}:{}}})}});await page.await();if(page.state!==2)throw Error("The Galaxy page did not start.");const{url,port}=app.context.zortexGalaxyPage;let opened=false;if(!options.noOpen)try{await openConnectionUrl(url);opened=true}catch{}process.stdout.write(JSON.stringify({port,version:productVersion,url,opened,...chosen.moved?{notice:`Port ${options.port} is used by another program, possibly an older Zortex window, so this version opened on port ${port}.`}:{}})+"\n");process.stdout.write(`zortex web: ${url}
2
- `);finishing=(async()=>{await startup.done;if(closing)return;const report=await residentReport();if(closing)return;process.stdout.write(JSON.stringify({onboarding:report})+"\n");help=await openHelpAfterStartup(app.context,startup,{authorization,report:residentReport,exposeOnly:options.noOpen,open:async helpUrl=>{if(closing)return;process.stdout.write(JSON.stringify({help:{url:helpUrl}})+"\n");if(!options.noOpen)await openConnectionUrl(helpUrl)}})})().catch(()=>{if(!closing)process.stderr.write("indra: startup results unavailable; inspect startup status.\n")});await new Promise(done=>{const stop2=()=>{process.removeListener("SIGINT",stop2);process.removeListener("SIGTERM",stop2);done()};process.once("SIGINT",stop2);process.once("SIGTERM",stop2)})}finally{closing=true;stop.abort();try{await finishing;await help?.close();await app.context.get("zortexConnectorHub")?.settleObservations?.({closing:true});const sent=await app.context.get("zortexPostHog")?.flush({wait:true});if(sent&&"err"in sent)process.stderr.write("indra feedback: delivery pending; retained for the next run.\n")}finally{await app.close()}}}
1
+ import{validateJoplinResult}from"./joplin-selection.js";import{lstat,readFile}from"node:fs/promises";import{isAbsolute,resolve}from"node:path";import*as galaxy from"@zortexhq/plugin-galaxy-ui";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{openProduct}from"./profile.js";import{readPublicActionProgress}from"./public-action-progress.js";import{provideAutoSync}from"./auto-sync.js";import{chooseWebPort}from"./web-port.js";import{residentStatus,startResident,residentInitialConnections,residentConnect,residentConnectRecovery,residentConnectReauthorize,residentConnectReadwiseMcpWrite,residentConnectGmailWrite,residentConnectManual,residentReconnectSaved,residentConnectJob,residentCancelConnect,residentConnectorStatus,residentConfigureNativeFiles,residentConfigureZotero,residentConfigureOwnTracks,residentConfigureZoom,residentConfigureBox,residentConfigureFront,residentConfigureHubSpot,residentConfigureGoogleContacts,residentConfigureGoogleChat,residentConfigureSalesforce,residentConfigureZendesk,residentConfigureDropbox,residentConfigureDiscord,residentConfigureProtonMail,residentConfigureJoplin,residentConfigureThunderbird,residentConfigureWeChat,residentConfigureCopyQ,residentConfigureFreshdesk,residentConfigureFigma,residentConfigureSmartsheet,residentConfigureNextcloud,residentConfigureZulip,residentConfigureFreshRSS,residentConfigureMiniflux,residentConfigureMattermost,residentConfigureWallabag,residentConfigureCalcom,residentConfigureWakatime,residentGatewayCall,residentCheck,residentRead}from"./resident-platform.js";import{fileURLToPath}from"node:url";import{HELP_CATALOG}from"./source-catalog.js";import{startGuidedRecovery,validateNativeFileResult}from"./recovery.js";import{mergedRecoveryProgress}from"./recovery-progress.js";import{sourceSupport,recoverySetupFlags}from"./recovery-support.js";export const WEB_USAGE="Use indra web --root <absolute directory> [--port 8781] [--no-open].";const entrypoint=fileURLToPath(new URL("./cli.js",import.meta.url));export function parseWebArgs(argv){let root,port=8781,portChosen=false,noOpen=false;for(let i=0;i<argv.length;i++){const arg=argv[i];if(arg==="--root"){if(root||!argv[i+1])throw Error("Pass one --root.");root=argv[++i]}else if(arg==="--port"){const value=argv[++i];if(!value||!/^\d{1,5}$/.test(value)||Number(value)>65535)throw Error("Port must be 0-65535.");port=Number(value);portChosen=true}else if(arg==="--no-open")noOpen=true;else throw Error(WEB_USAGE)}if(!root||!isAbsolute(root))throw Error("An explicit absolute data root is required.");return{root:resolve(root),port,portChosen,noOpen}}export async function launchWeb(argv){const options=parseWebArgs(argv);const productVersion=JSON.parse(await readFile(new URL("../package.json",import.meta.url),"utf8")).version;if(await lstat(options.root).then(stat=>stat.isSymbolicLink(),error=>{if(error.code==="ENOENT")return false;throw error}))throw Error("Product root cannot be a link.");const chosen=await chooseWebPort(options.port,options.portChosen);const app=await openProduct(options.root);const stop=new AbortController;let finishing;let connectionSession;let openingConnections;let closing=false;const residentReport=async()=>{const result=await residentGatewayCall(options.root,{operation:"manage",args:{what:"onboarding"}},stop.signal);if(!("ok"in result))throw Error("The background connection report is unavailable.");return result.ok};const authorization={reconnectSaved:(source,signal)=>residentReconnectSaved(options.root,source,signal),check:(source,signal)=>residentCheck(options.root,source,signal),status:signal=>residentConnectorStatus(options.root,signal),read:(source,request,signal)=>residentRead(options.root,source,request,signal),connect:async(source,requestId,signal,settings)=>{await startResident(options.root,entrypoint);return settings?.gmailWrite?residentConnectGmailWrite(options.root,requestId,signal):settings?.readwiseMcpWrite?residentConnectReadwiseMcpWrite(options.root,requestId,signal):settings?.selectAccount?residentConnectRecovery(options.root,source,requestId,signal):settings?.reauthorize?residentConnectReauthorize(options.root,source,requestId,signal):settings?.manualPresentation==="return-url"?residentConnectManual(options.root,source,requestId,signal):residentConnect(options.root,source,requestId,signal,{automatic:false})},job:async(requestId,signal)=>{await startResident(options.root,entrypoint);return residentConnectJob(options.root,requestId,signal)},cancel:(requestId,generation,challengeRef)=>residentCancelConnect(options.root,requestId,generation,challengeRef),configureWeChat:async(port,signal)=>validateNativeFileResult("wechat",await residentConfigureWeChat(options.root,port,signal)),configureJoplin:async(selection,signal)=>validateJoplinResult(await residentConfigureJoplin(options.root,selection,signal)),configureThunderbird:async(port,signal)=>validateNativeFileResult("thunderbird",await residentConfigureThunderbird(options.root,port,signal)),configureDiscord:async(selection,signal)=>validateNativeFileResult("discord",await residentConfigureDiscord(options.root,selection,signal)),configureProtonMail:async(port,signal)=>validateNativeFileResult("proton-mail",await residentConfigureProtonMail(options.root,port,signal)),configureZulip:async(selection,signal)=>validateNativeFileResult("zulip",await residentConfigureZulip(options.root,selection,signal)),configureFreshRSS:async(selection,signal)=>validateNativeFileResult("freshrss",await residentConfigureFreshRSS(options.root,selection,signal)),configureMiniflux:async(selection,signal)=>validateNativeFileResult("miniflux",await residentConfigureMiniflux(options.root,selection,signal)),configureMattermost:async(selection,signal)=>validateNativeFileResult("mattermost",await residentConfigureMattermost(options.root,selection,signal)),configureWallabag:async(selection,signal)=>validateNativeFileResult("wallabag",await residentConfigureWallabag(options.root,selection,signal)),configureCalcom:async(selection,signal)=>validateNativeFileResult("calcom",await residentConfigureCalcom(options.root,selection,signal)),configureWakatime:async(selection,signal)=>validateNativeFileResult("wakatime",await residentConfigureWakatime(options.root,selection,signal)),configureNextcloud:async(instanceUrl,signal)=>validateNativeFileResult("nextcloud",await residentConfigureNextcloud(options.root,instanceUrl,signal)),configureZoom:async(selection,signal)=>validateNativeFileResult("zoom",await residentConfigureZoom(options.root,selection,signal)),configureBox:async(selection,signal)=>validateNativeFileResult("box",await residentConfigureBox(options.root,selection,signal)),configureFront:async(selection,signal)=>validateNativeFileResult("front",await residentConfigureFront(options.root,selection,signal)),configureHubSpot:async(selection,signal)=>validateNativeFileResult("hubspot",await residentConfigureHubSpot(options.root,selection,signal)),configureGoogleContacts:async(selection,signal)=>validateNativeFileResult("google-contacts",await residentConfigureGoogleContacts(options.root,selection,signal)),configureGoogleChat:async(selection,signal)=>validateNativeFileResult("google-chat",await residentConfigureGoogleChat(options.root,selection,signal)),configureSalesforce:async(selection,signal)=>validateNativeFileResult("salesforce",await residentConfigureSalesforce(options.root,selection,signal)),configureZendesk:async(selection,signal)=>validateNativeFileResult("zendesk",await residentConfigureZendesk(options.root,selection,signal)),configureDropbox:async(selection,signal)=>validateNativeFileResult("dropbox",await residentConfigureDropbox(options.root,selection,signal)),configureFigma:async(mode,signal)=>validateNativeFileResult("figma",await residentConfigureFigma(options.root,mode,signal)),configureSmartsheet:async(region,signal)=>validateNativeFileResult("smartsheet",await residentConfigureSmartsheet(options.root,region,signal)),configureFreshdesk:async(subdomain,signal)=>validateNativeFileResult("freshdesk",await residentConfigureFreshdesk(options.root,subdomain,signal)),configureCopyQ:async(executable,session,signal)=>validateNativeFileResult("copyq",await residentConfigureCopyQ(options.root,executable,session,signal)),configureOwnTracks:async(port,signal)=>validateNativeFileResult("owntracks",await residentConfigureOwnTracks(options.root,port,signal)),configureZotero:async(libraryId,libraryType,signal)=>validateNativeFileResult("zotero",await residentConfigureZotero(options.root,libraryId,libraryType,signal)),configureNativeFiles:async(source,roots,signal)=>validateNativeFileResult(source,await residentConfigureNativeFiles(options.root,source,roots,signal))};const connectionRequest=async(input,signal)=>{if(!connectionSession||connectionSession.snapshot().state==="closed"){openingConnections??=residentReport().then(report=>startGuidedRecovery(app.context,{sources:report.sources,authorization}));try{connectionSession=await openingConnections}finally{openingConnections=void 0}}return connectionSession.request(input,signal)};try{await startResident(options.root,entrypoint);const startup={done:residentInitialConnections(options.root,stop.signal)};void startup.done.catch(()=>{});provideAutoSync(app.context,options.root,{residentStatus:async()=>{const value=(await residentStatus(options.root)).autoSync;return Array.isArray(value)?value:[]}});const page=app.context.plugin(galaxy,{productVersion,port:chosen.port,connectionRequest,directorySources:HELP_CATALOG.map(([source])=>source),sourceProgress:async()=>mergedRecoveryProgress(app.context),sourceSupport:async()=>{const result=await authorization.status(stop.signal);if(!("ok"in result))throw Error("Resident connector support unavailable");const listed=new Set(result.ok.map(row=>row.source));const states=[...result.ok,...(result.pending??[]).filter(row=>!listed.has(row.source)).map(row=>({source:row.source,state:"unavailable",registration:"deferred"}))];for(const row of states)listed.add(row.source);return[...states.map(row=>sourceSupport({...row,connection:row.state,...result.pending?.find(item=>item.source===row.source)?.reason?{setupReason:result.pending.find(item=>item.source===row.source).reason}:{}},Object.keys(recoverySetupFlags(row.source,authorization)).length>0)),...HELP_CATALOG.filter(([source])=>!listed.has(source)&&!(source==="teams"&&listed.has("microsoft-teams"))).map(([source])=>sourceSupport({source,catalogOnly:true},false))]},connectionStatus:async()=>{const result=await authorization.status(stop.signal);if(!("ok"in result))throw Error("Resident connector status unavailable");const report=await residentReport().catch(()=>null);const reads=new Map((report?.sources??[]).filter(row=>row.connection==="connected"&&!row.errorCode&&(row.availability==="read"||row.availability==="actions")&&row.operation==="succeeded"&&Number.isSafeInteger(row.returned)&&row.returned>=0&&(row.returned>0?row.read==="first-record":row.read==="empty")).map(row=>[row.source,row.returned]));const publicReads=new Map(readPublicActionProgress(app.context).map(item=>[item.source,item]));return result.ok.map(row=>{const publicRead=publicReads.get(row.source);return{...row,...row.state==="connected"&&reads.has(row.source)?{readEvidence:{state:"succeeded",returned:reads.get(row.source)}}:{},...publicRead?{publicRead}:{}}})}});await page.await();if(page.state!==2)throw Error("The Galaxy page did not start.");const{url,port}=app.context.zortexGalaxyPage;let opened=false;if(!options.noOpen)try{await openConnectionUrl(url);opened=true}catch{}process.stdout.write(JSON.stringify({port,version:productVersion,url,opened,...chosen.moved?{notice:`Port ${options.port} is used by another program, possibly an older Zortex window, so this version opened on port ${port}.`}:{}})+"\n");process.stdout.write(`zortex web: ${url}
2
+ `);finishing=(async()=>{await startup.done;if(closing)return;const report=await residentReport();if(!closing)process.stdout.write(JSON.stringify({onboarding:report})+"\n")})().catch(()=>{if(!closing)process.stderr.write("indra: startup results unavailable; refresh Apps to retry.\n")});await new Promise(done=>{const stop2=()=>{process.removeListener("SIGINT",stop2);process.removeListener("SIGTERM",stop2);done()};process.once("SIGINT",stop2);process.once("SIGTERM",stop2)})}finally{closing=true;stop.abort();try{await finishing;await openingConnections?.catch(()=>void 0);await connectionSession?.close();await app.context.get("zortexConnectorHub")?.settleObservations?.({closing:true});const sent=await app.context.get("zortexPostHog")?.flush({wait:true});if(sent&&"err"in sent)process.stderr.write("indra feedback: delivery pending; retained for the next run.\n")}finally{await app.close()}}}
@@ -1 +1 @@
1
- import{interpolate}from"@deepseek-ai/cordis-plugin-loader";import{prepareLevel1Configuration,updateLevel1Configuration}from"@zortexhq/plugin-connector-level1";import{isAbsolute}from"node:path";import{validZendeskSelection}from"./zendesk-selection.js";export async function configureZendeskLevel1(ctx,input){if(!validZendeskSelection(input))throw Error("Invalid Zendesk selection.");const selection={subdomain:input.subdomain,clientId:input.clientId,loopbackPort:input.loopbackPort};const source="zendesk",base={source,reloadRequired:false};const loader=ctx.get("loader"),vault=ctx.get("zortexVaultStore");if(!loader||!vault)return{...base,state:"unavailable",next:"The resident loader or secure Vault is unavailable."};const entries=[...loader.entries()].filter(row=>row.options.publicModule==="@zortexhq/plugin-connector-level1"||row.options.name==="@zortexhq/plugin-connector-level1");if(entries.length!==1)return{...base,state:"unavailable",next:"Load exactly one Level1 connector plugin before setup."};const entry=entries[0];let config;try{config=entry.fiber?.config??interpolate(entry.context,entry.options.config)}catch{return{...base,state:"configuration-required",next:"Check the Level1 plugin configuration."}}if(!config?.provisioningFile||!isAbsolute(config.provisioningFile))return{...base,state:"configuration-required",next:"Configure an absolute Level1 setup file."};try{const setupConfig=config;await updateLevel1Configuration(config.provisioningFile,async current=>{const saved=current??(await prepareLevel1Configuration(vault,{},setupConfig.runtimeDirectory?{runtimeDirectory:setupConfig.runtimeDirectory}:{})).configuration;const selected=[...new Set([...saved.sources??[],source])],requested=[...new Set([...saved.requestedSources??saved.sources??[],...selected])];return{configuration:{...saved,sources:selected,requestedSources:requested,prepared:{...saved.prepared,[source]:{mode:"oauth",...selection}}},value:void 0}});const enabled=!entry.disabled&&(config.sources===void 0||config.sources.includes(source));return{source,state:"configured",enabled,reloadRequired:true,next:enabled?"Restart the resident to register Zendesk, then choose Connect to begin OAuth authorization.":"The selection was saved; the existing disabled or explicit source setting still applies."}}catch{return{...base,state:"configuration-required",next:"Check the Level1 settings; no unrelated source was enabled."}}}
1
+ import{configurePreparedLevel1}from"./prepared-level1-setup.js";import{validZendeskSelection}from"./zendesk-selection.js";export async function configureZendeskLevel1(ctx,input){if(!validZendeskSelection(input))throw Error("Invalid Zendesk selection.");const selection={subdomain:input.subdomain,clientId:input.clientId,loopbackPort:input.loopbackPort};return configurePreparedLevel1(ctx,"zendesk",()=>({mode:"oauth",...selection}),"Restart the resident to register Zendesk, then choose Connect to begin OAuth authorization.")}
@@ -1 +1 @@
1
- import{interpolate}from"@deepseek-ai/cordis-plugin-loader";import{prepareLevel1Configuration,updateLevel1Configuration,createPreparedServiceSource}from"@zortexhq/plugin-connector-level1";import{isAbsolute}from"node:path";export async function configureZoomLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Zoom selection.");const keys=Reflect.ownKeys(input),client=Object.getOwnPropertyDescriptor(input,"clientId");if(keys.length!==1||keys.some(key=>key!=="clientId")||!client?.enumerable||!("value"in client)||typeof client.value!=="string")throw Error("Invalid Zoom selection.");createPreparedServiceSource("zoom",{mode:"oauth",clientId:client.value});const source="zoom",base={source,reloadRequired:false};const loader=ctx.get("loader"),vault=ctx.get("zortexVaultStore");if(!loader||!vault)return{...base,state:"unavailable",next:"The resident loader or secure Vault is unavailable."};const entries=[...loader.entries()].filter(row=>row.options.publicModule==="@zortexhq/plugin-connector-level1"||row.options.name==="@zortexhq/plugin-connector-level1");if(entries.length!==1)return{...base,state:"unavailable",next:"Load exactly one Level1 connector plugin before setup."};const entry=entries[0];let config;try{config=entry.fiber?.config??interpolate(entry.context,entry.options.config)}catch{return{...base,state:"configuration-required",next:"Check the Level1 plugin configuration."}}if(!config?.provisioningFile||!isAbsolute(config.provisioningFile))return{...base,state:"configuration-required",next:"Configure an absolute Level1 setup file."};try{const setupConfig=config;await updateLevel1Configuration(config.provisioningFile,async current=>{const saved=current??(await prepareLevel1Configuration(vault,{},setupConfig.runtimeDirectory?{runtimeDirectory:setupConfig.runtimeDirectory}:{})).configuration;const selected=[...new Set([...saved.sources??[],source])],requested=[...new Set([...saved.requestedSources??saved.sources??[],...selected])];return{configuration:{...saved,sources:selected,requestedSources:requested,prepared:{...saved.prepared,[source]:{mode:"oauth",clientId:client.value}}},value:void 0}});const enabled=!entry.disabled&&(config.sources===void 0||config.sources.includes(source));return{source,state:"configured",enabled,reloadRequired:true,next:enabled?"Restart the resident to register Zoom, then choose Connect to begin OAuth authorization.":"The selection was saved; the existing disabled or explicit source setting still applies."}}catch{return{...base,state:"configuration-required",next:"Check the Level1 settings; no unrelated source was enabled."}}}
1
+ import{configurePreparedLevel1}from"./prepared-level1-setup.js";import{createPreparedServiceSource}from"@zortexhq/plugin-connector-level1";export async function configureZoomLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Zoom selection.");const keys=Reflect.ownKeys(input),client=Object.getOwnPropertyDescriptor(input,"clientId");if(keys.length!==1||keys.some(key=>key!=="clientId")||!client?.enumerable||!("value"in client)||typeof client.value!=="string")throw Error("Invalid Zoom selection.");createPreparedServiceSource("zoom",{mode:"oauth",clientId:client.value});return configurePreparedLevel1(ctx,"zoom",()=>({mode:"oauth",clientId:client.value}),"Restart the resident to register Zoom, then choose Connect to begin OAuth authorization.")}
@@ -1 +1 @@
1
- import{interpolate}from"@deepseek-ai/cordis-plugin-loader";import{prepareLevel1Configuration,updateLevel1Configuration}from"@zortexhq/plugin-connector-level1";import{isAbsolute}from"node:path";import{validZulipSelection}from"./zulip-selection.js";export async function configureZulipLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Zulip selection.");if(!validZulipSelection(input))throw Error("Invalid Zulip selection.");const source="zulip",base={source,reloadRequired:false};const loader=ctx.get("loader"),vault=ctx.get("zortexVaultStore");if(!loader||!vault)return{...base,state:"unavailable",next:"The resident loader or secure Vault is unavailable."};const entries=[...loader.entries()].filter(row=>row.options.publicModule==="@zortexhq/plugin-connector-level1"||row.options.name==="@zortexhq/plugin-connector-level1");if(entries.length!==1)return{...base,state:"unavailable",next:"Load exactly one Level1 connector plugin before setup."};const entry=entries[0];let config;try{config=entry.fiber?.config??interpolate(entry.context,entry.options.config)}catch{return{...base,state:"configuration-required",next:"Check the Level1 plugin configuration."}}if(!config?.provisioningFile||!isAbsolute(config.provisioningFile))return{...base,state:"configuration-required",next:"Configure an absolute Level1 setup file."};try{const setupConfig=config;await updateLevel1Configuration(config.provisioningFile,async current=>{const saved=current??(await prepareLevel1Configuration(vault,{},setupConfig.runtimeDirectory?{runtimeDirectory:setupConfig.runtimeDirectory}:{})).configuration;const selected=[...new Set([...saved.sources??[],source])],requested=[...new Set([...saved.requestedSources??saved.sources??[],...selected])];return{configuration:{...saved,sources:selected,requestedSources:requested,prepared:{...saved.prepared,[source]:{mode:"fields",instanceUrl:input.instanceUrl,username:input.username}}},value:void 0}});const enabled=!entry.disabled&&(config.sources===void 0||config.sources.includes(source));return{source,state:"configured",enabled,reloadRequired:true,next:enabled?"Restart the resident to register Zulip, then connect using its protected API key form.":"The instance URL was saved; the existing disabled or explicit source setting still applies."}}catch{return{...base,state:"configuration-required",next:"Check the Level1 settings; no unrelated source was enabled."}}}
1
+ import{configurePreparedLevel1}from"./prepared-level1-setup.js";import{validZulipSelection}from"./zulip-selection.js";export async function configureZulipLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Zulip selection.");if(!validZulipSelection(input))throw Error("Invalid Zulip selection.");return configurePreparedLevel1(ctx,"zulip",()=>({mode:"fields",instanceUrl:input.instanceUrl,username:input.username}),"Restart the resident to register Zulip, then connect using its protected API key form.","The instance URL was saved; the existing disabled or explicit source setting still applies.")}