@zortexhq/indra-v2.5 0.2.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +11 -4
  2. package/bin/codex-postinstall.mjs +1 -1
  3. package/dist/auto-sync.js +1 -1
  4. package/dist/cli-run.js +1 -1
  5. package/dist/codex-install.js +1 -1
  6. package/dist/codex-setup.js +1 -1
  7. package/dist/connector-worker.js +1 -1
  8. package/dist/content-find.js +2 -2
  9. package/dist/find-snapshots.js +1 -0
  10. package/dist/gateway.js +1 -1
  11. package/dist/imessage-sync.js +1 -0
  12. package/dist/local-cloud-policy.js +1 -1
  13. package/dist/local-cloud.js +1 -1
  14. package/dist/mail-search-body.js +1 -0
  15. package/dist/match-excerpt.js +1 -0
  16. package/dist/mcp.js +1 -1
  17. package/dist/native-connect.js +1 -0
  18. package/dist/native-level1-setup.js +1 -1
  19. package/dist/public-tool.js +1 -1
  20. package/dist/read-route.js +1 -0
  21. package/dist/recovery-support.js +1 -1
  22. package/dist/resident-ensure-ready.js +1 -1
  23. package/dist/resident-host.js +2 -2
  24. package/dist/resident-jobs.js +1 -1
  25. package/dist/resident-platform.js +1 -1
  26. package/dist/source-data.js +1 -0
  27. package/dist/supervised-sync.js +1 -1
  28. package/dist/sync-sources.js +1 -0
  29. package/dist/worker-google-auth.js +1 -0
  30. package/node_modules/@zortexhq/plugin-connector-calendar/dist/provider.js +1 -1
  31. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/catalog.js +1 -0
  32. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/index.js +1 -0
  33. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/policy.js +1 -0
  34. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/result.js +1 -0
  35. package/node_modules/@zortexhq/plugin-connector-computer-files/package.json +18 -0
  36. package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
  37. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  38. package/node_modules/@zortexhq/plugin-connector-core/dist/native-file-roots.js +1 -0
  39. package/node_modules/@zortexhq/plugin-connector-drive/dist/provider.js +1 -1
  40. package/node_modules/@zortexhq/plugin-connector-framework/dist/manifest.js +1 -1
  41. package/node_modules/@zortexhq/plugin-connector-framework/dist/runtime.js +1 -1
  42. package/node_modules/@zortexhq/plugin-connector-gmail/dist/brokered.js +1 -1
  43. package/node_modules/@zortexhq/plugin-connector-gmail/dist/gmail-source.js +2 -2
  44. package/node_modules/@zortexhq/plugin-connector-gmail/dist/provider.js +1 -1
  45. package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/provider.js +1 -1
  46. package/node_modules/@zortexhq/plugin-connector-history/dist/provider.js +1 -1
  47. package/node_modules/@zortexhq/plugin-connector-imessage/dist/attributed-body.js +1 -0
  48. package/node_modules/@zortexhq/plugin-connector-imessage/dist/chatdb-source.js +1 -0
  49. package/node_modules/@zortexhq/plugin-connector-imessage/dist/connector.js +1 -0
  50. package/node_modules/@zortexhq/plugin-connector-imessage/dist/index.js +1 -0
  51. package/node_modules/@zortexhq/plugin-connector-imessage/dist/manifest.js +1 -0
  52. package/node_modules/@zortexhq/plugin-connector-imessage/dist/sqlite-snapshot.js +1 -0
  53. package/node_modules/@zortexhq/plugin-connector-imessage/package.json +16 -0
  54. package/node_modules/@zortexhq/plugin-connector-level1/dist/api/index.js +1 -0
  55. package/node_modules/@zortexhq/plugin-connector-level1/dist/computer-files-pages.js +1 -1
  56. package/node_modules/@zortexhq/plugin-connector-level1/dist/computer-files.js +1 -0
  57. package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -0
  58. package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
  59. package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
  60. package/node_modules/@zortexhq/plugin-connector-level1/dist/sources.js +1 -1
  61. package/node_modules/@zortexhq/plugin-connector-level1/package.json +5 -1
  62. package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
  63. package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
  64. package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
  65. package/node_modules/@zortexhq/plugin-device-auth/dist/authority.js +1 -1
  66. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-catalog.js +1 -0
  67. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-renderer.js +1 -0
  68. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/galaxy-text.js +1 -1
  69. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
  70. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
  71. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/routes.js +1 -1
  72. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/snapshot.js +1 -1
  73. package/node_modules/@zortexhq/plugin-galaxy-ui/package.json +1 -0
  74. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -1
  75. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -1
  76. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
  77. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -1
  78. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/galaxy-renderer.js +1 -1
  79. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/live-model.js +1 -1
  80. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/portrait-model.js +1 -1
  81. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.js +1 -1
  82. package/node_modules/@zortexhq/plugin-google-auth/default-client.json +1 -0
  83. package/node_modules/@zortexhq/plugin-google-auth/dist/desktop-client.js +1 -1
  84. package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
  85. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
  86. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/search-text.js +1 -0
  87. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/source-sync.js +1 -0
  88. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/current-records.js +1 -0
  89. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  90. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/record-rules.js +1 -1
  91. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +19 -2
  92. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -0
  93. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
  94. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -0
  95. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +1 -1
  96. package/node_modules/@zortexhq/rooktrail/dist/record-rules.js +1 -1
  97. package/node_modules/@zortexhq/rooktrail/dist/registry.js +1 -1
  98. package/package.json +11 -7
  99. package/release-provenance.json +45 -31
  100. package/update-manifest.json +380 -164
@@ -1 +1 @@
1
- const READ_OPERATIONS=["search","read"];const HELP_OPERATIONS=["instruction","handbook"];const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const denied=(message="This connection has not been granted this capability.")=>({err:{code:"permission_denied",layer:"auth",message}});const expired=()=>({err:{code:"unauthenticated",layer:"auth",message:"This Local Cloud authorization expired or was revoked. Reconnect on the original computer. An already-started action may have taken effect."}});export function remoteOperations(access){const operations=[];if(access.authorize("vault.read"))operations.push(...READ_OPERATIONS);if(access.authorize("actions.read"))operations.push("actions");if(access.authorize("actions.read")||access.authorize("actions.execute"))operations.push("manage");if(access.authorize("actions.execute"))operations.push("action");if(operations.length||access.authorize("computer.control"))operations.push(...HELP_OPERATIONS);return operations}export function createRemoteGateway(gateway,access){const alive=()=>!access.grant.signal.aborted&&access.grant.expiresAt>Date.now();return{async call(operation,args={},options={}){if(!alive())return expired();if(!object(args))return{err:{code:"invalid_argument",layer:"auth",message:"Arguments must be an object."}};if(operation==="search"||operation==="read"){if(!access.authorize("vault.read"))return denied()}else if(operation==="actions"){if(!access.authorize("actions.read"))return denied()}else if(operation==="manage"){if(!access.authorize(args.what==="plugin.set-enabled"?"actions.execute":"actions.read"))return denied()}else if(operation==="action"){if(!access.authorize("actions.execute"))return denied();if(typeof args.name!=="string"||!object(args.params))return{err:{code:"invalid_argument",layer:"auth",message:"Pass an action name and params object."}}}else if(!HELP_OPERATIONS.includes(operation)||remoteOperations(access).length===0){return denied()}if(!alive())return expired();const signal=options.signal?AbortSignal.any([options.signal,access.grant.signal]):access.grant.signal;signal.throwIfAborted();const result=await gateway.call(operation,args,{signal});if(!alive())return expired();if((operation==="instruction"||operation==="handbook")&&object(result)&&object(result.ok)){return{...result,ok:{...result.ok,recovery:"Inspect manage what=onboarding and what=sources. A missing source authorization requires indra connect --source <source> on the original computer; its local agent or operator completes the actual OAuth, QR or permission gateway. This remote connection can inspect status and use authorized source actions. Do not create a second Vault on the cloud runner.",management:"Use manage to inspect installed plugins, onboarding and source status. An action-enabled connection may update source enablement through the same resident dispatcher.",connectors:"Discover provider actions with actions source, then method. Invoke the returned schema using action name=connector.invoke and params={source,method,input:{params:{...}}}. The existing account and provider contracts apply. Use connector.sync for an authorized source. Native computer operations require an available cua source on the original computer; discover its actual methods before invoking them. Ordinary browser work can also use the calling host's authorized tools. Indra does not provide an embedded browser controller.",localCloud:{scopes:access.grant.scopes,computerControl:access.authorize("actions.execute"),accountSetup:"Run indra connect --source <source> on the original computer to open the selected source gateway. This remote MCP connection can inspect the resulting source status.",authorization:"Use the authenticated product connection for the requested work without another confirmation. computerControl reports grant authorization, not installed CUA availability. Explicit revocation still stops access. The original computer must be awake and online."}}}}return result}}}
1
+ const READ_OPERATIONS=["search","read"];const HELP_OPERATIONS=["instruction","handbook"];const PUBLIC_STATUS_OPERATIONS=["status","sources","onboarding","startup"];const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const publicReadAction=args=>args.name==="connector.find"&&object(args.params);const publicReadStatus=args=>PUBLIC_STATUS_OPERATIONS.includes(args.what);const denied=(message="This Zortex connection has not been granted this capability.")=>({err:{code:"permission_denied",layer:"auth",reason:"zortex_connection_scope_missing",message}});const expired=()=>({err:{code:"unauthenticated",layer:"auth",reason:"zortex_connection_auth_required",message:"This Zortex connection expired or was revoked. Reconnect Zortex in the current host, then retry. An already-started action may have taken effect."}});export function remoteOperations(access){const operations=[];if(access.authorize("vault.read"))operations.push(...READ_OPERATIONS);if(access.authorize("actions.read"))operations.push("actions");if(access.authorize("actions.read")||access.authorize("actions.execute"))operations.push("manage");if(access.authorize("actions.execute"))operations.push("action");if(operations.length||access.authorize("computer.control"))operations.push(...HELP_OPERATIONS);return operations}export function createRemoteGateway(gateway,access){const alive=()=>!access.grant.signal.aborted&&access.grant.expiresAt>Date.now();const identityAuthorized=()=>access.authorize("vault.read")||access.authorize("actions.read")||access.authorize("actions.execute");return{...gateway.connectedIdentities?{async connectedIdentities(signal){if(!alive()||!identityAuthorized())return[];const combined=signal?AbortSignal.any([signal,access.grant.signal]):access.grant.signal;combined.throwIfAborted();const identities=await gateway.connectedIdentities(combined);return alive()?identities:[]}}:{},async call(operation,args={},options={}){if(!alive())return expired();if(!object(args))return{err:{code:"invalid_argument",layer:"auth",message:"Arguments must be an object."}};if(operation==="search"||operation==="read"){if(!access.authorize("vault.read"))return denied()}else if(operation==="actions"){if(!access.authorize("actions.read"))return denied()}else if(operation==="manage"){const scope=args.what==="plugin.set-enabled"?"actions.execute":publicReadStatus(args)?void 0:"actions.read";if(scope){if(!access.authorize(scope))return denied()}else if(!access.authorize("vault.read")&&!access.authorize("actions.read"))return denied()}else if(operation==="action"){if(typeof args.name!=="string"||!object(args.params))return{err:{code:"invalid_argument",layer:"auth",message:"Pass an action name and params object."}};if(publicReadAction(args)){if(!access.authorize("vault.read"))return denied()}else if(!access.authorize("actions.execute"))return denied()}else if(!HELP_OPERATIONS.includes(operation)||remoteOperations(access).length===0){return denied()}if(!alive())return expired();const signal=options.signal?AbortSignal.any([options.signal,access.grant.signal]):access.grant.signal;signal.throwIfAborted();const result=await gateway.call(operation,args,{signal});if(!alive())return expired();if((operation==="instruction"||operation==="handbook")&&object(result)&&object(result.ok)){return{...result,ok:{...result.ok,recovery:"Use zortex status to inspect source readiness. If the result reports source authorization is required, call zortex ensure_ready for that source and follow only the returned provider-consent step. A Zortex connection authorization error is separate: reconnect Zortex in the current host. Never substitute browser or desktop automation.",management:"Use zortex status for product and source state. Use zortex ensure_ready only when the requested source is not ready.",connectors:"Use zortex find for bounded reads and zortex act for explicit reviewed effects. Preserve the connected account shown by the Zortex tool; never guess or switch to a similarly named host connector.",connection:{scopes:access.grant.scopes,actionsAuthorized:access.authorize("actions.execute"),authorization:"Zortex connection authorization and source-provider authorization are separate. Explicit revocation stops access. The Zortex host must remain online."}}}}return 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,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
+ 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}from"./local-cloud-policy.js";import{createPublicConfirmationStore}from"./public-tool.js";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){const anonymousConfirmations=createPublicConfirmationStore();const grantConfirmations=new Map;return async(request,access)=>{const now=Date.now();for(const[id,row]of grantConfirmations)if(row.expiresAt<=now)grantConfirmations.delete(id);let confirmationStore=anonymousConfirmations;if(access){let row=grantConfirmations.get(access.grant.id);if(!row){row={expiresAt:access.grant.expiresAt,store:createPublicConfirmationStore()};grantConfirmations.set(access.grant.id,row);access.grant.signal.addEventListener("abort",()=>grantConfirmations.delete(access.grant.id),{once:true})}confirmationStore=row.store}const server=createMcp(access?createRemoteGateway(gateway,access):gateway,{surface:"public",remote:true,requestSignal:request.signal,confirmationStore,...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")})})}
@@ -0,0 +1 @@
1
+ const FOOTER_MARKERS=["\u6B64\u90AE\u4EF6\u53D1\u9001\u7ED9","\u6B64\u90AE\u4EF6\u53D1\u9001\u81F3","\u6B64\u7535\u5B50\u90AE\u4EF6\u5DF2\u53D1\u9001\u81F3","this email was intended for","this email was sent to","this message was sent to"];const PREFIXES=[""," "," "," "];const boundaries=FOOTER_MARKERS.flatMap(marker=>PREFIXES.map(prefix=>"\n"+prefix+marker));export function mailSearchBody(source,body){if(source!=="gmail"&&source!=="outlook")return body;const normalized=body.replace(/\r/gu,""),search="\n"+normalized.toLowerCase();let end=normalized.length;for(const marker of boundaries){const at=search.indexOf(marker);if(at>=0)end=Math.min(end,at)}return normalized.slice(0,end)}export function mailSearchBodySql(body,source){const normalized=`replace(coalesce(${body},''),char(13),'')`;const ends=boundaries.map(marker=>`coalesce(nullif(instr(char(10)||lower(${normalized}),'${marker.replaceAll("'","''")}'),0)-1,length(${normalized}))`);return`CASE WHEN ${source} IN ('gmail','outlook') THEN substr(${normalized},1,min(${ends.join(",")})) ELSE ${body} END`}
@@ -0,0 +1 @@
1
+ export function matchExcerpt(body,plan,max=800){const value=body.trim().replace(/\s+/gu," ");if(value.length<=max)return value;const lower=value.toLowerCase(),terms=[plan.focus,...plan.queries,...plan.semanticTerms];let anchor=-1;for(const term of terms){const needle=term.toLowerCase();const at=needle==="thu"?lower.search(/(?:^|[^a-z0-9])thu(?=$|[^a-z0-9])/u):lower.indexOf(needle);if(at>=0){anchor=at;break}}let start=Math.max(0,anchor-Math.min(80,Math.floor(max/3)));start=Math.min(start,Math.max(0,value.length-(max-2)));if(start>0&&/[\uDC00-\uDFFF]/u.test(value[start]))start--;let end=Math.min(value.length,start+max-2);if(end<value.length&&/[\uDC00-\uDFFF]/u.test(value[end]))end--;return(start?"\u2026":"")+value.slice(start,end)+(end<value.length?"\u2026":"")}
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,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{traceProductOperation}from"./operation-telemetry.js";import{createPublicToolRouter,publicIntentOperation,publicTool}from"./public-tool.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 publicRouter=localUpdates?createPublicToolRouter({gateway,updater}):void 0;const server=new Server({name:"indra-v2",version:"0.1.0-dev.3"},{capabilities:{tools:{}}});const tools=localUpdates?[publicTool]: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 source action using name and params through the original computer. Native computer operations require an installed, available CUA provider and an action grant. Missing source authorization uses indra connect --source <source> on the original computer. Continue through available authorized 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)}}:{}}});server.setRequestHandler("tools/list",()=>({tools}));server.setRequestHandler("tools/call",async(request,context)=>{const name=request.params.name,publicCall=localUpdates&&name===publicTool.name,spec=localUpdates?void 0:specs.find(spec2=>"indra."+spec2.operation===name);const args=request.params.arguments??{};const tool=invocationTool(publicCall?publicIntentOperation(args):spec?.operation);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=publicCall?await publicRouter.call(args,signal):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(publicCall&&tool!=="update"&&!!result&&typeof result==="object"&&"ok"in result)).catch(()=>{})}let updateNotice;if(localUpdates&&publicCall&&tool!=="update"&&!(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{traceProductOperation}from"./operation-telemetry.js";import{createPublicTool,createPublicToolRouter,publicIntentOperation,publicTool}from"./public-tool.js";import{readFileSync}from"node:fs";export const ORDINARY_MCP_CONTRACT_VERSION="1";function runtimeIdentity(base=new URL("../",import.meta.url)){const read=name=>{try{return JSON.parse(readFileSync(new URL(name,base),"utf8"))}catch{return}};const manifest=read("package.json"),provenance=read("release-provenance.json");const version=typeof manifest?.version==="string"&&/^[0-9A-Za-z.+-]{1,80}$/u.test(manifest.version)?manifest.version:"unknown";const commit=version!=="unknown"&&provenance?.name==="@zortexhq/indra-v2.5"&&provenance.version===version&&typeof provenance.commit==="string"&&/^[a-f0-9]{40}$/u.test(provenance.commit)?provenance.commit:void 0;return{version,...commit?{commit}:{}}}const runtime=runtimeIdentity();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();if(options.surface==="public"&&options.operations)throw Error("PUBLIC_MCP_CANNOT_SELECT_DIAGNOSTIC_OPERATIONS");const publicSurface=options.surface?options.surface==="public":!options.remote&&!options.operations;const localUpdates=publicSurface&&!options.remote;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 publicRouter=publicSurface?createPublicToolRouter({gateway,updater,...options.confirmationStore?{confirmationStore:options.confirmationStore}:{}}):void 0;const surface=publicSurface?"ordinary":"scoped";const contractVersion=publicSurface?ORDINARY_MCP_CONTRACT_VERSION:"diagnostic-1";const server=new Server({name:"indra-v2",version:runtime.version,description:`Zortex ${surface} MCP surface (${contractVersion}).`},{capabilities:{tools:{},experimental:{zortex:{surface,contractVersion,productVersion:runtime.version,...runtime.commit?{sourceCommit:runtime.commit}:{}}}}});const tools=publicSurface?[publicTool]: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 source action using name and params through the original computer. Native computer operations require an installed, available CUA provider and an action grant. Missing source authorization uses indra connect --source <source> on the original computer. Continue through available authorized 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)}}:{}}});server.setRequestHandler("tools/list",async(_request,context)=>{if(!publicSurface||!gateway.connectedIdentities)return{tools};let identities=[];try{identities=await gateway.connectedIdentities(context.mcpReq.signal)}catch{}return{tools:[createPublicTool(identities)]}});server.setRequestHandler("tools/call",async(request,context)=>{const name=request.params.name,publicCall=publicSurface&&name===publicTool.name,spec=publicSurface?void 0:specs.find(spec2=>"indra."+spec2.operation===name);const args=request.params.arguments??{};const tool=invocationTool(publicCall?publicIntentOperation(args):spec?.operation);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=publicCall?await publicRouter.call(args,signal):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(publicCall&&tool!=="update"&&!!result&&typeof result==="object"&&"ok"in result)).catch(()=>{})}let updateNotice;if(localUpdates&&publicCall&&tool!=="update"&&!(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
3
  [Zortex update] Version ${offer.targetVersion} is available (installed ${offer.currentVersion}${estimate}). Use the zortex tool with intent=update and input={operation:"check"}, then intent=update with input={operation:"apply",version,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 publicAction=publicCall&&tool==="action"&&args&&typeof args==="object"&&!Array.isArray(args)&&"input"in args&&args.input&&typeof args.input==="object"&&!Array.isArray(args.input)?args.input:void 0;const saved=await observeBounded(()=>options.telemetry?.()?.record({operation,outcome,durationMs,...resultSummary?{result:resultSummary}:{},...errorCategory?{errorCategory}:{},...tool==="action"&&(args.name==="connector.invoke"||publicAction?.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:outcome==="ok"||outcome==="empty",...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")})}
@@ -0,0 +1 @@
1
+ export const NATIVE_AUTO_CONNECT_SOURCES=["google-chrome","microsoft-edge","activitywatch","computer-files"];export const isNativeAutoConnectSource=source=>NATIVE_AUTO_CONNECT_SOURCES.includes(source);export function nativeSetupOutcome(value,source){if(!value||typeof value!=="object"||!("sources"in value)||!Array.isArray(value.sources))return;return value.sources.find(row=>!!row&&typeof row==="object"&&"source"in row&&row.source===source&&"state"in row&&["configured","permission-required","selection-required","configuration-required","unavailable"].includes(String(row.state)))}export function nativeSetupError(outcome){if(outcome.enabled===false||outcome.state==="unavailable")return"unavailable";if(outcome.state==="configured")return;return outcome.state==="permission-required"?"permission_denied":"failed_precondition"}export async function connectWithNativeSetup(source,configure,connect,signal){if(signal?.aborted)return{err:{code:"aborted"}};if(!isNativeAutoConnectSource(source))return connect();const outcome=nativeSetupOutcome(await configure([source]),source);if(signal?.aborted)return{err:{code:"aborted"}};const code=outcome?nativeSetupError(outcome):"failed_precondition";return code?{err:{code}}:connect()}export{connectWithNativeSetup as connectWithNativeHistorySetup};const LOCAL_SERVICE_RETRY_DELAYS_MS=[5e3,3e4,12e4,15*6e4];export function createNativeSetupRecovery(options){const timers=new Map,attempts=new Map;let queue=Promise.resolve(),closed=false;const clear=source=>{clearTimeout(timers.get(source));timers.delete(source)};const close=()=>{closed=true;for(const source of timers.keys())clear(source)};options.signal.addEventListener("abort",close,{once:true});const prepare=source=>{const next=queue.then(async()=>{if(closed||options.signal.aborted)return;const result=await options.prepare([source],options.signal);if(closed||options.signal.aborted)return result;const outcome=nativeSetupOutcome(result,source);const retry=source==="activitywatch"&&outcome?.enabled!==false&&(outcome?.state==="unavailable"||outcome?.retryable===true);if(!retry){clear(source);return result}const attempt=attempts.get(source)??0;if(!timers.has(source)){attempts.set(source,Math.min(attempt+1,LOCAL_SERVICE_RETRY_DELAYS_MS.length-1));const timer=setTimeout(()=>{timers.delete(source);void prepare(source).then(recovered=>{const ready=nativeSetupOutcome(recovered,source);if(!closed&&!options.signal.aborted&&ready?.state==="configured"&&ready.enabled!==false)options.ready(source)}).catch(()=>{})},LOCAL_SERVICE_RETRY_DELAYS_MS[Math.min(attempt,LOCAL_SERVICE_RETRY_DELAYS_MS.length-1)]);timer.unref?.();timers.set(source,timer)}return result});queue=next.catch(()=>{});return next};return{prepare,async close(){close();options.signal.removeEventListener("abort",close);await queue}}}
@@ -1 +1 @@
1
- import{currentNativePrincipal,saveNativeReadPermission as saveNativePermission}from"@zortexhq/plugin-connector-core/api";export{currentNativePrincipal}from"@zortexhq/plugin-connector-core/api";import{interpolate}from"@deepseek-ai/cordis-plugin-loader";import{prepareMacAptOptions,preparedLocalRootsAudience,preparedLocalNativeSelection,prepareLevel1Configuration,updateLevel1Configuration}from"@zortexhq/plugin-connector-level1";import{historyReadAudience}from"@zortexhq/plugin-connector-history";import{activityWatchReadAudience,defaultActivityWatchUrl}from"@zortexhq/plugin-connector-activitywatch";import{lstat,readdir,realpath,readFile}from"node:fs/promises";import{join,isAbsolute}from"node:path";import{request}from"node:http";import{zoteroServerId}from"./zotero-level1-setup.js";const fileSources=["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","obsidian","local-audio","computer-files"];const fixedWindowsSources=["windows-event-viewer","windows-task-scheduler","wsl"];const fixedWindowsSource=source=>fixedWindowsSources.some(id=>id===source);const serviceSources=[...fixedWindowsSources,"docker-desktop","ollama","owntracks","wechat","copyq","zotero","imessage","macos-contacts"];const fileSource=source=>fileSources.includes(source);const serviceSource=source=>serviceSources.includes(source);const defaults=["google-chrome","microsoft-edge","activitywatch"];const sources=[...defaults,"mac-apt",...fileSources,...serviceSources];const modules={"google-chrome":"@zortexhq/plugin-connector-history/chrome","microsoft-edge":"@zortexhq/plugin-connector-history/edge",activitywatch:"@zortexhq/plugin-connector-activitywatch","mac-apt":"@zortexhq/plugin-connector-level1","visual-studio":"@zortexhq/plugin-connector-level1",modelsim:"@zortexhq/plugin-connector-level1",quartus:"@zortexhq/plugin-connector-level1",simulink:"@zortexhq/plugin-connector-level1",jianying:"@zortexhq/plugin-connector-level1","epic-games-launcher":"@zortexhq/plugin-connector-level1",ryujinx:"@zortexhq/plugin-connector-level1",modrinth:"@zortexhq/plugin-connector-level1",powerpoint:"@zortexhq/plugin-connector-level1","ti-ccs":"@zortexhq/plugin-connector-level1",pscad:"@zortexhq/plugin-connector-level1","adobe-photoshop":"@zortexhq/plugin-connector-level1",autocad:"@zortexhq/plugin-connector-level1","microsoft-word":"@zortexhq/plugin-connector-level1","microsoft-excel":"@zortexhq/plugin-connector-level1","local-git":"@zortexhq/plugin-connector-level1","vscode-local-history":"@zortexhq/plugin-connector-level1","libreoffice":"@zortexhq/plugin-connector-level1","adobe-acrobat":"@zortexhq/plugin-connector-level1","adobe-camera-raw":"@zortexhq/plugin-connector-level1","adobe-media-encoder":"@zortexhq/plugin-connector-level1","ansys-electronics-desktop":"@zortexhq/plugin-connector-level1","adobe-premiere-pro":"@zortexhq/plugin-connector-level1","packet-tracer":"@zortexhq/plugin-connector-level1","qt-designer":"@zortexhq/plugin-connector-level1","hearthstone-deck-tracker":"@zortexhq/plugin-connector-level1",visio:"@zortexhq/plugin-connector-level1",matlab:"@zortexhq/plugin-connector-level1","adobe-illustrator":"@zortexhq/plugin-connector-level1","minecraft-java":"@zortexhq/plugin-connector-level1","ni-tdms":"@zortexhq/plugin-connector-level1",jupyter:"@zortexhq/plugin-connector-level1",solidworks:"@zortexhq/plugin-connector-level1",lattics:"@zortexhq/plugin-connector-level1",jetbrains:"@zortexhq/plugin-connector-level1",eclipse:"@zortexhq/plugin-connector-level1",multisim:"@zortexhq/plugin-connector-level1",stm32cubemx:"@zortexhq/plugin-connector-level1",plecs:"@zortexhq/plugin-connector-level1",obsidian:"@zortexhq/plugin-connector-level1","local-audio":"@zortexhq/plugin-connector-level1","computer-files":"@zortexhq/plugin-connector-level1","windows-event-viewer":"@zortexhq/plugin-connector-level1","windows-task-scheduler":"@zortexhq/plugin-connector-level1","wsl":"@zortexhq/plugin-connector-level1","docker-desktop":"@zortexhq/plugin-connector-level1",ollama:"@zortexhq/plugin-connector-level1",owntracks:"@zortexhq/plugin-connector-level1",wechat:"@zortexhq/plugin-connector-level1",copyq:"@zortexhq/plugin-connector-level1",zotero:"@zortexhq/plugin-connector-level1",imessage:"@zortexhq/plugin-connector-level1","macos-contacts":"@zortexhq/plugin-connector-level1"};const validText=(value,max=512)=>typeof value==="string"&&!!value&&value===value.trim()&&value.length<=max&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value);export function readNativeActivityMetadata(base,path){const origin=new URL(base);if(origin.protocol!=="http:"||!["127.0.0.1","[::1]"].includes(origin.hostname)||origin.port==="0"||origin.pathname!=="/"||origin.search||origin.hash||origin.username||origin.password||!["/api/0/info","/api/0/buckets/"].includes(path))throw Error("Invalid local ActivityWatch selection.");return new Promise((resolve,reject)=>{const req=request(new URL(path,origin),{method:"GET",agent:false,headers:{accept:"application/json"}},res=>{if(res.statusCode!==200){res.resume();reject(Error("ActivityWatch metadata needs local access or authorization."));return}let bytes=0;const chunks=[];res.on("data",chunk=>{bytes+=chunk.length;if(bytes>1048576){req.destroy(Error("ActivityWatch metadata exceeds its bound."));return}chunks.push(chunk)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")))}catch{reject(Error("Invalid ActivityWatch metadata."))}});res.on("error",reject)});const timeout=setTimeout(()=>req.destroy(Error("ActivityWatch metadata timed out.")),5e3);req.on("close",()=>clearTimeout(timeout));req.on("error",reject);req.end()})}function plain(value,keys){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error("Invalid native source options.");for(const key of Reflect.ownKeys(value)){const descriptor=Object.getOwnPropertyDescriptor(value,key);if(typeof key!=="string"||!keys.includes(key)||!descriptor.enumerable||!("value"in descriptor))throw Error("Invalid native source options.")}}const validBuckets=value=>Array.isArray(value)&&value.length>0&&value.length<=32&&Object.keys(value).length===value.length&&new Set(value).size===value.length&&value.every(id=>validText(id,480)&&id!=="."&&id!==".."&&!/[\/\\]/u.test(id));function validRoots(value){if(!Array.isArray(value)||value.length<1||value.length>16||Object.keys(value).length!==value.length)return false;const roots=[];for(let index=0;index<value.length;index++){const item=Object.getOwnPropertyDescriptor(value,String(index));if(!item?.enumerable||!("value"in item)||!validText(item.value,4096)||!isAbsolute(item.value))return false;roots.push(item.value)}return new Set(roots).size===roots.length}function validateSelection(value){plain(value,["sources","options"]);if(value.sources!==void 0&&(!Array.isArray(value.sources)||Object.keys(value.sources).length!==value.sources.length||new Set(value.sources).size!==value.sources.length||value.sources.some(source=>!sources.includes(source))))throw Error("Invalid native source selection.");if(value.options!==void 0){plain(value.options,sources);for(const[source,options]of Object.entries(value.options)){plain(options,source==="mac-apt"?["pythonExecutable","packageDirectory","artifacts"]:fileSource(source)?["roots"]:serviceSource(source)?source==="docker-desktop"||fixedWindowsSource(source)?[]:source==="ollama"||source==="owntracks"||source==="wechat"?["port"]:source==="copyq"?["executable","session"]:source==="zotero"?["libraryId","libraryType"]:["executable"]:source==="activitywatch"?["baseUrl","bucketIds"]:["root","profile"]);if(fileSource(source)){if(source==="jianying"&&(!Array.isArray(options.roots)||options.roots.length!==1))throw Error("Choose one Jianying draft folder.");if(source==="simulink"&&(!Array.isArray(options.roots)||options.roots.length!==1))throw Error("Choose one Simulink model folder.");if((source==="visual-studio"||source==="modelsim"||source==="quartus"||source==="epic-games-launcher"||source==="ryujinx"||source==="modrinth"||source==="powerpoint"||source==="ti-ccs"||source==="pscad"||source==="adobe-photoshop"||source==="autocad"||source==="microsoft-word"||source==="microsoft-excel"||source==="local-git"||source==="vscode-local-history"||source==="libreoffice"||source==="adobe-acrobat"||source==="adobe-camera-raw"||source==="adobe-media-encoder"||source==="ansys-electronics-desktop"||source==="adobe-premiere-pro"||source==="packet-tracer"||source==="qt-designer"||source==="hearthstone-deck-tracker"||source==="visio"||source==="matlab"||source==="adobe-illustrator"||source==="minecraft-java"||source==="ni-tdms"||source==="jupyter")&&(!Array.isArray(options.roots)||options.roots.length!==1))throw Error("Choose one source folder.");if(options.roots!==void 0&&!validRoots(options.roots))throw Error("Invalid native file root selection.");continue}if(serviceSource(source)){if(options.port!==void 0&&(!Number.isInteger(options.port)||options.port<1024||options.port>65535)||options.executable!==void 0&&(!validText(options.executable,4096)||!isAbsolute(options.executable))||options.session!==void 0&&(typeof options.session!=="string"||!/^[\p{L}\p{N}_-]{0,16}$/u.test(options.session))||options.libraryId!==void 0&&(typeof options.libraryId!=="string"||!(/^[1-9][0-9]{0,19}$/u.test(options.libraryId)||options.libraryId==="0"&&options.libraryType==="user"))||options.libraryType!==void 0&&!["user","group"].includes(options.libraryType))throw Error("Invalid native service selection.");continue}if(source==="mac-apt"){for(const key of["pythonExecutable","packageDirectory"])if(options[key]!==void 0&&(!validText(options[key],4096)||!isAbsolute(options[key])))throw Error("Invalid native source options.");if(options.artifacts!==void 0){if(!Array.isArray(options.artifacts)||options.artifacts.length<1||options.artifacts.length>16)throw Error("Invalid native source options.");for(const item of options.artifacts){plain(item,["id","kind","path"]);if(!validText(item.id,64)||!["recent-places","install-history","dock-items"].includes(item.kind)||!validText(item.path,4096)||!isAbsolute(item.path))throw Error("Invalid native source options.")}}continue}if(options.root!==void 0&&(!validText(options.root,4096)||!isAbsolute(options.root))||options.profile!==void 0&&(!validText(options.profile,64)||!/^(Default|Profile \d{1,8})$/u.test(options.profile))||options.bucketIds!==void 0&&!validBuckets(options.bucketIds))throw Error("Invalid native source options.");if(options.baseUrl!==void 0){if(!validText(options.baseUrl,512))throw Error("Invalid native source options.");activityWatchReadAudience(options.baseUrl,"validation",["validation"])}}}}export async function readNativeLevel1Selection(file){if(!isAbsolute(file))throw Error("Native setup requires an absolute options file.");const stat=await lstat(file);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>1048576)throw Error("Invalid native source options file.");const raw=await readFile(file,"utf8");if(Buffer.byteLength(raw)>1048576)throw Error("Invalid native source options file.");const value=JSON.parse(raw);validateSelection(value);return value}export async function configureNativeLevel1(ctx,input={},deps={}){validateSelection(input);const selected=input.sources??(input.options?.["mac-apt"]?[...defaults,"mac-apt"]:defaults),results=[];if(!selected.length)return{sources:[],reloadRequired:false};let native;try{native=await(deps.principal??currentNativePrincipal)();if(!validText(native.issuer)||!validText(native.subject)||!validText(native.hostname)||!isAbsolute(native.home))throw Error()}catch{return{sources:selected.map(source=>({source,state:"unavailable",next:"Run native setup in the signed-in desktop session; its OS identity could not be verified."})),reloadRequired:false}}const loader=ctx.get("loader"),vault=ctx.get("zortexVaultStore");if(!loader||!vault)throw Error("Native setup requires the installed product loader and Vault.");for(const source of selected)try{const entries=[...loader.entries()].filter(row=>row.options.publicModule===modules[source]||row.options.name===modules[source]);if(entries.length!==1){results.push({source,state:"unavailable",next:"Load the installed source plugin once before native setup."});continue}const entry=entries[0],options=input.options?.[source]??{};const effective=entry.fiber?.config??interpolate(entry.context,entry.options.config);const existing=effective;let configuration,audience,scope;if(source==="mac-apt"||fileSource(source)||serviceSource(source)){const config=effective;if((source==="imessage"||source==="macos-contacts")&&process.platform!=="darwin"){results.push({source,state:"unavailable",next:"Run this source\u2019s native setup in the selected Mac user session with its installed Apple bridge and OS access."});continue}if(source==="mac-apt"&&(!options.pythonExecutable||!options.packageDirectory||!options.artifacts)){results.push({source,state:"configuration-required",next:'Install the pinned mac_apt runtime and supply its interpreter, package directory and selected artifact paths in options["mac-apt"].'});continue}if(fileSource(source)&&!options.roots){results.push({source,state:"selection-required",next:"Choose the folders this app may read in options[source].roots, then run native setup again."});continue}if(fixedWindowsSource(source)&&process.platform!=="win32"){results.push({source,state:"unavailable",next:"Run this native metadata reader in the signed-in Windows session."});continue}if(source==="docker-desktop"&&process.platform!=="win32"){results.push({source,state:"unavailable",next:"Select the local Windows Docker Desktop Linux engine."});continue}if(serviceSource(source)&&!fixedWindowsSource(source)&&source!=="docker-desktop"&&(source==="ollama"||source==="owntracks"||source==="wechat"?options.port===void 0:source==="copyq"?!options.executable||options.session===void 0:source==="zotero"?!options.libraryId||options.libraryType===void 0:!options.executable)){results.push({source,state:"selection-required",next:source==="ollama"?"Select the port of your existing local Ollama server.":source==="owntracks"?"Choose the existing local OwnTracks MCP port in options.owntracks.port.":source==="wechat"?"Choose the existing local WeChat chatlog MCP port in options.wechat.port.":source==="copyq"?"Select the installed CopyQ executable and session in options.copyq; an empty session explicitly selects its default session.":source==="zotero"?"Select the local Zotero libraryId and libraryType (user or group) in options.zotero.":"Select the installed Apple bridge executable in options[source].executable."});continue}if(!config?.provisioningFile||!isAbsolute(config.provisioningFile)){results.push({source,state:"configuration-required",next:"Load the installed Level1 setup file before configuring this native source."});continue}let prepared;if(source==="mac-apt")prepared={...await(deps.macApt??prepareMacAptOptions)(vault,{pythonExecutable:options.pythonExecutable,packageDirectory:options.packageDirectory,artifacts:options.artifacts})};else if(serviceSource(source)){let selection;try{const selectedOptions=source==="zotero"?{...options,serverId:await zoteroServerId()}:options;selection=preparedLocalNativeSelection(source,selectedOptions)}catch{results.push({source,state:"configuration-required",next:source==="zotero"?"Start Zotero 10 or later with the local API enabled and retry.":"Check this source\u2019s selected runtime, endpoint, session or library options, then run native setup again."});continue}const permission=await saveNativePermission(vault,source,native,selection.audience,selection.scope);prepared={...selection.options,resourceId:permission.resourceId,issuer:permission.issuer,audience:selection.audience,requiredScopes:[selection.scope]}}else{const roots=[];for(const chosen of options.roots){const root=await realpath(chosen),stat=await lstat(root);if(!stat.isDirectory()||native.uid!==void 0&&stat.uid!==native.uid)throw Error("Selected root is not owned by this native user.");roots.push(root)}roots.sort();const audience2=preparedLocalRootsAudience(source,roots),scope2="files.read";const permission=await saveNativePermission(vault,source,native,audience2,scope2);prepared={roots,resourceId:permission.resourceId,issuer:permission.issuer,audience:audience2,requiredScopes:[scope2]}}await updateLevel1Configuration(config.provisioningFile,async current=>{const saved=current??(await prepareLevel1Configuration(vault,{},config.runtimeDirectory?{runtimeDirectory:config.runtimeDirectory}:{})).configuration;const selected2=[...new Set([...saved.sources??[],source])],requested=[...new Set([...saved.requestedSources??saved.sources??[],...selected2])];return{configuration:{...saved,sources:selected2,requestedSources:requested,prepared:{...saved.prepared,[source]:prepared}},value:void 0}});results.push({source,state:"configured",enabled:!entry.disabled&&(config.sources===void 0||config.sources.includes(source))});continue}if(source!=="activitywatch"){const vendor=source==="google-chrome"?"Google/Chrome":"Microsoft/Edge";const fallback=process.platform==="win32"?join(native.localAppData??native.home,vendor,"User Data"):process.platform==="darwin"?join(native.home,"Library/Application Support",vendor):join(native.home,".config",source==="google-chrome"?"google-chrome":"microsoft-edge");const chosen=options.root??existing?.root??fallback;if(!isAbsolute(chosen))throw Error("Select an absolute browser root.");const root=await realpath(chosen),rootStat=await lstat(root);if(!rootStat.isDirectory()||native.uid!==void 0&&rootStat.uid!==native.uid)throw Error("Selected browser root is not owned by this native user.");const candidates=(await readdir(root,{withFileTypes:true})).filter(row=>row.isDirectory()&&/^(Default|Profile \d{1,8})$/u.test(row.name)).map(row=>row.name).sort();const profiles=[];for(const profile2 of candidates.slice(0,64)){const file=await lstat(join(root,profile2,"History")).catch(()=>void 0);if(file?.isFile()&&!file.isSymbolicLink()&&(native.uid===void 0||file.uid===native.uid))profiles.push(profile2)}const profile=options.profile??(existing?.root===root?existing.profile:void 0)??profiles[0];if(!profile||!profiles.includes(profile)){results.push({source,state:"selection-required",profiles,next:"Choose one listed browser profile in options[source].profile and run native setup again."});continue}audience=historyReadAudience(source,root,profile);scope="history.read";configuration={root,profile}}else{const baseUrl=options.baseUrl??existing?.baseUrl??defaultActivityWatchUrl,metadata=deps.metadata??readNativeActivityMetadata;const info=await metadata(baseUrl,"/api/0/info");if(!info||!validText(info.device_id)||typeof info.hostname!=="string")throw Error("ActivityWatch did not identify its native device.");let bucketIds=options.bucketIds??(existing?.baseUrl===baseUrl?existing.bucketIds:void 0);if(!bucketIds){const raw=await metadata(baseUrl,"/api/0/buckets/");if(!raw||typeof raw!=="object"||Array.isArray(raw))throw Error("ActivityWatch bucket metadata is unavailable.");const local=Object.entries(raw).filter(([id,bucket])=>validText(id,480)&&id!=="."&&id!==".."&&!/[\/\\]/u.test(id)&&bucket&&typeof bucket==="object"&&bucket.hostname===native.hostname).map(([id])=>id).sort();if(!local.length||local.length>32){results.push({source,state:"selection-required",bucketIds:local.slice(0,32),next:"Choose this computer\u2019s ActivityWatch buckets in options.activitywatch.bucketIds."});continue}bucketIds=local}audience=activityWatchReadAudience(baseUrl,info.device_id,bucketIds);scope="local-activity.read";configuration={baseUrl,deviceId:info.device_id,bucketIds,...existing?.apiKeyResourceId?{apiKeyResourceId:existing.apiKeyResourceId}:{}}}const authority=await saveNativePermission(vault,source,native,audience,scope);await loader.update(entry.id,{config:{...configuration,authority}});await loader.await();results.push({source,state:"configured",enabled:!entry.disabled})}catch(error){const code=source==="mac-apt"&&error&&typeof error==="object"&&"code"in error?error.code:void 0;if(code==="failed_precondition")results.push({source,state:"configuration-required",next:"Check the pinned mac_apt interpreter, dependencies and selected artifact paths, then run native setup again."});else if(code==="unavailable")results.push({source,state:"unavailable",next:"Run Mac history setup in the selected Mac user session."});else results.push({source,state:"permission-required",next:"Check this source\u2019s OS access and existing local permission. Other configured sources are retained."})}return{sources:results,reloadRequired:results.some(row=>row.state==="configured")}}const supported=new Set(["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","local-audio","obsidian","logseq","computer-files"]);function validSelection(value){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))return false;const keys=Reflect.ownKeys(value);if(keys.length!==2||keys.some(key=>typeof key!=="string"||!["source","roots"].includes(key)||!Object.getOwnPropertyDescriptor(value,key)?.enumerable||!("value"in Object.getOwnPropertyDescriptor(value,key))))return false;if((value.source==="visual-studio"||value.source==="modelsim"||value.source==="quartus"||value.source==="simulink"||value.source==="jianying"||value.source==="epic-games-launcher"||value.source==="ryujinx"||value.source==="modrinth"||value.source==="powerpoint"||value.source==="ti-ccs"||value.source==="pscad"||value.source==="adobe-photoshop"||value.source==="autocad"||value.source==="microsoft-word"||value.source==="microsoft-excel"||value.source==="local-git"||value.source==="vscode-local-history"||value.source==="libreoffice"||value.source==="adobe-acrobat"||value.source==="adobe-camera-raw"||value.source==="adobe-media-encoder"||value.source==="ansys-electronics-desktop"||value.source==="adobe-premiere-pro"||value.source==="packet-tracer"||value.source==="qt-designer"||value.source==="hearthstone-deck-tracker"||value.source==="visio"||value.source==="matlab"||value.source==="adobe-illustrator"||value.source==="minecraft-java"||value.source==="ni-tdms"||value.source==="jupyter")&&value.roots?.length!==1)return false;if(!supported.has(value.source)||!Array.isArray(value.roots)||value.roots.length<1||value.roots.length>16||Object.keys(value.roots).length!==value.roots.length)return false;return value.roots.every((root,index)=>{const d=Object.getOwnPropertyDescriptor(value.roots,String(index));return!!d?.enumerable&&"value"in d&&typeof root==="string"&&root===root.trim()&&root.length<=4096&&!/[\u0000-\u001f\u007f-\u009f]/u.test(root)&&isAbsolute(root)})&&new Set(value.roots).size===value.roots.length}export async function configureNativeFileLevel1(ctx,input,deps={}){if(!validSelection(input))throw Error("Invalid native file source selection.");const{source}=input;const base={source,reloadRequired:false};let native;try{native=await(deps.principal??currentNativePrincipal)();if(!native.issuer||!native.subject||!isAbsolute(native.home))throw Error()}catch{return{...base,state:"unavailable",next:"Run setup in the signed-in desktop session."}}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 before selecting folders."};const roots=[];try{for(const chosen of input.roots){const root=await realpath(chosen),stat=await lstat(root);if(!stat.isDirectory()||native.uid!==void 0&&stat.uid!==native.uid)throw Error("The selected directory is not available to the native user.");roots.push(root)}roots.sort();if(new Set(roots).size!==roots.length)throw Error("Selected directories resolve to the same location.")}catch{return{...base,state:"configuration-required",next:"The selected folder must exist and be accessible to the signed-in user; choose a valid folder."}}try{const setupConfig=config;await updateLevel1Configuration(config.provisioningFile,async current=>{const saved=current??(await prepareLevel1Configuration(vault,{},setupConfig.runtimeDirectory?{runtimeDirectory:setupConfig.runtimeDirectory}:{})).configuration;const audience=preparedLocalRootsAudience(source,roots),scope="files.read";const permission=await saveNativePermission(vault,source,native,audience,scope);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]:{...source==="logseq"?{mode:"files"}:{},roots,resourceId:permission.resourceId,issuer:permission.issuer,audience,requiredScopes:[scope]}}},value:void 0}});const enabled=!entry.disabled&&(config.sources===void 0||config.sources.includes(source));return{source,state:"configured",enabled,reloadRequired:true,next:enabled?"Reload the Level1 plugin to register this source, then connect it.":"The selection was saved; the existing disabled or explicit source setting still applies."}}catch{return{...base,state:"permission-required",next:"Check the selected folders, Vault permission and Level1 settings; no unrelated source was enabled."}}}
1
+ import{currentNativePrincipal,readNativeUserFileRoots,saveNativeReadPermission as saveNativePermission}from"@zortexhq/plugin-connector-core/api";export{currentNativePrincipal}from"@zortexhq/plugin-connector-core/api";import{interpolate}from"@deepseek-ai/cordis-plugin-loader";import{prepareMacAptOptions,preparedLocalRootsAudience,preparedLocalNativeSelection,prepareLevel1Configuration,updateLevel1Configuration}from"@zortexhq/plugin-connector-level1";import{historyReadAudience}from"@zortexhq/plugin-connector-history";import{activityWatchReadAudience,defaultActivityWatchUrl}from"@zortexhq/plugin-connector-activitywatch";import{defaultComputerFileRoots}from"@zortexhq/plugin-connector-computer-files";import{lstat,readdir,realpath,readFile}from"node:fs/promises";import{join,isAbsolute}from"node:path";import{request}from"node:http";import{isDeepStrictEqual}from"node:util";import{zoteroServerId}from"./zotero-level1-setup.js";import{NATIVE_AUTO_CONNECT_SOURCES}from"./native-connect.js";const fileSources=["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","obsidian","local-audio","computer-files"];const fixedWindowsSources=["windows-event-viewer","windows-task-scheduler","wsl"];const fixedWindowsSource=source=>fixedWindowsSources.some(id=>id===source);const serviceSources=[...fixedWindowsSources,"docker-desktop","ollama","owntracks","wechat","copyq","zotero","imessage","macos-contacts"];const fileSource=source=>fileSources.includes(source);const serviceSource=source=>serviceSources.includes(source);const defaults=[...NATIVE_AUTO_CONNECT_SOURCES];const sources=[...defaults,"mac-apt",...fileSources,...serviceSources];const modules={"google-chrome":"@zortexhq/plugin-connector-history/chrome","microsoft-edge":"@zortexhq/plugin-connector-history/edge",activitywatch:"@zortexhq/plugin-connector-activitywatch","mac-apt":"@zortexhq/plugin-connector-level1","visual-studio":"@zortexhq/plugin-connector-level1",modelsim:"@zortexhq/plugin-connector-level1",quartus:"@zortexhq/plugin-connector-level1",simulink:"@zortexhq/plugin-connector-level1",jianying:"@zortexhq/plugin-connector-level1","epic-games-launcher":"@zortexhq/plugin-connector-level1",ryujinx:"@zortexhq/plugin-connector-level1",modrinth:"@zortexhq/plugin-connector-level1",powerpoint:"@zortexhq/plugin-connector-level1","ti-ccs":"@zortexhq/plugin-connector-level1",pscad:"@zortexhq/plugin-connector-level1","adobe-photoshop":"@zortexhq/plugin-connector-level1",autocad:"@zortexhq/plugin-connector-level1","microsoft-word":"@zortexhq/plugin-connector-level1","microsoft-excel":"@zortexhq/plugin-connector-level1","local-git":"@zortexhq/plugin-connector-level1","vscode-local-history":"@zortexhq/plugin-connector-level1","libreoffice":"@zortexhq/plugin-connector-level1","adobe-acrobat":"@zortexhq/plugin-connector-level1","adobe-camera-raw":"@zortexhq/plugin-connector-level1","adobe-media-encoder":"@zortexhq/plugin-connector-level1","ansys-electronics-desktop":"@zortexhq/plugin-connector-level1","adobe-premiere-pro":"@zortexhq/plugin-connector-level1","packet-tracer":"@zortexhq/plugin-connector-level1","qt-designer":"@zortexhq/plugin-connector-level1","hearthstone-deck-tracker":"@zortexhq/plugin-connector-level1",visio:"@zortexhq/plugin-connector-level1",matlab:"@zortexhq/plugin-connector-level1","adobe-illustrator":"@zortexhq/plugin-connector-level1","minecraft-java":"@zortexhq/plugin-connector-level1","ni-tdms":"@zortexhq/plugin-connector-level1",jupyter:"@zortexhq/plugin-connector-level1",solidworks:"@zortexhq/plugin-connector-level1",lattics:"@zortexhq/plugin-connector-level1",jetbrains:"@zortexhq/plugin-connector-level1",eclipse:"@zortexhq/plugin-connector-level1",multisim:"@zortexhq/plugin-connector-level1",stm32cubemx:"@zortexhq/plugin-connector-level1",plecs:"@zortexhq/plugin-connector-level1",obsidian:"@zortexhq/plugin-connector-level1","local-audio":"@zortexhq/plugin-connector-level1","computer-files":"@zortexhq/plugin-connector-level1","windows-event-viewer":"@zortexhq/plugin-connector-level1","windows-task-scheduler":"@zortexhq/plugin-connector-level1","wsl":"@zortexhq/plugin-connector-level1","docker-desktop":"@zortexhq/plugin-connector-level1",ollama:"@zortexhq/plugin-connector-level1",owntracks:"@zortexhq/plugin-connector-level1",wechat:"@zortexhq/plugin-connector-level1",copyq:"@zortexhq/plugin-connector-level1",zotero:"@zortexhq/plugin-connector-level1",imessage:"@zortexhq/plugin-connector-level1","macos-contacts":"@zortexhq/plugin-connector-level1"};const validText=(value,max=512)=>typeof value==="string"&&!!value&&value===value.trim()&&value.length<=max&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value);export function readNativeActivityMetadata(base,path,signal){const origin=new URL(base);if(origin.protocol!=="http:"||!["127.0.0.1","[::1]"].includes(origin.hostname)||origin.port==="0"||origin.pathname!=="/"||origin.search||origin.hash||origin.username||origin.password||!["/api/0/info","/api/0/buckets/"].includes(path))throw Error("Invalid local ActivityWatch selection.");return new Promise((resolve,reject)=>{const req=request(new URL(path,origin),{method:"GET",agent:false,...signal?{signal}:{},headers:{accept:"application/json"}},res=>{if(res.statusCode!==200){res.resume();reject(Object.assign(Error("ActivityWatch metadata needs local access or authorization."),{code:res.statusCode===401||res.statusCode===403?"permission_denied":"LOCAL_SERVICE_UNAVAILABLE"}));return}let bytes=0;const chunks=[];res.on("data",chunk=>{bytes+=chunk.length;if(bytes>1048576){req.destroy(Error("ActivityWatch metadata exceeds its bound."));return}chunks.push(chunk)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")))}catch{reject(Error("Invalid ActivityWatch metadata."))}});res.on("error",reject);res.on("aborted",()=>reject(Object.assign(Error("ActivityWatch metadata was interrupted."),{code:"ECONNRESET"})))});const timeout=setTimeout(()=>req.destroy(Object.assign(Error("ActivityWatch metadata timed out."),{code:"ETIMEDOUT"})),5e3);req.on("close",()=>clearTimeout(timeout));req.on("error",reject);req.end()})}function plain(value,keys){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error("Invalid native source options.");for(const key of Reflect.ownKeys(value)){const descriptor=Object.getOwnPropertyDescriptor(value,key);if(typeof key!=="string"||!keys.includes(key)||!descriptor.enumerable||!("value"in descriptor))throw Error("Invalid native source options.")}}const validBuckets=value=>Array.isArray(value)&&value.length>0&&value.length<=32&&Object.keys(value).length===value.length&&new Set(value).size===value.length&&value.every(id=>validText(id,480)&&id!=="."&&id!==".."&&!/[\/\\]/u.test(id));function validRoots(value){if(!Array.isArray(value)||value.length<1||value.length>16||Object.keys(value).length!==value.length)return false;const roots=[];for(let index=0;index<value.length;index++){const item=Object.getOwnPropertyDescriptor(value,String(index));if(!item?.enumerable||!("value"in item)||!validText(item.value,4096)||!isAbsolute(item.value))return false;roots.push(item.value)}return new Set(roots).size===roots.length}function validateSelection(value){plain(value,["sources","options"]);if(value.sources!==void 0&&(!Array.isArray(value.sources)||Object.keys(value.sources).length!==value.sources.length||new Set(value.sources).size!==value.sources.length||value.sources.some(source=>!sources.includes(source))))throw Error("Invalid native source selection.");if(value.options!==void 0){plain(value.options,sources);for(const[source,options]of Object.entries(value.options)){plain(options,source==="mac-apt"?["pythonExecutable","packageDirectory","artifacts"]:fileSource(source)?["roots"]:serviceSource(source)?source==="docker-desktop"||fixedWindowsSource(source)?[]:source==="ollama"||source==="owntracks"||source==="wechat"?["port"]:source==="copyq"?["executable","session"]:source==="zotero"?["libraryId","libraryType"]:["executable"]:source==="activitywatch"?["baseUrl","bucketIds"]:["root","profile"]);if(fileSource(source)){if(source==="jianying"&&(!Array.isArray(options.roots)||options.roots.length!==1))throw Error("Choose one Jianying draft folder.");if(source==="simulink"&&(!Array.isArray(options.roots)||options.roots.length!==1))throw Error("Choose one Simulink model folder.");if((source==="visual-studio"||source==="modelsim"||source==="quartus"||source==="epic-games-launcher"||source==="ryujinx"||source==="modrinth"||source==="powerpoint"||source==="ti-ccs"||source==="pscad"||source==="adobe-photoshop"||source==="autocad"||source==="microsoft-word"||source==="microsoft-excel"||source==="local-git"||source==="vscode-local-history"||source==="libreoffice"||source==="adobe-acrobat"||source==="adobe-camera-raw"||source==="adobe-media-encoder"||source==="ansys-electronics-desktop"||source==="adobe-premiere-pro"||source==="packet-tracer"||source==="qt-designer"||source==="hearthstone-deck-tracker"||source==="visio"||source==="matlab"||source==="adobe-illustrator"||source==="minecraft-java"||source==="ni-tdms"||source==="jupyter")&&(!Array.isArray(options.roots)||options.roots.length!==1))throw Error("Choose one source folder.");if(options.roots!==void 0&&!validRoots(options.roots))throw Error("Invalid native file root selection.");continue}if(serviceSource(source)){if(options.port!==void 0&&(!Number.isInteger(options.port)||options.port<1024||options.port>65535)||options.executable!==void 0&&(!validText(options.executable,4096)||!isAbsolute(options.executable))||options.session!==void 0&&(typeof options.session!=="string"||!/^[\p{L}\p{N}_-]{0,16}$/u.test(options.session))||options.libraryId!==void 0&&(typeof options.libraryId!=="string"||!(/^[1-9][0-9]{0,19}$/u.test(options.libraryId)||options.libraryId==="0"&&options.libraryType==="user"))||options.libraryType!==void 0&&!["user","group"].includes(options.libraryType))throw Error("Invalid native service selection.");continue}if(source==="mac-apt"){for(const key of["pythonExecutable","packageDirectory"])if(options[key]!==void 0&&(!validText(options[key],4096)||!isAbsolute(options[key])))throw Error("Invalid native source options.");if(options.artifacts!==void 0){if(!Array.isArray(options.artifacts)||options.artifacts.length<1||options.artifacts.length>16)throw Error("Invalid native source options.");for(const item of options.artifacts){plain(item,["id","kind","path"]);if(!validText(item.id,64)||!["recent-places","install-history","dock-items"].includes(item.kind)||!validText(item.path,4096)||!isAbsolute(item.path))throw Error("Invalid native source options.")}}continue}if(options.root!==void 0&&(!validText(options.root,4096)||!isAbsolute(options.root))||options.profile!==void 0&&(!validText(options.profile,64)||!/^(Default|Profile \d{1,8})$/u.test(options.profile))||options.bucketIds!==void 0&&!validBuckets(options.bucketIds))throw Error("Invalid native source options.");if(options.baseUrl!==void 0){if(!validText(options.baseUrl,512))throw Error("Invalid native source options.");activityWatchReadAudience(options.baseUrl,"validation",["validation"])}}}}export async function readNativeLevel1Selection(file){if(!isAbsolute(file))throw Error("Native setup requires an absolute options file.");const stat=await lstat(file);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>1048576)throw Error("Invalid native source options file.");const raw=await readFile(file,"utf8");if(Buffer.byteLength(raw)>1048576)throw Error("Invalid native source options file.");const value=JSON.parse(raw);validateSelection(value);return value}export async function configureNativeLevel1(ctx,input={},deps={}){validateSelection(input);const selected=input.sources??(input.options?.["mac-apt"]?[...defaults,"mac-apt"]:defaults),results=[];if(!selected.length||deps.signal?.aborted)return{sources:[],reloadRequired:false};let native;try{native=await(deps.principal??currentNativePrincipal)();if(!validText(native.issuer)||!validText(native.subject)||!validText(native.hostname)||!isAbsolute(native.home))throw Error()}catch{return{sources:selected.map(source=>({source,state:"unavailable",next:"Run native setup in the signed-in desktop session; its OS identity could not be verified."})),reloadRequired:false}}const loader=ctx.get("loader"),vault=ctx.get("zortexVaultStore");if(!loader||!vault)throw Error("Native setup requires the installed product loader and Vault.");for(const source of selected)try{if(deps.signal?.aborted)break;const entries=[...loader.entries()].filter(row=>row.options.publicModule===modules[source]||row.options.name===modules[source]);if(entries.length!==1){results.push({source,state:"unavailable",next:"Load the installed source plugin once before native setup."});continue}const entry=entries[0],options=input.options?.[source]??{};if(deps.automatic&&entry.disabled){results.push({source,state:"unavailable",enabled:false,next:"This connector is turned off. Enable it in Apps to resume automatic connection."});continue}const effective=entry.fiber?.config??interpolate(entry.context,entry.options.config);const existing=effective;let configuration,audience,scope;if(source==="mac-apt"||fileSource(source)||serviceSource(source)){const config=effective;if((source==="imessage"||source==="macos-contacts")&&process.platform!=="darwin"){results.push({source,state:"unavailable",next:"Run this source\u2019s native setup in the selected Mac user session with its installed Apple bridge and OS access."});continue}if(source==="mac-apt"&&(!options.pythonExecutable||!options.packageDirectory||!options.artifacts)){results.push({source,state:"configuration-required",next:'Install the pinned mac_apt runtime and supply its interpreter, package directory and selected artifact paths in options["mac-apt"].'});continue}if(fileSource(source)&&!options.roots&&!(source==="computer-files"&&deps.automatic)){results.push({source,state:"selection-required",next:"Choose the folders this app may read in options[source].roots, then run native setup again."});continue}if(fixedWindowsSource(source)&&process.platform!=="win32"){results.push({source,state:"unavailable",next:"Run this native metadata reader in the signed-in Windows session."});continue}if(source==="docker-desktop"&&process.platform!=="win32"){results.push({source,state:"unavailable",next:"Select the local Windows Docker Desktop Linux engine."});continue}if(serviceSource(source)&&!fixedWindowsSource(source)&&source!=="docker-desktop"&&(source==="ollama"||source==="owntracks"||source==="wechat"?options.port===void 0:source==="copyq"?!options.executable||options.session===void 0:source==="zotero"?!options.libraryId||options.libraryType===void 0:!options.executable)){results.push({source,state:"selection-required",next:source==="ollama"?"Select the port of your existing local Ollama server.":source==="owntracks"?"Choose the existing local OwnTracks MCP port in options.owntracks.port.":source==="wechat"?"Choose the existing local WeChat chatlog MCP port in options.wechat.port.":source==="copyq"?"Select the installed CopyQ executable and session in options.copyq; an empty session explicitly selects its default session.":source==="zotero"?"Select the local Zotero libraryId and libraryType (user or group) in options.zotero.":"Select the installed Apple bridge executable in options[source].executable."});continue}if(!config?.provisioningFile||!isAbsolute(config.provisioningFile)){results.push({source,state:"configuration-required",next:"Load the installed Level1 setup file before configuring this native source."});continue}if(source==="computer-files"&&deps.automatic){const resident=ctx.get("zortexLevel1Connectors");if(config.sources!==void 0){const enabled=config.sources.includes(source);results.push({source,state:enabled&&resident?.provider(source)?"configured":enabled?"configuration-required":"unavailable",enabled,next:enabled?"The existing Computer Files selection remains authoritative.":"Computer Files is turned off in the existing source selection."});continue}let refusal;const unchanged=Error("Native file folders are already prepared.");try{await updateLevel1Configuration(config.provisioningFile,async current=>{const desired=current?.requestedSources??current?.sources;if(desired&&!desired.includes(source)){refusal={source,state:"unavailable",enabled:false,next:"Computer Files is turned off in the existing source selection."};throw Error("Source is not selected.")}const prior=current?.prepared?.[source];if(prior&&!validRoots(prior.roots)){refusal={source,state:"configuration-required",next:"The saved Computer Files folders need repair. Select the intended folders in Apps."};throw Error("Saved roots are invalid.")}let chosen=options.roots??prior?.roots;if(!chosen){const bindings=await vault.bindingCustody.bindings(source);if(!("ok"in bindings)||bindings.ok.length){refusal={source,state:"permission-required",next:"Computer Files has previous local permission but no saved folders. Restore the folder selection in Apps."};throw Error("Previous permission must remain authoritative.")}chosen=[];const nativeHome=await realpath(native.home);const defaults2=await(deps.fileRoots??readNativeUserFileRoots)(native,deps.signal?{signal:deps.signal}:{})??await defaultComputerFileRoots(native.home);for(const candidate of defaults2){try{const root=await realpath(candidate),metadata=await lstat(root);if(root!==nativeHome&&root!==join(root,"..")&&metadata.isDirectory()&&(native.uid===void 0||metadata.uid===native.uid)&&!chosen.includes(root))chosen.push(root)}catch{}}if(!chosen.length){refusal={source,state:"selection-required",next:"No accessible Documents, Desktop or Downloads folder was found. Choose the folders Computer Files may read in Apps."};throw Error("No useful default folders.")}}const roots=[];for(const selected3 of chosen){const root=await realpath(selected3),metadata=await lstat(root);if(!metadata.isDirectory()||native.uid!==void 0&&metadata.uid!==native.uid)throw Error("Selected folder is not available to this native user.");roots.push(root)}roots.sort();if(deps.signal?.aborted)throw Error("Native setup was cancelled.");const audience2=preparedLocalRootsAudience(source,roots),scope2="files.read";const permission=await saveNativePermission(vault,source,native,audience2,scope2);if(deps.signal?.aborted)throw Error("Native setup was cancelled.");const saved=current??(await prepareLevel1Configuration(vault,{},config.runtimeDirectory?{runtimeDirectory:config.runtimeDirectory}:{})).configuration;const selected2=[...new Set([...saved.sources??[],source])],requested=[...new Set([...saved.requestedSources??saved.sources??[],...selected2])];const configuration2={...saved,sources:selected2,requestedSources:requested,prepared:{...saved.prepared,[source]:{roots,resourceId:permission.resourceId,issuer:permission.issuer,audience:audience2,requiredScopes:[scope2]}}};if(isDeepStrictEqual(current,configuration2))throw unchanged;return{configuration:configuration2,value:void 0}},deps.signal?{signal:deps.signal}:{})}catch(error){if(refusal){results.push(refusal);continue}if(error!==unchanged)throw error}if(deps.signal?.aborted)break;const activated=await resident?.activate(source);results.push(activated?.status==="activated"?{source,state:"configured",enabled:true}:{source,state:"configuration-required",enabled:true,next:"The selected Computer Files folders were saved. Restart Indra to activate this changed source."});continue}let prepared;if(source==="mac-apt")prepared={...await(deps.macApt??prepareMacAptOptions)(vault,{pythonExecutable:options.pythonExecutable,packageDirectory:options.packageDirectory,artifacts:options.artifacts})};else if(serviceSource(source)){let selection;try{const selectedOptions=source==="zotero"?{...options,serverId:await zoteroServerId()}:options;selection=preparedLocalNativeSelection(source,selectedOptions)}catch{results.push({source,state:"configuration-required",next:source==="zotero"?"Start Zotero 10 or later with the local API enabled and retry.":"Check this source\u2019s selected runtime, endpoint, session or library options, then run native setup again."});continue}const permission=await saveNativePermission(vault,source,native,selection.audience,selection.scope);prepared={...selection.options,resourceId:permission.resourceId,issuer:permission.issuer,audience:selection.audience,requiredScopes:[selection.scope]}}else{const roots=[];for(const chosen of options.roots){const root=await realpath(chosen),stat=await lstat(root);if(!stat.isDirectory()||native.uid!==void 0&&stat.uid!==native.uid)throw Error("Selected root is not owned by this native user.");roots.push(root)}roots.sort();const audience2=preparedLocalRootsAudience(source,roots),scope2="files.read";const permission=await saveNativePermission(vault,source,native,audience2,scope2);prepared={roots,resourceId:permission.resourceId,issuer:permission.issuer,audience:audience2,requiredScopes:[scope2]}}await updateLevel1Configuration(config.provisioningFile,async current=>{const saved=current??(await prepareLevel1Configuration(vault,{},config.runtimeDirectory?{runtimeDirectory:config.runtimeDirectory}:{})).configuration;const selected2=[...new Set([...saved.sources??[],source])],requested=[...new Set([...saved.requestedSources??saved.sources??[],...selected2])];return{configuration:{...saved,sources:selected2,requestedSources:requested,prepared:{...saved.prepared,[source]:prepared}},value:void 0}});results.push({source,state:"configured",enabled:!entry.disabled&&(config.sources===void 0||config.sources.includes(source))});continue}if(source!=="activitywatch"){const vendor=source==="google-chrome"?"Google/Chrome":"Microsoft/Edge";const fallback=process.platform==="win32"?join(native.localAppData??native.home,vendor,"User Data"):process.platform==="darwin"?join(native.home,"Library/Application Support",vendor):join(native.home,".config",source==="google-chrome"?"google-chrome":"microsoft-edge");const chosen=options.root??existing?.root??fallback;if(!isAbsolute(chosen))throw Error("Select an absolute browser root.");const root=await realpath(chosen),rootStat=await lstat(root);if(!rootStat.isDirectory()||native.uid!==void 0&&rootStat.uid!==native.uid)throw Error("Selected browser root is not owned by this native user.");const candidates=(await readdir(root,{withFileTypes:true})).filter(row=>row.isDirectory()&&/^(Default|Profile \d{1,8})$/u.test(row.name)).map(row=>row.name).sort();const profiles=[];for(const profile2 of candidates.slice(0,64)){const file=await lstat(join(root,profile2,"History")).catch(()=>void 0);if(file?.isFile()&&!file.isSymbolicLink()&&(native.uid===void 0||file.uid===native.uid))profiles.push(profile2)}const profile=options.profile??(existing?.root===root?existing.profile:void 0)??profiles[0];if(!profile||!profiles.includes(profile)){results.push({source,state:"selection-required",profiles,next:"Choose one listed browser profile in options[source].profile and run native setup again."});continue}audience=historyReadAudience(source,root,profile);scope="history.read";configuration={root,profile}}else{const baseUrl=options.baseUrl??existing?.baseUrl??defaultActivityWatchUrl,metadata=deps.metadata??readNativeActivityMetadata;const info=await metadata(baseUrl,"/api/0/info",deps.signal);if(deps.signal?.aborted)break;if(!info||!validText(info.device_id)||typeof info.hostname!=="string")throw Error("ActivityWatch did not identify its native device.");let bucketIds=options.bucketIds??(existing?.baseUrl===baseUrl?existing.bucketIds:void 0);if(!bucketIds){const raw=await metadata(baseUrl,"/api/0/buckets/",deps.signal);if(deps.signal?.aborted)break;if(!raw||typeof raw!=="object"||Array.isArray(raw))throw Error("ActivityWatch bucket metadata is unavailable.");const local=Object.entries(raw).filter(([id,bucket])=>validText(id,480)&&id!=="."&&id!==".."&&!/[\/\\]/u.test(id)&&bucket&&typeof bucket==="object"&&bucket.hostname===native.hostname).map(([id])=>id).sort();if(!local.length||local.length>32){results.push({source,state:"selection-required",bucketIds:local.slice(0,32),...!local.length?{retryable:true}:{},next:!local.length?"ActivityWatch is running but has no buckets for this computer. Start its local watchers; Indra will retry automatically.":"Choose this computer\u2019s ActivityWatch buckets in options.activitywatch.bucketIds."});continue}bucketIds=local}audience=activityWatchReadAudience(baseUrl,info.device_id,bucketIds);scope="local-activity.read";configuration={baseUrl,deviceId:info.device_id,bucketIds,...existing?.apiKeyResourceId?{apiKeyResourceId:existing.apiKeyResourceId}:{}}}if(deps.signal?.aborted)break;const authority=await saveNativePermission(vault,source,native,audience,scope);if(deps.signal?.aborted)break;await loader.update(entry.id,{config:{...configuration,authority}});await loader.await();results.push({source,state:"configured",enabled:!entry.disabled})}catch(error){if(deps.signal?.aborted)break;const nativeCode=error&&typeof error==="object"&&"code"in error?String(error.code):void 0;if(source==="activitywatch"&&["ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ETIMEDOUT","LOCAL_SERVICE_UNAVAILABLE"].includes(nativeCode??"")){results.push({source,state:"unavailable",retryable:true,next:"ActivityWatch is not answering on this computer. Start or repair its local service; Indra will retry automatically. Connect checks again immediately."});continue}const code=source==="mac-apt"&&error&&typeof error==="object"&&"code"in error?error.code:void 0;if(code==="failed_precondition")results.push({source,state:"configuration-required",next:"Check the pinned mac_apt interpreter, dependencies and selected artifact paths, then run native setup again."});else if(code==="unavailable")results.push({source,state:"unavailable",next:"Run Mac history setup in the selected Mac user session."});else results.push({source,state:"permission-required",next:"Check this source\u2019s OS access and existing local permission. Other configured sources are retained."})}return{sources:results,reloadRequired:results.some(row=>row.state==="configured")}}const supported=new Set(["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","local-audio","obsidian","logseq","computer-files"]);function validSelection(value){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))return false;const keys=Reflect.ownKeys(value);if(keys.length!==2||keys.some(key=>typeof key!=="string"||!["source","roots"].includes(key)||!Object.getOwnPropertyDescriptor(value,key)?.enumerable||!("value"in Object.getOwnPropertyDescriptor(value,key))))return false;if((value.source==="visual-studio"||value.source==="modelsim"||value.source==="quartus"||value.source==="simulink"||value.source==="jianying"||value.source==="epic-games-launcher"||value.source==="ryujinx"||value.source==="modrinth"||value.source==="powerpoint"||value.source==="ti-ccs"||value.source==="pscad"||value.source==="adobe-photoshop"||value.source==="autocad"||value.source==="microsoft-word"||value.source==="microsoft-excel"||value.source==="local-git"||value.source==="vscode-local-history"||value.source==="libreoffice"||value.source==="adobe-acrobat"||value.source==="adobe-camera-raw"||value.source==="adobe-media-encoder"||value.source==="ansys-electronics-desktop"||value.source==="adobe-premiere-pro"||value.source==="packet-tracer"||value.source==="qt-designer"||value.source==="hearthstone-deck-tracker"||value.source==="visio"||value.source==="matlab"||value.source==="adobe-illustrator"||value.source==="minecraft-java"||value.source==="ni-tdms"||value.source==="jupyter")&&value.roots?.length!==1)return false;if(!supported.has(value.source)||!Array.isArray(value.roots)||value.roots.length<1||value.roots.length>16||Object.keys(value.roots).length!==value.roots.length)return false;return value.roots.every((root,index)=>{const d=Object.getOwnPropertyDescriptor(value.roots,String(index));return!!d?.enumerable&&"value"in d&&typeof root==="string"&&root===root.trim()&&root.length<=4096&&!/[\u0000-\u001f\u007f-\u009f]/u.test(root)&&isAbsolute(root)})&&new Set(value.roots).size===value.roots.length}export async function configureNativeFileLevel1(ctx,input,deps={}){if(!validSelection(input))throw Error("Invalid native file source selection.");const{source}=input;const base={source,reloadRequired:false};let native;try{native=await(deps.principal??currentNativePrincipal)();if(!native.issuer||!native.subject||!isAbsolute(native.home))throw Error()}catch{return{...base,state:"unavailable",next:"Run setup in the signed-in desktop session."}}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 before selecting folders."};const roots=[];try{for(const chosen of input.roots){const root=await realpath(chosen),stat=await lstat(root);if(!stat.isDirectory()||native.uid!==void 0&&stat.uid!==native.uid)throw Error("The selected directory is not available to the native user.");roots.push(root)}roots.sort();if(new Set(roots).size!==roots.length)throw Error("Selected directories resolve to the same location.")}catch{return{...base,state:"configuration-required",next:"The selected folder must exist and be accessible to the signed-in user; choose a valid folder."}}try{const setupConfig=config;await updateLevel1Configuration(config.provisioningFile,async current=>{const saved=current??(await prepareLevel1Configuration(vault,{},setupConfig.runtimeDirectory?{runtimeDirectory:setupConfig.runtimeDirectory}:{})).configuration;const audience=preparedLocalRootsAudience(source,roots),scope="files.read";const permission=await saveNativePermission(vault,source,native,audience,scope);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]:{...source==="logseq"?{mode:"files"}:{},roots,resourceId:permission.resourceId,issuer:permission.issuer,audience,requiredScopes:[scope]}}},value:void 0}});const enabled=!entry.disabled&&(config.sources===void 0||config.sources.includes(source));return{source,state:"configured",enabled,reloadRequired:true,next:enabled?"Reload the Level1 plugin to register this source, then connect it.":"The selection was saved; the existing disabled or explicit source setting still applies."}}catch{return{...base,state:"permission-required",next:"Check the selected folders, Vault permission and Level1 settings; no unrelated source was enabled."}}}
@@ -1 +1 @@
1
- import{createHash,randomUUID}from"node:crypto";import{businessError}from"@zortexhq/plugin-connector-framework/api";import{callUpdateTool}from"./update-tool.js";const intents=["ensure_ready","find","act","status","guide","update"];const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const exact=(value,allowed)=>Object.keys(value).every(key=>allowed.includes(key));const invalid=message=>businessError("invalid_argument",message,"plugin");const refused=message=>businessError("failed_precondition",message,"plugin");function canonical(value){if(value===null||typeof value!=="object")return JSON.stringify(value);if(Array.isArray(value))return"["+value.map(canonical).join(",")+"]";return"{"+Object.keys(value).sort().map(key=>JSON.stringify(key)+":"+canonical(value[key])).join(",")+"}"}const digest=value=>createHash("sha256").update(canonical(value)).digest("hex");export function publicIntentOperation(value){if(!object(value)||typeof value.intent!=="string")return;if(["ensure_ready","find","act"].includes(value.intent))return"action";if(value.intent==="status")return"manage";if(value.intent==="guide")return object(value.input)&&value.input.kind==="handbook"?"handbook":"instruction";if(value.intent==="update")return"update"}export const publicTool={name:"zortex",description:"The single ordinary Zortex entry. Use ensure_ready to make one source usable, find for bounded user-content retrieval, act for a reviewed write or other explicit product action, status for product state, guide for installed guidance, and update for the local release. act always returns a parameter-bound confirmation token before any effect; repeat the same request with that token to execute once. Raw SQL, action catalogs, provider reads and diagnostics are available only through explicit non-ordinary profiles.",inputSchema:{type:"object",properties:{intent:{type:"string",enum:[...intents]},input:{type:"object",description:"Intent-specific object. Keep source and query bounded; act uses {name,params}."},confirmationToken:{type:"string",description:"For act only: the opaque token returned by the matching confirmation_required preview."}},required:["intent"],additionalProperties:false},annotations:{readOnlyHint:false,destructiveHint:true,openWorldHint:true,idempotentHint:false}};export function createPublicToolRouter(options){const now=options.now??Date.now,makeToken=options.token??randomUUID,ttl=options.ttlMs??15*6e4,maxConfirmations=options.maxConfirmations??512;const confirmations=new Map,tokensByDigest=new Map;const clean=()=>{const at=now();for(const[token,row]of confirmations)if(row.expiresAt<=at&&!row.execution){confirmations.delete(token);if(tokensByDigest.get(row.digest)===token)tokensByDigest.delete(row.digest)}};const agent=(operation,args,signal)=>options.gateway.call(operation,args,{...signal?{signal}:{},surface:"agent"});return{async call(value,signal){clean();if(!object(value)||!exact(value,["intent","input","confirmationToken"])||typeof value.intent!=="string"||!intents.includes(value.intent)||value.input!==void 0&&!object(value.input)||value.confirmationToken!==void 0&&typeof value.confirmationToken!=="string")return invalid("Pass one supported intent, an optional input object and an act confirmationToken only when executing its preview.");const envelope=value,input=envelope.input??{};if(envelope.intent!=="act"&&envelope.confirmationToken!==void 0)return invalid("confirmationToken is accepted only for act.");if(envelope.intent==="ensure_ready")return agent("action",{name:"connector.ensure-ready",params:input},signal);if(envelope.intent==="find")return agent("action",{name:"connector.find",params:input},signal);if(envelope.intent==="status"){const statusInput=Object.keys(input).length?input:{what:"status"};if(!exact(statusInput,["what","about"])||!["status","sources","onboarding","startup"].includes(String(statusInput.what))||statusInput.about!==void 0&&typeof statusInput.about!=="string")return invalid("status accepts what status, sources, onboarding or startup and an optional source filter.");return agent("manage",statusInput,signal)}if(envelope.intent==="guide"){if(!exact(input,["kind"])||input.kind!==void 0&&!["instruction","handbook"].includes(String(input.kind)))return invalid("guide accepts kind instruction or handbook.");return agent(input.kind==="handbook"?"handbook":"instruction",{},signal)}if(envelope.intent==="update"){try{return await callUpdateTool(Object.keys(input).length?input:{operation:"check"},options.updater)}catch{return invalid("Run update check, then apply with its exact version and confirmationToken.")}}if(!exact(input,["name","params"])||typeof input.name!=="string"||!input.name||!object(input.params))return invalid("act input must be {name,params}.");const action={name:input.name,params:input.params},binding=digest({intent:"act",input:action});if(!envelope.confirmationToken){let token=tokensByDigest.get(binding),row2=token?confirmations.get(token):void 0;if(!token||!row2){if(confirmations.size>=maxConfirmations)return businessError("resource_exhausted","Too many action confirmations are retained in this MCP session. Finish or restart the session before staging another write.","plugin");do token=makeToken();while(confirmations.has(token));row2={digest:binding,expiresAt:now()+ttl};confirmations.set(token,row2);tokensByDigest.set(binding,token)}const source=typeof input.params.source==="string"?input.params.source:void 0,method=typeof input.params.method==="string"?input.params.method:void 0;return{ok:{state:"confirmation_required",confirmationToken:token,expiresAt:new Date(row2.expiresAt).toISOString(),action:{name:input.name,...source?{source}:{},...method?{method}:{},parameterKeys:Object.keys(input.params).sort()}}}}const row=confirmations.get(envelope.confirmationToken);if(!row||row.digest!==binding||row.expiresAt<=now()&&!row.execution)return refused("The action preview is missing, expired or does not match these parameters. Request a new preview.");row.execution??=agent("action",action,signal);return row.execution}}}
1
+ import{createHash,randomUUID}from"node:crypto";import{businessError}from"@zortexhq/plugin-connector-framework/api";import{callUpdateTool}from"./update-tool.js";export const createPublicConfirmationStore=()=>({confirmations:new Map,tokensByDigest:new Map});const intents=["ensure_ready","find","act","status","guide","update"];const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const exact=(value,allowed)=>Object.keys(value).every(key=>allowed.includes(key));const invalid=message=>businessError("invalid_argument",message,"plugin");const refused=message=>businessError("failed_precondition",message,"plugin");function canonical(value){if(value===null||typeof value!=="object")return JSON.stringify(value);if(Array.isArray(value))return"["+value.map(canonical).join(",")+"]";return"{"+Object.keys(value).sort().map(key=>JSON.stringify(key)+":"+canonical(value[key])).join(",")+"}"}const digest=value=>createHash("sha256").update(canonical(value)).digest("hex");export function publicIntentOperation(value){if(!object(value)||typeof value.intent!=="string")return;if(["ensure_ready","find","act"].includes(value.intent))return"action";if(value.intent==="status")return"manage";if(value.intent==="guide")return object(value.input)&&value.input.kind==="handbook"?"handbook":"instruction";if(value.intent==="update")return"update"}const sourceId={type:"string",pattern:"^[a-z][a-z0-9-]{0,63}$"};const branch=(intent,input,requiredInput=false,extra={})=>({type:"object",properties:{intent:{type:"string",const:intent},...input?{input}:{},...extra},required:["intent",...requiredInput?["input"]:[]],additionalProperties:false});export function createPublicTool(identities=[]){const connected=identities.length?` Current connected identities (authoritative for this session; do not infer another account): ${identities.map(row=>`${row.source}=${JSON.stringify(row.account)}`).join(", ")}.`:" No connected account identity is currently available in this session; use ensure_ready or status instead of guessing an account.";const schema={type:"object",oneOf:[branch("ensure_ready",{type:"object",properties:{source:{...sourceId,description:"Exact connector source to make ready."}},required:["source"],additionalProperties:false},true),branch("find",{type:"object",properties:{goal:{type:"string",minLength:1,maxLength:4096,description:"The user-level information goal. Zortex derives a bounded search plan and returns a server-generated conclusion, classified evidence and explicit coverage; do not write provider query syntax or infer beyond that coverage."},source:{...sourceId,description:"Optional exact connected source; aliases such as drive and calendar are normalized."},since:{type:"string",description:"Optional ISO timestamp lower bound."},until:{type:"string",description:"Optional ISO timestamp upper bound."},limit:{type:"integer",minimum:1,maximum:50,default:5},cursor:{type:"integer",minimum:0,default:0},freshness:{type:"string",enum:["auto","cached","live"],default:"auto"},snapshotToken:{type:"string",minLength:16,maxLength:200,pattern:"^[A-Za-z0-9_-]+$",description:"Reuse with nextCursor to page through the same committed local snapshot. Omit to start a new query."},continuationToken:{type:"string",minLength:16,maxLength:200,pattern:"^[A-Za-z0-9_-]+$",description:"Opaque token from a partial find result. Repeat the identical find input with this token at most once; never poll."}},required:["goal"],additionalProperties:false},true),branch("act",{type:"object",properties:{name:{type:"string",minLength:1},params:{type:"object"}},required:["name","params"],additionalProperties:false},true,{confirmationToken:{type:"string",description:"Opaque token returned by the identical confirmation_required preview."}}),branch("status",{type:"object",properties:{what:{type:"string",enum:["status","sources","onboarding","startup"],default:"status"},about:{...sourceId,description:"Optional exact source filter."}},additionalProperties:false}),branch("guide",{type:"object",properties:{kind:{type:"string",enum:["instruction","handbook"],default:"instruction"}},additionalProperties:false}),branch("update",{oneOf:[{type:"object",properties:{operation:{type:"string",const:"check"}},required:["operation"],additionalProperties:false},{type:"object",properties:{operation:{type:"string",const:"apply"},version:{type:"string",minLength:1},confirmationToken:{type:"string",minLength:1}},required:["operation","version","confirmationToken"],additionalProperties:false}]})]};return{name:"zortex",description:"The single ordinary Zortex entry. Select exactly one typed intent: ensure_ready makes one source usable; find retrieves bounded user content; act stages then executes an explicit reviewed action; status reads product state; guide reads installed guidance; update checks or applies the local release. When find returns partial with continuationToken, repeat the identical find once with that token, then answer from the returned conclusion and coverage; never poll. act always returns a parameter-bound confirmation token before any effect; repeat the same request with that token to execute once. Raw SQL, action catalogs, provider reads and diagnostics are available only through explicit non-ordinary profiles."+connected,inputSchema:schema,annotations:{readOnlyHint:false,destructiveHint:true,openWorldHint:true,idempotentHint:false}}}export const publicTool=createPublicTool();export function createPublicToolRouter(options){const now=options.now??Date.now,makeToken=options.token??randomUUID,ttl=options.ttlMs??15*6e4,maxConfirmations=options.maxConfirmations??512;const{confirmations,tokensByDigest}=options.confirmationStore??createPublicConfirmationStore();const clean=()=>{const at=now();for(const[token,row]of confirmations)if(row.expiresAt<=at&&!row.execution){confirmations.delete(token);if(tokensByDigest.get(row.digest)===token)tokensByDigest.delete(row.digest)}};const agent=(operation,args,signal)=>options.gateway.call(operation,args,{...signal?{signal}:{},surface:"agent"});return{async call(value,signal){clean();if(!object(value)||!exact(value,["intent","input","confirmationToken"])||typeof value.intent!=="string"||!intents.includes(value.intent)||value.input!==void 0&&!object(value.input)||value.confirmationToken!==void 0&&typeof value.confirmationToken!=="string")return invalid("Pass one supported intent, an optional input object and an act confirmationToken only when executing its preview.");const envelope=value,input=envelope.input??{};if(envelope.intent!=="act"&&envelope.confirmationToken!==void 0)return invalid("confirmationToken is accepted only for act.");if(envelope.intent==="ensure_ready")return agent("action",{name:"connector.ensure-ready",params:input},signal);if(envelope.intent==="find")return agent("action",{name:"connector.find",params:input},signal);if(envelope.intent==="status"){const statusInput=Object.keys(input).length?input:{what:"status"};if(!exact(statusInput,["what","about"])||!["status","sources","onboarding","startup"].includes(String(statusInput.what))||statusInput.about!==void 0&&typeof statusInput.about!=="string")return invalid("status accepts what status, sources, onboarding or startup and an optional source filter.");return agent("manage",statusInput,signal)}if(envelope.intent==="guide"){if(!exact(input,["kind"])||input.kind!==void 0&&!["instruction","handbook"].includes(String(input.kind)))return invalid("guide accepts kind instruction or handbook.");return agent(input.kind==="handbook"?"handbook":"instruction",{},signal)}if(envelope.intent==="update"){try{return await callUpdateTool(Object.keys(input).length?input:{operation:"check"},options.updater)}catch{return invalid("Run update check, then apply with its exact version and confirmationToken.")}}if(!exact(input,["name","params"])||typeof input.name!=="string"||!input.name||!object(input.params))return invalid("act input must be {name,params}.");const action={name:input.name,params:input.params},binding=digest({intent:"act",input:action});if(!envelope.confirmationToken){let token=tokensByDigest.get(binding),row2=token?confirmations.get(token):void 0;if(!token||!row2){if(confirmations.size>=maxConfirmations)return businessError("resource_exhausted","Too many action confirmations are retained in this MCP session. Finish or restart the session before staging another write.","plugin");do token=makeToken();while(confirmations.has(token));row2={digest:binding,expiresAt:now()+ttl};confirmations.set(token,row2);tokensByDigest.set(binding,token)}const source=typeof input.params.source==="string"?input.params.source:void 0,method=typeof input.params.method==="string"?input.params.method:void 0;return{ok:{state:"confirmation_required",confirmationToken:token,expiresAt:new Date(row2.expiresAt).toISOString(),action:{name:input.name,...source?{source}:{},...method?{method}:{},parameterKeys:Object.keys(input.params).sort()}}}}const row=confirmations.get(envelope.confirmationToken);if(!row||row.digest!==binding||row.expiresAt<=now()&&!row.execution)return refused("The action preview is missing, expired or does not match these parameters. Request a new preview.");row.execution??=agent("action",action,signal);return row.execution}}}
@@ -0,0 +1 @@
1
+ import{SYNC_WORKERS}from"./sync-sources.js";const LOCAL_SOURCES=new Set([...Object.keys(SYNC_WORKERS),"chrome-history"]);export function contentReadRoute(source,info){if(!source||LOCAL_SOURCES.has(source))return"local";return info?.data?.history==="sync"&&info.data.retention==="durable"?"local":"online"}
@@ -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 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.")}
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 platform==="darwin"?result("setup-required","cua_driver_required","The computer-use driver is unavailable to Zortex.","Run indra setup computer-use to install or restart the driver. Add --grant-permissions if macOS access is missing."):result("unsupported","cua_driver_required","The computer-use driver is unavailable to Zortex.","Install and configure a supported CUA Driver for this platform.");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.")}
@@ -1 +1 @@
1
- import{ok}from"@zortexhq/plugin-connector-framework/api";const failed=(source,errorCode,reason="unknown",retryability="none",nextStep)=>ok({source,state:"failed",reason,errorCode,retryability,...nextStep?{nextStep}:{}});function ready(source,value){if(value.source!==source)return failed(source,"invalid_readiness");if(value.basis==="actions"&&Number.isSafeInteger(value.actions)&&value.actions>0&&value.operation.state==="not-run")return ok({source,state:"ready",availability:"actions",actions:value.actions,operation:"not-run"});if(value.operation.state==="succeeded"&&Number.isSafeInteger(value.operation.returned)&&value.operation.returned>=0){const returned=value.operation.returned;return ok({source,state:"ready",availability:value.basis,...value.basis==="actions"&&Number.isSafeInteger(value.actions)?{actions:value.actions}:{},operation:"succeeded",returned})}return failed(source,value.basis==="actions"?"no_actions":"readiness_unverified","unknown","automatic","Zortex could not verify an available Action or bounded read.")}const retryableAuthorization=new Set(["unauthenticated","login_required","authorization_required","authorization_denied","failed_precondition"]);export function createResidentEnsureReady(options){return async(source,providedSignal)=>{const signal=providedSignal??new AbortController().signal;if(signal.aborted)return failed(source,"aborted","unknown","automatic");try{const observed=await options.status(signal);if(!("ok"in observed))return failed(source,"err"in observed?observed.err.code:"unavailable","unavailable","automatic","Zortex could not inspect this source.");const state=observed.ok.find(row=>row.source===source);if(!state)return failed(source,"not_found","unavailable","after_configuration","Install or enable this source, then try again.");if(state.state==="unavailable"||state.registration==="deferred"||state.verification==="configuration-only")return failed(source,"configuration_required","configuration","after_configuration","Complete this source setup in Zortex Help, then try again.");if(state.state==="connected"){const checked=await options.check(source,signal);if("ok"in checked)return ready(source,checked.ok);if(!("err"in checked)||!retryableAuthorization.has(checked.err.code))return failed(source,"err"in checked?checked.err.code:"unavailable","unknown","automatic","Zortex could not verify this source.")}let connected=await options.active(source,signal);if("err"in connected&&connected.err.code==="not_found")connected=await options.connect(source,options.requestId(),signal);else if("err"in connected&&connected.err.code==="connection_in_progress")connected=await options.active(source,signal);if(!("ok"in connected))return failed(source,"err"in connected?connected.err.code:"unavailable","authorization","automatic","Zortex could not start or recover the connection task.");const job=connected.ok;if(job.source!==source)return failed(source,"job_source_mismatch");if(job.state==="connecting")return ok({source,state:"connecting",jobId:job.id,recoveryHandle:job.id,retryability:"automatic"});if(job.state==="connected"){const checked=await options.check(source,signal);return"ok"in checked?ready(source,checked.ok):failed(source,"err"in checked?checked.err.code:"unavailable","unknown","automatic","The connection completed, but Zortex could not verify it.")}if(job.state==="waiting-user"){const handoff=await options.help(source,job,signal);const reason=job.authorizationImage?"qr":"authorization";return ok({source,state:"needs_user",jobId:job.id,recoveryHandle:job.id,helpUrl:handoff.url,expiresAt:handoff.expiresAt,reason,nextStep:"Open Zortex Help and finish the account step.",retryability:"after_user_action"})}return failed(source,job.state==="cancelled"?"aborted":job.error?.code??"authorization_failed","authorization",job.state==="cancelled"?"after_user_action":"automatic","The connection did not complete.")}catch{return failed(source,signal.aborted?"aborted":"unavailable","unavailable","automatic","Zortex could not complete the readiness check.")}}}
1
+ import{ok}from"@zortexhq/plugin-connector-framework/api";const failed=(source,errorCode,reason="unknown",retryability="none",nextStep)=>ok({source,state:"failed",reason,errorCode,retryability,...nextStep?{nextStep}:{}});function ready(source,value){if(value.source!==source)return failed(source,"invalid_readiness");if(value.basis==="actions"&&Number.isSafeInteger(value.actions)&&value.actions>0&&value.operation.state==="not-run")return ok({source,state:"ready",availability:"actions",actions:value.actions,operation:"not-run"});if(value.operation.state==="succeeded"&&Number.isSafeInteger(value.operation.returned)&&value.operation.returned>=0){const returned=value.operation.returned;return ok({source,state:"ready",availability:value.basis,...value.basis==="actions"&&Number.isSafeInteger(value.actions)?{actions:value.actions}:{},operation:"succeeded",returned})}return failed(source,value.basis==="actions"?"no_actions":"readiness_unverified","unknown","automatic","Zortex could not verify an available Action or bounded read.")}const retryableAuthorization=new Set(["unauthenticated","login_required","authorization_required","authorization_denied"]);export function createResidentEnsureReady(options){return async(source,providedSignal)=>{const signal=providedSignal??new AbortController().signal;if(signal.aborted)return failed(source,"aborted","unknown","automatic");try{const observed=await options.status(signal);if(!("ok"in observed))return failed(source,"err"in observed?observed.err.code:"unavailable","unavailable","automatic","Zortex could not inspect this source.");const state=observed.ok.find(row=>row.source===source);if(!state)return failed(source,"not_found","unavailable","after_configuration","Install or enable this source, then try again.");if(state.state==="unavailable"||state.registration==="deferred"||state.verification==="configuration-only")return failed(source,"configuration_required","configuration","after_configuration","Complete this source setup in Zortex Help, then try again.");if(state.state==="connected"){const checked=await options.check(source,signal);if("ok"in checked)return ready(source,checked.ok);if("err"in checked&&checked.err.code==="failed_precondition")return failed(source,"configuration_required","configuration","after_configuration","Zortex cannot use this connection until its product configuration or account binding is repaired. Repeating consent is not a configuration repair.");if(!("err"in checked)||!retryableAuthorization.has(checked.err.code))return failed(source,"err"in checked?checked.err.code:"unavailable","unknown","automatic","Zortex could not verify this source.")}let connected=await options.active(source,signal);if("err"in connected&&connected.err.code==="not_found")connected=await options.connect(source,options.requestId(),signal);else if("err"in connected&&connected.err.code==="connection_in_progress")connected=await options.active(source,signal);if(!("ok"in connected))return failed(source,"err"in connected?connected.err.code:"unavailable","authorization","automatic","Zortex could not start or recover the connection task.");const job=connected.ok;if(job.source!==source)return failed(source,"job_source_mismatch");if(job.state==="connecting")return ok({source,state:"connecting",jobId:job.id,recoveryHandle:job.id,retryability:"automatic"});if(job.state==="connected"){const checked=await options.check(source,signal);return"ok"in checked?ready(source,checked.ok):failed(source,"err"in checked?checked.err.code:"unavailable","unknown","automatic","The connection completed, but Zortex could not verify it.")}if(job.state==="waiting-user"){const handoff=await options.help(source,job,signal);const reason=job.authorizationImage?"qr":"authorization";return ok({source,state:"needs_user",jobId:job.id,recoveryHandle:job.id,helpUrl:handoff.url,expiresAt:handoff.expiresAt,reason,nextStep:"Open Zortex Help and finish the account step.",retryability:"after_user_action"})}return failed(source,job.state==="cancelled"?"aborted":job.error?.code??"authorization_failed","authorization",job.state==="cancelled"?"after_user_action":"automatic","The connection did not complete.")}catch{return failed(source,signal.aborted?"aborted":"unavailable","unavailable","automatic","Zortex could not complete the readiness check.")}}}