@zortexhq/indra-v2.5 0.4.1 → 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 (155) 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/recovery-authorization-url.js +1 -1
  32. package/dist/recovery-progress.js +1 -1
  33. package/dist/recovery.js +1 -1
  34. package/dist/resident-autopilot.js +1 -0
  35. package/dist/resident-ensure-ready.js +1 -1
  36. package/dist/resident-host.js +2 -2
  37. package/dist/resident-jobs.js +1 -1
  38. package/dist/resident-platform.js +2 -2
  39. package/dist/resident-runtime-identity.js +1 -1
  40. package/dist/resident-startup-state.js +1 -0
  41. package/dist/resident-telemetry.js +1 -1
  42. package/dist/shared-action-schemas.js +1 -0
  43. package/dist/source-data.js +1 -1
  44. package/dist/storage-compatibility.js +1 -0
  45. package/dist/supervised-sync.js +1 -1
  46. package/dist/tools.js +1 -1
  47. package/dist/update-check.js +1 -1
  48. package/dist/update-cli.js +1 -1
  49. package/dist/update-command.js +1 -1
  50. package/dist/update-recovery.js +1 -1
  51. package/node_modules/@zortexhq/plugin-auto-connect/dist/api/durable-dispatcher.js +1 -1
  52. package/node_modules/@zortexhq/plugin-auto-connect/dist/api/job-contract.js +1 -1
  53. package/node_modules/@zortexhq/plugin-autopilot/dist/api.js +1 -0
  54. package/node_modules/@zortexhq/plugin-autopilot/dist/cua.js +1 -0
  55. package/node_modules/@zortexhq/plugin-autopilot/dist/feedback.js +1 -0
  56. package/node_modules/@zortexhq/plugin-autopilot/dist/index.js +1 -0
  57. package/node_modules/@zortexhq/plugin-autopilot/dist/python-runtime.js +1 -0
  58. package/node_modules/@zortexhq/plugin-autopilot/dist/service.js +1 -0
  59. package/node_modules/@zortexhq/plugin-autopilot/dist/worker.js +1 -0
  60. package/node_modules/@zortexhq/plugin-autopilot/package.json +23 -0
  61. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/LICENSE +21 -0
  62. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/PROVENANCE.json +38 -0
  63. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/__init__.py +1 -0
  64. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/agent.py +178 -0
  65. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/browser.py +13 -0
  66. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/indra.patch +57 -0
  67. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/model.py +180 -0
  68. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/questions.py +26 -0
  69. package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/transport.py +70 -0
  70. package/node_modules/@zortexhq/plugin-autopilot/python/strategies.py +154 -0
  71. package/node_modules/@zortexhq/plugin-autopilot/python/worker.py +260 -0
  72. package/node_modules/@zortexhq/plugin-connector-calendar/dist/actions.js +1 -1
  73. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/catalog.js +1 -1
  74. package/node_modules/@zortexhq/plugin-connector-core/dist/api/action-outcome.js +1 -0
  75. package/node_modules/@zortexhq/plugin-connector-core/dist/api/content-acquisition.js +1 -1
  76. package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
  77. package/node_modules/@zortexhq/plugin-connector-core/dist/authorization-metrics.js +1 -1
  78. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  79. package/node_modules/@zortexhq/plugin-connector-core/dist/native-principal.js +1 -1
  80. package/node_modules/@zortexhq/plugin-connector-drive/dist/actions.js +1 -1
  81. package/node_modules/@zortexhq/plugin-connector-drive/package.json +2 -1
  82. package/node_modules/@zortexhq/plugin-connector-gmail/dist/actions.js +1 -1
  83. package/node_modules/@zortexhq/plugin-connector-gmail/dist/connector.js +1 -1
  84. package/node_modules/@zortexhq/plugin-connector-gmail/package.json +2 -1
  85. package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/compounds.js +1 -1
  86. package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/provider.js +1 -1
  87. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-helper.js +1 -1
  88. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-server.js +6 -6
  89. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-native-process.mjs +1 -0
  90. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-helper.js +1 -1
  91. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-server.js +2 -2
  92. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-helper.js +1 -1
  93. package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-server.js +2 -2
  94. package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -1
  95. package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
  96. package/node_modules/@zortexhq/plugin-connector-level1/dist/macos-contacts-server.js +1 -0
  97. package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-apple-native.js +1 -0
  98. package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
  99. package/node_modules/@zortexhq/plugin-connector-level1/dist/provisioning.js +1 -1
  100. package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
  101. package/node_modules/@zortexhq/plugin-connector-outlook/dist/actions.js +1 -1
  102. package/node_modules/@zortexhq/plugin-connector-slack/dist/actions.js +1 -1
  103. package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
  104. package/node_modules/@zortexhq/plugin-connector-teams/dist/actions.js +1 -1
  105. package/node_modules/@zortexhq/plugin-connector-teams/dist/provider.js +1 -1
  106. package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/auth-state.js +1 -1
  107. package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/provider.js +1 -1
  108. package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
  109. package/node_modules/@zortexhq/plugin-context-share/dist/api/action-schemas.js +1 -0
  110. package/node_modules/@zortexhq/plugin-context-share/dist/api/index.js +1 -1
  111. package/node_modules/@zortexhq/plugin-context-share/dist/index.js +1 -1
  112. package/node_modules/@zortexhq/plugin-context-share/dist/share.js +1 -1
  113. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-catalog.js +1 -1
  114. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
  115. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/account.js +1 -1
  116. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -1
  117. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -1
  118. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
  119. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -1
  120. package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
  121. package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -1
  122. package/node_modules/@zortexhq/plugin-process-local/dist/api/execution-scope.js +1 -0
  123. package/node_modules/@zortexhq/plugin-process-local/dist/api/stdio-transport.js +1 -0
  124. package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
  125. package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
  126. package/node_modules/@zortexhq/plugin-process-local/dist/windows-job.js +1 -1
  127. package/node_modules/@zortexhq/plugin-product-account/dist/index.js +4 -1
  128. package/node_modules/@zortexhq/plugin-product-account/dist/session-store.js +10 -0
  129. package/node_modules/@zortexhq/plugin-product-account/dist/storage.js +1 -0
  130. package/node_modules/@zortexhq/plugin-product-account/package.json +5 -1
  131. package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
  132. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
  133. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/public-result-visibility.js +1 -0
  134. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/content-acquisition.js +1 -1
  135. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/credentials.js +3 -3
  136. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  137. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/keychain.js +1 -1
  138. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/public-visibility.js +7 -0
  139. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/recovery-guard.js +1 -1
  140. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/runtime.js +1 -0
  141. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +2 -0
  142. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -1
  143. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
  144. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-worker.js +1 -1
  145. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot.js +1 -1
  146. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -1
  147. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +2 -1
  148. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql.js +1 -1
  149. package/package.json +13 -7
  150. package/profiles/core.yml +2 -0
  151. package/release-provenance.json +43 -36
  152. package/update-manifest.json +516 -275
  153. package/dist/content-find.js +0 -2
  154. package/dist/find-snapshots.js +0 -1
  155. package/dist/match-excerpt.js +0 -1
package/README.md CHANGED
@@ -5,7 +5,7 @@ installation. Your Vault holds records, settings and protected authorization.
5
5
 
6
6
  ## Get started
7
7
 
8
- With Node.js 24 or later installed, run:
8
+ With Node.js 24.18.1 or later installed, run:
9
9
 
10
10
  ```sh
11
11
  npm install -g @zortexhq/indra-v2.5@next
@@ -38,7 +38,7 @@ indra update
38
38
 
39
39
  This command chooses the current release, verifies and stages its files, and
40
40
  restarts the same idle background service after applying them. It preserves the
41
- Vault, saved sync policy and startup preference. If work is active or paused,
41
+ Vault and source permissions. If work is active,
42
42
  the update is deferred and the result explains why. Failure keeps or restores
43
43
  the previous installation. Repeat the command to repair an interrupted handover.
44
44
 
@@ -65,9 +65,9 @@ out of Codex preparation, set `ZORTEX_CODEX_SETUP=0`. To choose a new Vault,
65
65
  set `ZORTEX_ROOT` before the first installation. Existing conflicting bindings
66
66
  are never silently replaced.
67
67
 
68
- `indra update check` is a read-only diagnostic. The advanced
69
- `update apply --version <version> --confirmation-token <token>` form remains
70
- available for compatibility. Source workspaces, store-managed installs and old
68
+ `indra update check` is an optional read-only diagnostic and exposes no release
69
+ token. `indra update` checks and installs in one call; no prior check is required.
70
+ Source workspaces, store-managed installs and old
71
71
  versions without the updater use their package manager. The published channel
72
72
  is `next`; release identity is recorded in `release-provenance.json` and the
73
73
  package's `zortexRelease` metadata.
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{stat}from"node:fs/promises";const disabled=/^(0|false|off|no)$/i.test((process.env.ZORTEX_CODEX_SETUP??"").trim());if(!disabled){try{const installer=new URL("../dist/codex-install.js",import.meta.url);try{await stat(installer)}catch(error){if(error.code!=="ENOENT")throw error;const source=await Promise.all(["../src/codex-install.ts","../tsconfig.json"].map(async path=>{try{return(await stat(new URL(path,import.meta.url))).isFile()}catch{return false}}));if(source.every(Boolean)){process.stderr.write("indra: source checkout detected; build indra-v2, then rerun bin/codex-postinstall.mjs to prepare its Codex catalog.\n")}else throw Error("Installed Codex setup is missing. Reinstall the complete indra-v2 package, or set ZORTEX_CODEX_SETUP=0 to skip catalog preparation.")}if(await stat(installer).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error})){const{installCodexCatalog}=await import(installer.href);process.stdout.write(JSON.stringify(await installCodexCatalog())+"\n")}}catch(error){process.stderr.write("indra: Codex catalog preparation failed: "+(error instanceof Error?error.message:"unknown setup error")+"\n");process.exitCode=1}}if(process.platform==="darwin"&&await stat(new URL("../release-provenance.json",import.meta.url)).then(()=>true,()=>false)){try{const{setupCua}=await import("@zortexhq/plugin-connector-level1/api");const computerUse=await setupCua();process.stdout.write(JSON.stringify({computerUse})+"\n");if(computerUse.state==="install-failed")process.stderr.write("indra: "+computerUse.next+"\n")}catch{process.stderr.write("indra: Computer-use setup could not finish. Retry with indra setup computer-use.\n")}}
2
+ import{stat}from"node:fs/promises";if(process.platform==="darwin"&&await stat(new URL("../release-provenance.json",import.meta.url)).then(()=>true,()=>false)){try{const{prepareComputerUse}=await import(new URL("../dist/computer-use-setup.js",import.meta.url).href);const computerUse=await prepareComputerUse();process.stdout.write(JSON.stringify({computerUse})+"\n");if(computerUse.state==="install-failed")process.stderr.write("indra: "+computerUse.next+"\n");if(computerUse.worker?.state==="install-failed")process.stderr.write("indra: "+computerUse.worker.next+"\n")}catch{process.stderr.write("indra: Computer-use setup could not finish. Retry with indra setup computer-use.\n")}}const disabled=/^(0|false|off|no)$/i.test((process.env.ZORTEX_CODEX_SETUP??"").trim());const sourceCheckout=await stat(new URL("../src/onboard.ts",import.meta.url)).then(()=>true,()=>false);if(!disabled||!sourceCheckout){try{const installer=new URL("../dist/codex-install.js",import.meta.url);try{await stat(installer)}catch(error){if(error.code!=="ENOENT")throw error;const source=await Promise.all(["../src/codex-install.ts","../tsconfig.json"].map(async path=>{try{return(await stat(new URL(path,import.meta.url))).isFile()}catch{return false}}));if(source.every(Boolean)){process.stderr.write("indra: source checkout detected; build indra-v2, then rerun bin/codex-postinstall.mjs to prepare its Codex catalog.\n")}else throw Error("Installed Codex setup is missing. Reinstall the complete indra-v2 package, or set ZORTEX_CODEX_SETUP=0 to skip catalog preparation.")}if(await stat(installer).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error})){if(sourceCheckout){const{installCodexCatalog}=await import(installer.href);process.stdout.write(JSON.stringify(await installCodexCatalog())+"\n")}else{const{onboardProduct}=await import(new URL("../dist/onboard.js",import.meta.url).href);const installed=await onboardProduct({open:false,...disabled?{codex:false}:{}});process.stdout.write(JSON.stringify(installed)+"\n");if(installed.state==="needs_attention")process.stderr.write("indra: Onboarding needs attention. The package remains installed; run indra onboard to retry.\n")}}}catch(error){process.stderr.write("indra: Installation could not complete: "+(error instanceof Error?error.message:"unknown setup error")+"\n");process.exitCode=1}}
@@ -0,0 +1 @@
1
+ export function declaredActionEffect(schema){const effect=schema.effect&&typeof schema.effect==="object"&&!Array.isArray(schema.effect)?schema.effect.class:schema.effect;if(effect!==void 0&&effect!=="read"&&effect!=="write")return;const http=typeof schema.httpMethod==="string"?["GET","HEAD","OPTIONS"].includes(schema.httpMethod)?"read":"write":void 0;if(effect!==void 0&&http!==void 0&&effect!==http)return;return effect??http}
@@ -1 +1 @@
1
- import{beginRecoveryProgress,readRecoveryProgress}from"./recovery-progress.js";import{beginPublicActionProgress,tracksPublicRead}from"./public-action-progress.js";function zoteroCurrentCount(result){const ok=result&&typeof result==="object"&&"ok"in result?result.ok:void 0;const out=ok&&typeof ok==="object"&&"result"in ok?ok.result:void 0;if(!out||typeof out!=="object")return;const structured="structured"in out?out.structured:void 0;const wrapped=structured&&typeof structured==="object"&&"result"in structured?structured.result:void 0;const text="text"in out?out.text:void 0;const output=(typeof wrapped==="string"?wrapped:typeof text==="string"?text:"").trim();if(output==="No items found in your Zotero library.")return 0;if(output.length>1e5||!/^# 1 Most Recently Added Items\s*\n/u.test(output))return;if([...output.matchAll(/^\*\*Item Key:\*\* ([A-Z0-9]{8})\s*$/gmu)].length!==1||!/^## 1\. /mu.test(output))return;return 1}export async function trackConnectorFailure(ctx,source,run,signal){const version=()=>{const row=readRecoveryProgress(ctx).find(row2=>row2.source===source);return row?JSON.stringify([row.startedAt,row.endedAt,row.stage,row.connectionState,row.errorCode]):void 0};const before=version();const failed=code=>{if(version()===before)beginRecoveryProgress(ctx,source).finish({connectionState:"unverified",errorCode:signal?.aborted?"aborted":code})};try{const result=await run();if(result&&typeof result==="object"&&"err"in result){const code=result.err?.code;if(typeof code==="string"&&code!=="invalid_argument"&&code!=="not_found")failed(code)}return result}catch(error){failed("unknown");throw error}}export async function trackActionRead(ctx,hub,source,run,signal,classified=false,returnedCount,policy){let progress;let publicProgress;let access;let currentAuthority;const version=()=>{const row=readRecoveryProgress(ctx).find(row2=>row2.source===source);return row?JSON.stringify([row.startedAt,row.endedAt,row.stage,row.connectionState,row.errorCode]):void 0};const before=version();const unclassifiedFailure=code=>{if(access===void 0&&before!==void 0&&version()===before)beginRecoveryProgress(ctx,source).finish({connectionState:"unverified",errorCode:signal?.aborted?"aborted":code})};const onAccess=(value,isCurrent)=>{if(access!==void 0)return;access=value;currentAuthority=isCurrent;if(value!=="public"){progress=beginRecoveryProgress(ctx,source);progress.update("reading","unverified")}else if(tracksPublicRead(source))publicProgress=beginPublicActionProgress(ctx,Date.now,source)};if(!classified)onAccess("legacy");try{const result=await run(onAccess);if(!progress){if(publicProgress)publicProgress.finish(!signal?.aborted&&!!result&&typeof result==="object"&&"ok"in result?"succeeded":"failed");const code=result&&typeof result==="object"&&"err"in result?result.err?.code:void 0;if(typeof code==="string"&&code!=="invalid_argument"&&code!=="not_found")unclassifiedFailure(code);if(policy?.invalidateUnclassifiedSuccess&&result&&typeof result==="object"&&"ok"in result)unclassifiedFailure("unavailable");if(signal?.aborted&&policy?.abortedResult)return policy.abortedResult();return result}if(signal?.aborted){progress.finish({connectionState:"unverified",errorCode:"aborted"});return policy?.abortedResult?.()??result}if(!result||typeof result!=="object"||!("ok"in result)){const code=result&&typeof result==="object"&&"err"in result?result.err?.code:void 0;progress.finish({connectionState:"unverified",errorCode:code??"unknown"});return result}if(result.ok&&typeof result.ok==="object"&&"access"in result.ok&&result.ok.access==="public"){progress.finish({connectionState:"unverified",errorCode:"unavailable"});return result}const status=await hub.status(signal?{signal}:{});const row="ok"in status?status.ok.find(row2=>row2.source===source):void 0;const connected=row?.state==="connected"&&!row.verification&&!row.registration;const ready=connected?row.readiness:void 0;const needsProviderEvidence=source==="ticktick"||source==="zotero";const catalog=!needsProviderEvidence&&connected&&ready?.operation.state!=="succeeded"?await hub.catalog(source,{},{retention:"transient",...signal?{signal}:{}}):void 0;const value=catalog&&"ok"in catalog?catalog.ok:void 0;const total=value&&typeof value==="object"&&"total"in value?value.total:void 0;const actions=ready?.actions??(typeof total==="number"&&Number.isSafeInteger(total)&&total>0?total:void 0);const authorityCurrent=currentAuthority?await currentAuthority():false;const zoteroCount=source==="zotero"?zoteroCurrentCount(result):void 0;if(signal?.aborted||!connected||actions===void 0||!authorityCurrent||needsProviderEvidence&&ready?.operation.state!=="succeeded"||source==="zotero"&&(zoteroCount===void 0||ready?.operation.state!=="succeeded"||!Number.isSafeInteger(ready.operation.returned)||ready.operation.returned<0)){progress.finish({connectionState:"unverified",errorCode:signal?.aborted?"aborted":"unavailable"})}else{const count=source==="zotero"?zoteroCount:returnedCount?.(result);const operation=typeof count==="number"&&Number.isSafeInteger(count)&&count>=0?{state:"succeeded",returned:count}:!returnedCount&&ready?.operation.state==="succeeded"?ready.operation:{state:"succeeded"};progress.finish({connectionState:"connected",readiness:{source,basis:"actions",actions,operation}})}if(signal?.aborted&&policy?.abortedResult)return policy.abortedResult();if(!authorityCurrent&&policy?.staleAuthorityResult)return policy.staleAuthorityResult();return result}catch(error){if(publicProgress)publicProgress.finish("failed");if(progress)progress.finish({connectionState:"unverified",errorCode:signal?.aborted?"aborted":"unknown"});else unclassifiedFailure("unknown");throw error}}export async function trackConnectorRead(ctx,_hub,source,run,signal){const version=()=>{const row=readRecoveryProgress(ctx).find(row2=>row2.source===source);return row?JSON.stringify([row.startedAt,row.endedAt,row.stage,row.connectionState,row.errorCode]):void 0};const before=version();const finish=result=>{if(version()===before)beginRecoveryProgress(ctx,source).finish(result)};try{const result=await trackConnectorFailure(ctx,source,run,signal);const value=result&&typeof result==="object"&&"ok"in result?result.ok:void 0;const returned=value&&typeof value==="object"&&"returned"in value?value.returned:void 0;if(result&&typeof result==="object"&&"err"in result)return result;if(signal?.aborted||typeof returned!=="number"||!Number.isSafeInteger(returned)||returned<0){finish({connectionState:"unverified",errorCode:signal?.aborted?"aborted":"unavailable"});return result}finish({connectionState:"unverified",errorCode:"unavailable"});return result}catch(error){finish({connectionState:"unverified",errorCode:signal?.aborted?"aborted":"unknown"});throw error}}
1
+ import{beginRecoveryProgress,readRecoveryProgress,recoveryAuthorityProof}from"./recovery-progress.js";import{beginPublicActionProgress,tracksPublicRead}from"./public-action-progress.js";function zoteroCurrentCount(result){const ok=result&&typeof result==="object"&&"ok"in result?result.ok:void 0;const out=ok&&typeof ok==="object"&&"result"in ok?ok.result:void 0;if(!out||typeof out!=="object")return;const structured="structured"in out?out.structured:void 0;const wrapped=structured&&typeof structured==="object"&&"result"in structured?structured.result:void 0;const text="text"in out?out.text:void 0;const output=(typeof wrapped==="string"?wrapped:typeof text==="string"?text:"").trim();if(output==="No items found in your Zotero library.")return 0;if(output.length>1e5||!/^# 1 Most Recently Added Items\s*\n/u.test(output))return;if([...output.matchAll(/^\*\*Item Key:\*\* ([A-Z0-9]{8})\s*$/gmu)].length!==1||!/^## 1\. /mu.test(output))return;return 1}export async function trackConnectorFailure(ctx,source,run,signal){const version=()=>{const row=readRecoveryProgress(ctx).find(row2=>row2.source===source);return row?JSON.stringify([row.startedAt,row.endedAt,row.stage,row.connectionState,row.errorCode]):void 0};const before=version();const failed=code=>{if(version()===before)beginRecoveryProgress(ctx,source).finish({connectionState:"unverified",errorCode:signal?.aborted?"aborted":code})};try{const result=await run();if(result&&typeof result==="object"&&"err"in result){const code=result.err?.code;if(typeof code==="string"&&code!=="invalid_argument"&&code!=="not_found")failed(code)}return result}catch(error){failed("unknown");throw error}}export async function trackActionRead(ctx,hub,source,run,signal,classified=false,returnedCount,policy){const authorityProof=await recoveryAuthorityProof(ctx,source,signal);let progress;let publicProgress;let access;let currentAuthority;const version=()=>{const row=readRecoveryProgress(ctx).find(row2=>row2.source===source);return row?JSON.stringify([row.startedAt,row.endedAt,row.stage,row.connectionState,row.errorCode]):void 0};const before=version();const unclassifiedFailure=code=>{if(access===void 0&&before!==void 0&&version()===before)beginRecoveryProgress(ctx,source).finish({connectionState:"unverified",errorCode:signal?.aborted?"aborted":code})};const onAccess=(value,isCurrent)=>{if(access!==void 0)return;access=value;currentAuthority=isCurrent;if(value!=="public"){progress=beginRecoveryProgress(ctx,source);progress.update("reading","unverified")}else if(tracksPublicRead(source))publicProgress=beginPublicActionProgress(ctx,Date.now,source)};if(!classified)onAccess("legacy");try{const result=await run(onAccess);if(!progress){if(publicProgress)publicProgress.finish(!signal?.aborted&&!!result&&typeof result==="object"&&"ok"in result?"succeeded":"failed");const code=result&&typeof result==="object"&&"err"in result?result.err?.code:void 0;if(typeof code==="string"&&code!=="invalid_argument"&&code!=="not_found")unclassifiedFailure(code);if(policy?.invalidateUnclassifiedSuccess&&result&&typeof result==="object"&&"ok"in result)unclassifiedFailure("unavailable");if(signal?.aborted&&policy?.abortedResult)return policy.abortedResult();return result}if(signal?.aborted){progress.finish({connectionState:"unverified",errorCode:"aborted"});return policy?.abortedResult?.()??result}if(!result||typeof result!=="object"||!("ok"in result)){const code=result&&typeof result==="object"&&"err"in result?result.err?.code:void 0;progress.finish({connectionState:"unverified",errorCode:code??"unknown"});return result}if(result.ok&&typeof result.ok==="object"&&"access"in result.ok&&result.ok.access==="public"){progress.finish({connectionState:"unverified",errorCode:"unavailable"});return result}const status=await hub.status(signal?{signal}:{});const row="ok"in status?status.ok.find(row2=>row2.source===source):void 0;const connected=row?.state==="connected"&&!row.verification&&!row.registration;const ready=connected?row.readiness:void 0;const needsProviderEvidence=source==="ticktick"||source==="zotero";const catalog=!needsProviderEvidence&&connected&&ready?.operation.state!=="succeeded"?await hub.catalog(source,{},{retention:"transient",...signal?{signal}:{}}):void 0;const value=catalog&&"ok"in catalog?catalog.ok:void 0;const total=value&&typeof value==="object"&&"total"in value?value.total:void 0;const actions=ready?.actions??(typeof total==="number"&&Number.isSafeInteger(total)&&total>0?total:void 0);const authorityCurrent=currentAuthority?await currentAuthority():false;const zoteroCount=source==="zotero"?zoteroCurrentCount(result):void 0;if(signal?.aborted||!connected||actions===void 0||!authorityCurrent||needsProviderEvidence&&ready?.operation.state!=="succeeded"||source==="zotero"&&(zoteroCount===void 0||ready?.operation.state!=="succeeded"||!Number.isSafeInteger(ready.operation.returned)||ready.operation.returned<0)){progress.finish({connectionState:"unverified",errorCode:signal?.aborted?"aborted":"unavailable"})}else{const count=source==="zotero"?zoteroCount:returnedCount?.(result);const operation=typeof count==="number"&&Number.isSafeInteger(count)&&count>=0?{state:"succeeded",returned:count}:!returnedCount&&ready?.operation.state==="succeeded"?ready.operation:{state:"succeeded"};progress.finish({connectionState:"connected",readiness:{source,basis:"actions",actions,operation},...authorityProof?{authorityProof}:{}})}if(signal?.aborted&&policy?.abortedResult)return policy.abortedResult();if(!authorityCurrent&&policy?.staleAuthorityResult)return policy.staleAuthorityResult();return result}catch(error){if(publicProgress)publicProgress.finish("failed");if(progress)progress.finish({connectionState:"unverified",errorCode:signal?.aborted?"aborted":"unknown"});else unclassifiedFailure("unknown");throw error}}export async function trackConnectorRead(ctx,_hub,source,run,signal){const version=()=>{const row=readRecoveryProgress(ctx).find(row2=>row2.source===source);return row?JSON.stringify([row.startedAt,row.endedAt,row.stage,row.connectionState,row.errorCode]):void 0};const before=version();const finish=result=>{if(version()===before)beginRecoveryProgress(ctx,source).finish(result)};try{const result=await trackConnectorFailure(ctx,source,run,signal);const value=result&&typeof result==="object"&&"ok"in result?result.ok:void 0;const returned=value&&typeof value==="object"&&"returned"in value?value.returned:void 0;if(result&&typeof result==="object"&&"err"in result)return result;if(signal?.aborted||typeof returned!=="number"||!Number.isSafeInteger(returned)||returned<0){finish({connectionState:"unverified",errorCode:signal?.aborted?"aborted":"unavailable"});return result}finish({connectionState:"unverified",errorCode:"unavailable"});return result}catch(error){finish({connectionState:"unverified",errorCode:signal?.aborted?"aborted":"unknown"});throw error}}
@@ -0,0 +1 @@
1
+ import{createHash}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const invalid=message=>businessError("invalid_argument",message,"plugin");const digest=value=>createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0,24);const terms=value=>value.toLowerCase().match(/[\p{L}\p{N}]+/gu)??[];const escapePointer=value=>value.replace(/~/g,"~0").replace(/\//g,"~1");function schemaTarget(schema){if(object(schema.inputSchema))return{schemaPointer:"/inputSchema",callInputPointer:"/params"};if(object(schema.params))return{schemaPointer:"/params",callInputProjection:{kind:"pick",fields:{params:"/params",body:"/body",media:"/media"},absent:"omit"}};return void 0}function parameter(schema,path){const root=object(schema.inputSchema)?schema.inputSchema:object(schema.params)?schema.params:void 0;if(!root)return businessError("not_found","This action does not publish a parameter schema.","plugin");const names=path.startsWith("/")?path.slice(1).split("/").map(s=>s.replace(/~1/g,"/").replace(/~0/g,"~")):path.split(".");const roots=Array.isArray(root.oneOf)?root.oneOf.flatMap((value,index)=>object(value)?[{value,pointer:`/oneOf/${index}`}]:[]):[{value:root,pointer:""}],found=[];for(const branch of roots){let current=branch.value,parent=current,valid=true,schemaPointer=branch.pointer,pattern=false;const callPath=object(schema.inputSchema)?["params"]:[];for(const name of names){if(object(current.items)){current=current.items;schemaPointer+="/items";if(/^(0|[1-9][0-9]*)$/.test(name)){callPath.push(name);continue}callPath.push("*");pattern=true}parent=current;const properties=object(current.properties)?current.properties:void 0,next=properties?.[name];if(!object(next)){valid=false;break}current=next;schemaPointer+="/properties/"+escapePointer(name);callPath.push(name)}if(valid&&(!object(schema.params)||object(schema.inputSchema)||["params","body","media"].includes(callPath[0]??""))){const pointer="/"+callPath.map(escapePointer).join("/");found.push({schema:current,required:Array.isArray(parent.required)&&parent.required.includes(names.at(-1)),schemaPointer,...pattern?{callInputPattern:pointer}:{callInputPointer:pointer}})}}if(!found.length)return businessError("not_found","The requested parameter is not declared in this schema. Use the exact schema for conditional or referenced properties.","plugin");return ok({name:schema.name,...schema.source?{source:schema.source}:{},schemaTarget:schemaTarget(schema),parameter:{path,...found.length===1?found[0]:{alternatives:found},context:root}})}export function createActionCatalog(hub,shared){return async(args,signal)=>{if(Object.keys(args).some(key=>!["operation","scope","source","query","name","parameter","format","limit","cursor"].includes(key)))return invalid("Unknown action catalog field.");const operation=args.operation??"list",scope=args.scope??"available",format=args.format??"descriptions",limit=args.limit??50;if(!["find","list","lookup"].includes(String(operation))||!["available","all"].includes(String(scope))||!["count","names","descriptions"].includes(String(format))||!Number.isSafeInteger(limit)||Number(limit)<1||Number(limit)>100||args.source!==void 0&&(typeof args.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(args.source))||args.query!==void 0&&(typeof args.query!=="string"||args.query.length>4096)||args.name!==void 0&&(typeof args.name!=="string"||!args.name||args.name.length>512)||args.parameter!==void 0&&(typeof args.parameter!=="string"||!args.parameter||args.parameter.length>512)||args.cursor!==void 0&&(typeof args.cursor!=="string"||args.cursor.length>512))return invalid("Use a bounded catalog operation, scope, source, query, name, parameter and page.");if(signal?.aborted)return businessError("aborted","Action discovery was cancelled.","plugin");let inventory=hub?.describeActions?.()??[];if(operation==="lookup"){if(typeof args.name!=="string")return invalid("lookup requires an exact action name.");const common=shared.find(row=>row.name===args.name);let schema;if(common&&!args.source)schema=ok(common);else{const candidates=inventory.filter(row=>row.source===args.source||args.source===void 0&&row.catalog?.actions.some(action=>action.name===args.name));const source=typeof args.source==="string"?args.source:candidates.length===1?candidates[0].source:void 0;if(!source)return invalid("Specify source for a provider action whose exact catalog is not known or is ambiguous.");if(!hub)return businessError("unavailable","Connector hub is inactive.","plugin");schema=await hub.method(source,args.name,{...signal?{signal}:{},retention:"transient"});if("ok"in schema&&object(schema.ok))schema=ok({...schema.ok,source})}if(!("ok"in schema)||!object(schema.ok))return schema;return typeof args.parameter==="string"?parameter(schema.ok,args.parameter):ok({...schema.ok,...schemaTarget(schema.ok)?{schemaTarget:schemaTarget(schema.ok)}:{}})}if(args.name!==void 0||args.parameter!==void 0)return invalid("Exact name and parameter belong to lookup.");if(operation==="find"&&(typeof args.query!=="string"||!args.query.trim()))return invalid("find requires search text.");if(!hub&&args.source)return businessError("unavailable","Connector hub is inactive.","plugin");if(hub&&typeof args.source==="string"&&inventory.some(row=>row.source===args.source&&row.registration==="active"&&!row.catalog)){const loaded=await hub.catalog(args.source,{limit:100},{...signal?{signal}:{},retention:"transient"});if(!("ok"in loaded))return loaded;inventory=hub.describeActions?.()??inventory;const data=object(loaded.ok)?loaded.ok:void 0,rows2=data&&(Array.isArray(data.actions)?data.actions:Array.isArray(data.methods)?data.methods:void 0);if(rows2&&rows2.every(object))inventory=inventory.map(row=>row.source===args.source&&!row.catalog?{...row,catalog:{revision:digest(rows2),complete:data?.total===rows2.length,actions:rows2}}:row)}const states=hub?await hub.status(signal?{signal}:{}):ok([]);if(!("ok"in states))return states;if(inventory.some(row=>hub?.registrationRevision?.(row.source)!==void 0&&hub.registrationRevision(row.source)!==row.revision))return businessError("aborted","Source registration changed during discovery; retry.","plugin");const stateBySource=new Map(states.ok.map(row=>[row.source,row.state]));const selected=inventory.filter(row=>args.source===void 0||row.source===args.source);if(args.source!==void 0&&!selected.length)return businessError("not_found","Source is not installed or enabled.","plugin");const sources=selected.map(row=>({source:row.source,state:stateBySource.get(row.source)??"unavailable",knownActions:row.catalog?.actions.length??0,complete:row.catalog?.complete===true,revision:row.revision,catalogRevision:row.catalog?.revision??null}));const eligible=new Set(sources.filter(row=>scope==="all"||row.state==="connected").map(row=>row.source));const rows=args.source===void 0?shared.map(row=>({name:row.name,description:row.description,effect:row.effect,source:"indra",availability:"installed"})):[];for(const row of selected){if(!eligible.has(row.source))continue;for(const action of row.catalog?.actions??[]){if(typeof action.name!=="string")continue;rows.push({name:action.name,source:row.source,description:typeof action.description==="string"?action.description:"",effect:action.effect??null,availability:stateBySource.get(row.source)??"unavailable"});if(rows.length>25e3)return businessError("resource_exhausted","Narrow this catalog request to one source.","plugin")}}const needles=terms(String(args.query??""));const score=row=>needles.reduce((n,term)=>n+(row.name.toLowerCase().includes(term)?4:0)+(row.description.toLowerCase().includes(term)?1:0)+(row.source.includes(term)?2:0),0);const matched=needles.length?rows.filter(row=>needles.every(term=>(row.name+" "+row.description+" "+row.source).toLowerCase().includes(term))):rows;matched.sort((a,b)=>operation==="find"?score(b)-score(a)||a.source.localeCompare(b.source)||a.name.localeCompare(b.name):a.source.localeCompare(b.source)||a.name.localeCompare(b.name));const revision=digest({scope,source:args.source,query:args.query,format,sources,actions:matched.map(row=>[row.source,row.name])});let offset=0;if(args.cursor){try{const cursor=JSON.parse(Buffer.from(String(args.cursor),"base64url").toString());if(cursor.revision!==revision)return businessError("aborted","Action inventory changed; start a new page sequence.","plugin");if(!Number.isSafeInteger(cursor.offset)||cursor.offset<0||cursor.offset>matched.length)throw Error();offset=cursor.offset}catch{return invalid("Invalid action catalog cursor.")}}const page=matched.slice(offset,offset+Number(limit)),complete=sources.filter(row=>eligible.has(row.source)).every(row=>row.complete),next=offset+page.length;return ok({operation,scope,format,revision,count:{known:matched.length,total:complete?matched.length:null,complete},sources,actions:format==="count"?[]:format==="names"?page.map(row=>row.name):page,...format!=="count"&&next<matched.length?{nextCursor:Buffer.from(JSON.stringify({revision,offset:next})).toString("base64url")}:{},...operation==="find"?{ranking:"local-lexical"}:{},availability:"Source availability is observed metadata. Exact schema and authority are validated again at execution; unknown dynamic catalogs are incomplete."})}}
package/dist/auto-sync.js CHANGED
@@ -1 +1 @@
1
- import{acquireConnectorContent}from"@zortexhq/plugin-connector-core/api";import{randomUUID}from"node:crypto";import{Original}from"@zortexhq/plugin-connector-framework/api";import{browserReady,runSupervisedSource,sourceActive,WORKER_SYNC_SOURCES}from"./supervised-sync.js";import{createSourceData}from"./source-data.js";const INTERVAL_MS=15*6e4,BUSY_MS=6e4,AUTH_MS=30*6e4,ERROR_FIRST_MS=6e4,ERROR_MAX_MS=30*6e4;const DUE=/backoff not due until (\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z)/;export function createAutoSync(deps){const now=deps.now??Date.now,parallel=Math.max(1,deps.parallel??2),interval=deps.intervalMs??INTERVAL_MS;const rows=new Map(deps.sources.map(source=>[source,{source,state:"waiting",appended:0}]));const next=new Map,failures=new Map,running=new Map;let closed=false,paused=false,ticking;function settle(source,result){const row=rows.get(source),at=now();row.lastFinishedAt=new Date(at).toISOString();row.state=closed?"stopped":"waiting";const ok="ok"in result?result.ok:void 0;if(ok){failures.delete(source);delete row.errorCode;const appended=typeof ok.appended==="number"&&Number.isSafeInteger(ok.appended)&&ok.appended>0?ok.appended:0;if(row.complete!==false)row.appended=0;row.appended+=appended;row.complete=ok.complete===true;next.set(source,row.complete||deps.refreshOnly?.(source)?at+interval:at)}else{const err="err"in result?result.err:void 0,code=err?.code??"unknown";row.errorCode=code;const due2=DUE.exec(err?.message??"")?.[1];if(due2&&Number.isFinite(Date.parse(due2)))next.set(source,Math.max(at,Date.parse(due2)));else if(code==="deadline_exceeded")next.set(source,at);else if(code==="resource_exhausted")next.set(source,at+BUSY_MS);else if(code==="unauthenticated"||code==="permission_denied"||code==="failed_precondition")next.set(source,at+AUTH_MS);else if(code==="aborted")next.set(source,at);else{const count=(failures.get(source)??0)+1;failures.set(source,count);next.set(source,at+Math.min(ERROR_MAX_MS,ERROR_FIRST_MS*2**(count-1)))}}const due=next.get(source);if(due!==void 0&&!closed)row.nextAt=new Date(due).toISOString()}function start(source){const row=rows.get(source),stop=new AbortController;row.state="running";delete row.nextAt;const task=(async()=>{let result;try{result=await deps.run(source,stop.signal)}catch{result=Original.errResult({code:"unavailable",layer:"connector",retryability:"transient",message:"Sync run did not finish."})}settle(source,result)})().finally(()=>running.delete(source));running.set(source,{stop,task})}async function tick(){if(closed||paused)return;for(const source of await deps.discoverSources?.()??[])if(!rows.has(source))rows.set(source,{source,state:"waiting",appended:0});for(const source of rows.keys()){if(closed||paused||running.size>=parallel)return;if(running.has(source))continue;const due=next.get(source);if(due!==void 0&&due>now())continue;const row=rows.get(source);let connected=false;try{connected=await deps.connected(source)}catch{connected=false}if(closed||paused||running.size>=parallel)return;if(!connected){row.state="not-connected";delete row.nextAt;next.delete(source);continue}if(!next.has(source)&&deps.deferUntil){const saved=Date.parse(await deps.deferUntil(source)??"");if(Number.isFinite(saved)&&saved>now()){next.set(source,saved);row.nextAt=new Date(saved).toISOString();continue}}start(source)}}return{tick(){const current=(ticking??Promise.resolve()).then(tick);ticking=current.catch(()=>{});return current},async idle(){while(running.size)await Promise.allSettled([...running.values()].map(entry=>entry.task))},status(){return[...rows.values()].map(row=>({...row}))},enqueue(source){if(!closed&&rows.has(source))next.set(source,0)},async pause(){paused=true;for(const entry of running.values())entry.stop.abort();await Promise.allSettled([...running.values()].map(entry=>entry.task))},resume(){if(!closed)paused=false},async close(){closed=true;paused=true;for(const entry of running.values())entry.stop.abort();await Promise.allSettled([...running.values()].map(entry=>entry.task));for(const row of rows.values()){row.state="stopped";delete row.nextAt}}}}export function provideAutoSync(ctx,root,options={}){let sync;let residentRows=[];ctx.provide("indraSourceSync",{status:()=>sync?.status()??residentRows.map(row=>({...row}))});ctx.effect(()=>{if(!options.residentStatus){const running=startAutoSync(ctx,root,options);sync=running;return()=>{if(sync===running)sync=void 0;return running.close()}}let closed=false,timer;const poll=async()=>{try{residentRows=(await options.residentStatus()).map(row=>({...row}))}catch{residentRows=[]}if(!closed){timer=setTimeout(()=>void poll(),options.tickMs??2e3);timer.unref?.()}};void poll();return()=>{closed=true;if(timer)clearTimeout(timer);residentRows=[]}})}export function startAutoSync(ctx,root,options={}){const enabled=options.enabled??!/^(0|false|off|no)$/i.test((process.env.ZORTEX_AUTO_SYNC??"").trim());const sourceData=createSourceData(ctx);const bindings=async source=>{const found=await ctx.get("zortexVaultStore")?.bindingCustody?.bindings(source);return found&&"ok"in found?found.ok.filter(row=>row.state==="connected"):[]};const sync=createAutoSync({sources:enabled?[...WORKER_SYNC_SOURCES.filter(source=>source!=="imessage"),"computer-files"]:[],async discoverSources(){const connections=await ctx.get("zortexVaultStore")?.connections();if(!enabled||!connections||!("ok"in connections))return[];return connections.ok.filter(row=>row.state==="connected"&&!WORKER_SYNC_SOURCES.includes(row.source)&&row.source!=="computer-files"&&ctx.get("zortexConnectorHub")?.describe?.(row.source)?.content?.some(cap=>cap.resource==="connector.read"&&cap.automatic!==false&&cap.read==="implemented"&&cap.persistence==="durable")).map(row=>row.source)},refreshOnly:source=>source==="computer-files"||!WORKER_SYNC_SOURCES.includes(source),async deferUntil(source){const selected=await bindings(source);const states=await Promise.all(selected.length?selected.map(row=>sourceData.read(source,row.id)):[sourceData.read(source)]);if(states.some(row=>!row?.nextAt))return;return states.map(row=>row.nextAt).sort()[0]},async connected(source){if(source==="computer-files"){const state=await ctx.get("zortexComputerFiles")?.status();return!!state&&"ok"in state&&state.ok.enabled&&state.ok.state!=="paused"}if(!WORKER_SYNC_SOURCES.includes(source)){const info=ctx.get("zortexConnectorHub")?.describe?.(source);if(!info?.content?.some(cap=>cap.resource==="connector.read"&&cap.automatic!==false&&cap.persistence==="durable"))return false;const selected2=await ctx.get("zortexVaultStore")?.connection(source);return!!selected2&&"ok"in selected2&&selected2.ok?.state==="connected"}if(!sourceActive(ctx,source))return false;if(source==="google-chrome"||source==="microsoft-edge")return browserReady(source);if((await bindings(source)).length)return true;const selected=await ctx.get("zortexVaultStore")?.connection(source);return!!selected&&Original.isOk(selected)&&selected.ok?.state==="connected"},async run(source,signal){if(source==="computer-files"){const result=await ctx.get("zortexComputerFiles")?.scan({signal});if(result&&"ok"in result)return{ok:{complete:!result.ok.partial,appended:0}};return result&&"err"in result?result:{err:{code:"unavailable"}}}if(!WORKER_SYNC_SOURCES.includes(source)){const hub=ctx.get("zortexConnectorHub"),vault=ctx.get("zortexSqliteVault");if(!hub||!vault)return{err:{code:"unavailable"}};return sourceData.run(source,signal,async()=>{const result=await acquireConnectorContent({hub,vault},source,{limit:100},{signal});return"ok"in result?{ok:{complete:false,appended:result.ok.receipt.persisted,warnings:result.ok.warnings}}:result})}const selected=await bindings(source);let complete=true,appended=0;for(const bindingId of selected.length?selected.map(row=>row.id):[void 0]){if(signal.aborted)return{err:{code:"aborted"}};const settings=bindingId?{bindingId}:void 0;const result=await(options.run?.(source,signal,settings)??runSupervisedSource(ctx,root,source,randomUUID(),{signal,...settings}));const value="ok"in result?result.ok:void 0;if(!value)return result;complete&&=value.complete===true;appended+=typeof value.appended==="number"?value.appended:0}return{ok:{complete,appended}}}});let timer,closed=false,wake=()=>{};const done=(async()=>{if(!enabled)return;const stopped=new Promise(resolve=>{wake=resolve});await Promise.race([ctx.get("loader")?.await(),stopped]);while(!closed){await sync.tick().catch(()=>{});if(closed)break;await new Promise(resolve=>{wake=resolve;timer=setTimeout(resolve,options.tickMs??1e4);timer.unref?.()})}})();return{...sync,done,enqueue(source){sync.enqueue(source);wake()},pause:()=>sync.pause(),resume(){sync.resume();wake()},async close(){closed=true;if(timer)clearTimeout(timer);wake();await sync.close();await done}}}
1
+ import{acquireConnectorContent}from"@zortexhq/plugin-connector-core/api";import{randomUUID}from"node:crypto";import{Original}from"@zortexhq/plugin-connector-framework/api";import{browserReady,runSupervisedSource,sourceActive,imessageSyncAllowed,WORKER_SYNC_SOURCES}from"./supervised-sync.js";import{createSourceData,sourceRetry}from"./source-data.js";const INTERVAL_MS=15*6e4;export function createAutoSync(deps){const now=deps.now??Date.now,parallel=Math.max(1,deps.parallel??2),interval=deps.intervalMs??INTERVAL_MS;const key=target=>JSON.stringify([target.source,target.bindingId??null,target.authorityRevision??null]);const targets=new Map(deps.sources.map(source=>[key({source}),{source}]));const rows=new Map([...targets].map(([id,target])=>[id,{source:target.source,state:"waiting",appended:0}]));const next=new Map,failures=new Map,running=new Map;let closed=false,paused=false,ticking,nextSource=0;function settle(source,result){const row=rows.get(source),at=now();if(!row)return;row.lastFinishedAt=new Date(at).toISOString();row.state=closed?"stopped":"waiting";const ok="ok"in result?result.ok:void 0;if(ok){failures.delete(source);delete row.errorCode;const appended=typeof ok.appended==="number"&&Number.isSafeInteger(ok.appended)&&ok.appended>0?ok.appended:0;if(row.complete!==false)row.appended=0;row.appended+=appended;row.complete=ok.complete===true;next.set(source,row.complete||deps.refreshOnly?.(row.source)?at+interval:at)}else{const err="err"in result?result.err:void 0,code=err?.code??"unknown";row.errorCode=code;row.complete=false;const retry=sourceRetry(err??{code},at,failures.get(source)??0);failures.set(source,retry.failures);next.set(source,retry.nextAt)}const due=next.get(source);if(due!==void 0&&!closed)row.nextAt=new Date(due).toISOString()}function start(source){const row=rows.get(source),target=targets.get(source),stop=new AbortController;row.state="running";delete row.nextAt;const task=(async()=>{let result;try{result=await deps.run(target.source,stop.signal,target.bindingId)}catch{result=Original.errResult({code:"unavailable",layer:"connector",retryability:"transient",message:"Sync run did not finish."})}if(rows.get(source)!==row||targets.get(source)!==target)return;settle(source,result);if(!("ok"in result&&result.ok)&&deps.deferUntil&&!closed){let deferred;try{deferred=await deps.deferUntil(target.source,target.bindingId)}catch{return}if(closed||rows.get(source)!==row||targets.get(source)!==target)return;const saved=Date.parse(deferred??"");if(Number.isFinite(saved)){const due=Math.max(saved,next.get(source)??now());next.set(source,due);row.nextAt=new Date(due).toISOString()}}})().finally(()=>{running.delete(source);if(!closed&&!paused)deps.onSettled?.()});running.set(source,{stop,task})}async function tick(){if(closed||paused)return;if(deps.discoverTargets){const discovered=new Map((await deps.discoverTargets()).map(target=>[key(target),target]));for(const id of targets.keys())if(!discovered.has(id)){running.get(id)?.stop.abort();targets.delete(id);rows.delete(id);next.delete(id);failures.delete(id)}for(const[id,target]of discovered)if(!targets.has(id)){targets.set(id,{...target});rows.set(id,{source:target.source,state:"waiting",appended:0})}}for(const source of await deps.discoverSources?.()??[]){const id=key({source});if(!rows.has(id)){targets.set(id,{source});rows.set(id,{source,state:"waiting",appended:0})}}const sources=[...rows.keys()];for(let checked=0;checked<sources.length;checked++){if(closed||paused||running.size>=parallel)return;const source=sources[nextSource%sources.length];nextSource=(nextSource+1)%sources.length;if(running.has(source))continue;const due=next.get(source);if(due!==void 0&&due>now())continue;const row=rows.get(source),target=targets.get(source);let connected=false;try{connected=await deps.connected(target.source,target.bindingId)}catch{connected=false}if(closed||paused||running.size>=parallel)return;if(!connected){row.state="not-connected";delete row.nextAt;next.delete(source);continue}if(!next.has(source)&&deps.deferUntil){const saved=Date.parse(await deps.deferUntil(target.source,target.bindingId)??"");if(closed||paused||rows.get(source)!==row||targets.get(source)!==target)return;if(Number.isFinite(saved)&&saved>now()){next.set(source,saved);row.nextAt=new Date(saved).toISOString();continue}}start(source)}}return{tick(){const current=(ticking??Promise.resolve()).then(tick);ticking=current.catch(()=>{});return current},async idle(){while(running.size)await Promise.allSettled([...running.values()].map(entry=>entry.task))},status(){const grouped=new Map;for(const row of rows.values())grouped.set(row.source,[...grouped.get(row.source)??[],row]);return[...grouped].map(([source,parts])=>{if(parts.length===1)return{...parts[0]};const state=parts.some(row=>row.state==="running")?"running":parts.every(row=>row.state==="stopped")?"stopped":parts.some(row=>row.state==="waiting")?"waiting":"not-connected";const due=parts.flatMap(row=>row.nextAt?[row.nextAt]:[]).sort()[0],finished=parts.flatMap(row=>row.lastFinishedAt?[row.lastFinishedAt]:[]).sort().at(-1),error=parts.find(row=>row.errorCode)?.errorCode;return{source,state,appended:parts.reduce((total,row)=>total+row.appended,0),complete:parts.every(row=>row.complete===true),...state!=="running"&&due?{nextAt:due}:{},...finished?{lastFinishedAt:finished}:{},...error?{errorCode:error}:{}}})},enqueue(source){if(!closed){for(const[id,target]of targets)if(target.source===source)next.set(id,0)}},async pause(){paused=true;for(const entry of running.values())entry.stop.abort();await Promise.allSettled([...running.values()].map(entry=>entry.task))},resume(){if(!closed)paused=false},async close(){closed=true;paused=true;for(const entry of running.values())entry.stop.abort();await Promise.allSettled([...running.values()].map(entry=>entry.task));for(const row of rows.values()){row.state="stopped";delete row.nextAt}}}}export function provideAutoSync(ctx,root,options={}){let sync;let residentRows=[];ctx.provide("indraSourceSync",{status:()=>sync?.status()??residentRows.map(row=>({...row}))});ctx.effect(()=>{if(!options.residentStatus){const running=startAutoSync(ctx,root,options);sync=running;return()=>{if(sync===running)sync=void 0;return running.close()}}let closed=false,timer;const poll=async()=>{try{residentRows=(await options.residentStatus()).map(row=>({...row}))}catch{residentRows=[]}if(!closed){timer=setTimeout(()=>void poll(),options.tickMs??2e3);timer.unref?.()}};void poll();return()=>{closed=true;if(timer)clearTimeout(timer);residentRows=[]}})}export function startAutoSync(ctx,root,options={}){const enabled=options.enabled??true;const sourceData=createSourceData(ctx,options.now);const bindings=async source=>{const custody=ctx.get("zortexVaultStore")?.bindingCustody,found=await custody?.bindings(source);if(!custody||!found||!("ok"in found))return[];const eligible=[];for(const binding of found.ok){if(binding.state!=="connected")continue;const state=await custody.authoritySnapshot({kind:"binding",bindingId:binding.id});if(!("ok"in state)||!state.ok.inventory)continue;const{binding:current,grants}=state.ok.inventory,audience=current.authority?.resource??current.provider;const grantsForUse=grants.filter(grant=>grant.purpose==="L1"&&grant.audience===audience);if(current.identity.source===source&&current.state==="connected"&&grantsForUse.length===1&&grantsForUse[0].state==="active"){const grant=grantsForUse[0];eligible.push({source,bindingId:current.id,authorityRevision:JSON.stringify([current.revision,grant.id,grant.revision,grant.scopeEpoch])})}}return eligible};let timer,closed=false,wake=()=>{},pendingWake=false;const requestTick=()=>{if(closed)return;pendingWake=true;if(timer){clearTimeout(timer);timer=void 0}wake()};const sync=createAutoSync({onSettled:requestTick,sources:enabled?[...WORKER_SYNC_SOURCES,"computer-files"]:[],...options.now?{now:options.now}:{},async discoverTargets(){if(!enabled)return[];const targets=[];for(const source of WORKER_SYNC_SOURCES){const selected=sourceActive(ctx,source)&&!["imessage","google-chrome","microsoft-edge"].includes(source)?await bindings(source):[];targets.push(...selected.length?selected:[{source}])}targets.push({source:"computer-files"});const connections=await ctx.get("zortexVaultStore")?.connections();if(!connections||!("ok"in connections))return targets;targets.push(...connections.ok.filter(row=>row.state==="connected"&&!WORKER_SYNC_SOURCES.includes(row.source)&&row.source!=="computer-files"&&ctx.get("zortexConnectorHub")?.describe?.(row.source)?.content?.some(cap=>cap.resource==="connector.read"&&cap.automatic!==false&&cap.read==="implemented"&&cap.persistence==="durable")).map(row=>({source:row.source})));return targets},refreshOnly:source=>source==="computer-files"||!WORKER_SYNC_SOURCES.includes(source),async deferUntil(source,bindingId){return(await sourceData.read(source,bindingId))?.nextAt},async connected(source,bindingId){if(source==="computer-files"){const state=await ctx.get("zortexComputerFiles")?.status();return!!state&&"ok"in state&&state.ok.enabled&&state.ok.state!=="disconnected"}if(!WORKER_SYNC_SOURCES.includes(source)){const info=ctx.get("zortexConnectorHub")?.describe?.(source);if(!info?.content?.some(cap=>cap.resource==="connector.read"&&cap.automatic!==false&&cap.persistence==="durable"))return false;const selected2=await ctx.get("zortexVaultStore")?.connection(source);return!!selected2&&"ok"in selected2&&selected2.ok?.state==="connected"}if(!sourceActive(ctx,source))return false;if(source==="imessage")return imessageSyncAllowed(ctx);if(source==="google-chrome"||source==="microsoft-edge")return browserReady(source);if(bindingId)return(await bindings(source)).some(target=>target.bindingId===bindingId);const selected=await ctx.get("zortexVaultStore")?.connection(source);return!!selected&&Original.isOk(selected)&&selected.ok?.state==="connected"},async run(source,signal,bindingId){if(source==="computer-files"){const result=await ctx.get("zortexComputerFiles")?.scan({signal});if(result&&"ok"in result)return{ok:{complete:!result.ok.partial,appended:0}};return result&&"err"in result?result:{err:{code:"unavailable"}}}if(!WORKER_SYNC_SOURCES.includes(source)){const hub=ctx.get("zortexConnectorHub"),vault=ctx.get("zortexSqliteVault");if(!hub||!vault)return{err:{code:"unavailable"}};return sourceData.run(source,signal,async()=>{const result=await acquireConnectorContent({hub,vault},source,{limit:100},{signal});return"ok"in result?{ok:{complete:false,appended:result.ok.receipt.persisted,warnings:result.ok.warnings}}:result})}if(signal.aborted)return{err:{code:"aborted"}};const settings=bindingId?{bindingId}:void 0;return options.run?.(source,signal,settings)??sourceData.run(source,signal,()=>runSupervisedSource(ctx,root,source,randomUUID(),{signal,...settings}),bindingId)}});const done=(async()=>{if(!enabled)return;const stopped=new Promise(resolve=>{wake=resolve});await Promise.race([ctx.get("loader")?.await(),stopped]);while(!closed){pendingWake=false;await sync.tick().catch(()=>{});if(closed)break;if(pendingWake)continue;await new Promise(resolve=>{wake=resolve;timer=setTimeout(resolve,options.tickMs??1e4);timer.unref?.()})}})();return{...sync,done,enqueue(source){sync.enqueue(source);requestTick()},pause:()=>sync.pause(),resume(){sync.resume();requestTick()},async close(){closed=true;if(timer)clearTimeout(timer);wake();await sync.close();await done}}}
@@ -1 +1 @@
1
- import{createHash,randomUUID}from"node:crypto";import{readFile,writeFile,mkdir,lstat,realpath,rename,copyFile,cp,rm,chmod}from"node:fs/promises";import{resolve,join,dirname,relative,isAbsolute,sep}from"node:path";import{homedir}from"node:os";import{fileURLToPath}from"node:url";import{execFile}from"node:child_process";import{promisify}from"node:util";import{prepareDependencyUpdate}from"./update-dependencies.js";import{createUpdateTelemetry}from"./update-telemetry.js";import{createUpdateRecovery,safePath,safeFile,optionalBytes,dependencyPath,atomicWrite,JOURNAL,RECOVERY_FILE}from"./update-recovery.js";const execute=promisify(execFile);const NAME="@zortexhq/indra-v2.5";const MANIFEST="update-manifest.json";const MAX_BYTES=12e7;const hash=bytes=>createHash("sha256").update(bytes).digest("hex");const jsonBytes=value=>Buffer.from(JSON.stringify(value,null,2)+"\n");function metadataDigest(pkg){const update=pkg.zortexUpdate;if(update?.schemaVersion!==1||update.manifest!==MANIFEST||!/^[a-f0-9]{64}$/.test(update.sha256??""))return void 0;return update.sha256}function validateManifest(bytes,digest,version){if(hash(bytes)!==digest)throw Error("Update manifest integrity check failed.");const value=JSON.parse(bytes.toString("utf8"));if(value.schemaVersion!==1||value.package?.name!==NAME||value.package.version!==version||value.package.zortexUpdate||!Array.isArray(value.files)||value.files.length>8e3)throw Error("Invalid update manifest.");let total=0;const paths=new Set;for(const file of value.files){safePath(file.path);const key=file.path.toLowerCase();if(paths.has(key)||[MANIFEST,"package.json","release-provenance.json"].includes(key)||!/^[a-f0-9]{64}$/.test(file.sha256)||!Number.isSafeInteger(file.size)||file.size<0||file.mode!==void 0&&![420,493,420,493].includes(file.mode))throw Error("Invalid update file entry.");paths.add(key);total+=file.size}if(total>MAX_BYTES)throw Error("Update exceeds the installed product size limit.");return value}function dependencyShape(pkg){const bundled=new Set(pkg.bundledDependencies??[]);return JSON.stringify(["dependencies","optionalDependencies","peerDependencies","peerDependenciesMeta"].map(field=>[field,Object.entries(pkg[field]??{}).filter(([name])=>!bundled.has(name)).sort(([a],[b])=>a.localeCompare(b))]))}function binShape(pkg){const bins=typeof pkg.bin==="string"?{[pkg.name.split("/").at(-1)]:pkg.bin}:pkg.bin??{};return JSON.stringify(Object.entries(bins).map(([name,path])=>[name,typeof path==="string"?path.replace(/^\.\//,""):path]).sort(([a],[b])=>String(a).localeCompare(String(b))))}function versionParts(version){const match=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(version);if(!match)throw Error("Invalid registry version.");return[Number(match[1]),Number(match[2]),Number(match[3]),match[4]]}function newer(current,target,times={}){if(current===target)return false;const a=versionParts(current),b=versionParts(target);for(const i of[0,1,2])if(a[i]!==b[i])return b[i]>a[i];if(!a[3])return false;if(!b[3])return true;const oldTime=Date.parse(times[current]??""),newTime=Date.parse(times[target]??"");if(Number.isFinite(oldTime)&&Number.isFinite(newTime))return newTime>oldTime;const left=a[3].split("."),right=b[3].split(".");for(let i=0;i<Math.max(left.length,right.length);i++){if(left[i]===right[i])continue;if(left[i]===void 0)return true;if(right[i]===void 0)return false;return/^\d+$/.test(left[i])&&/^\d+$/.test(right[i])?Number(right[i])>Number(left[i]):right[i]>left[i]}return false}function manual(version,installationPath){return`Use the package manager that installed ${installationPath} to upgrade ${NAME} to exactly ${version} at that installation path.`}export function createUpdater(options={}){let packageRoot=resolve(options.packageRoot??fileURLToPath(new URL("..",import.meta.url)));const requestedRoot=packageRoot;const{recover,recoverLocked,withRecoveryLock,publishLock,rollback}=createUpdateRecovery(requestedRoot);let rootIsLinked=false,rootReady;const canonicalizeRoot=()=>rootReady??=(async()=>{rootIsLinked=(await lstat(requestedRoot)).isSymbolicLink();packageRoot=await realpath(requestedRoot)})();const cacheRoot=resolve(options.cacheRoot??join(homedir(),".zortex","updates",hash(packageRoot).slice(0,24)));const registry=(options.registryUrl??"https://registry.npmjs.org").replace(/\/$/,"");const content=(options.contentBaseUrl??"https://cdn.jsdelivr.net/npm").replace(/\/$/,"");const fetcher=options.fetch??globalThis.fetch,now=options.now??Date.now;const env=options.env??process.env;const outcomes=createUpdateTelemetry({cacheRoot,env,now});const disabled=()=>/^(0|false|off)$/i.test(env.ZORTEX_UPDATES??"");const offerPath=join(cacheRoot,"offer.json"),statusPath=join(cacheRoot,"status.json");const pkg=async()=>{await canonicalizeRoot();return JSON.parse(await readFile(join(packageRoot,"package.json"),"utf8"))};async function get(url,limit,timeout=5e3){const response=await fetcher(url,{signal:AbortSignal.timeout(timeout),redirect:"error"});if(!response.ok||!response.body)throw Error(`Update download unavailable (${response.status}).`);if(Number(response.headers.get("content-length")??0)>limit)throw Error("Update response exceeds its size limit.");const chunks=[];let size=0;for await(const chunk of response.body){size+=chunk.length;if(size>limit)throw Error("Update response exceeds its size limit.");chunks.push(chunk)}return Buffer.concat(chunks)}const fileUrl=(version,path)=>`${content}/${NAME}@${encodeURIComponent(version)}/${path.split("/").map(encodeURIComponent).join("/")}`;async function savedOffer(){await canonicalizeRoot();const bytes=await optionalBytes(offerPath);const parsed=bytes?JSON.parse(bytes.toString("utf8")):void 0;const offered=parsed?(({confirmationRequired:_legacy,...offer})=>offer)(parsed):void 0;return offered?.installationPath===packageRoot?offered:void 0}async function savedStatus(version){try{const bytes=await optionalBytes(statusPath);const cached=bytes?JSON.parse(bytes.toString("utf8")):void 0;if(cached?.status?.currentVersion===version&&cached.expiresAt>now())return cached.status}catch{}return void 0}async function remember(status2,ttl){await rm(offerPath,{force:true});await mkdir(cacheRoot,{recursive:true});await atomicWrite(statusPath,jsonBytes({status:status2,checkedAt:now(),expiresAt:now()+ttl}));return status2}async function writableInstallation(){await canonicalizeRoot();if(rootIsLinked||/[\\/](?:\.pnpm|\.yarn|_npx)[\\/]/i.test(packageRoot)||/[\\/](?:\.pnpm|\.yarn|_npx)[\\/]/i.test(requestedRoot)||await optionalBytes(join(packageRoot,"tsconfig.json")))throw Error("This installation is managed by a workspace or another package manager. Use its original upgrade command.");if((await pkg()).name!==NAME)throw Error("The running installation is not the Zortex package.")}async function check({force=false}={}){const installed=await pkg();if(disabled())return{state:"unavailable",currentVersion:installed.version,message:"Update checks are disabled."};try{const cached=await savedOffer();if(!force&&cached?.currentVersion===installed.version&&cached.expiresAt>now())return cached;if(!force){const cachedStatus=await savedStatus(installed.version);if(cachedStatus)return cachedStatus}const packument=JSON.parse((await get(`${registry}/${encodeURIComponent(NAME)}`,16e6)).toString("utf8"));const channel="next";const target=packument["dist-tags"]?.[channel];if(typeof target!=="string")throw Error("The update channel is unavailable.");if(!newer(installed.version,target,packument.time))return await remember({state:"current",currentVersion:installed.version},6*60*6e4);const targetPackage=packument.versions?.[target];if(targetPackage?.name!==NAME||targetPackage.version!==target)throw Error("Invalid registry package identity.");const digest=metadataDigest(targetPackage);if(!digest)return await remember({state:"unsupported",currentVersion:installed.version,targetVersion:target,message:"This release does not publish verified incremental updates. No package was downloaded.",manualCommand:manual(target,packageRoot)},6*60*6e4);if(binShape(installed)!==binShape(targetPackage))return await remember({state:"unsupported",currentVersion:installed.version,targetVersion:target,message:"This release changes installed command links and requires its original package manager.",manualCommand:manual(target,packageRoot)},6*60*6e4);await writableInstallation();let expectedDownloadBytes,expectedChangedFiles;try{const manifestBytes=await get(fileUrl(target,MANIFEST),4e6,15e3);const manifest=validateManifest(manifestBytes,digest,target);const oldDigest=metadataDigest(installed),oldBytes=oldDigest?await optionalBytes(join(packageRoot,MANIFEST)):void 0;if(oldDigest&&oldBytes){const old=validateManifest(oldBytes,oldDigest,installed.version);const oldByPath=new Map(old.files.map(file=>[file.path,file.sha256]));const generated=await reconstruct(manifest,manifestBytes,digest);for(const[path,bytes]of generated){if(oldByPath.get(path)===hash(bytes))continue;expectedDownloadBytes=(expectedDownloadBytes??0)+bytes.length;expectedChangedFiles=(expectedChangedFiles??0)+1}for(const file of manifest.files){if(oldByPath.get(file.path)===file.sha256)continue;expectedDownloadBytes=(expectedDownloadBytes??0)+file.size;expectedChangedFiles=(expectedChangedFiles??0)+1}}}catch{}const offer={state:"available",currentVersion:installed.version,targetVersion:target,installationPath:packageRoot,confirmationToken:randomUUID(),manifestSha256:digest,checkedAt:now(),expiresAt:now()+15*6e4,channel,...expectedDownloadBytes!==void 0&&expectedChangedFiles!==void 0?{expectedDownloadBytes,expectedChangedFiles}:{}};await mkdir(cacheRoot,{recursive:true});await atomicWrite(offerPath,jsonBytes(offer));await rm(statusPath,{force:true});return offer}catch(error){const unavailable={state:"unavailable",currentVersion:installed.version,message:error instanceof Error?error.message:"Update check failed."};try{await remember(unavailable,15*6e4)}catch{}return unavailable}}async function status(){const installed=await pkg();if(disabled())return{state:"unavailable",currentVersion:installed.version,message:"Update checks are disabled."};try{const cached=await savedOffer();if(cached?.currentVersion===installed.version&&cached.expiresAt>now())return cached}catch{}return await savedStatus(installed.version)??{state:"unavailable",currentVersion:installed.version,message:"No current update result is cached. Use update check to check the registry."}}async function reconstruct(manifest,bytes,digest){const packageBytes=jsonBytes({...manifest.package,zortexUpdate:{schemaVersion:1,manifest:MANIFEST,sha256:digest}});const generated=new Map([["package.json",packageBytes],[MANIFEST,bytes]]);if(manifest.provenance){const provenance=structuredClone(manifest.provenance);const own=manifest.files.filter(file=>!file.path.startsWith("node_modules/")).map(file=>({path:file.path,sha256:file.sha256}));own.push({path:"package.json",sha256:hash(packageBytes)},{path:MANIFEST,sha256:hash(bytes)});const root=provenance.packages?.find(row=>row.target==="");if(!root||root.filesSha256!==null)throw Error("Invalid update provenance template.");root.filesSha256=hash(own.map(file=>file.path+"\0"+file.sha256).sort().join("\n"));generated.set("release-provenance.json",jsonBytes(provenance))}return generated}async function smoke(version){if(options.smokeTest)return options.smokeTest(packageRoot,version);const cli=join(packageRoot,"dist","cli.js");const verificationEnv={...env,ZORTEX_UPDATES:"0",ZORTEX_UPDATE_VERIFY:"1",ZORTEX_AUTO_SYNC:"0",ZORTEX_CODEX_SETUP:"0",ZORTEX_TELEMETRY:"0",ZORTEX_FEEDBACK_TRAFFIC_CLASS:"internal_test"};const result=await execute(process.execPath,[cli,"--version"],{env:verificationEnv,timeout:3e4,windowsHide:true,maxBuffer:1024*1024});if(JSON.parse(result.stdout).version!==version)throw Error("The updated command still runs a different version.");await execute(process.execPath,[cli,"--help"],{env:verificationEnv,timeout:3e4,windowsHide:true,maxBuffer:1024*1024})}async function withInstallationLock(action){if(disabled())throw Error("Updates are disabled by ZORTEX_UPDATES.");await writableInstallation();await recover();let unlock;try{unlock=await withRecoveryLock(async()=>{await recoverLocked();return publishLock(join(packageRoot,".zortex-update.lock"))})}catch(error){if(error.code==="EEXIST")throw Error("Another update holds the installation lock.");throw error}try{return await action({installationPath:packageRoot,environment:{ZORTEX_UPDATE_HANDOVER:unlock.token}})}finally{await unlock()}}async function apply({version,confirmationToken},lifecycle){if(disabled())throw Error("Updates are disabled by ZORTEX_UPDATES.");const offered=await savedOffer();if(!confirmationToken||!offered||offered.confirmationToken!==confirmationToken||offered.targetVersion!==version||offered.expiresAt<=now())throw Error("The release offer is missing, expired or mismatched. Run check again and retry with its version and token.");const confirmedAt=performance.now();const attempt=await outcomes.confirmed(offered.currentVersion,version).catch(()=>void 0);try{const result=await applyConfirmed(offered,version,lifecycle);const durationMs=Math.round(performance.now()-confirmedAt);await outcomes.installed(attempt,durationMs).catch(()=>{});return{...result,durationMs}}catch(error){await outcomes.failed(attempt,performance.now()-confirmedAt).catch(()=>{});throw error}}async function applyConfirmed(offered,version,lifecycle){return withInstallationLock(async lease=>{const installed=await pkg();if(installed.version!==offered.currentVersion)throw Error("The installed version changed. Check again before updating.");await mkdir(cacheRoot,{recursive:true});const started=performance.now();const stageName=".zortex-update-"+randomUUID(),stage=join(packageRoot,stageName);let journal,retainRecovery=false,updated=false;try{const target=JSON.parse((await get(`${registry}/${encodeURIComponent(NAME)}/${encodeURIComponent(version)}`,2e6)).toString("utf8"));if(target.name!==NAME||target.version!==version||metadataDigest(target)!==offered.manifestSha256)throw Error("The release changed. Run check again and retry with the current version and token.");const manifestBytes=await get(fileUrl(version,MANIFEST),4e6,15e3);const manifest=validateManifest(manifestBytes,offered.manifestSha256,version);if(!manifest.files.some(file=>file.path===RECOVERY_FILE))throw Error("This release removes the standalone update recovery module. "+manual(version,packageRoot));if(binShape(installed)!==binShape(manifest.package))throw Error("This release changes installed command links. "+manual(version,packageRoot));const dependencyChange=dependencyShape(installed)!==dependencyShape(manifest.package);const oldDigest=metadataDigest(installed),oldBytes=await optionalBytes(join(packageRoot,MANIFEST));if(!oldDigest||!oldBytes)throw Error(`This installation predates the incremental updater. One package-manager upgrade is required to install the baseline. ${manual(version,packageRoot)}`);const old=validateManifest(oldBytes,oldDigest,installed.version);const oldSpelling=new Map(old.files.map(file=>[file.path.toLowerCase(),file.path]));if(manifest.files.some(file=>oldSpelling.has(file.path.toLowerCase())&&oldSpelling.get(file.path.toLowerCase())!==file.path))throw Error("This release renames files only by letter case. "+manual(version,packageRoot));const generated=await reconstruct(manifest,manifestBytes,offered.manifestSha256);const nextPaths=new Set(manifest.files.map(file=>file.path));const removed=old.files.filter(file=>!nextPaths.has(file.path)).map(file=>file.path);let dependencies;if(dependencyChange){const dependencyStage=join(stage,"dependencies");dependencies=await(options.prepareDependencies??prepareDependencyUpdate)({packageRoot,stageRoot:dependencyStage,installedPackage:installed,targetPackage:manifest.package,env,registryUrl:registry});if(dependencies.replacements.length+dependencies.removals.length>2e3)throw Error("Too many dependency changes.");const seen=new Set,owned=[...old.files,...manifest.files].map(file=>file.path.toLowerCase());for(const path of[...dependencies.removals,...dependencies.replacements.map(row=>row.path)]){dependencyPath(path);const key=path.toLowerCase();if(seen.has(key)||owned.some(file=>file===key||file.startsWith(key+"/")))throw Error("Dependency update overlaps bundled product files.");seen.add(key);const existing=await lstat(await safeFile(packageRoot,path)).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(existing&&!existing.isDirectory())throw Error("Dependency update destination is not a directory.")}for(const replacement of dependencies.replacements){const source=await realpath(replacement.source),rel=relative(dependencyStage,source);if(!rel||isAbsolute(rel)||rel===".."||rel.startsWith(".."+sep)||!(await lstat(source)).isDirectory()||(await lstat(replacement.source)).isSymbolicLink())throw Error("Dependency update source is outside the staging directory.");replacement.source=source}const hiddenLock="node_modules/.package-lock.json";if(await optionalBytes(await safeFile(packageRoot,hiddenLock)))removed.push(hiddenLock)}const changes=[];const binPaths=new Set((typeof manifest.package.bin==="string"?[manifest.package.bin]:Object.values(manifest.package.bin??{})).map(path=>path.replace(/^\.\//,"")));let downloadedBytes=manifestBytes.length,reusedBytes=0;let cursor=0,downloadFailed=false;const downloads=await Promise.allSettled(Array.from({length:8},async()=>{try{while(!downloadFailed&&cursor<manifest.files.length){const file=manifest.files[cursor++];const destination=await safeFile(packageRoot,file.path);const existing=await optionalBytes(destination);const existingMode=existing===null?void 0:(await lstat(destination)).mode&511;const mode=file.mode??(binPaths.has(file.path)?493:existingMode);if(existing?.length===file.size&&hash(existing)===file.sha256){reusedBytes+=file.size;if(process.platform!=="win32"&&mode!==void 0&&mode!==existingMode)changes.push({path:file.path,bytes:existing,mode});continue}const bytes=await get(fileUrl(version,file.path),file.size,3e4);if(bytes.length!==file.size||hash(bytes)!==file.sha256)throw Error("Updated file integrity check failed: "+file.path);downloadedBytes+=bytes.length;changes.push({path:file.path,bytes,...mode===void 0?{}:{mode}})}}catch(error){downloadFailed=true;throw error}}));const failed=downloads.find(result=>result.status==="rejected");if(failed)throw failed.reason;for(const[path,bytes]of generated)changes.push({path,bytes});changes.sort((a,b)=>a.path===RECOVERY_FILE?-1:b.path===RECOVERY_FILE?1:a.path==="package.json"?1:b.path==="package.json"?-1:a.path.localeCompare(b.path));await mkdir(join(stage,"backup"),{recursive:true});const files=[];for(const path of[...dependencies?.removals??[],...dependencies?.replacements.map(row=>row.path)??[]]){const destination=await safeFile(packageRoot,path),existing=await lstat(destination).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});files.push({path,existed:!!existing,kind:"directory"});if(existing){const backup=join(stage,"backup",path);await mkdir(dirname(backup),{recursive:true});await cp(destination,backup,{recursive:true,verbatimSymlinks:true})}}for(const path of[...removed,...changes.map(file=>file.path)]){const destination=await safeFile(packageRoot,path),existing=await optionalBytes(destination);files.push({path,existed:existing!==null});if(existing){const backup=join(stage,"backup",path);await mkdir(dirname(backup),{recursive:true});await copyFile(destination,backup)}}for(const file of changes){const staged=join(stage,"new",file.path);await mkdir(dirname(staged),{recursive:true});await writeFile(staged,file.bytes);if(file.mode!==void 0)await chmod(staged,file.mode)}await lifecycle?.before(lease);journal={schemaVersion:1,pid:process.pid,stage:stageName,phase:"applying",files};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(journal));for(const path of removed)await rm(await safeFile(packageRoot,path),{force:true});for(const path of dependencies?.removals??[])await rm(await safeFile(packageRoot,path),{recursive:true,force:true});for(const replacement of dependencies?.replacements??[]){const destination=await safeFile(packageRoot,replacement.path);await rm(destination,{recursive:true,force:true});await mkdir(dirname(destination),{recursive:true});await rename(replacement.source,destination)}for(const file of changes){const destination=await safeFile(packageRoot,file.path);await mkdir(dirname(destination),{recursive:true});await rename(join(stage,"new",file.path),destination)}await smoke(version);const committed={...journal,phase:"committed"};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(committed));journal=committed;updated=true;await rm(offerPath,{force:true}).catch(()=>{});await rm(statusPath,{force:true}).catch(()=>{});return{state:"updated",currentVersion:installed.version,targetVersion:version,installationPath:packageRoot,downloadedBytes,reusedBytes,byteScope:"product-files",...dependencies?{dependencyUpdate:{reusedPackages:dependencies.reusedPackages,changedPackages:dependencies.changedPackages,durationMs:dependencies.durationMs}}:{},changedFiles:changes.length,removedFiles:removed.length,durationMs:Math.round(performance.now()-started),restartRequired:true}}catch(error){if(journal?.phase==="applying"){try{await rollback(journal);const restored={...journal,phase:"committed"};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(restored));journal=restored}catch(recoveryError){retainRecovery=true;throw recoveryError}}throw error}finally{try{await lifecycle?.after(lease,retainRecovery?"recovery-required":updated?"updated":"unchanged")}finally{if(!retainRecovery){try{await rm(stage,{recursive:true,force:true});await rm(join(packageRoot,JOURNAL),{force:true})}catch(cleanupError){if(journal?.phase!=="committed")throw cleanupError}}}}})}return{check,status,apply,recover,withInstallationLock,get installationPath(){return packageRoot},get updatesEnabled(){return!disabled()},observe:outcomes.observe}}export const productUpdater=createUpdater();
1
+ import{createHash,randomUUID}from"node:crypto";import{readFile,writeFile,mkdir,lstat,realpath,rename,copyFile,cp,rm,chmod}from"node:fs/promises";import{resolve,join,dirname,relative,isAbsolute,sep}from"node:path";import{homedir}from"node:os";import{fileURLToPath}from"node:url";import{execFile}from"node:child_process";import{promisify}from"node:util";import{prepareDependencyUpdate}from"./update-dependencies.js";import{createUpdateTelemetry}from"./update-telemetry.js";import{createUpdateRecovery,safePath,safeFile,optionalBytes,dependencyPath,atomicWrite,JOURNAL,RECOVERY_FILE}from"./update-recovery.js";const execute=promisify(execFile);const NAME="@zortexhq/indra-v2.5";const MANIFEST="update-manifest.json";const MAX_BYTES=12e7;const hash=bytes=>createHash("sha256").update(bytes).digest("hex");const jsonBytes=value=>Buffer.from(JSON.stringify(value,null,2)+"\n");function metadataDigest(pkg){const update=pkg.zortexUpdate;if(update?.schemaVersion!==1||update.manifest!==MANIFEST||!/^[a-f0-9]{64}$/.test(update.sha256??""))return void 0;return update.sha256}function validateManifest(bytes,digest,version){if(hash(bytes)!==digest)throw Error("Update manifest integrity check failed.");const value=JSON.parse(bytes.toString("utf8"));if(value.schemaVersion!==1||value.package?.name!==NAME||value.package.version!==version||value.package.zortexUpdate||!Array.isArray(value.files)||value.files.length>8e3)throw Error("Invalid update manifest.");let total=0;const paths=new Set;for(const file of value.files){safePath(file.path);const key=file.path.toLowerCase();if(paths.has(key)||[MANIFEST,"package.json","release-provenance.json"].includes(key)||!/^[a-f0-9]{64}$/.test(file.sha256)||!Number.isSafeInteger(file.size)||file.size<0||file.mode!==void 0&&![420,493,420,493].includes(file.mode))throw Error("Invalid update file entry.");paths.add(key);total+=file.size}if(total>MAX_BYTES)throw Error("Update exceeds the installed product size limit.");return value}function dependencyShape(pkg){const bundled=new Set(pkg.bundledDependencies??[]);return JSON.stringify(["dependencies","optionalDependencies","peerDependencies","peerDependenciesMeta"].map(field=>[field,Object.entries(pkg[field]??{}).filter(([name])=>!bundled.has(name)).sort(([a],[b])=>a.localeCompare(b))]))}function binShape(pkg){const bins=typeof pkg.bin==="string"?{[pkg.name.split("/").at(-1)]:pkg.bin}:pkg.bin??{};return JSON.stringify(Object.entries(bins).map(([name,path])=>[name,typeof path==="string"?path.replace(/^\.\//,""):path]).sort(([a],[b])=>String(a).localeCompare(String(b))))}function versionParts(version){const match=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(version);if(!match)throw Error("Invalid registry version.");return[Number(match[1]),Number(match[2]),Number(match[3]),match[4]]}function newer(current,target,times={}){if(current===target)return false;const a=versionParts(current),b=versionParts(target);for(const i of[0,1,2])if(a[i]!==b[i])return b[i]>a[i];if(!a[3])return false;if(!b[3])return true;const oldTime=Date.parse(times[current]??""),newTime=Date.parse(times[target]??"");if(Number.isFinite(oldTime)&&Number.isFinite(newTime))return newTime>oldTime;const left=a[3].split("."),right=b[3].split(".");for(let i=0;i<Math.max(left.length,right.length);i++){if(left[i]===right[i])continue;if(left[i]===void 0)return true;if(right[i]===void 0)return false;return/^\d+$/.test(left[i])&&/^\d+$/.test(right[i])?Number(right[i])>Number(left[i]):right[i]>left[i]}return false}function manual(version,installationPath){return`Use the package manager that installed ${installationPath} to upgrade ${NAME} to exactly ${version} at that installation path.`}export function createUpdater(options={}){let packageRoot=resolve(options.packageRoot??fileURLToPath(new URL("..",import.meta.url)));const requestedRoot=packageRoot;const{recover,recoverLocked,withRecoveryLock,publishLock,rollback}=createUpdateRecovery(requestedRoot);let rootIsLinked=false,rootReady;const canonicalizeRoot=()=>rootReady??=(async()=>{rootIsLinked=(await lstat(requestedRoot)).isSymbolicLink();packageRoot=await realpath(requestedRoot)})();const cacheRoot=resolve(options.cacheRoot??join(homedir(),".zortex","updates",hash(packageRoot).slice(0,24)));const registry=(options.registryUrl??"https://registry.npmjs.org").replace(/\/$/,"");const content=(options.contentBaseUrl??"https://cdn.jsdelivr.net/npm").replace(/\/$/,"");const fetcher=options.fetch??globalThis.fetch,now=options.now??Date.now;const env=options.env??process.env;const outcomes=createUpdateTelemetry({cacheRoot,env,now});const disabled=()=>/^(0|false|off)$/i.test(env.ZORTEX_UPDATES??"");const offerPath=join(cacheRoot,"offer.json"),statusPath=join(cacheRoot,"status.json");const pkg=async()=>{await canonicalizeRoot();return JSON.parse(await readFile(join(packageRoot,"package.json"),"utf8"))};async function get(url,limit,timeout=5e3){const response=await fetcher(url,{signal:AbortSignal.timeout(timeout),redirect:"error"});if(!response.ok||!response.body)throw Error(`Update download unavailable (${response.status}).`);if(Number(response.headers.get("content-length")??0)>limit)throw Error("Update response exceeds its size limit.");const chunks=[];let size=0;for await(const chunk of response.body){size+=chunk.length;if(size>limit)throw Error("Update response exceeds its size limit.");chunks.push(chunk)}return Buffer.concat(chunks)}const fileUrl=(version,path)=>`${content}/${NAME}@${encodeURIComponent(version)}/${path.split("/").map(encodeURIComponent).join("/")}`;async function savedOffer(){await canonicalizeRoot();const bytes=await optionalBytes(offerPath);const parsed=bytes?JSON.parse(bytes.toString("utf8")):void 0;const offered=parsed?(({confirmationRequired:_legacy,...offer})=>offer)(parsed):void 0;return offered?.installationPath===packageRoot?offered:void 0}async function savedStatus(version){try{const bytes=await optionalBytes(statusPath);const cached=bytes?JSON.parse(bytes.toString("utf8")):void 0;if(cached?.status?.currentVersion===version&&cached.expiresAt>now())return cached.status}catch{}return void 0}async function remember(status2,ttl){await rm(offerPath,{force:true});await mkdir(cacheRoot,{recursive:true});await atomicWrite(statusPath,jsonBytes({status:status2,checkedAt:now(),expiresAt:now()+ttl}));return status2}async function writableInstallation(){await canonicalizeRoot();if(rootIsLinked||/[\\/](?:\.pnpm|\.yarn|_npx)[\\/]/i.test(packageRoot)||/[\\/](?:\.pnpm|\.yarn|_npx)[\\/]/i.test(requestedRoot)||await optionalBytes(join(packageRoot,"tsconfig.json")))throw Error("This installation is managed by a workspace or another package manager. Use its original upgrade command.");if((await pkg()).name!==NAME)throw Error("The running installation is not the Zortex package.")}async function check({force=false}={}){const installed=await pkg();if(disabled())return{state:"unavailable",currentVersion:installed.version,message:"Update checks are disabled."};try{const cached=await savedOffer();if(!force&&cached?.currentVersion===installed.version&&cached.expiresAt>now())return cached;if(!force){const cachedStatus=await savedStatus(installed.version);if(cachedStatus)return cachedStatus}const packument=JSON.parse((await get(`${registry}/${encodeURIComponent(NAME)}`,16e6)).toString("utf8"));const channel="next";const target=packument["dist-tags"]?.[channel];if(typeof target!=="string")throw Error("The update channel is unavailable.");if(!newer(installed.version,target,packument.time))return await remember({state:"current",currentVersion:installed.version},6*60*6e4);const targetPackage=packument.versions?.[target];if(targetPackage?.name!==NAME||targetPackage.version!==target)throw Error("Invalid registry package identity.");const digest=metadataDigest(targetPackage);if(!digest)return await remember({state:"unsupported",currentVersion:installed.version,targetVersion:target,message:"This release does not publish verified incremental updates. No package was downloaded.",manualCommand:manual(target,packageRoot)},6*60*6e4);if(binShape(installed)!==binShape(targetPackage))return await remember({state:"unsupported",currentVersion:installed.version,targetVersion:target,message:"This release changes installed command links and requires its original package manager.",manualCommand:manual(target,packageRoot)},6*60*6e4);await writableInstallation();let expectedDownloadBytes,expectedChangedFiles;try{const manifestBytes=await get(fileUrl(target,MANIFEST),4e6,15e3);const manifest=validateManifest(manifestBytes,digest,target);const oldDigest=metadataDigest(installed),oldBytes=oldDigest?await optionalBytes(join(packageRoot,MANIFEST)):void 0;if(oldDigest&&oldBytes){const old=validateManifest(oldBytes,oldDigest,installed.version);const oldByPath=new Map(old.files.map(file=>[file.path,file.sha256]));const generated=await reconstruct(manifest,manifestBytes,digest);for(const[path,bytes]of generated){if(oldByPath.get(path)===hash(bytes))continue;expectedDownloadBytes=(expectedDownloadBytes??0)+bytes.length;expectedChangedFiles=(expectedChangedFiles??0)+1}for(const file of manifest.files){if(oldByPath.get(file.path)===file.sha256)continue;expectedDownloadBytes=(expectedDownloadBytes??0)+file.size;expectedChangedFiles=(expectedChangedFiles??0)+1}}}catch{}const offer={state:"available",currentVersion:installed.version,targetVersion:target,installationPath:packageRoot,confirmationToken:randomUUID(),manifestSha256:digest,checkedAt:now(),expiresAt:now()+15*6e4,channel,...expectedDownloadBytes!==void 0&&expectedChangedFiles!==void 0?{expectedDownloadBytes,expectedChangedFiles}:{}};await mkdir(cacheRoot,{recursive:true});await atomicWrite(offerPath,jsonBytes(offer));await rm(statusPath,{force:true});return offer}catch(error){const unavailable={state:"unavailable",currentVersion:installed.version,message:error instanceof Error?error.message:"Update check failed."};try{await remember(unavailable,15*6e4)}catch{}return unavailable}}async function status(){const installed=await pkg();if(disabled())return{state:"unavailable",currentVersion:installed.version,message:"Update checks are disabled."};try{const cached=await savedOffer();if(cached?.currentVersion===installed.version&&cached.expiresAt>now())return cached}catch{}return await savedStatus(installed.version)??{state:"unavailable",currentVersion:installed.version,message:"No current update result is cached. Use update check to check the registry."}}async function reconstruct(manifest,bytes,digest){const packageBytes=jsonBytes({...manifest.package,zortexUpdate:{schemaVersion:1,manifest:MANIFEST,sha256:digest}});const generated=new Map([["package.json",packageBytes],[MANIFEST,bytes]]);if(manifest.provenance){const provenance=structuredClone(manifest.provenance);const own=manifest.files.filter(file=>!file.path.startsWith("node_modules/")).map(file=>({path:file.path,sha256:file.sha256}));own.push({path:"package.json",sha256:hash(packageBytes)},{path:MANIFEST,sha256:hash(bytes)});const root=provenance.packages?.find(row=>row.target==="");if(!root||root.filesSha256!==null)throw Error("Invalid update provenance template.");root.filesSha256=hash(own.map(file=>file.path+"\0"+file.sha256).sort().join("\n"));generated.set("release-provenance.json",jsonBytes(provenance))}return generated}async function smoke(version){if(options.smokeTest)return options.smokeTest(packageRoot,version);const cli=join(packageRoot,"dist","cli.js");const verificationEnv={...env,ZORTEX_UPDATES:"0",ZORTEX_UPDATE_VERIFY:"1",ZORTEX_AUTO_SYNC:"0",ZORTEX_CODEX_SETUP:"0",ZORTEX_TELEMETRY:"0",ZORTEX_FEEDBACK_TRAFFIC_CLASS:"internal_test"};const result=await execute(process.execPath,[cli,"--version"],{env:verificationEnv,timeout:3e4,windowsHide:true,maxBuffer:1024*1024});if(JSON.parse(result.stdout).version!==version)throw Error("The updated command still runs a different version.");await execute(process.execPath,[cli,"--help"],{env:verificationEnv,timeout:3e4,windowsHide:true,maxBuffer:1024*1024})}async function withInstallationLock(action,{scope="package"}={}){if(scope==="package"&&disabled())throw Error("Updates are disabled by ZORTEX_UPDATES.");await writableInstallation();await recover();let unlock;try{unlock=await withRecoveryLock(async()=>{await recoverLocked();return publishLock(join(packageRoot,".zortex-update.lock"))})}catch(error){if(error.code==="EEXIST")throw Error("Another update holds the installation lock.");throw error}try{return await action({installationPath:packageRoot,environment:{ZORTEX_UPDATE_HANDOVER:unlock.token}})}finally{await unlock()}}async function apply({version,confirmationToken},lifecycle){if(disabled())throw Error("Updates are disabled by ZORTEX_UPDATES.");const offered=await savedOffer();if(!confirmationToken||!offered||offered.confirmationToken!==confirmationToken||offered.targetVersion!==version||offered.expiresAt<=now())throw Error("The release offer is missing, expired or mismatched. Run check again and retry with its version and token.");const confirmedAt=performance.now();const attempt=await outcomes.confirmed(offered.currentVersion,version).catch(()=>void 0);try{const result=await applyConfirmed(offered,version,lifecycle);const durationMs=Math.round(performance.now()-confirmedAt);await outcomes.installed(attempt,durationMs).catch(()=>{});return{...result,durationMs}}catch(error){await outcomes.failed(attempt,performance.now()-confirmedAt).catch(()=>{});throw error}}async function applyConfirmed(offered,version,lifecycle){return withInstallationLock(async lease=>{const installed=await pkg();if(installed.version!==offered.currentVersion)throw Error("The installed version changed. Check again before updating.");await mkdir(cacheRoot,{recursive:true});const started=performance.now();const stageName=".zortex-update-"+randomUUID(),stage=join(packageRoot,stageName);let journal,retainRecovery=false,updated=false;try{const target=JSON.parse((await get(`${registry}/${encodeURIComponent(NAME)}/${encodeURIComponent(version)}`,2e6)).toString("utf8"));if(target.name!==NAME||target.version!==version||metadataDigest(target)!==offered.manifestSha256)throw Error("The release changed. Run check again and retry with the current version and token.");const manifestBytes=await get(fileUrl(version,MANIFEST),4e6,15e3);const manifest=validateManifest(manifestBytes,offered.manifestSha256,version);await lifecycle?.validateTarget?.(manifest.package);if(!manifest.files.some(file=>file.path===RECOVERY_FILE))throw Error("This release removes the standalone update recovery module. "+manual(version,packageRoot));if(binShape(installed)!==binShape(manifest.package))throw Error("This release changes installed command links. "+manual(version,packageRoot));const dependencyChange=dependencyShape(installed)!==dependencyShape(manifest.package);const oldDigest=metadataDigest(installed),oldBytes=await optionalBytes(join(packageRoot,MANIFEST));if(!oldDigest||!oldBytes)throw Error(`This installation predates the incremental updater. One package-manager upgrade is required to install the baseline. ${manual(version,packageRoot)}`);const old=validateManifest(oldBytes,oldDigest,installed.version);const oldSpelling=new Map(old.files.map(file=>[file.path.toLowerCase(),file.path]));if(manifest.files.some(file=>oldSpelling.has(file.path.toLowerCase())&&oldSpelling.get(file.path.toLowerCase())!==file.path))throw Error("This release renames files only by letter case. "+manual(version,packageRoot));const generated=await reconstruct(manifest,manifestBytes,offered.manifestSha256);const nextPaths=new Set(manifest.files.map(file=>file.path));const removed=old.files.filter(file=>!nextPaths.has(file.path)).map(file=>file.path);let dependencies;if(dependencyChange){const dependencyStage=join(stage,"dependencies");dependencies=await(options.prepareDependencies??prepareDependencyUpdate)({packageRoot,stageRoot:dependencyStage,installedPackage:installed,targetPackage:manifest.package,env,registryUrl:registry});if(dependencies.replacements.length+dependencies.removals.length>2e3)throw Error("Too many dependency changes.");const seen=new Set,owned=[...old.files,...manifest.files].map(file=>file.path.toLowerCase());for(const path of[...dependencies.removals,...dependencies.replacements.map(row=>row.path)]){dependencyPath(path);const key=path.toLowerCase();if(seen.has(key)||owned.some(file=>file===key||file.startsWith(key+"/")))throw Error("Dependency update overlaps bundled product files.");seen.add(key);const existing=await lstat(await safeFile(packageRoot,path)).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(existing&&!existing.isDirectory())throw Error("Dependency update destination is not a directory.")}for(const replacement of dependencies.replacements){const source=await realpath(replacement.source),rel=relative(dependencyStage,source);if(!rel||isAbsolute(rel)||rel===".."||rel.startsWith(".."+sep)||!(await lstat(source)).isDirectory()||(await lstat(replacement.source)).isSymbolicLink())throw Error("Dependency update source is outside the staging directory.");replacement.source=source}const hiddenLock="node_modules/.package-lock.json";if(await optionalBytes(await safeFile(packageRoot,hiddenLock)))removed.push(hiddenLock)}const changes=[];const binPaths=new Set((typeof manifest.package.bin==="string"?[manifest.package.bin]:Object.values(manifest.package.bin??{})).map(path=>path.replace(/^\.\//,"")));let downloadedBytes=manifestBytes.length,reusedBytes=0;let cursor=0,downloadFailed=false;const downloads=await Promise.allSettled(Array.from({length:8},async()=>{try{while(!downloadFailed&&cursor<manifest.files.length){const file=manifest.files[cursor++];const destination=await safeFile(packageRoot,file.path);const existing=await optionalBytes(destination);const existingMode=existing===null?void 0:(await lstat(destination)).mode&511;const mode=file.mode??(binPaths.has(file.path)?493:existingMode);if(existing?.length===file.size&&hash(existing)===file.sha256){reusedBytes+=file.size;if(process.platform!=="win32"&&mode!==void 0&&mode!==existingMode)changes.push({path:file.path,bytes:existing,mode});continue}const bytes=await get(fileUrl(version,file.path),file.size,3e4);if(bytes.length!==file.size||hash(bytes)!==file.sha256)throw Error("Updated file integrity check failed: "+file.path);downloadedBytes+=bytes.length;changes.push({path:file.path,bytes,...mode===void 0?{}:{mode}})}}catch(error){downloadFailed=true;throw error}}));const failed=downloads.find(result=>result.status==="rejected");if(failed)throw failed.reason;for(const[path,bytes]of generated)changes.push({path,bytes});changes.sort((a,b)=>a.path===RECOVERY_FILE?-1:b.path===RECOVERY_FILE?1:a.path==="package.json"?1:b.path==="package.json"?-1:a.path.localeCompare(b.path));await mkdir(join(stage,"backup"),{recursive:true});const files=[];for(const path of[...dependencies?.removals??[],...dependencies?.replacements.map(row=>row.path)??[]]){const destination=await safeFile(packageRoot,path),existing=await lstat(destination).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});files.push({path,existed:!!existing,kind:"directory"});if(existing){const backup=join(stage,"backup",path);await mkdir(dirname(backup),{recursive:true});await cp(destination,backup,{recursive:true,verbatimSymlinks:true})}}for(const path of[...removed,...changes.map(file=>file.path)]){const destination=await safeFile(packageRoot,path),existing=await optionalBytes(destination);files.push({path,existed:existing!==null});if(existing){const backup=join(stage,"backup",path);await mkdir(dirname(backup),{recursive:true});await copyFile(destination,backup)}}for(const file of changes){const staged=join(stage,"new",file.path);await mkdir(dirname(staged),{recursive:true});await writeFile(staged,file.bytes);if(file.mode!==void 0)await chmod(staged,file.mode)}await lifecycle?.before(lease);journal={schemaVersion:1,pid:process.pid,stage:stageName,phase:"applying",files};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(journal));for(const path of removed)await rm(await safeFile(packageRoot,path),{force:true});for(const path of dependencies?.removals??[])await rm(await safeFile(packageRoot,path),{recursive:true,force:true});for(const replacement of dependencies?.replacements??[]){const destination=await safeFile(packageRoot,replacement.path);await rm(destination,{recursive:true,force:true});await mkdir(dirname(destination),{recursive:true});await rename(replacement.source,destination)}for(const file of changes){const destination=await safeFile(packageRoot,file.path);await mkdir(dirname(destination),{recursive:true});await rename(join(stage,"new",file.path),destination)}await smoke(version);const committed={...journal,phase:"committed"};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(committed));journal=committed;updated=true;await rm(offerPath,{force:true}).catch(()=>{});await rm(statusPath,{force:true}).catch(()=>{});return{state:"updated",currentVersion:installed.version,targetVersion:version,installationPath:packageRoot,downloadedBytes,reusedBytes,byteScope:"product-files",...dependencies?{dependencyUpdate:{reusedPackages:dependencies.reusedPackages,changedPackages:dependencies.changedPackages,durationMs:dependencies.durationMs}}:{},changedFiles:changes.length,removedFiles:removed.length,durationMs:Math.round(performance.now()-started),restartRequired:true}}catch(error){if(journal?.phase==="applying"){try{await rollback(journal);const restored={...journal,phase:"committed"};await atomicWrite(join(packageRoot,JOURNAL),jsonBytes(restored));journal=restored}catch(recoveryError){retainRecovery=true;throw recoveryError}}throw error}finally{try{await lifecycle?.after(lease,retainRecovery?"recovery-required":updated?"updated":"unchanged")}finally{if(!retainRecovery){try{await rm(stage,{recursive:true,force:true});await rm(join(packageRoot,JOURNAL),{force:true})}catch(cleanupError){if(journal?.phase!=="committed")throw cleanupError}}}}})}return{check,status,apply,recover,withInstallationLock,get installationPath(){return packageRoot},get updatesEnabled(){return!disabled()},observe:outcomes.observe}}export const productUpdater=createUpdater();
@@ -0,0 +1 @@
1
+ import{spawn}from"node:child_process";import{fileURLToPath}from"node:url";import{isAbsolute}from"node:path";const states=new Set(["current","updated","repaired","deferred","unavailable","unsupported","failed"]);export function automaticUpdateResult(value){const result=value&&typeof value==="object"?value:{};if(result.pending===true||result.activation?.state==="failed")return{state:"deferred",reason:"handover_pending"};if(typeof result.state!=="string"||!states.has(result.state))return{state:"failed",reason:"update_result_unavailable"};return{state:result.state,...typeof result.reason==="string"&&/^[a-z][a-z0-9_]{0,79}$/.test(result.reason)?{reason:result.reason}:{},...typeof result.currentVersion==="string"&&result.currentVersion.length<100?{currentVersion:result.currentVersion}:{},...typeof result.targetVersion==="string"&&result.targetVersion.length<100?{targetVersion:result.targetVersion}:{}}}export function launchAutomaticUpdate(root){if(!isAbsolute(root))return Promise.reject(Error("Automatic update Vault must be absolute."));return new Promise(resolve=>{const child=spawn(process.execPath,[fileURLToPath(new URL("./update-check.js",import.meta.url)),"--apply","--root",root],{stdio:["ignore","ignore","ignore","ipc"],detached:true,windowsHide:true,env:process.env});let result,settled=false;const finish=()=>{if(settled)return;settled=true;resolve(result??{state:"failed",reason:"update_coordinator_unavailable"})};child.on("message",value=>{result=automaticUpdateResult(value)});child.once("error",finish);child.once("exit",finish);child.unref();child.channel?.unref()})}export function startAutomaticUpdates(root,options={}){const enabled=options.enabled??(!/^(0|false|off)$/i.test(process.env.ZORTEX_UPDATES??"")&&process.env.ZORTEX_FEEDBACK_TRAFFIC_CLASS!=="internal_test"&&process.env.ZORTEX_UPDATE_VERIFY!=="1");const run=options.run??launchAutomaticUpdate,now=options.now??Date.now,interval=Math.max(1,options.intervalMs??6*60*6e4),retry=Math.max(1,options.retryMs??6e4);let closed=!enabled,timer,running,failures=0;let status={state:enabled?"scheduled":"closed"};function schedule(delay){if(closed)return;status.nextAt=new Date(now()+delay).toISOString();timer=setTimeout(()=>{timer=void 0;void tick()},delay);timer.unref?.()}function tick(){if(closed||running)return running??Promise.resolve();status={...status,state:"running"};delete status.nextAt;running=(async()=>{let result;try{result=automaticUpdateResult(await run(root))}catch{result={state:"failed",reason:"update_coordinator_unavailable"}}if(closed)return;status={...result,lastFinishedAt:new Date(now()).toISOString()};const failed=result.state==="failed"||result.state==="unavailable";failures=failed?Math.min(failures+1,7):0;const delay=result.state==="deferred"?retry:failed?Math.min(interval,retry*2**(failures-1)):interval;schedule(delay)})().finally(()=>{running=void 0});return running}if(enabled)schedule(0);return{status:()=>({...status}),tick,close(){closed=true;if(timer)clearTimeout(timer);timer=void 0;status={...status,state:"closed"};delete status.nextAt}}}