@zortexhq/indra-v2.5 0.3.2 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +93 -152
  2. package/dist/auto-sync.js +1 -1
  3. package/dist/auto-update.js +1 -1
  4. package/dist/bundled-handbook.js +1 -1
  5. package/dist/cli-run.js +1 -1
  6. package/dist/cli.js +1 -1
  7. package/dist/codex-install.js +1 -1
  8. package/dist/codex-setup.js +1 -1
  9. package/dist/content-find.js +1 -1
  10. package/dist/gateway.js +1 -1
  11. package/dist/mcp.js +2 -2
  12. package/dist/onboard-cli.js +1 -0
  13. package/dist/onboard.js +1 -0
  14. package/dist/operation-telemetry.js +1 -1
  15. package/dist/public-tool.js +1 -1
  16. package/dist/read-route.js +1 -1
  17. package/dist/recovery-resident-port.js +1 -0
  18. package/dist/resident-host.js +2 -2
  19. package/dist/resident-jobs.js +1 -1
  20. package/dist/resident-platform.js +3 -3
  21. package/dist/resident-runtime-identity.js +1 -1
  22. package/dist/resident-shutdown.js +1 -0
  23. package/dist/resident-startup-preference.js +1 -0
  24. package/dist/resident-telemetry.js +1 -1
  25. package/dist/update-cli.js +1 -1
  26. package/dist/update-command.js +1 -0
  27. package/dist/update-handover.js +1 -0
  28. package/dist/update-recovery.js +1 -1
  29. package/dist/update-tool.js +1 -1
  30. package/dist/web.js +1 -1
  31. package/dist/zortex-cli.js +1 -1
  32. package/node_modules/@zortexhq/plugin-connector-activitywatch/dist/provider.js +1 -1
  33. package/node_modules/@zortexhq/plugin-connector-core/dist/api/connectors.js +1 -1
  34. package/node_modules/@zortexhq/plugin-connector-core/dist/api/content-acquisition.js +1 -0
  35. package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
  36. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  37. package/node_modules/@zortexhq/plugin-connector-level1/dist/action-content.js +1 -0
  38. package/node_modules/@zortexhq/plugin-connector-level1/dist/operational-client.js +1 -1
  39. package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-graph.js +1 -1
  40. package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/content.js +1 -0
  41. package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/specs.js +1 -1
  42. package/node_modules/@zortexhq/plugin-connector-level1/dist/service-sdk-matrix.js +1 -1
  43. package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
  44. package/node_modules/@zortexhq/plugin-connector-netease/dist/provider.js +1 -1
  45. package/node_modules/@zortexhq/plugin-connector-notion/dist/provider.js +1 -1
  46. package/node_modules/@zortexhq/plugin-connector-outlook/dist/actions.js +1 -1
  47. package/node_modules/@zortexhq/plugin-connector-outlook/dist/mail-sync.js +1 -1
  48. package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
  49. package/node_modules/@zortexhq/plugin-connector-steam/dist/provider.js +1 -1
  50. package/node_modules/@zortexhq/plugin-connector-teams/dist/provider.js +1 -1
  51. package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/provider.js +1 -1
  52. package/node_modules/@zortexhq/plugin-connector-youtube/dist/content.js +1 -0
  53. package/node_modules/@zortexhq/plugin-connector-youtube/dist/full-sync.js +1 -1
  54. package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
  55. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
  56. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/portrait-producer.js +1 -1
  57. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/record-identity.js +6 -0
  58. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/snapshot.js +1 -1
  59. package/node_modules/@zortexhq/plugin-posthog/dist/activity.js +1 -1
  60. package/node_modules/@zortexhq/plugin-posthog/dist/northstar.js +1 -1
  61. package/node_modules/@zortexhq/plugin-telemetry/dist/api/measurement.js +1 -1
  62. package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
  63. package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
  64. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-call.js +1 -1
  65. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-methods.js +1 -1
  66. package/node_modules/@zortexhq/plugin-telemetry/dist/index.js +1 -1
  67. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/content-acquisition.js +1 -0
  68. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
  69. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/content-acquisition.js +1 -0
  70. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  71. package/package.json +7 -7
  72. package/release-provenance.json +29 -29
  73. package/update-manifest.json +230 -146
@@ -1 +1 @@
1
- import{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())}
@@ -1 +1 @@
1
- export*from"./blob-store.js";export*from"./custody.js";export*from"./binding-custody.js";export*from"./connector-supervisor.js";export*from"./local-source.js";export*from"./sqlite-vault.js";export*from"./vault-backup.js";export*from"./vault-sql.js";export*from"./checkpoint-erasure-proof.js";export*from"./metadata.js";export*from"./storage-metadata.js";export*from"./source-sync.js";export*from"./search-text.js";
1
+ export*from"./blob-store.js";export*from"./custody.js";export*from"./binding-custody.js";export*from"./connector-supervisor.js";export*from"./local-source.js";export*from"./sqlite-vault.js";export*from"./vault-backup.js";export*from"./vault-sql.js";export*from"./checkpoint-erasure-proof.js";export*from"./metadata.js";export*from"./storage-metadata.js";export*from"./source-sync.js";export*from"./search-text.js";export*from"./content-acquisition.js";
@@ -0,0 +1 @@
1
+ import{createHash}from"node:crypto";import{Original,canonicalJson,businessError,ok}from"@zortexhq/plugin-connector-framework/api";const hash=value=>createHash("sha256").update(value).digest("hex");const fail=message=>businessError("failed_precondition",message,"auth");const nextId=Original.makeUlidFactory();function scope(db,source){try{const selection=db.query("SELECT binding_id,revision FROM source_selections WHERE source=?").get(source);const bindings=selection?db.query("SELECT id,metadata FROM account_bindings WHERE source=? AND id=?").all(source,selection.binding_id):db.query("SELECT id,metadata FROM account_bindings WHERE source=?").all(source);if(bindings.length!==1)return fail("Select one verified account before acquiring content.");const row=bindings[0],binding=JSON.parse(row.metadata);if(binding.state!=="connected"||binding.identity?.source!==source||!Number.isFinite(Date.parse(binding.verifiedAt))||!binding.identity.subject&&!binding.authority)return fail("Content acquisition requires a verified account or explicit session authority.");const pin=db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==binding.identity.subject)return fail("Content belongs to a different isolated account.");const grants=db.query("SELECT metadata FROM authorization_grants WHERE binding_id=? AND json_extract(metadata,'$.purpose')='L1' ORDER BY id").all(row.id);if(!grants.some(row2=>{const g=JSON.parse(row2.metadata);return g.purpose==="L1"&&g.state==="active"}))return fail("Content acquisition requires active L1 authorization.");const resources=db.query("SELECT id,revision FROM credential_resources WHERE binding_id=? ORDER BY id").all(row.id);return ok({fingerprint:hash(canonicalJson({selection:selection??null,binding,grants,resources})),identity:hash(canonicalJson(binding.identity.subject?{...binding.identity}:{source,authority:binding.authority}))})}catch{return fail("Content acquisition custody is unavailable; reconnect through the product.")}}export function beginContentAcquisition(deps,source,resource){if(!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof resource!=="string"||!resource.trim()||resource.length>256)return businessError("invalid_argument","A bounded source and resource are required.","storage");if(deps.closed())return fail("Vault is closed.");const captured=scope(deps.db,source);if(!("ok"in captured))return captured;const declared=deps.declare(source);if(!("ok"in declared))return declared;const expires=Date.now()+3e5;let used=false;return ok({append(records,signal){const check=()=>{if(deps.closed()||used||Date.now()>expires)return fail("Acquisition expired or was already committed.");if(signal?.aborted)return businessError("aborted","Content acquisition cancelled.","storage");const current=scope(deps.db,source);return"ok"in current&&current.ok.fingerprint===captured.ok.fingerprint?ok(true):businessError("permission_denied","Account or authorization changed before content commit.","auth")};const admitted=check();if(!("ok"in admitted))return admitted;if(!Array.isArray(records)||records.length>100)return businessError("invalid_argument","Acquire at most 100 reviewed records per page.","storage");const observedAt=new Date().toISOString(),id=nextId(),origin={kind:"connector",source,grant:id};let drafts;try{const ids=new Set;drafts=records.map(row=>{if(!row||typeof row.id!=="string"||!row.id||row.id.length>4096||ids.has(row.id)||typeof row.body!=="string"||!row.fields||typeof row.fields!=="object"||Array.isArray(row.fields)||Object.hasOwn(row.fields,"acquisition")||row.ts!==void 0&&(!Number.isFinite(Date.parse(row.ts))||new Date(row.ts).toISOString()!==row.ts))throw Error();ids.add(row.id);const payload=JSON.parse(canonicalJson({...row.fields,acquisition:{resource,nativeId:row.id,scope:"acquired",identity:captured.ok.identity}}));return{nk:{source,stream:"acquired-content",sourceId:hash(canonicalJson({identity:captured.ok.identity,resource,id:row.id})),rev:""},ts:row.ts??observedAt,tier:"api",kind:"content.acquired",schemaVersion:1,mentions:[],body:row.body,payload}});if(Buffer.byteLength(canonicalJson(drafts))>4*1024*1024)return businessError("resource_exhausted","Acquisition page exceeds the complete-content budget.","storage")}catch{return businessError("invalid_argument","Acquisition requires unique IDs and complete JSON content.","storage")}let receipt;const save=results=>{if(results.some(row=>!["appended","duplicate","head-noop"].includes(row.outcome)))return businessError("data_loss","Content was not durably accepted.","storage");receipt={id,source,resource,scope:"acquired",returned:records.length,persisted:results.length,observedAt};deps.db.query("INSERT INTO private_state(namespace,key,revision,value) VALUES(?,?,1,?)").run("content-acquisition",id,canonicalJson(receipt));return ok(true)};if(drafts.length){const result=deps.append(drafts,origin,check,save);if(!("ok"in result))return result}else{try{deps.db.exec("BEGIN IMMEDIATE");const checked=check();if(!("ok"in checked)){deps.db.exec("ROLLBACK");return checked}save([]);deps.db.exec("COMMIT")}catch{try{deps.db.exec("ROLLBACK")}catch{}return businessError("unavailable","Empty acquisition receipt could not commit.","storage")}}used=true;return ok(receipt)}})}export function contentAcquisitionScopes(db){const sources=db.query("SELECT DISTINCT source FROM events WHERE stream='acquired-content'").all();return sources.flatMap(({source})=>{const current=scope(db,source);return"ok"in current?[{source,identity:current.ok.identity}]:[]})}
@@ -1 +1 @@
1
- import{Original,businessError,ok,canonicalJson}from"@zortexhq/plugin-connector-framework/api";import{mkdirSync}from"node:fs";import{dirname,isAbsolute}from"node:path";import{randomUUID}from"node:crypto";import{Database}from"./sqlite.js";import{assertNotRecovery}from"./recovery-guard.js";import{rebuildCurrentRecords,updateCurrentRecords}from"./current-records.js";import{rebuildSearchRecords}from"./search-records.js";import{SCHEMA}from"./schema.js";import{LiftedRecordRules}from"./record-rules.js";import{createSqliteAppendPort}from"./append-port.js";import{createIdReader}from"./id-read.js";import{createProcessJournal,PROCESS_JOURNAL_SCHEMA}from"./process-journal.js";import{createLocalSourceRegistry,LOCAL_SOURCE_SCHEMA}from"./local-source-registry.js";import{createSqlReader,sqlLimits,DEFAULT_SQL_LIMITS}from"./sql.js";import{createBlobPort}from"./blob-port.js";import{createSourcePrincipalPort}from"./source-principal-port.js";import{createSnapshotReader}from"./snapshot.js";import{createCheckpointErasureProof}from"./checkpoint-erasure-proof.js";import{createStorageMetadataReader}from"./storage-metadata.js";import{createSourceSyncStore}from"./source-sync.js";export const name="zortex-sqlite-vault";export{createVaultMcp,startVaultMcp,vaultTools}from"./mcp.js";const inactive=()=>Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"SQLite Vault is closed."});export class SqliteVault{identity;db;records;facts;closed=false;declarations=new Map;authorities=new Map;requiredAuthorities=new Set;readPageRows;reader;snapshots;storageMetadata;constructor(config){if(!config||typeof config.file!=="string"||!isAbsolute(config.file)||!Array.isArray(config.streams))throw Error("SQLite Vault requires an absolute file and declared streams.");const backupNamespaces=config.backupPrivateNamespaces??[];if(!Array.isArray(backupNamespaces)||backupNamespaces.length>64||backupNamespaces.some(n=>typeof n!=="string"||!/^[a-z][a-z0-9.-]{0,63}$/.test(n)))throw Error("Invalid trusted backup namespace policy.");const busy=config.busyTimeoutMs??3e3;if(!Number.isSafeInteger(busy)||busy<1||busy>6e4)throw Error("SQLite busy timeout must be 1\u201360000 ms.");const pageRows=config.readPageRows??128;if(!Number.isSafeInteger(pageRows)||pageRows<1||pageRows>4096)throw Error("SQLite read page must be 1\u20134096 rows.");this.readPageRows=pageRows;const readLimits=sqlLimits(config.sql??DEFAULT_SQL_LIMITS);if(config.execution&&(!config.execution.runId||!config.execution.codeVersion))throw Error("Execution binding requires run identity and code version.");assertNotRecovery(config.file,busy);mkdirSync(dirname(config.file),{recursive:true});this.db=new Database(config.file);try{this.db.exec(`PRAGMA busy_timeout=${busy};`);const version=this.db.query("PRAGMA user_version").get().user_version;if(version!==0&&version!==1)throw Error("Unsupported SQLite Vault schema version.");const populated=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' LIMIT 1").get()!==null;if(populated){const hasMeta=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='meta'").get()!==null;if(!hasMeta||this.db.query("SELECT value FROM meta WHERE key='zortex-sqlite-vault-format'").get()?.value!=="1")throw Error("Different SQLite format; select a new Vault file.")}this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;");this.db.exec("BEGIN IMMEDIATE");try{this.db.exec(SCHEMA+PROCESS_JOURNAL_SCHEMA+LOCAL_SOURCE_SCHEMA);this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('zortex-sqlite-vault-format','1')").run();this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('vault-identity',?)").run(randomUUID());this.db.exec("PRAGMA user_version=1; COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}this.identity=this.db.query("SELECT value FROM meta WHERE key='vault-identity'").get().value;this.snapshots=createSnapshotReader(config.file,this.identity,[...backupNamespaces]);this.storageMetadata=createStorageMetadataReader(this.db,config.file,()=>this.closed);const now=config.now??(()=>new Date().toISOString());const saved=this.db.query("SELECT definition FROM source_streams ORDER BY source,stream").all().map(row=>JSON.parse(row.definition));for(const row of this.db.query("SELECT source FROM source_authority_required").all())this.requiredAuthorities.add(row.source);this.records=new LiftedRecordRules(this.db,saved,now,"events",config.execution,origin=>{const binding=this.authorities.get(origin.source);return!binding&&!this.requiredAuthorities.has(origin.source)&&!this.db.query("SELECT 1 FROM source_authority_required WHERE source=?").get(origin.source)?Original.ok(true):binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Required source append authority is inactive."})},event=>updateCurrentRecords(this.db,this.records,event));this.facts=new LiftedRecordRules(this.db,saved,now,"system_events",void 0,void 0,event=>updateCurrentRecords(this.db,this.records,event));for(const row of saved)this.declarations.set(row.source+"\0"+row.stream,row);const admitted=this.registerStreams(config.streams);if(!Original.isOk(admitted))throw Error("Source stream declaration changed or is invalid.");rebuildCurrentRecords(this.db,this.records);rebuildSearchRecords(this.db);this.reader=createSqlReader(config.file,readLimits)}catch(error){this.db.close();throw error}}createAppendPort(){return createSqliteAppendPort(this.db,this,()=>this.closed,this.readPageRows)}storageSnapshot(){return this.storageMetadata()}createSourceSyncStore(){return createSourceSyncStore(this.createPrivateStore("source-sync"))}createBlobPort(){return createBlobPort(this.db,()=>this.closed,origin=>{const binding=this.authorities.get(origin.source);return binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Connector blob bytes require a current trusted source authority binding."})})}createSourcePrincipalPort(){return createSourcePrincipalPort(this.db,()=>this.closed)}registerConnectorAuthority(source,authorize){return this.registerAuthority(source,authorize,false)}registerAuthority(source,authorize,bindingAuthority){if(this.closed||!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof authorize!=="function")throw Error("Invalid trusted source authority binding.");if(this.authorities.get(source)?.active)throw Error("Source authority is already bound.");if(!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source))throw Error("Isolated source requires binding authority.");this.db.query("INSERT OR IGNORE INTO source_authority_required(source) VALUES(?)").run(source);this.requiredAuthorities.add(source);const binding={authorize:origin=>!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source)?Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Isolated source requires binding authority."}):authorize(origin),active:true};this.authorities.set(source,binding);return()=>{binding.active=false}}registerConnectedSourceAuthority(source,expected){if(!Original.isUlid(expected?.grant)||typeof expected.account!=="string"||!expected.account||typeof expected.updatedAt!=="string"||!Number.isFinite(Date.parse(expected.updatedAt))||!Array.isArray(expected.scopes)||!expected.scopes.length||expected.scopes.some(scope=>typeof scope!=="string"||!scope))throw Error("Invalid connected source authority epoch.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Source identity or consent changed before append."});return this.registerConnectorAuthority(source,origin=>{if(origin.grant!==expected.grant)return denied();const row=this.db.query("SELECT metadata FROM connections WHERE source=?").get(source);if(!row)return denied();let current;try{current=JSON.parse(row.metadata)}catch{return denied()}if(!current||typeof current!=="object"||Array.isArray(current))return denied();const info=current;const scopes=info.scopes;if(info.source!==source||info.provider!=="google"||info.state!=="connected"||info.updatedAt!==expected.updatedAt||(info.accountId??info.account)!==expected.account||!Array.isArray(scopes)||expected.scopes.some(scope=>!scopes.includes(scope)))return denied();return Original.ok(true)})}registerBindingSourceAuthority(source,expected){const positive=value=>Number.isSafeInteger(value)&&Number(value)>0;const text=value=>typeof value==="string"&&value.length>0&&value.length<=2048;if(!expected||!Original.isUlid(expected.grant)||![expected.bindingId,expected.subject,expected.custodyGrantId,expected.audience].every(text)||![expected.bindingRevision,expected.custodyGrantRevision,expected.selectionRevision].every(positive)||!Number.isSafeInteger(expected.scopeEpoch)||expected.scopeEpoch<0||!Array.isArray(expected.scopes)||!expected.scopes.length||!expected.scopes.every(text))throw Error("Invalid binding source authority epoch.");if((expected.credentialResourceId!==void 0||expected.credentialResourceRevision!==void 0)&&(!text(expected.credentialResourceId)||!positive(expected.credentialResourceRevision)))throw Error("Invalid credential resource epoch.");const epoch={...expected,scopes:[...new Set(expected.scopes)].sort()};const pin=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==epoch.subject)throw Error("Isolated source is pinned to a different subject.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Selected source identity or consent changed before append."});const withdraw=this.registerAuthority(source,origin=>{if(origin.grant!==epoch.grant)return denied();try{const pin2=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin2&&pin2.subject!==epoch.subject)return denied();const selection=this.db.query("SELECT binding_id,revision FROM source_selections WHERE source=?").get(source);const binding=this.db.query("SELECT source,subject,revision,metadata FROM account_bindings WHERE id=?").get(epoch.bindingId);const grant=this.db.query("SELECT binding_id,revision,metadata FROM authorization_grants WHERE id=?").get(epoch.custodyGrantId);if(!selection||selection.binding_id!==epoch.bindingId||selection.revision!==epoch.selectionRevision||!binding||binding.source!==source||binding.subject!==epoch.subject||binding.revision!==epoch.bindingRevision||!grant||grant.binding_id!==epoch.bindingId||grant.revision!==epoch.custodyGrantRevision)return denied();if(epoch.credentialResourceId!==void 0){const resource=this.db.query("SELECT binding_id,kind,owner_key,revision FROM credential_resources WHERE id=?").get(epoch.credentialResourceId);if(!resource||resource.binding_id!==epoch.bindingId||resource.kind!=="oauth"||resource.owner_key!=="resident"||resource.revision!==epoch.credentialResourceRevision)return denied()}const b=JSON.parse(binding.metadata),g=JSON.parse(grant.metadata);if(b.id!==epoch.bindingId||b.revision!==epoch.bindingRevision||b.state!=="connected"||b.identity?.source!==source||b.identity?.subject!==epoch.subject||!Number.isFinite(Date.parse(b.verifiedAt))||g.id!==epoch.custodyGrantId||g.revision!==epoch.custodyGrantRevision||g.bindingId!==epoch.bindingId||g.state!=="active"||g.purpose!=="L1"||g.audience!==epoch.audience||g.scopeEpoch!==epoch.scopeEpoch||!Array.isArray(g.scopes)||JSON.stringify([...new Set(g.scopes)].sort())!==JSON.stringify(epoch.scopes))return denied();return Original.ok(true)}catch{return denied()}},true);return withdraw}createOriginalLogPort(){const port=this.createAppendPort();return{append:(batch,origin)=>origin.kind==="kernel"||origin.kind==="derivation"?this.appendSystem(batch,origin):this.append(batch,origin),readGeneration:port.readGeneration,scan:port.scan,scanMetadata:port.scanMetadata,headById:createIdReader(this.db,()=>this.closed),beginCooperativePageDrain:port.beginCooperativePageDrain,finishCooperativePageDrain:port.finishCooperativePageDrain,cancelCooperativePageDrain:port.cancelCooperativePageDrain}}createCheckpointErasureProof(){return createCheckpointErasureProof(this)}registerStreams(streams){if(this.closed)return inactive();if(!Array.isArray(streams)||streams.length>1e3)return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Source declaration batch is invalid."});const incoming=new Map;for(const candidate of streams){if(!candidate||Object.keys(candidate).some(key2=>!["source","stream","revOrder","comparator","quality","noneIdentity","deleteKind"].includes(key2))||candidate.deleteKind!==void 0&&(typeof candidate.deleteKind!=="string"||!candidate.deleteKind)||typeof candidate.source!=="string"||!candidate.source||typeof candidate.stream!=="string"||!candidate.stream||!Original.REV_ORDERS.includes(candidate.revOrder)||candidate.comparator!==void 0&&!["numeric","lex"].includes(candidate.comparator)||candidate.quality!==void 0&&!Original.DECLARABLE_IDENTITY_QUALITIES.includes(candidate.quality))return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid source stream declaration."});const key=candidate.source+"\0"+candidate.stream,prior=incoming.get(key)??this.declarations.get(key);const row={...candidate,...candidate.deleteKind===void 0&&prior?.deleteKind!==void 0?{deleteKind:prior.deleteKind}:{}};if(prior&&canonicalJson({...prior,...prior.deleteKind===void 0&&row.deleteKind!==void 0?{deleteKind:row.deleteKind}:{}})!==canonicalJson(row))return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Existing source stream authority changed; explicit migration is required."});incoming.set(key,JSON.parse(canonicalJson(row)))}this.db.exec("BEGIN IMMEDIATE");try{for(const[key,candidate]of incoming){const existing=this.db.query("SELECT definition FROM source_streams WHERE source=? AND stream=?").get(candidate.source,candidate.stream);const prior=existing?JSON.parse(existing.definition):void 0;const row={...candidate,...candidate.deleteKind===void 0&&prior?.deleteKind!==void 0?{deleteKind:prior.deleteKind}:{}};if(prior&&canonicalJson({...prior,...prior.deleteKind===void 0&&row.deleteKind!==void 0?{deleteKind:row.deleteKind}:{}})!==canonicalJson(row)){this.db.exec("ROLLBACK");return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Another owner declared a different stream authority."})}incoming.set(key,row);this.db.query("INSERT INTO source_streams(source,stream,definition) VALUES(?,?,?) ON CONFLICT(source,stream) DO UPDATE SET definition=excluded.definition").run(row.source,row.stream,canonicalJson(row))}this.db.exec("COMMIT")}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Stream binding did not commit."})}for(const[key,row]of incoming){this.declarations.set(key,row);this.records.registerStream(row);this.facts.registerStream(row)}return Original.ok(true)}createProcessJournal(){return createProcessJournal(this.db,()=>this.closed)}createPrivateStore(namespace){if(!/^[a-z][a-z0-9.-]{0,63}$/.test(namespace))throw Error("Private storage namespace must be declared by the trusted host.");const valid=key=>typeof key==="string"&&key.length>0&&key.length<=500,invalid=()=>businessError("invalid_argument","Invalid private key, value or revision.","storage");const unavailable=error=>businessError("unavailable",`Private state is temporarily busy${error instanceof Error&&error.message.includes("locked")?" (locked)":""}.`,"storage");const busy=error=>error instanceof Error&&(/SQLITE_BUSY|database is locked|database is busy/i.test(error.message)||error.code==="SQLITE_BUSY");const read=key=>{const row=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key=?").get(namespace,key);return row?{key:row.key,revision:row.revision,value:JSON.parse(row.value)}:null};const decode=row=>({key:row.key,revision:row.revision,value:JSON.parse(row.value)});const listPage=(options={})=>{if(this.closed)return inactive();const after=options.after??"",limit=options.limit??100;if(options.after!==void 0&&!valid(options.after)||!Number.isSafeInteger(limit)||limit<1||limit>1e3)return invalid();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key>? ORDER BY key LIMIT ?").all(namespace,after,limit+1),more=rows.length>limit,items=rows.slice(0,limit).map(decode);return ok({items,...more&&items.length?{next:items.at(-1).key}:{}})}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state page could not be read.","storage")}};const guardValid=guard=>guard===void 0||!!guard&&typeof guard==="object"&&valid(guard.key)&&Number.isSafeInteger(guard.revision)&&guard.revision>0;const guarded=guard=>guard===void 0||read(guard.key)?.revision===guard.revision;const remove=(key,expected,guard)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0||!guardValid(guard))return invalid();let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;if(!guarded(guard)){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state lease changed before the write.","storage")}const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before deleting this value.","storage")}this.db.query("DELETE FROM private_state WHERE namespace=? AND key=?").run(namespace,key);this.db.exec("COMMIT");begun=false;return ok(true)}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state deletion did not complete.","storage")}};return{delete:remove,get:key=>{if(this.closed)return inactive();if(!valid(key))return invalid();try{return ok(read(key))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be read.","storage")}},list:()=>{if(this.closed)return inactive();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? ORDER BY key LIMIT 10001").all(namespace);if(rows.length>1e4)return businessError("resource_exhausted","Private namespace exceeds the complete-read budget; use listPage.","storage");return ok(rows.map(decode))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be listed.","storage")}},listPage,put:(key,value,expected,guard)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0||!guardValid(guard))return invalid();let encoded;try{encoded=canonicalJson(value);if(Buffer.byteLength(encoded)>4*1024*1024)return businessError("resource_exhausted","Private state exceeds its complete-value budget.","storage")}catch{return invalid()}let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;if(!guarded(guard)){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state lease changed before the write.","storage")}const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before applying this transition.","storage")}const revision=expected+1;this.db.query("INSERT INTO private_state(namespace,key,revision,value) VALUES(?,?,?,?) ON CONFLICT(namespace,key) DO UPDATE SET revision=excluded.revision,value=excluded.value").run(namespace,key,revision,encoded);this.db.exec("COMMIT");begun=false;return ok({key,revision,value:JSON.parse(encoded)})}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state transaction did not complete.","storage")}}}}createLocalSourceRegistry(){return createLocalSourceRegistry(this.db,()=>this.closed)}sql(request,signal){return this.closed?Promise.resolve(inactive()):this.reader.sql(request,signal)}exportDataSnapshot(...args){return this.snapshots.exportDataSnapshot(...args)}append(batch,origin){return this.closed?inactive():this.records.appendCore(batch,origin)}appendFacts(batch){return this.closed?inactive():this.facts.appendCore(batch,{kind:"kernel"},true)}appendSystem(batch,origin){if(this.closed)return inactive();if(origin?.kind==="connector")return Original.errResult({code:"permission_denied",layer:"storage",retryability:"non-retryable",message:"Connector authority cannot write system facts."});return this.facts.appendCore(batch,origin)}importErasureDecisions(decisions){if(this.closed)throw Error("SQLite Vault is closed.");for(const row of decisions)if(!row||typeof row.source!=="string"||typeof row.stream!=="string"||typeof row.source_id!=="string"||typeof row.rev!=="string"||typeof row.kind!=="string"||!/^[0-9a-f]{64}$/.test(row.content_hash)||!Original.isUlid(row.tomb_id)||row.future_too!==0&&row.future_too!==1||Number.isNaN(Date.parse(row.ts)))throw Error("Invalid erasure decision.");this.db.exec("BEGIN IMMEDIATE");try{if(this.db.query("SELECT 1 FROM events LIMIT 1").get()!==null)throw Error("Erasure decisions must be imported before user records.");const put=this.db.query("INSERT OR REPLACE INTO tombstones(source,stream,source_id,rev,content_hash,tomb_id,future_too,ts,kind) VALUES (?,?,?,?,?,?,?,?,?)");for(const row of decisions)put.run(row.source,row.stream,row.source_id,row.rev,row.content_hash,row.tomb_id,row.future_too,row.ts,row.kind);this.db.exec("COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}}close(){if(!this.closed){this.closed=true;void this.reader.close();void this.snapshots.close();this.db.close()}}async closeAsync(){this.close();await Promise.all([this.reader.close(),this.snapshots.close()])}}export async function apply(ctx,config){const vault=new SqliteVault(config);ctx.reflect.provide("zortexSqliteVault",vault);ctx.reflect.provide("zortexConnectorStorage",{identity:vault.identity,appendPort:vault.createAppendPort(),declareStreams:streams=>vault.registerStreams(streams)});ctx.reflect.provide("zortexConnectorProcessJournal",vault.createProcessJournal());ctx.reflect.provide("zortexLocalSourceRegistry",vault.createLocalSourceRegistry());return()=>vault.closeAsync()}
1
+ import{Original,businessError,ok,canonicalJson}from"@zortexhq/plugin-connector-framework/api";import{mkdirSync}from"node:fs";import{dirname,isAbsolute}from"node:path";import{beginContentAcquisition,contentAcquisitionScopes}from"./content-acquisition.js";import{randomUUID}from"node:crypto";import{Database}from"./sqlite.js";import{assertNotRecovery}from"./recovery-guard.js";import{rebuildCurrentRecords,updateCurrentRecords}from"./current-records.js";import{rebuildSearchRecords}from"./search-records.js";import{SCHEMA}from"./schema.js";import{LiftedRecordRules}from"./record-rules.js";import{createSqliteAppendPort}from"./append-port.js";import{createIdReader}from"./id-read.js";import{createProcessJournal,PROCESS_JOURNAL_SCHEMA}from"./process-journal.js";import{createLocalSourceRegistry,LOCAL_SOURCE_SCHEMA}from"./local-source-registry.js";import{createSqlReader,sqlLimits,DEFAULT_SQL_LIMITS}from"./sql.js";import{createBlobPort}from"./blob-port.js";import{createSourcePrincipalPort}from"./source-principal-port.js";import{createSnapshotReader}from"./snapshot.js";import{createCheckpointErasureProof}from"./checkpoint-erasure-proof.js";import{createStorageMetadataReader}from"./storage-metadata.js";import{createSourceSyncStore}from"./source-sync.js";export const name="zortex-sqlite-vault";export{createVaultMcp,startVaultMcp,vaultTools}from"./mcp.js";const inactive=()=>Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"SQLite Vault is closed."});export class SqliteVault{identity;db;records;facts;closed=false;declarations=new Map;authorities=new Map;acquisitionAuthorities=new Map;requiredAuthorities=new Set;readPageRows;reader;snapshots;storageMetadata;constructor(config){if(!config||typeof config.file!=="string"||!isAbsolute(config.file)||!Array.isArray(config.streams))throw Error("SQLite Vault requires an absolute file and declared streams.");const backupNamespaces=config.backupPrivateNamespaces??[];if(!Array.isArray(backupNamespaces)||backupNamespaces.length>64||backupNamespaces.some(n=>typeof n!=="string"||!/^[a-z][a-z0-9.-]{0,63}$/.test(n)))throw Error("Invalid trusted backup namespace policy.");const busy=config.busyTimeoutMs??3e3;if(!Number.isSafeInteger(busy)||busy<1||busy>6e4)throw Error("SQLite busy timeout must be 1\u201360000 ms.");const pageRows=config.readPageRows??128;if(!Number.isSafeInteger(pageRows)||pageRows<1||pageRows>4096)throw Error("SQLite read page must be 1\u20134096 rows.");this.readPageRows=pageRows;const readLimits=sqlLimits(config.sql??DEFAULT_SQL_LIMITS);if(config.execution&&(!config.execution.runId||!config.execution.codeVersion))throw Error("Execution binding requires run identity and code version.");assertNotRecovery(config.file,busy);mkdirSync(dirname(config.file),{recursive:true});this.db=new Database(config.file);try{this.db.exec(`PRAGMA busy_timeout=${busy};`);const version=this.db.query("PRAGMA user_version").get().user_version;if(version!==0&&version!==1)throw Error("Unsupported SQLite Vault schema version.");const populated=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' LIMIT 1").get()!==null;if(populated){const hasMeta=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='meta'").get()!==null;if(!hasMeta||this.db.query("SELECT value FROM meta WHERE key='zortex-sqlite-vault-format'").get()?.value!=="1")throw Error("Different SQLite format; select a new Vault file.")}this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;");this.db.exec("BEGIN IMMEDIATE");try{this.db.exec(SCHEMA+PROCESS_JOURNAL_SCHEMA+LOCAL_SOURCE_SCHEMA);this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('zortex-sqlite-vault-format','1')").run();this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('vault-identity',?)").run(randomUUID());this.db.exec("PRAGMA user_version=1; COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}this.identity=this.db.query("SELECT value FROM meta WHERE key='vault-identity'").get().value;this.snapshots=createSnapshotReader(config.file,this.identity,[...backupNamespaces]);this.storageMetadata=createStorageMetadataReader(this.db,config.file,()=>this.closed);const now=config.now??(()=>new Date().toISOString());const saved=this.db.query("SELECT definition FROM source_streams ORDER BY source,stream").all().map(row=>JSON.parse(row.definition));for(const row of this.db.query("SELECT source FROM source_authority_required").all())this.requiredAuthorities.add(row.source);this.records=new LiftedRecordRules(this.db,saved,now,"events",config.execution,origin=>{const acquisition=this.acquisitionAuthorities.get(origin.source+"\0"+origin.grant);if(acquisition)return acquisition();const binding=this.authorities.get(origin.source);return!binding&&!this.requiredAuthorities.has(origin.source)&&!this.db.query("SELECT 1 FROM source_authority_required WHERE source=?").get(origin.source)?Original.ok(true):binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Required source append authority is inactive."})},event=>updateCurrentRecords(this.db,this.records,event));this.facts=new LiftedRecordRules(this.db,saved,now,"system_events",void 0,void 0,event=>updateCurrentRecords(this.db,this.records,event));for(const row of saved)this.declarations.set(row.source+"\0"+row.stream,row);const admitted=this.registerStreams(config.streams);if(!Original.isOk(admitted))throw Error("Source stream declaration changed or is invalid.");rebuildCurrentRecords(this.db,this.records);rebuildSearchRecords(this.db);this.reader=createSqlReader(config.file,readLimits)}catch(error){this.db.close();throw error}}createAppendPort(){return createSqliteAppendPort(this.db,this,()=>this.closed,this.readPageRows)}storageSnapshot(){return this.storageMetadata()}createSourceSyncStore(){return createSourceSyncStore(this.createPrivateStore("source-sync"))}createBlobPort(){return createBlobPort(this.db,()=>this.closed,origin=>{const binding=this.authorities.get(origin.source);return binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Connector blob bytes require a current trusted source authority binding."})})}createSourcePrincipalPort(){return createSourcePrincipalPort(this.db,()=>this.closed)}registerConnectorAuthority(source,authorize){return this.registerAuthority(source,authorize,false)}registerAuthority(source,authorize,bindingAuthority){if(this.closed||!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof authorize!=="function")throw Error("Invalid trusted source authority binding.");if(this.authorities.get(source)?.active)throw Error("Source authority is already bound.");if(!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source))throw Error("Isolated source requires binding authority.");this.db.query("INSERT OR IGNORE INTO source_authority_required(source) VALUES(?)").run(source);this.requiredAuthorities.add(source);const binding={authorize:origin=>!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source)?Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Isolated source requires binding authority."}):authorize(origin),active:true};this.authorities.set(source,binding);return()=>{binding.active=false}}registerConnectedSourceAuthority(source,expected){if(!Original.isUlid(expected?.grant)||typeof expected.account!=="string"||!expected.account||typeof expected.updatedAt!=="string"||!Number.isFinite(Date.parse(expected.updatedAt))||!Array.isArray(expected.scopes)||!expected.scopes.length||expected.scopes.some(scope=>typeof scope!=="string"||!scope))throw Error("Invalid connected source authority epoch.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Source identity or consent changed before append."});return this.registerConnectorAuthority(source,origin=>{if(origin.grant!==expected.grant)return denied();const row=this.db.query("SELECT metadata FROM connections WHERE source=?").get(source);if(!row)return denied();let current;try{current=JSON.parse(row.metadata)}catch{return denied()}if(!current||typeof current!=="object"||Array.isArray(current))return denied();const info=current;const scopes=info.scopes;if(info.source!==source||info.provider!=="google"||info.state!=="connected"||info.updatedAt!==expected.updatedAt||(info.accountId??info.account)!==expected.account||!Array.isArray(scopes)||expected.scopes.some(scope=>!scopes.includes(scope)))return denied();return Original.ok(true)})}registerBindingSourceAuthority(source,expected){const positive=value=>Number.isSafeInteger(value)&&Number(value)>0;const text=value=>typeof value==="string"&&value.length>0&&value.length<=2048;if(!expected||!Original.isUlid(expected.grant)||![expected.bindingId,expected.subject,expected.custodyGrantId,expected.audience].every(text)||![expected.bindingRevision,expected.custodyGrantRevision,expected.selectionRevision].every(positive)||!Number.isSafeInteger(expected.scopeEpoch)||expected.scopeEpoch<0||!Array.isArray(expected.scopes)||!expected.scopes.length||!expected.scopes.every(text))throw Error("Invalid binding source authority epoch.");if((expected.credentialResourceId!==void 0||expected.credentialResourceRevision!==void 0)&&(!text(expected.credentialResourceId)||!positive(expected.credentialResourceRevision)))throw Error("Invalid credential resource epoch.");const epoch={...expected,scopes:[...new Set(expected.scopes)].sort()};const pin=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==epoch.subject)throw Error("Isolated source is pinned to a different subject.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Selected source identity or consent changed before append."});const withdraw=this.registerAuthority(source,origin=>{if(origin.grant!==epoch.grant)return denied();try{const pin2=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin2&&pin2.subject!==epoch.subject)return denied();const selection=this.db.query("SELECT binding_id,revision FROM source_selections WHERE source=?").get(source);const binding=this.db.query("SELECT source,subject,revision,metadata FROM account_bindings WHERE id=?").get(epoch.bindingId);const grant=this.db.query("SELECT binding_id,revision,metadata FROM authorization_grants WHERE id=?").get(epoch.custodyGrantId);if(!selection||selection.binding_id!==epoch.bindingId||selection.revision!==epoch.selectionRevision||!binding||binding.source!==source||binding.subject!==epoch.subject||binding.revision!==epoch.bindingRevision||!grant||grant.binding_id!==epoch.bindingId||grant.revision!==epoch.custodyGrantRevision)return denied();if(epoch.credentialResourceId!==void 0){const resource=this.db.query("SELECT binding_id,kind,owner_key,revision FROM credential_resources WHERE id=?").get(epoch.credentialResourceId);if(!resource||resource.binding_id!==epoch.bindingId||resource.kind!=="oauth"||resource.owner_key!=="resident"||resource.revision!==epoch.credentialResourceRevision)return denied()}const b=JSON.parse(binding.metadata),g=JSON.parse(grant.metadata);if(b.id!==epoch.bindingId||b.revision!==epoch.bindingRevision||b.state!=="connected"||b.identity?.source!==source||b.identity?.subject!==epoch.subject||!Number.isFinite(Date.parse(b.verifiedAt))||g.id!==epoch.custodyGrantId||g.revision!==epoch.custodyGrantRevision||g.bindingId!==epoch.bindingId||g.state!=="active"||g.purpose!=="L1"||g.audience!==epoch.audience||g.scopeEpoch!==epoch.scopeEpoch||!Array.isArray(g.scopes)||JSON.stringify([...new Set(g.scopes)].sort())!==JSON.stringify(epoch.scopes))return denied();return Original.ok(true)}catch{return denied()}},true);return withdraw}contentAcquisitionScopes(){return this.closed?[]:contentAcquisitionScopes(this.db)}beginContentAcquisition(source,resource){return beginContentAcquisition({db:this.db,closed:()=>this.closed,declare:source2=>this.registerStreams([{source:source2,stream:"acquired-content",revOrder:"head-compare",quality:"durable"}]),append:(drafts,origin,check,after)=>{const key=origin.source+"\0"+origin.grant;this.acquisitionAuthorities.set(key,check);try{return this.records.appendCore(drafts,origin,false,{before:check,after})}finally{this.acquisitionAuthorities.delete(key)}}},source,resource)}createOriginalLogPort(){const port=this.createAppendPort();return{append:(batch,origin)=>origin.kind==="kernel"||origin.kind==="derivation"?this.appendSystem(batch,origin):this.append(batch,origin),readGeneration:port.readGeneration,scan:port.scan,scanMetadata:port.scanMetadata,headById:createIdReader(this.db,()=>this.closed),beginCooperativePageDrain:port.beginCooperativePageDrain,finishCooperativePageDrain:port.finishCooperativePageDrain,cancelCooperativePageDrain:port.cancelCooperativePageDrain}}createCheckpointErasureProof(){return createCheckpointErasureProof(this)}registerStreams(streams){if(this.closed)return inactive();if(!Array.isArray(streams)||streams.length>1e3)return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Source declaration batch is invalid."});const incoming=new Map;for(const candidate of streams){if(!candidate||Object.keys(candidate).some(key2=>!["source","stream","revOrder","comparator","quality","noneIdentity","deleteKind"].includes(key2))||candidate.deleteKind!==void 0&&(typeof candidate.deleteKind!=="string"||!candidate.deleteKind)||typeof candidate.source!=="string"||!candidate.source||typeof candidate.stream!=="string"||!candidate.stream||!Original.REV_ORDERS.includes(candidate.revOrder)||candidate.comparator!==void 0&&!["numeric","lex"].includes(candidate.comparator)||candidate.quality!==void 0&&!Original.DECLARABLE_IDENTITY_QUALITIES.includes(candidate.quality))return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid source stream declaration."});const key=candidate.source+"\0"+candidate.stream,prior=incoming.get(key)??this.declarations.get(key);const row={...candidate,...candidate.deleteKind===void 0&&prior?.deleteKind!==void 0?{deleteKind:prior.deleteKind}:{}};if(prior&&canonicalJson({...prior,...prior.deleteKind===void 0&&row.deleteKind!==void 0?{deleteKind:row.deleteKind}:{}})!==canonicalJson(row))return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Existing source stream authority changed; explicit migration is required."});incoming.set(key,JSON.parse(canonicalJson(row)))}this.db.exec("BEGIN IMMEDIATE");try{for(const[key,candidate]of incoming){const existing=this.db.query("SELECT definition FROM source_streams WHERE source=? AND stream=?").get(candidate.source,candidate.stream);const prior=existing?JSON.parse(existing.definition):void 0;const row={...candidate,...candidate.deleteKind===void 0&&prior?.deleteKind!==void 0?{deleteKind:prior.deleteKind}:{}};if(prior&&canonicalJson({...prior,...prior.deleteKind===void 0&&row.deleteKind!==void 0?{deleteKind:row.deleteKind}:{}})!==canonicalJson(row)){this.db.exec("ROLLBACK");return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Another owner declared a different stream authority."})}incoming.set(key,row);this.db.query("INSERT INTO source_streams(source,stream,definition) VALUES(?,?,?) ON CONFLICT(source,stream) DO UPDATE SET definition=excluded.definition").run(row.source,row.stream,canonicalJson(row))}this.db.exec("COMMIT")}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Stream binding did not commit."})}for(const[key,row]of incoming){this.declarations.set(key,row);this.records.registerStream(row);this.facts.registerStream(row)}return Original.ok(true)}createProcessJournal(){return createProcessJournal(this.db,()=>this.closed)}createPrivateStore(namespace){if(!/^[a-z][a-z0-9.-]{0,63}$/.test(namespace))throw Error("Private storage namespace must be declared by the trusted host.");const valid=key=>typeof key==="string"&&key.length>0&&key.length<=500,invalid=()=>businessError("invalid_argument","Invalid private key, value or revision.","storage");const unavailable=error=>businessError("unavailable",`Private state is temporarily busy${error instanceof Error&&error.message.includes("locked")?" (locked)":""}.`,"storage");const busy=error=>error instanceof Error&&(/SQLITE_BUSY|database is locked|database is busy/i.test(error.message)||error.code==="SQLITE_BUSY");const read=key=>{const row=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key=?").get(namespace,key);return row?{key:row.key,revision:row.revision,value:JSON.parse(row.value)}:null};const decode=row=>({key:row.key,revision:row.revision,value:JSON.parse(row.value)});const listPage=(options={})=>{if(this.closed)return inactive();const after=options.after??"",limit=options.limit??100;if(options.after!==void 0&&!valid(options.after)||!Number.isSafeInteger(limit)||limit<1||limit>1e3)return invalid();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key>? ORDER BY key LIMIT ?").all(namespace,after,limit+1),more=rows.length>limit,items=rows.slice(0,limit).map(decode);return ok({items,...more&&items.length?{next:items.at(-1).key}:{}})}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state page could not be read.","storage")}};const guardValid=guard=>guard===void 0||!!guard&&typeof guard==="object"&&valid(guard.key)&&Number.isSafeInteger(guard.revision)&&guard.revision>0;const guarded=guard=>guard===void 0||read(guard.key)?.revision===guard.revision;const remove=(key,expected,guard)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0||!guardValid(guard))return invalid();let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;if(!guarded(guard)){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state lease changed before the write.","storage")}const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before deleting this value.","storage")}this.db.query("DELETE FROM private_state WHERE namespace=? AND key=?").run(namespace,key);this.db.exec("COMMIT");begun=false;return ok(true)}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state deletion did not complete.","storage")}};return{delete:remove,get:key=>{if(this.closed)return inactive();if(!valid(key))return invalid();try{return ok(read(key))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be read.","storage")}},list:()=>{if(this.closed)return inactive();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? ORDER BY key LIMIT 10001").all(namespace);if(rows.length>1e4)return businessError("resource_exhausted","Private namespace exceeds the complete-read budget; use listPage.","storage");return ok(rows.map(decode))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be listed.","storage")}},listPage,put:(key,value,expected,guard)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0||!guardValid(guard))return invalid();let encoded;try{encoded=canonicalJson(value);if(Buffer.byteLength(encoded)>4*1024*1024)return businessError("resource_exhausted","Private state exceeds its complete-value budget.","storage")}catch{return invalid()}let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;if(!guarded(guard)){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state lease changed before the write.","storage")}const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before applying this transition.","storage")}const revision=expected+1;this.db.query("INSERT INTO private_state(namespace,key,revision,value) VALUES(?,?,?,?) ON CONFLICT(namespace,key) DO UPDATE SET revision=excluded.revision,value=excluded.value").run(namespace,key,revision,encoded);this.db.exec("COMMIT");begun=false;return ok({key,revision,value:JSON.parse(encoded)})}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state transaction did not complete.","storage")}}}}createLocalSourceRegistry(){return createLocalSourceRegistry(this.db,()=>this.closed)}sql(request,signal){return this.closed?Promise.resolve(inactive()):this.reader.sql(request,signal)}exportDataSnapshot(...args){return this.snapshots.exportDataSnapshot(...args)}append(batch,origin){return this.closed?inactive():this.records.appendCore(batch,origin)}appendFacts(batch){return this.closed?inactive():this.facts.appendCore(batch,{kind:"kernel"},true)}appendSystem(batch,origin){if(this.closed)return inactive();if(origin?.kind==="connector")return Original.errResult({code:"permission_denied",layer:"storage",retryability:"non-retryable",message:"Connector authority cannot write system facts."});return this.facts.appendCore(batch,origin)}importErasureDecisions(decisions){if(this.closed)throw Error("SQLite Vault is closed.");for(const row of decisions)if(!row||typeof row.source!=="string"||typeof row.stream!=="string"||typeof row.source_id!=="string"||typeof row.rev!=="string"||typeof row.kind!=="string"||!/^[0-9a-f]{64}$/.test(row.content_hash)||!Original.isUlid(row.tomb_id)||row.future_too!==0&&row.future_too!==1||Number.isNaN(Date.parse(row.ts)))throw Error("Invalid erasure decision.");this.db.exec("BEGIN IMMEDIATE");try{if(this.db.query("SELECT 1 FROM events LIMIT 1").get()!==null)throw Error("Erasure decisions must be imported before user records.");const put=this.db.query("INSERT OR REPLACE INTO tombstones(source,stream,source_id,rev,content_hash,tomb_id,future_too,ts,kind) VALUES (?,?,?,?,?,?,?,?,?)");for(const row of decisions)put.run(row.source,row.stream,row.source_id,row.rev,row.content_hash,row.tomb_id,row.future_too,row.ts,row.kind);this.db.exec("COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}}close(){if(!this.closed){this.closed=true;void this.reader.close();void this.snapshots.close();this.db.close()}}async closeAsync(){this.close();await Promise.all([this.reader.close(),this.snapshots.close()])}}export async function apply(ctx,config){const vault=new SqliteVault(config);ctx.reflect.provide("zortexSqliteVault",vault);ctx.reflect.provide("zortexConnectorStorage",{identity:vault.identity,appendPort:vault.createAppendPort(),declareStreams:streams=>vault.registerStreams(streams)});ctx.reflect.provide("zortexConnectorProcessJournal",vault.createProcessJournal());ctx.reflect.provide("zortexLocalSourceRegistry",vault.createLocalSourceRegistry());return()=>vault.closeAsync()}