@gravity-rail/cli 4.0.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -280,7 +280,7 @@ import lockfile from "proper-lockfile";
280
280
  // package.json
281
281
  var package_default = {
282
282
  name: "@gravity-rail/cli",
283
- version: "4.0.0",
283
+ version: "6.0.0",
284
284
  description: "Gravity Rail CLI \u2014 manage workspaces from the command line",
285
285
  type: "module",
286
286
  bin: {
@@ -330,13 +330,13 @@ var package_default = {
330
330
  dependencies: {
331
331
  "@gravity-rail/sdk": "workspace:^",
332
332
  "js-yaml": "^5.5.0",
333
- "libphonenumber-js": "^1.13.15",
333
+ "libphonenumber-js": "^1.13.16",
334
334
  "proper-lockfile": "^4.1.2"
335
335
  },
336
336
  devDependencies: {
337
337
  "@gravity-rail/sandbox": "workspace:*",
338
338
  "@types/jest": "^30.0.0",
339
- "@types/node": "^26.6.5",
339
+ "@types/node": "^26.6.6",
340
340
  "@types/proper-lockfile": "^4.1.4",
341
341
  jest: "^30.5.2",
342
342
  "ts-jest": "29.4.9",
@@ -1397,6 +1397,853 @@ function clearScreen() {
1397
1397
  process.stdout.write("\x1B[2J\x1B[H");
1398
1398
  }
1399
1399
 
1400
+ // src/cli-utils/agui.ts
1401
+ import {
1402
+ isProposedMessageSettlementStatus
1403
+ } from "@gravity-rail/sdk";
1404
+
1405
+ // src/lib/context.ts
1406
+ import { GravityRailClient as GravityRailClient3 } from "@gravity-rail/sdk";
1407
+ import { homedir } from "os";
1408
+
1409
+ // src/lib/jq.ts
1410
+ import { spawnSync } from "child_process";
1411
+
1412
+ // src/lib/errors.ts
1413
+ var CLIError = class extends Error {
1414
+ constructor(message, exitCode = 1) {
1415
+ super(message);
1416
+ this.exitCode = exitCode;
1417
+ this.name = "CLIError";
1418
+ }
1419
+ exitCode;
1420
+ };
1421
+ var AuthRequiredError = class extends CLIError {
1422
+ constructor(message = "Not authenticated. Run `gr login` or set GRAVITY_RAIL_API_KEY.") {
1423
+ super(message, 2);
1424
+ this.name = "AuthRequiredError";
1425
+ }
1426
+ };
1427
+ function unauthorizedHint() {
1428
+ return sandboxBrokerUrl() ? "session_credential" : "login";
1429
+ }
1430
+ var UNAUTHORIZED_HINT_TEXT = {
1431
+ login: 'Run "gr login" to authenticate, or set GRAVITY_RAIL_API_KEY for non-interactive use.',
1432
+ session_credential: "This session's credential does not allow this request. Logging in or setting an API key does not change that. Organization commands are outside a workspace session."
1433
+ };
1434
+ function handleError(err) {
1435
+ if (err instanceof CLIError) {
1436
+ process.stderr.write(`Error: ${err.message}
1437
+ `);
1438
+ process.exit(err.exitCode);
1439
+ }
1440
+ if (err instanceof Error) {
1441
+ process.stderr.write(`Error: ${err.message}
1442
+ `);
1443
+ if ("errors" in err && Array.isArray(err.errors)) {
1444
+ for (const e of err.errors) {
1445
+ process.stderr.write(` - ${e}
1446
+ `);
1447
+ }
1448
+ }
1449
+ if ("statusCode" in err && err.statusCode === 401) {
1450
+ process.stderr.write(`
1451
+ Hint: ${UNAUTHORIZED_HINT_TEXT[unauthorizedHint()]}
1452
+ `);
1453
+ }
1454
+ process.exit(1);
1455
+ }
1456
+ process.stderr.write(`Error: ${String(err)}
1457
+ `);
1458
+ process.exit(1);
1459
+ }
1460
+
1461
+ // src/lib/jq.ts
1462
+ function applyJqFilter(json, filter) {
1463
+ const result = spawnSync("jq", ["-r", filter], {
1464
+ input: json,
1465
+ encoding: "utf8",
1466
+ maxBuffer: 64 * 1024 * 1024
1467
+ });
1468
+ if (result.error && result.error.code === "ENOENT") {
1469
+ throw new CLIError(
1470
+ "--jq requires the `jq` binary on PATH, and it was not found. Install jq, or omit --jq and filter the JSON yourself."
1471
+ );
1472
+ }
1473
+ const wroteToExitedJq = result.error?.code === "EPIPE" && result.status !== null;
1474
+ if (result.error && !wroteToExitedJq) {
1475
+ throw new CLIError(`--jq could not run jq: ${result.error.message}`);
1476
+ }
1477
+ if (result.status !== 0) {
1478
+ const exited = result.signal ? `jq was killed by ${result.signal}` : `jq exited ${result.status}`;
1479
+ const detail = (result.stderr || "").trim() || exited;
1480
+ throw new CLIError(`--jq filter failed: ${detail}`);
1481
+ }
1482
+ return (result.stdout || "").replace(/\n$/, "");
1483
+ }
1484
+
1485
+ // src/lib/pagination.ts
1486
+ function isListResult(data) {
1487
+ if (!data || typeof data !== "object" || Array.isArray(data)) return false;
1488
+ const obj = data;
1489
+ return Array.isArray(obj.items) && ("supportsAll" in obj || "meta" in obj && (obj.meta === void 0 || typeof obj.meta === "object"));
1490
+ }
1491
+ function isPagePaginatedResponse(data) {
1492
+ if (!data || typeof data !== "object") return false;
1493
+ const obj = data;
1494
+ if (!Array.isArray(obj.items) || typeof obj.page !== "number") return false;
1495
+ if (typeof obj.totalPages === "number") return true;
1496
+ if (typeof obj.total === "number" && typeof obj.pageSize === "number") return true;
1497
+ return false;
1498
+ }
1499
+ function isCursorPaginatedResponse(data) {
1500
+ if (!data || typeof data !== "object") return false;
1501
+ const obj = data;
1502
+ return Array.isArray(obj.items) && typeof obj.hasMore === "boolean";
1503
+ }
1504
+ function isPaginatedResponse(data) {
1505
+ return isPagePaginatedResponse(data) || isCursorPaginatedResponse(data);
1506
+ }
1507
+ function extractPaginationMeta(data) {
1508
+ if (isPagePaginatedResponse(data)) {
1509
+ const totalPages = data.totalPages ?? (data.pageSize ? Math.ceil(data.total / data.pageSize) : void 0);
1510
+ return {
1511
+ total: data.total,
1512
+ page: data.page,
1513
+ totalPages
1514
+ };
1515
+ }
1516
+ if (isCursorPaginatedResponse(data)) {
1517
+ return {
1518
+ hasMore: data.hasMore,
1519
+ nextCursor: data.nextCursor
1520
+ };
1521
+ }
1522
+ return void 0;
1523
+ }
1524
+ function formatPaginationWarning(meta, supportsAll = true) {
1525
+ if (!meta) return void 0;
1526
+ const allHint = supportsAll ? " Use --all to fetch all pages." : "";
1527
+ if (meta.totalPages !== void 0 && meta.totalPages > 1) {
1528
+ const pageNum = meta.page ?? 1;
1529
+ return `Showing page ${pageNum} of ${meta.totalPages} (${meta.total} total items).${allHint}`;
1530
+ }
1531
+ if (meta.hasMore === true) {
1532
+ return `More results available.${allHint}`;
1533
+ }
1534
+ return void 0;
1535
+ }
1536
+ function unwrapItems(data) {
1537
+ if (Array.isArray(data)) return data;
1538
+ if (data && typeof data === "object" && "items" in data && Array.isArray(data.items)) {
1539
+ return data.items;
1540
+ }
1541
+ return [data];
1542
+ }
1543
+ var LIST_PAGINATION_ARGS = [
1544
+ { name: "page", description: "Page number" },
1545
+ { name: "page-size", description: "Page size" },
1546
+ { name: "all", description: "Fetch all pages and return combined results", isFlag: true }
1547
+ ];
1548
+ function parsePaginationArgs(args) {
1549
+ const result = {};
1550
+ if (args.all === true) {
1551
+ result.all = true;
1552
+ }
1553
+ if (args.page !== void 0) {
1554
+ const num = Number(args.page);
1555
+ if (isNaN(num) || num < 1) throw new CLIError("--page must be a positive integer");
1556
+ result.page = num;
1557
+ }
1558
+ if (args["page-size"] !== void 0) {
1559
+ const num = Number(args["page-size"]);
1560
+ if (isNaN(num) || num < 1) throw new CLIError("--page-size must be a positive integer");
1561
+ if (num > 100) throw new CLIError("--page-size must be at most 100 (API limit)");
1562
+ result.pageSize = num;
1563
+ }
1564
+ return result;
1565
+ }
1566
+ var MAX_PAGE_SIZE = 100;
1567
+ var MAX_PAGES = 200;
1568
+ async function fetchAllPages(fetcher) {
1569
+ const allItems = [];
1570
+ let page = 1;
1571
+ while (page <= MAX_PAGES) {
1572
+ const result = await fetcher({ page, pageSize: MAX_PAGE_SIZE });
1573
+ const items = unwrapItems(result);
1574
+ allItems.push(...items);
1575
+ const meta = extractPaginationMeta(result);
1576
+ if (meta?.totalPages !== void 0) {
1577
+ if (page >= meta.totalPages) break;
1578
+ } else if (!isPagePaginatedResponse(result)) {
1579
+ if (items.length < MAX_PAGE_SIZE) break;
1580
+ }
1581
+ if (page === MAX_PAGES) {
1582
+ throw new CLIError(
1583
+ `Reached maximum page limit (${MAX_PAGES}). Results may be incomplete.`
1584
+ );
1585
+ }
1586
+ page++;
1587
+ }
1588
+ return allItems;
1589
+ }
1590
+ async function fetchAllCursorPages(fetcher) {
1591
+ const allItems = [];
1592
+ let cursor;
1593
+ let pages = 0;
1594
+ while (pages < MAX_PAGES) {
1595
+ const result = await fetcher({ cursor });
1596
+ const items = unwrapItems(result);
1597
+ allItems.push(...items);
1598
+ pages++;
1599
+ if (isCursorPaginatedResponse(result) && result.hasMore && result.nextCursor) {
1600
+ cursor = result.nextCursor;
1601
+ } else {
1602
+ break;
1603
+ }
1604
+ if (pages === MAX_PAGES) {
1605
+ throw new CLIError(
1606
+ `Reached maximum page limit (${MAX_PAGES}). Results may be incomplete.`
1607
+ );
1608
+ }
1609
+ }
1610
+ return allItems;
1611
+ }
1612
+ function listResult(data, supportsAll = false) {
1613
+ return {
1614
+ items: unwrapItems(data),
1615
+ meta: extractPaginationMeta(data),
1616
+ supportsAll
1617
+ };
1618
+ }
1619
+
1620
+ // src/lib/output.ts
1621
+ function writeJson(value, opts, pretty = true) {
1622
+ const json = pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value);
1623
+ if (opts.jq) {
1624
+ const filtered = applyJqFilter(json, opts.jq);
1625
+ process.stdout.write(filtered === "" ? "\n" : filtered + "\n");
1626
+ return;
1627
+ }
1628
+ process.stdout.write(json + "\n");
1629
+ }
1630
+ function detectOutputFormat(explicit) {
1631
+ if (explicit) return explicit;
1632
+ return process.stdout.isTTY ? "table" : "json";
1633
+ }
1634
+ function outputData(data, opts, columns, paginationMeta, supportsAll) {
1635
+ let items;
1636
+ let meta;
1637
+ let allSupported;
1638
+ if (isListResult(data)) {
1639
+ items = data.items;
1640
+ meta = data.meta;
1641
+ allSupported = data.supportsAll ?? false;
1642
+ } else {
1643
+ items = unwrapItems(data);
1644
+ meta = paginationMeta ?? extractPaginationMeta(data);
1645
+ allSupported = supportsAll ?? false;
1646
+ }
1647
+ const warning = formatPaginationWarning(meta, allSupported);
1648
+ if (warning) {
1649
+ process.stderr.write(warning + "\n");
1650
+ }
1651
+ if (opts.jq) {
1652
+ writeJson(items, opts);
1653
+ return;
1654
+ }
1655
+ switch (opts.outputFormat) {
1656
+ case "json":
1657
+ writeJson(items, opts);
1658
+ break;
1659
+ case "jsonl":
1660
+ for (const item of items) {
1661
+ process.stdout.write(JSON.stringify(item) + "\n");
1662
+ }
1663
+ break;
1664
+ case "table":
1665
+ if (columns) {
1666
+ printTable(items, columns);
1667
+ } else {
1668
+ writeJson(items, opts);
1669
+ }
1670
+ break;
1671
+ }
1672
+ }
1673
+ function outputSingle(data, opts, columns) {
1674
+ if (opts.jq) {
1675
+ writeJson(data, opts);
1676
+ return;
1677
+ }
1678
+ switch (opts.outputFormat) {
1679
+ case "json":
1680
+ writeJson(data, opts);
1681
+ break;
1682
+ case "jsonl":
1683
+ process.stdout.write(JSON.stringify(data) + "\n");
1684
+ break;
1685
+ case "table":
1686
+ if (columns) {
1687
+ printTable([data], columns);
1688
+ } else {
1689
+ writeJson(data, opts);
1690
+ }
1691
+ break;
1692
+ }
1693
+ }
1694
+ var COL = {
1695
+ id: () => ({ header: "ID", getValue: (item) => String(item.id ?? "") }),
1696
+ uuid: () => ({ header: "UUID", getValue: (item) => item.uuid ?? "" }),
1697
+ name: () => ({ header: "NAME", getValue: (item) => item.name ?? "" }),
1698
+ status: () => ({ header: "STATUS", getValue: (item) => item.status ?? "" }),
1699
+ created: () => ({
1700
+ header: "CREATED",
1701
+ getValue: (item) => item.createdAt ?? ""
1702
+ }),
1703
+ updated: () => ({
1704
+ header: "UPDATED",
1705
+ getValue: (item) => item.updatedAt ?? ""
1706
+ }),
1707
+ description: () => ({
1708
+ header: "DESCRIPTION",
1709
+ getValue: (item) => item.description ?? ""
1710
+ }),
1711
+ enabled: () => ({
1712
+ header: "ENABLED",
1713
+ getValue: (item) => String(item.enabled ?? "")
1714
+ })
1715
+ };
1716
+ function hint(opts, lines) {
1717
+ if ((opts.outputFormat ?? "table") !== "table") return;
1718
+ process.stdout.write("\n" + lines.join("\n") + "\n");
1719
+ }
1720
+ function stderr2(msg) {
1721
+ process.stderr.write(msg + "\n");
1722
+ }
1723
+ async function flushStdout() {
1724
+ if (process.stdout.writableLength === 0) return;
1725
+ await new Promise((resolve3) => {
1726
+ process.stdout.write("", () => resolve3());
1727
+ });
1728
+ }
1729
+
1730
+ // src/lib/org-auth.ts
1731
+ import { createServer as createServer2 } from "http";
1732
+ import { execFile } from "child_process";
1733
+ import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
1734
+ var OrgSignInResponseError = class extends Error {
1735
+ };
1736
+ var ORG_AUTH_TIMEOUT_MS = 5 * 60 * 1e3;
1737
+ var ORG_SESSION_CACHE_TTL_MS = 6.5 * 24 * 60 * 60 * 1e3;
1738
+ var CLI_ORG_AUTH_BRIDGE_PATH = "/cli/org-auth";
1739
+ var ORG_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1740
+ async function tryDirectJoin(apiUrl, accessToken, orgAuthInfo) {
1741
+ const response = await fetch(`${apiUrl}/api/v2/o/${orgAuthInfo.orgUuid}/join`, {
1742
+ method: "POST",
1743
+ headers: {
1744
+ "Content-Type": "application/json",
1745
+ Authorization: `Bearer ${accessToken}`
1746
+ },
1747
+ body: "{}"
1748
+ });
1749
+ if (response.status === 400) {
1750
+ return null;
1751
+ }
1752
+ if (!response.ok) {
1753
+ throw new Error(`Org join failed (HTTP ${response.status})`);
1754
+ }
1755
+ let body;
1756
+ try {
1757
+ body = await response.json();
1758
+ } catch {
1759
+ throw new OrgSignInResponseError("Org join succeeded but returned an invalid response");
1760
+ }
1761
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
1762
+ throw new OrgSignInResponseError("Org join succeeded but returned an invalid response");
1763
+ }
1764
+ if (typeof body.orgSession !== "string" || !body.orgSession) {
1765
+ throw new OrgSignInResponseError("Org join succeeded but returned no org session");
1766
+ }
1767
+ let expiresAt;
1768
+ if (body.expiresAt !== void 0) {
1769
+ if (typeof body.expiresAt !== "string" || !Number.isFinite(Date.parse(body.expiresAt))) {
1770
+ throw new OrgSignInResponseError("Org join returned an invalid session expiry");
1771
+ }
1772
+ expiresAt = body.expiresAt;
1773
+ if (Date.parse(expiresAt) <= Date.now()) {
1774
+ throw new OrgSignInResponseError("Org join returned an expired session");
1775
+ }
1776
+ }
1777
+ return { session: body.orgSession, expiresAt };
1778
+ }
1779
+ function isAllowedAuthUrl(url, apiUrl, frontendUrl) {
1780
+ try {
1781
+ const parsed = new URL(url);
1782
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return false;
1783
+ const allowedHosts = [apiUrl, frontendUrl].filter((u) => Boolean(u)).map((u) => {
1784
+ try {
1785
+ return new URL(u).hostname;
1786
+ } catch {
1787
+ return void 0;
1788
+ }
1789
+ }).filter((h) => Boolean(h));
1790
+ return allowedHosts.includes(parsed.hostname);
1791
+ } catch {
1792
+ return false;
1793
+ }
1794
+ }
1795
+ function openBrowser2(url) {
1796
+ let command;
1797
+ let args;
1798
+ if (process.platform === "darwin") {
1799
+ command = "open";
1800
+ args = [url];
1801
+ } else if (process.platform === "win32") {
1802
+ command = "cmd.exe";
1803
+ args = ["/c", "start", "", url];
1804
+ } else {
1805
+ command = "xdg-open";
1806
+ args = [url];
1807
+ }
1808
+ execFile(command, args, (_err) => {
1809
+ });
1810
+ }
1811
+ function isHeadless() {
1812
+ if (process.env.GRAVITY_RAIL_NO_BROWSER) return true;
1813
+ if (process.platform === "linux") {
1814
+ return !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY;
1815
+ }
1816
+ return false;
1817
+ }
1818
+ function startOrgSessionCapture(expectedState, expectedOrgUuid, _allowedOrigin) {
1819
+ let resolveSession;
1820
+ let rejectSession;
1821
+ const session = new Promise((resolve3, reject) => {
1822
+ resolveSession = resolve3;
1823
+ rejectSession = reject;
1824
+ });
1825
+ const server = createServer2((req, res) => {
1826
+ res.setHeader("Cache-Control", "no-store");
1827
+ res.setHeader("Referrer-Policy", "no-referrer");
1828
+ if (req.method !== "GET") {
1829
+ res.writeHead(405);
1830
+ res.end();
1831
+ return;
1832
+ }
1833
+ const callback = new URL(req.url ?? "/", "http://127.0.0.1");
1834
+ const code = callback.searchParams.get("code");
1835
+ if (callback.pathname !== "/" || !code?.startsWith("gr_cli_org_") || callback.searchParams.get("state") !== expectedState || callback.searchParams.get("org_uuid") !== expectedOrgUuid) {
1836
+ res.writeHead(400);
1837
+ res.end("Invalid sign-in callback");
1838
+ return;
1839
+ }
1840
+ res.writeHead(200, { "Content-Type": "text/plain" });
1841
+ res.end("Return to the terminal to finish sign-in.");
1842
+ resolveSession(code);
1843
+ });
1844
+ let resolveReady;
1845
+ let rejectReady;
1846
+ const ready = new Promise((resolve3, reject) => {
1847
+ resolveReady = resolve3;
1848
+ rejectReady = reject;
1849
+ });
1850
+ server.on("error", (err) => {
1851
+ rejectReady(err);
1852
+ rejectSession(err);
1853
+ });
1854
+ server.listen(0, "127.0.0.1", () => {
1855
+ resolveReady(server.address().port);
1856
+ });
1857
+ const timeout = setTimeout(() => {
1858
+ rejectSession(
1859
+ new Error(
1860
+ "Organization authentication timed out.\nComplete sign-in in the browser, then re-run the command."
1861
+ )
1862
+ );
1863
+ }, ORG_AUTH_TIMEOUT_MS);
1864
+ timeout.unref();
1865
+ let closed = false;
1866
+ const close = () => {
1867
+ if (closed) return;
1868
+ closed = true;
1869
+ clearTimeout(timeout);
1870
+ server.close();
1871
+ };
1872
+ return { ready, session, close };
1873
+ }
1874
+ function buildStepUpUrl(authUrl, orgUuid, port, state, challenge) {
1875
+ const url = new URL(authUrl);
1876
+ const bridgeQuery = new URLSearchParams({ org: orgUuid, port: String(port), state, challenge });
1877
+ url.searchParams.set("return_to", `${CLI_ORG_AUTH_BRIDGE_PATH}?${bridgeQuery.toString()}`);
1878
+ return url.toString();
1879
+ }
1880
+ function newStateNonce() {
1881
+ return randomBytes2(16).toString("hex");
1882
+ }
1883
+ async function stepUpViaBrowser(orgAuthInfo, apiUrl, accessToken) {
1884
+ const state = newStateNonce();
1885
+ const verifier = randomBytes2(32).toString("base64url");
1886
+ const challenge = createHash2("sha256").update(verifier).digest("base64url");
1887
+ const allowedOrigin = new URL(orgAuthInfo.authUrl).origin;
1888
+ const capture = startOrgSessionCapture(state, orgAuthInfo.orgUuid, allowedOrigin);
1889
+ try {
1890
+ const port = await capture.ready;
1891
+ const stepUpUrl = buildStepUpUrl(
1892
+ orgAuthInfo.authUrl,
1893
+ orgAuthInfo.orgUuid,
1894
+ port,
1895
+ state,
1896
+ challenge
1897
+ );
1898
+ stderr2(`
1899
+ This workspace requires organization SSO authentication.`);
1900
+ stderr2(`Opening browser to complete sign-in...`);
1901
+ stderr2(` ${stepUpUrl}
1902
+ `);
1903
+ stderr2(`If the browser does not open, visit the URL above manually.`);
1904
+ openBrowser2(stepUpUrl);
1905
+ const code = await capture.session;
1906
+ const response = await fetch(`${apiUrl}/api/v2/auth/cli-org-handoff/redeem`, {
1907
+ method: "POST",
1908
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}` },
1909
+ body: JSON.stringify({ orgUuid: orgAuthInfo.orgUuid, code, verifier })
1910
+ });
1911
+ if (!response.ok)
1912
+ throw new Error(`Could not finish organization sign-in (${response.status}).`);
1913
+ let result;
1914
+ try {
1915
+ result = await response.json();
1916
+ } catch {
1917
+ throw new OrgSignInResponseError("Invalid organization sign-in response.");
1918
+ }
1919
+ if (!result || !isOrgSessionCredential(result.orgSession)) {
1920
+ throw new OrgSignInResponseError("Invalid organization sign-in response.");
1921
+ }
1922
+ return result.orgSession;
1923
+ } finally {
1924
+ capture.close();
1925
+ }
1926
+ }
1927
+ function registerOrgAuthHandler(apiClient, apiUrl, accessToken, orgAuthCtx) {
1928
+ apiClient.setOrgAuthHandler(
1929
+ async (orgAuthInfo) => {
1930
+ const orgUuid = orgAuthInfo.orgUuid;
1931
+ if (!ORG_UUID_RE.test(orgUuid)) {
1932
+ throw new Error("Invalid organization id in auth challenge");
1933
+ }
1934
+ const cm = orgAuthCtx?.credentialsManager;
1935
+ const initialCachedSession = cm && orgAuthCtx ? cm.getOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid) : void 0;
1936
+ const adopt = (session2, expiresAt) => {
1937
+ if (!isOrgSessionCredential(session2)) {
1938
+ throw new OrgSignInResponseError("Invalid organization sign-in response.");
1939
+ }
1940
+ if (cm && orgAuthCtx && expiresAt && cm.getOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid) === initialCachedSession) {
1941
+ cm.setOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid, session2, expiresAt);
1942
+ }
1943
+ return {
1944
+ session: session2,
1945
+ orgUuid,
1946
+ source: "new",
1947
+ onRejected: () => {
1948
+ if (cm && orgAuthCtx)
1949
+ cm.removeOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid, session2);
1950
+ }
1951
+ };
1952
+ };
1953
+ if (cm && orgAuthCtx && !orgAuthInfo.sessionRejected && !orgAuthInfo.acrValues?.length) {
1954
+ const cached = cm.getOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid);
1955
+ if (cached) {
1956
+ return {
1957
+ session: cached,
1958
+ orgUuid,
1959
+ source: "cache",
1960
+ onRejected: () => {
1961
+ cm.removeOrgSession(orgAuthCtx.env, orgAuthCtx.profile, orgUuid, cached);
1962
+ }
1963
+ };
1964
+ }
1965
+ }
1966
+ let orgSession = null;
1967
+ try {
1968
+ orgSession = await tryDirectJoin(apiUrl, accessToken, orgAuthInfo);
1969
+ } catch (err) {
1970
+ if (err instanceof OrgSignInResponseError) throw err;
1971
+ const msg = err instanceof Error ? err.message : String(err);
1972
+ stderr2(`Warning: org direct-join failed (${msg}); trying browser sign-in`);
1973
+ }
1974
+ if (orgSession !== null) {
1975
+ return adopt(orgSession.session, orgSession.expiresAt);
1976
+ }
1977
+ if (!orgAuthCtx?.interactive || isHeadless()) {
1978
+ throw new Error(
1979
+ "This workspace\u2019s organization requires SSO sign-in, which needs a browser.\nRun an interactive `gr` command on a machine with a browser to sign in once (the session is then cached), or use an API key for non-interactive use:\n export GRAVITY_RAIL_API_KEY=<key> (see: gr api-keys)"
1980
+ );
1981
+ }
1982
+ if (!isAllowedAuthUrl(orgAuthInfo.authUrl, apiUrl, orgAuthCtx.frontendUrl)) {
1983
+ throw new Error(
1984
+ `Refusing to open organization auth URL: host does not match the configured API/frontend host. Re-run with the expected --api-url, or contact support.`
1985
+ );
1986
+ }
1987
+ const session = await stepUpViaBrowser(orgAuthInfo, apiUrl, accessToken);
1988
+ return adopt(session, new Date(Date.now() + ORG_SESSION_CACHE_TTL_MS).toISOString());
1989
+ }
1990
+ );
1991
+ }
1992
+
1993
+ // ../sandbox/dist/index.js
1994
+ import {
1995
+ GravityRailClient,
1996
+ WorkspaceBuilder,
1997
+ runWorkspaceScript
1998
+ } from "@gravity-rail/sdk";
1999
+ import { writeFileSync as writeFileSync2 } from "fs";
2000
+ import { join as join3 } from "path";
2001
+ import { request as httpRequest } from "http";
2002
+ import {
2003
+ AgentBuilder,
2004
+ ApplyError,
2005
+ FormBuilder,
2006
+ GravityRailClient as GravityRailClient2,
2007
+ JourneyBuilder,
2008
+ MemberFilterBuilder,
2009
+ MemberLabelBuilder,
2010
+ NotificationRuleBuilder,
2011
+ RoutineBuilder,
2012
+ TaskBuilder,
2013
+ WorkspaceBuilder as WorkspaceBuilder2,
2014
+ WorkflowBuilder,
2015
+ runWorkspaceScript as runWorkspaceScript2,
2016
+ toSafeMemberImportPreview,
2017
+ toSafeMemberImportSummary
2018
+ } from "@gravity-rail/sdk";
2019
+ function createUnixBrokerFetch(socketPath) {
2020
+ return async (input, init) => {
2021
+ const request = new Request(input, init);
2022
+ const url = new URL(request.url);
2023
+ if (!["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)) {
2024
+ throw new Error("The sandbox broker requires a loopback request");
2025
+ }
2026
+ const body = request.body ? Buffer.from(await request.arrayBuffer()) : void 0;
2027
+ return new Promise((resolve3, reject) => {
2028
+ const connection = httpRequest(
2029
+ {
2030
+ socketPath,
2031
+ path: url.pathname + url.search,
2032
+ method: request.method,
2033
+ headers: Object.fromEntries(request.headers)
2034
+ },
2035
+ (response) => {
2036
+ const chunks = [];
2037
+ let length = 0;
2038
+ response.on("data", (chunk) => {
2039
+ length += chunk.length;
2040
+ if (length > 32 * 1024 * 1024) {
2041
+ connection.destroy(new Error("Sandbox response exceeds its size limit"));
2042
+ return;
2043
+ }
2044
+ chunks.push(chunk);
2045
+ });
2046
+ response.on("error", reject);
2047
+ response.on("end", () => {
2048
+ const headers = new Headers();
2049
+ for (const [name, value] of Object.entries(response.headers)) {
2050
+ if (Array.isArray(value)) value.forEach((item) => headers.append(name, item));
2051
+ else if (value !== void 0) headers.set(name, value);
2052
+ }
2053
+ const status = response.statusCode ?? 502;
2054
+ resolve3(
2055
+ new Response([204, 205, 304].includes(status) ? null : Buffer.concat(chunks), {
2056
+ status,
2057
+ headers
2058
+ })
2059
+ );
2060
+ });
2061
+ }
2062
+ );
2063
+ connection.on("error", reject);
2064
+ const abort = () => connection.destroy(new Error("Sandbox request was cancelled"));
2065
+ if (request.signal.aborted) abort();
2066
+ else request.signal.addEventListener("abort", abort, { once: true });
2067
+ connection.on("close", () => request.signal.removeEventListener("abort", abort));
2068
+ connection.end(body);
2069
+ });
2070
+ };
2071
+ }
2072
+
2073
+ // src/lib/sandbox-fetch.ts
2074
+ function withAuditHeaders(fetchFn, headers) {
2075
+ const { chatId, sessionId, toolCallId } = headers;
2076
+ return async (input, init) => {
2077
+ const reqHeaders = new Headers(init?.headers);
2078
+ const dynamicToolCallId = globalThis.__GRAVITY_RAIL_TOOL_CALL_ID__ || (typeof process !== "undefined" ? process.env.GRAVITY_RAIL_TOOL_CALL_ID : void 0);
2079
+ if (chatId !== void 0) {
2080
+ reqHeaders.set("X-GR-Chat-Id", String(chatId));
2081
+ }
2082
+ if (sessionId) {
2083
+ reqHeaders.set("X-GR-Session-Id", sessionId);
2084
+ }
2085
+ if (dynamicToolCallId || toolCallId) {
2086
+ reqHeaders.set("X-GR-Tool-Call-Id", dynamicToolCallId || toolCallId || "");
2087
+ }
2088
+ return fetchFn(input, { ...init, headers: reqHeaders });
2089
+ };
2090
+ }
2091
+ function createSandboxFetchFromEnv() {
2092
+ const env = typeof process !== "undefined" ? process.env : {};
2093
+ const chatIdRaw = env.GRAVITY_RAIL_CHAT_ID;
2094
+ const chatId = chatIdRaw ? Number(chatIdRaw) : void 0;
2095
+ return withAuditHeaders(
2096
+ env.GRAVITY_RAIL_BROKER_SOCKET ? createUnixBrokerFetch(env.GRAVITY_RAIL_BROKER_SOCKET) : fetch,
2097
+ {
2098
+ chatId: chatId !== void 0 && Number.isFinite(chatId) ? chatId : void 0,
2099
+ sessionId: env.GRAVITY_RAIL_SESSION_ID,
2100
+ toolCallId: env.GRAVITY_RAIL_TOOL_CALL_ID
2101
+ }
2102
+ );
2103
+ }
2104
+
2105
+ // src/lib/context.ts
2106
+ function makeApiClient(accessToken, apiUrl, fetchFn, orgAuthCtx) {
2107
+ const resolvedFetch = fetchFn ?? createSandboxFetchFromEnv();
2108
+ const apiClient = new GravityRailClient3(accessToken, apiUrl, resolvedFetch);
2109
+ registerOrgAuthHandler(apiClient, apiUrl, accessToken ?? "", orgAuthCtx);
2110
+ return apiClient;
2111
+ }
2112
+ function interactiveOrgAuth(ctx) {
2113
+ return {
2114
+ credentialsManager: ctx.credentialsManager,
2115
+ env: ctx.env,
2116
+ profile: ctx.profile,
2117
+ frontendUrl: ctx.envConfig.frontendUrl,
2118
+ interactive: true
2119
+ };
2120
+ }
2121
+ function isLoopbackBrokerUrl(rawUrl) {
2122
+ try {
2123
+ const { hostname, protocol } = new URL(rawUrl);
2124
+ if (protocol !== "http:" && protocol !== "https:") return false;
2125
+ const host = hostname.replace(/^\[|\]$/g, "");
2126
+ return host === "127.0.0.1" || host === "::1" || host === "localhost";
2127
+ } catch {
2128
+ return false;
2129
+ }
2130
+ }
2131
+ function sandboxBrokerUrl() {
2132
+ const brokerUrl = process.env.GRAVITY_RAIL_BROKER_URL;
2133
+ if (!brokerUrl || !isLoopbackBrokerUrl(brokerUrl)) return null;
2134
+ return brokerUrl;
2135
+ }
2136
+ function tryBrokerContext(ctx) {
2137
+ const brokerUrl = sandboxBrokerUrl();
2138
+ if (!brokerUrl) return null;
2139
+ const apiClient = makeApiClient(void 0, brokerUrl, createSandboxFetchFromEnv());
2140
+ return { ...ctx, accessToken: "", apiClient };
2141
+ }
2142
+ function contextWithToken(ctx, auth) {
2143
+ const apiClient = makeApiClient(
2144
+ auth.accessToken,
2145
+ ctx.envConfig.apiUrl,
2146
+ void 0,
2147
+ auth.credentials ? interactiveOrgAuth(ctx) : void 0
2148
+ );
2149
+ return {
2150
+ ...ctx,
2151
+ accessToken: auth.accessToken,
2152
+ apiClient,
2153
+ profileWorkspace: auth.credentials?.workspaceUuid
2154
+ };
2155
+ }
2156
+ function createContext(opts) {
2157
+ const envConfig = getEnvironmentConfig(opts.env, {
2158
+ apiUrl: opts.apiUrl,
2159
+ startDir: opts.startDir
2160
+ });
2161
+ const credentialsManager = new CredentialsManager(homedir(), envConfig.apiUrl);
2162
+ const profile = credentialsManager.resolveProfileName(opts.profile, opts.env);
2163
+ return {
2164
+ env: opts.env,
2165
+ envConfig,
2166
+ outputFormat: detectOutputFormat(opts.outputFormat),
2167
+ jq: opts.jq,
2168
+ verbose: opts.verbose ?? false,
2169
+ allowWrite: opts.allowWrite ?? false,
2170
+ credentialsManager,
2171
+ profile
2172
+ };
2173
+ }
2174
+ async function createAuthenticatedContext(opts) {
2175
+ const ctx = createContext(opts);
2176
+ const brokerCtx = tryBrokerContext(ctx);
2177
+ if (brokerCtx) return brokerCtx;
2178
+ const auth = await resolveNonInteractiveAuth({
2179
+ env: ctx.env,
2180
+ envConfig: ctx.envConfig,
2181
+ credentialsManager: ctx.credentialsManager,
2182
+ profile: ctx.profile
2183
+ });
2184
+ if (auth) return contextWithToken(ctx, auth);
2185
+ if (ctx.profile !== "default") {
2186
+ throw new AuthRequiredError(
2187
+ `No credentials for profile "${ctx.profile}" (${ctx.env}). Run: gr auth login --name ${ctx.profile} or gr auth import-dev`
2188
+ );
2189
+ }
2190
+ throw new AuthRequiredError(
2191
+ "Not authenticated. Run `gr login`, `gr auth import-dev` (local dev), or set GRAVITY_RAIL_API_KEY."
2192
+ );
2193
+ }
2194
+ function requireAuth(ctx) {
2195
+ if (!("apiClient" in ctx)) {
2196
+ throw new Error("Command handler accessed apiClient without declaring requiresAuth");
2197
+ }
2198
+ return ctx;
2199
+ }
2200
+ function createPublicContext(opts) {
2201
+ const env = opts.env ?? "prod";
2202
+ const envConfig = getEnvironmentConfig(env, {
2203
+ apiUrl: opts.apiUrl,
2204
+ frontendUrl: opts.frontendUrl,
2205
+ startDir: opts.startDir
2206
+ });
2207
+ const credentialsManager = new CredentialsManager(homedir(), envConfig.apiUrl);
2208
+ const profile = credentialsManager.resolveProfileName(opts.profile, env);
2209
+ return {
2210
+ env,
2211
+ envConfig,
2212
+ outputFormat: detectOutputFormat(opts.outputFormat),
2213
+ jq: opts.jq,
2214
+ verbose: opts.verbose ?? false,
2215
+ allowWrite: opts.allowWrite ?? false,
2216
+ credentialsManager,
2217
+ profile
2218
+ };
2219
+ }
2220
+ async function createPublicAuthenticatedContext(opts) {
2221
+ const ctx = createPublicContext(opts);
2222
+ const brokerCtx = tryBrokerContext(ctx);
2223
+ if (brokerCtx) return brokerCtx;
2224
+ const auth = await resolveNonInteractiveAuth({
2225
+ env: ctx.env,
2226
+ envConfig: ctx.envConfig,
2227
+ credentialsManager: ctx.credentialsManager,
2228
+ profile: ctx.profile
2229
+ });
2230
+ if (auth) return contextWithToken(ctx, auth);
2231
+ throw new AuthRequiredError();
2232
+ }
2233
+
2234
+ // src/lib/api-transport.ts
2235
+ function apiBaseUrl(ctx) {
2236
+ return sandboxBrokerUrl() ?? ctx.envConfig.apiUrl;
2237
+ }
2238
+ function apiAuthHeaders(accessToken) {
2239
+ if (sandboxBrokerUrl() || !accessToken) return {};
2240
+ return { Authorization: `Bearer ${accessToken}` };
2241
+ }
2242
+ function apiAccessToken(ctx) {
2243
+ return sandboxBrokerUrl() ? void 0 : ctx.accessToken || void 0;
2244
+ }
2245
+ var apiFetch = (input, init) => createSandboxFetchFromEnv()(input, init);
2246
+
1400
2247
  // src/cli-utils/agui.ts
1401
2248
  var AGUIClient = class {
1402
2249
  endpointUrl;
@@ -1435,7 +2282,7 @@ var AGUIClient = class {
1435
2282
  const url = this.chatRouteUrl(`inline-connect/${encodeURIComponent(appSlug)}/link`);
1436
2283
  if (!url) return null;
1437
2284
  try {
1438
- const res = await fetch(url, { headers: { Authorization: `Bearer ${this.accessToken}` } });
2285
+ const res = await apiFetch(url, { headers: apiAuthHeaders(this.accessToken) });
1439
2286
  if (!res.ok) return null;
1440
2287
  const body = await res.json();
1441
2288
  if (typeof body.connectUrl !== "string") return null;
@@ -1447,6 +2294,37 @@ var AGUIClient = class {
1447
2294
  return null;
1448
2295
  }
1449
2296
  }
2297
+ /**
2298
+ * Send or discard a message the Manager proposed as a draft. The three
2299
+ * results are different things to tell the operator: `settled` carries how
2300
+ * it ended, `refused` is the server saying no (a 409 is a draft settled
2301
+ * elsewhere), and `transport` is not knowing — the draft is unchanged as
2302
+ * far as this client can tell.
2303
+ */
2304
+ async settleProposedMessage(promptId, decision) {
2305
+ const url = this.chatRouteUrl(`proposed-messages/${encodeURIComponent(promptId)}/decision`);
2306
+ if (!url) return { kind: "transport" };
2307
+ try {
2308
+ const res = await apiFetch(url, {
2309
+ method: "POST",
2310
+ headers: {
2311
+ ...apiAuthHeaders(this.accessToken),
2312
+ "Content-Type": "application/json"
2313
+ },
2314
+ body: JSON.stringify({ decision })
2315
+ });
2316
+ if (!res.ok) return { kind: "refused", status: res.status };
2317
+ const body = await res.json();
2318
+ if (!isProposedMessageSettlementStatus(body.status)) return { kind: "transport" };
2319
+ return {
2320
+ kind: "settled",
2321
+ status: body.status,
2322
+ detail: typeof body.detail === "string" ? body.detail : null
2323
+ };
2324
+ } catch {
2325
+ return { kind: "transport" };
2326
+ }
2327
+ }
1450
2328
  inferenceStatusUrl() {
1451
2329
  const noChat = typeof this.chatId === "number" ? this.chatId <= 0 : this.chatId.length === 0;
1452
2330
  if (!this.workspaceUuid || noChat) return null;
@@ -1458,8 +2336,8 @@ var AGUIClient = class {
1458
2336
  const deadline = Date.now() + maxWaitMs;
1459
2337
  while (Date.now() < deadline) {
1460
2338
  try {
1461
- const res = await fetch(url, {
1462
- headers: { Authorization: `Bearer ${this.accessToken}` }
2339
+ const res = await apiFetch(url, {
2340
+ headers: apiAuthHeaders(this.accessToken)
1463
2341
  });
1464
2342
  if (res.ok) {
1465
2343
  const body = await res.json();
@@ -1505,10 +2383,10 @@ var AGUIClient = class {
1505
2383
  await this.postStream(body, onEvent, options);
1506
2384
  }
1507
2385
  async postStream(body, onEvent, options, conflictRetries = 0) {
1508
- const response = await fetch(this.endpointUrl, {
2386
+ const response = await apiFetch(this.endpointUrl, {
1509
2387
  method: "POST",
1510
2388
  headers: {
1511
- Authorization: `Bearer ${this.accessToken}`,
2389
+ ...apiAuthHeaders(this.accessToken),
1512
2390
  "Content-Type": "application/json",
1513
2391
  Accept: "text/event-stream"
1514
2392
  },
@@ -1563,11 +2441,11 @@ var AGUIClient = class {
1563
2441
  const connectedAt = Date.now();
1564
2442
  try {
1565
2443
  const headers = {
1566
- Authorization: `Bearer ${this.accessToken}`,
2444
+ ...apiAuthHeaders(this.accessToken),
1567
2445
  Accept: "text/event-stream"
1568
2446
  };
1569
2447
  if (lastEventId !== void 0) headers["Last-Event-ID"] = lastEventId;
1570
- const response = await fetch(feedUrl, { method: "GET", headers, signal });
2448
+ const response = await apiFetch(feedUrl, { method: "GET", headers, signal });
1571
2449
  if (!response.ok || !response.body) {
1572
2450
  throw new Error(`feed request failed: ${response.status}`);
1573
2451
  }
@@ -1692,7 +2570,6 @@ export {
1692
2570
  parsePublishedTarget,
1693
2571
  classifyCheckout,
1694
2572
  getEnvironmentConfig,
1695
- isOrgSessionCredential,
1696
2573
  DEFAULT_PROFILE,
1697
2574
  CredentialsManager,
1698
2575
  generatePKCE,
@@ -1710,11 +2587,43 @@ export {
1710
2587
  wrapText,
1711
2588
  printMessage,
1712
2589
  clearScreen,
2590
+ apiBaseUrl,
2591
+ apiAuthHeaders,
2592
+ apiAccessToken,
2593
+ apiFetch,
1713
2594
  AGUIClient,
1714
2595
  parseSseStream,
1715
2596
  isTextContentEvent,
1716
2597
  isErrorEvent,
1717
2598
  getTextDelta,
1718
- getErrorMessage
2599
+ getErrorMessage,
2600
+ isListResult,
2601
+ isPagePaginatedResponse,
2602
+ isCursorPaginatedResponse,
2603
+ isPaginatedResponse,
2604
+ extractPaginationMeta,
2605
+ formatPaginationWarning,
2606
+ unwrapItems,
2607
+ LIST_PAGINATION_ARGS,
2608
+ parsePaginationArgs,
2609
+ fetchAllPages,
2610
+ fetchAllCursorPages,
2611
+ listResult,
2612
+ detectOutputFormat,
2613
+ outputData,
2614
+ outputSingle,
2615
+ COL,
2616
+ hint,
2617
+ stderr2 as stderr,
2618
+ flushStdout,
2619
+ createContext,
2620
+ createAuthenticatedContext,
2621
+ requireAuth,
2622
+ createPublicContext,
2623
+ createPublicAuthenticatedContext,
2624
+ CLIError,
2625
+ AuthRequiredError,
2626
+ unauthorizedHint,
2627
+ handleError
1719
2628
  };
1720
- //# sourceMappingURL=chunk-KDWGBYCM.js.map
2629
+ //# sourceMappingURL=chunk-VA6G6IBW.js.map