@mars-sea/dsh-commandcode-provider 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -600,7 +600,70 @@ declare function commandDefinition<C extends CommandCodeConnectionOptions>(deps:
600
600
  /** Register the command on `ctx.commands` (called from the plugin entry). */
601
601
  declare function applyCommands<C extends CommandCodeConnectionOptions>(ctx: Context, deps: CommandCodeCommandDeps<C>): void;
602
602
  //#endregion
603
+ //#region src/login-wire.d.ts
604
+ /** Why a login attempt ended in `failed` (stable across versions for copy). */
605
+ type CommandCodeLoginFailureReason =
606
+ /** The Studio page reported the authorization was denied by the user. */
607
+ 'denied' |
608
+ /** No callback arrived within the flow's timeout window. */
609
+ 'timeout' |
610
+ /** The delivered key failed `/alpha/whoami` validation (401). */
611
+ 'invalid-key' |
612
+ /** The validation request could not reach the API. */
613
+ 'network' |
614
+ /** The key could not be stored (credentials seam unavailable). */
615
+ 'unavailable' |
616
+ /** The attempt was cancelled by the user or torn down with the plugin. */
617
+ 'cancelled' |
618
+ /** Anything else. */
619
+ 'error';
620
+ /** One login attempt's full state face, as carried over the wire. */
621
+ interface CommandCodeLoginStatus {
622
+ /**
623
+ * `idle` — no attempt; `waiting` — the loopback server is up and the
624
+ * Studio URL is live; `success` — the key validated and was stored;
625
+ * `failed` — see `reason`/`message`.
626
+ */
627
+ state: 'idle' | 'waiting' | 'success' | 'failed';
628
+ /** The Studio authorization URL while `waiting`. */
629
+ authUrl?: string;
630
+ /** The account display name reported by the Studio, on `success`. */
631
+ userName?: string;
632
+ /** The key's label from the Studio, on `success`. */
633
+ keyName?: string;
634
+ /** Why the attempt failed, when `failed`. */
635
+ reason?: CommandCodeLoginFailureReason;
636
+ /** Human-readable failure detail, when `failed` (secondary to `reason`). */
637
+ message?: string;
638
+ }
639
+ /** The canonical endpoint paths of the three login Remotes. */
640
+ declare const LOGIN_BEGIN_ENDPOINT = "commandcode/loginBegin";
641
+ declare const LOGIN_STATUS_ENDPOINT = "commandcode/loginStatus";
642
+ declare const LOGIN_CANCEL_ENDPOINT = "commandcode/loginCancel";
643
+ /**
644
+ * Parse one untrusted boundary value into a {@link CommandCodeLoginStatus}.
645
+ * Every field is shape-checked so a malformed frame fails the boundary
646
+ * instead of leaking into the page.
647
+ */
648
+ declare function parseLoginStatus(value: unknown): CommandCodeLoginStatus;
649
+ /** The strict result codec shared by all three login endpoints. */
650
+ declare const loginStatusSchema: TypertSchema<CommandCodeLoginStatus>;
651
+ //#endregion
603
652
  //#region src/usage-remote.d.ts
653
+ /**
654
+ * The browser-login face the usage service exposes (`commandcode/login*`).
655
+ * Backed by the Host-half {@link !CommandCodeLoginFlow} when the plugin entry
656
+ * wired one; absent, the methods degrade to a no-op status so an old client
657
+ * against a fresh page still answers instead of hanging.
658
+ */
659
+ interface LoginFlowFacade {
660
+ /** Start (or rejoin) an attempt; rejects when it cannot start at all. */
661
+ begin(): Promise<CommandCodeLoginStatus>;
662
+ /** The current attempt's status. */
663
+ status(): CommandCodeLoginStatus;
664
+ /** Cancel a waiting attempt. */
665
+ cancel(): void;
666
+ }
604
667
  /** Everything the usage service needs beyond its Cordis context. */
605
668
  interface CommandCodeUsageDeps<C extends CommandCodeConnectionOptions = CommandCodeConnectionOptions> {
606
669
  /** The registered adapter (for getUsage). */
@@ -611,6 +674,12 @@ interface CommandCodeUsageDeps<C extends CommandCodeConnectionOptions = CommandC
611
674
  * entry around `adapter.getUsage()`.
612
675
  */
613
676
  reports?: () => Promise<CommandCodeAccountsReport>;
677
+ /**
678
+ * The browser-login flow (wired by the plugin entry). Absent means the
679
+ * login endpoints answer `idle` / reject with a plain message — the page's
680
+ * manual paste path stays the fallback.
681
+ */
682
+ login?: LoginFlowFacade;
614
683
  }
615
684
  /**
616
685
  * The Remote receiver: a Cordis service the Gateway resolves by key
@@ -631,6 +700,18 @@ declare class CommandCodeUsageService<C extends CommandCodeConnectionOptions = C
631
700
  * the failure branch the page renders as a hint.
632
701
  */
633
702
  report(): Promise<CommandCodeAccountsReport>;
703
+ /**
704
+ * Start (or rejoin) a browser-login attempt and return its fresh status —
705
+ * `waiting` carrying the Studio URL. Rejects when the flow cannot start
706
+ * (no free loopback port, disposed plugin); the Gateway folds the throw
707
+ * into the failure branch the page renders.
708
+ */
709
+ loginBegin(): Promise<CommandCodeLoginStatus>;
710
+ /** Poll a login attempt's status. */
711
+ loginStatus(): Promise<CommandCodeLoginStatus>;
712
+ /** Cancel a waiting attempt; returns the post-cancel status. */
713
+ loginCancel(): Promise<CommandCodeLoginStatus>;
714
+ private requireLogin;
634
715
  }
635
716
  /**
636
717
  * Provide the usage service and register its Remote descriptor. The registry
@@ -639,6 +720,121 @@ declare class CommandCodeUsageService<C extends CommandCodeConnectionOptions = C
639
720
  */
640
721
  declare function applyUsageRemote<C extends CommandCodeConnectionOptions>(ctx: Context, deps: CommandCodeUsageDeps<C>): void;
641
722
  //#endregion
723
+ //#region src/login.d.ts
724
+ /** Give up on the browser after this long without a callback (mirrors the CLI). */
725
+ declare const LOGIN_TIMEOUT_MS = 120000;
726
+ /** First local port the flow tries (mirrors the CLI). */
727
+ declare const LOGIN_START_PORT = 5959;
728
+ /** How many consecutive ports to try from {@link LOGIN_START_PORT}. */
729
+ declare const LOGIN_MAX_PORT_ATTEMPTS = 10;
730
+ /** Reject callback bodies larger than this (mirrors the CLI). */
731
+ declare const LOGIN_BODY_LIMIT_BYTES = 10000;
732
+ /** The Studio origins allowed to POST credentials to the loopback server. */
733
+ declare const LOGIN_ALLOWED_ORIGINS: readonly string[];
734
+ /** Credentials as delivered by the Studio's callback POST. */
735
+ interface CommandCodeLoginCredentials {
736
+ apiKey: string;
737
+ userId: string;
738
+ userName: string;
739
+ keyName: string;
740
+ }
741
+ /** Outcome of validating a delivered key against `/alpha/whoami`. */
742
+ type ApiKeyValidation = {
743
+ valid: true;
744
+ } | {
745
+ valid: false;
746
+ error: 'invalid_key' | 'server_error' | 'network_error';
747
+ };
748
+ interface CommandCodeLoginFlowDeps {
749
+ /**
750
+ * The Provider API base used for `/alpha/whoami` validation; also selects
751
+ * the matching Studio base (staging api → staging studio). A thunk is fine:
752
+ * it is re-read when each attempt starts, so a settings change reaches the
753
+ * next login. Defaults to the public API base.
754
+ */
755
+ apiBase?: string | (() => string | undefined);
756
+ /** Attempt timeout in millis; defaults to {@link LOGIN_TIMEOUT_MS}. */
757
+ timeoutMs?: number;
758
+ /** First port to try; defaults to {@link LOGIN_START_PORT}. */
759
+ startPort?: number;
760
+ /** Consecutive-port attempts; defaults to {@link LOGIN_MAX_PORT_ATTEMPTS}. */
761
+ maxPortAttempts?: number;
762
+ /** Validation fetch seam; defaults to global `fetch`. */
763
+ fetchImpl?: typeof fetch;
764
+ /** Randomness seam; defaults to `node:crypto` randomBytes(32) base64url. */
765
+ randomToken?: (byteLength: number) => string;
766
+ /**
767
+ * Receives the validated credentials after a successful login. Rejecting
768
+ * fails the attempt with `unavailable`.
769
+ */
770
+ storeKey(credentials: CommandCodeLoginCredentials): Promise<void>;
771
+ }
772
+ /** Compose the Studio authorization URL (pure, exported for tests). */
773
+ declare function buildCommandAuthUrl(options: {
774
+ studioBase: string;
775
+ port: number;
776
+ state: string;
777
+ }): string;
778
+ /** Map an API base onto the Studio base the CLI pairs it with. */
779
+ declare function studioBaseForApiBase(apiBase: string): string;
780
+ /**
781
+ * Validate one candidate key against `/alpha/whoami` (pure, exported for
782
+ * tests). Mirrors the CLI's verdicts: 401 → invalid_key, other non-OK →
783
+ * server_error, transport failure → network_error.
784
+ */
785
+ declare function validateCommandApiKey(fetchImpl: typeof fetch, apiBase: string, apiKey: string): Promise<ApiKeyValidation>;
786
+ /**
787
+ * One browser-login attempt machine. Single-flight by design: `begin()` while
788
+ * waiting returns the live attempt's status instead of starting a second one;
789
+ * a terminal state makes the next `begin()` start fresh.
790
+ */
791
+ declare class CommandCodeLoginFlow {
792
+ private readonly deps;
793
+ private readonly listeners;
794
+ private statusValue;
795
+ private server;
796
+ private timer;
797
+ /** Settle hooks of the live attempt's callback promise. */
798
+ private settle;
799
+ private disposed;
800
+ constructor(deps: CommandCodeLoginFlowDeps);
801
+ /** Subscribe to state transitions. @returns the disposer. */
802
+ onChange(listener: () => void): () => void;
803
+ /** The current attempt's status face. */
804
+ status(): CommandCodeLoginStatus;
805
+ /**
806
+ * Start an attempt (or rejoin the live one) and resolve with its status —
807
+ * `waiting` carrying the Studio URL once the loopback server is up.
808
+ * Rejects only when the flow cannot start at all (no free port, disposed).
809
+ */
810
+ begin(): Promise<CommandCodeLoginStatus>;
811
+ /** Cancel a waiting attempt; terminal states are untouched. */
812
+ cancel(): void;
813
+ /** Stop everything; a waiting attempt ends cancelled. Idempotent. */
814
+ dispose(): void;
815
+ private readApiBase;
816
+ private setStatus;
817
+ /** First free port among the consecutive candidates. */
818
+ private findPort;
819
+ /**
820
+ * Bind the attempt's loopback server, resolving when the port is live.
821
+ * Pre-bind failures reject (surfacing from `begin()`); a later server error
822
+ * settles the live attempt as a tagged failure instead.
823
+ */
824
+ private bindServer;
825
+ /** One request against the attempt's callback endpoint (CLI-mirrored). */
826
+ private handleCallback;
827
+ /** Answer a decisive callback, stop listening, and settle the attempt. */
828
+ private settleAttempt;
829
+ /** Post-validation completion: whoami check, then hand-off to storage. */
830
+ private complete;
831
+ /** Map a tagged settle rejection onto the status face. */
832
+ private failFrom;
833
+ private clearTimer;
834
+ /** Close the server and watchdog without touching the published status. */
835
+ private teardown;
836
+ }
837
+ //#endregion
642
838
  //#region src/index.d.ts
643
839
  declare const name = "llm-commandcode";
644
840
  declare const inject: string[];
@@ -708,5 +904,5 @@ interface ResolvedCommandCodeOptions extends CommandCodeConnectionOptions {
708
904
  declare function resolveAdapterOptions(config: Config): ResolvedCommandCodeOptions;
709
905
  declare function apply(ctx: Context, config: Config): void;
710
906
  //#endregion
711
- export { BILLING_ACCESS_TTL_MS, COMMAND_CODE_CLI_VERSION, type CommandCodeAccountConfig, CommandCodeAccountPool, type CommandCodeAccountSlot, type CommandCodeAccountState, type CommandCodeAccountUsage, type CommandCodeAccountsReport, CommandCodeAdapter, type CommandCodeAdapterDeps, type CommandCodeBillingAccess, type CommandCodeCommandDeps, type CommandCodeConnectionOptions, type CommandCodeUsageDeps, type CommandCodeUsageReport, CommandCodeUsageService, Config, DEFAULT_API_BASE, DEFAULT_GENERATE_MAX_TOKENS, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_MODELS_CACHE_PATH, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, KNOWN_DEALS, KNOWN_EFFORTS, KNOWN_IMAGE_MODELS, KNOWN_PEAK_PRICING, KNOWN_PLANS, KNOWN_SUBSCRIPTION_PLANS, KNOWN_THINKING_MODELS, PLAN_LABELS, PLAN_ORDER, PROVIDER, type ResolveAttachments, ResolvedCommandCodeOptions, USAGE_REPORT_ENDPOINT, accountUsable, apply, applyCommands, applyUsageRemote, capabilityDescription, commandDefinition, compareByPlan, dealLabel, formatContext, inject, modelVisibleInPlan, name, peakPricingLabel, peakPricingState, planLabel, projectSlugFromPath, resolveAdapterOptions, resolveAuthFileApiKey, selectActiveAccount, subscriptionPlanInfo, usageReportSchema };
907
+ export { type ApiKeyValidation, BILLING_ACCESS_TTL_MS, COMMAND_CODE_CLI_VERSION, type CommandCodeAccountConfig, CommandCodeAccountPool, type CommandCodeAccountSlot, type CommandCodeAccountState, type CommandCodeAccountUsage, type CommandCodeAccountsReport, CommandCodeAdapter, type CommandCodeAdapterDeps, type CommandCodeBillingAccess, type CommandCodeCommandDeps, type CommandCodeConnectionOptions, type CommandCodeLoginCredentials, type CommandCodeLoginFailureReason, CommandCodeLoginFlow, type CommandCodeLoginFlowDeps, type CommandCodeLoginStatus, type CommandCodeUsageDeps, type CommandCodeUsageReport, CommandCodeUsageService, Config, DEFAULT_API_BASE, DEFAULT_GENERATE_MAX_TOKENS, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_MODELS_CACHE_PATH, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, KNOWN_DEALS, KNOWN_EFFORTS, KNOWN_IMAGE_MODELS, KNOWN_PEAK_PRICING, KNOWN_PLANS, KNOWN_SUBSCRIPTION_PLANS, KNOWN_THINKING_MODELS, LOGIN_ALLOWED_ORIGINS, LOGIN_BEGIN_ENDPOINT, LOGIN_BODY_LIMIT_BYTES, LOGIN_CANCEL_ENDPOINT, LOGIN_MAX_PORT_ATTEMPTS, LOGIN_START_PORT, LOGIN_STATUS_ENDPOINT, LOGIN_TIMEOUT_MS, type LoginFlowFacade, PLAN_LABELS, PLAN_ORDER, PROVIDER, type ResolveAttachments, ResolvedCommandCodeOptions, USAGE_REPORT_ENDPOINT, accountUsable, apply, applyCommands, applyUsageRemote, buildCommandAuthUrl, capabilityDescription, commandDefinition, compareByPlan, dealLabel, formatContext, inject, loginStatusSchema, modelVisibleInPlan, name, parseLoginStatus, peakPricingLabel, peakPricingState, planLabel, projectSlugFromPath, resolveAdapterOptions, resolveAuthFileApiKey, selectActiveAccount, studioBaseForApiBase, subscriptionPlanInfo, usageReportSchema, validateCommandApiKey };
712
908
  //# sourceMappingURL=index.d.ts.map