@withgauge/cli 0.25.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +83 -59
- package/dist/batchWorker.js +1 -1
- package/dist/{chatApi-KHPW7ED5.js → chatApi-CLMRDLLS.js} +1 -1
- package/dist/chunk-3I3IT3LG.js +1 -0
- package/dist/chunk-MAANSWGU.js +2 -0
- package/dist/{chunk-EVT234WT.js → chunk-NXOOFF5A.js} +1 -1
- package/dist/{chunk-KRHTXL5O.js → chunk-QWDJLPRW.js} +1 -1
- package/dist/index.js +116 -74
- package/dist/{orgDirectory-V3RCKGLA.js → orgDirectory-QX23FAS2.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-DEX43SUK.js +0 -1
- package/dist/chunk-XHPA33OA.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createdOrganization,credentialKind,fetchDirectory,findOrganization,isUuid,keyOrganization,legacySelection,missingAgentsOrg,productsLabel,resolveOrgValue,resolveSelection}from"./chunk-
|
|
1
|
+
import{createdOrganization,credentialKind,fetchDirectory,findOrganization,isUuid,keyOrganization,legacySelection,missingAgentsOrg,productsLabel,resolveOrgValue,resolveSelection}from"./chunk-3I3IT3LG.js";import"./chunk-MAANSWGU.js";import"./chunk-OIGVDK3F.js";import"./chunk-PSBF4TEK.js";export{createdOrganization,credentialKind,fetchDirectory,findOrganization,isUuid,keyOrganization,legacySelection,missingAgentsOrg,productsLabel,resolveOrgValue,resolveSelection};
|
package/package.json
CHANGED
package/dist/chunk-DEX43SUK.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{CliError,createClient,resolveToken}from"./chunk-XHPA33OA.js";var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var isUuid=value=>UUID_RE.test(value);function credentialKind(token=resolveToken()){if(!token)return"none";if(token.startsWith("gauge_cli_"))return"session";if(token.startsWith("gauge_sk_")||!token.startsWith("gauge_"))return"api_key";return"legacy"}async function fetchDirectory(){if(credentialKind()==="legacy")throw new CliError("usage","This Agents token cannot list or select organizations in this version of the CLI.",{hint:"If GAUGE_API_TOKEN is set, unset it first. Then run `gauge auth login` and `gauge orgs`."});const{chatPath,createChatApiClient}=await import("./chatApi-KHPW7ED5.js");const{data}=await createChatApiClient().get(chatPath("orgs"));if(!Array.isArray(data))throw new CliError("internal","Gauge returned an organization list the CLI could not read.",{hint:"Try `gauge orgs` again. If this continues, contact Gauge support."});return data}async function findOrganization(value){const org=(await fetchDirectory()).find(org2=>org2.id===value||org2.slug===value);if(!org)throw new CliError("not_found",`You don't have access to an organization named "${value}".`,{hint:"Run `gauge orgs` to see your organizations, then use a value from the slug column."});return org}async function resolveOrgValue(value){return isUuid(value)?{id:value}:findOrganization(value)}function legacySelection(source){const message=source==="config"?"Your saved organization needs to be selected again after this CLI update.":source==="project"?"This project's organization needs to be selected again after this CLI update.":"The organization in this run file needs to be selected again after this CLI update.";const hint=source==="config"?"Run `gauge orgs` to see your organizations, then `gauge orgs use <slug>` to choose one. If you have only one organization, `gauge auth login` updates your saved choice automatically.":source==="project"?"Run `gauge orgs`, then `gauge orgs use <slug> --project` to update gauge.json.":"Run `gauge orgs`, then rerun your command with --org <slug>. Or remove org from the run file to use your saved organization.";throw new CliError("usage",message,{hint})}async function resolveSelection(value,source){if(source!=="flag"&&!isUuid(value))legacySelection(source);return resolveOrgValue(value)}async function keyOrganization(){const{createChatApiClient}=await import("./chatApi-KHPW7ED5.js");const org=(await createChatApiClient().me()).apiKey?.organization;if(!org)throw new CliError("internal","Gauge could not identify which organization this API key belongs to.",{hint:"Check the key in Settings \u2192 API Keys and try again."});return org}async function createdOrganization(agentsSlug){const{orgs}=await createClient().get("/api/v1/me");const id=orgs.find(org=>org.slug===agentsSlug)?.canonicalGaugeOrganizationId;if(!id)throw new CliError("internal","Your workspace was created, but it is not ready to select in the CLI yet.",{hint:"Run `gauge orgs` to check for it, then `gauge orgs use <slug>`. If it is missing, contact Gauge support; you don't need to create it again."});return findOrganization(id)}async function missingAgentsOrg(org){const match=(await fetchDirectory()).find(o=>o.id===org);if(match?.products?.agents!==false)return void 0;return new CliError("not_found",`${match.name} doesn't use Gauge Agents.`,{hint:"Run `gauge orgs` to see which products each organization uses."})}function productsLabel(products){if(!products)return"unknown";return[products.chat?"Chat":void 0,products.agents?"Agents":void 0].filter(Boolean).join(", ")||"-"}export{isUuid,credentialKind,fetchDirectory,findOrganization,resolveOrgValue,legacySelection,resolveSelection,keyOrganization,createdOrganization,missingAgentsOrg,productsLabel};
|
package/dist/chunk-XHPA33OA.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{USER_AGENT,configDir,readConfig}from"./chunk-OIGVDK3F.js";import{__export}from"./chunk-PSBF4TEK.js";import{chmodSync,mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"fs";import{randomUUID}from"crypto";import{join}from"path";import{setTimeout as sleep}from"timers/promises";function credentialsPath(){return join(configDir(),"credentials")}function readCredentials(){try{const raw=readFileSync(credentialsPath(),"utf8").trim();if(!raw.startsWith("{"))return raw||null;const value=JSON.parse(raw);if(value.version!==1||typeof value.accessToken!=="string"||typeof value.authUrl!=="string"||typeof value.apiUrl!=="string")return null;return value}catch{return null}}function resolveToken(){const fromEnv=process.env.GAUGE_API_TOKEN?.trim();if(fromEnv)return fromEnv;const stored=readCredentials();return typeof stored==="string"?stored:stored?.accessToken??null}function atomicWrite(value){mkdirSync(configDir(),{recursive:true,mode:448});const temporary=`${credentialsPath()}.${randomUUID()}.tmp`;try{writeFileSync(temporary,`${value}
|
|
2
|
-
`,{encoding:"utf8",mode:384,flag:"wx"});chmodSync(temporary,384);renameSync(temporary,credentialsPath())}finally{rmSync(temporary,{force:true})}}function saveToken(token){atomicWrite(token.trim())}function saveCredentials(credentials){atomicWrite(JSON.stringify(credentials))}function clearToken(){rmSync(credentialsPath(),{force:true})}async function withCredentialLock(fn){mkdirSync(configDir(),{recursive:true,mode:448});const path=`${credentialsPath()}.lock`;const deadline=Date.now()+35e3;while(true){try{writeFileSync(path,String(process.pid),{flag:"wx",mode:384});break}catch(error){if(error.code!=="EEXIST")throw error;if(Date.now()>=deadline)throw new Error(`Timed out waiting for credential access. If no Gauge process is running, remove ${path} and retry.`);await sleep(50)}}try{return await fn()}finally{rmSync(path,{force:true})}}import{z}from"zod";var DEFAULT_AUTH_URL="https://app.withgauge.com";function resolveAuthUrl(){return(process.env.GAUGE_AUTH_URL||readConfig().authUrl||DEFAULT_AUTH_URL).replace(/\/+$/,"")}var sharedTokenSchema=z.object({accessToken:z.string().startsWith("gauge_cli_"),refreshToken:z.string().startsWith("gauge_refresh_"),tokenType:z.literal("bearer"),expiresAt:z.iso.datetime({offset:true}),refreshExpiresAt:z.iso.datetime({offset:true})});function storedSharedCredentials(){if(process.env.GAUGE_API_TOKEN?.trim())return null;const stored=readCredentials();return stored&&typeof stored!=="string"?stored:null}function assertTrustedOrigin(baseUrl,credentials){const origin=new URL(baseUrl).origin;if(![credentials.authUrl,credentials.apiUrl].some(value=>new URL(value).origin===origin))throw new Error("Your saved login is for a different Gauge server. Check GAUGE_AUTH_URL and GAUGE_API_URL, then run `gauge auth login` for the server you want to use.")}var RefreshError=class extends Error{constructor(message,unauthorized=false){super(message);this.unauthorized=unauthorized}unauthorized};function uncertainRefresh(){return new RefreshError("Gauge could not renew your login. Run `gauge auth login` to sign in again.",true)}async function refreshCredentials(previous,force=false){return withCredentialLock(async()=>{const current=readCredentials();if(!current||typeof current==="string")throw new Error("Your saved login changed. Run the command again.");if(current.sessionId!==previous.sessionId||current.authUrl!==previous.authUrl||current.apiUrl!==previous.apiUrl)throw new Error("Login changed while this command was running. Retry the command.");if(current.refreshPending)throw uncertainRefresh();if(current.accessToken!==previous.accessToken)return current;if(!current.refreshToken)return current;if(!force&&Date.parse(current.expiresAt??"")>Date.now()+6e4)return current;saveCredentials({...current,refreshPending:true});let response;try{response=await fetch(`${current.authUrl}/api/cli/refresh`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(15e3),headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({refreshToken:current.refreshToken})})}catch{throw uncertainRefresh()}if(response.status===429){saveCredentials(current);throw new RefreshError("Gauge is receiving too many sign-in requests. Wait a moment, then try again.")}if(!response.ok)throw response.status===401?new RefreshError("Your login is no longer valid. Run `gauge auth login` to sign in again.",true):uncertainRefresh();try{const tokens=sharedTokenSchema.parse(await response.json());const next={...current,...tokens};delete next.refreshPending;const latest=readCredentials();if(!latest||typeof latest==="string"||latest.refreshToken!==current.refreshToken)throw new Error("Your saved login changed while Gauge was renewing it. Run the command again.");saveCredentials(next);return next}catch{throw uncertainRefresh()}})}var batteries_exports={};__export(batteries_exports,{BATTERY_AGENTS:()=>BATTERY_AGENTS,BATTERY_CADENCES:()=>BATTERY_CADENCES,BATTERY_MAX_LIMITS:()=>BATTERY_MAX_LIMITS,MAX_SAMPLES_PER_CYCLE:()=>MAX_SAMPLES_PER_CYCLE,batchDetailSchema:()=>batchDetailSchema,batchListQuerySchema:()=>batchListQuerySchema,batchListResponseSchema:()=>batchListResponseSchema,batchRunStatusSchema:()=>batchRunStatusSchema,batchRunSummarySchema:()=>batchRunSummarySchema,batchSummarySchema:()=>batchSummarySchema,batteryAgentSchema:()=>batteryAgentSchema,batteryApplyResponseSchema:()=>batteryApplyResponseSchema,batteryDefaultsSchema:()=>batteryDefaultsSchema,batteryLimitsSchema:()=>batteryLimitsSchema,batteryPlanPromptSchema:()=>batteryPlanPromptSchema,batteryPlanScheduleSchema:()=>batteryPlanScheduleSchema,batteryPlanSchema:()=>batteryPlanSchema,batteryPromptSpecSchema:()=>batteryPromptSpecSchema,batteryScheduleSpecSchema:()=>batteryScheduleSpecSchema,batterySkillRefSchema:()=>batterySkillRefSchema,batterySkillsSchema:()=>batterySkillsSchema,batterySpecSchema:()=>batterySpecSchema});import{z as z3}from"zod";import{z as z2}from"zod";var ERROR_CODES=["unauthorized","forbidden","not_found","invalid_request","insufficient_credits","needs_provider_key","rate_limited","conflict","internal","upgrade_required"];var errorCodeSchema=z2.enum(ERROR_CODES);var upgradeOfferSchema=z2.object({skuId:z2.string(),tierLabel:z2.string(),monthlyAmountCents:z2.number().int(),monthlyCredits:z2.number().int(),billingUrl:z2.string()});var errorEnvelopeSchema=z2.object({error:z2.object({code:errorCodeSchema,message:z2.string(),upgrade:upgradeOfferSchema.optional()})});var listQuerySchema=z2.object({limit:z2.coerce.number().int().min(1).max(200).default(50),cursor:z2.string().optional()});function listResponseSchema(item){return z2.object({items:z2.array(item),nextCursor:z2.string().optional()})}var createdBySchema=z2.object({userId:z2.string().nullable(),email:z2.string().nullable(),name:z2.string().nullable()}).nullable().optional();var BATTERY_AGENTS=["CLAUDE_CODE","CODEX_CLI","CURSOR","PI","OPENCODE","ANTIGRAVITY"];var BATTERY_CADENCES=["NONE"];var batteryAgentSchema=z3.enum(BATTERY_AGENTS);var BATTERY_MAX_LIMITS={maxTurns:30,wallClockS:5400,maxUsd:10};var MAX_SAMPLES_PER_CYCLE=50;var batteryLimitsSchema=z3.object({maxTurns:z3.number().positive().max(BATTERY_MAX_LIMITS.maxTurns).optional(),wallClockS:z3.number().positive().max(BATTERY_MAX_LIMITS.wallClockS).optional(),maxUsd:z3.number().positive().max(BATTERY_MAX_LIMITS.maxUsd).optional()});var batterySkillRefSchema=z3.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*@\S+$/,'skills entries must be "name@label" (a bare name is a search, not a reference)');var batterySkillsSchema=z3.array(batterySkillRefSchema);var batteryScheduleSpecSchema=z3.object({repoUrl:z3.string().nullish(),repoRef:z3.string().nullish(),model:z3.string().nullable().optional(),agents:z3.array(batteryAgentSchema).optional(),samplesPerCycle:z3.number().int().min(1).max(MAX_SAMPLES_PER_CYCLE).optional(),cadence:z3.enum(BATTERY_CADENCES).optional(),experiment:z3.string().optional(),limits:batteryLimitsSchema.optional(),skills:batterySkillsSchema.optional()});var batteryDefaultsSchema=z3.object({isBranded:z3.boolean().optional(),topic:z3.string().optional(),tags:z3.array(z3.string()).optional(),model:z3.string().nullable().optional(),agents:z3.array(batteryAgentSchema).optional(),samplesPerCycle:z3.number().int().min(1).max(MAX_SAMPLES_PER_CYCLE).optional(),cadence:z3.enum(BATTERY_CADENCES).optional(),limits:batteryLimitsSchema.optional(),skills:batterySkillsSchema.optional()});var batteryPromptSpecSchema=z3.object({key:z3.string().min(1),text:z3.string().min(1),isBranded:z3.boolean().optional(),topic:z3.string().optional(),tags:z3.array(z3.string()).optional(),experiment:z3.string().optional(),schedules:z3.array(batteryScheduleSpecSchema).optional()});var batterySpecSchema=z3.object({version:z3.literal(1),org:z3.string().optional(),experiment:z3.string().optional(),expand:z3.boolean().optional(),defaults:batteryDefaultsSchema.optional(),prompts:z3.array(batteryPromptSpecSchema).min(1)});var batteryPlanScheduleSchema=z3.object({action:z3.enum(["create","update","none"]),repoUrl:z3.string().nullable(),repoRef:z3.string().nullable(),runs:z3.number().int()});var batteryPlanPromptSchema=z3.object({key:z3.string(),action:z3.enum(["create","update"]),schedules:z3.array(batteryPlanScheduleSchema)});var batteryPlanSchema=z3.object({dryRun:z3.literal(true),org:z3.string(),experiment:z3.string().nullable(),expand:z3.boolean(),prompts:z3.array(batteryPlanPromptSchema),summary:z3.object({promptsToCreate:z3.number().int(),promptsToUpdate:z3.number().int(),schedulesToCreate:z3.number().int(),schedulesToUpdate:z3.number().int(),runsToEnqueue:z3.number().int(),runsByAgent:z3.record(z3.string(),z3.number().int()),estimatedCredits:z3.number().int()})});var batteryApplyResponseSchema=z3.object({batchIds:z3.array(z3.string()),runIds:z3.array(z3.string()),experiment:z3.string().nullable(),blocked:z3.enum(["insufficient_credits","needs_provider_key"]).optional()});var batchRunStatusSchema=z3.enum(["QUEUED","CLAIMED","PROVISIONING","RUNNING","SUCCEEDED","FAILED","TIMED_OUT","CANCELED"]);var batchListQuerySchema=listQuerySchema.extend({promptId:z3.string().optional(),experiment:z3.string().optional()});var batchSummarySchema=z3.object({id:z3.string(),promptId:z3.string(),promptText:z3.string(),experiment:z3.string().nullable(),createdAt:z3.string(),runCounts:z3.record(z3.string(),z3.number().int())});var batchListResponseSchema=listResponseSchema(batchSummarySchema);var batchRunSummarySchema=z3.object({id:z3.string(),agent:z3.string(),model:z3.string(),status:batchRunStatusSchema,createdAt:z3.string(),startedAt:z3.string().nullable(),finishedAt:z3.string().nullable()});var batchDetailSchema=z3.object({id:z3.string(),promptId:z3.string(),promptText:z3.string(),scenario:z3.string(),repoUrl:z3.string().nullable(),repoRef:z3.string().nullable(),experiment:z3.string().nullable(),funding:z3.string(),createdAt:z3.string(),runCounts:z3.record(z3.string(),z3.number().int()),runs:z3.array(batchRunSummarySchema)});var brands_exports={};__export(brands_exports,{BRAND_KINDS:()=>BRAND_KINDS,BRAND_PACKAGE_ECOSYSTEMS:()=>BRAND_PACKAGE_ECOSYSTEMS,brandKindSchema:()=>brandKindSchema,brandListResponseSchema:()=>brandListResponseSchema,brandPackageEcosystemSchema:()=>brandPackageEcosystemSchema,brandPackageInputSchema:()=>brandPackageInputSchema,brandPackageSchema:()=>brandPackageSchema,brandSchema:()=>brandSchema,createBrandBodySchema:()=>createBrandBodySchema,listBrandsQuerySchema:()=>listBrandsQuerySchema,updateBrandBodySchema:()=>updateBrandBodySchema});import{z as z4}from"zod";var BRAND_KINDS=["OWNED","COMPETITOR","OTHER"];var brandKindSchema=z4.enum(BRAND_KINDS);var BRAND_PACKAGE_ECOSYSTEMS=["npm","pypi","cargo","go","rubygems","other"];var brandPackageEcosystemSchema=z4.enum(BRAND_PACKAGE_ECOSYSTEMS);var brandPackageSchema=z4.object({name:z4.string(),ecosystem:z4.string().nullable()});var brandSchema=z4.object({id:z4.string(),name:z4.string(),kind:brandKindSchema,source:z4.string(),aliases:z4.array(z4.string()),websites:z4.array(z4.string()),category:z4.string().nullable(),packages:z4.array(brandPackageSchema),createdAt:z4.string(),updatedAt:z4.string()});var brandPackageInputSchema=z4.object({name:z4.string().min(1),ecosystem:brandPackageEcosystemSchema.nullable().optional()});var createBrandBodySchema=z4.object({name:z4.string().min(1),kind:brandKindSchema,aliases:z4.array(z4.string().min(1)).default([]),websites:z4.array(z4.string().min(1)).default([]),packages:z4.array(brandPackageInputSchema).default([])});var updateBrandBodySchema=z4.object({name:z4.string().min(1).optional(),kind:brandKindSchema.optional(),aliases:z4.array(z4.string().min(1)).optional(),websites:z4.array(z4.string().min(1)).optional(),packages:z4.array(brandPackageInputSchema).optional()});var listBrandsQuerySchema=listQuerySchema.extend({kind:brandKindSchema.optional()});var brandListResponseSchema=listResponseSchema(brandSchema);var feedback_exports={};__export(feedback_exports,{FEEDBACK_KINDS:()=>FEEDBACK_KINDS,createFeedbackBodySchema:()=>createFeedbackBodySchema,createFeedbackResponseSchema:()=>createFeedbackResponseSchema,feedbackKindSchema:()=>feedbackKindSchema});import{z as z5}from"zod";var FEEDBACK_KINDS=["friction","missing","bug","other"];var feedbackKindSchema=z5.enum(FEEDBACK_KINDS);var createFeedbackBodySchema=z5.object({message:z5.string().trim().min(1).max(4e3),kind:feedbackKindSchema.default("other"),command:z5.string().trim().max(500).optional(),org:z5.string().optional()});var createFeedbackResponseSchema=z5.object({id:z5.string()});var keys_exports={};__export(keys_exports,{PROVIDER_TYPES:()=>PROVIDER_TYPES,providerKeyListResponseSchema:()=>providerKeyListResponseSchema,providerKeySchema:()=>providerKeySchema,providerTypeSchema:()=>providerTypeSchema,setProviderKeyBodySchema:()=>setProviderKeyBodySchema,setProviderKeyResponseSchema:()=>setProviderKeyResponseSchema});import{z as z6}from"zod";var PROVIDER_TYPES=["anthropic","openai"];var providerTypeSchema=z6.enum(PROVIDER_TYPES);var setProviderKeyBodySchema=z6.object({key:z6.string().min(1)});var setProviderKeyResponseSchema=z6.object({providerType:providerTypeSchema,last4:z6.string()});var providerKeySchema=z6.object({providerType:providerTypeSchema,last4:z6.string(),createdAt:z6.string(),updatedAt:z6.string()});var providerKeyListResponseSchema=listResponseSchema(providerKeySchema);var runConfig_exports={};__export(runConfig_exports,{ROSTERABLE_AGENTS:()=>ROSTERABLE_AGENTS,SCHEDULABLE_AGENTS:()=>SCHEDULABLE_AGENTS,agentConfigInputSchema:()=>agentConfigInputSchema,agentConfigSchema:()=>agentConfigSchema,assetRefListSchema:()=>assetRefListSchema,assetRefSchema:()=>assetRefSchema,modelUnits:()=>modelUnits,refAssetName:()=>refAssetName,rosterableAgentSchema:()=>rosterableAgentSchema,runsPerCycle:()=>runsPerCycle,schedulableAgentSchema:()=>schedulableAgentSchema,totalRunsPerCycle:()=>totalRunsPerCycle});import{z as z9}from"zod";import{z as z8}from"zod";var INTERVENTION_KINDS=["BASELINE","ADD_SKILL","REMOVE_SKILL","EDIT_SKILL","REWRITE_DOCS","PACKAGE_VERSION","PACKAGE_CONTENT","CLI_VERSION","CLI_INTERVENTION"];import{z as z7}from"zod";var ANALYSIS_SCHEMA_VERSION=1;var evidenceSequenceSchema=z7.number().int().nonnegative().describe("The event's recorded seq in this session attempt. Never infer it from an array index, line number, or turn.");var evidenceRefSchema=z7.discriminatedUnion("kind",[z7.object({kind:z7.literal("trace"),seq:evidenceSequenceSchema}).strict(),z7.object({kind:z7.literal("diff"),path:z7.string().min(1)}).strict()]);var INSTALL_PHASES=["NONE","ATTEMPTED","CONFIGURED","EXERCISED"];var sessionProductSchema=z7.object({name:z7.string(),mentioned:z7.boolean(),considered:z7.boolean(),recommended:z7.boolean(),chosen:z7.boolean(),rejected:z7.boolean(),abandoned:z7.boolean(),installPhase:z7.enum(INSTALL_PHASES),rank:z7.number().int().nullable(),source:z7.enum(["BRIEF","PERSONA","PRIOR","SEARCH","PAGE","REPO","UNKNOWN"]),reason:z7.string(),categories:z7.array(z7.string()),evidence:z7.record(z7.string(),z7.array(evidenceRefSchema))});var sessionObservationSchema=z7.object({id:z7.string(),kind:z7.enum(["FRICTION","OBJECTION","OPPORTUNITY"]),label:z7.string(),detail:z7.string(),subject:z7.string(),basis:z7.enum(["OBSERVED","AGENT_CLAIM","INFERRED"]),effect:z7.enum(["BLOCKED","RECOVERED","EXTRA_WORK","SELECTION_LOSS","UNKNOWN"]),cause:z7.enum(["PRODUCT","CONTENT","ACCESS","ENVIRONMENT","AGENT","UNKNOWN"]),tags:z7.array(z7.string()),evidence:z7.array(evidenceRefSchema)});var sessionAnalysisSchema=z7.object({schemaVersion:z7.literal(ANALYSIS_SCHEMA_VERSION),instructionsVersion:z7.string().min(1),id:z7.string(),runId:z7.string(),attempt:z7.number().int(),createdAt:z7.string(),origin:z7.enum(["MODEL","LEGACY"]),model:z7.string().nullable(),assessability:z7.enum(["ASSESSED","PARTIAL","UNASSESSABLE"]),limitation:z7.string().nullable(),selection:z7.enum(["MEASURED","UNASSESSABLE","NOT_MEASURED"]),directed:z7.boolean(),products:z7.array(sessionProductSchema),observations:z7.array(sessionObservationSchema)});var artifactPathSchema=z7.string().min(1).refine(value=>!value.startsWith("/")&&!value.includes("\\")&&!value.split("/").some(part=>part===".."||part===""),"Evidence paths must be relative paths inside the session artifacts");var portableEvidenceRefSchema=z7.discriminatedUnion("kind",[z7.object({kind:z7.literal("trace"),seq:evidenceSequenceSchema}).strict(),z7.object({kind:z7.literal("diff"),path:artifactPathSchema}).strict(),z7.object({kind:z7.literal("artifact"),artifact:artifactPathSchema.describe("Path relative to the session attempt directory, for example session/events.ndjson."),attempt:z7.number().int().positive().optional().describe("Must match the analysis attempt; defaults to that attempt."),line:z7.number().int().positive().optional().describe("One-based line number in the original artifact, before any filtering."),endLine:z7.number().int().positive().optional().describe("Inclusive last line of the evidence range."),seq:evidenceSequenceSchema.optional()}).strict().superRefine((ref,ctx)=>{if(ref.line===void 0&&ref.seq===void 0)ctx.addIssue({code:"custom",message:"Artifact evidence needs a line or seq"});if(ref.endLine!==void 0&&(ref.line===void 0||ref.endLine<ref.line))ctx.addIssue({code:"custom",path:["endLine"],message:"endLine requires line and must be at least line"})})]);var findingSubmissionSchema=sessionObservationSchema.omit({id:true}).extend({label:z7.string().trim().min(1).max(200),detail:z7.string().trim().min(1).max(1e4),subject:z7.string().trim().min(1).max(200),tags:z7.array(z7.string().trim().min(1).max(64)).max(32).default([]),evidence:z7.array(portableEvidenceRefSchema).min(1).max(100)}).strict();var criterionAnalysisSubmissionSchema=z7.object({criterionId:z7.string().min(1),outcome:z7.enum(["PASS","FAIL","UNASSESSABLE"]),label:z7.string().trim().min(1).max(1e4),evidence:z7.array(portableEvidenceRefSchema).max(100).default([])}).strict().superRefine((result,ctx)=>{if(result.outcome!=="UNASSESSABLE"&&result.evidence.length===0)ctx.addIssue({code:"custom",path:["evidence"],message:"A criterion verdict needs evidence"})});var productSubmissionSchema=sessionProductSchema.extend({name:z7.string().trim().min(1).max(200),evidence:z7.record(z7.string(),z7.array(portableEvidenceRefSchema))}).strict().superRefine((product,ctx)=>{if((product.chosen||product.rejected||product.recommended)&&!product.considered)ctx.addIssue({code:"custom",path:["considered"],message:"A chosen, rejected, or recommended product was considered"});if(product.considered&&!product.mentioned)ctx.addIssue({code:"custom",path:["mentioned"],message:"A considered product was mentioned"});if(!Object.values(product.evidence).some(refs=>refs.length>0))ctx.addIssue({code:"custom",path:["evidence"],message:"A product judgment needs evidence"})});var analysisSubmissionSchema=z7.object({schemaVersion:z7.literal(ANALYSIS_SCHEMA_VERSION),attempt:z7.number().int().positive().default(1),instructionsVersion:z7.string().trim().min(1),analyst:z7.object({name:z7.string().trim().min(1),model:z7.string().trim().min(1).optional()}).strict(),assessability:sessionAnalysisSchema.shape.assessability,limitation:z7.string().trim().min(1).nullable().default(null),selection:sessionAnalysisSchema.shape.selection.default("NOT_MEASURED"),directed:z7.boolean().default(false),findings:z7.array(findingSubmissionSchema).max(1e3).default([]),products:z7.array(productSubmissionSchema).max(1e3).default([]),criteria:z7.array(criterionAnalysisSubmissionSchema).max(1e3).default([])}).strict().superRefine((analysis,ctx)=>{for(const field of["products","criteria"]){const keys=field==="products"?analysis.products.map(product=>product.name.toLowerCase()):analysis.criteria.map(criterion=>criterion.criterionId);if(new Set(keys).size!==keys.length)ctx.addIssue({code:"custom",path:[field],message:`Duplicate ${field} are not allowed`})}if(analysis.assessability!=="ASSESSED"&&analysis.limitation===null)ctx.addIssue({code:"custom",path:["limitation"],message:"Partial or unassessable analysis needs a limitation"})});var RUN_STATUSES=["QUEUED","CLAIMED","PROVISIONING","RUNNING","SUCCEEDED","FAILED","TIMED_OUT","CANCELED"];var runStatusSchema=z8.enum(RUN_STATUSES);var AGENTS=["CLAUDE_CODE","CODEX_CLI","CURSOR","PI","OPENCODE","ANTIGRAVITY"];var agentSchema=z8.enum(AGENTS);var OBSERVED_PROVIDER_SOURCES=["AGENT_STREAM","GATEWAY_RESPONSE","GATEWAY_AUDIT","CANARY"];var observedProviderSourceSchema=z8.enum(OBSERVED_PROVIDER_SOURCES);var selectedProviderSchema=z8.object({slug:z8.string(),displayName:z8.string()});var observedProviderSchema=z8.object({slug:z8.string(),source:observedProviderSourceSchema});var RUN_TRIGGER_SOURCES=["UNKNOWN","UI","API","CADENCE","STAFF","OPERATOR","GITHUB"];var runTriggerSourceSchema=z8.enum(RUN_TRIGGER_SOURCES);var runTriggeredBySchema=z8.object({source:runTriggerSourceSchema,userId:z8.string().nullable(),email:z8.string().nullable()});var runOptimizationTrialSchema=z8.object({optimizationId:z8.string(),trialId:z8.string(),key:z8.string(),title:z8.string(),kind:z8.enum(INTERVENTION_KINDS)});var runCreditsChargedSchema=z8.number().int().nullable();var runStatusFilterSchema=z8.string().transform(raw=>raw.split(",").map(s=>s.trim().toUpperCase()).filter(Boolean)).pipe(z8.array(runStatusSchema).min(1));var runListQuerySchema=listQuerySchema.extend({status:runStatusFilterSchema.optional(),batch:z8.string().optional(),prompt:z8.string().optional(),experiment:z8.string().optional(),evalSet:z8.string().optional(),since:z8.string().optional()});var runListItemSchema=z8.object({id:z8.string(),status:runStatusSchema,agent:agentSchema,model:z8.string(),resolvedModel:z8.string().nullable().optional(),modelDisplayName:z8.string().nullable().optional(),selectedProvider:selectedProviderSchema.nullable().optional(),observedProvider:observedProviderSchema.nullable().optional(),promptId:z8.string(),promptSnippet:z8.string(),batchId:z8.string(),experiment:z8.string().nullable(),evalSetId:z8.string().nullable(),evalRevision:z8.string().optional(),optimizationTrial:runOptimizationTrialSchema.nullable().optional(),turns:z8.number().int().nullable(),usdCost:z8.number().nullable(),creditsCharged:runCreditsChargedSchema.optional(),triggeredBy:runTriggeredBySchema.optional(),durationMs:z8.number().int().nullable(),exitReason:z8.string().nullable(),createdAt:z8.string(),startedAt:z8.string().nullable(),finishedAt:z8.string().nullable(),parentRunId:z8.string().nullable(),fetchForkPlanId:z8.string().nullable()});var runListResponseSchema=listResponseSchema(runListItemSchema);var runSkillSchema=z8.discriminatedUnion("source",[z8.object({source:z8.literal("saved"),skillId:z8.string(),name:z8.string(),label:z8.string()}),z8.object({source:z8.literal("input"),name:z8.string(),commit:z8.string().nullable(),pullNumber:z8.number().int().nullable()})]);var runDetailSchema=runListItemSchema.omit({promptSnippet:true}).extend({promptText:z8.string(),attempt:z8.number().int(),cancelRequested:z8.boolean(),failureReason:z8.string().nullable(),repoUrl:z8.string().nullable(),repoRef:z8.string().nullable(),scenario:z8.string(),funding:z8.string(),usage:z8.unknown().nullable(),hasDiff:z8.boolean(),claimedAt:z8.string().nullable(),criterionResults:z8.array(z8.object({criterionId:z8.string().nullable(),name:z8.string(),passed:z8.boolean().nullable(),reasoning:z8.string().nullable()})),skills:z8.array(runSkillSchema).optional()});var cancelRunResponseSchema=z8.object({id:z8.string(),status:runStatusSchema,cancelRequested:z8.boolean(),note:z8.string().optional()});var regradeRunResponseSchema=z8.object({runId:z8.string(),evalSetId:z8.string().nullable(),criteria:z8.number().int()});var RUN_INSIGHT_STATUSES=["PENDING","RUNNING","COMPLETE","FAILED","SKIPPED"];var runInsightStatusSchema=z8.enum(RUN_INSIGHT_STATUSES);var insightPassSchema=z8.object({status:runInsightStatusSchema,model:z8.string().nullable(),inputTokens:z8.number().int().nullable(),outputTokens:z8.number().int().nullable(),usdCost:z8.number().nullable(),error:z8.string().nullable()});var runDecisionSchema=z8.object({index:z8.number().int(),category:z8.string(),categoryRaw:z8.string().nullable(),chosenName:z8.string(),chosenEcosystem:z8.string().nullable(),chosenPackage:z8.string().nullable(),reversed:z8.boolean(),detail:z8.unknown()});var RUN_INSIGHT_PASS_KINDS=["ANALYSIS","CLI_DISCOVERY","LEVER","EXPERIMENT_DELTA"];var runInsightPassKindSchema=z8.enum(RUN_INSIGHT_PASS_KINDS);var insightPipelinePassSchema=insightPassSchema.extend({kind:runInsightPassKindSchema});var runInsightResponseSchema=z8.object({runId:z8.string(),decision:insightPassSchema,passes:z8.array(insightPipelinePassSchema),decisions:z8.array(runDecisionSchema),experimentDelta:z8.unknown().nullable(),visibilityVerdict:z8.unknown().nullable(),analysis:sessionAnalysisSchema.nullable()});var runEventSchema=z8.looseObject({run_id:z8.string(),seq:z8.number(),turn:z8.number(),ts:z8.string(),type:z8.string()});var runCompareSideSchema=z8.object({runRequest:z8.string().min(1).optional(),batch:z8.array(z8.string().min(1)).min(1).max(100).optional(),evalSet:z8.string().min(1).optional(),evalRevision:z8.string().min(1).optional(),trial:z8.string().min(1).optional(),experiment:z8.string().min(1).optional(),agent:z8.array(agentSchema).min(1).optional(),model:z8.array(z8.string()).min(1).optional(),since:z8.string().optional(),until:z8.string().optional()}).strict().refine(side=>side.runRequest!==void 0||side.batch!==void 0||side.evalSet!==void 0||side.experiment!==void 0||side.trial!==void 0,"Select runs with runRequest, batch, evalSet, experiment, or trial");var runCompareBodySchema=z8.object({baseline:runCompareSideSchema,candidate:runCompareSideSchema}).strict();var runCompareStatsSchema=z8.object({runs:z8.number().int(),finished:z8.number().int(),succeeded:z8.number().int(),judged:z8.number().int(),passed:z8.number().int(),passRate:z8.number().nullable(),medianTurns:z8.number().nullable(),medianUsdCost:z8.number().nullable(),medianDurationMs:z8.number().nullable(),criteria:z8.array(z8.object({name:z8.string(),judged:z8.number().int(),passed:z8.number().int(),passRate:z8.number().nullable()}))});var runCompareDeltaSchema=z8.object({passRate:z8.number().nullable(),medianTurns:z8.number().nullable(),medianUsdCost:z8.number().nullable(),medianDurationMs:z8.number().nullable(),criteria:z8.array(z8.object({name:z8.string(),passRate:z8.number().nullable()}))});var runCompareRowSchema=z8.object({baseline:runCompareStatsSchema,candidate:runCompareStatsSchema,delta:runCompareDeltaSchema});var runCompareMixedRevisionSchema=z8.object({evalSetId:z8.string().nullable(),promptId:z8.string().nullable(),revisions:z8.array(z8.string())});var runCompareTrialSchema=runOptimizationTrialSchema.extend({runs:z8.number().int()});var runCompareResponseSchema=z8.object({overall:runCompareRowSchema,targets:z8.array(runCompareRowSchema.extend({agent:agentSchema,model:z8.string()})),sides:z8.object({baseline:z8.object({evalRevisions:z8.array(z8.string()),mixedRevisions:z8.array(runCompareMixedRevisionSchema).optional(),truncated:z8.boolean(),trials:z8.array(runCompareTrialSchema).optional()}),candidate:z8.object({evalRevisions:z8.array(z8.string()),mixedRevisions:z8.array(runCompareMixedRevisionSchema).optional(),truncated:z8.boolean(),trials:z8.array(runCompareTrialSchema).optional()})})});var SCHEDULABLE_AGENTS=["CLAUDE_CODE","CODEX_CLI","PI","OPENCODE"];var schedulableAgentSchema=z9.enum(SCHEDULABLE_AGENTS);var ROSTERABLE_AGENTS=[...SCHEDULABLE_AGENTS,"ANTIGRAVITY"];var rosterableAgentSchema=z9.enum(ROSTERABLE_AGENTS);var agentConfigSchema=z9.object({agent:agentSchema,models:z9.array(z9.string().min(1))});var agentConfigInputSchema=z9.object({agent:rosterableAgentSchema,models:z9.array(z9.string().min(1)).default([])});var assetRefSchema=z9.string().max(320).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*@[^\s,]+$/,'asset references must be "name@label"');function refAssetName(ref){const at=ref.indexOf("@");return at<0?ref:ref.slice(0,at)}var assetRefListSchema=z9.array(assetRefSchema).superRefine((refs,ctx)=>{const names=new Set;for(const ref of refs){const name=refAssetName(ref);if(names.has(name)){ctx.addIssue({code:"custom",message:`"${ref}" names an asset already referenced \u2014 one version per asset`})}names.add(name)}});function modelUnits(agents){return agents.reduce((n,a)=>n+Math.max(1,a.models.length),0)}function runsPerCycle(owner,samplesPerCycle){return modelUnits(owner.agents)*samplesPerCycle}function totalRunsPerCycle(owners,samplesPerCycle){return owners.reduce((n,o)=>n+runsPerCycle(o,samplesPerCycle),0)}var DEFAULT_API_URL="https://agents.withgauge.com";function exitCodeFor(code){switch(code){case"usage":case"invalid_request":return 2;case"insufficient_credits":case"needs_provider_key":return 3;default:return 1}}var CliError=class extends Error{code;exitCode;hint;docs;needsAccount;apiCode;details;constructor(code,message,options={}){super(message);this.name="CliError";this.code=code;this.exitCode=exitCodeFor(code);this.hint=options.hint;this.docs=options.docs;this.needsAccount=options.needsAccount??false;this.apiCode=options.apiCode;this.details=options.details}};function resolveBaseUrl(){return process.env.GAUGE_API_URL||readConfig().apiUrl||DEFAULT_API_URL}var ApiClient=class{baseUrl;token;shared;authOptional;constructor(options={}){this.baseUrl=(options.baseUrl??resolveBaseUrl()).replace(/\/+$/,"");this.token=options.token!==void 0?options.token:resolveToken();this.authOptional=options.authOptional??false;this.shared=options.token===void 0?storedSharedCredentials():null;if(this.shared)assertTrustedOrigin(this.baseUrl,this.shared)}get signedIn(){return this.token!==null}async get(path,query){return this.request("GET",path,{query})}async post(path,body,query){return this.request("POST",path,{body,query})}async patch(path,body,query){return this.request("PATCH",path,{body,query})}async put(path,body,query){return this.request("PUT",path,{body,query})}async delete(path,query,body){return this.request("DELETE",path,{body,query})}async sse(path,onEvent,options={}){const res=await this.authenticatedFetch(this.url(path,options.query),{method:"GET",headers:this.headers({Accept:"text/event-stream"}),signal:options.signal});if(!res.ok)throw await this.toError(res);if(!res.body){throw new CliError("internal","Event stream had no response body")}const reader=res.body.getReader();const decoder=new TextDecoder;let buffer="";try{while(true){const{done,value}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:true});let boundary=buffer.indexOf("\n\n");while(boundary!==-1){const raw=buffer.slice(0,boundary);const event=parseSseFrame(raw);buffer=buffer.slice(boundary+2);if(event)onEvent(event);else if(raw.trimStart().startsWith(":"))options.onComment?.();boundary=buffer.indexOf("\n\n")}}}catch(error){if(error instanceof Error&&error.name==="AbortError")return;throw new CliError("network",`Event stream failed: ${messageOf(error)}`)}}url(path,query){const url=new URL(`${this.baseUrl}${path}`);for(const[key,value]of Object.entries(query??{})){if(Array.isArray(value))for(const item of value)url.searchParams.append(key,item);else if(value!==void 0)url.searchParams.set(key,String(value))}return url}headers(extra){if(!this.token&&!this.authOptional){throw new CliError("unauthorized","Not logged in. Run `gauge auth login` or set GAUGE_API_TOKEN.",{needsAccount:true})}return{...this.token?{Authorization:`Bearer ${this.token}`}:{},"User-Agent":USER_AGENT,Accept:"application/json",...extra}}async authenticatedFetch(url,init){let renewalFailed=false;if(this.shared?.refreshToken){try{const next=await refreshCredentials(this.shared);assertTrustedOrigin(this.baseUrl,next);this.shared=next;this.token=this.shared.accessToken}catch(error){if(error instanceof RefreshError&&error.unauthorized)throw new CliError("unauthorized",messageOf(error));if(!(error instanceof RefreshError)||!(Date.parse(this.shared.expiresAt??"")>Date.now()))throw new CliError("network",messageOf(error));renewalFailed=true}}const send=()=>this.fetch(url,{...init,redirect:"error",headers:{...init.headers,...this.token?{Authorization:`Bearer ${this.token}`}:{}}});const response=await send();if(response.status!==401||!this.shared?.refreshToken||renewalFailed)return response;await response.body?.cancel();try{const next=await refreshCredentials(this.shared,true);assertTrustedOrigin(this.baseUrl,next);this.shared=next;this.token=this.shared.accessToken}catch(error){throw new CliError(error instanceof RefreshError&&error.unauthorized?"unauthorized":"network",messageOf(error))}return send()}async fetch(url,init){try{return await fetch(url,init)}catch(error){if(error instanceof Error&&error.name==="AbortError")throw error;throw new CliError("network",`Request to ${url.host} failed: ${messageOf(error)}`)}}async request(method,path,options={}){const headers=this.headers(options.body===void 0?void 0:{"Content-Type":"application/json"});const res=await this.authenticatedFetch(this.url(path,options.query),{method,headers,body:options.body===void 0?void 0:JSON.stringify(options.body)});if(!res.ok)throw await this.toError(res);if(res.status===204)return void 0;const text=await res.text();if(!text)return void 0;const contentType=res.headers.get("content-type")??"";if(contentType.includes("application/json")){return JSON.parse(text)}return text}async toError(res){const wait=res.status===429?retryAfterSeconds(res):void 0;const hint=wait===void 0?void 0:`Try again in ${wait} s.`;try{const parsed=errorEnvelopeSchema.safeParse(await res.clone().json());if(parsed.success){const{code,message}=parsed.data.error;if(code==="not_found"&&message.startsWith("Organization not found")){const explained=await explainMissingOrg(res.url);if(explained)return explained}return new CliError(code,message,{hint})}}catch{}const what=res.status===429?"Rate limited by the Gauge API":res.status>=500?"Gauge API server error":"API request failed";return new CliError(codeForStatus(res.status),`${what}: HTTP ${res.status} ${res.statusText}`.trim(),{hint})}};async function explainMissingOrg(url){const match=url&&/\/api\/v1\/orgs\/([^/?#]+)/.exec(new URL(url).pathname);if(!match)return void 0;try{const{missingAgentsOrg}=await import("./orgDirectory-V3RCKGLA.js");return await missingAgentsOrg(decodeURIComponent(match[1]))}catch{return void 0}}function createClient(options){return new ApiClient(options)}function retryAfterSeconds(res){const value=res.headers.get("retry-after");if(!value)return void 0;const seconds=Number(value);const at=Date.parse(value);if(Number.isFinite(seconds))return Math.max(0,Math.ceil(seconds));if(Number.isNaN(at))return void 0;return Math.max(0,Math.ceil((at-Date.now())/1e3))}function codeForStatus(status){switch(status){case 400:return"invalid_request";case 401:return"unauthorized";case 402:return"insufficient_credits";case 403:return"forbidden";case 404:return"not_found";case 409:return"conflict";case 429:return"rate_limited";default:return"internal"}}function parseSseFrame(frame){let eventName;const dataLines=[];for(const line of frame.split("\n")){if(line.startsWith(":"))continue;if(line.startsWith("event:")){eventName=line.slice("event:".length).trim()}else if(line.startsWith("data:")){dataLines.push(line.slice("data:".length).replace(/^ /,""))}}if(dataLines.length===0)return null;return{event:eventName,data:dataLines.join("\n")}}function messageOf(error){if(error instanceof Error){const cause=error.cause instanceof Error?`: ${error.cause.message}`:"";return`${error.message}${cause}`}return String(error)}export{errorEnvelopeSchema,listResponseSchema,createdBySchema,batteries_exports,brands_exports,feedback_exports,keys_exports,ANALYSIS_SCHEMA_VERSION,analysisSubmissionSchema,agentSchema,runTriggeredBySchema,runCreditsChargedSchema,runEventSchema,agentConfigSchema,agentConfigInputSchema,assetRefListSchema,runConfig_exports,credentialsPath,readCredentials,resolveToken,saveToken,saveCredentials,clearToken,withCredentialLock,resolveAuthUrl,sharedTokenSchema,storedSharedCredentials,exitCodeFor,CliError,resolveBaseUrl,ApiClient,createClient,retryAfterSeconds,codeForStatus};
|