@zortexhq/indra-v2.5 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/box-level1-setup.js +1 -1
- package/dist/calcom-level1-setup.js +1 -1
- package/dist/cli-run.js +1 -1
- package/dist/connector-worker.js +1 -1
- package/dist/discord-level1-setup.js +1 -1
- package/dist/dropbox-level1-setup.js +1 -1
- package/dist/figma-level1-setup.js +1 -1
- package/dist/freshdesk-level1-setup.js +1 -1
- package/dist/freshrss-level1-setup.js +1 -1
- package/dist/front-level1-setup.js +1 -1
- package/dist/gateway.js +1 -1
- package/dist/google-chat-level1-setup.js +1 -1
- package/dist/google-contacts-level1-setup.js +1 -1
- package/dist/hubspot-level1-setup.js +1 -1
- package/dist/joplin-selection.js +1 -1
- package/dist/local-cloud.js +1 -1
- package/dist/mattermost-level1-setup.js +1 -1
- package/dist/mcp.js +2 -2
- package/dist/measurement-context.js +1 -1
- package/dist/miniflux-level1-setup.js +1 -1
- package/dist/nextcloud-level1-setup.js +1 -1
- package/dist/operation-telemetry.js +1 -0
- package/dist/prepared-level1-setup.js +1 -0
- package/dist/profile.js +1 -1
- package/dist/proton-mail-level1-setup.js +1 -1
- package/dist/recovery-launch.js +10 -0
- package/dist/recovery-support.js +1 -1
- package/dist/recovery-surface.js +1 -0
- package/dist/recovery.js +1 -1
- package/dist/resident-host.js +2 -2
- package/dist/resident-jobs.js +1 -1
- package/dist/resident-platform.js +1 -1
- package/dist/resident-telemetry.js +1 -0
- package/dist/resource-telemetry.js +1 -0
- package/dist/salesforce-level1-setup.js +1 -1
- package/dist/smartsheet-level1-setup.js +1 -1
- package/dist/startup.js +2 -2
- package/dist/thunderbird-level1-setup.js +1 -1
- package/dist/update-cli.js +1 -1
- package/dist/wakatime-level1-setup.js +1 -1
- package/dist/wallabag-level1-setup.js +1 -1
- package/dist/web.js +2 -2
- package/dist/zendesk-level1-setup.js +1 -1
- package/dist/zoom-level1-setup.js +1 -1
- package/dist/zulip-level1-setup.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/operational-hub.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/chatgpt.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/mcp-feedback.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/operational-client.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/package.json +2 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/routes.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/server.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-catalog.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app.html +42 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-client.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-forms.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/demo.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.css +47 -6
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/original/fonts/LICENSE.txt +92 -0
- package/node_modules/@zortexhq/plugin-jev-autopilot/dist/feedback.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-autopilot/dist/google-oauth-bridge.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-autopilot/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/browser-actions.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/driver.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/operational-browser.js +1 -0
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/session-routes.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/shared-session.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/collection-status.js +1 -0
- package/node_modules/@zortexhq/plugin-posthog/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/indra.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/local-cloud.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/northstar.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/observations.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -0
- package/node_modules/@zortexhq/plugin-posthog/dist/resources.js +1 -0
- package/node_modules/@zortexhq/plugin-posthog/dist/source-ids.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/api/resources.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/resource-sampler.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/package.json +3 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/collection.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/measurement.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/observations.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/resources.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/source-ids.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-call.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-methods.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/upstream-tools.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/resources.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/package.json +3 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/storage-metadata.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/storage-metadata.js +1 -0
- package/package.json +6 -6
- package/release-provenance.json +26 -26
- package/update-manifest.json +379 -181
- package/dist/recovery-page.js +0 -215
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DatabaseSync}from"node:sqlite";import{mkdir,lstat,realpath}from"node:fs/promises";import{isAbsolute,join}from"node:path";import{createHash}from"node:crypto";import{hasScoredOutcome,northstarEvents,rawUsageEvents}from"./northstar.js";import{createBatchPacker,MAX_BATCH_EVENTS,retryDelayMs}from"./delivery-policy.js";import{createCollectionGapOutbox,initializeCollectionGap}from"./collection-gap.js";import{initializeAttribution,installationAttribution}from"./install-attribution.js";import{verifiedGithubLogin,verifiedGithubPerson}from"./github-identity.js";import{createLocalCloudOutbox}from"./local-cloud.js";import{createUpdateOutbox}from"./product-update.js";import{createOnboardingOutbox}from"./onboarding.js";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{isUsageCollection}from"@zortexhq/plugin-telemetry/api";export const name="zortex-posthog",inject=["zortexTelemetry"];export async function createPostHog(config,telemetry,request=fetch,identity=verifiedGithubLogin,_personIdentity=verifiedGithubPerson,account,runtime={}){if(!isAbsolute(config.root))throw Error("PostHog data root must be absolute.");const configured=!!config.host&&!!config.projectKey;let endpoint="";if(configured){const url=new URL(config.host);if(url.protocol!=="https:"||url.username||url.password||url.search||url.hash||url.pathname!=="/")throw Error("PostHog host must be an HTTPS origin.");endpoint=new URL("/batch/",url).href}await mkdir(config.root,{recursive:true,mode:448});if((await lstat(config.root)).isSymbolicLink())throw Error("PostHog data root cannot be a link.");const file=join(await realpath(config.root),"posthog.sqlite");if((await lstat(file).catch(()=>null))?.isSymbolicLink())throw Error("PostHog checkpoint cannot be a link.");const db=new DatabaseSync(file);try{db.exec("PRAGMA busy_timeout=3000;PRAGMA journal_mode=WAL;CREATE TABLE IF NOT EXISTS checkpoints(destination TEXT PRIMARY KEY,user_id TEXT NOT NULL,cursor INTEGER NOT NULL,last_success TEXT);CREATE TABLE IF NOT EXISTS delivery_state(destination TEXT PRIMARY KEY,failure_count INTEGER NOT NULL DEFAULT 0,next_retry_at INTEGER NOT NULL DEFAULT 0,last_error TEXT,last_batch_bytes INTEGER,last_batch_events INTEGER);");initializeCollectionGap(db)}catch(error){db.close();throw error}initializeAttribution(db);const cloud=createLocalCloudOutbox(db,async()=>{const batch=await telemetry.readBatch({limit:1});if(!("ok"in batch))throw Error("TELEMETRY_UNAVAILABLE");return{enabled:batch.ok.enabled,installId:batch.ok.userId}},config.trafficClass==="internal_test");const updates=createUpdateOutbox(db,async()=>{const batch=await telemetry.readBatch({limit:1});if(!("ok"in batch))throw Error("TELEMETRY_UNAVAILABLE");return batch.ok.enabled},account,config.trafficClass==="internal_test");const onboarding=createOnboardingOutbox(db,async()=>{const batch=await telemetry.readBatch({limit:1});if(!("ok"in batch))throw Error("TELEMETRY_UNAVAILABLE");return{enabled:batch.ok.enabled,installId:batch.ok.userId}},config.trafficClass==="internal_test");const destination=createHash("sha256").update(endpoint+"\0"+(config.projectKey??"")+(config.format?"\0"+config.format:"")).digest("hex"),stop=new AbortController;const now=runtime.now??Date.now,random=runtime.random??Math.random;let closed=false,pending,identityPromise,lastCollection;db.prepare("INSERT OR IGNORE INTO delivery_state(destination) VALUES(?)").run(destination);const gaps=createCollectionGapOutbox(db,destination,config.trafficClass??"usage");const checkpoint=db.prepare("SELECT * FROM checkpoints WHERE destination=?");const deliveryState=db.prepare("SELECT * FROM delivery_state WHERE destination=?");const failure=db.prepare("UPDATE delivery_state SET failure_count=?,next_retry_at=?,last_error=? WHERE destination=?");const batchSize=db.prepare("UPDATE delivery_state SET last_batch_bytes=?,last_batch_events=? WHERE destination=?");const resetFailure=db.prepare("UPDATE delivery_state SET failure_count=0,next_retry_at=0,last_error=NULL WHERE destination=?");const advance=db.prepare("INSERT INTO checkpoints(destination,user_id,cursor,last_success) VALUES(?,?,?,?) ON CONFLICT(destination) DO UPDATE SET cursor=MAX(cursor,excluded.cursor),last_success=COALESCE(excluded.last_success,last_success) WHERE user_id=excluded.user_id");const acknowledgeAttribution=db.prepare("UPDATE install_attribution SET delivered=1 WHERE id=1 AND install_id=?");function failed(reason,retryAfter){const count=Math.min(1e6,Number(deliveryState.get(destination)?.failure_count??0)+1),at=now();failure.run(count,at+retryDelayMs(count,retryAfter,at,random()),reason,destination)}async function prefixCursor(batch,after,consumed){if(!consumed)return ok(after);const positions=batch.eventCursors;if(positions){if(!Number.isSafeInteger(batch.cursor)||positions.length!==batch.events.length||positions.some((value,index)=>!Number.isSafeInteger(value)||value<=(index?positions[index-1]:after)||value>batch.cursor))return businessError("data_loss","Telemetry batch contains invalid cursor positions.","storage");return ok(positions[consumed-1])}if(consumed===batch.events.length)return ok(batch.cursor);const prefix=await telemetry.readBatch({after,limit:consumed});if(!("ok"in prefix))return prefix;if(!prefix.ok.enabled)return businessError("failed_precondition","Telemetry was disabled before delivery.","storage");if(prefix.ok.userId!==batch.userId||prefix.ok.events.length!==consumed||prefix.ok.events.some((event,index)=>event.id!==batch.events[index]?.id||event.at!==batch.events[index]?.at)||!Number.isSafeInteger(prefix.ok.cursor)||prefix.ok.cursor<=after||prefix.ok.cursor>batch.cursor)return businessError("data_loss","Telemetry prefix changed before delivery.","storage");return ok(prefix.ok.cursor)}async function send(){if(!configured)return businessError("failed_precondition","PostHog host/project configuration is missing.","plugin");const prior=checkpoint.get(destination),cursor=Number(prior?.cursor??0);const probe=await telemetry.readBatch({after:cursor,limit:1});if(!("ok"in probe))return probe;lastCollection=isUsageCollection(probe.ok.collection)?{...probe.ok.collection}:void 0;if(!probe.ok.enabled)return ok({sent:0,more:false});if(prior&&prior.user_id!==probe.ok.userId)return businessError("data_loss","Telemetry identity differs from the delivery checkpoint.","storage");const gapHead=gaps.observe(lastCollection,cursor,probe.ok.userId,new Date(now()).toISOString());if(gapHead&&gapHead.event.properties.install_id!==probe.ok.userId)return businessError("data_loss","Telemetry identity differs from the pending collection diagnostic.","storage");const cloudHead=cloud.read(destination,1),updateHead=updates.read(destination,1),onboardingHead=onboarding.read(destination,1);const attribution=config.format==="northstar"?installationAttribution(db,probe.ok.userId,new Date(now())):void 0;if(!probe.ok.events.length&&!cloudHead.events.length&&!updateHead.events.length&&!onboardingHead.events.length&&!attribution?.pending&&!gapHead)return ok({sent:0,more:false});if(Number(deliveryState.get(destination)?.next_retry_at??0)>now())return ok({sent:0,more:true});const read=probe.ok.more?await telemetry.readBatch({after:cursor,limit:MAX_BATCH_EVENTS}):probe;if(!("ok"in read))return read;const batch=read.ok;const collection=isUsageCollection(batch.collection)?{...batch.collection}:void 0,collectionObservedAt=new Date(now()).toISOString();lastCollection=collection;if(!batch.enabled)return ok({sent:0,more:false});if(batch.userId!==probe.ok.userId)return businessError("data_loss","Telemetry identity changed before delivery.","storage");const gap=gaps.observe(collection,cursor,batch.userId,collectionObservedAt);if(gap&&gap.event.properties.install_id!==batch.userId)return businessError("data_loss","Telemetry identity differs from the pending collection diagnostic.","storage");const cloudBatch=cloudHead.more?cloud.read(destination):cloudHead,updateBatch=updateHead.more?updates.read(destination):updateHead,onboardingBatch=onboardingHead.more?onboarding.read(destination):onboardingHead;const pack=createBatchPacker(config.projectKey);const decorate=(event,legacyContext=false)=>({...event,properties:{...event.properties,traffic_class:event.event.startsWith("zortex outcome ")?"real":config.trafficClass??"usage",...!event.event.startsWith("zortex outcome ")&&attribution&&event.timestamp>=attribution.at?{install_ref_hash:attribution.hash,attribution_scheme:"website_install_ref_v1"}:{},...legacyContext&&config.executionLocation?{execution_location:config.executionLocation,execution_location_provenance:"legacy_delivery_config"}:{}}});const gapIncluded=!!gap&&pack.append([gap.event]);const attributionIncluded=!!attribution?.pending&&pack.append([decorate(attribution.event)]);let cloudConsumed=0,updateConsumed=0,onboardingConsumed=0,consumed=0;for(const event of cloudBatch.events){if(!pack.append([event]))break;cloudConsumed++}for(const event of updateBatch.events){if(!pack.append([event]))break;updateConsumed++}for(const event of onboardingBatch.events){if(!pack.append([event]))break;onboardingConsumed++}for(const row of batch.events){const login=config.format==="northstar"&&config.trafficClass!=="internal_test"&&hasScoredOutcome(row)?await(identityPromise??=identity().catch(()=>void 0)):void 0;const group=config.format==="northstar"?northstarEvents(row,batch.userId,login,config.trafficClass==="internal_test"?void 0:account?.identityAt(row.at),config.trafficClass!=="internal_test"):rawUsageEvents(row,batch.userId);if(!pack.append(group.map(event=>decorate(event,!row.context))))break;consumed++}const position=await prefixCursor(batch,cursor,consumed);if(!("ok"in position))return position;let more=consumed<batch.events.length||batch.more||cloudConsumed<cloudBatch.events.length||cloudBatch.more||updateConsumed<updateBatch.events.length||updateBatch.more||onboardingConsumed<onboardingBatch.events.length||onboardingBatch.more||!!attribution?.pending&&!attributionIncluded||!!gap&&!gapIncluded;if(!pack.count&&!consumed){failed("payload_too_large");return businessError("resource_exhausted","A telemetry event group exceeds the delivery body limit.","plugin")}if(closed)return businessError("aborted","PostHog delivery closed before sending.","plugin");if(pack.count){batchSize.run(pack.bytes,pack.count,destination);const response=await request(endpoint,{method:"POST",headers:{"content-type":"application/json"},body:pack.body(),signal:AbortSignal.any([stop.signal,AbortSignal.timeout(1e4)]),redirect:"error"});if(closed){await response.body?.cancel().catch(()=>{});return businessError("aborted","PostHog delivery closed before acknowledgement.","plugin")}if(!response.ok){failed("http_"+response.status,response.status===429||response.status>=500?response.headers.get("retry-after")??void 0:void 0);await response.body?.cancel().catch(()=>{});return businessError(response.status===401||response.status===403?"unauthenticated":"unavailable","PostHog did not accept the batch ("+response.status+").","plugin")}const reader=response.body?.getReader(),decoder=new TextDecoder;let bytes="",length=0;if(reader){try{while(true){const part=await reader.read();if(part.done)break;length+=part.value.byteLength;if(length>4096){await reader.cancel();break}bytes+=decoder.decode(part.value,{stream:true})}bytes+=decoder.decode()}finally{reader.releaseLock()}}let accepted=false;try{const status=JSON.parse(bytes).status;accepted=length<=4096&&(status===1||status==="Ok")}catch{}if(!accepted){failed("invalid_ack");return businessError("data_loss","PostHog returned no valid batch acknowledgement.","plugin")}}if(closed)return businessError("aborted","PostHog delivery closed before acknowledgement.","plugin");db.exec("BEGIN IMMEDIATE");try{const changed=advance.run(destination,batch.userId,position.ok,pack.count?new Date(now()).toISOString():null);if(!changed.changes)throw Error("CHECKPOINT_IDENTITY_CHANGED");if(cloudConsumed)cloud.acknowledge(destination,cloudBatch.eventCursors[cloudConsumed-1]);if(updateConsumed)updates.acknowledge(destination,updateBatch.eventCursors[updateConsumed-1]);if(onboardingConsumed)onboarding.acknowledge(destination,onboardingBatch.eventCursors[onboardingConsumed-1]);if(attributionIncluded)acknowledgeAttribution.run(batch.userId);if(gapIncluded)gaps.acknowledge(gap);if(gaps.observe(collection,cursor,batch.userId,collectionObservedAt))more=true;if(pack.count)resetFailure.run(destination);db.exec("COMMIT")}catch(error){db.exec("ROLLBACK");throw error}return ok({sent:pack.count,more})}const service={recordLocalCloudCall:input=>cloud.recordLocalCloudCall(input),recordUpdateAttempt:input=>updates.recordUpdateAttempt(input),recordOnboardingAttempt:input=>onboarding.recordOnboardingAttempt(input),async flush(options){if(options?.wait)await pending;if(closed)return businessError("unavailable","PostHog delivery is inactive.","plugin");if(pending)return businessError("resource_exhausted","A PostHog batch is already in flight.","plugin");pending=send().catch(()=>{if(!closed){try{failed("transport_failure")}catch{}}return businessError(closed?"aborted":"unavailable","PostHog transport or checkpoint failed.","plugin")});try{return await pending}finally{pending=void 0}},async status(){if(closed)return businessError("unavailable","PostHog delivery is inactive.","plugin");const row=checkpoint.get(destination),state=deliveryState.get(destination);return ok({configured,cursor:Number(row?.cursor??0),consecutiveFailures:Number(state?.failure_count??0),...lastCollection?{collection:{...lastCollection}}:{},...state?.last_error?{lastError:String(state.last_error)}:{},...row?.last_success?{lastSuccess:String(row.last_success)}:{},...Number(state?.next_retry_at??0)>0?{nextRetryAt:new Date(Number(state.next_retry_at)).toISOString()}:{},...state?.last_batch_bytes!==null&&state?.last_batch_bytes!==void 0?{lastBatchBytes:Number(state.last_batch_bytes),lastBatchEvents:Number(state.last_batch_events)}:{}})},async close(){if(closed)return;closed=true;stop.abort();await pending;await cloud.close();await updates.close();await onboarding.close();db.close()}};return service}export async function apply(ctx,config){const interval=config.intervalMs??3e4;if(!Number.isInteger(interval)||interval<1e3||interval>36e5)throw Error("PostHog interval must be 1\u20133600 seconds.");const account={identityAt:at=>ctx.get("zortexProductAccount")?.identityAt(at)};const service=await createPostHog(config,ctx.zortexTelemetry,fetch,verifiedGithubLogin,verifiedGithubPerson,account);ctx.provide("zortexPostHog",service);ctx.effect(()=>{const timer=setInterval(()=>{void service.flush()},interval);timer.unref();void service.flush();return async()=>{clearInterval(timer);await service.close()}})}
|
|
1
|
+
import{DatabaseSync}from"node:sqlite";import{mkdir,lstat,realpath}from"node:fs/promises";import{isAbsolute,join}from"node:path";import{createHash}from"node:crypto";import{hasScoredOutcome,northstarEvents,rawUsageEvents}from"./northstar.js";import{createBatchPacker,MAX_BATCH_EVENTS,retryDelayMs}from"./delivery-policy.js";import{createCollectionGapOutbox,initializeCollectionGap}from"./collection-gap.js";import{initializeAttribution,installationAttribution}from"./install-attribution.js";import{verifiedGithubLogin,verifiedGithubPerson}from"./github-identity.js";import{createLocalCloudOutbox}from"./local-cloud.js";import{createUpdateOutbox}from"./product-update.js";import{createOnboardingOutbox}from"./onboarding.js";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{isUsageCollection,currentTelemetryContext}from"@zortexhq/plugin-telemetry/api";export const name="zortex-posthog",inject=["zortexTelemetry"];export async function createPostHog(config,telemetry,request=fetch,identity=verifiedGithubLogin,_personIdentity=verifiedGithubPerson,account,runtime={}){const captureClass=currentTelemetryContext()?.trafficClass;const simulated=config.trafficClass==="simulation"||captureClass==="simulation";const internalTraffic=config.trafficClass==="internal_test"||captureClass==="internal_test";if(!isAbsolute(config.root))throw Error("PostHog data root must be absolute.");const configured=!!config.host&&!!config.projectKey;let endpoint="";if(configured){const url=new URL(config.host);if(url.protocol!=="https:"||url.username||url.password||url.search||url.hash||url.pathname!=="/")throw Error("PostHog host must be an HTTPS origin.");endpoint=new URL("/batch/",url).href}await mkdir(config.root,{recursive:true,mode:448});if((await lstat(config.root)).isSymbolicLink())throw Error("PostHog data root cannot be a link.");const file=join(await realpath(config.root),"posthog.sqlite");if((await lstat(file).catch(()=>null))?.isSymbolicLink())throw Error("PostHog checkpoint cannot be a link.");const db=new DatabaseSync(file);try{db.exec("PRAGMA busy_timeout=3000;PRAGMA journal_mode=WAL;CREATE TABLE IF NOT EXISTS checkpoints(destination TEXT PRIMARY KEY,user_id TEXT NOT NULL,cursor INTEGER NOT NULL,last_success TEXT);CREATE TABLE IF NOT EXISTS delivery_state(destination TEXT PRIMARY KEY,failure_count INTEGER NOT NULL DEFAULT 0,next_retry_at INTEGER NOT NULL DEFAULT 0,last_error TEXT,last_batch_bytes INTEGER,last_batch_events INTEGER);");initializeCollectionGap(db)}catch(error){db.close();throw error}initializeAttribution(db);const cloud=createLocalCloudOutbox(db,async()=>{const batch=await telemetry.readBatch({limit:1});if(!("ok"in batch))throw Error("TELEMETRY_UNAVAILABLE");return{enabled:!simulated&&batch.ok.enabled,installId:batch.ok.userId}},internalTraffic);const updates=createUpdateOutbox(db,async()=>{if(simulated)return false;const batch=await telemetry.readBatch({limit:1});if(!("ok"in batch))throw Error("TELEMETRY_UNAVAILABLE");return batch.ok.enabled},account,internalTraffic);const onboarding=createOnboardingOutbox(db,async()=>{const batch=await telemetry.readBatch({limit:1});if(!("ok"in batch))throw Error("TELEMETRY_UNAVAILABLE");return{enabled:!simulated&&batch.ok.enabled,installId:batch.ok.userId}},internalTraffic);const destination=createHash("sha256").update(endpoint+"\0"+(config.projectKey??"")+(config.format?"\0"+config.format:"")).digest("hex"),stop=new AbortController;const now=runtime.now??Date.now,random=runtime.random??Math.random;let closed=false,pending,identityPromise,lastCollection;db.prepare("INSERT OR IGNORE INTO delivery_state(destination) VALUES(?)").run(destination);const gaps=createCollectionGapOutbox(db,destination,internalTraffic?"internal_test":"usage");const checkpoint=db.prepare("SELECT * FROM checkpoints WHERE destination=?");const deliveryState=db.prepare("SELECT * FROM delivery_state WHERE destination=?");const failure=db.prepare("UPDATE delivery_state SET failure_count=?,next_retry_at=?,last_error=? WHERE destination=?");const batchSize=db.prepare("UPDATE delivery_state SET last_batch_bytes=?,last_batch_events=? WHERE destination=?");const resetFailure=db.prepare("UPDATE delivery_state SET failure_count=0,next_retry_at=0,last_error=NULL WHERE destination=?");const advance=db.prepare("INSERT INTO checkpoints(destination,user_id,cursor,last_success) VALUES(?,?,?,?) ON CONFLICT(destination) DO UPDATE SET cursor=MAX(cursor,excluded.cursor),last_success=COALESCE(excluded.last_success,last_success) WHERE user_id=excluded.user_id");const acknowledgeAttribution=db.prepare("UPDATE install_attribution SET delivered=1 WHERE id=1 AND install_id=?");function failed(reason,retryAfter){const count=Math.min(1e6,Number(deliveryState.get(destination)?.failure_count??0)+1),at=now();failure.run(count,at+retryDelayMs(count,retryAfter,at,random()),reason,destination)}async function prefixCursor(batch,after,consumed){if(!consumed)return ok(after);const positions=batch.eventCursors;if(positions){if(!Number.isSafeInteger(batch.cursor)||positions.length!==batch.events.length||positions.some((value,index)=>!Number.isSafeInteger(value)||value<=(index?positions[index-1]:after)||value>batch.cursor))return businessError("data_loss","Telemetry batch contains invalid cursor positions.","storage");return ok(positions[consumed-1])}if(consumed===batch.events.length)return ok(batch.cursor);const prefix=await telemetry.readBatch({after,limit:consumed});if(!("ok"in prefix))return prefix;if(!prefix.ok.enabled)return businessError("failed_precondition","Telemetry was disabled before delivery.","storage");if(prefix.ok.userId!==batch.userId||prefix.ok.events.length!==consumed||prefix.ok.events.some((event,index)=>event.id!==batch.events[index]?.id||event.at!==batch.events[index]?.at)||!Number.isSafeInteger(prefix.ok.cursor)||prefix.ok.cursor<=after||prefix.ok.cursor>batch.cursor)return businessError("data_loss","Telemetry prefix changed before delivery.","storage");return ok(prefix.ok.cursor)}async function send(){if(simulated)return ok({sent:0,more:false});if(!configured)return businessError("failed_precondition","PostHog host/project configuration is missing.","plugin");const prior=checkpoint.get(destination),cursor=Number(prior?.cursor??0);const probe=await telemetry.readBatch({after:cursor,limit:1});if(!("ok"in probe))return probe;lastCollection=isUsageCollection(probe.ok.collection)?{...probe.ok.collection}:void 0;if(!probe.ok.enabled)return ok({sent:0,more:false});if(prior&&prior.user_id!==probe.ok.userId)return businessError("data_loss","Telemetry identity differs from the delivery checkpoint.","storage");const gapHead=gaps.observe(lastCollection,cursor,probe.ok.userId,new Date(now()).toISOString());if(gapHead&&gapHead.event.properties.install_id!==probe.ok.userId)return businessError("data_loss","Telemetry identity differs from the pending collection diagnostic.","storage");const cloudHead=cloud.read(destination,1),updateHead=updates.read(destination,1),onboardingHead=onboarding.read(destination,1);const attribution=config.format==="northstar"?installationAttribution(db,probe.ok.userId,new Date(now())):void 0;if(!probe.ok.events.length&&!cloudHead.events.length&&!updateHead.events.length&&!onboardingHead.events.length&&!attribution?.pending&&!gapHead)return ok({sent:0,more:false});if(Number(deliveryState.get(destination)?.next_retry_at??0)>now())return ok({sent:0,more:true});const read=probe.ok.more?await telemetry.readBatch({after:cursor,limit:MAX_BATCH_EVENTS}):probe;if(!("ok"in read))return read;const batch=read.ok;const collection=isUsageCollection(batch.collection)?{...batch.collection}:void 0,collectionObservedAt=new Date(now()).toISOString();lastCollection=collection;if(!batch.enabled)return ok({sent:0,more:false});if(batch.userId!==probe.ok.userId)return businessError("data_loss","Telemetry identity changed before delivery.","storage");const gap=gaps.observe(collection,cursor,batch.userId,collectionObservedAt);if(gap&&gap.event.properties.install_id!==batch.userId)return businessError("data_loss","Telemetry identity differs from the pending collection diagnostic.","storage");const cloudBatch=cloudHead.more?cloud.read(destination):cloudHead,updateBatch=updateHead.more?updates.read(destination):updateHead,onboardingBatch=onboardingHead.more?onboarding.read(destination):onboardingHead;const pack=createBatchPacker(config.projectKey);const withAttribution=event=>!event.event.startsWith("zortex outcome ")&&attribution&&event.timestamp>=attribution.at?{...event,properties:{...event.properties,install_ref_hash:attribution.hash,attribution_scheme:"website_install_ref_v1"}}:event;const decorate=(event,legacyContext=false)=>({...event,properties:{...withAttribution(event).properties,traffic_class:event.event.startsWith("zortex outcome ")?"real":internalTraffic||event.properties.capture_traffic_class==="internal_test"?"internal_test":"usage",...legacyContext&&config.executionLocation?{execution_location:config.executionLocation,execution_location_provenance:"legacy_delivery_config"}:{}}});const gapIncluded=!!gap&&pack.append([gap.event]);const attributionIncluded=!!attribution?.pending&&pack.append([decorate(attribution.event)]);let cloudConsumed=0,updateConsumed=0,onboardingConsumed=0,consumed=0;for(const event of cloudBatch.events){if(!pack.append([event]))break;cloudConsumed++}for(const event of updateBatch.events){if(!pack.append([event]))break;updateConsumed++}for(const event of onboardingBatch.events){if(!pack.append([withAttribution(event)]))break;onboardingConsumed++}for(const row of batch.events){if(row.context?.trafficClass==="simulation"){consumed++;continue}const internalTest=internalTraffic||row.context?.trafficClass==="internal_test";const login=config.format==="northstar"&&!internalTest&&hasScoredOutcome(row)?await(identityPromise??=identity().catch(()=>void 0)):void 0;const group=config.format==="northstar"?northstarEvents(row,batch.userId,login,internalTest?void 0:account?.identityAt(row.at),!internalTest):rawUsageEvents(row,batch.userId);if(!pack.append(group.map(event=>decorate(event,!row.context))))break;consumed++}const position=await prefixCursor(batch,cursor,consumed);if(!("ok"in position))return position;let more=consumed<batch.events.length||batch.more||cloudConsumed<cloudBatch.events.length||cloudBatch.more||updateConsumed<updateBatch.events.length||updateBatch.more||onboardingConsumed<onboardingBatch.events.length||onboardingBatch.more||!!attribution?.pending&&!attributionIncluded||!!gap&&!gapIncluded;if(!pack.count&&!consumed){failed("payload_too_large");return businessError("resource_exhausted","A telemetry event group exceeds the delivery body limit.","plugin")}if(closed)return businessError("aborted","PostHog delivery closed before sending.","plugin");if(pack.count){batchSize.run(pack.bytes,pack.count,destination);const response=await request(endpoint,{method:"POST",headers:{"content-type":"application/json"},body:pack.body(),signal:AbortSignal.any([stop.signal,AbortSignal.timeout(1e4)]),redirect:"error"});if(closed){await response.body?.cancel().catch(()=>{});return businessError("aborted","PostHog delivery closed before acknowledgement.","plugin")}if(!response.ok){failed("http_"+response.status,response.status===429||response.status>=500?response.headers.get("retry-after")??void 0:void 0);await response.body?.cancel().catch(()=>{});return businessError(response.status===401||response.status===403?"unauthenticated":"unavailable","PostHog did not accept the batch ("+response.status+").","plugin")}const reader=response.body?.getReader(),decoder=new TextDecoder;let bytes="",length=0;if(reader){try{while(true){const part=await reader.read();if(part.done)break;length+=part.value.byteLength;if(length>4096){await reader.cancel();break}bytes+=decoder.decode(part.value,{stream:true})}bytes+=decoder.decode()}finally{reader.releaseLock()}}let accepted=false;try{const status=JSON.parse(bytes).status;accepted=length<=4096&&(status===1||status==="Ok")}catch{}if(!accepted){failed("invalid_ack");return businessError("data_loss","PostHog returned no valid batch acknowledgement.","plugin")}}if(closed)return businessError("aborted","PostHog delivery closed before acknowledgement.","plugin");db.exec("BEGIN IMMEDIATE");try{const changed=advance.run(destination,batch.userId,position.ok,pack.count?new Date(now()).toISOString():null);if(!changed.changes)throw Error("CHECKPOINT_IDENTITY_CHANGED");if(cloudConsumed)cloud.acknowledge(destination,cloudBatch.eventCursors[cloudConsumed-1]);if(updateConsumed)updates.acknowledge(destination,updateBatch.eventCursors[updateConsumed-1]);if(onboardingConsumed)onboarding.acknowledge(destination,onboardingBatch.eventCursors[onboardingConsumed-1]);if(attributionIncluded)acknowledgeAttribution.run(batch.userId);if(gapIncluded)gaps.acknowledge(gap);if(gaps.observe(collection,cursor,batch.userId,collectionObservedAt))more=true;if(pack.count)resetFailure.run(destination);db.exec("COMMIT")}catch(error){db.exec("ROLLBACK");throw error}return ok({sent:pack.count,more})}const service={recordLocalCloudCall:input=>cloud.recordLocalCloudCall(input),recordUpdateAttempt:input=>updates.recordUpdateAttempt(input),recordOnboardingAttempt:input=>onboarding.recordOnboardingAttempt(input),async flush(options){if(options?.wait)await pending;if(closed)return businessError("unavailable","PostHog delivery is inactive.","plugin");if(pending)return businessError("resource_exhausted","A PostHog batch is already in flight.","plugin");pending=send().catch(()=>{if(!closed){try{failed("transport_failure")}catch{}}return businessError(closed?"aborted":"unavailable","PostHog transport or checkpoint failed.","plugin")});try{return await pending}finally{pending=void 0}},async status(){if(closed)return businessError("unavailable","PostHog delivery is inactive.","plugin");const row=checkpoint.get(destination),state=deliveryState.get(destination);return ok({configured,cursor:Number(row?.cursor??0),consecutiveFailures:Number(state?.failure_count??0),...lastCollection?{collection:{...lastCollection}}:{},...state?.last_error?{lastError:String(state.last_error)}:{},...row?.last_success?{lastSuccess:String(row.last_success)}:{},...Number(state?.next_retry_at??0)>0?{nextRetryAt:new Date(Number(state.next_retry_at)).toISOString()}:{},...state?.last_batch_bytes!==null&&state?.last_batch_bytes!==void 0?{lastBatchBytes:Number(state.last_batch_bytes),lastBatchEvents:Number(state.last_batch_events)}:{}})},async close(){if(closed)return;closed=true;stop.abort();await pending;await cloud.close();await updates.close();await onboarding.close();db.close()}};return service}export async function apply(ctx,config){const interval=config.intervalMs??3e4;if(!Number.isInteger(interval)||interval<1e3||interval>36e5)throw Error("PostHog interval must be 1\u20133600 seconds.");const account={identityAt:at=>ctx.get("zortexProductAccount")?.identityAt(at)};const service=await createPostHog(config,ctx.zortexTelemetry,fetch,verifiedGithubLogin,verifiedGithubPerson,account);ctx.provide("zortexPostHog",service);ctx.effect(()=>{const timer=setInterval(()=>{void service.flush()},interval);timer.unref();void service.flush();return async()=>{clearInterval(timer);await service.close()}})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{apply as applyPostHog}from"./index.js";export const name="indra-product-feedback",inject=["zortexTelemetry","zortexProductAccount"];const projectKey="phc_vMFzw2oWh4H4eLT8b5kCu3zXqoT8gw5HRDucMezD5ast";export async function apply(ctx,config){if(!/^(0|false|off|no)$/i.test((process.env.ZORTEX_TELEMETRY??"").trim())&&!/^(1|true|yes)$/i.test((process.env.DO_NOT_TRACK??"").trim()))process.stderr.write("indra: content-free usage diagnostics go to team PostHog (US); set ZORTEX_TELEMETRY=0 to disable.\n");await applyPostHog(ctx,{root:config.root,host:"https://us.i.posthog.com",projectKey,format:"northstar",...["local","cloud"].includes(process.env.ZORTEX_EXECUTION_MODE??"")?{executionLocation:process.env.ZORTEX_EXECUTION_MODE}:{},...process.env.ZORTEX_FEEDBACK_TRAFFIC_CLASS==="internal_test"?{trafficClass:"internal_test"}:{}})}
|
|
1
|
+
import{apply as applyPostHog}from"./index.js";export const name="indra-product-feedback",inject=["zortexTelemetry","zortexProductAccount"];const projectKey="phc_vMFzw2oWh4H4eLT8b5kCu3zXqoT8gw5HRDucMezD5ast";export async function apply(ctx,config){if(!/^(0|false|off|no)$/i.test((process.env.ZORTEX_TELEMETRY??"").trim())&&!/^(1|true|yes)$/i.test((process.env.DO_NOT_TRACK??"").trim()))process.stderr.write("indra: content-free usage diagnostics go to team PostHog (US); set ZORTEX_TELEMETRY=0 to disable.\n");await applyPostHog(ctx,{root:config.root,host:"https://us.i.posthog.com",projectKey,format:"northstar",...["local","cloud"].includes(process.env.ZORTEX_EXECUTION_MODE??"")?{executionLocation:process.env.ZORTEX_EXECUTION_MODE}:{},...process.env.ZORTEX_FEEDBACK_TRAFFIC_CLASS==="internal_test"?{trafficClass:"internal_test"}:process.env.ZORTEX_FEEDBACK_TRAFFIC_CLASS==="simulation"?{trafficClass:"simulation"}:{}})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{TELEMETRY_OUTCOMES,USAGE_TOOL_NAMES}from"@zortexhq/plugin-telemetry/api";const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;const fail=message=>businessError("failed_precondition",message,"plugin");export function createLocalCloudOutbox(db,context,internal){db.exec("CREATE TABLE IF NOT EXISTS local_cloud_calls(id TEXT PRIMARY KEY,receipt TEXT NOT NULL);CREATE TABLE IF NOT EXISTS local_cloud_events(seq INTEGER PRIMARY KEY AUTOINCREMENT,payload TEXT NOT NULL);CREATE TABLE IF NOT EXISTS local_cloud_checkpoints(destination TEXT PRIMARY KEY,cursor INTEGER NOT NULL);");const checkpoint=db.prepare("SELECT cursor FROM local_cloud_checkpoints WHERE destination=?");const pendingRows=db.prepare("SELECT seq,payload FROM local_cloud_events WHERE seq>? ORDER BY seq LIMIT ?");const advance=db.prepare("INSERT INTO local_cloud_checkpoints(destination,cursor) VALUES(?,?) ON CONFLICT(destination) DO UPDATE SET cursor=MAX(cursor,excluded.cursor)");let closed=false;const active=new Set;const track=work=>{if(closed)return Promise.resolve(fail("Local Cloud observation is closed."));const task=work().catch(()=>businessError("unavailable","Local Cloud observation could not be stored.","storage"));active.add(task);void task.finally(()=>active.delete(task));return task};const append=event=>db.prepare("INSERT INTO local_cloud_events(payload) VALUES(?)").run(JSON.stringify(event));const transaction=work=>{db.exec("BEGIN IMMEDIATE");try{work();db.exec("COMMIT")}catch(error){db.exec("ROLLBACK");throw error}};const common=call=>({product:"indra-v2",$process_person_profile:false,$geoip_disable:true,call_id:call.id,score_outcome_id:"local-cloud",score_outcome_version:/^local-cloud-v[1-9][0-9]{0,2}$/.test(call.version)?call.version:"unknown",success:call.success,duration_ms:call.durationMs,entrypoint:"local_cloud",tool:call.tool&&call.tool!=="unknown"?"indra."+call.tool:"unknown",tool_known:!!call.tool&&call.tool!=="unknown",outcome:call.outcome??"unknown"});return{recordLocalCloudCall(input){return track(async()=>{input={...input};if(!input||Object.keys(input).some(k=>!["id","at","version","success","durationMs","tool","outcome","entrypoint"].includes(k))||typeof input.id!=="string"||!uuid.test(input.id)||typeof input.at!=="string"||!Number.isFinite(Date.parse(input.at))||new Date(Date.parse(input.at)).toISOString()!==input.at||Math.abs(Date.now()-Date.parse(input.at))>864e5||typeof input.version!=="string"||!/^[a-zA-Z0-9._-]{1,80}$/.test(input.version)||typeof input.success!=="boolean"||!Number.isSafeInteger(input.durationMs)||input.durationMs<0||input.durationMs>864e5||input.tool!==void 0&&!USAGE_TOOL_NAMES.includes(input.tool)||input.outcome!==void 0&&!TELEMETRY_OUTCOMES.includes(input.outcome)||input.entrypoint!==void 0&&input.entrypoint!=="local_cloud")return fail("Pass only bounded content-free Local Cloud receipt fields.");const state=await context();if(!state.enabled)return ok({recorded:false});if(closed)return fail("Local Cloud observation is closed.");const call={id:input.id,at:input.at,version:input.version,success:input.success,durationMs:input.durationMs,...input.tool!==void 0?{tool:input.tool}:{},...input.outcome!==void 0?{outcome:input.outcome}:{},...input.entrypoint!==void 0?{entrypoint:input.entrypoint}:{}},serialized=JSON.stringify(call);let recorded=false;transaction(()=>{const prior=db.prepare("SELECT receipt FROM local_cloud_calls WHERE id=?").get(call.id);if(prior){if(prior.receipt!==serialized)throw Error("RECEIPT_CONFLICT");return}db.prepare("INSERT INTO local_cloud_calls(id,receipt) VALUES(?,?)").run(call.id,serialized);append({event:"local_cloud_task",uuid:randomUUID(),timestamp:call.at,properties:{...common(call),distinct_id:state.installId,install_id:state.installId,identity_scope:"installation",identity_scheme:"random_install_v1",trial_confirmed:false,traffic_class:internal?"internal_test":"usage"}});recorded=true});return ok({recorded})})},read(destination,limit=100){const size=Math.max(1,Math.min(100,Math.floor(limit))),startCursor=Number(checkpoint.get(destination)?.cursor??0),rows=pendingRows.all(startCursor,size+1),selected=rows.slice(0,size);return{events:selected.map(r=>JSON.parse(String(r.payload))),eventCursors:selected.map(r=>Number(r.seq)),startCursor,cursor:Number(selected.at(-1)?.seq??startCursor),more:rows.length>size}},acknowledge(destination,cursor){advance.run(destination,cursor)},async close(){closed=true;await Promise.allSettled(active)}}}
|
|
1
|
+
import{randomUUID}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{TELEMETRY_OUTCOMES,USAGE_TOOL_NAMES,isOperationalContext}from"@zortexhq/plugin-telemetry/api";const uuid=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;const fail=message=>businessError("failed_precondition",message,"plugin");export function createLocalCloudOutbox(db,context,internal){db.exec("CREATE TABLE IF NOT EXISTS local_cloud_calls(id TEXT PRIMARY KEY,receipt TEXT NOT NULL);CREATE TABLE IF NOT EXISTS local_cloud_events(seq INTEGER PRIMARY KEY AUTOINCREMENT,payload TEXT NOT NULL);CREATE TABLE IF NOT EXISTS local_cloud_checkpoints(destination TEXT PRIMARY KEY,cursor INTEGER NOT NULL);");const checkpoint=db.prepare("SELECT cursor FROM local_cloud_checkpoints WHERE destination=?");const pendingRows=db.prepare("SELECT seq,payload FROM local_cloud_events WHERE seq>? ORDER BY seq LIMIT ?");const advance=db.prepare("INSERT INTO local_cloud_checkpoints(destination,cursor) VALUES(?,?) ON CONFLICT(destination) DO UPDATE SET cursor=MAX(cursor,excluded.cursor)");let closed=false;const active=new Set;const track=work=>{if(closed)return Promise.resolve(fail("Local Cloud observation is closed."));const task=work().catch(()=>businessError("unavailable","Local Cloud observation could not be stored.","storage"));active.add(task);void task.finally(()=>active.delete(task));return task};const append=event=>db.prepare("INSERT INTO local_cloud_events(payload) VALUES(?)").run(JSON.stringify(event));const transaction=work=>{db.exec("BEGIN IMMEDIATE");try{work();db.exec("COMMIT")}catch(error){db.exec("ROLLBACK");throw error}};const common=call=>({product:"indra-v2",$process_person_profile:false,$geoip_disable:true,call_id:call.id,score_outcome_id:"local-cloud",score_outcome_version:/^local-cloud-v[1-9][0-9]{0,2}$/.test(call.version)?call.version:"unknown",success:call.success,duration_ms:call.durationMs,entrypoint:"local_cloud",tool:call.tool&&call.tool!=="unknown"?"indra."+call.tool:"unknown",tool_known:!!call.tool&&call.tool!=="unknown",outcome:call.outcome??"unknown",...call.execution?{run_id:call.execution.runId,step_id:call.execution.stepId}:{}});return{recordLocalCloudCall(input){return track(async()=>{input={...input};if(input.execution)input.execution={...input.execution};if(!input||Object.keys(input).some(k=>!["id","at","version","success","durationMs","tool","outcome","entrypoint","execution"].includes(k))||typeof input.id!=="string"||!uuid.test(input.id)||typeof input.at!=="string"||!Number.isFinite(Date.parse(input.at))||new Date(Date.parse(input.at)).toISOString()!==input.at||Math.abs(Date.now()-Date.parse(input.at))>864e5||typeof input.version!=="string"||!/^[a-zA-Z0-9._-]{1,80}$/.test(input.version)||typeof input.success!=="boolean"||!Number.isSafeInteger(input.durationMs)||input.durationMs<0||input.durationMs>864e5||input.tool!==void 0&&!USAGE_TOOL_NAMES.includes(input.tool)||input.outcome!==void 0&&!TELEMETRY_OUTCOMES.includes(input.outcome)||input.entrypoint!==void 0&&input.entrypoint!=="local_cloud"||input.execution!==void 0&&!isOperationalContext(input.execution))return fail("Pass only bounded content-free Local Cloud receipt fields.");const state=await context();if(!state.enabled)return ok({recorded:false});if(closed)return fail("Local Cloud observation is closed.");const call={id:input.id,at:input.at,version:input.version,success:input.success,durationMs:input.durationMs,...input.tool!==void 0?{tool:input.tool}:{},...input.outcome!==void 0?{outcome:input.outcome}:{},...input.entrypoint!==void 0?{entrypoint:input.entrypoint}:{},...input.execution?{execution:input.execution}:{}},serialized=JSON.stringify(call);let recorded=false;transaction(()=>{const prior=db.prepare("SELECT receipt FROM local_cloud_calls WHERE id=?").get(call.id);if(prior){if(prior.receipt!==serialized)throw Error("RECEIPT_CONFLICT");return}db.prepare("INSERT INTO local_cloud_calls(id,receipt) VALUES(?,?)").run(call.id,serialized);append({event:"local_cloud_task",uuid:randomUUID(),timestamp:call.at,properties:{...common(call),distinct_id:state.installId,install_id:state.installId,identity_scope:"installation",identity_scheme:"random_install_v1",trial_confirmed:false,traffic_class:internal?"internal_test":"usage"}});recorded=true});return ok({recorded})})},read(destination,limit=100){const size=Math.max(1,Math.min(100,Math.floor(limit))),startCursor=Number(checkpoint.get(destination)?.cursor??0),rows=pendingRows.all(startCursor,size+1),selected=rows.slice(0,size);return{events:selected.map(r=>JSON.parse(String(r.payload))),eventCursors:selected.map(r=>Number(r.seq)),startCursor,cursor:Number(selected.at(-1)?.seq??startCursor),more:rows.length>size}},acknowledge(destination,cursor){advance.run(destination,cursor)},async close(){closed=true;await Promise.allSettled(active)}}}
|
|
@@ -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";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=["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));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";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??"")}}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.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)}])}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),...invocationProperties(row)}:{};const eventAccount=row.operation==="product.feedback"?void 0:account;const accountProperties=eventAccount&&!scoreEvent?{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()}:{};const profileEnabled=processPersonProfile&&!scoreEvent;const profileProperties=profileEnabled?{$set:{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 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=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",$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),...invocationProperties(row),...observation?.properties??{}}}]}
|
|
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";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));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;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"}}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:account;const accountProperties=eventAccount&&!scoreEvent?{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()}:{};const profileEnabled=processPersonProfile&&!scoreEvent;const profileProperties=profileEnabled?{$set:{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",$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 +1 @@
|
|
|
1
|
-
import{isUsageInvocation,isUsageObservationFacts,snapshotUsageObservation}from"@zortexhq/plugin-telemetry/api";export function invocationProperties(row){const invocation=row.invocation?{...row.invocation}:void 0;return isUsageInvocation(invocation)?{entrypoint:invocation.entrypoint,invocation_known:true,invocation_id:invocation.id}:{entrypoint:"unknown",invocation_known:false}}export function invocationTool(row){const invocation=row.invocation?{...row.invocation}:void 0;return isUsageInvocation(invocation)?invocation.tool:void 0}export function observationProjection(row){const facts=snapshotUsageObservation(row.observation);if(!isUsageObservationFacts(facts)||row.operation!=="connector."+facts.kind||row.internal!==true)return;const common={observation_kind:facts.kind,connection_known:facts.connectionRef!==void 0,...facts.connectionRef?{connection_ref:facts.connectionRef}:{}};if(facts.kind==="inventory")return{event:"zortex inventory",properties:{...common,population:facts.population,attribution:facts.attribution,inventory_count_known:facts.countKnown,...facts.countKnown?{inventory_count:facts.count}:{},inventory_exact:facts.countKnown&&facts.coverage==="complete",count_basis:facts.countBasis,coverage:facts.coverage}};if(facts.kind==="connection")return{event:"zortex connection inventory",properties:{...common,provider:facts.provider,connection_state:facts.state,selected:facts.selected,grant_state:facts.grantState,permission_known:facts.permissionKnown,permission_basis:facts.permissionBasis,permission_capabilities:[...facts.capabilities].sort(),capability_count:facts.capabilities.length}};const known=(name,value)=>({[name+"_known"]:value!==void 0,...value!==void 0?{[name]:value}:{}});return{event:"zortex sync",properties:{...common,sync_status:facts.status,execution_phase:facts.execution??"unknown",duration_known:true,duration_ms:Math.round(facts.durationMs),...known("business_observed",facts.businessObserved),...known("sync_complete",facts.complete),...known("sync_ran",facts.ran),cleanup_known:facts.cleanupConfirmed!==void 0,...facts.cleanupConfirmed!==void 0?{cleanup_confirmed:facts.cleanupConfirmed}:{},...known("sync_stopped",facts.stopped),...known("sync_run_failed",facts.runFailed),...known("delivered_count",facts.delivered),...known("appended_count",facts.appended),...known("expected_count",facts.expected),coverage_streams_known:facts.coverageStreams!==void 0,...facts.coverageStreams!==void 0?{coverage_streams_count:facts.coverageStreams}:{},reason:facts.reason??"unknown"}}}
|
|
1
|
+
import{isUsageInvocation,isUsageObservationFacts,snapshotUsageObservation}from"@zortexhq/plugin-telemetry/api";export function invocationProperties(row){const invocation=row.invocation?{...row.invocation}:void 0;return isUsageInvocation(invocation)?{entrypoint:invocation.entrypoint,invocation_known:true,invocation_id:invocation.id,...invocation.sessionId?{transport_session_id:invocation.sessionId,transport_session_scope:invocation.sessionScope}:{}}:{entrypoint:"unknown",invocation_known:false}}export function invocationTool(row){const invocation=row.invocation?{...row.invocation}:void 0;return isUsageInvocation(invocation)?invocation.tool:void 0}export function observationProjection(row){const facts=snapshotUsageObservation(row.observation);if(!isUsageObservationFacts(facts)||row.operation!=="connector."+facts.kind||row.internal!==true)return;const common={observation_kind:facts.kind,connection_known:facts.connectionRef!==void 0,...facts.connectionRef?{connection_ref:facts.connectionRef}:{}};if(facts.kind==="inventory")return{event:"zortex inventory",properties:{...common,population:facts.population,attribution:facts.attribution,inventory_count_known:facts.countKnown,...facts.countKnown?{inventory_count:facts.count}:{},inventory_exact:facts.countKnown&&facts.coverage==="complete",count_basis:facts.countBasis,coverage:facts.coverage}};if(facts.kind==="connection")return{event:"zortex connection inventory",properties:{...common,provider:facts.provider,connection_state:facts.state,selected:facts.selected,grant_state:facts.grantState,permission_known:facts.permissionKnown,permission_basis:facts.permissionBasis,permission_capabilities:[...facts.capabilities].sort(),capability_count:facts.capabilities.length}};const known=(name,value)=>({[name+"_known"]:value!==void 0,...value!==void 0?{[name]:value}:{}});return{event:"zortex sync",properties:{...common,sync_status:facts.status,execution_phase:facts.execution??"unknown",duration_known:true,duration_ms:Math.round(facts.durationMs),...known("business_observed",facts.businessObserved),...known("sync_complete",facts.complete),...known("sync_ran",facts.ran),cleanup_known:facts.cleanupConfirmed!==void 0,...facts.cleanupConfirmed!==void 0?{cleanup_confirmed:facts.cleanupConfirmed}:{},...known("sync_stopped",facts.stopped),...known("sync_run_failed",facts.runFailed),...known("delivered_count",facts.delivered),...known("appended_count",facts.appended),...known("expected_count",facts.expected),coverage_streams_known:facts.coverageStreams!==void 0,...facts.coverageStreams!==void 0?{coverage_streams_count:facts.coverageStreams}:{},reason:facts.reason??"unknown"}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isUsageEvent,isOperationalContext}from"@zortexhq/plugin-telemetry/api";export function executionProperties(row){return isOperationalContext(row.execution)?{run_id:row.execution.runId,step_id:row.execution.stepId}:{}}export function operationalProperties(row){if(row.operation!=="product.trace"||!isUsageEvent(row,true)||!row.operational)return;const t=row.operational;if(row.execution&&(row.execution.runId!==t.runId||row.execution.stepId!==t.stepId))return;const duration=t.durationKnown&&Number.isFinite(row.durationMs)&&row.durationMs>=0&&row.durationMs<=864e5;return{trace_version:t.version,run_id:t.runId,step_id:t.stepId,...t.parentStepId?{parent_step_id:t.parentStepId}:{},emitter_id:t.emitterId,sequence:t.sequence,attempt:t.attempt,phase:t.phase,action:t.action,state:t.state,terminal:t.terminal,duration_known:duration,...duration?{duration_ms:Math.round(row.durationMs)}:{},coverage:"instrumented_steps_only",operation_id:t.operationId??"unknown",...t.sourceRef?{source_ref:t.sourceRef,source_identity:"installation_scoped"}:{},...t.processRef?{process_ref:t.processRef}:{},...t.actionRef?{action_ref:t.actionRef,action_identity:"installation_scoped"}:{},observed_count_known:t.observedCount!==void 0,...t.observedCount!==void 0?{observed_count:t.observedCount,count_basis:t.countBasis}:{},selection:t.selection??"unknown",trigger:t.trigger??"unknown",route:t.route??"unknown",profile:t.profile??"unknown",login_decision:t.loginDecision??"unknown",artifact_family:t.artifactFamily??"unknown",artifact_type:t.artifactType??"unknown",reason:t.reason??"unknown",error_category:t.errorCategory??"unknown",tool:t.tool??"unknown",method:t.method??"unknown",entrypoint:t.entrypoint??"unknown",download_observation:t.downloadObservation??"unknown",upstream_tool:t.upstreamTool??"unknown",rpc_method:t.rpcMethod??"unknown"}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isUsageEvent}from"@zortexhq/plugin-telemetry/api";export function resourceProperties(row){if(row.operation!=="product.resources"||!isUsageEvent(row,true)||!row.resource)return;const r=row.resource;const properties={resource_schema_version:r.schemaVersion,snapshot_id:r.snapshotId,resource_kind:r.kind,observed_at:r.asOf,sample_duration_ms:r.sampleDurationMs,resource_coverage:r.coverage};const copy=(key,value)=>{properties[key+"_known"]=value!==void 0;if(value!==void 0)properties[key]=value};if(r.kind==="process"){Object.assign(properties,{process_ref:r.processRef,process_role:r.role,memory_scope:r.memoryScope,child_memory_coverage:r.childMemoryCoverage,rss_basis:r.rssBasis??"unknown",cpu_basis:"process_cumulative_microseconds"});for(const[key,value]of Object.entries({rss_bytes:r.rssBytes,heap_used_bytes:r.heapUsedBytes,heap_total_bytes:r.heapTotalBytes,external_bytes:r.externalBytes,array_buffers_bytes:r.arrayBuffersBytes,peak_rss_bytes:r.peakRssBytes,cpu_user_micros:r.cpuUserMicros,cpu_system_micros:r.cpuSystemMicros,uptime_ms:r.uptimeMs,system_memory_total_bytes:r.systemMemoryTotalBytes,system_memory_free_bytes:r.systemMemoryFreeBytes,logical_cpu_count:r.logicalCpuCount}))copy(key,value)}else{Object.assign(properties,{storage_scope:r.scope,size_basis:r.sizeBasis});for(const[key,value]of Object.entries({database_bytes:r.databaseBytes,wal_bytes:r.walBytes,shm_bytes:r.shmBytes,total_bytes:r.totalBytes,physical_file_count:r.fileCount}))copy(key,value);for(const item of r.populations){copy(item.population,item.count);properties[item.population+"_coverage"]=item.coverage}}return properties}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const posthogSourceIds=new Set(
|
|
1
|
+
import{TELEMETRY_SOURCE_IDS}from"@zortexhq/plugin-telemetry/api";export const posthogSourceIds=new Set(TELEMETRY_SOURCE_IDS);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{startOwnedProcessResourceSampler}from"../resource-sampler.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as spawnChild}from"node:child_process";import{isAbsolute}from"node:path";import{fileURLToPath}from"node:url";import{setTimeout as delay}from"node:timers/promises";import{createWindowsJob}from"./windows-job.js";export const name="zortex-process-local";export const SENSITIVE_ENV=/KEY|PASSWORD|SECRET|TOKEN/i;export function childEnvironment(extra={}){const env={};for(const[key,value]of Object.entries(process.env)){if(value!==void 0&&!SENSITIVE_ENV.test(key)&&!/^DSH_/i.test(key)&&!/^NODE_CHANNEL_/i.test(key))env[key]=value}const find=key=>process.platform==="win32"?Object.keys(env).find(name2=>name2.toUpperCase()===key.toUpperCase()):key in env?key:void 0;for(const[key,value]of Object.entries(extra)){const existing=find(key);if(existing!==void 0)delete env[existing];if(value!==void 0)env[key]=value}return env}const runner=fileURLToPath(new URL("./runner.js",import.meta.url));const MAX_COLLECT=64*1024*1024;function posixGroupAlive(pgid){try{process.kill(-pgid,0);return true}catch(error){return error.code==="EPERM"}}function validMode(mode){if(mode==="ignore"||mode==="inherit")return true;const max=mode?.maxBytes;return typeof mode==="object"&&Number.isSafeInteger(max)&&max>0&&max<=MAX_COLLECT}class Tail{max;chunks=[];size=0;truncated=false;constructor(max){this.max=max}push(chunk){this.chunks.push(chunk);this.size+=chunk.length;while(this.size>this.max&&this.chunks.length){const extra=this.size-this.max,first=this.chunks[0];if(first.length<=extra){this.chunks.shift();this.size-=first.length}else{this.chunks[0]=first.subarray(extra);this.size-=extra}this.truncated=true}}read(){return{text:Buffer.concat(this.chunks).toString("utf8"),truncated:this.truncated}}}export function createProcesses(config={}){const disposeMs=config.disposeMs??1e4;if(!Number.isSafeInteger(disposeMs)||disposeMs<1||disposeMs>6e5)throw Error("Invalid disposeMs.");const live=new Set;let closed=false;function spawn(spec){if(closed)throw Error("Process service is closed.");if(!spec||!Array.isArray(spec.argv)||!spec.argv.length||spec.argv.some(part=>typeof part!=="string"||part.includes("\0")))throw Error("Invalid process argv.");if(!isAbsolute(spec.argv[0])&&/[\\/]/.test(spec.argv[0]))throw Error("Executable must be absolute or a bare PATH name.");if(typeof spec.cwd!=="string"||!isAbsolute(spec.cwd))throw Error("Process cwd must be absolute.");if(!spec.stdio||spec.stdio.stdin!=="ignore"||!validMode(spec.stdio.stdout)||!validMode(spec.stdio.stderr))throw Error("Invalid process stdio.");if(!Number.isSafeInteger(spec.graceMs)||spec.graceMs<0||spec.graceMs>6e5)throw Error("Invalid graceMs.");if(spec.signal?.aborted)throw Error("Process launch was aborted.");const windows=process.platform==="win32";
|
|
1
|
+
import{randomUUID}from"node:crypto";import{spawn as spawnChild}from"node:child_process";import{isAbsolute}from"node:path";import{fileURLToPath}from"node:url";import{setTimeout as delay}from"node:timers/promises";import{createWindowsJob}from"./windows-job.js";import{startOperationalStep}from"@zortexhq/plugin-telemetry/api";import{RESOURCE_PROCESS_ROLES}from"@zortexhq/plugin-telemetry/api/resources";import{startOwnedProcessResourceSampler}from"./resource-sampler.js";export const name="zortex-process-local";export const SENSITIVE_ENV=/KEY|PASSWORD|SECRET|TOKEN/i;export function childEnvironment(extra={}){const env={};for(const[key,value]of Object.entries(process.env)){if(value!==void 0&&!SENSITIVE_ENV.test(key)&&!/^DSH_/i.test(key)&&!/^NODE_CHANNEL_/i.test(key))env[key]=value}const find=key=>process.platform==="win32"?Object.keys(env).find(name2=>name2.toUpperCase()===key.toUpperCase()):key in env?key:void 0;for(const[key,value]of Object.entries(extra)){const existing=find(key);if(existing!==void 0)delete env[existing];if(value!==void 0)env[key]=value}return env}const runner=fileURLToPath(new URL("./runner.js",import.meta.url));const MAX_COLLECT=64*1024*1024;function posixGroupAlive(pgid){try{process.kill(-pgid,0);return true}catch(error){return error.code==="EPERM"}}function validMode(mode){if(mode==="ignore"||mode==="inherit")return true;const max=mode?.maxBytes;return typeof mode==="object"&&Number.isSafeInteger(max)&&max>0&&max<=MAX_COLLECT}class Tail{max;chunks=[];size=0;truncated=false;constructor(max){this.max=max}push(chunk){this.chunks.push(chunk);this.size+=chunk.length;while(this.size>this.max&&this.chunks.length){const extra=this.size-this.max,first=this.chunks[0];if(first.length<=extra){this.chunks.shift();this.size-=first.length}else{this.chunks[0]=first.subarray(extra);this.size-=extra}this.truncated=true}}read(){return{text:Buffer.concat(this.chunks).toString("utf8"),truncated:this.truncated}}}export function createProcesses(config={},metrics){const disposeMs=config.disposeMs??1e4;if(!Number.isSafeInteger(disposeMs)||disposeMs<1||disposeMs>6e5)throw Error("Invalid disposeMs.");const live=new Set;let closed=false;function spawn(spec){if(closed)throw Error("Process service is closed.");if(!spec||!Array.isArray(spec.argv)||!spec.argv.length||spec.argv.some(part=>typeof part!=="string"||part.includes("\0")))throw Error("Invalid process argv.");if(!isAbsolute(spec.argv[0])&&/[\\/]/.test(spec.argv[0]))throw Error("Executable must be absolute or a bare PATH name.");if(typeof spec.cwd!=="string"||!isAbsolute(spec.cwd))throw Error("Process cwd must be absolute.");if(!spec.stdio||spec.stdio.stdin!=="ignore"||!validMode(spec.stdio.stdout)||!validMode(spec.stdio.stderr))throw Error("Invalid process stdio.");if(!Number.isSafeInteger(spec.graceMs)||spec.graceMs<0||spec.graceMs>6e5)throw Error("Invalid graceMs.");if(spec.signal?.aborted)throw Error("Process launch was aborted.");let processRef;const execution=startOperationalStep(metrics,()=>{processRef=randomUUID();return{phase:"runtime",action:"execute",processRef}});const windows=process.platform==="win32";let job;try{job=windows?createWindowsJob():void 0}catch(error){execution.finish({state:"failed",errorCategory:"provider"});throw error}const pipeOf=mode=>typeof mode==="object"?"pipe":mode;const stdio=["ignore",pipeOf(spec.stdio.stdout),pipeOf(spec.stdio.stderr),"ipc"];let child;try{child=spawnChild(process.execPath,[runner,JSON.stringify({argv:spec.argv,cwd:spec.cwd})],{cwd:spec.cwd,env:childEnvironment(spec.env),stdio,detached:!windows,windowsHide:true,serialization:"json"})}catch(error){execution.finish({state:"failed",errorCategory:"provider"});job?.close();throw error}const tails={stdout:typeof spec.stdio.stdout==="object"?new Tail(spec.stdio.stdout.maxBytes):void 0,stderr:typeof spec.stdio.stderr==="object"?new Tail(spec.stdio.stderr.maxBytes):void 0};for(const stream of["stdout","stderr"]){const readable=child[stream],tail=tails[stream];readable?.on("error",()=>{});if(readable&&tail)readable.on("data",chunk=>tail.push(chunk))}const pid=child.pid;let reported;let launchError,quiescent=false,terminating=false,assigned=!job,killTimer;let cleanup;let resources;child.on("message",message=>{if(message==="ready"){if(job&&pid!==void 0){try{job.assign(pid);assigned=true}catch(error){launchError=error;child.kill();return}}if(terminating){if(job)job.terminate();else child.kill();return}if(child.connected)child.send("start",()=>{});return}if(message&&typeof message==="object"){const value=message;if(value.kind==="started"){if(!resources&&metrics&&Number.isSafeInteger(value.pid)&&value.pid>0&&pid!==void 0){try{const role=RESOURCE_PROCESS_ROLES.includes(spec.telemetryRole)?spec.telemetryRole:"worker";resources=execution.run(()=>startOwnedProcessResourceSampler({pid:value.pid,parentPid:pid,role,metrics,...processRef?{processRef}:{},isAlive:()=>reported===void 0&&!quiescent&&child.exitCode===null&&child.signalCode===null}))}catch{}}return}reported=value.error?"spawn-failed":{exitCode:value.exitCode??null,signal:value.signal??null}}});const failed=new Promise((_,reject)=>child.once("error",error=>{launchError??=error;reject(error)}));failed.catch(()=>{});const exited=new Promise(resolve=>child.once("exit",(code,signal)=>resolve({code,signal})));const channelClosed=new Promise(resolve=>{if(!child.connected)resolve();else child.once("disconnect",()=>resolve())});const done=(async()=>{const exit=await Promise.race([exited,failed]);await Promise.race([channelClosed,delay(1e3)]);if(launchError)throw launchError;if(reported==="spawn-failed")throw Error("Process could not be started.");return reported??{exitCode:exit.code,signal:exit.signal}})();void done.then(outcome=>{resources?.close();execution.finish({state:terminating?"cancelled":outcome.exitCode===0?"completed":"failed"})},()=>{resources?.close();execution.finish({state:terminating?"cancelled":"failed",errorCategory:"provider"})});function rangeAlive(){if(child.exitCode===null&&child.signalCode===null&&!launchError)return true;if(job)return job.activeProcesses()>0;return pid!==void 0&&posixGroupAlive(pid)}function finish(){if(quiescent)return;quiescent=true;resources?.close();if(killTimer)clearTimeout(killTimer);job?.close();child.stdout?.destroy();child.stderr?.destroy();if(child.connected)child.disconnect();spec.signal?.removeEventListener("abort",terminate);live.delete(handle);cleanup?.finish({state:"completed"})}function terminate(){if(quiescent)return;cleanup??=execution.run(()=>startOperationalStep(metrics,{phase:"runtime",action:"cleanup",...processRef?{processRef}:{}}));terminating=true;if(job){if(assigned)job.terminate();else child.kill();return}if(pid===void 0)return;try{process.kill(-pid,"SIGTERM")}catch{}killTimer??=setTimeout(()=>{try{process.kill(-pid,"SIGKILL")}catch{}},spec.graceMs);killTimer.unref()}const handle={pid,done,terminate,async waitForExit(signal){while(!quiescent){if(signal?.aborted){cleanup?.mark({state:"unknown",errorCategory:"timeout"});return false}let alive=true;try{alive=rangeAlive()}catch{alive=true}if(!alive){finish();break}await delay(25)}return true},output(stream){return tails[stream]?.read()??{text:"",truncated:false}}};spec.signal?.addEventListener("abort",terminate,{once:true});live.add(handle);return handle}return{spawn,active:()=>live.size,async close(){closed=true;const handles=[...live];for(const handle of handles)handle.terminate();const deadline=AbortSignal.timeout(disposeMs);await Promise.allSettled(handles.map(handle=>handle.waitForExit(deadline)))}}}export function apply(ctx,config={}){const service=createProcesses(config,()=>ctx.get("zortexTelemetry"));ctx.reflect.provide("zortexProcesses",service);ctx.effect(()=>()=>service.close(),`${name}: managed ranges`)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{open}from"node:fs/promises";import{spawn}from"node:child_process";import{randomUUID}from"node:crypto";import{isUsageResourceSnapshot}from"@zortexhq/plugin-telemetry/api/resources";const INTERVAL_MS=6e4,MEASUREMENT_DEADLINE_MS=250;const integer=value=>Number.isSafeInteger(value)&&Number(value)>=0;const validPid=value=>Number.isSafeInteger(value)&&value>0&&value<=2147483647;const validRef=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}$/i.test(value);export function parseOwnedLinuxProcess(stat,status,pid,parentPid){const end=stat.lastIndexOf(")"),prefix=stat.slice(0,stat.indexOf("(")).trim(),fields=stat.slice(end+1).trim().split(/\s+/);if(end<0||Number(prefix)!==pid||Number(fields[1])!==parentPid||!/^\d+$/.test(fields[19]??"")||fields[0]==="Z"||fields[0]==="X")return void 0;const rss=/^VmRSS:\s*(\d+)\s+kB\s*$/m.exec(status),peak=/^VmHWM:\s*(\d+)\s+kB\s*$/m.exec(status);if(!rss)return void 0;const rssBytes=Number(rss[1])*1024,peakRssBytes=peak?Number(peak[1])*1024:void 0;if(!integer(rssBytes)||peakRssBytes!==void 0&&!integer(peakRssBytes))return void 0;return{rssBytes,...peakRssBytes!==void 0?{peakRssBytes}:{},token:fields[19],rssBasis:"linux_proc_approximate"}}export function parseOwnedMacProcess(output,pid,parentPid){const rows=output.trim().split("\n");if(rows.length!==1)return void 0;const row=/^\s*(\d+)\s+(\d+)\s+((?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(\d+)\s*$/.exec(rows[0]);if(!row||Number(row[1])!==pid||Number(row[2])!==parentPid)return void 0;const rssBytes=Number(row[4])*1024;return integer(rssBytes)?{rssBytes,token:row[3],rssBasis:"macos_resident"}:void 0}let windowsApi;async function loadWindows(){const module=await import("koffi");return bindWindows(module.default)}function bindWindows(koffi){const kernel=koffi.load("kernel32.dll"),psapi=koffi.load("psapi.dll");const filetime=koffi.struct({low:"uint32_t",high:"uint32_t"});const counters=koffi.struct({cb:"uint32_t",PageFaultCount:"uint32_t",PeakWorkingSetSize:"uintptr_t",WorkingSetSize:"uintptr_t",QuotaPeakPagedPoolUsage:"uintptr_t",QuotaPagedPoolUsage:"uintptr_t",QuotaPeakNonPagedPoolUsage:"uintptr_t",QuotaNonPagedPoolUsage:"uintptr_t",PagefileUsage:"uintptr_t",PeakPagefileUsage:"uintptr_t",PrivateUsage:"uintptr_t"});return{koffi,counters,open:kernel.func("__stdcall","OpenProcess","void *",["uint32_t","int","uint32_t"]),close:kernel.func("__stdcall","CloseHandle","int",["void *"]),exit:kernel.func("__stdcall","GetExitCodeProcess","int",["void *",koffi.out(koffi.pointer("uint32_t"))]),times:kernel.func("__stdcall","GetProcessTimes","int",["void *",...Array.from({length:4},()=>koffi.out(koffi.pointer(filetime)))]),memory:psapi.func("__stdcall","GetProcessMemoryInfo","int",["void *",koffi.out(koffi.pointer(counters)),"uint32_t"])}}export function startOwnedProcessResourceSampler(options){let stopped=false,busy=false,processRef=validRef(options.processRef)?options.processRef:void 0,birth;let statHandle,statusHandle;let windowsHandle,win;const helpers=new Set;let timer;const close=()=>{if(stopped)return;stopped=true;if(timer)clearInterval(timer);for(const helper of helpers)try{helper.kill("SIGKILL")}catch{}if(statHandle)void statHandle.close().catch(()=>{});if(statusHandle)void statusHandle.close().catch(()=>{});if(windowsHandle&&win)try{win.close(windowsHandle)}catch{}windowsHandle=void 0};const alive=()=>{try{return!stopped&&(options.isAlive?.()??true)}catch{return false}};const enabled=()=>{try{if(!alive()){close();return void 0}const service=options.metrics();return service?.isEnabled?.()===true?service:void 0}catch{return void 0}};const readBounded=async handle=>{const bytes=Buffer.alloc(16384),read=await handle.read(bytes,0,bytes.length,0);return read.bytesRead===bytes.length?void 0:bytes.subarray(0,read.bytesRead).toString("utf8")};const linux=async()=>{if(!statHandle){const handle=await open(`/proc/${options.pid}/stat`,"r");if(!alive()){await handle.close();return void 0}statHandle=handle}if(!statusHandle){const handle=await open(`/proc/${options.pid}/status`,"r");if(!alive()){await handle.close();return void 0}statusHandle=handle}const before=await readBounded(statHandle),status=await readBounded(statusHandle),after=await readBounded(statHandle);if(before===void 0||status===void 0||after===void 0)return void 0;const first=parseOwnedLinuxProcess(before,status,options.pid,options.parentPid),last=parseOwnedLinuxProcess(after,status,options.pid,options.parentPid);return first&&last&&first.token===last.token?last:void 0};const mac=()=>new Promise(resolve=>{if(helpers.size){resolve(void 0);return}let helper;try{helper=spawn("/bin/ps",["-o","pid=,ppid=,lstart=,rss=","-p",String(options.pid)],{env:{PATH:"/usr/bin:/bin",LC_ALL:"C",LANG:"C"},stdio:["ignore","pipe","ignore"]})}catch{resolve(void 0);return}helpers.add(helper);let output="",settled=false;const finish=value=>{if(settled)return;settled=true;clearTimeout(deadline);resolve(value)};const deadline=setTimeout(()=>{helper.kill("SIGKILL");finish(void 0)},MEASUREMENT_DEADLINE_MS);helper.stdout?.on("data",data=>{output+=data.toString("utf8");if(Buffer.byteLength(output)>1024){helper.kill("SIGKILL");finish(void 0)}});helper.once("error",()=>finish(void 0));helper.once("close",code=>{helpers.delete(helper);finish(code===0?parseOwnedMacProcess(output,options.pid,options.parentPid):void 0)})});const windows=async()=>{win??=await(windowsApi??=loadWindows());if(!alive())return void 0;if(!windowsHandle)windowsHandle=win.open(4096,0,options.pid);if(!windowsHandle)return void 0;const exit=[0];if(!win.exit(windowsHandle,exit)||exit[0]!==259)return void 0;const creation={},ended={},kernel={},user={};if(!win.times(windowsHandle,creation,ended,kernel,user))return void 0;const memory={cb:win.koffi.sizeof(win.counters)};if(!win.memory(windowsHandle,memory,win.koffi.sizeof(win.counters)))return void 0;const ticks=value=>BigInt(value.high)*4294967296n+BigInt(value.low);const rssBytes=Number(memory.WorkingSetSize),peakRssBytes=Number(memory.PeakWorkingSetSize),cpuUserMicros=Number(ticks(user)/10n),cpuSystemMicros=Number(ticks(kernel)/10n);if(![rssBytes,peakRssBytes,cpuUserMicros,cpuSystemMicros].every(integer))return void 0;return{rssBytes,peakRssBytes,cpuUserMicros,cpuSystemMicros,token:ticks(creation).toString(),rssBasis:"windows_working_set"}};const sample=async()=>{if(!enabled()||!validPid(options.pid)||!validPid(options.parentPid)||busy)return;busy=true;const start=performance.now();let observed;try{observed=process.platform==="linux"?await linux():process.platform==="darwin"?await mac():process.platform==="win32"?await windows():void 0;if(observed){if(birth!==void 0&&observed.token!==birth)observed=void 0;else birth=observed.token}const service=enabled();if(!service)return;processRef??=randomUUID();const resource={schemaVersion:1,kind:"process",snapshotId:randomUUID(),processRef,role:options.role,asOf:new Date().toISOString(),sampleDurationMs:Math.min(6e4,Math.max(0,Math.round(performance.now()-start))),memoryScope:"owned_primary_process",childMemoryCoverage:"unavailable",coverage:observed?"partial":"unavailable",...observed?{rssBytes:observed.rssBytes,rssBasis:observed.rssBasis,...observed.peakRssBytes!==void 0?{peakRssBytes:observed.peakRssBytes}:{},...observed.cpuUserMicros!==void 0?{cpuUserMicros:observed.cpuUserMicros}:{},...observed.cpuSystemMicros!==void 0?{cpuSystemMicros:observed.cpuSystemMicros}:{}}:{}};if(isUsageResourceSnapshot(resource))try{void Promise.resolve(service.record({operation:"product.resources",outcome:observed?"ok":"unknown",durationMs:resource.sampleDurationMs,internal:true,resource})).catch(()=>{})}catch{}}catch{const service=enabled();if(service){processRef??=randomUUID();const resource={schemaVersion:1,kind:"process",snapshotId:randomUUID(),processRef,role:options.role,asOf:new Date().toISOString(),sampleDurationMs:Math.min(6e4,Math.max(0,Math.round(performance.now()-start))),memoryScope:"owned_primary_process",childMemoryCoverage:"unavailable",coverage:"unavailable"};if(isUsageResourceSnapshot(resource))try{void Promise.resolve(service.record({operation:"product.resources",outcome:"unknown",durationMs:resource.sampleDurationMs,internal:true,resource})).catch(()=>{})}catch{}}}finally{busy=false}};timer=setInterval(()=>{void sample()},INTERVAL_MS);timer.unref();void sample();return{sample,get processRef(){return processRef},close}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn}from"node:child_process";const spec=JSON.parse(process.argv[2]??"null");if(!spec||!Array.isArray(spec.argv)||!spec.argv.length||typeof spec.cwd!=="string"||typeof process.send!=="function")process.exit(70);const env={...process.env};delete env.NODE_CHANNEL_FD;delete env.NODE_CHANNEL_SERIALIZATION_MODE;let child,finished=false;process.on("SIGTERM",()=>{});process.on("SIGINT",()=>{});process.on("disconnect",()=>{if(finished)return;if(process.platform!=="win32")try{process.kill(-process.pid,"SIGKILL")}catch{}process.exit(1)});const report=(message,code)=>{finished=true;process.send(message,()=>{process.exitCode=code;process.disconnect()})};process.on("message",message=>{if(message!=="start"||child)return;try{child=spawn(spec.argv[0],spec.argv.slice(1),{cwd:spec.cwd,env,stdio:["ignore","inherit","inherit"],windowsHide:true})}catch{report({error:"spawn"},127);return}child.once("error",()=>{if(!finished)report({error:"spawn"},127)});child.once("exit",(exitCode,signal)=>{if(!finished)report({exitCode,signal},exitCode??1)})});process.send("ready");
|
|
1
|
+
import{spawn}from"node:child_process";const spec=JSON.parse(process.argv[2]??"null");if(!spec||!Array.isArray(spec.argv)||!spec.argv.length||typeof spec.cwd!=="string"||typeof process.send!=="function")process.exit(70);const env={...process.env};delete env.NODE_CHANNEL_FD;delete env.NODE_CHANNEL_SERIALIZATION_MODE;let child,finished=false;process.on("SIGTERM",()=>{});process.on("SIGINT",()=>{});process.on("disconnect",()=>{if(finished)return;if(process.platform!=="win32")try{process.kill(-process.pid,"SIGKILL")}catch{}process.exit(1)});const report=(message,code)=>{finished=true;process.send(message,()=>{process.exitCode=code;process.disconnect()})};process.on("message",message=>{if(message!=="start"||child)return;try{child=spawn(spec.argv[0],spec.argv.slice(1),{cwd:spec.cwd,env,stdio:["ignore","inherit","inherit"],windowsHide:true})}catch{report({error:"spawn"},127);return}child.once("spawn",()=>{if(!finished&&child?.pid!==void 0)process.send?.({kind:"started",pid:child.pid})});child.once("error",()=>{if(!finished)report({error:"spawn"},127)});child.once("exit",(exitCode,signal)=>{if(!finished)report({exitCode,signal},exitCode??1)})});process.send("ready");
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isUsageCollection}from"./measurement.js";import{isFlowId}from"./trace.js";import{RESOURCE_PROCESS_ROLES}from"./resources.js";const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const closed=(value,keys)=>Object.keys(value).every(key=>keys.includes(key));const count=value=>Number.isSafeInteger(value)&&Number(value)>=0;const iso=value=>typeof value==="string"&&value.length===24&&Number.isFinite(Date.parse(value))&&new Date(value).toISOString()===value;export function isUsageCaptureStats(value){const fields=["attempted","accepted","suppressed","rejected","failed","pending"];return object(value)&&closed(value,["producerRef","since","scope",...fields])&&isFlowId(value.producerRef)&&iso(value.since)&&value.scope==="record_and_observe_api_calls"&&fields.every(key=>count(value[key]))&&Number(value.attempted)===Number(value.accepted)+Number(value.suppressed)+Number(value.rejected)+Number(value.failed)+Number(value.pending)}export function isUsageResourceSamplerStats(value){const fields=["attempts","queued","rejected","disabled","overlapping","timeouts"];return object(value)&&closed(value,fields)&&fields.every(key=>count(value[key]))}export function isUsageCollectionStatus(value){if(!object(value)||!closed(value,["schemaVersion","snapshotId","asOf","role","coverage","capture","queue","sampler"])||value.schemaVersion!==1||!isFlowId(value.snapshotId)||!iso(value.asOf)||!RESOURCE_PROCESS_ROLES.includes(value.role)||!["complete","partial","unavailable"].includes(String(value.coverage)))return false;if(value.capture!==void 0&&!isUsageCaptureStats(value.capture)||value.queue!==void 0&&!isUsageCollection(value.queue)||value.sampler!==void 0&&!isUsageResourceSamplerStats(value.sampler))return false;if(value.queue!==void 0){const queue=value.queue;if(queue.oldestAvailableAt!==null&&!iso(queue.oldestAvailableAt)||queue.observations?.lastSuppressedAt!==void 0&&queue.observations.lastSuppressedAt!==null&&!iso(queue.observations.lastSuppressedAt))return false}const known=[value.capture,value.queue,value.sampler].filter(value2=>value2!==void 0).length;return value.coverage==="complete"?known===3:value.coverage==="unavailable"?known===0:known>0&&known<3}export function snapshotCollectionStatus(value){if(!object(value))return value;const copy={...value};for(const key of["capture","sampler","queue"])if(object(copy[key]))copy[key]={...copy[key]};if(object(copy.queue)&&object(copy.queue.observations))copy.queue.observations={...copy.queue.observations};return copy}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./telemetry.js";export*from"./trace.js";export*from"./measurement.js";export*from"./observations.js";
|
|
1
|
+
export*from"./telemetry.js";export*from"./trace.js";export*from"./measurement.js";export*from"./observations.js";export*from"./operational.js";export*from"./upstream-tools.js";export*from"./tool-methods.js";export*from"./tool-call.js";export*from"./source-ids.js";export*from"./resources.js";export*from"./collection.js";
|
|
@@ -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";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"]))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.executionLocation===void 0||typeof value.executionLocation==="string"&&["local","cloud","unknown"].includes(value.executionLocation))}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","result","correlation","errorCategory",...record?["id","at","context","feedback","invocation","observation"]:[]]))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.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.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","context","result","correlation","invocation"])if(object(copy[key]))copy[key]={...copy[key]};if(object(copy.observation))copy.observation=snapshotUsageObservation(copy.observation);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}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","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.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 +1 @@
|
|
|
1
|
-
import{AsyncLocalStorage}from"node:async_hooks";import{randomUUID}from"node:crypto";import{isFlowId}from"./trace.js";export const USAGE_ENTRYPOINTS=["mcp","local_cloud","cli","resident","unknown"];export const USAGE_TOOL_NAMES=["search","context","sql","actions","action","manage","instruction","handbook","read","update","unknown"];const invocationContext=new AsyncLocalStorage;export function isUsageInvocation(value){if(!plain(value)||!closed(value,["id","entrypoint","tool","owner"]))return false;return isFlowId(value.id)&&USAGE_ENTRYPOINTS.includes(value.entrypoint)&&USAGE_TOOL_NAMES.includes(value.tool)&&(value.owner==="gateway"||value.owner==="transport")}export function withUsageInvocation(input,run){const value=Object.freeze({...input,id:randomUUID()});if(!isUsageInvocation(value))throw Error("Invalid usage invocation context.");return invocationContext.run(value,run)}export const currentUsageInvocation=()=>invocationContext.getStore();export const OBSERVATION_SNAPSHOT_INTERVAL_MS=36e5,OBSERVATION_SNAPSHOT_DAILY_LIMIT=240;export const SYNC_STATUSES=["completed","partial","backoff","cancelled","failed","cleanup_blocked","not_admitted","unknown"];export const SYNC_EXECUTION_PHASES=["completed","failed","timed_out","cancelled","cleanup_blocked","not_admitted","unknown"];export const OBSERVATION_REASONS=["none","provider","storage","network","timeout","denied","identity","busy","missing_receipt","receipt_mismatch","cleanup","cancelled","backoff","unknown"];export const INVENTORY_POPULATIONS=["original_event_rows","cached_records","binding_records"];export const CONNECTION_PROVIDERS=["google","microsoft","slack","notion","github","linear","dropbox","box","atlassian","local","other"];export const CONNECTION_CAPABILITIES=["identity_read","mail_read","mail_write","calendar_read","calendar_write","contacts_read","contacts_write","files_read","files_write","chat_read","chat_write","tasks_read","tasks_write","notes_read","notes_write","workspace_read","workspace_write"];const plain=v=>!!v&&typeof v==="object"&&!Array.isArray(v);const closed=(v,keys)=>Object.keys(v).every(k=>keys.includes(k));const source=v=>typeof v==="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(v);const count=v=>Number.isSafeInteger(v)&&Number(v)>=0&&Number(v)<=1e8;const iso=v=>typeof v==="string"&&v.length===24&&Number.isFinite(Date.parse(v))&&new Date(Date.parse(v)).toISOString()===v;const enumValue=(v,values)=>typeof v==="string"&&values.includes(v);const optional=(v,valid)=>v===void 0||valid(v);const bool=v=>typeof v==="boolean";export function snapshotUsageObservation(value){if(!plain(value))return value;const copy={...value};if(Array.isArray(copy.capabilities))copy.capabilities=[...copy.capabilities];return copy}export function isUsageObservation(value){if(!plain(value)||typeof value.key!=="string"||!value.key.length||Buffer.byteLength(value.key)>512||!source(value.source)||!optional(value.at,iso)||!optional(value.connectionRef,isFlowId))return false;const base=["kind","key","source","at","connectionRef"];if(value.kind==="sync")return closed(value,[...base,"status","durationMs","execution","cleanupConfirmed","businessObserved","complete","ran","stopped","runFailed","delivered","appended","expected","coverageStreams","reason"])&&enumValue(value.status,SYNC_STATUSES)&&typeof value.durationMs==="number"&&Number.isFinite(value.durationMs)&&value.durationMs>=0&&value.durationMs<=864e5&&optional(value.execution,v=>enumValue(v,SYNC_EXECUTION_PHASES))&&["cleanupConfirmed","businessObserved","complete","ran","stopped","runFailed"].every(k=>optional(value[k],bool))&&["delivered","appended","expected","coverageStreams"].every(k=>optional(value[k],count))&&optional(value.reason,v=>enumValue(v,OBSERVATION_REASONS));if(value.kind==="inventory")return closed(value,[...base,"population","attribution","count","countKnown","countBasis","coverage"])&&enumValue(value.population,INVENTORY_POPULATIONS)&&enumValue(value.attribution,["source_unattributed","binding"])&&(value.attribution==="binding"?isFlowId(value.connectionRef):value.connectionRef===void 0)&&bool(value.countKnown)&&(value.countKnown?count(value.count):value.count===void 0)&&value.countBasis==="bounded_index"&&enumValue(value.coverage,["complete","lower_bound","unavailable"])&&(value.coverage==="unavailable"?!value.countKnown:true);if(value.kind==="connection")return closed(value,[...base,"provider","state","selected","grantState","capabilities","permissionBasis","permissionKnown"])&&isFlowId(value.connectionRef)&&enumValue(value.provider,CONNECTION_PROVIDERS)&&enumValue(value.state,["connected","disconnected","unknown"])&&bool(value.selected)&&enumValue(value.grantState,["active","revoked","mixed","unknown"])&&Array.isArray(value.capabilities)&&value.capabilities.length<=CONNECTION_CAPABILITIES.length&&new Set(value.capabilities).size===value.capabilities.length&&value.capabilities.every(v=>enumValue(v,CONNECTION_CAPABILITIES))&&enumValue(value.permissionBasis,["saved_grant","unknown"])&&bool(value.permissionKnown)&&(!value.permissionKnown||value.permissionBasis==="saved_grant");return false}export function isUsageObservationFacts(value){return plain(value)&&isUsageObservation({...value,key:"validation",source:"validation"})&&!Object.keys(value).some(key=>["key","source","at"].includes(key))}export function isUsageObservationStats(value){return plain(value)&&closed(value,["snapshotRateLimited","snapshotBudgetLimited","snapshotUnchanged","duplicates","lastSuppressedAt"])&&["snapshotRateLimited","snapshotBudgetLimited","snapshotUnchanged","duplicates"].every(k=>Number.isSafeInteger(value[k])&&Number(value[k])>=0)&&(value.lastSuppressedAt===null||iso(value.lastSuppressedAt))}
|
|
1
|
+
import{AsyncLocalStorage}from"node:async_hooks";import{randomUUID}from"node:crypto";import{isFlowId}from"./trace.js";export const USAGE_ENTRYPOINTS=["mcp","local_cloud","cli","resident","unknown"];export const USAGE_TOOL_NAMES=["search","context","sql","actions","action","manage","instruction","handbook","read","update","unknown"];export const USAGE_SESSION_SCOPES=["mcp_connection","mcp_request"];const invocationContext=new AsyncLocalStorage;export function isUsageInvocation(value){if(!plain(value)||!closed(value,["id","entrypoint","tool","owner","sessionId","sessionScope"]))return false;return isFlowId(value.id)&&USAGE_ENTRYPOINTS.includes(value.entrypoint)&&USAGE_TOOL_NAMES.includes(value.tool)&&(value.owner==="gateway"||value.owner==="transport")&&(value.sessionId===void 0&&value.sessionScope===void 0||isFlowId(value.sessionId)&&USAGE_SESSION_SCOPES.includes(value.sessionScope))}export function withUsageInvocation(input,run){const value=Object.freeze({...input,id:randomUUID()});if(!isUsageInvocation(value))throw Error("Invalid usage invocation context.");return invocationContext.run(value,run)}export const currentUsageInvocation=()=>invocationContext.getStore();export const OBSERVATION_SNAPSHOT_INTERVAL_MS=36e5,OBSERVATION_SNAPSHOT_DAILY_LIMIT=240;export const SYNC_STATUSES=["completed","partial","backoff","cancelled","failed","cleanup_blocked","not_admitted","unknown"];export const SYNC_EXECUTION_PHASES=["completed","failed","timed_out","cancelled","cleanup_blocked","not_admitted","unknown"];export const OBSERVATION_REASONS=["none","provider","storage","network","timeout","denied","identity","busy","missing_receipt","receipt_mismatch","cleanup","cancelled","backoff","unknown"];export const INVENTORY_POPULATIONS=["original_event_rows","cached_records","binding_records"];export const CONNECTION_PROVIDERS=["google","microsoft","slack","notion","github","linear","dropbox","box","atlassian","local","other"];export const CONNECTION_CAPABILITIES=["identity_read","mail_read","mail_write","calendar_read","calendar_write","contacts_read","contacts_write","files_read","files_write","chat_read","chat_write","tasks_read","tasks_write","notes_read","notes_write","workspace_read","workspace_write"];const plain=v=>!!v&&typeof v==="object"&&!Array.isArray(v);const closed=(v,keys)=>Object.keys(v).every(k=>keys.includes(k));const source=v=>typeof v==="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(v);const count=v=>Number.isSafeInteger(v)&&Number(v)>=0&&Number(v)<=1e8;const iso=v=>typeof v==="string"&&v.length===24&&Number.isFinite(Date.parse(v))&&new Date(Date.parse(v)).toISOString()===v;const enumValue=(v,values)=>typeof v==="string"&&values.includes(v);const optional=(v,valid)=>v===void 0||valid(v);const bool=v=>typeof v==="boolean";export function snapshotUsageObservation(value){if(!plain(value))return value;const copy={...value};if(Array.isArray(copy.capabilities))copy.capabilities=[...copy.capabilities];return copy}export function isUsageObservation(value){if(!plain(value)||typeof value.key!=="string"||!value.key.length||Buffer.byteLength(value.key)>512||!source(value.source)||!optional(value.at,iso)||!optional(value.connectionRef,isFlowId))return false;const base=["kind","key","source","at","connectionRef"];if(value.kind==="sync")return closed(value,[...base,"status","durationMs","execution","cleanupConfirmed","businessObserved","complete","ran","stopped","runFailed","delivered","appended","expected","coverageStreams","reason"])&&enumValue(value.status,SYNC_STATUSES)&&typeof value.durationMs==="number"&&Number.isFinite(value.durationMs)&&value.durationMs>=0&&value.durationMs<=864e5&&optional(value.execution,v=>enumValue(v,SYNC_EXECUTION_PHASES))&&["cleanupConfirmed","businessObserved","complete","ran","stopped","runFailed"].every(k=>optional(value[k],bool))&&["delivered","appended","expected","coverageStreams"].every(k=>optional(value[k],count))&&optional(value.reason,v=>enumValue(v,OBSERVATION_REASONS));if(value.kind==="inventory")return closed(value,[...base,"population","attribution","count","countKnown","countBasis","coverage"])&&enumValue(value.population,INVENTORY_POPULATIONS)&&enumValue(value.attribution,["source_unattributed","binding"])&&(value.attribution==="binding"?isFlowId(value.connectionRef):value.connectionRef===void 0)&&bool(value.countKnown)&&(value.countKnown?count(value.count):value.count===void 0)&&value.countBasis==="bounded_index"&&enumValue(value.coverage,["complete","lower_bound","unavailable"])&&(value.coverage==="unavailable"?!value.countKnown:true);if(value.kind==="connection")return closed(value,[...base,"provider","state","selected","grantState","capabilities","permissionBasis","permissionKnown"])&&isFlowId(value.connectionRef)&&enumValue(value.provider,CONNECTION_PROVIDERS)&&enumValue(value.state,["connected","disconnected","unknown"])&&bool(value.selected)&&enumValue(value.grantState,["active","revoked","mixed","unknown"])&&Array.isArray(value.capabilities)&&value.capabilities.length<=CONNECTION_CAPABILITIES.length&&new Set(value.capabilities).size===value.capabilities.length&&value.capabilities.every(v=>enumValue(v,CONNECTION_CAPABILITIES))&&enumValue(value.permissionBasis,["saved_grant","unknown"])&&bool(value.permissionKnown)&&(!value.permissionKnown||value.permissionBasis==="saved_grant");return false}export function isUsageObservationFacts(value){return plain(value)&&isUsageObservation({...value,key:"validation",source:"validation"})&&!Object.keys(value).some(key=>["key","source","at"].includes(key))}export function isUsageObservationStats(value){return plain(value)&&closed(value,["snapshotRateLimited","snapshotBudgetLimited","snapshotUnchanged","duplicates","lastSuppressedAt"])&&["snapshotRateLimited","snapshotBudgetLimited","snapshotUnchanged","duplicates"].every(k=>Number.isSafeInteger(value[k])&&Number(value[k])>=0)&&(value.lastSuppressedAt===null||iso(value.lastSuppressedAt))}
|
|
@@ -0,0 +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}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const RESOURCE_PROCESS_ROLES=["resident","cli","mcp","worker","connector_runtime","browser","model_worker","unknown"];export const RESOURCE_VAULT_POPULATIONS=["stored_event_rows","live_event_rows","system_event_rows","cached_records","binding_records","stored_blobs"];const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const closed=(value,keys)=>Object.keys(value).every(key=>keys.includes(key));const number=value=>Number.isSafeInteger(value)&&Number(value)>=0;const uuid=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}$/i.test(value);const date=value=>typeof value==="string"&&value.length===24&&Number.isFinite(Date.parse(value))&&new Date(value).toISOString()===value;const coverage=value=>["complete","partial","unavailable"].includes(String(value));const processFields=["rssBytes","heapUsedBytes","heapTotalBytes","externalBytes","arrayBuffersBytes","peakRssBytes","cpuUserMicros","cpuSystemMicros","uptimeMs","systemMemoryTotalBytes","systemMemoryFreeBytes","logicalCpuCount"];const vaultFields=["databaseBytes","walBytes","shmBytes","totalBytes","fileCount"];const vaultKeys=["schemaVersion","scope","asOf","coverage","sizeBasis","populations",...vaultFields];const baseKeys=["schemaVersion","snapshotId","asOf","sampleDurationMs","coverage","kind"];function validVault(value){if(value.schemaVersion!==1||value.scope!=="sqlite_files"||!date(value.asOf)||!coverage(value.coverage)||value.sizeBasis!=="logical_file_bytes"||!vaultFields.every(key=>value[key]===void 0||number(value[key]))||!Array.isArray(value.populations)||value.populations.length!==RESOURCE_VAULT_POPULATIONS.length)return false;const populations=value.populations;if(new Set(populations.map(row=>object(row)?row.population:void 0)).size!==RESOURCE_VAULT_POPULATIONS.length)return false;if(!populations.every(row=>object(row)&&closed(row,["population","count","coverage"])&&RESOURCE_VAULT_POPULATIONS.includes(row.population)&&["complete","lower_bound","unavailable"].includes(String(row.coverage))&&(row.coverage==="unavailable"?row.count===void 0:number(row.count))))return false;const physical=["databaseBytes","walBytes","shmBytes"].every(key=>number(value[key]));if(value.fileCount!==void 0&&(!physical||Number(value.fileCount)>3||Number(value.fileCount)<1))return false;if(value.totalBytes!==void 0&&(!physical||value.totalBytes!==Number(value.databaseBytes)+Number(value.walBytes)+Number(value.shmBytes)))return false;if(value.coverage==="complete"&&(!physical||value.totalBytes===void 0||value.fileCount===void 0||populations.some(row=>row.coverage!=="complete")))return false;if(value.coverage==="unavailable"&&(vaultFields.some(key=>value[key]!==void 0)||populations.some(row=>row.coverage!=="unavailable")))return false;if(value.coverage==="partial"&&!vaultFields.some(key=>value[key]!==void 0)&&!populations.some(row=>row.coverage!=="unavailable"))return false;return true}export function isResourceVaultMetadata(value){return object(value)&&closed(value,vaultKeys)&&validVault(value)}export function isUsageResourceSnapshot(value){if(!object(value)||value.schemaVersion!==1||!uuid(value.snapshotId)||!date(value.asOf)||!number(value.sampleDurationMs)||Number(value.sampleDurationMs)>6e4||!coverage(value.coverage))return false;if(value.kind==="vault")return closed(value,[...baseKeys,...vaultKeys])&&validVault(value);if(value.kind!=="process"||!closed(value,[...baseKeys,"processRef","role","memoryScope","childMemoryCoverage","rssBasis",...processFields])||!uuid(value.processRef)||!RESOURCE_PROCESS_ROLES.includes(value.role)||!["process_shared","owned_primary_process"].includes(String(value.memoryScope))||value.childMemoryCoverage!=="unavailable"||value.rssBasis!==void 0&&!["node_process","linux_proc_approximate","macos_resident","windows_working_set"].includes(String(value.rssBasis))||!processFields.every(key=>value[key]===void 0||number(value[key])))return false;if(value.logicalCpuCount!==void 0&&(Number(value.logicalCpuCount)<1||Number(value.logicalCpuCount)>65536))return false;if(value.heapUsedBytes!==void 0&&value.heapTotalBytes!==void 0&&Number(value.heapUsedBytes)>Number(value.heapTotalBytes))return false;if(value.systemMemoryTotalBytes!==void 0&&value.systemMemoryFreeBytes!==void 0&&Number(value.systemMemoryFreeBytes)>Number(value.systemMemoryTotalBytes))return false;return value.coverage==="complete"?processFields.every(key=>value[key]!==void 0):value.coverage==="unavailable"?processFields.every(key=>value[key]===void 0):processFields.some(key=>value[key]!==void 0)}export function snapshotResourceMetadata(value){if(!object(value))return value;const copy={...value};if(Array.isArray(copy.populations))copy.populations=copy.populations.map(row=>object(row)?{...row}:row);return copy}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const TELEMETRY_SOURCE_IDS=Object.freeze(["activitywatch","adobe-acrobat","adobe-camera-raw","adobe-illustrator","adobe-media-encoder","adobe-photoshop","adobe-premiere-pro","airtable","ansys-electronics-desktop","apple-music","apple-notes","apple-reminders","appstore","arxiv","asana","autocad","basecamp","box","browser-use","calcom","calendly","canva","chatgpt","chembl","chrome-history","clickup","cloudflare","coda","computer-files","confluence","copyq","crates-io","crossref","cua","datacite","dingtalk","discord","docker-desktop","dropbox","ecb","eclipse","energy-charts","epic-games-launcher","europe-pmc","eurostat","facebook","fastmail","figma","freshdesk","freshrss","front","gbif","ghost","github","gitlab","gmail","google-calendar","google-chat","google-chrome","google-contacts","google-drive","google-tasks","harvest","hearthstone-deck-tracker","hubspot","imessage","immich","instagram","intercom","jetbrains","jianying","jira","joplin","jupyter","karakeep","lark","lattics","libreoffice","linear","linkedin","local-audio","local-git","logseq","mac-apt","macos-contacts","matlab","matrix","mattermost","microsoft-edge","microsoft-excel","microsoft-planner","microsoft-teams","microsoft-todo","microsoft-word","minecraft-java","miniflux","miro","modelsim","modrinth","monday","multisim","neso","netease-mail","netease-mail-web","nextcloud","ni-tdms","notebooklm","notion","notion-l1","obsidian","ollama","onedrive","onenote","open-meteo","openai","openrouter","outlook","owntracks","packet-tracer","pipedrive","plecs","posthog","powerpoint","proton-mail","pscad","pypi","qt-designer","quartus","railway","raindrop","readwise","reddit","rednote","ryujinx","salesforce","sentry","sharepoint","shopify","simulink","slack","slack-web","smartsheet","solidworks","spotify","steam","steam-community","stm32cubemx","stripe","supabase","teams","telegram","thunderbird","ti-ccs","ticktick","tiktok","todoist","toggl","trello","usgs-earthquakes","visio","visual-studio","vscode-local-history","wakatime","wallabag","webflow","wechat","whatsapp","whatsapp-export","whatsapp-web","windows-event-viewer","windows-task-scheduler","wordpress","world-bank","wrike","wsl","x","youtube","zendesk","zenodo","zoom","zotero","zulip"]);const acceptedSources=new Set(TELEMETRY_SOURCE_IDS);export const isTelemetrySourceId=value=>typeof value==="string"&&acceptedSources.has(value);
|
|
@@ -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","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"){const state="state"in value?value.state:"status"in value&&value.status&&typeof value.status==="object"&&"state"in value.status?value.status.state:void 0;if(state==="failed"||state==="FAILED")return"fault";if(state==="cancelled")return"cancelled";if(state==="needs-user"||state==="needs_you"||state==="AUTH_BLOCKED")return"auth-blocked";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"){const state="state"in value?value.state:"status"in value&&value.status&&typeof value.status==="object"&&"state"in value.status?value.status.state:void 0;if(state==="failed"||state==="FAILED")return"fault";if(state==="cancelled")return"cancelled";if(state==="needs-user"||state==="needs_you"||state==="AUTH_BLOCKED")return"auth-blocked";if("returned"in value&&value.returned===0||"items"in value&&Array.isArray(value.items)&&!value.items.length)return"empty"}return"ok"}
|
|
@@ -0,0 +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()}
|
|
@@ -0,0 +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"];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const OPERATIONAL_UPSTREAM_TOOLS=["bring_to_front","browser_click","browser_dialog","browser_download","browser_motion_policy","browser_navigate","browser_pointer","browser_prepare","browser_select","browser_set_input_files","browser_type","check_for_update","check_permissions","click","clipboard_read","clipboard_write","double_click","drag","end_session","get_accessibility_tree","get_agent_cursor_state","get_browser_state","get_config","get_cursor_position","get_desktop_state","get_guide","get_recording_state","get_screen_size","get_session","get_window_state","health_report","hotkey","install_extension","install_ffmpeg","invoke_menu","kill_app","launch_app","list_apps","list_sessions","list_windows","move_cursor","page","parse_visual_regions","press_key","replay_trajectory","right_click","run_script","run_steps","scroll","set_agent_cursor_enabled","set_agent_cursor_motion","set_agent_cursor_theme","set_config","set_value","set_window_frame","start_recording","start_session","stop_recording","type_text","verify_state","zoom","mouse_button_down","mouse_button_up","mouse_drag","parallel_mouse_drag","debug_window_info","chatgpt_status","chatgpt_open_login","chatgpt_finish_login","chatgpt_close_browser","get_me","list_project_members","describe","execute","notion-get-self","execute_sentry_tool","whoami","unknown"];export const OPERATIONAL_RPC_METHODS=["tools/call","tools/list"];
|