@zortexhq/indra-v2.5 0.2.8 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/bin/codex-postinstall.mjs +1 -1
- package/dist/auto-sync.js +1 -1
- package/dist/cli-run.js +1 -1
- package/dist/codex-install.js +1 -1
- package/dist/codex-setup.js +1 -1
- package/dist/connector-worker.js +1 -1
- package/dist/content-find.js +2 -8
- package/dist/find-snapshots.js +1 -0
- package/dist/gateway.js +1 -1
- package/dist/imessage-sync.js +1 -0
- package/dist/mail-search-body.js +1 -0
- package/dist/match-excerpt.js +1 -0
- package/dist/native-connect.js +1 -0
- package/dist/native-level1-setup.js +1 -1
- package/dist/public-tool.js +1 -1
- package/dist/read-route.js +1 -0
- package/dist/recovery-support.js +1 -1
- package/dist/resident-host.js +2 -2
- package/dist/resident-jobs.js +1 -1
- package/dist/source-data.js +1 -1
- package/dist/supervised-sync.js +1 -1
- package/dist/sync-sources.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-computer-files/dist/catalog.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-computer-files/dist/index.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-computer-files/dist/policy.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-computer-files/dist/result.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-computer-files/package.json +18 -0
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/native-file-roots.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-imessage/dist/attributed-body.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-imessage/dist/chatdb-source.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-imessage/dist/connector.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-imessage/dist/index.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-imessage/dist/manifest.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-imessage/dist/sqlite-snapshot.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-imessage/package.json +16 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/api/index.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/computer-files-pages.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/computer-files.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/sources.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/package.json +5 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-catalog.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-renderer.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/galaxy-text.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/routes.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/snapshot.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/package.json +1 -0
- 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-galaxy-ui/src/integration/galaxy-renderer.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/live-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/portrait-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.js +1 -1
- package/node_modules/@zortexhq/plugin-google-auth/default-client.json +1 -0
- package/node_modules/@zortexhq/plugin-google-auth/dist/desktop-client.js +1 -1
- package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/search-text.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/current-records.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +13 -4
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +1 -1
- package/package.json +11 -7
- package/release-provenance.json +35 -21
- package/update-manifest.json +304 -118
package/README.md
CHANGED
|
@@ -86,6 +86,11 @@ the catalog. Keep the referenced installation in place. `indra setup codex
|
|
|
86
86
|
preserving its Vault binding and unrelated configuration; restart Codex afterward.
|
|
87
87
|
Plugin registration and MCP startup do not connect accounts.
|
|
88
88
|
|
|
89
|
+
On macOS, installation provisions the pinned CUA Driver and starts it in the
|
|
90
|
+
background. `indra setup computer-use` retries this step. To grant Accessibility
|
|
91
|
+
and Screen Recording in macOS, run `indra setup computer-use --grant-permissions`.
|
|
92
|
+
An existing Chrome profile can require its own browser grant.
|
|
93
|
+
|
|
89
94
|
## Background host and optional remote access
|
|
90
95
|
|
|
91
96
|
```sh
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{stat}from"node:fs/promises";const disabled=/^(0|false|off|no)$/i.test((process.env.ZORTEX_CODEX_SETUP??"").trim());if(!disabled){try{const installer=new URL("../dist/codex-install.js",import.meta.url);try{await stat(installer)}catch(error){if(error.code!=="ENOENT")throw error;const source=await Promise.all(["../src/codex-install.ts","../tsconfig.json"].map(async path=>{try{return(await stat(new URL(path,import.meta.url))).isFile()}catch{return false}}));if(source.every(Boolean)){process.stderr.write("indra: source checkout detected; build indra-v2, then rerun bin/codex-postinstall.mjs to prepare its Codex catalog.\n")}else throw Error("Installed Codex setup is missing. Reinstall the complete indra-v2 package, or set ZORTEX_CODEX_SETUP=0 to skip catalog preparation.")}if(await stat(installer).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error})){const{installCodexCatalog}=await import(installer.href);process.stdout.write(JSON.stringify(await installCodexCatalog())+"\n")}}catch(error){process.stderr.write("indra: Codex catalog preparation failed: "+(error instanceof Error?error.message:"unknown setup error")+"\n");process.exitCode=1}}
|
|
2
|
+
import{stat}from"node:fs/promises";const disabled=/^(0|false|off|no)$/i.test((process.env.ZORTEX_CODEX_SETUP??"").trim());if(!disabled){try{const installer=new URL("../dist/codex-install.js",import.meta.url);try{await stat(installer)}catch(error){if(error.code!=="ENOENT")throw error;const source=await Promise.all(["../src/codex-install.ts","../tsconfig.json"].map(async path=>{try{return(await stat(new URL(path,import.meta.url))).isFile()}catch{return false}}));if(source.every(Boolean)){process.stderr.write("indra: source checkout detected; build indra-v2, then rerun bin/codex-postinstall.mjs to prepare its Codex catalog.\n")}else throw Error("Installed Codex setup is missing. Reinstall the complete indra-v2 package, or set ZORTEX_CODEX_SETUP=0 to skip catalog preparation.")}if(await stat(installer).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error})){const{installCodexCatalog}=await import(installer.href);process.stdout.write(JSON.stringify(await installCodexCatalog())+"\n")}}catch(error){process.stderr.write("indra: Codex catalog preparation failed: "+(error instanceof Error?error.message:"unknown setup error")+"\n");process.exitCode=1}}if(process.platform==="darwin"&&await stat(new URL("../release-provenance.json",import.meta.url)).then(()=>true,()=>false)){try{const{setupCua}=await import("@zortexhq/plugin-connector-level1/api");const computerUse=await setupCua();process.stdout.write(JSON.stringify({computerUse})+"\n");if(computerUse.state==="install-failed")process.stderr.write("indra: "+computerUse.next+"\n")}catch{process.stderr.write("indra: Computer-use setup could not finish. Retry with indra setup computer-use.\n")}}
|
package/dist/auto-sync.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{Original}from"@zortexhq/plugin-connector-framework/api";import{browserReady,runSupervisedSource,sourceActive,WORKER_SYNC_SOURCES}from"./supervised-sync.js";import{createSourceData}from"./source-data.js";const INTERVAL_MS=15*6e4,BUSY_MS=6e4,AUTH_MS=30*6e4,ERROR_FIRST_MS=6e4,ERROR_MAX_MS=30*6e4;const DUE=/backoff not due until (\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z)/;export function createAutoSync(deps){const now=deps.now??Date.now,parallel=Math.max(1,deps.parallel??2),interval=deps.intervalMs??INTERVAL_MS;const rows=new Map(deps.sources.map(source=>[source,{source,state:"waiting",appended:0}]));const next=new Map,failures=new Map,running=new Map;let closed=false,paused=false,ticking;function settle(source,result){const row=rows.get(source),at=now();row.lastFinishedAt=new Date(at).toISOString();row.state=closed?"stopped":"waiting";const ok="ok"in result?result.ok:void 0;if(ok){failures.delete(source);delete row.errorCode;const appended=typeof ok.appended==="number"&&Number.isSafeInteger(ok.appended)&&ok.appended>0?ok.appended:0;if(row.complete!==false)row.appended=0;row.appended+=appended;row.complete=ok.complete===true;next.set(source,row.complete?at+interval:at)}else{const err="err"in result?result.err:void 0,code=err?.code??"unknown";row.errorCode=code;const due2=DUE.exec(err?.message??"")?.[1];if(due2&&Number.isFinite(Date.parse(due2)))next.set(source,Math.max(at,Date.parse(due2)));else if(code==="deadline_exceeded")next.set(source,at);else if(code==="resource_exhausted")next.set(source,at+BUSY_MS);else if(code==="unauthenticated"||code==="permission_denied"||code==="failed_precondition")next.set(source,at+AUTH_MS);else if(code==="aborted")next.set(source,at);else{const count=(failures.get(source)??0)+1;failures.set(source,count);next.set(source,at+Math.min(ERROR_MAX_MS,ERROR_FIRST_MS*2**(count-1)))}}const due=next.get(source);if(due!==void 0&&!closed)row.nextAt=new Date(due).toISOString()}function start(source){const row=rows.get(source),stop=new AbortController;row.state="running";delete row.nextAt;const task=(async()=>{let result;try{result=await deps.run(source,stop.signal)}catch{result=Original.errResult({code:"unavailable",layer:"connector",retryability:"transient",message:"Sync run did not finish."})}settle(source,result)})().finally(()=>running.delete(source));running.set(source,{stop,task})}async function tick(){if(closed||paused)return;for(const source of deps.sources){if(closed||paused||running.size>=parallel)return;if(running.has(source))continue;const due=next.get(source);if(due!==void 0&&due>now())continue;const row=rows.get(source);let connected=false;try{connected=await deps.connected(source)}catch{connected=false}if(closed||paused||running.size>=parallel)return;if(!connected){row.state="not-connected";delete row.nextAt;next.delete(source);continue}if(!next.has(source)&&deps.deferUntil){const saved=Date.parse(await deps.deferUntil(source)??"");if(Number.isFinite(saved)&&saved>now()){next.set(source,saved);row.nextAt=new Date(saved).toISOString();continue}}start(source)}}return{tick(){const current=(ticking??Promise.resolve()).then(tick);ticking=current.catch(()=>{});return current},async idle(){while(running.size)await Promise.allSettled([...running.values()].map(entry=>entry.task))},status(){return[...rows.values()].map(row=>({...row}))},enqueue(source){if(!closed&&rows.has(source))next.set(source,0)},async pause(){paused=true;for(const entry of running.values())entry.stop.abort();await Promise.allSettled([...running.values()].map(entry=>entry.task))},resume(){if(!closed)paused=false},async close(){closed=true;paused=true;for(const entry of running.values())entry.stop.abort();await Promise.allSettled([...running.values()].map(entry=>entry.task));for(const row of rows.values()){row.state="stopped";delete row.nextAt}}}}export function provideAutoSync(ctx,root,options={}){let sync;let residentRows=[];ctx.provide("indraSourceSync",{status:()=>sync?.status()??residentRows.map(row=>({...row}))});ctx.effect(()=>{if(!options.residentStatus){const running=startAutoSync(ctx,root,options);sync=running;return()=>{if(sync===running)sync=void 0;return running.close()}}let closed=false,timer;const poll=async()=>{try{residentRows=(await options.residentStatus()).map(row=>({...row}))}catch{residentRows=[]}if(!closed){timer=setTimeout(()=>void poll(),options.tickMs??2e3);timer.unref?.()}};void poll();return()=>{closed=true;if(timer)clearTimeout(timer);residentRows=[]}})}export function startAutoSync(ctx,root,options={}){const enabled=options.enabled??!/^(0|false|off|no)$/i.test((process.env.ZORTEX_AUTO_SYNC??"").trim());const sourceData=createSourceData(ctx);const bindings=async source=>{const found=await ctx.get("zortexVaultStore")?.bindingCustody?.bindings(source);return found&&"ok"in found?found.ok.filter(row=>row.state==="connected"):[]};const sync=createAutoSync({sources:enabled?WORKER_SYNC_SOURCES:[],async deferUntil(source){const selected=await bindings(source);const states=await Promise.all(selected.length?selected.map(row=>sourceData.read(source,row.id)):[sourceData.read(source)]);if(states.some(row=>!row?.nextAt))return;return states.map(row=>row.nextAt).sort()[0]},async connected(source){if(!sourceActive(ctx,source))return false;if(source==="google-chrome"||source==="microsoft-edge")return browserReady(source);if((await bindings(source)).length)return true;const selected=await ctx.get("zortexVaultStore")?.connection(source);return!!selected&&Original.isOk(selected)&&selected.ok?.state==="connected"},async run(source,signal){const selected=await bindings(source);let complete=true,appended=0;for(const bindingId of selected.length?selected.map(row=>row.id):[void 0]){if(signal.aborted)return{err:{code:"aborted"}};const settings=bindingId?{bindingId}:void 0;const result=await(options.run?.(source,signal,settings)??runSupervisedSource(ctx,root,source,randomUUID(),{signal,...settings}));const value="ok"in result?result.ok:void 0;if(!value)return result;complete&&=value.complete===true;appended+=typeof value.appended==="number"?value.appended:0}return{ok:{complete,appended}}}});let timer,closed=false,wake=()=>{};const done=(async()=>{if(!enabled)return;const stopped=new Promise(resolve=>{wake=resolve});await Promise.race([ctx.get("loader")?.await(),stopped]);while(!closed){await sync.tick().catch(()=>{});if(closed)break;await new Promise(resolve=>{wake=resolve;timer=setTimeout(resolve,options.tickMs??1e4);timer.unref?.()})}})();return{...sync,done,enqueue(source){sync.enqueue(source);wake()},pause:()=>sync.pause(),resume(){sync.resume();wake()},async close(){closed=true;if(timer)clearTimeout(timer);wake();await sync.close();await done}}}
|
|
1
|
+
import{randomUUID}from"node:crypto";import{Original}from"@zortexhq/plugin-connector-framework/api";import{browserReady,runSupervisedSource,sourceActive,WORKER_SYNC_SOURCES}from"./supervised-sync.js";import{createSourceData}from"./source-data.js";const INTERVAL_MS=15*6e4,BUSY_MS=6e4,AUTH_MS=30*6e4,ERROR_FIRST_MS=6e4,ERROR_MAX_MS=30*6e4;const DUE=/backoff not due until (\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z)/;export function createAutoSync(deps){const now=deps.now??Date.now,parallel=Math.max(1,deps.parallel??2),interval=deps.intervalMs??INTERVAL_MS;const rows=new Map(deps.sources.map(source=>[source,{source,state:"waiting",appended:0}]));const next=new Map,failures=new Map,running=new Map;let closed=false,paused=false,ticking;function settle(source,result){const row=rows.get(source),at=now();row.lastFinishedAt=new Date(at).toISOString();row.state=closed?"stopped":"waiting";const ok="ok"in result?result.ok:void 0;if(ok){failures.delete(source);delete row.errorCode;const appended=typeof ok.appended==="number"&&Number.isSafeInteger(ok.appended)&&ok.appended>0?ok.appended:0;if(row.complete!==false)row.appended=0;row.appended+=appended;row.complete=ok.complete===true;next.set(source,row.complete||deps.refreshOnly?.(source)?at+interval:at)}else{const err="err"in result?result.err:void 0,code=err?.code??"unknown";row.errorCode=code;const due2=DUE.exec(err?.message??"")?.[1];if(due2&&Number.isFinite(Date.parse(due2)))next.set(source,Math.max(at,Date.parse(due2)));else if(code==="deadline_exceeded")next.set(source,at);else if(code==="resource_exhausted")next.set(source,at+BUSY_MS);else if(code==="unauthenticated"||code==="permission_denied"||code==="failed_precondition")next.set(source,at+AUTH_MS);else if(code==="aborted")next.set(source,at);else{const count=(failures.get(source)??0)+1;failures.set(source,count);next.set(source,at+Math.min(ERROR_MAX_MS,ERROR_FIRST_MS*2**(count-1)))}}const due=next.get(source);if(due!==void 0&&!closed)row.nextAt=new Date(due).toISOString()}function start(source){const row=rows.get(source),stop=new AbortController;row.state="running";delete row.nextAt;const task=(async()=>{let result;try{result=await deps.run(source,stop.signal)}catch{result=Original.errResult({code:"unavailable",layer:"connector",retryability:"transient",message:"Sync run did not finish."})}settle(source,result)})().finally(()=>running.delete(source));running.set(source,{stop,task})}async function tick(){if(closed||paused)return;for(const source of deps.sources){if(closed||paused||running.size>=parallel)return;if(running.has(source))continue;const due=next.get(source);if(due!==void 0&&due>now())continue;const row=rows.get(source);let connected=false;try{connected=await deps.connected(source)}catch{connected=false}if(closed||paused||running.size>=parallel)return;if(!connected){row.state="not-connected";delete row.nextAt;next.delete(source);continue}if(!next.has(source)&&deps.deferUntil){const saved=Date.parse(await deps.deferUntil(source)??"");if(Number.isFinite(saved)&&saved>now()){next.set(source,saved);row.nextAt=new Date(saved).toISOString();continue}}start(source)}}return{tick(){const current=(ticking??Promise.resolve()).then(tick);ticking=current.catch(()=>{});return current},async idle(){while(running.size)await Promise.allSettled([...running.values()].map(entry=>entry.task))},status(){return[...rows.values()].map(row=>({...row}))},enqueue(source){if(!closed&&rows.has(source))next.set(source,0)},async pause(){paused=true;for(const entry of running.values())entry.stop.abort();await Promise.allSettled([...running.values()].map(entry=>entry.task))},resume(){if(!closed)paused=false},async close(){closed=true;paused=true;for(const entry of running.values())entry.stop.abort();await Promise.allSettled([...running.values()].map(entry=>entry.task));for(const row of rows.values()){row.state="stopped";delete row.nextAt}}}}export function provideAutoSync(ctx,root,options={}){let sync;let residentRows=[];ctx.provide("indraSourceSync",{status:()=>sync?.status()??residentRows.map(row=>({...row}))});ctx.effect(()=>{if(!options.residentStatus){const running=startAutoSync(ctx,root,options);sync=running;return()=>{if(sync===running)sync=void 0;return running.close()}}let closed=false,timer;const poll=async()=>{try{residentRows=(await options.residentStatus()).map(row=>({...row}))}catch{residentRows=[]}if(!closed){timer=setTimeout(()=>void poll(),options.tickMs??2e3);timer.unref?.()}};void poll();return()=>{closed=true;if(timer)clearTimeout(timer);residentRows=[]}})}export function startAutoSync(ctx,root,options={}){const enabled=options.enabled??!/^(0|false|off|no)$/i.test((process.env.ZORTEX_AUTO_SYNC??"").trim());const sourceData=createSourceData(ctx);const bindings=async source=>{const found=await ctx.get("zortexVaultStore")?.bindingCustody?.bindings(source);return found&&"ok"in found?found.ok.filter(row=>row.state==="connected"):[]};const sync=createAutoSync({sources:enabled?[...WORKER_SYNC_SOURCES.filter(source=>source!=="imessage"),"computer-files"]:[],refreshOnly:source=>source==="computer-files",async deferUntil(source){const selected=await bindings(source);const states=await Promise.all(selected.length?selected.map(row=>sourceData.read(source,row.id)):[sourceData.read(source)]);if(states.some(row=>!row?.nextAt))return;return states.map(row=>row.nextAt).sort()[0]},async connected(source){if(source==="computer-files"){const state=await ctx.get("zortexComputerFiles")?.status();return!!state&&"ok"in state&&state.ok.enabled&&state.ok.state!=="paused"}if(!sourceActive(ctx,source))return false;if(source==="google-chrome"||source==="microsoft-edge")return browserReady(source);if((await bindings(source)).length)return true;const selected=await ctx.get("zortexVaultStore")?.connection(source);return!!selected&&Original.isOk(selected)&&selected.ok?.state==="connected"},async run(source,signal){if(source==="computer-files"){const result=await ctx.get("zortexComputerFiles")?.scan({signal});if(result&&"ok"in result)return{ok:{complete:!result.ok.partial,appended:0}};return result&&"err"in result?result:{err:{code:"unavailable"}}}const selected=await bindings(source);let complete=true,appended=0;for(const bindingId of selected.length?selected.map(row=>row.id):[void 0]){if(signal.aborted)return{err:{code:"aborted"}};const settings=bindingId?{bindingId}:void 0;const result=await(options.run?.(source,signal,settings)??runSupervisedSource(ctx,root,source,randomUUID(),{signal,...settings}));const value="ok"in result?result.ok:void 0;if(!value)return result;complete&&=value.complete===true;appended+=typeof value.appended==="number"?value.appended:0}return{ok:{complete,appended}}}});let timer,closed=false,wake=()=>{};const done=(async()=>{if(!enabled)return;const stopped=new Promise(resolve=>{wake=resolve});await Promise.race([ctx.get("loader")?.await(),stopped]);while(!closed){await sync.tick().catch(()=>{});if(closed)break;await new Promise(resolve=>{wake=resolve;timer=setTimeout(resolve,options.tickMs??1e4);timer.unref?.()})}})();return{...sync,done,enqueue(source){sync.enqueue(source);wake()},pause:()=>sync.pause(),resume(){sync.resume();wake()},async close(){closed=true;if(timer)clearTimeout(timer);wake();await sync.close();await done}}}
|
package/dist/cli-run.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolve,isAbsolute}from"node:path";import{readFile}from"node:fs/promises";import{randomUUID}from"node:crypto";import{fileURLToPath}from"node:url";import{openProduct}from"./profile.js";import{runHostCommand}from"./resident-host.js";import{startResident,residentSync,residentConnect,residentConnectJob,residentCancelConnect,residentGatewayCall,residentEnsureReady,residentCheck,residentRead,residentInvoke}from"./resident-platform.js";import{createGateway}from"./gateway.js";import{startMcp}from"./mcp.js";import{launchWeb}from"./web.js";import{usageOutcome,withFeedbackFlow,createTraceRecorder}from"@zortexhq/plugin-telemetry/api";import{waitForAuthorization}from"./authorization.js";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{attributeProductInstallation}from"./installation-origin.js";import{configuredVaultRoot}from"./default-root.js";import{productUpdater}from"./auto-update.js";import{runningProductVersion}from"./update-telemetry.js";import{prepareCodexPlugin}from"./codex-setup.js";import{installCodexCatalog}from"./codex-install.js";const USAGE="indra --root <absolute Vault directory> <search|feedback|plugins|vault|status|connect|sync|action|manage|mcp|host>";const HELP={usage:USAGE,commands:{help:"Print command help.",connect:"Open one source connection gateway: --source <source>. Complete OAuth, QR pairing or local permission with your existing browser and computer tools. --presentation return-url prints the link without opening it. The command waits for provider verification.",search:"Read the Vault with --sql <query>. Credentials and private state are excluded.",actions:"Discover installed source actions with --json.",action:"Run a discovered source action with --json.",sync:"Read an authorized source into the Vault; --source <source> resumes its saved cursor.",status:"Show connection, fleet and process status as JSON.",feedback:"Rate a recent operation with fixed choices. --list shows receipts; --json submits programmatic feedback.",host:"Manage the background data host: start, stop, status, enable, disable, account-link or local-cloud.",mcp:"Expose the shared agent tools. Starting MCP does not connect accounts.",web:"Explicitly open the management application.",update:"Check and apply available updates.","setup codex":"Register the existing installation with Codex."}};const entrypoint=fileURLToPath(new URL("./cli.js",import.meta.url));export async function runIndraCli(argv=process.argv.slice(2)){const args=[...argv];if(args.length===1&&["--version","-v"].includes(args[0])){print({version:JSON.parse(await readFile(new URL("../package.json",import.meta.url),"utf8")).version});return}function flag(name){const at=args.indexOf(name);if(at<0)return void 0;const value=args[at+1];if(!value||value.startsWith("--"))throw Error("Missing "+name);args.splice(at,2);return value}if(args[0]==="web"&&!args.includes("--help"))return launchWeb(args.slice(1));if(!args.length||args.includes("--help")||args.includes("-h")||(args[0]==="help"||args[0]==="--root"&&args[2]==="help")){print(HELP);return}if(args[0]==="northstar"||args[0]==="--root"&&args[2]==="northstar"){const selectedRoot=flag("--root");args.shift();const operation=args.shift(),ref=flag("--install-ref");if(operation!=="attribute"||!ref||args.length)throw Error("Use indra northstar attribute --install-ref <website source code> [--root <absolute Vault directory>].");const root2=selectedRoot??await configuredVaultRoot({catalogFile:fileURLToPath(new URL("../codex/plugins/zortex/.mcp.json",import.meta.url))});if(!isAbsolute(root2))throw Error("Vault directory must be absolute.");print({ok:await attributeProductInstallation(resolve(root2),ref),note:"Website source saved locally. Usage is sent only when Zortex runs with telemetry enabled and network access. This is an installation identity, not a verified person."});return}if(args[0]==="setup"&&args[1]==="codex"){if(args.length===3&&args[2]==="--refresh"){print({ok:await installCodexCatalog({refresh:true})});return}args.splice(0,2);const output=flag("--out"),root2=flag("--root");if(!output||!root2||args.length)throw Error("Use indra setup codex --out <new absolute directory> --root <absolute Vault directory>, or indra setup codex --refresh.");print({ok:await prepareCodexPlugin({output,root:root2})});return}const selected=flag("--root");if(!selected||!isAbsolute(selected))throw Error("Use "+USAGE+". Run indra help for details.");const root=resolve(selected),command=args.shift();if(command==="feedback"){await(await import("./product-feedback.js")).bootstrapProductFeedback(["--root",root,"feedback",...args]);return}if(command==="host"){const result=await runHostCommand(root,args);if(result!==void 0)print(result);return}if(!["search","sql","plugins","vault","status","connect","sync","actions","action","manage","mcp","instruction","handbook"].includes(command??""))throw Error("Unknown command. Run indra help.");let resident;const ensureResident=()=>resident??=startResident(root,entrypoint).finally(()=>{resident=void 0});const app=await openProduct(root),gateway=createGateway(app.context,root,{entrypoint:"cli",resident:async(request,signal)=>{await ensureResident();return residentGatewayCall(root,request,signal)},ensureReady:async(source,signal)=>{await ensureResident();return residentEnsureReady(root,source,signal)},check:async(source,signal)=>{await ensureResident();return residentCheck(root,source,signal)},runWorkerSync:async(source,requestId,options)=>{await ensureResident();return residentSync(root,source,requestId,options)},read:async(source,request,signal)=>{await ensureResident();return residentRead(root,source,request,signal)},invoke:async(request,signal)=>{await ensureResident();return residentInvoke(root,request,signal)}});const observeUpdate=async normalLaunch=>{const posthog=app.context.get("zortexPostHog");if(posthog)await productUpdater.observe({runningVersion:await runningProductVersion,normalLaunch,record:receipt=>posthog.recordUpdateAttempt(receipt)}).catch(()=>{})};try{await observeUpdate(false);if(command==="mcp"){if(args.length)throw Error("Unknown MCP arguments.");await ensureResident();const handle=startMcp(gateway,{onUpdateObservation:observeUpdate,telemetry:()=>app.context.get("zortexTelemetry")});await new Promise(done=>{const close=()=>{process.stdin.removeListener("end",close);process.removeListener("SIGINT",close);process.removeListener("SIGTERM",close);void handle.close().finally(done)};process.stdin.once("end",close);process.once("SIGINT",close);process.once("SIGTERM",close)});return}const raw=flag("--json");let operation=command??"",input=raw?JSON.parse(raw):{};if(command==="search"||command==="sql"){operation="search";if(!raw)input={sql:flag("--sql")}}if(command==="plugins"||command==="vault"||command==="status"){operation="manage";if(!raw)input={what:command}}if(command==="connect"){const source=flag("--source"),location=flag("--location"),presentation=flag("--presentation")??"open";if(!source||!/^[a-z][a-z0-9-]{0,63}$/.test(source))throw Error("Pass --source <lowercase connector id>.");if(raw||args.length||!["open","return-url"].includes(presentation))throw Error("Use connect --source <source> [--presentation open|return-url].");if(location){if(source!=="chrome-history"||raw||args.length)throw Error("Directory selection is supported only for Chrome.");await withFeedbackFlow(source,async()=>{const metrics=()=>app.context.get("zortexTelemetry"),trace=createTraceRecorder(metrics,source);await trace.step("source_selected","started");const started=performance.now(),result2=await app.context.zortexLocalSourceAccess.connect(source,resolve(location));const reason="err"in result2&&result2.err.code==="not_found"?"local_directory_unavailable":"provider_error";await trace.step("source_selected","err"in result2?"failed":"completed","err"in result2?{reason}:{});const observation={source,outcome:usageOutcome(result2),durationMs:Math.min(864e5,performance.now()-started),internal:true};const saved=await metrics()?.record({operation:"connector.connect",...observation});if(saved&&"err"in saved)process.stderr.write("indra feedback: connection observation was not recorded.\n");if("err"in result2){const final=await metrics()?.record({operation:"connector.authorization",...observation,code:reason,trace:{flowId:trace.flowId,stage:"authorization_finished",state:"failed",mode:"manual",trigger:"tool"}});if(final&&"err"in final)process.stderr.write("indra feedback: authorization observation was not recorded.\n")}print(result2)},{flowId:randomUUID(),source,mode:"manual",trigger:"tool"});return}await ensureResident();const stop=new AbortController,cancel=()=>stop.abort();process.once("SIGINT",cancel);process.once("SIGTERM",cancel);let job;try{const result2=await residentConnect(root,source,randomUUID(),stop.signal,{automatic:false,manualPresentation:"return-url"});job="ok"in result2&&result2.ok&&typeof result2.ok==="object"?result2.ok:void 0;if(job?.state!=="waiting-user"||!job.id){print(result2);return}let opened=false;if(presentation==="open"&&job.authorizationUrl)try{await openConnectionUrl(job.authorizationUrl);opened=true}catch{}print({...result2,opened,waitingForAgent:true});const signature=value=>JSON.stringify([value.authorizationUrl,value.instructions,value.authorizationImage,value.devicePrompt]);let seen=signature(job);print(await waitForAuthorization(async id=>{const next=await residentConnectJob(root,id,stop.signal);if("ok"in next&&next.ok.state==="waiting-user"&&signature(next.ok)!==seen){seen=signature(next.ok);print({ok:next.ok,waitingForAgent:true})}return next},job.id,{signal:stop.signal}))}finally{if(stop.signal.aborted&&job&&Number.isSafeInteger(job.generation)&&job.challengeRef)await residentCancelConnect(root,job.id,job.generation,job.challengeRef).catch(()=>{});process.removeListener("SIGINT",cancel);process.removeListener("SIGTERM",cancel)}return}if(command==="sync"){operation="action";const source=flag("--source")??"chrome-history",requestId=flag("--request-id");input={name:"connector.sync",params:{source,...requestId?{requestId}:{}}}}if(args.length)throw Error("Unknown CLI arguments.");const result=await gateway.call(operation,input);if(result&&typeof result==="object"&&"ok"in result)await observeUpdate(true);print(result)}finally{try{await app.context.get("zortexConnectorHub")?.settleObservations?.({closing:true});const sent=await app.context.get("zortexPostHog")?.flush({wait:true});if(sent&&"err"in sent)process.stderr.write("indra feedback: delivery pending; retained for the next run.\n")}finally{await app.close()}}}function print(result){process.stdout.write(JSON.stringify(result)+"\n");if(result&&typeof result==="object"&&"err"in result)process.exitCode=2}
|
|
1
|
+
import{resolve,isAbsolute}from"node:path";import{readFile}from"node:fs/promises";import{randomUUID}from"node:crypto";import{fileURLToPath}from"node:url";import{openProduct}from"./profile.js";import{runHostCommand}from"./resident-host.js";import{startResident,residentSync,residentConnect,residentConnectJob,residentCancelConnect,residentGatewayCall,residentEnsureReady,residentCheck,residentRead,residentInvoke}from"./resident-platform.js";import{createGateway}from"./gateway.js";import{startMcp}from"./mcp.js";import{launchWeb}from"./web.js";import{usageOutcome,withFeedbackFlow,createTraceRecorder}from"@zortexhq/plugin-telemetry/api";import{waitForAuthorization}from"./authorization.js";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{setupCua}from"@zortexhq/plugin-connector-level1/api";import{attributeProductInstallation}from"./installation-origin.js";import{configuredVaultRoot}from"./default-root.js";import{productUpdater}from"./auto-update.js";import{runningProductVersion}from"./update-telemetry.js";import{prepareCodexPlugin,registerCodexPlugin}from"./codex-setup.js";import{installCodexCatalog}from"./codex-install.js";const USAGE="indra --root <absolute Vault directory> <search|feedback|plugins|vault|status|connect|sync|action|manage|mcp|host>";const HELP={usage:USAGE,commands:{help:"Print command help.",connect:"Open one source connection gateway: --source <source>. Complete OAuth, QR pairing or local permission with your existing browser and computer tools. --presentation return-url prints the link without opening it. The command waits for provider verification.",search:"Read the Vault with --sql <query>. Credentials and private state are excluded.",actions:"Discover installed source actions with --json.",action:"Run a discovered source action with --json.",sync:"Read an authorized source into the Vault; --source <source> resumes its saved cursor.",status:"Show connection, fleet and process status as JSON.",feedback:"Rate a recent operation with fixed choices. --list shows receipts; --json submits programmatic feedback.",host:"Manage the background data host: start, stop, status, enable, disable, account-link or local-cloud.",mcp:"Expose the shared agent tools. Starting MCP does not connect accounts.",web:"Explicitly open the management application.",update:"Check and apply available updates.","setup codex":"Generate the Codex install surface; add --register to also run the two Codex registration commands.","setup computer-use":"Install or restart the macOS computer-use driver. Add --grant-permissions to open its macOS permission setup."}};const entrypoint=fileURLToPath(new URL("./cli.js",import.meta.url));export async function runIndraCli(argv=process.argv.slice(2)){const args=[...argv];if(args.length===1&&["--version","-v"].includes(args[0])){print({version:JSON.parse(await readFile(new URL("../package.json",import.meta.url),"utf8")).version});return}function flag(name){const at=args.indexOf(name);if(at<0)return void 0;const value=args[at+1];if(!value||value.startsWith("--"))throw Error("Missing "+name);args.splice(at,2);return value}if(args[0]==="web"&&!args.includes("--help"))return launchWeb(args.slice(1));if(!args.length||args.includes("--help")||args.includes("-h")||(args[0]==="help"||args[0]==="--root"&&args[2]==="help")){print(HELP);return}if(args[0]==="northstar"||args[0]==="--root"&&args[2]==="northstar"){const selectedRoot=flag("--root");args.shift();const operation=args.shift(),ref=flag("--install-ref");if(operation!=="attribute"||!ref||args.length)throw Error("Use indra northstar attribute --install-ref <website source code> [--root <absolute Vault directory>].");const root2=selectedRoot??await configuredVaultRoot({catalogFile:fileURLToPath(new URL("../codex/plugins/zortex/.mcp.json",import.meta.url))});if(!isAbsolute(root2))throw Error("Vault directory must be absolute.");print({ok:await attributeProductInstallation(resolve(root2),ref),note:"Website source saved locally. Usage is sent only when Zortex runs with telemetry enabled and network access. This is an installation identity, not a verified person."});return}if(args[0]==="setup"&&args[1]==="codex"){if(args.length===3&&args[2]==="--refresh"){print({ok:await installCodexCatalog({refresh:true})});return}args.splice(0,2);const register=args.includes("--register");if(register)args.splice(args.indexOf("--register"),1);const output=flag("--out"),root2=flag("--root");if(!output||!root2||args.length)throw Error("Use indra setup codex --out <new absolute directory> --root <absolute Vault directory> [--register], or indra setup codex --refresh.");const prepared=await prepareCodexPlugin({output,root:root2});const packaged=process.platform==="darwin"&&await readFile(new URL("../release-provenance.json",import.meta.url)).then(()=>true,()=>false);const computerUse=packaged?await setupCua():void 0;print({ok:prepared,...register?{registration:await registerCodexPlugin(output)}:{},...computerUse?{computerUse}:{}});return}if(args[0]==="setup"&&args[1]==="computer-use"){const grantPermissions=args[2]==="--grant-permissions";if(args.length!==(grantPermissions?3:2))throw Error("Use indra setup computer-use [--grant-permissions].");print(await setupCua({grantPermissions}));return}const selected=flag("--root");if(!selected||!isAbsolute(selected))throw Error("Use "+USAGE+". Run indra help for details.");const root=resolve(selected),command=args.shift();if(command==="feedback"){await(await import("./product-feedback.js")).bootstrapProductFeedback(["--root",root,"feedback",...args]);return}if(command==="host"){const result=await runHostCommand(root,args);if(result!==void 0)print(result);return}if(!["search","sql","plugins","vault","status","connect","sync","actions","action","manage","mcp","instruction","handbook"].includes(command??""))throw Error("Unknown command. Run indra help.");let resident;const ensureResident=()=>resident??=startResident(root,entrypoint).finally(()=>{resident=void 0});const app=await openProduct(root),gateway=createGateway(app.context,root,{entrypoint:"cli",resident:async(request,signal)=>{await ensureResident();return residentGatewayCall(root,request,signal)},ensureReady:async(source,signal)=>{await ensureResident();return residentEnsureReady(root,source,signal)},check:async(source,signal)=>{await ensureResident();return residentCheck(root,source,signal)},runWorkerSync:async(source,requestId,options)=>{await ensureResident();return residentSync(root,source,requestId,options)},read:async(source,request,signal)=>{await ensureResident();return residentRead(root,source,request,signal)},invoke:async(request,signal)=>{await ensureResident();return residentInvoke(root,request,signal)}});const observeUpdate=async normalLaunch=>{const posthog=app.context.get("zortexPostHog");if(posthog)await productUpdater.observe({runningVersion:await runningProductVersion,normalLaunch,record:receipt=>posthog.recordUpdateAttempt(receipt)}).catch(()=>{})};try{await observeUpdate(false);if(command==="mcp"){if(args.length)throw Error("Unknown MCP arguments.");await ensureResident();const handle=startMcp(gateway,{onUpdateObservation:observeUpdate,telemetry:()=>app.context.get("zortexTelemetry")});await new Promise(done=>{const close=()=>{process.stdin.removeListener("end",close);process.removeListener("SIGINT",close);process.removeListener("SIGTERM",close);void handle.close().finally(done)};process.stdin.once("end",close);process.once("SIGINT",close);process.once("SIGTERM",close)});return}const raw=flag("--json");let operation=command??"",input=raw?JSON.parse(raw):{};if(command==="search"||command==="sql"){operation="search";if(!raw)input={sql:flag("--sql")}}if(command==="plugins"||command==="vault"||command==="status"){operation="manage";if(!raw)input={what:command}}if(command==="connect"){const source=flag("--source"),location=flag("--location"),presentation=flag("--presentation")??"open";if(!source||!/^[a-z][a-z0-9-]{0,63}$/.test(source))throw Error("Pass --source <lowercase connector id>.");if(raw||args.length||!["open","return-url"].includes(presentation))throw Error("Use connect --source <source> [--presentation open|return-url].");if(location){if(source!=="chrome-history"||raw||args.length)throw Error("Directory selection is supported only for Chrome.");await withFeedbackFlow(source,async()=>{const metrics=()=>app.context.get("zortexTelemetry"),trace=createTraceRecorder(metrics,source);await trace.step("source_selected","started");const started=performance.now(),result2=await app.context.zortexLocalSourceAccess.connect(source,resolve(location));const reason="err"in result2&&result2.err.code==="not_found"?"local_directory_unavailable":"provider_error";await trace.step("source_selected","err"in result2?"failed":"completed","err"in result2?{reason}:{});const observation={source,outcome:usageOutcome(result2),durationMs:Math.min(864e5,performance.now()-started),internal:true};const saved=await metrics()?.record({operation:"connector.connect",...observation});if(saved&&"err"in saved)process.stderr.write("indra feedback: connection observation was not recorded.\n");if("err"in result2){const final=await metrics()?.record({operation:"connector.authorization",...observation,code:reason,trace:{flowId:trace.flowId,stage:"authorization_finished",state:"failed",mode:"manual",trigger:"tool"}});if(final&&"err"in final)process.stderr.write("indra feedback: authorization observation was not recorded.\n")}print(result2)},{flowId:randomUUID(),source,mode:"manual",trigger:"tool"});return}await ensureResident();const stop=new AbortController,cancel=()=>stop.abort();process.once("SIGINT",cancel);process.once("SIGTERM",cancel);let job;try{const result2=await residentConnect(root,source,randomUUID(),stop.signal,{automatic:false,manualPresentation:"return-url"});job="ok"in result2&&result2.ok&&typeof result2.ok==="object"?result2.ok:void 0;if(job?.state!=="waiting-user"||!job.id){print(result2);return}let opened=false;if(presentation==="open"&&job.authorizationUrl)try{await openConnectionUrl(job.authorizationUrl);opened=true}catch{}print({...result2,opened,waitingForAgent:true});const signature=value=>JSON.stringify([value.authorizationUrl,value.instructions,value.authorizationImage,value.devicePrompt]);let seen=signature(job);print(await waitForAuthorization(async id=>{const next=await residentConnectJob(root,id,stop.signal);if("ok"in next&&next.ok.state==="waiting-user"&&signature(next.ok)!==seen){seen=signature(next.ok);print({ok:next.ok,waitingForAgent:true})}return next},job.id,{signal:stop.signal}))}finally{if(stop.signal.aborted&&job&&Number.isSafeInteger(job.generation)&&job.challengeRef)await residentCancelConnect(root,job.id,job.generation,job.challengeRef).catch(()=>{});process.removeListener("SIGINT",cancel);process.removeListener("SIGTERM",cancel)}return}if(command==="sync"){operation="action";const source=flag("--source")??"chrome-history",requestId=flag("--request-id");input={name:"connector.sync",params:{source,...requestId?{requestId}:{}}}}if(args.length)throw Error("Unknown CLI arguments.");const result=await gateway.call(operation,input);if(result&&typeof result==="object"&&"ok"in result)await observeUpdate(true);print(result)}finally{try{await app.context.get("zortexConnectorHub")?.settleObservations?.({closing:true});const sent=await app.context.get("zortexPostHog")?.flush({wait:true});if(sent&&"err"in sent)process.stderr.write("indra feedback: delivery pending; retained for the next run.\n")}finally{await app.close()}}}function print(result){process.stdout.write(JSON.stringify(result)+"\n");if(result&&typeof result==="object"&&"err"in result)process.exitCode=2}
|
package/dist/codex-install.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{lstat,readFile,realpath,writeFile}from"node:fs/promises";import{execFile}from"node:child_process";import{promisify,isDeepStrictEqual}from"node:util";import{join,resolve,isAbsolute}from"node:path";import{homedir}from"node:os";import{fileURLToPath}from"node:url";import{prepareCodexPlugin,codexMcpConfiguration}from"./codex-setup.js";import{defaultVaultRoot}from"./default-root.js";const exec=promisify(execFile);async function refreshInstalledCodexPlugin(output,prepared){const result=(state,detail)=>({state,...detail?{detail}:{}});try{const codexHome=process.env.CODEX_HOME||join(homedir(),".codex");const config=join(codexHome,"config.toml");try{await lstat(config)}catch(error){if(error.code==="ENOENT")return result("not-installed");throw error}const plugin=join(output,"plugins","zortex");const[manifest,mcp,pkg]=await Promise.all([readFile(join(plugin,".codex-plugin","plugin.json"),"utf8").then(JSON.parse),readFile(join(plugin,".mcp.json"),"utf8").then(JSON.parse),readFile(new URL("../package.json",import.meta.url),"utf8").then(JSON.parse)]);const cli=fileURLToPath(new URL("./cli.js",import.meta.url));if(manifest.name!=="zortex"||manifest.version!==pkg.version||mcp?.mcpServers?.zortex?.args?.[0]!==cli||mcp?.mcpServers?.zortex?.args?.at(-1)!=="mcp")return result("catalog-preserved");const run=async action=>{const args2=action==="list"?["plugin","list","--json"]:["plugin","add","zortex@zortex-local","--json"];const command=process.platform==="win32"?process.env.ComSpec||"cmd.exe":"codex";const commandArgs=process.platform==="win32"?["/d","/s","/c","codex.cmd "+args2.join(" ")]:args2;return exec(command,commandArgs,{timeout:2e4,maxBuffer:1024*1024,windowsHide:true})};const list=JSON.parse((await run("list")).stdout);if(!Array.isArray(list.installed))return result("unavailable","Invalid Codex plugin list.");const rows=list.installed.filter(row2=>row2.pluginId==="zortex@zortex-local"&&row2.installed===true);if(rows.length===0)return result("not-installed");if(rows.length!==1)return result("different-source");const row=rows[0];if(row.enabled!==true)return result("disabled");if(row.source?.source!=="local"||row.marketplaceSource?.sourceType!=="local"||typeof row.source.path!=="string"||typeof row.marketplaceSource.source!=="string")return result("different-source");const normalize=async path=>{const value=resolve(await realpath(path));return process.platform==="win32"?value.toLowerCase():value};const[actualPlugin,expectedPlugin,actualCatalog,expectedCatalog]=await Promise.all([normalize(row.source.path),normalize(plugin),normalize(row.marketplaceSource.source),normalize(output)]);if(actualPlugin!==expectedPlugin||actualCatalog!==expectedCatalog)return result("different-source");if(typeof row.version!=="string"||!/^[a-zA-Z0-9.+-]+$/.test(row.version))return result("binding-unavailable");const oldPath=join(codexHome,"plugins","cache","zortex-local","zortex",row.version,".mcp.json");let oldText,oldMcp;try{oldText=await readFile(oldPath,"utf8");oldMcp=JSON.parse(oldText)}catch{return result("binding-unavailable")}const args=oldMcp?.mcpServers?.zortex?.args;if(!Array.isArray(args)||args.length!==4||args[0]!==cli||args[1]!=="--root"||typeof args[2]!=="string"||!isAbsolute(args[2])||args[3]!=="mcp")return result("binding-unavailable");if(row.version===pkg.version)return{...result("current"),root:args[2]};const newPath=join(plugin,".mcp.json");if(prepared||isDeepStrictEqual(mcp,await codexMcpConfiguration(defaultVaultRoot())))await writeFile(newPath,oldText,"utf8");else if(!isDeepStrictEqual(oldMcp,mcp))return result("binding-changed");const added=JSON.parse((await run("add")).stdout);if(added.pluginId!=="zortex@zortex-local"||added.version!==pkg.version)return result("failed","Codex did not confirm the expected plugin version.");return{...result("updated"),root:args[2]}}catch{return result("unavailable","Codex refresh could not be confirmed. Inspect the existing installation before retrying.")}}export async function installCodexCatalog(options={}){const output=fileURLToPath(new URL("../codex",import.meta.url));if(/^(0|false|off|no)$/i.test((process.env.ZORTEX_CODEX_SETUP??"").trim()))return{state:"disabled",marketplace:output};const root=defaultVaultRoot();const preserved=()=>({state:"preserved",marketplace:output,next:"Existing Codex catalog left unchanged. Inspect it before adding it to Codex; use indra setup codex with a new output directory to change its Vault binding."});let catalog;try{await lstat(output);catalog=preserved()}catch(error){if(error.code!=="ENOENT")throw error;try{catalog={state:"prepared",...await prepareCodexPlugin({output,root})}}catch(creationError){if(creationError.code==="EEXIST")catalog=preserved();else throw creationError}}if(!options.refresh)return catalog;const refresh=await refreshInstalledCodexPlugin(output,catalog.state==="prepared");if((refresh.state==="updated"||refresh.state==="current")&&"root"in refresh){const{installationSteps:_steps,next:_next,...remaining}=catalog;return{...remaining,root:refresh.root,registered:true,refresh,next:refresh.state==="updated"?"The existing Codex plugin was updated and its MCP configuration and Vault binding were preserved. Restart the Codex session to load the updated plugin.":"The existing Codex plugin is already current and its Vault binding was preserved."}}if(refresh.state!=="not-installed"){const{installationSteps:_steps,next:_next,root:_root,registered:_registered,...remaining}=catalog;return{...remaining,refresh,next:"The existing Codex plugin status or Vault binding could not be safely confirmed. Inspect the refresh status and existing Codex configuration before making changes."}}return{...catalog,refresh}}
|
|
1
|
+
import{lstat,readFile,realpath,writeFile}from"node:fs/promises";import{execFile}from"node:child_process";import{promisify,isDeepStrictEqual}from"node:util";import{join,resolve,isAbsolute}from"node:path";import{homedir}from"node:os";import{fileURLToPath}from"node:url";import{prepareCodexPlugin,codexMcpConfiguration}from"./codex-setup.js";import{defaultVaultRoot}from"./default-root.js";const exec=promisify(execFile);async function refreshInstalledCodexPlugin(output,prepared){const result=(state,detail)=>({state,...detail?{detail}:{}});try{const codexHome=process.env.CODEX_HOME||join(homedir(),".codex");const config=join(codexHome,"config.toml");try{await lstat(config)}catch(error){if(error.code==="ENOENT")return result("not-installed");throw error}const plugin=join(output,"plugins","zortex");const[manifest,mcp,pkg]=await Promise.all([readFile(join(plugin,".codex-plugin","plugin.json"),"utf8").then(JSON.parse),readFile(join(plugin,".mcp.json"),"utf8").then(JSON.parse),readFile(new URL("../package.json",import.meta.url),"utf8").then(JSON.parse)]);const cli=fileURLToPath(new URL("./cli.js",import.meta.url));if(manifest.name!=="zortex"||manifest.version!==pkg.version||mcp?.mcpServers?.zortex?.args?.[0]!==cli||mcp?.mcpServers?.zortex?.args?.at(-1)!=="mcp")return result("catalog-preserved");const run=async action=>{const args2=action==="list"?["plugin","list","--marketplace","zortex-local","--json"]:["plugin","add","zortex@zortex-local","--json"];const command=process.platform==="win32"?process.env.ComSpec||"cmd.exe":"codex";const commandArgs=process.platform==="win32"?["/d","/s","/c","codex.cmd "+args2.join(" ")]:args2;return exec(command,commandArgs,{timeout:2e4,maxBuffer:1024*1024,windowsHide:true})};const list=JSON.parse((await run("list")).stdout);if(!Array.isArray(list.installed))return result("unavailable","Invalid Codex plugin list.");const rows=list.installed.filter(row2=>row2.pluginId==="zortex@zortex-local"&&row2.installed===true);if(rows.length===0)return result("not-installed");if(rows.length!==1)return result("different-source");const row=rows[0];if(row.enabled!==true)return result("disabled");if(row.source?.source!=="local"||row.marketplaceSource?.sourceType!=="local"||typeof row.source.path!=="string"||typeof row.marketplaceSource.source!=="string")return result("different-source");const normalize=async path=>{const value=resolve(await realpath(path));return process.platform==="win32"?value.toLowerCase():value};const[actualPlugin,expectedPlugin,actualCatalog,expectedCatalog]=await Promise.all([normalize(row.source.path),normalize(plugin),normalize(row.marketplaceSource.source),normalize(output)]);if(actualPlugin!==expectedPlugin||actualCatalog!==expectedCatalog)return result("different-source");if(typeof row.version!=="string"||!/^[a-zA-Z0-9.+-]+$/.test(row.version))return result("binding-unavailable");const oldPath=join(codexHome,"plugins","cache","zortex-local","zortex",row.version,".mcp.json");let oldText,oldMcp;try{oldText=await readFile(oldPath,"utf8");oldMcp=JSON.parse(oldText)}catch{return result("binding-unavailable")}const args=oldMcp?.mcpServers?.zortex?.args;if(!Array.isArray(args)||args.length!==4||args[0]!==cli||args[1]!=="--root"||typeof args[2]!=="string"||!isAbsolute(args[2])||args[3]!=="mcp")return result("binding-unavailable");if(row.version===pkg.version)return{...result("current"),root:args[2]};const newPath=join(plugin,".mcp.json");if(prepared||isDeepStrictEqual(mcp,await codexMcpConfiguration(defaultVaultRoot())))await writeFile(newPath,oldText,"utf8");else if(!isDeepStrictEqual(oldMcp,mcp))return result("binding-changed");const added=JSON.parse((await run("add")).stdout);if(added.pluginId!=="zortex@zortex-local"||added.version!==pkg.version)return result("failed","Codex did not confirm the expected plugin version.");return{...result("updated"),root:args[2]}}catch{return result("unavailable","Codex refresh could not be confirmed. Inspect the existing installation before retrying.")}}export async function installCodexCatalog(options={}){const output=fileURLToPath(new URL("../codex",import.meta.url));if(/^(0|false|off|no)$/i.test((process.env.ZORTEX_CODEX_SETUP??"").trim()))return{state:"disabled",marketplace:output};const root=defaultVaultRoot();const preserved=()=>({state:"preserved",marketplace:output,next:"Existing Codex catalog left unchanged. Inspect it before adding it to Codex; use indra setup codex with a new output directory to change its Vault binding."});let catalog;try{await lstat(output);catalog=preserved()}catch(error){if(error.code!=="ENOENT")throw error;try{catalog={state:"prepared",...await prepareCodexPlugin({output,root})}}catch(creationError){if(creationError.code==="EEXIST")catalog=preserved();else throw creationError}}if(!options.refresh)return catalog;const refresh=await refreshInstalledCodexPlugin(output,catalog.state==="prepared");if((refresh.state==="updated"||refresh.state==="current")&&"root"in refresh){const{installationSteps:_steps,next:_next,...remaining}=catalog;return{...remaining,root:refresh.root,registered:true,refresh,next:refresh.state==="updated"?"The existing Codex plugin was updated and its MCP configuration and Vault binding were preserved. Restart the Codex session to load the updated plugin.":"The existing Codex plugin is already current and its Vault binding was preserved."}}if(refresh.state!=="not-installed"){const{installationSteps:_steps,next:_next,root:_root,registered:_registered,...remaining}=catalog;return{...remaining,refresh,next:"The existing Codex plugin status or Vault binding could not be safely confirmed. Inspect the refresh status and existing Codex configuration before making changes."}}return{...catalog,refresh}}
|
package/dist/codex-setup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{access,mkdir,readFile,writeFile,realpath}from"node:fs/promises";import{join,isAbsolute,relative,sep,resolve,dirname,basename}from"node:path";import{fileURLToPath}from"node:url";export async function codexMcpConfiguration(root){const syncEnv=/^(0|false|off|no)$/i.test((process.env.ZORTEX_AUTO_SYNC??"").trim())?{ZORTEX_AUTO_SYNC:"0"}:void 0;const cli=fileURLToPath(new URL("./cli.js",import.meta.url));const prefix=resolve(dirname(cli),"../../../..");const candidate=join(prefix,"runtime",process.platform==="win32"?"node.exe":"bin/node");const executable=await access(candidate).then(()=>candidate,()=>process.execPath);return{mcpServers:{zortex:{command:executable,args:[cli,"--root",resolve(root),"mcp"],startup_timeout_sec:60,...syncEnv?{env:syncEnv}:{},env_vars:["ZORTEX_TELEMETRY","DO_NOT_TRACK",...syncEnv?[]:["ZORTEX_AUTO_SYNC"]]}}}}export async function prepareCodexPlugin(options){if(!isAbsolute(options.output)||!isAbsolute(options.root))throw Error("Codex output and Vault root must be absolute directories.");const syncEnv=/^(0|false|off|no)$/i.test((process.env.ZORTEX_AUTO_SYNC??"").trim())?{ZORTEX_AUTO_SYNC:"0"}:void 0;const output=resolve(options.output),root=resolve(options.root);const canonical=async path=>{try{return await realpath(path)}catch(error){if(error.code!=="ENOENT"||dirname(path)===path)throw error;return join(await canonical(dirname(path)),basename(path))}};const within=(parent,child)=>{const path=relative(parent,child);return path===""||!isAbsolute(path)&&path!==".."&&!path.startsWith(".."+sep)};const[outputTarget,rootTarget]=await Promise.all([canonical(output),canonical(root)]);if(within(outputTarget,rootTarget)||within(rootTarget,outputTarget))throw Error("Codex plugin output and private Vault must be separate directories.");const installed=JSON.parse(await readFile(new URL("../package.json",import.meta.url),"utf8"));const mcp=await codexMcpConfiguration(root);await mkdir(output);const plugin=join(output,"plugins","zortex");await mkdir(join(output,".agents","plugins"),{recursive:true});await mkdir(join(plugin,".codex-plugin"),{recursive:true});const json=(path,value)=>writeFile(path,JSON.stringify(value,null,2)+"\n",{flag:"wx"});await json(join(plugin,".codex-plugin","plugin.json"),{name:"zortex",version:installed.version,description:"Read connected sources through one local Vault and use existing agent tools for connection.",author:{name:"ZortexHQ"},mcpServers:"./.mcp.json"});await json(join(plugin,".mcp.json"),mcp);await json(join(output,".agents","plugins","marketplace.json"),{name:"zortex-local",interface:{displayName:"Zortex (local npm installation)"},plugins:[{name:"zortex",source:{source:"local",path:"./plugins/zortex"},policy:{installation:"AVAILABLE",authentication:"ON_INSTALL"},category:"Productivity"}]});return{marketplace:output,plugin,root,registered:false,installationSteps:[{command:"codex",args:["plugin","marketplace","add",output]},{command:"codex",args:["plugin","add","zortex@zortex-local"]}],next:(syncEnv?"Keep ZORTEX_AUTO_SYNC=0 when the requested installation stops before full sync. ":"")+"Register this installation with the two commands above. No account connection starts during installation or MCP startup. When the user requests a source, run indra --root <Vault> connect --source <source>; complete its actual OAuth, QR or permission gateway with the existing signed-in browser and ordinary CUA tools. Keep the command running for provider verification. Search and source Actions remain available through MCP. Keep this npm installation available."}}
|
|
1
|
+
import{exec}from"node:child_process";import{access,mkdir,readFile,writeFile,realpath}from"node:fs/promises";import{join,isAbsolute,relative,sep,resolve,dirname,basename}from"node:path";import{fileURLToPath}from"node:url";export async function codexMcpConfiguration(root){const syncEnv=/^(0|false|off|no)$/i.test((process.env.ZORTEX_AUTO_SYNC??"").trim())?{ZORTEX_AUTO_SYNC:"0"}:void 0;const cli=fileURLToPath(new URL("./cli.js",import.meta.url));const prefix=resolve(dirname(cli),"../../../..");const candidate=join(prefix,"runtime",process.platform==="win32"?"node.exe":"bin/node");const executable=await access(candidate).then(()=>candidate,()=>process.execPath);return{mcpServers:{zortex:{command:executable,args:[cli,"--root",resolve(root),"mcp"],startup_timeout_sec:60,...syncEnv?{env:syncEnv}:{},env_vars:["ZORTEX_TELEMETRY","DO_NOT_TRACK",...syncEnv?[]:["ZORTEX_AUTO_SYNC"]]}}}}export async function prepareCodexPlugin(options){if(!isAbsolute(options.output)||!isAbsolute(options.root))throw Error("Codex output and Vault root must be absolute directories.");const syncEnv=/^(0|false|off|no)$/i.test((process.env.ZORTEX_AUTO_SYNC??"").trim())?{ZORTEX_AUTO_SYNC:"0"}:void 0;const output=resolve(options.output),root=resolve(options.root);const canonical=async path=>{try{return await realpath(path)}catch(error){if(error.code!=="ENOENT"||dirname(path)===path)throw error;return join(await canonical(dirname(path)),basename(path))}};const within=(parent,child)=>{const path=relative(parent,child);return path===""||!isAbsolute(path)&&path!==".."&&!path.startsWith(".."+sep)};const[outputTarget,rootTarget]=await Promise.all([canonical(output),canonical(root)]);if(within(outputTarget,rootTarget)||within(rootTarget,outputTarget))throw Error("Codex plugin output and private Vault must be separate directories.");const installed=JSON.parse(await readFile(new URL("../package.json",import.meta.url),"utf8"));const mcp=await codexMcpConfiguration(root);await mkdir(output);const plugin=join(output,"plugins","zortex");await mkdir(join(output,".agents","plugins"),{recursive:true});await mkdir(join(plugin,".codex-plugin"),{recursive:true});const json=(path,value)=>writeFile(path,JSON.stringify(value,null,2)+"\n",{flag:"wx"});await json(join(plugin,".codex-plugin","plugin.json"),{name:"zortex",version:installed.version,description:"Read connected sources through one local Vault and use existing agent tools for connection.",author:{name:"ZortexHQ"},mcpServers:"./.mcp.json"});await json(join(plugin,".mcp.json"),mcp);await json(join(output,".agents","plugins","marketplace.json"),{name:"zortex-local",interface:{displayName:"Zortex (local npm installation)"},plugins:[{name:"zortex",source:{source:"local",path:"./plugins/zortex"},policy:{installation:"AVAILABLE",authentication:"ON_INSTALL"},category:"Productivity"}]});return{marketplace:output,plugin,root,registered:false,installationSteps:[{command:"codex",args:["plugin","marketplace","add",output]},{command:"codex",args:["plugin","add","zortex@zortex-local"]}],next:(syncEnv?"Keep ZORTEX_AUTO_SYNC=0 when the requested installation stops before full sync. ":"")+"Register this installation with the two commands above. No account connection starts during installation or MCP startup. When the user requests a source, run indra --root <Vault> connect --source <source>; complete its actual OAuth, QR or permission gateway with the existing signed-in browser and ordinary CUA tools. Keep the command running for provider verification. Search and source Actions remain available through MCP. Keep this npm installation available."}}export async function registerCodexPlugin(output,run=defaultRun){const steps=[];for(const[command,args]of[["codex",["plugin","marketplace","add",output]],["codex",["plugin","add","zortex@zortex-local"]]]){let ok=true,text;try{text=await run(command,[...args])}catch(error){ok=false;text=String(error instanceof Error?error.message:error)}steps.push({command,args:[...args],ok,output:text.slice(0,2e3)});if(!ok)break}return{registered:steps.length===2&&steps.every(step=>step.ok),steps}}function defaultRun(command,args){return new Promise((resolve2,reject)=>{const quote=value=>/\s/.test(value)?'"'+value.replace(/"/g,'\\"')+'"':value;exec([command,...args].map(quote).join(" "),{shell:process.platform==="win32"?process.env.ComSpec??"cmd.exe":"/bin/sh"},(error,stdout,stderr)=>{if(error)reject(Error((stderr||stdout||error.message).trim().slice(0,2e3)));else resolve2(stdout.trim())})})}
|
package/dist/connector-worker.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{resolve}from"node:path";import{Original}from"@zortexhq/plugin-connector-framework/api";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{createCustodiedGmailSync}from"@zortexhq/plugin-connector-gmail/custodied-sync";import{createCustodiedDriveSync}from"@zortexhq/plugin-connector-drive/custodied-full";import{createCalendarProvider}from"@zortexhq/plugin-connector-calendar";import{createYouTubeProvider}from"@zortexhq/plugin-connector-youtube";import{createSlackMessageSync}from"@zortexhq/plugin-connector-slack";import{createOutlookMailSync}from"@zortexhq/plugin-connector-outlook/mail-sync";import{openProfile}from"./profile.js";import{selectedWorkerGoogleAuth}from"./worker-google-auth.js";const codeVersion=source2=>source2==="chrome-history"?"zortex-v3/chrome-history@0.1.0+6315429c":"indra-v2/"+source2+"@0.1.0+full-sync";const[root,profile,source]=process.argv.slice(2);async function main(){const runId=process.env.ZORTEX_PROCESS_RUN_ID;if(!root||!profile||!source||!runId)throw Error("Worker requires trusted selection and run identity.");process.env.ZORTEX_ENGINE_ROOT=resolve(root);const app=await openProfile(profile,"worker");let googleAuth=app.context.zortexGoogleAuth;const selectedBindingId=process.env.ZORTEX_SELECTED_BINDING_ID,selectedGrantId=process.env.ZORTEX_SELECTED_GRANT_ID,selectedScopeEpoch=Number(process.env.ZORTEX_SELECTED_SCOPE_EPOCH);if(selectedBindingId){if(!selectedGrantId||!Number.isSafeInteger(selectedScopeEpoch)||selectedScopeEpoch<0)throw Error("Worker requires a complete selected authority fence.");const vault=app.context.zortexVaultStore,custody=vault.bindingCustody;const resolved=await custody.resolve({kind:"binding",bindingId:selectedBindingId});if(!Original.isOk(resolved)||resolved.ok.kind!=="resolved"||resolved.ok.binding.identity.source!==source||resolved.ok.binding.state!=="connected")throw Error("Selected worker binding is unavailable.");const binding=resolved.ok.binding,nativeSubject=binding.identity.subject;if(typeof nativeSubject!=="string"||!nativeSubject.trim())throw Error("This native worker requires a verified upstream account; an opaque MCP session is not a native identity.");const grant=await custody.grantForBinding(binding.id,"L1",binding.provider);if(!Original.isOk(grant)||!grant.ok||grant.ok.id!==selectedGrantId||grant.ok.scopeEpoch!==selectedScopeEpoch||grant.ok.state!=="active")throw Error("Selected worker grant changed.");const resourceId=oauthCredentialResourceId(binding.id),authorization={purpose:"L1",audience:binding.provider};const captured=await custody.credentialSnapshot(resourceId,authorization);if(!Original.isOk(captured)||captured.ok.binding.id!==binding.id||captured.ok.grant.id!==grant.ok.id||captured.ok.grant.scopeEpoch!==selectedScopeEpoch||captured.ok.material.kind!=="oauth")throw Error("Selected worker credential fence changed.");let snapshot=captured.ok;googleAuth=selectedWorkerGoogleAuth(googleAuth,source,binding.id);const connection=vault.connection.bind(vault),credential=vault.credential.bind(vault),updateCredential=vault.updateCredential.bind(vault);vault.connection=async requested=>requested===source?Original.ok({source,provider:binding.provider,account:binding.account,accountId:nativeSubject,scopes:[...snapshot.grant.scopes],state:"connected",updatedAt:binding.updatedAt}):connection(requested);vault.credential=async requested=>requested===source&&snapshot.material.kind==="oauth"?Original.ok(structuredClone(snapshot.material.credential)):credential(requested);vault.updateCredential=async(requested,next)=>{if(requested!==source)return updateCredential(requested,next);const refreshed=await custody.refreshResource(snapshot,{kind:"resident"},async current=>current.binding.id===binding.id&¤t.grant.id===selectedGrantId&¤t.grant.scopeEpoch===selectedScopeEpoch?Original.ok({kind:"oauth",credential:next}):Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Selected worker authority changed during refresh."}));if(!Original.isOk(refreshed))return refreshed;snapshot=refreshed.ok;return Original.ok(void 0)}}let withdraw,withdrawAuthority,closeSource;const bindGrant=(name,grant)=>app.context.zortexSqliteVault.registerConnectorAuthority(name,origin=>origin.grant===grant?Original.ok(true):Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Authorization changed during sync."}));const budget=Number(process.env.ZORTEX_SYNC_BUDGET_MS),runSignal=Number.isSafeInteger(budget)&&budget>0?AbortSignal.timeout(budget):void 0;try{if(source==="gmail"){const built=await createCustodiedGmailSync({parts:app.context.zortexOriginalAuthoring,provider:app.context.zortexOriginalProviderRead,auth:googleAuth,vault:app.context.zortexVaultStore});if(!Original.isOk(built)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,built,codeVersion(source));process.exitCode=2;return}closeSource=()=>built.ok.close();const current=await app.context.zortexVaultStore.connection(source);if(!Original.isOk(current)||!current.ok){const failed=Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:"Gmail connection changed before sync admission."});app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,failed,codeVersion(source));process.exitCode=2;return}const checked=await built.ok.assertCurrent();if(!Original.isOk(checked)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,checked,codeVersion(source));process.exitCode=2;return}withdrawAuthority=app.context.zortexSqliteVault.registerConnectedSourceAuthority(source,{grant:built.ok.grant.id,account:built.ok.accountId,updatedAt:current.ok.updatedAt,scopes:built.ok.scopes});withdraw=app.context.zortexOriginalSync.register(built.ok.connector,()=>built.ok.resolveGrant())}else if(source==="google-drive"){const built=createCustodiedDriveSync({parts:app.context.zortexOriginalAuthoring,auth:googleAuth,vault:app.context.zortexVaultStore,content:()=>app.context.reflect.get("zortexDriveContent")});closeSource=()=>built.close();const grant=await built.resolveGrant();if(!Original.isOk(grant)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,grant,codeVersion(source));process.exitCode=2;return}const epoch=built.currentEpoch();if(!epoch){const failed=Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Drive grant has no connected account epoch."});app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,failed,codeVersion(source));process.exitCode=2;return}withdrawAuthority=app.context.zortexSqliteVault.registerConnectedSourceAuthority(source,{grant:grant.ok.id,account:epoch.accountId,updatedAt:epoch.updatedAt,scopes:epoch.scopes});withdraw=app.context.zortexOriginalSync.register(built.connector,async()=>Original.ok(grant.ok))}else if(source==="google-calendar"){const built=createCalendarProvider({parts:app.context.zortexOriginalAuthoring,auth:googleAuth,vault:app.context.zortexVaultStore});closeSource=()=>built.close();const grant=await built.resolveGrant(),current=await app.context.zortexVaultStore.connection(source);if(!Original.isOk(grant)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,grant,codeVersion(source));process.exitCode=2;return}if(!Original.isOk(current)||!current.ok?.updatedAt||!grant.ok.account){const failed=Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:"Calendar connection changed before sync admission."});app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,failed,codeVersion(source));process.exitCode=2;return}withdrawAuthority=app.context.zortexSqliteVault.registerConnectedSourceAuthority(source,{grant:grant.ok.id,account:grant.ok.account,updatedAt:current.ok.updatedAt,scopes:grant.ok.scopes});withdraw=app.context.zortexOriginalSync.register(built.connector,async()=>Original.ok(grant.ok))}else if(source==="youtube"){const built=createYouTubeProvider({parts:app.context.zortexOriginalAuthoring,auth:googleAuth,vault:app.context.zortexVaultStore});closeSource=()=>built.close();const grant=await built.resolveGrant(),current=await app.context.zortexVaultStore.connection(source);if(!Original.isOk(grant)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,grant,codeVersion(source));process.exitCode=2;return}if(!Original.isOk(current)||!current.ok?.updatedAt||!grant.ok.account){const failed=Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:"YouTube connection changed before sync admission."});app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,failed,codeVersion(source));process.exitCode=2;return}withdrawAuthority=app.context.zortexSqliteVault.registerConnectedSourceAuthority(source,{grant:grant.ok.id,account:grant.ok.account,updatedAt:current.ok.updatedAt,scopes:grant.ok.scopes});withdraw=app.context.zortexOriginalSync.register(built.connector,async()=>Original.ok(grant.ok))}else if(source==="slack"){const built=createSlackMessageSync({vault:app.context.zortexVaultStore,transport:app.context.zortexConnectorHttp,parts:app.context.zortexOriginalAuthoring,...runSignal?{signal:runSignal}:{}});closeSource=()=>built.close();const grant=await built.resolveGrant();if(!Original.isOk(grant)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,grant,codeVersion(source));process.exitCode=2;return}withdrawAuthority=bindGrant(source,grant.ok.id);withdraw=app.context.zortexOriginalSync.register(built.connector,async()=>Original.ok(grant.ok))}else if(source==="outlook"){const built=createOutlookMailSync({vault:app.context.zortexVaultStore,transport:app.context.zortexConnectorHttp,...runSignal?{signal:runSignal}:{}});closeSource=()=>built.close();const grant=await built.resolveGrant(),current=await app.context.zortexVaultStore.connection(source);if(!Original.isOk(grant)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,grant,codeVersion(source));process.exitCode=2;return}if(!Original.isOk(current)||!current.ok?.updatedAt){const failed=Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:"Outlook connection changed before sync admission."});app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,failed,codeVersion(source));process.exitCode=2;return}withdrawAuthority=bindGrant(source,grant.ok.id);withdraw=app.context.zortexOriginalSync.register(built.connector,async()=>Original.ok(grant.ok))}else if(source!=="chrome-history"&&source!=="google-chrome"&&source!=="microsoft-edge")throw Error("Unknown original sync source.");const result=await app.context.zortexOriginalSync.run(source,{...runSignal?{signal:runSignal}:{},...process.env.ZORTEX_SYNC_USER_RETRY==="1"?{userRetry:true}:{}});app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,result,codeVersion(source));const partial=source!=="chrome-history"&&Original.isOk(result)&&result.ok.error===void 0&&result.ok.runFailed!==true&&result.ok.stopped===true;if(!Original.isOk(result)||result.ok.error!==void 0||result.ok.runFailed===true||!partial&&(result.ok.stopped===true||result.ok.state!=="IDLE"))process.exitCode=2}finally{withdraw?.();withdrawAuthority?.();await closeSource?.();await app.close()}}main().catch(()=>{process.stderr.write("Worker could not commit a business receipt.\n");process.exitCode=2});
|
|
2
|
+
import{resolve}from"node:path";import{Original}from"@zortexhq/plugin-connector-framework/api";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{createCustodiedGmailSync}from"@zortexhq/plugin-connector-gmail/custodied-sync";import{createCustodiedDriveSync}from"@zortexhq/plugin-connector-drive/custodied-full";import{createCalendarProvider}from"@zortexhq/plugin-connector-calendar";import{createTasksSource}from"@zortexhq/plugin-connector-google-tasks";import{createYouTubeProvider}from"@zortexhq/plugin-connector-youtube";import{createSlackMessageSync}from"@zortexhq/plugin-connector-slack";import{createOutlookMailSync}from"@zortexhq/plugin-connector-outlook/mail-sync";import{openImessageSync}from"./imessage-sync.js";import{openProfile}from"./profile.js";import{selectedWorkerGoogleAuth}from"./worker-google-auth.js";const codeVersion=source2=>source2==="chrome-history"?"zortex-v3/chrome-history@0.1.0+6315429c":"indra-v2/"+source2+"@0.1.0+full-sync";const[root,profile,source]=process.argv.slice(2);async function main(){const runId=process.env.ZORTEX_PROCESS_RUN_ID;if(!root||!profile||!source||!runId)throw Error("Worker requires trusted selection and run identity.");process.env.ZORTEX_ENGINE_ROOT=resolve(root);const app=await openProfile(profile,"worker");let googleAuth=app.context.zortexGoogleAuth;const selectedBindingId=process.env.ZORTEX_SELECTED_BINDING_ID,selectedGrantId=process.env.ZORTEX_SELECTED_GRANT_ID,selectedScopeEpoch=Number(process.env.ZORTEX_SELECTED_SCOPE_EPOCH);if(selectedBindingId){if(!selectedGrantId||!Number.isSafeInteger(selectedScopeEpoch)||selectedScopeEpoch<0)throw Error("Worker requires a complete selected authority fence.");const vault=app.context.zortexVaultStore,custody=vault.bindingCustody;const resolved=await custody.resolve({kind:"binding",bindingId:selectedBindingId});if(!Original.isOk(resolved)||resolved.ok.kind!=="resolved"||resolved.ok.binding.identity.source!==source||resolved.ok.binding.state!=="connected")throw Error("Selected worker binding is unavailable.");const binding=resolved.ok.binding,nativeSubject=binding.identity.subject;if(typeof nativeSubject!=="string"||!nativeSubject.trim())throw Error("This native worker requires a verified upstream account; an opaque MCP session is not a native identity.");const grant=await custody.grantForBinding(binding.id,"L1",binding.provider);if(!Original.isOk(grant)||!grant.ok||grant.ok.id!==selectedGrantId||grant.ok.scopeEpoch!==selectedScopeEpoch||grant.ok.state!=="active")throw Error("Selected worker grant changed.");const resourceId=oauthCredentialResourceId(binding.id),authorization={purpose:"L1",audience:binding.provider};const captured=await custody.credentialSnapshot(resourceId,authorization);if(!Original.isOk(captured)||captured.ok.binding.id!==binding.id||captured.ok.grant.id!==grant.ok.id||captured.ok.grant.scopeEpoch!==selectedScopeEpoch||captured.ok.material.kind!=="oauth")throw Error("Selected worker credential fence changed.");let snapshot=captured.ok;googleAuth=selectedWorkerGoogleAuth(googleAuth,source,binding.id);const connection=vault.connection.bind(vault),credential=vault.credential.bind(vault),updateCredential=vault.updateCredential.bind(vault);vault.connection=async requested=>requested===source?Original.ok({source,provider:binding.provider,account:binding.account,accountId:nativeSubject,scopes:[...snapshot.grant.scopes],state:"connected",updatedAt:binding.updatedAt}):connection(requested);vault.credential=async requested=>requested===source&&snapshot.material.kind==="oauth"?Original.ok(structuredClone(snapshot.material.credential)):credential(requested);vault.updateCredential=async(requested,next)=>{if(requested!==source)return updateCredential(requested,next);const refreshed=await custody.refreshResource(snapshot,{kind:"resident"},async current=>current.binding.id===binding.id&¤t.grant.id===selectedGrantId&¤t.grant.scopeEpoch===selectedScopeEpoch?Original.ok({kind:"oauth",credential:next}):Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Selected worker authority changed during refresh."}));if(!Original.isOk(refreshed))return refreshed;snapshot=refreshed.ok;return Original.ok(void 0)}}let withdraw,withdrawAuthority,closeSource;const bindGrant=(name,grant)=>app.context.zortexSqliteVault.registerConnectorAuthority(name,origin=>origin.grant===grant?Original.ok(true):Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Authorization changed during sync."}));const budget=Number(process.env.ZORTEX_SYNC_BUDGET_MS),runSignal=Number.isSafeInteger(budget)&&budget>0?AbortSignal.timeout(budget):void 0;try{if(source==="gmail"){const built=await createCustodiedGmailSync({parts:app.context.zortexOriginalAuthoring,provider:app.context.zortexOriginalProviderRead,auth:googleAuth,vault:app.context.zortexVaultStore});if(!Original.isOk(built)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,built,codeVersion(source));process.exitCode=2;return}closeSource=()=>built.ok.close();const current=await app.context.zortexVaultStore.connection(source);if(!Original.isOk(current)||!current.ok){const failed=Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:"Gmail connection changed before sync admission."});app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,failed,codeVersion(source));process.exitCode=2;return}const checked=await built.ok.assertCurrent();if(!Original.isOk(checked)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,checked,codeVersion(source));process.exitCode=2;return}withdrawAuthority=app.context.zortexSqliteVault.registerConnectedSourceAuthority(source,{grant:built.ok.grant.id,account:built.ok.accountId,updatedAt:current.ok.updatedAt,scopes:built.ok.scopes});withdraw=app.context.zortexOriginalSync.register(built.ok.connector,()=>built.ok.resolveGrant())}else if(source==="google-drive"){const built=createCustodiedDriveSync({parts:app.context.zortexOriginalAuthoring,auth:googleAuth,vault:app.context.zortexVaultStore,content:()=>app.context.reflect.get("zortexDriveContent")});closeSource=()=>built.close();const grant=await built.resolveGrant();if(!Original.isOk(grant)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,grant,codeVersion(source));process.exitCode=2;return}const epoch=built.currentEpoch();if(!epoch){const failed=Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Drive grant has no connected account epoch."});app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,failed,codeVersion(source));process.exitCode=2;return}withdrawAuthority=app.context.zortexSqliteVault.registerConnectedSourceAuthority(source,{grant:grant.ok.id,account:epoch.accountId,updatedAt:epoch.updatedAt,scopes:epoch.scopes});withdraw=app.context.zortexOriginalSync.register(built.connector,async()=>Original.ok(grant.ok))}else if(source==="google-calendar"||source==="google-tasks"){const built=(source==="google-tasks"?createTasksSource:createCalendarProvider)({parts:app.context.zortexOriginalAuthoring,auth:googleAuth,vault:app.context.zortexVaultStore});closeSource=()=>built.close();const grant=await built.resolveGrant(),current=await app.context.zortexVaultStore.connection(source);if(!Original.isOk(grant)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,grant,codeVersion(source));process.exitCode=2;return}if(!Original.isOk(current)||!current.ok?.updatedAt||!grant.ok.account){const failed=Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:source+" connection changed before sync admission."});app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,failed,codeVersion(source));process.exitCode=2;return}withdrawAuthority=app.context.zortexSqliteVault.registerConnectedSourceAuthority(source,{grant:grant.ok.id,account:grant.ok.account,updatedAt:current.ok.updatedAt,scopes:grant.ok.scopes});withdraw=app.context.zortexOriginalSync.register(built.connector,async()=>Original.ok(grant.ok))}else if(source==="youtube"){const built=createYouTubeProvider({parts:app.context.zortexOriginalAuthoring,auth:googleAuth,vault:app.context.zortexVaultStore});closeSource=()=>built.close();const grant=await built.resolveGrant(),current=await app.context.zortexVaultStore.connection(source);if(!Original.isOk(grant)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,grant,codeVersion(source));process.exitCode=2;return}if(!Original.isOk(current)||!current.ok?.updatedAt||!grant.ok.account){const failed=Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:"YouTube connection changed before sync admission."});app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,failed,codeVersion(source));process.exitCode=2;return}withdrawAuthority=app.context.zortexSqliteVault.registerConnectedSourceAuthority(source,{grant:grant.ok.id,account:grant.ok.account,updatedAt:current.ok.updatedAt,scopes:grant.ok.scopes});withdraw=app.context.zortexOriginalSync.register(built.connector,async()=>Original.ok(grant.ok))}else if(source==="slack"){const built=createSlackMessageSync({vault:app.context.zortexVaultStore,transport:app.context.zortexConnectorHttp,parts:app.context.zortexOriginalAuthoring,...runSignal?{signal:runSignal}:{}});closeSource=()=>built.close();const grant=await built.resolveGrant();if(!Original.isOk(grant)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,grant,codeVersion(source));process.exitCode=2;return}withdrawAuthority=bindGrant(source,grant.ok.id);withdraw=app.context.zortexOriginalSync.register(built.connector,async()=>Original.ok(grant.ok))}else if(source==="outlook"){const built=createOutlookMailSync({vault:app.context.zortexVaultStore,transport:app.context.zortexConnectorHttp,...runSignal?{signal:runSignal}:{}});closeSource=()=>built.close();const grant=await built.resolveGrant(),current=await app.context.zortexVaultStore.connection(source);if(!Original.isOk(grant)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,grant,codeVersion(source));process.exitCode=2;return}if(!Original.isOk(current)||!current.ok?.updatedAt){const failed=Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:"Outlook connection changed before sync admission."});app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,failed,codeVersion(source));process.exitCode=2;return}withdrawAuthority=bindGrant(source,grant.ok.id);withdraw=app.context.zortexOriginalSync.register(built.connector,async()=>Original.ok(grant.ok))}else if(source==="imessage"){const built=await openImessageSync(app.context.zortexOriginalAuthoring);if(!Original.isOk(built)){app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,built,codeVersion(source));process.exitCode=2;return}closeSource=built.ok.close;withdrawAuthority=bindGrant(source,built.ok.grant.id);withdraw=app.context.zortexOriginalSync.register(built.ok.connector,async()=>Original.ok(built.ok.grant))}else if(source!=="chrome-history"&&source!=="google-chrome"&&source!=="microsoft-edge")throw Error("Unknown original sync source.");const result=await app.context.zortexOriginalSync.run(source,{...runSignal?{signal:runSignal}:{},...process.env.ZORTEX_SYNC_USER_RETRY==="1"?{userRetry:true}:{}});app.context.zortexConnectorProcessJournal.writeBusiness(runId,source,result,codeVersion(source));const partial=source!=="chrome-history"&&Original.isOk(result)&&result.ok.error===void 0&&result.ok.runFailed!==true&&result.ok.stopped===true;if(!Original.isOk(result)||result.ok.error!==void 0||result.ok.runFailed===true||!partial&&(result.ok.stopped===true||result.ok.state!=="IDLE"))process.exitCode=2}finally{withdraw?.();withdrawAuthority?.();await closeSource?.();await app.close()}}main().catch(()=>{process.stderr.write("Worker could not commit a business receipt.\n");process.exitCode=2});
|
package/dist/content-find.js
CHANGED
|
@@ -1,8 +1,2 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";export function createContentFindContinuations(options={}){const now=options.now??Date.now,makeToken=options.token??randomUUID,ttlMs=options.ttlMs??5*6e4,maxEntries=options.maxEntries??256;const entries=new Map;const clean=()=>{const at=now();for(const[token,row]of entries)if(row.expiresAt<=at)entries.delete(token)};return{issue(state){clean();while(entries.size>=maxEntries)entries.delete(entries.keys().next().value);let token;do token=makeToken();while(entries.has(token));const expiresAt=now()+ttlMs;entries.set(token,{state,expiresAt});return{token,expiresAt:new Date(expiresAt).toISOString()}},consume(token,signature){clean();const row=entries.get(token);if(!row)return{error:"missing"};if(row.state.signature!==signature)return{error:"mismatch"};entries.delete(token);return{state:row.state}}}}const SOURCE_ALIASES={"drive":"google-drive","google-drive":"google-drive","google-calendar":"google-calendar","calendar":"google-calendar","google-mail":"gmail","gmail":"gmail"};const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const text=value=>typeof value==="string"?value:"";const bounded=(value,max=800)=>value.length<=max?value:value.slice(0,max);const iso=value=>typeof value==="string"&&Number.isFinite(Date.parse(value));const queryText=value=>value.trim().replace(/\s+/gu," ");const escapeLike=value=>value.replace(/[\\%_]/gu,match=>"\\"+match);const STOP_WORDS=new Set(["a","an","and","are","about","did","do","does","email","emails","find","for","from","has","have","i","in","is","it","latest","mail","me","my","of","on","or","please","show","that","the","to","was","were","what","whether","with"]);const ENTITY_GROUPS=[{test:/清华|tsinghua|\bthu\b/iu,aliases:["\u6E05\u534E","Tsinghua","THU"]}];const SEMANTIC_GROUPS=[{test:/accept|admission|接收|录用|中稿/iu,terms:["accept","accepted","acceptance","decision","notification","\u5F55\u7528","\u63A5\u6536","\u4E2D\u7A3F"],expansions:["accepted","acceptance"]},{test:/submit|submission|投稿|提交/iu,terms:["submit","submitted","submission","manuscript","paper","\u6295\u7A3F","\u63D0\u4EA4"],expansions:["submission","submitted"]},{test:/meet|会议|日程|邀请/iu,terms:["meeting","invite","invitation","schedule","\u4F1A\u8BAE","\u9080\u8BF7","\u65E5\u7A0B"],expansions:["invitation","meeting"]},{test:/invoice|receipt|payment|发票|收据|付款/iu,terms:["invoice","receipt","payment","paid","\u53D1\u7968","\u6536\u636E","\u4ED8\u6B3E"],expansions:["invoice","receipt"]},{test:/decision|决定|结论/iu,terms:["decision","result","outcome","\u51B3\u5B9A","\u7ED3\u8BBA"],expansions:["decision","result"]}];const ACCEPTANCE_NOTICE_PATTERNS=[/\b(?:paper|manuscript|abstract|proposal|article)\b.{0,100}\b(?:has been |is |was )?(?:accepted|approved)\b/isu,/\bwe are (?:pleased|delighted) to (?:inform|notify)\b.{0,140}\baccepted\b/isu,/\bacceptance (?:notification|notice|decision|letter)\b/iu,/(?:论文|稿件|摘要|文章).{0,50}(?:已)?(?:接收|录用|中稿)/su,/(?:接收|录用|中稿)(?:通知|决定|函)/u];const SUBMISSION_CONFIRMATION_PATTERNS=[/\b(?:submission|manuscript|paper) (?:has been |was )?(?:successfully )?(?:submitted|received)\b/iu,/\b(?:submission|receipt) confirmation\b/iu,/(?:投稿|提交)(?:已)?(?:成功|收到|确认)|(?:成功|已经)(?:投稿|提交)/u];const DECISION_NOTICE_PATTERNS=[/\b(?:decision|result|outcome) (?:notification|notice|letter)\b/iu,/(?:决定|结果|结论)(?:通知|函)/u];export function buildContentFindPlan(goal){const normalized=queryText(goal),quoted=[...normalized.matchAll(/["“”']([^"“”']{2,120})["“”']/gu)].map(row=>queryText(row[1]));const acronyms=[...normalized.matchAll(/\b[A-Z][A-Z0-9-]{1,}(?:\s+[A-Z][A-Z0-9-]{1,}){0,4}\b/gu)].map(row=>row[0]);const identifiers=[...normalized.matchAll(/\b[A-Za-z][A-Za-z0-9._+-]*\d[A-Za-z0-9._+-]*\b/gu)].map(row=>row[0]);const words=[...normalized.matchAll(/[A-Za-z][A-Za-z0-9._+-]{2,}/gu)].map(row=>row[0]).filter(word=>!STOP_WORDS.has(word.toLocaleLowerCase()));const entity=ENTITY_GROUPS.find(group=>group.test.test(normalized));const entityAliases=entity?[...entity.aliases].filter(alias=>alias!=="THU"||/\bTHU\b/iu.test(normalized)).sort((left,right)=>Number(!normalized.toLocaleLowerCase().includes(left.toLocaleLowerCase()))-Number(!normalized.toLocaleLowerCase().includes(right.toLocaleLowerCase()))):[];const chineseFocus=queryText(normalized.replace(/(?:请|麻烦)?(?:帮我|给我)?(?:找一下|查一下|搜索一下|查找一下|看看|寻找)/gu," ").replace(/(?:邮件|邮箱|消息)(?:中|里|内)?/gu," ").replace(/(?:最近|最新)(?:的)?|(?:一封|一条|一份|一个)|(?:有关|相关)(?:的)?|关于/gu," ")).replace(/^[和与及的中里内]+|[和与及的中里内]+$/gu,"");const focus=queryText(entityAliases[0]??quoted[0]??acronyms[0]??identifiers[0]??(words.slice(0,4).join(" ")||chineseFocus||normalized)).slice(0,500);const groups=SEMANTIC_GROUPS.filter(group=>group.test.test(normalized));const semanticTerms=[...new Set([...entityAliases,...groups.flatMap(group=>group.terms)])].slice(0,16);const expansions=[...new Set(groups.flatMap(group=>group.expansions))].filter(term=>!focus.toLocaleLowerCase().includes(term.toLocaleLowerCase()));const queries=(entityAliases.length?entityAliases:[...expansions.slice(0,2).map(term=>`${focus} ${term}`),focus,normalized]).map(value=>queryText(value).slice(0,500)).filter((value,index,all)=>!!value&&all.indexOf(value)===index).slice(0,3);const gmailAlias=entityAliases.length?`{${entityAliases.join(" ")}}`:void 0;const gmailQueries=gmailAlias?[...expansions.slice(0,2).map(term=>`${gmailAlias} ${term}`),gmailAlias].slice(0,3):void 0;return{focus:focus||normalized.slice(0,500),queries:queries.length?queries:[normalized.slice(0,500)],semanticTerms,recencyFirst:/latest|newest|most recent|最近|最新/iu.test(normalized),...gmailQueries?{gmailQueries}:{}}}export function parseContentFindRequest(value){if(!object(value)||Object.keys(value).some(key=>!["goal","source","since","until","limit","cursor","freshness","continuationToken"].includes(key)))return businessError("invalid_argument","Pass goal and optional source, since, until, limit, cursor, freshness and continuationToken.","kernel");const goal=typeof value.goal==="string"?queryText(value.goal):"";if(!goal||Buffer.byteLength(goal)>4096)return businessError("invalid_argument","goal must be nonempty and at most 4096 bytes.","kernel");let source;if(value.source!==void 0){if(typeof value.source!=="string")return businessError("invalid_argument","source must be a connector id.","kernel");const candidate=value.source.trim().toLowerCase();source=SOURCE_ALIASES[candidate]??candidate;if(!/^[a-z][a-z0-9-]{0,63}$/u.test(source))return businessError("invalid_argument","source must be a lowercase connector id.","kernel")}if(value.since!==void 0&&!iso(value.since)||value.until!==void 0&&!iso(value.until))return businessError("invalid_argument","since and until must be ISO timestamps.","kernel");const limit=value.limit===void 0?5:value.limit,cursor=value.cursor===void 0?0:value.cursor,freshness=value.freshness===void 0?"auto":value.freshness;if(!Number.isSafeInteger(limit)||Number(limit)<1||Number(limit)>50)return businessError("invalid_argument","limit must be an integer from 1 to 50.","kernel");if(!Number.isSafeInteger(cursor)||Number(cursor)<0)return businessError("invalid_argument","cursor must be a nonnegative integer.","kernel");if(freshness!=="auto"&&freshness!=="cached"&&freshness!=="live")return businessError("invalid_argument","freshness must be auto, cached or live.","kernel");if(value.continuationToken!==void 0&&(typeof value.continuationToken!=="string"||!/^[A-Za-z0-9_-]{16,200}$/u.test(value.continuationToken)))return businessError("invalid_argument","continuationToken must be the opaque token returned by the prior find result.","kernel");return ok({goal,...source?{source}:{},...typeof value.since==="string"?{since:value.since}:{},...typeof value.until==="string"?{until:value.until}:{},limit:Number(limit),cursor:Number(cursor),freshness,...typeof value.continuationToken==="string"?{continuationToken:value.continuationToken}:{}})}function requestSignature(request){return JSON.stringify({goal:request.goal,source:request.source??null,since:request.since??null,until:request.until??null,limit:request.limit,cursor:request.cursor,freshness:request.freshness})}function projectedRecord(row){const source=text(row.source),sourceId=text(row.source_id)||text(row.sourceId),ref=text(row.id)||text(row.ref)||(source&&sourceId?`${source}:${sourceId}`:""),title=text(row.title)||sourceId,body=text(row.body),ts=text(row.ts);if(!source||!sourceId||!ref)return;return{ref,source,sourceId,title:bounded(title,300),excerpt:bounded(body),ts}}function providerRecord(row){const source=row.source,sourceId=row.sourceId??row.eventId??row.ref??"";if(!source||!sourceId)return;const fields=object(row.fields)?row.fields:{},title=text(fields.name)||text(fields.title)||text(fields.subject)||row.kind||sourceId,body=row.body??text(fields.content),ts=row.ts??"";return{ref:row.ref??row.eventId??`${source}:${sourceId}`,source,sourceId,title:bounded(title,300),excerpt:bounded(body),ts}}function queryMatches(content,query){return query.toLocaleLowerCase().split(/[^\p{L}\p{N}._+-]+/u).filter(Boolean).every(term=>term==="thu"?/(?:^|[^a-z0-9])thu(?:$|[^a-z0-9])/u.test(content):content.includes(term))}function matches(row,plan){const content=`${row.title}
|
|
2
|
-
${row.excerpt}`.toLocaleLowerCase();return plan.queries.some(query=>queryMatches(content,query))}function ranked(rows,plan,limit){const focus=plan.focus.toLocaleLowerCase(),deduped=new Map;for(const row of rows)deduped.set(`${row.source}\0${row.sourceId}`,row);return[...deduped.values()].sort((a,b)=>{const score=row=>{const title=row.title.toLocaleLowerCase(),content=`${title}
|
|
3
|
-
${row.excerpt}`.toLocaleLowerCase(),semantic=plan.semanticTerms.filter(term=>content.includes(term.toLocaleLowerCase())).length;return(title===focus?0:title.includes(focus)?10:queryMatches(content,focus)?20:30)-Math.min(semantic,9)};const recency=String(b.ts).localeCompare(String(a.ts));return(plan.recencyFirst?recency||score(a)-score(b):score(a)-score(b)||recency)||a.ref.localeCompare(b.ref)}).slice(0,limit)}function classifies(patterns,value){return patterns.some(pattern=>pattern.test(value))}function classifyGoal(goal){if(/accept|admission|接收|录用|中稿/iu.test(goal))return"acceptance";if(/submit|submission|投稿|提交/iu.test(goal))return"submission";if(/decision|result|outcome|决定|结果|结论/iu.test(goal))return"decision";if(/meet|invite|schedule|会议|邀请|日程/iu.test(goal))return"meeting";if(/invoice|receipt|payment|发票|收据|付款/iu.test(goal))return"payment";return"general"}function classifyEvidence(record){const content=`${record.title}
|
|
4
|
-
${record.excerpt}`;if(classifies(ACCEPTANCE_NOTICE_PATTERNS,content))return"acceptance_notice";if(classifies(SUBMISSION_CONFIRMATION_PATTERNS,content))return"submission_confirmation";if(classifies(DECISION_NOTICE_PATTERNS,content))return"decision_notice";return"related"}function analyze(goal,records,coverage){const classification=classifyGoal(goal),evidence=records.slice(0,5).map(record=>({ref:record.ref,classification:classifyEvidence(record),quote:bounded(queryText(record.excerpt||record.title),240)}));const acceptance=evidence.some(item=>item.classification==="acceptance_notice"),submission=evidence.some(item=>item.classification==="submission_confirmation"),complete=coverage.status==="complete";let conclusion;if(classification==="acceptance"&&acceptance)conclusion={status:"confirmed",reason:"acceptance_notice",statement:"An acceptance notice matching the goal was found."};else if(classification==="acceptance"&&submission)conclusion={status:complete?"not_confirmed":"inconclusive",reason:"submission_confirmation_only",statement:"Only a submission confirmation was found; it does not establish acceptance."};else if(classification==="acceptance")conclusion=complete?{status:"not_confirmed",reason:"no_evidence",statement:"No acceptance notice was found in the completed search."}:{status:"inconclusive",reason:"coverage_incomplete",statement:"No acceptance notice was found, but search coverage is incomplete."};else if(records.length)conclusion={status:"confirmed",reason:"matching_evidence",statement:"Matching evidence was found."};else if(complete)conclusion={status:"not_confirmed",reason:"no_evidence",statement:"No matching evidence was found in the completed search."};else conclusion={status:"inconclusive",reason:"coverage_incomplete",statement:"No matching evidence was found, but search coverage is incomplete."};return{classification,conclusion,evidence,coverage}}function cachedCoverage(plan){return{status:"partial",scope:"cached-index",plannedQueries:plan.queries.length,completedQueries:plan.queries.length,reasons:["cached_only"]}}function liveCoverage(plan,completedQueries,options){const reasons=[];if(options.providerUnavailable)reasons.push("provider_unavailable");if(options.timeBudgetExhausted)reasons.push("time_budget_exhausted");if(options.stoppedEarly)reasons.push("early_stop");if(options.saturated)reasons.push("result_limit");if(options.warnings)reasons.push("provider_warning");if(completedQueries<plan.queries.length&&!options.stoppedEarly&&!options.providerUnavailable&&!options.timeBudgetExhausted)reasons.push("query_failed");return{status:reasons.length?"partial":"complete",scope:"live-provider",plannedQueries:plan.queries.length,completedQueries,reasons}}async function vaultRows(vault,request,plan,signal,includeLegacyCache=false){if(!vault)return ok({records:[],more:false});const params=[];const terms=plan.queries.map(query=>{if(query.toLocaleLowerCase()==="thu"){params.push("*[^a-z0-9]thu[^a-z0-9]*","*[^a-z0-9]thu[^a-z0-9]*");return"((' ' || lower(coalesce(title,'')) || ' ') GLOB ? OR (' ' || lower(coalesce(body,'')) || ' ') GLOB ?)"}const needle2=`%${escapeLike(query.toLocaleLowerCase())}%`;params.push(needle2,needle2);return"(lower(coalesce(title,'')) LIKE ? ESCAPE '\\' OR lower(coalesce(body,'')) LIKE ? ESCAPE '\\')"});const clauses=[`(${terms.join(" OR ")})`];if(request.source){clauses.push("source = ?");params.push(request.source)}if(request.since){clauses.push("ts >= ?");params.push(request.since)}if(request.until){clauses.push("ts <= ?");params.push(request.until)}const focus=plan.focus.toLocaleLowerCase(),needle=`%${escapeLike(focus)}%`,requested=request.limit+1;params.push(focus,needle,requested,request.cursor);const relevance=`CASE WHEN lower(coalesce(title,'')) = ? THEN 0 WHEN lower(coalesce(title,'')) LIKE ? ESCAPE '\\' THEN 1 ELSE 2 END`;const order=plan.recencyFirst?`ts DESC, ${relevance}, id`:`${relevance}, ts DESC, id`;const result=await vault.sql({sql:`WITH available AS (
|
|
5
|
-
SELECT id,source,source_id,title,body,ts,stream FROM z_current_records
|
|
6
|
-
${includeLegacyCache?`UNION ALL SELECT r.id,r.source,r.source_id,r.title,r.body,r.ts,r.stream FROM z_records r
|
|
7
|
-
WHERE r.stream='provider-read' AND NOT EXISTS(SELECT 1 FROM current_record_heads h WHERE h.source=r.source AND h.source_id=r.source_id)`:""}
|
|
8
|
-
) SELECT id,source,source_id,title,body,ts,stream FROM available WHERE ${clauses.join(" AND ")} ORDER BY ${order} LIMIT ? OFFSET ?`,params},signal);if(!("ok"in result))return result;const records=result.ok.rows.map(row=>projectedRecord(row)).filter(row=>!!row),more=records.length>request.limit;return ok({records:records.slice(0,request.limit),more,legacyCache:result.ok.rows.some(row=>row.stream==="provider-read")})}function waiting(value){const{source,state,jobId,recoveryHandle,helpUrl,expiresAt,reason,nextStep,errorCode,retryability}=value;return{state:state==="ready"?"failed":state,source,records:[],nextCursor:null,route:"none",warnings:[],...jobId?{jobId}:{},...recoveryHandle?{recoveryHandle}:{},...helpUrl?{helpUrl}:{},...expiresAt?{expiresAt}:{},...reason?{reason}:{},...nextStep?{nextStep}:{},...errorCode?{errorCode}:{},...retryability?{retryability}:{}}}const TIME_BUDGET=Symbol("time-budget");async function withinBudget(run,remainingMs,signal){if(remainingMs<=0)return TIME_BUDGET;const timeout=new AbortController,combined=signal?AbortSignal.any([signal,timeout.signal]):timeout.signal;let timer;const expired=new Promise(resolve=>{timer=setTimeout(()=>{resolve(TIME_BUDGET);timeout.abort()},remainingMs);timer.unref?.()});try{return await Promise.race([run(combined),expired])}finally{if(timer)clearTimeout(timer)}}export async function findContent(dependencies,request,signal){const startedAt=Date.now(),budgetMs=dependencies.budgetMs??12e3,plan=buildContentFindPlan(request.goal),signature=requestSignature(request);let continuation;if(request.continuationToken){if(!dependencies.continuations)return businessError("failed_precondition","This find continuation is unavailable. Start one new find request.","connector");const consumed=dependencies.continuations.consume(request.continuationToken,signature);if("error"in consumed)return businessError("invalid_argument",consumed.error==="mismatch"?"The continuation token does not match this find request.":"The continuation token is missing, expired or already used.","connector");continuation=consumed.state}let cached=await vaultRows(dependencies.vault,request,plan,signal,dependencies.includeLegacyCache);if(!("ok"in cached))return cached;let cachedRecords=ranked(cached.ok.records,plan,request.limit),cachedNext=cached.ok.more?request.cursor+request.limit:null;let data=request.source?await dependencies.dataState?.(request.source):void 0;const vaultCoverage=()=>{if(!dependencies.dataState)return cachedCoverage(plan);const reasons=[];if(!dependencies.vault)reasons.push("vault_unavailable");if("ok"in cached&&cached.ok.legacyCache)reasons.push("provider_read_cache");if(!data||data.phase!=="ready"||data.coverage.status!=="complete")reasons.push("sync_incomplete");if(data?.coverage.since&&(!request.since||request.since<data.coverage.since))reasons.push("outside_synced_range");if(data?.coverage.until&&(!request.until||request.until>data.coverage.until))reasons.push("outside_synced_range");const checked=data?.checkedAt?Date.parse(data.checkedAt):NaN;if(!Number.isFinite(checked)||(dependencies.now?.()??Date.now())-checked>(dependencies.maxAgeMs??15*6e4))reasons.push("stale_or_unchecked");reasons.push(...data?.coverage.limitations??[]);return{status:reasons.length?"partial":"complete",scope:"cached-index",plannedQueries:plan.queries.length,completedQueries:plan.queries.length,reasons,...data?.checkedAt?{checkedAt:data.checkedAt}:{},...data?{resources:data.coverage.resources}:{}}};const fromVault=()=>ok(cachedRecords.length?{state:"found",records:cachedRecords,nextCursor:cachedNext,route:"vault",warnings:[],...analyze(request.goal,cachedRecords,vaultCoverage())}:{state:"empty",records:[],nextCursor:null,route:"vault",warnings:[],...analyze(request.goal,[],vaultCoverage())});if(!request.source||request.freshness==="cached")return fromVault();if(!continuation&&request.freshness!=="live"&&vaultCoverage().status==="complete")return fromVault();if(!continuation&&cachedRecords.length&&request.freshness!=="live"&&!plan.recencyFirst)return fromVault();if(!continuation&&dependencies.refresh){await withinBudget(refreshSignal=>dependencies.refresh(request.source,refreshSignal),Math.min(4e3,budgetMs-(Date.now()-startedAt)),signal);if(signal?.aborted)return businessError("aborted","Find cancelled.","connector");cached=await vaultRows(dependencies.vault,request,plan,signal,dependencies.includeLegacyCache);if(!("ok"in cached))return cached;cachedRecords=ranked(cached.ok.records,plan,request.limit);cachedNext=cached.ok.more?request.cursor+request.limit:null;data=await dependencies.dataState?.(request.source);if(vaultCoverage().status==="complete")return fromVault()}if(!dependencies.ensureReady)return businessError("unavailable","The Resident ensure-ready service is inactive.","plugin");const readiness=await withinBudget(readySignal=>dependencies.ensureReady(request.source,readySignal),budgetMs-(Date.now()-startedAt),signal);if(signal?.aborted)return businessError("aborted","Find cancelled.","connector");if(readiness===TIME_BUDGET){const next=!request.continuationToken&&dependencies.continuations?dependencies.continuations.issue({signature,liveRecords:[],nextQueryIndex:0,successfulReads:0,warnings:[],saturated:false}):void 0;return ok({state:"partial",records:cachedRecords,nextCursor:cachedNext,route:cachedRecords.length?"vault":"live",warnings:["live:time_budget_exhausted"],errorCode:"deadline_exceeded",...next?{continuationToken:next.token,continuationExpiresAt:next.expiresAt}:{},...analyze(request.goal,cachedRecords,liveCoverage(plan,0,{warnings:false,saturated:false,stoppedEarly:false,timeBudgetExhausted:true}))})}if(!("ok"in readiness))return ok({state:"failed",source:request.source,records:[],nextCursor:null,route:"none",warnings:[],errorCode:"err"in readiness?readiness.err.code:"unavailable",retryability:"none"});if(readiness.ok.state!=="ready")return ok(waiting(readiness.ok));if(!dependencies.hub){if(cachedRecords.length){const coverage2=liveCoverage(plan,0,{warnings:true,saturated:false,stoppedEarly:false,providerUnavailable:true});return ok({state:"partial",records:cachedRecords,nextCursor:cachedNext,route:"vault",warnings:["live:unavailable"],errorCode:"unavailable",...analyze(request.goal,cachedRecords,coverage2)})}return ok({state:"failed",source:request.source,records:[],nextCursor:null,route:"none",warnings:[],errorCode:"unavailable",retryability:"none"})}const providerPlan=request.source==="gmail"&&plan.gmailQueries?{...plan,queries:plan.gmailQueries}:plan;const liveRecords=[...continuation?.liveRecords??[]],warnings=[...continuation?.warnings??[]];let successfulReads=continuation?.successfulReads??0,firstError=continuation?.firstError,saturated=continuation?.saturated??false,stoppedEarly=false;const startIndex=continuation?.nextQueryIndex??0;for(let index=startIndex;index<providerPlan.queries.length;index++){const query=providerPlan.queries[index];const readLimit=Math.min(request.limit,20),readRequest={query,limit:readLimit,...request.since?{since:request.since}:{},...request.until?{until:request.until}:{}};const live=await withinBudget(readSignal=>dependencies.hub.read(request.source,readRequest,{retention:"transient",signal:readSignal}),budgetMs-(Date.now()-startedAt),signal);if(live===TIME_BUDGET){const records2=ranked([...cachedRecords,...liveRecords],plan,request.limit),coverage2=liveCoverage(providerPlan,successfulReads,{warnings:!!warnings.length,saturated,stoppedEarly:false,timeBudgetExhausted:true});const next=!request.continuationToken&&dependencies.continuations?dependencies.continuations.issue({signature,liveRecords,nextQueryIndex:index,successfulReads,warnings,...firstError?{firstError}:{},saturated}):void 0;return ok({state:"partial",records:records2,nextCursor:cachedNext,route:liveRecords.length?"live":cachedRecords.length?"vault":"live",warnings:[...warnings,"live:time_budget_exhausted"],errorCode:"deadline_exceeded",...next?{continuationToken:next.token,continuationExpiresAt:next.expiresAt}:{},...analyze(request.goal,records2,coverage2)})}if("err"in live){firstError??=live.err.code;warnings.push(`live:plan-${index+1}:${live.err.code}`);continue}successfulReads++;if("ok"in live){warnings.push(...live.ok.warnings);saturated||=live.ok.returned>=readLimit;liveRecords.push(...live.ok.records.map(providerRecord).filter(row=>!!row).filter(row=>matches(row,plan)))}if(ranked(liveRecords,plan,request.limit).length>=request.limit&&index<providerPlan.queries.length-1){stoppedEarly=true;break}}const coverage=liveCoverage(providerPlan,successfulReads,{warnings:!!warnings.length,saturated,stoppedEarly});if(!successfulReads&&firstError){if(cachedRecords.length)return ok({state:"partial",records:cachedRecords,nextCursor:cachedNext,route:"vault",warnings,errorCode:firstError,...analyze(request.goal,cachedRecords,coverage)});return ok({state:"failed",source:request.source,records:[],nextCursor:null,route:"none",warnings,errorCode:firstError,retryability:"none"})}const records=ranked([...cachedRecords,...liveRecords],plan,request.limit);if(!records.length)return ok({state:"empty",records:[],nextCursor:null,route:"live",warnings,...analyze(request.goal,[],coverage)});return ok({state:"found",records,nextCursor:null,route:"live",warnings,...analyze(request.goal,records,coverage)})}
|
|
1
|
+
import{matchExcerpt}from"./match-excerpt.js";import{normalizeSearchDocument,normalizeSearchText}from"@zortexhq/plugin-vault-sqlite/api";import{randomUUID}from"node:crypto";import{contentReadRoute}from"./read-route.js";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";export function createContentFindContinuations(options={}){const now=options.now??Date.now,makeToken=options.token??randomUUID,ttlMs=options.ttlMs??5*6e4,maxEntries=options.maxEntries??256;const entries=new Map;const clean=()=>{const at=now();for(const[token,row]of entries)if(row.expiresAt<=at)entries.delete(token)};return{issue(state){clean();while(entries.size>=maxEntries)entries.delete(entries.keys().next().value);let token;do token=makeToken();while(entries.has(token));const expiresAt=now()+ttlMs;entries.set(token,{state,expiresAt});return{token,expiresAt:new Date(expiresAt).toISOString()}},consume(token,signature){clean();const row=entries.get(token);if(!row)return{error:"missing"};if(row.state.signature!==signature)return{error:"mismatch"};entries.delete(token);return{state:row.state}}}}const SOURCE_ALIASES={"drive":"google-drive","google-drive":"google-drive","google-calendar":"google-calendar","calendar":"google-calendar","google-mail":"gmail","gmail":"gmail"};const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const text=value=>typeof value==="string"?value:"";const bounded=(value,max=800)=>value.length<=max?value:value.slice(0,max);const iso=value=>typeof value==="string"&&Number.isFinite(Date.parse(value));const queryText=value=>normalizeSearchText(value).replace(/\s+/gu," ");const escapeLike=value=>value.replace(/[\\%_]/gu,match=>"\\"+match);const STOP_WORDS=new Set(["a","an","and","are","about","did","do","does","email","emails","find","for","from","has","have","i","in","is","it","latest","mail","me","my","of","on","or","please","show","that","the","to","was","were","what","whether","with"]);const ENTITY_GROUPS=[{test:/清华|tsinghua|\bthu\b/iu,aliases:["\u6E05\u534E","Tsinghua","THU"]}];const SEMANTIC_GROUPS=[{test:/accept|admission|接收|录用|中稿/iu,terms:["accept","accepted","acceptance","decision","notification","\u5F55\u7528","\u63A5\u6536","\u4E2D\u7A3F"],expansions:["accepted","acceptance"]},{test:/submit|submission|投稿|提交/iu,terms:["submit","submitted","submission","manuscript","paper","\u6295\u7A3F","\u63D0\u4EA4"],expansions:["submission","submitted"]},{test:/meet|会议|日程|邀请/iu,terms:["meeting","invite","invitation","schedule","\u4F1A\u8BAE","\u9080\u8BF7","\u65E5\u7A0B"],expansions:["invitation","meeting"]},{test:/invoice|receipt|payment|发票|收据|付款/iu,terms:["invoice","receipt","payment","paid","\u53D1\u7968","\u6536\u636E","\u4ED8\u6B3E"],expansions:["invoice","receipt"]},{test:/decision|决定|结论/iu,terms:["decision","result","outcome","\u51B3\u5B9A","\u7ED3\u8BBA"],expansions:["decision","result"]}];const ACCEPTANCE_NOTICE_PATTERNS=[/\b(?:paper|manuscript|abstract|proposal|article)\b.{0,100}\b(?:has been |is |was )?(?:accepted|approved)\b/isu,/\bwe are (?:pleased|delighted) to (?:inform|notify)\b.{0,140}\baccepted\b/isu,/\bacceptance (?:notification|notice|decision|letter)\b/iu,/(?:论文|稿件|摘要|文章).{0,50}(?:已)?(?:接收|录用|中稿)/su,/(?:接收|录用|中稿)(?:通知|决定|函)/u];const SUBMISSION_CONFIRMATION_PATTERNS=[/\b(?:submission|manuscript|paper) (?:has been |was )?(?:successfully )?(?:submitted|received)\b/iu,/\b(?:submission|receipt) confirmation\b/iu,/(?:投稿|提交)(?:已)?(?:成功|收到|确认)|(?:成功|已经)(?:投稿|提交)/u];const DECISION_NOTICE_PATTERNS=[/\b(?:decision|result|outcome) (?:notification|notice|letter)\b/iu,/(?:决定|结果|结论)(?:通知|函)/u];export function buildContentFindPlan(goal){const normalized=queryText(goal),quoted=[...normalized.matchAll(/["“”']([^"“”']{2,120})["“”']/gu)].map(row=>queryText(row[1]));const acronyms=[...normalized.matchAll(/\b[A-Z][A-Z0-9-]{1,}(?:\s+[A-Z][A-Z0-9-]{1,}){0,4}\b/gu)].map(row=>row[0]);const identifiers=[...normalized.matchAll(/\b[A-Za-z][A-Za-z0-9._+-]*\d[A-Za-z0-9._+-]*\b/gu)].map(row=>row[0]);const words=[...normalized.matchAll(/[A-Za-z][A-Za-z0-9._+-]{2,}/gu)].map(row=>row[0]).filter(word=>!STOP_WORDS.has(word.toLocaleLowerCase()));const entity=ENTITY_GROUPS.find(group=>group.test.test(normalized));const entityAliases=entity?[...entity.aliases].filter(alias=>alias!=="THU"||/\bTHU\b/iu.test(normalized)).sort((left,right)=>Number(!normalized.toLocaleLowerCase().includes(left.toLocaleLowerCase()))-Number(!normalized.toLocaleLowerCase().includes(right.toLocaleLowerCase()))):[];const chineseFocus=queryText(normalized.replace(/(?:请|麻烦)?(?:帮我|给我)?(?:找一下|查一下|搜索一下|查找一下|看看|寻找)/gu," ").replace(/(?:邮件|邮箱|消息)(?:中|里|内)?/gu," ").replace(/(?:最近|最新)(?:的)?|(?:一封|一条|一份|一个)|(?:有关|相关)(?:的)?|关于/gu," ")).replace(/^[和与及的中里内]+|[和与及的中里内]+$/gu,"");const focus=queryText(entityAliases[0]??quoted[0]??acronyms[0]??identifiers[0]??(words.slice(0,4).join(" ")||chineseFocus||normalized)).slice(0,500);const groups=SEMANTIC_GROUPS.filter(group=>group.test.test(normalized));const semanticTerms=[...new Set([...entityAliases,...groups.flatMap(group=>group.terms)])].slice(0,16);const expansions=[...new Set(groups.flatMap(group=>group.expansions))].filter(term=>!focus.toLocaleLowerCase().includes(term.toLocaleLowerCase()));const queries=(entityAliases.length?entityAliases:[...expansions.slice(0,2).map(term=>`${focus} ${term}`),focus,normalized]).map(value=>queryText(value).slice(0,500)).filter((value,index,all)=>!!value&&all.indexOf(value)===index).slice(0,3);const gmailAlias=entityAliases.length?`{${entityAliases.join(" ")}}`:void 0;const gmailQueries=gmailAlias?[...expansions.slice(0,2).map(term=>`${gmailAlias} ${term}`),gmailAlias].slice(0,3):void 0;return{focus:focus||normalized.slice(0,500),queries:queries.length?queries:[normalized.slice(0,500)],semanticTerms,recencyFirst:/latest|newest|most recent|最近|最新/iu.test(normalized),...quoted.length?{phrases:quoted}:{},...gmailQueries?{gmailQueries}:{}}}export function parseContentFindRequest(value){if(!object(value)||Object.keys(value).some(key=>!["goal","source","since","until","limit","cursor","freshness","continuationToken","snapshotToken"].includes(key)))return businessError("invalid_argument","Pass goal and optional source, since, until, limit, cursor, freshness, continuationToken and snapshotToken.","kernel");const goal=typeof value.goal==="string"?queryText(value.goal):"";if(!goal||Buffer.byteLength(goal)>4096)return businessError("invalid_argument","goal must be nonempty and at most 4096 bytes.","kernel");let source;if(value.source!==void 0){if(typeof value.source!=="string")return businessError("invalid_argument","source must be a connector id.","kernel");const candidate=value.source.trim().toLowerCase();source=SOURCE_ALIASES[candidate]??candidate;if(!/^[a-z][a-z0-9-]{0,63}$/u.test(source))return businessError("invalid_argument","source must be a lowercase connector id.","kernel")}if(value.since!==void 0&&!iso(value.since)||value.until!==void 0&&!iso(value.until)||typeof value.since==="string"&&typeof value.until==="string"&&Date.parse(value.since)>Date.parse(value.until))return businessError("invalid_argument","since and until must be ISO timestamps.","kernel");const limit=value.limit===void 0?5:value.limit,cursor=value.cursor===void 0?0:value.cursor,freshness=value.freshness===void 0?"auto":value.freshness;if(!Number.isSafeInteger(limit)||Number(limit)<1||Number(limit)>50)return businessError("invalid_argument","limit must be an integer from 1 to 50.","kernel");if(!Number.isSafeInteger(cursor)||Number(cursor)<0)return businessError("invalid_argument","cursor must be a nonnegative integer.","kernel");if(freshness!=="auto"&&freshness!=="cached"&&freshness!=="live")return businessError("invalid_argument","freshness must be auto, cached or live.","kernel");if(value.continuationToken!==void 0&&(typeof value.continuationToken!=="string"||!/^[A-Za-z0-9_-]{16,200}$/u.test(value.continuationToken)))return businessError("invalid_argument","continuationToken must be the opaque token returned by the prior find result.","kernel");if(value.snapshotToken!==void 0&&(typeof value.snapshotToken!=="string"||!/^[A-Za-z0-9_-]{16,200}$/u.test(value.snapshotToken)))return businessError("invalid_argument","snapshotToken must be the opaque token from this query.","kernel");if(value.snapshotToken!==void 0&&value.continuationToken!==void 0)return businessError("invalid_argument","Use either a snapshot or an online continuation.","kernel");return ok({goal,...typeof value.snapshotToken==="string"?{snapshotToken:value.snapshotToken}:{},...source?{source}:{},...typeof value.since==="string"?{since:value.since}:{},...typeof value.until==="string"?{until:value.until}:{},limit:Number(limit),cursor:Number(cursor),freshness,...typeof value.continuationToken==="string"?{continuationToken:value.continuationToken}:{}})}function requestSignature(request){return JSON.stringify({goal:request.goal,source:request.source??null,since:request.since??null,until:request.until??null,limit:request.limit,cursor:request.cursor,freshness:request.freshness})}function projectedRecord(row,plan){const source=text(row.source),sourceId=text(row.source_id)||text(row.sourceId),ref=text(row.id)||text(row.ref)||(source&&sourceId?`${source}:${sourceId}`:""),title=text(row.title)||sourceId,body=text(row.body),ts=text(row.ts);if(!source||!sourceId||!ref)return;return{ref,source,sourceId,title:bounded(title,300),excerpt:matchExcerpt(body,plan),ts}}function providerRecord(row,plan){const source=row.source,sourceId=row.sourceId??row.eventId??row.ref??"";if(!source||!sourceId)return;const fields=object(row.fields)?row.fields:{},title=text(fields.name)||text(fields.title)||text(fields.subject)||row.kind||sourceId,rawBody=row.body??text(fields.content),ts=row.ts??"";const normalized=normalizeSearchDocument({source,title,body:rawBody,payload:fields});const body=normalized.body;if(!matches({title:normalized.title,excerpt:body},plan))return;return{ref:row.ref??row.eventId??`${source}:${sourceId}`,source,sourceId,title:bounded(normalized.title,300),excerpt:matchExcerpt(body,plan),ts}}const queryTokens=query=>queryText(query).toLowerCase().split(/\s+/u).filter(Boolean).slice(0,8);function queryMatches(content,query){return queryTokens(query).every(term=>term==="thu"?/(?:^|[^a-z0-9])thu(?:$|[^a-z0-9])/u.test(content):content.includes(term))}function matches(row,plan){const content=queryText(`${row.title} ${row.excerpt}`).toLowerCase();return(plan.phrases??[]).every(phrase=>content.includes(queryText(phrase).toLowerCase()))&&plan.queries.some(query=>queryMatches(content,query))}function ranked(rows,plan,limit){const focus=plan.focus.toLocaleLowerCase(),deduped=new Map;for(const row of rows)deduped.set(`${row.source}\0${row.sourceId}`,row);return[...deduped.values()].sort((a,b)=>{const score=row=>{const title=row.title.toLowerCase();return title===focus?0:title.includes(focus)?1:2};const recency=String(b.ts).localeCompare(String(a.ts));return(plan.recencyFirst?recency||score(a)-score(b):score(a)-score(b)||recency)||a.ref.localeCompare(b.ref)}).slice(0,limit)}function classifies(patterns,value){return patterns.some(pattern=>pattern.test(value))}function classifyGoal(goal){if(/accept|admission|接收|录用|中稿/iu.test(goal))return"acceptance";if(/submit|submission|投稿|提交/iu.test(goal))return"submission";if(/decision|result|outcome|决定|结果|结论/iu.test(goal))return"decision";if(/meet|invite|schedule|会议|邀请|日程/iu.test(goal))return"meeting";if(/invoice|receipt|payment|发票|收据|付款/iu.test(goal))return"payment";return"general"}function classifyEvidence(record){const content=`${record.title}
|
|
2
|
+
${record.excerpt}`;if(classifies(ACCEPTANCE_NOTICE_PATTERNS,content))return"acceptance_notice";if(classifies(SUBMISSION_CONFIRMATION_PATTERNS,content))return"submission_confirmation";if(classifies(DECISION_NOTICE_PATTERNS,content))return"decision_notice";return"related"}function analyze(goal,records,coverage){const classification=classifyGoal(goal),evidence=records.slice(0,5).map(record=>({ref:record.ref,classification:classifyEvidence(record),quote:matchExcerpt(record.excerpt||record.title,buildContentFindPlan(goal),240)}));const acceptance=evidence.some(item=>item.classification==="acceptance_notice"),submission=evidence.some(item=>item.classification==="submission_confirmation"),complete=coverage.status==="complete";let conclusion;if(classification==="acceptance"&&acceptance)conclusion={status:"confirmed",reason:"acceptance_notice",statement:"An acceptance notice matching the goal was found."};else if(classification==="acceptance"&&submission)conclusion={status:complete?"not_confirmed":"inconclusive",reason:"submission_confirmation_only",statement:"Only a submission confirmation was found; it does not establish acceptance."};else if(classification==="acceptance")conclusion=complete?{status:"not_confirmed",reason:"no_evidence",statement:"No acceptance notice was found in the completed search."}:{status:"inconclusive",reason:"coverage_incomplete",statement:"No acceptance notice was found, but search coverage is incomplete."};else if(records.length)conclusion={status:"confirmed",reason:"matching_evidence",statement:"Matching evidence was found."};else if(complete)conclusion={status:"not_confirmed",reason:"no_evidence",statement:"No matching evidence was found in the completed search."};else conclusion={status:"inconclusive",reason:"coverage_incomplete",statement:"No matching evidence was found, but search coverage is incomplete."};return{classification,conclusion,evidence,coverage}}function cachedCoverage(plan){return{status:"partial",scope:"cached-index",plannedQueries:plan.queries.length,completedQueries:plan.queries.length,reasons:["cached_only"]}}function liveCoverage(plan,completedQueries,options){const reasons=[];if(options.providerUnavailable)reasons.push("provider_unavailable");if(options.timeBudgetExhausted)reasons.push("time_budget_exhausted");if(options.stoppedEarly)reasons.push("early_stop");if(options.saturated)reasons.push("result_limit");if(options.warnings)reasons.push("provider_warning");if(completedQueries<plan.queries.length&&!options.stoppedEarly&&!options.providerUnavailable&&!options.timeBudgetExhausted)reasons.push("query_failed");return{status:reasons.length?"partial":"complete",scope:"live-provider",plannedQueries:plan.queries.length,completedQueries,reasons}}async function vaultRows(vault,request,plan,signal){if(!vault)return businessError("unavailable","Local Vault search is inactive.","storage");const params=[];const predicate=term=>{if(term==="thu"){params.push("*[^a-z0-9]thu[^a-z0-9]*","*[^a-z0-9]thu[^a-z0-9]*");return"((' ' || lower(title) || ' ') GLOB ? OR (' ' || lower(body) || ' ') GLOB ?)"}const needle=`%${escapeLike(term)}%`;params.push(needle,needle);return"(lower(title) LIKE ? ESCAPE '\\' OR lower(body) LIKE ? ESCAPE '\\')"};const alternatives=plan.queries.map(query=>"("+queryTokens(query).map(predicate).join(" AND ")+")");const clauses=[`(${alternatives.join(" OR ")})`,...(plan.phrases??[]).map(phrase=>predicate(queryText(phrase).toLowerCase()))];if(request.source){clauses.push("source = ?");params.push(request.source)}if(request.since){clauses.push("ts >= ?");params.push(request.since)}if(request.until){clauses.push("ts <= ?");params.push(request.until)}const anchors=[...new Set(plan.queries.flatMap(queryTokens))];const positions=anchors.map(term=>{params.push(term);return"coalesce(nullif(instr(lower(body),?),0),length(body)+1)"});const anchor=positions.length===1?positions[0]:`min(${positions.join(",")})`;const start=`max(1,${anchor}-80)`;const focus=plan.focus.toLowerCase();params.push(focus,`%${escapeLike(focus)}%`,request.limit+1,request.cursor);const relevance="CASE WHEN lower(title) = ? THEN 0 WHEN lower(title) LIKE ? ESCAPE '\\' THEN 1 ELSE 2 END";const order=plan.recencyFirst?`ts DESC, ${relevance}, id`:`${relevance}, ts DESC, id`;const result=await vault.sql({sql:`WITH matched AS (SELECT * FROM z_search_records WHERE ${clauses.join(" AND ")}) SELECT id,source,source_id,substr(title,1,300) AS title,CASE WHEN length(body)>798 THEN '\u2026'||substr(body,${start},796)||'\u2026' ELSE body END AS body,ts,stream FROM matched ORDER BY ${order} LIMIT ? OFFSET ?`,params},signal);if(!("ok"in result))return result;const records=result.ok.rows.map(row=>projectedRecord(row,plan)).filter(row=>!!row),more=records.length>request.limit;return ok({records:records.slice(0,request.limit),more})}function waiting(value){const{source,state,jobId,recoveryHandle,helpUrl,expiresAt,reason,nextStep,errorCode,retryability}=value;return{state:state==="ready"?"failed":state,source,records:[],nextCursor:null,route:"none",warnings:[],...jobId?{jobId}:{},...recoveryHandle?{recoveryHandle}:{},...helpUrl?{helpUrl}:{},...expiresAt?{expiresAt}:{},...reason?{reason}:{},...nextStep?{nextStep}:{},...errorCode?{errorCode}:{},...retryability?{retryability}:{}}}const TIME_BUDGET=Symbol("time-budget");async function withinBudget(run,remainingMs,signal){if(remainingMs<=0)return TIME_BUDGET;const timeout=new AbortController,combined=signal?AbortSignal.any([signal,timeout.signal]):timeout.signal;let timer;const expired=new Promise(resolve=>{timer=setTimeout(()=>{resolve(TIME_BUDGET);timeout.abort()},remainingMs);timer.unref?.()});try{return await Promise.race([run(combined),expired])}finally{if(timer)clearTimeout(timer)}}export async function findContent(dependencies,request,signal){if(signal?.aborted)return businessError("aborted","Find cancelled.","connector");const startedAt=Date.now(),budgetMs=dependencies.budgetMs??12e3,plan=buildContentFindPlan(request.goal),signature=requestSignature(request);let continuation;if(request.continuationToken){if(!dependencies.continuations)return businessError("failed_precondition","This find continuation is unavailable. Start one new find request.","connector");const consumed=dependencies.continuations.consume(request.continuationToken,signature);if("error"in consumed)return businessError("invalid_argument",consumed.error==="mismatch"?"The continuation token does not match this find request.":"The continuation token is missing, expired or already used.","connector");continuation=consumed.state}const route=dependencies.route??contentReadRoute(request.source);const snapshotSignature=requestSignature({...request,cursor:0}),generation=route==="local"?await dependencies.generation?.(request.source)??"isolated":void 0;if(request.snapshotToken){if(route!=="local")return businessError("invalid_argument","Online-only sources do not accept local snapshots.","connector");const saved=dependencies.snapshots?.read(request.snapshotToken,snapshotSignature,generation);if(!saved)return businessError("failed_precondition","Query snapshot expired, changed authority or does not match. Start a new query.","connector");const records2=saved.value.records.slice(request.cursor,request.cursor+request.limit);if(records2.length&&dependencies.vault){const visible=await dependencies.vault.sql({sql:`SELECT id FROM events WHERE erased=0 AND id IN (${records2.map(()=>"?").join(",")})`,params:records2.map(row=>row.ref)},signal);if(!("ok"in visible))return visible;if(visible.ok.rows.length!==records2.length)return businessError("failed_precondition","A snapshot record was erased. Start a new query.","connector")}return ok({...records2.length?{state:"found",records:records2,nextCursor:request.cursor+records2.length<saved.value.records.length?request.cursor+records2.length:null}:{state:"empty",records:[],nextCursor:null},route:"vault",warnings:[],snapshotToken:saved.snapshotToken,snapshotExpiresAt:saved.snapshotExpiresAt,asOf:saved.asOf,...analyze(request.goal,records2,saved.value.coverage)})}if(route==="local"&&dependencies.snapshots&&request.cursor>0)return businessError("invalid_argument","Continue pagination with the snapshotToken from the first page.","connector");const asOf=new Date(dependencies.now?.()??Date.now()).toISOString();const capturedData=request.source?await dependencies.dataState?.(request.source):void 0;const scanRequest=route==="local"&&dependencies.snapshots?{...request,limit:199,cursor:0}:request;let cached=route==="local"?await vaultRows(dependencies.vault,scanRequest,plan,signal):ok({records:[],more:false,legacyCache:false});if(!("ok"in cached))return cached;let cachedRecords=cached.ok.records.slice(0,request.limit),cachedNext=cached.ok.more?request.cursor+request.limit:null;const data=capturedData;const vaultCoverage=()=>{if(!dependencies.dataState)return cachedCoverage(plan);const reasons=[];if(!dependencies.vault)reasons.push("vault_unavailable");if("ok"in cached&&cached.ok.legacyCache)reasons.push("provider_read_cache");if(!data||data.phase!=="ready"||data.coverage.status!=="complete")reasons.push("sync_incomplete");if(data?.coverage.since&&(!request.since||request.since<data.coverage.since))reasons.push("outside_synced_range");if(data?.coverage.until&&(!request.until||request.until>data.coverage.until))reasons.push("outside_synced_range");const checked=data?.checkedAt?Date.parse(data.checkedAt):NaN;if(!Number.isFinite(checked)||(dependencies.now?.()??Date.now())-checked>(dependencies.maxAgeMs??15*6e4))reasons.push("stale_or_unchecked");reasons.push(...data?.coverage.limitations??[]);return{status:reasons.length?"partial":"complete",scope:"cached-index",plannedQueries:plan.queries.length,completedQueries:plan.queries.length,reasons,...data?.checkedAt?{checkedAt:data.checkedAt}:{},...data?{resources:data.coverage.resources}:{}}};const fromVault=()=>ok(cachedRecords.length?{state:"found",records:cachedRecords,nextCursor:cachedNext,route:"vault",warnings:[],...analyze(request.goal,cachedRecords,vaultCoverage())}:{state:"empty",records:[],nextCursor:null,route:"vault",warnings:[],...analyze(request.goal,[],vaultCoverage())});if(route==="local"||!request.source){if(!dependencies.snapshots)return fromVault();if(generation!==await dependencies.generation?.(request.source)&&dependencies.generation)return businessError("permission_denied","Source authority changed during query.","connector");const coverage2=vaultCoverage();if(cached.ok.more){coverage2.status="partial";coverage2.reasons.push("snapshot_result_limit")}const records2=cached.ok.records,token=dependencies.snapshots.issue({signature:snapshotSignature,generation,records:records2,coverage:coverage2,asOf,bounded:cached.ok.more});if(!token)return businessError("resource_exhausted","Query snapshot exceeded its memory budget. Narrow the query.","connector");const page=records2.slice(0,request.limit);return ok({...page.length?{state:"found",records:page,nextCursor:page.length<records2.length?page.length:null}:{state:"empty",records:[],nextCursor:null},route:"vault",warnings:[],...token,...analyze(request.goal,page,coverage2)})}if(!dependencies.ensureReady)return businessError("unavailable","The Resident ensure-ready service is inactive.","plugin");const readiness=await withinBudget(readySignal=>dependencies.ensureReady(request.source,readySignal),budgetMs-(Date.now()-startedAt),signal);if(signal?.aborted)return businessError("aborted","Find cancelled.","connector");if(readiness===TIME_BUDGET){const next=!request.continuationToken&&dependencies.continuations?dependencies.continuations.issue({signature,liveRecords:[],nextQueryIndex:0,successfulReads:0,warnings:[],saturated:false}):void 0;return ok({state:"partial",records:cachedRecords,nextCursor:cachedNext,route:cachedRecords.length?"vault":"live",warnings:["live:time_budget_exhausted"],errorCode:"deadline_exceeded",...next?{continuationToken:next.token,continuationExpiresAt:next.expiresAt}:{},...analyze(request.goal,cachedRecords,liveCoverage(plan,0,{warnings:false,saturated:false,stoppedEarly:false,timeBudgetExhausted:true}))})}if(!("ok"in readiness))return ok({state:"failed",source:request.source,records:[],nextCursor:null,route:"none",warnings:[],errorCode:"err"in readiness?readiness.err.code:"unavailable",retryability:"none"});if(readiness.ok.state!=="ready")return ok(waiting(readiness.ok));if(!dependencies.hub){if(cachedRecords.length){const coverage2=liveCoverage(plan,0,{warnings:true,saturated:false,stoppedEarly:false,providerUnavailable:true});return ok({state:"partial",records:cachedRecords,nextCursor:cachedNext,route:"vault",warnings:["live:unavailable"],errorCode:"unavailable",...analyze(request.goal,cachedRecords,coverage2)})}return ok({state:"failed",source:request.source,records:[],nextCursor:null,route:"none",warnings:[],errorCode:"unavailable",retryability:"none"})}const providerPlan=request.source==="gmail"&&plan.gmailQueries?{...plan,queries:plan.gmailQueries}:plan;const liveRecords=[...continuation?.liveRecords??[]],warnings=[...continuation?.warnings??[]];let successfulReads=continuation?.successfulReads??0,firstError=continuation?.firstError,saturated=continuation?.saturated??false,stoppedEarly=false;const startIndex=continuation?.nextQueryIndex??0;for(let index=startIndex;index<providerPlan.queries.length;index++){const query=providerPlan.queries[index];const readLimit=Math.min(request.limit,20),readRequest={query,limit:readLimit,...request.since?{since:request.since}:{},...request.until?{until:request.until}:{}};const live=await withinBudget(readSignal=>dependencies.hub.read(request.source,readRequest,{retention:"transient",signal:readSignal}),budgetMs-(Date.now()-startedAt),signal);if(live===TIME_BUDGET){const records2=ranked([...cachedRecords,...liveRecords],plan,request.limit),coverage2=liveCoverage(providerPlan,successfulReads,{warnings:!!warnings.length,saturated,stoppedEarly:false,timeBudgetExhausted:true});const next=!request.continuationToken&&dependencies.continuations?dependencies.continuations.issue({signature,liveRecords,nextQueryIndex:index,successfulReads,warnings,...firstError?{firstError}:{},saturated}):void 0;return ok({state:"partial",records:records2,nextCursor:cachedNext,route:liveRecords.length?"live":cachedRecords.length?"vault":"live",warnings:[...warnings,"live:time_budget_exhausted"],errorCode:"deadline_exceeded",...next?{continuationToken:next.token,continuationExpiresAt:next.expiresAt}:{},...analyze(request.goal,records2,coverage2)})}if("err"in live){firstError??=live.err.code;warnings.push(`live:plan-${index+1}:${live.err.code}`);continue}successfulReads++;if("ok"in live){warnings.push(...live.ok.warnings);saturated||=live.ok.returned>=readLimit;liveRecords.push(...live.ok.records.filter(row=>row.source===request.source&&(!request.since||!!row.ts&&Date.parse(row.ts)>=Date.parse(request.since))&&(!request.until||!!row.ts&&Date.parse(row.ts)<=Date.parse(request.until))).map(row=>providerRecord(row,plan)).filter(row=>!!row))}if(ranked(liveRecords,plan,request.limit).length>=request.limit&&index<providerPlan.queries.length-1){stoppedEarly=true;break}}const coverage=liveCoverage(providerPlan,successfulReads,{warnings:!!warnings.length,saturated,stoppedEarly});if(!successfulReads&&firstError){if(cachedRecords.length)return ok({state:"partial",records:cachedRecords,nextCursor:cachedNext,route:"vault",warnings,errorCode:firstError,...analyze(request.goal,cachedRecords,coverage)});return ok({state:"failed",source:request.source,records:[],nextCursor:null,route:"none",warnings,errorCode:firstError,retryability:"none"})}const records=ranked([...cachedRecords,...liveRecords],plan,request.limit);if(!records.length)return ok({state:"empty",records:[],nextCursor:null,route:"live",warnings,...analyze(request.goal,[],coverage)});return ok({state:"found",records,nextCursor:null,route:"live",warnings,...analyze(request.goal,records,coverage)})}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID}from"node:crypto";export function createFindSnapshots(options={}){const now=options.now??Date.now,ttl=options.ttlMs??5*6e4,maxBytes=options.maxBytes??8*1024*1024;const entries=new Map;let bytes=0;const remove=key=>{const row=entries.get(key);if(row){bytes-=row.bytes;entries.delete(key)}};const clean=()=>{for(const[key,row]of entries)if(row.expiresAt<=now())remove(key)};return{issue(value){clean();const size=Buffer.byteLength(JSON.stringify(value));if(size>maxBytes)return;while(entries.size&&(bytes+size>maxBytes||entries.size>=64))remove(entries.keys().next().value);const token=randomUUID(),expiresAt=now()+ttl;entries.set(token,{value:structuredClone(value),expiresAt,bytes:size});bytes+=size;return{snapshotToken:token,snapshotExpiresAt:new Date(expiresAt).toISOString(),asOf:value.asOf}},read(token,signature,generation){clean();const row=entries.get(token);if(!row)return;if(row.value.signature!==signature||row.value.generation!==generation)return;return{value:structuredClone(row.value),snapshotToken:token,snapshotExpiresAt:new Date(row.expiresAt).toISOString(),asOf:row.value.asOf}},clear(){entries.clear();bytes=0}}}
|