@zortexhq/indra-v2.5 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/bin/codex-postinstall.mjs +1 -1
- package/dist/action-effect.js +1 -0
- package/dist/action-read-progress.js +1 -1
- package/dist/actions-catalog.js +1 -0
- package/dist/auto-sync.js +1 -1
- package/dist/auto-update.js +1 -1
- package/dist/automatic-updates.js +1 -0
- package/dist/bundled-handbook.js +1 -1
- package/dist/cli-run.js +1 -1
- package/dist/cli.js +1 -1
- package/dist/codex-install.js +1 -1
- package/dist/codex-setup.js +1 -1
- package/dist/computer-use-setup.js +1 -0
- package/dist/default-root.js +1 -1
- package/dist/documentation-action.js +1 -0
- package/dist/gateway.js +1 -1
- package/dist/imessage-sync.js +1 -1
- package/dist/local-cloud-policy.js +1 -1
- package/dist/local-cloud.js +1 -1
- package/dist/mcp.js +1 -3
- package/dist/native-connect.js +1 -1
- package/dist/native-level1-setup.js +1 -1
- package/dist/native-ollama-discovery.js +1 -0
- package/dist/native-vault-discovery.js +1 -1
- package/dist/onboard-cli.js +1 -1
- package/dist/onboard.js +1 -1
- package/dist/onboarding.js +1 -1
- package/dist/profile.js +1 -1
- package/dist/public-tool.js +4 -1
- package/dist/read-route.js +1 -1
- package/dist/recovery-authorization-url.js +1 -1
- package/dist/recovery-progress.js +1 -1
- package/dist/recovery.js +1 -1
- package/dist/resident-autopilot.js +1 -0
- package/dist/resident-ensure-ready.js +1 -1
- package/dist/resident-host.js +2 -2
- package/dist/resident-jobs.js +1 -1
- package/dist/resident-platform.js +2 -2
- package/dist/resident-runtime-identity.js +1 -1
- package/dist/resident-startup-state.js +1 -0
- package/dist/resident-telemetry.js +1 -1
- package/dist/shared-action-schemas.js +1 -0
- package/dist/source-data.js +1 -1
- package/dist/storage-compatibility.js +1 -0
- package/dist/supervised-sync.js +1 -1
- package/dist/tools.js +1 -1
- package/dist/update-check.js +1 -1
- package/dist/update-cli.js +1 -1
- package/dist/update-command.js +1 -1
- package/dist/update-recovery.js +1 -1
- package/node_modules/@zortexhq/plugin-auto-connect/dist/api/durable-dispatcher.js +1 -1
- package/node_modules/@zortexhq/plugin-auto-connect/dist/api/job-contract.js +1 -1
- package/node_modules/@zortexhq/plugin-autopilot/dist/api.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/cua.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/feedback.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/index.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/python-runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/service.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/worker.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/package.json +23 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/LICENSE +21 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/PROVENANCE.json +38 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/__init__.py +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/agent.py +178 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/browser.py +13 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/indra.patch +57 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/model.py +180 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/questions.py +26 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/transport.py +70 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/strategies.py +154 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/worker.py +260 -0
- package/node_modules/@zortexhq/plugin-connector-activitywatch/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-calendar/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-computer-files/dist/catalog.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/action-outcome.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/connectors.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/authorization-metrics.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/native-principal.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/package.json +2 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/connector.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/package.json +2 -1
- package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/compounds.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/action-content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-server.js +6 -6
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-native-process.mjs +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-server.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-server.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/macos-contacts-server.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-apple-native.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/provisioning.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/specs.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-netease/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-notion/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/mail-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-steam/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-teams/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-teams/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/auth-state.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/full-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/api/action-schemas.js +1 -0
- package/node_modules/@zortexhq/plugin-context-share/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/share.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-catalog.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/account.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -1
- package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/api/execution-scope.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/api/stdio-transport.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/windows-job.js +1 -1
- package/node_modules/@zortexhq/plugin-product-account/dist/index.js +4 -1
- package/node_modules/@zortexhq/plugin-product-account/dist/session-store.js +10 -0
- package/node_modules/@zortexhq/plugin-product-account/dist/storage.js +1 -0
- package/node_modules/@zortexhq/plugin-product-account/package.json +5 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/public-result-visibility.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/credentials.js +3 -3
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/keychain.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/public-visibility.js +7 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/recovery-guard.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +2 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-worker.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +2 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql.js +1 -1
- package/package.json +13 -7
- package/profiles/core.yml +2 -0
- package/release-provenance.json +48 -41
- package/update-manifest.json +573 -296
- package/dist/content-find.js +0 -2
- package/dist/find-snapshots.js +0 -1
- package/dist/match-excerpt.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";const namespace="indra-recovery-progress",prefix="progress/",staleMs=9e4;const codes=new Set(["unknown","aborted","interrupted","unavailable","failed_precondition","permission_denied","unauthenticated","not_found","data_loss","deadline_exceeded","resource_exhausted","authorization_timeout","authorization_denied","google_connection_failed","login_required","qr_scan_required","pairing_timeout","notion_page_selection_required","credentials_required","authorization_client_registration_failed","authorization_client_registration_required","authorization_callback_unavailable","authorization_callback_rejected","authorization_token_exchange_failed","authorization_credential_validation_failed","authorization_scope_mismatch","authorization_credential_storage_failed","authorization_registration_unavailable","authorization_client_configuration_required","configuration_reload_required","authorization_https_redirect_required","device_authorization_unavailable"]);const validSource=value=>typeof value==="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(value);const instant=value=>typeof value==="string"&&Number.isFinite(Date.parse(value));const count=value=>typeof value==="number"&&Number.isSafeInteger(value)&&value>=0;const safeCode=value=>codes.has(value)?value:"unknown";function projectReadiness(value,source){if(!value||typeof value!=="object")return;const row=value,operation=row.operation;if(row.source!==source||row.basis!=="actions"&&row.basis!=="read"||!operation||typeof operation!=="object")return;if(row.basis==="actions"&&(!count(row.actions)||row.actions===0)||row.basis==="read"&&row.actions!==void 0)return;if(operation.state!=="not-run"&&operation.state!=="succeeded")return;const returned="returned"in operation?operation.returned:void 0;if(returned!==void 0&&!count(returned)||operation.state==="not-run"&&returned!==void 0||row.basis==="read"&&(operation.state!=="succeeded"||!count(returned)))return;return{source,basis:row.basis,...row.basis==="actions"?{actions:row.actions}:{},operation:operation.state==="not-run"?{state:"not-run"}:{state:"succeeded",...count(returned)?{returned}:{}}}}
|
|
1
|
+
import{createHash,randomUUID}from"node:crypto";const namespace="indra-recovery-progress",prefix="progress/",staleMs=9e4;const codes=new Set(["unknown","aborted","interrupted","unavailable","failed_precondition","permission_denied","unauthenticated","not_found","data_loss","deadline_exceeded","resource_exhausted","authorization_timeout","authorization_denied","google_connection_failed","login_required","qr_scan_required","pairing_timeout","notion_page_selection_required","credentials_required","authorization_client_registration_failed","authorization_client_registration_required","authorization_callback_unavailable","authorization_callback_rejected","authorization_token_exchange_failed","authorization_credential_validation_failed","authorization_scope_mismatch","authorization_credential_storage_failed","authorization_registration_unavailable","authorization_client_configuration_required","configuration_reload_required","authorization_https_redirect_required","device_authorization_unavailable"]);const validSource=value=>typeof value==="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(value);const instant=value=>typeof value==="string"&&Number.isFinite(Date.parse(value));const count=value=>typeof value==="number"&&Number.isSafeInteger(value)&&value>=0;const safeCode=value=>codes.has(value)?value:"unknown";const validProof=value=>typeof value==="string"&&/^[a-f0-9]{64}$/.test(value);const registrationOwners=new WeakMap;export async function recoveryAuthorityProof(ctx,source,signal){try{const hub=ctx.get("zortexConnectorHub");if(signal?.aborted||!hub?.hasSource?.(source)&&!ctx.get("zortexLevel1Connectors")?.pending.some(row=>row.source===source))return;const enabled=()=>![...(ctx.get("loader")??ctx.loader)?.entries?.()??[]].some(row=>row.options.id===`indra-source-${source}`&&row.disabled);if(!enabled())return;const custody=ctx.get("zortexVaultStore")?.bindingCustody;if(!custody?.authoritySnapshot)return;const registration=hub?.registrationRevision?.(source),captured=await custody.authoritySnapshot({kind:"selected-source",source});if(!("ok"in captured)||captured.ok.source!==source||captured.ok.resolution.kind==="ambiguous_account")return;const{inventory,selection,legacy}=captured.ok;let authority;if(inventory){const{binding,grants}=inventory,audience=binding.authority?.resource??binding.provider;if(binding.state!=="connected")return;const selected=grants.filter(grant=>grant.bindingId===binding.id&&grant.purpose==="L1"&&grant.audience===audience);if(selected.length!==1||selected[0].state!=="active")return;authority={binding,grant:selected[0],selection}}else{if(legacy?.state==="disconnected")return;authority={legacy,selection}}if(signal?.aborted||!enabled()||ctx.get("zortexConnectorHub")!==hub||hub?.registrationRevision?.(source)!==registration)return;if(!registrationOwners.has(hub))registrationOwners.set(hub,randomUUID());return createHash("sha256").update(JSON.stringify({authority,registration,owner:registrationOwners.get(hub)})).digest("hex")}catch{return}}function projectReadiness(value,source){if(!value||typeof value!=="object")return;const row=value,operation=row.operation;if(row.source!==source||row.basis!=="actions"&&row.basis!=="read"||!operation||typeof operation!=="object")return;if(row.basis==="actions"&&(!count(row.actions)||row.actions===0)||row.basis==="read"&&row.actions!==void 0)return;if(operation.state!=="not-run"&&operation.state!=="succeeded")return;const returned="returned"in operation?operation.returned:void 0;if(returned!==void 0&&!count(returned)||operation.state==="not-run"&&returned!==void 0||row.basis==="read"&&(operation.state!=="succeeded"||!count(returned)))return;return{source,basis:row.basis,...row.basis==="actions"?{actions:row.actions}:{},operation:operation.state==="not-run"?{state:"not-run"}:{state:"succeeded",...count(returned)?{returned}:{}}}}function readRecoveryRows(ctx,now=Date.now()){try{const listed=ctx.get("zortexSqliteVault")?.createPrivateStore(namespace).list();if(!listed||!("ok"in listed))return[];return listed.ok.flatMap(entry=>{const row=entry.value;if(!row||!validSource(row.source)||entry.key!==prefix+row.source||!instant(row.startedAt)||!instant(row.updatedAt)||!["configuring","connecting","waiting-user","reading","finished"].includes(row.stage??"")||!["connected","unverified"].includes(row.connectionState??""))return[];const result={source:row.source,stage:row.stage,connectionState:row.connectionState,startedAt:row.startedAt,durationMs:Math.max(0,now-Date.parse(row.startedAt))};if(row.stage==="finished"){if(!instant(row.endedAt))return[];result.endedAt=row.endedAt;result.durationMs=Math.max(0,Date.parse(row.endedAt)-Date.parse(row.startedAt));if(count(row.returned))result.returned=row.returned;if(typeof row.errorCode==="string")result.errorCode=safeCode(row.errorCode);const readiness=row.connectionState==="connected"&&!row.errorCode?projectReadiness(row.readiness,row.source):void 0;if(readiness)result.readiness=readiness}else if(now-Date.parse(row.updatedAt)>staleMs){result.stage="finished";result.endedAt=row.updatedAt;result.durationMs=Math.max(0,Date.parse(row.updatedAt)-Date.parse(row.startedAt));result.errorCode="interrupted"}if(result.source==="ticktick"&&result.stage==="finished"&&!result.errorCode){result.connectionState="unverified";delete result.returned;delete result.readiness}return[{progress:result,...validProof(row.authorityProof)?{authorityProof:row.authorityProof}:{}}]})}catch{return[]}}export function readRecoveryProgress(ctx,now=Date.now()){return readRecoveryRows(ctx,now).map(row=>row.progress)}export async function readCurrentRecoveryProgress(ctx,now=Date.now()){return Promise.all(readRecoveryRows(ctx,now).map(async saved=>{const row={...saved.progress};if(row.connectionState==="connected"&&(!saved.authorityProof||await recoveryAuthorityProof(ctx,row.source)!==saved.authorityProof)){row.connectionState="unverified";delete row.readiness}return row}))}export function beginRecoveryProgress(ctx,source,now=Date.now,options={}){const attemptId=randomUUID();let row={source,stage:"connecting",connectionState:"unverified",startedAt:new Date(now()).toISOString(),durationMs:0,updatedAt:new Date(now()).toISOString(),attemptId},finished=false;let store;try{store=ctx.get("zortexSqliteVault")?.createPrivateStore(namespace)}catch{}function write(claim=false){if(!store||!validSource(source))return;try{for(let retry=0;retry<2;retry++){const saved=store.get(prefix+source);if(!("ok"in saved))return;const prior=saved.ok?.value;if(claim&&options.ifIdle&&prior?.stage!=="finished"&&instant(prior?.updatedAt)&&now()-Date.parse(prior.updatedAt)<=staleMs){finished=true;return}if(!claim&&prior?.attemptId!==attemptId)return;if(claim&&instant(prior?.startedAt)&&Date.parse(prior.startedAt)>=Date.parse(row.startedAt))row.startedAt=new Date(Date.parse(prior.startedAt)+1).toISOString();row.updatedAt=new Date(now()).toISOString();row.durationMs=Math.max(0,now()-Date.parse(row.startedAt));if("ok"in store.put(prefix+source,JSON.parse(JSON.stringify(row)),saved.ok?.revision??0))return}}catch{}}write(true);const heartbeat=finished?void 0:setInterval(()=>{if(!finished)write()},2e4);heartbeat?.unref();return{update(stage,connectionState){if(finished||row.stage===stage&&row.connectionState===connectionState)return;row={...row,stage,connectionState};write()},finish(result){if(finished)return;finished=true;clearInterval(heartbeat);const readiness=result.connectionState==="connected"&&!result.errorCode?projectReadiness(result.readiness,source):void 0;row={...row,stage:"finished",connectionState:result.connectionState,endedAt:new Date(now()).toISOString(),...count(result.returned)?{returned:result.returned}:{},...result.errorCode?{errorCode:safeCode(result.errorCode)}:{},...readiness?{readiness}:{},...validProof(result.authorityProof)?{authorityProof:result.authorityProof}:{}};write()}}}export async function mergedRecoveryProgress(ctx){const rows=new Map;try{for(const row of ctx.get("indraFleet")?.status().sources??[])if(validSource(row.source)&&instant(row.startedAt)){if(row.source==="ticktick")continue;const historical={...row,connectionState:"unverified",readiness:void 0};rows.set(row.source,historical)}}catch{}for(const row of await readCurrentRecoveryProgress(ctx)){const prior=rows.get(row.source);if(!prior||Date.parse(row.startedAt)>=Date.parse(prior.startedAt))rows.set(row.source,row)}return[...rows.values()]}
|
package/dist/recovery.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{supportsSavedReconnect}from"./saved-reconnect.js";import{validZendeskSelection}from"./zendesk-selection.js";import{validateJoplinSelection,validateJoplinResult}from"./joplin-selection.js";import{SETUP_RELOAD_NEXT}from"./setup-activation.js";import{createPreparedDiscordSource,createPreparedServiceSource,createPreparedWorkSource}from"@zortexhq/plugin-connector-level1";import{validZulipSelection}from"./zulip-selection.js";import{validFreshRSSSelection}from"./freshrss-selection.js";import{validMinifluxSelection}from"./miniflux-selection.js";import{validMattermostSelection}from"./mattermost-selection.js";import{validWallabagSelection}from"./wallabag-selection.js";import{validCalcomSelection}from"./calcom-selection.js";import{validWakatimeSelection}from"./wakatime-selection.js";import{validNextcloudInstanceUrl}from"./nextcloud-url.js";import{authorizationImage}from"@zortexhq/plugin-connector-core/api";import{createServer}from"node:http";import{randomBytes,randomUUID,timingSafeEqual}from"node:crypto";import{setTimeout as delay}from"node:timers/promises";import{isAbsolute}from"node:path";import{withFeedbackFlow}from"@zortexhq/plugin-telemetry/api";import{startupHistory}from"./startup.js";import{readOnboardingReport}from"./onboarding.js";import{HELP_CATALOG}from"./source-catalog.js";import{recoveryLaunch}from"./recovery-launch.js";import{recoverySurface}from"./recovery-surface.js";import{sourceSupport,recoverySetupFlags}from"./recovery-support.js";import{protectedRecoveryFormUrl,reviewedRecoveryAuthorizationUrl}from"./recovery-authorization-url.js";import{discoverNativeVaultCandidates}from"./native-vault-discovery.js";import{readRecoveryEvidence,saveRecoveryCheck,invalidateRecoveryEvidence,safeRecoverySource}from"./recovery-evidence.js";import{readPublicActionProgress}from"./public-action-progress.js";import{beginRecoveryProgress,readRecoveryProgress}from"./recovery-progress.js";export async function keepRecoverySurfaceOpen(session,opened,signal){if(opened&&!signal.aborted&&session.snapshot().state!=="closed")await session.closed}const NATIVE_FILE_SOURCES=new Set(["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","local-audio","obsidian","logseq","computer-files"]);const MAX_RECOVERY_REQUEST_BYTES=64*1024;const PUBLIC_ERROR_CODES=new Set(["unknown","account_identity_unavailable","aborted","interrupted","unavailable","failed_precondition","permission_denied","unauthenticated","not_found","data_loss","deadline_exceeded","resource_exhausted","authorization_timeout","authorization_denied","google_connection_failed","login_required","qr_scan_required","pairing_timeout","notion_page_selection_required","credentials_required","authorization_client_registration_failed","authorization_client_registration_required","authorization_callback_unavailable","authorization_callback_rejected","authorization_token_exchange_failed","authorization_credential_validation_failed","authorization_scope_mismatch","authorization_credential_storage_failed","authorization_registration_unavailable","authorization_client_configuration_required","configuration_reload_required","authorization_https_redirect_required","device_authorization_unavailable"]);const PENDING_HELP={"configuration-required":["This source needs configuration before it can be registered.","Complete this app\u2019s local setup with the available tools, then resume its connection. Other apps remain usable."],"authorization-required":["This source needs authorization before it can be registered.","Continue enrollment with the available browser or computer tools."],"ambiguous-account":["More than one account could be used for this source.","Use the task context and saved binding to identify the account, then continue connecting."],"ambiguous-resource":["More than one data resource could be used for this source.","Inspect the source configuration and saved account binding, repair the reported prerequisite and continue. Existing data and credentials are preserved."],"custody-unavailable":["The source authorization store is unavailable.","Inspect the source configuration and saved account binding, repair the reported prerequisite and continue. Existing data and credentials are preserved."]};export function validateNativeFileResult(source,result){if(result&&typeof result==="object"&&"ok"in result){const value=result.ok;if(value&&typeof value==="object"&&"source"in value&&value.source===source&&"state"in value&&typeof value.state==="string"&&["configured","configuration-required","permission-required","unavailable"].includes(value.state)&&"reloadRequired"in value&&typeof value.reloadRequired==="boolean"&&"next"in value&&typeof value.next==="string"&&(!("enabled"in value)||typeof value.enabled==="boolean"))return{ok:value}}if(result&&typeof result==="object"&&"err"in result&&result.err&&typeof result.err==="object"&&"code"in result.err&&typeof result.err.code==="string")return{err:{code:result.err.code}};return{err:{code:"invalid_resident_response"}}}const sessions=new WeakMap;const pendingSetupReloads=new WeakMap;const activeSources=new WeakMap;export function activeRecoverySource(ctx){return activeSources.get(ctx)?.source}const waiting=new Set(["connecting","waiting-user","reading"]);function authorizationHelp(code,_source){if(code==="failed_precondition")return["The connection prerequisites could not be verified.","Inspect the source configuration and saved account binding, repair the reported prerequisite and continue. Existing data and credentials are preserved."];if(code==="authorization_callback_unavailable")return["The saved authorization callback is already in use. Existing credentials are preserved.","Inspect the existing callback owner and continue that transaction. Start a replacement only after the previous owner has settled."];if(code==="authorization_client_registration_required")return["A new authorization cannot start with this installation\u2019s saved OAuth client. Existing credentials are preserved.","Repair the saved OAuth client\u2019s missing or incompatible callback details, then continue connecting."];if(code==="configuration_reload_required")return["Settings saved; connection has not been verified.",SETUP_RELOAD_NEXT];if(code==="authorization_client_configuration_required")return["This provider requires an OAuth client configuration that this connector does not currently have. No sign-in link was created.","Configure a supported OAuth client or connection service with the available setup tools, then resume this source."];if(code==="authorization_client_registration_failed")return["The provider could not register this installation\u2019s OAuth client. No sign-in link was created.","Repair the provider registration endpoint or client settings, then resume enrollment."];if(code==="authorization_registration_unavailable")return["This provider has no supported OAuth client registration configured. No sign-in link was created.","Configure a supported OAuth client through the available setup path, then resume enrollment."];if(code==="authorization_https_redirect_required")return["This provider requires an HTTPS callback that this local connection flow does not provide.","Configure the connector\u2019s supported HTTPS callback path before resuming enrollment."];if(code==="device_authorization_unavailable")return["The provider did not return a usable device authorization challenge. No sign-in code is available.","Repair the device authorization endpoint or client settings, then request a new challenge."];if(code==="credentials_required")return["This source needs credentials entered on its protected local connection page.","Use the protected local connection page and configured credential source. Request missing credential input only when the available tools cannot supply it; keep credentials out of chat."]}function reason(code,source){const help=authorizationHelp(code,source);if(help)return help[0];if(code==="authorization_denied"||code==="aborted"||code==="interrupted")return"Sign-in or authorization was not completed.";if(code==="authorization_timeout"||code==="deadline_exceeded")return"Authorization timed out. The previous link has expired.";if(code==="permission_denied")return"The current authorization does not include the required permissions.";if(code==="account_identity_unavailable")return"Zortex could not verify which account is signed in to this app.";if(code==="login_required")return"The provider reported that a signed-in session is required.";if(code==="qr_scan_required")return"WhatsApp needs a one-time QR scan from your phone.";if(code==="pairing_timeout")return"The WhatsApp QR code was not scanned in time.";return"Connection or reading did not finish. Your data and existing connections are saved."}const SITE_SIGN_IN=Object.freeze({x:"https://x.com/i/flow/login",instagram:"https://www.instagram.com/accounts/login/",linkedin:"https://www.linkedin.com/login",steam:"https://steamcommunity.com/login/home/",reddit:"https://www.reddit.com/login/",spotify:"https://accounts.spotify.com/login"});export function connectableOther(row){return row.state!=="unavailable"}const OTHER_HELP={steam:["Steam is not connected yet.","Continue Steam Community sign-in with the available browser tools, then check its profile read."],reddit:["Reddit is not connected yet.","Continue Reddit sign-in with the available browser tools, then check its read."],spotify:["Spotify is not connected yet.","Continue Spotify Web sign-in with the available browser tools, then check its read."],"google-tasks":["Google Tasks has not been verified on this computer yet.","Reuse the saved Google connection or continue sign-in with the available tools, then check Tasks."],"netease-mail":["NetEase Mail needs an IMAP authorization code.","Use the available mail settings and protected connection page to configure IMAP, then continue enrollment. Request the code only if it cannot be obtained through available tools."],notebooklm:["NotebookLM needs a Google sign-in in its connection browser.","Continue the Google connection page with the available browser or computer tools."],stripe:["Stripe needs a provider connection.","Complete the requested connection on Stripe\u2019s page with the available browser tools."],openrouter:["OpenRouter needs a provider connection.","Complete the requested connection on OpenRouter\u2019s page with the available browser tools."],calendly:["Calendly has not been verified on this computer yet.","Reuse the saved connection or continue Calendly sign-in with the available tools, then check its Actions."],shopify:["Shopify needs store and application configuration.","Find the requested store and configure its application through the available provider tools, then continue on the protected local connection page."],activitywatch:["ActivityWatch needs its local service running on this computer.","Start or repair the local ActivityWatch service with the available computer tools, then verify the source read."]};function currentReadinessRow(state){const proof=state.readiness;if(state.state!=="connected"||state.verification||state.registration||!proof||!Number.isSafeInteger(proof.actions)||proof.actions<1)return;if(!proof.operation||!["not-run","succeeded"].includes(proof.operation.state))return;const checked=proof.operation.state==="succeeded",returned=proof.operation.state==="succeeded"?proof.operation.returned:void 0;if(returned!==void 0&&(!Number.isSafeInteger(returned)||returned<0))return;const read=returned===void 0?"not-attempted":returned===0?"empty":"first-record";return{connection:"connected",availability:"actions",actions:proof.actions,operation:proof.operation.state,read,state:read==="empty"?"empty":"complete",message:read==="first-record"?"Connected and the first record has been read.":read==="empty"?"The read succeeded, but no data is currently visible.":checked?"Connected. An action completed successfully.":"Connected. Actions are available; no action has been run.",nextStep:read==="empty"?emptyHelp():"You can start using this source."}}function connectedRow(state){if(state.verification==="configuration-only")return{source:state.source,...typeof state.label==="string"?{label:state.label.slice(0,80)}:{},connection:"unknown",read:"not-attempted",state:"pending",message:"Settings saved; connection has not been verified.",nextStep:"Check the source connection and read its data."};const label=typeof state.label==="string"?state.label.slice(0,80):void 0;return{source:state.source,...label?{label}:{},connection:"connected",read:"not-attempted",state:"pending",message:"Connected. Available actions or data access have not been checked.",nextStep:"Run the readiness check for this connection.",...currentReadinessRow(state)}}function otherRow(state){const unavailable=state.state==="unavailable",[message,nextStep]=OTHER_HELP[state.source]??[`${typeof state.label==="string"?state.label:state.source} is not connected yet.`,"Continue the connection page with the available browser or computer tools."];const label=typeof state.label==="string"?state.label.slice(0,80):void 0;return{source:state.source,...label?{label}:{},connection:unavailable?"unavailable":"not-connected",read:"not-attempted",state:unavailable?"unavailable":"pending",message:unavailable&&typeof state.message==="string"&&!OTHER_HELP[state.source]?state.message.slice(0,300):message,nextStep:unavailable&&!OTHER_HELP[state.source]?"Inspect the source settings and repair the reported setup requirement before continuing.":nextStep}}function emptyHelp(_source){return"You can use this source. An empty result does not require another sign-in."}function safeUrl(source,value,ownedOrigin){try{if(typeof value!=="string"||value.length>24e3)return;const url=new URL(value);const graphDeviceSources=["onedrive","sharepoint","microsoft-planner","onenote"];const graphDeviceUrls=["https://login.microsoft.com/device","https://microsoft.com/devicelogin","https://login.microsoftonline.com/common/oauth2/deviceauth"];const routes={...Object.fromEntries(graphDeviceSources.map(source2=>[source2,graphDeviceUrls])),matrix:["https://account.matrix.org/authorize"],github:["https://github.com/login/device"],"microsoft-todo":["https://login.microsoftonline.com/common/oauth2/v2.0/authorize","https://login.microsoftonline.com/common/oauth2/deviceauth","https://microsoft.com/devicelogin"],gmail:["https://accounts.google.com/o/oauth2/v2/auth"],"google-drive":["https://accounts.google.com/o/oauth2/v2/auth"],"google-calendar":["https://accounts.google.com/o/oauth2/v2/auth"],"google-tasks":["https://accounts.google.com/o/oauth2/v2/auth"],youtube:["https://accounts.google.com/o/oauth2/v2/auth"],slack:["https://slack.com/oauth/v2/authorize"],outlook:["https://login.microsoftonline.com/common/oauth2/v2.0/authorize"],teams:["https://login.microsoftonline.com/common/oauth2/v2.0/authorize"],notion:["https://zortex-auth.pages.dev/notion/authorize","https://api.notion.com/v1/oauth/authorize"]};if(source==="whatsapp-web"&&url.protocol==="http:"&&url.hostname==="127.0.0.1"&&!url.username&&!url.password&&!url.hash&&!url.search&&/^\/[A-Za-z0-9_-]{32}$/.test(url.pathname))return url.href;if(url.protocol==="http:"&&url.hostname==="127.0.0.1"&&!url.username&&!url.password&&!url.hash&&!url.search&&/^\/connect\/[A-Za-z0-9_-]{32}$/.test(url.pathname))return url.href;if(url.protocol==="https:"&&!url.username&&!url.password&&!url.hash&&(routes[source]?.includes(url.origin+url.pathname)||ownedOrigin===url.origin)){if(source==="github"&&routes.github?.includes(url.origin+url.pathname)||(source==="microsoft-todo"||graphDeviceSources.includes(source))&&graphDeviceUrls.includes(url.origin+url.pathname))url.search="";return url.href}}catch{}return}const PAGE_GONE_MS=18e4;function seedRow(seed){const{source}=seed,setup=seed.configuration==="required",connection=setup?"unavailable":seed.connection;const positiveActions=Number.isSafeInteger(seed.actions)&&seed.actions>0;const failed=seed.read==="failed"||!!seed.errorCode||seed.availability==="none"||seed.availability==="actions"&&!positiveActions;const read=failed&&connection!=="unavailable"?"failed":connection==="connected"?seed.read:"not-attempted",actionsReady=connection==="connected"&&!failed&&seed.availability==="actions"&&positiveActions;return{source,connection,read,...seed.errorCode?{errorCode:PUBLIC_ERROR_CODES.has(seed.errorCode)?seed.errorCode:"unknown"}:{},...actionsReady?{availability:"actions",actions:seed.actions,operation:seed.operation??"not-run"}:connection==="connected"&&["first-record","empty"].includes(read)?{availability:"read",operation:"succeeded"}:{},...setup?{configuration:"required"}:{},state:connection==="unavailable"?"unavailable":actionsReady||read==="first-record"?"complete":read==="empty"?"empty":read==="failed"?"failed":"pending",message:setup?"This app still needs local setup.":connection==="unavailable"?"This source is not installed, is disabled, or is currently unavailable.":read==="first-record"?"Connected and the first record has been read.":read==="empty"?"The read succeeded, but no data is currently visible.":actionsReady?seed.operation==="succeeded"?"Connected. An action completed successfully.":"Connected. Actions are available; no action has been run.":connection==="connected"&&read==="not-attempted"&&!seed.errorCode?"Connected. Available actions or data access have not been checked.":reason(seed.errorCode,source),nextStep:actionsReady||read==="first-record"?"You can start using this source.":read==="empty"?emptyHelp():setup?"Complete this app\u2019s local setup with the available tools, then resume its connection. Other apps remain usable.":connection==="connected"?"Run the readiness check for this connection.":""}}export function startGuidedRecovery(ctx,options){const existing=sessions.get(ctx);if(existing)return existing.then(async session=>{const snapshot=session.snapshot();const changed=snapshot.sources.length!==options.sources.length||options.sources.some(seed=>{const current=snapshot.sources.find(row=>row.source===seed.source),next=seedRow(seed);return!current||["connection","read","availability","actions","operation","configuration","message"].some(key=>current[key]!==next[key])});if(snapshot.state==="closed"||!activeSources.has(ctx)&&!snapshot.sources.concat(snapshot.others).some(row=>waiting.has(row.state))&&changed){await session.close();return startGuidedRecovery(ctx,options)}return session});const pending=createSession(ctx,options).catch(error=>{sessions.delete(ctx);throw error});sessions.set(ctx,pending);return pending}async function createSession(ctx,{sources,pageGoneMs=PAGE_GONE_MS,authorization}){const providerReadinessSources=new Set;if(!Array.isArray(sources)||sources.some(row=>!safeRecoverySource(row.source))||new Set(sources.map(row=>row.source)).size!==sources.length)throw Error("Invalid recovery sources.");if(!!authorization?.status!==!!(authorization?.read||authorization?.check))throw Error("Invalid recovery owner: status and checks must use the same owner.");const rows=sources.map(seed=>{const row=seedRow(seed),label=HELP_CATALOG.find(([source])=>source===seed.source)?.[1];if(label)row.label=label;return row});for(const row of rows)if(row.read==="failed")fail(row,row.errorCode);const others=[];let initialStates;try{initialStates=authorization?.status?await authorization.status(AbortSignal.timeout(15e3)):await ctx.get("zortexConnectorHub")?.status({signal:AbortSignal.timeout(15e3)});if(initialStates&&"ok"in initialStates){for(const state of initialStates.ok)if(!rows.some(row=>row.source===state.source)&&!others.some(row=>row.source===state.source)&&safeRecoverySource(state.source))others.push(state.state==="connected"?connectedRow(state):otherRow(state))}}catch{}if(authorization?.status)for(const row of rows){const state=initialStates&&"ok"in initialStates?initialStates.ok.find(item=>item.source===row.source):void 0;row.connection=state?.verification==="configuration-only"?"unknown":state?.state??"unknown";if(state?.verification==="configuration-only"){clearReadiness(row);delete row.errorCode;row.state="pending";row.message="Settings saved; connection has not been verified.";row.nextStep="Check the source connection and read its data."}else if(row.read==="failed"&&row.connection!=="unavailable"){fail(row,row.errorCode)}else if(row.connection!=="connected"){clearReadiness(row);delete row.errorCode;row.read="not-attempted";row.state=row.connection==="unavailable"?"unavailable":"pending";row.message=row.connection==="unknown"?"Current connection status is unavailable.":reason()}}if(initialStates&&"ok"in initialStates)for(const row of[...rows,...others]){const state=initialStates.ok.find(item=>item.source===row.source);const readiness=state&¤tReadinessRow(state);if(readiness){Object.assign(row,readiness);delete row.errorCode;providerReadinessSources.add(row.source)}else if(state?.verification==="configuration-only"){row.read="not-attempted";delete row.errorCode}if(state?.registration==="deferred"){clearReadiness(row);delete row.errorCode;row.registration="deferred";row.connection="unavailable";row.read="not-attempted";row.state="unavailable";row.message="Setup is required before this connector can be used.";row.nextStep="Complete the setup with the available tools; connection continues when the configuration is active."}}const listed=new Set([...rows,...others].map(row=>row.source));for(const[entry,label]of HELP_CATALOG){const source=entry==="teams"&&!listed.has("teams")?"microsoft-teams":entry;if(!listed.has(source)){others.push({source,label,connection:"unknown",read:"not-attempted",state:"pending",catalogOnly:true,message:"This is a directory entry; registration and connection have not been checked.",nextStep:"Inspect the installed source catalog and enable or configure the source when available."});listed.add(source)}}const token=randomBytes(32).toString("base64url"),nonce=randomBytes(24).toString("base64url");let origin="",closed=false,active,activeSource,owned,settled=false,closeTask;const continuations=new Map,configured=new Set;function releaseExecution(stop){if(owned!==stop)return;owned=void 0;active=void 0;activeSource=void 0;if(activeSources.get(ctx)?.owner===token)activeSources.delete(ctx)}let resolveDone;const done=new Promise(resolve=>{resolveDone=resolve});let resolveClosed;const closedPromise=new Promise(resolve=>{resolveClosed=resolve});const expiresAt=new Date(Date.now()+18e5).toISOString();const allRows=()=>rows.concat(others);const reloads=pendingSetupReloads.get(ctx)??new Map;pendingSetupReloads.set(ctx,reloads);function acceptResidentReload(state){if(state?.reloadRequired===true)reloads.set(state.source,SETUP_RELOAD_NEXT);else if(state?.reloadRequired===false){reloads.delete(state.source);const row=allRows().find(item=>item.source===state.source);if(row)delete row.reloadRequired}}if(initialStates&&"ok"in initialStates)for(const state of initialStates.ok)acceptResidentReload(state);function retainSetupReload(row){const next=reloads.get(row.source);if(next===void 0)return false;clearHandoff(row);clearReadiness(row);row.reloadRequired=true;row.connection="unknown";row.read="not-attempted";row.state="pending";row.message="Settings saved; connection has not been verified.";row.nextStep=next;delete row.errorCode;delete row.authorizationUrl;delete row.deviceUserCode;delete row.authorizationImage;delete row.setupReason;providerReadinessSources.delete(row.source);return true}for(const row of allRows())retainSetupReload(row);async function withSetupProgress(source,stop,configure){const progress=beginRecoveryProgress(ctx,source);progress.update("configuring","unverified");const interrupted=()=>progress.finish({connectionState:"unverified",errorCode:"aborted"});stop.signal.addEventListener("abort",interrupted,{once:true});try{if(stop.signal.aborted){interrupted();return{err:{code:"aborted"}}}const result=await configure();if("ok"in result&&result.ok.state==="configured"){const row=allRows().find(item=>item.source===source);if(result.ok.reloadRequired){reloads.set(source,result.ok.next);if(row)retainSetupReload(row)}else{reloads.delete(source);configured.add(source);if(row){clearReadiness(row);delete row.reloadRequired;delete row.configuration;delete row.registration;delete row.setupReason;row.connection="unknown"}}}progress.finish({connectionState:"unverified",..."err"in result?{errorCode:result.err.code}:result.ok.state!=="configured"?{errorCode:result.ok.state==="unavailable"?"unavailable":"failed_precondition"}:result.ok.reloadRequired?{errorCode:"configuration_reload_required"}:{}});return result}catch(error){progress.finish({connectionState:"unverified",errorCode:"unknown"});throw error}finally{stop.signal.removeEventListener("abort",interrupted)}}const externalProgressSources=new Set;function applyPending(result){if(!result||!("ok"in result))return;const pending=Array.isArray(result.pending)?result.pending:[];for(const row of allRows()){if(externalProgressSources.has(row.source))continue;if(retainSetupReload(row))continue;const item=pending.find(value=>value&&value.source===row.source&&typeof value.reason==="string"&&Object.hasOwn(PENDING_HELP,value.reason));const nextReason=row.connection==="connected"?void 0:item?.reason;if(nextReason===row.setupReason)continue;if(nextReason)row.setupReason=nextReason;else delete row.setupReason;if(nextReason){[row.message,row.nextStep]=PENDING_HELP[nextReason];if(row.registration==="deferred")row.nextStep="Complete the setup with the available tools; connection continues when the configuration is active."}else if(row.catalogOnly){row.message="This is a directory entry; registration and connection have not been checked.";row.nextStep="Inspect the installed source catalog and enable or configure the source when available."}else if(row.connection!=="connected"){row.message="This source is not connected.";row.nextStep="Check the connection and try again."}}}applyPending(initialStates);function evidenceVersions(){const parts=new Map,add=(source,value)=>{parts.set(source,[...parts.get(source)??[],value])};try{const fleet=ctx.get("indraFleet");if(fleet){for(const receipt of startupHistory(fleet).receipts)for(const result of receipt.sources)add(result.source,["receipt",receipt.requestId,result.progress?.startedAt??receipt.startedAt,result.progress?.endedAt,result.state,result.returned,result.error?.code]);for(const progress of fleet.status().sources??[])add(progress.source,["progress",progress.startedAt,progress.endedAt,progress.stage,progress.returned,progress.error?.code])}for(const saved of readRecoveryEvidence(ctx,allRows().map(row=>row.source)).values())add(saved.source,["help",saved.updatedAt,saved.read,saved.returned]);for(const progress of readRecoveryProgress(ctx))add(progress.source,["manual-progress",progress.startedAt,progress.endedAt,progress.stage,progress.connectionState,progress.returned,progress.errorCode,progress.readiness])}catch{return new Map}return new Map([...parts].map(([source,values])=>[source,JSON.stringify(values)]))}const blockedEvidence=new Map,initialEvidence=evidenceVersions();for(const row of allRows())if(row.connection!=="connected")blockedEvidence.set(row.source,initialEvidence.get(row.source));let statusRefresh,lastStatusRefresh=0,interactionGeneration=0;function refreshResidentStatus(){if(active||closed||statusRefresh||Date.now()-lastStatusRefresh<5e3)return;lastStatusRefresh=Date.now();const generation=interactionGeneration;statusRefresh=(async()=>{const versions=evidenceVersions();let states;try{const signal=AbortSignal.timeout(15e3);states=await(authorization?.status?authorization.status(signal):ctx.get("zortexConnectorHub")?.status({signal}))}catch{}const evidenceContext=authorization?.status?{get:name=>name==="zortexConnectorHub"?{status:async()=>states??{err:{code:"unavailable"}}}:ctx.get(name)}:ctx;const progress=versions.size?await readOnboardingReport(evidenceContext,{enabled:true}):void 0;if(active||closed||generation!==interactionGeneration)return;const currentVersions=evidenceVersions();const manualProgress=new Map(readRecoveryProgress(ctx).map(item=>[item.source,item]));if(states&&"ok"in states){for(const state of states.ok)if(safeRecoverySource(state.source)&&!allRows().some(row=>row.source===state.source))others.push(state.state==="connected"?connectedRow(state):otherRow(state))}for(const row of allRows()){if(waiting.has(row.state)&&!externalProgressSources.has(row.source)||busy(row.source))continue;const state=states&&"ok"in states?states.ok.find(item=>item.source===row.source):void 0;acceptResidentReload(state);if(retainSetupReload(row))continue;if(row.catalogOnly&&!state)continue;if(state){delete row.catalogOnly;if(typeof state.label==="string")row.label=state.label.slice(0,80)}const deferred=state?.registration==="deferred",changedRegistration=row.registration==="deferred"!==deferred;if(deferred)row.registration="deferred";else delete row.registration;const external=manualProgress.get(row.source),version=versions.get(row.source);const stableEvidence=version!==void 0&&version===currentVersions.get(row.source);if(!deferred&&state&&external&&external.stage!=="finished"&&stableEvidence){externalProgressSources.add(row.source);blockedEvidence.set(row.source,version);clearReadiness(row);clearHandoff(row);delete row.errorCode;delete row.setupReason;row.connection=state.state;row.read="not-attempted";row.state=external.stage==="configuring"?"connecting":external.stage;row.message=external.stage==="waiting-user"?"The existing connection transaction has an active sign-in page.":external.stage==="reading"?"The current connection is being checked for readable data.":"A connection attempt is in progress.";row.nextStep="Finish the existing connection attempt; this page updates automatically.";continue}const endedExternal=externalProgressSources.delete(row.source);const readiness=state&¤tReadinessRow(state);if(readiness){Object.assign(row,readiness);delete row.errorCode;providerReadinessSources.add(row.source);delete row.setupReason;continue}const lostProviderReadiness=providerReadinessSources.delete(row.source);const next=deferred?"unavailable":state?.verification==="configuration-only"?"unknown":state?.state??(states&&"ok"in states?"unavailable":"unknown");const newEvidence=version!==void 0&&version===currentVersions.get(row.source)&&(!blockedEvidence.has(row.source)||blockedEvidence.get(row.source)!==version);if(next!=="connected"||lostProviderReadiness||row.state==="actions-ready")blockedEvidence.set(row.source,version);const evidence=progress?.sources.find(item=>item.source===row.source);if(next==="not-connected"&&newEvidence&&evidence?.read==="failed"){row.connection=next;delete row.setupReason;fail(row,evidence.errorCode);continue}if(next==="connected"&&evidence?.connection==="connected"&&version!==void 0&&version===currentVersions.get(row.source)&&(!blockedEvidence.has(row.source)||blockedEvidence.get(row.source)!==version)){blockedEvidence.delete(row.source);clearReadiness(row);clearHandoff(row);delete row.setupReason;delete row.errorCode;Object.assign(row,seedRow(evidence));if(evidence.read==="failed")fail(row,evidence.errorCode);continue}if(!endedExternal&&!lostProviderReadiness&&row.state!=="actions-ready"&&row.connection===next&&!changedRegistration&&!(state?.verification==="configuration-only"&&row.message!=="Settings saved; connection has not been verified.")&&!(next==="unknown"&&!state&&row.message==="Settings saved; connection has not been verified."))continue;row.connection=next;clearReadiness(row);clearHandoff(row);delete row.setupReason;row.read="not-attempted";delete row.errorCode;row.state=next==="unavailable"?"unavailable":"pending";row.message=deferred?"Setup is required before this connector can be used.":state?.verification==="configuration-only"?"Settings saved; connection has not been verified.":next==="connected"?"Connected. Check again to verify the current connection.":next==="unknown"?"Current connection status is unavailable.":next==="unavailable"?"This source is currently unavailable.":"This source is not connected.";row.nextStep=deferred?"Complete the setup with the available tools; connection continues when the configuration is active.":state?.verification==="configuration-only"?"Check the source connection and read its data.":next==="connected"?"Check available actions or data access.":"Check the connection and try again."}applyPending(states);complete()})().finally(()=>{statusRefresh=void 0})}const terminal=row=>["complete","empty","actions-ready"].includes(row.state)||row.state==="unavailable"&&row.configuration!=="required"&&row.registration!=="deferred"&&!row.reloadRequired;const complete=()=>{const checked=allRows().filter(row=>!row.catalogOnly);if(!settled&&checked.some(row=>["complete","empty","actions-ready"].includes(row.state))&&checked.every(terminal)){settled=true;resolveDone()}};function report(links=false){const checked=allRows().filter(row=>!row.catalogOnly);const success=checked.length>0&&checked.every(row=>["complete","empty","actions-ready"].includes(row.state)&&row.connection==="connected");const publicReads=new Map(readPublicActionProgress(ctx).map(item=>[item.source,item]));const shown=row=>{const{authorizationUrl,authorizationInstructions,deviceUserCode,authorizationImage:qrImage,authorizationExpiresAt,...safe}=row;const signInUrl=!closed&&(row.connection!=="connected"||row.errorCode==="login_required")&&["pending","failed"].includes(row.state)&&Object.hasOwn(SITE_SIGN_IN,row.source)?SITE_SIGN_IN[row.source]:void 0;const setup=recoverySetupFlags(row.source,authorization);const support=sourceSupport(row,Object.keys(setup).length>0);const publicRead=publicReads.get(row.source);const registered=!row.catalogOnly&&row.registration!=="deferred"&&row.connection!=="unavailable";const capabilities={...registered&&support.state==="supported"&&!row.reloadRequired&&!["joplin","google-chrome","microsoft-edge"].includes(row.source)&&!waiting.has(row.state)?{authorizationAvailable:true}:{},...registered&&authorization&&row.source==="gmail"?{gmailWriteAvailable:true}:{},...registered&&authorization&&row.source==="readwise"?{readwiseMcpWriteAvailable:true}:{},...registered&&supportsSavedReconnect(row.source)&&(!authorization||typeof authorization.reconnectSaved==="function")?{reconnectSavedAvailable:true}:{}};const publicRow={...safe,...setup,...capabilities,support,...publicRead?{publicRead}:{},...signInUrl?{signInUrl}:{},...links&&row.state==="waiting-user"&&authorizationInstructions?{nextStep:authorizationInstructions}:{},...links&&row.state==="waiting-user"&&qrImage?{authorizationImage:{...qrImage}}:{},...links&&row.state==="waiting-user"&&authorizationExpiresAt?{authorizationExpiresAt}:{},...links&&row.state==="waiting-user"&&authorizationUrl?{authorizationUrl,...deviceUserCode?{deviceUserCode}:{}}:{}};if(row.configuration==="required"&&support.reasonCode==="connector_unavailable"){}else if(support.state==="unsupported"){publicRow.state="unavailable";publicRow.message=support.message;publicRow.nextStep=support.nextStep}else if(row.registration==="deferred"||row.connection==="unavailable"){publicRow.message=support.message;publicRow.nextStep=support.nextStep}return publicRow};return{state:closed?"closed":success?"ready":checked.length>0&&checked.every(terminal)?"partial":"recovering",success,sources:rows.map(shown),others:others.map(shown),...activeSource?{activeSource}:{}}}function clearHandoff(row){delete row.authorizationUrl;delete row.authorizationInstructions;delete row.deviceUserCode;delete row.authorizationImage;delete row.authorizationExpiresAt}function clearReadiness(row){delete row.availability;delete row.actions;delete row.operation}function fail(row,code){clearHandoff(row);clearReadiness(row);delete row.authorizationUrl;delete row.deviceUserCode;delete row.authorizationImage;if(code)row.errorCode=PUBLIC_ERROR_CODES.has(code)?code:"unknown";else delete row.errorCode;row.state="failed";row.read="failed";if(row.source==="rednote"&&code==="unavailable"){row.message="The local RedNote service is unavailable.";row.nextStep="";return}if(row.source==="activitywatch"&&code==="unavailable"){row.message=OTHER_HELP.activitywatch[0];row.nextStep="";return}if(row.connection==="connected"&&code==="failed_precondition"&&["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(row.source)){row.message="Saved Google account access could not be verified.";row.nextStep="";return}const help=authorizationHelp(code,row.source);if(help){[row.message,row.nextStep]=help;return}row.message=reason(code,row.source);row.nextStep=""}function busy(source){return continuations.has(source)||(ctx.get("indraFleet")?.status().activeSources?.includes(source)??false)}async function run(row,stop,forceAuthorization,readOnly,repairLegacyClient=false,savedAccessOnly=false,readwiseMcpWrite=false,gmailWrite=false){const progress=beginRecoveryProgress(ctx,row.source);let returned,readiness,ownsFlow=true;const interrupted=()=>progress.finish({connectionState:row.connection==="connected"?"connected":"unverified",errorCode:"aborted"});stop.signal.addEventListener("abort",interrupted,{once:true});const hub=ctx.get("zortexConnectorHub");try{stop.signal.throwIfAborted();if(!hub){fail(row);return}const states=authorization?.status?await authorization.status(stop.signal):await hub.status({signal:stop.signal});stop.signal.throwIfAborted();if(!("ok"in states)){row.connection="unknown";fail(row);return}const state=states.ok.find(item=>item.source===row.source);if(!state||state.state==="unavailable"){row.state="unavailable";row.connection="unavailable";row.message="This source is not installed, is disabled, or is currently unavailable.";row.nextStep="Inspect the source settings and complete the available setup before resuming its connection.";return}delete row.catalogOnly;row.connection=state.state;if(readOnly&&state.state!=="connected"){fail(row,"unauthenticated");return}if(savedAccessOnly){const result2=authorization?await authorization.reconnectSaved?.(row.source,stop.signal):await hub.connect(row.source,{signal:stop.signal,retention:"transient",automatic:true,savedAccessOnly:true});if(!result2||!("ok"in result2)||result2.ok.source!==row.source||result2.ok.state!=="connected"){const code=result2&&"ok"in result2&&result2.ok.source===row.source&&result2.ok.state==="failed"?result2.ok.error?.code:void 0;fail(row,result2&&"err"in result2?result2.err.code:code??"failed_precondition");return}row.connection="connected"}else if(state.state!=="connected"||forceAuthorization){const started=Date.now(),requestId=randomUUID();let residentOwned=false;const selectAccount=forceAuthorization&&!gmailWrite&&["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(row.source);const reauthorize=forceAuthorization&&repairLegacyClient&&["todoist","linear"].includes(row.source);const settings={manualPresentation:"return-url",...gmailWrite?{gmailWrite:true}:{},...readwiseMcpWrite?{readwiseMcpWrite:true}:{},...selectAccount?{selectAccount:true}:{},...reauthorize?{reauthorize:true}:{}};const result2=authorization?await authorization.connect(row.source,requestId,stop.signal,settings):await hub.connect(row.source,{signal:stop.signal,retention:"transient",automatic:false,...settings});residentOwned=!!authorization;if(!("ok"in result2)){fail(row,"err"in result2?result2.err.code:"data_loss");return}let job=result2.ok,cancellation;const cancelResidentAuthorization=()=>{const current=job;if(!residentOwned||current.state!=="waiting-user"||!Number.isSafeInteger(current.generation)||typeof current.challengeRef!=="string"||!current.challengeRef)return;return cancellation??=authorization.cancel(requestId,current.generation,current.challengeRef).then(()=>void 0,()=>void 0)};try{stop.signal.throwIfAborted();if(!residentOwned&&job.state==="waiting-user"&&(!Number.isFinite(Date.parse(job.startedAt))||Date.parse(job.startedAt)<started)){ownsFlow=false;releaseExecution(stop);row.state="pending";row.message="Another sign-in is still waiting for authorization.";row.nextStep="Continue the existing transaction through its owning session, then check this source again.";return}const id=job.id;while(!stop.signal.aborted){if(job.id!==id||job.source!==row.source){fail(row);return}clearHandoff(row);if(job.state==="connected"){row.connection="connected";break}if(job.state!=="waiting-user"){fail(row,job.state==="cancelled"?"aborted":job.error?.code);return}if(row.source==="whatsapp-web"){row.state="waiting-user";row.message="Waiting for you to scan the QR code with WhatsApp on your phone.";row.nextStep="Settings \u2192 Linked devices \u2192 Link a device. The latest message will be read automatically after the scan. If you closed the page, use the link below to reopen it."}else{row.state="waiting-user";row.message="Authorization is in progress.";row.nextStep="Please wait. You do not need to click again."}if(typeof job.expiresAt==="string"&&Number.isFinite(Date.parse(job.expiresAt)))row.authorizationExpiresAt=new Date(job.expiresAt).toISOString();const qrImage=authorizationImage(job.authorizationImage);if(qrImage){row.authorizationImage=qrImage;if(row.source!=="whatsapp-web"){row.message="The provider returned a QR authorization challenge.";row.nextStep=""}}const url=safeUrl(row.source,job.authorizationUrl,residentOwned?job.authorizationOrigin:void 0)??reviewedRecoveryAuthorizationUrl(row.source,job)??protectedRecoveryFormUrl(row.source,job,residentOwned);if(url){row.authorizationUrl=url;const prompt=job.devicePrompt;if(prompt?.kind==="device-code"&&typeof prompt.userCode==="string"&&/^[A-Z0-9-]{4,32}$/i.test(prompt.userCode))row.deviceUserCode=prompt.userCode}if(residentOwned&&typeof job.instructions==="string"&&job.instructions.trim()&&Buffer.byteLength(job.instructions)<=2048&&!/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/u.test(job.instructions))row.authorizationInstructions=job.instructions;if(url||qrImage||row.authorizationInstructions){row.state="waiting-user";if(row.source!=="whatsapp-web"&&!qrImage){row.message="The connection page has an active sign-in or access step.";row.nextStep="Continue the live page with the available browser or computer tools. Request missing input only if those tools cannot complete the step."}}progress.update(row.state,"unverified");if(residentOwned&&job.automationActive!==true)releaseExecution(stop);try{await delay(250,void 0,{signal:stop.signal})}catch(error){await cancelResidentAuthorization();throw error}const next=authorization?await authorization.job(requestId,stop.signal):hub.job(id);if(!("ok"in next)){fail(row);return}job=next.ok}}finally{if(stop.signal.aborted)await cancelResidentAuthorization()}}while(active&&owned!==stop)await delay(50,void 0,{signal:stop.signal});stop.signal.throwIfAborted();owned=stop;activeSource=row.source;active=continuations.get(row.source)?.task;activeSources.set(ctx,{source:row.source,owner:token});clearHandoff(row);row.state="reading";row.message="Connection confirmed. Checking available actions or data access.";row.nextStep="Checking available actions or data access.";progress.update("reading","connected");const result=authorization?.check?await authorization.check(row.source,stop.signal):authorization?.read?await authorization.read(row.source,{limit:1},stop.signal).then(result2=>"ok"in result2?{ok:{source:row.source,basis:"read",operation:{state:"succeeded",returned:result2.ok.returned}}}:"empty"in result2?{ok:{source:row.source,basis:"read",operation:{state:"succeeded",returned:0}}}:result2):await hub.check(row.source,{signal:stop.signal,retention:"transient"});stop.signal.throwIfAborted();if(!("ok"in result)){fail(row,"err"in result?result.err.code:void 0);return}const check=result.ok;if(check.source!==row.source||check.basis==="actions"&&(!Number.isSafeInteger(check.actions)||check.actions<=0)){fail(row);return}if(!saveRecoveryCheck(ctx,check)){fail(row);row.message="Connection was checked, but progress could not be saved on this computer.";row.nextStep="Repair access to the data folder, then repeat the readiness check. The connection is saved.";return}readiness=check;if(check.basis==="actions"&&authorization?.status)providerReadinessSources.add(row.source);delete row.errorCode;row.availability=check.basis;row.operation=check.operation.state;if(check.basis==="actions")row.actions=check.actions;else delete row.actions;returned=check.operation.state==="succeeded"?check.operation.returned:void 0;row.read=returned===void 0?"not-attempted":returned>0?"first-record":"empty";row.state=row.read==="empty"?"empty":"complete";row.message=row.read==="first-record"?"Connected and the first record has been read.":row.read==="empty"?"The read succeeded, but no data is currently visible.":row.operation==="succeeded"?"Connected. An action completed successfully.":"Connected. Actions are available; no action has been run.";row.nextStep=row.read==="empty"?emptyHelp():"This source is ready to use."}catch{if(!closed)fail(row,stop.signal.aborted?"aborted":void 0)}finally{progress.finish({connectionState:row.connection==="connected"?"connected":"unverified",...readiness&&!stop.signal.aborted&&["complete","empty"].includes(row.state)?{readiness}:{},...returned!==void 0?{returned}:{},...["failed","unavailable","pending"].includes(row.state)?{errorCode:row.errorCode??(row.state==="unavailable"?"unavailable":"unknown")}:{}});stop.signal.removeEventListener("abort",interrupted);clearHandoff(row);releaseExecution(stop);if(ownsFlow)stop.abort();complete()}}function startRecovery(row,stop,forceAuthorization=false,readOnly=false,repairLegacyClient=false,savedAccessOnly=false,readwiseMcpWrite=false,gmailWrite=false){interactionGeneration++;owned=stop;activeSource=row.source;activeSources.set(ctx,{source:row.source,owner:token});const task=Promise.resolve().then(()=>withFeedbackFlow(row.source,()=>run(row,stop,forceAuthorization,readOnly,repairLegacyClient,savedAccessOnly,readwiseMcpWrite,gmailWrite),{flowId:randomUUID(),source:row.source,mode:"manual",trigger:"tool"})).catch(()=>{if(!closed)fail(row)}).finally(()=>{if(continuations.get(row.source)?.stop===stop)continuations.delete(row.source);releaseExecution(stop)});continuations.set(row.source,{stop,task});active=task}function finishSetup(row,stop){releaseExecution(stop);if(configured.delete(row.source)&&!closed&&!stop.signal.aborted)startRecovery(row,stop);else stop.abort()}function configureSource(response,row,configure,messages){if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row.source)){reply(response,503,{error:"save_failed"});return}const stop=new AbortController;interactionGeneration++;owned=stop;activeSource=row.source;activeSources.set(ctx,{source:row.source,owner:token});delete row.errorCode;row.state="connecting";row.read="not-attempted";row.message=messages.saving;row.nextStep="Please wait.";const failed=()=>{if(!closed){row.state="pending";row.message=messages.failed;row.nextStep=messages.retry}};active=Promise.resolve().then(()=>withSetupProgress(row.source,stop,()=>configure(stop.signal))).then(result=>{if(closed)return;row.state="pending";row.read="not-attempted";if("err"in result||result.ok.state!=="configured"){failed();return}row.message=messages.saved;row.nextStep=result.ok.next}).catch(failed).finally(()=>finishSetup(row,stop));reply(response,202,report(true))}function reply(response,status,value){response.writeHead(status,{"Content-Type":"application/json; charset=utf-8"}).end(JSON.stringify(value))}const server=createServer((request,response)=>{void handle(request,response).catch(()=>{if(!response.headersSent)reply(response,500,{error:"request_failed"});else response.end()})});let lastSeen=0;async function handle(request,response){response.setHeader("Cache-Control","no-store");response.setHeader("Referrer-Policy","no-referrer");response.setHeader("X-Content-Type-Options","nosniff");response.setHeader("Content-Security-Policy",`default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`);if(request.headers.host!==new URL(origin).host){reply(response,403,{error:"forbidden"});return}if(request.method==="GET"&&request.url==="/"){response.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}).end(recoveryLaunch(nonce));return}if(request.method!=="POST"||!["/api","/open"].includes(request.url??"")){reply(response,404,{error:"not_found"});return}const received=request.headers["x-zortex-recovery"];if(request.headers.origin!==origin||typeof received!=="string"||Buffer.byteLength(received)!==Buffer.byteLength(token)||!timingSafeEqual(Buffer.from(received),Buffer.from(token))){reply(response,403,{error:"forbidden"});return}lastSeen=Date.now();if(request.headers["content-type"]!=="application/json"){reply(response,415,{error:"json_required"});return}if(Number(request.headers["content-length"]??0)>MAX_RECOVERY_REQUEST_BYTES){request.resume();reply(response,413,{error:"too_large"});return}let bytes=0;const chunks=[];for await(const chunk of request){bytes+=chunk.length;if(bytes>MAX_RECOVERY_REQUEST_BYTES){reply(response,413,{error:"too_large"});return}chunks.push(chunk)}let body;try{body=JSON.parse(Buffer.concat(chunks).toString("utf8"))}catch{reply(response,400,{error:"invalid_request"});return}if(request.url==="/open"){if(!body||typeof body!=="object"||Array.isArray(body)||Object.keys(body).length){reply(response,400,{error:"invalid_request"});return}if(closed){reply(response,410,{error:"closed"});return}let current=session;const request2=async(input,signal)=>{if(current.snapshot().state==="closed")current=await startGuidedRecovery(ctx,{sources,pageGoneMs,...authorization?{authorization}:{}});return current.request(input,signal)};const url=await recoverySurface(ctx,{request:request2,snapshot:()=>current.snapshot(),...authorization?{authorization}:{},...sources.length===1?{source:sources[0].source}:{}});if(closed){reply(response,410,{error:"closed"});return}reply(response,200,{url});return}if(!body||typeof body!=="object"||Array.isArray(body)||Object.keys(body).some(key=>!["action","source","roots","libraryId","libraryType","port","executable","session","subdomain","region","instanceUrl","selection"].includes(key))||!["status","connect","read","authorize","authorize-readwise-mcp","authorize-gmail-write","reconnect-saved","cancel","close","discover-native-vault","configure-native-files","configure-zotero","configure-owntracks","configure-wechat","configure-joplin","configure-thunderbird","configure-proton-mail","configure-discord","configure-dropbox","configure-box","configure-front","configure-hubspot","configure-google-contacts","configure-google-chat","configure-salesforce","configure-zendesk","configure-zoom","configure-copyq","configure-freshdesk","configure-smartsheet","configure-figma","configure-nextcloud","configure-zulip","configure-freshrss","configure-miniflux","configure-mattermost","configure-wallabag","configure-calcom","configure-wakatime"].includes(String(body.action))||!["connect","read","authorize","authorize-readwise-mcp","authorize-gmail-write","reconnect-saved","cancel","discover-native-vault","configure-native-files","configure-zotero","configure-owntracks","configure-wechat","configure-joplin","configure-thunderbird","configure-proton-mail","configure-discord","configure-dropbox","configure-box","configure-front","configure-hubspot","configure-google-contacts","configure-google-chat","configure-salesforce","configure-zendesk","configure-zoom","configure-copyq","configure-freshdesk","configure-smartsheet","configure-figma","configure-nextcloud","configure-zulip","configure-freshrss","configure-miniflux","configure-mattermost","configure-wallabag","configure-calcom","configure-wakatime"].includes(String(body.action))&&body.source!==void 0||body.action!=="configure-native-files"&&body.roots!==void 0||body.action!=="configure-zotero"&&(body.libraryId!==void 0||body.libraryType!==void 0)||!["configure-owntracks","configure-wechat","configure-joplin","configure-thunderbird","configure-proton-mail"].includes(String(body.action))&&body.port!==void 0||body.action!=="configure-copyq"&&(body.executable!==void 0||body.session!==void 0)||body.action!=="configure-freshdesk"&&body.subdomain!==void 0||body.action!=="configure-smartsheet"&&body.region!==void 0||body.action!=="configure-nextcloud"&&body.instanceUrl!==void 0||!["configure-joplin","configure-discord","configure-dropbox","configure-box","configure-front","configure-hubspot","configure-google-contacts","configure-google-chat","configure-salesforce","configure-zendesk","configure-zoom","configure-figma","configure-zulip","configure-freshrss","configure-miniflux","configure-mattermost","configure-wallabag","configure-calcom","configure-wakatime"].includes(String(body.action))&&body.selection!==void 0){reply(response,400,{error:"invalid_request"});return}if(body.action==="authorize-readwise-mcp"&&(body.source!=="readwise"||Object.keys(body).length!==2)){reply(response,400,{error:"invalid_request"});return}if(body.action==="authorize-gmail-write"&&(body.source!=="gmail"||Object.keys(body).length!==2)){reply(response,400,{error:"invalid_request"});return}if(body.action==="discover-native-vault"){const row2=allRows().find(item=>item.source==="obsidian");if(Object.keys(body).length!==2||body.source!=="obsidian"||!row2||!authorization?.configureNativeFiles){reply(response,400,{error:"invalid_request"});return}if(closed){reply(response,410,{error:"closed"});return}const result=await discoverNativeVaultCandidates("obsidian");if(closed){reply(response,410,{error:"closed"});return}reply(response,200,{state:result.state,candidates:result.candidates.filter(path=>path.length<=512)});return}if(body.action==="status"){refreshResidentStatus();reply(response,200,report(true));return}if(body.action==="close"){reply(response,200,{...report(),state:"closed"});setImmediate(()=>{void session.close()});return}if(body.action==="cancel"){const row2=allRows().find(item=>item.source===body.source),continuation=typeof body.source==="string"?continuations.get(body.source):void 0,current=continuation?.task??active,cancelStop=continuation?.stop??owned;if(!row2){reply(response,400,{error:"unknown_source"});return}if(closed){reply(response,410,{error:"closed"});return}if(!current||!continuation&&activeSource!==row2.source||!cancelStop){reply(response,409,{error:"verification_not_active",activeSource:activeSource??activeSources.get(ctx)?.source});return}row2.message="Cancelling verification.";row2.nextStep="Please wait.";cancelStop.abort();let finished=false;await Promise.race([current.then(()=>{finished=true}),delay(5e3)]);if(finished&&!closed){row2.state="failed";row2.read="not-attempted";row2.errorCode="aborted";row2.message="Verification was cancelled. You can choose another source.";row2.nextStep="Choose Connect when you are ready to try again."}reply(response,finished?200:202,report(true));return}if(body.action==="configure-zulip"){const row2=allRows().find(item=>item.source==="zulip");if(!authorization?.configureZulip||!row2||body.source!=="zulip"||!validZulipSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureZulip(body.selection,signal),{saving:"Saving the Zulip instance URL and email.",saved:"Zulip instance URL and email saved. The current connection has not been verified.",failed:"The Zulip setup could not be saved.",retry:"Check the instance URL and email and try again."});return}if(body.action==="configure-freshrss"){const row2=allRows().find(item=>item.source==="freshrss");if(!authorization?.configureFreshRSS||!row2||body.source!=="freshrss"||!validFreshRSSSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureFreshRSS(body.selection,signal),{saving:"Saving the FreshRSS instance URL and username.",saved:"FreshRSS instance URL and username saved. The current connection has not been verified.",failed:"The FreshRSS setup could not be saved.",retry:"Check the instance URL and username and try again."});return}if(body.action==="configure-miniflux"){const row2=allRows().find(item=>item.source==="miniflux");if(!authorization?.configureMiniflux||!row2||body.source!=="miniflux"||!validMinifluxSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureMiniflux(body.selection,signal),{saving:"Saving the Miniflux instance URL and username.",saved:"Miniflux instance URL and username saved. The current connection has not been verified.",failed:"The Miniflux setup could not be saved.",retry:"Check the instance URL and username and try again."});return}if(body.action==="configure-mattermost"){const row2=allRows().find(item=>item.source==="mattermost");if(!authorization?.configureMattermost||!row2||body.source!=="mattermost"||!validMattermostSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureMattermost(body.selection,signal),{saving:"Saving the Mattermost instance URL and username.",saved:"Mattermost instance URL and username saved. The current connection has not been verified.",failed:"The Mattermost setup could not be saved.",retry:"Check the instance URL and username and try again."});return}if(body.action==="configure-wallabag"){const row2=allRows().find(item=>item.source==="wallabag");if(!authorization?.configureWallabag||!row2||body.source!=="wallabag"||!validWallabagSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureWallabag(body.selection,signal),{saving:"Saving the Wallabag instance URL and username.",saved:"Wallabag instance URL and username saved. The current connection has not been verified.",failed:"The Wallabag setup could not be saved.",retry:"Check the instance URL and username and try again."});return}if(body.action==="configure-calcom"){const row2=allRows().find(item=>item.source==="calcom");if(!authorization?.configureCalcom||!row2||body.source!=="calcom"||!validCalcomSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureCalcom(body.selection,signal),{saving:"Saving the Cal.com username.",saved:"Cal.com username saved. The current connection has not been verified.",failed:"The Cal.com setup could not be saved.",retry:"Check the username and try again."});return}if(body.action==="configure-wakatime"){const row2=allRows().find(item=>item.source==="wakatime");if(!authorization?.configureWakatime||!row2||body.source!=="wakatime"||!validWakatimeSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureWakatime(body.selection,signal),{saving:"Saving the WakaTime username or account ID.",saved:"WakaTime username or account ID saved. The current connection has not been verified.",failed:"The WakaTime setup could not be saved.",retry:"Check the username and try again."});return}if(body.action==="configure-nextcloud"){const row2=allRows().find(item=>item.source==="nextcloud");if(!authorization?.configureNextcloud||!row2||body.source!=="nextcloud"||!validNextcloudInstanceUrl(body.instanceUrl)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureNextcloud(body.instanceUrl,signal),{saving:"Saving the Nextcloud instance URL.",saved:"Nextcloud instance URL saved. The current connection has not been verified.",failed:"The Nextcloud setup could not be saved.",retry:"Check the instance URL and try again."});return}if(body.action==="configure-smartsheet"){const row2=allRows().find(item=>item.source==="smartsheet");if(!authorization?.configureSmartsheet||!row2||body.source!=="smartsheet"||typeof body.region!=="string"||!["us","eu","au"].includes(body.region)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureSmartsheet(body.region,signal),{saving:"Saving the Smartsheet region.",saved:"Smartsheet region saved. The current connection has not been verified.",failed:"The Smartsheet setup could not be saved.",retry:"Check the region and try again."});return}if(body.action==="configure-figma"){const row2=allRows().find(item=>item.source==="figma");if(!authorization?.configureFigma||!row2||body.source!=="figma"||!["fields","oauth"].includes(String(body.selection))){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureFigma(body.selection,signal),{saving:"Saving the Figma personal access token mode.",saved:"Figma connection mode saved. The current connection has not been verified.",failed:"The Figma setup could not be saved.",retry:"Check the personal access token mode and try again."});return}if(body.action==="configure-freshdesk"){const row2=allRows().find(item=>item.source==="freshdesk");if(!authorization?.configureFreshdesk||!row2||body.source!=="freshdesk"||typeof body.subdomain!=="string"||!/^(?:[a-z0-9]|[a-z0-9][a-z0-9-]{0,61}[a-z0-9])$/.test(body.subdomain)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureFreshdesk(body.subdomain,signal),{saving:"Saving the Freshdesk tenant.",saved:"Freshdesk tenant saved. The current connection has not been verified.",failed:"The Freshdesk setup could not be saved.",retry:"Check the tenant name and try again."});return}if(body.action==="configure-wechat"){const row2=allRows().find(item=>item.source==="wechat");if(!authorization?.configureWeChat||!row2||body.source!=="wechat"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureWeChat(body.port,signal),{saving:"Saving the WeChat local port.",saved:"WeChat setup saved. The current connection has not been verified.",failed:"The WeChat setup could not be saved.",retry:"Check the local port and try again."});return}if(body.action==="configure-joplin"){const row2=allRows().find(item=>item.source==="joplin");try{if(!authorization?.configureJoplin||!row2||body.source!=="joplin"||body.port!==void 0)throw Error();validateJoplinSelection(body.selection)}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy("joplin")){reply(response,409,{error:"connection_in_progress"});return}const selection=body.selection;if("phase"in selection&&selection.phase==="confirm"&&!invalidateRecoveryEvidence(ctx,"joplin")){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;owned=stop2;interactionGeneration++;activeSource="joplin";activeSources.set(ctx,{source:"joplin",owner:token});const disconnect=()=>{if(!response.writableEnded)stop2.abort()};response.once("close",disconnect);let result={err:{code:"invalid_setup_result"}};active=Promise.resolve().then(async()=>{result=validateJoplinResult(await withSetupProgress("joplin",stop2,()=>authorization.configureJoplin(selection,stop2.signal)))}).catch(()=>{result={err:{code:"pairing_failed"}}}).finally(()=>{response.removeListener("close",disconnect);releaseExecution(stop2)});await active;if(closed||response.destroyed)return;if("err"in result){reply(response,400,{error:"pairing_failed"});return}const pairing=result.ok;if(pairing.state==="configured"){row2.state="pending";row2.read="not-attempted";row2.message="Joplin paired. Note access has not been checked.";row2.nextStep=pairing.next;if(pairing.reloadRequired)reloads.set("joplin",pairing.next)}reply(response,200,{pairing});if(pairing.state==="configured")finishSetup(row2,stop2);return}if(body.action==="configure-thunderbird"){const row2=allRows().find(item=>item.source==="thunderbird");if(!authorization?.configureThunderbird||!row2||body.source!=="thunderbird"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureThunderbird(body.port,signal),{saving:"Saving the Thunderbird local port.",saved:"Thunderbird setup saved. The current connection has not been verified.",failed:"The Thunderbird setup could not be saved.",retry:"Check the local port and try again."});return}if(body.action==="configure-dropbox"){const row2=allRows().find(item=>item.source==="dropbox");try{const v=body.selection;if(!authorization?.configureDropbox||!row2||body.source!=="dropbox"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedServiceSource("dropbox",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureDropbox(body.selection,signal),{saving:"Saving Dropbox selection.",saved:"Dropbox setup saved. The current connection has not been verified.",failed:"The Dropbox setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-box"){const row2=allRows().find(item=>item.source==="box");try{const v=body.selection;if(!authorization?.configureBox||!row2||body.source!=="box"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedServiceSource("box",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureBox(body.selection,signal),{saving:"Saving Box selection.",saved:"Box setup saved. The current connection has not been verified.",failed:"The Box setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-front"){const row2=allRows().find(item=>item.source==="front");try{const v=body.selection;if(!authorization?.configureFront||!row2||body.source!=="front"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedWorkSource("front",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureFront(body.selection,signal),{saving:"Saving Front selection.",saved:"Front setup saved. The current connection has not been verified.",failed:"The Front setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-hubspot"){const row2=allRows().find(item=>item.source==="hubspot");try{const v=body.selection;if(!authorization?.configureHubSpot||!row2||body.source!=="hubspot"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedWorkSource("hubspot",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureHubSpot(body.selection,signal),{saving:"Saving HubSpot selection.",saved:"HubSpot setup saved. The current connection has not been verified.",failed:"The HubSpot setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-google-contacts"){const row2=allRows().find(item=>item.source==="google-contacts");try{const v=body.selection;if(!authorization?.configureGoogleContacts||!row2||body.source!=="google-contacts"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key)))throw Error("invalid");createPreparedServiceSource("google-contacts",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureGoogleContacts(body.selection,signal),{saving:"Saving Google Contacts selection.",saved:"Google Contacts setup saved. The current connection has not been verified.",failed:"The Google Contacts setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-google-chat"){const row2=allRows().find(item=>item.source==="google-chat");try{const v=body.selection;if(!authorization?.configureGoogleChat||!row2||body.source!=="google-chat"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key)))throw Error("invalid");createPreparedServiceSource("google-chat",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureGoogleChat(body.selection,signal),{saving:"Saving Google Chat selection.",saved:"Google Chat setup saved. The current connection has not been verified.",failed:"The Google Chat setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-salesforce"){const row2=allRows().find(item=>item.source==="salesforce");try{const v=body.selection;if(!authorization?.configureSalesforce||!row2||body.source!=="salesforce"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["environment","clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedWorkSource("salesforce",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureSalesforce(body.selection,signal),{saving:"Saving Salesforce selection.",saved:"Salesforce setup saved. The current connection has not been verified.",failed:"The Salesforce setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-zendesk"){const row2=allRows().find(item=>item.source==="zendesk");if(!authorization?.configureZendesk||!row2||body.source!=="zendesk"||!validZendeskSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureZendesk(body.selection,signal),{saving:"Saving Zendesk selection.",saved:"Zendesk setup saved. The current connection has not been verified.",failed:"The Zendesk setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-zoom"){const row2=allRows().find(item=>item.source==="zoom");try{const v=body.selection;if(!authorization?.configureZoom||!row2||body.source!=="zoom"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId"].includes(key)))throw Error("invalid");createPreparedServiceSource("zoom",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureZoom(body.selection,signal),{saving:"Saving Zoom selection.",saved:"Zoom setup saved. The current connection has not been verified.",failed:"The Zoom setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-discord"){const row2=allRows().find(item=>item.source==="discord");try{const v=body.selection;if(!authorization?.configureDiscord||!row2||body.source!=="discord"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","expectedSubject","ipcPath","channelIds"].includes(key)))throw Error("invalid");createPreparedDiscordSource("discord",{mode:"fields",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureDiscord(body.selection,signal),{saving:"Saving Discord selection.",saved:"Discord setup saved. The current connection has not been verified.",failed:"The Discord setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-proton-mail"){const row2=allRows().find(item=>item.source==="proton-mail");if(!authorization?.configureProtonMail||!row2||body.source!=="proton-mail"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureProtonMail(body.port,signal),{saving:"Saving the Proton Mail local port.",saved:"Proton Mail setup saved. The current connection has not been verified.",failed:"The Proton Mail setup could not be saved.",retry:"Check the local port and try again."});return}if(body.action==="configure-copyq"){const row2=allRows().find(item=>item.source==="copyq");if(!authorization?.configureCopyQ||!row2||body.source!=="copyq"||typeof body.executable!=="string"||body.executable.length<1||body.executable.length>512||body.executable.includes("\0")||!isAbsolute(body.executable)||typeof body.session!=="string"||!/^[\p{L}\p{N}_-]{0,16}$/u.test(body.session)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureCopyQ(body.executable,body.session,signal),{saving:"Saving the CopyQ application and session.",saved:"CopyQ setup saved. The current connection has not been verified.",failed:"The CopyQ setup could not be saved.",retry:"Check the application path and session and try again."});return}if(body.action==="configure-owntracks"){const row2=allRows().find(item=>item.source==="owntracks");if(!authorization?.configureOwnTracks||!row2||body.source!=="owntracks"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureOwnTracks(body.port,signal),{saving:"Saving the OwnTracks local port.",saved:"OwnTracks setup saved. The current connection has not been verified.",failed:"The OwnTracks setup could not be saved.",retry:"Check the local port and try again."});return}if(body.action==="configure-zotero"){const row2=allRows().find(item=>item.source==="zotero");if(!authorization?.configureZotero||!row2||body.source!=="zotero"||typeof body.libraryId!=="string"||!(/^[1-9][0-9]{0,19}$/.test(body.libraryId)||body.libraryType==="user"&&body.libraryId==="0")||!["user","group"].includes(String(body.libraryType))){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Zotero library selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureZotero(body.libraryId,body.libraryType,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Zotero selection could not be saved.";row2.nextStep="Check the library ID and local setup, then try again.";return}row2.message="Zotero selection saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Zotero selection could not be saved.";row2.nextStep="Check the local setup, then try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-native-files"){const row2=allRows().find(item=>item.source===body.source),roots=body.roots;if(!authorization?.configureNativeFiles||!row2||typeof body.source!=="string"||!NATIVE_FILE_SOURCES.has(body.source)||!Array.isArray(roots)||roots.length!==1||typeof roots[0]!=="string"||roots[0].length<1||roots[0].length>512||roots[0].includes("\0")||!isAbsolute(roots[0])){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){row2.message="Progress could not be saved on this computer. The folder selection has not been saved.";row2.nextStep="Check that the data folder is writable, then try again.";reply(response,503,report());return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the folder selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureNativeFiles(row2.source,roots,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result){row2.message="The folder selection could not be saved.";row2.nextStep="Check that the folder exists and is accessible, then try again.";return}if(result.ok.state!=="configured"){row2.message="The folder selection needs further setup.";row2.nextStep="Check the folder and its permissions, then try again.";return}row2.message="Folder selection saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The folder selection could not be saved.";row2.nextStep="Check that the folder exists and is accessible, then try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}const pendingReload=allRows().find(item=>item.source===body.source);if(pendingReload&&reloads.has(pendingReload.source)&&!closed&&!active){retainSetupReload(pendingReload);reply(response,200,report(true));return}const other=others.find(item=>item.source===body.source),row=rows.find(item=>item.source===body.source)??(other&&!other.catalogOnly&&connectableOther(other)&&["connect","read","authorize","authorize-readwise-mcp","authorize-gmail-write","reconnect-saved"].includes(body.action)?other:void 0);if(!row||row.source==="joplin"&&body.action!=="read"||row.registration==="deferred"){reply(response,400,{error:"unknown_source"});return}if(closed){reply(response,410,{error:"closed"});return}if(continuations.has(row.source)){reply(response,200,report(true));return}if(active){reply(response,activeSource===row.source?200:409,activeSource===row.source?report(true):{error:"connection_in_progress",activeSource});return}if(activeSources.has(ctx)){reply(response,409,{error:"connection_in_progress",activeSource:activeSources.get(ctx)?.source});return}if(busy(row.source)){reply(response,409,{error:"connection_in_progress",activeSource:row.source});return}if(row.state==="unavailable"){reply(response,409,{error:"source_unavailable"});return}if(body.action==="reconnect-saved"&&!supportsSavedReconnect(row.source)){reply(response,400,{error:"saved_reconnect_unsupported"});return}if(body.action==="authorize"&&["google-chrome","microsoft-edge"].includes(row.source)){reply(response,400,{error:"authorization_not_supported"});return}if(!invalidateRecoveryEvidence(ctx,row.source)){fail(row);row.message="Progress could not be saved on this computer. A new connection has not been started.";row.nextStep="Check that the data folder is writable, then try again.";reply(response,503,report());return}const repairLegacyClient=row.errorCode==="authorization_client_registration_required";const stop=new AbortController;interactionGeneration++;owned=stop;activeSource=row.source;activeSources.set(ctx,{source:row.source,owner:token});delete row.errorCode;row.state="connecting";row.read="not-attempted";row.message="Preparing to connect.";if(!other)row.nextStep="Please wait. You do not need to click again.";startRecovery(row,stop,body.action==="authorize"||body.action==="authorize-readwise-mcp"||body.action==="authorize-gmail-write",body.action==="read",repairLegacyClient,body.action==="reconnect-saved",body.action==="authorize-readwise-mcp",body.action==="authorize-gmail-write");reply(response,202,report(true))}server.requestTimeout=5e3;server.headersTimeout=5e3;server.keepAliveTimeout=1e3;await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error("Recovery listener unavailable.");origin=`http://127.0.0.1:${address.port}`;const timer=setTimeout(()=>{void session.close()},18e5);timer.unref();const gone=setInterval(()=>{if(lastSeen&&!active&&!continuations.size&&Date.now()-lastSeen>pageGoneMs)void session.close()},Math.min(15e3,Math.max(50,pageGoneMs/4)));gone.unref();const session={url:origin+"/#"+token,expiresAt,done,closed:closedPromise,snapshot:()=>report(),async request(input,signal){if(closed)return{status:410,body:{error:"closed"}};let body;try{body=JSON.stringify(input);if(typeof body!=="string")throw Error()}catch{return{status:400,body:{error:"invalid_request"}}}if(Buffer.byteLength(body)>MAX_RECOVERY_REQUEST_BYTES)return{status:413,body:{error:"too_large"}};const response=await fetch(origin+"/api",{method:"POST",redirect:"error",headers:{Origin:origin,"Content-Type":"application/json","X-Zortex-Recovery":token},body,signal});return{status:response.status,body:await response.json()}},close(){return closeTask??=(async()=>{closed=true;clearTimeout(timer);clearInterval(gone);owned?.abort();for(const pending of continuations.values())pending.stop.abort();for(const row of allRows()){clearHandoff(row);if(waiting.has(row.state)){row.state="pending";row.message="This connection session has ended.";row.nextStep=""}}server.closeAllConnections();await new Promise(resolve=>server.close(()=>resolve()));let waitTimer;await Promise.race([Promise.all([active,...[...continuations.values()].map(item=>item.task)]),new Promise(resolve=>{waitTimer=setTimeout(resolve,1e3)})]);if(waitTimer)clearTimeout(waitTimer);if(!active&&activeSources.get(ctx)?.owner===token)activeSources.delete(ctx);sessions.delete(ctx);if(!settled){settled=true;resolveDone()}resolveClosed()})()}};ctx.effect(()=>()=>session.close());complete();return session}
|
|
1
|
+
import{supportsSavedReconnect}from"./saved-reconnect.js";import{validZendeskSelection}from"./zendesk-selection.js";import{validateJoplinSelection,validateJoplinResult}from"./joplin-selection.js";import{SETUP_RELOAD_NEXT}from"./setup-activation.js";import{createPreparedDiscordSource,createPreparedServiceSource,createPreparedWorkSource}from"@zortexhq/plugin-connector-level1";import{validZulipSelection}from"./zulip-selection.js";import{validFreshRSSSelection}from"./freshrss-selection.js";import{validMinifluxSelection}from"./miniflux-selection.js";import{validMattermostSelection}from"./mattermost-selection.js";import{validWallabagSelection}from"./wallabag-selection.js";import{validCalcomSelection}from"./calcom-selection.js";import{validWakatimeSelection}from"./wakatime-selection.js";import{validNextcloudInstanceUrl}from"./nextcloud-url.js";import{authorizationImage}from"@zortexhq/plugin-connector-core/api";import{createServer}from"node:http";import{randomBytes,randomUUID,timingSafeEqual}from"node:crypto";import{setTimeout as delay}from"node:timers/promises";import{isAbsolute}from"node:path";import{withFeedbackFlow}from"@zortexhq/plugin-telemetry/api";import{startupHistory}from"./startup.js";import{readOnboardingReport}from"./onboarding.js";import{HELP_CATALOG}from"./source-catalog.js";import{recoveryLaunch}from"./recovery-launch.js";import{recoverySurface}from"./recovery-surface.js";import{sourceSupport,recoverySetupFlags}from"./recovery-support.js";import{protectedRecoveryFormUrl,reviewedRecoveryAuthorizationUrl,nativeRecoveryAuthorizationUrl}from"./recovery-authorization-url.js";import{discoverNativeVaultCandidates}from"./native-vault-discovery.js";import{readRecoveryEvidence,saveRecoveryCheck,invalidateRecoveryEvidence,safeRecoverySource}from"./recovery-evidence.js";import{readPublicActionProgress}from"./public-action-progress.js";import{beginRecoveryProgress,readRecoveryProgress,readCurrentRecoveryProgress,recoveryAuthorityProof}from"./recovery-progress.js";export async function keepRecoverySurfaceOpen(session,opened,signal){if(opened&&!signal.aborted&&session.snapshot().state!=="closed")await session.closed}const NATIVE_FILE_SOURCES=new Set(["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","local-audio","obsidian","logseq","computer-files"]);const MAX_RECOVERY_REQUEST_BYTES=64*1024;const PUBLIC_ERROR_CODES=new Set(["unknown","account_identity_unavailable","aborted","interrupted","unavailable","failed_precondition","permission_denied","unauthenticated","not_found","data_loss","deadline_exceeded","resource_exhausted","authorization_timeout","authorization_denied","google_connection_failed","login_required","qr_scan_required","pairing_timeout","notion_page_selection_required","credentials_required","authorization_client_registration_failed","authorization_client_registration_required","authorization_callback_unavailable","authorization_callback_rejected","authorization_token_exchange_failed","authorization_credential_validation_failed","authorization_scope_mismatch","authorization_credential_storage_failed","authorization_registration_unavailable","authorization_client_configuration_required","configuration_reload_required","authorization_https_redirect_required","device_authorization_unavailable"]);const PENDING_HELP={"configuration-required":["This source needs configuration before it can be registered.","Complete this app\u2019s local setup with the available tools, then resume its connection. Other apps remain usable."],"authorization-required":["This source needs authorization before it can be registered.","Continue enrollment with the available browser or computer tools."],"ambiguous-account":["More than one account could be used for this source.","Use the task context and saved binding to identify the account, then continue connecting."],"ambiguous-resource":["More than one data resource could be used for this source.","Inspect the source configuration and saved account binding, repair the reported prerequisite and continue. Existing data and credentials are preserved."],"custody-unavailable":["The source authorization store is unavailable.","Inspect the source configuration and saved account binding, repair the reported prerequisite and continue. Existing data and credentials are preserved."]};export function validateNativeFileResult(source,result){if(result&&typeof result==="object"&&"ok"in result){const value=result.ok;if(value&&typeof value==="object"&&"source"in value&&value.source===source&&"state"in value&&typeof value.state==="string"&&["configured","configuration-required","permission-required","unavailable"].includes(value.state)&&"reloadRequired"in value&&typeof value.reloadRequired==="boolean"&&"next"in value&&typeof value.next==="string"&&(!("enabled"in value)||typeof value.enabled==="boolean"))return{ok:value}}if(result&&typeof result==="object"&&"err"in result&&result.err&&typeof result.err==="object"&&"code"in result.err&&typeof result.err.code==="string")return{err:{code:result.err.code}};return{err:{code:"invalid_resident_response"}}}const sessions=new WeakMap;const pendingSetupReloads=new WeakMap;const activeSources=new WeakMap;export function activeRecoverySource(ctx){return activeSources.get(ctx)?.source}const waiting=new Set(["connecting","waiting-user","reading"]);function authorizationHelp(code,_source){if(code==="failed_precondition")return["The connection prerequisites could not be verified.","Inspect the source configuration and saved account binding, repair the reported prerequisite and continue. Existing data and credentials are preserved."];if(code==="authorization_callback_unavailable")return["The saved authorization callback is already in use. Existing credentials are preserved.","Inspect the existing callback owner and continue that transaction. Start a replacement only after the previous owner has settled."];if(code==="authorization_client_registration_required")return["A new authorization cannot start with this installation\u2019s saved OAuth client. Existing credentials are preserved.","Repair the saved OAuth client\u2019s missing or incompatible callback details, then continue connecting."];if(code==="configuration_reload_required")return["Settings saved; connection has not been verified.",SETUP_RELOAD_NEXT];if(code==="authorization_client_configuration_required")return["This provider requires an OAuth client configuration that this connector does not currently have. No sign-in link was created.","Configure a supported OAuth client or connection service with the available setup tools, then resume this source."];if(code==="authorization_client_registration_failed")return["The provider could not register this installation\u2019s OAuth client. No sign-in link was created.","Repair the provider registration endpoint or client settings, then resume enrollment."];if(code==="authorization_registration_unavailable")return["This provider has no supported OAuth client registration configured. No sign-in link was created.","Configure a supported OAuth client through the available setup path, then resume enrollment."];if(code==="authorization_https_redirect_required")return["This provider requires an HTTPS callback that this local connection flow does not provide.","Configure the connector\u2019s supported HTTPS callback path before resuming enrollment."];if(code==="device_authorization_unavailable")return["The provider did not return a usable device authorization challenge. No sign-in code is available.","Repair the device authorization endpoint or client settings, then request a new challenge."];if(code==="credentials_required")return["This source needs credentials entered on its protected local connection page.","Use the protected local connection page and configured credential source. Request missing credential input only when the available tools cannot supply it; keep credentials out of chat."]}function reason(code,source){const help=authorizationHelp(code,source);if(help)return help[0];if(code==="authorization_denied"||code==="aborted"||code==="interrupted")return"Sign-in or authorization was not completed.";if(code==="authorization_timeout"||code==="deadline_exceeded")return"Authorization timed out. The previous link has expired.";if(code==="permission_denied")return"The current authorization does not include the required permissions.";if(code==="account_identity_unavailable")return"Zortex could not verify which account is signed in to this app.";if(code==="login_required")return"The provider reported that a signed-in session is required.";if(code==="qr_scan_required")return"WhatsApp needs a one-time QR scan from your phone.";if(code==="pairing_timeout")return"The WhatsApp QR code was not scanned in time.";return"Connection or reading did not finish. Your data and existing connections are saved."}const SITE_SIGN_IN=Object.freeze({x:"https://x.com/i/flow/login",instagram:"https://www.instagram.com/accounts/login/",linkedin:"https://www.linkedin.com/login",steam:"https://steamcommunity.com/login/home/",reddit:"https://www.reddit.com/login/",spotify:"https://accounts.spotify.com/login"});export function connectableOther(row){return row.state!=="unavailable"}const OTHER_HELP={steam:["Steam is not connected yet.","Continue Steam Community sign-in with the available browser tools, then check its profile read."],reddit:["Reddit is not connected yet.","Continue Reddit sign-in with the available browser tools, then check its read."],spotify:["Spotify is not connected yet.","Continue Spotify Web sign-in with the available browser tools, then check its read."],"google-tasks":["Google Tasks has not been verified on this computer yet.","Reuse the saved Google connection or continue sign-in with the available tools, then check Tasks."],"netease-mail":["NetEase Mail needs an IMAP authorization code.","Use the available mail settings and protected connection page to configure IMAP, then continue enrollment. Request the code only if it cannot be obtained through available tools."],notebooklm:["NotebookLM needs a Google sign-in in its connection browser.","Continue the Google connection page with the available browser or computer tools."],stripe:["Stripe needs a provider connection.","Complete the requested connection on Stripe\u2019s page with the available browser tools."],openrouter:["OpenRouter needs a provider connection.","Complete the requested connection on OpenRouter\u2019s page with the available browser tools."],calendly:["Calendly has not been verified on this computer yet.","Reuse the saved connection or continue Calendly sign-in with the available tools, then check its Actions."],shopify:["Shopify needs store and application configuration.","Find the requested store and configure its application through the available provider tools, then continue on the protected local connection page."],activitywatch:["ActivityWatch needs its local service running on this computer.","Start or repair the local ActivityWatch service with the available computer tools, then verify the source read."]};function currentReadinessRow(state){const proof=state.readiness;if(state.state!=="connected"||state.verification||state.registration||!proof||!Number.isSafeInteger(proof.actions)||proof.actions<1)return;if(!proof.operation||!["not-run","succeeded"].includes(proof.operation.state))return;const checked=proof.operation.state==="succeeded",returned=proof.operation.state==="succeeded"?proof.operation.returned:void 0;if(returned!==void 0&&(!Number.isSafeInteger(returned)||returned<0))return;const read=returned===void 0?"not-attempted":returned===0?"empty":"first-record";return{connection:"connected",availability:"actions",actions:proof.actions,operation:proof.operation.state,read,state:read==="empty"?"empty":"complete",message:read==="first-record"?"Connected and the first record has been read.":read==="empty"?"The read succeeded, but no data is currently visible.":checked?"Connected. An action completed successfully.":"Connected. Actions are available; no action has been run.",nextStep:read==="empty"?emptyHelp():"You can start using this source."}}function connectedRow(state){if(state.verification==="configuration-only")return{source:state.source,...typeof state.label==="string"?{label:state.label.slice(0,80)}:{},connection:"unknown",read:"not-attempted",state:"pending",message:"Settings saved; connection has not been verified.",nextStep:"Check the source connection and read its data."};const label=typeof state.label==="string"?state.label.slice(0,80):void 0;return{source:state.source,...label?{label}:{},connection:"connected",read:"not-attempted",state:"pending",message:"Connected. Available actions or data access have not been checked.",nextStep:"Run the readiness check for this connection.",...currentReadinessRow(state)}}function otherRow(state){const unavailable=state.state==="unavailable",[message,nextStep]=OTHER_HELP[state.source]??[`${typeof state.label==="string"?state.label:state.source} is not connected yet.`,"Continue the connection page with the available browser or computer tools."];const label=typeof state.label==="string"?state.label.slice(0,80):void 0;return{source:state.source,...label?{label}:{},connection:unavailable?"unavailable":"not-connected",read:"not-attempted",state:unavailable?"unavailable":"pending",message:unavailable&&typeof state.message==="string"&&!OTHER_HELP[state.source]?state.message.slice(0,300):message,nextStep:unavailable&&!OTHER_HELP[state.source]?"Inspect the source settings and repair the reported setup requirement before continuing.":nextStep}}function emptyHelp(_source){return"You can use this source. An empty result does not require another sign-in."}const PAGE_GONE_MS=18e4;function seedRow(seed){const{source}=seed,setup=seed.configuration==="required",connection=setup?"unavailable":seed.connection;const positiveActions=Number.isSafeInteger(seed.actions)&&seed.actions>0;const failed=seed.read==="failed"||!!seed.errorCode||seed.availability==="none"||seed.availability==="actions"&&!positiveActions;const read=failed&&connection!=="unavailable"?"failed":connection==="connected"?seed.read:"not-attempted",actionsReady=connection==="connected"&&!failed&&seed.availability==="actions"&&positiveActions;return{source,connection,read,...seed.errorCode?{errorCode:PUBLIC_ERROR_CODES.has(seed.errorCode)?seed.errorCode:"unknown"}:{},...actionsReady?{availability:"actions",actions:seed.actions,operation:seed.operation??"not-run"}:connection==="connected"&&["first-record","empty"].includes(read)?{availability:"read",operation:"succeeded"}:{},...setup?{configuration:"required"}:{},state:connection==="unavailable"?"unavailable":actionsReady||read==="first-record"?"complete":read==="empty"?"empty":read==="failed"?"failed":"pending",message:setup?"This app still needs local setup.":connection==="unavailable"?"This source is not installed, is disabled, or is currently unavailable.":read==="first-record"?"Connected and the first record has been read.":read==="empty"?"The read succeeded, but no data is currently visible.":actionsReady?seed.operation==="succeeded"?"Connected. An action completed successfully.":"Connected. Actions are available; no action has been run.":connection==="connected"&&read==="not-attempted"&&!seed.errorCode?"Connected. Available actions or data access have not been checked.":reason(seed.errorCode,source),nextStep:actionsReady||read==="first-record"?"You can start using this source.":read==="empty"?emptyHelp():setup?"Complete this app\u2019s local setup with the available tools, then resume its connection. Other apps remain usable.":connection==="connected"?"Run the readiness check for this connection.":""}}export function startGuidedRecovery(ctx,options){const existing=sessions.get(ctx);if(existing)return existing.then(async session=>{const snapshot=session.snapshot();const changed=snapshot.sources.length!==options.sources.length||options.sources.some(seed=>{const current=snapshot.sources.find(row=>row.source===seed.source),next=seedRow(seed);return!current||["connection","read","availability","actions","operation","configuration","message"].some(key=>current[key]!==next[key])});if(snapshot.state==="closed"||!activeSources.has(ctx)&&!snapshot.sources.concat(snapshot.others).some(row=>waiting.has(row.state))&&changed){await session.close();return startGuidedRecovery(ctx,options)}return session});const pending=createSession(ctx,options).catch(error=>{sessions.delete(ctx);throw error});sessions.set(ctx,pending);return pending}async function createSession(ctx,{sources,pageGoneMs=PAGE_GONE_MS,authorization}){const providerReadinessSources=new Set;if(!Array.isArray(sources)||sources.some(row=>!safeRecoverySource(row.source))||new Set(sources.map(row=>row.source)).size!==sources.length)throw Error("Invalid recovery sources.");if(!!authorization?.status!==!!(authorization?.read||authorization?.check))throw Error("Invalid recovery owner: status and checks must use the same owner.");const rows=sources.map(seed=>{const row=seedRow(seed),label=HELP_CATALOG.find(([source])=>source===seed.source)?.[1];if(label)row.label=label;return row});for(const row of rows)if(row.read==="failed")fail(row,row.errorCode);const others=[];let initialStates;try{initialStates=authorization?.status?await authorization.status(AbortSignal.timeout(15e3)):await ctx.get("zortexConnectorHub")?.status({signal:AbortSignal.timeout(15e3)});if(initialStates&&"ok"in initialStates){for(const state of initialStates.ok)if(!rows.some(row=>row.source===state.source)&&!others.some(row=>row.source===state.source)&&safeRecoverySource(state.source))others.push(state.state==="connected"?connectedRow(state):otherRow(state))}}catch{}if(authorization?.status)for(const row of rows){const state=initialStates&&"ok"in initialStates?initialStates.ok.find(item=>item.source===row.source):void 0;row.connection=state?.verification==="configuration-only"?"unknown":state?.state??"unknown";if(state?.verification==="configuration-only"){clearReadiness(row);delete row.errorCode;row.state="pending";row.message="Settings saved; connection has not been verified.";row.nextStep="Check the source connection and read its data."}else if(row.read==="failed"&&row.connection!=="unavailable"){fail(row,row.errorCode)}else if(row.connection!=="connected"){clearReadiness(row);delete row.errorCode;row.read="not-attempted";row.state=row.connection==="unavailable"?"unavailable":"pending";row.message=row.connection==="unknown"?"Current connection status is unavailable.":reason()}}if(initialStates&&"ok"in initialStates)for(const row of[...rows,...others]){const state=initialStates.ok.find(item=>item.source===row.source);const readiness=state&¤tReadinessRow(state);if(readiness){Object.assign(row,readiness);delete row.errorCode;providerReadinessSources.add(row.source)}else if(state?.verification==="configuration-only"){row.read="not-attempted";delete row.errorCode}if(state?.registration==="deferred"){clearReadiness(row);delete row.errorCode;row.registration="deferred";row.connection="unavailable";row.read="not-attempted";row.state="unavailable";row.message="Setup is required before this connector can be used.";row.nextStep="Complete the setup with the available tools; connection continues when the configuration is active."}}const listed=new Set([...rows,...others].map(row=>row.source));for(const[entry,label]of HELP_CATALOG){const source=entry==="teams"&&!listed.has("teams")?"microsoft-teams":entry;if(!listed.has(source)){others.push({source,label,connection:"unknown",read:"not-attempted",state:"pending",catalogOnly:true,message:"This is a directory entry; registration and connection have not been checked.",nextStep:"Inspect the installed source catalog and enable or configure the source when available."});listed.add(source)}}const token=randomBytes(32).toString("base64url"),nonce=randomBytes(24).toString("base64url");let origin="",closed=false,active,activeSource,owned,settled=false,closeTask;const continuations=new Map,configured=new Set;function releaseExecution(stop){if(owned!==stop)return;owned=void 0;active=void 0;activeSource=void 0;if(activeSources.get(ctx)?.owner===token)activeSources.delete(ctx)}let resolveDone;const done=new Promise(resolve=>{resolveDone=resolve});let resolveClosed;const closedPromise=new Promise(resolve=>{resolveClosed=resolve});const expiresAt=new Date(Date.now()+18e5).toISOString();const allRows=()=>rows.concat(others);const reloads=pendingSetupReloads.get(ctx)??new Map;pendingSetupReloads.set(ctx,reloads);function acceptResidentReload(state){if(state?.reloadRequired===true)reloads.set(state.source,SETUP_RELOAD_NEXT);else if(state?.reloadRequired===false){reloads.delete(state.source);const row=allRows().find(item=>item.source===state.source);if(row)delete row.reloadRequired}}if(initialStates&&"ok"in initialStates)for(const state of initialStates.ok)acceptResidentReload(state);function retainSetupReload(row){const next=reloads.get(row.source);if(next===void 0)return false;clearHandoff(row);clearReadiness(row);row.reloadRequired=true;row.connection="unknown";row.read="not-attempted";row.state="pending";row.message="Settings saved; connection has not been verified.";row.nextStep=next;delete row.errorCode;delete row.authorizationUrl;delete row.deviceUserCode;delete row.authorizationImage;delete row.setupReason;providerReadinessSources.delete(row.source);return true}for(const row of allRows())retainSetupReload(row);async function withSetupProgress(source,stop,configure){const progress=beginRecoveryProgress(ctx,source);progress.update("configuring","unverified");const interrupted=()=>progress.finish({connectionState:"unverified",errorCode:"aborted"});stop.signal.addEventListener("abort",interrupted,{once:true});try{if(stop.signal.aborted){interrupted();return{err:{code:"aborted"}}}const result=await configure();if("ok"in result&&result.ok.state==="configured"){const row=allRows().find(item=>item.source===source);if(result.ok.reloadRequired){reloads.set(source,result.ok.next);if(row)retainSetupReload(row)}else{reloads.delete(source);configured.add(source);if(row){clearReadiness(row);delete row.reloadRequired;delete row.configuration;delete row.registration;delete row.setupReason;row.connection="unknown"}}}progress.finish({connectionState:"unverified",..."err"in result?{errorCode:result.err.code}:result.ok.state!=="configured"?{errorCode:result.ok.state==="unavailable"?"unavailable":"failed_precondition"}:result.ok.reloadRequired?{errorCode:"configuration_reload_required"}:{}});return result}catch(error){progress.finish({connectionState:"unverified",errorCode:"unknown"});throw error}finally{stop.signal.removeEventListener("abort",interrupted)}}const externalProgressSources=new Set;function applyPending(result){if(!result||!("ok"in result))return;const pending=Array.isArray(result.pending)?result.pending:[];for(const row of allRows()){if(externalProgressSources.has(row.source))continue;if(retainSetupReload(row))continue;const item=pending.find(value=>value&&value.source===row.source&&typeof value.reason==="string"&&Object.hasOwn(PENDING_HELP,value.reason));const nextReason=row.connection==="connected"?void 0:item?.reason;if(nextReason===row.setupReason)continue;if(nextReason)row.setupReason=nextReason;else delete row.setupReason;if(nextReason){[row.message,row.nextStep]=PENDING_HELP[nextReason];if(row.registration==="deferred")row.nextStep="Complete the setup with the available tools; connection continues when the configuration is active."}else if(row.catalogOnly){row.message="This is a directory entry; registration and connection have not been checked.";row.nextStep="Inspect the installed source catalog and enable or configure the source when available."}else if(row.connection!=="connected"){row.message="This source is not connected.";row.nextStep="Check the connection and try again."}}}applyPending(initialStates);function evidenceVersions(){const parts=new Map,add=(source,value)=>{parts.set(source,[...parts.get(source)??[],value])};try{const fleet=ctx.get("indraFleet");if(fleet){for(const receipt of startupHistory(fleet).receipts)for(const result of receipt.sources)add(result.source,["receipt",receipt.requestId,result.progress?.startedAt??receipt.startedAt,result.progress?.endedAt,result.state,result.returned,result.error?.code]);for(const progress of fleet.status().sources??[])add(progress.source,["progress",progress.startedAt,progress.endedAt,progress.stage,progress.returned,progress.error?.code])}for(const saved of readRecoveryEvidence(ctx,allRows().map(row=>row.source)).values())add(saved.source,["help",saved.updatedAt,saved.read,saved.returned]);for(const progress of readRecoveryProgress(ctx))add(progress.source,["manual-progress",progress.startedAt,progress.endedAt,progress.stage,progress.connectionState,progress.returned,progress.errorCode,progress.readiness])}catch{return new Map}return new Map([...parts].map(([source,values])=>[source,JSON.stringify(values)]))}const blockedEvidence=new Map,initialEvidence=evidenceVersions();for(const row of allRows())if(row.connection!=="connected")blockedEvidence.set(row.source,initialEvidence.get(row.source));let statusRefresh,lastStatusRefresh=0,interactionGeneration=0;function refreshResidentStatus(){if(active||closed||statusRefresh||Date.now()-lastStatusRefresh<5e3)return;lastStatusRefresh=Date.now();const generation=interactionGeneration;statusRefresh=(async()=>{const versions=evidenceVersions();let states;try{const signal=AbortSignal.timeout(15e3);states=await(authorization?.status?authorization.status(signal):ctx.get("zortexConnectorHub")?.status({signal}))}catch{}const evidenceContext=authorization?.status?{get:name=>name==="zortexConnectorHub"?{status:async()=>states??{err:{code:"unavailable"}}}:ctx.get(name)}:ctx;const progress=versions.size?await readOnboardingReport(evidenceContext,{enabled:true}):void 0;if(active||closed||generation!==interactionGeneration)return;const currentVersions=evidenceVersions();const manualProgress=new Map((await readCurrentRecoveryProgress(ctx)).map(item=>[item.source,item]));if(states&&"ok"in states){for(const state of states.ok)if(safeRecoverySource(state.source)&&!allRows().some(row=>row.source===state.source))others.push(state.state==="connected"?connectedRow(state):otherRow(state))}for(const row of allRows()){if(waiting.has(row.state)&&!externalProgressSources.has(row.source)||busy(row.source))continue;const state=states&&"ok"in states?states.ok.find(item=>item.source===row.source):void 0;acceptResidentReload(state);if(retainSetupReload(row))continue;if(row.catalogOnly&&!state)continue;if(state){delete row.catalogOnly;if(typeof state.label==="string")row.label=state.label.slice(0,80)}const deferred=state?.registration==="deferred",changedRegistration=row.registration==="deferred"!==deferred;if(deferred)row.registration="deferred";else delete row.registration;const external=manualProgress.get(row.source),version=versions.get(row.source);const stableEvidence=version!==void 0&&version===currentVersions.get(row.source);if(!deferred&&state&&external&&external.stage!=="finished"&&stableEvidence){externalProgressSources.add(row.source);blockedEvidence.set(row.source,version);clearReadiness(row);clearHandoff(row);delete row.errorCode;delete row.setupReason;row.connection=state.state;row.read="not-attempted";row.state=external.stage==="configuring"?"connecting":external.stage;row.message=external.stage==="waiting-user"?"The existing connection transaction has an active sign-in page.":external.stage==="reading"?"The current connection is being checked for readable data.":"A connection attempt is in progress.";row.nextStep="Finish the existing connection attempt; this page updates automatically.";continue}const endedExternal=externalProgressSources.delete(row.source);const readiness=state&¤tReadinessRow(state);if(readiness){Object.assign(row,readiness);delete row.errorCode;providerReadinessSources.add(row.source);delete row.setupReason;continue}const lostProviderReadiness=providerReadinessSources.delete(row.source);const next=deferred?"unavailable":state?.verification==="configuration-only"?"unknown":state?.state??(states&&"ok"in states?"unavailable":"unknown");const newEvidence=version!==void 0&&version===currentVersions.get(row.source)&&(!blockedEvidence.has(row.source)||blockedEvidence.get(row.source)!==version);if(next!=="connected"||lostProviderReadiness||row.state==="actions-ready")blockedEvidence.set(row.source,version);const evidence=progress?.sources.find(item=>item.source===row.source);if(next==="not-connected"&&newEvidence&&evidence?.read==="failed"){row.connection=next;delete row.setupReason;fail(row,evidence.errorCode);continue}if(next==="connected"&&evidence?.connection==="connected"&&version!==void 0&&version===currentVersions.get(row.source)&&(!blockedEvidence.has(row.source)||blockedEvidence.get(row.source)!==version)){blockedEvidence.delete(row.source);clearReadiness(row);clearHandoff(row);delete row.setupReason;delete row.errorCode;Object.assign(row,seedRow(evidence));if(evidence.read==="failed")fail(row,evidence.errorCode);continue}if(!endedExternal&&!lostProviderReadiness&&row.state!=="actions-ready"&&row.connection===next&&!changedRegistration&&!(state?.verification==="configuration-only"&&row.message!=="Settings saved; connection has not been verified.")&&!(next==="unknown"&&!state&&row.message==="Settings saved; connection has not been verified."))continue;row.connection=next;clearReadiness(row);clearHandoff(row);delete row.setupReason;row.read="not-attempted";delete row.errorCode;row.state=next==="unavailable"?"unavailable":"pending";row.message=deferred?"Setup is required before this connector can be used.":state?.verification==="configuration-only"?"Settings saved; connection has not been verified.":next==="connected"?"Connected. Check again to verify the current connection.":next==="unknown"?"Current connection status is unavailable.":next==="unavailable"?"This source is currently unavailable.":"This source is not connected.";row.nextStep=deferred?"Complete the setup with the available tools; connection continues when the configuration is active.":state?.verification==="configuration-only"?"Check the source connection and read its data.":next==="connected"?"Check available actions or data access.":"Check the connection and try again."}applyPending(states);complete()})().finally(()=>{statusRefresh=void 0})}const terminal=row=>["complete","empty","actions-ready"].includes(row.state)||row.state==="unavailable"&&row.configuration!=="required"&&row.registration!=="deferred"&&!row.reloadRequired;const complete=()=>{const checked=allRows().filter(row=>!row.catalogOnly);if(!settled&&checked.some(row=>["complete","empty","actions-ready"].includes(row.state))&&checked.every(terminal)){settled=true;resolveDone()}};function report(links=false){const checked=allRows().filter(row=>!row.catalogOnly);const success=checked.length>0&&checked.every(row=>["complete","empty","actions-ready"].includes(row.state)&&row.connection==="connected");const publicReads=new Map(readPublicActionProgress(ctx).map(item=>[item.source,item]));const shown=row=>{const{authorizationUrl,authorizationInstructions,deviceUserCode,authorizationImage:qrImage,authorizationExpiresAt,...safe}=row;const signInUrl=!closed&&(row.connection!=="connected"||row.errorCode==="login_required")&&["pending","failed"].includes(row.state)&&Object.hasOwn(SITE_SIGN_IN,row.source)?SITE_SIGN_IN[row.source]:void 0;const setup=recoverySetupFlags(row.source,authorization);const support=sourceSupport(row,Object.keys(setup).length>0);const publicRead=publicReads.get(row.source);const registered=!row.catalogOnly&&row.registration!=="deferred"&&row.connection!=="unavailable";const capabilities={...registered&&support.state==="supported"&&!row.reloadRequired&&!["joplin","google-chrome","microsoft-edge"].includes(row.source)&&!waiting.has(row.state)?{authorizationAvailable:true}:{},...registered&&authorization&&row.source==="gmail"?{gmailWriteAvailable:true}:{},...registered&&authorization&&row.source==="readwise"?{readwiseMcpWriteAvailable:true}:{},...registered&&supportsSavedReconnect(row.source)&&(!authorization||typeof authorization.reconnectSaved==="function")?{reconnectSavedAvailable:true}:{}};const publicRow={...safe,...setup,...capabilities,support,...publicRead?{publicRead}:{},...signInUrl?{signInUrl}:{},...links&&row.state==="waiting-user"&&authorizationInstructions?{nextStep:authorizationInstructions}:{},...links&&row.state==="waiting-user"&&qrImage?{authorizationImage:{...qrImage}}:{},...links&&row.state==="waiting-user"&&authorizationExpiresAt?{authorizationExpiresAt}:{},...links&&row.state==="waiting-user"&&authorizationUrl?{authorizationUrl,...deviceUserCode?{deviceUserCode}:{}}:{}};if(row.configuration==="required"&&support.reasonCode==="connector_unavailable"){}else if(support.state==="unsupported"){publicRow.state="unavailable";publicRow.message=support.message;publicRow.nextStep=support.nextStep}else if(row.registration==="deferred"||row.connection==="unavailable"){publicRow.message=support.message;publicRow.nextStep=support.nextStep}return publicRow};return{state:closed?"closed":success?"ready":checked.length>0&&checked.every(terminal)?"partial":"recovering",success,sources:rows.map(shown),others:others.map(shown),...activeSource?{activeSource}:{}}}function clearHandoff(row){delete row.authorizationUrl;delete row.authorizationInstructions;delete row.deviceUserCode;delete row.authorizationImage;delete row.authorizationExpiresAt}function clearReadiness(row){delete row.availability;delete row.actions;delete row.operation}function fail(row,code){clearHandoff(row);clearReadiness(row);delete row.authorizationUrl;delete row.deviceUserCode;delete row.authorizationImage;if(code)row.errorCode=PUBLIC_ERROR_CODES.has(code)?code:"unknown";else delete row.errorCode;row.state="failed";row.read="failed";if(row.source==="rednote"&&code==="unavailable"){row.message="The local RedNote service is unavailable.";row.nextStep="";return}if(row.source==="activitywatch"&&code==="unavailable"){row.message=OTHER_HELP.activitywatch[0];row.nextStep="";return}if(row.connection==="connected"&&code==="failed_precondition"&&["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(row.source)){row.message="Saved Google account access could not be verified.";row.nextStep="";return}const help=authorizationHelp(code,row.source);if(help){[row.message,row.nextStep]=help;return}row.message=reason(code,row.source);row.nextStep=""}function busy(source){return continuations.has(source)||(ctx.get("indraFleet")?.status().activeSources?.includes(source)??false)}async function run(row,stop,forceAuthorization,readOnly,repairLegacyClient=false,savedAccessOnly=false,readwiseMcpWrite=false,gmailWrite=false){const progress=beginRecoveryProgress(ctx,row.source);let returned,readiness,authorityProof,ownsFlow=true;const interrupted=()=>progress.finish({connectionState:row.connection==="connected"?"connected":"unverified",errorCode:"aborted"});stop.signal.addEventListener("abort",interrupted,{once:true});const hub=ctx.get("zortexConnectorHub");try{stop.signal.throwIfAborted();if(!hub){fail(row);return}const states=authorization?.status?await authorization.status(stop.signal):await hub.status({signal:stop.signal});stop.signal.throwIfAborted();if(!("ok"in states)){row.connection="unknown";fail(row);return}const state=states.ok.find(item=>item.source===row.source);if(!state||state.state==="unavailable"){row.state="unavailable";row.connection="unavailable";row.message="This source is not installed, is disabled, or is currently unavailable.";row.nextStep="Inspect the source settings and complete the available setup before resuming its connection.";return}delete row.catalogOnly;row.connection=state.state;if(readOnly&&state.state!=="connected"){fail(row,"unauthenticated");return}if(savedAccessOnly){const result2=authorization?await authorization.reconnectSaved?.(row.source,stop.signal):await hub.connect(row.source,{signal:stop.signal,retention:"transient",automatic:true,savedAccessOnly:true});if(!result2||!("ok"in result2)||result2.ok.source!==row.source||result2.ok.state!=="connected"){const code=result2&&"ok"in result2&&result2.ok.source===row.source&&result2.ok.state==="failed"?result2.ok.error?.code:void 0;fail(row,result2&&"err"in result2?result2.err.code:code??"failed_precondition");return}row.connection="connected"}else if(state.state!=="connected"||forceAuthorization){const started=Date.now(),requestId=randomUUID();let residentOwned=false;const selectAccount=forceAuthorization&&!gmailWrite&&["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(row.source);const reauthorize=forceAuthorization&&repairLegacyClient&&["todoist","linear"].includes(row.source);const settings={manualPresentation:"return-url",...gmailWrite?{gmailWrite:true}:{},...readwiseMcpWrite?{readwiseMcpWrite:true}:{},...selectAccount?{selectAccount:true}:{},...reauthorize?{reauthorize:true}:{}};const result2=authorization?await authorization.connect(row.source,requestId,stop.signal,settings):await hub.connect(row.source,{signal:stop.signal,retention:"transient",automatic:false,...settings});residentOwned=!!authorization;if(!("ok"in result2)){fail(row,"err"in result2?result2.err.code:"data_loss");return}let job=result2.ok,cancellation;const cancelResidentAuthorization=()=>{const current=job;if(!residentOwned||current.state!=="waiting-user"||!Number.isSafeInteger(current.generation)||typeof current.challengeRef!=="string"||!current.challengeRef)return;return cancellation??=authorization.cancel(requestId,current.generation,current.challengeRef).then(()=>void 0,()=>void 0)};try{stop.signal.throwIfAborted();if(!residentOwned&&job.state==="waiting-user"&&(!Number.isFinite(Date.parse(job.startedAt))||Date.parse(job.startedAt)<started)){ownsFlow=false;releaseExecution(stop);row.state="pending";row.message="Another sign-in is still waiting for authorization.";row.nextStep="Continue the existing transaction through its owning session, then check this source again.";return}const id=job.id;while(!stop.signal.aborted){if(job.id!==id||job.source!==row.source){fail(row);return}clearHandoff(row);if(job.state==="connected"){row.connection="connected";break}if(job.state!=="waiting-user"){fail(row,job.state==="cancelled"?"aborted":job.error?.code);return}if(row.source==="whatsapp-web"){row.state="waiting-user";row.message="Waiting for you to scan the QR code with WhatsApp on your phone.";row.nextStep="Settings \u2192 Linked devices \u2192 Link a device. The latest message will be read automatically after the scan. If you closed the page, use the link below to reopen it."}else{row.state="waiting-user";row.message="Authorization is in progress.";row.nextStep="Please wait. You do not need to click again."}if(typeof job.expiresAt==="string"&&Number.isFinite(Date.parse(job.expiresAt)))row.authorizationExpiresAt=new Date(job.expiresAt).toISOString();const qrImage=authorizationImage(job.authorizationImage);if(qrImage){row.authorizationImage=qrImage;if(row.source!=="whatsapp-web"){row.message="The provider returned a QR authorization challenge.";row.nextStep=""}}const url=nativeRecoveryAuthorizationUrl(row.source,job.authorizationUrl,residentOwned?job.authorizationOrigin:void 0)??reviewedRecoveryAuthorizationUrl(row.source,job)??protectedRecoveryFormUrl(row.source,job,residentOwned);if(url){row.authorizationUrl=url;const prompt=job.devicePrompt;if(prompt?.kind==="device-code"&&typeof prompt.userCode==="string"&&/^[A-Z0-9-]{4,32}$/i.test(prompt.userCode))row.deviceUserCode=prompt.userCode}if(residentOwned&&typeof job.instructions==="string"&&job.instructions.trim()&&Buffer.byteLength(job.instructions)<=2048&&!/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/u.test(job.instructions))row.authorizationInstructions=job.instructions;if(url||qrImage||row.authorizationInstructions){row.state="waiting-user";if(row.source!=="whatsapp-web"&&!qrImage){row.message="The connection page has an active sign-in or access step.";row.nextStep="Continue the live page with the available browser or computer tools. Request missing input only if those tools cannot complete the step."}}progress.update(row.state,"unverified");if(residentOwned&&job.automationActive!==true)releaseExecution(stop);try{await delay(250,void 0,{signal:stop.signal})}catch(error){await cancelResidentAuthorization();throw error}const next=authorization?await authorization.job(requestId,stop.signal):hub.job(id);if(!("ok"in next)){fail(row);return}job=next.ok}}finally{if(stop.signal.aborted)await cancelResidentAuthorization()}}while(active&&owned!==stop)await delay(50,void 0,{signal:stop.signal});stop.signal.throwIfAborted();owned=stop;activeSource=row.source;active=continuations.get(row.source)?.task;activeSources.set(ctx,{source:row.source,owner:token});clearHandoff(row);row.state="reading";row.message="Connection confirmed. Checking available actions or data access.";row.nextStep="Checking available actions or data access.";progress.update("reading","connected");authorityProof=await recoveryAuthorityProof(ctx,row.source,stop.signal);const result=authorization?.check?await authorization.check(row.source,stop.signal):authorization?.read?await authorization.read(row.source,{limit:1},stop.signal).then(result2=>"ok"in result2?{ok:{source:row.source,basis:"read",operation:{state:"succeeded",returned:result2.ok.returned}}}:"empty"in result2?{ok:{source:row.source,basis:"read",operation:{state:"succeeded",returned:0}}}:result2):await hub.check(row.source,{signal:stop.signal,retention:"transient"});stop.signal.throwIfAborted();if(!("ok"in result)){fail(row,"err"in result?result.err.code:void 0);return}const check=result.ok;if(check.source!==row.source||check.basis==="actions"&&(!Number.isSafeInteger(check.actions)||check.actions<=0)){fail(row);return}if(!saveRecoveryCheck(ctx,check)){fail(row);row.message="Connection was checked, but progress could not be saved on this computer.";row.nextStep="Repair access to the data folder, then repeat the readiness check. The connection is saved.";return}readiness=check;if(check.basis==="actions"&&authorization?.status)providerReadinessSources.add(row.source);delete row.errorCode;row.availability=check.basis;row.operation=check.operation.state;if(check.basis==="actions")row.actions=check.actions;else delete row.actions;returned=check.operation.state==="succeeded"?check.operation.returned:void 0;row.read=returned===void 0?"not-attempted":returned>0?"first-record":"empty";row.state=row.read==="empty"?"empty":"complete";row.message=row.read==="first-record"?"Connected and the first record has been read.":row.read==="empty"?"The read succeeded, but no data is currently visible.":row.operation==="succeeded"?"Connected. An action completed successfully.":"Connected. Actions are available; no action has been run.";row.nextStep=row.read==="empty"?emptyHelp():"This source is ready to use."}catch{if(!closed)fail(row,stop.signal.aborted?"aborted":void 0)}finally{progress.finish({connectionState:row.connection==="connected"?"connected":"unverified",...readiness&&!stop.signal.aborted&&["complete","empty"].includes(row.state)?{readiness,...authorityProof?{authorityProof}:{}}:{},...returned!==void 0?{returned}:{},...["failed","unavailable","pending"].includes(row.state)?{errorCode:row.errorCode??(row.state==="unavailable"?"unavailable":"unknown")}:{}});stop.signal.removeEventListener("abort",interrupted);clearHandoff(row);releaseExecution(stop);if(ownsFlow)stop.abort();complete()}}function startRecovery(row,stop,forceAuthorization=false,readOnly=false,repairLegacyClient=false,savedAccessOnly=false,readwiseMcpWrite=false,gmailWrite=false){interactionGeneration++;owned=stop;activeSource=row.source;activeSources.set(ctx,{source:row.source,owner:token});const task=Promise.resolve().then(()=>withFeedbackFlow(row.source,()=>run(row,stop,forceAuthorization,readOnly,repairLegacyClient,savedAccessOnly,readwiseMcpWrite,gmailWrite),{flowId:randomUUID(),source:row.source,mode:"manual",trigger:"tool"})).catch(()=>{if(!closed)fail(row)}).finally(()=>{if(continuations.get(row.source)?.stop===stop)continuations.delete(row.source);releaseExecution(stop)});continuations.set(row.source,{stop,task});active=task}function finishSetup(row,stop){releaseExecution(stop);if(configured.delete(row.source)&&!closed&&!stop.signal.aborted)startRecovery(row,stop);else stop.abort()}function configureSource(response,row,configure,messages){if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row.source)){reply(response,503,{error:"save_failed"});return}const stop=new AbortController;interactionGeneration++;owned=stop;activeSource=row.source;activeSources.set(ctx,{source:row.source,owner:token});delete row.errorCode;row.state="connecting";row.read="not-attempted";row.message=messages.saving;row.nextStep="Please wait.";const failed=()=>{if(!closed){row.state="pending";row.message=messages.failed;row.nextStep=messages.retry}};active=Promise.resolve().then(()=>withSetupProgress(row.source,stop,()=>configure(stop.signal))).then(result=>{if(closed)return;row.state="pending";row.read="not-attempted";if("err"in result||result.ok.state!=="configured"){failed();return}row.message=messages.saved;row.nextStep=result.ok.next}).catch(failed).finally(()=>finishSetup(row,stop));reply(response,202,report(true))}function reply(response,status,value){response.writeHead(status,{"Content-Type":"application/json; charset=utf-8"}).end(JSON.stringify(value))}const server=createServer((request,response)=>{void handle(request,response).catch(()=>{if(!response.headersSent)reply(response,500,{error:"request_failed"});else response.end()})});let lastSeen=0;async function handle(request,response){response.setHeader("Cache-Control","no-store");response.setHeader("Referrer-Policy","no-referrer");response.setHeader("X-Content-Type-Options","nosniff");response.setHeader("Content-Security-Policy",`default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`);if(request.headers.host!==new URL(origin).host){reply(response,403,{error:"forbidden"});return}if(request.method==="GET"&&request.url==="/"){response.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}).end(recoveryLaunch(nonce));return}if(request.method!=="POST"||!["/api","/open"].includes(request.url??"")){reply(response,404,{error:"not_found"});return}const received=request.headers["x-zortex-recovery"];if(request.headers.origin!==origin||typeof received!=="string"||Buffer.byteLength(received)!==Buffer.byteLength(token)||!timingSafeEqual(Buffer.from(received),Buffer.from(token))){reply(response,403,{error:"forbidden"});return}lastSeen=Date.now();if(request.headers["content-type"]!=="application/json"){reply(response,415,{error:"json_required"});return}if(Number(request.headers["content-length"]??0)>MAX_RECOVERY_REQUEST_BYTES){request.resume();reply(response,413,{error:"too_large"});return}let bytes=0;const chunks=[];for await(const chunk of request){bytes+=chunk.length;if(bytes>MAX_RECOVERY_REQUEST_BYTES){reply(response,413,{error:"too_large"});return}chunks.push(chunk)}let body;try{body=JSON.parse(Buffer.concat(chunks).toString("utf8"))}catch{reply(response,400,{error:"invalid_request"});return}if(request.url==="/open"){if(!body||typeof body!=="object"||Array.isArray(body)||Object.keys(body).length){reply(response,400,{error:"invalid_request"});return}if(closed){reply(response,410,{error:"closed"});return}let current=session;const request2=async(input,signal)=>{if(current.snapshot().state==="closed")current=await startGuidedRecovery(ctx,{sources,pageGoneMs,...authorization?{authorization}:{}});return current.request(input,signal)};const url=await recoverySurface(ctx,{request:request2,snapshot:()=>current.snapshot(),...authorization?{authorization}:{},...sources.length===1?{source:sources[0].source}:{}});if(closed){reply(response,410,{error:"closed"});return}reply(response,200,{url});return}if(!body||typeof body!=="object"||Array.isArray(body)||Object.keys(body).some(key=>!["action","source","roots","libraryId","libraryType","port","executable","session","subdomain","region","instanceUrl","selection"].includes(key))||!["status","connect","read","authorize","authorize-readwise-mcp","authorize-gmail-write","reconnect-saved","cancel","close","discover-native-vault","configure-native-files","configure-zotero","configure-owntracks","configure-wechat","configure-joplin","configure-thunderbird","configure-proton-mail","configure-discord","configure-dropbox","configure-box","configure-front","configure-hubspot","configure-google-contacts","configure-google-chat","configure-salesforce","configure-zendesk","configure-zoom","configure-copyq","configure-freshdesk","configure-smartsheet","configure-figma","configure-nextcloud","configure-zulip","configure-freshrss","configure-miniflux","configure-mattermost","configure-wallabag","configure-calcom","configure-wakatime"].includes(String(body.action))||!["connect","read","authorize","authorize-readwise-mcp","authorize-gmail-write","reconnect-saved","cancel","discover-native-vault","configure-native-files","configure-zotero","configure-owntracks","configure-wechat","configure-joplin","configure-thunderbird","configure-proton-mail","configure-discord","configure-dropbox","configure-box","configure-front","configure-hubspot","configure-google-contacts","configure-google-chat","configure-salesforce","configure-zendesk","configure-zoom","configure-copyq","configure-freshdesk","configure-smartsheet","configure-figma","configure-nextcloud","configure-zulip","configure-freshrss","configure-miniflux","configure-mattermost","configure-wallabag","configure-calcom","configure-wakatime"].includes(String(body.action))&&body.source!==void 0||body.action!=="configure-native-files"&&body.roots!==void 0||body.action!=="configure-zotero"&&(body.libraryId!==void 0||body.libraryType!==void 0)||!["configure-owntracks","configure-wechat","configure-joplin","configure-thunderbird","configure-proton-mail"].includes(String(body.action))&&body.port!==void 0||body.action!=="configure-copyq"&&(body.executable!==void 0||body.session!==void 0)||body.action!=="configure-freshdesk"&&body.subdomain!==void 0||body.action!=="configure-smartsheet"&&body.region!==void 0||body.action!=="configure-nextcloud"&&body.instanceUrl!==void 0||!["configure-joplin","configure-discord","configure-dropbox","configure-box","configure-front","configure-hubspot","configure-google-contacts","configure-google-chat","configure-salesforce","configure-zendesk","configure-zoom","configure-figma","configure-zulip","configure-freshrss","configure-miniflux","configure-mattermost","configure-wallabag","configure-calcom","configure-wakatime"].includes(String(body.action))&&body.selection!==void 0){reply(response,400,{error:"invalid_request"});return}if(body.action==="authorize-readwise-mcp"&&(body.source!=="readwise"||Object.keys(body).length!==2)){reply(response,400,{error:"invalid_request"});return}if(body.action==="authorize-gmail-write"&&(body.source!=="gmail"||Object.keys(body).length!==2)){reply(response,400,{error:"invalid_request"});return}if(body.action==="discover-native-vault"){const row2=allRows().find(item=>item.source==="obsidian");if(Object.keys(body).length!==2||body.source!=="obsidian"||!row2||!authorization?.configureNativeFiles){reply(response,400,{error:"invalid_request"});return}if(closed){reply(response,410,{error:"closed"});return}const result=await discoverNativeVaultCandidates("obsidian");if(closed){reply(response,410,{error:"closed"});return}reply(response,200,{state:result.state,candidates:result.candidates.filter(path=>path.length<=512)});return}if(body.action==="status"){refreshResidentStatus();reply(response,200,report(true));return}if(body.action==="close"){reply(response,200,{...report(),state:"closed"});setImmediate(()=>{void session.close()});return}if(body.action==="cancel"){const row2=allRows().find(item=>item.source===body.source),continuation=typeof body.source==="string"?continuations.get(body.source):void 0,current=continuation?.task??active,cancelStop=continuation?.stop??owned;if(!row2){reply(response,400,{error:"unknown_source"});return}if(closed){reply(response,410,{error:"closed"});return}if(!current||!continuation&&activeSource!==row2.source||!cancelStop){reply(response,409,{error:"verification_not_active",activeSource:activeSource??activeSources.get(ctx)?.source});return}row2.message="Cancelling verification.";row2.nextStep="Please wait.";cancelStop.abort();let finished=false;await Promise.race([current.then(()=>{finished=true}),delay(5e3)]);if(finished&&!closed){row2.state="failed";row2.read="not-attempted";row2.errorCode="aborted";row2.message="Verification was cancelled. You can choose another source.";row2.nextStep="Choose Connect when you are ready to try again."}reply(response,finished?200:202,report(true));return}if(body.action==="configure-zulip"){const row2=allRows().find(item=>item.source==="zulip");if(!authorization?.configureZulip||!row2||body.source!=="zulip"||!validZulipSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureZulip(body.selection,signal),{saving:"Saving the Zulip instance URL and email.",saved:"Zulip instance URL and email saved. The current connection has not been verified.",failed:"The Zulip setup could not be saved.",retry:"Check the instance URL and email and try again."});return}if(body.action==="configure-freshrss"){const row2=allRows().find(item=>item.source==="freshrss");if(!authorization?.configureFreshRSS||!row2||body.source!=="freshrss"||!validFreshRSSSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureFreshRSS(body.selection,signal),{saving:"Saving the FreshRSS instance URL and username.",saved:"FreshRSS instance URL and username saved. The current connection has not been verified.",failed:"The FreshRSS setup could not be saved.",retry:"Check the instance URL and username and try again."});return}if(body.action==="configure-miniflux"){const row2=allRows().find(item=>item.source==="miniflux");if(!authorization?.configureMiniflux||!row2||body.source!=="miniflux"||!validMinifluxSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureMiniflux(body.selection,signal),{saving:"Saving the Miniflux instance URL and username.",saved:"Miniflux instance URL and username saved. The current connection has not been verified.",failed:"The Miniflux setup could not be saved.",retry:"Check the instance URL and username and try again."});return}if(body.action==="configure-mattermost"){const row2=allRows().find(item=>item.source==="mattermost");if(!authorization?.configureMattermost||!row2||body.source!=="mattermost"||!validMattermostSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureMattermost(body.selection,signal),{saving:"Saving the Mattermost instance URL and username.",saved:"Mattermost instance URL and username saved. The current connection has not been verified.",failed:"The Mattermost setup could not be saved.",retry:"Check the instance URL and username and try again."});return}if(body.action==="configure-wallabag"){const row2=allRows().find(item=>item.source==="wallabag");if(!authorization?.configureWallabag||!row2||body.source!=="wallabag"||!validWallabagSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureWallabag(body.selection,signal),{saving:"Saving the Wallabag instance URL and username.",saved:"Wallabag instance URL and username saved. The current connection has not been verified.",failed:"The Wallabag setup could not be saved.",retry:"Check the instance URL and username and try again."});return}if(body.action==="configure-calcom"){const row2=allRows().find(item=>item.source==="calcom");if(!authorization?.configureCalcom||!row2||body.source!=="calcom"||!validCalcomSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureCalcom(body.selection,signal),{saving:"Saving the Cal.com username.",saved:"Cal.com username saved. The current connection has not been verified.",failed:"The Cal.com setup could not be saved.",retry:"Check the username and try again."});return}if(body.action==="configure-wakatime"){const row2=allRows().find(item=>item.source==="wakatime");if(!authorization?.configureWakatime||!row2||body.source!=="wakatime"||!validWakatimeSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureWakatime(body.selection,signal),{saving:"Saving the WakaTime username or account ID.",saved:"WakaTime username or account ID saved. The current connection has not been verified.",failed:"The WakaTime setup could not be saved.",retry:"Check the username and try again."});return}if(body.action==="configure-nextcloud"){const row2=allRows().find(item=>item.source==="nextcloud");if(!authorization?.configureNextcloud||!row2||body.source!=="nextcloud"||!validNextcloudInstanceUrl(body.instanceUrl)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureNextcloud(body.instanceUrl,signal),{saving:"Saving the Nextcloud instance URL.",saved:"Nextcloud instance URL saved. The current connection has not been verified.",failed:"The Nextcloud setup could not be saved.",retry:"Check the instance URL and try again."});return}if(body.action==="configure-smartsheet"){const row2=allRows().find(item=>item.source==="smartsheet");if(!authorization?.configureSmartsheet||!row2||body.source!=="smartsheet"||typeof body.region!=="string"||!["us","eu","au"].includes(body.region)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureSmartsheet(body.region,signal),{saving:"Saving the Smartsheet region.",saved:"Smartsheet region saved. The current connection has not been verified.",failed:"The Smartsheet setup could not be saved.",retry:"Check the region and try again."});return}if(body.action==="configure-figma"){const row2=allRows().find(item=>item.source==="figma");if(!authorization?.configureFigma||!row2||body.source!=="figma"||!["fields","oauth"].includes(String(body.selection))){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureFigma(body.selection,signal),{saving:"Saving the Figma personal access token mode.",saved:"Figma connection mode saved. The current connection has not been verified.",failed:"The Figma setup could not be saved.",retry:"Check the personal access token mode and try again."});return}if(body.action==="configure-freshdesk"){const row2=allRows().find(item=>item.source==="freshdesk");if(!authorization?.configureFreshdesk||!row2||body.source!=="freshdesk"||typeof body.subdomain!=="string"||!/^(?:[a-z0-9]|[a-z0-9][a-z0-9-]{0,61}[a-z0-9])$/.test(body.subdomain)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureFreshdesk(body.subdomain,signal),{saving:"Saving the Freshdesk tenant.",saved:"Freshdesk tenant saved. The current connection has not been verified.",failed:"The Freshdesk setup could not be saved.",retry:"Check the tenant name and try again."});return}if(body.action==="configure-wechat"){const row2=allRows().find(item=>item.source==="wechat");if(!authorization?.configureWeChat||!row2||body.source!=="wechat"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureWeChat(body.port,signal),{saving:"Saving the WeChat local port.",saved:"WeChat setup saved. The current connection has not been verified.",failed:"The WeChat setup could not be saved.",retry:"Check the local port and try again."});return}if(body.action==="configure-joplin"){const row2=allRows().find(item=>item.source==="joplin");try{if(!authorization?.configureJoplin||!row2||body.source!=="joplin"||body.port!==void 0)throw Error();validateJoplinSelection(body.selection)}catch{reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy("joplin")){reply(response,409,{error:"connection_in_progress"});return}const selection=body.selection;if("phase"in selection&&selection.phase==="confirm"&&!invalidateRecoveryEvidence(ctx,"joplin")){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;owned=stop2;interactionGeneration++;activeSource="joplin";activeSources.set(ctx,{source:"joplin",owner:token});const disconnect=()=>{if(!response.writableEnded)stop2.abort()};response.once("close",disconnect);let result={err:{code:"invalid_setup_result"}};active=Promise.resolve().then(async()=>{result=validateJoplinResult(await withSetupProgress("joplin",stop2,()=>authorization.configureJoplin(selection,stop2.signal)))}).catch(()=>{result={err:{code:"pairing_failed"}}}).finally(()=>{response.removeListener("close",disconnect);releaseExecution(stop2)});await active;if(closed||response.destroyed)return;if("err"in result){reply(response,400,{error:"pairing_failed"});return}const pairing=result.ok;if(pairing.state==="configured"){row2.state="pending";row2.read="not-attempted";row2.message="Joplin paired. Note access has not been checked.";row2.nextStep=pairing.next;if(pairing.reloadRequired)reloads.set("joplin",pairing.next)}reply(response,200,{pairing});if(pairing.state==="configured")finishSetup(row2,stop2);return}if(body.action==="configure-thunderbird"){const row2=allRows().find(item=>item.source==="thunderbird");if(!authorization?.configureThunderbird||!row2||body.source!=="thunderbird"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureThunderbird(body.port,signal),{saving:"Saving the Thunderbird local port.",saved:"Thunderbird setup saved. The current connection has not been verified.",failed:"The Thunderbird setup could not be saved.",retry:"Check the local port and try again."});return}if(body.action==="configure-dropbox"){const row2=allRows().find(item=>item.source==="dropbox");try{const v=body.selection;if(!authorization?.configureDropbox||!row2||body.source!=="dropbox"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedServiceSource("dropbox",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureDropbox(body.selection,signal),{saving:"Saving Dropbox selection.",saved:"Dropbox setup saved. The current connection has not been verified.",failed:"The Dropbox setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-box"){const row2=allRows().find(item=>item.source==="box");try{const v=body.selection;if(!authorization?.configureBox||!row2||body.source!=="box"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedServiceSource("box",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureBox(body.selection,signal),{saving:"Saving Box selection.",saved:"Box setup saved. The current connection has not been verified.",failed:"The Box setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-front"){const row2=allRows().find(item=>item.source==="front");try{const v=body.selection;if(!authorization?.configureFront||!row2||body.source!=="front"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedWorkSource("front",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureFront(body.selection,signal),{saving:"Saving Front selection.",saved:"Front setup saved. The current connection has not been verified.",failed:"The Front setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-hubspot"){const row2=allRows().find(item=>item.source==="hubspot");try{const v=body.selection;if(!authorization?.configureHubSpot||!row2||body.source!=="hubspot"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedWorkSource("hubspot",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureHubSpot(body.selection,signal),{saving:"Saving HubSpot selection.",saved:"HubSpot setup saved. The current connection has not been verified.",failed:"The HubSpot setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-google-contacts"){const row2=allRows().find(item=>item.source==="google-contacts");try{const v=body.selection;if(!authorization?.configureGoogleContacts||!row2||body.source!=="google-contacts"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key)))throw Error("invalid");createPreparedServiceSource("google-contacts",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureGoogleContacts(body.selection,signal),{saving:"Saving Google Contacts selection.",saved:"Google Contacts setup saved. The current connection has not been verified.",failed:"The Google Contacts setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-google-chat"){const row2=allRows().find(item=>item.source==="google-chat");try{const v=body.selection;if(!authorization?.configureGoogleChat||!row2||body.source!=="google-chat"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key)))throw Error("invalid");createPreparedServiceSource("google-chat",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureGoogleChat(body.selection,signal),{saving:"Saving Google Chat selection.",saved:"Google Chat setup saved. The current connection has not been verified.",failed:"The Google Chat setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-salesforce"){const row2=allRows().find(item=>item.source==="salesforce");try{const v=body.selection;if(!authorization?.configureSalesforce||!row2||body.source!=="salesforce"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["environment","clientId","loopbackPort"].includes(key)))throw Error("invalid");createPreparedWorkSource("salesforce",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureSalesforce(body.selection,signal),{saving:"Saving Salesforce selection.",saved:"Salesforce setup saved. The current connection has not been verified.",failed:"The Salesforce setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-zendesk"){const row2=allRows().find(item=>item.source==="zendesk");if(!authorization?.configureZendesk||!row2||body.source!=="zendesk"||!validZendeskSelection(body.selection)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureZendesk(body.selection,signal),{saving:"Saving Zendesk selection.",saved:"Zendesk setup saved. The current connection has not been verified.",failed:"The Zendesk setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-zoom"){const row2=allRows().find(item=>item.source==="zoom");try{const v=body.selection;if(!authorization?.configureZoom||!row2||body.source!=="zoom"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId"].includes(key)))throw Error("invalid");createPreparedServiceSource("zoom",{mode:"oauth",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureZoom(body.selection,signal),{saving:"Saving Zoom selection.",saved:"Zoom setup saved. The current connection has not been verified.",failed:"The Zoom setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-discord"){const row2=allRows().find(item=>item.source==="discord");try{const v=body.selection;if(!authorization?.configureDiscord||!row2||body.source!=="discord"||!v||typeof v!=="object"||Array.isArray(v)||Object.keys(v).some(key=>!["clientId","expectedSubject","ipcPath","channelIds"].includes(key)))throw Error("invalid");createPreparedDiscordSource("discord",{mode:"fields",...v})}catch{reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureDiscord(body.selection,signal),{saving:"Saving Discord selection.",saved:"Discord setup saved. The current connection has not been verified.",failed:"The Discord setup could not be saved.",retry:"Check the selection and try again."});return}if(body.action==="configure-proton-mail"){const row2=allRows().find(item=>item.source==="proton-mail");if(!authorization?.configureProtonMail||!row2||body.source!=="proton-mail"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureProtonMail(body.port,signal),{saving:"Saving the Proton Mail local port.",saved:"Proton Mail setup saved. The current connection has not been verified.",failed:"The Proton Mail setup could not be saved.",retry:"Check the local port and try again."});return}if(body.action==="configure-copyq"){const row2=allRows().find(item=>item.source==="copyq");if(!authorization?.configureCopyQ||!row2||body.source!=="copyq"||typeof body.executable!=="string"||body.executable.length<1||body.executable.length>512||body.executable.includes("\0")||!isAbsolute(body.executable)||typeof body.session!=="string"||!/^[\p{L}\p{N}_-]{0,16}$/u.test(body.session)){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureCopyQ(body.executable,body.session,signal),{saving:"Saving the CopyQ application and session.",saved:"CopyQ setup saved. The current connection has not been verified.",failed:"The CopyQ setup could not be saved.",retry:"Check the application path and session and try again."});return}if(body.action==="configure-owntracks"){const row2=allRows().find(item=>item.source==="owntracks");if(!authorization?.configureOwnTracks||!row2||body.source!=="owntracks"||!Number.isInteger(body.port)||Number(body.port)<1024||Number(body.port)>65535){reply(response,400,{error:"invalid_configuration"});return}configureSource(response,row2,signal=>authorization.configureOwnTracks(body.port,signal),{saving:"Saving the OwnTracks local port.",saved:"OwnTracks setup saved. The current connection has not been verified.",failed:"The OwnTracks setup could not be saved.",retry:"Check the local port and try again."});return}if(body.action==="configure-zotero"){const row2=allRows().find(item=>item.source==="zotero");if(!authorization?.configureZotero||!row2||body.source!=="zotero"||typeof body.libraryId!=="string"||!(/^[1-9][0-9]{0,19}$/.test(body.libraryId)||body.libraryType==="user"&&body.libraryId==="0")||!["user","group"].includes(String(body.libraryType))){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){reply(response,503,{error:"save_failed"});return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the Zotero library selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureZotero(body.libraryId,body.libraryType,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result||result.ok.state!=="configured"){row2.message="The Zotero selection could not be saved.";row2.nextStep="Check the library ID and local setup, then try again.";return}row2.message="Zotero selection saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The Zotero selection could not be saved.";row2.nextStep="Check the local setup, then try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}if(body.action==="configure-native-files"){const row2=allRows().find(item=>item.source===body.source),roots=body.roots;if(!authorization?.configureNativeFiles||!row2||typeof body.source!=="string"||!NATIVE_FILE_SOURCES.has(body.source)||!Array.isArray(roots)||roots.length!==1||typeof roots[0]!=="string"||roots[0].length<1||roots[0].length>512||roots[0].includes("\0")||!isAbsolute(roots[0])){reply(response,400,{error:"invalid_configuration"});return}if(closed){reply(response,410,{error:"closed"});return}if(active||activeSources.has(ctx)||busy(row2.source)){reply(response,409,{error:"connection_in_progress"});return}if(!invalidateRecoveryEvidence(ctx,row2.source)){row2.message="Progress could not be saved on this computer. The folder selection has not been saved.";row2.nextStep="Check that the data folder is writable, then try again.";reply(response,503,report());return}const stop2=new AbortController;interactionGeneration++;owned=stop2;activeSource=row2.source;activeSources.set(ctx,{source:row2.source,owner:token});delete row2.errorCode;row2.state="connecting";row2.read="not-attempted";row2.message="Saving the folder selection.";row2.nextStep="Please wait.";active=Promise.resolve().then(()=>withSetupProgress(body.source,stop2,()=>authorization.configureNativeFiles(row2.source,roots,stop2.signal))).then(result=>{if(closed)return;row2.state="pending";row2.read="not-attempted";if("err"in result){row2.message="The folder selection could not be saved.";row2.nextStep="Check that the folder exists and is accessible, then try again.";return}if(result.ok.state!=="configured"){row2.message="The folder selection needs further setup.";row2.nextStep="Check the folder and its permissions, then try again.";return}row2.message="Folder selection saved. The current connection has not been verified.";row2.nextStep=result.ok.next}).catch(()=>{if(!closed){row2.state="pending";row2.message="The folder selection could not be saved.";row2.nextStep="Check that the folder exists and is accessible, then try again."}}).finally(()=>finishSetup(row2,stop2));reply(response,202,report(true));return}const pendingReload=allRows().find(item=>item.source===body.source);if(pendingReload&&reloads.has(pendingReload.source)&&!closed&&!active){retainSetupReload(pendingReload);reply(response,200,report(true));return}const other=others.find(item=>item.source===body.source),row=rows.find(item=>item.source===body.source)??(other&&!other.catalogOnly&&connectableOther(other)&&["connect","read","authorize","authorize-readwise-mcp","authorize-gmail-write","reconnect-saved"].includes(body.action)?other:void 0);if(!row||row.source==="joplin"&&body.action!=="read"||row.registration==="deferred"){reply(response,400,{error:"unknown_source"});return}if(closed){reply(response,410,{error:"closed"});return}if(continuations.has(row.source)){reply(response,200,report(true));return}if(active){reply(response,activeSource===row.source?200:409,activeSource===row.source?report(true):{error:"connection_in_progress",activeSource});return}if(activeSources.has(ctx)){reply(response,409,{error:"connection_in_progress",activeSource:activeSources.get(ctx)?.source});return}if(busy(row.source)){reply(response,409,{error:"connection_in_progress",activeSource:row.source});return}if(row.state==="unavailable"){reply(response,409,{error:"source_unavailable"});return}if(body.action==="reconnect-saved"&&!supportsSavedReconnect(row.source)){reply(response,400,{error:"saved_reconnect_unsupported"});return}if(body.action==="authorize"&&["google-chrome","microsoft-edge"].includes(row.source)){reply(response,400,{error:"authorization_not_supported"});return}if(!invalidateRecoveryEvidence(ctx,row.source)){fail(row);row.message="Progress could not be saved on this computer. A new connection has not been started.";row.nextStep="Check that the data folder is writable, then try again.";reply(response,503,report());return}const repairLegacyClient=row.errorCode==="authorization_client_registration_required";const stop=new AbortController;interactionGeneration++;owned=stop;activeSource=row.source;activeSources.set(ctx,{source:row.source,owner:token});delete row.errorCode;row.state="connecting";row.read="not-attempted";row.message="Preparing to connect.";if(!other)row.nextStep="Please wait. You do not need to click again.";startRecovery(row,stop,body.action==="authorize"||body.action==="authorize-readwise-mcp"||body.action==="authorize-gmail-write",body.action==="read",repairLegacyClient,body.action==="reconnect-saved",body.action==="authorize-readwise-mcp",body.action==="authorize-gmail-write");reply(response,202,report(true))}server.requestTimeout=5e3;server.headersTimeout=5e3;server.keepAliveTimeout=1e3;await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error("Recovery listener unavailable.");origin=`http://127.0.0.1:${address.port}`;const timer=setTimeout(()=>{void session.close()},18e5);timer.unref();const gone=setInterval(()=>{if(lastSeen&&!active&&!continuations.size&&Date.now()-lastSeen>pageGoneMs)void session.close()},Math.min(15e3,Math.max(50,pageGoneMs/4)));gone.unref();const session={url:origin+"/#"+token,expiresAt,done,closed:closedPromise,snapshot:()=>report(),async request(input,signal){if(closed)return{status:410,body:{error:"closed"}};let body;try{body=JSON.stringify(input);if(typeof body!=="string")throw Error()}catch{return{status:400,body:{error:"invalid_request"}}}if(Buffer.byteLength(body)>MAX_RECOVERY_REQUEST_BYTES)return{status:413,body:{error:"too_large"}};const response=await fetch(origin+"/api",{method:"POST",redirect:"error",headers:{Origin:origin,"Content-Type":"application/json","X-Zortex-Recovery":token},body,signal});return{status:response.status,body:await response.json()}},close(){return closeTask??=(async()=>{closed=true;clearTimeout(timer);clearInterval(gone);owned?.abort();for(const pending of continuations.values())pending.stop.abort();for(const row of allRows()){clearHandoff(row);if(waiting.has(row.state)){row.state="pending";row.message="This connection session has ended.";row.nextStep=""}}server.closeAllConnections();await new Promise(resolve=>server.close(()=>resolve()));let waitTimer;await Promise.race([Promise.all([active,...[...continuations.values()].map(item=>item.task)]),new Promise(resolve=>{waitTimer=setTimeout(resolve,1e3)})]);if(waitTimer)clearTimeout(waitTimer);if(!active&&activeSources.get(ctx)?.owner===token)activeSources.delete(ctx);sessions.delete(ctx);if(!settled){settled=true;resolveDone()}resolveClosed()})()}};ctx.effect(()=>()=>session.close());complete();return session}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAutoSync}from"./auto-sync.js";import{beginRecoveryProgress,recoveryAuthorityProof}from"./recovery-progress.js";const automaticSourcePermission=recoveryAuthorityProof;export async function automaticSourceAllowed(ctx,source,signal){return await automaticSourcePermission(ctx,source,signal)!==void 0}export function createSelectedAutopilotSourcePolicy(ctx){const initial=new Map;const blocked=new Set;const enabled=source=>![...ctx.get("loader")?.entries()??[]].some(row=>row.options.id==="indra-source-"+source&&row.disabled);return async(source,signal)=>{if(blocked.has(source))return false;const refuse=()=>{blocked.add(source);return false};if(signal.aborted||!enabled(source))return refuse();try{const custody=ctx.get("zortexVaultStore")?.bindingCustody;if(!custody?.authoritySnapshot)return refuse();const captured=await custody.authoritySnapshot({kind:"selected-source",source});if(signal.aborted||!enabled(source)||!("ok"in captured)||captured.ok.source!==source||captured.ok.resolution.kind==="ambiguous_account")return refuse();const{inventory,selection,legacy,resolution}=captured.ok;if(resolution.kind==="resolved"&&!inventory)return refuse();const binding=inventory?.binding,audience=binding?.authority?.resource??binding?.provider;const grants=inventory?.grants.filter(grant=>grant.bindingId===binding.id&&grant.purpose==="L1"&&grant.audience===audience)??[];const denied=binding?binding.state!=="connected"||grants.length!==1||grants[0].state!=="active":legacy?.state==="disconnected";const previous=initial.get(source);if(!denied){initial.set(source,{requiresCurrent:true});return true}if(previous?.requiresCurrent)return refuse();const revision=JSON.stringify({binding:binding?[binding.id,binding.revision,binding.state]:null,grants:grants.map(grant=>[grant.id,grant.revision,grant.state,grant.scopeEpoch]).sort((a,b)=>String(a[0]).localeCompare(String(b[0]))),selection:selection?[selection.bindingId,selection.revision]:null,legacy});if(!previous){initial.set(source,{requiresCurrent:false,denied:revision});return true}return previous.denied===revision||refuse()}catch{return refuse()}}}export async function checkAutomaticSource(ctx,source,signal){const permission=await automaticSourcePermission(ctx,source,signal);if(permission===void 0)return{err:{code:signal.aborted?"aborted":"permission_denied"}};const progress=beginRecoveryProgress(ctx,source,Date.now,{ifIdle:true});progress.update("reading","connected");try{const result=await ctx.get("zortexConnectorHub").check(source,{signal,retention:"transient"});if(signal.aborted||await automaticSourcePermission(ctx,source,signal)!==permission){progress.finish({connectionState:"unverified",errorCode:"aborted"});return{err:{code:"aborted"}}}if("ok"in result){progress.finish({connectionState:"connected",authorityProof:permission,readiness:result.ok,...result.ok.operation.state==="succeeded"&&result.ok.operation.returned!==void 0?{returned:result.ok.operation.returned}:{}});return result}const code="err"in result?result.err.code:"unavailable";progress.finish({connectionState:"unverified",errorCode:code});return{err:{code}}}catch{progress.finish({connectionState:"unverified",errorCode:signal.aborted?"aborted":"unavailable"});return{err:{code:signal.aborted?"aborted":"unavailable"}}}}export function createResidentAutopilot(ports){const sources=new Map;return createAutoSync({sources:[],...ports.now?{now:ports.now}:{},async discoverSources(){const current=await ports.discover();sources.clear();for(const row of current)sources.set(row.source,row);return current.map(row=>row.source)},connected:async source=>sources.has(source)&&await ports.allowed(source),async run(source,signal){if(signal.aborted)return{err:{code:"aborted"}};const prepared=await ports.prepare(source,signal);if(prepared)return prepared;if(signal.aborted||!await ports.allowed(source))return{err:{code:"aborted"}};let connectedThisRun=false;const connect=async()=>{if(signal.aborted||!await ports.allowed(source))return{err:{code:"aborted"}};let result=await ports.active(source,signal);if("err"in result&&result.err.code==="not_found")result=await ports.connect(source,ports.requestId(),signal);if(!("ok"in result))return result.err.code==="connection_in_progress"?{err:{code:"authorization_pending"}}:result;if(result.ok.source!==source)return{err:{code:"job_source_mismatch"}};if(result.ok.state==="waiting-user"||result.ok.state==="connecting")return{err:{code:"authorization_pending"}};if(result.ok.state!=="connected")return{err:{code:result.ok.error?.code??(result.ok.state==="cancelled"?"aborted":"unavailable")}};connectedThisRun=true};if(sources.get(source)?.state!=="connected"){const pending=await connect();if(pending)return pending}if(signal.aborted||!await ports.allowed(source))return{err:{code:"aborted"}};let checked=await ports.check(source,signal);if("err"in checked&&!connectedThisRun&&["unauthenticated","login_required","authorization_required"].includes(checked.err.code)){const pending=await connect();if(pending)return pending;if(signal.aborted||!await ports.allowed(source))return{err:{code:"aborted"}};checked=await ports.check(source,signal)}if(!("ok"in checked))return checked;if(checked.ok.source!==source)return{err:{code:"invalid_readiness"}};if(signal.aborted||!await ports.allowed(source))return{err:{code:"aborted"}};ports.observed?.(source,checked.ok);if(checked.ok.operation.state==="succeeded")ports.verified?.(source,checked.ok);return{ok:{complete:true,appended:0}}}})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ok}from"@zortexhq/plugin-connector-framework/api";const failed=(source,errorCode,reason="unknown",retryability="none",nextStep)=>ok({source,state:"failed",reason,errorCode,retryability,...nextStep?{nextStep}:{}});function ready(source,value){if(value.source!==source)return failed(source,"invalid_readiness");if(value.basis==="actions"&&Number.isSafeInteger(value.actions)&&value.actions>0&&value.operation.state==="not-run")return ok({source,state:"
|
|
1
|
+
import{ok}from"@zortexhq/plugin-connector-framework/api";import{authorizationImage}from"@zortexhq/plugin-connector-core/api";import{nativeRecoveryAuthorizationUrl,protectedRecoveryFormUrl,reviewedRecoveryAuthorizationUrl}from"./recovery-authorization-url.js";const failed=(source,errorCode,reason="unknown",retryability="none",nextStep)=>ok({source,state:"failed",reason,errorCode,retryability,...nextStep?{nextStep}:{}});function ready(source,value){if(value.source!==source)return failed(source,"invalid_readiness");if(value.basis==="actions"&&Number.isSafeInteger(value.actions)&&value.actions>0&&value.operation.state==="not-run")return ok({source,state:"available",availability:"actions",actions:value.actions,operation:"not-run"});if(value.operation.state==="succeeded"&&(value.operation.returned===void 0&&value.basis==="actions"||Number.isSafeInteger(value.operation.returned)&&value.operation.returned>=0))return ok({source,state:"ready",availability:value.basis,...value.basis==="actions"&&Number.isSafeInteger(value.actions)?{actions:value.actions}:{},operation:"succeeded",...value.operation.returned!==void 0?{returned:value.operation.returned}:{}});return failed(source,value.basis==="actions"?"no_actions":"readiness_unverified","unknown","automatic","Zortex could not verify an available Action or bounded read.")}const retryableAuthorization=new Set(["unauthenticated","login_required","authorization_required","authorization_denied"]);export function createResidentEnsureReady(options){return async(source,providedSignal)=>{const signal=providedSignal??new AbortController().signal;if(signal.aborted)return failed(source,"aborted","unknown","automatic");try{const observed=await options.status(signal);if(!("ok"in observed))return failed(source,"err"in observed?observed.err.code:"unavailable","unavailable","automatic","Zortex could not inspect this source.");const state=observed.ok.find(row=>row.source===source);if(!state)return failed(source,"not_found","unavailable","after_configuration","Install or enable this source, then try again.");if(state.state==="unavailable"||state.registration==="deferred"||state.verification==="configuration-only")return failed(source,"configuration_required","configuration","after_configuration","This source is unavailable or its configuration has not been verified. Repair the reported source configuration before authorization.");if(state.state==="connected"){const checked=await options.check(source,signal);if("ok"in checked)return ready(source,checked.ok);if("err"in checked&&checked.err.code==="failed_precondition")return failed(source,"configuration_required","configuration","after_configuration","Zortex cannot use this connection until its product configuration or account binding is repaired. Repeating consent is not a configuration repair.");if(!("err"in checked)||!retryableAuthorization.has(checked.err.code))return failed(source,"err"in checked?checked.err.code:"unavailable","unknown","automatic","Zortex could not verify this source.")}let connected=await options.active(source,signal);if("err"in connected&&connected.err.code==="not_found")connected=await options.connect(source,options.requestId(),signal);else if("err"in connected&&connected.err.code==="connection_in_progress")connected=await options.active(source,signal);if(!("ok"in connected))return failed(source,"err"in connected?connected.err.code:"unavailable","authorization","automatic","Zortex could not start or recover the connection task.");const job=connected.ok;if(job.source!==source)return failed(source,"job_source_mismatch");if(job.state==="connecting")return ok({source,state:"connecting",jobId:job.id,recoveryHandle:job.id,retryability:"automatic"});if(job.state==="connected"){const checked=await options.check(source,signal);return"ok"in checked?ready(source,checked.ok):failed(source,"err"in checked?checked.err.code:"unavailable","unknown","automatic","The connection completed, but Zortex could not verify it.")}if(job.state==="waiting-user"){const pending={source,state:"connecting",jobId:job.id,recoveryHandle:job.id,reason:"authorization",retryability:"automatic"};if(job.expiresAt!==void 0&&(!Number.isFinite(Date.parse(job.expiresAt))||Date.parse(job.expiresAt)<=Date.now()))return ok({...pending,errorCode:"authorization_challenge_expired",nextStep:"The current provider challenge has expired. The Resident must recover this same authorization transaction before it can be continued."});const provider=job;const url=nativeRecoveryAuthorizationUrl(source,job.authorizationUrl)??reviewedRecoveryAuthorizationUrl(source,provider)??protectedRecoveryFormUrl(source,provider,true);const image=authorizationImage(job.authorizationImage);if(!url&&!image)return ok({...pending,errorCode:"authorization_handoff_unavailable",nextStep:"This provider transaction remains pending but has not supplied a validated destination or usable challenge. A background Resident cannot summon an absent host browser or computer tool."});const device=url&&job.devicePrompt?.kind==="device-code"&&/^[A-Z0-9-]{4,32}$/i.test(job.devicePrompt.userCode)?job.devicePrompt:void 0;const continuation={kind:"provider-authorization",executor:"calling-host",source,jobId:job.id,...Number.isSafeInteger(job.generation)&&job.generation>0?{generation:job.generation}:{},...typeof job.challengeRef==="string"&&job.challengeRef.length>0&&job.challengeRef.length<=512?{challengeRef:job.challengeRef}:{},...job.expiresAt?{expiresAt:job.expiresAt}:{},...url?{authorizationUrl:url}:{},...image?{authorizationImage:image}:{},...typeof job.instructions==="string"&&job.instructions.length<=4e3?{instructions:job.instructions}:{},...device?{devicePrompt:device}:{},resume:"retry-original-operation",background:"requires-active-host-capability"};return ok({...pending,continuation,nextStep:"Continue this exact provider transaction with the current host tools, preserving job and challenge identity. The Resident observes its callback and resumes automatically; retry the original operation with its same operationId after authorization succeeds."})}return failed(source,job.state==="cancelled"?"aborted":job.error?.code??"authorization_failed","authorization",job.state==="cancelled"?"after_user_action":"automatic","The connection did not complete.")}catch{return failed(source,signal.aborted?"aborted":"unavailable","unavailable","automatic","Zortex could not complete the readiness check.")}}}
|