@standardagents/cli 0.45.9 → 0.45.11

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
@@ -9,15 +9,16 @@ import crypto2, { createHash } from 'crypto';
9
9
  import childProcess, { spawn, spawnSync, execFileSync } from 'child_process';
10
10
  import os5 from 'os';
11
11
  import net from 'net';
12
- import chalk from 'chalk';
12
+ import chalk, { chalkStderr } from 'chalk';
13
13
  import { parse, parseDocument, visit, isScalar, isNode, isMap } from 'yaml';
14
14
  import { loadFile, writeFile, generateCode, builders } from 'magicast';
15
15
  import { addVitePlugin, getDefaultExportOptions } from 'magicast/helpers';
16
- import { useState, useMemo } from 'react';
17
- import { render, renderToString, Box, Text, useApp, useInput } from 'ink';
16
+ import { useState, useEffect, useSyncExternalStore } from 'react';
17
+ import { render, useApp, useInput, Text, Box, useStdout } from 'ink';
18
18
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
19
19
  import readline from 'readline';
20
20
  import { createRequire } from 'module';
21
+ import { EventEmitter } from 'events';
21
22
  import { copySkill } from '@standardagents/skill';
22
23
 
23
24
  // src/utils/platform-endpoint.ts
@@ -122,13 +123,13 @@ ${next}`);
122
123
  }
123
124
  };
124
125
  var RedirectRefusedError = class extends Error {
125
- constructor(host, status2, next) {
126
+ constructor(host, status, next) {
126
127
  super(
127
- `${host} answered with a redirect (HTTP ${status2}). The CLI does not follow a redirect with your sign-in.
128
+ `${host} answered with a redirect (HTTP ${status}). The CLI does not follow a redirect with your sign-in.
128
129
  ${next}`
129
130
  );
130
131
  this.host = host;
131
- this.status = status2;
132
+ this.status = status;
132
133
  this.name = "RedirectRefusedError";
133
134
  }
134
135
  };
@@ -613,29 +614,414 @@ function exitAfterOutput(exitCode) {
613
614
  function exitWithFatalError(error, argv) {
614
615
  return exitAfterOutput(reportFatalError(error, argv));
615
616
  }
616
- function status(...parts) {
617
- if (isJsonOutput()) console.error(...parts);
618
- else console.log(...parts);
617
+ var COLORS = {
618
+ success: [139, 203, 111],
619
+ link: [88, 174, 176],
620
+ warning: [255, 179, 92],
621
+ error: [255, 95, 95]
622
+ };
623
+ var BRAND_GRADIENT = [[255, 179, 92], [255, 92, 135], [139, 108, 255]];
624
+ var BRAND_CYCLE_MS = 1200;
625
+ var GLYPHS = {
626
+ done: "\u2713",
627
+ current: "\u25CF",
628
+ warning: "\u25B2",
629
+ error: "\u2717",
630
+ cursor: "\u203A"
631
+ };
632
+ var SPINNER_FRAMES = ["\u28F7", "\u28EF", "\u28DF", "\u287F", "\u28BF", "\u28FB", "\u28FD", "\u28FE"];
633
+ var SPINNER_FRAME_MS = 70;
634
+ var MARGIN = " ";
635
+ var CONTINUATION = " ";
636
+ var CLEAR_LINE = "\r\x1B[2K";
637
+ var DEFAULT_COLUMNS = 80;
638
+ var ANSI_PATTERN = new RegExp(
639
+ `${String.fromCharCode(27)}(?:\\[[0-9;?]*[A-Za-z]|\\]8;;[^${String.fromCharCode(27)}${String.fromCharCode(7)}]*(?:${String.fromCharCode(27)}\\\\|${String.fromCharCode(7)}))`,
640
+ "g"
641
+ );
642
+ var URL_PATTERN = /https?:\/\/[^\s"'<>()[\]]+/g;
643
+ function cliVersion() {
644
+ return "0.45.11";
645
+ }
646
+ function painter(target) {
647
+ return target === "stderr" ? chalkStderr : chalk;
648
+ }
649
+ function rgb(paint, color) {
650
+ return paint.rgb(color[0], color[1], color[2]);
651
+ }
652
+ function isTerminal(target) {
653
+ return Boolean(process[target].isTTY);
654
+ }
655
+ function statusTarget() {
656
+ return isJsonOutput() ? "stderr" : "stdout";
657
+ }
658
+ function stripAnsi(text2) {
659
+ return text2.replace(ANSI_PATTERN, "");
660
+ }
661
+ var GRAPHEMES = new Intl.Segmenter(void 0, { granularity: "grapheme" });
662
+ var EMOJI_PRESENTATION = /\p{Emoji_Presentation}/u;
663
+ var PICTOGRAPH = /\p{Extended_Pictographic}/u;
664
+ var EMOJI_VARIATION = "\uFE0F";
665
+ var KEYCAP = "\u20E3";
666
+ var ZERO_WIDTH = /^[\p{Mn}\p{Me}\p{Cf}\p{Cc}]+$/u;
667
+ var WIDE_RANGES = [
668
+ [4352, 4447],
669
+ [8986, 8987],
670
+ [9001, 9002],
671
+ [11904, 12350],
672
+ [12353, 12871],
673
+ [12880, 19903],
674
+ [19968, 42182],
675
+ [43360, 43388],
676
+ [44032, 55203],
677
+ [63744, 64255],
678
+ [65040, 65049],
679
+ [65072, 65131],
680
+ [65281, 65376],
681
+ [65504, 65510],
682
+ [94176, 101631],
683
+ [110576, 111359],
684
+ [127488, 127569],
685
+ [127744, 128591],
686
+ [128640, 128767],
687
+ [129280, 129791],
688
+ [131072, 262141]
689
+ ];
690
+ function graphemes(text2) {
691
+ return Array.from(GRAPHEMES.segment(text2), (part) => part.segment);
692
+ }
693
+ function graphemeWidth(grapheme) {
694
+ if (ZERO_WIDTH.test(grapheme)) return 0;
695
+ if (EMOJI_PRESENTATION.test(grapheme) || grapheme.includes(KEYCAP) || grapheme.includes(EMOJI_VARIATION) && PICTOGRAPH.test(grapheme)) return 2;
696
+ const codePoint = grapheme.codePointAt(0) ?? 0;
697
+ return WIDE_RANGES.some(([start, end]) => codePoint >= start && codePoint <= end) ? 2 : 1;
698
+ }
699
+ function visibleLength(text2) {
700
+ let cells = 0;
701
+ for (const grapheme of graphemes(stripAnsi(text2))) cells += graphemeWidth(grapheme);
702
+ return cells;
703
+ }
704
+ function takeCells(parts, start, cells) {
705
+ let used = 0;
706
+ let index = start;
707
+ while (index < parts.length) {
708
+ const width = graphemeWidth(parts[index]);
709
+ if (used + width > cells) break;
710
+ used += width;
711
+ index += 1;
712
+ }
713
+ return { text: parts.slice(start, index).join(""), next: index };
714
+ }
715
+ function truncateToCells(text2, cells) {
716
+ if (visibleLength(text2) <= cells) return text2;
717
+ return `${takeCells(graphemes(text2), 0, Math.max(0, cells - 1)).text.trimEnd()}\u2026`;
718
+ }
719
+ function formatDuration(ms) {
720
+ const totalSeconds = Math.max(0, Math.floor(ms / 1e3));
721
+ const minutes = Math.floor(totalSeconds / 60);
722
+ const seconds = totalSeconds % 60;
723
+ return minutes > 0 ? `${minutes}m ${String(seconds).padStart(2, "0")}s` : `${seconds}s`;
724
+ }
725
+ function brandColor(tick) {
726
+ const position = tick % BRAND_CYCLE_MS / BRAND_CYCLE_MS;
727
+ const triangle = position < 0.5 ? position * 2 : 2 - position * 2;
728
+ const scaled = triangle * (BRAND_GRADIENT.length - 1);
729
+ const index = Math.min(Math.floor(scaled), BRAND_GRADIENT.length - 2);
730
+ const amount = scaled - index;
731
+ const start = BRAND_GRADIENT[index];
732
+ const end = BRAND_GRADIENT[index + 1];
733
+ const mix = (left, right) => Math.round(left + (right - left) * amount);
734
+ return [mix(start[0], end[0]), mix(start[1], end[1]), mix(start[2], end[2])];
735
+ }
736
+ function link(target, url) {
737
+ if (!isTerminal(target)) return url;
738
+ const colored = rgb(painter(target), COLORS.link)(url);
739
+ return `\x1B]8;;${url}\x1B\\${colored}\x1B]8;;\x1B\\`;
740
+ }
741
+ function linkify(target, text2) {
742
+ if (text2.includes("\x1B]8;;")) return text2;
743
+ return text2.replace(URL_PATTERN, (match) => {
744
+ const url = match.replace(/[.,;:!?]+$/, "");
745
+ return `${link(target, url)}${match.slice(url.length)}`;
746
+ });
747
+ }
748
+ function wrap(text2, prefix, width) {
749
+ if (!width || /^\s/.test(text2) || visibleLength(prefix + text2) <= width) return [prefix + text2];
750
+ const hanging = " ".repeat(visibleLength(prefix));
751
+ const lines = [];
752
+ let current2 = prefix;
753
+ let hasWord = false;
754
+ for (const word of text2.split(" ")) {
755
+ const candidate = hasWord ? `${current2} ${word}` : `${current2}${word}`;
756
+ if (hasWord && visibleLength(candidate) > width) {
757
+ lines.push(current2);
758
+ current2 = `${hanging}${word}`;
759
+ } else {
760
+ current2 = candidate;
761
+ }
762
+ hasWord = true;
763
+ }
764
+ lines.push(current2);
765
+ return lines;
766
+ }
767
+ function glyphFor(target, kind) {
768
+ const paint = painter(target);
769
+ if (kind === "success") return rgb(paint, COLORS.success)(GLYPHS.done);
770
+ if (kind === "warning") return rgb(paint, COLORS.warning)(GLYPHS.warning);
771
+ if (kind === "error") return rgb(paint, COLORS.error)(GLYPHS.error);
772
+ if (kind === "current") return GLYPHS.current;
773
+ return void 0;
774
+ }
775
+ function formatMessage(target, kind, message) {
776
+ const glyph = glyphFor(target, kind);
777
+ if (!isTerminal(target)) {
778
+ return glyph ? `${glyph} ${message}` : message;
779
+ }
780
+ const paint = painter(target);
781
+ const columns = process[target].columns;
782
+ const width = columns ? columns - 1 : void 0;
783
+ const indented = kind === "detail" || kind === "dim";
784
+ const firstPrefix = glyph ? `${MARGIN}${glyph} ` : indented ? CONTINUATION : MARGIN;
785
+ const laterPrefix = glyph || indented ? CONTINUATION : MARGIN;
786
+ const style = (text2) => {
787
+ if (kind === "current") return paint.bold(text2);
788
+ if (kind === "dim") return paint.dim(text2);
789
+ return text2;
790
+ };
791
+ return message.split("\n").flatMap((line, index) => {
792
+ if (line === "") return [""];
793
+ const styled = index === 0 ? style(line) : kind === "dim" ? paint.dim(line) : line;
794
+ return wrap(styled, index === 0 ? firstPrefix : laterPrefix, width);
795
+ }).map((line) => linkify(target, line)).join("\n");
796
+ }
797
+ var liveLine;
798
+ var heldLines;
799
+ var lineObserver;
800
+ function holdLines(onLine) {
801
+ liveLine?.stop();
802
+ heldLines = [];
803
+ lineObserver = onLine;
804
+ return () => {
805
+ const held = heldLines ?? [];
806
+ heldLines = void 0;
807
+ lineObserver = void 0;
808
+ for (const line of held) writeLine(line.target, line.text);
809
+ };
810
+ }
811
+ function writeLine(target, text2) {
812
+ if (heldLines) {
813
+ heldLines.push({ target, text: text2 });
814
+ return;
815
+ }
816
+ liveLine?.clear();
817
+ if (target === "stderr") console.error(text2);
818
+ else console.log(text2);
819
+ liveLine?.render();
820
+ }
821
+ function print(target, kind, message) {
822
+ lineObserver?.(kind, message);
823
+ writeLine(target, formatMessage(target, kind, message));
824
+ }
825
+ function stopLiveLine() {
826
+ liveLine?.stop();
827
+ }
828
+ function startSpinnerLine(options) {
829
+ if (heldLines) return { clear() {
830
+ }, render() {
831
+ }, stop() {
832
+ } };
833
+ const stream = options.stream ?? process.stdout;
834
+ const startedAt = Date.now();
835
+ let stopped = false;
836
+ const render4 = () => {
837
+ if (stopped) return;
838
+ const width = Math.max(1, (stream.columns || DEFAULT_COLUMNS) - 1);
839
+ const room = Math.max(0, width - MARGIN.length - 2);
840
+ const label = truncateToCells(options.label, room);
841
+ const free = room - visibleLength(label);
842
+ const candidates = options.suffixes?.() ?? [];
843
+ let suffix = candidates.find((candidate) => visibleLength(candidate) <= free) ?? "";
844
+ if (!suffix && options.truncate && candidates[0] && free > 6) {
845
+ suffix = truncateToCells(candidates[0], free);
846
+ }
847
+ const tick = Date.now() - startedAt;
848
+ const frame = SPINNER_FRAMES[Math.floor(tick / SPINNER_FRAME_MS) % SPINNER_FRAMES.length];
849
+ const glyph = rgb(chalk, brandColor(tick)).bold(frame);
850
+ stream.write(`${CLEAR_LINE}${MARGIN}${glyph} ${label}${suffix ? chalk.dim(suffix) : ""}`);
851
+ };
852
+ const line = {
853
+ clear() {
854
+ if (!stopped) stream.write(CLEAR_LINE);
855
+ },
856
+ render: render4,
857
+ stop() {
858
+ if (stopped) return;
859
+ stream.write(CLEAR_LINE);
860
+ stopped = true;
861
+ clearInterval(timer);
862
+ if (liveLine === line) liveLine = void 0;
863
+ }
864
+ };
865
+ liveLine?.stop();
866
+ liveLine = line;
867
+ render4();
868
+ const timer = setInterval(render4, SPINNER_FRAME_MS);
869
+ return line;
870
+ }
871
+ function startActivity(options) {
872
+ const target = statusTarget();
873
+ const startedAt = Date.now();
874
+ const elapsed = () => {
875
+ const ms = Date.now() - startedAt;
876
+ return ms >= 1e3 ? formatDuration(ms) : "";
877
+ };
878
+ const doneLine = (message, detail) => {
879
+ const tail = detail ?? elapsed();
880
+ writeLine("stdout", `${formatMessage("stdout", "success", message)}${tail ? chalk.dim(` ${tail}`) : ""}`);
881
+ };
882
+ if (heldLines) return { live: true, output: () => {
883
+ }, done: doneLine };
884
+ if (target !== "stdout" || !isTerminal("stdout")) {
885
+ print(target, "plain", options.plain ?? `${options.label}...`);
886
+ return {
887
+ live: false,
888
+ output: () => {
889
+ },
890
+ done: (message, detail) => print(target, "success", detail ? `${message} (${detail})` : message)
891
+ };
892
+ }
893
+ let lastLine = "";
894
+ const spinner = startSpinnerLine({
895
+ label: options.label,
896
+ suffixes: () => lastLine ? [` ${lastLine}`] : [],
897
+ truncate: true
898
+ });
899
+ return {
900
+ live: true,
901
+ output(chunk) {
902
+ const lines = stripAnsi(chunk).split(/[\r\n]+/).map((line) => line.trim()).filter(Boolean);
903
+ const latest = lines.at(-1);
904
+ if (latest) lastLine = latest;
905
+ },
906
+ done(message, detail) {
907
+ spinner.stop();
908
+ doneLine(message, detail);
909
+ }
910
+ };
911
+ }
912
+ function printCapturedOutput(output) {
913
+ const lines = output.split("\n").map((line) => line.trimEnd()).filter(Boolean).slice(-12);
914
+ if (lines.length === 0) return;
915
+ if (!isTerminal("stderr")) {
916
+ for (const line of lines) writeLine("stderr", line);
917
+ writeLine("stderr", "");
918
+ return;
919
+ }
920
+ const paint = painter("stderr");
921
+ const room = Math.max(20, (process.stderr.columns || DEFAULT_COLUMNS) - 1 - CONTINUATION.length);
922
+ writeLine("stderr", "");
923
+ for (const line of lines) {
924
+ const parts = graphemes(stripAnsi(line));
925
+ for (let start = 0; start < parts.length; ) {
926
+ const piece = takeCells(parts, start, room);
927
+ const next = piece.next > start ? piece.next : start + 1;
928
+ writeLine("stderr", `${CONTINUATION}${paint.dim(parts.slice(start, next).join(""))}`);
929
+ start = next;
930
+ }
931
+ }
932
+ writeLine("stderr", "");
933
+ }
934
+ var ESC = String.fromCharCode(27);
935
+ var BEL = String.fromCharCode(7);
936
+ var code = (value) => String.fromCharCode(value);
937
+ var OSC_PATTERN = new RegExp(`${ESC}\\][^${ESC}${BEL}]*(?:${ESC}\\\\|${BEL})?`, "g");
938
+ var CSI_PATTERN = new RegExp(`${ESC}\\[[0-9;:?<=>]*[ -/]*[@-~]`, "g");
939
+ var SGR_PATTERN = new RegExp(`^${ESC}\\[[0-9;:]*m$`);
940
+ var UNFINISHED_CSI_PATTERN = new RegExp(`${ESC}(?:\\[[0-9;:?<=>]*[ -/]*)?$`);
941
+ var OTHER_ESCAPE_PATTERN = new RegExp(`${ESC}(?!\\[)[ -/]*[0-~]?`, "g");
942
+ var ESCAPE_THAT_IS_NO_COLOR_PATTERN = new RegExp(`${ESC}(?!\\[[0-9;:]*m)`, "g");
943
+ var CONTROL_PATTERN = new RegExp(`[${code(0)}-${code(6)}${code(8)}-${code(26)}${code(28)}-${code(31)}${code(127)}]`, "g");
944
+ function sanitizeOutputLine(line, keepColor = false) {
945
+ const visible = line.replace(/\r+$/, "");
946
+ const current2 = visible.slice(visible.lastIndexOf("\r") + 1);
947
+ const text2 = current2.replace(/\t/g, " ").replace(CONTROL_PATTERN, "").replace(OSC_PATTERN, "").replaceAll(BEL, "").replace(CSI_PATTERN, (sequence) => keepColor && SGR_PATTERN.test(sequence) ? sequence : "").replace(UNFINISHED_CSI_PATTERN, "").replace(OTHER_ESCAPE_PATTERN, "");
948
+ return text2.replace(keepColor ? ESCAPE_THAT_IS_NO_COLOR_PATTERN : new RegExp(ESC, "g"), "").trimEnd();
949
+ }
950
+ function printKeyValues(rows, options = {}) {
951
+ const target = statusTarget();
952
+ const width = Math.max(...rows.map(([key]) => key.length));
953
+ const paint = painter(target);
954
+ const margin = options.indent === false ? MARGIN : CONTINUATION;
955
+ for (const [key, value] of rows) {
956
+ if (!isTerminal(target)) {
957
+ writeLine(target, options.plain === "aligned" ? `${`${key}:`.padEnd(width + 2)}${value}` : `${key}: ${value}`);
958
+ continue;
959
+ }
960
+ const columns = process[target].columns;
961
+ const prefix = `${margin}${paint.dim(key.padEnd(width))} `;
962
+ const lines = wrap(value, prefix, columns ? columns - 1 : void 0);
963
+ writeLine(target, lines.map((line) => linkify(target, line)).join("\n"));
964
+ }
965
+ }
966
+ function printHeading(message) {
967
+ const target = statusTarget();
968
+ writeLine(target, isTerminal(target) ? `${MARGIN}${painter(target).bold(message)}` : message);
969
+ }
970
+ var deferredNotice;
971
+ var flushOnExitRegistered = false;
972
+ function flushDeferredNotice(trailingBlankLine) {
973
+ if (deferredNotice === void 0) return;
974
+ const notice = deferredNotice;
975
+ deferredNotice = void 0;
976
+ print("stderr", "warning", notice);
977
+ if (trailingBlankLine) writeLine("stderr", "");
978
+ }
979
+ function deferNotice(message) {
980
+ deferredNotice = message;
981
+ if (flushOnExitRegistered) return;
982
+ flushOnExitRegistered = true;
983
+ process.once("exit", () => flushDeferredNotice(false));
984
+ }
985
+ function takeDeferredNotice() {
986
+ const notice = deferredNotice;
987
+ deferredNotice = void 0;
988
+ return notice;
989
+ }
990
+ function printHeader() {
991
+ if (!isTerminal("stdout") || isJsonOutput()) {
992
+ flushDeferredNotice(false);
993
+ return;
994
+ }
995
+ writeLine("stdout", "");
996
+ writeLine("stdout", `${MARGIN}${chalk.bold("Standard Agents")} ${chalk.dim(cliVersion())}`);
997
+ writeLine("stdout", "");
998
+ flushDeferredNotice(true);
619
999
  }
1000
+
1001
+ // src/utils/logger.ts
620
1002
  var logger = {
621
1003
  success: (message) => {
622
- status(chalk.green("\u2713"), message);
1004
+ print(statusTarget(), "success", message);
623
1005
  },
624
1006
  error: (message) => {
625
- console.error(chalk.red("\u2717"), message);
1007
+ print("stderr", "error", message);
626
1008
  },
627
1009
  warning: (message) => {
628
- console.error(chalk.yellow("\u26A0"), message);
1010
+ print("stderr", "warning", message);
629
1011
  },
630
1012
  /** A continuation line of an error or warning (a list item, the manual step): stderr, like its heading. */
631
1013
  detail: (message) => {
632
- console.error(message);
1014
+ print("stderr", "detail", message);
633
1015
  },
634
1016
  info: (message) => {
635
- status(chalk.blue("\u2139"), message);
1017
+ print(statusTarget(), "plain", message);
1018
+ },
1019
+ /** Secondary text under a step, such as progress the platform reports. */
1020
+ note: (message) => {
1021
+ print(statusTarget(), "dim", message);
636
1022
  },
637
1023
  log: (message) => {
638
- status(message);
1024
+ print(statusTarget(), "plain", message);
639
1025
  }
640
1026
  };
641
1027
  var SCOPE_PREFIX = `${STANDARD_AGENTS_NPM_SCOPE}/`;
@@ -927,25 +1313,25 @@ function withTarget(before, keyPath, value) {
927
1313
  return root;
928
1314
  }
929
1315
  function sharesNodes(text2) {
930
- let shared = false;
1316
+ let shared2 = false;
931
1317
  visit(parseDocument(text2), {
932
1318
  Alias: () => {
933
- shared = true;
1319
+ shared2 = true;
934
1320
  },
935
1321
  Node: (_key, node) => {
936
- if (isNode(node) && node.anchor) shared = true;
1322
+ if (isNode(node) && node.anchor) shared2 = true;
937
1323
  },
938
1324
  Pair: (_key, pair) => {
939
- if (isScalar(pair.key) && pair.key.value === "<<") shared = true;
1325
+ if (isScalar(pair.key) && pair.key.value === "<<") shared2 = true;
940
1326
  }
941
1327
  });
942
- return shared;
1328
+ return shared2;
943
1329
  }
944
1330
  function setYamlString(text2, keyPath, value, isAcceptable) {
945
1331
  const document = parseDocument(text2);
946
1332
  if (document.errors.length > 0) return null;
947
- const current = keyPath.reduce((value2, key) => isRecord(value2) ? value2[key] : void 0, document.toJS());
948
- if (typeof current === "string" && isAcceptable(current)) return { text: text2, changed: false };
1333
+ const current2 = keyPath.reduce((value2, key) => isRecord(value2) ? value2[key] : void 0, document.toJS());
1334
+ if (typeof current2 === "string" && isAcceptable(current2)) return { text: text2, changed: false };
949
1335
  if (sharesNodes(text2)) return null;
950
1336
  const expected = withTarget(document.toJS(), keyPath, value);
951
1337
  if (expected === null) return null;
@@ -969,7 +1355,7 @@ function pinScopeRegistryInPnpmWorkspace(text2) {
969
1355
  text2,
970
1356
  PNPM_WORKSPACE_REGISTRY_PATH,
971
1357
  STANDARD_AGENTS_NPM_REGISTRY,
972
- (current) => withoutTrailingSlash(current) === PUBLIC_REGISTRY
1358
+ (current2) => withoutTrailingSlash(current2) === PUBLIC_REGISTRY
973
1359
  );
974
1360
  }
975
1361
  var YARNRC_REGISTRY_PATH = ["npmScopes", STANDARD_AGENTS_NPM_SCOPE.slice(1), "npmRegistryServer"];
@@ -978,7 +1364,7 @@ function pinScopeRegistryInYarnrc(text2) {
978
1364
  text2,
979
1365
  YARNRC_REGISTRY_PATH,
980
1366
  PUBLIC_REGISTRY,
981
- (current) => [PUBLIC_REGISTRY, "https://registry.yarnpkg.com"].includes(withoutTrailingSlash(current))
1367
+ (current2) => [PUBLIC_REGISTRY, "https://registry.yarnpkg.com"].includes(withoutTrailingSlash(current2))
982
1368
  );
983
1369
  }
984
1370
  var AUTH_KEYS = ["npmAuthToken", "npmAuthIdent"];
@@ -1076,8 +1462,8 @@ function planYaml(filePath, pin, keyPath, required, plan) {
1076
1462
  function planYarnrc(projectPath, required, plan) {
1077
1463
  const filePath = path19.join(projectPath, ".yarnrc.yml");
1078
1464
  const stat = fs14.lstatSync(filePath, { throwIfNoEntry: false });
1079
- const current = stat && !stat.isSymbolicLink() ? fs14.readFileSync(filePath, "utf-8") : "";
1080
- const credentials = pinScopeRegistryInYarnrc(current)?.changed ? yarnCredentialsBoundToScope(projectPath) : [];
1465
+ const current2 = stat && !stat.isSymbolicLink() ? fs14.readFileSync(filePath, "utf-8") : "";
1466
+ const credentials = pinScopeRegistryInYarnrc(current2)?.changed ? yarnCredentialsBoundToScope(projectPath) : [];
1081
1467
  if (credentials.length > 0) {
1082
1468
  refuse(
1083
1469
  plan,
@@ -1170,8 +1556,8 @@ function sleep(ms) {
1170
1556
  }
1171
1557
  function networkErrorCode(error) {
1172
1558
  const cause = error instanceof Error ? error.cause : void 0;
1173
- const code = cause !== null && typeof cause === "object" && "code" in cause ? cause.code : void 0;
1174
- return typeof code === "string" ? ` (${code})` : "";
1559
+ const code2 = cause !== null && typeof cause === "object" && "code" in cause ? cause.code : void 0;
1560
+ return typeof code2 === "string" ? ` (${code2})` : "";
1175
1561
  }
1176
1562
  async function startCliAuthSession(params) {
1177
1563
  let response;
@@ -1205,8 +1591,8 @@ async function cancelCliAuthSession(endpoint, sessionId) {
1205
1591
  }).then(() => void 0, () => void 0);
1206
1592
  await Promise.race([request, sleep(CANCEL_LIMIT_MS)]);
1207
1593
  }
1208
- function isRetryableStatus(status2) {
1209
- return status2 === 502 || status2 === 503 || status2 === 504;
1594
+ function isRetryableStatus(status) {
1595
+ return status === 502 || status === 503 || status === 504;
1210
1596
  }
1211
1597
  async function readCliAuthStatus(statusUrl, reader, options = {}) {
1212
1598
  const signal = options.signal;
@@ -1226,18 +1612,18 @@ async function readCliAuthStatus(statusUrl, reader, options = {}) {
1226
1612
  if (isRetryableStatus(response.status)) return null;
1227
1613
  throw new Error(`Platform auth status failed (${response.status})`);
1228
1614
  }
1229
- const status2 = await response.json();
1615
+ const status = await response.json();
1230
1616
  throwIfAborted();
1231
- if (status2.progress?.message) {
1232
- options.onProgress?.(status2.progress);
1617
+ if (status.progress?.message) {
1618
+ options.onProgress?.(status.progress);
1233
1619
  }
1234
- if (status2.status === "completed") {
1235
- const completion = reader.read(status2);
1620
+ if (status.status === "completed") {
1621
+ const completion = reader.read(status);
1236
1622
  if (completion === void 0) throw new Error(reader.unexpectedMessage);
1237
1623
  return completion;
1238
1624
  }
1239
- if (status2.status === "expired") throw new Error(reader.expiredMessage);
1240
- if (status2.status === "cancelled") throw new Error(reader.cancelledMessage);
1625
+ if (status.status === "expired") throw new Error(reader.expiredMessage);
1626
+ if (status.status === "cancelled") throw new Error(reader.cancelledMessage);
1241
1627
  return null;
1242
1628
  }
1243
1629
  function waitForCliAuthCompletionWs(wsUrl, expiresAt, reader, options = {}) {
@@ -1476,7 +1862,7 @@ async function revokeAccountApiKey(endpoint, sessionCookie, key, fetchImpl = fet
1476
1862
 
1477
1863
  // src/utils/interrupt.ts
1478
1864
  var SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 };
1479
- function createInterruptScope(source = process, exit = (code) => process.exit(code)) {
1865
+ function createInterruptScope(source = process, exit = (code2) => process.exit(code2)) {
1480
1866
  const cleanups = [];
1481
1867
  let listening = false;
1482
1868
  let interrupted = false;
@@ -1523,21 +1909,11 @@ function parkUntilExit() {
1523
1909
  }
1524
1910
 
1525
1911
  // src/utils/wait-indicator.ts
1526
- var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1527
- var CLEAR_LINE = "\r\x1B[2K";
1528
1912
  var CANCEL_HINT = "Press Ctrl-C to cancel.";
1529
1913
  var SHORT_CANCEL_HINT = "Ctrl-C to cancel";
1530
- var FRAME_MS = 100;
1531
- var DEFAULT_COLUMNS = 80;
1532
- function formatDuration(ms) {
1533
- const totalSeconds = Math.max(0, Math.floor(ms / 1e3));
1534
- const minutes = Math.floor(totalSeconds / 60);
1535
- const seconds = totalSeconds % 60;
1536
- return minutes > 0 ? `${minutes}m ${String(seconds).padStart(2, "0")}s` : `${seconds}s`;
1537
- }
1538
1914
  function startWaitIndicator(options) {
1539
1915
  const stream = options.stream ?? process.stdout;
1540
- const log = options.log ?? ((message) => console.log(message));
1916
+ const log = options.log ?? logger.note;
1541
1917
  const startedAt = Date.now();
1542
1918
  if (!stream.isTTY) {
1543
1919
  stream.write(
@@ -1547,42 +1923,91 @@ function startWaitIndicator(options) {
1547
1923
  return { note: log, stop: () => {
1548
1924
  } };
1549
1925
  }
1550
- const useColor = !process.env.NO_COLOR;
1551
- const dim = (text2) => useColor ? `\x1B[2m${text2}\x1B[22m` : text2;
1552
- const accent = (text2) => useColor ? `\x1B[36m${text2}\x1B[39m` : text2;
1553
- let frame = 0;
1554
1926
  let stopped = false;
1555
- const render3 = () => {
1556
- const width = Math.max(1, (stream.columns || DEFAULT_COLUMNS) - 1);
1557
- const left = `${formatDuration(options.expiresAt - Date.now())} left`;
1558
- const tails = [` \xB7 ${left} \xB7 ${SHORT_CANCEL_HINT}`, ` \xB7 ${left}`, ""];
1559
- const room = width - 2;
1560
- const label = options.label.length > room ? `${options.label.slice(0, Math.max(0, room - 1)).trimEnd()}\u2026` : options.label;
1561
- const tail = tails.find((candidate) => label.length + candidate.length <= room) ?? "";
1562
- stream.write(`${CLEAR_LINE}${accent(SPINNER_FRAMES[frame])} ${label}${dim(tail)}`);
1563
- frame = (frame + 1) % SPINNER_FRAMES.length;
1564
- };
1565
- render3();
1566
- const timer = setInterval(render3, FRAME_MS);
1927
+ let progress = "";
1928
+ const spinner = startSpinnerLine({
1929
+ label: options.label,
1930
+ suffixes: () => {
1931
+ const left = `${formatDuration(options.expiresAt - Date.now())} left`;
1932
+ const timed = [` ${left} \xB7 ${SHORT_CANCEL_HINT}`, ` ${left}`];
1933
+ return progress ? [` ${progress} \xB7 ${left} \xB7 ${SHORT_CANCEL_HINT}`, ` ${progress} \xB7 ${left}`, ` ${progress}`, ...timed] : timed;
1934
+ },
1935
+ stream
1936
+ });
1567
1937
  return {
1568
1938
  note(message) {
1569
- if (stopped) {
1570
- log(message);
1571
- return;
1572
- }
1573
- stream.write(CLEAR_LINE);
1574
- log(message);
1575
- render3();
1939
+ if (stopped) return;
1940
+ progress = message.replace(/\s+/g, " ").replace(/(\.{3}|…)$/, "").trim();
1941
+ spinner.render();
1576
1942
  },
1577
1943
  stop() {
1578
1944
  if (stopped) return;
1579
1945
  stopped = true;
1580
- clearInterval(timer);
1581
- stream.write(CLEAR_LINE);
1946
+ spinner.stop();
1582
1947
  }
1583
1948
  };
1584
1949
  }
1585
1950
 
1951
+ // src/utils/reporter.ts
1952
+ function printSummary(summary) {
1953
+ logger.log("");
1954
+ printHeading(summary.title);
1955
+ logger.log("");
1956
+ printKeyValues(summary.rows, { plain: "aligned" });
1957
+ if (summary.footer) {
1958
+ logger.log("");
1959
+ logger.log(summary.footer);
1960
+ }
1961
+ }
1962
+ function printFailure(failure, capturedOutput) {
1963
+ stopLiveLine();
1964
+ if (capturedOutput) printCapturedOutput(capturedOutput);
1965
+ const [headline, ...detail] = failure.cause.split("\n");
1966
+ logger.error(headline);
1967
+ for (const line of [...detail, ...failure.next]) {
1968
+ logger.detail(line);
1969
+ }
1970
+ }
1971
+ var lineReporter = {
1972
+ fullScreen: false,
1973
+ header: () => printHeader(),
1974
+ begin() {
1975
+ },
1976
+ stepStarted: (_id, options) => startActivity(options),
1977
+ stepDone: (_id, message) => logger.success(message),
1978
+ // `browser-sign-in.ts` imports this module, so its functions are read when they are called.
1979
+ signInStarted: (_id, about) => printSignInStep(about),
1980
+ signInUrl: (url, skipBrowserOpen) => presentSignInUrl(url, skipBrowserOpen),
1981
+ waitStarted: (options) => startWaitIndicator(options),
1982
+ devServerStarting(_id, url) {
1983
+ if (isTerminal(statusTarget())) {
1984
+ print(statusTarget(), "current", "Starting the dev server");
1985
+ } else {
1986
+ logger.info(`Starting the dev server at ${url}...`);
1987
+ logger.info("The dev server stays in this terminal. Press Ctrl-C to stop it.");
1988
+ }
1989
+ },
1990
+ devServerOutput() {
1991
+ },
1992
+ devServerReady() {
1993
+ logger.log("");
1994
+ logger.success("Started the dev server");
1995
+ },
1996
+ summary: printSummary,
1997
+ async failure(failure, capturedOutput) {
1998
+ printFailure(failure, capturedOutput);
1999
+ },
2000
+ async confirm() {
2001
+ }
2002
+ };
2003
+ var current = lineReporter;
2004
+ function flowReporter() {
2005
+ return current;
2006
+ }
2007
+ function setFlowReporter(reporter) {
2008
+ current = reporter;
2009
+ }
2010
+
1586
2011
  // src/utils/browser-sign-in.ts
1587
2012
  function shouldSkipBrowserOpen(value) {
1588
2013
  return /^(none|false|0|off)$/i.test(value?.trim() ?? "");
@@ -1620,7 +2045,7 @@ function openUrl(url) {
1620
2045
  resolve(opened);
1621
2046
  };
1622
2047
  child.on("error", () => finish(false));
1623
- child.on("exit", (code) => finish(code === 0));
2048
+ child.on("exit", (code2) => finish(code2 === 0));
1624
2049
  child.unref();
1625
2050
  });
1626
2051
  }
@@ -1632,17 +2057,41 @@ function browserSignInPolicy(options) {
1632
2057
  const allowed = isInteractiveTerminal() || skipBrowserOpen || process.env.STANDARD_AGENTS_NON_INTERACTIVE === "1";
1633
2058
  return { skipBrowserOpen, allowed };
1634
2059
  }
2060
+ function printSignInStep(about = {}) {
2061
+ const target = statusTarget();
2062
+ if (!isTerminal(target)) {
2063
+ for (const line of about.plain ?? []) print(target, "plain", line);
2064
+ return;
2065
+ }
2066
+ print(target, "current", "Sign in");
2067
+ if (about.terminal) print(target, "detail", about.terminal);
2068
+ }
2069
+ var SIGN_IN_LAUNCH_TEXT = {
2070
+ skipped: "Open this URL in a browser to continue:",
2071
+ opened: "The sign-in page opens in your browser. If it does not open, use this URL:",
2072
+ failed: "Could not open a browser on this machine. Open this URL in a browser to continue:"
2073
+ };
1635
2074
  async function presentSignInUrl(authUrl, skipBrowserOpen) {
1636
- logger.log("");
1637
- logger.log(`Sign-in URL: ${authUrl}`);
1638
- logger.log("");
1639
- if (skipBrowserOpen) {
1640
- logger.info("Open the sign-in URL in a browser to continue.");
1641
- } else if (await openUrl(authUrl)) {
1642
- logger.info("Opening your browser. If it does not open, use the sign-in URL above.");
2075
+ const target = statusTarget();
2076
+ const terminal = isTerminal(target);
2077
+ if (!terminal) {
2078
+ logger.log("");
2079
+ logger.log(`Sign-in URL: ${authUrl}`);
2080
+ logger.log("");
2081
+ }
2082
+ const launch = skipBrowserOpen ? "skipped" : await openUrl(authUrl) ? "opened" : "failed";
2083
+ if (launch === "failed") {
2084
+ logger.warning(terminal ? SIGN_IN_LAUNCH_TEXT.failed : "Could not open a browser on this machine. Open the sign-in URL above in a browser to continue.");
2085
+ } else if (terminal) {
2086
+ logger.note(SIGN_IN_LAUNCH_TEXT[launch]);
1643
2087
  } else {
1644
- logger.warning("Could not open a browser on this machine. Open the sign-in URL above in a browser to continue.");
2088
+ logger.note(launch === "skipped" ? "Open the sign-in URL in a browser to continue." : "The sign-in URL opens in your browser. Use the URL above if it does not open.");
2089
+ }
2090
+ if (terminal) {
2091
+ writeLine(target, ` ${link(target, authUrl)}`);
2092
+ writeLine(target, "");
1645
2093
  }
2094
+ return launch;
1646
2095
  }
1647
2096
  async function signInThroughBrowser(params) {
1648
2097
  const { endpoint, command } = params;
@@ -1655,6 +2104,9 @@ To sign in from another device or a script, print the sign-in URL and wait for i
1655
2104
  With a setup code from your project's Overview page: ${command} --bootstrap <code>`
1656
2105
  );
1657
2106
  }
2107
+ const reporter = flowReporter();
2108
+ reporter.begin("Sign in", []);
2109
+ reporter.signInStarted("sign-in");
1658
2110
  const session = await startCliAuthSession({
1659
2111
  endpoint,
1660
2112
  body: { purpose: "auth" },
@@ -1665,15 +2117,15 @@ With a setup code from your project's Overview page: ${command} --bootstrap <cod
1665
2117
  const stopCancelOnInterrupt = interrupts.onInterrupt(async () => {
1666
2118
  waitAbort.abort();
1667
2119
  indicator?.stop();
2120
+ stopLiveLine();
1668
2121
  await cancelCliAuthSession(endpoint, session.session_id);
1669
2122
  logger.info(`Sign-in cancelled. Start again when you are ready: ${command}`);
1670
2123
  });
1671
- await presentSignInUrl(session.auth_url, policy.skipBrowserOpen);
2124
+ await reporter.signInUrl(session.auth_url, policy.skipBrowserOpen);
1672
2125
  if (interrupts.isInterrupted()) return parkUntilExit();
1673
- const waitIndicator = indicator = startWaitIndicator({
2126
+ const waitIndicator = indicator = reporter.waitStarted({
1674
2127
  label: "Waiting for you to approve the sign-in in the browser",
1675
- expiresAt: session.expires_at,
1676
- log: logger.info
2128
+ expiresAt: session.expires_at
1677
2129
  });
1678
2130
  const reader = {
1679
2131
  read: (frame) => frame.bootstrap_code || void 0,
@@ -1703,14 +2155,16 @@ Use the setup command from that project's Overview page in the dashboard: ${comm
1703
2155
  }
1704
2156
  }
1705
2157
  }
2158
+
2159
+ // src/utils/stage-result.ts
1706
2160
  var stderrStageLog = {
1707
- success: (message) => console.error(chalk.green("\u2713"), message),
1708
- info: (message) => console.error(chalk.blue("\u2139"), message),
1709
- warning: (message) => console.error(chalk.yellow("\u26A0"), message),
1710
- log: (message) => console.error(message)
2161
+ success: (message) => print("stderr", "success", message),
2162
+ info: (message) => print("stderr", "plain", message),
2163
+ warning: (message) => print("stderr", "warning", message),
2164
+ log: (message) => print("stderr", "plain", message)
1711
2165
  };
1712
- function stageResult(stage, status2, message) {
1713
- return { stage, status: status2, message };
2166
+ function stageResult(stage, status, message) {
2167
+ return { stage, status, message };
1714
2168
  }
1715
2169
  async function runStage(stage, run2) {
1716
2170
  try {
@@ -1755,7 +2209,7 @@ function getScaffoldStandardAgentsVersion() {
1755
2209
  if (process.env.STANDARDAGENTS_WORKSPACE === "1") {
1756
2210
  return workspacePackageLink("@standardagents/builder");
1757
2211
  }
1758
- return "0.45.9";
2212
+ return "0.45.11";
1759
2213
  }
1760
2214
  var SPEC_PACKAGE = "@standardagents/spec";
1761
2215
  function specSpecifierFor(builderSpecifier) {
@@ -1804,8 +2258,8 @@ function updatePackageDependencies(cwd, versions = {}) {
1804
2258
  `, "utf-8");
1805
2259
  }
1806
2260
  if (pkg.dependencies?.[SPEC_PACKAGE] === void 0 && pkg.devDependencies?.[SPEC_PACKAGE] === void 0) {
1807
- const current = fs14.readFileSync(packageJsonPath, "utf-8");
1808
- const result = setPackageDependency(current, "dependencies", SPEC_PACKAGE, specSpecifierFor(desiredBuilderVersion));
2261
+ const current2 = fs14.readFileSync(packageJsonPath, "utf-8");
2262
+ const result = setPackageDependency(current2, "dependencies", SPEC_PACKAGE, specSpecifierFor(desiredBuilderVersion));
1809
2263
  fs14.writeFileSync(packageJsonPath, `${result.trimEnd()}
1810
2264
  `, "utf-8");
1811
2265
  }
@@ -1840,8 +2294,8 @@ async function modifyViteConfig(cwd, force, log) {
1840
2294
  const configName = path19.basename(configPath);
1841
2295
  try {
1842
2296
  const mod = await loadFile(configPath);
1843
- const code = fs14.readFileSync(configPath, "utf-8");
1844
- const hasAgentBuilder = code.includes("@standardagents/builder") || code.includes("builder()") || code.includes("agentbuilder()");
2297
+ const code2 = fs14.readFileSync(configPath, "utf-8");
2298
+ const hasAgentBuilder = code2.includes("@standardagents/builder") || code2.includes("builder()") || code2.includes("agentbuilder()");
1845
2299
  if (!hasAgentBuilder) {
1846
2300
  addVitePlugin(mod, {
1847
2301
  from: "@standardagents/builder",
@@ -2106,10 +2560,10 @@ function writeBuildGuardScript(projectPath) {
2106
2560
  }
2107
2561
 
2108
2562
  // src/utils/git-helper-command.ts
2109
- function cliVersion() {
2110
- return "0.45.9";
2563
+ function cliVersion2() {
2564
+ return "0.45.11";
2111
2565
  }
2112
- function defaultGitCredentialHelperCommand(version = cliVersion()) {
2566
+ function defaultGitCredentialHelperCommand(version = cliVersion2()) {
2113
2567
  return `!npx -y @standardagents/cli@${version} git-credential`;
2114
2568
  }
2115
2569
  var SETUP_CODE_OPTION_HELP = {
@@ -2136,23 +2590,23 @@ async function resolveSetupCode(options, readStdin2 = readStandardInput) {
2136
2590
  if (given.length > 1) {
2137
2591
  throw new Error(`Pass the setup code one way. This command received ${given.join(" and ")}.`);
2138
2592
  }
2139
- let code;
2593
+ let code2;
2140
2594
  let source = "";
2141
2595
  if (file) {
2142
2596
  source = `The file ${file}`;
2143
2597
  try {
2144
- code = fs14.readFileSync(file, "utf8");
2598
+ code2 = fs14.readFileSync(file, "utf8");
2145
2599
  } catch (error) {
2146
2600
  const reason = error instanceof Error && "code" in error ? String(error.code) : "it could not be read";
2147
2601
  throw new Error(`Cannot read the setup code file ${file} (${reason}).`);
2148
2602
  }
2149
2603
  } else if (options.bootstrapStdin) {
2150
2604
  source = "Standard input";
2151
- code = await readStdin2();
2605
+ code2 = await readStdin2();
2152
2606
  } else {
2153
2607
  return argument || void 0;
2154
2608
  }
2155
- const trimmed = code.trim();
2609
+ const trimmed = code2.trim();
2156
2610
  if (!trimmed) {
2157
2611
  throw new Error(`${source} holds no setup code.`);
2158
2612
  }
@@ -2252,10 +2706,12 @@ async function terminateProcessTree(child, options = {}) {
2252
2706
  await waitUntilGone(pids, options.killWaitMs ?? 2e3);
2253
2707
  }
2254
2708
  var CommandExitError = class extends Error {
2255
- constructor(exitCode, details = "") {
2256
- super(`Command failed with exit code ${exitCode}${details ? `
2257
- ${details}` : ""}`);
2709
+ /** The end of the output a quiet command wrote. Empty when its output went to the terminal. */
2710
+ constructor(exitCode, output = "") {
2711
+ super(`Command failed with exit code ${exitCode}${output ? `
2712
+ ${output}` : ""}`);
2258
2713
  this.exitCode = exitCode;
2714
+ this.output = output;
2259
2715
  this.name = "CommandExitError";
2260
2716
  }
2261
2717
  };
@@ -2291,24 +2747,25 @@ function runCommand(command, args, cwd, options = {}) {
2291
2747
  const stopOnInterrupt = interrupts.onInterrupt(() => terminateProcessTree(child));
2292
2748
  let outputTail = "";
2293
2749
  if (quiet) {
2294
- child.stdout?.on("data", (chunk) => {
2295
- outputTail = appendOutputTail(outputTail, chunk.toString());
2296
- });
2297
- child.stderr?.on("data", (chunk) => {
2298
- outputTail = appendOutputTail(outputTail, chunk.toString());
2299
- });
2750
+ const collect = (chunk) => {
2751
+ const text2 = chunk.toString();
2752
+ outputTail = appendOutputTail(outputTail, text2);
2753
+ options.onOutput?.(text2);
2754
+ };
2755
+ child.stdout?.on("data", collect);
2756
+ child.stderr?.on("data", collect);
2300
2757
  }
2301
2758
  const settle = (finish) => {
2302
2759
  stopOnInterrupt();
2303
2760
  if (!interrupts.isInterrupted()) finish();
2304
2761
  };
2305
- child.on("close", (code, signal) => {
2306
- if (code === 0) {
2762
+ child.on("close", (code2, signal) => {
2763
+ if (code2 === 0) {
2307
2764
  settle(resolve);
2308
2765
  return;
2309
2766
  }
2310
- const fail2 = () => settle(() => reject(new CommandExitError(code, outputTail.trim())));
2311
- const diedFromInterrupt = signal === "SIGINT" || signal === "SIGTERM" || code !== null && INTERRUPT_EXIT_CODES.has(code);
2767
+ const fail2 = () => settle(() => reject(new CommandExitError(code2, outputTail.trim())));
2768
+ const diedFromInterrupt = signal === "SIGINT" || signal === "SIGTERM" || code2 !== null && INTERRUPT_EXIT_CODES.has(code2);
2312
2769
  if (diedFromInterrupt && !interrupts.isInterrupted()) {
2313
2770
  setTimeout(fail2, INTERRUPT_SETTLE_MS);
2314
2771
  return;
@@ -2320,9 +2777,10 @@ function runCommand(command, args, cwd, options = {}) {
2320
2777
  }
2321
2778
  var INIT_COMMAND = cliCommand("init");
2322
2779
  var ACCOUNT_STEP_LINES = [
2323
- "Init signs you in to your Standard Agents account in the browser (or creates one).",
2324
- "The account supplies inference for your agents, so no provider keys are needed."
2780
+ "Init signs you in to your Standard Agents account in the browser, or creates an account.",
2781
+ "Your Standard Agents account supplies inference for your agents. You need no provider keys."
2325
2782
  ];
2783
+ var ACCOUNT_STEP_SUMMARY = ACCOUNT_STEP_LINES[1];
2326
2784
  var SESSION_EXPIRED_MESSAGE = `The sign-in session expired before the browser steps were finished.
2327
2785
  Start a new one: ${INIT_COMMAND}`;
2328
2786
  var SESSION_CANCELLED_MESSAGE = `Sign-in was cancelled in the browser.
@@ -2368,8 +2826,8 @@ function resolveFreeDirectoryName(cwd, name) {
2368
2826
  }
2369
2827
  }
2370
2828
  function commandFailureCause(label, error) {
2371
- const code = error !== null && typeof error === "object" && "code" in error ? error.code : void 0;
2372
- if (code === "ENOENT") {
2829
+ const code2 = error !== null && typeof error === "object" && "code" in error ? error.code : void 0;
2830
+ if (code2 === "ENOENT") {
2373
2831
  return `${label.split(" ")[0]} is not installed or is not on your PATH.`;
2374
2832
  }
2375
2833
  const exitCode = error !== null && typeof error === "object" && "exitCode" in error ? error.exitCode : void 0;
@@ -2428,6 +2886,39 @@ function devServerFailure(params) {
2428
2886
  ]
2429
2887
  };
2430
2888
  }
2889
+ var COLORS2 = {
2890
+ success: "#8bcb6f",
2891
+ link: "#58aeb0",
2892
+ warning: "#ffb35c",
2893
+ error: "#ff5f5f"
2894
+ };
2895
+ function Screen({ children }) {
2896
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", paddingLeft: 2, paddingTop: 1, children });
2897
+ }
2898
+ function Header({ notice }) {
2899
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [
2900
+ /* @__PURE__ */ jsxs(Text, { children: [
2901
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "Standard Agents" }),
2902
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: ` ${cliVersion()}` })
2903
+ ] }),
2904
+ notice ? /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Warning, { children: notice }) }) : null
2905
+ ] });
2906
+ }
2907
+ function Warning({ children }) {
2908
+ return /* @__PURE__ */ jsxs(Text, { children: [
2909
+ /* @__PURE__ */ jsx(Text, { color: COLORS2.warning, children: GLYPHS.warning }),
2910
+ ` ${children}`
2911
+ ] });
2912
+ }
2913
+ function Choice({ selected, label, description }) {
2914
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
2915
+ /* @__PURE__ */ jsx(Text, { bold: selected, children: `${selected ? GLYPHS.cursor : " "} ${label}` }),
2916
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: ` ${description}` })
2917
+ ] });
2918
+ }
2919
+ function KeyHints({ children }) {
2920
+ return /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { dimColor: true, children }) });
2921
+ }
2431
2922
 
2432
2923
  // src/tui/local-init-wizard.ts
2433
2924
  var INIT_PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
@@ -2590,7 +3081,7 @@ function createLocalInitWizard(config) {
2590
3081
  }
2591
3082
  var STAGE_LABELS = {
2592
3083
  project: "Project",
2593
- env: "Env",
3084
+ env: "Environment",
2594
3085
  scaffold: "Scaffold"
2595
3086
  };
2596
3087
  function getInitProgressStages(collectEnv) {
@@ -2605,60 +3096,16 @@ function getInitStepInfo(stage, collectEnv) {
2605
3096
  labels: flow.map((item) => STAGE_LABELS[item])
2606
3097
  };
2607
3098
  }
2608
- function Stepper({ activeStage, collectEnv }) {
2609
- const flow = getInitProgressStages(collectEnv);
2610
- const activeIndex = flow.indexOf(activeStage);
2611
- return /* @__PURE__ */ jsx(Box, { flexDirection: "row", marginBottom: 1, children: flow.map((stage, index) => {
2612
- const label = STAGE_LABELS[stage];
2613
- const isActive = index === activeIndex;
2614
- const isDone = index < activeIndex;
2615
- const fg = isActive ? "black" : isDone ? "green" : "gray";
2616
- const bg = isActive ? "cyan" : void 0;
2617
- const marker = isDone ? "\u2713" : isActive ? "\u25CF" : "\xB7";
2618
- return /* @__PURE__ */ jsx(Box, { marginRight: 1, children: /* @__PURE__ */ jsxs(Text, { color: fg, backgroundColor: bg, children: [
2619
- " ",
2620
- marker,
2621
- " ",
2622
- label,
2623
- " "
2624
- ] }) }, stage);
2625
- }) });
2626
- }
2627
- function InitStepFrame(props) {
2628
- const { step, total } = getInitStepInfo(props.stage, props.collectEnv);
2629
- const metadata = useMemo(() => {
2630
- const items = [];
2631
- if (props.projectName) {
2632
- items.push({ id: "project", label: "Project", value: props.projectName });
2633
- }
2634
- if (props.packageManager) {
2635
- items.push({ id: "pm", label: "Package manager", value: props.packageManager });
2636
- }
2637
- return items;
2638
- }, [props.packageManager, props.projectName]);
2639
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, children: [
2640
- /* @__PURE__ */ jsxs(Box, { borderStyle: "round", borderColor: "cyan", paddingX: 1, flexDirection: "column", children: [
2641
- /* @__PURE__ */ jsx(Text, { color: "cyanBright", bold: true, children: "Standard Agents CLI" }),
2642
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Project setup" })
2643
- ] }),
2644
- /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Stepper, { activeStage: props.stage, collectEnv: props.collectEnv }) }),
2645
- metadata.length > 0 && /* @__PURE__ */ jsx(Box, { marginBottom: 1, flexDirection: "row", children: metadata.map((item, index) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
2646
- /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
2647
- item.label,
2648
- " "
2649
- ] }),
2650
- /* @__PURE__ */ jsx(Text, { color: item.id === "project" ? "whiteBright" : "magentaBright", children: item.value }),
2651
- index < metadata.length - 1 ? /* @__PURE__ */ jsx(Text, { color: "gray", children: " \u2022 " }) : null
2652
- ] }, item.id)) }),
2653
- /* @__PURE__ */ jsxs(Text, { color: "whiteBright", bold: true, children: [
2654
- "Step ",
2655
- step,
2656
- "/",
2657
- total,
2658
- ": ",
2659
- props.title
2660
- ] }),
2661
- props.subtitle ? /* @__PURE__ */ jsx(Text, { color: "gray", children: props.subtitle }) : null
3099
+ function StepHeading(props) {
3100
+ const { step, total, labels } = getInitStepInfo(props.stage, props.collectEnv);
3101
+ const position = [`Step ${step} of ${total}`, labels[step - 1], props.projectName, props.packageManager].filter(Boolean).join(" \xB7 ");
3102
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3103
+ /* @__PURE__ */ jsx(Header, {}),
3104
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: position }),
3105
+ /* @__PURE__ */ jsxs(Box, { marginTop: 1, flexDirection: "column", children: [
3106
+ /* @__PURE__ */ jsx(Text, { bold: true, children: props.title }),
3107
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: props.subtitle })
3108
+ ] })
2662
3109
  ] });
2663
3110
  }
2664
3111
  var PACKAGE_MANAGER_DESCRIPTIONS = {
@@ -2685,71 +3132,70 @@ var ENV_FIELD_COPY = {
2685
3132
  }
2686
3133
  };
2687
3134
  var MASK = "\u2022";
2688
- function TextField({ state, placeholder, secret }) {
3135
+ function TextField({ state, placeholder, secret, oneRow }) {
2689
3136
  const chars = [...state.text].map((char) => secret ? MASK : char);
2690
- return /* @__PURE__ */ jsxs(Box, { borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [
2691
- /* @__PURE__ */ jsx(Text, { children: chars.slice(0, state.cursor).join("") }),
3137
+ return /* @__PURE__ */ jsxs(Text, { wrap: oneRow ? "truncate-start" : "wrap", children: [
3138
+ `${GLYPHS.cursor} `,
3139
+ chars.slice(0, state.cursor).join(""),
2692
3140
  /* @__PURE__ */ jsx(Text, { inverse: true, children: chars[state.cursor] ?? " " }),
2693
- chars.length > 0 ? /* @__PURE__ */ jsx(Text, { children: chars.slice(state.cursor + 1).join("") }) : /* @__PURE__ */ jsx(Text, { color: "gray", children: placeholder })
3141
+ chars.length > 0 ? chars.slice(state.cursor + 1).join("") : /* @__PURE__ */ jsx(Text, { dimColor: true, children: placeholder })
2694
3142
  ] });
2695
3143
  }
2696
- function WizardBody({ state, detected }) {
3144
+ function WizardBody({ state, detected, embedded = false, maxRows }) {
3145
+ const hints = (text2) => embedded ? null : /* @__PURE__ */ jsx(KeyHints, { children: text2 });
3146
+ const rows = maxRows ?? Number.POSITIVE_INFINITY;
3147
+ const top = rows >= 6 ? 1 : 0;
2697
3148
  if (state.step === "name") {
2698
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
2699
- state.nameError ? /* @__PURE__ */ jsx(Text, { color: "yellow", children: state.nameError }) : null,
2700
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Project name" }),
2701
- /* @__PURE__ */ jsx(TextField, { state, placeholder: "acme-agents" }),
2702
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Type a name. Press Enter to continue or Esc to cancel." })
3149
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginTop: top, children: [
3150
+ /* @__PURE__ */ jsx(TextField, { state, placeholder: "acme-agents", oneRow: embedded }),
3151
+ state.nameError ? /* @__PURE__ */ jsx(Warning, { children: state.nameError }) : null,
3152
+ hints("Enter to continue \xB7 Esc to cancel")
2703
3153
  ] });
2704
3154
  }
2705
3155
  if (state.step === "confirm") {
2706
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
2707
- /* @__PURE__ */ jsx(Text, { children: `"${state.target?.projectName ?? ""}" already holds a Standard Agents project.` }),
2708
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Setup will reinstall dependencies and refresh the scaffold files." }),
2709
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Existing values in .dev.vars will be kept." }),
2710
- /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: "Press Enter to update this project or Esc to cancel." }) })
3156
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginTop: top, children: [
3157
+ /* @__PURE__ */ jsx(Text, { children: `"${state.target?.projectName ?? ""}" holds a Standard Agents project.` }),
3158
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Setup will reinstall dependencies and refresh the scaffold files." }),
3159
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: "Existing values in .dev.vars will be kept." }),
3160
+ hints("Enter to update this project \xB7 Esc to cancel")
2711
3161
  ] });
2712
3162
  }
2713
3163
  if (state.step === "packageManager") {
2714
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
3164
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginTop: top, gap: rows >= 12 ? 1 : 0, children: [
2715
3165
  INIT_PACKAGE_MANAGERS.map((name) => {
2716
3166
  const selected = name === state.packageManager;
2717
- return /* @__PURE__ */ jsxs(Box, { children: [
2718
- /* @__PURE__ */ jsxs(Text, { color: selected ? "black" : "white", backgroundColor: selected ? "cyan" : void 0, bold: selected, children: [
2719
- selected ? "\u203A" : " ",
2720
- " ",
2721
- name,
2722
- name === detected ? " (detected)" : ""
2723
- ] }),
2724
- /* @__PURE__ */ jsx(Text, { color: selected ? "cyan" : "gray", children: ` ${PACKAGE_MANAGER_DESCRIPTIONS[name]}` })
2725
- ] }, name);
3167
+ const label = name === detected ? `${name} (detected)` : name;
3168
+ return rows >= 9 ? /* @__PURE__ */ jsx(Choice, { selected, label, description: PACKAGE_MANAGER_DESCRIPTIONS[name] }, name) : /* @__PURE__ */ jsx(Text, { bold: selected, wrap: "truncate-end", children: `${selected ? GLYPHS.cursor : " "} ${label}` }, name);
2726
3169
  }),
2727
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Use the arrow keys (or j/k). Press Enter to continue or Esc to cancel." })
3170
+ hints("\u2191\u2193 to move \xB7 Enter to continue \xB7 Esc to cancel")
2728
3171
  ] });
2729
3172
  }
2730
3173
  const activeIndex = ENV_FIELDS.indexOf(state.step);
2731
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, marginTop: 1, children: [
3174
+ const error = Boolean(state.fieldError);
3175
+ const allFields = rows >= 14 && !(embedded && error);
3176
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginTop: top, children: [
2732
3177
  ENV_FIELDS.map((field2, index) => {
2733
3178
  const copy = ENV_FIELD_COPY[field2];
2734
3179
  const isActive = index === activeIndex;
2735
3180
  const isComplete = index < activeIndex;
2736
- const marker = isComplete ? "\u2713" : isActive ? "\u203A" : "\xB7";
2737
3181
  const saved = state.env[field2] ? MASK.repeat(8) : "";
2738
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [
2739
- /* @__PURE__ */ jsxs(Text, { color: isActive ? "cyanBright" : isComplete ? "greenBright" : "gray", bold: isActive, children: [
2740
- marker,
2741
- " ",
2742
- copy.title
3182
+ if (!allFields && !isActive) return null;
3183
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginBottom: allFields ? 1 : 0, children: [
3184
+ /* @__PURE__ */ jsxs(Text, { bold: isActive, children: [
3185
+ isComplete ? /* @__PURE__ */ jsx(Text, { color: COLORS2.success, children: GLYPHS.done }) : isActive ? GLYPHS.current : " ",
3186
+ ` ${copy.title}`
2743
3187
  ] }),
2744
- /* @__PURE__ */ jsx(Text, { color: "gray", children: copy.description }),
2745
- isActive ? /* @__PURE__ */ jsxs(Fragment, { children: [
2746
- /* @__PURE__ */ jsx(TextField, { state, placeholder: copy.placeholder, secret: true }),
2747
- state.fieldError ? /* @__PURE__ */ jsx(Text, { color: "yellow", children: state.fieldError }) : null
2748
- ] }) : /* @__PURE__ */ jsx(Text, { color: isComplete ? "white" : "gray", children: saved || "(not set)" })
3188
+ /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingLeft: 2, children: [
3189
+ allFields || !error && rows >= 4 ? /* @__PURE__ */ jsx(Text, { dimColor: true, children: copy.description }) : null,
3190
+ isActive ? /* @__PURE__ */ jsxs(Fragment, { children: [
3191
+ /* @__PURE__ */ jsx(TextField, { state, placeholder: copy.placeholder, secret: true, oneRow: embedded }),
3192
+ state.fieldError ? /* @__PURE__ */ jsx(Warning, { children: state.fieldError }) : null
3193
+ ] }) : /* @__PURE__ */ jsx(Text, { dimColor: !isComplete, children: saved || "Not set" })
3194
+ ] })
2749
3195
  ] }, field2);
2750
3196
  }),
2751
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Keys for other providers can be added to .dev.vars later." }),
2752
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Press Enter to continue each field or Esc to cancel." })
3197
+ allFields || !error && rows >= 7 ? /* @__PURE__ */ jsx(Text, { dimColor: true, children: "You can add keys for other providers to .dev.vars later." }) : null,
3198
+ hints("Enter to continue \xB7 Esc to cancel")
2753
3199
  ] });
2754
3200
  }
2755
3201
  var ENV_FRAME = {
@@ -2758,7 +3204,7 @@ var ENV_FRAME = {
2758
3204
  subtitle: "Add optional provider keys and local admin access."
2759
3205
  };
2760
3206
  var STEP_FRAMES = {
2761
- name: { stage: "project", title: "Project", subtitle: "Choose the directory name for your new project." },
3207
+ name: { stage: "project", title: "Project name", subtitle: "Choose the directory name for your new project." },
2762
3208
  confirm: { stage: "project", title: "Existing project", subtitle: "Confirm the update of this project." },
2763
3209
  packageManager: {
2764
3210
  stage: "project",
@@ -2772,15 +3218,18 @@ var STEP_FRAMES = {
2772
3218
  function LocalInitWizardView({ wizard, detected }) {
2773
3219
  const { exit } = useApp();
2774
3220
  const [state, setState] = useState(() => wizard.snapshot());
3221
+ const settled = Boolean(state.outcome);
3222
+ useEffect(() => {
3223
+ if (settled) exit();
3224
+ }, [settled, exit]);
2775
3225
  useInput((input, key) => {
2776
3226
  wizard.handleKey(input, key);
2777
- const next = wizard.snapshot();
2778
- setState(next);
2779
- if (next.outcome) exit();
3227
+ setState(wizard.snapshot());
2780
3228
  });
2781
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
3229
+ if (settled) return null;
3230
+ return /* @__PURE__ */ jsxs(Screen, { children: [
2782
3231
  /* @__PURE__ */ jsx(
2783
- InitStepFrame,
3232
+ StepHeading,
2784
3233
  {
2785
3234
  ...STEP_FRAMES[state.step],
2786
3235
  projectName: state.target?.projectName,
@@ -2795,7 +3244,6 @@ async function runLocalInitWizardWithInk(config, terminal = { stdin: process.std
2795
3244
  const wizard = createLocalInitWizard(config);
2796
3245
  const settled = wizard.snapshot().outcome;
2797
3246
  if (settled) return settled.kind === "done" ? settled.result : null;
2798
- terminal.stdout.write("\x1B[2J\x1B[H");
2799
3247
  const instance = render(/* @__PURE__ */ jsx(LocalInitWizardView, { wizard, detected: config.detectedPackageManager }), {
2800
3248
  stdin: terminal.stdin,
2801
3249
  stdout: terminal.stdout,
@@ -2805,35 +3253,12 @@ async function runLocalInitWizardWithInk(config, terminal = { stdin: process.std
2805
3253
  const outcome = wizard.snapshot().outcome;
2806
3254
  return outcome?.kind === "done" ? outcome.result : null;
2807
3255
  }
2808
- function renderInitStepFrame(state) {
2809
- return renderToString(/* @__PURE__ */ jsx(InitStepFrame, { ...state }));
2810
- }
2811
3256
  var LOCAL_SIGN_IN_NOTES = [
2812
3257
  "Open the dev server URL. Sign in with username `admin` and the `SUPER_ADMIN_PASSWORD` value from `.dev.vars`.",
2813
3258
  "Open the gear menu, select Users, and create an account for yourself.",
2814
3259
  "Sign in with your own account, then remove `SUPER_ADMIN_PASSWORD` from `.dev.vars`.",
2815
3260
  "Add provider API keys to `.dev.vars` to use more model providers."
2816
3261
  ];
2817
- function renderInitCompleteFrame(input) {
2818
- return renderToString(
2819
- /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, children: [
2820
- /* @__PURE__ */ jsxs(Box, { borderStyle: "round", borderColor: "green", paddingX: 1, flexDirection: "column", children: [
2821
- /* @__PURE__ */ jsx(Text, { color: "greenBright", bold: true, children: "Setup complete" }),
2822
- /* @__PURE__ */ jsx(Text, { color: "whiteBright", children: input.useExistingProject ? "Project updated successfully." : "Project created successfully." })
2823
- ] }),
2824
- /* @__PURE__ */ jsxs(Box, { marginTop: 1, flexDirection: "column", children: [
2825
- /* @__PURE__ */ jsx(Text, { color: "cyanBright", bold: true, children: "Next steps" }),
2826
- input.changeDirectory ? /* @__PURE__ */ jsx(Text, { color: "white", children: ` cd ${input.projectName}` }) : null,
2827
- /* @__PURE__ */ jsx(Text, { color: "white", children: ` ${input.nextCommand}` })
2828
- ] }),
2829
- input.localSignIn ? /* @__PURE__ */ jsxs(Box, { marginTop: 1, flexDirection: "column", children: [
2830
- /* @__PURE__ */ jsx(Text, { color: "yellowBright", bold: true, children: "Sign in" }),
2831
- LOCAL_SIGN_IN_NOTES.map((note, index) => /* @__PURE__ */ jsx(Text, { color: "gray", children: ` ${index + 1}. ${note}` }, note))
2832
- ] }) : null,
2833
- /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: "Docs: https://docs.standardagents.ai" }) })
2834
- ] })
2835
- );
2836
- }
2837
3262
 
2838
3263
  // src/commands/init.ts
2839
3264
  var DEFAULT_ONBOARDING_URL = "https://platform.standardagents.ai/projects/new";
@@ -2849,48 +3274,21 @@ var GENERATED_STANDARD_AGENTS_PACKAGES = [
2849
3274
  var PACKAGE_MANAGERS2 = ["npm", "pnpm", "yarn", "bun"];
2850
3275
  var MISSING_PLATFORM_PROJECT_NAME_MESSAGE = "The platform did not return a project name. Please run the init command again to start a new project setup.";
2851
3276
  var LEGACY_BOOTSTRAP_RESPONSE_MESSAGE = "The platform returned an older onboarding response. Please run the init command again to start a new project setup.";
2852
- var SPINNER_FRAMES2 = ["-", "\\", "|", "/"];
2853
- async function withTuiSpinner(enabled, label, operation) {
2854
- if (!enabled || !process.stdout.isTTY) {
2855
- return operation();
2856
- }
2857
- let index = 0;
2858
- process.stdout.write("\n");
2859
- const renderFrame = (prefix) => {
2860
- process.stdout.write(`\r${prefix} ${label}`);
2861
- };
2862
- renderFrame(SPINNER_FRAMES2[index]);
2863
- const timer = setInterval(() => {
2864
- index = (index + 1) % SPINNER_FRAMES2.length;
2865
- renderFrame(SPINNER_FRAMES2[index]);
2866
- }, 80);
2867
- try {
2868
- const result = await operation();
2869
- clearInterval(timer);
2870
- renderFrame("\u2713");
2871
- process.stdout.write("\n");
2872
- return result;
2873
- } catch (error) {
2874
- clearInterval(timer);
2875
- renderFrame("!");
2876
- process.stdout.write("\n");
2877
- throw error;
2878
- }
2879
- }
2880
- function devServerSpawnOptions(cwd) {
3277
+ function devServerSpawnOptions(cwd, piped = false) {
2881
3278
  return {
2882
3279
  cwd,
2883
- stdio: "inherit",
2884
- shell: false
3280
+ stdio: piped ? ["ignore", "pipe", "pipe"] : "inherit",
3281
+ shell: false,
3282
+ ...piped ? { env: { ...process.env, FORCE_COLOR: "1" } } : {}
2885
3283
  };
2886
3284
  }
2887
- function startForegroundDevServer(command, args, cwd) {
2888
- return spawn(command, args, devServerSpawnOptions(cwd));
3285
+ function startForegroundDevServer(command, args, cwd, piped) {
3286
+ return spawn(command, args, devServerSpawnOptions(cwd, piped));
2889
3287
  }
2890
3288
  function waitForDevServerExit(child) {
2891
3289
  return new Promise((resolve, reject) => {
2892
3290
  child.once("error", reject);
2893
- child.once("close", (code) => resolve(code));
3291
+ child.once("close", (code2) => resolve(code2));
2894
3292
  });
2895
3293
  }
2896
3294
  function devCommandHint(packageManager) {
@@ -2920,7 +3318,10 @@ async function findAvailablePort(startPort) {
2920
3318
  }
2921
3319
  function buildDevServerCommand(packageManager, port, pnpmCompatibilityArgs = []) {
2922
3320
  const viteArgs = ["--host", "127.0.0.1", "--port", String(port), "--strictPort"];
2923
- return packageManager === "npm" ? ["run", "dev", "--", ...viteArgs] : [...packageManager === "pnpm" ? pnpmCompatibilityArgs : [], "dev", ...viteArgs];
3321
+ if (packageManager === "npm") return ["run", "--silent", "dev", "--", ...viteArgs];
3322
+ if (packageManager === "pnpm") return [...pnpmCompatibilityArgs, "--silent", "dev", ...viteArgs];
3323
+ if (packageManager === "bun") return ["run", "--silent", "dev", ...viteArgs];
3324
+ return ["dev", ...viteArgs];
2924
3325
  }
2925
3326
  async function waitForLocalDevServer(url, timeoutMs = 6e4, signal) {
2926
3327
  const deadline = Date.now() + timeoutMs;
@@ -3039,9 +3440,6 @@ function resolvePackageManager(requested, detected) {
3039
3440
  }
3040
3441
  throw new Error("package-manager must be npm, pnpm, yarn, or bun");
3041
3442
  }
3042
- function clearTerminalScreen(stdout = process.stdout) {
3043
- stdout.write("\x1B[2J\x1B[H");
3044
- }
3045
3443
  function silenceLoggerOutput(enabled) {
3046
3444
  if (!enabled) return () => {
3047
3445
  };
@@ -3066,7 +3464,7 @@ function silenceLoggerOutput(enabled) {
3066
3464
  logger.log = original.log;
3067
3465
  };
3068
3466
  }
3069
- function renderInitStepHeader(stage, title, subtitle, options) {
3467
+ function logInitStepHeader(stage, title, subtitle, options) {
3070
3468
  const { step, total, labels } = getInitStepInfo(stage, options.collectEnv);
3071
3469
  const progress = labels.map((label, index) => {
3072
3470
  const markerIndex = index + 1;
@@ -3074,20 +3472,6 @@ function renderInitStepHeader(stage, title, subtitle, options) {
3074
3472
  if (markerIndex === step) return `\u2192 ${label}`;
3075
3473
  return `\xB7 ${label}`;
3076
3474
  }).join(" ");
3077
- if (options.tuiMode) {
3078
- clearTerminalScreen();
3079
- process.stdout.write(
3080
- renderInitStepFrame({
3081
- stage,
3082
- title,
3083
- subtitle,
3084
- projectName: options.projectName,
3085
- packageManager: options.packageManager,
3086
- collectEnv: options.collectEnv
3087
- })
3088
- );
3089
- return;
3090
- }
3091
3475
  logger.log("");
3092
3476
  logger.log(progress);
3093
3477
  logger.info(`Step ${step}/${total}: ${title}`);
@@ -3095,7 +3479,7 @@ function renderInitStepHeader(stage, title, subtitle, options) {
3095
3479
  logger.log("");
3096
3480
  }
3097
3481
  function getCliVersion() {
3098
- return "0.45.9";
3482
+ return cliVersion();
3099
3483
  }
3100
3484
  function getSipVersion() {
3101
3485
  return "1.0.1";
@@ -3187,12 +3571,12 @@ function projectInstallArgs(packageManager, projectPath, command = "install", de
3187
3571
  const saveExact = packageManager === "npm" && dependencies.length > 0 ? ["--save-exact"] : [];
3188
3572
  return [...prefix, command, ...saveExact, ...dependencies];
3189
3573
  }
3190
- async function pinLatestFrameworkRelease(projectPath) {
3191
- const cliVersion2 = getCliVersion();
3192
- if (isPrereleaseVersion(cliVersion2)) {
3193
- const pinned2 = pinFrameworkDependencies(projectPath, cliVersion2);
3574
+ async function pinLatestFrameworkRelease(projectPath, reportPinned = logger.success) {
3575
+ const cliVersion3 = getCliVersion();
3576
+ if (isPrereleaseVersion(cliVersion3)) {
3577
+ const pinned2 = pinFrameworkDependencies(projectPath, cliVersion3);
3194
3578
  if (pinned2.length > 0) {
3195
- logger.info(`Pinned ${pinned2.length} Standard Agents packages to ${cliVersion2}, the release of this prerelease CLI.`);
3579
+ reportPinned(`Pinned ${pinned2.length} Standard Agents packages to ${cliVersion3}, the release of this prerelease CLI`);
3196
3580
  }
3197
3581
  return;
3198
3582
  }
@@ -3205,30 +3589,30 @@ async function pinLatestFrameworkRelease(projectPath) {
3205
3589
  }
3206
3590
  const pinned = pinFrameworkDependencies(projectPath, latest.version);
3207
3591
  if (pinned.length > 0) {
3208
- logger.info(`Pinned ${pinned.length} Standard Agents packages to ${latest.version}, the latest release.`);
3592
+ reportPinned(`Pinned ${pinned.length} Standard Agents packages to ${latest.version}, the latest release`);
3209
3593
  }
3210
3594
  }
3211
3595
  function shellQuote(value) {
3212
3596
  return `"${value.replace(/(["\\$`])/g, "\\$1")}"`;
3213
3597
  }
3214
3598
  function findWorkspaceCommandRoot(projectPath) {
3215
- let current = path19.dirname(projectPath);
3599
+ let current2 = path19.dirname(projectPath);
3216
3600
  while (true) {
3217
- const packageJsonPath = path19.join(current, "package.json");
3601
+ const packageJsonPath = path19.join(current2, "package.json");
3218
3602
  if (fs14.existsSync(packageJsonPath)) {
3219
3603
  try {
3220
3604
  const packageJson = JSON.parse(fs14.readFileSync(packageJsonPath, "utf-8"));
3221
3605
  if (packageJson?.scripts && typeof packageJson.scripts["sandbox:hmr"] === "string") {
3222
- return current;
3606
+ return current2;
3223
3607
  }
3224
3608
  } catch {
3225
3609
  }
3226
3610
  }
3227
- const parent = path19.dirname(current);
3228
- if (parent === current) {
3611
+ const parent = path19.dirname(current2);
3612
+ if (parent === current2) {
3229
3613
  return null;
3230
3614
  }
3231
- current = parent;
3615
+ current2 = parent;
3232
3616
  }
3233
3617
  }
3234
3618
  function linkWorkspaceProjectToolchain(projectPath, workspaceRoot) {
@@ -3301,10 +3685,10 @@ function onboardingUrlForEndpoint(endpoint) {
3301
3685
  function isBootstrapCodeFailureMessage(message) {
3302
3686
  return /bootstrap code/i.test(message);
3303
3687
  }
3304
- function formatBootstrapExchangeError(status2, body, endpoint) {
3688
+ function formatBootstrapExchangeError(status, body, endpoint) {
3305
3689
  const payload = body;
3306
3690
  const message = payload?.error?.message || payload?.message;
3307
- const base = message ? `Bootstrap exchange failed (${status2}): ${message}` : `Bootstrap exchange failed (${status2})`;
3691
+ const base = message ? `Bootstrap exchange failed (${status}): ${message}` : `Bootstrap exchange failed (${status})`;
3308
3692
  if (message && isBootstrapCodeFailureMessage(message)) {
3309
3693
  const url = onboardingUrlForEndpoint(endpoint);
3310
3694
  return `${base}
@@ -3336,11 +3720,11 @@ function extractSessionCookie(response) {
3336
3720
  }
3337
3721
  var BOOTSTRAP_EXCHANGE_TIMEOUT_NEXT = "Check your internet connection, then run the same command again. If the setup code is refused, copy a new setup command from the project's Overview page in the dashboard.";
3338
3722
  var AFTER_EXCHANGE_TIMEOUT_NEXT = "The setup code is already used. Copy a new setup command from the project's Overview page in the dashboard and run it.";
3339
- async function exchangeBootstrapCode(endpoint, code, fetchImpl = fetch) {
3723
+ async function exchangeBootstrapCode(endpoint, code2, fetchImpl = fetch) {
3340
3724
  const response = await platformFetch(endpoint, "/auth/bootstrap-code/consume", {
3341
3725
  method: "POST",
3342
3726
  headers: { "Content-Type": "application/json" },
3343
- body: JSON.stringify({ code })
3727
+ body: JSON.stringify({ code: code2 })
3344
3728
  }, { fetchImpl, next: BOOTSTRAP_EXCHANGE_TIMEOUT_NEXT });
3345
3729
  let body = {};
3346
3730
  try {
@@ -3600,8 +3984,8 @@ async function findFirstProjectId(endpoint, cookie, fetchImpl) {
3600
3984
  }
3601
3985
  return projectId;
3602
3986
  }
3603
- async function resolveBootstrapProject(endpoint, code, fetchImpl = fetch) {
3604
- const consumed = await exchangeBootstrapCode(endpoint, code, fetchImpl);
3987
+ async function resolveBootstrapProject(endpoint, code2, fetchImpl = fetch) {
3988
+ const consumed = await exchangeBootstrapCode(endpoint, code2, fetchImpl);
3605
3989
  const cookie = consumed.session_cookie;
3606
3990
  const projectId = consumed.project?.id ?? await findFirstProjectId(endpoint, cookie, fetchImpl);
3607
3991
  return requestCliHandoff(endpoint, projectId, cookie, fetchImpl);
@@ -3622,12 +4006,9 @@ async function requestCliHandoff(endpoint, projectId, cookie, fetchImpl = fetch)
3622
4006
  }
3623
4007
  return handoffBody.project;
3624
4008
  }
3625
- function exitWithInitFailure(failure) {
3626
- const [headline, ...detail] = failure.cause.split("\n");
3627
- logger.error(headline);
3628
- for (const line of [...detail, ...failure.next]) {
3629
- logger.detail(line);
3630
- }
4009
+ async function exitWithInitFailure(failure, commandError) {
4010
+ const output = commandError instanceof CommandExitError ? commandError.output : typeof commandError === "string" ? commandError : void 0;
4011
+ await flowReporter().failure(failure, output);
3631
4012
  process.exit(1);
3632
4013
  }
3633
4014
  function failureFromError(error) {
@@ -3649,9 +4030,8 @@ function browserOrigin(url) {
3649
4030
  }
3650
4031
  }
3651
4032
  async function createProjectThroughBrowser(params) {
3652
- for (const line of ACCOUNT_STEP_LINES) {
3653
- logger.info(line);
3654
- }
4033
+ const reporter = flowReporter();
4034
+ reporter.signInStarted("sign-in", { terminal: ACCOUNT_STEP_SUMMARY, plain: ACCOUNT_STEP_LINES });
3655
4035
  let session;
3656
4036
  try {
3657
4037
  session = await startPlatformCliSession({
@@ -3660,22 +4040,22 @@ async function createProjectThroughBrowser(params) {
3660
4040
  packageManager: params.packageManager
3661
4041
  });
3662
4042
  } catch (error) {
3663
- exitWithInitFailure(failureFromError(error));
4043
+ throw await exitWithInitFailure(failureFromError(error));
3664
4044
  }
3665
4045
  const waitAbort = new AbortController();
3666
4046
  let waitIndicator;
3667
4047
  const stopCancelOnInterrupt = interrupts.onInterrupt(async () => {
3668
4048
  waitAbort.abort();
3669
4049
  waitIndicator?.stop();
4050
+ stopLiveLine();
3670
4051
  await cancelCliAuthSession(params.endpoint, session.session_id);
3671
4052
  logger.info(`Sign-in cancelled. Start again when you are ready: ${INIT_COMMAND}`);
3672
4053
  });
3673
- await presentSignInUrl(session.auth_url, params.skipBrowserOpen);
4054
+ await reporter.signInUrl(session.auth_url, params.skipBrowserOpen);
3674
4055
  if (interrupts.isInterrupted()) return parkUntilExit();
3675
- const indicator = waitIndicator = startWaitIndicator({
4056
+ const indicator = waitIndicator = reporter.waitStarted({
3676
4057
  label: "Waiting for you to finish in the browser",
3677
- expiresAt: session.expires_at,
3678
- log: logger.info
4058
+ expiresAt: session.expires_at
3679
4059
  });
3680
4060
  let project;
3681
4061
  try {
@@ -3688,50 +4068,65 @@ async function createProjectThroughBrowser(params) {
3688
4068
  if (interrupts.isInterrupted()) return parkUntilExit();
3689
4069
  indicator.stop();
3690
4070
  stopCancelOnInterrupt();
3691
- exitWithInitFailure(failureFromError(error));
4071
+ throw await exitWithInitFailure(failureFromError(error));
3692
4072
  }
3693
4073
  if (interrupts.isInterrupted()) return parkUntilExit();
3694
4074
  indicator.stop();
3695
4075
  stopCancelOnInterrupt();
3696
4076
  return { project, dashboardUrl: browserOrigin(session.auth_url) };
3697
4077
  }
4078
+ function platformInitSteps(options) {
4079
+ return [
4080
+ ...options.bootstrap ? [{ id: "connect", label: "Connect" }] : [{ id: "sign-in", label: "Sign in" }, { id: "create", label: "Create project" }],
4081
+ { id: "clone", label: "Clone" },
4082
+ { id: "configure", label: "Configure" },
4083
+ { id: "install", label: "Install dependencies" },
4084
+ ...options.dev ? [{ id: "dev", label: "Start dev server" }] : []
4085
+ ];
4086
+ }
3698
4087
  async function runPlatformInit(projectNameArg, options) {
3699
4088
  const cwd = process.cwd();
4089
+ const reporter = flowReporter();
4090
+ reporter.header();
3700
4091
  let pm;
3701
4092
  try {
3702
4093
  pm = resolvePackageManager(options.packageManager, detectPackageManager());
3703
4094
  } catch (error) {
3704
- logger.error(error instanceof Error ? error.message : String(error));
3705
- process.exit(1);
4095
+ throw await exitWithInitFailure({ cause: error instanceof Error ? error.message : String(error), next: [] });
3706
4096
  }
3707
4097
  const requestedProjectName = projectNameArg?.trim() || void 0;
3708
4098
  if (requestedProjectName && fs14.existsSync(path19.join(cwd, requestedProjectName))) {
3709
- exitWithInitFailure(directoryExistsFailure(requestedProjectName));
4099
+ throw await exitWithInitFailure(directoryExistsFailure(requestedProjectName));
3710
4100
  }
3711
4101
  const endpoint = platformEndpoint(options);
3712
4102
  const bootstrapCode = options.bootstrap?.trim();
3713
4103
  const signIn = browserSignInPolicy(options);
3714
4104
  if (!bootstrapCode && !signIn.allowed) {
3715
- exitWithInitFailure(noTerminalFailure());
4105
+ throw await exitWithInitFailure(noTerminalFailure());
3716
4106
  }
3717
4107
  const gitVersion = installedGitVersion();
3718
4108
  if (gitVersion === null) {
3719
- exitWithInitFailure(gitMissingFailure());
4109
+ throw await exitWithInitFailure(gitMissingFailure());
3720
4110
  }
3721
4111
  if (!gitSupportsEnvironmentConfig(gitVersion)) {
3722
- exitWithInitFailure(gitTooOldFailure(gitVersion));
4112
+ throw await exitWithInitFailure(gitTooOldFailure(gitVersion));
3723
4113
  }
3724
4114
  if (!canStopProcessTrees()) {
3725
- exitWithInitFailure(processControlFailure());
4115
+ throw await exitWithInitFailure(processControlFailure());
3726
4116
  }
4117
+ reporter.begin("Create a project", platformInitSteps({ bootstrap: Boolean(bootstrapCode), dev: options.dev !== false }));
3727
4118
  let project;
3728
4119
  let dashboardUrl;
4120
+ let connecting;
3729
4121
  if (bootstrapCode) {
3730
- logger.info("Connecting to your Standard Agents instance...");
4122
+ connecting = reporter.stepStarted("connect", {
4123
+ label: "Connecting to your project",
4124
+ plain: "Connecting to your Standard Agents project..."
4125
+ });
3731
4126
  try {
3732
4127
  project = await resolveBootstrapProject(endpoint, bootstrapCode);
3733
4128
  } catch (error) {
3734
- exitWithInitFailure({ cause: error instanceof Error ? error.message : String(error), next: [] });
4129
+ throw await exitWithInitFailure({ cause: error instanceof Error ? error.message : String(error), next: [] });
3735
4130
  }
3736
4131
  } else {
3737
4132
  ({ project, dashboardUrl } = await createProjectThroughBrowser({
@@ -3747,37 +4142,55 @@ async function runPlatformInit(projectNameArg, options) {
3747
4142
  platformName = resolvePlatformProjectDirectoryName(project, requestedProjectName);
3748
4143
  projectPackageManager = resolvePlatformProjectPackageManager(project.package_manager, pm);
3749
4144
  } catch (error) {
3750
- exitWithInitFailure({ cause: error instanceof Error ? error.message : String(error), next: [] });
4145
+ throw await exitWithInitFailure({ cause: error instanceof Error ? error.message : String(error), next: [] });
3751
4146
  }
3752
4147
  const projectName = resolveFreeDirectoryName(cwd, platformName);
3753
4148
  const projectPath = path19.join(cwd, projectName);
3754
4149
  const projectLabel = project.name || projectName;
3755
- logger.success("Browser setup complete.");
4150
+ if (connecting) {
4151
+ connecting.done(`Connected to project ${projectLabel}`);
4152
+ } else {
4153
+ reporter.stepDone("sign-in", "Signed in");
4154
+ reporter.stepDone("create", `Created project ${projectLabel}`);
4155
+ }
3756
4156
  if (projectName !== platformName) {
3757
4157
  logger.warning(`Directory "${platformName}" already exists here, so the project will be cloned into "${projectName}".`);
3758
4158
  }
3759
- logger.info(`Cloning ${cloneDisplayUrl(project)}...`);
4159
+ const cloning = reporter.stepStarted("clone", {
4160
+ label: `Cloning into ${projectName}`,
4161
+ plain: `Cloning ${cloneDisplayUrl(project)}...`,
4162
+ detail: cloneDisplayUrl(project)
4163
+ });
4164
+ const cloneOutput = { quiet: cloning.live, onOutput: cloning.output };
3760
4165
  const stopRemoveOnInterrupt = interrupts.onInterrupt(() => {
4166
+ stopLiveLine();
3761
4167
  fs14.rmSync(projectPath, { recursive: true, force: true });
3762
4168
  logger.log("");
3763
4169
  logger.info(`Setup interrupted. Removed the partial "${projectName}" directory.`);
3764
4170
  for (const line of finishExistingProjectSteps(projectLabel, dashboardUrl)) {
3765
- logger.log(line);
4171
+ print(statusTarget(), "detail", line);
3766
4172
  }
3767
4173
  });
3768
4174
  try {
3769
- await runCommand("git", gitCloneArgs(project, projectName), cwd, { env: gitCloneEnv(project) });
4175
+ await runCommand("git", gitCloneArgs(project, projectName), cwd, { env: gitCloneEnv(project), ...cloneOutput });
3770
4176
  if (project.git_extra_header && project.repo_html_url) {
3771
- await runCommand("git", ["remote", "set-url", "origin", project.repo_html_url], projectPath);
4177
+ await runCommand("git", ["remote", "set-url", "origin", project.repo_html_url], projectPath, cloneOutput);
3772
4178
  }
3773
4179
  } catch (error) {
3774
4180
  stopRemoveOnInterrupt();
3775
- exitWithInitFailure(cloneFailure({
4181
+ throw await exitWithInitFailure(cloneFailure({
3776
4182
  projectName: projectLabel,
3777
4183
  cause: commandFailureCause("git clone", error),
3778
4184
  dashboardUrl
3779
- }));
4185
+ }), error);
3780
4186
  }
4187
+ cloning.done(`Cloned into ${projectName}`);
4188
+ const configuring = isTerminal(statusTarget()) ? reporter.stepStarted("configure", { label: `Configuring ${projectName}` }) : void 0;
4189
+ const configured = (message) => {
4190
+ if (configuring) configuring.output(`${message}
4191
+ `);
4192
+ else logger.success(message);
4193
+ };
3781
4194
  let envPath;
3782
4195
  try {
3783
4196
  const supportFiles2 = writeStandardAgentsSupportFiles(projectPath, {
@@ -3785,27 +4198,27 @@ async function runPlatformInit(projectNameArg, options) {
3785
4198
  packageManager: projectPackageManager
3786
4199
  });
3787
4200
  if (supportFiles2.length > 0) {
3788
- logger.success(`Wrote generated local support files: ${supportFiles2.join(", ")}.`);
4201
+ configured(`Wrote local support files: ${supportFiles2.join(", ")}`);
3789
4202
  }
3790
4203
  envPath = writeStandardAgentsEnv(projectPath, {
3791
4204
  apiKey: project.api_key,
3792
4205
  platformEndpoint: endpoint
3793
4206
  });
3794
- logger.success(`Wrote Standard Agents credentials to ${path19.relative(cwd, envPath)}.`);
4207
+ configured(`Wrote credentials to ${path19.relative(cwd, envPath)}`);
3795
4208
  if (project.git_extra_header) {
3796
4209
  await configurePlatformGitCredentialHelper(projectPath);
3797
- logger.success("Configured git credentials for the platform repository.");
4210
+ configured("Configured git credentials for the platform repository");
3798
4211
  }
3799
4212
  const linkedPackages = preparePlatformProjectDependencies(projectPath, projectPackageManager, options);
3800
4213
  if (linkedPackages.length > 0) {
3801
- logger.info(`Workspace mode detected: linked ${linkedPackages.length} Standard Agents packages locally.`);
4214
+ configured(`Linked ${linkedPackages.length} Standard Agents packages from the workspace`);
3802
4215
  }
3803
4216
  if (!shouldUseWorkspacePackages(options)) {
3804
- await pinLatestFrameworkRelease(projectPath);
4217
+ await pinLatestFrameworkRelease(projectPath, configured);
3805
4218
  }
3806
4219
  } catch (error) {
3807
4220
  stopRemoveOnInterrupt();
3808
- exitWithInitFailure(configureFailure({
4221
+ throw await exitWithInitFailure(configureFailure({
3809
4222
  projectName: projectLabel,
3810
4223
  directory: projectName,
3811
4224
  cause: commandFailureCause("Project configuration", error),
@@ -3813,7 +4226,6 @@ async function runPlatformInit(projectNameArg, options) {
3813
4226
  }));
3814
4227
  }
3815
4228
  stopRemoveOnInterrupt();
3816
- logger.info(`Installing dependencies with ${projectPackageManager}...`);
3817
4229
  const pnpmCompatibilityArgs = getPnpmWorkspaceCompatibilityArgs(projectPackageManager, projectPath);
3818
4230
  const devHint = pnpmCompatibilityArgs.length > 0 ? resolvePostInitRunCommand(projectPackageManager, projectPath, false, pnpmCompatibilityArgs) : devCommandHint(projectPackageManager);
3819
4231
  const freshInstall = freshInstallOptions(projectPackageManager);
@@ -3825,65 +4237,98 @@ async function runPlatformInit(projectNameArg, options) {
3825
4237
  ...freshInstall.args
3826
4238
  ];
3827
4239
  const installCommand = [projectPackageManager, ...installArgs].join(" ");
3828
- if (pinProjectScopeRegistry(projectPath, { packageManager: projectPackageManager, isolateFromParent: true }, logger).blocked) {
3829
- exitWithInitFailure(installFailure({
4240
+ const scopePinLog = {
4241
+ info: (message) => configured(message.replace(/\.$/, "")),
4242
+ warning: logger.warning
4243
+ };
4244
+ if (pinProjectScopeRegistry(projectPath, { packageManager: projectPackageManager, isolateFromParent: true }, scopePinLog).blocked) {
4245
+ throw await exitWithInitFailure(installFailure({
3830
4246
  directory: projectName,
3831
4247
  cause: SCOPE_REGISTRY_PIN_BLOCKED_CAUSE,
3832
4248
  installCommand,
3833
4249
  devCommand: devHint
3834
4250
  }));
3835
4251
  }
4252
+ configuring?.done(`Configured ${projectName}`, `credentials in ${DEV_VARS_FILENAME}`);
4253
+ const installing = reporter.stepStarted("install", {
4254
+ label: `Installing dependencies with ${projectPackageManager}`,
4255
+ detail: installCommand
4256
+ });
3836
4257
  const stopResumeHintOnInterrupt = interrupts.onInterrupt(() => {
4258
+ stopLiveLine();
3837
4259
  logger.log("");
3838
4260
  logger.info(`Setup interrupted. Your project is cloned and configured in "${projectName}". Finish with:`);
3839
4261
  for (const line of resumeSteps(projectName, installCommand, devHint)) {
3840
- logger.log(line);
4262
+ print(statusTarget(), "detail", line);
3841
4263
  }
3842
4264
  });
3843
4265
  try {
3844
- await runCommand(projectPackageManager, installArgs, projectPath, { env: freshInstall.env });
4266
+ await runCommand(projectPackageManager, installArgs, projectPath, {
4267
+ env: freshInstall.env,
4268
+ quiet: installing.live,
4269
+ onOutput: installing.output
4270
+ });
3845
4271
  } catch (error) {
3846
4272
  stopResumeHintOnInterrupt();
3847
- exitWithInitFailure(installFailure({
4273
+ throw await exitWithInitFailure(installFailure({
3848
4274
  directory: projectName,
3849
4275
  cause: commandFailureCause(`${projectPackageManager} install`, error),
3850
4276
  installCommand,
3851
4277
  devCommand: devHint
3852
- }));
4278
+ }), error);
3853
4279
  }
3854
4280
  stopResumeHintOnInterrupt();
4281
+ installing.done(`Installed dependencies with ${projectPackageManager}`);
3855
4282
  const repoUrl = project.repo_html_url ?? project.repo_clone_url;
4283
+ const startCommand = `cd ${projectName} && ${devHint}`;
3856
4284
  const tokenLocation = path19.relative(cwd, envPath);
3857
4285
  if (options.dev === false) {
3858
- logger.success("Your Standard Agents instance is ready.");
3859
- logger.log(`Repository: ${repoUrl}`);
3860
- logger.log(`Local token: ${tokenLocation}`);
3861
- logger.log("");
3862
- logger.log("Start it whenever you like:");
3863
- logger.log(` cd ${projectName}`);
3864
- logger.log(` ${devHint}`);
4286
+ reporter.summary({
4287
+ title: `${projectName} is ready`,
4288
+ rows: [
4289
+ ["Repository", repoUrl],
4290
+ ["Local token", tokenLocation],
4291
+ ["Start", startCommand]
4292
+ ]
4293
+ });
3865
4294
  return;
3866
4295
  }
3867
4296
  const devPort = await findAvailablePort(5173);
3868
4297
  const devUrl = `http://127.0.0.1:${devPort}`;
3869
- logger.info(`Starting local dev server at ${devUrl}...`);
3870
- logger.info("The dev server will stay in this terminal. Press Ctrl-C to stop it.");
4298
+ reporter.devServerStarting("dev", devUrl);
4299
+ const piped = reporter.fullScreen;
3871
4300
  const devProcess = startForegroundDevServer(
3872
4301
  projectPackageManager,
3873
4302
  buildDevServerCommand(projectPackageManager, devPort, pnpmCompatibilityArgs),
3874
- projectPath
4303
+ projectPath,
4304
+ piped
3875
4305
  );
4306
+ let devOutputTail = "";
4307
+ if (piped) {
4308
+ const collect = (chunk) => {
4309
+ const text2 = chunk.toString();
4310
+ devOutputTail = (devOutputTail + text2).slice(-8e3);
4311
+ reporter.devServerOutput(text2);
4312
+ };
4313
+ devProcess.stdout?.on("data", collect);
4314
+ devProcess.stderr?.on("data", collect);
4315
+ interrupts.onInterrupt(async () => {
4316
+ await terminateProcessTree(devProcess);
4317
+ logger.log("");
4318
+ logger.info("Stopped the dev server.");
4319
+ });
4320
+ }
3876
4321
  const devExit = waitForDevServerExit(devProcess);
3877
4322
  const devServerGone = new AbortController();
3878
4323
  devExit.catch(() => {
3879
4324
  }).finally(() => devServerGone.abort());
3880
4325
  let startup;
3881
- const exitWithDevServerFailure = (cause) => exitWithInitFailure(devServerFailure({ directory: projectName, cause, devCommand: devHint }));
3882
- const exitCodeNote = (code) => code === null ? "" : ` with code ${code}`;
4326
+ const exitWithDevServerFailure = (cause) => exitWithInitFailure(devServerFailure({ directory: projectName, cause, devCommand: devHint }), devOutputTail);
4327
+ const exitCodeNote = (code2) => code2 === null ? "" : ` with code ${code2}`;
3883
4328
  try {
3884
4329
  startup = await Promise.race([
3885
4330
  waitForLocalDevServer(devUrl, void 0, devServerGone.signal).then((ready) => ({ type: "ready", ready })),
3886
- devExit.then((code) => ({ type: "exit", code }))
4331
+ devExit.then((code2) => ({ type: "exit", code: code2 }))
3887
4332
  ]);
3888
4333
  } catch (error) {
3889
4334
  return exitWithDevServerFailure(
@@ -3894,20 +4339,22 @@ async function runPlatformInit(projectNameArg, options) {
3894
4339
  if (!signIn.skipBrowserOpen) {
3895
4340
  void openUrl(devUrl);
3896
4341
  }
3897
- logger.success("Project is connected to Standard Agents.");
3898
- logger.log(`Repository: ${repoUrl}`);
3899
- logger.log(`Dev server: ${devUrl}`);
3900
- logger.log(`Local token: ${tokenLocation}`);
3901
- logger.log("");
3902
- logger.log("The dev server is running in the foreground. Press Ctrl-C to stop it.");
3903
- logger.log("");
3904
- logger.log("To start it again later:");
3905
- logger.log(` cd ${projectName}`);
3906
- logger.log(` ${devHint}`);
4342
+ reporter.devServerReady(devUrl);
4343
+ reporter.summary({
4344
+ title: `${projectName} is ready`,
4345
+ rows: [
4346
+ ["Dev server", devUrl],
4347
+ ["Repository", repoUrl],
4348
+ ["Local token", tokenLocation],
4349
+ ["Start again", startCommand]
4350
+ ],
4351
+ // The record of a full-screen run is printed after the dev server stopped.
4352
+ ...piped ? {} : { footer: "The dev server runs in this terminal. Press Ctrl-C to stop it." }
4353
+ });
3907
4354
  const exitCode2 = await devExit;
3908
4355
  if (exitCode2 !== null && exitCode2 !== 0) {
3909
4356
  logger.log("");
3910
- exitWithDevServerFailure(`The dev server exited with code ${exitCode2}.`);
4357
+ await exitWithDevServerFailure(`The dev server exited with code ${exitCode2}.`);
3911
4358
  }
3912
4359
  return;
3913
4360
  }
@@ -3916,17 +4363,20 @@ async function runPlatformInit(projectNameArg, options) {
3916
4363
  `The dev server exited${exitCodeNote(startup.code)} before it responded at ${devUrl}. Its output is above.`
3917
4364
  );
3918
4365
  }
3919
- logger.warning(`The dev server didn't respond at ${devUrl} within 60s.`);
4366
+ logger.warning(`The dev server did not respond at ${devUrl} within 60 seconds.`);
3920
4367
  logger.log("");
3921
4368
  logger.info(`Your project is cloned and configured in "${projectName}".`);
3922
- logger.log(`Repository: ${repoUrl}`);
3923
- logger.log(`Dev server: ${devUrl}`);
3924
- logger.log(`Local token: ${tokenLocation}`);
3925
4369
  logger.log("");
3926
- logger.log("The dev server process is still running in this terminal. Press Ctrl-C to stop it.");
4370
+ printKeyValues([
4371
+ ["Dev server", devUrl],
4372
+ ["Repository", repoUrl],
4373
+ ["Local token", tokenLocation]
4374
+ ], { plain: "aligned" });
4375
+ logger.log("");
4376
+ logger.log("The dev server process still runs in this terminal. Press Ctrl-C to stop it.");
3927
4377
  const exitCode = await devExit;
3928
4378
  logger.log("");
3929
- exitWithDevServerFailure(
4379
+ await exitWithDevServerFailure(
3930
4380
  `The dev server exited${exitCodeNote(exitCode)} without responding at ${devUrl}. Its output is above.`
3931
4381
  );
3932
4382
  }
@@ -4025,14 +4475,12 @@ async function init(projectNameArg, initOptions = {}) {
4025
4475
  );
4026
4476
  process.exit(1);
4027
4477
  }
4478
+ const live = isTerminal("stdout");
4028
4479
  const logInfo = (message) => {
4029
- if (!initTuiMode) logger.info(message);
4030
- };
4031
- const logWarning = (message) => {
4032
- if (!initTuiMode) logger.warning(message);
4480
+ if (!live) logger.info(message);
4033
4481
  };
4034
4482
  const logSuccess = (message) => {
4035
- if (!initTuiMode) logger.success(message);
4483
+ if (!live) logger.success(message);
4036
4484
  };
4037
4485
  let requestedPm;
4038
4486
  if (options.packageManager) {
@@ -4050,6 +4498,14 @@ async function init(projectNameArg, initOptions = {}) {
4050
4498
  let target;
4051
4499
  let pm;
4052
4500
  let localEnv;
4501
+ const reporter = flowReporter();
4502
+ const localSteps = (existing) => [
4503
+ { id: "project", label: "Project" },
4504
+ ...existing ? [] : [{ id: "create", label: "Create Vite project" }],
4505
+ { id: "install", label: "Install dependencies" },
4506
+ { id: "files", label: "Write project files" }
4507
+ ];
4508
+ reporter.begin("Create a project", localSteps(initialTarget.ok && initialTarget.target.useExistingProject));
4053
4509
  if (!initTuiMode) {
4054
4510
  if (!initialTarget.ok) {
4055
4511
  logger.error(initialTarget.message);
@@ -4064,7 +4520,7 @@ async function init(projectNameArg, initOptions = {}) {
4064
4520
  existing: candidate.useExistingProject,
4065
4521
  collectEnv: needsLocalEnv(candidate)
4066
4522
  });
4067
- const answers = await runLocalInitWizardWithInk({
4523
+ const answers = await (reporter.askLocalSetup ?? runLocalInitWizardWithInk)({
4068
4524
  resolveTarget: (candidate) => {
4069
4525
  const resolution = resolveProjectTarget(cwd, candidate);
4070
4526
  if (!resolution.ok) return resolution;
@@ -4087,12 +4543,8 @@ async function init(projectNameArg, initOptions = {}) {
4087
4543
  localEnv = answers.env;
4088
4544
  }
4089
4545
  const { projectName, projectPath, useExistingProject } = target;
4090
- const headerOptions = {
4091
- tuiMode: initTuiMode,
4092
- projectName,
4093
- packageManager: pm,
4094
- collectEnv: localEnv !== void 0
4095
- };
4546
+ reporter.begin("Create a project", localSteps(useExistingProject));
4547
+ reporter.header();
4096
4548
  if (useExistingProject) {
4097
4549
  logInfo(`Using existing Standard Agents project "${projectName}"...`);
4098
4550
  } else {
@@ -4103,8 +4555,7 @@ async function init(projectNameArg, initOptions = {}) {
4103
4555
  try {
4104
4556
  packageSpecifier = resolvePackageSpecifier(options, pm);
4105
4557
  } catch (error) {
4106
- logger.error(error instanceof Error ? error.message : "Invalid package install mode");
4107
- process.exit(1);
4558
+ throw await exitWithInitFailure({ cause: error instanceof Error ? error.message : "Invalid package install mode", next: [] });
4108
4559
  }
4109
4560
  const bootstrapRequested = Boolean(providedBootstrap);
4110
4561
  const isManagedOrgMode = bootstrapRequested;
@@ -4112,13 +4563,16 @@ async function init(projectNameArg, initOptions = {}) {
4112
4563
  const openrouterKey = localEnv?.openrouterKey ?? "";
4113
4564
  const openaiKey = localEnv?.openaiKey ?? "";
4114
4565
  const adminPassword = localEnv?.adminPassword || crypto2.randomBytes(18).toString("base64url");
4115
- renderInitStepHeader(
4116
- "scaffold",
4117
- "Scaffold project",
4118
- "Installing dependencies and applying Standard Agents project structure.",
4119
- headerOptions
4120
- );
4566
+ if (!live) {
4567
+ logInitStepHeader(
4568
+ "scaffold",
4569
+ "Scaffold project",
4570
+ "Installing dependencies and applying Standard Agents project structure.",
4571
+ { collectEnv: localEnv !== void 0 }
4572
+ );
4573
+ }
4121
4574
  const stopRemoveOnInterrupt = !useExistingProject && !fs14.existsSync(projectPath) ? interrupts.onInterrupt(() => {
4575
+ stopLiveLine();
4122
4576
  fs14.rmSync(projectPath, { recursive: true, force: true });
4123
4577
  logger.log("");
4124
4578
  logger.info(`Setup interrupted. Removed the partial "${projectName}" directory.`);
@@ -4127,7 +4581,8 @@ async function init(projectNameArg, initOptions = {}) {
4127
4581
  if (!useExistingProject) {
4128
4582
  logInfo(`Running create-vite (${template})...`);
4129
4583
  try {
4130
- await withTuiSpinner(initTuiMode, "Creating Vite project...", async () => {
4584
+ {
4585
+ const creating = reporter.stepStarted("create", { label: "Creating the Vite project", plain: "Creating Vite project..." });
4131
4586
  let createCmd;
4132
4587
  let createArgs;
4133
4588
  switch (pm) {
@@ -4147,13 +4602,14 @@ async function init(projectNameArg, initOptions = {}) {
4147
4602
  createCmd = "npm";
4148
4603
  createArgs = ["create", "vite@latest", projectName, "--", "--template", template, "--no-interactive"];
4149
4604
  }
4150
- await runCommand(createCmd, createArgs, cwd, { quiet: initTuiMode });
4151
- });
4605
+ await runCommand(createCmd, createArgs, cwd, { quiet: creating.live, onOutput: creating.output });
4606
+ creating.done("Created the Vite project");
4607
+ }
4152
4608
  } catch (error) {
4153
- logger.error(
4154
- error instanceof Error ? `Failed to create Vite project: ${error.message}` : "Failed to create Vite project"
4155
- );
4156
- process.exit(1);
4609
+ throw await exitWithInitFailure({
4610
+ cause: error instanceof Error ? `Failed to create Vite project: ${error.message}` : "Failed to create Vite project",
4611
+ next: []
4612
+ });
4157
4613
  }
4158
4614
  const viteConfigPath = path19.join(projectPath, "vite.config.ts");
4159
4615
  if (!fs14.existsSync(viteConfigPath)) {
@@ -4194,8 +4650,7 @@ export default defineConfig({
4194
4650
  projectApiKey = (await resolveBootstrapProject(platformEndpoint(options), providedBootstrap)).api_key;
4195
4651
  logSuccess("The platform issued a project API key");
4196
4652
  } catch (error) {
4197
- logger.error(error instanceof Error ? error.message : "Bootstrap exchange failed");
4198
- process.exit(1);
4653
+ throw await exitWithInitFailure({ cause: error instanceof Error ? error.message : "Bootstrap exchange failed", next: [] });
4199
4654
  }
4200
4655
  }
4201
4656
  let projectPnpmCompatibilityArgs = [];
@@ -4211,15 +4666,15 @@ export default defineConfig({
4211
4666
  });
4212
4667
  const scopePin = pinProjectScopeRegistry(projectPath, { packageManager: pm, ...installBoundary }, { info: logInfo, warning: logger.warning });
4213
4668
  if (scopePin.blocked) {
4214
- logger.error(`Dependencies are not installed: ${SCOPE_REGISTRY_PIN_BLOCKED_CAUSE}`);
4215
- process.exit(1);
4669
+ await exitWithInitFailure({ cause: `Dependencies are not installed: ${SCOPE_REGISTRY_PIN_BLOCKED_CAUSE}`, next: [] });
4216
4670
  }
4217
4671
  projectPnpmCompatibilityArgs = getPnpmWorkspaceCompatibilityArgs(pm, projectPath);
4218
4672
  const installCmd = pm === "npm" ? "install" : "add";
4219
4673
  if (packageSpecifier === "workspace:*") {
4220
4674
  logInfo("Using local workspace @standardagents/* packages (link:).");
4221
4675
  }
4222
- await withTuiSpinner(initTuiMode, "Installing dependencies...", async () => {
4676
+ {
4677
+ const installing = reporter.stepStarted("install", { label: `Installing dependencies with ${pm}`, plain: "Installing dependencies..." });
4223
4678
  const standardAgentsPackage = (packageName) => `${packageName}@${resolveStandardAgentsPackageSpecifier(packageName, packageSpecifier)}`;
4224
4679
  const deps = [
4225
4680
  standardAgentsPackage("@standardagents/builder"),
@@ -4237,37 +4692,39 @@ export default defineConfig({
4237
4692
  ...installBoundary,
4238
4693
  ignoreProjectWorkspace: projectPnpmCompatibilityArgs.length > 0
4239
4694
  });
4240
- await runCommand(pm, installArgs, projectPath, { quiet: initTuiMode });
4241
- });
4695
+ await runCommand(pm, installArgs, projectPath, { quiet: installing.live, onOutput: installing.output });
4696
+ installing.done(`Installed dependencies with ${pm}`);
4697
+ }
4242
4698
  } catch (error) {
4243
- logger.error(
4244
- error instanceof Error ? `Failed to install dependencies: ${error.message}` : "Failed to install dependencies"
4245
- );
4246
- process.exit(1);
4699
+ throw await exitWithInitFailure({
4700
+ cause: error instanceof Error ? `Failed to install dependencies: ${error.message}` : "Failed to install dependencies",
4701
+ next: []
4702
+ });
4247
4703
  }
4248
4704
  process.chdir(projectPath);
4249
4705
  try {
4250
- const restoreLogger = silenceLoggerOutput(initTuiMode);
4706
+ const scaffolding = reporter.stepStarted("files", { label: "Writing the project files", plain: "Scaffolding project files..." });
4707
+ const restoreLogger = silenceLoggerOutput(live);
4251
4708
  try {
4252
- await withTuiSpinner(initTuiMode, "Scaffolding project files...", async () => {
4253
- assertScaffoldComplete(await scaffold(initScaffoldOptions(
4254
- useExistingProject,
4255
- packageSpecifier === "workspace:*" ? resolveStandardAgentsPackageSpecifier("@standardagents/builder", packageSpecifier) : void 0
4256
- )));
4257
- });
4709
+ assertScaffoldComplete(await scaffold(initScaffoldOptions(
4710
+ useExistingProject,
4711
+ packageSpecifier === "workspace:*" ? resolveStandardAgentsPackageSpecifier("@standardagents/builder", packageSpecifier) : void 0
4712
+ )));
4258
4713
  } finally {
4259
4714
  restoreLogger();
4260
4715
  }
4716
+ scaffolding.done("Wrote the project files");
4261
4717
  } catch (error) {
4718
+ stopLiveLine();
4262
4719
  if (projectApiKey) {
4263
- logWarning(
4720
+ logger.warning(
4264
4721
  "Scaffold failed after the setup code was used. Copy a new setup command from the project's Overview page in the dashboard to run it again."
4265
4722
  );
4266
4723
  }
4267
- logger.error(
4268
- error instanceof Error ? `Failed to scaffold Standard Agents project: ${error.message}` : "Failed to scaffold Standard Agents project"
4269
- );
4270
- process.exit(1);
4724
+ throw await exitWithInitFailure({
4725
+ cause: error instanceof Error ? `Failed to scaffold Standard Agents project: ${error.message}` : "Failed to scaffold Standard Agents project",
4726
+ next: []
4727
+ });
4271
4728
  }
4272
4729
  logInfo("Writing environment configuration...");
4273
4730
  const devVarsResult = writeLocalDevVars(projectPath, {
@@ -4281,21 +4738,27 @@ export default defineConfig({
4281
4738
  logSuccess(devVarsResult.status === "created" ? "Created .dev.vars with encryption key" : "Kept existing .dev.vars values and added missing keys");
4282
4739
  stopRemoveOnInterrupt();
4283
4740
  const nextRunCommand = resolvePostInitRunCommand(pm, projectPath, packageSpecifier === "workspace:*", projectPnpmCompatibilityArgs);
4284
- if (initTuiMode) {
4285
- clearTerminalScreen();
4286
- process.stdout.write(
4287
- renderInitCompleteFrame({
4288
- useExistingProject,
4289
- changeDirectory: projectPath !== cwd,
4290
- projectName,
4291
- nextCommand: nextRunCommand,
4292
- localSignIn: !isManagedOrgMode
4293
- })
4294
- );
4741
+ const startCommand = projectPath !== cwd ? `cd ${projectName} && ${nextRunCommand}` : nextRunCommand;
4742
+ if (live) {
4743
+ logger.log("");
4744
+ printHeading(useExistingProject ? `${projectName} is up to date` : `${projectName} is ready`);
4745
+ logger.log("");
4746
+ printKeyValues([
4747
+ ["Start", startCommand],
4748
+ ["Documentation", "https://standardagents.ai/docs"]
4749
+ ]);
4750
+ if (!isManagedOrgMode) {
4751
+ logger.log("");
4752
+ logger.log("Sign in to the local dev server:");
4753
+ LOCAL_SIGN_IN_NOTES.forEach((note, index) => {
4754
+ print("stdout", "detail", `${index + 1}. ${note}`);
4755
+ });
4756
+ }
4757
+ logger.log("");
4295
4758
  return;
4296
4759
  }
4297
4760
  logger.log("");
4298
- logger.success(useExistingProject ? "Project updated successfully!" : "Project created successfully!");
4761
+ logger.success(useExistingProject ? "Project updated." : "Project created.");
4299
4762
  logger.log("");
4300
4763
  logger.log("Next steps:");
4301
4764
  logger.log("");
@@ -4311,7 +4774,7 @@ export default defineConfig({
4311
4774
  });
4312
4775
  logger.log("");
4313
4776
  }
4314
- logger.log("For more information, visit: https://docs.standardagents.ai");
4777
+ logger.log("For more information, visit: https://standardagents.ai/docs");
4315
4778
  }
4316
4779
  function registerInitCommand(program2, action = init) {
4317
4780
  program2.command("init [project-name]").description(
@@ -4324,6 +4787,7 @@ function registerInitCommand(program2, action = init) {
4324
4787
 
4325
4788
  // src/utils/node-version.ts
4326
4789
  var SUPPORTED_DESCRIPTION = "Node.js 22 (22.12 or newer) and Node.js 24";
4790
+ var SUPPORTED_VERSIONS = "Supported versions are 22.12 or newer, and 24.";
4327
4791
  var SWITCH_HINT = "Install a supported version (for example: nvm install 24), then run the command again.";
4328
4792
  function evaluateNodeVersion(rawVersion) {
4329
4793
  const version = rawVersion.trim().replace(/^v/, "");
@@ -4331,7 +4795,7 @@ function evaluateNodeVersion(rawVersion) {
4331
4795
  if (!Number.isInteger(major) || !Number.isInteger(minor)) {
4332
4796
  return {
4333
4797
  status: "untested",
4334
- message: `Could not read the Node.js version. The Standard Agents CLI supports ${SUPPORTED_DESCRIPTION}.`
4798
+ message: `Could not read the Node.js version. ${SUPPORTED_VERSIONS}`
4335
4799
  };
4336
4800
  }
4337
4801
  if (major === 22 && minor >= 12 || major === 24) {
@@ -4346,14 +4810,21 @@ ${SWITCH_HINT}`
4346
4810
  }
4347
4811
  return {
4348
4812
  status: "untested",
4349
- message: `The Standard Agents CLI supports ${SUPPORTED_DESCRIPTION}. Node.js ${version} is not tested. If a step fails, switch to Node.js 24 (for example: nvm install 24).`
4813
+ message: `Node.js ${version} is untested. ${SUPPORTED_VERSIONS}`
4350
4814
  };
4351
4815
  }
4352
- function assertSupportedNodeVersion(rawVersion = process.versions.node, report = (message) => console.error(message), exit = (code) => process.exit(code)) {
4353
- const check = evaluateNodeVersion(rawVersion);
4816
+ function assertSupportedNodeVersion(options = {}) {
4817
+ const check = evaluateNodeVersion(options.rawVersion ?? process.versions.node);
4354
4818
  if (check.status === "supported" || !check.message) return;
4355
- report(check.message);
4356
- if (check.status === "unsupported") exit(1);
4819
+ if (check.status === "unsupported") {
4820
+ const [cause, ...next] = check.message.split("\n");
4821
+ print("stderr", "error", cause);
4822
+ for (const line of next) print("stderr", "detail", line);
4823
+ (options.exit ?? ((code2) => process.exit(code2)))(1);
4824
+ return;
4825
+ }
4826
+ if (options.deferUntested) deferNotice(check.message);
4827
+ else print("stderr", "warning", check.message);
4357
4828
  }
4358
4829
  function addPlatformEndpointOption(command, description) {
4359
4830
  return command.option("--endpoint <url>", description).addOption(new Option("--api-url <url>", "Alias of --endpoint").hideHelp()).hook("preAction", (thisCommand) => {
@@ -4482,7 +4953,7 @@ function parseStoredCliGitAuth(value) {
4482
4953
  return null;
4483
4954
  }
4484
4955
  const apiKeyId = optionalText(candidate.api_key_id);
4485
- const shared = {
4956
+ const shared2 = {
4486
4957
  endpoint: candidate.endpoint,
4487
4958
  ...apiKeyId ? { api_key_id: apiKeyId } : {},
4488
4959
  account_id: candidate.account_id,
@@ -4494,11 +4965,11 @@ function parseStoredCliGitAuth(value) {
4494
4965
  if (candidate.version === 2) {
4495
4966
  const keychainAccount = optionalText(candidate.keychain_account);
4496
4967
  if (candidate.secret_storage !== "keychain" || !keychainAccount) return null;
4497
- return { version: 2, secret_storage: "keychain", keychain_account: keychainAccount, ...shared };
4968
+ return { version: 2, secret_storage: "keychain", keychain_account: keychainAccount, ...shared2 };
4498
4969
  }
4499
4970
  if (candidate.version !== 1 || typeof candidate.session_cookie !== "string") return null;
4500
4971
  const apiKey = optionalText(candidate.api_key);
4501
- const { endpoint, ...rest } = shared;
4972
+ const { endpoint, ...rest } = shared2;
4502
4973
  return {
4503
4974
  version: 1,
4504
4975
  endpoint,
@@ -4826,9 +5297,9 @@ function authHeaders(session) {
4826
5297
  return session.apiKey !== void 0 ? { Authorization: `Bearer ${session.apiKey}` } : { Cookie: session.cookie };
4827
5298
  }
4828
5299
  var PlatformRequestError = class extends Error {
4829
- constructor(message, status2, endpoint, reason = null, withApiKey = false) {
5300
+ constructor(message, status, endpoint, reason = null, withApiKey = false) {
4830
5301
  super(message);
4831
- this.status = status2;
5302
+ this.status = status;
4832
5303
  this.endpoint = endpoint;
4833
5304
  this.reason = reason;
4834
5305
  this.withApiKey = withApiKey;
@@ -4858,13 +5329,13 @@ function wasReplacedByRetry(build) {
4858
5329
  return build.error_code === LEGAL_ACCEPTANCE_RETRIED;
4859
5330
  }
4860
5331
  function findDevVars(startDir) {
4861
- let current = path19.resolve(startDir);
5332
+ let current2 = path19.resolve(startDir);
4862
5333
  while (true) {
4863
- const candidate = path19.join(current, DEV_VARS_FILENAME);
5334
+ const candidate = path19.join(current2, DEV_VARS_FILENAME);
4864
5335
  if (fs14.existsSync(candidate)) return fs14.readFileSync(candidate, "utf-8");
4865
- const parent = path19.dirname(current);
4866
- if (parent === current) return "";
4867
- current = parent;
5336
+ const parent = path19.dirname(current2);
5337
+ if (parent === current2) return "";
5338
+ current2 = parent;
4868
5339
  }
4869
5340
  }
4870
5341
  function resolvePlatformSession(options = {}) {
@@ -5002,11 +5473,11 @@ function count(value) {
5002
5473
  }
5003
5474
  function parseBuild(value) {
5004
5475
  const id = text(field(value, "id"));
5005
- const status2 = text(field(value, "status"));
5006
- if (!id || !status2) return null;
5476
+ const status = text(field(value, "status"));
5477
+ if (!id || !status) return null;
5007
5478
  return {
5008
5479
  id,
5009
- status: status2,
5480
+ status,
5010
5481
  commit_sha: text(field(value, "commit_sha")) ?? "",
5011
5482
  branch: text(field(value, "branch")) ?? "",
5012
5483
  environment: text(field(value, "environment")) ?? "",
@@ -5213,11 +5684,11 @@ function findProjectDir(cwd) {
5213
5684
  }
5214
5685
  const toplevel = gitOutput(start, ["rev-parse", "--show-toplevel"]);
5215
5686
  const root = toplevel ? path19.resolve(toplevel) : null;
5216
- for (let current = start; ; current = path19.dirname(current)) {
5217
- if (fs14.existsSync(path19.join(current, DEV_VARS_FILENAME)) || isStandardAgentsProjectDir(current)) {
5218
- return current;
5687
+ for (let current2 = start; ; current2 = path19.dirname(current2)) {
5688
+ if (fs14.existsSync(path19.join(current2, DEV_VARS_FILENAME)) || isStandardAgentsProjectDir(current2)) {
5689
+ return current2;
5219
5690
  }
5220
- if (!root || current === root || path19.dirname(current) === current) break;
5691
+ if (!root || current2 === root || path19.dirname(current2) === current2) break;
5221
5692
  }
5222
5693
  return root && standardAgentsRemote(root) ? root : null;
5223
5694
  }
@@ -5311,8 +5782,8 @@ async function resolveAccountApiKey(endpoint, state, previous, fetchImpl) {
5311
5782
  async function performLogin(options = {}) {
5312
5783
  const endpoint = resolvePlatformEndpoint(options.endpoint);
5313
5784
  const fetchImpl = options.fetchImpl ?? fetch;
5314
- const code = await resolveSetupCode(options) || await signInThroughBrowser({ endpoint, command: LOGIN_COMMAND, open: options.open });
5315
- const consumed = await exchangeBootstrapCode(endpoint, code, fetchImpl);
5785
+ const code2 = await resolveSetupCode(options) || await signInThroughBrowser({ endpoint, command: LOGIN_COMMAND, open: options.open });
5786
+ const consumed = await exchangeBootstrapCode(endpoint, code2, fetchImpl);
5316
5787
  const store = options.secretStore === void 0 ? systemSecretStore() : options.secretStore;
5317
5788
  const accessKey = await resolveAccountApiKey(endpoint, consumed, lookupCliGitAuth(store), fetchImpl);
5318
5789
  const record = saveCliGitAuth({
@@ -5336,84 +5807,112 @@ async function performLogin(options = {}) {
5336
5807
  const project = projectDir ? await signInProject(projectDir, endpoint, consumed.session_cookie, consumed.project?.id, fetchImpl) : null;
5337
5808
  return { record, keyReused: accessKey?.reused === true, store, helper, ...helperError ? { helperError } : {}, project };
5338
5809
  }
5339
- function reportProject(project) {
5810
+ function projectRow(project) {
5340
5811
  const devVars = path19.join(path19.relative(process.cwd(), project.dir), DEV_VARS_FILENAME);
5341
5812
  if (project.status === "key_saved") {
5342
- logger.log(`Project: saved a project API key in ${devVars}. Local sign-in uses your Standard Agents account.`);
5343
- return;
5813
+ return ["Project", `saved a project API key in ${devVars}. Local sign-in uses your Standard Agents account.`];
5344
5814
  }
5345
5815
  if (project.status === "has_key") {
5346
- logger.log(`Project: ${devVars} holds a project API key. It was kept.`);
5347
- return;
5816
+ return ["Project", `${devVars} holds a project API key. It was kept.`];
5348
5817
  }
5818
+ return null;
5819
+ }
5820
+ function warnAboutProject(project) {
5821
+ const devVars = path19.join(path19.relative(process.cwd(), project.dir), DEV_VARS_FILENAME);
5349
5822
  const [headline, ...detail] = (project.reason ?? "").split("\n");
5350
5823
  logger.warning(`No project API key was saved in ${devVars}. ${headline}`);
5351
5824
  for (const line of detail) logger.detail(line);
5352
5825
  if (project.generatedAdminPassword) {
5353
5826
  logger.warning("This project used a default admin password. It now has a random one.");
5354
- logger.log(`Local sign-in: username \`admin\` with the \`SUPER_ADMIN_PASSWORD\` value in ${devVars}.`);
5355
- logger.log("The password is saved there and is not printed here.");
5827
+ logger.detail(`Local sign-in: username \`admin\` with the \`SUPER_ADMIN_PASSWORD\` value in ${devVars}.`);
5828
+ logger.detail("The password is saved there and is not printed here.");
5356
5829
  }
5357
5830
  }
5358
- function reportLogin(result) {
5359
- const { record, keyReused, store, helper, helperError, project } = result;
5360
- logger.log("");
5361
- logger.success("Signed in to Standard Agents.");
5362
- logger.log(`User: ${record.user_email}`);
5363
- logger.log(`Account: ${record.account_id}${record.account_slug ? ` (${record.account_slug})` : ""}`);
5364
- logger.log(`Platform: ${displayEndpoint(record.endpoint)}`);
5831
+ function loginRows(result) {
5832
+ const { record, keyReused, store, helper, project } = result;
5833
+ const rows = [
5834
+ ["User", record.user_email],
5835
+ ["Account", `${record.account_id}${record.account_slug ? ` (${record.account_slug})` : ""}`],
5836
+ ["Platform", displayEndpoint(record.endpoint)]
5837
+ ];
5365
5838
  if (record.api_key) {
5366
- logger.log(
5367
- `Credential: long-lived API key${keyReused ? ", kept from the previous sign-in on this machine" : ""}. Sign out with: ${cliCommand("logout")}`
5368
- );
5369
- } else {
5370
- logger.warning(`The platform issued no long-lived API key, so this sign-in ends with the browser session in a few days. Then run: ${LOGIN_COMMAND}`);
5371
- }
5372
- if (record.secret_storage === "keychain") {
5373
- logger.log(`Stored in: ${store?.label ?? "the credential store"}`);
5374
- } else {
5375
- logger.log(`Stored in: ${cliAuthStatePath()} (readable only by your user)`);
5376
- if (store && !plaintextStoreRequested()) {
5377
- logger.warning(
5378
- `The ${store.label} is not available in this session (it is locked, for example over SSH), so the file holds the sign-in. To move it, run from a desktop session: ${LOGIN_COMMAND}`
5379
- );
5380
- logger.detail(`Set ${CREDENTIAL_STORE_ENV}=file to choose the file.`);
5381
- }
5839
+ rows.push([
5840
+ "Credential",
5841
+ `long-lived API key${keyReused ? ", kept from the previous sign-in on this machine" : ""}. Sign out with: ${cliCommand("logout")}`
5842
+ ]);
5382
5843
  }
5844
+ rows.push([
5845
+ "Stored in",
5846
+ record.secret_storage === "keychain" ? store?.label ?? "the credential store" : `${cliAuthStatePath()} (readable only by your user)`
5847
+ ]);
5383
5848
  if (helper) {
5384
- logger.log(`Git credential helper: ${helper.helperCommand}${helper.helperAdded ? "" : " (already installed)"}`);
5849
+ rows.push(["Git credential helper", `${helper.helperCommand}${helper.helperAdded ? "" : " (already installed)"}`]);
5385
5850
  if (helper.globalUseHttpPath === "removed") {
5386
- logger.log(
5387
- "Git configuration: removed the global credential.useHttpPath that an earlier release set. It now applies to the Standard Agents Git hosts only."
5388
- );
5851
+ rows.push([
5852
+ "Git configuration",
5853
+ "removed the global credential.useHttpPath that an earlier release set. It now applies to the Standard Agents Git hosts only."
5854
+ ]);
5389
5855
  } else if (helper.globalUseHttpPath === "kept") {
5390
- logger.log(
5391
- "Git configuration: your global credential.useHttpPath was left as it is. Earlier releases set it for every host; if you did not set it yourself, remove it with: git config --global --unset-all credential.useHttpPath"
5392
- );
5856
+ rows.push([
5857
+ "Git configuration",
5858
+ "your global credential.useHttpPath was left as it is. Earlier releases set it for every host; if you did not set it yourself, remove it with: git config --global --unset-all credential.useHttpPath"
5859
+ ]);
5393
5860
  }
5394
- } else if (helperError) {
5861
+ }
5862
+ const projectSummary = project ? projectRow(project) : null;
5863
+ if (projectSummary) rows.push(projectSummary);
5864
+ return rows;
5865
+ }
5866
+ function printLoginWarnings(result) {
5867
+ const { record, store, helper, helperError, project } = result;
5868
+ if (!record.api_key) {
5869
+ logger.warning(`The platform issued no long-lived API key, so this sign-in ends with the browser session in a few days. Then run: ${LOGIN_COMMAND}`);
5870
+ }
5871
+ if (record.secret_storage !== "keychain" && store && !plaintextStoreRequested()) {
5872
+ logger.warning(
5873
+ `The ${store.label} is not available in this session (it is locked, for example over SSH), so the file holds the sign-in. To move it, run from a desktop session: ${LOGIN_COMMAND}`
5874
+ );
5875
+ logger.detail(`Set ${CREDENTIAL_STORE_ENV}=file to choose the file.`);
5876
+ }
5877
+ if (!helper && helperError) {
5395
5878
  logger.warning(`Global Git config was not updated: ${helperError}`);
5396
5879
  logger.detail(`Correct the cause, then run: ${LOGIN_COMMAND}`);
5397
5880
  }
5398
- if (project) reportProject(project);
5881
+ if (project && !projectRow(project)) warnAboutProject(project);
5882
+ }
5883
+ function reportLogin(result) {
5884
+ const terminal = isTerminal(statusTarget());
5885
+ if (!terminal) logger.log("");
5886
+ logger.success("Signed in to Standard Agents.");
5887
+ if (terminal) logger.log("");
5888
+ printKeyValues(loginRows(result));
5889
+ printLoginWarnings(result);
5399
5890
  logger.log("");
5400
5891
  }
5401
- function failLogin(error) {
5402
- const [headline, ...detail] = (error instanceof Error ? error.message : String(error)).split("\n");
5403
- logger.error(headline);
5404
- for (const line of detail) {
5405
- logger.detail(line);
5406
- }
5892
+ async function confirmLogin(result) {
5893
+ const { record } = result;
5894
+ const account = record.account_slug ? ` (${record.account_slug})` : "";
5895
+ logger.success(`Signed in to Standard Agents as ${record.user_email}${account}.`);
5896
+ printLoginWarnings(result);
5897
+ await flowReporter().confirm({ title: "Signed in to Standard Agents", rows: loginRows(result) });
5898
+ }
5899
+ async function failLogin(error) {
5900
+ await flowReporter().failure({ cause: error instanceof Error ? error.message : String(error), next: [] });
5407
5901
  process.exit(1);
5408
5902
  }
5409
5903
  async function login(options = {}) {
5410
5904
  try {
5411
- logger.log("");
5412
- logger.info("Signing in to Standard Agents...");
5413
- logger.log(`Platform: ${displayEndpoint(resolvePlatformEndpoint(options.endpoint))}`);
5414
- reportLogin(await performLogin(options));
5905
+ flowReporter().header();
5906
+ if (!isTerminal(statusTarget())) {
5907
+ logger.log("");
5908
+ logger.info("Signing in to Standard Agents...");
5909
+ logger.log(`Platform: ${displayEndpoint(resolvePlatformEndpoint(options.endpoint))}`);
5910
+ }
5911
+ const result = await performLogin(options);
5912
+ if (flowReporter().fullScreen) await confirmLogin(result);
5913
+ else reportLogin(result);
5415
5914
  } catch (error) {
5416
- failLogin(error);
5915
+ await failLogin(error);
5417
5916
  }
5418
5917
  }
5419
5918
 
@@ -5447,14 +5946,16 @@ async function whoami(options = {}) {
5447
5946
  `);
5448
5947
  return;
5449
5948
  }
5450
- logger.log(`User: ${record.user_email}`);
5451
- logger.log(`Account: ${record.account_id}${record.account_slug ? ` (${record.account_slug})` : ""}`);
5452
- logger.log(`Platform: ${displayEndpoint(record.endpoint)}`);
5453
- if (credential === "unreadable") {
5454
- logger.warning(SIGN_IN_UNREADABLE_MESSAGE);
5455
- return;
5949
+ const rows = [
5950
+ ["User", record.user_email],
5951
+ ["Account", `${record.account_id}${record.account_slug ? ` (${record.account_slug})` : ""}`],
5952
+ ["Platform", displayEndpoint(record.endpoint)]
5953
+ ];
5954
+ if (credential !== "unreadable") {
5955
+ rows.push(["Credential", credential === "api_key" ? "long-lived API key" : "browser session. It ends in a few days."]);
5456
5956
  }
5457
- logger.log(credential === "api_key" ? "Credential: long-lived API key" : "Credential: browser session. It ends in a few days.");
5957
+ printKeyValues(rows, { indent: false });
5958
+ if (credential === "unreadable") logger.warning(SIGN_IN_UNREADABLE_MESSAGE);
5458
5959
  }
5459
5960
 
5460
5961
  // src/commands/login-command.ts
@@ -5572,13 +6073,13 @@ function parseCredentialRequest(input) {
5572
6073
  return result;
5573
6074
  }
5574
6075
  function findDotDevVars(startDir = process.cwd()) {
5575
- let current = path19.resolve(startDir);
6076
+ let current2 = path19.resolve(startDir);
5576
6077
  while (true) {
5577
- const candidate = path19.join(current, DEV_VARS_FILENAME);
6078
+ const candidate = path19.join(current2, DEV_VARS_FILENAME);
5578
6079
  if (fs14.existsSync(candidate)) return candidate;
5579
- const parent = path19.dirname(current);
5580
- if (parent === current) return null;
5581
- current = parent;
6080
+ const parent = path19.dirname(current2);
6081
+ if (parent === current2) return null;
6082
+ current2 = parent;
5582
6083
  }
5583
6084
  }
5584
6085
  var PROJECT_API_KEY = "STANDARD_AGENTS_API_KEY";
@@ -5958,9 +6459,9 @@ function runChatDevServer(packageManager, projectPath, options) {
5958
6459
  if (interrupts.isInterrupted()) return;
5959
6460
  finish();
5960
6461
  };
5961
- child.on("close", (code, signal) => {
5962
- const report = () => settle(() => resolve(code));
5963
- const diedFromInterrupt = signal === "SIGINT" || signal === "SIGTERM" || code !== null && INTERRUPT_EXIT_CODES2.has(code);
6462
+ child.on("close", (code2, signal) => {
6463
+ const report = () => settle(() => resolve(code2));
6464
+ const diedFromInterrupt = signal === "SIGINT" || signal === "SIGTERM" || code2 !== null && INTERRUPT_EXIT_CODES2.has(code2);
5964
6465
  if (diedFromInterrupt && !interrupts.isInterrupted()) {
5965
6466
  setTimeout(report, INTERRUPT_SETTLE_MS2);
5966
6467
  return;
@@ -6624,10 +7125,10 @@ function registerInitChatCommand(program2, action = initChat) {
6624
7125
  var BUILDER = "@standardagents/builder";
6625
7126
  var PACKING_ENTRY = `${BUILDER}/packing`;
6626
7127
  var PackingUnavailableError = class extends Error {
6627
- constructor(message, hint, code = "packing_unavailable") {
7128
+ constructor(message, hint, code2 = "packing_unavailable") {
6628
7129
  super(message);
6629
7130
  this.hint = hint;
6630
- this.code = code;
7131
+ this.code = code2;
6631
7132
  this.name = "PackingUnavailableError";
6632
7133
  }
6633
7134
  };
@@ -6811,7 +7312,7 @@ async function selectItemModes(items, _agentName) {
6811
7312
  lines.push("");
6812
7313
  return lines;
6813
7314
  };
6814
- const render3 = (initial = false) => {
7315
+ const render4 = (initial = false) => {
6815
7316
  const lines = getDisplayLines();
6816
7317
  if (!initial) {
6817
7318
  stdout.write("\x1B[?25l");
@@ -6820,7 +7321,7 @@ async function selectItemModes(items, _agentName) {
6820
7321
  }
6821
7322
  stdout.write(lines.join("\n") + "\n");
6822
7323
  };
6823
- render3(true);
7324
+ render4(true);
6824
7325
  const wasRaw = stdin.isRaw;
6825
7326
  if (stdin.isTTY) {
6826
7327
  stdin.setRawMode(true);
@@ -6836,13 +7337,13 @@ async function selectItemModes(items, _agentName) {
6836
7337
  const onData = (key) => {
6837
7338
  if (key === "\x1B[A" || key === "k") {
6838
7339
  selectedIndex = (selectedIndex - 1 + items.length) % items.length;
6839
- render3();
7340
+ render4();
6840
7341
  } else if (key === "\x1B[B" || key === "j") {
6841
7342
  selectedIndex = (selectedIndex + 1) % items.length;
6842
- render3();
7343
+ render4();
6843
7344
  } else if (key === " ") {
6844
7345
  items[selectedIndex].mode = items[selectedIndex].mode === "extract" ? "copy" : "extract";
6845
- render3();
7346
+ render4();
6846
7347
  } else if (key === "\r" || key === "\n") {
6847
7348
  cleanup();
6848
7349
  resolve(items);
@@ -6856,7 +7357,8 @@ async function selectItemModes(items, _agentName) {
6856
7357
  });
6857
7358
  }
6858
7359
  async function pack(agentName, options) {
6859
- logger.info("Packing agent...\n");
7360
+ logger.info("Packing agent...");
7361
+ logger.log("");
6860
7362
  const rootDir = process.cwd();
6861
7363
  const { PackingService } = await loadProjectPackingOrExit(rootDir);
6862
7364
  const packingService = new PackingService();
@@ -6871,9 +7373,9 @@ async function pack(agentName, options) {
6871
7373
  agentName = agents[0];
6872
7374
  logger.info(`Found one agent: ${agentName}`);
6873
7375
  } else if (canPrompt) {
6874
- console.log("");
7376
+ logger.log("");
6875
7377
  agentName = await selectAgent(agents);
6876
- console.log("");
7378
+ logger.log("");
6877
7379
  } else {
6878
7380
  logger.error(
6879
7381
  options.interactive === false ? "This project has several agents, and --no-interactive cannot ask which one to pack." : "This project has several agents, and there is no terminal to ask which one to pack."
@@ -6881,7 +7383,7 @@ async function pack(agentName, options) {
6881
7383
  logger.info(`Name the agent: ${cliCommand("pack <agent-name>")}`);
6882
7384
  logger.info("Agents in this project:");
6883
7385
  for (const agent of agents) {
6884
- console.log(` - ${agent}`);
7386
+ logger.log(` - ${agent}`);
6885
7387
  }
6886
7388
  process.exit(1);
6887
7389
  }
@@ -6896,15 +7398,15 @@ async function pack(agentName, options) {
6896
7398
  }
6897
7399
  process.exit(1);
6898
7400
  }
6899
- console.log("");
7401
+ logger.log("");
6900
7402
  logger.info("Discovered constituents:");
6901
- console.log(` Agents: ${analysis.constituents.agents.map((a) => a.name).join(", ") || "(none)"}`);
6902
- console.log(` Prompts: ${analysis.constituents.prompts.map((p) => p.name).join(", ") || "(none)"}`);
6903
- console.log(` Tools: ${analysis.constituents.tools.map((t) => t.name).join(", ") || "(none)"}`);
6904
- console.log(` Models: ${analysis.constituents.models.map((m) => m.name).join(", ") || "(none)"}`);
6905
- console.log(` Hooks: ${analysis.constituents.hooks.map((h) => h.name).join(", ") || "(none)"}`);
7403
+ logger.log(` Agents: ${analysis.constituents.agents.map((a) => a.name).join(", ") || "(none)"}`);
7404
+ logger.log(` Prompts: ${analysis.constituents.prompts.map((p) => p.name).join(", ") || "(none)"}`);
7405
+ logger.log(` Tools: ${analysis.constituents.tools.map((t) => t.name).join(", ") || "(none)"}`);
7406
+ logger.log(` Models: ${analysis.constituents.models.map((m) => m.name).join(", ") || "(none)"}`);
7407
+ logger.log(` Hooks: ${analysis.constituents.hooks.map((h) => h.name).join(", ") || "(none)"}`);
6906
7408
  if (analysis.warnings.length > 0) {
6907
- console.log("");
7409
+ logger.log("");
6908
7410
  logger.warning("Warnings:");
6909
7411
  for (const warning of analysis.warnings) {
6910
7412
  logger.detail(` - ${warning}`);
@@ -6973,7 +7475,7 @@ async function pack(agentName, options) {
6973
7475
  }
6974
7476
  let itemSelections;
6975
7477
  if (canPrompt && selectionItems.length > 0) {
6976
- console.log("");
7478
+ logger.log("");
6977
7479
  const selections = await selectItemModes(selectionItems);
6978
7480
  itemSelections = selections.map((s) => ({
6979
7481
  name: s.name,
@@ -6981,10 +7483,10 @@ async function pack(agentName, options) {
6981
7483
  filePath: s.filePath,
6982
7484
  mode: options.remove === false ? "copy" : s.mode
6983
7485
  }));
6984
- console.log("");
7486
+ logger.log("");
6985
7487
  }
6986
7488
  const removed = itemSelections ? itemSelections.filter((item) => item.mode === "extract") : options.remove === false ? [] : selectionItems.filter((item) => item.mode === "extract");
6987
- console.log("");
7489
+ logger.log("");
6988
7490
  if (removed.length > 0) {
6989
7491
  logger.warning("Packing removes these original files from the project. The package keeps a copy of each. Pass --no-remove to keep them:");
6990
7492
  for (const item of removed) {
@@ -7010,26 +7512,26 @@ async function pack(agentName, options) {
7010
7512
  logger.error(`Packing failed: ${result.error}`);
7011
7513
  process.exit(1);
7012
7514
  }
7013
- console.log("");
7014
- logger.success("Packing complete!");
7015
- console.log(` Package ID: ${result.packageId}`);
7016
- console.log(` Output: ${result.outputPath}`);
7017
- console.log(` Files: ${result.filesCreated.length} created`);
7515
+ logger.log("");
7516
+ logger.success("Packing complete.");
7517
+ logger.log(` Package ID: ${result.packageId}`);
7518
+ logger.log(` Output: ${result.outputPath}`);
7519
+ logger.log(` Files: ${result.filesCreated.length} created`);
7018
7520
  if (result.filesRemoved && result.filesRemoved.length > 0) {
7019
- console.log(` Removed: ${result.filesRemoved.length} original files`);
7521
+ logger.log(` Removed: ${result.filesRemoved.length} original files`);
7020
7522
  }
7021
7523
  if (result.warnings.length > 0) {
7022
- console.log("");
7524
+ logger.log("");
7023
7525
  logger.warning("Warnings:");
7024
7526
  for (const warning of result.warnings) {
7025
7527
  logger.detail(` - ${warning}`);
7026
7528
  }
7027
7529
  }
7028
7530
  if (options.npm) {
7029
- console.log("");
7531
+ logger.log("");
7030
7532
  logger.info("NPM package structure created. To publish:");
7031
- console.log(` cd ${result.outputPath}`);
7032
- console.log(" npm publish");
7533
+ logger.log(` cd ${result.outputPath}`);
7534
+ logger.log(" npm publish");
7033
7535
  }
7034
7536
  }
7035
7537
  function registerPackCommand(program2) {
@@ -7350,23 +7852,26 @@ async function loadBuild(context, ref) {
7350
7852
  }
7351
7853
  }
7352
7854
  function printBuild(build) {
7353
- logger.log(`Build: ${build.id}`);
7354
- logger.log(`Status: ${build.status}`);
7355
- logger.log(`Commit: ${build.commit_sha} (${build.branch})`);
7356
- logger.log(`Environment: ${build.environment}`);
7357
- logger.log(`Created: ${timestamp(build.created_at)}`);
7358
- if (build.started_at) logger.log(`Started: ${timestamp(build.started_at)}`);
7359
- if (build.completed_at) logger.log(`Completed: ${timestamp(build.completed_at)}`);
7360
- if (wasReplacedByRetry(build)) logger.log("Note: replaced by a retry after the terms were accepted");
7361
- else if (build.error_code) logger.log(`Error code: ${build.error_code}`);
7362
- if (build.error_message) logger.log(`Error: ${build.error_message}`);
7855
+ const rows = [
7856
+ ["Build", build.id],
7857
+ ["Status", build.status],
7858
+ ["Commit", `${build.commit_sha} (${build.branch})`],
7859
+ ["Environment", build.environment],
7860
+ ["Created", timestamp(build.created_at)]
7861
+ ];
7862
+ if (build.started_at) rows.push(["Started", timestamp(build.started_at)]);
7863
+ if (build.completed_at) rows.push(["Completed", timestamp(build.completed_at)]);
7864
+ if (wasReplacedByRetry(build)) rows.push(["Note", "replaced by a retry after the terms were accepted"]);
7865
+ else if (build.error_code) rows.push(["Error code", build.error_code]);
7866
+ if (build.error_message) rows.push(["Error", build.error_message]);
7867
+ printKeyValues(rows, { plain: "aligned", indent: false });
7363
7868
  }
7364
7869
  async function buildsList(options) {
7365
7870
  const context = await loadContext(options);
7366
7871
  const limit = Math.min(Math.max(Number.parseInt(options.limit ?? "", 10) || 10, 1), BUILDS_PAGE_SIZE);
7367
7872
  const { builds } = await readBuildsPage(context.session, context.projectId, { limit });
7368
7873
  if (options.json) {
7369
- logger.log(JSON.stringify({ project_id: context.projectId, builds }, null, 2));
7874
+ console.log(JSON.stringify({ project_id: context.projectId, builds }, null, 2));
7370
7875
  return 0;
7371
7876
  }
7372
7877
  if (builds.length === 0) {
@@ -7424,7 +7929,7 @@ async function buildsStatus(buildRef, options) {
7424
7929
  if (options.wait && isSettledBuild(build) && !isDeployedBuild(build) && !wasReplacedByRetry(build)) exitCode = EXIT.FAILED;
7425
7930
  if (needsLegalAcceptance(build)) exitCode = EXIT.TERMS_REQUIRED;
7426
7931
  if (options.json) {
7427
- logger.log(JSON.stringify({
7932
+ console.log(JSON.stringify({
7428
7933
  project_id: context.projectId,
7429
7934
  build,
7430
7935
  ...waitNote ? { wait_error: waitNote } : {},
@@ -7454,9 +7959,9 @@ function followBuildLog(context, buildId, write) {
7454
7959
  if ((type === "snapshot" || type === "chunk") && typeof chunk === "string") {
7455
7960
  write(chunk);
7456
7961
  } else if (type === "complete") {
7457
- const status2 = frameField(frame, "status");
7962
+ const status = frameField(frame, "status");
7458
7963
  socket.close();
7459
- resolve(typeof status2 === "string" ? status2 : "unknown");
7964
+ resolve(typeof status === "string" ? status : "unknown");
7460
7965
  }
7461
7966
  },
7462
7967
  onDown: () => resolve(null)
@@ -7468,26 +7973,26 @@ async function buildsLogs(ref, options) {
7468
7973
  const build = await loadBuild(context, ref);
7469
7974
  if (options.follow && options.json && !isSettledBuild(build)) {
7470
7975
  let log = "";
7471
- const status2 = await followBuildLog(context, build.id, (chunk) => {
7976
+ const status = await followBuildLog(context, build.id, (chunk) => {
7472
7977
  log += chunk;
7473
7978
  process.stderr.write(chunk);
7474
7979
  });
7475
- const finished = status2 === null ? build : await loadBuild(context, build.id);
7476
- const result = isSettledBuild(finished) ? finished.status : status2;
7980
+ const finished = status === null ? build : await loadBuild(context, build.id);
7981
+ const result = isSettledBuild(finished) ? finished.status : status;
7477
7982
  const exitCode2 = needsLegalAcceptance(finished) ? EXIT.TERMS_REQUIRED : result === "live" || result === "superseded" ? EXIT.OK : EXIT.FAILED;
7478
- logger.log(JSON.stringify({
7983
+ console.log(JSON.stringify({
7479
7984
  project_id: context.projectId,
7480
7985
  build: finished,
7481
7986
  log,
7482
- ...status2 === null ? { wait_error: `The live log stream for build ${build.id} closed before the build finished.` } : {},
7987
+ ...status === null ? { wait_error: `The live log stream for build ${build.id} closed before the build finished.` } : {},
7483
7988
  exit_code: exitCode2
7484
7989
  }, null, 2));
7485
7990
  return exitCode2;
7486
7991
  }
7487
7992
  if (options.follow && !isSettledBuild(build)) {
7488
- const status2 = await followBuildLog(context, build.id, (chunk) => process.stdout.write(chunk));
7993
+ const status = await followBuildLog(context, build.id, (chunk) => process.stdout.write(chunk));
7489
7994
  process.stdout.write("\n");
7490
- if (status2 === null) {
7995
+ if (status === null) {
7491
7996
  logger.warning(`The live log stream for build ${build.id} closed before the build finished.`);
7492
7997
  logger.info(`Read its status with: ${cliCommand(`builds status ${build.id}`)}`);
7493
7998
  return EXIT.FAILED;
@@ -7496,13 +8001,13 @@ async function buildsLogs(ref, options) {
7496
8001
  if (isSettledBuild(finished)) {
7497
8002
  return reportSettledBuild(finished, context.project?.production_hostname ?? null);
7498
8003
  }
7499
- logger.info(`The build log ended with status ${status2}. Read the result with: ${cliCommand(`builds status ${build.id}`)}`);
7500
- return status2 === "failed" || status2 === "cancelled" ? EXIT.FAILED : EXIT.OK;
8004
+ logger.info(`The build log ended with status ${status}. Read the result with: ${cliCommand(`builds status ${build.id}`)}`);
8005
+ return status === "failed" || status === "cancelled" ? EXIT.FAILED : EXIT.OK;
7501
8006
  }
7502
8007
  const transcript = await readBuildLog(context.session, context.projectId, build.id);
7503
8008
  const exitCode = needsLegalAcceptance(transcript) ? EXIT.TERMS_REQUIRED : EXIT.OK;
7504
8009
  if (options.json) {
7505
- logger.log(JSON.stringify({ project_id: context.projectId, build, log: transcript.log, exit_code: exitCode }, null, 2));
8010
+ console.log(JSON.stringify({ project_id: context.projectId, build, log: transcript.log, exit_code: exitCode }, null, 2));
7506
8011
  if (exitCode === EXIT.TERMS_REQUIRED) console.error(TERMS_ACCEPT_FIX);
7507
8012
  return exitCode;
7508
8013
  }
@@ -7527,24 +8032,24 @@ async function printFailureLogTail(context, build) {
7527
8032
  const transcript = await readBuildLog(context.session, context.projectId, build.id).catch(() => null);
7528
8033
  const lines = transcript?.log?.trimEnd().split(/\r?\n/) ?? [];
7529
8034
  if (lines.length === 0) return;
7530
- console.error(`Last ${Math.min(lines.length, FAILURE_LOG_TAIL_LINES)} log lines of build ${build.id}:`);
7531
- for (const line of lines.slice(-FAILURE_LOG_TAIL_LINES)) console.error(` ${line}`);
8035
+ logger.detail(`Last ${Math.min(lines.length, FAILURE_LOG_TAIL_LINES)} log lines of build ${build.id}:`);
8036
+ for (const line of lines.slice(-FAILURE_LOG_TAIL_LINES)) logger.detail(` ${line}`);
7532
8037
  }
7533
8038
  async function reportStartedBuild(context, options, started, timeoutMs) {
7534
8039
  const label = started.action.charAt(0).toUpperCase() + started.action.slice(1);
7535
- const say = options.json ? (line) => console.error(line) : (line) => logger.info(line);
8040
+ const say2 = options.json ? (line) => console.error(line) : (line) => logger.info(line);
7536
8041
  let build = null;
7537
- let status2 = started.status;
7538
- let exitCode = status2 === "failed" ? EXIT.FAILED : EXIT.OK;
8042
+ let status = started.status;
8043
+ let exitCode = status === "failed" ? EXIT.FAILED : EXIT.OK;
7539
8044
  let waitNote = null;
7540
- if (status2 === "failed") {
7541
- say(`The platform could not start the ${started.action} of build ${started.fromBuildId}.`);
7542
- say(`Read why with: ${cliCommand(`builds status ${started.buildId ?? started.fromBuildId}`)}`);
8045
+ if (status === "failed") {
8046
+ say2(`The platform could not start the ${started.action} of build ${started.fromBuildId}.`);
8047
+ say2(`Read why with: ${cliCommand(`builds status ${started.buildId ?? started.fromBuildId}`)}`);
7543
8048
  } else {
7544
- say(`${label} of build ${started.fromBuildId} started${started.buildId ? ` as build ${started.buildId}` : ""} (${status2 ?? "unknown"}).`);
8049
+ say2(`${label} of build ${started.fromBuildId} started${started.buildId ? ` as build ${started.buildId}` : ""} (${status ?? "unknown"}).`);
7545
8050
  }
7546
- if (options.wait && started.buildId && status2 !== "failed" && status2 !== "live") {
7547
- say("Waiting for it to finish (Ctrl-C stops waiting; the build continues).");
8051
+ if (options.wait && started.buildId && status !== "failed" && status !== "live") {
8052
+ say2("Waiting for it to finish (Ctrl-C stops waiting; the build continues).");
7548
8053
  const outcome = await followBuild({
7549
8054
  session: context.session,
7550
8055
  projectId: context.projectId,
@@ -7553,7 +8058,7 @@ async function reportStartedBuild(context, options, started, timeoutMs) {
7553
8058
  noBuildGraceMs: 0
7554
8059
  });
7555
8060
  build = outcome.build;
7556
- status2 = build?.status ?? status2;
8061
+ status = build?.status ?? status;
7557
8062
  if (outcome.kind === "settled") {
7558
8063
  if (options.json) {
7559
8064
  exitCode = needsLegalAcceptance(outcome.build) ? EXIT.TERMS_REQUIRED : isDeployedBuild(outcome.build) ? EXIT.OK : EXIT.FAILED;
@@ -7563,7 +8068,7 @@ async function reportStartedBuild(context, options, started, timeoutMs) {
7563
8068
  if (exitCode === EXIT.FAILED) await printFailureLogTail(context, outcome.build);
7564
8069
  } else if (outcome.kind === "timeout") {
7565
8070
  exitCode = EXIT.TIMED_OUT;
7566
- waitNote = `Stopped waiting after ${timeoutMs / 1e3}s; build ${started.buildId} is still ${status2 ?? "in progress"}.`;
8071
+ waitNote = `Stopped waiting after ${timeoutMs / 1e3}s; build ${started.buildId} is still ${status ?? "in progress"}.`;
7567
8072
  } else if (outcome.kind === "no-build") {
7568
8073
  exitCode = EXIT.FAILED;
7569
8074
  waitNote = `Stopped waiting: build ${started.buildId} can no longer be found, so its deployment was not verified.`;
@@ -7572,16 +8077,16 @@ async function reportStartedBuild(context, options, started, timeoutMs) {
7572
8077
  waitNote = `Stopped waiting: ${outcome.reason} ${outcome.fix}`;
7573
8078
  }
7574
8079
  if (waitNote) console.error(waitNote);
7575
- } else if (!options.json && started.buildId && status2 !== "failed" && status2 !== "live") {
8080
+ } else if (!options.json && started.buildId && status !== "failed" && status !== "live") {
7576
8081
  logger.info(`Follow it with: ${cliCommand(`builds status ${started.buildId} --wait`)}`);
7577
8082
  }
7578
8083
  if (options.json) {
7579
- logger.log(JSON.stringify({
8084
+ console.log(JSON.stringify({
7580
8085
  project_id: context.projectId,
7581
8086
  action: started.action,
7582
8087
  from_build_id: started.fromBuildId,
7583
8088
  build_id: started.buildId,
7584
- status: status2,
8089
+ status,
7585
8090
  ...build ? { build } : {},
7586
8091
  ...waitNote ? { wait_error: waitNote } : {},
7587
8092
  exit_code: exitCode
@@ -7607,7 +8112,7 @@ async function buildsRetry(ref, options, dependencies = {}) {
7607
8112
  if (!newest || newest.status !== "failed") {
7608
8113
  const state = newest ? `The newest build of branch ${branch} (${newest.id}) is ${newest.status}.` : `This project has no build of branch ${branch}.`;
7609
8114
  if (options.json) {
7610
- logger.log(JSON.stringify({
8115
+ console.log(JSON.stringify({
7611
8116
  project_id: context.projectId,
7612
8117
  action: "retry",
7613
8118
  branch,
@@ -7637,10 +8142,10 @@ async function buildsRetry(ref, options, dependencies = {}) {
7637
8142
  const retried = await startBuildAction(context.session, context.projectId, build.id, "retry");
7638
8143
  return reportStartedBuild(context, options, { action: "retry", fromBuildId: build.id, ...retried }, timeoutMs);
7639
8144
  }
7640
- async function newestProductionBuild(context, status2) {
8145
+ async function newestProductionBuild(context, status) {
7641
8146
  let page = await readBuildsPage(context.session, context.projectId);
7642
8147
  while (true) {
7643
- const match = page.builds.find((build) => build.environment === "production" && build.status === status2);
8148
+ const match = page.builds.find((build) => build.environment === "production" && build.status === status);
7644
8149
  if (match) return match;
7645
8150
  if (!page.next) return null;
7646
8151
  page = await readBuildsPage(context.session, context.projectId, { before: page.next });
@@ -7675,8 +8180,8 @@ async function rollback(ref, options, dependencies = {}) {
7675
8180
  );
7676
8181
  }
7677
8182
  if (!options.yes) {
7678
- const isTerminal = dependencies.isTerminal ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
7679
- if (!isTerminal) {
8183
+ const isTerminal2 = dependencies.isTerminal ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
8184
+ if (!isTerminal2) {
7680
8185
  throw new BuildAccessError(
7681
8186
  "Rollback changes production, and no terminal is attached to confirm it.",
7682
8187
  `Run it again with --yes: ${cliCommand(`rollback ${target.id} --yes`)}`,
@@ -7722,12 +8227,12 @@ async function runBuildsAction(action, options = {}) {
7722
8227
  } catch (error) {
7723
8228
  const failure = describeBuildAccessFailure(error);
7724
8229
  if (options.json) {
7725
- logger.log(JSON.stringify({
8230
+ console.log(JSON.stringify({
7726
8231
  error: { message: failure.message, fix: failure.fix, exit_code: failure.exitCode }
7727
8232
  }, null, 2));
7728
8233
  }
7729
- console.error(`\u2717 ${failure.message}`);
7730
- console.error(failure.fix);
8234
+ logger.error(failure.message);
8235
+ logger.detail(failure.fix);
7731
8236
  process.exitCode = failure.exitCode;
7732
8237
  }
7733
8238
  }
@@ -7830,39 +8335,39 @@ function pushArtifactRemote(target) {
7830
8335
  process.stderr.write(chunk);
7831
8336
  });
7832
8337
  child.on("error", reject);
7833
- child.on("close", (code) => {
7834
- if (code === 0) {
8338
+ child.on("close", (code2) => {
8339
+ if (code2 === 0) {
7835
8340
  resolve(readPushOutput(stdout, stderr));
7836
8341
  return;
7837
8342
  }
7838
8343
  for (const line of stdout.split(/\r?\n/).filter((refLine) => refLine.startsWith("!"))) {
7839
- console.error(line.replace(/\t/g, " "));
8344
+ logger.detail(line.replace(/\t/g, " "));
7840
8345
  }
7841
- reject(new Error(`git push exited with code ${code}`));
8346
+ reject(new Error(`git push exited with code ${code2}`));
7842
8347
  });
7843
8348
  });
7844
8349
  }
7845
8350
  var NO_BUILD_GRACE_MS = 18e4;
7846
8351
  async function runDeploy(options = {}, dependencies = {}) {
7847
8352
  const git = dependencies.git ?? gitOutput3;
7848
- const say = {
8353
+ const say2 = {
7849
8354
  info: options.json ? (line) => console.error(line) : logger.info,
7850
8355
  success: options.json ? (line) => console.error(line) : logger.success,
7851
8356
  warning: options.json ? (line) => console.error(line) : logger.warning,
7852
8357
  error: options.json ? (line) => console.error(line) : logger.error
7853
8358
  };
7854
8359
  if (!options.json) {
7855
- console.log("");
7856
- logger.info(`${chalk.bold("Standard Agents Deploy")}
7857
- `);
8360
+ logger.log("");
8361
+ printHeading("Standard Agents Deploy");
8362
+ logger.log("");
7858
8363
  }
7859
8364
  try {
7860
8365
  configuredPlatformEndpoint(options.endpoint);
7861
8366
  } catch (err) {
7862
8367
  if (!(err instanceof PlatformEndpointError)) throw err;
7863
8368
  const [message, fix = ""] = err.message.split("\n");
7864
- say.error(message);
7865
- if (fix) say.info(fix);
8369
+ say2.error(message);
8370
+ if (fix) say2.info(fix);
7866
8371
  if (options.json) {
7867
8372
  console.log(JSON.stringify({ error: { message, fix, exit_code: EXIT.FAILED } }, null, 2));
7868
8373
  }
@@ -7875,9 +8380,9 @@ async function runDeploy(options = {}, dependencies = {}) {
7875
8380
  target = resolveArtifactGitDeployTarget(git, options.remote ?? ARTIFACT_DEPLOY_REMOTE_NAME, options.branch);
7876
8381
  } catch (err) {
7877
8382
  const message = err instanceof Error ? err.message : String(err);
7878
- say.error(message);
8383
+ say2.error(message);
7879
8384
  if (!(err instanceof BuildAccessError)) {
7880
- say.info("Run this command from a clone created by Standard Agents, or push to the platform git remote manually.");
8385
+ say2.info("Run this command from a clone created by Standard Agents, or push to the platform git remote manually.");
7881
8386
  }
7882
8387
  if (options.json) {
7883
8388
  console.log(JSON.stringify({ error: { message, exit_code: EXIT.USAGE } }, null, 2));
@@ -7903,35 +8408,35 @@ async function runDeploy(options = {}, dependencies = {}) {
7903
8408
  return exitCode;
7904
8409
  };
7905
8410
  const reportPushOnly = (reason, fix) => {
7906
- say.warning(`Only the push was verified. The build and deployment were not followed: ${reason}`);
7907
- say.info(fix);
7908
- say.info(`Then read the result with: ${cliCommand("builds status")}`);
8411
+ say2.warning(`Only the push was verified. The build and deployment were not followed: ${reason}`);
8412
+ say2.info(fix);
8413
+ say2.info(`Then read the result with: ${cliCommand("builds status")}`);
7909
8414
  };
7910
- say.info("Deployments build on the Standard Agents platform from git pushes.");
7911
- say.info(`Remote: ${remote}`);
7912
- say.info(`Branch: ${target.branch}`);
8415
+ say2.info("Deployments build on the Standard Agents platform from git pushes.");
8416
+ say2.info(`Remote: ${remote}`);
8417
+ say2.info(`Branch: ${target.branch}`);
7913
8418
  try {
7914
8419
  push = await (dependencies.push ?? pushArtifactRemote)(target);
7915
8420
  } catch {
7916
- say.error("The push failed, so nothing was deployed. Git printed the reason above.");
8421
+ say2.error("The push failed, so nothing was deployed. Git printed the reason above.");
7917
8422
  return finish("push_failed", EXIT.FAILED);
7918
8423
  }
7919
8424
  const nothingToPush = !push.sent;
7920
8425
  if (nothingToPush) {
7921
- say.info(`Nothing was pushed: ${target.remoteName}/${target.branch} already has ${commit.slice(0, 7)}. No build was started.`);
8426
+ say2.info(`Nothing was pushed: ${target.remoteName}/${target.branch} already has ${commit.slice(0, 7)}. No build was started.`);
7922
8427
  } else {
7923
- say.success(`Push accepted: ${commit.slice(0, 7)} is on ${target.remoteName}/${target.branch}. This is not yet a deployment.`);
8428
+ say2.success(`Push accepted: ${commit.slice(0, 7)} is on ${target.remoteName}/${target.branch}. This is not yet a deployment.`);
7924
8429
  }
7925
8430
  if (push.notice.length > 0) {
7926
- say.error("The platform stored the push and did not start a build.");
8431
+ say2.error("The platform stored the push and did not start a build.");
7927
8432
  if (/terms accept/.test(push.notice.join("\n"))) {
7928
- say.info(TERMS_ACCEPT_FIX);
8433
+ say2.info(TERMS_ACCEPT_FIX);
7929
8434
  return finish("terms_required", EXIT.TERMS_REQUIRED);
7930
8435
  }
7931
8436
  return finish("push_stored_no_build", EXIT.FAILED);
7932
8437
  }
7933
8438
  if (options.wait === false) {
7934
- say.info(nothingToPush ? `Not reading the existing build (--no-wait). Read it with: ${cliCommand("builds status")}` : `Not following the build (--no-wait). Read the result with: ${cliCommand("builds status")}`);
8439
+ say2.info(nothingToPush ? `Not reading the existing build (--no-wait). Read it with: ${cliCommand("builds status")}` : `Not following the build (--no-wait). Read the result with: ${cliCommand("builds status")}`);
7935
8440
  return finish(nothingToPush ? "nothing_pushed" : "not_followed", EXIT.OK);
7936
8441
  }
7937
8442
  let context;
@@ -7946,7 +8451,7 @@ async function runDeploy(options = {}, dependencies = {}) {
7946
8451
  reportPushOnly(failure.message, failure.fix);
7947
8452
  return finish("not_followed", EXIT.OK);
7948
8453
  }
7949
- say.info(nothingToPush ? "Reading the existing build of this commit." : "Following the platform build. Ctrl-C stops waiting; the build continues.");
8454
+ say2.info(nothingToPush ? "Reading the existing build of this commit." : "Following the platform build. Ctrl-C stops waiting; the build continues.");
7950
8455
  const noBuildGraceMs = nothingToPush ? 0 : dependencies.noBuildGraceMs ?? NO_BUILD_GRACE_MS;
7951
8456
  const outcome = await followBuild({
7952
8457
  session: context.session,
@@ -7957,24 +8462,24 @@ async function runDeploy(options = {}, dependencies = {}) {
7957
8462
  noBuildGraceMs,
7958
8463
  reconnectDelayMs: dependencies.reconnectDelayMs,
7959
8464
  onStatus: (build) => {
7960
- if (!isSettledBuild(build)) say.info(`Build ${build.id}: ${build.status}`);
8465
+ if (!isSettledBuild(build)) say2.info(`Build ${build.id}: ${build.status}`);
7961
8466
  }
7962
8467
  });
7963
8468
  if (outcome.kind === "settled") {
7964
8469
  const build = outcome.build;
7965
8470
  if (options.json) {
7966
8471
  if (needsLegalAcceptance(build)) {
7967
- say.error(build.error_message ?? "The platform did not start the build until the updated terms are accepted.");
7968
- say.info(TERMS_ACCEPT_FIX);
8472
+ say2.error(build.error_message ?? "The platform did not start the build until the updated terms are accepted.");
8473
+ say2.info(TERMS_ACCEPT_FIX);
7969
8474
  return finish("terms_required", EXIT.TERMS_REQUIRED, build);
7970
8475
  }
7971
8476
  if (build.status === "live" || build.status === "superseded") {
7972
- say.success(`Deployed: build ${build.id} is ${build.status}.`);
8477
+ say2.success(`Deployed: build ${build.id} is ${build.status}.`);
7973
8478
  return finish("deployed", EXIT.OK, build);
7974
8479
  }
7975
- say.error(`Build ${build.id} ${build.status === "cancelled" ? "was cancelled" : "failed"} and was not deployed${build.error_message ? `: ${build.error_message}` : "."}`);
8480
+ say2.error(`Build ${build.id} ${build.status === "cancelled" ? "was cancelled" : "failed"} and was not deployed${build.error_message ? `: ${build.error_message}` : "."}`);
7976
8481
  await printFailureLogTail(context, build);
7977
- say.info(`Read the build log with: ${cliCommand(`builds logs ${build.id}`)}`);
8482
+ say2.info(`Read the build log with: ${cliCommand(`builds logs ${build.id}`)}`);
7978
8483
  return finish("failed", EXIT.FAILED, build);
7979
8484
  }
7980
8485
  const exitCode = reportSettledBuild(build, context.project?.production_hostname ?? null);
@@ -7982,21 +8487,21 @@ async function runDeploy(options = {}, dependencies = {}) {
7982
8487
  return exitCode;
7983
8488
  }
7984
8489
  if (outcome.kind === "no-build" && outcome.build) {
7985
- say.error(`Build ${outcome.build.id} can no longer be found, so its deployment was not verified. It was ${outcome.build.status} when last read.`);
7986
- say.info(`See the project's builds with: ${cliCommand("builds")}`);
8490
+ say2.error(`Build ${outcome.build.id} can no longer be found, so its deployment was not verified. It was ${outcome.build.status} when last read.`);
8491
+ say2.info(`See the project's builds with: ${cliCommand("builds")}`);
7987
8492
  return finish("no_build", EXIT.FAILED, outcome.build);
7988
8493
  }
7989
8494
  if (outcome.kind === "no-build") {
7990
- say.error(nothingToPush ? `No build exists for ${commit.slice(0, 7)} on ${target.branch}, and this push sent nothing new, so the platform started none.` : `The platform started no build for ${commit.slice(0, 7)} on ${target.branch} within ${Math.round(noBuildGraceMs / 1e3)}s of the push.`);
7991
- say.info(`See the project's builds with: ${cliCommand("builds")}`);
8495
+ say2.error(nothingToPush ? `No build exists for ${commit.slice(0, 7)} on ${target.branch}, and this push sent nothing new, so the platform started none.` : `The platform started no build for ${commit.slice(0, 7)} on ${target.branch} within ${Math.round(noBuildGraceMs / 1e3)}s of the push.`);
8496
+ say2.info(`See the project's builds with: ${cliCommand("builds")}`);
7992
8497
  return finish("no_build", EXIT.FAILED);
7993
8498
  }
7994
8499
  if (outcome.kind === "timeout") {
7995
- say.error(outcome.build ? `Stopped waiting after ${timeoutMs / 1e3}s. Build ${outcome.build.id} is still ${outcome.build.status}; it has not deployed yet.` : `Stopped waiting after ${timeoutMs / 1e3}s. The platform has not started a build for ${commit.slice(0, 7)}.`);
7996
- say.info(`Read the result with: ${cliCommand("builds status --wait")}`);
8500
+ say2.error(outcome.build ? `Stopped waiting after ${timeoutMs / 1e3}s. Build ${outcome.build.id} is still ${outcome.build.status}; it has not deployed yet.` : `Stopped waiting after ${timeoutMs / 1e3}s. The platform has not started a build for ${commit.slice(0, 7)}.`);
8501
+ say2.info(`Read the result with: ${cliCommand("builds status --wait")}`);
7997
8502
  return finish("timed_out", EXIT.TIMED_OUT, outcome.build);
7998
8503
  }
7999
- if (outcome.build) say.info(`Build ${outcome.build.id} was ${outcome.build.status} when last read.`);
8504
+ if (outcome.build) say2.info(`Build ${outcome.build.id} was ${outcome.build.status} when last read.`);
8000
8505
  reportPushOnly(outcome.reason, outcome.fix);
8001
8506
  return finish("not_followed", EXIT.OK, outcome.build);
8002
8507
  }
@@ -8024,21 +8529,21 @@ function detectCliDirectoryContext(cwd = process.cwd()) {
8024
8529
  function getContextLabel(context) {
8025
8530
  switch (context) {
8026
8531
  case "outside_project":
8027
- return "Outside project";
8532
+ return "This directory is not a Standard Agents project.";
8028
8533
  case "inside_project_unlinked":
8029
- return "Project detected (unlinked)";
8534
+ return "This directory holds a Standard Agents project with no saved project API key.";
8030
8535
  case "inside_project_linked":
8031
- return "Linked Standard Agents project";
8536
+ return "This directory holds a linked Standard Agents project.";
8032
8537
  default:
8033
8538
  return "Unknown context";
8034
8539
  }
8035
8540
  }
8036
8541
  function getHomeActions(context) {
8037
- const shared = [
8542
+ const shared2 = [
8038
8543
  {
8039
8544
  id: "exit",
8040
- label: "Exit",
8041
- description: "Close this menu.",
8545
+ label: "Close this menu",
8546
+ description: "Exit without running a command.",
8042
8547
  argv: null
8043
8548
  }
8044
8549
  ];
@@ -8046,11 +8551,11 @@ function getHomeActions(context) {
8046
8551
  return [
8047
8552
  {
8048
8553
  id: "init",
8049
- label: "Init new project",
8554
+ label: "Create a project",
8050
8555
  description: "Create a new Standard Agents project in a fresh directory.",
8051
8556
  argv: ["init"]
8052
8557
  },
8053
- ...shared
8558
+ ...shared2
8054
8559
  ];
8055
8560
  }
8056
8561
  if (context === "inside_project_unlinked") {
@@ -8061,13 +8566,13 @@ function getHomeActions(context) {
8061
8566
  description: "Sign in through the browser and save the project API key of this project.",
8062
8567
  argv: ["login"]
8063
8568
  },
8064
- ...shared
8569
+ ...shared2
8065
8570
  ];
8066
8571
  }
8067
8572
  return [
8068
8573
  {
8069
8574
  id: "deploy",
8070
- label: "Deploy",
8575
+ label: "Deploy this project",
8071
8576
  description: "Push this linked project to Standard Agents and follow its platform build.",
8072
8577
  argv: ["deploy"]
8073
8578
  },
@@ -8077,31 +8582,42 @@ function getHomeActions(context) {
8077
8582
  description: "Sign in through the browser to change the account this machine uses. The project API key of this project is kept.",
8078
8583
  argv: ["login"]
8079
8584
  },
8080
- ...shared
8585
+ ...shared2
8081
8586
  ];
8082
8587
  }
8083
- var BRAND_LINES = [
8084
- " ____ _ _ _ _ _ ",
8085
- " / ___|| |_ __ _ _ __ __| | __ _ _ __ __| | / \\ __ _ ___ _ __ | |_ ___ ",
8086
- " \\___ \\| __/ _` | '_ \\ / _` |/ _` | '__/ _` | / _ \\ / _` |/ _ \\ '_ \\| __/ __|",
8087
- " ___) | || (_| | | | | (_| | (_| | | | (_| | / ___ \\ (_| | __/ | | | |_\\__ \\",
8088
- " |____/ \\__\\__,_|_| |_|\\__,_|\\__,_|_| \\__,_| /_/ \\_\\__, |\\___|_| |_|\\__|___/",
8089
- " |___/ "
8090
- ];
8091
- function restoreTuiTerminal(stdout = process.stdout) {
8588
+ function getHomeCommands(context, signedIn) {
8589
+ const command = (id, label, description, argv, inApp = false) => ({ id, label, description, argv, commandLine: cliCommand(argv.join(" ")), inApp });
8590
+ const signIn = context === "inside_project_unlinked" ? command("login", "Link this project", "Sign in through the browser and save the project API key of this project.", ["login"], true) : signedIn ? command("login", "Sign in again", "Sign in through the browser to change the account this machine uses.", ["login"], true) : command("login", "Sign in", "Sign in to your Standard Agents account through the browser. The sign-in is saved for this machine.", ["login"], true);
8591
+ const first = context === "outside_project" ? [command("init", "Create a project", "Create a new Standard Agents project in a fresh directory. Your account supplies inference.", ["init"], true)] : context === "inside_project_linked" ? [
8592
+ command("deploy", "Deploy this project", "Push the current branch to Standard Agents and follow the platform build to its result.", ["deploy"]),
8593
+ command("builds", "Builds", "List the recent platform builds of this project.", ["builds"])
8594
+ ] : [];
8595
+ return [
8596
+ ...first,
8597
+ ...context === "inside_project_unlinked" ? [signIn] : [],
8598
+ ...context !== "outside_project" ? [command("diag", "Diagnostics", "Show the builder version, watchdog budgets, and configuration warnings of the running instance.", ["diag", "instance"])] : [],
8599
+ command("models", "Models", "Print the current curated model guide.", ["current-models"]),
8600
+ ...signedIn ? [command("whoami", "Account", "Print the account this machine is signed in to, and the platform address.", ["whoami"])] : [],
8601
+ ...context === "inside_project_unlinked" ? [] : [signIn],
8602
+ ...signedIn ? [command("logout", "Sign out", "Remove the saved sign-in from this machine and revoke it on the platform.", ["logout"])] : [],
8603
+ command("skill", "Install the skill", "Install the Standard Agents Builder skill for your coding agent.", ["skill"])
8604
+ ];
8092
8605
  }
8093
- function HomeMenu({ contextLabel, actions, onSelect }) {
8606
+ function HomeMenu({ notice, contextLabel, actions, onSelect }) {
8094
8607
  const [selectedIndex, setSelectedIndex] = useState(0);
8608
+ const [closed, setClosed] = useState(false);
8095
8609
  const { exit } = useApp();
8610
+ useEffect(() => {
8611
+ if (closed) exit();
8612
+ }, [closed, exit]);
8613
+ const close = (selection) => {
8614
+ onSelect(selection);
8615
+ setClosed(true);
8616
+ };
8096
8617
  useInput((input, key) => {
8097
- if (key.ctrl && input === "c") {
8098
- onSelect(null);
8099
- exit();
8100
- return;
8101
- }
8102
- if (input === "q" || key.escape) {
8103
- onSelect(null);
8104
- exit();
8618
+ if (closed) return;
8619
+ if (key.ctrl && input === "c" || input === "q" || key.escape) {
8620
+ close(null);
8105
8621
  return;
8106
8622
  }
8107
8623
  if (key.upArrow || input === "k") {
@@ -8114,46 +8630,23 @@ function HomeMenu({ contextLabel, actions, onSelect }) {
8114
8630
  }
8115
8631
  if (key.return) {
8116
8632
  const chosen = actions[selectedIndex];
8117
- if (!chosen.argv) {
8118
- onSelect(null);
8119
- exit();
8120
- return;
8121
- }
8122
- onSelect({
8123
- actionId: chosen.id,
8124
- argv: chosen.argv,
8125
- preserveTuiScreen: chosen.id === "init"
8126
- });
8127
- exit();
8633
+ close(chosen.argv ? { actionId: chosen.id, argv: chosen.argv, runsInit: chosen.id === "init" } : null);
8128
8634
  }
8129
8635
  });
8130
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", paddingX: 1, children: [
8131
- /* @__PURE__ */ jsxs(Box, { borderStyle: "double", borderColor: "cyan", paddingX: 1, flexDirection: "column", children: [
8132
- /* @__PURE__ */ jsx(Text, { color: "cyanBright", bold: true, children: "STANDARD AGENTS CLI" }),
8133
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Command Center" })
8134
- ] }),
8135
- /* @__PURE__ */ jsx(Box, { marginTop: 1, flexDirection: "column", children: BRAND_LINES.map((line) => /* @__PURE__ */ jsx(Text, { color: "cyan", children: line }, line)) }),
8136
- /* @__PURE__ */ jsxs(Box, { marginTop: 1, borderStyle: "round", borderColor: "gray", paddingX: 1, flexDirection: "column", children: [
8137
- /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
8138
- "Context: ",
8139
- /* @__PURE__ */ jsx(Text, { color: "whiteBright", children: contextLabel })
8140
- ] }),
8141
- /* @__PURE__ */ jsx(Text, { color: "gray", children: "Use \u2191/\u2193 (or j/k), Enter to select, q to exit." })
8142
- ] }),
8143
- /* @__PURE__ */ jsxs(Box, { marginTop: 1, borderStyle: "round", borderColor: "cyan", paddingX: 1, flexDirection: "column", children: [
8144
- /* @__PURE__ */ jsx(Text, { color: "cyanBright", bold: true, children: "Actions" }),
8145
- actions.map((action, index) => {
8146
- const selected = selectedIndex === index;
8147
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginBottom: 0, marginTop: 0, children: [
8148
- /* @__PURE__ */ jsxs(Text, { color: selected ? "black" : "white", backgroundColor: selected ? "cyan" : void 0, bold: selected, children: [
8149
- selected ? "\u203A" : " ",
8150
- " ",
8151
- action.label
8152
- ] }),
8153
- /* @__PURE__ */ jsx(Text, { color: selected ? "cyan" : "gray", children: ` ${action.description}` })
8154
- ] }, action.id);
8155
- })
8156
- ] })
8636
+ if (closed) return null;
8637
+ return /* @__PURE__ */ jsxs(Screen, { children: [
8638
+ /* @__PURE__ */ jsx(Header, { notice }),
8639
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: contextLabel }),
8640
+ /* @__PURE__ */ jsx(Box, { marginTop: 1, flexDirection: "column", gap: 1, children: actions.map((action, index) => /* @__PURE__ */ jsx(
8641
+ Choice,
8642
+ {
8643
+ selected: selectedIndex === index,
8644
+ label: action.label,
8645
+ description: action.description
8646
+ },
8647
+ action.id
8648
+ )) }),
8649
+ /* @__PURE__ */ jsx(KeyHints, { children: "\u2191\u2193 to move \xB7 Enter to select \xB7 q to quit" })
8157
8650
  ] });
8158
8651
  }
8159
8652
  async function runHomeTui(cwd = process.cwd()) {
@@ -8166,6 +8659,7 @@ async function runHomeTui(cwd = process.cwd()) {
8166
8659
  /* @__PURE__ */ jsx(
8167
8660
  HomeMenu,
8168
8661
  {
8662
+ notice: takeDeferredNotice(),
8169
8663
  contextLabel,
8170
8664
  actions,
8171
8665
  onSelect: (value) => {
@@ -8180,6 +8674,923 @@ async function runHomeTui(cwd = process.cwd()) {
8180
8674
  await new Promise((resolve) => setTimeout(resolve, 0));
8181
8675
  return selection;
8182
8676
  }
8677
+
8678
+ // src/tui/layout.ts
8679
+ var MIN_COLUMNS = 60;
8680
+ var MIN_ROWS = 12;
8681
+ var COMPACT_ROWS = 20;
8682
+ var SEPARATOR_WIDTH = 5;
8683
+ var MAX_CONTENT_WIDTH = 100;
8684
+ function computeLayout(columns, rows) {
8685
+ const compact = columns < 80 || rows < COMPACT_ROWS;
8686
+ const name = compact ? "compact" : columns >= 140 ? "wide" : columns >= 100 ? "standard" : "narrow";
8687
+ const marginX = compact ? 1 : 2;
8688
+ const marginTop = compact ? 0 : 1;
8689
+ const gap = compact && rows < 16 ? 0 : 1;
8690
+ const innerWidth = Math.max(1, columns - marginX * 2);
8691
+ const leftWidth = name === "wide" ? 36 : name === "standard" ? 30 : 0;
8692
+ const mainRoom = leftWidth > 0 ? innerWidth - leftWidth - SEPARATOR_WIDTH : innerWidth;
8693
+ return {
8694
+ name,
8695
+ columns,
8696
+ rows,
8697
+ fits: columns >= MIN_COLUMNS && rows >= MIN_ROWS,
8698
+ compact,
8699
+ marginX,
8700
+ marginTop,
8701
+ gap,
8702
+ innerWidth,
8703
+ leftWidth,
8704
+ // A line in the main region stays short enough to read on a very wide terminal.
8705
+ mainWidth: Math.max(1, name === "wide" ? Math.min(mainRoom, MAX_CONTENT_WIDTH) : mainRoom),
8706
+ bodyHeight: Math.max(1, rows - marginTop - 2 - gap * 2)
8707
+ };
8708
+ }
8709
+ var GRAPHEMES2 = new Intl.Segmenter(void 0, { granularity: "grapheme" });
8710
+ function clusters(text2) {
8711
+ return Array.from(GRAPHEMES2.segment(text2), (part) => part.segment);
8712
+ }
8713
+ function take(parts, start, step, cells) {
8714
+ const taken = [];
8715
+ let used = 0;
8716
+ for (let index = start; index >= 0 && index < parts.length; index += step) {
8717
+ const width = visibleLength(parts[index]);
8718
+ if (used + width > cells) break;
8719
+ used += width;
8720
+ if (step === 1) taken.push(parts[index]);
8721
+ else taken.unshift(parts[index]);
8722
+ }
8723
+ return taken;
8724
+ }
8725
+ function truncateEnd(text2, cells) {
8726
+ if (cells <= 0) return "";
8727
+ if (visibleLength(text2) <= cells) return text2;
8728
+ return `${take(clusters(text2), 0, 1, cells - 1).join("").trimEnd()}\u2026`;
8729
+ }
8730
+ function truncateMiddle(text2, cells) {
8731
+ if (cells <= 0) return "";
8732
+ if (visibleLength(text2) <= cells) return text2;
8733
+ if (cells < 5) return truncateEnd(text2, cells);
8734
+ const parts = clusters(text2);
8735
+ const head = Math.ceil((cells - 1) / 2);
8736
+ return `${take(parts, 0, 1, head).join("")}\u2026${take(parts, parts.length - 1, -1, cells - 1 - head).join("")}`;
8737
+ }
8738
+ function hardWrap(text2, cells) {
8739
+ const parts = clusters(text2);
8740
+ const lines = [];
8741
+ for (let start = 0; start < parts.length; ) {
8742
+ const piece = take(parts, start, 1, Math.max(1, cells));
8743
+ const count2 = Math.max(1, piece.length);
8744
+ lines.push(parts.slice(start, start + count2).join(""));
8745
+ start += count2;
8746
+ }
8747
+ return lines.length > 0 ? lines : [""];
8748
+ }
8749
+ function wordWrap(text2, cells) {
8750
+ const width = Math.max(1, cells);
8751
+ return text2.split("\n").flatMap((paragraph) => {
8752
+ if (/^\s/.test(paragraph)) return [truncateMiddle(paragraph, width)];
8753
+ const lines = [];
8754
+ let current2 = "";
8755
+ for (const word of paragraph.split(" ").filter(Boolean)) {
8756
+ const pieces = visibleLength(word) > width ? hardWrap(word, width) : [word];
8757
+ for (const piece of pieces) {
8758
+ const candidate = current2 ? `${current2} ${piece}` : piece;
8759
+ if (current2 && visibleLength(candidate) > width) {
8760
+ lines.push(current2);
8761
+ current2 = piece;
8762
+ } else {
8763
+ current2 = candidate;
8764
+ }
8765
+ }
8766
+ }
8767
+ lines.push(current2);
8768
+ return lines;
8769
+ });
8770
+ }
8771
+ function padEnd(text2, cells) {
8772
+ return `${text2}${" ".repeat(Math.max(0, cells - visibleLength(text2)))}`;
8773
+ }
8774
+
8775
+ // src/tui/mode.ts
8776
+ var NO_TUI_FLAG = "--no-tui";
8777
+ function isSet2(value) {
8778
+ return value !== void 0 && value !== "" && value !== "0" && value.toLowerCase() !== "false";
8779
+ }
8780
+ function shouldUseTui(environment = {}) {
8781
+ const { stdin, stdout, env, argv, json } = {
8782
+ stdin: process.stdin,
8783
+ stdout: process.stdout,
8784
+ env: process.env,
8785
+ argv: process.argv.slice(2),
8786
+ json: isJsonOutput(),
8787
+ ...environment
8788
+ };
8789
+ if (!stdin.isTTY || !stdout.isTTY) return false;
8790
+ if (json || argv.includes("--json") || argv.includes(NO_TUI_FLAG)) return false;
8791
+ if (isSet2(env.CI) || isSet2(env.NO_TUI) || env.TERM === "dumb") return false;
8792
+ return (stdout.columns ?? 0) >= MIN_COLUMNS && (stdout.rows ?? 0) >= MIN_ROWS;
8793
+ }
8794
+ var blank = () => /* @__PURE__ */ jsx(Text, { children: " " });
8795
+ var plain = (text2, props = {}) => /* @__PURE__ */ jsx(Text, { bold: props.bold, dimColor: props.dim, color: props.color, children: text2 || " " });
8796
+ function isUrl(value) {
8797
+ return /^https?:\/\/\S+$/.test(value);
8798
+ }
8799
+ function LinkText({ url, children }) {
8800
+ return /* @__PURE__ */ jsx(Text, { color: COLORS2.link, children: `\x1B]8;;${url}\x07${children}\x1B]8;;\x07` });
8801
+ }
8802
+ function Spinner({ now }) {
8803
+ const [red, green, blue] = brandColor(now);
8804
+ const hex = `#${[red, green, blue].map((part) => part.toString(16).padStart(2, "0")).join("")}`;
8805
+ return /* @__PURE__ */ jsx(Text, { bold: true, color: hex, children: SPINNER_FRAMES[Math.floor(now / SPINNER_FRAME_MS) % SPINNER_FRAMES.length] });
8806
+ }
8807
+ function Region({ width, height, rows }) {
8808
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", width, height, overflow: "hidden", flexShrink: 0, children: rows.slice(0, height).map((row, index) => /* @__PURE__ */ jsx(Box, { height: 1, width, overflow: "hidden", flexShrink: 0, children: row }, index)) });
8809
+ }
8810
+ function keyValueRows(pairs, width) {
8811
+ const keyWidth = Math.max(...pairs.map(([key]) => visibleLength(key)));
8812
+ const room = Math.max(4, width - keyWidth - 2);
8813
+ return pairs.map(([key, value]) => {
8814
+ const shown = value.includes("/") ? truncateMiddle(value, room) : truncateEnd(value, room);
8815
+ return /* @__PURE__ */ jsxs(Text, { children: [
8816
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: padEnd(key, keyWidth) }),
8817
+ " ",
8818
+ isUrl(value) ? /* @__PURE__ */ jsx(LinkText, { url: value, children: shown }) : shown
8819
+ ] });
8820
+ });
8821
+ }
8822
+ function stepGlyph(step, now) {
8823
+ if (step.state === "done") return /* @__PURE__ */ jsx(Text, { color: COLORS2.success, children: GLYPHS.done });
8824
+ if (step.state === "failed") return /* @__PURE__ */ jsx(Text, { color: COLORS2.error, children: GLYPHS.error });
8825
+ if (step.state === "active") return /* @__PURE__ */ jsx(Spinner, { now });
8826
+ return /* @__PURE__ */ jsx(Text, { dimColor: true, children: "\xB7" });
8827
+ }
8828
+ function stepRows(state, width, now) {
8829
+ const rows = state.title ? [plain(truncateEnd(state.title, width), { dim: true }), blank()] : [];
8830
+ for (const step of state.steps) {
8831
+ const ms = step.state === "active" && step.startedAt ? now - step.startedAt : step.elapsedMs ?? 0;
8832
+ const time = step.state !== "pending" && ms >= 1e3 ? formatDuration(ms) : "";
8833
+ const label = padEnd(truncateEnd(step.label, width - 2 - (time ? time.length + 2 : 0)), width - 2 - time.length);
8834
+ rows.push(
8835
+ /* @__PURE__ */ jsxs(Text, { children: [
8836
+ stepGlyph(step, now),
8837
+ /* @__PURE__ */ jsx(Text, { bold: step.state === "active", dimColor: step.state === "pending", children: ` ${label}` }),
8838
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: time })
8839
+ ] })
8840
+ );
8841
+ }
8842
+ return rows;
8843
+ }
8844
+ function stepIndicator(steps, width, now) {
8845
+ const current2 = steps.find((step) => step.state === "failed") ?? steps.find((step) => step.state === "active") ?? [...steps].reverse().find((step) => step.state === "done") ?? steps[0];
8846
+ const position = `Step ${steps.indexOf(current2) + 1} of ${steps.length}`;
8847
+ return /* @__PURE__ */ jsxs(Text, { children: [
8848
+ stepGlyph(current2, now),
8849
+ /* @__PURE__ */ jsx(Text, { bold: true, children: ` ${position}` }),
8850
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: truncateEnd(` \xB7 ${current2.label}`, width - 2 - position.length) })
8851
+ ] });
8852
+ }
8853
+ function commandRows(panel, width) {
8854
+ return panel.commands.map((command, index) => {
8855
+ const selected = index === panel.selected;
8856
+ return plain(`${selected ? GLYPHS.cursor : " "} ${truncateEnd(command.label, width - 2)}`, { bold: selected });
8857
+ });
8858
+ }
8859
+ function previewRows(panel, width, height) {
8860
+ const command = panel.commands[panel.selected];
8861
+ const description = wordWrap(command.description, width).map((line) => plain(line));
8862
+ const facts = keyValueRows([["Command", command.commandLine], ...panel.facts], width);
8863
+ const rows = [plain(truncateEnd(command.label, width), { bold: true })];
8864
+ if (height >= 1 + description.length + 1 + facts.length) return [...rows, ...description, blank(), ...facts];
8865
+ if (height >= 3 + description.length) return [...rows, ...description, blank(), facts[0]];
8866
+ return height >= 3 ? [...rows, blank(), facts[0]] : rows;
8867
+ }
8868
+ function viewportRows(state, width, height, color) {
8869
+ if (height <= 0) return [];
8870
+ const unfinished = sanitizeOutputLine(state.partial, color);
8871
+ const lines = unfinished ? [...state.log, unfinished] : state.log;
8872
+ const scroll = Math.min(state.scroll, Math.max(0, lines.length - height));
8873
+ const end = lines.length - scroll;
8874
+ const shown = lines.slice(Math.max(0, end - height), end).map((line) => (
8875
+ // A colored line keeps its codes, and Ink cuts it at the width of the region.
8876
+ /* @__PURE__ */ jsx(Text, { wrap: "truncate-end", dimColor: !color, children: (color ? line : truncateEnd(line, width)) || " " })
8877
+ ));
8878
+ if (scroll > 0 && shown.length > 0) {
8879
+ shown[shown.length - 1] = plain(truncateEnd(`${scroll} newer ${scroll === 1 ? "line" : "lines"} below`, width), { dim: true });
8880
+ }
8881
+ return shown;
8882
+ }
8883
+ var MIN_VIEWPORT_ROWS = 3;
8884
+ function logRows(state, panel, width, height, metrics) {
8885
+ const rows = [plain(truncateEnd(panel.title, width), { bold: true })];
8886
+ const summary = panel.summary ? keyValueRows(panel.summary.rows, width) : [];
8887
+ const room = (extra) => height - rows.length - extra >= MIN_VIEWPORT_ROWS;
8888
+ if (summary.length > 0 && room(summary.length + 2)) rows.push(blank(), ...summary);
8889
+ else if (summary.length > 0 && room(3)) rows.push(blank(), summary[0]);
8890
+ else if (panel.detail && room(2)) rows.push(plain(truncateMiddle(panel.detail, width), { dim: true }));
8891
+ if (room(1)) rows.push(blank());
8892
+ metrics.viewportRows = Math.max(1, height - rows.length);
8893
+ return [...rows, ...viewportRows(state, width, height - rows.length, panel.color)];
8894
+ }
8895
+ function signInRows(panel, width, height, now) {
8896
+ const rows = [plain("Sign in", { bold: true })];
8897
+ if (!panel.url) return rows;
8898
+ const launch = wordWrap(SIGN_IN_LAUNCH_TEXT[panel.launch ?? "skipped"], width);
8899
+ const wrapped = hardWrap(panel.url, width);
8900
+ const about = panel.about ? wordWrap(panel.about, width) : [];
8901
+ const countdown = panel.expiresAt ? `This session expires in ${formatDuration(panel.expiresAt - now)}.` : "";
8902
+ const whole = height >= 1 + about.length + 1 + launch.length + wrapped.length + 2;
8903
+ const urlRows = whole ? wrapped : [truncateMiddle(panel.url, width)];
8904
+ const needed = 1 + launch.length + urlRows.length;
8905
+ if (about.length > 0 && height >= needed + about.length + 1) rows.push(...about.map((line) => plain(line)));
8906
+ if (height >= needed + 1 + (rows.length - 1)) rows.push(blank());
8907
+ rows.push(...launch.map((line) => plain(line, { dim: panel.launch !== "failed", color: panel.launch === "failed" ? COLORS2.warning : void 0 })));
8908
+ rows.push(...urlRows.map((line) => /* @__PURE__ */ jsx(LinkText, { url: panel.url ?? "", children: line })));
8909
+ if (countdown && height >= rows.length + 2) rows.push(blank(), plain(truncateEnd(countdown, width), { dim: true }));
8910
+ const notes = panel.notes.slice(-Math.max(0, height - rows.length - 1));
8911
+ if (notes.length > 0) rows.push(blank(), ...notes.map((note) => plain(truncateEnd(note, width), { dim: true })));
8912
+ return rows;
8913
+ }
8914
+ function failureRows(panel, width, height) {
8915
+ const [headline, ...detail] = panel.failure.cause.replace("Its output is above.", "Its output is below.").split("\n");
8916
+ const cause = wordWrap(headline, width - 2);
8917
+ const rows = cause.map((line, index) => /* @__PURE__ */ jsxs(Text, { children: [
8918
+ index === 0 ? /* @__PURE__ */ jsx(Text, { color: COLORS2.error, children: GLYPHS.error }) : " ",
8919
+ /* @__PURE__ */ jsx(Text, { bold: true, children: ` ${line}` })
8920
+ ] }));
8921
+ const steps = [...detail, ...panel.failure.next].flatMap((line) => wordWrap(line, width - 2));
8922
+ if (steps.length > 0) rows.push(blank(), ...steps.map((line) => plain(` ${line}`)));
8923
+ const room = height - rows.length - 1;
8924
+ if (panel.tail.length > 0 && room >= MIN_VIEWPORT_ROWS) {
8925
+ rows.push(blank(), ...panel.tail.slice(-room).map((line) => plain(truncateEnd(line, width), { dim: true })));
8926
+ }
8927
+ return rows;
8928
+ }
8929
+ function confirmRows(panel, warnings, width) {
8930
+ const keyWidth = Math.max(...panel.summary.rows.map(([key]) => visibleLength(key)));
8931
+ const rows = [
8932
+ /* @__PURE__ */ jsxs(Text, { children: [
8933
+ /* @__PURE__ */ jsx(Text, { color: COLORS2.success, children: GLYPHS.done }),
8934
+ /* @__PURE__ */ jsx(Text, { bold: true, children: ` ${truncateEnd(panel.summary.title, width - 2)}` })
8935
+ ] }),
8936
+ blank()
8937
+ ];
8938
+ for (const [key, value] of panel.summary.rows) {
8939
+ wordWrap(value, Math.max(8, width - keyWidth - 2)).forEach((line, index) => {
8940
+ rows.push(
8941
+ /* @__PURE__ */ jsxs(Text, { children: [
8942
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: padEnd(index === 0 ? key : "", keyWidth) }),
8943
+ ` ${line}`
8944
+ ] })
8945
+ );
8946
+ });
8947
+ }
8948
+ for (const warning of warnings) {
8949
+ rows.push(blank());
8950
+ wordWrap(warning.replace(/\n/g, " "), width - 2).forEach((line, index) => {
8951
+ rows.push(
8952
+ /* @__PURE__ */ jsxs(Text, { children: [
8953
+ index === 0 ? /* @__PURE__ */ jsx(Text, { color: COLORS2.warning, children: GLYPHS.warning }) : " ",
8954
+ ` ${line}`
8955
+ ] })
8956
+ );
8957
+ });
8958
+ }
8959
+ return rows;
8960
+ }
8961
+ function mainRows(state, layout, width, height, now, metrics) {
8962
+ const { panel } = state;
8963
+ if (panel.kind === "home") {
8964
+ if (layout.leftWidth > 0) return previewRows(panel, width, height);
8965
+ const list = commandRows(panel, width);
8966
+ const room = height - list.length - 1;
8967
+ return room >= 1 ? [...list, blank(), ...previewRows(panel, width, room)] : list;
8968
+ }
8969
+ if (panel.kind === "confirm") return confirmRows(panel, state.warnings, width);
8970
+ if (panel.kind === "failure") return failureRows(panel, width, height);
8971
+ const warning = state.warnings.at(-1);
8972
+ const notice = warning && height >= 14 ? [
8973
+ /* @__PURE__ */ jsxs(Text, { children: [
8974
+ /* @__PURE__ */ jsx(Text, { color: COLORS2.warning, children: GLYPHS.warning }),
8975
+ ` ${truncateEnd(warning.replace(/\n/g, " "), width - 2)}`
8976
+ ] }),
8977
+ blank()
8978
+ ] : [];
8979
+ const rest = height - notice.length;
8980
+ if (panel.kind === "signIn") return [...notice, ...signInRows(panel, width, rest, now)];
8981
+ if (panel.kind === "log") return [...notice, ...logRows(state, panel, width, rest, metrics)];
8982
+ return notice;
8983
+ }
8984
+ function hintFor(state) {
8985
+ const { panel } = state;
8986
+ if (panel.kind === "home") return { full: "\u2191\u2193 move \xB7 Enter run \xB7 q quit", short: "\u2191\u2193 \xB7 Enter \xB7 q quit" };
8987
+ if (panel.kind === "failure" || panel.kind === "confirm") return { full: "Enter close", short: "Enter close" };
8988
+ if (panel.kind === "signIn" && panel.url) {
8989
+ return { full: "o open browser \xB7 c copy URL \xB7 Ctrl-C cancel", short: "o open \xB7 c copy \xB7 ^C cancel" };
8990
+ }
8991
+ if (panel.kind === "wizard") {
8992
+ return panel.wizard.snapshot().step === "packageManager" ? { full: "\u2191\u2193 move \xB7 Enter continue \xB7 Esc cancel", short: "\u2191\u2193 \xB7 Enter \xB7 Esc cancel" } : { full: "Enter continue \xB7 Esc cancel", short: "Enter \xB7 Esc cancel" };
8993
+ }
8994
+ if (panel.kind === "log" && state.status.kind === "ready") {
8995
+ return { full: "o open the Builder \xB7 PgUp PgDn scroll \xB7 q stop and quit", short: "o open \xB7 q stop and quit" };
8996
+ }
8997
+ if (panel.kind === "log") return { full: "PgUp PgDn scroll \xB7 Ctrl-C cancel", short: "^C cancel" };
8998
+ return { full: "Ctrl-C cancel", short: "^C cancel" };
8999
+ }
9000
+ function statusTime(status, now) {
9001
+ if (status.until) return `${formatDuration(status.until - now)} left`;
9002
+ if (status.since && now - status.since >= 1e3) return formatDuration(now - status.since);
9003
+ return "";
9004
+ }
9005
+ function TopBar({ state, layout }) {
9006
+ const version = cliVersion();
9007
+ const used = "Standard Agents".length + 2 + version.length;
9008
+ const room = layout.innerWidth - used - 3;
9009
+ const account = truncateEnd(state.account ?? "Not signed in", Math.max(8, Math.floor(room * 0.6)));
9010
+ const directory = truncateMiddle(state.directory, room - visibleLength(account) - 3);
9011
+ const context = layout.compact || room < 16 ? "" : directory ? `${account} \xB7 ${directory}` : account;
9012
+ return /* @__PURE__ */ jsxs(Box, { width: layout.innerWidth, height: 1, justifyContent: "space-between", flexShrink: 0, children: [
9013
+ /* @__PURE__ */ jsxs(Text, { children: [
9014
+ /* @__PURE__ */ jsx(Text, { bold: true, children: "Standard Agents" }),
9015
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: ` ${truncateEnd(version, Math.max(1, layout.innerWidth - 17))}` })
9016
+ ] }),
9017
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: context })
9018
+ ] });
9019
+ }
9020
+ function BottomBar({ state, layout, now }) {
9021
+ const hint = hintFor(state);
9022
+ const fullFits = !layout.compact && visibleLength(hint.full) <= layout.innerWidth / 2;
9023
+ const keys = fullFits ? hint.full : hint.short;
9024
+ const { status } = state;
9025
+ const time = state.flash ? "" : statusTime(status, now);
9026
+ const note = state.flash ? "" : status.note ?? "";
9027
+ const room = layout.innerWidth - visibleLength(keys) - 4;
9028
+ const label = truncateEnd(state.flash ?? status.label, Math.max(4, room - (time ? time.length + 2 : 0)));
9029
+ const noteRoom = room - visibleLength(label) - (time ? time.length + 2 : 0) - 3;
9030
+ const glyph = state.flash ? /* @__PURE__ */ jsx(Text, { color: COLORS2.success, children: GLYPHS.done }) : status.kind === "busy" ? /* @__PURE__ */ jsx(Spinner, { now }) : status.kind === "failed" ? /* @__PURE__ */ jsx(Text, { color: COLORS2.error, children: GLYPHS.error }) : status.kind === "ready" ? /* @__PURE__ */ jsx(Text, { color: COLORS2.success, children: GLYPHS.current }) : null;
9031
+ return /* @__PURE__ */ jsxs(Box, { width: layout.innerWidth, height: 1, justifyContent: "space-between", flexShrink: 0, children: [
9032
+ /* @__PURE__ */ jsxs(Text, { children: [
9033
+ glyph,
9034
+ /* @__PURE__ */ jsx(Text, { dimColor: status.kind === "idle" && !state.flash, children: `${glyph ? " " : ""}${label}` }),
9035
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: note && noteRoom >= 8 ? ` \xB7 ${truncateEnd(note, noteRoom)}` : "" }),
9036
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: time ? ` ${time}` : "" })
9037
+ ] }),
9038
+ /* @__PURE__ */ jsx(Text, { dimColor: true, children: keys })
9039
+ ] });
9040
+ }
9041
+ function Body({ state, layout, now, metrics }) {
9042
+ const { panel } = state;
9043
+ const height = layout.bodyHeight;
9044
+ const hasList = panel.kind === "home" || state.steps.length > 0;
9045
+ if (panel.kind === "wizard") {
9046
+ const snapshot = panel.wizard.snapshot();
9047
+ const frame = STEP_FRAMES[snapshot.step];
9048
+ const side = layout.leftWidth > 0 ? layout.leftWidth + 5 : 0;
9049
+ const head2 = layout.leftWidth > 0 ? [] : [stepIndicator(state.steps, layout.mainWidth, now), ...layout.gap ? [blank()] : []];
9050
+ return /* @__PURE__ */ jsxs(Box, { height, flexDirection: "row", overflow: "hidden", flexShrink: 0, children: [
9051
+ side > 0 ? /* @__PURE__ */ jsx(Region, { width: layout.leftWidth, height, rows: stepRows(state, layout.leftWidth, now) }) : null,
9052
+ side > 0 ? /* @__PURE__ */ jsx(Separator, { height }) : null,
9053
+ /* @__PURE__ */ jsxs(Box, { flexDirection: "column", width: layout.mainWidth, height, overflow: "hidden", flexShrink: 0, children: [
9054
+ /* @__PURE__ */ jsx(Region, { width: layout.mainWidth, height: head2.length + 2, rows: [
9055
+ ...head2,
9056
+ plain(truncateEnd(frame.title, layout.mainWidth), { bold: true }),
9057
+ plain(truncateEnd(frame.subtitle, layout.mainWidth), { dim: true })
9058
+ ] }),
9059
+ /* @__PURE__ */ jsx(WizardBody, { state: snapshot, detected: panel.detected, embedded: true, maxRows: height - head2.length - 2 })
9060
+ ] })
9061
+ ] });
9062
+ }
9063
+ if (hasList && layout.leftWidth > 0) {
9064
+ const left = panel.kind === "home" ? [plain("Commands", { dim: true }), blank(), ...commandRows(panel, layout.leftWidth)] : stepRows(state, layout.leftWidth, now);
9065
+ return /* @__PURE__ */ jsxs(Box, { height, flexDirection: "row", overflow: "hidden", flexShrink: 0, children: [
9066
+ /* @__PURE__ */ jsx(Region, { width: layout.leftWidth, height, rows: left }),
9067
+ /* @__PURE__ */ jsx(Separator, { height }),
9068
+ /* @__PURE__ */ jsx(Region, { width: layout.mainWidth, height, rows: mainRows(state, layout, layout.mainWidth, height, now, metrics) })
9069
+ ] });
9070
+ }
9071
+ const head = state.steps.length > 0 ? [stepIndicator(state.steps, layout.mainWidth, now), ...layout.gap ? [blank()] : []] : [];
9072
+ const rows = [...head, ...mainRows(state, layout, layout.mainWidth, height - head.length, now, metrics)];
9073
+ return /* @__PURE__ */ jsx(Region, { width: layout.mainWidth, height, rows });
9074
+ }
9075
+ function Separator({ height }) {
9076
+ return /* @__PURE__ */ jsx(Box, { width: 5, height, flexShrink: 0, overflow: "hidden", children: /* @__PURE__ */ jsx(Text, { dimColor: true, children: Array.from({ length: height }, () => " \u2502 ").join("\n") }) });
9077
+ }
9078
+ function Frame({ state, columns, rows, now, metrics }) {
9079
+ const layout = computeLayout(columns, rows);
9080
+ if (!layout.fits) {
9081
+ return /* @__PURE__ */ jsx(Box, { width: columns, height: rows, overflow: "hidden", flexDirection: "column", children: /* @__PURE__ */ jsx(Text, { wrap: "truncate-end", children: `Make the window at least ${MIN_COLUMNS} columns by ${MIN_ROWS} rows.` }) });
9082
+ }
9083
+ const gap = layout.gap ? /* @__PURE__ */ jsx(Box, { height: 1, flexShrink: 0 }) : null;
9084
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", width: columns, height: rows, paddingX: layout.marginX, overflow: "hidden", children: [
9085
+ layout.marginTop ? /* @__PURE__ */ jsx(Box, { height: layout.marginTop, flexShrink: 0 }) : null,
9086
+ /* @__PURE__ */ jsx(TopBar, { state, layout }),
9087
+ gap,
9088
+ /* @__PURE__ */ jsx(Body, { state, layout, now, metrics }),
9089
+ gap,
9090
+ /* @__PURE__ */ jsx(BottomBar, { state, layout, now })
9091
+ ] });
9092
+ }
9093
+ function isAnimated(state) {
9094
+ return state.status.kind === "busy" || state.status.kind === "ready" || state.steps.some((step) => step.state === "active");
9095
+ }
9096
+ function App({ store, metrics, onKey }) {
9097
+ const state = useSyncExternalStore(store.subscribe, store.getState);
9098
+ const { stdout } = useStdout();
9099
+ const [size, setSize] = useState({ columns: stdout.columns, rows: stdout.rows });
9100
+ const [now, setNow] = useState(() => Date.now());
9101
+ const animated = isAnimated(state);
9102
+ useEffect(() => {
9103
+ const resized = () => setSize({ columns: stdout.columns, rows: stdout.rows });
9104
+ stdout.on("resize", resized);
9105
+ return () => {
9106
+ stdout.off("resize", resized);
9107
+ };
9108
+ }, [stdout]);
9109
+ useEffect(() => {
9110
+ if (!animated) return void 0;
9111
+ const timer = setInterval(() => setNow(Date.now()), SPINNER_FRAME_MS);
9112
+ return () => clearInterval(timer);
9113
+ }, [animated]);
9114
+ useInput(onKey);
9115
+ return /* @__PURE__ */ jsx(Frame, { state, columns: size.columns, rows: size.rows, now: animated ? now : Date.now(), metrics });
9116
+ }
9117
+ function clipboardCommand(env, platform) {
9118
+ if (platform === "darwin") return { command: "pbcopy", args: [] };
9119
+ if (platform === "win32") return { command: "clip", args: [] };
9120
+ if (env.WAYLAND_DISPLAY) return { command: "wl-copy", args: [] };
9121
+ if (env.DISPLAY) return { command: "xclip", args: ["-selection", "clipboard"] };
9122
+ return null;
9123
+ }
9124
+ function osc52(text2) {
9125
+ return `\x1B]52;c;${Buffer.from(text2, "utf8").toString("base64")}\x07`;
9126
+ }
9127
+ function copyToClipboard(text2, write, env = process.env, platform = process.platform) {
9128
+ write(osc52(text2));
9129
+ const tool = clipboardCommand(env, platform);
9130
+ if (!tool) return;
9131
+ try {
9132
+ const child = spawn(tool.command, tool.args, { stdio: ["pipe", "ignore", "ignore"] });
9133
+ child.on("error", () => {
9134
+ });
9135
+ child.stdin?.on("error", () => {
9136
+ });
9137
+ child.stdin?.end(text2);
9138
+ child.unref();
9139
+ } catch {
9140
+ }
9141
+ }
9142
+ var ENTER_SCREEN = "\x1B[?1049h\x1B[2J\x1B[H\x1B[?25l";
9143
+ var LEAVE_SCREEN = "\x1B[0m\x1B[?25h\x1B[?1049l";
9144
+ var BEGIN_UPDATE = "\x1B[?2026h";
9145
+ var END_UPDATE = "\x1B[?2026l";
9146
+ var CLEAR_SCREEN = "\x1B[2J";
9147
+ var FrameSink = class extends EventEmitter {
9148
+ constructor(columns, rows, onFrame = () => {
9149
+ }) {
9150
+ super();
9151
+ this.onFrame = onFrame;
9152
+ this.columns = columns;
9153
+ this.rows = rows;
9154
+ }
9155
+ isTTY = false;
9156
+ columns;
9157
+ rows;
9158
+ /** The newest frame, one string per row. */
9159
+ frame = [];
9160
+ write(chunk) {
9161
+ const lines = chunk.split("\n");
9162
+ this.frame = lines;
9163
+ this.onFrame(lines);
9164
+ return true;
9165
+ }
9166
+ resize(columns, rows) {
9167
+ this.columns = columns;
9168
+ this.rows = rows;
9169
+ this.emit("resize");
9170
+ }
9171
+ };
9172
+ function createPainter(output) {
9173
+ let shown = [];
9174
+ let clear = false;
9175
+ return {
9176
+ paint(frame) {
9177
+ const rows = output.rows ?? frame.length;
9178
+ let update = clear ? CLEAR_SCREEN : "";
9179
+ for (let row = 0; row < rows; row += 1) {
9180
+ const line = frame[row] ?? "";
9181
+ if (!clear && shown[row] === line) continue;
9182
+ update += `\x1B[${row + 1};1H${line}\x1B[0m\x1B[K`;
9183
+ }
9184
+ shown = frame.slice(0, rows);
9185
+ clear = false;
9186
+ if (update) output.write(`${BEGIN_UPDATE}${update}${END_UPDATE}`);
9187
+ },
9188
+ reset() {
9189
+ shown = [];
9190
+ clear = true;
9191
+ }
9192
+ };
9193
+ }
9194
+ var NOTIFY_MS = 16;
9195
+ function createTuiStore(initial, now = Date.now) {
9196
+ let state = {
9197
+ title: "",
9198
+ steps: [],
9199
+ panel: { kind: "blank" },
9200
+ status: { kind: "idle", label: "" },
9201
+ log: [],
9202
+ partial: "",
9203
+ scroll: 0,
9204
+ warnings: [],
9205
+ ...initial
9206
+ };
9207
+ const listeners = /* @__PURE__ */ new Set();
9208
+ let timer;
9209
+ const notify = () => {
9210
+ if (timer) return;
9211
+ timer = setTimeout(() => {
9212
+ timer = void 0;
9213
+ for (const listener of listeners) listener();
9214
+ }, NOTIFY_MS);
9215
+ timer.unref();
9216
+ };
9217
+ const set = (change) => {
9218
+ state = { ...state, ...typeof change === "function" ? change(state) : change };
9219
+ notify();
9220
+ };
9221
+ const keepColor = () => state.panel.kind === "log" && state.panel.color;
9222
+ return {
9223
+ getState: () => state,
9224
+ subscribe(listener) {
9225
+ listeners.add(listener);
9226
+ return () => listeners.delete(listener);
9227
+ },
9228
+ set,
9229
+ setSteps(steps) {
9230
+ const known = new Map(state.steps.map((step) => [step.id, step]));
9231
+ set({ steps: steps.map((step) => ({ ...known.get(step.id) ?? { state: "pending" }, ...step })) });
9232
+ },
9233
+ setStep(id, next) {
9234
+ set({
9235
+ steps: state.steps.map((step) => {
9236
+ if (step.id !== id) return step;
9237
+ if (next === "active") return { ...step, state: next, startedAt: now() };
9238
+ return { ...step, state: next, ...step.startedAt ? { elapsedMs: now() - step.startedAt } : {} };
9239
+ })
9240
+ });
9241
+ },
9242
+ failActiveStep() {
9243
+ const active = state.steps.find((step) => step.state === "active");
9244
+ if (active) this.setStep(active.id, "failed");
9245
+ },
9246
+ resetLog() {
9247
+ set({ log: [], partial: "", scroll: 0 });
9248
+ },
9249
+ appendLog(chunk) {
9250
+ const pieces = (state.partial + chunk).split("\n");
9251
+ const partial = pieces.pop() ?? "";
9252
+ const lines = pieces.map((line) => sanitizeOutputLine(line, keepColor()));
9253
+ while (state.log.length === 0 && lines.length > 0 && lines[0] === "") lines.shift();
9254
+ const log = lines.length > 0 ? [...state.log, ...lines].slice(-2e3) : state.log;
9255
+ set({ log, partial, scroll: state.scroll > 0 ? Math.min(state.scroll + lines.length, log.length) : 0 });
9256
+ },
9257
+ logTail(count2) {
9258
+ const unfinished = sanitizeOutputLine(state.partial, keepColor());
9259
+ return [...state.log, ...unfinished ? [unfinished] : []].slice(-count2);
9260
+ }
9261
+ };
9262
+ }
9263
+ var FLASH_MS = 2e3;
9264
+ function savedAccount() {
9265
+ try {
9266
+ const record = readCliAuthState().git_auth;
9267
+ if (!record) return null;
9268
+ return record.account_slug ? `${record.user_email} (${record.account_slug})` : record.user_email;
9269
+ } catch {
9270
+ return null;
9271
+ }
9272
+ }
9273
+ var DIRECTORY_FACT = {
9274
+ outside_project: "Not a Standard Agents project",
9275
+ inside_project_unlinked: "Standard Agents project with no saved project API key",
9276
+ inside_project_linked: "Linked Standard Agents project"
9277
+ };
9278
+ function createTuiSession(streams = { stdin: process.stdin, stdout: process.stdout }, cwd = process.cwd()) {
9279
+ const { stdin, stdout } = streams;
9280
+ const store = createTuiStore({ account: savedAccount(), directory: path19.basename(cwd) || cwd });
9281
+ const metrics = { viewportRows: 10 };
9282
+ let open = false;
9283
+ let instance;
9284
+ let releaseLines;
9285
+ let stopKeepAlive;
9286
+ let removeListeners;
9287
+ let dismiss;
9288
+ let chooseHome;
9289
+ let settleWizard;
9290
+ let devUrl;
9291
+ let flashTimer;
9292
+ const setPanel = (change) => store.set((state) => ({ panel: change(state.panel) }));
9293
+ const flash = (message) => {
9294
+ store.set({ flash: message });
9295
+ clearTimeout(flashTimer);
9296
+ flashTimer = setTimeout(() => store.set({ flash: void 0 }), FLASH_MS);
9297
+ flashTimer.unref();
9298
+ };
9299
+ const waitForDismiss = () => new Promise((resolve) => {
9300
+ dismiss = resolve;
9301
+ });
9302
+ const interrupt = () => {
9303
+ store.set({ status: { kind: "busy", label: "Stopping", since: Date.now() } });
9304
+ process.kill(process.pid, "SIGINT");
9305
+ };
9306
+ const handleKey = (input, key) => {
9307
+ const { panel, status, scroll, log } = store.getState();
9308
+ const ctrlC = Boolean(key.ctrl && input === "c");
9309
+ if (input.length > 1 && panel.kind !== "wizard" && !key.ctrl && !key.meta) {
9310
+ for (const character of input) handleKey(character, key);
9311
+ return;
9312
+ }
9313
+ if (dismiss) {
9314
+ if (key.return || key.escape || ctrlC || input === "q") {
9315
+ const settle = dismiss;
9316
+ dismiss = void 0;
9317
+ settle();
9318
+ }
9319
+ return;
9320
+ }
9321
+ if (panel.kind === "home") {
9322
+ const count2 = panel.commands.length;
9323
+ if (ctrlC || key.escape || input === "q") chooseHome?.(null);
9324
+ else if (key.return) chooseHome?.(panel.commands[panel.selected]);
9325
+ else if (key.upArrow || input === "k") setPanel(() => ({ ...panel, selected: (panel.selected - 1 + count2) % count2 }));
9326
+ else if (key.downArrow || input === "j") setPanel(() => ({ ...panel, selected: (panel.selected + 1) % count2 }));
9327
+ return;
9328
+ }
9329
+ if (panel.kind === "wizard") {
9330
+ panel.wizard.handleKey(input, key);
9331
+ setPanel(() => ({ ...panel, revision: panel.revision + 1 }));
9332
+ if (panel.wizard.snapshot().outcome) settleWizard?.();
9333
+ return;
9334
+ }
9335
+ if (ctrlC) {
9336
+ interrupt();
9337
+ return;
9338
+ }
9339
+ if (panel.kind === "signIn" && panel.url) {
9340
+ if (input === "o") {
9341
+ void openUrl(panel.url);
9342
+ flash("Opened the sign-in page in your browser");
9343
+ } else if (input === "c") {
9344
+ copyToClipboard(panel.url, (sequence) => stdout.write(sequence));
9345
+ flash("Copied the sign-in URL");
9346
+ }
9347
+ return;
9348
+ }
9349
+ if (panel.kind === "log") {
9350
+ const page = Math.max(1, metrics.viewportRows - 1);
9351
+ if (key.pageUp) store.set({ scroll: Math.min(scroll + page, Math.max(0, log.length - metrics.viewportRows)) });
9352
+ else if (key.pageDown) store.set({ scroll: Math.max(0, scroll - page) });
9353
+ else if (status.kind === "ready" && input === "o" && devUrl) {
9354
+ void openUrl(devUrl);
9355
+ flash("Opened the Builder in your browser");
9356
+ } else if (status.kind === "ready" && input === "q") interrupt();
9357
+ }
9358
+ };
9359
+ const session = {
9360
+ store,
9361
+ get isOpen() {
9362
+ return open;
9363
+ },
9364
+ get reporter() {
9365
+ return reporter;
9366
+ },
9367
+ handleKey,
9368
+ open() {
9369
+ if (open) return;
9370
+ open = true;
9371
+ stdout.write(ENTER_SCREEN);
9372
+ releaseLines = holdLines((kind, message) => {
9373
+ if (kind === "warning") store.set((state) => ({ warnings: [...state.warnings, message] }));
9374
+ });
9375
+ const painter2 = createPainter(stdout);
9376
+ const sink = new FrameSink(stdout.columns, stdout.rows, (frame) => {
9377
+ if (open) painter2.paint(frame);
9378
+ });
9379
+ const resized = () => {
9380
+ painter2.reset();
9381
+ sink.resize(stdout.columns, stdout.rows);
9382
+ };
9383
+ const hangup = () => process.kill(process.pid, "SIGTERM");
9384
+ stdout.on("resize", resized);
9385
+ process.on("exit", session.close);
9386
+ process.on("SIGHUP", hangup);
9387
+ removeListeners = () => {
9388
+ stdout.off("resize", resized);
9389
+ process.off("exit", session.close);
9390
+ process.off("SIGHUP", hangup);
9391
+ };
9392
+ stopKeepAlive = interrupts.onInterrupt(() => {
9393
+ });
9394
+ instance = render(/* @__PURE__ */ jsx(App, { store, metrics, onKey: handleKey }), {
9395
+ // Ink writes whole frames to the sink. The painter owns the real terminal.
9396
+ stdout: sink,
9397
+ stdin,
9398
+ debug: true,
9399
+ exitOnCtrlC: false,
9400
+ patchConsole: false
9401
+ });
9402
+ },
9403
+ close() {
9404
+ if (!open) return;
9405
+ open = false;
9406
+ clearTimeout(flashTimer);
9407
+ removeListeners?.();
9408
+ try {
9409
+ instance?.unmount();
9410
+ } finally {
9411
+ if (stdin.isTTY && stdin.isRaw) stdin.setRawMode(false);
9412
+ stdout.write(LEAVE_SCREEN);
9413
+ releaseLines?.();
9414
+ stopKeepAlive?.();
9415
+ }
9416
+ },
9417
+ home(directory = cwd) {
9418
+ session.open();
9419
+ const context = detectCliDirectoryContext(directory);
9420
+ const account = store.getState().account;
9421
+ const notice = takeDeferredNotice();
9422
+ store.set({
9423
+ title: "",
9424
+ steps: [],
9425
+ warnings: notice ? [notice] : [],
9426
+ status: { kind: "idle", label: "Select a command" },
9427
+ panel: {
9428
+ kind: "home",
9429
+ commands: getHomeCommands(context, account !== null),
9430
+ selected: 0,
9431
+ facts: [["Account", account ?? "Not signed in"], ["Directory", DIRECTORY_FACT[context]]]
9432
+ }
9433
+ });
9434
+ return new Promise((resolve) => {
9435
+ chooseHome = (command) => {
9436
+ chooseHome = void 0;
9437
+ store.set({ panel: { kind: "blank" }, status: { kind: "idle", label: "" } });
9438
+ resolve(command);
9439
+ };
9440
+ });
9441
+ }
9442
+ };
9443
+ const stepLabel = (id, fallback) => store.getState().steps.find((step) => step.id === id)?.label ?? fallback;
9444
+ const reporter = {
9445
+ get fullScreen() {
9446
+ return open;
9447
+ },
9448
+ header: lineReporter.header,
9449
+ begin(title, steps) {
9450
+ session.open();
9451
+ store.set({ title });
9452
+ store.setSteps(steps);
9453
+ if (store.getState().panel.kind === "home") store.set({ panel: { kind: "blank" } });
9454
+ },
9455
+ stepStarted(id, options) {
9456
+ const record = lineReporter.stepStarted(id, options);
9457
+ if (!open) return record;
9458
+ store.setStep(id, "active");
9459
+ store.resetLog();
9460
+ store.set({
9461
+ panel: { kind: "log", title: stepLabel(id, options.label), detail: options.detail, color: false },
9462
+ status: { kind: "busy", label: options.label, since: Date.now() }
9463
+ });
9464
+ return {
9465
+ live: true,
9466
+ output: (chunk) => store.appendLog(chunk),
9467
+ done(message, detail) {
9468
+ record.done(message, detail);
9469
+ store.setStep(id, "done");
9470
+ store.set({ status: { kind: "idle", label: message } });
9471
+ }
9472
+ };
9473
+ },
9474
+ stepDone(id, message) {
9475
+ lineReporter.stepDone(id, message);
9476
+ if (open) store.setStep(id, "done");
9477
+ },
9478
+ signInStarted(id, about) {
9479
+ lineReporter.signInStarted(id, about);
9480
+ if (!open) return;
9481
+ store.setStep(id, "active");
9482
+ store.set({
9483
+ panel: { kind: "signIn", about: about?.terminal, notes: [] },
9484
+ status: { kind: "busy", label: "Starting the sign-in", since: Date.now() }
9485
+ });
9486
+ },
9487
+ async signInUrl(url, skipBrowserOpen) {
9488
+ const show = (launch2) => setPanel((panel) => panel.kind === "signIn" ? { ...panel, url, launch: launch2 } : panel);
9489
+ if (open) show(skipBrowserOpen ? "skipped" : "opened");
9490
+ const launch = await lineReporter.signInUrl(url, skipBrowserOpen);
9491
+ if (open) show(launch);
9492
+ return launch;
9493
+ },
9494
+ waitStarted(options) {
9495
+ const record = lineReporter.waitStarted(options);
9496
+ if (!open) return record;
9497
+ setPanel((panel) => panel.kind === "signIn" ? { ...panel, expiresAt: options.expiresAt } : panel);
9498
+ store.set({ status: { kind: "busy", label: options.label, until: options.expiresAt } });
9499
+ let stopped = false;
9500
+ return {
9501
+ note(message) {
9502
+ if (stopped) return;
9503
+ const note = message.replace(/\s+/g, " ").replace(/(\.{3}|…)$/, "").trim();
9504
+ setPanel((panel) => panel.kind === "signIn" && panel.notes.at(-1) !== note ? { ...panel, notes: [...panel.notes, note] } : panel);
9505
+ store.set((state) => ({ status: { ...state.status, note } }));
9506
+ },
9507
+ stop() {
9508
+ if (stopped) return;
9509
+ stopped = true;
9510
+ record.stop();
9511
+ store.set({ status: { kind: "idle", label: "" } });
9512
+ }
9513
+ };
9514
+ },
9515
+ devServerStarting(id, url) {
9516
+ if (!open) {
9517
+ lineReporter.devServerStarting(id, url);
9518
+ return;
9519
+ }
9520
+ devUrl = url;
9521
+ store.setStep(id, "active");
9522
+ store.resetLog();
9523
+ store.set({
9524
+ panel: { kind: "log", title: "Dev server", detail: url, color: true },
9525
+ status: { kind: "busy", label: "Starting the dev server", since: Date.now() }
9526
+ });
9527
+ },
9528
+ devServerOutput(chunk) {
9529
+ if (open) store.appendLog(chunk);
9530
+ },
9531
+ devServerReady(url) {
9532
+ if (!open) {
9533
+ lineReporter.devServerReady(url);
9534
+ return;
9535
+ }
9536
+ logger.success("Started the dev server");
9537
+ const step = store.getState().steps.find((candidate) => candidate.state === "active");
9538
+ if (step) store.setStep(step.id, "done");
9539
+ store.set({ status: { kind: "ready", label: "Dev server running", note: url, since: Date.now() } });
9540
+ },
9541
+ summary(summary) {
9542
+ lineReporter.summary(summary);
9543
+ setPanel((panel) => panel.kind === "log" ? { ...panel, title: summary.title, detail: void 0, summary } : panel);
9544
+ },
9545
+ async failure(failure, capturedOutput) {
9546
+ await lineReporter.failure(failure, capturedOutput);
9547
+ if (!open) return;
9548
+ store.failActiveStep();
9549
+ const tail = (capturedOutput ?? "").split("\n").map((line) => sanitizeOutputLine(line)).filter(Boolean).slice(-12);
9550
+ store.set({
9551
+ panel: { kind: "failure", failure, tail },
9552
+ status: { kind: "failed", label: "Did not finish", note: "The report stays in your terminal" }
9553
+ });
9554
+ await waitForDismiss();
9555
+ },
9556
+ async confirm(summary) {
9557
+ if (!open) return;
9558
+ const active = store.getState().steps.find((step) => step.state === "active");
9559
+ if (active) store.setStep(active.id, "done");
9560
+ store.set({ account: savedAccount(), panel: { kind: "confirm", summary }, status: { kind: "idle", label: "" } });
9561
+ await waitForDismiss();
9562
+ },
9563
+ async askLocalSetup(config) {
9564
+ const wizard = createLocalInitWizard(config);
9565
+ const result = () => {
9566
+ const outcome = wizard.snapshot().outcome;
9567
+ return outcome?.kind === "done" ? outcome.result : null;
9568
+ };
9569
+ if (wizard.snapshot().outcome) return result();
9570
+ store.setStep("project", "active");
9571
+ store.set({
9572
+ panel: { kind: "wizard", wizard, detected: config.detectedPackageManager, revision: 0 },
9573
+ status: { kind: "idle", label: "Answer the questions to set up the project." }
9574
+ });
9575
+ await new Promise((resolve) => {
9576
+ settleWizard = resolve;
9577
+ });
9578
+ settleWizard = void 0;
9579
+ store.setStep("project", "done");
9580
+ store.set({ panel: { kind: "blank" }, status: { kind: "idle", label: "" } });
9581
+ return result();
9582
+ }
9583
+ };
9584
+ return session;
9585
+ }
9586
+ var shared;
9587
+ function tuiSession() {
9588
+ shared ??= createTuiSession();
9589
+ return shared;
9590
+ }
9591
+ function closeTuiSession() {
9592
+ shared?.close();
9593
+ }
8183
9594
  var DEFAULT_SKILL_NAME = "agentbuilder";
8184
9595
  function resolveCodexHome(env = process.env, homeDir = os5.homedir()) {
8185
9596
  return env.CODEX_HOME || path19.join(homeDir, ".codex");
@@ -8250,7 +9661,7 @@ async function selectInstallTarget(targets) {
8250
9661
  const stdin = process.stdin;
8251
9662
  const stdout = process.stdout;
8252
9663
  let selectedIndex = 0;
8253
- const render3 = (initial = false) => {
9664
+ const render4 = (initial = false) => {
8254
9665
  const lines = [];
8255
9666
  lines.push("Choose where to install the Standard Agents Builder skill:");
8256
9667
  lines.push("");
@@ -8273,7 +9684,7 @@ async function selectInstallTarget(targets) {
8273
9684
  }
8274
9685
  stdout.write(lines.join("\n") + "\n");
8275
9686
  };
8276
- render3(true);
9687
+ render4(true);
8277
9688
  const wasRaw = stdin.isRaw;
8278
9689
  if (stdin.isTTY) {
8279
9690
  stdin.setRawMode(true);
@@ -8289,10 +9700,10 @@ async function selectInstallTarget(targets) {
8289
9700
  const onData = (key) => {
8290
9701
  if (key === "\x1B[A" || key === "k") {
8291
9702
  selectedIndex = (selectedIndex - 1 + targets.length) % targets.length;
8292
- render3();
9703
+ render4();
8293
9704
  } else if (key === "\x1B[B" || key === "j") {
8294
9705
  selectedIndex = (selectedIndex + 1) % targets.length;
8295
- render3();
9706
+ render4();
8296
9707
  } else if (key === "\r" || key === "\n") {
8297
9708
  cleanup();
8298
9709
  resolve(targets[selectedIndex]);
@@ -8963,16 +10374,16 @@ async function loadProjectProviders(projectRoot, scanned, env) {
8963
10374
 
8964
10375
  // src/commands/available-models.ts
8965
10376
  var AvailableModelsError = class extends Error {
8966
- constructor(code, lines) {
10377
+ constructor(code2, lines) {
8967
10378
  super(lines.join("\n"));
8968
- this.code = code;
10379
+ this.code = code2;
8969
10380
  this.name = "AvailableModelsError";
8970
10381
  }
8971
10382
  };
8972
10383
  var CURRENT_MODELS_HINT = `To choose a model ID without a key, run: ${cliCommand("current-models")}
8973
10384
  It prints the current model guide.`;
8974
- function fail(code, lines) {
8975
- throw new AvailableModelsError(code, lines);
10385
+ function fail(code2, lines) {
10386
+ throw new AvailableModelsError(code2, lines);
8976
10387
  }
8977
10388
  function errorMessage2(error, fallback) {
8978
10389
  return error instanceof Error && error.message ? error.message : fallback;
@@ -9189,6 +10600,8 @@ async function availableModels(options = {}) {
9189
10600
  }
9190
10601
 
9191
10602
  // src/commands/diag.ts
10603
+ var say = (text2) => print("stdout", "plain", text2);
10604
+ var complain = (text2) => print("stderr", "plain", text2);
9192
10605
  function resolveDiagConfig(options, env = process.env, fetchImpl) {
9193
10606
  const endpoint = (options.endpoint || env.STANDARD_AGENTS_INSTANCE_URL || "http://localhost:5173").replace(/\/+$/, "");
9194
10607
  const token = options.token || env.STANDARD_AGENTS_INSTANCE_TOKEN || null;
@@ -9200,10 +10613,10 @@ function resolveDiagConfig(options, env = process.env, fetchImpl) {
9200
10613
  return { endpoint, token, json: Boolean(options.json), fetchImpl: resolvedFetch };
9201
10614
  }
9202
10615
  var DiagRequestError = class extends Error {
9203
- constructor(message, status2, code, requestId) {
10616
+ constructor(message, status, code2, requestId) {
9204
10617
  super(message);
9205
- this.status = status2;
9206
- this.code = code;
10618
+ this.status = status;
10619
+ this.code = code2;
9207
10620
  this.requestId = requestId;
9208
10621
  this.name = "DiagRequestError";
9209
10622
  }
@@ -9213,9 +10626,9 @@ function stringField(value, key) {
9213
10626
  const field2 = Reflect.get(value, key);
9214
10627
  return typeof field2 === "string" && field2 ? field2 : null;
9215
10628
  }
9216
- function describeFailedResponse(method, path27, status2, text2) {
10629
+ function describeFailedResponse(method, path28, status, text2) {
9217
10630
  let detail = text2.slice(0, 300);
9218
- let code = null;
10631
+ let code2 = null;
9219
10632
  let requestId = null;
9220
10633
  try {
9221
10634
  const parsed = JSON.parse(text2);
@@ -9223,15 +10636,15 @@ function describeFailedResponse(method, path27, status2, text2) {
9223
10636
  if (typeof error === "string" && error) {
9224
10637
  detail = error;
9225
10638
  } else if (error && typeof error === "object") {
9226
- code = stringField(error, "code");
9227
- detail = stringField(error, "message") ?? code ?? detail;
10639
+ code2 = stringField(error, "code");
10640
+ detail = stringField(error, "message") ?? code2 ?? detail;
9228
10641
  }
9229
10642
  requestId = stringField(parsed, "requestId");
9230
10643
  } catch {
9231
10644
  }
9232
- const context = [code ? `code: ${code}` : null, requestId ? `request ID: ${requestId}` : null].filter(Boolean);
10645
+ const context = [code2 ? `code: ${code2}` : null, requestId ? `request ID: ${requestId}` : null].filter(Boolean);
9233
10646
  const suffix = context.length > 0 ? ` (${context.join(", ")})` : "";
9234
- return new DiagRequestError(`${method} ${path27} \u2192 HTTP ${status2}: ${detail}${suffix}`, status2, code, requestId);
10647
+ return new DiagRequestError(`${method} ${path28} \u2192 HTTP ${status}: ${detail}${suffix}`, status, code2, requestId);
9235
10648
  }
9236
10649
  function diagJsonError(error) {
9237
10650
  const message = error instanceof Error ? error.message : String(error);
@@ -9243,40 +10656,40 @@ function diagJsonError(error) {
9243
10656
  ...error.requestId ? { request_id: error.requestId } : {}
9244
10657
  };
9245
10658
  }
9246
- async function apiGet(config, path27) {
9247
- return apiRequest(config, path27, "GET");
10659
+ async function apiGet(config, path28) {
10660
+ return apiRequest(config, path28, "GET");
9248
10661
  }
9249
- async function apiRequest(config, path27, method, body) {
10662
+ async function apiRequest(config, path28, method, body) {
9250
10663
  const headers = { Accept: "application/json" };
9251
10664
  if (config.token) headers.Authorization = `Bearer ${config.token}`;
9252
10665
  if (body !== void 0) headers["Content-Type"] = "application/json";
9253
10666
  let response;
9254
10667
  try {
9255
- response = await (config.token ? credentialFetch : fetchWithDeadline)(`${config.endpoint}${path27}`, {
10668
+ response = await (config.token ? credentialFetch : fetchWithDeadline)(`${config.endpoint}${path28}`, {
9256
10669
  method,
9257
10670
  headers,
9258
10671
  body: body === void 0 ? void 0 : JSON.stringify(body)
9259
10672
  }, { fetchImpl: config.fetchImpl, next: "Check the instance URL (--endpoint), then run the command again." });
9260
10673
  } catch (error) {
9261
10674
  if (error instanceof RequestTimeoutError) {
9262
- throw new DiagRequestError(`${method} ${path27}: ${error.message.replace("\n", " ")}`, null, "timeout", null);
10675
+ throw new DiagRequestError(`${method} ${path28}: ${error.message.replace("\n", " ")}`, null, "timeout", null);
9263
10676
  }
9264
10677
  if (error instanceof RedirectRefusedError) {
9265
- throw new DiagRequestError(`${method} ${path27}: ${error.message.replace("\n", " ")}`, error.status, "redirect_refused", null);
10678
+ throw new DiagRequestError(`${method} ${path28}: ${error.message.replace("\n", " ")}`, error.status, "redirect_refused", null);
9266
10679
  }
9267
10680
  const cause = error instanceof Error && error.cause instanceof Error ? error.cause.message : null;
9268
10681
  const detail = cause ?? (error instanceof Error ? error.message : String(error));
9269
- throw new DiagRequestError(`${method} ${path27} could not reach ${config.endpoint}: ${detail}`, null, "unreachable", null);
10682
+ throw new DiagRequestError(`${method} ${path28} could not reach ${config.endpoint}: ${detail}`, null, "unreachable", null);
9270
10683
  }
9271
10684
  const text2 = await response.text();
9272
10685
  if (!response.ok) {
9273
- throw describeFailedResponse(method, path27, response.status, text2);
10686
+ throw describeFailedResponse(method, path28, response.status, text2);
9274
10687
  }
9275
10688
  try {
9276
10689
  return JSON.parse(text2);
9277
10690
  } catch {
9278
10691
  throw new Error(
9279
- `${method} ${path27} returned non-JSON (is this a Standard Agents Builder instance URL?): ${text2.slice(0, 120)}`
10692
+ `${method} ${path28} returned non-JSON (is this a Standard Agents Builder instance URL?): ${text2.slice(0, 120)}`
9280
10693
  );
9281
10694
  }
9282
10695
  }
@@ -9365,10 +10778,10 @@ async function resolveThreadId(config, idOrPrefix) {
9365
10778
  const data = await apiGet(config, "/api/threads?limit=100");
9366
10779
  return resolveThreadIdFromList(data.threads ?? [], idOrPrefix);
9367
10780
  }
9368
- function printKeyValues(rows) {
10781
+ function printKeyValues2(rows) {
9369
10782
  const width = Math.max(...rows.map(([k]) => k.length));
9370
10783
  for (const [key, value] of rows) {
9371
- console.log(` ${key.padEnd(width)} ${value}`);
10784
+ say(` ${key.padEnd(width)} ${value}`);
9372
10785
  }
9373
10786
  }
9374
10787
  async function diagInstance(options, fetchImpl) {
@@ -9378,9 +10791,9 @@ async function diagInstance(options, fetchImpl) {
9378
10791
  writeJsonDocument(data);
9379
10792
  return;
9380
10793
  }
9381
- console.log(`Instance ${config.endpoint}`);
10794
+ say(`Instance ${config.endpoint}`);
9382
10795
  if (data.runtime) {
9383
- printKeyValues([
10796
+ printKeyValues2([
9384
10797
  ["builder version", data.runtime.builderVersion],
9385
10798
  ["first-chunk timeout", formatAge(data.runtime.streamFirstChunkTimeoutMs)],
9386
10799
  ["stall timeout", formatAge(data.runtime.streamStallTimeoutMs)],
@@ -9389,12 +10802,12 @@ async function diagInstance(options, fetchImpl) {
9389
10802
  ["config warnings", String(data.warnings?.length ?? 0)]
9390
10803
  ]);
9391
10804
  } else {
9392
- console.log(" builder version pre-0.26 (no runtime block in /api/diagnostics)");
9393
- console.log(` config warnings ${data.warnings?.length ?? 0}`);
10805
+ say(" builder version pre-0.26 (no runtime block in /api/diagnostics)");
10806
+ say(` config warnings ${data.warnings?.length ?? 0}`);
9394
10807
  }
9395
10808
  for (const warning of data.warnings ?? []) {
9396
10809
  if (warning && typeof warning === "object" && "message" in warning && typeof warning.message === "string") {
9397
- console.log(` warning: ${warning.message}`);
10810
+ say(` warning: ${warning.message}`);
9398
10811
  }
9399
10812
  }
9400
10813
  }
@@ -9443,24 +10856,24 @@ async function diagThreads(options, fetchImpl) {
9443
10856
  })),
9444
10857
  ...incomplete ? { error: { code: "incomplete_scan", message: unreadableSummary } } : {}
9445
10858
  });
9446
- if (incomplete) console.error(`diag: ${unreadableSummary}`);
10859
+ if (incomplete) complain(`diag: ${unreadableSummary}`);
9447
10860
  return incomplete ? 1 : 0;
9448
10861
  }
9449
10862
  if (filtered.length === 0) {
9450
- if (!options.stuck) console.log("No threads.");
9451
- else if (unreadable.length === 0) console.log(`No stuck threads in the ${threads.length} most recent.`);
9452
- else console.log(`No stuck threads in the ${threads.length - unreadable.length} threads that could be read.`);
10863
+ if (!options.stuck) say("No threads.");
10864
+ else if (unreadable.length === 0) say(`No stuck threads in the ${threads.length} most recent.`);
10865
+ else say(`No stuck threads in the ${threads.length - unreadable.length} threads that could be read.`);
9453
10866
  }
9454
10867
  for (const { thread, health, detail } of filtered) {
9455
10868
  const marker = health === "stuck" ? "\u2717" : health === "running" ? "\u25CF" : "\u25CB";
9456
- console.log(
10869
+ say(
9457
10870
  `${marker} ${thread.id.slice(0, 8)} ${String(health).toUpperCase().padEnd(10)} ${(thread.agent_id ?? "").padEnd(24)} ${detail}`
9458
10871
  );
9459
10872
  }
9460
10873
  if (unreadable.length > 0) {
9461
- console.error(`diag: ${unreadableSummary}`);
10874
+ complain(`diag: ${unreadableSummary}`);
9462
10875
  if (options.stuck) {
9463
- for (const { thread, detail } of unreadable) console.error(` ${thread.id.slice(0, 8)} ${detail}`);
10876
+ for (const { thread, detail } of unreadable) complain(` ${thread.id.slice(0, 8)} ${detail}`);
9464
10877
  }
9465
10878
  }
9466
10879
  return incomplete ? 1 : 0;
@@ -9474,13 +10887,13 @@ async function diagThread(idOrPrefix, options, fetchImpl) {
9474
10887
  return;
9475
10888
  }
9476
10889
  const { health, detail } = classifyThreadHealth(data);
9477
- console.log(`Thread ${threadId}`);
9478
- console.log(`Health: ${health.toUpperCase()} \u2014 ${detail}
10890
+ say(`Thread ${threadId}`);
10891
+ say(`Health: ${health.toUpperCase()} \u2014 ${detail}
9479
10892
  `);
9480
10893
  const thread = data.thread;
9481
10894
  if (thread) {
9482
- console.log("Execution");
9483
- printKeyValues([
10895
+ say("Execution");
10896
+ printKeyValues2([
9484
10897
  ["executing", String(thread.executing)],
9485
10898
  ["stopped", String(thread.stopped)],
9486
10899
  ["last progress", thread.silenceMs === null ? "\u2014" : `${formatAge(thread.silenceMs)} ago`],
@@ -9491,30 +10904,30 @@ async function diagThread(idOrPrefix, options, fetchImpl) {
9491
10904
  if (thread.contextUsage) {
9492
10905
  const usage = thread.contextUsage;
9493
10906
  const pct = usage.inputTokens && usage.maxContextTokens ? ` (${Math.round(usage.inputTokens / usage.maxContextTokens * 100)}% of window)` : "";
9494
- console.log(`
10907
+ say(`
9495
10908
  Context: ${usage.inputTokens ?? "?"} tokens on ${usage.model ?? "?"}${pct}`);
9496
10909
  }
9497
- console.log(`
10910
+ say(`
9498
10911
  Open request logs (${thread.incompleteLogs.length})`);
9499
10912
  for (const log of thread.incompleteLogs) {
9500
10913
  const age = formatAge(Date.now() - (normalizeTimestampMs(log.created_at) ?? Date.now()));
9501
- console.log(` ${log.id.slice(0, 8)} ${log.model ?? "?"} via ${log.provider ?? "?"} open ${age}`);
10914
+ say(` ${log.id.slice(0, 8)} ${log.model ?? "?"} via ${log.provider ?? "?"} open ${age}`);
9502
10915
  }
9503
- console.log(`
10916
+ say(`
9504
10917
  Alarm queue (${thread.alarmQueue.length} recent rows)`);
9505
10918
  for (const row of thread.alarmQueue.slice(0, 12)) {
9506
10919
  const scheduled = formatAge(Date.now() - (normalizeTimestampMs(row.scheduled_at) ?? Date.now()));
9507
10920
  const error = row.error ? ` error: ${row.error.slice(0, 60)}` : "";
9508
- console.log(
10921
+ say(
9509
10922
  ` ${row.method.padEnd(18)} ${row.status.padEnd(11)} attempts=${row.attempts} scheduled ${scheduled} ago${error}`
9510
10923
  );
9511
10924
  }
9512
10925
  }
9513
- console.log(`
10926
+ say(`
9514
10927
  Watchdog ${data.watchdog ? data.watchdog.armed ? "(armed)" : "(standing down)" : "(companion not available)"}`);
9515
10928
  for (const checkin of data.watchdog?.history?.slice(0, 5) ?? []) {
9516
10929
  const at = new Date(checkin.at).toISOString().slice(11, 19);
9517
- console.log(` ${at} ${checkin.verdict.padEnd(12)} ${checkin.action}`);
10930
+ say(` ${at} ${checkin.verdict.padEnd(12)} ${checkin.action}`);
9518
10931
  }
9519
10932
  }
9520
10933
  async function diagLogs(idOrPrefix, logId, options, fetchImpl) {
@@ -9527,7 +10940,7 @@ async function diagLogs(idOrPrefix, logId, options, fetchImpl) {
9527
10940
  return;
9528
10941
  }
9529
10942
  const detail = log.log ?? log;
9530
- printKeyValues(
10943
+ printKeyValues2(
9531
10944
  [
9532
10945
  ["id", String(detail.id ?? logId)],
9533
10946
  ["complete", String(detail.is_complete)],
@@ -9553,7 +10966,7 @@ async function diagLogs(idOrPrefix, logId, options, fetchImpl) {
9553
10966
  for (const log of data.logs ?? []) {
9554
10967
  const open = log.is_complete ? " " : "\u25B6";
9555
10968
  const err = log.error_type ? ` [${log.error_type}]` : "";
9556
- console.log(`${open} ${String(log.id).slice(0, 8)} ${log.model} in=${log.input_tokens ?? "\u2014"} out=${log.output_tokens ?? "\u2014"}${err}`);
10969
+ say(`${open} ${String(log.id).slice(0, 8)} ${log.model} in=${log.input_tokens ?? "\u2014"} out=${log.output_tokens ?? "\u2014"}${err}`);
9557
10970
  }
9558
10971
  }
9559
10972
  async function diagRevive(idOrPrefix, options, fetchImpl) {
@@ -9568,10 +10981,10 @@ async function diagRevive(idOrPrefix, options, fetchImpl) {
9568
10981
  writeJsonDocument(result);
9569
10982
  return;
9570
10983
  }
9571
- console.log(`Verdict: ${result.verdict}`);
9572
- console.log(`Action: ${result.action}`);
9573
- if (result.incompleteLogs) console.log(`Finalized/open logs: ${result.incompleteLogs}`);
9574
- if (result.requestRestart) console.log("A wedged execution was taken over; the DO was restarted.");
10984
+ say(`Verdict: ${result.verdict}`);
10985
+ say(`Action: ${result.action}`);
10986
+ if (result.incompleteLogs) say(`Finalized/open logs: ${result.incompleteLogs}`);
10987
+ if (result.requestRestart) say("A wedged execution was taken over; the DO was restarted.");
9575
10988
  }
9576
10989
  var NORMAL_CLOSE_CODES = /* @__PURE__ */ new Set([1e3, 1005]);
9577
10990
  function summarizeFrame(raw) {
@@ -9596,29 +11009,29 @@ async function diagTail(idOrPrefix, options, fetchImpl, socketConstructor) {
9596
11009
  if (!WebSocketCtor) {
9597
11010
  throw new Error("WebSocket is not available in this Node runtime (need Node 22+)");
9598
11011
  }
9599
- const status2 = config.json ? console.error : console.log;
9600
- status2(`Tailing ${threadId} \u2014 Ctrl-C to stop`);
11012
+ const status = config.json ? complain : say;
11013
+ status(`Tailing ${threadId} \u2014 Ctrl-C to stop`);
9601
11014
  const ws = new WebSocketCtor(wsUrl);
9602
11015
  return new Promise((resolve) => {
9603
- ws.onopen = () => status2("connected");
11016
+ ws.onopen = () => status("connected");
9604
11017
  ws.onclose = (event) => {
9605
11018
  if (NORMAL_CLOSE_CODES.has(event.code)) {
9606
- status2("closed");
11019
+ status("closed");
9607
11020
  resolve(0);
9608
11021
  return;
9609
11022
  }
9610
11023
  const reason = event.reason ? `: ${event.reason}` : "";
9611
- console.error(`diag: the log stream closed abnormally (code ${event.code}${reason})`);
11024
+ complain(`diag: the log stream closed abnormally (code ${event.code}${reason})`);
9612
11025
  resolve(1);
9613
11026
  };
9614
11027
  ws.onerror = () => {
9615
- console.error("websocket error");
11028
+ complain("websocket error");
9616
11029
  resolve(1);
9617
11030
  };
9618
11031
  ws.onmessage = (event) => {
9619
11032
  const raw = typeof event.data === "string" ? event.data : "";
9620
11033
  if (!config.json) {
9621
- console.log(summarizeFrame(raw));
11034
+ say(summarizeFrame(raw));
9622
11035
  return;
9623
11036
  }
9624
11037
  try {
@@ -9626,7 +11039,7 @@ async function diagTail(idOrPrefix, options, fetchImpl, socketConstructor) {
9626
11039
  process.stdout.write(`${/[\r\n]/.test(raw) ? JSON.stringify(frame) : raw}
9627
11040
  `);
9628
11041
  } catch {
9629
- console.error(`diag: skipped a frame that is not JSON: ${raw.slice(0, 160)}`);
11042
+ complain(`diag: skipped a frame that is not JSON: ${raw.slice(0, 160)}`);
9630
11043
  }
9631
11044
  };
9632
11045
  });
@@ -9667,7 +11080,7 @@ function wrapDiagAction(action, streamsFrames = false) {
9667
11080
  const exitCode = await action(...args);
9668
11081
  if (exitCode) process.exitCode = exitCode;
9669
11082
  } catch (error) {
9670
- console.error(`diag: ${error instanceof Error ? error.message : String(error)}`);
11083
+ complain(`diag: ${error instanceof Error ? error.message : String(error)}`);
9671
11084
  if (json && !streamsFrames) writeJsonDocument({ error: diagJsonError(error) });
9672
11085
  process.exitCode = 1;
9673
11086
  }
@@ -9781,7 +11194,7 @@ function parsePlatformError(body) {
9781
11194
  reason: details ? stringField2(details, "reason") : null
9782
11195
  };
9783
11196
  }
9784
- async function requestLegal(config, path27, init2) {
11197
+ async function requestLegal(config, path28, init2) {
9785
11198
  const fetchImpl = config.fetchImpl ?? fetch;
9786
11199
  const headers = {
9787
11200
  Accept: "application/json",
@@ -9791,7 +11204,7 @@ async function requestLegal(config, path27, init2) {
9791
11204
  if (init2.body !== void 0) headers["Content-Type"] = "application/json";
9792
11205
  let response;
9793
11206
  try {
9794
- response = await platformFetch(config.endpoint, path27, {
11207
+ response = await platformFetch(config.endpoint, path28, {
9795
11208
  method: init2.method,
9796
11209
  headers,
9797
11210
  // The cookie belongs to this endpoint only; never follow it elsewhere.
@@ -10097,23 +11510,23 @@ async function termsAccept(options, deps) {
10097
11510
  }
10098
11511
  const interactive = !options.json && !options.agree && (deps.isTTY ?? false);
10099
11512
  const confirm = deps.confirm ?? defaultConfirm;
10100
- const showForReview = (current) => {
11513
+ const showForReview = (current2) => {
10101
11514
  if (options.json) return;
10102
- printDocuments(io, current);
11515
+ printDocuments(io, current2);
10103
11516
  io.out("");
10104
- io.out(printable(current.acknowledgement));
11517
+ io.out(printable(current2.acknowledgement));
10105
11518
  io.out("");
10106
11519
  };
10107
- const confirmationNeeded = (current, code, reason) => {
10108
- const command = acceptCommand(current, options);
11520
+ const confirmationNeeded = (current2, code2, reason) => {
11521
+ const command = acceptCommand(current2, options);
10109
11522
  const next = command ? "To accept these versions, run:" : `Run this in a terminal to accept these versions: ${cliCommand("terms accept")}`;
10110
11523
  if (options.json) {
10111
11524
  io.json({
10112
11525
  ok: false,
10113
- error: { code, message: command ? `${reason} ${next} ${command}` : `${reason} ${next}` },
11526
+ error: { code: code2, message: command ? `${reason} ${next} ${command}` : `${reason} ${next}` },
10114
11527
  instruction: AGENT_INSTRUCTION,
10115
11528
  accept_command: command,
10116
- legal: current
11529
+ legal: current2
10117
11530
  });
10118
11531
  } else {
10119
11532
  io.err(reason);
@@ -10125,7 +11538,7 @@ async function termsAccept(options, deps) {
10125
11538
  };
10126
11539
  if (options.agree) {
10127
11540
  const reviewed = { terms: options.termsVersion, privacy: options.privacyVersion };
10128
- const current = shownVersions(legal);
11541
+ const current2 = shownVersions(legal);
10129
11542
  if (!reviewed.terms || !reviewed.privacy) {
10130
11543
  showForReview(legal);
10131
11544
  return confirmationNeeded(
@@ -10134,7 +11547,7 @@ async function termsAccept(options, deps) {
10134
11547
  "Nothing was accepted. `--agree` needs `--terms-version` and `--privacy-version` with the versions the person reviewed."
10135
11548
  );
10136
11549
  }
10137
- if (reviewed.terms !== current.terms || reviewed.privacy !== current.privacy) {
11550
+ if (reviewed.terms !== current2.terms || reviewed.privacy !== current2.privacy) {
10138
11551
  if (!options.json) {
10139
11552
  io.out("The documents changed. These are the current versions:");
10140
11553
  io.out("");
@@ -10254,7 +11667,7 @@ async function termsAccept(options, deps) {
10254
11667
  io.err("Nothing was accepted, because the documents kept changing. Run the command again.");
10255
11668
  return TERMS_EXIT.confirmationNeeded;
10256
11669
  }
10257
- function registerTermsCommand(program2, cliVersion2) {
11670
+ function registerTermsCommand(program2, cliVersion3) {
10258
11671
  const withCommonOptions = (cmd) => addPlatformEndpointOption(
10259
11672
  cmd.option("--json", "Print stable JSON and never prompt"),
10260
11673
  "Platform API endpoint (default: the endpoint of your saved sign-in)"
@@ -10262,7 +11675,7 @@ function registerTermsCommand(program2, cliVersion2) {
10262
11675
  const run2 = (action) => async (_options, command) => {
10263
11676
  const options = command.optsWithGlobals();
10264
11677
  process.exitCode = await action(options, {
10265
- cliVersion: cliVersion2,
11678
+ cliVersion: cliVersion3,
10266
11679
  isTTY: Boolean(process.stdin.isTTY && process.stdout.isTTY)
10267
11680
  });
10268
11681
  };
@@ -10298,7 +11711,7 @@ async function settleStdinForInitHandoff(stdin = process.stdin) {
10298
11711
  }
10299
11712
  }
10300
11713
  var program = new Command();
10301
- program.name("agents").description("CLI tool for Standard Agents Builder").version("0.45.9").exitOverride();
11714
+ program.name("agents").description("CLI tool for Standard Agents Builder").version("0.45.11").option(NO_TUI_FLAG, "Print lines instead of the full-screen app (also: NO_TUI=1)").exitOverride();
10302
11715
  registerInitCommand(program);
10303
11716
  registerLoginCommands(program);
10304
11717
  addPlatformEndpointOption(
@@ -10323,33 +11736,51 @@ program.command("skill").description("Install the bundled Standard Agents Builde
10323
11736
  program.command("current-models").description("Print the live curated model guide from standardagentspec.org (standardagentspec.com when that request fails)").option("--url <url>", "Request this models markdown URL instead").action(currentModels);
10324
11737
  program.command("available-models").description("List the model IDs of one provider in the current project, using its own key or the project's Standard Agents account key").option("--provider <provider>", "Provider to query: an installed provider package such as openai, or a provider defined in agents/providers/").option("--json", "Print the provider and its models as one JSON document on stdout").action(availableModels);
10325
11738
  registerDiagCommand(program);
10326
- registerTermsCommand(program, "0.45.9");
11739
+ registerTermsCommand(program, "0.45.11");
10327
11740
  async function run() {
10328
11741
  const userArgs = process.argv.slice(2);
11742
+ const isInteractiveTerminal3 = Boolean(process.stdin.isTTY && process.stdout.isTTY);
10329
11743
  if (userArgs[0] !== "git-credential") {
10330
- assertSupportedNodeVersion();
11744
+ const printsHeader = isInteractiveTerminal3 && (userArgs.length === 0 || userArgs[0] === "init" || userArgs[0] === "login");
11745
+ assertSupportedNodeVersion({ deferUntested: printsHeader });
11746
+ }
11747
+ const fullScreen = shouldUseTui();
11748
+ if (fullScreen) setFlowReporter(tuiSession().reporter);
11749
+ const commandArgs = userArgs.filter((arg) => arg !== NO_TUI_FLAG);
11750
+ if (commandArgs.length === 0 && isInteractiveTerminal3 && fullScreen) {
11751
+ const session = tuiSession();
11752
+ const command = await session.home();
11753
+ if (!command?.inApp) session.close();
11754
+ if (!command) return;
11755
+ try {
11756
+ await program.parseAsync(command.argv, { from: "user" });
11757
+ } finally {
11758
+ session.close();
11759
+ }
11760
+ return;
10331
11761
  }
10332
- const isInteractiveTerminal3 = Boolean(process.stdin.isTTY && process.stdout.isTTY);
10333
- if (userArgs.length === 0 && isInteractiveTerminal3) {
11762
+ if (commandArgs.length === 0 && isInteractiveTerminal3) {
10334
11763
  while (true) {
10335
11764
  const selection = await runHomeTui();
10336
11765
  if (!selection) return;
10337
- if (selection.preserveTuiScreen) {
11766
+ if (selection.runsInit) {
10338
11767
  await settleStdinForInitHandoff();
10339
- process.stdout.write("\x1B[2J\x1B[H");
10340
- try {
10341
- await init();
10342
- } finally {
10343
- restoreTuiTerminal();
10344
- }
11768
+ await init();
10345
11769
  return;
10346
11770
  }
10347
11771
  await program.parseAsync(selection.argv, { from: "user" });
10348
11772
  return;
10349
11773
  }
10350
11774
  }
10351
- await program.parseAsync(process.argv);
11775
+ try {
11776
+ await program.parseAsync(process.argv);
11777
+ } finally {
11778
+ closeTuiSession();
11779
+ }
10352
11780
  }
10353
- run().catch((error) => exitWithFatalError(error, process.argv.slice(2)));
11781
+ run().catch((error) => {
11782
+ closeTuiSession();
11783
+ return exitWithFatalError(error, process.argv.slice(2));
11784
+ });
10354
11785
  //# sourceMappingURL=index.js.map
10355
11786
  //# sourceMappingURL=index.js.map