@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
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{usageOutcome,usageResultSummary,usageErrorCategory,withFeedbackFlow,createTraceRecorder}from"@zortexhq/plugin-telemetry/api";import{instrumentConnectorHub}from"./operational-hub.js";import{validateRead}from"./api/index.js";import{sharedReadDiscovery}from"./shared-read-discovery.js";import{createEnrollment}from"./enrollment.js";import{createConnectorHttp}from"./transport.js";import{createAuthorizationMetrics}from"./authorization-metrics.js";import{createConnectionFeedback}from"./connection-feedback.js";import{actionReview,sameActionReview,validateReviewedInput}from"./action-review.js";import{createResourceAdmission}from"./resource-admission.js";import{bindConnectorActionRetention,isTransientConnectorAction,withTransientConnectorAction}from"./transient-action-context.js";import{informationFingerprint,publicFileSnapshot,sameProviderFile,validFileHandle,validInformationHandle,validProviderFile}from"./share-snapshot.js";export const name="zortex-connector-hub";export const inject=["zortexVaultStore"];function readiness(source,value){const invalid=()=>businessError("data_loss","Source returned invalid readiness metadata.","plugin");if(!value||value.source!==source||value.basis!=="actions"&&value.basis!=="read"||!value.operation)return invalid();if(value.basis==="actions"&&(!Number.isSafeInteger(value.actions)||value.actions<0))return invalid();const operation=value.operation;if(operation.state!=="not-run"&&operation.state!=="succeeded")return invalid();if(value.basis==="read"&&(operation.state!=="succeeded"||!Number.isSafeInteger(operation.returned)||operation.returned<0))return invalid();if(operation.state==="not-run")return ok({source,basis:value.basis,...value.basis==="actions"?{actions:value.actions}:{},operation:{state:"not-run"}});if(operation.returned!==void 0&&(!Number.isSafeInteger(operation.returned)||operation.returned<0))return invalid();let evidence;if(operation.evidence!==void 0){const{origin,observedAt,stage,ownRecords}=operation.evidence;if(!["live","connection-first-read","vault-cache"].includes(origin)||!["read-page","read-own-posts"].includes(stage)||typeof observedAt!=="string"||observedAt.length>27||!Number.isFinite(Date.parse(observedAt))||new Date(observedAt).toISOString()!==observedAt||ownRecords!==void 0&&(!Number.isSafeInteger(ownRecords)||ownRecords<0))return invalid();evidence={origin,observedAt,stage,...ownRecords!==void 0?{ownRecords}:{}}}return ok({source,basis:value.basis,...value.basis==="actions"?{actions:value.actions}:{},operation:{state:"succeeded",...operation.returned!==void 0?{returned:operation.returned}:{},...evidence?{evidence}:{}}})}function shareReadSchema(schema){const effect=schema.effect,http=schema.httpMethod;const effectClass=effect==="read"?"read":effect&&typeof effect==="object"&&!Array.isArray(effect)&&effect.class==="read"?"read":effect===void 0?void 0:"other";const httpClass=http===void 0?void 0:http==="GET"?"read":"other";return(effectClass==="read"||httpClass==="read")&&effectClass!=="other"&&httpClass!=="other"}export function createConnectorHub(dependencies={}){const statusTimeoutMs=dependencies.statusTimeoutMs??15e3;if(!Number.isSafeInteger(statusTimeoutMs)||statusTimeoutMs<1||statusTimeoutMs>3e4)throw Error("Invalid source metadata deadline.");const authorization=createAuthorizationMetrics(dependencies.metrics,dependencies.authorizationPollMs,dependencies.authorizationObserveMs);const sources=new Map,sourceEpochs=new Map,jobs=new Map,usability=new Map,observations=new Set;let closed=false,closing,admissionSequence=0;const SNAPSHOT_TTL_MS=30*60*1e3;const informationSnapshots=new Map;const fileSnapshots=new Map;const statusStop=new AbortController,statusProbes=new Map;const fail=message=>businessError("failed_precondition",message,"plugin");const provider=source=>closed?void 0:sources.get(source);const purgeSnapshots=()=>{const now=Date.now();for(const[handle,row]of informationSnapshots)if(Date.parse(row.public.expiresAt)<=now)informationSnapshots.delete(handle);for(const[handle,row]of fileSnapshots)if(Date.parse(row.public.expiresAt)<=now)fileSnapshots.delete(handle)};const samePublic=(left,right)=>{try{return JSON.stringify(left)===JSON.stringify(right)}catch{return false}};const admitted=(kind,source,needs,task,signal)=>{const retained=bindConnectorActionRetention(task);return dependencies.admission?.run(`${kind}/${source}/${++admissionSequence}`,needs,()=>Promise.resolve(retained()),{...signal?{signal}:{}})??retained()};const providerNeeds=(source,extra={})=>({http:1,[`provider:${source}`]:1,...extra});const unavailableStatus=(item,message)=>({...item.info,state:"unavailable",...item.actions?{actions:true}:{},message});function probeStatus(item){if(item.registration==="deferred")return Promise.resolve({...item.info,state:"unavailable",registration:"deferred",actions:false,message:"Setup required; no active provider is registered. Restart after setup."});const epoch=sourceEpochs.get(item.info.source)??0,existing=statusProbes.get(item);if(existing)return existing.epoch===epoch?existing.result:Promise.resolve(unavailableStatus(item,"A previous source registration is still settling."));const deadline=new AbortController,signal=AbortSignal.any([deadline.signal,statusStop.signal]);const timer=setTimeout(()=>deadline.abort(),statusTimeoutMs);let removeAbort=()=>{};const interrupted=new Promise(resolve=>{const cancel=()=>{clearTimeout(timer);resolve(unavailableStatus(item,closed?"Connector hub is inactive.":"Source status timed out."))};if(signal.aborted)cancel();else{signal.addEventListener("abort",cancel,{once:true});removeAbort=()=>signal.removeEventListener("abort",cancel)}});const operation=Promise.resolve().then(()=>admitted("probe",item.info.source,{[`provider:${item.info.source}`]:1},()=>signal.aborted?businessError("aborted","Source metadata inspection was cancelled.","plugin"):item.status({signal}),signal));const observed=operation.then(result2=>"ok"in result2?{...result2.ok,...item.actions?{actions:true}:{}}:unavailableStatus(item,"err"in result2?result2.err.message:"Source state was not confirmed."),()=>unavailableStatus(item,"Source status failed."));const result=Promise.race([observed,interrupted]);statusProbes.set(item,{epoch,result});const settled=()=>{clearTimeout(timer);removeAbort();if(statusProbes.get(item)?.result===result)statusProbes.delete(item)};void operation.then(settled,settled);return result}const retentionFailure=(item,options)=>options?.retention!==void 0&&options.retention!=="transient"?businessError("invalid_argument","Unsupported connector result retention policy.","plugin"):(options?.retention==="transient"||isTransientConnectorAction())&&item?.requiresPersistentPayloads?fail("This source requires persistent payload storage and has no qualified transient operation."):void 0;function observe(source,usable){if(!dependencies.availabilityMetrics||usability.get(source)===usable)return Promise.resolve();const task=(async()=>{try{const saved=await dependencies.metrics?.()?.record({operation:"connector.usable",source,outcome:usable?"ok":"cancelled",durationMs:0,internal:true});if(saved&&"ok"in saved&&saved.ok.recorded)usability.set(source,usable)}catch{}})();observations.add(task);void task.finally(()=>observations.delete(task));return task}async function observeResult(source,result,enabled){if(!enabled)return observe(source,false);const outcome=usageOutcome(result);if(outcome==="ok"||outcome==="empty")await observe(source,true);else if(outcome==="fault"||outcome==="auth-blocked")await observe(source,false)}const service={hasSource:source=>provider(source)!==void 0,...dependencies.metrics?{queryMetrics:"owned"}:{},register(item){if(closed)throw Error("Connector hub is inactive.");if(!/^[a-z][a-z0-9-]{0,63}$/.test(item.info.source))throw Error("Invalid source identity.");if(sources.has(item.info.source))throw Error("Duplicate connector source.");sources.set(item.info.source,item);sourceEpochs.set(item.info.source,(sourceEpochs.get(item.info.source)??0)+1);return()=>{if(sources.get(item.info.source)===item){sources.delete(item.info.source);sourceEpochs.set(item.info.source,(sourceEpochs.get(item.info.source)??0)+1);authorization.withdraw(item);void observe(item.info.source,false)}}},replaceDeferred(expected,item){const source=expected.info.source;if(closed||expected.registration!=="deferred"||item.registration==="deferred"||item.info.source!==source||sources.get(source)!==expected)return void 0;sources.set(source,item);sourceEpochs.set(source,(sourceEpochs.get(source)??0)+1);return()=>{if(sources.get(source)===item){sources.delete(source);sourceEpochs.set(source,(sourceEpochs.get(source)??0)+1);authorization.withdraw(item);void observe(source,false)}}},async status(options){if(closed)return businessError("unavailable","Connector hub is inactive.","plugin");if(options?.signal?.aborted)return businessError("aborted","Source status inspection was cancelled.","plugin");const states=Promise.all([...sources.values()].map(async item=>{const epoch=sourceEpochs.get(item.info.source),state=await probeStatus(item);return provider(item.info.source)===item&&sourceEpochs.get(item.info.source)===epoch?state:unavailableStatus(item,"Source was disabled before its status reply.")}));let removeAbort=()=>{};const cancelled=new Promise(resolve=>{if(options?.signal){const cancel=()=>resolve(businessError("aborted","Source status inspection was cancelled.","plugin"));options.signal.addEventListener("abort",cancel,{once:true});removeAbort=()=>options.signal.removeEventListener("abort",cancel)}});try{const result=await Promise.race([states.then(ok),cancelled]);return closed?businessError("unavailable","Connector hub is inactive.","plugin"):result}finally{removeAbort()}},async connect(source,options){options={...options,automatic:options?.automatic===true};const item=provider(source);if(!item)return fail("Source is not enabled: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(options.savedAccessOnly&&!item.supportsSavedReconnect)return businessError("failed_precondition","This source cannot reconnect using saved access.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;return withTransientConnectorAction(options?.retention==="transient",()=>admitted("connect",source,providerNeeds(source,{worker:1,[`refresh:${source}`]:1}),()=>withFeedbackFlow(source,async()=>{const trace=createTraceRecorder(dependencies.metrics,source);await trace.step("source_selected","completed");await trace.step("authorization_started","started");const started=performance.now();let result;try{result=await item.connect(options)}catch(error){await authorization.immediate(item,businessError(options?.signal?.aborted?"aborted":"unavailable","Connection failed.","plugin"),started);throw error}if(provider(source)!==item){result=businessError("unavailable","Source was disabled.","plugin");await authorization.immediate(item,result,started,"source_disabled");return result}if("ok"in result&&result.ok.source!==source)result=businessError("data_loss","Mismatched connection source.","plugin");if("ok"in result){jobs.set(result.ok.id,item);await authorization.track(item,result,started)}else await authorization.immediate(item,result,started);return result},authorization.currentFlow(item)),options?.signal))},job(id){const item=jobs.get(id);if(!item)return businessError("not_found","Unknown connector connection job.","plugin");if(provider(item.info.source)!==item)return businessError("unavailable","Source was disabled.","plugin");const result=item.job(id);authorization.observe(item,id,result);return result},cancelJob(id,source){const tracked=jobs.get(id),item=tracked??(source?provider(source):void 0);if(!item)return businessError("not_found","Unknown connector connection job.","plugin");if(source&&item.info.source!==source)return businessError("not_found","Unknown connector connection job.","plugin");if(provider(item.info.source)!==item)return businessError("unavailable","Source was disabled.","plugin");return item.cancelJob?.(id)},async settleObservations(options){if(options?.closing)await authorization.close();else await authorization.settle();await Promise.allSettled([...observations])},async check(source,options){const item=provider(source);if(!item)return fail("Source is not enabled: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;if(options?.signal?.aborted)return businessError("aborted","Source readiness was cancelled.","plugin");try{const result=item.check?await withTransientConnectorAction(options?.retention==="transient",()=>admitted("check",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.check(options),options?.signal)):await service.read(source,{limit:1},options).then(result2=>"ok"in result2?ok({source,basis:"read",operation:{state:"succeeded",returned:result2.ok.returned,...result2.ok.evidence?{evidence:result2.ok.evidence}:{}}}):"empty"in result2?ok({source,basis:"read",operation:{state:"succeeded",returned:0}}):result2);if(provider(source)!==item)return businessError("unavailable","Source was disabled before readiness delivery.","plugin");if(options?.signal?.aborted)return businessError("aborted","Source readiness was cancelled.","plugin");if("err"in result)return result;if(!("ok"in result))return businessError("data_loss","Source did not provide readiness metadata.","plugin");return readiness(source,result.ok)}catch{return businessError(options?.signal?.aborted?"aborted":"unavailable","Source readiness did not complete.","plugin")}},async read(source,request={},options){const item=provider(source);const run=()=>withFeedbackFlow(source,async()=>{const trace=createTraceRecorder(dependencies.metrics,source);if(dependencies.metrics)await trace.step("read_started","started");const started=performance.now();let disabled=false;const execute=async()=>{if(!item)return fail("Source is not enabled: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(provider(source)!==item){disabled=true;return businessError("unavailable","Source was disabled before the query.","plugin")}const retention=retentionFailure(item,options);if(retention)return retention;const invalid=validateRead(request,item.info.readById?["fileId"]:[]);if(invalid)return invalid;try{const result2=await item.read(request,options);if(provider(source)!==item){disabled=true;return businessError("unavailable","Source was disabled during the query.","plugin")}if("ok"in result2&&(result2.ok.source!==source||result2.ok.returned!==result2.ok.records.length||result2.ok.returned>(request.limit??1)))return businessError("data_loss","Source returned invalid or unbounded records.","plugin");return result2}catch{return businessError(options?.signal?.aborted?"aborted":"unavailable","Connector query did not complete.","plugin")}};const result=await execute();try{const metrics=dependencies.metrics?.();if(metrics){const summary=usageResultSummary(result),errorCategory=usageErrorCategory(result);await metrics.record({operation:"connector.read",outcome:disabled?"cancelled":usageOutcome(result),durationMs:performance.now()-started,internal:options?.internalTelemetry??false,...item?{source:item.info.source}:{},..."err"in result?{code:result.err.code}:{},...summary?{result:summary}:{},...errorCategory?{errorCategory}:{}})}}catch{}await trace.step("read_verified","err"in result?result.err.code==="aborted"?"cancelled":"failed":"ok"in result||"empty"in result?"completed":"unknown","ok"in result?{count:result.ok.returned}:"empty"in result?{count:0}:{});if(item)await observeResult(source,result,provider(source)===item);return item&&provider(source)!==item?businessError("unavailable","Source was disabled before query delivery.","plugin"):result});const feedback=dependencies.feedback?.();return withTransientConnectorAction(options?.retention==="transient",()=>admitted("read",source,providerNeeds(source,{worker:1}),()=>feedback?feedback.run(source,run):run(),options?.signal))},close(){if(!closing){closed=true;statusStop.abort();for(const source of sources.keys())void observe(source,false);sources.clear();jobs.clear();informationSnapshots.clear();fileSnapshots.clear();closing=(async()=>{await authorization.close();await Promise.allSettled([...observations])})()}return closing},async catalog(source,input,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{const item=provider(source);if(!item)return fail("Source is not installed or enabled: "+source);const retention=retentionFailure(item,options);if(retention)return retention;if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(!item.actions){const action=sharedReadDiscovery(item.info);return ok({source,actions:[{name:action.name,effect:action.effect,operation:action.operation}],total:1,discovery:"Request method=connector.read for the shared action schema; execute it with operation=action, not connector.invoke."})}const result=await admitted("catalog",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.actions.catalog(input),options?.signal);return provider(source)===item?result:businessError("unavailable","Source was disabled before its catalog reply.","plugin")})},async method(source,name2,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{const item=provider(source);if(!item)return fail("Source is not installed or enabled: "+source);const retention=retentionFailure(item,options);if(retention)return retention;if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(!item.actions)return name2==="connector.read"?ok(sharedReadDiscovery(item.info)):fail("This source has no installed action schema: "+name2);const result=await admitted("method",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.actions.method(name2),options?.signal);return provider(source)===item?result:businessError("unavailable","Source was disabled before its schema reply.","plugin")})},async review(source,name2,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{const item=provider(source),epoch=sourceEpochs.get(source)??0;if(!item?.actions)return fail("This source has no installed action schema: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;const result=await admitted("review",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.actions.method(name2),options?.signal);if(provider(source)!==item)return businessError("unavailable","Source was disabled before its schema reply.","plugin");if(!("ok"in result))return result;return actionReview(source,name2,epoch,result.ok)})},async invokeReviewed(review,input,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{if(!review||typeof review!=="object"||typeof review.source!=="string"||typeof review.name!=="string"||typeof review.revision!=="string")return fail("A reviewed action handle is required.");const item=provider(review.source),epoch=sourceEpochs.get(review.source)??0;if(!item?.actions)return fail("This source has no installed action port: "+review.source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;const current=await admitted("invoke-review",review.source,providerNeeds(review.source,{probe:1,discovery:1}),()=>item.actions.method(review.name),options?.signal);if(provider(review.source)!==item)return businessError("unavailable","Source was disabled before action review.","plugin");if(!("ok"in current))return current;if(!sameActionReview(review,epoch,current.ok))return businessError("failed_precondition","Provider action schema changed after review; inspect the new schema before dispatch.","plugin");const valid=validateReviewedInput(review,input);if(!("ok"in valid))return valid;return service.invoke(review.source,review.name,input,options)})},async invoke(source,name2,input,options){const item=provider(source);if(!item?.actions)return fail("This source has no installed action port: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const run=()=>withFeedbackFlow(source,async()=>{const trace=createTraceRecorder(dependencies.metrics,source);await trace.step("invoke_started","started");if(provider(source)!==item){await trace.step("invoke_finished","failed",{reason:"source_disabled"});return businessError("unavailable","Source was disabled before action dispatch.","plugin")}const retention=retentionFailure(item,options);if(retention){await trace.step("invoke_finished","failed",{reason:"provider_error"});return retention}const started=performance.now();let result;try{const reply=await admitted("invoke",source,providerNeeds(source,{worker:1}),()=>{if(provider(source)!==item)return businessError("unavailable","Source was disabled before action dispatch.","plugin");if(!item.actions.reportsActionAccess){try{options?.onActionAccess?.("legacy")}catch{}const legacyOptions=options?{...options}:void 0;if(legacyOptions)delete legacyOptions.onActionAccess;return item.actions.invoke(name2,input,legacyOptions)}return item.actions.invoke(name2,input,options)},options?.signal);result=provider(source)===item?reply:businessError("unavailable","Source was disabled before its reply.","plugin")}catch{result=businessError(options?.signal?.aborted?"aborted":"unavailable","Source action did not finish.","plugin")}let outcome="unknown";try{outcome=usageOutcome(result);const metrics=dependencies.metrics?.();if(metrics){const summary=usageResultSummary(result),errorCategory=usageErrorCategory(result);await metrics.record({operation:"connector.invoke",source,outcome,durationMs:performance.now()-started,internal:true,..."err"in result?{code:result.err.code}:{},...summary?{result:summary}:{},...errorCategory?{errorCategory}:{}})}}catch{}await trace.step("invoke_finished",outcome==="ok"||outcome==="empty"?"completed":outcome==="cancelled"?"cancelled":outcome==="auth-blocked"?"waiting":outcome==="fault"||outcome==="invalid"?"failed":"unknown");await observeResult(source,result,provider(source)===item);return provider(source)===item?result:businessError("unavailable","Source was disabled before action delivery.","plugin")});const feedback=dependencies.feedback?.();return withTransientConnectorAction(options?.retention==="transient",()=>feedback?feedback.run(source,run):run())},async captureInformation(review,input,options){purgeSnapshots();if(!review||typeof review!=="object"||!review.schema||!shareReadSchema(review.schema))return businessError("permission_denied","Share snapshots require an explicitly read-only Connector Action.","plugin");const item=provider(review.source),epoch=sourceEpochs.get(review.source)??0;if(!item)return fail("Source is not enabled: "+review.source);const result=await service.invokeReviewed(review,input,options);if(!("ok"in result))return result;if(provider(review.source)!==item||sourceEpochs.get(review.source)!==epoch)return businessError("unavailable","Source changed before its information snapshot was retained.","plugin");const fingerprint=informationFingerprint(result.ok);if(!("ok"in fingerprint))return fingerprint;const handle=randomUUID(),capturedAt=new Date().toISOString(),expiresAt=new Date(Date.now()+SNAPSHOT_TTL_MS).toISOString();const snapshot={kind:"information",source:review.source,name:review.name,handle,capturedAt,expiresAt,...fingerprint.ok};let savedReview,savedInput;try{savedReview=structuredClone(review);savedInput=structuredClone(input)}catch{return businessError("invalid_argument","Connector snapshot input is not cloneable.","plugin")}informationSnapshots.set(handle,{public:snapshot,review:savedReview,input:savedInput,provider:item,epoch});return ok(snapshot)},async verifyInformation(snapshot,options){purgeSnapshots();if(!validInformationHandle(snapshot))return businessError("invalid_argument","Pass one Connector information snapshot handle.","plugin");const stored=informationSnapshots.get(snapshot.handle);if(!stored||!samePublic(stored.public,snapshot))return fail("Connector information snapshot is missing, expired or changed.");if(provider(stored.public.source)!==stored.provider||sourceEpochs.get(stored.public.source)!==stored.epoch)return fail("Connector source changed after preview; review the Share again.");const result=await service.invokeReviewed(stored.review,stored.input,options);if(!("ok"in result))return result;const current=informationFingerprint(result.ok);if(!("ok"in current))return current;if(current.ok.sha256!==stored.public.sha256||current.ok.bytes!==stored.public.bytes)return businessError("aborted","Connector information changed after preview; review the Share again.","plugin");return ok(stored.public)},async inspectFile(source,input,options){purgeSnapshots();if(!input||typeof input.id!=="string"||!input.id||Buffer.byteLength(input.id)>1024)return businessError("invalid_argument","Connector file inspection requires one provider identity.","plugin");const item=provider(source),epoch=sourceEpochs.get(source)??0;if(!item?.fileSnapshots)return fail("This source does not provide file snapshots: "+source);const retention=retentionFailure(item,options);if(retention)return retention;if(options?.signal?.aborted)return businessError("aborted","Connector file inspection was cancelled.","plugin");const result=await withTransientConnectorAction(options?.retention==="transient",()=>admitted("file-inspect",source,providerNeeds(source,{worker:1}),()=>item.fileSnapshots.inspect(input,options),options?.signal));if(provider(source)!==item||sourceEpochs.get(source)!==epoch)return businessError("unavailable","Source changed before its file snapshot was retained.","plugin");if(!("ok"in result))return result;const checked=validProviderFile(result.ok,source);if(!("ok"in checked))return checked;let retained;try{retained=structuredClone(checked.ok)}catch{return businessError("data_loss","Connector file snapshot metadata is not retainable.","plugin")}const handle=randomUUID(),expiresAt=new Date(Date.now()+SNAPSHOT_TTL_MS).toISOString(),snapshot=publicFileSnapshot(handle,retained,expiresAt);fileSnapshots.set(handle,{public:snapshot,file:retained,provider:item,epoch});return ok(snapshot)},async materializeFile(snapshot,options){purgeSnapshots();if(!validFileHandle(snapshot))return businessError("invalid_argument","Pass one Connector file snapshot handle.","plugin");const stored=fileSnapshots.get(snapshot.handle);if(!stored||!samePublic(stored.public,snapshot))return fail("Connector file snapshot is missing, expired or changed.");const item=provider(stored.public.source);if(item!==stored.provider||sourceEpochs.get(stored.public.source)!==stored.epoch||!item.fileSnapshots)return fail("Connector source changed after preview; review the Share again.");const retention=retentionFailure(item,options);if(retention)return retention;if(options?.signal?.aborted)return businessError("aborted","Connector file materialization was cancelled.","plugin");const result=await withTransientConnectorAction(options?.retention==="transient",()=>admitted("file-materialize",stored.public.source,providerNeeds(stored.public.source,{worker:1}),()=>item.fileSnapshots.materialize(stored.file,options),options?.signal));if(provider(stored.public.source)!==item||sourceEpochs.get(stored.public.source)!==stored.epoch)return businessError("unavailable","Source changed while its file snapshot was materialized.","plugin");if(!("ok"in result))return result;const checked=validProviderFile(result.ok.file,stored.public.source);if(!("ok"in checked))return checked;if(!sameProviderFile(stored.file,checked.ok)||!(result.ok.content instanceof Uint8Array)||result.ok.mimeType!==stored.public.mimeType||result.ok.size!==result.ok.content.byteLength||result.ok.size<0)return businessError("data_loss","Connector file bytes did not match the inspected snapshot.","plugin");return ok({file:stored.public,content:result.ok.content,mimeType:result.ok.mimeType,size:result.ok.size})}};return instrumentConnectorHub(service,dependencies.metrics,id=>jobs.get(id)?.info.source)}export async function apply(ctx){const feedback=createConnectionFeedback({store:()=>ctx.get("zortexSqliteVault")?.createPrivateStore("connection-feedback"),connection:async source=>{const local=ctx.get("zortexLocalSourceRegistry")?.get(source);if(local)return ok(local);const level1=ctx.get("zortexLevel1Connectors");const namespace=source==="figma"&&level1?.provider("figma")?.spec.auth.kind==="fields"?"figma--pat":source;const result=await ctx.zortexVaultStore.connection(namespace);return namespace!==source&&"ok"in result&&result.ok?ok({...result.ok,source}):result}});ctx.provide("zortexConnectionFeedback",feedback);const admission=createResourceAdmission(),http=await createConnectorHttp({admission}),hub=createConnectorHub({metrics:()=>ctx.get("zortexTelemetry"),feedback:()=>feedback,availabilityMetrics:true,admission}),enrollment=createEnrollment({vault:ctx.zortexVaultStore,transport:http.fetch,metrics:()=>ctx.get("zortexTelemetry"),feedback:()=>feedback});ctx.provide("zortexResourceAdmission",admission);ctx.provide("zortexConnectorHttp",http.fetch);ctx.provide("zortexConnectorHub",hub);ctx.provide("zortexConnectorEnrollment",enrollment);ctx.effect(()=>()=>hub.close());ctx.effect(()=>async()=>{await enrollment.close();await http.close();admission.close()})}
|
|
1
|
+
import{randomUUID}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{usageOutcome,usageResultSummary,usageErrorCategory,withFeedbackFlow,createTraceRecorder}from"@zortexhq/plugin-telemetry/api";import{instrumentConnectorHub}from"./operational-hub.js";import{validateRead}from"./api/index.js";import{sharedReadDiscovery}from"./shared-read-discovery.js";import{createEnrollment}from"./enrollment.js";import{createConnectorHttp}from"./transport.js";import{createAuthorizationMetrics}from"./authorization-metrics.js";import{createConnectionFeedback}from"./connection-feedback.js";import{actionReview,sameActionReview,validateReviewedInput}from"./action-review.js";import{createResourceAdmission}from"./resource-admission.js";import{bindConnectorActionRetention,isTransientConnectorAction,withTransientConnectorAction}from"./transient-action-context.js";import{informationFingerprint,publicFileSnapshot,sameProviderFile,validFileHandle,validInformationHandle,validProviderFile}from"./share-snapshot.js";export const name="zortex-connector-hub";export const inject=["zortexVaultStore"];function readiness(source,value){const invalid=()=>businessError("data_loss","Source returned invalid readiness metadata.","plugin");if(!value||value.source!==source||value.basis!=="actions"&&value.basis!=="read"||!value.operation)return invalid();if(value.basis==="actions"&&(!Number.isSafeInteger(value.actions)||value.actions<0))return invalid();const operation=value.operation;if(operation.state!=="not-run"&&operation.state!=="succeeded")return invalid();if(value.basis==="read"&&(operation.state!=="succeeded"||!Number.isSafeInteger(operation.returned)||operation.returned<0))return invalid();if(operation.state==="not-run")return ok({source,basis:value.basis,...value.basis==="actions"?{actions:value.actions}:{},operation:{state:"not-run"}});if(operation.returned!==void 0&&(!Number.isSafeInteger(operation.returned)||operation.returned<0))return invalid();let evidence;if(operation.evidence!==void 0){const{origin,observedAt,stage,ownRecords}=operation.evidence;if(!["live","connection-first-read","vault-cache"].includes(origin)||!["read-page","read-own-posts"].includes(stage)||typeof observedAt!=="string"||observedAt.length>27||!Number.isFinite(Date.parse(observedAt))||new Date(observedAt).toISOString()!==observedAt||ownRecords!==void 0&&(!Number.isSafeInteger(ownRecords)||ownRecords<0))return invalid();evidence={origin,observedAt,stage,...ownRecords!==void 0?{ownRecords}:{}}}return ok({source,basis:value.basis,...value.basis==="actions"?{actions:value.actions}:{},operation:{state:"succeeded",...operation.returned!==void 0?{returned:operation.returned}:{},...evidence?{evidence}:{}}})}function shareReadSchema(schema){const effect=schema.effect,http=schema.httpMethod;const effectClass=effect==="read"?"read":effect&&typeof effect==="object"&&!Array.isArray(effect)&&effect.class==="read"?"read":effect===void 0?void 0:"other";const httpClass=http===void 0?void 0:http==="GET"?"read":"other";return(effectClass==="read"||httpClass==="read")&&effectClass!=="other"&&httpClass!=="other"}export function createConnectorHub(dependencies={}){const statusTimeoutMs=dependencies.statusTimeoutMs??15e3;if(!Number.isSafeInteger(statusTimeoutMs)||statusTimeoutMs<1||statusTimeoutMs>3e4)throw Error("Invalid source metadata deadline.");const authorization=createAuthorizationMetrics(dependencies.metrics,dependencies.authorizationPollMs,dependencies.authorizationObserveMs);const sources=new Map,sourceEpochs=new Map,jobs=new Map,usability=new Map,observations=new Set;let closed=false,closing,admissionSequence=0;const SNAPSHOT_TTL_MS=30*60*1e3;const informationSnapshots=new Map;const fileSnapshots=new Map;const statusStop=new AbortController,statusProbes=new Map;const fail=message=>businessError("failed_precondition",message,"plugin");const provider=source=>closed?void 0:sources.get(source);const purgeSnapshots=()=>{const now=Date.now();for(const[handle,row]of informationSnapshots)if(Date.parse(row.public.expiresAt)<=now)informationSnapshots.delete(handle);for(const[handle,row]of fileSnapshots)if(Date.parse(row.public.expiresAt)<=now)fileSnapshots.delete(handle)};const samePublic=(left,right)=>{try{return JSON.stringify(left)===JSON.stringify(right)}catch{return false}};const admitted=(kind,source,needs,task,signal)=>{const retained=bindConnectorActionRetention(task);return dependencies.admission?.run(`${kind}/${source}/${++admissionSequence}`,needs,()=>Promise.resolve(retained()),{...signal?{signal}:{}})??retained()};const providerNeeds=(source,extra={})=>({http:1,[`provider:${source}`]:1,...extra});const unavailableStatus=(item,message)=>({...item.info,state:"unavailable",...item.actions?{actions:true}:{},message});function probeStatus(item){if(item.registration==="deferred")return Promise.resolve({...item.info,state:"unavailable",registration:"deferred",actions:false,message:"Setup required; no active provider is registered. Restart after setup."});const epoch=sourceEpochs.get(item.info.source)??0,existing=statusProbes.get(item);if(existing)return existing.epoch===epoch?existing.result:Promise.resolve(unavailableStatus(item,"A previous source registration is still settling."));const deadline=new AbortController,signal=AbortSignal.any([deadline.signal,statusStop.signal]);const timer=setTimeout(()=>deadline.abort(),statusTimeoutMs);let removeAbort=()=>{};const interrupted=new Promise(resolve=>{const cancel=()=>{clearTimeout(timer);resolve(unavailableStatus(item,closed?"Connector hub is inactive.":"Source status timed out."))};if(signal.aborted)cancel();else{signal.addEventListener("abort",cancel,{once:true});removeAbort=()=>signal.removeEventListener("abort",cancel)}});const operation=Promise.resolve().then(()=>admitted("probe",item.info.source,{[`provider:${item.info.source}`]:1},()=>signal.aborted?businessError("aborted","Source metadata inspection was cancelled.","plugin"):item.status({signal}),signal));const observed=operation.then(result2=>"ok"in result2?{...result2.ok,...item.actions?{actions:true}:{}}:unavailableStatus(item,"err"in result2?result2.err.message:"Source state was not confirmed."),()=>unavailableStatus(item,"Source status failed."));const result=Promise.race([observed,interrupted]);statusProbes.set(item,{epoch,result});const settled=()=>{clearTimeout(timer);removeAbort();if(statusProbes.get(item)?.result===result)statusProbes.delete(item)};void operation.then(settled,settled);return result}const retentionFailure=(item,options)=>options?.retention!==void 0&&options.retention!=="transient"?businessError("invalid_argument","Unsupported connector result retention policy.","plugin"):(options?.retention==="transient"||isTransientConnectorAction())&&item?.requiresPersistentPayloads?fail("This source requires persistent payload storage and has no qualified transient operation."):void 0;function observe(source,usable){if(!dependencies.availabilityMetrics||usability.get(source)===usable)return Promise.resolve();const task=(async()=>{try{const saved=await dependencies.metrics?.()?.record({operation:"connector.usable",source,outcome:usable?"ok":"cancelled",durationMs:0,internal:true});if(saved&&"ok"in saved&&saved.ok.recorded)usability.set(source,usable)}catch{}})();observations.add(task);void task.finally(()=>observations.delete(task));return task}async function observeResult(source,result,enabled){if(!enabled)return observe(source,false);const outcome=usageOutcome(result);if(outcome==="ok"||outcome==="empty")await observe(source,true);else if(outcome==="fault"||outcome==="auth-blocked")await observe(source,false)}const service={hasSource:source=>provider(source)!==void 0,describe:source=>{const info=provider(source)?.info;return info?structuredClone(info):void 0},...dependencies.metrics?{queryMetrics:"owned"}:{},register(item){if(closed)throw Error("Connector hub is inactive.");if(!/^[a-z][a-z0-9-]{0,63}$/.test(item.info.source))throw Error("Invalid source identity.");if(sources.has(item.info.source))throw Error("Duplicate connector source.");sources.set(item.info.source,item);sourceEpochs.set(item.info.source,(sourceEpochs.get(item.info.source)??0)+1);return()=>{if(sources.get(item.info.source)===item){sources.delete(item.info.source);sourceEpochs.set(item.info.source,(sourceEpochs.get(item.info.source)??0)+1);authorization.withdraw(item);void observe(item.info.source,false)}}},replaceDeferred(expected,item){const source=expected.info.source;if(closed||expected.registration!=="deferred"||item.registration==="deferred"||item.info.source!==source||sources.get(source)!==expected)return void 0;sources.set(source,item);sourceEpochs.set(source,(sourceEpochs.get(source)??0)+1);return()=>{if(sources.get(source)===item){sources.delete(source);sourceEpochs.set(source,(sourceEpochs.get(source)??0)+1);authorization.withdraw(item);void observe(source,false)}}},async status(options){if(closed)return businessError("unavailable","Connector hub is inactive.","plugin");if(options?.signal?.aborted)return businessError("aborted","Source status inspection was cancelled.","plugin");const states=Promise.all([...sources.values()].map(async item=>{const epoch=sourceEpochs.get(item.info.source),state=await probeStatus(item);return provider(item.info.source)===item&&sourceEpochs.get(item.info.source)===epoch?state:unavailableStatus(item,"Source was disabled before its status reply.")}));let removeAbort=()=>{};const cancelled=new Promise(resolve=>{if(options?.signal){const cancel=()=>resolve(businessError("aborted","Source status inspection was cancelled.","plugin"));options.signal.addEventListener("abort",cancel,{once:true});removeAbort=()=>options.signal.removeEventListener("abort",cancel)}});try{const result=await Promise.race([states.then(ok),cancelled]);return closed?businessError("unavailable","Connector hub is inactive.","plugin"):result}finally{removeAbort()}},async connect(source,options){options={...options,automatic:options?.automatic===true};const item=provider(source);if(!item)return fail("Source is not enabled: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(options.savedAccessOnly&&!item.supportsSavedReconnect)return businessError("failed_precondition","This source cannot reconnect using saved access.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;return withTransientConnectorAction(options?.retention==="transient",()=>admitted("connect",source,providerNeeds(source,{worker:1,[`refresh:${source}`]:1}),()=>withFeedbackFlow(source,async()=>{const trace=createTraceRecorder(dependencies.metrics,source);await trace.step("source_selected","completed");await trace.step("authorization_started","started");const started=performance.now();let result;try{result=await item.connect(options)}catch(error){await authorization.immediate(item,businessError(options?.signal?.aborted?"aborted":"unavailable","Connection failed.","plugin"),started);throw error}if(provider(source)!==item){result=businessError("unavailable","Source was disabled.","plugin");await authorization.immediate(item,result,started,"source_disabled");return result}if("ok"in result&&result.ok.source!==source)result=businessError("data_loss","Mismatched connection source.","plugin");if("ok"in result){jobs.set(result.ok.id,item);await authorization.track(item,result,started)}else await authorization.immediate(item,result,started);return result},authorization.currentFlow(item)),options?.signal))},job(id){const item=jobs.get(id);if(!item)return businessError("not_found","Unknown connector connection job.","plugin");if(provider(item.info.source)!==item)return businessError("unavailable","Source was disabled.","plugin");const result=item.job(id);authorization.observe(item,id,result);return result},cancelJob(id,source){const tracked=jobs.get(id),item=tracked??(source?provider(source):void 0);if(!item)return businessError("not_found","Unknown connector connection job.","plugin");if(source&&item.info.source!==source)return businessError("not_found","Unknown connector connection job.","plugin");if(provider(item.info.source)!==item)return businessError("unavailable","Source was disabled.","plugin");return item.cancelJob?.(id)},async settleObservations(options){if(options?.closing)await authorization.close();else await authorization.settle();await Promise.allSettled([...observations])},async check(source,options){const item=provider(source);if(!item)return fail("Source is not enabled: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;if(options?.signal?.aborted)return businessError("aborted","Source readiness was cancelled.","plugin");try{const result=item.check?await withTransientConnectorAction(options?.retention==="transient",()=>admitted("check",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.check(options),options?.signal)):await service.read(source,{limit:1},options).then(result2=>"ok"in result2?ok({source,basis:"read",operation:{state:"succeeded",returned:result2.ok.returned,...result2.ok.evidence?{evidence:result2.ok.evidence}:{}}}):"empty"in result2?ok({source,basis:"read",operation:{state:"succeeded",returned:0}}):result2);if(provider(source)!==item)return businessError("unavailable","Source was disabled before readiness delivery.","plugin");if(options?.signal?.aborted)return businessError("aborted","Source readiness was cancelled.","plugin");if("err"in result)return result;if(!("ok"in result))return businessError("data_loss","Source did not provide readiness metadata.","plugin");return readiness(source,result.ok)}catch{return businessError(options?.signal?.aborted?"aborted":"unavailable","Source readiness did not complete.","plugin")}},async read(source,request={},options){const item=provider(source);const run=()=>withFeedbackFlow(source,async()=>{const trace=createTraceRecorder(dependencies.metrics,source);if(dependencies.metrics)await trace.step("read_started","started");const started=performance.now();let disabled=false;const execute=async()=>{if(!item)return fail("Source is not enabled: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(provider(source)!==item){disabled=true;return businessError("unavailable","Source was disabled before the query.","plugin")}const retention=retentionFailure(item,options);if(retention)return retention;const invalid=validateRead(request,item.info.readById?["fileId"]:[]);if(invalid)return invalid;try{const result2=await item.read(request,options);if(provider(source)!==item){disabled=true;return businessError("unavailable","Source was disabled during the query.","plugin")}if("ok"in result2&&(result2.ok.source!==source||result2.ok.returned!==result2.ok.records.length||result2.ok.returned>(request.limit??1)))return businessError("data_loss","Source returned invalid or unbounded records.","plugin");return result2}catch{return businessError(options?.signal?.aborted?"aborted":"unavailable","Connector query did not complete.","plugin")}};const result=await execute();try{const metrics=dependencies.metrics?.();if(metrics){const summary=usageResultSummary(result),errorCategory=usageErrorCategory(result);await metrics.record({operation:"connector.read",outcome:disabled?"cancelled":usageOutcome(result),durationMs:performance.now()-started,internal:options?.internalTelemetry??false,...item?{source:item.info.source}:{},..."err"in result?{code:result.err.code}:{},...summary?{result:summary}:{},...errorCategory?{errorCategory}:{}})}}catch{}await trace.step("read_verified","err"in result?result.err.code==="aborted"?"cancelled":"failed":"ok"in result||"empty"in result?"completed":"unknown","ok"in result?{count:result.ok.returned}:"empty"in result?{count:0}:{});if(item)await observeResult(source,result,provider(source)===item);return item&&provider(source)!==item?businessError("unavailable","Source was disabled before query delivery.","plugin"):result});const feedback=dependencies.feedback?.();return withTransientConnectorAction(options?.retention==="transient",()=>admitted("read",source,providerNeeds(source,{worker:1}),()=>feedback?feedback.run(source,run):run(),options?.signal))},close(){if(!closing){closed=true;statusStop.abort();for(const source of sources.keys())void observe(source,false);sources.clear();jobs.clear();informationSnapshots.clear();fileSnapshots.clear();closing=(async()=>{await authorization.close();await Promise.allSettled([...observations])})()}return closing},async catalog(source,input,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{const item=provider(source);if(!item)return fail("Source is not installed or enabled: "+source);const retention=retentionFailure(item,options);if(retention)return retention;if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(!item.actions){const action=sharedReadDiscovery(item.info);return ok({source,actions:[{name:action.name,effect:action.effect,operation:action.operation}],total:1,discovery:"Request method=connector.read for the shared action schema; execute it with operation=action, not connector.invoke."})}const result=await admitted("catalog",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.actions.catalog(input),options?.signal);return provider(source)===item?result:businessError("unavailable","Source was disabled before its catalog reply.","plugin")})},async method(source,name2,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{const item=provider(source);if(!item)return fail("Source is not installed or enabled: "+source);const retention=retentionFailure(item,options);if(retention)return retention;if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(!item.actions)return name2==="connector.read"?ok(sharedReadDiscovery(item.info)):fail("This source has no installed action schema: "+name2);const result=await admitted("method",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.actions.method(name2),options?.signal);return provider(source)===item?result:businessError("unavailable","Source was disabled before its schema reply.","plugin")})},async review(source,name2,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{const item=provider(source),epoch=sourceEpochs.get(source)??0;if(!item?.actions)return fail("This source has no installed action schema: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;const result=await admitted("review",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.actions.method(name2),options?.signal);if(provider(source)!==item)return businessError("unavailable","Source was disabled before its schema reply.","plugin");if(!("ok"in result))return result;return actionReview(source,name2,epoch,result.ok)})},async invokeReviewed(review,input,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{if(!review||typeof review!=="object"||typeof review.source!=="string"||typeof review.name!=="string"||typeof review.revision!=="string")return fail("A reviewed action handle is required.");const item=provider(review.source),epoch=sourceEpochs.get(review.source)??0;if(!item?.actions)return fail("This source has no installed action port: "+review.source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;const current=await admitted("invoke-review",review.source,providerNeeds(review.source,{probe:1,discovery:1}),()=>item.actions.method(review.name),options?.signal);if(provider(review.source)!==item)return businessError("unavailable","Source was disabled before action review.","plugin");if(!("ok"in current))return current;if(!sameActionReview(review,epoch,current.ok))return businessError("failed_precondition","Provider action schema changed after review; inspect the new schema before dispatch.","plugin");const valid=validateReviewedInput(review,input);if(!("ok"in valid))return valid;return service.invoke(review.source,review.name,input,options)})},async invoke(source,name2,input,options){const item=provider(source);if(!item?.actions)return fail("This source has no installed action port: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const run=()=>withFeedbackFlow(source,async()=>{const trace=createTraceRecorder(dependencies.metrics,source);await trace.step("invoke_started","started");if(provider(source)!==item){await trace.step("invoke_finished","failed",{reason:"source_disabled"});return businessError("unavailable","Source was disabled before action dispatch.","plugin")}const retention=retentionFailure(item,options);if(retention){await trace.step("invoke_finished","failed",{reason:"provider_error"});return retention}const started=performance.now();let result;try{const reply=await admitted("invoke",source,providerNeeds(source,{worker:1}),()=>{if(provider(source)!==item)return businessError("unavailable","Source was disabled before action dispatch.","plugin");if(!item.actions.reportsActionAccess){try{options?.onActionAccess?.("legacy")}catch{}const legacyOptions=options?{...options}:void 0;if(legacyOptions)delete legacyOptions.onActionAccess;return item.actions.invoke(name2,input,legacyOptions)}return item.actions.invoke(name2,input,options)},options?.signal);result=provider(source)===item?reply:businessError("unavailable","Source was disabled before its reply.","plugin")}catch{result=businessError(options?.signal?.aborted?"aborted":"unavailable","Source action did not finish.","plugin")}let outcome="unknown";try{outcome=usageOutcome(result);const metrics=dependencies.metrics?.();if(metrics){const summary=usageResultSummary(result),errorCategory=usageErrorCategory(result);await metrics.record({operation:"connector.invoke",source,outcome,durationMs:performance.now()-started,internal:true,..."err"in result?{code:result.err.code}:{},...summary?{result:summary}:{},...errorCategory?{errorCategory}:{}})}}catch{}await trace.step("invoke_finished",outcome==="ok"||outcome==="empty"?"completed":outcome==="cancelled"?"cancelled":outcome==="auth-blocked"?"waiting":outcome==="fault"||outcome==="invalid"?"failed":"unknown");await observeResult(source,result,provider(source)===item);return provider(source)===item?result:businessError("unavailable","Source was disabled before action delivery.","plugin")});const feedback=dependencies.feedback?.();return withTransientConnectorAction(options?.retention==="transient",()=>feedback?feedback.run(source,run):run())},async captureInformation(review,input,options){purgeSnapshots();if(!review||typeof review!=="object"||!review.schema||!shareReadSchema(review.schema))return businessError("permission_denied","Share snapshots require an explicitly read-only Connector Action.","plugin");const item=provider(review.source),epoch=sourceEpochs.get(review.source)??0;if(!item)return fail("Source is not enabled: "+review.source);const result=await service.invokeReviewed(review,input,options);if(!("ok"in result))return result;if(provider(review.source)!==item||sourceEpochs.get(review.source)!==epoch)return businessError("unavailable","Source changed before its information snapshot was retained.","plugin");const fingerprint=informationFingerprint(result.ok);if(!("ok"in fingerprint))return fingerprint;const handle=randomUUID(),capturedAt=new Date().toISOString(),expiresAt=new Date(Date.now()+SNAPSHOT_TTL_MS).toISOString();const snapshot={kind:"information",source:review.source,name:review.name,handle,capturedAt,expiresAt,...fingerprint.ok};let savedReview,savedInput;try{savedReview=structuredClone(review);savedInput=structuredClone(input)}catch{return businessError("invalid_argument","Connector snapshot input is not cloneable.","plugin")}informationSnapshots.set(handle,{public:snapshot,review:savedReview,input:savedInput,provider:item,epoch});return ok(snapshot)},async verifyInformation(snapshot,options){purgeSnapshots();if(!validInformationHandle(snapshot))return businessError("invalid_argument","Pass one Connector information snapshot handle.","plugin");const stored=informationSnapshots.get(snapshot.handle);if(!stored||!samePublic(stored.public,snapshot))return fail("Connector information snapshot is missing, expired or changed.");if(provider(stored.public.source)!==stored.provider||sourceEpochs.get(stored.public.source)!==stored.epoch)return fail("Connector source changed after preview; review the Share again.");const result=await service.invokeReviewed(stored.review,stored.input,options);if(!("ok"in result))return result;const current=informationFingerprint(result.ok);if(!("ok"in current))return current;if(current.ok.sha256!==stored.public.sha256||current.ok.bytes!==stored.public.bytes)return businessError("aborted","Connector information changed after preview; review the Share again.","plugin");return ok(stored.public)},async inspectFile(source,input,options){purgeSnapshots();if(!input||typeof input.id!=="string"||!input.id||Buffer.byteLength(input.id)>1024)return businessError("invalid_argument","Connector file inspection requires one provider identity.","plugin");const item=provider(source),epoch=sourceEpochs.get(source)??0;if(!item?.fileSnapshots)return fail("This source does not provide file snapshots: "+source);const retention=retentionFailure(item,options);if(retention)return retention;if(options?.signal?.aborted)return businessError("aborted","Connector file inspection was cancelled.","plugin");const result=await withTransientConnectorAction(options?.retention==="transient",()=>admitted("file-inspect",source,providerNeeds(source,{worker:1}),()=>item.fileSnapshots.inspect(input,options),options?.signal));if(provider(source)!==item||sourceEpochs.get(source)!==epoch)return businessError("unavailable","Source changed before its file snapshot was retained.","plugin");if(!("ok"in result))return result;const checked=validProviderFile(result.ok,source);if(!("ok"in checked))return checked;let retained;try{retained=structuredClone(checked.ok)}catch{return businessError("data_loss","Connector file snapshot metadata is not retainable.","plugin")}const handle=randomUUID(),expiresAt=new Date(Date.now()+SNAPSHOT_TTL_MS).toISOString(),snapshot=publicFileSnapshot(handle,retained,expiresAt);fileSnapshots.set(handle,{public:snapshot,file:retained,provider:item,epoch});return ok(snapshot)},async materializeFile(snapshot,options){purgeSnapshots();if(!validFileHandle(snapshot))return businessError("invalid_argument","Pass one Connector file snapshot handle.","plugin");const stored=fileSnapshots.get(snapshot.handle);if(!stored||!samePublic(stored.public,snapshot))return fail("Connector file snapshot is missing, expired or changed.");const item=provider(stored.public.source);if(item!==stored.provider||sourceEpochs.get(stored.public.source)!==stored.epoch||!item.fileSnapshots)return fail("Connector source changed after preview; review the Share again.");const retention=retentionFailure(item,options);if(retention)return retention;if(options?.signal?.aborted)return businessError("aborted","Connector file materialization was cancelled.","plugin");const result=await withTransientConnectorAction(options?.retention==="transient",()=>admitted("file-materialize",stored.public.source,providerNeeds(stored.public.source,{worker:1}),()=>item.fileSnapshots.materialize(stored.file,options),options?.signal));if(provider(stored.public.source)!==item||sourceEpochs.get(stored.public.source)!==stored.epoch)return businessError("unavailable","Source changed while its file snapshot was materialized.","plugin");if(!("ok"in result))return result;const checked=validProviderFile(result.ok.file,stored.public.source);if(!("ok"in checked))return checked;if(!sameProviderFile(stored.file,checked.ok)||!(result.ok.content instanceof Uint8Array)||result.ok.mimeType!==stored.public.mimeType||result.ok.size!==result.ok.content.byteLength||result.ok.size<0)return businessError("data_loss","Connector file bytes did not match the inspected snapshot.","plugin");return ok({file:stored.public,content:result.ok.content,mimeType:result.ok.mimeType,size:result.ok.size})}};return instrumentConnectorHub(service,dependencies.metrics,id=>jobs.get(id)?.info.source)}export async function apply(ctx){const feedback=createConnectionFeedback({store:()=>ctx.get("zortexSqliteVault")?.createPrivateStore("connection-feedback"),connection:async source=>{const local=ctx.get("zortexLocalSourceRegistry")?.get(source);if(local)return ok(local);const level1=ctx.get("zortexLevel1Connectors");const namespace=source==="figma"&&level1?.provider("figma")?.spec.auth.kind==="fields"?"figma--pat":source;const result=await ctx.zortexVaultStore.connection(namespace);return namespace!==source&&"ok"in result&&result.ok?ok({...result.ok,source}):result}});ctx.provide("zortexConnectionFeedback",feedback);const admission=createResourceAdmission(),http=await createConnectorHttp({admission}),hub=createConnectorHub({metrics:()=>ctx.get("zortexTelemetry"),feedback:()=>feedback,availabilityMetrics:true,admission}),enrollment=createEnrollment({vault:ctx.zortexVaultStore,transport:http.fetch,metrics:()=>ctx.get("zortexTelemetry"),feedback:()=>feedback});ctx.provide("zortexResourceAdmission",admission);ctx.provide("zortexConnectorHttp",http.fetch);ctx.provide("zortexConnectorHub",hub);ctx.provide("zortexConnectorEnrollment",enrollment);ctx.effect(()=>()=>hub.close());ctx.effect(()=>async()=>{await enrollment.close();await http.close();admission.close()})}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{execFile}from"node:child_process";import{promisify}from"node:util";import{win32}from"node:path";const TIMEOUT_MS=2e3,MAX_BYTES=32768;const script="$ErrorActionPreference='Stop';[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();$folders=@();foreach($name in @('MyDocuments','DesktopDirectory')){$path=[Environment]::GetFolderPath($name);if($path){$folders+=$path}};try{$shell=New-Object -ComObject Shell.Application;$folder=$shell.NameSpace('shell:Downloads');if($folder){$folders+=$folder.Self.Path}}catch{};[PSCustomObject]@{sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value;folders=@($folders)}|ConvertTo-Json -Compress";const execute=async(command,options)=>(await promisify(execFile)("powershell.exe",["-NoProfile","-NonInteractive","-Command",command],{...options,windowsHide:true})).stdout;export async function readNativeUserFileRoots(native,options={}){if((options.platform??process.platform)!=="win32")return void 0;if(options.signal?.aborted)return[];try{const raw=await(options.execute??execute)(script,{timeout:TIMEOUT_MS,maxBuffer:MAX_BYTES,...options.signal?{signal:options.signal}:{}});if(options.signal?.aborted||Buffer.byteLength(raw,"utf8")>MAX_BYTES)return[];const result=JSON.parse(raw);if(result.sid!==native.subject||!Array.isArray(result.folders)||result.folders.length>3)return[];const home=win32.resolve(native.home).toLowerCase(),seen=new Set,roots=[];for(const path of result.folders){if(typeof path!=="string"||!path||path!==path.trim()||path.length>4096||/[\u0000-\u001f\u007f-\u009f]/u.test(path)||!win32.isAbsolute(path))continue;const canonical=win32.resolve(path),key=canonical.toLowerCase();if(key===home||canonical===win32.resolve(path,"..")||seen.has(key))continue;seen.add(key);roots.push(path)}return roots}catch{return[]}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{validateRead,readResult,connectionState}from"@zortexhq/plugin-connector-core/api";import{createHash}from"node:crypto";import{METHODS,DISCOVERY_PIN}from"./generated.js";import{createTasksConnector}from"./connector.js";import{createTasksCompounds}from"./compounds.js";import{COMPOUND_METHODS}from"./compound-generated.js";import{record,protectedAuthority,safeProvider,validate}from"./guards.js";export function createTasksSource({parts,auth,vault,transport,transportSync,compoundCustody,compoundReceipts,now=()=>new Date().toISOString()}){const info={source:"google-tasks",label:"Google Tasks",group:"Connector / Google",auth:"oauth-browser"},stop=new AbortController,pending=new Set;let closed=false,principal=null,activeScopes=[];const fail=(code,message,layer="connector")=>businessError(code,message,layer);const methods=new Map(METHODS.flatMap(row=>[[row.id,row],[row.contract,row]]));const mutationReceipts=new Map;const method=id=>methods.has(id)?Original.ok(structuredClone(methods.get(id))):fail("not_found","Google Tasks method is not in the pinned provider catalog");const publicMethod=id=>{const compound=COMPOUND_METHODS.find(row=>row.id===id),selected=compound?Original.ok(structuredClone(compound)):method(id);return"ok"in selected?Original.ok({...selected.ok,httpMethod:selected.ok.method,...compound?{}:{level:1,effect:selected.ok.method==="GET"?"read":"write"}}):selected};async function resolveGrant(){if(closed)return fail("aborted","Tasks source is inactive");const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;if(!selected.ok||selected.ok.state!=="connected")return fail("unauthenticated","Connect Google Tasks before reading or acting","auth");if(typeof selected.ok.accountId!=="string"||!selected.ok.accountId.trim())return fail("failed_precondition","Google Tasks requires a verified OIDC subject; an email or grant id is not an account identity","auth");principal=selected.ok.accountId;activeScopes=[...selected.ok.scopes];return Original.ok({id:"0"+createHash("sha256").update(principal).digest("hex").slice(0,25).toUpperCase(),source:"google-tasks",account:principal,scopes:activeScopes,expiresAt:"2036-01-01T00:00:00.000Z"})}function prepare(row,call){if(protectedAuthority(call))return fail("invalid_argument","Credential or resource-key authority is forbidden in source action parameters");const invalid=validate(row.params,call);if(invalid)return fail("invalid_argument",invalid);if(!record(call)||!record(call.params))return fail("invalid_argument","Provider calls require the declared params object");const max=call.params["maxResults"];if(max!==void 0&&(typeof max!=="number"||max<1||max>(row.resource==="tasklists"?1e3:100)))return fail("invalid_argument","Google Tasks maxResults is outside the documented page bound");let path=row.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(call.params)){if(row.parameterLocations[key]==="path"){if(typeof value!=="string"||!value||value==="."||value===".."||value.length>4096)return fail("invalid_argument","Tasks provider identity is invalid");path=path.replace("{"+key+"}",encodeURIComponent(value))}else query.set(key,String(value))}if(path.includes("{"))return fail("invalid_argument","Google Tasks call is missing a required path identity");const url="https://tasks.googleapis.com/"+path+(query.size?"?"+query:"");const body=call.body===void 0?void 0:JSON.stringify(call.body);if(body!==void 0&&Buffer.byteLength(body)>2097152)return fail("resource_exhausted","Tasks input body exceeds the custody bound");return Original.ok({url,...body===void 0?{}:{body}})}function decode(row,raw){if(Buffer.byteLength(raw.body)>2097152)return fail("resource_exhausted","Tasks provider response exceeds the custody bound");if(raw.status>=400){let diagnostic={};try{diagnostic=safeProvider(JSON.parse(raw.body)).data}catch{}const googleRule=parts.googleStatusOverrideV1(JSON.stringify(diagnostic));return Original.errResult(parts.webStatusFailureV1(raw.status,{provider:"Google Tasks",what:row.id,bodyOverride:status2=>status2===400?{code:"invalid_argument",retryability:"non-retryable",meaning:"provider rejected the Tasks request"}:googleRule(status2),headers:raw.headers}))}let object;if(raw.status===204&&raw.body==="")object={};else try{object=JSON.parse(raw.body)}catch{return fail("data_loss","Google Tasks returned invalid JSON")}if(!record(object))return fail("data_loss","Google Tasks returned a non-object response");const safe=safeProvider(object);const status=parts.webStatusErrorV1(raw.status,{provider:"Google Tasks",what:row.id,bodyOverride:parts.googleStatusOverrideV1(JSON.stringify(safe.data)),headers:raw.headers});if(status)return Original.errResult(status);const payload=safe.data;const isList=row.operation==="list";if(isList&&payload["items"]!==void 0&&!Array.isArray(payload["items"]))return fail("data_loss","Google Tasks returned invalid items");const items=isList?payload["items"]??[]:row.method==="GET"?[payload]:[];if(!Array.isArray(items)||items.some(item=>!record(item)))return fail("data_loss","Google Tasks returned a malformed item collection");const next=payload["nextPageToken"];if(next!==void 0&&(typeof next!=="string"||next.length>8192||!next))return fail("data_loss","Google Tasks returned an invalid page token");return Original.ok({method:row.id,resource:row.resource,data:payload,items,...typeof next==="string"?{nextPageToken:next}:{},warnings:safe.withheld?["Protected assignment resource-key authority was withheld; origin-document access is not implied."]:[],effect:row.method==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}async function invokeInner(id,call,options={}){call=structuredClone(call);if(closed||options.signal?.aborted)return fail("aborted","Tasks source request was stopped");const row=method(id);if(!("ok"in row))return row;const prepared=prepare(row.ok,call);if(!("ok"in prepared))return prepared;const grant=await resolveGrant();if(!("ok"in grant))return grant;const boundPrincipal=principal;if(!row.ok.scopes.some(scope=>activeScopes.includes(scope)))return fail("permission_denied",row.ok.method==="GET"?"Google Tasks read scope is missing":"Google Tasks write scope requires separate user consent","auth");if(row.ok.resource==="tasks"&&["patch","update"].includes(row.ok.operation)&&record(call.body)&&Object.hasOwn(call.body,"deleted")){const target=await invoke("tasks.tasks.get",{params:{tasklist:call.params["tasklist"],task:call.params["task"]}},options);if(!("ok"in target))return target;if(record(target.ok.data["assignmentInfo"]))return fail("permission_denied","Task.deleted is readonly for assigned tasks; no source write was attempted");if(principal!==boundPrincipal)return fail("permission_denied","Tasks account changed before conditional field mutation","auth")}const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;const request={method:row.ok.method,...prepared.ok.body===void 0?{}:{body:prepared.ok.body,contentType:"application/json"},signal};const response=transport?await transport("google-tasks",prepared.ok.url,request):await auth.requestRaw("google-tasks",prepared.ok.url,request);if(closed||signal.aborted)return fail("aborted","Tasks response arrived after cancellation");const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;if(selected.ok?.accountId!==boundPrincipal||principal!==boundPrincipal)return fail("permission_denied","Tasks account changed while the provider request was active","auth");return"ok"in response?decode(row.ok,response.ok):response}function invoke(id,call,options={}){if(pending.size>=32)return Promise.resolve(fail("resource_exhausted","Tasks source has reached its active call bound"));const task=invokeInner(id,call,options).finally(()=>pending.delete(task));pending.add(task);return task}function invokeSync(id,call){call=structuredClone(call);if(!transportSync)return parts.gateRefusal("Google Tasks synchronous request","fixture-oracle only");if(!principal)return parts.gateRefusal("Google Tasks synchronous identity","bind verified account first");const row=method(id);if(!("ok"in row))return"err"in row?row:parts.connectorError("data_loss","Tasks method lookup was unconfirmed");const prepared=prepare(row.ok,call);if(!("ok"in prepared))return"err"in prepared?prepared:parts.connectorError("data_loss","Tasks input validation was unconfirmed");if(!row.ok.scopes.some(scope=>activeScopes.includes(scope)))return parts.connectorError("permission_denied","Google Tasks scope is missing");if(row.ok.resource==="tasks"&&["patch","update"].includes(row.ok.operation)&&record(call.body)&&Object.hasOwn(call.body,"deleted")){const target=invokeSync("tasks.tasks.get",{params:{tasklist:call.params["tasklist"],task:call.params["task"]}});if(!Original.isOk(target))return target;if(record(target.ok.data["assignmentInfo"]))return parts.connectorError("permission_denied","Task.deleted is readonly for assigned tasks; no source write was attempted")}const response=transportSync("google-tasks",prepared.ok.url,{method:row.ok.method,...prepared.ok.body===void 0?{}:{body:prepared.ok.body,contentType:"application/json"}});return"ok"in response?decode(row.ok,response.ok):"err"in response?response:parts.connectorError("data_loss","Tasks fixture response was unconfirmed")}const asOriginal=async(id,call,options)=>{const reply=await invoke(id,call,options);return"empty"in reply?parts.connectorError("data_loss","Tasks provider read was unconfirmed"):reply};const connector=createTasksConnector({parts,accountId:()=>principal,request:asOriginal,...transportSync?{requestSync:invokeSync}:{},now,live:()=>!closed});const rawCompounds=createTasksCompounds({invoke,account:()=>principal,...compoundCustody?{conditional:{async compareAndMutate(input){const selected=method(input.method);if(!("ok"in selected))return selected;const valid=prepare(selected.ok,input.call);if(!("ok"in valid))return valid;const grant=await resolveGrant();if(!("ok"in grant))return grant;if(input.accountId!==principal||!selected.ok.scopes.some(scope=>activeScopes.includes(scope)))return fail("permission_denied","Compound mutation authority is not bound to the verified write account","auth");return compoundCustody.compareAndMutate(input)}}}:{},...compoundReceipts?{receipts:compoundReceipts}:{}});function owned(task){const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled}const compOptions=read=>({signal:read?.signal?AbortSignal.any([read.signal,stop.signal]):stop.signal});const compounds={execute(name,input,key,read){input=structuredClone(input);return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.execute(name,input,key,compOptions(read))})())},compensate(key,read){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.compensate(key,compOptions(read))})())},probe(key){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return Original.ok({reading:"unknown"});return rawCompounds.probe(key)})())},recover(key,read){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.recover(key,compOptions(read))})())}};const arms={},probes={};for(const row of METHODS){arms[row.contract]=async(grant,call)=>{if(grant.source!=="google-tasks"||!row.scopes.some(scope=>grant.scopes.includes(scope)))return parts.connectorError("permission_denied","Tasks action grant does not authorize this method");if(!record(call.params)||!record(call.params["params"]))return parts.connectorError("invalid_argument","Tasks action must use the discovered input wrapper");const input=call.params,reply=await asOriginal(row.id,input,{signal:call.signal});if(!Original.isOk(reply))return reply;if(row.method==="GET")return Original.ok({result:reply.ok.data});if(mutationReceipts.size>=256)mutationReceipts.delete(mutationReceipts.keys().next().value);mutationReceipts.set(call.idempotencyKey,{method:row,call:structuredClone(input),reply:reply.ok});return Original.ok({evidenceHint:"google-tasks provider accepted mutation; verification required"})};if(row.method!=="GET")probes[row.contract+".verify"]={confidentAfterMs:0,read:async(_grant,call)=>{const receipt=mutationReceipts.get(call.idempotencyKey);if(!receipt)return Original.ok({reading:"unknown"});const params=receipt.call.params,body=receipt.call.body;if(row.operation==="clear"||row.operation==="move"||row.operation==="delete"||record(receipt.reply.data["assignmentInfo"]))return Original.ok({reading:"unknown"});const id=typeof receipt.reply.data["id"]==="string"?receipt.reply.data["id"]:params[row.resource==="tasklists"?"tasklist":"task"];if(typeof id!=="string")return Original.ok({reading:"unknown"});const lookup=row.resource==="tasklists"?{tasklist:id}:{tasklist:params["tasklist"],task:id};const answer=await invoke(row.resource==="tasklists"?"tasks.tasklists.get":"tasks.tasks.get",{params:lookup});if("err"in answer){if(row.operation==="delete"&&answer.err.code==="not_found")return Original.ok({reading:"effected"});return Original.ok({reading:"unknown"})}if(!("ok"in answer))return Original.ok({reading:"unknown"});if(row.operation==="delete")return Original.ok({reading:"absent"});if(!record(body))return Original.ok({reading:"unknown"});const matches=Object.entries(body).every(([key,value])=>JSON.stringify(answer.ok.data[key])===JSON.stringify(value));return Original.ok({reading:matches?"effected":"absent"})}}}connector.actionRail=parts.defineConnectorActions({arms,probes});for(const row of COMPOUND_METHODS){arms[row.contract]=async(grant,call)=>{if(grant.source!=="google-tasks"||!grant.scopes.includes("https://www.googleapis.com/auth/tasks"))return parts.connectorError("permission_denied","Personal compound requires an authorized Tasks write grant");if(!record(call.params)||!record(call.params["params"]))return parts.connectorError("invalid_argument","Personal compound requires generated wrapper parameters");const result=await compounds.execute(row.contract,call.params,call.idempotencyKey,{signal:call.signal});return"ok"in result?Original.ok({evidenceHint:"google-tasks-compound:"+result.ok.receiptKey}):"err"in result?result:parts.connectorError("data_loss","Compound execution was unconfirmed")};probes[row.contract+".verify"]={confidentAfterMs:0,read:async(_grant,call)=>{const result=await compounds.probe(call.idempotencyKey);return"ok"in result?Original.ok(result.ok):"err"in result?result:parts.connectorError("data_loss","Compound probe was unconfirmed")}}}connector.actionRail=parts.defineConnectorActions({arms,probes});const service={info,connector,compounds,resolveGrant,status:()=>closed?Promise.resolve(fail("aborted","Tasks source is inactive")):connectionState(vault,info),connect:options=>closed?Promise.resolve(fail("aborted","Tasks source is inactive")):auth.connect("google-tasks",options),job:id=>closed?fail("aborted","Tasks source is inactive"):auth.job(id),cancelJob:id=>auth.cancelJob(id),method,invoke,catalog(options={}){const limit=options.limit??20,cursor=options.cursor??0;if(!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return fail("invalid_argument","Catalog limit/cursor is invalid");const rows=METHODS.filter(row=>(!options.resource||row.resource===options.resource)&&(!options.query||(row.id+" "+row.description).toLowerCase().includes(options.query.toLowerCase())));return Original.ok({total:rows.length,methods:rows.slice(cursor,cursor+limit).map(row=>({id:row.id,contract:row.contract,resource:row.resource,method:row.method,scopes:row.scopes,body:row.body,media:false})),...cursor+limit<rows.length?{next:cursor+limit}:{},pin:DISCOVERY_PIN,gaps:["Tasks API exposes dates only, no due time of day, reminders, recurrence rule, attachments, author or complete revision history.","Assignment resource keys are protected; fetching its Docs/Chat origin requires that source authorization."]})},async*pages(id,params,options={}){const row=method(id);if(!("ok"in row)){yield row;return}if(row.ok.method!=="GET"||row.ok.operation!=="list"){yield fail("invalid_argument","Pagination only applies to Tasks read-list methods");return}const max=options.maxPages??1e4;if(!Number.isInteger(max)||max<1||max>1e5){yield fail("invalid_argument","maxPages is invalid");return}let current={...params};const seen=new Set;for(let page=0;page<max;page++){const answer=await invoke(id,{params:current},options);yield answer;if(!("ok"in answer)||!answer.ok.nextPageToken)return;const token=answer.ok.nextPageToken;if(seen.has(token)||current["pageToken"]===token){yield fail("data_loss","Google Tasks page token repeated; collection was not exhausted");return}seen.add(token);current={...current,pageToken:token}}yield fail("resource_exhausted","Requested pagination bound reached; collection is incomplete")},async check(options={}){if(closed||options.signal?.aborted)return fail("aborted","Tasks check was stopped");const grant=await resolveGrant();if(!("ok"in grant))return grant;const accountId=grant.ok.account;const answer=await invoke("tasks.tasklists.list",{params:{maxResults:1}},options);if(!("ok"in answer))return answer;const current=await vault.connection("google-tasks");if(closed||options.signal?.aborted)return fail("aborted","Tasks check was stopped");if(!("ok"in current))return current;if(current.ok?.state!=="connected"||current.ok.accountId!==accountId||!current.ok.scopes.some(scope=>scope==="https://www.googleapis.com/auth/tasks.readonly"||scope==="https://www.googleapis.com/auth/tasks"))return fail("permission_denied","Tasks check connection or scope changed","auth");if(answer.ok.items.length>1)return fail("data_loss","Tasks readiness response exceeded the requested one-record bound");return Original.ok({source:"google-tasks",basis:"read",operation:{state:"succeeded",returned:answer.ok.items.length}})},async read(request,options={}){const invalid=validateRead(request);if(invalid)return invalid;const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;if(closed||signal.aborted)return fail("aborted","Tasks read was stopped");const grant=await resolveGrant();if(!("ok"in grant))return grant;const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;const captured=structuredClone(selected.ok);if(!captured||captured.state!=="connected"||captured.accountId!==grant.ok.account)return fail("permission_denied","Tasks account changed before the selected read","auth");const readScope="https://www.googleapis.com/auth/tasks.readonly",writeScope="https://www.googleapis.com/auth/tasks",requiredScope=captured.scopes.includes(readScope)?readScope:captured.scopes.includes(writeScope)?writeScope:null;if(!requiredScope)return fail("permission_denied","Google Tasks read scope is missing","auth");const boundPrincipal=captured.accountId,boundGrant=structuredClone(grant.ok),limit=request.limit??1;const records=[],warnings=new Set;let scanned=0,matched=0;const fence=async()=>{if(closed||signal.aborted)return fail("aborted","Tasks read was stopped");const current=await vault.connection("google-tasks");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==boundPrincipal||!current.ok.scopes.includes(requiredScope))return fail("permission_denied","Tasks read connection or scope changed","auth");return Original.ok(void 0)};const reading=createTasksConnector({parts,accountId:()=>boundPrincipal,request:async(id,call)=>{const before=await fence();if(!("ok"in before))return"err"in before?before:parts.connectorError("data_loss","Tasks read fence was unconfirmed");const answer2=await asOriginal(id,call,{signal});const after=await fence();return"ok"in after?answer2:"err"in after?after:parts.connectorError("data_loss","Tasks read fence was unconfirmed")},now,live:()=>!closed&&!signal.aborted});for await(const page of reading.scan(boundGrant,null)){if(signal.aborted||closed)return fail("aborted","Tasks read was stopped");if(!Original.isOk(page))return page;scanned+=page.ok.items.length;for(const note of page.ok.notes??[])warnings.add(note);for(const item of page.ok.items){const proto=reading.normalize(item),fields=record(proto.payload)?proto.payload:{};if(fields["deleted"]===true)continue;const text=proto.body??"";if(request.query&&!text.toLowerCase().includes(request.query.toLowerCase()))continue;if(request.since&&Date.parse(proto.ts)<Date.parse(request.since)||request.until&&Date.parse(proto.ts)>Date.parse(request.until))continue;matched++;records.push({source:"google-tasks",sourceId:encodeURIComponent(boundPrincipal)+":"+proto.nk.sourceId,stream:proto.nk.stream,kind:proto.kind,ts:proto.ts,body:text,fields});records.sort((a,b)=>(b.ts??"").localeCompare(a.ts??"")||(a.sourceId??"").localeCompare(b.sourceId??""));if(records.length>limit)records.length=limit}}const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;const answer=readResult("google-tasks",records,[...warnings]);return"ok"in answer?Original.ok({...answer.ok,scanned,matched}):answer},async close(){closed=true;stop.abort();await Promise.allSettled([...pending]);mutationReceipts.clear();principal=null;activeScopes=[]}};const ownedRead=service.read.bind(service);service.read=(request,options)=>{if(closed)return Promise.resolve(fail("aborted","Tasks source is inactive"));const task=ownedRead(request,options).finally(()=>pending.delete(task));pending.add(task);return task};const ownedCheck=service.check.bind(service);service.check=options=>{if(closed)return Promise.resolve(fail("aborted","Tasks source is inactive"));const task=ownedCheck(options).finally(()=>pending.delete(task));pending.add(task);return task};service.actions={catalog(input){if(input?.profile&&input.profile!=="data")return fail("invalid_argument","Tasks supports the data profile only");if(input?.resource==="personal"||input?.resource==="personal-deleted"){const selected=COMPOUND_METHODS.filter(row=>row.resource===input.resource);return Original.ok({total:selected.length,methods:selected.map(row=>({id:row.id,contract:row.contract,resource:row.resource,method:row.method,scopes:row.scopes,body:row.body,media:false})),pin:"zortex-personal-task-compound@1",gaps:["Requires host atomic target+collection guard custody and durable private receipts"]})}const raw=service.catalog(input);return"ok"in raw?Original.ok({...raw.ok,additionalOperationResources:["personal","personal-deleted"]}):raw},method:publicMethod,async invoke(id,input,options){if(input.media!==void 0)return fail("invalid_argument","Tasks has no media-upload method");if(COMPOUND_METHODS.some(row=>row.id===id)){const receiptKey=Original.ulid();const result=await compounds.execute(id,input,receiptKey,options);return"ok"in result?Original.ok({method:id,resource:"personal",data:result.ok,items:[],warnings:["Private compound accepted; query its receipt/probe before claiming an effect"],effect:"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}}):result}return invoke(id,input,options)}};return service}
|
|
1
|
+
import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{validateRead,readResult,connectionState}from"@zortexhq/plugin-connector-core/api";import{createHash}from"node:crypto";import{METHODS,DISCOVERY_PIN}from"./generated.js";import{createTasksConnector}from"./connector.js";import{createTasksCompounds}from"./compounds.js";import{COMPOUND_METHODS}from"./compound-generated.js";import{record,protectedAuthority,safeProvider,validate}from"./guards.js";export function createTasksSource({parts,auth,vault,transport,transportSync,compoundCustody,compoundReceipts,now=()=>new Date().toISOString()}){const info={source:"google-tasks",label:"Google Tasks",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["tasklists","tasks"],limitations:[]}},stop=new AbortController,pending=new Set;let closed=false,principal=null,activeScopes=[];const fail=(code,message,layer="connector")=>businessError(code,message,layer);const methods=new Map(METHODS.flatMap(row=>[[row.id,row],[row.contract,row]]));const mutationReceipts=new Map;const method=id=>methods.has(id)?Original.ok(structuredClone(methods.get(id))):fail("not_found","Google Tasks method is not in the pinned provider catalog");const publicMethod=id=>{const compound=COMPOUND_METHODS.find(row=>row.id===id),selected=compound?Original.ok(structuredClone(compound)):method(id);return"ok"in selected?Original.ok({...selected.ok,httpMethod:selected.ok.method,...compound?{}:{level:1,effect:selected.ok.method==="GET"?"read":"write"}}):selected};async function resolveGrant(){if(closed)return fail("aborted","Tasks source is inactive");const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;if(!selected.ok||selected.ok.state!=="connected")return fail("unauthenticated","Connect Google Tasks before reading or acting","auth");if(typeof selected.ok.accountId!=="string"||!selected.ok.accountId.trim())return fail("failed_precondition","Google Tasks requires a verified OIDC subject; an email or grant id is not an account identity","auth");principal=selected.ok.accountId;activeScopes=[...selected.ok.scopes];return Original.ok({id:"0"+createHash("sha256").update(principal).digest("hex").slice(0,25).toUpperCase(),source:"google-tasks",account:principal,scopes:activeScopes,expiresAt:"2036-01-01T00:00:00.000Z"})}function prepare(row,call){if(protectedAuthority(call))return fail("invalid_argument","Credential or resource-key authority is forbidden in source action parameters");const invalid=validate(row.params,call);if(invalid)return fail("invalid_argument",invalid);if(!record(call)||!record(call.params))return fail("invalid_argument","Provider calls require the declared params object");const max=call.params["maxResults"];if(max!==void 0&&(typeof max!=="number"||max<1||max>(row.resource==="tasklists"?1e3:100)))return fail("invalid_argument","Google Tasks maxResults is outside the documented page bound");let path=row.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(call.params)){if(row.parameterLocations[key]==="path"){if(typeof value!=="string"||!value||value==="."||value===".."||value.length>4096)return fail("invalid_argument","Tasks provider identity is invalid");path=path.replace("{"+key+"}",encodeURIComponent(value))}else query.set(key,String(value))}if(path.includes("{"))return fail("invalid_argument","Google Tasks call is missing a required path identity");const url="https://tasks.googleapis.com/"+path+(query.size?"?"+query:"");const body=call.body===void 0?void 0:JSON.stringify(call.body);if(body!==void 0&&Buffer.byteLength(body)>2097152)return fail("resource_exhausted","Tasks input body exceeds the custody bound");return Original.ok({url,...body===void 0?{}:{body}})}function decode(row,raw){if(Buffer.byteLength(raw.body)>2097152)return fail("resource_exhausted","Tasks provider response exceeds the custody bound");if(raw.status>=400){let diagnostic={};try{diagnostic=safeProvider(JSON.parse(raw.body)).data}catch{}const googleRule=parts.googleStatusOverrideV1(JSON.stringify(diagnostic));return Original.errResult(parts.webStatusFailureV1(raw.status,{provider:"Google Tasks",what:row.id,bodyOverride:status2=>status2===400?{code:"invalid_argument",retryability:"non-retryable",meaning:"provider rejected the Tasks request"}:googleRule(status2),headers:raw.headers}))}let object;if(raw.status===204&&raw.body==="")object={};else try{object=JSON.parse(raw.body)}catch{return fail("data_loss","Google Tasks returned invalid JSON")}if(!record(object))return fail("data_loss","Google Tasks returned a non-object response");const safe=safeProvider(object);const status=parts.webStatusErrorV1(raw.status,{provider:"Google Tasks",what:row.id,bodyOverride:parts.googleStatusOverrideV1(JSON.stringify(safe.data)),headers:raw.headers});if(status)return Original.errResult(status);const payload=safe.data;const isList=row.operation==="list";if(isList&&payload["items"]!==void 0&&!Array.isArray(payload["items"]))return fail("data_loss","Google Tasks returned invalid items");const items=isList?payload["items"]??[]:row.method==="GET"?[payload]:[];if(!Array.isArray(items)||items.some(item=>!record(item)))return fail("data_loss","Google Tasks returned a malformed item collection");const next=payload["nextPageToken"];if(next!==void 0&&(typeof next!=="string"||next.length>8192||!next))return fail("data_loss","Google Tasks returned an invalid page token");return Original.ok({method:row.id,resource:row.resource,data:payload,items,...typeof next==="string"?{nextPageToken:next}:{},warnings:safe.withheld?["Protected assignment resource-key authority was withheld; origin-document access is not implied."]:[],effect:row.method==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}async function invokeInner(id,call,options={}){call=structuredClone(call);if(closed||options.signal?.aborted)return fail("aborted","Tasks source request was stopped");const row=method(id);if(!("ok"in row))return row;const prepared=prepare(row.ok,call);if(!("ok"in prepared))return prepared;const grant=await resolveGrant();if(!("ok"in grant))return grant;const boundPrincipal=principal;if(!row.ok.scopes.some(scope=>activeScopes.includes(scope)))return fail("permission_denied",row.ok.method==="GET"?"Google Tasks read scope is missing":"Google Tasks write scope requires separate user consent","auth");if(row.ok.resource==="tasks"&&["patch","update"].includes(row.ok.operation)&&record(call.body)&&Object.hasOwn(call.body,"deleted")){const target=await invoke("tasks.tasks.get",{params:{tasklist:call.params["tasklist"],task:call.params["task"]}},options);if(!("ok"in target))return target;if(record(target.ok.data["assignmentInfo"]))return fail("permission_denied","Task.deleted is readonly for assigned tasks; no source write was attempted");if(principal!==boundPrincipal)return fail("permission_denied","Tasks account changed before conditional field mutation","auth")}const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;const request={method:row.ok.method,...prepared.ok.body===void 0?{}:{body:prepared.ok.body,contentType:"application/json"},signal};const response=transport?await transport("google-tasks",prepared.ok.url,request):await auth.requestRaw("google-tasks",prepared.ok.url,request);if(closed||signal.aborted)return fail("aborted","Tasks response arrived after cancellation");const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;if(selected.ok?.accountId!==boundPrincipal||principal!==boundPrincipal)return fail("permission_denied","Tasks account changed while the provider request was active","auth");return"ok"in response?decode(row.ok,response.ok):response}function invoke(id,call,options={}){if(pending.size>=32)return Promise.resolve(fail("resource_exhausted","Tasks source has reached its active call bound"));const task=invokeInner(id,call,options).finally(()=>pending.delete(task));pending.add(task);return task}function invokeSync(id,call){call=structuredClone(call);if(!transportSync)return parts.gateRefusal("Google Tasks synchronous request","fixture-oracle only");if(!principal)return parts.gateRefusal("Google Tasks synchronous identity","bind verified account first");const row=method(id);if(!("ok"in row))return"err"in row?row:parts.connectorError("data_loss","Tasks method lookup was unconfirmed");const prepared=prepare(row.ok,call);if(!("ok"in prepared))return"err"in prepared?prepared:parts.connectorError("data_loss","Tasks input validation was unconfirmed");if(!row.ok.scopes.some(scope=>activeScopes.includes(scope)))return parts.connectorError("permission_denied","Google Tasks scope is missing");if(row.ok.resource==="tasks"&&["patch","update"].includes(row.ok.operation)&&record(call.body)&&Object.hasOwn(call.body,"deleted")){const target=invokeSync("tasks.tasks.get",{params:{tasklist:call.params["tasklist"],task:call.params["task"]}});if(!Original.isOk(target))return target;if(record(target.ok.data["assignmentInfo"]))return parts.connectorError("permission_denied","Task.deleted is readonly for assigned tasks; no source write was attempted")}const response=transportSync("google-tasks",prepared.ok.url,{method:row.ok.method,...prepared.ok.body===void 0?{}:{body:prepared.ok.body,contentType:"application/json"}});return"ok"in response?decode(row.ok,response.ok):"err"in response?response:parts.connectorError("data_loss","Tasks fixture response was unconfirmed")}const asOriginal=async(id,call,options)=>{const reply=await invoke(id,call,options);return"empty"in reply?parts.connectorError("data_loss","Tasks provider read was unconfirmed"):reply};const connector=createTasksConnector({parts,accountId:()=>principal,request:asOriginal,...transportSync?{requestSync:invokeSync}:{},now,live:()=>!closed});const rawCompounds=createTasksCompounds({invoke,account:()=>principal,...compoundCustody?{conditional:{async compareAndMutate(input){const selected=method(input.method);if(!("ok"in selected))return selected;const valid=prepare(selected.ok,input.call);if(!("ok"in valid))return valid;const grant=await resolveGrant();if(!("ok"in grant))return grant;if(input.accountId!==principal||!selected.ok.scopes.some(scope=>activeScopes.includes(scope)))return fail("permission_denied","Compound mutation authority is not bound to the verified write account","auth");return compoundCustody.compareAndMutate(input)}}}:{},...compoundReceipts?{receipts:compoundReceipts}:{}});function owned(task){const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled}const compOptions=read=>({signal:read?.signal?AbortSignal.any([read.signal,stop.signal]):stop.signal});const compounds={execute(name,input,key,read){input=structuredClone(input);return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.execute(name,input,key,compOptions(read))})())},compensate(key,read){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.compensate(key,compOptions(read))})())},probe(key){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return Original.ok({reading:"unknown"});return rawCompounds.probe(key)})())},recover(key,read){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.recover(key,compOptions(read))})())}};const arms={},probes={};for(const row of METHODS){arms[row.contract]=async(grant,call)=>{if(grant.source!=="google-tasks"||!row.scopes.some(scope=>grant.scopes.includes(scope)))return parts.connectorError("permission_denied","Tasks action grant does not authorize this method");if(!record(call.params)||!record(call.params["params"]))return parts.connectorError("invalid_argument","Tasks action must use the discovered input wrapper");const input=call.params,reply=await asOriginal(row.id,input,{signal:call.signal});if(!Original.isOk(reply))return reply;if(row.method==="GET")return Original.ok({result:reply.ok.data});if(mutationReceipts.size>=256)mutationReceipts.delete(mutationReceipts.keys().next().value);mutationReceipts.set(call.idempotencyKey,{method:row,call:structuredClone(input),reply:reply.ok});return Original.ok({evidenceHint:"google-tasks provider accepted mutation; verification required"})};if(row.method!=="GET")probes[row.contract+".verify"]={confidentAfterMs:0,read:async(_grant,call)=>{const receipt=mutationReceipts.get(call.idempotencyKey);if(!receipt)return Original.ok({reading:"unknown"});const params=receipt.call.params,body=receipt.call.body;if(row.operation==="clear"||row.operation==="move"||row.operation==="delete"||record(receipt.reply.data["assignmentInfo"]))return Original.ok({reading:"unknown"});const id=typeof receipt.reply.data["id"]==="string"?receipt.reply.data["id"]:params[row.resource==="tasklists"?"tasklist":"task"];if(typeof id!=="string")return Original.ok({reading:"unknown"});const lookup=row.resource==="tasklists"?{tasklist:id}:{tasklist:params["tasklist"],task:id};const answer=await invoke(row.resource==="tasklists"?"tasks.tasklists.get":"tasks.tasks.get",{params:lookup});if("err"in answer){if(row.operation==="delete"&&answer.err.code==="not_found")return Original.ok({reading:"effected"});return Original.ok({reading:"unknown"})}if(!("ok"in answer))return Original.ok({reading:"unknown"});if(row.operation==="delete")return Original.ok({reading:"absent"});if(!record(body))return Original.ok({reading:"unknown"});const matches=Object.entries(body).every(([key,value])=>JSON.stringify(answer.ok.data[key])===JSON.stringify(value));return Original.ok({reading:matches?"effected":"absent"})}}}connector.actionRail=parts.defineConnectorActions({arms,probes});for(const row of COMPOUND_METHODS){arms[row.contract]=async(grant,call)=>{if(grant.source!=="google-tasks"||!grant.scopes.includes("https://www.googleapis.com/auth/tasks"))return parts.connectorError("permission_denied","Personal compound requires an authorized Tasks write grant");if(!record(call.params)||!record(call.params["params"]))return parts.connectorError("invalid_argument","Personal compound requires generated wrapper parameters");const result=await compounds.execute(row.contract,call.params,call.idempotencyKey,{signal:call.signal});return"ok"in result?Original.ok({evidenceHint:"google-tasks-compound:"+result.ok.receiptKey}):"err"in result?result:parts.connectorError("data_loss","Compound execution was unconfirmed")};probes[row.contract+".verify"]={confidentAfterMs:0,read:async(_grant,call)=>{const result=await compounds.probe(call.idempotencyKey);return"ok"in result?Original.ok(result.ok):"err"in result?result:parts.connectorError("data_loss","Compound probe was unconfirmed")}}}connector.actionRail=parts.defineConnectorActions({arms,probes});const service={info,connector,compounds,resolveGrant,status:()=>closed?Promise.resolve(fail("aborted","Tasks source is inactive")):connectionState(vault,info),connect:options=>closed?Promise.resolve(fail("aborted","Tasks source is inactive")):auth.connect("google-tasks",options),job:id=>closed?fail("aborted","Tasks source is inactive"):auth.job(id),cancelJob:id=>auth.cancelJob(id),method,invoke,catalog(options={}){const limit=options.limit??20,cursor=options.cursor??0;if(!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return fail("invalid_argument","Catalog limit/cursor is invalid");const rows=METHODS.filter(row=>(!options.resource||row.resource===options.resource)&&(!options.query||(row.id+" "+row.description).toLowerCase().includes(options.query.toLowerCase())));return Original.ok({total:rows.length,methods:rows.slice(cursor,cursor+limit).map(row=>({id:row.id,contract:row.contract,resource:row.resource,method:row.method,scopes:row.scopes,body:row.body,media:false})),...cursor+limit<rows.length?{next:cursor+limit}:{},pin:DISCOVERY_PIN,gaps:["Tasks API exposes dates only, no due time of day, reminders, recurrence rule, attachments, author or complete revision history.","Assignment resource keys are protected; fetching its Docs/Chat origin requires that source authorization."]})},async*pages(id,params,options={}){const row=method(id);if(!("ok"in row)){yield row;return}if(row.ok.method!=="GET"||row.ok.operation!=="list"){yield fail("invalid_argument","Pagination only applies to Tasks read-list methods");return}const max=options.maxPages??1e4;if(!Number.isInteger(max)||max<1||max>1e5){yield fail("invalid_argument","maxPages is invalid");return}let current={...params};const seen=new Set;for(let page=0;page<max;page++){const answer=await invoke(id,{params:current},options);yield answer;if(!("ok"in answer)||!answer.ok.nextPageToken)return;const token=answer.ok.nextPageToken;if(seen.has(token)||current["pageToken"]===token){yield fail("data_loss","Google Tasks page token repeated; collection was not exhausted");return}seen.add(token);current={...current,pageToken:token}}yield fail("resource_exhausted","Requested pagination bound reached; collection is incomplete")},async check(options={}){if(closed||options.signal?.aborted)return fail("aborted","Tasks check was stopped");const grant=await resolveGrant();if(!("ok"in grant))return grant;const accountId=grant.ok.account;const answer=await invoke("tasks.tasklists.list",{params:{maxResults:1}},options);if(!("ok"in answer))return answer;const current=await vault.connection("google-tasks");if(closed||options.signal?.aborted)return fail("aborted","Tasks check was stopped");if(!("ok"in current))return current;if(current.ok?.state!=="connected"||current.ok.accountId!==accountId||!current.ok.scopes.some(scope=>scope==="https://www.googleapis.com/auth/tasks.readonly"||scope==="https://www.googleapis.com/auth/tasks"))return fail("permission_denied","Tasks check connection or scope changed","auth");if(answer.ok.items.length>1)return fail("data_loss","Tasks readiness response exceeded the requested one-record bound");return Original.ok({source:"google-tasks",basis:"read",operation:{state:"succeeded",returned:answer.ok.items.length}})},async read(request,options={}){const invalid=validateRead(request);if(invalid)return invalid;const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;if(closed||signal.aborted)return fail("aborted","Tasks read was stopped");const grant=await resolveGrant();if(!("ok"in grant))return grant;const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;const captured=structuredClone(selected.ok);if(!captured||captured.state!=="connected"||captured.accountId!==grant.ok.account)return fail("permission_denied","Tasks account changed before the selected read","auth");const readScope="https://www.googleapis.com/auth/tasks.readonly",writeScope="https://www.googleapis.com/auth/tasks",requiredScope=captured.scopes.includes(readScope)?readScope:captured.scopes.includes(writeScope)?writeScope:null;if(!requiredScope)return fail("permission_denied","Google Tasks read scope is missing","auth");const boundPrincipal=captured.accountId,boundGrant=structuredClone(grant.ok),limit=request.limit??1;const records=[],warnings=new Set;let scanned=0,matched=0;const fence=async()=>{if(closed||signal.aborted)return fail("aborted","Tasks read was stopped");const current=await vault.connection("google-tasks");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==boundPrincipal||!current.ok.scopes.includes(requiredScope))return fail("permission_denied","Tasks read connection or scope changed","auth");return Original.ok(void 0)};const reading=createTasksConnector({parts,accountId:()=>boundPrincipal,request:async(id,call)=>{const before=await fence();if(!("ok"in before))return"err"in before?before:parts.connectorError("data_loss","Tasks read fence was unconfirmed");const answer2=await asOriginal(id,call,{signal});const after=await fence();return"ok"in after?answer2:"err"in after?after:parts.connectorError("data_loss","Tasks read fence was unconfirmed")},now,live:()=>!closed&&!signal.aborted});for await(const page of reading.scan(boundGrant,null)){if(signal.aborted||closed)return fail("aborted","Tasks read was stopped");if(!Original.isOk(page))return page;scanned+=page.ok.items.length;for(const note of page.ok.notes??[])warnings.add(note);for(const item of page.ok.items){const proto=reading.normalize(item),fields=record(proto.payload)?proto.payload:{};if(fields["deleted"]===true)continue;const text=proto.body??"";if(request.query&&!text.toLowerCase().includes(request.query.toLowerCase()))continue;if(request.since&&Date.parse(proto.ts)<Date.parse(request.since)||request.until&&Date.parse(proto.ts)>Date.parse(request.until))continue;matched++;records.push({source:"google-tasks",sourceId:encodeURIComponent(boundPrincipal)+":"+proto.nk.sourceId,stream:proto.nk.stream,kind:proto.kind,ts:proto.ts,body:text,fields});records.sort((a,b)=>(b.ts??"").localeCompare(a.ts??"")||(a.sourceId??"").localeCompare(b.sourceId??""));if(records.length>limit)records.length=limit}}const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;const answer=readResult("google-tasks",records,[...warnings]);return"ok"in answer?Original.ok({...answer.ok,scanned,matched}):answer},async close(){closed=true;stop.abort();await Promise.allSettled([...pending]);mutationReceipts.clear();principal=null;activeScopes=[]}};const ownedRead=service.read.bind(service);service.read=(request,options)=>{if(closed)return Promise.resolve(fail("aborted","Tasks source is inactive"));const task=ownedRead(request,options).finally(()=>pending.delete(task));pending.add(task);return task};const ownedCheck=service.check.bind(service);service.check=options=>{if(closed)return Promise.resolve(fail("aborted","Tasks source is inactive"));const task=ownedCheck(options).finally(()=>pending.delete(task));pending.add(task);return task};service.actions={catalog(input){if(input?.profile&&input.profile!=="data")return fail("invalid_argument","Tasks supports the data profile only");if(input?.resource==="personal"||input?.resource==="personal-deleted"){const selected=COMPOUND_METHODS.filter(row=>row.resource===input.resource);return Original.ok({total:selected.length,methods:selected.map(row=>({id:row.id,contract:row.contract,resource:row.resource,method:row.method,scopes:row.scopes,body:row.body,media:false})),pin:"zortex-personal-task-compound@1",gaps:["Requires host atomic target+collection guard custody and durable private receipts"]})}const raw=service.catalog(input);return"ok"in raw?Original.ok({...raw.ok,additionalOperationResources:["personal","personal-deleted"]}):raw},method:publicMethod,async invoke(id,input,options){if(input.media!==void 0)return fail("invalid_argument","Tasks has no media-upload method");if(COMPOUND_METHODS.some(row=>row.id===id)){const receiptKey=Original.ulid();const result=await compounds.execute(id,input,receiptKey,options);return"ok"in result?Original.ok({method:id,resource:"personal",data:result.ok,items:[],warnings:["Private compound accepted; query its receipt/probe before claiming an effect"],effect:"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}}):result}return invoke(id,input,options)}};return service}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const NSSTRING=new TextEncoder().encode("NSString");const STRING_TAG=43;const TAG_WINDOW=8;function indexOf(hay,needle,from=0){outer:for(let i=from;i+needle.length<=hay.length;i++){for(let j=0;j<needle.length;j++)if(hay[i+j]!==needle[j])continue outer;return i}return-1}export function attributedBodyTextV1(body){if(body===null||body===void 0||body.length===0)return null;const at=indexOf(body,NSSTRING);if(at<0)return null;let i=at+NSSTRING.length;const stop=Math.min(body.length,i+TAG_WINDOW);while(i<stop&&body[i]!==STRING_TAG)i++;if(i>=stop)return null;i+=1;const lead=body[i];if(lead===void 0)return null;let length;if(lead<128){length=lead;i+=1}else if(lead===129){if(i+3>body.length)return null;length=body[i+1]|body[i+2]<<8;i+=3}else if(lead===130){if(i+5>body.length)return null;length=(body[i+1]|body[i+2]<<8|body[i+3]<<16|body[i+4]<<24)>>>0;i+=5}else{return null}if(length===0||i+length>body.length)return null;try{return new TextDecoder("utf-8",{fatal:true}).decode(body.subarray(i,i+length))}catch{return null}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DatabaseSync}from"node:sqlite";import{homedir}from"node:os";import{join}from"node:path";import{Original}from"@zortexhq/plugin-connector-framework/api";const{errResult,ok}=Original;import{snapshotError,snapshotLiveSqlite}from"./sqlite-snapshot.js";import{attributedBodyTextV1}from"./attributed-body.js";export const MAX_MESSAGES=25e4;const APPLE_2001_EPOCH_MS=Date.parse("2001-01-01T00:00:00.000Z");export function defaultMessagesChatDbPath(home=homedir()){return join(home,"Library","Messages","chat.db")}function sqliteErr(code,message,retryability="non-retryable"){return errResult({code,layer:"upstream",retryability,message})}function messagesDateToIso(raw){if(raw===null||raw===""||raw==="0")return"";const n=BigInt(raw);const ms=n>10000000000000n?Number(n/1000000n):Number(n*1000n);return new Date(APPLE_2001_EPOCH_MS+ms).toISOString()}function tableExists(db,name){const row=db.prepare("SELECT COUNT(*) AS n FROM sqlite_master WHERE type='table' AND name=?").get(name);return(row?.n??0)>0}function columnExists(db,table,column){return db.prepare(`SELECT COUNT(*) AS n FROM pragma_table_info('${table}') WHERE name = ?`).get(column)?.n===1}function relationMap(db,table,left,right){const out=new Map;if(!tableExists(db,table))return out;const rows=db.prepare(`SELECT CAST(${left} AS TEXT) AS l, CAST(${right} AS TEXT) AS r FROM ${table} ORDER BY ${left}, ${right}`).all();for(const row of rows){const list=out.get(row.l)??[];list.push(row.r);out.set(row.l,list)}return out}export class ChatDbMessagesSource{opts;constructor(opts={}){this.opts=opts}chatDbPath(){return this.opts.chatDbPath??defaultMessagesChatDbPath()}get cap(){return this.opts.cap??MAX_MESSAGES}get store(){return this.opts.store??this.chatDbPath()}snapshot;db;close(){try{this.db?.close()}finally{if(this.snapshot&&"ok"in this.snapshot)this.snapshot.ok.cleanup();this.db=void 0;this.snapshot=void 0}}read(fn){try{const snapshot=this.snapshot??=snapshotLiveSqlite(this.chatDbPath(),{...this.opts.snapshot,...this.opts.stagingRoot===void 0?{}:{stagingRoot:this.opts.stagingRoot}});if("err"in snapshot)return errResult(snapshotError(snapshot.err));if(!this.db){this.db=new DatabaseSync(snapshot.ok.path,{readOnly:true});if(!["message","chat","handle","attachment"].every(table=>tableExists(this.db,table))){this.close();return sqliteErr("data_loss","The Messages database is missing a required table.")}}return fn(this.db)}catch{return sqliteErr("data_loss","Indra could not read the Messages database snapshot.")}}census(){return this.read(db=>{const count=table=>tableExists(db,table)?db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()?.n??0:0;return ok({message:count("message"),chat:count("chat"),handle:count("handle"),attachment:count("attachment")})})}rowIds(){return this.read(db=>{const ids={message:[],chat:[],handle:[],attachment:[]};for(const stream of Object.keys(ids)){const rows=db.prepare(`SELECT CAST(ROWID AS TEXT) AS r FROM ${stream} ORDER BY ROWID LIMIT ?`).all(this.cap+1);if(rows.length>this.cap){return sqliteErr("resource_exhausted",`imessage: The Messages ${stream} table exceeds the ${this.cap}-row import limit.`)}ids[stream]=rows.map(row=>row.r)}return ok({store:this.store,ids})})}messages(){return this.read(db=>{const total=db.prepare("SELECT COUNT(*) AS n FROM message").get()?.n??0;if(total>this.cap)return sqliteErr("resource_exhausted",`imessage: ${total} messages exceeds cap ${this.cap} \u2014 refused loud, never truncated`);const chatIds=relationMap(db,"chat_message_join","message_id","chat_id");const attachmentIds=relationMap(db,"message_attachment_join","message_id","attachment_id");const rows=db.prepare("SELECT CAST(m.ROWID AS TEXT) AS rowid, m.guid AS guid, m.text AS text, m.service AS service, m.account AS account, CAST(m.handle_id AS TEXT) AS handle_id, h.id AS handle, h.service AS handle_service, CAST(m.date AS TEXT) AS date, CAST(m.date_read AS TEXT) AS date_read, CAST(m.date_delivered AS TEXT) AS date_delivered, m.is_from_me AS is_from_me, m.cache_roomnames AS cache_roomnames, m.associated_message_guid AS associated_message_guid, m.associated_message_type AS associated_message_type, "+(columnExists(db,"message","attributedBody")?"m.attributedBody":"NULL")+" AS attributed_body FROM message m LEFT JOIN handle h ON h.ROWID = m.handle_id ORDER BY m.ROWID").all();return ok(rows.map(r=>({store:this.store,rowid:r.rowid,guid:r.guid??"",text:r.text!==null&&r.text!==""?r.text:attributedBodyTextV1(r.attributed_body)??"",service:r.service??"",account:r.account??"",handleId:r.handle_id??"",handle:r.handle??"",handleService:r.handle_service??"",chatIds:chatIds.get(r.rowid)??[],attachmentIds:attachmentIds.get(r.rowid)??[],isFromMe:(r.is_from_me??0)===1,dateIso:messagesDateToIso(r.date),dateReadIso:messagesDateToIso(r.date_read),dateDeliveredIso:messagesDateToIso(r.date_delivered),cacheRoomnames:r.cache_roomnames??"",associatedMessageGuid:r.associated_message_guid??"",associatedMessageType:r.associated_message_type??0})))})}chats(){return this.read(db=>{const rows=db.prepare("SELECT CAST(ROWID AS TEXT) AS rowid, guid, chat_identifier, service_name, display_name, room_name, last_addressed_handle FROM chat ORDER BY ROWID").all();return ok(rows.map(r=>({store:this.store,rowid:r.rowid,guid:r.guid??"",chatIdentifier:r.chat_identifier??"",serviceName:r.service_name??"",displayName:r.display_name??"",roomName:r.room_name??"",lastAddressedHandle:r.last_addressed_handle??""})))})}handles(){return this.read(db=>{const rows=db.prepare("SELECT CAST(ROWID AS TEXT) AS rowid, id, service, country, uncanonicalized_id FROM handle ORDER BY ROWID").all();return ok(rows.map(r=>({store:this.store,rowid:r.rowid,id:r.id??"",service:r.service??"",country:r.country??"",uncanonicalizedId:r.uncanonicalized_id??""})))})}attachments(){return this.read(db=>{const rows=db.prepare("SELECT CAST(ROWID AS TEXT) AS rowid, guid, filename, mime_type, transfer_name, total_bytes, CAST(created_date AS TEXT) AS created_date, CAST(start_date AS TEXT) AS start_date, CAST(user_info AS TEXT) AS user_info FROM attachment ORDER BY ROWID").all();return ok(rows.map(r=>({store:this.store,rowid:r.rowid,guid:r.guid??"",filename:r.filename??"",mimeType:r.mime_type??"",transferName:r.transfer_name??"",totalBytes:r.total_bytes??0,createdIso:messagesDateToIso(r.created_date),startDateIso:messagesDateToIso(r.start_date),userInfo:r.user_info??""})))})}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Original}from"@zortexhq/plugin-connector-framework/api";import{IMESSAGE_ATTACHMENT_DELETED_KIND,IMESSAGE_ATTACHMENT_STREAM,IMESSAGE_CHAT_DELETED_KIND,IMESSAGE_CHAT_STREAM,IMESSAGE_HANDLE_DELETED_KIND,IMESSAGE_HANDLE_STREAM,IMESSAGE_MANIFEST,IMESSAGE_MESSAGE_DELETED_KIND,IMESSAGE_MESSAGE_STREAM,IMESSAGE_SOURCE}from"./manifest.js";const{isOk,ok}=Original;const IMESSAGE_STREAMS=[IMESSAGE_MESSAGE_STREAM,IMESSAGE_CHAT_STREAM,IMESSAGE_HANDLE_STREAM,IMESSAGE_ATTACHMENT_STREAM];const DELETED_KIND={message:IMESSAGE_MESSAGE_DELETED_KIND,chat:IMESSAGE_CHAT_DELETED_KIND,handle:IMESSAGE_HANDLE_DELETED_KIND,attachment:IMESSAGE_ATTACHMENT_DELETED_KIND};const EMITS_REV={message:true,chat:false,handle:false,attachment:false};export const IMESSAGE_AUDIT_EVIDENCE_MAX=2e3;function isRetiredMarker(raw){return raw!==null&&typeof raw==="object"&&raw.__imessageRetired===true}function retiredItem(stream,store,rowid,observedAtIso){const marker={__imessageRetired:true,store,rowid,observedAtIso};return{streamRef:stream,raw:marker}}function normalizeRetired(stream,marker){return{nk:{source:IMESSAGE_SOURCE,stream,sourceId:marker.rowid,...EMITS_REV[stream]?{rev:marker.observedAtIso}:{}},ts:marker.observedAtIso,tier:"local-app",kind:DELETED_KIND[stream],schemaVersion:1,mentions:[],body:`${stream} ${marker.rowid} \u2014 deleted from the Messages store`,payload:{store:marker.store,rowid:marker.rowid,deleted:true,observedAtIso:marker.observedAtIso}}}function mention(ns,value,role){return value!==""?[{role,raw:value,handle:{ns,value}}]:[]}function addCounts(into,one){into.message+=one.message;into.chat+=one.chat;into.handle+=one.handle;into.attachment+=one.attachment}export function createImessageConnector(parts,source,opts={}){const{auditFromListingV1,boundPageItemsV1,prefixEpoch}=parts;const now=opts.now??(()=>new Date().toISOString());const connector={manifest:IMESSAGE_MANIFEST,discover(grant){void grant;const c=source.census();if(!isOk(c))return c;const totals={message:0,chat:0,handle:0,attachment:0};addCounts(totals,c.ok);return ok({asOf:now(),streams:{[IMESSAGE_MESSAGE_STREAM]:{total:totals.message,method:"count-api"},[IMESSAGE_CHAT_STREAM]:{total:totals.chat,method:"count-api"},[IMESSAGE_HANDLE_STREAM]:{total:totals.handle,method:"count-api"},[IMESSAGE_ATTACHMENT_STREAM]:{total:totals.attachment,method:"count-api"}}})},pull(grant,cursor){void grant;void cursor;const messages=source.messages();if(!isOk(messages))return messages;const chats=source.chats();if(!isOk(chats))return chats;const handles=source.handles();if(!isOk(handles))return handles;const attachments=source.attachments();if(!isOk(attachments))return attachments;const items=[];for(const m of messages.ok)items.push({streamRef:IMESSAGE_MESSAGE_STREAM,raw:m});for(const c of chats.ok)items.push({streamRef:IMESSAGE_CHAT_STREAM,raw:c});for(const h of handles.ok)items.push({streamRef:IMESSAGE_HANDLE_STREAM,raw:h});for(const a of attachments.ok)items.push({streamRef:IMESSAGE_ATTACHMENT_STREAM,raw:a});return ok({items,next:null,exhausted:true})},normalize(item){if(isRetiredMarker(item.raw)){if(!IMESSAGE_STREAMS.includes(item.streamRef)){throw new Error(`imessage normalize: undeclared streamRef '${item.streamRef}'`)}return normalizeRetired(item.streamRef,item.raw)}switch(item.streamRef){case IMESSAGE_MESSAGE_STREAM:return normalizeMessage(item.raw);case IMESSAGE_CHAT_STREAM:return normalizeChat(item.raw);case IMESSAGE_HANDLE_STREAM:return normalizeHandle(item.raw);case IMESSAGE_ATTACHMENT_STREAM:return normalizeAttachment(item.raw);default:throw new Error(`imessage normalize: undeclared streamRef '${item.streamRef}'`)}}};connector.discoverAsync=async grant=>connector.discover(grant);connector.pullAsync=async(grant,cursor)=>connector.pull(grant,cursor);connector.auditAsync=async(grant,covered,request)=>{const observedAt=now();let store="";let prefix="";const bareOf=id=>prefix!==""&&id.startsWith(prefix)?id.slice(prefix.length):null;return auditFromListingV1({streams:IMESSAGE_STREAMS,expectedScope:"store",evidenceCap:IMESSAGE_AUDIT_EVIDENCE_MAX,now:()=>observedAt,list:async()=>{const read=source.rowIds();if(!isOk(read))return read;store=read.ok.store;const probe=prefixEpoch(store,"0");if(!isOk(probe))return probe;prefix=probe.ok.slice(0,-1);const listing={};for(const stream of IMESSAGE_STREAMS){listing[stream]={scope:"store",end:"complete",listed:new Set(read.ok.ids[stream].map(rowid=>`${prefix}${rowid}`))}}return ok(listing)},evidence:async(_g,_stream,id)=>ok(bareOf(id)===null?{byId:"unknown"}:{byId:"not-found"}),tombstone:(stream,id)=>retiredItem(stream,store,bareOf(id)??id,observedAt)})(grant,covered,request)};return boundPageItemsV1(connector)}function normalizeMessage(raw){const direction=raw.isFromMe?"sent":"received";const fallback=raw.handle!==""?`iMessage ${direction} with ${raw.handle}`:`iMessage ${direction}`;return{nk:{source:IMESSAGE_SOURCE,stream:IMESSAGE_MESSAGE_STREAM,sourceId:raw.rowid,rev:raw.dateIso},ts:raw.dateIso,tier:"local-app",kind:raw.isFromMe?"message.sent":"message.received",schemaVersion:1,mentions:[...mention("imessage-handle",raw.handle,raw.isFromMe?"participant":"actor"),...raw.chatIds.flatMap(id=>mention("imessage-chat",id,"participant"))],body:raw.text!==""?raw.text:fallback,payload:raw}}function normalizeChat(raw){const label=raw.displayName||raw.chatIdentifier||raw.guid||raw.rowid;return{nk:{source:IMESSAGE_SOURCE,stream:IMESSAGE_CHAT_STREAM,sourceId:raw.rowid},ts:"1970-01-01T00:00:00.000Z",tier:"local-app",kind:"im.chat",schemaVersion:1,mentions:mention("imessage-chat",raw.chatIdentifier,"participant"),body:label,payload:raw}}function normalizeHandle(raw){return{nk:{source:IMESSAGE_SOURCE,stream:IMESSAGE_HANDLE_STREAM,sourceId:raw.rowid},ts:"1970-01-01T00:00:00.000Z",tier:"local-app",kind:"im.handle",schemaVersion:1,mentions:mention("imessage-handle",raw.id,"participant"),body:raw.id||raw.uncanonicalizedId||raw.rowid,payload:raw}}function normalizeAttachment(raw){const label=raw.transferName||raw.filename||raw.guid||raw.rowid;return{nk:{source:IMESSAGE_SOURCE,stream:IMESSAGE_ATTACHMENT_STREAM,sourceId:raw.rowid},ts:raw.createdIso||raw.startDateIso||"1970-01-01T00:00:00.000Z",tier:"local-app",kind:"im.attachment",schemaVersion:1,mentions:[],body:label,payload:raw}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{createImessageConnector}from"./connector.js";export{ChatDbMessagesSource,defaultMessagesChatDbPath}from"./chatdb-source.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const IMESSAGE_SOURCE="imessage";export const IMESSAGE_MESSAGE_STREAM="message";export const IMESSAGE_CHAT_STREAM="chat";export const IMESSAGE_HANDLE_STREAM="handle";export const IMESSAGE_ATTACHMENT_STREAM="attachment";export const IMESSAGE_MESSAGE_DELETED_KIND="message.deleted";export const IMESSAGE_CHAT_DELETED_KIND="im.chat.deleted";export const IMESSAGE_HANDLE_DELETED_KIND="im.handle.deleted";export const IMESSAGE_ATTACHMENT_DELETED_KIND="im.attachment.deleted";export const IMESSAGE_MANIFEST={source:IMESSAGE_SOURCE,tier:"local-app",auth:{provider:"local",method:"local-permission",scopes:["messages.read"],multiAccount:false,probe:{op:"stat-messages-chatdb"}},tccPermissions:["full-disk"],streams:[{stream:IMESSAGE_MESSAGE_STREAM,kinds:["message.received","message.sent"],identity:{quality:"container-scoped",epochField:"store"},revOrder:"event-ts",deleteKind:IMESSAGE_MESSAGE_DELETED_KIND},{stream:IMESSAGE_CHAT_STREAM,kinds:["im.chat"],identity:{quality:"container-scoped",epochField:"store"},revOrder:"head-compare",deleteKind:IMESSAGE_CHAT_DELETED_KIND},{stream:IMESSAGE_HANDLE_STREAM,kinds:["im.handle"],identity:{quality:"container-scoped",epochField:"store"},revOrder:"head-compare",deleteKind:IMESSAGE_HANDLE_DELETED_KIND},{stream:IMESSAGE_ATTACHMENT_STREAM,kinds:["im.attachment"],identity:{quality:"container-scoped",epochField:"store"},revOrder:"head-compare",deleteKind:IMESSAGE_ATTACHMENT_DELETED_KIND}],actions:[],defaultTaint:"quoted-only",coverageProbe:"count-api",healthProbe:{kind:"fetch-one",intervalMin:15},retaliationRisk:"tolerant"};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{closeSync,copyFileSync,lstatSync,mkdtempSync,openSync,readSync,rmSync,constants}from"node:fs";import{tmpdir}from"node:os";import{join}from"node:path";import{DatabaseSync}from"node:sqlite";const errno=error=>error?.code;const deny=()=>Object.assign(new Error("Messages store files must belong to the native user."),{code:"EACCES"});function stamp(path){try{const stat=lstatSync(path,{bigint:true});if(!stat.isFile()||process.getuid&&stat.uid!==BigInt(process.getuid()))throw deny();return{inode:stat.ino,size:stat.size,modified:stat.mtimeNs}}catch(error){if(errno(error)==="ENOENT")return null;throw error}}function walHeader(path){const fd=openSync(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const bytes=Buffer.alloc(32);return bytes.subarray(0,readSync(fd,bytes,0,bytes.length,0)).toString("hex")}finally{closeSync(fd)}}function fingerprint(path){const db=stamp(path),wal=stamp(path+"-wal");return{db,wal,walHeader:wal?walHeader(path+"-wal"):""}}function stable(before,after){return!!before.db&&!!after.db&&before.db.inode===after.db.inode&&before.db.size===after.db.size&&before.db.modified===after.db.modified&&before.walHeader===after.walHeader&&(before.wal?!!after.wal&&before.wal.inode===after.wal.inode&&before.wal.size<=after.wal.size:after.wal===null)}export function snapshotLiveSqlite(path,options={}){const staging=mkdtempSync(join(options.stagingRoot??tmpdir(),"imessage-chatdb-"));const cleanup=()=>rmSync(staging,{recursive:true,force:true});let retained=false,onlyBusy=true;try{for(let attempt=0;attempt<(options.attempts??4);attempt++){if(attempt)Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,options.settleMs??200);const copy=join(staging,`snapshot-${attempt}.db`);try{const before=fingerprint(path);if(!before.db)return{err:"not_found"};copyFileSync(path,copy);options.betweenCopies?.();if(before.wal)copyFileSync(path+"-wal",copy+"-wal");if(!stable(before,fingerprint(path)))continue}catch(error){if(errno(error)==="EACCES"||errno(error)==="EPERM")return{err:"permission_denied"};if(errno(error)!=="ENOENT")onlyBusy=false;continue}try{const database=new DatabaseSync(copy);try{database.exec("PRAGMA wal_checkpoint(TRUNCATE)");if(database.prepare("PRAGMA quick_check").get()?.quick_check!=="ok"){onlyBusy=false;continue}}finally{database.close()}retained=true;return{ok:{path:copy,cleanup}}}catch{onlyBusy=false}}return{err:onlyBusy?"busy":"data_loss"}}finally{if(!retained)cleanup()}}export function snapshotError(kind){switch(kind){case"not_found":return{code:kind,layer:"upstream",retryability:"non-retryable",message:"The signed-in macOS user\u2019s Messages database is missing."};case"permission_denied":return{code:kind,layer:"auth",retryability:"non-retryable",message:"Allow the Indra host process to read Messages in macOS Full Disk Access and retry."};case"busy":return{code:"resource_exhausted",layer:"upstream",retryability:"transient",message:"Messages changed during every snapshot attempt. Retry the sync."};case"data_loss":return{code:kind,layer:"upstream",retryability:"transient",message:"Indra could not obtain a consistent Messages database snapshot."}}}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zortexhq/plugin-connector-imessage",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"exports": {
|
|
6
|
+
".": {
|
|
7
|
+
"default": "./dist/index.js"
|
|
8
|
+
}
|
|
9
|
+
},
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"@zortexhq/plugin-connector-framework": "0.1.0"
|
|
12
|
+
},
|
|
13
|
+
"zortex": {
|
|
14
|
+
"role": "plugin"
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{setupCua,startManagedCua}from"../cua-runtime.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{constants}from"node:fs";import{open,realpath,stat}from"node:fs/promises";import{isAbsolute,relative,sep}from"node:path";export const MAX_PAGE_BYTES=64*1024;export function pageSchema(name,schema){if(
|
|
1
|
+
import{constants}from"node:fs";import{open,opendir,realpath,stat}from"node:fs/promises";import{extname,isAbsolute,relative,sep}from"node:path";export const MAX_PAGE_BYTES=64*1024,MAX_DIRECTORY_ENTRIES=4096,MAX_DIRECTORY_PAGE=128;export function pageSchema(name,schema){if(!["read_text_file","read_media_file","list_directory"].includes(name)||!schema||typeof schema!=="object"||Array.isArray(schema))return schema;const value=schema;const properties=name==="list_directory"?{cursor:{type:"string",maxLength:512,description:"Continuation from a bounded directory page; invalidated when the directory changes."},limit:{type:"integer",minimum:1,maximum:MAX_DIRECTORY_PAGE}}:{offset:{type:"integer",minimum:0,description:"Optional byte offset; enables bounded base64 paging. Without paging, reads at most 64 KiB."},length:{type:"integer",minimum:1,maximum:MAX_PAGE_BYTES},version:{type:"string",maxLength:256,description:"Version returned by the previous page; abort if the file changed."}};return{...value,properties:{...value.properties,...properties}}}function inside(root,file){const rel=relative(root,file);return rel!==""&&!isAbsolute(rel)&&rel!==".."&&!rel.startsWith(".."+sep)}function versionOf(s){return[s.dev,s.ino,s.size,s.mtimeMs,s.ctimeMs].join(":")}async function selectedPath(roots,path,signal,directory=false){if(typeof path!=="string"||path.length>4096||!isAbsolute(path))throw Error("Select an absolute path in the granted folders.");signal.throwIfAborted();const resolved=await realpath(path),normalizedRoots=await Promise.all(roots.map(root=>realpath(root)));signal.throwIfAborted();if(normalizedRoots.some((root,index)=>root!==roots[index]))throw Error("Selected root changed.");if(!normalizedRoots.some(root=>inside(root,resolved)||directory&&root===resolved))throw Error("Path is outside the selected roots.");return resolved}const mediaTypes={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".wav":"audio/wav",".mp3":"audio/mpeg",".ogg":"audio/ogg",".flac":"audio/flac",".mp4":"video/mp4"};export async function readFilePage(roots,params,signal,kind="text"){const paging=params.offset!==void 0||params.length!==void 0||params.version!==void 0;if(Object.keys(params).some(k=>!["path","offset","length","version",...kind==="text"?["head","tail"]:[]].includes(k)))throw Error("Invalid bounded file read parameters.");const offset=params.offset??0,length=params.length??MAX_PAGE_BYTES,head=params.head,tail=params.tail;if(!Number.isSafeInteger(offset)||Number(offset)<0||!Number.isSafeInteger(length)||Number(length)<1||Number(length)>MAX_PAGE_BYTES||params.version!==void 0&&(typeof params.version!=="string"||params.version.length>256))throw Error("Invalid bounded file read parameters.");if(Number(offset)>0&&!params.version)throw Error("A file version is required after the first page.");if(head!==void 0&&(!Number.isSafeInteger(head)||Number(head)<1||Number(head)>1e4)||tail!==void 0&&(!Number.isSafeInteger(tail)||Number(tail)<1||Number(tail)>1e4)||head!==void 0&&tail!==void 0||paging&&(head!==void 0||tail!==void 0))throw Error("Choose bounded byte paging or one positive line selection.");const resolved=await selectedPath(roots,params.path,signal);const handle=await open(resolved,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0));try{const before=await handle.stat();signal.throwIfAborted();if(!before.isFile())throw Error("Selected path is not a regular file.");const checkedPath=await selectedPath(roots,params.path,signal),checked=await stat(checkedPath);if(checkedPath!==resolved||before.dev!==checked.dev||before.ino!==checked.ino)throw Error("Selected file changed during validation.");if(process.platform==="linux"&&await realpath("/proc/self/fd/"+handle.fd)!==resolved)throw Error("Opened file is outside the selected path.");const version=versionOf(before);if(params.version!==void 0&¶ms.version!==version)throw Error("Selected file changed between pages.");const start=tail===void 0?Number(offset):Math.max(0,before.size-Number(length));const buffer=Buffer.alloc(Number(length)+(paging?0:1));let count=0;while(count<buffer.length){signal.throwIfAborted();const read=await handle.read(buffer,count,buffer.length-count,start+count);signal.throwIfAborted();if(!read.bytesRead)break;count+=read.bytesRead}const after=await handle.stat(),finalPath=await selectedPath(roots,params.path,signal),final=await stat(finalPath);if(versionOf(after)!==version||finalPath!==resolved||final.dev!==before.dev||final.ino!==before.ino)throw Error("Selected file changed during reading.");signal.throwIfAborted();const data=buffer.subarray(0,Math.min(count,Number(length))),nextOffset=start+data.length,eof=nextOffset>=after.size;const page={offset:start,nextOffset,eof,version};if(paging)return{structured:{encoding:"base64",data:data.toString("base64"),...page}};if(kind==="media")return{structured:{encoding:"base64",mimeType:mediaTypes[extname(resolved).toLowerCase()]??"application/octet-stream",data:data.toString("base64"),bytes:data.length,truncated:!eof,...page}};let leading=0;if(tail!==void 0&&start>0)while(leading<3&&leading<data.length&&(data[leading]&192)===128)leading++;let text;try{text=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(data.subarray(leading),{stream:!eof})}catch{throw Error("This bounded prefix is not UTF-8 text; use read_media_file or explicit byte paging.")}if(text.includes("\0"))throw Error("This file contains binary data; use read_media_file or explicit byte paging.");const decodedEnd=start+leading+Buffer.byteLength(text,"utf8");let textOffset=start+leading;if(head!==void 0||tail!==void 0){const ended=text.endsWith("\n"),lines=text.split("\n");if(ended)lines.pop();if(tail!==void 0&&start>0&&lines.length>1)lines.shift();const chosen=head!==void 0?lines.slice(0,Number(head)):lines.slice(-Number(tail));text=chosen.join("\n")+(ended||head!==void 0&&chosen.length<lines.length?"\n":"");if(tail!==void 0)textOffset=decodedEnd-Buffer.byteLength(text,"utf8")}const textBytes=Buffer.byteLength(text,"utf8"),textNext=textOffset+textBytes;return{structured:{encoding:"utf-8",text,bytes:textBytes,truncated:textOffset>0||textNext<after.size,...page,offset:textOffset,nextOffset:textNext,eof:textNext>=after.size}}}finally{await handle.close()}}export async function listDirectoryPage(roots,params,signal){if(Object.keys(params).some(k=>!["path","cursor","limit"].includes(k)))throw Error("Invalid bounded directory parameters.");const limit=params.limit??MAX_DIRECTORY_PAGE;if(!Number.isSafeInteger(limit)||Number(limit)<1||Number(limit)>MAX_DIRECTORY_PAGE)throw Error("Choose a directory page of 1\u2013128 entries.");const path=await selectedPath(roots,params.path,signal,true),before=await stat(path),version=versionOf(before);if(!before.isDirectory())throw Error("Selected path is not a directory.");let offset=0;if(params.cursor!==void 0){if(typeof params.cursor!=="string"||!/^[A-Za-z0-9_-]{1,512}$/.test(params.cursor))throw Error("Invalid directory cursor.");const cursor=JSON.parse(Buffer.from(params.cursor,"base64url").toString("utf8"));if(!cursor||cursor.version!==version||!Number.isSafeInteger(cursor.offset)||Number(cursor.offset)<0||Number(cursor.offset)>=MAX_DIRECTORY_ENTRIES)throw Error("Directory changed or cursor exceeds the bounded listing.");offset=Number(cursor.offset)}const entries=[],directory=await opendir(path,{bufferSize:32});let visited=0,more=false,nextOffset=offset;try{if(await selectedPath(roots,params.path,signal,true)!==path||versionOf(await stat(path))!==version)throw Error("Directory changed while opening.");for await(const entry of directory){signal.throwIfAborted();if(visited>=MAX_DIRECTORY_ENTRIES){more=true;break}visited++;if(visited<=offset)continue;if(entries.length>=Number(limit)){more=true;break}entries.push({name:entry.name,type:entry.isSymbolicLink()?"symlink":entry.isDirectory()?"directory":entry.isFile()?"file":"other"});nextOffset=visited}if(await selectedPath(roots,params.path,signal,true)!==path||versionOf(await stat(path))!==version)throw Error("Directory changed during listing.");const next=more&&nextOffset<MAX_DIRECTORY_ENTRIES?Buffer.from(JSON.stringify({version,offset:nextOffset})).toString("base64url"):void 0;return{structured:{entries,text:entries.map(row=>(row.type==="directory"?"[DIR]":"[FILE]")+" "+row.name).join("\n"),truncated:more,scanned:visited,...next?{next}:{},...!next&&more?{warning:"Directory listing reached its entry limit; use computer-files.catalog.list for bounded catalog search."}:{}}}}finally{await directory.close().catch(()=>{})}}export function createComputerFilesAdapter(roots){let active=0;return async(name,params,signal)=>{if(name==="search_files")throw Error("Recursive filesystem search is disabled. Use computer-files.catalog.list for bounded catalog search.");if(!["read_text_file","read_media_file","list_directory"].includes(name))return void 0;if(active>=2)throw Error("Computer Files already has two local reads in progress.");active++;try{return name==="list_directory"?await listDirectoryPage(roots,params,signal):await readFilePage(roots,params,signal,name==="read_media_file"?"media":"text")}finally{active--}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{lstat}from"node:fs/promises";import{isDeepStrictEqual}from"node:util";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{createComputerFiles}from"@zortexhq/plugin-connector-computer-files";import{captureCustodied,checkCustodied}from"./custodied.js";import{withSettingsReadLock}from"./settings-transaction.js";const source="computer-files",prefix="computer-files.catalog.";const denied=()=>businessError("permission_denied","Computer Files folder selection or native permission changed. Reconnect the selected folders.","plugin");const revision=value=>[value.dev,value.ino,value.size,value.mtimeMs,value.ctimeMs].join(":");const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);export async function attachComputerFiles(original,options){const{vault,auth,selection}=options,prepared=selection.prepared?.[source];if(!Array.isArray(prepared?.roots)||prepared.roots.some(root=>typeof root!=="string")||auth.credentialKind!=="local-no-secret")throw Error("Computer Files requires its prepared native folders.");let closed=false;const currentSelection=value=>!!value?.sources?.includes(source)&&(value.requestedSources===void 0||value.requestedSources.includes(source))&&isDeepStrictEqual(value.prepared?.[source],prepared)&&isDeepStrictEqual(value.bindings?.[source],selection.bindings?.[source]);const authorize=async signal=>{const lifetime=signal??new AbortController().signal;if(closed)return businessError("unavailable","Computer Files is inactive.","plugin");const access=await captureCustodied(source,auth,vault,lifetime);if(!("ok"in access))return access;let selectedRevision;try{if(options.settingsFile)selectedRevision=await withSettingsReadLock(options.settingsFile,()=>{},async current=>{if(!currentSelection(current))throw Error("Folder selection changed.");const metadata=await lstat(options.settingsFile);if(!metadata.isFile()||metadata.isSymbolicLink())throw Error("Settings changed.");return revision(metadata)},{signal:lifetime})}catch{return denied()}const check=async(nextSignal=lifetime)=>{if(closed)return businessError("unavailable","Computer Files is inactive.","plugin");if(nextSignal.aborted)return businessError("aborted","Computer Files operation was cancelled.","plugin");const selected=async()=>{if(selectedRevision===void 0)return true;try{const metadata=await lstat(options.settingsFile);return metadata.isFile()&&!metadata.isSymbolicLink()&&revision(metadata)===selectedRevision}catch{return false}};if(!await selected())return denied();const checked2=await checkCustodied(source,auth,vault,access.ok,nextSignal);if(!("ok"in checked2))return checked2;if(!await selected())return denied();return ok(true)};const checked=await check();return"ok"in checked?ok({check}):checked};const files=await createComputerFiles({vault:options.sqlite,roots:prepared.roots,...options.excludeRoots?{excludeRoots:options.excludeRoots}:{},authorize});const local=files.provider,legacy=original.actions,catalog=local.actions;const provider={...original,status:local.status,connect:local.connect,check:local.check,read:local.read,...original.fileSnapshots?{fileSnapshots:{inspect:(input,readOptions)=>files.withAccess(()=>original.fileSnapshots.inspect(input,readOptions),readOptions?.signal),materialize:(file,readOptions)=>files.withReadAccess(()=>original.fileSnapshots.materialize(file,readOptions),readOptions?.signal)}}:{},job(id){const job=local.job(id);return"err"in job&&job.err.code==="not_found"?original.job(id):job},actions:{reportsActionAccess:true,async catalog(input){const limit=input?.limit??50,cursor=input?.cursor??0;if(!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return businessError("invalid_argument","Catalog limit/cursor is invalid.","plugin");const page=(base,actions2)=>{const value={...base,actions:actions2.slice(cursor,cursor+limit),total:actions2.length};delete value.nextCursor;if(cursor+limit<actions2.length)value.nextCursor=cursor+limit;return ok(value)};const metadata=await catalog.catalog(input);if(input?.query?.toLowerCase().startsWith(prefix))return"ok"in metadata&&object(metadata.ok)&&Array.isArray(metadata.ok.actions)?page(metadata.ok,metadata.ok.actions):metadata;const upstream=await legacy.catalog({...input,cursor:0,limit:100});if(!("ok"in metadata)||!object(metadata.ok)||!Array.isArray(metadata.ok.actions))return upstream;if(!("ok"in upstream)||!object(upstream.ok)||!Array.isArray(upstream.ok.actions))return page({...metadata.ok,warnings:["The filesystem Actions are currently unavailable; catalog Actions remain available."]},metadata.ok.actions);const actions=[...metadata.ok.actions,...upstream.ok.actions];return page(upstream.ok,actions)},method(name){return name.startsWith(prefix)?catalog.method(name):legacy.method(name)},async invoke(name,input,actionOptions){if(name==="computer-files.search_files")return files.withAccess(async()=>businessError("failed_precondition","Use computer-files.catalog.list to search the bounded metadata catalog by file name or path. Recursive filesystem MCP search is unavailable.","plugin"),actionOptions?.signal);if(!name.startsWith(prefix))return name==="computer-files.read_text_file"||name==="computer-files.read_media_file"?files.withReadAccess(()=>legacy.invoke(name,input,actionOptions),actionOptions?.signal):files.withAccess(()=>legacy.invoke(name,input,actionOptions),actionOptions?.signal);const access=await authorize(actionOptions?.signal);if(!("ok"in access))return access;try{actionOptions?.onActionAccess?.("account",async()=>"ok"in await access.ok.check(actionOptions?.signal))}catch{}return catalog.invoke(name,input,actionOptions)}},async close(){closed=true;await Promise.allSettled([files.close(),original.close()])}};return{provider,files}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{execFile}from"node:child_process";import{createHash}from"node:crypto";import{accessSync,constants}from"node:fs";import{mkdir,mkdtemp,rename,rm,stat}from"node:fs/promises";import{createConnection}from"node:net";import{homedir}from"node:os";import{dirname,join}from"node:path";import{setTimeout as delay}from"node:timers/promises";import{promisify}from"node:util";export const cuaVersion="0.28.2";const releases={arm64:["arm64","818ddefa0fa8ba2ec9cba837c7aa634a4b064221c748752cf49c5b08e2c94e8c"],x64:["x86_64","9e00cc92480a8f3d32bbcb7cb45cbc42293b7bd13c1808f5047f1f73a8b64f24"]};const invoke=promisify(execFile);const bundle="CuaDriver.app";const archiveLimit=8e7;const managedApp=join(homedir(),"Applications","Zortex",bundle);const appLocations=[managedApp,"/Applications/"+bundle,join(homedir(),"Applications",bundle)];const executable=app=>join(app,"Contents","MacOS","cua-driver");export const cuaSocket=process.platform==="darwin"?join(homedir(),"Library","Caches","cua-driver","cua-driver.sock"):void 0;function installed(app){try{accessSync(executable(app),constants.X_OK);return true}catch{return false}}export function macCuaApp(){return cuaSocket&&appLocations.find(installed)}export function cuaCommand(){const app=macCuaApp();return app?executable(app):"cua-driver"}async function run(command,args,timeout=15e3){return invoke(command,args,{timeout,maxBuffer:64*1024,windowsHide:true})}async function install(driverArch,sha256){const parent=dirname(managedApp);await mkdir(parent,{recursive:true});const stage=await mkdtemp(join(parent,".cua-driver-"));try{const asset=`cua-driver-rs-${cuaVersion}-darwin-${driverArch}`;const url=`https://github.com/trycua/cua/releases/download/cua-driver-rs-v${cuaVersion}/${asset}.tar.gz`;const{stdout:archive}=await invoke("/usr/bin/curl",["--disable","--fail","--silent","--show-error","--location","--proto","=https","--proto-redir","=https","--max-filesize",String(archiveLimit),url],{encoding:"buffer",timeout:12e4,maxBuffer:archiveLimit});if(createHash("sha256").update(archive).digest("hex")!==sha256)throw Error("The CUA Driver download failed its checksum.");const extraction=invoke("/usr/bin/tar",["-xzf","-","-C",stage,"--strip-components","1",`${asset}/${bundle}`],{timeout:3e4,maxBuffer:64*1024});extraction.child.stdin?.on("error",()=>{});extraction.child.stdin?.end(archive);await extraction;const app=join(stage,bundle);await run("/usr/bin/codesign",["--verify","--deep","--strict",app]);try{await rename(app,managedApp)}catch(error){if(!installed(managedApp))throw error}return managedApp}finally{await rm(stage,{recursive:true,force:true})}}async function serviceRunning(){if(!cuaSocket||!(await stat(cuaSocket).catch(()=>void 0))?.isSocket())return false;return new Promise(resolve=>{const client=createConnection(cuaSocket);const finish=connected=>{client.destroy();resolve(connected)};client.setTimeout(400,()=>finish(false));client.once("error",()=>finish(false));client.once("connect",()=>finish(true))})}let starting;async function startApp(app){if(await serviceRunning())return true;await run("/usr/bin/open",["-n","-g","-a",app,"--args","serve","--no-overlay","--no-permissions-gate"]);for(let attempt=0;attempt<30;attempt++){if(await serviceRunning())return true;await delay(200)}return false}function start(app){return starting??=startApp(app).finally(()=>{starting=void 0})}export async function startManagedCua(){if(cuaSocket&&installed(managedApp))await start(managedApp)}export async function setupCua({grantPermissions=false}={}){const release=releases[process.arch];if(!cuaSocket||!release)return{state:"unsupported-platform"};let app;try{app=macCuaApp()??await install(release[0],release[1])}catch(error){const failure=error;if(failure.code==="ENOSPC"||failure.stderr?.includes("No space left on device")){return{state:"install-failed",reason:"disk-full",next:"Free disk space, then retry indra setup computer-use."}}return{state:"install-failed",next:"Retry indra setup computer-use to download and verify CUA Driver."}}try{if(grantPermissions)await run(executable(app),["permissions","grant"],12e4);if(await start(app)){const{stdout}=await run(executable(app),["permissions","status","--json"]);const permissions=JSON.parse(stdout);if(permissions.accessibility&&permissions.screen_recording&&permissions.screen_recording_capturable!==false){return{state:"installed",permissions}}return{state:"installed",permissions,next:"Run indra setup computer-use --grant-permissions to finish macOS access."}}}catch{}return{state:"installed",permissions:"unverified",next:"Run indra setup computer-use --grant-permissions to verify macOS access."}}
|