@mutagent/cli 0.1.195 → 0.1.197

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/index.js CHANGED
@@ -316,125 +316,6 @@ var init_errors = __esm(() => {
316
316
  };
317
317
  });
318
318
 
319
- // src/lib/scorecard-extraction.ts
320
- function extractScorecardDetails(rawState, iterCtx) {
321
- if (!iterCtx)
322
- return {};
323
- const gc = rawState.globalContext;
324
- const gcCtx = gc?.context;
325
- const beforeExec = gcCtx?.executions;
326
- const beforeResults = beforeExec?.results ?? [];
327
- const beforeById = new Map;
328
- for (const r of beforeResults) {
329
- const id = r.id;
330
- if (id)
331
- beforeById.set(id, r);
332
- }
333
- let originalScore;
334
- if (beforeResults.length > 0) {
335
- const sum = beforeResults.reduce((acc, r) => {
336
- const eval_ = r.evaluation;
337
- return acc + (eval_?.score ?? 0);
338
- }, 0);
339
- originalScore = sum / beforeResults.length;
340
- }
341
- const afterExec = iterCtx.executionResults;
342
- const afterResults = afterExec?.executions ?? [];
343
- const datasetResults = afterResults.length > 0 ? afterResults.map((r) => {
344
- const id = r.id || "unknown";
345
- const afterEval = r.evaluation;
346
- const afterScore = afterEval?.score ?? 0;
347
- const beforeResult = beforeById.get(id);
348
- const beforeEval = beforeResult?.evaluation;
349
- const beforeScore = beforeEval?.score;
350
- return { id, beforeScore, afterScore };
351
- }) : undefined;
352
- const criteriaScores = extractCriteriaScores(beforeResults, afterResults);
353
- const rawFailureModes = iterCtx.failureModes;
354
- const failureModes = rawFailureModes?.categories && rawFailureModes.failures ? rawFailureModes.categories.map((category) => ({
355
- category,
356
- failures: (rawFailureModes.failures?.[category] ?? []).map((f) => ({
357
- description: f.description ?? f.label,
358
- summary: f.summary
359
- }))
360
- })) : undefined;
361
- const rawMutations = iterCtx.mutations;
362
- const mutations = rawMutations && rawMutations.length > 0 ? rawMutations.map((m) => ({
363
- label: m.label ?? "Unknown mutation",
364
- status: m.status ?? "pending",
365
- priority: m.priority,
366
- rationale: m.target?.rationale
367
- })) : undefined;
368
- const evaluationDetails = afterResults.length > 0 ? afterResults.map((r) => {
369
- const id = r.id || "unknown";
370
- const eval_ = r.evaluation;
371
- const score = eval_?.score ?? 0;
372
- const success = eval_?.success ?? false;
373
- const metrics = eval_?.evaluations?.map((metric) => {
374
- const criteria = metric.evaluationChecklist?.items?.map((item) => ({
375
- name: item.evaluationParameter ?? item.criteria ?? "unknown",
376
- score: item.llmScore ?? 0,
377
- success: item.success ?? false
378
- }));
379
- return {
380
- name: metric.name ?? "unknown",
381
- score: metric.score ?? 0,
382
- success: metric.success ?? false,
383
- failureMode: metric.failureMode,
384
- reasoning: metric.reasoning,
385
- criteria: criteria && criteria.length > 0 ? criteria : undefined
386
- };
387
- });
388
- return {
389
- itemId: id,
390
- score,
391
- success,
392
- metrics: metrics && metrics.length > 0 ? metrics : undefined
393
- };
394
- }) : undefined;
395
- return {
396
- originalScore,
397
- criteriaScores,
398
- datasetResults,
399
- failureModes,
400
- mutations,
401
- evaluationDetails
402
- };
403
- }
404
- function extractCriteriaScores(beforeResults, afterResults) {
405
- const metricNames = new Set;
406
- const beforeScores = new Map;
407
- const afterScores = new Map;
408
- for (const r of beforeResults) {
409
- const eval_ = r.evaluation;
410
- for (const m of eval_?.evaluations ?? []) {
411
- const name = m.name ?? "unknown";
412
- metricNames.add(name);
413
- const existing = beforeScores.get(name) ?? [];
414
- existing.push(m.score ?? 0);
415
- beforeScores.set(name, existing);
416
- }
417
- }
418
- for (const r of afterResults) {
419
- const eval_ = r.evaluation;
420
- for (const m of eval_?.evaluations ?? []) {
421
- const name = m.name ?? "unknown";
422
- metricNames.add(name);
423
- const existing = afterScores.get(name) ?? [];
424
- existing.push(m.score ?? 0);
425
- afterScores.set(name, existing);
426
- }
427
- }
428
- if (metricNames.size === 0)
429
- return;
430
- const avg = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;
431
- return Array.from(metricNames).map((name) => ({
432
- name,
433
- before: beforeScores.has(name) ? avg(beforeScores.get(name) ?? []) : undefined,
434
- after: afterScores.has(name) ? avg(afterScores.get(name) ?? []) : undefined
435
- }));
436
- }
437
-
438
319
  // src/lib/sdk-client.ts
439
320
  var exports_sdk_client = {};
440
321
  __export(exports_sdk_client, {
@@ -545,394 +426,6 @@ class SDKClientWrapper {
545
426
  }
546
427
  return response.json();
547
428
  }
548
- async listPrompts() {
549
- try {
550
- const response = await this.sdk.prompt.listPrompts();
551
- return response.result.data;
552
- } catch (error) {
553
- this.handleError(error);
554
- }
555
- }
556
- async getPrompt(id) {
557
- try {
558
- const response = await this.sdk.prompt.getPrompt({ id: parseInt(id, 10) });
559
- return response;
560
- } catch (error) {
561
- this.handleError(error);
562
- }
563
- }
564
- async createPrompt(data) {
565
- try {
566
- const response = await this.sdk.prompt.createPrompt({
567
- name: data.name ?? "",
568
- description: data.description ?? undefined,
569
- version: data.version ?? undefined,
570
- isLatest: data.isLatest ?? undefined,
571
- systemPrompt: data.systemPrompt ?? undefined,
572
- humanPrompt: data.humanPrompt ?? undefined,
573
- rawPrompt: data.rawPrompt ?? undefined,
574
- inputSchema: data.inputSchema ?? undefined,
575
- outputSchema: data.outputSchema ?? undefined,
576
- metadata: data.metadata ?? undefined,
577
- tags: data.tags ?? undefined
578
- });
579
- return response;
580
- } catch (error) {
581
- this.handleError(error);
582
- }
583
- }
584
- async updatePrompt(id, data) {
585
- try {
586
- const body = {
587
- description: data.description ?? undefined,
588
- isLatest: data.isLatest ?? undefined,
589
- systemPrompt: data.systemPrompt ?? undefined,
590
- humanPrompt: data.humanPrompt ?? undefined,
591
- rawPrompt: data.rawPrompt ?? undefined,
592
- inputSchema: data.inputSchema,
593
- outputSchema: data.outputSchema,
594
- metadata: data.metadata,
595
- tags: data.tags ?? undefined
596
- };
597
- if (data.name !== undefined) {
598
- body.name = data.name;
599
- }
600
- const updateArgs = { id: parseInt(id, 10), body };
601
- const response = await this.sdk.prompt.updatePrompt(updateArgs);
602
- return response;
603
- } catch (error) {
604
- this.handleError(error);
605
- }
606
- }
607
- async deletePrompt(id, options) {
608
- try {
609
- if (options?.force) {
610
- await this.request(`/api/prompt/${id}?force=true`, { method: "DELETE" });
611
- } else {
612
- await this.sdk.prompt.deletePrompt({ id: parseInt(id, 10) });
613
- }
614
- } catch (error) {
615
- this.handleError(error);
616
- }
617
- }
618
- async getDataset(datasetId) {
619
- try {
620
- return await this.request(`/api/prompts/datasets/${String(datasetId)}`);
621
- } catch (error) {
622
- this.handleError(error);
623
- }
624
- }
625
- async getDatasetItem(itemId) {
626
- try {
627
- return await this.request(`/api/prompts/dataset-items/${String(itemId)}`);
628
- } catch (error) {
629
- this.handleError(error);
630
- }
631
- }
632
- async listDatasets(promptId) {
633
- try {
634
- const response = await this.request(`/api/prompt/${promptId}/datasets`);
635
- return Array.isArray(response) ? response : response.data;
636
- } catch (error) {
637
- this.handleError(error);
638
- }
639
- }
640
- async addDataset(promptId, fileContent, name) {
641
- try {
642
- let parsed;
643
- try {
644
- parsed = JSON.parse(fileContent);
645
- } catch {
646
- parsed = null;
647
- }
648
- let datasetName = name ?? `Dataset ${new Date().toISOString().slice(0, 16)}`;
649
- let items;
650
- if (parsed !== null && !Array.isArray(parsed) && typeof parsed === "object" && "name" in parsed) {
651
- const meta = parsed;
652
- datasetName = meta.name ?? datasetName;
653
- if (Array.isArray(meta.items)) {
654
- items = meta.items;
655
- }
656
- } else if (Array.isArray(parsed)) {
657
- items = parsed;
658
- }
659
- const dataset = await this.request(`/api/prompt/${promptId}/datasets`, {
660
- method: "POST",
661
- body: JSON.stringify({
662
- name: datasetName
663
- })
664
- });
665
- let itemCount = 0;
666
- if (items && items.length > 0) {
667
- const mappedItems = items.map((item, index) => ({
668
- input: item.input ?? item,
669
- expectedOutput: item.expectedOutput ?? item.expected_output ?? undefined,
670
- name: item.name ?? `Item ${String(index + 1)}`,
671
- userFeedback: item.userFeedback,
672
- systemFeedback: item.systemFeedback,
673
- labels: item.labels,
674
- metadata: item.metadata
675
- }));
676
- const missingExpectedOutputCount = mappedItems.filter((item) => item.expectedOutput === undefined).length;
677
- await this.request(`/api/prompts/datasets/${String(dataset.id)}/items/bulk`, {
678
- method: "POST",
679
- body: JSON.stringify({ items: mappedItems })
680
- });
681
- itemCount = mappedItems.length;
682
- return { ...dataset, itemCount, missingExpectedOutputCount };
683
- }
684
- return { ...dataset, itemCount };
685
- } catch (error) {
686
- this.handleError(error);
687
- }
688
- }
689
- async listDatasetItems(datasetId) {
690
- try {
691
- const response = await this.request(`/api/prompts/datasets/${datasetId}/items`);
692
- return Array.isArray(response) ? response : response.data;
693
- } catch (error) {
694
- this.handleError(error);
695
- }
696
- }
697
- async deleteDataset(_promptId, datasetId, options) {
698
- try {
699
- const query = options?.force ? "?force=true" : "";
700
- await this.request(`/api/prompts/datasets/${datasetId}${query}`, { method: "DELETE" });
701
- } catch (error) {
702
- this.handleError(error);
703
- }
704
- }
705
- async listEvaluations(promptId) {
706
- try {
707
- const response = await this.request(`/api/prompts/evaluations?promptId=${promptId}`);
708
- return response.data;
709
- } catch (error) {
710
- this.handleError(error);
711
- }
712
- }
713
- async getEvaluation(evaluationId) {
714
- try {
715
- return await this.request(`/api/prompts/evaluations/${evaluationId}`);
716
- } catch (error) {
717
- this.handleError(error);
718
- }
719
- }
720
- async createEvaluation(promptId, data) {
721
- try {
722
- return await this.request("/api/prompts/evaluations", {
723
- method: "POST",
724
- body: JSON.stringify({
725
- promptId: parseInt(promptId, 10),
726
- name: data.name,
727
- description: data.description,
728
- evalConfig: data.evalConfig,
729
- llmConfig: data.llmConfig,
730
- tags: data.tags,
731
- metadata: data.metadata
732
- })
733
- });
734
- } catch (error) {
735
- this.handleError(error);
736
- }
737
- }
738
- async deleteEvaluation(evaluationId) {
739
- try {
740
- await this.request(`/api/prompts/evaluations/${evaluationId}`, { method: "DELETE" });
741
- } catch (error) {
742
- this.handleError(error);
743
- }
744
- }
745
- async listOptimizations() {
746
- try {
747
- const response = await this.request("/api/optimizations");
748
- if (Array.isArray(response))
749
- return response;
750
- const r = response;
751
- if (Array.isArray(r.data))
752
- return r.data;
753
- return [];
754
- } catch (error) {
755
- this.handleError(error);
756
- }
757
- }
758
- async listExperiments(filters) {
759
- try {
760
- const params = new URLSearchParams;
761
- if (filters?.promptId !== undefined)
762
- params.set("promptId", String(filters.promptId));
763
- if (filters?.status)
764
- params.set("status", filters.status);
765
- if (filters?.limit !== undefined)
766
- params.set("limit", String(filters.limit));
767
- if (filters?.offset !== undefined)
768
- params.set("offset", String(filters.offset));
769
- const qs = params.toString();
770
- const response = await this.request(`/api/prompts/experiments${qs ? `?${qs}` : ""}`);
771
- if (Array.isArray(response))
772
- return { experiments: response, total: response.length };
773
- const r = response;
774
- const experiments = r.experiments ?? r.data ?? [];
775
- return { experiments, total: r.total ?? experiments.length };
776
- } catch (error) {
777
- this.handleError(error);
778
- }
779
- }
780
- async createExperiment(data) {
781
- try {
782
- return await this.request("/api/prompts/experiments", {
783
- method: "POST",
784
- body: JSON.stringify(data)
785
- });
786
- } catch (error) {
787
- this.handleError(error);
788
- }
789
- }
790
- async getExperiment(id) {
791
- try {
792
- return await this.request(`/api/prompts/experiments/${id}`);
793
- } catch (error) {
794
- this.handleError(error);
795
- }
796
- }
797
- async deleteExperiment(id) {
798
- try {
799
- await this.request(`/api/prompts/experiments/${id}`, { method: "DELETE" });
800
- } catch (error) {
801
- this.handleError(error);
802
- }
803
- }
804
- async executeExperiment(id) {
805
- try {
806
- return await this.request(`/api/prompts/experiments/${id}/execute`, { method: "POST", body: JSON.stringify({}) });
807
- } catch (error) {
808
- this.handleError(error);
809
- }
810
- }
811
- async playgroundEval(promptId, data) {
812
- try {
813
- return await this.request(`/api/prompt/${promptId}/playground/eval`, {
814
- method: "POST",
815
- body: JSON.stringify(data)
816
- });
817
- } catch (error) {
818
- this.handleError(error);
819
- }
820
- }
821
- async cancelOptimization(jobId) {
822
- try {
823
- return await this.request(`/api/optimization/${jobId}/cancel`, {
824
- method: "POST"
825
- });
826
- } catch (error) {
827
- this.handleError(error);
828
- }
829
- }
830
- async startOptimization(promptId, datasetId, evaluationId, config) {
831
- try {
832
- return await this.request(`/api/prompt/${promptId}/optimize`, {
833
- method: "POST",
834
- body: JSON.stringify({
835
- datasetId: parseInt(datasetId, 10),
836
- evaluationId: parseInt(evaluationId, 10),
837
- config: {
838
- maxIterations: config?.maxIterations ?? 1,
839
- targetScore: config?.targetScore ?? 0.8,
840
- patience: config?.patience,
841
- ...config?.execModel ? { executionModel: config.execModel } : {},
842
- ...config?.model ? { model: config.model } : {},
843
- ...config?.evalModel ? { evaluationModel: config.evalModel } : {},
844
- ...config?.optModel ? { optimizationModel: config.optModel } : {},
845
- ...config?.providerId ? { executionProviderId: config.providerId } : {},
846
- ...config?.evalProviderId ? { evaluationProviderId: config.evalProviderId } : {},
847
- ...config?.optProviderId ? { optimizationProviderId: config.optProviderId } : {}
848
- },
849
- executionMode: "worker_loop"
850
- })
851
- });
852
- } catch (error) {
853
- this.handleError(error);
854
- }
855
- }
856
- async getOptimizationStatus(jobId) {
857
- try {
858
- const raw = await this.request(`/api/optimization/${jobId}`);
859
- const id = raw.id;
860
- return {
861
- ...raw,
862
- jobId: id ?? jobId,
863
- progressPercent: typeof raw.progress === "number" ? raw.progress : 0
864
- };
865
- } catch (error) {
866
- this.handleError(error);
867
- }
868
- }
869
- async getOptimizationScorecard(jobId) {
870
- try {
871
- const res = await this.request(`/api/optimization/${jobId}/results`);
872
- if (res.scorecard?.rendered) {
873
- return { rendered: res.scorecard.rendered, data: res.scorecard.data ?? [] };
874
- }
875
- return null;
876
- } catch {
877
- return null;
878
- }
879
- }
880
- async getOptimizationResults(jobId) {
881
- try {
882
- const job = await this.request(`/api/optimization/${jobId}`);
883
- const progress = await this.request(`/api/optimization/${jobId}/progress`);
884
- const prompt = await this.getPrompt(String(job.promptId ?? ""));
885
- const statesRes = await this.request(`/api/optimization/${jobId}/states`).catch(() => ({ states: [] }));
886
- const scorecardDigest = await this.getOptimizationScorecard(jobId);
887
- const latestState = statesRes.states[statesRes.states.length - 1];
888
- const rawState = latestState?.state ?? {};
889
- const iterCtx = rawState.iterationContext ?? rawState.current?.context;
890
- const basePromptObj = iterCtx?.basePrompt;
891
- const currentPromptObj = iterCtx?.currentPrompt;
892
- const mutatedPromptText = typeof currentPromptObj?.prompt === "string" ? currentPromptObj.prompt : undefined;
893
- const originalPromptText = typeof basePromptObj?.prompt === "string" ? basePromptObj.prompt : undefined;
894
- const extracted = extractScorecardDetails(rawState, iterCtx);
895
- return {
896
- job: {
897
- id: job.id ?? jobId,
898
- promptId: job.promptId ?? 0,
899
- status: job.status ?? "unknown",
900
- config: job.config
901
- },
902
- prompt,
903
- bestScore: job.bestScore,
904
- originalScore: extracted.originalScore,
905
- iterationsCompleted: job.currentIteration,
906
- scoreProgression: Array.isArray(progress.progression) ? progress.progression.map((p) => typeof p.score === "number" ? p.score : 0) : undefined,
907
- mutatedPromptText,
908
- originalPromptText,
909
- criteriaScores: extracted.criteriaScores,
910
- datasetResults: extracted.datasetResults,
911
- failureModes: extracted.failureModes,
912
- mutations: extracted.mutations,
913
- evaluationDetails: extracted.evaluationDetails,
914
- ...scorecardDigest ? { scorecard: scorecardDigest } : {}
915
- };
916
- } catch (error) {
917
- this.handleError(error);
918
- }
919
- }
920
- async listTraces(filters) {
921
- const filterRecord = {};
922
- if (filters?.promptId)
923
- filterRecord.promptId = filters.promptId;
924
- if (filters?.source)
925
- filterRecord.source = filters.source;
926
- const params = Object.keys(filterRecord).length > 0 ? new URLSearchParams(filterRecord).toString() : "";
927
- const response = await this.request(`/api/traces${params ? `?${params}` : ""}`);
928
- return response.data ?? [];
929
- }
930
- async getTrace(id) {
931
- return this.request(`/api/traces/${id}?include=io`);
932
- }
933
- async analyzeTraces(promptId) {
934
- return this.request(`/api/prompts/${promptId}/trace-analysis`);
935
- }
936
429
  async listAgents(filters) {
937
430
  try {
938
431
  const response = await this.sdk.agents.listAgents({
@@ -1040,42 +533,6 @@ class SDKClientWrapper {
1040
533
  this.handleError(error);
1041
534
  }
1042
535
  }
1043
- async executePrompt(promptId, input, options) {
1044
- try {
1045
- return await this.request(`/api/prompt/${promptId}/playground/call`, {
1046
- method: "POST",
1047
- body: JSON.stringify({ input, model: options?.model })
1048
- });
1049
- } catch (error) {
1050
- this.handleError(error);
1051
- }
1052
- }
1053
- async executePromptStream(promptId, input, options) {
1054
- const response = await fetch(`${this.endpoint}/api/prompt/${promptId}/execute/stream`, {
1055
- method: "POST",
1056
- headers: {
1057
- "x-api-key": this.apiKey,
1058
- "Content-Type": "application/json",
1059
- Accept: "text/event-stream"
1060
- },
1061
- body: JSON.stringify({ input, ...options })
1062
- });
1063
- if (!response.ok) {
1064
- if (response.status === 401) {
1065
- throw new AuthenticationError;
1066
- }
1067
- if (response.status === 403) {
1068
- throw new ApiError(403, await response.text() || "Access denied");
1069
- }
1070
- const error = await response.text();
1071
- const errorLower = error.toLowerCase();
1072
- if (errorLower.includes("workspace") && (errorLower.includes("missing") || errorLower.includes("required")) || errorLower.includes("x-workspace-id")) {
1073
- throw new WorkspaceContextError(error);
1074
- }
1075
- throw new ApiError(response.status, error);
1076
- }
1077
- return response;
1078
- }
1079
536
  async listProviders(filters) {
1080
537
  try {
1081
538
  const response = await this.sdk.providerConfigs.listProviders({
@@ -1479,5 +936,5 @@ export {
1479
936
  ApiError
1480
937
  };
1481
938
 
1482
- //# debugId=AB7295C3E53F637C64756E2164756E21
939
+ //# debugId=19176E018FECFE2064756E2164756E21
1483
940
  //# sourceMappingURL=index.js.map