@withgauge/cli 0.25.1 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -56
- package/dist/batchWorker.js +1 -1
- package/dist/{chatApi-W6HW3HKD.js → chatApi-CLMRDLLS.js} +1 -1
- package/dist/{chunk-E24F53BZ.js → chunk-3I3IT3LG.js} +1 -1
- package/dist/chunk-MAANSWGU.js +2 -0
- package/dist/{chunk-UANK5LHE.js → chunk-NXOOFF5A.js} +1 -1
- package/dist/{chunk-WJTCHKG6.js → chunk-QWDJLPRW.js} +1 -1
- package/dist/index.js +111 -71
- package/dist/{orgDirectory-BZW2ZAD3.js → orgDirectory-QX23FAS2.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-RRLAI72I.js +0 -2
package/README.md
CHANGED
|
@@ -227,7 +227,7 @@ contains the execution preference. Git is optional for workspace initialization.
|
|
|
227
227
|
| Project inputs and previews on saved measurement launches | yes | use case files/specs |
|
|
228
228
|
| Findings and summary queries | yes, supported fields | yes |
|
|
229
229
|
| Personas, recurring schedules, PR checks | no | yes |
|
|
230
|
-
| Optimizations (
|
|
230
|
+
| Optimizations (edit and rerun sessions) | no | yes |
|
|
231
231
|
| Stored credentials for MCP servers and connections | no | yes |
|
|
232
232
|
| Additional reporting datasets, dashboards, org settings | no | yes |
|
|
233
233
|
|
|
@@ -288,12 +288,13 @@ migration example. Use `gauge instructions eval` and `gauge instructions prefere
|
|
|
288
288
|
preference prompts, and `gauge instructions session-analysis` to investigate
|
|
289
289
|
product choices, source exposure, and interventions, from individual traces to
|
|
290
290
|
larger cohorts.
|
|
291
|
-
Use `gauge instructions
|
|
291
|
+
Use `gauge instructions issues` to choose what to improve and
|
|
292
|
+
`gauge instructions optimization` for the full optimization workflow.
|
|
292
293
|
`gauge instructions --list` shows available topics.
|
|
293
294
|
|
|
294
295
|
Run `gauge --help` (or `gauge <command> --help`) for the full command set:
|
|
295
296
|
run, eval, preference, models, personas, skills, mcp, repos, optimizations,
|
|
296
|
-
brands, tags,
|
|
297
|
+
brands, tags, issues, dashboards, members, org, provider keys,
|
|
297
298
|
billing, usage, stats, query, and more.
|
|
298
299
|
|
|
299
300
|
## Run committed Markdown evals
|
|
@@ -715,69 +716,60 @@ omit it and every scenario runs. On a recurring cadence, an eval launch or a
|
|
|
715
716
|
full preference launch moves the next scheduled run to one period from now. A
|
|
716
717
|
scenario subset leaves the schedule unchanged.
|
|
717
718
|
|
|
719
|
+
## Issues (hosted)
|
|
720
|
+
|
|
721
|
+
An issue groups the same finding across many sessions. `gauge issues list` shows
|
|
722
|
+
every issue with the most sessions first, with its type and product. Friction
|
|
723
|
+
shows how badly it hurt agents (blocked, recovered, extra work). Objections come
|
|
724
|
+
from preference sessions and show where agents went instead. Filter with
|
|
725
|
+
`--type friction|objection`. `gauge issues get <id>` lists the issue's
|
|
726
|
+
findings with their runs. `gauge run insight <run>` shows each finding's issue.
|
|
727
|
+
|
|
718
728
|
## Optimizations (hosted)
|
|
719
729
|
|
|
720
|
-
|
|
730
|
+
Optimizations can help hill climb your agent surfaces to improve Agent
|
|
731
|
+
Preference and Agent Experience. You edit a tree of pages, skills,
|
|
732
|
+
and CLI rules; Gauge reruns the source sessions with the tree injected
|
|
733
|
+
and compares their findings. Nothing deploys.
|
|
721
734
|
|
|
722
735
|
```sh
|
|
723
736
|
gauge instructions optimization
|
|
724
|
-
gauge
|
|
725
|
-
gauge
|
|
726
|
-
gauge run
|
|
727
|
-
gauge optimizations
|
|
728
|
-
gauge optimizations
|
|
737
|
+
gauge issues list -o json # by impact; --type friction|objection
|
|
738
|
+
gauge issues get is_1 # the issue's findings and runs
|
|
739
|
+
gauge optimizations create --issue is_1 # or --finding <id> --run <run>, or --goal <text>
|
|
740
|
+
gauge optimizations sessions add op_1 run_1 run_2 # a goal starts with none; up to 12
|
|
741
|
+
gauge optimizations authoring op_1
|
|
742
|
+
gauge run trace run_1 --seq 42 # read the cited evidence
|
|
743
|
+
gauge run web run_1 # the exact URLs the session fetched
|
|
729
744
|
```
|
|
730
745
|
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
`
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
an alternative when you need to establish a baseline; do not combine it with
|
|
739
|
-
`--from-run`. Use `--preference` instead of `--eval` for preference prompts.
|
|
746
|
+
Tree keys are `page:<url>`, `skill:<name>`, and `cli:<package>`. Copy an
|
|
747
|
+
original in with `file add` so the diff shows only your edit. Change part of a
|
|
748
|
+
page with `file edit`: `edits.json` is `[{find, replace}]` on the exact source,
|
|
749
|
+
which `file read --query` shows. Each find must appear once, all edits apply or
|
|
750
|
+
none do, and the output shows how much of the page you kept. Use `file write`
|
|
751
|
+
for a new page, a full rewrite, a skill file, or CLI rules. Files not in the
|
|
752
|
+
tree rerun as the source session had them.
|
|
740
753
|
|
|
741
754
|
```sh
|
|
742
|
-
gauge optimizations
|
|
743
|
-
gauge optimizations
|
|
744
|
-
|
|
745
|
-
gauge optimizations
|
|
746
|
-
gauge optimizations
|
|
747
|
-
gauge optimizations
|
|
748
|
-
gauge optimizations
|
|
749
|
-
gauge optimizations
|
|
750
|
-
gauge optimizations
|
|
751
|
-
gauge optimizations handoff cl_1
|
|
752
|
-
gauge optimizations complete cl_1 --yes
|
|
755
|
+
gauge optimizations file add op_1 --page https://docs.acme.dev/auth
|
|
756
|
+
gauge optimizations file read op_1 page:https://docs.acme.dev/auth --text
|
|
757
|
+
gauge optimizations file read op_1 page:https://docs.acme.dev/auth --query "API key"
|
|
758
|
+
gauge optimizations file edit op_1 --page https://docs.acme.dev/auth --edits edits.json
|
|
759
|
+
gauge optimizations file write op_1 --skill acme --path SKILL.md --from SKILL.md
|
|
760
|
+
gauge optimizations notes op_1 --from notes.md
|
|
761
|
+
gauge optimizations launch op_1 --yes
|
|
762
|
+
gauge optimizations watch op_1
|
|
763
|
+
gauge optimizations finish op_1 --from result.json --yes
|
|
753
764
|
```
|
|
754
765
|
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
`
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
accepts v3 `{schemaVersion:3, target, rules, shippingIntent}` and returns a sealed
|
|
763
|
-
bundle to put in `CLI_INTERVENTION.after`. It does not save or launch. The old
|
|
764
|
-
catalog/invocation-ID workflow is retired. Skills use `skill-files` and the
|
|
765
|
-
complete edited file bundle.
|
|
766
|
-
|
|
767
|
-
A checkpoint is a saved state of a baseline run. Resuming it avoids repeating
|
|
768
|
-
earlier work. Gauge automatically selects a compatible checkpoint before the
|
|
769
|
-
affected interaction for docs and CLI candidates, or starts fresh with a reason.
|
|
770
|
-
You do not select a checkpoint; omit checkpoint choices and fork flags. Skills
|
|
771
|
-
start fresh. Inspect
|
|
772
|
-
`runs[].candidateExecution` for actual starting mode and `candidateDelivery`
|
|
773
|
-
for exposure, observed artifacts, and evidence completeness. A score improvement
|
|
774
|
-
does not prove the change was exercised. Report sample counts and failed sessions.
|
|
775
|
-
|
|
776
|
-
Read `nextAction` on optimization detail; `watch` exits 4 when input is needed.
|
|
777
|
-
Round save replaces pending drafts but never launches. Use `--yes` for approved
|
|
778
|
-
spending and `trials add --idempotency-key` when retrying single-trial writes.
|
|
779
|
-
Adoption selects a winner without changing the baseline or deploying the change;
|
|
780
|
-
`handoff` supplies instructions to implement it in your source repository.
|
|
766
|
+
`watch` waits until every rerun finishes and is analyzed, then shows each source
|
|
767
|
+
finding as resolved or returned, and new findings as introduced. `launches
|
|
768
|
+
<id> <launchId> -o json` reads one launch again. `result.json` is
|
|
769
|
+
`{summary, changed, resolved, returned, introduced}`.
|
|
770
|
+
|
|
771
|
+
CLI versions before 0.26.0 used an earlier optimizations API and now get an
|
|
772
|
+
update message. Run `npm install -g @withgauge/cli`.
|
|
781
773
|
|
|
782
774
|
## Compare runs
|
|
783
775
|
|
|
@@ -853,7 +845,7 @@ index or background indexing process is maintained.
|
|
|
853
845
|
|
|
854
846
|
Every read supports `-o json` for scripting. `GAUGE_API_TOKEN` overrides
|
|
855
847
|
stored credentials (useful in CI). Exit codes: `0` ok · `1` error ·
|
|
856
|
-
`2` usage · `3` billing-blocked
|
|
848
|
+
`2` usage · `3` billing-blocked.
|
|
857
849
|
|
|
858
850
|
## Gauge Chat
|
|
859
851
|
|
package/dist/batchWorker.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{runLocal}from"./chunk-
|
|
1
|
+
import{runLocal}from"./chunk-NXOOFF5A.js";import"./chunk-QV7MOO3M.js";import"./chunk-MAANSWGU.js";import"./chunk-OIGVDK3F.js";import"./chunk-PSBF4TEK.js";import{randomBytes}from"crypto";import{readFile,rename,rm,writeFile}from"fs/promises";import{dirname,join}from"path";var requestPath=process.argv[2];var directory=dirname(requestPath);var requestLoaded=false;try{const request=JSON.parse(await readFile(requestPath,"utf8"));if(!request||typeof request.batchId!=="string"||typeof request.gaugeDir!=="string"||!request.definition)throw new Error("Invalid batch request");requestLoaded=true;await rm(requestPath);await runLocal(request.definition,[],request.gaugeDir,()=>{},{batchId:request.batchId,credentialSelections:request.credentialSelections,measurement:request.measurement})}catch(error){process.exitCode=1;const detail=requestLoaded?String(error):"Could not read a valid background batch request. Start a new batch.";console.error(detail);const statusPath=join(directory,"status.json");const previous=await readFile(statusPath,"utf8").then(raw=>JSON.parse(raw)).catch(()=>({}));const finishedSessions=previous.finishedSessions??0;const status={...previous,state:"failed",detail,finishedSessions,queuedSessions:0,skippedSessions:Math.max(0,(previous.expectedSessions??0)-finishedSessions),supervisorPid:process.pid};const temporary=`${statusPath}.${randomBytes(6).toString("hex")}.tmp`;await writeFile(temporary,`${JSON.stringify(status,null,2)}
|
|
2
2
|
`,{mode:384});await rename(temporary,statusPath);await writeFile(join(directory,"error.txt"),detail,{mode:384})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CHAT_API_PREFIX,CHAT_BATCH_SIZE,ChatApiClient,DEFAULT_MAX_ITEMS,addPageOptions,categoryScope,chatPath,chatScope,chunks,createChatApiClient,csv,describeScopes,fetchAll,fetchPages,parsePositive,printPage,resolveChatCategory,resolveChatOrg,resolveTagIds,resolveTopicId,truncate,withCategory}from"./chunk-
|
|
1
|
+
import{CHAT_API_PREFIX,CHAT_BATCH_SIZE,ChatApiClient,DEFAULT_MAX_ITEMS,addPageOptions,categoryScope,chatPath,chatScope,chunks,createChatApiClient,csv,describeScopes,fetchAll,fetchPages,parsePositive,printPage,resolveChatCategory,resolveChatOrg,resolveTagIds,resolveTopicId,truncate,withCategory}from"./chunk-QWDJLPRW.js";import"./chunk-3I3IT3LG.js";import"./chunk-MAANSWGU.js";import"./chunk-OIGVDK3F.js";import"./chunk-PSBF4TEK.js";export{CHAT_API_PREFIX,CHAT_BATCH_SIZE,ChatApiClient,DEFAULT_MAX_ITEMS,addPageOptions,categoryScope,chatPath,chatScope,chunks,createChatApiClient,csv,describeScopes,fetchAll,fetchPages,parsePositive,printPage,resolveChatCategory,resolveChatOrg,resolveTagIds,resolveTopicId,truncate,withCategory};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CliError,createClient,resolveToken}from"./chunk-
|
|
1
|
+
import{CliError,createClient,resolveToken}from"./chunk-MAANSWGU.js";var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var isUuid=value=>UUID_RE.test(value);function credentialKind(token=resolveToken()){if(!token)return"none";if(token.startsWith("gauge_cli_"))return"session";if(token.startsWith("gauge_sk_")||!token.startsWith("gauge_"))return"api_key";return"legacy"}async function fetchDirectory(){if(credentialKind()==="legacy")throw new CliError("usage","This Agents token cannot list or select organizations in this version of the CLI.",{hint:"If GAUGE_API_TOKEN is set, unset it first. Then run `gauge auth login` and `gauge orgs`."});const{chatPath,createChatApiClient}=await import("./chatApi-CLMRDLLS.js");const{data}=await createChatApiClient().get(chatPath("orgs"));if(!Array.isArray(data))throw new CliError("internal","Gauge returned an organization list the CLI could not read.",{hint:"Try `gauge orgs` again. If this continues, contact Gauge support."});return data}async function findOrganization(value){const org=(await fetchDirectory()).find(org2=>org2.id===value||org2.slug===value);if(org)return org;const{chatPath,createChatApiClient}=await import("./chatApi-CLMRDLLS.js");return createChatApiClient().get(chatPath("orgs",value))}async function resolveOrgValue(value){return isUuid(value)?{id:value}:findOrganization(value)}function legacySelection(source){const message=source==="config"?"Your saved organization needs to be selected again after this CLI update.":source==="project"?"This project's organization needs to be selected again after this CLI update.":"The organization in this run file needs to be selected again after this CLI update.";const hint=source==="config"?"Run `gauge orgs` to see your organizations, then `gauge orgs use <slug>` to choose one. If you have only one organization, `gauge auth login` updates your saved choice automatically.":source==="project"?"Run `gauge orgs`, then `gauge orgs use <slug> --project` to update gauge.json.":"Run `gauge orgs`, then rerun your command with --org <slug>. Or remove org from the run file to use your saved organization.";throw new CliError("usage",message,{hint})}async function resolveSelection(value,source){if(source!=="flag"&&!isUuid(value))legacySelection(source);return resolveOrgValue(value)}async function keyOrganization(){const{createChatApiClient}=await import("./chatApi-CLMRDLLS.js");const org=(await createChatApiClient().me()).apiKey?.organization;if(!org)throw new CliError("internal","Gauge could not identify which organization this API key belongs to.",{hint:"Check the key in Settings \u2192 API Keys and try again."});return org}async function createdOrganization(agentsSlug){const{orgs}=await createClient().get("/api/v1/me");const id=orgs.find(org=>org.slug===agentsSlug)?.canonicalGaugeOrganizationId;if(!id)throw new CliError("internal","Your workspace was created, but it is not ready to select in the CLI yet.",{hint:"Run `gauge orgs` to check for it, then `gauge orgs use <slug>`. If it is missing, contact Gauge support; you don't need to create it again."});return findOrganization(id)}async function missingAgentsOrg(org){const match=(await fetchDirectory()).find(o=>o.id===org);if(match?.products?.agents!==false)return void 0;return new CliError("not_found",`${match.name} doesn't use Gauge Agents.`,{hint:"Run `gauge orgs` to see which products each organization uses."})}function productsLabel(products){if(!products)return"unknown";return[products.chat?"Chat":void 0,products.agents?"Agents":void 0].filter(Boolean).join(", ")||"-"}export{isUuid,credentialKind,fetchDirectory,findOrganization,resolveOrgValue,legacySelection,resolveSelection,keyOrganization,createdOrganization,missingAgentsOrg,productsLabel};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{USER_AGENT,configDir,readConfig}from"./chunk-OIGVDK3F.js";import{__export}from"./chunk-PSBF4TEK.js";import{chmodSync,mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"fs";import{randomUUID}from"crypto";import{join}from"path";import{setTimeout as sleep}from"timers/promises";function credentialsPath(){return join(configDir(),"credentials")}function readCredentials(){try{const raw=readFileSync(credentialsPath(),"utf8").trim();if(!raw.startsWith("{"))return raw||null;const value=JSON.parse(raw);if(value.version!==1||typeof value.accessToken!=="string"||typeof value.authUrl!=="string"||typeof value.apiUrl!=="string")return null;return value}catch{return null}}function resolveToken(){const fromEnv=process.env.GAUGE_API_TOKEN?.trim();if(fromEnv)return fromEnv;const stored=readCredentials();return typeof stored==="string"?stored:stored?.accessToken??null}function atomicWrite(value){mkdirSync(configDir(),{recursive:true,mode:448});const temporary=`${credentialsPath()}.${randomUUID()}.tmp`;try{writeFileSync(temporary,`${value}
|
|
2
|
+
`,{encoding:"utf8",mode:384,flag:"wx"});chmodSync(temporary,384);renameSync(temporary,credentialsPath())}finally{rmSync(temporary,{force:true})}}function saveToken(token){atomicWrite(token.trim())}function saveCredentials(credentials){atomicWrite(JSON.stringify(credentials))}function clearToken(){rmSync(credentialsPath(),{force:true})}async function withCredentialLock(fn){mkdirSync(configDir(),{recursive:true,mode:448});const path=`${credentialsPath()}.lock`;const deadline=Date.now()+35e3;while(true){try{writeFileSync(path,String(process.pid),{flag:"wx",mode:384});break}catch(error){if(error.code!=="EEXIST")throw error;if(Date.now()>=deadline)throw new Error(`Timed out waiting for credential access. If no Gauge process is running, remove ${path} and retry.`);await sleep(50)}}try{return await fn()}finally{rmSync(path,{force:true})}}import{z}from"zod";var DEFAULT_AUTH_URL="https://app.withgauge.com";function resolveAuthUrl(){return(process.env.GAUGE_AUTH_URL||readConfig().authUrl||DEFAULT_AUTH_URL).replace(/\/+$/,"")}var sharedTokenSchema=z.object({accessToken:z.string().startsWith("gauge_cli_"),refreshToken:z.string().startsWith("gauge_refresh_"),tokenType:z.literal("bearer"),expiresAt:z.iso.datetime({offset:true}),refreshExpiresAt:z.iso.datetime({offset:true})});function storedSharedCredentials(){if(process.env.GAUGE_API_TOKEN?.trim())return null;const stored=readCredentials();return stored&&typeof stored!=="string"?stored:null}function assertTrustedOrigin(baseUrl,credentials){const origin=new URL(baseUrl).origin;if(![credentials.authUrl,credentials.apiUrl].some(value=>new URL(value).origin===origin))throw new Error("Your saved login is for a different Gauge server. Check GAUGE_AUTH_URL and GAUGE_API_URL, then run `gauge auth login` for the server you want to use.")}var RefreshError=class extends Error{constructor(message,unauthorized=false){super(message);this.unauthorized=unauthorized}unauthorized};function uncertainRefresh(){return new RefreshError("Gauge could not renew your login. Run `gauge auth login` to sign in again.",true)}async function refreshCredentials(previous,force=false){return withCredentialLock(async()=>{const current=readCredentials();if(!current||typeof current==="string")throw new Error("Your saved login changed. Run the command again.");if(current.sessionId!==previous.sessionId||current.authUrl!==previous.authUrl||current.apiUrl!==previous.apiUrl)throw new Error("Login changed while this command was running. Retry the command.");if(current.refreshPending)throw uncertainRefresh();if(current.accessToken!==previous.accessToken)return current;if(!current.refreshToken)return current;if(!force&&Date.parse(current.expiresAt??"")>Date.now()+6e4)return current;saveCredentials({...current,refreshPending:true});let response;try{response=await fetch(`${current.authUrl}/api/cli/refresh`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(15e3),headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({refreshToken:current.refreshToken})})}catch{throw uncertainRefresh()}if(response.status===429){saveCredentials(current);throw new RefreshError("Gauge is receiving too many sign-in requests. Wait a moment, then try again.")}if(!response.ok)throw response.status===401?new RefreshError("Your login is no longer valid. Run `gauge auth login` to sign in again.",true):uncertainRefresh();try{const tokens=sharedTokenSchema.parse(await response.json());const next={...current,...tokens};delete next.refreshPending;const latest=readCredentials();if(!latest||typeof latest==="string"||latest.refreshToken!==current.refreshToken)throw new Error("Your saved login changed while Gauge was renewing it. Run the command again.");saveCredentials(next);return next}catch{throw uncertainRefresh()}})}var batteries_exports={};__export(batteries_exports,{BATTERY_AGENTS:()=>BATTERY_AGENTS,BATTERY_CADENCES:()=>BATTERY_CADENCES,BATTERY_MAX_LIMITS:()=>BATTERY_MAX_LIMITS,MAX_SAMPLES_PER_CYCLE:()=>MAX_SAMPLES_PER_CYCLE,batchDetailSchema:()=>batchDetailSchema,batchListQuerySchema:()=>batchListQuerySchema,batchListResponseSchema:()=>batchListResponseSchema,batchRunStatusSchema:()=>batchRunStatusSchema,batchRunSummarySchema:()=>batchRunSummarySchema,batchSummarySchema:()=>batchSummarySchema,batteryAgentSchema:()=>batteryAgentSchema,batteryApplyResponseSchema:()=>batteryApplyResponseSchema,batteryDefaultsSchema:()=>batteryDefaultsSchema,batteryLimitsSchema:()=>batteryLimitsSchema,batteryPlanPromptSchema:()=>batteryPlanPromptSchema,batteryPlanScheduleSchema:()=>batteryPlanScheduleSchema,batteryPlanSchema:()=>batteryPlanSchema,batteryPromptSpecSchema:()=>batteryPromptSpecSchema,batteryScheduleSpecSchema:()=>batteryScheduleSpecSchema,batterySkillRefSchema:()=>batterySkillRefSchema,batterySkillsSchema:()=>batterySkillsSchema,batterySpecSchema:()=>batterySpecSchema});import{z as z3}from"zod";import{z as z2}from"zod";var ERROR_CODES=["unauthorized","forbidden","not_found","invalid_request","insufficient_credits","needs_provider_key","rate_limited","conflict","internal","upgrade_required"];var errorCodeSchema=z2.enum(ERROR_CODES);var upgradeOfferSchema=z2.object({skuId:z2.string(),tierLabel:z2.string(),monthlyAmountCents:z2.number().int(),monthlyCredits:z2.number().int(),billingUrl:z2.string()});var errorEnvelopeSchema=z2.object({error:z2.object({code:errorCodeSchema,message:z2.string(),upgrade:upgradeOfferSchema.optional()})});var listQuerySchema=z2.object({limit:z2.coerce.number().int().min(1).max(200).default(50),cursor:z2.string().optional()});function listResponseSchema(item){return z2.object({items:z2.array(item),nextCursor:z2.string().optional()})}var createdBySchema=z2.object({userId:z2.string().nullable(),email:z2.string().nullable(),name:z2.string().nullable()}).nullable().optional();var BATTERY_AGENTS=["CLAUDE_CODE","CODEX_CLI","CURSOR","PI","OPENCODE","ANTIGRAVITY"];var BATTERY_CADENCES=["NONE"];var batteryAgentSchema=z3.enum(BATTERY_AGENTS);var BATTERY_MAX_LIMITS={maxTurns:30,wallClockS:5400,maxUsd:10};var MAX_SAMPLES_PER_CYCLE=50;var batteryLimitsSchema=z3.object({maxTurns:z3.number().positive().max(BATTERY_MAX_LIMITS.maxTurns).optional(),wallClockS:z3.number().positive().max(BATTERY_MAX_LIMITS.wallClockS).optional(),maxUsd:z3.number().positive().max(BATTERY_MAX_LIMITS.maxUsd).optional()});var batterySkillRefSchema=z3.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*@\S+$/,'skills entries must be "name@label" (a bare name is a search, not a reference)');var batterySkillsSchema=z3.array(batterySkillRefSchema);var batteryScheduleSpecSchema=z3.object({repoUrl:z3.string().nullish(),repoRef:z3.string().nullish(),model:z3.string().nullable().optional(),agents:z3.array(batteryAgentSchema).optional(),samplesPerCycle:z3.number().int().min(1).max(MAX_SAMPLES_PER_CYCLE).optional(),cadence:z3.enum(BATTERY_CADENCES).optional(),experiment:z3.string().optional(),limits:batteryLimitsSchema.optional(),skills:batterySkillsSchema.optional()});var batteryDefaultsSchema=z3.object({isBranded:z3.boolean().optional(),topic:z3.string().optional(),tags:z3.array(z3.string()).optional(),model:z3.string().nullable().optional(),agents:z3.array(batteryAgentSchema).optional(),samplesPerCycle:z3.number().int().min(1).max(MAX_SAMPLES_PER_CYCLE).optional(),cadence:z3.enum(BATTERY_CADENCES).optional(),limits:batteryLimitsSchema.optional(),skills:batterySkillsSchema.optional()});var batteryPromptSpecSchema=z3.object({key:z3.string().min(1),text:z3.string().min(1),isBranded:z3.boolean().optional(),topic:z3.string().optional(),tags:z3.array(z3.string()).optional(),experiment:z3.string().optional(),schedules:z3.array(batteryScheduleSpecSchema).optional()});var batterySpecSchema=z3.object({version:z3.literal(1),org:z3.string().optional(),experiment:z3.string().optional(),expand:z3.boolean().optional(),defaults:batteryDefaultsSchema.optional(),prompts:z3.array(batteryPromptSpecSchema).min(1)});var batteryPlanScheduleSchema=z3.object({action:z3.enum(["create","update","none"]),repoUrl:z3.string().nullable(),repoRef:z3.string().nullable(),runs:z3.number().int()});var batteryPlanPromptSchema=z3.object({key:z3.string(),action:z3.enum(["create","update"]),schedules:z3.array(batteryPlanScheduleSchema)});var batteryPlanSchema=z3.object({dryRun:z3.literal(true),org:z3.string(),experiment:z3.string().nullable(),expand:z3.boolean(),prompts:z3.array(batteryPlanPromptSchema),summary:z3.object({promptsToCreate:z3.number().int(),promptsToUpdate:z3.number().int(),schedulesToCreate:z3.number().int(),schedulesToUpdate:z3.number().int(),runsToEnqueue:z3.number().int(),runsByAgent:z3.record(z3.string(),z3.number().int()),estimatedCredits:z3.number().int()})});var batteryApplyResponseSchema=z3.object({batchIds:z3.array(z3.string()),runIds:z3.array(z3.string()),experiment:z3.string().nullable(),blocked:z3.enum(["insufficient_credits","needs_provider_key"]).optional()});var batchRunStatusSchema=z3.enum(["QUEUED","CLAIMED","PROVISIONING","RUNNING","SUCCEEDED","FAILED","TIMED_OUT","CANCELED"]);var batchListQuerySchema=listQuerySchema.extend({promptId:z3.string().optional(),experiment:z3.string().optional()});var batchSummarySchema=z3.object({id:z3.string(),promptId:z3.string(),promptText:z3.string(),experiment:z3.string().nullable(),createdAt:z3.string(),runCounts:z3.record(z3.string(),z3.number().int())});var batchListResponseSchema=listResponseSchema(batchSummarySchema);var batchRunSummarySchema=z3.object({id:z3.string(),agent:z3.string(),model:z3.string(),status:batchRunStatusSchema,createdAt:z3.string(),startedAt:z3.string().nullable(),finishedAt:z3.string().nullable()});var batchDetailSchema=z3.object({id:z3.string(),promptId:z3.string(),promptText:z3.string(),scenario:z3.string(),repoUrl:z3.string().nullable(),repoRef:z3.string().nullable(),experiment:z3.string().nullable(),funding:z3.string(),createdAt:z3.string(),runCounts:z3.record(z3.string(),z3.number().int()),runs:z3.array(batchRunSummarySchema)});var brands_exports={};__export(brands_exports,{BRAND_KINDS:()=>BRAND_KINDS,BRAND_PACKAGE_ECOSYSTEMS:()=>BRAND_PACKAGE_ECOSYSTEMS,brandKindSchema:()=>brandKindSchema,brandListResponseSchema:()=>brandListResponseSchema,brandPackageEcosystemSchema:()=>brandPackageEcosystemSchema,brandPackageInputSchema:()=>brandPackageInputSchema,brandPackageSchema:()=>brandPackageSchema,brandSchema:()=>brandSchema,createBrandBodySchema:()=>createBrandBodySchema,listBrandsQuerySchema:()=>listBrandsQuerySchema,updateBrandBodySchema:()=>updateBrandBodySchema});import{z as z4}from"zod";var BRAND_KINDS=["OWNED","COMPETITOR","OTHER"];var brandKindSchema=z4.enum(BRAND_KINDS);var BRAND_PACKAGE_ECOSYSTEMS=["npm","pypi","cargo","go","rubygems","other"];var brandPackageEcosystemSchema=z4.enum(BRAND_PACKAGE_ECOSYSTEMS);var brandPackageSchema=z4.object({name:z4.string(),ecosystem:z4.string().nullable()});var brandSchema=z4.object({id:z4.string(),name:z4.string(),kind:brandKindSchema,source:z4.string(),aliases:z4.array(z4.string()),websites:z4.array(z4.string()),category:z4.string().nullable(),packages:z4.array(brandPackageSchema),createdAt:z4.string(),updatedAt:z4.string()});var brandPackageInputSchema=z4.object({name:z4.string().min(1),ecosystem:brandPackageEcosystemSchema.nullable().optional()});var createBrandBodySchema=z4.object({name:z4.string().min(1),kind:brandKindSchema,aliases:z4.array(z4.string().min(1)).default([]),websites:z4.array(z4.string().min(1)).default([]),packages:z4.array(brandPackageInputSchema).default([])});var updateBrandBodySchema=z4.object({name:z4.string().min(1).optional(),kind:brandKindSchema.optional(),aliases:z4.array(z4.string().min(1)).optional(),websites:z4.array(z4.string().min(1)).optional(),packages:z4.array(brandPackageInputSchema).optional()});var listBrandsQuerySchema=listQuerySchema.extend({kind:brandKindSchema.optional()});var brandListResponseSchema=listResponseSchema(brandSchema);var feedback_exports={};__export(feedback_exports,{FEEDBACK_KINDS:()=>FEEDBACK_KINDS,createFeedbackBodySchema:()=>createFeedbackBodySchema,createFeedbackResponseSchema:()=>createFeedbackResponseSchema,feedbackKindSchema:()=>feedbackKindSchema});import{z as z5}from"zod";var FEEDBACK_KINDS=["friction","missing","bug","other"];var feedbackKindSchema=z5.enum(FEEDBACK_KINDS);var createFeedbackBodySchema=z5.object({message:z5.string().trim().min(1).max(4e3),kind:feedbackKindSchema.default("other"),command:z5.string().trim().max(500).optional(),org:z5.string().optional()});var createFeedbackResponseSchema=z5.object({id:z5.string()});var keys_exports={};__export(keys_exports,{PROVIDER_TYPES:()=>PROVIDER_TYPES,providerKeyListResponseSchema:()=>providerKeyListResponseSchema,providerKeySchema:()=>providerKeySchema,providerTypeSchema:()=>providerTypeSchema,setProviderKeyBodySchema:()=>setProviderKeyBodySchema,setProviderKeyResponseSchema:()=>setProviderKeyResponseSchema});import{z as z6}from"zod";var PROVIDER_TYPES=["anthropic","openai"];var providerTypeSchema=z6.enum(PROVIDER_TYPES);var setProviderKeyBodySchema=z6.object({key:z6.string().min(1)});var setProviderKeyResponseSchema=z6.object({providerType:providerTypeSchema,last4:z6.string()});var providerKeySchema=z6.object({providerType:providerTypeSchema,last4:z6.string(),createdAt:z6.string(),updatedAt:z6.string()});var providerKeyListResponseSchema=listResponseSchema(providerKeySchema);var runConfig_exports={};__export(runConfig_exports,{ROSTERABLE_AGENTS:()=>ROSTERABLE_AGENTS,SCHEDULABLE_AGENTS:()=>SCHEDULABLE_AGENTS,agentConfigInputSchema:()=>agentConfigInputSchema,agentConfigSchema:()=>agentConfigSchema,assetRefListSchema:()=>assetRefListSchema,assetRefSchema:()=>assetRefSchema,modelUnits:()=>modelUnits,refAssetName:()=>refAssetName,rosterableAgentSchema:()=>rosterableAgentSchema,runsPerCycle:()=>runsPerCycle,schedulableAgentSchema:()=>schedulableAgentSchema,totalRunsPerCycle:()=>totalRunsPerCycle});import{z as z9}from"zod";import{z as z8}from"zod";var INTERVENTION_KINDS=["BASELINE","ADD_SKILL","REMOVE_SKILL","EDIT_SKILL","REWRITE_DOCS","PACKAGE_VERSION","PACKAGE_CONTENT","CLI_VERSION","CLI_INTERVENTION"];import{z as z7}from"zod";var ANALYSIS_SCHEMA_VERSION=1;var evidenceSequenceSchema=z7.number().int().nonnegative().describe("The event's recorded seq in this session attempt. Never infer it from an array index, line number, or turn.");var evidenceRefSchema=z7.discriminatedUnion("kind",[z7.object({kind:z7.literal("trace"),seq:evidenceSequenceSchema}).strict(),z7.object({kind:z7.literal("diff"),path:z7.string().min(1)}).strict()]);var INSTALL_PHASES=["NONE","ATTEMPTED","CONFIGURED","EXERCISED"];var sessionProductSchema=z7.object({name:z7.string(),mentioned:z7.boolean(),considered:z7.boolean(),recommended:z7.boolean(),chosen:z7.boolean(),rejected:z7.boolean(),abandoned:z7.boolean(),installPhase:z7.enum(INSTALL_PHASES),rank:z7.number().int().nullable(),source:z7.enum(["BRIEF","PERSONA","PRIOR","SEARCH","PAGE","REPO","UNKNOWN"]),reason:z7.string(),categories:z7.array(z7.string()),evidence:z7.record(z7.string(),z7.array(evidenceRefSchema))});var sessionObservationSchema=z7.object({id:z7.string(),kind:z7.enum(["FRICTION","OBJECTION","OPPORTUNITY"]),label:z7.string(),detail:z7.string(),subject:z7.string(),basis:z7.enum(["OBSERVED","AGENT_CLAIM","INFERRED"]),effect:z7.enum(["BLOCKED","RECOVERED","EXTRA_WORK","SELECTION_LOSS","UNKNOWN"]),cause:z7.enum(["PRODUCT","CONTENT","ACCESS","ENVIRONMENT","AGENT","UNKNOWN"]),tags:z7.array(z7.string()),evidence:z7.array(evidenceRefSchema),issueId:z7.string().nullable().optional()});var sessionAnalysisSchema=z7.object({schemaVersion:z7.literal(ANALYSIS_SCHEMA_VERSION),instructionsVersion:z7.string().min(1),id:z7.string(),runId:z7.string(),attempt:z7.number().int(),createdAt:z7.string(),origin:z7.enum(["MODEL","LEGACY"]),model:z7.string().nullable(),assessability:z7.enum(["ASSESSED","PARTIAL","UNASSESSABLE"]),limitation:z7.string().nullable(),selection:z7.enum(["MEASURED","UNASSESSABLE","NOT_MEASURED"]),directed:z7.boolean(),products:z7.array(sessionProductSchema),observations:z7.array(sessionObservationSchema)});var artifactPathSchema=z7.string().min(1).refine(value=>!value.startsWith("/")&&!value.includes("\\")&&!value.split("/").some(part=>part===".."||part===""),"Evidence paths must be relative paths inside the session artifacts");var portableEvidenceRefSchema=z7.discriminatedUnion("kind",[z7.object({kind:z7.literal("trace"),seq:evidenceSequenceSchema}).strict(),z7.object({kind:z7.literal("diff"),path:artifactPathSchema}).strict(),z7.object({kind:z7.literal("artifact"),artifact:artifactPathSchema.describe("Path relative to the session attempt directory, for example session/events.ndjson."),attempt:z7.number().int().positive().optional().describe("Must match the analysis attempt; defaults to that attempt."),line:z7.number().int().positive().optional().describe("One-based line number in the original artifact, before any filtering."),endLine:z7.number().int().positive().optional().describe("Inclusive last line of the evidence range."),seq:evidenceSequenceSchema.optional()}).strict().superRefine((ref,ctx)=>{if(ref.line===void 0&&ref.seq===void 0)ctx.addIssue({code:"custom",message:"Artifact evidence needs a line or seq"});if(ref.endLine!==void 0&&(ref.line===void 0||ref.endLine<ref.line))ctx.addIssue({code:"custom",path:["endLine"],message:"endLine requires line and must be at least line"})})]);var findingSubmissionSchema=sessionObservationSchema.omit({id:true,issueId:true}).extend({label:z7.string().trim().min(1).max(200),detail:z7.string().trim().min(1).max(1e4),subject:z7.string().trim().min(1).max(200),tags:z7.array(z7.string().trim().min(1).max(64)).max(32).default([]),evidence:z7.array(portableEvidenceRefSchema).min(1).max(100)}).strict();var criterionAnalysisSubmissionSchema=z7.object({criterionId:z7.string().min(1),outcome:z7.enum(["PASS","FAIL","UNASSESSABLE"]),label:z7.string().trim().min(1).max(1e4),evidence:z7.array(portableEvidenceRefSchema).max(100).default([])}).strict().superRefine((result,ctx)=>{if(result.outcome!=="UNASSESSABLE"&&result.evidence.length===0)ctx.addIssue({code:"custom",path:["evidence"],message:"A criterion verdict needs evidence"})});var productSubmissionSchema=sessionProductSchema.extend({name:z7.string().trim().min(1).max(200),evidence:z7.record(z7.string(),z7.array(portableEvidenceRefSchema))}).strict().superRefine((product,ctx)=>{if((product.chosen||product.rejected||product.recommended)&&!product.considered)ctx.addIssue({code:"custom",path:["considered"],message:"A chosen, rejected, or recommended product was considered"});if(product.considered&&!product.mentioned)ctx.addIssue({code:"custom",path:["mentioned"],message:"A considered product was mentioned"});if(!Object.values(product.evidence).some(refs=>refs.length>0))ctx.addIssue({code:"custom",path:["evidence"],message:"A product judgment needs evidence"})});var analysisSubmissionSchema=z7.object({schemaVersion:z7.literal(ANALYSIS_SCHEMA_VERSION),attempt:z7.number().int().positive().default(1),instructionsVersion:z7.string().trim().min(1),analyst:z7.object({name:z7.string().trim().min(1),model:z7.string().trim().min(1).optional()}).strict(),assessability:sessionAnalysisSchema.shape.assessability,limitation:z7.string().trim().min(1).nullable().default(null),selection:sessionAnalysisSchema.shape.selection.default("NOT_MEASURED"),directed:z7.boolean().default(false),findings:z7.array(findingSubmissionSchema).max(1e3).default([]),products:z7.array(productSubmissionSchema).max(1e3).default([]),criteria:z7.array(criterionAnalysisSubmissionSchema).max(1e3).default([])}).strict().superRefine((analysis,ctx)=>{for(const field of["products","criteria"]){const keys=field==="products"?analysis.products.map(product=>product.name.toLowerCase()):analysis.criteria.map(criterion=>criterion.criterionId);if(new Set(keys).size!==keys.length)ctx.addIssue({code:"custom",path:[field],message:`Duplicate ${field} are not allowed`})}if(analysis.assessability!=="ASSESSED"&&analysis.limitation===null)ctx.addIssue({code:"custom",path:["limitation"],message:"Partial or unassessable analysis needs a limitation"})});var RUN_STATUSES=["QUEUED","CLAIMED","PROVISIONING","RUNNING","SUCCEEDED","FAILED","TIMED_OUT","CANCELED"];var runStatusSchema=z8.enum(RUN_STATUSES);var AGENTS=["CLAUDE_CODE","CODEX_CLI","CURSOR","PI","OPENCODE","ANTIGRAVITY"];var agentSchema=z8.enum(AGENTS);var OBSERVED_PROVIDER_SOURCES=["AGENT_STREAM","GATEWAY_RESPONSE","GATEWAY_AUDIT","CANARY"];var observedProviderSourceSchema=z8.enum(OBSERVED_PROVIDER_SOURCES);var selectedProviderSchema=z8.object({slug:z8.string(),displayName:z8.string()});var observedProviderSchema=z8.object({slug:z8.string(),source:observedProviderSourceSchema});var RUN_TRIGGER_SOURCES=["UNKNOWN","UI","API","CADENCE","STAFF","OPERATOR","GITHUB"];var runTriggerSourceSchema=z8.enum(RUN_TRIGGER_SOURCES);var runTriggeredBySchema=z8.object({source:runTriggerSourceSchema,userId:z8.string().nullable(),email:z8.string().nullable()});var runOptimizationTrialSchema=z8.object({optimizationId:z8.string(),trialId:z8.string(),key:z8.string(),title:z8.string(),kind:z8.enum(INTERVENTION_KINDS)});var runCreditsChargedSchema=z8.number().int().nullable();var runStatusFilterSchema=z8.string().transform(raw=>raw.split(",").map(s=>s.trim().toUpperCase()).filter(Boolean)).pipe(z8.array(runStatusSchema).min(1));var runListQuerySchema=listQuerySchema.extend({status:runStatusFilterSchema.optional(),batch:z8.string().optional(),prompt:z8.string().optional(),experiment:z8.string().optional(),evalSet:z8.string().optional(),since:z8.string().optional()});var runListItemSchema=z8.object({id:z8.string(),status:runStatusSchema,agent:agentSchema,model:z8.string(),resolvedModel:z8.string().nullable().optional(),modelDisplayName:z8.string().nullable().optional(),selectedProvider:selectedProviderSchema.nullable().optional(),observedProvider:observedProviderSchema.nullable().optional(),promptId:z8.string(),promptSnippet:z8.string(),batchId:z8.string(),experiment:z8.string().nullable(),evalSetId:z8.string().nullable(),evalRevision:z8.string().optional(),optimizationTrial:runOptimizationTrialSchema.nullable().optional(),turns:z8.number().int().nullable(),usdCost:z8.number().nullable(),creditsCharged:runCreditsChargedSchema.optional(),triggeredBy:runTriggeredBySchema.optional(),durationMs:z8.number().int().nullable(),exitReason:z8.string().nullable(),createdAt:z8.string(),startedAt:z8.string().nullable(),finishedAt:z8.string().nullable(),parentRunId:z8.string().nullable(),fetchForkPlanId:z8.string().nullable()});var runListResponseSchema=listResponseSchema(runListItemSchema);var runSkillSchema=z8.discriminatedUnion("source",[z8.object({source:z8.literal("saved"),skillId:z8.string(),name:z8.string(),label:z8.string()}),z8.object({source:z8.literal("input"),name:z8.string(),commit:z8.string().nullable(),pullNumber:z8.number().int().nullable()})]);var runDetailSchema=runListItemSchema.omit({promptSnippet:true}).extend({promptText:z8.string(),attempt:z8.number().int(),cancelRequested:z8.boolean(),failureReason:z8.string().nullable(),repoUrl:z8.string().nullable(),repoRef:z8.string().nullable(),scenario:z8.string(),funding:z8.string(),usage:z8.unknown().nullable(),hasDiff:z8.boolean(),claimedAt:z8.string().nullable(),criterionResults:z8.array(z8.object({criterionId:z8.string().nullable(),name:z8.string(),passed:z8.boolean().nullable(),reasoning:z8.string().nullable()})),skills:z8.array(runSkillSchema).optional()});var cancelRunResponseSchema=z8.object({id:z8.string(),status:runStatusSchema,cancelRequested:z8.boolean(),note:z8.string().optional()});var regradeRunResponseSchema=z8.object({runId:z8.string(),evalSetId:z8.string().nullable(),criteria:z8.number().int()});var RUN_INSIGHT_STATUSES=["PENDING","RUNNING","COMPLETE","FAILED","SKIPPED"];var runInsightStatusSchema=z8.enum(RUN_INSIGHT_STATUSES);var insightPassSchema=z8.object({status:runInsightStatusSchema,model:z8.string().nullable(),inputTokens:z8.number().int().nullable(),outputTokens:z8.number().int().nullable(),usdCost:z8.number().nullable(),error:z8.string().nullable()});var runDecisionSchema=z8.object({index:z8.number().int(),category:z8.string(),categoryRaw:z8.string().nullable(),chosenName:z8.string(),chosenEcosystem:z8.string().nullable(),chosenPackage:z8.string().nullable(),reversed:z8.boolean(),detail:z8.unknown()});var RUN_INSIGHT_PASS_KINDS=["ANALYSIS","CLI_DISCOVERY","LEVER","EXPERIMENT_DELTA"];var runInsightPassKindSchema=z8.enum(RUN_INSIGHT_PASS_KINDS);var insightPipelinePassSchema=insightPassSchema.extend({kind:runInsightPassKindSchema});var runInsightResponseSchema=z8.object({runId:z8.string(),decision:insightPassSchema,passes:z8.array(insightPipelinePassSchema),decisions:z8.array(runDecisionSchema),experimentDelta:z8.unknown().nullable(),visibilityVerdict:z8.unknown().nullable(),analysis:sessionAnalysisSchema.nullable()});var runEventSchema=z8.looseObject({run_id:z8.string(),seq:z8.number(),turn:z8.number(),ts:z8.string(),type:z8.string()});var runCompareSideSchema=z8.object({runRequest:z8.string().min(1).optional(),batch:z8.array(z8.string().min(1)).min(1).max(100).optional(),evalSet:z8.string().min(1).optional(),evalRevision:z8.string().min(1).optional(),trial:z8.string().min(1).optional(),experiment:z8.string().min(1).optional(),agent:z8.array(agentSchema).min(1).optional(),model:z8.array(z8.string()).min(1).optional(),since:z8.string().optional(),until:z8.string().optional()}).strict().refine(side=>side.runRequest!==void 0||side.batch!==void 0||side.evalSet!==void 0||side.experiment!==void 0||side.trial!==void 0,"Select runs with runRequest, batch, evalSet, experiment, or trial");var runCompareBodySchema=z8.object({baseline:runCompareSideSchema,candidate:runCompareSideSchema}).strict();var runCompareStatsSchema=z8.object({runs:z8.number().int(),finished:z8.number().int(),succeeded:z8.number().int(),judged:z8.number().int(),passed:z8.number().int(),passRate:z8.number().nullable(),medianTurns:z8.number().nullable(),medianUsdCost:z8.number().nullable(),medianDurationMs:z8.number().nullable(),criteria:z8.array(z8.object({name:z8.string(),judged:z8.number().int(),passed:z8.number().int(),passRate:z8.number().nullable()}))});var runCompareDeltaSchema=z8.object({passRate:z8.number().nullable(),medianTurns:z8.number().nullable(),medianUsdCost:z8.number().nullable(),medianDurationMs:z8.number().nullable(),criteria:z8.array(z8.object({name:z8.string(),passRate:z8.number().nullable()}))});var runCompareRowSchema=z8.object({baseline:runCompareStatsSchema,candidate:runCompareStatsSchema,delta:runCompareDeltaSchema});var runCompareMixedRevisionSchema=z8.object({evalSetId:z8.string().nullable(),promptId:z8.string().nullable(),revisions:z8.array(z8.string())});var runCompareTrialSchema=runOptimizationTrialSchema.extend({runs:z8.number().int()});var runCompareResponseSchema=z8.object({overall:runCompareRowSchema,targets:z8.array(runCompareRowSchema.extend({agent:agentSchema,model:z8.string()})),sides:z8.object({baseline:z8.object({evalRevisions:z8.array(z8.string()),mixedRevisions:z8.array(runCompareMixedRevisionSchema).optional(),truncated:z8.boolean(),trials:z8.array(runCompareTrialSchema).optional()}),candidate:z8.object({evalRevisions:z8.array(z8.string()),mixedRevisions:z8.array(runCompareMixedRevisionSchema).optional(),truncated:z8.boolean(),trials:z8.array(runCompareTrialSchema).optional()})})});var SCHEDULABLE_AGENTS=["CLAUDE_CODE","CODEX_CLI","PI","OPENCODE"];var schedulableAgentSchema=z9.enum(SCHEDULABLE_AGENTS);var ROSTERABLE_AGENTS=[...SCHEDULABLE_AGENTS,"ANTIGRAVITY"];var rosterableAgentSchema=z9.enum(ROSTERABLE_AGENTS);var agentConfigSchema=z9.object({agent:agentSchema,models:z9.array(z9.string().min(1))});var agentConfigInputSchema=z9.object({agent:rosterableAgentSchema,models:z9.array(z9.string().min(1)).default([])});var assetRefSchema=z9.string().max(320).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*@[^\s,]+$/,'asset references must be "name@label"');function refAssetName(ref){const at=ref.indexOf("@");return at<0?ref:ref.slice(0,at)}var assetRefListSchema=z9.array(assetRefSchema).superRefine((refs,ctx)=>{const names=new Set;for(const ref of refs){const name=refAssetName(ref);if(names.has(name)){ctx.addIssue({code:"custom",message:`"${ref}" names an asset already referenced \u2014 one version per asset`})}names.add(name)}});function modelUnits(agents){return agents.reduce((n,a)=>n+Math.max(1,a.models.length),0)}function runsPerCycle(owner,samplesPerCycle){return modelUnits(owner.agents)*samplesPerCycle}function totalRunsPerCycle(owners,samplesPerCycle){return owners.reduce((n,o)=>n+runsPerCycle(o,samplesPerCycle),0)}var DEFAULT_API_URL="https://agents.withgauge.com";function exitCodeFor(code){switch(code){case"usage":case"invalid_request":return 2;case"insufficient_credits":case"needs_provider_key":return 3;default:return 1}}var CliError=class extends Error{code;exitCode;hint;docs;needsAccount;apiCode;details;constructor(code,message,options={}){super(message);this.name="CliError";this.code=code;this.exitCode=exitCodeFor(code);this.hint=options.hint;this.docs=options.docs;this.needsAccount=options.needsAccount??false;this.apiCode=options.apiCode;this.details=options.details}};function resolveBaseUrl(){return process.env.GAUGE_API_URL||readConfig().apiUrl||DEFAULT_API_URL}var ApiClient=class{baseUrl;token;shared;authOptional;constructor(options={}){this.baseUrl=(options.baseUrl??resolveBaseUrl()).replace(/\/+$/,"");this.token=options.token!==void 0?options.token:resolveToken();this.authOptional=options.authOptional??false;this.shared=options.token===void 0?storedSharedCredentials():null;if(this.shared)assertTrustedOrigin(this.baseUrl,this.shared)}get signedIn(){return this.token!==null}async get(path,query,signal){return this.request("GET",path,{query,signal})}async post(path,body,query){return this.request("POST",path,{body,query})}async patch(path,body,query){return this.request("PATCH",path,{body,query})}async put(path,body,query){return this.request("PUT",path,{body,query})}async delete(path,query,body){return this.request("DELETE",path,{body,query})}async sse(path,onEvent,options={}){const res=await this.authenticatedFetch(this.url(path,options.query),{method:"GET",headers:this.headers({Accept:"text/event-stream"}),signal:options.signal});if(!res.ok)throw await this.toError(res);if(!res.body){throw new CliError("internal","Event stream had no response body")}const reader=res.body.getReader();const decoder=new TextDecoder;let buffer="";try{while(true){const{done,value}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:true});let boundary=buffer.indexOf("\n\n");while(boundary!==-1){const raw=buffer.slice(0,boundary);const event=parseSseFrame(raw);buffer=buffer.slice(boundary+2);if(event)onEvent(event);else if(raw.trimStart().startsWith(":"))options.onComment?.();boundary=buffer.indexOf("\n\n")}}}catch(error){if(error instanceof Error&&error.name==="AbortError")return;throw new CliError("network",`Event stream failed: ${messageOf(error)}`)}}url(path,query){const url=new URL(`${this.baseUrl}${path}`);for(const[key,value]of Object.entries(query??{})){if(Array.isArray(value))for(const item of value)url.searchParams.append(key,item);else if(value!==void 0)url.searchParams.set(key,String(value))}return url}headers(extra){if(!this.token&&!this.authOptional){throw new CliError("unauthorized","Not logged in. Run `gauge auth login` or set GAUGE_API_TOKEN.",{needsAccount:true})}return{...this.token?{Authorization:`Bearer ${this.token}`}:{},"User-Agent":USER_AGENT,Accept:"application/json",...extra}}async authenticatedFetch(url,init){let renewalFailed=false;if(this.shared?.refreshToken){try{const next=await refreshCredentials(this.shared);assertTrustedOrigin(this.baseUrl,next);this.shared=next;this.token=this.shared.accessToken}catch(error){if(error instanceof RefreshError&&error.unauthorized)throw new CliError("unauthorized",messageOf(error));if(!(error instanceof RefreshError)||!(Date.parse(this.shared.expiresAt??"")>Date.now()))throw new CliError("network",messageOf(error));renewalFailed=true}}const send=()=>this.fetch(url,{...init,redirect:"error",headers:{...init.headers,...this.token?{Authorization:`Bearer ${this.token}`}:{}}});const response=await send();if(response.status!==401||!this.shared?.refreshToken||renewalFailed)return response;await response.body?.cancel();try{const next=await refreshCredentials(this.shared,true);assertTrustedOrigin(this.baseUrl,next);this.shared=next;this.token=this.shared.accessToken}catch(error){throw new CliError(error instanceof RefreshError&&error.unauthorized?"unauthorized":"network",messageOf(error))}return send()}async fetch(url,init){try{return await fetch(url,init)}catch(error){if(error instanceof Error&&error.name==="AbortError")throw error;throw new CliError("network",`Request to ${url.host} failed: ${messageOf(error)}`)}}async request(method,path,options={}){const headers=this.headers(options.body===void 0?void 0:{"Content-Type":"application/json"});const res=await this.authenticatedFetch(this.url(path,options.query),{method,headers,body:options.body===void 0?void 0:JSON.stringify(options.body),signal:options.signal});if(!res.ok)throw await this.toError(res);if(res.status===204)return void 0;const text=await res.text();if(!text)return void 0;const contentType=res.headers.get("content-type")??"";if(contentType.includes("application/json")){return JSON.parse(text)}return text}async toError(res){const wait=res.status===429?retryAfterSeconds(res):void 0;const hint=wait===void 0?void 0:`Try again in ${wait} s.`;try{const parsed=errorEnvelopeSchema.safeParse(await res.clone().json());if(parsed.success){const{code,message}=parsed.data.error;if(code==="not_found"&&message.startsWith("Organization not found")){const explained=await explainMissingOrg(res.url);if(explained)return explained}return new CliError(code,message,{hint})}}catch{}const what=res.status===429?"Rate limited by the Gauge API":res.status>=500?"Gauge API server error":"API request failed";return new CliError(codeForStatus(res.status),`${what}: HTTP ${res.status} ${res.statusText}`.trim(),{hint})}};async function explainMissingOrg(url){const match=url&&/\/api\/v1\/orgs\/([^/?#]+)/.exec(new URL(url).pathname);if(!match)return void 0;try{const{missingAgentsOrg}=await import("./orgDirectory-QX23FAS2.js");return await missingAgentsOrg(decodeURIComponent(match[1]))}catch{return void 0}}function createClient(options){return new ApiClient(options)}function retryAfterSeconds(res){const value=res.headers.get("retry-after");if(!value)return void 0;const seconds=Number(value);const at=Date.parse(value);if(Number.isFinite(seconds))return Math.max(0,Math.ceil(seconds));if(Number.isNaN(at))return void 0;return Math.max(0,Math.ceil((at-Date.now())/1e3))}function codeForStatus(status){switch(status){case 400:return"invalid_request";case 401:return"unauthorized";case 402:return"insufficient_credits";case 403:return"forbidden";case 404:return"not_found";case 409:return"conflict";case 429:return"rate_limited";default:return"internal"}}function parseSseFrame(frame){let eventName;const dataLines=[];for(const line of frame.split("\n")){if(line.startsWith(":"))continue;if(line.startsWith("event:")){eventName=line.slice("event:".length).trim()}else if(line.startsWith("data:")){dataLines.push(line.slice("data:".length).replace(/^ /,""))}}if(dataLines.length===0)return null;return{event:eventName,data:dataLines.join("\n")}}function messageOf(error){if(error instanceof Error){const cause=error.cause instanceof Error?`: ${error.cause.message}`:"";return`${error.message}${cause}`}return String(error)}export{errorEnvelopeSchema,listResponseSchema,createdBySchema,batteries_exports,brands_exports,feedback_exports,keys_exports,ANALYSIS_SCHEMA_VERSION,analysisSubmissionSchema,agentSchema,runTriggeredBySchema,runCreditsChargedSchema,runEventSchema,agentConfigSchema,agentConfigInputSchema,assetRefListSchema,runConfig_exports,credentialsPath,readCredentials,resolveToken,saveToken,saveCredentials,clearToken,withCredentialLock,resolveAuthUrl,sharedTokenSchema,storedSharedCredentials,exitCodeFor,CliError,resolveBaseUrl,ApiClient,createClient,retryAfterSeconds,codeForStatus};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{DockerCli,PI_AGENT_DIR,agentEnv,cleanupGateway,harnessCommand,prepareScript,preserveWorkspace,shellQuote,splitModel,validateGateway}from"./chunk-QV7MOO3M.js";import{CliError}from"./chunk-
|
|
1
|
+
import{DockerCli,PI_AGENT_DIR,agentEnv,cleanupGateway,harnessCommand,prepareScript,preserveWorkspace,shellQuote,splitModel,validateGateway}from"./chunk-QV7MOO3M.js";import{CliError}from"./chunk-MAANSWGU.js";import{configDir}from"./chunk-OIGVDK3F.js";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 join7}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
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(spec.gateway){validateGateway(spec.gateway);if(process.getuid?.()===65532)throw new Error("Host UID 65532 is reserved for the local gateway")}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});let credentialDir;let handedOff=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:2,containerName,credentialDir,socketPath:join2(credentialDir,"control.sock"),spec:options.spec,credentialExpiresAt:credential.expiresAt?.toISOString(),...options.spec.gateway?{gatewayName:`${containerName}-gateway`,trustContainerName:`${containerName}-trust`}:{}};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");record.workload={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]};await writeJsonAtomic(join2(directory,"session.json"),record);const initial={state:"preparing",turn:0,updatedAt:new Date().toISOString(),cleanupPending:true};await writeJsonAtomic(join2(directory,"status.json"),{...initial,driverPid:process.pid});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;handedOff=true;child.unref();await writeJsonAtomic(join2(directory,"status.json"),{...initial,driverPid:child.pid});await writeFile(join2(credentialDir,"handoff"),"ready\n",{mode:384})}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(handedOff)throw error;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&&record.version!==2)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");if(record.gatewayName&&(record.gatewayName!==`${record.containerName}-gateway`||record.trustContainerName!==`${record.containerName}-trust`))throw new Error("Refusing cleanup: invalid gateway 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;try{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 cleanupGateway(record,directory,engine);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.state!=="interrupted"?saved.detail:"Interrupted session cleaned up explicitly",artifacts:workspace?{...saved?.artifacts,workspace}:saved?.artifacts})}catch(error){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(),cleanupPending:true,detail:`Cleanup incomplete: ${String(error)}; retry stopSession after resolving the error`});throw 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 join4}from"path";import{randomUUID as randomUUID3}from"crypto";import{chmodSync,existsSync,mkdirSync,readdirSync,readFileSync,statSync}from"fs";import{createRequire}from"module";import{join as join3}from"path";var LOCAL_DATABASE_VERSION=1;var schema=`
|
|
3
3
|
CREATE TABLE measurements (
|
|
4
4
|
id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK(kind IN ('eval','preference')),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{credentialKind,fetchDirectory,isUuid,keyOrganization,legacySelection,resolveSelection}from"./chunk-E24F53BZ.js";import{ApiClient,CliError,codeForStatus,resolveAuthUrl,resolveToken,retryAfterSeconds,storedSharedCredentials}from"./chunk-RRLAI72I.js";import{readConfig}from"./chunk-OIGVDK3F.js";import{existsSync,readFileSync}from"fs";import{dirname,join,resolve}from"path";function findWorkspace(cwd=process.cwd()){let directory=resolve(cwd);while(true){if(existsSync(join(directory,"gauge.json")))return directory;const parent=dirname(directory);if(parent===directory)return void 0;directory=parent}}function gaugeState(command,cwd=process.cwd()){return readGaugeState(command.optsWithGlobals(),cwd)}function backend(value,location){if(value===void 0)return void 0;if(value==="local"||value==="hosted")return value;throw new CliError("usage",`Invalid backend in ${location}: expected local or hosted`)}function readGaugeState(flags,cwd=process.cwd(),account={signedIn:resolveToken()!==null,...readConfig()}){const root=findWorkspace(cwd);let config;let workspaceBackend;if(root){try{const parsed=JSON.parse(readFileSync(join(root,"gauge.json"),"utf8"));config=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}catch{config=null}if(config&&"mode"in config)throw new CliError("usage","gauge.json does not accept mode. Set backend in private .gauge/config.json; keep the project manifest backend-independent.");const path=join(root,".gauge","config.json");if(existsSync(path)){let value;try{value=JSON.parse(readFileSync(path,"utf8"))}catch{throw new CliError("usage",`${path} is not valid JSON`)}if(!value||value.version!==1)throw new CliError("usage",`Unsupported workspace configuration version in ${path}`);workspaceBackend=backend(value.backend,path)}}const userBackend=backend(account.backend,"user configuration");const[mode,source]=flags.local?["local","flag"]:flags.hosted?["hosted","flag"]:workspaceBackend?[workspaceBackend,"workspace"]:userBackend?[userBackend,"user"]:["local","default"];return{mode,source,root,inRepo:root!==void 0,config,signedIn:account.signedIn,orgId:account.orgId}}function instructionMode(state){const why={flag:"from the flag",workspace:"from .gauge/config.json",user:"from user configuration",default:"the default"};return{mode:state.mode,why:why[state.source]}}function header(state,topic,brief=false){const{mode,why}=instructionMode(state);const lines=[`Mode: ${mode} (${why}). Pass --${mode==="local"?"hosted":"local"} to switch for this command.`];if(mode==="local"&&topic&&!topic.local&&!topic.shared)lines.push("This topic is hosted only. Local guidance: `gauge instructions --local`.");if(state.config===null)lines.push("gauge.json is not valid JSON. Fix it before using this workspace.");else if(!state.root&&!brief)lines.push("Run `gauge init` to initialize this directory. It writes gauge.json and private .gauge/ state. Add --cases only to scaffold shared gauge-cases/ files.");else if(!brief&&(!topic||topic.key==="root"))lines.push("Next: `gauge instructions eval` or `gauge instructions preference` to create a saved measurement; `gauge instructions run` to launch it.");return lines}function selectedOrg(command,fileOrg){const{org}=command.optsWithGlobals();if(org)return{value:org,source:"flag"};if(fileOrg)return{value:fileOrg,source:"file"};const project=gaugeState(command).config;if(typeof project?.orgId==="string"&&project.orgId){if(!isUuid(project.orgId))throw new CliError("usage","The organization saved in gauge.json is not valid.",{hint:"Run `gauge orgs`, then `gauge orgs use <slug> --project` to choose this project's organization."});return{value:project.orgId,source:"project"}}if(project?.org)legacySelection("project");const{orgId,defaultOrg}=readConfig();if(orgId){if(!isUuid(orgId))throw new CliError("usage","Your saved organization is not valid.",{hint:"Run `gauge orgs`, then `gauge orgs use <slug>` to choose your organization."});return{value:orgId,source:"config"}}if(defaultOrg)legacySelection("config");return void 0}var NO_ORG_MESSAGE="No organization selected. Pass --org <org> or set a default with `gauge orgs use <org>`.";async function resolveOrg(command,fileOrg){const selection=selectedOrg(command,fileOrg);if(!selection)throw new CliError("usage",NO_ORG_MESSAGE,{needsAccount:true});return(await resolveSelection(selection.value,selection.source)).id}function resolveOutput(command){const{output}=command.optsWithGlobals();return output==="json"?"json":"table"}function requireHosted(command,{account=false,hint}={}){const{mode,source}=gaugeState(command);if(mode==="local"&&(source==="flag"||!account))throw new CliError("usage","This command needs hosted Gauge.",{needsAccount:true,hint})}function hostedOnly(command,options={}){return command.hook("preAction",(_command,action)=>requireHosted(action,options))}var OUTPUT_FORMATS=["table","json"];function colorEnabled(stream){if(process.env.FORCE_COLOR)return process.env.FORCE_COLOR!=="0";return stream.isTTY===true&&!process.env.NO_COLOR&&process.env.TERM!=="dumb"}function style(code,stream=process.stdout){const on=colorEnabled(stream);return text=>on?`\x1B[${code}m${text}\x1B[0m`:text}function printJson(value){console.log(JSON.stringify(value,null,2))}function printItems(items,format,columns){if(format==="json"){printJson(items);return}if(items.length===0){console.log("(no results)");return}const cols=columns??Object.keys(items[0]).map(key=>({key}));const headers=cols.map(col=>col.header??col.key);const rows=items.map(item=>cols.map(col=>cell(item[col.key])));const widths=headers.map((header2,i)=>Math.max(header2.length,...rows.map(row=>row[i].length)));const line=values=>values.map((value,i)=>value.padEnd(widths[i])).join(" ").trimEnd();console.log(line(headers));for(const row of rows)console.log(line(row))}function cell(value){if(value===null||value===void 0||value==="")return"\u2014";if(value instanceof Date)return value.toISOString();if(typeof value==="object")return JSON.stringify(value);return String(value)}var CHAT_API_PREFIX="/api/v1";var CHAT_BATCH_SIZE=500;var INVALID_CODES=new Set(["invalid_request","invalid_query","invalid_id","invalid_cursor","range_too_large"]);function exitFamily(status,code){if(code==="limit_exceeded")return"insufficient_credits";if(status===400||status===422||INVALID_CODES.has(code))return"invalid_request";if(code==="rate_limited")return"rate_limited";return codeForStatus(status)}function isChatErrorBody(value){const error=value?.error;return typeof error==="object"&&error!==null&&typeof error.code==="string"&&typeof error.message==="string"}function loginHint(){return process.env.GAUGE_API_TOKEN?.trim()?"Replace GAUGE_API_TOKEN with a valid key, or unset it and run `gauge auth login`.":"Run `gauge auth login`, or set GAUGE_API_TOKEN to an org API key (Settings \u2192 API Keys)."}function hintFor(code,field,extra,retryAfter){switch(code){case"forbidden":return field==="explain"?"--explain (or `explain` in --json) is only available to Gauge staff; rerun without it.":void 0;case"unauthorized":return loginHint();case"insufficient_scope":return extra.requiredScope&&extra.requiredScope!=="write"?`Ask an organization admin for '${String(extra.requiredScope)}' permission.`:"Ask an organization admin for write access, or create a Read & write API key in Settings \u2192 API Keys.";case"limit_exceeded":return typeof extra.remaining==="number"?`Your plan allows ${extra.remaining} more prompt(s); nothing was created.`:"Nothing was created.";case"rate_limited":return retryAfter===void 0?"Retry shortly.":`Retry in ${retryAfter} s.`;case"product_not_enabled":return"Run `gauge orgs` to see which products each organization uses.";default:return void 0}}function describeScopes(scopes){if(scopes.includes("write"))return"read & write";if(scopes.length===1&&scopes[0]==="read")return"read-only";return scopes.length?scopes.join(", "):"no permissions"}var ChatApiClient=class extends ApiClient{describingScope=false;orgName;async me(){try{return await this.get(chatPath("me"))}catch(error){if(!(error instanceof CliError)||error.code!=="not_found")throw error;throw new CliError("not_found","This Gauge server cannot show your account details yet.",{hint:"Run `gauge orgs` to check your access. If you use a custom Gauge server, ask its administrator to update it."})}}async scopeHint(required){if(this.describingScope)return void 0;this.describingScope=true;try{const{token}=await this.me();const needs=String(required??"write");const access=token.scopes.length?`${describeScopes(token.scopes)} access`:"no permissions";if(token.kind==="api_key")return`This API key has ${access}.${needs==="write"?" Create a Read & write key in Settings \u2192 API Keys, then update GAUGE_API_TOKEN or import it with `gauge auth login --with-token`.":` Use a key with '${needs}' permission.`}`;if(token.kind==="session")return`Your login has ${access}. Ask an organization admin for ${needs==="write"?"write access":`'${needs}' permission`}.`;return void 0}catch{return void 0}finally{this.describingScope=false}}constructor(options={}){super({...options,baseUrl:options.baseUrl??storedSharedCredentials()?.authUrl??resolveAuthUrl()})}headers(extra){if(!this.signedIn)throw new CliError("unauthorized","Not logged in to Gauge.",{hint:loginHint()});return super.headers(extra)}async toError(res){let body;try{body=await res.clone().json()}catch{}if(!isChatErrorBody(body)){if(res.status===404)return unknownEndpoint(res);return super.toError(res)}const{code,message,field,...extra}=body.error;const retryAfter=typeof extra.retryAfter==="number"?extra.retryAfter:res.status===429?retryAfterSeconds(res):void 0;const details={status:res.status,...field?{field}:{},...extra,...retryAfter!==void 0?{retryAfter}:{}};if(code==="product_not_enabled"&&this.orgName)return new CliError(exitFamily(res.status,code),`${this.orgName} doesn't use Gauge Chat.`,{apiCode:code,details,hint:hintFor(code,field,extra,retryAfter)});return new CliError(exitFamily(res.status,code),`${code==="insufficient_scope"?"You don't have the permissions needed for this command.":message}${field?` (field: ${field})`:""}`,{apiCode:code,details,hint:(code==="insufficient_scope"?await this.scopeHint(extra.requiredScope):void 0)??hintFor(code,field,extra,retryAfter)})}};function unknownEndpoint(res){const url=res.url?new URL(res.url):void 0;return new CliError("not_found",`This Gauge server${url?` (${url.host})`:""} does not support this command at the requested address.`,{details:{status:404,...url?{path:url.pathname}:{}},hint:"Check GAUGE_AUTH_URL or `gauge config get authUrl` if you use a custom server. Otherwise, contact Gauge support."})}function createChatApiClient(options={}){return new ChatApiClient(options)}function chatPath(...segments){return`${CHAT_API_PREFIX}/${segments.map(encodeURIComponent).join("/")}`}async function resolveChatOrg(command){const{org}=command.optsWithGlobals();const isKey=credentialKind()==="api_key";const selection=isKey?org?{value:org,source:"flag"}:void 0:selectedOrg(command);if(selection){const resolved=await resolveSelection(selection.value,selection.source);return{id:resolved.id,name:resolved.name,source:selection.source}}if(isKey){const keyOrg=await keyOrganization();return{id:keyOrg.id,name:keyOrg.name,source:"key"}}const chatOrgs=(await fetchDirectory()).filter(o=>o.products?.chat!==false);if(chatOrgs.length===1)return{id:chatOrgs[0].id,name:chatOrgs[0].name,source:"only"};throw new CliError("usage",chatOrgs.length===0?"You are not a member of any organization with Gauge Chat.":`Several organizations have Gauge Chat (${chatOrgs.map(o=>o.slug).join(", ")}). Pass --org <org> or run \`gauge orgs use <org>\`.`)}async function resolveChatCategory(command,client,org){const{category}=command.optsWithGlobals();if(category)return category;const{chatCategory,chatCategoryOrg}=readConfig();if(chatCategory&&(chatCategoryOrg?chatCategoryOrg===org.id:org.source==="config"))return chatCategory;const{data}=await client.get(chatPath("orgs",org.id,"categories"));if(data.length===1)return data[0].slug;const label=org.name??org.id;throw new CliError("usage",data.length===0?`Organization ${label} has no categories.`:`Organization ${label} has several categories (${data.map(c=>c.slug).join(", ")}). Pass --category <slug> or run \`gauge chat categories use <slug>\`.`)}async function chatScope(command){const client=createChatApiClient();const chatOrg=await resolveChatOrg(command);client.orgName=chatOrg.name??chatOrg.id;return{client,org:chatOrg.id,chatOrg}}async function categoryScope(command){const scope=await chatScope(command);const category=await resolveChatCategory(command,scope.client,scope.chatOrg);return{...scope,category,base:["orgs",scope.org,"categories",category]}}var DEFAULT_MAX_ITEMS=5e3;function parsePositive(raw,flag,max){if(raw===void 0)return void 0;const value=Number(raw);if(!Number.isInteger(value)||value<1||max&&value>max)throw new CliError("usage",`${flag} must be an integer${max?` between 1 and ${max}`:" of at least 1"}`);return value}async function fetchPages(client,path,query,options,maxLimit=200){const limit=parsePositive(options.limit,"--limit",maxLimit);if(!options.all)return client.get(path,{...query,limit,cursor:options.cursor});const max=parsePositive(options.max,"--max")??DEFAULT_MAX_ITEMS;const data=[];let cursor=options.cursor;do{const page=await client.get(path,{...query,limit:Math.min(limit??maxLimit,max-data.length),cursor});data.push(...page.data);cursor=page.nextCursor??void 0}while(cursor&&data.length<max);return{data,nextCursor:cursor??null}}async function fetchAll(client,path,query={}){return(await fetchPages(client,path,query,{all:true})).data}function printPage(page,output,row){if(output==="json"){printJson({data:page.data,nextCursor:page.nextCursor??null});return}printItems(page.data.map(row),"table");if(page.nextCursor)console.error(`(more results \u2014 rerun with --cursor ${page.nextCursor}, or pass --all)`)}function addPageOptions(command,maxLimit=200){return command.option("--limit <n>",`page size (1-${maxLimit})`).option("--cursor <cursor>","resume from a previous page's nextCursor").option("--all","follow nextCursor through every page").option("--max <n>",`with --all, stop after this many items (default ${DEFAULT_MAX_ITEMS})`)}function chunks(items,size=CHAT_BATCH_SIZE){const out=[];for(let i=0;i<items.length;i+=size)out.push(items.slice(i,i+size));return out}var csv=raw=>raw.split(",").map(s=>s.trim()).filter(Boolean);function truncate(text,length=80){const flat=text.replace(/\s+/g," ").trim();return flat.length>length?`${flat.slice(0,length-1)}\u2026`:flat}var lower=s=>s.trim().toLowerCase();async function resolveTopicId(scope,value){if(value.startsWith("top_"))return value;const topics=await fetchAll(scope.client,chatPath(...scope.base,"topics"));const match=topics.filter(t=>t.slug===value||lower(t.title)===lower(value));if(match.length===1)return match[0].id;throw new CliError("not_found",match.length?`Topic "${value}" is ambiguous; pass its id (${match.map(t=>t.id).join(", ")}).`:`Topic "${value}" not found in category ${scope.category}.`,{hint:"Run `gauge chat topics list`, or create it with `gauge chat topics create`."})}async function resolveTagIds(scope,values){if(values.every(v=>v.startsWith("tag_")))return values;const tags=await fetchAll(scope.client,chatPath("orgs",scope.org,"tags"));return values.map(value=>{if(value.startsWith("tag_"))return value;const match=tags.filter(t=>lower(t.name)===lower(value));if(match.length===1)return match[0].id;throw new CliError("not_found",match.length?`Tag "${value}" is ambiguous; pass its id (${match.map(t=>t.id).join(", ")}).`:`Tag "${value}" not found.`,{hint:"Run `gauge chat tags list`, or create it with `gauge chat tags create`."})})}function withCategory(command){return command.option("--category <category>","category slug or cat_ id (default: chatCategory config, else the org's only category)")}export{findWorkspace,gaugeState,readGaugeState,instructionMode,header,resolveOrg,resolveOutput,requireHosted,hostedOnly,OUTPUT_FORMATS,style,printJson,printItems,CHAT_API_PREFIX,CHAT_BATCH_SIZE,describeScopes,ChatApiClient,createChatApiClient,chatPath,resolveChatOrg,resolveChatCategory,chatScope,categoryScope,DEFAULT_MAX_ITEMS,parsePositive,fetchPages,fetchAll,printPage,addPageOptions,chunks,csv,truncate,resolveTopicId,resolveTagIds,withCategory};
|
|
1
|
+
import{credentialKind,fetchDirectory,isUuid,keyOrganization,legacySelection,resolveSelection}from"./chunk-3I3IT3LG.js";import{ApiClient,CliError,codeForStatus,resolveAuthUrl,resolveToken,retryAfterSeconds,storedSharedCredentials}from"./chunk-MAANSWGU.js";import{readConfig}from"./chunk-OIGVDK3F.js";import{existsSync,readFileSync}from"fs";import{dirname,join,resolve}from"path";function findWorkspace(cwd=process.cwd()){let directory=resolve(cwd);while(true){if(existsSync(join(directory,"gauge.json")))return directory;const parent=dirname(directory);if(parent===directory)return void 0;directory=parent}}function gaugeState(command,cwd=process.cwd()){return readGaugeState(command.optsWithGlobals(),cwd)}function backend(value,location){if(value===void 0)return void 0;if(value==="local"||value==="hosted")return value;throw new CliError("usage",`Invalid backend in ${location}: expected local or hosted`)}function readGaugeState(flags,cwd=process.cwd(),account={signedIn:resolveToken()!==null,...readConfig()}){const root=findWorkspace(cwd);let config;let workspaceBackend;if(root){try{const parsed=JSON.parse(readFileSync(join(root,"gauge.json"),"utf8"));config=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}catch{config=null}if(config&&"mode"in config)throw new CliError("usage","gauge.json does not accept mode. Set backend in private .gauge/config.json; keep the project manifest backend-independent.");const path=join(root,".gauge","config.json");if(existsSync(path)){let value;try{value=JSON.parse(readFileSync(path,"utf8"))}catch{throw new CliError("usage",`${path} is not valid JSON`)}if(!value||value.version!==1)throw new CliError("usage",`Unsupported workspace configuration version in ${path}`);workspaceBackend=backend(value.backend,path)}}const userBackend=backend(account.backend,"user configuration");const[mode,source]=flags.local?["local","flag"]:flags.hosted?["hosted","flag"]:workspaceBackend?[workspaceBackend,"workspace"]:userBackend?[userBackend,"user"]:["local","default"];return{mode,source,root,inRepo:root!==void 0,config,signedIn:account.signedIn,orgId:account.orgId}}function instructionMode(state){const why={flag:"from the flag",workspace:"from .gauge/config.json",user:"from user configuration",default:"the default"};return{mode:state.mode,why:why[state.source]}}function header(state,topic,brief=false){const{mode,why}=instructionMode(state);const lines=[`Mode: ${mode} (${why}). Pass --${mode==="local"?"hosted":"local"} to switch for this command.`];if(mode==="local"&&topic&&!topic.local&&!topic.shared)lines.push("This topic is hosted only. Local guidance: `gauge instructions --local`.");if(state.config===null)lines.push("gauge.json is not valid JSON. Fix it before using this workspace.");else if(!state.root&&!brief)lines.push("Run `gauge init` to initialize this directory. It writes gauge.json and private .gauge/ state. Add --cases only to scaffold shared gauge-cases/ files.");else if(!brief&&(!topic||topic.key==="root"))lines.push("Next: `gauge instructions eval` or `gauge instructions preference` to create a saved measurement; `gauge instructions run` to launch it.");return lines}function selectedOrg(command,fileOrg){const{org}=command.optsWithGlobals();if(org)return{value:org,source:"flag"};if(fileOrg)return{value:fileOrg,source:"file"};const project=gaugeState(command).config;if(typeof project?.orgId==="string"&&project.orgId){if(!isUuid(project.orgId))throw new CliError("usage","The organization saved in gauge.json is not valid.",{hint:"Run `gauge orgs`, then `gauge orgs use <slug> --project` to choose this project's organization."});return{value:project.orgId,source:"project"}}if(project?.org)legacySelection("project");const{orgId,defaultOrg}=readConfig();if(orgId){if(!isUuid(orgId))throw new CliError("usage","Your saved organization is not valid.",{hint:"Run `gauge orgs`, then `gauge orgs use <slug>` to choose your organization."});return{value:orgId,source:"config"}}if(defaultOrg)legacySelection("config");return void 0}var NO_ORG_MESSAGE="No organization selected. Pass --org <org> or set a default with `gauge orgs use <org>`.";async function resolveOrg(command,fileOrg){const selection=selectedOrg(command,fileOrg);if(!selection)throw new CliError("usage",NO_ORG_MESSAGE,{needsAccount:true});return(await resolveSelection(selection.value,selection.source)).id}function resolveOutput(command){const{output}=command.optsWithGlobals();return output==="json"?"json":"table"}function requireHosted(command,{account=false,hint}={}){const{mode,source}=gaugeState(command);if(mode==="local"&&(source==="flag"||!account))throw new CliError("usage","This command needs hosted Gauge.",{needsAccount:true,hint})}function hostedOnly(command,options={}){return command.hook("preAction",(_command,action)=>requireHosted(action,options))}var OUTPUT_FORMATS=["table","json"];function colorEnabled(stream){if(process.env.FORCE_COLOR)return process.env.FORCE_COLOR!=="0";return stream.isTTY===true&&!process.env.NO_COLOR&&process.env.TERM!=="dumb"}function style(code,stream=process.stdout){const on=colorEnabled(stream);return text=>on?`\x1B[${code}m${text}\x1B[0m`:text}function printJson(value){console.log(JSON.stringify(value,null,2))}function printItems(items,format,columns){if(format==="json"){printJson(items);return}if(items.length===0){console.log("(no results)");return}const cols=columns??Object.keys(items[0]).map(key=>({key}));const headers=cols.map(col=>col.header??col.key);const rows=items.map(item=>cols.map(col=>cell(item[col.key])));const widths=headers.map((header2,i)=>Math.max(header2.length,...rows.map(row=>row[i].length)));const line=values=>values.map((value,i)=>value.padEnd(widths[i])).join(" ").trimEnd();console.log(line(headers));for(const row of rows)console.log(line(row))}function cell(value){if(value===null||value===void 0||value==="")return"\u2014";if(value instanceof Date)return value.toISOString();if(typeof value==="object")return JSON.stringify(value);return String(value)}var CHAT_API_PREFIX="/api/v1";var CHAT_BATCH_SIZE=500;var INVALID_CODES=new Set(["invalid_request","invalid_query","invalid_id","invalid_cursor","range_too_large"]);function exitFamily(status,code){if(code==="limit_exceeded")return"insufficient_credits";if(status===400||status===422||INVALID_CODES.has(code))return"invalid_request";if(code==="rate_limited")return"rate_limited";return codeForStatus(status)}function isChatErrorBody(value){const error=value?.error;return typeof error==="object"&&error!==null&&typeof error.code==="string"&&typeof error.message==="string"}function loginHint(){return process.env.GAUGE_API_TOKEN?.trim()?"Replace GAUGE_API_TOKEN with a valid key, or unset it and run `gauge auth login`.":"Run `gauge auth login`, or set GAUGE_API_TOKEN to an org API key (Settings \u2192 API Keys)."}function hintFor(code,field,extra,retryAfter){switch(code){case"forbidden":return field==="explain"?"--explain (or `explain` in --json) is only available to Gauge staff; rerun without it.":void 0;case"unauthorized":return loginHint();case"insufficient_scope":return extra.requiredScope&&extra.requiredScope!=="write"?`Ask an organization admin for '${String(extra.requiredScope)}' permission.`:"Ask an organization admin for write access, or create a Read & write API key in Settings \u2192 API Keys.";case"limit_exceeded":return typeof extra.remaining==="number"?`Your plan allows ${extra.remaining} more prompt(s); nothing was created.`:"Nothing was created.";case"rate_limited":return retryAfter===void 0?"Retry shortly.":`Retry in ${retryAfter} s.`;case"product_not_enabled":return"Run `gauge orgs` to see which products each organization uses.";default:return void 0}}function describeScopes(scopes){if(scopes.includes("write"))return"read & write";if(scopes.length===1&&scopes[0]==="read")return"read-only";return scopes.length?scopes.join(", "):"no permissions"}var ChatApiClient=class extends ApiClient{describingScope=false;orgName;async me(){try{return await this.get(chatPath("me"))}catch(error){if(!(error instanceof CliError)||error.code!=="not_found")throw error;throw new CliError("not_found","This Gauge server cannot show your account details yet.",{hint:"Run `gauge orgs` to check your access. If you use a custom Gauge server, ask its administrator to update it."})}}async scopeHint(required){if(this.describingScope)return void 0;this.describingScope=true;try{const{token}=await this.me();const needs=String(required??"write");const access=token.scopes.length?`${describeScopes(token.scopes)} access`:"no permissions";if(token.kind==="api_key")return`This API key has ${access}.${needs==="write"?" Create a Read & write key in Settings \u2192 API Keys, then update GAUGE_API_TOKEN or import it with `gauge auth login --with-token`.":` Use a key with '${needs}' permission.`}`;if(token.kind==="session")return`Your login has ${access}. Ask an organization admin for ${needs==="write"?"write access":`'${needs}' permission`}.`;return void 0}catch{return void 0}finally{this.describingScope=false}}constructor(options={}){super({...options,baseUrl:options.baseUrl??storedSharedCredentials()?.authUrl??resolveAuthUrl()})}headers(extra){if(!this.signedIn)throw new CliError("unauthorized","Not logged in to Gauge.",{hint:loginHint()});return super.headers(extra)}async toError(res){let body;try{body=await res.clone().json()}catch{}if(!isChatErrorBody(body)){if(res.status===404)return unknownEndpoint(res);return super.toError(res)}const{code,message,field,...extra}=body.error;const retryAfter=typeof extra.retryAfter==="number"?extra.retryAfter:res.status===429?retryAfterSeconds(res):void 0;const details={status:res.status,...field?{field}:{},...extra,...retryAfter!==void 0?{retryAfter}:{}};if(code==="product_not_enabled"&&this.orgName)return new CliError(exitFamily(res.status,code),`${this.orgName} doesn't use Gauge Chat.`,{apiCode:code,details,hint:hintFor(code,field,extra,retryAfter)});return new CliError(exitFamily(res.status,code),`${code==="insufficient_scope"?"You don't have the permissions needed for this command.":message}${field?` (field: ${field})`:""}`,{apiCode:code,details,hint:(code==="insufficient_scope"?await this.scopeHint(extra.requiredScope):void 0)??hintFor(code,field,extra,retryAfter)})}};function unknownEndpoint(res){const url=res.url?new URL(res.url):void 0;return new CliError("not_found",`This Gauge server${url?` (${url.host})`:""} does not support this command at the requested address.`,{details:{status:404,...url?{path:url.pathname}:{}},hint:"Check GAUGE_AUTH_URL or `gauge config get authUrl` if you use a custom server. Otherwise, contact Gauge support."})}function createChatApiClient(options={}){return new ChatApiClient(options)}function chatPath(...segments){return`${CHAT_API_PREFIX}/${segments.map(encodeURIComponent).join("/")}`}async function resolveChatOrg(command){const{org}=command.optsWithGlobals();const isKey=credentialKind()==="api_key";const selection=isKey?org?{value:org,source:"flag"}:void 0:selectedOrg(command);if(selection){const resolved=await resolveSelection(selection.value,selection.source);return{id:resolved.id,name:resolved.name,source:selection.source}}if(isKey){const keyOrg=await keyOrganization();return{id:keyOrg.id,name:keyOrg.name,source:"key"}}const chatOrgs=(await fetchDirectory()).filter(o=>o.products?.chat!==false);if(chatOrgs.length===1)return{id:chatOrgs[0].id,name:chatOrgs[0].name,source:"only"};throw new CliError("usage",chatOrgs.length===0?"You are not a member of any organization with Gauge Chat.":`Several organizations have Gauge Chat (${chatOrgs.map(o=>o.slug).join(", ")}). Pass --org <org> or run \`gauge orgs use <org>\`.`)}async function resolveChatCategory(command,client,org){const{category}=command.optsWithGlobals();if(category)return category;const{chatCategory,chatCategoryOrg}=readConfig();if(chatCategory&&(chatCategoryOrg?chatCategoryOrg===org.id:org.source==="config"))return chatCategory;const{data}=await client.get(chatPath("orgs",org.id,"categories"));if(data.length===1)return data[0].slug;const label=org.name??org.id;throw new CliError("usage",data.length===0?`Organization ${label} has no categories.`:`Organization ${label} has several categories (${data.map(c=>c.slug).join(", ")}). Pass --category <slug> or run \`gauge chat categories use <slug>\`.`)}async function chatScope(command){const client=createChatApiClient();const chatOrg=await resolveChatOrg(command);client.orgName=chatOrg.name??chatOrg.id;return{client,org:chatOrg.id,chatOrg}}async function categoryScope(command){const scope=await chatScope(command);const category=await resolveChatCategory(command,scope.client,scope.chatOrg);return{...scope,category,base:["orgs",scope.org,"categories",category]}}var DEFAULT_MAX_ITEMS=5e3;function parsePositive(raw,flag,max){if(raw===void 0)return void 0;const value=Number(raw);if(!Number.isInteger(value)||value<1||max&&value>max)throw new CliError("usage",`${flag} must be an integer${max?` between 1 and ${max}`:" of at least 1"}`);return value}async function fetchPages(client,path,query,options,maxLimit=200){const limit=parsePositive(options.limit,"--limit",maxLimit);if(!options.all)return client.get(path,{...query,limit,cursor:options.cursor});const max=parsePositive(options.max,"--max")??DEFAULT_MAX_ITEMS;const data=[];let cursor=options.cursor;do{const page=await client.get(path,{...query,limit:Math.min(limit??maxLimit,max-data.length),cursor});data.push(...page.data);cursor=page.nextCursor??void 0}while(cursor&&data.length<max);return{data,nextCursor:cursor??null}}async function fetchAll(client,path,query={}){return(await fetchPages(client,path,query,{all:true})).data}function printPage(page,output,row){if(output==="json"){printJson({data:page.data,nextCursor:page.nextCursor??null});return}printItems(page.data.map(row),"table");if(page.nextCursor)console.error(`(more results \u2014 rerun with --cursor ${page.nextCursor}, or pass --all)`)}function addPageOptions(command,maxLimit=200){return command.option("--limit <n>",`page size (1-${maxLimit})`).option("--cursor <cursor>","resume from a previous page's nextCursor").option("--all","follow nextCursor through every page").option("--max <n>",`with --all, stop after this many items (default ${DEFAULT_MAX_ITEMS})`)}function chunks(items,size=CHAT_BATCH_SIZE){const out=[];for(let i=0;i<items.length;i+=size)out.push(items.slice(i,i+size));return out}var csv=raw=>raw.split(",").map(s=>s.trim()).filter(Boolean);function truncate(text,length=80){const flat=text.replace(/\s+/g," ").trim();return flat.length>length?`${flat.slice(0,length-1)}\u2026`:flat}var lower=s=>s.trim().toLowerCase();async function resolveTopicId(scope,value){if(value.startsWith("top_"))return value;const topics=await fetchAll(scope.client,chatPath(...scope.base,"topics"));const match=topics.filter(t=>t.slug===value||lower(t.title)===lower(value));if(match.length===1)return match[0].id;throw new CliError("not_found",match.length?`Topic "${value}" is ambiguous; pass its id (${match.map(t=>t.id).join(", ")}).`:`Topic "${value}" not found in category ${scope.category}.`,{hint:"Run `gauge chat topics list`, or create it with `gauge chat topics create`."})}async function resolveTagIds(scope,values){if(values.every(v=>v.startsWith("tag_")))return values;const tags=await fetchAll(scope.client,chatPath("orgs",scope.org,"tags"));return values.map(value=>{if(value.startsWith("tag_"))return value;const match=tags.filter(t=>lower(t.name)===lower(value));if(match.length===1)return match[0].id;throw new CliError("not_found",match.length?`Tag "${value}" is ambiguous; pass its id (${match.map(t=>t.id).join(", ")}).`:`Tag "${value}" not found.`,{hint:"Run `gauge chat tags list`, or create it with `gauge chat tags create`."})})}function withCategory(command){return command.option("--category <category>","category slug or cat_ id (default: chatCategory config, else the org's only category)")}export{findWorkspace,gaugeState,readGaugeState,instructionMode,header,resolveOrg,resolveOutput,requireHosted,hostedOnly,OUTPUT_FORMATS,style,printJson,printItems,CHAT_API_PREFIX,CHAT_BATCH_SIZE,describeScopes,ChatApiClient,createChatApiClient,chatPath,resolveChatOrg,resolveChatCategory,chatScope,categoryScope,DEFAULT_MAX_ITEMS,parsePositive,fetchPages,fetchAll,printPage,addPageOptions,chunks,csv,truncate,resolveTopicId,resolveTagIds,withCategory};
|