@zortexhq/indra-v2.5 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/bin/codex-postinstall.mjs +1 -1
- package/dist/action-effect.js +1 -0
- package/dist/action-read-progress.js +1 -1
- package/dist/actions-catalog.js +1 -0
- package/dist/auto-sync.js +1 -1
- package/dist/auto-update.js +1 -1
- package/dist/automatic-updates.js +1 -0
- package/dist/bundled-handbook.js +1 -1
- package/dist/cli-run.js +1 -1
- package/dist/cli.js +1 -1
- package/dist/codex-install.js +1 -1
- package/dist/codex-setup.js +1 -1
- package/dist/computer-use-setup.js +1 -0
- package/dist/default-root.js +1 -1
- package/dist/documentation-action.js +1 -0
- package/dist/gateway.js +1 -1
- package/dist/imessage-sync.js +1 -1
- package/dist/local-cloud-policy.js +1 -1
- package/dist/local-cloud.js +1 -1
- package/dist/mcp.js +1 -3
- package/dist/native-connect.js +1 -1
- package/dist/native-level1-setup.js +1 -1
- package/dist/native-ollama-discovery.js +1 -0
- package/dist/native-vault-discovery.js +1 -1
- package/dist/onboard-cli.js +1 -1
- package/dist/onboard.js +1 -1
- package/dist/onboarding.js +1 -1
- package/dist/profile.js +1 -1
- package/dist/public-tool.js +4 -1
- package/dist/read-route.js +1 -1
- package/dist/recovery-authorization-url.js +1 -1
- package/dist/recovery-progress.js +1 -1
- package/dist/recovery.js +1 -1
- package/dist/resident-autopilot.js +1 -0
- package/dist/resident-ensure-ready.js +1 -1
- package/dist/resident-host.js +2 -2
- package/dist/resident-jobs.js +1 -1
- package/dist/resident-platform.js +2 -2
- package/dist/resident-runtime-identity.js +1 -1
- package/dist/resident-startup-state.js +1 -0
- package/dist/resident-telemetry.js +1 -1
- package/dist/shared-action-schemas.js +1 -0
- package/dist/source-data.js +1 -1
- package/dist/storage-compatibility.js +1 -0
- package/dist/supervised-sync.js +1 -1
- package/dist/tools.js +1 -1
- package/dist/update-check.js +1 -1
- package/dist/update-cli.js +1 -1
- package/dist/update-command.js +1 -1
- package/dist/update-recovery.js +1 -1
- package/node_modules/@zortexhq/plugin-auto-connect/dist/api/durable-dispatcher.js +1 -1
- package/node_modules/@zortexhq/plugin-auto-connect/dist/api/job-contract.js +1 -1
- package/node_modules/@zortexhq/plugin-autopilot/dist/api.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/cua.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/feedback.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/index.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/python-runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/service.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/worker.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/package.json +23 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/LICENSE +21 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/PROVENANCE.json +38 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/__init__.py +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/agent.py +178 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/browser.py +13 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/indra.patch +57 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/model.py +180 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/questions.py +26 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/transport.py +70 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/strategies.py +154 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/worker.py +260 -0
- package/node_modules/@zortexhq/plugin-connector-activitywatch/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-calendar/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-computer-files/dist/catalog.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/action-outcome.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/connectors.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/authorization-metrics.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/native-principal.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/package.json +2 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/connector.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/package.json +2 -1
- package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/compounds.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/action-content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-server.js +6 -6
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-native-process.mjs +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-server.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-server.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/macos-contacts-server.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-apple-native.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/provisioning.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/specs.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-netease/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-notion/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/mail-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-steam/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-teams/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-teams/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/auth-state.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/full-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/api/action-schemas.js +1 -0
- package/node_modules/@zortexhq/plugin-context-share/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/share.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-catalog.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/account.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -1
- package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/api/execution-scope.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/api/stdio-transport.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/windows-job.js +1 -1
- package/node_modules/@zortexhq/plugin-product-account/dist/index.js +4 -1
- package/node_modules/@zortexhq/plugin-product-account/dist/session-store.js +10 -0
- package/node_modules/@zortexhq/plugin-product-account/dist/storage.js +1 -0
- package/node_modules/@zortexhq/plugin-product-account/package.json +5 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/public-result-visibility.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/credentials.js +3 -3
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/keychain.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/public-visibility.js +7 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/recovery-guard.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +2 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-worker.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +2 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql.js +1 -1
- package/package.json +13 -7
- package/profiles/core.yml +2 -0
- package/release-provenance.json +48 -41
- package/update-manifest.json +573 -296
- package/dist/content-find.js +0 -2
- package/dist/find-snapshots.js +0 -1
- package/dist/match-excerpt.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isOk,ok}from"./original-contracts.js";export function createConnectorModule(parts,manifest){const{auditFromListingChunksV1,boundPageItemsV1,connectorError,cursorCodecV1}=parts;const{GMAIL_ATTACHMENT_KIND,GMAIL_ATTACHMENT_STREAM,GMAIL_DRAFT_KIND,GMAIL_DRAFT_STREAM,GMAIL_LABEL_KIND,GMAIL_LABEL_STREAM,GMAIL_MANIFEST,GMAIL_MESSAGE_DELETED_KIND,GMAIL_MESSAGE_KIND,GMAIL_MESSAGE_STREAM,GMAIL_SOURCE,GMAIL_THREAD_KIND,GMAIL_THREAD_STREAM}=manifest;function isMessageDeletionMarker(raw){return raw!==null&&typeof raw==="object"&&raw.__gmailDeletion===true}const GMAIL_LABEL_TS_UNKNOWN="1970-01-01T00:00:00.000Z";const GMAIL_HISTORY_CATCHUP_MS=15*6e4;const GMAIL_HISTORY_CATCHUP_MAX=200;const GMAIL_THREAD_REFRESH_MAX=25;const GMAIL_TOUCHED_THREADS_MAX=400;const GMAIL_AUDIT_LIST_PAGES=10;const GMAIL_AUDIT_FETCH_MAX=100;const GMAIL_AUDIT_CONFIRM_MAX=200;function splitCoveredMessageId(covered){const at=covered.indexOf(":");if(at<=0||at===covered.length-1)return null;try{return{account:decodeURIComponent(covered.slice(0,at)),id:covered.slice(at+1)}}catch{return null}}const GMAIL_CURSOR=cursorCodecV1({source:GMAIL_SOURCE,version:1,toWire:s=>"done"in s?{done:true,sh:s.sh}:s.phase==="changes"?{ph:s.phase,sh:s.sinceHistoryId,l:s.labelsDone,t:s.threads,hd:s.historyDone}:{ph:s.phase,p:s.pageToken,l:s.labelsDone,sh:s.sinceHistoryId,...s.historyCheckedAtMs===null?{}:{ht:s.historyCheckedAtMs}},validate:wire=>{if(wire===null||typeof wire!=="object")return null;const o=wire;const sinceHistoryId=typeof o.sh==="string"?o.sh:null;const historyCheckedAtMs=typeof o.ht==="number"&&Number.isFinite(o.ht)?o.ht:null;if(o.done===true)return{done:true,sh:sinceHistoryId};if(o.ph==="changes"){const threads=o.t==="all"?"all":Array.isArray(o.t)&&o.t.every(id=>typeof id==="string"&&id!=="")?o.t:null;if(sinceHistoryId===null||threads===null)return null;return{phase:"changes",sinceHistoryId,labelsDone:o.l===true,threads,historyDone:o.hd===true}}if(o.ph==="threads"){const threadToken=typeof o.p==="string"||o.p!==null&&typeof o.p==="object"?o.p:null;return{phase:"threads",pageToken:threadToken,labelsDone:o.l===true,sinceHistoryId,historyCheckedAtMs}}const phase=o.ph==="drafts"?"drafts":"messages";return{phase,pageToken:typeof o.p==="string"?o.p:null,labelsDone:o.l===true,sinceHistoryId,historyCheckedAtMs}}});function decodeCursor(cursor){const d=GMAIL_CURSOR.decode(cursor);if(d===null)return{phase:"messages",pageToken:null,labelsDone:false,sinceHistoryId:null,historyCheckedAtMs:null};if("done"in d){return d.sh===null?{phase:"messages",pageToken:null,labelsDone:false,sinceHistoryId:null,historyCheckedAtMs:null}:{phase:"changes",sinceHistoryId:d.sh,labelsDone:false,threads:[],historyDone:false}}return d}function encodeChangesCursor(sinceHistoryId,labelsDone,threads,historyDone){return GMAIL_CURSOR.encode({phase:"changes",sinceHistoryId,labelsDone,threads,historyDone})}function encodeCursor(phase,pageToken,labelsDone,sinceHistoryId,historyCheckedAtMs=null){const state=phase==="threads"?{phase,pageToken,labelsDone,sinceHistoryId,historyCheckedAtMs}:{phase,pageToken,labelsDone,sinceHistoryId,historyCheckedAtMs};return GMAIL_CURSOR.encode(state)}function encodeDoneCursor(sinceHistoryId){return GMAIL_CURSOR.encode({done:true,sh:sinceHistoryId})}function gmailPage(items,next,exhausted){return"err"in next?next:ok({items,next:next.ok,exhausted})}function headerValue(headers,name){const lower=name.toLowerCase();for(const h of headers)if(h.name.toLowerCase()===lower)return h.value;return void 0}function parseAddress(token){const raw=token.trim();const angled=/<([^>]+)>/.exec(raw);if(angled){const email=angled[1].trim();return email!==""?{raw,email}:{raw}}if(/^[^\s@,]+@[^\s@,]+$/.test(raw))return{raw,email:raw};return{raw}}function parseAddressList(value){return value.split(",").map(t=>t.trim()).filter(t=>t!=="").map(parseAddress)}function mention(role,addr){return{role,raw:addr.raw,...addr.email!==void 0?{handle:{ns:"email",value:addr.email}}:{}}}function extractMentions(headers){const out=[];const from=headerValue(headers,"From");if(from!==void 0)for(const a of parseAddressList(from))out.push(mention("actor",a));const to=headerValue(headers,"To");if(to!==void 0)for(const a of parseAddressList(to))out.push(mention("participant",a));const cc=headerValue(headers,"Cc");if(cc!==void 0)for(const a of parseAddressList(cc))out.push(mention("participant",a));return out}function extractRefs(headers){const out=[];const messageId=headerValue(headers,"Message-ID");if(messageId!==void 0&&messageId.trim()!==""){out.push({rel:"rfc822-message-id",to:{ns:"rfc822-msgid",value:messageId.trim()}})}const inReplyTo=headerValue(headers,"In-Reply-To");if(inReplyTo!==void 0&&inReplyTo.trim()!==""){out.push({rel:"reply-to",to:{ns:"rfc822-msgid",value:inReplyTo.trim()}})}const references=headerValue(headers,"References");if(references!==void 0){for(const r of references.split(/\s+/).map(t=>t.trim()).filter(t=>t!=="")){out.push({rel:"references",to:{ns:"rfc822-msgid",value:r}})}}return out}function decodeB64Url(data){return Buffer.from(data,"base64url").toString("utf8")}function extractBodyText(payload){if(payload===void 0)return"";const out=[];const walk=p=>{const mime=(p.mimeType??"").toLowerCase();const isAttachment=(p.filename??"")!==""||(p.body?.attachmentId??"")!=="";if(!isAttachment&&mime.startsWith("text/plain")&&typeof p.body?.data==="string"&&p.body.data!==""){const t=decodeB64Url(p.body.data);if(t!=="")out.push(t)}for(const c of p.parts??[])walk(c)};walk(payload);return out.join("\n").trim()}function messageBody(headers,snippet,payload,receivedAt){const from=(headerValue(headers,"From")??"").trim();const subject=(headerValue(headers,"Subject")??"").trim();const text=extractBodyText(payload);const content=text!==""?text:snippet.trim();const when=receivedAt===GMAIL_LABEL_TS_UNKNOWN?"":receivedAt;return[when,from,subject,content].filter(s=>s!=="").join(" \u2014 ")}function internalDateToIso(internalDate){if(internalDate===void 0)return GMAIL_LABEL_TS_UNKNOWN;const ms=Number(internalDate);if(!Number.isFinite(ms))return GMAIL_LABEL_TS_UNKNOWN;return new Date(ms).toISOString()}function threadTs(t){let latest=Number.NEGATIVE_INFINITY;for(const m of t.messages??[]){if(m.internalDate===void 0)continue;const ms=Number(m.internalDate);if(Number.isFinite(ms)&&ms>latest)latest=ms}return latest>Number.NEGATIVE_INFINITY?new Date(latest).toISOString():GMAIL_LABEL_TS_UNKNOWN}function threadMentions(t){const seen=new Set;const out=[];for(const m of t.messages??[]){for(const x of extractMentions(m.payload?.headers??[])){const key=`${x.role}|${x.raw}|${x.handle?.value??""}`;if(seen.has(key))continue;seen.add(key);out.push(x)}}return out}function threadBody(t){const first=(t.messages??[])[0];const subject=first!==void 0?(headerValue(first.payload?.headers??[],"Subject")??"").trim():"";const snippet=(t.snippet??"").trim();const head=[subject,snippet].filter(s=>s!=="").join(" \u2014 ");if(head!=="")return head;const count=(t.messages??[]).length;return count>0?`thread ${t.id} (${count} messages)`:`thread ${t.id}`}function attachmentBody(a){const name=a.filename!==""?a.filename:"(unnamed attachment)";const detail=`${a.mimeType}, ${a.size} bytes`;return a.contentOmitted==="over-cap"?`${name} \u2014 ${detail} (content by-reference, over-cap)`:`${name} \u2014 ${detail}`}function attachmentBlobs(a){if(a.sha256===void 0)return void 0;const ref={sha256:a.sha256,bytes:a.size};if(a.mimeType!=="")ref.mime=a.mimeType;if(a.filename!=="")ref.name=a.filename;return[ref]}function createGmailSelectedConnector(source,opts={}){const connector=createGmailConnector(source,opts);const{audit:_accountAudit,auditAsync:_accountAuditAsync,...selected}=connector;return boundPageItemsV1({...selected,pull(grant,cursor){const dec=decodeCursor(cursor);const pageR=source.messagesPage(grant,dec.phase==="messages"?dec.pageToken:null);if(!isOk(pageR))return pageR;const items=pageR.ok.messages.map(message=>({streamRef:GMAIL_MESSAGE_STREAM,raw:message}));const next=pageR.ok.nextPageToken;return gmailPage(items,next===null?encodeDoneCursor(null):encodeCursor("messages",next,true,null),next===null)},discover(grant){const selected2=connector.discover(grant);if(!isOk(selected2))return selected2;return ok({...selected2.ok,streams:Object.fromEntries(Object.entries(selected2.ok.streams).map(([stream,census])=>[stream,{method:census.method,partialReasons:[...census.partialReasons??[],{reason:stream===GMAIL_MESSAGE_STREAM?"selected-gmail;full-corpus-not-measured":"not-read;selected-gmail;full-corpus-not-measured"}]}]))})}})}function createGmailConnector(source,opts={}){const now=opts.now??(()=>new Date().toISOString());function pullChanges(grant,dec,nowMs){const items=[];if(!dec.historyDone){if(!dec.labelsDone){const labelsR=source.labels(grant);if(!isOk(labelsR))return labelsR;for(const l of labelsR.ok)items.push({streamRef:GMAIL_LABEL_STREAM,raw:l})}const changes=source.messageChanges(grant,dec.sinceHistoryId,GMAIL_HISTORY_CATCHUP_MAX);if(!isOk(changes)){if(changes.err.code!=="not_found")return changes;return gmailPage(items,encodeCursor("messages",null,false,null),false)}for(const m of changes.ok.messages)items.push({streamRef:GMAIL_MESSAGE_STREAM,raw:m});for(const a of changes.ok.attachments)items.push({streamRef:GMAIL_ATTACHMENT_STREAM,raw:a});for(const d of changes.ok.deletions){const marker={__gmailDeletion:true,account:d.account,id:d.id,atHistoryId:d.atHistoryId};items.push({streamRef:GMAIL_MESSAGE_STREAM,raw:marker})}let threads=dec.threads;if(threads!=="all"){const touched=new Set(threads);for(const m of changes.ok.messages)if(typeof m.threadId==="string"&&m.threadId!=="")touched.add(m.threadId);threads=touched.size>GMAIL_TOUCHED_THREADS_MAX||source.threadsByIds===void 0?"all":[...touched]}const checkpoint=changes.ok.historyId??dec.sinceHistoryId;return gmailPage(items,encodeChangesCursor(checkpoint,true,threads,!changes.ok.more),false)}if(dec.threads==="all")return gmailPage(items,encodeCursor("threads",null,true,dec.sinceHistoryId,nowMs),false);const batch=dec.threads.slice(0,GMAIL_THREAD_REFRESH_MAX),rest=dec.threads.slice(batch.length);if(batch.length>0&&source.threadsByIds!==void 0){const threadsR=source.threadsByIds(grant,batch);if(!isOk(threadsR))return threadsR;for(const t of threadsR.ok.threads)items.push({streamRef:GMAIL_THREAD_STREAM,raw:t})}return gmailPage(items,rest.length>0?encodeChangesCursor(dec.sinceHistoryId,true,rest,true):encodeCursor("drafts",null,true,dec.sinceHistoryId,nowMs),false)}let deletionHistoryId=null;const gmailAudit=auditFromListingChunksV1({streams:[GMAIL_MESSAGE_STREAM],expectedScope:"account",repairCap:GMAIL_AUDIT_FETCH_MAX,evidenceCap:GMAIL_AUDIT_CONFIRM_MAX,now,beginCall:()=>{deletionHistoryId=null},listChunk:(grant,scope,pageToken)=>{const profile=source.getProfile(grant);if(!isOk(profile))return profile;const listed=source.listMessageIdsPage(grant,scope,pageToken,GMAIL_AUDIT_LIST_PAGES);if(!isOk(listed))return listed;const epoch=encodeURIComponent(profile.ok.emailAddress);return ok({scope:scope==="full"?"account":"recent",ids:{[GMAIL_MESSAGE_STREAM]:listed.ok.ids.map(id=>`${epoch}:${id}`)},next:listed.ok.nextPageToken})},fetchRepairs:(grant,_stream,ids)=>{const coveredOf=new Map;for(const id of ids){const parts2=splitCoveredMessageId(id);if(parts2!==null)coveredOf.set(parts2.id,id)}const hydrated=source.messagesByIds(grant,[...coveredOf.keys()]);if(!isOk(hydrated))return hydrated;return ok({items:[...hydrated.ok.messages.map(m=>({streamRef:GMAIL_MESSAGE_STREAM,raw:m})),...hydrated.ok.attachments.map(a=>({streamRef:GMAIL_ATTACHMENT_STREAM,raw:a}))],repaired:hydrated.ok.messages.map(m=>coveredOf.get(m.id)).filter(id=>id!==void 0)})},evidence:(grant,_stream,id)=>{const parts2=splitCoveredMessageId(id);if(parts2===null)return ok({byId:"unknown"});const answer=source.messageEvidence(grant,parts2.id);if(!isOk(answer))return answer;if(answer.ok==="present")return ok({byId:"present"});if(deletionHistoryId===null){const profile=source.getProfile(grant);if(!isOk(profile))return profile;if(profile.ok.historyId===void 0){return connectorError("internal","gmail getProfile: historyId missing \u2014 cannot order a deletion (REST-surface drift, FM-19)")}deletionHistoryId=profile.ok.historyId}return ok(answer.ok==="trashed"?{byId:"present",trashed:true}:{byId:"not-found"})},tombstone:(_stream,id)=>{const parts2=splitCoveredMessageId(id);const marker={__gmailDeletion:true,account:parts2.account,id:parts2.id,atHistoryId:deletionHistoryId};return{streamRef:GMAIL_MESSAGE_STREAM,raw:marker}}});return boundPageItemsV1({manifest:GMAIL_MANIFEST,discover(grant){const c=source.census(grant);if(!isOk(c))return c;const message={total:c.ok.messages.total,method:"census"};if(c.ok.messages.partialReasons!==void 0)message.partialReasons=c.ok.messages.partialReasons;return ok({asOf:now(),streams:{[GMAIL_MESSAGE_STREAM]:message,[GMAIL_LABEL_STREAM]:{total:c.ok.labels.total,method:"census"},[GMAIL_THREAD_STREAM]:{total:c.ok.threads.total,method:"census"},[GMAIL_DRAFT_STREAM]:{total:c.ok.drafts.total,method:"census"},[GMAIL_ATTACHMENT_STREAM]:{method:"pagination-exhaustion"}}})},pull(grant,cursor){const dec=decodeCursor(cursor);const items=[];const nowMs=Date.parse(now());if(dec.phase==="changes")return pullChanges(grant,dec,nowMs);if(dec.sinceHistoryId!==null&&(dec.historyCheckedAtMs===null||nowMs-dec.historyCheckedAtMs>=GMAIL_HISTORY_CATCHUP_MS)){const changes=source.messageChanges(grant,dec.sinceHistoryId,GMAIL_HISTORY_CATCHUP_MAX);if(!isOk(changes)){if(changes.err.code!=="not_found")return changes;return gmailPage(items,encodeCursor(dec.phase,dec.pageToken,dec.labelsDone,null,nowMs),false)}for(const m of changes.ok.messages)items.push({streamRef:GMAIL_MESSAGE_STREAM,raw:m});for(const a of changes.ok.attachments)items.push({streamRef:GMAIL_ATTACHMENT_STREAM,raw:a});for(const d of changes.ok.deletions){const marker={__gmailDeletion:true,account:d.account,id:d.id,atHistoryId:d.atHistoryId};items.push({streamRef:GMAIL_MESSAGE_STREAM,raw:marker})}const checkpoint=changes.ok.historyId??dec.sinceHistoryId;return gmailPage(items,encodeCursor(dec.phase,dec.pageToken,dec.labelsDone,checkpoint,changes.ok.more?null:nowMs),false)}if(dec.phase==="messages"){let sinceHistoryId=dec.sinceHistoryId,historyCheckedAtMs=dec.historyCheckedAtMs;if(!dec.labelsDone){const labelsR=source.labels(grant);if(!isOk(labelsR))return labelsR;for(const l of labelsR.ok)items.push({streamRef:GMAIL_LABEL_STREAM,raw:l});if(sinceHistoryId===null){const profR2=source.getProfile(grant);if(!isOk(profR2))return profR2;if(profR2.ok.historyId!==void 0){sinceHistoryId=profR2.ok.historyId;historyCheckedAtMs=nowMs}}if(dec.sinceHistoryId!==null){const delR=source.messageDeletions(grant,dec.sinceHistoryId);if(!isOk(delR)){const e=delR.err;if(e.code!=="not_found")return delR}else{for(const d of delR.ok){const marker={__gmailDeletion:true,account:d.account,id:d.id,atHistoryId:d.atHistoryId};items.push({streamRef:GMAIL_MESSAGE_STREAM,raw:marker})}}}}const pageR2=source.messagesPage(grant,dec.pageToken);if(!isOk(pageR2))return pageR2;for(const m of pageR2.ok.messages)items.push({streamRef:GMAIL_MESSAGE_STREAM,raw:m});for(const a of pageR2.ok.attachments)items.push({streamRef:GMAIL_ATTACHMENT_STREAM,raw:a});const next2=pageR2.ok.nextPageToken;if(next2===null)return gmailPage(items,encodeCursor("threads",null,true,sinceHistoryId,historyCheckedAtMs),false);return gmailPage(items,encodeCursor("messages",next2,true,sinceHistoryId,historyCheckedAtMs),false)}if(dec.phase==="threads"){const pageR2=source.threadsPage(grant,dec.pageToken);if(!isOk(pageR2))return pageR2;for(const t of pageR2.ok.threads)items.push({streamRef:GMAIL_THREAD_STREAM,raw:t});const next2=pageR2.ok.nextPageToken;if(next2===null)return gmailPage(items,encodeCursor("drafts",null,true,dec.sinceHistoryId,dec.historyCheckedAtMs),false);return gmailPage(items,encodeCursor("threads",next2,true,dec.sinceHistoryId,dec.historyCheckedAtMs),false)}const pageR=source.draftsPage(grant,dec.pageToken);if(!isOk(pageR))return pageR;for(const d of pageR.ok.drafts)items.push({streamRef:GMAIL_DRAFT_STREAM,raw:d});const next=pageR.ok.nextPageToken;if(next!==null)return gmailPage(items,encodeCursor("drafts",next,true,dec.sinceHistoryId,dec.historyCheckedAtMs),false);if(dec.sinceHistoryId!==null)return gmailPage(items,encodeDoneCursor(dec.sinceHistoryId),true);const profR=source.getProfile(grant);const nextSince=isOk(profR)&&profR.ok.historyId!==void 0?profR.ok.historyId:null;return gmailPage(items,encodeDoneCursor(nextSince),true)},audit(grant,covered,request){return gmailAudit.audit(grant,covered,request)},normalize(item){if(item.streamRef===GMAIL_MESSAGE_STREAM){if(isMessageDeletionMarker(item.raw)){const raw2=item.raw;return{nk:{source:GMAIL_SOURCE,stream:GMAIL_MESSAGE_STREAM,sourceId:raw2.id,rev:raw2.atHistoryId},ts:GMAIL_LABEL_TS_UNKNOWN,tier:"api",kind:GMAIL_MESSAGE_DELETED_KIND,schemaVersion:1,mentions:[],body:`${raw2.id} \u2014 deleted`,payload:{id:raw2.id,deleted:true,atHistoryId:raw2.atHistoryId}}}const raw=item.raw;const headers=raw.payload?.headers??[];const refs=extractRefs(headers);const draft={nk:{source:GMAIL_SOURCE,stream:GMAIL_MESSAGE_STREAM,sourceId:raw.id,rev:raw.historyId},ts:internalDateToIso(raw.internalDate),tier:"api",kind:GMAIL_MESSAGE_KIND,schemaVersion:1,mentions:extractMentions(headers),body:messageBody(headers,raw.snippet??"",raw.payload,internalDateToIso(raw.internalDate)),payload:item.raw};if(refs.length>0)draft.refs=refs;return draft}if(item.streamRef===GMAIL_THREAD_STREAM){const raw=item.raw;return{nk:{source:GMAIL_SOURCE,stream:GMAIL_THREAD_STREAM,sourceId:raw.id,rev:raw.historyId},ts:threadTs(raw),tier:"api",kind:GMAIL_THREAD_KIND,schemaVersion:1,mentions:threadMentions(raw),body:threadBody(raw),payload:item.raw}}if(item.streamRef===GMAIL_DRAFT_STREAM){const raw=item.raw;const headers=raw.message.payload?.headers??[];const refs=extractRefs(headers);const draft={nk:{source:GMAIL_SOURCE,stream:GMAIL_DRAFT_STREAM,sourceId:raw.id,rev:raw.message.historyId},ts:internalDateToIso(raw.message.internalDate),tier:"api",kind:GMAIL_DRAFT_KIND,schemaVersion:1,mentions:extractMentions(headers),body:messageBody(headers,raw.message.snippet??"",raw.message.payload,internalDateToIso(raw.message.internalDate)),payload:item.raw};if(refs.length>0)draft.refs=refs;return draft}if(item.streamRef===GMAIL_ATTACHMENT_STREAM){const raw=item.raw;const blobs=attachmentBlobs(raw);const draft={nk:{source:GMAIL_SOURCE,stream:GMAIL_ATTACHMENT_STREAM,sourceId:`${encodeURIComponent(raw.messageId)}:${raw.partId}`},ts:internalDateToIso(raw.internalDate),tier:"api",kind:GMAIL_ATTACHMENT_KIND,schemaVersion:1,mentions:[],body:attachmentBody(raw),payload:item.raw};if(blobs!==void 0)draft.blobs=blobs;return draft}if(item.streamRef===GMAIL_LABEL_STREAM){const raw=item.raw;return{nk:{source:GMAIL_SOURCE,stream:GMAIL_LABEL_STREAM,sourceId:raw.id},ts:GMAIL_LABEL_TS_UNKNOWN,tier:"api",kind:GMAIL_LABEL_KIND,schemaVersion:1,mentions:[],body:raw.name,payload:item.raw}}throw new Error(`gmail normalize: undeclared streamRef '${item.streamRef}'`)}})}return{GMAIL_LABEL_TS_UNKNOWN,GMAIL_HISTORY_CATCHUP_MS,GMAIL_HISTORY_CATCHUP_MAX,GMAIL_AUDIT_LIST_PAGES,GMAIL_AUDIT_FETCH_MAX,GMAIL_AUDIT_CONFIRM_MAX,createGmailSelectedConnector,createGmailConnector}}
|
|
1
|
+
import{isOk,ok}from"./original-contracts.js";export function createConnectorModule(parts,manifest){const{auditFromListingChunksV1,boundPageItemsV1,connectorError,cursorCodecV1}=parts;const{GMAIL_ATTACHMENT_KIND,GMAIL_ATTACHMENT_STREAM,GMAIL_DRAFT_KIND,GMAIL_DRAFT_STREAM,GMAIL_LABEL_KIND,GMAIL_LABEL_STREAM,GMAIL_MANIFEST,GMAIL_MESSAGE_DELETED_KIND,GMAIL_MESSAGE_KIND,GMAIL_MESSAGE_STREAM,GMAIL_SOURCE,GMAIL_THREAD_KIND,GMAIL_THREAD_STREAM}=manifest;function isMessageDeletionMarker(raw){return raw!==null&&typeof raw==="object"&&raw.__gmailDeletion===true}const GMAIL_LABEL_TS_UNKNOWN="1970-01-01T00:00:00.000Z";const GMAIL_HISTORY_CATCHUP_MS=15*6e4;const GMAIL_HISTORY_CATCHUP_MAX=200;const GMAIL_THREAD_REFRESH_MAX=25;const GMAIL_TOUCHED_THREADS_MAX=400;const GMAIL_AUDIT_LIST_PAGES=10;const GMAIL_AUDIT_FETCH_MAX=100;const GMAIL_AUDIT_CONFIRM_MAX=200;function splitCoveredMessageId(covered){const at=covered.indexOf(":");if(at<=0||at===covered.length-1)return null;try{return{account:decodeURIComponent(covered.slice(0,at)),id:covered.slice(at+1)}}catch{return null}}const GMAIL_CURSOR=cursorCodecV1({source:GMAIL_SOURCE,version:1,toWire:s=>"done"in s?{done:true,sh:s.sh}:s.phase==="changes"?{ph:s.phase,sh:s.sinceHistoryId,l:s.labelsDone,t:s.threads,hd:s.historyDone}:{ph:s.phase,p:s.pageToken,l:s.labelsDone,sh:s.sinceHistoryId,...s.historyCheckedAtMs===null?{}:{ht:s.historyCheckedAtMs}},validate:wire=>{if(wire===null||typeof wire!=="object")return null;const o=wire;const sinceHistoryId=typeof o.sh==="string"?o.sh:null;const historyCheckedAtMs=typeof o.ht==="number"&&Number.isFinite(o.ht)?o.ht:null;if(o.done===true)return{done:true,sh:sinceHistoryId};if(o.ph==="changes"){const threads=o.t==="all"?"all":Array.isArray(o.t)&&o.t.every(id=>typeof id==="string"&&id!=="")?o.t:null;if(sinceHistoryId===null||threads===null)return null;return{phase:"changes",sinceHistoryId,labelsDone:o.l===true,threads,historyDone:o.hd===true}}if(o.ph==="threads"){const threadToken=typeof o.p==="string"||o.p!==null&&typeof o.p==="object"?o.p:null;return{phase:"threads",pageToken:threadToken,labelsDone:o.l===true,sinceHistoryId,historyCheckedAtMs}}const phase=o.ph==="drafts"?"drafts":"messages";return{phase,pageToken:typeof o.p==="string"?o.p:null,labelsDone:o.l===true,sinceHistoryId,historyCheckedAtMs}}});function decodeCursor(cursor){const d=GMAIL_CURSOR.decode(cursor);if(d===null)return{phase:"messages",pageToken:null,labelsDone:false,sinceHistoryId:null,historyCheckedAtMs:null};if("done"in d){return d.sh===null?{phase:"messages",pageToken:null,labelsDone:false,sinceHistoryId:null,historyCheckedAtMs:null}:{phase:"changes",sinceHistoryId:d.sh,labelsDone:false,threads:[],historyDone:false}}return d}function encodeChangesCursor(sinceHistoryId,labelsDone,threads,historyDone){return GMAIL_CURSOR.encode({phase:"changes",sinceHistoryId,labelsDone,threads,historyDone})}function encodeCursor(phase,pageToken,labelsDone,sinceHistoryId,historyCheckedAtMs=null){const state=phase==="threads"?{phase,pageToken,labelsDone,sinceHistoryId,historyCheckedAtMs}:{phase,pageToken,labelsDone,sinceHistoryId,historyCheckedAtMs};return GMAIL_CURSOR.encode(state)}function encodeDoneCursor(sinceHistoryId){return GMAIL_CURSOR.encode({done:true,sh:sinceHistoryId})}function gmailPage(items,next,exhausted){return"err"in next?next:ok({items,next:next.ok,exhausted})}function headerValue(headers,name){const lower=name.toLowerCase();for(const h of headers)if(h.name.toLowerCase()===lower)return h.value;return void 0}function parseAddress(token){const raw=token.trim();const angled=/<([^>]+)>/.exec(raw);if(angled){const email=angled[1].trim();return email!==""?{raw,email}:{raw}}if(/^[^\s@,]+@[^\s@,]+$/.test(raw))return{raw,email:raw};return{raw}}function parseAddressList(value){return value.split(",").map(t=>t.trim()).filter(t=>t!=="").map(parseAddress)}function mention(role,addr){return{role,raw:addr.raw,...addr.email!==void 0?{handle:{ns:"email",value:addr.email}}:{}}}function extractMentions(headers){const out=[];const from=headerValue(headers,"From");if(from!==void 0)for(const a of parseAddressList(from))out.push(mention("actor",a));const to=headerValue(headers,"To");if(to!==void 0)for(const a of parseAddressList(to))out.push(mention("participant",a));const cc=headerValue(headers,"Cc");if(cc!==void 0)for(const a of parseAddressList(cc))out.push(mention("participant",a));return out}function extractRefs(headers){const out=[];const messageId=headerValue(headers,"Message-ID");if(messageId!==void 0&&messageId.trim()!==""){out.push({rel:"rfc822-message-id",to:{ns:"rfc822-msgid",value:messageId.trim()}})}const inReplyTo=headerValue(headers,"In-Reply-To");if(inReplyTo!==void 0&&inReplyTo.trim()!==""){out.push({rel:"reply-to",to:{ns:"rfc822-msgid",value:inReplyTo.trim()}})}const references=headerValue(headers,"References");if(references!==void 0){for(const r of references.split(/\s+/).map(t=>t.trim()).filter(t=>t!=="")){out.push({rel:"references",to:{ns:"rfc822-msgid",value:r}})}}return out}function decodeB64Url(data){return Buffer.from(data,"base64url").toString("utf8")}function extractBodyText(payload){if(payload===void 0)return"";const out=[];const walk=p=>{const mime=(p.mimeType??"").toLowerCase();const isAttachment=(p.filename??"")!==""||(p.body?.attachmentId??"")!=="";if(!isAttachment&&mime.startsWith("text/plain")&&typeof p.body?.data==="string"&&p.body.data!==""){const t=decodeB64Url(p.body.data);if(t!=="")out.push(t)}for(const c of p.parts??[])walk(c)};walk(payload);return out.join("\n").trim()}function messageBody(headers,snippet,payload,receivedAt){const from=(headerValue(headers,"From")??"").trim();const subject=(headerValue(headers,"Subject")??"").trim();const text=extractBodyText(payload);const content=text!==""?text:snippet.trim();const when=receivedAt===GMAIL_LABEL_TS_UNKNOWN?"":receivedAt;return[when,from,subject,content].filter(s=>s!=="").join(" \u2014 ")}function internalDateToIso(internalDate){if(internalDate===void 0)return GMAIL_LABEL_TS_UNKNOWN;const ms=Number(internalDate);if(!Number.isFinite(ms))return GMAIL_LABEL_TS_UNKNOWN;return new Date(ms).toISOString()}function threadTs(t){let latest=Number.NEGATIVE_INFINITY;for(const m of t.messages??[]){if(m.internalDate===void 0)continue;const ms=Number(m.internalDate);if(Number.isFinite(ms)&&ms>latest)latest=ms}return latest>Number.NEGATIVE_INFINITY?new Date(latest).toISOString():GMAIL_LABEL_TS_UNKNOWN}function threadMentions(t){const seen=new Set;const out=[];for(const m of t.messages??[]){for(const x of extractMentions(m.payload?.headers??[])){const key=`${x.role}|${x.raw}|${x.handle?.value??""}`;if(seen.has(key))continue;seen.add(key);out.push(x)}}return out}function threadBody(t){const first=(t.messages??[])[0];const subject=first!==void 0?(headerValue(first.payload?.headers??[],"Subject")??"").trim():"";const snippet=(t.snippet??"").trim();const head=[subject,snippet].filter(s=>s!=="").join(" \u2014 ");if(head!=="")return head;const count=(t.messages??[]).length;return count>0?`thread ${t.id} (${count} messages)`:`thread ${t.id}`}function attachmentBody(a){const name=a.filename!==""?a.filename:"(unnamed attachment)";const detail=`${a.mimeType}, ${a.size} bytes`;return a.contentOmitted==="over-cap"?`${name} \u2014 ${detail} (content by-reference, over-cap)`:`${name} \u2014 ${detail}`}function attachmentBlobs(a){if(a.sha256===void 0)return void 0;const ref={sha256:a.sha256,bytes:a.size};if(a.mimeType!=="")ref.mime=a.mimeType;if(a.filename!=="")ref.name=a.filename;return[ref]}function createGmailSelectedConnector(source,opts={}){const connector=createGmailConnector(source,opts);const{audit:_accountAudit,auditAsync:_accountAuditAsync,...selected}=connector;return boundPageItemsV1({...selected,pull(grant,cursor){const dec=decodeCursor(cursor);const pageR=source.messagesPage(grant,dec.phase==="messages"?dec.pageToken:null);if(!isOk(pageR))return pageR;const items=pageR.ok.messages.map(message=>({streamRef:GMAIL_MESSAGE_STREAM,raw:message}));const next=pageR.ok.nextPageToken;return gmailPage(items,next===null?encodeDoneCursor(null):encodeCursor("messages",next,true,null),next===null)},discover(grant){const selected2=connector.discover(grant);if(!isOk(selected2))return selected2;return ok({...selected2.ok,streams:Object.fromEntries(Object.entries(selected2.ok.streams).map(([stream,census])=>[stream,{method:census.method,partialReasons:[...census.partialReasons??[],{reason:stream===GMAIL_MESSAGE_STREAM?"selected-gmail;full-corpus-not-measured":"not-read;selected-gmail;full-corpus-not-measured"}]}]))})}})}function createGmailConnector(source,opts={}){const now=opts.now??(()=>new Date().toISOString());function pullChanges(grant,dec,nowMs){const items=[];if(!dec.historyDone){if(!dec.labelsDone){const labelsR=source.labels(grant);if(!isOk(labelsR))return labelsR;for(const l of labelsR.ok)items.push({streamRef:GMAIL_LABEL_STREAM,raw:l})}const changes=source.messageChanges(grant,dec.sinceHistoryId,GMAIL_HISTORY_CATCHUP_MAX);if(!isOk(changes)){if(changes.err.code!=="not_found")return changes;return gmailPage(items,encodeCursor("messages",null,false,null),false)}for(const m of changes.ok.messages)items.push({streamRef:GMAIL_MESSAGE_STREAM,raw:m});for(const a of changes.ok.attachments)items.push({streamRef:GMAIL_ATTACHMENT_STREAM,raw:a});for(const d of changes.ok.deletions){const marker={__gmailDeletion:true,account:d.account,id:d.id,atHistoryId:d.atHistoryId};items.push({streamRef:GMAIL_MESSAGE_STREAM,raw:marker})}let threads=dec.threads;if(threads!=="all"){const touched=new Set(threads);for(const m of changes.ok.messages)if(typeof m.threadId==="string"&&m.threadId!=="")touched.add(m.threadId);threads=touched.size>GMAIL_TOUCHED_THREADS_MAX||source.threadsByIds===void 0?"all":[...touched]}const checkpoint=changes.ok.historyId??dec.sinceHistoryId;return gmailPage(items,encodeChangesCursor(checkpoint,true,threads,!changes.ok.more),false)}if(dec.threads==="all")return gmailPage(items,encodeCursor("threads",null,true,dec.sinceHistoryId,nowMs),false);const batch=dec.threads.slice(0,GMAIL_THREAD_REFRESH_MAX),rest=dec.threads.slice(batch.length);if(batch.length>0&&source.threadsByIds!==void 0){const threadsR=source.threadsByIds(grant,batch);if(!isOk(threadsR))return threadsR;for(const t of threadsR.ok.threads)items.push({streamRef:GMAIL_THREAD_STREAM,raw:t})}return gmailPage(items,rest.length>0?encodeChangesCursor(dec.sinceHistoryId,true,rest,true):encodeCursor("drafts",null,true,dec.sinceHistoryId,nowMs),false)}let deletionHistoryId=null;const gmailAudit=auditFromListingChunksV1({streams:[GMAIL_MESSAGE_STREAM],expectedScope:"account",repairCap:GMAIL_AUDIT_FETCH_MAX,evidenceCap:GMAIL_AUDIT_CONFIRM_MAX,now,beginCall:()=>{deletionHistoryId=null},listChunk:(grant,scope,pageToken)=>{const profile=source.getProfile(grant);if(!isOk(profile))return profile;const listed=source.listMessageIdsPage(grant,scope,pageToken,GMAIL_AUDIT_LIST_PAGES);if(!isOk(listed))return listed;const epoch=encodeURIComponent(profile.ok.emailAddress);return ok({scope:scope==="full"?"account":"recent",ids:{[GMAIL_MESSAGE_STREAM]:listed.ok.ids.map(id=>`${epoch}:${id}`)},next:listed.ok.nextPageToken})},fetchRepairs:(grant,_stream,ids)=>{const coveredOf=new Map;for(const id of ids){const parts2=splitCoveredMessageId(id);if(parts2!==null)coveredOf.set(parts2.id,id)}const hydrated=source.messagesByIds(grant,[...coveredOf.keys()]);if(!isOk(hydrated))return hydrated;return ok({items:[...hydrated.ok.messages.map(m=>({streamRef:GMAIL_MESSAGE_STREAM,raw:m})),...hydrated.ok.attachments.map(a=>({streamRef:GMAIL_ATTACHMENT_STREAM,raw:a}))],repaired:hydrated.ok.messages.map(m=>coveredOf.get(m.id)).filter(id=>id!==void 0)})},evidence:(grant,_stream,id)=>{const parts2=splitCoveredMessageId(id);if(parts2===null)return ok({byId:"unknown"});const answer=source.messageEvidence(grant,parts2.id);if(!isOk(answer))return answer;if(answer.ok==="present")return ok({byId:"present"});if(deletionHistoryId===null){const profile=source.getProfile(grant);if(!isOk(profile))return profile;if(profile.ok.historyId===void 0){return connectorError("internal","gmail getProfile: historyId missing \u2014 cannot order a deletion (REST-surface drift, FM-19)")}deletionHistoryId=profile.ok.historyId}return ok(answer.ok==="trashed"?{byId:"present",trashed:true}:{byId:"not-found"})},tombstone:(_stream,id)=>{const parts2=splitCoveredMessageId(id);const marker={__gmailDeletion:true,account:parts2.account,id:parts2.id,atHistoryId:deletionHistoryId};return{streamRef:GMAIL_MESSAGE_STREAM,raw:marker}}});return boundPageItemsV1({manifest:GMAIL_MANIFEST,discover(grant){const c=source.census(grant);if(!isOk(c))return c;const message={total:c.ok.messages.total,method:"census"};if(c.ok.messages.partialReasons!==void 0)message.partialReasons=c.ok.messages.partialReasons;return ok({asOf:now(),streams:{[GMAIL_MESSAGE_STREAM]:message,[GMAIL_LABEL_STREAM]:{total:c.ok.labels.total,method:"census"},[GMAIL_THREAD_STREAM]:{total:c.ok.threads.total,method:"census"},[GMAIL_DRAFT_STREAM]:{total:c.ok.drafts.total,method:"census"},[GMAIL_ATTACHMENT_STREAM]:{method:"pagination-exhaustion"}}})},pull(grant,cursor){const dec=decodeCursor(cursor);const items=[];const nowMs=Date.parse(now());if(dec.phase==="changes")return pullChanges(grant,dec,nowMs);if(dec.sinceHistoryId!==null&&(dec.historyCheckedAtMs===null||nowMs-dec.historyCheckedAtMs>=GMAIL_HISTORY_CATCHUP_MS)){const changes=source.messageChanges(grant,dec.sinceHistoryId,GMAIL_HISTORY_CATCHUP_MAX);if(!isOk(changes)){if(changes.err.code!=="not_found")return changes;return gmailPage(items,encodeCursor("messages",null,false,null),false)}for(const m of changes.ok.messages)items.push({streamRef:GMAIL_MESSAGE_STREAM,raw:m});for(const a of changes.ok.attachments)items.push({streamRef:GMAIL_ATTACHMENT_STREAM,raw:a});for(const d of changes.ok.deletions){const marker={__gmailDeletion:true,account:d.account,id:d.id,atHistoryId:d.atHistoryId};items.push({streamRef:GMAIL_MESSAGE_STREAM,raw:marker})}const checkpoint=changes.ok.historyId??dec.sinceHistoryId;return gmailPage(items,encodeCursor(dec.phase,dec.pageToken,dec.labelsDone,checkpoint,changes.ok.more?null:nowMs),false)}if(dec.phase==="messages"){let sinceHistoryId=dec.sinceHistoryId,historyCheckedAtMs=dec.historyCheckedAtMs;if(!dec.labelsDone){const labelsR=source.labels(grant);if(!isOk(labelsR))return labelsR;for(const l of labelsR.ok)items.push({streamRef:GMAIL_LABEL_STREAM,raw:l});if(sinceHistoryId===null){const profR2=source.getProfile(grant);if(!isOk(profR2))return profR2;if(profR2.ok.historyId!==void 0){sinceHistoryId=profR2.ok.historyId;historyCheckedAtMs=nowMs}}if(dec.sinceHistoryId!==null){const delR=source.messageDeletions(grant,dec.sinceHistoryId);if(!isOk(delR)){const e=delR.err;if(e.code!=="not_found")return delR}else{for(const d of delR.ok){const marker={__gmailDeletion:true,account:d.account,id:d.id,atHistoryId:d.atHistoryId};items.push({streamRef:GMAIL_MESSAGE_STREAM,raw:marker})}}}}const pageR2=source.messagesPage(grant,dec.pageToken);if(!isOk(pageR2))return pageR2;for(const m of pageR2.ok.messages)items.push({streamRef:GMAIL_MESSAGE_STREAM,raw:m});for(const a of pageR2.ok.attachments)items.push({streamRef:GMAIL_ATTACHMENT_STREAM,raw:a});const next2=pageR2.ok.nextPageToken;if(next2===null)return gmailPage(items,encodeCursor("threads",null,true,sinceHistoryId,historyCheckedAtMs),false);return gmailPage(items,encodeCursor("messages",next2,true,sinceHistoryId,historyCheckedAtMs),false)}if(dec.phase==="threads"){const pageR2=source.threadsPage(grant,dec.pageToken);if(!isOk(pageR2))return pageR2;for(const t of pageR2.ok.threads)items.push({streamRef:GMAIL_THREAD_STREAM,raw:t});const next2=pageR2.ok.nextPageToken;if(next2===null)return gmailPage(items,encodeCursor("drafts",null,true,dec.sinceHistoryId,dec.historyCheckedAtMs),false);return gmailPage(items,encodeCursor("threads",next2,true,dec.sinceHistoryId,dec.historyCheckedAtMs),false)}const pageR=source.draftsPage(grant,dec.pageToken);if(!isOk(pageR))return pageR;for(const d of pageR.ok.drafts)items.push({streamRef:GMAIL_DRAFT_STREAM,raw:d});const next=pageR.ok.nextPageToken;if(next!==null)return gmailPage(items,encodeCursor("drafts",next,true,dec.sinceHistoryId,dec.historyCheckedAtMs),false);if(dec.sinceHistoryId!==null)return gmailPage(items,encodeDoneCursor(dec.sinceHistoryId),true);const profR=source.getProfile(grant);const nextSince=isOk(profR)&&profR.ok.historyId!==void 0?profR.ok.historyId:null;return gmailPage(items,encodeDoneCursor(nextSince),true)},audit(grant,covered,request){return gmailAudit.audit(grant,covered,request)},normalize(item){if(item.streamRef===GMAIL_MESSAGE_STREAM){if(isMessageDeletionMarker(item.raw)){const raw2=item.raw;return{nk:{source:GMAIL_SOURCE,stream:GMAIL_MESSAGE_STREAM,sourceId:raw2.id,rev:raw2.atHistoryId},ts:GMAIL_LABEL_TS_UNKNOWN,tier:"api",kind:GMAIL_MESSAGE_DELETED_KIND,schemaVersion:1,mentions:[],body:`${raw2.id} \u2014 deleted`,payload:{id:raw2.id,deleted:true,atHistoryId:raw2.atHistoryId}}}const raw=item.raw;const headers=raw.payload?.headers??[];const refs=extractRefs(headers);const draft={nk:{source:GMAIL_SOURCE,stream:GMAIL_MESSAGE_STREAM,sourceId:raw.id,rev:raw.historyId},ts:internalDateToIso(raw.internalDate),tier:"api",kind:GMAIL_MESSAGE_KIND,schemaVersion:1,mentions:extractMentions(headers),body:messageBody(headers,raw.snippet??"",raw.payload,internalDateToIso(raw.internalDate)),payload:item.raw};if(refs.length>0)draft.refs=refs;return draft}if(item.streamRef===GMAIL_THREAD_STREAM){const raw=item.raw;return{nk:{source:GMAIL_SOURCE,stream:GMAIL_THREAD_STREAM,sourceId:raw.id,rev:raw.historyId},ts:threadTs(raw),tier:"api",kind:GMAIL_THREAD_KIND,schemaVersion:1,mentions:threadMentions(raw),body:threadBody(raw),payload:item.raw}}if(item.streamRef===GMAIL_DRAFT_STREAM){const raw=item.raw;const headers=raw.message.payload?.headers??[];const refs=extractRefs(headers);const draft={nk:{source:GMAIL_SOURCE,stream:GMAIL_DRAFT_STREAM,sourceId:raw.id,rev:raw.message.historyId},ts:internalDateToIso(raw.message.internalDate),tier:"api",kind:GMAIL_DRAFT_KIND,schemaVersion:1,mentions:extractMentions(headers),body:messageBody(headers,raw.message.snippet??"",raw.message.payload,internalDateToIso(raw.message.internalDate)),payload:item.raw};if(refs.length>0)draft.refs=refs;return draft}if(item.streamRef===GMAIL_ATTACHMENT_STREAM){const raw=item.raw;const blobs=attachmentBlobs(raw);const draft={nk:{source:GMAIL_SOURCE,stream:GMAIL_ATTACHMENT_STREAM,sourceId:`${encodeURIComponent(raw.messageId)}:${raw.partId}`},ts:internalDateToIso(raw.internalDate),tier:"api",kind:GMAIL_ATTACHMENT_KIND,schemaVersion:1,mentions:[],body:attachmentBody(raw),payload:item.raw};if(blobs!==void 0)draft.blobs=blobs;return draft}if(item.streamRef===GMAIL_LABEL_STREAM){const raw=item.raw;return{nk:{source:GMAIL_SOURCE,stream:GMAIL_LABEL_STREAM,sourceId:raw.id},ts:GMAIL_LABEL_TS_UNKNOWN,tier:"api",kind:GMAIL_LABEL_KIND,schemaVersion:1,mentions:[],body:raw.name,payload:item.raw}}throw new Error(`gmail normalize: undeclared streamRef '${item.streamRef}'`)}})}return{GMAIL_LABEL_TS_UNKNOWN,GMAIL_HISTORY_CATCHUP_MS,GMAIL_HISTORY_CATCHUP_MAX,GMAIL_AUDIT_LIST_PAGES,GMAIL_AUDIT_FETCH_MAX,GMAIL_AUDIT_CONFIRM_MAX,createGmailSelectedConnector,createGmailConnector}}
|
|
@@ -20,7 +20,8 @@
|
|
|
20
20
|
"@zortexhq/plugin-connector-framework": "0.1.0",
|
|
21
21
|
"@zortexhq/plugin-connector-core": "0.1.0",
|
|
22
22
|
"@zortexhq/plugin-google-auth": "0.1.0",
|
|
23
|
-
"@zortexhq/plugin-vault-sqlite": "0.1.0"
|
|
23
|
+
"@zortexhq/plugin-vault-sqlite": "0.1.0",
|
|
24
|
+
"@zortexhq/plugin-process-local": "0.1.0"
|
|
24
25
|
},
|
|
25
26
|
"zortex": {
|
|
26
27
|
"role": "plugin"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Original,canonicalJson}from"@zortexhq/plugin-connector-framework/api";import{record}from"./guards.js";import{createHash}from"node:crypto";export const COMPOUND_NAMES=["google-tasks.personal_list_create","google-tasks.personal_list_patch","google-tasks.personal_list_replace","google-tasks.personal_task_create","google-tasks.personal_task_reorder","google-tasks.personal_task_set_deleted"];export function createTasksCompounds(options){const fail=message=>Original.errResult({code:"failed_precondition",layer:"connector",retryability:"non-retryable",message});const conflict=message=>Original.errResult({code:"aborted",layer:"connector",retryability:"non-retryable",message});const digest=value=>createHash("sha256").update(canonicalJson(value)).digest("hex");function personal(row){return row["assignmentInfo"]===void 0&&row["hidden"]!==true&&row["deleted"]!==true}function flagRow(row){return row["assignmentInfo"]===void 0&&typeof row["id"]==="string"&&row["id"].length>0&&typeof row["title"]==="string"&&(row["status"]==="needsAction"||row["status"]==="completed")&&(row["deleted"]===void 0||typeof row["deleted"]==="boolean")&&(row["hidden"]===void 0||typeof row["hidden"]==="boolean")&&row["hidden"]!==true&&(row["parent"]===void 0||typeof row["parent"]==="string")}function flagTarget(row){return flagRow(row)&&row["parent"]===void 0}function flagCollection(items,target){return new Set(items.map(row=>row["id"])).size===items.length&&items.every(row=>row["id"]===target?flagTarget(row):flagRow(row)&&row["deleted"]!==true)}const strip=row=>{const result={};for(const[key,value]of Object.entries(row))if(!["etag","updated","kind","selfLink","webViewLink","position"].includes(key))result[key]=value;return result};const flagSemantic=row=>({...strip(row),deleted:row["deleted"]??false,position:row["position"]??null});const flagRows=items=>items.map(flagSemantic).sort((a,b)=>String(a["id"]).localeCompare(String(b["id"])));async function get(method,params,read){return options.invoke(method,{params},read)}async function rows(tasklist,read){const all=[],seen=new Set;let token;do{const answer=await get("tasks.tasks.list",{tasklist,maxResults:100,showAssigned:true,showHidden:true,showCompleted:true,showDeleted:true,...token?{pageToken:token}:{}},read);if(!("ok"in answer))return answer;all.push(...answer.ok.items);token=answer.ok.nextPageToken;if(token){if(seen.has(token))return fail("Task compound snapshot did not exhaust pagination");seen.add(token)}}while(token);return Original.ok(all)}const guard=(method,params,value)=>({method,params,hash:digest(value)});async function listRows(read){const all=[],seen=new Set;let token;do{const answer=await get("tasks.tasklists.list",{maxResults:100,...token?{pageToken:token}:{}},read);if(!("ok"in answer))return answer;all.push(...answer.ok.items);token=answer.ok.nextPageToken;if(token){if(seen.has(token))return fail("Compound list snapshot did not exhaust pagination");seen.add(token)}}while(token);return Original.ok(all)}async function mutate(accountId,method,call,guards,intent,read){if(!options.conditional)return fail("Tasks atomic conditional mutation custody port is unavailable");return options.conditional.compareAndMutate({accountId,method,call,guards,intent,...read?.signal?{signal:read.signal}:{}})}async function durableIntent(key,expected,phase){const stored=await receipt(key);if(!("ok"in stored))return stored;if(canonicalJson(stored.ok)!==canonicalJson(JSON.parse(JSON.stringify(expected))))return fail("Owned durable receipt differs from the correlated operation snapshot");return Original.ok({receiptKey:key,operation:stored.ok.operation,phase})}async function execute(operation,input,key,read){input=structuredClone(input);if(!COMPOUND_NAMES.includes(operation))return fail("Unknown personal Tasks compound");if(!options.conditional||!options.receipts)return fail("Personal Tasks compounds require atomic guard custody and durable private receipts");const accountId=options.account();if(!accountId)return fail("Personal Tasks compound requires verified OIDC identity");const existing=await options.receipts.get(key);if(!("ok"in existing))return existing;if(existing.ok)return fail("Compound receipt key already exists; query the existing receipt instead of replaying");if(!record(input)||!record(input.params)||Object.keys(input).some(name=>name!=="params"&&name!=="body"))return fail("Compound input requires only declared params/body; host intent authority is not an input field");const p=input.params,body=input.body;let before=null,beforeRows=[],method,call,guards=[];const listCreate=operation.endsWith("list_create"),taskCreate=operation.endsWith("task_create"),reorder=operation.endsWith("task_reorder"),deletedFlag=operation.endsWith("task_set_deleted");if(listCreate){if(Object.keys(p).length||!record(body)||Object.keys(body).some(name=>name!=="title")||typeof body["title"]!=="string"||!body["title"])return fail("Private list creation accepts only a nonempty title");const previous=await listRows(read);if(!("ok"in previous))return previous;beforeRows=previous.ok;guards.push(guard("tasks.tasklists.list.all",{},beforeRows));method="tasks.tasklists.insert";call={params:{},body}}else{if(typeof p["tasklist"]!=="string"||!p["tasklist"])return fail("Personal task operation requires a list identity");const list=p["tasklist"];const collection=await rows(list,read);if(!("ok"in collection))return collection;beforeRows=collection.ok;if(deletedFlag?!flagCollection(beforeRows,p["task"]):beforeRows.some(row=>!personal(row)))return fail("Personal compound excludes assigned, hidden or unrelated deleted resources");const listRead=await get("tasks.tasklists.get",{tasklist:list},read);if(!("ok"in listRead))return listRead;guards.push(guard("tasks.tasklists.get",{tasklist:list},listRead.ok.data),guard("tasks.tasks.list.all",{tasklist:list},beforeRows));if(taskCreate){if(Object.keys(p).some(name=>name!=="tasklist")||!record(body)||Object.keys(body).some(name=>!["title","notes","due"].includes(name))||typeof body["title"]!=="string"||!body["title"])return fail("Private task creation accepts title/notes/date only without assignment/hierarchy/status");method="tasks.tasks.insert";call={params:{tasklist:list},body}}else if(deletedFlag){if(Object.keys(p).some(name=>!["tasklist","task"].includes(name))||typeof p["task"]!=="string"||!record(body)||Object.keys(body).some(name=>name!=="deleted")||typeof body["deleted"]!=="boolean")return fail("Private deleted flag accepts only an explicit boolean and a selected task identity");const selected=beforeRows.find(row=>row["id"]===p["task"]);if(!selected||!flagTarget(selected)||beforeRows.some(row=>row["parent"]===p["task"]))return fail("Private deleted flag needs a complete unassigned visible top-level task without children");before=selected;guards.push(guard("tasks.tasks.get",{tasklist:list,task:p["task"]},selected));method="tasks.tasks.patch";call={params:{tasklist:list,task:p["task"]},body:{deleted:body["deleted"]}}}else if(reorder){if(Object.keys(p).some(name=>!["tasklist","task","previous"].includes(name))||typeof p["task"]!=="string"||input.body!==void 0)return fail("Private reorder is within one list, top-level and without a body");const selected=beforeRows.find(row=>row["id"]===p["task"]);if(!selected||selected["parent"]!==void 0)return fail("Private reorder requires a visible unassigned top-level task");if(p["previous"]!==void 0&&!beforeRows.some(row=>row["id"]===p["previous"]&&row["parent"]===void 0&&row["id"]!==p["task"]))return fail("Previous sibling is outside the private top-level snapshot");before=selected;guards.push(guard("tasks.tasks.get",{tasklist:list,task:p["task"]},selected));method="tasks.tasks.move";call={params:{tasklist:list,task:p["task"],...p["previous"]===void 0?{}:{previous:p["previous"]}}}}else{if(Object.keys(p).some(name=>name!=="tasklist")||!record(body)||Object.keys(body).some(name=>name!=="title")||typeof body["title"]!=="string")return fail("Private list edit accepts title only");before=listRead.ok.data;method=operation.endsWith("list_patch")?"tasks.tasklists.patch":"tasks.tasklists.update";call={params:{tasklist:list},body:{title:body["title"]}}}}const snapshot={operation,accountId,input:structuredClone(input),before,beforeRows,after:{},afterRows:[],forward:{method,resource:listCreate||operation.includes("list_")?"tasklists":"tasks",data:{},items:[],warnings:["Mutation has not produced an acknowledged result"],effect:"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}},stage:"snapshotted"};const pinned=await options.receipts.put(key,snapshot);if(!("ok"in pinned))return pinned;const intent=await durableIntent(key,snapshot,"forward");if(!("ok"in intent))return intent;const changed=await mutate(accountId,method,call,guards,intent.ok,read);if(!("ok"in changed))return changed;const after=changed.ok.data;if(!(deletedFlag?flagTarget(after)&&after["id"]===p["task"]:personal(after)))return conflict("Provider returned an assigned/non-personal or incomplete compound result; effect is unknown");if(record(body)&&Object.entries(body).some(([name,value])=>name==="due"?String(after[name]).slice(0,10)!==String(value).slice(0,10):canonicalJson(after[name]??null)!==canonicalJson(value)))return conflict("Provider response does not match the requested compound mutation");if((listCreate||taskCreate)&&(typeof after["id"]!=="string"||beforeRows.some(row=>row["id"]===after["id"])))return conflict("Created identity was already in the pre-mutation snapshot; inverse is unsafe");const listId=listCreate?after["id"]:p["tasklist"];if(typeof listId!=="string")return conflict("Provider returned no created list identity");const postRows=await rows(listId,read);if(!("ok"in postRows))return postRows;if(deletedFlag?!flagCollection(postRows.ok,p["task"]):postRows.ok.some(row=>!personal(row)))return conflict("Collection changed into a non-personal state; effect remains unknown");const targetMethod=listCreate||operation.includes("list_")?"tasks.tasklists.get":"tasks.tasks.get",targetParams=targetMethod==="tasks.tasklists.get"?{tasklist:listId}:{tasklist:listId,task:after["id"]};const observed=await get(targetMethod,targetParams,read);if(!("ok"in observed))return observed;if(digest(observed.ok.data)!==digest(after))return conflict("Compound target changed before the accepted readback; effect remains unknown");if(reorder){const ordered=items=>items.filter(row=>row["parent"]===void 0).sort((a,b)=>String(a["position"]).localeCompare(String(b["position"]))).map(row=>row["id"]);const expected=ordered(beforeRows).filter(id=>id!==p["task"]),index=p["previous"]===void 0?0:expected.indexOf(p["previous"])+1;expected.splice(index,0,p["task"]);if(canonicalJson(ordered(postRows.ok))!==canonicalJson(expected))return conflict("Provider did not establish the requested private sibling order")}if(deletedFlag){const expected=beforeRows.map(row=>row["id"]===p["task"]?{...row,deleted:body["deleted"]===true}:row);if(canonicalJson(flagRows(postRows.ok))!==canonicalJson(flagRows(expected)))return conflict("Deleted flag changed other semantic fields or collection membership; effect remains unknown")}const saved=await options.receipts.put(key,{...snapshot,after,afterRows:postRows.ok,forward:changed.ok,stage:"accepted"});if(!("ok"in saved))return saved;return Original.ok({receiptKey:key,effect:"unverified",operation})}async function receipt(key){if(!options.receipts)return fail("Task compound receipt store is unavailable");const found=await options.receipts.get(key);if(!("ok"in found))return found;if(!found.ok)return fail("Task compound receipt is missing; do not retry uncertain effects");if(found.ok.accountId!==options.account())return fail("Compound receipt belongs to another verified account");return Original.ok(found.ok)}async function recover(key,_read){const found=await receipt(key);if(!("ok"in found))return found;const r=found.ok;if(r.stage==="accepted")return Original.ok({state:"accepted",receiptKey:key});return Original.ok({state:"unknown",receiptKey:key,reason:r.stage==="snapshotted"?"Provider effect was not acknowledged with a correlated durable witness; identical current state cannot authorize recovery or compensation":"Inverse may have executed; no forward replay or repeated inverse is authorized"})}async function compensate(key,read){const found=await receipt(key);if(!("ok"in found))return found;const r=found.ok;if(r.stage!=="accepted"||r.compensated)return fail("Compound is not in an accepted state for inverse; query uncertain execution instead of retrying");const listCreate=r.operation.endsWith("list_create"),taskCreate=r.operation.endsWith("task_create"),reorder=r.operation.endsWith("task_reorder"),deletedFlag=r.operation.endsWith("task_set_deleted"),list=String(listCreate?r.after["id"]:r.input.params["tasklist"]);const currentRows=await rows(list,read);if(!("ok"in currentRows))return currentRows;if(digest(currentRows.ok)!==digest(r.afterRows)||(deletedFlag?!flagCollection(currentRows.ok,r.after["id"]):currentRows.ok.some(row=>!personal(row))))return conflict("Concurrent collection change prevents compensation");const getter=listCreate||!taskCreate&&!reorder&&!deletedFlag?"tasks.tasklists.get":"tasks.tasks.get",params=getter==="tasks.tasklists.get"?{tasklist:list}:{tasklist:list,task:r.after["id"]};const current=await get(getter,params,read);if(!("ok"in current))return current;if(digest(current.ok.data)!==digest(r.after))return conflict("Concurrent target change prevents compensation");const guards=[guard(getter,params,current.ok.data),guard("tasks.tasks.list.all",{tasklist:list},currentRows.ok)];let method,call;if(listCreate){if(currentRows.ok.length)return conflict("New private list is no longer empty");method="tasks.tasklists.delete";call={params:{tasklist:list}}}else if(taskCreate){if(currentRows.ok.some(row=>row["parent"]===r.after["id"]))return conflict("New private task has children; inverse refused");method="tasks.tasks.delete";call={params:{tasklist:list,task:r.after["id"]}}}else if(reorder){const sorted=r.beforeRows.filter(row=>row["parent"]===void 0).sort((a,b)=>String(a["position"]).localeCompare(String(b["position"]))),index=sorted.findIndex(row=>row["id"]===r.before["id"]);const previous=index>0?sorted[index-1]["id"]:void 0;method="tasks.tasks.move";call={params:{tasklist:list,task:r.after["id"],...previous===void 0?{}:{previous}}}}else if(deletedFlag){method="tasks.tasks.patch";call={params:{tasklist:list,task:r.after["id"]},body:{deleted:r.before["deleted"]===true}}}else{method="tasks.tasklists.patch";call={params:{tasklist:list},body:{title:r.before["title"]}}}const inverseSnapshot={...r,stage:"inverse-executing"},executing=await options.receipts.put(key,inverseSnapshot);if(!("ok"in executing))return executing;const intent=await durableIntent(key,inverseSnapshot,"inverse");if(!("ok"in intent))return intent;const inverse=await mutate(r.accountId,method,call,guards,intent.ok,read);if(!("ok"in inverse))return inverse;let restored=false;if(listCreate||taskCreate){const absent=await get(getter,params,read);restored="err"in absent&&absent.err.code==="not_found"}else{const after=await get(getter,params,read);if("ok"in after)restored=deletedFlag?flagTarget(after.ok.data)&&after.ok.data["id"]===r.before["id"]&&canonicalJson(flagSemantic(after.ok.data))===canonicalJson(flagSemantic(r.before)):JSON.stringify(strip(after.ok.data))===JSON.stringify(strip(r.before));if(deletedFlag&&restored){const post=await rows(list,read);if(!("ok"in post))return post;restored=flagCollection(post.ok,r.before["id"])&&canonicalJson(flagRows(post.ok))===canonicalJson(flagRows(r.beforeRows))}if(reorder&&restored){const post=await rows(list,read);if(!("ok"in post))return post;const order=items=>items.filter(row=>row["parent"]===void 0).sort((a,b)=>String(a["position"]).localeCompare(String(b["position"]))).map(row=>row["id"]);restored=JSON.stringify(order(post.ok))===JSON.stringify(order(r.beforeRows))}}if(!restored)return conflict("Inverse response did not prove semantic restoration");const saved=await options.receipts.put(key,{...r,compensated:true,stage:"compensated"});if(!("ok"in saved))return saved;return Original.ok({restored:true,receiptKey:key,metadataClocksRestored:false})}async function probe(key){const found=await receipt(key);if(!("ok"in found)||found.ok.stage!=="accepted")return Original.ok({reading:"unknown"});const r=found.ok,list=String(r.operation.endsWith("list_create")?r.after["id"]:r.input.params["tasklist"]),getter=r.operation.includes("task_")?"tasks.tasks.get":"tasks.tasklists.get",params=getter==="tasks.tasks.get"?{tasklist:list,task:r.after["id"]}:{tasklist:list};const current=await get(getter,params);return Original.ok({reading:"ok"in current&&digest(current.ok.data)===digest(r.after)?"effected":"unknown"})}return{execute,compensate,probe,recover}}
|
|
1
|
+
import{actionNotApplied}from"@zortexhq/plugin-connector-core/api";import{Original,canonicalJson}from"@zortexhq/plugin-connector-framework/api";import{record}from"./guards.js";import{createHash}from"node:crypto";export const COMPOUND_NAMES=["google-tasks.personal_list_create","google-tasks.personal_list_patch","google-tasks.personal_list_replace","google-tasks.personal_task_create","google-tasks.personal_task_reorder","google-tasks.personal_task_set_deleted"];export function createTasksCompounds(options){const fail=message=>Original.errResult({code:"failed_precondition",layer:"connector",retryability:"non-retryable",message});const conflict=message=>Original.errResult({code:"aborted",layer:"connector",retryability:"non-retryable",message});const digest=value=>createHash("sha256").update(canonicalJson(value)).digest("hex");function personal(row){return row["assignmentInfo"]===void 0&&row["hidden"]!==true&&row["deleted"]!==true}function flagRow(row){return row["assignmentInfo"]===void 0&&typeof row["id"]==="string"&&row["id"].length>0&&typeof row["title"]==="string"&&(row["status"]==="needsAction"||row["status"]==="completed")&&(row["deleted"]===void 0||typeof row["deleted"]==="boolean")&&(row["hidden"]===void 0||typeof row["hidden"]==="boolean")&&row["hidden"]!==true&&(row["parent"]===void 0||typeof row["parent"]==="string")}function flagTarget(row){return flagRow(row)&&row["parent"]===void 0}function flagCollection(items,target){return new Set(items.map(row=>row["id"])).size===items.length&&items.every(row=>row["id"]===target?flagTarget(row):flagRow(row)&&row["deleted"]!==true)}const strip=row=>{const result={};for(const[key,value]of Object.entries(row))if(!["etag","updated","kind","selfLink","webViewLink","position"].includes(key))result[key]=value;return result};const flagSemantic=row=>({...strip(row),deleted:row["deleted"]??false,position:row["position"]??null});const flagRows=items=>items.map(flagSemantic).sort((a,b)=>String(a["id"]).localeCompare(String(b["id"])));async function get(method,params,read){return options.invoke(method,{params},read)}async function rows(tasklist,read){const all=[],seen=new Set;let token;do{const answer=await get("tasks.tasks.list",{tasklist,maxResults:100,showAssigned:true,showHidden:true,showCompleted:true,showDeleted:true,...token?{pageToken:token}:{}},read);if(!("ok"in answer))return answer;all.push(...answer.ok.items);token=answer.ok.nextPageToken;if(token){if(seen.has(token))return fail("Task compound snapshot did not exhaust pagination");seen.add(token)}}while(token);return Original.ok(all)}const guard=(method,params,value)=>({method,params,hash:digest(value)});async function listRows(read){const all=[],seen=new Set;let token;do{const answer=await get("tasks.tasklists.list",{maxResults:100,...token?{pageToken:token}:{}},read);if(!("ok"in answer))return answer;all.push(...answer.ok.items);token=answer.ok.nextPageToken;if(token){if(seen.has(token))return fail("Compound list snapshot did not exhaust pagination");seen.add(token)}}while(token);return Original.ok(all)}async function mutate(accountId,method,call,guards,intent,read){if(!options.conditional)return fail("Tasks atomic conditional mutation custody port is unavailable");return options.conditional.compareAndMutate({accountId,method,call,guards,intent,...read?.signal?{signal:read.signal}:{}})}async function durableIntent(key,expected,phase){const stored=await receipt(key);if(!("ok"in stored))return stored;if(canonicalJson(stored.ok)!==canonicalJson(JSON.parse(JSON.stringify(expected))))return fail("Owned durable receipt differs from the correlated operation snapshot");return Original.ok({receiptKey:key,operation:stored.ok.operation,phase})}async function executeInner(operation,input,key,read,dispatch){input=structuredClone(input);if(!COMPOUND_NAMES.includes(operation))return fail("Unknown personal Tasks compound");if(!options.conditional||!options.receipts)return fail("Personal Tasks compounds require atomic guard custody and durable private receipts");const accountId=options.account();if(!accountId)return fail("Personal Tasks compound requires verified OIDC identity");const existing=await options.receipts.get(key);if(!("ok"in existing))return existing;if(existing.ok)return fail("Compound receipt key already exists; query the existing receipt instead of replaying");if(!record(input)||!record(input.params)||Object.keys(input).some(name=>name!=="params"&&name!=="body"))return fail("Compound input requires only declared params/body; host intent authority is not an input field");const p=input.params,body=input.body;let before=null,beforeRows=[],method,call,guards=[];const listCreate=operation.endsWith("list_create"),taskCreate=operation.endsWith("task_create"),reorder=operation.endsWith("task_reorder"),deletedFlag=operation.endsWith("task_set_deleted");if(listCreate){if(Object.keys(p).length||!record(body)||Object.keys(body).some(name=>name!=="title")||typeof body["title"]!=="string"||!body["title"])return fail("Private list creation accepts only a nonempty title");const previous=await listRows(read);if(!("ok"in previous))return previous;beforeRows=previous.ok;guards.push(guard("tasks.tasklists.list.all",{},beforeRows));method="tasks.tasklists.insert";call={params:{},body}}else{if(typeof p["tasklist"]!=="string"||!p["tasklist"])return fail("Personal task operation requires a list identity");const list=p["tasklist"];const collection=await rows(list,read);if(!("ok"in collection))return collection;beforeRows=collection.ok;if(deletedFlag?!flagCollection(beforeRows,p["task"]):beforeRows.some(row=>!personal(row)))return fail("Personal compound excludes assigned, hidden or unrelated deleted resources");const listRead=await get("tasks.tasklists.get",{tasklist:list},read);if(!("ok"in listRead))return listRead;guards.push(guard("tasks.tasklists.get",{tasklist:list},listRead.ok.data),guard("tasks.tasks.list.all",{tasklist:list},beforeRows));if(taskCreate){if(Object.keys(p).some(name=>name!=="tasklist")||!record(body)||Object.keys(body).some(name=>!["title","notes","due"].includes(name))||typeof body["title"]!=="string"||!body["title"])return fail("Private task creation accepts title/notes/date only without assignment/hierarchy/status");method="tasks.tasks.insert";call={params:{tasklist:list},body}}else if(deletedFlag){if(Object.keys(p).some(name=>!["tasklist","task"].includes(name))||typeof p["task"]!=="string"||!record(body)||Object.keys(body).some(name=>name!=="deleted")||typeof body["deleted"]!=="boolean")return fail("Private deleted flag accepts only an explicit boolean and a selected task identity");const selected=beforeRows.find(row=>row["id"]===p["task"]);if(!selected||!flagTarget(selected)||beforeRows.some(row=>row["parent"]===p["task"]))return fail("Private deleted flag needs a complete unassigned visible top-level task without children");before=selected;guards.push(guard("tasks.tasks.get",{tasklist:list,task:p["task"]},selected));method="tasks.tasks.patch";call={params:{tasklist:list,task:p["task"]},body:{deleted:body["deleted"]}}}else if(reorder){if(Object.keys(p).some(name=>!["tasklist","task","previous"].includes(name))||typeof p["task"]!=="string"||input.body!==void 0)return fail("Private reorder is within one list, top-level and without a body");const selected=beforeRows.find(row=>row["id"]===p["task"]);if(!selected||selected["parent"]!==void 0)return fail("Private reorder requires a visible unassigned top-level task");if(p["previous"]!==void 0&&!beforeRows.some(row=>row["id"]===p["previous"]&&row["parent"]===void 0&&row["id"]!==p["task"]))return fail("Previous sibling is outside the private top-level snapshot");before=selected;guards.push(guard("tasks.tasks.get",{tasklist:list,task:p["task"]},selected));method="tasks.tasks.move";call={params:{tasklist:list,task:p["task"],...p["previous"]===void 0?{}:{previous:p["previous"]}}}}else{if(Object.keys(p).some(name=>name!=="tasklist")||!record(body)||Object.keys(body).some(name=>name!=="title")||typeof body["title"]!=="string")return fail("Private list edit accepts title only");before=listRead.ok.data;method=operation.endsWith("list_patch")?"tasks.tasklists.patch":"tasks.tasklists.update";call={params:{tasklist:list},body:{title:body["title"]}}}}const snapshot={operation,accountId,input:structuredClone(input),before,beforeRows,after:{},afterRows:[],forward:{method,resource:listCreate||operation.includes("list_")?"tasklists":"tasks",data:{},items:[],warnings:["Mutation has not produced an acknowledged result"],effect:"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}},stage:"snapshotted"};const pinned=await options.receipts.put(key,snapshot);if(!("ok"in pinned))return pinned;const intent=await durableIntent(key,snapshot,"forward");if(!("ok"in intent))return intent;dispatch();const changed=await mutate(accountId,method,call,guards,intent.ok,read);if(!("ok"in changed))return changed;const after=changed.ok.data;if(!(deletedFlag?flagTarget(after)&&after["id"]===p["task"]:personal(after)))return conflict("Provider returned an assigned/non-personal or incomplete compound result; effect is unknown");if(record(body)&&Object.entries(body).some(([name,value])=>name==="due"?String(after[name]).slice(0,10)!==String(value).slice(0,10):canonicalJson(after[name]??null)!==canonicalJson(value)))return conflict("Provider response does not match the requested compound mutation");if((listCreate||taskCreate)&&(typeof after["id"]!=="string"||beforeRows.some(row=>row["id"]===after["id"])))return conflict("Created identity was already in the pre-mutation snapshot; inverse is unsafe");const listId=listCreate?after["id"]:p["tasklist"];if(typeof listId!=="string")return conflict("Provider returned no created list identity");const postRows=await rows(listId,read);if(!("ok"in postRows))return postRows;if(deletedFlag?!flagCollection(postRows.ok,p["task"]):postRows.ok.some(row=>!personal(row)))return conflict("Collection changed into a non-personal state; effect remains unknown");const targetMethod=listCreate||operation.includes("list_")?"tasks.tasklists.get":"tasks.tasks.get",targetParams=targetMethod==="tasks.tasklists.get"?{tasklist:listId}:{tasklist:listId,task:after["id"]};const observed=await get(targetMethod,targetParams,read);if(!("ok"in observed))return observed;if(digest(observed.ok.data)!==digest(after))return conflict("Compound target changed before the accepted readback; effect remains unknown");if(reorder){const ordered=items=>items.filter(row=>row["parent"]===void 0).sort((a,b)=>String(a["position"]).localeCompare(String(b["position"]))).map(row=>row["id"]);const expected=ordered(beforeRows).filter(id=>id!==p["task"]),index=p["previous"]===void 0?0:expected.indexOf(p["previous"])+1;expected.splice(index,0,p["task"]);if(canonicalJson(ordered(postRows.ok))!==canonicalJson(expected))return conflict("Provider did not establish the requested private sibling order")}if(deletedFlag){const expected=beforeRows.map(row=>row["id"]===p["task"]?{...row,deleted:body["deleted"]===true}:row);if(canonicalJson(flagRows(postRows.ok))!==canonicalJson(flagRows(expected)))return conflict("Deleted flag changed other semantic fields or collection membership; effect remains unknown")}const saved=await options.receipts.put(key,{...snapshot,after,afterRows:postRows.ok,forward:changed.ok,stage:"accepted"});if(!("ok"in saved))return saved;return Original.ok({receiptKey:key,effect:"unverified",operation})}async function execute(operation,input,key,read){let dispatched=false;const result=await executeInner(operation,input,key,read,()=>{dispatched=true}).catch(()=>fail("Personal Tasks compound did not complete."));if("err"in result&&dispatched){const unknown={...result,effectDisposition:"unknown"};return unknown}return dispatched?result:actionNotApplied(result)}async function receipt(key){if(!options.receipts)return fail("Task compound receipt store is unavailable");const found=await options.receipts.get(key);if(!("ok"in found))return found;if(!found.ok)return fail("Task compound receipt is missing; do not retry uncertain effects");if(found.ok.accountId!==options.account())return fail("Compound receipt belongs to another verified account");return Original.ok(found.ok)}async function recover(key,_read){const found=await receipt(key);if(!("ok"in found))return found;const r=found.ok;if(r.stage==="accepted")return Original.ok({state:"accepted",receiptKey:key});return Original.ok({state:"unknown",receiptKey:key,reason:r.stage==="snapshotted"?"Provider effect was not acknowledged with a correlated durable witness; identical current state cannot authorize recovery or compensation":"Inverse may have executed; no forward replay or repeated inverse is authorized"})}async function compensate(key,read){const found=await receipt(key);if(!("ok"in found))return found;const r=found.ok;if(r.stage!=="accepted"||r.compensated)return fail("Compound is not in an accepted state for inverse; query uncertain execution instead of retrying");const listCreate=r.operation.endsWith("list_create"),taskCreate=r.operation.endsWith("task_create"),reorder=r.operation.endsWith("task_reorder"),deletedFlag=r.operation.endsWith("task_set_deleted"),list=String(listCreate?r.after["id"]:r.input.params["tasklist"]);const currentRows=await rows(list,read);if(!("ok"in currentRows))return currentRows;if(digest(currentRows.ok)!==digest(r.afterRows)||(deletedFlag?!flagCollection(currentRows.ok,r.after["id"]):currentRows.ok.some(row=>!personal(row))))return conflict("Concurrent collection change prevents compensation");const getter=listCreate||!taskCreate&&!reorder&&!deletedFlag?"tasks.tasklists.get":"tasks.tasks.get",params=getter==="tasks.tasklists.get"?{tasklist:list}:{tasklist:list,task:r.after["id"]};const current=await get(getter,params,read);if(!("ok"in current))return current;if(digest(current.ok.data)!==digest(r.after))return conflict("Concurrent target change prevents compensation");const guards=[guard(getter,params,current.ok.data),guard("tasks.tasks.list.all",{tasklist:list},currentRows.ok)];let method,call;if(listCreate){if(currentRows.ok.length)return conflict("New private list is no longer empty");method="tasks.tasklists.delete";call={params:{tasklist:list}}}else if(taskCreate){if(currentRows.ok.some(row=>row["parent"]===r.after["id"]))return conflict("New private task has children; inverse refused");method="tasks.tasks.delete";call={params:{tasklist:list,task:r.after["id"]}}}else if(reorder){const sorted=r.beforeRows.filter(row=>row["parent"]===void 0).sort((a,b)=>String(a["position"]).localeCompare(String(b["position"]))),index=sorted.findIndex(row=>row["id"]===r.before["id"]);const previous=index>0?sorted[index-1]["id"]:void 0;method="tasks.tasks.move";call={params:{tasklist:list,task:r.after["id"],...previous===void 0?{}:{previous}}}}else if(deletedFlag){method="tasks.tasks.patch";call={params:{tasklist:list,task:r.after["id"]},body:{deleted:r.before["deleted"]===true}}}else{method="tasks.tasklists.patch";call={params:{tasklist:list},body:{title:r.before["title"]}}}const inverseSnapshot={...r,stage:"inverse-executing"},executing=await options.receipts.put(key,inverseSnapshot);if(!("ok"in executing))return executing;const intent=await durableIntent(key,inverseSnapshot,"inverse");if(!("ok"in intent))return intent;const inverse=await mutate(r.accountId,method,call,guards,intent.ok,read);if(!("ok"in inverse))return inverse;let restored=false;if(listCreate||taskCreate){const absent=await get(getter,params,read);restored="err"in absent&&absent.err.code==="not_found"}else{const after=await get(getter,params,read);if("ok"in after)restored=deletedFlag?flagTarget(after.ok.data)&&after.ok.data["id"]===r.before["id"]&&canonicalJson(flagSemantic(after.ok.data))===canonicalJson(flagSemantic(r.before)):JSON.stringify(strip(after.ok.data))===JSON.stringify(strip(r.before));if(deletedFlag&&restored){const post=await rows(list,read);if(!("ok"in post))return post;restored=flagCollection(post.ok,r.before["id"])&&canonicalJson(flagRows(post.ok))===canonicalJson(flagRows(r.beforeRows))}if(reorder&&restored){const post=await rows(list,read);if(!("ok"in post))return post;const order=items=>items.filter(row=>row["parent"]===void 0).sort((a,b)=>String(a["position"]).localeCompare(String(b["position"]))).map(row=>row["id"]);restored=JSON.stringify(order(post.ok))===JSON.stringify(order(r.beforeRows))}}if(!restored)return conflict("Inverse response did not prove semantic restoration");const saved=await options.receipts.put(key,{...r,compensated:true,stage:"compensated"});if(!("ok"in saved))return saved;return Original.ok({restored:true,receiptKey:key,metadataClocksRestored:false})}async function probe(key){const found=await receipt(key);if(!("ok"in found)||found.ok.stage!=="accepted")return Original.ok({reading:"unknown"});const r=found.ok,list=String(r.operation.endsWith("list_create")?r.after["id"]:r.input.params["tasklist"]),getter=r.operation.includes("task_")?"tasks.tasks.get":"tasks.tasklists.get",params=getter==="tasks.tasks.get"?{tasklist:list,task:r.after["id"]}:{tasklist:list};const current=await get(getter,params);return Original.ok({reading:"ok"in current&&digest(current.ok.data)===digest(r.after)?"effected":"unknown"})}return{execute,compensate,probe,recover}}
|
|
@@ -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",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}
|
|
1
|
+
import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{actionOutcome,actionNotApplied,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 actionOutcome(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})),raw.status===400?"not_applied":"unknown")}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={},dispatched=()=>{}){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};dispatched();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(actionNotApplied(fail("resource_exhausted","Tasks source has reached its active call bound")));let dispatched=false;const task=invokeInner(id,call,options,()=>{dispatched=true}).then(result=>dispatched?actionOutcome(result,"unknown"):actionNotApplied(result),()=>actionOutcome(fail(options.signal?.aborted?"aborted":"unavailable","Tasks request did not complete."),dispatched?"unknown":"not_applied")).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 actionNotApplied(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
|
+
import{createHash}from"node:crypto";import{canonicalJson}from"@zortexhq/plugin-connector-framework/api";const secretKey=/^(?:access_?token|refresh_?token|id_?token|client_?secret|api_?key|password|passwd|authorization|cookie|set-cookie|private_?key|credential(?:s)?)$/i;export function contentActionAllowed(name){return!/(?:^|[_.-])(?:auth|oauth|login|logout|token|tokens|secret|secrets|password|credential|credentials|cookie|cookies|environment|env|config|configuration|settings|session|sessions)(?:$|[_.-])/i.test(name.replace(/([a-z])([A-Z])/g,"$1_$2"))}function inspect(value,depth=0){if(depth>64)throw Error("Content response nesting exceeds the preservation bound.");if(typeof value==="string"){if(/-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----/.test(value))throw Error("Credential material is not content.");if(depth<64&&/^[\s]*[\[{]/.test(value)){let parsed;try{parsed=JSON.parse(value)}catch{return}inspect(parsed,depth+1)}}else if(value&&typeof value==="object"){for(const[key,item]of Object.entries(value)){if(secretKey.test(key))throw Error("Credential fields are not content.");inspect(item,depth+1)}}}export function actionContentRecord(source,action,response){if(!contentActionAllowed(action.name.slice(source.length+1)))throw Error("This Action reads configuration or authorization state.");if(response.content!==void 0&&(!Array.isArray(response.content)||response.content.some(block=>!block||typeof block!=="object"||!["text","resource"].includes(block.type)||block.type==="resource"&&(typeof block.resource?.text!=="string"||block.resource?.blob!==void 0))))throw Error("Non-text MCP content needs a format-specific mapper.");const data=response.structured;if(data&&typeof data==="object"&&!Array.isArray(data)){const row=data;if(row.success===false||row.error||Array.isArray(row.errors)&&row.errors.length)throw Error("Provider returned a failed content response.")}inspect(response);const payload=JSON.parse(canonicalJson(response)),scope=createHash("sha256").update(canonicalJson(action.params)).digest("hex");const embedded=Array.isArray(response.content)?response.content.filter(block=>block.type==="resource").map(block=>block.resource.text):[];return{source,sourceId:action.name+":"+scope,kind:"mcp-response",body:[response.text,...embedded,data===void 0?"":canonicalJson(data)].filter(Boolean).join("\n"),fields:{title:action.name,action:action.name,response:payload,scope:"acquired-response"}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync}from"node:child_process";import{readFile,writeFile}from"node:fs/promises";const[inputPath,outputPath]=process.argv.slice(2);if(!inputPath||!outputPath)process.exit(2);let result;try{const script=await readFile(inputPath,"utf8");const child=spawnSync("/usr/bin/osascript",["-l","JavaScript","-e",script],{encoding:"utf8",timeout:
|
|
1
|
+
import{NATIVE_CHILD_TIMEOUT,nativeProcessError}from"./apple-native-process.mjs";import{spawnSync}from"node:child_process";import{readFile,writeFile}from"node:fs/promises";const[inputPath,outputPath]=process.argv.slice(2);if(!inputPath||!outputPath)process.exit(2);let result;try{const script=await readFile(inputPath,"utf8");const child=spawnSync("/usr/bin/osascript",["-l","JavaScript","-e",script],{encoding:"utf8",timeout:NATIVE_CHILD_TIMEOUT,maxBuffer:1048576});result={code:child.status??1,stdout:child.stdout??"",stderr:nativeProcessError(child)}}catch(error){result={code:1,stdout:"",stderr:String(error)}}await writeFile(outputPath,JSON.stringify(result),{encoding:"utf8",mode:384});
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import{execFile}from"node:child_process";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{fileURLToPath}from"node:url";import{promisify}from"node:util";import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";import{appleMusicTools}from"./apple-music-tools.js";const runFile=promisify(execFile);const prelude=`const app=Application('Music');
|
|
1
|
+
import{NATIVE_HELPER_TIMEOUT}from"./apple-native-process.mjs";import{execFile}from"node:child_process";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{fileURLToPath}from"node:url";import{promisify}from"node:util";import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";import{appleMusicTools}from"./apple-music-tools.js";const runFile=promisify(execFile);const prelude=`const app=Application('Music');
|
|
2
2
|
app.name();
|
|
3
3
|
const safe=(f,d=null)=>{try{return f()}catch(_){return d}};
|
|
4
4
|
const iso=d=>d&&d.toISOString?d.toISOString():null;
|
|
5
5
|
const libraries=()=>app.libraryPlaylists();
|
|
6
6
|
const library=()=>{const xs=libraries();if(!xs.length)throw Error('Music library not found');return xs[0]};
|
|
7
|
-
const playlistRow=p=>({id:safe(()=>p.
|
|
8
|
-
const trackRow=t=>({id:safe(()=>t.
|
|
7
|
+
const playlistRow=p=>({id:safe(()=>p.persistentID()),name:safe(()=>p.name(),''),kind:String(safe(()=>p.specialKind(),'none')),duration:Number(safe(()=>p.duration(),0)),trackCount:Number(safe(()=>p.tracks().length,0)),visible:Boolean(safe(()=>p.visible(),true))});
|
|
8
|
+
const trackRow=t=>({id:safe(()=>t.persistentID()),databaseId:Number(safe(()=>t.databaseID(),0)),name:safe(()=>t.name(),''),artist:safe(()=>t.artist(),''),album:safe(()=>t.album(),''),albumArtist:safe(()=>t.albumArtist(),''),composer:safe(()=>t.composer(),''),genre:safe(()=>t.genre(),''),duration:Number(safe(()=>t.duration(),0)),dateAdded:iso(safe(()=>t.dateAdded())),playedDate:iso(safe(()=>t.playedDate())),playedCount:Number(safe(()=>t.playedCount(),0)),rating:Number(safe(()=>t.rating(),0)),favorited:Boolean(safe(()=>t.favorited(),false)),cloudStatus:String(safe(()=>t.cloudStatus(),'unknown'))});
|
|
9
9
|
const allPlaylists=()=>app.playlists();
|
|
10
|
-
const playlistById=id=>{for(const p of allPlaylists())if(String(safe(()=>p.
|
|
11
|
-
const userPlaylistById=id=>{for(const p of app.userPlaylists())if(String(safe(()=>p.
|
|
10
|
+
const playlistById=id=>{for(const p of allPlaylists())if(String(safe(()=>p.persistentID(),''))===id)return p;throw Error('Playlist not found')};
|
|
11
|
+
const userPlaylistById=id=>{for(const p of app.userPlaylists())if(String(safe(()=>p.persistentID(),''))===id)return p;throw Error('User playlist not found')};`;async function jxa(body,args){if(process.platform!=="darwin")throw Error("Apple Music is available only on macOS.");const script=`(()=>{${prelude}
|
|
12
12
|
const a=${JSON.stringify(args)};
|
|
13
|
-
${body}})()`;const dir=await mkdtemp(join(tmpdir(),"zortex-music-")),input=join(dir,"input.js"),output=join(dir,"output.json"),label=`zortex.music.${process.pid}.${Date.now()}`;try{await writeFile(input,script,{encoding:"utf8",mode:384});await runFile("/bin/launchctl",["submit","-l",label,"--",process.execPath,fileURLToPath(new URL("./apple-music-helper.js",import.meta.url)),input,output],{timeout:5e3,maxBuffer:65536,env:{PATH:"/usr/bin:/bin"}});const deadline=Date.now()+
|
|
13
|
+
${body}})()`;const dir=await mkdtemp(join(tmpdir(),"zortex-music-")),input=join(dir,"input.js"),output=join(dir,"output.json"),label=`zortex.music.${process.pid}.${Date.now()}`;try{await writeFile(input,script,{encoding:"utf8",mode:384});await runFile("/bin/launchctl",["submit","-l",label,"--",process.execPath,fileURLToPath(new URL("./apple-music-helper.js",import.meta.url)),input,output],{timeout:5e3,maxBuffer:65536,env:{PATH:"/usr/bin:/bin"}});const deadline=Date.now()+NATIVE_HELPER_TIMEOUT;let raw="";while(Date.now()<deadline){try{raw=await readFile(output,"utf8");break}catch{await new Promise(done=>setTimeout(done,50))}}await runFile("/bin/launchctl",["remove",label],{timeout:5e3,maxBuffer:65536}).catch(()=>{});if(!raw)throw Error("Music helper timed out.");const result=JSON.parse(raw);if(result.code!==0)throw Object.assign(Error(result.stderr||"Music returned no result."),{stderr:result.stderr});return JSON.parse(result.stdout)}catch(error){const message=String(error?.stderr??error?.message??error);if(/-1743|not authorized to send apple events/i.test(message))throw Error("macOS denied Automation access to Music (-1743).");if(/timed out|-1712/i.test(message))throw Error("Music did not answer before the action deadline (-1712).");throw Error(`Music action failed: ${(message.split("\n")[0]??"unknown failure").slice(0,360)}`)}finally{await rm(dir,{recursive:true,force:true})}}async function call(name,a){if(name==="get_identity")return jxa(`const l=library(),s=app.sources()[0];return JSON.stringify({libraryId:l.persistentID(),libraryName:l.name(),sourceName:s?s.name():null,applicationVersion:app.version()});`,a);if(name==="list_playlists")return jxa(`return JSON.stringify({playlists:allPlaylists().slice(0,a.limit||100).map(playlistRow)});`,a);if(name==="list_tracks")return jxa(`const p=a.playlistId?playlistById(a.playlistId):library();return JSON.stringify({playlist:playlistRow(p),tracks:p.tracks().slice(0,a.limit||100).map(trackRow)});`,a);if(name==="search_tracks")return jxa(`const p=a.playlistId?playlistById(a.playlistId):library(),xs=app.search(p,{for:a.query,only:'all'});return JSON.stringify({playlist:playlistRow(p),tracks:xs.slice(0,a.limit||50).map(trackRow)});`,a);if(name==="get_track")return jxa(`for(const t of library().tracks())if(String(safe(()=>t.persistentID(),''))===a.trackId)return JSON.stringify(trackRow(t));throw Error('Track not found');`,a);if(name==="get_playback")return jxa(`const t=safe(()=>app.currentTrack());return JSON.stringify({state:String(safe(()=>app.playerState(),'stopped')),position:Number(safe(()=>app.playerPosition(),0)),currentTrack:t?trackRow(t):null,currentPlaylist:safe(()=>playlistRow(app.currentPlaylist()))});`,a);if(name==="create_playlist")return jxa(`const p=app.UserPlaylist({name:a.name});app.userPlaylists.push(p);return JSON.stringify(playlistRow(p));`,a);if(name==="rename_playlist")return jxa(`const p=userPlaylistById(a.playlistId);p.name=a.name;return JSON.stringify(playlistRow(p));`,a);if(name==="delete_playlist")return jxa(`const p=userPlaylistById(a.playlistId);app.delete(p);return JSON.stringify({deleted:true,playlistId:a.playlistId});`,a);throw Error("This operation is not exposed.")}export function createAppleMusicServer(){const server=new Server({name:"zortex-apple-music",version:"0.1.0"},{capabilities:{tools:{}}});server.setRequestHandler("tools/list",()=>({tools:appleMusicTools}));server.setRequestHandler("tools/call",async request=>{try{const value=await call(request.params.name,request.params.arguments??{});return{content:[{type:"text",text:JSON.stringify(value)}],structuredContent:value}}catch(error){return{content:[{type:"text",text:String(error.message).slice(0,500)}],isError:true}}});return server}const handle=serveStdio(()=>createAppleMusicServer(),{onerror:()=>process.stderr.write("Apple Music MCP operation failed.\n")});await new Promise(done=>{process.stdin.once("end",()=>{void handle.close().finally(done)});process.once("SIGINT",()=>{void handle.close().finally(done)})});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const NATIVE_CHILD_TIMEOUT=2e4;export const NATIVE_HELPER_TIMEOUT=3e4;export function nativeProcessError(result){const error=result.error;if(error?.code==="ETIMEDOUT"||error?.killed&&error?.signal==="SIGTERM")return"Native macOS read timed out.";return result.stderr||error?.message||(error?String(error):"Native macOS process returned no result.")}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync}from"node:child_process";import{readFile,writeFile}from"node:fs/promises";const[inputPath,outputPath]=process.argv.slice(2);if(!inputPath||!outputPath)process.exit(2);let result;try{const script=await readFile(inputPath,"utf8");const child=spawnSync("/usr/bin/osascript",["-l","JavaScript","-e",script],{encoding:"utf8",timeout:
|
|
1
|
+
import{NATIVE_CHILD_TIMEOUT,nativeProcessError}from"./apple-native-process.mjs";import{spawnSync}from"node:child_process";import{readFile,writeFile}from"node:fs/promises";const[inputPath,outputPath]=process.argv.slice(2);if(!inputPath||!outputPath)process.exit(2);let result;try{const script=await readFile(inputPath,"utf8");const child=spawnSync("/usr/bin/osascript",["-l","JavaScript","-e",script],{encoding:"utf8",timeout:NATIVE_CHILD_TIMEOUT,maxBuffer:1048576});result={code:child.status??1,stdout:child.stdout??"",stderr:nativeProcessError(child)}}catch(error){result={code:1,stdout:"",stderr:String(error)}}await writeFile(outputPath,JSON.stringify(result),{encoding:"utf8",mode:384});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{execFile}from"node:child_process";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{fileURLToPath}from"node:url";import{promisify}from"node:util";import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";const runFile=promisify(execFile),text={type:"string",minLength:1,maxLength:512},noteId={...text,pattern:"^[^\\r\\n]+$"};const tool=(name,description,properties,required=[],readOnly=true)=>({name,description,inputSchema:{type:"object",properties,required,additionalProperties:false},annotations:{readOnlyHint:readOnly,destructiveHint:name==="delete_note",openWorldHint:false,idempotentHint:readOnly||name==="delete_note"}});export const appleNotesTools=[tool("get_identity","Read the default macOS Notes account that identifies the local Notes store.",{}),tool("list_folders","List Notes folders, including their owning account.",{}),tool("list_notes","List note metadata without note bodies.",{folderId:noteId,limit:{type:"integer",minimum:1,maximum:500}}),tool("search_notes","Search note titles in the local Notes store.",{query:text,limit:{type:"integer",minimum:1,maximum:100}},["query"]),tool("get_note","Read one note, including its body when it is unlocked.",{noteId},["noteId"]),tool("list_attachments","List attachment metadata for one note.",{noteId},["noteId"]),tool("create_note","Create a note in a selected folder.",{folderId:noteId,title:{type:"string",minLength:1,maxLength:255},body:{type:"string",maxLength:1e5}},["folderId","title"],false),tool("update_note","Update the title or body of one note.",{noteId,title:{type:"string",minLength:1,maxLength:255},body:{type:"string",maxLength:1e5}},["noteId"],false),tool("delete_note","Move one note to Notes Recently Deleted.",{noteId},["noteId"],false)];const prelude=`const app=Application('Notes');
|
|
1
|
+
import{NATIVE_HELPER_TIMEOUT}from"./apple-native-process.mjs";import{execFile}from"node:child_process";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{fileURLToPath}from"node:url";import{promisify}from"node:util";import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";const runFile=promisify(execFile),text={type:"string",minLength:1,maxLength:512},noteId={...text,pattern:"^[^\\r\\n]+$"};const tool=(name,description,properties,required=[],readOnly=true)=>({name,description,inputSchema:{type:"object",properties,required,additionalProperties:false},annotations:{readOnlyHint:readOnly,destructiveHint:name==="delete_note",openWorldHint:false,idempotentHint:readOnly||name==="delete_note"}});export const appleNotesTools=[tool("get_identity","Read the default macOS Notes account that identifies the local Notes store.",{}),tool("list_folders","List Notes folders, including their owning account.",{}),tool("list_notes","List note metadata without note bodies.",{folderId:noteId,limit:{type:"integer",minimum:1,maximum:500}}),tool("search_notes","Search note titles in the local Notes store.",{query:text,limit:{type:"integer",minimum:1,maximum:100}},["query"]),tool("get_note","Read one note, including its body when it is unlocked.",{noteId},["noteId"]),tool("list_attachments","List attachment metadata for one note.",{noteId},["noteId"]),tool("create_note","Create a note in a selected folder.",{folderId:noteId,title:{type:"string",minLength:1,maxLength:255},body:{type:"string",maxLength:1e5}},["folderId","title"],false),tool("update_note","Update the title or body of one note.",{noteId,title:{type:"string",minLength:1,maxLength:255},body:{type:"string",maxLength:1e5}},["noteId"],false),tool("delete_note","Move one note to Notes Recently Deleted.",{noteId},["noteId"],false)];const prelude=`const app=Application('Notes');
|
|
2
2
|
app.name();
|
|
3
3
|
const safe=(f,d=null)=>{try{return f()}catch(_){return d}};
|
|
4
4
|
const iso=d=>d&&d.toISOString?d.toISOString():null;
|
|
@@ -10,4 +10,4 @@ const folderById=id=>{for(const x of allFolders())if(x.id===id)return x.f;throw
|
|
|
10
10
|
const noteById=id=>{for(const x of allFolders()){try{const n=x.f.notes.byId(id);n.id();return n}catch(_){}}throw Error('Note not found in the selected account')};
|
|
11
11
|
const noteRow=(n,withBody=false)=>{const row={id:n.id(),name:safe(()=>n.name(),''),creationDate:iso(safe(()=>n.creationDate())),modificationDate:iso(safe(()=>n.modificationDate())),passwordProtected:safe(()=>n.passwordProtected(),false),shared:safe(()=>n.shared(),false)};if(withBody){try{row.body=n.body();row.bodyUnreadable=false}catch(_){row.body='';row.bodyUnreadable=true}}return row};`;async function jxa(body,args){if(process.platform!=="darwin")throw Error("Apple Notes is available only on macOS.");const script=`(()=>{${prelude}
|
|
12
12
|
const a=${JSON.stringify(args)};
|
|
13
|
-
${body}})()`;const dir=await mkdtemp(join(tmpdir(),"zortex-notes-")),input=join(dir,"input.js"),output=join(dir,"output.json"),label=`zortex.notes.${process.pid}.${Date.now()}`;try{await writeFile(input,script,{encoding:"utf8",mode:384});await runFile("/bin/launchctl",["submit","-l",label,"--",process.execPath,fileURLToPath(new URL("./apple-notes-helper.js",import.meta.url)),input,output],{timeout:5e3,maxBuffer:65536,env:{PATH:"/usr/bin:/bin"}});const deadline=Date.now()+
|
|
13
|
+
${body}})()`;const dir=await mkdtemp(join(tmpdir(),"zortex-notes-")),input=join(dir,"input.js"),output=join(dir,"output.json"),label=`zortex.notes.${process.pid}.${Date.now()}`;try{await writeFile(input,script,{encoding:"utf8",mode:384});await runFile("/bin/launchctl",["submit","-l",label,"--",process.execPath,fileURLToPath(new URL("./apple-notes-helper.js",import.meta.url)),input,output],{timeout:5e3,maxBuffer:65536,env:{PATH:"/usr/bin:/bin"}});const deadline=Date.now()+NATIVE_HELPER_TIMEOUT;let raw="";while(Date.now()<deadline){try{raw=await readFile(output,"utf8");break}catch{await new Promise(done=>setTimeout(done,50))}}await runFile("/bin/launchctl",["remove",label],{timeout:5e3,maxBuffer:65536}).catch(()=>{});if(!raw)throw Error("Notes helper timed out.");const result=JSON.parse(raw);if(result.code!==0)throw Object.assign(Error(result.stderr),{stderr:result.stderr});return JSON.parse(result.stdout)}catch(error){const message=String(error?.stderr??error?.message??error);if(/-1743|not authorized to send apple events/i.test(message))throw Error("macOS denied Automation access to Notes (-1743).");if(/timed out|-1712/i.test(message))throw Error("Notes did not answer before the action deadline (-1712).");throw Error(`Notes action failed: ${(message.split("\n")[0]??"unknown failure").slice(0,360)}`)}finally{await rm(dir,{recursive:true,force:true})}}async function call(name,a){if(name==="get_identity")return jxa(`return JSON.stringify(identity());`,a);if(name==="list_folders")return jxa(`const who=identity();return JSON.stringify({identity:who,folders:allFolders().map(x=>({id:x.id,name:safe(()=>x.f.name()),shared:safe(()=>x.f.shared(),false)}))});`,a);if(name==="list_notes")return jxa(`const out=[];for(const x of allFolders()){if(a.folderId&&x.id!==a.folderId)continue;for(const n of safe(()=>x.f.notes(),[])){out.push({...noteRow(n),folderId:x.id,folderName:safe(()=>x.f.name())});if(out.length>=(a.limit||100))return JSON.stringify({notes:out})}}return JSON.stringify({notes:out});`,a);if(name==="search_notes")return jxa(`const q=a.query.toLocaleLowerCase(),out=[];for(const x of allFolders()){const ns=x.f.notes,ids=safe(()=>ns.id(),[]),names=safe(()=>ns.name(),[]),created=safe(()=>ns.creationDate(),[]),modified=safe(()=>ns.modificationDate(),[]),protectedValues=safe(()=>ns.passwordProtected(),[]),sharedValues=safe(()=>ns.shared(),[]);for(let i=0;i<ids.length;i++)if(String(names[i]||'').toLocaleLowerCase().includes(q)){out.push({id:ids[i],name:names[i]||'',creationDate:iso(created[i]),modificationDate:iso(modified[i]),passwordProtected:Boolean(protectedValues[i]),shared:Boolean(sharedValues[i]),folderId:x.id,folderName:safe(()=>x.f.name())});if(out.length>=(a.limit||50))return JSON.stringify({notes:out})}}return JSON.stringify({notes:out});`,a);if(name==="get_note")return jxa(`return JSON.stringify(noteRow(noteById(a.noteId),true));`,a);if(name==="list_attachments")return jxa(`const n=noteById(a.noteId),out=[],seen={};for(const x of safe(()=>n.attachments(),[])){const id=safe(()=>x.id());if(!id||seen[id])continue;seen[id]=1;out.push({id,name:safe(()=>x.name()),contentIdentifier:safe(()=>x.contentIdentifier()),creationDate:iso(safe(()=>x.creationDate())),modificationDate:iso(safe(()=>x.modificationDate())),url:safe(()=>x.url()),shared:safe(()=>x.shared(),false)})}return JSON.stringify({attachments:out});`,a);if(name==="create_note")return jxa(`const f=folderById(a.folderId),n=app.Note({body:noteHtml(a.title,a.body||'')});f.notes.push(n);return JSON.stringify(noteRow(n,true));`,a);if(name==="update_note")return jxa(`const n=noteById(a.noteId);if(a.title===undefined&&a.body===undefined)throw Error('Provide title or body');if(a.body!==undefined)n.body=noteHtml(a.title===undefined?n.name():a.title,a.body);else n.name=a.title;return JSON.stringify(noteRow(n,true));`,a);if(name==="delete_note")return jxa(`const n=noteById(a.noteId);app.delete(n);return JSON.stringify({deleted:true,noteId:a.noteId});`,a);throw Error("This operation is not exposed.")}export function createAppleNotesServer(){const server=new Server({name:"zortex-apple-notes",version:"0.1.0"},{capabilities:{tools:{}}});server.setRequestHandler("tools/list",()=>({tools:appleNotesTools}));server.setRequestHandler("tools/call",async request=>{try{const value=await call(request.params.name,request.params.arguments??{});return{content:[{type:"text",text:JSON.stringify(value)}],structuredContent:value}}catch(error){return{content:[{type:"text",text:String(error.message).slice(0,500)}],isError:true}}});return server}const handle=serveStdio(()=>createAppleNotesServer(),{onerror:()=>process.stderr.write("Apple Notes MCP operation failed.\n")});await new Promise(done=>{process.stdin.once("end",()=>{void handle.close().finally(done)});process.once("SIGINT",()=>{void handle.close().finally(done)})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync}from"node:child_process";import{readFile,writeFile}from"node:fs/promises";const[inputPath,outputPath]=process.argv.slice(2);if(!inputPath||!outputPath)process.exit(2);let result;try{const script=await readFile(inputPath,"utf8");const child=spawnSync("/usr/bin/osascript",["-l","JavaScript","-e",script],{encoding:"utf8",timeout:
|
|
1
|
+
import{NATIVE_CHILD_TIMEOUT,nativeProcessError}from"./apple-native-process.mjs";import{spawnSync}from"node:child_process";import{readFile,writeFile}from"node:fs/promises";const[inputPath,outputPath]=process.argv.slice(2);if(!inputPath||!outputPath)process.exit(2);let result;try{const script=await readFile(inputPath,"utf8");const child=spawnSync("/usr/bin/osascript",["-l","JavaScript","-e",script],{encoding:"utf8",timeout:NATIVE_CHILD_TIMEOUT,maxBuffer:1048576});result={code:child.status??1,stdout:child.stdout??"",stderr:nativeProcessError(child)}}catch(error){result={code:1,stdout:"",stderr:String(error)}}await writeFile(outputPath,JSON.stringify(result),{encoding:"utf8",mode:384});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{execFile}from"node:child_process";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{fileURLToPath}from"node:url";import{promisify}from"node:util";import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";const runFile=promisify(execFile),text={type:"string",minLength:1,maxLength:512},nativeId={...text,pattern:"^[^\\r\\n]+$"};const tool=(name,description,properties,required=[],readOnly=true)=>({name,description,inputSchema:{type:"object",properties,required,additionalProperties:false},annotations:{readOnlyHint:readOnly,destructiveHint:name==="delete_reminder",openWorldHint:false,idempotentHint:readOnly||name==="delete_reminder"||name==="set_completed"}});export const appleRemindersTools=[tool("get_identity","Read the default macOS Reminders account that identifies the local store.",{}),tool("list_lists","List Reminders lists and their owning accounts.",{}),tool("list_reminders","List bounded reminder metadata.",{listId:nativeId,completed:{type:"boolean"},limit:{type:"integer",minimum:1,maximum:500}}),tool("search_reminders","Search reminder titles and notes.",{query:text,completed:{type:"boolean"},limit:{type:"integer",minimum:1,maximum:100}},["query"]),tool("get_reminder","Read one reminder.",{reminderId:nativeId},["reminderId"]),tool("create_reminder","Create a reminder in a selected list.",{listId:nativeId,title:{type:"string",minLength:1,maxLength:255},notes:{type:"string",maxLength:1e5},priority:{type:"integer",minimum:0,maximum:9},flagged:{type:"boolean"}},["listId","title"],false),tool("update_reminder","Update the title, notes, priority, or flagged state of one reminder.",{reminderId:nativeId,title:{type:"string",minLength:1,maxLength:255},notes:{type:"string",maxLength:1e5},priority:{type:"integer",minimum:0,maximum:9},flagged:{type:"boolean"}},["reminderId"],false),tool("set_completed","Complete or reopen one reminder.",{reminderId:nativeId,completed:{type:"boolean"}},["reminderId","completed"],false),tool("delete_reminder","Delete one reminder.",{reminderId:nativeId},["reminderId"],false)];const prelude=`const app=Application('Reminders');
|
|
1
|
+
import{NATIVE_HELPER_TIMEOUT}from"./apple-native-process.mjs";import{execFile}from"node:child_process";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{fileURLToPath}from"node:url";import{promisify}from"node:util";import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";const runFile=promisify(execFile),text={type:"string",minLength:1,maxLength:512},nativeId={...text,pattern:"^[^\\r\\n]+$"};const tool=(name,description,properties,required=[],readOnly=true)=>({name,description,inputSchema:{type:"object",properties,required,additionalProperties:false},annotations:{readOnlyHint:readOnly,destructiveHint:name==="delete_reminder",openWorldHint:false,idempotentHint:readOnly||name==="delete_reminder"||name==="set_completed"}});export const appleRemindersTools=[tool("get_identity","Read the default macOS Reminders account that identifies the local store.",{}),tool("list_lists","List Reminders lists and their owning accounts.",{}),tool("list_reminders","List bounded reminder metadata.",{listId:nativeId,completed:{type:"boolean"},limit:{type:"integer",minimum:1,maximum:500}}),tool("search_reminders","Search reminder titles and notes.",{query:text,completed:{type:"boolean"},limit:{type:"integer",minimum:1,maximum:100}},["query"]),tool("get_reminder","Read one reminder.",{reminderId:nativeId},["reminderId"]),tool("create_reminder","Create a reminder in a selected list.",{listId:nativeId,title:{type:"string",minLength:1,maxLength:255},notes:{type:"string",maxLength:1e5},priority:{type:"integer",minimum:0,maximum:9},flagged:{type:"boolean"}},["listId","title"],false),tool("update_reminder","Update the title, notes, priority, or flagged state of one reminder.",{reminderId:nativeId,title:{type:"string",minLength:1,maxLength:255},notes:{type:"string",maxLength:1e5},priority:{type:"integer",minimum:0,maximum:9},flagged:{type:"boolean"}},["reminderId"],false),tool("set_completed","Complete or reopen one reminder.",{reminderId:nativeId,completed:{type:"boolean"}},["reminderId","completed"],false),tool("delete_reminder","Delete one reminder.",{reminderId:nativeId},["reminderId"],false)];const prelude=`const app=Application('Reminders');
|
|
2
2
|
app.name();
|
|
3
3
|
const safe=(f,d=null)=>{try{return f()}catch(_){return d}};
|
|
4
4
|
const iso=d=>d&&d.toISOString?d.toISOString():null;
|
|
@@ -8,4 +8,4 @@ const listById=id=>{for(const x of allLists())if(x.id===id)return x.l;throw Erro
|
|
|
8
8
|
const reminderById=id=>{for(const x of allLists())for(const r of safe(()=>x.l.reminders(),[]))if(safe(()=>r.id())===id)return{r,list:x.l};throw Error('Reminder not found')};
|
|
9
9
|
const row=(r,l)=>({id:r.id(),name:safe(()=>r.name(),''),body:safe(()=>r.body(),''),completed:Boolean(safe(()=>r.completed(),false)),completionDate:iso(safe(()=>r.completionDate())),creationDate:iso(safe(()=>r.creationDate())),modificationDate:iso(safe(()=>r.modificationDate())),dueDate:iso(safe(()=>r.dueDate())),allDayDueDate:iso(safe(()=>r.alldayDueDate())),remindMeDate:iso(safe(()=>r.remindMeDate())),priority:Number(safe(()=>r.priority(),0)),flagged:Boolean(safe(()=>r.flagged(),false)),listId:l.id(),listName:safe(()=>l.name(),''),accountId:safe(()=>l.container().id()),accountName:safe(()=>l.container().name())});`;async function jxa(body,args){if(process.platform!=="darwin")throw Error("Apple Reminders is available only on macOS.");const script=`(()=>{${prelude}
|
|
10
10
|
const a=${JSON.stringify(args)};
|
|
11
|
-
${body}})()`;const dir=await mkdtemp(join(tmpdir(),"zortex-reminders-")),input=join(dir,"input.js"),output=join(dir,"output.json"),label=`zortex.reminders.${process.pid}.${Date.now()}`;try{await writeFile(input,script,{encoding:"utf8",mode:384});await runFile("/bin/launchctl",["submit","-l",label,"--",process.execPath,fileURLToPath(new URL("./apple-reminders-helper.js",import.meta.url)),input,output],{timeout:5e3,maxBuffer:65536,env:{PATH:"/usr/bin:/bin"}});const deadline=Date.now()+
|
|
11
|
+
${body}})()`;const dir=await mkdtemp(join(tmpdir(),"zortex-reminders-")),input=join(dir,"input.js"),output=join(dir,"output.json"),label=`zortex.reminders.${process.pid}.${Date.now()}`;try{await writeFile(input,script,{encoding:"utf8",mode:384});await runFile("/bin/launchctl",["submit","-l",label,"--",process.execPath,fileURLToPath(new URL("./apple-reminders-helper.js",import.meta.url)),input,output],{timeout:5e3,maxBuffer:65536,env:{PATH:"/usr/bin:/bin"}});const deadline=Date.now()+NATIVE_HELPER_TIMEOUT;let raw="";while(Date.now()<deadline){try{raw=await readFile(output,"utf8");break}catch{await new Promise(done=>setTimeout(done,50))}}await runFile("/bin/launchctl",["remove",label],{timeout:5e3,maxBuffer:65536}).catch(()=>{});if(!raw)throw Error("Reminders helper timed out.");const result=JSON.parse(raw);if(result.code!==0)throw Object.assign(Error(result.stderr||"Reminders returned no result."),{stderr:result.stderr});return JSON.parse(result.stdout)}catch(error){const message=String(error?.stderr??error?.message??error);if(/-1743|not authorized to send apple events/i.test(message))throw Error("macOS denied Automation access to Reminders (-1743).");if(/timed out|-1712/i.test(message))throw Error("Reminders did not answer before the action deadline (-1712).");throw Error(`Reminders action failed: ${(message.split("\n")[0]??"unknown failure").slice(0,360)}`)}finally{await rm(dir,{recursive:true,force:true})}}async function call(name,a){if(name==="get_identity")return jxa(`return JSON.stringify(identity());`,a);if(name==="list_lists")return jxa(`const who=identity();return JSON.stringify({identity:who,lists:allLists().map(x=>({id:x.id,name:safe(()=>x.l.name(),''),color:safe(()=>x.l.color()),emblem:safe(()=>x.l.emblem()),accountId:safe(()=>x.l.container().id()),accountName:safe(()=>x.l.container().name())}))});`,a);if(name==="list_reminders")return jxa(`const out=[];for(const x of allLists()){if(a.listId&&x.id!==a.listId)continue;for(const r of safe(()=>x.l.reminders(),[])){const v=row(r,x.l);if(a.completed!==undefined&&v.completed!==a.completed)continue;out.push(v);if(out.length>=(a.limit||100))return JSON.stringify({reminders:out})}}return JSON.stringify({reminders:out});`,a);if(name==="search_reminders")return jxa(`const q=a.query.toLocaleLowerCase(),out=[];for(const x of allLists())for(const r of safe(()=>x.l.reminders(),[])){const v=row(r,x.l);if(a.completed!==undefined&&v.completed!==a.completed)continue;if((v.name+' '+v.body).toLocaleLowerCase().includes(q)){out.push(v);if(out.length>=(a.limit||50))return JSON.stringify({reminders:out})}}return JSON.stringify({reminders:out});`,a);if(name==="get_reminder")return jxa(`const x=reminderById(a.reminderId);return JSON.stringify(row(x.r,x.list));`,a);if(name==="create_reminder")return jxa(`const l=listById(a.listId),r=app.Reminder({name:a.title,body:a.notes||''});l.reminders.push(r);if(a.priority!==undefined)r.priority=a.priority;if(a.flagged!==undefined)r.flagged=a.flagged;return JSON.stringify(row(r,l));`,a);if(name==="update_reminder")return jxa(`const x=reminderById(a.reminderId),r=x.r;if(a.title===undefined&&a.notes===undefined&&a.priority===undefined&&a.flagged===undefined)throw Error('Provide a field to update');if(a.title!==undefined)r.name=a.title;if(a.notes!==undefined)r.body=a.notes;if(a.priority!==undefined)r.priority=a.priority;if(a.flagged!==undefined)r.flagged=a.flagged;return JSON.stringify(row(r,x.list));`,a);if(name==="set_completed")return jxa(`const x=reminderById(a.reminderId);x.r.completed=a.completed;return JSON.stringify(row(x.r,x.list));`,a);if(name==="delete_reminder")return jxa(`const x=reminderById(a.reminderId);app.delete(x.r);return JSON.stringify({deleted:true,reminderId:a.reminderId});`,a);throw Error("This operation is not exposed.")}export function createAppleRemindersServer(){const server=new Server({name:"zortex-apple-reminders",version:"0.1.0"},{capabilities:{tools:{}}});server.setRequestHandler("tools/list",()=>({tools:appleRemindersTools}));server.setRequestHandler("tools/call",async request=>{try{const value=await call(request.params.name,request.params.arguments??{});return{content:[{type:"text",text:JSON.stringify(value)}],structuredContent:value}}catch(error){return{content:[{type:"text",text:String(error.message).slice(0,500)}],isError:true}}});return server}const handle=serveStdio(()=>createAppleRemindersServer(),{onerror:()=>process.stderr.write("Apple Reminders MCP operation failed.\n")});await new Promise(done=>{process.stdin.once("end",()=>{void handle.close().finally(done)});process.once("SIGINT",()=>{void handle.close().finally(done)})});
|
|
@@ -1 +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");
|
|
1
|
+
import{execFile}from"node:child_process";import{createHash}from"node:crypto";import{accessSync,constants,statSync}from"node:fs";import{mkdir,mkdtemp,rename,rm,stat}from"node:fs/promises";import{createConnection}from"node:net";import{homedir,userInfo}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=[...new Set([managedApp,"/Applications/"+bundle,join(homedir(),"Applications",bundle),join(loginHome(),"Applications","Zortex",bundle),join(loginHome(),"Applications",bundle)])];const executable=app=>join(app,"Contents","MacOS","cua-driver");const socketAt=home=>join(home,"Library","Caches","cua-driver","cua-driver.sock");function loginHome(){try{return userInfo().homedir}catch{return homedir()}}function isSocket(path){try{return statSync(path).isSocket()}catch{return false}}export function resolveCuaSocket(options={}){if((options.platform??process.platform)!=="darwin")return void 0;const override=(options.env??process.env).ZORTEX_CUA_SOCKET?.trim();if(override)return override;const homes=[options.home??homedir(),options.loginHome??loginHome()];const candidates=[...new Set(homes.map(socketAt))];return candidates.find(options.isSocket??isSocket)??socketAt(homes[1])}export let cuaSocket=resolveCuaSocket();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(){cuaSocket=resolveCuaSocket();const socket=cuaSocket;if(!socket||!(await stat(socket).catch(()=>void 0))?.isSocket())return false;return new Promise(resolve=>{const client=createConnection(socket);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})}function managedCuaBootDelayMs(env=process.env){const value=env.ZORTEX_MANAGED_CUA_BOOT_DELAY_MS?.trim();const raw=value?Number(value):NaN;return Number.isFinite(raw)&&raw>=0&&raw<=3e4?Math.floor(raw):2500}export async function startManagedCua(options={}){const env=options.env??process.env;if(options.signal?.aborted)return;if(/^(1|true|yes|on)$/i.test((env.ZORTEX_DISABLE_AUTO_CUA??"").trim()))return;const app=macCuaApp();if(!app)return;const bootDelay=options.immediate?0:managedCuaBootDelayMs(env);if(bootDelay>0){try{await delay(bootDelay,void 0,{ref:false,...options.signal?{signal:options.signal}:{}})}catch(error){if(options.signal?.aborted)return;throw error}}if(options.signal?.aborted)return;if(installed(app))await start(app)}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."}}
|