@zortexhq/indra-v2.5 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +93 -152
  2. package/dist/auto-update.js +1 -1
  3. package/dist/bundled-handbook.js +1 -1
  4. package/dist/cli-run.js +1 -1
  5. package/dist/cli.js +1 -1
  6. package/dist/codex-install.js +1 -1
  7. package/dist/codex-setup.js +1 -1
  8. package/dist/gateway.js +1 -1
  9. package/dist/mcp.js +2 -2
  10. package/dist/onboard-cli.js +1 -0
  11. package/dist/onboard.js +1 -0
  12. package/dist/operation-telemetry.js +1 -1
  13. package/dist/public-tool.js +1 -1
  14. package/dist/recovery-resident-port.js +1 -0
  15. package/dist/resident-host.js +2 -2
  16. package/dist/resident-jobs.js +1 -1
  17. package/dist/resident-platform.js +3 -3
  18. package/dist/resident-runtime-identity.js +1 -1
  19. package/dist/resident-shutdown.js +1 -0
  20. package/dist/resident-startup-preference.js +1 -0
  21. package/dist/resident-telemetry.js +1 -1
  22. package/dist/update-cli.js +1 -1
  23. package/dist/update-command.js +1 -0
  24. package/dist/update-handover.js +1 -0
  25. package/dist/update-recovery.js +1 -1
  26. package/dist/update-tool.js +1 -1
  27. package/dist/web.js +1 -1
  28. package/dist/zortex-cli.js +1 -1
  29. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  30. package/node_modules/@zortexhq/plugin-connector-level1/dist/operational-client.js +1 -1
  31. package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-graph.js +1 -1
  32. package/node_modules/@zortexhq/plugin-connector-level1/dist/service-sdk-matrix.js +1 -1
  33. package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
  34. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
  35. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/portrait-producer.js +1 -1
  36. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/record-identity.js +6 -0
  37. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/snapshot.js +1 -1
  38. package/node_modules/@zortexhq/plugin-posthog/dist/activity.js +1 -1
  39. package/node_modules/@zortexhq/plugin-posthog/dist/northstar.js +1 -1
  40. package/node_modules/@zortexhq/plugin-telemetry/dist/api/measurement.js +1 -1
  41. package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
  42. package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
  43. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-call.js +1 -1
  44. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-methods.js +1 -1
  45. package/node_modules/@zortexhq/plugin-telemetry/dist/index.js +1 -1
  46. package/package.json +7 -7
  47. package/release-provenance.json +16 -16
  48. package/update-manifest.json +143 -95
@@ -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}}
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{AUTHORIZATION_REASON_CODES,TELEMETRY_OPERATIONS,FEEDBACK_OPERATIONS,FEEDBACK_RATINGS,FEEDBACK_REASONS,FEEDBACK_CHANNELS,USAGE_ERROR_CATEGORIES,isFlowId,isUsageTrace}from"@zortexhq/plugin-telemetry/api";import{Original}from"@zortexhq/plugin-connector-framework/api";import{measurementSource,SOURCE_TAXONOMY_VERSION}from"./source-taxonomy.js";import{invocationProperties,invocationTool,observationProjection}from"./observations.js";import{executionProperties,operationalProperties}from"./operational.js";import{resourceProperties}from"./resources.js";import{collectionStatusProperties}from"./collection-status.js";import{activityProperties}from"./activity.js";const tools=new Set(["search","context","sql","actions","action","manage","instruction","handbook","mcp.call"]);const outcomes=new Set(["ok","empty","fault","auth-blocked","cancelled","invalid"]);export const NORTHSTAR_LOCAL_ONLY_OPERATIONS=[];const operationalOnly=new Set(["action_result","append","feedback","done","connector.fabricate","flywheel.start","flywheel.run"]);const connectorOutcomes={x:{id:"connector-x",version:"connector-x-v1",owner:"Raven",authorLogin:"ngsanchong0801"},instagram:{id:"connector-instagram",version:"connector-instagram-v1",owner:"Raven",authorLogin:"ngsanchong0801"},linkedin:{id:"connector-linkedin",version:"connector-linkedin-v1",owner:"Raven",authorLogin:"ngsanchong0801"},whatsapp:{id:"connector-whatsapp",version:"connector-whatsapp-v1",owner:"Raven",authorLogin:"ngsanchong0801"},gmail:{id:"autopilot-gmail",version:"autopilot-gmail-v1",owner:"Raven",authorLogin:"ngsanchong0801"},"google-drive":{id:"autopilot-google-drive",version:"autopilot-google-drive-v1",owner:"Raven",authorLogin:"ngsanchong0801"}};const vaultOutcome={id:"vault-search-local",version:"vault-search-local-v1",owner:"\u4E66\u4FCA",authorLogin:"cao-unix"};const jevOutcome={id:"jev-auto-login",version:"jev-auto-login-v1",owner:"\u6D77\u6D32",authorLogin:"hhz200"};const feedbackOutcome={id:"posthog-product-feedback",version:"posthog-product-feedback-v1",owner:"\u6C9B\u9716",authorLogin:"jpl302e2"};function scoreOutcomes(row,outcome){const scored=[],success=outcome==="ok";const source=row.source==="whatsapp-web"?"whatsapp":row.source;const connectorOutcome=source&&Object.hasOwn(connectorOutcomes,source)?connectorOutcomes[source]:void 0;if(row.operation==="connector.read"&&connectorOutcome)scored.push({definition:connectorOutcome,success});if(["search","context","sql"].includes(row.operation))scored.push({definition:vaultOutcome,success});if(row.operation==="connector.authorization"){if(row.trace?.driver==="jev"&&row.trace.mode==="automatic")scored.push({definition:jevOutcome,success});const traceComplete=isUsageTrace(row.trace)&&row.trace.stage==="authorization_finished"&&["completed","failed","cancelled","unknown"].includes(row.trace.state??"");scored.push({definition:feedbackOutcome,success:traceComplete})}return scored}export function hasScoredOutcome(row){return scoreOutcomes(row,outcomes.has(row.outcome)?row.outcome:"unknown").length>0}const platforms=new Set(["darwin","win32","linux","unknown"]);const executionLocations=new Set(["local","cloud","unknown"]);const errorCategories=new Set(USAGE_ERROR_CATEGORIES);const feedbackRatings=new Set(FEEDBACK_RATINGS);const feedbackReasons=new Set(FEEDBACK_REASONS);const feedbackChannels=new Set(FEEDBACK_CHANNELS);const feedbackOperations=new Set(FEEDBACK_OPERATIONS);const version=value=>typeof value==="string"&&value.length<=64&&/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(value);const isoTimestamp=value=>typeof value==="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(value)&&Number.isFinite(Date.parse(value));const accountIdPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function eventAccountIdentity(account,at){if(!account||typeof account.id!=="string"||!accountIdPattern.test(account.id)||!Number.isSafeInteger(account.registeredAt)||account.registeredAt<0)return;const registered=account.registeredAt*1e3,eventTime=Date.parse(at);if(!Number.isSafeInteger(registered)||!Number.isFinite(eventTime)||registered>eventTime)return;return{id:account.id,registeredAt:account.registeredAt}}const profileName=(kind,id)=>typeof id==="string"&&isFlowId(id.toLowerCase())?`${kind} ${id.slice(0,8)}`:kind;function invocationMetadata(row,operational){const invocation=invocationProperties(row);return invocation.entrypoint==="unknown"&&typeof operational?.entrypoint==="string"?{...invocation,entrypoint:operational.entrypoint}:invocation}function contextProperties(context,prefix=""){const productVersion=version(context?.productVersion)?context.productVersion:"unknown";const platform=platforms.has(context?.platform??"")?context.platform:"unknown";const executionLocation=executionLocations.has(context?.executionLocation??"")?context.executionLocation:"unknown";const traffic=context?.trafficClass;const deviceId=typeof context?.deviceId==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(context.deviceId)?context.deviceId:void 0;const deviceKind=platform==="darwin"?"Mac":platform==="win32"?"Windows PC":platform==="linux"?"Linux PC":"Device";return{[prefix+"product_version"]:productVersion,[prefix+"platform"]:platform,[prefix+"execution_location"]:executionLocation,[prefix+"capture_context_known"]:!!context&&(context.productVersion===void 0||version(context.productVersion))&&platforms.has(context.platform??"")&&executionLocations.has(context.executionLocation??""),[prefix+"capture_traffic_class"]:traffic==="usage"||traffic==="internal_test"||traffic==="simulation"?traffic:"unknown",...traffic==="internal_test"||traffic==="simulation"?{}:{[prefix+"device_identity_known"]:!!deviceId,...deviceId?{[prefix+"device_id"]:deviceId,[prefix+"device_alias"]:deviceKind+" "+deviceId.slice(0,8),[prefix+"device_identity_scheme"]:"random_app_user_device_v1"}:{}}}}function resultProperties(result,prefix=""){const count=result?.count,known=Number.isSafeInteger(count)&&count!==void 0&&count>=0&&count<=1e8;return{[prefix+"result_count_known"]:known,...known?{[prefix+"result_count"]:count,[prefix+"result_nonempty"]:count>0}:{},...typeof result?.truncated==="boolean"?{[prefix+"result_truncated"]:result.truncated}:{}}}function correlationProperties(row){const correlation=row.correlation??(isUsageTrace(row.trace)?row.trace:void 0);if(!isFlowId(correlation?.flowId))return{};return{flow_id:correlation.flowId,...isFlowId(correlation.connectionFlowId)?{connection_flow_id:correlation.connectionFlowId}:{}}}function feedbackProperties(row){const f=row.feedback,t=f?.target;if(!f||!isFlowId(f.targetReceiptId)||!feedbackRatings.has(f.rating)||!feedbackChannels.has(f.submissionChannel)||!t||!feedbackOperations.has(t.operation)||!(outcomes.has(t.outcome)||t.outcome==="unknown")||!isoTimestamp(t.at))return;const source=measurementSource(t.source);return{feedback_measurement:"receipt_usefulness_v1",target_receipt_id:f.targetReceiptId,target_at:t.at,target_operation:t.operation,target_outcome:t.outcome,target_connector:source,target_connector_known:source!=="other",rating:f.rating,feedback_reason:f.reason===void 0?"not_provided":feedbackReasons.has(f.reason)?f.reason:"unknown",submission_channel:f.submissionChannel,...contextProperties(t.context,"target_"),...resultProperties(t.result,"target_")}}const galaxyStates=new Set(["live_local","empty","vault_unavailable"]);export function northstarEvents(row,installId,verifiedGithubLogin,account,processPersonProfile=true){const projected=[],outcome=outcomes.has(row.outcome)?row.outcome:"unknown";const duration=Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=6e5?Math.round(row.durationMs):void 0;const connector=measurementSource(row.source),sourceProperties={connector,connector_known:connector!=="other",source_taxonomy_version:SOURCE_TAXONOMY_VERSION};if(row.operation==="product.collection"){const properties=collectionStatusProperties(row);if(!properties)return[];projected.push(["zortex collection status",properties])}else if(row.operation==="product.resources"){const properties=resourceProperties(row);if(!properties)return[];projected.push(["zortex resource snapshot",properties])}else if(row.operation==="product.trace"){const properties=operationalProperties(row);if(!properties)return[];projected.push(["zortex operation step",{...sourceProperties,...properties}])}else if(row.operation==="product.feedback"){const feedback=feedbackProperties(row);if(feedback)projected.push(["zortex product feedback",feedback])}else if(row.operation==="product.account_signed_in"){projected.push(["zortex account signed in",{outcome,identity_scope:"installation"}])}else if(row.operation==="product.first_start"||row.operation==="product.started"){projected.push([row.operation==="product.first_start"?"zortex first start":"zortex started",{identity_scope:"installation",...row.operation==="product.first_start"?{new_install_known:["new_install","first_observed"].includes(row.code??""),is_new_install:row.code==="new_install"}:{}}])}else if(row.operation==="product.galaxy_opened"){projected.push(["zortex galaxy opened",{identity_scope:"installation",outcome,galaxy_state:galaxyStates.has(row.code??"")?row.code:"unknown"}])}else if(row.operation==="connector.trace"&&isUsageTrace(row.trace)){const t=row.trace;projected.push(["zortex connection step",{...sourceProperties,flow_id:t.flowId,...t.connectionFlowId?{connection_flow_id:t.connectionFlowId}:{},duration_known:t.durationKnown===true&&duration!==void 0,stage:t.stage,state:t.state??"unknown",mode:t.mode??"unknown",trigger:t.trigger??"unknown",outcome,...t.page?{page:t.page}:{},...t.action?{action:t.action}:{},...t.reason?{reason:t.reason}:{},...t.error?{error_category:t.error}:{},...t.statusCode!==void 0?{status_code:t.statusCode}:{},...t.count!==void 0?{record_count:t.count}:{},...t.elapsedMs!==void 0?{elapsed_ms:Math.round(t.elapsedMs)}:{},...t.durationKnown===true&&duration!==void 0?{duration_ms:duration}:{}}])}else if(["connector.sync","connector.inventory","connector.connection"].includes(row.operation)){const observation=observationProjection(row);if(observation)projected.push([observation.event,{...sourceProperties,...observation.properties}])}else if(tools.has(row.operation)){const tool="indra."+(invocationTool(row)??(row.operation==="mcp.call"?"unknown":row.operation)),error=!["ok","empty"].includes(outcome);const detail={...correlationProperties(row),...row.source!==void 0?sourceProperties:{},error_category:errorCategories.has(row.errorCategory??"")?row.errorCategory:"unknown"};projected.push([outcome==="auth-blocked"?"zortex refused":row.operation==="search"?"zortex delivery":"zortex call",{tool,client:"indra-v2",error,...detail}]);projected.push(["zortex call timing",{tool,error,...detail,duration_known:duration!==void 0,...duration!==void 0?{duration_ms:duration}:{}}])}else if(row.operation==="connector.authorization"){const phase=row.outcome==="ok"?"completed":row.outcome==="cancelled"?"cancelled":["fault","auth-blocked","invalid"].includes(row.outcome)?"failed":"unresolved";const elapsed=Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?Math.round(row.durationMs):void 0;projected.push(["zortex auth journey",{...sourceProperties,phase,final:true,outcome:phase==="unresolved"?"unknown":outcome,...isUsageTrace(row.trace)?{flow_id:row.trace.flowId,connection_flow_id:row.trace.connectionFlowId??row.trace.flowId,mode:row.trace.mode??"unknown",trigger:row.trace.trigger??"unknown",...row.trace.driver?{driver:row.trace.driver}:{}}:{},...row.code?{reason:AUTHORIZATION_REASON_CODES.some(code=>code===row.code)?row.code:"provider_error"}:{},duration_known:elapsed!==void 0,...elapsed!==void 0?{duration_ms:elapsed}:{}}])}else if(row.operation==="connector.connect"){projected.push(["zortex auth journey",{...sourceProperties,phase:"request_returned",outcome,...correlationProperties(row)}])}else if(["connector.read","connector.invoke","connector.usable"].includes(row.operation)){const observedOperation=row.operation!=="connector.usable",elapsed=observedOperation&&Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?Math.round(row.durationMs):void 0;const errorCategory=errorCategories.has(row.errorCategory??"")?row.errorCategory:isUsageTrace(row.trace)&&row.trace.error?row.trace.error:"unknown";projected.push(["zortex connector health",{...sourceProperties,plane:"query",operation:row.operation,outcome,evidence_kind:observedOperation?"operation_receipt":"query_availability",duration_known:elapsed!==void 0,...elapsed!==void 0?{duration_ms:elapsed}:{},error_category:errorCategory,...correlationProperties(row)}])}else if(operationalOnly.has(row.operation)){const elapsed=Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?Math.round(row.durationMs):void 0;projected.push(["zortex product operation",{...sourceProperties,evidence_kind:"operation_receipt",duration_known:elapsed!==void 0,...elapsed!==void 0?{duration_ms:elapsed}:{},...correlationProperties(row)}])}const definitions=verifiedGithubLogin?scoreOutcomes(row,outcome):[];for(const{definition,success}of definitions){const score={score_outcome_id:definition.id,score_outcome_version:definition.version,score_owner:definition.owner,score_author_login:definition.authorLogin,score_success:success,identity_scope:"verified_human",identity_scheme:"github_api_user_v1"};projected.push(["zortex outcome attempted",score]);if(success)projected.push(["zortex outcome succeeded",score])}return projected.map(([event,properties])=>{const scoreEvent=event.startsWith("zortex outcome ");const scoreIdentity=scoreEvent?":"+String(properties.score_outcome_id):"";const hex=createHash("sha256").update("indra-v2-northstar:1:"+installId+":"+row.id+":"+event+scoreIdentity).digest("hex");const usageProperties=!scoreEvent?{install_id:installId,identity_scope:"installation",identity_scheme:"random_install_v1",operation:row.operation,outcome,internal:row.internal??false,effective_usage:!row.internal&&row.outcome==="ok"&&(["search","context","sql"].includes(row.operation)||row.operation==="action"&&row.code==="effective_invoke")&&["zortex delivery","zortex call"].includes(event),usage_measurement:"successful_tool_receipt_v1",...isFlowId(row.id)?{receipt_id:row.id}:{},...contextProperties(row.context),...resultProperties(row.result),...invocationMetadata(row,event==="zortex operation step"?properties:void 0),...executionProperties(row)}:{};const eventAccount=row.operation==="product.feedback"?void 0:eventAccountIdentity(account,row.at);const accountProperties=!scoreEvent?{account_known:!!eventAccount,...eventAccount?{account_id:eventAccount.id,distinct_id:`zortex-account:${eventAccount.id}`,identity_scope:"verified_email_account",identity_scheme:"zortex_email_v1",account_registered_at:new Date(eventAccount.registeredAt*1e3).toISOString()}:{},...activityProperties(row.operation,event,row.trace)}:{};const profileEnabled=processPersonProfile&&!scoreEvent;const profileProperties=profileEnabled?{$set:{name:profileName(eventAccount?"Account":"Installation",eventAccount?.id??installId),product:"indra-v2",identity_scope:eventAccount?"verified_email_account":"installation",identity_scheme:eventAccount?"zortex_email_v1":"random_install_v1"}}:{};return{event,uuid:`${hex.slice(0,8)}-${hex.slice(8,12)}-5${hex.slice(13,16)}-a${hex.slice(17,20)}-${hex.slice(20,32)}`,timestamp:row.at,properties:{distinct_id:scoreEvent?`github:${verifiedGithubLogin}`:installId,$process_person_profile:profileEnabled,$geoip_disable:true,product:"indra-v2",schema_version:scoreEvent?2:1,...properties,...usageProperties,...accountProperties,...profileProperties}}})}const rawCodes=new Set([...AUTHORIZATION_REASON_CODES,...Original.ERROR_CODES,"effective_invoke","new_install","first_observed",...galaxyStates]);export function rawUsageEvents(row,installId){if(!TELEMETRY_OPERATIONS.includes(row.operation))return[];const operational=row.operation==="product.trace"?operationalProperties(row):void 0;if(row.operation==="product.trace"&&!operational)return[];const resource=row.operation==="product.resources"?resourceProperties(row):void 0;if(row.operation==="product.resources"&&!resource)return[];const collectionStatus=row.operation==="product.collection"?collectionStatusProperties(row):void 0;if(row.operation==="product.collection"&&!collectionStatus)return[];const observation=["connector.sync","connector.inventory","connector.connection"].includes(row.operation)?observationProjection(row):void 0;if(["connector.sync","connector.inventory","connector.connection"].includes(row.operation)&&!observation)return[];const duration=(!operational||operational.duration_known===true)&&Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?row.durationMs:void 0;return[{event:"zortex."+row.operation,uuid:row.id,timestamp:row.at,properties:{distinct_id:installId,install_id:installId,identity_scope:"installation",identity_scheme:"random_install_v1",account_known:false,...activityProperties(row.operation,"zortex."+row.operation,row.trace),$process_person_profile:false,$geoip_disable:true,operation:row.operation,outcome:outcomes.has(row.outcome)?row.outcome:"unknown",duration_known:duration!==void 0,...duration!==void 0?{duration_ms:duration}:{},internal:row.internal??false,...row.source!==void 0?{source:measurementSource(row.source),source_known:measurementSource(row.source)!=="other",source_taxonomy_version:SOURCE_TAXONOMY_VERSION}:{},...row.code!==void 0?{code:rawCodes.has(row.code)?row.code:"unknown",code_known:rawCodes.has(row.code)}:{},...contextProperties(row.context),...resultProperties(row.result),...correlationProperties(row),...executionProperties(row),...observation?.properties??{},...operational??{},...resource??{},...collectionStatus??{},...invocationMetadata(row,operational)}}]}
1
+ import{createHash}from"node:crypto";import{AUTHORIZATION_REASON_CODES,TELEMETRY_OPERATIONS,FEEDBACK_OPERATIONS,FEEDBACK_RATINGS,FEEDBACK_REASONS,FEEDBACK_CHANNELS,USAGE_ERROR_CATEGORIES,isFlowId,isUsageTrace,isUsageSearchSummary}from"@zortexhq/plugin-telemetry/api";import{Original}from"@zortexhq/plugin-connector-framework/api";import{measurementSource,SOURCE_TAXONOMY_VERSION}from"./source-taxonomy.js";import{invocationProperties,invocationTool,observationProjection}from"./observations.js";import{executionProperties,operationalProperties}from"./operational.js";import{resourceProperties}from"./resources.js";import{collectionStatusProperties}from"./collection-status.js";import{activityProperties}from"./activity.js";const tools=new Set(["search","context","sql","actions","action","manage","instruction","handbook","mcp.call"]);const outcomes=new Set(["ok","empty","fault","auth-blocked","cancelled","invalid"]);export const NORTHSTAR_LOCAL_ONLY_OPERATIONS=[];const operationalOnly=new Set(["action_result","append","feedback","done","connector.fabricate","flywheel.start","flywheel.run"]);const connectorOutcomes={x:{id:"connector-x",version:"connector-x-v1",owner:"Raven",authorLogin:"ngsanchong0801"},instagram:{id:"connector-instagram",version:"connector-instagram-v1",owner:"Raven",authorLogin:"ngsanchong0801"},linkedin:{id:"connector-linkedin",version:"connector-linkedin-v1",owner:"Raven",authorLogin:"ngsanchong0801"},whatsapp:{id:"connector-whatsapp",version:"connector-whatsapp-v1",owner:"Raven",authorLogin:"ngsanchong0801"},gmail:{id:"autopilot-gmail",version:"autopilot-gmail-v1",owner:"Raven",authorLogin:"ngsanchong0801"},"google-drive":{id:"autopilot-google-drive",version:"autopilot-google-drive-v1",owner:"Raven",authorLogin:"ngsanchong0801"}};const vaultOutcome={id:"vault-search-local",version:"vault-search-local-v1",owner:"\u4E66\u4FCA",authorLogin:"cao-unix"};const jevOutcome={id:"jev-auto-login",version:"jev-auto-login-v1",owner:"\u6D77\u6D32",authorLogin:"hhz200"};const feedbackOutcome={id:"posthog-product-feedback",version:"posthog-product-feedback-v1",owner:"\u6C9B\u9716",authorLogin:"jpl302e2"};function scoreOutcomes(row,outcome){const scored=[],success=outcome==="ok";const source=row.source==="whatsapp-web"?"whatsapp":row.source;const connectorOutcome=source&&Object.hasOwn(connectorOutcomes,source)?connectorOutcomes[source]:void 0;if(row.operation==="connector.read"&&connectorOutcome)scored.push({definition:connectorOutcome,success});if(["search","context","sql"].includes(row.operation))scored.push({definition:vaultOutcome,success});if(row.operation==="connector.authorization"){if(row.trace?.driver==="jev"&&row.trace.mode==="automatic")scored.push({definition:jevOutcome,success});const traceComplete=isUsageTrace(row.trace)&&row.trace.stage==="authorization_finished"&&["completed","failed","cancelled","unknown"].includes(row.trace.state??"");scored.push({definition:feedbackOutcome,success:traceComplete})}return scored}export function hasScoredOutcome(row){return scoreOutcomes(row,outcomes.has(row.outcome)?row.outcome:"unknown").length>0}const platforms=new Set(["darwin","win32","linux","unknown"]);const executionLocations=new Set(["local","cloud","unknown"]);const errorCategories=new Set(USAGE_ERROR_CATEGORIES);const feedbackRatings=new Set(FEEDBACK_RATINGS);const feedbackReasons=new Set(FEEDBACK_REASONS);const feedbackChannels=new Set(FEEDBACK_CHANNELS);const feedbackOperations=new Set(FEEDBACK_OPERATIONS);const version=value=>typeof value==="string"&&value.length<=64&&/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(value);const isoTimestamp=value=>typeof value==="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(value)&&Number.isFinite(Date.parse(value));const accountIdPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function eventAccountIdentity(account,at){if(!account||typeof account.id!=="string"||!accountIdPattern.test(account.id)||!Number.isSafeInteger(account.registeredAt)||account.registeredAt<0)return;const registered=account.registeredAt*1e3,eventTime=Date.parse(at);if(!Number.isSafeInteger(registered)||!Number.isFinite(eventTime)||registered>eventTime)return;return{id:account.id,registeredAt:account.registeredAt}}const profileName=(kind,id)=>typeof id==="string"&&isFlowId(id.toLowerCase())?`${kind} ${id.slice(0,8)}`:kind;function invocationMetadata(row,operational){const invocation=invocationProperties(row);return invocation.entrypoint==="unknown"&&typeof operational?.entrypoint==="string"?{...invocation,entrypoint:operational.entrypoint}:invocation}function contextProperties(context,prefix=""){const productVersion=version(context?.productVersion)?context.productVersion:"unknown";const platform=platforms.has(context?.platform??"")?context.platform:"unknown";const executionLocation=executionLocations.has(context?.executionLocation??"")?context.executionLocation:"unknown";const traffic=context?.trafficClass;const deviceId=typeof context?.deviceId==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(context.deviceId)?context.deviceId:void 0;const deviceKind=platform==="darwin"?"Mac":platform==="win32"?"Windows PC":platform==="linux"?"Linux PC":"Device";return{[prefix+"product_version"]:productVersion,[prefix+"platform"]:platform,[prefix+"execution_location"]:executionLocation,[prefix+"capture_context_known"]:!!context&&(context.productVersion===void 0||version(context.productVersion))&&platforms.has(context.platform??"")&&executionLocations.has(context.executionLocation??""),[prefix+"capture_traffic_class"]:traffic==="usage"||traffic==="internal_test"||traffic==="simulation"?traffic:"unknown",...traffic==="internal_test"||traffic==="simulation"?{}:{[prefix+"device_identity_known"]:!!deviceId,...deviceId?{[prefix+"device_id"]:deviceId,[prefix+"device_alias"]:deviceKind+" "+deviceId.slice(0,8),[prefix+"device_identity_scheme"]:"random_app_user_device_v1"}:{}}}}function resultProperties(result,prefix=""){const count=result?.count,known=Number.isSafeInteger(count)&&count!==void 0&&count>=0&&count<=1e8;return{[prefix+"result_count_known"]:known,...known?{[prefix+"result_count"]:count,[prefix+"result_nonempty"]:count>0}:{},...typeof result?.truncated==="boolean"?{[prefix+"result_truncated"]:result.truncated}:{}}}function searchProperties(search,prefix=""){if(!isUsageSearchSummary(search))return{};return{[prefix+"search_state"]:search.state,[prefix+"search_route"]:search.route,[prefix+"search_coverage"]:search.coverage,[prefix+"search_reason"]:search.reason}}function successfulFind(row){const count=row.result?.count;return row.code==="content_find"&&isUsageSearchSummary(row.search)&&row.search.state==="found"&&(row.search.route==="vault"||row.search.route==="live")&&row.errorCategory===void 0&&Number.isSafeInteger(count)&&Number(count)>0&&Number(count)<=1e8}function correlationProperties(row){const correlation=row.correlation??(isUsageTrace(row.trace)?row.trace:void 0);if(!isFlowId(correlation?.flowId))return{};return{flow_id:correlation.flowId,...isFlowId(correlation.connectionFlowId)?{connection_flow_id:correlation.connectionFlowId}:{}}}function feedbackProperties(row){const f=row.feedback,t=f?.target;if(!f||!isFlowId(f.targetReceiptId)||!feedbackRatings.has(f.rating)||!feedbackChannels.has(f.submissionChannel)||!t||!feedbackOperations.has(t.operation)||!(outcomes.has(t.outcome)||t.outcome==="unknown")||!isoTimestamp(t.at))return;const source=measurementSource(t.source);return{feedback_measurement:"receipt_usefulness_v1",target_receipt_id:f.targetReceiptId,target_at:t.at,target_operation:t.operation,target_outcome:t.outcome,target_connector:source,target_connector_known:source!=="other",rating:f.rating,feedback_reason:f.reason===void 0?"not_provided":feedbackReasons.has(f.reason)?f.reason:"unknown",submission_channel:f.submissionChannel,...contextProperties(t.context,"target_"),...resultProperties(t.result,"target_"),...searchProperties(t.search,"target_"),...errorCategories.has(t.errorCategory??"")?{target_error_category:t.errorCategory}:{}}}const galaxyStates=new Set(["live_local","empty","vault_unavailable"]);export function northstarEvents(row,installId,verifiedGithubLogin,account,processPersonProfile=true){const projected=[],outcome=outcomes.has(row.outcome)?row.outcome:"unknown";const duration=Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=6e5?Math.round(row.durationMs):void 0;const connector=measurementSource(row.source),sourceProperties={connector,connector_known:connector!=="other",source_taxonomy_version:SOURCE_TAXONOMY_VERSION};if(row.operation==="product.collection"){const properties=collectionStatusProperties(row);if(!properties)return[];projected.push(["zortex collection status",properties])}else if(row.operation==="product.resources"){const properties=resourceProperties(row);if(!properties)return[];projected.push(["zortex resource snapshot",properties])}else if(row.operation==="product.trace"){const properties=operationalProperties(row);if(!properties)return[];projected.push(["zortex operation step",{...sourceProperties,...properties}])}else if(row.operation==="product.feedback"){const feedback=feedbackProperties(row);if(feedback)projected.push(["zortex product feedback",feedback])}else if(row.operation==="product.account_signed_in"){projected.push(["zortex account signed in",{outcome,identity_scope:"installation"}])}else if(row.operation==="product.first_start"||row.operation==="product.started"){projected.push([row.operation==="product.first_start"?"zortex first start":"zortex started",{identity_scope:"installation",...row.operation==="product.first_start"?{new_install_known:["new_install","first_observed"].includes(row.code??""),is_new_install:row.code==="new_install"}:{}}])}else if(row.operation==="product.galaxy_opened"){projected.push(["zortex galaxy opened",{identity_scope:"installation",outcome,galaxy_state:galaxyStates.has(row.code??"")?row.code:"unknown"}])}else if(row.operation==="connector.trace"&&isUsageTrace(row.trace)){const t=row.trace;projected.push(["zortex connection step",{...sourceProperties,flow_id:t.flowId,...t.connectionFlowId?{connection_flow_id:t.connectionFlowId}:{},duration_known:t.durationKnown===true&&duration!==void 0,stage:t.stage,state:t.state??"unknown",mode:t.mode??"unknown",trigger:t.trigger??"unknown",outcome,...t.page?{page:t.page}:{},...t.action?{action:t.action}:{},...t.reason?{reason:t.reason}:{},...t.error?{error_category:t.error}:{},...t.statusCode!==void 0?{status_code:t.statusCode}:{},...t.count!==void 0?{record_count:t.count}:{},...t.elapsedMs!==void 0?{elapsed_ms:Math.round(t.elapsedMs)}:{},...t.durationKnown===true&&duration!==void 0?{duration_ms:duration}:{}}])}else if(["connector.sync","connector.inventory","connector.connection"].includes(row.operation)){const observation=observationProjection(row);if(observation)projected.push([observation.event,{...sourceProperties,...observation.properties}])}else if(tools.has(row.operation)){const tool="indra."+(invocationTool(row)??(row.operation==="mcp.call"?"unknown":row.operation)),error=!["ok","empty"].includes(outcome);const detail={...correlationProperties(row),...row.source!==void 0?sourceProperties:{},error_category:errorCategories.has(row.errorCategory??"")?row.errorCategory:"unknown"};projected.push([outcome==="auth-blocked"?"zortex refused":row.operation==="search"?"zortex delivery":"zortex call",{tool,client:"indra-v2",error,...detail}]);projected.push(["zortex call timing",{tool,error,...detail,duration_known:duration!==void 0,...duration!==void 0?{duration_ms:duration}:{}}])}else if(row.operation==="connector.authorization"){const phase=row.outcome==="ok"?"completed":row.outcome==="cancelled"?"cancelled":["fault","auth-blocked","invalid"].includes(row.outcome)?"failed":"unresolved";const elapsed=Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?Math.round(row.durationMs):void 0;projected.push(["zortex auth journey",{...sourceProperties,phase,final:true,outcome:phase==="unresolved"?"unknown":outcome,...isUsageTrace(row.trace)?{flow_id:row.trace.flowId,connection_flow_id:row.trace.connectionFlowId??row.trace.flowId,mode:row.trace.mode??"unknown",trigger:row.trace.trigger??"unknown",...row.trace.driver?{driver:row.trace.driver}:{}}:{},...row.code?{reason:AUTHORIZATION_REASON_CODES.some(code=>code===row.code)?row.code:"provider_error"}:{},duration_known:elapsed!==void 0,...elapsed!==void 0?{duration_ms:elapsed}:{}}])}else if(row.operation==="connector.connect"){projected.push(["zortex auth journey",{...sourceProperties,phase:"request_returned",outcome,...correlationProperties(row)}])}else if(["connector.read","connector.invoke","connector.usable"].includes(row.operation)){const observedOperation=row.operation!=="connector.usable",elapsed=observedOperation&&Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?Math.round(row.durationMs):void 0;const errorCategory=errorCategories.has(row.errorCategory??"")?row.errorCategory:isUsageTrace(row.trace)&&row.trace.error?row.trace.error:"unknown";projected.push(["zortex connector health",{...sourceProperties,plane:"query",operation:row.operation,outcome,evidence_kind:observedOperation?"operation_receipt":"query_availability",duration_known:elapsed!==void 0,...elapsed!==void 0?{duration_ms:elapsed}:{},error_category:errorCategory,...correlationProperties(row)}])}else if(operationalOnly.has(row.operation)){const elapsed=Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?Math.round(row.durationMs):void 0;projected.push(["zortex product operation",{...sourceProperties,evidence_kind:"operation_receipt",duration_known:elapsed!==void 0,...elapsed!==void 0?{duration_ms:elapsed}:{},...correlationProperties(row)}])}const definitions=verifiedGithubLogin?scoreOutcomes(row,outcome):[];for(const{definition,success}of definitions){const score={score_outcome_id:definition.id,score_outcome_version:definition.version,score_owner:definition.owner,score_author_login:definition.authorLogin,score_success:success,identity_scope:"verified_human",identity_scheme:"github_api_user_v1"};projected.push(["zortex outcome attempted",score]);if(success)projected.push(["zortex outcome succeeded",score])}return projected.map(([event,properties])=>{const scoreEvent=event.startsWith("zortex outcome ");const scoreIdentity=scoreEvent?":"+String(properties.score_outcome_id):"";const hex=createHash("sha256").update("indra-v2-northstar:1:"+installId+":"+row.id+":"+event+scoreIdentity).digest("hex");const usageProperties=!scoreEvent?{install_id:installId,identity_scope:"installation",identity_scheme:"random_install_v1",operation:row.operation,outcome,internal:row.internal??false,effective_usage:!row.internal&&row.outcome==="ok"&&(["search","context","sql"].includes(row.operation)||row.operation==="action"&&(row.code==="effective_invoke"||successfulFind(row)))&&["zortex delivery","zortex call"].includes(event),usage_measurement:"successful_tool_receipt_v1",...isFlowId(row.id)?{receipt_id:row.id}:{},...contextProperties(row.context),...resultProperties(row.result),...searchProperties(row.search),...invocationMetadata(row,event==="zortex operation step"?properties:void 0),...executionProperties(row)}:{};const eventAccount=row.operation==="product.feedback"?void 0:eventAccountIdentity(account,row.at);const accountProperties=!scoreEvent?{account_known:!!eventAccount,...eventAccount?{account_id:eventAccount.id,distinct_id:`zortex-account:${eventAccount.id}`,identity_scope:"verified_email_account",identity_scheme:"zortex_email_v1",account_registered_at:new Date(eventAccount.registeredAt*1e3).toISOString()}:{},...activityProperties(row.operation,event,row.trace,row.code)}:{};const profileEnabled=processPersonProfile&&!scoreEvent;const profileProperties=profileEnabled?{$set:{name:profileName(eventAccount?"Account":"Installation",eventAccount?.id??installId),product:"indra-v2",identity_scope:eventAccount?"verified_email_account":"installation",identity_scheme:eventAccount?"zortex_email_v1":"random_install_v1"}}:{};return{event,uuid:`${hex.slice(0,8)}-${hex.slice(8,12)}-5${hex.slice(13,16)}-a${hex.slice(17,20)}-${hex.slice(20,32)}`,timestamp:row.at,properties:{distinct_id:scoreEvent?`github:${verifiedGithubLogin}`:installId,$process_person_profile:profileEnabled,$geoip_disable:true,product:"indra-v2",schema_version:scoreEvent?2:1,...properties,...usageProperties,...accountProperties,...profileProperties}}})}const rawCodes=new Set([...AUTHORIZATION_REASON_CODES,...Original.ERROR_CODES,"effective_invoke","content_find","new_install","first_observed",...galaxyStates]);export function rawUsageEvents(row,installId){if(!TELEMETRY_OPERATIONS.includes(row.operation))return[];const operational=row.operation==="product.trace"?operationalProperties(row):void 0;if(row.operation==="product.trace"&&!operational)return[];const resource=row.operation==="product.resources"?resourceProperties(row):void 0;if(row.operation==="product.resources"&&!resource)return[];const collectionStatus=row.operation==="product.collection"?collectionStatusProperties(row):void 0;if(row.operation==="product.collection"&&!collectionStatus)return[];const observation=["connector.sync","connector.inventory","connector.connection"].includes(row.operation)?observationProjection(row):void 0;if(["connector.sync","connector.inventory","connector.connection"].includes(row.operation)&&!observation)return[];const duration=(!operational||operational.duration_known===true)&&Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5?row.durationMs:void 0;return[{event:"zortex."+row.operation,uuid:row.id,timestamp:row.at,properties:{distinct_id:installId,install_id:installId,identity_scope:"installation",identity_scheme:"random_install_v1",account_known:false,...activityProperties(row.operation,"zortex."+row.operation,row.trace,row.code),$process_person_profile:false,$geoip_disable:true,operation:row.operation,outcome:outcomes.has(row.outcome)?row.outcome:"unknown",duration_known:duration!==void 0,...duration!==void 0?{duration_ms:duration}:{},internal:row.internal??false,...row.source!==void 0?{source:measurementSource(row.source),source_known:measurementSource(row.source)!=="other",source_taxonomy_version:SOURCE_TAXONOMY_VERSION}:{},...row.code!==void 0?{code:rawCodes.has(row.code)?row.code:"unknown",code_known:rawCodes.has(row.code)}:{},...contextProperties(row.context),...resultProperties(row.result),...searchProperties(row.search),...correlationProperties(row),...executionProperties(row),...observation?.properties??{},...operational??{},...resource??{},...collectionStatus??{},...invocationMetadata(row,operational)}}]}
@@ -1 +1 @@
1
- import{AsyncLocalStorage}from"node:async_hooks";import{TELEMETRY_OPERATIONS,TELEMETRY_OUTCOMES}from"./telemetry.js";import{isFlowId,isUsageTrace}from"./trace.js";import{isUsageInvocation,isUsageObservationFacts,isUsageObservationStats,snapshotUsageObservation}from"./observations.js";import{isOperationalContext,isUsageOperationalTrace}from"./operational.js";import{isTelemetrySourceId}from"./source-ids.js";import{isUsageResourceSnapshot,snapshotResourceMetadata}from"./resources.js";import{isUsageCollectionStatus,snapshotCollectionStatus}from"./collection.js";export const USAGE_TRAFFIC_CLASSES=["usage","internal_test","simulation"];export const USAGE_ERROR_CATEGORIES=["timeout","denied","network","provider","storage","identity","unknown"];export const FEEDBACK_OPERATIONS=["search","context","sql","action","connector.read","connector.invoke"];export const FEEDBACK_RATINGS=["useful","partly_useful","not_useful","cannot_judge"];export const FEEDBACK_REASONS=["saved_time","answered_question","incomplete","wrong_result","no_result","too_slow","connection_problem","unclear"];export const FEEDBACK_CHANNELS=["interactive_cli","programmatic_cli"];const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const closed=(value,keys)=>Object.keys(value).every(key=>keys.includes(key));const id=value=>typeof value==="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(value);export function isUsageContext(value){if(!object(value)||!closed(value,["productVersion","platform","executionLocation","deviceId","trafficClass"]))return false;return(value.productVersion===void 0||typeof value.productVersion==="string"&&value.productVersion.length<=64&&/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/.test(value.productVersion))&&(value.platform===void 0||typeof value.platform==="string"&&["darwin","win32","linux","unknown"].includes(value.platform))&&(value.deviceId===void 0||typeof value.deviceId==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value.deviceId))&&(value.executionLocation===void 0||typeof value.executionLocation==="string"&&["local","cloud","unknown"].includes(value.executionLocation))&&(value.trafficClass===void 0||typeof value.trafficClass==="string"&&USAGE_TRAFFIC_CLASSES.includes(value.trafficClass))}export function isUsageResultSummary(value){return object(value)&&closed(value,["count","truncated"])&&(value.count===void 0||Number.isSafeInteger(value.count)&&Number(value.count)>=0&&Number(value.count)<=1e8)&&(value.truncated===void 0||typeof value.truncated==="boolean")}export function isUsageCorrelation(value){return object(value)&&closed(value,["flowId","connectionFlowId"])&&isFlowId(value.flowId)&&(value.connectionFlowId===void 0||isFlowId(value.connectionFlowId))}export function isUsageFeedbackInput(value){return object(value)&&closed(value,["receiptId","rating","reason"])&&isFlowId(value.receiptId)&&FEEDBACK_RATINGS.includes(value.rating)&&(value.reason===void 0||FEEDBACK_REASONS.includes(value.reason))}export function isUsageFeedback(value){if(!object(value)||!closed(value,["targetReceiptId","rating","reason","submissionChannel","target"])||!isUsageFeedbackInput({receiptId:value.targetReceiptId,rating:value.rating,...value.reason!==void 0?{reason:value.reason}:{}})||!FEEDBACK_CHANNELS.includes(value.submissionChannel)||!object(value.target))return false;const target=value.target;return closed(target,["operation","source","outcome","at","context","result"])&&FEEDBACK_OPERATIONS.includes(target.operation)&&TELEMETRY_OUTCOMES.includes(target.outcome)&&typeof target.at==="string"&&Number.isFinite(Date.parse(target.at))&&(target.source===void 0||id(target.source))&&(target.context===void 0||isUsageContext(target.context))&&(target.result===void 0||isUsageResultSummary(target.result))}export function isUsageEvent(value,record=false){if(!object(value)||!closed(value,["operation","outcome","durationMs","source","code","internal","trace","operational","resource","collectionStatus","result","correlation","errorCategory",...record?["id","at","context","feedback","invocation","observation","execution"]:[]]))return false;const event=value;return TELEMETRY_OPERATIONS.includes(event.operation)&&TELEMETRY_OUTCOMES.includes(event.outcome)&&Number.isFinite(event.durationMs)&&event.durationMs>=0&&event.durationMs<=864e5&&(event.source===void 0||id(event.source))&&(event.code===void 0||typeof event.code==="string"&&/^[a-z][a-z0-9_]{0,63}$/.test(event.code))&&(event.internal===void 0||typeof event.internal==="boolean")&&(event.trace===void 0||isUsageTrace(event.trace))&&(event.operation!=="connector.trace"||event.trace!==void 0)&&(event.operation==="product.trace"?isUsageOperationalTrace(event.operational)&&event.internal===true&&event.code===void 0&&event.trace===void 0&&event.result===void 0&&(event.source===void 0||isTelemetrySourceId(event.source)):event.operational===void 0)&&(event.operation==="product.resources"?isUsageResourceSnapshot(event.resource)&&event.internal===true&&event.source===void 0&&event.code===void 0&&event.trace===void 0&&event.result===void 0&&event.correlation===void 0:event.resource===void 0)&&(event.operation==="product.collection"?isUsageCollectionStatus(event.collectionStatus)&&event.internal===true&&event.source===void 0&&event.code===void 0&&event.trace===void 0&&event.result===void 0&&event.correlation===void 0&&event.errorCategory===void 0&&event.execution===void 0&&event.invocation===void 0:event.collectionStatus===void 0)&&(event.result===void 0||isUsageResultSummary(event.result))&&(event.correlation===void 0||isUsageCorrelation(event.correlation))&&(event.errorCategory===void 0||USAGE_ERROR_CATEGORIES.includes(event.errorCategory))&&(!record||isFlowId(event.id)&&typeof event.at==="string"&&Number.isFinite(Date.parse(event.at))&&(event.context===void 0||isUsageContext(event.context))&&(event.feedback===void 0||isUsageFeedback(event.feedback))&&(event.invocation===void 0||isUsageInvocation(event.invocation))&&(event.observation===void 0||isUsageObservationFacts(event.observation))&&(event.execution===void 0||isOperationalContext(event.execution)))&&(event.operation==="product.feedback"?record&&event.feedback!==void 0&&event.internal===true:event.feedback===void 0)&&(["connector.sync","connector.inventory","connector.connection"].includes(event.operation)?record&&event.internal===true&&event.observation!==void 0&&event.operation==="connector."+event.observation.kind:event.observation===void 0)}export function feedbackEligible(event){return FEEDBACK_OPERATIONS.includes(event.operation)&&(event.operation!=="action"||event.code==="effective_invoke")&&(!event.internal||event.operation==="connector.read"||event.operation==="connector.invoke")}export function snapshotUsageRecord(value){if(!object(value))return value;const copy={...value};for(const key of["trace","operational","execution","context","result","correlation","invocation"])if(object(copy[key]))copy[key]={...copy[key]};if(object(copy.observation))copy.observation=snapshotUsageObservation(copy.observation);if(object(copy.resource))copy.resource=snapshotResourceMetadata(copy.resource);if(object(copy.collectionStatus))copy.collectionStatus=snapshotCollectionStatus(copy.collectionStatus);if(object(copy.feedback)){const feedback={...copy.feedback};if(object(feedback.target)){const target={...feedback.target};for(const key of["context","result"])if(object(target[key]))target[key]={...target[key]};feedback.target=target}copy.feedback=feedback}return copy}export function isUsageCollection(value){if(!object(value)||!closed(value,["retainedEvents","prunedEvents","retentionFloor","limited","retentionDays","maxEvents","oldestAvailableAt","observations"]))return false;return["retainedEvents","prunedEvents","retentionFloor","retentionDays","maxEvents"].every(key=>Number.isSafeInteger(value[key])&&Number(value[key])>=0)&&typeof value.limited==="boolean"&&(value.oldestAvailableAt===null||typeof value.oldestAvailableAt==="string"&&Number.isFinite(Date.parse(value.oldestAvailableAt)))&&(value.observations===void 0||isUsageObservationStats(value.observations))}export function usageResultSummary(reply){if(!("ok"in reply)||!object(reply.ok))return void 0;const value=reply.ok;const count=Number.isSafeInteger(value.returned)&&Number(value.returned)>=0&&Number(value.returned)<=1e8?Number(value.returned):Array.isArray(value.rows)?value.rows.length:Array.isArray(value.items)?value.items.length:void 0;const truncated=typeof value.truncated==="boolean"?value.truncated:void 0;return count===void 0&&truncated===void 0?void 0:{...count!==void 0?{count}:{},...truncated!==void 0?{truncated}:{}}}export function usageErrorCategory(reply){if(!("err"in reply))return void 0;if(reply.err.code==="deadline_exceeded")return"timeout";if(reply.err.code==="permission_denied")return"denied";if(reply.err.code==="unauthenticated")return"identity";if(reply.err.layer==="storage")return"storage";return"unknown"}const hostContext=new AsyncLocalStorage;export function withTelemetryContext(context,run){const captured=Object.freeze({...context});if(!isUsageContext(captured))throw Error("Invalid telemetry runtime context.");return hostContext.run(captured,run)}export const currentTelemetryContext=()=>hostContext.getStore();
1
+ import{AsyncLocalStorage}from"node:async_hooks";import{TELEMETRY_OPERATIONS,TELEMETRY_OUTCOMES,usageOutcome}from"./telemetry.js";import{isFlowId,isUsageTrace}from"./trace.js";import{isUsageInvocation,isUsageObservationFacts,isUsageObservationStats,snapshotUsageObservation}from"./observations.js";import{isOperationalContext,isUsageOperationalTrace}from"./operational.js";import{isTelemetrySourceId}from"./source-ids.js";import{isUsageResourceSnapshot,snapshotResourceMetadata}from"./resources.js";import{isUsageCollectionStatus,snapshotCollectionStatus}from"./collection.js";export const USAGE_TRAFFIC_CLASSES=["usage","internal_test","simulation"];export const USAGE_SEARCH_STATES=["found","empty","partial","connecting","needs_user","failed","cancelled","invalid","unknown"];export const USAGE_SEARCH_ROUTES=["vault","live","none","unknown"];export const USAGE_SEARCH_COVERAGE=["complete","partial","unknown"];export const USAGE_SEARCH_REASONS=["none","time_budget_exhausted","provider_unavailable","provider_warning","query_failed","sync_incomplete","outside_synced_range","cached_only","result_limit","snapshot_result_limit","early_stop","timeout","denied","identity","storage","network","provider","unknown"];export const USAGE_ERROR_CATEGORIES=["timeout","denied","network","provider","storage","identity","unknown"];export const FEEDBACK_OPERATIONS=["search","context","sql","action","connector.read","connector.invoke"];export const FEEDBACK_RATINGS=["useful","partly_useful","not_useful","cannot_judge"];export const FEEDBACK_REASONS=["saved_time","answered_question","incomplete","wrong_result","no_result","too_slow","connection_problem","unclear"];export const FEEDBACK_CHANNELS=["interactive_cli","programmatic_cli"];const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const closed=(value,keys)=>Object.keys(value).every(key=>keys.includes(key));const id=value=>typeof value==="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(value);export function isUsageContext(value){if(!object(value)||!closed(value,["productVersion","platform","executionLocation","deviceId","trafficClass"]))return false;return(value.productVersion===void 0||typeof value.productVersion==="string"&&value.productVersion.length<=64&&/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$/.test(value.productVersion))&&(value.platform===void 0||typeof value.platform==="string"&&["darwin","win32","linux","unknown"].includes(value.platform))&&(value.deviceId===void 0||typeof value.deviceId==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value.deviceId))&&(value.executionLocation===void 0||typeof value.executionLocation==="string"&&["local","cloud","unknown"].includes(value.executionLocation))&&(value.trafficClass===void 0||typeof value.trafficClass==="string"&&USAGE_TRAFFIC_CLASSES.includes(value.trafficClass))}export function isUsageResultSummary(value){return object(value)&&closed(value,["count","truncated"])&&(value.count===void 0||Number.isSafeInteger(value.count)&&Number(value.count)>=0&&Number(value.count)<=1e8)&&(value.truncated===void 0||typeof value.truncated==="boolean")}export function isUsageSearchSummary(value){return object(value)&&closed(value,["state","route","coverage","reason"])&&USAGE_SEARCH_STATES.includes(value.state)&&USAGE_SEARCH_ROUTES.includes(value.route)&&USAGE_SEARCH_COVERAGE.includes(value.coverage)&&USAGE_SEARCH_REASONS.includes(value.reason)}export function isUsageCorrelation(value){return object(value)&&closed(value,["flowId","connectionFlowId"])&&isFlowId(value.flowId)&&(value.connectionFlowId===void 0||isFlowId(value.connectionFlowId))}export function isUsageFeedbackInput(value){return object(value)&&closed(value,["receiptId","rating","reason"])&&isFlowId(value.receiptId)&&FEEDBACK_RATINGS.includes(value.rating)&&(value.reason===void 0||FEEDBACK_REASONS.includes(value.reason))}export function isUsageFeedback(value){if(!object(value)||!closed(value,["targetReceiptId","rating","reason","submissionChannel","target"])||!isUsageFeedbackInput({receiptId:value.targetReceiptId,rating:value.rating,...value.reason!==void 0?{reason:value.reason}:{}})||!FEEDBACK_CHANNELS.includes(value.submissionChannel)||!object(value.target))return false;const target=value.target;return closed(target,["operation","source","outcome","at","context","result","search","errorCategory"])&&FEEDBACK_OPERATIONS.includes(target.operation)&&TELEMETRY_OUTCOMES.includes(target.outcome)&&typeof target.at==="string"&&Number.isFinite(Date.parse(target.at))&&(target.source===void 0||id(target.source))&&(target.context===void 0||isUsageContext(target.context))&&(target.result===void 0||isUsageResultSummary(target.result))&&(target.search===void 0||isUsageSearchSummary(target.search))&&(target.errorCategory===void 0||USAGE_ERROR_CATEGORIES.includes(target.errorCategory))}export function isUsageEvent(value,record=false){if(!object(value)||!closed(value,["operation","outcome","durationMs","source","code","internal","trace","operational","resource","collectionStatus","result","search","correlation","errorCategory",...record?["id","at","context","feedback","invocation","observation","execution"]:[]]))return false;const event=value;return TELEMETRY_OPERATIONS.includes(event.operation)&&TELEMETRY_OUTCOMES.includes(event.outcome)&&Number.isFinite(event.durationMs)&&event.durationMs>=0&&event.durationMs<=864e5&&(event.source===void 0||id(event.source))&&(event.code===void 0||typeof event.code==="string"&&/^[a-z][a-z0-9_]{0,63}$/.test(event.code))&&(event.internal===void 0||typeof event.internal==="boolean")&&(event.trace===void 0||isUsageTrace(event.trace))&&(event.operation!=="connector.trace"||event.trace!==void 0)&&(event.operation==="product.trace"?isUsageOperationalTrace(event.operational)&&event.internal===true&&event.code===void 0&&event.trace===void 0&&event.result===void 0&&(event.source===void 0||isTelemetrySourceId(event.source)):event.operational===void 0)&&(event.operation==="product.resources"?isUsageResourceSnapshot(event.resource)&&event.internal===true&&event.source===void 0&&event.code===void 0&&event.trace===void 0&&event.result===void 0&&event.correlation===void 0:event.resource===void 0)&&(event.operation==="product.collection"?isUsageCollectionStatus(event.collectionStatus)&&event.internal===true&&event.source===void 0&&event.code===void 0&&event.trace===void 0&&event.result===void 0&&event.correlation===void 0&&event.errorCategory===void 0&&event.execution===void 0&&event.invocation===void 0:event.collectionStatus===void 0)&&(event.result===void 0||isUsageResultSummary(event.result))&&(event.search===void 0||event.operation==="action"&&event.code==="content_find"&&isUsageSearchSummary(event.search))&&(event.correlation===void 0||isUsageCorrelation(event.correlation))&&(event.errorCategory===void 0||USAGE_ERROR_CATEGORIES.includes(event.errorCategory))&&(!record||isFlowId(event.id)&&typeof event.at==="string"&&Number.isFinite(Date.parse(event.at))&&(event.context===void 0||isUsageContext(event.context))&&(event.feedback===void 0||isUsageFeedback(event.feedback))&&(event.invocation===void 0||isUsageInvocation(event.invocation))&&(event.observation===void 0||isUsageObservationFacts(event.observation))&&(event.execution===void 0||isOperationalContext(event.execution)))&&(event.operation==="product.feedback"?record&&event.feedback!==void 0&&event.internal===true:event.feedback===void 0)&&(["connector.sync","connector.inventory","connector.connection"].includes(event.operation)?record&&event.internal===true&&event.observation!==void 0&&event.operation==="connector."+event.observation.kind:event.observation===void 0)}export function feedbackEligible(event){return FEEDBACK_OPERATIONS.includes(event.operation)&&(event.operation!=="action"||event.code==="effective_invoke"||event.code==="content_find")&&(!event.internal||event.operation==="connector.read"||event.operation==="connector.invoke")}export function snapshotUsageRecord(value){if(!object(value))return value;const copy={...value};for(const key of["trace","operational","execution","context","result","search","correlation","invocation"])if(object(copy[key]))copy[key]={...copy[key]};if(object(copy.observation))copy.observation=snapshotUsageObservation(copy.observation);if(object(copy.resource))copy.resource=snapshotResourceMetadata(copy.resource);if(object(copy.collectionStatus))copy.collectionStatus=snapshotCollectionStatus(copy.collectionStatus);if(object(copy.feedback)){const feedback={...copy.feedback};if(object(feedback.target)){const target={...feedback.target};for(const key of["context","result","search"])if(object(target[key]))target[key]={...target[key]};feedback.target=target}copy.feedback=feedback}return copy}export function isUsageCollection(value){if(!object(value)||!closed(value,["retainedEvents","prunedEvents","retentionFloor","limited","retentionDays","maxEvents","oldestAvailableAt","observations"]))return false;return["retainedEvents","prunedEvents","retentionFloor","retentionDays","maxEvents"].every(key=>Number.isSafeInteger(value[key])&&Number(value[key])>=0)&&typeof value.limited==="boolean"&&(value.oldestAvailableAt===null||typeof value.oldestAvailableAt==="string"&&Number.isFinite(Date.parse(value.oldestAvailableAt)))&&(value.observations===void 0||isUsageObservationStats(value.observations))}export function usageResultSummary(reply){if(!("ok"in reply)||!object(reply.ok))return void 0;const value=reply.ok;const count=Number.isSafeInteger(value.returned)&&Number(value.returned)>=0&&Number(value.returned)<=1e8?Number(value.returned):Array.isArray(value.rows)?value.rows.length:Array.isArray(value.items)?value.items.length:void 0;const truncated=typeof value.truncated==="boolean"?value.truncated:void 0;return count===void 0&&truncated===void 0?void 0:{...count!==void 0?{count}:{},...truncated!==void 0?{truncated}:{}}}export function usageErrorCategory(reply){if(!("err"in reply))return void 0;if(reply.err.code==="deadline_exceeded")return"timeout";if(reply.err.code==="permission_denied")return"denied";if(reply.err.code==="unauthenticated")return"identity";if(reply.err.layer==="storage")return"storage";return"unknown"}export function usageFindMeasurement(reply){if(!("ok"in reply)){const outcome2="err"in reply&&reply.err.code==="failed_precondition"?"invalid":usageOutcome(reply),errorCategory2=usageErrorCategory(reply);return{outcome:outcome2,...errorCategory2?{errorCategory:errorCategory2}:{},search:{state:outcome2==="cancelled"?"cancelled":outcome2==="invalid"?"invalid":outcome2==="auth-blocked"?"needs_user":outcome2==="empty"?"empty":"failed",route:"unknown",coverage:"unknown",reason:errorCategory2??"unknown"}}}const value=object(reply.ok)?reply.ok:void 0;const state=value&&USAGE_SEARCH_STATES.includes(value.state)?value.state:"unknown";const route=value&&USAGE_SEARCH_ROUTES.includes(value.route)?value.route:"unknown";const completed=state==="found"||state==="empty",searched=completed||state==="partial";const rawCoverage=searched&&value&&object(value.coverage)?value.coverage:void 0;const coverage=rawCoverage&&USAGE_SEARCH_COVERAGE.includes(rawCoverage.status)?rawCoverage.status:"unknown";const reasons=rawCoverage&&Array.isArray(rawCoverage.reasons)?rawCoverage.reasons.slice(0,16):[];const closedReason=reasons.find(reason2=>typeof reason2==="string"&&USAGE_SEARCH_REASONS.includes(reason2)&&reason2!=="none");const code=value?.errorCode;const errorCategory=code==="deadline_exceeded"?"timeout":code==="permission_denied"?"denied":code==="unauthenticated"?"identity":state==="failed"||state==="partial"?"unknown":void 0;const reason=closedReason??(reasons.length?"unknown":errorCategory??(coverage==="complete"?"none":"unknown"));const records=searched&&(route==="vault"||route==="live")&&value&&Array.isArray(value.records)?value.records:void 0;const count=records&&records.length<=1e8?records.length:void 0;const consistent=count!==void 0&&(state!=="found"||count>0)&&(state!=="empty"||count===0)&&(route==="vault"||route==="live");const outcome=state==="needs_user"?"auth-blocked":state==="failed"?"fault":state==="cancelled"?"cancelled":state==="invalid"?"invalid":completed&&consistent&&errorCategory===void 0?state==="found"?"ok":"empty":"unknown";const cursor=value?.nextCursor;const truncated=cursor===null?false:Number.isSafeInteger(cursor)&&Number(cursor)>=0?true:void 0;return{outcome,search:{state,route,coverage,reason},...errorCategory?{errorCategory}:{},...count!==void 0?{result:{count,...truncated!==void 0?{truncated}:{}}}:{}}}const hostContext=new AsyncLocalStorage;export function withTelemetryContext(context,run){const captured=Object.freeze({...context});if(!isUsageContext(captured))throw Error("Invalid telemetry runtime context.");return hostContext.run(captured,run)}export const currentTelemetryContext=()=>hostContext.getStore();
@@ -1 +1 @@
1
- import{AsyncLocalStorage}from"node:async_hooks";import{randomUUID}from"node:crypto";import{AUTHORIZATION_REASON_CODES}from"./telemetry.js";import{currentFeedbackFlow,isFlowId}from"./trace.js";import{currentUsageInvocation,USAGE_TOOL_NAMES,USAGE_ENTRYPOINTS}from"./observations.js";import{isTelemetrySourceId}from"./source-ids.js";import{OPERATIONAL_TOOL_METHODS}from"./tool-methods.js";import{OPERATIONAL_UPSTREAM_TOOLS,OPERATIONAL_RPC_METHODS}from"./upstream-tools.js";export const OPERATIONAL_PHASES=["onboarding","tool","connector","browser","computer","runtime"];export const OPERATIONAL_ACTIONS=["source_selection","session_selection","readiness","login","open","reuse","connect","observe","click","type","scroll","key","download","install","cleanup","execute","status","catalog","read","invoke","review","cancel","share","goal","plan","ground","reveal","call","list_tools"];export const OPERATIONAL_STATES=["started","completed","failed","cancelled","waiting","unknown"];export const OPERATIONAL_ROUTES=["extension","attached_chrome","native_chrome","isolated_chromium","upstream_browser","mcp_stdio","mcp_http","unknown"];export const OPERATIONAL_PROFILES=["existing","dedicated","temporary","unknown"];export const OPERATIONAL_LOGIN_DECISIONS=["reuse","start_login","not_available","unknown"];export const OPERATIONAL_SELECTIONS=["default_roster","requested","saved","recovery","explicit","unknown"];export const OPERATIONAL_TRIGGERS=["automatic_startup","agent_action","user_request","recovery","scheduled","unknown"];export const OPERATIONAL_ARTIFACT_FAMILIES=["chatgpt_desktop","chromium","codex","indra","connector_runtime","other","unknown"];export const OPERATIONAL_ARTIFACT_TYPES=["installer","archive","package","browser_download","unknown"];export const OPERATIONAL_REASONS=[...AUTHORIZATION_REASON_CODES,"runtime_missing","browser_missing","browser_driver_unavailable","not_available","provider_failure"];export const OPERATIONAL_ERRORS=["timeout","denied","network","provider","storage","identity","unknown"];export const OPERATIONAL_DOWNLOAD_OBSERVATION=["supported","unavailable","unknown"];export const OPERATIONAL_OPERATIONS=["hub.status","hub.connect","hub.job","hub.cancel","hub.check","hub.read","hub.catalog","hub.method","hub.review","hub.invoke_reviewed","hub.invoke","hub.capture_information","hub.verify_information","hub.inspect_file","hub.materialize_file","tool.search","tool.context","tool.sql","tool.actions","tool.action","tool.manage","tool.instruction","tool.handbook","tool.read","tool.update","connector.status","connector.mcp_call_tool","connector.mcp_list_tools","connector.connect","connector.recover","connector.job","connector.read","connector.invoke","connector.sync","connector.disconnect","fleet.status","fleet.run","fleet.receipt","share.preview","share.create-link","share.inspect-link","share.read-file","browser.open","browser.observe","browser.click","browser.type","browser.scroll","browser.key","browser.close","browser.run_goal","browser.plan","browser.ground","browser.reveal","resident.configure","resident.connect_manual","resident.connect_automatic","resident.reauthorize","resident.recover","resident.connect_write","resident.connect","resident.connect_job","resident.cancel_connect","resident.reconnect","resident.startup","resident.pause_automation","resident.resume_sync","resident.local_cloud","resident.status","resident.stop","resident.check","unknown"];const fieldEnums={operationId:OPERATIONAL_OPERATIONS,countBasis:["catalog_total","returned_entries","available_sources"],route:OPERATIONAL_ROUTES,profile:OPERATIONAL_PROFILES,loginDecision:OPERATIONAL_LOGIN_DECISIONS,selection:OPERATIONAL_SELECTIONS,trigger:OPERATIONAL_TRIGGERS,artifactFamily:OPERATIONAL_ARTIFACT_FAMILIES,artifactType:OPERATIONAL_ARTIFACT_TYPES,reason:OPERATIONAL_REASONS,errorCategory:OPERATIONAL_ERRORS,tool:USAGE_TOOL_NAMES,method:OPERATIONAL_TOOL_METHODS,entrypoint:USAGE_ENTRYPOINTS,downloadObservation:OPERATIONAL_DOWNLOAD_OBSERVATION,upstreamTool:OPERATIONAL_UPSTREAM_TOOLS,rpcMethod:OPERATIONAL_RPC_METHODS};const fieldKeys=[...Object.keys(fieldEnums),"observedCount","processRef","actionRef","sourceRef"],enumHas=(values,value)=>typeof value==="string"&&values.includes(value);const isOperationalReference=value=>typeof value==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value);const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const closed=(value,keys)=>Object.keys(value).every(key=>keys.includes(key));function validFields(value){return Object.entries(fieldEnums).every(([key,values])=>value[key]===void 0||enumHas(values,value[key]))&&(value.observedCount===void 0?value.countBasis===void 0:Number.isSafeInteger(value.observedCount)&&Number(value.observedCount)>=0&&Number(value.observedCount)<=1e8&&value.countBasis!==void 0)&&["processRef","actionRef","sourceRef"].every(key=>value[key]===void 0||isOperationalReference(value[key]))}export function isOperationalContext(value){return object(value)&&closed(value,["runId","stepId"])&&isFlowId(value.runId)&&isFlowId(value.stepId)}export function isUsageOperationalTrace(value){if(!object(value)||!closed(value,["version","runId","stepId","parentStepId","emitterId","sequence","attempt","phase","action","state","terminal","durationKnown",...fieldKeys]))return false;return value.version===1&&isFlowId(value.runId)&&isFlowId(value.stepId)&&isFlowId(value.emitterId)&&(value.parentStepId===void 0||isFlowId(value.parentStepId)&&value.parentStepId!==value.stepId)&&Number.isSafeInteger(value.sequence)&&Number(value.sequence)>0&&Number(value.sequence)<=1e9&&Number.isSafeInteger(value.attempt)&&Number(value.attempt)>0&&Number(value.attempt)<=1e4&&enumHas(OPERATIONAL_PHASES,value.phase)&&enumHas(OPERATIONAL_ACTIONS,value.action)&&enumHas(OPERATIONAL_STATES,value.state)&&typeof value.terminal==="boolean"&&typeof value.durationKnown==="boolean"&&validFields(value)&&(["started","waiting"].includes(String(value.state))?!value.terminal&&!value.durationKnown:["completed","failed","cancelled"].includes(String(value.state))?value.terminal:!value.durationKnown||value.terminal)}export function operationalReason(value){return enumHas(OPERATIONAL_REASONS,value)?value:"unknown"}const executionContext=new AsyncLocalStorage;let emitterId=randomUUID(),sequence=0;function emissionOrder(){if(sequence>=1e9){emitterId=randomUUID();sequence=0}return{emitterId,sequence:++sequence}}export function withoutOperationalContext(run){return executionContext.exit(run)}export function currentOperationalExecution(){const value=executionContext.getStore();return value?{runId:value.runId,stepId:value.stepId}:void 0}export function withOperationalContext(input,run){const captured={...input};if(!isOperationalContext(captured))throw Error("Invalid operational context.");return executionContext.run(captured,run)}export function startOperationalRun(metrics,input){return executionContext.exit(()=>startOperationalStep(metrics,input))}export function startOperationalStep(metrics,input){const parent=executionContext.getStore(),fallback=currentFeedbackFlow()?.flowId??currentUsageInvocation()?.id;const scope={runId:parent?.runId??(isFlowId(fallback)?fallback:randomUUID()),stepId:randomUUID()};const pending=new Set;let fields,finished=false;const enabled=()=>{try{const value=metrics?.();return value?.isEnabled?.()===true?value:void 0}catch{return void 0}};const service=enabled();if(service)try{const value={...typeof input==="function"?input():input};if(closed(value,["runId","source","phase","action","attempt",...fieldKeys])&&enumHas(OPERATIONAL_PHASES,value.phase)&&enumHas(OPERATIONAL_ACTIONS,value.action)&&validFields(value)&&(value.runId===void 0||isFlowId(value.runId))&&(value.source===void 0||typeof value.source==="string")&&(value.attempt===void 0||Number.isSafeInteger(value.attempt)&&value.attempt>0&&value.attempt<=1e4)){if(value.source)try{const reference=service.sourceReference?.(value.source);if(isOperationalReference(reference))value.sourceRef=reference}catch{}fields=value;if(!parent&&isFlowId(value.runId))scope.runId=value.runId}}catch{}const started=performance.now();const emit=(state,terminal,extra={})=>{const target=enabled();if(!target||!fields)return;let details;try{details={...extra}}catch{return}if(!closed(details,fieldKeys)||!validFields(details))return;const combined=Object.fromEntries(Object.entries({...fields,...details}).filter(([key,value])=>fieldKeys.includes(key)&&value!==void 0));const elapsed=terminal?performance.now()-started:0;const durationKnown=terminal&&Number.isFinite(elapsed)&&elapsed>=0&&elapsed<=864e5;const durationMs=durationKnown?elapsed:0;const operational={version:1,runId:scope.runId,stepId:scope.stepId,...parent?{parentStepId:parent.stepId}:{},...emissionOrder(),attempt:fields.attempt??1,phase:fields.phase,action:fields.action,state,terminal,durationKnown,...combined};try{const result=executionContext.run(scope,()=>target.record({operation:"product.trace",internal:true,outcome:state==="completed"?"ok":state==="failed"?"fault":state==="cancelled"?"cancelled":"unknown",durationMs,...isTelemetrySourceId(fields.source)?{source:fields.source}:{},operational}));let timer;const bounded=Promise.race([Promise.resolve(result).then(()=>{},()=>{}),new Promise(resolve=>{timer=setTimeout(resolve,50)})]).then(()=>{if(timer)clearTimeout(timer)});pending.add(bounded);void bounded.finally(()=>pending.delete(bounded))}catch{}};const step={get runId(){return scope.runId},stepId:scope.stepId,run:fn=>executionContext.run(scope,fn),mark(value){try{if(finished||!fields||!enabled()||!value)return;const{state,...details}=value;if(["waiting","unknown"].includes(state))emit(state,false,details)}catch{}},finish(value){try{if(finished)return;finished=true;if(!fields||!enabled()||!value)return;const{state,...details}=value;if(["completed","failed","cancelled","unknown"].includes(state))emit(state,true,details)}catch{}},async flush(){await Promise.allSettled([...pending])}};emit("started",false);return step}export function operationalTraceSummary(events,collection={}){const steps=new Map,receipts=new Set;for(const row of events){if(receipts.has(row.id)||!isUsageOperationalTrace(row.operational))continue;receipts.add(row.id);const t=row.operational,key=t.runId+":"+t.stepId,step=steps.get(key)??{start:false,terminal:false};step.start||=t.state==="started";step.terminal||=t.terminal;steps.set(key,step)}const observed=steps.size>0,rows=[...steps.values()];return{coverage:"instrumented_steps_only",observation:collection.enabled===false?"disabled":observed?"observed":"unobserved",historyLimited:collection.limited===true,startedSteps:observed?rows.filter(s=>s.start).length:null,terminalSteps:observed?rows.filter(s=>s.terminal).length:null,unfinishedSteps:observed?rows.filter(s=>s.start&&!s.terminal).length:null,orphanTerminals:observed?rows.filter(s=>!s.start&&s.terminal).length:null}}
1
+ import{AsyncLocalStorage}from"node:async_hooks";import{randomUUID}from"node:crypto";import{AUTHORIZATION_REASON_CODES}from"./telemetry.js";import{currentFeedbackFlow,isFlowId}from"./trace.js";import{currentUsageInvocation,USAGE_TOOL_NAMES,USAGE_ENTRYPOINTS}from"./observations.js";import{isTelemetrySourceId}from"./source-ids.js";import{OPERATIONAL_TOOL_METHODS}from"./tool-methods.js";import{OPERATIONAL_UPSTREAM_TOOLS,OPERATIONAL_RPC_METHODS}from"./upstream-tools.js";export const OPERATIONAL_PHASES=["onboarding","tool","connector","browser","computer","runtime"];export const OPERATIONAL_ACTIONS=["source_selection","session_selection","readiness","login","open","reuse","connect","observe","click","type","scroll","key","download","install","cleanup","execute","status","catalog","read","invoke","review","cancel","share","goal","plan","ground","reveal","call","list_tools"];export const OPERATIONAL_STATES=["started","completed","failed","cancelled","waiting","unknown"];export const OPERATIONAL_ROUTES=["extension","attached_chrome","native_chrome","isolated_chromium","upstream_browser","mcp_stdio","mcp_http","unknown"];export const OPERATIONAL_PROFILES=["existing","dedicated","temporary","unknown"];export const OPERATIONAL_LOGIN_DECISIONS=["reuse","start_login","not_available","unknown"];export const OPERATIONAL_SELECTIONS=["default_roster","requested","saved","recovery","explicit","unknown"];export const OPERATIONAL_TRIGGERS=["automatic_startup","agent_action","user_request","recovery","scheduled","unknown"];export const OPERATIONAL_ARTIFACT_FAMILIES=["chatgpt_desktop","chromium","codex","indra","connector_runtime","other","unknown"];export const OPERATIONAL_ARTIFACT_TYPES=["installer","archive","package","browser_download","unknown"];export const OPERATIONAL_REASONS=[...AUTHORIZATION_REASON_CODES,"runtime_missing","browser_missing","browser_driver_unavailable","not_available","provider_failure"];export const OPERATIONAL_ERRORS=["timeout","denied","network","provider","storage","identity","unknown"];export const OPERATIONAL_DOWNLOAD_OBSERVATION=["supported","unavailable","unknown"];export const OPERATIONAL_OPERATIONS=["hub.status","hub.connect","hub.job","hub.cancel","hub.check","hub.read","hub.catalog","hub.method","hub.review","hub.invoke_reviewed","hub.invoke","hub.capture_information","hub.verify_information","hub.inspect_file","hub.materialize_file","tool.search","tool.context","tool.sql","tool.actions","tool.action","tool.manage","tool.instruction","tool.handbook","tool.read","tool.update","connector.status","connector.mcp_call_tool","connector.mcp_list_tools","connector.connect","connector.recover","connector.job","connector.read","connector.find","connector.invoke","connector.sync","connector.disconnect","fleet.status","fleet.run","fleet.receipt","share.preview","share.create-link","share.inspect-link","share.read-file","browser.open","browser.observe","browser.click","browser.type","browser.scroll","browser.key","browser.close","browser.run_goal","browser.plan","browser.ground","browser.reveal","resident.configure","resident.connect_manual","resident.connect_automatic","resident.reauthorize","resident.recover","resident.connect_write","resident.connect","resident.connect_job","resident.cancel_connect","resident.reconnect","resident.startup","resident.pause_automation","resident.resume_sync","resident.local_cloud","resident.status","resident.stop","resident.check","unknown"];const fieldEnums={operationId:OPERATIONAL_OPERATIONS,countBasis:["catalog_total","returned_entries","available_sources"],route:OPERATIONAL_ROUTES,profile:OPERATIONAL_PROFILES,loginDecision:OPERATIONAL_LOGIN_DECISIONS,selection:OPERATIONAL_SELECTIONS,trigger:OPERATIONAL_TRIGGERS,artifactFamily:OPERATIONAL_ARTIFACT_FAMILIES,artifactType:OPERATIONAL_ARTIFACT_TYPES,reason:OPERATIONAL_REASONS,errorCategory:OPERATIONAL_ERRORS,tool:USAGE_TOOL_NAMES,method:OPERATIONAL_TOOL_METHODS,entrypoint:USAGE_ENTRYPOINTS,downloadObservation:OPERATIONAL_DOWNLOAD_OBSERVATION,upstreamTool:OPERATIONAL_UPSTREAM_TOOLS,rpcMethod:OPERATIONAL_RPC_METHODS};const fieldKeys=[...Object.keys(fieldEnums),"observedCount","processRef","actionRef","sourceRef"],enumHas=(values,value)=>typeof value==="string"&&values.includes(value);const isOperationalReference=value=>typeof value==="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value);const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const closed=(value,keys)=>Object.keys(value).every(key=>keys.includes(key));function validFields(value){return Object.entries(fieldEnums).every(([key,values])=>value[key]===void 0||enumHas(values,value[key]))&&(value.observedCount===void 0?value.countBasis===void 0:Number.isSafeInteger(value.observedCount)&&Number(value.observedCount)>=0&&Number(value.observedCount)<=1e8&&value.countBasis!==void 0)&&["processRef","actionRef","sourceRef"].every(key=>value[key]===void 0||isOperationalReference(value[key]))}export function isOperationalContext(value){return object(value)&&closed(value,["runId","stepId"])&&isFlowId(value.runId)&&isFlowId(value.stepId)}export function isUsageOperationalTrace(value){if(!object(value)||!closed(value,["version","runId","stepId","parentStepId","emitterId","sequence","attempt","phase","action","state","terminal","durationKnown",...fieldKeys]))return false;return value.version===1&&isFlowId(value.runId)&&isFlowId(value.stepId)&&isFlowId(value.emitterId)&&(value.parentStepId===void 0||isFlowId(value.parentStepId)&&value.parentStepId!==value.stepId)&&Number.isSafeInteger(value.sequence)&&Number(value.sequence)>0&&Number(value.sequence)<=1e9&&Number.isSafeInteger(value.attempt)&&Number(value.attempt)>0&&Number(value.attempt)<=1e4&&enumHas(OPERATIONAL_PHASES,value.phase)&&enumHas(OPERATIONAL_ACTIONS,value.action)&&enumHas(OPERATIONAL_STATES,value.state)&&typeof value.terminal==="boolean"&&typeof value.durationKnown==="boolean"&&validFields(value)&&(["started","waiting"].includes(String(value.state))?!value.terminal&&!value.durationKnown:["completed","failed","cancelled"].includes(String(value.state))?value.terminal:!value.durationKnown||value.terminal)}export function operationalReason(value){return enumHas(OPERATIONAL_REASONS,value)?value:"unknown"}const executionContext=new AsyncLocalStorage;let emitterId=randomUUID(),sequence=0;function emissionOrder(){if(sequence>=1e9){emitterId=randomUUID();sequence=0}return{emitterId,sequence:++sequence}}export function withoutOperationalContext(run){return executionContext.exit(run)}export function currentOperationalExecution(){const value=executionContext.getStore();return value?{runId:value.runId,stepId:value.stepId}:void 0}export function withOperationalContext(input,run){const captured={...input};if(!isOperationalContext(captured))throw Error("Invalid operational context.");return executionContext.run(captured,run)}export function startOperationalRun(metrics,input){return executionContext.exit(()=>startOperationalStep(metrics,input))}export function startOperationalStep(metrics,input){const parent=executionContext.getStore(),fallback=currentFeedbackFlow()?.flowId??currentUsageInvocation()?.id;const scope={runId:parent?.runId??(isFlowId(fallback)?fallback:randomUUID()),stepId:randomUUID()};const pending=new Set;let fields,finished=false;const enabled=()=>{try{const value=metrics?.();return value?.isEnabled?.()===true?value:void 0}catch{return void 0}};const service=enabled();if(service)try{const value={...typeof input==="function"?input():input};if(closed(value,["runId","source","phase","action","attempt",...fieldKeys])&&enumHas(OPERATIONAL_PHASES,value.phase)&&enumHas(OPERATIONAL_ACTIONS,value.action)&&validFields(value)&&(value.runId===void 0||isFlowId(value.runId))&&(value.source===void 0||typeof value.source==="string")&&(value.attempt===void 0||Number.isSafeInteger(value.attempt)&&value.attempt>0&&value.attempt<=1e4)){if(value.source)try{const reference=service.sourceReference?.(value.source);if(isOperationalReference(reference))value.sourceRef=reference}catch{}fields=value;if(!parent&&isFlowId(value.runId))scope.runId=value.runId}}catch{}const started=performance.now();const emit=(state,terminal,extra={})=>{const target=enabled();if(!target||!fields)return;let details;try{details={...extra}}catch{return}if(!closed(details,fieldKeys)||!validFields(details))return;const combined=Object.fromEntries(Object.entries({...fields,...details}).filter(([key,value])=>fieldKeys.includes(key)&&value!==void 0));const elapsed=terminal?performance.now()-started:0;const durationKnown=terminal&&Number.isFinite(elapsed)&&elapsed>=0&&elapsed<=864e5;const durationMs=durationKnown?elapsed:0;const operational={version:1,runId:scope.runId,stepId:scope.stepId,...parent?{parentStepId:parent.stepId}:{},...emissionOrder(),attempt:fields.attempt??1,phase:fields.phase,action:fields.action,state,terminal,durationKnown,...combined};try{const result=executionContext.run(scope,()=>target.record({operation:"product.trace",internal:true,outcome:state==="completed"?"ok":state==="failed"?"fault":state==="cancelled"?"cancelled":"unknown",durationMs,...isTelemetrySourceId(fields.source)?{source:fields.source}:{},operational}));let timer;const bounded=Promise.race([Promise.resolve(result).then(()=>{},()=>{}),new Promise(resolve=>{timer=setTimeout(resolve,50)})]).then(()=>{if(timer)clearTimeout(timer)});pending.add(bounded);void bounded.finally(()=>pending.delete(bounded))}catch{}};const step={get runId(){return scope.runId},stepId:scope.stepId,run:fn=>executionContext.run(scope,fn),mark(value){try{if(finished||!fields||!enabled()||!value)return;const{state,...details}=value;if(["waiting","unknown"].includes(state))emit(state,false,details)}catch{}},finish(value){try{if(finished)return;finished=true;if(!fields||!enabled()||!value)return;const{state,...details}=value;if(["completed","failed","cancelled","unknown"].includes(state))emit(state,true,details)}catch{}},async flush(){await Promise.allSettled([...pending])}};emit("started",false);return step}export function operationalTraceSummary(events,collection={}){const steps=new Map,receipts=new Set;for(const row of events){if(receipts.has(row.id)||!isUsageOperationalTrace(row.operational))continue;receipts.add(row.id);const t=row.operational,key=t.runId+":"+t.stepId,step=steps.get(key)??{start:false,terminal:false};step.start||=t.state==="started";step.terminal||=t.terminal;steps.set(key,step)}const observed=steps.size>0,rows=[...steps.values()];return{coverage:"instrumented_steps_only",observation:collection.enabled===false?"disabled":observed?"observed":"unobserved",historyLimited:collection.limited===true,startedSteps:observed?rows.filter(s=>s.start).length:null,terminalSteps:observed?rows.filter(s=>s.terminal).length:null,unfinishedSteps:observed?rows.filter(s=>s.start&&!s.terminal).length:null,orphanTerminals:observed?rows.filter(s=>!s.start&&s.terminal).length:null}}
@@ -1 +1 @@
1
- export const TELEMETRY_OPERATIONS=["search","context","action","actions","action_result","append","feedback","manage","sql","done","instruction","handbook","mcp.call","product.first_start","product.started","product.account_signed_in","product.galaxy_opened","product.feedback","product.trace","product.resources","product.collection","connector.trace","connector.read","connector.invoke","connector.connect","connector.authorization","connector.fabricate","connector.usable","connector.sync","connector.inventory","connector.connection","flywheel.start","flywheel.run"];export const TELEMETRY_OUTCOMES=["ok","empty","fault","auth-blocked","cancelled","invalid","unknown"];export const AUTHORIZATION_REASON_CODES=["authorization_timeout","authorization_denied","browser_open_failed","connection_failed","google_connection_failed","provider_error","local_directory_unavailable","source_disabled","observation_timeout","job_unavailable","job_mismatch","host_closed","account_selection_required","browser_session_unavailable","browser_session_limit","browser_agent_continuation","consent_app_unverified","account_chooser_unavailable","chooser_rows_unavailable","grant_review_required","observation_failed","click_failed","stale_control","oauth_page_changed","unknown_google_page","cancelled","cancelled_or_timed_out","browser_cleanup_failed","jev_unavailable","invalid_jev_choice","driver_error","step_limit","unknown","invalid_authorization_request","notion_page_selection_required","login_required","task_expired","callback_mismatch","untrusted_origin","transaction_mismatch","transaction_mismatch_client_id","transaction_mismatch_state","transaction_mismatch_redirect_uri","transaction_mismatch_resource","transaction_mismatch_scope","transaction_mismatch_response_type","transaction_mismatch_code_challenge","transaction_mismatch_code_challenge_method","transaction_mismatch_iss","transaction_mismatch_user_scope","human_required","human_secure_control","human_textbox","human_challenge","human_unverified_warning","planner_human_handoff","account_not_found","ambiguous_accounts","account_chooser_skipped","app_identity_unconfirmed","browser_renderer_unavailable","no_safe_controls","too_many_controls","model_budget_exhausted","invalid_plan","planner_low_confidence","admin_approval_required","grounder_invalid_control","already_selected","repeated_action","untrusted_target","planner_aborted","planner_invalid_response","planner_missing_content","planner_output_too_large","planner_json_invalid","planner_step_invalid","planner_model_not_configured","provider_missing_key","jev_invalid_response","jev_low_confidence","jev_model_not_configured"];export function usageOutcome(result){if("err"in result){const code=result.err.code;return code==="failed_precondition"||code==="permission_denied"||code==="unauthenticated"?"auth-blocked":code==="aborted"?"cancelled":code==="invalid_argument"?"invalid":"fault"}if("empty"in result)return"empty";const value=result.ok;if(value&&typeof value==="object"){if("result"in value&&value.result&&typeof value.result==="object"&&"isError"in value.result&&value.result.isError===true)return"fault";const status="status"in value?value.status:void 0;const state=("state"in value?value.state:void 0)??(status&&typeof status==="object"&&"state"in status?status.state:status);if(state==="failed"||state==="FAILED")return"fault";if(state==="empty")return"empty";if(state==="cancelled")return"cancelled";if(typeof state==="string"&&["needs-user","needs_user","needs_you","waiting-user","AUTH_BLOCKED"].includes(state))return"auth-blocked";if(typeof state==="string"&&["pending","queued","running","waiting","unknown","confirmation_required"].includes(state))return"unknown";if("returned"in value&&value.returned===0||"items"in value&&Array.isArray(value.items)&&!value.items.length)return"empty"}return"ok"}
1
+ export const TELEMETRY_OPERATIONS=["search","context","action","actions","action_result","append","feedback","manage","sql","done","instruction","handbook","mcp.call","product.first_start","product.started","product.account_signed_in","product.galaxy_opened","product.feedback","product.trace","product.resources","product.collection","connector.trace","connector.read","connector.invoke","connector.connect","connector.authorization","connector.fabricate","connector.usable","connector.sync","connector.inventory","connector.connection","flywheel.start","flywheel.run"];export const TELEMETRY_OUTCOMES=["ok","empty","fault","auth-blocked","cancelled","invalid","unknown"];export const AUTHORIZATION_REASON_CODES=["authorization_timeout","authorization_denied","browser_open_failed","connection_failed","google_connection_failed","provider_error","local_directory_unavailable","source_disabled","observation_timeout","job_unavailable","job_mismatch","host_closed","account_selection_required","browser_session_unavailable","browser_session_limit","browser_agent_continuation","consent_app_unverified","account_chooser_unavailable","chooser_rows_unavailable","grant_review_required","observation_failed","click_failed","stale_control","oauth_page_changed","unknown_google_page","cancelled","cancelled_or_timed_out","browser_cleanup_failed","jev_unavailable","invalid_jev_choice","driver_error","step_limit","unknown","invalid_authorization_request","notion_page_selection_required","login_required","task_expired","callback_mismatch","untrusted_origin","transaction_mismatch","transaction_mismatch_client_id","transaction_mismatch_state","transaction_mismatch_redirect_uri","transaction_mismatch_resource","transaction_mismatch_scope","transaction_mismatch_response_type","transaction_mismatch_code_challenge","transaction_mismatch_code_challenge_method","transaction_mismatch_iss","transaction_mismatch_user_scope","human_required","human_secure_control","human_textbox","human_challenge","human_unverified_warning","planner_human_handoff","account_not_found","ambiguous_accounts","account_chooser_skipped","app_identity_unconfirmed","browser_renderer_unavailable","no_safe_controls","too_many_controls","model_budget_exhausted","invalid_plan","planner_low_confidence","admin_approval_required","grounder_invalid_control","already_selected","repeated_action","untrusted_target","planner_aborted","planner_invalid_response","planner_missing_content","planner_output_too_large","planner_json_invalid","planner_step_invalid","planner_model_not_configured","provider_missing_key","jev_invalid_response","jev_low_confidence","jev_model_not_configured"];export function usageOutcome(result){if("err"in result){const code=result.err.code;return code==="failed_precondition"||code==="permission_denied"||code==="unauthenticated"?"auth-blocked":code==="aborted"?"cancelled":code==="invalid_argument"?"invalid":"fault"}if("empty"in result)return"empty";const value=result.ok;if(value&&typeof value==="object"){if("result"in value&&value.result&&typeof value.result==="object"&&"isError"in value.result&&value.result.isError===true)return"fault";const status="status"in value?value.status:void 0;const state=("state"in value?value.state:void 0)??(status&&typeof status==="object"&&"state"in status?status.state:status);if(state==="failed"||state==="FAILED")return"fault";if(state==="empty")return"empty";if(state==="cancelled")return"cancelled";if(typeof state==="string"&&["needs-user","needs_user","needs_you","waiting-user","AUTH_BLOCKED"].includes(state))return"auth-blocked";if(typeof state==="string"&&["pending","queued","running","waiting","connecting","partial","unknown","confirmation_required"].includes(state))return"unknown";if("returned"in value&&value.returned===0||"items"in value&&Array.isArray(value.items)&&!value.items.length)return"empty"}return"ok"}
@@ -1 +1 @@
1
- import{AsyncLocalStorage}from"node:async_hooks";import{currentUsageInvocation,USAGE_ENTRYPOINTS,USAGE_TOOL_NAMES}from"./observations.js";import{OPERATIONAL_OPERATIONS,startOperationalStep}from"./operational.js";import{OPERATIONAL_TOOL_METHODS}from"./tool-methods.js";const calls=new AsyncLocalStorage;const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);function terminal(result){if(!object(result))return{state:"unknown"};const envelope=object(result.structuredContent)?result.structuredContent:result;if(object(envelope.err)){const code=envelope.err.code;if(code==="aborted"||code==="cancelled")return{state:"cancelled",reason:"cancelled"};const errorCategory=code==="deadline_exceeded"?"timeout":code==="unauthenticated"?"identity":code==="permission_denied"?"denied":envelope.err.layer==="storage"?"storage":"unknown";return{state:"failed",errorCategory}}if(result.isError===true)return{state:"failed",reason:"provider_failure",errorCategory:"provider"};if("ok"in envelope){if(object(envelope.ok)&&object(envelope.ok.result)&&envelope.ok.result.isError===true)return{state:"failed",reason:"provider_failure",errorCategory:"provider"};const value=object(envelope.ok)?envelope.ok:void 0,state=value?.state??(object(value?.status)?value.status.state:value?.status);if(typeof state==="string"&&["pending","queued","running","waiting","waiting-user","needs-user","needs_user","needs_you","AUTH_BLOCKED"].includes(state))return"waiting";if(state==="failed"||state==="FAILED")return{state:"failed",errorCategory:"unknown"};if(state==="cancelled")return{state:"cancelled",reason:"cancelled"};return{state:"completed"}}if("empty"in envelope)return{state:"completed"};return{state:"unknown"}}export function runOperationalToolCall(metrics,input,run,options={}){const invocation=currentUsageInvocation();if(invocation&&calls.getStore()?.invocationId===invocation.id)return run();let service,enabled=false;try{service=metrics?.();enabled=service?.isEnabled?.()===true}catch{}if(!enabled)return run();const step=startOperationalStep(()=>service,()=>{const value=typeof input==="function"?input():input;const tool=typeof value.tool==="string"&&USAGE_TOOL_NAMES.includes(value.tool)?value.tool:"unknown";const method=typeof value.method==="string"&&OPERATIONAL_TOOL_METHODS.includes(value.method)?value.method:"unknown";const entrypoint=typeof value.entrypoint==="string"&&USAGE_ENTRYPOINTS.includes(value.entrypoint)?value.entrypoint:invocation?.entrypoint??"unknown";const known=candidate=>typeof candidate==="string"&&OPERATIONAL_OPERATIONS.includes(candidate);const operationId=known(value.method)?value.method:known("tool."+tool)?"tool."+tool:"unknown";return{phase:"tool",action:"call",operationId,trigger:"agent_action",tool,method,entrypoint,...typeof value.source==="string"?{source:value.source}:{}}});const execute=()=>step.run(async()=>{try{const result=await run();try{if(service?.isEnabled?.()!==true)return result;const outcome=options.signal?.aborted?{state:"cancelled",reason:"cancelled"}:terminal(result);if(outcome==="waiting"){step.mark({state:"waiting"});step.finish({state:"unknown"})}else step.finish(outcome)}catch{step.finish({state:"unknown"})}return result}catch(error){step.finish(options.signal?.aborted?{state:"cancelled",reason:"cancelled"}:{state:"failed",errorCategory:"unknown"});throw error}});return invocation?calls.run({invocationId:invocation.id,step},execute):execute()}
1
+ import{AsyncLocalStorage}from"node:async_hooks";import{currentUsageInvocation,USAGE_ENTRYPOINTS,USAGE_TOOL_NAMES}from"./observations.js";import{OPERATIONAL_OPERATIONS,startOperationalStep}from"./operational.js";import{OPERATIONAL_TOOL_METHODS}from"./tool-methods.js";import{usageFindMeasurement}from"./measurement.js";const calls=new AsyncLocalStorage;const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);function terminal(result,contentFind=false){if(!object(result))return{state:"unknown"};const envelope=object(result.structuredContent)?result.structuredContent:result;if(object(envelope.err)){const code=envelope.err.code;if(code==="aborted"||code==="cancelled")return{state:"cancelled",reason:"cancelled"};const errorCategory=code==="deadline_exceeded"?"timeout":code==="unauthenticated"?"identity":code==="permission_denied"?"denied":envelope.err.layer==="storage"?"storage":"unknown";return{state:"failed",errorCategory}}if(result.isError===true)return{state:"failed",reason:"provider_failure",errorCategory:"provider"};if(contentFind&&("ok"in envelope||"empty"in envelope)){const measured=usageFindMeasurement(envelope);if(measured.search.state==="connecting"||measured.search.state==="needs_user")return"waiting";if(measured.outcome==="ok"||measured.outcome==="empty")return{state:"completed"};if(measured.outcome==="cancelled")return{state:"cancelled",reason:"cancelled"};if(measured.outcome==="fault"||measured.outcome==="auth-blocked"||measured.outcome==="invalid")return{state:"failed",...measured.errorCategory?{errorCategory:measured.errorCategory}:{}};return{state:"unknown"}}if("ok"in envelope){if(object(envelope.ok)&&object(envelope.ok.result)&&envelope.ok.result.isError===true)return{state:"failed",reason:"provider_failure",errorCategory:"provider"};const value=object(envelope.ok)?envelope.ok:void 0,state=value?.state??(object(value?.status)?value.status.state:value?.status);if(typeof state==="string"&&["pending","queued","running","connecting","waiting","waiting-user","needs-user","needs_user","needs_you","AUTH_BLOCKED"].includes(state))return"waiting";if(state==="failed"||state==="FAILED")return{state:"failed",errorCategory:value?.errorCode==="deadline_exceeded"?"timeout":value?.errorCode==="unauthenticated"?"identity":value?.errorCode==="permission_denied"?"denied":"unknown"};if(state==="partial"||state==="unknown"||state==="confirmation_required")return{state:"unknown"};if(state==="cancelled")return{state:"cancelled",reason:"cancelled"};return{state:"completed"}}if("empty"in envelope)return{state:"completed"};return{state:"unknown"}}export function runOperationalToolCall(metrics,input,run,options={}){const invocation=currentUsageInvocation();if(invocation&&calls.getStore()?.invocationId===invocation.id)return run();let service,enabled=false;try{service=metrics?.();enabled=service?.isEnabled?.()===true}catch{}if(!enabled)return run();let contentFind=false;const step=startOperationalStep(()=>service,()=>{const value=typeof input==="function"?input():input;const tool=typeof value.tool==="string"&&USAGE_TOOL_NAMES.includes(value.tool)?value.tool:"unknown";const method=typeof value.method==="string"&&OPERATIONAL_TOOL_METHODS.includes(value.method)?value.method:"unknown";contentFind=method==="connector.find";const entrypoint=typeof value.entrypoint==="string"&&USAGE_ENTRYPOINTS.includes(value.entrypoint)?value.entrypoint:invocation?.entrypoint??"unknown";const known=candidate=>typeof candidate==="string"&&OPERATIONAL_OPERATIONS.includes(candidate);const operationId=known(value.method)?value.method:known("tool."+tool)?"tool."+tool:"unknown";return{phase:"tool",action:"call",operationId,trigger:"agent_action",tool,method,entrypoint,...typeof value.source==="string"?{source:value.source}:{}}});const execute=()=>step.run(async()=>{try{const result=await run();try{if(service?.isEnabled?.()!==true)return result;const outcome=options.signal?.aborted?{state:"cancelled",reason:"cancelled"}:terminal(result,contentFind);if(outcome==="waiting"){step.mark({state:"waiting"});step.finish({state:"unknown"})}else step.finish(outcome)}catch{step.finish({state:"unknown"})}return result}catch(error){step.finish(options.signal?.aborted?{state:"cancelled",reason:"cancelled"}:{state:"failed",errorCategory:"unknown"});throw error}});return invocation?calls.run({invocationId:invocation.id,step},execute):execute()}
@@ -1 +1 @@
1
- export const OPERATIONAL_TOOL_METHODS=["connector.connect","connector.job","connector.status","connector.read","connector.invoke","connector.sync","connector.disconnect","connector.recover","fleet.run","fleet.receipt","browser.open","browser.observe","browser.click","browser.type","browser.scroll","browser.close","browser.run_goal","share.preview","share.create-link","share.inspect-link","share.read-file","unknown"];
1
+ export const OPERATIONAL_TOOL_METHODS=["connector.connect","connector.job","connector.status","connector.read","connector.find","connector.invoke","connector.sync","connector.disconnect","connector.recover","fleet.run","fleet.receipt","browser.open","browser.observe","browser.click","browser.type","browser.scroll","browser.close","browser.run_goal","share.preview","share.create-link","share.inspect-link","share.read-file","unknown"];
@@ -1 +1 @@
1
- import{DatabaseSync}from"node:sqlite";import{mkdir,lstat,realpath}from"node:fs/promises";import{isAbsolute,join,resolve}from"node:path";import{createHash,createHmac,randomUUID}from"node:crypto";import{localDeviceIdentity}from"./device-identity.js";import{businessError,canonicalJson,ok}from"@zortexhq/plugin-connector-framework/api";import{currentOperationalExecution}from"./api/operational.js";import{isUsageEvent,isUsageContext,isUsageFeedbackInput,isFlowId,snapshotUsageRecord,currentFeedbackFlow,currentTelemetryContext,currentUsageInvocation,isUsageObservation,snapshotUsageObservation,OBSERVATION_SNAPSHOT_INTERVAL_MS,OBSERVATION_SNAPSHOT_DAILY_LIMIT,feedbackEligible,FEEDBACK_CHANNELS}from"./api/index.js";export{aggregateUsage}from"./aggregate.js";export const name="zortex-telemetry";export const TELEMETRY_RETENTION_DAYS=30,TELEMETRY_MAX_EVENTS=5e4,TELEMETRY_MAX_RECORD_BYTES=2048;const DAY=864e5,FEEDBACK_DAYS=7;export async function createTelemetry({root,enabled=true,startup=false,newInstallation=false,context=currentTelemetryContext(),deviceIdentityFile},runtime={}){if(typeof newInstallation!=="boolean")throw Error("newInstallation must be boolean.");if(!isAbsolute(root)||typeof enabled!=="boolean"||typeof startup!=="boolean")throw Error("Telemetry root must be absolute; enabled must be boolean.");const deviceId=enabled&&context?.trafficClass!=="internal_test"&&context?.trafficClass!=="simulation"&&deviceIdentityFile?await localDeviceIdentity(deviceIdentityFile).catch(()=>void 0):void 0;const capturedContext=context||deviceId?Object.freeze({...context,...deviceId?{deviceId}:{}}):void 0;if(context!==void 0&&!isUsageContext(capturedContext))throw Error("Invalid telemetry runtime context.");await mkdir(root,{recursive:true,mode:448});if((await lstat(root)).isSymbolicLink())throw Error("Telemetry root cannot be a link.");const file=join(await realpath(root),"telemetry.sqlite");if((await lstat(file).catch(()=>null))?.isSymbolicLink())throw Error("Telemetry database cannot be a link.");const db=new DatabaseSync(file),now=runtime.now??Date.now;let created=false,userId="",actionSalt="",closed=false,initializing=false,nextAgeSweep=0;try{db.exec("PRAGMA busy_timeout=3000;PRAGMA journal_mode=WAL;BEGIN IMMEDIATE");initializing=true;db.exec("CREATE TABLE IF NOT EXISTS identity(id INTEGER PRIMARY KEY CHECK(id=1),user TEXT NOT NULL);CREATE TABLE IF NOT EXISTS usage(id TEXT PRIMARY KEY,at TEXT NOT NULL,operation TEXT NOT NULL,outcome TEXT NOT NULL,duration REAL NOT NULL,source TEXT,code TEXT,internal INTEGER NOT NULL DEFAULT 0);");const columns=new Set(db.prepare("PRAGMA table_info(usage)").all().map(column=>String(column.name)));for(const[column,type]of[["internal","INTEGER NOT NULL DEFAULT 0"],["trace","TEXT"],["metadata","TEXT"],["feedback_target","TEXT"],["feedback_channel","TEXT"],["observation_key","TEXT"],["observation_fingerprint","TEXT"],["observation_scope","TEXT"],["observation_recorded_at","INTEGER"]])if(!columns.has(column))db.exec(`ALTER TABLE usage ADD COLUMN ${column} ${type}`);created=Number(db.prepare("INSERT OR IGNORE INTO identity(id,user) VALUES(1,?)").run(randomUUID()).changes)===1;userId=String(db.prepare("SELECT user FROM identity").get().user);if(!db.prepare("PRAGMA table_info(identity)").all().some(column=>column.name==="action_salt"))db.exec("ALTER TABLE identity ADD COLUMN action_salt TEXT");if(enabled){db.prepare("UPDATE identity SET action_salt=? WHERE id=1 AND action_salt IS NULL").run(randomUUID());actionSalt=String(db.prepare("SELECT action_salt FROM identity WHERE id=1").get().action_salt)}db.exec("CREATE TABLE IF NOT EXISTS usage_export_seq(seq INTEGER PRIMARY KEY AUTOINCREMENT,event_id TEXT UNIQUE NOT NULL);CREATE TABLE IF NOT EXISTS collection_state(id INTEGER PRIMARY KEY CHECK(id=1),retained_events INTEGER NOT NULL,pruned_events INTEGER NOT NULL DEFAULT 0,retention_floor INTEGER NOT NULL DEFAULT 0,sequence_backfilled INTEGER NOT NULL DEFAULT 0);");if(!db.prepare("SELECT id FROM collection_state WHERE id=1").get())db.exec("INSERT INTO collection_state(id,retained_events) SELECT 1,COUNT(*) FROM usage;");if(!db.prepare("SELECT sequence_backfilled FROM collection_state WHERE id=1").get().sequence_backfilled){db.exec("INSERT OR IGNORE INTO usage_export_seq(event_id) SELECT id FROM usage ORDER BY at,id;UPDATE collection_state SET sequence_backfilled=1 WHERE id=1;")}db.exec("CREATE INDEX IF NOT EXISTS usage_at ON usage(at,id);CREATE UNIQUE INDEX IF NOT EXISTS usage_feedback_once ON usage(feedback_target,feedback_channel) WHERE feedback_target IS NOT NULL;CREATE UNIQUE INDEX IF NOT EXISTS usage_observation_once ON usage(observation_key) WHERE observation_key IS NOT NULL;CREATE INDEX IF NOT EXISTS usage_observation_scope ON usage(observation_scope,observation_recorded_at) WHERE observation_scope IS NOT NULL;CREATE INDEX IF NOT EXISTS usage_observation_budget ON usage(observation_recorded_at) WHERE observation_scope IS NOT NULL;CREATE TABLE IF NOT EXISTS observation_counters(id INTEGER PRIMARY KEY CHECK(id=1),rate_limited INTEGER NOT NULL DEFAULT 0,budget_limited INTEGER NOT NULL DEFAULT 0,unchanged INTEGER NOT NULL DEFAULT 0,duplicates INTEGER NOT NULL DEFAULT 0,last_suppressed_at TEXT);INSERT OR IGNORE INTO observation_counters(id) VALUES(1);CREATE TRIGGER IF NOT EXISTS usage_count_insert AFTER INSERT ON usage BEGIN UPDATE collection_state SET retained_events=retained_events+1 WHERE id=1;END;CREATE TRIGGER IF NOT EXISTS usage_count_delete AFTER DELETE ON usage BEGIN UPDATE collection_state SET retained_events=retained_events-1 WHERE id=1;END;COMMIT;PRAGMA busy_timeout=20;");initializing=false}catch(error){if(initializing){try{db.exec("ROLLBACK")}catch{}}db.close();throw error}const state=db.prepare("SELECT retained_events,pruned_events,retention_floor FROM collection_state WHERE id=1");const add=db.prepare("INSERT OR IGNORE INTO usage(id,at,operation,outcome,duration,source,code,internal,trace,metadata,feedback_target,feedback_channel) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)");const addSequence=db.prepare("INSERT INTO usage_export_seq(event_id) VALUES(?)");const byId=db.prepare("SELECT * FROM usage WHERE id=?");const byFeedback=db.prepare("SELECT * FROM usage WHERE feedback_target=? AND feedback_channel=?");const pageQuery=db.prepare("SELECT s.seq,u.* FROM usage_export_seq s JOIN usage u ON u.id=s.event_id WHERE s.seq>? ORDER BY s.seq LIMIT ?");const pruneFacts=db.prepare("SELECT COUNT(*) AS n,COALESCE(MAX(s.seq),0) AS last_seq FROM usage_export_seq s JOIN usage u ON u.id=s.event_id WHERE u.id IN (SELECT id FROM usage WHERE id<>? AND at<? ORDER BY at,id LIMIT ?)");const pruneSequences=db.prepare("DELETE FROM usage_export_seq WHERE event_id IN (SELECT id FROM usage WHERE id<>? AND at<? ORDER BY at,id LIMIT ?)");const pruneRows=db.prepare("DELETE FROM usage WHERE id IN (SELECT id FROM usage WHERE id<>? AND at<? ORDER BY at,id LIMIT ?)");const rememberPruning=db.prepare("UPDATE collection_state SET pruned_events=pruned_events+?,retention_floor=MAX(retention_floor,?) WHERE id=1");const oldest=db.prepare("SELECT MIN(at) AS at FROM usage WHERE id<>?");const observationByKey=db.prepare("SELECT id,observation_fingerprint FROM usage WHERE observation_key=?");const lastSnapshot=db.prepare("SELECT observation_fingerprint,observation_recorded_at FROM usage WHERE observation_scope=? ORDER BY observation_recorded_at DESC,id DESC LIMIT 1");const snapshotBudget=db.prepare("SELECT COUNT(*) AS n FROM usage WHERE observation_scope IS NOT NULL AND observation_recorded_at>=? AND observation_recorded_at<?");const observationMetadata=db.prepare("UPDATE usage SET observation_key=?,observation_fingerprint=?,observation_scope=?,observation_recorded_at=? WHERE id=?");const observationCounters=db.prepare("SELECT * FROM observation_counters WHERE id=1");const perform=async fn=>{if(closed)return businessError("unavailable","Telemetry is inactive.","storage");try{return fn()}catch(error){return businessError(error.errcode===5?"unavailable":"data_loss","Telemetry operation failed.","storage")}};const captureIdentity=enabled?{producerRef:randomUUID(),since:new Date(now()).toISOString()}:void 0;const captureCounts={attempted:0,accepted:0,suppressed:0,rejected:0,failed:0};const capture=async fn=>{if(!enabled||closed)return perform(fn);captureCounts.attempted++;const result=await perform(fn);if("ok"in result)captureCounts[result.ok.recorded?"accepted":"suppressed"]++;else if("err"in result&&["invalid_argument","already_exists"].includes(result.err.code))captureCounts.rejected++;else captureCounts.failed++;return result};function collection(after=0){const row=state.get(),stats=observationCounters.get();return{retainedEvents:Number(row.retained_events),prunedEvents:Number(row.pruned_events),retentionFloor:Number(row.retention_floor),limited:after<Number(row.retention_floor),retentionDays:TELEMETRY_RETENTION_DAYS,maxEvents:TELEMETRY_MAX_EVENTS,oldestAvailableAt:oldest.get(userId).at,observations:{snapshotRateLimited:Number(stats.rate_limited),snapshotBudgetLimited:Number(stats.budget_limited),snapshotUnchanged:Number(stats.unchanged),duplicates:Number(stats.duplicates),lastSuppressedAt:stats.last_suppressed_at}}}function decode(row){const metadata=row.metadata?JSON.parse(String(row.metadata)):{};return{id:String(row.id),at:String(row.at),operation:String(row.operation),outcome:String(row.outcome),durationMs:Number(row.duration),...row.source?{source:String(row.source)}:{},...row.code?{code:String(row.code)}:{},...row.internal?{internal:true}:{},...row.trace?{trace:JSON.parse(String(row.trace))}:{},...metadata}}function prune(cutoff,limit){const facts=pruneFacts.get(userId,cutoff,limit);if(!Number(facts.n))return;pruneSequences.run(userId,cutoff,limit);pruneRows.run(userId,cutoff,limit);rememberPruning.run(Number(facts.n),Number(facts.last_seq))}function maintain(){const now2=Date.now();if(now2>=nextAgeSweep){prune(new Date(now2-TELEMETRY_RETENTION_DAYS*DAY).toISOString(),2147483647);nextAgeSweep=now2+6e4}const excess=Number(state.get().retained_events)-TELEMETRY_MAX_EVENTS;if(excess>0)prune("9999-12-31T23:59:59.999Z",excess+Math.min(255,TELEMETRY_MAX_EVENTS-1))}function insert(event,id=randomUUID(),transaction=true,at=new Date().toISOString()){const execution=["product.resources","product.collection"].includes(event.operation)?void 0:currentOperationalExecution();const record={...event,id,at,...capturedContext?{context:capturedContext}:{},...execution?{execution}:{}};if(Buffer.byteLength(JSON.stringify(record))>TELEMETRY_MAX_RECORD_BYTES)throw Error("Telemetry record exceeds its closed metadata budget.");const metadata={...record.context?{context:record.context}:{},...record.execution?{execution:record.execution}:{},...event.operational?{operational:event.operational}:{},...event.resource?{resource:event.resource}:{},...event.collectionStatus?{collectionStatus:event.collectionStatus}:{},...event.result?{result:event.result}:{},...event.correlation?{correlation:event.correlation}:{},...event.errorCategory?{errorCategory:event.errorCategory}:{},...event.feedback?{feedback:event.feedback}:{},...event.observation?{observation:event.observation}:{},...event.invocation?{invocation:event.invocation}:{}};if(transaction)db.exec("BEGIN IMMEDIATE");try{const inserted=add.run(id,at,event.operation,event.outcome,event.durationMs,event.source??null,event.code??null,Number(event.internal??false),event.trace?JSON.stringify(event.trace):null,Object.keys(metadata).length?JSON.stringify(metadata):null,event.feedback?.targetReceiptId??null,event.feedback?.submissionChannel??null);if(Number(inserted.changes))addSequence.run(id);maintain();if(transaction)db.exec("COMMIT");return id}catch(error){if(transaction)db.exec("ROLLBACK");throw error}}if(enabled){try{db.exec("BEGIN IMMEDIATE");maintain();db.exec("COMMIT")}catch(error){try{db.exec("ROLLBACK")}catch{}db.close();throw error}}if(startup&&enabled){insert({operation:"product.first_start",outcome:"ok",durationMs:0,internal:true,code:created&&newInstallation?"new_install":"first_observed"},userId);insert({operation:"product.started",outcome:"ok",durationMs:0,internal:true})}const service={isEnabled:()=>enabled&&!closed,collectionStats:()=>!enabled||closed||!captureIdentity?void 0:{...captureIdentity,scope:"record_and_observe_api_calls",...captureCounts,pending:captureCounts.attempted-captureCounts.accepted-captureCounts.suppressed-captureCounts.rejected-captureCounts.failed},sourceReference(source){if(!enabled||closed||!actionSalt||typeof source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(source))return;const hash=createHmac("sha256",actionSalt).update(JSON.stringify(["zortex-source-v1",source])).digest("hex");return hash.slice(0,8)+"-"+hash.slice(8,12)+"-8"+hash.slice(13,16)+"-a"+hash.slice(17,20)+"-"+hash.slice(20,32)},actionReference(source,method){if(!enabled||closed||!actionSalt||typeof source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof method!=="string"||!method.length||Buffer.byteLength(method)>512)return;const hash=createHmac("sha256",actionSalt).update(JSON.stringify(["zortex-action-v2",source,method])).digest("hex");return hash.slice(0,8)+"-"+hash.slice(8,12)+"-8"+hash.slice(13,16)+"-a"+hash.slice(17,20)+"-"+hash.slice(20,32)},observe:input=>capture(()=>{if(!enabled)return ok({recorded:false,reason:"disabled"});const snapshot=snapshotUsageObservation(input);if(!isUsageObservation(snapshot))return businessError("invalid_argument","Observation accepts only fixed, content-free metadata and known counts.","storage");const{key,source,at,...rawFacts}=snapshot;const facts=Object.fromEntries(Object.entries(rawFacts).filter(([,value])=>value!==void 0));if(facts.kind==="connection")facts.capabilities=[...facts.capabilities].sort();const hash=value=>createHash("sha256").update(canonicalJson(value)).digest("hex");const observationKey=hash(["zortex-observation-v1",userId,snapshot.kind,source,key]);const fingerprint=hash({source,facts});const receiptId=observationKey.slice(0,8)+"-"+observationKey.slice(8,12)+"-5"+observationKey.slice(13,16)+"-a"+observationKey.slice(17,20)+"-"+observationKey.slice(20,32);const recordedAt=now(),observedAt=at??new Date(recordedAt).toISOString();const scope=facts.kind==="sync"?null:hash([facts.kind,source,facts.connectionRef??null,...facts.kind==="inventory"?[facts.population,facts.attribution]:[]]);db.exec("BEGIN IMMEDIATE");try{const prior=observationByKey.get(observationKey);if(prior){if(prior.observation_fingerprint!==fingerprint){db.exec("COMMIT");return businessError("already_exists","This observation key already has different metadata.","storage")}db.exec("UPDATE observation_counters SET duplicates=duplicates+1 WHERE id=1");db.exec("COMMIT");return ok({recorded:false,reason:"duplicate",receiptId:String(prior.id)})}if(scope){const previous=lastSnapshot.get(scope),elapsed=recordedAt-Number(previous?.observation_recorded_at??0);const unchanged=previous&&previous.observation_fingerprint===fingerprint&&elapsed<DAY;const limited=previous&&elapsed<OBSERVATION_SNAPSHOT_INTERVAL_MS;const dayStart=Math.floor(recordedAt/DAY)*DAY;const budget=Number(snapshotBudget.get(dayStart,dayStart+DAY).n)>=OBSERVATION_SNAPSHOT_DAILY_LIMIT;if(unchanged||limited||budget){const field=unchanged?"unchanged":limited?"rate_limited":"budget_limited";db.prepare(`UPDATE observation_counters SET ${field}=${field}+1,last_suppressed_at=? WHERE id=1`).run(new Date(recordedAt).toISOString());db.exec("COMMIT");return ok({recorded:false,reason:unchanged?"unchanged":"rate_limited"})}}const outcome=facts.kind!=="sync"?"ok":facts.status==="completed"?"ok":facts.status==="cancelled"?"cancelled":facts.status==="failed"||facts.status==="cleanup_blocked"?"fault":"unknown";insert({operation:"connector."+facts.kind,outcome,durationMs:facts.kind==="sync"?facts.durationMs:0,source,internal:true,observation:facts},receiptId,false,observedAt);observationMetadata.run(observationKey,fingerprint,scope,recordedAt,receiptId);db.exec("COMMIT");return ok({recorded:true,reason:"recorded",receiptId})}catch(error){db.exec("ROLLBACK");throw error}}),record:input=>capture(()=>{if(!enabled)return ok({recorded:false});const snapshot=snapshotUsageRecord(input);if(!isUsageEvent(snapshot)||snapshot.operation==="product.feedback"||snapshot.operation==="product.first_start")return businessError("invalid_argument","Usage accepts only content-free fields; startup and feedback anchors are provider-owned.","storage");const event=snapshot,flow=currentFeedbackFlow();if(!["product.resources","product.collection"].includes(event.operation)&&!event.correlation&&flow&&(!event.source||event.source===flow.source)&&isFlowId(flow.flowId))event.correlation={flowId:flow.flowId,...isFlowId(flow.connectionFlowId)?{connectionFlowId:flow.connectionFlowId}:{}};const invocation=["product.resources","product.collection"].includes(event.operation)?void 0:currentUsageInvocation();const measuredAt=event.resource?.asOf??event.collectionStatus?.asOf;return ok({recorded:true,receiptId:insert({...event,...invocation?{invocation:{...invocation}}:{}},void 0,true,measuredAt)})}),readBatch:({after=0,limit=500})=>perform(()=>{if(!Number.isSafeInteger(after)||after<0||!Number.isInteger(limit)||limit<1||limit>1e3)return businessError("invalid_argument","Usage paging needs an ordered cursor and 1\u20131000 events.","storage");const found=pageQuery.all(after,limit+1),selected=found.slice(0,limit);return ok({format:"zortex-usage/v1",userId,enabled,cursor:selected.length?Number(selected.at(-1).seq):after,more:found.length>limit,eventCursors:selected.map(row=>Number(row.seq)),events:selected.map(decode),collection:collection(after)})}),export:()=>perform(()=>{const events=db.prepare("SELECT * FROM usage ORDER BY at,id LIMIT 100001").all().map(decode);if(events.length>1e5)return businessError("resource_exhausted","Usage export exceeds its batch limit.","storage");return ok({format:"zortex-usage/v1",userId,enabled,events,collection:collection()})}),recent:({limit=5}={})=>perform(()=>{if(!Number.isInteger(limit)||limit<1||limit>20)return businessError("invalid_argument","Recent feedback needs a limit from 1 to 20.","storage");if(!enabled)return ok({enabled,events:[]});const rows=db.prepare("SELECT * FROM usage WHERE at>=? AND at<=? AND (operation IN ('search','context','sql','connector.read','connector.invoke') OR operation='action' AND code='effective_invoke') AND (internal=0 OR operation IN ('connector.read','connector.invoke')) ORDER BY at DESC,id DESC LIMIT ?").all(new Date(Date.now()-FEEDBACK_DAYS*DAY).toISOString(),new Date().toISOString(),limit);return ok({enabled,events:rows.map(row=>{const event=decode(row);return{receiptId:event.id,at:event.at,operation:event.operation,outcome:event.outcome,durationMs:event.durationMs,...event.source?{source:event.source}:{},...event.context?{context:event.context}:{},...event.result?{result:event.result}:{}}})})}),recordFeedback:(input,channel)=>perform(()=>{input={...input};channel={...channel};if(!isUsageFeedbackInput(input)||!channel||Object.keys(channel).some(key=>key!=="submissionChannel")||!FEEDBACK_CHANNELS.includes(channel.submissionChannel))return businessError("invalid_argument","Feedback needs one recent receipt, a fixed rating and an optional fixed reason.","storage");if(!enabled)return ok({recorded:false,delivery:"disabled"});db.exec("BEGIN IMMEDIATE");try{const prior=byFeedback.get(input.receiptId,channel.submissionChannel);if(prior){const feedback2=decode(prior).feedback;db.exec("COMMIT");return feedback2.rating===input.rating&&feedback2.reason===input.reason?ok({recorded:false,delivery:"queued",receiptId:String(prior.id)}):businessError("already_exists","This operation already has a different report through this channel.","storage")}const row=byId.get(input.receiptId);if(!row){db.exec("COMMIT");return businessError("not_found","The operation receipt is not available on this installation.","storage")}const target=decode(row),age=Date.now()-Date.parse(target.at);if(!feedbackEligible(target)||age<0||age>FEEDBACK_DAYS*DAY){db.exec("COMMIT");return businessError("failed_precondition","Feedback requires an eligible operation from the last seven days.","storage")}const feedback={targetReceiptId:target.id,rating:input.rating,...input.reason?{reason:input.reason}:{},submissionChannel:channel.submissionChannel,target:{operation:target.operation,outcome:target.outcome,at:target.at,...target.source?{source:target.source}:{},...target.context?{context:target.context}:{},...target.result?{result:target.result}:{}}};const receiptId=insert({operation:"product.feedback",outcome:"ok",durationMs:0,internal:true,feedback},randomUUID(),false);db.exec("COMMIT");return ok({recorded:true,delivery:"queued",receiptId})}catch(error){db.exec("ROLLBACK");throw error}}),report:()=>perform(()=>{const total=db.prepare("SELECT COUNT(*) AS calls,COALESCE(SUM(duration),0) AS duration FROM usage WHERE internal=0 AND operation NOT IN ('flywheel.start','flywheel.run','product.feedback')").get();const flywheel=db.prepare("SELECT COUNT(*) FILTER(WHERE operation='flywheel.start') AS started,COUNT(*) FILTER(WHERE operation='flywheel.run' AND outcome IN ('ok','empty')) AS completed,COUNT(*) FILTER(WHERE operation='flywheel.run' AND outcome='fault') AS failed FROM usage").get();const rows=db.prepare("SELECT source,COUNT(*) FILTER(WHERE outcome IN ('ok','empty','fault')) AS attempted,COUNT(*) FILTER(WHERE outcome='fault') AS faults,COUNT(*) FILTER(WHERE outcome='auth-blocked') AS authBlocked,COUNT(*) FILTER(WHERE outcome='cancelled') AS cancelled,COUNT(*) FILTER(WHERE outcome='invalid') AS invalid FROM usage WHERE operation IN ('connector.read','connector.invoke') AND source IS NOT NULL GROUP BY source ORDER BY source").all();const fabrication=db.prepare("SELECT source,COUNT(*) FILTER(WHERE outcome='ok') AS completed,COUNT(*) FILTER(WHERE outcome='fault') AS failed,COALESCE(SUM(duration),0) AS duration FROM usage WHERE operation='connector.fabricate' AND source IS NOT NULL GROUP BY source ORDER BY source").all();const usable=db.prepare("SELECT COUNT(*) AS n FROM usage_export_seq s JOIN usage u ON u.id=s.event_id WHERE u.operation='connector.usable' AND u.source IS NOT NULL AND u.outcome='ok' AND s.seq=(SELECT MAX(s2.seq) FROM usage_export_seq s2 JOIN usage u2 ON u2.id=s2.event_id WHERE u2.operation='connector.usable' AND u2.source=u.source)").get();return ok({enabled,userId,calls:Number(total.calls),durationMs:Number(total.duration),flywheel:{started:Number(flywheel.started),completed:Number(flywheel.completed),failed:Number(flywheel.failed)},connectors:rows.map(row=>({source:String(row.source),attempted:Number(row.attempted),faults:Number(row.faults),faultRate:Number(row.attempted)?Number(row.faults)/Number(row.attempted):null,authBlocked:Number(row.authBlocked),cancelled:Number(row.cancelled),invalid:Number(row.invalid)})),fabrication:fabrication.map(row=>({source:String(row.source),completed:Number(row.completed),failed:Number(row.failed),durationMs:Number(row.duration)})),usableConnectors:Number(usable.n),collection:collection()})}),async close(){if(!closed){closed=true;db.close()}}};return service}export async function apply(ctx,config){const freshRoot=process.env.ZORTEX_TELEMETRY_NEW_INSTALL_ROOT;const newInstallation=config.newInstallation??!!(freshRoot&&isAbsolute(freshRoot)&&typeof config.root==="string"&&resolve(freshRoot)===resolve(config.root));const service=await createTelemetry({...config,newInstallation,startup:config.startup??true});ctx.provide("zortexTelemetry",service);ctx.effect(()=>()=>service.close())}
1
+ import{DatabaseSync}from"node:sqlite";import{mkdir,lstat,realpath}from"node:fs/promises";import{isAbsolute,join,resolve}from"node:path";import{createHash,createHmac,randomUUID}from"node:crypto";import{localDeviceIdentity}from"./device-identity.js";import{businessError,canonicalJson,ok}from"@zortexhq/plugin-connector-framework/api";import{currentOperationalExecution}from"./api/operational.js";import{isUsageEvent,isUsageContext,isUsageFeedbackInput,isFlowId,snapshotUsageRecord,currentFeedbackFlow,currentTelemetryContext,currentUsageInvocation,isUsageObservation,snapshotUsageObservation,OBSERVATION_SNAPSHOT_INTERVAL_MS,OBSERVATION_SNAPSHOT_DAILY_LIMIT,feedbackEligible,FEEDBACK_CHANNELS}from"./api/index.js";export{aggregateUsage}from"./aggregate.js";export const name="zortex-telemetry";export const TELEMETRY_RETENTION_DAYS=30,TELEMETRY_MAX_EVENTS=5e4,TELEMETRY_MAX_RECORD_BYTES=2048;const DAY=864e5,FEEDBACK_DAYS=7;export async function createTelemetry({root,enabled=true,startup=false,newInstallation=false,context=currentTelemetryContext(),deviceIdentityFile},runtime={}){if(typeof newInstallation!=="boolean")throw Error("newInstallation must be boolean.");if(!isAbsolute(root)||typeof enabled!=="boolean"||typeof startup!=="boolean")throw Error("Telemetry root must be absolute; enabled must be boolean.");const deviceId=enabled&&context?.trafficClass!=="internal_test"&&context?.trafficClass!=="simulation"&&deviceIdentityFile?await localDeviceIdentity(deviceIdentityFile).catch(()=>void 0):void 0;const capturedContext=context||deviceId?Object.freeze({...context,...deviceId?{deviceId}:{}}):void 0;if(context!==void 0&&!isUsageContext(capturedContext))throw Error("Invalid telemetry runtime context.");await mkdir(root,{recursive:true,mode:448});if((await lstat(root)).isSymbolicLink())throw Error("Telemetry root cannot be a link.");const file=join(await realpath(root),"telemetry.sqlite");if((await lstat(file).catch(()=>null))?.isSymbolicLink())throw Error("Telemetry database cannot be a link.");const db=new DatabaseSync(file),now=runtime.now??Date.now;let created=false,userId="",actionSalt="",closed=false,initializing=false,nextAgeSweep=0;try{db.exec("PRAGMA busy_timeout=3000;PRAGMA journal_mode=WAL;BEGIN IMMEDIATE");initializing=true;db.exec("CREATE TABLE IF NOT EXISTS identity(id INTEGER PRIMARY KEY CHECK(id=1),user TEXT NOT NULL);CREATE TABLE IF NOT EXISTS usage(id TEXT PRIMARY KEY,at TEXT NOT NULL,operation TEXT NOT NULL,outcome TEXT NOT NULL,duration REAL NOT NULL,source TEXT,code TEXT,internal INTEGER NOT NULL DEFAULT 0);");const columns=new Set(db.prepare("PRAGMA table_info(usage)").all().map(column=>String(column.name)));for(const[column,type]of[["internal","INTEGER NOT NULL DEFAULT 0"],["trace","TEXT"],["metadata","TEXT"],["feedback_target","TEXT"],["feedback_channel","TEXT"],["observation_key","TEXT"],["observation_fingerprint","TEXT"],["observation_scope","TEXT"],["observation_recorded_at","INTEGER"]])if(!columns.has(column))db.exec(`ALTER TABLE usage ADD COLUMN ${column} ${type}`);created=Number(db.prepare("INSERT OR IGNORE INTO identity(id,user) VALUES(1,?)").run(randomUUID()).changes)===1;userId=String(db.prepare("SELECT user FROM identity").get().user);if(!db.prepare("PRAGMA table_info(identity)").all().some(column=>column.name==="action_salt"))db.exec("ALTER TABLE identity ADD COLUMN action_salt TEXT");if(enabled){db.prepare("UPDATE identity SET action_salt=? WHERE id=1 AND action_salt IS NULL").run(randomUUID());actionSalt=String(db.prepare("SELECT action_salt FROM identity WHERE id=1").get().action_salt)}db.exec("CREATE TABLE IF NOT EXISTS usage_export_seq(seq INTEGER PRIMARY KEY AUTOINCREMENT,event_id TEXT UNIQUE NOT NULL);CREATE TABLE IF NOT EXISTS collection_state(id INTEGER PRIMARY KEY CHECK(id=1),retained_events INTEGER NOT NULL,pruned_events INTEGER NOT NULL DEFAULT 0,retention_floor INTEGER NOT NULL DEFAULT 0,sequence_backfilled INTEGER NOT NULL DEFAULT 0);");if(!db.prepare("SELECT id FROM collection_state WHERE id=1").get())db.exec("INSERT INTO collection_state(id,retained_events) SELECT 1,COUNT(*) FROM usage;");if(!db.prepare("SELECT sequence_backfilled FROM collection_state WHERE id=1").get().sequence_backfilled){db.exec("INSERT OR IGNORE INTO usage_export_seq(event_id) SELECT id FROM usage ORDER BY at,id;UPDATE collection_state SET sequence_backfilled=1 WHERE id=1;")}db.exec("CREATE INDEX IF NOT EXISTS usage_at ON usage(at,id);CREATE UNIQUE INDEX IF NOT EXISTS usage_feedback_once ON usage(feedback_target,feedback_channel) WHERE feedback_target IS NOT NULL;CREATE UNIQUE INDEX IF NOT EXISTS usage_observation_once ON usage(observation_key) WHERE observation_key IS NOT NULL;CREATE INDEX IF NOT EXISTS usage_observation_scope ON usage(observation_scope,observation_recorded_at) WHERE observation_scope IS NOT NULL;CREATE INDEX IF NOT EXISTS usage_observation_budget ON usage(observation_recorded_at) WHERE observation_scope IS NOT NULL;CREATE TABLE IF NOT EXISTS observation_counters(id INTEGER PRIMARY KEY CHECK(id=1),rate_limited INTEGER NOT NULL DEFAULT 0,budget_limited INTEGER NOT NULL DEFAULT 0,unchanged INTEGER NOT NULL DEFAULT 0,duplicates INTEGER NOT NULL DEFAULT 0,last_suppressed_at TEXT);INSERT OR IGNORE INTO observation_counters(id) VALUES(1);CREATE TRIGGER IF NOT EXISTS usage_count_insert AFTER INSERT ON usage BEGIN UPDATE collection_state SET retained_events=retained_events+1 WHERE id=1;END;CREATE TRIGGER IF NOT EXISTS usage_count_delete AFTER DELETE ON usage BEGIN UPDATE collection_state SET retained_events=retained_events-1 WHERE id=1;END;COMMIT;PRAGMA busy_timeout=20;");initializing=false}catch(error){if(initializing){try{db.exec("ROLLBACK")}catch{}}db.close();throw error}const state=db.prepare("SELECT retained_events,pruned_events,retention_floor FROM collection_state WHERE id=1");const add=db.prepare("INSERT OR IGNORE INTO usage(id,at,operation,outcome,duration,source,code,internal,trace,metadata,feedback_target,feedback_channel) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)");const addSequence=db.prepare("INSERT INTO usage_export_seq(event_id) VALUES(?)");const byId=db.prepare("SELECT * FROM usage WHERE id=?");const byFeedback=db.prepare("SELECT * FROM usage WHERE feedback_target=? AND feedback_channel=?");const pageQuery=db.prepare("SELECT s.seq,u.* FROM usage_export_seq s JOIN usage u ON u.id=s.event_id WHERE s.seq>? ORDER BY s.seq LIMIT ?");const pruneFacts=db.prepare("SELECT COUNT(*) AS n,COALESCE(MAX(s.seq),0) AS last_seq FROM usage_export_seq s JOIN usage u ON u.id=s.event_id WHERE u.id IN (SELECT id FROM usage WHERE id<>? AND at<? ORDER BY at,id LIMIT ?)");const pruneSequences=db.prepare("DELETE FROM usage_export_seq WHERE event_id IN (SELECT id FROM usage WHERE id<>? AND at<? ORDER BY at,id LIMIT ?)");const pruneRows=db.prepare("DELETE FROM usage WHERE id IN (SELECT id FROM usage WHERE id<>? AND at<? ORDER BY at,id LIMIT ?)");const rememberPruning=db.prepare("UPDATE collection_state SET pruned_events=pruned_events+?,retention_floor=MAX(retention_floor,?) WHERE id=1");const oldest=db.prepare("SELECT MIN(at) AS at FROM usage WHERE id<>?");const observationByKey=db.prepare("SELECT id,observation_fingerprint FROM usage WHERE observation_key=?");const lastSnapshot=db.prepare("SELECT observation_fingerprint,observation_recorded_at FROM usage WHERE observation_scope=? ORDER BY observation_recorded_at DESC,id DESC LIMIT 1");const snapshotBudget=db.prepare("SELECT COUNT(*) AS n FROM usage WHERE observation_scope IS NOT NULL AND observation_recorded_at>=? AND observation_recorded_at<?");const observationMetadata=db.prepare("UPDATE usage SET observation_key=?,observation_fingerprint=?,observation_scope=?,observation_recorded_at=? WHERE id=?");const observationCounters=db.prepare("SELECT * FROM observation_counters WHERE id=1");const perform=async fn=>{if(closed)return businessError("unavailable","Telemetry is inactive.","storage");try{return fn()}catch(error){return businessError(error.errcode===5?"unavailable":"data_loss","Telemetry operation failed.","storage")}};const captureIdentity=enabled?{producerRef:randomUUID(),since:new Date(now()).toISOString()}:void 0;const captureCounts={attempted:0,accepted:0,suppressed:0,rejected:0,failed:0};const capture=async fn=>{if(!enabled||closed)return perform(fn);captureCounts.attempted++;const result=await perform(fn);if("ok"in result)captureCounts[result.ok.recorded?"accepted":"suppressed"]++;else if("err"in result&&["invalid_argument","already_exists"].includes(result.err.code))captureCounts.rejected++;else captureCounts.failed++;return result};function collection(after=0){const row=state.get(),stats=observationCounters.get();return{retainedEvents:Number(row.retained_events),prunedEvents:Number(row.pruned_events),retentionFloor:Number(row.retention_floor),limited:after<Number(row.retention_floor),retentionDays:TELEMETRY_RETENTION_DAYS,maxEvents:TELEMETRY_MAX_EVENTS,oldestAvailableAt:oldest.get(userId).at,observations:{snapshotRateLimited:Number(stats.rate_limited),snapshotBudgetLimited:Number(stats.budget_limited),snapshotUnchanged:Number(stats.unchanged),duplicates:Number(stats.duplicates),lastSuppressedAt:stats.last_suppressed_at}}}function decode(row){const metadata=row.metadata?JSON.parse(String(row.metadata)):{};return{id:String(row.id),at:String(row.at),operation:String(row.operation),outcome:String(row.outcome),durationMs:Number(row.duration),...row.source?{source:String(row.source)}:{},...row.code?{code:String(row.code)}:{},...row.internal?{internal:true}:{},...row.trace?{trace:JSON.parse(String(row.trace))}:{},...metadata}}function prune(cutoff,limit){const facts=pruneFacts.get(userId,cutoff,limit);if(!Number(facts.n))return;pruneSequences.run(userId,cutoff,limit);pruneRows.run(userId,cutoff,limit);rememberPruning.run(Number(facts.n),Number(facts.last_seq))}function maintain(){const now2=Date.now();if(now2>=nextAgeSweep){prune(new Date(now2-TELEMETRY_RETENTION_DAYS*DAY).toISOString(),2147483647);nextAgeSweep=now2+6e4}const excess=Number(state.get().retained_events)-TELEMETRY_MAX_EVENTS;if(excess>0)prune("9999-12-31T23:59:59.999Z",excess+Math.min(255,TELEMETRY_MAX_EVENTS-1))}function insert(event,id=randomUUID(),transaction=true,at=new Date().toISOString()){const execution=["product.resources","product.collection"].includes(event.operation)?void 0:currentOperationalExecution();const record={...event,id,at,...capturedContext?{context:capturedContext}:{},...execution?{execution}:{}};if(Buffer.byteLength(JSON.stringify(record))>TELEMETRY_MAX_RECORD_BYTES)throw Error("Telemetry record exceeds its closed metadata budget.");const metadata={...record.context?{context:record.context}:{},...record.execution?{execution:record.execution}:{},...event.operational?{operational:event.operational}:{},...event.resource?{resource:event.resource}:{},...event.collectionStatus?{collectionStatus:event.collectionStatus}:{},...event.result?{result:event.result}:{},...event.search?{search:event.search}:{},...event.correlation?{correlation:event.correlation}:{},...event.errorCategory?{errorCategory:event.errorCategory}:{},...event.feedback?{feedback:event.feedback}:{},...event.observation?{observation:event.observation}:{},...event.invocation?{invocation:event.invocation}:{}};if(transaction)db.exec("BEGIN IMMEDIATE");try{const inserted=add.run(id,at,event.operation,event.outcome,event.durationMs,event.source??null,event.code??null,Number(event.internal??false),event.trace?JSON.stringify(event.trace):null,Object.keys(metadata).length?JSON.stringify(metadata):null,event.feedback?.targetReceiptId??null,event.feedback?.submissionChannel??null);if(Number(inserted.changes))addSequence.run(id);maintain();if(transaction)db.exec("COMMIT");return id}catch(error){if(transaction)db.exec("ROLLBACK");throw error}}if(enabled){try{db.exec("BEGIN IMMEDIATE");maintain();db.exec("COMMIT")}catch(error){try{db.exec("ROLLBACK")}catch{}db.close();throw error}}if(startup&&enabled){insert({operation:"product.first_start",outcome:"ok",durationMs:0,internal:true,code:created&&newInstallation?"new_install":"first_observed"},userId);insert({operation:"product.started",outcome:"ok",durationMs:0,internal:true})}const service={isEnabled:()=>enabled&&!closed,collectionStats:()=>!enabled||closed||!captureIdentity?void 0:{...captureIdentity,scope:"record_and_observe_api_calls",...captureCounts,pending:captureCounts.attempted-captureCounts.accepted-captureCounts.suppressed-captureCounts.rejected-captureCounts.failed},sourceReference(source){if(!enabled||closed||!actionSalt||typeof source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(source))return;const hash=createHmac("sha256",actionSalt).update(JSON.stringify(["zortex-source-v1",source])).digest("hex");return hash.slice(0,8)+"-"+hash.slice(8,12)+"-8"+hash.slice(13,16)+"-a"+hash.slice(17,20)+"-"+hash.slice(20,32)},actionReference(source,method){if(!enabled||closed||!actionSalt||typeof source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof method!=="string"||!method.length||Buffer.byteLength(method)>512)return;const hash=createHmac("sha256",actionSalt).update(JSON.stringify(["zortex-action-v2",source,method])).digest("hex");return hash.slice(0,8)+"-"+hash.slice(8,12)+"-8"+hash.slice(13,16)+"-a"+hash.slice(17,20)+"-"+hash.slice(20,32)},observe:input=>capture(()=>{if(!enabled)return ok({recorded:false,reason:"disabled"});const snapshot=snapshotUsageObservation(input);if(!isUsageObservation(snapshot))return businessError("invalid_argument","Observation accepts only fixed, content-free metadata and known counts.","storage");const{key,source,at,...rawFacts}=snapshot;const facts=Object.fromEntries(Object.entries(rawFacts).filter(([,value])=>value!==void 0));if(facts.kind==="connection")facts.capabilities=[...facts.capabilities].sort();const hash=value=>createHash("sha256").update(canonicalJson(value)).digest("hex");const observationKey=hash(["zortex-observation-v1",userId,snapshot.kind,source,key]);const fingerprint=hash({source,facts});const receiptId=observationKey.slice(0,8)+"-"+observationKey.slice(8,12)+"-5"+observationKey.slice(13,16)+"-a"+observationKey.slice(17,20)+"-"+observationKey.slice(20,32);const recordedAt=now(),observedAt=at??new Date(recordedAt).toISOString();const scope=facts.kind==="sync"?null:hash([facts.kind,source,facts.connectionRef??null,...facts.kind==="inventory"?[facts.population,facts.attribution]:[]]);db.exec("BEGIN IMMEDIATE");try{const prior=observationByKey.get(observationKey);if(prior){if(prior.observation_fingerprint!==fingerprint){db.exec("COMMIT");return businessError("already_exists","This observation key already has different metadata.","storage")}db.exec("UPDATE observation_counters SET duplicates=duplicates+1 WHERE id=1");db.exec("COMMIT");return ok({recorded:false,reason:"duplicate",receiptId:String(prior.id)})}if(scope){const previous=lastSnapshot.get(scope),elapsed=recordedAt-Number(previous?.observation_recorded_at??0);const unchanged=previous&&previous.observation_fingerprint===fingerprint&&elapsed<DAY;const limited=previous&&elapsed<OBSERVATION_SNAPSHOT_INTERVAL_MS;const dayStart=Math.floor(recordedAt/DAY)*DAY;const budget=Number(snapshotBudget.get(dayStart,dayStart+DAY).n)>=OBSERVATION_SNAPSHOT_DAILY_LIMIT;if(unchanged||limited||budget){const field=unchanged?"unchanged":limited?"rate_limited":"budget_limited";db.prepare(`UPDATE observation_counters SET ${field}=${field}+1,last_suppressed_at=? WHERE id=1`).run(new Date(recordedAt).toISOString());db.exec("COMMIT");return ok({recorded:false,reason:unchanged?"unchanged":"rate_limited"})}}const outcome=facts.kind!=="sync"?"ok":facts.status==="completed"?"ok":facts.status==="cancelled"?"cancelled":facts.status==="failed"||facts.status==="cleanup_blocked"?"fault":"unknown";insert({operation:"connector."+facts.kind,outcome,durationMs:facts.kind==="sync"?facts.durationMs:0,source,internal:true,observation:facts},receiptId,false,observedAt);observationMetadata.run(observationKey,fingerprint,scope,recordedAt,receiptId);db.exec("COMMIT");return ok({recorded:true,reason:"recorded",receiptId})}catch(error){db.exec("ROLLBACK");throw error}}),record:input=>capture(()=>{if(!enabled)return ok({recorded:false});const snapshot=snapshotUsageRecord(input);if(!isUsageEvent(snapshot)||snapshot.operation==="product.feedback"||snapshot.operation==="product.first_start")return businessError("invalid_argument","Usage accepts only content-free fields; startup and feedback anchors are provider-owned.","storage");const event=snapshot,flow=currentFeedbackFlow();if(!["product.resources","product.collection"].includes(event.operation)&&!event.correlation&&flow&&(!event.source||event.source===flow.source)&&isFlowId(flow.flowId))event.correlation={flowId:flow.flowId,...isFlowId(flow.connectionFlowId)?{connectionFlowId:flow.connectionFlowId}:{}};const invocation=["product.resources","product.collection"].includes(event.operation)?void 0:currentUsageInvocation();const measuredAt=event.resource?.asOf??event.collectionStatus?.asOf;return ok({recorded:true,receiptId:insert({...event,...invocation?{invocation:{...invocation}}:{}},void 0,true,measuredAt)})}),readBatch:({after=0,limit=500})=>perform(()=>{if(!Number.isSafeInteger(after)||after<0||!Number.isInteger(limit)||limit<1||limit>1e3)return businessError("invalid_argument","Usage paging needs an ordered cursor and 1\u20131000 events.","storage");const found=pageQuery.all(after,limit+1),selected=found.slice(0,limit);return ok({format:"zortex-usage/v1",userId,enabled,cursor:selected.length?Number(selected.at(-1).seq):after,more:found.length>limit,eventCursors:selected.map(row=>Number(row.seq)),events:selected.map(decode),collection:collection(after)})}),export:()=>perform(()=>{const events=db.prepare("SELECT * FROM usage ORDER BY at,id LIMIT 100001").all().map(decode);if(events.length>1e5)return businessError("resource_exhausted","Usage export exceeds its batch limit.","storage");return ok({format:"zortex-usage/v1",userId,enabled,events,collection:collection()})}),recent:({limit=5}={})=>perform(()=>{if(!Number.isInteger(limit)||limit<1||limit>20)return businessError("invalid_argument","Recent feedback needs a limit from 1 to 20.","storage");if(!enabled)return ok({enabled,events:[]});const rows=db.prepare("SELECT * FROM usage WHERE at>=? AND at<=? AND (operation IN ('search','context','sql','connector.read','connector.invoke') OR operation='action' AND code IN ('effective_invoke','content_find')) AND (internal=0 OR operation IN ('connector.read','connector.invoke')) ORDER BY at DESC,id DESC LIMIT ?").all(new Date(Date.now()-FEEDBACK_DAYS*DAY).toISOString(),new Date().toISOString(),limit);return ok({enabled,events:rows.map(row=>{const event=decode(row);return{receiptId:event.id,at:event.at,operation:event.operation,outcome:event.outcome,durationMs:event.durationMs,...event.source?{source:event.source}:{},...event.context?{context:event.context}:{},...event.result?{result:event.result}:{},...event.search?{search:event.search}:{},...event.errorCategory?{errorCategory:event.errorCategory}:{}}})})}),recordFeedback:(input,channel)=>perform(()=>{input={...input};channel={...channel};if(!isUsageFeedbackInput(input)||!channel||Object.keys(channel).some(key=>key!=="submissionChannel")||!FEEDBACK_CHANNELS.includes(channel.submissionChannel))return businessError("invalid_argument","Feedback needs one recent receipt, a fixed rating and an optional fixed reason.","storage");if(!enabled)return ok({recorded:false,delivery:"disabled"});db.exec("BEGIN IMMEDIATE");try{const prior=byFeedback.get(input.receiptId,channel.submissionChannel);if(prior){const feedback2=decode(prior).feedback;db.exec("COMMIT");return feedback2.rating===input.rating&&feedback2.reason===input.reason?ok({recorded:false,delivery:"queued",receiptId:String(prior.id)}):businessError("already_exists","This operation already has a different report through this channel.","storage")}const row=byId.get(input.receiptId);if(!row){db.exec("COMMIT");return businessError("not_found","The operation receipt is not available on this installation.","storage")}const target=decode(row),age=Date.now()-Date.parse(target.at);if(!feedbackEligible(target)||age<0||age>FEEDBACK_DAYS*DAY){db.exec("COMMIT");return businessError("failed_precondition","Feedback requires an eligible operation from the last seven days.","storage")}const feedback={targetReceiptId:target.id,rating:input.rating,...input.reason?{reason:input.reason}:{},submissionChannel:channel.submissionChannel,target:{operation:target.operation,outcome:target.outcome,at:target.at,...target.source?{source:target.source}:{},...target.context?{context:target.context}:{},...target.result?{result:target.result}:{},...target.search?{search:target.search}:{},...target.errorCategory?{errorCategory:target.errorCategory}:{}}};const receiptId=insert({operation:"product.feedback",outcome:"ok",durationMs:0,internal:true,feedback},randomUUID(),false);db.exec("COMMIT");return ok({recorded:true,delivery:"queued",receiptId})}catch(error){db.exec("ROLLBACK");throw error}}),report:()=>perform(()=>{const total=db.prepare("SELECT COUNT(*) AS calls,COALESCE(SUM(duration),0) AS duration FROM usage WHERE internal=0 AND operation NOT IN ('flywheel.start','flywheel.run','product.feedback')").get();const flywheel=db.prepare("SELECT COUNT(*) FILTER(WHERE operation='flywheel.start') AS started,COUNT(*) FILTER(WHERE operation='flywheel.run' AND outcome IN ('ok','empty')) AS completed,COUNT(*) FILTER(WHERE operation='flywheel.run' AND outcome='fault') AS failed FROM usage").get();const rows=db.prepare("SELECT source,COUNT(*) FILTER(WHERE outcome IN ('ok','empty','fault')) AS attempted,COUNT(*) FILTER(WHERE outcome='fault') AS faults,COUNT(*) FILTER(WHERE outcome='auth-blocked') AS authBlocked,COUNT(*) FILTER(WHERE outcome='cancelled') AS cancelled,COUNT(*) FILTER(WHERE outcome='invalid') AS invalid FROM usage WHERE operation IN ('connector.read','connector.invoke') AND source IS NOT NULL GROUP BY source ORDER BY source").all();const fabrication=db.prepare("SELECT source,COUNT(*) FILTER(WHERE outcome='ok') AS completed,COUNT(*) FILTER(WHERE outcome='fault') AS failed,COALESCE(SUM(duration),0) AS duration FROM usage WHERE operation='connector.fabricate' AND source IS NOT NULL GROUP BY source ORDER BY source").all();const usable=db.prepare("SELECT COUNT(*) AS n FROM usage_export_seq s JOIN usage u ON u.id=s.event_id WHERE u.operation='connector.usable' AND u.source IS NOT NULL AND u.outcome='ok' AND s.seq=(SELECT MAX(s2.seq) FROM usage_export_seq s2 JOIN usage u2 ON u2.id=s2.event_id WHERE u2.operation='connector.usable' AND u2.source=u.source)").get();return ok({enabled,userId,calls:Number(total.calls),durationMs:Number(total.duration),flywheel:{started:Number(flywheel.started),completed:Number(flywheel.completed),failed:Number(flywheel.failed)},connectors:rows.map(row=>({source:String(row.source),attempted:Number(row.attempted),faults:Number(row.faults),faultRate:Number(row.attempted)?Number(row.faults)/Number(row.attempted):null,authBlocked:Number(row.authBlocked),cancelled:Number(row.cancelled),invalid:Number(row.invalid)})),fabrication:fabrication.map(row=>({source:String(row.source),completed:Number(row.completed),failed:Number(row.failed),durationMs:Number(row.duration)})),usableConnectors:Number(usable.n),collection:collection()})}),async close(){if(!closed){closed=true;db.close()}}};return service}export async function apply(ctx,config){const freshRoot=process.env.ZORTEX_TELEMETRY_NEW_INSTALL_ROOT;const newInstallation=config.newInstallation??!!(freshRoot&&isAbsolute(freshRoot)&&typeof config.root==="string"&&resolve(freshRoot)===resolve(config.root));const service=await createTelemetry({...config,newInstallation,startup:config.startup??true});ctx.provide("zortexTelemetry",service);ctx.effect(()=>()=>service.close())}