@eigenpal/cli 0.23.6 → 0.23.7

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/dist/cli.js CHANGED
@@ -7326,14 +7326,11 @@ var init_runtime_file_ref = __esm(() => {
7326
7326
  });
7327
7327
 
7328
7328
  // ../types/src/processor/configs/document-parser.ts
7329
- var DocumentParserInputSchema, DocumentParserOutputSchema, DocumentParserConfigSchema;
7329
+ var DocumentParserConfigSchema;
7330
7330
  var init_document_parser = __esm(() => {
7331
7331
  init_zod();
7332
7332
  init_ai_client();
7333
- init_runtime_file_ref();
7334
7333
  init_parser();
7335
- DocumentParserInputSchema = ResolvedProcessorFileSchema;
7336
- DocumentParserOutputSchema = ParseResultSchema;
7337
7334
  DocumentParserConfigSchema = object({
7338
7335
  parseMode: ParseModeSchema.optional().describe('Base parser for PDF/image inputs. OCR is the default. `native` extracts PDF text only (never OCR/vision). `native-or-ocr` requests OCR when pages have detectable native-text anomalies (empty, U+FFFD, lone surrogates, forbidden controls, unassigned/noncharacter, heavy PUA). Page selection, subset egress, and billing are provider-dependent. Valid-looking wrong text and literal "?" are not flagged.'),
7339
7336
  ocrModel: string2().optional().describe("OCR provider ID for PDF/image parsing"),
@@ -7356,12 +7353,11 @@ var init_document_parser = __esm(() => {
7356
7353
  });
7357
7354
 
7358
7355
  // ../types/src/processor/configs/document-parser-v2.ts
7359
- var ImageReadingBackendSchema, ParseV2TextFormatSchema, ParseV2SettingsSchema, DocumentParserV2ConfigSchema, AiParseV2ConfigSchema, ParseV2PageSchema, ParseV2ResultSchema, DocumentParserV2InputSchema;
7356
+ var ImageReadingBackendSchema, ParseV2TextFormatSchema, ParseV2SettingsSchema, DocumentParserV2ConfigSchema, AiParseV2ConfigSchema, ParseV2PageSchema, ParseV2ResultSchema;
7360
7357
  var init_document_parser_v2 = __esm(() => {
7361
7358
  init_zod();
7362
7359
  init_ai_client();
7363
7360
  init_parser();
7364
- init_document_parser();
7365
7361
  ImageReadingBackendSchema = _enum(["ocr", "vision"]);
7366
7362
  ParseV2TextFormatSchema = _enum(["plain", "markdown", "html", "djot"]);
7367
7363
  ParseV2SettingsSchema = strictObject({
@@ -7438,7 +7434,6 @@ var init_document_parser_v2 = __esm(() => {
7438
7434
  visionPagesProcessed: number2().int().nonnegative()
7439
7435
  })
7440
7436
  });
7441
- DocumentParserV2InputSchema = DocumentParserInputSchema;
7442
7437
  });
7443
7438
 
7444
7439
  // ../types/src/processor/configs/parse-v2-migration.ts
@@ -7689,32 +7684,6 @@ var init_common = __esm(() => {
7689
7684
  });
7690
7685
  });
7691
7686
 
7692
- // ../types/src/core/ids.ts
7693
- var PROCESSOR_IDS;
7694
- var init_ids = __esm(() => {
7695
- PROCESSOR_IDS = {
7696
- MERGE: "builtin/merge",
7697
- DOCUMENT_PARSER: "builtin/parser",
7698
- DOCUMENT_PARSER_V2: "builtin/parser-v2",
7699
- EXTRACT: "builtin/extract",
7700
- SPLIT: "builtin/split",
7701
- SEGMENT: "builtin/segment",
7702
- CLASSIFY: "builtin/classify",
7703
- CLASSIFY_PAGES: "builtin/classify-pages",
7704
- VISION: "builtin/vision",
7705
- SEARCH_FILES: "builtin/search-files",
7706
- FIGURE_CROPS: "builtin/figure-crops",
7707
- TEMPLATE: "builtin/template",
7708
- PDF_EMBEDDER: "builtin/pdf-embedder",
7709
- CROP_REGIONS: "builtin/crop-regions",
7710
- XLSX_TO_JSON: "builtin/xlsx-to-json",
7711
- JSON_TO_XLSX: "builtin/json-to-xlsx",
7712
- ARCHIVE_LIST: "builtin/archive-list",
7713
- ARCHIVE_EXTRACT: "builtin/archive-extract",
7714
- MERGE_DOCUMENTS: "builtin/merge-documents"
7715
- };
7716
- });
7717
-
7718
7687
  // ../types/src/core/index.ts
7719
7688
  var init_core3 = __esm(() => {
7720
7689
  init_common();
@@ -15716,11 +15685,11 @@ var init_segment = __esm(() => {
15716
15685
  text: string2().describe("Extracted text for this page"),
15717
15686
  pageName: string2().optional()
15718
15687
  })).min(1).describe("Per-page parsed content from a document parser")
15719
- }).passthrough().describe("Document-parser-shaped input. Pass {{ steps.parse.output }} directly — extra fields like text/metadata are ignored.");
15688
+ }).passthrough().describe("Document-parser-shaped input. Pass {{ steps.parse.output }} directly: extra fields like text/metadata are ignored.");
15720
15689
  SegmentConfigSchema = object({
15721
15690
  documentTypes: array(object({
15722
15691
  name: string2().min(1).describe('Type label returned in documents[].type (e.g. "timesheet", "deal-memo").'),
15723
- description: string2().optional().describe("What this document type looks like — headings, layout, vocabulary, and the visual cues that mark its FIRST page. Fed to the LLM as guidance for both boundary detection and typing.")
15692
+ description: string2().optional().describe("What this document type looks like: headings, layout, vocabulary, and the visual cues that mark its FIRST page. Fed to the LLM as guidance for both boundary detection and typing.")
15724
15693
  })).min(1).describe('The document-type taxonomy. The LLM tags each detected document with one of these names, or the reserved "unknown" type when none fit.'),
15725
15694
  rules: string2().optional().describe("Optional natural-language rules appended to the system prompt"),
15726
15695
  provider: string2().optional().describe('Provider ID from eigenpal.config.yaml (e.g. "openai/gpt-6-luna"). Falls back to the tenant default LLM provider when omitted.'),
@@ -15731,8 +15700,8 @@ var init_segment = __esm(() => {
15731
15700
  SegmentSummarySchema = object({
15732
15701
  total: number2().int().describe("Total documents discovered in the batch."),
15733
15702
  labelled: number2().int().describe('Documents assigned a known taxonomy type (type !== "unknown").'),
15734
- unlabelled: number2().int().describe('Documents the segmenter could not label (type === "unknown") — escalate to a human.'),
15735
- lowConfidence: number2().int().describe('Documents whose boundary/type confidence is "low" — also worth human review.'),
15703
+ unlabelled: number2().int().describe('Documents the segmenter could not label (type === "unknown"): escalate to a human.'),
15704
+ lowConfidence: number2().int().describe('Documents whose boundary/type confidence is "low", also worth human review.'),
15736
15705
  byType: record(string2(), number2().int()).describe('Per-type document counts, keyed by type name (includes "unknown").'),
15737
15706
  needsReview: array(object({
15738
15707
  index: number2().int(),
@@ -15753,7 +15722,7 @@ var init_segment = __esm(() => {
15753
15722
  evidence: object({
15754
15723
  start_heading_text: string2().nullable().optional().describe("Verbatim heading/title text the LLM cited as the document start"),
15755
15724
  start_page: number2().int().nullable().optional().describe("Page where the start appears")
15756
- }).optional().describe("Structured start evidence — for downstream parsing without regex over `notes`."),
15725
+ }).optional().describe("Structured start evidence, for downstream parsing without regex over `notes`."),
15757
15726
  text: string2().describe("Joined per-page text for this document, ready for ai.extract"),
15758
15727
  pages: array(object({
15759
15728
  pageIndex: number2().int(),
@@ -15778,13 +15747,13 @@ var init_split = __esm(() => {
15778
15747
  text: string2().describe("Extracted text for this page"),
15779
15748
  pageName: string2().optional()
15780
15749
  })).min(1).describe("Per-page parsed content from a document parser")
15781
- }).passthrough().describe("Document-parser-shaped input. Pass {{ steps.parse.output }} directly — extra fields like text/metadata are ignored.");
15750
+ }).passthrough().describe("Document-parser-shaped input. Pass {{ steps.parse.output }} directly: extra fields like text/metadata are ignored.");
15782
15751
  SplitConfigSchema = object({
15783
15752
  sections: array(object({
15784
15753
  name: string2().min(1).describe("Stable id for the section"),
15785
15754
  description: string2().min(1).describe("What this section looks like in the document. Use the document's own terminology (e.g. 'Príloha 2 / Anlage 2') and visual cues."),
15786
15755
  required: boolean2().optional().describe('If true, log a warn when this section is not found, and lean the LLM toward expecting it. Default: false (Reducto-style "may be absent").'),
15787
- endHints: array(string2()).optional().describe('Natural-language hints fed to the LLM about what marks the END of this section (e.g. ["PRÍPAD PORUŠENIA ZMLUVY", "*Koniec prílohy*", "the next chapter heading"]). The LLM uses these as guidance — not a regex match — so casing variants, missing diacritics, and multilingual phrasings still close the section correctly. The LLM emits a structured end_anchor per section it judges closed; deterministic merge applies it.')
15756
+ endHints: array(string2()).optional().describe('Natural-language hints fed to the LLM about what marks the END of this section (e.g. ["PRÍPAD PORUŠENIA ZMLUVY", "*Koniec prílohy*", "the next chapter heading"]). The LLM uses these as guidance, not a regex match: so casing variants, missing diacritics, and multilingual phrasings still close the section correctly. The LLM emits a structured end_anchor per section it judges closed; deterministic merge applies it.')
15788
15757
  })).min(1),
15789
15758
  rules: string2().optional().describe("Optional natural-language rules appended to the system prompt"),
15790
15759
  provider: string2().optional().describe('Provider ID from eigenpal.config.yaml (e.g. "openai/gpt-6-luna"). Falls back to the tenant default LLM provider when omitted.'),
@@ -15800,7 +15769,7 @@ var init_split = __esm(() => {
15800
15769
  evidence: object({
15801
15770
  start_heading_text: string2().nullable().optional().describe("Verbatim heading text the LLM cited as the section start"),
15802
15771
  start_page: number2().int().nullable().optional().describe("Page where start_heading_text appears")
15803
- }).optional().describe("Structured start-anchor evidence the LLM cited — for downstream parsing without regex over `notes`."),
15772
+ }).optional().describe("Structured start-anchor evidence the LLM cited, for downstream parsing without regex over `notes`."),
15804
15773
  end_evidence: object({
15805
15774
  end_page: number2().int().describe("LAST page of the section (inclusive)"),
15806
15775
  confidence: ConfidenceLevelSchema2,
@@ -15885,10 +15854,9 @@ function refineXlsxToJsonHeaderRowColumns(config, ctx) {
15885
15854
  }
15886
15855
  }
15887
15856
  }
15888
- var XLSX_TO_JSON_DEFAULT_LIMITS, A1_RANGE_RE, XlsxToJsonColumnSchema, XlsxToJsonLimitsSchema, XlsxToJsonInputSchema, XlsxToJsonSheetMetaSchema, XlsxToJsonDiagnosticSchema, XlsxToJsonOutputSchema, XlsxToJsonConfigSchema;
15857
+ var XLSX_TO_JSON_DEFAULT_LIMITS, A1_RANGE_RE, XlsxToJsonColumnSchema, XlsxToJsonLimitsSchema, XlsxToJsonSheetMetaSchema, XlsxToJsonDiagnosticSchema, XlsxToJsonOutputSchema, XlsxToJsonConfigSchema;
15889
15858
  var init_xlsx_to_json = __esm(() => {
15890
15859
  init_zod();
15891
- init_runtime_file_ref();
15892
15860
  init_spreadsheet_evidence();
15893
15861
  XLSX_TO_JSON_DEFAULT_LIMITS = {
15894
15862
  maxInputBytes: 50 * 1024 * 1024,
@@ -15925,7 +15893,6 @@ var init_xlsx_to_json = __esm(() => {
15925
15893
  maxColumns: number2().int().min(1).max(XLSX_TO_JSON_DEFAULT_LIMITS.maxColumns).optional().describe(`Maximum columns in the selected range. Omitted uses the server default (${XLSX_TO_JSON_DEFAULT_LIMITS.maxColumns}). Cannot exceed it.`),
15926
15894
  maxCells: number2().int().min(1).max(XLSX_TO_JSON_DEFAULT_LIMITS.maxCells).optional().describe(`Maximum cells in the selected range. Omitted uses the server default (${XLSX_TO_JSON_DEFAULT_LIMITS.maxCells.toLocaleString("en-US")}). Cannot exceed it.`)
15927
15895
  }).describe("Optional workload caps that can only lower the server defaults. Omitted fields use the server defaults.");
15928
- XlsxToJsonInputSchema = ResolvedProcessorFileSchema;
15929
15896
  XlsxToJsonSheetMetaSchema = object({
15930
15897
  name: string2().describe("Selected sheet name"),
15931
15898
  declaredRange: string2().optional().describe("Worksheet declared extent before empty trailing rows/columns were removed"),
@@ -15977,21 +15944,7 @@ var init_xlsx_to_json = __esm(() => {
15977
15944
  });
15978
15945
 
15979
15946
  // ../types/src/processor/configs/index.ts
15980
- var PROCESSOR_SCHEMAS;
15981
15947
  var init_configs = __esm(() => {
15982
- init_ids();
15983
- init_document_parser_v2();
15984
- init_classify();
15985
- init_classify_pages();
15986
- init_document_parser();
15987
- init_extract();
15988
- init_json_to_xlsx();
15989
- init_merge();
15990
- init_pdf_embedder();
15991
- init_segment();
15992
- init_split();
15993
- init_template();
15994
- init_xlsx_to_json();
15995
15948
  init_classify();
15996
15949
  init_classify_pages();
15997
15950
  init_document_parser();
@@ -16004,80 +15957,6 @@ var init_configs = __esm(() => {
16004
15957
  init_split();
16005
15958
  init_template();
16006
15959
  init_xlsx_to_json();
16007
- PROCESSOR_SCHEMAS = {
16008
- [PROCESSOR_IDS.DOCUMENT_PARSER_V2]: {
16009
- id: PROCESSOR_IDS.DOCUMENT_PARSER_V2,
16010
- inputSchema: DocumentParserV2InputSchema,
16011
- outputSchema: ParseV2ResultSchema,
16012
- configSchema: DocumentParserV2ConfigSchema
16013
- },
16014
- [PROCESSOR_IDS.EXTRACT]: {
16015
- id: PROCESSOR_IDS.EXTRACT,
16016
- inputSchema: ExtractInputSchema,
16017
- outputSchema: ExtractOutputSchema,
16018
- configSchema: ExtractConfigSchema
16019
- },
16020
- [PROCESSOR_IDS.DOCUMENT_PARSER]: {
16021
- id: PROCESSOR_IDS.DOCUMENT_PARSER,
16022
- inputSchema: DocumentParserInputSchema,
16023
- outputSchema: DocumentParserOutputSchema,
16024
- configSchema: DocumentParserConfigSchema
16025
- },
16026
- [PROCESSOR_IDS.MERGE]: {
16027
- id: PROCESSOR_IDS.MERGE,
16028
- inputSchema: MergeInputSchema,
16029
- outputSchema: MergeOutputSchema,
16030
- configSchema: MergeConfigSchema
16031
- },
16032
- [PROCESSOR_IDS.TEMPLATE]: {
16033
- id: PROCESSOR_IDS.TEMPLATE,
16034
- inputSchema: TemplateInputSchema,
16035
- outputSchema: TemplateOutputSchema,
16036
- configSchema: TemplateConfigSchema
16037
- },
16038
- [PROCESSOR_IDS.PDF_EMBEDDER]: {
16039
- id: PROCESSOR_IDS.PDF_EMBEDDER,
16040
- inputSchema: PdfEmbedderInputSchema,
16041
- outputSchema: PdfEmbedderOutputSchema,
16042
- configSchema: PdfEmbedderConfigSchema
16043
- },
16044
- [PROCESSOR_IDS.SPLIT]: {
16045
- id: PROCESSOR_IDS.SPLIT,
16046
- inputSchema: SplitInputSchema,
16047
- outputSchema: SplitOutputSchema,
16048
- configSchema: SplitConfigSchema
16049
- },
16050
- [PROCESSOR_IDS.SEGMENT]: {
16051
- id: PROCESSOR_IDS.SEGMENT,
16052
- inputSchema: SegmentInputSchema,
16053
- outputSchema: SegmentOutputSchema,
16054
- configSchema: SegmentConfigSchema
16055
- },
16056
- [PROCESSOR_IDS.CLASSIFY]: {
16057
- id: PROCESSOR_IDS.CLASSIFY,
16058
- inputSchema: ClassifyInputSchema,
16059
- outputSchema: ClassifyOutputSchema,
16060
- configSchema: ClassifyConfigSchema
16061
- },
16062
- [PROCESSOR_IDS.CLASSIFY_PAGES]: {
16063
- id: PROCESSOR_IDS.CLASSIFY_PAGES,
16064
- inputSchema: ClassifyPagesInputSchema,
16065
- outputSchema: ClassifyPagesOutputSchema,
16066
- configSchema: ClassifyPagesConfigSchema
16067
- },
16068
- [PROCESSOR_IDS.XLSX_TO_JSON]: {
16069
- id: PROCESSOR_IDS.XLSX_TO_JSON,
16070
- inputSchema: XlsxToJsonInputSchema,
16071
- outputSchema: XlsxToJsonOutputSchema,
16072
- configSchema: XlsxToJsonConfigSchema
16073
- },
16074
- [PROCESSOR_IDS.JSON_TO_XLSX]: {
16075
- id: PROCESSOR_IDS.JSON_TO_XLSX,
16076
- inputSchema: JsonToXlsxInputSchema,
16077
- outputSchema: JsonToXlsxOutputSchema,
16078
- configSchema: JsonToXlsxConfigSchema
16079
- }
16080
- };
16081
15960
  });
16082
15961
 
16083
15962
  // ../types/src/processor/index.ts
@@ -16139,16 +16018,16 @@ var init_run_expand = __esm(() => {
16139
16018
  RUN_DETAIL_EXPAND_PRESET = RUN_EXPAND_SECTIONS.join(",");
16140
16019
  LEGACY_RUN_EXPAND_MIGRATION = {
16141
16020
  output: "`output` is not expandable; completed detail responses include top-level `output`",
16142
- lineage: "use `expand=execution` — batch, retry, and annotation live on `execution`",
16021
+ lineage: "use `expand=execution`: batch, retry, and annotation live on `execution`",
16143
16022
  cost: "use `expand=usage`",
16144
- input: "still `expand=input` — args now live at `input.args`",
16145
- metadata: "use `expand=input` — metadata now lives at `input.metadata`",
16023
+ input: "still `expand=input`: args now live at `input.args`",
16024
+ metadata: "use `expand=input`: metadata now lives at `input.metadata`",
16146
16025
  observability: "use `expand=debug`",
16147
- review: "use `expand=execution` — reviews live at `execution.review`",
16148
- steps: "use `expand=execution` — steps live at `execution.steps` (workflow runs)",
16149
- definition: "use `expand=execution` — definitionSnapshot lives at `execution.definitionSnapshot` (workflow runs)",
16026
+ review: "use `expand=execution`: reviews live at `execution.review`",
16027
+ steps: "use `expand=execution`: steps live at `execution.steps` (workflow runs)",
16028
+ definition: "use `expand=execution`: definitionSnapshot lives at `execution.definitionSnapshot` (workflow runs)",
16150
16029
  files: "downloadable output refs live at top-level `files` on completed detail responses; `expand=execution` adds `execution.files.output` metadata for agent runs",
16151
- expected: "use `expand=execution` — expected output lives at `execution.expected`",
16030
+ expected: "use `expand=execution`: expected output lives at `execution.expected`",
16152
16031
  trace: "trace id: `expand=debug` (`debug.traceId`); trace files: `GET /api/v1/runs/{id}/artifacts`",
16153
16032
  issues: "use `GET /api/v1/runs/{id}/artifacts` and look for `issues.md`",
16154
16033
  lockfile: "use `GET /api/v1/runs/{id}/artifacts` and look for `eigenpal.lock`"
@@ -54039,7 +53918,7 @@ var init_retry = __esm(() => {
54039
53918
  });
54040
53919
 
54041
53920
  // ../types/src/workflow/steps.ts
54042
- var AI_STEP_TYPES, TRANSFORM_STEP_TYPES, ACTION_STEP_TYPES, CONTROL_STEP_TYPES, STEP_TYPES, StepTypeSchema, BaseStepSchema, ControlContainerBaseStepSchema, AIStepSchema, TransformStepSchema, HttpMethodSchema, ActionStepSchema, WaitStepSchema, HumanReviewStepSchema, FailStepSchema, LegacyBlockStepSchemaInner, IfStepSchemaInner, SwitchCaseSchemaInner, SwitchStepSchemaInner, ParallelBranchSchemaInner, ParallelStepSchemaInner, ForeachStepSchemaInner, ParallelMapStepSchemaInner, StepSchema;
53921
+ var AI_STEP_TYPES, TRANSFORM_STEP_TYPES, ACTION_STEP_TYPES, CONTROL_STEP_TYPES, STEP_TYPES, StepTypeSchema, BaseStepSchema, ControlContainerBaseStepSchema, AIStepSchema, TransformStepSchema, HttpMethodSchema, ActionStepSchema, WaitStepSchema, HumanReviewStepSchema, FailStepSchema, IfStepSchemaInner, SwitchCaseSchemaInner, SwitchStepSchemaInner, ParallelBranchSchemaInner, ParallelStepSchemaInner, ForeachStepSchemaInner, ParallelMapStepSchemaInner, StepSchema;
54043
53922
  var init_steps = __esm(() => {
54044
53923
  init_zod();
54045
53924
  init_retry();
@@ -54132,13 +54011,6 @@ var init_steps = __esm(() => {
54132
54011
  statusCode: number2().int().min(400).max(599).optional(),
54133
54012
  message: string2().min(1)
54134
54013
  });
54135
- LegacyBlockStepSchemaInner = BaseStepSchema.extend({
54136
- type: literal("control.block"),
54137
- retries: number2().int().min(0).optional(),
54138
- retryDelay: number2().positive().optional(),
54139
- blockName: string2().min(1),
54140
- inputs: record(string2(), unknown()).optional()
54141
- });
54142
54014
  IfStepSchemaInner = ControlContainerBaseStepSchema.extend({
54143
54015
  type: literal("control.if"),
54144
54016
  condition: string2(),
@@ -54185,7 +54057,6 @@ var init_steps = __esm(() => {
54185
54057
  WaitStepSchema,
54186
54058
  HumanReviewStepSchema,
54187
54059
  FailStepSchema,
54188
- LegacyBlockStepSchemaInner,
54189
54060
  IfStepSchemaInner,
54190
54061
  SwitchStepSchemaInner,
54191
54062
  ParallelStepSchemaInner,
@@ -55841,7 +55712,7 @@ var init_evaluator_config = __esm(() => {
55841
55712
  mode: JudgeModeSchema.default("continuous").describe("Continuous = the LLM returns a free-form score in [0, 1]. Discrete = the LLM picks one of your labels and the score is looked up from the table."),
55842
55713
  labels: LabelsRecord.optional().describe("Allowed labels and the score each maps to. Required in discrete mode. The judge MUST return one of these labels; each score must be in [0, 1]."),
55843
55714
  passThreshold: ScoreInUnitInterval.optional().describe(LEGACY_EVALUATOR_THRESHOLD_DESCRIPTION),
55844
- promptExtension: string2().trim().min(LLM_JUDGE_PROMPT_MIN_LENGTH, `judge prompt is required — describe what makes a good answer for this workflow (≥${LLM_JUDGE_PROMPT_MIN_LENGTH} chars). An empty prompt makes the model invent its own scoring criteria.`).describe("Required. Evaluation criteria appended to the judge prompt — describe what makes a good answer for this workflow (tone, completeness, edge cases). Cannot be empty: an empty prompt yields the model inventing its own criteria."),
55715
+ promptExtension: string2().trim().min(LLM_JUDGE_PROMPT_MIN_LENGTH, `judge prompt is required: describe what makes a good answer for this workflow (≥${LLM_JUDGE_PROMPT_MIN_LENGTH} chars). An empty prompt makes the model invent its own scoring criteria.`).describe("Required. Evaluation criteria appended to the judge prompt: describe what makes a good answer for this workflow (tone, completeness, edge cases). Cannot be empty: an empty prompt yields the model inventing its own criteria."),
55845
55716
  docLabel: string2().default("output").describe("Name the judge uses to refer to the output in its prompt (e.g. 'invoice', 'extraction'). Default is 'output'.")
55846
55717
  }).superRefine((val2, ctx) => {
55847
55718
  if (val2.mode === "discrete") {
@@ -215183,9 +215054,401 @@ import path20 from "path";
215183
215054
  import { fileURLToPath as fileURLToPath8 } from "url";
215184
215055
 
215185
215056
  // src/commands/agents/index.ts
215186
- import { existsSync as existsSync13 } from "node:fs";
215057
+ import { existsSync as existsSync11 } from "node:fs";
215187
215058
  import path16 from "node:path";
215188
215059
 
215060
+ // ../sdk-typescript/src/lib/fetch-body.ts
215061
+ function isNodeReadableStream(body) {
215062
+ return typeof body.pipe === "function";
215063
+ }
215064
+ function byteViewToArrayBuffer(view) {
215065
+ if (view.buffer instanceof ArrayBuffer && view.byteOffset === 0 && view.byteLength === view.buffer.byteLength) {
215066
+ return view.buffer;
215067
+ }
215068
+ const copy = new Uint8Array(view.byteLength);
215069
+ copy.set(view);
215070
+ return copy.buffer;
215071
+ }
215072
+ function toPutBody(body) {
215073
+ if (isNodeReadableStream(body)) {
215074
+ return body;
215075
+ }
215076
+ return byteViewToArrayBuffer(body);
215077
+ }
215078
+ function destroyUnreadNodeReadable(stream) {
215079
+ const readable = stream;
215080
+ if (!readable.readableEnded && !readable.destroyed && typeof readable.destroy === "function") {
215081
+ readable.destroy();
215082
+ }
215083
+ }
215084
+ async function ensureNodeReadableFullySent(stream, expectedByteLength) {
215085
+ const readable = stream;
215086
+ if (readable.readableEnded) {
215087
+ return expectedByteLength ?? 0;
215088
+ }
215089
+ if (readable.destroyed) {
215090
+ throw new Error("Upload stream was destroyed before the request body finished sending");
215091
+ }
215092
+ let bytes = 0;
215093
+ for await (const chunk of stream) {
215094
+ bytes += typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk.length;
215095
+ }
215096
+ if (expectedByteLength !== undefined && bytes !== expectedByteLength) {
215097
+ throw new Error(`Upload sent ${bytes} byte(s) but ${expectedByteLength} were expected for this part`);
215098
+ }
215099
+ return bytes;
215100
+ }
215101
+ // ../sdk-typescript/src/lib/upload-presigned-multipart.ts
215102
+ var MULTIPART_UPLOAD_CONCURRENCY = 4;
215103
+ var MULTIPART_PART_MAX_RETRIES = 4;
215104
+ var MULTIPART_PART_RETRY_BASE_MS = 250;
215105
+ function expectedPartByteLength(totalSize, partSizeBytes, partNumber, partCount) {
215106
+ if (!Number.isInteger(partNumber) || partNumber < 1 || partNumber > partCount) {
215107
+ throw new Error(`partNumber must be an integer in [1, ${partCount}]`);
215108
+ }
215109
+ if (totalSize === 0)
215110
+ return 0;
215111
+ if (partNumber < partCount)
215112
+ return partSizeBytes;
215113
+ const remainder = totalSize % partSizeBytes;
215114
+ return remainder === 0 ? partSizeBytes : remainder;
215115
+ }
215116
+ function partByteOffset(partSizeBytes, partNumber) {
215117
+ return (partNumber - 1) * partSizeBytes;
215118
+ }
215119
+ function isTransientHttpStatus(status) {
215120
+ return status === 408 || status === 429 || status >= 500 && status <= 599;
215121
+ }
215122
+ function filterStorageHeaders(headers, stripContentLength) {
215123
+ return Object.fromEntries(Object.entries(headers ?? {}).filter(([name]) => stripContentLength ? name.toLowerCase() !== "content-length" : true));
215124
+ }
215125
+ function partIsAuthoritativelyComplete(listed, partNumber, expectedSize) {
215126
+ const found = listed.find((part) => part.partNumber === partNumber);
215127
+ if (!found)
215128
+ return false;
215129
+ return found.size === expectedSize;
215130
+ }
215131
+
215132
+ class PartUploadHttpError extends Error {
215133
+ status;
215134
+ constructor(status) {
215135
+ super(`Storage part upload failed (${status})`);
215136
+ this.status = status;
215137
+ this.name = "PartUploadHttpError";
215138
+ }
215139
+ }
215140
+ function isAbortError(error) {
215141
+ return error instanceof Error && error.name === "AbortError" || typeof DOMException !== "undefined" && error instanceof DOMException && error.name === "AbortError";
215142
+ }
215143
+ function shouldAbortMultipartUploadSession(options) {
215144
+ return !options.partsReady;
215145
+ }
215146
+ function shouldAbortPresignedPutUploadSession(options) {
215147
+ return !options.putReady;
215148
+ }
215149
+ function multipartCompleteRetryHint(uploadId) {
215150
+ return `Uploaded parts remain stored for ${uploadId}; retry complete and do not abort the session.`;
215151
+ }
215152
+ function presignedPutCompleteRetryHint(uploadId) {
215153
+ return `Uploaded object remains stored for ${uploadId}; retry complete and do not abort the session.`;
215154
+ }
215155
+ function annotateMultipartCompleteFailure(uploadId, error) {
215156
+ return annotateUploadCompleteFailure(multipartCompleteRetryHint(uploadId), error);
215157
+ }
215158
+ function annotatePresignedPutCompleteFailure(uploadId, error) {
215159
+ return annotateUploadCompleteFailure(presignedPutCompleteRetryHint(uploadId), error);
215160
+ }
215161
+ function annotateUploadCompleteFailure(hint, error) {
215162
+ if (error instanceof Error) {
215163
+ if (!error.message.includes("retry complete")) {
215164
+ error.message = `${error.message} ${hint}`;
215165
+ }
215166
+ return error;
215167
+ }
215168
+ return new Error(`${String(error)} ${hint}`);
215169
+ }
215170
+ function isRetryablePartError(error, signal) {
215171
+ if (signal?.aborted)
215172
+ return false;
215173
+ if (isAbortError(error))
215174
+ return false;
215175
+ if (error instanceof PartUploadHttpError)
215176
+ return isTransientHttpStatus(error.status);
215177
+ return true;
215178
+ }
215179
+ async function sleep(ms, signal) {
215180
+ if (signal?.aborted)
215181
+ throw abortError(signal);
215182
+ await new Promise((resolve, reject) => {
215183
+ const timer = setTimeout(resolve, ms);
215184
+ const onAbort = () => {
215185
+ clearTimeout(timer);
215186
+ reject(abortError(signal));
215187
+ };
215188
+ signal?.addEventListener("abort", onAbort, { once: true });
215189
+ });
215190
+ }
215191
+ function abortError(signal) {
215192
+ if (signal?.reason instanceof Error)
215193
+ return signal.reason;
215194
+ return typeof DOMException !== "undefined" ? new DOMException("Upload aborted", "AbortError") : Object.assign(new Error("Upload aborted"), { name: "AbortError" });
215195
+ }
215196
+ async function mapPool(items, concurrency, signal, worker) {
215197
+ if (items.length === 0)
215198
+ return;
215199
+ let cursor = 0;
215200
+ let firstError;
215201
+ await Promise.all(Array.from({ length: Math.min(Math.max(1, concurrency), items.length) }, async () => {
215202
+ while (firstError == null) {
215203
+ if (signal?.aborted)
215204
+ throw abortError(signal);
215205
+ const index = cursor++;
215206
+ if (index >= items.length)
215207
+ return;
215208
+ try {
215209
+ await worker(items[index]);
215210
+ } catch (error) {
215211
+ firstError ??= error;
215212
+ }
215213
+ }
215214
+ }));
215215
+ if (firstError)
215216
+ throw firstError;
215217
+ }
215218
+ async function uploadPresignedMultipartParts(options) {
215219
+ const concurrency = options.concurrency ?? MULTIPART_UPLOAD_CONCURRENCY;
215220
+ let uploadedBytes = 0;
215221
+ const credited = new Set;
215222
+ const credit = (partNumber, length) => {
215223
+ if (credited.has(partNumber))
215224
+ return;
215225
+ credited.add(partNumber);
215226
+ uploadedBytes += length;
215227
+ options.onProgress?.(uploadedBytes, options.totalSize);
215228
+ };
215229
+ const pendingPartNumbers = async () => {
215230
+ const listed = await options.listParts();
215231
+ const pending = [];
215232
+ for (let partNumber = 1;partNumber <= options.partCount; partNumber++) {
215233
+ const length = expectedPartByteLength(options.totalSize, options.partSizeBytes, partNumber, options.partCount);
215234
+ if (partIsAuthoritativelyComplete(listed, partNumber, length)) {
215235
+ credit(partNumber, length);
215236
+ continue;
215237
+ }
215238
+ pending.push(partNumber);
215239
+ }
215240
+ return pending;
215241
+ };
215242
+ const uploadOne = async (partNumber) => {
215243
+ const length = expectedPartByteLength(options.totalSize, options.partSizeBytes, partNumber, options.partCount);
215244
+ const start = partByteOffset(options.partSizeBytes, partNumber);
215245
+ let lastError;
215246
+ for (let attempt = 0;attempt <= MULTIPART_PART_MAX_RETRIES; attempt++) {
215247
+ if (options.signal?.aborted)
215248
+ throw abortError(options.signal);
215249
+ try {
215250
+ const signed = await options.presignPart(partNumber);
215251
+ const partLength = Number.isInteger(signed.partSizeBytes) ? signed.partSizeBytes : length;
215252
+ await options.putPart({
215253
+ url: signed.url,
215254
+ headers: signed.headers ?? {},
215255
+ partNumber,
215256
+ start,
215257
+ length: partLength
215258
+ });
215259
+ credit(partNumber, length);
215260
+ return;
215261
+ } catch (error) {
215262
+ lastError = error;
215263
+ if (!isRetryablePartError(error, options.signal) || attempt === MULTIPART_PART_MAX_RETRIES) {
215264
+ throw error;
215265
+ }
215266
+ await sleep(MULTIPART_PART_RETRY_BASE_MS * 2 ** attempt, options.signal);
215267
+ }
215268
+ }
215269
+ throw lastError;
215270
+ };
215271
+ let pending = await pendingPartNumbers();
215272
+ if (pending.length > 0) {
215273
+ await mapPool(pending, concurrency, options.signal, uploadOne);
215274
+ }
215275
+ pending = await pendingPartNumbers();
215276
+ if (pending.length > 0) {
215277
+ await mapPool(pending, concurrency, options.signal, uploadOne);
215278
+ pending = await pendingPartNumbers();
215279
+ }
215280
+ if (pending.length > 0) {
215281
+ throw new Error(`Upload incomplete: ${pending.length} part(s) missing from storage before complete`);
215282
+ }
215283
+ }
215284
+
215285
+ // ../sdk-typescript/src/lib/upload-app-chunked.ts
215286
+ var HTTP_CHUNKED_MAX_RETRIES = 4;
215287
+ var HTTP_CHUNKED_RETRY_BASE_MS = 250;
215288
+ function expectedHttpChunkByteLength(totalSize, chunkSizeBytes, chunkIndex, chunkCount) {
215289
+ if (!Number.isInteger(chunkIndex) || chunkIndex < 0 || chunkIndex >= chunkCount) {
215290
+ throw new Error(`chunkIndex must be an integer in [0, ${chunkCount})`);
215291
+ }
215292
+ if (totalSize === 0)
215293
+ return 0;
215294
+ if (chunkIndex < chunkCount - 1)
215295
+ return chunkSizeBytes;
215296
+ const remainder = totalSize % chunkSizeBytes;
215297
+ return remainder === 0 ? chunkSizeBytes : remainder;
215298
+ }
215299
+ function chunkByteOffset(chunkSizeBytes, chunkIndex) {
215300
+ return chunkIndex * chunkSizeBytes;
215301
+ }
215302
+ function shouldAbortHttpChunkedUploadSession(options) {
215303
+ return !options.chunksReady;
215304
+ }
215305
+ function httpChunkedCompleteRetryHint(uploadId) {
215306
+ return `Uploaded chunks remain stored for ${uploadId}; retry complete and do not abort the session.`;
215307
+ }
215308
+ function annotateHttpChunkedCompleteFailure(uploadId, error) {
215309
+ const hint = httpChunkedCompleteRetryHint(uploadId);
215310
+ if (error instanceof Error) {
215311
+ if (!error.message.includes("retry complete")) {
215312
+ error.message = `${error.message} ${hint}`;
215313
+ }
215314
+ return error;
215315
+ }
215316
+ return new Error(`${String(error)} ${hint}`);
215317
+ }
215318
+
215319
+ class ChunkUploadHttpError extends Error {
215320
+ status;
215321
+ constructor(status) {
215322
+ super(`Chunk upload failed (${status})`);
215323
+ this.status = status;
215324
+ this.name = "ChunkUploadHttpError";
215325
+ }
215326
+ }
215327
+ function isRetryableChunkError(error, signal) {
215328
+ if (signal?.aborted)
215329
+ return false;
215330
+ if (isAbortError(error))
215331
+ return false;
215332
+ if (error instanceof ChunkUploadHttpError)
215333
+ return isTransientHttpStatus(error.status);
215334
+ return true;
215335
+ }
215336
+ function abortError2(signal) {
215337
+ if (signal?.reason instanceof Error)
215338
+ return signal.reason;
215339
+ return typeof DOMException !== "undefined" ? new DOMException("Upload aborted", "AbortError") : Object.assign(new Error("Upload aborted"), { name: "AbortError" });
215340
+ }
215341
+ async function uploadHttpChunks(options) {
215342
+ let uploadedBytes = 0;
215343
+ for (let chunkIndex = 0;chunkIndex < options.chunkCount; chunkIndex++) {
215344
+ if (options.signal?.aborted)
215345
+ throw abortError2(options.signal);
215346
+ const length = expectedHttpChunkByteLength(options.totalSize, options.chunkSizeBytes, chunkIndex, options.chunkCount);
215347
+ const start = chunkByteOffset(options.chunkSizeBytes, chunkIndex);
215348
+ let lastError;
215349
+ for (let attempt = 0;attempt <= HTTP_CHUNKED_MAX_RETRIES; attempt++) {
215350
+ if (options.signal?.aborted)
215351
+ throw abortError2(options.signal);
215352
+ try {
215353
+ await options.putChunk({ chunkIndex, start, length });
215354
+ uploadedBytes += length;
215355
+ options.onProgress?.(uploadedBytes, options.totalSize);
215356
+ lastError = undefined;
215357
+ break;
215358
+ } catch (error) {
215359
+ lastError = error;
215360
+ if (!isRetryableChunkError(error, options.signal) || attempt === HTTP_CHUNKED_MAX_RETRIES) {
215361
+ throw error;
215362
+ }
215363
+ await sleep(HTTP_CHUNKED_RETRY_BASE_MS * 2 ** attempt, options.signal);
215364
+ }
215365
+ }
215366
+ if (lastError)
215367
+ throw lastError;
215368
+ }
215369
+ }
215370
+ // ../sdk-typescript/src/lib/upload-limits.ts
215371
+ var DEFAULT_MULTIPART_MAX_BYTES = Math.floor(4.5 * 1024 * 1024);
215372
+ var MULTIPART_ENVELOPE_HEADROOM_BYTES = 256 * 1024;
215373
+ function multipartFileByteBudget(multipartMaxBytes = DEFAULT_MULTIPART_MAX_BYTES) {
215374
+ if (multipartMaxBytes === null)
215375
+ return null;
215376
+ return Math.max(0, multipartMaxBytes - MULTIPART_ENVELOPE_HEADROOM_BYTES);
215377
+ }
215378
+ function indicesRequiringPreUpload(files, multipartMaxBytes = DEFAULT_MULTIPART_MAX_BYTES) {
215379
+ const budget = multipartFileByteBudget(multipartMaxBytes);
215380
+ const toPreUpload = new Set;
215381
+ if (budget === null)
215382
+ return toPreUpload;
215383
+ files.forEach((file, index) => {
215384
+ if (file.size > budget)
215385
+ toPreUpload.add(index);
215386
+ });
215387
+ let multipartTotal = 0;
215388
+ files.forEach((file, index) => {
215389
+ if (!toPreUpload.has(index))
215390
+ multipartTotal += file.size;
215391
+ });
215392
+ const candidates = files.map((file, index) => ({ size: file.size, index })).filter(({ index }) => !toPreUpload.has(index)).sort((a, b) => b.size - a.size || a.index - b.index);
215393
+ for (const { size, index } of candidates) {
215394
+ if (multipartTotal <= budget)
215395
+ break;
215396
+ toPreUpload.add(index);
215397
+ multipartTotal -= size;
215398
+ }
215399
+ return toPreUpload;
215400
+ }
215401
+ // src/lib/api-paths.ts
215402
+ var API_PREFIX = "/v1";
215403
+ function apiPath(suffix) {
215404
+ if (suffix === "/v1" || suffix.startsWith("/v1/"))
215405
+ return suffix;
215406
+ if (suffix === "/api/v1" || suffix.startsWith("/api/v1/")) {
215407
+ return `${API_PREFIX}${suffix.slice("/api/v1".length)}`;
215408
+ }
215409
+ const normalized = suffix.startsWith("/") ? suffix : `/${suffix}`;
215410
+ return `${API_PREFIX}${normalized}`;
215411
+ }
215412
+ function canonicalApiPath(path) {
215413
+ if (path === "/api/v1" || path.startsWith("/api/v1/")) {
215414
+ return `${API_PREFIX}${path.slice("/api/v1".length)}`;
215415
+ }
215416
+ return path;
215417
+ }
215418
+ function parseBaseUrl(baseUrl) {
215419
+ return new URL(baseUrl.match(/^https?:\/\//i) ? baseUrl : `https://${baseUrl}`);
215420
+ }
215421
+ function endsWithApiPrefix(basePath) {
215422
+ return basePath === "/api" || basePath.endsWith("/api");
215423
+ }
215424
+ function endsWithApiV1Prefix(basePath) {
215425
+ return basePath === "/api/v1" || basePath.endsWith("/api/v1");
215426
+ }
215427
+ function resolveRequestUrl(baseUrl, path) {
215428
+ if (/^https?:\/\//i.test(path))
215429
+ return path;
215430
+ const requestPath = canonicalApiPath(path);
215431
+ const isCanonicalV1 = requestPath === API_PREFIX || requestPath.startsWith(`${API_PREFIX}/`);
215432
+ const base = parseBaseUrl(baseUrl);
215433
+ const basePath = base.pathname.replace(/\/+$/, "");
215434
+ if (isCanonicalV1) {
215435
+ if (endsWithApiV1Prefix(basePath)) {
215436
+ const suffix = requestPath === API_PREFIX ? "" : requestPath.slice(API_PREFIX.length);
215437
+ return `${base.origin}${basePath}${suffix}`;
215438
+ }
215439
+ if (endsWithApiPrefix(basePath)) {
215440
+ return `${base.origin}${basePath}${requestPath}`;
215441
+ }
215442
+ return `${base.origin}${requestPath}`;
215443
+ }
215444
+ if (requestPath.startsWith("/api/") && (endsWithApiPrefix(basePath) || endsWithApiV1Prefix(basePath))) {
215445
+ return `${base.origin}${requestPath}`;
215446
+ }
215447
+ if (!basePath)
215448
+ return `${base.origin}${requestPath}`;
215449
+ return `${base.origin}${basePath}${requestPath}`;
215450
+ }
215451
+
215189
215452
  // ../../node_modules/@t3-oss/env-core/dist/standard.js
215190
215453
  function ensureSynchronous(value, message) {
215191
215454
  if (value instanceof Promise)
@@ -215507,6 +215770,9 @@ function addJsonFlag(cmd) {
215507
215770
  function withBaseUrl(cmd) {
215508
215771
  return cmd.option("--base-url <url>", "Server base URL");
215509
215772
  }
215773
+ function printJson(value) {
215774
+ console.log(JSON.stringify(value, null, 2));
215775
+ }
215510
215776
  function intArg(value) {
215511
215777
  if (!/^-?\d+$/.test(value)) {
215512
215778
  throw new InvalidArgumentError("Expected a whole number");
@@ -215591,80 +215857,10 @@ function requireApiKey(config) {
215591
215857
  }
215592
215858
  return config.apiKey;
215593
215859
  }
215594
-
215595
- // src/lib/api-paths.ts
215596
- var API_PREFIX = "/v1";
215597
- function apiPath(suffix) {
215598
- if (suffix === "/v1" || suffix.startsWith("/v1/"))
215599
- return suffix;
215600
- if (suffix === "/api/v1" || suffix.startsWith("/api/v1/")) {
215601
- return `${API_PREFIX}${suffix.slice("/api/v1".length)}`;
215602
- }
215603
- const normalized = suffix.startsWith("/") ? suffix : `/${suffix}`;
215604
- return `${API_PREFIX}${normalized}`;
215605
- }
215606
- function canonicalApiPath(path) {
215607
- if (path === "/api/v1" || path.startsWith("/api/v1/")) {
215608
- return `${API_PREFIX}${path.slice("/api/v1".length)}`;
215609
- }
215610
- return path;
215611
- }
215612
- function parseBaseUrl(baseUrl) {
215613
- return new URL(baseUrl.match(/^https?:\/\//i) ? baseUrl : `https://${baseUrl}`);
215614
- }
215615
- function endsWithApiPrefix(basePath) {
215616
- return basePath === "/api" || basePath.endsWith("/api");
215617
- }
215618
- function endsWithApiV1Prefix(basePath) {
215619
- return basePath === "/api/v1" || basePath.endsWith("/api/v1");
215620
- }
215621
- function resolveRequestUrl(baseUrl, path) {
215622
- if (/^https?:\/\//i.test(path))
215623
- return path;
215624
- const requestPath = canonicalApiPath(path);
215625
- const isCanonicalV1 = requestPath === API_PREFIX || requestPath.startsWith(`${API_PREFIX}/`);
215626
- const base = parseBaseUrl(baseUrl);
215627
- const basePath = base.pathname.replace(/\/+$/, "");
215628
- if (isCanonicalV1) {
215629
- if (endsWithApiV1Prefix(basePath)) {
215630
- const suffix = requestPath === API_PREFIX ? "" : requestPath.slice(API_PREFIX.length);
215631
- return `${base.origin}${basePath}${suffix}`;
215632
- }
215633
- if (endsWithApiPrefix(basePath)) {
215634
- return `${base.origin}${basePath}${requestPath}`;
215635
- }
215636
- return `${base.origin}${requestPath}`;
215637
- }
215638
- if (requestPath.startsWith("/api/") && (endsWithApiPrefix(basePath) || endsWithApiV1Prefix(basePath))) {
215639
- return `${base.origin}${requestPath}`;
215640
- }
215641
- if (!basePath)
215642
- return `${base.origin}${requestPath}`;
215643
- return `${base.origin}${basePath}${requestPath}`;
215644
- }
215645
-
215646
- // src/lib/fetch-body.ts
215647
- function isNodeReadableStream(body) {
215648
- return typeof body.pipe === "function";
215649
- }
215650
- function byteViewToArrayBuffer(view) {
215651
- if (view.buffer instanceof ArrayBuffer && view.byteOffset === 0 && view.byteLength === view.buffer.byteLength) {
215652
- return view.buffer;
215653
- }
215654
- const copy = new Uint8Array(view.byteLength);
215655
- copy.set(view);
215656
- return copy.buffer;
215657
- }
215658
- function toPutBody(body) {
215659
- if (isNodeReadableStream(body)) {
215660
- return body;
215661
- }
215662
- return byteViewToArrayBuffer(body);
215663
- }
215664
215860
  // package.json
215665
215861
  var package_default = {
215666
215862
  name: "@eigenpal/cli",
215667
- version: "0.23.6",
215863
+ version: "0.23.7",
215668
215864
  description: "Eigenpal CLI — author and run document workflows from your terminal. Agent-ready.",
215669
215865
  keywords: [
215670
215866
  "eigenpal",
@@ -215728,6 +215924,7 @@ var package_default = {
215728
215924
  },
215729
215925
  devDependencies: {
215730
215926
  "@eigenpal/common": "workspace:*",
215927
+ "@eigenpal/sdk": "workspace:*",
215731
215928
  "@eigenpal/types": "workspace:*",
215732
215929
  "@eigenpal/workflow-yaml": "workspace:*",
215733
215930
  "@t3-oss/env-core": "^0.13.11",
@@ -215767,14 +215964,21 @@ class ApiError extends Error {
215767
215964
  body;
215768
215965
  retryAfterSeconds;
215769
215966
  constructor(status, body, retryAfterSeconds) {
215770
- const msg = typeof body === "object" && body !== null && "error" in body ? body.error : `HTTP ${status}`;
215771
- super(msg);
215967
+ super(apiErrorMessage(status, body));
215772
215968
  this.status = status;
215773
215969
  this.body = body;
215774
215970
  this.retryAfterSeconds = retryAfterSeconds;
215775
215971
  this.name = "ApiError";
215776
215972
  }
215777
215973
  }
215974
+ function apiErrorMessage(status, body) {
215975
+ if (typeof body !== "object" || body === null)
215976
+ return `HTTP ${status}`;
215977
+ const envelope = body;
215978
+ const firstIssue = Array.isArray(envelope.issues) ? envelope.issues[0] : undefined;
215979
+ const base = typeof firstIssue?.message === "string" && firstIssue.message.length > 0 ? firstIssue.message : typeof envelope.error === "string" && envelope.error.length > 0 ? envelope.error : `HTTP ${status}`;
215980
+ return typeof envelope.requestId === "string" && envelope.requestId.length > 0 ? `${base} (request id: ${envelope.requestId})` : base;
215981
+ }
215778
215982
 
215779
215983
  class HtmlResponseError extends Error {
215780
215984
  resolvedUrl;
@@ -215982,6 +216186,11 @@ class ApiClient {
215982
216186
  return res;
215983
216187
  }
215984
216188
  }
216189
+ function buildClient(opts) {
216190
+ const config = resolveConfig(opts);
216191
+ requireApiKey(config);
216192
+ return new ApiClient(config);
216193
+ }
215985
216194
 
215986
216195
  // src/lib/format-error.ts
215987
216196
  var CONNECTION_FAILURE_TOKENS = [
@@ -216085,13 +216294,23 @@ function printApiError(err, context) {
216085
216294
  }
216086
216295
  error2(formatCliError(err, context));
216087
216296
  }
216297
+
216298
+ class UsageError extends Error {
216299
+ constructor(message) {
216300
+ super(message);
216301
+ this.name = "UsageError";
216302
+ }
216303
+ }
216304
+ function exitCodeForError(err) {
216305
+ return err instanceof UsageError || err instanceof InvalidArgumentError ? 2 : 1;
216306
+ }
216088
216307
  function action(body) {
216089
216308
  return async (...args) => {
216090
216309
  try {
216091
216310
  await body(...args);
216092
216311
  } catch (err) {
216093
216312
  printApiError(err, { baseUrl: resolveBaseUrlFromActionArgs(args) });
216094
- process.exit(1);
216313
+ process.exit(exitCodeForError(err));
216095
216314
  }
216096
216315
  };
216097
216316
  }
@@ -216120,7 +216339,7 @@ function nonInteractiveYesRequired(action) {
216120
216339
  function requireYesInNonInteractive(yes, action) {
216121
216340
  if (yes || isInteractiveStderr())
216122
216341
  return;
216123
- throw new Error(nonInteractiveYesRequired(action));
216342
+ throw new UsageError(nonInteractiveYesRequired(action));
216124
216343
  }
216125
216344
  async function confirmTyped(id, actionName) {
216126
216345
  if (!isInteractiveStderr())
@@ -216139,7 +216358,7 @@ async function requireTypedConfirmation(opts) {
216139
216358
  if (opts.yes)
216140
216359
  return;
216141
216360
  if (!isInteractiveStderr()) {
216142
- throw new Error(nonInteractiveYesRequired(`Typed confirmation to ${opts.actionName}`));
216361
+ throw new UsageError(nonInteractiveYesRequired(`Typed confirmation to ${opts.actionName}`));
216143
216362
  }
216144
216363
  const ok = await confirmTyped(opts.id, opts.actionName);
216145
216364
  if (!ok) {
@@ -216836,7 +217055,7 @@ async function readPackageManifest(packageRoot, config) {
216836
217055
  function requirePackageContext(opts = {}) {
216837
217056
  const context = resolveGitSourceContext(opts);
216838
217057
  if (!context.gitRoot || !context.packageRoot || !context.packagePath) {
216839
- throw new Error("Run this command inside a source package, or pass --dir.");
217058
+ throw new UsageError("Run this command inside a source package, or pass --dir.");
216840
217059
  }
216841
217060
  return {
216842
217061
  gitRoot: context.gitRoot,
@@ -217508,7 +217727,7 @@ function writeSecretsFile(packageRoot, value) {
217508
217727
  async function readSecretInput(opts) {
217509
217728
  const selected = [opts.stdin, opts.valueFile].filter(Boolean).length;
217510
217729
  if (selected > 1)
217511
- throw new Error("Pass only one of --stdin or --value-file.");
217730
+ throw new UsageError("Pass only one of --stdin or --value-file.");
217512
217731
  if (opts.stdin)
217513
217732
  return readFileSync6(0, "utf8").replace(/\n$/, "");
217514
217733
  if (opts.valueFile)
@@ -217735,7 +217954,8 @@ function hostedArchiveRequest(input) {
217735
217954
  if (!match)
217736
217955
  return null;
217737
217956
  const [, baseUrl, gitRepositoryPath] = match;
217738
- return `${baseUrl}/export/orgs/${encodeURIComponent(gitRepositoryPath)}/${encodeURIComponent(input.ref)}/${input.packagePath}`;
217957
+ const packagePath = input.packagePath.split("/").map(encodeURIComponent).join("/");
217958
+ return `${baseUrl}/export/orgs/${encodeURIComponent(gitRepositoryPath)}/${encodeURIComponent(input.ref)}/${packagePath}`;
217739
217959
  }
217740
217960
  async function resolvePackageRef(input) {
217741
217961
  if (input.ref === "main" || /^[0-9a-f]{40}$/.test(input.ref)) {
@@ -217808,6 +218028,9 @@ async function tryHostedArchive(input) {
217808
218028
  authorization: `Bearer ${requireApiKey(input.config)}`
217809
218029
  }
217810
218030
  }).catch(() => null);
218031
+ if (response?.status === 401 || response?.status === 403) {
218032
+ throw new Error(`The API key cannot export this agent source (HTTP ${response.status}). Check its access, or run from a clone.`);
218033
+ }
217811
218034
  if (!response?.ok)
217812
218035
  return false;
217813
218036
  rmSync(input.outDir, { recursive: true, force: true });
@@ -218115,7 +218338,7 @@ async function cloneSource(opts) {
218115
218338
  success(`Cloned ${repo.remoteUrl}`);
218116
218339
  }
218117
218340
  async function show(target, opts) {
218118
- const client = new ApiClient(resolveConfig(opts));
218341
+ const client = buildClient(opts);
218119
218342
  const automation = await getPublicAgentAutomation(client, target);
218120
218343
  if (opts.json)
218121
218344
  console.log(JSON.stringify(automation, null, 2));
@@ -218151,7 +218374,7 @@ description: ${automation.description}`);
218151
218374
  }
218152
218375
  async function versions2(target, opts) {
218153
218376
  const packagePath = resolvePackagePath(target);
218154
- const client = new ApiClient(resolveConfig(opts));
218377
+ const client = buildClient(opts);
218155
218378
  const parsed = ReleasesSchema.parse(await client.get("/v1/source/releases", { packagePath }));
218156
218379
  const sorted = { ...parsed, releases: sortReleasesNewestFirst(parsed.releases) };
218157
218380
  if (opts.json)
@@ -218265,7 +218488,7 @@ async function sync(target, opts) {
218265
218488
  if (!isAutomationPackagePath(packagePath)) {
218266
218489
  throw new Error("Sync only supports agent and workflow packages.");
218267
218490
  }
218268
- await syncLatestAutomation(new ApiClient(resolveConfig(opts)), packagePath);
218491
+ await syncLatestAutomation(buildClient(opts), packagePath);
218269
218492
  }
218270
218493
  function localPackageInputHash(context, dependencies = []) {
218271
218494
  const typed = /^(agents|resources)\//.test(context.packagePath);
@@ -218526,14 +218749,6 @@ function registerGitCommands(program) {
218526
218749
  }
218527
218750
 
218528
218751
  // src/commands/workflow/lifecycle-shared.ts
218529
- function buildClient(opts) {
218530
- const config = resolveConfig(opts);
218531
- requireApiKey(config);
218532
- return new ApiClient(config);
218533
- }
218534
- function printJson(value) {
218535
- console.log(JSON.stringify(value, null, 2));
218536
- }
218537
218752
  async function fetchAutomation(client, automationId) {
218538
218753
  return await client.get(`/v1/automations/${encodeURIComponent(automationId)}`);
218539
218754
  }
@@ -219190,145 +219405,13 @@ function zipSync(data, opts) {
219190
219405
  }
219191
219406
 
219192
219407
  // src/commands/agents/dataset.ts
219193
- import { existsSync as existsSync9, promises as fs4 } from "node:fs";
219408
+ import { existsSync as existsSync8, promises as fs4 } from "node:fs";
219194
219409
  import path10 from "node:path";
219195
219410
 
219196
219411
  // src/commands/dataset-review-request.ts
219197
219412
  import { mkdir, readFile as readFile2, stat, writeFile as writeFile2 } from "node:fs/promises";
219198
219413
  import { basename, dirname as dirname2, isAbsolute, join as join2, relative, resolve } from "node:path";
219199
219414
 
219200
- // src/commands/agents/shared.ts
219201
- init_src();
219202
- import { existsSync as existsSync7, promises as fs2 } from "node:fs";
219203
- import path8 from "node:path";
219204
- var DATASET_DIR = "dataset";
219205
- var AGENT_EXAMPLE_INPUT_JSON = "input.json";
219206
- var AGENT_EXAMPLE_EXPECTED_JSON = "expected.json";
219207
- var LEGACY_LAYOUTS = [
219208
- ["workflow", "agent"],
219209
- ["eval", "dataset"]
219210
- ];
219211
- function collectRepeated(value, previous = []) {
219212
- return [...previous, value];
219213
- }
219214
- function agentAutomationId(value) {
219215
- if (value.startsWith("agents.") || value.startsWith("workflows."))
219216
- return value;
219217
- if (value.includes("_"))
219218
- return value;
219219
- return `agents.${value}`;
219220
- }
219221
- function buildClient2(opts) {
219222
- const config = resolveConfig(opts);
219223
- requireApiKey(config);
219224
- return new ApiClient(config);
219225
- }
219226
- async function writeBase64File(file, contentBase64) {
219227
- await fs2.mkdir(path8.dirname(file), { recursive: true });
219228
- await fs2.writeFile(file, Buffer.from(contentBase64, "base64"));
219229
- }
219230
- async function pollRun(client, executionId, interval, maxWait, json = false) {
219231
- const started = Date.now();
219232
- const base = `/v1/runs/${encodeURIComponent(executionId)}`;
219233
- for (;; ) {
219234
- const payload = await client.get(`${base}?expand=execution`);
219235
- const status = payload.execution?.status;
219236
- if (payload.finished || isTerminalExecutionStatus(status)) {
219237
- return await client.get(`${base}?expand=usage,execution`);
219238
- }
219239
- if (Date.now() - started > maxWait * 1000) {
219240
- if (json)
219241
- printJson2(payload);
219242
- process.stderr.write(`Timed out waiting for run ${executionId}
219243
- `);
219244
- process.exit(2);
219245
- }
219246
- await new Promise((resolve) => setTimeout(resolve, interval * 1000));
219247
- }
219248
- }
219249
- async function pollExperiment(client, automationId, batchId, interval, maxWait, json = false) {
219250
- const started = Date.now();
219251
- let notFoundRetries = 0;
219252
- let lastPayload;
219253
- for (;; ) {
219254
- let payload;
219255
- try {
219256
- payload = await client.get(`/v1/automations/${encodeURIComponent(automationId)}/experiments/${encodeURIComponent(batchId)}`);
219257
- lastPayload = payload;
219258
- } catch (error) {
219259
- if (!(error instanceof ApiError) || error.status !== 404 || notFoundRetries >= 2)
219260
- throw error;
219261
- notFoundRetries++;
219262
- await new Promise((resolve) => setTimeout(resolve, interval * 1000));
219263
- continue;
219264
- }
219265
- if (payload.status === "completed")
219266
- return payload;
219267
- if (Date.now() - started > maxWait * 1000) {
219268
- if (json)
219269
- printJson2(lastPayload ?? { batchId, status: "pending" });
219270
- process.stderr.write(`Timed out waiting for experiment ${batchId}
219271
- `);
219272
- process.exit(2);
219273
- }
219274
- await new Promise((resolve) => setTimeout(resolve, interval * 1000));
219275
- }
219276
- }
219277
- function renderRunPayload(payload, opts) {
219278
- if (opts.json)
219279
- return printJson2(payload);
219280
- const run = payload;
219281
- if (!run || run.id === undefined)
219282
- return printJson2(payload);
219283
- const status = run.execution?.status ?? (run.finished === true ? "completed" : "running");
219284
- success(`Run ${run.id} is ${status}`);
219285
- }
219286
- function setExitCodeForFailedTerminalRun(payload) {
219287
- const run = payload;
219288
- const status = run?.execution?.status;
219289
- if (status === "failed" || status === "cancelled" || status === "rejected" || run?.finished === true && run?.error) {
219290
- process.exitCode = 1;
219291
- }
219292
- }
219293
- function renderGeneric(payload, opts, message) {
219294
- if (opts.json)
219295
- return printJson2(payload);
219296
- success(message);
219297
- }
219298
- function compactParams(opts) {
219299
- const params = {};
219300
- for (const [key, value] of Object.entries(opts)) {
219301
- if (value === undefined || value === null || key === "json" || key === "baseUrl" || key === "yes" || key === "compact")
219302
- continue;
219303
- params[key] = String(value);
219304
- }
219305
- return params;
219306
- }
219307
- function printJson2(value) {
219308
- console.log(JSON.stringify(value, null, 2));
219309
- }
219310
- function parseDatasetMode(value) {
219311
- if (value === "append" || value === "replace")
219312
- return value;
219313
- throw new InvalidArgumentError("mode must be append or replace");
219314
- }
219315
- function parseResultsFormat(value) {
219316
- if (value === "csv" || value === "json")
219317
- return value;
219318
- throw new InvalidArgumentError("format must be csv or json");
219319
- }
219320
- function toCsv(rows, columns) {
219321
- const escape = (value) => {
219322
- const text = value == null ? "" : String(value);
219323
- return /[",\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
219324
- };
219325
- return [
219326
- columns.join(","),
219327
- ...rows.map((row) => columns.map((column) => escape(row[column])).join(","))
219328
- ].join(`
219329
- `);
219330
- }
219331
-
219332
219415
  // src/commands/dataset-review-request-briefing.ts
219333
219416
  function splitOnce(value, separator) {
219334
219417
  const index = value.indexOf(separator);
@@ -219340,11 +219423,11 @@ function parseFocusReasonFlag(value) {
219340
219423
  const [path, reason] = splitOnce(value, "=");
219341
219424
  const trimmedPath = path.trim();
219342
219425
  if (!trimmedPath) {
219343
- throw new Error("--focus-reason requires path=reason");
219426
+ throw new UsageError("--focus-reason requires path=reason");
219344
219427
  }
219345
219428
  const trimmedReason = reason?.trim();
219346
219429
  if (!trimmedReason) {
219347
- throw new Error("--focus-reason requires path=reason");
219430
+ throw new UsageError("--focus-reason requires path=reason");
219348
219431
  }
219349
219432
  return { path: trimmedPath, reason: trimmedReason };
219350
219433
  }
@@ -219353,7 +219436,7 @@ function parseItemNoteFlag(value) {
219353
219436
  const trimmedName = exampleName.trim();
219354
219437
  const trimmedComment = comment?.trim();
219355
219438
  if (!trimmedName || !trimmedComment) {
219356
- throw new Error("--item-note requires exampleName=comment");
219439
+ throw new UsageError("--item-note requires exampleName=comment");
219357
219440
  }
219358
219441
  return { exampleName: trimmedName, comment: trimmedComment };
219359
219442
  }
@@ -219364,7 +219447,7 @@ function parseFieldNoteFlag(value) {
219364
219447
  const exampleName = (dot < 0 ? left : left.slice(0, dot)).trim();
219365
219448
  const path = (dot < 0 ? "" : left.slice(dot + 1)).trim();
219366
219449
  if (!exampleName || !path || !trimmedComment) {
219367
- throw new Error("--field-note requires exampleName.path=comment");
219450
+ throw new UsageError("--field-note requires exampleName.path=comment");
219368
219451
  }
219369
219452
  return { exampleName, fields: [{ path, comment: trimmedComment }] };
219370
219453
  }
@@ -219431,12 +219514,12 @@ function formatProgress(progress) {
219431
219514
  function parseApprovalDecision(opts, action) {
219432
219515
  if (opts.clear) {
219433
219516
  if (opts.decision !== undefined) {
219434
- throw new Error("pass either --clear or --decision, not both");
219517
+ throw new UsageError("pass either --clear or --decision, not both");
219435
219518
  }
219436
219519
  return null;
219437
219520
  }
219438
219521
  if (opts.decision === undefined) {
219439
- throw new Error(`--decision or --clear is required when --action ${action}`);
219522
+ throw new UsageError(`--decision or --clear is required when --action ${action}`);
219440
219523
  }
219441
219524
  const normalized = opts.decision.trim().toLowerCase();
219442
219525
  if (normalized === "null" || normalized === "clear") {
@@ -219445,7 +219528,7 @@ function parseApprovalDecision(opts, action) {
219445
219528
  if (normalized === "approved" || normalized === "removed") {
219446
219529
  return normalized;
219447
219530
  }
219448
- throw new Error("--decision must be approved, removed, null, or clear");
219531
+ throw new UsageError("--decision must be approved, removed, null, or clear");
219449
219532
  }
219450
219533
  function parseFieldDecision(opts) {
219451
219534
  return parseApprovalDecision(opts, "field-decision");
@@ -219466,15 +219549,15 @@ function buildReviewItemPatchBody(action, opts) {
219466
219549
  body.filePath = opts.filePath;
219467
219550
  if (action === "edit") {
219468
219551
  if (opts.expectedJson === undefined) {
219469
- throw new Error("--expected-json is required when --action edit");
219552
+ throw new UsageError("--expected-json is required when --action edit");
219470
219553
  }
219471
219554
  body.expected = parseJsonObjectFlag(opts.expectedJson, "--expected-json");
219472
219555
  } else if (opts.expectedJson !== undefined) {
219473
- throw new Error("--expected-json is only valid with --action edit");
219556
+ throw new UsageError("--expected-json is only valid with --action edit");
219474
219557
  }
219475
219558
  if (action === "field-decision") {
219476
219559
  if (!opts.fieldPath?.trim()) {
219477
- throw new Error("--field-path is required when --action field-decision");
219560
+ throw new UsageError("--field-path is required when --action field-decision");
219478
219561
  }
219479
219562
  body.decision = parseFieldDecision({ decision: opts.decision, clear: opts.clear });
219480
219563
  } else if (opts.decision !== undefined || opts.clear) {
@@ -219484,13 +219567,13 @@ function buildReviewItemPatchBody(action, opts) {
219484
219567
  }
219485
219568
  if (action === "file-decision") {
219486
219569
  if (!opts.filePath?.trim()) {
219487
- throw new Error("--file-path is required when --action file-decision");
219570
+ throw new UsageError("--file-path is required when --action file-decision");
219488
219571
  }
219489
219572
  if (opts.fieldPath !== undefined) {
219490
- throw new Error("--field-path is only valid with --action comment or field-decision");
219573
+ throw new UsageError("--field-path is only valid with --action comment or field-decision");
219491
219574
  }
219492
219575
  if (opts.newPath !== undefined || opts.file !== undefined) {
219493
- throw new Error("--new-path / --file are only valid with --action edit-file");
219576
+ throw new UsageError("--new-path / --file are only valid with --action edit-file");
219494
219577
  }
219495
219578
  if (opts.decision !== undefined || opts.clear) {
219496
219579
  body.decision = parseFileDecision({ decision: opts.decision, clear: opts.clear });
@@ -219514,7 +219597,7 @@ function buildReviewItemFileFields(opts) {
219514
219597
  throw new Error("pass exactly one of --file-path (correct an existing expected file) or --new-path (upload a brand-new expected file) when --action edit-file");
219515
219598
  }
219516
219599
  if (!opts.file?.trim()) {
219517
- throw new Error("--file <local path> is required when --action edit-file");
219600
+ throw new UsageError("--file <local path> is required when --action edit-file");
219518
219601
  }
219519
219602
  return {
219520
219603
  ...hasFilePath ? { filePath: opts.filePath.trim() } : {},
@@ -219626,13 +219709,13 @@ design; reviewers can err) → \`update --status closed\`.
219626
219709
  Use \`--json\` from agents; API errors exit non-zero.
219627
219710
  `).action(action(async (automationRef, opts) => {
219628
219711
  if (opts.exampleName.length === 0) {
219629
- throw new Error("pass at least one --example-name");
219712
+ throw new UsageError("pass at least one --example-name");
219630
219713
  }
219631
219714
  const { client, automationId } = await resolveAutomation(automationRef, opts);
219632
219715
  const focusFromFlags = mergeFocusFields(opts.focus ?? [], (opts.focusReason ?? []).map(parseFocusReasonFlag));
219633
219716
  const focusFromJson = opts.focusJson ? parseJsonObjectFlag(opts.focusJson, "--focus-json") : [];
219634
219717
  if (opts.focusJson && !Array.isArray(focusFromJson)) {
219635
- throw new Error("--focus-json must be a JSON array");
219718
+ throw new UsageError("--focus-json must be a JSON array");
219636
219719
  }
219637
219720
  const notesFromFlags = mergeItemNotes([
219638
219721
  ...(opts.itemNote ?? []).map(parseItemNoteFlag),
@@ -219640,7 +219723,7 @@ Use \`--json\` from agents; API errors exit non-zero.
219640
219723
  ]);
219641
219724
  const notesFromJson = opts.notesJson ? parseJsonObjectFlag(opts.notesJson, "--notes-json") : [];
219642
219725
  if (opts.notesJson && !Array.isArray(notesFromJson)) {
219643
- throw new Error("--notes-json must be a JSON array");
219726
+ throw new UsageError("--notes-json must be a JSON array");
219644
219727
  }
219645
219728
  const body = {
219646
219729
  title: opts.title,
@@ -219663,7 +219746,7 @@ Use \`--json\` from agents; API errors exit non-zero.
219663
219746
  body.itemNotes = itemNotes;
219664
219747
  const payload = await client.post(datasetReviewRequestsPath(automationId), body);
219665
219748
  if (opts.json)
219666
- return printJson2(payload);
219749
+ return printJson(payload);
219667
219750
  const created = payload;
219668
219751
  success(`Created review request ${ui.bold(created.id ?? "(unknown id)")}` + (created.status ? ` ${ui.dim(`(${created.status})`)}` : ""));
219669
219752
  }));
@@ -219671,7 +219754,7 @@ Use \`--json\` from agents; API errors exit non-zero.
219671
219754
  const { client, automationId } = await resolveAutomation(automationRef, opts);
219672
219755
  const payload = await client.get(datasetReviewRequestsPath(automationId, reviewId));
219673
219756
  if (opts.json)
219674
- return printJson2(payload);
219757
+ return printJson(payload);
219675
219758
  const detail = payload;
219676
219759
  console.log(table([
219677
219760
  { field: "id", value: detail.id },
@@ -219731,7 +219814,7 @@ the request (frozen like closed, reopenable with \`--status open\`).
219731
219814
  const focusFromFlags = mergeFocusFields(opts.focus ?? [], (opts.focusReason ?? []).map(parseFocusReasonFlag));
219732
219815
  const focusFromJson = opts.focusJson ? parseJsonObjectFlag(opts.focusJson, "--focus-json") : [];
219733
219816
  if (opts.focusJson && !Array.isArray(focusFromJson)) {
219734
- throw new Error("--focus-json must be a JSON array");
219817
+ throw new UsageError("--focus-json must be a JSON array");
219735
219818
  }
219736
219819
  body.focusFields = [...focusFromFlags, ...focusFromJson];
219737
219820
  }
@@ -219746,7 +219829,7 @@ the request (frozen like closed, reopenable with \`--status open\`).
219746
219829
  const { client, automationId } = await resolveAutomation(automationRef, opts);
219747
219830
  const payload = await client.patch(datasetReviewRequestsPath(automationId, reviewId), body);
219748
219831
  if (opts.json)
219749
- return printJson2(payload);
219832
+ return printJson(payload);
219750
219833
  const updated = payload;
219751
219834
  success(`Updated review request ${ui.bold(updated.id ?? reviewId)}` + (updated.status ? ` ${ui.dim(`(${updated.status})`)}` : ""));
219752
219835
  }));
@@ -219757,7 +219840,7 @@ the request (frozen like closed, reopenable with \`--status open\`).
219757
219840
  params.status = opts.status;
219758
219841
  const payload = await client.get(datasetReviewRequestItemsPath(automationId, reviewId), params);
219759
219842
  if (opts.json)
219760
- return printJson2(payload);
219843
+ return printJson(payload);
219761
219844
  const items = payload.items ?? [];
219762
219845
  console.log(table(items.map((item) => ({
219763
219846
  exampleName: item.exampleName,
@@ -219775,7 +219858,7 @@ the request (frozen like closed, reopenable with \`--status open\`).
219775
219858
  const { client, automationId } = await resolveAutomation(automationRef, opts);
219776
219859
  const payload = await client.get(datasetReviewRequestEventsPath(automationId, reviewId));
219777
219860
  if (opts.json)
219778
- return printJson2(payload);
219861
+ return printJson(payload);
219779
219862
  const events = payload.events ?? [];
219780
219863
  console.log(table(events.map((event) => ({
219781
219864
  action: event.action,
@@ -219834,7 +219917,7 @@ Always pass \`--expected-updated-at\` from the item payload you last observed.
219834
219917
  const localPath = resolve(opts.file.trim());
219835
219918
  const fileStat = await stat(localPath);
219836
219919
  if (!fileStat.isFile()) {
219837
- throw new Error(`--file is not a file: ${localPath}`);
219920
+ throw new UsageError(`--file is not a file: ${localPath}`);
219838
219921
  }
219839
219922
  if (fileStat.size > REVIEW_EDIT_FILE_MAX_BYTES) {
219840
219923
  throw new Error(`--file ${localPath} is ${(fileStat.size / 1024 / 1024).toFixed(1)}MB; the edit-file cap is 50MB`);
@@ -219852,7 +219935,7 @@ Always pass \`--expected-updated-at\` from the item payload you last observed.
219852
219935
  form.set("expectedUpdatedAt", fields.expectedUpdatedAt);
219853
219936
  const payload = await client.patchFormData(itemPath, form);
219854
219937
  if (opts.json)
219855
- return printJson2(payload);
219938
+ return printJson(payload);
219856
219939
  const item = payload.item;
219857
219940
  success(`Updated ${ui.bold(item?.exampleName ?? itemId)}` + (item?.status ? ` ${ui.dim(`(${item.status})`)}` : ""));
219858
219941
  return;
@@ -219870,7 +219953,7 @@ Always pass \`--expected-updated-at\` from the item payload you last observed.
219870
219953
  });
219871
219954
  const payload = await client.patch(itemPath, body);
219872
219955
  if (opts.json)
219873
- return printJson2(payload);
219956
+ return printJson(payload);
219874
219957
  const item = payload.item;
219875
219958
  success(`Updated ${ui.bold(item?.exampleName ?? itemId)}` + (item?.status ? ` ${ui.dim(`(${item.status})`)}` : ""));
219876
219959
  }));
@@ -219926,33 +220009,295 @@ live dataset example-by-example by hand (reviewers can err), then
219926
220009
  });
219927
220010
  }
219928
220011
  if (opts.json) {
219929
- return printJson2({ out: outDir, examples: summary, fileCount });
220012
+ return printJson({ out: outDir, examples: summary, fileCount });
219930
220013
  }
219931
220014
  success(`Pulled ${fileCount} expected file${fileCount === 1 ? "" : "s"} ` + `across ${summary.length} example${summary.length === 1 ? "" : "s"} ` + `to ${ui.bold(outDir)}`);
219932
220015
  }));
219933
220016
  }
219934
220017
 
220018
+ // src/commands/agents/shared.ts
220019
+ init_src();
220020
+ import { promises as fs2 } from "node:fs";
220021
+ import path8 from "node:path";
220022
+
220023
+ // src/lib/watch.ts
220024
+ init_src();
220025
+ var STATUS_BADGES = {
220026
+ pending: "[ ]",
220027
+ running: "[..]",
220028
+ completed: "[ok]",
220029
+ failed: "[x]",
220030
+ cancelled: "[-]",
220031
+ skipped: "[s]"
220032
+ };
220033
+ function statusBadge(status) {
220034
+ return STATUS_BADGES[status] ?? `[${status.slice(0, 3)}]`;
220035
+ }
220036
+ function durationSuffix(ms) {
220037
+ const formatted = formatDuration(ms);
220038
+ return formatted ? ` ${formatted}` : "";
220039
+ }
220040
+ function renderFrame(snapshot) {
220041
+ const lines = [
220042
+ `${statusBadge(snapshot.status)} ${snapshot.id}${durationSuffix(snapshot.durationMs)}`
220043
+ ];
220044
+ for (const step of snapshot.stepExecutions ?? []) {
220045
+ const errSuffix = step.error ? ` err: ${step.error.slice(0, 80)}` : "";
220046
+ lines.push(` ${statusBadge(step.status)} ${step.stepName}${durationSuffix(step.durationMs)}${errSuffix}`);
220047
+ if (step.outputPreview) {
220048
+ lines.push(` ↳ ${step.outputPreview}`);
220049
+ }
220050
+ }
220051
+ if (snapshot.error && (snapshot.stepExecutions ?? []).length === 0) {
220052
+ lines.push(` err: ${snapshot.error.slice(0, 200)}`);
220053
+ }
220054
+ return lines.join(`
220055
+ `);
220056
+ }
220057
+ var ANSI_CURSOR_UP = "\x1B[A";
220058
+ var ANSI_CLEAR_LINE = "\x1B[2K\r";
220059
+ function makeAnsiRenderer() {
220060
+ const isTty = Boolean(process.stderr.isTTY);
220061
+ let previousLineCount = 0;
220062
+ return (frame) => {
220063
+ let buf = "";
220064
+ if (isTty) {
220065
+ for (let i = 0;i < previousLineCount; i++) {
220066
+ buf += i === 0 ? ANSI_CLEAR_LINE : `${ANSI_CURSOR_UP}${ANSI_CLEAR_LINE}`;
220067
+ }
220068
+ }
220069
+ buf += frame;
220070
+ if (!frame.endsWith(`
220071
+ `))
220072
+ buf += `
220073
+ `;
220074
+ if (!isTty && previousLineCount > 0)
220075
+ buf += `
220076
+ `;
220077
+ process.stderr.write(buf);
220078
+ previousLineCount = frame.split(`
220079
+ `).length;
220080
+ };
220081
+ }
220082
+ function defaultSleep(ms) {
220083
+ return new Promise((resolve) => setTimeout(resolve, ms));
220084
+ }
220085
+ function snapshotsDiffer(a, b) {
220086
+ if (a.status !== b.status)
220087
+ return true;
220088
+ const aSteps = a.stepExecutions ?? [];
220089
+ const bSteps = b.stepExecutions ?? [];
220090
+ if (aSteps.length !== bSteps.length)
220091
+ return true;
220092
+ for (let i = 0;i < aSteps.length; i++) {
220093
+ if (aSteps[i].stepName !== bSteps[i].stepName || aSteps[i].status !== bSteps[i].status) {
220094
+ return true;
220095
+ }
220096
+ }
220097
+ return false;
220098
+ }
220099
+ function defaultShouldAbort(err) {
220100
+ return err instanceof ApiError && err.status >= 400 && err.status < 500;
220101
+ }
220102
+ async function watchExecution(opts) {
220103
+ const sleep = opts.sleep ?? defaultSleep;
220104
+ const now = opts.now ?? (() => Date.now());
220105
+ const render = opts.render ?? makeAnsiRenderer();
220106
+ const maxMs = opts.maxMs ?? 30 * 60 * 1000;
220107
+ const transitionInterval = opts.transitionIntervalMs ?? 2000;
220108
+ const steadyInterval = opts.steadyIntervalMs ?? 5000;
220109
+ const shouldAbort = opts.shouldAbort ?? defaultShouldAbort;
220110
+ const start = now();
220111
+ let previous;
220112
+ let lastFetched;
220113
+ while (true) {
220114
+ let current;
220115
+ try {
220116
+ current = await opts.fetch();
220117
+ } catch (err) {
220118
+ if (shouldAbort(err))
220119
+ throw err;
220120
+ const message = err instanceof Error ? err.message : String(err);
220121
+ render(`(network) ${message.slice(0, 120)}`);
220122
+ if (lastFetched && now() - start >= maxMs) {
220123
+ return { final: lastFetched, detached: true };
220124
+ }
220125
+ await sleep(steadyInterval);
220126
+ continue;
220127
+ }
220128
+ lastFetched = current;
220129
+ render(renderFrame(current));
220130
+ if (isTerminalExecutionStatus(current.status)) {
220131
+ return { final: current, detached: false };
220132
+ }
220133
+ if (now() - start >= maxMs) {
220134
+ return { final: current, detached: true };
220135
+ }
220136
+ const transitioned = previous == null || snapshotsDiffer(previous, current);
220137
+ previous = current;
220138
+ await sleep(transitioned ? transitionInterval : steadyInterval);
220139
+ }
220140
+ }
220141
+ async function pollUntil(opts) {
220142
+ const start = Date.now();
220143
+ while (true) {
220144
+ const value = await opts.fetch();
220145
+ opts.onTick?.(value);
220146
+ if (opts.isTerminal(value))
220147
+ return { value, timedOut: false };
220148
+ if (Date.now() - start >= opts.maxWaitMs)
220149
+ return { value, timedOut: true };
220150
+ await new Promise((resolve) => setTimeout(resolve, opts.intervalMs));
220151
+ }
220152
+ }
220153
+
220154
+ // src/commands/agents/shared.ts
220155
+ var DATASET_DIR = "dataset";
220156
+ var AGENT_EXAMPLE_INPUT_JSON = "input.json";
220157
+ var AGENT_EXAMPLE_EXPECTED_JSON = "expected.json";
220158
+ var LEGACY_LAYOUTS = [
220159
+ ["workflow", "agent"],
220160
+ ["eval", "dataset"]
220161
+ ];
220162
+ function collectRepeated(value, previous = []) {
220163
+ return [...previous, value];
220164
+ }
220165
+ function agentAutomationId(value) {
220166
+ if (value.startsWith("agents.") || value.startsWith("workflows."))
220167
+ return value;
220168
+ if (value.includes("_"))
220169
+ return value;
220170
+ return `agents.${value}`;
220171
+ }
220172
+ async function writeBase64File(file, contentBase64) {
220173
+ await fs2.mkdir(path8.dirname(file), { recursive: true });
220174
+ await fs2.writeFile(file, Buffer.from(contentBase64, "base64"));
220175
+ }
220176
+ async function pollRun(client, executionId, interval, maxWait, json = false) {
220177
+ const base = `/v1/runs/${encodeURIComponent(executionId)}`;
220178
+ const { value, timedOut } = await pollUntil({
220179
+ fetch: async () => await client.get(`${base}?expand=execution`),
220180
+ isTerminal: (run) => Boolean(run.finished) || isTerminalExecutionStatus(run.execution?.status),
220181
+ intervalMs: interval * 1000,
220182
+ maxWaitMs: maxWait * 1000
220183
+ });
220184
+ if (timedOut) {
220185
+ if (json)
220186
+ printJson(value);
220187
+ process.stderr.write(`Timed out waiting for run ${executionId}
220188
+ `);
220189
+ process.exit(2);
220190
+ }
220191
+ return await client.get(`${base}?expand=usage,execution`);
220192
+ }
220193
+ async function pollExperiment(client, automationId, batchId, interval, maxWait, json = false) {
220194
+ let notFoundRetries = 0;
220195
+ let lastPayload;
220196
+ const url = `/v1/automations/${encodeURIComponent(automationId)}/experiments/${encodeURIComponent(batchId)}`;
220197
+ const { timedOut, value } = await pollUntil({
220198
+ fetch: async () => {
220199
+ try {
220200
+ lastPayload = await client.get(url);
220201
+ return lastPayload;
220202
+ } catch (error) {
220203
+ if (!(error instanceof ApiError) || error.status !== 404 || notFoundRetries >= 2)
220204
+ throw error;
220205
+ notFoundRetries++;
220206
+ return { status: "pending" };
220207
+ }
220208
+ },
220209
+ isTerminal: (payload) => payload.status === "completed",
220210
+ intervalMs: interval * 1000,
220211
+ maxWaitMs: maxWait * 1000
220212
+ });
220213
+ if (timedOut) {
220214
+ if (json)
220215
+ printJson(lastPayload ?? { batchId, status: "pending" });
220216
+ process.stderr.write(`Timed out waiting for experiment ${batchId}
220217
+ `);
220218
+ process.exit(2);
220219
+ }
220220
+ return value;
220221
+ }
220222
+ function setExitCodeForFailedExperiment(payload) {
220223
+ const counts = payload;
220224
+ if ([counts?.failedCount, counts?.cancelledCount, counts?.rejectedCount].some((count) => typeof count === "number" && count > 0)) {
220225
+ process.exitCode = 1;
220226
+ }
220227
+ }
220228
+ function renderRunPayload(payload, opts) {
220229
+ if (opts.json)
220230
+ return printJson(payload);
220231
+ const run = payload;
220232
+ if (!run || run.id === undefined)
220233
+ return printJson(payload);
220234
+ const status = run.execution?.status ?? (run.finished === true ? "completed" : "running");
220235
+ success(`Run ${run.id} is ${status}`);
220236
+ }
220237
+ function setExitCodeForFailedTerminalRun(payload) {
220238
+ const run = payload;
220239
+ const status = run?.execution?.status;
220240
+ if (status === "failed" || status === "cancelled" || status === "rejected" || run?.finished === true && run?.error) {
220241
+ process.exitCode = 1;
220242
+ }
220243
+ }
220244
+ function renderGeneric(payload, opts, message) {
220245
+ if (opts.json)
220246
+ return printJson(payload);
220247
+ success(message);
220248
+ }
220249
+ function compactParams(opts) {
220250
+ const params = {};
220251
+ for (const [key, value] of Object.entries(opts)) {
220252
+ if (value === undefined || value === null || key === "json" || key === "baseUrl" || key === "yes" || key === "compact")
220253
+ continue;
220254
+ params[key] = String(value);
220255
+ }
220256
+ return params;
220257
+ }
220258
+ function parseDatasetMode(value) {
220259
+ if (value === "append" || value === "replace")
220260
+ return value;
220261
+ throw new InvalidArgumentError("mode must be append or replace");
220262
+ }
220263
+ function parseResultsFormat(value) {
220264
+ if (value === "csv" || value === "json")
220265
+ return value;
220266
+ throw new InvalidArgumentError("format must be csv or json");
220267
+ }
220268
+ function toCsv(rows, columns) {
220269
+ const escape = (value) => {
220270
+ const text = value == null ? "" : String(value);
220271
+ return /[",\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
220272
+ };
220273
+ return [
220274
+ columns.join(","),
220275
+ ...rows.map((row) => columns.map((column) => escape(row[column])).join(","))
220276
+ ].join(`
220277
+ `);
220278
+ }
220279
+
219935
220280
  // src/commands/agents/validation.ts
219936
220281
  init_src();
219937
- import { existsSync as existsSync8, promises as fs3 } from "node:fs";
220282
+ import { existsSync as existsSync7, promises as fs3 } from "node:fs";
219938
220283
  import path9 from "node:path";
219939
220284
  async function validateAgentProject(root) {
219940
220285
  const errors = [];
219941
220286
  const warnings = [];
219942
220287
  for (const [oldName] of LEGACY_LAYOUTS) {
219943
- if (existsSync8(path9.join(root, oldName))) {
220288
+ if (existsSync7(path9.join(root, oldName))) {
219944
220289
  errors.push(`Legacy layout ${oldName}/ is removed; use Git source under agents/<slug>/`);
219945
220290
  }
219946
220291
  }
219947
- if (!existsSync8(path9.join(root, "agent.ts")))
220292
+ if (!existsSync7(path9.join(root, "agent.ts")))
219948
220293
  errors.push("Missing agent.ts");
219949
- if (!existsSync8(path9.join(root, DATASET_DIR)))
220294
+ if (!existsSync7(path9.join(root, DATASET_DIR)))
219950
220295
  warnings.push(`Missing ${DATASET_DIR}/`);
219951
220296
  return { valid: errors.length === 0, errors, warnings };
219952
220297
  }
219953
220298
  async function validateDatasetDir(dir, opts = {}) {
219954
220299
  const errors = [];
219955
- if (!existsSync8(dir))
220300
+ if (!existsSync7(dir))
219956
220301
  errors.push(`Missing dataset directory: ${dir}`);
219957
220302
  for (const [oldName, newName] of LEGACY_LAYOUTS) {
219958
220303
  if (path9.basename(dir) === oldName) {
@@ -219961,7 +220306,7 @@ async function validateDatasetDir(dir, opts = {}) {
219961
220306
  }
219962
220307
  if (errors.length > 0)
219963
220308
  return { valid: false, errors };
219964
- if (existsSync8(path9.join(dir, "manifest.json"))) {
220309
+ if (existsSync7(path9.join(dir, "manifest.json"))) {
219965
220310
  return {
219966
220311
  valid: false,
219967
220312
  errors: [
@@ -219970,7 +220315,7 @@ async function validateDatasetDir(dir, opts = {}) {
219970
220315
  };
219971
220316
  }
219972
220317
  const examplesDir = path9.join(dir, "examples");
219973
- if (!existsSync8(examplesDir) || !(await fs3.stat(examplesDir)).isDirectory()) {
220318
+ if (!existsSync7(examplesDir) || !(await fs3.stat(examplesDir)).isDirectory()) {
219974
220319
  errors.push("examples/: missing examples/ directory at dataset root");
219975
220320
  const flatFolders = await listImmediateDirs(dir);
219976
220321
  if (flatFolders.length > 0) {
@@ -219979,7 +220324,7 @@ async function validateDatasetDir(dir, opts = {}) {
219979
220324
  return { valid: false, errors };
219980
220325
  }
219981
220326
  const agentDir = opts.agentDir ?? process.cwd();
219982
- const compiled = existsSync8(path9.join(agentDir, "agent.ts")) ? await compileLocalAgent(agentDir, opts.config) : null;
220327
+ const compiled = existsSync7(path9.join(agentDir, "agent.ts")) ? await compileLocalAgent(agentDir, opts.config) : null;
219983
220328
  const inputSchema = compiled?.definition.inputSchema ?? null;
219984
220329
  const outputSchema = compiled?.definition.outputSchema ?? null;
219985
220330
  const examples = (await fs3.readdir(examplesDir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
@@ -220013,7 +220358,7 @@ async function validateDatasetExample(exampleRoot, example, schemas) {
220013
220358
  }
220014
220359
  }
220015
220360
  const inputJsonPath = path9.join(exampleRoot, AGENT_EXAMPLE_INPUT_JSON);
220016
- if (!existsSync8(inputJsonPath)) {
220361
+ if (!existsSync7(inputJsonPath)) {
220017
220362
  errors.push(`${label}/input.json: input.json is required`);
220018
220363
  return errors;
220019
220364
  }
@@ -220033,7 +220378,7 @@ async function validateDatasetExample(exampleRoot, example, schemas) {
220033
220378
  }));
220034
220379
  const expectedJsonPath = path9.join(exampleRoot, AGENT_EXAMPLE_EXPECTED_JSON);
220035
220380
  let expectedOutput = null;
220036
- if (existsSync8(expectedJsonPath)) {
220381
+ if (existsSync7(expectedJsonPath)) {
220037
220382
  const expected = await readJson(expectedJsonPath, `${label}/expected.json`, errors);
220038
220383
  if (expected !== undefined) {
220039
220384
  if (isExpectedErrorRef(expected)) {
@@ -220057,7 +220402,7 @@ async function validateDatasetExample(exampleRoot, example, schemas) {
220057
220402
  }
220058
220403
  }
220059
220404
  const metaJsonPath = path9.join(exampleRoot, "meta.json");
220060
- if (existsSync8(metaJsonPath)) {
220405
+ if (existsSync7(metaJsonPath)) {
220061
220406
  const meta = await readJson(metaJsonPath, `${label}/meta.json`, errors);
220062
220407
  if (meta !== undefined) {
220063
220408
  const parsed = DatasetMetaSchema.safeParse(meta);
@@ -220113,7 +220458,7 @@ function validateFileRefs(args) {
220113
220458
  }
220114
220459
  async function listFilesUnder(dir) {
220115
220460
  const out = new Set;
220116
- if (!existsSync8(dir))
220461
+ if (!existsSync7(dir))
220117
220462
  return out;
220118
220463
  async function walk(current, relPrefix) {
220119
220464
  for (const entry of await fs3.readdir(current, { withFileTypes: true })) {
@@ -220257,16 +220602,16 @@ Layout (mirrors the server import rules)
220257
220602
  ` + ` only when they complete.
220258
220603
  `).action(action(validateDatasetCommand));
220259
220604
  registerDatasetReviewRequestCommands(dataset, async (agentId, opts) => {
220260
- const client = buildClient2(opts);
220605
+ const client = buildClient(opts);
220261
220606
  return { client, automationId: agentAutomationId(agentId) };
220262
220607
  });
220263
220608
  }
220264
220609
  async function listDataset(agentId, opts) {
220265
- const client = buildClient2(opts);
220610
+ const client = buildClient(opts);
220266
220611
  const payload = await client.get(`/v1/automations/${encodeURIComponent(agentAutomationId(agentId))}/examples`, compactParams(opts));
220267
220612
  const examples = payload.data ?? [];
220268
220613
  if (opts.json)
220269
- return printJson2(payload);
220614
+ return printJson(payload);
220270
220615
  console.log(table(examples.map((row) => ({ id: row.id, name: row.name })), [
220271
220616
  { key: "id", header: "ID" },
220272
220617
  { key: "name", header: "NAME" }
@@ -220288,14 +220633,14 @@ async function pushDataset(agentId, opts) {
220288
220633
  const form = new FormData;
220289
220634
  form.set("file", new Blob([archive], { type: "application/zip" }), stat.isDirectory() ? "dataset.zip" : path10.basename(resolved));
220290
220635
  form.set("mode", opts.mode);
220291
- const client = buildClient2(opts);
220636
+ const client = buildClient(opts);
220292
220637
  const payload = await client.postFormData(`/v1/automations/${encodeURIComponent(agentAutomationId(agentId))}/dataset/import`, form);
220293
220638
  if (opts.json)
220294
- return printJson2(payload);
220639
+ return printJson(payload);
220295
220640
  success(`${opts.mode === "replace" ? "Replaced" : "Uploaded"} dataset archive`);
220296
220641
  }
220297
220642
  async function pullDataset(agentId, opts) {
220298
- const client = buildClient2(opts);
220643
+ const client = buildClient(opts);
220299
220644
  const res = await client.getStream(`/v1/automations/${encodeURIComponent(agentAutomationId(agentId))}/dataset/export`);
220300
220645
  const archive = Buffer.from(await res.arrayBuffer());
220301
220646
  const out = path10.resolve(opts.out ?? DATASET_DIR);
@@ -220309,7 +220654,7 @@ async function validateDatasetCommand(dir = DATASET_DIR, opts) {
220309
220654
  config: resolveConfig(opts)
220310
220655
  });
220311
220656
  if (opts.json)
220312
- return printJson2(result);
220657
+ return printJson(result);
220313
220658
  if (result.valid)
220314
220659
  return success("Dataset is valid");
220315
220660
  for (const issue of result.errors)
@@ -220317,7 +220662,7 @@ async function validateDatasetCommand(dir = DATASET_DIR, opts) {
220317
220662
  process.exit(1);
220318
220663
  }
220319
220664
  async function readDirAsZip(dir) {
220320
- if (!existsSync9(dir))
220665
+ if (!existsSync8(dir))
220321
220666
  throw new Error(`directory does not exist: ${dir}`);
220322
220667
  const files = {};
220323
220668
  async function walk(current, relPrefix) {
@@ -220340,7 +220685,7 @@ async function readDirAsZip(dir) {
220340
220685
 
220341
220686
  // src/commands/agents/env.ts
220342
220687
  init_src();
220343
- import { existsSync as existsSync10, promises as fs5, readFileSync as readFileSync8 } from "node:fs";
220688
+ import { existsSync as existsSync9, promises as fs5, readFileSync as readFileSync8 } from "node:fs";
220344
220689
  import path11 from "node:path";
220345
220690
 
220346
220691
  // src/commands/agents/target.ts
@@ -220379,9 +220724,9 @@ function registerSecretsExportCommands(agent) {
220379
220724
  async function pullAgentEnv(target, opts) {
220380
220725
  const format = opts.format ?? "shell";
220381
220726
  if (format !== "shell" && format !== "dotenv") {
220382
- throw new Error("--format must be shell or dotenv");
220727
+ throw new UsageError("--format must be shell or dotenv");
220383
220728
  }
220384
- const client = buildClient2(opts);
220729
+ const client = buildClient(opts);
220385
220730
  const requests = target ? await collectEncryptedSecretsForTarget(client, target) : await collectEncryptedSecrets(path11.resolve(opts.dir ?? "."));
220386
220731
  if (requests.length === 0)
220387
220732
  return;
@@ -220450,7 +220795,7 @@ async function collectEncryptedSecrets(root) {
220450
220795
  const requests = [];
220451
220796
  for (const packageRoot of roots) {
220452
220797
  const secretsPath = path11.join(packageRoot, SOURCE_SECRETS_FILENAME);
220453
- if (!existsSync10(secretsPath))
220798
+ if (!existsSync9(secretsPath))
220454
220799
  continue;
220455
220800
  const parsed = SourceSecretsFileSchema.parse(exports_dist.parse(await fs5.readFile(secretsPath, "utf8")));
220456
220801
  const sourcePath = sourcePathForInstalledPackage(root, packageRoot);
@@ -220472,7 +220817,7 @@ async function collectEncryptedSecrets(root) {
220472
220817
  return requests;
220473
220818
  }
220474
220819
  async function listModulePackageRoots(modulesRoot) {
220475
- if (!existsSync10(modulesRoot))
220820
+ if (!existsSync9(modulesRoot))
220476
220821
  return [];
220477
220822
  const result = [];
220478
220823
  for (const type of await fs5.readdir(modulesRoot)) {
@@ -220498,7 +220843,7 @@ function sourcePathForInstalledPackage(root, packageRoot) {
220498
220843
  if (!relative.startsWith(".."))
220499
220844
  return relative;
220500
220845
  const lockfilePath = path11.join(root, ".eigenpal", "eigenpal.lock");
220501
- if (packageRoot === root && existsSync10(lockfilePath)) {
220846
+ if (packageRoot === root && existsSync9(lockfilePath)) {
220502
220847
  const lockfile = JSON.parse(readFileSync8(lockfilePath, "utf8"));
220503
220848
  if (typeof lockfile.root?.packagePath === "string")
220504
220849
  return lockfile.root.packagePath;
@@ -220993,9 +221338,9 @@ async function fetchExperimentOutputs(client, experimentId) {
220993
221338
  executionId: run.id,
220994
221339
  exampleId: run.exampleId ?? null,
220995
221340
  exampleName: run.exampleName ?? null,
220996
- status: payload.execution?.status ?? payload.status ?? payload.result?.status ?? null,
220997
- error: payload.error ?? payload.execution?.error ?? payload.result?.error ?? null,
220998
- output: payload.output !== undefined ? payload.output : payload.result?.output
221341
+ status: payload.execution?.status ?? payload.status ?? null,
221342
+ error: payload.error ?? payload.execution?.error ?? null,
221343
+ output: payload.output
220999
221344
  };
221000
221345
  });
221001
221346
  return { automationId: ref.automationId, rows };
@@ -221206,7 +221551,7 @@ function registerExperimentCommands(agent) {
221206
221551
  addJsonFlag(withBaseUrl(experiment.command("cancel <agent-id-or-slug> <batch-id>"))).description("Cancel every active execution in an experiment.").option("--yes", "Skip confirmation (required in CI / agent terminals without a TTY)").action(action(cancelExperiment));
221207
221552
  }
221208
221553
  async function runExperiment(agentId, opts) {
221209
- const client = buildClient2(opts);
221554
+ const client = buildClient(opts);
221210
221555
  const automationId = agentAutomationId(agentId);
221211
221556
  let payload = await client.post(`/v1/automations/${encodeURIComponent(automationId)}/experiments`, {
221212
221557
  ...opts.exampleId ? { examples: [opts.exampleId] } : {}
@@ -221224,28 +221569,22 @@ async function runExperiment(agentId, opts) {
221224
221569
  total: payload.runCount ?? payload.total
221225
221570
  };
221226
221571
  renderGeneric(stablePayload, opts, `${opts.wait ? "Completed" : "Started"} experiment ${experimentId ?? ""}`);
221227
- const failedCount = payload.failedCount;
221228
- if (opts.wait && typeof failedCount === "number" && failedCount > 0) {
221229
- process.exitCode = 1;
221230
- }
221572
+ if (opts.wait)
221573
+ setExitCodeForFailedExperiment(payload);
221231
221574
  }
221232
221575
  async function experimentStatus(agentId, batchId, opts) {
221233
- const client = buildClient2(opts);
221576
+ const client = buildClient(opts);
221234
221577
  const automationId = agentAutomationId(agentId);
221235
221578
  const payload = opts.watch ? await pollExperiment(client, automationId, batchId, opts.interval, opts.maxWait, opts.json) : await client.get(`/v1/automations/${encodeURIComponent(automationId)}/experiments/${encodeURIComponent(batchId)}`);
221236
221579
  renderGeneric(payload, opts, `Experiment ${batchId}`);
221237
- if (opts.watch) {
221238
- const counts = payload;
221239
- if ([counts.failedCount, counts.cancelledCount, counts.rejectedCount].some((count) => typeof count === "number" && count > 0)) {
221240
- process.exitCode = 1;
221241
- }
221242
- }
221580
+ if (opts.watch)
221581
+ setExitCodeForFailedExperiment(payload);
221243
221582
  }
221244
221583
  async function experimentResults(agentId, batchId, opts) {
221245
- const client = buildClient2(opts);
221584
+ const client = buildClient(opts);
221246
221585
  const automationId = agentAutomationId(agentId);
221247
221586
  if (opts.json && opts.format !== "json") {
221248
- throw new Error("--json cannot be combined with --format csv");
221587
+ throw new UsageError("--json cannot be combined with --format csv");
221249
221588
  }
221250
221589
  const selected = batchId ?? String((await client.get(`/v1/automations/${encodeURIComponent(automationId)}/experiments`, {
221251
221590
  limit: "1",
@@ -221256,7 +221595,7 @@ async function experimentResults(agentId, batchId, opts) {
221256
221595
  const analyze = opts.summary || opts.failedOnly || opts.evaluator !== undefined || opts.select !== undefined;
221257
221596
  if (analyze) {
221258
221597
  if (opts.format !== "json")
221259
- throw new Error("Experiment analysis options require --format json");
221598
+ throw new UsageError("Experiment analysis options require --format json");
221260
221599
  const detail = await client.get(`/v1/automations/${encodeURIComponent(automationId)}/experiments/${encodeURIComponent(selected)}`);
221261
221600
  const analysis = analyzeExperimentResults({
221262
221601
  rows: experimentRowsFromDetail(detail),
@@ -221290,7 +221629,7 @@ async function experimentResults(agentId, batchId, opts) {
221290
221629
  }
221291
221630
  }
221292
221631
  async function listExperiments(agentId, opts) {
221293
- const client = buildClient2(opts);
221632
+ const client = buildClient(opts);
221294
221633
  const automationId = agentAutomationId(agentId);
221295
221634
  const payload = await client.get(`/v1/automations/${encodeURIComponent(automationId)}/experiments`, compactParams(opts));
221296
221635
  const experiments = payload.data ?? [];
@@ -221298,7 +221637,7 @@ async function listExperiments(agentId, opts) {
221298
221637
  payload.data = experiments.filter((row) => row.id === opts.batchId || row.batchId === opts.batchId);
221299
221638
  }
221300
221639
  if (opts.json)
221301
- return printJson2(payload);
221640
+ return printJson(payload);
221302
221641
  console.log(table(payload.data ?? experiments, [
221303
221642
  { key: "id", header: "EXPERIMENT" },
221304
221643
  { key: "runCount", header: "RUNS" }
@@ -221308,9 +221647,9 @@ async function compareExperiments(batchIdA, batchIdB, opts) {
221308
221647
  const sort = normalizeCompareSort(opts.sort);
221309
221648
  const threshold = opts.regressionThreshold;
221310
221649
  if (!Number.isFinite(threshold) || threshold < 0) {
221311
- throw new Error("--regression-threshold must be a non-negative number");
221650
+ throw new UsageError("--regression-threshold must be a non-negative number");
221312
221651
  }
221313
- const client = buildClient2(opts);
221652
+ const client = buildClient(opts);
221314
221653
  if (opts.outputs) {
221315
221654
  const [outputsA, outputsB] = await Promise.all([
221316
221655
  fetchExperimentOutputs(client, batchIdA),
@@ -221326,7 +221665,7 @@ async function compareExperiments(batchIdA, batchIdB, opts) {
221326
221665
  rowsB: outputsB.rows
221327
221666
  });
221328
221667
  if (opts.json)
221329
- return printJson2(diff);
221668
+ return printJson(diff);
221330
221669
  renderExperimentOutputDiffHuman(diff);
221331
221670
  return;
221332
221671
  }
@@ -221343,12 +221682,12 @@ async function compareExperiments(batchIdA, batchIdB, opts) {
221343
221682
  regressionThreshold: threshold
221344
221683
  });
221345
221684
  if (opts.json)
221346
- return printJson2(diff);
221685
+ return printJson(diff);
221347
221686
  renderBatchDiffHuman(diff);
221348
221687
  }
221349
221688
  async function cancelExperiment(agentId, batchId, opts) {
221350
221689
  requireYesInNonInteractive(opts.yes, "Cancel experiment batch");
221351
- const client = buildClient2(opts);
221690
+ const client = buildClient(opts);
221352
221691
  const payload = await client.post(`/v1/automations/${encodeURIComponent(agentAutomationId(agentId))}/experiments/${encodeURIComponent(batchId)}/cancel`);
221353
221692
  renderGeneric(payload, opts, `Cancelled experiment ${batchId}`);
221354
221693
  }
@@ -221367,24 +221706,24 @@ function registerAgentFileCommands(agent) {
221367
221706
  addJsonFlag(withBaseUrl(file.command("diff <agent-id-or-slug> <remote-path> <local-path>"))).description("Compare one live agent file against a local file.").action(action(diffAgentFile));
221368
221707
  }
221369
221708
  async function listAgentFiles(agentId, opts) {
221370
- const client = buildClient2(opts);
221709
+ const client = buildClient(opts);
221371
221710
  const packagePath = await resolveAgentPackagePath2(client, agentId);
221372
221711
  const payload = await client.get("/v1/source/tree", {
221373
221712
  packagePath,
221374
221713
  ...opts.path ? { prefix: normalizeAgentFilePath(opts.path, { allowEmpty: true }) } : {}
221375
221714
  });
221376
221715
  if (opts.json)
221377
- return printJson2(payload);
221716
+ return printJson(payload);
221378
221717
  console.log(table((payload.files ?? []).map((name) => ({ name })), [{ key: "name", header: "PATH" }]));
221379
221718
  }
221380
221719
  async function getAgentFile(agentId, remotePath, opts) {
221381
221720
  if (opts.json && opts.out) {
221382
- throw new Error("--json and --out are mutually exclusive");
221721
+ throw new UsageError("--json and --out are mutually exclusive");
221383
221722
  }
221384
- const client = buildClient2(opts);
221723
+ const client = buildClient(opts);
221385
221724
  const payload = await readAgentFile(client, agentId, remotePath);
221386
221725
  if (opts.json)
221387
- return printJson2(payload);
221726
+ return printJson(payload);
221388
221727
  const out = path12.resolve(opts.out ?? payload.path);
221389
221728
  await writeBase64File(out, payload.contentBase64);
221390
221729
  success(`Downloaded ${payload.path} to ${ui.bold(out)}`);
@@ -221392,11 +221731,11 @@ async function getAgentFile(agentId, remotePath, opts) {
221392
221731
  async function diffAgentFile(agentId, remotePath, localPath, opts) {
221393
221732
  const report = await buildAgentFileDiff(agentId, remotePath, path12.resolve(localPath), opts);
221394
221733
  if (opts.json)
221395
- return printJson2(report);
221734
+ return printJson(report);
221396
221735
  renderAgentFileDiff(report);
221397
221736
  }
221398
221737
  async function buildAgentFileDiff(agentId, remotePath, localPath, opts) {
221399
- const client = buildClient2(opts);
221738
+ const client = buildClient(opts);
221400
221739
  const local = await fs7.readFile(localPath);
221401
221740
  let remote = null;
221402
221741
  let serverPath = normalizeAgentFilePath(remotePath);
@@ -221504,10 +221843,10 @@ function registerSessionCommands(agent) {
221504
221843
  addJsonFlag(withBaseUrl(session.command("stop <session-id>"))).description("Stop a builder session.").option("--yes", "Skip confirmation (required in CI / agent terminals without a TTY)").action(action(stopSession));
221505
221844
  }
221506
221845
  async function listSessions(agentId, opts) {
221507
- const client = buildClient2(opts);
221846
+ const client = buildClient(opts);
221508
221847
  const payload = await client.get(`/v1/agents/${encodeURIComponent(agentId)}/sessions`, compactParams(opts));
221509
221848
  if (opts.json)
221510
- return printJson2(payload);
221849
+ return printJson(payload);
221511
221850
  console.log(table(payload.sessions, [
221512
221851
  { key: "id", header: "ID" },
221513
221852
  { key: "status", header: "STATUS" },
@@ -221515,24 +221854,24 @@ async function listSessions(agentId, opts) {
221515
221854
  ]));
221516
221855
  }
221517
221856
  async function getSession(sessionId, opts) {
221518
- const client = buildClient2(opts);
221857
+ const client = buildClient(opts);
221519
221858
  renderGeneric(await client.get(`/v1/agents/sessions/${encodeURIComponent(sessionId)}`), opts, `Session ${sessionId}`);
221520
221859
  }
221521
221860
  async function startSession(agentId, opts) {
221522
- const client = buildClient2(opts);
221861
+ const client = buildClient(opts);
221523
221862
  renderGeneric(await client.post(`/v1/agents/${encodeURIComponent(agentId)}/sessions`, {
221524
221863
  ...opts.title ? { title: opts.title } : {}
221525
221864
  }), opts, "Started session");
221526
221865
  }
221527
221866
  async function messageSession(sessionId, opts) {
221528
- const client = buildClient2(opts);
221867
+ const client = buildClient(opts);
221529
221868
  renderGeneric(await client.post(`/v1/agents/sessions/${encodeURIComponent(sessionId)}`, {
221530
221869
  text: opts.text
221531
221870
  }), opts, "Sent message");
221532
221871
  }
221533
221872
  async function stopSession(sessionId, opts) {
221534
221873
  requireYesInNonInteractive(opts.yes, "Stop builder session");
221535
- const client = buildClient2(opts);
221874
+ const client = buildClient(opts);
221536
221875
  renderGeneric(await client.delete(`/v1/agents/sessions/${encodeURIComponent(sessionId)}`), opts, "Stopped session");
221537
221876
  }
221538
221877
 
@@ -221540,7 +221879,7 @@ async function stopSession(sessionId, opts) {
221540
221879
  init_src();
221541
221880
  import { spawnSync as spawnSync4 } from "node:child_process";
221542
221881
  import { createHash as createHash4 } from "node:crypto";
221543
- import { promises as fs16, readFileSync as readFileSync13 } from "node:fs";
221882
+ import { promises as fs16, readFileSync as readFileSync11 } from "node:fs";
221544
221883
  import path15 from "node:path";
221545
221884
 
221546
221885
  // src/lib/workflow-rows.ts
@@ -221648,125 +221987,6 @@ async function resolveWorkflowId(client, idOrSlug) {
221648
221987
  return match.id;
221649
221988
  }
221650
221989
 
221651
- // src/lib/watch.ts
221652
- init_src();
221653
- var STATUS_BADGES = {
221654
- pending: "[ ]",
221655
- running: "[..]",
221656
- completed: "[ok]",
221657
- failed: "[x]",
221658
- cancelled: "[-]",
221659
- skipped: "[s]"
221660
- };
221661
- function statusBadge(status) {
221662
- return STATUS_BADGES[status] ?? `[${status.slice(0, 3)}]`;
221663
- }
221664
- function durationSuffix(ms) {
221665
- const formatted = formatDuration(ms);
221666
- return formatted ? ` ${formatted}` : "";
221667
- }
221668
- function renderFrame(snapshot) {
221669
- const lines = [
221670
- `${statusBadge(snapshot.status)} ${snapshot.id}${durationSuffix(snapshot.durationMs)}`
221671
- ];
221672
- for (const step of snapshot.stepExecutions ?? []) {
221673
- const errSuffix = step.error ? ` err: ${step.error.slice(0, 80)}` : "";
221674
- lines.push(` ${statusBadge(step.status)} ${step.stepName}${durationSuffix(step.durationMs)}${errSuffix}`);
221675
- if (step.outputPreview) {
221676
- lines.push(` ↳ ${step.outputPreview}`);
221677
- }
221678
- }
221679
- if (snapshot.error && (snapshot.stepExecutions ?? []).length === 0) {
221680
- lines.push(` err: ${snapshot.error.slice(0, 200)}`);
221681
- }
221682
- return lines.join(`
221683
- `);
221684
- }
221685
- var ANSI_CURSOR_UP = "\x1B[A";
221686
- var ANSI_CLEAR_LINE = "\x1B[2K\r";
221687
- function makeAnsiRenderer() {
221688
- const isTty = Boolean(process.stderr.isTTY);
221689
- let previousLineCount = 0;
221690
- return (frame) => {
221691
- let buf = "";
221692
- if (isTty) {
221693
- for (let i = 0;i < previousLineCount; i++) {
221694
- buf += i === 0 ? ANSI_CLEAR_LINE : `${ANSI_CURSOR_UP}${ANSI_CLEAR_LINE}`;
221695
- }
221696
- }
221697
- buf += frame;
221698
- if (!frame.endsWith(`
221699
- `))
221700
- buf += `
221701
- `;
221702
- if (!isTty && previousLineCount > 0)
221703
- buf += `
221704
- `;
221705
- process.stderr.write(buf);
221706
- previousLineCount = frame.split(`
221707
- `).length;
221708
- };
221709
- }
221710
- function defaultSleep(ms) {
221711
- return new Promise((resolve) => setTimeout(resolve, ms));
221712
- }
221713
- function snapshotsDiffer(a, b) {
221714
- if (a.status !== b.status)
221715
- return true;
221716
- const aSteps = a.stepExecutions ?? [];
221717
- const bSteps = b.stepExecutions ?? [];
221718
- if (aSteps.length !== bSteps.length)
221719
- return true;
221720
- for (let i = 0;i < aSteps.length; i++) {
221721
- if (aSteps[i].stepName !== bSteps[i].stepName || aSteps[i].status !== bSteps[i].status) {
221722
- return true;
221723
- }
221724
- }
221725
- return false;
221726
- }
221727
- function defaultShouldAbort(err) {
221728
- return err instanceof ApiError && err.status >= 400 && err.status < 500;
221729
- }
221730
- async function watchExecution(opts) {
221731
- const sleep = opts.sleep ?? defaultSleep;
221732
- const now = opts.now ?? (() => Date.now());
221733
- const render = opts.render ?? makeAnsiRenderer();
221734
- const maxMs = opts.maxMs ?? 30 * 60 * 1000;
221735
- const transitionInterval = opts.transitionIntervalMs ?? 2000;
221736
- const steadyInterval = opts.steadyIntervalMs ?? 5000;
221737
- const shouldAbort = opts.shouldAbort ?? defaultShouldAbort;
221738
- const start = now();
221739
- let previous;
221740
- let lastFetched;
221741
- while (true) {
221742
- let current;
221743
- try {
221744
- current = await opts.fetch();
221745
- } catch (err) {
221746
- if (shouldAbort(err))
221747
- throw err;
221748
- const message = err instanceof Error ? err.message : String(err);
221749
- render(`(network) ${message.slice(0, 120)}`);
221750
- if (lastFetched && now() - start >= maxMs) {
221751
- return { final: lastFetched, detached: true };
221752
- }
221753
- await sleep(steadyInterval);
221754
- continue;
221755
- }
221756
- lastFetched = current;
221757
- render(renderFrame(current));
221758
- if (isTerminalExecutionStatus(current.status)) {
221759
- return { final: current, detached: false };
221760
- }
221761
- if (now() - start >= maxMs) {
221762
- return { final: current, detached: true };
221763
- }
221764
- const transitioned = previous == null || snapshotsDiffer(previous, current);
221765
- previous = current;
221766
- await sleep(transitioned ? transitionInterval : steadyInterval);
221767
- }
221768
- }
221769
-
221770
221990
  // ../common/src/office-placeholder-inspect.ts
221771
221991
  var import_pizzip = __toESM(require_js(), 1);
221772
221992
  var SHARED_STRING_ITEM_RE = /<si\b[^>]*>([\s\S]*?)<\/si>/gi;
@@ -249325,7 +249545,7 @@ function extractXlsxComparableText(filePath) {
249325
249545
  init_src();
249326
249546
 
249327
249547
  // src/lib/execution-artifacts.ts
249328
- import { existsSync as existsSync11, mkdirSync as mkdirSync4, readdirSync as readdirSync3, readFileSync as readFileSync11, writeFileSync as writeFileSync6 } from "fs";
249548
+ import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync6 } from "fs";
249329
249549
  import { join as join5 } from "path";
249330
249550
 
249331
249551
  // src/lib/format.ts
@@ -249509,22 +249729,13 @@ function gradeAgainstExpected(expected, actual) {
249509
249729
  }
249510
249730
 
249511
249731
  // src/lib/payload.ts
249512
- import { existsSync as existsSync12, readdirSync as readdirSync4, readFileSync as readFileSync12, statSync as statSync3 } from "fs";
249513
- import { join as join7 } from "path";
249514
-
249515
- // src/lib/fs-helpers.ts
249516
- init_src();
249517
- import { extname as extname3, join as join6 } from "path";
249518
- function guessMimeType(filename) {
249519
- return mimeTypeForExtension(extname3(filename)) ?? "";
249520
- }
249521
-
249522
- // src/lib/payload.ts
249732
+ import { existsSync as existsSync10 } from "fs";
249733
+ import { join as join6 } from "path";
249523
249734
  var DATASET_EXAMPLES_DIR = ["dataset", "examples"];
249524
249735
  function resolveEvalBaseDir(dir) {
249525
- const candidates = [join7(dir, ...DATASET_EXAMPLES_DIR), join7(...DATASET_EXAMPLES_DIR)];
249736
+ const candidates = [join6(dir, ...DATASET_EXAMPLES_DIR), join6(...DATASET_EXAMPLES_DIR)];
249526
249737
  for (const candidate of candidates) {
249527
- if (existsSync12(candidate))
249738
+ if (existsSync10(candidate))
249528
249739
  return candidate;
249529
249740
  }
249530
249741
  return null;
@@ -249544,7 +249755,7 @@ function resolveEvalGraceMs() {
249544
249755
  var EVAL_GRACE_MS = resolveEvalGraceMs();
249545
249756
  var EVAL_POLL_INTERVAL_MS = 2000;
249546
249757
  var EXAMPLE_PAGE_SIZE = 100;
249547
- var TERMINAL = new Set(["completed", "failed", "cancelled", "rejected", "timeout"]);
249758
+ var TERMINAL = new Set(["completed", "failed", "cancelled", "rejected"]);
249548
249759
  function fmtScore(score) {
249549
249760
  return typeof score === "number" ? score.toFixed(2) : "n/a";
249550
249761
  }
@@ -249584,19 +249795,20 @@ async function resolveExample(client, workflowId, name) {
249584
249795
  }
249585
249796
  }
249586
249797
  async function pollRunTerminal(client, runId, intervalMs, maxWaitMs) {
249587
- const start = Date.now();
249588
249798
  const base = `/v1/runs/${encodeURIComponent(runId)}`;
249589
- for (;; ) {
249590
- const run = await client.get(base);
249591
- const status = run.execution?.status ?? run.status;
249592
- if (run.finished || status && TERMINAL.has(status)) {
249593
- return await client.get(`${base}?expand=execution`);
249594
- }
249595
- if (Date.now() - start > maxWaitMs) {
249596
- return { ...run, status: "timeout", execution: { status: "timeout" } };
249597
- }
249598
- await new Promise((r) => setTimeout(r, intervalMs));
249799
+ const { timedOut } = await pollUntil({
249800
+ fetch: async () => await client.get(base),
249801
+ isTerminal: (run) => {
249802
+ const status = run.execution?.status ?? run.status;
249803
+ return Boolean(run.finished) || Boolean(status && TERMINAL.has(status));
249804
+ },
249805
+ intervalMs,
249806
+ maxWaitMs
249807
+ });
249808
+ if (timedOut) {
249809
+ throw new Error(`Timed out after ${Math.round(maxWaitMs / 1000)}s waiting for run ${runId}`);
249599
249810
  }
249811
+ return await client.get(`${base}?expand=execution`);
249600
249812
  }
249601
249813
  async function pollEvalRollup(client, runId) {
249602
249814
  const start = Date.now();
@@ -249887,7 +250099,7 @@ async function runExample(agentId, opts) {
249887
250099
  if (opts.failOnMismatch && !opts.wait) {
249888
250100
  throw new Error("--fail-on-mismatch requires --wait because the evaluator verdict is asynchronous");
249889
250101
  }
249890
- const client = buildClient2(opts);
250102
+ const client = buildClient(opts);
249891
250103
  const started = await client.post(`/v1/automations/${encodeURIComponent(agentAutomationId(agentId))}/experiments`, {
249892
250104
  examples: [opts.example],
249893
250105
  ...opts.sourceRef ? { sourceRef: opts.sourceRef } : {}
@@ -249941,7 +250153,7 @@ async function runExample(agentId, opts) {
249941
250153
  status: "pending"
249942
250154
  };
249943
250155
  if (opts.json)
249944
- return printJson2(payload);
250156
+ return printJson(payload);
249945
250157
  success(`Run ${runId ?? ""} queued for example ${opts.example}`);
249946
250158
  }
249947
250159
  async function waitForExampleEvalRollup(client, agentId, runId, sourceRef) {
@@ -250025,7 +250237,7 @@ function projectionIncludeSource(opts) {
250025
250237
  return parts.length > 0 ? parts.join(",") : undefined;
250026
250238
  }
250027
250239
  var STEP_HYDRATE_CONCURRENCY = 8;
250028
- async function mapPool(items, concurrency, fn) {
250240
+ async function mapPool2(items, concurrency, fn) {
250029
250241
  const out = new Array(items.length);
250030
250242
  let next = 0;
250031
250243
  async function worker() {
@@ -250039,7 +250251,7 @@ async function mapPool(items, concurrency, fn) {
250039
250251
  return out;
250040
250252
  }
250041
250253
  async function hydrateWorkflowStepPayloads(client, runId, steps) {
250042
- return mapPool(steps, STEP_HYDRATE_CONCURRENCY, async (step) => {
250254
+ return mapPool2(steps, STEP_HYDRATE_CONCURRENCY, async (step) => {
250043
250255
  const stepId = typeof step.id === "string" ? step.id : null;
250044
250256
  if (!stepId) {
250045
250257
  throw new Error(`Cannot load step payloads for ${step.stepName ?? "unknown step"}: missing step execution id.`);
@@ -250068,7 +250280,7 @@ function wantsWorkflowStepPayloads(includes) {
250068
250280
  ].some((field) => wanted.has(field));
250069
250281
  }
250070
250282
  async function getRun(executionId, opts) {
250071
- const client = buildClient2(opts);
250283
+ const client = buildClient(opts);
250072
250284
  const run = toLegacyRunView(await client.get(`/v1/runs/${encodeURIComponent(executionId)}`, {
250073
250285
  expand: serverExpandParam({ expand: opts.expand, include: opts.include })
250074
250286
  }));
@@ -250083,10 +250295,10 @@ async function getRun(executionId, opts) {
250083
250295
  }
250084
250296
  const projectedRun = opts.step || wantsWorkflowStepPayloads(projectionIncludes) ? { ...run, stepExecutions: projectWorkflowSteps(steps, projectionIncludes) } : { ...run, stepExecutions: steps };
250085
250297
  if (opts.select) {
250086
- return printJson2(selectJsonValue(projectedRun, opts.select));
250298
+ return printJson(selectJsonValue(projectedRun, opts.select));
250087
250299
  }
250088
250300
  if (opts.json) {
250089
- return printJson2(projectedRun);
250301
+ return printJson(projectedRun);
250090
250302
  }
250091
250303
  console.log(renderFrame(toExecutionSnapshot(projectedRun, executionId)));
250092
250304
  process.stderr.write(`${ui.dim(`use --json for the full payload, then pipe to jq for field projection`)}
@@ -250094,7 +250306,7 @@ async function getRun(executionId, opts) {
250094
250306
  return;
250095
250307
  }
250096
250308
  if (opts.select)
250097
- return printJson2(selectJsonValue(run, opts.select));
250309
+ return printJson(selectJsonValue(run, opts.select));
250098
250310
  renderRunPayload(run, opts);
250099
250311
  }
250100
250312
  function isWorkflowRun(run) {
@@ -250108,26 +250320,21 @@ function toLegacyRunView(run) {
250108
250320
  const source = objectOrNull2(run.source);
250109
250321
  const sourceGit = objectOrNull2(source?.git);
250110
250322
  const trigger = objectOrNull2(run.trigger);
250111
- const lineage = objectOrNull2(run.lineage);
250112
250323
  const execution = objectOrNull2(run.execution);
250113
- const legacyRetry = objectOrNull2(lineage?.retry);
250114
- const retry = objectOrNull2(execution?.retry) ?? legacyRetry;
250324
+ const retry = objectOrNull2(execution?.retry);
250115
250325
  const nextRun = objectOrNull2(retry?.nextRun);
250116
250326
  const evalInfo = objectOrNull2(run.eval);
250117
- const result = objectOrNull2(run.result);
250118
250327
  const input = objectOrNull2(run.input);
250119
250328
  const usage = objectOrNull2(run.usage);
250120
250329
  const tokens = objectOrNull2(usage?.tokens);
250121
250330
  const executionFiles = objectOrNull2(execution?.files);
250122
250331
  const executionExpected = objectOrNull2(execution?.expected);
250123
250332
  const debug = objectOrNull2(run.debug);
250124
- const hasGroupedShape = timing != null || source != null || result != null || run.output !== undefined;
250333
+ const hasGroupedShape = timing != null || source != null || run.output !== undefined;
250125
250334
  if (!hasGroupedShape)
250126
250335
  return run;
250127
- const terminalOutput = run.output !== undefined ? run.output : result?.output;
250128
- const terminalFiles = run.files !== undefined ? run.files : result?.files ?? executionFiles?.output;
250129
- const terminalError = runErrorMessage(run.error !== undefined ? run.error : result?.error);
250130
- const terminalSchemaValid = execution?.schemaValid !== undefined ? execution.schemaValid : result?.schemaValid;
250336
+ const terminalFiles = run.files !== undefined ? run.files : executionFiles?.output;
250337
+ const terminalError = runErrorMessage(run.error);
250131
250338
  return {
250132
250339
  ...run,
250133
250340
  createdAt: timing?.createdAt,
@@ -250148,19 +250355,19 @@ function toLegacyRunView(run) {
250148
250355
  triggerType: trigger?.type,
250149
250356
  triggeredBy: trigger?.by,
250150
250357
  emailTrigger: trigger?.email,
250151
- batchId: execution?.batchId ?? lineage?.batchId,
250358
+ batchId: execution?.batchId,
250152
250359
  retryNumber: retry?.number,
250153
250360
  previousExecutionId: retry?.previousRunId,
250154
- annotation: execution?.annotation ?? lineage?.annotation,
250361
+ annotation: execution?.annotation,
250155
250362
  exampleId: evalInfo?.exampleId ?? evalInfo?.example,
250156
250363
  exampleName: evalInfo?.example,
250157
250364
  status: execution?.status ?? run.status,
250158
250365
  finished: run.finished,
250159
250366
  evalScore: evalInfo?.score,
250160
250367
  evalPassed: evalInfo?.passed,
250161
- output: terminalOutput,
250368
+ output: run.output,
250162
250369
  resultFiles: terminalFiles,
250163
- schemaValid: terminalSchemaValid,
250370
+ schemaValid: execution?.schemaValid,
250164
250371
  error: terminalError,
250165
250372
  input: input?.args,
250166
250373
  inputFiles: input?.files,
@@ -250275,7 +250482,7 @@ function previewOutput(value) {
250275
250482
  return flat.length > PREVIEW_MAX ? `${flat.slice(0, PREVIEW_MAX - 3)}...` : flat;
250276
250483
  }
250277
250484
  async function rerunRun(executionId, opts) {
250278
- const client = buildClient2(opts);
250485
+ const client = buildClient(opts);
250279
250486
  const params = new URLSearchParams;
250280
250487
  const version = (opts.sourceRef ?? opts.version)?.trim();
250281
250488
  if (version && version !== "latest") {
@@ -250295,21 +250502,21 @@ async function rerunRun(executionId, opts) {
250295
250502
  return;
250296
250503
  }
250297
250504
  if (opts.json)
250298
- return printJson2(payload);
250505
+ return printJson(payload);
250299
250506
  success(`Started rerun ${ui.bold(rerunId)} from ${executionId}`);
250300
250507
  }
250301
250508
  async function promoteRun(executionId, opts) {
250302
- const client = buildClient2(opts);
250509
+ const client = buildClient(opts);
250303
250510
  const body = {};
250304
250511
  if (opts.name)
250305
250512
  body.name = opts.name;
250306
250513
  const payload = await client.post(`/v1/runs/${encodeURIComponent(executionId)}/promote`, body);
250307
250514
  if (opts.json)
250308
- return printJson2(payload);
250515
+ return printJson(payload);
250309
250516
  success(`Promoted ${executionId} to example ${ui.bold(payload.name ?? payload.exampleId ?? "")}` + `${payload.automationId ? ` on ${payload.automationType ?? ""} ${payload.automationId}`.trimEnd() : ""}`);
250310
250517
  }
250311
250518
  async function fetchRunArtifacts(executionId, opts) {
250312
- const client = buildClient2(opts);
250519
+ const client = buildClient(opts);
250313
250520
  const baseRun = toLegacyRunView(await client.get(`/v1/runs/${encodeURIComponent(executionId)}`, {
250314
250521
  expand: "input,execution"
250315
250522
  }));
@@ -250342,7 +250549,7 @@ async function fetchRunArtifacts(executionId, opts) {
250342
250549
  }
250343
250550
  };
250344
250551
  if (opts.json)
250345
- return printJson2(summary);
250552
+ return printJson(summary);
250346
250553
  success(`Fetched run artifacts for ${executionId} to ${out}`);
250347
250554
  dim(`Wrote ${written.length} artifact${written.length === 1 ? "" : "s"}${skipped.length ? `; skipped missing ${skipped.join(", ")}` : ""}`);
250348
250555
  }
@@ -250377,7 +250584,7 @@ async function inspectRunArtifact(runId, artifactPathArg, opts) {
250377
250584
  if (source.kind === "local") {
250378
250585
  buffer = await fs16.readFile(source.path);
250379
250586
  } else {
250380
- const client = buildClient2(opts);
250587
+ const client = buildClient(opts);
250381
250588
  const response = await client.getStream(`/v1/runs/${encodeURIComponent(source.runId)}/artifacts/${encodeRunArtifactPath(source.artifactPath)}`);
250382
250589
  buffer = Buffer.from(await response.arrayBuffer());
250383
250590
  }
@@ -250386,13 +250593,13 @@ async function inspectRunArtifact(runId, artifactPathArg, opts) {
250386
250593
  ...source.kind === "local" ? { file: source.path } : { runId: source.runId, artifactPath: source.artifactPath },
250387
250594
  ...inspect
250388
250595
  };
250389
- printJson2(payload);
250596
+ printJson(payload);
250390
250597
  }
250391
250598
  async function listRunArtifacts(executionId, opts) {
250392
- const client = buildClient2(opts);
250599
+ const client = buildClient(opts);
250393
250600
  const artifacts = await listCanonicalRunArtifacts(client, executionId);
250394
250601
  if (opts.json)
250395
- return printJson2({ runId: executionId, artifacts });
250602
+ return printJson({ runId: executionId, artifacts });
250396
250603
  console.log(table(artifacts, [
250397
250604
  { key: "kind", header: "KIND" },
250398
250605
  { key: "name", header: "NAME" },
@@ -250503,7 +250710,7 @@ async function writeRunArtifact(client, executionId, out, artifactPath, run) {
250503
250710
  return artifactPath;
250504
250711
  }
250505
250712
  async function traceRun(executionId, opts) {
250506
- const client = buildClient2(opts);
250713
+ const client = buildClient(opts);
250507
250714
  const text = await downloadTraceText(client, executionId);
250508
250715
  if (text.length === 0) {
250509
250716
  warn(`No trace events recorded for run ${executionId}.`);
@@ -250518,7 +250725,7 @@ async function traceRun(executionId, opts) {
250518
250725
  success(`Downloaded trace for ${executionId} to ${ui.bold(out)}`);
250519
250726
  }
250520
250727
  async function compareRun(referenceId, executionId, opts) {
250521
- const client = buildClient2(opts);
250728
+ const client = buildClient(opts);
250522
250729
  const target = toLegacyRunView(await client.get(`/v1/runs/${encodeURIComponent(executionId)}`, {
250523
250730
  expand: "execution"
250524
250731
  }));
@@ -250533,7 +250740,7 @@ async function compareRun(referenceId, executionId, opts) {
250533
250740
  ]);
250534
250741
  const report = compareWorkflowRuns(referenceId, { ...reference, stepExecutions: hydratedReferenceSteps }, executionId, { ...target, stepExecutions: hydratedTargetSteps }, opts.step);
250535
250742
  if (opts.json) {
250536
- printJson2(report);
250743
+ printJson(report);
250537
250744
  } else {
250538
250745
  renderWorkflowComparisonReport(report);
250539
250746
  }
@@ -250572,7 +250779,7 @@ async function compareRun(referenceId, executionId, opts) {
250572
250779
  };
250573
250780
  await fs16.writeFile(path15.join(out, "comparison.json"), JSON.stringify(report, null, 2));
250574
250781
  if (opts.json) {
250575
- printJson2(report);
250782
+ printJson(report);
250576
250783
  } else {
250577
250784
  renderComparisonReport(report);
250578
250785
  }
@@ -250689,7 +250896,7 @@ function compareOutputs(reference, target) {
250689
250896
  return `differs (A=${referenceJson.length}b, B=${targetJson.length}b)`;
250690
250897
  }
250691
250898
  async function listRuns(source, opts) {
250692
- const client = buildClient2(opts);
250899
+ const client = buildClient(opts);
250693
250900
  const parsedAgentTarget = source && (opts.type === "agent" || source.startsWith("agents.") || source.includes("@")) ? parseAgentTarget(source) : null;
250694
250901
  const resolvedWorkflowSource = source && opts.type === "workflow" ? await resolveWorkflowId(client, source) : undefined;
250695
250902
  const params = {
@@ -250700,7 +250907,7 @@ async function listRuns(source, opts) {
250700
250907
  const payload = await client.get("/v1/runs", params);
250701
250908
  const viewRuns = payload.runs.map(toLegacyRunView);
250702
250909
  if (opts.json)
250703
- return printJson2({ ...payload, runs: viewRuns });
250910
+ return printJson({ ...payload, runs: viewRuns });
250704
250911
  const rows = opts.compact ? viewRuns.map(compactRunRow) : viewRuns;
250705
250912
  if (payload.scanLimited)
250706
250913
  warn("Filtered run list scanned only the first matching window.");
@@ -250746,7 +250953,7 @@ function buildRunListParams(opts) {
250746
250953
  });
250747
250954
  }
250748
250955
  async function updateRunReview(executionId, opts) {
250749
- const client = buildClient2(opts);
250956
+ const client = buildClient(opts);
250750
250957
  const body = {};
250751
250958
  if (opts.status)
250752
250959
  body.status = opts.status;
@@ -250768,7 +250975,7 @@ async function updateRunReview(executionId, opts) {
250768
250975
  renderGeneric(payload, opts, `Updated review for ${executionId}`);
250769
250976
  }
250770
250977
  async function closeRunReview(executionId, opts) {
250771
- const client = buildClient2(opts);
250978
+ const client = buildClient(opts);
250772
250979
  const body = { status: opts.status ?? "closed" };
250773
250980
  if (opts.noteFile)
250774
250981
  body.note = await fs16.readFile(opts.noteFile, "utf-8");
@@ -250801,7 +251008,7 @@ async function clearRunReview(executionId, opts) {
250801
251008
  actionName: "clear review artifacts",
250802
251009
  cancelledMessage: "Clear cancelled"
250803
251010
  });
250804
- const client = buildClient2(opts);
251011
+ const client = buildClient(opts);
250805
251012
  const payload = await client.delete(`/v1/runs/${encodeURIComponent(executionId)}/reviews`);
250806
251013
  renderGeneric(payload, opts, `Cleared review for ${executionId}`);
250807
251014
  }
@@ -250815,16 +251022,16 @@ async function readRunExpected(client, executionId) {
250815
251022
  };
250816
251023
  }
250817
251024
  async function listRunExpected(executionId, opts) {
250818
- const client = buildClient2(opts);
251025
+ const client = buildClient(opts);
250819
251026
  const payload = await readRunExpected(client, executionId);
250820
251027
  if (opts.json)
250821
- return printJson2(payload);
251028
+ return printJson(payload);
250822
251029
  console.log(table(payload.files, [{ key: "name", header: "NAME" }]));
250823
251030
  if (payload.expected != null)
250824
251031
  dim("expected.json present");
250825
251032
  }
250826
251033
  async function pullRunExpected(executionId, opts) {
250827
- const client = buildClient2(opts);
251034
+ const client = buildClient(opts);
250828
251035
  const payload = await readRunExpected(client, executionId);
250829
251036
  const out = path15.resolve(opts.out ?? path15.join(executionId, "expected"));
250830
251037
  await fs16.mkdir(out, { recursive: true });
@@ -250848,7 +251055,7 @@ async function downloadExpectedFiles(client, executionId, out, files) {
250848
251055
  return written.filter((name) => Boolean(name));
250849
251056
  }
250850
251057
  async function uploadRunExpected(executionId, file, opts) {
250851
- const client = buildClient2(opts);
251058
+ const client = buildClient(opts);
250852
251059
  const form = new FormData;
250853
251060
  const data = await fs16.readFile(file);
250854
251061
  form.append("file", new Blob([data]), path15.basename(file));
@@ -250858,7 +251065,7 @@ async function uploadRunExpected(executionId, file, opts) {
250858
251065
  renderGeneric(payload, opts, `Uploaded expected file for ${executionId}`);
250859
251066
  }
250860
251067
  async function copyOutputToExpected(executionId, outputFile, opts) {
250861
- const client = buildClient2(opts);
251068
+ const client = buildClient(opts);
250862
251069
  const payload = await client.post(`/v1/runs/${encodeURIComponent(executionId)}/reviews/expected`, {
250863
251070
  outputFileName: outputFile,
250864
251071
  ...opts.name ? { expectedName: opts.name } : {}
@@ -250866,7 +251073,7 @@ async function copyOutputToExpected(executionId, outputFile, opts) {
250866
251073
  renderGeneric(payload, opts, `Copied output file to expected for ${executionId}`);
250867
251074
  }
250868
251075
  async function renameRunExpected(executionId, oldName, newName, opts) {
250869
- const client = buildClient2(opts);
251076
+ const client = buildClient(opts);
250870
251077
  const payload = await client.patch(`/v1/runs/${encodeURIComponent(executionId)}/reviews/expected/${encodeURIComponent(oldName)}`, { name: newName });
250871
251078
  renderGeneric(payload, opts, `Renamed expected file for ${executionId}`);
250872
251079
  }
@@ -250877,12 +251084,12 @@ async function deleteRunExpected(executionId, name, opts) {
250877
251084
  actionName: "delete expected file",
250878
251085
  cancelledMessage: "Delete cancelled"
250879
251086
  });
250880
- const client = buildClient2(opts);
251087
+ const client = buildClient(opts);
250881
251088
  await client.delete(`/v1/runs/${encodeURIComponent(executionId)}/reviews/expected/${encodeURIComponent(name)}`);
250882
251089
  renderGeneric({ ok: true }, opts, `Deleted expected file ${name}`);
250883
251090
  }
250884
251091
  async function watchRunCommand(executionId, opts) {
250885
- const client = buildClient2(opts);
251092
+ const client = buildClient(opts);
250886
251093
  if (opts.json) {
250887
251094
  const payload = await pollRun(client, executionId, opts.interval, opts.maxWait, opts.json);
250888
251095
  renderRunPayload(payload, opts);
@@ -250912,10 +251119,10 @@ Detached after ${opts.maxWait}s without reaching terminal status. Re-run \`eigen
250912
251119
  }
250913
251120
  async function cancelRun(executionId, opts) {
250914
251121
  requireYesInNonInteractive(opts.yes, "Cancel run");
250915
- const client = buildClient2(opts);
251122
+ const client = buildClient(opts);
250916
251123
  const payload = await client.post(`/v1/runs/${encodeURIComponent(executionId)}/cancel`, {});
250917
251124
  if (opts.json) {
250918
- printJson2(payload);
251125
+ printJson(payload);
250919
251126
  return;
250920
251127
  }
250921
251128
  success(`Cancellation requested for run ${executionId}.`);
@@ -251112,7 +251319,7 @@ async function downloadStreamToFile(client, url, target) {
251112
251319
  function extractComparableText(file) {
251113
251320
  const ext = path15.extname(file).toLowerCase();
251114
251321
  if ([".txt", ".md", ".json", ".csv", ".xml"].includes(ext)) {
251115
- return { text: readFileSync13(file, "utf8") };
251322
+ return { text: readFileSync11(file, "utf8") };
251116
251323
  }
251117
251324
  if (ext === ".xlsx" || ext === ".xls") {
251118
251325
  return extractXlsxComparableText(file);
@@ -251196,7 +251403,7 @@ agent id (for example \`agents.invoice\`) to confirm.
251196
251403
  async function deleteAgent(agentRef, opts) {
251197
251404
  requireYesInNonInteractive(opts.yes, "delete agent");
251198
251405
  const automationId = agentAutomationId(agentRef);
251199
- const client = buildClient2(opts);
251406
+ const client = buildClient(opts);
251200
251407
  const automation = await fetchAutomation(client, automationId);
251201
251408
  if (automation.type != null && automation.type !== "agent") {
251202
251409
  throw new Error(`${automationId} is a workflow, not an agent. Use \`eigenpal workflow delete\` instead.`);
@@ -251214,19 +251421,19 @@ async function deleteAgent(agentRef, opts) {
251214
251421
  const result = await client.delete(`/v1/automations/${encodeURIComponent(automationId)}`);
251215
251422
  const parsed = parseAutomationDeleteResult(result);
251216
251423
  if (opts.json) {
251217
- printJson2({ ...parsed, id: automationId, slug: automation.slug ?? null });
251424
+ printJson({ ...parsed, id: automationId, slug: automation.slug ?? null });
251218
251425
  return;
251219
251426
  }
251220
251427
  success(`Deleted agent ${ui.bold(label)} ${ui.dim(`(${automationId})`)}`);
251221
251428
  }
251222
251429
  async function listAgents(opts) {
251223
- const client = buildClient2(opts);
251430
+ const client = buildClient(opts);
251224
251431
  const payload = await client.get("/v1/automations", {
251225
251432
  ...compactParams(opts),
251226
251433
  type: "agent"
251227
251434
  });
251228
251435
  if (opts.json)
251229
- return printJson2(payload);
251436
+ return printJson(payload);
251230
251437
  console.log(table(payload.data, [
251231
251438
  { key: "slug", header: "SLUG" },
251232
251439
  { key: "name", header: "NAME" },
@@ -251238,7 +251445,7 @@ async function validateAgentCommand(dir = ".", opts) {
251238
251445
  const root = path16.resolve(dir);
251239
251446
  const project = await validateAgentProject(root);
251240
251447
  const result = { ...project };
251241
- if (existsSync13(path16.join(root, "agent.ts"))) {
251448
+ if (existsSync11(path16.join(root, "agent.ts"))) {
251242
251449
  const source = await validateSourcePackage(root, resolveConfig(opts));
251243
251450
  result.valid = project.valid && source.valid;
251244
251451
  result.packagePath = source.packagePath;
@@ -251248,7 +251455,7 @@ async function validateAgentCommand(dir = ".", opts) {
251248
251455
  }
251249
251456
  }
251250
251457
  if (opts.json) {
251251
- printJson2(result);
251458
+ printJson(result);
251252
251459
  if (!result.valid)
251253
251460
  process.exit(1);
251254
251461
  return;
@@ -251777,7 +251984,7 @@ async function completion(shell, program) {
251777
251984
  }
251778
251985
 
251779
251986
  // src/commands/docs.ts
251780
- import { existsSync as existsSync14, readFileSync as readFileSync14 } from "node:fs";
251987
+ import { existsSync as existsSync12, readFileSync as readFileSync12 } from "node:fs";
251781
251988
  var docsCache = null;
251782
251989
  function bundledDocs() {
251783
251990
  if (docsCache)
@@ -251786,11 +251993,11 @@ function bundledDocs() {
251786
251993
  new URL("./docs-bundle.json", import.meta.url),
251787
251994
  new URL("../docs-bundle.json", import.meta.url)
251788
251995
  ];
251789
- const bundleUrl = candidates.find((candidate) => existsSync14(candidate));
251996
+ const bundleUrl = candidates.find((candidate) => existsSync12(candidate));
251790
251997
  if (!bundleUrl) {
251791
251998
  throw new Error("Bundled documentation asset is missing. Reinstall the Eigenpal CLI.");
251792
251999
  }
251793
- const parsed = JSON.parse(readFileSync14(bundleUrl, "utf8"));
252000
+ const parsed = JSON.parse(readFileSync12(bundleUrl, "utf8"));
251794
252001
  if (!Array.isArray(parsed.entries)) {
251795
252002
  throw new Error("Bundled documentation asset is invalid. Reinstall the Eigenpal CLI.");
251796
252003
  }
@@ -251840,7 +252047,7 @@ function registerDocsCommands(program) {
251840
252047
  addJsonFlag(command.command("list [prefix]")).description("List bundled documentation topics, optionally under a path prefix.").option("--source <source>", "Filter by public, agent-reference, or api").action(action(async (prefix, opts) => {
251841
252048
  const results = listDocs(prefix, opts.source);
251842
252049
  if (opts.json) {
251843
- printJson2(results.map(({ content: _content, ...doc }) => doc));
252050
+ printJson(results.map(({ content: _content, ...doc }) => doc));
251844
252051
  return;
251845
252052
  }
251846
252053
  console.log(table(results, [
@@ -251852,7 +252059,7 @@ function registerDocsCommands(program) {
251852
252059
  addJsonFlag(command.command("search <query>")).description("Search every public page and detailed agent reference.").option("--limit <n>", "Maximum matches", intArg, 20).action(action(async (query, opts) => {
251853
252060
  const results = searchDocs(query, opts.limit);
251854
252061
  if (opts.json) {
251855
- printJson2(results.map(({ content: _content, ...doc }) => doc));
252062
+ printJson(results.map(({ content: _content, ...doc }) => doc));
251856
252063
  return;
251857
252064
  }
251858
252065
  console.log(table(results.map((doc) => ({ ...doc, match: doc.snippet || doc.description })), [
@@ -251864,7 +252071,7 @@ function registerDocsCommands(program) {
251864
252071
  addJsonFlag(command.command("read <topic>")).description("Print one bundled documentation topic to stdout.").action(action(async (topic, opts) => {
251865
252072
  const doc = resolveDoc(topic);
251866
252073
  if (opts.json) {
251867
- printJson2(doc);
252074
+ printJson(doc);
251868
252075
  return;
251869
252076
  }
251870
252077
  process.stdout.write(doc.content.endsWith(`
@@ -251911,7 +252118,7 @@ function matchingSnippet(content, terms) {
251911
252118
 
251912
252119
  // src/lib/email-servers-cli.ts
251913
252120
  init_src();
251914
- import { existsSync as existsSync15, readFileSync as readFileSync15 } from "node:fs";
252121
+ import { readFileSync as readFileSync13 } from "node:fs";
251915
252122
  import { resolve as resolve4 } from "node:path";
251916
252123
  var SECRET_KEYS = new Set(["apiKey", "password", "caPem", "ciphertext"]);
251917
252124
  var SMTP_UPDATE_TARGET_FIELDS = ["host", "port", "security", "fromEmail", "fromName"];
@@ -251937,7 +252144,7 @@ function countTruthy(values) {
251937
252144
  function assertExclusiveConfigSource(explicitFieldCount, opts, command) {
251938
252145
  const configSources = countTruthy([opts.configJson, opts.configFile]);
251939
252146
  if (configSources > 1) {
251940
- throw new Error("Pass only one of --config-json or --config-file.");
252147
+ throw new UsageError("Pass only one of --config-json or --config-file.");
251941
252148
  }
251942
252149
  if (configSources > 0 && explicitFieldCount > 0) {
251943
252150
  throw new Error(`${command} accepts either explicit flags or --config-json/--config-file, not both.`);
@@ -251952,10 +252159,10 @@ function readConfigObject(opts) {
251952
252159
  try {
251953
252160
  parsed = JSON.parse(opts.configJson);
251954
252161
  } catch {
251955
- throw new Error("--config-json must be valid JSON.");
252162
+ throw new UsageError("--config-json must be valid JSON.");
251956
252163
  }
251957
252164
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
251958
- throw new Error("--config-json must be a JSON object.");
252165
+ throw new UsageError("--config-json must be a JSON object.");
251959
252166
  }
251960
252167
  return parsed;
251961
252168
  }
@@ -251963,7 +252170,7 @@ function readConfigObject(opts) {
251963
252170
  const filePath = opts.configFile === "-" ? undefined : resolve4(opts.configFile);
251964
252171
  let raw;
251965
252172
  try {
251966
- raw = opts.configFile === "-" ? readFileSync15(0, "utf8") : readFileSync15(filePath, "utf8");
252173
+ raw = opts.configFile === "-" ? readFileSync13(0, "utf8") : readFileSync13(filePath, "utf8");
251967
252174
  } catch (err) {
251968
252175
  const code = err && typeof err === "object" && "code" in err ? String(err.code) : "";
251969
252176
  if (code === "ENOENT") {
@@ -251975,10 +252182,10 @@ function readConfigObject(opts) {
251975
252182
  try {
251976
252183
  parsed = JSON.parse(raw);
251977
252184
  } catch {
251978
- throw new Error("--config-file must contain a JSON object.");
252185
+ throw new UsageError("--config-file must contain a JSON object.");
251979
252186
  }
251980
252187
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
251981
- throw new Error("--config-file must contain a JSON object.");
252188
+ throw new UsageError("--config-file must contain a JSON object.");
251982
252189
  }
251983
252190
  return parsed;
251984
252191
  }
@@ -251997,12 +252204,12 @@ async function readSecretInput2(label, opts, required) {
251997
252204
  throw new Error(`Pass only one of --${label}-stdin or --${label}-file.`);
251998
252205
  }
251999
252206
  if (opts.stdin) {
252000
- return readFileSync15(0, "utf8").replace(/\n$/, "");
252207
+ return readFileSync13(0, "utf8").replace(/\n$/, "");
252001
252208
  }
252002
252209
  if (opts.file) {
252003
252210
  const filePath = opts.file === "-" ? undefined : resolve4(opts.file);
252004
252211
  try {
252005
- return (opts.file === "-" ? readFileSync15(0, "utf8") : readFileSync15(filePath, "utf8")).replace(/\n$/, "");
252212
+ return (opts.file === "-" ? readFileSync13(0, "utf8") : readFileSync13(filePath, "utf8")).replace(/\n$/, "");
252006
252213
  } catch (err) {
252007
252214
  const code = err && typeof err === "object" && "code" in err ? String(err.code) : "";
252008
252215
  if (code === "ENOENT") {
@@ -252026,7 +252233,7 @@ async function readSecretInput2(label, opts, required) {
252026
252233
  }
252027
252234
  function parseEnabled(opts) {
252028
252235
  if (opts.enabled && opts.disabled) {
252029
- throw new Error("Pass only one of --enabled or --disabled.");
252236
+ throw new UsageError("Pass only one of --enabled or --disabled.");
252030
252237
  }
252031
252238
  if (opts.disabled)
252032
252239
  return false;
@@ -252145,7 +252352,7 @@ async function buildUpdateRequest(input) {
252145
252352
  if (caPem !== undefined)
252146
252353
  body.caPem = caPem;
252147
252354
  if (Object.keys(body).length === 0) {
252148
- throw new Error("No changes requested. Pass fields to update or --config-json/--config-file.");
252355
+ throw new UsageError("No changes requested. Pass fields to update or --config-json/--config-file.");
252149
252356
  }
252150
252357
  assertCompleteSmtpUpdateTarget(body);
252151
252358
  if (body.transport === "resend" && existing.transport !== "resend" && body.apiKey === undefined) {
@@ -252232,14 +252439,6 @@ var LIST_COLUMNS = [
252232
252439
  format: (value) => formatTimestamp(value)
252233
252440
  }
252234
252441
  ];
252235
- function buildClient3(opts) {
252236
- const config = resolveConfig(opts);
252237
- requireApiKey(config);
252238
- return new ApiClient(config);
252239
- }
252240
- function printJson3(value) {
252241
- console.log(JSON.stringify(value, null, 2));
252242
- }
252243
252442
  function sharedCreateOptions(cmd) {
252244
252443
  return cmd.option("--config-json <json>", "JSON object (non-secret fields only; use secret *-stdin/*-file flags)").option("--config-file <path>", "JSON file path (`-` reads stdin; non-secret fields only)").option("--name <name>", "Display name").option("--transport <kind>", "Transport: resend or smtp").option("--from-email <email>", "From address").option("--from-name <name>", "From display name (no control characters or <>)").option("--enabled", "Enable the server (default on create)").option("--disabled", "Disable the server").option("--host <host>", "SMTP host (required on update when --transport smtp)").option("--port <n>", "SMTP port. Required on update when --transport smtp; create defaults from --security", intArg).option("--security <mode>", "SMTP security: starttls, tls, or none (unauthenticated trusted relays; credentials are rejected). Required on update when --transport smtp; create defaults to starttls").option("--username <user>", "SMTP username (non-secret)").option("--api-key-stdin", "Read the Resend API key from stdin").option("--api-key-file <path>", "Read the Resend API key from a file (`-` for stdin)").option("--password-stdin", "Read the SMTP password from stdin").option("--password-file <path>", "Read the SMTP password from a file (`-` for stdin)").option("--ca-pem-stdin", "Read a custom SMTP CA PEM from stdin").option("--ca-pem-file <path>", "Read a custom SMTP CA PEM from a file (`-` for stdin)");
252245
252444
  }
@@ -252269,7 +252468,7 @@ function registerEmailServersCommands(program) {
252269
252468
  const emailServers = program.command("email-servers").alias("email-server").description("Manage outbound email servers (ems_…): list, inspect, create, update, delete, and send a real test message.").addHelpText("after", EMAIL_SERVERS_EXAMPLES);
252270
252469
  const listCmd = emailServers.command("list").description("List outbound email servers for the current workspace.");
252271
252470
  addJsonFlag(withBaseUrl(withPagination(listCmd))).action(action(async (opts) => {
252272
- const client = buildClient3(opts);
252471
+ const client = buildClient(opts);
252273
252472
  const raw = await client.get(apiPath("/email-servers"), {
252274
252473
  limit: String(opts.limit),
252275
252474
  offset: String(opts.offset)
@@ -252281,11 +252480,11 @@ function registerEmailServersCommands(program) {
252281
252480
  }));
252282
252481
  const getCmd = emailServers.command("get <id>").description("Inspect one email server. Human output is redacted even if the API regresses.");
252283
252482
  addJsonFlag(withBaseUrl(getCmd)).action(action(async (id, opts) => {
252284
- const client = buildClient3(opts);
252483
+ const client = buildClient(opts);
252285
252484
  const raw = await client.get(apiPath(`/email-servers/${encodeURIComponent(id)}`));
252286
252485
  const redacted = redactEmailServerPayload(raw);
252287
252486
  if (opts.json) {
252288
- printJson3(redacted);
252487
+ printJson(redacted);
252289
252488
  return;
252290
252489
  }
252291
252490
  console.log(formatEmailServerHuman(redacted));
@@ -252293,11 +252492,11 @@ function registerEmailServersCommands(program) {
252293
252492
  const createCmd = emailServers.command("create").description("Create an outbound email server. Resend requires an API key; SMTP accepts optional username/password except with --security none, plus optional CA PEM, and defaults to starttls on port 587.");
252294
252493
  addJsonFlag(withBaseUrl(sharedCreateOptions(createCmd))).action(action(async (opts) => {
252295
252494
  const body = await buildCreateRequest(opts);
252296
- const client = buildClient3(opts);
252495
+ const client = buildClient(opts);
252297
252496
  const created = await client.post(apiPath("/email-servers"), body);
252298
252497
  const redacted = redactEmailServerPayload(created);
252299
252498
  if (opts.json) {
252300
- printJson3(redacted);
252499
+ printJson(redacted);
252301
252500
  return;
252302
252501
  }
252303
252502
  success(`Created ${ui.bold(redacted.id)} (${redacted.transport})`);
@@ -252305,13 +252504,13 @@ function registerEmailServersCommands(program) {
252305
252504
  }));
252306
252505
  const updateCmd = emailServers.command("update <id>").description("Update metadata or replace transport configuration. Omitted secrets are retained. Passing --transport smtp requires --host, --port, --security, --from-email, and --from-name (no security/port defaults). Metadata-only updates omit --transport.");
252307
252506
  addJsonFlag(withBaseUrl(sharedUpdateOptions(updateCmd))).action(action(async (id, opts) => {
252308
- const client = buildClient3(opts);
252507
+ const client = buildClient(opts);
252309
252508
  const existing = await client.get(apiPath(`/email-servers/${encodeURIComponent(id)}`));
252310
252509
  const body = await buildUpdateRequest({ existing, opts });
252311
252510
  const updated = await client.patch(apiPath(`/email-servers/${encodeURIComponent(id)}`), body);
252312
252511
  const redacted = redactEmailServerPayload(updated);
252313
252512
  if (opts.json) {
252314
- printJson3(redacted);
252513
+ printJson(redacted);
252315
252514
  return;
252316
252515
  }
252317
252516
  success(`Updated ${ui.bold(redacted.id)}`);
@@ -252322,22 +252521,22 @@ function registerEmailServersCommands(program) {
252322
252521
  if (!opts.yes && !process.stdout.isTTY) {
252323
252522
  throw new Error("email-servers delete is destructive and requires --yes when run non-interactively");
252324
252523
  }
252325
- const client = buildClient3(opts);
252524
+ const client = buildClient(opts);
252326
252525
  const result = await client.delete(apiPath(`/email-servers/${encodeURIComponent(id)}`));
252327
252526
  if (opts.json) {
252328
- printJson3(result);
252527
+ printJson(result);
252329
252528
  return;
252330
252529
  }
252331
252530
  success(`Deleted ${ui.bold(id)}`);
252332
252531
  }));
252333
252532
  const testCmd = emailServers.command("test <id>").description("Send a real connectivity test email through the stored server to --to. Disabled servers fail with a conflict.").requiredOption("--to <email>", "Recipient for the live test message");
252334
252533
  addJsonFlag(withBaseUrl(testCmd)).action(action(async (id, opts) => {
252335
- const client = buildClient3(opts);
252534
+ const client = buildClient(opts);
252336
252535
  const result = await client.post(apiPath(`/email-servers/${encodeURIComponent(id)}/test`), {
252337
252536
  to: opts.to
252338
252537
  });
252339
252538
  if (opts.json) {
252340
- printJson3(result);
252539
+ printJson(result);
252341
252540
  if (!result.ok)
252342
252541
  process.exit(1);
252343
252542
  return;
@@ -252354,14 +252553,14 @@ function registerEmailServersCommands(program) {
252354
252553
  init_dist4();
252355
252554
  import {
252356
252555
  copyFileSync,
252357
- existsSync as existsSync16,
252556
+ existsSync as existsSync13,
252358
252557
  mkdirSync as mkdirSync5,
252359
- readdirSync as readdirSync5,
252360
- readFileSync as readFileSync16,
252361
- statSync as statSync4,
252558
+ readdirSync as readdirSync3,
252559
+ readFileSync as readFileSync14,
252560
+ statSync as statSync3,
252362
252561
  writeFileSync as writeFileSync7
252363
252562
  } from "node:fs";
252364
- import { dirname as dirname5, join as join8, relative as relative3, resolve as resolve5 } from "node:path";
252563
+ import { dirname as dirname5, join as join7, relative as relative3, resolve as resolve5 } from "node:path";
252365
252564
  import { fileURLToPath as fileURLToPath6 } from "node:url";
252366
252565
  var TEMPLATE_NAMES = [
252367
252566
  "blank",
@@ -252383,10 +252582,10 @@ function isValidProjectName(name) {
252383
252582
  function resolveTemplatesRoot() {
252384
252583
  const here = dirname5(fileURLToPath6(import.meta.url));
252385
252584
  const srcCandidate = resolve5(here, "..", "..", "templates");
252386
- if (existsSync16(srcCandidate))
252585
+ if (existsSync13(srcCandidate))
252387
252586
  return srcCandidate;
252388
252587
  const distCandidate = resolve5(here, "templates");
252389
- if (existsSync16(distCandidate))
252588
+ if (existsSync13(distCandidate))
252390
252589
  return distCandidate;
252391
252590
  throw new Error(`Cannot locate bundled templates. Looked in:
252392
252591
  ${srcCandidate}
@@ -252398,7 +252597,7 @@ async function init(name, opts) {
252398
252597
  }
252399
252598
  const target = resolve5(process.cwd(), opts.dir ?? name);
252400
252599
  assertSafeTargetDir(target, opts.dir);
252401
- if (existsSync16(target) && readdirSync5(target).length > 0) {
252600
+ if (existsSync13(target) && readdirSync3(target).length > 0) {
252402
252601
  throw new Error(`Target directory ${relative3(process.cwd(), target)} exists and is not empty.`);
252403
252602
  }
252404
252603
  let template;
@@ -252412,8 +252611,8 @@ async function init(name, opts) {
252412
252611
  } else {
252413
252612
  template = await promptForTemplate();
252414
252613
  }
252415
- const sourceRoot = join8(resolveTemplatesRoot(), template);
252416
- if (!existsSync16(sourceRoot)) {
252614
+ const sourceRoot = join7(resolveTemplatesRoot(), template);
252615
+ if (!existsSync13(sourceRoot)) {
252417
252616
  throw new Error(`Template directory missing on disk: ${sourceRoot}`);
252418
252617
  }
252419
252618
  const written = copyTemplate(sourceRoot, target, name);
@@ -252455,18 +252654,18 @@ function copyTemplate(src, dst, projectName) {
252455
252654
  const stack = [src];
252456
252655
  while (stack.length > 0) {
252457
252656
  const dir = stack.pop();
252458
- for (const entry of readdirSync5(dir)) {
252459
- const sourcePath = join8(dir, entry);
252657
+ for (const entry of readdirSync3(dir)) {
252658
+ const sourcePath = join7(dir, entry);
252460
252659
  const relativePath = relative3(src, sourcePath);
252461
- const targetPath = join8(dst, relativePath);
252462
- const stats = statSync4(sourcePath);
252660
+ const targetPath = join7(dst, relativePath);
252661
+ const stats = statSync3(sourcePath);
252463
252662
  if (stats.isDirectory()) {
252464
252663
  stack.push(sourcePath);
252465
252664
  continue;
252466
252665
  }
252467
252666
  mkdirSync5(dirname5(targetPath), { recursive: true });
252468
252667
  if (isTextFile(sourcePath)) {
252469
- const text = readFileSync16(sourcePath, "utf-8").replaceAll(PLACEHOLDER, projectName);
252668
+ const text = readFileSync14(sourcePath, "utf-8").replaceAll(PLACEHOLDER, projectName);
252470
252669
  writeFileSync7(targetPath, text);
252471
252670
  } else {
252472
252671
  copyFileSync(sourcePath, targetPath);
@@ -252563,250 +252762,11 @@ import { createReadStream } from "node:fs";
252563
252762
  import { stat as stat3 } from "node:fs/promises";
252564
252763
  import path17 from "node:path";
252565
252764
 
252566
- // src/lib/upload-presigned-multipart.ts
252567
- var MULTIPART_UPLOAD_CONCURRENCY = 4;
252568
- var MULTIPART_PART_MAX_RETRIES = 4;
252569
- var MULTIPART_PART_RETRY_BASE_MS = 250;
252570
- function expectedPartByteLength(totalSize, partSizeBytes, partNumber, partCount) {
252571
- if (!Number.isInteger(partNumber) || partNumber < 1 || partNumber > partCount) {
252572
- throw new Error(`partNumber must be an integer in [1, ${partCount}]`);
252573
- }
252574
- if (totalSize === 0)
252575
- return 0;
252576
- if (partNumber < partCount)
252577
- return partSizeBytes;
252578
- const remainder = totalSize % partSizeBytes;
252579
- return remainder === 0 ? partSizeBytes : remainder;
252580
- }
252581
- function partByteOffset(partSizeBytes, partNumber) {
252582
- return (partNumber - 1) * partSizeBytes;
252583
- }
252584
- function isTransientHttpStatus(status) {
252585
- return status === 408 || status === 429 || status >= 500 && status <= 599;
252586
- }
252587
- function filterStorageHeaders(headers, stripContentLength) {
252588
- return Object.fromEntries(Object.entries(headers ?? {}).filter(([name]) => stripContentLength ? name.toLowerCase() !== "content-length" : true));
252589
- }
252590
- function partIsAuthoritativelyComplete(listed, partNumber, expectedSize) {
252591
- const found = listed.find((part) => part.partNumber === partNumber);
252592
- if (!found)
252593
- return false;
252594
- return found.size === expectedSize;
252595
- }
252596
-
252597
- class PartUploadHttpError extends Error {
252598
- status;
252599
- constructor(status) {
252600
- super(`Storage part upload failed (${status})`);
252601
- this.status = status;
252602
- this.name = "PartUploadHttpError";
252603
- }
252604
- }
252605
- function isAbortError(error) {
252606
- return error instanceof Error && error.name === "AbortError" || typeof DOMException !== "undefined" && error instanceof DOMException && error.name === "AbortError";
252607
- }
252608
- function shouldAbortMultipartUploadSession(options) {
252609
- return !options.partsReady;
252610
- }
252611
- function multipartCompleteRetryHint(uploadId) {
252612
- return `Uploaded parts remain stored for ${uploadId}; retry complete and do not abort the session.`;
252613
- }
252614
- function annotateMultipartCompleteFailure(uploadId, error) {
252615
- const hint = multipartCompleteRetryHint(uploadId);
252616
- if (error instanceof Error) {
252617
- if (!error.message.includes("retry complete")) {
252618
- error.message = `${error.message} ${hint}`;
252619
- }
252620
- return error;
252621
- }
252622
- return new Error(`${String(error)} ${hint}`);
252623
- }
252624
- function isRetryablePartError(error, signal) {
252625
- if (signal?.aborted)
252626
- return false;
252627
- if (isAbortError(error))
252628
- return false;
252629
- if (error instanceof PartUploadHttpError)
252630
- return isTransientHttpStatus(error.status);
252631
- return true;
252632
- }
252633
- async function sleep(ms, signal) {
252634
- if (signal?.aborted)
252635
- throw abortError(signal);
252636
- await new Promise((resolve, reject) => {
252637
- const timer = setTimeout(resolve, ms);
252638
- const onAbort = () => {
252639
- clearTimeout(timer);
252640
- reject(abortError(signal));
252641
- };
252642
- signal?.addEventListener("abort", onAbort, { once: true });
252643
- });
252644
- }
252645
- function abortError(signal) {
252646
- if (signal?.reason instanceof Error)
252647
- return signal.reason;
252648
- return typeof DOMException !== "undefined" ? new DOMException("Upload aborted", "AbortError") : Object.assign(new Error("Upload aborted"), { name: "AbortError" });
252649
- }
252650
- async function mapPool2(items, concurrency, signal, worker) {
252651
- if (items.length === 0)
252652
- return;
252653
- let cursor = 0;
252654
- let firstError;
252655
- await Promise.all(Array.from({ length: Math.min(Math.max(1, concurrency), items.length) }, async () => {
252656
- while (firstError == null) {
252657
- if (signal?.aborted)
252658
- throw abortError(signal);
252659
- const index = cursor++;
252660
- if (index >= items.length)
252661
- return;
252662
- try {
252663
- await worker(items[index]);
252664
- } catch (error) {
252665
- firstError ??= error;
252666
- }
252667
- }
252668
- }));
252669
- if (firstError)
252670
- throw firstError;
252671
- }
252672
- async function uploadPresignedMultipartParts(options) {
252673
- const concurrency = options.concurrency ?? MULTIPART_UPLOAD_CONCURRENCY;
252674
- let uploadedBytes = 0;
252675
- const credited = new Set;
252676
- const credit = (partNumber, length) => {
252677
- if (credited.has(partNumber))
252678
- return;
252679
- credited.add(partNumber);
252680
- uploadedBytes += length;
252681
- options.onProgress?.(uploadedBytes, options.totalSize);
252682
- };
252683
- const pendingPartNumbers = async () => {
252684
- const listed = await options.listParts();
252685
- const pending = [];
252686
- for (let partNumber = 1;partNumber <= options.partCount; partNumber++) {
252687
- const length = expectedPartByteLength(options.totalSize, options.partSizeBytes, partNumber, options.partCount);
252688
- if (partIsAuthoritativelyComplete(listed, partNumber, length)) {
252689
- credit(partNumber, length);
252690
- continue;
252691
- }
252692
- pending.push(partNumber);
252693
- }
252694
- return pending;
252695
- };
252696
- const uploadOne = async (partNumber) => {
252697
- const length = expectedPartByteLength(options.totalSize, options.partSizeBytes, partNumber, options.partCount);
252698
- const start = partByteOffset(options.partSizeBytes, partNumber);
252699
- let lastError;
252700
- for (let attempt = 0;attempt <= MULTIPART_PART_MAX_RETRIES; attempt++) {
252701
- if (options.signal?.aborted)
252702
- throw abortError(options.signal);
252703
- try {
252704
- const signed = await options.presignPart(partNumber);
252705
- const partLength = Number.isInteger(signed.partSizeBytes) ? signed.partSizeBytes : length;
252706
- await options.putPart({
252707
- url: signed.url,
252708
- headers: signed.headers ?? {},
252709
- partNumber,
252710
- start,
252711
- length: partLength
252712
- });
252713
- credit(partNumber, length);
252714
- return;
252715
- } catch (error) {
252716
- lastError = error;
252717
- if (!isRetryablePartError(error, options.signal) || attempt === MULTIPART_PART_MAX_RETRIES) {
252718
- throw error;
252719
- }
252720
- await sleep(MULTIPART_PART_RETRY_BASE_MS * 2 ** attempt, options.signal);
252721
- }
252722
- }
252723
- throw lastError;
252724
- };
252725
- let pending = await pendingPartNumbers();
252726
- if (pending.length > 0) {
252727
- await mapPool2(pending, concurrency, options.signal, uploadOne);
252728
- }
252729
- pending = await pendingPartNumbers();
252730
- if (pending.length > 0) {
252731
- await mapPool2(pending, concurrency, options.signal, uploadOne);
252732
- pending = await pendingPartNumbers();
252733
- }
252734
- if (pending.length > 0) {
252735
- throw new Error(`Upload incomplete: ${pending.length} part(s) missing from storage before complete`);
252736
- }
252737
- }
252738
-
252739
- // src/lib/upload-app-chunked.ts
252740
- var HTTP_CHUNKED_MAX_RETRIES = 4;
252741
- var HTTP_CHUNKED_RETRY_BASE_MS = 250;
252742
- function expectedHttpChunkByteLength(totalSize, chunkSizeBytes, chunkIndex, chunkCount) {
252743
- if (!Number.isInteger(chunkIndex) || chunkIndex < 0 || chunkIndex >= chunkCount) {
252744
- throw new Error(`chunkIndex must be an integer in [0, ${chunkCount})`);
252745
- }
252746
- if (totalSize === 0)
252747
- return 0;
252748
- if (chunkIndex < chunkCount - 1)
252749
- return chunkSizeBytes;
252750
- const remainder = totalSize % chunkSizeBytes;
252751
- return remainder === 0 ? chunkSizeBytes : remainder;
252752
- }
252753
- function chunkByteOffset(chunkSizeBytes, chunkIndex) {
252754
- return chunkIndex * chunkSizeBytes;
252755
- }
252756
- function shouldAbortHttpChunkedUploadSession(options) {
252757
- return !options.chunksReady;
252758
- }
252759
- function httpChunkedCompleteRetryHint(uploadId) {
252760
- return `Uploaded chunks remain stored for ${uploadId}; retry complete and do not abort the session.`;
252761
- }
252762
- function annotateHttpChunkedCompleteFailure(uploadId, error) {
252763
- const hint = httpChunkedCompleteRetryHint(uploadId);
252764
- if (error instanceof Error) {
252765
- if (!error.message.includes("retry complete")) {
252766
- error.message = `${error.message} ${hint}`;
252767
- }
252768
- return error;
252769
- }
252770
- return new Error(`${String(error)} ${hint}`);
252771
- }
252772
-
252773
- class ChunkUploadHttpError extends Error {
252774
- status;
252775
- constructor(status) {
252776
- super(`Chunk upload failed (${status})`);
252777
- this.status = status;
252778
- this.name = "ChunkUploadHttpError";
252779
- }
252780
- }
252781
- function isRetryableChunkError(error) {
252782
- if (error instanceof ChunkUploadHttpError)
252783
- return isTransientHttpStatus(error.status);
252784
- return true;
252785
- }
252786
- async function uploadHttpChunks(options) {
252787
- for (let chunkIndex = 0;chunkIndex < options.chunkCount; chunkIndex++) {
252788
- const length = expectedHttpChunkByteLength(options.totalSize, options.chunkSizeBytes, chunkIndex, options.chunkCount);
252789
- const start = chunkByteOffset(options.chunkSizeBytes, chunkIndex);
252790
- let lastError;
252791
- for (let attempt = 0;attempt <= HTTP_CHUNKED_MAX_RETRIES; attempt++) {
252792
- try {
252793
- await options.putChunk({ chunkIndex, start, length });
252794
- lastError = undefined;
252795
- break;
252796
- } catch (error) {
252797
- lastError = error;
252798
- if (!isRetryableChunkError(error) || attempt === HTTP_CHUNKED_MAX_RETRIES) {
252799
- throw error;
252800
- }
252801
- await sleep2(HTTP_CHUNKED_RETRY_BASE_MS * 2 ** attempt);
252802
- }
252803
- }
252804
- if (lastError)
252805
- throw lastError;
252806
- }
252807
- }
252808
- function sleep2(ms) {
252809
- return new Promise((resolve) => setTimeout(resolve, ms));
252765
+ // src/lib/fs-helpers.ts
252766
+ init_src();
252767
+ import { extname as extname3, join as join8 } from "path";
252768
+ function guessMimeType(filename) {
252769
+ return mimeTypeForExtension(extname3(filename)) ?? "";
252810
252770
  }
252811
252771
 
252812
252772
  // src/lib/upload-reusable-file.ts
@@ -252961,45 +252921,6 @@ async function uploadPresignedMultipart(client, source, session) {
252961
252921
  throw annotateMultipartCompleteFailure(session.uploadId, error);
252962
252922
  }
252963
252923
  }
252964
- function destroyUnreadNodeReadable(stream) {
252965
- const readable = stream;
252966
- if (!readable.readableEnded && !readable.destroyed && typeof readable.destroy === "function") {
252967
- readable.destroy();
252968
- }
252969
- }
252970
- async function ensureNodeReadableFullySent(stream, expectedByteLength) {
252971
- const readable = stream;
252972
- if (readable.readableEnded) {
252973
- return expectedByteLength ?? 0;
252974
- }
252975
- if (readable.destroyed) {
252976
- throw new Error("Upload stream was destroyed before the request body finished sending");
252977
- }
252978
- let bytes = 0;
252979
- for await (const chunk of stream) {
252980
- bytes += typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk.length;
252981
- }
252982
- if (expectedByteLength !== undefined && bytes !== expectedByteLength) {
252983
- throw new Error(`Upload sent ${bytes} byte(s) but ${expectedByteLength} were expected for this part`);
252984
- }
252985
- return bytes;
252986
- }
252987
- function shouldAbortPresignedPutUploadSession(options) {
252988
- return !options.putReady;
252989
- }
252990
- function presignedPutCompleteRetryHint(uploadId) {
252991
- return `Uploaded object remains stored for ${uploadId}; retry complete and do not abort the session.`;
252992
- }
252993
- function annotatePresignedPutCompleteFailure(uploadId, error) {
252994
- const hint = presignedPutCompleteRetryHint(uploadId);
252995
- if (error instanceof Error) {
252996
- if (!error.message.includes("retry complete")) {
252997
- error.message = `${error.message} ${hint}`;
252998
- }
252999
- return error;
253000
- }
253001
- return new Error(`${String(error)} ${hint}`);
253002
- }
253003
252924
  async function putStorageObject(url, headers, body, options) {
253004
252925
  const stream = options.stream && isNodeReadableStream(body);
253005
252926
  const init = {
@@ -253142,20 +253063,12 @@ function formatReviewTaskDetail(task) {
253142
253063
  }
253143
253064
 
253144
253065
  // src/commands/reviews.ts
253145
- function buildClient4(opts) {
253146
- const config = resolveConfig(opts);
253147
- requireApiKey(config);
253148
- return new ApiClient(config);
253149
- }
253150
- function printJson4(value) {
253151
- console.log(JSON.stringify(value, null, 2));
253152
- }
253153
253066
  function taskPath(taskId, suffix = "") {
253154
253067
  return apiPath(`/human-reviews/${encodeURIComponent(taskId)}${suffix}`);
253155
253068
  }
253156
253069
  function renderTaskResult(task, json) {
253157
253070
  if (json) {
253158
- printJson4({ task });
253071
+ printJson({ task });
253159
253072
  return;
253160
253073
  }
253161
253074
  console.log(formatReviewTaskDetail(task));
@@ -253194,10 +253107,10 @@ function registerReviewsCommands(program) {
253194
253107
  withBaseUrl(reviews.command("download <task-id> <file-id>").description("Download one file attached to a review task.").requiredOption("--out <path>", "Write bytes to this file path")).action(action(downloadReviewFile));
253195
253108
  }
253196
253109
  async function listReviews(opts) {
253197
- const client = buildClient4(opts);
253110
+ const client = buildClient(opts);
253198
253111
  const payload = await client.get(apiPath("/human-reviews"), buildReviewListParams(opts));
253199
253112
  if (opts.json) {
253200
- printJson4(payload);
253113
+ printJson(payload);
253201
253114
  writeListHint(payload);
253202
253115
  return;
253203
253116
  }
@@ -253213,20 +253126,20 @@ function writeListHint(payload) {
253213
253126
  `);
253214
253127
  }
253215
253128
  async function getReview(taskId, opts) {
253216
- const client = buildClient4(opts);
253129
+ const client = buildClient(opts);
253217
253130
  const payload = await client.get(taskPath(taskId));
253218
253131
  renderTaskResult(payload.task, opts.json);
253219
253132
  }
253220
253133
  async function confirmReviewField(taskId, opts) {
253221
253134
  if (opts.value !== undefined && opts.valueJson !== undefined) {
253222
- throw new Error("Pass only one of --value or --value-json.");
253135
+ throw new UsageError("Pass only one of --value or --value-json.");
253223
253136
  }
253224
253137
  const rawValue = opts.valueJson ?? opts.value;
253225
253138
  if (rawValue === undefined) {
253226
- throw new Error("Missing field value. Pass --value <scalar> or --value-json <json>.");
253139
+ throw new UsageError("Missing field value. Pass --value <scalar> or --value-json <json>.");
253227
253140
  }
253228
253141
  const value = opts.valueJson !== undefined ? parseReviewJsonScalar(JSON.parse(opts.valueJson)) : parseReviewScalarValue(rawValue);
253229
- const client = buildClient4(opts);
253142
+ const client = buildClient(opts);
253230
253143
  const payload = await client.put(taskPath(taskId, "/fields"), {
253231
253144
  path: opts.path,
253232
253145
  value,
@@ -253235,40 +253148,40 @@ async function confirmReviewField(taskId, opts) {
253235
253148
  confirmed: opts.withdraw ? false : true
253236
253149
  });
253237
253150
  if (opts.json) {
253238
- printJson4(payload);
253151
+ printJson(payload);
253239
253152
  return;
253240
253153
  }
253241
253154
  success(`Updated ${ui.bold(payload.task.id)} (${payload.task.confirmedCount}/${payload.task.requiredCount} confirmed)`);
253242
253155
  console.log(formatReviewTaskSummary(payload.task));
253243
253156
  }
253244
253157
  async function approveReview(taskId, opts) {
253245
- const client = buildClient4(opts);
253158
+ const client = buildClient(opts);
253246
253159
  const payload = await client.post(taskPath(taskId, "/approve"), {
253247
253160
  expectedVersion: opts.expectedVersion
253248
253161
  });
253249
253162
  if (opts.json) {
253250
- printJson4(payload);
253163
+ printJson(payload);
253251
253164
  return;
253252
253165
  }
253253
253166
  success(`Approved ${ui.bold(payload.task.id)} · run ${payload.task.executionId} resumed`);
253254
253167
  console.log(formatReviewTaskSummary(payload.task));
253255
253168
  }
253256
253169
  async function rejectReview(taskId, opts) {
253257
- const client = buildClient4(opts);
253170
+ const client = buildClient(opts);
253258
253171
  const payload = await client.post(taskPath(taskId, "/reject"), {
253259
253172
  reason: opts.reason,
253260
253173
  expectedVersion: opts.expectedVersion,
253261
253174
  idempotencyKey: resolveReviewIdempotencyKey(opts.idempotencyKey)
253262
253175
  });
253263
253176
  if (opts.json) {
253264
- printJson4(payload);
253177
+ printJson(payload);
253265
253178
  return;
253266
253179
  }
253267
253180
  success(`Rejected ${ui.bold(payload.task.id)} · run ${payload.task.executionId} failed`);
253268
253181
  console.log(formatReviewTaskSummary(payload.task));
253269
253182
  }
253270
253183
  async function downloadReviewFile(taskId, fileId, opts) {
253271
- const client = buildClient4(opts);
253184
+ const client = buildClient(opts);
253272
253185
  const res = await client.getStream(taskPath(taskId, `/files/${encodeURIComponent(fileId)}/content`));
253273
253186
  const buf = Buffer.from(await res.arrayBuffer());
253274
253187
  await fs17.writeFile(opts.out, buf);
@@ -253283,36 +253196,8 @@ import { promises as fs18 } from "node:fs";
253283
253196
  import path18 from "node:path";
253284
253197
 
253285
253198
  // src/lib/upload-limits.ts
253286
- var DEFAULT_MULTIPART_MAX_BYTES = Math.floor(4.5 * 1024 * 1024);
253287
- var MULTIPART_ENVELOPE_HEADROOM_BYTES = 256 * 1024;
253288
- function multipartFileByteBudget(multipartMaxBytes = multipartMaxBytesFromEnv()) {
253289
- if (multipartMaxBytes === null)
253290
- return null;
253291
- return Math.max(0, multipartMaxBytes - MULTIPART_ENVELOPE_HEADROOM_BYTES);
253292
- }
253293
- function indicesRequiringPreUpload(files, multipartMaxBytes = multipartMaxBytesFromEnv()) {
253294
- const budget = multipartFileByteBudget(multipartMaxBytes);
253295
- const toPreUpload = new Set;
253296
- if (budget === null)
253297
- return toPreUpload;
253298
- files.forEach((file, index) => {
253299
- if (file.size > budget) {
253300
- toPreUpload.add(index);
253301
- }
253302
- });
253303
- let multipartTotal = 0;
253304
- files.forEach((file, index) => {
253305
- if (!toPreUpload.has(index))
253306
- multipartTotal += file.size;
253307
- });
253308
- const candidates = files.map((file, index) => ({ file, index })).filter(({ index }) => !toPreUpload.has(index)).slice().sort((a, b) => b.file.size - a.file.size || a.index - b.index);
253309
- for (const { file, index } of candidates) {
253310
- if (multipartTotal <= budget)
253311
- break;
253312
- toPreUpload.add(index);
253313
- multipartTotal -= file.size;
253314
- }
253315
- return toPreUpload;
253199
+ function indicesRequiringPreUpload2(files, multipartMaxBytes = multipartMaxBytesFromEnv()) {
253200
+ return indicesRequiringPreUpload(files, multipartMaxBytes);
253316
253201
  }
253317
253202
  function multipartMaxBytesFromEnv(raw = env.EIGENPAL_MULTIPART_MAX_BYTES) {
253318
253203
  if (raw == null || raw.trim() === "")
@@ -253344,7 +253229,7 @@ async function buildPreparedRunRequest(client, input) {
253344
253229
  for (const spec of parseInputFileSpecs(input.inputFile ?? [])) {
253345
253230
  const info = await fs18.stat(spec.filePath);
253346
253231
  if (!info.isFile()) {
253347
- throw new Error(`--input-file path is not a file: ${spec.filePath}`);
253232
+ throw new UsageError(`--input-file path is not a file: ${spec.filePath}`);
253348
253233
  }
253349
253234
  localFiles.push({
253350
253235
  fieldName: spec.fieldName,
@@ -253364,7 +253249,7 @@ async function buildPreparedRunRequest(client, input) {
253364
253249
  size: content.byteLength
253365
253250
  });
253366
253251
  }
253367
- const preUploadIndices = indicesRequiringPreUpload(localFiles.map((file) => ({ size: file.size })));
253252
+ const preUploadIndices = indicesRequiringPreUpload2(localFiles.map((file) => ({ size: file.size })));
253368
253253
  upgradeMixedFieldPreUpload(localFiles, preUploadIndices);
253369
253254
  const preUploadRefsByField = new Map;
253370
253255
  const preUploadIdempotencyKeys = localFiles.map(() => newIdempotencyKey());
@@ -253447,7 +253332,7 @@ function parseInputFileSpecs(inputFile) {
253447
253332
  const fieldName = value.slice(0, separatorIndex).trim();
253448
253333
  const filePath = value.slice(separatorIndex + 1).trim();
253449
253334
  if (!fieldName || !filePath) {
253450
- throw new Error("--input-file must be <field=path> or a bare path");
253335
+ throw new UsageError("--input-file must be <field=path> or a bare path");
253451
253336
  }
253452
253337
  assertValidFileFieldName(fieldName);
253453
253338
  return { fieldName, filePath };
@@ -253456,7 +253341,7 @@ function parseInputFileSpecs(inputFile) {
253456
253341
 
253457
253342
  // src/lib/format-eigenpal.ts
253458
253343
  import { spawnSync as spawnSync5 } from "child_process";
253459
- import { existsSync as existsSync17, readFileSync as readFileSync17 } from "fs";
253344
+ import { existsSync as existsSync14, readFileSync as readFileSync15 } from "fs";
253460
253345
  import { join as join9, resolve as resolve6 } from "path";
253461
253346
  var PRETTRC_NAMES = [
253462
253347
  ".prettierrc",
@@ -253470,14 +253355,14 @@ var PRETTRC_NAMES = [
253470
253355
  ];
253471
253356
  function hasPrettierConfig(cwd) {
253472
253357
  for (const name of PRETTRC_NAMES) {
253473
- if (existsSync17(join9(cwd, name)))
253358
+ if (existsSync14(join9(cwd, name)))
253474
253359
  return true;
253475
253360
  }
253476
253361
  try {
253477
253362
  const pkgPath = join9(cwd, "package.json");
253478
- if (!existsSync17(pkgPath))
253363
+ if (!existsSync14(pkgPath))
253479
253364
  return false;
253480
- const raw = readFileSync17(pkgPath, "utf-8");
253365
+ const raw = readFileSync15(pkgPath, "utf-8");
253481
253366
  const pkg = JSON.parse(raw);
253482
253367
  return pkg != null && typeof pkg === "object" && "prettier" in pkg;
253483
253368
  } catch {
@@ -253487,7 +253372,7 @@ function hasPrettierConfig(cwd) {
253487
253372
  function formatEigenpalDirIfAvailable(dir) {
253488
253373
  const cwd = process.cwd();
253489
253374
  const absDir = resolve6(cwd, dir);
253490
- if (!existsSync17(absDir))
253375
+ if (!existsSync14(absDir))
253491
253376
  return;
253492
253377
  if (!hasPrettierConfig(cwd))
253493
253378
  return;
@@ -253560,9 +253445,9 @@ async function runTarget(target, opts) {
253560
253445
  const tags = opts.tag?.length ? ExecutionTagsSchema.parse(opts.tag) : undefined;
253561
253446
  if (opts.example) {
253562
253447
  if (tags)
253563
- throw new Error("--tag is supported for ad-hoc runs; example runs do not accept tags");
253448
+ throw new UsageError("--tag is supported for ad-hoc runs; example runs do not accept tags");
253564
253449
  if (opts.inputJson || opts.inputFile && opts.inputFile.length > 0) {
253565
- throw new Error("--example cannot be combined with --input-json or --input-file");
253450
+ throw new UsageError("--example cannot be combined with --input-json or --input-file");
253566
253451
  }
253567
253452
  if (parsed.type === "agent") {
253568
253453
  return runExample(parsed.slug, {
@@ -253577,7 +253462,7 @@ async function runTarget(target, opts) {
253577
253462
  failOnMismatch: opts.failOnMismatch
253578
253463
  });
253579
253464
  }
253580
- const client = buildClient2(opts);
253465
+ const client = buildClient(opts);
253581
253466
  let payload;
253582
253467
  const runPath = runTargetApiPath(target);
253583
253468
  const pathTarget = runStartMultipartTarget(target);
@@ -253621,11 +253506,11 @@ async function rerunTarget(runId, opts) {
253621
253506
  init_dist4();
253622
253507
  import { createHash as createHash5 } from "node:crypto";
253623
253508
  import {
253624
- existsSync as existsSync18,
253509
+ existsSync as existsSync15,
253625
253510
  lstatSync as lstatSync2,
253626
253511
  mkdirSync as mkdirSync6,
253627
- readFileSync as readFileSync18,
253628
- readdirSync as readdirSync6,
253512
+ readFileSync as readFileSync16,
253513
+ readdirSync as readdirSync4,
253629
253514
  rmSync as rmSync2,
253630
253515
  rmdirSync,
253631
253516
  unlinkSync as unlinkSync2,
@@ -253707,10 +253592,10 @@ var MANIFEST_NAME = ".eigenpal-manifest.json";
253707
253592
  function resolveSkillSource() {
253708
253593
  const here = dirname6(fileURLToPath7(import.meta.url));
253709
253594
  const srcCandidate = resolve7(here, "..", "..", "skill");
253710
- if (existsSync18(srcCandidate))
253595
+ if (existsSync15(srcCandidate))
253711
253596
  return srcCandidate;
253712
253597
  const distCandidate = resolve7(here, "skill");
253713
- if (existsSync18(distCandidate))
253598
+ if (existsSync15(distCandidate))
253714
253599
  return distCandidate;
253715
253600
  throw new Error(`Cannot locate bundled skill content. Looked in:
253716
253601
  ${srcCandidate}
@@ -253747,15 +253632,15 @@ async function installSkill(opts) {
253747
253632
  for (const relativePath of sourceFiles) {
253748
253633
  const sourcePath = join11(source, relativePath);
253749
253634
  const targetPath = join11(target, relativePath);
253750
- const sourceBytes = templateSourceFile(relativePath, readFileSync18(sourcePath), cliVersion);
253635
+ const sourceBytes = templateSourceFile(relativePath, readFileSync16(sourcePath), cliVersion);
253751
253636
  const sourceHash = sha256(sourceBytes);
253752
- if (!existsSync18(targetPath)) {
253637
+ if (!existsSync15(targetPath)) {
253753
253638
  mkdirSync6(dirname6(targetPath), { recursive: true });
253754
253639
  writeFileSync8(targetPath, sourceBytes);
253755
253640
  written += 1;
253756
253641
  continue;
253757
253642
  }
253758
- const targetBytes = readFileSync18(targetPath);
253643
+ const targetBytes = readFileSync16(targetPath);
253759
253644
  const targetHash = sha256(targetBytes);
253760
253645
  if (targetHash === sourceHash) {
253761
253646
  skipped += 1;
@@ -253787,9 +253672,9 @@ async function installSkill(opts) {
253787
253672
  const manifestEntries = [];
253788
253673
  for (const relativePath of sourceFiles) {
253789
253674
  const targetPath = join11(target, relativePath);
253790
- if (!existsSync18(targetPath))
253675
+ if (!existsSync15(targetPath))
253791
253676
  continue;
253792
- manifestEntries.push({ path: relativePath, sha256: sha256(readFileSync18(targetPath)) });
253677
+ manifestEntries.push({ path: relativePath, sha256: sha256(readFileSync16(targetPath)) });
253793
253678
  }
253794
253679
  const manifest = {
253795
253680
  cliVersion,
@@ -253830,9 +253715,9 @@ async function uninstallSkill(opts) {
253830
253715
  console.error(`Refusing to touch ${path}: manifest path escapes ${targetReal}`);
253831
253716
  continue;
253832
253717
  }
253833
- if (!existsSync18(path))
253718
+ if (!existsSync15(path))
253834
253719
  continue;
253835
- const currentHash = sha256(readFileSync18(path));
253720
+ const currentHash = sha256(readFileSync16(path));
253836
253721
  if (currentHash !== entry.sha256 && !opts.yes) {
253837
253722
  kept += 1;
253838
253723
  continue;
@@ -254033,17 +253918,17 @@ function hintFor(tool, installed, detected) {
254033
253918
  return tool.relativePath;
254034
253919
  }
254035
253920
  function isInstalled(cwd, tool) {
254036
- return existsSync18(join11(cwd, tool.relativePath, MANIFEST_NAME));
253921
+ return existsSync15(join11(cwd, tool.relativePath, MANIFEST_NAME));
254037
253922
  }
254038
253923
  function isProjectUsing(cwd, tool) {
254039
- return tool.detectPaths.some((p) => existsSync18(join11(cwd, p)));
253924
+ return tool.detectPaths.some((p) => existsSync15(join11(cwd, p)));
254040
253925
  }
254041
253926
  function listFiles(root) {
254042
253927
  const out = [];
254043
253928
  const stack = [root];
254044
253929
  while (stack.length > 0) {
254045
253930
  const dir = stack.pop();
254046
- for (const entry of readdirSync6(dir)) {
253931
+ for (const entry of readdirSync4(dir)) {
254047
253932
  const full = join11(dir, entry);
254048
253933
  const rel = relative4(root, full);
254049
253934
  const stats = lstatSync2(full);
@@ -254060,10 +253945,10 @@ function listFiles(root) {
254060
253945
  }
254061
253946
  function readManifest(target) {
254062
253947
  const path = join11(target, MANIFEST_NAME);
254063
- if (!existsSync18(path))
253948
+ if (!existsSync15(path))
254064
253949
  return null;
254065
253950
  try {
254066
- return JSON.parse(readFileSync18(path, "utf-8"));
253951
+ return JSON.parse(readFileSync16(path, "utf-8"));
254067
253952
  } catch {
254068
253953
  return null;
254069
253954
  }
@@ -254077,8 +253962,8 @@ function readCliVersion() {
254077
253962
  resolve7(here, "..", "package.json")
254078
253963
  ];
254079
253964
  for (const candidate of candidates) {
254080
- if (existsSync18(candidate)) {
254081
- const pkg = JSON.parse(readFileSync18(candidate, "utf-8"));
253965
+ if (existsSync15(candidate)) {
253966
+ const pkg = JSON.parse(readFileSync16(candidate, "utf-8"));
254082
253967
  if (pkg.name && pkg.name !== "@eigenpal/cli")
254083
253968
  continue;
254084
253969
  if (pkg.version)
@@ -254089,11 +253974,11 @@ function readCliVersion() {
254089
253974
  return "unknown";
254090
253975
  }
254091
253976
  function pruneEmptyDirs(root) {
254092
- if (!existsSync18(root))
253977
+ if (!existsSync15(root))
254093
253978
  return;
254094
253979
  const stack = [];
254095
253980
  const collect = (dir) => {
254096
- for (const entry of readdirSync6(dir)) {
253981
+ for (const entry of readdirSync4(dir)) {
254097
253982
  const full = join11(dir, entry);
254098
253983
  if (lstatSync2(full).isDirectory())
254099
253984
  collect(full);
@@ -254103,7 +253988,7 @@ function pruneEmptyDirs(root) {
254103
253988
  collect(root);
254104
253989
  for (const dir of stack) {
254105
253990
  try {
254106
- if (readdirSync6(dir).length === 0)
253991
+ if (readdirSync4(dir).length === 0)
254107
253992
  rmdirSync(dir);
254108
253993
  } catch {}
254109
253994
  }
@@ -254634,9 +254519,6 @@ function validateStepConfigsRecursive(steps, pathPrefix) {
254634
254519
  for (let i = 0;i < steps.length; i++) {
254635
254520
  const step = steps[i];
254636
254521
  const stepPath = [...pathPrefix, i];
254637
- if (step.type === "control.block") {
254638
- continue;
254639
- }
254640
254522
  if (step.type === "control.human_review" && pathPrefix.length > 1) {
254641
254523
  issues.push({
254642
254524
  path: [...stepPath, "type"],
@@ -254880,7 +254762,7 @@ function scanValue(value, path, inScope, out) {
254880
254762
  out.push({
254881
254763
  code: "unknown-step-reference",
254882
254764
  field: path,
254883
- message: `references \`steps.${name}\` but no step named "${name}" is in scope here. Steps nested inside control.parallel branches, control.parallel_map/control.foreach bodies, and control.if branches are not addressable from outside the container — reach inner outputs through the container's aggregate output instead.`,
254765
+ message: `references \`steps.${name}\` but no step named "${name}" is in scope here. Steps nested inside control.parallel branches, control.parallel_map/control.foreach bodies, and control.if branches are not addressable from outside the container: reach inner outputs through the container's aggregate output instead.`,
254884
254766
  hint: `Use the container step's aggregate output, e.g. \`steps.<parallel>.output.<branch>.${name}.<field>\` or \`steps.<foreach>.output.items[i].${name}.<field>\`. See the "Control containers" section of \`step-types.md\`.`
254885
254767
  });
254886
254768
  }
@@ -254908,8 +254790,6 @@ var RUNTIME_READ_KEYS = {
254908
254790
  "transform.merge": ["input", "inputs"]
254909
254791
  };
254910
254792
  function warnIgnoredConfigKeys(step, basePath, out) {
254911
- if (step.type === "control.block")
254912
- return;
254913
254793
  const def = getStepSchema(step.type);
254914
254794
  const cfg = step.with;
254915
254795
  if (!def?.configInWith || !cfg || typeof cfg !== "object" || Array.isArray(cfg))
@@ -255049,12 +254929,12 @@ function looksLikeFreeform(prop) {
255049
254929
  return prop.pattern !== undefined || prop.format !== undefined;
255050
254930
  }
255051
254931
  // src/commands/workflow/index.ts
255052
- import { existsSync as existsSync24, promises as fs23 } from "node:fs";
254932
+ import { existsSync as existsSync21, promises as fs23 } from "node:fs";
255053
254933
  import path19 from "node:path";
255054
254934
 
255055
254935
  // src/lib/local-templates.ts
255056
254936
  init_src();
255057
- import { existsSync as existsSync19, promises as fs19, realpathSync as realpathSync4, statSync as statSync5 } from "node:fs";
254937
+ import { existsSync as existsSync16, promises as fs19, realpathSync as realpathSync4, statSync as statSync4 } from "node:fs";
255058
254938
  import { basename as basename2, dirname as dirname7, isAbsolute as isAbsolute2, relative as relative5, resolve as resolve8, sep } from "node:path";
255059
254939
 
255060
254940
  // src/lib/office-template.ts
@@ -255297,7 +255177,7 @@ function walkTemplateSteps(steps, visit) {
255297
255177
  }
255298
255178
  function resolveWorkflowProjectRoot(workflowFile) {
255299
255179
  const abs = resolve8(workflowFile);
255300
- if (!existsSync19(abs)) {
255180
+ if (!existsSync16(abs)) {
255301
255181
  throw new Error(`Workflow file not found: ${abs}`);
255302
255182
  }
255303
255183
  return dirname7(realpathSync4(abs));
@@ -255320,11 +255200,11 @@ function resolveWorkflowTemplatePath(workflowFile, templatePath, opts = {}) {
255320
255200
  if (!opts.allowExternal) {
255321
255201
  assertInsideProject(projectRoot, templatePath, candidate);
255322
255202
  }
255323
- if (!existsSync19(candidate)) {
255203
+ if (!existsSync16(candidate)) {
255324
255204
  throw new Error(`Local template not found: ${candidate}`);
255325
255205
  }
255326
255206
  const real = realpathSync4(candidate);
255327
- if (!statSync5(real).isFile()) {
255207
+ if (!statSync4(real).isFile()) {
255328
255208
  throw new Error(`Local template is not a file: ${real}`);
255329
255209
  }
255330
255210
  if (!opts.allowExternal) {
@@ -255502,13 +255382,13 @@ function rewriteLocalTemplateYaml(yamlText, resolved) {
255502
255382
  }
255503
255383
 
255504
255384
  // src/commands/workflow/clear.ts
255505
- import { existsSync as existsSync20, readdirSync as readdirSync7, rmSync as rmSync3, statSync as statSync6 } from "fs";
255385
+ import { existsSync as existsSync17, readdirSync as readdirSync5, rmSync as rmSync3, statSync as statSync5 } from "fs";
255506
255386
  import { basename as basename3, join as join12 } from "path";
255507
255387
  var EMPTY_REPORT = { removed: 0, kept: 0, touched: 0 };
255508
255388
  function getDirectoryEntries(path) {
255509
- if (!existsSync20(path))
255389
+ if (!existsSync17(path))
255510
255390
  return [];
255511
- return readdirSync7(path).filter((entry) => statSync6(join12(path, entry)).isDirectory()).sort();
255391
+ return readdirSync5(path).filter((entry) => statSync5(join12(path, entry)).isDirectory()).sort();
255512
255392
  }
255513
255393
  function removeDirEntriesWithRetention(path, removeAll) {
255514
255394
  const entries = getDirectoryEntries(path);
@@ -255527,10 +255407,10 @@ function removeDirEntriesWithRetention(path, removeAll) {
255527
255407
  return { removed, kept: keepSet.size, touched: entries.length };
255528
255408
  }
255529
255409
  function removeJudgeSummaryFilesWithRetention(exampleDir, removeAll) {
255530
- if (!existsSync20(exampleDir))
255410
+ if (!existsSync17(exampleDir))
255531
255411
  return EMPTY_REPORT;
255532
255412
  const stampByFile = new Map;
255533
- for (const fileName of readdirSync7(exampleDir).sort()) {
255413
+ for (const fileName of readdirSync5(exampleDir).sort()) {
255534
255414
  const match = /^llm-judge-summary-(.+)\.(json|md)$/.exec(fileName);
255535
255415
  if (match)
255536
255416
  stampByFile.set(fileName, match[1]);
@@ -255559,7 +255439,7 @@ function getTargetExampleDirs(dir, exampleNames) {
255559
255439
  error2(`No dataset/examples directory at ${join12(dir, "dataset", "examples")}`);
255560
255440
  process.exit(1);
255561
255441
  }
255562
- const all = readdirSync7(baseDir).filter((entry) => statSync6(join12(baseDir, entry)).isDirectory());
255442
+ const all = readdirSync5(baseDir).filter((entry) => statSync5(join12(baseDir, entry)).isDirectory());
255563
255443
  if (exampleNames.length === 0)
255564
255444
  return all.map((name) => join12(baseDir, name));
255565
255445
  const matched = all.filter((name) => exampleNames.includes(name));
@@ -255599,7 +255479,7 @@ async function clearEvalOutputs(dir, exampleNames = [], options = {}) {
255599
255479
  runSection({
255600
255480
  exampleDirs,
255601
255481
  clean: (exampleDir) => removeDirEntriesWithRetention(join12(exampleDir, "executions"), removeAll),
255602
- shouldCount: (exampleDir) => existsSync20(join12(exampleDir, "executions")),
255482
+ shouldCount: (exampleDir) => existsSync17(join12(exampleDir, "executions")),
255603
255483
  successLabel: "Execution cleanup complete",
255604
255484
  scannedLabel: "examples scanned:",
255605
255485
  seenLabel: "runs seen: ",
@@ -255611,7 +255491,7 @@ async function clearEvalOutputs(dir, exampleNames = [], options = {}) {
255611
255491
  runSection({
255612
255492
  exampleDirs,
255613
255493
  clean: (exampleDir) => removeJudgeSummaryFilesWithRetention(exampleDir, removeAll),
255614
- shouldCount: (exampleDir) => existsSync20(exampleDir),
255494
+ shouldCount: (exampleDir) => existsSync17(exampleDir),
255615
255495
  successLabel: "Judge summary cleanup complete",
255616
255496
  scannedLabel: "examples scanned: ",
255617
255497
  seenLabel: "summary files seen: ",
@@ -255964,7 +255844,7 @@ import { resolve as resolve9 } from "node:path";
255964
255844
  function registerParserMigrationCommand(workflow) {
255965
255845
  workflow.command("migrate-parser <file>").description("Write a reviewable ai.parse-v2 workflow migration to a new file. Never pushes or changes the source.").requiredOption("--policy <policy>", "preserve backend restrictions, or auto to adopt automatic native/OCR/vision parsing").requiredOption("--out <file>", "New YAML output file (must not already exist)").option("--json", "Emit migration summary as JSON").action(action(async (file, options) => {
255966
255846
  if (options.policy !== "preserve" && options.policy !== "auto")
255967
- throw new Error("--policy must be preserve or auto");
255847
+ throw new UsageError("--policy must be preserve or auto");
255968
255848
  if (resolve9(file) === resolve9(options.out))
255969
255849
  throw new Error("Migration output must differ from the source");
255970
255850
  const source = $parse(await readFile4(file, "utf8"));
@@ -255987,44 +255867,10 @@ function registerParserMigrationCommand(workflow) {
255987
255867
  }));
255988
255868
  }
255989
255869
 
255990
- // src/commands/workflow/step-exec.ts
255991
- init_src();
255992
- var UNSUPPORTED_TYPE_EXIT = 2;
255993
- function exitUnsupported(type) {
255994
- error2(`\`workflow step exec ${type}\` is currently disabled.
255995
- ` + ` The previous local-runner implementation ran every step in the CLI process,
255996
- ` + ` which diverged from production worker behavior. Tracking the server-side
255997
- ` + ` redesign in EIG-104.
255998
-
255999
- ` + ` To run a single step today, push the workflow and run it via:
256000
- ` + ` $ eigenpal run workflows.<workflow-id>
256001
- ` + ` $ eigenpal workflow experiment run <workflow-id> --example-id <name>`);
256002
- process.exit(UNSUPPORTED_TYPE_EXIT);
256003
- }
256004
- function registerStepExecCommands(workflow) {
256005
- const step = workflow.command("step").description("Run a single workflow step (placeholder; see EIG-104).");
256006
- step.command("exec <type>").description("DISABLED — local mimic runners removed pending server-side redesign (EIG-104). " + "Use `run` or `workflow experiment run` instead.").option("--config-json <json>", "(unused; kept for back-compat parsing)").option("--config-file <path>", "(unused)").option("--inputs <pairs...>", "(unused)").option("--output-schema <path>", "(unused)").action(action(async (rawType) => {
256007
- const known = listStepTypes();
256008
- if (!known.includes(rawType)) {
256009
- error2(`Unknown step type: ${rawType}. Run \`eigenpal workflow step-type list\`.`);
256010
- process.exit(UNSUPPORTED_TYPE_EXIT);
256011
- }
256012
- exitUnsupported(rawType);
256013
- }));
256014
- }
256015
-
256016
255870
  // src/commands/workflow/templates.ts
256017
255871
  init_src();
256018
- import { existsSync as existsSync21, promises as fs21 } from "node:fs";
255872
+ import { existsSync as existsSync18, promises as fs21 } from "node:fs";
256019
255873
  import { basename as basename4, resolve as resolve10 } from "node:path";
256020
- function buildClient5(opts) {
256021
- const config = resolveConfig(opts);
256022
- requireApiKey(config);
256023
- return new ApiClient(config);
256024
- }
256025
- function printJson5(value) {
256026
- console.log(JSON.stringify(value, null, 2));
256027
- }
256028
255874
  async function readJsonFixtureFile(fixturePath) {
256029
255875
  let raw;
256030
255876
  try {
@@ -256040,10 +255886,10 @@ async function readJsonFixtureFile(fixturePath) {
256040
255886
  try {
256041
255887
  parsed = JSON.parse(raw);
256042
255888
  } catch {
256043
- throw new Error(`--data must be a JSON fixture file containing an object (${fixturePath})`);
255889
+ throw new UsageError(`--data must be a JSON fixture file containing an object (${fixturePath})`);
256044
255890
  }
256045
255891
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
256046
- throw new Error("--data must be a JSON object (template data keys)");
255892
+ throw new UsageError("--data must be a JSON object (template data keys)");
256047
255893
  }
256048
255894
  return parsed;
256049
255895
  }
@@ -256081,7 +255927,7 @@ function registerTemplateCommands(parent) {
256081
255927
  addJsonFlag(withBaseUrl(uploadCmd)).action(action(async (file, opts) => {
256082
255928
  const filePath = resolve10(file);
256083
255929
  const bytes = await fs21.readFile(filePath);
256084
- const client = buildClient5(opts);
255930
+ const client = buildClient(opts);
256085
255931
  const template = await uploadWorkspaceTemplate(client, {
256086
255932
  bytes,
256087
255933
  filename: basename4(filePath),
@@ -256089,7 +255935,7 @@ function registerTemplateCommands(parent) {
256089
255935
  description: opts.description
256090
255936
  });
256091
255937
  if (opts.json) {
256092
- printJson5(template);
255938
+ printJson(template);
256093
255939
  return;
256094
255940
  }
256095
255941
  success(`Uploaded ${ui.bold(template.id)} revision ${ui.bold(template.currentRevision?.id ?? "-")} (${template.format})`);
@@ -256097,10 +255943,10 @@ function registerTemplateCommands(parent) {
256097
255943
  }));
256098
255944
  const listCmd = templates.command("list").description("List workspace templates.");
256099
255945
  addJsonFlag(withBaseUrl(withPagination(listCmd))).action(action(async (opts) => {
256100
- const client = buildClient5(opts);
255946
+ const client = buildClient(opts);
256101
255947
  const result = await listPublicTemplates(client, { limit: opts.limit, offset: opts.offset });
256102
255948
  if (opts.json) {
256103
- printJson5(result);
255949
+ printJson(result);
256104
255950
  return;
256105
255951
  }
256106
255952
  console.log(table(result.items.map((row) => ({
@@ -256125,10 +255971,10 @@ function registerTemplateCommands(parent) {
256125
255971
  }));
256126
255972
  const getCmd = templates.command("get <template-id>").alias("inspect").description("Inspect a tmpl_… resource: current tmpr_…, format, checksum, tokens, grammar.");
256127
255973
  addJsonFlag(withBaseUrl(getCmd)).action(action(async (templateId, opts) => {
256128
- const client = buildClient5(opts);
255974
+ const client = buildClient(opts);
256129
255975
  const template = await getPublicTemplate(client, templateId);
256130
255976
  if (opts.json) {
256131
- printJson5(template);
255977
+ printJson(template);
256132
255978
  return;
256133
255979
  }
256134
255980
  printTemplateHuman(template);
@@ -256136,8 +255982,8 @@ function registerTemplateCommands(parent) {
256136
255982
  const downloadCmd = templates.command("download <template-id>").description("Download current (or pinned) template bytes.").option("--out <path>", "Write to this file (required)").option("--revision-id <tmpr>", "Pin an immutable tmpr_… revision");
256137
255983
  withBaseUrl(downloadCmd).action(action(async (templateId, opts) => {
256138
255984
  if (!opts.out)
256139
- throw new Error("Missing --out <path>.");
256140
- const client = buildClient5(opts);
255985
+ throw new UsageError("Missing --out <path>.");
255986
+ const client = buildClient(opts);
256141
255987
  const downloaded = await downloadTemplateBytes(client, templateId, opts.revisionId);
256142
255988
  await fs21.writeFile(opts.out, downloaded.bytes);
256143
255989
  success(`Wrote ${ui.bold(opts.out)} ${ui.dim(`(${downloaded.bytes.byteLength} bytes)`)}`);
@@ -256146,12 +255992,12 @@ function registerTemplateCommands(parent) {
256146
255992
  addJsonFlag(withBaseUrl(replaceCmd)).action(action(async (templateId, file, opts) => {
256147
255993
  const filePath = resolve10(file);
256148
255994
  const bytes = await fs21.readFile(filePath);
256149
- const client = buildClient5(opts);
255995
+ const client = buildClient(opts);
256150
255996
  const current = await getPublicTemplate(client, templateId);
256151
255997
  const nextInspection = inspectOfficeTemplateBytes(bytes, basename4(filePath));
256152
255998
  if (current.currentRevision?.sha256 === nextInspection.sha256 || current.sha256 === nextInspection.sha256) {
256153
255999
  if (opts.json) {
256154
- printJson5({ ...current, reused: true });
256000
+ printJson({ ...current, reused: true });
256155
256001
  return;
256156
256002
  }
256157
256003
  success(`Checksum matches current revision ${ui.bold(current.currentRevision?.id ?? "-")} — skipped upload`);
@@ -256163,7 +256009,7 @@ function registerTemplateCommands(parent) {
256163
256009
  filename: basename4(filePath)
256164
256010
  });
256165
256011
  if (opts.json) {
256166
- printJson5(template);
256012
+ printJson(template);
256167
256013
  return;
256168
256014
  }
256169
256015
  success(`Replaced ${ui.bold(template.id)} → revision ${ui.bold(template.currentRevision?.id ?? "-")}`);
@@ -256174,10 +256020,10 @@ function registerTemplateCommands(parent) {
256174
256020
  if (!opts.yes && !process.stdout.isTTY) {
256175
256021
  throw new Error("templates delete is destructive and requires --yes when run non-interactively");
256176
256022
  }
256177
- const client = buildClient5(opts);
256023
+ const client = buildClient(opts);
256178
256024
  const result = await deleteWorkspaceTemplate(client, templateId);
256179
256025
  if (opts.json) {
256180
- printJson5(result);
256026
+ printJson(result);
256181
256027
  return;
256182
256028
  }
256183
256029
  success(`Deleted ${ui.bold(templateId)}`);
@@ -256190,13 +256036,13 @@ function registerTemplateCommands(parent) {
256190
256036
  let filename;
256191
256037
  const isTmpl = TemplateIdSchema.safeParse(templateArg).success;
256192
256038
  if (isTmpl) {
256193
- const client = buildClient5(opts);
256039
+ const client = buildClient(opts);
256194
256040
  const downloaded = await downloadTemplateBytes(client, templateArg, opts.revisionId);
256195
256041
  bytes = downloaded.bytes;
256196
256042
  filename = downloaded.filename;
256197
256043
  } else {
256198
256044
  const filePath = resolve10(templateArg);
256199
- if (!existsSync21(filePath)) {
256045
+ if (!existsSync18(filePath)) {
256200
256046
  throw new Error(`Template file not found: ${filePath}. Pass a local .docx/.xlsx path or a tmpl_… id.`);
256201
256047
  }
256202
256048
  bytes = await fs21.readFile(filePath);
@@ -256218,7 +256064,7 @@ function registerTemplateCommands(parent) {
256218
256064
  bytes: rendered.output.byteLength
256219
256065
  };
256220
256066
  if (opts.json) {
256221
- printJson5(payload);
256067
+ printJson(payload);
256222
256068
  return;
256223
256069
  }
256224
256070
  success(`Wrote ${ui.bold(opts.out)} (${rendered.inspection.format}, ${rendered.output.byteLength} bytes)`);
@@ -256238,12 +256084,12 @@ function registerTemplateCommands(parent) {
256238
256084
 
256239
256085
  // src/commands/workflow/validation.ts
256240
256086
  init_src();
256241
- import { existsSync as existsSync23, readdirSync as readdirSync8, readFileSync as readFileSync20, statSync as statSync7 } from "fs";
256087
+ import { existsSync as existsSync20, readdirSync as readdirSync6, readFileSync as readFileSync18, statSync as statSync6 } from "fs";
256242
256088
  import { join as join13, resolve as resolve11 } from "path";
256243
256089
 
256244
256090
  // src/lib/template-diagnostics.ts
256245
256091
  init_src();
256246
- import { existsSync as existsSync22, readFileSync as readFileSync19 } from "node:fs";
256092
+ import { existsSync as existsSync19, readFileSync as readFileSync17 } from "node:fs";
256247
256093
  function walkSteps(steps, pathPrefix, visit) {
256248
256094
  if (!Array.isArray(steps))
256249
256095
  return;
@@ -256368,7 +256214,7 @@ async function diagnoseTemplateSteps(args) {
256368
256214
  });
256369
256215
  continue;
256370
256216
  }
256371
- if (!existsSync22(absolute)) {
256217
+ if (!existsSync19(absolute)) {
256372
256218
  diagnostics.push({
256373
256219
  field: `${info.fieldPath}.template`,
256374
256220
  message: `File not found: ${absolute}`,
@@ -256377,7 +256223,7 @@ async function diagnoseTemplateSteps(args) {
256377
256223
  continue;
256378
256224
  }
256379
256225
  try {
256380
- const bytes = readFileSync19(absolute);
256226
+ const bytes = readFileSync17(absolute);
256381
256227
  const inspection = inspectOfficeTemplateBytes(bytes, absolute);
256382
256228
  diagnostics.push(...formatDiagnostics(info, inspection));
256383
256229
  } catch (err) {
@@ -256471,7 +256317,7 @@ async function diagnoseTemplateSteps(args) {
256471
256317
  var NAME_RE = /^[a-z0-9][a-z0-9-_]*$/;
256472
256318
  function isDirSafe(path, issues, field) {
256473
256319
  try {
256474
- return statSync7(path).isDirectory();
256320
+ return statSync6(path).isDirectory();
256475
256321
  } catch (err) {
256476
256322
  issues.push({
256477
256323
  field,
@@ -256513,7 +256359,7 @@ function countInvokeWorkflowSteps(steps) {
256513
256359
  return count;
256514
256360
  }
256515
256361
  function validateWorkflowYaml(path) {
256516
- if (!existsSync23(path)) {
256362
+ if (!existsSync20(path)) {
256517
256363
  return {
256518
256364
  issues: [{ field: path, message: "File not found." }],
256519
256365
  warnings: [],
@@ -256522,7 +256368,7 @@ function validateWorkflowYaml(path) {
256522
256368
  steps: []
256523
256369
  };
256524
256370
  }
256525
- const text = readFileSync20(path, "utf-8");
256371
+ const text = readFileSync18(path, "utf-8");
256526
256372
  try {
256527
256373
  const definition = parseWorkflow(text);
256528
256374
  let warnings = [];
@@ -256623,10 +256469,10 @@ function printSchemaQualityWarnings(path, warnings) {
256623
256469
  }
256624
256470
  }
256625
256471
  function validateEvaluatorsYaml(path) {
256626
- if (!existsSync23(path)) {
256472
+ if (!existsSync20(path)) {
256627
256473
  return [{ field: path, message: "File not found." }];
256628
256474
  }
256629
- const text = readFileSync20(path, "utf-8");
256475
+ const text = readFileSync18(path, "utf-8");
256630
256476
  let parsed;
256631
256477
  try {
256632
256478
  parsed = $parse(text);
@@ -256643,21 +256489,21 @@ function validateEvaluatorsYaml(path) {
256643
256489
  }
256644
256490
  function validateDatasetFolder(root) {
256645
256491
  const issues = [];
256646
- if (!existsSync23(root)) {
256492
+ if (!existsSync20(root)) {
256647
256493
  return [{ field: root, message: "Folder not found." }];
256648
256494
  }
256649
- if (existsSync23(join13(root, "manifest.json"))) {
256495
+ if (existsSync20(join13(root, "manifest.json"))) {
256650
256496
  issues.push({
256651
256497
  field: "manifest.json",
256652
256498
  message: "Top-level manifest.json is the legacy format. Re-export the dataset using the folder convention."
256653
256499
  });
256654
256500
  }
256655
256501
  const examplesDir = join13(root, "examples");
256656
- if (!existsSync23(examplesDir)) {
256502
+ if (!existsSync20(examplesDir)) {
256657
256503
  issues.push({ field: "examples/", message: "No examples/ directory found at dataset root." });
256658
256504
  return issues;
256659
256505
  }
256660
- for (const exampleName of readdirSync8(examplesDir)) {
256506
+ for (const exampleName of readdirSync6(examplesDir)) {
256661
256507
  const exampleFolder = join13(examplesDir, exampleName);
256662
256508
  if (!isDirSafe(exampleFolder, issues, `examples/${exampleName}`))
256663
256509
  continue;
@@ -256669,7 +256515,7 @@ function validateDatasetFolder(root) {
256669
256515
  continue;
256670
256516
  }
256671
256517
  const inputJsonPath = join13(exampleFolder, "input.json");
256672
- const hasInputJson = existsSync23(inputJsonPath);
256518
+ const hasInputJson = existsSync20(inputJsonPath);
256673
256519
  if (!hasInputJson) {
256674
256520
  issues.push({
256675
256521
  field: `examples/${exampleName}/input.json`,
@@ -256679,7 +256525,7 @@ function validateDatasetFolder(root) {
256679
256525
  }
256680
256526
  let args;
256681
256527
  try {
256682
- const parsed = JSON.parse(readFileSync20(inputJsonPath, "utf-8"));
256528
+ const parsed = JSON.parse(readFileSync18(inputJsonPath, "utf-8"));
256683
256529
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
256684
256530
  issues.push({
256685
256531
  field: `examples/${exampleName}/input.json`,
@@ -256696,7 +256542,7 @@ function validateDatasetFolder(root) {
256696
256542
  continue;
256697
256543
  }
256698
256544
  const inputDir = join13(exampleFolder, "input");
256699
- if (existsSync23(join13(inputDir, "arguments.json"))) {
256545
+ if (existsSync20(join13(inputDir, "arguments.json"))) {
256700
256546
  issues.push({
256701
256547
  field: `examples/${exampleName}/input/arguments.json`,
256702
256548
  message: "Legacy input/arguments.json is no longer accepted. Use input.json instead."
@@ -256713,8 +256559,8 @@ function validateDatasetFolder(root) {
256713
256559
  }
256714
256560
  const expectedDir = join13(exampleFolder, "expected");
256715
256561
  const expectedJsonPath = join13(exampleFolder, "expected.json");
256716
- if (existsSync23(expectedDir)) {
256717
- for (const entry of readdirSync8(expectedDir)) {
256562
+ if (existsSync20(expectedDir)) {
256563
+ for (const entry of readdirSync6(expectedDir)) {
256718
256564
  if (entry === "output.json" || entry === "error.json") {
256719
256565
  issues.push({
256720
256566
  field: `examples/${exampleName}/expected/${entry}`,
@@ -256726,7 +256572,7 @@ function validateDatasetFolder(root) {
256726
256572
  const field = `examples/${exampleName}/expected/${entry}`;
256727
256573
  let isDir;
256728
256574
  try {
256729
- isDir = statSync7(sub).isDirectory();
256575
+ isDir = statSync6(sub).isDirectory();
256730
256576
  } catch (err) {
256731
256577
  issues.push({
256732
256578
  field,
@@ -256749,10 +256595,10 @@ function validateDatasetFolder(root) {
256749
256595
  }
256750
256596
  }
256751
256597
  }
256752
- if (existsSync23(expectedJsonPath)) {
256598
+ if (existsSync20(expectedJsonPath)) {
256753
256599
  let parsed;
256754
256600
  try {
256755
- parsed = JSON.parse(readFileSync20(expectedJsonPath, "utf-8"));
256601
+ parsed = JSON.parse(readFileSync18(expectedJsonPath, "utf-8"));
256756
256602
  } catch {
256757
256603
  issues.push({
256758
256604
  field: `examples/${exampleName}/expected.json`,
@@ -256835,7 +256681,7 @@ function validateFileRefs2(args) {
256835
256681
  });
256836
256682
  continue;
256837
256683
  }
256838
- if (!existsSync23(join13(args.filesRoot, relative))) {
256684
+ if (!existsSync20(join13(args.filesRoot, relative))) {
256839
256685
  issues.push({
256840
256686
  field: `${args.fieldPrefix}:${ref.jsonPath}`,
256841
256687
  message: `Referenced file does not exist: ${ref.path}.`
@@ -256867,7 +256713,7 @@ async function onlineInvokeIssues(yamlText, opts) {
256867
256713
  }
256868
256714
  function discoverWorkflowProjectRoots(rootPath) {
256869
256715
  const root = resolve11(rootPath);
256870
- if (existsSync23(join13(root, "workflow.yaml")))
256716
+ if (existsSync20(join13(root, "workflow.yaml")))
256871
256717
  return [root];
256872
256718
  const candidates = [
256873
256719
  join13(root, "eigenpal", "workflows"),
@@ -256875,9 +256721,9 @@ function discoverWorkflowProjectRoots(rootPath) {
256875
256721
  root.endsWith(join13("eigenpal", "workflows")) ? root : ""
256876
256722
  ].filter(Boolean);
256877
256723
  for (const parent of candidates) {
256878
- if (!existsSync23(parent) || !statSync7(parent).isDirectory())
256724
+ if (!existsSync20(parent) || !statSync6(parent).isDirectory())
256879
256725
  continue;
256880
- const projects = readdirSync8(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && existsSync23(join13(parent, entry.name, "workflow.yaml"))).map((entry) => join13(parent, entry.name)).sort();
256726
+ const projects = readdirSync6(parent, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && existsSync20(join13(parent, entry.name, "workflow.yaml"))).map((entry) => join13(parent, entry.name)).sort();
256881
256727
  if (projects.length > 0)
256882
256728
  return projects;
256883
256729
  }
@@ -256894,10 +256740,10 @@ async function validateProjectRoot(root, opts) {
256894
256740
  }
256895
256741
  const evOk = printIssues("evaluators.yaml", relPath(root, join13(root, "evaluators.yaml")), validateEvaluatorsYaml(join13(root, "evaluators.yaml")));
256896
256742
  const dsOk = printIssues("dataset/", relPath(root, join13(root, "dataset")), validateDatasetFolder(join13(root, "dataset")));
256897
- const templateOk = wfOk && existsSync23(wfFile) ? await runTemplateDiagnostics(wfFile, wfResult.steps, opts) : true;
256743
+ const templateOk = wfOk && existsSync20(wfFile) ? await runTemplateDiagnostics(wfFile, wfResult.steps, opts) : true;
256898
256744
  let onlineOk = true;
256899
- if (wfOk && opts.online && existsSync23(wfFile)) {
256900
- onlineOk = printIssues("invoke refs (server)", wfPath, await onlineInvokeIssues(readFileSync20(wfFile, "utf-8"), opts));
256745
+ if (wfOk && opts.online && existsSync20(wfFile)) {
256746
+ onlineOk = printIssues("invoke refs (server)", wfPath, await onlineInvokeIssues(readFileSync18(wfFile, "utf-8"), opts));
256901
256747
  }
256902
256748
  return wfOk && evOk && dsOk && templateOk && onlineOk;
256903
256749
  }
@@ -256913,7 +256759,7 @@ Note
256913
256759
  ` + ` project unless you pass --allow-external-templates.
256914
256760
  `);
256915
256761
  withBaseUrl(cmd).action(action(async (path, opts) => {
256916
- if (path && (!existsSync23(resolve11(path)) || !statSync7(resolve11(path)).isDirectory())) {
256762
+ if (path && (!existsSync20(resolve11(path)) || !statSync6(resolve11(path)).isDirectory())) {
256917
256763
  const target = resolve11(path);
256918
256764
  const wfResult = validateWorkflowYaml(target);
256919
256765
  const wfOk = printIssues("workflow.yaml", target, wfResult.issues);
@@ -256924,7 +256770,7 @@ Note
256924
256770
  const templateOk = wfOk ? await runTemplateDiagnostics(target, wfResult.steps, opts) : true;
256925
256771
  let onlineOk = true;
256926
256772
  if (wfOk && opts.online) {
256927
- onlineOk = printIssues("invoke refs (server)", target, await onlineInvokeIssues(readFileSync20(target, "utf-8"), opts));
256773
+ onlineOk = printIssues("invoke refs (server)", target, await onlineInvokeIssues(readFileSync18(target, "utf-8"), opts));
256928
256774
  }
256929
256775
  if (!wfOk || !templateOk || !onlineOk)
256930
256776
  process.exit(1);
@@ -256973,22 +256819,14 @@ function relPath(root, target) {
256973
256819
  }
256974
256820
 
256975
256821
  // src/commands/workflow/index.ts
256976
- function buildClient6(opts) {
256977
- const config = resolveConfig(opts);
256978
- requireApiKey(config);
256979
- return new ApiClient(config);
256980
- }
256981
256822
  async function buildClientForWorkflow(workflowIdOrSlug, opts) {
256982
- const client = buildClient6(opts);
256823
+ const client = buildClient(opts);
256983
256824
  const workflowId = await resolveWorkflowId(client, workflowIdOrSlug);
256984
256825
  return { client, workflowId };
256985
256826
  }
256986
256827
  function descriptionFor(tool) {
256987
256828
  return WORKFLOW_TOOL_METADATA[tool].description;
256988
256829
  }
256989
- function printJson6(value) {
256990
- console.log(JSON.stringify(value, null, 2));
256991
- }
256992
256830
  function renderWorkflowDetail(row) {
256993
256831
  const steps = row.currentVersion?.definition?.steps;
256994
256832
  const fields = [
@@ -257103,12 +256941,11 @@ YAML's \`name:\` field). Both:
257103
256941
  registerEvaluatorTypeCommands(workflow);
257104
256942
  registerAllValidateCommand(workflow);
257105
256943
  registerClearLocalCommand(workflow);
257106
- registerStepExecCommands(workflow);
257107
256944
  }
257108
256945
  function registerWorkflowCoreCommands(parent) {
257109
256946
  const listCmd = parent.command("list").description(descriptionFor("workflow_list")).option("--search <q>", "Filter by name");
257110
256947
  addJsonFlag(withBaseUrl(withPagination(listCmd))).action(action(async (opts) => {
257111
- const client = buildClient6(opts);
256948
+ const client = buildClient(opts);
257112
256949
  const params = {
257113
256950
  limit: String(opts.limit),
257114
256951
  offset: String(opts.offset)
@@ -257141,7 +256978,7 @@ file and \`workflow versions list\` for the version history.
257141
256978
  const { client, workflowId } = await buildClientForWorkflow(workflow, opts);
257142
256979
  const row = withWorkflowRowFields(await client.get(`/api/workflows/${workflowId}`));
257143
256980
  if (opts.json) {
257144
- printJson6(row);
256981
+ printJson(row);
257145
256982
  return;
257146
256983
  }
257147
256984
  renderWorkflowDetail(row);
@@ -257207,13 +257044,13 @@ new uploads are deleted. The file on disk is not rewritten.
257207
257044
  `);
257208
257045
  addJsonFlag(withBaseUrl(pushCmd)).action(action(async (opts) => {
257209
257046
  if (opts.bump && opts.setVersion) {
257210
- throw new Error("Pass either --bump or --set-version, not both.");
257047
+ throw new UsageError("Pass either --bump or --set-version, not both.");
257211
257048
  }
257212
257049
  if (opts.bump && !isBumpLevel(opts.bump)) {
257213
- throw new Error(`--bump must be one of: patch, minor, major (got "${opts.bump}").`);
257050
+ throw new UsageError(`--bump must be one of: patch, minor, major (got "${opts.bump}").`);
257214
257051
  }
257215
257052
  if (opts.setVersion && !SEMVER_RE.test(opts.setVersion)) {
257216
- throw new Error(`--set-version must be bare semver X.Y.Z (got "${opts.setVersion}").`);
257053
+ throw new UsageError(`--set-version must be bare semver X.Y.Z (got "${opts.setVersion}").`);
257217
257054
  }
257218
257055
  let filePath = opts.file;
257219
257056
  if (!filePath) {
@@ -257225,7 +257062,7 @@ new uploads are deleted. The file on disk is not rewritten.
257225
257062
  defaultValue: "workflow.yaml",
257226
257063
  validate: (value) => {
257227
257064
  const p = value || "workflow.yaml";
257228
- if (!existsSync24(p))
257065
+ if (!existsSync21(p))
257229
257066
  return `Not found: ${p}`;
257230
257067
  return;
257231
257068
  }
@@ -257236,11 +257073,11 @@ new uploads are deleted. The file on disk is not rewritten.
257236
257073
  }
257237
257074
  filePath = answer || "workflow.yaml";
257238
257075
  } else {
257239
- throw new Error("Missing --file <yaml>.");
257076
+ throw new UsageError("Missing --file <yaml>.");
257240
257077
  }
257241
257078
  }
257242
257079
  const yamlOnDisk = await fs23.readFile(filePath, "utf8");
257243
- const client = buildClient6(opts);
257080
+ const client = buildClient(opts);
257244
257081
  const definition = parseWorkflowOrThrow(yamlOnDisk);
257245
257082
  const loadedTemplates = await loadLocalTemplatesForPush(filePath, definition.steps, {
257246
257083
  allowExternal: Boolean(opts.allowExternalTemplates)
@@ -257310,7 +257147,7 @@ new uploads are deleted. The file on disk is not rewritten.
257310
257147
  fallbackVersion: nextVersion ?? null
257311
257148
  });
257312
257149
  if (opts.json) {
257313
- printJson6(withPushExtras(summary, result.warnings, resolvedTemplates));
257150
+ printJson(withPushExtras(summary, result.warnings, resolvedTemplates));
257314
257151
  return;
257315
257152
  }
257316
257153
  success(`Pushed ${ui.bold(workflowId)} (v${summary.version ?? "?"})`);
@@ -257331,7 +257168,7 @@ new uploads are deleted. The file on disk is not rewritten.
257331
257168
  fallbackVersion: createVersion ?? null
257332
257169
  });
257333
257170
  if (opts.json) {
257334
- printJson6(withPushExtras(summary, result.warnings, resolvedTemplates));
257171
+ printJson(withPushExtras(summary, result.warnings, resolvedTemplates));
257335
257172
  return;
257336
257173
  }
257337
257174
  success(`Created ${ui.bold(summary.id ?? "?")} (v${summary.version ?? "?"})`);
@@ -257355,7 +257192,7 @@ the root. Agents cannot be moved with this command.
257355
257192
  folderPath: opts.folder
257356
257193
  });
257357
257194
  if (opts.json) {
257358
- printJson6(result);
257195
+ printJson(result);
257359
257196
  return;
257360
257197
  }
257361
257198
  const target = opts.folder.trim() === "/" ? "root" : opts.folder;
@@ -257386,7 +257223,7 @@ resolved workflow id to confirm.
257386
257223
  const result = await client.delete(`/v1/automations/${encodeURIComponent(workflowId)}`);
257387
257224
  const parsed = parseAutomationDeleteResult(result);
257388
257225
  if (opts.json) {
257389
- printJson6({ ...parsed, id: workflowId });
257226
+ printJson({ ...parsed, id: workflowId });
257390
257227
  return;
257391
257228
  }
257392
257229
  success(`Deleted workflow ${ui.bold(workflowId)}`);
@@ -257462,7 +257299,7 @@ async function preflightVersionConflict(client, workflowId, nextVersion, opts) {
257462
257299
  localName: workflowRowName(current),
257463
257300
  fallbackVersion: nextVersion
257464
257301
  });
257465
- printJson6({ ...summary, unchanged: true, workflowId });
257302
+ printJson({ ...summary, unchanged: true, workflowId });
257466
257303
  return true;
257467
257304
  }
257468
257305
  }
@@ -257550,10 +257387,10 @@ function resolveWorkflowVersionCreateRequest(opts) {
257550
257387
  const hasFile = Boolean(opts.file);
257551
257388
  const hasFrom = Boolean(opts.from);
257552
257389
  if (hasFile && hasFrom) {
257553
- throw new Error("Pass either --file or --from, not both.");
257390
+ throw new UsageError("Pass either --file or --from, not both.");
257554
257391
  }
257555
257392
  if (!hasFile && !hasFrom) {
257556
- throw new Error("Pass --file <yaml> or --from <version-id> to create a tagged version.");
257393
+ throw new UsageError("Pass --file <yaml> or --from <version-id> to create a tagged version.");
257557
257394
  }
257558
257395
  if (opts.setVersion && opts.yamlVersion) {
257559
257396
  throw new Error(`--set-version conflicts with the top-level \`version: ${opts.yamlVersion}\` in the YAML. Remove the YAML field, or omit the flag.`);
@@ -257593,7 +257430,7 @@ function registerEvaluatorsCommands(parent) {
257593
257430
  yaml
257594
257431
  });
257595
257432
  if (opts.json) {
257596
- printJson6(result);
257433
+ printJson(result);
257597
257434
  return;
257598
257435
  }
257599
257436
  let count = null;
@@ -257663,7 +257500,7 @@ then close the request when review is finished.
257663
257500
  `);
257664
257501
  addJsonFlag(withBaseUrl(pushCmd)).action(action(async (workflow, opts) => {
257665
257502
  if (opts.mode !== "append" && opts.mode !== "replace") {
257666
- throw new Error('--mode must be "append" or "replace"');
257503
+ throw new UsageError('--mode must be "append" or "replace"');
257667
257504
  }
257668
257505
  if (opts.mode === "replace") {
257669
257506
  requireYesInNonInteractive(opts.yes, "Replace workflow dataset");
@@ -257706,7 +257543,7 @@ then close the request when review is finished.
257706
257543
  }));
257707
257544
  if (issues.length === 0) {
257708
257545
  error2("Import aborted with no structured issues — server-side bug.");
257709
- printJson6(terminal);
257546
+ printJson(terminal);
257710
257547
  } else {
257711
257548
  printIssues("dataset", opts.file, issues);
257712
257549
  if (errPayload.limitMb != null && errPayload.actualMb != null) {
@@ -257727,7 +257564,7 @@ then close the request when review is finished.
257727
257564
  if (terminal.phase === "done") {
257728
257565
  const done = terminal;
257729
257566
  if (opts.json) {
257730
- printJson6(done);
257567
+ printJson(done);
257731
257568
  return;
257732
257569
  }
257733
257570
  const created = done.created ?? 0;
@@ -257745,7 +257582,7 @@ then close the request when review is finished.
257745
257582
  }
257746
257583
  } else {
257747
257584
  error2(`Import response had unexpected terminal phase: ${terminal.phase}`);
257748
- printJson6(terminal);
257585
+ printJson(terminal);
257749
257586
  process.exit(1);
257750
257587
  }
257751
257588
  }));
@@ -257810,7 +257647,7 @@ exclusive. To attach files without a dataset folder, pass ingress refs in JSON:
257810
257647
  const { client, workflowId } = await buildClientForWorkflow(workflow, opts);
257811
257648
  const result = await client.post(`/v1/automations/${workflowId}/examples`, body);
257812
257649
  if (opts.json) {
257813
- printJson6(result);
257650
+ printJson(result);
257814
257651
  return;
257815
257652
  }
257816
257653
  success(`Created example ${ui.bold(opts.name)} (${result.id}) in ${ui.bold(workflowId)}`);
@@ -257836,7 +257673,7 @@ exclusive. To attach files without a dataset folder, pass ingress refs in JSON:
257836
257673
  const { client, workflowId } = await buildClientForWorkflow(workflow, opts);
257837
257674
  const result = await client.patch(`/v1/automations/${workflowId}/examples/${encodeURIComponent(exampleId)}`, body);
257838
257675
  if (opts.json) {
257839
- printJson6(result);
257676
+ printJson(result);
257840
257677
  return;
257841
257678
  }
257842
257679
  const fields = Object.keys(body).join(", ");
@@ -257850,7 +257687,7 @@ exclusive. To attach files without a dataset folder, pass ingress refs in JSON:
257850
257687
  const { client, workflowId } = await buildClientForWorkflow(workflow, opts);
257851
257688
  const deleted = await client.delete(`/v1/automations/${workflowId}/examples/${encodeURIComponent(exampleId)}`);
257852
257689
  if (opts.json) {
257853
- printJson6(deleted);
257690
+ printJson(deleted);
257854
257691
  return;
257855
257692
  }
257856
257693
  success(`Deleted example ${ui.bold(deleted.name ?? exampleId)} ${ui.dim(`(${exampleId})`)} from ${ui.bold(workflowId)}`);
@@ -257860,7 +257697,7 @@ exclusive. To attach files without a dataset folder, pass ingress refs in JSON:
257860
257697
  const { client, workflowId } = await buildClientForWorkflow(workflow, opts);
257861
257698
  const row = await client.get(`/v1/automations/${workflowId}/examples/${encodeURIComponent(exampleId)}`);
257862
257699
  if (opts.json) {
257863
- printJson6(row);
257700
+ printJson(row);
257864
257701
  return;
257865
257702
  }
257866
257703
  renderExampleHuman(row);
@@ -257987,7 +257824,7 @@ returns immediately with \`{ batchId, total }\`; poll
257987
257824
  const total = start.runCount ?? start.total ?? 0;
257988
257825
  if (!opts.wait) {
257989
257826
  if (opts.json) {
257990
- printJson6({ ...start, batchId: experimentId, total });
257827
+ printJson({ ...start, batchId: experimentId, total });
257991
257828
  return;
257992
257829
  }
257993
257830
  success(`Started experiment ${ui.bold(experimentId)} ${ui.dim(`(${total} run${total === 1 ? "" : "s"} queued)`)}`);
@@ -258001,7 +257838,7 @@ returns immediately with \`{ batchId, total }\`; poll
258001
257838
  const status = await client.get(`/v1/automations/${workflowId}/experiments/${experimentId}`);
258002
257839
  if (status.status === "completed") {
258003
257840
  if (opts.json) {
258004
- printJson6({
257841
+ printJson({
258005
257842
  ...status,
258006
257843
  batchId: experimentId,
258007
257844
  total: status.runCount ?? status.total
@@ -258021,7 +257858,7 @@ returns immediately with \`{ batchId, total }\`; poll
258021
257858
  }
258022
257859
  if (Date.now() >= deadline) {
258023
257860
  if (opts.json) {
258024
- printJson6({
257861
+ printJson({
258025
257862
  ...status,
258026
257863
  batchId: experimentId,
258027
257864
  total: status.runCount ?? status.total
@@ -258052,7 +257889,7 @@ returns immediately with \`{ batchId, total }\`; poll
258052
257889
  let execs = [];
258053
257890
  for (let attempt = 1;attempt <= 3; attempt++) {
258054
257891
  result = await client.get(url);
258055
- execs = result.executions ?? result.runs ?? [];
257892
+ execs = result.runs ?? [];
258056
257893
  if (execs.length > 0)
258057
257894
  break;
258058
257895
  if (attempt < 3)
@@ -258061,12 +257898,12 @@ returns immediately with \`{ batchId, total }\`; poll
258061
257898
  const summary = summarizeExperimentExecutions(execs);
258062
257899
  if (execs.length === 0) {
258063
257900
  if (opts.json)
258064
- printJson6({ ...result, summary: rollupForJson(summary) });
257901
+ printJson({ ...result, summary: rollupForJson(summary) });
258065
257902
  error2(`Experiment ${batchId} still has no executions after retrying — check the batch id.`);
258066
257903
  process.exit(1);
258067
257904
  }
258068
257905
  if (opts.json) {
258069
- printJson6({ ...result, summary: rollupForJson(summary) });
257906
+ printJson({ ...result, summary: rollupForJson(summary) });
258070
257907
  return;
258071
257908
  }
258072
257909
  if (opts.short) {
@@ -258098,7 +257935,7 @@ returns immediately with \`{ batchId, total }\`; poll
258098
257935
  maxWait: opts.maxWait,
258099
257936
  onTerminal: (result, summary) => {
258100
257937
  if (wantPayload) {
258101
- printJson6({ ...result, summary: rollupForJson(summary) });
257938
+ printJson({ ...result, summary: rollupForJson(summary) });
258102
257939
  } else {
258103
257940
  process.stderr.write(`${ui.dim(`use --include payload (or --json) for the full per-execution snapshot`)}
258104
257941
  `);
@@ -258106,7 +257943,7 @@ returns immediately with \`{ batchId, total }\`; poll
258106
257943
  },
258107
257944
  onDeadline: (result, summary) => {
258108
257945
  if (wantPayload)
258109
- printJson6({ ...result, summary: rollupForJson(summary) });
257946
+ printJson({ ...result, summary: rollupForJson(summary) });
258110
257947
  }
258111
257948
  });
258112
257949
  }));
@@ -258130,7 +257967,7 @@ Behavior:
258130
257967
  const { client, workflowId } = await buildClientForWorkflow(workflow, opts);
258131
257968
  const result = await client.post(`/v1/automations/${workflowId}/experiments/${batchId}/cancel`);
258132
257969
  if (opts.json) {
258133
- printJson6(result);
257970
+ printJson(result);
258134
257971
  return;
258135
257972
  }
258136
257973
  const c = result.counts;
@@ -258155,7 +257992,7 @@ Behavior:
258155
257992
  addJsonFlag(withBaseUrl(resultsCmd)).action(action(async (workflow, batchId, opts) => {
258156
257993
  const { client, workflowId } = await buildClientForWorkflow(workflow, opts);
258157
257994
  if (opts.json && opts.format !== "json") {
258158
- throw new Error("--json cannot be combined with --format csv");
257995
+ throw new UsageError("--json cannot be combined with --format csv");
258159
257996
  }
258160
257997
  const analyze = opts.summary || opts.failedOnly || opts.evaluator !== undefined || opts.select !== undefined;
258161
257998
  if (analyze) {
@@ -258163,7 +258000,7 @@ Behavior:
258163
258000
  throw new Error("--summary, --failed-only, --evaluator, and --select require a single experiment batch id");
258164
258001
  }
258165
258002
  if (opts.format !== "json") {
258166
- throw new Error("Experiment analysis options require --format json");
258003
+ throw new UsageError("Experiment analysis options require --format json");
258167
258004
  }
258168
258005
  const detailPayload = await client.get(`/v1/automations/${workflowId}/experiments/${encodeURIComponent(batchId)}`);
258169
258006
  const analysis = analyzeExperimentResults({
@@ -258202,9 +258039,9 @@ batches must belong to the same workflow within the caller's tenant.
258202
258039
  const sort = normalizeCompareSort(opts.sort);
258203
258040
  const threshold = opts.regressionThreshold;
258204
258041
  if (!Number.isFinite(threshold) || threshold < 0) {
258205
- throw new Error("--regression-threshold must be a non-negative number");
258042
+ throw new UsageError("--regression-threshold must be a non-negative number");
258206
258043
  }
258207
- const client = buildClient6(opts);
258044
+ const client = buildClient(opts);
258208
258045
  if (opts.outputs) {
258209
258046
  const [outputsA, outputsB] = await Promise.all([
258210
258047
  fetchExperimentOutputs(client, batchIdA),
@@ -258220,7 +258057,7 @@ batches must belong to the same workflow within the caller's tenant.
258220
258057
  rowsB: outputsB.rows
258221
258058
  });
258222
258059
  if (opts.json)
258223
- printJson6(outputDiff);
258060
+ printJson(outputDiff);
258224
258061
  else
258225
258062
  renderExperimentOutputDiffHuman(outputDiff);
258226
258063
  return;
@@ -258238,7 +258075,7 @@ batches must belong to the same workflow within the caller's tenant.
258238
258075
  regressionThreshold: threshold
258239
258076
  });
258240
258077
  if (opts.json) {
258241
- printJson6(diff);
258078
+ printJson(diff);
258242
258079
  return;
258243
258080
  }
258244
258081
  renderBatchDiffHuman(diff);
@@ -258276,7 +258113,7 @@ Behavior:
258276
258113
  const dest = opts.pull ? opts.pullOnComplete ?? `./results-${batchId}.${opts.format}` : null;
258277
258114
  if (dest) {
258278
258115
  const dir = path19.dirname(dest);
258279
- if (!existsSync24(dir)) {
258116
+ if (!existsSync21(dir)) {
258280
258117
  error2(`Destination directory does not exist: ${dir}. Create it first or pass a path under an existing directory.`);
258281
258118
  process.exit(2);
258282
258119
  }
@@ -258371,60 +258208,61 @@ async function pollExperimentUntilTerminal({
258371
258208
  onTerminal,
258372
258209
  onDeadline
258373
258210
  }) {
258374
- const deadline = Date.now() + maxWait * 1000;
258375
258211
  let lastSummary = "";
258376
258212
  let emptyPolls = 0;
258377
- while (true) {
258378
- const result = await client.get(url);
258379
- const execs = result.executions ?? result.runs ?? [];
258380
- if (execs.length === 0) {
258381
- emptyPolls += 1;
258382
- if (emptyPolls >= 3) {
258383
- if (process.stderr.isTTY)
258384
- process.stderr.write(`
258213
+ const poll = await pollUntil({
258214
+ fetch: async () => {
258215
+ const result = await client.get(url);
258216
+ const execs = result.runs ?? [];
258217
+ return { result, summary: summarizeExperimentExecutions(execs), execs };
258218
+ },
258219
+ onTick: ({ execs, summary }) => {
258220
+ if (execs.length === 0) {
258221
+ emptyPolls += 1;
258222
+ if (emptyPolls >= 3) {
258223
+ if (process.stderr.isTTY)
258224
+ process.stderr.write(`
258385
258225
  `);
258386
- error2(`Experiment still has no executions after ${emptyPolls} polls — check the batch id.`);
258387
- process.exit(1);
258388
- }
258389
- } else {
258390
- emptyPolls = 0;
258391
- }
258392
- const summary = summarizeExperimentExecutions(execs);
258393
- const line = renderTickLine(summary);
258394
- if (line !== lastSummary) {
258395
- if (process.stderr.isTTY) {
258396
- process.stderr.write(`\r\x1B[K${line}`);
258226
+ error2(`Experiment still has no executions after ${emptyPolls} polls. Check the batch id.`);
258227
+ process.exit(1);
258228
+ }
258397
258229
  } else {
258398
- process.stderr.write(`${line}
258399
- `);
258230
+ emptyPolls = 0;
258400
258231
  }
258401
- lastSummary = line;
258402
- }
258403
- if (summary.done) {
258404
- if (process.stderr.isTTY)
258405
- process.stderr.write(`
258232
+ const line = renderTickLine(summary);
258233
+ if (line !== lastSummary) {
258234
+ if (process.stderr.isTTY) {
258235
+ process.stderr.write(`\r\x1B[K${line}`);
258236
+ } else {
258237
+ process.stderr.write(`${line}
258406
258238
  `);
258407
- const failed = summary.counts.failed ?? 0;
258408
- const cancelled = summary.counts.cancelled ?? 0;
258409
- const rejected = summary.counts.rejected ?? 0;
258410
- const badCount = failed + cancelled + rejected;
258411
- if (badCount > 0)
258412
- renderExperimentFailures(execs, summary.total);
258413
- await onTerminal(result, summary);
258414
- if (badCount > 0)
258415
- process.exit(1);
258416
- return;
258417
- }
258418
- if (Date.now() >= deadline) {
258419
- if (process.stderr.isTTY)
258420
- process.stderr.write(`
258239
+ }
258240
+ lastSummary = line;
258241
+ }
258242
+ },
258243
+ isTerminal: ({ summary }) => summary.done,
258244
+ intervalMs: interval * 1000,
258245
+ maxWaitMs: maxWait * 1000
258246
+ });
258247
+ const { result, execs, summary } = poll.value;
258248
+ if (!poll.timedOut) {
258249
+ if (process.stderr.isTTY)
258250
+ process.stderr.write(`
258421
258251
  `);
258422
- error2(`Timed out after ${maxWait}s with ${summary.total - summary.terminal} non-terminal execution(s). Re-run to keep watching.`);
258423
- onDeadline?.(result, summary);
258424
- process.exit(2);
258425
- }
258426
- await new Promise((r) => setTimeout(r, interval * 1000));
258252
+ const badCount = (summary.counts.failed ?? 0) + (summary.counts.cancelled ?? 0) + (summary.counts.rejected ?? 0);
258253
+ if (badCount > 0)
258254
+ renderExperimentFailures(execs, summary.total);
258255
+ await onTerminal(result, summary);
258256
+ if (badCount > 0)
258257
+ process.exit(1);
258258
+ return;
258427
258259
  }
258260
+ if (process.stderr.isTTY)
258261
+ process.stderr.write(`
258262
+ `);
258263
+ error2(`Timed out after ${maxWait}s with ${summary.total - summary.terminal} non-terminal execution(s). Re-run to keep watching.`);
258264
+ onDeadline?.(result, summary);
258265
+ process.exit(2);
258428
258266
  }
258429
258267
  function registerVersionsCommands(parent) {
258430
258268
  const versions = parent.command("versions").description("Create, list, promote, and restore YAML workflow versions.").addHelpText("after", `
@@ -258523,7 +258361,7 @@ sent to the server is replaced with \`templateId\` + \`templateRevisionId\`.
258523
258361
  const result = await client.post(automationVersionsPath(workflowId), body).catch((err) => rethrowAfterTemplateCleanup(client, created, err));
258524
258362
  await finalizeCreatedWorkspaceTemplates(client, created);
258525
258363
  if (opts.json) {
258526
- printJson6(withLocalTemplates(result, resolvedTemplates));
258364
+ printJson(withLocalTemplates(result, resolvedTemplates));
258527
258365
  return;
258528
258366
  }
258529
258367
  const id = typeof result.id === "string" ? result.id : "?";
@@ -258546,7 +258384,7 @@ restore HEAD) return 404 — create a tagged copy first.
258546
258384
  const { client, workflowId } = await buildClientForWorkflow(workflow, opts);
258547
258385
  const result = await client.post(automationVersionsPath(workflowId, `/${encodeURIComponent(versionId)}/promote`));
258548
258386
  if (opts.json) {
258549
- printJson6(result);
258387
+ printJson(result);
258550
258388
  return;
258551
258389
  }
258552
258390
  const label = formatWorkflowVersionLabel(result.version);
@@ -258569,7 +258407,7 @@ promoted until you create a tagged copy.
258569
258407
  const body = opts.message ? { message: opts.message } : {};
258570
258408
  const result = await client.post(automationVersionsPath(workflowId, `/${encodeURIComponent(versionId)}/restore`), body);
258571
258409
  if (opts.json) {
258572
- printJson6(result);
258410
+ printJson(result);
258573
258411
  return;
258574
258412
  }
258575
258413
  const id = typeof result.id === "string" ? result.id : "?";
@@ -259002,29 +258840,19 @@ program2.name("eigenpal").description("Eigenpal CLI — AI workflows, evals, and
259002
258840
  setJsonMode(true);
259003
258841
  });
259004
258842
  program2.command("status").description("One-shot dashboard: server, active tenant, user, key id, workflow count. Pair with `--json` for scripting.").option("--base-url <url>", "Server base URL").option("--json", "Emit machine-readable JSON instead of human-readable text").action(action(async (opts) => status(opts)));
259005
- var initCmd = program2.command("init [name]").description("Scaffold a new workflow project. Without `[name]`, scaffolds into the current directory using the cwd basename as the workflow name. With `[name]`, creates `./<name>/` and uses that as the slug. The flat layout matches what `run workflows.<slug>` already discovers — no manual file moves.").option("--template <name>", "Skip the picker; use this template").option("--dir <dir>", "Target directory (default: cwd if `[name]` omitted, else ./<name>)").option("--yes", "Non-interactive: pick the default template (blank)").action(async (name, opts) => {
259006
- try {
259007
- if (name) {
259008
- await init(name, opts);
259009
- } else {
259010
- const path = await import("node:path");
259011
- const raw = path.basename(process.cwd());
259012
- const slug = /^[a-z0-9][a-z0-9-_]*$/.test(raw) && raw.length <= 60 ? raw : "my-workflow";
259013
- await init(slug, { ...opts, dir: opts.dir ?? "." });
259014
- }
259015
- } catch (err) {
259016
- console.error(err instanceof Error ? err.message : String(err));
259017
- process.exit(1);
259018
- }
259019
- });
259020
- initCmd.command("workflow <name>").description("Alias of `eigenpal init <name>`. Kept so the `init {workflow,agent}` namespace stays visible — once the agent surface lights up, both kinds will live as siblings here.").option("--template <name>", "Skip the picker; use this template").option("--dir <dir>", "Target directory (default: ./<name>)").option("--yes", "Non-interactive: pick the default template (blank)").action(async (name, opts) => {
259021
- try {
258843
+ var initCmd = program2.command("init [name]").description("Scaffold a new workflow project. Without `[name]`, scaffolds into the current directory using the cwd basename as the workflow name. With `[name]`, creates `./<name>/` and uses that as the slug. The flat layout matches what `run workflows.<slug>` already discovers — no manual file moves.").option("--template <name>", "Skip the picker; use this template").option("--dir <dir>", "Target directory (default: cwd if `[name]` omitted, else ./<name>)").option("--yes", "Non-interactive: pick the default template (blank)").action(action(async (name, opts) => {
258844
+ if (name) {
259022
258845
  await init(name, opts);
259023
- } catch (err) {
259024
- console.error(err instanceof Error ? err.message : String(err));
259025
- process.exit(1);
258846
+ } else {
258847
+ const path = await import("node:path");
258848
+ const raw = path.basename(process.cwd());
258849
+ const slug = /^[a-z0-9][a-z0-9-_]*$/.test(raw) && raw.length <= 60 ? raw : "my-workflow";
258850
+ await init(slug, { ...opts, dir: opts.dir ?? "." });
259026
258851
  }
259027
- });
258852
+ }));
258853
+ initCmd.command("workflow <name>").description("Alias of `eigenpal init <name>`. Kept so the `init {workflow,agent}` namespace stays visible — once the agent surface lights up, both kinds will live as siblings here.").option("--template <name>", "Skip the picker; use this template").option("--dir <dir>", "Target directory (default: ./<name>)").option("--yes", "Non-interactive: pick the default template (blank)").action(action(async (name, opts) => {
258854
+ await init(name, opts);
258855
+ }));
259028
258856
  var authCmd = program2.command("auth").description("Manage authentication. Credentials live in ~/.config/eigenpal/credentials.json as named profiles. Switch tenants with `auth use <name>` or set `EIGENPAL_PROFILE=<name>` for one shell.");
259029
258857
  authCmd.command("login").description("Authenticate with Eigenpal. Opens a browser to create an API key, stores it under a profile named after the tenant, and makes that profile active. Re-running `login` against the same tenant updates the existing profile in place.").option("--base-url <url>", "Server base URL", undefined).addHelpText("after", `
259030
258858
  Examples:
@@ -259057,15 +258885,9 @@ registerRunsCommands(program2);
259057
258885
  registerReviewsCommands(program2);
259058
258886
  registerGitCommands(program2);
259059
258887
  registerDocsCommands(program2);
259060
- program2.command("completion <shell>").description("Print a shell completion script to stdout (supported shells: bash, zsh, fish). Pipe into the appropriate completion file for your shell — see the script header for install instructions.").action(async (shell) => {
259061
- try {
259062
- await completion(shell, program2);
259063
- } catch (err) {
259064
- process.stderr.write(`${err instanceof Error ? err.message : String(err)}
259065
- `);
259066
- process.exit(1);
259067
- }
259068
- });
258888
+ program2.command("completion <shell>").description("Print a shell completion script to stdout (supported shells: bash, zsh, fish). Pipe into the appropriate completion file for your shell — see the script header for install instructions.").action(action(async (shell) => {
258889
+ await completion(shell, program2);
258890
+ }));
259069
258891
  var skillCmd = program2.command("skill").description("Install / uninstall / list the Eigenpal agent skill in your project (Claude Code, Cursor, Codex, Gemini CLI, Antigravity, OpenCode, Pi, Windsurf, GitHub Copilot).").action(() => {
259070
258892
  process.stderr.write("`eigenpal skill` requires a subcommand: `install`, `uninstall`, or `list`.\nRun `eigenpal skill --help` to see options.\n");
259071
258893
  process.exit(2);
@@ -259087,36 +258909,21 @@ Examples
259087
258909
  eigenpal skill install # interactive picker
259088
258910
  eigenpal skill install --tools claude,cursor --yes # scripted install
259089
258911
  eigenpal skill install --tools "" --yes # uninstall everything via install picker
259090
- `).action(async (opts) => {
259091
- try {
259092
- await installSkillTools(opts);
259093
- } catch (err) {
259094
- console.error(err instanceof Error ? err.message : String(err));
259095
- process.exit(1);
259096
- }
259097
- });
258912
+ `).action(action(async (opts) => {
258913
+ await installSkillTools(opts);
258914
+ }));
259098
258915
  skillCmd.command("uninstall [toolIds...]").description("Remove the skill from named tools (e.g. `skill uninstall claude cursor`), pass `--all` to wipe every install, or run with no args in a TTY for an interactive picker showing only installed tools.").option("--all", "Uninstall every tool that has an Eigenpal skill installed").option("--target <path>", "Power-user override: uninstall a single custom directory (skips tool detection)").option("--yes", "Required for non-TTY shells; skips confirmation in TTY").addHelpText("after", `${SUPPORTED_TOOLS_BLOCK}
259099
258916
  Examples
259100
258917
  eigenpal skill uninstall claude # remove one
259101
258918
  eigenpal skill uninstall claude cursor # remove several
259102
258919
  eigenpal skill uninstall --all --yes # remove every install (CI / scripts)
259103
258920
  eigenpal skill uninstall # interactive picker (only installed tools shown)
259104
- `).action(async (toolIds, opts) => {
259105
- try {
259106
- await uninstallSkillTools({ toolIds, ...opts });
259107
- } catch (err) {
259108
- console.error(err instanceof Error ? err.message : String(err));
259109
- process.exit(1);
259110
- }
259111
- });
259112
- skillCmd.command("list").description("Show every tool that has an Eigenpal skill installed in the current directory, with the CLI version that wrote it.").option("--json", "Emit machine-readable JSON instead of a table").action((opts) => {
259113
- try {
259114
- listSkillTools(opts);
259115
- } catch (err) {
259116
- console.error(err instanceof Error ? err.message : String(err));
259117
- process.exit(1);
259118
- }
259119
- });
258921
+ `).action(action(async (toolIds, opts) => {
258922
+ await uninstallSkillTools({ toolIds, ...opts });
258923
+ }));
258924
+ skillCmd.command("list").description("Show every tool that has an Eigenpal skill installed in the current directory, with the CLI version that wrote it.").option("--json", "Emit machine-readable JSON instead of a table").action(action(async (opts) => {
258925
+ listSkillTools(opts);
258926
+ }));
259120
258927
  applyCommandAliasConventions(program2);
259121
258928
  function isEntryPoint() {
259122
258929
  const argv1 = process.argv[1];