@withgauge/cli 0.26.0 → 0.27.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.
@@ -0,0 +1,6 @@
1
+ import{CredentialError,batchDirectory,cancellationRequested,finishSession,getSessionStatus,openLocalStore,resolveSessionCredential,startSession,stopSession}from"./chunk-PUNARKS2.js";import{CliError}from"./chunk-PMX3NOGH.js";import{configDir}from"./chunk-OIGVDK3F.js";import{spawn as spawn2}from"child_process";import{randomBytes as randomBytes2}from"crypto";import{copyFile,mkdir as mkdir2,writeFile,open,readFile,rename}from"fs/promises";import{existsSync}from"fs";import{join as join3}from"path";import{setTimeout as delay}from"timers/promises";var LOCAL_MCP_HINT="Gauge exposes no local MCP configuration for registered servers. Hosted sessions can discover and call their tools; supplied files cannot test the live server. If hosted testing is acceptable, start with `gauge onboard`, select a workspace and MCP version, configure any required connection, then preview with --hosted. Login and static verification do not establish server reachability or access. Hosted sessions use credits; previews contact Gauge and may upload inputs. Do not issue hosted commands for a local-only request. See `gauge instructions hillclimb`.";function assertLocalCapabilities(config,prefix=""){if(config.lifecycle!=null)throw new CliError("usage",`${prefix}lifecycle requires hosted Gauge.`,{hint:"Setup and teardown scripts run in hosted sessions. Use --hosted or remove lifecycle."});for(const field of["profileId","marketId","skillRefs","mcpRefs","connectionIds"]){const value=config[field];if(Array.isArray(value)?value.length>0:Boolean(value))throw new CliError("usage",`${prefix}${field} requires hosted Gauge.`,{hint:field==="mcpRefs"?LOCAL_MCP_HINT:"Use --hosted for personas and hosted assets, or select local files and Skills through named inputs in gauge.json."})}if(config.addons&&Object.keys(config.addons).length>0)throw new CliError("usage",`${prefix}addons requires hosted Gauge.`,{hint:"Managed browser addons are unavailable locally. Use --hosted or remove the addon."})}import{fileURLToPath}from"url";import{mkdirSync,readFileSync,renameSync,writeFileSync}from"fs";import{randomBytes}from"crypto";import{homedir}from"os";import{join}from"path";import{z}from"zod";var LOCAL_TARGETS={CLAUDE_CODE:{kind:"claude-code",model:"claude-sonnet-5-5"},CODEX_CLI:{kind:"codex",model:"gpt-6-astra"},PI:{kind:"pi",model:"openai-codex/gpt-6-astra"},OPENCODE:{kind:"opencode",model:"openai/gpt-6-astra"}};var agents=["CLAUDE_CODE","CODEX_CLI","PI","OPENCODE"];var variable=z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);var profileSchema=z.object({agent:z.enum(agents),provider:z.enum(["anthropic","openai","openai-codex","fireworks","openrouter"]),auth:z.enum(["api_key","access_token","setup_token"]),env:variable.optional()}).strict();var storeSchema=z.object({version:z.literal(1),profiles:z.record(z.string(),profileSchema),defaults:z.record(z.string(),z.string())}).strict();var API_KEY_ENV={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",fireworks:"FIREWORKS_API_KEY",openrouter:"OPENROUTER_API_KEY"};var profilePath=()=>join(configDir(),"local-profiles.json");function readProfiles(){let raw;try{raw=readFileSync(profilePath(),"utf8")}catch(error){if(error.code==="ENOENT")return{version:1,profiles:{},defaults:{}};throw error}try{const parsed=storeSchema.safeParse(JSON.parse(raw));if(parsed.success)return parsed.data}catch{}throw new CliError("usage","Invalid local credential profile file.",{hint:`Repair ${profilePath()}.`})}function writeProfiles(store){mkdirSync(configDir(),{recursive:true,mode:448});const temporary=`${profilePath()}.${randomBytes(6).toString("hex")}.tmp`;writeFileSync(temporary,`${JSON.stringify(storeSchema.parse(store),null,2)}
2
+ `,{mode:384});renameSync(temporary,profilePath())}function validateProfile(value){const parsed=profileSchema.safeParse(value);if(!parsed.success)throw new CliError("usage","Invalid profile. Supply a supported --agent, --provider and --auth, and an environment variable name with --env.");const p=parsed.data;const expectedProvider=p.agent==="CLAUDE_CODE"?"anthropic":p.agent==="CODEX_CLI"?"openai":void 0;if(expectedProvider&&p.provider!==expectedProvider)throw new CliError("usage",`${p.agent} requires provider ${expectedProvider}.`);if(p.auth==="access_token"){const provider=p.agent==="CLAUDE_CODE"?"anthropic":p.agent==="PI"?"openai-codex":"openai";if(p.provider!==provider||p.env)throw new CliError("usage",`Native login for ${p.agent} requires provider ${provider} and no --env.`)}else if(p.auth==="setup_token"){if(p.agent!=="CLAUDE_CODE")throw new CliError("usage","Setup tokens are supported only for CLAUDE_CODE.");p.env??="CLAUDE_CODE_OAUTH_TOKEN"}else{if(!API_KEY_ENV[p.provider])throw new CliError("usage",`API-key auth is unsupported for ${p.provider}.`);p.env??=API_KEY_ENV[p.provider]}return p}function setProfile(name,value,replace=false){if(!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}$/.test(name)||["__proto__","constructor","prototype"].includes(name))throw new CliError("usage","Profile names must be 1\u201364 letters, digits, dots, underscores or hyphens.");const p=validateProfile(value);const store=readProfiles();const previous=Object.hasOwn(store.profiles,name)?store.profiles[name]:void 0;if(previous&&!replace)throw new CliError("usage",`Profile ${name} already exists. Pass --replace to update it.`);if(previous&&previous.agent!==p.agent&&store.defaults[previous.agent]===name)delete store.defaults[previous.agent];store.profiles[name]=p;writeProfiles(store);return store}function requireProfile(store,name){if(!Object.hasOwn(store.profiles,name))throw new CliError("not_found",`Local credential profile ${name} does not exist.`,{hint:"Run gauge local profiles list."});return validateProfile(store.profiles[name])}function credentialKey(agent,model){return`${agent}:${model}`}function providerFor(agent,model){if(agent==="CLAUDE_CODE")return"anthropic";if(agent==="CODEX_CLI")return"openai";const slash=model.indexOf("/");if(slash<1||slash===model.length-1)throw new CliError("usage",`${agent} model ${model} must include provider/model.`);return model.slice(0,slash)}function resolveLocalProfile(agent,model,options={},store=void 0,env=process.env){const key=credentialKey(agent,model);if(options.credentialSelections){const selected=options.credentialSelections[key];if(!selected)throw new CliError("usage",`This batch has no saved login settings for ${agent} ${model}.`,{hint:"Check `gauge local profiles list`, then start a new batch with the profile you want to use."});validateCompatibility(selected,agent,model);return selected}store??=readProfiles();const provider=providerFor(agent,model);const name=options.profile??store.defaults[agent]??null;let p;if(name)p=requireProfile(store,name);else{const apiEnv=API_KEY_ENV[provider];const nativeProvider=agent==="CLAUDE_CODE"?"anthropic":agent==="PI"?"openai-codex":"openai";const auth=apiEnv&&env[apiEnv]?.trim()||provider!==nativeProvider?"api_key":agent==="CLAUDE_CODE"&&env.CLAUDE_CODE_OAUTH_TOKEN?.trim()?"setup_token":"access_token";p=validateProfile({agent,provider,auth})}validateCompatibility(p,agent,model);const nativeDirectory=p.auth==="access_token"?p.agent==="CLAUDE_CODE"?env.CLAUDE_CONFIG_DIR||void 0:env.CODEX_HOME||join(homedir(),".codex"):void 0;return{...p,name,source:p.env?`env:${p.env}`:p.agent==="CLAUDE_CODE"?"native:claude":"native:codex",...nativeDirectory?{nativeDirectory}:{}}}function validateCompatibility(p,agent,model){validateProfile(pickProfile(p));if(p.agent!==agent||p.provider!==providerFor(agent,model))throw new CliError("usage",`Credential profile for ${p.agent}/${p.provider} is incompatible with ${agent} ${model}.`,{hint:"Select a compatible --profile or change this harness's default with gauge local profiles use."})}function pickProfile(p){return{agent:p.agent,provider:p.provider,auth:p.auth,...p.env?{env:p.env}:{}}}function profileCredentialSources(profile,env=process.env){const mapped={...env};if(profile.env){if(!env[profile.env]?.trim())throw new CredentialError(`Credential environment variable ${profile.env} is not set.`,`Export ${profile.env} before starting the batch, or update the profile's --env reference.`);const canonical=profile.auth==="setup_token"?"CLAUDE_CODE_OAUTH_TOKEN":API_KEY_ENV[profile.provider];mapped[canonical]=env[profile.env]}if(profile.nativeDirectory)mapped[profile.agent==="CLAUDE_CODE"?"CLAUDE_CONFIG_DIR":"CODEX_HOME"]=profile.nativeDirectory;return{env:mapped,homeDir:homedir(),now:new Date}}function readinessSpec(agent,model,profile){return{image:"unused",agent:{kind:LOCAL_TARGETS[agent].kind,model},auth:{mode:profile.auth},workspace:null,resources:[],prompt:{text:""},limits:{turnTimeoutS:1800,responseTimeoutS:60,maxTurns:1}}}async function inspectLocalCredential(agent,model,options={},store){let profile;try{profile=resolveLocalProfile(agent,model,options,store);const credential=await resolveSessionCredential(readinessSpec(agent,model,profile),profileCredentialSources(profile));return{agent,model,profile,ready:true,...credential.expiresAt?{expiresAt:credential.expiresAt.toISOString()}:{},verification:"local"}}catch(error){const problem=error instanceof CredentialError?`${error.message} Fix: ${error.remedy}`:error instanceof CliError?error.message:"Could not read the credential source. Repair or renew the native login and retry.";return{agent,model,profile,ready:false,problem,verification:"local"}}}import{execFileSync,spawn}from"child_process";var runtime_manifest_default={version:"0.1.2",repository:"ghcr.io/gauge-sh/gauge-runtime",digest:"sha256:4056830a1efcb0116fb70e25a18576e26ad7222a87683d6f03387eb88f596c32",contract:"1",platforms:["linux/amd64","linux/arm64"],revision:"abb55dbfa9ceaa160c7a9685a0fd2b4e68a259aa"};var gateway_manifest_default={version:"0.1.0",repository:"ghcr.io/gauge-sh/gauge-gateway",digest:"sha256:ab5489cfe65feb717a79d7be6bd76be8bf915f3e44a5e832cee313772e590e1c",contract:"gateway-1",platforms:["linux/amd64","linux/arm64"],revision:"cdb3a7985666fbb6287be5b2b041aff327c874d7"};var RUNTIME_MANIFEST=runtime_manifest_default;var RUNTIME_IMAGE=runtime_manifest_default.digest?`${runtime_manifest_default.repository}@${runtime_manifest_default.digest}`:`${runtime_manifest_default.repository}:${runtime_manifest_default.version}`;var GATEWAY_IMAGE=gateway_manifest_default.digest?`${gateway_manifest_default.repository}@${gateway_manifest_default.digest}`:`${gateway_manifest_default.repository}:${gateway_manifest_default.version}`;var dockerRead=args=>execFileSync("docker",args,{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:15e3});function inspectLocalRuntime(image=RUNTIME_IMAGE,docker=dockerRead,manifest=RUNTIME_MANIFEST){const result={reference:image,expectedContract:manifest.contract,supportedPlatforms:manifest.platforms,ready:false};const fail=(code,message,hint)=>({...result,problem:{code,message,hint}});let server;try{server=JSON.parse(docker(["version","--format","{{json .Server}}"]));if(!server?.Os||!server.Arch)throw new Error("No Docker server")}catch{return fail("docker_unavailable","Local runs need a running Docker daemon.","Start Docker Desktop (using Linux containers) or the Docker daemon, then retry.")}result.dockerPlatform=`${server.Os}/${server.Arch}`;if(!manifest.platforms.includes(result.dockerPlatform))return fail("platform_unsupported",`Docker ${server.Os}/${server.Arch} is not a qualified runtime platform.`,`Supported native Docker platforms: ${manifest.platforms.join(", ")}. Emulation is not qualified.`);let details;try{[details]=JSON.parse(docker(["image","inspect",image]))}catch{return fail("image_missing",`Local runs need the ${image} Docker image.`,image===RUNTIME_IMAGE?"Run: gauge local runtime pull":`Pull or build the selected runtime image: ${image}`)}if(!details?.Id||!details.Os||!details.Architecture)return fail("image_invalid",`Docker returned incomplete image metadata for ${image}.`,"Check docker image inspect for the selected image.");result.imageId=details.Id;result.repoDigest=details.RepoDigests?.find(digest=>digest.startsWith(`${manifest.repository}@`))??details.RepoDigests?.[0];result.contract=details.Config?.Labels?.["sh.gauge.contract"];result.platform=`${details.Os}/${details.Architecture}`;if(result.contract!==manifest.contract)return fail("contract_unsupported",`Runtime contract ${result.contract??"(missing)"} is unsupported; expected ${manifest.contract}.`,"Use a runtime derived from the supported Gauge image and preserve its contract.");if(!manifest.platforms.includes(result.platform)||server.Os!==details.Os||server.Arch!==details.Architecture)return fail("platform_unsupported",`Runtime ${result.platform} is not supported on Docker ${server.Os}/${server.Arch}.`,`Supported native Docker platforms: ${manifest.platforms.join(", ")}. Emulation is not qualified.`);result.ready=true;return result}function requireLocalRuntime(image=RUNTIME_IMAGE,manifest){const result=inspectLocalRuntime(image,void 0,manifest);if(!result.ready){const problem=result.problem;throw new CliError(problem.code==="image_missing"||problem.code==="docker_unavailable"?"not_found":"usage",problem.message,{hint:problem.hint})}return result}var inspectLocalGateway=(image=GATEWAY_IMAGE,docker)=>inspectLocalRuntime(image,docker,gateway_manifest_default);var requireLocalGateway=(image=GATEWAY_IMAGE)=>requireLocalRuntime(image,gateway_manifest_default);var pullLocalGateway=()=>pullLocalRuntime(GATEWAY_IMAGE,gateway_manifest_default);async function pullLocalRuntime(image=RUNTIME_IMAGE,manifest=RUNTIME_MANIFEST){const before=inspectLocalRuntime(image,void 0,manifest);if(!before.dockerPlatform||!manifest.platforms.includes(before.dockerPlatform)){const problem=before.problem;throw new CliError(problem.code==="docker_unavailable"?"not_found":"usage",problem.message,{hint:problem.hint})}const platform=before.dockerPlatform;await new Promise((resolve,reject)=>{const child=spawn("docker",["pull","--platform",platform,image],{stdio:["ignore","pipe","pipe"]});child.stdout.pipe(process.stderr);child.stderr.pipe(process.stderr);child.once("error",()=>reject(new CliError("not_found","Docker could not start.",{hint:"Install and start Docker, then retry."})));child.once("exit",code=>code===0?resolve():reject(new CliError("network",`Could not pull ${image}.`,{hint:"Check the network and public registry availability, then retry gauge local runtime pull."})))});return requireLocalRuntime(image,manifest)}import{execFile}from"child_process";import{randomUUID}from"crypto";import{mkdtemp,mkdir,rm}from"fs/promises";import{tmpdir}from"os";import{join as join2}from"path";import{promisify}from"util";var exec=promisify(execFile);var tools=["sh","bash","git","sha256sum","mkdir","cp","tar","chmod","touch","node","npm","jq","curl"];var harnesses={"claude-code":"claude",codex:"codex",pi:"pi",opencode:"opencode"};var marker="GAUGE_RUNTIME_COMPATIBLE";async function checkLocalRuntimeCompatibility(imageId,agents2){if(!process.getuid||!process.getgid)throw new CliError("usage","Local runtime execution requires a Unix host UID/GID.",{hint:"Run Gauge on macOS or Linux with local Docker running Linux containers, or inside WSL on Windows."});const directory=await mkdtemp(join2(tmpdir(),"gauge-runtime-check-"));const name=`gauge-runtime-check-${randomUUID()}`;try{if(/[,"\n]/.test(directory))throw new CliError("usage","The temporary directory cannot be mounted by Docker.",{hint:"Set TMPDIR to a path without commas, quotes or newlines, then retry."});await mkdir(join2(directory,"workspace"),{mode:448});const commands=[...new Set(agents2.map(agent=>harnesses[agent]))];const script=["set -eu",...tools.map(tool=>`command -v ${tool} >/dev/null || { echo 'missing tool: ${tool}' >&2; exit 41; }`),"mkdir -p /gauge/session/home /gauge/session/workspace || { echo 'session directory is not writable' >&2; exit 42; }","touch /gauge/session/workspace/probe /tmp/gauge-runtime-probe || { echo 'session directory or /tmp is not writable' >&2; exit 42; }","mkdir -p /gauge/session/npm/bin","printf '#!/bin/sh\\nexit 0\\n' > /gauge/session/npm/bin/gauge-runtime-path-probe","chmod 755 /gauge/session/npm/bin/gauge-runtime-path-probe",...["sh -c","sh -lc","bash -lc"].map(shell=>`${shell} gauge-runtime-path-probe >/dev/null || { echo 'environment-installed tools are missing from PATH in ${shell}; rebuild from the current Gauge runtime or preserve /gauge/session/npm/bin in the system login profile and image PATH' >&2; exit 44; }`),"cd /gauge/session/workspace","git init --quiet && git -c user.name=gauge -c user.email=gauge@localhost commit --quiet --allow-empty -m probe","tar --create --gzip --file /tmp/gauge-probe.tar.gz probe","tar --extract --gzip --file /tmp/gauge-probe.tar.gz --directory /gauge/session/workspace --no-same-owner --no-same-permissions","sha256sum probe | sha256sum -c --quiet -",...commands.map(command=>`${command} --version >/dev/null || { echo 'missing or broken harness: ${command}' >&2; exit 43; }`),`echo ${marker}`].join("\n");let stdout;try{({stdout}=await exec("docker",["run","--rm","--pull","never","--name",name,"--network","none","--user",`${process.getuid()}:${process.getgid()}`,"--env","HOME=/gauge/session/home","--env","CLAUDE_CONFIG_DIR=/gauge/session/claude","--env","CODEX_HOME=/gauge/session/codex","--env","PI_CODING_AGENT_DIR=/tmp/pi-agent","--env","XDG_DATA_HOME=/gauge/session/opencode/data","--env","XDG_STATE_HOME=/gauge/session/opencode/state","--mount",`type=bind,source=${join2(directory,"workspace")},target=/gauge/session`,imageId,"sh","-c",script],{timeout:6e4,maxBuffer:1024*1024}))}catch(error){const stderr=String(error.stderr??"").trim();const detail=stderr?` ${stderr.slice(-2e3)}`:" The probe failed or timed out.";throw new CliError("usage",`Runtime ${imageId} failed its compatibility check.${detail}`,{hint:"Derive from the supported Gauge runtime; preserve required tools, harnesses and the session npm bin in ordinary/login-shell PATH, permit the host UID/GID to write /gauge/session and /tmp, and have ENTRYPOINT execute the supplied command."})}if(!stdout.split(/\r?\n/).includes(marker))throw new CliError("usage",`Runtime ${imageId} did not execute Gauge's compatibility command.`,{hint:'Remove the custom ENTRYPOINT or make it finish with exec "$@". Gauge supplies sh -c and must receive its output.'})}finally{await exec("docker",["rm","--force",name],{timeout:1e4}).catch(()=>{});await rm(directory,{recursive:true,force:true})}}import{createHash}from"crypto";import{createReadStream}from"fs";import{list}from"tar";import{z as z3}from"zod";import{z as z2}from"zod";var websiteUrlSchema=z2.url().refine(raw=>{const u=new URL(raw);return u.protocol==="https:"&&!u.username&&!u.password&&!u.port&&!u.search&&!u.hash},"Expected an HTTPS documentation URL without credentials, port, query or fragment");var websiteUseSchema=z2.object({type:z2.literal("website"),url:websiteUrlSchema.refine(url=>new URL(url).pathname==="/","Website inputs require an origin without a path")}).strict();var deploymentSourceSchema=z2.object({type:z2.literal("github-deployment"),environment:z2.string().min(1).max(128)}).strict();var commentSourceSchema=z2.object({type:z2.literal("github-pr-comment"),author:z2.string().min(1).max(100).regex(/^[a-zA-Z0-9-]+(?:\[bot\])?$/),bodyIncludes:z2.string().min(1).max(256).describe("Literal marker identifying the provider's preview comment."),pattern:z2.string().min(1).max(2048).refine(pattern=>{try{new RegExp(pattern,"gm");return pattern.includes("(?<url>")&&pattern.includes("(?<sha>")}catch{return false}},"Use a valid regex with named url and sha captures; match only a ready preview").describe("JavaScript regex (gm flags) matching readiness and capturing url and sha (7\u201340 hex characters). Execution is time limited."),failureIncludes:z2.string().min(1).max(256).optional().describe("Literal failure marker in the selected comment; failure never falls back to older comments.")}).strict();var websiteSourceSchema=z2.discriminatedUnion("type",[deploymentSourceSchema,commentSourceSchema]);function withinWebsiteScope(raw,base){const u=new URL(raw),scope=new URL(base);const prefix=scope.pathname.replace(/\/$/,"");return u.origin===scope.origin&&(u.pathname===prefix||u.pathname.startsWith(`${prefix}/`))}var MAX_WEB_FIXTURE_BYTES=1e6;function normalizeWebFixtureUrl(raw){const url=new URL(raw);url.hash="";return url.href}var searchResultSchema=z3.object({title:z3.string().min(1),url:z3.url().transform(normalizeWebFixtureUrl),snippet:z3.string()});var searchFixtureSchema=z3.object({query:z3.string().trim().min(1),results:z3.array(searchResultSchema)});var pageFixtureSchema=z3.object({url:z3.url().transform(normalizeWebFixtureUrl),status:z3.int().min(100).max(599).default(200),contentType:z3.string().trim().min(1).default("text/html"),body:z3.string()});var originProxySchema=z3.object({origin:websiteUrlSchema.refine(raw=>new URL(raw).pathname==="/","Expected an origin").transform(raw=>new URL(raw).origin),upstream:websiteUrlSchema.refine(raw=>new URL(raw).pathname==="/","Expected an origin").transform(raw=>new URL(raw).origin)}).strict();var webFixtureSchema=z3.object({version:z3.literal(1),origins:z3.array(originProxySchema).max(32).optional(),scopes:z3.array(websiteUrlSchema.transform(normalizeWebFixtureUrl)).max(32).optional(),searches:z3.array(searchFixtureSchema).default([]),pages:z3.array(pageFixtureSchema).default([])}).superRefine((fixture,ctx)=>{if(fixture.scopes?.some(scope=>!fixture.pages.some(page=>new URL(page.url).origin===new URL(scope).origin)))ctx.addIssue({code:"custom",path:["scopes"],message:"Each scope must have a captured page on its origin"});const origins=new Set;for(const route of fixture.origins??[]){if(origins.has(route.origin)||route.origin===route.upstream||fixture.pages.some(page=>new URL(page.url).origin===route.origin)||fixture.scopes?.some(scope=>new URL(scope).origin===route.origin))ctx.addIssue({code:"custom",message:"Origin proxy overlaps another fixture route"});origins.add(route.origin)}const queries=new Set;fixture.searches.forEach((entry,index)=>{if(queries.has(entry.query)){ctx.addIssue({code:"custom",path:["searches",index,"query"],message:`duplicate normalized query: ${entry.query}`})}queries.add(entry.query)});const urls=new Set;fixture.pages.forEach((entry,index)=>{if(urls.has(entry.url)){ctx.addIssue({code:"custom",path:["pages",index,"url"],message:`duplicate normalized URL: ${entry.url}`})}urls.add(entry.url)});const bytes=new TextEncoder().encode(JSON.stringify(fixture)).byteLength;if(bytes>MAX_WEB_FIXTURE_BYTES){ctx.addIssue({code:"custom",message:`serialized fixture is ${bytes} bytes; maximum is ${MAX_WEB_FIXTURE_BYTES}`})}});var webFixtureInputSchema=webFixtureSchema.safeExtend({searches:z3.array(z3.never()).max(0).default([]),pages:z3.array(pageFixtureSchema.safeExtend({url:z3.url().refine(raw=>{const url=new URL(raw);return url.protocol==="https:"&&!url.port&&!url.username&&!url.password},"Expected an HTTPS URL without credentials or a custom port").transform(normalizeWebFixtureUrl),status:z3.int().min(200).max(599).default(200),contentType:z3.string().trim().min(1).regex(/^[\x20-\x7e]+$/).default("text/html"),body:z3.string().refine(body=>!/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(body),"Body must be valid Unicode")}).strict().refine(page=>![204,205,304].includes(page.status)||page.body==="","This HTTP status requires an empty body")).default([])}).strict().refine(fixture=>fixture.pages.length>0||(fixture.origins?.length??0)>0,"Web fixture must contain pages or origin mappings");function parseWebFixtureInput(text){if(new TextEncoder().encode(text).byteLength>MAX_WEB_FIXTURE_BYTES)throw new Error(`Web fixture exceeds ${MAX_WEB_FIXTURE_BYTES} bytes`);return webFixtureInputSchema.parse(JSON.parse(text))}function mergeWebFixtures(fixtures){if(!fixtures.length)return void 0;const scopes=[];for(const[index,fixture]of fixtures.entries()){for(const scope of fixture.scopes??[]){if(scopes.some(other=>withinWebsiteScope(scope,other)||withinWebsiteScope(other,scope)))throw new Error("Web fixture scopes overlap in this case");if(fixtures.some((other,otherIndex)=>otherIndex!==index&&other.pages.some(page=>withinWebsiteScope(page.url,scope))))throw new Error("Web fixture scope overlaps another input's pages");scopes.push(scope)}}return webFixtureSchema.parse({version:1,scopes,origins:fixtures.flatMap(f=>f.origins??[]),searches:fixtures.flatMap(f=>f.searches),pages:fixtures.flatMap(f=>f.pages)})}async function readWebFixtureArchive(path,member,digest){const hash=createHash("sha256");for await(const chunk of createReadStream(path))hash.update(chunk);if(`sha256:${hash.digest("hex")}`!==digest)throw new Error("Web fixture archive digest mismatch");const chunks=[];let found=0;let bytes=0;let problem;await list({file:path,strict:true,onReadEntry(entry){if(entry.path.replace(/^\.\//,"")!==member||entry.type!=="File"||entry.size>MAX_WEB_FIXTURE_BYTES){problem=new Error("Web fixture archive must contain exactly its declared JSON file (at most 1 MB)");entry.resume();return}found++;entry.on("data",chunk=>{bytes+=chunk.length;if(bytes>MAX_WEB_FIXTURE_BYTES)problem=new Error("Web fixture exceeds 1 MB");else chunks.push(chunk)})}});if(problem)throw problem;if(found!==1)throw new Error("Web fixture archive must contain exactly one JSON file");return parseWebFixtureInput(Buffer.concat(chunks).toString("utf8"))}async function freezeWebFixtures(definition,archives){const inputs=new Map;for(const resource of definition.resources){if(resource.use.type!=="web-fixture")continue;if(resource.source.type!=="upload")throw new Error(`Web fixture ${resource.name} requires a local file`);const digest=resource.source.sha256;const archive=archives.find(a=>a.sha256===digest);if(!archive)throw new Error(`Missing web fixture archive: ${resource.name}`);inputs.set(resource.name,await readWebFixtureArchive(archive.path,resource.use.path,archive.sha256))}const cases={};for(const item of definition.cases){const fixture=mergeWebFixtures((item.config.inputs??[...inputs.keys()]).flatMap(name=>inputs.get(name)??[]));if(fixture)cases[item.path]={fixture,digest:`sha256:${createHash("sha256").update(JSON.stringify(fixture)).digest("hex")}`}}return cases}var CONCURRENCY=4;var POLL_MS=1e3;var LOCAL_AGENTS=LOCAL_TARGETS;function analysisNext(batchId){return["Next: analyze these runs. Run this command and follow it:"," gauge instructions session-analysis --local",`Analyze only batch ${batchId}.`].join("\n")}async function planLocal(definition,options={}){const{queue}=plan(definition);const warnings=[];const runtime=inspectLocalRuntime(options.runtimeImage);const gateway=definition.resources.some(r=>r.use.type==="web-fixture")?inspectLocalGateway(options.gatewayImage):void 0;if(gateway?.problem)warnings.push(`${gateway.problem.message} ${gateway.problem.hint}`);if(runtime.problem)warnings.push(`${runtime.problem.message} ${runtime.problem.hint}`);const credentials=await credentialReadiness(queue,options);for(const target of credentials)if(!target.ready)warnings.push(`${target.agent} ${target.model}: ${target.problem}`);return{mode:"local",runtime,gateway,runtimeProbe:"not_run",expectedSessions:queue.length,cases:definition.cases.map(item=>{const sessions=new Map;for(const job of queue.filter(job2=>job2.item===item)){const key=`${job.agent}\0${job.model}`;const entry=sessions.get(key)??{agent:job.agent,model:job.model,samples:0};entry.samples++;sessions.set(key,entry)}return{path:item.path,criteria:item.criteria?.length??0,sessions:[...sessions.values()]}}),inputs:definition.resources.map(r=>({name:r.name,use:r.use.type})),warnings,credentials}}function plan(definition){for(const item of definition.cases){assertLocalCapabilities(item.config,`${item.path}: config.`);if(item.config.repoRef&&!item.config.repoUrl)throw new CliError("usage",`${item.path}: config.repoRef requires config.repoUrl.`);for(const name of item.config.inputs??[])if(!definition.resources.some(resource=>resource.name===name))throw new CliError("usage",`${item.path}: input ${name} is missing from this launch.`)}const resources=new Map(definition.resources.filter(resource=>resource.use.type!=="web-fixture").map(resource=>[resource.name,toResourceRef(resource)]));const queue=definition.cases.flatMap(item=>item.config.agents.flatMap(entry=>{const agent=LOCAL_AGENTS[entry.agent];if(!agent)throw new CliError("usage",`${item.path}: agent ${entry.agent} cannot run locally.`,{hint:"Use CLAUDE_CODE, CODEX_CLI, PI, or OPENCODE, or pass --hosted."});const models=entry.models?.length?entry.models:[agent.model];return models.flatMap(model=>Array.from({length:item.config.sampleCount??1},(_,sample)=>({item,agent:entry.agent,model,sample:sample+1})))}));return{resources,queue}}async function prepareLocal(definition,uploads,gaugeDir,options={}){const{queue}=plan(definition);const webFixtures=await freezeWebFixtures(definition,uploads);const gateway=Object.keys(webFixtures).length?requireLocalGateway(options.gatewayImage):void 0;await freezeCredentials(queue,options);const runtime=requireLocalRuntime(options.runtimeImage);await checkLocalRuntimeCompatibility(runtime.imageId,[...new Set(queue.map(job=>LOCAL_AGENTS[job.agent].kind))]);const blobsDirectory=join3(gaugeDir,"blobs");await mkdir2(blobsDirectory,{recursive:true});for(const upload of uploads)await copyFile(upload.path,join3(blobsDirectory,upload.sha256.slice(7)));const batchId=`b_${randomBytes2(6).toString("hex")}`;const directory=batchDirectory(gaugeDir,batchId);await mkdir2(directory,{recursive:true,mode:448});await writeJson(join3(directory,"runtime.json"),runtime);await writeJson(join3(directory,"gateway.json"),{gateway,cases:webFixtures});await writeJson(join3(directory,"status.json"),{batchId,runtime,state:"queued",expectedSessions:plan(definition).queue.length});const store=openLocalStore(gaugeDir);try{store.recordLaunch({id:batchId,measurementId:options.measurement?.id,measurementRevision:options.measurement?.revision,configuration:definition,provenance:definition.source??{}})}finally{store.close()}return batchId}async function detachLocal(definition,uploads,gaugeDir,options={}){const credentialSelections=await freezeCredentials(plan(definition).queue,options);const batchId=await prepareLocal(definition,uploads,gaugeDir,{...options,credentialSelections});const directory=batchDirectory(gaugeDir,batchId);await writeFile(join3(directory,"request.json"),JSON.stringify({definition,gaugeDir,batchId,credentialSelections,measurement:options.measurement}),{mode:384});const log=await open(join3(directory,"supervisor.log"),"a",384);try{const bundledWorker=fileURLToPath(new URL("./batchWorker.js",import.meta.url));const workerArgs=existsSync(bundledWorker)?[bundledWorker]:[...process.execArgv,fileURLToPath(new URL("../batchWorker.ts",import.meta.url))];const child=spawn2(process.execPath,[...workerArgs,join3(directory,"request.json")],{detached:true,stdio:["ignore",log.fd,log.fd]});await new Promise((resolve,reject)=>{child.once("spawn",resolve);child.once("error",reject)});let exited=false;child.once("exit",()=>{exited=true});const deadline=Date.now()+1e4;while(true){const status=JSON.parse(await readFile(join3(directory,"status.json"),"utf8"));if(status.state!=="queued")break;if(exited||Date.now()>=deadline){await writeFile(join3(directory,"cancel"),"",{mode:384});throw new CliError("network",`Background supervisor did not become ready. See ${join3(directory,"supervisor.log")}`)}await delay(50)}child.unref()}finally{await log.close()}return{batchId,status:`gauge run status --batch ${batchId} --local`,wait:`gauge run wait --batch ${batchId} --local`,stop:`gauge run cancel --batch ${batchId} --local`}}async function runLocal(definition,uploads,gaugeDir,onRun=()=>{},options={}){const{resources,queue}=plan(definition);const credentialSelections=await freezeCredentials(queue,options);const batchId=options.batchId??await prepareLocal(definition,uploads,gaugeDir,{...options,credentialSelections});const directory=batchDirectory(gaugeDir,batchId);const runtime=JSON.parse(await readFile(join3(directory,"runtime.json"),"utf8"));const gatewayPlan=JSON.parse(await readFile(join3(directory,"gateway.json"),"utf8"));const expectedSessions=queue.length;let interrupted=false;const signal=()=>{interrupted=true;process.exitCode=130};process.on("SIGINT",signal);process.on("SIGTERM",signal);const canceled=()=>interrupted||cancellationRequested(directory);const runs=[];let progress=Promise.resolve();const save=state=>writeJson(join3(directory,"status.json"),{batchId,runtime,state,expectedSessions,finishedSessions:runs.length,queuedSessions:state==="running"?queue.length:0,skippedSessions:state==="running"?0:queue.length,supervisorPid:process.pid});try{await save("running");options.onStart?.(batchId);const worker=async()=>{while(!canceled()){const job=queue.shift();if(!job)break;const run=await runJob(job,{batchId,gaugeDir,blobsDirectory:join3(gaugeDir,"blobs"),resources,credentialSelections,runtime,gateway:gatewayPlan.gateway&&gatewayPlan.cases[job.item.path]?{image:gatewayPlan.gateway.imageId,...gatewayPlan.cases[job.item.path]}:void 0,canceled,measurement:options.measurement,provenance:definition.source??{}});runs.push(run);onRun(run);progress=progress.then(()=>save("running"));await progress}};const settled=await Promise.allSettled(Array.from({length:CONCURRENCY},worker));const failure=settled.find(s=>s.status==="rejected");await save(failure?"failed":canceled()?"canceled":"completed");if(failure?.status==="rejected")throw failure.reason;return{batchId,runs,next:analysisNext(batchId),canceled:canceled()}}finally{process.off("SIGINT",signal);process.off("SIGTERM",signal)}}function toResourceRef(resource){if(resource.source.type!=="upload")throw new CliError("usage",`Input ${resource.name} has no local file; local runs need every input in the working tree`);const base={name:resource.name,digest:resource.source.sha256,filename:`${resource.name}.tar.gz`,kind:"archive"};const use=resource.use;if(use.type==="files")return{...base,use:{type:"files"}};if(use.type==="skill"&&use.root===".")return{...base,use:{type:"skill"}};if(use.type==="npm-package")return{...base,use:{type:"npm-package",package:use.package,install:use.install??"workspace"}};throw new CliError("usage",`Input ${resource.name}: ${use.type==="skill"?"supply the Skill as a directory":`${use.type} inputs run on hosted Gauge only`}`)}async function credentialReadiness(queue,options){const store=options.credentialSelections?{version:1,profiles:{},defaults:{}}:readProfiles();const targets=new Map(queue.map(job=>[credentialKey(job.agent,job.model),job]));return Promise.all([...targets.values()].map(job=>inspectLocalCredential(job.agent,job.model,options,store)))}async function freezeCredentials(queue,options){const readiness=await credentialReadiness(queue,options);const failures=readiness.filter(target=>!target.ready);if(failures.length)throw new CliError("usage",failures.map(target=>`${target.agent} ${target.model}: ${target.problem}`).join("\n"),{hint:"Inspect credentials with gauge local profiles inspect <profile>, or preview every target with gauge run --local --dry-run -o json."});return Object.fromEntries(readiness.map(target=>[credentialKey(target.agent,target.model),target.profile]))}function sessionSpec(job,resources,profile,runtimeImage=RUNTIME_IMAGE){const names=job.item.config.inputs??[...resources.keys()];const selected=names.flatMap(name=>resources.get(name)??[]);const files=selected.filter(r=>r.use?.type==="files");const note=files.length?`
3
+
4
+ Prepared inputs:
5
+ ${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=join3(context.gaugeDir,"runs",id,"attempts","1");const directory=join3(attemptDir,"session");await mkdir2(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(join3(attemptDir,"spec.json"),metadata);const session={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,session);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);spec.gateway=context.gateway;await writeJson(join3(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&&existsSync(join3(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(join3(attemptDir,"result.json"),{outcome,endedBy,turns,endedAt,durationMs,...detail?{detail}:{}});persistSession(context.gaugeDir,{...session,outcome,endedBy,turns,endedAt,durationMs});return result}function persistSession(gaugeDir,session){const store=openLocalStore(gaugeDir);try{store.upsertSession(session)}finally{store.close()}}async function drive(directory,summary,canceled,session={getSessionStatus,stopSession,finishSession}){let endedBy="session";let stopDetail;for(;;){if(canceled()&&endedBy!=="user_cancel"){endedBy="user_cancel";await session.stopSession(directory)}const status=await session.getSessionStatus(directory);if(status.state==="waiting"&&endedBy==="session"){endedBy="supervisor_finish";await session.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 session.stopSession(directory)}else if(["completed","failed","canceled","interrupted"].includes(status.state)){if(status.cleanupPending||status.state==="interrupted")await session.stopSession(directory);const final=await session.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 writeFile(temporary,`${JSON.stringify(value,null,2)}
6
+ `,{mode:384});await rename(temporary,path)}export{LOCAL_MCP_HINT,assertLocalCapabilities,inspectLocalRuntime,inspectLocalGateway,pullLocalGateway,pullLocalRuntime,LOCAL_TARGETS,readProfiles,writeProfiles,setProfile,requireProfile,inspectLocalCredential,websiteUseSchema,deploymentSourceSchema,commentSourceSchema,websiteSourceSchema,parseWebFixtureInput,mergeWebFixtures,readWebFixtureArchive,freezeWebFixtures,LOCAL_AGENTS,analysisNext,planLocal,detachLocal,runLocal};
@@ -0,0 +1 @@
1
+ import{SessionUnavailableError,getSessionStatus,localId,openLocalStore}from"./chunk-PUNARKS2.js";import{existsSync,statSync}from"fs";import{open,readdir,readFile,stat}from"fs/promises";import{dirname,join}from"path";var TERMINAL=new Set(["completed","failed","canceled","interrupted"]);async function readJson(path){try{return JSON.parse(await readFile(path,"utf8"))}catch{return void 0}}var lineCache=new Map;async function readLines(path){let size;try{size=(await stat(path)).size}catch{lineCache.delete(path);return[]}let cached=lineCache.get(path);if(!cached||size<cached.bytes)cached={bytes:0,lines:[]};if(size>cached.bytes){const buffer=Buffer.alloc(size-cached.bytes);const file=await open(path,"r");try{await file.read(buffer,0,buffer.length,cached.bytes)}finally{await file.close()}const complete=buffer.lastIndexOf(10)+1;const lines=[...cached.lines];for(const line of buffer.subarray(0,complete).toString("utf8").split("\n")){if(!line)continue;try{lines.push(JSON.parse(line))}catch{}}cached={bytes:cached.bytes+complete,lines}}lineCache.set(path,cached);return cached.lines}var specCache=new Map;async function readSpec(attemptDir){const path=join(attemptDir,"spec.json");let mtimeMs;try{mtimeMs=(await stat(path)).mtimeMs}catch{return void 0}const cached=specCache.get(path);if(cached?.mtimeMs===mtimeMs)return cached.spec;const spec=await readJson(path);specCache.set(path,{mtimeMs,spec});return spec}async function names(path){try{return(await readdir(path,{withFileTypes:true})).filter(d=>d.isDirectory()).map(d=>d.name)}catch{return[]}}async function latestAttempt(gaugeDir,id){const attempts=join(gaugeDir,"runs",id,"attempts");const numbers=(await names(attempts)).map(Number).filter(Number.isSafeInteger);for(const n of numbers.sort((a,b)=>b-a)){const spec=await readSpec(join(attempts,String(n)));if(spec?.attempt?.runId!==id||spec.attempt.n!==n||typeof spec.attempt.batchId!=="string")continue;return{batchId:spec.attempt.batchId,directory:join(attempts,String(n),"session"),attempt:n}}return void 0}async function latestAttempts(gaugeDir){const ids=await names(join(gaugeDir,"runs"));const found=await Promise.all(ids.map(id=>latestAttempt(gaugeDir,id)));return new Map(ids.flatMap((id,i)=>found[i]?[[id,found[i]]]:[]))}var rowCache;function storeRows(gaugeDir){const path=join(gaugeDir,"gauge.sqlite");if(!existsSync(path))return new Map;const key=[path,`${path}-wal`].map(file=>{try{const{mtimeMs,size}=statSync(file);return`${mtimeMs}:${size}`}catch{return""}}).join("|");if(rowCache?.key===key)return rowCache.rows;try{const store=openLocalStore(gaugeDir);try{rowCache={key,rows:new Map(store.listSessions().map(row=>[row.id,row]))};return rowCache.rows}finally{store.close()}}catch{return new Map}}async function summarize(id,{batchId,directory,attempt},row){const attemptDir=dirname(directory);let[spec={},status,result]=await Promise.all([readSpec(attemptDir),readJson(join(directory,"status.json")),readJson(join(attemptDir,"result.json"))]);let state=result?.outcome??status?.state??"preparing";let lastKnownState=null;let unavailableDetail;if(!result&&!TERMINAL.has(state)){try{status=await getSessionStatus(directory,{timeoutMs:1e3});state=status.state}catch(error){if(error instanceof SessionUnavailableError)status=error.lastKnownStatus??status;result=await readJson(join(attemptDir,"result.json"));if(result)state=result.outcome;else{lastKnownState=status?.state??"preparing";state="unavailable";unavailableDetail="Controller status is unavailable; the session may still be running. Status will be checked again."}}}const measurement=spec.measurement;return{spec,session:{id,batchId,attempt,case:spec.case?.path??row?.case??null,agent:spec.agentName??row?.agent??null,model:spec.agent?.model??row?.model??null,sample:typeof spec.sample==="number"?spec.sample:null,measurement:measurement&&typeof measurement.id==="string"?{id:measurement.id,kind:measurement.kind,revision:measurement.revision}:null,state,lastKnownState,live:!result&&state!=="unavailable"&&!TERMINAL.has(state),turns:result?.turns??status?.turn??0,detail:unavailableDetail??result?.detail??status?.detail??null,createdAt:spec.createdAt??row?.createdAt??null,updatedAt:status?.updatedAt??null,endedAt:result?.endedAt??null,durationMs:result?.durationMs??null,inputTokens:row?.inputTokens??null,outputTokens:row?.outputTokens??null,analyzed:row?.analyzed??false}}}async function listWatchSessions(gaugeDir){const rows=storeRows(gaugeDir);const sessions=await Promise.all([...await latestAttempts(gaugeDir)].map(async([id,attempt])=>(await summarize(id,attempt,rows.get(id))).session));return sessions.sort((a,b)=>(b.createdAt??"").localeCompare(a.createdAt??"")||a.id.localeCompare(b.id))}function findAttempt(gaugeDir,id){return latestAttempt(gaugeDir,localId(id))}async function getWatchSession(gaugeDir,id){const attempt=await findAttempt(gaugeDir,id);if(!attempt)return void 0;const{session,spec}=await summarize(id,attempt,storeRows(gaugeDir).get(id));return{...session,prompt:spec.case?.prompt??null,criteria:spec.case?.criteria??null,preference:spec.case?.preference??null}}async function readWatchTrace(gaugeDir,id,after=-1){const attempt=await findAttempt(gaugeDir,id);if(!attempt)return void 0;const[events,inputs]=await Promise.all([readLines(join(attempt.directory,"events.ndjson")),readLines(join(attempt.directory,"inputs.ndjson"))]);return{events:events.filter(event=>event.seq>after).map(({seq,turn,observedAt,payload})=>({seq,turn,observedAt,payload})),inputs:inputs.map(({turn,observedAt,text,answer})=>typeof text==="string"?{turn,observedAt,text}:{turn,observedAt,answer})}}async function readWatchDiff(gaugeDir,id){const attempt=await findAttempt(gaugeDir,id);if(!attempt)return void 0;try{return await readFile(join(attempt.directory,"diff.patch"),"utf8")}catch{return""}}export{readJson,listWatchSessions,getWatchSession,readWatchTrace,readWatchDiff};