@zortexhq/indra-v2.5 0.2.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +11 -4
  2. package/bin/codex-postinstall.mjs +1 -1
  3. package/dist/auto-sync.js +1 -1
  4. package/dist/cli-run.js +1 -1
  5. package/dist/codex-install.js +1 -1
  6. package/dist/codex-setup.js +1 -1
  7. package/dist/connector-worker.js +1 -1
  8. package/dist/content-find.js +2 -2
  9. package/dist/find-snapshots.js +1 -0
  10. package/dist/gateway.js +1 -1
  11. package/dist/imessage-sync.js +1 -0
  12. package/dist/local-cloud-policy.js +1 -1
  13. package/dist/local-cloud.js +1 -1
  14. package/dist/mail-search-body.js +1 -0
  15. package/dist/match-excerpt.js +1 -0
  16. package/dist/mcp.js +1 -1
  17. package/dist/native-connect.js +1 -0
  18. package/dist/native-level1-setup.js +1 -1
  19. package/dist/public-tool.js +1 -1
  20. package/dist/read-route.js +1 -0
  21. package/dist/recovery-support.js +1 -1
  22. package/dist/resident-ensure-ready.js +1 -1
  23. package/dist/resident-host.js +2 -2
  24. package/dist/resident-jobs.js +1 -1
  25. package/dist/resident-platform.js +1 -1
  26. package/dist/source-data.js +1 -0
  27. package/dist/supervised-sync.js +1 -1
  28. package/dist/sync-sources.js +1 -0
  29. package/dist/worker-google-auth.js +1 -0
  30. package/node_modules/@zortexhq/plugin-connector-calendar/dist/provider.js +1 -1
  31. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/catalog.js +1 -0
  32. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/index.js +1 -0
  33. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/policy.js +1 -0
  34. package/node_modules/@zortexhq/plugin-connector-computer-files/dist/result.js +1 -0
  35. package/node_modules/@zortexhq/plugin-connector-computer-files/package.json +18 -0
  36. package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
  37. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  38. package/node_modules/@zortexhq/plugin-connector-core/dist/native-file-roots.js +1 -0
  39. package/node_modules/@zortexhq/plugin-connector-drive/dist/provider.js +1 -1
  40. package/node_modules/@zortexhq/plugin-connector-framework/dist/manifest.js +1 -1
  41. package/node_modules/@zortexhq/plugin-connector-framework/dist/runtime.js +1 -1
  42. package/node_modules/@zortexhq/plugin-connector-gmail/dist/brokered.js +1 -1
  43. package/node_modules/@zortexhq/plugin-connector-gmail/dist/gmail-source.js +2 -2
  44. package/node_modules/@zortexhq/plugin-connector-gmail/dist/provider.js +1 -1
  45. package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/provider.js +1 -1
  46. package/node_modules/@zortexhq/plugin-connector-history/dist/provider.js +1 -1
  47. package/node_modules/@zortexhq/plugin-connector-imessage/dist/attributed-body.js +1 -0
  48. package/node_modules/@zortexhq/plugin-connector-imessage/dist/chatdb-source.js +1 -0
  49. package/node_modules/@zortexhq/plugin-connector-imessage/dist/connector.js +1 -0
  50. package/node_modules/@zortexhq/plugin-connector-imessage/dist/index.js +1 -0
  51. package/node_modules/@zortexhq/plugin-connector-imessage/dist/manifest.js +1 -0
  52. package/node_modules/@zortexhq/plugin-connector-imessage/dist/sqlite-snapshot.js +1 -0
  53. package/node_modules/@zortexhq/plugin-connector-imessage/package.json +16 -0
  54. package/node_modules/@zortexhq/plugin-connector-level1/dist/api/index.js +1 -0
  55. package/node_modules/@zortexhq/plugin-connector-level1/dist/computer-files-pages.js +1 -1
  56. package/node_modules/@zortexhq/plugin-connector-level1/dist/computer-files.js +1 -0
  57. package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -0
  58. package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
  59. package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
  60. package/node_modules/@zortexhq/plugin-connector-level1/dist/sources.js +1 -1
  61. package/node_modules/@zortexhq/plugin-connector-level1/package.json +5 -1
  62. package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
  63. package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
  64. package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
  65. package/node_modules/@zortexhq/plugin-device-auth/dist/authority.js +1 -1
  66. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-catalog.js +1 -0
  67. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-renderer.js +1 -0
  68. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/galaxy-text.js +1 -1
  69. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
  70. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
  71. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/routes.js +1 -1
  72. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/snapshot.js +1 -1
  73. package/node_modules/@zortexhq/plugin-galaxy-ui/package.json +1 -0
  74. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -1
  75. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -1
  76. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
  77. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -1
  78. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/galaxy-renderer.js +1 -1
  79. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/live-model.js +1 -1
  80. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/portrait-model.js +1 -1
  81. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.js +1 -1
  82. package/node_modules/@zortexhq/plugin-google-auth/default-client.json +1 -0
  83. package/node_modules/@zortexhq/plugin-google-auth/dist/desktop-client.js +1 -1
  84. package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
  85. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
  86. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/search-text.js +1 -0
  87. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/source-sync.js +1 -0
  88. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/current-records.js +1 -0
  89. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  90. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/record-rules.js +1 -1
  91. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +19 -2
  92. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -0
  93. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
  94. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -0
  95. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +1 -1
  96. package/node_modules/@zortexhq/rooktrail/dist/record-rules.js +1 -1
  97. package/node_modules/@zortexhq/rooktrail/dist/registry.js +1 -1
  98. package/package.json +11 -7
  99. package/release-provenance.json +45 -31
  100. package/update-manifest.json +380 -164
@@ -1,8 +1,8 @@
1
- import{EXEC_RESPONSE_BODY_MAX_BYTES,isOk,ok,sha256Hex}from"./original-contracts.js";export function createGmailSourceModule(parts){const{connectorError,gateRefusal,googleErrorReasonV1,googleStatusOverrideV1,readByIdAnswerV1,webStatusErrorV1}=parts;const GMAIL_AUDIT_RECENT_QUERY="newer_than:3d";const GMAIL_MESSAGE_PULL_CAP=5e4;const GMAIL_CENSUS_MAX_PAGES=5e3;const GMAIL_THREAD_PAGE_BYTE_BUDGET=24*1024*1024;const GMAIL_DELETIONS_CAP=5e4;const GMAIL_HISTORY_MAX_PAGES=5e3;const GMAIL_ATTACHMENT_CONTENT_CAP=1024*1024;const GMAIL_ATTACHMENT_TRANSPORT_SAFE_BYTES=Math.floor((EXEC_RESPONSE_BODY_MAX_BYTES-16384)*3/4);const GMAIL_API_BASE="https://gmail.googleapis.com/gmail/v1";const GMAIL_BATCH_URL="https://gmail.googleapis.com/batch/gmail/v1";const GMAIL_BATCH_CHUNK_SIZE=50;const GMAIL_WAN_GATE="G1-outbound chokepoint \u2014 live WAN transport opens at C-P6-1; real-provider OAuth walks at C-P6-2 (G2)";const refuseWanTransport=()=>({ok:false,error:GMAIL_WAN_GATE});function buildAttachmentContent(mimeType,bytes,cap){if(bytes.length>cap)return{contentOmitted:"over-cap"};const mime=mimeType!==""?mimeType:"application/octet-stream";const b64=Buffer.from(bytes).toString("base64");return{sha256:sha256Hex(bytes),contentDataUri:`data:${mime};base64,${b64}`}}function chunkIds(ids,size){const chunks=[];for(let i=0;i<ids.length;i+=size)chunks.push(ids.slice(i,i+size));return chunks}function headerBodySplit(text,from=0){const crlf=text.indexOf("\r\n\r\n",from);const lf=text.indexOf("\n\n",from);if(crlf<0&&lf<0)return null;if(crlf>=0&&(lf<0||crlf<=lf))return{index:crlf,sepLen:4};return{index:lf,sepLen:2}}function splitMultipartMixed(body){const opening=/(?:^|\r?\n)--([^\r\n]+)\r?\n/.exec(body);if(opening===null)return null;const delimiter=`--${opening[1]}`;const parts2=[];for(const raw of body.split(delimiter).slice(1)){if(raw.startsWith("--"))break;const segment=raw.replace(/^\r?\n/,"");const split=headerBodySplit(segment);if(split===null)return null;const headers=segment.slice(0,split.index);const nested=segment.slice(split.index+split.sepLen);const id=/^Content-ID:\s*<?([^>\r\n]+)>?/im.exec(headers);const status=/^HTTP\/[\d.]+\s+(\d{3})/.exec(nested);const nestedSplit=headerBodySplit(nested);if(status===null||nestedSplit===null)return null;parts2.push({contentId:id?.[1]?.trim()??null,status:Number.parseInt(status[1],10),body:nested.slice(nestedSplit.index+nestedSplit.sepLen)})}return parts2.length===0?null:parts2}const GMAIL_METADATA_HEADERS=["From","To","Cc","Subject","Date"];const GMAIL_STARTER_MESSAGE_LIMIT=10;const GMAIL_STARTER_CONTENT_BYTES=1024*1024;function decodedBytes(part){if(part===void 0)return 0;const own=typeof part.body?.data==="string"?Buffer.from(part.body.data,"base64url").byteLength:0;return own+(part.parts??[]).reduce((total,child)=>total+decodedBytes(child),0)}function stripStarterBody(part){if(part===void 0)return void 0;const body=part.body===void 0?void 0:{...part.body.attachmentId===void 0?{}:{attachmentId:part.body.attachmentId},...part.body.size===void 0?{}:{size:part.body.size}};return{...part.partId===void 0?{}:{partId:part.partId},...part.mimeType===void 0?{}:{mimeType:part.mimeType},...part.filename===void 0?{}:{filename:part.filename},...part.headers===void 0?{}:{headers:part.headers.map(header=>({...header}))},...body===void 0?{}:{body},...part.parts===void 0?{}:{parts:part.parts.map(stripStarterBody)}}}function capStarterContent(messages,budget){let consumed=0;return messages.map(message=>{const bytes=decodedBytes(message.payload);if(consumed+bytes<=budget){consumed+=bytes;return message}return{...message,...message.payload===void 0?{}:{payload:stripStarterBody(message.payload)},starterContentOmitted:"starter-cap"}})}class HttpGmailSource{transport;authHeaders;cap;pageSize;attachmentCap;query;messageFormat;messageLimit;starterContentBytes;fetchAttachments;resolvedAccount=null;prefetch;threadPageByteBudget;constructor(transport,authHeaders,cap,pageSize,attachmentCap,query,messageFormat,messageLimit,starterContentBytes,fetchAttachments,prefetch,threadPageByteBudget=GMAIL_THREAD_PAGE_BYTE_BUDGET){this.threadPageByteBudget=threadPageByteBudget;this.transport=transport;this.authHeaders=authHeaders;this.cap=cap;this.pageSize=pageSize;this.attachmentCap=attachmentCap;this.query=query;this.messageFormat=messageFormat;this.messageLimit=messageLimit;this.starterContentBytes=starterContentBytes;this.fetchAttachments=fetchAttachments;this.prefetch=prefetch}batchRequest(ids,headersParam,headers){const boundary=sha256Hex(Buffer.from([...ids].sort().join("\0"),"utf8"));const body=ids.map(id=>{const path=`/gmail/v1/users/me/messages/${encodeURIComponent(id)}?format=${this.messageFormat}${headersParam}`;return`--${boundary}\r
1
+ import{EXEC_RESPONSE_BODY_MAX_BYTES,isOk,ok,sha256Hex}from"./original-contracts.js";export function createGmailSourceModule(parts){const{connectorError,gateRefusal,googleErrorReasonV1,googleStatusOverrideV1,readByIdAnswerV1,webStatusErrorV1}=parts;const GMAIL_AUDIT_RECENT_QUERY="newer_than:3d";const GMAIL_MESSAGE_PULL_CAP=5e4;const GMAIL_CENSUS_MAX_PAGES=5e3;const GMAIL_THREAD_PAGE_BYTE_BUDGET=24*1024*1024;const GMAIL_DELETIONS_CAP=5e4;const GMAIL_HISTORY_MAX_PAGES=5e3;const GMAIL_ATTACHMENT_CONTENT_CAP=1024*1024;const GMAIL_ATTACHMENT_TRANSPORT_SAFE_BYTES=Math.floor((EXEC_RESPONSE_BODY_MAX_BYTES-16384)*3/4);const GMAIL_API_BASE="https://gmail.googleapis.com/gmail/v1";const GMAIL_BATCH_URL="https://gmail.googleapis.com/batch/gmail/v1";const GMAIL_BATCH_CHUNK_SIZE=50;const GMAIL_WAN_GATE="G1-outbound chokepoint \u2014 live WAN transport opens at C-P6-1; real-provider OAuth walks at C-P6-2 (G2)";const refuseWanTransport=()=>({ok:false,error:GMAIL_WAN_GATE});function buildAttachmentContent(mimeType,bytes,cap){if(bytes.length>cap)return{contentOmitted:"over-cap"};const mime=mimeType!==""?mimeType:"application/octet-stream";const b64=Buffer.from(bytes).toString("base64");return{sha256:sha256Hex(bytes),contentDataUri:`data:${mime};base64,${b64}`}}function chunkIds(ids,size){const chunks=[];for(let i=0;i<ids.length;i+=size)chunks.push(ids.slice(i,i+size));return chunks}function headerBodySplit(text,from=0){const crlf=text.indexOf("\r\n\r\n",from);const lf=text.indexOf("\n\n",from);if(crlf<0&&lf<0)return null;if(crlf>=0&&(lf<0||crlf<=lf))return{index:crlf,sepLen:4};return{index:lf,sepLen:2}}function splitMultipartMixed(body){const opening=/(?:^|\r?\n)--([^\r\n]+)\r?\n/.exec(body);if(opening===null)return null;const delimiter=`--${opening[1]}`;const parts2=[];for(const raw of body.split(delimiter).slice(1)){if(raw.startsWith("--"))break;const segment=raw.replace(/^\r?\n/,"");const split=headerBodySplit(segment);if(split===null)return null;const headers=segment.slice(0,split.index);const nested=segment.slice(split.index+split.sepLen);const id=/^Content-ID:\s*<?([^>\r\n]+)>?/im.exec(headers);const status=/^HTTP\/[\d.]+\s+(\d{3})/.exec(nested);const nestedSplit=headerBodySplit(nested);if(status===null||nestedSplit===null)return null;parts2.push({contentId:id?.[1]?.trim()??null,status:Number.parseInt(status[1],10),body:nested.slice(nestedSplit.index+nestedSplit.sepLen)})}return parts2.length===0?null:parts2}const GMAIL_METADATA_HEADERS=["From","To","Cc","Subject","Date"];const GMAIL_STARTER_MESSAGE_LIMIT=10;const GMAIL_STARTER_CONTENT_BYTES=1024*1024;function decodedBytes(part){if(part===void 0)return 0;const own=typeof part.body?.data==="string"?Buffer.from(part.body.data,"base64url").byteLength:0;return own+(part.parts??[]).reduce((total,child)=>total+decodedBytes(child),0)}function stripStarterBody(part){if(part===void 0)return void 0;const body=part.body===void 0?void 0:{...part.body.attachmentId===void 0?{}:{attachmentId:part.body.attachmentId},...part.body.size===void 0?{}:{size:part.body.size}};return{...part.partId===void 0?{}:{partId:part.partId},...part.mimeType===void 0?{}:{mimeType:part.mimeType},...part.filename===void 0?{}:{filename:part.filename},...part.headers===void 0?{}:{headers:part.headers.map(header=>({...header}))},...body===void 0?{}:{body},...part.parts===void 0?{}:{parts:part.parts.map(stripStarterBody)}}}function capStarterContent(messages,budget){let consumed=0;return messages.map(message=>{const bytes=decodedBytes(message.payload);if(consumed+bytes<=budget){consumed+=bytes;return message}return{...message,...message.payload===void 0?{}:{payload:stripStarterBody(message.payload)},starterContentOmitted:"starter-cap"}})}class HttpGmailSource{transport;authHeaders;cap;pageSize;attachmentCap;query;selectedMessageIds;messageFormat;messageLimit;starterContentBytes;fetchAttachments;resolvedAccount=null;prefetch;threadPageByteBudget;constructor(transport,authHeaders,cap,pageSize,attachmentCap,query,selectedMessageIds,messageFormat,messageLimit,starterContentBytes,fetchAttachments,prefetch,threadPageByteBudget=GMAIL_THREAD_PAGE_BYTE_BUDGET){this.threadPageByteBudget=threadPageByteBudget;this.transport=transport;this.authHeaders=authHeaders;this.cap=cap;this.pageSize=pageSize;this.attachmentCap=attachmentCap;this.query=query;this.selectedMessageIds=selectedMessageIds;this.messageFormat=messageFormat;this.messageLimit=messageLimit;this.starterContentBytes=starterContentBytes;this.fetchAttachments=fetchAttachments;this.prefetch=prefetch}batchRequest(ids,headersParam,headers){const boundary=sha256Hex(Buffer.from([...ids].sort().join("\0"),"utf8"));const body=ids.map(id=>{const path=`/gmail/v1/users/me/messages/${encodeURIComponent(id)}?format=${this.messageFormat}${headersParam}`;return`--${boundary}\r
2
2
  Content-Type: application/http\r
3
3
  Content-ID: <${id}>\r
4
4
  \r
5
5
  GET ${path} HTTP/1.1\r
6
6
  \r
7
7
  `}).join("")+`--${boundary}--\r
8
- `;return{url:GMAIL_BATCH_URL,headers:{...headers,"Content-Type":`multipart/mixed; boundary=${boundary}`},method:"POST",body}}hint(grant,ids,headersParam){if(this.prefetch===void 0||ids.length===0)return;const hdrs=this.authHeaders(grant);if(!isOk(hdrs))return;for(const chunk of chunkIds(ids,GMAIL_BATCH_CHUNK_SIZE)){this.prefetch([this.batchRequest(chunk,headersParam,hdrs.ok)])}}hintGets(grant,paths){if(this.prefetch===void 0||paths.length===0)return;const headers=this.authHeaders(grant);if(!isOk(headers))return;this.prefetch(paths.map(path=>({url:`${GMAIL_API_BASE}${path}`,headers:headers.ok,method:"GET"})))}static create(opts){return new HttpGmailSource(opts.transport??refuseWanTransport,opts.authHeaders,opts.cap??GMAIL_MESSAGE_PULL_CAP,opts.pageSize??100,opts.attachmentCap??GMAIL_ATTACHMENT_CONTENT_CAP,opts.query!==void 0&&opts.query.trim()!==""?opts.query.trim():void 0,opts.messageFormat??"full",opts.messageLimit??null,opts.starterContentBytes??null,opts.fetchAttachments??true,opts.prefetch,opts.threadPageByteBudget??GMAIL_THREAD_PAGE_BYTE_BUDGET)}get(grant,path,what){const hdrs=this.authHeaders(grant);if(!isOk(hdrs))return hdrs;const res=this.transport(`${GMAIL_API_BASE}${path}`,hdrs.ok);if(!res.ok){if(res.structuredError!==void 0)return{err:res.structuredError};if(res.error===GMAIL_WAN_GATE)return gateRefusal("gmail live WAN transport",GMAIL_WAN_GATE);return connectorError("unavailable",`gmail ${what} transport failure: ${res.error} \u2014 NEVER an empty success (FM-21)`,"transient")}return this.routeStatus(res.status,res.body,what)}routeStatus(status,body,what){if(status===200){try{return ok(JSON.parse(body))}catch{return connectorError("internal",`gmail ${what}: 200 body is not JSON \u2014 REST-surface drift (FM-19)`)}}return{err:webStatusErrorV1(status,{provider:"gmail",what,bodyOverride:googleStatusOverrideV1(body),...googleErrorReasonV1(body)===void 0?{}:{detail:googleErrorReasonV1(body)}})}}batchGetMessages(grant,ids,headersParam){const auth=this.authHeaders(grant);if(!isOk(auth))return auth;const request=this.batchRequest(ids,headersParam,auth.ok);const response=this.transport(request.url,request.headers,{method:request.method,body:request.body});if(!response.ok){if(response.structuredError!==void 0)return{err:response.structuredError};if(response.error===GMAIL_WAN_GATE)return gateRefusal("gmail live WAN transport",GMAIL_WAN_GATE);return connectorError("unavailable",`gmail messages.batchGet transport failure: ${response.error} \u2014 NEVER an empty success (FM-21)`,"transient")}if(response.status!==200)return this.routeStatus(response.status,response.body,"messages.batchGet");const parts2=splitMultipartMixed(response.body);if(parts2===null)return connectorError("internal","gmail messages.batchGet: malformed multipart response \u2014 REST-surface drift (FM-19)");const out=new Map;const throttled=[];for(const part of parts2){if(part.contentId===null)return connectorError("internal","gmail messages.batchGet: missing Content-ID \u2014 cannot correlate response (FM-19)");const contentId=part.contentId.replace(/^response-/,"");const id=ids.find(candidate=>contentId===candidate||contentId.endsWith(`/${candidate}`));if(id===void 0||out.has(id)||throttled.includes(id))return connectorError("internal",`gmail messages.batchGet: unexpected or duplicate Content-ID '${part.contentId}' (FM-19)`);const routed=this.routeStatus(part.status,part.body,"messages.get");if(!isOk(routed)){if("err"in routed&&routed.err.retryability==="throttling"){throttled.push(id);continue}return routed}out.set(id,routed.ok)}for(const id of throttled){const single=this.get(grant,`/users/me/messages/${encodeURIComponent(id)}?format=${this.messageFormat}${headersParam}`,"messages.get");if(!isOk(single))return single;out.set(id,single.ok)}for(const id of ids){if(!out.has(id))return connectorError("internal",`gmail messages.batchGet: response omitted message '${id}' (FM-19)`)}return ok(out)}account(grant){if(this.resolvedAccount!==null)return ok(this.resolvedAccount);const p=this.getProfile(grant);if(!isOk(p))return p;this.resolvedAccount=p.ok.emailAddress;return ok(this.resolvedAccount)}getProfile(grant){const r=this.get(grant,"/users/me/profile","getProfile");if(!isOk(r))return r;const o=r.ok;if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail getProfile: response is not an object \u2014 REST-surface drift (FM-19)")}const email=o.emailAddress;if(typeof email!=="string"||email===""){return connectorError("internal","gmail getProfile: emailAddress missing \u2014 cannot source the account epoch (REST-surface drift, FM-19)")}return ok(o)}enumerateAll(grant,path,listKey,what){const out=[];let pageToken=null;const seenPageTokens=new Set;let pages=0;for(;;){if(pages>=GMAIL_CENSUS_MAX_PAGES){return connectorError("resource_exhausted",`gmail ${what} census exceeded the ${GMAIL_CENSUS_MAX_PAGES}-page safety cap \u2014 refusing a partial census`,"non-retryable")}pages+=1;const sep=path.includes("?")?"&":"?";const searchable=path.includes("/messages")||path.includes("/threads");const q=`${sep}maxResults=500${searchable&&this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const r=this.get(grant,`${path}${q}`,what);if(!isOk(r))return r;const parsed=this.parseListIds(r.ok,listKey,what);if(!isOk(parsed))return parsed;for(const id of parsed.ok.ids)out.push(id);if(out.length>this.cap){return connectorError("resource_exhausted",`gmail ${what} enumeration exceeded the ${this.cap} cap \u2014 refusing a partial census (loud, never a silent truncation that would misreconcile FM-18); narrow the sync window`,"non-retryable")}if(parsed.ok.nextPageToken===null)return ok(out);if(seenPageTokens.has(parsed.ok.nextPageToken)){return connectorError("data_loss",`gmail ${what} census repeated a provider page token \u2014 refusing a partial census`,"non-retryable")}seenPageTokens.add(parsed.ok.nextPageToken);pageToken=parsed.ok.nextPageToken}}parseListIds(o,listKey,what){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal",`gmail ${what}: response is not an object \u2014 REST-surface drift (FM-19)`)}const raw=o[listKey];const ids=[];if(raw!==void 0){if(!Array.isArray(raw)){return connectorError("internal",`gmail ${what}: \`${listKey}\` is not an array \u2014 REST-surface drift (FM-19)`)}for(const row of raw){const id=row?.id;if(typeof id!=="string"||id===""){return connectorError("internal",`gmail ${what}: a row is missing a string \`id\` \u2014 REST-surface drift (FM-19)`)}ids.push(id)}}const next=o.nextPageToken;if(next!==void 0&&typeof next!=="string"){return connectorError("internal",`gmail ${what}: nextPageToken is not a string \u2014 REST-surface drift (FM-19)`)}return ok({ids,nextPageToken:typeof next==="string"&&next!==""?next:null})}parseIdList(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail messages.list: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const raw=rec.messages;const ids=[];if(raw!==void 0){if(!Array.isArray(raw)){return connectorError("internal","gmail messages.list: `messages` is not an array \u2014 REST-surface drift (FM-19)")}for(const m of raw){const id=m?.id;if(typeof id!=="string"||id===""){return connectorError("internal","gmail messages.list: a row is missing a string `id` \u2014 REST-surface drift (FM-19)")}const threadId=m.threadId;ids.push({id,...typeof threadId==="string"?{threadId}:{}})}}const next=rec.nextPageToken;if(next!==void 0&&typeof next!=="string"){return connectorError("internal","gmail messages.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)")}return ok({ids,nextPageToken:typeof next==="string"&&next!==""?next:null})}census(grant){const msgs=this.enumerateAll(grant,"/users/me/messages?includeSpamTrash=true","messages","messages.list");if(!isOk(msgs))return msgs;const labelsR=this.labels(grant);if(!isOk(labelsR))return labelsR;const threads=this.enumerateAll(grant,"/users/me/threads?includeSpamTrash=true","threads","threads.list");if(!isOk(threads))return threads;const drafts=this.enumerateAll(grant,"/users/me/drafts","drafts","drafts.list");if(!isOk(drafts))return drafts;return ok({messages:{total:msgs.ok.length},labels:{total:labelsR.ok.length},threads:{total:threads.ok.length},drafts:{total:drafts.ok.length}})}messagesPage(grant,pageToken,maxMessages){const acct=this.account(grant);if(!isOk(acct))return acct;if(this.messageLimit!==null&&pageToken!==null){return connectorError("invalid_argument","gmail starter source has one bounded page","non-retryable")}const wanted=this.messageLimit===null?maxMessages:maxMessages===void 0?this.messageLimit:Math.min(maxMessages,this.messageLimit);const pageSize=wanted===void 0?this.pageSize:Math.min(this.pageSize,wanted);const q=`maxResults=${pageSize}&includeSpamTrash=true${this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const listR=this.get(grant,`/users/me/messages?${q}`,"messages.list");if(!isOk(listR))return listR;const parsed=this.parseIdList(listR.ok);if(!isOk(parsed))return parsed;if(wanted!==void 0&&parsed.ok.ids.length>wanted){return connectorError("data_loss",`gmail messages.list returned ${parsed.ok.ids.length} IDs for a requested page size of ${wanted}`,"non-retryable")}const ids=(wanted===void 0?parsed.ok.ids:parsed.ok.ids.slice(0,wanted)).map(({id})=>id);const headersParam=this.messageFormat==="metadata"?GMAIL_METADATA_HEADERS.map(h=>`&metadataHeaders=${h}`).join(""):"";const messages=[];const attachments=[];this.hint(grant,ids,headersParam);const hydrated=this.hydrateMessages(grant,acct.ok,ids,false);if(!isOk(hydrated))return hydrated;messages.push(...hydrated.ok.messages);attachments.push(...hydrated.ok.attachments);return ok({messages:this.starterContentBytes===null?messages:capStarterContent(messages,this.starterContentBytes),attachments,nextPageToken:this.messageLimit===null?parsed.ok.nextPageToken:null})}messageCensus(grant){const ids=this.enumerateAll(grant,`/users/me/messages?includeSpamTrash=true${this.query===void 0?"":`&q=${encodeURIComponent(this.query)}`}`,"messages","messages.list");if(!isOk(ids))return ids;return ok(ids.ok.length)}hydrateMessages(grant,account,ids,skipGone){const headersParam=this.messageFormat==="metadata"?GMAIL_METADATA_HEADERS.map(h=>`&metadataHeaders=${h}`).join(""):"";const messages=[];const attachments=[];const keep=raw=>{const m=this.parseMessage(raw,account);if(!isOk(m))return m;messages.push(this.messageFormat==="metadata"?{...m.ok,starterContentOmitted:"fields-metadata"}:m.ok);if(this.messageFormat==="full"&&this.messageLimit===null&&this.fetchAttachments){const att=this.attachmentsFor(grant,m.ok);if(!isOk(att))return att;for(const a of att.ok)attachments.push(a)}return ok(true)};if(!skipGone){for(const chunk of chunkIds([...ids],GMAIL_BATCH_CHUNK_SIZE)){const batch=this.batchGetMessages(grant,chunk,headersParam);if(!isOk(batch))return batch;for(const id of chunk){const kept=keep(batch.ok.get(id));if(!isOk(kept))return kept}}return ok({messages,attachments})}for(const id of ids){const getR=this.get(grant,`/users/me/messages/${encodeURIComponent(id)}?format=${this.messageFormat}${headersParam}`,"messages.get");if(!isOk(getR)){if(skipGone&&getR.err.code==="not_found")continue;return getR}const m=this.parseMessage(getR.ok,account);if(!isOk(m))return m;messages.push(this.messageFormat==="metadata"?{...m.ok,starterContentOmitted:"fields-metadata"}:m.ok);if(this.messageFormat==="full"&&this.messageLimit===null&&this.fetchAttachments){const att=this.attachmentsFor(grant,m.ok);if(!isOk(att))return att;for(const a of att.ok)attachments.push(a)}}return ok({messages,attachments})}listMessageIdsPage(grant,scope,pageToken,maxPages){const base=this.query===void 0?scope==="recent"?GMAIL_AUDIT_RECENT_QUERY:void 0:scope==="recent"?`(${this.query}) ${GMAIL_AUDIT_RECENT_QUERY}`:this.query;const ids=[];let token=pageToken;for(let pages=0;pages<Math.max(1,maxPages);pages++){const r=this.get(grant,`/users/me/messages?includeSpamTrash=true&maxResults=500${base===void 0?"":`&q=${encodeURIComponent(base)}`}${token!==null?`&pageToken=${encodeURIComponent(token)}`:""}`,"messages.list");if(!isOk(r))return r;const parsed=this.parseListIds(r.ok,"messages","messages.list");if(!isOk(parsed))return parsed;for(const id of parsed.ok.ids)ids.push(id);token=parsed.ok.nextPageToken;if(token===null)break}return ok({ids,nextPageToken:token})}messageEvidence(grant,id){const hdrs=this.authHeaders(grant);if(!isOk(hdrs))return hdrs;const res=this.transport(`${GMAIL_API_BASE}/users/me/messages/${encodeURIComponent(id)}?format=minimal`,hdrs.ok);if(!res.ok){if(res.structuredError!==void 0)return{err:res.structuredError};if(res.error===GMAIL_WAN_GATE)return gateRefusal("gmail live WAN transport",GMAIL_WAN_GATE);return connectorError("unavailable",`gmail messages.get (audit evidence) transport failure: ${res.error} \u2014 never "not-found" (FM-21)`,"transient")}const answer=readByIdAnswerV1(res.status,{provider:"gmail",what:"messages.get (audit evidence)",bodyOverride:googleStatusOverrideV1(res.body),...googleErrorReasonV1(res.body)===void 0?{}:{detail:googleErrorReasonV1(res.body)}});if("err"in answer)return answer;if(answer.ok==="not-found")return ok("not-found");let body;try{body=JSON.parse(res.body)}catch{return connectorError("internal","gmail messages.get (audit evidence): 200 body is not JSON \u2014 REST-surface drift (FM-19)")}const labels=body!==null&&typeof body==="object"?body.labelIds:void 0;return ok(Array.isArray(labels)&&labels.includes("TRASH")?"trashed":"present")}messagesByIds(grant,ids){const acct=this.account(grant);if(!isOk(acct))return acct;return this.hydrateMessages(grant,acct.ok,ids,true)}messageChanges(grant,sinceHistoryId,maxMessages){const acct=this.account(grant);if(!isOk(acct))return acct;const changed=[];const seen=new Set;const deletions=[];const deletedIds=new Set;let pageToken=null;let pages=0;let lastRecord=null;let mailboxHistoryId=null;let more=false;walk:for(;;){const types=["messageAdded","labelAdded","labelRemoved","messageDeleted"].map(t=>`&historyTypes=${t}`).join("");const q=`startHistoryId=${encodeURIComponent(sinceHistoryId)}${types}&maxResults=500${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const r=this.get(grant,`/users/me/history?${q}`,"history.list");if(!isOk(r))return r;const parsed=this.parseHistoryChanges(r.ok);if(!isOk(parsed))return parsed;mailboxHistoryId=parsed.ok.historyId??mailboxHistoryId;for(const record of parsed.ok.records){const fresh=record.changed.filter(id=>!seen.has(id));if(changed.length>0&&changed.length+fresh.length>maxMessages){more=true;break walk}for(const id of fresh){seen.add(id);changed.push(id)}for(const id of record.deleted){deletedIds.add(id);deletions.push({account:acct.ok,id,atHistoryId:record.id})}lastRecord=record.id}if(++pages>GMAIL_HISTORY_MAX_PAGES){return connectorError("resource_exhausted",`gmail history.list pagination exceeded ${GMAIL_HISTORY_MAX_PAGES} pages \u2014 pageToken-cycle drift (FM-19)`,"non-retryable")}if(parsed.ok.nextPageToken===null)break;pageToken=parsed.ok.nextPageToken}const hydrated=this.hydrateMessages(grant,acct.ok,changed.filter(id=>!deletedIds.has(id)),true);if(!isOk(hydrated))return hydrated;return ok({...hydrated.ok,deletions,historyId:more?lastRecord:mailboxHistoryId??lastRecord,more})}parseHistoryChanges(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail history.list: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const records=[];if(rec.history!==void 0){if(!Array.isArray(rec.history))return connectorError("internal","gmail history.list: `history` is not an array \u2014 REST-surface drift (FM-19)");for(const record of rec.history){const id=record?.id;if(typeof id!=="string"||id==="")return connectorError("internal","gmail history.list: a history record is missing string `id` \u2014 REST-surface drift (FM-19)");const idsOf=key=>{const rows=record[key];if(rows===void 0)return ok([]);if(!Array.isArray(rows))return connectorError("internal",`gmail history.list: \`${key}\` is not an array \u2014 REST-surface drift (FM-19)`);const out=[];for(const row of rows){const mid=row?.message?.id;if(typeof mid!=="string"||mid==="")return connectorError("internal",`gmail history.list: a ${key} row is missing message.id \u2014 REST-surface drift (FM-19)`);out.push(mid)}return ok(out)};const added=idsOf("messagesAdded");const labelled=idsOf("labelsAdded");const unlabelled=idsOf("labelsRemoved");const deleted=idsOf("messagesDeleted");for(const part of[added,labelled,unlabelled,deleted])if(!isOk(part))return part;records.push({id,changed:[...added.ok,...labelled.ok,...unlabelled.ok],deleted:deleted.ok})}}const next=rec.nextPageToken;if(next!==void 0&&typeof next!=="string")return connectorError("internal","gmail history.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)");const hid=rec.historyId;return ok({records,nextPageToken:typeof next==="string"&&next!==""?next:null,historyId:typeof hid==="string"&&hid!==""?hid:null})}attachmentsFor(grant,m){const descriptors=this.collectAttachments(m.payload);const out=[];for(const d of descriptors){const base={account:m.account,messageId:m.id,...m.threadId!==void 0?{threadId:m.threadId}:{},partId:d.partId,attachmentId:d.attachmentId,filename:d.filename,mimeType:d.mimeType,size:d.size,...m.internalDate!==void 0?{internalDate:m.internalDate}:{}};if(d.size>this.attachmentCap||d.size>GMAIL_ATTACHMENT_TRANSPORT_SAFE_BYTES){out.push({...base,contentOmitted:"over-cap"});continue}const bodyR=this.get(grant,`/users/me/messages/${encodeURIComponent(m.id)}/attachments/${encodeURIComponent(d.attachmentId)}`,"messages.attachments.get");if(!isOk(bodyR))return bodyR;const parsed=this.parseAttachmentBody(bodyR.ok);if(!isOk(parsed))return parsed;const bytes=Buffer.from(parsed.ok.data,"base64url");const content=buildAttachmentContent(d.mimeType,bytes,this.attachmentCap);out.push({...base,size:bytes.length,...content})}return ok(out)}collectAttachments(payload){const out=[];const walk=(part,path)=>{const attId=part.body?.attachmentId;if(typeof attId==="string"&&attId!==""){const partId=typeof part.partId==="string"&&part.partId!==""?part.partId:path;out.push({partId,attachmentId:attId,filename:typeof part.filename==="string"?part.filename:"",mimeType:typeof part.mimeType==="string"?part.mimeType:"application/octet-stream",size:typeof part.body?.size==="number"?part.body.size:0})}const parts2=part.parts??[];for(let i=0;i<parts2.length;i++)walk(parts2[i],path===""?String(i):`${path}.${i}`)};if(payload!==void 0)walk(payload,"");return out}parseAttachmentBody(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail attachments.get: response is not an object \u2014 REST-surface drift (FM-19)")}const data=o.data;if(typeof data!=="string"){return connectorError("internal","gmail attachments.get: missing string `data` (the attachment bytes) \u2014 REST-surface drift (FM-19)")}const size=o.size;return ok({size:typeof size==="number"?size:0,data})}parseMessage(o,account){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail messages.get: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const id=rec["id"];if(typeof id!=="string"||id===""){return connectorError("internal","gmail messages.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)")}const historyId=rec["historyId"];if(typeof historyId!=="string"||historyId===""){return connectorError("internal",`gmail messages.get '${id}': missing string \`historyId\` (the upstream-version rev token) \u2014 REST-surface drift (FM-19)`)}return ok({...rec,account})}threadsByIds(grant,ids){const acct=this.account(grant);if(!isOk(acct))return acct;const threads=[];for(const id of ids){const getR=this.get(grant,`/users/me/threads/${encodeURIComponent(id)}?format=metadata`,"threads.get");if(!isOk(getR)){if(getR.err.code==="not_found")continue;return getR}const t=this.parseThread(getR.ok,acct.ok);if(!isOk(t))return t;threads.push(t.ok)}return ok({threads})}threadsPage(grant,pageToken){let pageIds;let consumed;let nextProviderPageToken;if(pageToken!==null&&typeof pageToken!=="string"){const continuation=this.validateThreadContinuation(pageToken);if(!isOk(continuation))return continuation;pageIds=continuation.ok.ids;consumed=continuation.ok.consumed;nextProviderPageToken=continuation.ok.nextProviderPageToken}else{consumed=0;const providerPageToken=pageToken;const q=`maxResults=${this.pageSize}&includeSpamTrash=true${this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${providerPageToken!==null?`&pageToken=${encodeURIComponent(providerPageToken)}`:""}`;const listR=this.get(grant,`/users/me/threads?${q}`,"threads.list");if(!isOk(listR))return listR;const parsed=this.parseListIds(listR.ok,"threads","threads.list");if(!isOk(parsed))return parsed;pageIds=parsed.ok.ids;nextProviderPageToken=parsed.ok.nextPageToken}const acct=this.account(grant);if(!isOk(acct))return acct;const threads=[];let pageBytes=0;let largestThreadBytes=0;for(let i=consumed;i<pageIds.length;i++){const id=pageIds[i];const getR=this.get(grant,`/users/me/threads/${encodeURIComponent(id)}?format=metadata`,"threads.get");if(!isOk(getR))return getR;const t=this.parseThread(getR.ok,acct.ok);if(!isOk(t))return t;threads.push(t.ok);const threadBytes=new TextEncoder().encode(JSON.stringify(getR.ok)).byteLength;pageBytes+=threadBytes;largestThreadBytes=Math.max(largestThreadBytes,threadBytes);const nextConsumed=i+1;if(pageBytes+largestThreadBytes>this.threadPageByteBudget&&nextConsumed<pageIds.length){return ok({threads,nextPageToken:{kind:"gmail-thread-page-v1",ids:[...pageIds],consumed:nextConsumed,nextProviderPageToken}})}}return ok({threads,nextPageToken:nextProviderPageToken})}validateThreadContinuation(value){if(value===null||typeof value!=="object"||Array.isArray(value)){return connectorError("invalid_argument","gmail threads continuation must be a stable page-identity object")}const row=value;if(row["kind"]!=="gmail-thread-page-v1"){return connectorError("invalid_argument","gmail threads continuation has an unknown version")}const ids=row["ids"];if(!Array.isArray(ids)||ids.length===0||ids.some(id=>typeof id!=="string"||id==="")){return connectorError("invalid_argument","gmail threads continuation ids must be a non-empty provider-id page")}const consumed=row["consumed"];if(!Number.isSafeInteger(consumed)||consumed<=0||consumed>=ids.length){return connectorError("invalid_argument",`gmail threads continuation boundary '${String(consumed)}' is outside its ${ids.length}-id stable page`)}const nextProviderPageToken=row["nextProviderPageToken"];if(nextProviderPageToken!==null&&typeof nextProviderPageToken!=="string"){return connectorError("invalid_argument","gmail threads continuation next provider token must be an opaque string or null")}return ok({kind:"gmail-thread-page-v1",ids:[...ids],consumed,nextProviderPageToken})}parseThread(o,account){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail threads.get: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const id=rec["id"];if(typeof id!=="string"||id===""){return connectorError("internal","gmail threads.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)")}const historyId=rec["historyId"];if(typeof historyId!=="string"||historyId===""){return connectorError("internal",`gmail threads.get '${id}': missing string \`historyId\` (the upstream-version rev token) \u2014 REST-surface drift (FM-19)`)}let messages;const rawMsgs=rec["messages"];if(rawMsgs!==void 0){if(!Array.isArray(rawMsgs)){return connectorError("internal",`gmail threads.get '${id}': \`messages\` is not an array \u2014 REST-surface drift (FM-19)`)}messages=[];for(const rm of rawMsgs){const pm=this.parseMessage(rm,account);if(!isOk(pm))return pm;messages.push(pm.ok)}}return ok({...rec,account,...messages!==void 0?{messages}:{}})}draftsPage(grant,pageToken){const acct=this.account(grant);if(!isOk(acct))return acct;const q=`maxResults=${this.pageSize}${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const listR=this.get(grant,`/users/me/drafts?${q}`,"drafts.list");if(!isOk(listR))return listR;const parsed=this.parseListIds(listR.ok,"drafts","drafts.list");if(!isOk(parsed))return parsed;const drafts=[];this.hintGets(grant,parsed.ok.ids.map(id=>`/users/me/drafts/${encodeURIComponent(id)}?format=full`));for(const id of parsed.ok.ids){const getR=this.get(grant,`/users/me/drafts/${encodeURIComponent(id)}?format=full`,"drafts.get");if(!isOk(getR))return getR;const d=this.parseDraft(getR.ok,acct.ok);if(!isOk(d))return d;drafts.push(d.ok)}return ok({drafts,nextPageToken:parsed.ok.nextPageToken})}parseDraft(o,account){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail drafts.get: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const id=rec["id"];if(typeof id!=="string"||id===""){return connectorError("internal","gmail drafts.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)")}const msg=this.parseMessage(rec["message"],account);if(!isOk(msg))return msg;return ok({...rec,account,id,message:msg.ok})}labels(grant){const acct=this.account(grant);if(!isOk(acct))return acct;const r=this.get(grant,"/users/me/labels","labels.list");if(!isOk(r))return r;const o=r.ok;if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail labels.list: response is not an object \u2014 REST-surface drift (FM-19)")}const raw=o.labels;if(raw===void 0)return ok([]);if(!Array.isArray(raw)){return connectorError("internal","gmail labels.list: `labels` is not an array \u2014 REST-surface drift (FM-19)")}const out=[];for(const l of raw){const id=l?.id;const name=l.name;if(typeof id!=="string"||id===""){return connectorError("internal","gmail labels.list: a label is missing a string `id` \u2014 REST-surface drift (FM-19)")}if(typeof name!=="string"){return connectorError("internal",`gmail labels.list: label '${id}' is missing a string \`name\` \u2014 REST-surface drift (FM-19)`)}out.push({...l,account:acct.ok})}return ok(out)}parseHistoryDeletions(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail history.list: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const rows=[];if(rec.history!==void 0){if(!Array.isArray(rec.history)){return connectorError("internal","gmail history.list: `history` is not an array \u2014 REST-surface drift (FM-19)")}for(const record of rec.history){const recordId=record?.id;if(typeof recordId!=="string"||recordId===""){return connectorError("internal","gmail history.list: a history record is missing string `id` \u2014 REST-surface drift (FM-19)")}const deleted=record?.messagesDeleted;if(deleted===void 0)continue;if(!Array.isArray(deleted)){return connectorError("internal","gmail history.list: `messagesDeleted` is not an array \u2014 REST-surface drift (FM-19)")}for(const row of deleted){const id=row?.message?.id;if(typeof id!=="string"||id===""){return connectorError("internal","gmail history.list: a messagesDeleted row is missing message.id \u2014 REST-surface drift (FM-19)")}rows.push({id,atHistoryId:recordId})}}}const next=rec.nextPageToken;if(next!==void 0&&typeof next!=="string"){return connectorError("internal","gmail history.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)")}return ok({rows,nextPageToken:typeof next==="string"&&next!==""?next:null})}messageDeletions(grant,sinceHistoryId){const acct=this.account(grant);if(!isOk(acct))return acct;const out=[];let pageToken=null;let pages=0;for(;;){const q=`startHistoryId=${encodeURIComponent(sinceHistoryId)}&historyTypes=messageDeleted${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const r=this.get(grant,`/users/me/history?${q}`,"history.list");if(!isOk(r))return r;const parsed=this.parseHistoryDeletions(r.ok);if(!isOk(parsed))return parsed;for(const row of parsed.ok.rows)out.push({account:acct.ok,id:row.id,atHistoryId:row.atHistoryId});if(out.length>GMAIL_DELETIONS_CAP){return connectorError("resource_exhausted",`gmail history.list deletions exceeded the ${GMAIL_DELETIONS_CAP} cap \u2014 refusing a partial sweep (loud, never a silent truncation)`,"non-retryable")}if(++pages>GMAIL_HISTORY_MAX_PAGES){return connectorError("resource_exhausted",`gmail history.list pagination exceeded ${GMAIL_HISTORY_MAX_PAGES} pages \u2014 pageToken-cycle drift (FM-19)`,"non-retryable")}if(parsed.ok.nextPageToken===null)return ok(out);pageToken=parsed.ok.nextPageToken}}}return{GMAIL_AUDIT_RECENT_QUERY,GMAIL_MESSAGE_PULL_CAP,GMAIL_CENSUS_MAX_PAGES,GMAIL_THREAD_PAGE_BYTE_BUDGET,GMAIL_DELETIONS_CAP,GMAIL_HISTORY_MAX_PAGES,GMAIL_ATTACHMENT_CONTENT_CAP,GMAIL_ATTACHMENT_TRANSPORT_SAFE_BYTES,GMAIL_API_BASE,GMAIL_BATCH_URL,GMAIL_BATCH_CHUNK_SIZE,GMAIL_WAN_GATE,refuseWanTransport,buildAttachmentContent,GMAIL_METADATA_HEADERS,GMAIL_STARTER_MESSAGE_LIMIT,GMAIL_STARTER_CONTENT_BYTES,capStarterContent,HttpGmailSource}}
8
+ `;return{url:GMAIL_BATCH_URL,headers:{...headers,"Content-Type":`multipart/mixed; boundary=${boundary}`},method:"POST",body}}hint(grant,ids,headersParam){if(this.prefetch===void 0||ids.length===0)return;const hdrs=this.authHeaders(grant);if(!isOk(hdrs))return;for(const chunk of chunkIds(ids,GMAIL_BATCH_CHUNK_SIZE)){this.prefetch([this.batchRequest(chunk,headersParam,hdrs.ok)])}}hintGets(grant,paths){if(this.prefetch===void 0||paths.length===0)return;const headers=this.authHeaders(grant);if(!isOk(headers))return;this.prefetch(paths.map(path=>({url:`${GMAIL_API_BASE}${path}`,headers:headers.ok,method:"GET"})))}static create(opts){return new HttpGmailSource(opts.transport??refuseWanTransport,opts.authHeaders,opts.cap??GMAIL_MESSAGE_PULL_CAP,opts.pageSize??100,opts.attachmentCap??GMAIL_ATTACHMENT_CONTENT_CAP,opts.query!==void 0&&opts.query.trim()!==""?opts.query.trim():void 0,opts.selectedMessageIds===void 0?void 0:[...new Set(opts.selectedMessageIds.filter(id=>typeof id==="string"&&id!==""))],opts.messageFormat??"full",opts.messageLimit??null,opts.starterContentBytes??null,opts.fetchAttachments??true,opts.prefetch,opts.threadPageByteBudget??GMAIL_THREAD_PAGE_BYTE_BUDGET)}get(grant,path,what){const hdrs=this.authHeaders(grant);if(!isOk(hdrs))return hdrs;const res=this.transport(`${GMAIL_API_BASE}${path}`,hdrs.ok);if(!res.ok){if(res.structuredError!==void 0)return{err:res.structuredError};if(res.error===GMAIL_WAN_GATE)return gateRefusal("gmail live WAN transport",GMAIL_WAN_GATE);return connectorError("unavailable",`gmail ${what} transport failure: ${res.error} \u2014 NEVER an empty success (FM-21)`,"transient")}return this.routeStatus(res.status,res.body,what)}routeStatus(status,body,what){if(status===200){try{return ok(JSON.parse(body))}catch{return connectorError("internal",`gmail ${what}: 200 body is not JSON \u2014 REST-surface drift (FM-19)`)}}return{err:webStatusErrorV1(status,{provider:"gmail",what,bodyOverride:googleStatusOverrideV1(body),...googleErrorReasonV1(body)===void 0?{}:{detail:googleErrorReasonV1(body)}})}}batchGetMessages(grant,ids,headersParam){const auth=this.authHeaders(grant);if(!isOk(auth))return auth;const request=this.batchRequest(ids,headersParam,auth.ok);const response=this.transport(request.url,request.headers,{method:request.method,body:request.body});if(!response.ok){if(response.structuredError!==void 0)return{err:response.structuredError};if(response.error===GMAIL_WAN_GATE)return gateRefusal("gmail live WAN transport",GMAIL_WAN_GATE);return connectorError("unavailable",`gmail messages.batchGet transport failure: ${response.error} \u2014 NEVER an empty success (FM-21)`,"transient")}if(response.status!==200)return this.routeStatus(response.status,response.body,"messages.batchGet");const parts2=splitMultipartMixed(response.body);if(parts2===null)return connectorError("internal","gmail messages.batchGet: malformed multipart response \u2014 REST-surface drift (FM-19)");const out=new Map;const throttled=[];for(const part of parts2){if(part.contentId===null)return connectorError("internal","gmail messages.batchGet: missing Content-ID \u2014 cannot correlate response (FM-19)");const contentId=part.contentId.replace(/^response-/,"");const id=ids.find(candidate=>contentId===candidate||contentId.endsWith(`/${candidate}`));if(id===void 0||out.has(id)||throttled.includes(id))return connectorError("internal",`gmail messages.batchGet: unexpected or duplicate Content-ID '${part.contentId}' (FM-19)`);const routed=this.routeStatus(part.status,part.body,"messages.get");if(!isOk(routed)){if("err"in routed&&routed.err.retryability==="throttling"){throttled.push(id);continue}return routed}out.set(id,routed.ok)}for(const id of throttled){const single=this.get(grant,`/users/me/messages/${encodeURIComponent(id)}?format=${this.messageFormat}${headersParam}`,"messages.get");if(!isOk(single))return single;out.set(id,single.ok)}for(const id of ids){if(!out.has(id))return connectorError("internal",`gmail messages.batchGet: response omitted message '${id}' (FM-19)`)}return ok(out)}account(grant){if(this.resolvedAccount!==null)return ok(this.resolvedAccount);const p=this.getProfile(grant);if(!isOk(p))return p;this.resolvedAccount=p.ok.emailAddress;return ok(this.resolvedAccount)}getProfile(grant){const r=this.get(grant,"/users/me/profile","getProfile");if(!isOk(r))return r;const o=r.ok;if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail getProfile: response is not an object \u2014 REST-surface drift (FM-19)")}const email=o.emailAddress;if(typeof email!=="string"||email===""){return connectorError("internal","gmail getProfile: emailAddress missing \u2014 cannot source the account epoch (REST-surface drift, FM-19)")}return ok(o)}enumerateAll(grant,path,listKey,what){const out=[];let pageToken=null;const seenPageTokens=new Set;let pages=0;for(;;){if(pages>=GMAIL_CENSUS_MAX_PAGES){return connectorError("resource_exhausted",`gmail ${what} census exceeded the ${GMAIL_CENSUS_MAX_PAGES}-page safety cap \u2014 refusing a partial census`,"non-retryable")}pages+=1;const sep=path.includes("?")?"&":"?";const searchable=path.includes("/messages")||path.includes("/threads");const q=`${sep}maxResults=500${searchable&&this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const r=this.get(grant,`${path}${q}`,what);if(!isOk(r))return r;const parsed=this.parseListIds(r.ok,listKey,what);if(!isOk(parsed))return parsed;for(const id of parsed.ok.ids)out.push(id);if(out.length>this.cap){return connectorError("resource_exhausted",`gmail ${what} enumeration exceeded the ${this.cap} cap \u2014 refusing a partial census (loud, never a silent truncation that would misreconcile FM-18); narrow the sync window`,"non-retryable")}if(parsed.ok.nextPageToken===null)return ok(out);if(seenPageTokens.has(parsed.ok.nextPageToken)){return connectorError("data_loss",`gmail ${what} census repeated a provider page token \u2014 refusing a partial census`,"non-retryable")}seenPageTokens.add(parsed.ok.nextPageToken);pageToken=parsed.ok.nextPageToken}}parseListIds(o,listKey,what){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal",`gmail ${what}: response is not an object \u2014 REST-surface drift (FM-19)`)}const raw=o[listKey];const ids=[];if(raw!==void 0){if(!Array.isArray(raw)){return connectorError("internal",`gmail ${what}: \`${listKey}\` is not an array \u2014 REST-surface drift (FM-19)`)}for(const row of raw){const id=row?.id;if(typeof id!=="string"||id===""){return connectorError("internal",`gmail ${what}: a row is missing a string \`id\` \u2014 REST-surface drift (FM-19)`)}ids.push(id)}}const next=o.nextPageToken;if(next!==void 0&&typeof next!=="string"){return connectorError("internal",`gmail ${what}: nextPageToken is not a string \u2014 REST-surface drift (FM-19)`)}return ok({ids,nextPageToken:typeof next==="string"&&next!==""?next:null})}parseIdList(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail messages.list: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const raw=rec.messages;const ids=[];if(raw!==void 0){if(!Array.isArray(raw)){return connectorError("internal","gmail messages.list: `messages` is not an array \u2014 REST-surface drift (FM-19)")}for(const m of raw){const id=m?.id;if(typeof id!=="string"||id===""){return connectorError("internal","gmail messages.list: a row is missing a string `id` \u2014 REST-surface drift (FM-19)")}const threadId=m.threadId;ids.push({id,...typeof threadId==="string"?{threadId}:{}})}}const next=rec.nextPageToken;if(next!==void 0&&typeof next!=="string"){return connectorError("internal","gmail messages.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)")}return ok({ids,nextPageToken:typeof next==="string"&&next!==""?next:null})}census(grant){const msgs=this.enumerateAll(grant,"/users/me/messages?includeSpamTrash=true","messages","messages.list");if(!isOk(msgs))return msgs;const labelsR=this.labels(grant);if(!isOk(labelsR))return labelsR;const threads=this.enumerateAll(grant,"/users/me/threads?includeSpamTrash=true","threads","threads.list");if(!isOk(threads))return threads;const drafts=this.enumerateAll(grant,"/users/me/drafts","drafts","drafts.list");if(!isOk(drafts))return drafts;return ok({messages:{total:msgs.ok.length},labels:{total:labelsR.ok.length},threads:{total:threads.ok.length},drafts:{total:drafts.ok.length}})}messagesPage(grant,pageToken,maxMessages){const acct=this.account(grant);if(!isOk(acct))return acct;if(this.selectedMessageIds!==void 0){if(pageToken!==null){return connectorError("invalid_argument","gmail exact-id source has one bounded page","non-retryable")}const ids2=maxMessages===void 0?[...this.selectedMessageIds]:this.selectedMessageIds.slice(0,maxMessages);const headersParam2=this.messageFormat==="metadata"?GMAIL_METADATA_HEADERS.map(h=>`&metadataHeaders=${h}`).join(""):"";this.hint(grant,ids2,headersParam2);const hydrated2=this.hydrateMessages(grant,acct.ok,ids2,true);if(!isOk(hydrated2))return hydrated2;return ok({messages:this.starterContentBytes===null?hydrated2.ok.messages:capStarterContent(hydrated2.ok.messages,this.starterContentBytes),attachments:[],nextPageToken:null})}if(this.messageLimit!==null&&pageToken!==null){return connectorError("invalid_argument","gmail starter source has one bounded page","non-retryable")}const wanted=this.messageLimit===null?maxMessages:maxMessages===void 0?this.messageLimit:Math.min(maxMessages,this.messageLimit);const pageSize=wanted===void 0?this.pageSize:Math.min(this.pageSize,wanted);const q=`maxResults=${pageSize}&includeSpamTrash=true${this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const listR=this.get(grant,`/users/me/messages?${q}`,"messages.list");if(!isOk(listR))return listR;const parsed=this.parseIdList(listR.ok);if(!isOk(parsed))return parsed;if(wanted!==void 0&&parsed.ok.ids.length>wanted){return connectorError("data_loss",`gmail messages.list returned ${parsed.ok.ids.length} IDs for a requested page size of ${wanted}`,"non-retryable")}const ids=(wanted===void 0?parsed.ok.ids:parsed.ok.ids.slice(0,wanted)).map(({id})=>id);const headersParam=this.messageFormat==="metadata"?GMAIL_METADATA_HEADERS.map(h=>`&metadataHeaders=${h}`).join(""):"";const messages=[];const attachments=[];this.hint(grant,ids,headersParam);const hydrated=this.hydrateMessages(grant,acct.ok,ids,false);if(!isOk(hydrated))return hydrated;messages.push(...hydrated.ok.messages);attachments.push(...hydrated.ok.attachments);return ok({messages:this.starterContentBytes===null?messages:capStarterContent(messages,this.starterContentBytes),attachments,nextPageToken:this.messageLimit===null?parsed.ok.nextPageToken:null})}messageCensus(grant){const ids=this.enumerateAll(grant,`/users/me/messages?includeSpamTrash=true${this.query===void 0?"":`&q=${encodeURIComponent(this.query)}`}`,"messages","messages.list");if(!isOk(ids))return ids;return ok(ids.ok.length)}hydrateMessages(grant,account,ids,skipGone){const headersParam=this.messageFormat==="metadata"?GMAIL_METADATA_HEADERS.map(h=>`&metadataHeaders=${h}`).join(""):"";const messages=[];const attachments=[];const keep=raw=>{const m=this.parseMessage(raw,account);if(!isOk(m))return m;messages.push(this.messageFormat==="metadata"?{...m.ok,starterContentOmitted:"fields-metadata"}:m.ok);if(this.messageFormat==="full"&&this.messageLimit===null&&this.fetchAttachments){const att=this.attachmentsFor(grant,m.ok);if(!isOk(att))return att;for(const a of att.ok)attachments.push(a)}return ok(true)};if(!skipGone){for(const chunk of chunkIds([...ids],GMAIL_BATCH_CHUNK_SIZE)){const batch=this.batchGetMessages(grant,chunk,headersParam);if(!isOk(batch))return batch;for(const id of chunk){const kept=keep(batch.ok.get(id));if(!isOk(kept))return kept}}return ok({messages,attachments})}for(const id of ids){const getR=this.get(grant,`/users/me/messages/${encodeURIComponent(id)}?format=${this.messageFormat}${headersParam}`,"messages.get");if(!isOk(getR)){if(skipGone&&getR.err.code==="not_found")continue;return getR}const m=this.parseMessage(getR.ok,account);if(!isOk(m))return m;messages.push(this.messageFormat==="metadata"?{...m.ok,starterContentOmitted:"fields-metadata"}:m.ok);if(this.messageFormat==="full"&&this.messageLimit===null&&this.fetchAttachments){const att=this.attachmentsFor(grant,m.ok);if(!isOk(att))return att;for(const a of att.ok)attachments.push(a)}}return ok({messages,attachments})}listMessageIdsPage(grant,scope,pageToken,maxPages){const base=this.query===void 0?scope==="recent"?GMAIL_AUDIT_RECENT_QUERY:void 0:scope==="recent"?`(${this.query}) ${GMAIL_AUDIT_RECENT_QUERY}`:this.query;const ids=[];let token=pageToken;for(let pages=0;pages<Math.max(1,maxPages);pages++){const r=this.get(grant,`/users/me/messages?includeSpamTrash=true&maxResults=500${base===void 0?"":`&q=${encodeURIComponent(base)}`}${token!==null?`&pageToken=${encodeURIComponent(token)}`:""}`,"messages.list");if(!isOk(r))return r;const parsed=this.parseListIds(r.ok,"messages","messages.list");if(!isOk(parsed))return parsed;for(const id of parsed.ok.ids)ids.push(id);token=parsed.ok.nextPageToken;if(token===null)break}return ok({ids,nextPageToken:token})}messageEvidence(grant,id){const hdrs=this.authHeaders(grant);if(!isOk(hdrs))return hdrs;const res=this.transport(`${GMAIL_API_BASE}/users/me/messages/${encodeURIComponent(id)}?format=minimal`,hdrs.ok);if(!res.ok){if(res.structuredError!==void 0)return{err:res.structuredError};if(res.error===GMAIL_WAN_GATE)return gateRefusal("gmail live WAN transport",GMAIL_WAN_GATE);return connectorError("unavailable",`gmail messages.get (audit evidence) transport failure: ${res.error} \u2014 never "not-found" (FM-21)`,"transient")}const answer=readByIdAnswerV1(res.status,{provider:"gmail",what:"messages.get (audit evidence)",bodyOverride:googleStatusOverrideV1(res.body),...googleErrorReasonV1(res.body)===void 0?{}:{detail:googleErrorReasonV1(res.body)}});if("err"in answer)return answer;if(answer.ok==="not-found")return ok("not-found");let body;try{body=JSON.parse(res.body)}catch{return connectorError("internal","gmail messages.get (audit evidence): 200 body is not JSON \u2014 REST-surface drift (FM-19)")}const labels=body!==null&&typeof body==="object"?body.labelIds:void 0;return ok(Array.isArray(labels)&&labels.includes("TRASH")?"trashed":"present")}messagesByIds(grant,ids){const acct=this.account(grant);if(!isOk(acct))return acct;return this.hydrateMessages(grant,acct.ok,ids,true)}messageChanges(grant,sinceHistoryId,maxMessages){const acct=this.account(grant);if(!isOk(acct))return acct;const changed=[];const seen=new Set;const deletions=[];const deletedIds=new Set;let pageToken=null;let pages=0;let lastRecord=null;let mailboxHistoryId=null;let more=false;walk:for(;;){const types=["messageAdded","labelAdded","labelRemoved","messageDeleted"].map(t=>`&historyTypes=${t}`).join("");const q=`startHistoryId=${encodeURIComponent(sinceHistoryId)}${types}&maxResults=500${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const r=this.get(grant,`/users/me/history?${q}`,"history.list");if(!isOk(r))return r;const parsed=this.parseHistoryChanges(r.ok);if(!isOk(parsed))return parsed;mailboxHistoryId=parsed.ok.historyId??mailboxHistoryId;for(const record of parsed.ok.records){const fresh=record.changed.filter(id=>!seen.has(id));if(changed.length>0&&changed.length+fresh.length>maxMessages){more=true;break walk}for(const id of fresh){seen.add(id);changed.push(id)}for(const id of record.deleted){deletedIds.add(id);deletions.push({account:acct.ok,id,atHistoryId:record.id})}lastRecord=record.id}if(++pages>GMAIL_HISTORY_MAX_PAGES){return connectorError("resource_exhausted",`gmail history.list pagination exceeded ${GMAIL_HISTORY_MAX_PAGES} pages \u2014 pageToken-cycle drift (FM-19)`,"non-retryable")}if(parsed.ok.nextPageToken===null)break;pageToken=parsed.ok.nextPageToken}const hydrated=this.hydrateMessages(grant,acct.ok,changed.filter(id=>!deletedIds.has(id)),true);if(!isOk(hydrated))return hydrated;return ok({...hydrated.ok,deletions,historyId:more?lastRecord:mailboxHistoryId??lastRecord,more})}parseHistoryChanges(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail history.list: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const records=[];if(rec.history!==void 0){if(!Array.isArray(rec.history))return connectorError("internal","gmail history.list: `history` is not an array \u2014 REST-surface drift (FM-19)");for(const record of rec.history){const id=record?.id;if(typeof id!=="string"||id==="")return connectorError("internal","gmail history.list: a history record is missing string `id` \u2014 REST-surface drift (FM-19)");const idsOf=key=>{const rows=record[key];if(rows===void 0)return ok([]);if(!Array.isArray(rows))return connectorError("internal",`gmail history.list: \`${key}\` is not an array \u2014 REST-surface drift (FM-19)`);const out=[];for(const row of rows){const mid=row?.message?.id;if(typeof mid!=="string"||mid==="")return connectorError("internal",`gmail history.list: a ${key} row is missing message.id \u2014 REST-surface drift (FM-19)`);out.push(mid)}return ok(out)};const added=idsOf("messagesAdded");const labelled=idsOf("labelsAdded");const unlabelled=idsOf("labelsRemoved");const deleted=idsOf("messagesDeleted");for(const part of[added,labelled,unlabelled,deleted])if(!isOk(part))return part;records.push({id,changed:[...added.ok,...labelled.ok,...unlabelled.ok],deleted:deleted.ok})}}const next=rec.nextPageToken;if(next!==void 0&&typeof next!=="string")return connectorError("internal","gmail history.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)");const hid=rec.historyId;return ok({records,nextPageToken:typeof next==="string"&&next!==""?next:null,historyId:typeof hid==="string"&&hid!==""?hid:null})}attachmentsFor(grant,m){const descriptors=this.collectAttachments(m.payload);const out=[];for(const d of descriptors){const base={account:m.account,messageId:m.id,...m.threadId!==void 0?{threadId:m.threadId}:{},partId:d.partId,attachmentId:d.attachmentId,filename:d.filename,mimeType:d.mimeType,size:d.size,...m.internalDate!==void 0?{internalDate:m.internalDate}:{}};if(d.size>this.attachmentCap||d.size>GMAIL_ATTACHMENT_TRANSPORT_SAFE_BYTES){out.push({...base,contentOmitted:"over-cap"});continue}const bodyR=this.get(grant,`/users/me/messages/${encodeURIComponent(m.id)}/attachments/${encodeURIComponent(d.attachmentId)}`,"messages.attachments.get");if(!isOk(bodyR))return bodyR;const parsed=this.parseAttachmentBody(bodyR.ok);if(!isOk(parsed))return parsed;const bytes=Buffer.from(parsed.ok.data,"base64url");const content=buildAttachmentContent(d.mimeType,bytes,this.attachmentCap);out.push({...base,size:bytes.length,...content})}return ok(out)}collectAttachments(payload){const out=[];const walk=(part,path)=>{const attId=part.body?.attachmentId;if(typeof attId==="string"&&attId!==""){const partId=typeof part.partId==="string"&&part.partId!==""?part.partId:path;out.push({partId,attachmentId:attId,filename:typeof part.filename==="string"?part.filename:"",mimeType:typeof part.mimeType==="string"?part.mimeType:"application/octet-stream",size:typeof part.body?.size==="number"?part.body.size:0})}const parts2=part.parts??[];for(let i=0;i<parts2.length;i++)walk(parts2[i],path===""?String(i):`${path}.${i}`)};if(payload!==void 0)walk(payload,"");return out}parseAttachmentBody(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail attachments.get: response is not an object \u2014 REST-surface drift (FM-19)")}const data=o.data;if(typeof data!=="string"){return connectorError("internal","gmail attachments.get: missing string `data` (the attachment bytes) \u2014 REST-surface drift (FM-19)")}const size=o.size;return ok({size:typeof size==="number"?size:0,data})}parseMessage(o,account){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail messages.get: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const id=rec["id"];if(typeof id!=="string"||id===""){return connectorError("internal","gmail messages.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)")}const historyId=rec["historyId"];if(typeof historyId!=="string"||historyId===""){return connectorError("internal",`gmail messages.get '${id}': missing string \`historyId\` (the upstream-version rev token) \u2014 REST-surface drift (FM-19)`)}return ok({...rec,account})}threadsByIds(grant,ids){const acct=this.account(grant);if(!isOk(acct))return acct;const threads=[];for(const id of ids){const getR=this.get(grant,`/users/me/threads/${encodeURIComponent(id)}?format=metadata`,"threads.get");if(!isOk(getR)){if(getR.err.code==="not_found")continue;return getR}const t=this.parseThread(getR.ok,acct.ok);if(!isOk(t))return t;threads.push(t.ok)}return ok({threads})}threadsPage(grant,pageToken){let pageIds;let consumed;let nextProviderPageToken;if(pageToken!==null&&typeof pageToken!=="string"){const continuation=this.validateThreadContinuation(pageToken);if(!isOk(continuation))return continuation;pageIds=continuation.ok.ids;consumed=continuation.ok.consumed;nextProviderPageToken=continuation.ok.nextProviderPageToken}else{consumed=0;const providerPageToken=pageToken;const q=`maxResults=${this.pageSize}&includeSpamTrash=true${this.query!==void 0?`&q=${encodeURIComponent(this.query)}`:""}${providerPageToken!==null?`&pageToken=${encodeURIComponent(providerPageToken)}`:""}`;const listR=this.get(grant,`/users/me/threads?${q}`,"threads.list");if(!isOk(listR))return listR;const parsed=this.parseListIds(listR.ok,"threads","threads.list");if(!isOk(parsed))return parsed;pageIds=parsed.ok.ids;nextProviderPageToken=parsed.ok.nextPageToken}const acct=this.account(grant);if(!isOk(acct))return acct;const threads=[];let pageBytes=0;let largestThreadBytes=0;for(let i=consumed;i<pageIds.length;i++){const id=pageIds[i];const getR=this.get(grant,`/users/me/threads/${encodeURIComponent(id)}?format=metadata`,"threads.get");if(!isOk(getR))return getR;const t=this.parseThread(getR.ok,acct.ok);if(!isOk(t))return t;threads.push(t.ok);const threadBytes=new TextEncoder().encode(JSON.stringify(getR.ok)).byteLength;pageBytes+=threadBytes;largestThreadBytes=Math.max(largestThreadBytes,threadBytes);const nextConsumed=i+1;if(pageBytes+largestThreadBytes>this.threadPageByteBudget&&nextConsumed<pageIds.length){return ok({threads,nextPageToken:{kind:"gmail-thread-page-v1",ids:[...pageIds],consumed:nextConsumed,nextProviderPageToken}})}}return ok({threads,nextPageToken:nextProviderPageToken})}validateThreadContinuation(value){if(value===null||typeof value!=="object"||Array.isArray(value)){return connectorError("invalid_argument","gmail threads continuation must be a stable page-identity object")}const row=value;if(row["kind"]!=="gmail-thread-page-v1"){return connectorError("invalid_argument","gmail threads continuation has an unknown version")}const ids=row["ids"];if(!Array.isArray(ids)||ids.length===0||ids.some(id=>typeof id!=="string"||id==="")){return connectorError("invalid_argument","gmail threads continuation ids must be a non-empty provider-id page")}const consumed=row["consumed"];if(!Number.isSafeInteger(consumed)||consumed<=0||consumed>=ids.length){return connectorError("invalid_argument",`gmail threads continuation boundary '${String(consumed)}' is outside its ${ids.length}-id stable page`)}const nextProviderPageToken=row["nextProviderPageToken"];if(nextProviderPageToken!==null&&typeof nextProviderPageToken!=="string"){return connectorError("invalid_argument","gmail threads continuation next provider token must be an opaque string or null")}return ok({kind:"gmail-thread-page-v1",ids:[...ids],consumed,nextProviderPageToken})}parseThread(o,account){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail threads.get: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const id=rec["id"];if(typeof id!=="string"||id===""){return connectorError("internal","gmail threads.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)")}const historyId=rec["historyId"];if(typeof historyId!=="string"||historyId===""){return connectorError("internal",`gmail threads.get '${id}': missing string \`historyId\` (the upstream-version rev token) \u2014 REST-surface drift (FM-19)`)}let messages;const rawMsgs=rec["messages"];if(rawMsgs!==void 0){if(!Array.isArray(rawMsgs)){return connectorError("internal",`gmail threads.get '${id}': \`messages\` is not an array \u2014 REST-surface drift (FM-19)`)}messages=[];for(const rm of rawMsgs){const pm=this.parseMessage(rm,account);if(!isOk(pm))return pm;messages.push(pm.ok)}}return ok({...rec,account,...messages!==void 0?{messages}:{}})}draftsPage(grant,pageToken){const acct=this.account(grant);if(!isOk(acct))return acct;const q=`maxResults=${this.pageSize}${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const listR=this.get(grant,`/users/me/drafts?${q}`,"drafts.list");if(!isOk(listR))return listR;const parsed=this.parseListIds(listR.ok,"drafts","drafts.list");if(!isOk(parsed))return parsed;const drafts=[];this.hintGets(grant,parsed.ok.ids.map(id=>`/users/me/drafts/${encodeURIComponent(id)}?format=full`));for(const id of parsed.ok.ids){const getR=this.get(grant,`/users/me/drafts/${encodeURIComponent(id)}?format=full`,"drafts.get");if(!isOk(getR))return getR;const d=this.parseDraft(getR.ok,acct.ok);if(!isOk(d))return d;drafts.push(d.ok)}return ok({drafts,nextPageToken:parsed.ok.nextPageToken})}parseDraft(o,account){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail drafts.get: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const id=rec["id"];if(typeof id!=="string"||id===""){return connectorError("internal","gmail drafts.get: missing string `id` (the durable identity) \u2014 REST-surface drift (FM-19)")}const msg=this.parseMessage(rec["message"],account);if(!isOk(msg))return msg;return ok({...rec,account,id,message:msg.ok})}labels(grant){const acct=this.account(grant);if(!isOk(acct))return acct;const r=this.get(grant,"/users/me/labels","labels.list");if(!isOk(r))return r;const o=r.ok;if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail labels.list: response is not an object \u2014 REST-surface drift (FM-19)")}const raw=o.labels;if(raw===void 0)return ok([]);if(!Array.isArray(raw)){return connectorError("internal","gmail labels.list: `labels` is not an array \u2014 REST-surface drift (FM-19)")}const out=[];for(const l of raw){const id=l?.id;const name=l.name;if(typeof id!=="string"||id===""){return connectorError("internal","gmail labels.list: a label is missing a string `id` \u2014 REST-surface drift (FM-19)")}if(typeof name!=="string"){return connectorError("internal",`gmail labels.list: label '${id}' is missing a string \`name\` \u2014 REST-surface drift (FM-19)`)}out.push({...l,account:acct.ok})}return ok(out)}parseHistoryDeletions(o){if(o===null||typeof o!=="object"||Array.isArray(o)){return connectorError("internal","gmail history.list: response is not an object \u2014 REST-surface drift (FM-19)")}const rec=o;const rows=[];if(rec.history!==void 0){if(!Array.isArray(rec.history)){return connectorError("internal","gmail history.list: `history` is not an array \u2014 REST-surface drift (FM-19)")}for(const record of rec.history){const recordId=record?.id;if(typeof recordId!=="string"||recordId===""){return connectorError("internal","gmail history.list: a history record is missing string `id` \u2014 REST-surface drift (FM-19)")}const deleted=record?.messagesDeleted;if(deleted===void 0)continue;if(!Array.isArray(deleted)){return connectorError("internal","gmail history.list: `messagesDeleted` is not an array \u2014 REST-surface drift (FM-19)")}for(const row of deleted){const id=row?.message?.id;if(typeof id!=="string"||id===""){return connectorError("internal","gmail history.list: a messagesDeleted row is missing message.id \u2014 REST-surface drift (FM-19)")}rows.push({id,atHistoryId:recordId})}}}const next=rec.nextPageToken;if(next!==void 0&&typeof next!=="string"){return connectorError("internal","gmail history.list: nextPageToken is not a string \u2014 REST-surface drift (FM-19)")}return ok({rows,nextPageToken:typeof next==="string"&&next!==""?next:null})}messageDeletions(grant,sinceHistoryId){const acct=this.account(grant);if(!isOk(acct))return acct;const out=[];let pageToken=null;let pages=0;for(;;){const q=`startHistoryId=${encodeURIComponent(sinceHistoryId)}&historyTypes=messageDeleted${pageToken!==null?`&pageToken=${encodeURIComponent(pageToken)}`:""}`;const r=this.get(grant,`/users/me/history?${q}`,"history.list");if(!isOk(r))return r;const parsed=this.parseHistoryDeletions(r.ok);if(!isOk(parsed))return parsed;for(const row of parsed.ok.rows)out.push({account:acct.ok,id:row.id,atHistoryId:row.atHistoryId});if(out.length>GMAIL_DELETIONS_CAP){return connectorError("resource_exhausted",`gmail history.list deletions exceeded the ${GMAIL_DELETIONS_CAP} cap \u2014 refusing a partial sweep (loud, never a silent truncation)`,"non-retryable")}if(++pages>GMAIL_HISTORY_MAX_PAGES){return connectorError("resource_exhausted",`gmail history.list pagination exceeded ${GMAIL_HISTORY_MAX_PAGES} pages \u2014 pageToken-cycle drift (FM-19)`,"non-retryable")}if(parsed.ok.nextPageToken===null)return ok(out);pageToken=parsed.ok.nextPageToken}}}return{GMAIL_AUDIT_RECENT_QUERY,GMAIL_MESSAGE_PULL_CAP,GMAIL_CENSUS_MAX_PAGES,GMAIL_THREAD_PAGE_BYTE_BUDGET,GMAIL_DELETIONS_CAP,GMAIL_HISTORY_MAX_PAGES,GMAIL_ATTACHMENT_CONTENT_CAP,GMAIL_ATTACHMENT_TRANSPORT_SAFE_BYTES,GMAIL_API_BASE,GMAIL_BATCH_URL,GMAIL_BATCH_CHUNK_SIZE,GMAIL_WAN_GATE,refuseWanTransport,buildAttachmentContent,GMAIL_METADATA_HEADERS,GMAIL_STARTER_MESSAGE_LIMIT,GMAIL_STARTER_CONTENT_BYTES,capStarterContent,HttpGmailSource}}
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{validateRead,readResult,connectionState}from"@zortexhq/plugin-connector-core/api";import{createGmailActions}from"./actions.js";import{createBrokeredGmail}from"./brokered.js";export const name="zortex-gmail-original-provider",inject=["zortexConnectorHub","zortexOriginalAuthoring","zortexGoogleAuth","zortexVaultStore"];export function createGmailProvider({parts,provider=parts.createProviderRead(),auth,vault,files}){const info={source:"gmail",label:"Gmail",group:"Connector / Google",auth:"oauth-browser"},stop=new AbortController,pending=new Set;let closed=false;const unavailable=()=>businessError("unavailable","Gmail source is inactive.","plugin");const mcp=vault.credential?createGmailActions(auth,vault,files):void 0;const service={info,...mcp?{actions:mcp.actions}:{},status:()=>connectionState(vault,info),connect:options=>auth.connect("gmail",options),job:id=>auth.job(id),cancelJob:id=>auth.cancelJob(id),async read(input,options={}){if(closed)return unavailable();const invalid=validateRead(input);if(invalid)return invalid;const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;if(signal.aborted)return businessError("aborted","Gmail selected read was cancelled.","connector");const selected=await vault.connection("gmail");if(!("ok"in selected))return selected;if(!selected.ok||selected.ok.state!=="connected")return businessError("unauthenticated","Connect Gmail before reading messages.","auth");if(typeof selected.ok.accountId!=="string"||!selected.ok.accountId.trim())return businessError("failed_precondition","Select a verified native account before reading.","auth");const account=selected.ok.accountId,grant={id:"0"+createHash("sha256").update(account).digest("hex").slice(0,25).toUpperCase(),source:"gmail",scopes:selected.ok.scopes,expiresAt:"2036-01-01T00:00:00.000Z"};const guard=()=>closed||signal.aborted;const talon={grant,execute:()=>Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Resident Gmail reads require asynchronous custody."}),async executeAsync(g,request){if(g.id!==grant.id||g.source!=="gmail")return Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Gmail custody belongs to another source grant."});if(guard())return Original.errResult({code:"aborted",layer:"connector",retryability:"non-retryable",message:"Gmail selected read was stopped."});const contentType=Object.entries(request.headers).find(([key])=>key.toLowerCase()==="content-type")?.[1];const response=await auth.requestRaw("gmail",request.url,{method:request.method,...request.body?{body:Buffer.from(request.body).toString("utf8")}:{},...contentType?{contentType}:{},signal});if(guard())return Original.errResult({code:"aborted",layer:"connector",retryability:"non-retryable",message:"Gmail custody response arrived after cancellation."});const current=await vault.connection("gmail");if(!("ok"in current))return"err"in current?current:Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:"Gmail connection could not be confirmed."});if(current.ok?.state!=="connected"||current.ok.accountId!==account)return Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Gmail account changed while a selected read was active."});return"ok"in response?Original.ok({status:response.ok.status,headers:response.ok.headers,body:new TextEncoder().encode(response.ok.body)}):"err"in response?response:Original.errResult({code:"data_loss",layer:"connector",retryability:"non-retryable",message:"Gmail custody returned unconfirmed empty content."})},close:()=>Original.ok(void 0)};const query=[input.query??"in:inbox",input.since?"after:"+Math.floor(Date.parse(input.since)/1e3):"",input.until?"before:"+Math.floor(Date.parse(input.until)/1e3):""].filter(Boolean).join(" ");const built=createBrokeredGmail(parts,provider,{talon,query,retrievalLimit:input.limit??1,messageFormat:"full"});if(!Original.isOk(built))return built;try{const page=await built.ok.connector.pullAsync(grant,null,{remainingItems:input.limit??1});if(!Original.isOk(page))return page;if(guard())return businessError("aborted","Gmail selected read was stopped.","connector");const prepared=parts.prepareBatch(built.ok.connector,built.ok.connector.manifest,page.ok.items,{phase:"snapshot",syncRun:Original.ulid()});if(!Original.isOk(prepared))return prepared;if(prepared.ok.leaks.length)return businessError("permission_denied","The original emission rail contained a token-bearing Gmail item; no records were cached.","auth");const records=[];for(const entry of prepared.ok.drafts){const proto=entry.draft,normalized=JSON.parse(JSON.stringify(proto)),raw=normalized.payload,headers=raw.payload?.headers??[],subject=headers.find(row=>row.name.toLowerCase()==="subject")?.value??"";records.push({source:"gmail",sourceId:entry.sourceId,stream:entry.stream,kind:proto.kind,ts:proto.ts,body:proto.body??"",fields:{...raw,subject,normalized}})}const current=await vault.connection("gmail");if(!("ok"in current))return current;if(guard())return businessError("aborted","Gmail selected read was stopped.","connector");if(current.ok?.state!=="connected"||current.ok.account!==selected.ok.account||current.ok.accountId!==account||!selected.ok.scopes.every(scope=>current.ok.scopes.includes(scope)))return businessError("permission_denied","Gmail authorization changed while a selected read was active.","auth");const warnings=page.ok.exhausted?[]:["More messages are available beyond this requested batch; selected reads do not measure the full mailbox."];if(prepared.ok.redactions.length)warnings.push("The original emission rail redacted token-shaped source content.");return readResult("gmail",records,warnings)}finally{built.ok.close()}},async close(){closed=true;stop.abort();await mcp?.close();await Promise.allSettled([...pending])}};return{...service,read(input,options){if(closed)return Promise.resolve(unavailable());if(pending.size)return Promise.resolve(businessError("resource_exhausted","Gmail has an active selected read.","connector"));const task=service.read(input,options).finally(()=>pending.delete(task));pending.add(task);return task}}}export async function apply(ctx,config={}){const provider=createGmailProvider({parts:ctx.zortexOriginalAuthoring,auth:ctx.zortexGoogleAuth,vault:ctx.zortexVaultStore,files:config}),withdraw=ctx.zortexConnectorHub.register(provider);return async()=>{withdraw();await provider.close()}}
1
+ import{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{validateRead,readResult,connectionState}from"@zortexhq/plugin-connector-core/api";import{createGmailActions}from"./actions.js";import{createBrokeredGmail}from"./brokered.js";export const name="zortex-gmail-original-provider",inject=["zortexConnectorHub","zortexOriginalAuthoring","zortexGoogleAuth","zortexVaultStore"];const GMAIL_CANDIDATE_LIMIT=20,GMAIL_TEXT_LIMIT=32e3;const object=value=>value!==null&&typeof value==="object"&&!Array.isArray(value)?value:void 0;function headers(raw){const payload=object(raw.payload),rows=payload?.headers;if(!Array.isArray(rows))return new Map;return new Map(rows.flatMap(row=>{const item=object(row),name2=item?.name,value=item?.value;return typeof name2==="string"&&typeof value==="string"?[[name2.toLowerCase(),value]]:[]}))}function bounded(value){return value.length<=GMAIL_TEXT_LIMIT?value:value.slice(0,GMAIL_TEXT_LIMIT)+"\n[truncated]"}function candidateIds(drafts,query,limit){const terms=(query??"").toLocaleLowerCase().match(/[\p{L}\p{N}._+-]{2,}/gu)?.filter(term=>!["after","before","newer_than","older_than","in","label","from","to","subject"].includes(term))??[];return drafts.map((entry,index)=>{const raw=object(entry.draft.payload),id=raw?.id,head=raw?headers(raw):new Map,subject=head.get("subject")??"",searchable=`${subject} ${head.get("from")??""} ${entry.draft.body??""}`.toLocaleLowerCase(),score=terms.reduce((sum,term)=>sum+(subject.toLocaleLowerCase().includes(term)?3:0)+(searchable.includes(term)?1:0),0);return{id:typeof id==="string"?id:void 0,index,score}}).filter(row=>row.id!==void 0).sort((a,b)=>b.score-a.score||a.index-b.index).slice(0,limit).map(row=>row.id)}function recordFrom(entry){const proto=entry.draft,raw=object(proto.payload)??{},head=headers(raw),labelIds=Array.isArray(raw.labelIds)?raw.labelIds.filter(label=>typeof label==="string"):[],safeFields={subject:head.get("subject")??""};for(const key of["from","to","cc","date"]){const value=head.get(key);if(value)safeFields[key]=value}if(typeof raw.threadId==="string")safeFields.threadId=raw.threadId;if(typeof raw.snippet==="string"&&raw.snippet)safeFields.snippet=bounded(raw.snippet);if(labelIds.length)safeFields.labelIds=labelIds;return{source:"gmail",sourceId:entry.sourceId,stream:entry.stream,kind:entry.kind,ts:proto.ts,body:bounded(proto.body??""),fields:safeFields}}export function createGmailProvider({parts,provider=parts.createProviderRead(),auth,vault,files}){const info={source:"gmail",label:"Gmail",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"delta",retention:"durable",resources:["messages"],limitations:[]}},stop=new AbortController,pending=new Set;let closed=false;const unavailable=()=>businessError("unavailable","Gmail source is inactive.","plugin");const mcp=vault.credential?createGmailActions(auth,vault,files):void 0;const service={info,...mcp?{actions:mcp.actions}:{},status:()=>connectionState(vault,info),connect:options=>auth.connect("gmail",options),job:id=>auth.job(id),cancelJob:id=>auth.cancelJob(id),async read(input,options={}){if(closed)return unavailable();const invalid=validateRead(input);if(invalid)return invalid;const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;if(signal.aborted)return businessError("aborted","Gmail selected read was cancelled.","connector");const selected=await vault.connection("gmail");if(!("ok"in selected))return selected;if(!selected.ok||selected.ok.state!=="connected")return businessError("unauthenticated","Connect Gmail before reading messages.","auth");if(typeof selected.ok.accountId!=="string"||!selected.ok.accountId.trim())return businessError("failed_precondition","Select a verified native account before reading.","auth");const account=selected.ok.accountId,grant={id:"0"+createHash("sha256").update(account).digest("hex").slice(0,25).toUpperCase(),source:"gmail",scopes:selected.ok.scopes,expiresAt:"2036-01-01T00:00:00.000Z"};const guard=()=>closed||signal.aborted;const talon={grant,execute:()=>Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Resident Gmail reads require asynchronous custody."}),async executeAsync(g,request){if(g.id!==grant.id||g.source!=="gmail")return Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Gmail custody belongs to another source grant."});if(guard())return Original.errResult({code:"aborted",layer:"connector",retryability:"non-retryable",message:"Gmail selected read was stopped."});const contentType=Object.entries(request.headers).find(([key])=>key.toLowerCase()==="content-type")?.[1];const response=await auth.requestRaw("gmail",request.url,{method:request.method,...request.body?{body:Buffer.from(request.body).toString("utf8")}:{},...contentType?{contentType}:{},signal});if(guard())return Original.errResult({code:"aborted",layer:"connector",retryability:"non-retryable",message:"Gmail custody response arrived after cancellation."});const current=await vault.connection("gmail");if(!("ok"in current))return"err"in current?current:Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:"Gmail connection could not be confirmed."});if(current.ok?.state!=="connected"||current.ok.accountId!==account)return Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Gmail account changed while a selected read was active."});return"ok"in response?Original.ok({status:response.ok.status,headers:response.ok.headers,body:new TextEncoder().encode(response.ok.body)}):"err"in response?response:Original.errResult({code:"data_loss",layer:"connector",retryability:"non-retryable",message:"Gmail custody returned unconfirmed empty content."})},close:()=>Original.ok(void 0)};const query=[input.query??"in:inbox",input.since?"after:"+Math.floor(Date.parse(input.since)/1e3):"",input.until?"before:"+Math.floor(Date.parse(input.until)/1e3):""].filter(Boolean).join(" "),requested=input.limit??1,candidateLimit=Math.min(GMAIL_CANDIDATE_LIMIT,Math.max(10,requested*3));const metadata=createBrokeredGmail(parts,provider,{talon,query,retrievalLimit:candidateLimit,messageFormat:"metadata"});if(!Original.isOk(metadata))return metadata;let ids=[],metadataRedactions=0;try{const page=await metadata.ok.connector.pullAsync(grant,null,{remainingItems:candidateLimit});if(!Original.isOk(page))return page;if(guard())return businessError("aborted","Gmail selected read was stopped.","connector");const prepared=parts.prepareBatch(metadata.ok.connector,metadata.ok.connector.manifest,page.ok.items,{phase:"snapshot",syncRun:Original.ulid()});if(!Original.isOk(prepared))return prepared;if(prepared.ok.leaks.length)return businessError("permission_denied","The Gmail metadata rail contained token-bearing content; no records were returned.","auth");metadataRedactions=prepared.ok.redactions.length;ids=candidateIds(prepared.ok.drafts,input.query,requested)}finally{metadata.ok.close()}if(ids.length===0)return readResult("gmail",[],metadataRedactions?["Gmail metadata fields containing token-shaped content were redacted."]:[]);const content=createBrokeredGmail(parts,provider,{talon,selectedMessageIds:ids,retrievalLimit:ids.length,messageFormat:"full"});if(!Original.isOk(content))return content;try{const page=await content.ok.connector.pullAsync(grant,null,{remainingItems:ids.length});if(!Original.isOk(page))return page;if(guard())return businessError("aborted","Gmail selected read was stopped.","connector");const prepared=parts.prepareBatch(content.ok.connector,content.ok.connector.manifest,page.ok.items,{phase:"snapshot",syncRun:Original.ulid()});if(!Original.isOk(prepared))return prepared;if(prepared.ok.leaks.length)return businessError("permission_denied","The Gmail content rail contained token-bearing content; no records were returned.","auth");const records=prepared.ok.drafts.map(recordFrom);const current=await vault.connection("gmail");if(!("ok"in current))return current;if(guard())return businessError("aborted","Gmail selected read was stopped.","connector");if(current.ok?.state!=="connected"||current.ok.account!==selected.ok.account||current.ok.accountId!==account||!selected.ok.scopes.every(scope=>current.ok.scopes.includes(scope)))return businessError("permission_denied","Gmail authorization changed while a selected read was active.","auth");const warnings=[];if(metadataRedactions||prepared.ok.redactions.length)warnings.push("Gmail fields containing token-shaped content were redacted.");if(records.length<ids.length)warnings.push("One or more Gmail candidates changed or disappeared before their bounded text was read.");return readResult("gmail",records,warnings)}finally{content.ok.close()}},async close(){closed=true;stop.abort();await mcp?.close();await Promise.allSettled([...pending])}};return{...service,read(input,options){if(closed)return Promise.resolve(unavailable());if(pending.size)return Promise.resolve(businessError("resource_exhausted","Gmail has an active selected read.","connector"));const task=service.read(input,options).finally(()=>pending.delete(task));pending.add(task);return task}}}export async function apply(ctx,config={}){const provider=createGmailProvider({parts:ctx.zortexOriginalAuthoring,auth:ctx.zortexGoogleAuth,vault:ctx.zortexVaultStore,files:config}),withdraw=ctx.zortexConnectorHub.register(provider);return async()=>{withdraw();await provider.close()}}
@@ -1 +1 @@
1
- import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{validateRead,readResult,connectionState}from"@zortexhq/plugin-connector-core/api";import{createHash}from"node:crypto";import{METHODS,DISCOVERY_PIN}from"./generated.js";import{createTasksConnector}from"./connector.js";import{createTasksCompounds}from"./compounds.js";import{COMPOUND_METHODS}from"./compound-generated.js";import{record,protectedAuthority,safeProvider,validate}from"./guards.js";export function createTasksSource({parts,auth,vault,transport,transportSync,compoundCustody,compoundReceipts,now=()=>new Date().toISOString()}){const info={source:"google-tasks",label:"Google Tasks",group:"Connector / Google",auth:"oauth-browser"},stop=new AbortController,pending=new Set;let closed=false,principal=null,activeScopes=[];const fail=(code,message,layer="connector")=>businessError(code,message,layer);const methods=new Map(METHODS.flatMap(row=>[[row.id,row],[row.contract,row]]));const mutationReceipts=new Map;const method=id=>methods.has(id)?Original.ok(structuredClone(methods.get(id))):fail("not_found","Google Tasks method is not in the pinned provider catalog");const publicMethod=id=>{const compound=COMPOUND_METHODS.find(row=>row.id===id),selected=compound?Original.ok(structuredClone(compound)):method(id);return"ok"in selected?Original.ok({...selected.ok,httpMethod:selected.ok.method,...compound?{}:{level:1,effect:selected.ok.method==="GET"?"read":"write"}}):selected};async function resolveGrant(){if(closed)return fail("aborted","Tasks source is inactive");const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;if(!selected.ok||selected.ok.state!=="connected")return fail("unauthenticated","Connect Google Tasks before reading or acting","auth");if(typeof selected.ok.accountId!=="string"||!selected.ok.accountId.trim())return fail("failed_precondition","Google Tasks requires a verified OIDC subject; an email or grant id is not an account identity","auth");principal=selected.ok.accountId;activeScopes=[...selected.ok.scopes];return Original.ok({id:"0"+createHash("sha256").update(principal).digest("hex").slice(0,25).toUpperCase(),source:"google-tasks",account:principal,scopes:activeScopes,expiresAt:"2036-01-01T00:00:00.000Z"})}function prepare(row,call){if(protectedAuthority(call))return fail("invalid_argument","Credential or resource-key authority is forbidden in source action parameters");const invalid=validate(row.params,call);if(invalid)return fail("invalid_argument",invalid);if(!record(call)||!record(call.params))return fail("invalid_argument","Provider calls require the declared params object");const max=call.params["maxResults"];if(max!==void 0&&(typeof max!=="number"||max<1||max>(row.resource==="tasklists"?1e3:100)))return fail("invalid_argument","Google Tasks maxResults is outside the documented page bound");let path=row.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(call.params)){if(row.parameterLocations[key]==="path"){if(typeof value!=="string"||!value||value==="."||value===".."||value.length>4096)return fail("invalid_argument","Tasks provider identity is invalid");path=path.replace("{"+key+"}",encodeURIComponent(value))}else query.set(key,String(value))}if(path.includes("{"))return fail("invalid_argument","Google Tasks call is missing a required path identity");const url="https://tasks.googleapis.com/"+path+(query.size?"?"+query:"");const body=call.body===void 0?void 0:JSON.stringify(call.body);if(body!==void 0&&Buffer.byteLength(body)>2097152)return fail("resource_exhausted","Tasks input body exceeds the custody bound");return Original.ok({url,...body===void 0?{}:{body}})}function decode(row,raw){if(Buffer.byteLength(raw.body)>2097152)return fail("resource_exhausted","Tasks provider response exceeds the custody bound");if(raw.status>=400){let diagnostic={};try{diagnostic=safeProvider(JSON.parse(raw.body)).data}catch{}const googleRule=parts.googleStatusOverrideV1(JSON.stringify(diagnostic));return Original.errResult(parts.webStatusFailureV1(raw.status,{provider:"Google Tasks",what:row.id,bodyOverride:status2=>status2===400?{code:"invalid_argument",retryability:"non-retryable",meaning:"provider rejected the Tasks request"}:googleRule(status2),headers:raw.headers}))}let object;if(raw.status===204&&raw.body==="")object={};else try{object=JSON.parse(raw.body)}catch{return fail("data_loss","Google Tasks returned invalid JSON")}if(!record(object))return fail("data_loss","Google Tasks returned a non-object response");const safe=safeProvider(object);const status=parts.webStatusErrorV1(raw.status,{provider:"Google Tasks",what:row.id,bodyOverride:parts.googleStatusOverrideV1(JSON.stringify(safe.data)),headers:raw.headers});if(status)return Original.errResult(status);const payload=safe.data;const isList=row.operation==="list";if(isList&&payload["items"]!==void 0&&!Array.isArray(payload["items"]))return fail("data_loss","Google Tasks returned invalid items");const items=isList?payload["items"]??[]:row.method==="GET"?[payload]:[];if(!Array.isArray(items)||items.some(item=>!record(item)))return fail("data_loss","Google Tasks returned a malformed item collection");const next=payload["nextPageToken"];if(next!==void 0&&(typeof next!=="string"||next.length>8192||!next))return fail("data_loss","Google Tasks returned an invalid page token");return Original.ok({method:row.id,resource:row.resource,data:payload,items,...typeof next==="string"?{nextPageToken:next}:{},warnings:safe.withheld?["Protected assignment resource-key authority was withheld; origin-document access is not implied."]:[],effect:row.method==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}async function invokeInner(id,call,options={}){call=structuredClone(call);if(closed||options.signal?.aborted)return fail("aborted","Tasks source request was stopped");const row=method(id);if(!("ok"in row))return row;const prepared=prepare(row.ok,call);if(!("ok"in prepared))return prepared;const grant=await resolveGrant();if(!("ok"in grant))return grant;const boundPrincipal=principal;if(!row.ok.scopes.some(scope=>activeScopes.includes(scope)))return fail("permission_denied",row.ok.method==="GET"?"Google Tasks read scope is missing":"Google Tasks write scope requires separate user consent","auth");if(row.ok.resource==="tasks"&&["patch","update"].includes(row.ok.operation)&&record(call.body)&&Object.hasOwn(call.body,"deleted")){const target=await invoke("tasks.tasks.get",{params:{tasklist:call.params["tasklist"],task:call.params["task"]}},options);if(!("ok"in target))return target;if(record(target.ok.data["assignmentInfo"]))return fail("permission_denied","Task.deleted is readonly for assigned tasks; no source write was attempted");if(principal!==boundPrincipal)return fail("permission_denied","Tasks account changed before conditional field mutation","auth")}const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;const request={method:row.ok.method,...prepared.ok.body===void 0?{}:{body:prepared.ok.body,contentType:"application/json"},signal};const response=transport?await transport("google-tasks",prepared.ok.url,request):await auth.requestRaw("google-tasks",prepared.ok.url,request);if(closed||signal.aborted)return fail("aborted","Tasks response arrived after cancellation");const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;if(selected.ok?.accountId!==boundPrincipal||principal!==boundPrincipal)return fail("permission_denied","Tasks account changed while the provider request was active","auth");return"ok"in response?decode(row.ok,response.ok):response}function invoke(id,call,options={}){if(pending.size>=32)return Promise.resolve(fail("resource_exhausted","Tasks source has reached its active call bound"));const task=invokeInner(id,call,options).finally(()=>pending.delete(task));pending.add(task);return task}function invokeSync(id,call){call=structuredClone(call);if(!transportSync)return parts.gateRefusal("Google Tasks synchronous request","fixture-oracle only");if(!principal)return parts.gateRefusal("Google Tasks synchronous identity","bind verified account first");const row=method(id);if(!("ok"in row))return"err"in row?row:parts.connectorError("data_loss","Tasks method lookup was unconfirmed");const prepared=prepare(row.ok,call);if(!("ok"in prepared))return"err"in prepared?prepared:parts.connectorError("data_loss","Tasks input validation was unconfirmed");if(!row.ok.scopes.some(scope=>activeScopes.includes(scope)))return parts.connectorError("permission_denied","Google Tasks scope is missing");if(row.ok.resource==="tasks"&&["patch","update"].includes(row.ok.operation)&&record(call.body)&&Object.hasOwn(call.body,"deleted")){const target=invokeSync("tasks.tasks.get",{params:{tasklist:call.params["tasklist"],task:call.params["task"]}});if(!Original.isOk(target))return target;if(record(target.ok.data["assignmentInfo"]))return parts.connectorError("permission_denied","Task.deleted is readonly for assigned tasks; no source write was attempted")}const response=transportSync("google-tasks",prepared.ok.url,{method:row.ok.method,...prepared.ok.body===void 0?{}:{body:prepared.ok.body,contentType:"application/json"}});return"ok"in response?decode(row.ok,response.ok):"err"in response?response:parts.connectorError("data_loss","Tasks fixture response was unconfirmed")}const asOriginal=async(id,call,options)=>{const reply=await invoke(id,call,options);return"empty"in reply?parts.connectorError("data_loss","Tasks provider read was unconfirmed"):reply};const connector=createTasksConnector({parts,accountId:()=>principal,request:asOriginal,...transportSync?{requestSync:invokeSync}:{},now,live:()=>!closed});const rawCompounds=createTasksCompounds({invoke,account:()=>principal,...compoundCustody?{conditional:{async compareAndMutate(input){const selected=method(input.method);if(!("ok"in selected))return selected;const valid=prepare(selected.ok,input.call);if(!("ok"in valid))return valid;const grant=await resolveGrant();if(!("ok"in grant))return grant;if(input.accountId!==principal||!selected.ok.scopes.some(scope=>activeScopes.includes(scope)))return fail("permission_denied","Compound mutation authority is not bound to the verified write account","auth");return compoundCustody.compareAndMutate(input)}}}:{},...compoundReceipts?{receipts:compoundReceipts}:{}});function owned(task){const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled}const compOptions=read=>({signal:read?.signal?AbortSignal.any([read.signal,stop.signal]):stop.signal});const compounds={execute(name,input,key,read){input=structuredClone(input);return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.execute(name,input,key,compOptions(read))})())},compensate(key,read){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.compensate(key,compOptions(read))})())},probe(key){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return Original.ok({reading:"unknown"});return rawCompounds.probe(key)})())},recover(key,read){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.recover(key,compOptions(read))})())}};const arms={},probes={};for(const row of METHODS){arms[row.contract]=async(grant,call)=>{if(grant.source!=="google-tasks"||!row.scopes.some(scope=>grant.scopes.includes(scope)))return parts.connectorError("permission_denied","Tasks action grant does not authorize this method");if(!record(call.params)||!record(call.params["params"]))return parts.connectorError("invalid_argument","Tasks action must use the discovered input wrapper");const input=call.params,reply=await asOriginal(row.id,input,{signal:call.signal});if(!Original.isOk(reply))return reply;if(row.method==="GET")return Original.ok({result:reply.ok.data});if(mutationReceipts.size>=256)mutationReceipts.delete(mutationReceipts.keys().next().value);mutationReceipts.set(call.idempotencyKey,{method:row,call:structuredClone(input),reply:reply.ok});return Original.ok({evidenceHint:"google-tasks provider accepted mutation; verification required"})};if(row.method!=="GET")probes[row.contract+".verify"]={confidentAfterMs:0,read:async(_grant,call)=>{const receipt=mutationReceipts.get(call.idempotencyKey);if(!receipt)return Original.ok({reading:"unknown"});const params=receipt.call.params,body=receipt.call.body;if(row.operation==="clear"||row.operation==="move"||row.operation==="delete"||record(receipt.reply.data["assignmentInfo"]))return Original.ok({reading:"unknown"});const id=typeof receipt.reply.data["id"]==="string"?receipt.reply.data["id"]:params[row.resource==="tasklists"?"tasklist":"task"];if(typeof id!=="string")return Original.ok({reading:"unknown"});const lookup=row.resource==="tasklists"?{tasklist:id}:{tasklist:params["tasklist"],task:id};const answer=await invoke(row.resource==="tasklists"?"tasks.tasklists.get":"tasks.tasks.get",{params:lookup});if("err"in answer){if(row.operation==="delete"&&answer.err.code==="not_found")return Original.ok({reading:"effected"});return Original.ok({reading:"unknown"})}if(!("ok"in answer))return Original.ok({reading:"unknown"});if(row.operation==="delete")return Original.ok({reading:"absent"});if(!record(body))return Original.ok({reading:"unknown"});const matches=Object.entries(body).every(([key,value])=>JSON.stringify(answer.ok.data[key])===JSON.stringify(value));return Original.ok({reading:matches?"effected":"absent"})}}}connector.actionRail=parts.defineConnectorActions({arms,probes});for(const row of COMPOUND_METHODS){arms[row.contract]=async(grant,call)=>{if(grant.source!=="google-tasks"||!grant.scopes.includes("https://www.googleapis.com/auth/tasks"))return parts.connectorError("permission_denied","Personal compound requires an authorized Tasks write grant");if(!record(call.params)||!record(call.params["params"]))return parts.connectorError("invalid_argument","Personal compound requires generated wrapper parameters");const result=await compounds.execute(row.contract,call.params,call.idempotencyKey,{signal:call.signal});return"ok"in result?Original.ok({evidenceHint:"google-tasks-compound:"+result.ok.receiptKey}):"err"in result?result:parts.connectorError("data_loss","Compound execution was unconfirmed")};probes[row.contract+".verify"]={confidentAfterMs:0,read:async(_grant,call)=>{const result=await compounds.probe(call.idempotencyKey);return"ok"in result?Original.ok(result.ok):"err"in result?result:parts.connectorError("data_loss","Compound probe was unconfirmed")}}}connector.actionRail=parts.defineConnectorActions({arms,probes});const service={info,connector,compounds,resolveGrant,status:()=>closed?Promise.resolve(fail("aborted","Tasks source is inactive")):connectionState(vault,info),connect:options=>closed?Promise.resolve(fail("aborted","Tasks source is inactive")):auth.connect("google-tasks",options),job:id=>closed?fail("aborted","Tasks source is inactive"):auth.job(id),cancelJob:id=>auth.cancelJob(id),method,invoke,catalog(options={}){const limit=options.limit??20,cursor=options.cursor??0;if(!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return fail("invalid_argument","Catalog limit/cursor is invalid");const rows=METHODS.filter(row=>(!options.resource||row.resource===options.resource)&&(!options.query||(row.id+" "+row.description).toLowerCase().includes(options.query.toLowerCase())));return Original.ok({total:rows.length,methods:rows.slice(cursor,cursor+limit).map(row=>({id:row.id,contract:row.contract,resource:row.resource,method:row.method,scopes:row.scopes,body:row.body,media:false})),...cursor+limit<rows.length?{next:cursor+limit}:{},pin:DISCOVERY_PIN,gaps:["Tasks API exposes dates only, no due time of day, reminders, recurrence rule, attachments, author or complete revision history.","Assignment resource keys are protected; fetching its Docs/Chat origin requires that source authorization."]})},async*pages(id,params,options={}){const row=method(id);if(!("ok"in row)){yield row;return}if(row.ok.method!=="GET"||row.ok.operation!=="list"){yield fail("invalid_argument","Pagination only applies to Tasks read-list methods");return}const max=options.maxPages??1e4;if(!Number.isInteger(max)||max<1||max>1e5){yield fail("invalid_argument","maxPages is invalid");return}let current={...params};const seen=new Set;for(let page=0;page<max;page++){const answer=await invoke(id,{params:current},options);yield answer;if(!("ok"in answer)||!answer.ok.nextPageToken)return;const token=answer.ok.nextPageToken;if(seen.has(token)||current["pageToken"]===token){yield fail("data_loss","Google Tasks page token repeated; collection was not exhausted");return}seen.add(token);current={...current,pageToken:token}}yield fail("resource_exhausted","Requested pagination bound reached; collection is incomplete")},async check(options={}){if(closed||options.signal?.aborted)return fail("aborted","Tasks check was stopped");const grant=await resolveGrant();if(!("ok"in grant))return grant;const accountId=grant.ok.account;const answer=await invoke("tasks.tasklists.list",{params:{maxResults:1}},options);if(!("ok"in answer))return answer;const current=await vault.connection("google-tasks");if(closed||options.signal?.aborted)return fail("aborted","Tasks check was stopped");if(!("ok"in current))return current;if(current.ok?.state!=="connected"||current.ok.accountId!==accountId||!current.ok.scopes.some(scope=>scope==="https://www.googleapis.com/auth/tasks.readonly"||scope==="https://www.googleapis.com/auth/tasks"))return fail("permission_denied","Tasks check connection or scope changed","auth");if(answer.ok.items.length>1)return fail("data_loss","Tasks readiness response exceeded the requested one-record bound");return Original.ok({source:"google-tasks",basis:"read",operation:{state:"succeeded",returned:answer.ok.items.length}})},async read(request,options={}){const invalid=validateRead(request);if(invalid)return invalid;const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;if(closed||signal.aborted)return fail("aborted","Tasks read was stopped");const grant=await resolveGrant();if(!("ok"in grant))return grant;const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;const captured=structuredClone(selected.ok);if(!captured||captured.state!=="connected"||captured.accountId!==grant.ok.account)return fail("permission_denied","Tasks account changed before the selected read","auth");const readScope="https://www.googleapis.com/auth/tasks.readonly",writeScope="https://www.googleapis.com/auth/tasks",requiredScope=captured.scopes.includes(readScope)?readScope:captured.scopes.includes(writeScope)?writeScope:null;if(!requiredScope)return fail("permission_denied","Google Tasks read scope is missing","auth");const boundPrincipal=captured.accountId,boundGrant=structuredClone(grant.ok),limit=request.limit??1;const records=[],warnings=new Set;let scanned=0,matched=0;const fence=async()=>{if(closed||signal.aborted)return fail("aborted","Tasks read was stopped");const current=await vault.connection("google-tasks");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==boundPrincipal||!current.ok.scopes.includes(requiredScope))return fail("permission_denied","Tasks read connection or scope changed","auth");return Original.ok(void 0)};const reading=createTasksConnector({parts,accountId:()=>boundPrincipal,request:async(id,call)=>{const before=await fence();if(!("ok"in before))return"err"in before?before:parts.connectorError("data_loss","Tasks read fence was unconfirmed");const answer2=await asOriginal(id,call,{signal});const after=await fence();return"ok"in after?answer2:"err"in after?after:parts.connectorError("data_loss","Tasks read fence was unconfirmed")},now,live:()=>!closed&&!signal.aborted});for await(const page of reading.scan(boundGrant,null)){if(signal.aborted||closed)return fail("aborted","Tasks read was stopped");if(!Original.isOk(page))return page;scanned+=page.ok.items.length;for(const note of page.ok.notes??[])warnings.add(note);for(const item of page.ok.items){const proto=reading.normalize(item),fields=record(proto.payload)?proto.payload:{};if(fields["deleted"]===true)continue;const text=proto.body??"";if(request.query&&!text.toLowerCase().includes(request.query.toLowerCase()))continue;if(request.since&&Date.parse(proto.ts)<Date.parse(request.since)||request.until&&Date.parse(proto.ts)>Date.parse(request.until))continue;matched++;records.push({source:"google-tasks",sourceId:encodeURIComponent(boundPrincipal)+":"+proto.nk.sourceId,stream:proto.nk.stream,kind:proto.kind,ts:proto.ts,body:text,fields});records.sort((a,b)=>(b.ts??"").localeCompare(a.ts??"")||(a.sourceId??"").localeCompare(b.sourceId??""));if(records.length>limit)records.length=limit}}const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;const answer=readResult("google-tasks",records,[...warnings]);return"ok"in answer?Original.ok({...answer.ok,scanned,matched}):answer},async close(){closed=true;stop.abort();await Promise.allSettled([...pending]);mutationReceipts.clear();principal=null;activeScopes=[]}};const ownedRead=service.read.bind(service);service.read=(request,options)=>{if(closed)return Promise.resolve(fail("aborted","Tasks source is inactive"));const task=ownedRead(request,options).finally(()=>pending.delete(task));pending.add(task);return task};const ownedCheck=service.check.bind(service);service.check=options=>{if(closed)return Promise.resolve(fail("aborted","Tasks source is inactive"));const task=ownedCheck(options).finally(()=>pending.delete(task));pending.add(task);return task};service.actions={catalog(input){if(input?.profile&&input.profile!=="data")return fail("invalid_argument","Tasks supports the data profile only");if(input?.resource==="personal"||input?.resource==="personal-deleted"){const selected=COMPOUND_METHODS.filter(row=>row.resource===input.resource);return Original.ok({total:selected.length,methods:selected.map(row=>({id:row.id,contract:row.contract,resource:row.resource,method:row.method,scopes:row.scopes,body:row.body,media:false})),pin:"zortex-personal-task-compound@1",gaps:["Requires host atomic target+collection guard custody and durable private receipts"]})}const raw=service.catalog(input);return"ok"in raw?Original.ok({...raw.ok,additionalOperationResources:["personal","personal-deleted"]}):raw},method:publicMethod,async invoke(id,input,options){if(input.media!==void 0)return fail("invalid_argument","Tasks has no media-upload method");if(COMPOUND_METHODS.some(row=>row.id===id)){const receiptKey=Original.ulid();const result=await compounds.execute(id,input,receiptKey,options);return"ok"in result?Original.ok({method:id,resource:"personal",data:result.ok,items:[],warnings:["Private compound accepted; query its receipt/probe before claiming an effect"],effect:"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}}):result}return invoke(id,input,options)}};return service}
1
+ import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{validateRead,readResult,connectionState}from"@zortexhq/plugin-connector-core/api";import{createHash}from"node:crypto";import{METHODS,DISCOVERY_PIN}from"./generated.js";import{createTasksConnector}from"./connector.js";import{createTasksCompounds}from"./compounds.js";import{COMPOUND_METHODS}from"./compound-generated.js";import{record,protectedAuthority,safeProvider,validate}from"./guards.js";export function createTasksSource({parts,auth,vault,transport,transportSync,compoundCustody,compoundReceipts,now=()=>new Date().toISOString()}){const info={source:"google-tasks",label:"Google Tasks",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["tasklists","tasks"],limitations:[]}},stop=new AbortController,pending=new Set;let closed=false,principal=null,activeScopes=[];const fail=(code,message,layer="connector")=>businessError(code,message,layer);const methods=new Map(METHODS.flatMap(row=>[[row.id,row],[row.contract,row]]));const mutationReceipts=new Map;const method=id=>methods.has(id)?Original.ok(structuredClone(methods.get(id))):fail("not_found","Google Tasks method is not in the pinned provider catalog");const publicMethod=id=>{const compound=COMPOUND_METHODS.find(row=>row.id===id),selected=compound?Original.ok(structuredClone(compound)):method(id);return"ok"in selected?Original.ok({...selected.ok,httpMethod:selected.ok.method,...compound?{}:{level:1,effect:selected.ok.method==="GET"?"read":"write"}}):selected};async function resolveGrant(){if(closed)return fail("aborted","Tasks source is inactive");const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;if(!selected.ok||selected.ok.state!=="connected")return fail("unauthenticated","Connect Google Tasks before reading or acting","auth");if(typeof selected.ok.accountId!=="string"||!selected.ok.accountId.trim())return fail("failed_precondition","Google Tasks requires a verified OIDC subject; an email or grant id is not an account identity","auth");principal=selected.ok.accountId;activeScopes=[...selected.ok.scopes];return Original.ok({id:"0"+createHash("sha256").update(principal).digest("hex").slice(0,25).toUpperCase(),source:"google-tasks",account:principal,scopes:activeScopes,expiresAt:"2036-01-01T00:00:00.000Z"})}function prepare(row,call){if(protectedAuthority(call))return fail("invalid_argument","Credential or resource-key authority is forbidden in source action parameters");const invalid=validate(row.params,call);if(invalid)return fail("invalid_argument",invalid);if(!record(call)||!record(call.params))return fail("invalid_argument","Provider calls require the declared params object");const max=call.params["maxResults"];if(max!==void 0&&(typeof max!=="number"||max<1||max>(row.resource==="tasklists"?1e3:100)))return fail("invalid_argument","Google Tasks maxResults is outside the documented page bound");let path=row.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(call.params)){if(row.parameterLocations[key]==="path"){if(typeof value!=="string"||!value||value==="."||value===".."||value.length>4096)return fail("invalid_argument","Tasks provider identity is invalid");path=path.replace("{"+key+"}",encodeURIComponent(value))}else query.set(key,String(value))}if(path.includes("{"))return fail("invalid_argument","Google Tasks call is missing a required path identity");const url="https://tasks.googleapis.com/"+path+(query.size?"?"+query:"");const body=call.body===void 0?void 0:JSON.stringify(call.body);if(body!==void 0&&Buffer.byteLength(body)>2097152)return fail("resource_exhausted","Tasks input body exceeds the custody bound");return Original.ok({url,...body===void 0?{}:{body}})}function decode(row,raw){if(Buffer.byteLength(raw.body)>2097152)return fail("resource_exhausted","Tasks provider response exceeds the custody bound");if(raw.status>=400){let diagnostic={};try{diagnostic=safeProvider(JSON.parse(raw.body)).data}catch{}const googleRule=parts.googleStatusOverrideV1(JSON.stringify(diagnostic));return Original.errResult(parts.webStatusFailureV1(raw.status,{provider:"Google Tasks",what:row.id,bodyOverride:status2=>status2===400?{code:"invalid_argument",retryability:"non-retryable",meaning:"provider rejected the Tasks request"}:googleRule(status2),headers:raw.headers}))}let object;if(raw.status===204&&raw.body==="")object={};else try{object=JSON.parse(raw.body)}catch{return fail("data_loss","Google Tasks returned invalid JSON")}if(!record(object))return fail("data_loss","Google Tasks returned a non-object response");const safe=safeProvider(object);const status=parts.webStatusErrorV1(raw.status,{provider:"Google Tasks",what:row.id,bodyOverride:parts.googleStatusOverrideV1(JSON.stringify(safe.data)),headers:raw.headers});if(status)return Original.errResult(status);const payload=safe.data;const isList=row.operation==="list";if(isList&&payload["items"]!==void 0&&!Array.isArray(payload["items"]))return fail("data_loss","Google Tasks returned invalid items");const items=isList?payload["items"]??[]:row.method==="GET"?[payload]:[];if(!Array.isArray(items)||items.some(item=>!record(item)))return fail("data_loss","Google Tasks returned a malformed item collection");const next=payload["nextPageToken"];if(next!==void 0&&(typeof next!=="string"||next.length>8192||!next))return fail("data_loss","Google Tasks returned an invalid page token");return Original.ok({method:row.id,resource:row.resource,data:payload,items,...typeof next==="string"?{nextPageToken:next}:{},warnings:safe.withheld?["Protected assignment resource-key authority was withheld; origin-document access is not implied."]:[],effect:row.method==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}async function invokeInner(id,call,options={}){call=structuredClone(call);if(closed||options.signal?.aborted)return fail("aborted","Tasks source request was stopped");const row=method(id);if(!("ok"in row))return row;const prepared=prepare(row.ok,call);if(!("ok"in prepared))return prepared;const grant=await resolveGrant();if(!("ok"in grant))return grant;const boundPrincipal=principal;if(!row.ok.scopes.some(scope=>activeScopes.includes(scope)))return fail("permission_denied",row.ok.method==="GET"?"Google Tasks read scope is missing":"Google Tasks write scope requires separate user consent","auth");if(row.ok.resource==="tasks"&&["patch","update"].includes(row.ok.operation)&&record(call.body)&&Object.hasOwn(call.body,"deleted")){const target=await invoke("tasks.tasks.get",{params:{tasklist:call.params["tasklist"],task:call.params["task"]}},options);if(!("ok"in target))return target;if(record(target.ok.data["assignmentInfo"]))return fail("permission_denied","Task.deleted is readonly for assigned tasks; no source write was attempted");if(principal!==boundPrincipal)return fail("permission_denied","Tasks account changed before conditional field mutation","auth")}const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;const request={method:row.ok.method,...prepared.ok.body===void 0?{}:{body:prepared.ok.body,contentType:"application/json"},signal};const response=transport?await transport("google-tasks",prepared.ok.url,request):await auth.requestRaw("google-tasks",prepared.ok.url,request);if(closed||signal.aborted)return fail("aborted","Tasks response arrived after cancellation");const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;if(selected.ok?.accountId!==boundPrincipal||principal!==boundPrincipal)return fail("permission_denied","Tasks account changed while the provider request was active","auth");return"ok"in response?decode(row.ok,response.ok):response}function invoke(id,call,options={}){if(pending.size>=32)return Promise.resolve(fail("resource_exhausted","Tasks source has reached its active call bound"));const task=invokeInner(id,call,options).finally(()=>pending.delete(task));pending.add(task);return task}function invokeSync(id,call){call=structuredClone(call);if(!transportSync)return parts.gateRefusal("Google Tasks synchronous request","fixture-oracle only");if(!principal)return parts.gateRefusal("Google Tasks synchronous identity","bind verified account first");const row=method(id);if(!("ok"in row))return"err"in row?row:parts.connectorError("data_loss","Tasks method lookup was unconfirmed");const prepared=prepare(row.ok,call);if(!("ok"in prepared))return"err"in prepared?prepared:parts.connectorError("data_loss","Tasks input validation was unconfirmed");if(!row.ok.scopes.some(scope=>activeScopes.includes(scope)))return parts.connectorError("permission_denied","Google Tasks scope is missing");if(row.ok.resource==="tasks"&&["patch","update"].includes(row.ok.operation)&&record(call.body)&&Object.hasOwn(call.body,"deleted")){const target=invokeSync("tasks.tasks.get",{params:{tasklist:call.params["tasklist"],task:call.params["task"]}});if(!Original.isOk(target))return target;if(record(target.ok.data["assignmentInfo"]))return parts.connectorError("permission_denied","Task.deleted is readonly for assigned tasks; no source write was attempted")}const response=transportSync("google-tasks",prepared.ok.url,{method:row.ok.method,...prepared.ok.body===void 0?{}:{body:prepared.ok.body,contentType:"application/json"}});return"ok"in response?decode(row.ok,response.ok):"err"in response?response:parts.connectorError("data_loss","Tasks fixture response was unconfirmed")}const asOriginal=async(id,call,options)=>{const reply=await invoke(id,call,options);return"empty"in reply?parts.connectorError("data_loss","Tasks provider read was unconfirmed"):reply};const connector=createTasksConnector({parts,accountId:()=>principal,request:asOriginal,...transportSync?{requestSync:invokeSync}:{},now,live:()=>!closed});const rawCompounds=createTasksCompounds({invoke,account:()=>principal,...compoundCustody?{conditional:{async compareAndMutate(input){const selected=method(input.method);if(!("ok"in selected))return selected;const valid=prepare(selected.ok,input.call);if(!("ok"in valid))return valid;const grant=await resolveGrant();if(!("ok"in grant))return grant;if(input.accountId!==principal||!selected.ok.scopes.some(scope=>activeScopes.includes(scope)))return fail("permission_denied","Compound mutation authority is not bound to the verified write account","auth");return compoundCustody.compareAndMutate(input)}}}:{},...compoundReceipts?{receipts:compoundReceipts}:{}});function owned(task){const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled}const compOptions=read=>({signal:read?.signal?AbortSignal.any([read.signal,stop.signal]):stop.signal});const compounds={execute(name,input,key,read){input=structuredClone(input);return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.execute(name,input,key,compOptions(read))})())},compensate(key,read){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.compensate(key,compOptions(read))})())},probe(key){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return Original.ok({reading:"unknown"});return rawCompounds.probe(key)})())},recover(key,read){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.recover(key,compOptions(read))})())}};const arms={},probes={};for(const row of METHODS){arms[row.contract]=async(grant,call)=>{if(grant.source!=="google-tasks"||!row.scopes.some(scope=>grant.scopes.includes(scope)))return parts.connectorError("permission_denied","Tasks action grant does not authorize this method");if(!record(call.params)||!record(call.params["params"]))return parts.connectorError("invalid_argument","Tasks action must use the discovered input wrapper");const input=call.params,reply=await asOriginal(row.id,input,{signal:call.signal});if(!Original.isOk(reply))return reply;if(row.method==="GET")return Original.ok({result:reply.ok.data});if(mutationReceipts.size>=256)mutationReceipts.delete(mutationReceipts.keys().next().value);mutationReceipts.set(call.idempotencyKey,{method:row,call:structuredClone(input),reply:reply.ok});return Original.ok({evidenceHint:"google-tasks provider accepted mutation; verification required"})};if(row.method!=="GET")probes[row.contract+".verify"]={confidentAfterMs:0,read:async(_grant,call)=>{const receipt=mutationReceipts.get(call.idempotencyKey);if(!receipt)return Original.ok({reading:"unknown"});const params=receipt.call.params,body=receipt.call.body;if(row.operation==="clear"||row.operation==="move"||row.operation==="delete"||record(receipt.reply.data["assignmentInfo"]))return Original.ok({reading:"unknown"});const id=typeof receipt.reply.data["id"]==="string"?receipt.reply.data["id"]:params[row.resource==="tasklists"?"tasklist":"task"];if(typeof id!=="string")return Original.ok({reading:"unknown"});const lookup=row.resource==="tasklists"?{tasklist:id}:{tasklist:params["tasklist"],task:id};const answer=await invoke(row.resource==="tasklists"?"tasks.tasklists.get":"tasks.tasks.get",{params:lookup});if("err"in answer){if(row.operation==="delete"&&answer.err.code==="not_found")return Original.ok({reading:"effected"});return Original.ok({reading:"unknown"})}if(!("ok"in answer))return Original.ok({reading:"unknown"});if(row.operation==="delete")return Original.ok({reading:"absent"});if(!record(body))return Original.ok({reading:"unknown"});const matches=Object.entries(body).every(([key,value])=>JSON.stringify(answer.ok.data[key])===JSON.stringify(value));return Original.ok({reading:matches?"effected":"absent"})}}}connector.actionRail=parts.defineConnectorActions({arms,probes});for(const row of COMPOUND_METHODS){arms[row.contract]=async(grant,call)=>{if(grant.source!=="google-tasks"||!grant.scopes.includes("https://www.googleapis.com/auth/tasks"))return parts.connectorError("permission_denied","Personal compound requires an authorized Tasks write grant");if(!record(call.params)||!record(call.params["params"]))return parts.connectorError("invalid_argument","Personal compound requires generated wrapper parameters");const result=await compounds.execute(row.contract,call.params,call.idempotencyKey,{signal:call.signal});return"ok"in result?Original.ok({evidenceHint:"google-tasks-compound:"+result.ok.receiptKey}):"err"in result?result:parts.connectorError("data_loss","Compound execution was unconfirmed")};probes[row.contract+".verify"]={confidentAfterMs:0,read:async(_grant,call)=>{const result=await compounds.probe(call.idempotencyKey);return"ok"in result?Original.ok(result.ok):"err"in result?result:parts.connectorError("data_loss","Compound probe was unconfirmed")}}}connector.actionRail=parts.defineConnectorActions({arms,probes});const service={info,connector,compounds,resolveGrant,status:()=>closed?Promise.resolve(fail("aborted","Tasks source is inactive")):connectionState(vault,info),connect:options=>closed?Promise.resolve(fail("aborted","Tasks source is inactive")):auth.connect("google-tasks",options),job:id=>closed?fail("aborted","Tasks source is inactive"):auth.job(id),cancelJob:id=>auth.cancelJob(id),method,invoke,catalog(options={}){const limit=options.limit??20,cursor=options.cursor??0;if(!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return fail("invalid_argument","Catalog limit/cursor is invalid");const rows=METHODS.filter(row=>(!options.resource||row.resource===options.resource)&&(!options.query||(row.id+" "+row.description).toLowerCase().includes(options.query.toLowerCase())));return Original.ok({total:rows.length,methods:rows.slice(cursor,cursor+limit).map(row=>({id:row.id,contract:row.contract,resource:row.resource,method:row.method,scopes:row.scopes,body:row.body,media:false})),...cursor+limit<rows.length?{next:cursor+limit}:{},pin:DISCOVERY_PIN,gaps:["Tasks API exposes dates only, no due time of day, reminders, recurrence rule, attachments, author or complete revision history.","Assignment resource keys are protected; fetching its Docs/Chat origin requires that source authorization."]})},async*pages(id,params,options={}){const row=method(id);if(!("ok"in row)){yield row;return}if(row.ok.method!=="GET"||row.ok.operation!=="list"){yield fail("invalid_argument","Pagination only applies to Tasks read-list methods");return}const max=options.maxPages??1e4;if(!Number.isInteger(max)||max<1||max>1e5){yield fail("invalid_argument","maxPages is invalid");return}let current={...params};const seen=new Set;for(let page=0;page<max;page++){const answer=await invoke(id,{params:current},options);yield answer;if(!("ok"in answer)||!answer.ok.nextPageToken)return;const token=answer.ok.nextPageToken;if(seen.has(token)||current["pageToken"]===token){yield fail("data_loss","Google Tasks page token repeated; collection was not exhausted");return}seen.add(token);current={...current,pageToken:token}}yield fail("resource_exhausted","Requested pagination bound reached; collection is incomplete")},async check(options={}){if(closed||options.signal?.aborted)return fail("aborted","Tasks check was stopped");const grant=await resolveGrant();if(!("ok"in grant))return grant;const accountId=grant.ok.account;const answer=await invoke("tasks.tasklists.list",{params:{maxResults:1}},options);if(!("ok"in answer))return answer;const current=await vault.connection("google-tasks");if(closed||options.signal?.aborted)return fail("aborted","Tasks check was stopped");if(!("ok"in current))return current;if(current.ok?.state!=="connected"||current.ok.accountId!==accountId||!current.ok.scopes.some(scope=>scope==="https://www.googleapis.com/auth/tasks.readonly"||scope==="https://www.googleapis.com/auth/tasks"))return fail("permission_denied","Tasks check connection or scope changed","auth");if(answer.ok.items.length>1)return fail("data_loss","Tasks readiness response exceeded the requested one-record bound");return Original.ok({source:"google-tasks",basis:"read",operation:{state:"succeeded",returned:answer.ok.items.length}})},async read(request,options={}){const invalid=validateRead(request);if(invalid)return invalid;const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;if(closed||signal.aborted)return fail("aborted","Tasks read was stopped");const grant=await resolveGrant();if(!("ok"in grant))return grant;const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;const captured=structuredClone(selected.ok);if(!captured||captured.state!=="connected"||captured.accountId!==grant.ok.account)return fail("permission_denied","Tasks account changed before the selected read","auth");const readScope="https://www.googleapis.com/auth/tasks.readonly",writeScope="https://www.googleapis.com/auth/tasks",requiredScope=captured.scopes.includes(readScope)?readScope:captured.scopes.includes(writeScope)?writeScope:null;if(!requiredScope)return fail("permission_denied","Google Tasks read scope is missing","auth");const boundPrincipal=captured.accountId,boundGrant=structuredClone(grant.ok),limit=request.limit??1;const records=[],warnings=new Set;let scanned=0,matched=0;const fence=async()=>{if(closed||signal.aborted)return fail("aborted","Tasks read was stopped");const current=await vault.connection("google-tasks");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==boundPrincipal||!current.ok.scopes.includes(requiredScope))return fail("permission_denied","Tasks read connection or scope changed","auth");return Original.ok(void 0)};const reading=createTasksConnector({parts,accountId:()=>boundPrincipal,request:async(id,call)=>{const before=await fence();if(!("ok"in before))return"err"in before?before:parts.connectorError("data_loss","Tasks read fence was unconfirmed");const answer2=await asOriginal(id,call,{signal});const after=await fence();return"ok"in after?answer2:"err"in after?after:parts.connectorError("data_loss","Tasks read fence was unconfirmed")},now,live:()=>!closed&&!signal.aborted});for await(const page of reading.scan(boundGrant,null)){if(signal.aborted||closed)return fail("aborted","Tasks read was stopped");if(!Original.isOk(page))return page;scanned+=page.ok.items.length;for(const note of page.ok.notes??[])warnings.add(note);for(const item of page.ok.items){const proto=reading.normalize(item),fields=record(proto.payload)?proto.payload:{};if(fields["deleted"]===true)continue;const text=proto.body??"";if(request.query&&!text.toLowerCase().includes(request.query.toLowerCase()))continue;if(request.since&&Date.parse(proto.ts)<Date.parse(request.since)||request.until&&Date.parse(proto.ts)>Date.parse(request.until))continue;matched++;records.push({source:"google-tasks",sourceId:encodeURIComponent(boundPrincipal)+":"+proto.nk.sourceId,stream:proto.nk.stream,kind:proto.kind,ts:proto.ts,body:text,fields});records.sort((a,b)=>(b.ts??"").localeCompare(a.ts??"")||(a.sourceId??"").localeCompare(b.sourceId??""));if(records.length>limit)records.length=limit}}const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;const answer=readResult("google-tasks",records,[...warnings]);return"ok"in answer?Original.ok({...answer.ok,scanned,matched}):answer},async close(){closed=true;stop.abort();await Promise.allSettled([...pending]);mutationReceipts.clear();principal=null;activeScopes=[]}};const ownedRead=service.read.bind(service);service.read=(request,options)=>{if(closed)return Promise.resolve(fail("aborted","Tasks source is inactive"));const task=ownedRead(request,options).finally(()=>pending.delete(task));pending.add(task);return task};const ownedCheck=service.check.bind(service);service.check=options=>{if(closed)return Promise.resolve(fail("aborted","Tasks source is inactive"));const task=ownedCheck(options).finally(()=>pending.delete(task));pending.add(task);return task};service.actions={catalog(input){if(input?.profile&&input.profile!=="data")return fail("invalid_argument","Tasks supports the data profile only");if(input?.resource==="personal"||input?.resource==="personal-deleted"){const selected=COMPOUND_METHODS.filter(row=>row.resource===input.resource);return Original.ok({total:selected.length,methods:selected.map(row=>({id:row.id,contract:row.contract,resource:row.resource,method:row.method,scopes:row.scopes,body:row.body,media:false})),pin:"zortex-personal-task-compound@1",gaps:["Requires host atomic target+collection guard custody and durable private receipts"]})}const raw=service.catalog(input);return"ok"in raw?Original.ok({...raw.ok,additionalOperationResources:["personal","personal-deleted"]}):raw},method:publicMethod,async invoke(id,input,options){if(input.media!==void 0)return fail("invalid_argument","Tasks has no media-upload method");if(COMPOUND_METHODS.some(row=>row.id===id)){const receiptKey=Original.ulid();const result=await compounds.execute(id,input,receiptKey,options);return"ok"in result?Original.ok({method:id,resource:"personal",data:result.ok,items:[],warnings:["Private compound accepted; query its receipt/probe before claiming an effect"],effect:"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}}):result}return invoke(id,input,options)}};return service}
@@ -1 +1 @@
1
- import{DatabaseSync}from"node:sqlite";import{lstat,realpath}from"node:fs/promises";import{homedir}from"node:os";import{join,isAbsolute,resolve}from"node:path";import{pathToFileURL}from"node:url";import{randomUUID,createHash}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{captureLocalReadAuthority,checkLocalReadAuthority,validateRead,readResult,cache}from"@zortexhq/plugin-connector-core/api";import{historySnapshot}from"./snapshot.js";const SCOPES=["history.read"],PROFILE=/^(Default|Profile \d{1,8})$/u;const sourceValid=source=>source==="google-chrome"||source==="microsoft-edge";const text=(value,max=4096)=>typeof value==="string"&&!!value&&value===value.trim()&&value.length<=max&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value);function plain(value,keys){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error("Invalid native browser selection.");for(const key of Reflect.ownKeys(value)){const descriptor=Object.getOwnPropertyDescriptor(value,key);if(typeof key!=="string"||!keys.includes(key)||!descriptor.enumerable||!("value"in descriptor))throw Error("Invalid native browser selection.")}}export function defaultHistoryRoot(source){const vendor=source==="google-chrome"?"Google/Chrome":"Microsoft/Edge";return process.platform==="win32"?join(process.env.LOCALAPPDATA??homedir(),vendor,"User Data"):process.platform==="darwin"?join(homedir(),"Library/Application Support",vendor):join(homedir(),".config",source==="google-chrome"?"google-chrome":"microsoft-edge")}export function historyReadAudience(source,canonicalRoot,profile){if(!sourceValid(source)||!text(canonicalRoot)||!isAbsolute(canonicalRoot)||resolve(canonicalRoot)!==canonicalRoot||!text(profile,64)||!PROFILE.test(profile))throw Error("A canonical browser root and explicit profile are required.");return`indra-local-history:${source}:${createHash("sha256").update(JSON.stringify([pathToFileURL(canonicalRoot).href,profile])).digest("hex")}`}class Refused extends Error{result;constructor(result){super(result.err.message);this.result=result}}function requireOk(result){if(!("ok"in result))throw new Refused("err"in result?result:businessError("data_loss","Local permission custody returned no authority receipt.","storage"));return result.ok}const deny=message=>new Refused(businessError("permission_denied",message,"auth"));export function createHistoryProvider(source,config={},vault){if(!sourceValid(source))throw Error("Name google-chrome or microsoft-edge.");plain(config,["root","profile","authority"]);if(config.authority!==void 0)plain(config.authority,["resourceId","issuer","subject","tenant"]);const selectedRoot=config.root??process.env[source==="google-chrome"?"ZORTEX_CHROME_HISTORY_ROOT":"ZORTEX_EDGE_HISTORY_ROOT"]??defaultHistoryRoot(source);if(!text(selectedRoot)||!isAbsolute(selectedRoot))throw Error("Browser history root must be absolute.");const root=resolve(selectedRoot),profile=config.profile;if(profile!==void 0&&(!text(profile,64)||!PROFILE.test(profile)))throw Error("A browser profile must be Default or Profile N.");const policy=config.authority&&profile?{...config.authority,audience:historyReadAudience(source,root,profile),requiredScopes:SCOPES}:void 0;const info={source,label:source==="google-chrome"?"Chrome \u6D4F\u89C8\u5386\u53F2":"Edge \u6D4F\u89C8\u5386\u53F2",group:"Connector / \u672C\u673A\u6D4F\u89C8\u5668",auth:"none"};const jobs=new Map,stop=new AbortController;let closed=false;const signalFor=signal=>signal?AbortSignal.any([signal,stop.signal]):stop.signal;function active(signal){if(closed)throw new Refused(businessError("unavailable","History source is inactive.","plugin"));if(signal.aborted)throw new Refused(businessError("aborted","History read cancelled.","plugin"))}async function capture(signal){active(signal);if(!vault||!policy)throw new Refused(businessError("failed_precondition","Select a verified native OS-user/profile permission before reading browser history.","auth"));return requireOk(await captureLocalReadAuthority(source,policy,vault,signal))}async function guard(authority,signal){active(signal);requireOk(await checkLocalReadAuthority(authority,vault,signal));active(signal)}async function file(authority,signal){await guard(authority,signal);const actualRoot=await realpath(root);if(actualRoot!==root)throw deny("The selected browser root is not its approved canonical location.");await guard(authority,signal);const directory=join(root,profile),profileStat=await lstat(directory,{bigint:true});if(!profileStat.isDirectory()||profileStat.isSymbolicLink())throw deny("The selected browser profile is not a native directory.");await guard(authority,signal);if(await realpath(directory)!==directory)throw deny("The selected browser profile escaped its approved root.");await guard(authority,signal);const target=join(directory,"History"),stat=await lstat(target,{bigint:true});if(!stat.isFile()||stat.isSymbolicLink())throw deny("The selected History is not a native regular file.");await guard(authority,signal);if(await realpath(target)!==target)throw deny("History escaped the selected native profile.");await guard(authority,signal);return{target,profile,profileIdentity:`${profileStat.dev}:${profileStat.ino}`,fileIdentity:`${stat.dev}:${stat.ino}`}}async function sameFile(expected,authority,signal){const current=await file(authority,signal);if(current.target!==expected.target||current.profileIdentity!==expected.profileIdentity||current.fileIdentity!==expected.fileIdentity)throw deny("The selected native browser profile changed while the read was pending.")}const failed=(error,signal)=>error instanceof Refused?error.result:businessError(signal.aborted?"aborted":"unavailable","Local history cannot be queried consistently; database may be changing or its schema changed. No empty result was assumed.","plugin");const service={info,async status(){const signal=signalFor();if(closed)return businessError("unavailable","History source is inactive.","plugin");try{const authority=await capture(signal);await file(authority,signal);return ok({...info,state:"connected",account:authority.binding.account})}catch{return ok({...info,state:"not-connected",message:"A verified native OS-user/profile permission and readable selected History are required."})}},async connect(options={}){const signal=signalFor(options.signal);try{const authority=await capture(signal),target=options.expectedBinding;if(target&&(target.kind==="binding"?target.bindingId!==authority.binding.id:target.source!==source))throw deny("The requested binding does not match the selected native profile.");const result=await service.read({limit:1},{signal});if(!("ok"in result))return result;await guard(authority,signal);const job={id:randomUUID(),source,state:"connected",startedAt:new Date().toISOString(),account:authority.binding.account};jobs.set(job.id,job);return ok({...job})}catch(error){return failed(error,signal)}},job(id){const job=jobs.get(id);return job?ok({...job}):businessError("not_found","History connection job not found.","plugin")},async read(request,options={}){const invalid=validateRead(request);if(invalid)return invalid;const signal=signalFor(options.signal);try{const authority=await capture(signal),found=await file(authority,signal);let db,snapshot,records=[];try{await guard(authority,signal);try{db=new DatabaseSync(found.target,{readOnly:true});db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=100;");db.prepare("SELECT 1 FROM urls LIMIT 1").get()}catch(error){db?.close();db=void 0;if(!/locked|busy/i.test(error.message))throw error;snapshot=await historySnapshot(found.target,signal,()=>guard(authority,signal));await sameFile(found,authority,signal);await guard(authority,signal);db=new DatabaseSync(snapshot.path);db.exec("PRAGMA query_only=ON;");if(db.prepare("PRAGMA quick_check").get()?.quick_check!=="ok")throw Error("History snapshot failed SQLite integrity validation.")}const terms=["last_visit_time > 0"],parameters=[];if(request.query){terms.push("(instr(lower(url),lower(?)) > 0 OR instr(lower(title),lower(?)) > 0)");parameters.push(request.query,request.query)}for(const[key,operator]of[["since",">="],["until","<="]])if(request[key]){terms.push("last_visit_time "+operator+" ?");parameters.push(Date.parse(request[key])*1e3+116444736e8)}await guard(authority,signal);const rows=db.prepare("SELECT CAST(id AS TEXT) AS id,url,title,CAST(last_visit_time AS TEXT) AS visit_timestamp FROM urls WHERE "+terms.join(" AND ")+" ORDER BY last_visit_time DESC,urls.id DESC LIMIT ?").all(...parameters,request.limit??1);records=rows.map(row=>{const id=String(row.id),timestamp=String(row.visit_timestamp);if(!/^[1-9][0-9]{0,18}$/u.test(id)||BigInt(id)>9223372036854775807n||!/^\d{1,19}$/u.test(timestamp)||typeof row.url!=="string"||!row.url||row.title!==null&&typeof row.title!=="string")throw new Refused(businessError("data_loss","Browser History returned an invalid native record.","plugin"));const date=new Date(Number((BigInt(timestamp)-11644473600000000n)/1000n));if(!Number.isFinite(date.getTime()))throw new Refused(businessError("data_loss","Browser History returned an invalid native timestamp.","plugin"));return{source,sourceId:found.profile+":"+id+":"+timestamp,kind:"browser-history",ts:date.toISOString(),body:(row.title??"")+"\n"+row.url,fields:{url:row.url,title:row.title??"",profile:found.profile}}});await sameFile(found,authority,signal);await guard(authority,signal);const saved=await cache(vault,source,records,{source,account:authority.binding.account,accountId:authority.binding.identity.subject,requiredScopes:[...SCOPES],signal});if(!("ok"in saved))return saved;await guard(authority,signal)}finally{try{db?.close()}finally{await snapshot?.dispose()}}await sameFile(found,authority,signal);await guard(authority,signal);return readResult(source,records)}catch(error){return failed(error,signal)}},close(){closed=true;stop.abort()}};return service}
1
+ import{DatabaseSync}from"node:sqlite";import{lstat,realpath}from"node:fs/promises";import{homedir}from"node:os";import{join,isAbsolute,resolve}from"node:path";import{pathToFileURL}from"node:url";import{randomUUID,createHash}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{captureLocalReadAuthority,checkLocalReadAuthority,validateRead,readResult,cache}from"@zortexhq/plugin-connector-core/api";import{historySnapshot}from"./snapshot.js";const SCOPES=["history.read"],PROFILE=/^(Default|Profile \d{1,8})$/u;const sourceValid=source=>source==="google-chrome"||source==="microsoft-edge";const text=(value,max=4096)=>typeof value==="string"&&!!value&&value===value.trim()&&value.length<=max&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value);function plain(value,keys){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error("Invalid native browser selection.");for(const key of Reflect.ownKeys(value)){const descriptor=Object.getOwnPropertyDescriptor(value,key);if(typeof key!=="string"||!keys.includes(key)||!descriptor.enumerable||!("value"in descriptor))throw Error("Invalid native browser selection.")}}export function defaultHistoryRoot(source){const vendor=source==="google-chrome"?"Google/Chrome":"Microsoft/Edge";return process.platform==="win32"?join(process.env.LOCALAPPDATA??homedir(),vendor,"User Data"):process.platform==="darwin"?join(homedir(),"Library/Application Support",vendor):join(homedir(),".config",source==="google-chrome"?"google-chrome":"microsoft-edge")}export function historyReadAudience(source,canonicalRoot,profile){if(!sourceValid(source)||!text(canonicalRoot)||!isAbsolute(canonicalRoot)||resolve(canonicalRoot)!==canonicalRoot||!text(profile,64)||!PROFILE.test(profile))throw Error("A canonical browser root and explicit profile are required.");return`indra-local-history:${source}:${createHash("sha256").update(JSON.stringify([pathToFileURL(canonicalRoot).href,profile])).digest("hex")}`}class Refused extends Error{result;constructor(result){super(result.err.message);this.result=result}}function requireOk(result){if(!("ok"in result))throw new Refused("err"in result?result:businessError("data_loss","Local permission custody returned no authority receipt.","storage"));return result.ok}const deny=message=>new Refused(businessError("permission_denied",message,"auth"));export function createHistoryProvider(source,config={},vault){if(!sourceValid(source))throw Error("Name google-chrome or microsoft-edge.");plain(config,["root","profile","authority"]);if(config.authority!==void 0)plain(config.authority,["resourceId","issuer","subject","tenant"]);const selectedRoot=config.root??process.env[source==="google-chrome"?"ZORTEX_CHROME_HISTORY_ROOT":"ZORTEX_EDGE_HISTORY_ROOT"]??defaultHistoryRoot(source);if(!text(selectedRoot)||!isAbsolute(selectedRoot))throw Error("Browser history root must be absolute.");const root=resolve(selectedRoot),profile=config.profile;if(profile!==void 0&&(!text(profile,64)||!PROFILE.test(profile)))throw Error("A browser profile must be Default or Profile N.");const policy=config.authority&&profile?{...config.authority,audience:historyReadAudience(source,root,profile),requiredScopes:SCOPES}:void 0;const info={source,label:source==="google-chrome"?"Chrome \u6D4F\u89C8\u5386\u53F2":"Edge \u6D4F\u89C8\u5386\u53F2",group:"Connector / \u672C\u673A\u6D4F\u89C8\u5668",auth:"none",data:{history:"sync",updates:"rescan",retention:"durable",resources:["selected_profile_history"],limitations:["local_history_retention"]}};const jobs=new Map,stop=new AbortController;let closed=false;const signalFor=signal=>signal?AbortSignal.any([signal,stop.signal]):stop.signal;function active(signal){if(closed)throw new Refused(businessError("unavailable","History source is inactive.","plugin"));if(signal.aborted)throw new Refused(businessError("aborted","History read cancelled.","plugin"))}async function capture(signal){active(signal);if(!vault||!policy)throw new Refused(businessError("failed_precondition","Select a verified native OS-user/profile permission before reading browser history.","auth"));return requireOk(await captureLocalReadAuthority(source,policy,vault,signal))}async function guard(authority,signal){active(signal);requireOk(await checkLocalReadAuthority(authority,vault,signal));active(signal)}async function file(authority,signal){await guard(authority,signal);const actualRoot=await realpath(root);if(actualRoot!==root)throw deny("The selected browser root is not its approved canonical location.");await guard(authority,signal);const directory=join(root,profile),profileStat=await lstat(directory,{bigint:true});if(!profileStat.isDirectory()||profileStat.isSymbolicLink())throw deny("The selected browser profile is not a native directory.");await guard(authority,signal);if(await realpath(directory)!==directory)throw deny("The selected browser profile escaped its approved root.");await guard(authority,signal);const target=join(directory,"History"),stat=await lstat(target,{bigint:true});if(!stat.isFile()||stat.isSymbolicLink())throw deny("The selected History is not a native regular file.");await guard(authority,signal);if(await realpath(target)!==target)throw deny("History escaped the selected native profile.");await guard(authority,signal);return{target,profile,profileIdentity:`${profileStat.dev}:${profileStat.ino}`,fileIdentity:`${stat.dev}:${stat.ino}`}}async function sameFile(expected,authority,signal){const current=await file(authority,signal);if(current.target!==expected.target||current.profileIdentity!==expected.profileIdentity||current.fileIdentity!==expected.fileIdentity)throw deny("The selected native browser profile changed while the read was pending.")}const failed=(error,signal)=>error instanceof Refused?error.result:businessError(signal.aborted?"aborted":"unavailable","Local history cannot be queried consistently; database may be changing or its schema changed. No empty result was assumed.","plugin");const service={info,async status(){const signal=signalFor();if(closed)return businessError("unavailable","History source is inactive.","plugin");try{const authority=await capture(signal);await file(authority,signal);return ok({...info,state:"connected",account:authority.binding.account})}catch{return ok({...info,state:"not-connected",message:"A verified native OS-user/profile permission and readable selected History are required."})}},async connect(options={}){const signal=signalFor(options.signal);try{const authority=await capture(signal),target=options.expectedBinding;if(target&&(target.kind==="binding"?target.bindingId!==authority.binding.id:target.source!==source))throw deny("The requested binding does not match the selected native profile.");const result=await service.read({limit:1},{signal});if(!("ok"in result))return result;await guard(authority,signal);const job={id:randomUUID(),source,state:"connected",startedAt:new Date().toISOString(),account:authority.binding.account};jobs.set(job.id,job);return ok({...job})}catch(error){return failed(error,signal)}},job(id){const job=jobs.get(id);return job?ok({...job}):businessError("not_found","History connection job not found.","plugin")},async read(request,options={}){const invalid=validateRead(request);if(invalid)return invalid;const signal=signalFor(options.signal);try{const authority=await capture(signal),found=await file(authority,signal);let db,snapshot,records=[];try{await guard(authority,signal);try{db=new DatabaseSync(found.target,{readOnly:true});db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=100;");db.prepare("SELECT 1 FROM urls LIMIT 1").get()}catch(error){db?.close();db=void 0;if(!/locked|busy/i.test(error.message))throw error;snapshot=await historySnapshot(found.target,signal,()=>guard(authority,signal));await sameFile(found,authority,signal);await guard(authority,signal);db=new DatabaseSync(snapshot.path);db.exec("PRAGMA query_only=ON;");if(db.prepare("PRAGMA quick_check").get()?.quick_check!=="ok")throw Error("History snapshot failed SQLite integrity validation.")}const terms=["last_visit_time > 0"],parameters=[];if(request.query){terms.push("(instr(lower(url),lower(?)) > 0 OR instr(lower(title),lower(?)) > 0)");parameters.push(request.query,request.query)}for(const[key,operator]of[["since",">="],["until","<="]])if(request[key]){terms.push("last_visit_time "+operator+" ?");parameters.push(Date.parse(request[key])*1e3+116444736e8)}await guard(authority,signal);const rows=db.prepare("SELECT CAST(id AS TEXT) AS id,url,title,CAST(last_visit_time AS TEXT) AS visit_timestamp FROM urls WHERE "+terms.join(" AND ")+" ORDER BY last_visit_time DESC,urls.id DESC LIMIT ?").all(...parameters,request.limit??1);records=rows.map(row=>{const id=String(row.id),timestamp=String(row.visit_timestamp);if(!/^[1-9][0-9]{0,18}$/u.test(id)||BigInt(id)>9223372036854775807n||!/^\d{1,19}$/u.test(timestamp)||typeof row.url!=="string"||!row.url||row.title!==null&&typeof row.title!=="string")throw new Refused(businessError("data_loss","Browser History returned an invalid native record.","plugin"));const date=new Date(Number((BigInt(timestamp)-11644473600000000n)/1000n));if(!Number.isFinite(date.getTime()))throw new Refused(businessError("data_loss","Browser History returned an invalid native timestamp.","plugin"));return{source,sourceId:found.profile+":"+id+":"+timestamp,kind:"browser-history",ts:date.toISOString(),body:(row.title??"")+"\n"+row.url,fields:{url:row.url,title:row.title??"",profile:found.profile}}});await sameFile(found,authority,signal);await guard(authority,signal);const saved=await cache(vault,source,records,{source,account:authority.binding.account,accountId:authority.binding.identity.subject,requiredScopes:[...SCOPES],signal});if(!("ok"in saved))return saved;await guard(authority,signal)}finally{try{db?.close()}finally{await snapshot?.dispose()}}await sameFile(found,authority,signal);await guard(authority,signal);return readResult(source,records)}catch(error){return failed(error,signal)}},close(){closed=true;stop.abort()}};return service}
@@ -0,0 +1 @@
1
+ const NSSTRING=new TextEncoder().encode("NSString");const STRING_TAG=43;const TAG_WINDOW=8;function indexOf(hay,needle,from=0){outer:for(let i=from;i+needle.length<=hay.length;i++){for(let j=0;j<needle.length;j++)if(hay[i+j]!==needle[j])continue outer;return i}return-1}export function attributedBodyTextV1(body){if(body===null||body===void 0||body.length===0)return null;const at=indexOf(body,NSSTRING);if(at<0)return null;let i=at+NSSTRING.length;const stop=Math.min(body.length,i+TAG_WINDOW);while(i<stop&&body[i]!==STRING_TAG)i++;if(i>=stop)return null;i+=1;const lead=body[i];if(lead===void 0)return null;let length;if(lead<128){length=lead;i+=1}else if(lead===129){if(i+3>body.length)return null;length=body[i+1]|body[i+2]<<8;i+=3}else if(lead===130){if(i+5>body.length)return null;length=(body[i+1]|body[i+2]<<8|body[i+3]<<16|body[i+4]<<24)>>>0;i+=5}else{return null}if(length===0||i+length>body.length)return null;try{return new TextDecoder("utf-8",{fatal:true}).decode(body.subarray(i,i+length))}catch{return null}}
@@ -0,0 +1 @@
1
+ import{DatabaseSync}from"node:sqlite";import{homedir}from"node:os";import{join}from"node:path";import{Original}from"@zortexhq/plugin-connector-framework/api";const{errResult,ok}=Original;import{snapshotError,snapshotLiveSqlite}from"./sqlite-snapshot.js";import{attributedBodyTextV1}from"./attributed-body.js";export const MAX_MESSAGES=25e4;const APPLE_2001_EPOCH_MS=Date.parse("2001-01-01T00:00:00.000Z");export function defaultMessagesChatDbPath(home=homedir()){return join(home,"Library","Messages","chat.db")}function sqliteErr(code,message,retryability="non-retryable"){return errResult({code,layer:"upstream",retryability,message})}function messagesDateToIso(raw){if(raw===null||raw===""||raw==="0")return"";const n=BigInt(raw);const ms=n>10000000000000n?Number(n/1000000n):Number(n*1000n);return new Date(APPLE_2001_EPOCH_MS+ms).toISOString()}function tableExists(db,name){const row=db.prepare("SELECT COUNT(*) AS n FROM sqlite_master WHERE type='table' AND name=?").get(name);return(row?.n??0)>0}function columnExists(db,table,column){return db.prepare(`SELECT COUNT(*) AS n FROM pragma_table_info('${table}') WHERE name = ?`).get(column)?.n===1}function relationMap(db,table,left,right){const out=new Map;if(!tableExists(db,table))return out;const rows=db.prepare(`SELECT CAST(${left} AS TEXT) AS l, CAST(${right} AS TEXT) AS r FROM ${table} ORDER BY ${left}, ${right}`).all();for(const row of rows){const list=out.get(row.l)??[];list.push(row.r);out.set(row.l,list)}return out}export class ChatDbMessagesSource{opts;constructor(opts={}){this.opts=opts}chatDbPath(){return this.opts.chatDbPath??defaultMessagesChatDbPath()}get cap(){return this.opts.cap??MAX_MESSAGES}get store(){return this.opts.store??this.chatDbPath()}snapshot;db;close(){try{this.db?.close()}finally{if(this.snapshot&&"ok"in this.snapshot)this.snapshot.ok.cleanup();this.db=void 0;this.snapshot=void 0}}read(fn){try{const snapshot=this.snapshot??=snapshotLiveSqlite(this.chatDbPath(),{...this.opts.snapshot,...this.opts.stagingRoot===void 0?{}:{stagingRoot:this.opts.stagingRoot}});if("err"in snapshot)return errResult(snapshotError(snapshot.err));if(!this.db){this.db=new DatabaseSync(snapshot.ok.path,{readOnly:true});if(!["message","chat","handle","attachment"].every(table=>tableExists(this.db,table))){this.close();return sqliteErr("data_loss","The Messages database is missing a required table.")}}return fn(this.db)}catch{return sqliteErr("data_loss","Indra could not read the Messages database snapshot.")}}census(){return this.read(db=>{const count=table=>tableExists(db,table)?db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()?.n??0:0;return ok({message:count("message"),chat:count("chat"),handle:count("handle"),attachment:count("attachment")})})}rowIds(){return this.read(db=>{const ids={message:[],chat:[],handle:[],attachment:[]};for(const stream of Object.keys(ids)){const rows=db.prepare(`SELECT CAST(ROWID AS TEXT) AS r FROM ${stream} ORDER BY ROWID LIMIT ?`).all(this.cap+1);if(rows.length>this.cap){return sqliteErr("resource_exhausted",`imessage: The Messages ${stream} table exceeds the ${this.cap}-row import limit.`)}ids[stream]=rows.map(row=>row.r)}return ok({store:this.store,ids})})}messages(){return this.read(db=>{const total=db.prepare("SELECT COUNT(*) AS n FROM message").get()?.n??0;if(total>this.cap)return sqliteErr("resource_exhausted",`imessage: ${total} messages exceeds cap ${this.cap} \u2014 refused loud, never truncated`);const chatIds=relationMap(db,"chat_message_join","message_id","chat_id");const attachmentIds=relationMap(db,"message_attachment_join","message_id","attachment_id");const rows=db.prepare("SELECT CAST(m.ROWID AS TEXT) AS rowid, m.guid AS guid, m.text AS text, m.service AS service, m.account AS account, CAST(m.handle_id AS TEXT) AS handle_id, h.id AS handle, h.service AS handle_service, CAST(m.date AS TEXT) AS date, CAST(m.date_read AS TEXT) AS date_read, CAST(m.date_delivered AS TEXT) AS date_delivered, m.is_from_me AS is_from_me, m.cache_roomnames AS cache_roomnames, m.associated_message_guid AS associated_message_guid, m.associated_message_type AS associated_message_type, "+(columnExists(db,"message","attributedBody")?"m.attributedBody":"NULL")+" AS attributed_body FROM message m LEFT JOIN handle h ON h.ROWID = m.handle_id ORDER BY m.ROWID").all();return ok(rows.map(r=>({store:this.store,rowid:r.rowid,guid:r.guid??"",text:r.text!==null&&r.text!==""?r.text:attributedBodyTextV1(r.attributed_body)??"",service:r.service??"",account:r.account??"",handleId:r.handle_id??"",handle:r.handle??"",handleService:r.handle_service??"",chatIds:chatIds.get(r.rowid)??[],attachmentIds:attachmentIds.get(r.rowid)??[],isFromMe:(r.is_from_me??0)===1,dateIso:messagesDateToIso(r.date),dateReadIso:messagesDateToIso(r.date_read),dateDeliveredIso:messagesDateToIso(r.date_delivered),cacheRoomnames:r.cache_roomnames??"",associatedMessageGuid:r.associated_message_guid??"",associatedMessageType:r.associated_message_type??0})))})}chats(){return this.read(db=>{const rows=db.prepare("SELECT CAST(ROWID AS TEXT) AS rowid, guid, chat_identifier, service_name, display_name, room_name, last_addressed_handle FROM chat ORDER BY ROWID").all();return ok(rows.map(r=>({store:this.store,rowid:r.rowid,guid:r.guid??"",chatIdentifier:r.chat_identifier??"",serviceName:r.service_name??"",displayName:r.display_name??"",roomName:r.room_name??"",lastAddressedHandle:r.last_addressed_handle??""})))})}handles(){return this.read(db=>{const rows=db.prepare("SELECT CAST(ROWID AS TEXT) AS rowid, id, service, country, uncanonicalized_id FROM handle ORDER BY ROWID").all();return ok(rows.map(r=>({store:this.store,rowid:r.rowid,id:r.id??"",service:r.service??"",country:r.country??"",uncanonicalizedId:r.uncanonicalized_id??""})))})}attachments(){return this.read(db=>{const rows=db.prepare("SELECT CAST(ROWID AS TEXT) AS rowid, guid, filename, mime_type, transfer_name, total_bytes, CAST(created_date AS TEXT) AS created_date, CAST(start_date AS TEXT) AS start_date, CAST(user_info AS TEXT) AS user_info FROM attachment ORDER BY ROWID").all();return ok(rows.map(r=>({store:this.store,rowid:r.rowid,guid:r.guid??"",filename:r.filename??"",mimeType:r.mime_type??"",transferName:r.transfer_name??"",totalBytes:r.total_bytes??0,createdIso:messagesDateToIso(r.created_date),startDateIso:messagesDateToIso(r.start_date),userInfo:r.user_info??""})))})}}
@@ -0,0 +1 @@
1
+ import{Original}from"@zortexhq/plugin-connector-framework/api";import{IMESSAGE_ATTACHMENT_DELETED_KIND,IMESSAGE_ATTACHMENT_STREAM,IMESSAGE_CHAT_DELETED_KIND,IMESSAGE_CHAT_STREAM,IMESSAGE_HANDLE_DELETED_KIND,IMESSAGE_HANDLE_STREAM,IMESSAGE_MANIFEST,IMESSAGE_MESSAGE_DELETED_KIND,IMESSAGE_MESSAGE_STREAM,IMESSAGE_SOURCE}from"./manifest.js";const{isOk,ok}=Original;const IMESSAGE_STREAMS=[IMESSAGE_MESSAGE_STREAM,IMESSAGE_CHAT_STREAM,IMESSAGE_HANDLE_STREAM,IMESSAGE_ATTACHMENT_STREAM];const DELETED_KIND={message:IMESSAGE_MESSAGE_DELETED_KIND,chat:IMESSAGE_CHAT_DELETED_KIND,handle:IMESSAGE_HANDLE_DELETED_KIND,attachment:IMESSAGE_ATTACHMENT_DELETED_KIND};const EMITS_REV={message:true,chat:false,handle:false,attachment:false};export const IMESSAGE_AUDIT_EVIDENCE_MAX=2e3;function isRetiredMarker(raw){return raw!==null&&typeof raw==="object"&&raw.__imessageRetired===true}function retiredItem(stream,store,rowid,observedAtIso){const marker={__imessageRetired:true,store,rowid,observedAtIso};return{streamRef:stream,raw:marker}}function normalizeRetired(stream,marker){return{nk:{source:IMESSAGE_SOURCE,stream,sourceId:marker.rowid,...EMITS_REV[stream]?{rev:marker.observedAtIso}:{}},ts:marker.observedAtIso,tier:"local-app",kind:DELETED_KIND[stream],schemaVersion:1,mentions:[],body:`${stream} ${marker.rowid} \u2014 deleted from the Messages store`,payload:{store:marker.store,rowid:marker.rowid,deleted:true,observedAtIso:marker.observedAtIso}}}function mention(ns,value,role){return value!==""?[{role,raw:value,handle:{ns,value}}]:[]}function addCounts(into,one){into.message+=one.message;into.chat+=one.chat;into.handle+=one.handle;into.attachment+=one.attachment}export function createImessageConnector(parts,source,opts={}){const{auditFromListingV1,boundPageItemsV1,prefixEpoch}=parts;const now=opts.now??(()=>new Date().toISOString());const connector={manifest:IMESSAGE_MANIFEST,discover(grant){void grant;const c=source.census();if(!isOk(c))return c;const totals={message:0,chat:0,handle:0,attachment:0};addCounts(totals,c.ok);return ok({asOf:now(),streams:{[IMESSAGE_MESSAGE_STREAM]:{total:totals.message,method:"count-api"},[IMESSAGE_CHAT_STREAM]:{total:totals.chat,method:"count-api"},[IMESSAGE_HANDLE_STREAM]:{total:totals.handle,method:"count-api"},[IMESSAGE_ATTACHMENT_STREAM]:{total:totals.attachment,method:"count-api"}}})},pull(grant,cursor){void grant;void cursor;const messages=source.messages();if(!isOk(messages))return messages;const chats=source.chats();if(!isOk(chats))return chats;const handles=source.handles();if(!isOk(handles))return handles;const attachments=source.attachments();if(!isOk(attachments))return attachments;const items=[];for(const m of messages.ok)items.push({streamRef:IMESSAGE_MESSAGE_STREAM,raw:m});for(const c of chats.ok)items.push({streamRef:IMESSAGE_CHAT_STREAM,raw:c});for(const h of handles.ok)items.push({streamRef:IMESSAGE_HANDLE_STREAM,raw:h});for(const a of attachments.ok)items.push({streamRef:IMESSAGE_ATTACHMENT_STREAM,raw:a});return ok({items,next:null,exhausted:true})},normalize(item){if(isRetiredMarker(item.raw)){if(!IMESSAGE_STREAMS.includes(item.streamRef)){throw new Error(`imessage normalize: undeclared streamRef '${item.streamRef}'`)}return normalizeRetired(item.streamRef,item.raw)}switch(item.streamRef){case IMESSAGE_MESSAGE_STREAM:return normalizeMessage(item.raw);case IMESSAGE_CHAT_STREAM:return normalizeChat(item.raw);case IMESSAGE_HANDLE_STREAM:return normalizeHandle(item.raw);case IMESSAGE_ATTACHMENT_STREAM:return normalizeAttachment(item.raw);default:throw new Error(`imessage normalize: undeclared streamRef '${item.streamRef}'`)}}};connector.discoverAsync=async grant=>connector.discover(grant);connector.pullAsync=async(grant,cursor)=>connector.pull(grant,cursor);connector.auditAsync=async(grant,covered,request)=>{const observedAt=now();let store="";let prefix="";const bareOf=id=>prefix!==""&&id.startsWith(prefix)?id.slice(prefix.length):null;return auditFromListingV1({streams:IMESSAGE_STREAMS,expectedScope:"store",evidenceCap:IMESSAGE_AUDIT_EVIDENCE_MAX,now:()=>observedAt,list:async()=>{const read=source.rowIds();if(!isOk(read))return read;store=read.ok.store;const probe=prefixEpoch(store,"0");if(!isOk(probe))return probe;prefix=probe.ok.slice(0,-1);const listing={};for(const stream of IMESSAGE_STREAMS){listing[stream]={scope:"store",end:"complete",listed:new Set(read.ok.ids[stream].map(rowid=>`${prefix}${rowid}`))}}return ok(listing)},evidence:async(_g,_stream,id)=>ok(bareOf(id)===null?{byId:"unknown"}:{byId:"not-found"}),tombstone:(stream,id)=>retiredItem(stream,store,bareOf(id)??id,observedAt)})(grant,covered,request)};return boundPageItemsV1(connector)}function normalizeMessage(raw){const direction=raw.isFromMe?"sent":"received";const fallback=raw.handle!==""?`iMessage ${direction} with ${raw.handle}`:`iMessage ${direction}`;return{nk:{source:IMESSAGE_SOURCE,stream:IMESSAGE_MESSAGE_STREAM,sourceId:raw.rowid,rev:raw.dateIso},ts:raw.dateIso,tier:"local-app",kind:raw.isFromMe?"message.sent":"message.received",schemaVersion:1,mentions:[...mention("imessage-handle",raw.handle,raw.isFromMe?"participant":"actor"),...raw.chatIds.flatMap(id=>mention("imessage-chat",id,"participant"))],body:raw.text!==""?raw.text:fallback,payload:raw}}function normalizeChat(raw){const label=raw.displayName||raw.chatIdentifier||raw.guid||raw.rowid;return{nk:{source:IMESSAGE_SOURCE,stream:IMESSAGE_CHAT_STREAM,sourceId:raw.rowid},ts:"1970-01-01T00:00:00.000Z",tier:"local-app",kind:"im.chat",schemaVersion:1,mentions:mention("imessage-chat",raw.chatIdentifier,"participant"),body:label,payload:raw}}function normalizeHandle(raw){return{nk:{source:IMESSAGE_SOURCE,stream:IMESSAGE_HANDLE_STREAM,sourceId:raw.rowid},ts:"1970-01-01T00:00:00.000Z",tier:"local-app",kind:"im.handle",schemaVersion:1,mentions:mention("imessage-handle",raw.id,"participant"),body:raw.id||raw.uncanonicalizedId||raw.rowid,payload:raw}}function normalizeAttachment(raw){const label=raw.transferName||raw.filename||raw.guid||raw.rowid;return{nk:{source:IMESSAGE_SOURCE,stream:IMESSAGE_ATTACHMENT_STREAM,sourceId:raw.rowid},ts:raw.createdIso||raw.startDateIso||"1970-01-01T00:00:00.000Z",tier:"local-app",kind:"im.attachment",schemaVersion:1,mentions:[],body:label,payload:raw}}
@@ -0,0 +1 @@
1
+ export{createImessageConnector}from"./connector.js";export{ChatDbMessagesSource,defaultMessagesChatDbPath}from"./chatdb-source.js";
@@ -0,0 +1 @@
1
+ export const IMESSAGE_SOURCE="imessage";export const IMESSAGE_MESSAGE_STREAM="message";export const IMESSAGE_CHAT_STREAM="chat";export const IMESSAGE_HANDLE_STREAM="handle";export const IMESSAGE_ATTACHMENT_STREAM="attachment";export const IMESSAGE_MESSAGE_DELETED_KIND="message.deleted";export const IMESSAGE_CHAT_DELETED_KIND="im.chat.deleted";export const IMESSAGE_HANDLE_DELETED_KIND="im.handle.deleted";export const IMESSAGE_ATTACHMENT_DELETED_KIND="im.attachment.deleted";export const IMESSAGE_MANIFEST={source:IMESSAGE_SOURCE,tier:"local-app",auth:{provider:"local",method:"local-permission",scopes:["messages.read"],multiAccount:false,probe:{op:"stat-messages-chatdb"}},tccPermissions:["full-disk"],streams:[{stream:IMESSAGE_MESSAGE_STREAM,kinds:["message.received","message.sent"],identity:{quality:"container-scoped",epochField:"store"},revOrder:"event-ts",deleteKind:IMESSAGE_MESSAGE_DELETED_KIND},{stream:IMESSAGE_CHAT_STREAM,kinds:["im.chat"],identity:{quality:"container-scoped",epochField:"store"},revOrder:"head-compare",deleteKind:IMESSAGE_CHAT_DELETED_KIND},{stream:IMESSAGE_HANDLE_STREAM,kinds:["im.handle"],identity:{quality:"container-scoped",epochField:"store"},revOrder:"head-compare",deleteKind:IMESSAGE_HANDLE_DELETED_KIND},{stream:IMESSAGE_ATTACHMENT_STREAM,kinds:["im.attachment"],identity:{quality:"container-scoped",epochField:"store"},revOrder:"head-compare",deleteKind:IMESSAGE_ATTACHMENT_DELETED_KIND}],actions:[],defaultTaint:"quoted-only",coverageProbe:"count-api",healthProbe:{kind:"fetch-one",intervalMin:15},retaliationRisk:"tolerant"};
@@ -0,0 +1 @@
1
+ import{closeSync,copyFileSync,lstatSync,mkdtempSync,openSync,readSync,rmSync,constants}from"node:fs";import{tmpdir}from"node:os";import{join}from"node:path";import{DatabaseSync}from"node:sqlite";const errno=error=>error?.code;const deny=()=>Object.assign(new Error("Messages store files must belong to the native user."),{code:"EACCES"});function stamp(path){try{const stat=lstatSync(path,{bigint:true});if(!stat.isFile()||process.getuid&&stat.uid!==BigInt(process.getuid()))throw deny();return{inode:stat.ino,size:stat.size,modified:stat.mtimeNs}}catch(error){if(errno(error)==="ENOENT")return null;throw error}}function walHeader(path){const fd=openSync(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const bytes=Buffer.alloc(32);return bytes.subarray(0,readSync(fd,bytes,0,bytes.length,0)).toString("hex")}finally{closeSync(fd)}}function fingerprint(path){const db=stamp(path),wal=stamp(path+"-wal");return{db,wal,walHeader:wal?walHeader(path+"-wal"):""}}function stable(before,after){return!!before.db&&!!after.db&&before.db.inode===after.db.inode&&before.db.size===after.db.size&&before.db.modified===after.db.modified&&before.walHeader===after.walHeader&&(before.wal?!!after.wal&&before.wal.inode===after.wal.inode&&before.wal.size<=after.wal.size:after.wal===null)}export function snapshotLiveSqlite(path,options={}){const staging=mkdtempSync(join(options.stagingRoot??tmpdir(),"imessage-chatdb-"));const cleanup=()=>rmSync(staging,{recursive:true,force:true});let retained=false,onlyBusy=true;try{for(let attempt=0;attempt<(options.attempts??4);attempt++){if(attempt)Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,options.settleMs??200);const copy=join(staging,`snapshot-${attempt}.db`);try{const before=fingerprint(path);if(!before.db)return{err:"not_found"};copyFileSync(path,copy);options.betweenCopies?.();if(before.wal)copyFileSync(path+"-wal",copy+"-wal");if(!stable(before,fingerprint(path)))continue}catch(error){if(errno(error)==="EACCES"||errno(error)==="EPERM")return{err:"permission_denied"};if(errno(error)!=="ENOENT")onlyBusy=false;continue}try{const database=new DatabaseSync(copy);try{database.exec("PRAGMA wal_checkpoint(TRUNCATE)");if(database.prepare("PRAGMA quick_check").get()?.quick_check!=="ok"){onlyBusy=false;continue}}finally{database.close()}retained=true;return{ok:{path:copy,cleanup}}}catch{onlyBusy=false}}return{err:onlyBusy?"busy":"data_loss"}}finally{if(!retained)cleanup()}}export function snapshotError(kind){switch(kind){case"not_found":return{code:kind,layer:"upstream",retryability:"non-retryable",message:"The signed-in macOS user\u2019s Messages database is missing."};case"permission_denied":return{code:kind,layer:"auth",retryability:"non-retryable",message:"Allow the Indra host process to read Messages in macOS Full Disk Access and retry."};case"busy":return{code:"resource_exhausted",layer:"upstream",retryability:"transient",message:"Messages changed during every snapshot attempt. Retry the sync."};case"data_loss":return{code:kind,layer:"upstream",retryability:"transient",message:"Indra could not obtain a consistent Messages database snapshot."}}}
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "@zortexhq/plugin-connector-imessage",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "default": "./dist/index.js"
8
+ }
9
+ },
10
+ "dependencies": {
11
+ "@zortexhq/plugin-connector-framework": "0.1.0"
12
+ },
13
+ "zortex": {
14
+ "role": "plugin"
15
+ }
16
+ }
@@ -0,0 +1 @@
1
+ export{setupCua,startManagedCua}from"../cua-runtime.js";
@@ -1 +1 @@
1
- import{constants}from"node:fs";import{open,realpath,stat}from"node:fs/promises";import{isAbsolute,relative,sep}from"node:path";export const MAX_PAGE_BYTES=64*1024;export function pageSchema(name,schema){if(name!=="read_text_file"||!schema||typeof schema!=="object"||Array.isArray(schema))return schema;const value=schema;return{...value,properties:{...value.properties,offset:{type:"integer",minimum:0,description:"Optional byte offset; enables bounded base64 paging."},length:{type:"integer",minimum:1,maximum:MAX_PAGE_BYTES},version:{type:"string",description:"Version returned by the previous page; abort if the file changed."}}}}function inside(root,file){const rel=relative(root,file);return rel!==""&&!isAbsolute(rel)&&rel!==".."&&!rel.startsWith(".."+sep)}function versionOf(s){return[s.dev,s.ino,s.size,s.mtimeMs,s.ctimeMs].join(":")}export async function readFilePage(roots,params,signal){if(params.offset===void 0&&params.length===void 0&&params.version===void 0)return void 0;if(Object.keys(params).some(k=>!["path","offset","length","version"].includes(k))||typeof params.path!=="string"||!isAbsolute(params.path)||!Number.isSafeInteger(params.offset)||Number(params.offset)<0||!Number.isSafeInteger(params.length)||Number(params.length)<1||Number(params.length)>MAX_PAGE_BYTES||params.version!==void 0&&typeof params.version!=="string")throw Error("Invalid bounded file read parameters.");if(Number(params.offset)>0&&!params.version)throw Error("A file version is required after the first page.");signal.throwIfAborted();const resolved=await realpath(params.path);const normalizedRoots=await Promise.all(roots.map(root=>realpath(root)));if(normalizedRoots.some((root,index)=>root!==roots[index]))throw Error("Selected root changed.");if(!normalizedRoots.some(root=>inside(root,resolved)))throw Error("File is outside the selected roots.");const handle=await open(resolved,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{const before=await handle.stat();if(!before.isFile())throw Error("Selected path is not a regular file.");const checkedPath=await realpath(params.path),checked=await stat(checkedPath);if(checkedPath!==resolved||before.dev!==checked.dev||before.ino!==checked.ino||!normalizedRoots.some(root=>inside(root,checkedPath)))throw Error("Selected file changed during validation.");const version=versionOf(before);if(params.version!==void 0&&params.version!==version)throw Error("Selected file changed between pages.");const offset=Number(params.offset),buffer=Buffer.alloc(Number(params.length));signal.throwIfAborted();const{bytesRead}=await handle.read(buffer,0,buffer.length,offset);const after=await handle.stat();if(versionOf(after)!==version)throw Error("Selected file changed during reading.");signal.throwIfAborted();return{structured:{encoding:"base64",data:buffer.subarray(0,bytesRead).toString("base64"),offset,nextOffset:offset+bytesRead,eof:offset+bytesRead>=after.size,version}}}finally{await handle.close()}}
1
+ import{constants}from"node:fs";import{open,opendir,realpath,stat}from"node:fs/promises";import{extname,isAbsolute,relative,sep}from"node:path";export const MAX_PAGE_BYTES=64*1024,MAX_DIRECTORY_ENTRIES=4096,MAX_DIRECTORY_PAGE=128;export function pageSchema(name,schema){if(!["read_text_file","read_media_file","list_directory"].includes(name)||!schema||typeof schema!=="object"||Array.isArray(schema))return schema;const value=schema;const properties=name==="list_directory"?{cursor:{type:"string",maxLength:512,description:"Continuation from a bounded directory page; invalidated when the directory changes."},limit:{type:"integer",minimum:1,maximum:MAX_DIRECTORY_PAGE}}:{offset:{type:"integer",minimum:0,description:"Optional byte offset; enables bounded base64 paging. Without paging, reads at most 64 KiB."},length:{type:"integer",minimum:1,maximum:MAX_PAGE_BYTES},version:{type:"string",maxLength:256,description:"Version returned by the previous page; abort if the file changed."}};return{...value,properties:{...value.properties,...properties}}}function inside(root,file){const rel=relative(root,file);return rel!==""&&!isAbsolute(rel)&&rel!==".."&&!rel.startsWith(".."+sep)}function versionOf(s){return[s.dev,s.ino,s.size,s.mtimeMs,s.ctimeMs].join(":")}async function selectedPath(roots,path,signal,directory=false){if(typeof path!=="string"||path.length>4096||!isAbsolute(path))throw Error("Select an absolute path in the granted folders.");signal.throwIfAborted();const resolved=await realpath(path),normalizedRoots=await Promise.all(roots.map(root=>realpath(root)));signal.throwIfAborted();if(normalizedRoots.some((root,index)=>root!==roots[index]))throw Error("Selected root changed.");if(!normalizedRoots.some(root=>inside(root,resolved)||directory&&root===resolved))throw Error("Path is outside the selected roots.");return resolved}const mediaTypes={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".wav":"audio/wav",".mp3":"audio/mpeg",".ogg":"audio/ogg",".flac":"audio/flac",".mp4":"video/mp4"};export async function readFilePage(roots,params,signal,kind="text"){const paging=params.offset!==void 0||params.length!==void 0||params.version!==void 0;if(Object.keys(params).some(k=>!["path","offset","length","version",...kind==="text"?["head","tail"]:[]].includes(k)))throw Error("Invalid bounded file read parameters.");const offset=params.offset??0,length=params.length??MAX_PAGE_BYTES,head=params.head,tail=params.tail;if(!Number.isSafeInteger(offset)||Number(offset)<0||!Number.isSafeInteger(length)||Number(length)<1||Number(length)>MAX_PAGE_BYTES||params.version!==void 0&&(typeof params.version!=="string"||params.version.length>256))throw Error("Invalid bounded file read parameters.");if(Number(offset)>0&&!params.version)throw Error("A file version is required after the first page.");if(head!==void 0&&(!Number.isSafeInteger(head)||Number(head)<1||Number(head)>1e4)||tail!==void 0&&(!Number.isSafeInteger(tail)||Number(tail)<1||Number(tail)>1e4)||head!==void 0&&tail!==void 0||paging&&(head!==void 0||tail!==void 0))throw Error("Choose bounded byte paging or one positive line selection.");const resolved=await selectedPath(roots,params.path,signal);const handle=await open(resolved,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0));try{const before=await handle.stat();signal.throwIfAborted();if(!before.isFile())throw Error("Selected path is not a regular file.");const checkedPath=await selectedPath(roots,params.path,signal),checked=await stat(checkedPath);if(checkedPath!==resolved||before.dev!==checked.dev||before.ino!==checked.ino)throw Error("Selected file changed during validation.");if(process.platform==="linux"&&await realpath("/proc/self/fd/"+handle.fd)!==resolved)throw Error("Opened file is outside the selected path.");const version=versionOf(before);if(params.version!==void 0&&params.version!==version)throw Error("Selected file changed between pages.");const start=tail===void 0?Number(offset):Math.max(0,before.size-Number(length));const buffer=Buffer.alloc(Number(length)+(paging?0:1));let count=0;while(count<buffer.length){signal.throwIfAborted();const read=await handle.read(buffer,count,buffer.length-count,start+count);signal.throwIfAborted();if(!read.bytesRead)break;count+=read.bytesRead}const after=await handle.stat(),finalPath=await selectedPath(roots,params.path,signal),final=await stat(finalPath);if(versionOf(after)!==version||finalPath!==resolved||final.dev!==before.dev||final.ino!==before.ino)throw Error("Selected file changed during reading.");signal.throwIfAborted();const data=buffer.subarray(0,Math.min(count,Number(length))),nextOffset=start+data.length,eof=nextOffset>=after.size;const page={offset:start,nextOffset,eof,version};if(paging)return{structured:{encoding:"base64",data:data.toString("base64"),...page}};if(kind==="media")return{structured:{encoding:"base64",mimeType:mediaTypes[extname(resolved).toLowerCase()]??"application/octet-stream",data:data.toString("base64"),bytes:data.length,truncated:!eof,...page}};let leading=0;if(tail!==void 0&&start>0)while(leading<3&&leading<data.length&&(data[leading]&192)===128)leading++;let text;try{text=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(data.subarray(leading),{stream:!eof})}catch{throw Error("This bounded prefix is not UTF-8 text; use read_media_file or explicit byte paging.")}if(text.includes("\0"))throw Error("This file contains binary data; use read_media_file or explicit byte paging.");const decodedEnd=start+leading+Buffer.byteLength(text,"utf8");let textOffset=start+leading;if(head!==void 0||tail!==void 0){const ended=text.endsWith("\n"),lines=text.split("\n");if(ended)lines.pop();if(tail!==void 0&&start>0&&lines.length>1)lines.shift();const chosen=head!==void 0?lines.slice(0,Number(head)):lines.slice(-Number(tail));text=chosen.join("\n")+(ended||head!==void 0&&chosen.length<lines.length?"\n":"");if(tail!==void 0)textOffset=decodedEnd-Buffer.byteLength(text,"utf8")}const textBytes=Buffer.byteLength(text,"utf8"),textNext=textOffset+textBytes;return{structured:{encoding:"utf-8",text,bytes:textBytes,truncated:textOffset>0||textNext<after.size,...page,offset:textOffset,nextOffset:textNext,eof:textNext>=after.size}}}finally{await handle.close()}}export async function listDirectoryPage(roots,params,signal){if(Object.keys(params).some(k=>!["path","cursor","limit"].includes(k)))throw Error("Invalid bounded directory parameters.");const limit=params.limit??MAX_DIRECTORY_PAGE;if(!Number.isSafeInteger(limit)||Number(limit)<1||Number(limit)>MAX_DIRECTORY_PAGE)throw Error("Choose a directory page of 1\u2013128 entries.");const path=await selectedPath(roots,params.path,signal,true),before=await stat(path),version=versionOf(before);if(!before.isDirectory())throw Error("Selected path is not a directory.");let offset=0;if(params.cursor!==void 0){if(typeof params.cursor!=="string"||!/^[A-Za-z0-9_-]{1,512}$/.test(params.cursor))throw Error("Invalid directory cursor.");const cursor=JSON.parse(Buffer.from(params.cursor,"base64url").toString("utf8"));if(!cursor||cursor.version!==version||!Number.isSafeInteger(cursor.offset)||Number(cursor.offset)<0||Number(cursor.offset)>=MAX_DIRECTORY_ENTRIES)throw Error("Directory changed or cursor exceeds the bounded listing.");offset=Number(cursor.offset)}const entries=[],directory=await opendir(path,{bufferSize:32});let visited=0,more=false,nextOffset=offset;try{if(await selectedPath(roots,params.path,signal,true)!==path||versionOf(await stat(path))!==version)throw Error("Directory changed while opening.");for await(const entry of directory){signal.throwIfAborted();if(visited>=MAX_DIRECTORY_ENTRIES){more=true;break}visited++;if(visited<=offset)continue;if(entries.length>=Number(limit)){more=true;break}entries.push({name:entry.name,type:entry.isSymbolicLink()?"symlink":entry.isDirectory()?"directory":entry.isFile()?"file":"other"});nextOffset=visited}if(await selectedPath(roots,params.path,signal,true)!==path||versionOf(await stat(path))!==version)throw Error("Directory changed during listing.");const next=more&&nextOffset<MAX_DIRECTORY_ENTRIES?Buffer.from(JSON.stringify({version,offset:nextOffset})).toString("base64url"):void 0;return{structured:{entries,text:entries.map(row=>(row.type==="directory"?"[DIR]":"[FILE]")+" "+row.name).join("\n"),truncated:more,scanned:visited,...next?{next}:{},...!next&&more?{warning:"Directory listing reached its entry limit; use computer-files.catalog.list for bounded catalog search."}:{}}}}finally{await directory.close().catch(()=>{})}}export function createComputerFilesAdapter(roots){let active=0;return async(name,params,signal)=>{if(name==="search_files")throw Error("Recursive filesystem search is disabled. Use computer-files.catalog.list for bounded catalog search.");if(!["read_text_file","read_media_file","list_directory"].includes(name))return void 0;if(active>=2)throw Error("Computer Files already has two local reads in progress.");active++;try{return name==="list_directory"?await listDirectoryPage(roots,params,signal):await readFilePage(roots,params,signal,name==="read_media_file"?"media":"text")}finally{active--}}}
@@ -0,0 +1 @@
1
+ import{lstat}from"node:fs/promises";import{isDeepStrictEqual}from"node:util";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{createComputerFiles}from"@zortexhq/plugin-connector-computer-files";import{captureCustodied,checkCustodied}from"./custodied.js";import{withSettingsReadLock}from"./settings-transaction.js";const source="computer-files",prefix="computer-files.catalog.";const denied=()=>businessError("permission_denied","Computer Files folder selection or native permission changed. Reconnect the selected folders.","plugin");const revision=value=>[value.dev,value.ino,value.size,value.mtimeMs,value.ctimeMs].join(":");const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);export async function attachComputerFiles(original,options){const{vault,auth,selection}=options,prepared=selection.prepared?.[source];if(!Array.isArray(prepared?.roots)||prepared.roots.some(root=>typeof root!=="string")||auth.credentialKind!=="local-no-secret")throw Error("Computer Files requires its prepared native folders.");let closed=false;const currentSelection=value=>!!value?.sources?.includes(source)&&(value.requestedSources===void 0||value.requestedSources.includes(source))&&isDeepStrictEqual(value.prepared?.[source],prepared)&&isDeepStrictEqual(value.bindings?.[source],selection.bindings?.[source]);const authorize=async signal=>{const lifetime=signal??new AbortController().signal;if(closed)return businessError("unavailable","Computer Files is inactive.","plugin");const access=await captureCustodied(source,auth,vault,lifetime);if(!("ok"in access))return access;let selectedRevision;try{if(options.settingsFile)selectedRevision=await withSettingsReadLock(options.settingsFile,()=>{},async current=>{if(!currentSelection(current))throw Error("Folder selection changed.");const metadata=await lstat(options.settingsFile);if(!metadata.isFile()||metadata.isSymbolicLink())throw Error("Settings changed.");return revision(metadata)},{signal:lifetime})}catch{return denied()}const check=async(nextSignal=lifetime)=>{if(closed)return businessError("unavailable","Computer Files is inactive.","plugin");if(nextSignal.aborted)return businessError("aborted","Computer Files operation was cancelled.","plugin");const selected=async()=>{if(selectedRevision===void 0)return true;try{const metadata=await lstat(options.settingsFile);return metadata.isFile()&&!metadata.isSymbolicLink()&&revision(metadata)===selectedRevision}catch{return false}};if(!await selected())return denied();const checked2=await checkCustodied(source,auth,vault,access.ok,nextSignal);if(!("ok"in checked2))return checked2;if(!await selected())return denied();return ok(true)};const checked=await check();return"ok"in checked?ok({check}):checked};const files=await createComputerFiles({vault:options.sqlite,roots:prepared.roots,...options.excludeRoots?{excludeRoots:options.excludeRoots}:{},authorize});const local=files.provider,legacy=original.actions,catalog=local.actions;const provider={...original,status:local.status,connect:local.connect,check:local.check,read:local.read,...original.fileSnapshots?{fileSnapshots:{inspect:(input,readOptions)=>files.withAccess(()=>original.fileSnapshots.inspect(input,readOptions),readOptions?.signal),materialize:(file,readOptions)=>files.withReadAccess(()=>original.fileSnapshots.materialize(file,readOptions),readOptions?.signal)}}:{},job(id){const job=local.job(id);return"err"in job&&job.err.code==="not_found"?original.job(id):job},actions:{reportsActionAccess:true,async catalog(input){const limit=input?.limit??50,cursor=input?.cursor??0;if(!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return businessError("invalid_argument","Catalog limit/cursor is invalid.","plugin");const page=(base,actions2)=>{const value={...base,actions:actions2.slice(cursor,cursor+limit),total:actions2.length};delete value.nextCursor;if(cursor+limit<actions2.length)value.nextCursor=cursor+limit;return ok(value)};const metadata=await catalog.catalog(input);if(input?.query?.toLowerCase().startsWith(prefix))return"ok"in metadata&&object(metadata.ok)&&Array.isArray(metadata.ok.actions)?page(metadata.ok,metadata.ok.actions):metadata;const upstream=await legacy.catalog({...input,cursor:0,limit:100});if(!("ok"in metadata)||!object(metadata.ok)||!Array.isArray(metadata.ok.actions))return upstream;if(!("ok"in upstream)||!object(upstream.ok)||!Array.isArray(upstream.ok.actions))return page({...metadata.ok,warnings:["The filesystem Actions are currently unavailable; catalog Actions remain available."]},metadata.ok.actions);const actions=[...metadata.ok.actions,...upstream.ok.actions];return page(upstream.ok,actions)},method(name){return name.startsWith(prefix)?catalog.method(name):legacy.method(name)},async invoke(name,input,actionOptions){if(name==="computer-files.search_files")return files.withAccess(async()=>businessError("failed_precondition","Use computer-files.catalog.list to search the bounded metadata catalog by file name or path. Recursive filesystem MCP search is unavailable.","plugin"),actionOptions?.signal);if(!name.startsWith(prefix))return name==="computer-files.read_text_file"||name==="computer-files.read_media_file"?files.withReadAccess(()=>legacy.invoke(name,input,actionOptions),actionOptions?.signal):files.withAccess(()=>legacy.invoke(name,input,actionOptions),actionOptions?.signal);const access=await authorize(actionOptions?.signal);if(!("ok"in access))return access;try{actionOptions?.onActionAccess?.("account",async()=>"ok"in await access.ok.check(actionOptions?.signal))}catch{}return catalog.invoke(name,input,actionOptions)}},async close(){closed=true;await Promise.allSettled([files.close(),original.close()])}};return{provider,files}}
@@ -0,0 +1 @@
1
+ import{execFile}from"node:child_process";import{createHash}from"node:crypto";import{accessSync,constants}from"node:fs";import{mkdir,mkdtemp,rename,rm,stat}from"node:fs/promises";import{createConnection}from"node:net";import{homedir}from"node:os";import{dirname,join}from"node:path";import{setTimeout as delay}from"node:timers/promises";import{promisify}from"node:util";export const cuaVersion="0.28.2";const releases={arm64:["arm64","818ddefa0fa8ba2ec9cba837c7aa634a4b064221c748752cf49c5b08e2c94e8c"],x64:["x86_64","9e00cc92480a8f3d32bbcb7cb45cbc42293b7bd13c1808f5047f1f73a8b64f24"]};const invoke=promisify(execFile);const bundle="CuaDriver.app";const archiveLimit=8e7;const managedApp=join(homedir(),"Applications","Zortex",bundle);const appLocations=[managedApp,"/Applications/"+bundle,join(homedir(),"Applications",bundle)];const executable=app=>join(app,"Contents","MacOS","cua-driver");export const cuaSocket=process.platform==="darwin"?join(homedir(),"Library","Caches","cua-driver","cua-driver.sock"):void 0;function installed(app){try{accessSync(executable(app),constants.X_OK);return true}catch{return false}}export function macCuaApp(){return cuaSocket&&appLocations.find(installed)}export function cuaCommand(){const app=macCuaApp();return app?executable(app):"cua-driver"}async function run(command,args,timeout=15e3){return invoke(command,args,{timeout,maxBuffer:64*1024,windowsHide:true})}async function install(driverArch,sha256){const parent=dirname(managedApp);await mkdir(parent,{recursive:true});const stage=await mkdtemp(join(parent,".cua-driver-"));try{const asset=`cua-driver-rs-${cuaVersion}-darwin-${driverArch}`;const url=`https://github.com/trycua/cua/releases/download/cua-driver-rs-v${cuaVersion}/${asset}.tar.gz`;const{stdout:archive}=await invoke("/usr/bin/curl",["--disable","--fail","--silent","--show-error","--location","--proto","=https","--proto-redir","=https","--max-filesize",String(archiveLimit),url],{encoding:"buffer",timeout:12e4,maxBuffer:archiveLimit});if(createHash("sha256").update(archive).digest("hex")!==sha256)throw Error("The CUA Driver download failed its checksum.");const extraction=invoke("/usr/bin/tar",["-xzf","-","-C",stage,"--strip-components","1",`${asset}/${bundle}`],{timeout:3e4,maxBuffer:64*1024});extraction.child.stdin?.on("error",()=>{});extraction.child.stdin?.end(archive);await extraction;const app=join(stage,bundle);await run("/usr/bin/codesign",["--verify","--deep","--strict",app]);try{await rename(app,managedApp)}catch(error){if(!installed(managedApp))throw error}return managedApp}finally{await rm(stage,{recursive:true,force:true})}}async function serviceRunning(){if(!cuaSocket||!(await stat(cuaSocket).catch(()=>void 0))?.isSocket())return false;return new Promise(resolve=>{const client=createConnection(cuaSocket);const finish=connected=>{client.destroy();resolve(connected)};client.setTimeout(400,()=>finish(false));client.once("error",()=>finish(false));client.once("connect",()=>finish(true))})}let starting;async function startApp(app){if(await serviceRunning())return true;await run("/usr/bin/open",["-n","-g","-a",app,"--args","serve","--no-overlay","--no-permissions-gate"]);for(let attempt=0;attempt<30;attempt++){if(await serviceRunning())return true;await delay(200)}return false}function start(app){return starting??=startApp(app).finally(()=>{starting=void 0})}export async function startManagedCua(){if(cuaSocket&&installed(managedApp))await start(managedApp)}export async function setupCua({grantPermissions=false}={}){const release=releases[process.arch];if(!cuaSocket||!release)return{state:"unsupported-platform"};let app;try{app=macCuaApp()??await install(release[0],release[1])}catch(error){const failure=error;if(failure.code==="ENOSPC"||failure.stderr?.includes("No space left on device")){return{state:"install-failed",reason:"disk-full",next:"Free disk space, then retry indra setup computer-use."}}return{state:"install-failed",next:"Retry indra setup computer-use to download and verify CUA Driver."}}try{if(grantPermissions)await run(executable(app),["permissions","grant"],12e4);if(await start(app)){const{stdout}=await run(executable(app),["permissions","status","--json"]);const permissions=JSON.parse(stdout);if(permissions.accessibility&&permissions.screen_recording&&permissions.screen_recording_capturable!==false){return{state:"installed",permissions}}return{state:"installed",permissions,next:"Run indra setup computer-use --grant-permissions to finish macOS access."}}}catch{}return{state:"installed",permissions:"unverified",next:"Run indra setup computer-use --grant-permissions to verify macOS access."}}