@viberaven/mcp 1.7.1 → 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.
package/dist/server.js CHANGED
@@ -573,6 +573,321 @@ var registry_generated_default = {
573
573
  }
574
574
  };
575
575
 
576
+ // ../providers/recent-changes.generated.mjs
577
+ var recent_changes_generated_default = {
578
+ "hash": "d2aaaaf9089270914954d2a8fd7b4fa3933c8525111162650feeb7bf726c67dc",
579
+ "pack": {
580
+ "schemaVersion": 1,
581
+ "packVersion": "1.0.0",
582
+ "reviewedAt": "2026-10-30",
583
+ "dateConvention": "effective = provider-stated date; announced = publication/release date; verified = checked date only, not rollout.",
584
+ "limits": [
585
+ "Guidance only; repository and live provider state remain not_checked.",
586
+ "Static, reviewed official sources can change. A matching entry is a candidate explanation, not a diagnosis or evidence that a fix worked.",
587
+ "No provider connection, account, credential, runtime file read, network request, deployment or data change is performed."
588
+ ],
589
+ "correctionsAndConflicts": [
590
+ "Lovable current official dates Oct 23 retirement/Dec 1 deletion replace seeded Oct5/Nov 4. Affected built-in-backend projects only.",
591
+ "Vercel current docs list 26.x default; 24.x remains supported but is not the current default claim.",
592
+ "Railway IaC migration doc says --apply clears settings, but newer Oct 16 changelog explicitly requires separate cutover. Current CLI help must be inspected before execution.",
593
+ "Railway announcement has2026-08-21 visible publish date despite Aug 20 URL; avoid inventing Aug 20 announced date.",
594
+ "Clerk production-instance setup is evergreen verified Oct 30, not an Oct 30 provider change. Related secret masking is dated Oct 19.",
595
+ "Supabase legacy-key end 2026 deprecation is not an exact shutdown day; no mandatory day invented."
596
+ ],
597
+ "sources": [
598
+ {
599
+ "id": "supabase-grants-announcement",
600
+ "url": "https://supabase.com/changelog/45329-breaking-change-tables-not-exposed-to-data-and-graphql-api-automatically",
601
+ "notes": "Dated April 28, 2026. Announces October 30 application to existing projects; newly created public tables need explicit grants. Existing table grants persist; direct Postgres users unaffected. Official example uses code 42501 and permission denied for table your_table."
602
+ },
603
+ {
604
+ "id": "supabase-api-security",
605
+ "url": "https://supabase.com/docs/guides/api/securing-your-api",
606
+ "notes": "Grants determine object/role access; RLS controls rows. Configure both for API-exposed tables. Does not prove hosted project rollout or actual grants."
607
+ },
608
+ {
609
+ "id": "vercel-node20-announcement",
610
+ "url": "https://vercel.com/changelog/node-js-20-is-being-deprecated",
611
+ "notes": "Published July 14, 2026. October 1 deprecation for Builds/Functions affects new deployments, not existing invocations. Official upgrade example sets engines.node to 24.x, matches local/CI and reruns build/tests."
612
+ },
613
+ {
614
+ "id": "vercel-node-versions",
615
+ "url": "https://vercel.com/docs/functions/runtimes/node-js/node-js-versions",
616
+ "notes": "Current docs list 26.x default and 24.x/22.x supported. package.json engines.node overrides Project Settings. Do not repeat seed's 24.x default claim."
617
+ },
618
+ {
619
+ "id": "vercel-node-error-source",
620
+ "url": "https://raw.githubusercontent.com/vercel/vercel/main/packages/build-utils/src/fs/node-version.ts",
621
+ "notes": "Official mutable main source lists20.x discontinueDate 2026-10-01 and constructs discontinued error prefix with selected range; code BUILD_UTILS_NODE_VERSION_DISCONTINUED. Prefix instantiated at20.x is source-derived, not a deployment observation."
622
+ },
623
+ {
624
+ "id": "next164-announcement",
625
+ "url": "https://nextjs.org/blog/next-16-4",
626
+ "notes": "Dated October 6,2026. New create-next-app apps enable Cache Components by default; existing apps require adoption. This is not a universal default switch for every existing app."
627
+ },
628
+ {
629
+ "id": "next-blocking-error",
630
+ "url": "https://nextjs.org/docs/messages/blocking-route",
631
+ "notes": "Official exact error title. With cacheComponents enabled, request-time async data needs parent Suspense. Cache deliberately reusable data with use cache, or move runtime read into child below Suspense. Build --debug-prerender may identify component."
632
+ },
633
+ {
634
+ "id": "next-cache-migration",
635
+ "url": "https://nextjs.org/docs/app/guides/migrating-to-cache-components",
636
+ "notes": "Route configs dynamic/revalidate/fetchCache replaced by use cache/cacheLife under Cache Components; avoid caching user request data indiscriminately."
637
+ },
638
+ {
639
+ "id": "lovable-environments",
640
+ "url": "https://docs.lovable.dev/features/environments",
641
+ "notes": "Current guide states retirement October 23,2026; detached Test databases restorable untilDecember 1,2026 then deleted. Built-in backend only. Drafts preview code with same database. Publishing schema/policies/functions does not copy rows/files/auth settings. Restore request required after detachment."
642
+ },
643
+ {
644
+ "id": "railway-cac",
645
+ "url": "https://docs.railway.com/config-as-code",
646
+ "notes": "Existing railway.json/toml services continue until 2026-12-01 hard cutoff; new services cannot opt into CaC. Prefer .railway/railway.ts."
647
+ },
648
+ {
649
+ "id": "railway-iac",
650
+ "url": "https://docs.railway.com/infrastructure-as-code",
651
+ "notes": "Review railway config plan before apply; whole-project omissions can delete resources; deployments do not read .railway directly. Migration section still claims --apply clears settings, conflicting with newer Oct 16 changelog's separate cutover."
652
+ },
653
+ {
654
+ "id": "railway-guided-migration",
655
+ "url": "https://railway.com/changelog/2026-10-16-activity-feed-filters",
656
+ "notes": "Dated Oct 16,2026. --apply writes config without switching services. migrate cutover lists effects/saves old paths; status reports and undo restores paths. Use newer scoped migration flow and installed CLI help rather than stale IaC snippet."
657
+ },
658
+ {
659
+ "id": "railway-cac-announcement",
660
+ "url": "https://railway.com/changelog/2026-08-20-railway-anon",
661
+ "notes": "Visible publish date 2026-08-21 despiteURLAug 20. Announces August 28 new-project restriction and December 1 end. Its older statement allows new services in existing projects; current CaC docs disallow new services, so avoid generalizing that exception."
662
+ },
663
+ {
664
+ "id": "clerk-production",
665
+ "url": "https://clerk.com/docs/guides/development/deployment/production",
666
+ "notes": "Evergreen current guidance: create/select production instance; use pk_live_/sk_live_ pair in production host vars then redeploy. Configure production OAuth/webhooks/DNS. This is verified Oct 30, not a newOct 30 rollout."
667
+ },
668
+ {
669
+ "id": "clerk-environments",
670
+ "url": "https://clerk.com/docs/guides/development/managing-environments",
671
+ "notes": "Development/Production instances differ; development unsuitable for production. Does not prove a particular app's live keys or readiness."
672
+ },
673
+ {
674
+ "id": "clerk-keys-once",
675
+ "url": "https://clerk.com/changelog/2026-10-19-secret-keys-visible-only-on-creation",
676
+ "notes": "Published Oct 19; URL supplies2026 and footer2026. Full secret value shown only on creation. Existing keys still work; if lost, add replacement, update code, delete old only after no longer used."
677
+ },
678
+ {
679
+ "id": "supabase-api-keys",
680
+ "url": "https://supabase.com/docs/guides/getting-started/api-keys",
681
+ "notes": "Current docs say legacy anon/service_role deprecated by end 2026, no exact shutdown date. Publishable/secret replace them; secret server-only/BYPASSRLS and browser rejectionHTTP401. New keys not JWTs; use apikey header, not Authorization bearer as a userJWT."
682
+ },
683
+ {
684
+ "id": "supabase-key-migration",
685
+ "url": "https://supabase.com/docs/guides/getting-started/migrating-to-new-api-keys",
686
+ "notes": "Create new keys alongside legacy; replace frontend anon with publishable and backend service_role with secret. Check components then disable legacy keys. Grant/RLS behavior retained, and key switch doesn't fix access policy."
687
+ }
688
+ ],
689
+ "entries": [
690
+ {
691
+ "id": "supabase-explicit-data-api-grants",
692
+ "provider": "supabase",
693
+ "date": "2026-10-30",
694
+ "dateKind": "effective",
695
+ "dateNote": "Provider-announced application date for existing projects; announced 2026-04-28. This is not verification that any particular hosted project has rolled over.",
696
+ "whatChanged": "After the rollout, new public tables need explicit role grants to be reachable through the Data/GraphQL API. Existing table grants remain; direct Postgres connections are unaffected.",
697
+ "errorText": "permission denied for table your_table",
698
+ "errorTextKind": "official_documentation_example",
699
+ "errorCode": "42501",
700
+ "fix": "Confirm the actual role/table/operation. In a reviewed migration, grant only required privileges (for example GRANT SELECT ON public.your_table TO authenticated), and keep RLS enabled with policies matching intended row access. Do not replace a missing grant with a server secret in browser code.",
701
+ "officialSource": "https://supabase.com/changelog/45329-breaking-change-tables-not-exposed-to-data-and-graphql-api-automatically",
702
+ "sourceIds": [
703
+ "supabase-grants-announcement",
704
+ "supabase-api-security"
705
+ ],
706
+ "limitations": "Repo inspection cannot establish hosted grants, actual rollout, policy behavior, or a successful live request."
707
+ },
708
+ {
709
+ "id": "vercel-node20-to24",
710
+ "provider": "vercel",
711
+ "date": "2026-10-01",
712
+ "dateKind": "effective",
713
+ "dateNote": "Announced 2026-07-14. Scope: new Builds/Functions deployments, not already-deployed function invocations.",
714
+ "whatChanged": "Node 20 is discontinued for new Builds/Functions deployments. Node 24 remains supported; current docs additionally list Node 26 as default, so 24 must not be described as today's default.",
715
+ "errorText": 'Node.js Version "20.x" is discontinued and must be upgraded.',
716
+ "errorTextKind": "official_source_template_instantiated",
717
+ "errorCode": "BUILD_UTILS_NODE_VERSION_DISCONTINUED",
718
+ "fix": "Change a Node 20 engines.node pin to 24.x, or select 24.x in Project Settings when engines is absent; engines overrides settings. Match local/CI runtime, reinstall dependencies, run build/tests, then verify the runtime in a future deployment. No deployment performed here.",
719
+ "officialSource": "https://vercel.com/changelog/node-js-20-is-being-deprecated",
720
+ "sourceIds": [
721
+ "vercel-node20-announcement",
722
+ "vercel-node-versions",
723
+ "vercel-node-error-source"
724
+ ],
725
+ "limitations": "Exact prefix comes from official source with 20.x substituted, not a newly observed build. Container deployments have a separate runtime model."
726
+ },
727
+ {
728
+ "id": "next-cache-components-suspense",
729
+ "provider": "nextjs",
730
+ "date": "2026-10-06",
731
+ "dateKind": "announced",
732
+ "dateNote": "Next 16.4 release date. Default enablement statement applies to newly generated create-next-app apps; existing app config must be inspected.",
733
+ "whatChanged": "Next 16.4 enables Cache Components in new create-next-app apps. With cacheComponents enabled, uncached request-time reads without a parent Suspense boundary trigger the documented error.",
734
+ "errorText": "Uncached data was accessed outside of `<Suspense>`",
735
+ "errorTextKind": "official_documentation_title",
736
+ "errorCode": null,
737
+ "fix": 'Move request-time reads into a child rendered under <Suspense fallback={...}>. For deliberately reusable data, use "use cache" with an appropriate lifetime. Migrate incompatible route configs such as dynamic/revalidate/fetchCache using the official guide, and build to verify.',
738
+ "officialSource": "https://nextjs.org/blog/next-16-4",
739
+ "sourceIds": [
740
+ "next164-announcement",
741
+ "next-blocking-error",
742
+ "next-cache-migration"
743
+ ],
744
+ "limitations": "No app/version-specific reproduction or build run. Do not cache authentication/request data indiscriminately."
745
+ },
746
+ {
747
+ "id": "lovable-test-live-retired",
748
+ "provider": "lovable",
749
+ "date": "2026-10-23",
750
+ "dateKind": "effective",
751
+ "dateNote": "Current official guide differs from seeded VibeRaven dates Oct 5/Nov 4. Current retirement Oct 23 and deletion Dec 1 verified Oct 30.",
752
+ "whatChanged": "Separate Test/Live on the built-in backend retired; projects use one database. Detached Test databases remain restorable by request until 2026-12-01, then are deleted. Drafts share data with the published app.",
753
+ "errorText": null,
754
+ "errorTextKind": "not_documented",
755
+ "symptom": "Test/Live switcher disappears; missing data may remain in detached Test rather than Live.",
756
+ "fix": "If needed data is in detached Test, request restoration before December 1, export needed rows/files and move them into Live, reconcile duplicates and verify Live content. Publishing alone does not migrate rows/files/auth settings. No account or data changes performed.",
757
+ "officialSource": "https://docs.lovable.dev/features/environments",
758
+ "sourceIds": [
759
+ "lovable-environments"
760
+ ],
761
+ "limitations": "Applies to built-in-backend projects that used the split, not every external Supabase project. No runtime error quote supplied by the guide."
762
+ },
763
+ {
764
+ "id": "railway-config-as-code-retirement",
765
+ "provider": "railway",
766
+ "date": "2026-12-01",
767
+ "dateKind": "effective",
768
+ "dateNote": "Upcoming hard cutoff documented today; announcement page visible date 2026-08-21 despite Aug 20 URL. Guided migration announced Oct 16.",
769
+ "whatChanged": "railway.json/railway.toml Config as Code is deprecated and stops working for existing services at Dec 1 cutoff. New services cannot opt in; prefer .railway/railway.ts IaC.",
770
+ "errorText": null,
771
+ "errorTextKind": "not_documented",
772
+ "symptom": "IaC plan is blocked for a service still managed by a CaC file; no exact cutoff failure message verified.",
773
+ "fix": "Preview with railway config migrate, inspect generated IaC, write with --apply, review separate migrate cutover using current CLI help, then migrate status and config plan. Review all changes/deletions before any authorized apply; committing .railway alone does not apply configuration.",
774
+ "officialSource": "https://docs.railway.com/config-as-code",
775
+ "sourceIds": [
776
+ "railway-cac",
777
+ "railway-iac",
778
+ "railway-guided-migration",
779
+ "railway-cac-announcement"
780
+ ],
781
+ "limitations": "Official IaC page still says --apply clears config settings; newer Oct 16 changelog explicitly separates cutover. No CLI/provider execution here; avoid unverified variables flags or predicting post-cutoff fallback."
782
+ },
783
+ {
784
+ "id": "clerk-production-instance-keys",
785
+ "provider": "clerk",
786
+ "date": "2026-10-30",
787
+ "dateKind": "verified",
788
+ "dateNote": "Verification date only for evergreen production-instance guidance, not a rollout date. Related show-secret-once change announced 2026-10-19.",
789
+ "whatChanged": "Current production deployment guidance requires production-instance pk_live_/sk_live_ keys. Separately, since the Oct 19 announcement, existing secret values are masked and full values appear only when created.",
790
+ "errorText": null,
791
+ "errorTextKind": "not_documented",
792
+ "symptom": "Production app still uses pk_test_/sk_test_, or a lost secret cannot be revealed again.",
793
+ "fix": "Use matching production-instance keys in the production host environment and redeploy, with production OAuth/webhook/DNS configuration checked. If a secret value is lost, create a replacement, update all consuming components, then delete the old one only after it is unused. Existing keys are not invalidated merely by masking.",
794
+ "officialSource": "https://clerk.com/docs/guides/development/deployment/production",
795
+ "sourceIds": [
796
+ "clerk-production",
797
+ "clerk-environments",
798
+ "clerk-keys-once"
799
+ ],
800
+ "limitations": "No account, secret, production-instance, redirect, or deployment inspection. These docs give no single exact runtime error for the whole symptom."
801
+ },
802
+ {
803
+ "id": "supabase-publishable-secret-api-keys",
804
+ "provider": "supabase",
805
+ "date": "2026-10-30",
806
+ "dateKind": "verified",
807
+ "dateNote": "Verification date only. Docs say legacy keys deprecated by end 2026; no exact shutdown day claimed or checked here.",
808
+ "whatChanged": "Publishable (sb_publishable_) and secret (sb_secret_) replace legacy anon/service_role keys. New keys are not JWTs; both systems can coexist during migration.",
809
+ "errorText": "HTTP 401 Unauthorized",
810
+ "errorTextKind": "official_documented_http_status",
811
+ "symptom": "A secret key sent with a browser User-Agent is rejected; this is not a guarantee against use from scripts.",
812
+ "fix": "Replace public/client anon usage with publishable and backend service_role usage with secret; keep privileged keys out of client code. Send API keys through apikey; use actual user JWTs for user Authorization. Verify all clients before disabling legacy keys. Rotate a leaked secret after fixing its exposure.",
813
+ "officialSource": "https://supabase.com/docs/guides/getting-started/api-keys",
814
+ "sourceIds": [
815
+ "supabase-api-keys",
816
+ "supabase-key-migration"
817
+ ],
818
+ "limitations": "No key/account/provider inspection, rotation, or live request. Switching key formats does not fix missing grants or RLS policies."
819
+ }
820
+ ]
821
+ }
822
+ };
823
+
824
+ // ../providers/recentChanges.mjs
825
+ var availableProviders = [...new Set(recent_changes_generated_default.pack.entries.map((entry) => entry.provider))].sort();
826
+ var RECENT_PROVIDER_CHANGES_TOOL = {
827
+ name: "recent_provider_changes",
828
+ title: "Check recent provider changes",
829
+ description: `Check dated official provider guidance before answering a provider error or updating a deployment. Returns candidate changes, documented errors or symptoms, fixes, date meanings and official supporting sources. Filter by provider or redacted error keywords. Available providers: ${availableProviders.join(", ")}.
830
+ Limits: guidance only; does not read your repo, connect to providers, run fixes or verify rollout, deployment or live behavior.`,
831
+ inputSchema: {
832
+ type: "object",
833
+ properties: {
834
+ provider: { type: "string", enum: [...availableProviders], description: "Optional lowercase provider id. Unsupported ids return the bounded available list." },
835
+ query: { type: "string", minLength: 1, maxLength: 500, description: "Optional redacted error text or public keywords. Remove credentials, private paths and personal data before calling." },
836
+ limit: { type: "integer", minimum: 1, maximum: 8, default: 5, description: "Maximum entries, 1 to 8; default 5." }
837
+ },
838
+ additionalProperties: false
839
+ },
840
+ outputSchema: {
841
+ type: "object",
842
+ properties: { packVersion: { type: "string" }, packHash: { type: "string" }, reviewedAt: { type: "string" }, dateConvention: { type: "string" }, entries: { type: "array", items: { type: "object" }, maxItems: 8 }, availableProviders: { type: "array", items: { type: "string" } }, limits: { type: "array", items: { type: "string" } }, correctionsAndConflicts: { type: "array", items: { type: "string" } }, verification: { type: "object" } },
843
+ required: ["packVersion", "packHash", "reviewedAt", "dateConvention", "entries", "availableProviders", "limits", "correctionsAndConflicts", "verification"],
844
+ additionalProperties: false
845
+ },
846
+ annotations: { title: "Check recent provider changes", readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true }
847
+ };
848
+ var stopWords = /* @__PURE__ */ new Set([...availableProviders, "next", "js", ..."a an and app apps are as at be before by can does error for from has have how in is it not of on or provider the this to was what when which with".split(" ")]);
849
+ var words = (text) => [...new Set((text.toLowerCase().match(/[a-z0-9_]+/g) ?? []).filter((word) => (word.length >= 3 || /^\d{2,}$/.test(word)) && !stopWords.has(word)))];
850
+ var indexed = recent_changes_generated_default.pack.entries.map((entry) => ({ entry, words: new Set(words([entry.id, entry.provider, entry.whatChanged, entry.errorText, entry.errorCode, entry.symptom, entry.fix].filter(Boolean).join(" "))) }));
851
+ function invalidInput(field) {
852
+ return { isError: true, content: [{ type: "text", text: `invalid_input: Use optional supported provider, redacted query (1 to 500 characters), and limit (integer 1 to 8).
853
+ Field: ${field}
854
+ Example arguments: {"provider":"supabase","query":"42501","limit":5}
855
+ Next step: Choose an available provider: ${availableProviders.join(", ")}. Retrieval returns guidance; no connection or check was attempted.` }] };
856
+ }
857
+ function renderRecentChanges(result) {
858
+ const lines = [`Recent provider changes ${result.packVersion} (reviewed ${result.reviewedAt})`, result.dateConvention, "Guidance only. Repository and live checks: not checked.", ""];
859
+ if (!result.entries.length) lines.push("No entry matched. A missing match does not rule out a provider change; inspect the current official documentation and actual app evidence.");
860
+ for (const entry of result.entries) {
861
+ lines.push(`${entry.provider}: ${entry.id}`, `Date: ${entry.date} (${entry.dateKind}). ${entry.dateNote}`, `What changed: ${entry.whatChanged}`);
862
+ if (entry.errorText !== null) lines.push(`Error: ${entry.errorText} (${entry.errorTextKind}${entry.errorCode ? `; code ${entry.errorCode}` : ""})`);
863
+ else lines.push(`Error: no exact error documented (${entry.errorTextKind}).`);
864
+ if (entry.symptom) lines.push(`Symptom: ${entry.symptom}`);
865
+ lines.push(`Fix guidance: ${entry.fix}`, `Official source: ${entry.officialSource}`, `Supporting sources: ${entry.sources.map((source) => source.url).join(" ")}`, `Limits: ${entry.limitations}`, "");
866
+ }
867
+ lines.push("Source corrections and conflicts:", ...result.correctionsAndConflicts.map((note) => `- ${note}`), "Limits:", ...result.limits.map((limit) => `- ${limit}`));
868
+ return lines.join("\n");
869
+ }
870
+ function recentProviderChanges(args) {
871
+ if (!args || typeof args !== "object" || Array.isArray(args) || Object.keys(args).some((key) => !["provider", "query", "limit"].includes(key))) return invalidInput("arguments");
872
+ if (Object.hasOwn(args, "provider") && (typeof args.provider !== "string" || !availableProviders.includes(args.provider))) return invalidInput("provider");
873
+ if (Object.hasOwn(args, "query") && (typeof args.query !== "string" || args.query.length > 500 || !args.query.trim() || /\u0000/.test(args.query))) return invalidInput("query");
874
+ if (Object.hasOwn(args, "limit") && (!Number.isInteger(args.limit) || args.limit < 1 || args.limit > 8)) return invalidInput("limit");
875
+ const terms = args.query === void 0 ? null : words(args.query);
876
+ const entries = indexed.filter((item) => args.provider === void 0 || item.entry.provider === args.provider).map((item) => ({ ...item, score: terms === null ? 0 : terms.reduce((score, term) => score + Number(item.words.has(term)), 0) })).filter((item) => terms === null || item.score > 0).sort((a, b) => b.score - a.score).slice(0, args.limit ?? 5).map(({ entry }) => ({ ...entry, sources: entry.sourceIds.map((id2) => recent_changes_generated_default.pack.sources.find((source) => source.id === id2)) }));
877
+ const structuredContent = JSON.parse(JSON.stringify({
878
+ packVersion: recent_changes_generated_default.pack.packVersion,
879
+ packHash: recent_changes_generated_default.hash,
880
+ reviewedAt: recent_changes_generated_default.pack.reviewedAt,
881
+ dateConvention: recent_changes_generated_default.pack.dateConvention,
882
+ entries,
883
+ availableProviders,
884
+ limits: recent_changes_generated_default.pack.limits,
885
+ correctionsAndConflicts: recent_changes_generated_default.pack.correctionsAndConflicts,
886
+ verification: { repo: "not_checked", live: "not_checked" }
887
+ }));
888
+ return { isError: false, structuredContent, content: [{ type: "text", text: renderRecentChanges(structuredContent) }] };
889
+ }
890
+
576
891
  // ../providers/index.mjs
577
892
  var PROVIDER_TOOL = {
578
893
  name: "provider_playbook",
@@ -1052,15 +1367,718 @@ var npmTools = [
1052
1367
  }
1053
1368
  ];
1054
1369
 
1055
- // src/lib/cli-runner.ts
1370
+ // ../cli/src/hosted/credentials.ts
1056
1371
  var import_node_child_process = require("node:child_process");
1372
+ var import_node_crypto = require("node:crypto");
1373
+ var import_promises = require("node:fs/promises");
1374
+ var import_node_os = require("node:os");
1375
+ var import_node_path = require("node:path");
1376
+ var CREDENTIALS_FILE_NAME = "credentials.json";
1377
+ function defaultConfigDir(env = process.env, platform = process.platform) {
1378
+ const override = env.VIBERAVEN_CONFIG_DIR?.trim();
1379
+ if (override) return (0, import_node_path.resolve)(override);
1380
+ if (platform === "win32") {
1381
+ return (0, import_node_path.join)(env.APPDATA?.trim() || (0, import_node_path.join)((0, import_node_os.homedir)(), "AppData", "Roaming"), "viberaven");
1382
+ }
1383
+ if (platform === "darwin") {
1384
+ return (0, import_node_path.join)((0, import_node_os.homedir)(), "Library", "Application Support", "viberaven");
1385
+ }
1386
+ return (0, import_node_path.join)(env.XDG_CONFIG_HOME?.trim() || (0, import_node_path.join)((0, import_node_os.homedir)(), ".config"), "viberaven");
1387
+ }
1388
+ var CredentialLocationError = class extends Error {
1389
+ };
1390
+ var CredentialPermissionError = class extends Error {
1391
+ constructor(message, toolMissing) {
1392
+ super(message);
1393
+ this.toolMissing = toolMissing;
1394
+ }
1395
+ };
1396
+ var restrictWithIcacls = (path2) => {
1397
+ const name = (0, import_node_os.userInfo)().username;
1398
+ const user = process.env.USERDOMAIN ? `${process.env.USERDOMAIN}\\${name}` : name;
1399
+ return new Promise((resolveRestrict, reject) => {
1400
+ (0, import_node_child_process.execFile)("icacls", [path2, "/inheritance:r", "/grant:r", `${user}:F`], { windowsHide: true, timeout: 1e4 }, (error) => {
1401
+ if (error) reject(error);
1402
+ else resolveRestrict();
1403
+ });
1404
+ });
1405
+ };
1406
+ function isInside(child, parent) {
1407
+ const rel = (0, import_node_path.relative)((0, import_node_path.resolve)(parent), (0, import_node_path.resolve)(child));
1408
+ return rel === "" || !rel.startsWith("..") && !(0, import_node_path.isAbsolute)(rel);
1409
+ }
1410
+ var TRANSIENT_FS_CODES = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EBUSY"]);
1411
+ var FS_ATTEMPTS = 8;
1412
+ var FS_BACKOFF_MS = 10;
1413
+ async function retryTransient(work) {
1414
+ for (let attempt = 1; ; attempt += 1) {
1415
+ try {
1416
+ return await work();
1417
+ } catch (error) {
1418
+ const code = error?.code;
1419
+ if (attempt >= FS_ATTEMPTS || !code || !TRANSIENT_FS_CODES.has(code)) throw error;
1420
+ await new Promise((resolveWait) => setTimeout(resolveWait, FS_BACKOFF_MS * attempt));
1421
+ }
1422
+ }
1423
+ }
1424
+ var CredentialStore = class {
1425
+ constructor(configDir, workspacePath, options = {}) {
1426
+ this.configDir = configDir;
1427
+ this.workspacePath = workspacePath;
1428
+ this.path = (0, import_node_path.join)(configDir, CREDENTIALS_FILE_NAME);
1429
+ this.homeDir = options.homeDir ?? (0, import_node_os.homedir)();
1430
+ this.restrict = options.restrict !== void 0 ? options.restrict : process.platform === "win32" ? restrictWithIcacls : null;
1431
+ 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 };
1432
+ }
1433
+ path;
1434
+ restrict;
1435
+ fs;
1436
+ homeDir;
1437
+ /** Every change to the file runs one at a time, in the order it was asked for. */
1438
+ queue = Promise.resolve();
1439
+ async read() {
1440
+ let raw;
1441
+ try {
1442
+ raw = await retryTransient(() => this.fs.readFile(this.path, "utf8"));
1443
+ } catch {
1444
+ return null;
1445
+ }
1446
+ try {
1447
+ const parsed = JSON.parse(raw);
1448
+ 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")) {
1449
+ return parsed;
1450
+ }
1451
+ } catch {
1452
+ }
1453
+ return null;
1454
+ }
1455
+ /** The stored session, only if it was issued by `apiBaseUrl`. */
1456
+ async readFor(apiBaseUrl) {
1457
+ const stored = await this.read();
1458
+ return stored && stored.apiBaseUrl === apiBaseUrl ? stored : null;
1459
+ }
1460
+ /** Resolves once every change queued so far has landed (or failed). */
1461
+ idle() {
1462
+ return this.queue;
1463
+ }
1464
+ /** Standalone account commands have no workspace, but their credentials still must stay outside Git. */
1465
+ async assertLocation() {
1466
+ if (this.workspacePath && isInside(this.configDir, this.workspacePath)) {
1467
+ throw new CredentialLocationError("VibeRaven account storage must be outside the project.");
1468
+ }
1469
+ const missing = [];
1470
+ let existing = (0, import_node_path.resolve)(this.configDir);
1471
+ while (true) {
1472
+ try {
1473
+ await (0, import_promises.lstat)(existing);
1474
+ break;
1475
+ } catch (error) {
1476
+ if (error.code !== "ENOENT" || (0, import_node_path.dirname)(existing) === existing) throw error;
1477
+ missing.unshift((0, import_node_path.basename)(existing));
1478
+ existing = (0, import_node_path.dirname)(existing);
1479
+ }
1480
+ }
1481
+ const canonical = (0, import_node_path.resolve)(await (0, import_promises.realpath)(existing), ...missing);
1482
+ const workspace = this.workspacePath ? await (0, import_promises.realpath)(this.workspacePath).catch((error) => {
1483
+ if (error.code === "ENOENT") return (0, import_node_path.resolve)(this.workspacePath);
1484
+ throw error;
1485
+ }) : void 0;
1486
+ if (workspace && isInside(canonical, workspace)) {
1487
+ throw new CredentialLocationError("VibeRaven account storage must be outside the project.");
1488
+ }
1489
+ const home = (0, import_node_path.resolve)(this.homeDir);
1490
+ const boundaries = /* @__PURE__ */ new Set([home, (0, import_node_path.join)(home, ".config")]);
1491
+ for (const boundary of [...boundaries]) boundaries.add(await (0, import_promises.realpath)(boundary).catch(() => boundary));
1492
+ for (const path2 of /* @__PURE__ */ new Set([(0, import_node_path.resolve)(this.configDir), canonical])) {
1493
+ for (let cursor = path2; ; cursor = (0, import_node_path.dirname)(cursor)) {
1494
+ if ([...boundaries].some((boundary) => (0, import_node_path.relative)(boundary, cursor) === "")) break;
1495
+ try {
1496
+ await (0, import_promises.lstat)((0, import_node_path.join)(cursor, ".git"));
1497
+ throw new CredentialLocationError("VibeRaven account storage must be outside Git checkouts.");
1498
+ } catch (error) {
1499
+ if (error.code !== "ENOENT") throw error;
1500
+ }
1501
+ if ((0, import_node_path.dirname)(cursor) === cursor) break;
1502
+ }
1503
+ }
1504
+ const target = await (0, import_promises.lstat)(this.path).catch((error) => {
1505
+ if (error.code === "ENOENT") return void 0;
1506
+ throw error;
1507
+ });
1508
+ if (target && (!target.isFile() || target.isSymbolicLink())) throw new CredentialLocationError("VibeRaven account storage must be a regular private file.");
1509
+ }
1510
+ serial(work) {
1511
+ const run = this.queue.then(work, work);
1512
+ this.queue = run.then(() => void 0, () => void 0);
1513
+ return run;
1514
+ }
1515
+ write(credentials) {
1516
+ return this.serial(async () => {
1517
+ await this.writeNow({ version: 1, ...credentials, savedAt: (/* @__PURE__ */ new Date()).toISOString() });
1518
+ });
1519
+ }
1520
+ /** Must run inside `serial`. Returns false when `guard` stopped the swap and the file was left alone. */
1521
+ async writeNow(body, guard) {
1522
+ if (this.workspacePath && isInside(this.configDir, this.workspacePath)) {
1523
+ throw new CredentialLocationError(
1524
+ `Refusing to store the VibeRaven sign-in inside this project (${this.configDir}). Set VIBERAVEN_CONFIG_DIR to a folder outside the repo.`
1525
+ );
1526
+ }
1527
+ await this.assertLocation();
1528
+ await (0, import_promises.mkdir)(this.configDir, { recursive: true, mode: 448 });
1529
+ const temp = `${this.path}.${(0, import_node_crypto.randomUUID)()}.tmp`;
1530
+ await (0, import_promises.writeFile)(temp, `${JSON.stringify(body, null, 2)}
1531
+ `, { encoding: "utf8", mode: 384 });
1532
+ await (0, import_promises.chmod)(temp, 384).catch(() => void 0);
1533
+ try {
1534
+ if (this.restrict) await this.restrict(temp);
1535
+ } catch (error) {
1536
+ await (0, import_promises.rm)(temp, { force: true });
1537
+ const code = error?.code;
1538
+ const toolMissing = code === "ENOENT";
1539
+ throw new CredentialPermissionError(
1540
+ 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)})`,
1541
+ toolMissing
1542
+ );
1543
+ }
1544
+ if (guard) {
1545
+ const onDisk = await this.readFor(guard.apiBaseUrl);
1546
+ if (onDisk?.accessToken !== guard.accessToken || guard.isCurrent && !guard.isCurrent()) {
1547
+ await (0, import_promises.rm)(temp, { force: true });
1548
+ return false;
1549
+ }
1550
+ }
1551
+ try {
1552
+ await retryTransient(() => this.fs.rename(temp, this.path));
1553
+ } catch (error) {
1554
+ await (0, import_promises.rm)(temp, { force: true });
1555
+ throw error;
1556
+ }
1557
+ await (0, import_promises.chmod)(this.path, 384).catch(() => void 0);
1558
+ return true;
1559
+ }
1560
+ /** Keeps the stored plan label in step with what the API last said. */
1561
+ updatePlan(apiBaseUrl, plan) {
1562
+ return this.serial(async () => {
1563
+ const stored = await this.readFor(apiBaseUrl);
1564
+ if (!stored || stored.account.plan === plan) return;
1565
+ await this.writeNow(
1566
+ { version: 1, apiBaseUrl: stored.apiBaseUrl, accessToken: stored.accessToken, account: { ...stored.account, plan }, savedAt: (/* @__PURE__ */ new Date()).toISOString() },
1567
+ { apiBaseUrl: stored.apiBaseUrl, accessToken: stored.accessToken }
1568
+ );
1569
+ });
1570
+ }
1571
+ /**
1572
+ * Replaces the saved account label with what the API holds now. Only touches the file while it
1573
+ * still holds the sign-in `accessToken` belongs to and `isCurrent()` still says yes, so a
1574
+ * sign-out or a new sign-in made while the API was answering is never overwritten. `savedAt`
1575
+ * is the sign-in time and is kept.
1576
+ */
1577
+ updateAccount(apiBaseUrl, accessToken, account, isCurrent) {
1578
+ return this.serial(async () => {
1579
+ const stored = await this.readFor(apiBaseUrl);
1580
+ if (!stored || stored.accessToken !== accessToken) return;
1581
+ if (stored.account.email === account.email && stored.account.plan === account.plan) return;
1582
+ if (isCurrent && !isCurrent()) return;
1583
+ await this.writeNow(
1584
+ { version: 1, apiBaseUrl: stored.apiBaseUrl, accessToken, account: { ...stored.account, ...account }, savedAt: stored.savedAt },
1585
+ { apiBaseUrl: stored.apiBaseUrl, accessToken, isCurrent }
1586
+ );
1587
+ });
1588
+ }
1589
+ clear() {
1590
+ return this.serial(() => retryTransient(() => this.fs.rm(this.path)));
1591
+ }
1592
+ };
1593
+
1594
+ // ../../src/station/fetchUtils.ts
1595
+ function isNetworkFetchFailure(error) {
1596
+ if (error == null) {
1597
+ return false;
1598
+ }
1599
+ if (error instanceof TypeError) {
1600
+ const m = error.message;
1601
+ if (m === "fetch failed" || m.toLowerCase().includes("fetch failed") || m.includes("Failed to fetch")) {
1602
+ return true;
1603
+ }
1604
+ }
1605
+ if (error instanceof AggregateError) {
1606
+ return error.errors.some((e2) => isNetworkFetchFailure(e2));
1607
+ }
1608
+ if (error instanceof Error && "cause" in error && error.cause != null) {
1609
+ return isNetworkFetchFailure(error.cause);
1610
+ }
1611
+ const e = error;
1612
+ if (typeof e.code === "string") {
1613
+ if (["ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EAI_AGAIN", "ETIMEDOUT", "ENETUNREACH", "EHOSTUNREACH"].includes(
1614
+ e.code
1615
+ )) {
1616
+ return true;
1617
+ }
1618
+ }
1619
+ return false;
1620
+ }
1621
+
1622
+ // ../../shared/deviceAuthorization.ts
1623
+ var DEVICE_AUTH_PROTOCOL_VERSION = 2;
1624
+ function normalizeUserCode(value) {
1625
+ if (typeof value !== "string") return null;
1626
+ const code = value.trim().toUpperCase();
1627
+ if (!/^[A-HJ-NP-Z2-9]{4}-?[A-HJ-NP-Z2-9]{4}$/.test(code)) return null;
1628
+ const compact = code.replace("-", "");
1629
+ return `${compact.slice(0, 4)}-${compact.slice(4)}`;
1630
+ }
1631
+ function isOpaqueDeviceCode(value) {
1632
+ return typeof value === "string" && /^vrdc_[A-Za-z0-9_-]{43}$/.test(value);
1633
+ }
1634
+
1635
+ // ../cli/src/hosted/deviceAuthorization.ts
1636
+ var DEVICE_START_REQUEST = { protocolVersion: DEVICE_AUTH_PROTOCOL_VERSION };
1637
+ var DEFAULT_SITE = "https://viberaven.dev";
1638
+ var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
1639
+ function deviceSiteOrigin(value = process.env.VIBERAVEN_SITE_URL || DEFAULT_SITE) {
1640
+ try {
1641
+ const url = new URL(value);
1642
+ if (url.username || url.password || url.search || url.hash || url.pathname !== "/" || !(url.protocol === "https:" || url.protocol === "http:" && LOOPBACK.has(url.hostname))) throw new Error();
1643
+ return url.origin;
1644
+ } catch {
1645
+ throw new Error("VIBERAVEN_SITE_URL must name the trusted HTTPS site origin (HTTP is allowed only for loopback tests).");
1646
+ }
1647
+ }
1648
+ function validateDeviceAuthorization(value, expectedOrigin = deviceSiteOrigin()) {
1649
+ const fail = () => {
1650
+ 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.");
1651
+ };
1652
+ if (!value || typeof value !== "object") return fail();
1653
+ const input = value;
1654
+ const userCode = normalizeUserCode(input.userCode);
1655
+ 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();
1656
+ let url;
1657
+ try {
1658
+ url = new URL(input.verificationUrl);
1659
+ } catch {
1660
+ return fail();
1661
+ }
1662
+ 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();
1663
+ return {
1664
+ protocolVersion: DEVICE_AUTH_PROTOCOL_VERSION,
1665
+ userCode,
1666
+ deviceCode: input.deviceCode,
1667
+ verificationUrl: url.toString(),
1668
+ expiresAt: input.expiresAt,
1669
+ pollIntervalSeconds: input.pollIntervalSeconds
1670
+ };
1671
+ }
1672
+
1673
+ // ../cli/src/hosted/hostedClient.ts
1674
+ var DEFAULT_API_BASE_URL = "https://jaohiwzjhtwljyqligpu.supabase.co/functions/v1/viberice-api";
1675
+ function normalizeBaseUrl(baseUrl) {
1676
+ return baseUrl.trim().replace(/\/+$/, "");
1677
+ }
1678
+ function resolveApiBaseUrl(env = process.env) {
1679
+ const raw = env.VIBERAVEN_API_URL?.trim();
1680
+ return normalizeBaseUrl(raw || DEFAULT_API_BASE_URL);
1681
+ }
1682
+ var HostedCallError = class extends Error {
1683
+ constructor(kind, message, details = {}) {
1684
+ super(message);
1685
+ this.kind = kind;
1686
+ this.details = details;
1687
+ }
1688
+ };
1689
+ async function postJson(url, payload, options) {
1690
+ return requestJson(url, { ...options, method: "POST", body: JSON.stringify(payload === void 0 ? {} : payload) });
1691
+ }
1692
+ async function getJson(url, options) {
1693
+ return requestJson(url, { ...options, method: "GET" });
1694
+ }
1695
+ async function requestJson(url, options) {
1696
+ let response2;
1697
+ try {
1698
+ response2 = await (options.fetcher ?? fetch)(url, {
1699
+ method: options.method,
1700
+ headers: {
1701
+ ...options.body !== void 0 ? { "Content-Type": "application/json" } : {},
1702
+ ...options.headers ?? {},
1703
+ ...options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {}
1704
+ },
1705
+ body: options.body,
1706
+ // Never follow a redirect with the sign-in token and the project attached.
1707
+ redirect: "error",
1708
+ signal: AbortSignal.timeout(options.timeoutMs)
1709
+ });
1710
+ } catch (error) {
1711
+ const name = error?.name;
1712
+ if (name === "TimeoutError" || name === "AbortError") {
1713
+ throw new HostedCallError("timeout", `${options.label} did not answer within ${Math.round(options.timeoutMs / 1e3)}s.`);
1714
+ }
1715
+ if (/redirect/i.test(`${error?.message ?? ""} ${error?.cause?.message ?? ""}`)) {
1716
+ 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.`);
1717
+ }
1718
+ if (isNetworkFetchFailure(error) || error instanceof TypeError) {
1719
+ throw new HostedCallError("network", `Could not reach VibeRaven at ${new URL(url).origin}. Check your connection and try again.`);
1720
+ }
1721
+ throw error;
1722
+ }
1723
+ if (!response2.ok) {
1724
+ let text = "";
1725
+ try {
1726
+ text = (await response2.text()).trim();
1727
+ } catch {
1728
+ text = "";
1729
+ }
1730
+ let upgradeUrl;
1731
+ try {
1732
+ const parsed = JSON.parse(text);
1733
+ if (typeof parsed.upgrade_url === "string" && parsed.upgrade_url) upgradeUrl = parsed.upgrade_url;
1734
+ } catch {
1735
+ }
1736
+ const retryAfter = Number(response2.headers.get("retry-after"));
1737
+ const authCall = options.label.startsWith("Sign-in");
1738
+ 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)}` : ""}`, {
1739
+ status: response2.status,
1740
+ ...authCall ? {} : { body: text.slice(0, 2e3) },
1741
+ ...authCall ? {} : { upgradeUrl },
1742
+ retryAfterSeconds: Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : void 0
1743
+ });
1744
+ }
1745
+ try {
1746
+ return await response2.json();
1747
+ } catch {
1748
+ throw new HostedCallError("invalid_response", `${options.label} returned a body that is not JSON.`);
1749
+ }
1750
+ }
1751
+ async function startSignIn(baseUrl, timeoutMs, fetcher) {
1752
+ const payload = await postJson(`${normalizeBaseUrl(baseUrl)}/v1/auth/device/start`, DEVICE_START_REQUEST, { timeoutMs, label: "Sign-in start", fetcher });
1753
+ try {
1754
+ return validateDeviceAuthorization(payload);
1755
+ } catch {
1756
+ throw new HostedCallError("invalid_response", "Device sign-in requires the updated API and CLI protocol. Upgrade VibeRaven and deploy the matching device-flow API.");
1757
+ }
1758
+ }
1759
+ async function pollSignIn(baseUrl, deviceCode, timeoutMs, fetcher) {
1760
+ let payload;
1761
+ try {
1762
+ payload = await postJson(`${normalizeBaseUrl(baseUrl)}/v1/auth/device/poll`, { deviceCode }, { timeoutMs, label: "Sign-in poll", fetcher });
1763
+ } catch (error) {
1764
+ if (error instanceof HostedCallError && error.details.status === 410) return { status: "expired" };
1765
+ throw error;
1766
+ }
1767
+ if (!isSignInPoll(payload)) {
1768
+ throw new HostedCallError("invalid_response", "Sign-in poll response was invalid.");
1769
+ }
1770
+ return payload;
1771
+ }
1772
+ async function fetchAccount(baseUrl, accessToken, timeoutMs, fetcher) {
1773
+ const payload = await getJson(`${normalizeBaseUrl(baseUrl)}/v1/account/me`, { accessToken, timeoutMs, label: "Account check", fetcher });
1774
+ if (!isAccount(payload)) {
1775
+ throw new HostedCallError("invalid_response", "Account response did not match the expected shape.");
1776
+ }
1777
+ return { email: payload.email, plan: payload.plan, usage: payload.usage };
1778
+ }
1779
+ function isRecord(value) {
1780
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1781
+ }
1782
+ function isNonEmptyString(value) {
1783
+ return typeof value === "string" && value.trim().length > 0;
1784
+ }
1785
+ function isSignInPoll(value) {
1786
+ if (!isRecord(value) || !isNonEmptyString(value.status)) return false;
1787
+ if (value.status === "pending" || value.status === "expired" || value.status === "denied") return true;
1788
+ 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));
1789
+ }
1790
+ function isUsage(value) {
1791
+ if (!isRecord(value) || value.plan !== "free" && value.plan !== "pro") return false;
1792
+ if (value.remainingPrompts !== null && typeof value.remainingPrompts !== "number") return false;
1793
+ if (typeof value.used !== "number" || typeof value.limit !== "number") return false;
1794
+ if (value.period !== "lifetime" && value.period !== "monthly") return false;
1795
+ return Array.isArray(value.unlockedMapCategoryKeys) && value.unlockedMapCategoryKeys.every((k) => typeof k === "string");
1796
+ }
1797
+ function isAccount(value) {
1798
+ return isRecord(value) && isNonEmptyString(value.email) && (value.plan === "free" || value.plan === "pro") && isUsage(value.usage);
1799
+ }
1800
+
1801
+ // ../cli/src/openBrowser.ts
1802
+ var import_node_child_process2 = require("node:child_process");
1803
+ function createOpenCommand(target, platform = process.platform) {
1804
+ if (platform === "win32") {
1805
+ return {
1806
+ command: "rundll32",
1807
+ args: ["url.dll,FileProtocolHandler", target],
1808
+ shell: false
1809
+ };
1810
+ }
1811
+ if (platform === "darwin") {
1812
+ return { command: "open", args: [target], shell: false };
1813
+ }
1814
+ return { command: "xdg-open", args: [target], shell: false };
1815
+ }
1816
+ async function openWithSystemDefault(target) {
1817
+ const { command, args, shell } = createOpenCommand(target);
1818
+ await new Promise((resolve3, reject) => {
1819
+ const child = (0, import_node_child_process2.spawn)(command, args, { stdio: "ignore", shell });
1820
+ child.on("error", reject);
1821
+ child.on("exit", (code) => {
1822
+ if (code === 0) {
1823
+ resolve3();
1824
+ } else {
1825
+ reject(new Error(`Could not open browser (exit ${code ?? "unknown"}). Open manually: ${target}`));
1826
+ }
1827
+ });
1828
+ });
1829
+ }
1830
+ async function openUrlInBrowser(url) {
1831
+ const trimmed = url.trim();
1832
+ if (!/^https?:\/\//i.test(trimmed)) {
1833
+ throw new Error(`Not a valid http(s) URL: ${url}`);
1834
+ }
1835
+ await openWithSystemDefault(trimmed);
1836
+ }
1837
+
1838
+ // ../cli/src/providers/liveAdapters.ts
1839
+ async function boundedJson2(response2) {
1840
+ if (!response2.body) throw new Error("Empty response");
1841
+ const reader = response2.body.getReader();
1842
+ const chunks = [];
1843
+ let size = 0;
1844
+ try {
1845
+ while (true) {
1846
+ const next = await reader.read();
1847
+ if (next.done) break;
1848
+ size += next.value.byteLength;
1849
+ if (size > 256e3) throw new Error("Response too large");
1850
+ chunks.push(next.value);
1851
+ }
1852
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
1853
+ } finally {
1854
+ await reader.cancel().catch(() => {
1855
+ });
1856
+ reader.releaseLock();
1857
+ }
1858
+ }
1859
+
1860
+ // ../cli/src/version.ts
1861
+ var VERSION = "1.7.3";
1862
+
1863
+ // ../cli/src/commands/account.ts
1864
+ var loginNext = `npx -y viberaven@${VERSION} login --json`;
1865
+ function apiUrl(value) {
1866
+ const url = new URL(value);
1867
+ 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.");
1868
+ }
1869
+ function actionUrl(value) {
1870
+ if (typeof value !== "string" || value.length > 2048 || /[\x00-\x20\x7f]/.test(value)) return false;
1871
+ try {
1872
+ apiUrl(value.split("?")[0]);
1873
+ const url = new URL(value);
1874
+ return url.origin === deviceSiteOrigin() && !url.username && !url.password && !url.hash;
1875
+ } catch {
1876
+ return false;
1877
+ }
1878
+ }
1879
+ function statusCode(error) {
1880
+ return error instanceof HostedCallError ? error.details.status : void 0;
1881
+ }
1882
+ function defaults() {
1883
+ return {
1884
+ api: resolveApiBaseUrl(),
1885
+ configDir: defaultConfigDir(),
1886
+ fetch,
1887
+ now: Date.now,
1888
+ sleep: (ms) => new Promise((resolve3) => setTimeout(resolve3, ms)),
1889
+ openUrl: openUrlInBrowser,
1890
+ progress: (value) => console.error(JSON.stringify(value))
1891
+ };
1892
+ }
1893
+ async function loginAccount(options, deps) {
1894
+ try {
1895
+ apiUrl(deps.api);
1896
+ const credentials = new CredentialStore(deps.configDir, void 0);
1897
+ await credentials.assertLocation();
1898
+ const existing = await credentials.readFor(deps.api);
1899
+ if (existing) {
1900
+ try {
1901
+ const account = await fetchAccount(deps.api, existing.accessToken, 2e4, deps.fetch);
1902
+ await credentials.updateAccount(deps.api, existing.accessToken, { email: account.email, plan: account.plan });
1903
+ return { state: "authenticated", message: "Signed in. Use viberaven account to read the current live allowance." };
1904
+ } catch (error) {
1905
+ if (statusCode(error) !== 401) throw error;
1906
+ }
1907
+ }
1908
+ const started = await startSignIn(deps.api, 2e4, deps.fetch);
1909
+ const expires = Date.parse(started.expiresAt);
1910
+ 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.");
1911
+ deps.progress({ state: "requires_approval", actionUrl: started.verificationUrl, expiresAt: new Date(expires).toISOString() });
1912
+ if (!options.json && !options.noBrowser) await deps.openUrl(started.verificationUrl).catch(() => {
1913
+ });
1914
+ const deadline = Math.min(expires, deps.now() + 6e5);
1915
+ while (deps.now() < deadline) {
1916
+ await deps.sleep(Math.min(started.pollIntervalSeconds * 1e3, deadline - deps.now()));
1917
+ if (deps.now() >= deadline) break;
1918
+ let polled;
1919
+ try {
1920
+ polled = await pollSignIn(deps.api, started.deviceCode, Math.max(1, Math.min(2e4, deadline - deps.now())), deps.fetch);
1921
+ } catch (error) {
1922
+ const status = statusCode(error);
1923
+ if (error instanceof HostedCallError && (["network", "timeout"].includes(error.kind) || status === 429 || status !== void 0 && status >= 500 && status <= 599)) {
1924
+ const retryMs = (error.details.retryAfterSeconds ?? 0) * 1e3;
1925
+ if (retryMs > 0 && deps.now() < deadline) await deps.sleep(Math.min(retryMs, deadline - deps.now()));
1926
+ continue;
1927
+ }
1928
+ throw error;
1929
+ }
1930
+ if (polled.status === "pending") continue;
1931
+ 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." };
1932
+ if (polled.status === "approved") {
1933
+ await credentials.write({ apiBaseUrl: deps.api, accessToken: polled.accessToken, account: polled.account });
1934
+ return { state: "authenticated", message: "Signed in. Use viberaven account to read the current live allowance." };
1935
+ }
1936
+ }
1937
+ return { state: "expired", message: "Browser approval expired. Run login again; no provider read or payment was made." };
1938
+ } catch (error) {
1939
+ 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." };
1940
+ if (error instanceof CredentialLocationError) return {
1941
+ state: "unavailable",
1942
+ reason: "credential_location",
1943
+ message: "Set VIBERAVEN_CONFIG_DIR to a private user folder outside Git checkouts, then retry login. No credentials were printed."
1944
+ };
1945
+ 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." };
1946
+ }
1947
+ }
1948
+ function allowance(raw, plan, now) {
1949
+ if (!raw || typeof raw !== "object") throw new Error("Invalid allowance.");
1950
+ const r = raw;
1951
+ const integer = (value, max = Number.MAX_SAFE_INTEGER) => Number.isSafeInteger(value) && Number(value) >= 0 && Number(value) <= max;
1952
+ const date = new Date(now);
1953
+ const periodStart = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1);
1954
+ const periodEnd = Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1);
1955
+ 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.");
1956
+ return {
1957
+ policyVersion: r.policyVersion,
1958
+ plan,
1959
+ monthlyLimit: r.monthlyLimit,
1960
+ consumed: r.consumed,
1961
+ reserved: r.reserved,
1962
+ remaining: r.remaining,
1963
+ concurrencyLimit: r.concurrencyLimit,
1964
+ periodStart: new Date(r.periodStart).toISOString(),
1965
+ periodEnd: new Date(r.periodEnd).toISOString()
1966
+ };
1967
+ }
1968
+ async function readAccount(deps) {
1969
+ try {
1970
+ apiUrl(deps.api);
1971
+ const credentials = new CredentialStore(deps.configDir, void 0);
1972
+ await credentials.assertLocation();
1973
+ const auth = await credentials.readFor(deps.api);
1974
+ 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." };
1975
+ const response2 = await deps.fetch(`${deps.api}/v1/account/live-allowance`, {
1976
+ method: "GET",
1977
+ headers: { Authorization: `Bearer ${auth.accessToken}` },
1978
+ redirect: "error",
1979
+ signal: AbortSignal.timeout(2e4)
1980
+ });
1981
+ if (!response2.ok) {
1982
+ await response2.body?.cancel();
1983
+ 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." };
1984
+ if (response2.status === 401) return { state: "requires_connection", next: loginNext, message: "Account sign-in expired. Approve login again; local checks still need no account." };
1985
+ throw new Error("Account unavailable.");
1986
+ }
1987
+ const raw = await boundedJson2(response2);
1988
+ 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.");
1989
+ return {
1990
+ state: "account",
1991
+ plan: raw.plan,
1992
+ liveSteps: {
1993
+ state: raw.liveSteps.state,
1994
+ allowance: raw.liveSteps.state === "available" ? allowance(raw.liveSteps.allowance, raw.plan, deps.now()) : null
1995
+ },
1996
+ upgradeUrl: raw.upgradeUrl,
1997
+ ...raw.plan === "pro" ? { billingUrl: new URL("/account", deviceSiteOrigin()).toString() } : {}
1998
+ };
1999
+ } catch (error) {
2000
+ if (error instanceof CredentialLocationError) return {
2001
+ state: "unavailable",
2002
+ reason: "credential_location",
2003
+ message: "Set VIBERAVEN_CONFIG_DIR to a private user folder outside Git checkouts, then retry account. No credentials were printed."
2004
+ };
2005
+ 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." };
2006
+ }
2007
+ }
2008
+
2009
+ // src/tools/account.ts
2010
+ var accountTools = [
2011
+ {
2012
+ name: "viberaven_account",
2013
+ 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.",
2014
+ inputSchema: { type: "object", properties: {}, additionalProperties: false }
2015
+ },
2016
+ {
2017
+ name: "viberaven_login",
2018
+ 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.",
2019
+ 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 }
2020
+ }
2021
+ ];
2022
+ var isAccountTool = (name) => name === "viberaven_account" || name === "viberaven_login";
2023
+ function response(view) {
2024
+ const state = view.state;
2025
+ return {
2026
+ content: [{ type: "text", text: JSON.stringify(view, null, 2) }],
2027
+ structuredContent: view,
2028
+ ...["unavailable", "expired", "denied", "invalid_arguments"].includes(state ?? "") ? { isError: true } : {}
2029
+ };
2030
+ }
2031
+ function createAccountToolHandler(depsFactory = defaults) {
2032
+ let pending;
2033
+ return async (name, raw) => {
2034
+ 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." });
2035
+ const args = raw;
2036
+ 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." });
2037
+ if (name === "viberaven_account") {
2038
+ if (pending?.finished && pending.view?.state === "authenticated") pending = void 0;
2039
+ const account = await readAccount(depsFactory());
2040
+ if (account.state === "requires_connection" && pending) {
2041
+ if (!pending.finished) return response(pending.view ?? await pending.initial);
2042
+ return response({ ...account, signIn: pending.view });
2043
+ }
2044
+ return response(account);
2045
+ }
2046
+ 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." });
2047
+ if (pending && !pending.finished) return response(pending.view ?? await pending.initial);
2048
+ let resolveInitial;
2049
+ const initial = new Promise((resolve3) => {
2050
+ resolveInitial = resolve3;
2051
+ });
2052
+ const flow = { initial, view: void 0, finished: false };
2053
+ pending = flow;
2054
+ const deps = { ...depsFactory(), progress: (view) => {
2055
+ flow.view = view;
2056
+ resolveInitial(view);
2057
+ } };
2058
+ void loginAccount({ json: true, noBrowser: true }, deps).then((view) => {
2059
+ flow.view = view;
2060
+ flow.finished = true;
2061
+ resolveInitial(view);
2062
+ }, () => {
2063
+ const view = { state: "unavailable", message: "Sign-in could not complete. Retry the account API; no credentials were printed." };
2064
+ flow.view = view;
2065
+ flow.finished = true;
2066
+ resolveInitial(view);
2067
+ });
2068
+ return response(await initial);
2069
+ };
2070
+ }
2071
+ var handleAccountTool = createAccountToolHandler();
2072
+
2073
+ // src/lib/cli-runner.ts
2074
+ var import_node_child_process3 = require("node:child_process");
1057
2075
  var import_node_fs3 = require("node:fs");
1058
- var import_node_path2 = require("node:path");
2076
+ var import_node_path3 = require("node:path");
1059
2077
 
1060
2078
  // src/lib/work-report-runner.ts
1061
2079
  var import_node_fs2 = require("node:fs");
1062
2080
  var import_node_module = require("node:module");
1063
- var import_node_path = require("node:path");
2081
+ var import_node_path2 = require("node:path");
1064
2082
 
1065
2083
  // ../../shared/workReportRunner.ts
1066
2084
  var import_node_fs = require("node:fs");
@@ -1079,7 +2097,7 @@ function runWorkReportProcess(entry, args, cwd3, spawnFn2) {
1079
2097
  } catch {
1080
2098
  return Promise.resolve(workReportFailure());
1081
2099
  }
1082
- return new Promise((resolve2) => {
2100
+ return new Promise((resolve3) => {
1083
2101
  let settled = false, stdoutBytes = 0, stderrBytes = 0;
1084
2102
  const chunks = [];
1085
2103
  let child;
@@ -1087,7 +2105,7 @@ function runWorkReportProcess(entry, args, cwd3, spawnFn2) {
1087
2105
  if (!settled) {
1088
2106
  settled = true;
1089
2107
  clearTimeout(timer);
1090
- resolve2(result);
2108
+ resolve3(result);
1091
2109
  }
1092
2110
  };
1093
2111
  const fail = () => {
@@ -1133,20 +2151,20 @@ ${stdout.trim()}` });
1133
2151
 
1134
2152
  // src/lib/work-report-runner.ts
1135
2153
  var within = (root, target) => {
1136
- const rel = (0, import_node_path.relative)(root, target);
1137
- return !rel || !(0, import_node_path.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(`..${import_node_path.sep}`);
2154
+ const rel = (0, import_node_path2.relative)(root, target);
2155
+ return !rel || !(0, import_node_path2.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(`..${import_node_path2.sep}`);
1138
2156
  };
1139
2157
  function resolveInstalledCli(version, cwd3) {
1140
2158
  const override = process.env.VIBERAVEN_CLI_PATH;
1141
2159
  try {
1142
- if (override !== void 0 && !(0, import_node_path.isAbsolute)(override)) throw new Error("Unavailable installed CLI");
1143
- 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");
2160
+ if (override !== void 0 && !(0, import_node_path2.isAbsolute)(override)) throw new Error("Unavailable installed CLI");
2161
+ 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");
1144
2162
  const info = (0, import_node_fs2.lstatSync)(selected);
1145
2163
  if (!info.isFile() || info.isSymbolicLink()) throw new Error("Unavailable installed CLI");
1146
2164
  const entry = (0, import_node_fs2.realpathSync)(selected);
1147
- const root = (0, import_node_fs2.realpathSync)((0, import_node_path.join)((0, import_node_path.dirname)(entry), ".."));
1148
- 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");
1149
- const manifestPath = (0, import_node_path.join)(root, "package.json"), manifestInfo = (0, import_node_fs2.lstatSync)(manifestPath);
2165
+ const root = (0, import_node_fs2.realpathSync)((0, import_node_path2.join)((0, import_node_path2.dirname)(entry), ".."));
2166
+ 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");
2167
+ const manifestPath = (0, import_node_path2.join)(root, "package.json"), manifestInfo = (0, import_node_fs2.lstatSync)(manifestPath);
1150
2168
  if (!manifestInfo.isFile() || manifestInfo.isSymbolicLink() || manifestInfo.size > 65536 || (0, import_node_fs2.realpathSync)(manifestPath) !== manifestPath) throw new Error("Unavailable installed CLI");
1151
2169
  const manifest = JSON.parse((0, import_node_fs2.readFileSync)(manifestPath, "utf8"));
1152
2170
  if (manifest.name !== "@viberaven/cli" || manifest.version !== version) throw new Error("Unavailable installed CLI");
@@ -1178,14 +2196,14 @@ var cachedVersion;
1178
2196
  function mcpVersion() {
1179
2197
  if (cachedVersion) return cachedVersion;
1180
2198
  let found;
1181
- for (let dir = __dirname, depth = 0; depth < 4 && !found; depth += 1, dir = (0, import_node_path2.dirname)(dir)) {
2199
+ for (let dir = __dirname, depth = 0; depth < 4 && !found; depth += 1, dir = (0, import_node_path3.dirname)(dir)) {
1182
2200
  try {
1183
- const manifest = JSON.parse((0, import_node_fs3.readFileSync)((0, import_node_path2.join)(dir, "package.json"), "utf8"));
2201
+ const manifest = JSON.parse((0, import_node_fs3.readFileSync)((0, import_node_path3.join)(dir, "package.json"), "utf8"));
1184
2202
  if (manifest.name === MCP_PACKAGE && typeof manifest.version === "string") found = manifest.version;
1185
2203
  } catch {
1186
2204
  }
1187
2205
  }
1188
- found ??= true ? "1.7.1" : void 0;
2206
+ found ??= true ? "1.7.3" : void 0;
1189
2207
  if (!found || !PLAIN_VERSION.test(found)) {
1190
2208
  throw new Error(`Could not read a valid ${MCP_PACKAGE} version (got ${JSON.stringify(found)}), so the matching ${CLI_PACKAGE} cannot be pinned.`);
1191
2209
  }
@@ -1210,7 +2228,7 @@ function cliChildEnv(env = process.env) {
1210
2228
  }
1211
2229
  return out;
1212
2230
  }
1213
- var spawnFn = import_node_child_process.spawn;
2231
+ var spawnFn = import_node_child_process3.spawn;
1214
2232
  function safeStringArg(value, label) {
1215
2233
  if (typeof value !== "string") throw new Error(`Invalid ${label}: expected string`);
1216
2234
  if (!value.trim()) throw new Error(`Invalid ${label}: expected non-empty string`);
@@ -1308,7 +2326,7 @@ function runVibeRavenDetailed(args, cwd3) {
1308
2326
  } catch (error) {
1309
2327
  return Promise.resolve(transportFailure(error));
1310
2328
  }
1311
- return new Promise((resolve2) => {
2329
+ return new Promise((resolve3) => {
1312
2330
  let child;
1313
2331
  try {
1314
2332
  child = spawnFn(built.command, built.args, {
@@ -1319,7 +2337,7 @@ function runVibeRavenDetailed(args, cwd3) {
1319
2337
  stdio: ["ignore", "pipe", "pipe"]
1320
2338
  });
1321
2339
  } catch (error) {
1322
- resolve2(transportFailure(error));
2340
+ resolve3(transportFailure(error));
1323
2341
  return;
1324
2342
  }
1325
2343
  let stdout = "";
@@ -1333,7 +2351,7 @@ function runVibeRavenDetailed(args, cwd3) {
1333
2351
  if (settled) return;
1334
2352
  settled = true;
1335
2353
  if (timer) clearTimeout(timer);
1336
- resolve2(result);
2354
+ resolve3(result);
1337
2355
  };
1338
2356
  const stopRls = (reason) => {
1339
2357
  finish(transportFailure(new Error(reason)));
@@ -1400,7 +2418,9 @@ var ALL_TOOLS = [
1400
2418
  ...npmTools,
1401
2419
  ...WORK_TOOLS,
1402
2420
  PROVIDER_TOOL,
1403
- ...LIVE_TOOLS
2421
+ RECENT_PROVIDER_CHANGES_TOOL,
2422
+ ...LIVE_TOOLS,
2423
+ ...accountTools
1404
2424
  ];
1405
2425
  function parseJsonObjectFromToolText(text) {
1406
2426
  const start = text.indexOf("{");
@@ -1426,7 +2446,9 @@ function isCompletedNegativeNpmVerdict(receipt) {
1426
2446
  async function handleRequest(method, params) {
1427
2447
  if (method === "tools/list") return { tools: ALL_TOOLS };
1428
2448
  if (method === "tools/call") {
2449
+ if (isAccountTool(params.name)) return handleAccountTool(params.name, params.arguments ?? {});
1429
2450
  if (params.name === "provider_playbook") return providerPlaybook(params.arguments);
2451
+ if (params.name === "recent_provider_changes") return recentProviderChanges(params.arguments ?? {});
1430
2452
  const args = params.arguments || {};
1431
2453
  const cliArgs = buildToolArgs(params.name, args);
1432
2454
  const run = await runVibeRavenDetailed(cliArgs, args.cwd);
@@ -1449,7 +2471,7 @@ async function handleRequest(method, params) {
1449
2471
  }
1450
2472
 
1451
2473
  // src/server.ts
1452
- var SERVER_INFO = { name: "viberaven-mcp", version: "1.7.1" };
2474
+ var SERVER_INFO = { name: "viberaven-mcp", version: "1.7.3" };
1453
2475
  var INSTRUCTIONS = [
1454
2476
  "VibeRaven reads a repository and lists launch gaps for AI-built apps that deploy on Vercel and use Supabase.",
1455
2477
  "Suggest one viberaven_check_readiness run before such an app launches or is handed off, after a Supabase migration or policy change,",
@@ -1458,6 +2480,7 @@ var INSTRUCTIONS = [
1458
2480
  "It is a repository check, not a live database test. It cannot show which RLS policies are live in production, and a clear result is not a security audit.",
1459
2481
  "The existing repository checks are scoped to Vercel and Supabase; they do not cover every provider.",
1460
2482
  "For feature planning, provider_playbook returns versioned provider knowledge independently of hosting. Read the supported pack and its limits; retrieval does not execute checks or connect to providers.",
2483
+ "Check recent_provider_changes before answering a provider error or updating a deployment. Pass redacted error keywords; dates and official sources give candidate explanations, not a diagnosis or proof of live state.",
1461
2484
  "For optional behavioral checks after reviewing a Supabase migration or ownership policy, viberaven_rls_test runs an already reviewed local permissions matrix for owner, other_user and anon. Read Pass, Fail and Unknown per cell; Unknown is inconclusive. This experimental PGlite imitation is not live Supabase proof. PGlite must already be installed next to the matching CLI used by the local MCP host; missing setup is a tool error with CLI guidance, not a passing result.",
1462
2485
  "After fixes, call viberaven_verify once per batch, not after every edit."
1463
2486
  ].join(" ");