@zortexhq/indra-v2.5 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/README.md +5 -5
  2. package/bin/codex-postinstall.mjs +1 -1
  3. package/dist/action-effect.js +1 -0
  4. package/dist/action-read-progress.js +1 -1
  5. package/dist/actions-catalog.js +1 -0
  6. package/dist/auto-sync.js +1 -1
  7. package/dist/auto-update.js +1 -1
  8. package/dist/automatic-updates.js +1 -0
  9. package/dist/bundled-handbook.js +1 -1
  10. package/dist/cli-run.js +1 -1
  11. package/dist/cli.js +1 -1
  12. package/dist/codex-install.js +1 -1
  13. package/dist/codex-setup.js +1 -1
  14. package/dist/computer-use-setup.js +1 -0
  15. package/dist/default-root.js +1 -1
  16. package/dist/documentation-action.js +1 -0
  17. package/dist/gateway.js +1 -1
  18. package/dist/imessage-sync.js +1 -1
  19. package/dist/local-cloud-policy.js +1 -1
  20. package/dist/local-cloud.js +1 -1
  21. package/dist/mcp.js +1 -3
  22. package/dist/native-connect.js +1 -1
  23. package/dist/native-level1-setup.js +1 -1
  24. package/dist/native-ollama-discovery.js +1 -0
  25. package/dist/native-vault-discovery.js +1 -1
  26. package/dist/onboard-cli.js +1 -1
  27. package/dist/onboard.js +1 -1
  28. package/dist/onboarding.js +1 -1
  29. package/dist/profile.js +1 -1
  30. package/dist/public-tool.js +4 -1
  31. package/dist/read-route.js +1 -1
  32. package/dist/recovery-authorization-url.js +1 -1
  33. package/dist/recovery-progress.js +1 -1
  34. package/dist/recovery.js +1 -1
  35. package/dist/resident-autopilot.js +1 -0
  36. package/dist/resident-ensure-ready.js +1 -1
  37. package/dist/resident-host.js +2 -2
  38. package/dist/resident-jobs.js +1 -1
  39. package/dist/resident-platform.js +2 -2
  40. package/dist/resident-runtime-identity.js +1 -1
  41. package/dist/resident-startup-state.js +1 -0
  42. package/dist/resident-telemetry.js +1 -1
  43. package/dist/shared-action-schemas.js +1 -0
  44. package/dist/source-data.js +1 -1
  45. package/dist/storage-compatibility.js +1 -0
  46. package/dist/supervised-sync.js +1 -1
  47. package/dist/tools.js +1 -1
  48. package/dist/update-check.js +1 -1
  49. package/dist/update-cli.js +1 -1
  50. package/dist/update-command.js +1 -1
  51. package/dist/update-recovery.js +1 -1
  52. package/node_modules/@zortexhq/plugin-auto-connect/dist/api/durable-dispatcher.js +1 -1
  53. package/node_modules/@zortexhq/plugin-auto-connect/dist/api/job-contract.js +1 -1
  54. package/node_modules/@zortexhq/plugin-autopilot/dist/api.js +1 -0
  55. package/node_modules/@zortexhq/plugin-autopilot/dist/cua.js +1 -0
  56. package/node_modules/@zortexhq/plugin-autopilot/dist/feedback.js +1 -0
  57. package/node_modules/@zortexhq/plugin-autopilot/dist/index.js +1 -0
  58. package/node_modules/@zortexhq/plugin-autopilot/dist/python-runtime.js +1 -0
  59. package/node_modules/@zortexhq/plugin-autopilot/dist/service.js +1 -0
  60. package/node_modules/@zortexhq/plugin-autopilot/dist/worker.js +1 -0
  61. package/node_modules/@zortexhq/plugin-autopilot/package.json +23 -0
  62. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/LICENSE +21 -0
  63. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/PROVENANCE.json +38 -0
  64. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/__init__.py +1 -0
  65. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/agent.py +178 -0
  66. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/browser.py +13 -0
  67. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/indra.patch +57 -0
  68. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/model.py +180 -0
  69. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/questions.py +26 -0
  70. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/transport.py +70 -0
  71. package/node_modules/@zortexhq/plugin-autopilot/python/strategies.py +154 -0
  72. package/node_modules/@zortexhq/plugin-autopilot/python/worker.py +260 -0
  73. package/node_modules/@zortexhq/plugin-connector-activitywatch/dist/provider.js +1 -1
  74. package/node_modules/@zortexhq/plugin-connector-calendar/dist/actions.js +1 -1
  75. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/catalog.js +1 -1
  76. package/node_modules/@zortexhq/plugin-connector-core/dist/api/action-outcome.js +1 -0
  77. package/node_modules/@zortexhq/plugin-connector-core/dist/api/connectors.js +1 -1
  78. package/node_modules/@zortexhq/plugin-connector-core/dist/api/content-acquisition.js +1 -0
  79. package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
  80. package/node_modules/@zortexhq/plugin-connector-core/dist/authorization-metrics.js +1 -1
  81. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  82. package/node_modules/@zortexhq/plugin-connector-core/dist/native-principal.js +1 -1
  83. package/node_modules/@zortexhq/plugin-connector-drive/dist/actions.js +1 -1
  84. package/node_modules/@zortexhq/plugin-connector-drive/package.json +2 -1
  85. package/node_modules/@zortexhq/plugin-connector-gmail/dist/actions.js +1 -1
  86. package/node_modules/@zortexhq/plugin-connector-gmail/dist/connector.js +1 -1
  87. package/node_modules/@zortexhq/plugin-connector-gmail/package.json +2 -1
  88. package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/compounds.js +1 -1
  89. package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/provider.js +1 -1
  90. package/node_modules/@zortexhq/plugin-connector-level1/dist/action-content.js +1 -0
  91. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-helper.js +1 -1
  92. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-server.js +6 -6
  93. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-native-process.mjs +1 -0
  94. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-helper.js +1 -1
  95. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-server.js +2 -2
  96. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-helper.js +1 -1
  97. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-server.js +2 -2
  98. package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -1
  99. package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
  100. package/node_modules/@zortexhq/plugin-connector-level1/dist/macos-contacts-server.js +1 -0
  101. package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-apple-native.js +1 -0
  102. package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
  103. package/node_modules/@zortexhq/plugin-connector-level1/dist/provisioning.js +1 -1
  104. package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/content.js +1 -0
  105. package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/specs.js +1 -1
  106. package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
  107. package/node_modules/@zortexhq/plugin-connector-netease/dist/provider.js +1 -1
  108. package/node_modules/@zortexhq/plugin-connector-notion/dist/provider.js +1 -1
  109. package/node_modules/@zortexhq/plugin-connector-outlook/dist/actions.js +1 -1
  110. package/node_modules/@zortexhq/plugin-connector-outlook/dist/mail-sync.js +1 -1
  111. package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
  112. package/node_modules/@zortexhq/plugin-connector-slack/dist/actions.js +1 -1
  113. package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
  114. package/node_modules/@zortexhq/plugin-connector-steam/dist/provider.js +1 -1
  115. package/node_modules/@zortexhq/plugin-connector-teams/dist/actions.js +1 -1
  116. package/node_modules/@zortexhq/plugin-connector-teams/dist/provider.js +1 -1
  117. package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/auth-state.js +1 -1
  118. package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/provider.js +1 -1
  119. package/node_modules/@zortexhq/plugin-connector-youtube/dist/content.js +1 -0
  120. package/node_modules/@zortexhq/plugin-connector-youtube/dist/full-sync.js +1 -1
  121. package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
  122. package/node_modules/@zortexhq/plugin-context-share/dist/api/action-schemas.js +1 -0
  123. package/node_modules/@zortexhq/plugin-context-share/dist/api/index.js +1 -1
  124. package/node_modules/@zortexhq/plugin-context-share/dist/index.js +1 -1
  125. package/node_modules/@zortexhq/plugin-context-share/dist/share.js +1 -1
  126. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-catalog.js +1 -1
  127. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
  128. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/account.js +1 -1
  129. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -1
  130. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -1
  131. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
  132. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -1
  133. package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
  134. package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -1
  135. package/node_modules/@zortexhq/plugin-process-local/dist/api/execution-scope.js +1 -0
  136. package/node_modules/@zortexhq/plugin-process-local/dist/api/stdio-transport.js +1 -0
  137. package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
  138. package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
  139. package/node_modules/@zortexhq/plugin-process-local/dist/windows-job.js +1 -1
  140. package/node_modules/@zortexhq/plugin-product-account/dist/index.js +4 -1
  141. package/node_modules/@zortexhq/plugin-product-account/dist/session-store.js +10 -0
  142. package/node_modules/@zortexhq/plugin-product-account/dist/storage.js +1 -0
  143. package/node_modules/@zortexhq/plugin-product-account/package.json +5 -1
  144. package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
  145. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/content-acquisition.js +1 -0
  146. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
  147. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/public-result-visibility.js +1 -0
  148. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/content-acquisition.js +1 -0
  149. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/credentials.js +3 -3
  150. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  151. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/keychain.js +1 -1
  152. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/public-visibility.js +7 -0
  153. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/recovery-guard.js +1 -1
  154. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/runtime.js +1 -0
  155. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +2 -0
  156. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -1
  157. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
  158. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-worker.js +1 -1
  159. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot.js +1 -1
  160. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -1
  161. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +2 -1
  162. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql.js +1 -1
  163. package/package.json +13 -7
  164. package/profiles/core.yml +2 -0
  165. package/release-provenance.json +48 -41
  166. package/update-manifest.json +573 -296
  167. package/dist/content-find.js +0 -2
  168. package/dist/find-snapshots.js +0 -1
  169. package/dist/match-excerpt.js +0 -1
@@ -1 +1 @@
1
- import{createServer}from"node:http";import{createHash,randomBytes,randomUUID}from"node:crypto";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{isTransientConnectorAction}from"@zortexhq/plugin-connector-core/api";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{GOOGLE_TOKEN_URL,localGoogleDesktopClient,usesDirectGoogleOAuth}from"./desktop-client.js";import{isGmailReadBatch}from"./read-batch.js";import{createTraceRecorder}from"@zortexhq/plugin-telemetry/api";export const GOOGLE_PUBLIC_CLIENT_ID="230897508334-5f6voqm2ie55t258ksmp7odd7vh9ejvn.apps.googleusercontent.com";export const DEFAULT_GOOGLE_BROKER_URL="https://zortex-google-oauth.google-oauth-broker.workers.dev";export const name="zortex-google-auth";export const inject=["zortexVaultStore","zortexConnectorHttp"];class GoogleHttpFailure extends Error{status;constructor(status){super("Google endpoint returned a failed status.");this.status=status}}const scopes={gmail:"https://mail.google.com/ openid email","google-drive":"https://www.googleapis.com/auth/drive","google-calendar":"https://www.googleapis.com/auth/calendar",youtube:"https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/yt-analytics.readonly openid email","google-tasks":"https://www.googleapis.com/auth/tasks openid email"};const gmailReadScope="https://www.googleapis.com/auth/gmail.readonly";const gmailReadScopes=[gmailReadScope,"https://www.googleapis.com/auth/gmail.modify","https://mail.google.com/"];const driveReadScopes=["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive"];const oidc="https://openidconnect.googleapis.com/v1/userinfo";const identity={gmail:oidc,"google-drive":"https://www.googleapis.com/drive/v3/about?fields=user(permissionId,emailAddress)","google-calendar":"https://www.googleapis.com/calendar/v3/users/me/calendarList?maxResults=1",youtube:oidc,"google-tasks":oidc};const allowed={gmail:{origin:"https://gmail.googleapis.com",prefix:"/gmail/v1/"},"google-drive":{origin:"https://www.googleapis.com",prefix:"/drive/v3/"},"google-calendar":{origin:"https://www.googleapis.com",prefix:"/calendar/v3/"},youtube:{origin:"https://www.googleapis.com",prefix:"/youtube/v3/"},"google-tasks":{origin:"https://tasks.googleapis.com",prefix:"/tasks/v1/"}};const permitted=(source,endpoint,method)=>{if(endpoint.username||endpoint.password||endpoint.hash)return false;const boundary=allowed[source];if(boundary&&endpoint.origin===boundary.origin&&endpoint.pathname.startsWith(boundary.prefix))return true;if(source==="youtube"&&method==="GET"&&(endpoint.origin==="https://youtubeanalytics.googleapis.com"&&endpoint.pathname.startsWith("/v2/")||endpoint.origin==="https://youtubereporting.googleapis.com"&&endpoint.pathname.startsWith("/v1/")))return true;return source==="google-drive"&&method==="GET"&&(endpoint.origin==="https://docs.googleapis.com"&&/^\/v1\/documents\/[A-Za-z0-9_-]{1,200}$/.test(endpoint.pathname)||endpoint.origin==="https://sheets.googleapis.com"&&/^\/v4\/spreadsheets\/[A-Za-z0-9_-]{1,200}$/.test(endpoint.pathname))};export const openSystemUrl=openConnectionUrl;export function createGoogleAuth({vault,desktopClient=localGoogleDesktopClient,transport=fetch,tokenTransport=transport,openUrl=openSystemUrl,timeoutMs=6e5,now=Date.now,metrics,feedback}){const jobs=new Map,jobModes=new WeakMap;const listeners=new Map;const stop=new AbortController;const refreshing=new Map,callbacks=new Set;let closed=false,closing;const fail=(code,message)=>businessError(code,message,"plugin");async function json(url,options={},send=transport){if(closed)throw Error("google_auth_inactive");const signal=options.signal?AbortSignal.any([options.signal,stop.signal,AbortSignal.timeout(45e3)]):AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);const response=await send(url,{...options,redirect:"error",signal});if(!response.ok){await response.body?.cancel().catch(()=>{});throw new GoogleHttpFailure(response.status)}const reader=response.body?.getReader();if(!reader)throw Error("empty_response");const chunks=[];let size=0;for(;;){const part=await reader.read();if(part.done)break;size+=part.value.length;if(size>2*1024*1024){await reader.cancel();throw Error("response_too_large")}chunks.push(part.value)}return JSON.parse(Buffer.concat(chunks).toString("utf8"))}function directToken(client,fields,signal){return json(GOOGLE_TOKEN_URL,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:client.clientId,client_secret:client.clientSecret,...fields}),...signal?{signal}:{}},tokenTransport)}const missingDesktopClient=source=>businessError("failed_precondition",`Zortex Google OAuth client configuration is unavailable. The product administrator must restore the registered client; reconnecting the account cannot repair product configuration. For self-managed installs, save the Google-downloaded Desktop app client JSON with {"installed":{"client_id":"<id>.apps.googleusercontent.com","client_secret":"<secret>"}} as ~/.zortex/google-oauth/${source}.json (directory 0700, file 0600), or set ZORTEX_GOOGLE_OAUTH_CLIENT_ID and ZORTEX_GOOGLE_OAUTH_CLIENT_SECRET, then retry the connection.`,"plugin");const configuredClient=async source=>{const client=await desktopClient(source);return client?.clientId===GOOGLE_PUBLIC_CLIENT_ID?void 0:client};function releaseListener(id){const entry=listeners.get(id);if(entry?.finished&&entry.serverClosed&&!entry.task)listeners.delete(id)}function finish(job){const resources=listeners.get(job.id);if(resources&&!resources.finished){resources.finished=true;clearTimeout(resources.timer);resources.detach?.();resources.server.closeAllConnections();resources.server.close(error=>{resources.serverClosed=!error||error.code==="ERR_SERVER_NOT_RUNNING";releaseListener(job.id)});releaseListener(job.id)}delete job.authorizationUrl;delete job.instructions}async function access(source,bindingId){if(isTransientConnectorAction()&&!bindingId)return readAccess(source);const key=bindingId?source+":"+bindingId:source;let task=refreshing.get(key);if(!task){task=readAccess(source,bindingId);refreshing.set(key,task)}try{const result=await task;return closed?fail("unavailable","Google authorization is inactive."):result}finally{if(refreshing.get(key)===task)refreshing.delete(key)}}async function readAccess(source,bindingId){const custody=vault.bindingCustody;let found,snapshot;const choices=source==="google-tasks"?["https://www.googleapis.com/auth/tasks.readonly","https://www.googleapis.com/auth/tasks"]:source==="youtube"?["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"]:source==="google-calendar"?["https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/calendar"]:source==="gmail"?["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.modify","https://mail.google.com/"]:driveReadScopes;const hasReadScope=granted=>Array.isArray(granted)&&choices.some(scope=>granted.includes(scope));const direct=usesDirectGoogleOAuth(source);const client=direct?await configuredClient(source):void 0;const sealedClient=credential=>credential.clientAuthentication?.method==="client_secret_post"&&credential.clientAuthentication.secret&&(credential.clientAuthentication.expiresAt===void 0||credential.clientAuthentication.expiresAt>now())?{clientId:credential.clientId,clientSecret:credential.clientAuthentication.secret}:void 0;const originalBroker=credential=>source!=="google-tasks"&&credential.clientId===GOOGLE_PUBLIC_CLIENT_ID&&!credential.clientAuthentication;const requiresTasksReconnect=credential=>source==="google-tasks"&&!sealedClient(credential)&&credential.clientId!==client?.clientId;const reconnect=()=>fail("failed_precondition","Reconnect this source with its Google Desktop OAuth client.");const reconnectTasks=()=>client?reconnect():missingDesktopClient("google-tasks");const refreshConfigurationError=credential=>{if(sealedClient(credential)||originalBroker(credential))return;if(direct&&!client)return missingDesktopClient(source);if(!direct&&credential.clientId!==GOOGLE_PUBLIC_CLIENT_ID)return fail("failed_precondition","The original Google OAuth client configuration is unavailable. Product configuration must be restored before refreshing this grant.");if(client&&credential.clientId!==client.clientId)return missingDesktopClient(source)};const authorized=current=>current.material.kind!=="oauth"||current.resource.owner.kind!=="resident"?fail("failed_precondition","Google credential resource is not owned by the resident."):!hasReadScope(current.grant.scopes)||!hasReadScope(current.material.credential.scopes)?fail("permission_denied","The stored grant lacks the selected source read scope."):requiresTasksReconnect(current.material.credential)?reconnectTasks():ok({credential:current.material.credential,snapshot:current});if(custody){let resolution=await custody.resolve(bindingId?{kind:"binding",bindingId}:{kind:isTransientConnectorAction()&&custody.sourceSelection?"selected-source":"legacy-source",source});if(!bindingId&&"ok"in resolution&&resolution.ok.kind==="legacy-unattributed"&&custody.recoverLegacy){let expired;const verify=async(connection,credential)=>{if(requiresTasksReconnect(credential))return reconnectTasks();if(connection.provider!=="google"||!hasReadScope(connection.scopes)||!hasReadScope(credential.scopes))return fail("permission_denied","The legacy Google credential lacks the selected read scope. Open zortex help for account recovery; ordinary reconnect does not resolve mixed legacy history.");if(credential.expiresAt<=now()+6e4){if(credential.refreshToken)expired=credential;return fail("failed_precondition","The legacy Google credential has expired. Open zortex help for explicit account recovery; ordinary reconnect does not resolve mixed legacy history.")}try{return ok(await verifyLegacyIdentity(source,credential.accessToken))}catch{return fail("failed_precondition","Google could not verify the original legacy account. Open zortex help for explicit account recovery; preserve its legacy history and do not retry ordinary reconnect to clear ambiguity.")}};let recovered=await custody.recoverLegacy(source,verify);if(!("ok"in recovered)&&expired&&custody.refreshLegacyCredential){const configurationError2=refreshConfigurationError(expired);if(configurationError2)return configurationError2;const refreshedLegacy=await custody.refreshLegacyCredential(source,expired,async(connection,current2)=>{if(connection.provider!=="google"||!hasReadScope(connection.scopes)||!hasReadScope(current2.scopes)||!current2.refreshToken)return fail("failed_precondition","Legacy Google authorization cannot be recovered with its original grant. Open zortex help for account recovery.");const next2=await refreshed(current2,false);return"ok"in next2?next2:fail("err"in next2?next2.err.code:"internal","The original legacy Google grant could not be refreshed. Preserve this Vault and open zortex help for account recovery; do not repeat ordinary reconnect to clear mixed history.")});if(!("ok"in refreshedLegacy))return refreshedLegacy;recovered=await custody.recoverLegacy(source,verify)}if(!("ok"in recovered))return recovered;resolution=ok({kind:"resolved",binding:recovered.ok})}if(!("ok"in resolution)||resolution.ok.kind!=="resolved")return"err"in resolution?resolution:fail("failed_precondition","Google source needs an explicitly selected account binding. Open zortex help for account recovery; ordinary reconnect does not resolve mixed legacy history.");if(resolution.ok.binding.identity.source!==source)return fail("permission_denied","The selected account binding belongs to another source.");const current=await custody.credentialSnapshot(oauthCredentialResourceId(resolution.ok.binding.id),{purpose:"L1",audience:"google"});if(!("ok"in current))return current;snapshot=current.ok;found=authorized(snapshot)}else{const legacy=await vault.credential(source);found="ok"in legacy?ok({credential:legacy.ok}):legacy}if(!("ok"in found))return"err"in found?found:fail("failed_precondition","Google source is not connected.");if(requiresTasksReconnect(found.ok.credential))return reconnectTasks();if((source==="google-tasks"||source==="youtube")&&!hasReadScope(found.ok.credential.scopes))return fail("permission_denied","The stored grant lacks the selected source read scope.");if(found.ok.credential.expiresAt>now()+6e4)return found;if(!found.ok.credential.refreshToken)return fail("unauthenticated","Google authorization expired. Start the connection flow again.");const configurationError=refreshConfigurationError(found.ok.credential);if(configurationError)return configurationError;async function refreshed(current,pinClient=true){const configurationError2=refreshConfigurationError(current);if(configurationError2)return configurationError2;if(!current.refreshToken)return fail("unauthenticated","Google authorization expired. Start the connection flow again.");const issuingClient=originalBroker(current)?void 0:sealedClient(current)??client;try{const token=issuingClient?await directToken(issuingClient,{grant_type:"refresh_token",refresh_token:current.refreshToken}):await json(DEFAULT_GOOGLE_BROKER_URL+"/google/refresh",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({clientId:current.clientId,refreshToken:current.refreshToken})});if(typeof token.access_token!=="string"||!token.access_token||!Number.isFinite(token.expires_in)||token.expires_in<=0||token.refresh_token!==void 0&&(typeof token.refresh_token!=="string"||!token.refresh_token))throw Error("invalid_token_response");return ok({...current,...issuingClient&&pinClient?{clientAuthentication:{method:"client_secret_post",secret:issuingClient.clientSecret}}:{},accessToken:token.access_token,...token.refresh_token!==void 0?{refreshToken:token.refresh_token}:{},expiresAt:now()+token.expires_in*1e3})}catch(error){return error instanceof GoogleHttpFailure&&[400,401,403].includes(error.status)?fail("unauthenticated","Google authorization is no longer accepted. Reconnect this source."):fail("unavailable","Google authorization refresh did not complete; no missing grant was assumed.")}}if(custody&&snapshot){const stored2=await custody.refreshResource(snapshot,{kind:"resident"},async current2=>{const permitted2=authorized(current2);if(!("ok"in permitted2))return permitted2;const next2=await refreshed(permitted2.ok.credential);return"ok"in next2?ok({kind:"oauth",credential:next2.ok}):next2});if("ok"in stored2)return authorized(stored2.ok);if(!("err"in stored2)||stored2.err.code!=="failed_precondition")return stored2;const current=await custody.credentialSnapshot(snapshot.resource.id,{purpose:"L1",audience:"google"});if(!("ok"in current))return current;const winner=authorized(current.ok);return current.ok.resource.revision>snapshot.resource.revision&&"ok"in winner&&winner.ok.credential.expiresAt>now()+6e4?winner:stored2}const next=await refreshed(found.ok.credential);if(!("ok"in next))return next;const stored=await vault.updateCredential(source,next.ok);return"ok"in stored?ok({credential:next.ok}):"err"in stored?stored:fail("internal","Credential update was not confirmed.")}async function checkAccess(source,selected,bindingId){const custody=vault.bindingCustody,expected=selected.snapshot;if(!custody)return ok(void 0);const changed=()=>fail("permission_denied","The selected Google account, grant or credential changed during the request; its response was withheld.");if(!expected)return changed();const current=await custody.credentialSnapshot(expected.resource.id,{purpose:"L1",audience:"google"});if(!("ok"in current))return current;const resolved=await custody.resolve(bindingId?{kind:"binding",bindingId}:{kind:isTransientConnectorAction()&&custody.sourceSelection?"selected-source":"legacy-source",source});if(!("ok"in resolved))return resolved;if(resolved.ok.kind!=="resolved"||resolved.ok.binding.id!==expected.binding.id||resolved.ok.binding.revision!==expected.binding.revision)return changed();return current.ok.binding.id===expected.binding.id&&current.ok.binding.revision===expected.binding.revision&&current.ok.grant.id===expected.grant.id&&current.ok.grant.revision===expected.grant.revision&&current.ok.grant.scopeEpoch===expected.grant.scopeEpoch&&current.ok.resource.id===expected.resource.id&&current.ok.resource.revision===expected.resource.revision?ok(void 0):changed()}async function captureSelection(source,readOnly=true){const custody=vault.bindingCustody;if(!custody?.sourceSelection)return ok(async()=>ok(void 0));const found=await custody.sourceSelection(source);if(!("ok"in found))return found;if(found.ok&&!isTransientConnectorAction())return fail("failed_precondition","This explicitly recovered account supports transient L1 reads. Source-only history sync remains disabled; use zortex help to read the selected account.");if(found.ok&&!readOnly)return fail("permission_denied","Explicit account recovery authorizes bounded reads only.");const expected=found.ok;return ok(async()=>{const current=await custody.sourceSelection(source);if(!("ok"in current))return current;return current.ok?.bindingId===expected?.bindingId&&current.ok?.revision===expected?.revision?ok(void 0):fail("permission_denied","The selected account changed during this request; its response was withheld.")})}async function verifyLegacyIdentity(source,accessToken){const headers={Authorization:"Bearer "+accessToken};let profile=await json(identity[source],{headers});if(source==="google-drive"){const subject=profile.user?.permissionId,account=profile.user?.emailAddress??subject;if(typeof subject!=="string"||!subject.trim()||subject.length>500||typeof account!=="string"||!account)throw Error("drive_identity_not_confirmed");return{accountId:subject,account}}if(source==="google-calendar"){const seen=new Set;for(let page=0;page<20;page++){if(!Array.isArray(profile.items)||profile.items.some(row=>!row||typeof row!=="object"))throw Error("invalid_calendar_identity");const primary=profile.items.filter(row=>row.primary===true);if(primary.length>1)throw Error("ambiguous_calendar_identity");if(primary.length===1){const subject=primary[0].id;if(typeof subject!=="string"||!subject.trim()||subject.length>500)throw Error("invalid_calendar_identity");return{accountId:subject,account:subject}}const next=profile.nextPageToken;if(typeof next!=="string"||!next||next.length>8192||seen.has(next))throw Error("primary_calendar_not_found");seen.add(next);const url=new URL("https://www.googleapis.com/calendar/v3/users/me/calendarList");url.searchParams.set("maxResults","250");url.searchParams.set("pageToken",next);url.searchParams.set("fields","items(id,primary),nextPageToken");profile=await json(url.href,{headers})}throw Error("calendar_identity_budget_exceeded")}if(profile.email_verified!==true||typeof profile.sub!=="string"||!/^[\x21-\x7e]{1,255}$/.test(profile.sub)||typeof profile.email!=="string"||!profile.email)throw Error("account_not_confirmed");return{accountId:profile.sub,account:profile.email}}const service={async connect(source,options={}){if(options.automatic===true)return fail("invalid_argument","Automatic enrollment is retired. Open the source connection gateway.");options={...options,automatic:false};if(options.signal?.aborted)return fail("aborted","Google authorization cancelled.");if(options.selectAccount!==void 0&&(options.selectAccount!==true||options.automatic!==false))return fail("invalid_argument","Explicit account selection requires manual recovery.");if(options.gmailWrite!==void 0&&(options.gmailWrite!==true||source!=="gmail"||options.automatic!==false||options.selectAccount||options.reauthorize))return fail("invalid_argument","Gmail write consent requires an explicit same-account manual authorization.");const custodyForWrite=options.gmailWrite?vault.bindingCustody:void 0;if(options.gmailWrite&&(!custodyForWrite?.sourceSelection||!custodyForWrite.resolve))return fail("failed_precondition","A selected Gmail account is required before requesting write access.");const writeSelection=options.gmailWrite?await custodyForWrite.sourceSelection("gmail"):void 0;if(writeSelection&&!("ok"in writeSelection))return writeSelection;const writeBinding=options.gmailWrite?await custodyForWrite.resolve(writeSelection&&"ok"in writeSelection&&writeSelection.ok?{kind:"binding",bindingId:writeSelection.ok.bindingId}:{kind:"legacy-source",source:"gmail"}):void 0;if(writeBinding&&(!("ok"in writeBinding)||writeBinding.ok.kind!=="resolved"||writeBinding.ok.binding.identity.source!=="gmail"||writeBinding.ok.binding.provider!=="google"||!writeBinding.ok.binding.identity.subject))return fail("failed_precondition","Select a verified Gmail account before requesting write access.");const writeInventory=writeBinding&&"ok"in writeBinding&&writeBinding.ok.kind==="resolved"?await custodyForWrite.bindingInventory(writeBinding.ok.binding.id):void 0;if(options.gmailWrite&&(!writeInventory||!("ok"in writeInventory)||!writeInventory.ok))return fail("failed_precondition","Gmail credential custody is unavailable.");const writeTarget=writeInventory&&"ok"in writeInventory?writeInventory.ok:void 0;const writeGrant=writeTarget?.grants.find(g=>g.purpose==="L1"&&g.audience==="google");const writeResource=writeTarget?.resources.find(r=>r.id===oauthCredentialResourceId(writeTarget.binding.id));if(options.gmailWrite&&(!writeTarget||!writeGrant||!writeResource||!writeBinding||!("ok"in writeBinding)||writeBinding.ok.kind!=="resolved"||writeTarget.binding.revision!==writeBinding.ok.binding.revision))return fail("failed_precondition","Gmail credential custody changed.");if(options.selectAccount&&(!vault.bindingCustody?.sourceSelection||!vault.bindingCustody.selectSourceBinding))return fail("failed_precondition","This Vault does not support explicit account recovery.");const selectionBefore=options.selectAccount?await vault.bindingCustody.sourceSelection(source):ok(null);if(!("ok"in selectionBefore))return selectionBefore;const direct=usesDirectGoogleOAuth(source);const client=direct?await configuredClient(source):void 0;if(direct&&!client)return missingDesktopClient(source);const clientId=client?.clientId??GOOGLE_PUBLIC_CLIENT_ID;const requestedScopes=source==="gmail"&&!options.gmailWrite?`${gmailReadScope} openid email`:scopes[source];const interactionMode=options.manualPresentation==="return-url"?"manual-return-url":"manual-open";const deadline=timeoutMs;if(closed)return fail("unavailable","Google authorization is inactive.");if(!Object.hasOwn(scopes,source))return fail("invalid_argument","Unknown Google source.");const running=[...jobs.values()].find(job2=>job2.source===source&&job2.state==="waiting-user");if(running&&(options.selectAccount||options.gmailWrite))return fail("failed_precondition","Wait for the current authorization to finish before explicit account recovery.");if(running)return jobModes.get(running)!==interactionMode?fail("failed_precondition","Previous source authorization uses a different interaction mode. Wait for its owned cleanup."):ok({...running});if([...listeners].some(([id])=>jobs.get(id)?.source===source))return fail("failed_precondition","Previous source authorization still owns active work. Wait for cleanup.");const job={id:randomUUID(),source,state:"waiting-user",startedAt:new Date(now()).toISOString()};jobModes.set(job,interactionMode);jobs.set(job.id,job);const jobStop=new AbortController,jobSignal=AbortSignal.any([stop.signal,jobStop.signal,...options.signal?[options.signal]:[]]);const trace=createTraceRecorder(metrics,source);let stage="callback_received";await trace.step("authorization_started","started");const verifier=randomBytes(48).toString("base64url"),state=randomBytes(24).toString("base64url");let used=false;let redirectUri="";const server=createServer((request,response)=>{const url=new URL(request.url??"/",redirectUri);if(request.method!=="GET"||url.pathname!=="/callback"){response.writeHead(404).end("Not found.");return}if(url.searchParams.get("state")!==state){response.writeHead(400).end("Invalid authorization state.");return}if(used){response.writeHead(409).end("Authorization callback already received.");return}const code=url.searchParams.get("code"),error=url.searchParams.get("error");if(error||!code){used=true;job.state="failed";job.error={code:"authorization_denied",message:"Google authorization was not completed."};void trace.step("callback_received","failed",{error:"denied"});response.writeHead(400).end("Authorization was not completed.");finish(job);return}used=true;response.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"}).end("Authorization received. Zortex is validating the connection. You may close this page.");const callback=(async()=>{try{await trace.step("callback_received","completed");stage="token_exchange";await trace.step(stage,"started");const exchange=()=>client?directToken(client,{grant_type:"authorization_code",code,code_verifier:verifier,redirect_uri:redirectUri},jobSignal):json(DEFAULT_GOOGLE_BROKER_URL+"/google/token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({clientId,code,codeVerifier:verifier,redirectUri}),signal:jobSignal});const token=await exchange();if(!token.access_token||!Number.isFinite(token.expires_in))throw Error("invalid_token_response");const granted=(token.scope??requestedScopes).split(" ");if(source==="google-drive"?!driveReadScopes.some(scope=>granted.includes(scope)):source==="gmail"?!((options.gmailWrite?granted.includes("https://mail.google.com/"):gmailReadScopes.some(scope=>granted.includes(scope)))&&granted.includes("openid")&&(granted.includes("email")||granted.includes("https://www.googleapis.com/auth/userinfo.email"))):!requestedScopes.split(" ").every(scope=>granted.includes(scope)||scope==="email"&&granted.includes("https://www.googleapis.com/auth/userinfo.email")))throw Error("required_scope_missing");await trace.step(stage,"completed");stage="identity_verified";await trace.step(stage,"started");let profile=await json(identity[source],{headers:{Authorization:"Bearer "+token.access_token},signal:jobSignal});let calendarAccount;if(source==="google-calendar"){const seen=new Set;for(let page=0;page<50;page++){if(closed||job.state!=="waiting-user")throw Error("connection_cancelled");if(!Array.isArray(profile.items)||profile.items.some(row=>!row||typeof row!=="object"))throw Error("invalid_calendar_identity");const primary=profile.items.filter(row=>row.primary===true);if(primary.length>1)throw Error("ambiguous_calendar_identity");if(primary.length===1){if(typeof primary[0].id!=="string"||!primary[0].id.trim()||primary[0].id.length>500)throw Error("invalid_calendar_identity");calendarAccount=primary[0].id;break}const next=profile.nextPageToken;if(next===void 0)throw Error("primary_calendar_not_found");if(typeof next!=="string"||!next||next.length>8192||seen.has(next))throw Error("invalid_calendar_identity_cursor");seen.add(next);const url2=new URL("https://www.googleapis.com/calendar/v3/users/me/calendarList");url2.searchParams.set("maxResults","250");url2.searchParams.set("pageToken",next);url2.searchParams.set("fields","items(id,primary),nextPageToken");profile=await json(url2.href,{headers:{Authorization:"Bearer "+token.access_token},signal:jobSignal})}if(!calendarAccount)throw Error("calendar_identity_budget_exceeded")}const oidcSource=source==="gmail"||source==="youtube"||source==="google-tasks";const account=source==="google-drive"?profile.user?.emailAddress??profile.user?.permissionId:oidcSource?profile.email:calendarAccount;if(source==="google-drive"&&(typeof profile.user?.permissionId!=="string"||!profile.user.permissionId.trim()||profile.user.permissionId.length>500))throw Error("drive_identity_not_confirmed");if(oidcSource&&(profile.email_verified!==true||typeof profile.sub!=="string"||!/^[\x21-\x7e]{1,255}$/.test(profile.sub)))throw Error("account_not_confirmed");if(typeof account!=="string"||!account)throw Error("account_not_confirmed");let readGuard=null;if(source==="gmail"&&!options.gmailWrite&&vault.bindingCustody){const known=await vault.bindingCustody.bindings("gmail");if(!("ok"in known))throw Error("gmail_existing_grant_unavailable");const previous=known.ok.filter(binding=>binding.provider==="google"&&binding.identity.subject===profile.sub);if(previous.length>1)throw Error("gmail_existing_grant_unavailable");readGuard=null;for(const binding of previous){const inventory=await vault.bindingCustody.bindingInventory(binding.id);if(!("ok"in inventory)||!inventory.ok)throw Error("gmail_existing_grant_unavailable");const existing=inventory.ok.grants.find(g=>g.purpose==="L1"&&g.audience==="google");const resource=inventory.ok.resources.find(r=>r.id===oauthCredentialResourceId(binding.id));if(!existing||!resource||inventory.ok.binding.revision!==binding.revision)throw Error("gmail_existing_grant_unavailable");readGuard={bindingId:binding.id,bindingRevision:binding.revision,grantId:existing.id,grantRevision:existing.revision,resourceId:resource.id,resourceRevision:resource.revision};const writable=(existing.scopes??[]).filter(scope=>scope==="https://mail.google.com/"||/^https:\/\/www\.googleapis\.com\/auth\/gmail\.(modify|compose|send|insert|labels|settings\.basic|settings\.sharing)$/.test(scope));if(writable.some(scope=>!granted.includes(scope))&&!granted.includes("https://mail.google.com/"))throw Error("gmail_write_scope_would_be_lost")}}if(options.gmailWrite){if(!writeBinding||!("ok"in writeBinding)||writeBinding.ok.kind!=="resolved"||profile.sub!==writeBinding.ok.binding.identity.subject)throw Error("gmail_write_account_mismatch");const selection=await custodyForWrite.sourceSelection("gmail");if(!("ok"in selection)||!writeSelection||!("ok"in writeSelection)||selection.ok?.revision!==writeSelection.ok?.revision||selection.ok?.bindingId!==writeSelection.ok?.bindingId)throw Error("gmail_write_selection_changed");const current=await custodyForWrite.resolve(selection.ok?{kind:"binding",bindingId:selection.ok.bindingId}:{kind:"legacy-source",source:"gmail"});if(!("ok"in current)||current.ok.kind!=="resolved"||current.ok.binding.id!==writeBinding.ok.binding.id||current.ok.binding.revision!==writeBinding.ok.binding.revision||current.ok.binding.identity.subject!==profile.sub)throw Error("gmail_write_binding_changed")}if(closed||job.state!=="waiting-user")return;const credential={accessToken:token.access_token,...token.refresh_token?{refreshToken:token.refresh_token}:{},...client?{clientAuthentication:{method:"client_secret_post",secret:client.clientSecret}}:{},expiresAt:now()+token.expires_in*1e3,clientId,scopes:granted};await trace.step(stage,"completed");stage="credentials_saved";await trace.step(stage,"started");if(closed||job.state!=="waiting-user")return;const stored=await vault.saveConnection({source,provider:"google",account,...oidcSource?{accountId:String(profile.sub)}:source==="google-calendar"?{accountId:account}:source==="google-drive"?{accountId:String(profile.user.permissionId)}:{},scopes:granted,state:"connected",updatedAt:new Date(now()).toISOString()},credential,{signal:jobSignal,...source==="gmail"&&!options.gmailWrite&&vault.bindingCustody?{expectedCredential:readGuard}:{},...options.gmailWrite&&writeTarget&&writeGrant&&writeResource&&writeSelection&&"ok"in writeSelection?{expectedCredential:{bindingId:writeTarget.binding.id,bindingRevision:writeTarget.binding.revision,grantId:writeGrant.id,grantRevision:writeGrant.revision,resourceId:writeResource.id,resourceRevision:writeResource.revision},selectSource:{expectedSelectionRevision:writeSelection.ok?.revision??null,expectedBindingRevision:writeTarget.binding.revision}}:{}});if(!("ok"in stored))throw Error("credential_store_failed");if(closed)return;if(options.selectAccount){if(jobSignal.aborted||job.state!=="waiting-user")return;const custody=vault.bindingCustody,found=await custody.bindings(source);if(!("ok"in found))throw Error("account_selection_failed");const matches=found.ok.filter(binding=>binding.provider==="google"&&binding.identity.subject===stored.ok.accountId&&binding.account===stored.ok.account&&binding.updatedAt===stored.ok.updatedAt);if(matches.length!==1||jobSignal.aborted||job.state!=="waiting-user")throw Error("account_selection_failed");const selected=await custody.selectSourceBinding(source,matches[0].id,matches[0].revision,selectionBefore.ok?.revision??null);if(!("ok"in selected))throw Error("account_selection_failed")}if(closed||job.state!=="waiting-user")return;await trace.step(stage,"completed");await feedback?.()?.bind(stored.ok,trace.flow);if(closed||job.state!=="waiting-user")return;job.state="connected";job.account=account}catch(error2){await trace.step(stage,stop.signal.aborted?"cancelled":"failed",{error:jobStop.signal.aborted?"timeout":stage==="credentials_saved"?"storage":error2 instanceof GoogleHttpFailure?"provider":"unknown",...error2 instanceof GoogleHttpFailure&&error2.status>=100&&error2.status<=599?{statusCode:error2.status}:{}});if(!closed&&job.state==="waiting-user"){job.state="failed";job.error=error2 instanceof Error&&error2.message==="gmail_write_scope_would_be_lost"?{code:"permission_denied",message:"The existing Gmail account has write access. To preserve it, open Zortex Help and choose Grant full Gmail access."}:{code:"google_connection_failed",message:"Google authorization or account validation failed. No successful connection was confirmed."}}}finally{finish(job)}})();callbacks.add(callback);const owned=listeners.get(job.id);if(owned)owned.task=callback;const release=()=>{callbacks.delete(callback);if(owned)delete owned.task;releaseListener(job.id)};void callback.then(release,release)});try{await new Promise((done,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",done)});const address=server.address();if(!address||typeof address==="string")throw Error("callback_unavailable");redirectUri=`http://127.0.0.1:${address.port}/callback`;const url=new URL("https://accounts.google.com/o/oauth2/v2/auth");for(const[key,value]of Object.entries({response_type:"code",client_id:clientId,redirect_uri:redirectUri,scope:requestedScopes,access_type:"offline",prompt:options.selectAccount?"select_account consent":"consent",code_challenge:createHash("sha256").update(verifier).digest("base64url"),code_challenge_method:"S256",state}))url.searchParams.set(key,value);job.authorizationUrl=url.toString();const timer=setTimeout(()=>{if(job.state!=="waiting-user")return;jobStop.abort();void trace.step("waiting_for_user","failed",{error:"timeout"});job.state="failed";job.error={code:"authorization_timeout",message:"Google authorization timed out; start a new connection."};finish(job)},deadline);const cancel=()=>{if(job.state==="waiting-user")job.state="cancelled";jobStop.abort();finish(job)};listeners.set(job.id,{server,timer,cancel,detach:()=>options.signal?.removeEventListener("abort",cancel)});options.signal?.addEventListener("abort",cancel,{once:true});if(options.signal?.aborted){cancel();return ok({...job})}await trace.step("waiting_for_user","waiting",{mode:"manual",action:"request_manual"});job.instructions="Complete this source\u2019s Google authorization in the existing signed-in browser. The original state-checked callback verifies the account and saves its grant.";if(options.manualPresentation!=="return-url"){try{await trace.step("browser_opened","started");await openUrl(job.authorizationUrl);await trace.step("browser_opened","completed")}catch{await trace.step("browser_opened","failed",{error:"unknown"});job.instructions+=" The page could not be opened automatically; use authorizationUrl with the available browser tools."}}return ok({...job})}catch{await trace.step("browser_opened","failed",{error:"unknown"});job.state="failed";job.error={code:"browser_open_failed",message:"Could not open the Google consent page."};finish(job);return ok({...job})}},job(id){const job=jobs.get(id);return job?ok({...job}):fail("not_found","Authorization job not found.")},cancelJob(id){const job=jobs.get(id);if(!job)return ok({id,cleanup:"confirmed"});const resources=listeners.get(id);if(job.state==="waiting-user"){if(resources?.cancel)resources.cancel();else{job.state="cancelled";finish(job)}}else if(resources&&!resources.finished)resources.cancel?.();delete job.authorizationUrl;delete job.instructions;return ok({id,cleanup:listeners.has(id)?"pending":"confirmed"})},async accounts(source){const custody=vault.bindingCustody;if(!custody)return fail("failed_precondition","Account binding custody is unavailable.");const rows=await custody.bindings(source);if(!("ok"in rows))return rows;const accounts=[];for(const binding of rows.ok){const subject=binding.identity.subject;if(typeof subject!=="string"||!subject)continue;const grant=await custody.grantForBinding(binding.id,"L1","google");if(!("ok"in grant))return grant;accounts.push({bindingId:binding.id,account:binding.account,subject,state:binding.state,scopes:grant.ok?[...grant.ok.scopes]:[]})}return ok(accounts)},async request(source,url,options={}){if(options.signal?.aborted)return fail("aborted","Google request cancelled.");if(closed)return fail("unavailable","Google authorization is inactive.");let endpoint;try{endpoint=new URL(url)}catch{return fail("invalid_argument","Invalid Google API destination.")}if(!permitted(source,endpoint,"GET"))return fail("invalid_argument","Credential destination is outside the selected Google API.");const selection=options.bindingId?ok(async()=>ok(void 0)):await captureSelection(source);if(!("ok"in selection))return selection;const selected=await access(source,options.bindingId);if(!("ok"in selected))return selected;const selectionBefore=await selection.ok();if(!("ok"in selectionBefore))return selectionBefore;const before=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in before))return before;try{const value=await json(url,{headers:{Authorization:"Bearer "+selected.ok.credential.accessToken,Accept:"application/json"},...options.signal?{signal:options.signal}:{}});const after=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in after))return after;const selectionAfter=await selection.ok();if(!("ok"in selectionAfter))return selectionAfter;return closed?fail("unavailable","Google authorization is inactive."):options.signal?.aborted?fail("aborted","Google request cancelled."):ok(value)}catch{return fail(options.signal?.aborted?"aborted":"unavailable",options.signal?.aborted?"Google request cancelled.":"Google API request failed; reconnect if the grant has expired.")}},async requestRaw(source,url,options={}){if(options.signal?.aborted)return fail("aborted","Google request cancelled.");if(closed)return fail("unavailable","Google authorization is inactive.");const method=options.method??"GET";if(!["GET","POST","PUT","PATCH","DELETE"].includes(method)||options.body!==void 0&&(typeof options.body!=="string"||Buffer.byteLength(options.body)>2097152)||method==="GET"&&options.body!==void 0)return fail("invalid_argument","Google request method/body is outside the bounded source contract.");if(options.responseType!==void 0&&options.responseType!=="text"&&options.responseType!=="bytes")return fail("invalid_argument","Google response type must be text or bytes.");let endpoint;try{endpoint=new URL(url)}catch{return fail("invalid_argument","Invalid Google API destination.")}const readBatch=source==="gmail"&&isGmailReadBatch(endpoint,method,options.contentType,options.body);if(options.contentType!==void 0&&!/^(application\/(json|octet-stream)|text\/plain|(?:video|audio)\/[a-z0-9.+-]+)$/.test(options.contentType)&&!readBatch)return fail("invalid_argument","Google content type is outside the bounded source contract.");if(!permitted(source,endpoint,method)&&!readBatch)return fail("invalid_argument","Credential destination is outside the selected Google API.");const selection=options.bindingId?ok(async()=>ok(void 0)):await captureSelection(source,method==="GET"||readBatch);if(!("ok"in selection))return selection;const selected=await access(source,options.bindingId);if(!("ok"in selected))return selected;const credential=selected.ok.credential;if(method!=="GET"&&!readBatch){const required=source==="google-tasks"?["https://www.googleapis.com/auth/tasks"]:source==="youtube"?["https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"]:source==="google-calendar"?["https://www.googleapis.com/auth/calendar"]:[];if(!required.some(scope=>credential.scopes.includes(scope))||selected.ok.snapshot&&!required.some(scope=>selected.ok.snapshot.grant.scopes.includes(scope)))return fail("permission_denied","This source grant does not authorize mutation; use its explicit write enrollment.")}if([credential.accessToken,credential.refreshToken].some(secret=>secret&&(options.body?.includes(secret)||endpoint.href.includes(secret)||endpoint.href.includes(encodeURIComponent(secret)))))return fail("permission_denied","Credential material may not appear in a provider object or destination.");const selectionBefore=await selection.ok();if(!("ok"in selectionBefore))return selectionBefore;const before=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in before))return before;const signal=options.signal?AbortSignal.any([options.signal,stop.signal,AbortSignal.timeout(45e3)]):AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);if(signal.aborted)return fail("aborted","Google request was stopped.");try{const response=await transport(endpoint.href,{method,headers:{Authorization:"Bearer "+credential.accessToken,Accept:"*/*",...options.body!==void 0?{"Content-Type":options.contentType??"application/json"}:{}},...options.body!==void 0?{body:options.body}:{},redirect:"error",signal});const chunks=[];let size=0;const reader=response.body?.getReader();if(!reader&&response.status!==204)return fail("data_loss","Google returned an empty response stream.");if(reader)for(;;){const part=await reader.read();if(part.done)break;size+=part.value.length;if(size>2*1024*1024){await reader.cancel();return fail("resource_exhausted","Google response exceeds the 2097152-byte body I-7 return-guard limit.")}chunks.push(part.value)}const raw=Buffer.concat(chunks),body=raw.toString("utf8");if([credential.accessToken,credential.refreshToken].some(secret=>secret&&(body.includes(secret)||raw.includes(secret))))return fail("permission_denied","Google response reflected credential material; content was withheld.");const after=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in after))return method!=="GET"&&!readBatch?fail("permission_denied","Google authorization could not be confirmed after the request. The mutation may have completed; its outcome is unknown and must not be automatically retried."):after;if(closed||signal.aborted)return fail("aborted","Google request was stopped.");const selectionAfter=await selection.ok();if(!("ok"in selectionAfter))return selectionAfter;const headers={};for(const name2 of["content-type","retry-after"]){const value=response.headers.get(name2);if(value!==null)headers[name2]=value}return ok({status:response.status,body,headers,...options.responseType==="bytes"?{bytes:new Uint8Array(raw)}:{}})}catch{return fail(signal.aborted?"aborted":"unavailable",signal.aborted?"Google request cancelled.":"Google raw response could not be read.")}},close(){if(!closing){closed=true;stop.abort();for(const job of jobs.values())if(job.state==="waiting-user"){job.state="cancelled";finish(job)}closing=(async()=>{await Promise.allSettled([...callbacks,...refreshing.values()])})()}return closing}};return service}export function apply(ctx){const service=createGoogleAuth({vault:ctx.zortexVaultStore,transport:(input,options)=>(ctx.get("zortexConnectorHttp")??fetch)(input,options),tokenTransport:fetch,metrics:()=>ctx.get("zortexTelemetry"),feedback:()=>ctx.get("zortexConnectionFeedback")});ctx.provide("zortexGoogleAuth",service);ctx.effect(()=>()=>service.close())}
1
+ import{createServer}from"node:http";import{createHash,randomBytes,randomUUID}from"node:crypto";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{actionOutcome,isTransientConnectorAction}from"@zortexhq/plugin-connector-core/api";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{GOOGLE_TOKEN_URL,localGoogleDesktopClient,usesDirectGoogleOAuth}from"./desktop-client.js";import{isGmailReadBatch}from"./read-batch.js";import{createTraceRecorder}from"@zortexhq/plugin-telemetry/api";export const GOOGLE_PUBLIC_CLIENT_ID="230897508334-5f6voqm2ie55t258ksmp7odd7vh9ejvn.apps.googleusercontent.com";export const DEFAULT_GOOGLE_BROKER_URL="https://zortex-google-oauth.google-oauth-broker.workers.dev";export const name="zortex-google-auth";export const inject=["zortexVaultStore","zortexConnectorHttp"];const oauthErrors=new Set(["invalid_request","invalid_client","deleted_client","invalid_grant","unauthorized_client","unsupported_grant_type","invalid_scope","access_denied","admin_policy_enforced","org_internal","temporarily_unavailable"]);class GoogleHttpFailure extends Error{status;oauthError;constructor(status,oauthError){super("Google endpoint returned a failed status.");this.status=status;this.oauthError=oauthError}}const scopes={gmail:"https://mail.google.com/ openid email","google-drive":"https://www.googleapis.com/auth/drive","google-calendar":"https://www.googleapis.com/auth/calendar",youtube:"https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/yt-analytics.readonly openid email","google-tasks":"https://www.googleapis.com/auth/tasks openid email"};const gmailReadScope="https://www.googleapis.com/auth/gmail.readonly";const gmailReadScopes=[gmailReadScope,"https://www.googleapis.com/auth/gmail.modify","https://mail.google.com/"];const driveReadScopes=["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive"];const readScopes={gmail:gmailReadScopes,"google-drive":driveReadScopes,"google-calendar":["https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/calendar"],youtube:["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"],"google-tasks":["https://www.googleapis.com/auth/tasks.readonly","https://www.googleapis.com/auth/tasks"]};const oidc="https://openidconnect.googleapis.com/v1/userinfo";const identity={gmail:oidc,"google-drive":"https://www.googleapis.com/drive/v3/about?fields=user(permissionId,emailAddress)","google-calendar":"https://www.googleapis.com/calendar/v3/users/me/calendarList?maxResults=1",youtube:oidc,"google-tasks":oidc};const allowed={gmail:{origin:"https://gmail.googleapis.com",prefix:"/gmail/v1/"},"google-drive":{origin:"https://www.googleapis.com",prefix:"/drive/v3/"},"google-calendar":{origin:"https://www.googleapis.com",prefix:"/calendar/v3/"},youtube:{origin:"https://www.googleapis.com",prefix:"/youtube/v3/"},"google-tasks":{origin:"https://tasks.googleapis.com",prefix:"/tasks/v1/"}};const permitted=(source,endpoint,method)=>{if(endpoint.username||endpoint.password||endpoint.hash)return false;const boundary=allowed[source];if(boundary&&endpoint.origin===boundary.origin&&endpoint.pathname.startsWith(boundary.prefix))return true;if(source==="youtube"&&method==="GET"&&(endpoint.origin==="https://youtubeanalytics.googleapis.com"&&endpoint.pathname.startsWith("/v2/")||endpoint.origin==="https://youtubereporting.googleapis.com"&&endpoint.pathname.startsWith("/v1/")))return true;return source==="google-drive"&&method==="GET"&&(endpoint.origin==="https://docs.googleapis.com"&&/^\/v1\/documents\/[A-Za-z0-9_-]{1,200}$/.test(endpoint.pathname)||endpoint.origin==="https://sheets.googleapis.com"&&/^\/v4\/spreadsheets\/[A-Za-z0-9_-]{1,200}$/.test(endpoint.pathname))};export const openSystemUrl=openConnectionUrl;export function createGoogleAuth({vault,desktopClient=localGoogleDesktopClient,transport=fetch,tokenTransport=transport,openUrl=openSystemUrl,timeoutMs=6e5,now=Date.now,metrics,feedback}){const jobs=new Map,jobModes=new WeakMap,jobBindings=new WeakMap;const listeners=new Map;const stop=new AbortController;const refreshing=new Map,callbacks=new Set;let closed=false,closing;const fail=(code,message)=>businessError(code,message,"plugin");const unconsumed=failure=>({...failure,refreshOutcome:"not-consumed"});async function responseJson(response,limit){const reader=response.body?.getReader();if(!reader)throw Error("empty_response");const chunks=[];let size=0;for(;;){const part=await reader.read();if(part.done)break;size+=part.value.length;if(size>limit){await reader.cancel();throw Error("response_too_large")}chunks.push(part.value)}return JSON.parse(Buffer.concat(chunks).toString("utf8"))}async function json(url,options={},send=transport){if(closed)throw Error("google_auth_inactive");const signal=options.signal?AbortSignal.any([options.signal,stop.signal,AbortSignal.timeout(45e3)]):AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);const response=await send(url,{...options,redirect:"error",signal});if(!response.ok){let oauthError;try{const value=await responseJson(response,8192);if(value&&typeof value==="object"&&!Array.isArray(value)){const body=value;if(typeof body.error==="string"&&oauthErrors.has(body.error)&&!["access_token","refresh_token","id_token"].some(key=>key in body))oauthError=body.error}}catch{}throw new GoogleHttpFailure(response.status,oauthError)}return await responseJson(response,2*1024*1024)}function directToken(client,fields,signal){return json(GOOGLE_TOKEN_URL,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:client.clientId,client_secret:client.clientSecret,...fields}),...signal?{signal}:{}},tokenTransport)}const missingDesktopClient=source=>businessError("failed_precondition",`Zortex Google OAuth client configuration is unavailable. The product administrator must restore the registered client; reconnecting the account cannot repair product configuration. For self-managed installs, save the Google-downloaded Desktop app client JSON with {"installed":{"client_id":"<id>.apps.googleusercontent.com","client_secret":"<secret>"}} as ~/.zortex/google-oauth/${source}.json (directory 0700, file 0600), or set ZORTEX_GOOGLE_OAUTH_CLIENT_ID and ZORTEX_GOOGLE_OAUTH_CLIENT_SECRET, then retry the connection.`,"plugin");const configuredClient=async source=>{const client=await desktopClient(source);return client?.clientId===GOOGLE_PUBLIC_CLIENT_ID?void 0:client};const sealedClient=credential=>credential.clientAuthentication?.method==="client_secret_post"&&credential.clientAuthentication.secret&&(credential.clientAuthentication.expiresAt===void 0||credential.clientAuthentication.expiresAt>now())?{clientId:credential.clientId,clientSecret:credential.clientAuthentication.secret}:void 0;const originalBroker=(source,credential)=>source!=="google-tasks"&&credential.clientId===GOOGLE_PUBLIC_CLIENT_ID&&!credential.clientAuthentication;function releaseListener(id){const entry=listeners.get(id);if(entry?.finished&&entry.serverClosed&&!entry.task)listeners.delete(id)}function finish(job){const resources=listeners.get(job.id);if(resources&&!resources.finished){resources.finished=true;clearTimeout(resources.timer);resources.detach?.();resources.server.closeAllConnections();resources.server.close(error=>{resources.serverClosed=!error||error.code==="ERR_SERVER_NOT_RUNNING";releaseListener(job.id)});releaseListener(job.id)}delete job.authorizationUrl;delete job.instructions}async function access(source,bindingId){if(isTransientConnectorAction()&&!bindingId)return readAccess(source);const key=bindingId?source+":"+bindingId:source;let task=refreshing.get(key);if(!task){task=readAccess(source,bindingId);refreshing.set(key,task)}try{const result=await task;return closed?fail("unavailable","Google authorization is inactive."):result}finally{if(refreshing.get(key)===task)refreshing.delete(key)}}async function readAccess(source,bindingId){const custody=vault.bindingCustody;let found,snapshot;const choices=readScopes[source];const hasReadScope=granted=>Array.isArray(granted)&&choices.some(scope=>granted.includes(scope));const direct=usesDirectGoogleOAuth(source);const client=direct?await configuredClient(source):void 0;const requiresTasksReconnect=credential=>source==="google-tasks"&&!sealedClient(credential)&&credential.clientId!==client?.clientId;const reconnect=()=>fail("failed_precondition","Reconnect this source with its Google Desktop OAuth client.");const reconnectTasks=()=>client?reconnect():missingDesktopClient("google-tasks");const refreshConfigurationError=credential=>{if(sealedClient(credential)||originalBroker(source,credential))return;if(direct&&!client)return missingDesktopClient(source);if(!direct&&credential.clientId!==GOOGLE_PUBLIC_CLIENT_ID)return fail("failed_precondition","The original Google OAuth client configuration is unavailable. Product configuration must be restored before refreshing this grant.");if(client&&credential.clientId!==client.clientId)return missingDesktopClient(source)};const authorized=current=>current.material.kind!=="oauth"||current.resource.owner.kind!=="resident"?fail("failed_precondition","Google credential resource is not owned by the resident."):!hasReadScope(current.grant.scopes)||!hasReadScope(current.material.credential.scopes)?fail("permission_denied","The stored grant lacks the selected source read scope."):requiresTasksReconnect(current.material.credential)?reconnectTasks():ok({credential:current.material.credential,snapshot:current});if(custody){let resolution=await custody.resolve(bindingId?{kind:"binding",bindingId}:{kind:isTransientConnectorAction()&&custody.sourceSelection?"selected-source":"legacy-source",source});if(!bindingId&&"ok"in resolution&&resolution.ok.kind==="legacy-unattributed"&&custody.recoverLegacy){let expired;const verify=async(connection,credential)=>{if(requiresTasksReconnect(credential))return reconnectTasks();if(connection.provider!=="google"||!hasReadScope(connection.scopes)||!hasReadScope(credential.scopes))return fail("permission_denied","The legacy Google credential lacks the selected read scope. Open zortex help for account recovery; ordinary reconnect does not resolve mixed legacy history.");if(credential.expiresAt<=now()+6e4){if(credential.refreshToken)expired=credential;return fail("failed_precondition","The legacy Google credential has expired. Open zortex help for explicit account recovery; ordinary reconnect does not resolve mixed legacy history.")}try{return ok(await verifyLegacyIdentity(source,credential.accessToken))}catch{return fail("failed_precondition","Google could not verify the original legacy account. Open zortex help for explicit account recovery; preserve its legacy history and do not retry ordinary reconnect to clear ambiguity.")}};let recovered=await custody.recoverLegacy(source,verify);if(!("ok"in recovered)&&expired&&custody.refreshLegacyCredential){const configurationError2=refreshConfigurationError(expired);if(configurationError2)return configurationError2;const refreshedLegacy=await custody.refreshLegacyCredential(source,expired,async(connection,current2)=>{if(connection.provider!=="google"||!hasReadScope(connection.scopes)||!hasReadScope(current2.scopes)||!current2.refreshToken)return unconsumed(fail("failed_precondition","Legacy Google authorization cannot be recovered with its original grant. Open zortex help for account recovery."));return refreshed(current2,false)});if(!("ok"in refreshedLegacy))return refreshedLegacy;recovered=await custody.recoverLegacy(source,verify)}if(!("ok"in recovered))return recovered;resolution=ok({kind:"resolved",binding:recovered.ok})}if(!("ok"in resolution)||resolution.ok.kind!=="resolved")return"err"in resolution?resolution:fail("failed_precondition","Google source needs an explicitly selected account binding. Open zortex help for account recovery; ordinary reconnect does not resolve mixed legacy history.");if(resolution.ok.binding.identity.source!==source)return fail("permission_denied","The selected account binding belongs to another source.");const current=await custody.credentialSnapshot(oauthCredentialResourceId(resolution.ok.binding.id),{purpose:"L1",audience:"google"});if(!("ok"in current))return current;snapshot=current.ok;found=authorized(snapshot)}else{const legacy=await vault.credential(source);found="ok"in legacy?ok({credential:legacy.ok}):legacy}if(!("ok"in found))return"err"in found?found:fail("failed_precondition","Google source is not connected.");if(requiresTasksReconnect(found.ok.credential))return reconnectTasks();if((source==="google-tasks"||source==="youtube")&&!hasReadScope(found.ok.credential.scopes))return fail("permission_denied","The stored grant lacks the selected source read scope.");if(found.ok.credential.expiresAt>now()+6e4)return found;if(!found.ok.credential.refreshToken)return fail("unauthenticated","Google authorization expired. Start the connection flow again.");const configurationError=refreshConfigurationError(found.ok.credential);if(configurationError)return configurationError;async function refreshed(current,pinClient=true){const configurationError2=refreshConfigurationError(current);if(configurationError2)return unconsumed(configurationError2);if(!current.refreshToken)return unconsumed(fail("unauthenticated","Google authorization expired. Start the connection flow again."));if(closed||stop.signal.aborted)return unconsumed(fail("aborted","Google authorization stopped before refresh dispatch."));const issuingClient=originalBroker(source,current)?void 0:sealedClient(current)??client;try{const token=issuingClient?await directToken(issuingClient,{grant_type:"refresh_token",refresh_token:current.refreshToken}):await json(DEFAULT_GOOGLE_BROKER_URL+"/google/refresh",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({clientId:current.clientId,refreshToken:current.refreshToken})});if(typeof token.access_token!=="string"||!token.access_token||!Number.isFinite(token.expires_in)||token.expires_in<=0||token.refresh_token!==void 0&&(typeof token.refresh_token!=="string"||!token.refresh_token))throw Error("invalid_token_response");return ok({...current,...issuingClient&&pinClient?{clientAuthentication:{method:"client_secret_post",secret:issuingClient.clientSecret}}:{},accessToken:token.access_token,...token.refresh_token!==void 0?{refreshToken:token.refresh_token}:{},expiresAt:now()+token.expires_in*1e3})}catch(error){if(error instanceof GoogleHttpFailure&&error.oauthError){const code=error.oauthError;const failure=code==="invalid_grant"?fail("unauthenticated","Google rejected the saved refresh grant. Reconnect this source with the same account."):["invalid_scope","access_denied","admin_policy_enforced","org_internal"].includes(code)?fail("permission_denied","Google refused the requested authorization scope or account policy."):code==="temporarily_unavailable"?{err:{...fail("unavailable","Google temporarily refused credential refresh; retry under the existing grant.").err,retryability:"transient"}}:fail("failed_precondition","Google rejected the OAuth client configuration or refresh request. Restore the original product client configuration before retrying.");return issuingClient?unconsumed(failure):failure}return fail(stop.signal.aborted?"aborted":"unavailable","Google authorization refresh did not complete; its token outcome is unknown.")}}if(custody&&snapshot){const stored2=await custody.refreshResource(snapshot,{kind:"resident"},async current2=>{const permitted2=authorized(current2);if(!("ok"in permitted2))return"err"in permitted2?unconsumed(permitted2):permitted2;const next2=await refreshed(permitted2.ok.credential);return"ok"in next2?ok({kind:"oauth",credential:next2.ok}):next2});if("ok"in stored2)return authorized(stored2.ok);if(!("err"in stored2)||stored2.err.code!=="failed_precondition")return stored2;const current=await custody.credentialSnapshot(snapshot.resource.id,{purpose:"L1",audience:"google"});if(!("ok"in current))return current;const winner=authorized(current.ok);return current.ok.resource.revision>snapshot.resource.revision&&"ok"in winner&&winner.ok.credential.expiresAt>now()+6e4?winner:stored2}const next=await refreshed(found.ok.credential);if(!("ok"in next))return"err"in next?{err:next.err}:next;const stored=await vault.updateCredential(source,next.ok);return"ok"in stored?ok({credential:next.ok}):"err"in stored?stored:fail("internal","Credential update was not confirmed.")}async function checkAccess(source,selected,bindingId){const custody=vault.bindingCustody,expected=selected.snapshot;if(!custody)return ok(void 0);const changed=()=>fail("permission_denied","The selected Google account, grant or credential changed during the request; its response was withheld.");if(!expected)return changed();const current=await custody.credentialSnapshot(expected.resource.id,{purpose:"L1",audience:"google"});if(!("ok"in current))return current;const resolved=await custody.resolve(bindingId?{kind:"binding",bindingId}:{kind:isTransientConnectorAction()&&custody.sourceSelection?"selected-source":"legacy-source",source});if(!("ok"in resolved))return resolved;if(resolved.ok.kind!=="resolved"||resolved.ok.binding.id!==expected.binding.id||resolved.ok.binding.revision!==expected.binding.revision)return changed();return current.ok.binding.id===expected.binding.id&&current.ok.binding.revision===expected.binding.revision&&current.ok.grant.id===expected.grant.id&&current.ok.grant.revision===expected.grant.revision&&current.ok.grant.scopeEpoch===expected.grant.scopeEpoch&&current.ok.resource.id===expected.resource.id&&current.ok.resource.revision===expected.resource.revision?ok(void 0):changed()}async function captureSelection(source,readOnly=true){const custody=vault.bindingCustody;if(!custody?.sourceSelection)return ok(async()=>ok(void 0));const found=await custody.sourceSelection(source);if(!("ok"in found))return found;if(found.ok&&!isTransientConnectorAction())return fail("failed_precondition","This explicitly recovered account supports transient L1 reads. Source-only history sync remains disabled; use zortex help to read the selected account.");if(found.ok&&!readOnly)return fail("permission_denied","Explicit account recovery authorizes bounded reads only.");const expected=found.ok;return ok(async()=>{const current=await custody.sourceSelection(source);if(!("ok"in current))return current;return current.ok?.bindingId===expected?.bindingId&&current.ok?.revision===expected?.revision?ok(void 0):fail("permission_denied","The selected account changed during this request; its response was withheld.")})}async function verifyLegacyIdentity(source,accessToken){const headers={Authorization:"Bearer "+accessToken};let profile=await json(identity[source],{headers});if(source==="google-drive"){const subject=profile.user?.permissionId,account=profile.user?.emailAddress??subject;if(typeof subject!=="string"||!subject.trim()||subject.length>500||typeof account!=="string"||!account)throw Error("drive_identity_not_confirmed");return{accountId:subject,account}}if(source==="google-calendar"){const seen=new Set;for(let page=0;page<20;page++){if(!Array.isArray(profile.items)||profile.items.some(row=>!row||typeof row!=="object"))throw Error("invalid_calendar_identity");const primary=profile.items.filter(row=>row.primary===true);if(primary.length>1)throw Error("ambiguous_calendar_identity");if(primary.length===1){const subject=primary[0].id;if(typeof subject!=="string"||!subject.trim()||subject.length>500)throw Error("invalid_calendar_identity");return{accountId:subject,account:subject}}const next=profile.nextPageToken;if(typeof next!=="string"||!next||next.length>8192||seen.has(next))throw Error("primary_calendar_not_found");seen.add(next);const url=new URL("https://www.googleapis.com/calendar/v3/users/me/calendarList");url.searchParams.set("maxResults","250");url.searchParams.set("pageToken",next);url.searchParams.set("fields","items(id,primary),nextPageToken");profile=await json(url.href,{headers})}throw Error("calendar_identity_budget_exceeded")}if(profile.email_verified!==true||typeof profile.sub!=="string"||!/^[\x21-\x7e]{1,255}$/.test(profile.sub)||typeof profile.email!=="string"||!profile.email)throw Error("account_not_confirmed");return{accountId:profile.sub,account:profile.email}}const service={async connect(source,options={}){const automatic=options.automatic===true;options={...options,automatic};if(options.signal?.aborted)return fail("aborted","Google authorization cancelled.");if(closed)return fail("unavailable","Google authorization is inactive.");if(!Object.hasOwn(scopes,source))return fail("invalid_argument","Unknown Google source.");if(options.selectAccount!==void 0&&(options.selectAccount!==true||options.automatic!==false))return fail("invalid_argument","Explicit account selection requires manual recovery.");if(options.gmailWrite!==void 0&&(options.gmailWrite!==true||source!=="gmail"||options.automatic!==false||options.selectAccount||options.reauthorize))return fail("invalid_argument","Gmail write consent requires an explicit same-account manual authorization.");if(automatic&&options.reauthorize)return fail("invalid_argument","Automatic connection does not replace saved authority.");let automaticRecovery,recoverySelection=null;const bindingTarget=options.expectedBinding?.kind==="binding"?options.expectedBinding.bindingId:void 0;if(options.expectedBinding&&(!automatic||options.expectedBinding.kind!=="binding"&&options.expectedBinding.source!==source))return fail("failed_precondition","A pinned Google recovery target must identify this source and use automatic same-account recovery.");if(automatic){const custody=vault.bindingCustody;if(!custody?.authoritySnapshot)return fail("failed_precondition","Automatic Google connection requires installed coherent credential custody.");const captured=await custody.authoritySnapshot(options.expectedBinding??{kind:"selected-source",source});if(!("ok"in captured))return captured;if(captured.ok.source!==source)return fail("permission_denied","The pinned account belongs to another source.");const resolved=captured.ok.resolution;if(resolved.kind==="ambiguous_account")return fail("failed_precondition","Automatic Google connection requires a selected or explicitly targeted account.");const saved=resolved.kind==="resolved"?resolved.binding:captured.ok.legacy;if(saved){if(saved.state!=="connected")return fail("permission_denied","This source was disconnected; automatic connection cannot restore its authority.");const exactBinding=resolved.kind==="resolved"?resolved.binding.id:void 0;const existing=await access(source,exactBinding);if("ok"in existing){if(options.signal?.aborted)return fail("aborted","Google authorization cancelled.");if(!bindingTarget){const current2=await custody.authoritySnapshot(options.expectedBinding??{kind:"selected-source",source});if(!("ok"in current2)||current2.ok.selection?.bindingId!==captured.ok.selection?.bindingId||current2.ok.selection?.revision!==captured.ok.selection?.revision)return fail("permission_denied","The selected Google account changed during access recovery.")}const account=existing.ok.snapshot?.binding.account??saved.account;const job2=[...jobs.values()].find(row=>row.source===source&&row.state==="connected"&&row.account===account)??{id:randomUUID(),source,state:"connected",startedAt:new Date(now()).toISOString(),account};jobs.set(job2.id,job2);return ok({...job2})}if(!("err"in existing)||existing.err.code!=="unauthenticated")return existing;if(resolved.kind!=="resolved"||resolved.binding.provider!=="google"||!resolved.binding.identity.subject)return fail("failed_precondition","Automatic Google recovery requires one verified account.");const inventory=captured.ok.inventory;const originalGrant=inventory?.grants.find(grant=>grant.purpose==="L1"&&grant.audience==="google");const originalResource=inventory?.resources.find(resource=>resource.id===oauthCredentialResourceId(resolved.binding.id));const current=await custody.credentialSnapshot(oauthCredentialResourceId(resolved.binding.id),{purpose:"L1",audience:"google"});if(!("ok"in current))return current;const snapshot=current.ok;if(snapshot.binding.revision!==resolved.binding.revision||snapshot.grant.id!==originalGrant?.id||snapshot.grant.revision!==originalGrant.revision||snapshot.resource.id!==originalResource?.id||snapshot.resource.revision!==originalResource.revision||snapshot.material.kind!=="oauth"||snapshot.resource.owner.kind!=="resident")return fail("failed_precondition","Google credential custody changed before recovery.");const credential=snapshot.material.credential;if(!readScopes[source].some(scope=>snapshot.grant.scopes.includes(scope))||snapshot.grant.scopes.some(scope=>!credential.scopes.includes(scope)))return fail("permission_denied","The saved Google grant cannot authorize the requested source.");recoverySelection=bindingTarget?null:captured.ok.selection;if(!bindingTarget){const currentAuthority=await custody.authoritySnapshot(options.expectedBinding??{kind:"selected-source",source});if(!("ok"in currentAuthority))return currentAuthority;if(currentAuthority.ok.selection?.bindingId!==recoverySelection?.bindingId||currentAuthority.ok.selection?.revision!==recoverySelection?.revision)return fail("failed_precondition","The selected Google account changed before recovery.")}automaticRecovery={credential,snapshot}}}const custodyForWrite=options.gmailWrite?vault.bindingCustody:void 0;if(options.gmailWrite&&(!custodyForWrite?.sourceSelection||!custodyForWrite.resolve))return fail("failed_precondition","A selected Gmail account is required before requesting write access.");const writeSelection=options.gmailWrite?await custodyForWrite.sourceSelection("gmail"):void 0;if(writeSelection&&!("ok"in writeSelection))return writeSelection;const writeBinding=options.gmailWrite?await custodyForWrite.resolve(writeSelection&&"ok"in writeSelection&&writeSelection.ok?{kind:"binding",bindingId:writeSelection.ok.bindingId}:{kind:"legacy-source",source:"gmail"}):void 0;if(writeBinding&&(!("ok"in writeBinding)||writeBinding.ok.kind!=="resolved"||writeBinding.ok.binding.identity.source!=="gmail"||writeBinding.ok.binding.provider!=="google"||!writeBinding.ok.binding.identity.subject))return fail("failed_precondition","Select a verified Gmail account before requesting write access.");const writeInventory=writeBinding&&"ok"in writeBinding&&writeBinding.ok.kind==="resolved"?await custodyForWrite.bindingInventory(writeBinding.ok.binding.id):void 0;if(options.gmailWrite&&(!writeInventory||!("ok"in writeInventory)||!writeInventory.ok))return fail("failed_precondition","Gmail credential custody is unavailable.");const writeTarget=writeInventory&&"ok"in writeInventory?writeInventory.ok:void 0;const writeGrant=writeTarget?.grants.find(g=>g.purpose==="L1"&&g.audience==="google");const writeResource=writeTarget?.resources.find(r=>r.id===oauthCredentialResourceId(writeTarget.binding.id));if(options.gmailWrite&&(!writeTarget||!writeGrant||!writeResource||!writeBinding||!("ok"in writeBinding)||writeBinding.ok.kind!=="resolved"||writeTarget.binding.revision!==writeBinding.ok.binding.revision))return fail("failed_precondition","Gmail credential custody changed.");if(options.selectAccount&&(!vault.bindingCustody?.sourceSelection||!vault.bindingCustody.selectSourceBinding))return fail("failed_precondition","This Vault does not support explicit account recovery.");const selectionBefore=options.selectAccount?await vault.bindingCustody.sourceSelection(source):ok(null);if(!("ok"in selectionBefore))return selectionBefore;const direct=usesDirectGoogleOAuth(source);const brokerRecovery=automaticRecovery&&originalBroker(source,automaticRecovery.credential);const client=automaticRecovery?sealedClient(automaticRecovery.credential)??(direct&&!brokerRecovery?await configuredClient(source):void 0):direct?await configuredClient(source):void 0;if(direct&&!client&&!brokerRecovery)return missingDesktopClient(source);const clientId=client?.clientId??GOOGLE_PUBLIC_CLIENT_ID;if(automaticRecovery&&clientId!==automaticRecovery.credential.clientId)return fail("failed_precondition","The original Google OAuth client must be restored before recovering this account.");const requestedScopes=automaticRecovery?automaticRecovery.snapshot.grant.scopes.join(" "):source==="gmail"&&!options.gmailWrite?`${gmailReadScope} openid email`:scopes[source];const interactionMode=options.manualPresentation==="return-url"?"manual-return-url":"manual-open";const deadline=timeoutMs;if(closed)return fail("unavailable","Google authorization is inactive.");if(!Object.hasOwn(scopes,source))return fail("invalid_argument","Unknown Google source.");const running=[...jobs.values()].find(job2=>job2.source===source&&job2.state==="waiting-user");if(running&&(options.selectAccount||options.gmailWrite))return fail("failed_precondition","Wait for the current authorization to finish before explicit account recovery.");const recoveryBinding=automaticRecovery?.snapshot.binding.id??bindingTarget;if(running&&jobBindings.get(running)!==recoveryBinding)return fail("failed_precondition","Another account owns the active Google authorization transaction.");if(running)return jobModes.get(running)!==interactionMode?fail("failed_precondition","Previous source authorization uses a different interaction mode. Wait for its owned cleanup."):ok({...running});if([...listeners].some(([id])=>jobs.get(id)?.source===source))return fail("failed_precondition","Previous source authorization still owns active work. Wait for cleanup.");const job={id:randomUUID(),source,state:"waiting-user",startedAt:new Date(now()).toISOString()};jobModes.set(job,interactionMode);jobBindings.set(job,recoveryBinding);jobs.set(job.id,job);const jobStop=new AbortController,jobSignal=AbortSignal.any([stop.signal,jobStop.signal,...options.signal?[options.signal]:[]]);const trace=createTraceRecorder(metrics,source);let stage="callback_received";await trace.step("authorization_started","started");const verifier=randomBytes(48).toString("base64url"),state=randomBytes(24).toString("base64url");let used=false;let redirectUri="";const server=createServer((request,response)=>{const url=new URL(request.url??"/",redirectUri);if(request.method!=="GET"||url.pathname!=="/callback"){response.writeHead(404).end("Not found.");return}if(url.searchParams.get("state")!==state){response.writeHead(400).end("Invalid authorization state.");return}if(used){response.writeHead(409).end("Authorization callback already received.");return}const code=url.searchParams.get("code"),error=url.searchParams.get("error");if(error||!code){used=true;job.state="failed";job.error={code:"authorization_denied",message:"Google authorization was not completed."};void trace.step("callback_received","failed",{error:"denied"});response.writeHead(400).end("Authorization was not completed.");finish(job);return}used=true;response.writeHead(200,{"Content-Type":"text/plain; charset=utf-8"}).end("Authorization received. Zortex is validating the connection. You may close this page.");const callback=(async()=>{try{await trace.step("callback_received","completed");stage="token_exchange";await trace.step(stage,"started");const exchange=()=>client?directToken(client,{grant_type:"authorization_code",code,code_verifier:verifier,redirect_uri:redirectUri},jobSignal):json(DEFAULT_GOOGLE_BROKER_URL+"/google/token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({clientId,code,codeVerifier:verifier,redirectUri}),signal:jobSignal});const token=await exchange();if(!token.access_token||!Number.isFinite(token.expires_in))throw Error("invalid_token_response");const granted=(token.scope??requestedScopes).split(" ");if(automaticRecovery){const normalized=values=>[...new Set(values.map(scope=>scope==="https://www.googleapis.com/auth/userinfo.email"?"email":scope))].sort().join(" ");if(normalized(granted)!==normalized(automaticRecovery.snapshot.grant.scopes))throw Error("google_recovery_scope_changed")}if(!automaticRecovery&&(source==="google-drive"?!driveReadScopes.some(scope=>granted.includes(scope)):source==="gmail"?!((options.gmailWrite?granted.includes("https://mail.google.com/"):gmailReadScopes.some(scope=>granted.includes(scope)))&&granted.includes("openid")&&(granted.includes("email")||granted.includes("https://www.googleapis.com/auth/userinfo.email"))):!requestedScopes.split(" ").every(scope=>granted.includes(scope)||scope==="email"&&granted.includes("https://www.googleapis.com/auth/userinfo.email"))))throw Error("required_scope_missing");await trace.step(stage,"completed");stage="identity_verified";await trace.step(stage,"started");let profile=await json(identity[source],{headers:{Authorization:"Bearer "+token.access_token},signal:jobSignal});let calendarAccount;if(source==="google-calendar"){const seen=new Set;for(let page=0;page<50;page++){if(closed||job.state!=="waiting-user")throw Error("connection_cancelled");if(!Array.isArray(profile.items)||profile.items.some(row=>!row||typeof row!=="object"))throw Error("invalid_calendar_identity");const primary=profile.items.filter(row=>row.primary===true);if(primary.length>1)throw Error("ambiguous_calendar_identity");if(primary.length===1){if(typeof primary[0].id!=="string"||!primary[0].id.trim()||primary[0].id.length>500)throw Error("invalid_calendar_identity");calendarAccount=primary[0].id;break}const next=profile.nextPageToken;if(next===void 0)throw Error("primary_calendar_not_found");if(typeof next!=="string"||!next||next.length>8192||seen.has(next))throw Error("invalid_calendar_identity_cursor");seen.add(next);const url2=new URL("https://www.googleapis.com/calendar/v3/users/me/calendarList");url2.searchParams.set("maxResults","250");url2.searchParams.set("pageToken",next);url2.searchParams.set("fields","items(id,primary),nextPageToken");profile=await json(url2.href,{headers:{Authorization:"Bearer "+token.access_token},signal:jobSignal})}if(!calendarAccount)throw Error("calendar_identity_budget_exceeded")}const oidcSource=source==="gmail"||source==="youtube"||source==="google-tasks";const account=source==="google-drive"?profile.user?.emailAddress??profile.user?.permissionId:oidcSource?profile.email:calendarAccount;if(source==="google-drive"&&(typeof profile.user?.permissionId!=="string"||!profile.user.permissionId.trim()||profile.user.permissionId.length>500))throw Error("drive_identity_not_confirmed");if(oidcSource&&(profile.email_verified!==true||typeof profile.sub!=="string"||!/^[\x21-\x7e]{1,255}$/.test(profile.sub)))throw Error("account_not_confirmed");if(typeof account!=="string"||!account)throw Error("account_not_confirmed");if(automaticRecovery){const subject=oidcSource?profile.sub:source==="google-drive"?profile.user.permissionId:calendarAccount;if(subject!==automaticRecovery.snapshot.binding.identity.subject)throw Error("google_recovery_account_mismatch");const current=await checkAccess(source,automaticRecovery,automaticRecovery.snapshot.binding.id),selection=bindingTarget?void 0:await vault.bindingCustody.sourceSelection?.(source);if(!("ok"in current)||selection&&(!("ok"in selection)||selection.ok?.bindingId!==recoverySelection?.bindingId||selection.ok?.revision!==recoverySelection?.revision))throw Error("google_recovery_authority_changed")}let readGuard=null;if(source==="gmail"&&!options.gmailWrite&&vault.bindingCustody){const known=await vault.bindingCustody.bindings("gmail");if(!("ok"in known))throw Error("gmail_existing_grant_unavailable");const previous=known.ok.filter(binding=>binding.provider==="google"&&binding.identity.subject===profile.sub);if(previous.length>1)throw Error("gmail_existing_grant_unavailable");readGuard=null;for(const binding of previous){const inventory=await vault.bindingCustody.bindingInventory(binding.id);if(!("ok"in inventory)||!inventory.ok)throw Error("gmail_existing_grant_unavailable");const existing=inventory.ok.grants.find(g=>g.purpose==="L1"&&g.audience==="google");const resource=inventory.ok.resources.find(r=>r.id===oauthCredentialResourceId(binding.id));if(!existing||!resource||inventory.ok.binding.revision!==binding.revision)throw Error("gmail_existing_grant_unavailable");readGuard={bindingId:binding.id,bindingRevision:binding.revision,grantId:existing.id,grantRevision:existing.revision,resourceId:resource.id,resourceRevision:resource.revision};const writable=(existing.scopes??[]).filter(scope=>scope==="https://mail.google.com/"||/^https:\/\/www\.googleapis\.com\/auth\/gmail\.(modify|compose|send|insert|labels|settings\.basic|settings\.sharing)$/.test(scope));if(writable.some(scope=>!granted.includes(scope))&&!granted.includes("https://mail.google.com/"))throw Error("gmail_write_scope_would_be_lost")}}if(options.gmailWrite){if(!writeBinding||!("ok"in writeBinding)||writeBinding.ok.kind!=="resolved"||profile.sub!==writeBinding.ok.binding.identity.subject)throw Error("gmail_write_account_mismatch");const selection=await custodyForWrite.sourceSelection("gmail");if(!("ok"in selection)||!writeSelection||!("ok"in writeSelection)||selection.ok?.revision!==writeSelection.ok?.revision||selection.ok?.bindingId!==writeSelection.ok?.bindingId)throw Error("gmail_write_selection_changed");const current=await custodyForWrite.resolve(selection.ok?{kind:"binding",bindingId:selection.ok.bindingId}:{kind:"legacy-source",source:"gmail"});if(!("ok"in current)||current.ok.kind!=="resolved"||current.ok.binding.id!==writeBinding.ok.binding.id||current.ok.binding.revision!==writeBinding.ok.binding.revision||current.ok.binding.identity.subject!==profile.sub)throw Error("gmail_write_binding_changed")}if(closed||job.state!=="waiting-user")return;const credential={accessToken:token.access_token,...token.refresh_token?{refreshToken:token.refresh_token}:{},...client?{clientAuthentication:{method:"client_secret_post",secret:client.clientSecret}}:{},expiresAt:now()+token.expires_in*1e3,clientId,scopes:granted};const recovery=automaticRecovery?.snapshot;await trace.step(stage,"completed");stage="credentials_saved";await trace.step(stage,"started");if(closed||job.state!=="waiting-user")return;const stored=await vault.saveConnection({source,provider:"google",account,...oidcSource?{accountId:String(profile.sub)}:source==="google-calendar"?{accountId:account}:source==="google-drive"?{accountId:String(profile.user.permissionId)}:{},scopes:granted,state:"connected",updatedAt:new Date(now()).toISOString()},credential,{signal:jobSignal,...recovery?{expectedCredential:{bindingId:recovery.binding.id,bindingRevision:recovery.binding.revision,grantId:recovery.grant.id,grantRevision:recovery.grant.revision,resourceId:recovery.resource.id,resourceRevision:recovery.resource.revision},...!bindingTarget?{expectedSelectionRevision:recoverySelection?.revision??null}:{}}:automatic?{expectedCredential:null,expectedSelectionRevision:null}:source==="gmail"&&!options.gmailWrite&&vault.bindingCustody?{expectedCredential:readGuard}:{},...options.gmailWrite&&writeTarget&&writeGrant&&writeResource&&writeSelection&&"ok"in writeSelection?{expectedCredential:{bindingId:writeTarget.binding.id,bindingRevision:writeTarget.binding.revision,grantId:writeGrant.id,grantRevision:writeGrant.revision,resourceId:writeResource.id,resourceRevision:writeResource.revision},selectSource:{expectedSelectionRevision:writeSelection.ok?.revision??null,expectedBindingRevision:writeTarget.binding.revision}}:{}});if(!("ok"in stored))throw Error("credential_store_failed");if(closed)return;if(options.selectAccount){if(jobSignal.aborted||job.state!=="waiting-user")return;const custody=vault.bindingCustody,found=await custody.bindings(source);if(!("ok"in found))throw Error("account_selection_failed");const matches=found.ok.filter(binding=>binding.provider==="google"&&binding.identity.subject===stored.ok.accountId&&binding.account===stored.ok.account&&binding.updatedAt===stored.ok.updatedAt);if(matches.length!==1||jobSignal.aborted||job.state!=="waiting-user")throw Error("account_selection_failed");const selected=await custody.selectSourceBinding(source,matches[0].id,matches[0].revision,selectionBefore.ok?.revision??null);if(!("ok"in selected))throw Error("account_selection_failed")}if(closed||job.state!=="waiting-user")return;await trace.step(stage,"completed");await feedback?.()?.bind(stored.ok,trace.flow);if(closed||job.state!=="waiting-user")return;job.state="connected";job.account=account}catch(error2){await trace.step(stage,stop.signal.aborted?"cancelled":"failed",{error:jobStop.signal.aborted?"timeout":stage==="credentials_saved"?"storage":error2 instanceof GoogleHttpFailure?"provider":"unknown",...error2 instanceof GoogleHttpFailure&&error2.status>=100&&error2.status<=599?{statusCode:error2.status}:{}});if(!closed&&job.state==="waiting-user"){job.state="failed";job.error=error2 instanceof Error&&error2.message==="gmail_write_scope_would_be_lost"?{code:"permission_denied",message:"The existing Gmail account has write access. To preserve it, open Zortex Help and choose Grant full Gmail access."}:{code:"google_connection_failed",message:"Google authorization or account validation failed. No successful connection was confirmed."}}}finally{finish(job)}})();callbacks.add(callback);const owned=listeners.get(job.id);if(owned)owned.task=callback;const release=()=>{callbacks.delete(callback);if(owned)delete owned.task;releaseListener(job.id)};void callback.then(release,release)});try{await new Promise((done,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",done)});const address=server.address();if(!address||typeof address==="string")throw Error("callback_unavailable");redirectUri=`http://127.0.0.1:${address.port}/callback`;const url=new URL("https://accounts.google.com/o/oauth2/v2/auth");for(const[key,value]of Object.entries({response_type:"code",client_id:clientId,redirect_uri:redirectUri,scope:requestedScopes,access_type:"offline",prompt:options.selectAccount?"select_account consent":"consent",code_challenge:createHash("sha256").update(verifier).digest("base64url"),code_challenge_method:"S256",state}))url.searchParams.set(key,value);job.authorizationUrl=url.toString();const timer=setTimeout(()=>{if(job.state!=="waiting-user")return;jobStop.abort();void trace.step("waiting_for_user","failed",{error:"timeout"});job.state="failed";job.error={code:"authorization_timeout",message:"Google authorization timed out; start a new connection."};finish(job)},deadline);const cancel=()=>{if(job.state==="waiting-user")job.state="cancelled";jobStop.abort();finish(job)};listeners.set(job.id,{server,timer,cancel,detach:()=>options.signal?.removeEventListener("abort",cancel)});options.signal?.addEventListener("abort",cancel,{once:true});if(options.signal?.aborted){cancel();return ok({...job})}await trace.step("waiting_for_user","waiting",{mode:automatic?"automatic":"manual",...!automatic?{action:"request_manual"}:{}});job.instructions="Complete this source\u2019s Google authorization in the existing signed-in browser. The original state-checked callback verifies the account and saves its grant.";if(options.manualPresentation!=="return-url"){try{await trace.step("browser_opened","started");await openUrl(job.authorizationUrl);await trace.step("browser_opened","completed")}catch{await trace.step("browser_opened","failed",{error:"unknown"});job.instructions+=" The page could not be opened automatically; use authorizationUrl with the available browser tools."}}return ok({...job})}catch{await trace.step("browser_opened","failed",{error:"unknown"});job.state="failed";job.error={code:"browser_open_failed",message:"Could not open the Google consent page."};finish(job);return ok({...job})}},job(id){const job=jobs.get(id);return job?ok({...job}):fail("not_found","Authorization job not found.")},cancelJob(id){const job=jobs.get(id);if(!job)return ok({id,cleanup:"confirmed"});const resources=listeners.get(id);if(job.state==="waiting-user"){if(resources?.cancel)resources.cancel();else{job.state="cancelled";finish(job)}}else if(resources&&!resources.finished)resources.cancel?.();delete job.authorizationUrl;delete job.instructions;return ok({id,cleanup:listeners.has(id)?"pending":"confirmed"})},async accounts(source){const custody=vault.bindingCustody;if(!custody)return fail("failed_precondition","Account binding custody is unavailable.");const rows=await custody.bindings(source);if(!("ok"in rows))return rows;const accounts=[];for(const binding of rows.ok){const subject=binding.identity.subject;if(typeof subject!=="string"||!subject)continue;const grant=await custody.grantForBinding(binding.id,"L1","google");if(!("ok"in grant))return grant;accounts.push({bindingId:binding.id,account:binding.account,subject,state:binding.state,scopes:grant.ok?[...grant.ok.scopes]:[]})}return ok(accounts)},async request(source,url,options={}){if(options.signal?.aborted)return fail("aborted","Google request cancelled.");if(closed)return fail("unavailable","Google authorization is inactive.");let endpoint;try{endpoint=new URL(url)}catch{return fail("invalid_argument","Invalid Google API destination.")}if(!permitted(source,endpoint,"GET"))return fail("invalid_argument","Credential destination is outside the selected Google API.");const selection=options.bindingId?ok(async()=>ok(void 0)):await captureSelection(source);if(!("ok"in selection))return selection;const selected=await access(source,options.bindingId);if(!("ok"in selected))return selected;const selectionBefore=await selection.ok();if(!("ok"in selectionBefore))return selectionBefore;const before=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in before))return before;try{const value=await json(url,{headers:{Authorization:"Bearer "+selected.ok.credential.accessToken,Accept:"application/json"},...options.signal?{signal:options.signal}:{}});const after=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in after))return after;const selectionAfter=await selection.ok();if(!("ok"in selectionAfter))return selectionAfter;return closed?fail("unavailable","Google authorization is inactive."):options.signal?.aborted?fail("aborted","Google request cancelled."):ok(value)}catch{return fail(options.signal?.aborted?"aborted":"unavailable",options.signal?.aborted?"Google request cancelled.":"Google API request failed; reconnect if the grant has expired.")}},async requestRaw(source,url,options={}){let dispatched=false;try{const result=await(async()=>{if(options.signal?.aborted)return fail("aborted","Google request cancelled.");if(closed)return fail("unavailable","Google authorization is inactive.");const method=options.method??"GET";if(!["GET","POST","PUT","PATCH","DELETE"].includes(method)||options.body!==void 0&&(typeof options.body!=="string"||Buffer.byteLength(options.body)>2097152)||method==="GET"&&options.body!==void 0)return fail("invalid_argument","Google request method/body is outside the bounded source contract.");if(options.responseType!==void 0&&options.responseType!=="text"&&options.responseType!=="bytes")return fail("invalid_argument","Google response type must be text or bytes.");let endpoint;try{endpoint=new URL(url)}catch{return fail("invalid_argument","Invalid Google API destination.")}const readBatch=source==="gmail"&&isGmailReadBatch(endpoint,method,options.contentType,options.body);if(options.contentType!==void 0&&!/^(application\/(json|octet-stream)|text\/plain|(?:video|audio)\/[a-z0-9.+-]+)$/.test(options.contentType)&&!readBatch)return fail("invalid_argument","Google content type is outside the bounded source contract.");if(!permitted(source,endpoint,method)&&!readBatch)return fail("invalid_argument","Credential destination is outside the selected Google API.");const selection=options.bindingId?ok(async()=>ok(void 0)):await captureSelection(source,method==="GET"||readBatch);if(!("ok"in selection))return selection;const selected=await access(source,options.bindingId);if(!("ok"in selected))return selected;const credential=selected.ok.credential;if(method!=="GET"&&!readBatch){const required=source==="google-tasks"?["https://www.googleapis.com/auth/tasks"]:source==="youtube"?["https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"]:source==="google-calendar"?["https://www.googleapis.com/auth/calendar"]:[];if(!required.some(scope=>credential.scopes.includes(scope))||selected.ok.snapshot&&!required.some(scope=>selected.ok.snapshot.grant.scopes.includes(scope)))return fail("permission_denied","This source grant does not authorize mutation; use its explicit write enrollment.")}if([credential.accessToken,credential.refreshToken].some(secret=>secret&&(options.body?.includes(secret)||endpoint.href.includes(secret)||endpoint.href.includes(encodeURIComponent(secret)))))return fail("permission_denied","Credential material may not appear in a provider object or destination.");const selectionBefore=await selection.ok();if(!("ok"in selectionBefore))return selectionBefore;const before=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in before))return before;const signal=options.signal?AbortSignal.any([options.signal,stop.signal,AbortSignal.timeout(45e3)]):AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);if(signal.aborted)return fail("aborted","Google request was stopped.");try{dispatched=true;const response=await transport(endpoint.href,{method,headers:{Authorization:"Bearer "+credential.accessToken,Accept:"*/*",...options.body!==void 0?{"Content-Type":options.contentType??"application/json"}:{}},...options.body!==void 0?{body:options.body}:{},redirect:"error",signal});const chunks=[];let size=0;const reader=response.body?.getReader();if(!reader&&response.status!==204)return fail("data_loss","Google returned an empty response stream.");if(reader)for(;;){const part=await reader.read();if(part.done)break;size+=part.value.length;if(size>2*1024*1024){await reader.cancel();return fail("resource_exhausted","Google response exceeds the 2097152-byte body I-7 return-guard limit.")}chunks.push(part.value)}const raw=Buffer.concat(chunks),body=raw.toString("utf8");if([credential.accessToken,credential.refreshToken].some(secret=>secret&&(body.includes(secret)||raw.includes(secret))))return fail("permission_denied","Google response reflected credential material; content was withheld.");const after=await checkAccess(source,selected.ok,options.bindingId);if(!("ok"in after))return method!=="GET"&&!readBatch?fail("permission_denied","Google authorization could not be confirmed after the request. The mutation may have completed; its outcome is unknown and must not be automatically retried."):after;if(closed||signal.aborted)return fail("aborted","Google request was stopped.");const selectionAfter=await selection.ok();if(!("ok"in selectionAfter))return selectionAfter;const headers={};for(const name2 of["content-type","retry-after"]){const value=response.headers.get(name2);if(value!==null)headers[name2]=value}return ok({status:response.status,body,headers,...options.responseType==="bytes"?{bytes:new Uint8Array(raw)}:{}})}catch{return fail(signal.aborted?"aborted":"unavailable",signal.aborted?"Google request cancelled.":"Google raw response could not be read.")}})();return actionOutcome(result,dispatched?"unknown":"not_applied")}catch{return actionOutcome(fail(options.signal?.aborted?"aborted":"unavailable","Google request could not finish."),dispatched?"unknown":"not_applied")}},close(){if(!closing){closed=true;stop.abort();for(const job of jobs.values())if(job.state==="waiting-user"){job.state="cancelled";finish(job)}closing=(async()=>{await Promise.allSettled([...callbacks,...refreshing.values()])})()}return closing}};return service}export function apply(ctx){const service=createGoogleAuth({vault:ctx.zortexVaultStore,transport:(input,options)=>(ctx.get("zortexConnectorHttp")??fetch)(input,options),tokenTransport:fetch,metrics:()=>ctx.get("zortexTelemetry"),feedback:()=>ctx.get("zortexConnectionFeedback")});ctx.provide("zortexGoogleAuth",service);ctx.effect(()=>()=>service.close())}
@@ -1 +1 @@
1
- import{isUsageEvent,isOperationalContext}from"@zortexhq/plugin-telemetry/api";export function executionProperties(row){return isOperationalContext(row.execution)?{run_id:row.execution.runId,step_id:row.execution.stepId}:{}}export function operationalProperties(row){if(row.operation!=="product.trace"||!isUsageEvent(row,true)||!row.operational)return;const t=row.operational;if(row.execution&&(row.execution.runId!==t.runId||row.execution.stepId!==t.stepId))return;const duration=t.durationKnown&&Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5;return{trace_version:t.version,run_id:t.runId,step_id:t.stepId,...t.parentStepId?{parent_step_id:t.parentStepId}:{},emitter_id:t.emitterId,sequence:t.sequence,attempt:t.attempt,phase:t.phase,action:t.action,state:t.state,terminal:t.terminal,duration_known:duration,...duration?{duration_ms:Math.round(row.durationMs)}:{},coverage:"instrumented_steps_only",operation_id:t.operationId??"unknown",...t.sourceRef?{source_ref:t.sourceRef,source_identity:"installation_scoped"}:{},...t.processRef?{process_ref:t.processRef}:{},...t.actionRef?{action_ref:t.actionRef,action_identity:"installation_scoped"}:{},observed_count_known:t.observedCount!==void 0,...t.observedCount!==void 0?{observed_count:t.observedCount,count_basis:t.countBasis}:{},selection:t.selection??"unknown",trigger:t.trigger??"unknown",route:t.route??"unknown",profile:t.profile??"unknown",login_decision:t.loginDecision??"unknown",artifact_family:t.artifactFamily??"unknown",artifact_type:t.artifactType??"unknown",reason:t.reason??"unknown",error_category:t.errorCategory??"unknown",tool:t.tool??"unknown",method:t.method??"unknown",entrypoint:t.entrypoint??"unknown",download_observation:t.downloadObservation??"unknown",upstream_tool:t.upstreamTool??"unknown",rpc_method:t.rpcMethod??"unknown"}}
1
+ import{isUsageEvent,isOperationalContext}from"@zortexhq/plugin-telemetry/api";export function executionProperties(row){return isOperationalContext(row.execution)?{run_id:row.execution.runId,step_id:row.execution.stepId}:{}}export function operationalProperties(row){if(row.operation!=="product.trace"||!isUsageEvent(row,true)||!row.operational)return;const t=row.operational;if(row.execution&&(row.execution.runId!==t.runId||row.execution.stepId!==t.stepId))return;const duration=t.durationKnown&&Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5;return{trace_version:t.version,run_id:t.runId,step_id:t.stepId,...t.parentStepId?{parent_step_id:t.parentStepId}:{},emitter_id:t.emitterId,sequence:t.sequence,attempt:t.attempt,phase:t.phase,action:t.action,state:t.state,terminal:t.terminal,duration_known:duration,...duration?{duration_ms:Math.round(row.durationMs)}:{},coverage:"instrumented_steps_only",operation_id:t.operationId??"unknown",...t.sourceRef?{source_ref:t.sourceRef,source_identity:"installation_scoped"}:{},...t.processRef?{process_ref:t.processRef}:{},...t.actionRef?{action_ref:t.actionRef,action_identity:"installation_scoped"}:{},observed_count_known:t.observedCount!==void 0,...t.observedCount!==void 0?{observed_count:t.observedCount,count_basis:t.countBasis}:{},selection:t.selection??"unknown",trigger:t.trigger??"unknown",route:t.route??"unknown",profile:t.profile??"unknown",login_decision:t.loginDecision??"unknown",artifact_family:t.artifactFamily??"unknown",artifact_type:t.artifactType??"unknown",reason:t.reason??"unknown",error_category:t.errorCategory??"unknown",tool:t.tool??"unknown",method:t.method??"unknown",entrypoint:t.entrypoint??"unknown",download_observation:t.downloadObservation??"unknown",upstream_tool:t.upstreamTool??"unknown",rpc_method:t.rpcMethod??"unknown",...t.actor?{actor:t.actor}:{},...t.pageKind?{page_kind:t.pageKind}:{},...t.targetKind?{target_kind:t.targetKind}:{},...t.expected?{expected:t.expected}:{},...t.observed?{observed:t.observed}:{},...t.handoffKind?{handoff_kind:t.handoffKind}:{},...t.agentMode?{agent_mode:t.agentMode}:{},...t.failureMode?{failure_mode:t.failureMode}:{},...t.disposition?{disposition:t.disposition}:{},...t.readinessBasis?{readiness_basis:t.readinessBasis}:{},...t.pageEvidence?{page_evidence:t.pageEvidence}:{},...t.decisionOrdinal!==void 0?{decision_ordinal:t.decisionOrdinal}:{},...t.observationOrdinal!==void 0?{observation_ordinal:t.observationOrdinal}:{},...t.rowsExamined!==void 0?{rows_examined:t.rowsExamined}:{},...t.rowsTruncated!==void 0?{rows_truncated:t.rowsTruncated}:{},...t.rowsMissingRef!==void 0?{rows_missing_ref:t.rowsMissingRef}:{},...t.rowsDisabled!==void 0?{rows_disabled:t.rowsDisabled}:{},...t.rowsOffscreen!==void 0?{rows_offscreen:t.rowsOffscreen}:{},...t.rowsProtected!==void 0?{rows_protected:t.rowsProtected}:{},...t.rowsUnsupported!==void 0?{rows_unsupported:t.rowsUnsupported}:{},...t.feedbackAttempted!==void 0?{feedback_attempted:t.feedbackAttempted}:{},...t.feedbackFailed!==void 0?{feedback_failed:t.feedbackFailed}:{},...t.feedbackAccepted!==void 0?{feedback_accepted:t.feedbackAccepted}:{}}}
@@ -0,0 +1 @@
1
+ import{AsyncLocalStorage}from"node:async_hooks";import{randomUUID}from"node:crypto";import{existsSync,lstatSync,mkdirSync,readFileSync,readdirSync,realpathSync,rmSync,rmdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{join,isAbsolute}from"node:path";import{windowsJobQuiescent}from"../windows-job.js";const scopes=new AsyncLocalStorage,marker=".zortex-action-owner";export function currentExecutionScope(){return scopes.getStore()}export function processRangeQuiescent(range){if(range.platform!==process.platform)return false;if(process.platform==="win32")try{return windowsJobQuiescent(range.id)}catch{return false}try{process.kill(-range.pid,0)}catch(error){return error.code==="ESRCH"}if(process.platform==="linux")try{for(const entry of readdirSync("/proc"))if(/^\d+$/.test(entry)){let raw;try{raw=readFileSync(`/proc/${entry}/stat`,"utf8")}catch(error){if(error.code==="ENOENT")continue;return false}const fields=raw.slice(raw.lastIndexOf(")")+2).split(" ");if(Number(fields[2])===range.pid&&fields[0]!=="Z"&&fields[0]!=="X")return false}return true}catch{return false}return false}function validState(value,ref,ownerId){if(!value||typeof value!=="object")return false;const s=value;return s.version===1&&s.ref===ref&&s.ownerId===ownerId&&typeof s.closed==="boolean"&&Array.isArray(s.ranges)&&s.ranges.length<=32&&s.ranges.every(r=>r&&/^zortex-[a-f0-9-]{36}$/.test(r.id)&&Number.isSafeInteger(r.pid)&&r.pid>0&&typeof r.platform==="string"&&typeof r.pending==="boolean")&&Array.isArray(s.directories)&&s.directories.length<=16&&s.directories.every(d=>d&&typeof d.path==="string"&&isAbsolute(d.path)&&typeof d.token==="string"&&/^[a-f0-9-]{36}$/.test(d.token))}function removeDirectory(directory){try{if(!existsSync(directory.path))return true;const stat=lstatSync(directory.path);if(!stat.isDirectory()||stat.isSymbolicLink())return false;const path=join(directory.path,marker);if(!existsSync(path)){rmdirSync(directory.path);return true}if(lstatSync(path).isSymbolicLink()||readFileSync(path,"utf8")!==directory.token)return false;rmSync(directory.path,{recursive:true,force:true});return!existsSync(directory.path)}catch{return false}}export function createExecutionScope(options){const{store,ref,ownerId}=options,prior=store.get(ref);if(!("ok"in prior)||prior.ok)throw Error("Execution cleanup owner already exists or cannot be read.");const state={version:1,ownerId,ref,ranges:[],directories:[],closed:false};let revision=0;const save=()=>{const result=store.put(ref,state,revision);if(!("ok"in result))throw Error("Execution cleanup ownership could not be saved.");revision=result.ok.revision};save();const requests=new Map,handles=new Map,executions=new Set;const scope={run:body=>scopes.run(scope,body),retain(task){if(state.closed)throw Error("Execution cleanup owner is closed.");executions.add(task);void task.then(()=>executions.delete(task),()=>executions.delete(task))},track(handle,request){if(state.closed||handle.pid===void 0)throw Error("Execution cleanup owner is not active.");let range=state.ranges.find(value=>value.id===handle.rangeId);if(!range){if(state.ranges.length>=32)throw Error("Execution process resource bound exceeded.");range={id:handle.rangeId,pid:handle.pid,platform:process.platform,pending:true};state.ranges.push(range)}handles.set(handle.rangeId,handle);let ids=requests.get(handle.rangeId);if(!ids){ids=new Set;requests.set(handle.rangeId,ids)}ids.add(request);range.pending=true;save()},release(handle,request){const ids=requests.get(handle.rangeId);if(!ids?.delete(request))return;const range=state.ranges.find(value=>value.id===handle.rangeId);range.pending=ids.size>0;save()},reserveDirectory(prefix){if(state.closed||state.directories.length>=16||!/^zortex-[a-z0-9-]+-$/.test(prefix))throw Error("Invalid execution temporary resource.");const directory={path:join(realpathSync(tmpdir()),prefix+randomUUID()),token:randomUUID()};state.directories.push(directory);save();mkdirSync(directory.path,{mode:448});writeFileSync(join(directory.path,marker),directory.token,{mode:384,flag:"wx"});return directory.path},async cleanup(){if(executions.size)return"pending";for(const range of state.ranges.filter(value=>value.pending)){const handle=handles.get(range.id);if(handle){handle.terminate();await handle.waitForExit(AbortSignal.timeout(5e3))}if(!processRangeQuiescent(range))return"pending";range.pending=false}if(!state.directories.every(removeDirectory))return"pending";state.closed=true;save();return"confirmed"}};return scope}export function reserveTemporaryDirectory(prefix){const scope=currentExecutionScope();if(scope)return scope.reserveDirectory(prefix);if(!/^zortex-[a-z0-9-]+-$/.test(prefix))throw Error("Invalid temporary resource prefix.");const path=join(realpathSync(tmpdir()),prefix+randomUUID());mkdirSync(path,{mode:448});return path}export async function recoverExecutionScope(options){if(!options.ownerStopped)return"pending";const found=options.store.get(options.ref);if(!("ok"in found))return"pending";if(!found.ok)return"confirmed";if(!validState(found.ok.value,options.ref,options.ownerId))return"pending";const state=found.ok.value;if(state.ranges.some(range=>range.pending&&!processRangeQuiescent(range))||!state.directories.every(removeDirectory))return"pending";const value={...state,closed:true,ranges:state.ranges.map(range=>({...range,pending:false}))};return"ok"in options.store.put(options.ref,value,found.ok.revision)?"confirmed":"pending"}
@@ -0,0 +1 @@
1
+ import{createProcesses}from"../index.js";import{currentExecutionScope}from"./execution-scope.js";import{JSONRPCMessageSchema}from"@modelcontextprotocol/core";export class ManagedStdioTransport{options;onclose;onerror;onmessage;processes=createProcesses();handle;closing;ended=false;lifetimeScope;pending=new Map;buffer=Buffer.alloc(0);constructor(options){this.options=options}get pid(){return this.ended?null:this.handle?.pid??null}async start(){if(this.handle||this.closing)throw Error("Managed stdio transport is already started or closed.");const scope=currentExecutionScope();this.lifetimeScope=this.options.ownedUntilClose?scope:void 0;try{const handle=this.handle=this.processes.spawn({argv:[this.options.command,...this.options.args??[]],cwd:this.options.cwd??process.cwd(),...this.options.env?{env:this.options.env}:{},stdio:{stdin:"pipe",stdout:"pipe",stderr:this.options.stderr??"ignore"},graceMs:this.options.graceMs??100,telemetryRole:"connector_runtime",onSpawn:handle2=>{scope?.track(handle2,"startup");this.lifetimeScope?.track(handle2,"lifetime")}});handle.stdout.on("data",chunk=>{if(this.closing||this.ended)return;try{this.buffer=Buffer.concat([this.buffer,chunk]);if(this.buffer.length>16*1024*1024)throw Error("Managed stdio message exceeded its bound.");let newline;while((newline=this.buffer.indexOf(10))>=0){const line=this.buffer.subarray(0,newline).toString("utf8").replace(/\r$/,"");this.buffer=this.buffer.subarray(newline+1);if(!line)continue;const message=JSONRPCMessageSchema.parse(JSON.parse(line));if("id"in message&&message.id!==void 0&&("result"in message||"error"in message)){const key=JSON.stringify(message.id),owned=this.pending.get(key);if(owned){owned.scope.release(owned.handle,owned.request);this.pending.delete(key)}}this.onmessage?.(message)}}catch(error){void this.close().catch(()=>{});try{this.onerror?.(error instanceof Error?error:Error("Managed stdio input failed."))}catch{}}});handle.stdin.on("error",error=>this.onerror?.(error));void handle.done.then(()=>this.close(),error=>{this.onerror?.(error);return this.close()}).catch(()=>{});await handle.started;scope?.release(handle,"startup")}catch(error){await this.close().catch(()=>{});throw error}}async send(message){const handle=this.handle;if(!handle||this.ended||this.closing)throw Error("Managed stdio transport is closed.");const line=JSON.stringify(message)+"\n";if(Buffer.byteLength(line)>16*1024*1024)throw Error("Managed stdio message exceeded its bound.");const value=message,scope=currentExecutionScope();if(scope&&value.id!==void 0&&typeof value.method==="string"){const key=JSON.stringify(value.id),request="rpc:"+key;scope.track(handle,request);this.pending.set(key,{scope,handle,request})}await new Promise((resolve,reject)=>handle.stdin.write(line,error=>error?reject(error):resolve()))}close(){this.closing??=(async()=>{const handle=this.handle;handle?.terminate();const stopped=!handle||await handle.waitForExit(AbortSignal.timeout(5e3));await this.processes.close();if(!stopped)throw Error("Managed stdio range cleanup is still pending.");if(handle)this.lifetimeScope?.release(handle,"lifetime");if(!this.ended){this.ended=true;this.onclose?.()}})();return this.closing}}
@@ -1 +1 @@
1
- import{randomUUID}from"node:crypto";import{spawn as spawnChild}from"node:child_process";import{isAbsolute}from"node:path";import{fileURLToPath}from"node:url";import{setTimeout as delay}from"node:timers/promises";import{createWindowsJob}from"./windows-job.js";import{startOperationalStep}from"@zortexhq/plugin-telemetry/api";import{RESOURCE_PROCESS_ROLES}from"@zortexhq/plugin-telemetry/api/resources";import{startOwnedProcessResourceSampler}from"./resource-sampler.js";export const name="zortex-process-local";export const SENSITIVE_ENV=/KEY|PASSWORD|SECRET|TOKEN/i;export function childEnvironment(extra={}){const env={};for(const[key,value]of Object.entries(process.env)){if(value!==void 0&&!SENSITIVE_ENV.test(key)&&!/^DSH_/i.test(key)&&!/^NODE_CHANNEL_/i.test(key))env[key]=value}const find=key=>process.platform==="win32"?Object.keys(env).find(name2=>name2.toUpperCase()===key.toUpperCase()):key in env?key:void 0;for(const[key,value]of Object.entries(extra)){const existing=find(key);if(existing!==void 0)delete env[existing];if(value!==void 0)env[key]=value}return env}const runner=fileURLToPath(new URL("./runner.js",import.meta.url));const MAX_COLLECT=64*1024*1024;function posixGroupAlive(pgid){try{process.kill(-pgid,0);return true}catch(error){return error.code==="EPERM"}}function validMode(mode){if(mode==="ignore"||mode==="inherit")return true;const max=mode?.maxBytes;return typeof mode==="object"&&Number.isSafeInteger(max)&&max>0&&max<=MAX_COLLECT}class Tail{max;chunks=[];size=0;truncated=false;constructor(max){this.max=max}push(chunk){this.chunks.push(chunk);this.size+=chunk.length;while(this.size>this.max&&this.chunks.length){const extra=this.size-this.max,first=this.chunks[0];if(first.length<=extra){this.chunks.shift();this.size-=first.length}else{this.chunks[0]=first.subarray(extra);this.size-=extra}this.truncated=true}}read(){return{text:Buffer.concat(this.chunks).toString("utf8"),truncated:this.truncated}}}export function createProcesses(config={},metrics){const disposeMs=config.disposeMs??1e4;if(!Number.isSafeInteger(disposeMs)||disposeMs<1||disposeMs>6e5)throw Error("Invalid disposeMs.");const live=new Set;let closed=false;function spawn(spec){if(closed)throw Error("Process service is closed.");if(!spec||!Array.isArray(spec.argv)||!spec.argv.length||spec.argv.some(part=>typeof part!=="string"||part.includes("\0")))throw Error("Invalid process argv.");if(!isAbsolute(spec.argv[0])&&/[\\/]/.test(spec.argv[0]))throw Error("Executable must be absolute or a bare PATH name.");if(typeof spec.cwd!=="string"||!isAbsolute(spec.cwd))throw Error("Process cwd must be absolute.");if(!spec.stdio||spec.stdio.stdin!=="ignore"||!validMode(spec.stdio.stdout)||!validMode(spec.stdio.stderr))throw Error("Invalid process stdio.");if(!Number.isSafeInteger(spec.graceMs)||spec.graceMs<0||spec.graceMs>6e5)throw Error("Invalid graceMs.");if(spec.signal?.aborted)throw Error("Process launch was aborted.");let processRef;const execution=startOperationalStep(metrics,()=>{processRef=randomUUID();return{phase:"runtime",action:"execute",processRef}});const windows=process.platform==="win32";let job;try{job=windows?createWindowsJob():void 0}catch(error){execution.finish({state:"failed",errorCategory:"provider"});throw error}const pipeOf=mode=>typeof mode==="object"?"pipe":mode;const stdio=["ignore",pipeOf(spec.stdio.stdout),pipeOf(spec.stdio.stderr),"ipc"];let child;try{child=spawnChild(process.execPath,[runner,JSON.stringify({argv:spec.argv,cwd:spec.cwd})],{cwd:spec.cwd,env:childEnvironment(spec.env),stdio,detached:!windows,windowsHide:true,serialization:"json"})}catch(error){execution.finish({state:"failed",errorCategory:"provider"});job?.close();throw error}const tails={stdout:typeof spec.stdio.stdout==="object"?new Tail(spec.stdio.stdout.maxBytes):void 0,stderr:typeof spec.stdio.stderr==="object"?new Tail(spec.stdio.stderr.maxBytes):void 0};for(const stream of["stdout","stderr"]){const readable=child[stream],tail=tails[stream];readable?.on("error",()=>{});if(readable&&tail)readable.on("data",chunk=>tail.push(chunk))}const pid=child.pid;let reported;let launchError,quiescent=false,terminating=false,assigned=!job,killTimer;let cleanup;let resources;child.on("message",message=>{if(message==="ready"){if(job&&pid!==void 0){try{job.assign(pid);assigned=true}catch(error){launchError=error;child.kill();return}}if(terminating){if(job)job.terminate();else child.kill();return}if(child.connected)child.send("start",()=>{});return}if(message&&typeof message==="object"){const value=message;if(value.kind==="started"){if(!resources&&metrics&&Number.isSafeInteger(value.pid)&&value.pid>0&&pid!==void 0){try{const role=RESOURCE_PROCESS_ROLES.includes(spec.telemetryRole)?spec.telemetryRole:"worker";resources=execution.run(()=>startOwnedProcessResourceSampler({pid:value.pid,parentPid:pid,role,metrics,...processRef?{processRef}:{},isAlive:()=>reported===void 0&&!quiescent&&child.exitCode===null&&child.signalCode===null}))}catch{}}return}reported=value.error?"spawn-failed":{exitCode:value.exitCode??null,signal:value.signal??null}}});const failed=new Promise((_,reject)=>child.once("error",error=>{launchError??=error;reject(error)}));failed.catch(()=>{});const exited=new Promise(resolve=>child.once("exit",(code,signal)=>resolve({code,signal})));const channelClosed=new Promise(resolve=>{if(!child.connected)resolve();else child.once("disconnect",()=>resolve())});const done=(async()=>{const exit=await Promise.race([exited,failed]);await Promise.race([channelClosed,delay(1e3)]);if(launchError)throw launchError;if(reported==="spawn-failed")throw Error("Process could not be started.");return reported??{exitCode:exit.code,signal:exit.signal}})();void done.then(outcome=>{resources?.close();execution.finish({state:terminating?"cancelled":outcome.exitCode===0?"completed":"failed"})},()=>{resources?.close();execution.finish({state:terminating?"cancelled":"failed",errorCategory:"provider"})});function rangeAlive(){if(child.exitCode===null&&child.signalCode===null&&!launchError)return true;if(job)return job.activeProcesses()>0;return pid!==void 0&&posixGroupAlive(pid)}function finish(){if(quiescent)return;quiescent=true;resources?.close();if(killTimer)clearTimeout(killTimer);job?.close();child.stdout?.destroy();child.stderr?.destroy();if(child.connected)child.disconnect();spec.signal?.removeEventListener("abort",terminate);live.delete(handle);cleanup?.finish({state:"completed"})}function terminate(){if(quiescent)return;cleanup??=execution.run(()=>startOperationalStep(metrics,{phase:"runtime",action:"cleanup",...processRef?{processRef}:{}}));terminating=true;if(job){if(assigned)job.terminate();else child.kill();return}if(pid===void 0)return;try{process.kill(-pid,"SIGTERM")}catch{}killTimer??=setTimeout(()=>{try{process.kill(-pid,"SIGKILL")}catch{}},spec.graceMs);killTimer.unref()}const handle={pid,done,terminate,async waitForExit(signal){while(!quiescent){if(signal?.aborted){cleanup?.mark({state:"unknown",errorCategory:"timeout"});return false}let alive=true;try{alive=rangeAlive()}catch{alive=true}if(!alive){finish();break}await delay(25)}return true},output(stream){return tails[stream]?.read()??{text:"",truncated:false}}};spec.signal?.addEventListener("abort",terminate,{once:true});live.add(handle);return handle}return{spawn,active:()=>live.size,async close(){closed=true;const handles=[...live];for(const handle of handles)handle.terminate();const deadline=AbortSignal.timeout(disposeMs);await Promise.allSettled(handles.map(handle=>handle.waitForExit(deadline)))}}}export function apply(ctx,config={}){const service=createProcesses(config,()=>ctx.get("zortexTelemetry"));ctx.reflect.provide("zortexProcesses",service);ctx.effect(()=>()=>service.close(),`${name}: managed ranges`)}
1
+ import{randomUUID}from"node:crypto";import{spawn as spawnChild}from"node:child_process";import{isAbsolute}from"node:path";import{fileURLToPath}from"node:url";import{setTimeout as delay}from"node:timers/promises";import{createWindowsJob}from"./windows-job.js";import{startOperationalStep}from"@zortexhq/plugin-telemetry/api";import{RESOURCE_PROCESS_ROLES}from"@zortexhq/plugin-telemetry/api/resources";import{startOwnedProcessResourceSampler}from"./resource-sampler.js";import{processRangeQuiescent}from"./api/execution-scope.js";export const name="zortex-process-local";export const SENSITIVE_ENV=/KEY|PASSWORD|SECRET|TOKEN/i;export function childEnvironment(extra={}){const env={};for(const[key,value]of Object.entries(process.env)){if(value!==void 0&&!SENSITIVE_ENV.test(key)&&!/^DSH_/i.test(key)&&!/^NODE_CHANNEL_/i.test(key))env[key]=value}const find=key=>process.platform==="win32"?Object.keys(env).find(name2=>name2.toUpperCase()===key.toUpperCase()):key in env?key:void 0;for(const[key,value]of Object.entries(extra)){const existing=find(key);if(existing!==void 0)delete env[existing];if(value!==void 0)env[key]=value}return env}const runner=fileURLToPath(new URL("./runner.js",import.meta.url));const MAX_COLLECT=64*1024*1024;function validMode(mode){if(mode==="ignore"||mode==="inherit"||mode==="pipe")return true;const max=mode?.maxBytes;return typeof mode==="object"&&Number.isSafeInteger(max)&&max>0&&max<=MAX_COLLECT}class Tail{max;chunks=[];size=0;truncated=false;constructor(max){this.max=max}push(chunk){this.chunks.push(chunk);this.size+=chunk.length;while(this.size>this.max&&this.chunks.length){const extra=this.size-this.max,first=this.chunks[0];if(first.length<=extra){this.chunks.shift();this.size-=first.length}else{this.chunks[0]=first.subarray(extra);this.size-=extra}this.truncated=true}}read(){return{text:Buffer.concat(this.chunks).toString("utf8"),truncated:this.truncated}}}export function createProcesses(config={},metrics){const disposeMs=config.disposeMs??1e4;if(!Number.isSafeInteger(disposeMs)||disposeMs<1||disposeMs>6e5)throw Error("Invalid disposeMs.");const live=new Set;let closed=false;function spawn(spec){if(closed)throw Error("Process service is closed.");if(!spec||!Array.isArray(spec.argv)||!spec.argv.length||spec.argv.some(part=>typeof part!=="string"||part.includes("\0")))throw Error("Invalid process argv.");if(!isAbsolute(spec.argv[0])&&/[\\/]/.test(spec.argv[0]))throw Error("Executable must be absolute or a bare PATH name.");if(typeof spec.cwd!=="string"||!isAbsolute(spec.cwd))throw Error("Process cwd must be absolute.");if(!spec.stdio||!["ignore","pipe"].includes(spec.stdio.stdin)||!validMode(spec.stdio.stdout)||!validMode(spec.stdio.stderr))throw Error("Invalid process stdio.");if(!Number.isSafeInteger(spec.graceMs)||spec.graceMs<0||spec.graceMs>6e5)throw Error("Invalid graceMs.");if(spec.signal?.aborted)throw Error("Process launch was aborted.");let processRef;const execution=startOperationalStep(metrics,()=>{processRef=randomUUID();return{phase:"runtime",action:"execute",processRef}});const windows=process.platform==="win32";const rangeId="zortex-"+randomUUID(),guardAfterExit=spec.stdio.stdin==="pipe";let job;try{job=windows?createWindowsJob(rangeId):void 0}catch(error){execution.finish({state:"failed",errorCategory:"provider"});throw error}const pipeOf=mode=>typeof mode==="object"?"pipe":mode;const stdio=[spec.stdio.stdin,pipeOf(spec.stdio.stdout),pipeOf(spec.stdio.stderr),"ipc"];let child;try{child=spawnChild(process.execPath,[runner,JSON.stringify({argv:spec.argv,cwd:spec.cwd,pipeInput:spec.stdio.stdin==="pipe",guardAfterExit})],{cwd:spec.cwd,env:childEnvironment(spec.env),stdio,detached:!windows,windowsHide:true,serialization:"json"})}catch(error){execution.finish({state:"failed",errorCategory:"provider"});job?.close();throw error}const tails={stdout:typeof spec.stdio.stdout==="object"?new Tail(spec.stdio.stdout.maxBytes):void 0,stderr:typeof spec.stdio.stderr==="object"?new Tail(spec.stdio.stderr.maxBytes):void 0};for(const stream of["stdout","stderr"]){const readable=child[stream],tail=tails[stream];readable?.on("error",()=>{});if(readable&&tail)readable.on("data",chunk=>tail.push(chunk))}const pid=child.pid;let reported;let launchError,quiescent=false,terminating=false,assigned=!job,killTimer;let cleanup;let resources;let startResolve,startReject,reportResolve,reportReject;const started=new Promise((resolve,reject)=>{startResolve=resolve;startReject=reject});started.catch(()=>{});const report=new Promise((resolve,reject)=>{reportResolve=resolve;reportReject=reject});report.catch(()=>{});child.on("message",message=>{if(message==="ready"){if(job&&pid!==void 0){try{job.assign(pid);assigned=true}catch(error){launchError=error;child.kill();return}}if(terminating){if(job)job.terminate();else child.kill();return}if(child.connected)child.send("start",()=>{});return}if(message&&typeof message==="object"){const value=message;if(value.kind==="started"){startResolve();if(!resources&&metrics&&Number.isSafeInteger(value.pid)&&value.pid>0&&pid!==void 0){try{const role=RESOURCE_PROCESS_ROLES.includes(spec.telemetryRole)?spec.telemetryRole:"worker";resources=execution.run(()=>startOwnedProcessResourceSampler({pid:value.pid,parentPid:pid,role,metrics,...processRef?{processRef}:{},isAlive:()=>reported===void 0&&!quiescent&&child.exitCode===null&&child.signalCode===null}))}catch{}}return}reported=value.error?"spawn-failed":{exitCode:value.exitCode??null,signal:value.signal??null};if(reported==="spawn-failed"){const error=Error("Process could not be started.");startReject(error);reportReject(error)}else reportResolve(reported)}});const failed=new Promise((_,reject)=>child.once("error",error=>{launchError??=error;startReject(error);reject(error)}));failed.catch(()=>{});const exited=new Promise(resolve=>child.once("exit",(code,signal)=>{startReject(Error("Managed process exited before startup."));resolve({code,signal})}));const channelClosed=new Promise(resolve=>{if(!child.connected)resolve();else child.once("disconnect",()=>resolve())});const done=(async()=>{if(guardAfterExit)return Promise.race([report,failed,exited.then(exit2=>{if(reported==="spawn-failed")throw Error("Process could not be started.");return reported??{exitCode:exit2.code,signal:exit2.signal}})]);const exit=await Promise.race([exited,failed]);await Promise.race([channelClosed,delay(1e3)]);if(launchError)throw launchError;if(reported==="spawn-failed")throw Error("Process could not be started.");return reported??{exitCode:exit.code,signal:exit.signal}})();void done.then(outcome=>{resources?.close();execution.finish({state:terminating?"cancelled":outcome.exitCode===0?"completed":"failed"})},()=>{resources?.close();execution.finish({state:terminating?"cancelled":"failed",errorCategory:"provider"})});function rangeAlive(){if(child.exitCode===null&&child.signalCode===null&&!launchError)return true;if(job)return job.activeProcesses()>0;return pid!==void 0&&!processRangeQuiescent({pid,id:rangeId,platform:process.platform})}function finish(){if(quiescent)return;quiescent=true;resources?.close();if(killTimer)clearTimeout(killTimer);job?.close();child.stdout?.destroy();child.stderr?.destroy();child.stdin?.destroy();if(child.connected)child.disconnect();spec.signal?.removeEventListener("abort",terminate);live.delete(handle);cleanup?.finish({state:"completed"})}function terminate(){if(quiescent)return;cleanup??=execution.run(()=>startOperationalStep(metrics,{phase:"runtime",action:"cleanup",...processRef?{processRef}:{}}));terminating=true;if(job){if(assigned)job.terminate();else child.kill();return}if(pid===void 0)return;try{process.kill(-pid,"SIGTERM")}catch{}killTimer??=setTimeout(()=>{try{process.kill(-pid,"SIGKILL")}catch{}},spec.graceMs);killTimer.unref()}const handle={pid,done,started,rangeId,stdin:child.stdin,stdout:child.stdout,stderr:child.stderr,terminate,async waitForExit(signal){while(!quiescent){if(signal?.aborted){cleanup?.mark({state:"unknown",errorCategory:"timeout"});return false}let alive=true;try{alive=rangeAlive()}catch{alive=true}if(!alive){finish();break}await delay(25)}return true},output(stream){return tails[stream]?.read()??{text:"",truncated:false}}};spec.signal?.addEventListener("abort",terminate,{once:true});live.add(handle);try{spec.onSpawn?.(handle)}catch(error){terminate();throw error}return handle}return{spawn,active:()=>live.size,async close(){closed=true;const handles=[...live];for(const handle of handles)handle.terminate();const deadline=AbortSignal.timeout(disposeMs);await Promise.allSettled(handles.map(handle=>handle.waitForExit(deadline)))}}}export function apply(ctx,config={}){const service=createProcesses(config,()=>ctx.get("zortexTelemetry"));ctx.reflect.provide("zortexProcesses",service);ctx.effect(()=>()=>service.close(),`${name}: managed ranges`)}
@@ -1 +1 @@
1
- import{spawn}from"node:child_process";const spec=JSON.parse(process.argv[2]??"null");if(!spec||!Array.isArray(spec.argv)||!spec.argv.length||typeof spec.cwd!=="string"||typeof process.send!=="function")process.exit(70);const env={...process.env};delete env.NODE_CHANNEL_FD;delete env.NODE_CHANNEL_SERIALIZATION_MODE;let child,finished=false;process.on("SIGTERM",()=>{});process.on("SIGINT",()=>{});process.on("disconnect",()=>{if(finished)return;if(process.platform!=="win32")try{process.kill(-process.pid,"SIGKILL")}catch{}process.exit(1)});const report=(message,code)=>{finished=true;process.send(message,()=>{process.exitCode=code;process.disconnect()})};process.on("message",message=>{if(message!=="start"||child)return;try{child=spawn(spec.argv[0],spec.argv.slice(1),{cwd:spec.cwd,env,stdio:["ignore","inherit","inherit"],windowsHide:true})}catch{report({error:"spawn"},127);return}child.once("spawn",()=>{if(!finished&&child?.pid!==void 0)process.send?.({kind:"started",pid:child.pid})});child.once("error",()=>{if(!finished)report({error:"spawn"},127)});child.once("exit",(exitCode,signal)=>{if(!finished)report({exitCode,signal},exitCode??1)})});process.send("ready");
1
+ import{spawn}from"node:child_process";const spec=JSON.parse(process.argv[2]??"null");if(!spec||!Array.isArray(spec.argv)||!spec.argv.length||typeof spec.cwd!=="string"||typeof process.send!=="function")process.exit(70);const env={...process.env};delete env.NODE_CHANNEL_FD;delete env.NODE_CHANNEL_SERIALIZATION_MODE;let child,finished=false;process.on("SIGTERM",()=>{});process.on("SIGINT",()=>{});process.on("disconnect",()=>{if(finished&&!spec.guardAfterExit)return;if(process.platform!=="win32")try{process.kill(-process.pid,"SIGKILL")}catch{}process.exit(1)});const report=(message,code)=>{finished=true;process.send(message,()=>{if(!spec.guardAfterExit){process.exitCode=code;process.disconnect()}})};process.on("message",message=>{if(message!=="start"||child)return;try{child=spawn(spec.argv[0],spec.argv.slice(1),{cwd:spec.cwd,env,stdio:[spec.pipeInput?"inherit":"ignore","inherit","inherit"],windowsHide:true})}catch{report({error:"spawn"},127);return}child.once("spawn",()=>{if(!finished&&child?.pid!==void 0)process.send?.({kind:"started",pid:child.pid})});child.once("error",()=>{if(!finished)report({error:"spawn"},127)});child.once("exit",(exitCode,signal)=>{if(!finished)report({exitCode,signal},exitCode??1)})});process.send("ready");
@@ -1 +1 @@
1
- import koffi from"koffi";const JobObjectBasicAccountingInformation=1,JobObjectExtendedLimitInformation=9;const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE=8192,PROCESS_TERMINATE=1,PROCESS_SET_QUOTA=256;let api;function load(){if(koffi.sizeof("void *")!==8)throw Error("Managed process ranges need 64-bit Windows.");const basic=koffi.struct({PerProcessUserTimeLimit:"int64_t",PerJobUserTimeLimit:"int64_t",LimitFlags:"uint32_t",MinimumWorkingSetSize:"size_t",MaximumWorkingSetSize:"size_t",ActiveProcessLimit:"uint32_t",Affinity:"uintptr_t",PriorityClass:"uint32_t",SchedulingClass:"uint32_t"});const io=koffi.struct({ReadOperationCount:"uint64_t",WriteOperationCount:"uint64_t",OtherOperationCount:"uint64_t",ReadTransferCount:"uint64_t",WriteTransferCount:"uint64_t",OtherTransferCount:"uint64_t"});const extended=koffi.struct({BasicLimitInformation:basic,IoInfo:io,ProcessMemoryLimit:"size_t",JobMemoryLimit:"size_t",PeakProcessMemoryUsed:"size_t",PeakJobMemoryUsed:"size_t"});const accounting=koffi.struct({TotalUserTime:"int64_t",TotalKernelTime:"int64_t",ThisPeriodTotalUserTime:"int64_t",ThisPeriodTotalKernelTime:"int64_t",TotalPageFaultCount:"uint32_t",TotalProcesses:"uint32_t",ActiveProcesses:"uint32_t",TotalTerminatedProcesses:"uint32_t"});const kernel=koffi.load("kernel32.dll");return{koffi,extended,accounting,CreateJobObjectW:kernel.func("__stdcall","CreateJobObjectW","void *",["void *","void *"]),SetInformationJobObject:kernel.func("__stdcall","SetInformationJobObject","int",["void *","int",koffi.pointer(extended),"uint32_t"]),QueryInformationJobObject:kernel.func("__stdcall","QueryInformationJobObject","int",["void *","int",koffi.out(koffi.pointer(accounting)),"uint32_t","void *"]),AssignProcessToJobObject:kernel.func("__stdcall","AssignProcessToJobObject","int",["void *","void *"]),TerminateJobObject:kernel.func("__stdcall","TerminateJobObject","int",["void *","uint32_t"]),OpenProcess:kernel.func("__stdcall","OpenProcess","void *",["uint32_t","int","uint32_t"]),CloseHandle:kernel.func("__stdcall","CloseHandle","int",["void *"]),GetLastError:kernel.func("__stdcall","GetLastError","uint32_t",[])}}export function createWindowsJob(){const a=api??=load();const handle=a.CreateJobObjectW(null,null);if(!handle)throw Error(`CreateJobObjectW failed (${a.GetLastError()}).`);const limits={BasicLimitInformation:{PerProcessUserTimeLimit:0,PerJobUserTimeLimit:0,LimitFlags:JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,MinimumWorkingSetSize:0,MaximumWorkingSetSize:0,ActiveProcessLimit:0,Affinity:0,PriorityClass:0,SchedulingClass:0},IoInfo:{ReadOperationCount:0,WriteOperationCount:0,OtherOperationCount:0,ReadTransferCount:0,WriteTransferCount:0,OtherTransferCount:0},ProcessMemoryLimit:0,JobMemoryLimit:0,PeakProcessMemoryUsed:0,PeakJobMemoryUsed:0};if(!a.SetInformationJobObject(handle,JobObjectExtendedLimitInformation,limits,a.koffi.sizeof(a.extended))){const code=a.GetLastError();a.CloseHandle(handle);throw Error(`SetInformationJobObject failed (${code}).`)}let closed=false;return{assign(pid){const process=a.OpenProcess(PROCESS_SET_QUOTA|PROCESS_TERMINATE,0,pid);if(!process)throw Error(`OpenProcess failed (${a.GetLastError()}).`);try{if(!a.AssignProcessToJobObject(handle,process))throw Error(`AssignProcessToJobObject failed (${a.GetLastError()}).`)}finally{a.CloseHandle(process)}},terminate(){if(!closed)a.TerminateJobObject(handle,1)},activeProcesses(){if(closed)return 0;const out={};if(!a.QueryInformationJobObject(handle,JobObjectBasicAccountingInformation,out,a.koffi.sizeof(a.accounting),null))throw Error(`QueryInformationJobObject failed (${a.GetLastError()}).`);return Number(out.ActiveProcesses)},close(){if(!closed){closed=true;a.CloseHandle(handle)}}}}
1
+ import koffi from"koffi";const JobObjectBasicAccountingInformation=1,JobObjectExtendedLimitInformation=9;const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE=8192,PROCESS_TERMINATE=1,PROCESS_SET_QUOTA=256;let api;function load(){if(koffi.sizeof("void *")!==8)throw Error("Managed process ranges need 64-bit Windows.");const basic=koffi.struct({PerProcessUserTimeLimit:"int64_t",PerJobUserTimeLimit:"int64_t",LimitFlags:"uint32_t",MinimumWorkingSetSize:"size_t",MaximumWorkingSetSize:"size_t",ActiveProcessLimit:"uint32_t",Affinity:"uintptr_t",PriorityClass:"uint32_t",SchedulingClass:"uint32_t"});const io=koffi.struct({ReadOperationCount:"uint64_t",WriteOperationCount:"uint64_t",OtherOperationCount:"uint64_t",ReadTransferCount:"uint64_t",WriteTransferCount:"uint64_t",OtherTransferCount:"uint64_t"});const extended=koffi.struct({BasicLimitInformation:basic,IoInfo:io,ProcessMemoryLimit:"size_t",JobMemoryLimit:"size_t",PeakProcessMemoryUsed:"size_t",PeakJobMemoryUsed:"size_t"});const accounting=koffi.struct({TotalUserTime:"int64_t",TotalKernelTime:"int64_t",ThisPeriodTotalUserTime:"int64_t",ThisPeriodTotalKernelTime:"int64_t",TotalPageFaultCount:"uint32_t",TotalProcesses:"uint32_t",ActiveProcesses:"uint32_t",TotalTerminatedProcesses:"uint32_t"});const kernel=koffi.load("kernel32.dll");return{koffi,extended,accounting,CreateJobObjectW:kernel.func("__stdcall","CreateJobObjectW","void *",["void *","void *"]),SetInformationJobObject:kernel.func("__stdcall","SetInformationJobObject","int",["void *","int",koffi.pointer(extended),"uint32_t"]),QueryInformationJobObject:kernel.func("__stdcall","QueryInformationJobObject","int",["void *","int",koffi.out(koffi.pointer(accounting)),"uint32_t","void *"]),AssignProcessToJobObject:kernel.func("__stdcall","AssignProcessToJobObject","int",["void *","void *"]),TerminateJobObject:kernel.func("__stdcall","TerminateJobObject","int",["void *","uint32_t"]),OpenProcess:kernel.func("__stdcall","OpenProcess","void *",["uint32_t","int","uint32_t"]),OpenJobObjectW:kernel.func("__stdcall","OpenJobObjectW","void *",["uint32_t","int","void *"]),CloseHandle:kernel.func("__stdcall","CloseHandle","int",["void *"]),GetLastError:kernel.func("__stdcall","GetLastError","uint32_t",[])}}export function createWindowsJob(name){const a=api??=load();const handle=a.CreateJobObjectW(null,name?Buffer.from(name+"\0","utf16le"):null);if(!handle)throw Error(`CreateJobObjectW failed (${a.GetLastError()}).`);const limits={BasicLimitInformation:{PerProcessUserTimeLimit:0,PerJobUserTimeLimit:0,LimitFlags:JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,MinimumWorkingSetSize:0,MaximumWorkingSetSize:0,ActiveProcessLimit:0,Affinity:0,PriorityClass:0,SchedulingClass:0},IoInfo:{ReadOperationCount:0,WriteOperationCount:0,OtherOperationCount:0,ReadTransferCount:0,WriteTransferCount:0,OtherTransferCount:0},ProcessMemoryLimit:0,JobMemoryLimit:0,PeakProcessMemoryUsed:0,PeakJobMemoryUsed:0};if(!a.SetInformationJobObject(handle,JobObjectExtendedLimitInformation,limits,a.koffi.sizeof(a.extended))){const code=a.GetLastError();a.CloseHandle(handle);throw Error(`SetInformationJobObject failed (${code}).`)}let closed=false;return{assign(pid){const process=a.OpenProcess(PROCESS_SET_QUOTA|PROCESS_TERMINATE,0,pid);if(!process)throw Error(`OpenProcess failed (${a.GetLastError()}).`);try{if(!a.AssignProcessToJobObject(handle,process))throw Error(`AssignProcessToJobObject failed (${a.GetLastError()}).`)}finally{a.CloseHandle(process)}},terminate(){if(!closed)a.TerminateJobObject(handle,1)},activeProcesses(){if(closed)return 0;const out={};if(!a.QueryInformationJobObject(handle,JobObjectBasicAccountingInformation,out,a.koffi.sizeof(a.accounting),null))throw Error(`QueryInformationJobObject failed (${a.GetLastError()}).`);return Number(out.ActiveProcesses)},close(){if(!closed){closed=true;a.CloseHandle(handle)}}}}export function windowsJobQuiescent(name){const a=api??=load(),handle=a.OpenJobObjectW(4,0,Buffer.from(name+"\0","utf16le"));if(!handle)return a.GetLastError()===2;try{const out={};if(!a.QueryInformationJobObject(handle,JobObjectBasicAccountingInformation,out,a.koffi.sizeof(a.accounting),null))return false;return out.ActiveProcesses===0}finally{a.CloseHandle(handle)}}
@@ -1 +1,4 @@
1
- import{DatabaseSync}from"node:sqlite";import{mkdir,lstat,realpath,chmod}from"node:fs/promises";import{isAbsolute,join}from"node:path";export const name="zortex-product-account";export const inject=["zortexTelemetry"];const authority="https://zortex.me/api/product-auth";const uuid=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function session(value){if(!value||typeof value!=="object")throw Error("Invalid account response.");const v=value;if(!uuid.test(v.id)||typeof v.email!=="string"||v.email.length>254||typeof v.token!=="string"||v.token.length<32||v.token.length>128||!Number.isSafeInteger(v.registeredAt)||!Number.isSafeInteger(v.expiresAt)||v.expiresAt<=v.registeredAt)throw Error("Invalid account response.");return{id:v.id,email:v.email,token:v.token,registeredAt:v.registeredAt,expiresAt:v.expiresAt}}export async function createAccount(config,request=fetch,clock=Date.now,onSignIn=async()=>{}){if(!isAbsolute(config.root))throw Error("Account root must be absolute.");await mkdir(config.root,{recursive:true,mode:448});if((await lstat(config.root)).isSymbolicLink())throw Error("Account root cannot be a link.");const file=join(await realpath(config.root),"account.sqlite");if((await lstat(file).catch(()=>null))?.isSymbolicLink())throw Error("Account store cannot be a link.");const db=new DatabaseSync(file);try{await chmod(file,384);db.exec("PRAGMA busy_timeout=3000;CREATE TABLE IF NOT EXISTS session(value TEXT NOT NULL);CREATE TABLE IF NOT EXISTS identities(id TEXT NOT NULL,registered INTEGER NOT NULL,start INTEGER NOT NULL,end INTEGER NOT NULL);")}catch(error){db.close();throw error}let current,challenge,closed=false;let queue=Promise.resolve();const abort=new AbortController;const exclusive=work=>{const next=queue.then(()=>{if(closed)throw Error("Account service is closed.");return work()});queue=next.catch(()=>{});return next};const refresh=()=>{const saved=db.prepare("SELECT value FROM session").get();current=void 0;if(saved)try{current=session(JSON.parse(String(saved.value)))}catch{db.prepare("DELETE FROM session").run()}};refresh();const clear=expectedToken=>{db.exec("BEGIN IMMEDIATE");try{refresh();if(expectedToken&&current?.token!==expectedToken){db.exec("COMMIT");return}db.prepare("UPDATE identities SET end=? WHERE end>?").run(clock(),clock());db.prepare("DELETE FROM session").run();db.exec("COMMIT")}catch(e){db.exec("ROLLBACK");throw e}current=void 0;challenge=void 0};if(!current)clear();async function call(path,body,bearer){let response;try{response=await request(authority+path,{method:body===void 0?"GET":"POST",headers:{...body===void 0?{}:{"content-type":"application/json"},...bearer?{authorization:"Bearer "+bearer}:{}},...body===void 0?{}:{body:JSON.stringify(body)},redirect:"error",signal:AbortSignal.any([abort.signal,AbortSignal.timeout(3e4)])})}catch{throw Error("Cannot reach Zortex sign-in service. Try again.")}if(!response.ok){await response.body?.cancel();if(response.status===401){if(path==="/me")clear(bearer);throw Error(path==="/verify"?"Invalid or expired code. Request a new code after five attempts.":"Your session expired. Sign in again.")}throw Error(response.status===429?"Too many attempts. Wait before trying again.":response.status===503?"Email delivery is unavailable. Try again later.":"Zortex sign-in request failed.")}if(response.status===204)return{};const reader=response.body?.getReader();let text="";let size=0;const decoder=new TextDecoder;if(reader)try{for(;;){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>4096){await reader.cancel();throw Error("Invalid account response.")}text+=decoder.decode(part.value,{stream:true})}}finally{reader.releaseLock()}try{return JSON.parse(text)}catch{throw Error("Invalid account response.")}}if(current){const validating=current;if(validating.expiresAt*1e3<=clock())clear(validating.token);else try{const me=await call("/me",void 0,validating.token);if(me.id!==validating.id)clear(validating.token)}catch{}}function view(){refresh();if(current&&current.expiresAt*1e3<=clock())clear(current.token);return current?{state:"signed_in",id:current.id,email:current.email,expiresAt:current.expiresAt}:{state:"signed_out"}}return{status:()=>exclusive(async()=>view()),requestCode:email=>exclusive(async()=>{if(typeof email!=="string"||email.length>254||!/^\S+@\S+\.\S+$/.test(email.trim()))throw Error("Enter a valid email address.");challenge=void 0;const value=await call("/challenge",{email:email.trim()});if(typeof value.challenge!=="string"||typeof value.secret!=="string"||value.challenge.length>128||value.secret.length>128||value.expiresIn!==600)throw Error("Invalid account response.");challenge={challenge:value.challenge,secret:value.secret,expires:clock()+6e5};return{expiresIn:600}}),verify:code=>exclusive(async()=>{if(!challenge||challenge.expires<=clock())throw Error("Request a new code first.");if(!/^\d{8}$/.test(code))throw Error("Enter the eight-digit code from your email.");const value=session(await call("/verify",{challenge:challenge.challenge,secret:challenge.secret,code}));if(value.expiresAt*1e3<=clock())throw Error("Invalid account response.");const now=clock();db.exec("BEGIN IMMEDIATE");try{db.prepare("UPDATE identities SET end=? WHERE end>?").run(now,now);db.prepare("DELETE FROM session").run();db.prepare("INSERT INTO session VALUES(?)").run(JSON.stringify(value));db.prepare("INSERT INTO identities VALUES(?,?,?,?)").run(value.id,value.registeredAt,now,value.expiresAt*1e3);db.exec("COMMIT")}catch(e){db.exec("ROLLBACK");throw e}current=value;challenge=void 0;await onSignIn().catch(()=>{});return view()}),logout:()=>exclusive(async()=>{view();const token=current?.token;clear(token);if(token)await call("/logout",{},token)}),identityAt(at){if(closed)return;const time=Date.parse(at);if(!Number.isFinite(time))return;const row=db.prepare("SELECT id,registered FROM identities WHERE start<=? AND end>? ORDER BY start DESC LIMIT 1").get(time,time);return row?{id:String(row.id),registeredAt:Number(row.registered)}:void 0},async close(){if(closed)return;closed=true;abort.abort();await queue;db.close()}}}export async function apply(ctx,config){const telemetry=ctx.get("zortexTelemetry");const account=await createAccount(config,fetch,Date.now,async()=>telemetry?.record({operation:"product.account_signed_in",outcome:"ok",durationMs:0}));ctx.provide("zortexProductAccount",account);ctx.effect(()=>()=>account.close())}
1
+ import{sign}from"node:crypto";import{openSessionStore,session}from"./session-store.js";export const name="zortex-product-account";export const inject=["zortexTelemetry"];const authority="https://zortex.me/api/product-auth";export async function createAccount(config,request=fetch,clock=Date.now,onSignIn=async()=>{},options={}){const store=await openSessionStore(config.root,clock,options.codec);let challenge,closed=false,unavailableAt;let queue=Promise.resolve();const abort=new AbortController;const exclusive=work=>{const next=queue.then(()=>{if(closed)throw Error("Account service is closed.");return work()});queue=next.catch(()=>{});return next};async function read(){let state=await store.read();if(state.state==="ready"&&state.value&&state.value.expiresAt*1e3<=clock()){store.clear(state.version);state=await store.read()}if(state.state==="unavailable")unavailableAt??=clock();else unavailableAt=void 0;return state}async function discardRejected(bearer){const state=await read();if(state.state==="ready"&&state.value?.token===bearer)store.clear(state.version)}async function call(path,body,bearer){let response;try{response=await request(authority+path,{method:body===void 0?"GET":"POST",headers:{...body===void 0?{}:{"content-type":"application/json"},...bearer?{authorization:"Bearer "+bearer}:{}},...body===void 0?{}:{body:JSON.stringify(body)},redirect:"error",signal:AbortSignal.any([abort.signal,AbortSignal.timeout(3e4)])})}catch{throw Error("Cannot reach Zortex sign-in service. Try again.")}if(!response.ok){await response.body?.cancel();if(response.status===401){if(path==="/me"&&bearer)await discardRejected(bearer);throw Error(path==="/verify"?"Invalid or expired code. Request a new code after five attempts.":"Your session expired. Sign in again.")}throw Error(response.status===429?"Too many attempts. Wait before trying again.":response.status===503?"Email delivery is unavailable. Try again later.":"Zortex sign-in request failed.")}if(response.status===204)return{};const reader=response.body?.getReader();let text="";let size=0;const decoder=new TextDecoder;if(reader)try{for(;;){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>4096){await reader.cancel();throw Error("Invalid account response.")}text+=decoder.decode(part.value,{stream:true})}text+=decoder.decode()}finally{reader.releaseLock()}try{return JSON.parse(text)}catch{throw Error("Invalid account response.")}}try{const initial=await read();if(initial.state==="ready"&&!initial.value)store.closeOrphanedIdentities(initial.version);if(initial.state==="ready"&&initial.value){const validating=initial.value;try{const me=await call("/me",void 0,validating.token);if(me.id!==validating.id)await discardRejected(validating.token)}catch{}}}catch(error){store.close();throw error}async function view(){const state=await read();if(state.state==="unavailable")return{state:"unavailable",reason:state.reason,message:state.message};const current=state.value;return current?{state:"signed_in",id:current.id,email:current.email,expiresAt:current.expiresAt}:{state:"signed_out"}}const managedError=code=>Object.assign(Error("Managed JEV unavailable."),{code});let deviceToken;async function jevBearer(signal){return exclusive(async()=>{if(signal.aborted||abort.signal.aborted)throw managedError("cancelled");const state=await read();if(state.state!=="ready")throw managedError("managed_jev_service_unavailable");if(state.value)return state.value.token;if(deviceToken&&deviceToken.expiresAt*1e3>clock()+3e4)return deviceToken.token;let identity;try{identity=await store.deviceIdentity()}catch{throw managedError("managed_jev_service_unavailable")}if(signal.aborted||abort.signal.aborted)throw managedError("cancelled");async function provision(path,body){const timeout=AbortSignal.timeout(23e3);let response;try{response=await request(authority+"/autopilot/"+path,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(body),redirect:"error",signal:AbortSignal.any([signal,abort.signal,timeout])})}catch{throw managedError(signal.aborted||abort.signal.aborted?"cancelled":timeout.aborted?"managed_jev_timeout":"managed_jev_network")}if(!response.ok){await response.body?.cancel();throw managedError(response.status===429?"managed_jev_rate_limited":response.status===404?"managed_jev_route_missing":"managed_jev_service_unavailable")}const reader=response.body?.getReader();if(!reader)throw managedError("managed_jev_invalid_response");let raw="";let bytes=0;const decoder=new TextDecoder;try{for(;;){const part=await reader.read();if(part.done)break;bytes+=part.value.byteLength;if(bytes>4096){await reader.cancel();throw managedError("managed_jev_invalid_response")}raw+=decoder.decode(part.value,{stream:true})}raw+=decoder.decode()}catch(error){if(signal.aborted||abort.signal.aborted||timeout.aborted)throw managedError(signal.aborted||abort.signal.aborted?"cancelled":"managed_jev_timeout");throw error}finally{reader.releaseLock()}try{return JSON.parse(raw)}catch{throw managedError("managed_jev_invalid_response")}}const{publicKey}=identity;const challenge2=await provision("device-challenge",{publicKey});if(typeof challenge2?.challenge!=="string"||!/^[A-Za-z0-9_-]{32,128}$/.test(challenge2.challenge)||!Number.isSafeInteger(challenge2.expiresAt)||challenge2.expiresAt*1e3<=clock())throw managedError("managed_jev_invalid_response");const signature=sign(null,Buffer.from(`zortex-autopilot-device/v1
2
+ ${challenge2.challenge}
3
+ ${publicKey}
4
+ `),identity.privateKey).toString("base64url");const token=await provision("device-token",{publicKey,challenge:challenge2.challenge,signature});if(typeof token?.token!=="string"||!/^jev_device_[A-Za-z0-9_-]{32,128}$/.test(token.token)||!Number.isSafeInteger(token.expiresAt)||token.expiresAt*1e3<=clock()+3e4||token.expiresAt*1e3>clock()+36e5)throw managedError("managed_jev_invalid_response");deviceToken={token:token.token,expiresAt:token.expiresAt};return deviceToken.token})}async function managedJev(path,signal,body){const token=await jevBearer(signal);const payload=body===void 0?void 0:JSON.stringify(body);if(payload!==void 0&&Buffer.byteLength(payload)>128*1024)throw managedError("managed_jev_invalid_response");const timeout=AbortSignal.timeout(23e3);let response;try{response=await request(authority+"/autopilot/"+path,{method:body===void 0?"GET":"POST",headers:{authorization:"Bearer "+token,...body===void 0?{}:{"content-type":"application/json"}},...payload===void 0?{}:{body:payload},redirect:"error",signal:AbortSignal.any([signal,abort.signal,timeout])})}catch{throw managedError(signal.aborted||abort.signal.aborted?"cancelled":timeout.aborted?"managed_jev_timeout":"managed_jev_network")}if(!response.ok){if(response.status===401&&deviceToken?.token===token)deviceToken=void 0;try{await response.body?.cancel()}catch{}throw managedError(response.status===401||response.status===403?"managed_jev_auth_refused":response.status===404?"managed_jev_route_missing":response.status===429?"managed_jev_rate_limited":"managed_jev_service_unavailable")}const reader=response.body?.getReader();if(!reader)throw managedError("managed_jev_invalid_response");const chunks=[];let size=0;try{for(;;){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>512*1024){await reader.cancel();throw managedError("managed_jev_invalid_response")}chunks.push(part.value)}}catch(error){if(signal.aborted||abort.signal.aborted||timeout.aborted)throw managedError(signal.aborted||abort.signal.aborted?"cancelled":"managed_jev_timeout");throw error}finally{reader.releaseLock()}try{return JSON.parse(Buffer.concat(chunks).toString("utf8"))}catch{throw managedError("managed_jev_invalid_response")}}const availability=async signal=>{try{const result=await managedJev("status",signal);if(result&&typeof result==="object"&&"jev"in result){if(result.jev===true)return{state:"available"};if(result.jev===false)return{state:"unavailable",code:"managed_jev_not_enabled"}}return{state:"unavailable",code:"managed_jev_invalid_response"}}catch(error){const code=error&&typeof error==="object"&&"code"in error?error.code:void 0;const allowed=["managed_jev_signed_out","managed_jev_auth_refused","managed_jev_route_missing","managed_jev_rate_limited","managed_jev_service_unavailable","managed_jev_network","managed_jev_invalid_response","managed_jev_not_enabled","managed_jev_timeout","cancelled"];return{state:"unavailable",code:typeof code==="string"&&allowed.includes(code)?code:"managed_jev_service_unavailable"}}};return{status:()=>exclusive(view),jev:{availability,ready:async signal=>(await availability(signal)).state==="available",decide:(body,signal)=>managedJev("decision",signal,body)},requestCode:email=>exclusive(async()=>{if(typeof email!=="string"||email.length>254||!/^\S+@\S+\.\S+$/.test(email.trim()))throw Error("Enter a valid email address.");challenge=void 0;const value=await call("/challenge",{email:email.trim()});if(typeof value.challenge!=="string"||typeof value.secret!=="string"||value.challenge.length>128||value.secret.length>128||value.expiresIn!==600)throw Error("Invalid account response.");challenge={challenge:value.challenge,secret:value.secret,expires:clock()+6e5};return{expiresIn:600}}),verify:code=>exclusive(async()=>{if(!challenge||challenge.expires<=clock())throw Error("Request a new code first.");if(!/^\d{8}$/.test(code))throw Error("Enter the eight-digit code from your email.");const before=await read();if(before.state==="unavailable")throw Error(before.message);const value=session(await call("/verify",{challenge:challenge.challenge,secret:challenge.secret,code}));if(value.expiresAt*1e3<=clock())throw Error("Invalid account response.");await store.save(value,before.version);challenge=void 0;await onSignIn().catch(()=>{});return view()}),logout:()=>exclusive(async()=>{const state=await read(),token=state.state==="ready"?state.value?.token:void 0;store.clear();challenge=void 0;unavailableAt=void 0;if(token)await call("/logout",{},token)}),identityAt(at){if(closed)return;const time=Date.parse(at);if(!Number.isFinite(time)||unavailableAt!==void 0&&time>=unavailableAt)return;return store.identityAt(time)},async close(){if(closed)return;closed=true;abort.abort();await queue;store.close()}}}export async function apply(ctx,config){const telemetry=ctx.get("zortexTelemetry");const account=await createAccount(config,fetch,Date.now,async()=>telemetry?.record({operation:"product.account_signed_in",outcome:"ok",durationMs:0}));ctx.provide("zortexProductAccount",account);ctx.effect(()=>()=>account.close())}
@@ -0,0 +1,10 @@
1
+ import{DatabaseSync}from"node:sqlite";import{randomUUID,generateKeyPairSync,createPrivateKey,createPublicKey}from"node:crypto";import{mkdir,lstat,realpath,chmod}from"node:fs/promises";import{isAbsolute,join}from"node:path";import{createSystemCodec}from"@zortexhq/plugin-vault-sqlite/codec";const uuid=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;export function session(value){if(!value||typeof value!=="object")throw Error("Invalid account response.");const v=value;if(!uuid.test(v.id)||typeof v.email!=="string"||v.email.length>254||typeof v.token!=="string"||v.token.length<32||v.token.length>128||!Number.isSafeInteger(v.registeredAt)||!Number.isSafeInteger(v.expiresAt)||v.expiresAt<=v.registeredAt)throw Error("Invalid account response.");return{id:v.id,email:v.email,token:v.token,registeredAt:v.registeredAt,expiresAt:v.expiresAt}}export async function openSessionStore(root,clock,providedCodec){if(!isAbsolute(root))throw Error("Account root must be absolute.");await mkdir(root,{recursive:true,mode:448});if((await lstat(root)).isSymbolicLink())throw Error("Account root cannot be a link.");const file=join(await realpath(root),"account.sqlite");if((await lstat(file).catch(()=>null))?.isSymbolicLink())throw Error("Account store cannot be a link.");const db=new DatabaseSync(file);try{await chmod(file,384);db.exec(`PRAGMA busy_timeout=3000;PRAGMA secure_delete=ON;
2
+ CREATE TABLE IF NOT EXISTS session(value TEXT NOT NULL);
3
+ CREATE TABLE IF NOT EXISTS jev_device(id INTEGER PRIMARY KEY CHECK(id=1),ciphertext TEXT NOT NULL);
4
+ CREATE TABLE IF NOT EXISTS identities(id TEXT NOT NULL,registered INTEGER NOT NULL,start INTEGER NOT NULL,end INTEGER NOT NULL);
5
+ CREATE TABLE IF NOT EXISTS account_store(id INTEGER PRIMARY KEY CHECK(id=1),store_id TEXT NOT NULL,format INTEGER NOT NULL,writable INTEGER NOT NULL DEFAULT 0,revision INTEGER NOT NULL DEFAULT 0,scrub_pending INTEGER NOT NULL DEFAULT 0);`);db.prepare("INSERT OR IGNORE INTO account_store(id,store_id,format) VALUES(1,?,1)").run(randomUUID());for(const event of["INSERT","UPDATE","DELETE"]){db.exec(`CREATE TRIGGER IF NOT EXISTS account_session_guard_${event.toLowerCase()} BEFORE ${event} ON session
6
+ WHEN (SELECT format>=2 AND writable=0 FROM account_store WHERE id=1)
7
+ BEGIN SELECT RAISE(ABORT,'A newer account runtime is required for this protected store.'); END;
8
+ CREATE TRIGGER IF NOT EXISTS account_session_revision_${event.toLowerCase()} AFTER ${event} ON session
9
+ WHEN (SELECT writable=0 FROM account_store WHERE id=1)
10
+ BEGIN UPDATE account_store SET revision=revision+1 WHERE id=1; END;`)}}catch(error){db.close();throw error}const metadata=db.prepare("SELECT store_id,format,writable,revision,scrub_pending FROM account_store WHERE id=1");const first=metadata.get();if(!first||!uuid.test(String(first.store_id))||first.writable!==0||![1,2].includes(Number(first.format))){db.close();throw Error("Account store format is unavailable.")}const codec=providedCodec??createSystemCodec({account:"zortex-product-account-"+String(first.store_id)});let closed=false;function capture(){db.exec("BEGIN");try{const meta=metadata.get(),rows=db.prepare("SELECT value FROM session LIMIT 2").all();if(rows.length>1)throw Error("Account store has conflicting sessions.");const value={revision:Number(meta.revision),raw:rows.length?String(rows[0].value):void 0,format:Number(meta.format),scrubPending:meta.scrub_pending===1};db.exec("COMMIT");return value}catch(error){db.exec("ROLLBACK");throw error}}function same(a,b){return a.revision===b.revision&&a.raw===b.raw}function mutate(expected,work){db.exec("BEGIN IMMEDIATE");try{const row=db.prepare("SELECT value FROM session").get(),revision=Number(metadata.get().revision);if(expected&&!same(expected,{revision,raw:row?String(row.value):void 0})){db.exec("ROLLBACK");return false}db.prepare("UPDATE account_store SET writable=1 WHERE id=1").run();work();db.prepare("UPDATE account_store SET writable=0,revision=revision+1 WHERE id=1").run();db.exec("COMMIT");return true}catch(error){db.exec("ROLLBACK");throw error}}function clear(expected){return mutate(expected,()=>{const at=clock();db.prepare("UPDATE identities SET end=? WHERE end>?").run(at,at);db.prepare("DELETE FROM session").run()})}function scrub(){const before=db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();if(before&&Number(before.busy)>0)throw Error("Account protection cleanup is pending.");db.exec("VACUUM");const after=db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();if(after&&Number(after.busy)>0)throw Error("Account protection cleanup is pending.");db.prepare("UPDATE account_store SET scrub_pending=0 WHERE id=1").run()}function unavailable(version,reason){const messages={protection_unavailable:"Protected account storage is temporarily unavailable. The saved session is preserved.",protected_session_invalid:"The protected account session could not be decoded. Its saved data is preserved.",protection_cleanup_pending:"Account protection migration is finishing. Its saved session is preserved.",session_changed:"The account session changed while it was being read. Retry the operation."};return{state:"unavailable",version,reason,message:messages[reason]}}async function read(){for(let tries=0;tries<4;tries++){const saved=capture();if(saved.scrubPending)try{scrub()}catch{return unavailable(saved,"protection_cleanup_pending")}if(saved.raw===void 0)return{state:"ready",version:saved};let parsed;try{parsed=JSON.parse(saved.raw)}catch{if(saved.format>=2)return unavailable(saved,"protected_session_invalid");clear(saved);continue}if(saved.format>=2){const envelope=parsed;if(!envelope||envelope.version!==2||typeof envelope.ciphertext!=="string"||!envelope.ciphertext.length||envelope.ciphertext.length>65536)return unavailable(saved,"protected_session_invalid");let plaintext;try{plaintext=await codec.open(envelope.ciphertext)}catch{if(!same(saved,capture()))continue;return unavailable(saved,"protection_unavailable")}if(!same(saved,capture()))continue;try{return{state:"ready",value:session(JSON.parse(plaintext)),version:saved}}catch{return unavailable(saved,"protected_session_invalid")}}let legacy;try{legacy=session(parsed)}catch{clear(saved);continue}let ciphertext;try{ciphertext=await codec.seal(JSON.stringify(legacy))}catch{if(!same(saved,capture()))continue;return unavailable(saved,"protection_unavailable")}if(!mutate(saved,()=>{db.prepare("UPDATE account_store SET format=2,scrub_pending=1 WHERE id=1").run();db.prepare("UPDATE session SET value=?").run(JSON.stringify({version:2,ciphertext}))}))continue}return unavailable(capture(),"session_changed")}return{read,async deviceIdentity(){let row=db.prepare("SELECT ciphertext FROM jev_device WHERE id=1").get();if(!row){const pair=generateKeyPairSync("ed25519");const ciphertext=await codec.seal(pair.privateKey.export({type:"pkcs8",format:"pem"}).toString());db.prepare("INSERT OR IGNORE INTO jev_device VALUES(1,?)").run(ciphertext);row=db.prepare("SELECT ciphertext FROM jev_device WHERE id=1").get()}const privateKey=createPrivateKey(await codec.open(String(row.ciphertext)));if(privateKey.asymmetricKeyType!=="ed25519")throw Error("Invalid device identity.");const publicKey=createPublicKey(privateKey).export({format:"jwk"}).x;if(!publicKey)throw Error("Invalid device identity.");return{privateKey,publicKey}},async save(value,expected){let ciphertext;try{ciphertext=await codec.seal(JSON.stringify(value))}catch{throw Error("Account protection is unavailable. Sign-in was not persisted.")}const saved=mutate(expected,()=>{const at=clock();db.prepare("UPDATE account_store SET format=2 WHERE id=1").run();db.prepare("UPDATE identities SET end=? WHERE end>?").run(at,at);db.prepare("DELETE FROM session").run();db.prepare("INSERT INTO session VALUES(?)").run(JSON.stringify({version:2,ciphertext}));db.prepare("INSERT INTO identities VALUES(?,?,?,?)").run(value.id,value.registeredAt,at,value.expiresAt*1e3)});if(!saved)throw Error("The account changed while signing in. The newer account state was preserved.")},clear,closeOrphanedIdentities(expected){if(expected.raw===void 0&&db.prepare("SELECT 1 FROM identities WHERE end>? LIMIT 1").get(clock()))clear(expected)},identityAt(time){const row=db.prepare("SELECT id,registered FROM identities WHERE start<=? AND end>? ORDER BY start DESC LIMIT 1").get(time,time);return row?{id:String(row.id),registeredAt:Number(row.registered)}:void 0},close(){if(!closed){closed=true;db.close()}}}}
@@ -0,0 +1 @@
1
+ import{DatabaseSync}from"node:sqlite";import{lstat}from"node:fs/promises";import{join,isAbsolute}from"node:path";export async function accountStorageFormat(root){if(!isAbsolute(root))throw Error("Account root must be absolute.");const file=join(root,"account.sqlite");let stat;try{stat=await lstat(file)}catch(error){if(error.code==="ENOENT")return 1;throw error}if(!stat.isFile()||stat.isSymbolicLink())throw Error("Account store cannot be a link.");const db=new DatabaseSync(file,{readOnly:true,allowExtension:false,timeout:1e3});try{const exists=db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='account_store'").get();if(!exists)return 1;const value=Number(db.prepare("SELECT format FROM account_store WHERE id=1").get()?.format);if(!Number.isSafeInteger(value)||value<1)throw Error("Account format metadata is invalid.");return value}finally{db.close()}}
@@ -5,10 +5,14 @@
5
5
  "exports": {
6
6
  ".": {
7
7
  "import": "./dist/index.js"
8
+ },
9
+ "./storage": {
10
+ "import": "./dist/storage.js"
8
11
  }
9
12
  },
10
13
  "dependencies": {
11
- "@zortexhq/plugin-telemetry": "0.1.0"
14
+ "@zortexhq/plugin-telemetry": "0.1.0",
15
+ "@zortexhq/plugin-vault-sqlite": "0.1.0"
12
16
  },
13
17
  "zortex": {
14
18
  "role": "plugin"
@@ -1 +1 @@
1
- import{AsyncLocalStorage}from"node:async_hooks";import{randomUUID}from"node:crypto";import{AUTHORIZATION_REASON_CODES}from"./telemetry.js";import{currentFeedbackFlow,isFlowId}from"./trace.js";import{currentUsageInvocation,USAGE_TOOL_NAMES,USAGE_ENTRYPOINTS}from"./observations.js";import{isTelemetrySourceId}from"./source-ids.js";import{OPERATIONAL_TOOL_METHODS}from"./tool-methods.js";import{OPERATIONAL_UPSTREAM_TOOLS,OPERATIONAL_RPC_METHODS}from"./upstream-tools.js";export const OPERATIONAL_PHASES=["onboarding","tool","connector","browser","computer","runtime"];export const OPERATIONAL_ACTIONS=["source_selection","session_selection","readiness","login","open","reuse","connect","observe","click","type","scroll","key","download","install","cleanup","execute","status","catalog","read","invoke","review","cancel","share","goal","plan","ground","reveal","call","list_tools"];export const OPERATIONAL_STATES=["started","completed","failed","cancelled","waiting","unknown"];export const OPERATIONAL_ROUTES=["extension","attached_chrome","native_chrome","isolated_chromium","upstream_browser","mcp_stdio","mcp_http","unknown"];export const OPERATIONAL_PROFILES=["existing","dedicated","temporary","unknown"];export const OPERATIONAL_LOGIN_DECISIONS=["reuse","start_login","not_available","unknown"];export const OPERATIONAL_SELECTIONS=["default_roster","requested","saved","recovery","explicit","unknown"];export const OPERATIONAL_TRIGGERS=["automatic_startup","agent_action","user_request","recovery","scheduled","unknown"];export const OPERATIONAL_ARTIFACT_FAMILIES=["chatgpt_desktop","chromium","codex","indra","connector_runtime","other","unknown"];export const OPERATIONAL_ARTIFACT_TYPES=["installer","archive","package","browser_download","unknown"];export const OPERATIONAL_REASONS=[...AUTHORIZATION_REASON_CODES,"runtime_missing","browser_missing","browser_driver_unavailable","not_available","provider_failure"];export const OPERATIONAL_ERRORS=["timeout","denied","network","provider","storage","identity","unknown"];export const OPERATIONAL_DOWNLOAD_OBSERVATION=["supported","unavailable","unknown"];export const OPERATIONAL_OPERATIONS=["hub.status","hub.connect","hub.job","hub.cancel","hub.check","hub.read","hub.catalog","hub.method","hub.review","hub.invoke_reviewed","hub.invoke","hub.capture_information","hub.verify_information","hub.inspect_file","hub.materialize_file","tool.search","tool.context","tool.sql","tool.actions","tool.action","tool.manage","tool.instruction","tool.handbook","tool.read","tool.update","connector.status","connector.mcp_call_tool","connector.mcp_list_tools","connector.connect","connector.recover","connector.job","connector.read","connector.find","connector.invoke","connector.sync","connector.disconnect","fleet.status","fleet.run","fleet.receipt","share.preview","share.create-link","share.inspect-link","share.read-file","browser.open","browser.observe","browser.click","browser.type","browser.scroll","browser.key","browser.close","browser.run_goal","browser.plan","browser.ground","browser.reveal","resident.configure","resident.connect_manual","resident.connect_automatic","resident.reauthorize","resident.recover","resident.connect_write","resident.connect","resident.connect_job","resident.cancel_connect","resident.reconnect","resident.startup","resident.pause_automation","resident.resume_sync","resident.local_cloud","resident.status","resident.stop","resident.check","unknown"];const fieldEnums={operationId:OPERATIONAL_OPERATIONS,countBasis:["catalog_total","returned_entries","available_sources"],route:OPERATIONAL_ROUTES,profile:OPERATIONAL_PROFILES,loginDecision:OPERATIONAL_LOGIN_DECISIONS,selection:OPERATIONAL_SELECTIONS,trigger:OPERATIONAL_TRIGGERS,artifactFamily:OPERATIONAL_ARTIFACT_FAMILIES,artifactType:OPERATIONAL_ARTIFACT_TYPES,reason:OPERATIONAL_REASONS,errorCategory:OPERATIONAL_ERRORS,tool:USAGE_TOOL_NAMES,method:OPERATIONAL_TOOL_METHODS,entrypoint:USAGE_ENTRYPOINTS,downloadObservation:OPERATIONAL_DOWNLOAD_OBSERVATION,upstreamTool:OPERATIONAL_UPSTREAM_TOOLS,rpcMethod:OPERATIONAL_RPC_METHODS};const fieldKeys=[...Object.keys(fieldEnums),"observedCount","processRef","actionRef","sourceRef"],enumHas=(values,value)=>typeof value==="string"&&values.includes(value);const isOperationalReference=value=>typeof value==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value);const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const closed=(value,keys)=>Object.keys(value).every(key=>keys.includes(key));function validFields(value){return Object.entries(fieldEnums).every(([key,values])=>value[key]===void 0||enumHas(values,value[key]))&&(value.observedCount===void 0?value.countBasis===void 0:Number.isSafeInteger(value.observedCount)&&Number(value.observedCount)>=0&&Number(value.observedCount)<=1e8&&value.countBasis!==void 0)&&["processRef","actionRef","sourceRef"].every(key=>value[key]===void 0||isOperationalReference(value[key]))}export function isOperationalContext(value){return object(value)&&closed(value,["runId","stepId"])&&isFlowId(value.runId)&&isFlowId(value.stepId)}export function isUsageOperationalTrace(value){if(!object(value)||!closed(value,["version","runId","stepId","parentStepId","emitterId","sequence","attempt","phase","action","state","terminal","durationKnown",...fieldKeys]))return false;return value.version===1&&isFlowId(value.runId)&&isFlowId(value.stepId)&&isFlowId(value.emitterId)&&(value.parentStepId===void 0||isFlowId(value.parentStepId)&&value.parentStepId!==value.stepId)&&Number.isSafeInteger(value.sequence)&&Number(value.sequence)>0&&Number(value.sequence)<=1e9&&Number.isSafeInteger(value.attempt)&&Number(value.attempt)>0&&Number(value.attempt)<=1e4&&enumHas(OPERATIONAL_PHASES,value.phase)&&enumHas(OPERATIONAL_ACTIONS,value.action)&&enumHas(OPERATIONAL_STATES,value.state)&&typeof value.terminal==="boolean"&&typeof value.durationKnown==="boolean"&&validFields(value)&&(["started","waiting"].includes(String(value.state))?!value.terminal&&!value.durationKnown:["completed","failed","cancelled"].includes(String(value.state))?value.terminal:!value.durationKnown||value.terminal)}export function operationalReason(value){return enumHas(OPERATIONAL_REASONS,value)?value:"unknown"}const executionContext=new AsyncLocalStorage;let emitterId=randomUUID(),sequence=0;function emissionOrder(){if(sequence>=1e9){emitterId=randomUUID();sequence=0}return{emitterId,sequence:++sequence}}export function withoutOperationalContext(run){return executionContext.exit(run)}export function currentOperationalExecution(){const value=executionContext.getStore();return value?{runId:value.runId,stepId:value.stepId}:void 0}export function withOperationalContext(input,run){const captured={...input};if(!isOperationalContext(captured))throw Error("Invalid operational context.");return executionContext.run(captured,run)}export function startOperationalRun(metrics,input){return executionContext.exit(()=>startOperationalStep(metrics,input))}export function startOperationalStep(metrics,input){const parent=executionContext.getStore(),fallback=currentFeedbackFlow()?.flowId??currentUsageInvocation()?.id;const scope={runId:parent?.runId??(isFlowId(fallback)?fallback:randomUUID()),stepId:randomUUID()};const pending=new Set;let fields,finished=false;const enabled=()=>{try{const value=metrics?.();return value?.isEnabled?.()===true?value:void 0}catch{return void 0}};const service=enabled();if(service)try{const value={...typeof input==="function"?input():input};if(closed(value,["runId","source","phase","action","attempt",...fieldKeys])&&enumHas(OPERATIONAL_PHASES,value.phase)&&enumHas(OPERATIONAL_ACTIONS,value.action)&&validFields(value)&&(value.runId===void 0||isFlowId(value.runId))&&(value.source===void 0||typeof value.source==="string")&&(value.attempt===void 0||Number.isSafeInteger(value.attempt)&&value.attempt>0&&value.attempt<=1e4)){if(value.source)try{const reference=service.sourceReference?.(value.source);if(isOperationalReference(reference))value.sourceRef=reference}catch{}fields=value;if(!parent&&isFlowId(value.runId))scope.runId=value.runId}}catch{}const started=performance.now();const emit=(state,terminal,extra={})=>{const target=enabled();if(!target||!fields)return;let details;try{details={...extra}}catch{return}if(!closed(details,fieldKeys)||!validFields(details))return;const combined=Object.fromEntries(Object.entries({...fields,...details}).filter(([key,value])=>fieldKeys.includes(key)&&value!==void 0));const elapsed=terminal?performance.now()-started:0;const durationKnown=terminal&&Number.isFinite(elapsed)&&elapsed>=0&&elapsed<=864e5;const durationMs=durationKnown?elapsed:0;const operational={version:1,runId:scope.runId,stepId:scope.stepId,...parent?{parentStepId:parent.stepId}:{},...emissionOrder(),attempt:fields.attempt??1,phase:fields.phase,action:fields.action,state,terminal,durationKnown,...combined};try{const result=executionContext.run(scope,()=>target.record({operation:"product.trace",internal:true,outcome:state==="completed"?"ok":state==="failed"?"fault":state==="cancelled"?"cancelled":"unknown",durationMs,...isTelemetrySourceId(fields.source)?{source:fields.source}:{},operational}));let timer;const bounded=Promise.race([Promise.resolve(result).then(()=>{},()=>{}),new Promise(resolve=>{timer=setTimeout(resolve,50)})]).then(()=>{if(timer)clearTimeout(timer)});pending.add(bounded);void bounded.finally(()=>pending.delete(bounded))}catch{}};const step={get runId(){return scope.runId},stepId:scope.stepId,run:fn=>executionContext.run(scope,fn),mark(value){try{if(finished||!fields||!enabled()||!value)return;const{state,...details}=value;if(["waiting","unknown"].includes(state))emit(state,false,details)}catch{}},finish(value){try{if(finished)return;finished=true;if(!fields||!enabled()||!value)return;const{state,...details}=value;if(["completed","failed","cancelled","unknown"].includes(state))emit(state,true,details)}catch{}},async flush(){await Promise.allSettled([...pending])}};emit("started",false);return step}export function operationalTraceSummary(events,collection={}){const steps=new Map,receipts=new Set;for(const row of events){if(receipts.has(row.id)||!isUsageOperationalTrace(row.operational))continue;receipts.add(row.id);const t=row.operational,key=t.runId+":"+t.stepId,step=steps.get(key)??{start:false,terminal:false};step.start||=t.state==="started";step.terminal||=t.terminal;steps.set(key,step)}const observed=steps.size>0,rows=[...steps.values()];return{coverage:"instrumented_steps_only",observation:collection.enabled===false?"disabled":observed?"observed":"unobserved",historyLimited:collection.limited===true,startedSteps:observed?rows.filter(s=>s.start).length:null,terminalSteps:observed?rows.filter(s=>s.terminal).length:null,unfinishedSteps:observed?rows.filter(s=>s.start&&!s.terminal).length:null,orphanTerminals:observed?rows.filter(s=>!s.start&&s.terminal).length:null}}
1
+ import{AsyncLocalStorage}from"node:async_hooks";import{randomUUID}from"node:crypto";import{AUTHORIZATION_REASON_CODES}from"./telemetry.js";import{currentFeedbackFlow,isFlowId}from"./trace.js";import{currentUsageInvocation,USAGE_TOOL_NAMES,USAGE_ENTRYPOINTS}from"./observations.js";import{isTelemetrySourceId}from"./source-ids.js";import{OPERATIONAL_TOOL_METHODS}from"./tool-methods.js";import{OPERATIONAL_UPSTREAM_TOOLS,OPERATIONAL_RPC_METHODS}from"./upstream-tools.js";export const OPERATIONAL_PHASES=["onboarding","tool","connector","browser","computer","runtime"];export const OPERATIONAL_ACTIONS=["source_selection","session_selection","readiness","login","open","reuse","connect","observe","click","type","scroll","key","download","install","cleanup","execute","status","catalog","read","invoke","review","cancel","share","goal","plan","ground","reveal","call","list_tools"];export const OPERATIONAL_STATES=["started","completed","failed","cancelled","waiting","unknown"];export const OPERATIONAL_ROUTES=["extension","attached_chrome","native_chrome","isolated_chromium","upstream_browser","mcp_stdio","mcp_http","cua_browser","cua_native","unknown"];export const OPERATIONAL_PROFILES=["existing","dedicated","temporary","unknown"];export const OPERATIONAL_LOGIN_DECISIONS=["reuse","start_login","not_available","unknown"];export const OPERATIONAL_SELECTIONS=["default_roster","requested","saved","recovery","explicit","unknown"];export const OPERATIONAL_TRIGGERS=["automatic_startup","agent_action","user_request","recovery","scheduled","unknown"];export const OPERATIONAL_ARTIFACT_FAMILIES=["chatgpt_desktop","chromium","codex","indra","connector_runtime","other","unknown"];export const OPERATIONAL_ARTIFACT_TYPES=["installer","archive","package","browser_download","unknown"];export const OPERATIONAL_REASONS=[...AUTHORIZATION_REASON_CODES,"runtime_missing","browser_missing","browser_driver_unavailable","not_available","provider_failure","acceleration_unavailable","model_acceleration_unavailable","model_credential_unavailable","python_runtime_unavailable","cua_driver_unavailable","cua_target_ambiguous","cua_target_unavailable","cua_binding_not_exact","cua_binding_changed","cua_tab_ambiguous","cua_tab_selection_required","cua_snapshot_unavailable","cua_page_unavailable","browser_origin_outside_scope","browser_requires_setup","browser_route_unavailable","native_target_required","cua_action_unverified","cua_unavailable","cua_refused","cua_invalid_result","cua_busy","stale_page","stale_observation","invalid_action","input_required","input_mismatch","credentials_required","loop_blocked","loop_budget","loop_timeout","source_operation_timeout","source_operation_pending","loop_failed","loop_runtime_unavailable","bridge_unavailable","bridge_busy","invalid_model_output","authorization_expired","provider_verification_pending","provider_not_ready","authorization_interrupted","agent_continuation_required","agent_requested","driver_owned","pairing_required","device_code_required","source_unavailable","source_cleanup_pending","source_cleanup_unavailable","skipped_by_agent","agent_blocked","connection_unavailable","authorization_required","receipt_conflict","sources_unavailable","no_eligible_sources","unknown_source","model_failed","worker_report_missing","confirmation_expired","confirmation_rejected","missing_field_value","model_unavailable","driver_outcome_unknown","invalid_bridge","observed_done","model_blocked","loop_no_progress","worker_cleanup_unavailable","worker_not_started","worker_task_not_claimed","worker_exit_nonzero","worker_exit_no_result","driver_unavailable","background_unavailable","browser_consent_required","invalid_freshness","invalid_task","invalid_bridge_response","not_found","aborted","authorization_failed","authorization_cancelled","job_unavailable","provider_error","login_required","source_disabled","cua_session_not_open","invalid_target","authorization_url_invalid","managed_jev_signed_out","managed_jev_auth_refused","managed_jev_route_missing","managed_jev_rate_limited","managed_jev_service_unavailable","managed_jev_network","managed_jev_invalid_response","managed_jev_not_enabled","managed_jev_timeout"];export const OPERATIONAL_ERRORS=["timeout","denied","network","provider","storage","identity","unknown"];export const OPERATIONAL_DOWNLOAD_OBSERVATION=["supported","unavailable","unknown"];export const OPERATIONAL_OPERATIONS=["hub.status","hub.connect","hub.job","hub.cancel","hub.check","hub.read","hub.catalog","hub.method","hub.review","hub.invoke_reviewed","hub.invoke","hub.capture_information","hub.verify_information","hub.inspect_file","hub.materialize_file","tool.search","tool.context","tool.sql","tool.actions","tool.action","tool.manage","tool.instruction","tool.handbook","tool.read","tool.update","connector.status","connector.mcp_call_tool","connector.mcp_list_tools","connector.connect","connector.recover","connector.job","connector.read","connector.find","connector.invoke","connector.sync","connector.disconnect","fleet.status","fleet.run","fleet.receipt","share.preview","share.create-link","share.inspect-link","share.read-file","browser.open","browser.observe","browser.click","browser.type","browser.scroll","browser.key","browser.close","browser.run_goal","browser.plan","browser.ground","browser.reveal","resident.configure","resident.connect_manual","resident.connect_automatic","resident.reauthorize","resident.recover","resident.connect_write","resident.connect","resident.connect_job","resident.cancel_connect","resident.reconnect","resident.startup","resident.pause_automation","resident.resume_sync","resident.local_cloud","resident.status","resident.stop","resident.check","autopilot.entry","autopilot.run","autopilot.source","autopilot.preflight","autopilot.provider_job","autopilot.provider_verification","autopilot.cua_session","autopilot.worker","autopilot.worker_process","autopilot.decision","autopilot.observation","autopilot.input","autopilot.freshness","autopilot.postcondition","autopilot.handoff","autopilot.prepare","unknown"];export const AUTOPILOT_ACTORS=["indra_autopilot","host_agent","unknown"];export const AUTOPILOT_PAGES=["credential_controls","challenge_controls","account_choice_controls","consent_controls","device_pairing_controls","provider_error_controls","other","unknown"];export const AUTOPILOT_TARGETS=["account_choice","consent","continue","credential","scroll","wait","other","unknown"];export const AUTOPILOT_OBSERVATIONS=["provider_ready","provider_not_ready","callback_pending","provider_connected","provider_failed","provider_cancelled","worker_done","worker_blocked","fresh","stale","action_dispatched","action_unverified","page_changed","page_unchanged","model_available","model_unavailable","selected_action","selected_done","selected_blocked","job_prepared","job_missing","source_skipped","confirmation_pending","confirmation_accepted","worker_task_received","worker_result_received","unknown"];export const AUTOPILOT_EXPECTATIONS=["provider_ready","authorization_job","observed_page","valid_decision","accepted_action","fresh_page","post_action_observation","runtime_available","source_terminal","confirmation_received","unknown"];export const AUTOPILOT_HANDOFFS=["provider","runtime","target","browser","verification","unknown"];export const AUTOPILOT_MODES=["jev","hybrid","llm"];export const AUTOPILOT_FAILURE_MODES=["FM-01","FM-02","FM-03","FM-04","FM-05","FM-06","FM-07","FM-08","FM-09","FM-10","FM-11","FM-12","FM-99"];export const AUTOPILOT_DISPOSITIONS=["pending","blocked","queued","cancelled","skipped","unresolved","handoff","unknown"];export const AUTOPILOT_READINESS_BASES=["action_catalog","verified_read","verified_operation","unknown"];export const AUTOPILOT_PAGE_EVIDENCE=["semantic_hint","unknown"];const autopilotCounters=["decisionOrdinal","observationOrdinal","rowsExamined","rowsTruncated","rowsMissingRef","rowsDisabled","rowsOffscreen","rowsProtected","rowsUnsupported","feedbackAttempted","feedbackFailed","feedbackAccepted"];const fieldEnums={operationId:OPERATIONAL_OPERATIONS,countBasis:["catalog_total","returned_entries","available_sources","selected_sources","action_candidates"],route:OPERATIONAL_ROUTES,profile:OPERATIONAL_PROFILES,loginDecision:OPERATIONAL_LOGIN_DECISIONS,selection:OPERATIONAL_SELECTIONS,trigger:OPERATIONAL_TRIGGERS,artifactFamily:OPERATIONAL_ARTIFACT_FAMILIES,artifactType:OPERATIONAL_ARTIFACT_TYPES,reason:OPERATIONAL_REASONS,errorCategory:OPERATIONAL_ERRORS,tool:USAGE_TOOL_NAMES,method:OPERATIONAL_TOOL_METHODS,entrypoint:USAGE_ENTRYPOINTS,downloadObservation:OPERATIONAL_DOWNLOAD_OBSERVATION,upstreamTool:OPERATIONAL_UPSTREAM_TOOLS,rpcMethod:OPERATIONAL_RPC_METHODS,actor:AUTOPILOT_ACTORS,pageKind:AUTOPILOT_PAGES,targetKind:AUTOPILOT_TARGETS,observed:AUTOPILOT_OBSERVATIONS,expected:AUTOPILOT_EXPECTATIONS,handoffKind:AUTOPILOT_HANDOFFS,agentMode:AUTOPILOT_MODES,failureMode:AUTOPILOT_FAILURE_MODES,disposition:AUTOPILOT_DISPOSITIONS,readinessBasis:AUTOPILOT_READINESS_BASES,pageEvidence:AUTOPILOT_PAGE_EVIDENCE};const fieldKeys=[...Object.keys(fieldEnums),"observedCount","processRef","actionRef","sourceRef",...autopilotCounters],enumHas=(values,value)=>typeof value==="string"&&values.includes(value);const isOperationalReference=value=>typeof value==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value);const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const closed=(value,keys)=>Object.keys(value).every(key=>keys.includes(key));function validFields(value){return Object.entries(fieldEnums).every(([key,values])=>value[key]===void 0||enumHas(values,value[key]))&&(value.observedCount===void 0?value.countBasis===void 0:Number.isSafeInteger(value.observedCount)&&Number(value.observedCount)>=0&&Number(value.observedCount)<=1e8&&value.countBasis!==void 0)&&["processRef","actionRef","sourceRef"].every(key=>value[key]===void 0||isOperationalReference(value[key]))&&autopilotCounters.every(key=>value[key]===void 0||Number.isSafeInteger(value[key])&&Number(value[key])>=0&&Number(value[key])<=1e8)}export function isOperationalContext(value){return object(value)&&closed(value,["runId","stepId"])&&isFlowId(value.runId)&&isFlowId(value.stepId)}export function isUsageOperationalTrace(value){if(!object(value)||!closed(value,["version","runId","stepId","parentStepId","emitterId","sequence","attempt","phase","action","state","terminal","durationKnown",...fieldKeys]))return false;return value.version===1&&isFlowId(value.runId)&&isFlowId(value.stepId)&&isFlowId(value.emitterId)&&(value.parentStepId===void 0||isFlowId(value.parentStepId)&&value.parentStepId!==value.stepId)&&Number.isSafeInteger(value.sequence)&&Number(value.sequence)>0&&Number(value.sequence)<=1e9&&Number.isSafeInteger(value.attempt)&&Number(value.attempt)>0&&Number(value.attempt)<=1e4&&enumHas(OPERATIONAL_PHASES,value.phase)&&enumHas(OPERATIONAL_ACTIONS,value.action)&&enumHas(OPERATIONAL_STATES,value.state)&&typeof value.terminal==="boolean"&&typeof value.durationKnown==="boolean"&&validFields(value)&&(["started","waiting"].includes(String(value.state))?!value.terminal&&!value.durationKnown:["completed","failed","cancelled"].includes(String(value.state))?value.terminal:!value.durationKnown||value.terminal)}export function operationalReason(value){return enumHas(OPERATIONAL_REASONS,value)?value:"unknown"}const executionContext=new AsyncLocalStorage;let emitterId=randomUUID(),sequence=0;function emissionOrder(){if(sequence>=1e9){emitterId=randomUUID();sequence=0}return{emitterId,sequence:++sequence}}export function withoutOperationalContext(run){return executionContext.exit(run)}export function currentOperationalExecution(){const value=executionContext.getStore();return value?{runId:value.runId,stepId:value.stepId}:void 0}export function withOperationalContext(input,run){const captured={...input};if(!isOperationalContext(captured))throw Error("Invalid operational context.");return executionContext.run(captured,run)}export function startOperationalRun(metrics,input){return executionContext.exit(()=>startOperationalStep(metrics,input))}export function startOperationalStep(metrics,input){const parent=executionContext.getStore(),fallback=currentFeedbackFlow()?.flowId??currentUsageInvocation()?.id;const scope={runId:parent?.runId??(isFlowId(fallback)?fallback:randomUUID()),stepId:randomUUID()};const pending=new Set;let fields,finished=false;const enabled=()=>{try{const value=metrics?.();return value?.isEnabled?.()===true?value:void 0}catch{return void 0}};const service=enabled();if(service)try{const value={...typeof input==="function"?input():input};if(closed(value,["runId","source","phase","action","attempt",...fieldKeys])&&enumHas(OPERATIONAL_PHASES,value.phase)&&enumHas(OPERATIONAL_ACTIONS,value.action)&&validFields(value)&&(value.runId===void 0||isFlowId(value.runId))&&(value.source===void 0||typeof value.source==="string")&&(value.attempt===void 0||Number.isSafeInteger(value.attempt)&&value.attempt>0&&value.attempt<=1e4)){if(value.source)try{const reference=service.sourceReference?.(value.source);if(isOperationalReference(reference))value.sourceRef=reference}catch{}fields=value;if(!parent&&isFlowId(value.runId))scope.runId=value.runId}}catch{}const started=performance.now();const emit=(state,terminal,extra={})=>{const target=enabled();if(!target||!fields)return;let details;try{details={...extra}}catch{return}if(!closed(details,fieldKeys)||!validFields(details))return;const combined=Object.fromEntries(Object.entries({...fields,...details}).filter(([key,value])=>fieldKeys.includes(key)&&value!==void 0));const elapsed=terminal?performance.now()-started:0;const durationKnown=terminal&&Number.isFinite(elapsed)&&elapsed>=0&&elapsed<=864e5;const durationMs=durationKnown?elapsed:0;const operational={version:1,runId:scope.runId,stepId:scope.stepId,...parent?{parentStepId:parent.stepId}:{},...emissionOrder(),attempt:fields.attempt??1,phase:fields.phase,action:fields.action,state,terminal,durationKnown,...combined};try{const result=executionContext.run(scope,()=>target.record({operation:"product.trace",internal:true,outcome:state==="completed"?"ok":state==="failed"?"fault":state==="cancelled"?"cancelled":"unknown",durationMs,...isTelemetrySourceId(fields.source)?{source:fields.source}:{},operational}));let timer;const bounded=Promise.race([Promise.resolve(result).then(()=>{},()=>{}),new Promise(resolve=>{timer=setTimeout(resolve,50)})]).then(()=>{if(timer)clearTimeout(timer)});pending.add(bounded);void bounded.finally(()=>pending.delete(bounded))}catch{}};const step={get runId(){return scope.runId},stepId:scope.stepId,run:fn=>executionContext.run(scope,fn),mark(value){try{if(finished||!fields||!enabled()||!value)return;const{state,...details}=value;if(["waiting","unknown"].includes(state))emit(state,false,details)}catch{}},finish(value){try{if(finished)return;finished=true;if(!fields||!enabled()||!value)return;const{state,...details}=value;if(["completed","failed","cancelled","unknown"].includes(state))emit(state,true,details)}catch{}},async flush(){await Promise.allSettled([...pending])}};emit("started",false);return step}export function operationalTraceSummary(events,collection={}){const steps=new Map,receipts=new Set;for(const row of events){if(receipts.has(row.id)||!isUsageOperationalTrace(row.operational))continue;receipts.add(row.id);const t=row.operational,key=t.runId+":"+t.stepId,step=steps.get(key)??{start:false,terminal:false};step.start||=t.state==="started";step.terminal||=t.terminal;steps.set(key,step)}const observed=steps.size>0,rows=[...steps.values()];return{coverage:"instrumented_steps_only",observation:collection.enabled===false?"disabled":observed?"observed":"unobserved",historyLimited:collection.limited===true,startedSteps:observed?rows.filter(s=>s.start).length:null,terminalSteps:observed?rows.filter(s=>s.terminal).length:null,unfinishedSteps:observed?rows.filter(s=>s.start&&!s.terminal).length:null,orphanTerminals:observed?rows.filter(s=>!s.start&&s.terminal).length:null}}