@withgauge/cli 0.25.1 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -206,7 +206,7 @@ describe the transport and person-profile behavior.
206
206
  For an end-to-end improvement loop, run `gauge instructions hillclimb`. It guides
207
207
  your coding agent to identify product inputs, propose a representative pilot,
208
208
  inspect and publish findings, implement a focused change, and rerun to compare.
209
- Init and the generated `AGENTS.md` point to this guidance. `gauge install-skill`
209
+ Init and the `AGENTS.md` block from `init --cases` point to this guidance. `gauge install-skill`
210
210
  installs the Gauge skill, which directs agents to the installed CLI's instructions.
211
211
 
212
212
  Execution backend is independent of definition source. Resolve an explicit
@@ -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 (managed docs rewriting) | no | yes |
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
 
@@ -264,6 +264,7 @@ target; `--copy` copies files instead of creating symlinks.
264
264
  ## Usage
265
265
 
266
266
  ```sh
267
+ gauge run "Which CLI should I deploy with?" # one open-ended preference run, nothing saved
267
268
  gauge status # the org at a glance
268
269
  gauge eval list # saved eval sets
269
270
  gauge preference list # saved Agent Preference prompts
@@ -288,12 +289,13 @@ migration example. Use `gauge instructions eval` and `gauge instructions prefere
288
289
  preference prompts, and `gauge instructions session-analysis` to investigate
289
290
  product choices, source exposure, and interventions, from individual traces to
290
291
  larger cohorts.
291
- Use `gauge instructions optimization` for the full optimization workflow.
292
+ Use `gauge instructions issues` to choose what to improve and
293
+ `gauge instructions optimization` for the full optimization workflow.
292
294
  `gauge instructions --list` shows available topics.
293
295
 
294
296
  Run `gauge --help` (or `gauge <command> --help`) for the full command set:
295
297
  run, eval, preference, models, personas, skills, mcp, repos, optimizations,
296
- brands, tags, actions, dashboards, members, org, provider keys,
298
+ brands, tags, issues, dashboards, members, org, provider keys,
297
299
  billing, usage, stats, query, and more.
298
300
 
299
301
  ## Run committed Markdown evals
@@ -391,7 +393,7 @@ alongside your product:
391
393
  ```json
392
394
  {
393
395
  "version": 2,
394
- "org": "my-org",
396
+ "orgId": "00000000-0000-0000-0000-000000000000",
395
397
  "inputs": {
396
398
  "cli": {
397
399
  "type": "npm-package",
@@ -413,8 +415,9 @@ existing checkout settings, including GitHub's default merge checkout. Omit
413
415
  `source.artifact` when the workflow uploads one artifact, or select it by name.
414
416
 
415
417
  For automatic checks, connect the Gauge GitHub App with repository access and
416
- Actions read permission. Set `org` and enable the repository and target branches
417
- in **Settings → GitHub**. Waiting for inputs starts no sessions and spends no
418
+ Actions read permission. Run `gauge orgs use <slug> --project` to record the
419
+ organization as `orgId`, and enable the repository and target branches in
420
+ **Settings → GitHub**. Waiting for inputs starts no sessions and spends no
418
421
  session credits.
419
422
  Fork pull requests are disabled by default. Check **Allow fork pull requests** to let
420
423
  workspace members authorize an evaluation from its GitHub check. Authorization
@@ -636,8 +639,8 @@ do not test discovery of the canonical docs. Static verification validates
636
639
  configuration; it does not prove backend support, delivery, or an eval pass.
637
640
 
638
641
  Editor schemas are published at
639
- `https://agents.withgauge.com/schemas/gauge/v2.8.0/gauge.json` and
640
- `https://agents.withgauge.com/schemas/gauge/v2.8.0/case.json`. Associate them in editor
642
+ `https://agents.withgauge.com/schemas/gauge/v2.10.0/gauge.json` and
643
+ `https://agents.withgauge.com/schemas/gauge/v2.10.0/case.json`. Associate them in editor
641
644
  settings; `gauge.json` does not accept a `$schema` field. These release URLs are
642
645
  immutable. Cases default to `gauge-cases/`, or use explicit `cases` paths.
643
646
 
@@ -700,6 +703,89 @@ A prompt with zero scenarios is a valid definition — it simply never comes due
700
703
  Sessions per launch = scenarios × agent/model targets × samples. Omit the
701
704
  run-settings flags on `create` and the org's default roster applies.
702
705
 
706
+ ## Hosted setup and teardown scripts
707
+
708
+ Run `gauge instructions lifecycle` for the complete script API reference and
709
+ the author → preview → launch workflow. This guidance ships with the CLI.
710
+
711
+ Upload JavaScript or TypeScript source on an eval or preference prompt:
712
+
713
+ ```sh
714
+ gauge eval edit <evalId> --hosted --setup-file ./setup.ts --teardown-file ./teardown.ts
715
+ gauge preference edit <promptId> --hosted --setup-file ./setup.ts \
716
+ --setup-timeout 180 --lifecycle-params '{"feature":"checkout"}'
717
+ ```
718
+
719
+ The same file flags work on `create`. The CLI reads UTF-8 files locally and
720
+ uploads their contents; paths are not stored or resolved on the server. Files
721
+ must be nonempty and at most 128 KiB. Each file is one script module; companion
722
+ files are not uploaded. Hooks run in hosted sessions, and are not supported by
723
+ `--local` or Git-authored case definitions.
724
+
725
+ Scripts can use top-level await and the provided session bindings:
726
+
727
+ ```ts
728
+ import { params, state } from "@withgauge/session";
729
+
730
+ console.log("Preparing", params.feature);
731
+ await state.set("prepared", true);
732
+ ```
733
+
734
+ Setup runs before the coding agent. Teardown runs during cleanup, independently
735
+ of the agent's result. Scripts use the session's configured MCP servers and
736
+ Connections. Script authoring itself does not launch a paid session.
737
+
738
+ Each phase defaults to 120 seconds for a new script. Set `--setup-timeout` or
739
+ `--teardown-timeout` to an integer from 1 to 600; these flags can also update an
740
+ existing script's timeout without re-uploading it. Replacing a script preserves
741
+ its timeout unless overridden. `--lifecycle-params` replaces the JSON parameter
742
+ object (maximum 64 KiB); pass `'{}'` to empty it.
743
+
744
+ Hook edits fetch the saved lifecycle configuration and send its updated value,
745
+ preserving the other phase, parameters, and timeouts when omitted. Ordinary
746
+ edits leave lifecycle configuration untouched. To remove scripts:
747
+
748
+ ```sh
749
+ gauge eval edit <evalId> --hosted --clear-setup # keep teardown and params
750
+ gauge preference edit <promptId> --hosted --clear-teardown
751
+ gauge eval edit <evalId> --hosted --clear-lifecycle # remove both and params
752
+ ```
753
+
754
+ Clearing the last script also removes its parameter object. Each new run freezes
755
+ the uploaded configuration; editing it does not change existing sessions.
756
+
757
+ For a one-off prompt, attach scripts directly without creating a saved eval or
758
+ preference prompt:
759
+
760
+ ```sh
761
+ gauge run --hosted "Build a dashboard" --setup-file ./setup.ts --teardown-file ./teardown.ts \
762
+ --setup-timeout 180 --lifecycle-params '{"feature":"temporary-test"}'
763
+ gauge run --hosted "Build a dashboard" --setup-file ./setup.ts --dry-run
764
+ ```
765
+
766
+ `--dry-run` validates the prompt and hook configuration and shows the configured
767
+ phases and deadlines without displaying source or parameters. It does not execute
768
+ scripts or launch sessions. Only the supplied scripts and parameters apply;
769
+ there is no saved configuration to inherit or update.
770
+
771
+ To override hooks for one launch of a saved measurement, pass the same upload,
772
+ timeout, parameter, or clear flags to `run --eval` or `run --preference`:
773
+
774
+ ```sh
775
+ gauge run --hosted --eval <evalId> --setup-file ./setup.ts --teardown-file ./teardown.ts
776
+ gauge run --hosted --preference <promptId> --scenario <scenarioId> \
777
+ --setup-file ./setup.ts --lifecycle-params '{"feature":"temporary-test"}'
778
+ gauge run --hosted --eval <evalId> --clear-lifecycle
779
+ ```
780
+
781
+ These overrides affect only the requested launch; the saved eval or preference
782
+ prompt is never edited. Unspecified phases, timeouts, and parameters inherit
783
+ the saved values. `--clear-lifecycle` disables both hooks for this launch only.
784
+ Without lifecycle flags, saved measurements use their saved hooks. One-off hook
785
+ flags require hosted execution; they are not supported with `--local`, `--apply`,
786
+ or case files. Saved measurement launches do not support `--dry-run`.
787
+ Launching runs consumes credits normally.
788
+
703
789
  ## Hosted schedules
704
790
 
705
791
  `--cadence none` is "manual": the measurement stops coming due and runs only
@@ -715,69 +801,84 @@ omit it and every scenario runs. On a recurring cadence, an eval launch or a
715
801
  full preference launch moves the next scheduled run to one period from now. A
716
802
  scenario subset leaves the schedule unchanged.
717
803
 
804
+ ## Issues (hosted)
805
+
806
+ An issue groups the same finding across many sessions. `gauge issues list` shows
807
+ open issues with the most sessions first, with their type, product, and status.
808
+ Friction shows how badly it hurt agents (blocked, recovered, extra work).
809
+ Objections come from preference sessions and show where agents went instead.
810
+ Filter with `--type friction|objection` and `--status open|fixed|muted|all`.
811
+ `gauge issues get <id>` lists the issue's findings with their runs.
812
+ `gauge run insight <run>` shows each finding's issue.
813
+
814
+ Each issue is open, fixed, or muted. A fixed issue reopens when a later run
815
+ shows it again; a muted one never does.
816
+
817
+ ```sh
818
+ gauge issues fix is_1 # done; reopens if agents hit it again
819
+ gauge issues mute is_1 # not relevant; never reopens
820
+ gauge issues reopen is_1 # back to open (also unmutes)
821
+ gauge issues recheck is_1 # preview the past runs it would repeat
822
+ gauge issues recheck is_1 --confirm # rerun them (spends credits); --run <runId>... picks others
823
+ ```
824
+
825
+ `recheck` (alias `verify`) never prompts: without `--confirm` it only prints
826
+ the preview. `gauge issues get` then shows which reruns still show the issue;
827
+ a recheck never closes it, so mark it fixed with `gauge issues fix`.
828
+
718
829
  ## Optimizations (hosted)
719
830
 
720
- Start by finding runs that encountered the surface you want to improve:
831
+ Optimizations can help hill climb your agent surfaces to improve Agent
832
+ Preference and Agent Experience. You edit a tree of pages, skills,
833
+ and CLI rules; Gauge reruns the source sessions with the tree injected
834
+ and compares their findings. Nothing deploys.
721
835
 
722
836
  ```sh
723
837
  gauge instructions optimization
724
- gauge optimizations baselines --eval ev_1 -o json
725
- gauge run insight run_1 -o json
726
- gauge run get run_1 --logs -o json
727
- gauge optimizations start --eval ev_1 --from-run run_1 --yes
728
- gauge optimizations watch cl_1
729
- ```
730
-
731
- `baselines` returns observed owned surfaces grouped by run, source evidence,
732
- judging status, eligibility (including the baseline's complete run set), and a
733
- `nextCursor` for `--cursor`. It uses the UI baseline picker's compatibility rules
734
- and recent 100-batch eligibility window. Missing evidence is unknown; the list
735
- is an analysis summary, not an exhaustive inventory of every trace event.
736
- `--from-run` inherits the eligible baseline's harness/model and reuses its runs.
737
- A stale choice fails instead of silently buying a new baseline. `--target` is
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.
838
+ gauge issues list -o json # by impact; --type friction|objection
839
+ gauge issues get is_1 # the issue's findings and runs
840
+ gauge optimizations create --issue is_1 # or --finding <id> --run <run>, or --goal <text>
841
+ gauge optimizations sessions add op_1 run_1 run_2 # a goal starts with none; up to 12
842
+ gauge optimizations authoring op_1
843
+ gauge run trace run_1 --seq 42 # read the cited evidence
844
+ gauge run web run_1 # the exact URLs the session fetched
845
+ ```
846
+
847
+ Tree keys are `page:<url>`, `skill:<name>`, and `cli:<package>`. Copy an
848
+ original in with `file add` so the diff shows only your edit. Change part of a
849
+ page with `file edit`: `edits.json` is `[{find, replace}]` on the exact source,
850
+ which `file read --query` shows. Each find must appear once, all edits apply or
851
+ none do, and the output shows how much of the page you kept. Use `file write`
852
+ for a new page, a full rewrite, a skill file, or CLI rules. Files not in the
853
+ tree rerun as the source session had them.
740
854
 
741
855
  ```sh
742
- gauge optimizations authoring cl_1 > context.json
743
- gauge optimizations page cl_1 --url https://docs.acme.dev/auth -o json
744
- # Author round.json using context.revision and the observed baseline evidence.
745
- gauge optimizations round preview cl_1 --file round.json -o json
746
- gauge optimizations round save cl_1 --file round.json --digest <previewDigest>
747
- gauge optimizations launch cl_1 --yes
748
- gauge optimizations watch cl_1
749
- gauge optimizations trial cl_1 R1.1 -o json
750
- gauge optimizations adopt cl_1 R1.1 --yes
751
- gauge optimizations handoff cl_1
752
- gauge optimizations complete cl_1 --yes
753
- ```
754
-
755
- A round is `{revision, trials: [{trial: {title, hypothesis, lever, intervention}}]}`.
756
- Docs `REWRITE_DOCS` proposals supply `after.pages` with URL and exact `edits`
757
- (`find`/`replace`), or a complete `body` and `rewriteReason`. Check the page's
758
- `source`: `scrape` means current fetched content, not the captured response.
759
-
760
- For CLI trials, inspect `cliIntervention.guidance` and `targets` in authoring
761
- and use `gauge run get <id> --logs` for the cited command evidence. `cli-change --file change.json`
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.
856
+ gauge optimizations file add op_1 --page https://docs.acme.dev/auth
857
+ gauge optimizations file read op_1 page:https://docs.acme.dev/auth --text
858
+ gauge optimizations file read op_1 page:https://docs.acme.dev/auth --query "API key"
859
+ gauge optimizations file edit op_1 --page https://docs.acme.dev/auth --edits edits.json
860
+ gauge optimizations file write op_1 --skill acme --path SKILL.md --from SKILL.md
861
+ gauge optimizations notes op_1 --from notes.md
862
+ gauge optimizations launch op_1 --yes
863
+ gauge optimizations watch op_1
864
+ gauge optimizations launch op_1 --restore-before run_9:140 --yes
865
+ gauge optimizations checkpoints op_1
866
+ gauge optimizations finish op_1 --from result.json --yes
867
+ ```
868
+
869
+ `launch` restores each rerun from the deepest checkpoint of an earlier rerun
870
+ taken before it saw a changed surface, or starts fresh. `--restore-before
871
+ <rerun>:<seq>` restores from the deepest checkpoint at or before that seq,
872
+ `--checkpoint <id>` from one checkpoint, and `--fresh [sourceRunId...]` starts
873
+ from zero. Launch prints the checkpoint and seq each rerun restored from.
874
+
875
+ `watch` waits until every rerun finishes and is analyzed, then shows each source
876
+ finding as resolved or returned, and new findings as introduced. `launches
877
+ <id> <launchId> -o json` reads one launch again. `result.json` is
878
+ `{summary, changed, resolved, returned, introduced}`.
879
+
880
+ CLI versions before 0.26.0 used an earlier optimizations API and now get an
881
+ update message. Run `npm install -g @withgauge/cli`.
781
882
 
782
883
  ## Compare runs
783
884
 
@@ -853,7 +954,7 @@ index or background indexing process is maintained.
853
954
 
854
955
  Every read supports `-o json` for scripting. `GAUGE_API_TOKEN` overrides
855
956
  stored credentials (useful in CI). Exit codes: `0` ok · `1` error ·
856
- `2` usage · `3` billing-blocked · `4` needs your input (`optimizations watch`).
957
+ `2` usage · `3` billing-blocked.
857
958
 
858
959
  ## Gauge Chat
859
960
 
@@ -965,13 +1066,25 @@ unless every session completed.
965
1066
  Batch cancellation is persisted before workers are contacted, including during
966
1067
  startup. A pending cancellation returns nonzero; inspect status before retrying.
967
1068
 
968
- After an interruption, `gauge cleanup --local` retries cleanup for recorded
969
- interrupted sessions or sessions with incomplete cleanup in this repository.
1069
+ Session status and `gauge watch` probe the host controller with a one-second
1070
+ deadline. If it cannot be reached, they report `unavailable` and the last known
1071
+ state, without changing the saved outcome. Watch keeps checking and displays
1072
+ terminal results when they arrive. Batch supervisors have no status endpoint;
1073
+ nonterminal batch status is `unavailable` with `lastKnownState` and recorded
1074
+ progress. `run wait` continues waiting for a recorded terminal batch outcome.
1075
+ PIDs are not used to infer interruption because coding-agent commands may run in
1076
+ different process namespaces even when they share the same Gauge workspace.
1077
+
1078
+ `gauge cleanup --local` retries incomplete cleanup for recorded terminal sessions
1079
+ in this repository.
970
1080
  It preserves evidence and recovered work, and makes recovered results visible
971
1081
  in `gauge run list`. It leaves live sessions, other repositories, unrelated
972
1082
  containers, and cached images alone. Recovery checks Gauge's container label
973
1083
  and workspace mount before removing a remaining container. Uncertain worker
974
1084
  ownership is reported rather than signaling a potentially reused PID.
1085
+ If a controller dies abruptly without recording a terminal outcome, status stays
1086
+ unavailable and automatic orphan cleanup is unavailable. Preserve the evidence
1087
+ and runtime files for manual recovery; `run wait` may need to be interrupted.
975
1088
 
976
1089
  Local workers have a 30-minute turn deadline and a 60-second supervisor
977
1090
  response deadline, so losing a supervisor cannot leave an idle worker forever.
@@ -1,2 +1,2 @@
1
- import{runLocal}from"./chunk-UANK5LHE.js";import"./chunk-QV7MOO3M.js";import"./chunk-RRLAI72I.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)}
1
+ import{runLocal}from"./chunk-TAFB66SK.js";import"./chunk-PUNARKS2.js";import"./chunk-QV7MOO3M.js";import"./chunk-PMX3NOGH.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-WJTCHKG6.js";import"./chunk-E24F53BZ.js";import"./chunk-RRLAI72I.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
+ 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-PVTU7NGL.js";import"./chunk-AZKXHO6C.js";import"./chunk-PMX3NOGH.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-RRLAI72I.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-W6HW3HKD.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-W6HW3HKD.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-W6HW3HKD.js");const org=(await createChatApiClient().me()).apiKey?.organization;if(!org)throw new CliError("internal","Gauge could not identify which organization this API key belongs to.",{hint:"Check the key in Settings \u2192 API Keys and try again."});return org}async function createdOrganization(agentsSlug){const{orgs}=await createClient().get("/api/v1/me");const id=orgs.find(org=>org.slug===agentsSlug)?.canonicalGaugeOrganizationId;if(!id)throw new CliError("internal","Your workspace was created, but it is not ready to select in the CLI yet.",{hint:"Run `gauge orgs` to check for it, then `gauge orgs use <slug>`. If it is missing, contact Gauge support; you don't need to create it again."});return findOrganization(id)}async function missingAgentsOrg(org){const match=(await fetchDirectory()).find(o=>o.id===org);if(match?.products?.agents!==false)return void 0;return new CliError("not_found",`${match.name} doesn't use Gauge Agents.`,{hint:"Run `gauge orgs` to see which products each organization uses."})}function productsLabel(products){if(!products)return"unknown";return[products.chat?"Chat":void 0,products.agents?"Agents":void 0].filter(Boolean).join(", ")||"-"}export{isUuid,credentialKind,fetchDirectory,findOrganization,resolveOrgValue,legacySelection,resolveSelection,keyOrganization,createdOrganization,missingAgentsOrg,productsLabel};
1
+ import{CliError,createClient,resolveToken}from"./chunk-PMX3NOGH.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-HF2R3SVR.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-HF2R3SVR.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-HF2R3SVR.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);import{z as z7}from"zod";var DEFAULT_LIFECYCLE_TIMEOUT_SECONDS=120;var MAX_LIFECYCLE_TIMEOUT_SECONDS=600;var MAX_LIFECYCLE_SOURCE_LENGTH=128*1024;var lifecycleScriptSchema=z7.object({source:z7.string().min(1).max(MAX_LIFECYCLE_SOURCE_LENGTH),timeoutSeconds:z7.number().int().min(1).max(MAX_LIFECYCLE_TIMEOUT_SECONDS).default(DEFAULT_LIFECYCLE_TIMEOUT_SECONDS)}).strict();var lifecycleSchema=z7.object({version:z7.literal(1),setup:lifecycleScriptSchema.optional(),teardown:lifecycleScriptSchema.optional(),params:z7.record(z7.string().min(1).max(128),z7.json()).default({})}).strict().refine(value=>value.setup!==void 0||value.teardown!==void 0,{message:"Configure a setup or teardown script"}).refine(value=>new TextEncoder().encode(JSON.stringify(value.params)).byteLength<=64*1024,{path:["params"],message:"Lifecycle parameters must fit within 64 KiB"});var runConfig_exports={};__export(runConfig_exports,{ROSTERABLE_AGENTS:()=>ROSTERABLE_AGENTS,SCHEDULABLE_AGENTS:()=>SCHEDULABLE_AGENTS,agentConfigInputSchema:()=>agentConfigInputSchema,agentConfigSchema:()=>agentConfigSchema,assetRefListSchema:()=>assetRefListSchema,assetRefSchema:()=>assetRefSchema,modelUnits:()=>modelUnits,refAssetName:()=>refAssetName,rosterableAgentSchema:()=>rosterableAgentSchema,runsPerCycle:()=>runsPerCycle,schedulableAgentSchema:()=>schedulableAgentSchema,totalRunsPerCycle:()=>totalRunsPerCycle});import{z as z10}from"zod";import{z as z9}from"zod";var INTERVENTION_KINDS=["BASELINE","ADD_SKILL","REMOVE_SKILL","EDIT_SKILL","REWRITE_DOCS","PACKAGE_VERSION","PACKAGE_CONTENT","CLI_VERSION","CLI_INTERVENTION"];import{z as z8}from"zod";var ANALYSIS_SCHEMA_VERSION=1;var evidenceSequenceSchema=z8.number().int().nonnegative().describe("The event's recorded seq in this session attempt. Never infer it from an array index, line number, or turn.");var evidenceRefSchema=z8.discriminatedUnion("kind",[z8.object({kind:z8.literal("trace"),seq:evidenceSequenceSchema}).strict(),z8.object({kind:z8.literal("diff"),path:z8.string().min(1)}).strict()]);var INSTALL_PHASES=["NONE","ATTEMPTED","CONFIGURED","EXERCISED"];var sessionProductSchema=z8.object({name:z8.string(),mentioned:z8.boolean(),considered:z8.boolean(),recommended:z8.boolean(),chosen:z8.boolean(),rejected:z8.boolean(),abandoned:z8.boolean(),installPhase:z8.enum(INSTALL_PHASES),rank:z8.number().int().nullable(),source:z8.enum(["BRIEF","PERSONA","PRIOR","SEARCH","PAGE","REPO","UNKNOWN"]),reason:z8.string(),categories:z8.array(z8.string()),evidence:z8.record(z8.string(),z8.array(evidenceRefSchema))});var sessionObservationSchema=z8.object({id:z8.string(),kind:z8.enum(["FRICTION","OBJECTION","OPPORTUNITY"]),label:z8.string(),detail:z8.string(),subject:z8.string(),basis:z8.enum(["OBSERVED","AGENT_CLAIM","INFERRED"]),effect:z8.enum(["BLOCKED","RECOVERED","EXTRA_WORK","SELECTION_LOSS","UNKNOWN"]),cause:z8.enum(["PRODUCT","CONTENT","ACCESS","ENVIRONMENT","AGENT","UNKNOWN"]),tags:z8.array(z8.string()),evidence:z8.array(evidenceRefSchema),issueId:z8.string().nullable().optional()});var sessionAnalysisSchema=z8.object({schemaVersion:z8.literal(ANALYSIS_SCHEMA_VERSION),instructionsVersion:z8.string().min(1),id:z8.string(),runId:z8.string(),attempt:z8.number().int(),createdAt:z8.string(),origin:z8.enum(["MODEL","LEGACY"]),model:z8.string().nullable(),assessability:z8.enum(["ASSESSED","PARTIAL","UNASSESSABLE"]),limitation:z8.string().nullable(),selection:z8.enum(["MEASURED","UNASSESSABLE","NOT_MEASURED"]),directed:z8.boolean(),products:z8.array(sessionProductSchema),observations:z8.array(sessionObservationSchema)});var artifactPathSchema=z8.string().min(1).refine(value=>!value.startsWith("/")&&!value.includes("\\")&&!value.split("/").some(part=>part===".."||part===""),"Evidence paths must be relative paths inside the session artifacts");var portableEvidenceRefSchema=z8.discriminatedUnion("kind",[z8.object({kind:z8.literal("trace"),seq:evidenceSequenceSchema}).strict(),z8.object({kind:z8.literal("diff"),path:artifactPathSchema}).strict(),z8.object({kind:z8.literal("artifact"),artifact:artifactPathSchema.describe("Path relative to the session attempt directory, for example session/events.ndjson."),attempt:z8.number().int().positive().optional().describe("Must match the analysis attempt; defaults to that attempt."),line:z8.number().int().positive().optional().describe("One-based line number in the original artifact, before any filtering."),endLine:z8.number().int().positive().optional().describe("Inclusive last line of the evidence range."),seq:evidenceSequenceSchema.optional()}).strict().superRefine((ref,ctx)=>{if(ref.line===void 0&&ref.seq===void 0)ctx.addIssue({code:"custom",message:"Artifact evidence needs a line or seq"});if(ref.endLine!==void 0&&(ref.line===void 0||ref.endLine<ref.line))ctx.addIssue({code:"custom",path:["endLine"],message:"endLine requires line and must be at least line"})})]);var findingSubmissionSchema=sessionObservationSchema.omit({id:true,issueId:true}).extend({label:z8.string().trim().min(1).max(200),detail:z8.string().trim().min(1).max(1e4),subject:z8.string().trim().min(1).max(200),tags:z8.array(z8.string().trim().min(1).max(64)).max(32).default([]),evidence:z8.array(portableEvidenceRefSchema).min(1).max(100)}).strict();var criterionAnalysisSubmissionSchema=z8.object({criterionId:z8.string().min(1),outcome:z8.enum(["PASS","FAIL","UNASSESSABLE"]),label:z8.string().trim().min(1).max(1e4),evidence:z8.array(portableEvidenceRefSchema).max(100).default([])}).strict().superRefine((result,ctx)=>{if(result.outcome!=="UNASSESSABLE"&&result.evidence.length===0)ctx.addIssue({code:"custom",path:["evidence"],message:"A criterion verdict needs evidence"})});var productSubmissionSchema=sessionProductSchema.extend({name:z8.string().trim().min(1).max(200),evidence:z8.record(z8.string(),z8.array(portableEvidenceRefSchema))}).strict().superRefine((product,ctx)=>{if((product.chosen||product.rejected||product.recommended)&&!product.considered)ctx.addIssue({code:"custom",path:["considered"],message:"A chosen, rejected, or recommended product was considered"});if(product.considered&&!product.mentioned)ctx.addIssue({code:"custom",path:["mentioned"],message:"A considered product was mentioned"});if(!Object.values(product.evidence).some(refs=>refs.length>0))ctx.addIssue({code:"custom",path:["evidence"],message:"A product judgment needs evidence"})});var analysisSubmissionSchema=z8.object({schemaVersion:z8.literal(ANALYSIS_SCHEMA_VERSION),attempt:z8.number().int().positive().default(1),instructionsVersion:z8.string().trim().min(1),analyst:z8.object({name:z8.string().trim().min(1),model:z8.string().trim().min(1).optional()}).strict(),assessability:sessionAnalysisSchema.shape.assessability,limitation:z8.string().trim().min(1).nullable().default(null),selection:sessionAnalysisSchema.shape.selection.default("NOT_MEASURED"),directed:z8.boolean().default(false),findings:z8.array(findingSubmissionSchema).max(1e3).default([]),products:z8.array(productSubmissionSchema).max(1e3).default([]),criteria:z8.array(criterionAnalysisSubmissionSchema).max(1e3).default([])}).strict().superRefine((analysis,ctx)=>{for(const field of["products","criteria"]){const keys=field==="products"?analysis.products.map(product=>product.name.toLowerCase()):analysis.criteria.map(criterion=>criterion.criterionId);if(new Set(keys).size!==keys.length)ctx.addIssue({code:"custom",path:[field],message:`Duplicate ${field} are not allowed`})}if(analysis.assessability!=="ASSESSED"&&analysis.limitation===null)ctx.addIssue({code:"custom",path:["limitation"],message:"Partial or unassessable analysis needs a limitation"})});var RUN_STATUSES=["QUEUED","CLAIMED","PROVISIONING","RUNNING","SUCCEEDED","FAILED","TIMED_OUT","CANCELED"];var runStatusSchema=z9.enum(RUN_STATUSES);var AGENTS=["CLAUDE_CODE","CODEX_CLI","CURSOR","PI","OPENCODE","ANTIGRAVITY"];var agentSchema=z9.enum(AGENTS);var OBSERVED_PROVIDER_SOURCES=["AGENT_STREAM","GATEWAY_RESPONSE","GATEWAY_AUDIT","CANARY"];var observedProviderSourceSchema=z9.enum(OBSERVED_PROVIDER_SOURCES);var selectedProviderSchema=z9.object({slug:z9.string(),displayName:z9.string()});var observedProviderSchema=z9.object({slug:z9.string(),source:observedProviderSourceSchema});var RUN_TRIGGER_SOURCES=["UNKNOWN","UI","API","CADENCE","STAFF","OPERATOR","GITHUB"];var runTriggerSourceSchema=z9.enum(RUN_TRIGGER_SOURCES);var runTriggeredBySchema=z9.object({source:runTriggerSourceSchema,userId:z9.string().nullable(),email:z9.string().nullable()});var runOptimizationTrialSchema=z9.object({optimizationId:z9.string(),trialId:z9.string(),key:z9.string(),title:z9.string(),kind:z9.enum(INTERVENTION_KINDS)});var runCreditsChargedSchema=z9.number().int().nullable();var runStatusFilterSchema=z9.string().transform(raw=>raw.split(",").map(s=>s.trim().toUpperCase()).filter(Boolean)).pipe(z9.array(runStatusSchema).min(1));var runListQuerySchema=listQuerySchema.extend({status:runStatusFilterSchema.optional(),batch:z9.string().optional(),prompt:z9.string().optional(),experiment:z9.string().optional(),evalSet:z9.string().optional(),since:z9.string().optional()});var runListItemSchema=z9.object({id:z9.string(),status:runStatusSchema,agent:agentSchema,model:z9.string(),resolvedModel:z9.string().nullable().optional(),modelDisplayName:z9.string().nullable().optional(),selectedProvider:selectedProviderSchema.nullable().optional(),observedProvider:observedProviderSchema.nullable().optional(),promptId:z9.string(),promptSnippet:z9.string(),batchId:z9.string(),experiment:z9.string().nullable(),evalSetId:z9.string().nullable(),evalRevision:z9.string().optional(),optimizationTrial:runOptimizationTrialSchema.nullable().optional(),turns:z9.number().int().nullable(),usdCost:z9.number().nullable(),creditsCharged:runCreditsChargedSchema.optional(),triggeredBy:runTriggeredBySchema.optional(),durationMs:z9.number().int().nullable(),exitReason:z9.string().nullable(),createdAt:z9.string(),startedAt:z9.string().nullable(),finishedAt:z9.string().nullable(),parentRunId:z9.string().nullable(),fetchForkPlanId:z9.string().nullable()});var runListResponseSchema=listResponseSchema(runListItemSchema);var runSkillSchema=z9.discriminatedUnion("source",[z9.object({source:z9.literal("saved"),skillId:z9.string(),name:z9.string(),label:z9.string()}),z9.object({source:z9.literal("input"),name:z9.string(),commit:z9.string().nullable(),pullNumber:z9.number().int().nullable()})]);var runDetailSchema=runListItemSchema.omit({promptSnippet:true}).extend({promptText:z9.string(),attempt:z9.number().int(),cancelRequested:z9.boolean(),failureReason:z9.string().nullable(),repoUrl:z9.string().nullable(),repoRef:z9.string().nullable(),scenario:z9.string(),funding:z9.string(),usage:z9.unknown().nullable(),hasDiff:z9.boolean(),claimedAt:z9.string().nullable(),criterionResults:z9.array(z9.object({criterionId:z9.string().nullable(),name:z9.string(),passed:z9.boolean().nullable(),reasoning:z9.string().nullable()})),skills:z9.array(runSkillSchema).optional()});var cancelRunResponseSchema=z9.object({id:z9.string(),status:runStatusSchema,cancelRequested:z9.boolean(),note:z9.string().optional()});var regradeRunResponseSchema=z9.object({runId:z9.string(),evalSetId:z9.string().nullable(),criteria:z9.number().int()});var RUN_INSIGHT_STATUSES=["PENDING","RUNNING","COMPLETE","FAILED","SKIPPED"];var runInsightStatusSchema=z9.enum(RUN_INSIGHT_STATUSES);var insightPassSchema=z9.object({status:runInsightStatusSchema,model:z9.string().nullable(),inputTokens:z9.number().int().nullable(),outputTokens:z9.number().int().nullable(),usdCost:z9.number().nullable(),error:z9.string().nullable()});var runDecisionSchema=z9.object({index:z9.number().int(),category:z9.string(),categoryRaw:z9.string().nullable(),chosenName:z9.string(),chosenEcosystem:z9.string().nullable(),chosenPackage:z9.string().nullable(),reversed:z9.boolean(),detail:z9.unknown()});var RUN_INSIGHT_PASS_KINDS=["ANALYSIS","CLI_DISCOVERY","LEVER","EXPERIMENT_DELTA"];var runInsightPassKindSchema=z9.enum(RUN_INSIGHT_PASS_KINDS);var insightPipelinePassSchema=insightPassSchema.extend({kind:runInsightPassKindSchema});var runInsightResponseSchema=z9.object({runId:z9.string(),decision:insightPassSchema,passes:z9.array(insightPipelinePassSchema),decisions:z9.array(runDecisionSchema),experimentDelta:z9.unknown().nullable(),visibilityVerdict:z9.unknown().nullable(),analysis:sessionAnalysisSchema.nullable()});var runEventSchema=z9.looseObject({run_id:z9.string(),seq:z9.number(),turn:z9.number(),ts:z9.string(),type:z9.string()});var runCompareSideSchema=z9.object({runRequest:z9.string().min(1).optional(),batch:z9.array(z9.string().min(1)).min(1).max(100).optional(),evalSet:z9.string().min(1).optional(),evalRevision:z9.string().min(1).optional(),trial:z9.string().min(1).optional(),experiment:z9.string().min(1).optional(),agent:z9.array(agentSchema).min(1).optional(),model:z9.array(z9.string()).min(1).optional(),since:z9.string().optional(),until:z9.string().optional()}).strict().refine(side=>side.runRequest!==void 0||side.batch!==void 0||side.evalSet!==void 0||side.experiment!==void 0||side.trial!==void 0,"Select runs with runRequest, batch, evalSet, experiment, or trial");var runCompareBodySchema=z9.object({baseline:runCompareSideSchema,candidate:runCompareSideSchema}).strict();var runCompareStatsSchema=z9.object({runs:z9.number().int(),finished:z9.number().int(),succeeded:z9.number().int(),judged:z9.number().int(),passed:z9.number().int(),passRate:z9.number().nullable(),medianTurns:z9.number().nullable(),medianUsdCost:z9.number().nullable(),medianDurationMs:z9.number().nullable(),criteria:z9.array(z9.object({name:z9.string(),judged:z9.number().int(),passed:z9.number().int(),passRate:z9.number().nullable()}))});var runCompareDeltaSchema=z9.object({passRate:z9.number().nullable(),medianTurns:z9.number().nullable(),medianUsdCost:z9.number().nullable(),medianDurationMs:z9.number().nullable(),criteria:z9.array(z9.object({name:z9.string(),passRate:z9.number().nullable()}))});var runCompareRowSchema=z9.object({baseline:runCompareStatsSchema,candidate:runCompareStatsSchema,delta:runCompareDeltaSchema});var runCompareMixedRevisionSchema=z9.object({evalSetId:z9.string().nullable(),promptId:z9.string().nullable(),revisions:z9.array(z9.string())});var runCompareTrialSchema=runOptimizationTrialSchema.extend({runs:z9.number().int()});var runCompareResponseSchema=z9.object({overall:runCompareRowSchema,targets:z9.array(runCompareRowSchema.extend({agent:agentSchema,model:z9.string()})),sides:z9.object({baseline:z9.object({evalRevisions:z9.array(z9.string()),mixedRevisions:z9.array(runCompareMixedRevisionSchema).optional(),truncated:z9.boolean(),trials:z9.array(runCompareTrialSchema).optional()}),candidate:z9.object({evalRevisions:z9.array(z9.string()),mixedRevisions:z9.array(runCompareMixedRevisionSchema).optional(),truncated:z9.boolean(),trials:z9.array(runCompareTrialSchema).optional()})})});var SCHEDULABLE_AGENTS=["CLAUDE_CODE","CODEX_CLI","PI","OPENCODE"];var schedulableAgentSchema=z10.enum(SCHEDULABLE_AGENTS);var ROSTERABLE_AGENTS=[...SCHEDULABLE_AGENTS,"ANTIGRAVITY"];var rosterableAgentSchema=z10.enum(ROSTERABLE_AGENTS);var agentConfigSchema=z10.object({agent:agentSchema,models:z10.array(z10.string().min(1))});var agentConfigInputSchema=z10.object({agent:rosterableAgentSchema,models:z10.array(z10.string().min(1)).default([])});var assetRefSchema=z10.string().max(320).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*@[^\s,]+$/,'asset references must be "name@label"');function refAssetName(ref){const at=ref.indexOf("@");return at<0?ref:ref.slice(0,at)}var assetRefListSchema=z10.array(assetRefSchema).superRefine((refs,ctx)=>{const names=new Set;for(const ref of refs){const name=refAssetName(ref);if(names.has(name)){ctx.addIssue({code:"custom",message:`"${ref}" names an asset already referenced \u2014 one version per asset`})}names.add(name)}});function modelUnits(agents){return agents.reduce((n,a)=>n+Math.max(1,a.models.length),0)}function runsPerCycle(owner,samplesPerCycle){return modelUnits(owner.agents)*samplesPerCycle}function totalRunsPerCycle(owners,samplesPerCycle){return owners.reduce((n,o)=>n+runsPerCycle(o,samplesPerCycle),0)}var DEFAULT_API_URL="https://agents.withgauge.com";function exitCodeFor(code){switch(code){case"usage":case"invalid_request":return 2;case"insufficient_credits":case"needs_provider_key":return 3;default:return 1}}var CliError=class extends Error{code;exitCode;hint;docs;needsAccount;apiCode;details;constructor(code,message,options={}){super(message);this.name="CliError";this.code=code;this.exitCode=exitCodeFor(code);this.hint=options.hint;this.docs=options.docs;this.needsAccount=options.needsAccount??false;this.apiCode=options.apiCode;this.details=options.details}};function resolveBaseUrl(){return process.env.GAUGE_API_URL||readConfig().apiUrl||DEFAULT_API_URL}var ApiClient=class{baseUrl;token;shared;authOptional;constructor(options={}){this.baseUrl=(options.baseUrl??resolveBaseUrl()).replace(/\/+$/,"");this.token=options.token!==void 0?options.token:resolveToken();this.authOptional=options.authOptional??false;this.shared=options.token===void 0?storedSharedCredentials():null;if(this.shared)assertTrustedOrigin(this.baseUrl,this.shared)}get signedIn(){return this.token!==null}async get(path,query,signal){return this.request("GET",path,{query,signal})}async post(path,body,query){return this.request("POST",path,{body,query})}async patch(path,body,query){return this.request("PATCH",path,{body,query})}async put(path,body,query){return this.request("PUT",path,{body,query})}async delete(path,query,body){return this.request("DELETE",path,{body,query})}async sse(path,onEvent,options={}){const res=await this.authenticatedFetch(this.url(path,options.query),{method:"GET",headers:this.headers({Accept:"text/event-stream"}),signal:options.signal});if(!res.ok)throw await this.toError(res);if(!res.body){throw new CliError("internal","Event stream had no response body")}const reader=res.body.getReader();const decoder=new TextDecoder;let buffer="";try{while(true){const{done,value}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:true});let boundary=buffer.indexOf("\n\n");while(boundary!==-1){const raw=buffer.slice(0,boundary);const event=parseSseFrame(raw);buffer=buffer.slice(boundary+2);if(event)onEvent(event);else if(raw.trimStart().startsWith(":"))options.onComment?.();boundary=buffer.indexOf("\n\n")}}}catch(error){if(error instanceof Error&&error.name==="AbortError")return;throw new CliError("network",`Event stream failed: ${messageOf(error)}`)}}url(path,query){const url=new URL(`${this.baseUrl}${path}`);for(const[key,value]of Object.entries(query??{})){if(Array.isArray(value))for(const item of value)url.searchParams.append(key,item);else if(value!==void 0)url.searchParams.set(key,String(value))}return url}headers(extra){if(!this.token&&!this.authOptional){throw new CliError("unauthorized","Not logged in. Run `gauge auth login` or set GAUGE_API_TOKEN.",{needsAccount:true})}return{...this.token?{Authorization:`Bearer ${this.token}`}:{},"User-Agent":USER_AGENT,Accept:"application/json",...extra}}async authenticatedFetch(url,init){let renewalFailed=false;if(this.shared?.refreshToken){try{const next=await refreshCredentials(this.shared);assertTrustedOrigin(this.baseUrl,next);this.shared=next;this.token=this.shared.accessToken}catch(error){if(error instanceof RefreshError&&error.unauthorized)throw new CliError("unauthorized",messageOf(error));if(!(error instanceof RefreshError)||!(Date.parse(this.shared.expiresAt??"")>Date.now()))throw new CliError("network",messageOf(error));renewalFailed=true}}const send=()=>this.fetch(url,{...init,redirect:"error",headers:{...init.headers,...this.token?{Authorization:`Bearer ${this.token}`}:{}}});const response=await send();if(response.status!==401||!this.shared?.refreshToken||renewalFailed)return response;await response.body?.cancel();try{const next=await refreshCredentials(this.shared,true);assertTrustedOrigin(this.baseUrl,next);this.shared=next;this.token=this.shared.accessToken}catch(error){throw new CliError(error instanceof RefreshError&&error.unauthorized?"unauthorized":"network",messageOf(error))}return send()}async fetch(url,init){try{return await fetch(url,init)}catch(error){if(error instanceof Error&&error.name==="AbortError")throw error;throw new CliError("network",`Request to ${url.host} failed: ${messageOf(error)}`)}}async request(method,path,options={}){const headers=this.headers(options.body===void 0?void 0:{"Content-Type":"application/json"});const res=await this.authenticatedFetch(this.url(path,options.query),{method,headers,body:options.body===void 0?void 0:JSON.stringify(options.body),signal:options.signal});if(!res.ok)throw await this.toError(res);if(res.status===204)return void 0;const text=await res.text();if(!text)return void 0;const contentType=res.headers.get("content-type")??"";if(contentType.includes("application/json")){return JSON.parse(text)}return text}async toError(res){const wait=res.status===429?retryAfterSeconds(res):void 0;const hint=wait===void 0?void 0:`Try again in ${wait} s.`;try{const parsed=errorEnvelopeSchema.safeParse(await res.clone().json());if(parsed.success){const{code,message}=parsed.data.error;if(code==="not_found"&&message.startsWith("Organization not found")){const explained=await explainMissingOrg(res.url);if(explained)return explained}return new CliError(code,message,{hint})}}catch{}const what=res.status===429?"Rate limited by the Gauge API":res.status>=500?"Gauge API server error":"API request failed";return new CliError(codeForStatus(res.status),`${what}: HTTP ${res.status} ${res.statusText}`.trim(),{hint})}};async function explainMissingOrg(url){const match=url&&/\/api\/v1\/orgs\/([^/?#]+)/.exec(new URL(url).pathname);if(!match)return void 0;try{const{missingAgentsOrg}=await import("./orgDirectory-QCOOVF65.js");return await missingAgentsOrg(decodeURIComponent(match[1]))}catch{return void 0}}function createClient(options){return new ApiClient(options)}function retryAfterSeconds(res){const value=res.headers.get("retry-after");if(!value)return void 0;const seconds=Number(value);const at=Date.parse(value);if(Number.isFinite(seconds))return Math.max(0,Math.ceil(seconds));if(Number.isNaN(at))return void 0;return Math.max(0,Math.ceil((at-Date.now())/1e3))}function codeForStatus(status){switch(status){case 400:return"invalid_request";case 401:return"unauthorized";case 402:return"insufficient_credits";case 403:return"forbidden";case 404:return"not_found";case 409:return"conflict";case 429:return"rate_limited";default:return"internal"}}function parseSseFrame(frame){let eventName;const dataLines=[];for(const line of frame.split("\n")){if(line.startsWith(":"))continue;if(line.startsWith("event:")){eventName=line.slice("event:".length).trim()}else if(line.startsWith("data:")){dataLines.push(line.slice("data:".length).replace(/^ /,""))}}if(dataLines.length===0)return null;return{event:eventName,data:dataLines.join("\n")}}function messageOf(error){if(error instanceof Error){const cause=error.cause instanceof Error?`: ${error.cause.message}`:"";return`${error.message}${cause}`}return String(error)}export{errorEnvelopeSchema,listResponseSchema,createdBySchema,batteries_exports,brands_exports,feedback_exports,keys_exports,DEFAULT_LIFECYCLE_TIMEOUT_SECONDS,MAX_LIFECYCLE_TIMEOUT_SECONDS,MAX_LIFECYCLE_SOURCE_LENGTH,lifecycleSchema,ANALYSIS_SCHEMA_VERSION,analysisSubmissionSchema,agentSchema,runTriggeredBySchema,runCreditsChargedSchema,runEventSchema,agentConfigSchema,agentConfigInputSchema,assetRefListSchema,runConfig_exports,credentialsPath,readCredentials,resolveToken,saveToken,saveCredentials,clearToken,withCredentialLock,resolveAuthUrl,sharedTokenSchema,storedSharedCredentials,exitCodeFor,CliError,resolveBaseUrl,ApiClient,createClient,retryAfterSeconds,codeForStatus};