@zortexhq/indra-v2.5 0.3.2 → 0.4.1

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 (73) hide show
  1. package/README.md +93 -152
  2. package/dist/auto-sync.js +1 -1
  3. package/dist/auto-update.js +1 -1
  4. package/dist/bundled-handbook.js +1 -1
  5. package/dist/cli-run.js +1 -1
  6. package/dist/cli.js +1 -1
  7. package/dist/codex-install.js +1 -1
  8. package/dist/codex-setup.js +1 -1
  9. package/dist/content-find.js +1 -1
  10. package/dist/gateway.js +1 -1
  11. package/dist/mcp.js +2 -2
  12. package/dist/onboard-cli.js +1 -0
  13. package/dist/onboard.js +1 -0
  14. package/dist/operation-telemetry.js +1 -1
  15. package/dist/public-tool.js +1 -1
  16. package/dist/read-route.js +1 -1
  17. package/dist/recovery-resident-port.js +1 -0
  18. package/dist/resident-host.js +2 -2
  19. package/dist/resident-jobs.js +1 -1
  20. package/dist/resident-platform.js +3 -3
  21. package/dist/resident-runtime-identity.js +1 -1
  22. package/dist/resident-shutdown.js +1 -0
  23. package/dist/resident-startup-preference.js +1 -0
  24. package/dist/resident-telemetry.js +1 -1
  25. package/dist/update-cli.js +1 -1
  26. package/dist/update-command.js +1 -0
  27. package/dist/update-handover.js +1 -0
  28. package/dist/update-recovery.js +1 -1
  29. package/dist/update-tool.js +1 -1
  30. package/dist/web.js +1 -1
  31. package/dist/zortex-cli.js +1 -1
  32. package/node_modules/@zortexhq/plugin-connector-activitywatch/dist/provider.js +1 -1
  33. package/node_modules/@zortexhq/plugin-connector-core/dist/api/connectors.js +1 -1
  34. package/node_modules/@zortexhq/plugin-connector-core/dist/api/content-acquisition.js +1 -0
  35. package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
  36. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  37. package/node_modules/@zortexhq/plugin-connector-level1/dist/action-content.js +1 -0
  38. package/node_modules/@zortexhq/plugin-connector-level1/dist/operational-client.js +1 -1
  39. package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-graph.js +1 -1
  40. package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/content.js +1 -0
  41. package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/specs.js +1 -1
  42. package/node_modules/@zortexhq/plugin-connector-level1/dist/service-sdk-matrix.js +1 -1
  43. package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
  44. package/node_modules/@zortexhq/plugin-connector-netease/dist/provider.js +1 -1
  45. package/node_modules/@zortexhq/plugin-connector-notion/dist/provider.js +1 -1
  46. package/node_modules/@zortexhq/plugin-connector-outlook/dist/actions.js +1 -1
  47. package/node_modules/@zortexhq/plugin-connector-outlook/dist/mail-sync.js +1 -1
  48. package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
  49. package/node_modules/@zortexhq/plugin-connector-steam/dist/provider.js +1 -1
  50. package/node_modules/@zortexhq/plugin-connector-teams/dist/provider.js +1 -1
  51. package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/provider.js +1 -1
  52. package/node_modules/@zortexhq/plugin-connector-youtube/dist/content.js +1 -0
  53. package/node_modules/@zortexhq/plugin-connector-youtube/dist/full-sync.js +1 -1
  54. package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
  55. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
  56. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/portrait-producer.js +1 -1
  57. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/record-identity.js +6 -0
  58. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/snapshot.js +1 -1
  59. package/node_modules/@zortexhq/plugin-posthog/dist/activity.js +1 -1
  60. package/node_modules/@zortexhq/plugin-posthog/dist/northstar.js +1 -1
  61. package/node_modules/@zortexhq/plugin-telemetry/dist/api/measurement.js +1 -1
  62. package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
  63. package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
  64. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-call.js +1 -1
  65. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-methods.js +1 -1
  66. package/node_modules/@zortexhq/plugin-telemetry/dist/index.js +1 -1
  67. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/content-acquisition.js +1 -0
  68. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
  69. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/content-acquisition.js +1 -0
  70. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  71. package/package.json +7 -7
  72. package/release-provenance.json +29 -29
  73. package/update-manifest.json +230 -146
@@ -1 +1 @@
1
- import{randomUUID}from"node:crypto";import makeWASocket,{Browsers,DisconnectReason,fetchLatestBaileysVersion,jidDecode}from"baileys";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{sessionStore}from"./auth-state.js";import{toRecords}from"./messages.js";import{openPairingPage}from"./pairing-page.js";import{TransientMessageBuffer,TRANSIENT_MESSAGE_LIMIT}from"./transient-buffer.js";export const SOURCE="whatsapp-web";const silent={level:"silent",child:()=>silent,trace(){},debug(){},info(){},warn(){},error(){},fatal(){}};async function defaultSocket(auth,fullHistory){const version=await Promise.race([fetchLatestBaileysVersion().then(r=>r.version).catch(()=>void 0),new Promise(resolve=>setTimeout(resolve,5e3))]);return makeWASocket({auth,logger:silent,browser:Browsers.macOS("Chrome"),syncFullHistory:fullHistory,markOnlineOnConnect:false,...version?{version}:{}})}const statusCode=update=>update.lastDisconnect?.error?.output?.statusCode;function nativeAccount(socket){const identity=jidDecode(socket?.user?.id);return identity?.server==="s.whatsapp.net"&&/^[1-9][0-9]{4,19}$/u.test(identity.user)?identity.user:void 0}export function createWhatsappProvider({vault,socket,pairingPage=openPairingPage,openUrl=openConnectionUrl,payloadRetention="cache",pairingTimeoutMs=18e4,resumeTimeoutMs=2e4,historyTimeoutMs=3e4}){if(!["cache","transient"].includes(payloadRetention)||[pairingTimeoutMs,resumeTimeoutMs,historyTimeoutMs].some(ms=>!Number.isInteger(ms)||ms<1||ms>6e5))throw Error("Invalid WhatsApp retention or timeout configuration.");const transient=payloadRetention==="transient",makeSocket=socket??(auth=>defaultSocket(auth,!transient));const info={source:SOURCE,label:"WhatsApp",group:"Connector / Chat",auth:"native-browser"};const jobs=new Map,names=new Map,buffer=new TransientMessageBuffer,pairings=new Set;const initializing=new Set;let live,resuming,closed=false,closing;let writes=Promise.resolve(),persistTimer;const fail=(code,message)=>businessError(code,message,"plugin");const enqueue=task=>{writes=writes.then(task,task).catch(()=>void 0);return writes};const track=task=>{initializing.add(task);void task.then(()=>initializing.delete(task),()=>initializing.delete(task));return task};const notify=entry=>{for(const wake of entry.waiters)wake()};const owned=(entry,sock=entry.socket)=>!closed&&!entry.stopped&&live===entry&&entry.socket===sock;function remember(jid,name){if(!jid||jid.length>512||!name)return;names.delete(jid);names.set(jid,name.slice(0,256));if(names.size>2e3)names.delete(names.keys().next().value)}function stopLive(entry){entry.stopped=true;entry.online=false;entry.resolveOpen(false);notify(entry);entry.socket?.end();if(live===entry){live=void 0;buffer.clear();names.clear()}}function waitUntil(entry,predicate,timeout,signal){if(predicate())return Promise.resolve(true);if(signal?.aborted||closed||entry.stopped)return Promise.resolve(false);return new Promise(resolve=>{const finish=value=>{clearTimeout(timer);entry.waiters.delete(wake);signal?.removeEventListener("abort",abort);resolve(value)};const wake=()=>{if(predicate())finish(true);else if(closed||entry.stopped)finish(false)};const abort=()=>finish(false),timer=setTimeout(()=>finish(false),timeout);entry.waiters.add(wake);signal?.addEventListener("abort",abort,{once:true});wake()})}async function captureAuthority(accountId){const custody=vault.bindingCustody;if(!custody)return transient?fail("failed_precondition","Transient WhatsApp requires durable native account custody."):ok(void 0);const selected=await custody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved")return fail("failed_precondition","WhatsApp needs one explicit native account binding.");const current=await custody.credentialSnapshot(oauthCredentialResourceId(selected.ok.binding.id),{purpose:"L1",audience:SOURCE});if(!("ok"in current))return current;const value=current.ok;if(value.binding.identity.source!==SOURCE||value.binding.identity.issuer!==SOURCE||value.binding.identity.subject!==accountId||value.binding.identity.tenant!==null||value.material.kind!=="oauth"||value.resource.kind!=="oauth"||value.resource.owner.kind!=="resident"||value.material.credential.clientId!=="whatsapp-linked-device"||!value.grant.scopes.includes("messages.read"))return fail("permission_denied","WhatsApp session custody does not match the selected native account.");return ok({binding:value.binding,grant:value.grant,resource:value.resource})}async function checkAuthority(entry){if(!entry.accountId||nativeAccount(entry.socket)!==entry.accountId)return fail("failed_precondition","WhatsApp signed-in account changed. Reconnect the selected account.");const current=await captureAuthority(entry.accountId);if(!("ok"in current))return current;const expected=entry.authority,latest=current.ok;if(expected&&(!latest||latest.binding.id!==expected.binding.id||latest.binding.revision!==expected.binding.revision||latest.grant.id!==expected.grant.id||latest.grant.revision!==expected.grant.revision||latest.grant.scopeEpoch!==expected.grant.scopeEpoch||latest.resource.id!==expected.resource.id))return fail("permission_denied","WhatsApp account permission changed while the operation was pending.");return ok(latest)}async function persistNow(entry){if(!entry.accountId||!entry.online||entry.stopped)return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}if(entry.stopped||!entry.online)return;const credential={accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]};const saved=allowed.ok&&vault.bindingCustody?await vault.bindingCustody.compareAndSwapResource({...allowed.ok.resource,updatedAt:new Date().toISOString()},{kind:"oauth",credential},allowed.ok.resource.revision):await vault.updateCredential(SOURCE,credential);if(!("ok"in saved))stopLive(entry)}function persist(entry){if(!owned(entry)||!entry.accountId)return;clearTimeout(persistTimer);persistTimer=setTimeout(()=>{void enqueue(()=>persistNow(entry))},1e3);persistTimer.unref?.()}function store(entry,sock,messages,history=false){if(!owned(entry,sock)||!entry.accountId||nativeAccount(sock)!==entry.accountId||transient&&!entry.online)return;if(transient){for(const message of messages)for(const record of toRecords(entry.accountId,[message],jid=>names.get(jid)))buffer.add(record);if(history||messages.length>0)entry.historyArrived=true;notify(entry);return}const records=toRecords(entry.accountId,messages,jid=>names.get(jid));for(let i=0;i<records.length;i+=100){const batch=records.slice(i,i+100);void enqueue(async()=>{if(!await entry.open||!owned(entry,sock))return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}await cache(vault,SOURCE,batch);entry.historyArrived=true;notify(entry)})}}async function markLoggedOut(entry){if(!entry.accountId)return;if(vault.bindingCustody&&entry.authority){const current=await vault.bindingCustody.binding(entry.authority.binding.id);if("ok"in current&&current.ok?.revision===entry.authority.binding.revision)await vault.bindingCustody.compareAndSwapBinding({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},current.ok.revision)}else{const current=await vault.connection(SOURCE);if("ok"in current&&current.ok?.accountId===entry.accountId)await vault.saveConnection({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},{accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]})}}async function start(stateStore,accountId,authority,onView,onOpen,onFailure){if(closed)throw Error("inactive");let resolveOpen;const open=new Promise(resolve=>{resolveOpen=resolve});const current={store:stateStore,open,resolveOpen,...accountId?{accountId}:{},...authority?{authority}:{},online:false,stopped:false,historyArrived:false,needsPairing:false,waiters:new Set};live=current;buffer.clear();names.clear();let restarts=0,generation=0;const failed=code=>{current.failure=code;stopLive(current);onFailure?.(code)};const connect=async()=>{if(!owned(current))return;const attempt=++generation,previous=current.socket;delete current.socket;previous?.end();const sock=await track(makeSocket(current.store.state));if(!owned(current)||attempt!==generation){sock.end();return}current.socket=sock;sock.ev.on("creds.update",()=>{if(owned(current,sock))persist(current)});sock.ev.on("connection.update",update=>{if(!owned(current,sock))return;if(update.qr){current.needsPairing=true;onView?.({state:"qr",qr:update.qr});notify(current)}if(update.connection==="open"){const linked=nativeAccount(sock);if(!linked||current.accountId&&current.accountId!==linked){failed("account_changed");return}current.accountId=linked;void(async()=>{const completed=await onOpen?.(current);if(!owned(current,sock))return;const captured=current.authority?await checkAuthority(current):await captureAuthority(linked);if(!("ok"in captured)){failed("account_permission_changed");return}if(!owned(current,sock))return;if(!current.authority)current.authority=captured.ok;current.online=true;current.needsPairing=false;restarts=0;resolveOpen(true);notify(current);completed?.()})().catch(()=>failed("pairing_unavailable"))}if(update.connection==="close"){current.online=false;notify(current);const code=statusCode(update);if(code===DisconnectReason.loggedOut){current.needsPairing=true;void enqueue(()=>markLoggedOut(current));failed("qr_scan_required");return}if(code!==DisconnectReason.connectionReplaced&&restarts++<5){void connect().catch(()=>failed("connection_unavailable"));return}failed("connection_unavailable")}});sock.ev.on("messaging-history.set",({chats,contacts,messages})=>{if(!owned(current,sock))return;for(const chat of chats)remember(chat.id,chat.name);for(const contact of contacts)remember(contact.id,contact.name??contact.notify);store(current,sock,messages,true)});sock.ev.on("chats.upsert",chats=>{if(owned(current,sock))for(const chat of chats)remember(chat.id,chat.name)});sock.ev.on("contacts.upsert",contacts=>{if(owned(current,sock))for(const contact of contacts)remember(contact.id,contact.name??contact.notify)});sock.ev.on("messages.upsert",({messages})=>{if(!owned(current,sock))return;for(const message of messages)if(!message.key.fromMe)remember(message.key.remoteJid,message.key.remoteJid?.endsWith("@g.us")?void 0:message.pushName);store(current,sock,messages)})};try{await connect()}catch(error){failed("connection_unavailable");throw error}return current}async function resume(){if(live&&!live.stopped)return live;if(resuming)return resuming;resuming=(async()=>{const connection=await vault.connection(SOURCE);if(!("ok"in connection))throw Error("account_permission_changed");if(connection.ok?.state!=="connected"||!connection.ok.accountId)return void 0;const grant=await vault.credential(SOURCE);if(!("ok"in grant))throw Error("account_permission_changed");const authority=await captureAuthority(connection.ok.accountId);if(!("ok"in authority))throw Error("account_permission_changed");const restored=sessionStore(grant.ok.accessToken,()=>{if(live)persist(live)});return start(restored,connection.ok.accountId,authority.ok)})();try{return await resuming}finally{resuming=void 0}}function cleanPairing(pair2){clearTimeout(pair2.timer);pair2.removeAbort?.();pair2.page?.close();pairings.delete(pair2)}function failPairing(pair2,code,message){if(pair2.job.state==="waiting-user"){pair2.job.state="failed";pair2.job.error={code,message};delete pair2.job.authorizationUrl;delete pair2.job.instructions;pair2.stop.abort();pair2.page?.update({state:"failed",message});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live)}cleanPairing(pair2)}function cancelPairing(pair2){if(pair2.job.state==="waiting-user")pair2.job.state="cancelled";delete pair2.job.authorizationUrl;delete pair2.job.instructions;delete pair2.job.error;pair2.stop.abort();pair2.page?.update({state:"failed",message:"WhatsApp connection was cancelled."});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live);cleanPairing(pair2)}async function pair(job,options,expectedAccountId){if(closed)throw Error("inactive");const owner={job,stop:new AbortController};pairings.add(owner);const abort=()=>failPairing(owner,"aborted","WhatsApp connection was cancelled.");options.signal?.addEventListener("abort",abort,{once:true});owner.removeAbort=()=>options.signal?.removeEventListener("abort",abort);try{owner.page=await pairingPage();if(closed||options.signal?.aborted||owner.stop.signal.aborted){abort();return}job.authorizationUrl=owner.page.url;job.instructions="Open the QR code page, then use WhatsApp on your phone: Settings \u2192 Linked devices \u2192 Link a device. The connection continues automatically after scanning.";job.error={code:"qr_scan_required",message:"Scan the WhatsApp QR code with your phone."};owner.timer=setTimeout(()=>failPairing(owner,"pairing_timeout","WhatsApp QR was not scanned before it expired."),pairingTimeoutMs);owner.timer.unref?.();const fresh=sessionStore(void 0,()=>{if(owner.entry)persist(owner.entry)});if(live)stopLive(live);owner.entry=await start(fresh,expectedAccountId,void 0,view=>{if(job.state==="waiting-user")owner.page?.update(view)},async current=>{if(job.state==="connected"&&!closed)return;if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)throw Error("aborted");const saved=await vault.saveConnection({source:SOURCE,provider:SOURCE,account:current.socket?.user?.name?.slice(0,256)||"WhatsApp",accountId:current.accountId,scopes:["messages.read"],state:"connected",updatedAt:new Date().toISOString()},{accessToken:current.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]},{signal:owner.stop.signal});if(!("ok"in saved))throw Error("custody_failed");return()=>{if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)return;clearTimeout(owner.timer);owner.removeAbort?.();job.state="connected";job.account=saved.ok.account;delete job.instructions;delete job.authorizationUrl;delete job.error;owner.page?.update({state:"connected"});owner.timer=setTimeout(()=>cleanPairing(owner),1e4);owner.timer.unref?.()}},code=>failPairing(owner,code,code==="account_changed"?"The scanned WhatsApp account does not match the selected account.":"WhatsApp pairing did not complete."));if(owner.stop.signal.aborted)stopLive(owner.entry);if(!options.automatic&&options.manualPresentation!=="return-url"&&job.state==="waiting-user")await openUrl(owner.page.url)}catch{failPairing(owner,"pairing_unavailable","WhatsApp pairing page or connection could not start.")}}return{info,...transient?{}:{requiresPersistentPayloads:true},status:()=>connectionState(vault,info),job(id){const job=jobs.get(id);return job?ok({...job}):fail("not_found","WhatsApp connection job not found.")},cancelJob(id){const job=jobs.get(id);if(!job)return ok({id,cleanup:"confirmed"});const pairing=[...pairings].find(owner=>owner.job===job);if(pairing)cancelPairing(pairing);else if(job.state==="waiting-user")job.state="cancelled";delete job.authorizationUrl;delete job.instructions;return ok({id,cleanup:[...pairings].some(owner=>owner.job===job)?"pending":"confirmed"})},async connect(options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");const running=[...jobs.values()].find(job2=>job2.state==="waiting-user");if(running)return ok({...running});for(const[id,job2]of jobs)if(jobs.size>=32&&job2.state!=="waiting-user")jobs.delete(id);const job={id:randomUUID(),source:SOURCE,state:"waiting-user",startedAt:new Date().toISOString()};jobs.set(job.id,job);try{const selected=await vault.connection(SOURCE);if(!("ok"in selected))return selected;if(selected.ok&&!selected.ok.accountId)return fail("failed_precondition","WhatsApp needs a verified native account binding.");if(options.expectedBinding?.kind==="legacy-source"&&options.expectedBinding.source!==SOURCE)return fail("invalid_argument","WhatsApp account selection names another source.");if(options.expectedBinding?.kind==="binding"){const binding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in binding)||binding.ok.kind!=="resolved"||binding.ok.binding.id!==options.expectedBinding.bindingId)return fail("failed_precondition","WhatsApp account selection does not match this linked device.")}if(closed)return fail("unavailable","WhatsApp source is inactive.");const resumed=await track(resume());if(resumed){await waitUntil(resumed,()=>resumed.online||resumed.needsPairing,resumeTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");if(resumed.online){const allowed=await checkAuthority(resumed);if(!("ok"in allowed))return allowed;job.state="connected";if(selected.ok)job.account=selected.ok.account;return ok({...job})}if(!resumed.needsPairing){job.state="failed";job.error={code:resumed.failure??"connection_unavailable",message:resumed.failure==="account_changed"?"WhatsApp signed in as a different account.":"The existing WhatsApp session did not reconnect."};return ok({...job})}}if(options.automatic&&!transient){job.state="failed";job.error={code:"qr_scan_required",message:"WhatsApp needs one QR scan from the phone; connect it explicitly."};return ok({...job})}if(options.automatic&&selected.ok?.accountId&&vault.bindingCustody){const selectedBinding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if("ok"in selectedBinding&&selectedBinding.ok.kind==="resolved"){const grant=await vault.bindingCustody.grantForBinding(selectedBinding.ok.binding.id,"L1",SOURCE);if(!("ok"in grant))return grant;if(grant.ok?.state==="revoked")return fail("permission_denied","WhatsApp access was revoked. Reconnect explicitly to grant it again.")}}await track(pair(job,options,selected.ok?.accountId))}catch{job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp session permission or connection could not be verified."}}finally{if(job.state==="waiting-user"&&![...pairings].some(owner=>owner.job===job)){job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp did not start an owned connection job."}}}return ok({...job})},async read(request,options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");const invalid=validateRead(request);if(invalid)return invalid;if(request.fileId!==void 0)return fail("invalid_argument","WhatsApp message reads support limit, query and time filters; file download is not supported.");if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const connection=await vault.connection(SOURCE);if(!("ok"in connection))return connection;if(connection.ok?.state!=="connected"||!connection.ok.accountId)return fail("unauthenticated","Connect WhatsApp by scanning its QR code first.");const session=await track(resume()).catch(()=>void 0);const online=session?await waitUntil(session,()=>session.online,resumeTimeoutMs,options.signal):false;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const warnings=[];let records;if(transient){if(!online||!session)return fail("unavailable","WhatsApp is offline; transient reads need the selected live session.");const allowed=await checkAuthority(session);if(!("ok"in allowed)){stopLive(session);return allowed}await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");if(!owned(session)||!session.online)return fail("unavailable","WhatsApp session ended before the message read.");const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(!session.historyArrived)return fail("unavailable","No live WhatsApp message batch has arrived for this session yet. Retry after the phone finishes linking or a message arrives.");records=buffer.snapshot();warnings.push(`This live session retains at most ${TRANSIENT_MESSAGE_LIMIT} messages and 4 MiB in memory. Messages are not saved and are cleared on restart.`)}else{if(!online)warnings.push("WhatsApp is offline right now; showing messages already saved in the Vault.");if(online&&session&&!session.historyArrived){const stored2=await vault.records(SOURCE,1);if(!("ok"in stored2)||!stored2.ok.length)await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal)}await writes;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const stored=await vault.records(SOURCE,100);if(!("ok"in stored))return stored;records=stored.ok.map(row=>row.data);if(request.query||request.since||request.until)warnings.push("Filters apply to the 100 most recent saved messages; use SQL search over z_records for older history.")}const since=request.since?Date.parse(request.since):-Infinity,until=request.until?Date.parse(request.until):Infinity,query=request.query?.toLowerCase();records=records.filter(record=>record.sourceId?.startsWith(connection.ok.accountId+":")).filter(record=>{const at=Date.parse(record.ts??"");return at>=since&&at<=until}).filter(record=>!query||`${record.body} ${record.fields?.chat??""}`.toLowerCase().includes(query)).slice(0,request.limit??1);if(transient&&session){const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(closed||!owned(session)||options.signal?.aborted)return fail("aborted","WhatsApp read was cancelled before delivery.")}return readResult(SOURCE,records,warnings)},close(){if(closing)return closing;closing=(async()=>{closed=true;clearTimeout(persistTimer);for(const owner of[...pairings]){if(owner.job.state==="waiting-user")failPairing(owner,"aborted","WhatsApp source was closed.");else cleanPairing(owner)}await Promise.allSettled([...initializing]);await writes;if(live){const current=live;await persistNow(current).catch(()=>void 0);stopLive(current)}buffer.clear();names.clear()})();return closing}}}
1
+ import{acquiredReadCapability,unreviewedActionContent}from"@zortexhq/plugin-connector-core/api";import{randomUUID}from"node:crypto";import makeWASocket,{Browsers,DisconnectReason,fetchLatestBaileysVersion,jidDecode}from"baileys";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{sessionStore}from"./auth-state.js";import{toRecords}from"./messages.js";import{openPairingPage}from"./pairing-page.js";import{TransientMessageBuffer,TRANSIENT_MESSAGE_LIMIT}from"./transient-buffer.js";export const SOURCE="whatsapp-web";const silent={level:"silent",child:()=>silent,trace(){},debug(){},info(){},warn(){},error(){},fatal(){}};async function defaultSocket(auth,fullHistory){const version=await Promise.race([fetchLatestBaileysVersion().then(r=>r.version).catch(()=>void 0),new Promise(resolve=>setTimeout(resolve,5e3))]);return makeWASocket({auth,logger:silent,browser:Browsers.macOS("Chrome"),syncFullHistory:fullHistory,markOnlineOnConnect:false,...version?{version}:{}})}const statusCode=update=>update.lastDisconnect?.error?.output?.statusCode;function nativeAccount(socket){const identity=jidDecode(socket?.user?.id);return identity?.server==="s.whatsapp.net"&&/^[1-9][0-9]{4,19}$/u.test(identity.user)?identity.user:void 0}export function createWhatsappProvider({vault,socket,pairingPage=openPairingPage,openUrl=openConnectionUrl,payloadRetention="cache",pairingTimeoutMs=18e4,resumeTimeoutMs=2e4,historyTimeoutMs=3e4}){if(!["cache","transient"].includes(payloadRetention)||[pairingTimeoutMs,resumeTimeoutMs,historyTimeoutMs].some(ms=>!Number.isInteger(ms)||ms<1||ms>6e5))throw Error("Invalid WhatsApp retention or timeout configuration.");const transient=payloadRetention==="transient",makeSocket=socket??(auth=>defaultSocket(auth,!transient));const info={content:[acquiredReadCapability(["plugins/connector-whatsapp/README.md"]),unreviewedActionContent(["plugins/connector-whatsapp/README.md"])],source:SOURCE,label:"WhatsApp",group:"Connector / Chat",auth:"native-browser"};const jobs=new Map,names=new Map,buffer=new TransientMessageBuffer,pairings=new Set;const initializing=new Set;let live,resuming,closed=false,closing;let writes=Promise.resolve(),persistTimer;const fail=(code,message)=>businessError(code,message,"plugin");const enqueue=task=>{writes=writes.then(task,task).catch(()=>void 0);return writes};const track=task=>{initializing.add(task);void task.then(()=>initializing.delete(task),()=>initializing.delete(task));return task};const notify=entry=>{for(const wake of entry.waiters)wake()};const owned=(entry,sock=entry.socket)=>!closed&&!entry.stopped&&live===entry&&entry.socket===sock;function remember(jid,name){if(!jid||jid.length>512||!name)return;names.delete(jid);names.set(jid,name.slice(0,256));if(names.size>2e3)names.delete(names.keys().next().value)}function stopLive(entry){entry.stopped=true;entry.online=false;entry.resolveOpen(false);notify(entry);entry.socket?.end();if(live===entry){live=void 0;buffer.clear();names.clear()}}function waitUntil(entry,predicate,timeout,signal){if(predicate())return Promise.resolve(true);if(signal?.aborted||closed||entry.stopped)return Promise.resolve(false);return new Promise(resolve=>{const finish=value=>{clearTimeout(timer);entry.waiters.delete(wake);signal?.removeEventListener("abort",abort);resolve(value)};const wake=()=>{if(predicate())finish(true);else if(closed||entry.stopped)finish(false)};const abort=()=>finish(false),timer=setTimeout(()=>finish(false),timeout);entry.waiters.add(wake);signal?.addEventListener("abort",abort,{once:true});wake()})}async function captureAuthority(accountId){const custody=vault.bindingCustody;if(!custody)return transient?fail("failed_precondition","Transient WhatsApp requires durable native account custody."):ok(void 0);const selected=await custody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved")return fail("failed_precondition","WhatsApp needs one explicit native account binding.");const current=await custody.credentialSnapshot(oauthCredentialResourceId(selected.ok.binding.id),{purpose:"L1",audience:SOURCE});if(!("ok"in current))return current;const value=current.ok;if(value.binding.identity.source!==SOURCE||value.binding.identity.issuer!==SOURCE||value.binding.identity.subject!==accountId||value.binding.identity.tenant!==null||value.material.kind!=="oauth"||value.resource.kind!=="oauth"||value.resource.owner.kind!=="resident"||value.material.credential.clientId!=="whatsapp-linked-device"||!value.grant.scopes.includes("messages.read"))return fail("permission_denied","WhatsApp session custody does not match the selected native account.");return ok({binding:value.binding,grant:value.grant,resource:value.resource})}async function checkAuthority(entry){if(!entry.accountId||nativeAccount(entry.socket)!==entry.accountId)return fail("failed_precondition","WhatsApp signed-in account changed. Reconnect the selected account.");const current=await captureAuthority(entry.accountId);if(!("ok"in current))return current;const expected=entry.authority,latest=current.ok;if(expected&&(!latest||latest.binding.id!==expected.binding.id||latest.binding.revision!==expected.binding.revision||latest.grant.id!==expected.grant.id||latest.grant.revision!==expected.grant.revision||latest.grant.scopeEpoch!==expected.grant.scopeEpoch||latest.resource.id!==expected.resource.id))return fail("permission_denied","WhatsApp account permission changed while the operation was pending.");return ok(latest)}async function persistNow(entry){if(!entry.accountId||!entry.online||entry.stopped)return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}if(entry.stopped||!entry.online)return;const credential={accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]};const saved=allowed.ok&&vault.bindingCustody?await vault.bindingCustody.compareAndSwapResource({...allowed.ok.resource,updatedAt:new Date().toISOString()},{kind:"oauth",credential},allowed.ok.resource.revision):await vault.updateCredential(SOURCE,credential);if(!("ok"in saved))stopLive(entry)}function persist(entry){if(!owned(entry)||!entry.accountId)return;clearTimeout(persistTimer);persistTimer=setTimeout(()=>{void enqueue(()=>persistNow(entry))},1e3);persistTimer.unref?.()}function store(entry,sock,messages,history=false){if(!owned(entry,sock)||!entry.accountId||nativeAccount(sock)!==entry.accountId||transient&&!entry.online)return;if(transient){for(const message of messages)for(const record of toRecords(entry.accountId,[message],jid=>names.get(jid)))buffer.add(record);if(history||messages.length>0)entry.historyArrived=true;notify(entry);return}const records=toRecords(entry.accountId,messages,jid=>names.get(jid));for(let i=0;i<records.length;i+=100){const batch=records.slice(i,i+100);void enqueue(async()=>{if(!await entry.open||!owned(entry,sock))return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}await cache(vault,SOURCE,batch);entry.historyArrived=true;notify(entry)})}}async function markLoggedOut(entry){if(!entry.accountId)return;if(vault.bindingCustody&&entry.authority){const current=await vault.bindingCustody.binding(entry.authority.binding.id);if("ok"in current&&current.ok?.revision===entry.authority.binding.revision)await vault.bindingCustody.compareAndSwapBinding({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},current.ok.revision)}else{const current=await vault.connection(SOURCE);if("ok"in current&&current.ok?.accountId===entry.accountId)await vault.saveConnection({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},{accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]})}}async function start(stateStore,accountId,authority,onView,onOpen,onFailure){if(closed)throw Error("inactive");let resolveOpen;const open=new Promise(resolve=>{resolveOpen=resolve});const current={store:stateStore,open,resolveOpen,...accountId?{accountId}:{},...authority?{authority}:{},online:false,stopped:false,historyArrived:false,needsPairing:false,waiters:new Set};live=current;buffer.clear();names.clear();let restarts=0,generation=0;const failed=code=>{current.failure=code;stopLive(current);onFailure?.(code)};const connect=async()=>{if(!owned(current))return;const attempt=++generation,previous=current.socket;delete current.socket;previous?.end();const sock=await track(makeSocket(current.store.state));if(!owned(current)||attempt!==generation){sock.end();return}current.socket=sock;sock.ev.on("creds.update",()=>{if(owned(current,sock))persist(current)});sock.ev.on("connection.update",update=>{if(!owned(current,sock))return;if(update.qr){current.needsPairing=true;onView?.({state:"qr",qr:update.qr});notify(current)}if(update.connection==="open"){const linked=nativeAccount(sock);if(!linked||current.accountId&&current.accountId!==linked){failed("account_changed");return}current.accountId=linked;void(async()=>{const completed=await onOpen?.(current);if(!owned(current,sock))return;const captured=current.authority?await checkAuthority(current):await captureAuthority(linked);if(!("ok"in captured)){failed("account_permission_changed");return}if(!owned(current,sock))return;if(!current.authority)current.authority=captured.ok;current.online=true;current.needsPairing=false;restarts=0;resolveOpen(true);notify(current);completed?.()})().catch(()=>failed("pairing_unavailable"))}if(update.connection==="close"){current.online=false;notify(current);const code=statusCode(update);if(code===DisconnectReason.loggedOut){current.needsPairing=true;void enqueue(()=>markLoggedOut(current));failed("qr_scan_required");return}if(code!==DisconnectReason.connectionReplaced&&restarts++<5){void connect().catch(()=>failed("connection_unavailable"));return}failed("connection_unavailable")}});sock.ev.on("messaging-history.set",({chats,contacts,messages})=>{if(!owned(current,sock))return;for(const chat of chats)remember(chat.id,chat.name);for(const contact of contacts)remember(contact.id,contact.name??contact.notify);store(current,sock,messages,true)});sock.ev.on("chats.upsert",chats=>{if(owned(current,sock))for(const chat of chats)remember(chat.id,chat.name)});sock.ev.on("contacts.upsert",contacts=>{if(owned(current,sock))for(const contact of contacts)remember(contact.id,contact.name??contact.notify)});sock.ev.on("messages.upsert",({messages})=>{if(!owned(current,sock))return;for(const message of messages)if(!message.key.fromMe)remember(message.key.remoteJid,message.key.remoteJid?.endsWith("@g.us")?void 0:message.pushName);store(current,sock,messages)})};try{await connect()}catch(error){failed("connection_unavailable");throw error}return current}async function resume(){if(live&&!live.stopped)return live;if(resuming)return resuming;resuming=(async()=>{const connection=await vault.connection(SOURCE);if(!("ok"in connection))throw Error("account_permission_changed");if(connection.ok?.state!=="connected"||!connection.ok.accountId)return void 0;const grant=await vault.credential(SOURCE);if(!("ok"in grant))throw Error("account_permission_changed");const authority=await captureAuthority(connection.ok.accountId);if(!("ok"in authority))throw Error("account_permission_changed");const restored=sessionStore(grant.ok.accessToken,()=>{if(live)persist(live)});return start(restored,connection.ok.accountId,authority.ok)})();try{return await resuming}finally{resuming=void 0}}function cleanPairing(pair2){clearTimeout(pair2.timer);pair2.removeAbort?.();pair2.page?.close();pairings.delete(pair2)}function failPairing(pair2,code,message){if(pair2.job.state==="waiting-user"){pair2.job.state="failed";pair2.job.error={code,message};delete pair2.job.authorizationUrl;delete pair2.job.instructions;pair2.stop.abort();pair2.page?.update({state:"failed",message});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live)}cleanPairing(pair2)}function cancelPairing(pair2){if(pair2.job.state==="waiting-user")pair2.job.state="cancelled";delete pair2.job.authorizationUrl;delete pair2.job.instructions;delete pair2.job.error;pair2.stop.abort();pair2.page?.update({state:"failed",message:"WhatsApp connection was cancelled."});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live);cleanPairing(pair2)}async function pair(job,options,expectedAccountId){if(closed)throw Error("inactive");const owner={job,stop:new AbortController};pairings.add(owner);const abort=()=>failPairing(owner,"aborted","WhatsApp connection was cancelled.");options.signal?.addEventListener("abort",abort,{once:true});owner.removeAbort=()=>options.signal?.removeEventListener("abort",abort);try{owner.page=await pairingPage();if(closed||options.signal?.aborted||owner.stop.signal.aborted){abort();return}job.authorizationUrl=owner.page.url;job.instructions="Open the QR code page, then use WhatsApp on your phone: Settings \u2192 Linked devices \u2192 Link a device. The connection continues automatically after scanning.";job.error={code:"qr_scan_required",message:"Scan the WhatsApp QR code with your phone."};owner.timer=setTimeout(()=>failPairing(owner,"pairing_timeout","WhatsApp QR was not scanned before it expired."),pairingTimeoutMs);owner.timer.unref?.();const fresh=sessionStore(void 0,()=>{if(owner.entry)persist(owner.entry)});if(live)stopLive(live);owner.entry=await start(fresh,expectedAccountId,void 0,view=>{if(job.state==="waiting-user")owner.page?.update(view)},async current=>{if(job.state==="connected"&&!closed)return;if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)throw Error("aborted");const saved=await vault.saveConnection({source:SOURCE,provider:SOURCE,account:current.socket?.user?.name?.slice(0,256)||"WhatsApp",accountId:current.accountId,scopes:["messages.read"],state:"connected",updatedAt:new Date().toISOString()},{accessToken:current.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]},{signal:owner.stop.signal});if(!("ok"in saved))throw Error("custody_failed");return()=>{if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)return;clearTimeout(owner.timer);owner.removeAbort?.();job.state="connected";job.account=saved.ok.account;delete job.instructions;delete job.authorizationUrl;delete job.error;owner.page?.update({state:"connected"});owner.timer=setTimeout(()=>cleanPairing(owner),1e4);owner.timer.unref?.()}},code=>failPairing(owner,code,code==="account_changed"?"The scanned WhatsApp account does not match the selected account.":"WhatsApp pairing did not complete."));if(owner.stop.signal.aborted)stopLive(owner.entry);if(!options.automatic&&options.manualPresentation!=="return-url"&&job.state==="waiting-user")await openUrl(owner.page.url)}catch{failPairing(owner,"pairing_unavailable","WhatsApp pairing page or connection could not start.")}}return{info,...transient?{}:{requiresPersistentPayloads:true},status:()=>connectionState(vault,info),job(id){const job=jobs.get(id);return job?ok({...job}):fail("not_found","WhatsApp connection job not found.")},cancelJob(id){const job=jobs.get(id);if(!job)return ok({id,cleanup:"confirmed"});const pairing=[...pairings].find(owner=>owner.job===job);if(pairing)cancelPairing(pairing);else if(job.state==="waiting-user")job.state="cancelled";delete job.authorizationUrl;delete job.instructions;return ok({id,cleanup:[...pairings].some(owner=>owner.job===job)?"pending":"confirmed"})},async connect(options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");const running=[...jobs.values()].find(job2=>job2.state==="waiting-user");if(running)return ok({...running});for(const[id,job2]of jobs)if(jobs.size>=32&&job2.state!=="waiting-user")jobs.delete(id);const job={id:randomUUID(),source:SOURCE,state:"waiting-user",startedAt:new Date().toISOString()};jobs.set(job.id,job);try{const selected=await vault.connection(SOURCE);if(!("ok"in selected))return selected;if(selected.ok&&!selected.ok.accountId)return fail("failed_precondition","WhatsApp needs a verified native account binding.");if(options.expectedBinding?.kind==="legacy-source"&&options.expectedBinding.source!==SOURCE)return fail("invalid_argument","WhatsApp account selection names another source.");if(options.expectedBinding?.kind==="binding"){const binding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in binding)||binding.ok.kind!=="resolved"||binding.ok.binding.id!==options.expectedBinding.bindingId)return fail("failed_precondition","WhatsApp account selection does not match this linked device.")}if(closed)return fail("unavailable","WhatsApp source is inactive.");const resumed=await track(resume());if(resumed){await waitUntil(resumed,()=>resumed.online||resumed.needsPairing,resumeTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");if(resumed.online){const allowed=await checkAuthority(resumed);if(!("ok"in allowed))return allowed;job.state="connected";if(selected.ok)job.account=selected.ok.account;return ok({...job})}if(!resumed.needsPairing){job.state="failed";job.error={code:resumed.failure??"connection_unavailable",message:resumed.failure==="account_changed"?"WhatsApp signed in as a different account.":"The existing WhatsApp session did not reconnect."};return ok({...job})}}if(options.automatic&&!transient){job.state="failed";job.error={code:"qr_scan_required",message:"WhatsApp needs one QR scan from the phone; connect it explicitly."};return ok({...job})}if(options.automatic&&selected.ok?.accountId&&vault.bindingCustody){const selectedBinding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if("ok"in selectedBinding&&selectedBinding.ok.kind==="resolved"){const grant=await vault.bindingCustody.grantForBinding(selectedBinding.ok.binding.id,"L1",SOURCE);if(!("ok"in grant))return grant;if(grant.ok?.state==="revoked")return fail("permission_denied","WhatsApp access was revoked. Reconnect explicitly to grant it again.")}}await track(pair(job,options,selected.ok?.accountId))}catch{job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp session permission or connection could not be verified."}}finally{if(job.state==="waiting-user"&&![...pairings].some(owner=>owner.job===job)){job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp did not start an owned connection job."}}}return ok({...job})},async read(request,options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");const invalid=validateRead(request);if(invalid)return invalid;if(request.fileId!==void 0)return fail("invalid_argument","WhatsApp message reads support limit, query and time filters; file download is not supported.");if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const connection=await vault.connection(SOURCE);if(!("ok"in connection))return connection;if(connection.ok?.state!=="connected"||!connection.ok.accountId)return fail("unauthenticated","Connect WhatsApp by scanning its QR code first.");const session=await track(resume()).catch(()=>void 0);const online=session?await waitUntil(session,()=>session.online,resumeTimeoutMs,options.signal):false;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const warnings=[];let records;if(transient){if(!online||!session)return fail("unavailable","WhatsApp is offline; transient reads need the selected live session.");const allowed=await checkAuthority(session);if(!("ok"in allowed)){stopLive(session);return allowed}await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");if(!owned(session)||!session.online)return fail("unavailable","WhatsApp session ended before the message read.");const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(!session.historyArrived)return fail("unavailable","No live WhatsApp message batch has arrived for this session yet. Retry after the phone finishes linking or a message arrives.");records=buffer.snapshot();warnings.push(`This live session retains at most ${TRANSIENT_MESSAGE_LIMIT} messages and 4 MiB in memory. Messages are not saved and are cleared on restart.`)}else{if(!online)warnings.push("WhatsApp is offline right now; showing messages already saved in the Vault.");if(online&&session&&!session.historyArrived){const stored2=await vault.records(SOURCE,1);if(!("ok"in stored2)||!stored2.ok.length)await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal)}await writes;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const stored=await vault.records(SOURCE,100);if(!("ok"in stored))return stored;records=stored.ok.map(row=>row.data);if(request.query||request.since||request.until)warnings.push("Filters apply to the 100 most recent saved messages; use SQL search over z_records for older history.")}const since=request.since?Date.parse(request.since):-Infinity,until=request.until?Date.parse(request.until):Infinity,query=request.query?.toLowerCase();records=records.filter(record=>record.sourceId?.startsWith(connection.ok.accountId+":")).filter(record=>{const at=Date.parse(record.ts??"");return at>=since&&at<=until}).filter(record=>!query||`${record.body} ${record.fields?.chat??""}`.toLowerCase().includes(query)).slice(0,request.limit??1);if(transient&&session){const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(closed||!owned(session)||options.signal?.aborted)return fail("aborted","WhatsApp read was cancelled before delivery.")}return readResult(SOURCE,records,warnings)},close(){if(closing)return closing;closing=(async()=>{closed=true;clearTimeout(persistTimer);for(const owner of[...pairings]){if(owner.job.state==="waiting-user")failPairing(owner,"aborted","WhatsApp source was closed.");else cleanPairing(owner)}await Promise.allSettled([...initializing]);await writes;if(live){const current=live;await persistNow(current).catch(()=>void 0);stopLive(current)}buffer.clear();names.clear()})();return closing}}}
@@ -0,0 +1 @@
1
+ import{pinnedMethods}from"./discovery-data.js";import{creatorMethods}from"./creator-data.js";export const youtubeContent=[...["channels","subscriptions","playlists","playlistItems","videos","commentThreads"].map(resource=>({resource:`account/${resource}`,read:"implemented",acquisition:"collection",persistence:"durable",readFields:["selected-parts"],storedFields:["selected-parts"],updates:"rescan",evidence:["https://developers.google.com/youtube/v3/docs","src/full-sync.ts"],limitations:["Authorized account walk only; parts, quota and partialReasons bound coverage; inline comment replies are not complete reply history."]})),...[...pinnedMethods,...creatorMethods].filter(m=>m.httpMethod==="GET").map(m=>({resource:m.id,read:m.scopes?.length&&!m.id.endsWith(".stream")?"implemented":"unimplemented",acquisition:"lookup",persistence:"unimplemented",readFields:m.supportsMediaDownload?["content","mime"]:["data","items","nextPageToken"],storedFields:[],updates:"lookup",evidence:["src/discovery-data.ts","src/creator-data.ts","src/source.ts"],limitations:["Selected parameters, scopes and provider admission apply. No automatic durable path for this selected-method response."]})),...["personal-search-history","watch-history","watch-later","complete-authored-comment-history"].map(resource=>({resource,read:"unsupported",acquisition:"none",persistence:"not-applicable",readFields:[],storedFields:[],updates:"none",evidence:["src/full-sync.ts"],limitations:["Unavailable through the reviewed Data API path; explicit user exports are a separate acquisition path."]}))];
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{Original}from"@zortexhq/plugin-connector-framework/api";import{manifest as sourceManifest}from"./discovery-data.js";import{object}from"./schema.js";const READONLY="https://www.googleapis.com/auth/youtube.readonly";export const YOUTUBE_READ_SCOPES=Object.freeze([READONLY,"https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"]);const API="https://www.googleapis.com/youtube/v3/";const HOUR=36e5,DAY=24*HOUR;const UNKNOWN_TS="1970-01-01T00:00:00.000Z";const MAX_WALK_PAGES=2e5,HEAD_IDS=3,COMMENT_SLACK_MS=DAY,QUOTA_SLACK_MS=6e4;export const YOUTUBE_INCREMENTAL_EVERY_MS=6*HOUR,YOUTUBE_FULL_EVERY_MS=7*DAY;const READ_STREAMS=["channels","subscriptions","playlists","playlistItems","videos","commentThreads"];const LISTED_ONLY=["comments","search","captions","members"];const STATIC_REASONS={channels:["brand-channels-need-own-grant"],playlistItems:["watch-history-not-in-api","watch-later-not-in-api"],comments:["authored-comments-not-in-api"],search:["search-history-not-in-api"],captions:["captions-need-force-ssl-scope"],members:["memberships-need-creator-scope"]};export const youtubeSyncManifest=(()=>{const wanted=new Set([...READ_STREAMS,...LISTED_ONLY]),copy=structuredClone(sourceManifest);delete copy.actionScopes;return{...copy,streams:copy.streams.filter(stream=>wanted.has(stream.stream)),actions:[]}})();const PHASES=["channels","subscriptions","playlists","playlistItems","uploads","likes","dislikes","comments","done"];const text=value=>typeof value==="string"?value.trim():"";const json=value=>JSON.parse(JSON.stringify(value));const instant=(...values)=>{for(const value of values)if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return UNKNOWN_TS};const reasonCode=(reason,fallback)=>(reason??"").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)||fallback;const shortHash=value=>createHash("sha256").update(value).digest("hex").slice(0,10);export function nextPacificMidnight(nowMs){const at=Math.floor(nowMs/1e3)*1e3;try{const parts=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}).formatToParts(new Date(at)).map(part=>[part.type,part.value]));const[y,m,d]=[Number(parts.year),Number(parts.month),Number(parts.day)];const offset=Date.UTC(y,m-1,d,Number(parts.hour),Number(parts.minute),Number(parts.second))-at;const next=Date.UTC(y,m-1,d+1)-offset;if(Number.isFinite(next)&&next>at)return next}catch{}return Math.floor((at-8*HOUR)/DAY+1)*DAY+8*HOUR}function stringRecord(value){return object(value)&&Object.values(value).every(item=>typeof item==="string")}function parseMarks(value){if(!object(value))return null;const marks={};if(value.since!==void 0){if(typeof value.since!=="string"||!Number.isFinite(Date.parse(value.since)))return null;marks.since=value.since}if(value.heads!==void 0){if(!object(value.heads)||!Object.values(value.heads).every(ids=>Array.isArray(ids)&&ids.every(id=>typeof id==="string")))return null;marks.heads=value.heads}if(value.tags!==void 0){if(!stringRecord(value.tags))return null;marks.tags=value.tags}return marks}function parseWalk(wire){if(!object(wire))return null;const w=wire;const strings=value=>Array.isArray(value)&&value.every(item=>typeof item==="string");const optionalInstant=value=>value===void 0||typeof value==="string"&&Number.isFinite(Date.parse(value));if(typeof w.account!=="string"||!w.account||w.mode!=="full"&&w.mode!=="incremental"||typeof w.startedAt!=="string"||!Number.isFinite(Date.parse(w.startedAt)))return null;if(!PHASES.includes(w.phase)||w.token!==null&&typeof w.token!=="string"||!Number.isSafeInteger(w.pages)||Number(w.pages)<0)return null;if(!strings(w.channels)||!strings(w.uploads)||w.channels.length!==w.uploads.length||!Number.isSafeInteger(w.at)||Number(w.at)<0)return null;if(!Array.isArray(w.queue)||!w.queue.every(entry=>Array.isArray(entry)&&entry.length===2&&entry.every(part=>typeof part==="string"))||w.more!==null&&typeof w.more!=="string")return null;const prior=parseMarks(w.prior),next=parseMarks(w.next);if(!prior||!next||!object(w.gaps)||!Object.values(w.gaps).every(n=>Number.isSafeInteger(n)&&Number(n)>=0))return null;if(!optionalInstant(w.completedAt)||!optionalInstant(w.fullAt)||!optionalInstant(w.quotaUntil)||w.phase==="done"&&w.completedAt===void 0)return null;return{account:w.account,mode:w.mode,startedAt:w.startedAt,phase:w.phase,token:w.token,pages:Number(w.pages),channels:[...w.channels],uploads:[...w.uploads],at:Number(w.at),queue:w.queue.map(([id,tag])=>[id,tag]),more:w.more,prior,next,gaps:{...w.gaps},...w.completedAt===void 0?{}:{completedAt:w.completedAt},...w.fullAt===void 0?{}:{fullAt:w.fullAt},...w.quotaUntil===void 0?{}:{quotaUntil:w.quotaUntil}}}function stable(value,stream,depth=0){if(Array.isArray(value))return value.map(item=>stable(item,stream,depth+1));if(!object(value))return value;const out={};for(const[key,item]of Object.entries(value)){if(key==="etag"||depth===0&&key==="statistics")continue;if(stream==="commentThreads"&&(key==="likeCount"||key==="viewerRating"||key==="canRate"))continue;out[key]=stable(item,stream,depth+1)}return out}function snippet(item){return object(item.snippet)?item.snippet:{}}function commentLine(comment){const s=object(comment)&&object(comment.snippet)?comment.snippet:{};const said=text(s.textOriginal)||text(s.textDisplay);return said?[text(s.authorDisplayName),said].filter(Boolean).join(": "):""}function describe(stream,raw){const item=raw.item,s=snippet(item),title=text(s.title);const lines=(...parts)=>parts.filter(Boolean).join("\n");switch(stream){case"channels":return{title,ts:instant(s.publishedAt),body:lines("YouTube channel: "+title,text(s.customUrl),text(s.description))};case"subscriptions":return{title,ts:instant(s.publishedAt),body:lines("Subscribed to: "+title,text(s.description))};case"playlists":return{title,ts:instant(s.publishedAt),body:lines("Playlist: "+title,text(s.description))};case"playlistItems":{const details=object(item.contentDetails)?item.contentDetails:{};const owner=text(s.videoOwnerChannelTitle);return{title,ts:instant(s.publishedAt,details.videoPublishedAt),body:lines((raw.via==="uploads"?"Uploaded: ":"In playlist: ")+title,owner?"by "+owner:"",text(s.description))}}case"videos":{const tags=Array.isArray(s.tags)?s.tags.filter(tag=>typeof tag==="string"):[];const channel=text(s.channelTitle);return{title,ts:instant(s.publishedAt),body:lines((raw.via==="dislike"?"Disliked video: ":"Liked video: ")+title,channel?"by "+channel:"",text(s.description),tags.join(", "))}}case"commentThreads":{const top=s.topLevelComment,first=commentLine(top),replies=object(item.replies)&&Array.isArray(item.replies.comments)?item.replies.comments.map(commentLine).filter(Boolean):[];const topSnippet=object(top)&&object(top.snippet)?top.snippet:{};return{title:first.slice(0,120),ts:instant(topSnippet.updatedAt,topSnippet.publishedAt),body:lines(first,...replies)}}default:throw Error("YouTube full sync does not normalize stream "+stream+".")}}export function createYouTubeProvider({parts,auth,vault,now=()=>new Date().toISOString(),incrementalEveryMs=YOUTUBE_INCREMENTAL_EVERY_MS,fullEveryMs=YOUTUBE_FULL_EVERY_MS}){if(!Number.isFinite(incrementalEveryMs)||incrementalEveryMs<0||!Number.isFinite(fullEveryMs)||fullEveryMs<0)throw Error("YouTube sync pacing must be non-negative milliseconds.");const info={source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser"};const stop=new AbortController,pending=new Set;let closed=false;let latest=null;const codec=parts.cursorCodecV1({source:"youtube",version:2,versionKey:"v",validate:parseWalk});const fail=(code,message,retryability="non-retryable",cause)=>parts.connectorError(code,message,retryability,cause);const inactive=()=>fail("aborted","YouTube source is inactive.");const owned=task=>{const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled};const declared=new Map(youtubeSyncManifest.streams.map(stream=>[stream.stream,stream]));async function resolveGrant(){if(closed)return inactive();const connection=await vault.connection("youtube");if(!("ok"in connection))return"err"in connection?connection:fail("data_loss","YouTube connection metadata was unconfirmed.");const row=connection.ok;if(!row||row.state!=="connected")return fail("unauthenticated","Connect YouTube before syncing it.");if(typeof row.accountId!=="string"||!row.accountId.trim())return fail("failed_precondition","YouTube sync needs the verified Google subject; an email or grant id is never the account identity.");const scope=YOUTUBE_READ_SCOPES.find(candidate=>row.scopes.includes(candidate));if(!scope)return fail("permission_denied","The YouTube connection has no read scope; reconnect YouTube.");if(closed)return inactive();return Original.ok({id:"0"+createHash("sha256").update(row.accountId).digest("hex").slice(0,25).toUpperCase(),source:"youtube",account:row.accountId,scopes:[scope],expiresAt:new Date(Date.parse(now())+HOUR).toISOString()})}function checkGrant(grant){if(grant.source!=="youtube"||!grant.account?.trim())return fail("permission_denied","YouTube grant is not bound to a verified account.");if(!grant.scopes.some(scope=>YOUTUBE_READ_SCOPES.includes(scope)))return fail("permission_denied","YouTube grant has no read scope.");return void 0}async function fence(grant){if(closed||stop.signal.aborted)return inactive();const current=await vault.connection("youtube");if(!("ok"in current))return"err"in current?current:fail("data_loss","YouTube account fence was unconfirmed.");if(closed||stop.signal.aborted)return inactive();const row=current.ok;if(!row||row.state!=="connected")return fail("unauthenticated","YouTube was disconnected during the sync.");if(row.accountId!==grant.account)return fail("permission_denied","The YouTube account changed during the sync; nothing from the old grant is attributed to the new account.");if(!grant.scopes.every(scope=>row.scopes.includes(scope)))return fail("permission_denied","YouTube read consent was withdrawn.");return Original.ok(void 0)}async function call(grant,listing2,token){const url=new URL(listing2.resource,API);for(const[key,value]of Object.entries(listing2.params))url.searchParams.set(key,value);if(token)url.searchParams.set("pageToken",token);const before=await fence(grant);if(!Original.isOk(before))return before;const reply=await auth.requestRaw("youtube",url.href,{signal:stop.signal});if(closed||stop.signal.aborted)return inactive();if(!("ok"in reply)){const err="err"in reply?reply.err:void 0;if(!err||err.code==="unavailable"||err.code==="aborted")return fail("unavailable","A YouTube list request did not complete (network or request timeout); the page is retried from the same cursor.","transient",err);return reply}const after=await fence(grant);if(!Original.isOk(after))return after;return reply}function soleChannel(walk){return walk.channels.length===1?walk.channels[0]:null}function listing(walk){const page2=(resource,params)=>({resource,params:{...params,maxResults:"50"}});switch(walk.phase){case"channels":return{...page2("channels",{part:"snippet,contentDetails,brandingSettings,status,topicDetails,localizations",mine:"true"}),stream:"channels",via:"mine",owner:null};case"subscriptions":return{...page2("subscriptions",{part:"snippet",mine:"true"}),stream:"subscriptions",via:"subscription",owner:soleChannel(walk)};case"playlists":return{...page2("playlists",{part:"snippet,contentDetails,status,localizations",mine:"true"}),stream:"playlists",via:"playlist",owner:soleChannel(walk)};case"playlistItems":{const id=walk.queue[0][0];return{...page2("playlistItems",{part:"snippet,contentDetails,status",playlistId:id}),stream:"playlistItems",via:"playlist",owner:soleChannel(walk),playlistId:id}}case"uploads":{const id=walk.uploads[walk.at];return{...page2("playlistItems",{part:"snippet,contentDetails,status",playlistId:id}),stream:"playlistItems",via:"uploads",owner:walk.channels[walk.at],playlistId:id,head:"uploads:"+id}}case"likes":case"dislikes":{const rating=walk.phase==="likes"?"like":"dislike";return{...page2("videos",{part:"snippet,contentDetails,status,topicDetails",myRating:rating}),stream:"videos",via:rating,owner:soleChannel(walk),head:rating}}case"comments":return{resource:"commentThreads",params:{part:"snippet,replies",allThreadsRelatedToChannelId:walk.channels[walk.at],maxResults:"100",order:"time",textFormat:"plainText"},stream:"commentThreads",via:"channel-comments",owner:walk.channels[walk.at],byTime:true};case"done":throw Error("A completed YouTube walk has no listing.")}}function settle(walk){for(;;){if(walk.phase==="playlistItems"&&!walk.queue.length){if(walk.more!==null){walk.phase="playlists";walk.token=walk.more;walk.more=null}else{walk.phase="uploads";walk.at=0;walk.token=null}continue}if(walk.phase==="uploads"){while(walk.at<walk.channels.length&&!walk.uploads[walk.at])walk.at++;if(walk.at>=walk.channels.length){walk.phase="likes";walk.at=0;walk.token=null;continue}}if(walk.phase==="comments"&&walk.at>=walk.channels.length){walk.phase="done";walk.token=null;continue}return}}function finish(walk,read){switch(walk.phase){case"channels":walk.phase="subscriptions";break;case"subscriptions":walk.phase="playlists";walk.more=null;break;case"playlists":walk.phase="playlistItems";walk.queue=[];walk.more=null;break;case"playlistItems":{const[id,tag]=walk.queue.shift();if(read)walk.next.tags={...walk.next.tags,[id]:tag};break}case"uploads":walk.at++;break;case"likes":walk.phase="dislikes";break;case"dislikes":walk.phase="comments";walk.at=0;break;case"comments":walk.at++;break;case"done":break}walk.token=null}function gap(walk,stream,reason,count=1){const key=stream+":"+reason;walk.gaps[key]=(walk.gaps[key]??0)+count}function begin(account,mode,prior,fullAt,at){return{account,mode,startedAt:at,phase:"channels",token:null,pages:0,channels:[],uploads:[],at:0,queue:[],more:null,prior:mode==="full"?{}:prior,next:{},gaps:{},...fullAt===void 0?{}:{fullAt}}}function complete(walk,at){return{...walk,phase:"done",token:null,at:0,queue:[],more:null,prior:{...walk.next,since:walk.startedAt},next:{},completedAt:at,...walk.mode==="full"?{fullAt:at}:{}}}function encode(walk,notes){let attempt=codec.encode(walk);if("ok"in attempt)return attempt;if(walk.prior.tags||walk.next.tags){const{tags:_p,...prior}=walk.prior,{tags:_n,...next}=walk.next;walk.prior=prior;walk.next=next;notes.push("youtube: playlist-marks-dropped \u2014 remembered playlist versions were dropped to keep the cursor within "+Original.SYNC_CURSOR_MAX_CHARS+" chars; those playlists are read in full");attempt=codec.encode(walk);if("ok"in attempt)return attempt}if(walk.prior.heads||walk.next.heads){const{heads:_p,...prior}=walk.prior,{heads:_n,...next}=walk.next;walk.prior=prior;walk.next=next;notes.push("youtube: head-marks-dropped \u2014 remembered list heads were dropped to keep the cursor bounded; those lists are read in full");attempt=codec.encode(walk)}return attempt}function page(items,walk,exhausted,notes){latest=walk;const next=encode(walk,notes);if(!("ok"in next))return next;return Original.ok({items,next:next.ok,exhausted,...notes.length?{notes}:{}})}function respond(items,walk,at,notes){return walk.phase==="done"?page(items,complete(walk,at),true,notes):page(items,walk,false,notes)}function quotaWait(until){return fail("resource_exhausted","YouTube daily quota is exhausted (youtube-daily-quota-exhausted): the project's YouTube Data API units for today are used up. Quota backoff not due until "+until+", when Google resets the quota at midnight Pacific Time; the walk then resumes from its saved cursor and nothing is skipped.","retry-at-higher-level")}const RATE_LIMIT=new Set(["rateLimitExceeded","userRateLimitExceeded","RATE_LIMIT_EXCEEDED"]),DAILY=new Set(["quotaExceeded","dailyLimitExceeded"]),GRANT=new Set(["insufficientPermissions","authError","unauthorized","PERMISSION_DENIED","UNAUTHENTICATED"]);function classify(walk,reply){const what=walk.phase==="uploads"||walk.phase==="playlistItems"?"playlistItems.list":walk.phase==="likes"||walk.phase==="dislikes"?"videos.list":walk.phase==="comments"?"commentThreads.list":walk.phase+".list";if(reply.status===200){let data;try{data=JSON.parse(reply.body)}catch{return{kind:"err",err:fail("data_loss","YouTube "+what+" returned a body that is not JSON; the page is asked again.","transient").err}}if(!object(data)||data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item)))||data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return{kind:"err",err:fail("data_loss","YouTube "+what+" returned a malformed list; the page is asked again.","transient").err};return{kind:"ok",data}}const reason=parts.googleErrorReasonV1(reply.body);if((reply.status===403||reply.status===429)&&reason!==void 0&&DAILY.has(reason))return{kind:"quota"};const status=()=>parts.webStatusErrorV1(reply.status,{provider:"YouTube",what,headers:reply.headers,...reason?{detail:reason}:{},bodyOverride:code=>code===403&&reason!==void 0&&RATE_LIMIT.has(reason)?{code:"resource_exhausted",retryability:"throttling",meaning:"the provider throttled the call ("+reason+")"}:void 0})??fail("internal","YouTube "+what+" returned HTTP "+reply.status+".").err;if(reply.status===429||reply.status===403&&reason!==void 0&&RATE_LIMIT.has(reason))return{kind:"err",err:status()};if(reason==="youtubeSignupRequired"&&(reply.status===401||reply.status===403))return{kind:"gap",reason:"youtube-signup-required"};if(reply.status===401)return{kind:"err",err:status()};if(reply.status===403){if(walk.phase==="channels"||reason===void 0||GRANT.has(reason))return{kind:"err",err:status()};return{kind:"gap",reason:reasonCode(reason,"forbidden")}}if(reply.status===404)return{kind:"gap",reason:reasonCode(reason,"not-found")};if(reply.status===400&&reason==="invalidPageToken"&&walk.token!==null)return{kind:"restart"};return{kind:"err",err:status()}}async function pullInner(grant,cursor){const invalid=checkGrant(grant);if(invalid)return invalid;if(closed)return inactive();const notes=[],nowMs=Date.parse(now()),nowIso=new Date(nowMs).toISOString();let walk=cursor===null?null:codec.decode(cursor);if(cursor!==null&&walk===null)notes.push("youtube: cursor-unreadable \u2014 the walk starts again from the first list");if(walk&&walk.account!==grant.account){notes.push("youtube: account-changed \u2014 the walk starts again for the connected account");walk=null}if(walk?.quotaUntil!==void 0){if(nowMs<Date.parse(walk.quotaUntil)){latest=walk;return quotaWait(walk.quotaUntil)}const{quotaUntil:_q,...resumed}=walk;walk=resumed;notes.push("youtube: quota-reset \u2014 the walk resumes where the daily quota stopped it")}if(!walk){walk=begin(grant.account,"full",{},void 0,nowIso);notes.push("youtube: full-pass \u2014 every list is read")}else if(walk.phase==="done"){const due=Date.parse(walk.completedAt)+incrementalEveryMs;if(nowMs<due&&cursor!==null){latest=walk;return Original.ok({items:[],next:cursor,exhausted:true,notes:[...notes,"youtube: pass-not-due \u2014 the next pass starts after "+new Date(due).toISOString()+" (quota pacing)"]})}const full=walk.fullAt===void 0||nowMs-Date.parse(walk.fullAt)>=fullEveryMs;walk=begin(grant.account,full?"full":"incremental",walk.prior,walk.fullAt,nowIso);notes.push(full?"youtube: full-pass \u2014 every list is read again (periodic re-walk)":"youtube: incremental-pass \u2014 cheap lists re-listed, unchanged playlists skipped, newest-first lists stop at the remembered head")}settle(walk);if(walk.phase==="done")return page([],complete(walk,nowIso),true,notes);if(walk.pages>=MAX_WALK_PAGES)return fail("resource_exhausted","YouTube walk exceeded "+MAX_WALK_PAGES+" provider pages; the cursor is kept.");const current=listing(walk),reply=await call(grant,current,walk.token);if(!("ok"in reply))return"err"in reply?reply:fail("data_loss","YouTube request result was unconfirmed.");walk.pages++;const outcome=classify(walk,reply.ok),stream=current.stream,items=[];if(outcome.kind==="err")return{err:outcome.err};if(outcome.kind==="quota"){walk.quotaUntil=new Date(nextPacificMidnight(nowMs)+QUOTA_SLACK_MS).toISOString();notes.push("youtube: youtube-daily-quota-exhausted \u2014 no request until "+walk.quotaUntil+"; the walk resumes at this list");return page([],walk,false,notes)}if(outcome.kind==="restart"){walk.token=null;notes.push("youtube: page-token-expired \u2014 this list is read again from its first page");return page([],walk,false,notes)}if(outcome.kind==="gap"){const reason=walk.phase==="channels"&&outcome.reason==="youtube-signup-required"?"no-youtube-channel":outcome.reason;gap(walk,stream,reason);notes.push("youtube: "+stream+" not read \u2014 "+reason+" (HTTP "+reply.ok.status+")");finish(walk,false);settle(walk);return respond(items,walk,nowIso,notes)}const data=outcome.data,rows=Array.isArray(data.items)?data.items:[],nextToken=typeof data.nextPageToken==="string"?data.nextPageToken:null;const ids=[];let missing=0,unavailable=0;for(const item of rows){const id=typeof item.id==="string"&&item.id?item.id:"";if(!id){missing++;continue}ids.push(id);const s=snippet(item);const owner=walk.phase==="channels"?id:current.via==="subscription"||current.via==="playlist"?text(s.channelId)||current.owner:current.owner;const raw={account:walk.account,channelId:owner,via:current.via,...current.playlistId?{playlistId:current.playlistId}:{},item};items.push({streamRef:stream,raw:json(raw)});if(stream==="playlistItems"&&(s.title==="Private video"||s.title==="Deleted video"))unavailable++}if(missing){gap(walk,stream,"item-without-id",missing);notes.push("youtube: "+stream+" item-without-id \u2014 "+missing+" item(s) without a provider id were not stored")}if(unavailable){gap(walk,"playlistItems","video-unavailable",unavailable);notes.push("youtube: video-unavailable \u2014 "+unavailable+" playlist item(s) point to a private or deleted video; only the placeholder is stored")}if(walk.phase==="channels"){for(const item of rows){if(typeof item.id!=="string"||!item.id)continue;const details=object(item.contentDetails)&&object(item.contentDetails.relatedPlaylists)?item.contentDetails.relatedPlaylists:{};walk.channels.push(item.id);walk.uploads.push(text(details.uploads))}if(!nextToken&&!walk.channels.length){gap(walk,"channels","no-youtube-channel");notes.push("youtube: channels not read \u2014 no-youtube-channel (this identity has no channel; a Brand Account channel needs its own grant)")}}if(walk.phase==="playlists"){const queue=[];for(const item of rows){if(typeof item.id!=="string"||!item.id)continue;const details=object(item.contentDetails)?item.contentDetails:{};const tag=shortHash(typeof item.etag==="string"?item.etag:Original.jcsCanonicalize(json(item)));if(details.itemCount===0||walk.mode==="incremental"&&walk.prior.tags?.[item.id]===tag){walk.next.tags={...walk.next.tags,[item.id]:tag};continue}queue.push([item.id,tag])}finish(walk,true);walk.queue=queue;walk.more=nextToken}else{if(current.head&&walk.token===null)walk.next.heads={...walk.next.heads,[current.head]:ids.slice(0,HEAD_IDS)};const known=current.head?walk.prior.heads?.[current.head]:void 0;const reachedHead=walk.mode==="incremental"&&!!known?.length&&ids.some(id=>known.includes(id));const since=walk.prior.since===void 0?NaN:Date.parse(walk.prior.since)-COMMENT_SLACK_MS;const reachedOld=walk.mode==="incremental"&&current.byTime===true&&Number.isFinite(since)&&rows.some(item=>{const top=snippet(item).topLevelComment,published=object(top)&&object(top.snippet)?Date.parse(String(top.snippet.publishedAt)):NaN;return Number.isFinite(published)&&published<since});if(nextToken&&nextToken===walk.token){gap(walk,stream,"repeated-page-token");notes.push("youtube: "+stream+" repeated-page-token \u2014 the provider repeated a page token; the rest of this list is not read");finish(walk,false)}else if(nextToken&&!reachedHead&&!reachedOld)walk.token=nextToken;else finish(walk,true)}settle(walk);return respond(items,walk,nowIso,notes)}const connector={manifest:youtubeSyncManifest,discover:()=>parts.gateRefusal("YouTube synchronous census","The production YouTube provider is async; use discoverAsync"),pull:()=>parts.gateRefusal("YouTube synchronous pull","The production YouTube provider is async; use pullAsync"),discoverAsync:grant=>owned((async()=>{const invalid=checkGrant(grant);if(invalid)return invalid;const fenced=await fence(grant);if(!Original.isOk(fenced))return fenced;const gaps=latest&&latest.account===grant.account?latest.gaps:{};const streams={};for(const stream of[...READ_STREAMS,...LISTED_ONLY]){const reasons=[...(STATIC_REASONS[stream]??[]).map(reason=>({reason})),...Object.entries(gaps).filter(([key])=>key.startsWith(stream+":")).map(([key,count])=>({reason:key.slice(stream.length+1),count}))];streams[stream]={method:"pagination-exhaustion",...reasons.length?{partialReasons:reasons}:{}}}return Original.ok({asOf:new Date(Date.parse(now())).toISOString(),streams})})()),pullAsync:(grant,cursor)=>owned(pullInner(grant,cursor)),normalize(item){const decl=declared.get(item.streamRef);if(!decl||!READ_STREAMS.includes(item.streamRef))throw Error("YouTube full sync does not emit stream "+item.streamRef+".");if(!object(item.raw)||!object(item.raw.item)||typeof item.raw.account!=="string"||typeof item.raw.via!=="string")throw Error("YouTube normalization requires the wrapped provider resource.");const raw=item.raw,id=typeof raw.item.id==="string"?raw.item.id:"";if(!id)throw Error("YouTube resource has no provider id.");const{title,body,ts}=describe(item.streamRef,raw);const payload={title,account:raw.account,channelId:typeof raw.channelId==="string"?raw.channelId:null,via:raw.via,...typeof raw.playlistId==="string"?{playlistId:raw.playlistId}:{},item:stable(raw.item,item.streamRef)};return{nk:{source:"youtube",stream:item.streamRef,sourceId:item.streamRef==="videos"?raw.via+":"+id:id},ts,kind:decl.kinds[0],tier:"api",schemaVersion:1,mentions:[],body,payload:json(payload)}}};return{info,connector,resolveGrant:()=>owned(resolveGrant()),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}}}
1
+ import{createHash}from"node:crypto";import{Original}from"@zortexhq/plugin-connector-framework/api";import{manifest as sourceManifest}from"./discovery-data.js";import{object}from"./schema.js";const READONLY="https://www.googleapis.com/auth/youtube.readonly";export const YOUTUBE_READ_SCOPES=Object.freeze([READONLY,"https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"]);const API="https://www.googleapis.com/youtube/v3/";const HOUR=36e5,DAY=24*HOUR;const UNKNOWN_TS="1970-01-01T00:00:00.000Z";const MAX_WALK_PAGES=2e5,HEAD_IDS=3,COMMENT_SLACK_MS=DAY,QUOTA_SLACK_MS=6e4;export const YOUTUBE_INCREMENTAL_EVERY_MS=6*HOUR,YOUTUBE_FULL_EVERY_MS=7*DAY;const READ_STREAMS=["channels","subscriptions","playlists","playlistItems","videos","commentThreads"];const LISTED_ONLY=["comments","search","captions","members"];const STATIC_REASONS={channels:["brand-channels-need-own-grant"],playlistItems:["watch-history-not-in-api","watch-later-not-in-api"],comments:["authored-comments-not-in-api"],search:["search-history-not-in-api"],captions:["captions-sync-not-implemented"],members:["members-sync-not-implemented"]};export const youtubeSyncManifest=(()=>{const wanted=new Set([...READ_STREAMS,...LISTED_ONLY]),copy=structuredClone(sourceManifest);delete copy.actionScopes;return{...copy,streams:copy.streams.filter(stream=>wanted.has(stream.stream)),actions:[]}})();const PHASES=["channels","subscriptions","playlists","playlistItems","uploads","likes","dislikes","comments","done"];const text=value=>typeof value==="string"?value.trim():"";const json=value=>JSON.parse(JSON.stringify(value));const instant=(...values)=>{for(const value of values)if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return UNKNOWN_TS};const reasonCode=(reason,fallback)=>(reason??"").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)||fallback;const shortHash=value=>createHash("sha256").update(value).digest("hex").slice(0,10);export function nextPacificMidnight(nowMs){const at=Math.floor(nowMs/1e3)*1e3;try{const parts=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}).formatToParts(new Date(at)).map(part=>[part.type,part.value]));const[y,m,d]=[Number(parts.year),Number(parts.month),Number(parts.day)];const offset=Date.UTC(y,m-1,d,Number(parts.hour),Number(parts.minute),Number(parts.second))-at;const next=Date.UTC(y,m-1,d+1)-offset;if(Number.isFinite(next)&&next>at)return next}catch{}return Math.floor((at-8*HOUR)/DAY+1)*DAY+8*HOUR}function stringRecord(value){return object(value)&&Object.values(value).every(item=>typeof item==="string")}function parseMarks(value){if(!object(value))return null;const marks={};if(value.since!==void 0){if(typeof value.since!=="string"||!Number.isFinite(Date.parse(value.since)))return null;marks.since=value.since}if(value.heads!==void 0){if(!object(value.heads)||!Object.values(value.heads).every(ids=>Array.isArray(ids)&&ids.every(id=>typeof id==="string")))return null;marks.heads=value.heads}if(value.tags!==void 0){if(!stringRecord(value.tags))return null;marks.tags=value.tags}return marks}function parseWalk(wire){if(!object(wire))return null;const w=wire;const strings=value=>Array.isArray(value)&&value.every(item=>typeof item==="string");const optionalInstant=value=>value===void 0||typeof value==="string"&&Number.isFinite(Date.parse(value));if(typeof w.account!=="string"||!w.account||w.mode!=="full"&&w.mode!=="incremental"||typeof w.startedAt!=="string"||!Number.isFinite(Date.parse(w.startedAt)))return null;if(!PHASES.includes(w.phase)||w.token!==null&&typeof w.token!=="string"||!Number.isSafeInteger(w.pages)||Number(w.pages)<0)return null;if(!strings(w.channels)||!strings(w.uploads)||w.channels.length!==w.uploads.length||!Number.isSafeInteger(w.at)||Number(w.at)<0)return null;if(!Array.isArray(w.queue)||!w.queue.every(entry=>Array.isArray(entry)&&entry.length===2&&entry.every(part=>typeof part==="string"))||w.more!==null&&typeof w.more!=="string")return null;const prior=parseMarks(w.prior),next=parseMarks(w.next);if(!prior||!next||!object(w.gaps)||!Object.values(w.gaps).every(n=>Number.isSafeInteger(n)&&Number(n)>=0))return null;if(!optionalInstant(w.completedAt)||!optionalInstant(w.fullAt)||!optionalInstant(w.quotaUntil)||w.phase==="done"&&w.completedAt===void 0)return null;return{account:w.account,mode:w.mode,startedAt:w.startedAt,phase:w.phase,token:w.token,pages:Number(w.pages),channels:[...w.channels],uploads:[...w.uploads],at:Number(w.at),queue:w.queue.map(([id,tag])=>[id,tag]),more:w.more,prior,next,gaps:{...w.gaps},...w.completedAt===void 0?{}:{completedAt:w.completedAt},...w.fullAt===void 0?{}:{fullAt:w.fullAt},...w.quotaUntil===void 0?{}:{quotaUntil:w.quotaUntil}}}function stable(value,stream,depth=0){if(Array.isArray(value))return value.map(item=>stable(item,stream,depth+1));if(!object(value))return value;const out={};for(const[key,item]of Object.entries(value)){if(key==="etag"||depth===0&&key==="statistics")continue;if(stream==="commentThreads"&&(key==="likeCount"||key==="viewerRating"||key==="canRate"))continue;out[key]=stable(item,stream,depth+1)}return out}function snippet(item){return object(item.snippet)?item.snippet:{}}function commentLine(comment){const s=object(comment)&&object(comment.snippet)?comment.snippet:{};const said=text(s.textOriginal)||text(s.textDisplay);return said?[text(s.authorDisplayName),said].filter(Boolean).join(": "):""}function describe(stream,raw){const item=raw.item,s=snippet(item),title=text(s.title);const lines=(...parts)=>parts.filter(Boolean).join("\n");switch(stream){case"channels":return{title,ts:instant(s.publishedAt),body:lines("YouTube channel: "+title,text(s.customUrl),text(s.description))};case"subscriptions":return{title,ts:instant(s.publishedAt),body:lines("Subscribed to: "+title,text(s.description))};case"playlists":return{title,ts:instant(s.publishedAt),body:lines("Playlist: "+title,text(s.description))};case"playlistItems":{const details=object(item.contentDetails)?item.contentDetails:{};const owner=text(s.videoOwnerChannelTitle);return{title,ts:instant(s.publishedAt,details.videoPublishedAt),body:lines((raw.via==="uploads"?"Uploaded: ":"In playlist: ")+title,owner?"by "+owner:"",text(s.description))}}case"videos":{const tags=Array.isArray(s.tags)?s.tags.filter(tag=>typeof tag==="string"):[];const channel=text(s.channelTitle);return{title,ts:instant(s.publishedAt),body:lines((raw.via==="dislike"?"Disliked video: ":"Liked video: ")+title,channel?"by "+channel:"",text(s.description),tags.join(", "))}}case"commentThreads":{const top=s.topLevelComment,first=commentLine(top),replies=object(item.replies)&&Array.isArray(item.replies.comments)?item.replies.comments.map(commentLine).filter(Boolean):[];const topSnippet=object(top)&&object(top.snippet)?top.snippet:{};return{title:first.slice(0,120),ts:instant(topSnippet.updatedAt,topSnippet.publishedAt),body:lines(first,...replies)}}default:throw Error("YouTube full sync does not normalize stream "+stream+".")}}export function createYouTubeProvider({parts,auth,vault,now=()=>new Date().toISOString(),incrementalEveryMs=YOUTUBE_INCREMENTAL_EVERY_MS,fullEveryMs=YOUTUBE_FULL_EVERY_MS}){if(!Number.isFinite(incrementalEveryMs)||incrementalEveryMs<0||!Number.isFinite(fullEveryMs)||fullEveryMs<0)throw Error("YouTube sync pacing must be non-negative milliseconds.");const info={source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser"};const stop=new AbortController,pending=new Set;let closed=false;let latest=null;const codec=parts.cursorCodecV1({source:"youtube",version:2,versionKey:"v",validate:parseWalk});const fail=(code,message,retryability="non-retryable",cause)=>parts.connectorError(code,message,retryability,cause);const inactive=()=>fail("aborted","YouTube source is inactive.");const owned=task=>{const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled};const declared=new Map(youtubeSyncManifest.streams.map(stream=>[stream.stream,stream]));async function resolveGrant(){if(closed)return inactive();const connection=await vault.connection("youtube");if(!("ok"in connection))return"err"in connection?connection:fail("data_loss","YouTube connection metadata was unconfirmed.");const row=connection.ok;if(!row||row.state!=="connected")return fail("unauthenticated","Connect YouTube before syncing it.");if(typeof row.accountId!=="string"||!row.accountId.trim())return fail("failed_precondition","YouTube sync needs the verified Google subject; an email or grant id is never the account identity.");const scope=YOUTUBE_READ_SCOPES.find(candidate=>row.scopes.includes(candidate));if(!scope)return fail("permission_denied","The YouTube connection has no read scope; reconnect YouTube.");if(closed)return inactive();return Original.ok({id:"0"+createHash("sha256").update(row.accountId).digest("hex").slice(0,25).toUpperCase(),source:"youtube",account:row.accountId,scopes:[scope],expiresAt:new Date(Date.parse(now())+HOUR).toISOString()})}function checkGrant(grant){if(grant.source!=="youtube"||!grant.account?.trim())return fail("permission_denied","YouTube grant is not bound to a verified account.");if(!grant.scopes.some(scope=>YOUTUBE_READ_SCOPES.includes(scope)))return fail("permission_denied","YouTube grant has no read scope.");return void 0}async function fence(grant){if(closed||stop.signal.aborted)return inactive();const current=await vault.connection("youtube");if(!("ok"in current))return"err"in current?current:fail("data_loss","YouTube account fence was unconfirmed.");if(closed||stop.signal.aborted)return inactive();const row=current.ok;if(!row||row.state!=="connected")return fail("unauthenticated","YouTube was disconnected during the sync.");if(row.accountId!==grant.account)return fail("permission_denied","The YouTube account changed during the sync; nothing from the old grant is attributed to the new account.");if(!grant.scopes.every(scope=>row.scopes.includes(scope)))return fail("permission_denied","YouTube read consent was withdrawn.");return Original.ok(void 0)}async function call(grant,listing2,token){const url=new URL(listing2.resource,API);for(const[key,value]of Object.entries(listing2.params))url.searchParams.set(key,value);if(token)url.searchParams.set("pageToken",token);const before=await fence(grant);if(!Original.isOk(before))return before;const reply=await auth.requestRaw("youtube",url.href,{signal:stop.signal});if(closed||stop.signal.aborted)return inactive();if(!("ok"in reply)){const err="err"in reply?reply.err:void 0;if(!err||err.code==="unavailable"||err.code==="aborted")return fail("unavailable","A YouTube list request did not complete (network or request timeout); the page is retried from the same cursor.","transient",err);return reply}const after=await fence(grant);if(!Original.isOk(after))return after;return reply}function soleChannel(walk){return walk.channels.length===1?walk.channels[0]:null}function listing(walk){const page2=(resource,params)=>({resource,params:{...params,maxResults:"50"}});switch(walk.phase){case"channels":return{...page2("channels",{part:"snippet,contentDetails,brandingSettings,status,topicDetails,localizations",mine:"true"}),stream:"channels",via:"mine",owner:null};case"subscriptions":return{...page2("subscriptions",{part:"snippet",mine:"true"}),stream:"subscriptions",via:"subscription",owner:soleChannel(walk)};case"playlists":return{...page2("playlists",{part:"snippet,contentDetails,status,localizations",mine:"true"}),stream:"playlists",via:"playlist",owner:soleChannel(walk)};case"playlistItems":{const id=walk.queue[0][0];return{...page2("playlistItems",{part:"snippet,contentDetails,status",playlistId:id}),stream:"playlistItems",via:"playlist",owner:soleChannel(walk),playlistId:id}}case"uploads":{const id=walk.uploads[walk.at];return{...page2("playlistItems",{part:"snippet,contentDetails,status",playlistId:id}),stream:"playlistItems",via:"uploads",owner:walk.channels[walk.at],playlistId:id,head:"uploads:"+id}}case"likes":case"dislikes":{const rating=walk.phase==="likes"?"like":"dislike";return{...page2("videos",{part:"snippet,contentDetails,status,topicDetails",myRating:rating}),stream:"videos",via:rating,owner:soleChannel(walk),head:rating}}case"comments":return{resource:"commentThreads",params:{part:"snippet,replies",allThreadsRelatedToChannelId:walk.channels[walk.at],maxResults:"100",order:"time",textFormat:"plainText"},stream:"commentThreads",via:"channel-comments",owner:walk.channels[walk.at],byTime:true};case"done":throw Error("A completed YouTube walk has no listing.")}}function settle(walk){for(;;){if(walk.phase==="playlistItems"&&!walk.queue.length){if(walk.more!==null){walk.phase="playlists";walk.token=walk.more;walk.more=null}else{walk.phase="uploads";walk.at=0;walk.token=null}continue}if(walk.phase==="uploads"){while(walk.at<walk.channels.length&&!walk.uploads[walk.at])walk.at++;if(walk.at>=walk.channels.length){walk.phase="likes";walk.at=0;walk.token=null;continue}}if(walk.phase==="comments"&&walk.at>=walk.channels.length){walk.phase="done";walk.token=null;continue}return}}function finish(walk,read){switch(walk.phase){case"channels":walk.phase="subscriptions";break;case"subscriptions":walk.phase="playlists";walk.more=null;break;case"playlists":walk.phase="playlistItems";walk.queue=[];walk.more=null;break;case"playlistItems":{const[id,tag]=walk.queue.shift();if(read)walk.next.tags={...walk.next.tags,[id]:tag};break}case"uploads":walk.at++;break;case"likes":walk.phase="dislikes";break;case"dislikes":walk.phase="comments";walk.at=0;break;case"comments":walk.at++;break;case"done":break}walk.token=null}function gap(walk,stream,reason,count=1){const key=stream+":"+reason;walk.gaps[key]=(walk.gaps[key]??0)+count}function begin(account,mode,prior,fullAt,at){return{account,mode,startedAt:at,phase:"channels",token:null,pages:0,channels:[],uploads:[],at:0,queue:[],more:null,prior:mode==="full"?{}:prior,next:{},gaps:{},...fullAt===void 0?{}:{fullAt}}}function complete(walk,at){return{...walk,phase:"done",token:null,at:0,queue:[],more:null,prior:{...walk.next,since:walk.startedAt},next:{},completedAt:at,...walk.mode==="full"?{fullAt:at}:{}}}function encode(walk,notes){let attempt=codec.encode(walk);if("ok"in attempt)return attempt;if(walk.prior.tags||walk.next.tags){const{tags:_p,...prior}=walk.prior,{tags:_n,...next}=walk.next;walk.prior=prior;walk.next=next;notes.push("youtube: playlist-marks-dropped \u2014 remembered playlist versions were dropped to keep the cursor within "+Original.SYNC_CURSOR_MAX_CHARS+" chars; those playlists are read in full");attempt=codec.encode(walk);if("ok"in attempt)return attempt}if(walk.prior.heads||walk.next.heads){const{heads:_p,...prior}=walk.prior,{heads:_n,...next}=walk.next;walk.prior=prior;walk.next=next;notes.push("youtube: head-marks-dropped \u2014 remembered list heads were dropped to keep the cursor bounded; those lists are read in full");attempt=codec.encode(walk)}return attempt}function page(items,walk,exhausted,notes){latest=walk;const next=encode(walk,notes);if(!("ok"in next))return next;return Original.ok({items,next:next.ok,exhausted,...notes.length?{notes}:{}})}function respond(items,walk,at,notes){return walk.phase==="done"?page(items,complete(walk,at),true,notes):page(items,walk,false,notes)}function quotaWait(until){return fail("resource_exhausted","YouTube daily quota is exhausted (youtube-daily-quota-exhausted): the project's YouTube Data API units for today are used up. Quota backoff not due until "+until+", when Google resets the quota at midnight Pacific Time; the walk then resumes from its saved cursor and nothing is skipped.","retry-at-higher-level")}const RATE_LIMIT=new Set(["rateLimitExceeded","userRateLimitExceeded","RATE_LIMIT_EXCEEDED"]),DAILY=new Set(["quotaExceeded","dailyLimitExceeded"]),GRANT=new Set(["insufficientPermissions","authError","unauthorized","PERMISSION_DENIED","UNAUTHENTICATED"]);function classify(walk,reply){const what=walk.phase==="uploads"||walk.phase==="playlistItems"?"playlistItems.list":walk.phase==="likes"||walk.phase==="dislikes"?"videos.list":walk.phase==="comments"?"commentThreads.list":walk.phase+".list";if(reply.status===200){let data;try{data=JSON.parse(reply.body)}catch{return{kind:"err",err:fail("data_loss","YouTube "+what+" returned a body that is not JSON; the page is asked again.","transient").err}}if(!object(data)||data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item)))||data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return{kind:"err",err:fail("data_loss","YouTube "+what+" returned a malformed list; the page is asked again.","transient").err};return{kind:"ok",data}}const reason=parts.googleErrorReasonV1(reply.body);if((reply.status===403||reply.status===429)&&reason!==void 0&&DAILY.has(reason))return{kind:"quota"};const status=()=>parts.webStatusErrorV1(reply.status,{provider:"YouTube",what,headers:reply.headers,...reason?{detail:reason}:{},bodyOverride:code=>code===403&&reason!==void 0&&RATE_LIMIT.has(reason)?{code:"resource_exhausted",retryability:"throttling",meaning:"the provider throttled the call ("+reason+")"}:void 0})??fail("internal","YouTube "+what+" returned HTTP "+reply.status+".").err;if(reply.status===429||reply.status===403&&reason!==void 0&&RATE_LIMIT.has(reason))return{kind:"err",err:status()};if(reason==="youtubeSignupRequired"&&(reply.status===401||reply.status===403))return{kind:"gap",reason:"youtube-signup-required"};if(reply.status===401)return{kind:"err",err:status()};if(reply.status===403){if(walk.phase==="channels"||reason===void 0||GRANT.has(reason))return{kind:"err",err:status()};return{kind:"gap",reason:reasonCode(reason,"forbidden")}}if(reply.status===404)return{kind:"gap",reason:reasonCode(reason,"not-found")};if(reply.status===400&&reason==="invalidPageToken"&&walk.token!==null)return{kind:"restart"};return{kind:"err",err:status()}}async function pullInner(grant,cursor){const invalid=checkGrant(grant);if(invalid)return invalid;if(closed)return inactive();const notes=[],nowMs=Date.parse(now()),nowIso=new Date(nowMs).toISOString();let walk=cursor===null?null:codec.decode(cursor);if(cursor!==null&&walk===null)notes.push("youtube: cursor-unreadable \u2014 the walk starts again from the first list");if(walk&&walk.account!==grant.account){notes.push("youtube: account-changed \u2014 the walk starts again for the connected account");walk=null}if(walk?.quotaUntil!==void 0){if(nowMs<Date.parse(walk.quotaUntil)){latest=walk;return quotaWait(walk.quotaUntil)}const{quotaUntil:_q,...resumed}=walk;walk=resumed;notes.push("youtube: quota-reset \u2014 the walk resumes where the daily quota stopped it")}if(!walk){walk=begin(grant.account,"full",{},void 0,nowIso);notes.push("youtube: full-pass \u2014 every list is read")}else if(walk.phase==="done"){const due=Date.parse(walk.completedAt)+incrementalEveryMs;if(nowMs<due&&cursor!==null){latest=walk;return Original.ok({items:[],next:cursor,exhausted:true,notes:[...notes,"youtube: pass-not-due \u2014 the next pass starts after "+new Date(due).toISOString()+" (quota pacing)"]})}const full=walk.fullAt===void 0||nowMs-Date.parse(walk.fullAt)>=fullEveryMs;walk=begin(grant.account,full?"full":"incremental",walk.prior,walk.fullAt,nowIso);notes.push(full?"youtube: full-pass \u2014 every list is read again (periodic re-walk)":"youtube: incremental-pass \u2014 cheap lists re-listed, unchanged playlists skipped, newest-first lists stop at the remembered head")}settle(walk);if(walk.phase==="done")return page([],complete(walk,nowIso),true,notes);if(walk.pages>=MAX_WALK_PAGES)return fail("resource_exhausted","YouTube walk exceeded "+MAX_WALK_PAGES+" provider pages; the cursor is kept.");const current=listing(walk),reply=await call(grant,current,walk.token);if(!("ok"in reply))return"err"in reply?reply:fail("data_loss","YouTube request result was unconfirmed.");walk.pages++;const outcome=classify(walk,reply.ok),stream=current.stream,items=[];if(outcome.kind==="err")return{err:outcome.err};if(outcome.kind==="quota"){walk.quotaUntil=new Date(nextPacificMidnight(nowMs)+QUOTA_SLACK_MS).toISOString();notes.push("youtube: youtube-daily-quota-exhausted \u2014 no request until "+walk.quotaUntil+"; the walk resumes at this list");return page([],walk,false,notes)}if(outcome.kind==="restart"){walk.token=null;notes.push("youtube: page-token-expired \u2014 this list is read again from its first page");return page([],walk,false,notes)}if(outcome.kind==="gap"){const reason=walk.phase==="channels"&&outcome.reason==="youtube-signup-required"?"no-youtube-channel":outcome.reason;gap(walk,stream,reason);notes.push("youtube: "+stream+" not read \u2014 "+reason+" (HTTP "+reply.ok.status+")");finish(walk,false);settle(walk);return respond(items,walk,nowIso,notes)}const data=outcome.data,rows=Array.isArray(data.items)?data.items:[],nextToken=typeof data.nextPageToken==="string"?data.nextPageToken:null;const ids=[];let missing=0,unavailable=0;for(const item of rows){const id=typeof item.id==="string"&&item.id?item.id:"";if(!id){missing++;continue}ids.push(id);const s=snippet(item);const owner=walk.phase==="channels"?id:current.via==="subscription"||current.via==="playlist"?text(s.channelId)||current.owner:current.owner;const raw={account:walk.account,channelId:owner,via:current.via,...current.playlistId?{playlistId:current.playlistId}:{},item};items.push({streamRef:stream,raw:json(raw)});if(stream==="playlistItems"&&(s.title==="Private video"||s.title==="Deleted video"))unavailable++}if(missing){gap(walk,stream,"item-without-id",missing);notes.push("youtube: "+stream+" item-without-id \u2014 "+missing+" item(s) without a provider id were not stored")}if(unavailable){gap(walk,"playlistItems","video-unavailable",unavailable);notes.push("youtube: video-unavailable \u2014 "+unavailable+" playlist item(s) point to a private or deleted video; only the placeholder is stored")}if(walk.phase==="channels"){for(const item of rows){if(typeof item.id!=="string"||!item.id)continue;const details=object(item.contentDetails)&&object(item.contentDetails.relatedPlaylists)?item.contentDetails.relatedPlaylists:{};walk.channels.push(item.id);walk.uploads.push(text(details.uploads))}if(!nextToken&&!walk.channels.length){gap(walk,"channels","no-youtube-channel");notes.push("youtube: channels not read \u2014 no-youtube-channel (this identity has no channel; a Brand Account channel needs its own grant)")}}if(walk.phase==="playlists"){const queue=[];for(const item of rows){if(typeof item.id!=="string"||!item.id)continue;const details=object(item.contentDetails)?item.contentDetails:{};const tag=shortHash(typeof item.etag==="string"?item.etag:Original.jcsCanonicalize(json(item)));if(details.itemCount===0||walk.mode==="incremental"&&walk.prior.tags?.[item.id]===tag){walk.next.tags={...walk.next.tags,[item.id]:tag};continue}queue.push([item.id,tag])}finish(walk,true);walk.queue=queue;walk.more=nextToken}else{if(current.head&&walk.token===null)walk.next.heads={...walk.next.heads,[current.head]:ids.slice(0,HEAD_IDS)};const known=current.head?walk.prior.heads?.[current.head]:void 0;const reachedHead=walk.mode==="incremental"&&!!known?.length&&ids.some(id=>known.includes(id));const since=walk.prior.since===void 0?NaN:Date.parse(walk.prior.since)-COMMENT_SLACK_MS;const reachedOld=walk.mode==="incremental"&&current.byTime===true&&Number.isFinite(since)&&rows.some(item=>{const top=snippet(item).topLevelComment,published=object(top)&&object(top.snippet)?Date.parse(String(top.snippet.publishedAt)):NaN;return Number.isFinite(published)&&published<since});if(nextToken&&nextToken===walk.token){gap(walk,stream,"repeated-page-token");notes.push("youtube: "+stream+" repeated-page-token \u2014 the provider repeated a page token; the rest of this list is not read");finish(walk,false)}else if(nextToken&&!reachedHead&&!reachedOld)walk.token=nextToken;else finish(walk,true)}settle(walk);return respond(items,walk,nowIso,notes)}const connector={manifest:youtubeSyncManifest,discover:()=>parts.gateRefusal("YouTube synchronous census","The production YouTube provider is async; use discoverAsync"),pull:()=>parts.gateRefusal("YouTube synchronous pull","The production YouTube provider is async; use pullAsync"),discoverAsync:grant=>owned((async()=>{const invalid=checkGrant(grant);if(invalid)return invalid;const fenced=await fence(grant);if(!Original.isOk(fenced))return fenced;const gaps=latest&&latest.account===grant.account?latest.gaps:{};const streams={};for(const stream of[...READ_STREAMS,...LISTED_ONLY]){const reasons=[...(STATIC_REASONS[stream]??[]).map(reason=>({reason})),...Object.entries(gaps).filter(([key])=>key.startsWith(stream+":")).map(([key,count])=>({reason:key.slice(stream.length+1),count}))];streams[stream]={method:"pagination-exhaustion",...reasons.length?{partialReasons:reasons}:{}}}return Original.ok({asOf:new Date(Date.parse(now())).toISOString(),streams})})()),pullAsync:(grant,cursor)=>owned(pullInner(grant,cursor)),normalize(item){const decl=declared.get(item.streamRef);if(!decl||!READ_STREAMS.includes(item.streamRef))throw Error("YouTube full sync does not emit stream "+item.streamRef+".");if(!object(item.raw)||!object(item.raw.item)||typeof item.raw.account!=="string"||typeof item.raw.via!=="string")throw Error("YouTube normalization requires the wrapped provider resource.");const raw=item.raw,id=typeof raw.item.id==="string"?raw.item.id:"";if(!id)throw Error("YouTube resource has no provider id.");const{title,body,ts}=describe(item.streamRef,raw);const payload={title,account:raw.account,channelId:typeof raw.channelId==="string"?raw.channelId:null,via:raw.via,...typeof raw.playlistId==="string"?{playlistId:raw.playlistId}:{},item:stable(raw.item,item.streamRef)};return{nk:{source:"youtube",stream:item.streamRef,sourceId:item.streamRef==="videos"?raw.via+":"+id:id},ts,kind:decl.kinds[0],tier:"api",schemaVersion:1,mentions:[],body,payload:json(payload)}}};return{info,connector,resolveGrant:()=>owned(resolveGrant()),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}}}
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{pinnedMethods,discoveryPin}from"./discovery-data.js";import{creatorMethods}from"./creator-data.js";import{object,invalidSchema}from"./schema.js";import{createYouTubeConnector}from"./connector.js";import{readTakeout}from"./takeout.js";const methodMap=new Map([...pinnedMethods,...creatorMethods].flatMap(method=>[[method.id,method],[method.contractName,method]]));const info={source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["authorized_collections"],limitations:["provider_history_limits"]},readById:true};export function createYouTubeSource({parts,auth,vault,transport,takeoutRoot}){const stop=new AbortController,pending=new Set;let closed=false;const track=work=>{pending.add(work);return work.finally(()=>pending.delete(work))};const unavailable=()=>businessError("unavailable","YouTube source is inactive.","connector");const aborted=()=>businessError("aborted","YouTube read was cancelled.","connector");function catalog(options={}){const{query="",resource,limit=20,cursor=0,profile="data"}=options;if(typeof query!=="string"||query.length>500||resource!==void 0&&typeof resource!=="string"||!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return businessError("invalid_argument","Catalog query/limit/cursor is invalid.","connector");if(!["data","analytics","reporting","all"].includes(profile))return businessError("invalid_argument","Unknown YouTube capability profile.","connector");const selected=[...pinnedMethods,...creatorMethods].filter(m=>(profile==="all"||(m.profile??"data")===profile)&&(!resource||m.resource===resource)&&(!query||[m.id,m.description??""].join(" ").toLowerCase().includes(query.toLowerCase())));return Original.ok({total:selected.length,methods:selected.slice(cursor,cursor+limit).map(m=>({id:m.id,contract:m.contractName,resource:m.resource,method:m.httpMethod,scopes:m.scopes??[],body:!!m.request?.$ref,media:!!m.supportsMediaUpload})),...cursor+limit<selected.length?{next:cursor+limit}:{},pin:discoveryPin,gaps:["watchHistory/watchLater require explicit read-only Takeout","creator Analytics/Reporting need separate admitted profile and scopes","audio/video bytes require provider permission","write effects require original action rail verification; HTTP success is not EFFECTED"]})}function method(id){const found=methodMap.get(id);return found?Original.ok(structuredClone(found)):businessError("not_found","Unknown pinned YouTube method.","connector")}async function invokeInner(id,input,options={},level1=false){if(closed)return unavailable();const m=methodMap.get(id);if(!m)return businessError("not_found","Unknown pinned YouTube method.","connector");const invalid=invalidSchema(m.params,input);if(invalid)return businessError("invalid_argument",invalid,"connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const conn=await vault.connection("youtube");if(!("ok"in conn))return conn;if(!conn.ok||conn.ok.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(closed||signal.aborted)return aborted();if(!m.scopes?.length)return businessError("failed_precondition","The pinned provider method "+m.id+" publishes no OAuth scope requirement. Scope/admission reconnaissance is required before a dispatch; no permission was guessed.","auth");if(!(m.scopes??[]).some(scope=>conn.ok.scopes.includes(scope)))return businessError("permission_denied","Method "+id+" requires one of the declared scopes: "+(m.scopes??[]).join(", ")+". Reauthorize this source; no API-key fallback.","auth");if(input.params.onBehalfOfContentOwner!==void 0&&!conn.ok.scopes.includes("https://www.googleapis.com/auth/youtubepartner"))return businessError("permission_denied","Content-owner operations require the partner scope and linked CMS admission.","auth");let pathname=m.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(input.params)){if(m.parameters?.[key]?.location==="path"){const text=String(value);if(text.split("/").some(segment=>segment==="."||segment==="..")||/[?#%\\]/.test(text))return businessError("invalid_argument","Path parameters cannot contain traversal or encoded routing material.","connector");const reserved=pathname.includes("{+"+key+"}");if(reserved&&!/^[A-Za-z0-9_./-]+$/.test(text))return businessError("invalid_argument","Reserved resource paths must be canonical provider resource names.","connector");pathname=pathname.replace(reserved?"{+"+key+"}":"{"+key+"}",reserved?text.split("/").map(encodeURIComponent).join("/"):encodeURIComponent(text))}else query.set(key,Array.isArray(value)?value.join(","):String(value))}if(pathname.includes("{"))return businessError("invalid_argument","Provider path parameter is missing.","connector");if(input.media)return businessError("failed_precondition","Media upload needs the separately admitted bounded streaming transport; no effect was dispatched.","connector");if(m.id==="youtube.youtube.v3.liveChat.messages.stream")return businessError("failed_precondition","The pinned server-streaming RPC requires an admitted cancelable stream transport; use liveChatMessages.list with pageToken until that profile is enabled.","connector");if(m.httpMethod!=="GET"&&!transport&&!level1)return businessError("failed_precondition","Write transport and original action admission are required for "+id+"; no effect was dispatched.","connector");const url=new URL(pathname,m.baseUrl??"https://www.googleapis.com/");url.search=query.toString();const raw=transport?await transport("youtube",url.href,{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"},signal}):await auth.requestRaw("youtube",url.href,{signal,...level1?{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"}}:{}});if(closed||signal.aborted)return aborted();if(!("ok"in raw))return raw;if(Buffer.byteLength(raw.ok.body,"utf8")>2*1024*1024)return businessError("resource_exhausted","YouTube response exceeds the bounded broker body budget. Use an admitted streaming path; no body was truncated.","connector");const reason=parts.googleErrorReasonV1(raw.ok.body),baseOverride=parts.googleStatusOverrideV1(raw.ok.body),status=parts.webStatusErrorV1(raw.ok.status,{provider:"YouTube",what:id,headers:raw.ok.headers,bodyOverride:status2=>status2===403&&reason==="quotaExceeded"?{code:"resource_exhausted",retryability:"throttling",meaning:"the YouTube project quota bucket is exhausted (quotaExceeded)"}:baseOverride(status2),...reason?{detail:reason}:{}});if(status)return{err:status};if(m.supportsMediaDownload){return Original.ok({method:id,resource:m.resource,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain",items:[{id:input.params.id??input.params.resourceName,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain"}],warnings:[],effect:"read",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}if(raw.ok.status===204||!raw.ok.body)return Original.ok({method:id,resource:m.resource,items:[],warnings:["Provider response carries no body; upstream effect remains unverified."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}});let data;try{data=JSON.parse(raw.ok.body)}catch{return businessError("data_loss","YouTube returned invalid JSON for "+id+".","connector")}if(!object(data))return businessError("data_loss","YouTube response must be an object.","connector");if(data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item))))return businessError("data_loss","YouTube response items are malformed.","connector");if(data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return businessError("data_loss","YouTube nextPageToken is malformed.","connector");const items=Array.isArray(data.items)?data.items:typeof data.id==="string"?[data]:[];return Original.ok({method:id,resource:m.resource,data,items,...typeof data.nextPageToken==="string"?{nextPageToken:data.nextPageToken}:{},warnings:m.httpMethod==="GET"?[]:["HTTP response accepted. Only original action read-after-write/event-confirm can mark EFFECTED."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}function invoke(id,input,options={},level1=false){return track(invokeInner(id,input,options,level1).catch(error=>{if(closed||options.signal?.aborted)return aborted();const cause=object(error)?Original.validateStructuredError(error.structuredError):void 0;return parts.connectorError("unavailable","Trusted YouTube transport failed before a confirmed provider response. Raw custody exception text is not a tool result.","transient",cause&&"ok"in cause?cause.ok:void 0)}))}async function*pages(id,params,options={}){const m=methodMap.get(id);if(!m||m.httpMethod!=="GET"){yield businessError("invalid_argument","Only pinned GET methods can be paginated.","connector");return}if(options.maxPages!==void 0&&(!Number.isInteger(options.maxPages)||options.maxPages<1)){yield businessError("invalid_argument","maxPages must be a positive integer.","connector");return}const seen=new Set;let token=typeof params.pageToken==="string"?params.pageToken:void 0,count=0;for(;;){if(token&&seen.has(token)){yield businessError("failed_precondition","YouTube repeated a page token; coverage is incomplete.","connector");return}if(token)seen.add(token);const result=await invoke(id,{params:{...params,...token?{pageToken:token}:{}}},options);yield result;if(!("ok"in result))return;count++;token=result.ok.nextPageToken;if(!token)return;if(options.maxPages!==void 0&&count>=options.maxPages){yield businessError("resource_exhausted","Selected page budget ended with a nonterminal token; coverage is incomplete.","connector");return}}}async function readInner(request,options={}){if(closed)return unavailable();const bad=validateRead(request,["fileId"]);if(bad)return bad;request=structuredClone(request);if(request.fileId!==void 0&&(!/^[A-Za-z0-9_-]{1,200}$/.test(request.fileId)||request.query!==void 0||request.since!==void 0||request.until!==void 0))return businessError("invalid_argument","An exact YouTube video read takes fileId without query or time bounds.","connector");const selected=request.fileId?"youtube.videos.list":request.query?"youtube.search.list":"youtube.activities.list";const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const connection=await vault.connection("youtube");if(!("ok"in connection))return connection;const captured=structuredClone(connection.ok);if(!captured||captured.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(typeof captured.accountId!=="string"||!captured.accountId.trim())return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");const firstScopes=methodMap.get(selected)?.scopes??[],detailScopes=request.query?methodMap.get("youtube.videos.list")?.scopes??[]:firstScopes,scopes=firstScopes.filter(scope=>detailScopes.includes(scope)),readonly="https://www.googleapis.com/auth/youtube.readonly";const requiredScope=scopes.includes(readonly)&&captured.scopes.includes(readonly)?readonly:scopes.find(scope=>captured.scopes.includes(scope));if(!requiredScope)return businessError("permission_denied","The selected YouTube query requires one of its pinned read scopes.","auth");const fence=async()=>{if(closed||signal.aborted)return aborted();const current=await vault.connection("youtube");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==captured.accountId||!current.ok.scopes.includes(requiredScope))return businessError("permission_denied","YouTube selected read connection or scope changed.","auth");return Original.ok(void 0)};const boundInvoke=async(id,input)=>{const before=await fence();if(!("ok"in before))return before;const answer2=await invoke(id,input,{signal});const after=await fence();return"ok"in after?answer2:after};const wanted=request.limit??1,params=request.fileId?{part:["snippet","contentDetails","status","statistics"],id:[request.fileId]}:request.query?{part:["snippet"],q:request.query,type:["video"],maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}}:{part:["snippet","contentDetails"],mine:true,maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}};let answer=await boundInvoke(selected,{params});if("err"in answer&&selected==="youtube.activities.list"&&answer.err.code==="permission_denied"){const channels=await boundInvoke("youtube.channels.list",{params:{part:["id"],mine:true,maxResults:1}});if("ok"in channels&&!channels.ok.items.length)return readResult("youtube",[],["This Google account has no YouTube channel, so it has no own activity to read; full sync records it as no-youtube-channel."])}if(!("ok"in answer))return answer;const items=[...answer.ok.items],seen=new Set;let steps=1;while(items.length<wanted&&answer.ok.nextPageToken){const token=answer.ok.nextPageToken;if(seen.has(token))return businessError("failed_precondition","Selected YouTube read repeated a token; no complete result was asserted.","connector");seen.add(token);if(++steps>100)return businessError("resource_exhausted","Selected YouTube read exceeded the page budget before satisfying its limit; no complete result was asserted.","connector");answer=await boundInvoke(selected,{params:{...params,pageToken:token}});if(!("ok"in answer))return answer;items.push(...answer.ok.items)}let retained=items.slice(0,wanted),resource=answer.ok.resource;if(request.query&&retained.length){const selectedItems=retained,details=[];for(let index=0;index<selectedItems.length;index+=50){const block=selectedItems.slice(index,index+50),ids=block.map(item=>object(item.id)?item.id.videoId:void 0).filter(id=>typeof id==="string");if(ids.length!==block.length)return businessError("data_loss","A selected YouTube video search result lacks its native video id.","connector");const hydrated=await boundInvoke("youtube.videos.list",{params:{part:["snippet","contentDetails","status","statistics","topicDetails","recordingDetails","localizations"],id:ids}});if(!("ok"in hydrated))return hydrated;for(const item of hydrated.ok.items)details.push({...item,_selection:block.find(selected2=>object(selected2.id)&&selected2.id.videoId===item.id)??null})}retained=details;resource="videos"}const records=retained.map(item=>({source:"youtube",sourceId:captured.accountId+":"+resource+":"+itemId(item),stream:resource,kind:"youtube."+resource.toLowerCase()+".changed",ts:itemTime(item),body:JSON.stringify(item),fields:{...item}}));const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;if(closed||signal.aborted)return aborted();return readResult("youtube",records,[...answer.ok.warnings,...answer.ok.nextPageToken||items.length>wanted?["More provider results exist beyond this selected batch."]:[],...retained.length<Math.min(items.length,wanted)?["Some selected videos are currently inaccessible/deleted; search metadata is retained only as an attributed missing detail, never a fabricated video body."]:[],"This selected API query does not establish complete YouTube account or archive coverage."])}function read(request,options={}){return track(readInner(request,options))}async function importTakeout(root=takeoutRoot??"",options={}){if(closed)return unavailable();if(!root)return businessError("failed_precondition","Supply an explicit extracted read-only Takeout copy; API success cannot substitute for history.","connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;const result=await readTakeout(root,signal);if(!("ok"in result))return result;if(closed||signal.aborted)return aborted();const saved=await cache(vault,"youtube",result.ok.records);if(!("ok"in saved))return saved;return result}const account=async()=>{const row=await vault.connection("youtube");if(!("ok"in row))return row;if(!row.ok||row.ok.state!=="connected")return businessError("unauthenticated","YouTube identity needs a connected account.","auth");if(!row.ok.accountId)return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");return Original.ok(row.ok.accountId)};function actionSchema(schema){const{id:_discoveryType,...result}=schema;if(result.properties)result.properties=Object.fromEntries(Object.entries(result.properties).map(([key,value])=>[key,actionSchema(value)]));if(result.items)result.items=actionSchema(result.items);if(object(result.additionalProperties))result.additionalProperties=actionSchema(result.additionalProperties);return result}const actions={catalog,method:id=>{const result=method(id);if(!("ok"in result))return result;const m=result.ok;return Original.ok({...m,params:actionSchema(m.params),...!m.supportsMediaUpload&&m.id!=="youtube.youtube.v3.liveChat.messages.stream"&&(!m.profile||m.httpMethod==="GET")?{level:1,effect:m.httpMethod==="GET"?"read":"write"}:{}})},invoke:(id,input,options={})=>invoke(id,input,options,true)};const source={info,actions,catalog,method,invoke,pages,read,status:()=>closed?Promise.resolve(Original.ok({...info,state:"unavailable",message:"YouTube source is inactive."})):connectionState(vault,info),connect:options=>closed?Promise.resolve(unavailable()):track(auth.connect("youtube",options)),job:id=>closed?unavailable():auth.job(id),cancelJob:id=>auth.cancelJob(id),importTakeout:(root,options)=>track(importTakeout(root,options)),createConnector:(plan,options={})=>createYouTubeConnector({parts,invoke,method,account,isClosed:()=>closed},plan,options),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}};return source}export function itemId(item){if(typeof item.id==="string")return item.id;if(typeof item.videoId==="string")return item.videoId;if(object(item.id)){for(const key of["videoId","channelId","playlistId"])if(typeof item.id[key]==="string")return key+":"+item.id[key]}const value=JSON.parse(JSON.stringify(item.id??item));return createHash("sha256").update(Original.jcsCanonicalize(value)).digest("hex")}export function itemTime(item){const snippet=object(item.snippet)?item.snippet:{};for(const value of[item.time,item.updated,item.updatedAt,snippet.updatedAt,snippet.publishedAt])if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return"1970-01-01T00:00:00.000Z"}
1
+ import{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{pinnedMethods,discoveryPin}from"./discovery-data.js";import{creatorMethods}from"./creator-data.js";import{object,invalidSchema}from"./schema.js";import{createYouTubeConnector}from"./connector.js";import{readTakeout}from"./takeout.js";import{youtubeContent}from"./content.js";const methodMap=new Map([...pinnedMethods,...creatorMethods].flatMap(method=>[[method.id,method],[method.contractName,method]]));const info={content:youtubeContent,source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["authorized_collections"],limitations:["provider_history_limits"]},readById:true};export function createYouTubeSource({parts,auth,vault,transport,takeoutRoot}){const stop=new AbortController,pending=new Set;let closed=false;const track=work=>{pending.add(work);return work.finally(()=>pending.delete(work))};const unavailable=()=>businessError("unavailable","YouTube source is inactive.","connector");const aborted=()=>businessError("aborted","YouTube read was cancelled.","connector");function catalog(options={}){const{query="",resource,limit=20,cursor=0,profile="data"}=options;if(typeof query!=="string"||query.length>500||resource!==void 0&&typeof resource!=="string"||!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return businessError("invalid_argument","Catalog query/limit/cursor is invalid.","connector");if(!["data","analytics","reporting","all"].includes(profile))return businessError("invalid_argument","Unknown YouTube capability profile.","connector");const selected=[...pinnedMethods,...creatorMethods].filter(m=>(profile==="all"||(m.profile??"data")===profile)&&(!resource||m.resource===resource)&&(!query||[m.id,m.description??""].join(" ").toLowerCase().includes(query.toLowerCase())));return Original.ok({total:selected.length,methods:selected.slice(cursor,cursor+limit).map(m=>({id:m.id,contract:m.contractName,resource:m.resource,method:m.httpMethod,scopes:m.scopes??[],body:!!m.request?.$ref,media:!!m.supportsMediaUpload})),...cursor+limit<selected.length?{next:cursor+limit}:{},pin:discoveryPin,gaps:["watchHistory/watchLater require explicit read-only Takeout","creator Analytics/Reporting need separate admitted profile and scopes","audio/video bytes require provider permission","write effects require original action rail verification; HTTP success is not EFFECTED"]})}function method(id){const found=methodMap.get(id);return found?Original.ok(structuredClone(found)):businessError("not_found","Unknown pinned YouTube method.","connector")}async function invokeInner(id,input,options={},level1=false){if(closed)return unavailable();const m=methodMap.get(id);if(!m)return businessError("not_found","Unknown pinned YouTube method.","connector");const invalid=invalidSchema(m.params,input);if(invalid)return businessError("invalid_argument",invalid,"connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const conn=await vault.connection("youtube");if(!("ok"in conn))return conn;if(!conn.ok||conn.ok.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(closed||signal.aborted)return aborted();if(!m.scopes?.length)return businessError("failed_precondition","The pinned provider method "+m.id+" publishes no OAuth scope requirement. Scope/admission reconnaissance is required before a dispatch; no permission was guessed.","auth");if(!(m.scopes??[]).some(scope=>conn.ok.scopes.includes(scope)))return businessError("permission_denied","Method "+id+" requires one of the declared scopes: "+(m.scopes??[]).join(", ")+". Reauthorize this source; no API-key fallback.","auth");if(input.params.onBehalfOfContentOwner!==void 0&&!conn.ok.scopes.includes("https://www.googleapis.com/auth/youtubepartner"))return businessError("permission_denied","Content-owner operations require the partner scope and linked CMS admission.","auth");let pathname=m.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(input.params)){if(m.parameters?.[key]?.location==="path"){const text=String(value);if(text.split("/").some(segment=>segment==="."||segment==="..")||/[?#%\\]/.test(text))return businessError("invalid_argument","Path parameters cannot contain traversal or encoded routing material.","connector");const reserved=pathname.includes("{+"+key+"}");if(reserved&&!/^[A-Za-z0-9_./-]+$/.test(text))return businessError("invalid_argument","Reserved resource paths must be canonical provider resource names.","connector");pathname=pathname.replace(reserved?"{+"+key+"}":"{"+key+"}",reserved?text.split("/").map(encodeURIComponent).join("/"):encodeURIComponent(text))}else query.set(key,Array.isArray(value)?value.join(","):String(value))}if(pathname.includes("{"))return businessError("invalid_argument","Provider path parameter is missing.","connector");if(input.media)return businessError("failed_precondition","Media upload needs the separately admitted bounded streaming transport; no effect was dispatched.","connector");if(m.id==="youtube.youtube.v3.liveChat.messages.stream")return businessError("failed_precondition","The pinned server-streaming RPC requires an admitted cancelable stream transport; use liveChatMessages.list with pageToken until that profile is enabled.","connector");if(m.httpMethod!=="GET"&&!transport&&!level1)return businessError("failed_precondition","Write transport and original action admission are required for "+id+"; no effect was dispatched.","connector");const url=new URL(pathname,m.baseUrl??"https://www.googleapis.com/");url.search=query.toString();const raw=transport?await transport("youtube",url.href,{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"},signal}):await auth.requestRaw("youtube",url.href,{signal,...level1?{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"}}:{}});if(closed||signal.aborted)return aborted();if(!("ok"in raw))return raw;if(Buffer.byteLength(raw.ok.body,"utf8")>2*1024*1024)return businessError("resource_exhausted","YouTube response exceeds the bounded broker body budget. Use an admitted streaming path; no body was truncated.","connector");const reason=parts.googleErrorReasonV1(raw.ok.body),baseOverride=parts.googleStatusOverrideV1(raw.ok.body),status=parts.webStatusErrorV1(raw.ok.status,{provider:"YouTube",what:id,headers:raw.ok.headers,bodyOverride:status2=>status2===403&&reason==="quotaExceeded"?{code:"resource_exhausted",retryability:"throttling",meaning:"the YouTube project quota bucket is exhausted (quotaExceeded)"}:baseOverride(status2),...reason?{detail:reason}:{}});if(status)return{err:status};if(m.supportsMediaDownload){return Original.ok({method:id,resource:m.resource,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain",items:[{id:input.params.id??input.params.resourceName,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain"}],warnings:[],effect:"read",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}if(raw.ok.status===204||!raw.ok.body)return Original.ok({method:id,resource:m.resource,items:[],warnings:["Provider response carries no body; upstream effect remains unverified."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}});let data;try{data=JSON.parse(raw.ok.body)}catch{return businessError("data_loss","YouTube returned invalid JSON for "+id+".","connector")}if(!object(data))return businessError("data_loss","YouTube response must be an object.","connector");if(data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item))))return businessError("data_loss","YouTube response items are malformed.","connector");if(data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return businessError("data_loss","YouTube nextPageToken is malformed.","connector");const items=Array.isArray(data.items)?data.items:typeof data.id==="string"?[data]:[];return Original.ok({method:id,resource:m.resource,data,items,...typeof data.nextPageToken==="string"?{nextPageToken:data.nextPageToken}:{},warnings:m.httpMethod==="GET"?[]:["HTTP response accepted. Only original action read-after-write/event-confirm can mark EFFECTED."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}function invoke(id,input,options={},level1=false){return track(invokeInner(id,input,options,level1).catch(error=>{if(closed||options.signal?.aborted)return aborted();const cause=object(error)?Original.validateStructuredError(error.structuredError):void 0;return parts.connectorError("unavailable","Trusted YouTube transport failed before a confirmed provider response. Raw custody exception text is not a tool result.","transient",cause&&"ok"in cause?cause.ok:void 0)}))}async function*pages(id,params,options={}){const m=methodMap.get(id);if(!m||m.httpMethod!=="GET"){yield businessError("invalid_argument","Only pinned GET methods can be paginated.","connector");return}if(options.maxPages!==void 0&&(!Number.isInteger(options.maxPages)||options.maxPages<1)){yield businessError("invalid_argument","maxPages must be a positive integer.","connector");return}const seen=new Set;let token=typeof params.pageToken==="string"?params.pageToken:void 0,count=0;for(;;){if(token&&seen.has(token)){yield businessError("failed_precondition","YouTube repeated a page token; coverage is incomplete.","connector");return}if(token)seen.add(token);const result=await invoke(id,{params:{...params,...token?{pageToken:token}:{}}},options);yield result;if(!("ok"in result))return;count++;token=result.ok.nextPageToken;if(!token)return;if(options.maxPages!==void 0&&count>=options.maxPages){yield businessError("resource_exhausted","Selected page budget ended with a nonterminal token; coverage is incomplete.","connector");return}}}async function readInner(request,options={}){if(closed)return unavailable();const bad=validateRead(request,["fileId"]);if(bad)return bad;request=structuredClone(request);if(request.fileId!==void 0&&(!/^[A-Za-z0-9_-]{1,200}$/.test(request.fileId)||request.query!==void 0||request.since!==void 0||request.until!==void 0))return businessError("invalid_argument","An exact YouTube video read takes fileId without query or time bounds.","connector");const selected=request.fileId?"youtube.videos.list":request.query?"youtube.search.list":"youtube.activities.list";const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const connection=await vault.connection("youtube");if(!("ok"in connection))return connection;const captured=structuredClone(connection.ok);if(!captured||captured.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(typeof captured.accountId!=="string"||!captured.accountId.trim())return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");const firstScopes=methodMap.get(selected)?.scopes??[],detailScopes=request.query?methodMap.get("youtube.videos.list")?.scopes??[]:firstScopes,scopes=firstScopes.filter(scope=>detailScopes.includes(scope)),readonly="https://www.googleapis.com/auth/youtube.readonly";const requiredScope=scopes.includes(readonly)&&captured.scopes.includes(readonly)?readonly:scopes.find(scope=>captured.scopes.includes(scope));if(!requiredScope)return businessError("permission_denied","The selected YouTube query requires one of its pinned read scopes.","auth");const fence=async()=>{if(closed||signal.aborted)return aborted();const current=await vault.connection("youtube");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==captured.accountId||!current.ok.scopes.includes(requiredScope))return businessError("permission_denied","YouTube selected read connection or scope changed.","auth");return Original.ok(void 0)};const boundInvoke=async(id,input)=>{const before=await fence();if(!("ok"in before))return before;const answer2=await invoke(id,input,{signal});const after=await fence();return"ok"in after?answer2:after};const wanted=request.limit??1,params=request.fileId?{part:["snippet","contentDetails","status","statistics"],id:[request.fileId]}:request.query?{part:["snippet"],q:request.query,type:["video"],maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}}:{part:["snippet","contentDetails"],mine:true,maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}};let answer=await boundInvoke(selected,{params});if("err"in answer&&selected==="youtube.activities.list"&&answer.err.code==="permission_denied"){const channels=await boundInvoke("youtube.channels.list",{params:{part:["id"],mine:true,maxResults:1}});if("ok"in channels&&!channels.ok.items.length)return readResult("youtube",[],["This Google account has no YouTube channel, so it has no own activity to read; full sync records it as no-youtube-channel."])}if(!("ok"in answer))return answer;const items=[...answer.ok.items],seen=new Set;let steps=1;while(items.length<wanted&&answer.ok.nextPageToken){const token=answer.ok.nextPageToken;if(seen.has(token))return businessError("failed_precondition","Selected YouTube read repeated a token; no complete result was asserted.","connector");seen.add(token);if(++steps>100)return businessError("resource_exhausted","Selected YouTube read exceeded the page budget before satisfying its limit; no complete result was asserted.","connector");answer=await boundInvoke(selected,{params:{...params,pageToken:token}});if(!("ok"in answer))return answer;items.push(...answer.ok.items)}let retained=items.slice(0,wanted),resource=answer.ok.resource;if(request.query&&retained.length){const selectedItems=retained,details=[];for(let index=0;index<selectedItems.length;index+=50){const block=selectedItems.slice(index,index+50),ids=block.map(item=>object(item.id)?item.id.videoId:void 0).filter(id=>typeof id==="string");if(ids.length!==block.length)return businessError("data_loss","A selected YouTube video search result lacks its native video id.","connector");const hydrated=await boundInvoke("youtube.videos.list",{params:{part:["snippet","contentDetails","status","statistics","topicDetails","recordingDetails","localizations"],id:ids}});if(!("ok"in hydrated))return hydrated;for(const item of hydrated.ok.items)details.push({...item,_selection:block.find(selected2=>object(selected2.id)&&selected2.id.videoId===item.id)??null})}retained=details;resource="videos"}const records=retained.map(item=>({source:"youtube",sourceId:captured.accountId+":"+resource+":"+itemId(item),stream:resource,kind:"youtube."+resource.toLowerCase()+".changed",ts:itemTime(item),body:JSON.stringify(item),fields:{...item}}));const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;if(closed||signal.aborted)return aborted();return readResult("youtube",records,[...answer.ok.warnings,...answer.ok.nextPageToken||items.length>wanted?["More provider results exist beyond this selected batch."]:[],...retained.length<Math.min(items.length,wanted)?["Some selected videos are currently inaccessible/deleted; search metadata is retained only as an attributed missing detail, never a fabricated video body."]:[],"This selected API query does not establish complete YouTube account or archive coverage."])}function read(request,options={}){return track(readInner(request,options))}async function importTakeout(root=takeoutRoot??"",options={}){if(closed)return unavailable();if(!root)return businessError("failed_precondition","Supply an explicit extracted read-only Takeout copy; API success cannot substitute for history.","connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;const result=await readTakeout(root,signal);if(!("ok"in result))return result;if(closed||signal.aborted)return aborted();const saved=await cache(vault,"youtube",result.ok.records);if(!("ok"in saved))return saved;return result}const account=async()=>{const row=await vault.connection("youtube");if(!("ok"in row))return row;if(!row.ok||row.ok.state!=="connected")return businessError("unauthenticated","YouTube identity needs a connected account.","auth");if(!row.ok.accountId)return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");return Original.ok(row.ok.accountId)};function actionSchema(schema){const{id:_discoveryType,...result}=schema;if(result.properties)result.properties=Object.fromEntries(Object.entries(result.properties).map(([key,value])=>[key,actionSchema(value)]));if(result.items)result.items=actionSchema(result.items);if(object(result.additionalProperties))result.additionalProperties=actionSchema(result.additionalProperties);return result}const actions={catalog,method:id=>{const result=method(id);if(!("ok"in result))return result;const m=result.ok;return Original.ok({...m,params:actionSchema(m.params),...!m.supportsMediaUpload&&m.id!=="youtube.youtube.v3.liveChat.messages.stream"&&(!m.profile||m.httpMethod==="GET")?{level:1,effect:m.httpMethod==="GET"?"read":"write"}:{}})},invoke:(id,input,options={})=>invoke(id,input,options,true)};const source={info,actions,catalog,method,invoke,pages,read,status:()=>closed?Promise.resolve(Original.ok({...info,state:"unavailable",message:"YouTube source is inactive."})):connectionState(vault,info),connect:options=>closed?Promise.resolve(unavailable()):track(auth.connect("youtube",options)),job:id=>closed?unavailable():auth.job(id),cancelJob:id=>auth.cancelJob(id),importTakeout:(root,options)=>track(importTakeout(root,options)),createConnector:(plan,options={})=>createYouTubeConnector({parts,invoke,method,account,isClosed:()=>closed},plan,options),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}};return source}export function itemId(item){if(typeof item.id==="string")return item.id;if(typeof item.videoId==="string")return item.videoId;if(object(item.id)){for(const key of["videoId","channelId","playlistId"])if(typeof item.id[key]==="string")return key+":"+item.id[key]}const value=JSON.parse(JSON.stringify(item.id??item));return createHash("sha256").update(Original.jcsCanonicalize(value)).digest("hex")}export function itemTime(item){const snippet=object(item.snippet)?item.snippet:{};for(const value of[item.time,item.updated,item.updatedAt,snippet.updatedAt,snippet.publishedAt])if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return"1970-01-01T00:00:00.000Z"}
@@ -1 +1 @@
1
- import{readGalaxySnapshot,withFileCatalog}from"./snapshot.js";import{readFileCatalog}from"./file-catalog.js";import{galaxyRoute}from"./routes.js";import{startGalaxyServer,LOOPBACK_HOSTS}from"./server.js";import{producePortrait}from"./portrait-producer.js";import{configuredSourceIds,connectionStates,progressStates,supportStates}from"./original-adapter.js";import{readSyncProgress}from"./sync-progress.js";export{readGalaxySnapshot}from"./snapshot.js";export{readSyncProgress}from"./sync-progress.js";export{localizer,localizerScript,LANGUAGE_KEY}from"./localizer.js";export const name="zortex-galaxy-ui";export const inject=["zortexSqliteVault"];const releaseVersion=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.]{1,40})?$/;const SYNC_READ_MS=4e3;export async function apply(ctx,config={}){const host=config?.host??"127.0.0.1",port=config?.port??0;if(!LOOPBACK_HOSTS.includes(host))throw Error("Galaxy listens on a loopback address only.");if(!Number.isSafeInteger(port)||port<0||port>65535)throw Error("Galaxy port must be 0-65535.");const productVersion=typeof config?.productVersion==="string"&&releaseVersion.test(config.productVersion)?config.productVersion:null;const lifetime=new AbortController;const service=name2=>ctx.get(name2);const fileReader=()=>config.computerFiles??(config.snapshotReader?void 0:service("zortexComputerFiles"));const readSnapshot=config.snapshotReader??(()=>{const computerFiles=fileReader();return readGalaxySnapshot(ctx.zortexSqliteVault,()=>new Date,{...computerFiles?{computerFiles}:{},signal:lifetime.signal})});const unavailableSnapshot=()=>({version:1,status:"unavailable",generatedAt:new Date().toISOString(),totalItems:0,first:null,latest:null,sources:[],daily:[],hourly:[],sourceDays:[],records:[]});let snapshot=config.snapshotReader?await readSnapshot().catch(()=>unavailableSnapshot()):await readSnapshot();const currentSnapshot=async()=>{const reader=fileReader();return reader||!config.snapshotReader&&snapshot.fileCatalog?withFileCatalog(snapshot,await readFileCatalog(reader,lifetime.signal)):snapshot};let portrait={state:"unavailable",reason:"cached_vectors_unavailable"};const analyze=value=>config.snapshotReader?Promise.resolve({state:"unavailable",reason:"cached_vectors_unavailable"}):producePortrait(ctx.zortexSqliteVault,value,service("zortexGeminiSearch"),lifetime.signal);const configuredSources=configuredSourceIds(config.configuredSources);const installed=async()=>{if(config.sourceInventory){try{const value=await config.sourceInventory();return Array.isArray(value)?connectionStates(value.filter(row=>row?.configuration!=="required")):null}catch{return null}}if(config.snapshotReader&&!config.connectionStatus)return null;if(config.connectionStatus){try{const value=await config.connectionStatus();return Array.isArray(value)?connectionStates(value):null}catch{return null}}const hub=service("zortexConnectorHub");try{const value=(await hub?.status())?.ok;return Array.isArray(value)?connectionStates(value):null}catch{return null}};const progress=async()=>{if(config.sourceProgress){try{return progressStates(await config.sourceProgress())}catch{return[]}}if(config.snapshotReader)return[];const fleet=service("indraFleet");try{return progressStates((await fleet?.status())?.sources)}catch{return[]}};const support=async()=>{try{return supportStates(await config.sourceSupport?.())}catch{return[]}};let active=true;let syncRead;const syncProgress=async()=>{if(!active||config.snapshotReader)return void 0;if(!syncRead||Date.now()-syncRead.at>=SYNC_READ_MS)syncRead={at:Date.now(),value:readSyncProgress(ctx.zortexSqliteVault,{journal:service("zortexConnectorProcessJournal"),scheduler:service("indraSourceSync"),signal:lifetime.signal})};return syncRead.value};const route=await galaxyRoute(currentSnapshot,installed,productVersion,async durationMs=>{const telemetry=service("zortexTelemetry");const current=await currentSnapshot();await telemetry?.record({operation:"product.galaxy_opened",outcome:"ok",durationMs,code:current.coverageNote?.providerCache==="unavailable"||current.coverageNote?.bounded||current.fileCatalog?.partial||current.fileCatalog?.sampled||current.fileCatalog?.state==="unavailable"?"live_local_partial":"live_local"}).catch(()=>void 0)},configuredSources,progress,()=>portrait,syncProgress,configuredSourceIds(config.directorySources??config.catalogSources),support,config.openConnection,service("zortexProductAccount"),config.connectionRequest);const page=await startGalaxyServer(route,{host,port,entry:"/zortex-galaxy/app.html"});ctx.effect(()=>()=>page.close(),`${name}: local page server`);ctx.reflect.provide("zortexGalaxyPage",{url:page.url,origin:page.origin,port:page.port});ctx.reflect.provide("zortexGalaxyReader",page.reader);if(config?.announce===true)ctx.logger.info("Galaxy page: %s",page.url);let readAt=Date.now(),pending;const refresh=()=>pending??=(async()=>{try{const next=await readSnapshot();if(!active)return;const measured=await analyze(next);if(active){snapshot=next;portrait=measured;readAt=Date.now()}}catch{if(active)snapshot={...snapshot,status:"unavailable"}}finally{pending=void 0}})();void refresh();const timer=setInterval(()=>{if(snapshot.status==="unavailable"||Date.now()-readAt>=6e4)void refresh()},5e3);timer.unref();ctx.effect(()=>()=>{active=false;lifetime.abort();clearInterval(timer)},`${name}: aggregate refresh`)}
1
+ import{readGalaxySnapshot,withFileCatalog}from"./snapshot.js";import{readFileCatalog}from"./file-catalog.js";import{galaxyRoute}from"./routes.js";import{startGalaxyServer,LOOPBACK_HOSTS}from"./server.js";import{producePortrait}from"./portrait-producer.js";import{configuredSourceIds,connectionStates,progressStates,supportStates}from"./original-adapter.js";import{readSyncProgress}from"./sync-progress.js";export{readGalaxySnapshot}from"./snapshot.js";export{readSyncProgress}from"./sync-progress.js";export{localizer,localizerScript,LANGUAGE_KEY}from"./localizer.js";export const name="zortex-galaxy-ui";export const inject=["zortexSqliteVault"];const releaseVersion=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.]{1,40})?$/;const SYNC_READ_MS=4e3;export async function apply(ctx,config={}){const host=config?.host??"127.0.0.1",port=config?.port??0;if(!LOOPBACK_HOSTS.includes(host))throw Error("Galaxy listens on a loopback address only.");if(!Number.isSafeInteger(port)||port<0||port>65535)throw Error("Galaxy port must be 0-65535.");const productVersion=typeof config?.productVersion==="string"&&releaseVersion.test(config.productVersion)?config.productVersion:null;const lifetime=new AbortController;const service=name2=>ctx.get(name2);const fileReader=()=>config.computerFiles??(config.snapshotReader?void 0:service("zortexComputerFiles"));const readSnapshot=config.snapshotReader??(()=>{const computerFiles=fileReader();return readGalaxySnapshot(ctx.zortexSqliteVault,()=>new Date,{...computerFiles?{computerFiles}:{},signal:lifetime.signal})});const unavailableSnapshot=()=>({version:1,status:"unavailable",generatedAt:new Date().toISOString(),totalItems:0,first:null,latest:null,sources:[],daily:[],hourly:[],sourceDays:[],records:[]});let snapshot=config.snapshotReader?await readSnapshot().catch(()=>unavailableSnapshot()):await readSnapshot();const currentSnapshot=async()=>{const reader=fileReader();return reader||!config.snapshotReader&&snapshot.fileCatalog?withFileCatalog(snapshot,await readFileCatalog(reader,lifetime.signal)):snapshot};let portrait={state:"unavailable",reason:"cached_vectors_unavailable"};const analyze=value=>config.snapshotReader?Promise.resolve({state:"unavailable",reason:"cached_vectors_unavailable"}):producePortrait(ctx.zortexSqliteVault,value,service("zortexGeminiSearch"),lifetime.signal);const configuredSources=configuredSourceIds(config.configuredSources);const installed=async()=>{if(config.sourceInventory){try{const value=await config.sourceInventory();return Array.isArray(value)?connectionStates(value.filter(row=>row?.configuration!=="required")):null}catch{return null}}if(config.snapshotReader&&!config.connectionStatus)return null;if(config.connectionStatus){try{const value=await config.connectionStatus();return Array.isArray(value)?connectionStates(value):null}catch{return null}}const hub=service("zortexConnectorHub");try{const value=(await hub?.status())?.ok;return Array.isArray(value)?connectionStates(value):null}catch{return null}};const progress=async()=>{if(config.sourceProgress){try{return progressStates(await config.sourceProgress())}catch{return[]}}if(config.snapshotReader)return[];const fleet=service("indraFleet");try{return progressStates((await fleet?.status())?.sources)}catch{return[]}};const support=async()=>{try{return supportStates(await config.sourceSupport?.())}catch{return[]}};let active=true;let syncRead;const syncProgress=async()=>{if(!active||config.snapshotReader)return void 0;if(!syncRead||Date.now()-syncRead.at>=SYNC_READ_MS)syncRead={at:Date.now(),value:readSyncProgress(ctx.zortexSqliteVault,{journal:service("zortexConnectorProcessJournal"),scheduler:service("indraSourceSync"),signal:lifetime.signal})};return syncRead.value};const route=await galaxyRoute(currentSnapshot,installed,productVersion,async durationMs=>{const telemetry=service("zortexTelemetry");const current=await currentSnapshot();await telemetry?.record({operation:"product.galaxy_opened",outcome:"ok",durationMs,code:current.coverageNote?.partial||current.coverageNote?.providerCache==="unavailable"||current.coverageNote?.bounded||current.fileCatalog?.partial||current.fileCatalog?.sampled||current.fileCatalog?.state==="unavailable"?"live_local_partial":"live_local"}).catch(()=>void 0)},configuredSources,progress,()=>portrait,syncProgress,configuredSourceIds(config.directorySources??config.catalogSources),support,config.openConnection,service("zortexProductAccount"),config.connectionRequest);const page=await startGalaxyServer(route,{host,port,entry:"/zortex-galaxy/app.html"});ctx.effect(()=>()=>page.close(),`${name}: local page server`);ctx.reflect.provide("zortexGalaxyPage",{url:page.url,origin:page.origin,port:page.port});ctx.reflect.provide("zortexGalaxyReader",page.reader);if(config?.announce===true)ctx.logger.info("Galaxy page: %s",page.url);let readAt=Date.now(),pending;const refresh=()=>pending??=(async()=>{try{const next=await readSnapshot();if(!active)return;const measured=await analyze(next);if(active){snapshot=next;portrait=measured;readAt=Date.now()}}catch{if(active)snapshot={...snapshot,status:"unavailable"}}finally{pending=void 0}})();void refresh();const timer=setInterval(()=>{if(snapshot.status==="unavailable"||Date.now()-readAt>=6e4)void refresh()},5e3);timer.unref();ctx.effect(()=>()=>{active=false;lifetime.abort();clearInterval(timer)},`${name}: aggregate refresh`)}
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{Worker}from"node:worker_threads";const LIMIT=2e4,VECTOR_LIMIT=256;const key=(source,id)=>createHash("sha256").update(`${source}\0${id}`).digest("hex");const flags=(payload,source,kind,body)=>{const j=path=>`COALESCE(json_extract(${payload}, '$.${path}'), json_extract(${payload}, '$.fields.${path}'))`;const note=`(${source}='apple-notes' AND ${kind}='note.changed')`;const drive=`(${source}='google-drive' AND ${j("lastModifyingUser.me")}=1 AND COALESCE(${j("trashed")},0)=0 AND (${j("mimeType")} LIKE 'text/%' OR ${j("mimeType")} IN ('application/vnd.google-apps.document','application/vnd.google-apps.spreadsheet','application/vnd.google-apps.presentation','application/pdf')))`;const openai=`(${source} IN ('openai','chatgpt') AND ${j("message.author.role")}='user')`;const speech=`((${source}='gmail' AND ${j("labelIds")} LIKE '%"SENT"%') OR (${source}='imessage' AND ${j("isFromMe")}=1 AND length(${body})>=80) OR (${source}='wechat' AND ${j("direction")}=1 AND ${j("type")}=1 AND length(${body})>=80))`;const knowledge=`(${note} OR ${drive} OR ${openai})`;return`CASE WHEN ${knowledge} OR ${speech} THEN 1 ELSE 0 END AS authored, CASE WHEN ${knowledge} THEN 1 ELSE 0 END AS knowledge`};export async function readAuthoredMetadata(vault){const records=[];let scanned=0,pages=0;const deadline=Date.now()+1e4;for(const cache of[false,true]){let cursor="";for(;;){if(++pages>40||Date.now()>deadline)return{records,bounded:true};const table=cache?"connector_records":"events",id=cache?"r.source || ':' || r.source_id":"r.id";const sql=`SELECT ${id} AS cursor, ${id} AS id, r.source,r.source_id,r.ts,${flags("r.payload","r.source",cache?"json_extract(r.payload,'$.kind')":"r.kind","r.body")} FROM ${table} r WHERE (${id}) > ? ${cache?"":"AND r.erased=0 AND r.tomb IS NULL"} AND NOT EXISTS (SELECT 1 FROM events x WHERE x.source=r.source AND x.source_id=r.source_id AND (x.erased<>0 OR x.tomb IS NOT NULL)) ORDER BY cursor LIMIT 500`;const result=await vault.sql({sql,params:[cursor],timeoutMs:3e3});if(!("ok"in result))return void 0;const page=result.ok.rows;scanned+=page.length;for(const row of page){if(typeof row.id!=="string"||typeof row.source!=="string"||typeof row.source_id!=="string"||typeof row.ts!=="string"||!Number.isFinite(Date.parse(row.ts)))continue;records.push({id:row.id,key:key(row.source,row.source_id),source:row.source,time:new Date(row.ts).toISOString(),authored:row.authored===1,knowledge:row.knowledge===1})}if(scanned>=LIMIT)return{records:records.slice(0,LIMIT),bounded:true};if(page.length<500)break;const next=page.at(-1)?.cursor;if(typeof next!=="string"||next<=cursor)return void 0;cursor=next}}return{records,bounded:false}}export async function producePortrait(vault,snapshot,reader,signal){if(signal?.aborted)return{state:"unavailable",reason:"local_analysis_failed"};if(!reader||typeof reader.cachedVectors!=="function")return{state:"unavailable",reason:"cached_vectors_unavailable"};try{const metadata=await readAuthoredMetadata(vault);if(signal?.aborted)return{state:"unavailable",reason:"local_analysis_failed"};if(!metadata)return{state:"unavailable",reason:"metadata_unavailable"};const eligible=new Set(metadata.records.filter(r=>r.knowledge).map(r=>r.id)),vectors=[];let after,pages=0,bounded=metadata.bounded;const seen=new Set,vectorIds=new Set,deadline=Date.now()+1e4;do{if(++pages>200||Date.now()>deadline){bounded=true;break}const page=await reader.cachedVectors({...after?{after}:{},limit:100});if(signal?.aborted)return{state:"unavailable",reason:"local_analysis_failed"};if(!("ok"in page))return{state:"unavailable",reason:"cached_vectors_unavailable"};for(const row of page.ok.rows){if(eligible.has(row.record)&&!vectorIds.has(row.record)&&vectors.length<VECTOR_LIMIT){vectorIds.add(row.record);vectors.push({record:row.record,vector:row.vector})}}const next=page.ok.next;if(next&&(seen.has(next)||after!==void 0&&next<=after))return{state:"unavailable",reason:"cached_vectors_unavailable"};if(next)seen.add(next);after=next;if(vectors.length>=VECTOR_LIMIT){bounded=true;break}}while(after);if(vectors.length<4)return{state:"unavailable",reason:"insufficient_authored_vectors"};return await new Promise(resolve=>{const worker=new Worker(new URL("./portrait-worker.js",import.meta.url),{workerData:{snapshot,records:metadata.records,vectors,bounded}});let done=false;const finish=value=>{if(done)return;done=true;clearTimeout(timer);signal?.removeEventListener("abort",abort);void worker.terminate();resolve(value)};const abort=()=>finish({state:"unavailable",reason:"local_analysis_failed"});const timer=setTimeout(()=>finish({state:"unavailable",reason:"local_analysis_failed"}),3e4);signal?.addEventListener("abort",abort,{once:true});worker.once("message",portrait=>finish(portrait?{state:"measured-subset",portrait}:{state:"unavailable",reason:"insufficient_authored_vectors"}));worker.once("error",()=>finish({state:"unavailable",reason:"local_analysis_failed"}));worker.once("exit",()=>finish({state:"unavailable",reason:"local_analysis_failed"}))})}catch{return{state:"unavailable",reason:"local_analysis_failed"}}}
1
+ import{recordKey,providerCacheTable,liveIdentity}from"./record-identity.js";import{Worker}from"node:worker_threads";const LIMIT=2e4,VECTOR_LIMIT=256;const flags=(payload,source,kind,body)=>{const j=path=>`COALESCE(json_extract(${payload}, '$.${path}'), json_extract(${payload}, '$.fields.${path}'))`;const note=`(${source}='apple-notes' AND ${kind}='note.changed')`;const drive=`(${source}='google-drive' AND ${j("lastModifyingUser.me")}=1 AND COALESCE(${j("trashed")},0)=0 AND (${j("mimeType")} LIKE 'text/%' OR ${j("mimeType")} IN ('application/vnd.google-apps.document','application/vnd.google-apps.spreadsheet','application/vnd.google-apps.presentation','application/pdf')))`;const openai=`(${source} IN ('openai','chatgpt') AND ${j("message.author.role")}='user')`;const speech=`((${source}='gmail' AND ${j("labelIds")} LIKE '%"SENT"%') OR (${source}='imessage' AND ${j("isFromMe")}=1 AND length(${body})>=80) OR (${source}='wechat' AND ${j("direction")}=1 AND ${j("type")}=1 AND length(${body})>=80))`;const knowledge=`(${note} OR ${drive} OR ${openai})`;return`CASE WHEN ${knowledge} OR ${speech} THEN 1 ELSE 0 END AS authored, CASE WHEN ${knowledge} THEN 1 ELSE 0 END AS knowledge`};export async function readAuthoredMetadata(vault){const records=[];let scanned=0,pages=0,ambiguousCache=false;const deadline=Date.now()+1e4;for(const cache of[false,true]){let cursor="";for(;;){if(++pages>40||Date.now()>deadline)return{records,bounded:true};const table=cache?providerCacheTable:"events",id=cache?"r.source || ':' || r.source_id":"r.id";const sql=`SELECT ${id} AS cursor, ${id} AS id, r.source,r.stream,r.source_id,r.ts,${cache?"r.identity_ambiguous,":""}${flags("r.payload","r.source",cache?"json_extract(r.payload,'$.kind')":"r.kind","r.body")} FROM ${table} r WHERE (${id}) > ? ${cache?"":"AND r.erased=0 AND r.tomb IS NULL"} AND ${liveIdentity("r")} ORDER BY cursor LIMIT 500`;const result=await vault.sql({sql,params:[cursor],timeoutMs:3e3});if(!("ok"in result))return void 0;const page=result.ok.rows;scanned+=page.length;for(const row of page){if(cache&&row.identity_ambiguous===1){ambiguousCache=true;continue}if(typeof row.id!=="string"||typeof row.source!=="string"||typeof row.source_id!=="string"||typeof row.ts!=="string"||!Number.isFinite(Date.parse(row.ts)))continue;if(!cache&&typeof row.stream!=="string")continue;records.push({id:row.id,key:recordKey(row.source,typeof row.stream==="string"?row.stream:null,row.source_id),source:row.source,time:new Date(row.ts).toISOString(),authored:row.authored===1,knowledge:row.knowledge===1})}if(scanned>=LIMIT)return{records:records.slice(0,LIMIT),bounded:true};if(page.length<500)break;const next=page.at(-1)?.cursor;if(typeof next!=="string"||next<=cursor)return void 0;cursor=next}}return{records,bounded:ambiguousCache}}export async function producePortrait(vault,snapshot,reader,signal){if(signal?.aborted)return{state:"unavailable",reason:"local_analysis_failed"};if(!reader||typeof reader.cachedVectors!=="function")return{state:"unavailable",reason:"cached_vectors_unavailable"};try{const metadata=await readAuthoredMetadata(vault);if(signal?.aborted)return{state:"unavailable",reason:"local_analysis_failed"};if(!metadata)return{state:"unavailable",reason:"metadata_unavailable"};const eligible=new Set(metadata.records.filter(r=>r.knowledge).map(r=>r.id)),vectors=[];let after,pages=0,bounded=metadata.bounded;const seen=new Set,vectorIds=new Set,deadline=Date.now()+1e4;do{if(++pages>200||Date.now()>deadline){bounded=true;break}const page=await reader.cachedVectors({...after?{after}:{},limit:100});if(signal?.aborted)return{state:"unavailable",reason:"local_analysis_failed"};if(!("ok"in page))return{state:"unavailable",reason:"cached_vectors_unavailable"};for(const row of page.ok.rows){if(eligible.has(row.record)&&!vectorIds.has(row.record)&&vectors.length<VECTOR_LIMIT){vectorIds.add(row.record);vectors.push({record:row.record,vector:row.vector})}}const next=page.ok.next;if(next&&(seen.has(next)||after!==void 0&&next<=after))return{state:"unavailable",reason:"cached_vectors_unavailable"};if(next)seen.add(next);after=next;if(vectors.length>=VECTOR_LIMIT){bounded=true;break}}while(after);if(vectors.length<4)return{state:"unavailable",reason:"insufficient_authored_vectors"};return await new Promise(resolve=>{const worker=new Worker(new URL("./portrait-worker.js",import.meta.url),{workerData:{snapshot,records:metadata.records,vectors,bounded}});let done=false;const finish=value=>{if(done)return;done=true;clearTimeout(timer);signal?.removeEventListener("abort",abort);void worker.terminate();resolve(value)};const abort=()=>finish({state:"unavailable",reason:"local_analysis_failed"});const timer=setTimeout(()=>finish({state:"unavailable",reason:"local_analysis_failed"}),3e4);signal?.addEventListener("abort",abort,{once:true});worker.once("message",portrait=>finish(portrait?{state:"measured-subset",portrait}:{state:"unavailable",reason:"insufficient_authored_vectors"}));worker.once("error",()=>finish({state:"unavailable",reason:"local_analysis_failed"}));worker.once("exit",()=>finish({state:"unavailable",reason:"local_analysis_failed"}))})}catch{return{state:"unavailable",reason:"local_analysis_failed"}}}
@@ -0,0 +1,6 @@
1
+ import{createHash}from"node:crypto";export const recordKey=(source,stream,id)=>createHash("sha256").update(JSON.stringify(stream===null?["provider-cache",source,id]:["event",source,stream,id])).digest("hex");const explicitStream="json_type(c.payload,'$.stream')='text' AND length(json_extract(c.payload,'$.stream'))>0";export const providerCacheTable=`(SELECT c.*,
2
+ CASE WHEN ${explicitStream} THEN json_extract(c.payload,'$.stream') WHEN h.streams=1 THEN h.stream ELSE NULL END AS stream,
3
+ CASE WHEN ${explicitStream} THEN 0 ELSE COALESCE(h.streams,0)>1 END AS identity_ambiguous
4
+ FROM connector_records c LEFT JOIN
5
+ (SELECT source,source_id,MIN(stream) AS stream,COUNT(DISTINCT stream) AS streams FROM events GROUP BY source,source_id) h
6
+ ON h.source=c.source AND h.source_id=c.source_id)`;export const liveIdentity=alias=>`(${alias}.stream IS NULL OR (${alias}.source,${alias}.stream,${alias}.source_id) NOT IN (SELECT x.source,x.stream,x.source_id FROM events x WHERE x.erased<>0 OR x.tomb IS NOT NULL))`;
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{FILE_REFERENCE_LIMIT,readFileCatalog}from"./file-catalog.js";export const GALAXY_RECORD_LIMIT=2e4;const LIMIT=GALAXY_RECORD_LIMIT,PAGE=500;const date=v=>typeof v==="string"&&Number.isFinite(Date.parse(v))?new Date(v).toISOString():null;const empty=now=>({version:1,status:"unavailable",generatedAt:now().toISOString(),totalItems:0,first:null,latest:null,sources:[],daily:[],hourly:[],sourceDays:[],records:[]});function activityCounts(records){const sources=new Map,days=new Map,hours=new Map,sourceDays=new Map;for(const r of records){const prior=sources.get(r.source);sources.set(r.source,{source:r.source,items:(prior?.items??0)+1,first:prior?.first??r.time,latest:r.time??prior?.latest??null});if(!r.time)continue;const day=r.time.slice(0,10),hour=new Date(r.time).getUTCHours(),key=`${r.source}|${day}`;days.set(day,(days.get(day)??0)+1);hours.set(hour,(hours.get(hour)??0)+1);sourceDays.set(key,{source:r.source,day,items:(sourceDays.get(key)?.items??0)+1})}const times=records.flatMap(r=>r.time?[r.time]:[]);return{totalItems:records.length,first:times[0]??null,latest:times.at(-1)??null,sources:[...sources.values()].sort((a,b)=>b.items-a.items||a.source.localeCompare(b.source)),daily:[...days].map(([day,items])=>({day,items})),hourly:[...hours].sort(([a],[b])=>a-b).map(([hour,items])=>({hour,items})),sourceDays:[...sourceDays.values()].sort((a,b)=>a.day.localeCompare(b.day)||a.source.localeCompare(b.source))}}export function withFileCatalog(snapshot,fileCatalog){const limit=LIMIT-Math.min(FILE_REFERENCE_LIMIT,fileCatalog.records.length);if(snapshot.records&&snapshot.records.length>limit){const records=snapshot.records.slice(0,limit);snapshot={...snapshot,...activityCounts(records),records,...snapshot.coverageNote?{coverageNote:{...snapshot.coverageNote,bounded:true}}:{}}}const status=snapshot.totalItems||fileCatalog.records.length?"live-local":snapshot.coverageNote?.eventRecords==="unavailable"||fileCatalog.state==="unavailable"?"unavailable":"empty";return{...snapshot,status,fileCatalog}}export async function readGalaxySnapshot(vault,now=()=>new Date,options={}){const activityLimit=options.computerFiles?LIMIT-FILE_REFERENCE_LIMIT:LIMIT;const finish=async value=>options.computerFiles?withFileCatalog(value,await readFileCatalog(options.computerFiles,options.signal)):value;const failed=()=>finish({...empty(now),coverageNote:{bounded:false,scanned:0,limit:LIMIT,basis:"source-record-id",authored:"unverified",time:"record-timestamp",eventRecords:"unavailable",providerCache:"unavailable"}});const found=new Map;let scanned=0,bounded=false,providerCache="not-scanned";for(const origin of["event","provider-cache"]){let cursor="";for(;;){const sql=origin==="event"?`SELECT e.id AS cursor, e.source, e.source_id, e.ts FROM events e INDEXED BY sqlite_autoindex_events_1 WHERE e.erased=0 AND e.id > ? AND (e.source, e.source_id) NOT IN (SELECT x.source, x.source_id FROM events x WHERE x.erased<>0 OR x.tomb IS NOT NULL) ORDER BY e.id LIMIT 500`:`SELECT c.source || ':' || c.source_id AS cursor, c.source, c.source_id, c.ts FROM connector_records c WHERE (c.source || ':' || c.source_id) > ? AND (c.source, c.source_id) NOT IN (SELECT x.source, x.source_id FROM events x WHERE x.erased<>0 OR x.tomb IS NOT NULL) ORDER BY cursor LIMIT 500`;if(options.signal?.aborted)return failed();const result=await vault.sql({sql,params:[cursor],timeoutMs:3e3},options.signal);if(!("ok"in result)){if(origin==="provider-cache"&&"err"in result&&result.err.code==="invalid_argument"){providerCache="unavailable";break}return failed()}if(origin==="provider-cache")providerCache="read";const rows=result.ok.rows;for(const row of rows){if(scanned>=activityLimit){bounded=true;break}scanned++;if(typeof row.source!=="string"||!/^[a-z0-9][a-z0-9._-]{0,95}$/i.test(row.source)||typeof row.source_id!=="string")continue;const key=createHash("sha256").update(`${row.source}\0${row.source_id}`).digest("hex");const next={key,source:row.source,time:date(row.ts),origin},previous=found.get(key);if(!previous||(next.time??"")>(previous.time??""))found.set(key,next)}if(bounded)break;if(rows.length<PAGE)break;const nextCursor=rows.at(-1)?.cursor;if(typeof nextCursor!=="string"||nextCursor<=cursor)return failed();cursor=nextCursor;if(scanned>=activityLimit){bounded=true;break}}if(bounded)break}const inventoryResult=await vault.sql({sql:"SELECT count(*) AS storedRecords FROM z_records",params:[],timeoutMs:3e3},options.signal).catch(()=>null);const storedRecords=inventoryResult&&"ok"in inventoryResult?inventoryResult.ok.rows[0]?.storedRecords:void 0;const inventory=typeof storedRecords==="number"&&Number.isSafeInteger(storedRecords)&&storedRecords>=0?{storedRecords}:void 0;const records=[...found.values()].sort((a,b)=>(a.time??"").localeCompare(b.time??"")||a.key.localeCompare(b.key));return finish({...inventory?{inventory}:{},version:1,status:records.length?"live-local":"empty",generatedAt:now().toISOString(),...activityCounts(records),records,coverageNote:{bounded,scanned,limit:LIMIT,basis:"source-record-id",authored:"unverified",time:"record-timestamp",eventRecords:"read",providerCache,...providerCache==="unavailable"?{errorCode:"invalid_argument"}:{}}})}
1
+ import{recordKey,providerCacheTable,liveIdentity}from"./record-identity.js";import{FILE_REFERENCE_LIMIT,readFileCatalog}from"./file-catalog.js";export const GALAXY_RECORD_LIMIT=2e4;const LIMIT=GALAXY_RECORD_LIMIT,PAGE=500;const date=v=>typeof v==="string"&&Number.isFinite(Date.parse(v))?new Date(v).toISOString():null;const empty=now=>({version:1,status:"unavailable",generatedAt:now().toISOString(),totalItems:0,first:null,latest:null,sources:[],daily:[],hourly:[],sourceDays:[],records:[]});function activityCounts(records){const sources=new Map,days=new Map,hours=new Map,sourceDays=new Map;for(const r of records){const prior=sources.get(r.source);sources.set(r.source,{source:r.source,items:(prior?.items??0)+1,first:prior?.first??r.time,latest:r.time??prior?.latest??null});if(!r.time)continue;const day=r.time.slice(0,10),hour=new Date(r.time).getUTCHours(),key=`${r.source}|${day}`;days.set(day,(days.get(day)??0)+1);hours.set(hour,(hours.get(hour)??0)+1);sourceDays.set(key,{source:r.source,day,items:(sourceDays.get(key)?.items??0)+1})}const times=records.flatMap(r=>r.time?[r.time]:[]);return{totalItems:records.length,first:times[0]??null,latest:times.at(-1)??null,sources:[...sources.values()].sort((a,b)=>b.items-a.items||a.source.localeCompare(b.source)),daily:[...days].map(([day,items])=>({day,items})),hourly:[...hours].sort(([a],[b])=>a-b).map(([hour,items])=>({hour,items})),sourceDays:[...sourceDays.values()].sort((a,b)=>a.day.localeCompare(b.day)||a.source.localeCompare(b.source))}}export function withFileCatalog(snapshot,fileCatalog){const limit=LIMIT-Math.min(FILE_REFERENCE_LIMIT,fileCatalog.records.length);if(snapshot.records&&snapshot.records.length>limit){const records=snapshot.records.slice(0,limit);snapshot={...snapshot,...activityCounts(records),records,...snapshot.coverageNote?{coverageNote:{...snapshot.coverageNote,bounded:true,partial:true}}:{}}}const status=snapshot.totalItems||fileCatalog.records.length?"live-local":snapshot.coverageNote?.eventRecords==="unavailable"||fileCatalog.state==="unavailable"?"unavailable":"empty";return{...snapshot,status,fileCatalog}}export async function readGalaxySnapshot(vault,now=()=>new Date,options={}){const activityLimit=options.computerFiles?LIMIT-FILE_REFERENCE_LIMIT:LIMIT;const finish=async value=>options.computerFiles?withFileCatalog(value,await readFileCatalog(options.computerFiles,options.signal)):value;const failed=()=>finish({...empty(now),coverageNote:{bounded:false,scanned:0,limit:LIMIT,basis:"source-stream-record-id",authored:"unverified",time:"record-timestamp",partial:true,eventRecords:"unavailable",providerCache:"unavailable"}});const found=new Map;let scanned=0,bounded=false,ambiguousCacheRecords=0,providerCache="not-scanned";for(const origin of["event","provider-cache"]){let cursor="";for(;;){const sql=origin==="event"?`SELECT e.id AS cursor, e.source, e.stream, e.source_id, e.ts FROM events e INDEXED BY sqlite_autoindex_events_1 WHERE e.erased=0 AND e.id > ? AND ${liveIdentity("e")} ORDER BY e.id LIMIT 500`:`SELECT r.source || ':' || r.source_id AS cursor, r.source, r.stream, r.source_id, r.ts, r.identity_ambiguous FROM ${providerCacheTable} r WHERE (r.source || ':' || r.source_id) > ? AND ${liveIdentity("r")} ORDER BY cursor LIMIT 500`;if(options.signal?.aborted)return failed();const result=await vault.sql({sql,params:[cursor],timeoutMs:3e3},options.signal);if(!("ok"in result)){if(origin==="provider-cache"&&"err"in result&&result.err.code==="invalid_argument"){providerCache="unavailable";break}return failed()}if(origin==="provider-cache")providerCache="read";const rows=result.ok.rows;for(const row of rows){if(scanned>=activityLimit){bounded=true;break}scanned++;if(origin==="provider-cache"&&row.identity_ambiguous===1){ambiguousCacheRecords++;continue}if(typeof row.source!=="string"||!/^[a-z0-9][a-z0-9._-]{0,95}$/i.test(row.source)||typeof row.source_id!=="string")continue;if(origin==="event"&&typeof row.stream!=="string")continue;const key=recordKey(row.source,typeof row.stream==="string"?row.stream:null,row.source_id);const next={key,source:row.source,time:date(row.ts),origin},previous=found.get(key);if(!previous||(next.time??"")>(previous.time??""))found.set(key,next)}if(bounded)break;if(rows.length<PAGE)break;const nextCursor=rows.at(-1)?.cursor;if(typeof nextCursor!=="string"||nextCursor<=cursor)return failed();cursor=nextCursor;if(scanned>=activityLimit){bounded=true;break}}if(bounded)break}const inventoryResult=await vault.sql({sql:"SELECT count(*) AS storedRecords FROM z_records",params:[],timeoutMs:3e3},options.signal).catch(()=>null);const storedRecords=inventoryResult&&"ok"in inventoryResult?inventoryResult.ok.rows[0]?.storedRecords:void 0;const inventory=typeof storedRecords==="number"&&Number.isSafeInteger(storedRecords)&&storedRecords>=0?{storedRecords}:void 0;const records=[...found.values()].sort((a,b)=>(a.time??"").localeCompare(b.time??"")||a.key.localeCompare(b.key));return finish({...inventory?{inventory}:{},version:1,status:records.length?"live-local":"empty",generatedAt:now().toISOString(),...activityCounts(records),records,coverageNote:{bounded,scanned,limit:LIMIT,basis:"source-stream-record-id",authored:"unverified",time:"record-timestamp",partial:bounded||providerCache==="unavailable"||ambiguousCacheRecords>0,ambiguousCacheRecords,eventRecords:"read",providerCache,...providerCache==="unavailable"?{errorCode:"invalid_argument"}:{}}})}
@@ -1 +1 @@
1
- export const ANALYTICS_CONTRACT_VERSION="indra-activity-v1";const activities={search:["vault.search","Search local data"],context:["vault.context","Build context from local data"],sql:["vault.query","Query local data"],action:["connector.action","Run a product action"],actions:["connector.actions_list","Browse available actions"],action_result:["agent.action_result","Report an action result"],append:["vault.append","Append local data"],feedback:["agent.feedback","Report agent feedback"],manage:["product.manage","Manage the product"],done:["agent.turn_finished","Finish an agent turn"],instruction:["product.instructions","Read product instructions"],handbook:["product.handbook","Read the product handbook"],"mcp.call":["tool.call","Call a product tool"],"product.first_start":["installation.first_observed","Observe an installation for the first time"],"product.started":["product.started","Start the product"],"product.account_signed_in":["account.signed_in","Sign in to a product account"],"product.galaxy_opened":["product.galaxy_opened","Open Galaxy"],"product.feedback":["product.feedback_submitted","Submit feedback about an operation"],"product.trace":["operation.step","Observe an operational step"],"product.resources":["diagnostics.resources","Measure local resource usage"],"product.collection":["diagnostics.collection","Measure telemetry collection health"],"connector.trace":["connector.connection_step","Observe a connector step"],"connector.read":["connector.read","Read connector data"],"connector.invoke":["connector.invoke","Run a connector action"],"connector.connect":["connector.connect_requested","Request a source connection"],"connector.authorization":["connector.authorization_finished","Finish source authorization"],"connector.fabricate":["connector.fabricate","Build a connector"],"connector.usable":["connector.availability","Observe connector availability"],"connector.sync":["connector.sync","Synchronize connector data"],"connector.inventory":["diagnostics.data_inventory","Observe stored data counts"],"connector.connection":["diagnostics.connection_inventory","Observe saved connection permissions"],"flywheel.start":["automation.started","Start an automation run"],"flywheel.run":["automation.finished","Finish an automation run"]};const connectorStepLabels={source_selected:"Observe a source selection",authorization_started:"Observe source authorization",browser_opened:"Observe an authorization browser",waiting_for_user:"Observe authorization waiting for input",callback_received:"Observe an authorization callback",token_exchange:"Observe an authorization token exchange",identity_verified:"Observe source identity verification",credentials_saved:"Observe source credential storage",page_observed:"Observe an authorization page",action_selected:"Observe an authorization action selection",action_executed:"Observe an authorization action result",manual_required:"Observe an authorization handoff",automation_finished:"Observe authorization automation results",authorization_finished:"Observe a source authorization result",read_started:"Start reading connector data",read_verified:"Observe a connector read result",invoke_started:"Start a connector action",invoke_finished:"Observe a connector action result",vault_saved:"Observe local data storage",startup_failed:"Observe a product startup failure"};const primary=new Set(["search","context","sql","action","actions","append","manage","instruction","handbook","mcp.call","connector.fabricate"]);const connectorOperations=new Set(["connector.read","connector.invoke","connector.sync"]);const lifecycle=new Set(["product.first_start","product.started","product.account_signed_in","product.galaxy_opened","connector.connect","connector.authorization","flywheel.start","flywheel.run"]);export function activityProperties(operation,event,trace){const activity=Object.hasOwn(activities,operation)?activities[operation]:void 0;if(!activity)return{};const role=event==="zortex call timing"?"operation_timing":primary.has(operation)?"primary_operation":connectorOperations.has(operation)?"connector_operation":lifecycle.has(operation)?"lifecycle":"diagnostic";const label=operation==="connector.trace"&&trace&&Object.hasOwn(connectorStepLabels,trace.stage)?connectorStepLabels[trace.stage]:activity[1];return{analytics_contract_version:ANALYTICS_CONTRACT_VERSION,analytics_activity:activity[0],analytics_activity_label:label,analytics_event_role:role}}
1
+ export const ANALYTICS_CONTRACT_VERSION="indra-activity-v1";const activities={search:["vault.search","Search local data"],context:["vault.context","Build context from local data"],sql:["vault.query","Query local data"],action:["connector.action","Run a product action"],actions:["connector.actions_list","Browse available actions"],action_result:["agent.action_result","Report an action result"],append:["vault.append","Append local data"],feedback:["agent.feedback","Report agent feedback"],manage:["product.manage","Manage the product"],done:["agent.turn_finished","Finish an agent turn"],instruction:["product.instructions","Read product instructions"],handbook:["product.handbook","Read the product handbook"],"mcp.call":["tool.call","Call a product tool"],"product.first_start":["installation.first_observed","Observe an installation for the first time"],"product.started":["product.started","Start the product"],"product.account_signed_in":["account.signed_in","Sign in to a product account"],"product.galaxy_opened":["product.galaxy_opened","Open Galaxy"],"product.feedback":["product.feedback_submitted","Submit feedback about an operation"],"product.trace":["operation.step","Observe an operational step"],"product.resources":["diagnostics.resources","Measure local resource usage"],"product.collection":["diagnostics.collection","Measure telemetry collection health"],"connector.trace":["connector.connection_step","Observe a connector step"],"connector.read":["connector.read","Read connector data"],"connector.invoke":["connector.invoke","Run a connector action"],"connector.connect":["connector.connect_requested","Request a source connection"],"connector.authorization":["connector.authorization_finished","Finish source authorization"],"connector.fabricate":["connector.fabricate","Build a connector"],"connector.usable":["connector.availability","Observe connector availability"],"connector.sync":["connector.sync","Synchronize connector data"],"connector.inventory":["diagnostics.data_inventory","Observe stored data counts"],"connector.connection":["diagnostics.connection_inventory","Observe saved connection permissions"],"flywheel.start":["automation.started","Start an automation run"],"flywheel.run":["automation.finished","Finish an automation run"]};const connectorStepLabels={source_selected:"Observe a source selection",authorization_started:"Observe source authorization",browser_opened:"Observe an authorization browser",waiting_for_user:"Observe authorization waiting for input",callback_received:"Observe an authorization callback",token_exchange:"Observe an authorization token exchange",identity_verified:"Observe source identity verification",credentials_saved:"Observe source credential storage",page_observed:"Observe an authorization page",action_selected:"Observe an authorization action selection",action_executed:"Observe an authorization action result",manual_required:"Observe an authorization handoff",automation_finished:"Observe authorization automation results",authorization_finished:"Observe a source authorization result",read_started:"Start reading connector data",read_verified:"Observe a connector read result",invoke_started:"Start a connector action",invoke_finished:"Observe a connector action result",vault_saved:"Observe local data storage",startup_failed:"Observe a product startup failure"};const primary=new Set(["search","context","sql","action","actions","append","manage","instruction","handbook","mcp.call","connector.fabricate"]);const connectorOperations=new Set(["connector.read","connector.invoke","connector.sync"]);const lifecycle=new Set(["product.first_start","product.started","product.account_signed_in","product.galaxy_opened","connector.connect","connector.authorization","flywheel.start","flywheel.run"]);export function activityProperties(operation,event,trace,code){const contentFind=operation==="action"&&code==="content_find";const activity=contentFind?activities.search:Object.hasOwn(activities,operation)?activities[operation]:void 0;if(!activity)return{};const role=event==="zortex call timing"?"operation_timing":primary.has(operation)?"primary_operation":connectorOperations.has(operation)?"connector_operation":lifecycle.has(operation)?"lifecycle":"diagnostic";const label=contentFind?"Find content":operation==="connector.trace"&&trace&&Object.hasOwn(connectorStepLabels,trace.stage)?connectorStepLabels[trace.stage]:activity[1];return{analytics_contract_version:ANALYTICS_CONTRACT_VERSION,analytics_activity:activity[0],analytics_activity_label:label,analytics_event_role:role}}