@withgauge/cli 0.22.0 → 0.24.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 +41 -12
- package/dist/batchWorker.js +1 -1
- package/dist/{chunk-CIJ4U33Y.js → chunk-NVAONV7U.js} +5 -5
- package/dist/index.js +22 -19
- package/dist/worker.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -174,7 +174,7 @@ contains the execution preference. Git is optional for workspace initialization.
|
|
|
174
174
|
| `run`, `run list`, `run compare --local`, `models list`, `cleanup`, `feedback` | yes | yes |
|
|
175
175
|
| Binary, website, and MCP inputs | no | yes |
|
|
176
176
|
| Saved eval sets and preference prompts | yes | yes |
|
|
177
|
-
|
|
|
177
|
+
| Project inputs and previews on saved measurement launches | yes | use case files/specs |
|
|
178
178
|
| Findings and summary queries | yes, supported fields | yes |
|
|
179
179
|
| Personas, recurring schedules, PR checks | no | yes |
|
|
180
180
|
| Optimizations (managed docs rewriting) | no | yes |
|
|
@@ -282,9 +282,11 @@ working-tree definitions in either backend, including uncommitted edits. Selecte
|
|
|
282
282
|
filesystem inputs are packaged for local execution or hosted upload; explicit remote
|
|
283
283
|
artifacts retain their declared source. GitHub checks fetch committed definitions.
|
|
284
284
|
Content digests identify the exact bytes separately from Git provenance.
|
|
285
|
-
Preview `inputSnapshots` includes the selected source `path
|
|
286
|
-
`gaugeArchive: { sha256, bytes }
|
|
287
|
-
|
|
285
|
+
Preview `inputSnapshots` includes the selected source `path`,
|
|
286
|
+
`gaugeArchive: { sha256, bytes }`, and the archived `files` (the first 100) with
|
|
287
|
+
`fileCount`. Those values describe Gauge's delivery archive, which contains the
|
|
288
|
+
selected files. `unattachedInputs` names the `gauge.json` inputs that the launch
|
|
289
|
+
leaves out. For npm inputs it contains the `.tgz`; the raw
|
|
288
290
|
tarball has a different hash and size. Each launch takes a fresh snapshot.
|
|
289
291
|
Each case owns its agents, models, consumer repository/ref, Persona and criteria.
|
|
290
292
|
The optional `config.inputs` selects named inputs; all attach by default.
|
|
@@ -478,9 +480,14 @@ it, `run wait` exits 0 once the request settles, whatever the verdict.
|
|
|
478
480
|
Set `GAUGE_API_TOKEN` as a CI secret and replace `my-org` with your workspace slug.
|
|
479
481
|
This can run immediately after your build in the same CI job.
|
|
480
482
|
|
|
481
|
-
Repeat `--input name=path` for each input.
|
|
482
|
-
|
|
483
|
-
|
|
483
|
+
Repeat `--input name=path` for each input. The path replaces the input's
|
|
484
|
+
configured files entirely; only its type and settings carry over. It may be a
|
|
485
|
+
glob, using the same syntax as `gauge.json`; quote it so the shell passes it
|
|
486
|
+
through. Skills accept a directory containing `SKILL.md` or a ZIP/tar.gz archive;
|
|
487
|
+
npm inputs accept a packed `.tgz` or a glob matching exactly one. Files inputs
|
|
488
|
+
accept a directory, a single file, or a glob; archive paths are relative to the
|
|
489
|
+
directory, or to the glob's directory before its first wildcard. Binary inputs
|
|
490
|
+
accept a directory or glob, with `commands` relative to it.
|
|
484
491
|
Use a dedicated build directory: links are rejected, and common credential files
|
|
485
492
|
and `node_modules` are excluded. Each input is limited to 512 MiB and 20,000 files.
|
|
486
493
|
|
|
@@ -498,6 +505,26 @@ JSON is still the only output. Automatic PR checks continue to use configured
|
|
|
498
505
|
sources; disable those checks in Gauge's GitHub settings if CI owns the trigger.
|
|
499
506
|
Save `results.json` as a CI artifact even when the check fails.
|
|
500
507
|
|
|
508
|
+
### Antigravity (hosted)
|
|
509
|
+
|
|
510
|
+
Antigravity is available to organizations enrolled in Antigravity access. Run
|
|
511
|
+
`gauge models list --hosted` to find the available model identifiers, then select
|
|
512
|
+
one with `--agent antigravity:<model>` when creating or launching a saved eval or
|
|
513
|
+
preference prompt. Case files and JSON specs use `agent: ANTIGRAVITY` with the
|
|
514
|
+
model identifier in `models`.
|
|
515
|
+
|
|
516
|
+
Launch with `--hosted`, for example:
|
|
517
|
+
|
|
518
|
+
```sh
|
|
519
|
+
gauge run --eval <id> --agent antigravity:<model> --hosted
|
|
520
|
+
```
|
|
521
|
+
|
|
522
|
+
For case files or a JSON case spec, preview with `gauge run --hosted --dry-run`
|
|
523
|
+
or `gauge run --apply cases.json --hosted --dry-run` before launching.
|
|
524
|
+
Hosted previews contact Gauge and may upload inputs; launches use credits.
|
|
525
|
+
The server checks organization access and model availability. Antigravity cannot
|
|
526
|
+
run locally yet.
|
|
527
|
+
|
|
501
528
|
### Authenticated MCP servers
|
|
502
529
|
|
|
503
530
|
Connect your account in Gauge's MCP setup, completing OAuth in your browser when
|
|
@@ -518,15 +545,15 @@ They are fetched live rather than snapshotted.
|
|
|
518
545
|
Canonical-site preview routing requires hosted execution. Local runs reject
|
|
519
546
|
website inputs, including `--input` overrides, before checking Docker or credentials.
|
|
520
547
|
For local content-only testing, supply docs as a `files` input or put a reachable
|
|
521
|
-
preview URL directly in the prompt. Confirm that the preview contains the edits
|
|
548
|
+
preview URL directly in the prompt. Inputs never include `.gauge/`. Confirm that the preview contains the edits
|
|
522
549
|
and is reachable from the agent's environment; the host's localhost is not
|
|
523
550
|
automatically reachable from a container. These alternatives change exposure and
|
|
524
551
|
do not test discovery of the canonical docs. Static verification validates
|
|
525
552
|
configuration; it does not prove backend support, delivery, or an eval pass.
|
|
526
553
|
|
|
527
554
|
Editor schemas are published at
|
|
528
|
-
`https://agents.withgauge.com/schemas/gauge/v2.
|
|
529
|
-
`https://agents.withgauge.com/schemas/gauge/v2.
|
|
555
|
+
`https://agents.withgauge.com/schemas/gauge/v2.8.0/gauge.json` and
|
|
556
|
+
`https://agents.withgauge.com/schemas/gauge/v2.8.0/case.json`. Associate them in editor
|
|
530
557
|
settings; `gauge.json` does not accept a `$schema` field. These release URLs are
|
|
531
558
|
immutable. Cases default to `gauge-cases/`, or use explicit `cases` paths.
|
|
532
559
|
|
|
@@ -540,8 +567,10 @@ plus editable templates and defaults. Local records live in workspace SQLite;
|
|
|
540
567
|
hosted records live in your organization. Launches freeze identity, revision, and
|
|
541
568
|
effective settings. Renaming or editing a measurement preserves its history.
|
|
542
569
|
Local measurements run on demand; recurring schedules, personas, markets, and
|
|
543
|
-
hosted resource references require hosted execution.
|
|
544
|
-
|
|
570
|
+
hosted resource references require hosted execution. Measurements do not store
|
|
571
|
+
project inputs: attach them to a local launch with
|
|
572
|
+
`gauge run --eval <id> --input <name>`, or `--input <name>=<path>` to replace the
|
|
573
|
+
configured files.
|
|
545
574
|
|
|
546
575
|
An **eval** is one prompt against one configuration. This hosted example uses
|
|
547
576
|
registered skills and recurring scheduling; omit those hosted features locally:
|
package/dist/batchWorker.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{runLocal}from"./chunk-
|
|
1
|
+
import{runLocal}from"./chunk-NVAONV7U.js";import"./chunk-FCK3MQPV.js";import"./chunk-RB7Q72OV.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,6 +1,6 @@
|
|
|
1
1
|
import{configDir,readConfig}from"./chunk-FCK3MQPV.js";import{DockerCli,PI_AGENT_DIR,agentEnv,harnessCommand,prepareScript,preserveWorkspace,shellQuote,splitModel}from"./chunk-RB7Q72OV.js";import{__export}from"./chunk-PSBF4TEK.js";import{createRequire}from"module";var CLI_VERSION=createRequire(import.meta.url)("../package.json").version;import{spawn as spawn3}from"child_process";import{randomBytes as randomBytes2}from"crypto";import{copyFile,mkdir as mkdir4,writeFile as writeFile3,open as open3,readFile as readFile5,rename as rename2}from"fs/promises";import{existsSync as existsSync3}from"fs";import{join as join8}from"path";import{setTimeout as delay}from"timers/promises";import{spawn}from"child_process";import{randomUUID as randomUUID2}from"crypto";import{chmod,lstat,mkdir as mkdir2,mkdtemp,open as open2,readFile as readFile3,rm as rm2,writeFile}from"fs/promises";import{createConnection}from"net";import{tmpdir}from"os";import{basename,dirname as dirname2,isAbsolute,join as join2,resolve}from"path";import{fileURLToPath}from"url";import{execFile}from"child_process";import{readFile}from"fs/promises";import{promisify}from"util";import{join}from"path";var CredentialError=class extends Error{remedy;constructor(message,remedy){super(message);this.remedy=remedy}};var RENEWAL_MARGIN_S=300;async function readOptional(path){try{return await readFile(path,"utf8")}catch(error){if(error.code==="ENOENT")return void 0;throw error}}async function readClaudeKeychain(){if(process.platform!=="darwin")return void 0;try{const{stdout}=await promisify(execFile)("security",["find-generic-password","-s","Claude Code-credentials","-w"]);return stdout}catch{return void 0}}function jwtExpiry(token){const payload=token.split(".")[1];if(!payload)return void 0;try{const exp=JSON.parse(Buffer.from(payload,"base64url").toString("utf8")).exp;return typeof exp==="number"?new Date(exp*1e3):void 0}catch{return void 0}}function envFile(name,value,variable2){const target=`/run/gauge/${name}`;return{files:[{name,contents:value,target,readonly:true}],exports:[`export ${variable2}="$(cat ${target})"`]}}async function claudeCredential(spec,src,read){switch(spec.auth.mode){case"setup_token":{const token=src.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();if(!token)throw new CredentialError("CLAUDE_CODE_OAUTH_TOKEN is not set.","Set CLAUDE_CODE_OAUTH_TOKEN, or use the Claude Code login on this machine.");return envFile("claude-token",token,"CLAUDE_CODE_OAUTH_TOKEN")}case"api_key":return providerApiKey("anthropic",src);case"access_token":{const{access,expiresAt}=await claudeLogin(spec,src,read);return{...envFile("claude-token",access,"CLAUDE_CODE_OAUTH_TOKEN"),expiresAt}}}}async function claudeLogin(spec,src,read){const configDir2=src.env.CLAUDE_CONFIG_DIR||join(src.homeDir,".claude");const raw=await(src.readKeychain??readClaudeKeychain)()??await read(join(configDir2,".credentials.json"));let login;try{login=raw?JSON.parse(raw).claudeAiOauth:void 0}catch{login=void 0}if(typeof login?.accessToken!=="string"||typeof login.expiresAt!=="number")throw new CredentialError("No Claude Code login found on this machine.","Run `claude` on this machine and log in, or set ANTHROPIC_API_KEY.");const expiresAt=new Date(login.expiresAt);const needed=spec.limits.turnTimeoutS+RENEWAL_MARGIN_S;if(expiresAt.getTime()-src.now.getTime()<needed*1e3)throw new CredentialError(`The Claude Code login expires at ${expiresAt.toISOString()}, too soon for a ${spec.limits.turnTimeoutS}s turn.`,"Run `claude -p ok` once on this machine to renew its login.");return{access:login.accessToken,expiresAt}}async function chatGptLogin(spec,src,read){const home=src.env.CODEX_HOME||join(src.homeDir,".codex");const raw=await read(join(home,"auth.json"));let auth;try{auth=raw?JSON.parse(raw):void 0}catch{throw new CredentialError("The native Codex login file is invalid.","Run `codex login` on this machine to replace it.")}const access=auth?.tokens?.access_token;if(!auth||auth.auth_mode!=="chatgpt"||!access)throw new CredentialError("No ChatGPT login found (Codex's ~/.codex/auth.json).","Run `codex login` on this machine, or select API-key auth.");const expiresAt=jwtExpiry(access);const needed=spec.limits.turnTimeoutS+RENEWAL_MARGIN_S;if(!expiresAt||expiresAt.getTime()-src.now.getTime()<needed*1e3)throw new CredentialError(`The ChatGPT access token ${expiresAt?`expires at ${expiresAt.toISOString()}`:"has no readable expiry"}, too soon for a ${spec.limits.turnTimeoutS}s turn.`,"Run `codex` once on this machine to renew its login.");return{auth,access,accountId:auth.tokens?.account_id,expiresAt}}var API_KEY_ENV={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",fireworks:"FIREWORKS_API_KEY",openrouter:"OPENROUTER_API_KEY"};function providerApiKey(provider,src){const variable2=API_KEY_ENV[provider];if(!variable2)throw new CredentialError(`API-key auth is not supported for provider ${provider}.`,`Use one of: ${Object.keys(API_KEY_ENV).join(", ")}.`);const key=src.env[variable2]?.trim();if(!key)throw new CredentialError(`API-key mode was selected but ${variable2} is not set.`,`Export ${variable2}, or select subscription auth.`);return envFile(variable2.toLowerCase().replace(/_/g,"-"),key,variable2)}function noClaudeSubscription(agent){throw new CredentialError(`Claude subscriptions are supported only in Claude Code, not ${agent}.`,"Use an Anthropic API key, or a ChatGPT login with an openai model.")}async function codexCredential(spec,src,read){switch(spec.auth.mode){case"access_token":{const{auth,expiresAt}=await chatGptLogin(spec,src,read);const stripped={...auth,OPENAI_API_KEY:null,tokens:{...auth.tokens,refresh_token:""}};return{files:[{name:"codex-auth.json",contents:JSON.stringify(stripped),target:"/run/gauge/codex-auth.json",readonly:true}],exports:["cp /run/gauge/codex-auth.json /gauge/session/codex/auth.json","chmod 600 /gauge/session/codex/auth.json"],expiresAt}}case"api_key":{const credential=providerApiKey("openai",src);return{...credential,exports:[...credential.exports,"codex login --with-api-key < /run/gauge/openai-api-key"]}}case"setup_token":throw new CredentialError("setup-token auth applies to Claude only.","Use the existing ChatGPT login or an API key for Codex.")}}async function openCodeCredential(spec,src,read){const{provider}=splitModel(spec.agent.model);switch(spec.auth.mode){case"access_token":{if(provider!=="openai")throw new CredentialError(`A ChatGPT login serves only openai/* models in OpenCode, not ${provider}.`,"Choose an openai/<model>, or select API-key auth.");const{access,accountId,expiresAt}=await chatGptLogin(spec,src,read);const content=JSON.stringify({openai:{type:"oauth",access,refresh:"",expires:expiresAt.getTime(),accountId}});return{...envFile("opencode-auth.json",content,"OPENCODE_AUTH_CONTENT"),expiresAt}}case"api_key":return providerApiKey(provider,src);case"setup_token":return noClaudeSubscription("OpenCode")}}async function piCredential(spec,src,read){const{provider}=splitModel(spec.agent.model);const agentDir=`mkdir -p ${PI_AGENT_DIR}`;switch(spec.auth.mode){case"access_token":{if(provider!=="openai-codex")throw new CredentialError(`A ChatGPT login serves only openai-codex/* models in Pi, not ${provider}.`,"Choose an openai-codex/<model>, or select API-key auth.");const{access,accountId,expiresAt}=await chatGptLogin(spec,src,read);const target="/run/gauge/pi-auth.json";return{files:[{name:"pi-auth.json",contents:JSON.stringify({"openai-codex":{type:"oauth",access,refresh:"",expires:expiresAt.getTime(),accountId}}),target,readonly:true}],exports:[agentDir,`cp ${target} ${PI_AGENT_DIR}/auth.json`,`chmod 600 ${PI_AGENT_DIR}/auth.json`],expiresAt}}case"api_key":{const credential=providerApiKey(provider,src);return{...credential,exports:[agentDir,...credential.exports]}}case"setup_token":return noClaudeSubscription("Pi")}}async function resolveSessionCredential(spec,src){const read=src.readFile??readOptional;switch(spec.agent.kind){case"claude-code":return claudeCredential(spec,src,read);case"codex":return codexCredential(spec,src,read);case"opencode":return openCodeCredential(spec,src,read);case"pi":return piCredential(spec,src,read)}}import{randomUUID}from"crypto";import{mkdir,open,readFile as readFile2,rename,rm}from"fs/promises";import{dirname}from"path";function tempPath(path){return`${path}.tmp-${process.pid}-${randomUUID()}`}async function writeSynced(path,data,mode){const handle=await open(path,"wx",mode);try{await handle.writeFile(data);await handle.sync()}finally{await handle.close()}}async function writeFileAtomic(path,data,mode=420){await mkdir(dirname(path),{recursive:true});const tmp=tempPath(path);try{await writeSynced(tmp,data,mode);await rename(tmp,path)}catch(error){await rm(tmp,{force:true});throw error}}function writeJsonAtomic(path,value){return writeFileAtomic(path,`${JSON.stringify(value,null,2)}
|
|
2
|
-
`)}async function readJson(path){try{return JSON.parse(await readFile2(path,"utf8"))}catch(error){if(error.code==="ENOENT")return void 0;throw error}}var terminal=state=>state==="completed"||state==="failed"||state==="canceled"||state==="interrupted";var SessionNotFoundError=class extends Error{constructor(){super("no supported session in this directory");this.name="SessionNotFoundError"}};var SessionUnavailableError=class extends Error{constructor(message,cause){super(message,{cause});this.name="SessionUnavailableError"}};var socketUnavailable=error=>["ENOENT","ECONNREFUSED"].includes(error?.code??"");function driverExited(status){const pid=status?.driverPid;if(typeof pid!=="number"||!Number.isSafeInteger(pid)||pid<=0)return false;try{process.kill(pid,0);return false}catch(error){return error.code==="ESRCH"}}function validateSpec(spec){if(!["claude-code","codex","pi","opencode"].includes(spec.agent.kind))throw new Error("unsupported agent");if(!spec.image||!spec.agent.model||!spec.prompt.text)throw new Error("image, model and prompt are required");if(spec.workspace){const url=new URL(spec.workspace.repo);if(url.protocol!=="https:"||url.hostname!=="github.com"||url.username||url.password||url.search||url.hash||!/^\/[\w.-]+\/[\w.-]+\/?$/.test(url.pathname))throw new Error("workspace must be a public GitHub HTTPS repository URL");if(!spec.workspace.ref||spec.workspace.ref.startsWith("-"))throw new Error("invalid repository ref")}for(const value of[spec.limits.turnTimeoutS,spec.limits.maxTurns])if(!Number.isSafeInteger(value)||value<1)throw new Error("limits must be positive integers");if(spec.limits.responseTimeoutS!==null&&(!Number.isSafeInteger(spec.limits.responseTimeoutS)||spec.limits.responseTimeoutS<1))throw new Error("response timeout must be null or a positive integer");const names=new Set;for(const r of spec.resources){if(!["file","archive"].includes(r.kind))throw new Error("unsupported resource kind");if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(r.name)||names.has(r.name))throw new Error("invalid or duplicate resource name");if(!/^[\w.-]+$/.test(r.filename)||r.filename==="."||r.filename==="..")throw new Error("invalid resource filename");if(!/^sha256:[a-f0-9]{64}$/.test(r.digest))throw new Error("invalid resource digest");if(r.use&&r.kind!=="archive")throw new Error("resource use requires an archive");if(r.use&&!["files","skill","npm-package"].includes(r.use.type))throw new Error("unsupported resource use");if(r.use?.type==="npm-package"&&(!/^[\w.-]+\.tgz$/.test(r.use.package)||!["environment","workspace"].includes(r.use.install)))throw new Error("invalid npm input");names.add(r.name)}}async function startSession(options){validateSpec(options.spec);const directory=resolve(options.directory);const credential=await resolveSessionCredential(options.spec,{...options.credentials,now:new Date});await mkdir2(dirname2(directory),{recursive:true});await mkdir2(directory,{mode:448});const engine=new DockerCli;let credentialDir;let created=false;const containerName=`gauge-session-${randomUUID2()}`;try{const runtime=options.runtimeDirectory??tmpdir();await mkdir2(runtime,{recursive:true});credentialDir=await mkdtemp(join2(runtime,"gauge-"));await chmod(credentialDir,448);await mkdir2(join2(credentialDir,"workspace"),{mode:448});const record={version:1,containerName,credentialDir,socketPath:join2(credentialDir,"control.sock"),spec:options.spec,credentialExpiresAt:credential.expiresAt?.toISOString()};if(Buffer.byteLength(record.socketPath)>100)throw new Error("runtimeDirectory is too long for a Unix socket");await writeJsonAtomic(join2(directory,"session.json"),record);const mounts=[{type:"bind",source:join2(credentialDir,"workspace"),target:"/gauge/session",readonly:false}];for(const file of credential.files){const source=join2(credentialDir,file.name);await writeFile(source,file.contents,{mode:384});mounts.push({type:"bind",source,target:file.target,readonly:file.readonly})}for(const resource of options.spec.resources){if(!options.blobsDirectory)throw new Error("blobsDirectory is required for resources");mounts.push({type:"bind",source:resolve(options.blobsDirectory,resource.digest.slice(7)),target:`/gauge/inputs/${resource.name}`,readonly:true})}const script=[prepareScript(options.spec),...credential.exports,`exec ${harnessCommand(options.spec).map(shellQuote).join(" ")}`].join("\n");const result=await engine.create({name:containerName,image:options.spec.image,interactive:true,user:`${process.getuid()}:${process.getgid()}`,labels:{"sh.gauge.session":containerName},mounts,env:{...agentEnv(options.spec.agent.kind),HOME:"/gauge/session/home"},command:["sh","-c",script]});if(result!=="created")throw new Error("session container already exists");created=true;const log=await open2(join2(directory,"driver.log"),"a",384);try{const child=spawn(process.execPath,[fileURLToPath(new URL("./worker.js",import.meta.url)),directory],{detached:true,stdio:["ignore",log.fd,log.fd],env:Object.fromEntries(Object.entries(process.env).filter(([key])=>!/(?:API_KEY|AUTH_TOKEN|OAUTH_TOKEN|ACCESS_TOKEN|REFRESH_TOKEN)$/.test(key)))});const spawned=new Promise((yes,no)=>{child.once("spawn",yes);child.once("error",no)});await spawned;child.unref()}finally{await log.close()}const deadline=Date.now()+1e4;while(Date.now()<deadline){try{return await request(record.socketPath,{action:"status"})}catch{const saved=await readJson(join2(directory,"status.json"));if(saved&&terminal(saved.state))return saved;await new Promise(r=>setTimeout(r,50))}}throw new Error("host session process did not start; see driver.log")}catch(error){if(created){await engine.stop(containerName,2);await engine.remove(containerName)}if(credentialDir)await rm2(credentialDir,{recursive:true,force:true});await writeJsonAtomic(join2(directory,"status.json"),{state:"failed",turn:0,updatedAt:new Date().toISOString(),detail:String(error)});throw error}}async function request(socketPath,command2){return new Promise((resolve2,reject)=>{const socket=createConnection(socketPath);let bytes="";socket.setEncoding("utf8");socket.setTimeout(35e3,()=>socket.destroy(new Error("session command timed out; delivery may have succeeded")));socket.on("error",reject);socket.on("connect",()=>socket.write(JSON.stringify(command2)+"\n"));socket.on("data",chunk=>{bytes+=chunk;if(Buffer.byteLength(bytes)>8*1024*1024){socket.destroy(new Error("session response too large"));return}if(bytes.includes("\n")){try{resolve2(JSON.parse(bytes.slice(0,bytes.indexOf("\n"))))}catch(e){reject(e)}socket.end()}});socket.on("end",()=>{if(!bytes.includes("\n"))reject(new Error("session disconnected before acknowledging command"))})})}async function launchRecord(directory){const record=await readJson(join2(directory,"session.json"));if(!record)throw new SessionNotFoundError;if(record.version!==1)throw new Error("Unsupported session record version");return record}async function getSessionStatus(directory){const record=await launchRecord(directory);const saved=await readJson(join2(directory,"status.json"));if(saved&&terminal(saved.state))return saved;try{return await request(record.socketPath,{action:"status"})}catch(error){const latest=await readJson(join2(directory,"status.json"));if(latest&&terminal(latest.state))return latest;if(!socketUnavailable(error)||!driverExited(latest))throw new SessionUnavailableError("Session status is unavailable; the driver may still be running. Check status again before taking action.",error);return{...latest,state:"interrupted",turn:latest?.turn??0,updatedAt:new Date().toISOString(),detail:"Host session process is unavailable. Stop this session to clean up; prompts are never replayed automatically."}}}async function command(directory,value){const record=await launchRecord(directory);let receipt;try{receipt=await request(record.socketPath,value)}catch(error){throw new SessionUnavailableError("Session command was not acknowledged; delivery may have succeeded. Check status before retrying.",error)}if(!receipt.accepted)throw new Error(receipt.error??"session rejected command");return receipt}var finishSession=(directory,expectedTurn)=>command(directory,{action:"finish",turn:expectedTurn});async function stopSession(directory){const record=await launchRecord(directory);let saved=await readJson(join2(directory,"status.json"));if(saved&&terminal(saved.state)&&!saved.cleanupPending)return;let receipt;try{receipt=await request(record.socketPath,{action:"cancel"})}catch(error){saved=await readJson(join2(directory,"status.json"));if(saved&&terminal(saved.state)&&!saved.cleanupPending)return;if(!socketUnavailable(error)||!driverExited(saved))throw new SessionUnavailableError("Cancellation was not acknowledged; the driver may still be running. Check status before retrying.",error);await cleanupOrphan(directory,record);return}if(!receipt.accepted)throw new Error(receipt.error??"session rejected cancellation");const deadline=Date.now()+3e4;while(Date.now()<deadline){saved=await readJson(join2(directory,"status.json"));if(saved&&terminal(saved.state)){if(saved.cleanupPending)throw new Error(saved.detail??"Cleanup incomplete; call stopSession again after the driver exits");return}if(driverExited(saved)){await cleanupOrphan(directory,record);return}await new Promise(r=>setTimeout(r,100))}throw new SessionUnavailableError("Cancellation was accepted but cleanup is still pending. Check status; the driver retains ownership of cleanup.")}async function cleanupOrphan(directory,record){if(!/^gauge-session-[a-f0-9-]{36}$/.test(record.containerName)||!isAbsolute(record.credentialDir)||!/^gauge-[A-Za-z0-9]+$/.test(basename(record.credentialDir))||record.socketPath!==join2(record.credentialDir,"control.sock"))throw new Error("Refusing cleanup: invalid Gauge runtime ownership record");try{if(!(await lstat(record.credentialDir)).isDirectory())throw new Error("Refusing cleanup: Gauge runtime is not a directory")}catch(error){if(error.code!=="ENOENT")throw error}const engine=new DockerCli;await engine.assertSessionOwner(record.containerName,record.credentialDir);await engine.stop(record.containerName,2);const workspace=await preserveWorkspace(directory,record.credentialDir);await engine.remove(record.containerName);await rm2(record.credentialDir,{recursive:true,force:true});const saved=await readJson(join2(directory,"status.json"));await writeJsonAtomic(join2(directory,"status.json"),{...saved,state:saved&&terminal(saved.state)?saved.state:"interrupted",turn:saved?.turn??0,updatedAt:new Date().toISOString(),question:void 0,cleanupPending:false,detail:saved&&terminal(saved.state)?saved.detail:"Interrupted session cleaned up explicitly",artifacts:workspace?{...saved?.artifacts,workspace}:saved?.artifacts})}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 z2}from"zod";import{z}from"zod";var ERROR_CODES=["unauthorized","forbidden","not_found","invalid_request","insufficient_credits","needs_provider_key","rate_limited","conflict","internal","upgrade_required"];var errorCodeSchema=z.enum(ERROR_CODES);var upgradeOfferSchema=z.object({skuId:z.string(),tierLabel:z.string(),monthlyAmountCents:z.number().int(),monthlyCredits:z.number().int(),billingUrl:z.string()});var errorEnvelopeSchema=z.object({error:z.object({code:errorCodeSchema,message:z.string(),upgrade:upgradeOfferSchema.optional()})});var listQuerySchema=z.object({limit:z.coerce.number().int().min(1).max(200).default(50),cursor:z.string().optional()});function listResponseSchema(item){return z.object({items:z.array(item),nextCursor:z.string().optional()})}var BATTERY_AGENTS=["CLAUDE_CODE","CODEX_CLI","CURSOR","PI","OPENCODE"];var BATTERY_CADENCES=["NONE"];var batteryAgentSchema=z2.enum(BATTERY_AGENTS);var BATTERY_MAX_LIMITS={maxTurns:30,wallClockS:5400,maxUsd:10};var MAX_SAMPLES_PER_CYCLE=50;var batteryLimitsSchema=z2.object({maxTurns:z2.number().positive().max(BATTERY_MAX_LIMITS.maxTurns).optional(),wallClockS:z2.number().positive().max(BATTERY_MAX_LIMITS.wallClockS).optional(),maxUsd:z2.number().positive().max(BATTERY_MAX_LIMITS.maxUsd).optional()});var batterySkillRefSchema=z2.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=z2.array(batterySkillRefSchema);var batteryScheduleSpecSchema=z2.object({repoUrl:z2.string().nullish(),repoRef:z2.string().nullish(),model:z2.string().nullable().optional(),agents:z2.array(batteryAgentSchema).optional(),samplesPerCycle:z2.number().int().min(1).max(MAX_SAMPLES_PER_CYCLE).optional(),cadence:z2.enum(BATTERY_CADENCES).optional(),experiment:z2.string().optional(),limits:batteryLimitsSchema.optional(),skills:batterySkillsSchema.optional()});var batteryDefaultsSchema=z2.object({isBranded:z2.boolean().optional(),topic:z2.string().optional(),tags:z2.array(z2.string()).optional(),model:z2.string().nullable().optional(),agents:z2.array(batteryAgentSchema).optional(),samplesPerCycle:z2.number().int().min(1).max(MAX_SAMPLES_PER_CYCLE).optional(),cadence:z2.enum(BATTERY_CADENCES).optional(),limits:batteryLimitsSchema.optional(),skills:batterySkillsSchema.optional()});var batteryPromptSpecSchema=z2.object({key:z2.string().min(1),text:z2.string().min(1),isBranded:z2.boolean().optional(),topic:z2.string().optional(),tags:z2.array(z2.string()).optional(),experiment:z2.string().optional(),schedules:z2.array(batteryScheduleSpecSchema).optional()});var batterySpecSchema=z2.object({version:z2.literal(1),org:z2.string().optional(),experiment:z2.string().optional(),expand:z2.boolean().optional(),defaults:batteryDefaultsSchema.optional(),prompts:z2.array(batteryPromptSpecSchema).min(1)});var batteryPlanScheduleSchema=z2.object({action:z2.enum(["create","update","none"]),repoUrl:z2.string().nullable(),repoRef:z2.string().nullable(),runs:z2.number().int()});var batteryPlanPromptSchema=z2.object({key:z2.string(),action:z2.enum(["create","update"]),schedules:z2.array(batteryPlanScheduleSchema)});var batteryPlanSchema=z2.object({dryRun:z2.literal(true),org:z2.string(),experiment:z2.string().nullable(),expand:z2.boolean(),prompts:z2.array(batteryPlanPromptSchema),summary:z2.object({promptsToCreate:z2.number().int(),promptsToUpdate:z2.number().int(),schedulesToCreate:z2.number().int(),schedulesToUpdate:z2.number().int(),runsToEnqueue:z2.number().int(),runsByAgent:z2.record(z2.string(),z2.number().int()),estimatedCredits:z2.number().int()})});var batteryApplyResponseSchema=z2.object({batchIds:z2.array(z2.string()),runIds:z2.array(z2.string()),experiment:z2.string().nullable(),blocked:z2.enum(["insufficient_credits","needs_provider_key"]).optional()});var batchRunStatusSchema=z2.enum(["QUEUED","CLAIMED","PROVISIONING","RUNNING","SUCCEEDED","FAILED","TIMED_OUT","CANCELED"]);var batchListQuerySchema=listQuerySchema.extend({promptId:z2.string().optional(),experiment:z2.string().optional()});var batchSummarySchema=z2.object({id:z2.string(),promptId:z2.string(),promptText:z2.string(),experiment:z2.string().nullable(),createdAt:z2.string(),runCounts:z2.record(z2.string(),z2.number().int())});var batchListResponseSchema=listResponseSchema(batchSummarySchema);var batchRunSummarySchema=z2.object({id:z2.string(),agent:z2.string(),model:z2.string(),status:batchRunStatusSchema,createdAt:z2.string(),startedAt:z2.string().nullable(),finishedAt:z2.string().nullable()});var batchDetailSchema=z2.object({id:z2.string(),promptId:z2.string(),promptText:z2.string(),scenario:z2.string(),repoUrl:z2.string().nullable(),repoRef:z2.string().nullable(),experiment:z2.string().nullable(),funding:z2.string(),createdAt:z2.string(),runCounts:z2.record(z2.string(),z2.number().int()),runs:z2.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 z3}from"zod";var BRAND_KINDS=["OWNED","COMPETITOR","OTHER"];var brandKindSchema=z3.enum(BRAND_KINDS);var BRAND_PACKAGE_ECOSYSTEMS=["npm","pypi","cargo","go","rubygems","other"];var brandPackageEcosystemSchema=z3.enum(BRAND_PACKAGE_ECOSYSTEMS);var brandPackageSchema=z3.object({name:z3.string(),ecosystem:z3.string().nullable()});var brandSchema=z3.object({id:z3.string(),name:z3.string(),kind:brandKindSchema,source:z3.string(),aliases:z3.array(z3.string()),websites:z3.array(z3.string()),category:z3.string().nullable(),packages:z3.array(brandPackageSchema),createdAt:z3.string(),updatedAt:z3.string()});var brandPackageInputSchema=z3.object({name:z3.string().min(1),ecosystem:brandPackageEcosystemSchema.nullable().optional()});var createBrandBodySchema=z3.object({name:z3.string().min(1),kind:brandKindSchema,aliases:z3.array(z3.string().min(1)).default([]),websites:z3.array(z3.string().min(1)).default([]),packages:z3.array(brandPackageInputSchema).default([])});var updateBrandBodySchema=z3.object({name:z3.string().min(1).optional(),kind:brandKindSchema.optional(),aliases:z3.array(z3.string().min(1)).optional(),websites:z3.array(z3.string().min(1)).optional(),packages:z3.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 z4}from"zod";var FEEDBACK_KINDS=["friction","missing","bug","other"];var feedbackKindSchema=z4.enum(FEEDBACK_KINDS);var createFeedbackBodySchema=z4.object({message:z4.string().trim().min(1).max(4e3),kind:feedbackKindSchema.default("other"),command:z4.string().trim().max(500).optional(),org:z4.string().optional()});var createFeedbackResponseSchema=z4.object({id:z4.string()});var keys_exports={};__export(keys_exports,{PROVIDER_TYPES:()=>PROVIDER_TYPES,providerKeyListResponseSchema:()=>providerKeyListResponseSchema,providerKeySchema:()=>providerKeySchema,providerTypeSchema:()=>providerTypeSchema,setProviderKeyBodySchema:()=>setProviderKeyBodySchema,setProviderKeyResponseSchema:()=>setProviderKeyResponseSchema});import{z as z5}from"zod";var PROVIDER_TYPES=["anthropic","openai"];var providerTypeSchema=z5.enum(PROVIDER_TYPES);var setProviderKeyBodySchema=z5.object({key:z5.string().min(1)});var setProviderKeyResponseSchema=z5.object({providerType:providerTypeSchema,last4:z5.string()});var providerKeySchema=z5.object({providerType:providerTypeSchema,last4:z5.string(),createdAt:z5.string(),updatedAt:z5.string()});var providerKeyListResponseSchema=listResponseSchema(providerKeySchema);var runConfig_exports={};__export(runConfig_exports,{SCHEDULABLE_AGENTS:()=>SCHEDULABLE_AGENTS,agentConfigInputSchema:()=>agentConfigInputSchema,agentConfigSchema:()=>agentConfigSchema,assetRefListSchema:()=>assetRefListSchema,assetRefSchema:()=>assetRefSchema,modelUnits:()=>modelUnits,refAssetName:()=>refAssetName,runsPerCycle:()=>runsPerCycle,schedulableAgentSchema:()=>schedulableAgentSchema,totalRunsPerCycle:()=>totalRunsPerCycle});import{z as z8}from"zod";import{z as z7}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 z6}from"zod";var ANALYSIS_SCHEMA_VERSION=1;var evidenceSequenceSchema=z6.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=z6.discriminatedUnion("kind",[z6.object({kind:z6.literal("trace"),seq:evidenceSequenceSchema}).strict(),z6.object({kind:z6.literal("diff"),path:z6.string().min(1)}).strict()]);var INSTALL_PHASES=["NONE","ATTEMPTED","CONFIGURED","EXERCISED"];var sessionProductSchema=z6.object({name:z6.string(),mentioned:z6.boolean(),considered:z6.boolean(),recommended:z6.boolean(),chosen:z6.boolean(),rejected:z6.boolean(),abandoned:z6.boolean(),installPhase:z6.enum(INSTALL_PHASES),rank:z6.number().int().nullable(),source:z6.enum(["BRIEF","PERSONA","PRIOR","SEARCH","PAGE","REPO","UNKNOWN"]),reason:z6.string(),categories:z6.array(z6.string()),evidence:z6.record(z6.string(),z6.array(evidenceRefSchema))});var sessionObservationSchema=z6.object({id:z6.string(),kind:z6.enum(["FRICTION","OBJECTION","OPPORTUNITY"]),label:z6.string(),detail:z6.string(),subject:z6.string(),basis:z6.enum(["OBSERVED","AGENT_CLAIM","INFERRED"]),effect:z6.enum(["BLOCKED","RECOVERED","EXTRA_WORK","SELECTION_LOSS","UNKNOWN"]),cause:z6.enum(["PRODUCT","CONTENT","ACCESS","ENVIRONMENT","AGENT","UNKNOWN"]),tags:z6.array(z6.string()),evidence:z6.array(evidenceRefSchema)});var sessionAnalysisSchema=z6.object({schemaVersion:z6.literal(ANALYSIS_SCHEMA_VERSION),instructionsVersion:z6.string().min(1),id:z6.string(),runId:z6.string(),attempt:z6.number().int(),createdAt:z6.string(),origin:z6.enum(["MODEL","LEGACY"]),model:z6.string().nullable(),assessability:z6.enum(["ASSESSED","PARTIAL","UNASSESSABLE"]),limitation:z6.string().nullable(),selection:z6.enum(["MEASURED","UNASSESSABLE","NOT_MEASURED"]),directed:z6.boolean(),products:z6.array(sessionProductSchema),observations:z6.array(sessionObservationSchema)});var artifactPathSchema=z6.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=z6.discriminatedUnion("kind",[z6.object({kind:z6.literal("trace"),seq:evidenceSequenceSchema}).strict(),z6.object({kind:z6.literal("diff"),path:artifactPathSchema}).strict(),z6.object({kind:z6.literal("artifact"),artifact:artifactPathSchema.describe("Path relative to the session attempt directory, for example session/events.ndjson."),attempt:z6.number().int().positive().optional().describe("Must match the analysis attempt; defaults to that attempt."),line:z6.number().int().positive().optional().describe("One-based line number in the original artifact, before any filtering."),endLine:z6.number().int().positive().optional().describe("Inclusive last line of the evidence range."),seq:evidenceSequenceSchema.optional()}).strict().superRefine((ref,ctx)=>{if(ref.line===void 0&&ref.seq===void 0)ctx.addIssue({code:"custom",message:"Artifact evidence needs a line or seq"});if(ref.endLine!==void 0&&(ref.line===void 0||ref.endLine<ref.line))ctx.addIssue({code:"custom",path:["endLine"],message:"endLine requires line and must be at least line"})})]);var findingSubmissionSchema=sessionObservationSchema.omit({id:true}).extend({label:z6.string().trim().min(1).max(200),detail:z6.string().trim().min(1).max(1e4),subject:z6.string().trim().min(1).max(200),tags:z6.array(z6.string().trim().min(1).max(64)).max(32).default([]),evidence:z6.array(portableEvidenceRefSchema).min(1).max(100)}).strict();var criterionAnalysisSubmissionSchema=z6.object({criterionId:z6.string().min(1),outcome:z6.enum(["PASS","FAIL","UNASSESSABLE"]),label:z6.string().trim().min(1).max(1e4),evidence:z6.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:z6.string().trim().min(1).max(200),evidence:z6.record(z6.string(),z6.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=z6.object({schemaVersion:z6.literal(ANALYSIS_SCHEMA_VERSION),attempt:z6.number().int().positive().default(1),instructionsVersion:z6.string().trim().min(1),analyst:z6.object({name:z6.string().trim().min(1),model:z6.string().trim().min(1).optional()}).strict(),assessability:sessionAnalysisSchema.shape.assessability,limitation:z6.string().trim().min(1).nullable().default(null),selection:sessionAnalysisSchema.shape.selection.default("NOT_MEASURED"),directed:z6.boolean().default(false),findings:z6.array(findingSubmissionSchema).max(1e3).default([]),products:z6.array(productSubmissionSchema).max(1e3).default([]),criteria:z6.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=z7.enum(RUN_STATUSES);var AGENTS=["CLAUDE_CODE","CODEX_CLI","CURSOR","PI","OPENCODE"];var agentSchema=z7.enum(AGENTS);var OBSERVED_PROVIDER_SOURCES=["AGENT_STREAM","GATEWAY_RESPONSE","GATEWAY_AUDIT","CANARY"];var observedProviderSourceSchema=z7.enum(OBSERVED_PROVIDER_SOURCES);var selectedProviderSchema=z7.object({slug:z7.string(),displayName:z7.string()});var observedProviderSchema=z7.object({slug:z7.string(),source:observedProviderSourceSchema});var RUN_TRIGGER_SOURCES=["UNKNOWN","UI","API","CADENCE","STAFF","OPERATOR","GITHUB"];var runTriggerSourceSchema=z7.enum(RUN_TRIGGER_SOURCES);var runTriggeredBySchema=z7.object({source:runTriggerSourceSchema,userId:z7.string().nullable(),email:z7.string().nullable()});var runOptimizationTrialSchema=z7.object({optimizationId:z7.string(),trialId:z7.string(),key:z7.string(),title:z7.string(),kind:z7.enum(INTERVENTION_KINDS)});var runCreditsChargedSchema=z7.number().int().nullable();var runStatusFilterSchema=z7.string().transform(raw=>raw.split(",").map(s=>s.trim().toUpperCase()).filter(Boolean)).pipe(z7.array(runStatusSchema).min(1));var runListQuerySchema=listQuerySchema.extend({status:runStatusFilterSchema.optional(),batch:z7.string().optional(),prompt:z7.string().optional(),experiment:z7.string().optional(),evalSet:z7.string().optional(),since:z7.string().optional()});var runListItemSchema=z7.object({id:z7.string(),status:runStatusSchema,agent:agentSchema,model:z7.string(),resolvedModel:z7.string().nullable().optional(),modelDisplayName:z7.string().nullable().optional(),selectedProvider:selectedProviderSchema.nullable().optional(),observedProvider:observedProviderSchema.nullable().optional(),promptId:z7.string(),promptSnippet:z7.string(),batchId:z7.string(),experiment:z7.string().nullable(),evalSetId:z7.string().nullable(),evalRevision:z7.string().optional(),optimizationTrial:runOptimizationTrialSchema.nullable().optional(),turns:z7.number().int().nullable(),usdCost:z7.number().nullable(),creditsCharged:runCreditsChargedSchema.optional(),triggeredBy:runTriggeredBySchema.optional(),durationMs:z7.number().int().nullable(),exitReason:z7.string().nullable(),createdAt:z7.string(),startedAt:z7.string().nullable(),finishedAt:z7.string().nullable(),parentRunId:z7.string().nullable(),fetchForkPlanId:z7.string().nullable()});var runListResponseSchema=listResponseSchema(runListItemSchema);var runSkillSchema=z7.discriminatedUnion("source",[z7.object({source:z7.literal("saved"),skillId:z7.string(),name:z7.string(),label:z7.string()}),z7.object({source:z7.literal("input"),name:z7.string(),commit:z7.string().nullable(),pullNumber:z7.number().int().nullable()})]);var runDetailSchema=runListItemSchema.omit({promptSnippet:true}).extend({promptText:z7.string(),attempt:z7.number().int(),cancelRequested:z7.boolean(),failureReason:z7.string().nullable(),repoUrl:z7.string().nullable(),repoRef:z7.string().nullable(),scenario:z7.string(),funding:z7.string(),usage:z7.unknown().nullable(),hasDiff:z7.boolean(),claimedAt:z7.string().nullable(),criterionResults:z7.array(z7.object({criterionId:z7.string().nullable(),name:z7.string(),passed:z7.boolean().nullable(),reasoning:z7.string().nullable()})),skills:z7.array(runSkillSchema).optional()});var cancelRunResponseSchema=z7.object({id:z7.string(),status:runStatusSchema,cancelRequested:z7.boolean(),note:z7.string().optional()});var regradeRunResponseSchema=z7.object({runId:z7.string(),evalSetId:z7.string().nullable(),criteria:z7.number().int()});var RUN_INSIGHT_STATUSES=["PENDING","RUNNING","COMPLETE","FAILED","SKIPPED"];var runInsightStatusSchema=z7.enum(RUN_INSIGHT_STATUSES);var insightPassSchema=z7.object({status:runInsightStatusSchema,model:z7.string().nullable(),inputTokens:z7.number().int().nullable(),outputTokens:z7.number().int().nullable(),usdCost:z7.number().nullable(),error:z7.string().nullable()});var runDecisionSchema=z7.object({index:z7.number().int(),category:z7.string(),categoryRaw:z7.string().nullable(),chosenName:z7.string(),chosenEcosystem:z7.string().nullable(),chosenPackage:z7.string().nullable(),reversed:z7.boolean(),detail:z7.unknown()});var RUN_INSIGHT_PASS_KINDS=["ANALYSIS","CLI_DISCOVERY","LEVER","EXPERIMENT_DELTA"];var runInsightPassKindSchema=z7.enum(RUN_INSIGHT_PASS_KINDS);var insightPipelinePassSchema=insightPassSchema.extend({kind:runInsightPassKindSchema});var runInsightResponseSchema=z7.object({runId:z7.string(),decision:insightPassSchema,passes:z7.array(insightPipelinePassSchema),decisions:z7.array(runDecisionSchema),experimentDelta:z7.unknown().nullable(),visibilityVerdict:z7.unknown().nullable(),analysis:sessionAnalysisSchema.nullable()});var runEventSchema=z7.looseObject({run_id:z7.string(),seq:z7.number(),turn:z7.number(),ts:z7.string(),type:z7.string()});var runCompareSideSchema=z7.object({runRequest:z7.string().min(1).optional(),batch:z7.array(z7.string().min(1)).min(1).max(100).optional(),evalSet:z7.string().min(1).optional(),evalRevision:z7.string().min(1).optional(),trial:z7.string().min(1).optional(),experiment:z7.string().min(1).optional(),agent:z7.array(agentSchema).min(1).optional(),model:z7.array(z7.string()).min(1).optional(),since:z7.string().optional(),until:z7.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=z7.object({baseline:runCompareSideSchema,candidate:runCompareSideSchema}).strict();var runCompareStatsSchema=z7.object({runs:z7.number().int(),finished:z7.number().int(),succeeded:z7.number().int(),judged:z7.number().int(),passed:z7.number().int(),passRate:z7.number().nullable(),medianTurns:z7.number().nullable(),medianUsdCost:z7.number().nullable(),medianDurationMs:z7.number().nullable(),criteria:z7.array(z7.object({name:z7.string(),judged:z7.number().int(),passed:z7.number().int(),passRate:z7.number().nullable()}))});var runCompareDeltaSchema=z7.object({passRate:z7.number().nullable(),medianTurns:z7.number().nullable(),medianUsdCost:z7.number().nullable(),medianDurationMs:z7.number().nullable(),criteria:z7.array(z7.object({name:z7.string(),passRate:z7.number().nullable()}))});var runCompareRowSchema=z7.object({baseline:runCompareStatsSchema,candidate:runCompareStatsSchema,delta:runCompareDeltaSchema});var runCompareMixedRevisionSchema=z7.object({evalSetId:z7.string().nullable(),promptId:z7.string().nullable(),revisions:z7.array(z7.string())});var runCompareTrialSchema=runOptimizationTrialSchema.extend({runs:z7.number().int()});var runCompareResponseSchema=z7.object({overall:runCompareRowSchema,targets:z7.array(runCompareRowSchema.extend({agent:agentSchema,model:z7.string()})),sides:z7.object({baseline:z7.object({evalRevisions:z7.array(z7.string()),mixedRevisions:z7.array(runCompareMixedRevisionSchema).optional(),truncated:z7.boolean(),trials:z7.array(runCompareTrialSchema).optional()}),candidate:z7.object({evalRevisions:z7.array(z7.string()),mixedRevisions:z7.array(runCompareMixedRevisionSchema).optional(),truncated:z7.boolean(),trials:z7.array(runCompareTrialSchema).optional()})})});var SCHEDULABLE_AGENTS=["CLAUDE_CODE","CODEX_CLI","PI","OPENCODE"];var schedulableAgentSchema=z8.enum(SCHEDULABLE_AGENTS);var agentConfigSchema=z8.object({agent:agentSchema,models:z8.array(z8.string().min(1))});var agentConfigInputSchema=z8.object({agent:schedulableAgentSchema,models:z8.array(z8.string().min(1)).default([])});var assetRefSchema=z8.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=z8.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(agents2){return agents2.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)}import{chmodSync,mkdirSync,readFileSync,rmSync,writeFileSync}from"fs";import{join as join3}from"path";function credentialsPath(){return join3(configDir(),"credentials")}function resolveToken(){const fromEnv=process.env.GAUGE_API_TOKEN?.trim();if(fromEnv)return fromEnv;try{const stored=readFileSync(credentialsPath(),"utf8").trim();return stored||null}catch{return null}}function saveToken(token){mkdirSync(configDir(),{recursive:true,mode:448});writeFileSync(credentialsPath(),`${token.trim()}
|
|
3
|
-
`,{encoding:"utf8",mode:384});chmodSync(credentialsPath(),384)}function clearToken(){rmSync(credentialsPath(),{force:true})}var DEFAULT_API_URL="https://agents.withgauge.com";var USER_AGENT=`gauge-cli/${CLI_VERSION}`;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;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}};function resolveBaseUrl(){return process.env.GAUGE_API_URL||readConfig().apiUrl||DEFAULT_API_URL}var ApiClient=class{baseUrl;token;authOptional;constructor(options={}){this.baseUrl=(options.baseUrl??resolveBaseUrl()).replace(/\/+$/,"");this.token=options.token!==void 0?options.token:resolveToken();this.authOptional=options.authOptional??false}get signedIn(){return this.token!==null}async get(path,query){return this.request("GET",path,{query})}async post(path,body,query){return this.request("POST",path,{body,query})}async patch(path,body,query){return this.request("PATCH",path,{body,query})}async put(path,body,query){return this.request("PUT",path,{body,query})}async delete(path,query){return this.request("DELETE",path,{query})}async sse(path,onEvent,options={}){const res=await this.fetch(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(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 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.fetch(this.url(path,options.query),{method,headers,body:options.body===void 0?void 0:JSON.stringify(options.body)});if(!res.ok)throw await this.toError(res);if(res.status===204)return void 0;const text=await res.text();if(!text)return void 0;const contentType=res.headers.get("content-type")??"";if(contentType.includes("application/json")){return JSON.parse(text)}return text}async toError(res){const wait=res.status===429?retryAfterSeconds(res):void 0;const hint=wait===void 0?void 0:`Try again in ${wait} s.`;try{const parsed=errorEnvelopeSchema.safeParse(await res.clone().json());if(parsed.success){return new CliError(parsed.data.error.code,parsed.data.error.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})}};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)}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=""){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{existsSync as existsSync2}from"fs";import{lstat as lstat2,readdir,readFile as readFile4,writeFile as writeFile2}from"fs/promises";import{join as join5}from"path";import{randomUUID as randomUUID3}from"crypto";import{chmodSync as chmodSync2,existsSync,mkdirSync as mkdirSync2,readdirSync,readFileSync as readFileSync2,statSync}from"fs";import{createRequire as createRequire2}from"module";import{join as join4}from"path";var LOCAL_DATABASE_VERSION=1;var schema=`
|
|
2
|
+
`)}async function readJson(path){try{return JSON.parse(await readFile2(path,"utf8"))}catch(error){if(error.code==="ENOENT")return void 0;throw error}}var terminal=state=>state==="completed"||state==="failed"||state==="canceled"||state==="interrupted";var SessionNotFoundError=class extends Error{constructor(){super("no supported session in this directory");this.name="SessionNotFoundError"}};var SessionUnavailableError=class extends Error{constructor(message,cause){super(message,{cause});this.name="SessionUnavailableError"}};var socketUnavailable=error=>["ENOENT","ECONNREFUSED"].includes(error?.code??"");function driverExited(status){const pid=status?.driverPid;if(typeof pid!=="number"||!Number.isSafeInteger(pid)||pid<=0)return false;try{process.kill(pid,0);return false}catch(error){return error.code==="ESRCH"}}function validateSpec(spec){if(!["claude-code","codex","pi","opencode"].includes(spec.agent.kind))throw new Error("unsupported agent");if(!spec.image||!spec.agent.model||!spec.prompt.text)throw new Error("image, model and prompt are required");if(spec.workspace){const url=new URL(spec.workspace.repo);if(url.protocol!=="https:"||url.hostname!=="github.com"||url.username||url.password||url.search||url.hash||!/^\/[\w.-]+\/[\w.-]+\/?$/.test(url.pathname))throw new Error("workspace must be a public GitHub HTTPS repository URL");if(!spec.workspace.ref||spec.workspace.ref.startsWith("-"))throw new Error("invalid repository ref")}for(const value of[spec.limits.turnTimeoutS,spec.limits.maxTurns])if(!Number.isSafeInteger(value)||value<1)throw new Error("limits must be positive integers");if(spec.limits.responseTimeoutS!==null&&(!Number.isSafeInteger(spec.limits.responseTimeoutS)||spec.limits.responseTimeoutS<1))throw new Error("response timeout must be null or a positive integer");const names=new Set;for(const r of spec.resources){if(!["file","archive"].includes(r.kind))throw new Error("unsupported resource kind");if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(r.name)||names.has(r.name))throw new Error("invalid or duplicate resource name");if(!/^[\w.-]+$/.test(r.filename)||r.filename==="."||r.filename==="..")throw new Error("invalid resource filename");if(!/^sha256:[a-f0-9]{64}$/.test(r.digest))throw new Error("invalid resource digest");if(r.use&&r.kind!=="archive")throw new Error("resource use requires an archive");if(r.use&&!["files","skill","npm-package"].includes(r.use.type))throw new Error("unsupported resource use");if(r.use?.type==="npm-package"&&(!/^[\w.-]+\.tgz$/.test(r.use.package)||!["environment","workspace"].includes(r.use.install)))throw new Error("invalid npm input");names.add(r.name)}}async function startSession(options){validateSpec(options.spec);const directory=resolve(options.directory);const credential=await resolveSessionCredential(options.spec,{...options.credentials,now:new Date});await mkdir2(dirname2(directory),{recursive:true});await mkdir2(directory,{mode:448});const engine=new DockerCli;let credentialDir;let created=false;const containerName=`gauge-session-${randomUUID2()}`;try{const runtime=options.runtimeDirectory??tmpdir();await mkdir2(runtime,{recursive:true});credentialDir=await mkdtemp(join2(runtime,"gauge-"));await chmod(credentialDir,448);await mkdir2(join2(credentialDir,"workspace"),{mode:448});const record={version:1,containerName,credentialDir,socketPath:join2(credentialDir,"control.sock"),spec:options.spec,credentialExpiresAt:credential.expiresAt?.toISOString()};if(Buffer.byteLength(record.socketPath)>100)throw new Error("runtimeDirectory is too long for a Unix socket");await writeJsonAtomic(join2(directory,"session.json"),record);const mounts=[{type:"bind",source:join2(credentialDir,"workspace"),target:"/gauge/session",readonly:false}];for(const file of credential.files){const source=join2(credentialDir,file.name);await writeFile(source,file.contents,{mode:384});mounts.push({type:"bind",source,target:file.target,readonly:file.readonly})}for(const resource of options.spec.resources){if(!options.blobsDirectory)throw new Error("blobsDirectory is required for resources");mounts.push({type:"bind",source:resolve(options.blobsDirectory,resource.digest.slice(7)),target:`/gauge/inputs/${resource.name}`,readonly:true})}const script=[prepareScript(options.spec),...credential.exports,`exec ${harnessCommand(options.spec).map(shellQuote).join(" ")}`].join("\n");const result=await engine.create({name:containerName,image:options.spec.image,interactive:true,user:`${process.getuid()}:${process.getgid()}`,labels:{"sh.gauge.session":containerName},mounts,env:{...agentEnv(options.spec.agent.kind),HOME:"/gauge/session/home"},command:["sh","-c",script]});if(result!=="created")throw new Error("session container already exists");created=true;const log=await open2(join2(directory,"driver.log"),"a",384);try{const child=spawn(process.execPath,[fileURLToPath(new URL("./worker.js",import.meta.url)),directory],{detached:true,stdio:["ignore",log.fd,log.fd],env:Object.fromEntries(Object.entries(process.env).filter(([key])=>!/(?:API_KEY|AUTH_TOKEN|OAUTH_TOKEN|ACCESS_TOKEN|REFRESH_TOKEN)$/.test(key)))});const spawned=new Promise((yes,no)=>{child.once("spawn",yes);child.once("error",no)});await spawned;child.unref()}finally{await log.close()}const deadline=Date.now()+1e4;while(Date.now()<deadline){try{return await request(record.socketPath,{action:"status"})}catch{const saved=await readJson(join2(directory,"status.json"));if(saved&&terminal(saved.state))return saved;await new Promise(r=>setTimeout(r,50))}}throw new Error("host session process did not start; see driver.log")}catch(error){if(created){await engine.stop(containerName,2);await engine.remove(containerName)}if(credentialDir)await rm2(credentialDir,{recursive:true,force:true});await writeJsonAtomic(join2(directory,"status.json"),{state:"failed",turn:0,updatedAt:new Date().toISOString(),detail:String(error)});throw error}}async function request(socketPath,command2){return new Promise((resolve2,reject)=>{const socket=createConnection(socketPath);let bytes="";socket.setEncoding("utf8");socket.setTimeout(35e3,()=>socket.destroy(new Error("session command timed out; delivery may have succeeded")));socket.on("error",reject);socket.on("connect",()=>socket.write(JSON.stringify(command2)+"\n"));socket.on("data",chunk=>{bytes+=chunk;if(Buffer.byteLength(bytes)>8*1024*1024){socket.destroy(new Error("session response too large"));return}if(bytes.includes("\n")){try{resolve2(JSON.parse(bytes.slice(0,bytes.indexOf("\n"))))}catch(e){reject(e)}socket.end()}});socket.on("end",()=>{if(!bytes.includes("\n"))reject(new Error("session disconnected before acknowledging command"))})})}async function launchRecord(directory){const record=await readJson(join2(directory,"session.json"));if(!record)throw new SessionNotFoundError;if(record.version!==1)throw new Error("Unsupported session record version");return record}async function getSessionStatus(directory){const record=await launchRecord(directory);const saved=await readJson(join2(directory,"status.json"));if(saved&&terminal(saved.state))return saved;try{return await request(record.socketPath,{action:"status"})}catch(error){const latest=await readJson(join2(directory,"status.json"));if(latest&&terminal(latest.state))return latest;if(!socketUnavailable(error)||!driverExited(latest))throw new SessionUnavailableError("Session status is unavailable; the driver may still be running. Check status again before taking action.",error);return{...latest,state:"interrupted",turn:latest?.turn??0,updatedAt:new Date().toISOString(),detail:"Host session process is unavailable. Stop this session to clean up; prompts are never replayed automatically."}}}async function command(directory,value){const record=await launchRecord(directory);let receipt;try{receipt=await request(record.socketPath,value)}catch(error){throw new SessionUnavailableError("Session command was not acknowledged; delivery may have succeeded. Check status before retrying.",error)}if(!receipt.accepted)throw new Error(receipt.error??"session rejected command");return receipt}var finishSession=(directory,expectedTurn)=>command(directory,{action:"finish",turn:expectedTurn});async function stopSession(directory){const record=await launchRecord(directory);let saved=await readJson(join2(directory,"status.json"));if(saved&&terminal(saved.state)&&!saved.cleanupPending)return;let receipt;try{receipt=await request(record.socketPath,{action:"cancel"})}catch(error){saved=await readJson(join2(directory,"status.json"));if(saved&&terminal(saved.state)&&!saved.cleanupPending)return;if(!socketUnavailable(error)||!driverExited(saved))throw new SessionUnavailableError("Cancellation was not acknowledged; the driver may still be running. Check status before retrying.",error);await cleanupOrphan(directory,record);return}if(!receipt.accepted)throw new Error(receipt.error??"session rejected cancellation");const deadline=Date.now()+3e4;while(Date.now()<deadline){saved=await readJson(join2(directory,"status.json"));if(saved&&terminal(saved.state)){if(saved.cleanupPending)throw new Error(saved.detail??"Cleanup incomplete; call stopSession again after the driver exits");return}if(driverExited(saved)){await cleanupOrphan(directory,record);return}await new Promise(r=>setTimeout(r,100))}throw new SessionUnavailableError("Cancellation was accepted but cleanup is still pending. Check status; the driver retains ownership of cleanup.")}async function cleanupOrphan(directory,record){if(!/^gauge-session-[a-f0-9-]{36}$/.test(record.containerName)||!isAbsolute(record.credentialDir)||!/^gauge-[A-Za-z0-9]+$/.test(basename(record.credentialDir))||record.socketPath!==join2(record.credentialDir,"control.sock"))throw new Error("Refusing cleanup: invalid Gauge runtime ownership record");try{if(!(await lstat(record.credentialDir)).isDirectory())throw new Error("Refusing cleanup: Gauge runtime is not a directory")}catch(error){if(error.code!=="ENOENT")throw error}const engine=new DockerCli;await engine.assertSessionOwner(record.containerName,record.credentialDir);await engine.stop(record.containerName,2);const workspace=await preserveWorkspace(directory,record.credentialDir);await engine.remove(record.containerName);await rm2(record.credentialDir,{recursive:true,force:true});const saved=await readJson(join2(directory,"status.json"));await writeJsonAtomic(join2(directory,"status.json"),{...saved,state:saved&&terminal(saved.state)?saved.state:"interrupted",turn:saved?.turn??0,updatedAt:new Date().toISOString(),question:void 0,cleanupPending:false,detail:saved&&terminal(saved.state)?saved.detail:"Interrupted session cleaned up explicitly",artifacts:workspace?{...saved?.artifacts,workspace}:saved?.artifacts})}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 z2}from"zod";import{z}from"zod";var ERROR_CODES=["unauthorized","forbidden","not_found","invalid_request","insufficient_credits","needs_provider_key","rate_limited","conflict","internal","upgrade_required"];var errorCodeSchema=z.enum(ERROR_CODES);var upgradeOfferSchema=z.object({skuId:z.string(),tierLabel:z.string(),monthlyAmountCents:z.number().int(),monthlyCredits:z.number().int(),billingUrl:z.string()});var errorEnvelopeSchema=z.object({error:z.object({code:errorCodeSchema,message:z.string(),upgrade:upgradeOfferSchema.optional()})});var listQuerySchema=z.object({limit:z.coerce.number().int().min(1).max(200).default(50),cursor:z.string().optional()});function listResponseSchema(item){return z.object({items:z.array(item),nextCursor:z.string().optional()})}var createdBySchema=z.object({userId:z.string().nullable(),email:z.string().nullable(),name:z.string().nullable()}).nullable().optional();var BATTERY_AGENTS=["CLAUDE_CODE","CODEX_CLI","CURSOR","PI","OPENCODE","ANTIGRAVITY"];var BATTERY_CADENCES=["NONE"];var batteryAgentSchema=z2.enum(BATTERY_AGENTS);var BATTERY_MAX_LIMITS={maxTurns:30,wallClockS:5400,maxUsd:10};var MAX_SAMPLES_PER_CYCLE=50;var batteryLimitsSchema=z2.object({maxTurns:z2.number().positive().max(BATTERY_MAX_LIMITS.maxTurns).optional(),wallClockS:z2.number().positive().max(BATTERY_MAX_LIMITS.wallClockS).optional(),maxUsd:z2.number().positive().max(BATTERY_MAX_LIMITS.maxUsd).optional()});var batterySkillRefSchema=z2.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=z2.array(batterySkillRefSchema);var batteryScheduleSpecSchema=z2.object({repoUrl:z2.string().nullish(),repoRef:z2.string().nullish(),model:z2.string().nullable().optional(),agents:z2.array(batteryAgentSchema).optional(),samplesPerCycle:z2.number().int().min(1).max(MAX_SAMPLES_PER_CYCLE).optional(),cadence:z2.enum(BATTERY_CADENCES).optional(),experiment:z2.string().optional(),limits:batteryLimitsSchema.optional(),skills:batterySkillsSchema.optional()});var batteryDefaultsSchema=z2.object({isBranded:z2.boolean().optional(),topic:z2.string().optional(),tags:z2.array(z2.string()).optional(),model:z2.string().nullable().optional(),agents:z2.array(batteryAgentSchema).optional(),samplesPerCycle:z2.number().int().min(1).max(MAX_SAMPLES_PER_CYCLE).optional(),cadence:z2.enum(BATTERY_CADENCES).optional(),limits:batteryLimitsSchema.optional(),skills:batterySkillsSchema.optional()});var batteryPromptSpecSchema=z2.object({key:z2.string().min(1),text:z2.string().min(1),isBranded:z2.boolean().optional(),topic:z2.string().optional(),tags:z2.array(z2.string()).optional(),experiment:z2.string().optional(),schedules:z2.array(batteryScheduleSpecSchema).optional()});var batterySpecSchema=z2.object({version:z2.literal(1),org:z2.string().optional(),experiment:z2.string().optional(),expand:z2.boolean().optional(),defaults:batteryDefaultsSchema.optional(),prompts:z2.array(batteryPromptSpecSchema).min(1)});var batteryPlanScheduleSchema=z2.object({action:z2.enum(["create","update","none"]),repoUrl:z2.string().nullable(),repoRef:z2.string().nullable(),runs:z2.number().int()});var batteryPlanPromptSchema=z2.object({key:z2.string(),action:z2.enum(["create","update"]),schedules:z2.array(batteryPlanScheduleSchema)});var batteryPlanSchema=z2.object({dryRun:z2.literal(true),org:z2.string(),experiment:z2.string().nullable(),expand:z2.boolean(),prompts:z2.array(batteryPlanPromptSchema),summary:z2.object({promptsToCreate:z2.number().int(),promptsToUpdate:z2.number().int(),schedulesToCreate:z2.number().int(),schedulesToUpdate:z2.number().int(),runsToEnqueue:z2.number().int(),runsByAgent:z2.record(z2.string(),z2.number().int()),estimatedCredits:z2.number().int()})});var batteryApplyResponseSchema=z2.object({batchIds:z2.array(z2.string()),runIds:z2.array(z2.string()),experiment:z2.string().nullable(),blocked:z2.enum(["insufficient_credits","needs_provider_key"]).optional()});var batchRunStatusSchema=z2.enum(["QUEUED","CLAIMED","PROVISIONING","RUNNING","SUCCEEDED","FAILED","TIMED_OUT","CANCELED"]);var batchListQuerySchema=listQuerySchema.extend({promptId:z2.string().optional(),experiment:z2.string().optional()});var batchSummarySchema=z2.object({id:z2.string(),promptId:z2.string(),promptText:z2.string(),experiment:z2.string().nullable(),createdAt:z2.string(),runCounts:z2.record(z2.string(),z2.number().int())});var batchListResponseSchema=listResponseSchema(batchSummarySchema);var batchRunSummarySchema=z2.object({id:z2.string(),agent:z2.string(),model:z2.string(),status:batchRunStatusSchema,createdAt:z2.string(),startedAt:z2.string().nullable(),finishedAt:z2.string().nullable()});var batchDetailSchema=z2.object({id:z2.string(),promptId:z2.string(),promptText:z2.string(),scenario:z2.string(),repoUrl:z2.string().nullable(),repoRef:z2.string().nullable(),experiment:z2.string().nullable(),funding:z2.string(),createdAt:z2.string(),runCounts:z2.record(z2.string(),z2.number().int()),runs:z2.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 z3}from"zod";var BRAND_KINDS=["OWNED","COMPETITOR","OTHER"];var brandKindSchema=z3.enum(BRAND_KINDS);var BRAND_PACKAGE_ECOSYSTEMS=["npm","pypi","cargo","go","rubygems","other"];var brandPackageEcosystemSchema=z3.enum(BRAND_PACKAGE_ECOSYSTEMS);var brandPackageSchema=z3.object({name:z3.string(),ecosystem:z3.string().nullable()});var brandSchema=z3.object({id:z3.string(),name:z3.string(),kind:brandKindSchema,source:z3.string(),aliases:z3.array(z3.string()),websites:z3.array(z3.string()),category:z3.string().nullable(),packages:z3.array(brandPackageSchema),createdAt:z3.string(),updatedAt:z3.string()});var brandPackageInputSchema=z3.object({name:z3.string().min(1),ecosystem:brandPackageEcosystemSchema.nullable().optional()});var createBrandBodySchema=z3.object({name:z3.string().min(1),kind:brandKindSchema,aliases:z3.array(z3.string().min(1)).default([]),websites:z3.array(z3.string().min(1)).default([]),packages:z3.array(brandPackageInputSchema).default([])});var updateBrandBodySchema=z3.object({name:z3.string().min(1).optional(),kind:brandKindSchema.optional(),aliases:z3.array(z3.string().min(1)).optional(),websites:z3.array(z3.string().min(1)).optional(),packages:z3.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 z4}from"zod";var FEEDBACK_KINDS=["friction","missing","bug","other"];var feedbackKindSchema=z4.enum(FEEDBACK_KINDS);var createFeedbackBodySchema=z4.object({message:z4.string().trim().min(1).max(4e3),kind:feedbackKindSchema.default("other"),command:z4.string().trim().max(500).optional(),org:z4.string().optional()});var createFeedbackResponseSchema=z4.object({id:z4.string()});var keys_exports={};__export(keys_exports,{PROVIDER_TYPES:()=>PROVIDER_TYPES,providerKeyListResponseSchema:()=>providerKeyListResponseSchema,providerKeySchema:()=>providerKeySchema,providerTypeSchema:()=>providerTypeSchema,setProviderKeyBodySchema:()=>setProviderKeyBodySchema,setProviderKeyResponseSchema:()=>setProviderKeyResponseSchema});import{z as z5}from"zod";var PROVIDER_TYPES=["anthropic","openai"];var providerTypeSchema=z5.enum(PROVIDER_TYPES);var setProviderKeyBodySchema=z5.object({key:z5.string().min(1)});var setProviderKeyResponseSchema=z5.object({providerType:providerTypeSchema,last4:z5.string()});var providerKeySchema=z5.object({providerType:providerTypeSchema,last4:z5.string(),createdAt:z5.string(),updatedAt:z5.string()});var providerKeyListResponseSchema=listResponseSchema(providerKeySchema);var runConfig_exports={};__export(runConfig_exports,{ROSTERABLE_AGENTS:()=>ROSTERABLE_AGENTS,SCHEDULABLE_AGENTS:()=>SCHEDULABLE_AGENTS,agentConfigInputSchema:()=>agentConfigInputSchema,agentConfigSchema:()=>agentConfigSchema,assetRefListSchema:()=>assetRefListSchema,assetRefSchema:()=>assetRefSchema,modelUnits:()=>modelUnits,refAssetName:()=>refAssetName,rosterableAgentSchema:()=>rosterableAgentSchema,runsPerCycle:()=>runsPerCycle,schedulableAgentSchema:()=>schedulableAgentSchema,totalRunsPerCycle:()=>totalRunsPerCycle});import{z as z8}from"zod";import{z as z7}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 z6}from"zod";var ANALYSIS_SCHEMA_VERSION=1;var evidenceSequenceSchema=z6.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=z6.discriminatedUnion("kind",[z6.object({kind:z6.literal("trace"),seq:evidenceSequenceSchema}).strict(),z6.object({kind:z6.literal("diff"),path:z6.string().min(1)}).strict()]);var INSTALL_PHASES=["NONE","ATTEMPTED","CONFIGURED","EXERCISED"];var sessionProductSchema=z6.object({name:z6.string(),mentioned:z6.boolean(),considered:z6.boolean(),recommended:z6.boolean(),chosen:z6.boolean(),rejected:z6.boolean(),abandoned:z6.boolean(),installPhase:z6.enum(INSTALL_PHASES),rank:z6.number().int().nullable(),source:z6.enum(["BRIEF","PERSONA","PRIOR","SEARCH","PAGE","REPO","UNKNOWN"]),reason:z6.string(),categories:z6.array(z6.string()),evidence:z6.record(z6.string(),z6.array(evidenceRefSchema))});var sessionObservationSchema=z6.object({id:z6.string(),kind:z6.enum(["FRICTION","OBJECTION","OPPORTUNITY"]),label:z6.string(),detail:z6.string(),subject:z6.string(),basis:z6.enum(["OBSERVED","AGENT_CLAIM","INFERRED"]),effect:z6.enum(["BLOCKED","RECOVERED","EXTRA_WORK","SELECTION_LOSS","UNKNOWN"]),cause:z6.enum(["PRODUCT","CONTENT","ACCESS","ENVIRONMENT","AGENT","UNKNOWN"]),tags:z6.array(z6.string()),evidence:z6.array(evidenceRefSchema)});var sessionAnalysisSchema=z6.object({schemaVersion:z6.literal(ANALYSIS_SCHEMA_VERSION),instructionsVersion:z6.string().min(1),id:z6.string(),runId:z6.string(),attempt:z6.number().int(),createdAt:z6.string(),origin:z6.enum(["MODEL","LEGACY"]),model:z6.string().nullable(),assessability:z6.enum(["ASSESSED","PARTIAL","UNASSESSABLE"]),limitation:z6.string().nullable(),selection:z6.enum(["MEASURED","UNASSESSABLE","NOT_MEASURED"]),directed:z6.boolean(),products:z6.array(sessionProductSchema),observations:z6.array(sessionObservationSchema)});var artifactPathSchema=z6.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=z6.discriminatedUnion("kind",[z6.object({kind:z6.literal("trace"),seq:evidenceSequenceSchema}).strict(),z6.object({kind:z6.literal("diff"),path:artifactPathSchema}).strict(),z6.object({kind:z6.literal("artifact"),artifact:artifactPathSchema.describe("Path relative to the session attempt directory, for example session/events.ndjson."),attempt:z6.number().int().positive().optional().describe("Must match the analysis attempt; defaults to that attempt."),line:z6.number().int().positive().optional().describe("One-based line number in the original artifact, before any filtering."),endLine:z6.number().int().positive().optional().describe("Inclusive last line of the evidence range."),seq:evidenceSequenceSchema.optional()}).strict().superRefine((ref,ctx)=>{if(ref.line===void 0&&ref.seq===void 0)ctx.addIssue({code:"custom",message:"Artifact evidence needs a line or seq"});if(ref.endLine!==void 0&&(ref.line===void 0||ref.endLine<ref.line))ctx.addIssue({code:"custom",path:["endLine"],message:"endLine requires line and must be at least line"})})]);var findingSubmissionSchema=sessionObservationSchema.omit({id:true}).extend({label:z6.string().trim().min(1).max(200),detail:z6.string().trim().min(1).max(1e4),subject:z6.string().trim().min(1).max(200),tags:z6.array(z6.string().trim().min(1).max(64)).max(32).default([]),evidence:z6.array(portableEvidenceRefSchema).min(1).max(100)}).strict();var criterionAnalysisSubmissionSchema=z6.object({criterionId:z6.string().min(1),outcome:z6.enum(["PASS","FAIL","UNASSESSABLE"]),label:z6.string().trim().min(1).max(1e4),evidence:z6.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:z6.string().trim().min(1).max(200),evidence:z6.record(z6.string(),z6.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=z6.object({schemaVersion:z6.literal(ANALYSIS_SCHEMA_VERSION),attempt:z6.number().int().positive().default(1),instructionsVersion:z6.string().trim().min(1),analyst:z6.object({name:z6.string().trim().min(1),model:z6.string().trim().min(1).optional()}).strict(),assessability:sessionAnalysisSchema.shape.assessability,limitation:z6.string().trim().min(1).nullable().default(null),selection:sessionAnalysisSchema.shape.selection.default("NOT_MEASURED"),directed:z6.boolean().default(false),findings:z6.array(findingSubmissionSchema).max(1e3).default([]),products:z6.array(productSubmissionSchema).max(1e3).default([]),criteria:z6.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=z7.enum(RUN_STATUSES);var AGENTS=["CLAUDE_CODE","CODEX_CLI","CURSOR","PI","OPENCODE","ANTIGRAVITY"];var agentSchema=z7.enum(AGENTS);var OBSERVED_PROVIDER_SOURCES=["AGENT_STREAM","GATEWAY_RESPONSE","GATEWAY_AUDIT","CANARY"];var observedProviderSourceSchema=z7.enum(OBSERVED_PROVIDER_SOURCES);var selectedProviderSchema=z7.object({slug:z7.string(),displayName:z7.string()});var observedProviderSchema=z7.object({slug:z7.string(),source:observedProviderSourceSchema});var RUN_TRIGGER_SOURCES=["UNKNOWN","UI","API","CADENCE","STAFF","OPERATOR","GITHUB"];var runTriggerSourceSchema=z7.enum(RUN_TRIGGER_SOURCES);var runTriggeredBySchema=z7.object({source:runTriggerSourceSchema,userId:z7.string().nullable(),email:z7.string().nullable()});var runOptimizationTrialSchema=z7.object({optimizationId:z7.string(),trialId:z7.string(),key:z7.string(),title:z7.string(),kind:z7.enum(INTERVENTION_KINDS)});var runCreditsChargedSchema=z7.number().int().nullable();var runStatusFilterSchema=z7.string().transform(raw=>raw.split(",").map(s=>s.trim().toUpperCase()).filter(Boolean)).pipe(z7.array(runStatusSchema).min(1));var runListQuerySchema=listQuerySchema.extend({status:runStatusFilterSchema.optional(),batch:z7.string().optional(),prompt:z7.string().optional(),experiment:z7.string().optional(),evalSet:z7.string().optional(),since:z7.string().optional()});var runListItemSchema=z7.object({id:z7.string(),status:runStatusSchema,agent:agentSchema,model:z7.string(),resolvedModel:z7.string().nullable().optional(),modelDisplayName:z7.string().nullable().optional(),selectedProvider:selectedProviderSchema.nullable().optional(),observedProvider:observedProviderSchema.nullable().optional(),promptId:z7.string(),promptSnippet:z7.string(),batchId:z7.string(),experiment:z7.string().nullable(),evalSetId:z7.string().nullable(),evalRevision:z7.string().optional(),optimizationTrial:runOptimizationTrialSchema.nullable().optional(),turns:z7.number().int().nullable(),usdCost:z7.number().nullable(),creditsCharged:runCreditsChargedSchema.optional(),triggeredBy:runTriggeredBySchema.optional(),durationMs:z7.number().int().nullable(),exitReason:z7.string().nullable(),createdAt:z7.string(),startedAt:z7.string().nullable(),finishedAt:z7.string().nullable(),parentRunId:z7.string().nullable(),fetchForkPlanId:z7.string().nullable()});var runListResponseSchema=listResponseSchema(runListItemSchema);var runSkillSchema=z7.discriminatedUnion("source",[z7.object({source:z7.literal("saved"),skillId:z7.string(),name:z7.string(),label:z7.string()}),z7.object({source:z7.literal("input"),name:z7.string(),commit:z7.string().nullable(),pullNumber:z7.number().int().nullable()})]);var runDetailSchema=runListItemSchema.omit({promptSnippet:true}).extend({promptText:z7.string(),attempt:z7.number().int(),cancelRequested:z7.boolean(),failureReason:z7.string().nullable(),repoUrl:z7.string().nullable(),repoRef:z7.string().nullable(),scenario:z7.string(),funding:z7.string(),usage:z7.unknown().nullable(),hasDiff:z7.boolean(),claimedAt:z7.string().nullable(),criterionResults:z7.array(z7.object({criterionId:z7.string().nullable(),name:z7.string(),passed:z7.boolean().nullable(),reasoning:z7.string().nullable()})),skills:z7.array(runSkillSchema).optional()});var cancelRunResponseSchema=z7.object({id:z7.string(),status:runStatusSchema,cancelRequested:z7.boolean(),note:z7.string().optional()});var regradeRunResponseSchema=z7.object({runId:z7.string(),evalSetId:z7.string().nullable(),criteria:z7.number().int()});var RUN_INSIGHT_STATUSES=["PENDING","RUNNING","COMPLETE","FAILED","SKIPPED"];var runInsightStatusSchema=z7.enum(RUN_INSIGHT_STATUSES);var insightPassSchema=z7.object({status:runInsightStatusSchema,model:z7.string().nullable(),inputTokens:z7.number().int().nullable(),outputTokens:z7.number().int().nullable(),usdCost:z7.number().nullable(),error:z7.string().nullable()});var runDecisionSchema=z7.object({index:z7.number().int(),category:z7.string(),categoryRaw:z7.string().nullable(),chosenName:z7.string(),chosenEcosystem:z7.string().nullable(),chosenPackage:z7.string().nullable(),reversed:z7.boolean(),detail:z7.unknown()});var RUN_INSIGHT_PASS_KINDS=["ANALYSIS","CLI_DISCOVERY","LEVER","EXPERIMENT_DELTA"];var runInsightPassKindSchema=z7.enum(RUN_INSIGHT_PASS_KINDS);var insightPipelinePassSchema=insightPassSchema.extend({kind:runInsightPassKindSchema});var runInsightResponseSchema=z7.object({runId:z7.string(),decision:insightPassSchema,passes:z7.array(insightPipelinePassSchema),decisions:z7.array(runDecisionSchema),experimentDelta:z7.unknown().nullable(),visibilityVerdict:z7.unknown().nullable(),analysis:sessionAnalysisSchema.nullable()});var runEventSchema=z7.looseObject({run_id:z7.string(),seq:z7.number(),turn:z7.number(),ts:z7.string(),type:z7.string()});var runCompareSideSchema=z7.object({runRequest:z7.string().min(1).optional(),batch:z7.array(z7.string().min(1)).min(1).max(100).optional(),evalSet:z7.string().min(1).optional(),evalRevision:z7.string().min(1).optional(),trial:z7.string().min(1).optional(),experiment:z7.string().min(1).optional(),agent:z7.array(agentSchema).min(1).optional(),model:z7.array(z7.string()).min(1).optional(),since:z7.string().optional(),until:z7.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=z7.object({baseline:runCompareSideSchema,candidate:runCompareSideSchema}).strict();var runCompareStatsSchema=z7.object({runs:z7.number().int(),finished:z7.number().int(),succeeded:z7.number().int(),judged:z7.number().int(),passed:z7.number().int(),passRate:z7.number().nullable(),medianTurns:z7.number().nullable(),medianUsdCost:z7.number().nullable(),medianDurationMs:z7.number().nullable(),criteria:z7.array(z7.object({name:z7.string(),judged:z7.number().int(),passed:z7.number().int(),passRate:z7.number().nullable()}))});var runCompareDeltaSchema=z7.object({passRate:z7.number().nullable(),medianTurns:z7.number().nullable(),medianUsdCost:z7.number().nullable(),medianDurationMs:z7.number().nullable(),criteria:z7.array(z7.object({name:z7.string(),passRate:z7.number().nullable()}))});var runCompareRowSchema=z7.object({baseline:runCompareStatsSchema,candidate:runCompareStatsSchema,delta:runCompareDeltaSchema});var runCompareMixedRevisionSchema=z7.object({evalSetId:z7.string().nullable(),promptId:z7.string().nullable(),revisions:z7.array(z7.string())});var runCompareTrialSchema=runOptimizationTrialSchema.extend({runs:z7.number().int()});var runCompareResponseSchema=z7.object({overall:runCompareRowSchema,targets:z7.array(runCompareRowSchema.extend({agent:agentSchema,model:z7.string()})),sides:z7.object({baseline:z7.object({evalRevisions:z7.array(z7.string()),mixedRevisions:z7.array(runCompareMixedRevisionSchema).optional(),truncated:z7.boolean(),trials:z7.array(runCompareTrialSchema).optional()}),candidate:z7.object({evalRevisions:z7.array(z7.string()),mixedRevisions:z7.array(runCompareMixedRevisionSchema).optional(),truncated:z7.boolean(),trials:z7.array(runCompareTrialSchema).optional()})})});var SCHEDULABLE_AGENTS=["CLAUDE_CODE","CODEX_CLI","PI","OPENCODE"];var schedulableAgentSchema=z8.enum(SCHEDULABLE_AGENTS);var ROSTERABLE_AGENTS=[...SCHEDULABLE_AGENTS,"ANTIGRAVITY"];var rosterableAgentSchema=z8.enum(ROSTERABLE_AGENTS);var agentConfigSchema=z8.object({agent:agentSchema,models:z8.array(z8.string().min(1))});var agentConfigInputSchema=z8.object({agent:rosterableAgentSchema,models:z8.array(z8.string().min(1)).default([])});var assetRefSchema=z8.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=z8.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(agents2){return agents2.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)}import{chmodSync,mkdirSync,readFileSync,rmSync,writeFileSync}from"fs";import{join as join3}from"path";function credentialsPath(){return join3(configDir(),"credentials")}function resolveToken(){const fromEnv=process.env.GAUGE_API_TOKEN?.trim();if(fromEnv)return fromEnv;try{const stored=readFileSync(credentialsPath(),"utf8").trim();return stored||null}catch{return null}}function saveToken(token){mkdirSync(configDir(),{recursive:true,mode:448});writeFileSync(credentialsPath(),`${token.trim()}
|
|
3
|
+
`,{encoding:"utf8",mode:384});chmodSync(credentialsPath(),384)}function clearToken(){rmSync(credentialsPath(),{force:true})}var DEFAULT_API_URL="https://agents.withgauge.com";var USER_AGENT=`gauge-cli/${CLI_VERSION}`;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;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}};function resolveBaseUrl(){return process.env.GAUGE_API_URL||readConfig().apiUrl||DEFAULT_API_URL}var ApiClient=class{baseUrl;token;authOptional;constructor(options={}){this.baseUrl=(options.baseUrl??resolveBaseUrl()).replace(/\/+$/,"");this.token=options.token!==void 0?options.token:resolveToken();this.authOptional=options.authOptional??false}get signedIn(){return this.token!==null}async get(path,query){return this.request("GET",path,{query})}async post(path,body,query){return this.request("POST",path,{body,query})}async patch(path,body,query){return this.request("PATCH",path,{body,query})}async put(path,body,query){return this.request("PUT",path,{body,query})}async delete(path,query){return this.request("DELETE",path,{query})}async sse(path,onEvent,options={}){const res=await this.fetch(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(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 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.fetch(this.url(path,options.query),{method,headers,body:options.body===void 0?void 0:JSON.stringify(options.body)});if(!res.ok)throw await this.toError(res);if(res.status===204)return void 0;const text=await res.text();if(!text)return void 0;const contentType=res.headers.get("content-type")??"";if(contentType.includes("application/json")){return JSON.parse(text)}return text}async toError(res){const wait=res.status===429?retryAfterSeconds(res):void 0;const hint=wait===void 0?void 0:`Try again in ${wait} s.`;try{const parsed=errorEnvelopeSchema.safeParse(await res.clone().json());if(parsed.success){return new CliError(parsed.data.error.code,parsed.data.error.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})}};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)}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=""){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{existsSync as existsSync2,statSync as statSync2}from"fs";import{lstat as lstat2,readdir,readFile as readFile4,writeFile as writeFile2}from"fs/promises";import{join as join5}from"path";import{randomUUID as randomUUID3}from"crypto";import{chmodSync as chmodSync2,existsSync,mkdirSync as mkdirSync2,readdirSync,readFileSync as readFileSync2,statSync}from"fs";import{createRequire as createRequire2}from"module";import{join as join4}from"path";var LOCAL_DATABASE_VERSION=1;var schema=`
|
|
4
4
|
CREATE TABLE measurements (
|
|
5
5
|
id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK(kind IN ('eval','preference')),
|
|
6
6
|
revision INTEGER NOT NULL, definition TEXT NOT NULL,
|
|
@@ -62,9 +62,9 @@ PRAGMA user_version = 1;
|
|
|
62
62
|
input_tokens=COALESCE(excluded.input_tokens,sessions.input_tokens),output_tokens=COALESCE(excluded.output_tokens,sessions.output_tokens),
|
|
63
63
|
configuration=CASE WHEN excluded.configuration='{}' THEN sessions.configuration ELSE excluded.configuration END,
|
|
64
64
|
provenance=CASE WHEN excluded.provenance='{}' THEN sessions.provenance ELSE excluded.provenance END
|
|
65
|
-
WHERE excluded.attempt >= sessions.attempt`).run(input.id,input.batchId,input.launchId??null,input.measurementId??null,input.measurementKind??null,input.measurementRevision??null,input.case,input.agent,input.model,input.attempt,input.outcome,input.endedBy,input.turns,input.createdAt,input.endedAt,input.durationMs??null,input.inputTokens??null,input.outputTokens??null,json(input.configuration??{}),json(input.provenance??{}));return this.getSession(input.id)}getSession(id){const row=this.db.prepare("SELECT * FROM sessions WHERE id = ?").get(id);return row?session(row):void 0}listSessions(filter={}){const conditions=[];const values=[];for(const[key,column]of[["measurementId","measurement_id"],["measurementKind","measurement_kind"],["batchId","batch_id"]]){if(filter[key]!==void 0){conditions.push(`${column} = ?`);values.push(filter[key])}}return this.db.prepare(`SELECT * FROM sessions${conditions.length?` WHERE ${conditions.join(" AND ")}`:""} ORDER BY COALESCE(ended_at,created_at) DESC,id`).all(...values).map(session)}repairSessionSummaries(ids){const runs=join4(this.gaugeDir,"runs");if(!existsSync(runs))return{repaired:0,skipped:[]};let repaired=0;const skipped=[];for(const entry of readdirSync(runs,{withFileTypes:true})){if(!entry.isDirectory()||ids&&!ids.includes(entry.name))continue;const attempts=join4(runs,entry.name,"attempts");if(!existsSync(attempts))continue;const n=readdirSync(attempts).map(Number).filter(n2=>Number.isInteger(n2)&&n2>0).sort((a,b)=>b-a)[0];if(n===void 0)continue;try{const directory=join4(attempts,String(n));const spec=object(readJson2(join4(directory,"spec.json")));const attempt=object(spec.attempt);const agent=object(spec.agent);if(attempt.runId!==entry.name||attempt.n!==n||typeof attempt.batchId!=="string"||typeof agent.kind!=="string"||typeof agent.model!=="string")throw new Error("invalid spec.json");const result=object(readJson2(join4(directory,"result.json")));const status=object(readJson2(join4(directory,"session","status.json")));const item=object(spec.case);const association=object(spec.measurement);const previous=this.getSession(entry.name);const createdAt=typeof spec.createdAt==="string"?spec.createdAt:previous?.createdAt??statSync(join4(directory,"spec.json")).mtime.toISOString();this.upsertSession({id:entry.name,batchId:attempt.batchId,launchId:typeof spec.launchId==="string"?spec.launchId:null,measurementId:typeof association.id==="string"?association.id:null,measurementKind:association.kind==="eval"||association.kind==="preference"?association.kind:null,measurementRevision:typeof association.revision==="number"?association.revision:null,case:typeof item.path==="string"?item.path:null,agent:typeof spec.agentName==="string"?spec.agentName:agent.kind,model:agent.model,attempt:n,outcome:String(result.outcome??status.state??"queued"),endedBy:typeof result.endedBy==="string"?result.endedBy:null,turns:typeof result.turns==="number"?result.turns:typeof status.turn==="number"?status.turn:null,createdAt,endedAt:typeof result.endedAt==="string"?result.endedAt:null,durationMs:numberOrNull(result.durationMs),inputTokens:numberOrNull(result.inputTokens),outputTokens:numberOrNull(result.outputTokens),configuration:{...object(spec.configuration),case:item},provenance:object(spec.provenance)});repaired++}catch(error){skipped.push(`${entry.name}: ${error instanceof Error?error.message:String(error)}`)}}return{repaired,skipped}}};function numberOrNull(value){return typeof value==="number"&&Number.isFinite(value)?value:null}function readJson2(path){try{return JSON.parse(readFileSync2(path,"utf8"))}catch(error){if(error.code==="ENOENT")return void 0;throw error}}function normalizeDefinition(definition){if(!definition.name?.trim()||!definition.promptText?.trim())throw new CliError("usage","A local measurement requires a nonempty name and promptText.");if(definition.tags&&(!Array.isArray(definition.tags)||definition.tags.some(tag=>typeof tag!=="string"||!tag.trim())))throw new CliError("usage","Measurement tags must be nonempty strings.");for(const key of["id","measurementKind","revision","createdAt","updatedAt"]){if(key in definition)throw new CliError("usage",`Measurement field ${key} is assigned by Gauge.`)}return{...definition,tags:[...new Set(definition.tags??[])]}}function measurement(row){return{...parse(row.definition),id:String(row.id),measurementKind:row.kind,revision:Number(row.revision),createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function session(row){return{id:String(row.id),batchId:String(row.batch_id),launchId:row.launch_id,measurementId:row.measurement_id,measurementKind:row.measurement_kind,measurementRevision:row.measurement_revision,case:row.case_path,agent:String(row.agent),model:String(row.model),attempt:Number(row.attempt),outcome:String(row.outcome),endedBy:row.ended_by,turns:row.turns,createdAt:String(row.created_at),endedAt:row.ended_at,durationMs:row.duration_ms,inputTokens:row.input_tokens,outputTokens:row.output_tokens,configuration:parse(row.configuration),provenance:parse(row.provenance),currentAnalysisId:row.current_analysis_id,analyzed:row.current_analysis_id!==null}}function openLocalStore(gaugeDir){mkdirSync2(gaugeDir,{recursive:true,mode:448});const path=join4(gaugeDir,"gauge.sqlite");const{DatabaseSync:SQLite}=loadSQLite();const db=new SQLite(path);try{chmodSync2(path,384);db.exec("PRAGMA busy_timeout = 5000; PRAGMA foreign_keys = ON;");const version=Number(db.prepare("PRAGMA user_version").get().user_version);if(version>LOCAL_DATABASE_VERSION)throw new CliError("usage",`This workspace uses database version ${version}; this CLI supports ${LOCAL_DATABASE_VERSION}. Upgrade Gauge. Your data has not been changed.`);db.exec("PRAGMA journal_mode = WAL;");if(version===0){db.exec("BEGIN IMMEDIATE");try{if(Number(db.prepare("PRAGMA user_version").get().user_version)===0)db.exec(schema);db.exec("COMMIT")}catch(error){db.exec("ROLLBACK");throw error}}return new LocalStore(gaugeDir,db)}catch(error){db.close();throw error}}function loadSQLite(){const emitWarning=process.emitWarning;process.emitWarning=(warning,...args)=>{if(warning==="SQLite is an experimental feature and might change at any time"&&args[0]==="ExperimentalWarning")return;Reflect.apply(emitWarning,process,[warning,...args])};try{return createRequire2(import.meta.url)("node:sqlite")}finally{process.emitWarning=emitWarning}}function localId(id){if(!/^[a-zA-Z0-9_-]+$/.test(id))throw new CliError("usage","Invalid local ID");return id}var batchDirectory=(gaugeDir,id)=>join5(gaugeDir,"batches",localId(id));var cancellationRequested=directory=>existsSync2(join5(directory,"cancel"));async function directories(path){try{if(!(await lstat2(path)).isDirectory())return[];return(await readdir(path,{withFileTypes:true})).filter(d=>d.isDirectory()).map(d=>d.name)}catch(error){if(error.code==="ENOENT")return[];throw error}}async function localSessions(gaugeDir){const sessions=[];for(const id of await directories(join5(gaugeDir,"runs"))){const attempts=join5(gaugeDir,"runs",id,"attempts");for(const n of await directories(attempts)){const attempt=join5(attempts,n);try{if(!(await lstat2(join5(attempt,"spec.json"))).isFile())continue;const spec=JSON.parse(await readFile4(join5(attempt,"spec.json"),"utf8"));if(spec.attempt?.runId!==id||String(spec.attempt.n)!==n||typeof spec.attempt.batchId!=="string")continue;const directory=join5(attempt,"session");if(existsSync2(directory)&&!(await lstat2(directory)).isDirectory())continue;sessions.push({id,batchId:spec.attempt.batchId,directory})}catch(error){if(!(error instanceof SyntaxError)&&error.code!=="ENOENT")throw error}}}return sessions}async function localStatus(gaugeDir,filter={}){const sessions=(await localSessions(gaugeDir)).filter(s=>(!filter.id||s.id===filter.id)&&(!filter.batch||s.batchId===filter.batch));return Promise.all(sessions.map(async session2=>{try{const status=await getSessionStatus(session2.directory);return{id:session2.id,batchId:session2.batchId,state:status.state,turns:status.turn,cleanupPending:status.cleanupPending??false,detail:status.detail}}catch(error){if(!existsSync2(join5(session2.directory,"session.json"))){try{const result=JSON.parse(await readFile4(join5(session2.directory,"..","result.json"),"utf8"));return{id:session2.id,batchId:session2.batchId,state:result.outcome,turns:result.turns,detail:result.detail}}catch{}}return{id:session2.id,batchId:session2.batchId,state:"unavailable",detail:String(error)}}}))}async function cancelLocal(gaugeDir,filter){if(Boolean(filter.id)===Boolean(filter.batch))throw new CliError("usage","Pass a run ID or --batch <batch-id>");if(filter.id)localId(filter.id);if(filter.batch)localId(filter.batch);const sessions=(await localSessions(gaugeDir)).filter(s=>filter.id?s.id===filter.id:s.batchId===filter.batch);if(filter.batch){const directory=batchDirectory(gaugeDir,filter.batch);if(existsSync2(directory)){if(!(await lstat2(directory)).isDirectory())throw new CliError("usage","Refusing a linked batch directory");await writeFile2(join5(directory,"cancel"),"",{mode:384})}else if(!sessions.length)throw new CliError("not_found","Local batch not found")}else if(!sessions.length)throw new CliError("not_found","Local run not found");for(const session2 of sessions)await writeFile2(join5(session2.directory,"..","cancel"),"",{mode:384});return Promise.all(sessions.map(async session2=>{try{await stopSession(session2.directory);return{id:session2.id,status:"stopped"}}catch(error){return{id:session2.id,status:"pending",detail:String(error)}}}))}async function cleanupLocal(gaugeDir){const results=[];for(const session2 of await localSessions(gaugeDir)){if(!existsSync2(join5(session2.directory,"session.json")))continue;try{const status=await getSessionStatus(session2.directory);if(status.state!=="interrupted"&&!status.cleanupPending)continue;await stopSession(session2.directory);const final=await getSessionStatus(session2.directory);try{await writeFile2(join5(session2.directory,"..","result.json"),JSON.stringify({outcome:final.state,endedBy:"recovery",turns:final.turn,endedAt:final.updatedAt,detail:final.detail})+"\n",{flag:"wx",mode:384})}catch(error){if(error.code!=="EEXIST")throw error}const store=openLocalStore(gaugeDir);try{const{skipped}=store.repairSessionSummaries([session2.id]);if(skipped.length)throw new Error(skipped.join("; "))}finally{store.close()}results.push({id:session2.id,status:"cleaned"})}catch(error){results.push({id:session2.id,status:"error",detail:String(error)})}}return results}async function localBatchStatus(gaugeDir,id){const directory=batchDirectory(gaugeDir,id);const status=JSON.parse(await readFile4(join5(directory,"status.json"),"utf8"));if(status.state==="running"&&Number.isSafeInteger(status.supervisorPid)&&status.supervisorPid>0){try{process.kill(status.supervisorPid,0)}catch(error){if(error.code==="ESRCH")status.state="interrupted"}}return{...status,cancelRequested:cancellationRequested(directory)}}import{fileURLToPath as fileURLToPath2}from"url";import{mkdirSync as mkdirSync3,readFileSync as readFileSync3,renameSync,writeFileSync as writeFileSync2}from"fs";import{randomBytes}from"crypto";import{homedir}from"os";import{join as join6}from"path";import{z as z9}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=z9.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);var profileSchema=z9.object({agent:z9.enum(agents),provider:z9.enum(["anthropic","openai","openai-codex","fireworks","openrouter"]),auth:z9.enum(["api_key","access_token","setup_token"]),env:variable.optional()}).strict();var storeSchema=z9.object({version:z9.literal(1),profiles:z9.record(z9.string(),profileSchema),defaults:z9.record(z9.string(),z9.string())}).strict();var API_KEY_ENV2={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",fireworks:"FIREWORKS_API_KEY",openrouter:"OPENROUTER_API_KEY"};var profilePath=()=>join6(configDir(),"local-profiles.json");function readProfiles(){let raw;try{raw=readFileSync3(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){mkdirSync3(configDir(),{recursive:true,mode:448});const temporary=`${profilePath()}.${randomBytes(6).toString("hex")}.tmp`;writeFileSync2(temporary,`${JSON.stringify(storeSchema.parse(store),null,2)}
|
|
65
|
+
WHERE excluded.attempt >= sessions.attempt`).run(input.id,input.batchId,input.launchId??null,input.measurementId??null,input.measurementKind??null,input.measurementRevision??null,input.case,input.agent,input.model,input.attempt,input.outcome,input.endedBy,input.turns,input.createdAt,input.endedAt,input.durationMs??null,input.inputTokens??null,input.outputTokens??null,json(input.configuration??{}),json(input.provenance??{}));return this.getSession(input.id)}getSession(id){const row=this.db.prepare("SELECT * FROM sessions WHERE id = ?").get(id);return row?session(row):void 0}listSessions(filter={}){const conditions=[];const values=[];for(const[key,column]of[["measurementId","measurement_id"],["measurementKind","measurement_kind"],["batchId","batch_id"]]){if(filter[key]!==void 0){conditions.push(`${column} = ?`);values.push(filter[key])}}return this.db.prepare(`SELECT * FROM sessions${conditions.length?` WHERE ${conditions.join(" AND ")}`:""} ORDER BY COALESCE(ended_at,created_at) DESC,id`).all(...values).map(session)}repairSessionSummaries(ids){const runs=join4(this.gaugeDir,"runs");if(!existsSync(runs))return{repaired:0,skipped:[]};let repaired=0;const skipped=[];for(const entry of readdirSync(runs,{withFileTypes:true})){if(!entry.isDirectory()||ids&&!ids.includes(entry.name))continue;const attempts=join4(runs,entry.name,"attempts");if(!existsSync(attempts))continue;const n=readdirSync(attempts).map(Number).filter(n2=>Number.isInteger(n2)&&n2>0).sort((a,b)=>b-a)[0];if(n===void 0)continue;try{const directory=join4(attempts,String(n));const spec=object(readJson2(join4(directory,"spec.json")));const attempt=object(spec.attempt);const agent=object(spec.agent);if(attempt.runId!==entry.name||attempt.n!==n||typeof attempt.batchId!=="string"||typeof agent.kind!=="string"||typeof agent.model!=="string")throw new Error("invalid spec.json");const result=object(readJson2(join4(directory,"result.json")));const status=object(readJson2(join4(directory,"session","status.json")));const item=object(spec.case);const association=object(spec.measurement);const previous=this.getSession(entry.name);const createdAt=typeof spec.createdAt==="string"?spec.createdAt:previous?.createdAt??statSync(join4(directory,"spec.json")).mtime.toISOString();this.upsertSession({id:entry.name,batchId:attempt.batchId,launchId:typeof spec.launchId==="string"?spec.launchId:null,measurementId:typeof association.id==="string"?association.id:null,measurementKind:association.kind==="eval"||association.kind==="preference"?association.kind:null,measurementRevision:typeof association.revision==="number"?association.revision:null,case:typeof item.path==="string"?item.path:null,agent:typeof spec.agentName==="string"?spec.agentName:agent.kind,model:agent.model,attempt:n,outcome:String(result.outcome??status.state??"queued"),endedBy:typeof result.endedBy==="string"?result.endedBy:null,turns:typeof result.turns==="number"?result.turns:typeof status.turn==="number"?status.turn:null,createdAt,endedAt:typeof result.endedAt==="string"?result.endedAt:null,durationMs:numberOrNull(result.durationMs),inputTokens:numberOrNull(result.inputTokens),outputTokens:numberOrNull(result.outputTokens),configuration:{...object(spec.configuration),case:item},provenance:object(spec.provenance)});repaired++}catch(error){skipped.push(`${entry.name}: ${error instanceof Error?error.message:String(error)}`)}}return{repaired,skipped}}};function numberOrNull(value){return typeof value==="number"&&Number.isFinite(value)?value:null}function readJson2(path){try{return JSON.parse(readFileSync2(path,"utf8"))}catch(error){if(error.code==="ENOENT")return void 0;throw error}}function normalizeDefinition(definition){if(!definition.name?.trim()||!definition.promptText?.trim())throw new CliError("usage","A local measurement requires a nonempty name and promptText.");if(definition.tags&&(!Array.isArray(definition.tags)||definition.tags.some(tag=>typeof tag!=="string"||!tag.trim())))throw new CliError("usage","Measurement tags must be nonempty strings.");for(const key of["id","measurementKind","revision","createdAt","updatedAt"]){if(key in definition)throw new CliError("usage",`Measurement field ${key} is assigned by Gauge.`)}return{...definition,tags:[...new Set(definition.tags??[])]}}function measurement(row){return{...parse(row.definition),id:String(row.id),measurementKind:row.kind,revision:Number(row.revision),createdAt:String(row.created_at),updatedAt:String(row.updated_at)}}function session(row){return{id:String(row.id),batchId:String(row.batch_id),launchId:row.launch_id,measurementId:row.measurement_id,measurementKind:row.measurement_kind,measurementRevision:row.measurement_revision,case:row.case_path,agent:String(row.agent),model:String(row.model),attempt:Number(row.attempt),outcome:String(row.outcome),endedBy:row.ended_by,turns:row.turns,createdAt:String(row.created_at),endedAt:row.ended_at,durationMs:row.duration_ms,inputTokens:row.input_tokens,outputTokens:row.output_tokens,configuration:parse(row.configuration),provenance:parse(row.provenance),currentAnalysisId:row.current_analysis_id,analyzed:row.current_analysis_id!==null}}function openLocalStore(gaugeDir){mkdirSync2(gaugeDir,{recursive:true,mode:448});const path=join4(gaugeDir,"gauge.sqlite");const{DatabaseSync:SQLite}=loadSQLite();const db=new SQLite(path);try{chmodSync2(path,384);db.exec("PRAGMA busy_timeout = 5000; PRAGMA foreign_keys = ON;");const version=Number(db.prepare("PRAGMA user_version").get().user_version);if(version>LOCAL_DATABASE_VERSION)throw new CliError("usage",`This workspace uses database version ${version}; this CLI supports ${LOCAL_DATABASE_VERSION}. Upgrade Gauge. Your data has not been changed.`);db.exec("PRAGMA journal_mode = WAL;");if(version===0){db.exec("BEGIN IMMEDIATE");try{if(Number(db.prepare("PRAGMA user_version").get().user_version)===0)db.exec(schema);db.exec("COMMIT")}catch(error){db.exec("ROLLBACK");throw error}}return new LocalStore(gaugeDir,db)}catch(error){db.close();throw error}}function loadSQLite(){const emitWarning=process.emitWarning;process.emitWarning=(warning,...args)=>{if(warning==="SQLite is an experimental feature and might change at any time"&&args[0]==="ExperimentalWarning")return;Reflect.apply(emitWarning,process,[warning,...args])};try{return createRequire2(import.meta.url)("node:sqlite")}finally{process.emitWarning=emitWarning}}function localId(id){if(!/^[a-zA-Z0-9_-]+$/.test(id))throw new CliError("usage","Invalid local ID");return id}var batchDirectory=(gaugeDir,id)=>join5(gaugeDir,"batches",localId(id));var cancellationRequested=directory=>existsSync2(join5(directory,"cancel"));async function directories(path){try{if(!(await lstat2(path)).isDirectory())return[];return(await readdir(path,{withFileTypes:true})).filter(d=>d.isDirectory()).map(d=>d.name)}catch(error){if(error.code==="ENOENT")return[];throw error}}async function localSessions(gaugeDir){const sessions=[];for(const id of await directories(join5(gaugeDir,"runs"))){const attempts=join5(gaugeDir,"runs",id,"attempts");for(const n of await directories(attempts)){const attempt=join5(attempts,n);try{if(!(await lstat2(join5(attempt,"spec.json"))).isFile())continue;const spec=JSON.parse(await readFile4(join5(attempt,"spec.json"),"utf8"));if(spec.attempt?.runId!==id||String(spec.attempt.n)!==n||typeof spec.attempt.batchId!=="string")continue;const directory=join5(attempt,"session");if(existsSync2(directory)&&!(await lstat2(directory)).isDirectory())continue;sessions.push({id,batchId:spec.attempt.batchId,directory})}catch(error){if(!(error instanceof SyntaxError)&&error.code!=="ENOENT")throw error}}}return sessions}async function resultDetail(directory){try{const result=JSON.parse(await readFile4(join5(directory,"..","result.json"),"utf8"));return typeof result.detail==="string"?result.detail:void 0}catch{return}}function stderrLog(directory,state){if(state!=="failed")return;const path=join5(directory,"agent.stderr.log");try{return statSync2(path).size?path:void 0}catch{return}}async function localStatus(gaugeDir,filter={}){const sessions=(await localSessions(gaugeDir)).filter(s=>(!filter.id||s.id===filter.id)&&(!filter.batch||s.batchId===filter.batch));return Promise.all(sessions.map(async session2=>{try{const status=await getSessionStatus(session2.directory);return{id:session2.id,batchId:session2.batchId,state:status.state,turns:status.turn,cleanupPending:status.cleanupPending??false,detail:status.detail??await resultDetail(session2.directory),stderrLog:stderrLog(session2.directory,status.state)}}catch(error){if(!existsSync2(join5(session2.directory,"session.json"))){try{const result=JSON.parse(await readFile4(join5(session2.directory,"..","result.json"),"utf8"));return{id:session2.id,batchId:session2.batchId,state:result.outcome,turns:result.turns,detail:result.detail,stderrLog:stderrLog(session2.directory,result.outcome)}}catch{}}return{id:session2.id,batchId:session2.batchId,state:"unavailable",detail:String(error),stderrLog:void 0}}}))}async function cancelLocal(gaugeDir,filter){if(Boolean(filter.id)===Boolean(filter.batch))throw new CliError("usage","Pass a run ID or --batch <batch-id>");if(filter.id)localId(filter.id);if(filter.batch)localId(filter.batch);const sessions=(await localSessions(gaugeDir)).filter(s=>filter.id?s.id===filter.id:s.batchId===filter.batch);if(filter.batch){const directory=batchDirectory(gaugeDir,filter.batch);if(existsSync2(directory)){if(!(await lstat2(directory)).isDirectory())throw new CliError("usage","Refusing a linked batch directory");await writeFile2(join5(directory,"cancel"),"",{mode:384})}else if(!sessions.length)throw new CliError("not_found","Local batch not found")}else if(!sessions.length)throw new CliError("not_found","Local run not found");for(const session2 of sessions)await writeFile2(join5(session2.directory,"..","cancel"),"",{mode:384});return Promise.all(sessions.map(async session2=>{try{await stopSession(session2.directory);return{id:session2.id,status:"stopped"}}catch(error){return{id:session2.id,status:"pending",detail:String(error)}}}))}async function cleanupLocal(gaugeDir){const results=[];for(const session2 of await localSessions(gaugeDir)){if(!existsSync2(join5(session2.directory,"session.json")))continue;try{const status=await getSessionStatus(session2.directory);if(status.state!=="interrupted"&&!status.cleanupPending)continue;await stopSession(session2.directory);const final=await getSessionStatus(session2.directory);try{await writeFile2(join5(session2.directory,"..","result.json"),JSON.stringify({outcome:final.state,endedBy:"recovery",turns:final.turn,endedAt:final.updatedAt,detail:final.detail})+"\n",{flag:"wx",mode:384})}catch(error){if(error.code!=="EEXIST")throw error}const store=openLocalStore(gaugeDir);try{const{skipped}=store.repairSessionSummaries([session2.id]);if(skipped.length)throw new Error(skipped.join("; "))}finally{store.close()}results.push({id:session2.id,status:"cleaned"})}catch(error){results.push({id:session2.id,status:"error",detail:String(error)})}}return results}async function localBatchStatus(gaugeDir,id){const directory=batchDirectory(gaugeDir,id);const status=JSON.parse(await readFile4(join5(directory,"status.json"),"utf8"));if(status.state==="running"&&Number.isSafeInteger(status.supervisorPid)&&status.supervisorPid>0){try{process.kill(status.supervisorPid,0)}catch(error){if(error.code==="ESRCH")status.state="interrupted"}}return{...status,cancelRequested:cancellationRequested(directory)}}import{fileURLToPath as fileURLToPath2}from"url";import{mkdirSync as mkdirSync3,readFileSync as readFileSync3,renameSync,writeFileSync as writeFileSync2}from"fs";import{randomBytes}from"crypto";import{homedir}from"os";import{join as join6}from"path";import{z as z9}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=z9.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);var profileSchema=z9.object({agent:z9.enum(agents),provider:z9.enum(["anthropic","openai","openai-codex","fireworks","openrouter"]),auth:z9.enum(["api_key","access_token","setup_token"]),env:variable.optional()}).strict();var storeSchema=z9.object({version:z9.literal(1),profiles:z9.record(z9.string(),profileSchema),defaults:z9.record(z9.string(),z9.string())}).strict();var API_KEY_ENV2={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",fireworks:"FIREWORKS_API_KEY",openrouter:"OPENROUTER_API_KEY"};var profilePath=()=>join6(configDir(),"local-profiles.json");function readProfiles(){let raw;try{raw=readFileSync3(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){mkdirSync3(configDir(),{recursive:true,mode:448});const temporary=`${profilePath()}.${randomBytes(6).toString("hex")}.tmp`;writeFileSync2(temporary,`${JSON.stringify(storeSchema.parse(store),null,2)}
|
|
66
66
|
`,{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_ENV2[p.provider])throw new CliError("usage",`API-key auth is unsupported for ${p.provider}.`);p.env??=API_KEY_ENV2[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",`No frozen credential selection for ${agent} ${model}.`);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_ENV2[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||join6(homedir(),".claude"):env.CODEX_HOME||join6(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_ENV2[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 as spawn2}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 RUNTIME_IMAGE=runtime_manifest_default.digest?`${runtime_manifest_default.repository}@${runtime_manifest_default.digest}`:`${runtime_manifest_default.repository}:${runtime_manifest_default.version}`;var dockerRead=args=>execFileSync("docker",args,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:15e3});function inspectLocalRuntime(image=RUNTIME_IMAGE,docker=dockerRead){const result={reference:image,expectedContract:runtime_manifest_default.contract,supportedPlatforms:runtime_manifest_default.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(!runtime_manifest_default.platforms.includes(result.dockerPlatform))return fail("platform_unsupported",`Docker ${server.Os}/${server.Arch} is not a qualified runtime platform.`,`Supported native Docker platforms: ${runtime_manifest_default.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(`${runtime_manifest_default.repository}@`))??details.RepoDigests?.[0];result.contract=details.Config?.Labels?.["sh.gauge.contract"];result.platform=`${details.Os}/${details.Architecture}`;if(result.contract!==runtime_manifest_default.contract)return fail("contract_unsupported",`Runtime contract ${result.contract??"(missing)"} is unsupported; expected ${runtime_manifest_default.contract}.`,"Use a runtime derived from the supported Gauge image and preserve its contract.");if(!runtime_manifest_default.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: ${runtime_manifest_default.platforms.join(", ")}. Emulation is not qualified.`);result.ready=true;return result}function requireLocalRuntime(image=RUNTIME_IMAGE){const result=inspectLocalRuntime(image);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}async function pullLocalRuntime(){const before=inspectLocalRuntime();if(!before.dockerPlatform||!runtime_manifest_default.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((resolve2,reject)=>{const child=spawn2("docker",["pull","--platform",platform,RUNTIME_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?resolve2():reject(new CliError("network",`Could not pull ${RUNTIME_IMAGE}.`,{hint:"Check the network and public registry availability, then retry gauge local runtime pull."})))});return requireLocalRuntime()}import{execFile as execFile2}from"child_process";import{randomUUID as randomUUID4}from"crypto";import{mkdtemp as mkdtemp2,mkdir as mkdir3,rm as rm3}from"fs/promises";import{tmpdir as tmpdir2}from"os";import{join as join7}from"path";import{promisify as promisify2}from"util";var exec=promisify2(execFile2);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 mkdtemp2(join7(tmpdir2(),"gauge-runtime-check-"));const name=`gauge-runtime-check-${randomUUID4()}`;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 mkdir3(join7(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(command2=>`${command2} --version >/dev/null || { echo 'missing or broken harness: ${command2}' >&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=${join7(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 rm3(directory,{recursive:true,force:true})}}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{resources,queue}=plan(definition);const warnings=[];const runtime=inspectLocalRuntime(options.runtimeImage);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,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:[...resources.values()].map(r=>({name:r.name,use:r.use?.type??r.kind})),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.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);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=join8(gaugeDir,"blobs");await mkdir4(blobsDirectory,{recursive:true});for(const upload of uploads)await copyFile(upload.path,join8(blobsDirectory,upload.sha256.slice(7)));const batchId=`b_${randomBytes2(6).toString("hex")}`;const directory=batchDirectory(gaugeDir,batchId);await mkdir4(directory,{recursive:true,mode:448});await writeJson(join8(directory,"runtime.json"),runtime);await writeJson(join8(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 writeFile3(join8(directory,"request.json"),JSON.stringify({definition,gaugeDir,batchId,credentialSelections,measurement:options.measurement}),{mode:384});const log=await open3(join8(directory,"supervisor.log"),"a",384);try{const bundledWorker=fileURLToPath2(new URL("./batchWorker.js",import.meta.url));const workerArgs=existsSync3(bundledWorker)?[bundledWorker]:[...process.execArgv,fileURLToPath2(new URL("../batchWorker.ts",import.meta.url))];const child=spawn3(process.execPath,[...workerArgs,join8(directory,"request.json")],{detached:true,stdio:["ignore",log.fd,log.fd]});await new Promise((resolve2,reject)=>{child.once("spawn",resolve2);child.once("error",reject)});let exited=false;child.once("exit",()=>{exited=true});const deadline=Date.now()+1e4;while(true){const status=JSON.parse(await readFile5(join8(directory,"status.json"),"utf8"));if(status.state!=="queued")break;if(exited||Date.now()>=deadline){await writeFile3(join8(directory,"cancel"),"",{mode:384});throw new CliError("network",`Background supervisor did not become ready. See ${join8(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 readFile5(join8(directory,"runtime.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(join8(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:join8(gaugeDir,"blobs"),resources,credentialSelections,runtime,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?`
|
|
67
67
|
|
|
68
68
|
Prepared inputs:
|
|
69
|
-
${files.map(r=>`- ${r.name}: /gauge/session/resources/${r.name}/content`).join("\n")}`:"";const{repoUrl,repoRef}=job.item.config;const agent=LOCAL_AGENTS[job.agent];return{image:runtimeImage,agent:{kind:agent.kind,model:job.model},auth:{mode:profile.auth},workspace:repoUrl?{repo:repoUrl,ref:repoRef??"HEAD"}:null,resources:selected,prompt:{text:job.item.prompt+note},limits:{turnTimeoutS:1800,responseTimeoutS:60,maxTurns:1}}}async function runJob(job,context){const id=`r_${randomBytes2(6).toString("hex")}`;const attemptDir=join8(context.gaugeDir,"runs",id,"attempts","1");const directory=join8(attemptDir,"session");await mkdir4(attemptDir,{recursive:true});const createdAt=new Date().toISOString();const frozenCase={...job.item,criteria:job.item.criteria?.map((criterion,index)=>({...criterion,id:context.measurement?.criterionIds?.[index]??`criterion-${index+1}`}))??null,preference:job.item.preference??null};const configuration={...job.item.config,case:frozenCase};const metadata={attempt:{runId:id,n:1,batchId:context.batchId},createdAt,launchId:context.batchId,measurement:context.measurement??null,provenance:context.provenance,configuration,agent:{kind:LOCAL_AGENTS[job.agent].kind,model:job.model},agentName:job.agent,runtime:context.runtime,case:frozenCase,sample:job.sample};await writeJson(join8(attemptDir,"spec.json"),metadata);const session2={id,batchId:context.batchId,launchId:context.batchId,measurementId:context.measurement?.id??null,measurementKind:context.measurement?.kind??null,measurementRevision:context.measurement?.revision??null,case:job.item.path,agent:job.agent,model:job.model,attempt:1,outcome:"starting",endedBy:null,turns:null,createdAt,endedAt:null,configuration,provenance:context.provenance};persistSession(context.gaugeDir,session2);const summary=(status,endedBy2)=>({id,case:job.item.path,agent:job.agent,model:job.model,sample:job.sample,outcome:status.state,endedBy:endedBy2,turns:status.turn,...status.detail?{detail:status.detail}:{}});const canceled=()=>context.canceled()||cancellationRequested(attemptDir);let result;try{const profile=resolveLocalProfile(job.agent,job.model,{credentialSelections:context.credentialSelections});const spec=sessionSpec(job,context.resources,profile,context.runtime.imageId);await writeJson(join8(attemptDir,"spec.json"),{...metadata,session:spec,credentialProfile:profile});if(canceled()){result=summary({state:"canceled",turn:0},"user_cancel")}else{await startSession({directory,spec,blobsDirectory:context.blobsDirectory,credentials:profileCredentialSources(profile)});result=await drive(directory,summary,canceled)}}catch(error){let cleanupError;try{await stopSession(directory)}catch(failure){cleanupError=failure}result=summary({state:"failed",turn:0,detail:error instanceof CredentialError?`${error.message} Fix: ${error.remedy}`:error instanceof Error?error.message:String(error)},"error");if(cleanupError&&existsSync3(join8(directory,"session.json")))result.detail+=`; cleanup pending: ${String(cleanupError)}. Run gauge cleanup --local.`}const{outcome,endedBy,turns,detail}=result;const endedAt=new Date().toISOString();const durationMs=Date.parse(endedAt)-Date.parse(createdAt);await writeJson(join8(attemptDir,"result.json"),{outcome,endedBy,turns,endedAt,durationMs,...detail?{detail}:{}});persistSession(context.gaugeDir,{...session2,outcome,endedBy,turns,endedAt,durationMs});return result}function persistSession(gaugeDir,session2){const store=openLocalStore(gaugeDir);try{store.upsertSession(session2)}finally{store.close()}}async function drive(directory,summary,canceled){let endedBy="session";for(;;){if(canceled()&&endedBy!=="user_cancel"){endedBy="user_cancel";await stopSession(directory)}const status=await getSessionStatus(directory);if(status.state==="waiting"&&endedBy==="session"){endedBy="supervisor_finish";await finishSession(directory,status.turn)}else if(status.state==="blocked"&&endedBy==="session"){endedBy="supervisor_stop";await stopSession(directory)}else if(["completed","failed","canceled","interrupted"].includes(status.state)){if(status.cleanupPending||status.state==="interrupted")await stopSession(directory);
|
|
70
|
-
`,{mode:384});await rename2(temporary,path)}export{errorEnvelopeSchema,listResponseSchema,batteries_exports,brands_exports,feedback_exports,keys_exports,ANALYSIS_SCHEMA_VERSION,analysisSubmissionSchema,agentSchema,runTriggeredBySchema,runCreditsChargedSchema,runEventSchema,agentConfigSchema,agentConfigInputSchema,assetRefListSchema,runConfig_exports,CLI_VERSION,credentialsPath,resolveToken,saveToken,clearToken,USER_AGENT,exitCodeFor,CliError,resolveBaseUrl,ApiClient,createClient,openLocalStore,localStatus,cancelLocal,cleanupLocal,localBatchStatus,LOCAL_MCP_HINT,assertLocalCapabilities,inspectLocalRuntime,pullLocalRuntime,LOCAL_TARGETS,readProfiles,writeProfiles,setProfile,requireProfile,inspectLocalCredential,LOCAL_AGENTS,analysisNext,planLocal,detachLocal,runLocal};
|
|
69
|
+
${files.map(r=>`- ${r.name}: /gauge/session/resources/${r.name}/content`).join("\n")}`:"";const{repoUrl,repoRef}=job.item.config;const agent=LOCAL_AGENTS[job.agent];return{image:runtimeImage,agent:{kind:agent.kind,model:job.model},auth:{mode:profile.auth},workspace:repoUrl?{repo:repoUrl,ref:repoRef??"HEAD"}:null,resources:selected,prompt:{text:job.item.prompt+note},limits:{turnTimeoutS:1800,responseTimeoutS:60,maxTurns:1}}}async function runJob(job,context){const id=`r_${randomBytes2(6).toString("hex")}`;const attemptDir=join8(context.gaugeDir,"runs",id,"attempts","1");const directory=join8(attemptDir,"session");await mkdir4(attemptDir,{recursive:true});const createdAt=new Date().toISOString();const frozenCase={...job.item,criteria:job.item.criteria?.map((criterion,index)=>({...criterion,id:context.measurement?.criterionIds?.[index]??`criterion-${index+1}`}))??null,preference:job.item.preference??null};const configuration={...job.item.config,case:frozenCase};const metadata={attempt:{runId:id,n:1,batchId:context.batchId},createdAt,launchId:context.batchId,measurement:context.measurement??null,provenance:context.provenance,configuration,agent:{kind:LOCAL_AGENTS[job.agent].kind,model:job.model},agentName:job.agent,runtime:context.runtime,case:frozenCase,sample:job.sample};await writeJson(join8(attemptDir,"spec.json"),metadata);const session2={id,batchId:context.batchId,launchId:context.batchId,measurementId:context.measurement?.id??null,measurementKind:context.measurement?.kind??null,measurementRevision:context.measurement?.revision??null,case:job.item.path,agent:job.agent,model:job.model,attempt:1,outcome:"starting",endedBy:null,turns:null,createdAt,endedAt:null,configuration,provenance:context.provenance};persistSession(context.gaugeDir,session2);const summary=(status,endedBy2)=>({id,case:job.item.path,agent:job.agent,model:job.model,sample:job.sample,outcome:status.state,endedBy:endedBy2,turns:status.turn,...status.detail?{detail:status.detail}:{}});const canceled=()=>context.canceled()||cancellationRequested(attemptDir);let result;try{const profile=resolveLocalProfile(job.agent,job.model,{credentialSelections:context.credentialSelections});const spec=sessionSpec(job,context.resources,profile,context.runtime.imageId);await writeJson(join8(attemptDir,"spec.json"),{...metadata,session:spec,credentialProfile:profile});if(canceled()){result=summary({state:"canceled",turn:0},"user_cancel")}else{await startSession({directory,spec,blobsDirectory:context.blobsDirectory,credentials:profileCredentialSources(profile)});result=await drive(directory,summary,canceled)}}catch(error){let cleanupError;try{await stopSession(directory)}catch(failure){cleanupError=failure}result=summary({state:"failed",turn:0,detail:error instanceof CredentialError?`${error.message} Fix: ${error.remedy}`:error instanceof Error?error.message:String(error)},"error");if(cleanupError&&existsSync3(join8(directory,"session.json")))result.detail+=`; cleanup pending: ${String(cleanupError)}. Run gauge cleanup --local.`}const{outcome,endedBy,turns,detail}=result;const endedAt=new Date().toISOString();const durationMs=Date.parse(endedAt)-Date.parse(createdAt);await writeJson(join8(attemptDir,"result.json"),{outcome,endedBy,turns,endedAt,durationMs,...detail?{detail}:{}});persistSession(context.gaugeDir,{...session2,outcome,endedBy,turns,endedAt,durationMs});return result}function persistSession(gaugeDir,session2){const store=openLocalStore(gaugeDir);try{store.upsertSession(session2)}finally{store.close()}}async function drive(directory,summary,canceled,session2={getSessionStatus,stopSession,finishSession}){let endedBy="session";let stopDetail;for(;;){if(canceled()&&endedBy!=="user_cancel"){endedBy="user_cancel";await session2.stopSession(directory)}const status=await session2.getSessionStatus(directory);if(status.state==="waiting"&&endedBy==="session"){endedBy="supervisor_finish";await session2.finishSession(directory,status.turn)}else if(status.state==="blocked"&&endedBy==="session"){endedBy="supervisor_stop";stopDetail="Stopped: the agent asked a question, and local runs have no user to answer it";await session2.stopSession(directory)}else if(["completed","failed","canceled","interrupted"].includes(status.state)){if(status.cleanupPending||status.state==="interrupted")await session2.stopSession(directory);const final=await session2.getSessionStatus(directory);return summary(stopDetail?{...final,detail:stopDetail}:final,endedBy)}await delay(POLL_MS)}}async function writeJson(path,value){const temporary=`${path}.${randomBytes2(6).toString("hex")}.tmp`;await writeFile3(temporary,`${JSON.stringify(value,null,2)}
|
|
70
|
+
`,{mode:384});await rename2(temporary,path)}export{errorEnvelopeSchema,listResponseSchema,createdBySchema,batteries_exports,brands_exports,feedback_exports,keys_exports,ANALYSIS_SCHEMA_VERSION,analysisSubmissionSchema,agentSchema,runTriggeredBySchema,runCreditsChargedSchema,runEventSchema,agentConfigSchema,agentConfigInputSchema,assetRefListSchema,runConfig_exports,CLI_VERSION,credentialsPath,resolveToken,saveToken,clearToken,USER_AGENT,exitCodeFor,CliError,resolveBaseUrl,ApiClient,createClient,openLocalStore,localStatus,cancelLocal,cleanupLocal,localBatchStatus,LOCAL_MCP_HINT,assertLocalCapabilities,inspectLocalRuntime,pullLocalRuntime,LOCAL_TARGETS,readProfiles,writeProfiles,setProfile,requireProfile,inspectLocalCredential,LOCAL_AGENTS,analysisNext,planLocal,detachLocal,runLocal};
|