@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 +1 @@
1
- const failure=()=>Error("Invalid or expired Joplin pairing. Start again from Help.");const validPort=port=>Number.isInteger(port)&&Number(port)>=1024&&Number(port)<=65535;function validate(input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw failure();for(const key of Reflect.ownKeys(input)){const d=Object.getOwnPropertyDescriptor(input,key);if(typeof key!=="string"||!d.enumerable||!("value"in d))throw failure()}const phase="phase"in input?input.phase:"legacy";const keys={legacy:["port"],start:["phase"],inspect:["phase","pairingId","pluginPublicKey"],confirm:["phase","pairingId","port","fingerprint"],cancel:["phase","pairingId"]};if(!Object.hasOwn(keys,phase)||Object.keys(input).sort().join(",")!==keys[phase].sort().join(","))throw failure();if("port"in input&&!validPort(input.port)||"pairingId"in input&&(typeof input.pairingId!=="string"||!/^[a-f0-9]{32}$/.test(input.pairingId)))throw failure();if("pluginPublicKey"in input&&(typeof input.pluginPublicKey!=="string"||!/^[a-f0-9]{88}$/.test(input.pluginPublicKey)))throw failure();if("fingerprint"in input&&(typeof input.fingerprint!=="string"||!/^[a-f0-9]{64}$/.test(input.fingerprint)))throw failure()}export function validateJoplinSelection(input){validate(input)}export function validateJoplinResult(value){const fail={err:{code:"invalid_setup_result"}};if(!value||typeof value!=="object"||!("ok"in value))return fail;const r=value.ok;if(!r||typeof r!=="object"||r.source!=="joplin"||!["pairing","confirm-required","configured","cancelled","recovery-required","configuration-required","permission-required","unavailable"].includes(String(r.state))||typeof r.reloadRequired!=="boolean")return fail;const state=r.state;const next={pairing:"Exchange public keys with the Zortex Joplin plugin.","confirm-required":"Match the pairing fingerprint with Joplin using the available computer tools, then connect its displayed port.",configured:r.reloadRequired?"Pairing saved. Restart Zortex, then run a read check.":"Pairing saved. Run a read check to verify note access.",cancelled:"Pairing cancelled.","recovery-required":"An interrupted pairing was disabled. Revoke the old pairing in Joplin, then start again.","configuration-required":"Pairing could not be completed. Keep Joplin open and start again.","permission-required":"Joplin permission is required.",unavailable:"Secure Joplin pairing is unavailable in this resident."};const result={source:"joplin",state,reloadRequired:r.reloadRequired,next:next[state]};if(typeof r.enabled==="boolean")result.enabled=r.enabled;if(state==="pairing"||state==="confirm-required"){if(typeof r.pairingId!=="string"||!/^[a-f0-9]{32}$/.test(r.pairingId)||typeof r.expiresAt!=="number"||!Number.isSafeInteger(r.expiresAt))return fail;result.pairingId=r.pairingId;result.expiresAt=r.expiresAt;if(state==="pairing"){if(typeof r.zortexPublicKey!=="string"||!/^[a-f0-9]{88}$/.test(r.zortexPublicKey))return fail;result.zortexPublicKey=r.zortexPublicKey}else{if(typeof r.fingerprint!=="string"||!/^[a-f0-9]{64}$/.test(r.fingerprint))return fail;result.fingerprint=r.fingerprint}}return{ok:result}}
1
+ const failure=()=>Error("Invalid or expired Joplin pairing. Start pairing again in Apps.");const validPort=port=>Number.isInteger(port)&&Number(port)>=1024&&Number(port)<=65535;function validate(input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw failure();for(const key of Reflect.ownKeys(input)){const d=Object.getOwnPropertyDescriptor(input,key);if(typeof key!=="string"||!d.enumerable||!("value"in d))throw failure()}const phase="phase"in input?input.phase:"legacy";const keys={legacy:["port"],start:["phase"],inspect:["phase","pairingId","pluginPublicKey"],confirm:["phase","pairingId","port","fingerprint"],cancel:["phase","pairingId"]};if(!Object.hasOwn(keys,phase)||Object.keys(input).sort().join(",")!==keys[phase].sort().join(","))throw failure();if("port"in input&&!validPort(input.port)||"pairingId"in input&&(typeof input.pairingId!=="string"||!/^[a-f0-9]{32}$/.test(input.pairingId)))throw failure();if("pluginPublicKey"in input&&(typeof input.pluginPublicKey!=="string"||!/^[a-f0-9]{88}$/.test(input.pluginPublicKey)))throw failure();if("fingerprint"in input&&(typeof input.fingerprint!=="string"||!/^[a-f0-9]{64}$/.test(input.fingerprint)))throw failure()}export function validateJoplinSelection(input){validate(input)}export function validateJoplinResult(value){const fail={err:{code:"invalid_setup_result"}};if(!value||typeof value!=="object"||!("ok"in value))return fail;const r=value.ok;if(!r||typeof r!=="object"||r.source!=="joplin"||!["pairing","confirm-required","configured","cancelled","recovery-required","configuration-required","permission-required","unavailable"].includes(String(r.state))||typeof r.reloadRequired!=="boolean")return fail;const state=r.state;const next={pairing:"Exchange public keys with the Zortex Joplin plugin.","confirm-required":"Match the pairing fingerprint with Joplin using the available computer tools, then connect its displayed port.",configured:r.reloadRequired?"Pairing saved. Restart Zortex, then run a read check.":"Pairing saved. Run a read check to verify note access.",cancelled:"Pairing cancelled.","recovery-required":"An interrupted pairing was disabled. Revoke the old pairing in Joplin, then start again.","configuration-required":"Pairing could not be completed. Keep Joplin open and start again.","permission-required":"Joplin permission is required.",unavailable:"Secure Joplin pairing is unavailable in this resident."};const result={source:"joplin",state,reloadRequired:r.reloadRequired,next:next[state]};if(typeof r.enabled==="boolean")result.enabled=r.enabled;if(state==="pairing"||state==="confirm-required"){if(typeof r.pairingId!=="string"||!/^[a-f0-9]{32}$/.test(r.pairingId)||typeof r.expiresAt!=="number"||!Number.isSafeInteger(r.expiresAt))return fail;result.pairingId=r.pairingId;result.expiresAt=r.expiresAt;if(state==="pairing"){if(typeof r.zortexPublicKey!=="string"||!/^[a-f0-9]{88}$/.test(r.zortexPublicKey))return fail;result.zortexPublicKey=r.zortexPublicKey}else{if(typeof r.fingerprint!=="string"||!/^[a-f0-9]{64}$/.test(r.fingerprint))return fail;result.fingerprint=r.fingerprint}}return{ok:result}}
@@ -1 +1 @@
1
- import{spawn}from"node:child_process";import{createHash,randomBytes}from"node:crypto";import{createServer}from"node:http";import{mkdir,open,writeFile}from"node:fs/promises";import{constants}from"node:fs";import{dirname,join}from"node:path";import{WebStandardStreamableHTTPServerTransport}from"@modelcontextprotocol/server";import{AuthError,SCOPES,createDeviceAuthority}from"@zortexhq/plugin-device-auth/api";import{createMcp}from"./mcp.js";import{createRemoteGateway,remoteOperations}from"./local-cloud-policy.js";export const LOCAL_CLOUD_OPERATIONS=["search","read","instruction","handbook"];const MAX_BODY=1048576;const json=(body,status=200,headers={})=>new Response(JSON.stringify(body),{status,headers:{"content-type":"application/json","cache-control":"no-store",...headers}});export async function localCloudPassword(file){try{const handle=await open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{const stat=await handle.stat();if(!stat.isFile()||stat.size>1024||process.platform!=="win32"&&(stat.mode&63)!==0)throw Error("LOCAL_CLOUD_PASSWORD_UNSAFE");const value2=(await handle.readFile("utf8")).trim();if(value2.length<16||value2.length>512)throw Error("LOCAL_CLOUD_PASSWORD_INVALID");return value2}finally{await handle.close()}}catch(error){if(error.code!=="ENOENT")throw error}const value=randomBytes(24).toString("base64url");await mkdir(dirname(file),{recursive:true,mode:448});try{await writeFile(file,value+"\n",{mode:384,flag:"wx"});return value}catch(error){if(error.code==="EEXIST")return localCloudPassword(file);throw error}}export function createLocalCloudMcp(gateway,onCall){return async(request,access)=>{const server=createMcp(access?createRemoteGateway(gateway,access):gateway,{operations:access?remoteOperations(access):LOCAL_CLOUD_OPERATIONS,sqlTimeoutMaxMs:3e3,remote:true,requestSignal:request.signal,...onCall?{onCall}:{}});const transport=new WebStandardStreamableHTTPServerTransport({enableJsonResponse:true});try{await server.connect(transport);const response=await transport.handleRequest(request);const body=response.body?await response.arrayBuffer():null;return new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers})}finally{await server.close()}}}export function quickTunnelStore(root,issuer){const hash=createHash("sha256").update(issuer).digest("hex");return join(root,"host",`local-cloud-authorization-quick-${hash}.sqlite`)}export function createDoor(options){let authority,publicUrl="",generation=0;const audit=event=>{try{options.audit?.(event)}catch{}};const unavailable=()=>json({error:"starting"},503);return{async setPublicUrl(value,storageFile=options.storageFile){if(authority&&value===publicUrl)return;const revision=++generation,previous=authority;authority=void 0;publicUrl="";await previous?.close();if(!value)return;const next=await createDeviceAuthority({issuer:value,ownerPassword:options.password,audit,...storageFile?{storageFile}:{},...options.accountBrowser?{accountBrowser:options.accountBrowser}:{},...options.galaxy?{readResourcePrefixes:["/zortex-galaxy/"]}:{},...options.allowLoopbackHttp?{allowLoopbackHttp:true}:{}});if(revision!==generation){await next.close();return}authority=next;publicUrl=next.issuer},get publicUrl(){return publicUrl},handleNode(req,res){const path=new URL(req.url??"/","http://127.0.0.1").pathname;if(options.galaxy&&path.startsWith("/zortex-galaxy/")||path==="/mcp"||path==="/.well-known/oauth-protected-resource"||path==="/.well-known/oauth-protected-resource/mcp")return false;if(!authority){res.writeHead(503,{"content-type":"application/json","cache-control":"no-store"});res.end('{"error":"starting"}');return true}authority.callback(req,res);return true},async fetch(req){const current=authority;if(!current)return unavailable();const url=new URL(req.url),path=url.pathname;if(path==="/.well-known/oauth-protected-resource"||path==="/.well-known/oauth-protected-resource/mcp"){if(req.method!=="GET"&&req.method!=="HEAD")return json({error:"method_not_allowed"},405,{allow:"GET, HEAD"});return json({resource:current.resource,authorization_servers:[current.issuer],bearer_methods_supported:["header"],scopes_supported:SCOPES})}const galaxy=options.galaxy&&path.startsWith("/zortex-galaxy/")?options.galaxy:void 0;if(path!=="/mcp"&&!galaxy)return json({error:"not_found"},404);const origin=req.headers.get("origin");if(origin!==null&&origin!==current.issuer&&!(galaxy&&origin===options.accountBrowser?.origin))return json({error:"invalid_origin"},403);try{const canonical=new Request(current.issuer+url.pathname+url.search,req);const grant=await current.authenticateRequest(canonical);if(galaxy){if(!current.authorize(grant,"vault.read"))throw new AuthError("insufficient_scope",403);const response=await galaxy.fetch(new Request(canonical,{signal:AbortSignal.any([canonical.signal,grant.signal])}));if(!options.accountBrowser)return response;const headers=new Headers(response.headers);const csp=headers.get("content-security-policy")??"default-src 'self'";headers.set("content-security-policy",csp.replace(/(?:^|;)\s*frame-ancestors[^;]*/g,"")+"; frame-ancestors 'self' "+options.accountBrowser.origin);headers.delete("x-frame-options");return new Response(response.body,{status:response.status,headers})}return await options.mcp(canonical,{grant,authorize:scope=>current.authorize(grant,scope)})}catch(error){if(error instanceof AuthError)return json({error:error.code},error.status,error.headers);audit("mcp.request_failed");return json({error:"server_error"},500)}},listGrants(){return authority?.listGrants()??[]},revokeGrant(id){return authority?.revokeGrant(id)??Promise.resolve(false)},async close(){++generation;const previous=authority;authority=void 0;publicUrl="";await previous?.close()}}}export async function serveLoopback(handler,port=0,handleNode){const server=createServer((req,res)=>{void(async()=>{if(!req.url?.startsWith("/")||req.url.startsWith("//")){res.writeHead(400).end();return}if(handleNode?.(req,res))return;const controller=new AbortController;const disconnected=()=>{if(!res.writableFinished)controller.abort()};req.once("aborted",disconnected);res.once("close",disconnected);try{const chunks=[];let size=0;for await(const chunk of req){size+=chunk.length;if(size>MAX_BODY){res.writeHead(413).end();return}chunks.push(chunk)}const headers=new Headers;for(const[key,value]of Object.entries(req.headers))if(value!==void 0)headers.set(key,Array.isArray(value)?value.join(", "):value);const method=req.method??"GET";const response=await handler(new Request(`http://127.0.0.1${req.url??"/"}`,{method,headers,signal:controller.signal,...method==="GET"||method==="HEAD"?{}:{body:Buffer.concat(chunks)}}));res.writeHead(response.status,Object.fromEntries(response.headers));if(response.body)for await(const part of response.body)res.write(part);res.end()}finally{req.off("aborted",disconnected);res.off("close",disconnected)}})().catch(()=>{if(!res.headersSent)res.writeHead(500);res.end()})});await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(port,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error("LOCAL_CLOUD_LISTENER_UNAVAILABLE");return{port:address.port,close:()=>new Promise(r=>{server.closeAllConnections();server.close(()=>r())})}}export async function waitForTunnelExit(tunnel,signal){if(signal.aborted)return;let onAbort=()=>{};const aborted=new Promise(resolve=>{onAbort=resolve;signal.addEventListener("abort",onAbort,{once:true})});try{await Promise.race([tunnel.exited,aborted])}finally{signal.removeEventListener("abort",onAbort)}}export async function withTunnel(tunnel,run){try{return await run()}finally{tunnel.child.kill();let timer;try{await Promise.race([tunnel.exited,new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error("TUNNEL_CLEANUP_TIMEOUT")),5e3)})])}finally{if(timer)clearTimeout(timer)}}}export function openTunnel(binary,port,timeoutMs=6e4,signal){signal?.throwIfAborted();const child=spawn(binary,["tunnel","--no-autoupdate","--protocol","http2","--url",`http://127.0.0.1:${port}`],{stdio:["ignore","pipe","pipe"],windowsHide:true});const exited=new Promise(r=>child.once("close",code=>r(code)));return new Promise((resolve,reject)=>{let buf="",url="",settled=false;const abort=()=>fail("TUNNEL_ABORTED");const fail=code=>{if(settled)return;settled=true;clearTimeout(timer);signal?.removeEventListener("abort",abort);void withTunnel({url,child,exited},async()=>{throw Error(code)}).catch(reject)};const timer=setTimeout(()=>fail("TUNNEL_TIMEOUT"),timeoutMs);const on=d=>{buf=(buf+String(d)).slice(-8192);url||=buf.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/)?.[0]??"";if(!settled&&url&&/Registered tunnel connection/.test(buf)){settled=true;clearTimeout(timer);signal?.removeEventListener("abort",abort);child.stdout.off("data",on);child.stderr.off("data",on);child.stdout.resume();child.stderr.resume();resolve({url,child,exited})}};child.stdout.on("data",on);child.stderr.on("data",on);child.once("error",()=>fail("TUNNEL_UNAVAILABLE"));signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted)abort();void exited.then(()=>{if(!url||!/Registered tunnel connection/.test(buf))fail("TUNNEL_EXITED")})})}
1
+ import{spawn}from"node:child_process";import{createHash,randomBytes}from"node:crypto";import{createServer}from"node:http";import{mkdir,open,writeFile}from"node:fs/promises";import{constants}from"node:fs";import{dirname,join}from"node:path";import{WebStandardStreamableHTTPServerTransport}from"@modelcontextprotocol/server";import{AuthError,SCOPES,createDeviceAuthority}from"@zortexhq/plugin-device-auth/api";import{createMcp}from"./mcp.js";import{createRemoteGateway,remoteOperations}from"./local-cloud-policy.js";export const LOCAL_CLOUD_OPERATIONS=["search","read","instruction","handbook"];const MAX_BODY=1048576;const json=(body,status=200,headers={})=>new Response(JSON.stringify(body),{status,headers:{"content-type":"application/json","cache-control":"no-store",...headers}});export async function localCloudPassword(file){try{const handle=await open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{const stat=await handle.stat();if(!stat.isFile()||stat.size>1024||process.platform!=="win32"&&(stat.mode&63)!==0)throw Error("LOCAL_CLOUD_PASSWORD_UNSAFE");const value2=(await handle.readFile("utf8")).trim();if(value2.length<16||value2.length>512)throw Error("LOCAL_CLOUD_PASSWORD_INVALID");return value2}finally{await handle.close()}}catch(error){if(error.code!=="ENOENT")throw error}const value=randomBytes(24).toString("base64url");await mkdir(dirname(file),{recursive:true,mode:448});try{await writeFile(file,value+"\n",{mode:384,flag:"wx"});return value}catch(error){if(error.code==="EEXIST")return localCloudPassword(file);throw error}}export function createLocalCloudMcp(gateway,onCall,telemetry){return async(request,access)=>{const server=createMcp(access?createRemoteGateway(gateway,access):gateway,{operations:access?remoteOperations(access):LOCAL_CLOUD_OPERATIONS,sqlTimeoutMaxMs:3e3,remote:true,requestSignal:request.signal,...onCall?{onCall}:{},...telemetry?{telemetry}:{}});const transport=new WebStandardStreamableHTTPServerTransport({enableJsonResponse:true});try{await server.connect(transport);const response=await transport.handleRequest(request);const body=response.body?await response.arrayBuffer():null;return new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers})}finally{await server.close()}}}export function quickTunnelStore(root,issuer){const hash=createHash("sha256").update(issuer).digest("hex");return join(root,"host",`local-cloud-authorization-quick-${hash}.sqlite`)}export function createDoor(options){let authority,publicUrl="",generation=0;const audit=event=>{try{options.audit?.(event)}catch{}};const unavailable=()=>json({error:"starting"},503);return{async setPublicUrl(value,storageFile=options.storageFile){if(authority&&value===publicUrl)return;const revision=++generation,previous=authority;authority=void 0;publicUrl="";await previous?.close();if(!value)return;const next=await createDeviceAuthority({issuer:value,ownerPassword:options.password,audit,...storageFile?{storageFile}:{},...options.accountBrowser?{accountBrowser:options.accountBrowser}:{},...options.galaxy?{readResourcePrefixes:["/zortex-galaxy/"]}:{},...options.allowLoopbackHttp?{allowLoopbackHttp:true}:{}});if(revision!==generation){await next.close();return}authority=next;publicUrl=next.issuer},get publicUrl(){return publicUrl},handleNode(req,res){const path=new URL(req.url??"/","http://127.0.0.1").pathname;if(options.galaxy&&path.startsWith("/zortex-galaxy/")||path==="/mcp"||path==="/.well-known/oauth-protected-resource"||path==="/.well-known/oauth-protected-resource/mcp")return false;if(!authority){res.writeHead(503,{"content-type":"application/json","cache-control":"no-store"});res.end('{"error":"starting"}');return true}authority.callback(req,res);return true},async fetch(req){const current=authority;if(!current)return unavailable();const url=new URL(req.url),path=url.pathname;if(path==="/.well-known/oauth-protected-resource"||path==="/.well-known/oauth-protected-resource/mcp"){if(req.method!=="GET"&&req.method!=="HEAD")return json({error:"method_not_allowed"},405,{allow:"GET, HEAD"});return json({resource:current.resource,authorization_servers:[current.issuer],bearer_methods_supported:["header"],scopes_supported:SCOPES})}const galaxy=options.galaxy&&path.startsWith("/zortex-galaxy/")?options.galaxy:void 0;if(path!=="/mcp"&&!galaxy)return json({error:"not_found"},404);const origin=req.headers.get("origin");if(origin!==null&&origin!==current.issuer&&!(galaxy&&origin===options.accountBrowser?.origin))return json({error:"invalid_origin"},403);try{const canonical=new Request(current.issuer+url.pathname+url.search,req);const grant=await current.authenticateRequest(canonical);if(galaxy){if(!current.authorize(grant,"vault.read"))throw new AuthError("insufficient_scope",403);const response=await galaxy.fetch(new Request(canonical,{signal:AbortSignal.any([canonical.signal,grant.signal])}));if(!options.accountBrowser)return response;const headers=new Headers(response.headers);const csp=headers.get("content-security-policy")??"default-src 'self'";headers.set("content-security-policy",csp.replace(/(?:^|;)\s*frame-ancestors[^;]*/g,"")+"; frame-ancestors 'self' "+options.accountBrowser.origin);headers.delete("x-frame-options");return new Response(response.body,{status:response.status,headers})}return await options.mcp(canonical,{grant,authorize:scope=>current.authorize(grant,scope)})}catch(error){if(error instanceof AuthError)return json({error:error.code},error.status,error.headers);audit("mcp.request_failed");return json({error:"server_error"},500)}},listGrants(){return authority?.listGrants()??[]},revokeGrant(id){return authority?.revokeGrant(id)??Promise.resolve(false)},async close(){++generation;const previous=authority;authority=void 0;publicUrl="";await previous?.close()}}}export async function serveLoopback(handler,port=0,handleNode){const server=createServer((req,res)=>{void(async()=>{if(!req.url?.startsWith("/")||req.url.startsWith("//")){res.writeHead(400).end();return}if(handleNode?.(req,res))return;const controller=new AbortController;const disconnected=()=>{if(!res.writableFinished)controller.abort()};req.once("aborted",disconnected);res.once("close",disconnected);try{const chunks=[];let size=0;for await(const chunk of req){size+=chunk.length;if(size>MAX_BODY){res.writeHead(413).end();return}chunks.push(chunk)}const headers=new Headers;for(const[key,value]of Object.entries(req.headers))if(value!==void 0)headers.set(key,Array.isArray(value)?value.join(", "):value);const method=req.method??"GET";const response=await handler(new Request(`http://127.0.0.1${req.url??"/"}`,{method,headers,signal:controller.signal,...method==="GET"||method==="HEAD"?{}:{body:Buffer.concat(chunks)}}));res.writeHead(response.status,Object.fromEntries(response.headers));if(response.body)for await(const part of response.body)res.write(part);res.end()}finally{req.off("aborted",disconnected);res.off("close",disconnected)}})().catch(()=>{if(!res.headersSent)res.writeHead(500);res.end()})});await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(port,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error("LOCAL_CLOUD_LISTENER_UNAVAILABLE");return{port:address.port,close:()=>new Promise(r=>{server.closeAllConnections();server.close(()=>r())})}}export async function waitForTunnelExit(tunnel,signal){if(signal.aborted)return;let onAbort=()=>{};const aborted=new Promise(resolve=>{onAbort=resolve;signal.addEventListener("abort",onAbort,{once:true})});try{await Promise.race([tunnel.exited,aborted])}finally{signal.removeEventListener("abort",onAbort)}}export async function withTunnel(tunnel,run){try{return await run()}finally{tunnel.child.kill();let timer;try{await Promise.race([tunnel.exited,new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error("TUNNEL_CLEANUP_TIMEOUT")),5e3)})])}finally{if(timer)clearTimeout(timer)}}}export function openTunnel(binary,port,timeoutMs=6e4,signal){signal?.throwIfAborted();const child=spawn(binary,["tunnel","--no-autoupdate","--protocol","http2","--url",`http://127.0.0.1:${port}`],{stdio:["ignore","pipe","pipe"],windowsHide:true});const exited=new Promise(r=>child.once("close",code=>r(code)));return new Promise((resolve,reject)=>{let buf="",url="",settled=false;const abort=()=>fail("TUNNEL_ABORTED");const fail=code=>{if(settled)return;settled=true;clearTimeout(timer);signal?.removeEventListener("abort",abort);void withTunnel({url,child,exited},async()=>{throw Error(code)}).catch(reject)};const timer=setTimeout(()=>fail("TUNNEL_TIMEOUT"),timeoutMs);const on=d=>{buf=(buf+String(d)).slice(-8192);url||=buf.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/)?.[0]??"";if(!settled&&url&&/Registered tunnel connection/.test(buf)){settled=true;clearTimeout(timer);signal?.removeEventListener("abort",abort);child.stdout.off("data",on);child.stderr.off("data",on);child.stdout.resume();child.stderr.resume();resolve({url,child,exited})}};child.stdout.on("data",on);child.stderr.on("data",on);child.once("error",()=>fail("TUNNEL_UNAVAILABLE"));signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted)abort();void exited.then(()=>{if(!url||!/Registered tunnel connection/.test(buf))fail("TUNNEL_EXITED")})})}
@@ -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{validMattermostSelection}from"./mattermost-selection.js";export async function configureMattermostLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Mattermost selection.");if(!validMattermostSelection(input))throw Error("Invalid Mattermost selection.");const source="mattermost",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 Mattermost, then connect using its protected personal 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{validMattermostSelection}from"./mattermost-selection.js";export async function configureMattermostLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Mattermost selection.");if(!validMattermostSelection(input))throw Error("Invalid Mattermost selection.");return configurePreparedLevel1(ctx,"mattermost",()=>({mode:"fields",instanceUrl:input.instanceUrl,username:input.username}),"Restart the resident to register Mattermost, then connect using its protected personal access token form.","The instance URL was saved; the existing disabled or explicit source setting still applies.")}
package/dist/mcp.js CHANGED
@@ -1,3 +1,3 @@
1
- import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";import{businessError}from"@zortexhq/plugin-connector-framework/api";import{withUsageInvocation,currentUsageInvocation,USAGE_TOOL_NAMES,usageOutcome,usageResultSummary,usageErrorCategory}from"@zortexhq/plugin-telemetry/api";import{toolSpecs}from"./tools.js";import{randomUUID}from"node:crypto";import{productUpdater}from"./auto-update.js";import{callUpdateTool,updateTool}from"./update-tool.js";const invocationTool=operation=>operation&&USAGE_TOOL_NAMES.includes(operation)?operation:"unknown";function boundedSqlError(args,maxMs){if(!args||typeof args!=="object"||Array.isArray(args))return"Pass a SQL argument object.";const request=args;if(Object.keys(request).some(key=>!["sql","params","timeoutMs"].includes(key)))return"Only sql, params and timeoutMs are accepted.";if(typeof request.sql!=="string"||!request.sql.trim()||Buffer.byteLength(request.sql)>65536)return"sql must be a nonempty string of at most 65536 bytes.";if("params"in request&&(!Array.isArray(request.params)||request.params.length>100||request.params.some(value=>value!==null&&typeof value!=="boolean"&&(typeof value!=="number"||!Number.isFinite(value))&&(typeof value!=="string"||Buffer.byteLength(value)>16384))))return"params must be an array of at most 100 bounded scalar values; omit params when unused.";if("timeoutMs"in request&&(!Number.isSafeInteger(request.timeoutMs)||Number(request.timeoutMs)<50||Number(request.timeoutMs)>maxMs))return`timeoutMs must be an integer from 50 to ${maxMs}; omit timeoutMs to use the default.`}const surfacedVersions=new Set;const formatBytes=bytes=>bytes<1024?`${bytes} B`:bytes<1048576?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/1048576).toFixed(1)} MB`;export function createMcp(gateway,options={}){const localUpdates=!options.remote&&!options.operations;const updater=options.updater??productUpdater;if(localUpdates&&process.env.ZORTEX_FEEDBACK_TRAFFIC_CLASS!=="internal_test")void updater.check().catch(()=>{});const specs=options.operations?toolSpecs.filter(spec=>options.operations.includes(spec.operation)):toolSpecs.filter(spec=>spec.operation!=="read");const server=new Server({name:"indra-v2",version:"0.1.0-dev.3"},{capabilities:{tools:{}}});const tools=specs.map(spec=>{let properties=Object.fromEntries(Object.entries(spec.parameters).map(([key,value])=>[key,{type:"type"in value?value.type==="json"?"object":value.type:"object"}]));const bounded=spec.operation==="search"&&options.sqlTimeoutMaxMs;if(bounded){properties.sql={type:"string",minLength:1,maxLength:65536};properties.params={type:"array",maxItems:100,items:{type:["string","number","boolean","null"]},description:"Omit when SQL has no placeholders; do not send null."};properties.timeoutMs={type:"integer",minimum:50,maximum:bounded,description:`Omit to use the server default of ${bounded} ms.`}}const remoteDescription=options.remote&&spec.operation==="action"?"Invoke a discovered product action using name and params, including browser, computer control and connector setup. Product use supplies authorization; continue through available tools.":spec.description;return{name:"indra."+spec.operation,description:bounded?`${remoteDescription} Omit timeoutMs to use the ${bounded} ms default; omit params when unused.`:remoteDescription,inputSchema:{type:"object",properties,required:Object.entries(spec.parameters).filter(([,value])=>value.required).map(([key])=>key),additionalProperties:false},...options.operations?{annotations:{readOnlyHint:spec.operation!=="action",destructiveHint:spec.operation==="action",openWorldHint:["action","actions","read"].includes(spec.operation)}}:{}}});if(localUpdates)tools.push(updateTool);server.setRequestHandler("tools/list",()=>({tools}));server.setRequestHandler("tools/call",async(request,context)=>{const name=request.params.name,spec=specs.find(spec2=>"indra."+spec2.operation===name);const args=request.params.arguments??{};const tool=invocationTool(spec?.operation??(localUpdates&&name===updateTool.name?"update":void 0));return withUsageInvocation({entrypoint:options.remote?"local_cloud":"mcp",tool,owner:options.remote||options.telemetry?"transport":"gateway"},async()=>{const started=performance.now();let result;const signal=options.requestSignal?AbortSignal.any([context.mcpReq.signal,options.requestSignal]):context.mcpReq.signal;try{const sqlError=spec?.operation==="search"&&options.sqlTimeoutMaxMs?boundedSqlError(args,options.sqlTimeoutMaxMs):void 0;result=localUpdates&&name===updateTool.name?await callUpdateTool(args,updater):sqlError?businessError("invalid_argument",sqlError,"plugin"):spec?await gateway.call(spec.operation,args,{signal}):{err:{code:"not_found",layer:"plugin",message:"Unknown indra tool."}};if(localUpdates&&options.onUpdateObservation){await options.onUpdateObservation(!!spec&&!!result&&typeof result==="object"&&"ok"in result).catch(()=>{})}let updateNotice;if(localUpdates&&spec&&!(result&&typeof result==="object"&&"err"in result)){try{const offer=await updater.status();if(offer?.state==="available"&&typeof offer.targetVersion==="string"&&!surfacedVersions.has(offer.targetVersion)){surfacedVersions.add(offer.targetVersion);const estimate=typeof offer.expectedDownloadBytes==="number"&&typeof offer.expectedChangedFiles==="number"?`; about ${formatBytes(offer.expectedDownloadBytes)} across ${offer.expectedChangedFiles} changed files`:"";updateNotice=`
1
+ import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";import{businessError}from"@zortexhq/plugin-connector-framework/api";import{withUsageInvocation,currentUsageInvocation,currentOperationalExecution,USAGE_TOOL_NAMES,usageOutcome,usageResultSummary,usageErrorCategory}from"@zortexhq/plugin-telemetry/api";import{toolSpecs}from"./tools.js";import{randomUUID}from"node:crypto";import{productUpdater}from"./auto-update.js";import{callUpdateTool,updateTool}from"./update-tool.js";import{traceProductOperation}from"./operation-telemetry.js";const invocationTool=operation=>operation&&USAGE_TOOL_NAMES.includes(operation)?operation:"unknown";async function observeBounded(run){let timer;try{return await Promise.race([Promise.resolve().then(run),new Promise(resolve=>{timer=setTimeout(()=>resolve(void 0),50)})])}finally{if(timer)clearTimeout(timer)}}function boundedSqlError(args,maxMs){if(!args||typeof args!=="object"||Array.isArray(args))return"Pass a SQL argument object.";const request=args;if(Object.keys(request).some(key=>!["sql","params","timeoutMs"].includes(key)))return"Only sql, params and timeoutMs are accepted.";if(typeof request.sql!=="string"||!request.sql.trim()||Buffer.byteLength(request.sql)>65536)return"sql must be a nonempty string of at most 65536 bytes.";if("params"in request&&(!Array.isArray(request.params)||request.params.length>100||request.params.some(value=>value!==null&&typeof value!=="boolean"&&(typeof value!=="number"||!Number.isFinite(value))&&(typeof value!=="string"||Buffer.byteLength(value)>16384))))return"params must be an array of at most 100 bounded scalar values; omit params when unused.";if("timeoutMs"in request&&(!Number.isSafeInteger(request.timeoutMs)||Number(request.timeoutMs)<50||Number(request.timeoutMs)>maxMs))return`timeoutMs must be an integer from 50 to ${maxMs}; omit timeoutMs to use the default.`}const surfacedVersions=new Set;const formatBytes=bytes=>bytes<1024?`${bytes} B`:bytes<1048576?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/1048576).toFixed(1)} MB`;export function createMcp(gateway,options={}){const connectionSessionId=randomUUID();const localUpdates=!options.remote&&!options.operations;const updater=options.updater??productUpdater;if(localUpdates&&process.env.ZORTEX_FEEDBACK_TRAFFIC_CLASS!=="internal_test")void updater.check().catch(()=>{});const specs=options.operations?toolSpecs.filter(spec=>options.operations.includes(spec.operation)):toolSpecs.filter(spec=>spec.operation!=="read");const server=new Server({name:"indra-v2",version:"0.1.0-dev.3"},{capabilities:{tools:{}}});const tools=specs.map(spec=>{let properties=Object.fromEntries(Object.entries(spec.parameters).map(([key,value])=>[key,{type:"type"in value?value.type==="json"?"object":value.type:"object"}]));const bounded=spec.operation==="search"&&options.sqlTimeoutMaxMs;if(bounded){properties.sql={type:"string",minLength:1,maxLength:65536};properties.params={type:"array",maxItems:100,items:{type:["string","number","boolean","null"]},description:"Omit when SQL has no placeholders; do not send null."};properties.timeoutMs={type:"integer",minimum:50,maximum:bounded,description:`Omit to use the server default of ${bounded} ms.`}}const remoteDescription=options.remote&&spec.operation==="action"?"Invoke a discovered product action using name and params, including browser, computer control and connector setup. Product use supplies authorization; continue through available tools.":spec.description;return{name:"indra."+spec.operation,description:bounded?`${remoteDescription} Omit timeoutMs to use the ${bounded} ms default; omit params when unused.`:remoteDescription,inputSchema:{type:"object",properties,required:Object.entries(spec.parameters).filter(([,value])=>value.required).map(([key])=>key),additionalProperties:false},...options.operations?{annotations:{readOnlyHint:spec.operation!=="action",destructiveHint:spec.operation==="action",openWorldHint:["action","actions","read"].includes(spec.operation)}}:{}}});if(localUpdates)tools.push(updateTool);server.setRequestHandler("tools/list",()=>({tools}));server.setRequestHandler("tools/call",async(request,context)=>{const name=request.params.name,spec=specs.find(spec2=>"indra."+spec2.operation===name);const args=request.params.arguments??{};const tool=invocationTool(spec?.operation??(localUpdates&&name===updateTool.name?"update":void 0));return withUsageInvocation({entrypoint:options.remote?"local_cloud":"mcp",tool,owner:options.remote||options.telemetry?"transport":"gateway",sessionId:options.remote?randomUUID():connectionSessionId,sessionScope:options.remote?"mcp_request":"mcp_connection"},()=>{const signal=options.requestSignal?AbortSignal.any([context.mcpReq.signal,options.requestSignal]):context.mcpReq.signal;return traceProductOperation(options.telemetry,tool,args,async()=>{const started=performance.now();let result;try{const sqlError=spec?.operation==="search"&&options.sqlTimeoutMaxMs?boundedSqlError(args,options.sqlTimeoutMaxMs):void 0;result=localUpdates&&name===updateTool.name?await callUpdateTool(args,updater):sqlError?businessError("invalid_argument",sqlError,"plugin"):spec?await gateway.call(spec.operation,args,{signal}):{err:{code:"not_found",layer:"plugin",message:"Unknown indra tool."}};if(localUpdates&&options.onUpdateObservation){await observeBounded(()=>options.onUpdateObservation(!!spec&&!!result&&typeof result==="object"&&"ok"in result)).catch(()=>{})}let updateNotice;if(localUpdates&&spec&&!(result&&typeof result==="object"&&"err"in result)){try{const offer=await updater.status();if(offer?.state==="available"&&typeof offer.targetVersion==="string"&&!surfacedVersions.has(offer.targetVersion)){surfacedVersions.add(offer.targetVersion);const estimate=typeof offer.expectedDownloadBytes==="number"&&typeof offer.expectedChangedFiles==="number"?`; about ${formatBytes(offer.expectedDownloadBytes)} across ${offer.expectedChangedFiles} changed files`:"";updateNotice=`
2
2
 
3
- [Zortex update] Version ${offer.targetVersion} is available (installed ${offer.currentVersion}${estimate}). Use the indra.update tool: operation check to review the offer, then operation apply with its version and confirmationToken. Only changed files are downloaded; the new version takes effect after the host and MCP session restart.`}}catch{}}return{content:[{type:"text",text:JSON.stringify(result)+(updateNotice??"")}],structuredContent:result,isError:!!result&&typeof result==="object"&&"err"in result}}finally{try{const reply=result&&typeof result==="object"&&("ok"in result||"err"in result||"empty"in result)?result:businessError(signal.aborted?"aborted":"unavailable","Operation did not return.","plugin");const outcome=usageOutcome(reply),durationMs=Math.min(864e5,Math.max(0,Math.round(performance.now()-started)));if(!options.remote&&options.telemetry)try{const resultSummary=usageResultSummary(reply),errorCategory=usageErrorCategory(reply);const operation=["search","context","sql","actions","action","manage","instruction","handbook"].includes(tool)?tool:"mcp.call";const saved=await options.telemetry()?.record({operation,outcome,durationMs,...resultSummary?{result:resultSummary}:{},...errorCategory?{errorCategory}:{},...tool==="action"&&args.name==="connector.invoke"?{code:"effective_invoke"}:{}});if(saved&&"err"in saved)process.stderr.write("indra feedback: local observation was not recorded.\n")}catch{process.stderr.write("indra feedback: local observation failed.\n")}if(options.onCall)try{await options.onCall({id:currentUsageInvocation()?.id??randomUUID(),at:new Date().toISOString(),operation:tool,outcome,success:!!result&&typeof result==="object"&&"ok"in result,durationMs,paramsState:!("params"in args)?"omitted":Array.isArray(args.params)?"array":args.params===null?"null":"invalid",timeoutState:!("timeoutMs"in args)?"omitted":Number.isSafeInteger(args.timeoutMs)&&Number(args.timeoutMs)>=50&&Number(args.timeoutMs)<=(options.sqlTimeoutMaxMs??3e3)?"valid":"invalid"})}catch{process.stderr.write("local cloud: CALL_OBSERVATION_FAILED\n")}}catch{process.stderr.write("indra feedback: terminal observation failed.\n")}}})});return server}export function startMcp(gateway,options={}){return serveStdio(()=>createMcp(gateway,options),{onerror:()=>process.stderr.write("indra MCP request failed.\n")})}
3
+ [Zortex update] Version ${offer.targetVersion} is available (installed ${offer.currentVersion}${estimate}). Use the indra.update tool: operation check to review the offer, then operation apply with its version and confirmationToken. Only changed files are downloaded; the new version takes effect after the host and MCP session restart.`}}catch{}}return{content:[{type:"text",text:JSON.stringify(result)+(updateNotice??"")}],structuredContent:result,isError:!!result&&typeof result==="object"&&"err"in result}}finally{try{const reply=result&&typeof result==="object"&&("ok"in result||"err"in result||"empty"in result)?result:businessError(signal.aborted?"aborted":"unavailable","Operation did not return.","plugin");const outcome=usageOutcome(reply),durationMs=Math.min(864e5,Math.max(0,Math.round(performance.now()-started)));if(!options.remote&&options.telemetry)try{const resultSummary=usageResultSummary(reply),errorCategory=usageErrorCategory(reply);const operation=["search","context","sql","actions","action","manage","instruction","handbook"].includes(tool)?tool:"mcp.call";const saved=await observeBounded(()=>options.telemetry?.()?.record({operation,outcome,durationMs,...resultSummary?{result:resultSummary}:{},...errorCategory?{errorCategory}:{},...tool==="action"&&args.name==="connector.invoke"?{code:"effective_invoke"}:{}}));if(saved&&"err"in saved)process.stderr.write("indra feedback: local observation was not recorded.\n")}catch{process.stderr.write("indra feedback: local observation failed.\n")}if(options.onCall)try{const execution=currentOperationalExecution();await observeBounded(()=>options.onCall({id:currentUsageInvocation()?.id??randomUUID(),at:new Date().toISOString(),operation:tool,outcome,success:!!result&&typeof result==="object"&&"ok"in result,...execution?{execution}:{},durationMs,paramsState:!("params"in args)?"omitted":Array.isArray(args.params)?"array":args.params===null?"null":"invalid",timeoutState:!("timeoutMs"in args)?"omitted":Number.isSafeInteger(args.timeoutMs)&&Number(args.timeoutMs)>=50&&Number(args.timeoutMs)<=(options.sqlTimeoutMaxMs??3e3)?"valid":"invalid"}))}catch{process.stderr.write("local cloud: CALL_OBSERVATION_FAILED\n")}}catch{process.stderr.write("indra feedback: terminal observation failed.\n")}}},signal)})});return server}export function startMcp(gateway,options={}){return serveStdio(()=>createMcp(gateway,options),{onerror:()=>process.stderr.write("indra MCP request failed.\n")})}
@@ -1 +1 @@
1
- import{runningProductVersion}from"./update-telemetry.js";export async function productMeasurementContext(){const productVersion=await runningProductVersion;const platform=process.platform==="darwin"||process.platform==="win32"||process.platform==="linux"?process.platform:"unknown";const mode=process.env.ZORTEX_EXECUTION_MODE;return{...productVersion&&productVersion.length<=64&&/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/.test(productVersion)?{productVersion}:{},platform,executionLocation:mode==="local"||mode==="cloud"?mode:"unknown"}}
1
+ import{runningProductVersion}from"./update-telemetry.js";export async function productMeasurementContext(){const productVersion=await runningProductVersion;const platform=process.platform==="darwin"||process.platform==="win32"||process.platform==="linux"?process.platform:"unknown";const mode=process.env.ZORTEX_EXECUTION_MODE;const traffic=process.env.ZORTEX_FEEDBACK_TRAFFIC_CLASS;return{...productVersion&&productVersion.length<=64&&/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/.test(productVersion)?{productVersion}:{},platform,executionLocation:mode==="local"||mode==="cloud"?mode:"unknown",trafficClass:traffic==="internal_test"||traffic==="simulation"?traffic:"usage"}}
@@ -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{validMinifluxSelection}from"./miniflux-selection.js";export async function configureMinifluxLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Miniflux selection.");if(!validMinifluxSelection(input))throw Error("Invalid Miniflux selection.");const source="miniflux",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 Miniflux, 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{validMinifluxSelection}from"./miniflux-selection.js";export async function configureMinifluxLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Miniflux selection.");if(!validMinifluxSelection(input))throw Error("Invalid Miniflux selection.");return configurePreparedLevel1(ctx,"miniflux",()=>({mode:"fields",instanceUrl:input.instanceUrl,username:input.username}),"Restart the resident to register Miniflux, then connect using its protected API key form.","The instance URL 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{validNextcloudInstanceUrl}from"./nextcloud-url.js";export async function configureNextcloudLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Nextcloud selection.");const keys=Reflect.ownKeys(input),descriptor=Object.getOwnPropertyDescriptor(input,"instanceUrl");if(keys.length!==1||keys[0]!=="instanceUrl"||!descriptor?.enumerable||!("value"in descriptor)||typeof descriptor.value!=="string"||!validNextcloudInstanceUrl(descriptor.value))throw Error("Invalid Nextcloud selection.");const source="nextcloud",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: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 Nextcloud, then connect using its protected credential 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{validNextcloudInstanceUrl}from"./nextcloud-url.js";export async function configureNextcloudLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid Nextcloud selection.");const keys=Reflect.ownKeys(input),descriptor=Object.getOwnPropertyDescriptor(input,"instanceUrl");if(keys.length!==1||keys[0]!=="instanceUrl"||!descriptor?.enumerable||!("value"in descriptor)||typeof descriptor.value!=="string"||!validNextcloudInstanceUrl(descriptor.value))throw Error("Invalid Nextcloud selection.");return configurePreparedLevel1(ctx,"nextcloud",()=>({mode:"fields",instanceUrl:descriptor.value}),"Restart the resident to register Nextcloud, then connect using its protected credential form.","The instance URL was saved; the existing disabled or explicit source setting still applies.")}
@@ -0,0 +1 @@
1
+ import{runOperationalToolCall}from"@zortexhq/plugin-telemetry/api";const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);export async function traceProductOperation(metrics,operation,args,run,signal){return runOperationalToolCall(metrics,()=>{const actionName=operation==="action"&&object(args)&&typeof args.name==="string"?args.name:void 0;const params=object(args)&&object(args.params)?args.params:void 0;const source=typeof params?.source==="string"?params.source:object(args)&&typeof args.source==="string"?args.source:actionName?.startsWith("browser.")?"browser-use":void 0;return{tool:operation,method:actionName,source}},run,signal?{signal}:{})}
@@ -0,0 +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 configurePreparedLevel1(ctx,source,prepare,next,disabledNext="The selection was saved; the existing disabled or explicit source setting still applies."){const 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])];const requested=[...new Set([...saved.requestedSources??saved.sources??[],...selected])];return{configuration:{...saved,sources:selected,requestedSources:requested,prepared:{...saved.prepared,[source]:prepare(saved.prepared?.[source]??{})}},value:void 0}});const enabled=!entry.disabled&&(config.sources===void 0||config.sources.includes(source));return{source,state:"configured",enabled,reloadRequired:true,next:enabled?next:disabledNext}}catch{return{...base,state:"configuration-required",next:"Check the Level1 settings; no unrelated source was enabled."}}}
package/dist/profile.js CHANGED
@@ -1 +1 @@
1
- import{Context}from"@deepseek-ai/cordis";import Loader from"@deepseek-ai/cordis-plugin-loader";import{mkdir,readFile,realpath}from"node:fs/promises";import{dirname,join,resolve,sep}from"node:path";import{fileURLToPath,pathToFileURL}from"node:url";import{parseDocument,isSeq,isMap}from"yaml";import{setTimeout as delay}from"node:timers/promises";import{createTraceRecorder,withStartupFeedbackFlow,withTelemetryContext}from"@zortexhq/plugin-telemetry/api";import{productMeasurementContext}from"./measurement-context.js";import{isFreshProductDirectory}from"./installation-origin.js";import{ensureProductProfile}from"./profile-upgrade.js";import{ProductProfileInclude}from"./profile-include.js";export async function openProfile(profile){return withTelemetryContext(await productMeasurementContext(),async()=>{const ctx=new Context;const product=await realpath(dirname(fileURLToPath(new URL("../package.json",import.meta.url))));ctx.baseUrl=pathToFileURL(product+sep).href;try{await ctx.registry.plugin(Loader);ctx.loader.builtins["indra-profile-include"]=ProductProfileInclude;await ctx.loader.create({name:"cordis:indra-profile-include",config:{path:pathToFileURL(resolve(profile)).href}});await ctx.loader.await();for(const row of ctx.loader.entries()){if(row.disabled||row.options.group)continue;await row.fiber?.await();if(!row.fiber||row.fiber.state!==2)throw Error("Plugin failed to activate: "+row.options.name)}return{context:ctx,close:()=>ctx.fiber.dispose()}}catch(error){try{if(ctx.get("zortexTelemetry"))await withStartupFeedbackFlow("other",()=>createTraceRecorder(()=>ctx.get("zortexTelemetry"),"other").step("startup_failed","failed"));const sent=await ctx.get("zortexPostHog")?.flush({wait:true});if(sent&&"err"in sent)process.stderr.write("indra feedback: delivery pending; retained for the next run.\n")}catch{process.stderr.write("indra feedback: startup failure observation could not be delivered.\n")}try{await ctx.fiber.dispose()}catch{process.stderr.write("indra: startup cleanup failed.\n")}throw error}})}export async function openProduct(root,installationOptions={}){const fresh=installationOptions.newInstallation??await isFreshProductDirectory(root);process.env.ZORTEX_ENGINE_ROOT=root;process.env.ZORTEX_TELEMETRY_NEW_INSTALL_ROOT=fresh?resolve(root,"metrics"):"";await mkdir(root,{recursive:true});const profile=join(root,"indra-profile.yml");const base=fileURLToPath(new URL("../profiles/",import.meta.url));const options={customTags:[{tag:"tag:yaml.org,2002:js",resolve:value=>value}]};const core=parseDocument(await readFile(join(base,"core.yml"),"utf8"),options);const vault=parseDocument(await readFile(join(base,"vault.yml"),"utf8"),options);if(!isSeq(core.contents)||!isSeq(vault.contents)||core.errors.length||vault.errors.length)throw Error("Invalid installed profile.");const vaultRows=vault.contents.items;core.contents.items=core.contents.items.flatMap(row=>isMap(row)&&row.toJSON().id==="indra-core-vault"?vaultRows:[row]);for(const row of core.contents.items){if(!isMap(row))throw Error("Invalid installed plugin row.");const specifier=String(row.toJSON().name);const mutable=row;mutable.set("publicModule",specifier);mutable.set("name",pathToFileURL(await realpath(fileURLToPath(import.meta.resolve(specifier)))).href)}await ensureProductProfile(profile,String(core));for(let attempt=0;;attempt++){try{return await openProfile(profile)}catch(error){const sqlite=error;if(attempt>=2||sqlite?.code!=="ERR_SQLITE_ERROR"||sqlite.errcode!==5)throw error;await delay(100*(attempt+1))}}}
1
+ import{Context}from"@deepseek-ai/cordis";import Loader from"@deepseek-ai/cordis-plugin-loader";import{mkdir,readFile,realpath}from"node:fs/promises";import{dirname,join,resolve,sep}from"node:path";import{fileURLToPath,pathToFileURL}from"node:url";import{parseDocument,isSeq,isMap}from"yaml";import{setTimeout as delay}from"node:timers/promises";import{createTraceRecorder,withStartupFeedbackFlow,withTelemetryContext}from"@zortexhq/plugin-telemetry/api";import{productMeasurementContext}from"./measurement-context.js";import{isFreshProductDirectory}from"./installation-origin.js";import{ensureProductProfile}from"./profile-upgrade.js";import{ProductProfileInclude}from"./profile-include.js";import{attachResourceTelemetry}from"./resource-telemetry.js";export async function openProfile(profile,processRole="unknown"){return withTelemetryContext(await productMeasurementContext(),async()=>{const ctx=new Context;const product=await realpath(dirname(fileURLToPath(new URL("../package.json",import.meta.url))));ctx.baseUrl=pathToFileURL(product+sep).href;try{await ctx.registry.plugin(Loader);ctx.loader.builtins["indra-profile-include"]=ProductProfileInclude;await ctx.loader.create({name:"cordis:indra-profile-include",config:{path:pathToFileURL(resolve(profile)).href}});await ctx.loader.await();for(const row of ctx.loader.entries()){if(row.disabled||row.options.group)continue;await row.fiber?.await();if(!row.fiber||row.fiber.state!==2)throw Error("Plugin failed to activate: "+row.options.name)}const stopResources=attachResourceTelemetry(ctx,processRole);ctx.effect(()=>stopResources);return{context:ctx,close:()=>{stopResources();return ctx.fiber.dispose()}}}catch(error){try{if(ctx.get("zortexTelemetry"))await withStartupFeedbackFlow("other",()=>createTraceRecorder(()=>ctx.get("zortexTelemetry"),"other").step("startup_failed","failed"));const sent=await ctx.get("zortexPostHog")?.flush({wait:true});if(sent&&"err"in sent)process.stderr.write("indra feedback: delivery pending; retained for the next run.\n")}catch{process.stderr.write("indra feedback: startup failure observation could not be delivered.\n")}try{await ctx.fiber.dispose()}catch{process.stderr.write("indra: startup cleanup failed.\n")}throw error}})}export async function openProduct(root,installationOptions={}){const fresh=installationOptions.newInstallation??await isFreshProductDirectory(root);process.env.ZORTEX_ENGINE_ROOT=root;process.env.ZORTEX_TELEMETRY_NEW_INSTALL_ROOT=fresh?resolve(root,"metrics"):"";await mkdir(root,{recursive:true});const profile=join(root,"indra-profile.yml");const base=fileURLToPath(new URL("../profiles/",import.meta.url));const options={customTags:[{tag:"tag:yaml.org,2002:js",resolve:value=>value}]};const core=parseDocument(await readFile(join(base,"core.yml"),"utf8"),options);const vault=parseDocument(await readFile(join(base,"vault.yml"),"utf8"),options);if(!isSeq(core.contents)||!isSeq(vault.contents)||core.errors.length||vault.errors.length)throw Error("Invalid installed profile.");const vaultRows=vault.contents.items;core.contents.items=core.contents.items.flatMap(row=>isMap(row)&&row.toJSON().id==="indra-core-vault"?vaultRows:[row]);for(const row of core.contents.items){if(!isMap(row))throw Error("Invalid installed plugin row.");const specifier=String(row.toJSON().name);const mutable=row;mutable.set("publicModule",specifier);mutable.set("name",pathToFileURL(await realpath(fileURLToPath(import.meta.resolve(specifier)))).href)}await ensureProductProfile(profile,String(core));for(let attempt=0;;attempt++){try{return await openProfile(profile,installationOptions.processRole??"cli")}catch(error){const sqlite=error;if(attempt>=2||sqlite?.code!=="ERR_SQLITE_ERROR"||sqlite.errcode!==5)throw error;await delay(100*(attempt+1))}}}
@@ -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 configureProtonMailLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid ProtonMail 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 ProtonMail selection.");const source="proton-mail",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",imapPort: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 Proton Mail, then enter Bridge credentials in the protected local 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 configureProtonMailLevel1(ctx,input){if(!input||typeof input!=="object"||Array.isArray(input)||![Object.prototype,null].includes(Object.getPrototypeOf(input)))throw Error("Invalid ProtonMail 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 ProtonMail selection.");return configurePreparedLevel1(ctx,"proton-mail",()=>({mode:"fields",imapPort:descriptor.value}),"Restart the resident to register Proton Mail, then enter Bridge credentials in the protected local form.","The port was saved; the existing disabled or explicit source setting still applies.")}
@@ -0,0 +1,10 @@
1
+ export function recoveryLaunch(nonce){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Opening your apps</title></head><body><p id="status" role="status">Opening your apps\u2026</p><script nonce="${nonce}">
2
+ const token=location.hash.slice(1);
3
+ history.replaceState(null,'',location.pathname);
4
+ fetch('/open',{method:'POST',headers:{'Content-Type':'application/json','X-Zortex-Recovery':token},body:'{}',redirect:'error'}).then(async response=>{
5
+ if(!response.ok)throw Error();
6
+ const result=await response.json(),url=new URL(result.url);
7
+ if(url.protocol!=='http:'||url.hostname!=='127.0.0.1'||url.username||url.password)throw Error();
8
+ location.replace(url.href);
9
+ }).catch(()=>{document.getElementById('status').textContent='This connection link is unavailable. Open Zortex and choose Apps, or run zortex help again.';});
10
+ <\/script></body></html>`}
@@ -1 +1 @@
1
- const setups={joplin:["configureJoplin","joplinSetupAvailable"],"visual-studio":["configureNativeFiles","setupAvailable"],modelsim:["configureNativeFiles","setupAvailable"],quartus:["configureNativeFiles","setupAvailable"],simulink:["configureNativeFiles","setupAvailable"],jianying:["configureNativeFiles","setupAvailable"],"epic-games-launcher":["configureNativeFiles","setupAvailable"],"ryujinx":["configureNativeFiles","setupAvailable"],"modrinth":["configureNativeFiles","setupAvailable"],"powerpoint":["configureNativeFiles","setupAvailable"],"ti-ccs":["configureNativeFiles","setupAvailable"],"pscad":["configureNativeFiles","setupAvailable"],"adobe-photoshop":["configureNativeFiles","setupAvailable"],autocad:["configureNativeFiles","setupAvailable"],"microsoft-word":["configureNativeFiles","setupAvailable"],"microsoft-excel":["configureNativeFiles","setupAvailable"],"local-git":["configureNativeFiles","setupAvailable"],"vscode-local-history":["configureNativeFiles","setupAvailable"],"libreoffice":["configureNativeFiles","setupAvailable"],"adobe-acrobat":["configureNativeFiles","setupAvailable"],"adobe-camera-raw":["configureNativeFiles","setupAvailable"],"adobe-media-encoder":["configureNativeFiles","setupAvailable"],"ansys-electronics-desktop":["configureNativeFiles","setupAvailable"],"adobe-premiere-pro":["configureNativeFiles","setupAvailable"],"packet-tracer":["configureNativeFiles","setupAvailable"],"qt-designer":["configureNativeFiles","setupAvailable"],"hearthstone-deck-tracker":["configureNativeFiles","setupAvailable"],visio:["configureNativeFiles","setupAvailable"],matlab:["configureNativeFiles","setupAvailable"],"adobe-illustrator":["configureNativeFiles","setupAvailable"],"minecraft-java":["configureNativeFiles","setupAvailable"],"ni-tdms":["configureNativeFiles","setupAvailable"],jupyter:["configureNativeFiles","setupAvailable"],solidworks:["configureNativeFiles","setupAvailable"],lattics:["configureNativeFiles","setupAvailable"],jetbrains:["configureNativeFiles","setupAvailable"],eclipse:["configureNativeFiles","setupAvailable"],multisim:["configureNativeFiles","setupAvailable"],stm32cubemx:["configureNativeFiles","setupAvailable"],plecs:["configureNativeFiles","setupAvailable"],"local-audio":["configureNativeFiles","setupAvailable"],obsidian:["configureNativeFiles","setupAvailable"],logseq:["configureNativeFiles","setupAvailable"],"computer-files":["configureNativeFiles","setupAvailable"],zotero:["configureZotero","zoteroSetupAvailable"],owntracks:["configureOwnTracks","owntracksSetupAvailable"],wechat:["configureWeChat","wechatSetupAvailable"],thunderbird:["configureThunderbird","thunderbirdSetupAvailable"],"proton-mail":["configureProtonMail","protonMailSetupAvailable"],discord:["configureDiscord","discordSetupAvailable"],dropbox:["configureDropbox","dropboxSetupAvailable"],box:["configureBox","boxSetupAvailable"],front:["configureFront","frontSetupAvailable"],hubspot:["configureHubSpot","hubspotSetupAvailable"],"google-contacts":["configureGoogleContacts","googleContactsSetupAvailable"],"google-chat":["configureGoogleChat","googleChatSetupAvailable"],salesforce:["configureSalesforce","salesforceSetupAvailable"],zendesk:["configureZendesk","zendeskSetupAvailable"],zoom:["configureZoom","zoomSetupAvailable"],copyq:["configureCopyQ","copyqSetupAvailable"],freshdesk:["configureFreshdesk","freshdeskSetupAvailable"],figma:["configureFigma","figmaSetupAvailable"],smartsheet:["configureSmartsheet","smartsheetSetupAvailable"],nextcloud:["configureNextcloud","nextcloudSetupAvailable"],zulip:["configureZulip","zulipSetupAvailable"],freshrss:["configureFreshRSS","freshrssSetupAvailable"],miniflux:["configureMiniflux","minifluxSetupAvailable"],mattermost:["configureMattermost","mattermostSetupAvailable"],wallabag:["configureWallabag","wallabagSetupAvailable"],calcom:["configureCalcom","calcomSetupAvailable"],wakatime:["configureWakatime","wakatimeSetupAvailable"]};export function recoverySetupFlags(source,authorization){const setup=setups[source];return setup&&authorization&&typeof Reflect.get(authorization,setup[0])==="function"?{[setup[1]]:true}:{}}export function sourceSupport(row,hasSetup,platform=process.platform){const{source}=row;const result=(state,reasonCode,message,nextStep)=>({source,state,reasonCode,message,nextStep});if(source==="joplin"&&row.connection==="connected"&&row.registration!=="deferred"&&!row.reloadRequired)return result("supported","existing_authorization_read_only","Joplin is paired. Check note access with a read Action.","Choose Read again to verify note access; use pairing to replace the connection.");if(source==="joplin"&&hasSetup)return result("setup-required","paired_plugin_required","Joplin uses encrypted pairing with its local Zortex plugin.","Install the Zortex Joplin plugin, then compare the fingerprints in both applications. No Web Clipper token is needed.");if(source==="joplin")return result("unsupported","unsafe_authorization","This resident does not offer secure Joplin pairing.","Update the resident to use the paired Joplin plugin. Do not enter a Web Clipper token.");if(row.reloadRequired)return result("setup-required","configuration_reload_required","Settings are saved, but the running connector has not reloaded them.","Restart Zortex, reopen Help, then click Connect. Saving settings alone does not verify a connection.");if(row.catalogOnly)return result("unsupported","connector_not_registered","This source is listed in the directory but has no registered connector in this session.","This version cannot connect this source from Help until its connector is installed and registered.");const unavailable=row.connection==="unavailable"||row.state==="unavailable"||row.registration==="deferred";if(unavailable||row.setupReason){if(platform!=="darwin"&&["apple-music","apple-notes","apple-reminders","imessage","macos-contacts","mac-apt"].includes(source))return result("unsupported","macos_required","This connector requires a macOS native application or runtime. This version has no Windows adapter.","Use this source on a supported Mac. It cannot be connected from Windows Help.");if(source==="cua")return result("unsupported","cua_driver_required","The computer-use connector requires the cua-driver executable, which is unavailable to this Zortex process.","Install and configure the supported cua-driver runtime, then restart Zortex and check again. Help cannot install this runtime.");if(source==="microsoft-teams")return result("unsupported","verified_tenant_binding_required","Microsoft Teams requires a protected delegated grant bound to a verified tenant and account. The unbound server-session route is disabled.","This version has no Help setup for that protected account binding. An administrator-approved connector integration is required before manual connection.");if(source==="dingtalk")return result("unsupported","organization_user_grant_required","DingTalk requires organization enablement and a protected user grant bound to the verified corporation and user.","This version has no supported browser login, device login or token-import setup in Help. Bot credentials cannot be used for this connection.");if(source==="telegram")return result("unsupported","selected_tdlib_session_required","Telegram requires a pre-authorized TDLib session, an exact account and chat selection, and a verified native runtime.","This version cannot create or select that Telegram session in Help. A supported session-setup integration is required before manual connection.");if(hasSetup)return result("setup-required","configuration_required","This source needs setup before its connection can be checked.","Complete the setup with the available tools. Zortex continues connection and readiness checks after the configuration is active.");if(row.registration==="deferred")return result("unsupported","manual_setup_unavailable","This connector requires configuration, but this version has no supported setup form for it in Help.","Manual connection cannot be completed in Help yet. Its connector setup integration must be added before retrying.");return result("unsupported","connector_unavailable","The registered connector is unavailable in this session. The cause has not been verified.","Connection cannot be completed in Help while the connector is unavailable. Check its platform requirements, installation and configuration.")}return result("supported","connection_available","A connection route is available in Zortex Help.","Continue the provider or local setup with the available tools. Connection and data access are verified separately.")}
1
+ const setups={joplin:["configureJoplin","joplinSetupAvailable"],"visual-studio":["configureNativeFiles","setupAvailable"],modelsim:["configureNativeFiles","setupAvailable"],quartus:["configureNativeFiles","setupAvailable"],simulink:["configureNativeFiles","setupAvailable"],jianying:["configureNativeFiles","setupAvailable"],"epic-games-launcher":["configureNativeFiles","setupAvailable"],"ryujinx":["configureNativeFiles","setupAvailable"],"modrinth":["configureNativeFiles","setupAvailable"],"powerpoint":["configureNativeFiles","setupAvailable"],"ti-ccs":["configureNativeFiles","setupAvailable"],"pscad":["configureNativeFiles","setupAvailable"],"adobe-photoshop":["configureNativeFiles","setupAvailable"],autocad:["configureNativeFiles","setupAvailable"],"microsoft-word":["configureNativeFiles","setupAvailable"],"microsoft-excel":["configureNativeFiles","setupAvailable"],"local-git":["configureNativeFiles","setupAvailable"],"vscode-local-history":["configureNativeFiles","setupAvailable"],"libreoffice":["configureNativeFiles","setupAvailable"],"adobe-acrobat":["configureNativeFiles","setupAvailable"],"adobe-camera-raw":["configureNativeFiles","setupAvailable"],"adobe-media-encoder":["configureNativeFiles","setupAvailable"],"ansys-electronics-desktop":["configureNativeFiles","setupAvailable"],"adobe-premiere-pro":["configureNativeFiles","setupAvailable"],"packet-tracer":["configureNativeFiles","setupAvailable"],"qt-designer":["configureNativeFiles","setupAvailable"],"hearthstone-deck-tracker":["configureNativeFiles","setupAvailable"],visio:["configureNativeFiles","setupAvailable"],matlab:["configureNativeFiles","setupAvailable"],"adobe-illustrator":["configureNativeFiles","setupAvailable"],"minecraft-java":["configureNativeFiles","setupAvailable"],"ni-tdms":["configureNativeFiles","setupAvailable"],jupyter:["configureNativeFiles","setupAvailable"],solidworks:["configureNativeFiles","setupAvailable"],lattics:["configureNativeFiles","setupAvailable"],jetbrains:["configureNativeFiles","setupAvailable"],eclipse:["configureNativeFiles","setupAvailable"],multisim:["configureNativeFiles","setupAvailable"],stm32cubemx:["configureNativeFiles","setupAvailable"],plecs:["configureNativeFiles","setupAvailable"],"local-audio":["configureNativeFiles","setupAvailable"],obsidian:["configureNativeFiles","setupAvailable"],logseq:["configureNativeFiles","setupAvailable"],"computer-files":["configureNativeFiles","setupAvailable"],zotero:["configureZotero","zoteroSetupAvailable"],owntracks:["configureOwnTracks","owntracksSetupAvailable"],wechat:["configureWeChat","wechatSetupAvailable"],thunderbird:["configureThunderbird","thunderbirdSetupAvailable"],"proton-mail":["configureProtonMail","protonMailSetupAvailable"],discord:["configureDiscord","discordSetupAvailable"],dropbox:["configureDropbox","dropboxSetupAvailable"],box:["configureBox","boxSetupAvailable"],front:["configureFront","frontSetupAvailable"],hubspot:["configureHubSpot","hubspotSetupAvailable"],"google-contacts":["configureGoogleContacts","googleContactsSetupAvailable"],"google-chat":["configureGoogleChat","googleChatSetupAvailable"],salesforce:["configureSalesforce","salesforceSetupAvailable"],zendesk:["configureZendesk","zendeskSetupAvailable"],zoom:["configureZoom","zoomSetupAvailable"],copyq:["configureCopyQ","copyqSetupAvailable"],freshdesk:["configureFreshdesk","freshdeskSetupAvailable"],figma:["configureFigma","figmaSetupAvailable"],smartsheet:["configureSmartsheet","smartsheetSetupAvailable"],nextcloud:["configureNextcloud","nextcloudSetupAvailable"],zulip:["configureZulip","zulipSetupAvailable"],freshrss:["configureFreshRSS","freshrssSetupAvailable"],miniflux:["configureMiniflux","minifluxSetupAvailable"],mattermost:["configureMattermost","mattermostSetupAvailable"],wallabag:["configureWallabag","wallabagSetupAvailable"],calcom:["configureCalcom","calcomSetupAvailable"],wakatime:["configureWakatime","wakatimeSetupAvailable"]};export function recoverySetupFlags(source,authorization){const setup=setups[source];return setup&&authorization&&typeof Reflect.get(authorization,setup[0])==="function"?{[setup[1]]:true}:{}}export function sourceSupport(row,hasSetup,platform=process.platform){const{source}=row;const result=(state,reasonCode,message,nextStep)=>({source,state,reasonCode,message,nextStep});if(source==="joplin"&&row.connection==="connected"&&row.registration!=="deferred"&&!row.reloadRequired)return result("supported","existing_authorization_read_only","Joplin is paired. Check note access with a read Action.","Choose Check connection to verify note access; use pairing to replace the connection.");if(source==="joplin"&&hasSetup)return result("setup-required","paired_plugin_required","Joplin uses encrypted pairing with its local Zortex plugin.","Install the Zortex Joplin plugin, then compare the fingerprints in both applications. No Web Clipper token is needed.");if(source==="joplin")return result("unsupported","unsafe_authorization","This resident does not offer secure Joplin pairing.","Update the resident to use the paired Joplin plugin. Do not enter a Web Clipper token.");if(row.reloadRequired)return result("setup-required","configuration_reload_required","Settings are saved, but the running connector has not reloaded them.","Restart Zortex, open this app in Apps, then connect again. Saving settings alone does not verify a connection.");if(row.catalogOnly)return hasSetup?result("setup-required","configuration_required","Set up this app before checking its connection.","Complete the setup here. Zortex continues when the configured connector is available."):result("unsupported","connector_not_registered","This source is listed in the directory but has no registered connector in this session.","This version cannot connect this source in Apps until its connector is installed and registered.");const unavailable=row.connection==="unavailable"||row.state==="unavailable"||row.registration==="deferred";if(unavailable||row.setupReason){if(platform!=="darwin"&&["apple-music","apple-notes","apple-reminders","imessage","macos-contacts","mac-apt"].includes(source))return result("unsupported","macos_required","This connector requires a macOS native application or runtime. This version has no Windows adapter.","Use this source on a supported Mac. It cannot be connected on Windows.");if(source==="cua")return result("unsupported","cua_driver_required","The computer-use connector requires the cua-driver executable, which is unavailable to this Zortex process.","Install and configure the supported cua-driver runtime, then restart Zortex and check again. This app cannot install this runtime.");if(source==="microsoft-teams")return result("unsupported","verified_tenant_binding_required","Microsoft Teams requires a protected delegated grant bound to a verified tenant and account. The unbound server-session route is disabled.","This version has no setup form for that protected account binding. An administrator-approved connector integration is required before manual connection.");if(source==="dingtalk")return result("unsupported","organization_user_grant_required","DingTalk requires organization enablement and a protected user grant bound to the verified corporation and user.","This version has no supported browser login, device login or token-import setup in Apps. Bot credentials cannot be used for this connection.");if(source==="telegram")return result("unsupported","selected_tdlib_session_required","Telegram requires a pre-authorized TDLib session, an exact account and chat selection, and a verified native runtime.","This version cannot create or select that Telegram session in Apps. A supported session-setup integration is required before manual connection.");if(hasSetup)return result("setup-required","configuration_required","This source needs setup before its connection can be checked.","Complete the setup in this app. Zortex continues connection and readiness checks when the configuration is active.");if(row.registration==="deferred")return result("unsupported","manual_setup_unavailable","This connector requires configuration, but this version has no supported setup form for it in Apps.","Manual connection cannot be completed in Apps yet. Its connector setup integration must be added before retrying.");return result("unsupported","connector_unavailable","The registered connector is unavailable in this session. The cause has not been verified.","Connection cannot be completed in Apps while the connector is unavailable. Check its platform requirements, installation and configuration.")}return result("supported","connection_available","Connect this app here.","Choose Connect manually, then follow the sign-in or setup steps. Your saved connection and available data are shown here.")}
@@ -0,0 +1 @@
1
+ import{HELP_CATALOG}from"./source-catalog.js";import{mergedRecoveryProgress}from"./recovery-progress.js";const mounts=new WeakMap;export async function recoverySurface(ctx,options){let page=ctx.get("zortexGalaxyPage");if(!page){let pending=mounts.get(ctx);if(!pending){pending=(async()=>{const galaxy=await import("@zortexhq/plugin-galaxy-ui");const child=ctx.plugin(galaxy,{directorySources:HELP_CATALOG.map(([source])=>source),connectionRequest:options.request,...options.authorization?.status?{connectionStatus:async()=>{const result=await options.authorization.status(AbortSignal.timeout(15e3));if(!("ok"in result))throw Error("Connection status is unavailable.");return result.ok}}:{},sourceProgress:async()=>mergedRecoveryProgress(ctx),sourceSupport:async()=>{const report=options.snapshot();return report.sources.concat(report.others).flatMap(row=>row.support?[row.support]:[])}});try{await child.await();const mounted=ctx.get("zortexGalaxyPage");if(!mounted)throw Error("The application could not be opened.");return mounted}catch(error){await child.dispose();throw error}})();mounts.set(ctx,pending);void pending.catch(()=>mounts.delete(ctx));ctx.effect(()=>()=>{mounts.delete(ctx)})}page=await pending}const url=new URL(page.url);url.hash=options.source?`apps/${options.source}`:"apps";return url.href}