@viberaven/mcp 1.7.2 → 1.7.3

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.
@@ -25,6 +25,7 @@ __export(tools_exports, {
25
25
  __resetSpawnForTest: () => __resetSpawnForTest,
26
26
  __setSpawnForTest: () => __setSpawnForTest,
27
27
  callTool: () => callTool,
28
+ createAccountToolHandler: () => createAccountToolHandler,
28
29
  handleRequest: () => handleRequest,
29
30
  parseJsonObjectFromToolText: () => parseJsonObjectFromToolText
30
31
  });
@@ -1367,15 +1368,718 @@ var npmTools = [
1367
1368
  }
1368
1369
  ];
1369
1370
 
1370
- // src/lib/cli-runner.ts
1371
+ // ../cli/src/hosted/credentials.ts
1371
1372
  var import_node_child_process = require("node:child_process");
1373
+ var import_node_crypto = require("node:crypto");
1374
+ var import_promises = require("node:fs/promises");
1375
+ var import_node_os = require("node:os");
1376
+ var import_node_path = require("node:path");
1377
+ var CREDENTIALS_FILE_NAME = "credentials.json";
1378
+ function defaultConfigDir(env = process.env, platform = process.platform) {
1379
+ const override = env.VIBERAVEN_CONFIG_DIR?.trim();
1380
+ if (override) return (0, import_node_path.resolve)(override);
1381
+ if (platform === "win32") {
1382
+ return (0, import_node_path.join)(env.APPDATA?.trim() || (0, import_node_path.join)((0, import_node_os.homedir)(), "AppData", "Roaming"), "viberaven");
1383
+ }
1384
+ if (platform === "darwin") {
1385
+ return (0, import_node_path.join)((0, import_node_os.homedir)(), "Library", "Application Support", "viberaven");
1386
+ }
1387
+ return (0, import_node_path.join)(env.XDG_CONFIG_HOME?.trim() || (0, import_node_path.join)((0, import_node_os.homedir)(), ".config"), "viberaven");
1388
+ }
1389
+ var CredentialLocationError = class extends Error {
1390
+ };
1391
+ var CredentialPermissionError = class extends Error {
1392
+ constructor(message, toolMissing) {
1393
+ super(message);
1394
+ this.toolMissing = toolMissing;
1395
+ }
1396
+ };
1397
+ var restrictWithIcacls = (path2) => {
1398
+ const name = (0, import_node_os.userInfo)().username;
1399
+ const user = process.env.USERDOMAIN ? `${process.env.USERDOMAIN}\\${name}` : name;
1400
+ return new Promise((resolveRestrict, reject) => {
1401
+ (0, import_node_child_process.execFile)("icacls", [path2, "/inheritance:r", "/grant:r", `${user}:F`], { windowsHide: true, timeout: 1e4 }, (error) => {
1402
+ if (error) reject(error);
1403
+ else resolveRestrict();
1404
+ });
1405
+ });
1406
+ };
1407
+ function isInside(child, parent) {
1408
+ const rel = (0, import_node_path.relative)((0, import_node_path.resolve)(parent), (0, import_node_path.resolve)(child));
1409
+ return rel === "" || !rel.startsWith("..") && !(0, import_node_path.isAbsolute)(rel);
1410
+ }
1411
+ var TRANSIENT_FS_CODES = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
1412
+ var FS_ATTEMPTS = 8;
1413
+ var FS_BACKOFF_MS = 10;
1414
+ async function retryTransient(work) {
1415
+ for (let attempt = 1; ; attempt += 1) {
1416
+ try {
1417
+ return await work();
1418
+ } catch (error) {
1419
+ const code = error?.code;
1420
+ if (attempt >= FS_ATTEMPTS || !code || !TRANSIENT_FS_CODES.has(code)) throw error;
1421
+ await new Promise((resolveWait) => setTimeout(resolveWait, FS_BACKOFF_MS * attempt));
1422
+ }
1423
+ }
1424
+ }
1425
+ var CredentialStore = class {
1426
+ constructor(configDir, workspacePath, options = {}) {
1427
+ this.configDir = configDir;
1428
+ this.workspacePath = workspacePath;
1429
+ this.path = (0, import_node_path.join)(configDir, CREDENTIALS_FILE_NAME);
1430
+ this.homeDir = options.homeDir ?? (0, import_node_os.homedir)();
1431
+ this.restrict = options.restrict !== void 0 ? options.restrict : process.platform === "win32" ? restrictWithIcacls : null;
1432
+ this.fs = { readFile: (path2, encoding) => (0, import_promises.readFile)(path2, encoding), rename: (from, to) => (0, import_promises.rename)(from, to), rm: (path2) => (0, import_promises.rm)(path2, { force: true }), ...options.fs };
1433
+ }
1434
+ path;
1435
+ restrict;
1436
+ fs;
1437
+ homeDir;
1438
+ /** Every change to the file runs one at a time, in the order it was asked for. */
1439
+ queue = Promise.resolve();
1440
+ async read() {
1441
+ let raw;
1442
+ try {
1443
+ raw = await retryTransient(() => this.fs.readFile(this.path, "utf8"));
1444
+ } catch {
1445
+ return null;
1446
+ }
1447
+ try {
1448
+ const parsed = JSON.parse(raw);
1449
+ if (parsed.version === 1 && typeof parsed.apiBaseUrl === "string" && typeof parsed.accessToken === "string" && parsed.accessToken.length > 0 && parsed.account && typeof parsed.account.email === "string" && (parsed.account.plan === "free" || parsed.account.plan === "pro")) {
1450
+ return parsed;
1451
+ }
1452
+ } catch {
1453
+ }
1454
+ return null;
1455
+ }
1456
+ /** The stored session, only if it was issued by `apiBaseUrl`. */
1457
+ async readFor(apiBaseUrl) {
1458
+ const stored = await this.read();
1459
+ return stored && stored.apiBaseUrl === apiBaseUrl ? stored : null;
1460
+ }
1461
+ /** Resolves once every change queued so far has landed (or failed). */
1462
+ idle() {
1463
+ return this.queue;
1464
+ }
1465
+ /** Standalone account commands have no workspace, but their credentials still must stay outside Git. */
1466
+ async assertLocation() {
1467
+ if (this.workspacePath && isInside(this.configDir, this.workspacePath)) {
1468
+ throw new CredentialLocationError("VibeRaven account storage must be outside the project.");
1469
+ }
1470
+ const missing = [];
1471
+ let existing = (0, import_node_path.resolve)(this.configDir);
1472
+ while (true) {
1473
+ try {
1474
+ await (0, import_promises.lstat)(existing);
1475
+ break;
1476
+ } catch (error) {
1477
+ if (error.code !== "ENOENT" || (0, import_node_path.dirname)(existing) === existing) throw error;
1478
+ missing.unshift((0, import_node_path.basename)(existing));
1479
+ existing = (0, import_node_path.dirname)(existing);
1480
+ }
1481
+ }
1482
+ const canonical = (0, import_node_path.resolve)(await (0, import_promises.realpath)(existing), ...missing);
1483
+ const workspace = this.workspacePath ? await (0, import_promises.realpath)(this.workspacePath).catch((error) => {
1484
+ if (error.code === "ENOENT") return (0, import_node_path.resolve)(this.workspacePath);
1485
+ throw error;
1486
+ }) : void 0;
1487
+ if (workspace && isInside(canonical, workspace)) {
1488
+ throw new CredentialLocationError("VibeRaven account storage must be outside the project.");
1489
+ }
1490
+ const home = (0, import_node_path.resolve)(this.homeDir);
1491
+ const boundaries = /* @__PURE__ */ new Set([home, (0, import_node_path.join)(home, ".config")]);
1492
+ for (const boundary of [...boundaries]) boundaries.add(await (0, import_promises.realpath)(boundary).catch(() => boundary));
1493
+ for (const path2 of /* @__PURE__ */ new Set([(0, import_node_path.resolve)(this.configDir), canonical])) {
1494
+ for (let cursor = path2; ; cursor = (0, import_node_path.dirname)(cursor)) {
1495
+ if ([...boundaries].some((boundary) => (0, import_node_path.relative)(boundary, cursor) === "")) break;
1496
+ try {
1497
+ await (0, import_promises.lstat)((0, import_node_path.join)(cursor, ".git"));
1498
+ throw new CredentialLocationError("VibeRaven account storage must be outside Git checkouts.");
1499
+ } catch (error) {
1500
+ if (error.code !== "ENOENT") throw error;
1501
+ }
1502
+ if ((0, import_node_path.dirname)(cursor) === cursor) break;
1503
+ }
1504
+ }
1505
+ const target = await (0, import_promises.lstat)(this.path).catch((error) => {
1506
+ if (error.code === "ENOENT") return void 0;
1507
+ throw error;
1508
+ });
1509
+ if (target && (!target.isFile() || target.isSymbolicLink())) throw new CredentialLocationError("VibeRaven account storage must be a regular private file.");
1510
+ }
1511
+ serial(work) {
1512
+ const run = this.queue.then(work, work);
1513
+ this.queue = run.then(() => void 0, () => void 0);
1514
+ return run;
1515
+ }
1516
+ write(credentials) {
1517
+ return this.serial(async () => {
1518
+ await this.writeNow({ version: 1, ...credentials, savedAt: (/* @__PURE__ */ new Date()).toISOString() });
1519
+ });
1520
+ }
1521
+ /** Must run inside `serial`. Returns false when `guard` stopped the swap and the file was left alone. */
1522
+ async writeNow(body, guard) {
1523
+ if (this.workspacePath && isInside(this.configDir, this.workspacePath)) {
1524
+ throw new CredentialLocationError(
1525
+ `Refusing to store the VibeRaven sign-in inside this project (${this.configDir}). Set VIBERAVEN_CONFIG_DIR to a folder outside the repo.`
1526
+ );
1527
+ }
1528
+ await this.assertLocation();
1529
+ await (0, import_promises.mkdir)(this.configDir, { recursive: true, mode: 448 });
1530
+ const temp = `${this.path}.${(0, import_node_crypto.randomUUID)()}.tmp`;
1531
+ await (0, import_promises.writeFile)(temp, `${JSON.stringify(body, null, 2)}
1532
+ `, { encoding: "utf8", mode: 384 });
1533
+ await (0, import_promises.chmod)(temp, 384).catch(() => void 0);
1534
+ try {
1535
+ if (this.restrict) await this.restrict(temp);
1536
+ } catch (error) {
1537
+ await (0, import_promises.rm)(temp, { force: true });
1538
+ const code = error?.code;
1539
+ const toolMissing = code === "ENOENT";
1540
+ throw new CredentialPermissionError(
1541
+ toolMissing ? "Windows icacls was not found, so the sign-in could not be locked to your user account" : `Could not lock the sign-in file to your user account (${error instanceof Error ? error.message : String(error)})`,
1542
+ toolMissing
1543
+ );
1544
+ }
1545
+ if (guard) {
1546
+ const onDisk = await this.readFor(guard.apiBaseUrl);
1547
+ if (onDisk?.accessToken !== guard.accessToken || guard.isCurrent && !guard.isCurrent()) {
1548
+ await (0, import_promises.rm)(temp, { force: true });
1549
+ return false;
1550
+ }
1551
+ }
1552
+ try {
1553
+ await retryTransient(() => this.fs.rename(temp, this.path));
1554
+ } catch (error) {
1555
+ await (0, import_promises.rm)(temp, { force: true });
1556
+ throw error;
1557
+ }
1558
+ await (0, import_promises.chmod)(this.path, 384).catch(() => void 0);
1559
+ return true;
1560
+ }
1561
+ /** Keeps the stored plan label in step with what the API last said. */
1562
+ updatePlan(apiBaseUrl, plan) {
1563
+ return this.serial(async () => {
1564
+ const stored = await this.readFor(apiBaseUrl);
1565
+ if (!stored || stored.account.plan === plan) return;
1566
+ await this.writeNow(
1567
+ { version: 1, apiBaseUrl: stored.apiBaseUrl, accessToken: stored.accessToken, account: { ...stored.account, plan }, savedAt: (/* @__PURE__ */ new Date()).toISOString() },
1568
+ { apiBaseUrl: stored.apiBaseUrl, accessToken: stored.accessToken }
1569
+ );
1570
+ });
1571
+ }
1572
+ /**
1573
+ * Replaces the saved account label with what the API holds now. Only touches the file while it
1574
+ * still holds the sign-in `accessToken` belongs to and `isCurrent()` still says yes, so a
1575
+ * sign-out or a new sign-in made while the API was answering is never overwritten. `savedAt`
1576
+ * is the sign-in time and is kept.
1577
+ */
1578
+ updateAccount(apiBaseUrl, accessToken, account, isCurrent) {
1579
+ return this.serial(async () => {
1580
+ const stored = await this.readFor(apiBaseUrl);
1581
+ if (!stored || stored.accessToken !== accessToken) return;
1582
+ if (stored.account.email === account.email && stored.account.plan === account.plan) return;
1583
+ if (isCurrent && !isCurrent()) return;
1584
+ await this.writeNow(
1585
+ { version: 1, apiBaseUrl: stored.apiBaseUrl, accessToken, account: { ...stored.account, ...account }, savedAt: stored.savedAt },
1586
+ { apiBaseUrl: stored.apiBaseUrl, accessToken, isCurrent }
1587
+ );
1588
+ });
1589
+ }
1590
+ clear() {
1591
+ return this.serial(() => retryTransient(() => this.fs.rm(this.path)));
1592
+ }
1593
+ };
1594
+
1595
+ // ../../src/station/fetchUtils.ts
1596
+ function isNetworkFetchFailure(error) {
1597
+ if (error == null) {
1598
+ return false;
1599
+ }
1600
+ if (error instanceof TypeError) {
1601
+ const m = error.message;
1602
+ if (m === "fetch failed" || m.toLowerCase().includes("fetch failed") || m.includes("Failed to fetch")) {
1603
+ return true;
1604
+ }
1605
+ }
1606
+ if (error instanceof AggregateError) {
1607
+ return error.errors.some((e2) => isNetworkFetchFailure(e2));
1608
+ }
1609
+ if (error instanceof Error && "cause" in error && error.cause != null) {
1610
+ return isNetworkFetchFailure(error.cause);
1611
+ }
1612
+ const e = error;
1613
+ if (typeof e.code === "string") {
1614
+ if (["ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EAI_AGAIN", "ETIMEDOUT", "ENETUNREACH", "EHOSTUNREACH"].includes(
1615
+ e.code
1616
+ )) {
1617
+ return true;
1618
+ }
1619
+ }
1620
+ return false;
1621
+ }
1622
+
1623
+ // ../../shared/deviceAuthorization.ts
1624
+ var DEVICE_AUTH_PROTOCOL_VERSION = 2;
1625
+ function normalizeUserCode(value) {
1626
+ if (typeof value !== "string") return null;
1627
+ const code = value.trim().toUpperCase();
1628
+ if (!/^[A-HJ-NP-Z2-9]{4}-?[A-HJ-NP-Z2-9]{4}$/.test(code)) return null;
1629
+ const compact = code.replace("-", "");
1630
+ return `${compact.slice(0, 4)}-${compact.slice(4)}`;
1631
+ }
1632
+ function isOpaqueDeviceCode(value) {
1633
+ return typeof value === "string" && /^vrdc_[A-Za-z0-9_-]{43}$/.test(value);
1634
+ }
1635
+
1636
+ // ../cli/src/hosted/deviceAuthorization.ts
1637
+ var DEVICE_START_REQUEST = { protocolVersion: DEVICE_AUTH_PROTOCOL_VERSION };
1638
+ var DEFAULT_SITE = "https://viberaven.dev";
1639
+ var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
1640
+ function deviceSiteOrigin(value = process.env.VIBERAVEN_SITE_URL || DEFAULT_SITE) {
1641
+ try {
1642
+ const url = new URL(value);
1643
+ if (url.username || url.password || url.search || url.hash || url.pathname !== "/" || !(url.protocol === "https:" || url.protocol === "http:" && LOOPBACK.has(url.hostname))) throw new Error();
1644
+ return url.origin;
1645
+ } catch {
1646
+ throw new Error("VIBERAVEN_SITE_URL must name the trusted HTTPS site origin (HTTP is allowed only for loopback tests).");
1647
+ }
1648
+ }
1649
+ function validateDeviceAuthorization(value, expectedOrigin = deviceSiteOrigin()) {
1650
+ const fail = () => {
1651
+ throw new Error("Device sign-in requires the updated API and CLI protocol. Upgrade VibeRaven and ask the owner to deploy the matching device-flow API.");
1652
+ };
1653
+ if (!value || typeof value !== "object") return fail();
1654
+ const input = value;
1655
+ const userCode = normalizeUserCode(input.userCode);
1656
+ if (input.protocolVersion !== DEVICE_AUTH_PROTOCOL_VERSION || !userCode || !isOpaqueDeviceCode(input.deviceCode) || typeof input.verificationUrl !== "string" || typeof input.expiresAt !== "string" || !Number.isFinite(Date.parse(input.expiresAt)) || typeof input.pollIntervalSeconds !== "number" || !Number.isFinite(input.pollIntervalSeconds) || input.pollIntervalSeconds < 1 || input.pollIntervalSeconds > 60) return fail();
1657
+ let url;
1658
+ try {
1659
+ url = new URL(input.verificationUrl);
1660
+ } catch {
1661
+ return fail();
1662
+ }
1663
+ if (url.origin !== expectedOrigin || url.username || url.password || url.hash || url.pathname !== "/connect" || [...url.searchParams.keys()].length !== 1 || normalizeUserCode(url.searchParams.get("user_code")) !== userCode) return fail();
1664
+ return {
1665
+ protocolVersion: DEVICE_AUTH_PROTOCOL_VERSION,
1666
+ userCode,
1667
+ deviceCode: input.deviceCode,
1668
+ verificationUrl: url.toString(),
1669
+ expiresAt: input.expiresAt,
1670
+ pollIntervalSeconds: input.pollIntervalSeconds
1671
+ };
1672
+ }
1673
+
1674
+ // ../cli/src/hosted/hostedClient.ts
1675
+ var DEFAULT_API_BASE_URL = "https://jaohiwzjhtwljyqligpu.supabase.co/functions/v1/viberice-api";
1676
+ function normalizeBaseUrl(baseUrl) {
1677
+ return baseUrl.trim().replace(/\/+$/, "");
1678
+ }
1679
+ function resolveApiBaseUrl(env = process.env) {
1680
+ const raw = env.VIBERAVEN_API_URL?.trim();
1681
+ return normalizeBaseUrl(raw || DEFAULT_API_BASE_URL);
1682
+ }
1683
+ var HostedCallError = class extends Error {
1684
+ constructor(kind, message, details = {}) {
1685
+ super(message);
1686
+ this.kind = kind;
1687
+ this.details = details;
1688
+ }
1689
+ };
1690
+ async function postJson(url, payload, options) {
1691
+ return requestJson(url, { ...options, method: "POST", body: JSON.stringify(payload === void 0 ? {} : payload) });
1692
+ }
1693
+ async function getJson(url, options) {
1694
+ return requestJson(url, { ...options, method: "GET" });
1695
+ }
1696
+ async function requestJson(url, options) {
1697
+ let response2;
1698
+ try {
1699
+ response2 = await (options.fetcher ?? fetch)(url, {
1700
+ method: options.method,
1701
+ headers: {
1702
+ ...options.body !== void 0 ? { "Content-Type": "application/json" } : {},
1703
+ ...options.headers ?? {},
1704
+ ...options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {}
1705
+ },
1706
+ body: options.body,
1707
+ // Never follow a redirect with the sign-in token and the project attached.
1708
+ redirect: "error",
1709
+ signal: AbortSignal.timeout(options.timeoutMs)
1710
+ });
1711
+ } catch (error) {
1712
+ const name = error?.name;
1713
+ if (name === "TimeoutError" || name === "AbortError") {
1714
+ throw new HostedCallError("timeout", `${options.label} did not answer within ${Math.round(options.timeoutMs / 1e3)}s.`);
1715
+ }
1716
+ if (/redirect/i.test(`${error?.message ?? ""} ${error?.cause?.message ?? ""}`)) {
1717
+ throw new HostedCallError("redirect", `${options.label} was answered with a redirect. The Studio never follows redirects with your sign-in attached, so nothing was sent on. Check VIBERAVEN_API_URL.`);
1718
+ }
1719
+ if (isNetworkFetchFailure(error) || error instanceof TypeError) {
1720
+ throw new HostedCallError("network", `Could not reach VibeRaven at ${new URL(url).origin}. Check your connection and try again.`);
1721
+ }
1722
+ throw error;
1723
+ }
1724
+ if (!response2.ok) {
1725
+ let text = "";
1726
+ try {
1727
+ text = (await response2.text()).trim();
1728
+ } catch {
1729
+ text = "";
1730
+ }
1731
+ let upgradeUrl;
1732
+ try {
1733
+ const parsed = JSON.parse(text);
1734
+ if (typeof parsed.upgrade_url === "string" && parsed.upgrade_url) upgradeUrl = parsed.upgrade_url;
1735
+ } catch {
1736
+ }
1737
+ const retryAfter = Number(response2.headers.get("retry-after"));
1738
+ const authCall = options.label.startsWith("Sign-in");
1739
+ throw new HostedCallError("http", `${options.label} failed with ${response2.status}${authCall ? response2.status === 426 ? ": upgrade VibeRaven to use the updated sign-in protocol." : "" : text ? `: ${text.slice(0, 300)}` : ""}`, {
1740
+ status: response2.status,
1741
+ ...authCall ? {} : { body: text.slice(0, 2e3) },
1742
+ ...authCall ? {} : { upgradeUrl },
1743
+ retryAfterSeconds: Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : void 0
1744
+ });
1745
+ }
1746
+ try {
1747
+ return await response2.json();
1748
+ } catch {
1749
+ throw new HostedCallError("invalid_response", `${options.label} returned a body that is not JSON.`);
1750
+ }
1751
+ }
1752
+ async function startSignIn(baseUrl, timeoutMs, fetcher) {
1753
+ const payload = await postJson(`${normalizeBaseUrl(baseUrl)}/v1/auth/device/start`, DEVICE_START_REQUEST, { timeoutMs, label: "Sign-in start", fetcher });
1754
+ try {
1755
+ return validateDeviceAuthorization(payload);
1756
+ } catch {
1757
+ throw new HostedCallError("invalid_response", "Device sign-in requires the updated API and CLI protocol. Upgrade VibeRaven and deploy the matching device-flow API.");
1758
+ }
1759
+ }
1760
+ async function pollSignIn(baseUrl, deviceCode, timeoutMs, fetcher) {
1761
+ let payload;
1762
+ try {
1763
+ payload = await postJson(`${normalizeBaseUrl(baseUrl)}/v1/auth/device/poll`, { deviceCode }, { timeoutMs, label: "Sign-in poll", fetcher });
1764
+ } catch (error) {
1765
+ if (error instanceof HostedCallError && error.details.status === 410) return { status: "expired" };
1766
+ throw error;
1767
+ }
1768
+ if (!isSignInPoll(payload)) {
1769
+ throw new HostedCallError("invalid_response", "Sign-in poll response was invalid.");
1770
+ }
1771
+ return payload;
1772
+ }
1773
+ async function fetchAccount(baseUrl, accessToken, timeoutMs, fetcher) {
1774
+ const payload = await getJson(`${normalizeBaseUrl(baseUrl)}/v1/account/me`, { accessToken, timeoutMs, label: "Account check", fetcher });
1775
+ if (!isAccount(payload)) {
1776
+ throw new HostedCallError("invalid_response", "Account response did not match the expected shape.");
1777
+ }
1778
+ return { email: payload.email, plan: payload.plan, usage: payload.usage };
1779
+ }
1780
+ function isRecord(value) {
1781
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1782
+ }
1783
+ function isNonEmptyString(value) {
1784
+ return typeof value === "string" && value.trim().length > 0;
1785
+ }
1786
+ function isSignInPoll(value) {
1787
+ if (!isRecord(value) || !isNonEmptyString(value.status)) return false;
1788
+ if (value.status === "pending" || value.status === "expired" || value.status === "denied") return true;
1789
+ return value.status === "approved" && isNonEmptyString(value.accessToken) && isRecord(value.account) && isNonEmptyString(value.account.email) && (value.account.plan === "free" || value.account.plan === "pro") && (value.account.trialEndsAt === null || isNonEmptyString(value.account.trialEndsAt));
1790
+ }
1791
+ function isUsage(value) {
1792
+ if (!isRecord(value) || value.plan !== "free" && value.plan !== "pro") return false;
1793
+ if (value.remainingPrompts !== null && typeof value.remainingPrompts !== "number") return false;
1794
+ if (typeof value.used !== "number" || typeof value.limit !== "number") return false;
1795
+ if (value.period !== "lifetime" && value.period !== "monthly") return false;
1796
+ return Array.isArray(value.unlockedMapCategoryKeys) && value.unlockedMapCategoryKeys.every((k) => typeof k === "string");
1797
+ }
1798
+ function isAccount(value) {
1799
+ return isRecord(value) && isNonEmptyString(value.email) && (value.plan === "free" || value.plan === "pro") && isUsage(value.usage);
1800
+ }
1801
+
1802
+ // ../cli/src/openBrowser.ts
1803
+ var import_node_child_process2 = require("node:child_process");
1804
+ function createOpenCommand(target, platform = process.platform) {
1805
+ if (platform === "win32") {
1806
+ return {
1807
+ command: "rundll32",
1808
+ args: ["url.dll,FileProtocolHandler", target],
1809
+ shell: false
1810
+ };
1811
+ }
1812
+ if (platform === "darwin") {
1813
+ return { command: "open", args: [target], shell: false };
1814
+ }
1815
+ return { command: "xdg-open", args: [target], shell: false };
1816
+ }
1817
+ async function openWithSystemDefault(target) {
1818
+ const { command, args, shell } = createOpenCommand(target);
1819
+ await new Promise((resolve3, reject) => {
1820
+ const child = (0, import_node_child_process2.spawn)(command, args, { stdio: "ignore", shell });
1821
+ child.on("error", reject);
1822
+ child.on("exit", (code) => {
1823
+ if (code === 0) {
1824
+ resolve3();
1825
+ } else {
1826
+ reject(new Error(`Could not open browser (exit ${code ?? "unknown"}). Open manually: ${target}`));
1827
+ }
1828
+ });
1829
+ });
1830
+ }
1831
+ async function openUrlInBrowser(url) {
1832
+ const trimmed = url.trim();
1833
+ if (!/^https?:\/\//i.test(trimmed)) {
1834
+ throw new Error(`Not a valid http(s) URL: ${url}`);
1835
+ }
1836
+ await openWithSystemDefault(trimmed);
1837
+ }
1838
+
1839
+ // ../cli/src/providers/liveAdapters.ts
1840
+ async function boundedJson2(response2) {
1841
+ if (!response2.body) throw new Error("Empty response");
1842
+ const reader = response2.body.getReader();
1843
+ const chunks = [];
1844
+ let size = 0;
1845
+ try {
1846
+ while (true) {
1847
+ const next = await reader.read();
1848
+ if (next.done) break;
1849
+ size += next.value.byteLength;
1850
+ if (size > 256e3) throw new Error("Response too large");
1851
+ chunks.push(next.value);
1852
+ }
1853
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
1854
+ } finally {
1855
+ await reader.cancel().catch(() => {
1856
+ });
1857
+ reader.releaseLock();
1858
+ }
1859
+ }
1860
+
1861
+ // ../cli/src/version.ts
1862
+ var VERSION = "1.7.3";
1863
+
1864
+ // ../cli/src/commands/account.ts
1865
+ var loginNext = `npx -y viberaven@${VERSION} login --json`;
1866
+ function apiUrl(value) {
1867
+ const url = new URL(value);
1868
+ if (url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))) throw new Error("Invalid account API.");
1869
+ }
1870
+ function actionUrl(value) {
1871
+ if (typeof value !== "string" || value.length > 2048 || /[\x00-\x20\x7f]/.test(value)) return false;
1872
+ try {
1873
+ apiUrl(value.split("?")[0]);
1874
+ const url = new URL(value);
1875
+ return url.origin === deviceSiteOrigin() && !url.username && !url.password && !url.hash;
1876
+ } catch {
1877
+ return false;
1878
+ }
1879
+ }
1880
+ function statusCode(error) {
1881
+ return error instanceof HostedCallError ? error.details.status : void 0;
1882
+ }
1883
+ function defaults() {
1884
+ return {
1885
+ api: resolveApiBaseUrl(),
1886
+ configDir: defaultConfigDir(),
1887
+ fetch,
1888
+ now: Date.now,
1889
+ sleep: (ms) => new Promise((resolve3) => setTimeout(resolve3, ms)),
1890
+ openUrl: openUrlInBrowser,
1891
+ progress: (value) => console.error(JSON.stringify(value))
1892
+ };
1893
+ }
1894
+ async function loginAccount(options, deps) {
1895
+ try {
1896
+ apiUrl(deps.api);
1897
+ const credentials = new CredentialStore(deps.configDir, void 0);
1898
+ await credentials.assertLocation();
1899
+ const existing = await credentials.readFor(deps.api);
1900
+ if (existing) {
1901
+ try {
1902
+ const account = await fetchAccount(deps.api, existing.accessToken, 2e4, deps.fetch);
1903
+ await credentials.updateAccount(deps.api, existing.accessToken, { email: account.email, plan: account.plan });
1904
+ return { state: "authenticated", message: "Signed in. Use viberaven account to read the current live allowance." };
1905
+ } catch (error) {
1906
+ if (statusCode(error) !== 401) throw error;
1907
+ }
1908
+ }
1909
+ const started = await startSignIn(deps.api, 2e4, deps.fetch);
1910
+ const expires = Date.parse(started.expiresAt);
1911
+ if (!actionUrl(started.verificationUrl) || !Number.isFinite(expires) || expires <= deps.now() || expires > deps.now() + 63e4 || !Number.isFinite(started.pollIntervalSeconds) || started.pollIntervalSeconds < 1 || started.pollIntervalSeconds > 10) throw new Error("Invalid sign-in response.");
1912
+ deps.progress({ state: "requires_approval", actionUrl: started.verificationUrl, expiresAt: new Date(expires).toISOString() });
1913
+ if (!options.json && !options.noBrowser) await deps.openUrl(started.verificationUrl).catch(() => {
1914
+ });
1915
+ const deadline = Math.min(expires, deps.now() + 6e5);
1916
+ while (deps.now() < deadline) {
1917
+ await deps.sleep(Math.min(started.pollIntervalSeconds * 1e3, deadline - deps.now()));
1918
+ if (deps.now() >= deadline) break;
1919
+ let polled;
1920
+ try {
1921
+ polled = await pollSignIn(deps.api, started.deviceCode, Math.max(1, Math.min(2e4, deadline - deps.now())), deps.fetch);
1922
+ } catch (error) {
1923
+ const status = statusCode(error);
1924
+ if (error instanceof HostedCallError && (["network", "timeout"].includes(error.kind) || status === 429 || status !== void 0 && status >= 500 && status <= 599)) {
1925
+ const retryMs = (error.details.retryAfterSeconds ?? 0) * 1e3;
1926
+ if (retryMs > 0 && deps.now() < deadline) await deps.sleep(Math.min(retryMs, deadline - deps.now()));
1927
+ continue;
1928
+ }
1929
+ throw error;
1930
+ }
1931
+ if (polled.status === "pending") continue;
1932
+ if (polled.status === "expired" || polled.status === "denied") return { state: polled.status, message: "Sign-in was not approved. Run login again when you want to connect." };
1933
+ if (polled.status === "approved") {
1934
+ await credentials.write({ apiBaseUrl: deps.api, accessToken: polled.accessToken, account: polled.account });
1935
+ return { state: "authenticated", message: "Signed in. Use viberaven account to read the current live allowance." };
1936
+ }
1937
+ }
1938
+ return { state: "expired", message: "Browser approval expired. Run login again; no provider read or payment was made." };
1939
+ } catch (error) {
1940
+ if ([404, 426].includes(statusCode(error) ?? 0)) return { state: "unavailable", reason: "api_unsupported", message: "This account API does not support this sign-in protocol. Upgrade VibeRaven and ask the owner to deploy the matching API." };
1941
+ if (error instanceof CredentialLocationError) return {
1942
+ state: "unavailable",
1943
+ reason: "credential_location",
1944
+ message: "Set VIBERAVEN_CONFIG_DIR to a private user folder outside Git checkouts, then retry login. No credentials were printed."
1945
+ };
1946
+ return { state: "unavailable", message: "Sign-in could not complete. Check the account API and private local credential storage, then retry. No raw server or storage error is printed." };
1947
+ }
1948
+ }
1949
+ function allowance(raw, plan, now) {
1950
+ if (!raw || typeof raw !== "object") throw new Error("Invalid allowance.");
1951
+ const r = raw;
1952
+ const integer = (value, max = Number.MAX_SAFE_INTEGER) => Number.isSafeInteger(value) && Number(value) >= 0 && Number(value) <= max;
1953
+ const date = new Date(now);
1954
+ const periodStart = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1);
1955
+ const periodEnd = Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1);
1956
+ if (r.plan !== plan || typeof r.policyVersion !== "string" || !/^[A-Za-z0-9._-]{1,64}$/.test(r.policyVersion) || !integer(r.consumed) || !integer(r.reserved) || !integer(r.concurrencyLimit, 20) || r.concurrencyLimit < 1 || (plan === "pro" ? r.monthlyLimit !== null || r.remaining !== null : !integer(r.monthlyLimit, 1e5) || !integer(r.remaining, 1e5) || r.remaining !== Math.max(0, r.monthlyLimit - r.consumed - r.reserved)) || typeof r.periodStart !== "string" || r.periodStart.length > 40 || typeof r.periodEnd !== "string" || r.periodEnd.length > 40 || !Number.isFinite(Date.parse(r.periodStart)) || !Number.isFinite(Date.parse(r.periodEnd)) || Date.parse(r.periodStart) !== periodStart || Date.parse(r.periodEnd) !== periodEnd) throw new Error("Invalid allowance.");
1957
+ return {
1958
+ policyVersion: r.policyVersion,
1959
+ plan,
1960
+ monthlyLimit: r.monthlyLimit,
1961
+ consumed: r.consumed,
1962
+ reserved: r.reserved,
1963
+ remaining: r.remaining,
1964
+ concurrencyLimit: r.concurrencyLimit,
1965
+ periodStart: new Date(r.periodStart).toISOString(),
1966
+ periodEnd: new Date(r.periodEnd).toISOString()
1967
+ };
1968
+ }
1969
+ async function readAccount(deps) {
1970
+ try {
1971
+ apiUrl(deps.api);
1972
+ const credentials = new CredentialStore(deps.configDir, void 0);
1973
+ await credentials.assertLocation();
1974
+ const auth = await credentials.readFor(deps.api);
1975
+ if (!auth) return { state: "requires_connection", next: loginNext, message: "Run login and approve the free account in your browser. Local checks remain free without login." };
1976
+ const response2 = await deps.fetch(`${deps.api}/v1/account/live-allowance`, {
1977
+ method: "GET",
1978
+ headers: { Authorization: `Bearer ${auth.accessToken}` },
1979
+ redirect: "error",
1980
+ signal: AbortSignal.timeout(2e4)
1981
+ });
1982
+ if (!response2.ok) {
1983
+ await response2.body?.cancel();
1984
+ if (response2.status === 404) return { state: "unavailable", reason: "api_unsupported", message: "This account API does not support live allowance. Ask the owner to deploy the matching API." };
1985
+ if (response2.status === 401) return { state: "requires_connection", next: loginNext, message: "Account sign-in expired. Approve login again; local checks still need no account." };
1986
+ throw new Error("Account unavailable.");
1987
+ }
1988
+ const raw = await boundedJson2(response2);
1989
+ if (!raw || !["free", "pro"].includes(raw.plan) || !raw.liveSteps || !["available", "disabled", "unavailable"].includes(raw.liveSteps.state) || !actionUrl(raw.upgradeUrl) || raw.liveSteps.state !== "available" && raw.liveSteps.allowance !== null) throw new Error("Invalid account response.");
1990
+ return {
1991
+ state: "account",
1992
+ plan: raw.plan,
1993
+ liveSteps: {
1994
+ state: raw.liveSteps.state,
1995
+ allowance: raw.liveSteps.state === "available" ? allowance(raw.liveSteps.allowance, raw.plan, deps.now()) : null
1996
+ },
1997
+ upgradeUrl: raw.upgradeUrl,
1998
+ ...raw.plan === "pro" ? { billingUrl: new URL("/account", deviceSiteOrigin()).toString() } : {}
1999
+ };
2000
+ } catch (error) {
2001
+ if (error instanceof CredentialLocationError) return {
2002
+ state: "unavailable",
2003
+ reason: "credential_location",
2004
+ message: "Set VIBERAVEN_CONFIG_DIR to a private user folder outside Git checkouts, then retry account. No credentials were printed."
2005
+ };
2006
+ return { state: "unavailable", message: "Current plan and live allowance were not checked. Check the account API and private credential storage; no raw response is printed." };
2007
+ }
2008
+ }
2009
+
2010
+ // src/tools/account.ts
2011
+ var accountTools = [
2012
+ {
2013
+ name: "viberaven_account",
2014
+ description: "Read the signed-in VibeRaven plan, live-step allowance and upgrade URL, or check progress after browser approval. This does not start sign-in, create an account, read a provider or pay. Local repository checks need no account.",
2015
+ inputSchema: { type: "object", properties: {}, additionalProperties: false }
2016
+ },
2017
+ {
2018
+ name: "viberaven_login",
2019
+ description: "When the person asks to connect their VibeRaven account, set userRequestedSignIn to true. Returns the public browser approval link promptly; the person must approve it themselves. Then call viberaven_account to read progress and the plan. Never approve a link for the person, request credentials or use sign-in for a free local check.",
2020
+ inputSchema: { type: "object", properties: { userRequestedSignIn: { type: "boolean", description: "True only after the person asks to sign in. False or absent starts no flow." } }, additionalProperties: false }
2021
+ }
2022
+ ];
2023
+ var isAccountTool = (name) => name === "viberaven_account" || name === "viberaven_login";
2024
+ function response(view) {
2025
+ const state = view.state;
2026
+ return {
2027
+ content: [{ type: "text", text: JSON.stringify(view, null, 2) }],
2028
+ structuredContent: view,
2029
+ ...["unavailable", "expired", "denied", "invalid_arguments"].includes(state ?? "") ? { isError: true } : {}
2030
+ };
2031
+ }
2032
+ function createAccountToolHandler(depsFactory = defaults) {
2033
+ let pending;
2034
+ return async (name, raw) => {
2035
+ if (!isAccountTool(name) || !raw || typeof raw !== "object" || Array.isArray(raw)) return response({ state: "invalid_arguments", message: "Invalid account-tool arguments. Credentials and host configuration are not accepted." });
2036
+ const args = raw;
2037
+ if (Object.keys(args).some((key) => name !== "viberaven_login" || key !== "userRequestedSignIn") || args.userRequestedSignIn !== void 0 && typeof args.userRequestedSignIn !== "boolean") return response({ state: "invalid_arguments", message: "Invalid account-tool arguments. Credentials and host configuration are not accepted." });
2038
+ if (name === "viberaven_account") {
2039
+ if (pending?.finished && pending.view?.state === "authenticated") pending = void 0;
2040
+ const account = await readAccount(depsFactory());
2041
+ if (account.state === "requires_connection" && pending) {
2042
+ if (!pending.finished) return response(pending.view ?? await pending.initial);
2043
+ return response({ ...account, signIn: pending.view });
2044
+ }
2045
+ return response(account);
2046
+ }
2047
+ if (args.userRequestedSignIn !== true) return response({ state: "requires_user_request", message: "Ask the person whether they want to sign in. Local checks remain free without an account." });
2048
+ if (pending && !pending.finished) return response(pending.view ?? await pending.initial);
2049
+ let resolveInitial;
2050
+ const initial = new Promise((resolve3) => {
2051
+ resolveInitial = resolve3;
2052
+ });
2053
+ const flow = { initial, view: void 0, finished: false };
2054
+ pending = flow;
2055
+ const deps = { ...depsFactory(), progress: (view) => {
2056
+ flow.view = view;
2057
+ resolveInitial(view);
2058
+ } };
2059
+ void loginAccount({ json: true, noBrowser: true }, deps).then((view) => {
2060
+ flow.view = view;
2061
+ flow.finished = true;
2062
+ resolveInitial(view);
2063
+ }, () => {
2064
+ const view = { state: "unavailable", message: "Sign-in could not complete. Retry the account API; no credentials were printed." };
2065
+ flow.view = view;
2066
+ flow.finished = true;
2067
+ resolveInitial(view);
2068
+ });
2069
+ return response(await initial);
2070
+ };
2071
+ }
2072
+ var handleAccountTool = createAccountToolHandler();
2073
+
2074
+ // src/lib/cli-runner.ts
2075
+ var import_node_child_process3 = require("node:child_process");
1372
2076
  var import_node_fs3 = require("node:fs");
1373
- var import_node_path2 = require("node:path");
2077
+ var import_node_path3 = require("node:path");
1374
2078
 
1375
2079
  // src/lib/work-report-runner.ts
1376
2080
  var import_node_fs2 = require("node:fs");
1377
2081
  var import_node_module = require("node:module");
1378
- var import_node_path = require("node:path");
2082
+ var import_node_path2 = require("node:path");
1379
2083
 
1380
2084
  // ../../shared/workReportRunner.ts
1381
2085
  var import_node_fs = require("node:fs");
@@ -1394,7 +2098,7 @@ function runWorkReportProcess(entry, args, cwd3, spawnFn2) {
1394
2098
  } catch {
1395
2099
  return Promise.resolve(workReportFailure());
1396
2100
  }
1397
- return new Promise((resolve2) => {
2101
+ return new Promise((resolve3) => {
1398
2102
  let settled = false, stdoutBytes = 0, stderrBytes = 0;
1399
2103
  const chunks = [];
1400
2104
  let child;
@@ -1402,7 +2106,7 @@ function runWorkReportProcess(entry, args, cwd3, spawnFn2) {
1402
2106
  if (!settled) {
1403
2107
  settled = true;
1404
2108
  clearTimeout(timer);
1405
- resolve2(result);
2109
+ resolve3(result);
1406
2110
  }
1407
2111
  };
1408
2112
  const fail = () => {
@@ -1448,20 +2152,20 @@ ${stdout.trim()}` });
1448
2152
 
1449
2153
  // src/lib/work-report-runner.ts
1450
2154
  var within = (root, target) => {
1451
- const rel = (0, import_node_path.relative)(root, target);
1452
- return !rel || !(0, import_node_path.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(`..${import_node_path.sep}`);
2155
+ const rel = (0, import_node_path2.relative)(root, target);
2156
+ return !rel || !(0, import_node_path2.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(`..${import_node_path2.sep}`);
1453
2157
  };
1454
2158
  function resolveInstalledCli(version, cwd3) {
1455
2159
  const override = process.env.VIBERAVEN_CLI_PATH;
1456
2160
  try {
1457
- if (override !== void 0 && !(0, import_node_path.isAbsolute)(override)) throw new Error("Unavailable installed CLI");
1458
- const selected = override ?? (0, import_node_path.join)((0, import_node_path.dirname)((0, import_node_module.createRequire)(__filename).resolve("@viberaven/cli/package.json")), "dist", "cli.js");
2161
+ if (override !== void 0 && !(0, import_node_path2.isAbsolute)(override)) throw new Error("Unavailable installed CLI");
2162
+ const selected = override ?? (0, import_node_path2.join)((0, import_node_path2.dirname)((0, import_node_module.createRequire)(__filename).resolve("@viberaven/cli/package.json")), "dist", "cli.js");
1459
2163
  const info = (0, import_node_fs2.lstatSync)(selected);
1460
2164
  if (!info.isFile() || info.isSymbolicLink()) throw new Error("Unavailable installed CLI");
1461
2165
  const entry = (0, import_node_fs2.realpathSync)(selected);
1462
- const root = (0, import_node_fs2.realpathSync)((0, import_node_path.join)((0, import_node_path.dirname)(entry), ".."));
1463
- if (entry !== (0, import_node_path.resolve)(selected) || entry !== (0, import_node_path.join)(root, "dist", "cli.js") || within((0, import_node_fs2.realpathSync)(cwd3), entry)) throw new Error("Unavailable installed CLI");
1464
- const manifestPath = (0, import_node_path.join)(root, "package.json"), manifestInfo = (0, import_node_fs2.lstatSync)(manifestPath);
2166
+ const root = (0, import_node_fs2.realpathSync)((0, import_node_path2.join)((0, import_node_path2.dirname)(entry), ".."));
2167
+ if (entry !== (0, import_node_path2.resolve)(selected) || entry !== (0, import_node_path2.join)(root, "dist", "cli.js") || within((0, import_node_fs2.realpathSync)(cwd3), entry)) throw new Error("Unavailable installed CLI");
2168
+ const manifestPath = (0, import_node_path2.join)(root, "package.json"), manifestInfo = (0, import_node_fs2.lstatSync)(manifestPath);
1465
2169
  if (!manifestInfo.isFile() || manifestInfo.isSymbolicLink() || manifestInfo.size > 65536 || (0, import_node_fs2.realpathSync)(manifestPath) !== manifestPath) throw new Error("Unavailable installed CLI");
1466
2170
  const manifest = JSON.parse((0, import_node_fs2.readFileSync)(manifestPath, "utf8"));
1467
2171
  if (manifest.name !== "@viberaven/cli" || manifest.version !== version) throw new Error("Unavailable installed CLI");
@@ -1493,14 +2197,14 @@ var cachedVersion;
1493
2197
  function mcpVersion() {
1494
2198
  if (cachedVersion) return cachedVersion;
1495
2199
  let found;
1496
- for (let dir = __dirname, depth = 0; depth < 4 && !found; depth += 1, dir = (0, import_node_path2.dirname)(dir)) {
2200
+ for (let dir = __dirname, depth = 0; depth < 4 && !found; depth += 1, dir = (0, import_node_path3.dirname)(dir)) {
1497
2201
  try {
1498
- const manifest = JSON.parse((0, import_node_fs3.readFileSync)((0, import_node_path2.join)(dir, "package.json"), "utf8"));
2202
+ const manifest = JSON.parse((0, import_node_fs3.readFileSync)((0, import_node_path3.join)(dir, "package.json"), "utf8"));
1499
2203
  if (manifest.name === MCP_PACKAGE && typeof manifest.version === "string") found = manifest.version;
1500
2204
  } catch {
1501
2205
  }
1502
2206
  }
1503
- found ??= true ? "1.7.2" : void 0;
2207
+ found ??= true ? "1.7.3" : void 0;
1504
2208
  if (!found || !PLAIN_VERSION.test(found)) {
1505
2209
  throw new Error(`Could not read a valid ${MCP_PACKAGE} version (got ${JSON.stringify(found)}), so the matching ${CLI_PACKAGE} cannot be pinned.`);
1506
2210
  }
@@ -1525,12 +2229,12 @@ function cliChildEnv(env = process.env) {
1525
2229
  }
1526
2230
  return out;
1527
2231
  }
1528
- var spawnFn = import_node_child_process.spawn;
2232
+ var spawnFn = import_node_child_process3.spawn;
1529
2233
  function __setSpawnForTest(fn) {
1530
2234
  spawnFn = fn;
1531
2235
  }
1532
2236
  function __resetSpawnForTest() {
1533
- spawnFn = import_node_child_process.spawn;
2237
+ spawnFn = import_node_child_process3.spawn;
1534
2238
  }
1535
2239
  function safeStringArg(value, label) {
1536
2240
  if (typeof value !== "string") throw new Error(`Invalid ${label}: expected string`);
@@ -1632,7 +2336,7 @@ function runVibeRavenDetailed(args, cwd3) {
1632
2336
  } catch (error) {
1633
2337
  return Promise.resolve(transportFailure(error));
1634
2338
  }
1635
- return new Promise((resolve2) => {
2339
+ return new Promise((resolve3) => {
1636
2340
  let child;
1637
2341
  try {
1638
2342
  child = spawnFn(built.command, built.args, {
@@ -1643,7 +2347,7 @@ function runVibeRavenDetailed(args, cwd3) {
1643
2347
  stdio: ["ignore", "pipe", "pipe"]
1644
2348
  });
1645
2349
  } catch (error) {
1646
- resolve2(transportFailure(error));
2350
+ resolve3(transportFailure(error));
1647
2351
  return;
1648
2352
  }
1649
2353
  let stdout = "";
@@ -1657,7 +2361,7 @@ function runVibeRavenDetailed(args, cwd3) {
1657
2361
  if (settled) return;
1658
2362
  settled = true;
1659
2363
  if (timer) clearTimeout(timer);
1660
- resolve2(result);
2364
+ resolve3(result);
1661
2365
  };
1662
2366
  const stopRls = (reason) => {
1663
2367
  finish(transportFailure(new Error(reason)));
@@ -1725,7 +2429,8 @@ var ALL_TOOLS = [
1725
2429
  ...WORK_TOOLS,
1726
2430
  PROVIDER_TOOL,
1727
2431
  RECENT_PROVIDER_CHANGES_TOOL,
1728
- ...LIVE_TOOLS
2432
+ ...LIVE_TOOLS,
2433
+ ...accountTools
1729
2434
  ];
1730
2435
  function parseJsonObjectFromToolText(text) {
1731
2436
  const start = text.indexOf("{");
@@ -1749,6 +2454,7 @@ function isCompletedNegativeNpmVerdict(receipt) {
1749
2454
  }
1750
2455
  }
1751
2456
  async function callTool(name, args) {
2457
+ if (isAccountTool(name)) return (await handleAccountTool(name, args ?? {})).content[0].text;
1752
2458
  if (name === "provider_playbook") return providerPlaybook(args).content[0].text;
1753
2459
  if (name === "recent_provider_changes") return recentProviderChanges(args).content[0].text;
1754
2460
  return runVibeRaven(buildToolArgs(name, args || {}), args?.cwd);
@@ -1756,6 +2462,7 @@ async function callTool(name, args) {
1756
2462
  async function handleRequest(method, params) {
1757
2463
  if (method === "tools/list") return { tools: ALL_TOOLS };
1758
2464
  if (method === "tools/call") {
2465
+ if (isAccountTool(params.name)) return handleAccountTool(params.name, params.arguments ?? {});
1759
2466
  if (params.name === "provider_playbook") return providerPlaybook(params.arguments);
1760
2467
  if (params.name === "recent_provider_changes") return recentProviderChanges(params.arguments ?? {});
1761
2468
  const args = params.arguments || {};
@@ -1784,6 +2491,7 @@ async function handleRequest(method, params) {
1784
2491
  __resetSpawnForTest,
1785
2492
  __setSpawnForTest,
1786
2493
  callTool,
2494
+ createAccountToolHandler,
1787
2495
  handleRequest,
1788
2496
  parseJsonObjectFromToolText
1789
2497
  });