@withgauge/cli 0.27.0 → 0.29.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 +7 -0
- package/dist/batchWorker.js +1 -1
- package/dist/{chatApi-HF2R3SVR.js → chatApi-G5BMHJOC.js} +1 -1
- package/dist/{chunk-TAFB66SK.js → chunk-4SZPSHNF.js} +1 -1
- package/dist/{chunk-Y4Y2AKDY.js → chunk-MKC7K5NV.js} +1 -1
- package/dist/{chunk-PMX3NOGH.js → chunk-QJ2UAX2V.js} +1 -1
- package/dist/{chunk-PVTU7NGL.js → chunk-VHV7YMN5.js} +1 -1
- package/dist/{chunk-AZKXHO6C.js → chunk-ZXRPUGCO.js} +1 -1
- package/dist/{chunk-PUNARKS2.js → chunk-ZZK6V3ZF.js} +1 -1
- package/dist/index.js +104 -50
- package/dist/{orgDirectory-QCOOVF65.js → orgDirectory-52KLEIVN.js} +1 -1
- package/dist/watchServer.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -754,6 +754,13 @@ gauge eval edit <evalId> --hosted --clear-lifecycle # remove both and params
|
|
|
754
754
|
Clearing the last script also removes its parameter object. Each new run freezes
|
|
755
755
|
the uploaded configuration; editing it does not change existing sessions.
|
|
756
756
|
|
|
757
|
+
For CLI stubs and redirects, use `gauge run --hosted --cli-rules rules.json`
|
|
758
|
+
with a prompt, saved eval/preference, or case files/spec. Rules apply only to
|
|
759
|
+
that launch; they require no optimization or previous session. They leave
|
|
760
|
+
saved settings and the fixture repository unchanged. Local runs and legacy
|
|
761
|
+
battery specs are unsupported. Read `gauge instructions cli-rules --hosted`
|
|
762
|
+
for a complete v4 stub example, discovery guidance, and matching limits.
|
|
763
|
+
|
|
757
764
|
For a one-off prompt, attach scripts directly without creating a saved eval or
|
|
758
765
|
preference prompt:
|
|
759
766
|
|
package/dist/batchWorker.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{runLocal}from"./chunk-
|
|
1
|
+
import{runLocal}from"./chunk-4SZPSHNF.js";import"./chunk-ZZK6V3ZF.js";import"./chunk-QV7MOO3M.js";import"./chunk-QJ2UAX2V.js";import"./chunk-OIGVDK3F.js";import"./chunk-PSBF4TEK.js";import{randomBytes}from"crypto";import{readFile,rename,rm,writeFile}from"fs/promises";import{dirname,join}from"path";var requestPath=process.argv[2];var directory=dirname(requestPath);var requestLoaded=false;try{const request=JSON.parse(await readFile(requestPath,"utf8"));if(!request||typeof request.batchId!=="string"||typeof request.gaugeDir!=="string"||!request.definition)throw new Error("Invalid batch request");requestLoaded=true;await rm(requestPath);await runLocal(request.definition,[],request.gaugeDir,()=>{},{batchId:request.batchId,credentialSelections:request.credentialSelections,measurement:request.measurement})}catch(error){process.exitCode=1;const detail=requestLoaded?String(error):"Could not read a valid background batch request. Start a new batch.";console.error(detail);const statusPath=join(directory,"status.json");const previous=await readFile(statusPath,"utf8").then(raw=>JSON.parse(raw)).catch(()=>({}));const finishedSessions=previous.finishedSessions??0;const status={...previous,state:"failed",detail,finishedSessions,queuedSessions:0,skippedSessions:Math.max(0,(previous.expectedSessions??0)-finishedSessions),supervisorPid:process.pid};const temporary=`${statusPath}.${randomBytes(6).toString("hex")}.tmp`;await writeFile(temporary,`${JSON.stringify(status,null,2)}
|
|
2
2
|
`,{mode:384});await rename(temporary,statusPath);await writeFile(join(directory,"error.txt"),detail,{mode:384})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CHAT_API_PREFIX,CHAT_BATCH_SIZE,ChatApiClient,DEFAULT_MAX_ITEMS,addPageOptions,categoryScope,chatPath,chatScope,chunks,createChatApiClient,csv,describeScopes,fetchAll,fetchPages,parsePositive,printPage,resolveChatCategory,resolveChatOrg,resolveTagIds,resolveTopicId,truncate,withCategory}from"./chunk-
|
|
1
|
+
import{CHAT_API_PREFIX,CHAT_BATCH_SIZE,ChatApiClient,DEFAULT_MAX_ITEMS,addPageOptions,categoryScope,chatPath,chatScope,chunks,createChatApiClient,csv,describeScopes,fetchAll,fetchPages,parsePositive,printPage,resolveChatCategory,resolveChatOrg,resolveTagIds,resolveTopicId,truncate,withCategory}from"./chunk-VHV7YMN5.js";import"./chunk-ZXRPUGCO.js";import"./chunk-QJ2UAX2V.js";import"./chunk-OIGVDK3F.js";import"./chunk-PSBF4TEK.js";export{CHAT_API_PREFIX,CHAT_BATCH_SIZE,ChatApiClient,DEFAULT_MAX_ITEMS,addPageOptions,categoryScope,chatPath,chatScope,chunks,createChatApiClient,csv,describeScopes,fetchAll,fetchPages,parsePositive,printPage,resolveChatCategory,resolveChatOrg,resolveTagIds,resolveTopicId,truncate,withCategory};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{CredentialError,batchDirectory,cancellationRequested,finishSession,getSessionStatus,openLocalStore,resolveSessionCredential,startSession,stopSession}from"./chunk-
|
|
1
|
+
import{CredentialError,batchDirectory,cancellationRequested,finishSession,getSessionStatus,openLocalStore,resolveSessionCredential,startSession,stopSession}from"./chunk-ZZK6V3ZF.js";import{CliError}from"./chunk-QJ2UAX2V.js";import{configDir}from"./chunk-OIGVDK3F.js";import{spawn as spawn2}from"child_process";import{randomBytes as randomBytes2}from"crypto";import{copyFile,mkdir as mkdir2,writeFile,open,readFile,rename}from"fs/promises";import{existsSync}from"fs";import{join as join3}from"path";import{setTimeout as delay}from"timers/promises";var LOCAL_MCP_HINT="Gauge exposes no local MCP configuration for registered servers. Hosted sessions can discover and call their tools; supplied files cannot test the live server. If hosted testing is acceptable, start with `gauge onboard`, select a workspace and MCP version, configure any required connection, then preview with --hosted. Login and static verification do not establish server reachability or access. Hosted sessions use credits; previews contact Gauge and may upload inputs. Do not issue hosted commands for a local-only request. See `gauge instructions hillclimb`.";function assertLocalCapabilities(config,prefix=""){if(config.lifecycle!=null)throw new CliError("usage",`${prefix}lifecycle requires hosted Gauge.`,{hint:"Setup and teardown scripts run in hosted sessions. Use --hosted or remove lifecycle."});for(const field of["profileId","marketId","skillRefs","mcpRefs","connectionIds"]){const value=config[field];if(Array.isArray(value)?value.length>0:Boolean(value))throw new CliError("usage",`${prefix}${field} requires hosted Gauge.`,{hint:field==="mcpRefs"?LOCAL_MCP_HINT:"Use --hosted for personas and hosted assets, or select local files and Skills through named inputs in gauge.json."})}if(config.addons&&Object.keys(config.addons).length>0)throw new CliError("usage",`${prefix}addons requires hosted Gauge.`,{hint:"Managed browser addons are unavailable locally. Use --hosted or remove the addon."})}import{fileURLToPath}from"url";import{mkdirSync,readFileSync,renameSync,writeFileSync}from"fs";import{randomBytes}from"crypto";import{homedir}from"os";import{join}from"path";import{z}from"zod";var LOCAL_TARGETS={CLAUDE_CODE:{kind:"claude-code",model:"claude-sonnet-5-5"},CODEX_CLI:{kind:"codex",model:"gpt-6-astra"},PI:{kind:"pi",model:"openai-codex/gpt-6-astra"},OPENCODE:{kind:"opencode",model:"openai/gpt-6-astra"}};var agents=["CLAUDE_CODE","CODEX_CLI","PI","OPENCODE"];var variable=z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);var profileSchema=z.object({agent:z.enum(agents),provider:z.enum(["anthropic","openai","openai-codex","fireworks","openrouter"]),auth:z.enum(["api_key","access_token","setup_token"]),env:variable.optional()}).strict();var storeSchema=z.object({version:z.literal(1),profiles:z.record(z.string(),profileSchema),defaults:z.record(z.string(),z.string())}).strict();var API_KEY_ENV={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",fireworks:"FIREWORKS_API_KEY",openrouter:"OPENROUTER_API_KEY"};var profilePath=()=>join(configDir(),"local-profiles.json");function readProfiles(){let raw;try{raw=readFileSync(profilePath(),"utf8")}catch(error){if(error.code==="ENOENT")return{version:1,profiles:{},defaults:{}};throw error}try{const parsed=storeSchema.safeParse(JSON.parse(raw));if(parsed.success)return parsed.data}catch{}throw new CliError("usage","Invalid local credential profile file.",{hint:`Repair ${profilePath()}.`})}function writeProfiles(store){mkdirSync(configDir(),{recursive:true,mode:448});const temporary=`${profilePath()}.${randomBytes(6).toString("hex")}.tmp`;writeFileSync(temporary,`${JSON.stringify(storeSchema.parse(store),null,2)}
|
|
2
2
|
`,{mode:384});renameSync(temporary,profilePath())}function validateProfile(value){const parsed=profileSchema.safeParse(value);if(!parsed.success)throw new CliError("usage","Invalid profile. Supply a supported --agent, --provider and --auth, and an environment variable name with --env.");const p=parsed.data;const expectedProvider=p.agent==="CLAUDE_CODE"?"anthropic":p.agent==="CODEX_CLI"?"openai":void 0;if(expectedProvider&&p.provider!==expectedProvider)throw new CliError("usage",`${p.agent} requires provider ${expectedProvider}.`);if(p.auth==="access_token"){const provider=p.agent==="CLAUDE_CODE"?"anthropic":p.agent==="PI"?"openai-codex":"openai";if(p.provider!==provider||p.env)throw new CliError("usage",`Native login for ${p.agent} requires provider ${provider} and no --env.`)}else if(p.auth==="setup_token"){if(p.agent!=="CLAUDE_CODE")throw new CliError("usage","Setup tokens are supported only for CLAUDE_CODE.");p.env??="CLAUDE_CODE_OAUTH_TOKEN"}else{if(!API_KEY_ENV[p.provider])throw new CliError("usage",`API-key auth is unsupported for ${p.provider}.`);p.env??=API_KEY_ENV[p.provider]}return p}function setProfile(name,value,replace=false){if(!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}$/.test(name)||["__proto__","constructor","prototype"].includes(name))throw new CliError("usage","Profile names must be 1\u201364 letters, digits, dots, underscores or hyphens.");const p=validateProfile(value);const store=readProfiles();const previous=Object.hasOwn(store.profiles,name)?store.profiles[name]:void 0;if(previous&&!replace)throw new CliError("usage",`Profile ${name} already exists. Pass --replace to update it.`);if(previous&&previous.agent!==p.agent&&store.defaults[previous.agent]===name)delete store.defaults[previous.agent];store.profiles[name]=p;writeProfiles(store);return store}function requireProfile(store,name){if(!Object.hasOwn(store.profiles,name))throw new CliError("not_found",`Local credential profile ${name} does not exist.`,{hint:"Run gauge local profiles list."});return validateProfile(store.profiles[name])}function credentialKey(agent,model){return`${agent}:${model}`}function providerFor(agent,model){if(agent==="CLAUDE_CODE")return"anthropic";if(agent==="CODEX_CLI")return"openai";const slash=model.indexOf("/");if(slash<1||slash===model.length-1)throw new CliError("usage",`${agent} model ${model} must include provider/model.`);return model.slice(0,slash)}function resolveLocalProfile(agent,model,options={},store=void 0,env=process.env){const key=credentialKey(agent,model);if(options.credentialSelections){const selected=options.credentialSelections[key];if(!selected)throw new CliError("usage",`This batch has no saved login settings for ${agent} ${model}.`,{hint:"Check `gauge local profiles list`, then start a new batch with the profile you want to use."});validateCompatibility(selected,agent,model);return selected}store??=readProfiles();const provider=providerFor(agent,model);const name=options.profile??store.defaults[agent]??null;let p;if(name)p=requireProfile(store,name);else{const apiEnv=API_KEY_ENV[provider];const nativeProvider=agent==="CLAUDE_CODE"?"anthropic":agent==="PI"?"openai-codex":"openai";const auth=apiEnv&&env[apiEnv]?.trim()||provider!==nativeProvider?"api_key":agent==="CLAUDE_CODE"&&env.CLAUDE_CODE_OAUTH_TOKEN?.trim()?"setup_token":"access_token";p=validateProfile({agent,provider,auth})}validateCompatibility(p,agent,model);const nativeDirectory=p.auth==="access_token"?p.agent==="CLAUDE_CODE"?env.CLAUDE_CONFIG_DIR||void 0:env.CODEX_HOME||join(homedir(),".codex"):void 0;return{...p,name,source:p.env?`env:${p.env}`:p.agent==="CLAUDE_CODE"?"native:claude":"native:codex",...nativeDirectory?{nativeDirectory}:{}}}function validateCompatibility(p,agent,model){validateProfile(pickProfile(p));if(p.agent!==agent||p.provider!==providerFor(agent,model))throw new CliError("usage",`Credential profile for ${p.agent}/${p.provider} is incompatible with ${agent} ${model}.`,{hint:"Select a compatible --profile or change this harness's default with gauge local profiles use."})}function pickProfile(p){return{agent:p.agent,provider:p.provider,auth:p.auth,...p.env?{env:p.env}:{}}}function profileCredentialSources(profile,env=process.env){const mapped={...env};if(profile.env){if(!env[profile.env]?.trim())throw new CredentialError(`Credential environment variable ${profile.env} is not set.`,`Export ${profile.env} before starting the batch, or update the profile's --env reference.`);const canonical=profile.auth==="setup_token"?"CLAUDE_CODE_OAUTH_TOKEN":API_KEY_ENV[profile.provider];mapped[canonical]=env[profile.env]}if(profile.nativeDirectory)mapped[profile.agent==="CLAUDE_CODE"?"CLAUDE_CONFIG_DIR":"CODEX_HOME"]=profile.nativeDirectory;return{env:mapped,homeDir:homedir(),now:new Date}}function readinessSpec(agent,model,profile){return{image:"unused",agent:{kind:LOCAL_TARGETS[agent].kind,model},auth:{mode:profile.auth},workspace:null,resources:[],prompt:{text:""},limits:{turnTimeoutS:1800,responseTimeoutS:60,maxTurns:1}}}async function inspectLocalCredential(agent,model,options={},store){let profile;try{profile=resolveLocalProfile(agent,model,options,store);const credential=await resolveSessionCredential(readinessSpec(agent,model,profile),profileCredentialSources(profile));return{agent,model,profile,ready:true,...credential.expiresAt?{expiresAt:credential.expiresAt.toISOString()}:{},verification:"local"}}catch(error){const problem=error instanceof CredentialError?`${error.message} Fix: ${error.remedy}`:error instanceof CliError?error.message:"Could not read the credential source. Repair or renew the native login and retry.";return{agent,model,profile,ready:false,problem,verification:"local"}}}import{execFileSync,spawn}from"child_process";var runtime_manifest_default={version:"0.1.2",repository:"ghcr.io/gauge-sh/gauge-runtime",digest:"sha256:4056830a1efcb0116fb70e25a18576e26ad7222a87683d6f03387eb88f596c32",contract:"1",platforms:["linux/amd64","linux/arm64"],revision:"abb55dbfa9ceaa160c7a9685a0fd2b4e68a259aa"};var gateway_manifest_default={version:"0.1.0",repository:"ghcr.io/gauge-sh/gauge-gateway",digest:"sha256:ab5489cfe65feb717a79d7be6bd76be8bf915f3e44a5e832cee313772e590e1c",contract:"gateway-1",platforms:["linux/amd64","linux/arm64"],revision:"cdb3a7985666fbb6287be5b2b041aff327c874d7"};var RUNTIME_MANIFEST=runtime_manifest_default;var RUNTIME_IMAGE=runtime_manifest_default.digest?`${runtime_manifest_default.repository}@${runtime_manifest_default.digest}`:`${runtime_manifest_default.repository}:${runtime_manifest_default.version}`;var GATEWAY_IMAGE=gateway_manifest_default.digest?`${gateway_manifest_default.repository}@${gateway_manifest_default.digest}`:`${gateway_manifest_default.repository}:${gateway_manifest_default.version}`;var dockerRead=args=>execFileSync("docker",args,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:15e3});function inspectLocalRuntime(image=RUNTIME_IMAGE,docker=dockerRead,manifest=RUNTIME_MANIFEST){const result={reference:image,expectedContract:manifest.contract,supportedPlatforms:manifest.platforms,ready:false};const fail=(code,message,hint)=>({...result,problem:{code,message,hint}});let server;try{server=JSON.parse(docker(["version","--format","{{json .Server}}"]));if(!server?.Os||!server.Arch)throw new Error("No Docker server")}catch{return fail("docker_unavailable","Local runs need a running Docker daemon.","Start Docker Desktop (using Linux containers) or the Docker daemon, then retry.")}result.dockerPlatform=`${server.Os}/${server.Arch}`;if(!manifest.platforms.includes(result.dockerPlatform))return fail("platform_unsupported",`Docker ${server.Os}/${server.Arch} is not a qualified runtime platform.`,`Supported native Docker platforms: ${manifest.platforms.join(", ")}. Emulation is not qualified.`);let details;try{[details]=JSON.parse(docker(["image","inspect",image]))}catch{return fail("image_missing",`Local runs need the ${image} Docker image.`,image===RUNTIME_IMAGE?"Run: gauge local runtime pull":`Pull or build the selected runtime image: ${image}`)}if(!details?.Id||!details.Os||!details.Architecture)return fail("image_invalid",`Docker returned incomplete image metadata for ${image}.`,"Check docker image inspect for the selected image.");result.imageId=details.Id;result.repoDigest=details.RepoDigests?.find(digest=>digest.startsWith(`${manifest.repository}@`))??details.RepoDigests?.[0];result.contract=details.Config?.Labels?.["sh.gauge.contract"];result.platform=`${details.Os}/${details.Architecture}`;if(result.contract!==manifest.contract)return fail("contract_unsupported",`Runtime contract ${result.contract??"(missing)"} is unsupported; expected ${manifest.contract}.`,"Use a runtime derived from the supported Gauge image and preserve its contract.");if(!manifest.platforms.includes(result.platform)||server.Os!==details.Os||server.Arch!==details.Architecture)return fail("platform_unsupported",`Runtime ${result.platform} is not supported on Docker ${server.Os}/${server.Arch}.`,`Supported native Docker platforms: ${manifest.platforms.join(", ")}. Emulation is not qualified.`);result.ready=true;return result}function requireLocalRuntime(image=RUNTIME_IMAGE,manifest){const result=inspectLocalRuntime(image,void 0,manifest);if(!result.ready){const problem=result.problem;throw new CliError(problem.code==="image_missing"||problem.code==="docker_unavailable"?"not_found":"usage",problem.message,{hint:problem.hint})}return result}var inspectLocalGateway=(image=GATEWAY_IMAGE,docker)=>inspectLocalRuntime(image,docker,gateway_manifest_default);var requireLocalGateway=(image=GATEWAY_IMAGE)=>requireLocalRuntime(image,gateway_manifest_default);var pullLocalGateway=()=>pullLocalRuntime(GATEWAY_IMAGE,gateway_manifest_default);async function pullLocalRuntime(image=RUNTIME_IMAGE,manifest=RUNTIME_MANIFEST){const before=inspectLocalRuntime(image,void 0,manifest);if(!before.dockerPlatform||!manifest.platforms.includes(before.dockerPlatform)){const problem=before.problem;throw new CliError(problem.code==="docker_unavailable"?"not_found":"usage",problem.message,{hint:problem.hint})}const platform=before.dockerPlatform;await new Promise((resolve,reject)=>{const child=spawn("docker",["pull","--platform",platform,image],{stdio:["ignore","pipe","pipe"]});child.stdout.pipe(process.stderr);child.stderr.pipe(process.stderr);child.once("error",()=>reject(new CliError("not_found","Docker could not start.",{hint:"Install and start Docker, then retry."})));child.once("exit",code=>code===0?resolve():reject(new CliError("network",`Could not pull ${image}.`,{hint:"Check the network and public registry availability, then retry gauge local runtime pull."})))});return requireLocalRuntime(image,manifest)}import{execFile}from"child_process";import{randomUUID}from"crypto";import{mkdtemp,mkdir,rm}from"fs/promises";import{tmpdir}from"os";import{join as join2}from"path";import{promisify}from"util";var exec=promisify(execFile);var tools=["sh","bash","git","sha256sum","mkdir","cp","tar","chmod","touch","node","npm","jq","curl"];var harnesses={"claude-code":"claude",codex:"codex",pi:"pi",opencode:"opencode"};var marker="GAUGE_RUNTIME_COMPATIBLE";async function checkLocalRuntimeCompatibility(imageId,agents2){if(!process.getuid||!process.getgid)throw new CliError("usage","Local runtime execution requires a Unix host UID/GID.",{hint:"Run Gauge on macOS or Linux with local Docker running Linux containers, or inside WSL on Windows."});const directory=await mkdtemp(join2(tmpdir(),"gauge-runtime-check-"));const name=`gauge-runtime-check-${randomUUID()}`;try{if(/[,"\n]/.test(directory))throw new CliError("usage","The temporary directory cannot be mounted by Docker.",{hint:"Set TMPDIR to a path without commas, quotes or newlines, then retry."});await mkdir(join2(directory,"workspace"),{mode:448});const commands=[...new Set(agents2.map(agent=>harnesses[agent]))];const script=["set -eu",...tools.map(tool=>`command -v ${tool} >/dev/null || { echo 'missing tool: ${tool}' >&2; exit 41; }`),"mkdir -p /gauge/session/home /gauge/session/workspace || { echo 'session directory is not writable' >&2; exit 42; }","touch /gauge/session/workspace/probe /tmp/gauge-runtime-probe || { echo 'session directory or /tmp is not writable' >&2; exit 42; }","mkdir -p /gauge/session/npm/bin","printf '#!/bin/sh\\nexit 0\\n' > /gauge/session/npm/bin/gauge-runtime-path-probe","chmod 755 /gauge/session/npm/bin/gauge-runtime-path-probe",...["sh -c","sh -lc","bash -lc"].map(shell=>`${shell} gauge-runtime-path-probe >/dev/null || { echo 'environment-installed tools are missing from PATH in ${shell}; rebuild from the current Gauge runtime or preserve /gauge/session/npm/bin in the system login profile and image PATH' >&2; exit 44; }`),"cd /gauge/session/workspace","git init --quiet && git -c user.name=gauge -c user.email=gauge@localhost commit --quiet --allow-empty -m probe","tar --create --gzip --file /tmp/gauge-probe.tar.gz probe","tar --extract --gzip --file /tmp/gauge-probe.tar.gz --directory /gauge/session/workspace --no-same-owner --no-same-permissions","sha256sum probe | sha256sum -c --quiet -",...commands.map(command=>`${command} --version >/dev/null || { echo 'missing or broken harness: ${command}' >&2; exit 43; }`),`echo ${marker}`].join("\n");let stdout;try{({stdout}=await exec("docker",["run","--rm","--pull","never","--name",name,"--network","none","--user",`${process.getuid()}:${process.getgid()}`,"--env","HOME=/gauge/session/home","--env","CLAUDE_CONFIG_DIR=/gauge/session/claude","--env","CODEX_HOME=/gauge/session/codex","--env","PI_CODING_AGENT_DIR=/tmp/pi-agent","--env","XDG_DATA_HOME=/gauge/session/opencode/data","--env","XDG_STATE_HOME=/gauge/session/opencode/state","--mount",`type=bind,source=${join2(directory,"workspace")},target=/gauge/session`,imageId,"sh","-c",script],{timeout:6e4,maxBuffer:1024*1024}))}catch(error){const stderr=String(error.stderr??"").trim();const detail=stderr?` ${stderr.slice(-2e3)}`:" The probe failed or timed out.";throw new CliError("usage",`Runtime ${imageId} failed its compatibility check.${detail}`,{hint:"Derive from the supported Gauge runtime; preserve required tools, harnesses and the session npm bin in ordinary/login-shell PATH, permit the host UID/GID to write /gauge/session and /tmp, and have ENTRYPOINT execute the supplied command."})}if(!stdout.split(/\r?\n/).includes(marker))throw new CliError("usage",`Runtime ${imageId} did not execute Gauge's compatibility command.`,{hint:'Remove the custom ENTRYPOINT or make it finish with exec "$@". Gauge supplies sh -c and must receive its output.'})}finally{await exec("docker",["rm","--force",name],{timeout:1e4}).catch(()=>{});await rm(directory,{recursive:true,force:true})}}import{createHash}from"crypto";import{createReadStream}from"fs";import{list}from"tar";import{z as z3}from"zod";import{z as z2}from"zod";var websiteUrlSchema=z2.url().refine(raw=>{const u=new URL(raw);return u.protocol==="https:"&&!u.username&&!u.password&&!u.port&&!u.search&&!u.hash},"Expected an HTTPS documentation URL without credentials, port, query or fragment");var websiteUseSchema=z2.object({type:z2.literal("website"),url:websiteUrlSchema.refine(url=>new URL(url).pathname==="/","Website inputs require an origin without a path")}).strict();var deploymentSourceSchema=z2.object({type:z2.literal("github-deployment"),environment:z2.string().min(1).max(128)}).strict();var commentSourceSchema=z2.object({type:z2.literal("github-pr-comment"),author:z2.string().min(1).max(100).regex(/^[a-zA-Z0-9-]+(?:\[bot\])?$/),bodyIncludes:z2.string().min(1).max(256).describe("Literal marker identifying the provider's preview comment."),pattern:z2.string().min(1).max(2048).refine(pattern=>{try{new RegExp(pattern,"gm");return pattern.includes("(?<url>")&&pattern.includes("(?<sha>")}catch{return false}},"Use a valid regex with named url and sha captures; match only a ready preview").describe("JavaScript regex (gm flags) matching readiness and capturing url and sha (7\u201340 hex characters). Execution is time limited."),failureIncludes:z2.string().min(1).max(256).optional().describe("Literal failure marker in the selected comment; failure never falls back to older comments.")}).strict();var websiteSourceSchema=z2.discriminatedUnion("type",[deploymentSourceSchema,commentSourceSchema]);function withinWebsiteScope(raw,base){const u=new URL(raw),scope=new URL(base);const prefix=scope.pathname.replace(/\/$/,"");return u.origin===scope.origin&&(u.pathname===prefix||u.pathname.startsWith(`${prefix}/`))}var MAX_WEB_FIXTURE_BYTES=1e6;function normalizeWebFixtureUrl(raw){const url=new URL(raw);url.hash="";return url.href}var searchResultSchema=z3.object({title:z3.string().min(1),url:z3.url().transform(normalizeWebFixtureUrl),snippet:z3.string()});var searchFixtureSchema=z3.object({query:z3.string().trim().min(1),results:z3.array(searchResultSchema)});var pageFixtureSchema=z3.object({url:z3.url().transform(normalizeWebFixtureUrl),status:z3.int().min(100).max(599).default(200),contentType:z3.string().trim().min(1).default("text/html"),body:z3.string()});var originProxySchema=z3.object({origin:websiteUrlSchema.refine(raw=>new URL(raw).pathname==="/","Expected an origin").transform(raw=>new URL(raw).origin),upstream:websiteUrlSchema.refine(raw=>new URL(raw).pathname==="/","Expected an origin").transform(raw=>new URL(raw).origin)}).strict();var webFixtureSchema=z3.object({version:z3.literal(1),origins:z3.array(originProxySchema).max(32).optional(),scopes:z3.array(websiteUrlSchema.transform(normalizeWebFixtureUrl)).max(32).optional(),searches:z3.array(searchFixtureSchema).default([]),pages:z3.array(pageFixtureSchema).default([])}).superRefine((fixture,ctx)=>{if(fixture.scopes?.some(scope=>!fixture.pages.some(page=>new URL(page.url).origin===new URL(scope).origin)))ctx.addIssue({code:"custom",path:["scopes"],message:"Each scope must have a captured page on its origin"});const origins=new Set;for(const route of fixture.origins??[]){if(origins.has(route.origin)||route.origin===route.upstream||fixture.pages.some(page=>new URL(page.url).origin===route.origin)||fixture.scopes?.some(scope=>new URL(scope).origin===route.origin))ctx.addIssue({code:"custom",message:"Origin proxy overlaps another fixture route"});origins.add(route.origin)}const queries=new Set;fixture.searches.forEach((entry,index)=>{if(queries.has(entry.query)){ctx.addIssue({code:"custom",path:["searches",index,"query"],message:`duplicate normalized query: ${entry.query}`})}queries.add(entry.query)});const urls=new Set;fixture.pages.forEach((entry,index)=>{if(urls.has(entry.url)){ctx.addIssue({code:"custom",path:["pages",index,"url"],message:`duplicate normalized URL: ${entry.url}`})}urls.add(entry.url)});const bytes=new TextEncoder().encode(JSON.stringify(fixture)).byteLength;if(bytes>MAX_WEB_FIXTURE_BYTES){ctx.addIssue({code:"custom",message:`serialized fixture is ${bytes} bytes; maximum is ${MAX_WEB_FIXTURE_BYTES}`})}});var webFixtureInputSchema=webFixtureSchema.safeExtend({searches:z3.array(z3.never()).max(0).default([]),pages:z3.array(pageFixtureSchema.safeExtend({url:z3.url().refine(raw=>{const url=new URL(raw);return url.protocol==="https:"&&!url.port&&!url.username&&!url.password},"Expected an HTTPS URL without credentials or a custom port").transform(normalizeWebFixtureUrl),status:z3.int().min(200).max(599).default(200),contentType:z3.string().trim().min(1).regex(/^[\x20-\x7e]+$/).default("text/html"),body:z3.string().refine(body=>!/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(body),"Body must be valid Unicode")}).strict().refine(page=>![204,205,304].includes(page.status)||page.body==="","This HTTP status requires an empty body")).default([])}).strict().refine(fixture=>fixture.pages.length>0||(fixture.origins?.length??0)>0,"Web fixture must contain pages or origin mappings");function parseWebFixtureInput(text){if(new TextEncoder().encode(text).byteLength>MAX_WEB_FIXTURE_BYTES)throw new Error(`Web fixture exceeds ${MAX_WEB_FIXTURE_BYTES} bytes`);return webFixtureInputSchema.parse(JSON.parse(text))}function mergeWebFixtures(fixtures){if(!fixtures.length)return void 0;const scopes=[];for(const[index,fixture]of fixtures.entries()){for(const scope of fixture.scopes??[]){if(scopes.some(other=>withinWebsiteScope(scope,other)||withinWebsiteScope(other,scope)))throw new Error("Web fixture scopes overlap in this case");if(fixtures.some((other,otherIndex)=>otherIndex!==index&&other.pages.some(page=>withinWebsiteScope(page.url,scope))))throw new Error("Web fixture scope overlaps another input's pages");scopes.push(scope)}}return webFixtureSchema.parse({version:1,scopes,origins:fixtures.flatMap(f=>f.origins??[]),searches:fixtures.flatMap(f=>f.searches),pages:fixtures.flatMap(f=>f.pages)})}async function readWebFixtureArchive(path,member,digest){const hash=createHash("sha256");for await(const chunk of createReadStream(path))hash.update(chunk);if(`sha256:${hash.digest("hex")}`!==digest)throw new Error("Web fixture archive digest mismatch");const chunks=[];let found=0;let bytes=0;let problem;await list({file:path,strict:true,onReadEntry(entry){if(entry.path.replace(/^\.\//,"")!==member||entry.type!=="File"||entry.size>MAX_WEB_FIXTURE_BYTES){problem=new Error("Web fixture archive must contain exactly its declared JSON file (at most 1 MB)");entry.resume();return}found++;entry.on("data",chunk=>{bytes+=chunk.length;if(bytes>MAX_WEB_FIXTURE_BYTES)problem=new Error("Web fixture exceeds 1 MB");else chunks.push(chunk)})}});if(problem)throw problem;if(found!==1)throw new Error("Web fixture archive must contain exactly one JSON file");return parseWebFixtureInput(Buffer.concat(chunks).toString("utf8"))}async function freezeWebFixtures(definition,archives){const inputs=new Map;for(const resource of definition.resources){if(resource.use.type!=="web-fixture")continue;if(resource.source.type!=="upload")throw new Error(`Web fixture ${resource.name} requires a local file`);const digest=resource.source.sha256;const archive=archives.find(a=>a.sha256===digest);if(!archive)throw new Error(`Missing web fixture archive: ${resource.name}`);inputs.set(resource.name,await readWebFixtureArchive(archive.path,resource.use.path,archive.sha256))}const cases={};for(const item of definition.cases){const fixture=mergeWebFixtures((item.config.inputs??[...inputs.keys()]).flatMap(name=>inputs.get(name)??[]));if(fixture)cases[item.path]={fixture,digest:`sha256:${createHash("sha256").update(JSON.stringify(fixture)).digest("hex")}`}}return cases}var CONCURRENCY=4;var POLL_MS=1e3;var LOCAL_AGENTS=LOCAL_TARGETS;function analysisNext(batchId){return["Next: analyze these runs. Run this command and follow it:"," gauge instructions session-analysis --local",`Analyze only batch ${batchId}.`].join("\n")}async function planLocal(definition,options={}){const{queue}=plan(definition);const warnings=[];const runtime=inspectLocalRuntime(options.runtimeImage);const gateway=definition.resources.some(r=>r.use.type==="web-fixture")?inspectLocalGateway(options.gatewayImage):void 0;if(gateway?.problem)warnings.push(`${gateway.problem.message} ${gateway.problem.hint}`);if(runtime.problem)warnings.push(`${runtime.problem.message} ${runtime.problem.hint}`);const credentials=await credentialReadiness(queue,options);for(const target of credentials)if(!target.ready)warnings.push(`${target.agent} ${target.model}: ${target.problem}`);return{mode:"local",runtime,gateway,runtimeProbe:"not_run",expectedSessions:queue.length,cases:definition.cases.map(item=>{const sessions=new Map;for(const job of queue.filter(job2=>job2.item===item)){const key=`${job.agent}\0${job.model}`;const entry=sessions.get(key)??{agent:job.agent,model:job.model,samples:0};entry.samples++;sessions.set(key,entry)}return{path:item.path,criteria:item.criteria?.length??0,sessions:[...sessions.values()]}}),inputs:definition.resources.map(r=>({name:r.name,use:r.use.type})),warnings,credentials}}function plan(definition){for(const item of definition.cases){assertLocalCapabilities(item.config,`${item.path}: config.`);if(item.config.repoRef&&!item.config.repoUrl)throw new CliError("usage",`${item.path}: config.repoRef requires config.repoUrl.`);for(const name of item.config.inputs??[])if(!definition.resources.some(resource=>resource.name===name))throw new CliError("usage",`${item.path}: input ${name} is missing from this launch.`)}const resources=new Map(definition.resources.filter(resource=>resource.use.type!=="web-fixture").map(resource=>[resource.name,toResourceRef(resource)]));const queue=definition.cases.flatMap(item=>item.config.agents.flatMap(entry=>{const agent=LOCAL_AGENTS[entry.agent];if(!agent)throw new CliError("usage",`${item.path}: agent ${entry.agent} cannot run locally.`,{hint:"Use CLAUDE_CODE, CODEX_CLI, PI, or OPENCODE, or pass --hosted."});const models=entry.models?.length?entry.models:[agent.model];return models.flatMap(model=>Array.from({length:item.config.sampleCount??1},(_,sample)=>({item,agent:entry.agent,model,sample:sample+1})))}));return{resources,queue}}async function prepareLocal(definition,uploads,gaugeDir,options={}){const{queue}=plan(definition);const webFixtures=await freezeWebFixtures(definition,uploads);const gateway=Object.keys(webFixtures).length?requireLocalGateway(options.gatewayImage):void 0;await freezeCredentials(queue,options);const runtime=requireLocalRuntime(options.runtimeImage);await checkLocalRuntimeCompatibility(runtime.imageId,[...new Set(queue.map(job=>LOCAL_AGENTS[job.agent].kind))]);const blobsDirectory=join3(gaugeDir,"blobs");await mkdir2(blobsDirectory,{recursive:true});for(const upload of uploads)await copyFile(upload.path,join3(blobsDirectory,upload.sha256.slice(7)));const batchId=`b_${randomBytes2(6).toString("hex")}`;const directory=batchDirectory(gaugeDir,batchId);await mkdir2(directory,{recursive:true,mode:448});await writeJson(join3(directory,"runtime.json"),runtime);await writeJson(join3(directory,"gateway.json"),{gateway,cases:webFixtures});await writeJson(join3(directory,"status.json"),{batchId,runtime,state:"queued",expectedSessions:plan(definition).queue.length});const store=openLocalStore(gaugeDir);try{store.recordLaunch({id:batchId,measurementId:options.measurement?.id,measurementRevision:options.measurement?.revision,configuration:definition,provenance:definition.source??{}})}finally{store.close()}return batchId}async function detachLocal(definition,uploads,gaugeDir,options={}){const credentialSelections=await freezeCredentials(plan(definition).queue,options);const batchId=await prepareLocal(definition,uploads,gaugeDir,{...options,credentialSelections});const directory=batchDirectory(gaugeDir,batchId);await writeFile(join3(directory,"request.json"),JSON.stringify({definition,gaugeDir,batchId,credentialSelections,measurement:options.measurement}),{mode:384});const log=await open(join3(directory,"supervisor.log"),"a",384);try{const bundledWorker=fileURLToPath(new URL("./batchWorker.js",import.meta.url));const workerArgs=existsSync(bundledWorker)?[bundledWorker]:[...process.execArgv,fileURLToPath(new URL("../batchWorker.ts",import.meta.url))];const child=spawn2(process.execPath,[...workerArgs,join3(directory,"request.json")],{detached:true,stdio:["ignore",log.fd,log.fd]});await new Promise((resolve,reject)=>{child.once("spawn",resolve);child.once("error",reject)});let exited=false;child.once("exit",()=>{exited=true});const deadline=Date.now()+1e4;while(true){const status=JSON.parse(await readFile(join3(directory,"status.json"),"utf8"));if(status.state!=="queued")break;if(exited||Date.now()>=deadline){await writeFile(join3(directory,"cancel"),"",{mode:384});throw new CliError("network",`Background supervisor did not become ready. See ${join3(directory,"supervisor.log")}`)}await delay(50)}child.unref()}finally{await log.close()}return{batchId,status:`gauge run status --batch ${batchId} --local`,wait:`gauge run wait --batch ${batchId} --local`,stop:`gauge run cancel --batch ${batchId} --local`}}async function runLocal(definition,uploads,gaugeDir,onRun=()=>{},options={}){const{resources,queue}=plan(definition);const credentialSelections=await freezeCredentials(queue,options);const batchId=options.batchId??await prepareLocal(definition,uploads,gaugeDir,{...options,credentialSelections});const directory=batchDirectory(gaugeDir,batchId);const runtime=JSON.parse(await readFile(join3(directory,"runtime.json"),"utf8"));const gatewayPlan=JSON.parse(await readFile(join3(directory,"gateway.json"),"utf8"));const expectedSessions=queue.length;let interrupted=false;const signal=()=>{interrupted=true;process.exitCode=130};process.on("SIGINT",signal);process.on("SIGTERM",signal);const canceled=()=>interrupted||cancellationRequested(directory);const runs=[];let progress=Promise.resolve();const save=state=>writeJson(join3(directory,"status.json"),{batchId,runtime,state,expectedSessions,finishedSessions:runs.length,queuedSessions:state==="running"?queue.length:0,skippedSessions:state==="running"?0:queue.length,supervisorPid:process.pid});try{await save("running");options.onStart?.(batchId);const worker=async()=>{while(!canceled()){const job=queue.shift();if(!job)break;const run=await runJob(job,{batchId,gaugeDir,blobsDirectory:join3(gaugeDir,"blobs"),resources,credentialSelections,runtime,gateway:gatewayPlan.gateway&&gatewayPlan.cases[job.item.path]?{image:gatewayPlan.gateway.imageId,...gatewayPlan.cases[job.item.path]}:void 0,canceled,measurement:options.measurement,provenance:definition.source??{}});runs.push(run);onRun(run);progress=progress.then(()=>save("running"));await progress}};const settled=await Promise.allSettled(Array.from({length:CONCURRENCY},worker));const failure=settled.find(s=>s.status==="rejected");await save(failure?"failed":canceled()?"canceled":"completed");if(failure?.status==="rejected")throw failure.reason;return{batchId,runs,next:analysisNext(batchId),canceled:canceled()}}finally{process.off("SIGINT",signal);process.off("SIGTERM",signal)}}function toResourceRef(resource){if(resource.source.type!=="upload")throw new CliError("usage",`Input ${resource.name} has no local file; local runs need every input in the working tree`);const base={name:resource.name,digest:resource.source.sha256,filename:`${resource.name}.tar.gz`,kind:"archive"};const use=resource.use;if(use.type==="files")return{...base,use:{type:"files"}};if(use.type==="skill"&&use.root===".")return{...base,use:{type:"skill"}};if(use.type==="npm-package")return{...base,use:{type:"npm-package",package:use.package,install:use.install??"workspace"}};throw new CliError("usage",`Input ${resource.name}: ${use.type==="skill"?"supply the Skill as a directory":`${use.type} inputs run on hosted Gauge only`}`)}async function credentialReadiness(queue,options){const store=options.credentialSelections?{version:1,profiles:{},defaults:{}}:readProfiles();const targets=new Map(queue.map(job=>[credentialKey(job.agent,job.model),job]));return Promise.all([...targets.values()].map(job=>inspectLocalCredential(job.agent,job.model,options,store)))}async function freezeCredentials(queue,options){const readiness=await credentialReadiness(queue,options);const failures=readiness.filter(target=>!target.ready);if(failures.length)throw new CliError("usage",failures.map(target=>`${target.agent} ${target.model}: ${target.problem}`).join("\n"),{hint:"Inspect credentials with gauge local profiles inspect <profile>, or preview every target with gauge run --local --dry-run -o json."});return Object.fromEntries(readiness.map(target=>[credentialKey(target.agent,target.model),target.profile]))}function sessionSpec(job,resources,profile,runtimeImage=RUNTIME_IMAGE){const names=job.item.config.inputs??[...resources.keys()];const selected=names.flatMap(name=>resources.get(name)??[]);const files=selected.filter(r=>r.use?.type==="files");const note=files.length?`
|
|
3
3
|
|
|
4
4
|
Prepared inputs:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SessionUnavailableError,getSessionStatus,localId,openLocalStore}from"./chunk-
|
|
1
|
+
import{SessionUnavailableError,getSessionStatus,localId,openLocalStore}from"./chunk-ZZK6V3ZF.js";import{existsSync,statSync}from"fs";import{open,readdir,readFile,stat}from"fs/promises";import{dirname,join}from"path";var TERMINAL=new Set(["completed","failed","canceled","interrupted"]);async function readJson(path){try{return JSON.parse(await readFile(path,"utf8"))}catch{return void 0}}var lineCache=new Map;async function readLines(path){let size;try{size=(await stat(path)).size}catch{lineCache.delete(path);return[]}let cached=lineCache.get(path);if(!cached||size<cached.bytes)cached={bytes:0,lines:[]};if(size>cached.bytes){const buffer=Buffer.alloc(size-cached.bytes);const file=await open(path,"r");try{await file.read(buffer,0,buffer.length,cached.bytes)}finally{await file.close()}const complete=buffer.lastIndexOf(10)+1;const lines=[...cached.lines];for(const line of buffer.subarray(0,complete).toString("utf8").split("\n")){if(!line)continue;try{lines.push(JSON.parse(line))}catch{}}cached={bytes:cached.bytes+complete,lines}}lineCache.set(path,cached);return cached.lines}var specCache=new Map;async function readSpec(attemptDir){const path=join(attemptDir,"spec.json");let mtimeMs;try{mtimeMs=(await stat(path)).mtimeMs}catch{return void 0}const cached=specCache.get(path);if(cached?.mtimeMs===mtimeMs)return cached.spec;const spec=await readJson(path);specCache.set(path,{mtimeMs,spec});return spec}async function names(path){try{return(await readdir(path,{withFileTypes:true})).filter(d=>d.isDirectory()).map(d=>d.name)}catch{return[]}}async function latestAttempt(gaugeDir,id){const attempts=join(gaugeDir,"runs",id,"attempts");const numbers=(await names(attempts)).map(Number).filter(Number.isSafeInteger);for(const n of numbers.sort((a,b)=>b-a)){const spec=await readSpec(join(attempts,String(n)));if(spec?.attempt?.runId!==id||spec.attempt.n!==n||typeof spec.attempt.batchId!=="string")continue;return{batchId:spec.attempt.batchId,directory:join(attempts,String(n),"session"),attempt:n}}return void 0}async function latestAttempts(gaugeDir){const ids=await names(join(gaugeDir,"runs"));const found=await Promise.all(ids.map(id=>latestAttempt(gaugeDir,id)));return new Map(ids.flatMap((id,i)=>found[i]?[[id,found[i]]]:[]))}var rowCache;function storeRows(gaugeDir){const path=join(gaugeDir,"gauge.sqlite");if(!existsSync(path))return new Map;const key=[path,`${path}-wal`].map(file=>{try{const{mtimeMs,size}=statSync(file);return`${mtimeMs}:${size}`}catch{return""}}).join("|");if(rowCache?.key===key)return rowCache.rows;try{const store=openLocalStore(gaugeDir);try{rowCache={key,rows:new Map(store.listSessions().map(row=>[row.id,row]))};return rowCache.rows}finally{store.close()}}catch{return new Map}}async function summarize(id,{batchId,directory,attempt},row){const attemptDir=dirname(directory);let[spec={},status,result]=await Promise.all([readSpec(attemptDir),readJson(join(directory,"status.json")),readJson(join(attemptDir,"result.json"))]);let state=result?.outcome??status?.state??"preparing";let lastKnownState=null;let unavailableDetail;if(!result&&!TERMINAL.has(state)){try{status=await getSessionStatus(directory,{timeoutMs:1e3});state=status.state}catch(error){if(error instanceof SessionUnavailableError)status=error.lastKnownStatus??status;result=await readJson(join(attemptDir,"result.json"));if(result)state=result.outcome;else{lastKnownState=status?.state??"preparing";state="unavailable";unavailableDetail="Controller status is unavailable; the session may still be running. Status will be checked again."}}}const measurement=spec.measurement;return{spec,session:{id,batchId,attempt,case:spec.case?.path??row?.case??null,agent:spec.agentName??row?.agent??null,model:spec.agent?.model??row?.model??null,sample:typeof spec.sample==="number"?spec.sample:null,measurement:measurement&&typeof measurement.id==="string"?{id:measurement.id,kind:measurement.kind,revision:measurement.revision}:null,state,lastKnownState,live:!result&&state!=="unavailable"&&!TERMINAL.has(state),turns:result?.turns??status?.turn??0,detail:unavailableDetail??result?.detail??status?.detail??null,createdAt:spec.createdAt??row?.createdAt??null,updatedAt:status?.updatedAt??null,endedAt:result?.endedAt??null,durationMs:result?.durationMs??null,inputTokens:row?.inputTokens??null,outputTokens:row?.outputTokens??null,analyzed:row?.analyzed??false}}}async function listWatchSessions(gaugeDir){const rows=storeRows(gaugeDir);const sessions=await Promise.all([...await latestAttempts(gaugeDir)].map(async([id,attempt])=>(await summarize(id,attempt,rows.get(id))).session));return sessions.sort((a,b)=>(b.createdAt??"").localeCompare(a.createdAt??"")||a.id.localeCompare(b.id))}function findAttempt(gaugeDir,id){return latestAttempt(gaugeDir,localId(id))}async function getWatchSession(gaugeDir,id){const attempt=await findAttempt(gaugeDir,id);if(!attempt)return void 0;const{session,spec}=await summarize(id,attempt,storeRows(gaugeDir).get(id));return{...session,prompt:spec.case?.prompt??null,criteria:spec.case?.criteria??null,preference:spec.case?.preference??null}}async function readWatchTrace(gaugeDir,id,after=-1){const attempt=await findAttempt(gaugeDir,id);if(!attempt)return void 0;const[events,inputs]=await Promise.all([readLines(join(attempt.directory,"events.ndjson")),readLines(join(attempt.directory,"inputs.ndjson"))]);return{events:events.filter(event=>event.seq>after).map(({seq,turn,observedAt,payload})=>({seq,turn,observedAt,payload})),inputs:inputs.map(({turn,observedAt,text,answer})=>typeof text==="string"?{turn,observedAt,text}:{turn,observedAt,answer})}}async function readWatchDiff(gaugeDir,id){const attempt=await findAttempt(gaugeDir,id);if(!attempt)return void 0;try{return await readFile(join(attempt.directory,"diff.patch"),"utf8")}catch{return""}}export{readJson,listWatchSessions,getWatchSession,readWatchTrace,readWatchDiff};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
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);import{z as z7}from"zod";var DEFAULT_LIFECYCLE_TIMEOUT_SECONDS=120;var MAX_LIFECYCLE_TIMEOUT_SECONDS=600;var MAX_LIFECYCLE_SOURCE_LENGTH=128*1024;var lifecycleScriptSchema=z7.object({source:z7.string().min(1).max(MAX_LIFECYCLE_SOURCE_LENGTH),timeoutSeconds:z7.number().int().min(1).max(MAX_LIFECYCLE_TIMEOUT_SECONDS).default(DEFAULT_LIFECYCLE_TIMEOUT_SECONDS)}).strict();var lifecycleSchema=z7.object({version:z7.literal(1),setup:lifecycleScriptSchema.optional(),teardown:lifecycleScriptSchema.optional(),params:z7.record(z7.string().min(1).max(128),z7.json()).default({})}).strict().refine(value=>value.setup!==void 0||value.teardown!==void 0,{message:"Configure a setup or teardown script"}).refine(value=>new TextEncoder().encode(JSON.stringify(value.params)).byteLength<=64*1024,{path:["params"],message:"Lifecycle parameters must fit within 64 KiB"});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 z10}from"zod";import{z as z9}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 z8}from"zod";var ANALYSIS_SCHEMA_VERSION=1;var evidenceSequenceSchema=z8.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=z8.discriminatedUnion("kind",[z8.object({kind:z8.literal("trace"),seq:evidenceSequenceSchema}).strict(),z8.object({kind:z8.literal("diff"),path:z8.string().min(1)}).strict()]);var INSTALL_PHASES=["NONE","ATTEMPTED","CONFIGURED","EXERCISED"];var sessionProductSchema=z8.object({name:z8.string(),mentioned:z8.boolean(),considered:z8.boolean(),recommended:z8.boolean(),chosen:z8.boolean(),rejected:z8.boolean(),abandoned:z8.boolean(),installPhase:z8.enum(INSTALL_PHASES),rank:z8.number().int().nullable(),source:z8.enum(["BRIEF","PERSONA","PRIOR","SEARCH","PAGE","REPO","UNKNOWN"]),reason:z8.string(),categories:z8.array(z8.string()),evidence:z8.record(z8.string(),z8.array(evidenceRefSchema))});var sessionObservationSchema=z8.object({id:z8.string(),kind:z8.enum(["FRICTION","OBJECTION","OPPORTUNITY"]),label:z8.string(),detail:z8.string(),subject:z8.string(),basis:z8.enum(["OBSERVED","AGENT_CLAIM","INFERRED"]),effect:z8.enum(["BLOCKED","RECOVERED","EXTRA_WORK","SELECTION_LOSS","UNKNOWN"]),cause:z8.enum(["PRODUCT","CONTENT","ACCESS","ENVIRONMENT","AGENT","UNKNOWN"]),tags:z8.array(z8.string()),evidence:z8.array(evidenceRefSchema),issueId:z8.string().nullable().optional()});var sessionAnalysisSchema=z8.object({schemaVersion:z8.literal(ANALYSIS_SCHEMA_VERSION),instructionsVersion:z8.string().min(1),id:z8.string(),runId:z8.string(),attempt:z8.number().int(),createdAt:z8.string(),origin:z8.enum(["MODEL","LEGACY"]),model:z8.string().nullable(),assessability:z8.enum(["ASSESSED","PARTIAL","UNASSESSABLE"]),limitation:z8.string().nullable(),selection:z8.enum(["MEASURED","UNASSESSABLE","NOT_MEASURED"]),directed:z8.boolean(),products:z8.array(sessionProductSchema),observations:z8.array(sessionObservationSchema)});var artifactPathSchema=z8.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=z8.discriminatedUnion("kind",[z8.object({kind:z8.literal("trace"),seq:evidenceSequenceSchema}).strict(),z8.object({kind:z8.literal("diff"),path:artifactPathSchema}).strict(),z8.object({kind:z8.literal("artifact"),artifact:artifactPathSchema.describe("Path relative to the session attempt directory, for example session/events.ndjson."),attempt:z8.number().int().positive().optional().describe("Must match the analysis attempt; defaults to that attempt."),line:z8.number().int().positive().optional().describe("One-based line number in the original artifact, before any filtering."),endLine:z8.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,issueId:true}).extend({label:z8.string().trim().min(1).max(200),detail:z8.string().trim().min(1).max(1e4),subject:z8.string().trim().min(1).max(200),tags:z8.array(z8.string().trim().min(1).max(64)).max(32).default([]),evidence:z8.array(portableEvidenceRefSchema).min(1).max(100)}).strict();var criterionAnalysisSubmissionSchema=z8.object({criterionId:z8.string().min(1),outcome:z8.enum(["PASS","FAIL","UNASSESSABLE"]),label:z8.string().trim().min(1).max(1e4),evidence:z8.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:z8.string().trim().min(1).max(200),evidence:z8.record(z8.string(),z8.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=z8.object({schemaVersion:z8.literal(ANALYSIS_SCHEMA_VERSION),attempt:z8.number().int().positive().default(1),instructionsVersion:z8.string().trim().min(1),analyst:z8.object({name:z8.string().trim().min(1),model:z8.string().trim().min(1).optional()}).strict(),assessability:sessionAnalysisSchema.shape.assessability,limitation:z8.string().trim().min(1).nullable().default(null),selection:sessionAnalysisSchema.shape.selection.default("NOT_MEASURED"),directed:z8.boolean().default(false),findings:z8.array(findingSubmissionSchema).max(1e3).default([]),products:z8.array(productSubmissionSchema).max(1e3).default([]),criteria:z8.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=z9.enum(RUN_STATUSES);var AGENTS=["CLAUDE_CODE","CODEX_CLI","CURSOR","PI","OPENCODE","ANTIGRAVITY"];var agentSchema=z9.enum(AGENTS);var OBSERVED_PROVIDER_SOURCES=["AGENT_STREAM","GATEWAY_RESPONSE","GATEWAY_AUDIT","CANARY"];var observedProviderSourceSchema=z9.enum(OBSERVED_PROVIDER_SOURCES);var selectedProviderSchema=z9.object({slug:z9.string(),displayName:z9.string()});var observedProviderSchema=z9.object({slug:z9.string(),source:observedProviderSourceSchema});var RUN_TRIGGER_SOURCES=["UNKNOWN","UI","API","CADENCE","STAFF","OPERATOR","GITHUB"];var runTriggerSourceSchema=z9.enum(RUN_TRIGGER_SOURCES);var runTriggeredBySchema=z9.object({source:runTriggerSourceSchema,userId:z9.string().nullable(),email:z9.string().nullable()});var runOptimizationTrialSchema=z9.object({optimizationId:z9.string(),trialId:z9.string(),key:z9.string(),title:z9.string(),kind:z9.enum(INTERVENTION_KINDS)});var runCreditsChargedSchema=z9.number().int().nullable();var runStatusFilterSchema=z9.string().transform(raw=>raw.split(",").map(s=>s.trim().toUpperCase()).filter(Boolean)).pipe(z9.array(runStatusSchema).min(1));var runListQuerySchema=listQuerySchema.extend({status:runStatusFilterSchema.optional(),batch:z9.string().optional(),prompt:z9.string().optional(),experiment:z9.string().optional(),evalSet:z9.string().optional(),since:z9.string().optional()});var runListItemSchema=z9.object({id:z9.string(),status:runStatusSchema,agent:agentSchema,model:z9.string(),resolvedModel:z9.string().nullable().optional(),modelDisplayName:z9.string().nullable().optional(),selectedProvider:selectedProviderSchema.nullable().optional(),observedProvider:observedProviderSchema.nullable().optional(),promptId:z9.string(),promptSnippet:z9.string(),batchId:z9.string(),experiment:z9.string().nullable(),evalSetId:z9.string().nullable(),evalRevision:z9.string().optional(),optimizationTrial:runOptimizationTrialSchema.nullable().optional(),turns:z9.number().int().nullable(),usdCost:z9.number().nullable(),creditsCharged:runCreditsChargedSchema.optional(),triggeredBy:runTriggeredBySchema.optional(),durationMs:z9.number().int().nullable(),exitReason:z9.string().nullable(),createdAt:z9.string(),startedAt:z9.string().nullable(),finishedAt:z9.string().nullable(),parentRunId:z9.string().nullable(),fetchForkPlanId:z9.string().nullable()});var runListResponseSchema=listResponseSchema(runListItemSchema);var runSkillSchema=z9.discriminatedUnion("source",[z9.object({source:z9.literal("saved"),skillId:z9.string(),name:z9.string(),label:z9.string()}),z9.object({source:z9.literal("input"),name:z9.string(),commit:z9.string().nullable(),pullNumber:z9.number().int().nullable()})]);var runDetailSchema=runListItemSchema.omit({promptSnippet:true}).extend({promptText:z9.string(),attempt:z9.number().int(),cancelRequested:z9.boolean(),failureReason:z9.string().nullable(),repoUrl:z9.string().nullable(),repoRef:z9.string().nullable(),scenario:z9.string(),funding:z9.string(),usage:z9.unknown().nullable(),hasDiff:z9.boolean(),claimedAt:z9.string().nullable(),criterionResults:z9.array(z9.object({criterionId:z9.string().nullable(),name:z9.string(),passed:z9.boolean().nullable(),reasoning:z9.string().nullable()})),skills:z9.array(runSkillSchema).optional()});var cancelRunResponseSchema=z9.object({id:z9.string(),status:runStatusSchema,cancelRequested:z9.boolean(),note:z9.string().optional()});var regradeRunResponseSchema=z9.object({runId:z9.string(),evalSetId:z9.string().nullable(),criteria:z9.number().int()});var RUN_INSIGHT_STATUSES=["PENDING","RUNNING","COMPLETE","FAILED","SKIPPED"];var runInsightStatusSchema=z9.enum(RUN_INSIGHT_STATUSES);var insightPassSchema=z9.object({status:runInsightStatusSchema,model:z9.string().nullable(),inputTokens:z9.number().int().nullable(),outputTokens:z9.number().int().nullable(),usdCost:z9.number().nullable(),error:z9.string().nullable()});var runDecisionSchema=z9.object({index:z9.number().int(),category:z9.string(),categoryRaw:z9.string().nullable(),chosenName:z9.string(),chosenEcosystem:z9.string().nullable(),chosenPackage:z9.string().nullable(),reversed:z9.boolean(),detail:z9.unknown()});var RUN_INSIGHT_PASS_KINDS=["ANALYSIS","CLI_DISCOVERY","LEVER","EXPERIMENT_DELTA"];var runInsightPassKindSchema=z9.enum(RUN_INSIGHT_PASS_KINDS);var insightPipelinePassSchema=insightPassSchema.extend({kind:runInsightPassKindSchema});var runInsightResponseSchema=z9.object({runId:z9.string(),decision:insightPassSchema,passes:z9.array(insightPipelinePassSchema),decisions:z9.array(runDecisionSchema),experimentDelta:z9.unknown().nullable(),visibilityVerdict:z9.unknown().nullable(),analysis:sessionAnalysisSchema.nullable()});var runEventSchema=z9.looseObject({run_id:z9.string(),seq:z9.number(),turn:z9.number(),ts:z9.string(),type:z9.string()});var runCompareSideSchema=z9.object({runRequest:z9.string().min(1).optional(),batch:z9.array(z9.string().min(1)).min(1).max(100).optional(),evalSet:z9.string().min(1).optional(),evalRevision:z9.string().min(1).optional(),trial:z9.string().min(1).optional(),experiment:z9.string().min(1).optional(),agent:z9.array(agentSchema).min(1).optional(),model:z9.array(z9.string()).min(1).optional(),since:z9.string().optional(),until:z9.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=z9.object({baseline:runCompareSideSchema,candidate:runCompareSideSchema}).strict();var runCompareStatsSchema=z9.object({runs:z9.number().int(),finished:z9.number().int(),succeeded:z9.number().int(),judged:z9.number().int(),passed:z9.number().int(),passRate:z9.number().nullable(),medianTurns:z9.number().nullable(),medianUsdCost:z9.number().nullable(),medianDurationMs:z9.number().nullable(),criteria:z9.array(z9.object({name:z9.string(),judged:z9.number().int(),passed:z9.number().int(),passRate:z9.number().nullable()}))});var runCompareDeltaSchema=z9.object({passRate:z9.number().nullable(),medianTurns:z9.number().nullable(),medianUsdCost:z9.number().nullable(),medianDurationMs:z9.number().nullable(),criteria:z9.array(z9.object({name:z9.string(),passRate:z9.number().nullable()}))});var runCompareRowSchema=z9.object({baseline:runCompareStatsSchema,candidate:runCompareStatsSchema,delta:runCompareDeltaSchema});var runCompareMixedRevisionSchema=z9.object({evalSetId:z9.string().nullable(),promptId:z9.string().nullable(),revisions:z9.array(z9.string())});var runCompareTrialSchema=runOptimizationTrialSchema.extend({runs:z9.number().int()});var runCompareResponseSchema=z9.object({overall:runCompareRowSchema,targets:z9.array(runCompareRowSchema.extend({agent:agentSchema,model:z9.string()})),sides:z9.object({baseline:z9.object({evalRevisions:z9.array(z9.string()),mixedRevisions:z9.array(runCompareMixedRevisionSchema).optional(),truncated:z9.boolean(),trials:z9.array(runCompareTrialSchema).optional()}),candidate:z9.object({evalRevisions:z9.array(z9.string()),mixedRevisions:z9.array(runCompareMixedRevisionSchema).optional(),truncated:z9.boolean(),trials:z9.array(runCompareTrialSchema).optional()})})});var SCHEDULABLE_AGENTS=["CLAUDE_CODE","CODEX_CLI","PI","OPENCODE"];var schedulableAgentSchema=z10.enum(SCHEDULABLE_AGENTS);var ROSTERABLE_AGENTS=[...SCHEDULABLE_AGENTS,"ANTIGRAVITY"];var rosterableAgentSchema=z10.enum(ROSTERABLE_AGENTS);var agentConfigSchema=z10.object({agent:agentSchema,models:z10.array(z10.string().min(1))});var agentConfigInputSchema=z10.object({agent:rosterableAgentSchema,models:z10.array(z10.string().min(1)).default([])});var assetRefSchema=z10.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=z10.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,signal){return this.request("GET",path,{query,signal})}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),signal:options.signal});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-QCOOVF65.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,DEFAULT_LIFECYCLE_TIMEOUT_SECONDS,MAX_LIFECYCLE_TIMEOUT_SECONDS,MAX_LIFECYCLE_SOURCE_LENGTH,lifecycleSchema,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};
|
|
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);import{z as z7}from"zod";var DEFAULT_LIFECYCLE_TIMEOUT_SECONDS=120;var MAX_LIFECYCLE_TIMEOUT_SECONDS=600;var MAX_LIFECYCLE_SOURCE_LENGTH=128*1024;var lifecycleScriptSchema=z7.object({source:z7.string().min(1).max(MAX_LIFECYCLE_SOURCE_LENGTH),timeoutSeconds:z7.number().int().min(1).max(MAX_LIFECYCLE_TIMEOUT_SECONDS).default(DEFAULT_LIFECYCLE_TIMEOUT_SECONDS)}).strict();var lifecycleSchema=z7.object({version:z7.literal(1),setup:lifecycleScriptSchema.optional(),teardown:lifecycleScriptSchema.optional(),params:z7.record(z7.string().min(1).max(128),z7.json()).default({})}).strict().refine(value=>value.setup!==void 0||value.teardown!==void 0,{message:"Configure a setup or teardown script"}).refine(value=>new TextEncoder().encode(JSON.stringify(value.params)).byteLength<=64*1024,{path:["params"],message:"Lifecycle parameters must fit within 64 KiB"});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 z10}from"zod";import{z as z9}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 z8}from"zod";var ANALYSIS_SCHEMA_VERSION=1;var evidenceSequenceSchema=z8.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=z8.discriminatedUnion("kind",[z8.object({kind:z8.literal("trace"),seq:evidenceSequenceSchema}).strict(),z8.object({kind:z8.literal("diff"),path:z8.string().min(1)}).strict()]);var INSTALL_PHASES=["NONE","ATTEMPTED","CONFIGURED","EXERCISED"];var sessionProductSchema=z8.object({name:z8.string(),mentioned:z8.boolean(),considered:z8.boolean(),recommended:z8.boolean(),chosen:z8.boolean(),rejected:z8.boolean(),abandoned:z8.boolean(),installPhase:z8.enum(INSTALL_PHASES),rank:z8.number().int().nullable(),source:z8.enum(["BRIEF","PERSONA","PRIOR","SEARCH","PAGE","REPO","UNKNOWN"]),reason:z8.string(),categories:z8.array(z8.string()),evidence:z8.record(z8.string(),z8.array(evidenceRefSchema))});var sessionObservationSchema=z8.object({id:z8.string(),kind:z8.enum(["FRICTION","OBJECTION","OPPORTUNITY"]),label:z8.string(),detail:z8.string(),subject:z8.string(),basis:z8.enum(["OBSERVED","AGENT_CLAIM","INFERRED"]),effect:z8.enum(["BLOCKED","RECOVERED","EXTRA_WORK","SELECTION_LOSS","UNKNOWN"]),cause:z8.enum(["PRODUCT","CONTENT","ACCESS","ENVIRONMENT","AGENT","UNKNOWN"]),tags:z8.array(z8.string()),evidence:z8.array(evidenceRefSchema),issueId:z8.string().nullable().optional()});var sessionAnalysisSchema=z8.object({schemaVersion:z8.literal(ANALYSIS_SCHEMA_VERSION),instructionsVersion:z8.string().min(1),id:z8.string(),runId:z8.string(),attempt:z8.number().int(),createdAt:z8.string(),origin:z8.enum(["MODEL","LEGACY"]),model:z8.string().nullable(),assessability:z8.enum(["ASSESSED","PARTIAL","UNASSESSABLE"]),limitation:z8.string().nullable(),selection:z8.enum(["MEASURED","UNASSESSABLE","NOT_MEASURED"]),directed:z8.boolean(),products:z8.array(sessionProductSchema),observations:z8.array(sessionObservationSchema)});var artifactPathSchema=z8.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=z8.discriminatedUnion("kind",[z8.object({kind:z8.literal("trace"),seq:evidenceSequenceSchema}).strict(),z8.object({kind:z8.literal("diff"),path:artifactPathSchema}).strict(),z8.object({kind:z8.literal("artifact"),artifact:artifactPathSchema.describe("Path relative to the session attempt directory, for example session/events.ndjson."),attempt:z8.number().int().positive().optional().describe("Must match the analysis attempt; defaults to that attempt."),line:z8.number().int().positive().optional().describe("One-based line number in the original artifact, before any filtering."),endLine:z8.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,issueId:true}).extend({label:z8.string().trim().min(1).max(200),detail:z8.string().trim().min(1).max(1e4),subject:z8.string().trim().min(1).max(200),tags:z8.array(z8.string().trim().min(1).max(64)).max(32).default([]),evidence:z8.array(portableEvidenceRefSchema).min(1).max(100)}).strict();var criterionAnalysisSubmissionSchema=z8.object({criterionId:z8.string().min(1),outcome:z8.enum(["PASS","FAIL","UNASSESSABLE"]),label:z8.string().trim().min(1).max(1e4),evidence:z8.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:z8.string().trim().min(1).max(200),evidence:z8.record(z8.string(),z8.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=z8.object({schemaVersion:z8.literal(ANALYSIS_SCHEMA_VERSION),attempt:z8.number().int().positive().default(1),instructionsVersion:z8.string().trim().min(1),analyst:z8.object({name:z8.string().trim().min(1),model:z8.string().trim().min(1).optional()}).strict(),assessability:sessionAnalysisSchema.shape.assessability,limitation:z8.string().trim().min(1).nullable().default(null),selection:sessionAnalysisSchema.shape.selection.default("NOT_MEASURED"),directed:z8.boolean().default(false),findings:z8.array(findingSubmissionSchema).max(1e3).default([]),products:z8.array(productSubmissionSchema).max(1e3).default([]),criteria:z8.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=z9.enum(RUN_STATUSES);var AGENTS=["CLAUDE_CODE","CODEX_CLI","CURSOR","PI","OPENCODE","ANTIGRAVITY"];var agentSchema=z9.enum(AGENTS);var OBSERVED_PROVIDER_SOURCES=["AGENT_STREAM","GATEWAY_RESPONSE","GATEWAY_AUDIT","CANARY"];var observedProviderSourceSchema=z9.enum(OBSERVED_PROVIDER_SOURCES);var selectedProviderSchema=z9.object({slug:z9.string(),displayName:z9.string()});var observedProviderSchema=z9.object({slug:z9.string(),source:observedProviderSourceSchema});var RUN_TRIGGER_SOURCES=["UNKNOWN","UI","API","CADENCE","STAFF","OPERATOR","GITHUB"];var runTriggerSourceSchema=z9.enum(RUN_TRIGGER_SOURCES);var runTriggeredBySchema=z9.object({source:runTriggerSourceSchema,userId:z9.string().nullable(),email:z9.string().nullable()});var runOptimizationTrialSchema=z9.object({optimizationId:z9.string(),trialId:z9.string(),key:z9.string(),title:z9.string(),kind:z9.enum(INTERVENTION_KINDS)});var runCreditsChargedSchema=z9.number().int().nullable();var runStatusFilterSchema=z9.string().transform(raw=>raw.split(",").map(s=>s.trim().toUpperCase()).filter(Boolean)).pipe(z9.array(runStatusSchema).min(1));var runListQuerySchema=listQuerySchema.extend({status:runStatusFilterSchema.optional(),batch:z9.string().optional(),prompt:z9.string().optional(),experiment:z9.string().optional(),evalSet:z9.string().optional(),since:z9.string().optional()});var runListItemSchema=z9.object({id:z9.string(),status:runStatusSchema,agent:agentSchema,model:z9.string(),resolvedModel:z9.string().nullable().optional(),modelDisplayName:z9.string().nullable().optional(),selectedProvider:selectedProviderSchema.nullable().optional(),observedProvider:observedProviderSchema.nullable().optional(),promptId:z9.string(),promptSnippet:z9.string(),batchId:z9.string(),experiment:z9.string().nullable(),evalSetId:z9.string().nullable(),evalRevision:z9.string().optional(),optimizationTrial:runOptimizationTrialSchema.nullable().optional(),turns:z9.number().int().nullable(),usdCost:z9.number().nullable(),creditsCharged:runCreditsChargedSchema.optional(),triggeredBy:runTriggeredBySchema.optional(),durationMs:z9.number().int().nullable(),exitReason:z9.string().nullable(),createdAt:z9.string(),startedAt:z9.string().nullable(),finishedAt:z9.string().nullable(),parentRunId:z9.string().nullable(),fetchForkPlanId:z9.string().nullable()});var runListResponseSchema=listResponseSchema(runListItemSchema);var runSkillSchema=z9.discriminatedUnion("source",[z9.object({source:z9.literal("saved"),skillId:z9.string(),name:z9.string(),label:z9.string()}),z9.object({source:z9.literal("input"),name:z9.string(),commit:z9.string().nullable(),pullNumber:z9.number().int().nullable()})]);var runDetailSchema=runListItemSchema.omit({promptSnippet:true}).extend({promptText:z9.string(),attempt:z9.number().int(),cancelRequested:z9.boolean(),failureReason:z9.string().nullable(),repoUrl:z9.string().nullable(),repoRef:z9.string().nullable(),scenario:z9.string(),funding:z9.string(),usage:z9.unknown().nullable(),hasDiff:z9.boolean(),claimedAt:z9.string().nullable(),criterionResults:z9.array(z9.object({criterionId:z9.string().nullable(),name:z9.string(),passed:z9.boolean().nullable(),reasoning:z9.string().nullable()})),skills:z9.array(runSkillSchema).optional(),recorded:z9.boolean().optional(),forkedFrom:z9.object({runId:z9.string(),beforeSeq:z9.number().int().nullable(),message:z9.boolean().optional(),mock:z9.object({id:z9.string(),url:z9.string(),summary:z9.string().nullable()}).optional()}).nullable().optional()});var cancelRunResponseSchema=z9.object({id:z9.string(),status:runStatusSchema,cancelRequested:z9.boolean(),note:z9.string().optional()});var regradeRunResponseSchema=z9.object({runId:z9.string(),evalSetId:z9.string().nullable(),criteria:z9.number().int()});var RUN_INSIGHT_STATUSES=["PENDING","RUNNING","COMPLETE","FAILED","SKIPPED"];var runInsightStatusSchema=z9.enum(RUN_INSIGHT_STATUSES);var insightPassSchema=z9.object({status:runInsightStatusSchema,model:z9.string().nullable(),inputTokens:z9.number().int().nullable(),outputTokens:z9.number().int().nullable(),usdCost:z9.number().nullable(),error:z9.string().nullable()});var runDecisionSchema=z9.object({index:z9.number().int(),category:z9.string(),categoryRaw:z9.string().nullable(),chosenName:z9.string(),chosenEcosystem:z9.string().nullable(),chosenPackage:z9.string().nullable(),reversed:z9.boolean(),detail:z9.unknown()});var RUN_INSIGHT_PASS_KINDS=["ANALYSIS","CLI_DISCOVERY","LEVER","EXPERIMENT_DELTA"];var runInsightPassKindSchema=z9.enum(RUN_INSIGHT_PASS_KINDS);var insightPipelinePassSchema=insightPassSchema.extend({kind:runInsightPassKindSchema});var runInsightResponseSchema=z9.object({runId:z9.string(),decision:insightPassSchema,passes:z9.array(insightPipelinePassSchema),decisions:z9.array(runDecisionSchema),experimentDelta:z9.unknown().nullable(),visibilityVerdict:z9.unknown().nullable(),analysis:sessionAnalysisSchema.nullable()});var runEventSchema=z9.looseObject({run_id:z9.string(),seq:z9.number(),turn:z9.number(),ts:z9.string(),type:z9.string()});var runCompareSideSchema=z9.object({runRequest:z9.string().min(1).optional(),batch:z9.array(z9.string().min(1)).min(1).max(100).optional(),evalSet:z9.string().min(1).optional(),evalRevision:z9.string().min(1).optional(),trial:z9.string().min(1).optional(),experiment:z9.string().min(1).optional(),agent:z9.array(agentSchema).min(1).optional(),model:z9.array(z9.string()).min(1).optional(),since:z9.string().optional(),until:z9.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=z9.object({baseline:runCompareSideSchema,candidate:runCompareSideSchema}).strict();var runCompareStatsSchema=z9.object({runs:z9.number().int(),finished:z9.number().int(),succeeded:z9.number().int(),judged:z9.number().int(),passed:z9.number().int(),passRate:z9.number().nullable(),medianTurns:z9.number().nullable(),medianUsdCost:z9.number().nullable(),medianDurationMs:z9.number().nullable(),criteria:z9.array(z9.object({name:z9.string(),judged:z9.number().int(),passed:z9.number().int(),passRate:z9.number().nullable()}))});var runCompareDeltaSchema=z9.object({passRate:z9.number().nullable(),medianTurns:z9.number().nullable(),medianUsdCost:z9.number().nullable(),medianDurationMs:z9.number().nullable(),criteria:z9.array(z9.object({name:z9.string(),passRate:z9.number().nullable()}))});var runCompareRowSchema=z9.object({baseline:runCompareStatsSchema,candidate:runCompareStatsSchema,delta:runCompareDeltaSchema});var runCompareMixedRevisionSchema=z9.object({evalSetId:z9.string().nullable(),promptId:z9.string().nullable(),revisions:z9.array(z9.string())});var runCompareTrialSchema=runOptimizationTrialSchema.extend({runs:z9.number().int()});var runCompareResponseSchema=z9.object({overall:runCompareRowSchema,targets:z9.array(runCompareRowSchema.extend({agent:agentSchema,model:z9.string()})),sides:z9.object({baseline:z9.object({evalRevisions:z9.array(z9.string()),mixedRevisions:z9.array(runCompareMixedRevisionSchema).optional(),truncated:z9.boolean(),trials:z9.array(runCompareTrialSchema).optional()}),candidate:z9.object({evalRevisions:z9.array(z9.string()),mixedRevisions:z9.array(runCompareMixedRevisionSchema).optional(),truncated:z9.boolean(),trials:z9.array(runCompareTrialSchema).optional()})})});var SCHEDULABLE_AGENTS=["CLAUDE_CODE","CODEX_CLI","PI","OPENCODE"];var schedulableAgentSchema=z10.enum(SCHEDULABLE_AGENTS);var ROSTERABLE_AGENTS=[...SCHEDULABLE_AGENTS,"ANTIGRAVITY"];var rosterableAgentSchema=z10.enum(ROSTERABLE_AGENTS);var agentConfigSchema=z10.object({agent:agentSchema,models:z10.array(z10.string().min(1))});var agentConfigInputSchema=z10.object({agent:rosterableAgentSchema,models:z10.array(z10.string().min(1)).default([])});var assetRefSchema=z10.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=z10.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,signal){return this.request("GET",path,{query,signal})}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),signal:options.signal});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-52KLEIVN.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,DEFAULT_LIFECYCLE_TIMEOUT_SECONDS,MAX_LIFECYCLE_TIMEOUT_SECONDS,MAX_LIFECYCLE_SOURCE_LENGTH,lifecycleSchema,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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{credentialKind,fetchDirectory,isUuid,keyOrganization,legacySelection,resolveSelection}from"./chunk-AZKXHO6C.js";import{ApiClient,CliError,codeForStatus,resolveAuthUrl,resolveToken,retryAfterSeconds,storedSharedCredentials}from"./chunk-PMX3NOGH.js";import{readConfig}from"./chunk-OIGVDK3F.js";import{existsSync,readFileSync}from"fs";import{dirname,join,resolve}from"path";function findWorkspace(cwd=process.cwd()){let directory=resolve(cwd);while(true){if(existsSync(join(directory,"gauge.json"))||existsSync(join(directory,".gauge","config.json")))return directory;const parent=dirname(directory);if(parent===directory)return void 0;directory=parent}}function gaugeState(command,cwd=process.cwd()){return readGaugeState(command.optsWithGlobals(),cwd)}function backend(value,location){if(value===void 0)return void 0;if(value==="local"||value==="hosted")return value;throw new CliError("usage",`Invalid backend in ${location}: expected local or hosted`)}function readGaugeState(flags,cwd=process.cwd(),account={signedIn:resolveToken()!==null,...readConfig()}){const root=findWorkspace(cwd);let config;let workspaceBackend;if(root){if(!existsSync(join(root,"gauge.json")))config={};else try{const parsed=JSON.parse(readFileSync(join(root,"gauge.json"),"utf8"));config=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}catch{config=null}if(config&&"mode"in config)throw new CliError("usage","gauge.json does not accept mode. Set backend in private .gauge/config.json; keep the project manifest backend-independent.");const path=join(root,".gauge","config.json");if(existsSync(path)){let value;try{value=JSON.parse(readFileSync(path,"utf8"))}catch{throw new CliError("usage",`${path} is not valid JSON`)}if(!value||value.version!==1)throw new CliError("usage",`Unsupported workspace configuration version in ${path}`);workspaceBackend=backend(value.backend,path)}}const userBackend=backend(account.backend,"user configuration");const[mode,source]=flags.local?["local","flag"]:flags.hosted?["hosted","flag"]:workspaceBackend?[workspaceBackend,"workspace"]:userBackend?[userBackend,"user"]:["local","default"];return{mode,source,root,inRepo:root!==void 0,config,signedIn:account.signedIn,orgId:account.orgId}}function instructionMode(state){const why={flag:"from the flag",workspace:"from .gauge/config.json",user:"from user configuration",default:"the default"};return{mode:state.mode,why:why[state.source]}}function header(state,topic,brief=false){const{mode,why}=instructionMode(state);const lines=[`Mode: ${mode} (${why}). Pass --${mode==="local"?"hosted":"local"} to switch for this command.`];if(mode==="local"&&topic&&!topic.local&&!topic.shared)lines.push("This topic is hosted only. Local guidance: `gauge instructions --local`.");if(state.config===null)lines.push("gauge.json is not valid JSON. Fix it before using this workspace.");else if(!state.root&&!brief)lines.push("Run `gauge init` to initialize this directory. It writes only private .gauge/ state. Add --cases to also write shared gauge.json, gauge-cases/, and an AGENTS.md block.");else if(!brief&&(!topic||topic.key==="root"))lines.push("Next: `gauge instructions eval` or `gauge instructions preference` to create a saved measurement; `gauge instructions run` to launch it.");return lines}function selectedOrg(command,fileOrg){const{org}=command.optsWithGlobals();if(org)return{value:org,source:"flag"};if(fileOrg)return{value:fileOrg,source:"file"};const project=gaugeState(command).config;if(typeof project?.orgId==="string"&&project.orgId){if(!isUuid(project.orgId))throw new CliError("usage","The organization saved in gauge.json is not valid.",{hint:"Run `gauge orgs`, then `gauge orgs use <slug> --project` to choose this project's organization."});return{value:project.orgId,source:"project"}}if(project?.org)legacySelection("project");const{orgId,defaultOrg}=readConfig();if(orgId){if(!isUuid(orgId))throw new CliError("usage","Your saved organization is not valid.",{hint:"Run `gauge orgs`, then `gauge orgs use <slug>` to choose your organization."});return{value:orgId,source:"config"}}if(defaultOrg)legacySelection("config");return void 0}var NO_ORG_MESSAGE="No organization selected. Pass --org <org> or set a default with `gauge orgs use <org>`.";async function resolveOrg(command,fileOrg){const selection=selectedOrg(command,fileOrg);if(!selection)throw new CliError("usage",NO_ORG_MESSAGE,{needsAccount:true});return(await resolveSelection(selection.value,selection.source)).id}function resolveOutput(command){const{output}=command.optsWithGlobals();return output==="json"?"json":"table"}function requireHosted(command,{account=false,hint}={}){const{mode,source}=gaugeState(command);if(mode==="local"&&(source==="flag"||!account))throw new CliError("usage","This command needs hosted Gauge.",{needsAccount:true,hint})}function hostedOnly(command,options={}){return command.hook("preAction",(_command,action)=>requireHosted(action,options))}var OUTPUT_FORMATS=["table","json"];function colorEnabled(stream){if(process.env.FORCE_COLOR)return process.env.FORCE_COLOR!=="0";return stream.isTTY===true&&!process.env.NO_COLOR&&process.env.TERM!=="dumb"}function style(code,stream=process.stdout){const on=colorEnabled(stream);return text=>on?`\x1B[${code}m${text}\x1B[0m`:text}function printJson(value){console.log(JSON.stringify(value,null,2))}function printItems(items,format,columns){if(format==="json"){printJson(items);return}if(items.length===0){console.log("(no results)");return}const cols=columns??Object.keys(items[0]).map(key=>({key}));const headers=cols.map(col=>col.header??col.key);const rows=items.map(item=>cols.map(col=>cell(item[col.key])));const widths=headers.map((header2,i)=>Math.max(header2.length,...rows.map(row=>row[i].length)));const line=values=>values.map((value,i)=>value.padEnd(widths[i])).join(" ").trimEnd();console.log(line(headers));for(const row of rows)console.log(line(row))}function cell(value){if(value===null||value===void 0||value==="")return"\u2014";if(value instanceof Date)return value.toISOString();if(typeof value==="object")return JSON.stringify(value);return String(value)}var CHAT_API_PREFIX="/api/v1";var CHAT_BATCH_SIZE=500;var INVALID_CODES=new Set(["invalid_request","invalid_query","invalid_id","invalid_cursor","range_too_large"]);function exitFamily(status,code){if(code==="limit_exceeded")return"insufficient_credits";if(status===400||status===422||INVALID_CODES.has(code))return"invalid_request";if(code==="rate_limited")return"rate_limited";return codeForStatus(status)}function isChatErrorBody(value){const error=value?.error;return typeof error==="object"&&error!==null&&typeof error.code==="string"&&typeof error.message==="string"}function loginHint(){return process.env.GAUGE_API_TOKEN?.trim()?"Replace GAUGE_API_TOKEN with a valid key, or unset it and run `gauge auth login`.":"Run `gauge auth login`, or set GAUGE_API_TOKEN to an org API key (Settings \u2192 API Keys)."}function hintFor(code,field,extra,retryAfter){switch(code){case"forbidden":return field==="explain"?"--explain (or `explain` in --json) is only available to Gauge staff; rerun without it.":void 0;case"unauthorized":return loginHint();case"insufficient_scope":return extra.requiredScope&&extra.requiredScope!=="write"?`Ask an organization admin for '${String(extra.requiredScope)}' permission.`:"Ask an organization admin for write access, or create a Read & write API key in Settings \u2192 API Keys.";case"limit_exceeded":return typeof extra.remaining==="number"?`Your plan allows ${extra.remaining} more prompt(s); nothing was created.`:"Nothing was created.";case"rate_limited":return retryAfter===void 0?"Retry shortly.":`Retry in ${retryAfter} s.`;case"product_not_enabled":return"Run `gauge orgs` to see which products each organization uses.";default:return void 0}}function describeScopes(scopes){if(scopes.includes("write"))return"read & write";if(scopes.length===1&&scopes[0]==="read")return"read-only";return scopes.length?scopes.join(", "):"no permissions"}var ChatApiClient=class extends ApiClient{describingScope=false;orgName;async me(){try{return await this.get(chatPath("me"))}catch(error){if(!(error instanceof CliError)||error.code!=="not_found")throw error;throw new CliError("not_found","This Gauge server cannot show your account details yet.",{hint:"Run `gauge orgs` to check your access. If you use a custom Gauge server, ask its administrator to update it."})}}async scopeHint(required){if(this.describingScope)return void 0;this.describingScope=true;try{const{token}=await this.me();const needs=String(required??"write");const access=token.scopes.length?`${describeScopes(token.scopes)} access`:"no permissions";if(token.kind==="api_key")return`This API key has ${access}.${needs==="write"?" Create a Read & write key in Settings \u2192 API Keys, then update GAUGE_API_TOKEN or import it with `gauge auth login --with-token`.":` Use a key with '${needs}' permission.`}`;if(token.kind==="session")return`Your login has ${access}. Ask an organization admin for ${needs==="write"?"write access":`'${needs}' permission`}.`;return void 0}catch{return void 0}finally{this.describingScope=false}}constructor(options={}){super({...options,baseUrl:options.baseUrl??storedSharedCredentials()?.authUrl??resolveAuthUrl()})}headers(extra){if(!this.signedIn)throw new CliError("unauthorized","Not logged in to Gauge.",{hint:loginHint()});return super.headers(extra)}async toError(res){let body;try{body=await res.clone().json()}catch{}if(!isChatErrorBody(body)){if(res.status===404)return unknownEndpoint(res);return super.toError(res)}const{code,message,field,...extra}=body.error;const retryAfter=typeof extra.retryAfter==="number"?extra.retryAfter:res.status===429?retryAfterSeconds(res):void 0;const details={status:res.status,...field?{field}:{},...extra,...retryAfter!==void 0?{retryAfter}:{}};if(code==="product_not_enabled"&&this.orgName)return new CliError(exitFamily(res.status,code),`${this.orgName} doesn't use Gauge Chat.`,{apiCode:code,details,hint:hintFor(code,field,extra,retryAfter)});return new CliError(exitFamily(res.status,code),`${code==="insufficient_scope"?"You don't have the permissions needed for this command.":message}${field?` (field: ${field})`:""}`,{apiCode:code,details,hint:(code==="insufficient_scope"?await this.scopeHint(extra.requiredScope):void 0)??hintFor(code,field,extra,retryAfter)})}};function unknownEndpoint(res){const url=res.url?new URL(res.url):void 0;return new CliError("not_found",`This Gauge server${url?` (${url.host})`:""} does not support this command at the requested address.`,{details:{status:404,...url?{path:url.pathname}:{}},hint:"Check GAUGE_AUTH_URL or `gauge config get authUrl` if you use a custom server. Otherwise, contact Gauge support."})}function createChatApiClient(options={}){return new ChatApiClient(options)}function chatPath(...segments){return`${CHAT_API_PREFIX}/${segments.map(encodeURIComponent).join("/")}`}async function resolveChatOrg(command){const{org}=command.optsWithGlobals();const isKey=credentialKind()==="api_key";const selection=isKey?org?{value:org,source:"flag"}:void 0:selectedOrg(command);if(selection){const resolved=await resolveSelection(selection.value,selection.source);return{id:resolved.id,name:resolved.name,source:selection.source}}if(isKey){const keyOrg=await keyOrganization();return{id:keyOrg.id,name:keyOrg.name,source:"key"}}const chatOrgs=(await fetchDirectory()).filter(o=>o.products?.chat!==false);if(chatOrgs.length===1)return{id:chatOrgs[0].id,name:chatOrgs[0].name,source:"only"};throw new CliError("usage",chatOrgs.length===0?"You are not a member of any organization with Gauge Chat.":`Several organizations have Gauge Chat (${chatOrgs.map(o=>o.slug).join(", ")}). Pass --org <org> or run \`gauge orgs use <org>\`.`)}async function resolveChatCategory(command,client,org){const{category}=command.optsWithGlobals();if(category)return category;const{chatCategory,chatCategoryOrg}=readConfig();if(chatCategory&&(chatCategoryOrg?chatCategoryOrg===org.id:org.source==="config"))return chatCategory;const{data}=await client.get(chatPath("orgs",org.id,"categories"));if(data.length===1)return data[0].slug;const label=org.name??org.id;throw new CliError("usage",data.length===0?`Organization ${label} has no categories.`:`Organization ${label} has several categories (${data.map(c=>c.slug).join(", ")}). Pass --category <slug> or run \`gauge chat categories use <slug>\`.`)}async function chatScope(command){const client=createChatApiClient();const chatOrg=await resolveChatOrg(command);client.orgName=chatOrg.name??chatOrg.id;return{client,org:chatOrg.id,chatOrg}}async function categoryScope(command){const scope=await chatScope(command);const category=await resolveChatCategory(command,scope.client,scope.chatOrg);return{...scope,category,base:["orgs",scope.org,"categories",category]}}var DEFAULT_MAX_ITEMS=5e3;function parsePositive(raw,flag,max){if(raw===void 0)return void 0;const value=Number(raw);if(!Number.isInteger(value)||value<1||max&&value>max)throw new CliError("usage",`${flag} must be an integer${max?` between 1 and ${max}`:" of at least 1"}`);return value}async function fetchPages(client,path,query,options,maxLimit=200){const limit=parsePositive(options.limit,"--limit",maxLimit);if(!options.all)return client.get(path,{...query,limit,cursor:options.cursor});const max=parsePositive(options.max,"--max")??DEFAULT_MAX_ITEMS;const data=[];let cursor=options.cursor;do{const page=await client.get(path,{...query,limit:Math.min(limit??maxLimit,max-data.length),cursor});data.push(...page.data);cursor=page.nextCursor??void 0}while(cursor&&data.length<max);return{data,nextCursor:cursor??null}}async function fetchAll(client,path,query={}){return(await fetchPages(client,path,query,{all:true})).data}function printPage(page,output,row){if(output==="json"){printJson({data:page.data,nextCursor:page.nextCursor??null});return}printItems(page.data.map(row),"table");if(page.nextCursor)console.error(`(more results \u2014 rerun with --cursor ${page.nextCursor}, or pass --all)`)}function addPageOptions(command,maxLimit=200){return command.option("--limit <n>",`page size (1-${maxLimit})`).option("--cursor <cursor>","resume from a previous page's nextCursor").option("--all","follow nextCursor through every page").option("--max <n>",`with --all, stop after this many items (default ${DEFAULT_MAX_ITEMS})`)}function chunks(items,size=CHAT_BATCH_SIZE){const out=[];for(let i=0;i<items.length;i+=size)out.push(items.slice(i,i+size));return out}var csv=raw=>raw.split(",").map(s=>s.trim()).filter(Boolean);function truncate(text,length=80){const flat=text.replace(/\s+/g," ").trim();return flat.length>length?`${flat.slice(0,length-1)}\u2026`:flat}var lower=s=>s.trim().toLowerCase();async function resolveTopicId(scope,value){if(value.startsWith("top_"))return value;const topics=await fetchAll(scope.client,chatPath(...scope.base,"topics"));const match=topics.filter(t=>t.slug===value||lower(t.title)===lower(value));if(match.length===1)return match[0].id;throw new CliError("not_found",match.length?`Topic "${value}" is ambiguous; pass its id (${match.map(t=>t.id).join(", ")}).`:`Topic "${value}" not found in category ${scope.category}.`,{hint:"Run `gauge chat topics list`, or create it with `gauge chat topics create`."})}async function resolveTagIds(scope,values){if(values.every(v=>v.startsWith("tag_")))return values;const tags=await fetchAll(scope.client,chatPath("orgs",scope.org,"tags"));return values.map(value=>{if(value.startsWith("tag_"))return value;const match=tags.filter(t=>lower(t.name)===lower(value));if(match.length===1)return match[0].id;throw new CliError("not_found",match.length?`Tag "${value}" is ambiguous; pass its id (${match.map(t=>t.id).join(", ")}).`:`Tag "${value}" not found.`,{hint:"Run `gauge chat tags list`, or create it with `gauge chat tags create`."})})}function withCategory(command){return command.option("--category <category>","category slug or cat_ id (default: chatCategory config, else the org's only category)")}export{findWorkspace,gaugeState,readGaugeState,instructionMode,header,selectedOrg,resolveOrg,resolveOutput,requireHosted,hostedOnly,OUTPUT_FORMATS,style,printJson,printItems,CHAT_API_PREFIX,CHAT_BATCH_SIZE,describeScopes,ChatApiClient,createChatApiClient,chatPath,resolveChatOrg,resolveChatCategory,chatScope,categoryScope,DEFAULT_MAX_ITEMS,parsePositive,fetchPages,fetchAll,printPage,addPageOptions,chunks,csv,truncate,resolveTopicId,resolveTagIds,withCategory};
|
|
1
|
+
import{credentialKind,fetchDirectory,isUuid,keyOrganization,legacySelection,resolveSelection}from"./chunk-ZXRPUGCO.js";import{ApiClient,CliError,codeForStatus,resolveAuthUrl,resolveToken,retryAfterSeconds,storedSharedCredentials}from"./chunk-QJ2UAX2V.js";import{readConfig}from"./chunk-OIGVDK3F.js";import{existsSync,readFileSync}from"fs";import{dirname,join,resolve}from"path";function findWorkspace(cwd=process.cwd()){let directory=resolve(cwd);while(true){if(existsSync(join(directory,"gauge.json"))||existsSync(join(directory,".gauge","config.json")))return directory;const parent=dirname(directory);if(parent===directory)return void 0;directory=parent}}function gaugeState(command,cwd=process.cwd()){return readGaugeState(command.optsWithGlobals(),cwd)}function backend(value,location){if(value===void 0)return void 0;if(value==="local"||value==="hosted")return value;throw new CliError("usage",`Invalid backend in ${location}: expected local or hosted`)}function readGaugeState(flags,cwd=process.cwd(),account={signedIn:resolveToken()!==null,...readConfig()}){const root=findWorkspace(cwd);let config;let workspaceBackend;if(root){if(!existsSync(join(root,"gauge.json")))config={};else try{const parsed=JSON.parse(readFileSync(join(root,"gauge.json"),"utf8"));config=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}catch{config=null}if(config&&"mode"in config)throw new CliError("usage","gauge.json does not accept mode. Set backend in private .gauge/config.json; keep the project manifest backend-independent.");const path=join(root,".gauge","config.json");if(existsSync(path)){let value;try{value=JSON.parse(readFileSync(path,"utf8"))}catch{throw new CliError("usage",`${path} is not valid JSON`)}if(!value||value.version!==1)throw new CliError("usage",`Unsupported workspace configuration version in ${path}`);workspaceBackend=backend(value.backend,path)}}const userBackend=backend(account.backend,"user configuration");const[mode,source]=flags.local?["local","flag"]:flags.hosted?["hosted","flag"]:workspaceBackend?[workspaceBackend,"workspace"]:userBackend?[userBackend,"user"]:["local","default"];return{mode,source,root,inRepo:root!==void 0,config,signedIn:account.signedIn,orgId:account.orgId}}function instructionMode(state){const why={flag:"from the flag",workspace:"from .gauge/config.json",user:"from user configuration",default:"the default"};return{mode:state.mode,why:why[state.source]}}function header(state,topic,brief=false){const{mode,why}=instructionMode(state);const lines=[`Mode: ${mode} (${why}). Pass --${mode==="local"?"hosted":"local"} to switch for this command.`];if(mode==="local"&&topic&&!topic.local&&!topic.shared)lines.push("This topic is hosted only. Local guidance: `gauge instructions --local`.");if(state.config===null)lines.push("gauge.json is not valid JSON. Fix it before using this workspace.");else if(!state.root&&!brief)lines.push("Run `gauge init` to initialize this directory. It writes only private .gauge/ state. Add --cases to also write shared gauge.json, gauge-cases/, and an AGENTS.md block.");else if(!brief&&(!topic||topic.key==="root"))lines.push("Next: `gauge instructions eval` or `gauge instructions preference` to create a saved measurement; `gauge instructions run` to launch it.");return lines}function selectedOrg(command,fileOrg){const{org}=command.optsWithGlobals();if(org)return{value:org,source:"flag"};if(fileOrg)return{value:fileOrg,source:"file"};const project=gaugeState(command).config;if(typeof project?.orgId==="string"&&project.orgId){if(!isUuid(project.orgId))throw new CliError("usage","The organization saved in gauge.json is not valid.",{hint:"Run `gauge orgs`, then `gauge orgs use <slug> --project` to choose this project's organization."});return{value:project.orgId,source:"project"}}if(project?.org)legacySelection("project");const{orgId,defaultOrg}=readConfig();if(orgId){if(!isUuid(orgId))throw new CliError("usage","Your saved organization is not valid.",{hint:"Run `gauge orgs`, then `gauge orgs use <slug>` to choose your organization."});return{value:orgId,source:"config"}}if(defaultOrg)legacySelection("config");return void 0}var NO_ORG_MESSAGE="No organization selected. Pass --org <org> or set a default with `gauge orgs use <org>`.";async function resolveOrg(command,fileOrg){const selection=selectedOrg(command,fileOrg);if(!selection)throw new CliError("usage",NO_ORG_MESSAGE,{needsAccount:true});return(await resolveSelection(selection.value,selection.source)).id}function resolveOutput(command){const{output}=command.optsWithGlobals();return output==="json"?"json":"table"}function requireHosted(command,{account=false,hint}={}){const{mode,source}=gaugeState(command);if(mode==="local"&&(source==="flag"||!account))throw new CliError("usage","This command needs hosted Gauge.",{needsAccount:true,hint})}function hostedOnly(command,options={}){return command.hook("preAction",(_command,action)=>requireHosted(action,options))}var OUTPUT_FORMATS=["table","json"];function colorEnabled(stream){if(process.env.FORCE_COLOR)return process.env.FORCE_COLOR!=="0";return stream.isTTY===true&&!process.env.NO_COLOR&&process.env.TERM!=="dumb"}function style(code,stream=process.stdout){const on=colorEnabled(stream);return text=>on?`\x1B[${code}m${text}\x1B[0m`:text}function printJson(value){console.log(JSON.stringify(value,null,2))}function printItems(items,format,columns){if(format==="json"){printJson(items);return}if(items.length===0){console.log("(no results)");return}const cols=columns??Object.keys(items[0]).map(key=>({key}));const headers=cols.map(col=>col.header??col.key);const rows=items.map(item=>cols.map(col=>cell(item[col.key])));const widths=headers.map((header2,i)=>Math.max(header2.length,...rows.map(row=>row[i].length)));const line=values=>values.map((value,i)=>value.padEnd(widths[i])).join(" ").trimEnd();console.log(line(headers));for(const row of rows)console.log(line(row))}function cell(value){if(value===null||value===void 0||value==="")return"\u2014";if(value instanceof Date)return value.toISOString();if(typeof value==="object")return JSON.stringify(value);return String(value)}var CHAT_API_PREFIX="/api/v1";var CHAT_BATCH_SIZE=500;var INVALID_CODES=new Set(["invalid_request","invalid_query","invalid_id","invalid_cursor","range_too_large"]);function exitFamily(status,code){if(code==="limit_exceeded")return"insufficient_credits";if(status===400||status===422||INVALID_CODES.has(code))return"invalid_request";if(code==="rate_limited")return"rate_limited";return codeForStatus(status)}function isChatErrorBody(value){const error=value?.error;return typeof error==="object"&&error!==null&&typeof error.code==="string"&&typeof error.message==="string"}function loginHint(){return process.env.GAUGE_API_TOKEN?.trim()?"Replace GAUGE_API_TOKEN with a valid key, or unset it and run `gauge auth login`.":"Run `gauge auth login`, or set GAUGE_API_TOKEN to an org API key (Settings \u2192 API Keys)."}function hintFor(code,field,extra,retryAfter){switch(code){case"forbidden":return field==="explain"?"--explain (or `explain` in --json) is only available to Gauge staff; rerun without it.":void 0;case"unauthorized":return loginHint();case"insufficient_scope":return extra.requiredScope&&extra.requiredScope!=="write"?`Ask an organization admin for '${String(extra.requiredScope)}' permission.`:"Ask an organization admin for write access, or create a Read & write API key in Settings \u2192 API Keys.";case"limit_exceeded":return typeof extra.remaining==="number"?`Your plan allows ${extra.remaining} more prompt(s); nothing was created.`:"Nothing was created.";case"rate_limited":return retryAfter===void 0?"Retry shortly.":`Retry in ${retryAfter} s.`;case"product_not_enabled":return"Run `gauge orgs` to see which products each organization uses.";default:return void 0}}function describeScopes(scopes){if(scopes.includes("write"))return"read & write";if(scopes.length===1&&scopes[0]==="read")return"read-only";return scopes.length?scopes.join(", "):"no permissions"}var ChatApiClient=class extends ApiClient{describingScope=false;orgName;async me(){try{return await this.get(chatPath("me"))}catch(error){if(!(error instanceof CliError)||error.code!=="not_found")throw error;throw new CliError("not_found","This Gauge server cannot show your account details yet.",{hint:"Run `gauge orgs` to check your access. If you use a custom Gauge server, ask its administrator to update it."})}}async scopeHint(required){if(this.describingScope)return void 0;this.describingScope=true;try{const{token}=await this.me();const needs=String(required??"write");const access=token.scopes.length?`${describeScopes(token.scopes)} access`:"no permissions";if(token.kind==="api_key")return`This API key has ${access}.${needs==="write"?" Create a Read & write key in Settings \u2192 API Keys, then update GAUGE_API_TOKEN or import it with `gauge auth login --with-token`.":` Use a key with '${needs}' permission.`}`;if(token.kind==="session")return`Your login has ${access}. Ask an organization admin for ${needs==="write"?"write access":`'${needs}' permission`}.`;return void 0}catch{return void 0}finally{this.describingScope=false}}constructor(options={}){super({...options,baseUrl:options.baseUrl??storedSharedCredentials()?.authUrl??resolveAuthUrl()})}headers(extra){if(!this.signedIn)throw new CliError("unauthorized","Not logged in to Gauge.",{hint:loginHint()});return super.headers(extra)}async toError(res){let body;try{body=await res.clone().json()}catch{}if(!isChatErrorBody(body)){if(res.status===404)return unknownEndpoint(res);return super.toError(res)}const{code,message,field,...extra}=body.error;const retryAfter=typeof extra.retryAfter==="number"?extra.retryAfter:res.status===429?retryAfterSeconds(res):void 0;const details={status:res.status,...field?{field}:{},...extra,...retryAfter!==void 0?{retryAfter}:{}};if(code==="product_not_enabled"&&this.orgName)return new CliError(exitFamily(res.status,code),`${this.orgName} doesn't use Gauge Chat.`,{apiCode:code,details,hint:hintFor(code,field,extra,retryAfter)});return new CliError(exitFamily(res.status,code),`${code==="insufficient_scope"?"You don't have the permissions needed for this command.":message}${field?` (field: ${field})`:""}`,{apiCode:code,details,hint:(code==="insufficient_scope"?await this.scopeHint(extra.requiredScope):void 0)??hintFor(code,field,extra,retryAfter)})}};function unknownEndpoint(res){const url=res.url?new URL(res.url):void 0;return new CliError("not_found",`This Gauge server${url?` (${url.host})`:""} does not support this command at the requested address.`,{details:{status:404,...url?{path:url.pathname}:{}},hint:"Check GAUGE_AUTH_URL or `gauge config get authUrl` if you use a custom server. Otherwise, contact Gauge support."})}function createChatApiClient(options={}){return new ChatApiClient(options)}function chatPath(...segments){return`${CHAT_API_PREFIX}/${segments.map(encodeURIComponent).join("/")}`}async function resolveChatOrg(command){const{org}=command.optsWithGlobals();const isKey=credentialKind()==="api_key";const selection=isKey?org?{value:org,source:"flag"}:void 0:selectedOrg(command);if(selection){const resolved=await resolveSelection(selection.value,selection.source);return{id:resolved.id,name:resolved.name,source:selection.source}}if(isKey){const keyOrg=await keyOrganization();return{id:keyOrg.id,name:keyOrg.name,source:"key"}}const chatOrgs=(await fetchDirectory()).filter(o=>o.products?.chat!==false);if(chatOrgs.length===1)return{id:chatOrgs[0].id,name:chatOrgs[0].name,source:"only"};throw new CliError("usage",chatOrgs.length===0?"You are not a member of any organization with Gauge Chat.":`Several organizations have Gauge Chat (${chatOrgs.map(o=>o.slug).join(", ")}). Pass --org <org> or run \`gauge orgs use <org>\`.`)}async function resolveChatCategory(command,client,org){const{category}=command.optsWithGlobals();if(category)return category;const{chatCategory,chatCategoryOrg}=readConfig();if(chatCategory&&(chatCategoryOrg?chatCategoryOrg===org.id:org.source==="config"))return chatCategory;const{data}=await client.get(chatPath("orgs",org.id,"categories"));if(data.length===1)return data[0].slug;const label=org.name??org.id;throw new CliError("usage",data.length===0?`Organization ${label} has no categories.`:`Organization ${label} has several categories (${data.map(c=>c.slug).join(", ")}). Pass --category <slug> or run \`gauge chat categories use <slug>\`.`)}async function chatScope(command){const client=createChatApiClient();const chatOrg=await resolveChatOrg(command);client.orgName=chatOrg.name??chatOrg.id;return{client,org:chatOrg.id,chatOrg}}async function categoryScope(command){const scope=await chatScope(command);const category=await resolveChatCategory(command,scope.client,scope.chatOrg);return{...scope,category,base:["orgs",scope.org,"categories",category]}}var DEFAULT_MAX_ITEMS=5e3;function parsePositive(raw,flag,max){if(raw===void 0)return void 0;const value=Number(raw);if(!Number.isInteger(value)||value<1||max&&value>max)throw new CliError("usage",`${flag} must be an integer${max?` between 1 and ${max}`:" of at least 1"}`);return value}async function fetchPages(client,path,query,options,maxLimit=200){const limit=parsePositive(options.limit,"--limit",maxLimit);if(!options.all)return client.get(path,{...query,limit,cursor:options.cursor});const max=parsePositive(options.max,"--max")??DEFAULT_MAX_ITEMS;const data=[];let cursor=options.cursor;do{const page=await client.get(path,{...query,limit:Math.min(limit??maxLimit,max-data.length),cursor});data.push(...page.data);cursor=page.nextCursor??void 0}while(cursor&&data.length<max);return{data,nextCursor:cursor??null}}async function fetchAll(client,path,query={}){return(await fetchPages(client,path,query,{all:true})).data}function printPage(page,output,row){if(output==="json"){printJson({data:page.data,nextCursor:page.nextCursor??null});return}printItems(page.data.map(row),"table");if(page.nextCursor)console.error(`(more results \u2014 rerun with --cursor ${page.nextCursor}, or pass --all)`)}function addPageOptions(command,maxLimit=200){return command.option("--limit <n>",`page size (1-${maxLimit})`).option("--cursor <cursor>","resume from a previous page's nextCursor").option("--all","follow nextCursor through every page").option("--max <n>",`with --all, stop after this many items (default ${DEFAULT_MAX_ITEMS})`)}function chunks(items,size=CHAT_BATCH_SIZE){const out=[];for(let i=0;i<items.length;i+=size)out.push(items.slice(i,i+size));return out}var csv=raw=>raw.split(",").map(s=>s.trim()).filter(Boolean);function truncate(text,length=80){const flat=text.replace(/\s+/g," ").trim();return flat.length>length?`${flat.slice(0,length-1)}\u2026`:flat}var lower=s=>s.trim().toLowerCase();async function resolveTopicId(scope,value){if(value.startsWith("top_"))return value;const topics=await fetchAll(scope.client,chatPath(...scope.base,"topics"));const match=topics.filter(t=>t.slug===value||lower(t.title)===lower(value));if(match.length===1)return match[0].id;throw new CliError("not_found",match.length?`Topic "${value}" is ambiguous; pass its id (${match.map(t=>t.id).join(", ")}).`:`Topic "${value}" not found in category ${scope.category}.`,{hint:"Run `gauge chat topics list`, or create it with `gauge chat topics create`."})}async function resolveTagIds(scope,values){if(values.every(v=>v.startsWith("tag_")))return values;const tags=await fetchAll(scope.client,chatPath("orgs",scope.org,"tags"));return values.map(value=>{if(value.startsWith("tag_"))return value;const match=tags.filter(t=>lower(t.name)===lower(value));if(match.length===1)return match[0].id;throw new CliError("not_found",match.length?`Tag "${value}" is ambiguous; pass its id (${match.map(t=>t.id).join(", ")}).`:`Tag "${value}" not found.`,{hint:"Run `gauge chat tags list`, or create it with `gauge chat tags create`."})})}function withCategory(command){return command.option("--category <category>","category slug or cat_ id (default: chatCategory config, else the org's only category)")}export{findWorkspace,gaugeState,readGaugeState,instructionMode,header,selectedOrg,resolveOrg,resolveOutput,requireHosted,hostedOnly,OUTPUT_FORMATS,style,printJson,printItems,CHAT_API_PREFIX,CHAT_BATCH_SIZE,describeScopes,ChatApiClient,createChatApiClient,chatPath,resolveChatOrg,resolveChatCategory,chatScope,categoryScope,DEFAULT_MAX_ITEMS,parsePositive,fetchPages,fetchAll,printPage,addPageOptions,chunks,csv,truncate,resolveTopicId,resolveTagIds,withCategory};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CliError,createClient,resolveToken}from"./chunk-
|
|
1
|
+
import{CliError,createClient,resolveToken}from"./chunk-QJ2UAX2V.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-G5BMHJOC.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)return org;const{chatPath,createChatApiClient}=await import("./chatApi-G5BMHJOC.js");return createChatApiClient().get(chatPath("orgs",value))}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-G5BMHJOC.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};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{DockerCli,PI_AGENT_DIR,agentEnv,cleanupGateway,harnessCommand,prepareScript,preserveWorkspace,shellQuote,splitModel,validateGateway}from"./chunk-QV7MOO3M.js";import{CliError}from"./chunk-
|
|
1
|
+
import{DockerCli,PI_AGENT_DIR,agentEnv,cleanupGateway,harnessCommand,prepareScript,preserveWorkspace,shellQuote,splitModel,validateGateway}from"./chunk-QV7MOO3M.js";import{CliError}from"./chunk-QJ2UAX2V.js";import{randomUUID}from"crypto";import{chmodSync,existsSync,mkdirSync,readdirSync,readFileSync,statSync}from"fs";import{createRequire}from"module";import{join}from"path";var LOCAL_DATABASE_VERSION=1;var schema=`
|
|
2
2
|
CREATE TABLE measurements (
|
|
3
3
|
id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK(kind IN ('eval','preference')),
|
|
4
4
|
revision INTEGER NOT NULL, definition TEXT NOT NULL,
|