@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.
@@ -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
  });
@@ -573,6 +574,321 @@ var registry_generated_default = {
573
574
  }
574
575
  };
575
576
 
577
+ // ../providers/recent-changes.generated.mjs
578
+ var recent_changes_generated_default = {
579
+ "hash": "d2aaaaf9089270914954d2a8fd7b4fa3933c8525111162650feeb7bf726c67dc",
580
+ "pack": {
581
+ "schemaVersion": 1,
582
+ "packVersion": "1.0.0",
583
+ "reviewedAt": "2026-10-30",
584
+ "dateConvention": "effective = provider-stated date; announced = publication/release date; verified = checked date only, not rollout.",
585
+ "limits": [
586
+ "Guidance only; repository and live provider state remain not_checked.",
587
+ "Static, reviewed official sources can change. A matching entry is a candidate explanation, not a diagnosis or evidence that a fix worked.",
588
+ "No provider connection, account, credential, runtime file read, network request, deployment or data change is performed."
589
+ ],
590
+ "correctionsAndConflicts": [
591
+ "Lovable current official dates Oct 23 retirement/Dec 1 deletion replace seeded Oct5/Nov 4. Affected built-in-backend projects only.",
592
+ "Vercel current docs list 26.x default; 24.x remains supported but is not the current default claim.",
593
+ "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.",
594
+ "Railway announcement has2026-08-21 visible publish date despite Aug 20 URL; avoid inventing Aug 20 announced date.",
595
+ "Clerk production-instance setup is evergreen verified Oct 30, not an Oct 30 provider change. Related secret masking is dated Oct 19.",
596
+ "Supabase legacy-key end 2026 deprecation is not an exact shutdown day; no mandatory day invented."
597
+ ],
598
+ "sources": [
599
+ {
600
+ "id": "supabase-grants-announcement",
601
+ "url": "https://supabase.com/changelog/45329-breaking-change-tables-not-exposed-to-data-and-graphql-api-automatically",
602
+ "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."
603
+ },
604
+ {
605
+ "id": "supabase-api-security",
606
+ "url": "https://supabase.com/docs/guides/api/securing-your-api",
607
+ "notes": "Grants determine object/role access; RLS controls rows. Configure both for API-exposed tables. Does not prove hosted project rollout or actual grants."
608
+ },
609
+ {
610
+ "id": "vercel-node20-announcement",
611
+ "url": "https://vercel.com/changelog/node-js-20-is-being-deprecated",
612
+ "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."
613
+ },
614
+ {
615
+ "id": "vercel-node-versions",
616
+ "url": "https://vercel.com/docs/functions/runtimes/node-js/node-js-versions",
617
+ "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."
618
+ },
619
+ {
620
+ "id": "vercel-node-error-source",
621
+ "url": "https://raw.githubusercontent.com/vercel/vercel/main/packages/build-utils/src/fs/node-version.ts",
622
+ "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."
623
+ },
624
+ {
625
+ "id": "next164-announcement",
626
+ "url": "https://nextjs.org/blog/next-16-4",
627
+ "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."
628
+ },
629
+ {
630
+ "id": "next-blocking-error",
631
+ "url": "https://nextjs.org/docs/messages/blocking-route",
632
+ "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."
633
+ },
634
+ {
635
+ "id": "next-cache-migration",
636
+ "url": "https://nextjs.org/docs/app/guides/migrating-to-cache-components",
637
+ "notes": "Route configs dynamic/revalidate/fetchCache replaced by use cache/cacheLife under Cache Components; avoid caching user request data indiscriminately."
638
+ },
639
+ {
640
+ "id": "lovable-environments",
641
+ "url": "https://docs.lovable.dev/features/environments",
642
+ "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."
643
+ },
644
+ {
645
+ "id": "railway-cac",
646
+ "url": "https://docs.railway.com/config-as-code",
647
+ "notes": "Existing railway.json/toml services continue until 2026-12-01 hard cutoff; new services cannot opt into CaC. Prefer .railway/railway.ts."
648
+ },
649
+ {
650
+ "id": "railway-iac",
651
+ "url": "https://docs.railway.com/infrastructure-as-code",
652
+ "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."
653
+ },
654
+ {
655
+ "id": "railway-guided-migration",
656
+ "url": "https://railway.com/changelog/2026-10-16-activity-feed-filters",
657
+ "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."
658
+ },
659
+ {
660
+ "id": "railway-cac-announcement",
661
+ "url": "https://railway.com/changelog/2026-08-20-railway-anon",
662
+ "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."
663
+ },
664
+ {
665
+ "id": "clerk-production",
666
+ "url": "https://clerk.com/docs/guides/development/deployment/production",
667
+ "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."
668
+ },
669
+ {
670
+ "id": "clerk-environments",
671
+ "url": "https://clerk.com/docs/guides/development/managing-environments",
672
+ "notes": "Development/Production instances differ; development unsuitable for production. Does not prove a particular app's live keys or readiness."
673
+ },
674
+ {
675
+ "id": "clerk-keys-once",
676
+ "url": "https://clerk.com/changelog/2026-10-19-secret-keys-visible-only-on-creation",
677
+ "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."
678
+ },
679
+ {
680
+ "id": "supabase-api-keys",
681
+ "url": "https://supabase.com/docs/guides/getting-started/api-keys",
682
+ "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."
683
+ },
684
+ {
685
+ "id": "supabase-key-migration",
686
+ "url": "https://supabase.com/docs/guides/getting-started/migrating-to-new-api-keys",
687
+ "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."
688
+ }
689
+ ],
690
+ "entries": [
691
+ {
692
+ "id": "supabase-explicit-data-api-grants",
693
+ "provider": "supabase",
694
+ "date": "2026-10-30",
695
+ "dateKind": "effective",
696
+ "dateNote": "Provider-announced application date for existing projects; announced 2026-04-28. This is not verification that any particular hosted project has rolled over.",
697
+ "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.",
698
+ "errorText": "permission denied for table your_table",
699
+ "errorTextKind": "official_documentation_example",
700
+ "errorCode": "42501",
701
+ "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.",
702
+ "officialSource": "https://supabase.com/changelog/45329-breaking-change-tables-not-exposed-to-data-and-graphql-api-automatically",
703
+ "sourceIds": [
704
+ "supabase-grants-announcement",
705
+ "supabase-api-security"
706
+ ],
707
+ "limitations": "Repo inspection cannot establish hosted grants, actual rollout, policy behavior, or a successful live request."
708
+ },
709
+ {
710
+ "id": "vercel-node20-to24",
711
+ "provider": "vercel",
712
+ "date": "2026-10-01",
713
+ "dateKind": "effective",
714
+ "dateNote": "Announced 2026-07-14. Scope: new Builds/Functions deployments, not already-deployed function invocations.",
715
+ "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.",
716
+ "errorText": 'Node.js Version "20.x" is discontinued and must be upgraded.',
717
+ "errorTextKind": "official_source_template_instantiated",
718
+ "errorCode": "BUILD_UTILS_NODE_VERSION_DISCONTINUED",
719
+ "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.",
720
+ "officialSource": "https://vercel.com/changelog/node-js-20-is-being-deprecated",
721
+ "sourceIds": [
722
+ "vercel-node20-announcement",
723
+ "vercel-node-versions",
724
+ "vercel-node-error-source"
725
+ ],
726
+ "limitations": "Exact prefix comes from official source with 20.x substituted, not a newly observed build. Container deployments have a separate runtime model."
727
+ },
728
+ {
729
+ "id": "next-cache-components-suspense",
730
+ "provider": "nextjs",
731
+ "date": "2026-10-06",
732
+ "dateKind": "announced",
733
+ "dateNote": "Next 16.4 release date. Default enablement statement applies to newly generated create-next-app apps; existing app config must be inspected.",
734
+ "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.",
735
+ "errorText": "Uncached data was accessed outside of `<Suspense>`",
736
+ "errorTextKind": "official_documentation_title",
737
+ "errorCode": null,
738
+ "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.',
739
+ "officialSource": "https://nextjs.org/blog/next-16-4",
740
+ "sourceIds": [
741
+ "next164-announcement",
742
+ "next-blocking-error",
743
+ "next-cache-migration"
744
+ ],
745
+ "limitations": "No app/version-specific reproduction or build run. Do not cache authentication/request data indiscriminately."
746
+ },
747
+ {
748
+ "id": "lovable-test-live-retired",
749
+ "provider": "lovable",
750
+ "date": "2026-10-23",
751
+ "dateKind": "effective",
752
+ "dateNote": "Current official guide differs from seeded VibeRaven dates Oct 5/Nov 4. Current retirement Oct 23 and deletion Dec 1 verified Oct 30.",
753
+ "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.",
754
+ "errorText": null,
755
+ "errorTextKind": "not_documented",
756
+ "symptom": "Test/Live switcher disappears; missing data may remain in detached Test rather than Live.",
757
+ "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.",
758
+ "officialSource": "https://docs.lovable.dev/features/environments",
759
+ "sourceIds": [
760
+ "lovable-environments"
761
+ ],
762
+ "limitations": "Applies to built-in-backend projects that used the split, not every external Supabase project. No runtime error quote supplied by the guide."
763
+ },
764
+ {
765
+ "id": "railway-config-as-code-retirement",
766
+ "provider": "railway",
767
+ "date": "2026-12-01",
768
+ "dateKind": "effective",
769
+ "dateNote": "Upcoming hard cutoff documented today; announcement page visible date 2026-08-21 despite Aug 20 URL. Guided migration announced Oct 16.",
770
+ "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.",
771
+ "errorText": null,
772
+ "errorTextKind": "not_documented",
773
+ "symptom": "IaC plan is blocked for a service still managed by a CaC file; no exact cutoff failure message verified.",
774
+ "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.",
775
+ "officialSource": "https://docs.railway.com/config-as-code",
776
+ "sourceIds": [
777
+ "railway-cac",
778
+ "railway-iac",
779
+ "railway-guided-migration",
780
+ "railway-cac-announcement"
781
+ ],
782
+ "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."
783
+ },
784
+ {
785
+ "id": "clerk-production-instance-keys",
786
+ "provider": "clerk",
787
+ "date": "2026-10-30",
788
+ "dateKind": "verified",
789
+ "dateNote": "Verification date only for evergreen production-instance guidance, not a rollout date. Related show-secret-once change announced 2026-10-19.",
790
+ "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.",
791
+ "errorText": null,
792
+ "errorTextKind": "not_documented",
793
+ "symptom": "Production app still uses pk_test_/sk_test_, or a lost secret cannot be revealed again.",
794
+ "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.",
795
+ "officialSource": "https://clerk.com/docs/guides/development/deployment/production",
796
+ "sourceIds": [
797
+ "clerk-production",
798
+ "clerk-environments",
799
+ "clerk-keys-once"
800
+ ],
801
+ "limitations": "No account, secret, production-instance, redirect, or deployment inspection. These docs give no single exact runtime error for the whole symptom."
802
+ },
803
+ {
804
+ "id": "supabase-publishable-secret-api-keys",
805
+ "provider": "supabase",
806
+ "date": "2026-10-30",
807
+ "dateKind": "verified",
808
+ "dateNote": "Verification date only. Docs say legacy keys deprecated by end 2026; no exact shutdown day claimed or checked here.",
809
+ "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.",
810
+ "errorText": "HTTP 401 Unauthorized",
811
+ "errorTextKind": "official_documented_http_status",
812
+ "symptom": "A secret key sent with a browser User-Agent is rejected; this is not a guarantee against use from scripts.",
813
+ "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.",
814
+ "officialSource": "https://supabase.com/docs/guides/getting-started/api-keys",
815
+ "sourceIds": [
816
+ "supabase-api-keys",
817
+ "supabase-key-migration"
818
+ ],
819
+ "limitations": "No key/account/provider inspection, rotation, or live request. Switching key formats does not fix missing grants or RLS policies."
820
+ }
821
+ ]
822
+ }
823
+ };
824
+
825
+ // ../providers/recentChanges.mjs
826
+ var availableProviders = [...new Set(recent_changes_generated_default.pack.entries.map((entry) => entry.provider))].sort();
827
+ var RECENT_PROVIDER_CHANGES_TOOL = {
828
+ name: "recent_provider_changes",
829
+ title: "Check recent provider changes",
830
+ 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(", ")}.
831
+ Limits: guidance only; does not read your repo, connect to providers, run fixes or verify rollout, deployment or live behavior.`,
832
+ inputSchema: {
833
+ type: "object",
834
+ properties: {
835
+ provider: { type: "string", enum: [...availableProviders], description: "Optional lowercase provider id. Unsupported ids return the bounded available list." },
836
+ query: { type: "string", minLength: 1, maxLength: 500, description: "Optional redacted error text or public keywords. Remove credentials, private paths and personal data before calling." },
837
+ limit: { type: "integer", minimum: 1, maximum: 8, default: 5, description: "Maximum entries, 1 to 8; default 5." }
838
+ },
839
+ additionalProperties: false
840
+ },
841
+ outputSchema: {
842
+ type: "object",
843
+ 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" } },
844
+ required: ["packVersion", "packHash", "reviewedAt", "dateConvention", "entries", "availableProviders", "limits", "correctionsAndConflicts", "verification"],
845
+ additionalProperties: false
846
+ },
847
+ annotations: { title: "Check recent provider changes", readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true }
848
+ };
849
+ 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(" ")]);
850
+ var words = (text) => [...new Set((text.toLowerCase().match(/[a-z0-9_]+/g) ?? []).filter((word) => (word.length >= 3 || /^\d{2,}$/.test(word)) && !stopWords.has(word)))];
851
+ 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(" "))) }));
852
+ function invalidInput(field) {
853
+ 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).
854
+ Field: ${field}
855
+ Example arguments: {"provider":"supabase","query":"42501","limit":5}
856
+ Next step: Choose an available provider: ${availableProviders.join(", ")}. Retrieval returns guidance; no connection or check was attempted.` }] };
857
+ }
858
+ function renderRecentChanges(result) {
859
+ const lines = [`Recent provider changes ${result.packVersion} (reviewed ${result.reviewedAt})`, result.dateConvention, "Guidance only. Repository and live checks: not checked.", ""];
860
+ 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.");
861
+ for (const entry of result.entries) {
862
+ lines.push(`${entry.provider}: ${entry.id}`, `Date: ${entry.date} (${entry.dateKind}). ${entry.dateNote}`, `What changed: ${entry.whatChanged}`);
863
+ if (entry.errorText !== null) lines.push(`Error: ${entry.errorText} (${entry.errorTextKind}${entry.errorCode ? `; code ${entry.errorCode}` : ""})`);
864
+ else lines.push(`Error: no exact error documented (${entry.errorTextKind}).`);
865
+ if (entry.symptom) lines.push(`Symptom: ${entry.symptom}`);
866
+ lines.push(`Fix guidance: ${entry.fix}`, `Official source: ${entry.officialSource}`, `Supporting sources: ${entry.sources.map((source) => source.url).join(" ")}`, `Limits: ${entry.limitations}`, "");
867
+ }
868
+ lines.push("Source corrections and conflicts:", ...result.correctionsAndConflicts.map((note) => `- ${note}`), "Limits:", ...result.limits.map((limit) => `- ${limit}`));
869
+ return lines.join("\n");
870
+ }
871
+ function recentProviderChanges(args) {
872
+ if (!args || typeof args !== "object" || Array.isArray(args) || Object.keys(args).some((key) => !["provider", "query", "limit"].includes(key))) return invalidInput("arguments");
873
+ if (Object.hasOwn(args, "provider") && (typeof args.provider !== "string" || !availableProviders.includes(args.provider))) return invalidInput("provider");
874
+ if (Object.hasOwn(args, "query") && (typeof args.query !== "string" || args.query.length > 500 || !args.query.trim() || /\u0000/.test(args.query))) return invalidInput("query");
875
+ if (Object.hasOwn(args, "limit") && (!Number.isInteger(args.limit) || args.limit < 1 || args.limit > 8)) return invalidInput("limit");
876
+ const terms = args.query === void 0 ? null : words(args.query);
877
+ 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)) }));
878
+ const structuredContent = JSON.parse(JSON.stringify({
879
+ packVersion: recent_changes_generated_default.pack.packVersion,
880
+ packHash: recent_changes_generated_default.hash,
881
+ reviewedAt: recent_changes_generated_default.pack.reviewedAt,
882
+ dateConvention: recent_changes_generated_default.pack.dateConvention,
883
+ entries,
884
+ availableProviders,
885
+ limits: recent_changes_generated_default.pack.limits,
886
+ correctionsAndConflicts: recent_changes_generated_default.pack.correctionsAndConflicts,
887
+ verification: { repo: "not_checked", live: "not_checked" }
888
+ }));
889
+ return { isError: false, structuredContent, content: [{ type: "text", text: renderRecentChanges(structuredContent) }] };
890
+ }
891
+
576
892
  // ../providers/index.mjs
577
893
  var PROVIDER_TOOL = {
578
894
  name: "provider_playbook",
@@ -1052,15 +1368,718 @@ var npmTools = [
1052
1368
  }
1053
1369
  ];
1054
1370
 
1055
- // src/lib/cli-runner.ts
1371
+ // ../cli/src/hosted/credentials.ts
1056
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");
1057
2076
  var import_node_fs3 = require("node:fs");
1058
- var import_node_path2 = require("node:path");
2077
+ var import_node_path3 = require("node:path");
1059
2078
 
1060
2079
  // src/lib/work-report-runner.ts
1061
2080
  var import_node_fs2 = require("node:fs");
1062
2081
  var import_node_module = require("node:module");
1063
- var import_node_path = require("node:path");
2082
+ var import_node_path2 = require("node:path");
1064
2083
 
1065
2084
  // ../../shared/workReportRunner.ts
1066
2085
  var import_node_fs = require("node:fs");
@@ -1079,7 +2098,7 @@ function runWorkReportProcess(entry, args, cwd3, spawnFn2) {
1079
2098
  } catch {
1080
2099
  return Promise.resolve(workReportFailure());
1081
2100
  }
1082
- return new Promise((resolve2) => {
2101
+ return new Promise((resolve3) => {
1083
2102
  let settled = false, stdoutBytes = 0, stderrBytes = 0;
1084
2103
  const chunks = [];
1085
2104
  let child;
@@ -1087,7 +2106,7 @@ function runWorkReportProcess(entry, args, cwd3, spawnFn2) {
1087
2106
  if (!settled) {
1088
2107
  settled = true;
1089
2108
  clearTimeout(timer);
1090
- resolve2(result);
2109
+ resolve3(result);
1091
2110
  }
1092
2111
  };
1093
2112
  const fail = () => {
@@ -1133,20 +2152,20 @@ ${stdout.trim()}` });
1133
2152
 
1134
2153
  // src/lib/work-report-runner.ts
1135
2154
  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}`);
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}`);
1138
2157
  };
1139
2158
  function resolveInstalledCli(version, cwd3) {
1140
2159
  const override = process.env.VIBERAVEN_CLI_PATH;
1141
2160
  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");
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");
1144
2163
  const info = (0, import_node_fs2.lstatSync)(selected);
1145
2164
  if (!info.isFile() || info.isSymbolicLink()) throw new Error("Unavailable installed CLI");
1146
2165
  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);
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);
1150
2169
  if (!manifestInfo.isFile() || manifestInfo.isSymbolicLink() || manifestInfo.size > 65536 || (0, import_node_fs2.realpathSync)(manifestPath) !== manifestPath) throw new Error("Unavailable installed CLI");
1151
2170
  const manifest = JSON.parse((0, import_node_fs2.readFileSync)(manifestPath, "utf8"));
1152
2171
  if (manifest.name !== "@viberaven/cli" || manifest.version !== version) throw new Error("Unavailable installed CLI");
@@ -1178,14 +2197,14 @@ var cachedVersion;
1178
2197
  function mcpVersion() {
1179
2198
  if (cachedVersion) return cachedVersion;
1180
2199
  let found;
1181
- 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)) {
1182
2201
  try {
1183
- 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"));
1184
2203
  if (manifest.name === MCP_PACKAGE && typeof manifest.version === "string") found = manifest.version;
1185
2204
  } catch {
1186
2205
  }
1187
2206
  }
1188
- found ??= true ? "1.7.1" : void 0;
2207
+ found ??= true ? "1.7.3" : void 0;
1189
2208
  if (!found || !PLAIN_VERSION.test(found)) {
1190
2209
  throw new Error(`Could not read a valid ${MCP_PACKAGE} version (got ${JSON.stringify(found)}), so the matching ${CLI_PACKAGE} cannot be pinned.`);
1191
2210
  }
@@ -1210,12 +2229,12 @@ function cliChildEnv(env = process.env) {
1210
2229
  }
1211
2230
  return out;
1212
2231
  }
1213
- var spawnFn = import_node_child_process.spawn;
2232
+ var spawnFn = import_node_child_process3.spawn;
1214
2233
  function __setSpawnForTest(fn) {
1215
2234
  spawnFn = fn;
1216
2235
  }
1217
2236
  function __resetSpawnForTest() {
1218
- spawnFn = import_node_child_process.spawn;
2237
+ spawnFn = import_node_child_process3.spawn;
1219
2238
  }
1220
2239
  function safeStringArg(value, label) {
1221
2240
  if (typeof value !== "string") throw new Error(`Invalid ${label}: expected string`);
@@ -1317,7 +2336,7 @@ function runVibeRavenDetailed(args, cwd3) {
1317
2336
  } catch (error) {
1318
2337
  return Promise.resolve(transportFailure(error));
1319
2338
  }
1320
- return new Promise((resolve2) => {
2339
+ return new Promise((resolve3) => {
1321
2340
  let child;
1322
2341
  try {
1323
2342
  child = spawnFn(built.command, built.args, {
@@ -1328,7 +2347,7 @@ function runVibeRavenDetailed(args, cwd3) {
1328
2347
  stdio: ["ignore", "pipe", "pipe"]
1329
2348
  });
1330
2349
  } catch (error) {
1331
- resolve2(transportFailure(error));
2350
+ resolve3(transportFailure(error));
1332
2351
  return;
1333
2352
  }
1334
2353
  let stdout = "";
@@ -1342,7 +2361,7 @@ function runVibeRavenDetailed(args, cwd3) {
1342
2361
  if (settled) return;
1343
2362
  settled = true;
1344
2363
  if (timer) clearTimeout(timer);
1345
- resolve2(result);
2364
+ resolve3(result);
1346
2365
  };
1347
2366
  const stopRls = (reason) => {
1348
2367
  finish(transportFailure(new Error(reason)));
@@ -1409,7 +2428,9 @@ var ALL_TOOLS = [
1409
2428
  ...npmTools,
1410
2429
  ...WORK_TOOLS,
1411
2430
  PROVIDER_TOOL,
1412
- ...LIVE_TOOLS
2431
+ RECENT_PROVIDER_CHANGES_TOOL,
2432
+ ...LIVE_TOOLS,
2433
+ ...accountTools
1413
2434
  ];
1414
2435
  function parseJsonObjectFromToolText(text) {
1415
2436
  const start = text.indexOf("{");
@@ -1433,13 +2454,17 @@ function isCompletedNegativeNpmVerdict(receipt) {
1433
2454
  }
1434
2455
  }
1435
2456
  async function callTool(name, args) {
2457
+ if (isAccountTool(name)) return (await handleAccountTool(name, args ?? {})).content[0].text;
1436
2458
  if (name === "provider_playbook") return providerPlaybook(args).content[0].text;
2459
+ if (name === "recent_provider_changes") return recentProviderChanges(args).content[0].text;
1437
2460
  return runVibeRaven(buildToolArgs(name, args || {}), args?.cwd);
1438
2461
  }
1439
2462
  async function handleRequest(method, params) {
1440
2463
  if (method === "tools/list") return { tools: ALL_TOOLS };
1441
2464
  if (method === "tools/call") {
2465
+ if (isAccountTool(params.name)) return handleAccountTool(params.name, params.arguments ?? {});
1442
2466
  if (params.name === "provider_playbook") return providerPlaybook(params.arguments);
2467
+ if (params.name === "recent_provider_changes") return recentProviderChanges(params.arguments ?? {});
1443
2468
  const args = params.arguments || {};
1444
2469
  const cliArgs = buildToolArgs(params.name, args);
1445
2470
  const run = await runVibeRavenDetailed(cliArgs, args.cwd);
@@ -1466,6 +2491,7 @@ async function handleRequest(method, params) {
1466
2491
  __resetSpawnForTest,
1467
2492
  __setSpawnForTest,
1468
2493
  callTool,
2494
+ createAccountToolHandler,
1469
2495
  handleRequest,
1470
2496
  parseJsonObjectFromToolText
1471
2497
  });