aipctl 2026.10.3 → 2026.10.4

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/build/index.cjs CHANGED
@@ -8532,10 +8532,10 @@ const defects = self => reverse$1(reduce$1(self, empty$r(), (list, cause) => cau
8532
8532
  /** @internal */
8533
8533
  const interruptors$1 = self => reduce$1(self, empty$o(), (set, cause) => cause._tag === OP_INTERRUPT ? some$1(pipe(set, add(cause.fiberId))) : none$7());
8534
8534
  /** @internal */
8535
- const failureOption = self => find(self, cause => cause._tag === OP_FAIL$2 ? some$1(cause.error) : none$7());
8535
+ const failureOption$1 = self => find(self, cause => cause._tag === OP_FAIL$2 ? some$1(cause.error) : none$7());
8536
8536
  /** @internal */
8537
8537
  const failureOrCause$1 = self => {
8538
- const option = failureOption(self);
8538
+ const option = failureOption$1(self);
8539
8539
  switch (option._tag) {
8540
8540
  case "None":
8541
8541
  {
@@ -9978,7 +9978,7 @@ const causeSquash = self => {
9978
9978
  };
9979
9979
  /** @internal */
9980
9980
  const causeSquashWith = /*#__PURE__*/dual(2, (self, f) => {
9981
- const option = pipe(self, failureOption, map$j(f));
9981
+ const option = pipe(self, failureOption$1, map$j(f));
9982
9982
  switch (option._tag) {
9983
9983
  case "None":
9984
9984
  {
@@ -16583,6 +16583,19 @@ const isInterruptedOnly = isInterruptedOnly$1;
16583
16583
  * @category Getters
16584
16584
  */
16585
16585
  const interruptors = interruptors$1;
16586
+ /**
16587
+ * Retrieves the first `Fail` error in a `Cause`, if present.
16588
+ *
16589
+ * **Details**
16590
+ *
16591
+ * This function returns an `Option` containing the first recoverable error
16592
+ * (`E`) from the cause. It's often used to quickly check if there's a primary
16593
+ * error to handle or display.
16594
+ *
16595
+ * @since 2.0.0
16596
+ * @category Getters
16597
+ */
16598
+ const failureOption = failureOption$1;
16586
16599
  /**
16587
16600
  * Splits a `Cause` into either its first `Fail` error or the rest of the cause
16588
16601
  * (which might only contain `Die` or `Interrupt`).
@@ -17781,12 +17794,24 @@ const effect_provide = /*#__PURE__*/dual(2, (self, source) => {
17781
17794
  });
17782
17795
 
17783
17796
  /** @internal */
17784
- const consoleWith = f => fiberRefGetWith(currentServices, services => f(get$a(services, consoleTag)));
17797
+ const consoleWith$1 = f => fiberRefGetWith(currentServices, services => f(get$a(services, consoleTag)));
17785
17798
  /** @internal */
17786
- const error$2 = (...args) => consoleWith(_ => _.error(...args));
17799
+ const withConsole$1 = /*#__PURE__*/dual(2, (effect, value) => fiberRefLocallyWith(effect, currentServices, add$2(consoleTag, value)));
17787
17800
  /** @internal */
17788
- const log$1 = (...args) => consoleWith(_ => _.log(...args));
17801
+ const error$2 = (...args) => consoleWith$1(_ => _.error(...args));
17802
+ /** @internal */
17803
+ const log$1 = (...args) => consoleWith$1(_ => _.log(...args));
17789
17804
 
17805
+ /**
17806
+ * @since 2.0.0
17807
+ * @category default services
17808
+ */
17809
+ const withConsole = withConsole$1;
17810
+ /**
17811
+ * @since 2.0.0
17812
+ * @category accessor
17813
+ */
17814
+ const consoleWith = consoleWith$1;
17790
17815
  /**
17791
17816
  * @since 2.0.0
17792
17817
  * @category accessor
@@ -89663,1286 +89688,169 @@ const runMain = runMain$1;
89663
89688
  ({
89664
89689
  ...CommitPrototype$1});
89665
89690
 
89666
- const BUILD_ENVS = ["local", "dev", "qa", "stage", "prod", "test"];
89667
- const isBuildEnv = (value) => BUILD_ENVS.includes(value);
89691
+ const NOT_LOGGED_IN_MESSAGE = 'Not logged in. Please run "aipctl auth login" first.';
89692
+ const SESSION_EXPIRED_MESSAGE = 'Session expired. Run "aipctl auth login" to continue.';
89668
89693
 
89669
- const injectedBuildEnv = "dev".length > 0 ? "dev" : "local";
89670
- if (!isBuildEnv(injectedBuildEnv)) {
89671
- throw new Error(`Invalid AIPCTL_BUILD_ENV: ${injectedBuildEnv}`);
89694
+ const CONFIG_SET_HINT = "aipctl config set --app-url https://app.example.com";
89695
+ const CONFIG_DIR$2 = path__namespace.join(os__namespace.homedir(), ".config", "aip");
89696
+ const CONFIG_FILE = path__namespace.join(CONFIG_DIR$2, "config.json");
89697
+ let cachedConfig;
89698
+ class ConfigServiceTag extends Tag$1("ConfigService")() {
89672
89699
  }
89673
- const VERSION = "2026.10.3".length > 0 ? "2026.10.3" : "0.0.0";
89674
- const BUILD_ENV = injectedBuildEnv;
89675
- const INCLUDE_NATIVE_LOGS = BUILD_ENV !== "prod";
89676
-
89677
- const loadBinaryModule = () => {
89678
- const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
89679
- return require$1(["..", "binary.cjs"].join("/"));
89680
- };
89681
- const resolveNativeBinary = (options = {}) => {
89682
- const env = options.env ?? process.env;
89683
- if (env.AIPCTL_NATIVE_BINARY && env.AIPCTL_NATIVE_BINARY.length > 0) {
89684
- return env.AIPCTL_NATIVE_BINARY;
89700
+ class AppUrlNotConfiguredError extends Error {
89701
+ constructor() {
89702
+ super(`App URL is not configured. Run "${CONFIG_SET_HINT}" first.`);
89703
+ this.name = "AppUrlNotConfiguredError";
89685
89704
  }
89686
- const binary = (options.loadBinaryModule ?? loadBinaryModule)();
89687
- return binary.resolveBinaryPath(options.platform ?? process.platform, options.arch ?? process.arch);
89688
- };
89689
- const runNativeCommand = (args, options = {}) => new Promise((resolve) => {
89690
- const env = options.env ?? process.env;
89691
- const spawn = options.spawn ?? childProcess.spawn;
89692
- const binaryPath = resolveNativeBinary(options);
89693
- const child = spawn(binaryPath, [...args], {
89694
- stdio: "inherit",
89695
- env
89696
- });
89697
- child.on("error", (error) => {
89698
- console.error(`Failed to start native command: ${error.message}`);
89699
- process.exitCode = 1;
89700
- resolve();
89701
- });
89702
- child.on("exit", (code) => {
89703
- process.exitCode = code ?? 1;
89704
- resolve();
89705
- });
89706
- });
89707
-
89708
- const restArgs = text$2({ name: "arg" }).pipe(
89709
- repeated,
89710
- withDescription$5("Arguments passed through to the native aipctl command")
89711
- );
89712
- const makeNativeCommand = (name, description) => make$4(
89713
- name,
89714
- { rest: restArgs },
89715
- ({ rest }) => promise$1(() => runNativeCommand([name, ...rest]))
89716
- ).pipe(withDescription(description));
89717
-
89718
- const nativeCommandDefinitions = [
89719
- { name: "install", description: "Install an MCP preset into a local client", includeInProd: true },
89720
- { name: "run", description: "Run the native MCP server", includeInProd: true },
89721
- { name: "tunnel", description: "Manage Edge Tunnel connections", includeInProd: true },
89722
- { name: "logs", description: "Inspect native MCP CLI logs", includeInProd: false }
89723
- ];
89724
- const nativeCommandNames = nativeCommandDefinitions.map(({ name }) => name);
89725
- const isEnabledNativeCommand = (definition, includeLogs) => definition.includeInProd || includeLogs;
89726
- const nativeSubcommands = nativeCommandDefinitions.filter((definition) => isEnabledNativeCommand(definition, INCLUDE_NATIVE_LOGS)).map(({ name, description }) => makeNativeCommand(name, description));
89727
- const isNativeCommandEnabled = (command, includeLogs = INCLUDE_NATIVE_LOGS) => {
89728
- const definition = nativeCommandDefinitions.find(({ name }) => name === command);
89729
- return definition ? isEnabledNativeCommand(definition, includeLogs) : false;
89730
- };
89731
-
89732
- const FORCED_ARGS_SEPARATOR = "--";
89733
- const NATIVE_ROOT_COMMANDS = new Set(nativeCommandNames);
89734
- const trailingOptionSpecs = [
89735
- ...["list", "get", "create", "update", "rename", "delete", "set-default", "unset-default"].map((command) => ({
89736
- command: ["admin", "preset", command],
89737
- booleanOptions: new Set(command === "delete" ? ["--force", "-f"] : ["list", "get"].includes(command) ? ["--json"] : []),
89738
- valueOptions: /* @__PURE__ */ new Set(["--org", ...command === "list" ? ["--page", "--pageSize"] : []]),
89739
- explicitBooleanValues: true,
89740
- booleanAliases: { "-f": "--force" }
89741
- })),
89742
- ...["invite", "remove-member", "update-member-role"].map((command) => ({
89743
- command: ["admin", "org", command],
89744
- booleanOptions: new Set(command === "remove-member" ? ["--force", "-f"] : []),
89745
- valueOptions: /* @__PURE__ */ new Set(["--org", ...command !== "remove-member" ? ["--role"] : []]),
89746
- explicitBooleanValues: true,
89747
- booleanAliases: { "-f": "--force" }
89748
- })),
89749
- {
89750
- command: ["org", "exit"],
89751
- booleanOptions: /* @__PURE__ */ new Set(["--force", "-f"]),
89752
- valueOptions: /* @__PURE__ */ new Set(["--org"]),
89753
- explicitBooleanValues: true,
89754
- booleanAliases: { "-f": "--force" }
89755
- },
89756
- ...["list", "get"].map((command) => ({
89757
- command: ["automation", command],
89758
- booleanOptions: /* @__PURE__ */ new Set(["--json"]),
89759
- valueOptions: /* @__PURE__ */ new Set(["--org", ...command === "list" ? ["--name"] : []]),
89760
- explicitBooleanValues: true
89761
- })),
89762
- {
89763
- command: ["automation", "delete"],
89764
- booleanOptions: /* @__PURE__ */ new Set(["--force", "-f"]),
89765
- valueOptions: /* @__PURE__ */ new Set(["--org"]),
89766
- explicitBooleanValues: true,
89767
- booleanAliases: { "-f": "--force" }
89768
- },
89769
- {
89770
- command: ["drive", "delete"],
89771
- booleanOptions: /* @__PURE__ */ new Set(["--force", "-f"]),
89772
- valueOptions: /* @__PURE__ */ new Set(["--org"])
89773
- },
89774
- {
89775
- command: ["automation", "history"],
89776
- booleanOptions: /* @__PURE__ */ new Set(),
89777
- valueOptions: /* @__PURE__ */ new Set(["--page", "--org"])
89778
- },
89779
- {
89780
- command: ["automation", "triggers"],
89781
- booleanOptions: /* @__PURE__ */ new Set(),
89782
- valueOptions: /* @__PURE__ */ new Set(["--account-id", "--folder-id", "--service-type", "--org"])
89783
- },
89784
- {
89785
- command: ["admin", "skill", "github", "import"],
89786
- booleanOptions: /* @__PURE__ */ new Set(["--overwrite", "--json"]),
89787
- valueOptions: /* @__PURE__ */ new Set(["--org", "--pat-env"])
89705
+ }
89706
+ class InvalidAppUrlError extends Error {
89707
+ rawValue;
89708
+ constructor(rawValue, reason) {
89709
+ super(`App URL is invalid: ${reason}. Run "${CONFIG_SET_HINT}" to fix it.`);
89710
+ this.name = "InvalidAppUrlError";
89711
+ this.rawValue = rawValue;
89788
89712
  }
89789
- ];
89790
- const getOptionName = (arg) => arg.split("=", 1)[0];
89791
- const findTrailingOptionSpec = (args) => trailingOptionSpecs.find((spec) => spec.command.every((part, index) => args[index] === part));
89792
- const isNativeRootCommand = (args) => NATIVE_ROOT_COMMANDS.has(args[0] ?? "");
89793
- const isBooleanOption = (arg, spec) => spec.booleanOptions.has(arg);
89794
- const isValueOption = (arg, spec) => spec.valueOptions.has(getOptionName(arg));
89795
- const normalizeTrailingOptions = (args, spec) => {
89796
- const options = [];
89797
- const rest = [];
89798
- for (let index = 0; index < args.length; index += 1) {
89799
- const arg = args[index];
89800
- if (arg === void 0) {
89801
- continue;
89802
- }
89803
- if (spec.explicitBooleanValues && spec.booleanOptions.has(getOptionName(arg))) {
89804
- const nextArg = args[index + 1];
89805
- const optionName = spec.booleanAliases?.[getOptionName(arg)] ?? getOptionName(arg);
89806
- if (arg.includes("=")) {
89807
- options.push(`${optionName}${arg.slice(arg.indexOf("="))}`);
89808
- } else if (nextArg === "true" || nextArg === "false") {
89809
- options.push(`${optionName}=${nextArg}`);
89810
- index += 1;
89811
- } else {
89812
- options.push(`${optionName}=true`);
89813
- }
89814
- continue;
89815
- }
89816
- if (isBooleanOption(arg, spec)) {
89817
- options.push(arg);
89818
- continue;
89819
- }
89820
- if (isValueOption(arg, spec)) {
89821
- options.push(arg);
89822
- const nextArg = args[index + 1];
89823
- if (!arg.includes("=") && nextArg !== void 0 && !nextArg.startsWith("-")) {
89824
- index += 1;
89825
- options.push(nextArg);
89826
- }
89827
- continue;
89713
+ }
89714
+ function isRecord$1(value) {
89715
+ return typeof value === "object" && value !== null;
89716
+ }
89717
+ function optionalString$1(value) {
89718
+ return typeof value === "string" ? value : void 0;
89719
+ }
89720
+ function parseCurrentOrganization(value) {
89721
+ if (!isRecord$1(value)) {
89722
+ return void 0;
89723
+ }
89724
+ const id = optionalString$1(value["id"]);
89725
+ const slug = optionalString$1(value["slug"]);
89726
+ const name = optionalString$1(value["name"]);
89727
+ if (!id || !slug || !name) {
89728
+ return void 0;
89729
+ }
89730
+ return { id, slug, name };
89731
+ }
89732
+ function normalizeLoadedConfig(value) {
89733
+ if (!isRecord$1(value)) {
89734
+ return {};
89735
+ }
89736
+ return {
89737
+ appBaseUrl: optionalString$1(value["appBaseUrl"]),
89738
+ currentOrganization: parseCurrentOrganization(value["currentOrganization"])
89739
+ };
89740
+ }
89741
+ function cloneConfig(config) {
89742
+ return {
89743
+ appBaseUrl: config.appBaseUrl,
89744
+ currentOrganization: config.currentOrganization ? { ...config.currentOrganization } : void 0
89745
+ };
89746
+ }
89747
+ function readConfigFile() {
89748
+ try {
89749
+ const content = fs__namespace.readFileSync(CONFIG_FILE, "utf-8");
89750
+ return normalizeLoadedConfig(JSON.parse(content));
89751
+ } catch {
89752
+ return {};
89753
+ }
89754
+ }
89755
+ function isSameCurrentOrganization(left, right) {
89756
+ return left?.id === right?.id && left?.slug === right?.slug && left?.name === right?.name;
89757
+ }
89758
+ function isSameConfig(left, right) {
89759
+ return left.appBaseUrl === right.appBaseUrl && isSameCurrentOrganization(left.currentOrganization, right.currentOrganization);
89760
+ }
89761
+ function isLoopbackHostname(hostname) {
89762
+ const normalized = hostname.toLowerCase();
89763
+ return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1" || normalized === "[::1]";
89764
+ }
89765
+ function hasExplicitAppUrlProtocol(value) {
89766
+ const protocolMatch = /^[a-z][a-z\d+.-]*:/i.exec(value);
89767
+ if (!protocolMatch) {
89768
+ return false;
89769
+ }
89770
+ const valueAfterProtocol = value.slice(protocolMatch[0].length);
89771
+ return !/^\d+(?:$|[/?#])/.test(valueAfterProtocol);
89772
+ }
89773
+ function normalizeAppUrl(rawValue) {
89774
+ const trimmed = rawValue.trim();
89775
+ if (trimmed.length === 0) {
89776
+ throw new InvalidAppUrlError(rawValue, "value must not be empty");
89777
+ }
89778
+ const appUrl = hasExplicitAppUrlProtocol(trimmed) ? trimmed : `https://${trimmed}`;
89779
+ let url;
89780
+ try {
89781
+ url = new URL(appUrl);
89782
+ } catch {
89783
+ throw new InvalidAppUrlError(rawValue, "value must be a valid URL");
89784
+ }
89785
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
89786
+ throw new InvalidAppUrlError(rawValue, "only https:// URLs are supported, with http:// allowed for localhost development");
89787
+ }
89788
+ if (url.protocol === "http:" && !isLoopbackHostname(url.hostname)) {
89789
+ throw new InvalidAppUrlError(rawValue, "http:// is only supported for localhost development; use https:// for app URLs");
89790
+ }
89791
+ return url.origin;
89792
+ }
89793
+ function deriveInternalBaseUrls(appBaseUrl) {
89794
+ const url = new URL(normalizeAppUrl(appBaseUrl));
89795
+ return {
89796
+ apiBaseUrl: `${url.protocol}//api.${url.host}`,
89797
+ chatBaseUrl: `${url.protocol}//chat.${url.host}`
89798
+ };
89799
+ }
89800
+ function getAppUrlStatus(config) {
89801
+ const rawValue = config.appBaseUrl;
89802
+ if (!rawValue) {
89803
+ return { state: "unconfigured" };
89804
+ }
89805
+ try {
89806
+ return {
89807
+ state: "configured",
89808
+ value: normalizeAppUrl(rawValue)
89809
+ };
89810
+ } catch (error) {
89811
+ if (error instanceof InvalidAppUrlError) {
89812
+ return {
89813
+ state: "invalid",
89814
+ value: rawValue,
89815
+ reason: error.message
89816
+ };
89828
89817
  }
89829
- rest.push(arg);
89818
+ throw error;
89830
89819
  }
89831
- return [...options, ...rest];
89832
- };
89833
- const normalizeAipArgs = (args) => {
89834
- if (isNativeRootCommand(args)) {
89835
- return [...args];
89820
+ }
89821
+ function requireAppBaseUrl(config) {
89822
+ const rawValue = config.appBaseUrl;
89823
+ if (!rawValue) {
89824
+ throw new AppUrlNotConfiguredError();
89836
89825
  }
89837
- const forcedArgsIndex = args.indexOf(FORCED_ARGS_SEPARATOR);
89838
- const parsedArgs = forcedArgsIndex === -1 ? args : args.slice(0, forcedArgsIndex);
89839
- const forcedArgs = forcedArgsIndex === -1 ? [] : args.slice(forcedArgsIndex);
89840
- const spec = findTrailingOptionSpec(parsedArgs);
89841
- if (!spec) {
89842
- return [...args];
89826
+ return normalizeAppUrl(rawValue);
89827
+ }
89828
+ function requireApiBaseUrl(config) {
89829
+ return deriveInternalBaseUrls(requireAppBaseUrl(config)).apiBaseUrl;
89830
+ }
89831
+ function requireChatBaseUrl(config) {
89832
+ return deriveInternalBaseUrls(requireAppBaseUrl(config)).chatBaseUrl;
89833
+ }
89834
+ const ConfigServiceLive = succeed$2(ConfigServiceTag, {
89835
+ load: () => {
89836
+ cachedConfig ??= readConfigFile();
89837
+ return cloneConfig(cachedConfig);
89838
+ },
89839
+ save: (config, currentConfig) => {
89840
+ const current = currentConfig ?? cachedConfig ?? readConfigFile();
89841
+ const merged = cloneConfig({
89842
+ ...current,
89843
+ ...config
89844
+ });
89845
+ cachedConfig = merged;
89846
+ if (isSameConfig(current, merged)) {
89847
+ return;
89848
+ }
89849
+ fs__namespace.mkdirSync(CONFIG_DIR$2, { recursive: true });
89850
+ fs__namespace.writeFileSync(CONFIG_FILE, JSON.stringify(merged, null, 2));
89843
89851
  }
89844
- const commandPrefix = parsedArgs.slice(0, spec.command.length);
89845
- const suffix = parsedArgs.slice(spec.command.length);
89846
- return [
89847
- ...commandPrefix,
89848
- ...normalizeTrailingOptions(suffix, spec),
89849
- ...forcedArgs
89850
- ];
89851
- };
89852
-
89853
- const implementedCommandOperationIds = /* @__PURE__ */ new Set([
89854
- "listCliAgents",
89855
- "getCliAgent",
89856
- "listCliAgentTemplates",
89857
- "createCliAgent",
89858
- "updateCliAgent",
89859
- "deleteCliAgent",
89860
- "updateCliAgentStatus",
89861
- "getCliAgentShare",
89862
- "getCliMe",
89863
- "getCliUserSettings",
89864
- "listCliOrganizations",
89865
- "getCliOrganizationCapabilities",
89866
- "listCliOrganizationMembers",
89867
- "listCliModels",
89868
- "listCliModelExecModels",
89869
- "createCliModelChatExecution",
89870
- "listCliSkills",
89871
- "getCliSkill",
89872
- "deleteCliSkill",
89873
- "listCliSkillLibrary",
89874
- "createCliSkillClones",
89875
- "listCliBuiltInSkills",
89876
- "createCliBuiltInSkillClones",
89877
- "listCliAdminSkills",
89878
- "getCliAdminSkill",
89879
- "deleteCliAdminSkill",
89880
- "updateCliAdminSkill",
89881
- "listCliAdminBuiltInSkills",
89882
- "createCliAdminBuiltInSkillClones",
89883
- "listCliDriveEntries",
89884
- "getCliDriveUsage",
89885
- "createCliDriveFolder",
89886
- "updateCliDriveEntryName",
89887
- "deleteCliDriveEntries",
89888
- "listCliChats",
89889
- "getCliChat",
89890
- "listCliChatMessages",
89891
- "listCliIntegrations",
89892
- "listCliAvailableIntegrations",
89893
- "getCliAdminIntegration",
89894
- "listCliIntegrationTools",
89895
- "listCliAutomations",
89896
- "getCliAutomation",
89897
- "listCliAutomationTriggers",
89898
- "listCliAutomationHistory",
89899
- "createCliAutomation",
89900
- "updateCliAutomation",
89901
- "deleteCliAutomation",
89902
- "updateCliAutomationStatus",
89903
- "getCliCreditUsage",
89904
- "listCliTopUsers",
89905
- "getCliDailyUsageGraph",
89906
- "listCliDailyUsers",
89907
- "listCliTopMcpTools",
89908
- "listCliAuditLogs",
89909
- "listCliAuditEventTypes",
89910
- "listCliPresets",
89911
- "getCliPreset",
89912
- "createCliPreset",
89913
- "updateCliPreset",
89914
- "updateCliPresetName",
89915
- "deleteCliPreset",
89916
- "updateCliDefaultPreset",
89917
- "deleteCliDefaultPreset",
89918
- "createCliOrganizationMemberInvitations",
89919
- "deleteCliOrganizationMembers",
89920
- "updateCliOrganizationMemberRoles",
89921
- "deleteCliOrganizationMembership",
89922
- "getCliTunnelStatus"
89923
- ]);
89924
- const releaseEnabledCommandOperationIds = /* @__PURE__ */ new Set([
89925
- "listCliAgents",
89926
- "getCliAgent",
89927
- "listCliAgentTemplates",
89928
- "createCliAgent",
89929
- "updateCliAgent",
89930
- "deleteCliAgent",
89931
- "updateCliAgentStatus",
89932
- "getCliAgentShare",
89933
- "getCliMe",
89934
- "getCliUserSettings",
89935
- "listCliOrganizations",
89936
- "getCliOrganizationCapabilities",
89937
- "listCliOrganizationMembers",
89938
- "listCliModels",
89939
- "listCliModelExecModels",
89940
- "listCliSkills",
89941
- "getCliSkill",
89942
- "deleteCliSkill",
89943
- "listCliSkillLibrary",
89944
- "createCliSkillClones",
89945
- "listCliBuiltInSkills",
89946
- "createCliBuiltInSkillClones",
89947
- "listCliAdminSkills",
89948
- "getCliAdminSkill",
89949
- "deleteCliAdminSkill",
89950
- "updateCliAdminSkill",
89951
- "listCliAdminBuiltInSkills",
89952
- "createCliAdminBuiltInSkillClones",
89953
- "listCliDriveEntries",
89954
- "getCliDriveUsage",
89955
- "createCliDriveFolder",
89956
- "updateCliDriveEntryName",
89957
- "deleteCliDriveEntries",
89958
- "listCliChats",
89959
- "getCliChat",
89960
- "listCliChatMessages",
89961
- "listCliIntegrations",
89962
- "listCliAvailableIntegrations",
89963
- "getCliAdminIntegration",
89964
- "listCliIntegrationTools",
89965
- "listCliAutomations",
89966
- "getCliAutomation",
89967
- "listCliAutomationTriggers",
89968
- "listCliAutomationHistory",
89969
- "createCliAutomation",
89970
- "updateCliAutomation",
89971
- "deleteCliAutomation",
89972
- "updateCliAutomationStatus",
89973
- "getCliCreditUsage",
89974
- "listCliTopUsers",
89975
- "getCliDailyUsageGraph",
89976
- "listCliDailyUsers",
89977
- "listCliTopMcpTools",
89978
- "listCliAuditLogs",
89979
- "listCliAuditEventTypes",
89980
- "listCliPresets",
89981
- "getCliPreset",
89982
- "createCliPreset",
89983
- "updateCliPreset",
89984
- "updateCliPresetName",
89985
- "deleteCliPreset",
89986
- "updateCliDefaultPreset",
89987
- "deleteCliDefaultPreset",
89988
- "createCliOrganizationMemberInvitations",
89989
- "deleteCliOrganizationMembers",
89990
- "updateCliOrganizationMemberRoles",
89991
- "deleteCliOrganizationMembership",
89992
- "getCliTunnelStatus"
89993
- ]);
89994
- const direct = (commands, operation) => commands.map((command) => ({
89995
- command,
89996
- tier: "GA_DIRECT",
89997
- availability: !implementedCommandOperationIds.has(operation.operationId ?? "") ? "PLANNED" : releaseEnabledCommandOperationIds.has(operation.operationId ?? "") ? "IMPLEMENTED" : "GATED",
89998
- ...operation
89999
- }));
90000
- const candidate = (commands, owner, authBoundary, requiredGates) => commands.map((command) => ({
90001
- command,
90002
- tier: "GA_CANDIDATE",
90003
- owner,
90004
- authBoundary,
90005
- quotaClass: "endpoint-guard",
90006
- availability: "GATED",
90007
- capability: `cli.${command.replaceAll(" ", ".")}`,
90008
- requiredGates
90009
- }));
90010
- const fixedBoundary = (commands, tier, owner, authBoundary) => commands.map((command) => ({
90011
- command,
90012
- tier,
90013
- owner,
90014
- authBoundary,
90015
- quotaClass: "none",
90016
- availability: tier === "INTERNAL_HIDDEN" ? "HIDDEN" : "AVAILABLE"
90017
- }));
90018
- const orgPath = "/api/cli/v1/organizations/{organizationSlug}";
90019
- const commandManifest = [
90020
- ...direct(["auth whoami"], {
90021
- owner: "backend",
90022
- authBoundary: "user-oauth",
90023
- quotaClass: "bootstrap",
90024
- endpoint: { method: "GET", path: "/api/cli/v1/me" },
90025
- operationId: "getCliMe",
90026
- canonicalOperation: "cli.identity.me.read",
90027
- capability: "cli.identity.me"
90028
- }),
90029
- ...direct(["org list", "org use", "org select"], {
90030
- owner: "backend",
90031
- authBoundary: "user-oauth",
90032
- quotaClass: "bootstrap",
90033
- endpoint: { method: "GET", path: "/api/cli/v1/organizations" },
90034
- operationId: "listCliOrganizations",
90035
- canonicalOperation: "cli.organization.list",
90036
- capability: "cli.organization.discovery"
90037
- }),
90038
- ...direct(["org capabilities"], {
90039
- owner: "backend",
90040
- authBoundary: "organization-oauth",
90041
- quotaClass: "metadata",
90042
- endpoint: { method: "GET", path: `${orgPath}/capabilities` },
90043
- operationId: "getCliOrganizationCapabilities",
90044
- canonicalOperation: "cli.organization.capabilities.read",
90045
- capability: "cli.organization.capabilities"
90046
- }),
90047
- ...direct(["org settings"], {
90048
- owner: "backend",
90049
- authBoundary: "user-oauth",
90050
- quotaClass: "bootstrap",
90051
- endpoint: { method: "GET", path: "/api/cli/v1/me/settings" },
90052
- operationId: "getCliUserSettings",
90053
- canonicalOperation: "cli.user.settings.read",
90054
- capability: "cli.user.settings"
90055
- }),
90056
- ...direct(["org members"], {
90057
- owner: "backend",
90058
- authBoundary: "organization-oauth",
90059
- quotaClass: "metadata",
90060
- endpoint: { method: "GET", path: `${orgPath}/members` },
90061
- operationId: "listCliOrganizationMembers",
90062
- canonicalOperation: "cli.organization.members.list",
90063
- capability: "cli.organization.members.read"
90064
- }),
90065
- ...direct(["org exit"], {
90066
- owner: "backend",
90067
- authBoundary: "organization-oauth",
90068
- quotaClass: "metadata",
90069
- endpoint: { method: "DELETE", path: `${orgPath}/membership` },
90070
- operationId: "deleteCliOrganizationMembership",
90071
- canonicalOperation: "cli.organization.membership.exit",
90072
- capability: "cli.organization.exit"
90073
- }),
90074
- ...direct(["admin org invite"], {
90075
- owner: "backend",
90076
- authBoundary: "organization-oauth",
90077
- quotaClass: "metadata",
90078
- endpoint: { method: "POST", path: `${orgPath}/members/invitations` },
90079
- operationId: "createCliOrganizationMemberInvitations",
90080
- canonicalOperation: "cli.organization.members.invite",
90081
- capability: "cli.organization.members.write"
90082
- }),
90083
- ...direct(["admin org remove-member"], {
90084
- owner: "backend",
90085
- authBoundary: "organization-oauth",
90086
- quotaClass: "metadata",
90087
- endpoint: { method: "DELETE", path: `${orgPath}/members` },
90088
- operationId: "deleteCliOrganizationMembers",
90089
- canonicalOperation: "cli.organization.members.remove",
90090
- capability: "cli.organization.members.write"
90091
- }),
90092
- ...direct(["admin org update-member-role"], {
90093
- owner: "backend",
90094
- authBoundary: "organization-oauth",
90095
- quotaClass: "metadata",
90096
- endpoint: { method: "PUT", path: `${orgPath}/members/role` },
90097
- operationId: "updateCliOrganizationMemberRoles",
90098
- canonicalOperation: "cli.organization.members.role.update",
90099
- capability: "cli.organization.members.write"
90100
- }),
90101
- ...direct(["model list"], {
90102
- owner: "chat",
90103
- authBoundary: "organization-oauth",
90104
- quotaClass: "metadata",
90105
- endpoint: { method: "GET", path: `${orgPath}/models` },
90106
- operationId: "listCliModels",
90107
- canonicalOperation: "cli.model.catalog.read",
90108
- capability: "cli.model.catalog"
90109
- }),
90110
- ...direct(["model-exec models", "model-exec get", "model-exec sample"], {
90111
- owner: "chat",
90112
- authBoundary: "organization-oauth",
90113
- quotaClass: "metadata",
90114
- endpoint: { method: "GET", path: `${orgPath}/model-exec/models` },
90115
- operationId: "listCliModelExecModels",
90116
- canonicalOperation: "cli.model.catalog.read",
90117
- capability: "cli.model.catalog"
90118
- }),
90119
- ...direct(["model-exec chat"], {
90120
- owner: "chat",
90121
- authBoundary: "organization-oauth",
90122
- quotaClass: "text-execution",
90123
- endpoint: { method: "POST", path: `${orgPath}/model-exec/chat` },
90124
- operationId: "createCliModelChatExecution",
90125
- canonicalOperation: "cli.model.text.execute",
90126
- capability: "cli.model.text.execute"
90127
- }),
90128
- ...direct(["agent list"], {
90129
- owner: "backend",
90130
- authBoundary: "organization-oauth",
90131
- quotaClass: "metadata",
90132
- endpoint: { method: "GET", path: `${orgPath}/agents` },
90133
- operationId: "listCliAgents",
90134
- canonicalOperation: "cli.agent.list",
90135
- capability: "cli.agent.read"
90136
- }),
90137
- ...direct(["agent get"], {
90138
- owner: "backend",
90139
- authBoundary: "organization-oauth",
90140
- quotaClass: "metadata",
90141
- endpoint: { method: "GET", path: `${orgPath}/agents/{installedAgentId}` },
90142
- operationId: "getCliAgent",
90143
- canonicalOperation: "cli.agent.get",
90144
- capability: "cli.agent.read"
90145
- }),
90146
- ...direct(["agent enable", "agent disable"], {
90147
- owner: "backend",
90148
- authBoundary: "organization-oauth",
90149
- quotaClass: "metadata",
90150
- endpoint: { method: "PATCH", path: `${orgPath}/agents/{installedAgentId}/status` },
90151
- operationId: "updateCliAgentStatus",
90152
- canonicalOperation: "cli.agent.status.update",
90153
- capability: "cli.agent.write"
90154
- }),
90155
- ...direct(["admin agent templates"], {
90156
- owner: "backend",
90157
- authBoundary: "organization-oauth",
90158
- quotaClass: "metadata",
90159
- endpoint: { method: "GET", path: `${orgPath}/agents/templates` },
90160
- operationId: "listCliAgentTemplates",
90161
- canonicalOperation: "cli.agent.templates.list",
90162
- capability: "cli.agent.read"
90163
- }),
90164
- ...direct(["admin agent create"], {
90165
- owner: "backend",
90166
- authBoundary: "organization-oauth",
90167
- quotaClass: "metadata",
90168
- endpoint: { method: "POST", path: `${orgPath}/agents` },
90169
- operationId: "createCliAgent",
90170
- canonicalOperation: "cli.agent.create",
90171
- capability: "cli.agent.write"
90172
- }),
90173
- ...direct(["admin agent update"], {
90174
- owner: "backend",
90175
- authBoundary: "organization-oauth",
90176
- quotaClass: "metadata",
90177
- endpoint: { method: "PATCH", path: `${orgPath}/agents/{installedAgentId}` },
90178
- operationId: "updateCliAgent",
90179
- canonicalOperation: "cli.agent.update",
90180
- capability: "cli.agent.write"
90181
- }),
90182
- ...direct(["admin agent delete"], {
90183
- owner: "backend",
90184
- authBoundary: "organization-oauth",
90185
- quotaClass: "metadata",
90186
- endpoint: { method: "DELETE", path: `${orgPath}/agents/{installedAgentId}` },
90187
- operationId: "deleteCliAgent",
90188
- canonicalOperation: "cli.agent.delete",
90189
- capability: "cli.agent.write"
90190
- }),
90191
- ...direct(["admin agent share"], {
90192
- owner: "backend",
90193
- authBoundary: "organization-oauth",
90194
- quotaClass: "metadata",
90195
- endpoint: { method: "GET", path: `${orgPath}/agents/{installedAgentId}/share` },
90196
- operationId: "getCliAgentShare",
90197
- canonicalOperation: "cli.agent.share.read",
90198
- capability: "cli.agent.read"
90199
- }),
90200
- ...direct(["skill list"], {
90201
- owner: "backend",
90202
- authBoundary: "organization-oauth",
90203
- quotaClass: "metadata",
90204
- endpoint: { method: "GET", path: `${orgPath}/skills` },
90205
- operationId: "listCliSkills",
90206
- canonicalOperation: "cli.skill.list",
90207
- capability: "cli.skill.read"
90208
- }),
90209
- ...direct(["skill get"], {
90210
- owner: "backend",
90211
- authBoundary: "organization-oauth",
90212
- quotaClass: "metadata",
90213
- endpoint: { method: "GET", path: `${orgPath}/skills/{skillId}` },
90214
- operationId: "getCliSkill",
90215
- canonicalOperation: "cli.skill.get",
90216
- capability: "cli.skill.read"
90217
- }),
90218
- ...direct(["skill delete"], {
90219
- owner: "backend",
90220
- authBoundary: "organization-oauth",
90221
- quotaClass: "metadata",
90222
- endpoint: { method: "DELETE", path: `${orgPath}/skills/{skillId}` },
90223
- operationId: "deleteCliSkill",
90224
- canonicalOperation: "cli.skill.delete",
90225
- capability: "cli.skill.write"
90226
- }),
90227
- ...direct(["skill library"], {
90228
- owner: "backend",
90229
- authBoundary: "organization-oauth",
90230
- quotaClass: "metadata",
90231
- endpoint: { method: "GET", path: `${orgPath}/skills/library` },
90232
- operationId: "listCliSkillLibrary",
90233
- canonicalOperation: "cli.skill.library.list",
90234
- capability: "cli.skill.read"
90235
- }),
90236
- ...direct(["skill clone"], {
90237
- owner: "backend",
90238
- authBoundary: "organization-oauth",
90239
- quotaClass: "metadata",
90240
- endpoint: { method: "POST", path: `${orgPath}/skills/library/clone` },
90241
- operationId: "createCliSkillClones",
90242
- canonicalOperation: "cli.skill.library.clone",
90243
- capability: "cli.skill.write"
90244
- }),
90245
- ...direct(["skill built-in"], {
90246
- owner: "backend",
90247
- authBoundary: "organization-oauth",
90248
- quotaClass: "metadata",
90249
- endpoint: { method: "GET", path: `${orgPath}/skills/built-in` },
90250
- operationId: "listCliBuiltInSkills",
90251
- canonicalOperation: "cli.skill.built-in.list",
90252
- capability: "cli.skill.read"
90253
- }),
90254
- ...direct(["skill clone-built-in"], {
90255
- owner: "backend",
90256
- authBoundary: "organization-oauth",
90257
- quotaClass: "metadata",
90258
- endpoint: { method: "POST", path: `${orgPath}/skills/built-in/clone` },
90259
- operationId: "createCliBuiltInSkillClones",
90260
- canonicalOperation: "cli.skill.built-in.clone",
90261
- capability: "cli.skill.write"
90262
- }),
90263
- ...direct(["admin skill list"], {
90264
- owner: "backend",
90265
- authBoundary: "organization-oauth",
90266
- quotaClass: "metadata",
90267
- endpoint: { method: "GET", path: `${orgPath}/admin/skills` },
90268
- operationId: "listCliAdminSkills",
90269
- canonicalOperation: "cli.admin.skill.list",
90270
- capability: "cli.admin.skill.read"
90271
- }),
90272
- ...direct(["admin skill get"], {
90273
- owner: "backend",
90274
- authBoundary: "organization-oauth",
90275
- quotaClass: "metadata",
90276
- endpoint: { method: "GET", path: `${orgPath}/admin/skills/{skillId}` },
90277
- operationId: "getCliAdminSkill",
90278
- canonicalOperation: "cli.admin.skill.get",
90279
- capability: "cli.admin.skill.read"
90280
- }),
90281
- ...direct(["admin skill delete"], {
90282
- owner: "backend",
90283
- authBoundary: "organization-oauth",
90284
- quotaClass: "metadata",
90285
- endpoint: { method: "DELETE", path: `${orgPath}/admin/skills/{skillId}` },
90286
- operationId: "deleteCliAdminSkill",
90287
- canonicalOperation: "cli.admin.skill.delete",
90288
- capability: "cli.admin.skill.write"
90289
- }),
90290
- ...direct(["admin skill publish", "admin skill unpublish"], {
90291
- owner: "backend",
90292
- authBoundary: "organization-oauth",
90293
- quotaClass: "metadata",
90294
- endpoint: { method: "PATCH", path: `${orgPath}/admin/skills/{skillId}` },
90295
- operationId: "updateCliAdminSkill",
90296
- canonicalOperation: "cli.admin.skill.update",
90297
- capability: "cli.admin.skill.write"
90298
- }),
90299
- ...direct(["admin skill built-in"], {
90300
- owner: "backend",
90301
- authBoundary: "organization-oauth",
90302
- quotaClass: "metadata",
90303
- endpoint: { method: "GET", path: `${orgPath}/admin/skills/built-in` },
90304
- operationId: "listCliAdminBuiltInSkills",
90305
- canonicalOperation: "cli.admin.skill.built-in.list",
90306
- capability: "cli.admin.skill.read"
90307
- }),
90308
- ...direct(["admin skill clone-built-in"], {
90309
- owner: "backend",
90310
- authBoundary: "organization-oauth",
90311
- quotaClass: "metadata",
90312
- endpoint: { method: "POST", path: `${orgPath}/admin/skills/built-in/clone` },
90313
- operationId: "createCliAdminBuiltInSkillClones",
90314
- canonicalOperation: "cli.admin.skill.built-in.clone",
90315
- capability: "cli.admin.skill.write"
90316
- }),
90317
- ...direct(["drive list"], {
90318
- owner: "backend",
90319
- authBoundary: "organization-oauth",
90320
- quotaClass: "metadata",
90321
- endpoint: { method: "GET", path: `${orgPath}/drive/entries` },
90322
- operationId: "listCliDriveEntries",
90323
- canonicalOperation: "cli.drive.entries.list",
90324
- capability: "cli.drive.read"
90325
- }),
90326
- ...direct(["drive usage"], {
90327
- owner: "backend",
90328
- authBoundary: "organization-oauth",
90329
- quotaClass: "metadata",
90330
- endpoint: { method: "GET", path: `${orgPath}/drive/usage` },
90331
- operationId: "getCliDriveUsage",
90332
- canonicalOperation: "cli.drive.usage.read",
90333
- capability: "cli.drive.read"
90334
- }),
90335
- ...direct(["drive mkdir"], {
90336
- owner: "backend",
90337
- authBoundary: "organization-oauth",
90338
- quotaClass: "metadata",
90339
- endpoint: { method: "POST", path: `${orgPath}/drive/folders` },
90340
- operationId: "createCliDriveFolder",
90341
- canonicalOperation: "cli.drive.folder.create",
90342
- capability: "cli.drive.write"
90343
- }),
90344
- ...direct(["drive rename"], {
90345
- owner: "backend",
90346
- authBoundary: "organization-oauth",
90347
- quotaClass: "metadata",
90348
- endpoint: { method: "PATCH", path: `${orgPath}/drive/entries/{entryId}` },
90349
- operationId: "updateCliDriveEntryName",
90350
- canonicalOperation: "cli.drive.entry.rename",
90351
- capability: "cli.drive.write"
90352
- }),
90353
- ...direct(["drive delete"], {
90354
- owner: "backend",
90355
- authBoundary: "organization-oauth",
90356
- quotaClass: "metadata",
90357
- endpoint: { method: "POST", path: `${orgPath}/drive/entries/delete` },
90358
- operationId: "deleteCliDriveEntries",
90359
- canonicalOperation: "cli.drive.entries.delete",
90360
- capability: "cli.drive.write"
90361
- }),
90362
- ...direct(["chat list"], {
90363
- owner: "chat",
90364
- authBoundary: "organization-oauth",
90365
- quotaClass: "metadata",
90366
- endpoint: { method: "GET", path: `${orgPath}/chats` },
90367
- operationId: "listCliChats",
90368
- canonicalOperation: "cli.chat.list",
90369
- capability: "cli.chat.read"
90370
- }),
90371
- ...direct(["chat get"], {
90372
- owner: "chat",
90373
- authBoundary: "organization-oauth",
90374
- quotaClass: "metadata",
90375
- endpoint: { method: "GET", path: `${orgPath}/chats/{conversationId}` },
90376
- operationId: "getCliChat",
90377
- canonicalOperation: "cli.chat.get",
90378
- capability: "cli.chat.read"
90379
- }),
90380
- ...direct(["chat messages"], {
90381
- owner: "chat",
90382
- authBoundary: "organization-oauth",
90383
- quotaClass: "metadata",
90384
- endpoint: { method: "GET", path: `${orgPath}/chats/{conversationId}/messages` },
90385
- operationId: "listCliChatMessages",
90386
- canonicalOperation: "cli.chat.messages.list",
90387
- capability: "cli.chat.read"
90388
- }),
90389
- ...direct(["integration list"], {
90390
- owner: "backend",
90391
- authBoundary: "organization-oauth",
90392
- quotaClass: "metadata",
90393
- endpoint: { method: "GET", path: `${orgPath}/integrations` },
90394
- operationId: "listCliIntegrations",
90395
- canonicalOperation: "cli.integration.list",
90396
- capability: "cli.integration.read"
90397
- }),
90398
- ...direct(["admin integration available"], {
90399
- owner: "backend",
90400
- authBoundary: "organization-oauth",
90401
- quotaClass: "metadata",
90402
- endpoint: { method: "GET", path: `${orgPath}/admin/integrations/available` },
90403
- operationId: "listCliAvailableIntegrations",
90404
- canonicalOperation: "cli.admin.integration.available.list",
90405
- capability: "cli.admin.integration.read"
90406
- }),
90407
- ...direct(["admin integration get"], {
90408
- owner: "backend",
90409
- authBoundary: "organization-oauth",
90410
- quotaClass: "metadata",
90411
- endpoint: { method: "GET", path: `${orgPath}/admin/integrations/{integrationId}` },
90412
- operationId: "getCliAdminIntegration",
90413
- canonicalOperation: "cli.admin.integration.get",
90414
- capability: "cli.admin.integration.read"
90415
- }),
90416
- ...direct(["admin integration tools"], {
90417
- owner: "backend",
90418
- authBoundary: "organization-oauth",
90419
- quotaClass: "metadata",
90420
- endpoint: { method: "GET", path: `${orgPath}/admin/integrations/{integrationId}/tools` },
90421
- operationId: "listCliIntegrationTools",
90422
- canonicalOperation: "cli.admin.integration.tools.list",
90423
- capability: "cli.admin.integration.read"
90424
- }),
90425
- ...direct(["automation list"], {
90426
- owner: "backend",
90427
- authBoundary: "organization-oauth",
90428
- quotaClass: "metadata",
90429
- endpoint: { method: "GET", path: `${orgPath}/automations` },
90430
- operationId: "listCliAutomations",
90431
- canonicalOperation: "cli.automation.list",
90432
- capability: "cli.automation.read"
90433
- }),
90434
- ...direct(["automation get"], {
90435
- owner: "backend",
90436
- authBoundary: "organization-oauth",
90437
- quotaClass: "metadata",
90438
- endpoint: { method: "GET", path: `${orgPath}/automations/{automationId}` },
90439
- operationId: "getCliAutomation",
90440
- canonicalOperation: "cli.automation.get",
90441
- capability: "cli.automation.read"
90442
- }),
90443
- ...direct(["automation triggers"], {
90444
- owner: "backend",
90445
- authBoundary: "organization-oauth",
90446
- quotaClass: "metadata",
90447
- endpoint: { method: "GET", path: `${orgPath}/automations/triggers` },
90448
- operationId: "listCliAutomationTriggers",
90449
- canonicalOperation: "cli.automation.triggers.list",
90450
- capability: "cli.automation.read"
90451
- }),
90452
- ...direct(["automation history"], {
90453
- owner: "backend",
90454
- authBoundary: "organization-oauth",
90455
- quotaClass: "metadata",
90456
- endpoint: { method: "GET", path: `${orgPath}/automations/{automationId}/history` },
90457
- operationId: "listCliAutomationHistory",
90458
- canonicalOperation: "cli.automation.history.list",
90459
- capability: "cli.automation.read"
90460
- }),
90461
- ...direct(["automation create"], {
90462
- owner: "backend",
90463
- authBoundary: "organization-oauth",
90464
- quotaClass: "metadata",
90465
- endpoint: { method: "POST", path: `${orgPath}/automations` },
90466
- operationId: "createCliAutomation",
90467
- canonicalOperation: "cli.automation.create",
90468
- capability: "cli.automation.write"
90469
- }),
90470
- ...direct(["automation update"], {
90471
- owner: "backend",
90472
- authBoundary: "organization-oauth",
90473
- quotaClass: "metadata",
90474
- endpoint: { method: "PUT", path: `${orgPath}/automations/{automationId}` },
90475
- operationId: "updateCliAutomation",
90476
- canonicalOperation: "cli.automation.update",
90477
- capability: "cli.automation.write"
90478
- }),
90479
- ...direct(["automation delete"], {
90480
- owner: "backend",
90481
- authBoundary: "organization-oauth",
90482
- quotaClass: "metadata",
90483
- endpoint: { method: "DELETE", path: `${orgPath}/automations/{automationId}` },
90484
- operationId: "deleteCliAutomation",
90485
- canonicalOperation: "cli.automation.delete",
90486
- capability: "cli.automation.write"
90487
- }),
90488
- ...direct(["automation enable", "automation disable"], {
90489
- owner: "backend",
90490
- authBoundary: "organization-oauth",
90491
- quotaClass: "metadata",
90492
- endpoint: { method: "PATCH", path: `${orgPath}/automations/{automationId}/status` },
90493
- operationId: "updateCliAutomationStatus",
90494
- canonicalOperation: "cli.automation.status.update",
90495
- capability: "cli.automation.write"
90496
- }),
90497
- ...direct(["admin usage credit"], {
90498
- owner: "backend",
90499
- authBoundary: "organization-oauth",
90500
- quotaClass: "metadata",
90501
- endpoint: { method: "GET", path: `${orgPath}/admin/usage/credit` },
90502
- operationId: "getCliCreditUsage",
90503
- canonicalOperation: "cli.admin.usage.credit.read",
90504
- capability: "cli.admin.usage.read"
90505
- }),
90506
- ...direct(["admin usage top-users"], {
90507
- owner: "backend",
90508
- authBoundary: "organization-oauth",
90509
- quotaClass: "metadata",
90510
- endpoint: { method: "GET", path: `${orgPath}/admin/usage/top-users` },
90511
- operationId: "listCliTopUsers",
90512
- canonicalOperation: "cli.admin.usage.top-users.read",
90513
- capability: "cli.admin.usage.read"
90514
- }),
90515
- ...direct(["admin usage daily-graph"], {
90516
- owner: "backend",
90517
- authBoundary: "organization-oauth",
90518
- quotaClass: "metadata",
90519
- endpoint: { method: "GET", path: `${orgPath}/admin/usage/daily-graph` },
90520
- operationId: "getCliDailyUsageGraph",
90521
- canonicalOperation: "cli.admin.usage.daily-graph.read",
90522
- capability: "cli.admin.usage.read"
90523
- }),
90524
- ...direct(["admin usage daily-users"], {
90525
- owner: "backend",
90526
- authBoundary: "organization-oauth",
90527
- quotaClass: "metadata",
90528
- endpoint: { method: "GET", path: `${orgPath}/admin/usage/daily-users` },
90529
- operationId: "listCliDailyUsers",
90530
- canonicalOperation: "cli.admin.usage.daily-users.read",
90531
- capability: "cli.admin.usage.read"
90532
- }),
90533
- ...direct(["admin usage mcp-top"], {
90534
- owner: "backend",
90535
- authBoundary: "organization-oauth",
90536
- quotaClass: "metadata",
90537
- endpoint: { method: "GET", path: `${orgPath}/admin/usage/mcp-top` },
90538
- operationId: "listCliTopMcpTools",
90539
- canonicalOperation: "cli.admin.usage.mcp-top.read",
90540
- capability: "cli.admin.usage.read"
90541
- }),
90542
- ...direct(["admin audit list"], {
90543
- owner: "backend",
90544
- authBoundary: "organization-oauth",
90545
- quotaClass: "metadata",
90546
- endpoint: { method: "GET", path: `${orgPath}/admin/audit` },
90547
- operationId: "listCliAuditLogs",
90548
- canonicalOperation: "cli.admin.audit.list",
90549
- capability: "cli.admin.audit.read"
90550
- }),
90551
- ...direct(["admin audit types"], {
90552
- owner: "backend",
90553
- authBoundary: "organization-oauth",
90554
- quotaClass: "metadata",
90555
- endpoint: { method: "GET", path: `${orgPath}/admin/audit/types` },
90556
- operationId: "listCliAuditEventTypes",
90557
- canonicalOperation: "cli.admin.audit.types.list",
90558
- capability: "cli.admin.audit.read"
90559
- }),
90560
- ...direct(["admin preset list"], {
90561
- owner: "backend",
90562
- authBoundary: "organization-oauth",
90563
- quotaClass: "metadata",
90564
- endpoint: { method: "GET", path: `${orgPath}/admin/presets` },
90565
- operationId: "listCliPresets",
90566
- canonicalOperation: "cli.admin.preset.list",
90567
- capability: "cli.admin.preset.read"
90568
- }),
90569
- ...direct(["admin preset get"], {
90570
- owner: "backend",
90571
- authBoundary: "organization-oauth",
90572
- quotaClass: "metadata",
90573
- endpoint: { method: "GET", path: `${orgPath}/admin/presets/{presetId}` },
90574
- operationId: "getCliPreset",
90575
- canonicalOperation: "cli.admin.preset.get",
90576
- capability: "cli.admin.preset.read"
90577
- }),
90578
- ...direct(["admin preset create"], {
90579
- owner: "backend",
90580
- authBoundary: "organization-oauth",
90581
- quotaClass: "metadata",
90582
- endpoint: { method: "POST", path: `${orgPath}/admin/presets` },
90583
- operationId: "createCliPreset",
90584
- canonicalOperation: "cli.admin.preset.create",
90585
- capability: "cli.admin.preset.write"
90586
- }),
90587
- ...direct(["admin preset update"], {
90588
- owner: "backend",
90589
- authBoundary: "organization-oauth",
90590
- quotaClass: "metadata",
90591
- endpoint: { method: "PUT", path: `${orgPath}/admin/presets/{presetId}` },
90592
- operationId: "updateCliPreset",
90593
- canonicalOperation: "cli.admin.preset.update",
90594
- capability: "cli.admin.preset.write"
90595
- }),
90596
- ...direct(["admin preset rename"], {
90597
- owner: "backend",
90598
- authBoundary: "organization-oauth",
90599
- quotaClass: "metadata",
90600
- endpoint: { method: "PATCH", path: `${orgPath}/admin/presets/{presetId}` },
90601
- operationId: "updateCliPresetName",
90602
- canonicalOperation: "cli.admin.preset.rename",
90603
- capability: "cli.admin.preset.write"
90604
- }),
90605
- ...direct(["admin preset delete"], {
90606
- owner: "backend",
90607
- authBoundary: "organization-oauth",
90608
- quotaClass: "metadata",
90609
- endpoint: { method: "DELETE", path: `${orgPath}/admin/presets/{presetId}` },
90610
- operationId: "deleteCliPreset",
90611
- canonicalOperation: "cli.admin.preset.delete",
90612
- capability: "cli.admin.preset.write"
90613
- }),
90614
- ...direct(["admin preset set-default"], {
90615
- owner: "backend",
90616
- authBoundary: "organization-oauth",
90617
- quotaClass: "metadata",
90618
- endpoint: { method: "PUT", path: `${orgPath}/admin/presets/{presetId}/default` },
90619
- operationId: "updateCliDefaultPreset",
90620
- canonicalOperation: "cli.admin.preset.default.set",
90621
- capability: "cli.admin.preset.write"
90622
- }),
90623
- ...direct(["admin preset unset-default"], {
90624
- owner: "backend",
90625
- authBoundary: "organization-oauth",
90626
- quotaClass: "metadata",
90627
- endpoint: { method: "DELETE", path: `${orgPath}/admin/presets/{presetId}/default` },
90628
- operationId: "deleteCliDefaultPreset",
90629
- canonicalOperation: "cli.admin.preset.default.unset",
90630
- capability: "cli.admin.preset.write"
90631
- }),
90632
- ...direct(["admin tunnel status"], {
90633
- owner: "backend",
90634
- authBoundary: "organization-oauth",
90635
- quotaClass: "metadata",
90636
- endpoint: { method: "GET", path: `${orgPath}/admin/tunnel/status` },
90637
- operationId: "getCliTunnelStatus",
90638
- canonicalOperation: "cli.admin.tunnel.status.read",
90639
- capability: "cli.admin.tunnel.read"
90640
- }),
90641
- ...candidate(["agent chat"], "chat", "organization-oauth", [
90642
- "streaming-performance",
90643
- "execution-permit-lifetime",
90644
- "disconnect-cancel-recovery"
90645
- ]),
90646
- ...candidate(["admin agent export"], "backend", "organization-oauth", [
90647
- "bounded-download",
90648
- "partial-file-cleanup",
90649
- "authorization-audit"
90650
- ]),
90651
- ...candidate(["skill upload", "skill download", "admin skill upload", "admin skill download"], "backend", "organization-oauth", [
90652
- "archive-size-mime-validation",
90653
- "presigned-host-policy",
90654
- "abort-complete-recovery"
90655
- ]),
90656
- ...candidate([
90657
- "admin skill github inspect",
90658
- "admin skill github import",
90659
- "admin skill github sync"
90660
- ], "backend", "organization-oauth", [
90661
- "external-timeout",
90662
- "repository-size-limit",
90663
- "duplicate-import-protection",
90664
- "credential-redaction"
90665
- ]),
90666
- ...candidate([
90667
- "admin skill github credentials set",
90668
- "admin skill github credentials clear"
90669
- ], "backend", "organization-oauth", [
90670
- "secret-redaction",
90671
- "rotation-revoke-audit"
90672
- ]),
90673
- ...candidate(["drive upload", "drive download"], "backend", "organization-oauth", [
90674
- "byte-timeout-bound",
90675
- "presigned-host-policy",
90676
- "storage-quota",
90677
- "partial-file-cleanup"
90678
- ]),
90679
- ...candidate(["chat send"], "chat", "organization-oauth", [
90680
- "conversation-idempotency",
90681
- "paid-execution-deduplication",
90682
- "timeout-cancel-recovery"
90683
- ]),
90684
- ...candidate(["integration test"], "backend", "organization-oauth", [
90685
- "external-timeout",
90686
- "credential-redaction"
90687
- ]),
90688
- ...candidate(["admin integration update", "admin integration delete"], "backend", "organization-oauth", [
90689
- "typed-contract",
90690
- "credential-redaction",
90691
- "mutation-idempotency"
90692
- ]),
90693
- ...candidate(["automation run", "automation cancel", "automation webhook-regen"], "backend", "organization-oauth", [
90694
- "operation-idempotency",
90695
- "state-transition-validation",
90696
- "execution-quota",
90697
- "secret-rotation"
90698
- ]),
90699
- ...candidate(["admin preset regen-key", "admin preset regen-static-key"], "backend", "organization-oauth", [
90700
- "key-redaction",
90701
- "rotation-audit",
90702
- "retry-rollback-safety"
90703
- ]),
90704
- ...candidate(["admin tunnel config", "admin tunnel token"], "backend", "organization-oauth", [
90705
- "sensitive-output-policy",
90706
- "token-ttl-redaction",
90707
- "audit"
90708
- ]),
90709
- {
90710
- command: "model-exec image generate",
90711
- tier: "DEFERRED",
90712
- owner: "chat",
90713
- authBoundary: "organization-oauth",
90714
- quotaClass: "endpoint-guard",
90715
- availability: "DEFERRED",
90716
- capability: "cli.model.image.generate",
90717
- requiredGates: ["async-job-lifecycle", "artifact-ttl", "my-drive-output", "cost-reservation"]
90718
- },
90719
- ...fixedBoundary(["auth login", "auth refresh"], "STANDARD_OAUTH", "backend", "standard-oauth"),
90720
- ...fixedBoundary([
90721
- "auth status",
90722
- "auth logout",
90723
- "config set",
90724
- "config status",
90725
- "org current"
90726
- ], "LOCAL_ONLY", "desktop", "local"),
90727
- ...fixedBoundary(["install", "run", "tunnel"], "EXISTING_NATIVE", "native", "native"),
90728
- ...fixedBoundary(["logs"], "INTERNAL_HIDDEN", "native", "hidden")
90729
- ];
90730
-
90731
- const CUSTOMER_AVAILABILITIES = /* @__PURE__ */ new Set([
90732
- "IMPLEMENTED",
90733
- "AVAILABLE"
90734
- ]);
90735
- const isCustomerAvailable = (entry) => CUSTOMER_AVAILABILITIES.has(entry.availability);
90736
- const normalizeCliArgCase = (arg) => arg.toLowerCase();
90737
- const commandSegments = (command) => command.split(" ");
90738
- const PROD_DISABLED_BUILT_INS = /* @__PURE__ */ new Set(["--completions", "--wizard"]);
90739
- const isCommandPrefix = (entry, args) => {
90740
- const segments = commandSegments(entry.command);
90741
- return segments.length <= args.length && segments.every((segment, index) => args[index] === segment);
90742
- };
90743
- const commandPathBeforeOptions = (args) => args.slice(0, args.findIndex((arg) => arg.startsWith("-")) === -1 ? args.length : args.findIndex((arg) => arg.startsWith("-")));
90744
- const formatUnavailableMessage = (command) => `Command "aipctl ${command}" is not available in this aipctl release. Run "aipctl --help" to see supported commands.`;
90745
- const formatUnavailableOptionMessage = (option) => `Option "aipctl ${option}" is not available in this aipctl release. Run "aipctl --help" to see supported commands.`;
90746
- const commandArgsForAvailability = (args) => {
90747
- const commandArgs = [];
90748
- for (let index = 0; index < args.length; index += 1) {
90749
- const arg = args[index];
90750
- if (arg === "--log-level") {
90751
- index += 1;
90752
- continue;
90753
- }
90754
- commandArgs.push(arg);
90755
- }
90756
- return commandArgs;
90757
- };
90758
- const getUnavailableCommandMessage = (args, buildEnv) => {
90759
- if (buildEnv !== "prod" || args.length === 0) {
90760
- return null;
90761
- }
90762
- const normalizedArgs = args.map(normalizeCliArgCase);
90763
- const disabledBuiltIn = normalizedArgs.find((arg) => PROD_DISABLED_BUILT_INS.has(arg));
90764
- if (disabledBuiltIn) {
90765
- return formatUnavailableOptionMessage(disabledBuiltIn);
90766
- }
90767
- const commandArgs = commandArgsForAvailability(normalizedArgs);
90768
- const entry = commandManifest.filter((candidate) => isCommandPrefix(candidate, commandArgs)).sort((left, right) => commandSegments(right.command).length - commandSegments(left.command).length).at(0);
90769
- if (entry) {
90770
- return isCustomerAvailable(entry) ? null : formatUnavailableMessage(entry.command);
90771
- }
90772
- const path = commandPathBeforeOptions(commandArgs).join(" ");
90773
- if (!path) {
90774
- return null;
90775
- }
90776
- const descendants = commandManifest.filter(({ command }) => command.startsWith(`${path} `));
90777
- if (descendants.length > 0 && descendants.every((candidate) => !isCustomerAvailable(candidate))) {
90778
- return formatUnavailableMessage(path);
90779
- }
90780
- return null;
90781
- };
90782
-
90783
- const NOT_LOGGED_IN_MESSAGE = 'Not logged in. Please run "aipctl auth login" first.';
90784
- const SESSION_EXPIRED_MESSAGE = 'Session expired. Run "aipctl auth login" to continue.';
90785
-
90786
- const CONFIG_SET_HINT = "aipctl config set --app-url https://app.example.com";
90787
- const CONFIG_DIR$2 = path__namespace.join(os__namespace.homedir(), ".config", "aip");
90788
- const CONFIG_FILE = path__namespace.join(CONFIG_DIR$2, "config.json");
90789
- let cachedConfig;
90790
- class ConfigServiceTag extends Tag$1("ConfigService")() {
90791
- }
90792
- class AppUrlNotConfiguredError extends Error {
90793
- constructor() {
90794
- super(`App URL is not configured. Run "${CONFIG_SET_HINT}" first.`);
90795
- this.name = "AppUrlNotConfiguredError";
90796
- }
90797
- }
90798
- class InvalidAppUrlError extends Error {
90799
- rawValue;
90800
- constructor(rawValue, reason) {
90801
- super(`App URL is invalid: ${reason}. Run "${CONFIG_SET_HINT}" to fix it.`);
90802
- this.name = "InvalidAppUrlError";
90803
- this.rawValue = rawValue;
90804
- }
90805
- }
90806
- function isRecord$1(value) {
90807
- return typeof value === "object" && value !== null;
90808
- }
90809
- function optionalString$1(value) {
90810
- return typeof value === "string" ? value : void 0;
90811
- }
90812
- function parseCurrentOrganization(value) {
90813
- if (!isRecord$1(value)) {
90814
- return void 0;
90815
- }
90816
- const id = optionalString$1(value["id"]);
90817
- const slug = optionalString$1(value["slug"]);
90818
- const name = optionalString$1(value["name"]);
90819
- if (!id || !slug || !name) {
90820
- return void 0;
90821
- }
90822
- return { id, slug, name };
90823
- }
90824
- function normalizeLoadedConfig(value) {
90825
- if (!isRecord$1(value)) {
90826
- return {};
90827
- }
90828
- return {
90829
- appBaseUrl: optionalString$1(value["appBaseUrl"]),
90830
- currentOrganization: parseCurrentOrganization(value["currentOrganization"])
90831
- };
90832
- }
90833
- function cloneConfig(config) {
90834
- return {
90835
- appBaseUrl: config.appBaseUrl,
90836
- currentOrganization: config.currentOrganization ? { ...config.currentOrganization } : void 0
90837
- };
90838
- }
90839
- function readConfigFile() {
90840
- try {
90841
- const content = fs__namespace.readFileSync(CONFIG_FILE, "utf-8");
90842
- return normalizeLoadedConfig(JSON.parse(content));
90843
- } catch {
90844
- return {};
90845
- }
90846
- }
90847
- function isSameCurrentOrganization(left, right) {
90848
- return left?.id === right?.id && left?.slug === right?.slug && left?.name === right?.name;
90849
- }
90850
- function isSameConfig(left, right) {
90851
- return left.appBaseUrl === right.appBaseUrl && isSameCurrentOrganization(left.currentOrganization, right.currentOrganization);
90852
- }
90853
- function isLoopbackHostname(hostname) {
90854
- const normalized = hostname.toLowerCase();
90855
- return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1" || normalized === "[::1]";
90856
- }
90857
- function hasExplicitAppUrlProtocol(value) {
90858
- const protocolMatch = /^[a-z][a-z\d+.-]*:/i.exec(value);
90859
- if (!protocolMatch) {
90860
- return false;
90861
- }
90862
- const valueAfterProtocol = value.slice(protocolMatch[0].length);
90863
- return !/^\d+(?:$|[/?#])/.test(valueAfterProtocol);
90864
- }
90865
- function normalizeAppUrl(rawValue) {
90866
- const trimmed = rawValue.trim();
90867
- if (trimmed.length === 0) {
90868
- throw new InvalidAppUrlError(rawValue, "value must not be empty");
90869
- }
90870
- const appUrl = hasExplicitAppUrlProtocol(trimmed) ? trimmed : `https://${trimmed}`;
90871
- let url;
90872
- try {
90873
- url = new URL(appUrl);
90874
- } catch {
90875
- throw new InvalidAppUrlError(rawValue, "value must be a valid URL");
90876
- }
90877
- if (url.protocol !== "http:" && url.protocol !== "https:") {
90878
- throw new InvalidAppUrlError(rawValue, "only https:// URLs are supported, with http:// allowed for localhost development");
90879
- }
90880
- if (url.protocol === "http:" && !isLoopbackHostname(url.hostname)) {
90881
- throw new InvalidAppUrlError(rawValue, "http:// is only supported for localhost development; use https:// for app URLs");
90882
- }
90883
- return url.origin;
90884
- }
90885
- function deriveInternalBaseUrls(appBaseUrl) {
90886
- const url = new URL(normalizeAppUrl(appBaseUrl));
90887
- return {
90888
- apiBaseUrl: `${url.protocol}//api.${url.host}`,
90889
- chatBaseUrl: `${url.protocol}//chat.${url.host}`
90890
- };
90891
- }
90892
- function getAppUrlStatus(config) {
90893
- const rawValue = config.appBaseUrl;
90894
- if (!rawValue) {
90895
- return { state: "unconfigured" };
90896
- }
90897
- try {
90898
- return {
90899
- state: "configured",
90900
- value: normalizeAppUrl(rawValue)
90901
- };
90902
- } catch (error) {
90903
- if (error instanceof InvalidAppUrlError) {
90904
- return {
90905
- state: "invalid",
90906
- value: rawValue,
90907
- reason: error.message
90908
- };
90909
- }
90910
- throw error;
90911
- }
90912
- }
90913
- function requireAppBaseUrl(config) {
90914
- const rawValue = config.appBaseUrl;
90915
- if (!rawValue) {
90916
- throw new AppUrlNotConfiguredError();
90917
- }
90918
- return normalizeAppUrl(rawValue);
90919
- }
90920
- function requireApiBaseUrl(config) {
90921
- return deriveInternalBaseUrls(requireAppBaseUrl(config)).apiBaseUrl;
90922
- }
90923
- function requireChatBaseUrl(config) {
90924
- return deriveInternalBaseUrls(requireAppBaseUrl(config)).chatBaseUrl;
90925
- }
90926
- const ConfigServiceLive = succeed$2(ConfigServiceTag, {
90927
- load: () => {
90928
- cachedConfig ??= readConfigFile();
90929
- return cloneConfig(cachedConfig);
90930
- },
90931
- save: (config, currentConfig) => {
90932
- const current = currentConfig ?? cachedConfig ?? readConfigFile();
90933
- const merged = cloneConfig({
90934
- ...current,
90935
- ...config
90936
- });
90937
- cachedConfig = merged;
90938
- if (isSameConfig(current, merged)) {
90939
- return;
90940
- }
90941
- fs__namespace.mkdirSync(CONFIG_DIR$2, { recursive: true });
90942
- fs__namespace.writeFileSync(CONFIG_FILE, JSON.stringify(merged, null, 2));
90943
- }
90944
- });
90945
- const ConfigService = ConfigServiceTag;
89852
+ });
89853
+ const ConfigService = ConfigServiceTag;
90946
89854
 
90947
89855
  var properLockfile = {exports: {}};
90948
89856
 
@@ -93838,6 +92746,7 @@ const CLI_FLAG_PATTERN = /(\-\-(?:access-token|refresh-token|token|secret|client
93838
92746
  const HIGH_RISK_KEY_VALUE_PATTERN = /((?:["']?)\b(?:webhook[_-]?url|invitation[_-]?link|invite[_-]?link|mcp[_-]?url|upload[_-]?url|download[_-]?url)\b(?:["']?)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|https?:\/\/[^\s"'`<>]+|[^\s,;]+)/gi;
93839
92747
  const KEY_VALUE_PATTERN = /((?:["']?)\b(?:access[_-]?token|refresh[_-]?token|auth[_-]?token|token|secret|client[_-]?secret|password|api[_-]?key|private[_-]?key|secret[_-]?key|pat|credential|credentials|cookie|signature|sig)\b(?:["']?)\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&}]+)/gi;
93840
92748
  const AUTH_HEADER_PATTERN = /(Authorization\s*:\s*(?:Bearer|Basic)\s+)([^\s,;]+)/gi;
92749
+ const BEARER_PATTERN = /(\bBearer\s+)([^\s,;]+)/gi;
93841
92750
  const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/gi;
93842
92751
  function normalizeKey(value) {
93843
92752
  return value.replace(/[^a-z0-9]/gi, "").toLowerCase();
@@ -93950,6 +92859,7 @@ function sanitizeOAuthAuthorizeUrlForDisplay(value) {
93950
92859
  function maskSensitiveText(value) {
93951
92860
  let masked = value;
93952
92861
  masked = masked.replace(AUTH_HEADER_PATTERN, `$1${REDACTED_VALUE}`);
92862
+ masked = masked.replace(BEARER_PATTERN, `$1${REDACTED_VALUE}`);
93953
92863
  masked = masked.replace(CLI_FLAG_PATTERN, `$1${REDACTED_VALUE}`);
93954
92864
  masked = masked.replace(HIGH_RISK_KEY_VALUE_PATTERN, `$1${REDACTED_VALUE}`);
93955
92865
  masked = masked.replace(KEY_VALUE_PATTERN, `$1${REDACTED_VALUE}`);
@@ -94010,31 +92920,270 @@ function maskSensitiveData(value, options = {}, context = {}) {
94010
92920
  masked[key] = maskDictionaryString(entry, options);
94011
92921
  continue;
94012
92922
  }
94013
- if (isFullyRedactedKey(key)) {
94014
- if (entry !== null && typeof entry === "object") {
94015
- masked[key] = maskSensitiveData(entry, options, {
94016
- key,
94017
- forceMaskPrimitives: true
94018
- });
94019
- } else {
94020
- masked[key] = entry == null ? entry : REDACTED_VALUE;
92923
+ if (isFullyRedactedKey(key)) {
92924
+ if (entry !== null && typeof entry === "object") {
92925
+ masked[key] = maskSensitiveData(entry, options, {
92926
+ key,
92927
+ forceMaskPrimitives: true
92928
+ });
92929
+ } else {
92930
+ masked[key] = entry == null ? entry : REDACTED_VALUE;
92931
+ }
92932
+ continue;
92933
+ }
92934
+ if (normalizedKey === MASKED_COMMAND_KEY && typeof entry === "string") {
92935
+ masked[key] = entry;
92936
+ continue;
92937
+ }
92938
+ if (normalizedKey === COMMAND_KEY && typeof entry === "string") {
92939
+ masked[key] = maskSensitiveText(entry);
92940
+ continue;
92941
+ }
92942
+ masked[key] = maskSensitiveData(entry, options, {
92943
+ key,
92944
+ forceMaskPrimitives: context.forceMaskPrimitives || isSensitiveContainerKey(key)
92945
+ });
92946
+ }
92947
+ return masked;
92948
+ }
92949
+
92950
+ const MAX_CONCURRENCY = 3;
92951
+ const MAX_RATE_REQUESTS = 10;
92952
+ const RATE_WINDOW_MS = 5e3;
92953
+ const POLL_INTERVAL_MS = 300;
92954
+ const CONFIG_DIR = path__namespace.join(os__namespace.homedir(), ".config", "aip");
92955
+ const STATE_FILE = path__namespace.join(CONFIG_DIR, "rate-limit.json");
92956
+ function pruneOldRequests(recentRequests, now = Date.now()) {
92957
+ return recentRequests.filter((ts) => now - new Date(ts).getTime() < RATE_WINDOW_MS);
92958
+ }
92959
+ function pruneDeadSlots(slots) {
92960
+ return slots.filter((slot) => {
92961
+ try {
92962
+ process.kill(slot.pid, 0);
92963
+ return true;
92964
+ } catch {
92965
+ return false;
92966
+ }
92967
+ });
92968
+ }
92969
+ function getRateLimitWaitMs(recentRequests, now = Date.now()) {
92970
+ const active = pruneOldRequests(recentRequests, now);
92971
+ if (active.length < MAX_RATE_REQUESTS) return 0;
92972
+ const oldestMs = Math.min(...active.map((ts) => new Date(ts).getTime()));
92973
+ return oldestMs + RATE_WINDOW_MS - now;
92974
+ }
92975
+ function ensureConfigDir() {
92976
+ fs__namespace.mkdirSync(CONFIG_DIR, { recursive: true });
92977
+ }
92978
+ function readState() {
92979
+ try {
92980
+ const raw = fs__namespace.readFileSync(STATE_FILE, "utf-8");
92981
+ return JSON.parse(raw);
92982
+ } catch {
92983
+ return { slots: [], recentRequests: [] };
92984
+ }
92985
+ }
92986
+ function writeState(state) {
92987
+ fs__namespace.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
92988
+ }
92989
+ async function withLock(fn) {
92990
+ ensureConfigDir();
92991
+ if (!fs__namespace.existsSync(STATE_FILE)) {
92992
+ writeState({ slots: [], recentRequests: [] });
92993
+ }
92994
+ const release2 = await lockfile.lock(STATE_FILE, {
92995
+ retries: { retries: 20, minTimeout: 50, maxTimeout: 200 },
92996
+ stale: 5e3
92997
+ });
92998
+ try {
92999
+ return fn();
93000
+ } finally {
93001
+ await release2();
93002
+ }
93003
+ }
93004
+ async function release(id) {
93005
+ try {
93006
+ await withLock(() => {
93007
+ const state = readState();
93008
+ state.slots = state.slots.filter((s) => id ? s.id !== id : s.pid !== process.pid);
93009
+ writeState(state);
93010
+ });
93011
+ } catch {
93012
+ }
93013
+ }
93014
+ async function acquire(signal) {
93015
+ const id = crypto.randomUUID();
93016
+ while (true) {
93017
+ signal?.throwIfAborted();
93018
+ let concurrencyFull = false;
93019
+ let rateLimitWaitMs = 0;
93020
+ try {
93021
+ await withLock(() => {
93022
+ signal?.throwIfAborted();
93023
+ const state = readState();
93024
+ state.slots = pruneDeadSlots(state.slots);
93025
+ const now = Date.now();
93026
+ state.recentRequests = pruneOldRequests(state.recentRequests, now);
93027
+ if (state.slots.length >= MAX_CONCURRENCY) {
93028
+ concurrencyFull = true;
93029
+ writeState(state);
93030
+ return;
93031
+ }
93032
+ rateLimitWaitMs = getRateLimitWaitMs(state.recentRequests, now);
93033
+ if (rateLimitWaitMs > 0) {
93034
+ writeState(state);
93035
+ return;
93036
+ }
93037
+ state.slots.push({ pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString(), id });
93038
+ state.recentRequests.push((/* @__PURE__ */ new Date()).toISOString());
93039
+ writeState(state);
93040
+ });
93041
+ } catch {
93042
+ signal?.throwIfAborted();
93043
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
93044
+ continue;
93045
+ }
93046
+ if (!concurrencyFull && rateLimitWaitMs === 0) {
93047
+ if (signal?.aborted) {
93048
+ await release(id);
93049
+ signal.throwIfAborted();
94021
93050
  }
94022
- continue;
94023
- }
94024
- if (normalizedKey === MASKED_COMMAND_KEY && typeof entry === "string") {
94025
- masked[key] = entry;
94026
- continue;
94027
- }
94028
- if (normalizedKey === COMMAND_KEY && typeof entry === "string") {
94029
- masked[key] = maskSensitiveText(entry);
94030
- continue;
93051
+ return id;
94031
93052
  }
94032
- masked[key] = maskSensitiveData(entry, options, {
94033
- key,
94034
- forceMaskPrimitives: context.forceMaskPrimitives || isSensitiveContainerKey(key)
93053
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
93054
+ }
93055
+ }
93056
+
93057
+ const HTTP_DEADLINE_MS = 12e4;
93058
+ const HTTP_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
93059
+ const TRANSFER_DEADLINE_MS = 6e5;
93060
+ const TRANSFER_MAX_RESPONSE_BYTES = 128 * 1024 * 1024;
93061
+ const pendingHttp = /* @__PURE__ */ new Set();
93062
+ function track(task) {
93063
+ pendingHttp.add(task);
93064
+ void task.then(() => pendingHttp.delete(task), () => pendingHttp.delete(task));
93065
+ return task;
93066
+ }
93067
+ async function waitForHttpCleanup() {
93068
+ if (pendingHttp.size === 0) return;
93069
+ let timer;
93070
+ try {
93071
+ await Promise.race([
93072
+ Promise.allSettled([...pendingHttp]),
93073
+ new Promise((resolve) => {
93074
+ timer = setTimeout(resolve, 5e3);
93075
+ })
93076
+ ]);
93077
+ } finally {
93078
+ clearTimeout(timer);
93079
+ }
93080
+ }
93081
+ class HttpRequestError extends Error {
93082
+ constructor(code, message, outcome, requestId) {
93083
+ super(message);
93084
+ this.code = code;
93085
+ this.outcome = outcome;
93086
+ this.requestId = requestId;
93087
+ this.name = "HttpRequestError";
93088
+ }
93089
+ }
93090
+ function withHttpResponse(input, init, consume, options = {}) {
93091
+ return track(performHttpResponse(input, init, consume, options));
93092
+ }
93093
+ async function performHttpResponse(input, init, consume, options) {
93094
+ const controller = new AbortController();
93095
+ const timeoutMs = options.timeoutMs ?? HTTP_DEADLINE_MS;
93096
+ const maxBytes = options.maxResponseBytes ?? HTTP_MAX_RESPONSE_BYTES;
93097
+ const mutation = !["GET", "HEAD"].includes((init.method ?? "GET").toUpperCase());
93098
+ const externalSignal = options.signal ?? init.signal ?? void 0;
93099
+ let acquired = false;
93100
+ let lease;
93101
+ let finished = false;
93102
+ let dispatched = false;
93103
+ let response;
93104
+ let limitedResponse;
93105
+ let stopError;
93106
+ let rejectStopped;
93107
+ const stopped = new Promise((_, reject) => {
93108
+ rejectStopped = reject;
93109
+ });
93110
+ const outcome = () => !dispatched ? "not-dispatched" : mutation ? "unknown" : "read-failed";
93111
+ const stop = (code) => {
93112
+ stopError = new HttpRequestError(
93113
+ code,
93114
+ code === "CLI_REQUEST_TIMEOUT" ? "The request timed out." : "The request was cancelled.",
93115
+ outcome(),
93116
+ response?.headers.get("x-request-id") ?? void 0
93117
+ );
93118
+ controller.abort(stopError);
93119
+ rejectStopped(stopError);
93120
+ };
93121
+ const cancel = () => stop("CLI_REQUEST_CANCELLED");
93122
+ externalSignal?.addEventListener("abort", cancel, { once: true });
93123
+ const timer = setTimeout(() => stop("CLI_REQUEST_TIMEOUT"), timeoutMs);
93124
+ const work = async () => {
93125
+ if (externalSignal?.aborted) cancel();
93126
+ controller.signal.throwIfAborted();
93127
+ if (options.localAdmission !== false) {
93128
+ lease = await acquire(controller.signal);
93129
+ acquired = true;
93130
+ if (finished || controller.signal.aborted) {
93131
+ acquired = false;
93132
+ await release(lease);
93133
+ controller.signal.throwIfAborted();
93134
+ }
93135
+ }
93136
+ controller.signal.throwIfAborted();
93137
+ dispatched = true;
93138
+ response = await fetch(input, { ...init, signal: controller.signal });
93139
+ controller.signal.throwIfAborted();
93140
+ const tooLarge = () => new HttpRequestError(
93141
+ "CLI_RESPONSE_TOO_LARGE",
93142
+ "The response exceeded the size limit. Request a smaller page or narrower range.",
93143
+ outcome(),
93144
+ response?.headers.get("x-request-id") ?? void 0
93145
+ );
93146
+ const declaredBytes = response.headers.get("content-length");
93147
+ if (declaredBytes && /^\d+$/.test(declaredBytes) && Number(declaredBytes) > Math.min(maxBytes, options.responseBudget?.remainingBytes ?? maxBytes)) throw tooLarge();
93148
+ let bytes = 0;
93149
+ const body = response.body?.pipeThrough(new TransformStream({
93150
+ transform(chunk, stream) {
93151
+ bytes += chunk.byteLength;
93152
+ if (options.responseBudget) options.responseBudget.remainingBytes -= chunk.byteLength;
93153
+ if (bytes > maxBytes || options.responseBudget && options.responseBudget.remainingBytes < 0) throw tooLarge();
93154
+ stream.enqueue(chunk);
93155
+ }
93156
+ }));
93157
+ limitedResponse = new Response(body ?? null, {
93158
+ status: response.status,
93159
+ statusText: response.statusText,
93160
+ headers: response.headers
93161
+ });
93162
+ return await consume(limitedResponse);
93163
+ };
93164
+ try {
93165
+ return await Promise.race([track(work()), stopped]);
93166
+ } catch (error) {
93167
+ if (stopError) throw stopError;
93168
+ if (error instanceof HttpRequestError) throw error;
93169
+ if (typeof error === "object" && error !== null && "_tag" in error) throw error;
93170
+ throw new HttpRequestError(
93171
+ error instanceof SyntaxError ? "CLI_RESPONSE_INVALID" : "CLI_REQUEST_FAILED",
93172
+ error instanceof SyntaxError ? "The server response was incomplete or invalid." : "The request could not be completed.",
93173
+ outcome(),
93174
+ response?.headers.get("x-request-id") ?? void 0
93175
+ );
93176
+ } finally {
93177
+ finished = true;
93178
+ clearTimeout(timer);
93179
+ externalSignal?.removeEventListener("abort", cancel);
93180
+ controller.abort();
93181
+ void limitedResponse?.body?.cancel().catch(() => {
93182
+ });
93183
+ void response?.body?.cancel().catch(() => {
94035
93184
  });
93185
+ if (acquired) await release(lease);
94036
93186
  }
94037
- return masked;
94038
93187
  }
94039
93188
 
94040
93189
  const CALLBACK_HOST = "127.0.0.1";
@@ -94054,13 +93203,18 @@ const CALLBACK_RESPONSE_HEADERS$1 = {
94054
93203
  Connection: "close"
94055
93204
  };
94056
93205
  class OAuthRequestError extends Error {
93206
+ _tag = "OAuthRequestError";
94057
93207
  statusCode;
94058
93208
  code;
94059
- constructor(message, statusCode, code) {
94060
- super(message);
93209
+ outcome;
93210
+ requestId;
93211
+ constructor(message, statusCode, code, diagnostics = {}) {
93212
+ super(maskSensitiveText(message) + (diagnostics.outcome === "unknown" ? " The server may have processed this request. Check your authentication state before running it again." : ""));
94061
93213
  this.name = "OAuthRequestError";
94062
93214
  this.statusCode = statusCode;
94063
- this.code = code;
93215
+ this.code = code ? maskSensitiveText(code).slice(0, 128) : void 0;
93216
+ this.outcome = diagnostics.outcome;
93217
+ this.requestId = diagnostics.requestId ? maskSensitiveText(diagnostics.requestId).slice(0, 128) : void 0;
94064
93218
  }
94065
93219
  }
94066
93220
  function generateState$1() {
@@ -94073,6 +93227,7 @@ function trimTrailingSlash(value) {
94073
93227
  return value.replace(/\/+$/, "");
94074
93228
  }
94075
93229
  function toError$1(error, fallbackMessage) {
93230
+ if (error instanceof OAuthRequestError) return error;
94076
93231
  return error instanceof Error ? new Error(maskSensitiveText(error.message)) : new Error(maskSensitiveText(fallbackMessage));
94077
93232
  }
94078
93233
  function isRecord(value) {
@@ -94102,39 +93257,49 @@ function parseOAuthTokenResponse(value) {
94102
93257
  scope: optionalString(value["scope"])
94103
93258
  };
94104
93259
  }
94105
- async function fetchJson(input, init) {
94106
- const abortController = new AbortController();
94107
- const abortTimeout = setTimeout(() => abortController.abort(), OAUTH_REQUEST_TIMEOUT_MS);
94108
- let response;
93260
+ async function fetchJson(input, init, parse = (value) => value) {
94109
93261
  try {
94110
- response = await fetch(input, { ...init, signal: abortController.signal });
93262
+ return await withHttpResponse(input, init ?? {}, async (response) => {
93263
+ if (!response.ok) {
93264
+ let errorData = {};
93265
+ try {
93266
+ errorData = await response.json();
93267
+ } catch (error) {
93268
+ if (error instanceof HttpRequestError) throw error;
93269
+ }
93270
+ const message = errorData.error_description ?? errorData.message ?? errorData.error ?? `HTTP ${response.status}: ${response.statusText}`;
93271
+ throw new OAuthRequestError(message, response.status, errorData.error ?? errorData.code, {
93272
+ requestId: response.headers.get("x-request-id") ?? void 0
93273
+ });
93274
+ }
93275
+ const value = await response.json();
93276
+ try {
93277
+ return parse(value);
93278
+ } catch (error) {
93279
+ if (!(error instanceof OAuthRequestError)) throw error;
93280
+ throw new OAuthRequestError(error.message, response.status, error.code, {
93281
+ outcome: ["GET", "HEAD"].includes((init?.method ?? "GET").toUpperCase()) ? "read-failed" : "unknown",
93282
+ requestId: response.headers.get("x-request-id") ?? void 0
93283
+ });
93284
+ }
93285
+ }, { timeoutMs: OAUTH_REQUEST_TIMEOUT_MS, localAdmission: false });
94111
93286
  } catch (error) {
94112
- if (abortController.signal.aborted) {
93287
+ if (error instanceof OAuthRequestError) throw error;
93288
+ if (error instanceof HttpRequestError && error.code === "CLI_REQUEST_TIMEOUT") {
94113
93289
  throw new OAuthRequestError(
94114
93290
  `OAuth request timed out after ${OAUTH_REQUEST_TIMEOUT_SECONDS} seconds`,
94115
93291
  void 0,
94116
- "timeout"
93292
+ "timeout",
93293
+ { outcome: error.outcome, requestId: error.requestId }
94117
93294
  );
94118
93295
  }
94119
93296
  throw new OAuthRequestError(
94120
93297
  error instanceof Error ? maskSensitiveText(error.message) : "OAuth request failed",
94121
93298
  void 0,
94122
- "request_failed"
93299
+ "request_failed",
93300
+ error instanceof HttpRequestError ? { outcome: error.outcome, requestId: error.requestId } : {}
94123
93301
  );
94124
- } finally {
94125
- clearTimeout(abortTimeout);
94126
- }
94127
- if (!response.ok) {
94128
- let errorData = {};
94129
- try {
94130
- errorData = await response.json();
94131
- } catch {
94132
- }
94133
- const message = errorData.error_description ?? errorData.message ?? errorData.error ?? `HTTP ${response.status}: ${response.statusText}`;
94134
- const code = errorData.error ?? errorData.code;
94135
- throw new OAuthRequestError(maskSensitiveText(message), response.status, code);
94136
93302
  }
94137
- return await response.json();
94138
93303
  }
94139
93304
  async function discoverOAuthMetadata(apiBaseUrl) {
94140
93305
  const normalizedBaseUrl = trimTrailingSlash(apiBaseUrl);
@@ -94161,7 +93326,7 @@ async function discoverOAuthMetadata(apiBaseUrl) {
94161
93326
  }
94162
93327
  }
94163
93328
  async function registerCliOAuthClient(metadata) {
94164
- const response = await fetchJson(metadata.registrationEndpoint, {
93329
+ return fetchJson(metadata.registrationEndpoint, {
94165
93330
  method: "POST",
94166
93331
  headers: {
94167
93332
  "Content-Type": "application/json"
@@ -94175,13 +93340,11 @@ async function registerCliOAuthClient(metadata) {
94175
93340
  token_endpoint_auth_method: "none",
94176
93341
  scope: OAUTH_SCOPE
94177
93342
  })
93343
+ }, (response) => {
93344
+ const clientId = isRecord(response) ? optionalString(response["client_id"]) : void 0;
93345
+ if (!clientId) throw new OAuthRequestError("OAuth client registration did not return client_id", void 0, "invalid_client_response");
93346
+ return { clientId };
94178
93347
  });
94179
- if (!response.client_id) {
94180
- throw new Error("OAuth client registration did not return client_id");
94181
- }
94182
- return {
94183
- clientId: response.client_id
94184
- };
94185
93348
  }
94186
93349
  function generatePkcePair() {
94187
93350
  const verifier = toBase64Url(crypto__namespace.randomBytes(64));
@@ -94222,14 +93385,13 @@ async function exchangeAuthorizationCode(input) {
94222
93385
  code: input.code,
94223
93386
  code_verifier: input.codeVerifier
94224
93387
  });
94225
- const response = await fetchJson(input.tokenEndpoint, {
93388
+ return fetchJson(input.tokenEndpoint, {
94226
93389
  method: "POST",
94227
93390
  headers: {
94228
93391
  "Content-Type": "application/x-www-form-urlencoded"
94229
93392
  },
94230
93393
  body
94231
- });
94232
- return parseOAuthTokenResponse(response);
93394
+ }, parseOAuthTokenResponse);
94233
93395
  }
94234
93396
  async function refreshOAuthToken(input) {
94235
93397
  const body = new URLSearchParams({
@@ -94237,14 +93399,13 @@ async function refreshOAuthToken(input) {
94237
93399
  client_id: input.clientId,
94238
93400
  refresh_token: input.refreshToken
94239
93401
  });
94240
- const response = await fetchJson(input.tokenEndpoint, {
93402
+ return fetchJson(input.tokenEndpoint, {
94241
93403
  method: "POST",
94242
93404
  headers: {
94243
93405
  "Content-Type": "application/x-www-form-urlencoded"
94244
93406
  },
94245
93407
  body
94246
- });
94247
- return parseOAuthTokenResponse(response);
93408
+ }, parseOAuthTokenResponse);
94248
93409
  }
94249
93410
  function tokenExpiresAt(now, expiresInSeconds, fallbackMs) {
94250
93411
  return now + (expiresInSeconds === void 0 ? fallbackMs : expiresInSeconds * 1e3);
@@ -94289,330 +93450,1159 @@ const OAUTH_RESULT_PAGE = {
94289
93450
  title: "Authentication successful",
94290
93451
  message: "You can close this window."
94291
93452
  },
94292
- error: {
94293
- title: "Authentication failed",
94294
- message: 'Check the terminal, then run "aipctl auth login" again.'
94295
- }
94296
- };
94297
- function buildOAuthResultHtml(variant) {
94298
- const { title, message } = OAUTH_RESULT_PAGE[variant];
94299
- return `
94300
- <!DOCTYPE html>
94301
- <html lang="en">
94302
- <head>
94303
- <meta charset="utf-8" />
94304
- <meta name="viewport" content="width=device-width, initial-scale=1" />
94305
- <title>${title}</title>
94306
- <style>
94307
- :root {
94308
- color-scheme: light dark;
94309
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
94310
- --background: #ffffff;
94311
- --foreground: #171717;
94312
- --muted-foreground: #737373;
94313
- background: var(--background);
94314
- color: var(--foreground);
94315
- }
94316
- @media (prefers-color-scheme: dark) {
94317
- :root {
94318
- --background: #171717;
94319
- --foreground: #fafafa;
94320
- --muted-foreground: #a3a3a3;
94321
- }
94322
- }
94323
- * { box-sizing: border-box; }
94324
- body {
94325
- margin: 0;
94326
- min-height: 100vh;
94327
- min-height: 100svh;
94328
- display: grid;
94329
- place-items: center;
94330
- padding: 24px;
94331
- background: var(--background);
94332
- color: var(--foreground);
94333
- }
94334
- main {
94335
- max-width: 48rem;
94336
- text-align: center;
94337
- }
94338
- h1 {
94339
- margin: 0;
94340
- font-size: clamp(1.75rem, 5vw, 2.5rem);
94341
- font-weight: 600;
94342
- line-height: 1.15;
94343
- letter-spacing: -0.03em;
94344
- }
94345
- p {
94346
- margin: 1rem 0 0;
94347
- color: var(--muted-foreground);
94348
- font-size: 1rem;
94349
- line-height: 1.6;
94350
- }
94351
- </style>
94352
- </head>
94353
- <body data-variant="${variant}">
94354
- <main aria-labelledby="result-title">
94355
- <h1 id="result-title">${title}</h1>
94356
- <p>${message}</p>
94357
- </main>
94358
- </body>
94359
- </html>
94360
- `;
94361
- }
94362
- const successHtml$1 = buildOAuthResultHtml("success");
94363
- const errorHtml$1 = buildOAuthResultHtml("error");
94364
- function createServerCloser$1(server) {
94365
- let closePromise;
94366
- return () => {
94367
- if (!closePromise) {
94368
- closePromise = new Promise((resolve) => {
94369
- if (!server.listening) {
94370
- resolve();
94371
- return;
94372
- }
94373
- let settled = false;
94374
- const finish = () => {
94375
- if (settled) {
94376
- return;
94377
- }
94378
- settled = true;
94379
- clearTimeout(forceCloseTimeout);
94380
- resolve();
94381
- };
94382
- const forceCloseTimeout = setTimeout(() => {
94383
- server.closeAllConnections?.();
94384
- finish();
94385
- }, CALLBACK_SERVER_CLOSE_TIMEOUT_MS$1);
94386
- server.close(finish);
94387
- server.closeIdleConnections?.();
94388
- });
94389
- }
94390
- return closePromise;
94391
- };
94392
- }
94393
- async function listenOnCallbackPort$1(server) {
94394
- await new Promise((resolve, reject) => {
94395
- let settled = false;
94396
- const onError = (error) => {
94397
- if (settled) {
94398
- return;
94399
- }
94400
- settled = true;
94401
- server.off("error", onError);
94402
- if (error.code === "EADDRINUSE") {
94403
- reject(new Error(CALLBACK_PORT_IN_USE_MESSAGE$1));
94404
- return;
94405
- }
94406
- reject(error);
94407
- };
94408
- server.on("error", onError);
94409
- server.listen(CALLBACK_PORT, CALLBACK_HOST, () => {
94410
- if (settled) {
94411
- return;
94412
- }
94413
- settled = true;
94414
- server.off("error", onError);
94415
- resolve();
94416
- });
94417
- });
94418
- }
94419
- const startOAuthFlow = gen(function* () {
94420
- const config = yield* ConfigService;
94421
- const credentials = yield* CredentialService;
94422
- const apiBaseUrl = yield* try_({
94423
- try: () => requireApiBaseUrl(config.load()),
94424
- catch: (error) => toError$1(error, "App URL validation failed")
94425
- });
94426
- const pkce = generatePkcePair();
94427
- const state = generateState$1();
94428
- const deferred = yield* make$m();
94429
- const server = Http__namespace.createServer((req, res) => {
94430
- const url = new URL(req.url || "/", CALLBACK_URL);
94431
- if (url.pathname !== CALLBACK_PATH) {
94432
- res.writeHead(404);
94433
- res.end("Not Found");
94434
- return;
94435
- }
94436
- try {
94437
- const callback = parseOAuthCallback(url.searchParams, state);
94438
- res.writeHead(200, CALLBACK_RESPONSE_HEADERS$1);
94439
- res.end(successHtml$1);
94440
- runSync(succeed$5(deferred, callback));
94441
- } catch (error) {
94442
- res.writeHead(400, CALLBACK_RESPONSE_HEADERS$1);
94443
- res.end(errorHtml$1);
94444
- runSync(fail$4(deferred, toError$1(error, "Authentication failed")));
94445
- } finally {
94446
- void closeServer();
94447
- }
94448
- });
94449
- const closeServer = createServerCloser$1(server);
94450
- yield* tryPromise({
94451
- try: () => listenOnCallbackPort$1(server),
94452
- catch: (error) => toError$1(error, "Failed to start OAuth callback server")
94453
- });
94454
- return yield* gen(function* () {
94455
- const metadata = yield* tryPromise({
94456
- try: () => discoverOAuthMetadata(apiBaseUrl),
94457
- catch: (error) => toError$1(error, "OAuth metadata discovery failed")
94458
- });
94459
- const registration = yield* tryPromise({
94460
- try: () => registerCliOAuthClient(metadata),
94461
- catch: (error) => toError$1(error, "OAuth client registration failed")
94462
- });
94463
- const authorizeUrl = buildAuthorizeUrl({
94464
- authorizationEndpoint: metadata.authorizationEndpoint,
94465
- clientId: registration.clientId,
94466
- state,
94467
- codeChallenge: pkce.challenge
94468
- });
94469
- yield* sync$1(() => {
94470
- console.log("Opening browser for login...");
94471
- console.log(`If browser doesn't open, visit: ${sanitizeOAuthAuthorizeUrlForDisplay(authorizeUrl)}`);
94472
- void open(authorizeUrl).catch(() => void 0);
94473
- });
94474
- const callback = yield* raceFirst(
94475
- _await(deferred),
94476
- sleep$1("5 minutes").pipe(flatMap$5(() => fail$3(new Error("Login timeout"))))
94477
- );
94478
- yield* sync$1(() => {
94479
- console.log("Authorization received. Exchanging token...");
94480
- });
94481
- const tokenResponse = yield* tryPromise({
94482
- try: () => exchangeAuthorizationCode({
94483
- tokenEndpoint: metadata.tokenEndpoint,
94484
- clientId: registration.clientId,
94485
- code: callback.code,
94486
- codeVerifier: pkce.verifier
94487
- }),
94488
- catch: (error) => toError$1(error, "OAuth token exchange failed")
94489
- });
94490
- const nextCredentials = toCredentialsFromTokenResponse({
94491
- tokenResponse,
94492
- clientId: registration.clientId,
94493
- issuer: metadata.issuer
94494
- });
94495
- credentials.save(nextCredentials);
94496
- return nextCredentials;
94497
- }).pipe(ensuring$1(promise$1(() => closeServer())));
94498
- });
94499
-
94500
- const MAX_CONCURRENCY = 3;
94501
- const MAX_RATE_REQUESTS = 10;
94502
- const RATE_WINDOW_MS = 5e3;
94503
- const POLL_INTERVAL_MS = 300;
94504
- const CONFIG_DIR = path__namespace.join(os__namespace.homedir(), ".config", "aip");
94505
- const STATE_FILE = path__namespace.join(CONFIG_DIR, "rate-limit.json");
94506
- function pruneOldRequests(recentRequests, now = Date.now()) {
94507
- return recentRequests.filter((ts) => now - new Date(ts).getTime() < RATE_WINDOW_MS);
94508
- }
94509
- function pruneDeadSlots(slots) {
94510
- return slots.filter((slot) => {
94511
- try {
94512
- process.kill(slot.pid, 0);
94513
- return true;
94514
- } catch {
94515
- return false;
94516
- }
94517
- });
94518
- }
94519
- function getRateLimitWaitMs(recentRequests, now = Date.now()) {
94520
- const active = pruneOldRequests(recentRequests, now);
94521
- if (active.length < MAX_RATE_REQUESTS) return 0;
94522
- const oldestMs = Math.min(...active.map((ts) => new Date(ts).getTime()));
94523
- return oldestMs + RATE_WINDOW_MS - now;
94524
- }
94525
- function ensureConfigDir() {
94526
- fs__namespace.mkdirSync(CONFIG_DIR, { recursive: true });
94527
- }
94528
- function readState() {
94529
- try {
94530
- const raw = fs__namespace.readFileSync(STATE_FILE, "utf-8");
94531
- return JSON.parse(raw);
94532
- } catch {
94533
- return { slots: [], recentRequests: [] };
94534
- }
94535
- }
94536
- function writeState(state) {
94537
- fs__namespace.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
94538
- }
94539
- async function withLock(fn) {
94540
- ensureConfigDir();
94541
- if (!fs__namespace.existsSync(STATE_FILE)) {
94542
- writeState({ slots: [], recentRequests: [] });
94543
- }
94544
- const release2 = await lockfile.lock(STATE_FILE, {
94545
- retries: { retries: 20, minTimeout: 50, maxTimeout: 200 },
94546
- stale: 5e3
94547
- });
94548
- try {
94549
- return fn();
94550
- } finally {
94551
- await release2();
94552
- }
94553
- }
94554
- async function release() {
94555
- try {
94556
- await withLock(() => {
94557
- const state = readState();
94558
- state.slots = state.slots.filter((s) => s.pid !== process.pid);
94559
- writeState(state);
94560
- });
94561
- } catch {
94562
- process.stderr.write("\n[Rate limit] \uC2AC\uB86F \uBC18\uB0A9 \uC2E4\uD328. \uB2E4\uC74C \uC694\uCCAD \uC2DC \uC790\uB3D9\uC73C\uB85C \uC815\uB9AC\uB429\uB2C8\uB2E4.\n");
94563
- }
94564
- }
94565
- async function acquire() {
94566
- let waitStart = null;
94567
- while (true) {
94568
- let concurrencyFull = false;
94569
- let rateLimitWaitMs = 0;
94570
- try {
94571
- await withLock(() => {
94572
- const state = readState();
94573
- state.slots = pruneDeadSlots(state.slots);
94574
- const now = Date.now();
94575
- state.recentRequests = pruneOldRequests(state.recentRequests, now);
94576
- if (state.slots.length >= MAX_CONCURRENCY) {
94577
- concurrencyFull = true;
94578
- writeState(state);
94579
- return;
94580
- }
94581
- rateLimitWaitMs = getRateLimitWaitMs(state.recentRequests, now);
94582
- if (rateLimitWaitMs > 0) {
94583
- writeState(state);
94584
- return;
94585
- }
94586
- state.slots.push({ pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString() });
94587
- state.recentRequests.push((/* @__PURE__ */ new Date()).toISOString());
94588
- writeState(state);
94589
- });
94590
- } catch {
94591
- process.stderr.write("\n[Rate limit] \uB77D \uD68D\uB4DD \uC2E4\uD328. \uC7A0\uC2DC \uD6C4 \uC7AC\uC2DC\uB3C4\uD569\uB2C8\uB2E4...\n");
94592
- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
94593
- continue;
94594
- }
94595
- if (!concurrencyFull && rateLimitWaitMs === 0) {
94596
- if (waitStart !== null) {
94597
- process.stderr.write("\r" + " ".repeat(80) + "\r");
94598
- }
94599
- return;
94600
- }
94601
- if (waitStart === null) waitStart = Date.now();
94602
- const elapsed = Math.floor((Date.now() - waitStart) / 1e3);
94603
- if (concurrencyFull) {
94604
- process.stderr.write(
94605
- `\r[Rate limit] \uB3D9\uC2DC \uC2E4\uD589: ${MAX_CONCURRENCY}/${MAX_CONCURRENCY} | \uC2AC\uB86F \uB300\uAE30 \uC911... (${elapsed}\uCD08 \uACBD\uACFC)`
94606
- );
94607
- } else if (rateLimitWaitMs > 0) {
94608
- const remainSec = Math.ceil(rateLimitWaitMs / 1e3);
94609
- process.stderr.write(
94610
- `\r[Rate limit] \uC694\uCCAD \uD55C\uB3C4 \uCD08\uACFC (${MAX_RATE_REQUESTS}/${RATE_WINDOW_MS / 1e3}\uCD08) | ${remainSec}\uCD08 \uD6C4 \uC7AC\uC2DC\uB3C4...`
94611
- );
94612
- }
94613
- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
94614
- }
94615
- }
93453
+ error: {
93454
+ title: "Authentication failed",
93455
+ message: 'Check the terminal, then run "aipctl auth login" again.'
93456
+ }
93457
+ };
93458
+ function buildOAuthResultHtml(variant) {
93459
+ const { title, message } = OAUTH_RESULT_PAGE[variant];
93460
+ return `
93461
+ <!DOCTYPE html>
93462
+ <html lang="en">
93463
+ <head>
93464
+ <meta charset="utf-8" />
93465
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
93466
+ <title>${title}</title>
93467
+ <style>
93468
+ :root {
93469
+ color-scheme: light dark;
93470
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
93471
+ --background: #ffffff;
93472
+ --foreground: #171717;
93473
+ --muted-foreground: #737373;
93474
+ background: var(--background);
93475
+ color: var(--foreground);
93476
+ }
93477
+ @media (prefers-color-scheme: dark) {
93478
+ :root {
93479
+ --background: #171717;
93480
+ --foreground: #fafafa;
93481
+ --muted-foreground: #a3a3a3;
93482
+ }
93483
+ }
93484
+ * { box-sizing: border-box; }
93485
+ body {
93486
+ margin: 0;
93487
+ min-height: 100vh;
93488
+ min-height: 100svh;
93489
+ display: grid;
93490
+ place-items: center;
93491
+ padding: 24px;
93492
+ background: var(--background);
93493
+ color: var(--foreground);
93494
+ }
93495
+ main {
93496
+ max-width: 48rem;
93497
+ text-align: center;
93498
+ }
93499
+ h1 {
93500
+ margin: 0;
93501
+ font-size: clamp(1.75rem, 5vw, 2.5rem);
93502
+ font-weight: 600;
93503
+ line-height: 1.15;
93504
+ letter-spacing: -0.03em;
93505
+ }
93506
+ p {
93507
+ margin: 1rem 0 0;
93508
+ color: var(--muted-foreground);
93509
+ font-size: 1rem;
93510
+ line-height: 1.6;
93511
+ }
93512
+ </style>
93513
+ </head>
93514
+ <body data-variant="${variant}">
93515
+ <main aria-labelledby="result-title">
93516
+ <h1 id="result-title">${title}</h1>
93517
+ <p>${message}</p>
93518
+ </main>
93519
+ </body>
93520
+ </html>
93521
+ `;
93522
+ }
93523
+ const successHtml$1 = buildOAuthResultHtml("success");
93524
+ const errorHtml$1 = buildOAuthResultHtml("error");
93525
+ function createServerCloser$1(server) {
93526
+ let closePromise;
93527
+ return () => {
93528
+ if (!closePromise) {
93529
+ closePromise = new Promise((resolve) => {
93530
+ if (!server.listening) {
93531
+ resolve();
93532
+ return;
93533
+ }
93534
+ let settled = false;
93535
+ const finish = () => {
93536
+ if (settled) {
93537
+ return;
93538
+ }
93539
+ settled = true;
93540
+ clearTimeout(forceCloseTimeout);
93541
+ resolve();
93542
+ };
93543
+ const forceCloseTimeout = setTimeout(() => {
93544
+ server.closeAllConnections?.();
93545
+ finish();
93546
+ }, CALLBACK_SERVER_CLOSE_TIMEOUT_MS$1);
93547
+ server.close(finish);
93548
+ server.closeIdleConnections?.();
93549
+ });
93550
+ }
93551
+ return closePromise;
93552
+ };
93553
+ }
93554
+ async function listenOnCallbackPort$1(server) {
93555
+ await new Promise((resolve, reject) => {
93556
+ let settled = false;
93557
+ const onError = (error) => {
93558
+ if (settled) {
93559
+ return;
93560
+ }
93561
+ settled = true;
93562
+ server.off("error", onError);
93563
+ if (error.code === "EADDRINUSE") {
93564
+ reject(new Error(CALLBACK_PORT_IN_USE_MESSAGE$1));
93565
+ return;
93566
+ }
93567
+ reject(error);
93568
+ };
93569
+ server.on("error", onError);
93570
+ server.listen(CALLBACK_PORT, CALLBACK_HOST, () => {
93571
+ if (settled) {
93572
+ return;
93573
+ }
93574
+ settled = true;
93575
+ server.off("error", onError);
93576
+ resolve();
93577
+ });
93578
+ });
93579
+ }
93580
+ const startOAuthFlow = gen(function* () {
93581
+ const config = yield* ConfigService;
93582
+ const credentials = yield* CredentialService;
93583
+ const apiBaseUrl = yield* try_({
93584
+ try: () => requireApiBaseUrl(config.load()),
93585
+ catch: (error) => toError$1(error, "App URL validation failed")
93586
+ });
93587
+ const pkce = generatePkcePair();
93588
+ const state = generateState$1();
93589
+ const deferred = yield* make$m();
93590
+ const server = Http__namespace.createServer((req, res) => {
93591
+ const url = new URL(req.url || "/", CALLBACK_URL);
93592
+ if (url.pathname !== CALLBACK_PATH) {
93593
+ res.writeHead(404);
93594
+ res.end("Not Found");
93595
+ return;
93596
+ }
93597
+ try {
93598
+ const callback = parseOAuthCallback(url.searchParams, state);
93599
+ res.writeHead(200, CALLBACK_RESPONSE_HEADERS$1);
93600
+ res.end(successHtml$1);
93601
+ runSync(succeed$5(deferred, callback));
93602
+ } catch (error) {
93603
+ res.writeHead(400, CALLBACK_RESPONSE_HEADERS$1);
93604
+ res.end(errorHtml$1);
93605
+ runSync(fail$4(deferred, toError$1(error, "Authentication failed")));
93606
+ } finally {
93607
+ void closeServer();
93608
+ }
93609
+ });
93610
+ const closeServer = createServerCloser$1(server);
93611
+ yield* tryPromise({
93612
+ try: () => listenOnCallbackPort$1(server),
93613
+ catch: (error) => toError$1(error, "Failed to start OAuth callback server")
93614
+ });
93615
+ return yield* gen(function* () {
93616
+ const metadata = yield* tryPromise({
93617
+ try: () => discoverOAuthMetadata(apiBaseUrl),
93618
+ catch: (error) => toError$1(error, "OAuth metadata discovery failed")
93619
+ });
93620
+ const registration = yield* tryPromise({
93621
+ try: () => registerCliOAuthClient(metadata),
93622
+ catch: (error) => toError$1(error, "OAuth client registration failed")
93623
+ });
93624
+ const authorizeUrl = buildAuthorizeUrl({
93625
+ authorizationEndpoint: metadata.authorizationEndpoint,
93626
+ clientId: registration.clientId,
93627
+ state,
93628
+ codeChallenge: pkce.challenge
93629
+ });
93630
+ yield* sync$1(() => {
93631
+ console.log("Opening browser for login...");
93632
+ console.log(`If browser doesn't open, visit: ${sanitizeOAuthAuthorizeUrlForDisplay(authorizeUrl)}`);
93633
+ void open(authorizeUrl).catch(() => void 0);
93634
+ });
93635
+ const callback = yield* raceFirst(
93636
+ _await(deferred),
93637
+ sleep$1("5 minutes").pipe(flatMap$5(() => fail$3(new Error("Login timeout"))))
93638
+ );
93639
+ yield* sync$1(() => {
93640
+ console.log("Authorization received. Exchanging token...");
93641
+ });
93642
+ const tokenResponse = yield* tryPromise({
93643
+ try: () => exchangeAuthorizationCode({
93644
+ tokenEndpoint: metadata.tokenEndpoint,
93645
+ clientId: registration.clientId,
93646
+ code: callback.code,
93647
+ codeVerifier: pkce.verifier
93648
+ }),
93649
+ catch: (error) => toError$1(error, "OAuth token exchange failed")
93650
+ });
93651
+ const nextCredentials = toCredentialsFromTokenResponse({
93652
+ tokenResponse,
93653
+ clientId: registration.clientId,
93654
+ issuer: metadata.issuer
93655
+ });
93656
+ credentials.save(nextCredentials);
93657
+ return nextCredentials;
93658
+ }).pipe(ensuring$1(promise$1(() => closeServer())));
93659
+ });
93660
+
93661
+ const BUILD_ENVS = ["local", "dev", "qa", "stage", "prod", "test"];
93662
+ const isBuildEnv = (value) => BUILD_ENVS.includes(value);
93663
+
93664
+ const injectedBuildEnv = "dev".length > 0 ? "dev" : "local";
93665
+ if (!isBuildEnv(injectedBuildEnv)) {
93666
+ throw new Error(`Invalid AIPCTL_BUILD_ENV: ${injectedBuildEnv}`);
93667
+ }
93668
+ const VERSION = "2026.10.4".length > 0 ? "2026.10.4" : "0.0.0";
93669
+ const BUILD_ENV = injectedBuildEnv;
93670
+ const INCLUDE_NATIVE_LOGS = BUILD_ENV !== "prod";
93671
+
93672
+ function parseMyCliQuota(value) {
93673
+ const invalid = () => new HttpRequestError("CLI_RESPONSE_INVALID", "The quota response was invalid. Available capacity is unknown.", "read-failed");
93674
+ const object = (item) => {
93675
+ if (!item || typeof item !== "object" || Array.isArray(item)) throw invalid();
93676
+ return item;
93677
+ };
93678
+ const integer = (item) => {
93679
+ if (typeof item !== "number" || !Number.isSafeInteger(item) || item < 0) throw invalid();
93680
+ return item;
93681
+ };
93682
+ const nullableInteger = (item) => item === null ? null : integer(item);
93683
+ const source = object(value);
93684
+ const limits = (item) => {
93685
+ const fields = object(item);
93686
+ return {
93687
+ metadataRequestsPerMinute: integer(fields["metadataRequestsPerMinute"]),
93688
+ metadataRequestBurst: integer(fields["metadataRequestBurst"]),
93689
+ textRequestsPerMinute: integer(fields["textRequestsPerMinute"]),
93690
+ textRequestBurst: integer(fields["textRequestBurst"]),
93691
+ concurrentTextExecutions: integer(fields["concurrentTextExecutions"])
93692
+ };
93693
+ };
93694
+ const usage = object(source["usage"]);
93695
+ const status = usage["status"];
93696
+ if (status !== "AVAILABLE" && status !== "UNAVAILABLE") throw invalid();
93697
+ const reset = usage["dailyResetAt"];
93698
+ if (reset !== null && (typeof reset !== "string" || !Number.isFinite(Date.parse(reset)))) throw invalid();
93699
+ const parsedUsage = {
93700
+ status,
93701
+ dailyTextAdmissionsUsed: nullableInteger(usage["dailyTextAdmissionsUsed"]),
93702
+ activeTextExecutions: nullableInteger(usage["activeTextExecutions"]),
93703
+ unresolvedTextExecutions: nullableInteger(usage["unresolvedTextExecutions"]),
93704
+ dailyResetAt: reset
93705
+ };
93706
+ const counters = [parsedUsage.dailyTextAdmissionsUsed, parsedUsage.activeTextExecutions, parsedUsage.unresolvedTextExecutions, reset];
93707
+ if (status === "UNAVAILABLE" ? counters.some((item) => item !== null) : counters.some((item) => item === null)) throw invalid();
93708
+ if (parsedUsage.unresolvedTextExecutions !== null && parsedUsage.activeTextExecutions !== null && parsedUsage.unresolvedTextExecutions > parsedUsage.activeTextExecutions) throw invalid();
93709
+ return {
93710
+ userLimits: { ...limits(source["userLimits"]), dailyTextAdmissions: integer(object(source["userLimits"])["dailyTextAdmissions"]) },
93711
+ organizationSharedLimits: limits(source["organizationSharedLimits"]),
93712
+ organizationPolicyVersion: nullableInteger(source["organizationPolicyVersion"]),
93713
+ userPolicyVersion: nullableInteger(source["userPolicyVersion"]),
93714
+ usage: parsedUsage
93715
+ };
93716
+ }
93717
+
93718
+ const implementedCommandOperationIds = /* @__PURE__ */ new Set([
93719
+ "getCliMyQuota",
93720
+ "listCliAgents",
93721
+ "getCliAgent",
93722
+ "listCliAgentTemplates",
93723
+ "createCliAgent",
93724
+ "updateCliAgent",
93725
+ "deleteCliAgent",
93726
+ "updateCliAgentStatus",
93727
+ "getCliAgentShare",
93728
+ "getCliMe",
93729
+ "getCliUserSettings",
93730
+ "listCliOrganizations",
93731
+ "getCliOrganizationCapabilities",
93732
+ "listCliOrganizationMembers",
93733
+ "listCliModels",
93734
+ "listCliModelExecModels",
93735
+ "createCliModelChatExecution",
93736
+ "listCliSkills",
93737
+ "getCliSkill",
93738
+ "deleteCliSkill",
93739
+ "listCliSkillLibrary",
93740
+ "createCliSkillClones",
93741
+ "listCliBuiltInSkills",
93742
+ "createCliBuiltInSkillClones",
93743
+ "listCliAdminSkills",
93744
+ "getCliAdminSkill",
93745
+ "deleteCliAdminSkill",
93746
+ "updateCliAdminSkill",
93747
+ "listCliAdminBuiltInSkills",
93748
+ "createCliAdminBuiltInSkillClones",
93749
+ "listCliDriveEntries",
93750
+ "getCliDriveUsage",
93751
+ "createCliDriveFolder",
93752
+ "updateCliDriveEntryName",
93753
+ "deleteCliDriveEntries",
93754
+ "listCliChats",
93755
+ "getCliChat",
93756
+ "listCliChatMessages",
93757
+ "listCliIntegrations",
93758
+ "listCliAvailableIntegrations",
93759
+ "getCliAdminIntegration",
93760
+ "listCliIntegrationTools",
93761
+ "listCliAutomations",
93762
+ "getCliAutomation",
93763
+ "listCliAutomationTriggers",
93764
+ "listCliAutomationHistory",
93765
+ "createCliAutomation",
93766
+ "updateCliAutomation",
93767
+ "deleteCliAutomation",
93768
+ "updateCliAutomationStatus",
93769
+ "getCliCreditUsage",
93770
+ "listCliTopUsers",
93771
+ "getCliDailyUsageGraph",
93772
+ "listCliDailyUsers",
93773
+ "listCliTopMcpTools",
93774
+ "listCliAuditLogs",
93775
+ "listCliAuditEventTypes",
93776
+ "listCliPresets",
93777
+ "getCliPreset",
93778
+ "createCliPreset",
93779
+ "updateCliPreset",
93780
+ "updateCliPresetName",
93781
+ "deleteCliPreset",
93782
+ "updateCliDefaultPreset",
93783
+ "deleteCliDefaultPreset",
93784
+ "createCliOrganizationMemberInvitations",
93785
+ "deleteCliOrganizationMembers",
93786
+ "updateCliOrganizationMemberRoles",
93787
+ "deleteCliOrganizationMembership",
93788
+ "getCliTunnelStatus"
93789
+ ]);
93790
+ const releaseEnabledCommandOperationIds = /* @__PURE__ */ new Set([
93791
+ "getCliMyQuota",
93792
+ "listCliAgents",
93793
+ "getCliAgent",
93794
+ "listCliAgentTemplates",
93795
+ "createCliAgent",
93796
+ "updateCliAgent",
93797
+ "deleteCliAgent",
93798
+ "updateCliAgentStatus",
93799
+ "getCliAgentShare",
93800
+ "getCliMe",
93801
+ "getCliUserSettings",
93802
+ "listCliOrganizations",
93803
+ "getCliOrganizationCapabilities",
93804
+ "listCliOrganizationMembers",
93805
+ "listCliModels",
93806
+ "listCliModelExecModels",
93807
+ "listCliSkills",
93808
+ "getCliSkill",
93809
+ "deleteCliSkill",
93810
+ "listCliSkillLibrary",
93811
+ "createCliSkillClones",
93812
+ "listCliBuiltInSkills",
93813
+ "createCliBuiltInSkillClones",
93814
+ "listCliAdminSkills",
93815
+ "getCliAdminSkill",
93816
+ "deleteCliAdminSkill",
93817
+ "updateCliAdminSkill",
93818
+ "listCliAdminBuiltInSkills",
93819
+ "createCliAdminBuiltInSkillClones",
93820
+ "listCliDriveEntries",
93821
+ "getCliDriveUsage",
93822
+ "createCliDriveFolder",
93823
+ "updateCliDriveEntryName",
93824
+ "deleteCliDriveEntries",
93825
+ "listCliChats",
93826
+ "getCliChat",
93827
+ "listCliChatMessages",
93828
+ "listCliIntegrations",
93829
+ "listCliAvailableIntegrations",
93830
+ "getCliAdminIntegration",
93831
+ "listCliIntegrationTools",
93832
+ "listCliAutomations",
93833
+ "getCliAutomation",
93834
+ "listCliAutomationTriggers",
93835
+ "listCliAutomationHistory",
93836
+ "createCliAutomation",
93837
+ "updateCliAutomation",
93838
+ "deleteCliAutomation",
93839
+ "updateCliAutomationStatus",
93840
+ "getCliCreditUsage",
93841
+ "listCliTopUsers",
93842
+ "getCliDailyUsageGraph",
93843
+ "listCliDailyUsers",
93844
+ "listCliTopMcpTools",
93845
+ "listCliAuditLogs",
93846
+ "listCliAuditEventTypes",
93847
+ "listCliPresets",
93848
+ "getCliPreset",
93849
+ "createCliPreset",
93850
+ "updateCliPreset",
93851
+ "updateCliPresetName",
93852
+ "deleteCliPreset",
93853
+ "updateCliDefaultPreset",
93854
+ "deleteCliDefaultPreset",
93855
+ "createCliOrganizationMemberInvitations",
93856
+ "deleteCliOrganizationMembers",
93857
+ "updateCliOrganizationMemberRoles",
93858
+ "deleteCliOrganizationMembership",
93859
+ "getCliTunnelStatus"
93860
+ ]);
93861
+ const direct = (commands, operation) => commands.map((command) => ({
93862
+ command,
93863
+ tier: "GA_DIRECT",
93864
+ availability: !implementedCommandOperationIds.has(operation.operationId ?? "") ? "PLANNED" : releaseEnabledCommandOperationIds.has(operation.operationId ?? "") ? "IMPLEMENTED" : "GATED",
93865
+ ...operation
93866
+ }));
93867
+ const candidate = (commands, owner, authBoundary, requiredGates) => commands.map((command) => ({
93868
+ command,
93869
+ tier: "GA_CANDIDATE",
93870
+ owner,
93871
+ authBoundary,
93872
+ quotaClass: "endpoint-guard",
93873
+ availability: "GATED",
93874
+ capability: `cli.${command.replaceAll(" ", ".")}`,
93875
+ requiredGates
93876
+ }));
93877
+ const fixedBoundary = (commands, tier, owner, authBoundary) => commands.map((command) => ({
93878
+ command,
93879
+ tier,
93880
+ owner,
93881
+ authBoundary,
93882
+ quotaClass: "none",
93883
+ availability: tier === "INTERNAL_HIDDEN" ? "HIDDEN" : "AVAILABLE"
93884
+ }));
93885
+ const orgPath = "/api/cli/v1/organizations/{organizationSlug}";
93886
+ const commandManifest = [
93887
+ ...direct(["quota status"], {
93888
+ owner: "backend",
93889
+ authBoundary: "organization-oauth",
93890
+ quotaClass: "control-read",
93891
+ endpoint: { method: "GET", path: `${orgPath}/quota` },
93892
+ operationId: "getCliMyQuota",
93893
+ canonicalOperation: "cli.quota.self.read",
93894
+ capability: "cli.quota.self"
93895
+ }),
93896
+ ...direct(["auth whoami"], {
93897
+ owner: "backend",
93898
+ authBoundary: "user-oauth",
93899
+ quotaClass: "bootstrap",
93900
+ endpoint: { method: "GET", path: "/api/cli/v1/me" },
93901
+ operationId: "getCliMe",
93902
+ canonicalOperation: "cli.identity.me.read",
93903
+ capability: "cli.identity.me"
93904
+ }),
93905
+ ...direct(["org list", "org use", "org select"], {
93906
+ owner: "backend",
93907
+ authBoundary: "user-oauth",
93908
+ quotaClass: "bootstrap",
93909
+ endpoint: { method: "GET", path: "/api/cli/v1/organizations" },
93910
+ operationId: "listCliOrganizations",
93911
+ canonicalOperation: "cli.organization.list",
93912
+ capability: "cli.organization.discovery"
93913
+ }),
93914
+ ...direct(["org capabilities"], {
93915
+ owner: "backend",
93916
+ authBoundary: "organization-oauth",
93917
+ quotaClass: "metadata",
93918
+ endpoint: { method: "GET", path: `${orgPath}/capabilities` },
93919
+ operationId: "getCliOrganizationCapabilities",
93920
+ canonicalOperation: "cli.organization.capabilities.read",
93921
+ capability: "cli.organization.capabilities"
93922
+ }),
93923
+ ...direct(["org settings"], {
93924
+ owner: "backend",
93925
+ authBoundary: "user-oauth",
93926
+ quotaClass: "bootstrap",
93927
+ endpoint: { method: "GET", path: "/api/cli/v1/me/settings" },
93928
+ operationId: "getCliUserSettings",
93929
+ canonicalOperation: "cli.user.settings.read",
93930
+ capability: "cli.user.settings"
93931
+ }),
93932
+ ...direct(["org members"], {
93933
+ owner: "backend",
93934
+ authBoundary: "organization-oauth",
93935
+ quotaClass: "metadata",
93936
+ endpoint: { method: "GET", path: `${orgPath}/members` },
93937
+ operationId: "listCliOrganizationMembers",
93938
+ canonicalOperation: "cli.organization.members.list",
93939
+ capability: "cli.organization.members.read"
93940
+ }),
93941
+ ...direct(["org exit"], {
93942
+ owner: "backend",
93943
+ authBoundary: "organization-oauth",
93944
+ quotaClass: "metadata",
93945
+ endpoint: { method: "DELETE", path: `${orgPath}/membership` },
93946
+ operationId: "deleteCliOrganizationMembership",
93947
+ canonicalOperation: "cli.organization.membership.exit",
93948
+ capability: "cli.organization.exit"
93949
+ }),
93950
+ ...direct(["admin org invite"], {
93951
+ owner: "backend",
93952
+ authBoundary: "organization-oauth",
93953
+ quotaClass: "metadata",
93954
+ endpoint: { method: "POST", path: `${orgPath}/members/invitations` },
93955
+ operationId: "createCliOrganizationMemberInvitations",
93956
+ canonicalOperation: "cli.organization.members.invite",
93957
+ capability: "cli.organization.members.write"
93958
+ }),
93959
+ ...direct(["admin org remove-member"], {
93960
+ owner: "backend",
93961
+ authBoundary: "organization-oauth",
93962
+ quotaClass: "metadata",
93963
+ endpoint: { method: "DELETE", path: `${orgPath}/members` },
93964
+ operationId: "deleteCliOrganizationMembers",
93965
+ canonicalOperation: "cli.organization.members.remove",
93966
+ capability: "cli.organization.members.write"
93967
+ }),
93968
+ ...direct(["admin org update-member-role"], {
93969
+ owner: "backend",
93970
+ authBoundary: "organization-oauth",
93971
+ quotaClass: "metadata",
93972
+ endpoint: { method: "PUT", path: `${orgPath}/members/role` },
93973
+ operationId: "updateCliOrganizationMemberRoles",
93974
+ canonicalOperation: "cli.organization.members.role.update",
93975
+ capability: "cli.organization.members.write"
93976
+ }),
93977
+ ...direct(["model list"], {
93978
+ owner: "chat",
93979
+ authBoundary: "organization-oauth",
93980
+ quotaClass: "metadata",
93981
+ endpoint: { method: "GET", path: `${orgPath}/models` },
93982
+ operationId: "listCliModels",
93983
+ canonicalOperation: "cli.model.catalog.read",
93984
+ capability: "cli.model.catalog"
93985
+ }),
93986
+ ...direct(["model-exec models", "model-exec get", "model-exec sample"], {
93987
+ owner: "chat",
93988
+ authBoundary: "organization-oauth",
93989
+ quotaClass: "metadata",
93990
+ endpoint: { method: "GET", path: `${orgPath}/model-exec/models` },
93991
+ operationId: "listCliModelExecModels",
93992
+ canonicalOperation: "cli.model.catalog.read",
93993
+ capability: "cli.model.catalog"
93994
+ }),
93995
+ ...direct(["model-exec chat"], {
93996
+ owner: "chat",
93997
+ authBoundary: "organization-oauth",
93998
+ quotaClass: "text-execution",
93999
+ endpoint: { method: "POST", path: `${orgPath}/model-exec/chat` },
94000
+ operationId: "createCliModelChatExecution",
94001
+ canonicalOperation: "cli.model.text.execute",
94002
+ capability: "cli.model.text.execute"
94003
+ }),
94004
+ ...direct(["agent list"], {
94005
+ owner: "backend",
94006
+ authBoundary: "organization-oauth",
94007
+ quotaClass: "metadata",
94008
+ endpoint: { method: "GET", path: `${orgPath}/agents` },
94009
+ operationId: "listCliAgents",
94010
+ canonicalOperation: "cli.agent.list",
94011
+ capability: "cli.agent.read"
94012
+ }),
94013
+ ...direct(["agent get"], {
94014
+ owner: "backend",
94015
+ authBoundary: "organization-oauth",
94016
+ quotaClass: "metadata",
94017
+ endpoint: { method: "GET", path: `${orgPath}/agents/{installedAgentId}` },
94018
+ operationId: "getCliAgent",
94019
+ canonicalOperation: "cli.agent.get",
94020
+ capability: "cli.agent.read"
94021
+ }),
94022
+ ...direct(["agent enable", "agent disable"], {
94023
+ owner: "backend",
94024
+ authBoundary: "organization-oauth",
94025
+ quotaClass: "metadata",
94026
+ endpoint: { method: "PATCH", path: `${orgPath}/agents/{installedAgentId}/status` },
94027
+ operationId: "updateCliAgentStatus",
94028
+ canonicalOperation: "cli.agent.status.update",
94029
+ capability: "cli.agent.write"
94030
+ }),
94031
+ ...direct(["admin agent templates"], {
94032
+ owner: "backend",
94033
+ authBoundary: "organization-oauth",
94034
+ quotaClass: "metadata",
94035
+ endpoint: { method: "GET", path: `${orgPath}/agents/templates` },
94036
+ operationId: "listCliAgentTemplates",
94037
+ canonicalOperation: "cli.agent.templates.list",
94038
+ capability: "cli.agent.read"
94039
+ }),
94040
+ ...direct(["admin agent create"], {
94041
+ owner: "backend",
94042
+ authBoundary: "organization-oauth",
94043
+ quotaClass: "metadata",
94044
+ endpoint: { method: "POST", path: `${orgPath}/agents` },
94045
+ operationId: "createCliAgent",
94046
+ canonicalOperation: "cli.agent.create",
94047
+ capability: "cli.agent.write"
94048
+ }),
94049
+ ...direct(["admin agent update"], {
94050
+ owner: "backend",
94051
+ authBoundary: "organization-oauth",
94052
+ quotaClass: "metadata",
94053
+ endpoint: { method: "PATCH", path: `${orgPath}/agents/{installedAgentId}` },
94054
+ operationId: "updateCliAgent",
94055
+ canonicalOperation: "cli.agent.update",
94056
+ capability: "cli.agent.write"
94057
+ }),
94058
+ ...direct(["admin agent delete"], {
94059
+ owner: "backend",
94060
+ authBoundary: "organization-oauth",
94061
+ quotaClass: "metadata",
94062
+ endpoint: { method: "DELETE", path: `${orgPath}/agents/{installedAgentId}` },
94063
+ operationId: "deleteCliAgent",
94064
+ canonicalOperation: "cli.agent.delete",
94065
+ capability: "cli.agent.write"
94066
+ }),
94067
+ ...direct(["admin agent share"], {
94068
+ owner: "backend",
94069
+ authBoundary: "organization-oauth",
94070
+ quotaClass: "metadata",
94071
+ endpoint: { method: "GET", path: `${orgPath}/agents/{installedAgentId}/share` },
94072
+ operationId: "getCliAgentShare",
94073
+ canonicalOperation: "cli.agent.share.read",
94074
+ capability: "cli.agent.read"
94075
+ }),
94076
+ ...direct(["skill list"], {
94077
+ owner: "backend",
94078
+ authBoundary: "organization-oauth",
94079
+ quotaClass: "metadata",
94080
+ endpoint: { method: "GET", path: `${orgPath}/skills` },
94081
+ operationId: "listCliSkills",
94082
+ canonicalOperation: "cli.skill.list",
94083
+ capability: "cli.skill.read"
94084
+ }),
94085
+ ...direct(["skill get"], {
94086
+ owner: "backend",
94087
+ authBoundary: "organization-oauth",
94088
+ quotaClass: "metadata",
94089
+ endpoint: { method: "GET", path: `${orgPath}/skills/{skillId}` },
94090
+ operationId: "getCliSkill",
94091
+ canonicalOperation: "cli.skill.get",
94092
+ capability: "cli.skill.read"
94093
+ }),
94094
+ ...direct(["skill delete"], {
94095
+ owner: "backend",
94096
+ authBoundary: "organization-oauth",
94097
+ quotaClass: "metadata",
94098
+ endpoint: { method: "DELETE", path: `${orgPath}/skills/{skillId}` },
94099
+ operationId: "deleteCliSkill",
94100
+ canonicalOperation: "cli.skill.delete",
94101
+ capability: "cli.skill.write"
94102
+ }),
94103
+ ...direct(["skill library"], {
94104
+ owner: "backend",
94105
+ authBoundary: "organization-oauth",
94106
+ quotaClass: "metadata",
94107
+ endpoint: { method: "GET", path: `${orgPath}/skills/library` },
94108
+ operationId: "listCliSkillLibrary",
94109
+ canonicalOperation: "cli.skill.library.list",
94110
+ capability: "cli.skill.read"
94111
+ }),
94112
+ ...direct(["skill clone"], {
94113
+ owner: "backend",
94114
+ authBoundary: "organization-oauth",
94115
+ quotaClass: "metadata",
94116
+ endpoint: { method: "POST", path: `${orgPath}/skills/library/clone` },
94117
+ operationId: "createCliSkillClones",
94118
+ canonicalOperation: "cli.skill.library.clone",
94119
+ capability: "cli.skill.write"
94120
+ }),
94121
+ ...direct(["skill built-in"], {
94122
+ owner: "backend",
94123
+ authBoundary: "organization-oauth",
94124
+ quotaClass: "metadata",
94125
+ endpoint: { method: "GET", path: `${orgPath}/skills/built-in` },
94126
+ operationId: "listCliBuiltInSkills",
94127
+ canonicalOperation: "cli.skill.built-in.list",
94128
+ capability: "cli.skill.read"
94129
+ }),
94130
+ ...direct(["skill clone-built-in"], {
94131
+ owner: "backend",
94132
+ authBoundary: "organization-oauth",
94133
+ quotaClass: "metadata",
94134
+ endpoint: { method: "POST", path: `${orgPath}/skills/built-in/clone` },
94135
+ operationId: "createCliBuiltInSkillClones",
94136
+ canonicalOperation: "cli.skill.built-in.clone",
94137
+ capability: "cli.skill.write"
94138
+ }),
94139
+ ...direct(["admin skill list"], {
94140
+ owner: "backend",
94141
+ authBoundary: "organization-oauth",
94142
+ quotaClass: "metadata",
94143
+ endpoint: { method: "GET", path: `${orgPath}/admin/skills` },
94144
+ operationId: "listCliAdminSkills",
94145
+ canonicalOperation: "cli.admin.skill.list",
94146
+ capability: "cli.admin.skill.read"
94147
+ }),
94148
+ ...direct(["admin skill get"], {
94149
+ owner: "backend",
94150
+ authBoundary: "organization-oauth",
94151
+ quotaClass: "metadata",
94152
+ endpoint: { method: "GET", path: `${orgPath}/admin/skills/{skillId}` },
94153
+ operationId: "getCliAdminSkill",
94154
+ canonicalOperation: "cli.admin.skill.get",
94155
+ capability: "cli.admin.skill.read"
94156
+ }),
94157
+ ...direct(["admin skill delete"], {
94158
+ owner: "backend",
94159
+ authBoundary: "organization-oauth",
94160
+ quotaClass: "metadata",
94161
+ endpoint: { method: "DELETE", path: `${orgPath}/admin/skills/{skillId}` },
94162
+ operationId: "deleteCliAdminSkill",
94163
+ canonicalOperation: "cli.admin.skill.delete",
94164
+ capability: "cli.admin.skill.write"
94165
+ }),
94166
+ ...direct(["admin skill publish", "admin skill unpublish"], {
94167
+ owner: "backend",
94168
+ authBoundary: "organization-oauth",
94169
+ quotaClass: "metadata",
94170
+ endpoint: { method: "PATCH", path: `${orgPath}/admin/skills/{skillId}` },
94171
+ operationId: "updateCliAdminSkill",
94172
+ canonicalOperation: "cli.admin.skill.update",
94173
+ capability: "cli.admin.skill.write"
94174
+ }),
94175
+ ...direct(["admin skill built-in"], {
94176
+ owner: "backend",
94177
+ authBoundary: "organization-oauth",
94178
+ quotaClass: "metadata",
94179
+ endpoint: { method: "GET", path: `${orgPath}/admin/skills/built-in` },
94180
+ operationId: "listCliAdminBuiltInSkills",
94181
+ canonicalOperation: "cli.admin.skill.built-in.list",
94182
+ capability: "cli.admin.skill.read"
94183
+ }),
94184
+ ...direct(["admin skill clone-built-in"], {
94185
+ owner: "backend",
94186
+ authBoundary: "organization-oauth",
94187
+ quotaClass: "metadata",
94188
+ endpoint: { method: "POST", path: `${orgPath}/admin/skills/built-in/clone` },
94189
+ operationId: "createCliAdminBuiltInSkillClones",
94190
+ canonicalOperation: "cli.admin.skill.built-in.clone",
94191
+ capability: "cli.admin.skill.write"
94192
+ }),
94193
+ ...direct(["drive list"], {
94194
+ owner: "backend",
94195
+ authBoundary: "organization-oauth",
94196
+ quotaClass: "metadata",
94197
+ endpoint: { method: "GET", path: `${orgPath}/drive/entries` },
94198
+ operationId: "listCliDriveEntries",
94199
+ canonicalOperation: "cli.drive.entries.list",
94200
+ capability: "cli.drive.read"
94201
+ }),
94202
+ ...direct(["drive usage"], {
94203
+ owner: "backend",
94204
+ authBoundary: "organization-oauth",
94205
+ quotaClass: "metadata",
94206
+ endpoint: { method: "GET", path: `${orgPath}/drive/usage` },
94207
+ operationId: "getCliDriveUsage",
94208
+ canonicalOperation: "cli.drive.usage.read",
94209
+ capability: "cli.drive.read"
94210
+ }),
94211
+ ...direct(["drive mkdir"], {
94212
+ owner: "backend",
94213
+ authBoundary: "organization-oauth",
94214
+ quotaClass: "metadata",
94215
+ endpoint: { method: "POST", path: `${orgPath}/drive/folders` },
94216
+ operationId: "createCliDriveFolder",
94217
+ canonicalOperation: "cli.drive.folder.create",
94218
+ capability: "cli.drive.write"
94219
+ }),
94220
+ ...direct(["drive rename"], {
94221
+ owner: "backend",
94222
+ authBoundary: "organization-oauth",
94223
+ quotaClass: "metadata",
94224
+ endpoint: { method: "PATCH", path: `${orgPath}/drive/entries/{entryId}` },
94225
+ operationId: "updateCliDriveEntryName",
94226
+ canonicalOperation: "cli.drive.entry.rename",
94227
+ capability: "cli.drive.write"
94228
+ }),
94229
+ ...direct(["drive delete"], {
94230
+ owner: "backend",
94231
+ authBoundary: "organization-oauth",
94232
+ quotaClass: "metadata",
94233
+ endpoint: { method: "POST", path: `${orgPath}/drive/entries/delete` },
94234
+ operationId: "deleteCliDriveEntries",
94235
+ canonicalOperation: "cli.drive.entries.delete",
94236
+ capability: "cli.drive.write"
94237
+ }),
94238
+ ...direct(["chat list"], {
94239
+ owner: "chat",
94240
+ authBoundary: "organization-oauth",
94241
+ quotaClass: "metadata",
94242
+ endpoint: { method: "GET", path: `${orgPath}/chats` },
94243
+ operationId: "listCliChats",
94244
+ canonicalOperation: "cli.chat.list",
94245
+ capability: "cli.chat.read"
94246
+ }),
94247
+ ...direct(["chat get"], {
94248
+ owner: "chat",
94249
+ authBoundary: "organization-oauth",
94250
+ quotaClass: "metadata",
94251
+ endpoint: { method: "GET", path: `${orgPath}/chats/{conversationId}` },
94252
+ operationId: "getCliChat",
94253
+ canonicalOperation: "cli.chat.get",
94254
+ capability: "cli.chat.read"
94255
+ }),
94256
+ ...direct(["chat messages"], {
94257
+ owner: "chat",
94258
+ authBoundary: "organization-oauth",
94259
+ quotaClass: "metadata",
94260
+ endpoint: { method: "GET", path: `${orgPath}/chats/{conversationId}/messages` },
94261
+ operationId: "listCliChatMessages",
94262
+ canonicalOperation: "cli.chat.messages.list",
94263
+ capability: "cli.chat.read"
94264
+ }),
94265
+ ...direct(["integration list"], {
94266
+ owner: "backend",
94267
+ authBoundary: "organization-oauth",
94268
+ quotaClass: "metadata",
94269
+ endpoint: { method: "GET", path: `${orgPath}/integrations` },
94270
+ operationId: "listCliIntegrations",
94271
+ canonicalOperation: "cli.integration.list",
94272
+ capability: "cli.integration.read"
94273
+ }),
94274
+ ...direct(["admin integration available"], {
94275
+ owner: "backend",
94276
+ authBoundary: "organization-oauth",
94277
+ quotaClass: "metadata",
94278
+ endpoint: { method: "GET", path: `${orgPath}/admin/integrations/available` },
94279
+ operationId: "listCliAvailableIntegrations",
94280
+ canonicalOperation: "cli.admin.integration.available.list",
94281
+ capability: "cli.admin.integration.read"
94282
+ }),
94283
+ ...direct(["admin integration get"], {
94284
+ owner: "backend",
94285
+ authBoundary: "organization-oauth",
94286
+ quotaClass: "metadata",
94287
+ endpoint: { method: "GET", path: `${orgPath}/admin/integrations/{integrationId}` },
94288
+ operationId: "getCliAdminIntegration",
94289
+ canonicalOperation: "cli.admin.integration.get",
94290
+ capability: "cli.admin.integration.read"
94291
+ }),
94292
+ ...direct(["admin integration tools"], {
94293
+ owner: "backend",
94294
+ authBoundary: "organization-oauth",
94295
+ quotaClass: "metadata",
94296
+ endpoint: { method: "GET", path: `${orgPath}/admin/integrations/{integrationId}/tools` },
94297
+ operationId: "listCliIntegrationTools",
94298
+ canonicalOperation: "cli.admin.integration.tools.list",
94299
+ capability: "cli.admin.integration.read"
94300
+ }),
94301
+ ...direct(["automation list"], {
94302
+ owner: "backend",
94303
+ authBoundary: "organization-oauth",
94304
+ quotaClass: "metadata",
94305
+ endpoint: { method: "GET", path: `${orgPath}/automations` },
94306
+ operationId: "listCliAutomations",
94307
+ canonicalOperation: "cli.automation.list",
94308
+ capability: "cli.automation.read"
94309
+ }),
94310
+ ...direct(["automation get"], {
94311
+ owner: "backend",
94312
+ authBoundary: "organization-oauth",
94313
+ quotaClass: "metadata",
94314
+ endpoint: { method: "GET", path: `${orgPath}/automations/{automationId}` },
94315
+ operationId: "getCliAutomation",
94316
+ canonicalOperation: "cli.automation.get",
94317
+ capability: "cli.automation.read"
94318
+ }),
94319
+ ...direct(["automation triggers"], {
94320
+ owner: "backend",
94321
+ authBoundary: "organization-oauth",
94322
+ quotaClass: "metadata",
94323
+ endpoint: { method: "GET", path: `${orgPath}/automations/triggers` },
94324
+ operationId: "listCliAutomationTriggers",
94325
+ canonicalOperation: "cli.automation.triggers.list",
94326
+ capability: "cli.automation.read"
94327
+ }),
94328
+ ...direct(["automation history"], {
94329
+ owner: "backend",
94330
+ authBoundary: "organization-oauth",
94331
+ quotaClass: "metadata",
94332
+ endpoint: { method: "GET", path: `${orgPath}/automations/{automationId}/history` },
94333
+ operationId: "listCliAutomationHistory",
94334
+ canonicalOperation: "cli.automation.history.list",
94335
+ capability: "cli.automation.read"
94336
+ }),
94337
+ ...direct(["automation create"], {
94338
+ owner: "backend",
94339
+ authBoundary: "organization-oauth",
94340
+ quotaClass: "metadata",
94341
+ endpoint: { method: "POST", path: `${orgPath}/automations` },
94342
+ operationId: "createCliAutomation",
94343
+ canonicalOperation: "cli.automation.create",
94344
+ capability: "cli.automation.write"
94345
+ }),
94346
+ ...direct(["automation update"], {
94347
+ owner: "backend",
94348
+ authBoundary: "organization-oauth",
94349
+ quotaClass: "metadata",
94350
+ endpoint: { method: "PUT", path: `${orgPath}/automations/{automationId}` },
94351
+ operationId: "updateCliAutomation",
94352
+ canonicalOperation: "cli.automation.update",
94353
+ capability: "cli.automation.write"
94354
+ }),
94355
+ ...direct(["automation delete"], {
94356
+ owner: "backend",
94357
+ authBoundary: "organization-oauth",
94358
+ quotaClass: "metadata",
94359
+ endpoint: { method: "DELETE", path: `${orgPath}/automations/{automationId}` },
94360
+ operationId: "deleteCliAutomation",
94361
+ canonicalOperation: "cli.automation.delete",
94362
+ capability: "cli.automation.write"
94363
+ }),
94364
+ ...direct(["automation enable", "automation disable"], {
94365
+ owner: "backend",
94366
+ authBoundary: "organization-oauth",
94367
+ quotaClass: "metadata",
94368
+ endpoint: { method: "PATCH", path: `${orgPath}/automations/{automationId}/status` },
94369
+ operationId: "updateCliAutomationStatus",
94370
+ canonicalOperation: "cli.automation.status.update",
94371
+ capability: "cli.automation.write"
94372
+ }),
94373
+ ...direct(["admin usage credit"], {
94374
+ owner: "backend",
94375
+ authBoundary: "organization-oauth",
94376
+ quotaClass: "metadata",
94377
+ endpoint: { method: "GET", path: `${orgPath}/admin/usage/credit` },
94378
+ operationId: "getCliCreditUsage",
94379
+ canonicalOperation: "cli.admin.usage.credit.read",
94380
+ capability: "cli.admin.usage.read"
94381
+ }),
94382
+ ...direct(["admin usage top-users"], {
94383
+ owner: "backend",
94384
+ authBoundary: "organization-oauth",
94385
+ quotaClass: "metadata",
94386
+ endpoint: { method: "GET", path: `${orgPath}/admin/usage/top-users` },
94387
+ operationId: "listCliTopUsers",
94388
+ canonicalOperation: "cli.admin.usage.top-users.read",
94389
+ capability: "cli.admin.usage.read"
94390
+ }),
94391
+ ...direct(["admin usage daily-graph"], {
94392
+ owner: "backend",
94393
+ authBoundary: "organization-oauth",
94394
+ quotaClass: "metadata",
94395
+ endpoint: { method: "GET", path: `${orgPath}/admin/usage/daily-graph` },
94396
+ operationId: "getCliDailyUsageGraph",
94397
+ canonicalOperation: "cli.admin.usage.daily-graph.read",
94398
+ capability: "cli.admin.usage.read"
94399
+ }),
94400
+ ...direct(["admin usage daily-users"], {
94401
+ owner: "backend",
94402
+ authBoundary: "organization-oauth",
94403
+ quotaClass: "metadata",
94404
+ endpoint: { method: "GET", path: `${orgPath}/admin/usage/daily-users` },
94405
+ operationId: "listCliDailyUsers",
94406
+ canonicalOperation: "cli.admin.usage.daily-users.read",
94407
+ capability: "cli.admin.usage.read"
94408
+ }),
94409
+ ...direct(["admin usage mcp-top"], {
94410
+ owner: "backend",
94411
+ authBoundary: "organization-oauth",
94412
+ quotaClass: "metadata",
94413
+ endpoint: { method: "GET", path: `${orgPath}/admin/usage/mcp-top` },
94414
+ operationId: "listCliTopMcpTools",
94415
+ canonicalOperation: "cli.admin.usage.mcp-top.read",
94416
+ capability: "cli.admin.usage.read"
94417
+ }),
94418
+ ...direct(["admin audit list"], {
94419
+ owner: "backend",
94420
+ authBoundary: "organization-oauth",
94421
+ quotaClass: "metadata",
94422
+ endpoint: { method: "GET", path: `${orgPath}/admin/audit` },
94423
+ operationId: "listCliAuditLogs",
94424
+ canonicalOperation: "cli.admin.audit.list",
94425
+ capability: "cli.admin.audit.read"
94426
+ }),
94427
+ ...direct(["admin audit types"], {
94428
+ owner: "backend",
94429
+ authBoundary: "organization-oauth",
94430
+ quotaClass: "metadata",
94431
+ endpoint: { method: "GET", path: `${orgPath}/admin/audit/types` },
94432
+ operationId: "listCliAuditEventTypes",
94433
+ canonicalOperation: "cli.admin.audit.types.list",
94434
+ capability: "cli.admin.audit.read"
94435
+ }),
94436
+ ...direct(["admin preset list"], {
94437
+ owner: "backend",
94438
+ authBoundary: "organization-oauth",
94439
+ quotaClass: "metadata",
94440
+ endpoint: { method: "GET", path: `${orgPath}/admin/presets` },
94441
+ operationId: "listCliPresets",
94442
+ canonicalOperation: "cli.admin.preset.list",
94443
+ capability: "cli.admin.preset.read"
94444
+ }),
94445
+ ...direct(["admin preset get"], {
94446
+ owner: "backend",
94447
+ authBoundary: "organization-oauth",
94448
+ quotaClass: "metadata",
94449
+ endpoint: { method: "GET", path: `${orgPath}/admin/presets/{presetId}` },
94450
+ operationId: "getCliPreset",
94451
+ canonicalOperation: "cli.admin.preset.get",
94452
+ capability: "cli.admin.preset.read"
94453
+ }),
94454
+ ...direct(["admin preset create"], {
94455
+ owner: "backend",
94456
+ authBoundary: "organization-oauth",
94457
+ quotaClass: "metadata",
94458
+ endpoint: { method: "POST", path: `${orgPath}/admin/presets` },
94459
+ operationId: "createCliPreset",
94460
+ canonicalOperation: "cli.admin.preset.create",
94461
+ capability: "cli.admin.preset.write"
94462
+ }),
94463
+ ...direct(["admin preset update"], {
94464
+ owner: "backend",
94465
+ authBoundary: "organization-oauth",
94466
+ quotaClass: "metadata",
94467
+ endpoint: { method: "PUT", path: `${orgPath}/admin/presets/{presetId}` },
94468
+ operationId: "updateCliPreset",
94469
+ canonicalOperation: "cli.admin.preset.update",
94470
+ capability: "cli.admin.preset.write"
94471
+ }),
94472
+ ...direct(["admin preset rename"], {
94473
+ owner: "backend",
94474
+ authBoundary: "organization-oauth",
94475
+ quotaClass: "metadata",
94476
+ endpoint: { method: "PATCH", path: `${orgPath}/admin/presets/{presetId}` },
94477
+ operationId: "updateCliPresetName",
94478
+ canonicalOperation: "cli.admin.preset.rename",
94479
+ capability: "cli.admin.preset.write"
94480
+ }),
94481
+ ...direct(["admin preset delete"], {
94482
+ owner: "backend",
94483
+ authBoundary: "organization-oauth",
94484
+ quotaClass: "metadata",
94485
+ endpoint: { method: "DELETE", path: `${orgPath}/admin/presets/{presetId}` },
94486
+ operationId: "deleteCliPreset",
94487
+ canonicalOperation: "cli.admin.preset.delete",
94488
+ capability: "cli.admin.preset.write"
94489
+ }),
94490
+ ...direct(["admin preset set-default"], {
94491
+ owner: "backend",
94492
+ authBoundary: "organization-oauth",
94493
+ quotaClass: "metadata",
94494
+ endpoint: { method: "PUT", path: `${orgPath}/admin/presets/{presetId}/default` },
94495
+ operationId: "updateCliDefaultPreset",
94496
+ canonicalOperation: "cli.admin.preset.default.set",
94497
+ capability: "cli.admin.preset.write"
94498
+ }),
94499
+ ...direct(["admin preset unset-default"], {
94500
+ owner: "backend",
94501
+ authBoundary: "organization-oauth",
94502
+ quotaClass: "metadata",
94503
+ endpoint: { method: "DELETE", path: `${orgPath}/admin/presets/{presetId}/default` },
94504
+ operationId: "deleteCliDefaultPreset",
94505
+ canonicalOperation: "cli.admin.preset.default.unset",
94506
+ capability: "cli.admin.preset.write"
94507
+ }),
94508
+ ...direct(["admin tunnel status"], {
94509
+ owner: "backend",
94510
+ authBoundary: "organization-oauth",
94511
+ quotaClass: "metadata",
94512
+ endpoint: { method: "GET", path: `${orgPath}/admin/tunnel/status` },
94513
+ operationId: "getCliTunnelStatus",
94514
+ canonicalOperation: "cli.admin.tunnel.status.read",
94515
+ capability: "cli.admin.tunnel.read"
94516
+ }),
94517
+ ...candidate(["agent chat"], "chat", "organization-oauth", [
94518
+ "streaming-performance",
94519
+ "execution-permit-lifetime",
94520
+ "disconnect-cancel-recovery"
94521
+ ]),
94522
+ ...candidate(["admin agent export"], "backend", "organization-oauth", [
94523
+ "bounded-download",
94524
+ "partial-file-cleanup",
94525
+ "authorization-audit"
94526
+ ]),
94527
+ ...candidate(["skill upload", "skill download", "admin skill upload", "admin skill download"], "backend", "organization-oauth", [
94528
+ "archive-size-mime-validation",
94529
+ "presigned-host-policy",
94530
+ "abort-complete-recovery"
94531
+ ]),
94532
+ ...candidate([
94533
+ "admin skill github inspect",
94534
+ "admin skill github import",
94535
+ "admin skill github sync"
94536
+ ], "backend", "organization-oauth", [
94537
+ "external-timeout",
94538
+ "repository-size-limit",
94539
+ "duplicate-import-protection",
94540
+ "credential-redaction"
94541
+ ]),
94542
+ ...candidate([
94543
+ "admin skill github credentials set",
94544
+ "admin skill github credentials clear"
94545
+ ], "backend", "organization-oauth", [
94546
+ "secret-redaction",
94547
+ "rotation-revoke-audit"
94548
+ ]),
94549
+ ...candidate(["drive upload", "drive download"], "backend", "organization-oauth", [
94550
+ "byte-timeout-bound",
94551
+ "presigned-host-policy",
94552
+ "storage-quota",
94553
+ "partial-file-cleanup"
94554
+ ]),
94555
+ ...candidate(["chat send"], "chat", "organization-oauth", [
94556
+ "conversation-idempotency",
94557
+ "paid-execution-deduplication",
94558
+ "timeout-cancel-recovery"
94559
+ ]),
94560
+ ...candidate(["integration test"], "backend", "organization-oauth", [
94561
+ "external-timeout",
94562
+ "credential-redaction"
94563
+ ]),
94564
+ ...candidate(["admin integration update", "admin integration delete"], "backend", "organization-oauth", [
94565
+ "typed-contract",
94566
+ "credential-redaction",
94567
+ "mutation-idempotency"
94568
+ ]),
94569
+ ...candidate(["automation run", "automation cancel", "automation webhook-regen"], "backend", "organization-oauth", [
94570
+ "operation-idempotency",
94571
+ "state-transition-validation",
94572
+ "execution-quota",
94573
+ "secret-rotation"
94574
+ ]),
94575
+ ...candidate(["admin preset regen-key", "admin preset regen-static-key"], "backend", "organization-oauth", [
94576
+ "key-redaction",
94577
+ "rotation-audit",
94578
+ "retry-rollback-safety"
94579
+ ]),
94580
+ ...candidate(["admin tunnel config", "admin tunnel token"], "backend", "organization-oauth", [
94581
+ "sensitive-output-policy",
94582
+ "token-ttl-redaction",
94583
+ "audit"
94584
+ ]),
94585
+ {
94586
+ command: "model-exec image generate",
94587
+ tier: "DEFERRED",
94588
+ owner: "chat",
94589
+ authBoundary: "organization-oauth",
94590
+ quotaClass: "endpoint-guard",
94591
+ availability: "DEFERRED",
94592
+ capability: "cli.model.image.generate",
94593
+ requiredGates: ["async-job-lifecycle", "artifact-ttl", "my-drive-output", "cost-reservation"]
94594
+ },
94595
+ ...fixedBoundary(["auth login", "auth refresh"], "STANDARD_OAUTH", "backend", "standard-oauth"),
94596
+ ...fixedBoundary([
94597
+ "auth status",
94598
+ "auth logout",
94599
+ "config set",
94600
+ "config status",
94601
+ "org current"
94602
+ ], "LOCAL_ONLY", "desktop", "local"),
94603
+ ...fixedBoundary(["install", "run", "tunnel"], "EXISTING_NATIVE", "native", "native"),
94604
+ ...fixedBoundary(["logs"], "INTERNAL_HIDDEN", "native", "hidden")
94605
+ ];
94616
94606
 
94617
94607
  class ApiError extends TaggedError$1("ApiError") {
94618
94608
  }
@@ -94645,6 +94635,14 @@ function apiErrorFromUnknown(error, fallbackMessage) {
94645
94635
  if (error instanceof ApiError) {
94646
94636
  return error;
94647
94637
  }
94638
+ if (error instanceof HttpRequestError) {
94639
+ return createApiError({
94640
+ message: error.message + (error.outcome === "unknown" ? " The server may have completed the action. Check its state before running it again." : ""),
94641
+ code: error.code,
94642
+ outcome: error.outcome,
94643
+ ...error.requestId ? { requestId: maskSensitiveText(error.requestId).slice(0, 128) } : {}
94644
+ });
94645
+ }
94648
94646
  return createApiError({
94649
94647
  message: error instanceof Error ? error.message : fallbackMessage
94650
94648
  });
@@ -94655,6 +94653,7 @@ class AgentChatStreamIncompleteError extends Error {
94655
94653
  this.sawOnlyTerminalEnvelope = sawOnlyTerminalEnvelope;
94656
94654
  this.name = "AgentChatStreamIncompleteError";
94657
94655
  }
94656
+ _tag = "AgentChatStreamIncompleteError";
94658
94657
  }
94659
94658
  function normalizeAutomationPagination(pagination) {
94660
94659
  return {
@@ -94745,14 +94744,6 @@ function normalizeSharedUserList(sharedUserList) {
94745
94744
  return { userId, userName };
94746
94745
  });
94747
94746
  }
94748
- async function rateLimitedFetch(input, init) {
94749
- await acquire();
94750
- try {
94751
- return await fetch(input, init);
94752
- } finally {
94753
- await release();
94754
- }
94755
- }
94756
94747
  async function sleep(ms) {
94757
94748
  await new Promise((resolve) => setTimeout(resolve, ms));
94758
94749
  }
@@ -94760,7 +94751,8 @@ async function toApiError(response) {
94760
94751
  let errorData = {};
94761
94752
  try {
94762
94753
  errorData = await response.json();
94763
- } catch {
94754
+ } catch (error) {
94755
+ if (error instanceof HttpRequestError) throw error;
94764
94756
  }
94765
94757
  const code = errorData.code ?? errorData.errorCode;
94766
94758
  const details = isCliQuotaErrorCode(code) ? parseCliQuotaErrorDetails(errorData.details, code) : void 0;
@@ -94770,7 +94762,8 @@ async function toApiError(response) {
94770
94762
  statusCode: response.status,
94771
94763
  code,
94772
94764
  ...details ? { details } : {},
94773
- ...retryAfterSeconds === void 0 ? {} : { retryAfterSeconds }
94765
+ ...retryAfterSeconds === void 0 ? {} : { retryAfterSeconds },
94766
+ ...response.headers.get("x-request-id") ? { requestId: maskSensitiveText(response.headers.get("x-request-id")).slice(0, 128) } : {}
94774
94767
  });
94775
94768
  }
94776
94769
  function isCliQuotaErrorCode(code) {
@@ -94838,29 +94831,23 @@ function parseRetryAfterSeconds(value) {
94838
94831
  return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : void 0;
94839
94832
  }
94840
94833
  const makeRequest = (baseUrl, path, accessToken, options) => tryPromise({
94841
- try: async () => {
94834
+ try: async (signal) => {
94842
94835
  const resolvedBaseUrl = typeof baseUrl === "function" ? baseUrl() : baseUrl;
94843
- const response = await rateLimitedFetch(`${resolvedBaseUrl}${path}`, {
94836
+ return withHttpResponse(`${resolvedBaseUrl}${path}`, {
94844
94837
  method: options?.method || "GET",
94845
94838
  headers: jsonBearerHeaders(accessToken),
94846
94839
  body: options?.body ? JSON.stringify(options.body) : void 0
94847
- });
94848
- if (!response.ok) {
94849
- throw await toApiError(response);
94850
- }
94851
- if (options?.skipJsonParse || response.status === 202 || response.status === 204) {
94852
- return void 0;
94853
- }
94854
- return await response.json();
94840
+ }, async (response) => {
94841
+ if (!response.ok) {
94842
+ throw await toApiError(response);
94843
+ }
94844
+ if (options?.skipJsonParse || response.status === 202 || response.status === 204) {
94845
+ return void 0;
94846
+ }
94847
+ return await response.json();
94848
+ }, { signal, ...options?.timeoutMs ? { timeoutMs: options.timeoutMs } : {}, ...options?.responseBudget ? { responseBudget: options.responseBudget } : {} });
94855
94849
  },
94856
- catch: (error) => {
94857
- if (error instanceof ApiError) {
94858
- return error;
94859
- }
94860
- return createApiError({
94861
- message: error instanceof Error ? error.message : "Unknown error"
94862
- });
94863
- }
94850
+ catch: (error) => apiErrorFromUnknown(error, "The request could not be completed.")
94864
94851
  });
94865
94852
  const getSseData = (line) => {
94866
94853
  if (!line.startsWith("data:")) {
@@ -95014,7 +95001,9 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95014
95001
  return createApiError({
95015
95002
  message: error.message,
95016
95003
  statusCode: error.statusCode,
95017
- code: error.code
95004
+ code: error.code,
95005
+ outcome: error.outcome,
95006
+ requestId: error.requestId
95018
95007
  });
95019
95008
  }
95020
95009
  return createApiError({
@@ -95113,21 +95102,23 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95113
95102
  const resolvedChatBaseUrl = yield* requireChatBaseUrlEffect();
95114
95103
  const path = `/api/${encodeURIComponent(orgSlug)}/conversations/${encodeURIComponent(conversationId)}/stream`;
95115
95104
  return yield* tryPromise({
95116
- try: async () => {
95105
+ try: async (signal) => {
95106
+ const deadline = Date.now() + TRANSFER_DEADLINE_MS;
95117
95107
  for (let attempt = 1; attempt <= AGENT_CHAT_STREAM_MAX_ATTEMPTS; attempt += 1) {
95118
- const response = await rateLimitedFetch(`${resolvedChatBaseUrl}${path}`, {
95119
- method: "POST",
95120
- headers: jsonBearerHeaders(token),
95121
- body: JSON.stringify({})
95122
- });
95123
- if (!response.ok) {
95124
- throw await toApiError(response);
95125
- }
95126
- if (!response.body) {
95127
- throw createApiError({ message: "No response body from agent chat stream endpoint" });
95128
- }
95129
95108
  try {
95130
- return await parseSseStream(response.body);
95109
+ return await withHttpResponse(`${resolvedChatBaseUrl}${path}`, {
95110
+ method: "POST",
95111
+ headers: jsonBearerHeaders(token),
95112
+ body: JSON.stringify({})
95113
+ }, async (response) => {
95114
+ if (!response.ok) {
95115
+ throw await toApiError(response);
95116
+ }
95117
+ if (!response.body) {
95118
+ throw createApiError({ message: "No response body from agent chat stream endpoint" });
95119
+ }
95120
+ return await parseSseStream(response.body);
95121
+ }, { signal, timeoutMs: Math.max(1, deadline - Date.now()) });
95131
95122
  } catch (error) {
95132
95123
  if (error instanceof AgentChatStreamIncompleteError && error.sawOnlyTerminalEnvelope && attempt < AGENT_CHAT_STREAM_MAX_ATTEMPTS) {
95133
95124
  await sleep(AGENT_CHAT_STREAM_RETRY_DELAY_MS);
@@ -95141,11 +95132,13 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95141
95132
  catch: (error) => {
95142
95133
  if (error instanceof ApiError) return error;
95143
95134
  if (error instanceof AgentChatStreamIncompleteError) {
95144
- return createApiError({ message: error.message });
95135
+ return createApiError({
95136
+ message: "The chat response was incomplete. Check the conversation before sending the message again.",
95137
+ code: "CLI_RESPONSE_INVALID",
95138
+ outcome: "unknown"
95139
+ });
95145
95140
  }
95146
- return createApiError({
95147
- message: error instanceof Error ? error.message : "Agent chat failed"
95148
- });
95141
+ return apiErrorFromUnknown(error, "Agent chat failed");
95149
95142
  }
95150
95143
  });
95151
95144
  });
@@ -95173,6 +95166,13 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95173
95166
  return conversation.agentInstallationId;
95174
95167
  });
95175
95168
  return {
95169
+ getMyCliQuota: (orgSlug) => gen(function* () {
95170
+ const token = yield* getAccessToken();
95171
+ yield* requireReleaseEnabledOperation("getCliMyQuota");
95172
+ const path = `/api/cli/v1/organizations/${encodeURIComponent(orgSlug)}/quota`;
95173
+ const response = yield* makeRequest(baseUrl, path, token);
95174
+ return yield* try_({ try: () => parseMyCliQuota(response), catch: (error) => apiErrorFromUnknown(error, "Invalid quota response") });
95175
+ }),
95176
95176
  listOrganizations: () => gen(function* () {
95177
95177
  const token = yield* getAccessToken();
95178
95178
  yield* requireReleaseEnabledOperation("listCliOrganizations");
@@ -95250,19 +95250,17 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95250
95250
  });
95251
95251
  }),
95252
95252
  uploadToS3: (uploadUrl, headers, fileBuffer) => tryPromise({
95253
- try: async () => {
95254
- const response = await fetch(uploadUrl, {
95255
- method: "PUT",
95256
- headers,
95257
- body: fileBuffer
95258
- });
95253
+ try: async (signal) => withHttpResponse(uploadUrl, {
95254
+ method: "PUT",
95255
+ headers,
95256
+ body: fileBuffer
95257
+ }, async (response) => {
95259
95258
  if (!response.ok) {
95260
- throw new Error(`S3 upload failed: ${response.status} ${response.statusText}`);
95259
+ throw createApiError({ message: `S3 upload failed: ${response.status}`, statusCode: response.status });
95261
95260
  }
95262
- },
95263
- catch: (error) => createApiError({
95264
- message: error instanceof Error ? error.message : "S3 upload failed"
95265
- })
95261
+ await response.arrayBuffer();
95262
+ }, { signal, timeoutMs: TRANSFER_DEADLINE_MS, localAdmission: false }),
95263
+ catch: (error) => apiErrorFromUnknown(error, "S3 upload failed")
95266
95264
  }),
95267
95265
  completeUpload: (orgSlug, skillId, overwrite) => gen(function* () {
95268
95266
  const token = yield* getAccessToken();
@@ -95395,17 +95393,14 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95395
95393
  });
95396
95394
  }),
95397
95395
  downloadFromUrl: (url) => tryPromise({
95398
- try: async () => {
95399
- const response = await fetch(url);
95396
+ try: async (signal) => withHttpResponse(url, {}, async (response) => {
95400
95397
  if (!response.ok) {
95401
- throw new Error(`Download failed: ${response.status} ${response.statusText}`);
95398
+ throw createApiError({ message: `Download failed: ${response.status}`, statusCode: response.status });
95402
95399
  }
95403
95400
  const arrayBuffer = await response.arrayBuffer();
95404
95401
  return Buffer.from(arrayBuffer);
95405
- },
95406
- catch: (error) => createApiError({
95407
- message: error instanceof Error ? error.message : "Download failed"
95408
- })
95402
+ }, { signal, timeoutMs: TRANSFER_DEADLINE_MS, maxResponseBytes: TRANSFER_MAX_RESPONSE_BYTES, localAdmission: false }),
95403
+ catch: (error) => apiErrorFromUnknown(error, "Download failed")
95409
95404
  }),
95410
95405
  listLibrarySkills: (orgSlug, options) => gen(function* () {
95411
95406
  const token = yield* getAccessToken();
@@ -95577,7 +95572,8 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95577
95572
  const path = `/api/cli/v1/organizations/${encodeURIComponent(orgSlug)}/model-exec/chat`;
95578
95573
  return yield* makeRequest(chatBaseUrl, path, token, {
95579
95574
  method: "POST",
95580
- body
95575
+ body,
95576
+ timeoutMs: TRANSFER_DEADLINE_MS + 1e4
95581
95577
  });
95582
95578
  }),
95583
95579
  executeModelExecImageGeneration: (orgSlug, body) => gen(function* () {
@@ -95796,20 +95792,16 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95796
95792
  const token = yield* getAccessToken();
95797
95793
  const path = `/web/admin/organizations/slug/${encodeURIComponent(orgSlug)}/installed-agents/${encodeURIComponent(agentId)}/export`;
95798
95794
  return yield* tryPromise({
95799
- try: async () => {
95800
- const response = await rateLimitedFetch(`${resolvedApiBaseUrl}${path}`, {
95801
- headers: bearerHeaders(token)
95802
- });
95795
+ try: async (signal) => withHttpResponse(`${resolvedApiBaseUrl}${path}`, {
95796
+ headers: bearerHeaders(token)
95797
+ }, async (response) => {
95803
95798
  if (!response.ok) {
95804
95799
  throw await toApiError(response);
95805
95800
  }
95806
95801
  const arrayBuffer = await response.arrayBuffer();
95807
95802
  return Buffer.from(arrayBuffer);
95808
- },
95809
- catch: (error) => {
95810
- if (error instanceof ApiError) return error;
95811
- return createApiError({ message: error instanceof Error ? error.message : "Export failed" });
95812
- }
95803
+ }, { signal, timeoutMs: TRANSFER_DEADLINE_MS, maxResponseBytes: TRANSFER_MAX_RESPONSE_BYTES }),
95804
+ catch: (error) => apiErrorFromUnknown(error, "Export failed")
95813
95805
  });
95814
95806
  }),
95815
95807
  getInstalledAgentShare: (orgSlug, agentId) => gen(function* () {
@@ -95831,9 +95823,39 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95831
95823
  yield* requireReleaseEnabledOperation("listCliAgentTemplates");
95832
95824
  const path = `/api/cli/v1/organizations/${encodeURIComponent(orgSlug)}/agents/templates`;
95833
95825
  const templates = [];
95826
+ const ids = /* @__PURE__ */ new Set();
95827
+ const responseBudget = { remainingBytes: HTTP_MAX_RESPONSE_BYTES };
95828
+ const deadline = Date.now() + HTTP_DEADLINE_MS;
95829
+ let firstPagination;
95834
95830
  let page = 1;
95835
95831
  while (true) {
95836
- const raw = yield* makeRequest(baseUrl, page === 1 ? path : `${path}?page=${page}`, token);
95832
+ if (page > 100 || templates.length >= 1e4 || Date.now() >= deadline) {
95833
+ return yield* fail$3(createApiError({
95834
+ message: "The template catalog exceeded the collection limit. Contact support to inspect the catalog.",
95835
+ code: "CLI_COLLECTION_LIMIT"
95836
+ }));
95837
+ }
95838
+ const raw = yield* makeRequest(baseUrl, page === 1 ? path : `${path}?page=${page}`, token, { timeoutMs: Math.max(1, deadline - Date.now()), responseBudget });
95839
+ const pagination = raw.pagination;
95840
+ if (!Array.isArray(raw.list) || !pagination || pagination.page !== page || !Number.isSafeInteger(pagination.pageSize) || pagination.pageSize < 1 || pagination.pageSize > 100 || !Number.isSafeInteger(pagination.total) || pagination.total < 0 || raw.list.length > pagination.pageSize || raw.list.length === 0 && (page - 1) * pagination.pageSize < pagination.total) {
95841
+ return yield* fail$3(createApiError({ message: "The template page was inconsistent. No partial catalog was returned.", code: "CLI_RESPONSE_INVALID" }));
95842
+ }
95843
+ if (firstPagination && (pagination.pageSize !== firstPagination.pageSize || pagination.total !== firstPagination.total)) {
95844
+ return yield* fail$3(createApiError({ message: "The template catalog changed during collection. No partial catalog was returned.", code: "CLI_COLLECTION_CHANGED" }));
95845
+ }
95846
+ firstPagination ??= pagination;
95847
+ if (raw.list.length !== Math.min(pagination.pageSize, Math.max(0, pagination.total - (page - 1) * pagination.pageSize))) {
95848
+ return yield* fail$3(createApiError({ message: "The template page was incomplete. No partial catalog was returned.", code: "CLI_RESPONSE_INVALID" }));
95849
+ }
95850
+ for (const item of raw.list) {
95851
+ if (typeof item.agentId !== "string" || !item.agentId || ids.has(item.agentId)) {
95852
+ return yield* fail$3(createApiError({ message: "The template catalog changed during collection. No partial catalog was returned.", code: "CLI_COLLECTION_CHANGED" }));
95853
+ }
95854
+ ids.add(item.agentId);
95855
+ }
95856
+ if (templates.length + raw.list.length > 1e4) {
95857
+ return yield* fail$3(createApiError({ message: "The template catalog exceeded the collection limit.", code: "CLI_COLLECTION_LIMIT" }));
95858
+ }
95837
95859
  templates.push(...raw.list);
95838
95860
  if (raw.list.length === 0 || page * raw.pagination.pageSize >= raw.pagination.total) break;
95839
95861
  page += 1;
@@ -96094,6 +96116,305 @@ const makeApiServiceLive = (buildEnv) => effect$1(
96094
96116
  const ApiServiceLive = makeApiServiceLive(BUILD_ENV);
96095
96117
  const ApiService = ApiServiceTag;
96096
96118
 
96119
+ function jsonOutputRequested(args) {
96120
+ const forced = args.indexOf("--");
96121
+ const options = forced === -1 ? args : args.slice(0, forced);
96122
+ return options.some((arg, index) => arg === "--json=true" || arg === "--json" && options[index + 1] !== "false");
96123
+ }
96124
+ function reportInterruption(json) {
96125
+ const message = "The command was interrupted. Check the status of any change or execution before running it again.";
96126
+ process.stderr.write(`${json ? JSON.stringify({ error: { code: "CLI_COMMAND_INTERRUPTED", message, outcome: "unknown" } }) : message}
96127
+ `);
96128
+ process.exitCode = 130;
96129
+ }
96130
+ function cliTeardown(json) {
96131
+ return (exit, onExit) => {
96132
+ if (isFailure(exit) && isInterruptedOnly(exit.cause) && process.exitCode !== 130) reportInterruption(json);
96133
+ defaultTeardown(exit, (code) => {
96134
+ void waitForHttpCleanup().then(() => onExit(process.exitCode ? Number(process.exitCode) : code));
96135
+ });
96136
+ };
96137
+ }
96138
+ function withCliFailureOutput(program, json) {
96139
+ return consoleWith((original) => {
96140
+ const pending = [];
96141
+ let errorCount = 0;
96142
+ const flush = () => forEach$2(pending, ({ method, args }) => original[method](...args), { discard: true });
96143
+ const defer = (method) => (...args) => sync$1(() => {
96144
+ if (method !== "error" || errorCount++ < 100) pending.push({ method, args });
96145
+ });
96146
+ const console = {
96147
+ ...original,
96148
+ error: defer("error"),
96149
+ ...json ? { log: defer("log"), info: defer("info"), debug: defer("debug"), warn: defer("warn") } : {}
96150
+ };
96151
+ return program.pipe(
96152
+ withConsole(console),
96153
+ tap(() => flush()),
96154
+ catchAllCause((cause) => {
96155
+ if (isInterruptedOnly(cause)) {
96156
+ return sync$1(() => {
96157
+ reportInterruption(json);
96158
+ }).pipe(uninterruptible);
96159
+ }
96160
+ const failure = failureOption(cause);
96161
+ const output = isSome(failure) ? formatCliFailure(failure.value, json) : void 0;
96162
+ if (!output) return flush().pipe(zipRight$2(failCause$2(cause)));
96163
+ return sync$1(() => {
96164
+ process.stderr.write(`${output}
96165
+ `);
96166
+ process.exitCode = 1;
96167
+ });
96168
+ })
96169
+ );
96170
+ });
96171
+ }
96172
+ function formatCliFailure(error, json) {
96173
+ if (!(error instanceof ApiError || error instanceof OAuthRequestError || error instanceof NotLoggedInError || error instanceof NoOrganizationSelectedError)) return void 0;
96174
+ const diagnosticError = error instanceof ApiError || error instanceof OAuthRequestError;
96175
+ if (!json) return maskSensitiveText(error.message + (diagnosticError && error.requestId ? ` Request ID: ${error.requestId}` : ""));
96176
+ return JSON.stringify({ error: {
96177
+ code: diagnosticError ? error.code ?? (error instanceof OAuthRequestError ? "CLI_OAUTH_ERROR" : "CLI_API_ERROR") : error._tag === "NotLoggedInError" ? "CLI_AUTH_REQUIRED" : "CLI_ORGANIZATION_REQUIRED",
96178
+ message: maskSensitiveText(error.message),
96179
+ ...diagnosticError ? {
96180
+ ...error.statusCode === void 0 ? {} : { statusCode: error.statusCode },
96181
+ ...error instanceof ApiError && error.details ? { details: error.details } : {},
96182
+ ...error instanceof ApiError && error.retryAfterSeconds !== void 0 ? { retryAfterSeconds: error.retryAfterSeconds } : {},
96183
+ ...error.outcome ? { outcome: error.outcome } : {},
96184
+ ...error.requestId ? { requestId: error.requestId } : {}
96185
+ } : {}
96186
+ } });
96187
+ }
96188
+
96189
+ const loadBinaryModule = () => {
96190
+ const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
96191
+ return require$1(["..", "binary.cjs"].join("/"));
96192
+ };
96193
+ const resolveNativeBinary = (options = {}) => {
96194
+ const env = options.env ?? process.env;
96195
+ if (env.AIPCTL_NATIVE_BINARY && env.AIPCTL_NATIVE_BINARY.length > 0) {
96196
+ return env.AIPCTL_NATIVE_BINARY;
96197
+ }
96198
+ const binary = (options.loadBinaryModule ?? loadBinaryModule)();
96199
+ return binary.resolveBinaryPath(options.platform ?? process.platform, options.arch ?? process.arch);
96200
+ };
96201
+ const runNativeCommand = (args, options = {}) => new Promise((resolve) => {
96202
+ const env = options.env ?? process.env;
96203
+ const spawn = options.spawn ?? childProcess.spawn;
96204
+ const binaryPath = resolveNativeBinary(options);
96205
+ const child = spawn(binaryPath, [...args], {
96206
+ stdio: "inherit",
96207
+ env
96208
+ });
96209
+ child.on("error", (error) => {
96210
+ console.error(`Failed to start native command: ${error.message}`);
96211
+ process.exitCode = 1;
96212
+ resolve();
96213
+ });
96214
+ child.on("exit", (code) => {
96215
+ process.exitCode = code ?? 1;
96216
+ resolve();
96217
+ });
96218
+ });
96219
+
96220
+ const restArgs = text$2({ name: "arg" }).pipe(
96221
+ repeated,
96222
+ withDescription$5("Arguments passed through to the native aipctl command")
96223
+ );
96224
+ const makeNativeCommand = (name, description) => make$4(
96225
+ name,
96226
+ { rest: restArgs },
96227
+ ({ rest }) => promise$1(() => runNativeCommand([name, ...rest]))
96228
+ ).pipe(withDescription(description));
96229
+
96230
+ const nativeCommandDefinitions = [
96231
+ { name: "install", description: "Install an MCP preset into a local client", includeInProd: true },
96232
+ { name: "run", description: "Run the native MCP server", includeInProd: true },
96233
+ { name: "tunnel", description: "Manage Edge Tunnel connections", includeInProd: true },
96234
+ { name: "logs", description: "Inspect native MCP CLI logs", includeInProd: false }
96235
+ ];
96236
+ const nativeCommandNames = nativeCommandDefinitions.map(({ name }) => name);
96237
+ const isEnabledNativeCommand = (definition, includeLogs) => definition.includeInProd || includeLogs;
96238
+ const nativeSubcommands = nativeCommandDefinitions.filter((definition) => isEnabledNativeCommand(definition, INCLUDE_NATIVE_LOGS)).map(({ name, description }) => makeNativeCommand(name, description));
96239
+ const isNativeCommandEnabled = (command, includeLogs = INCLUDE_NATIVE_LOGS) => {
96240
+ const definition = nativeCommandDefinitions.find(({ name }) => name === command);
96241
+ return definition ? isEnabledNativeCommand(definition, includeLogs) : false;
96242
+ };
96243
+
96244
+ const FORCED_ARGS_SEPARATOR = "--";
96245
+ const NATIVE_ROOT_COMMANDS = new Set(nativeCommandNames);
96246
+ const trailingOptionSpecs = [
96247
+ { command: ["quota", "status"], booleanOptions: /* @__PURE__ */ new Set(["--json"]), valueOptions: /* @__PURE__ */ new Set(["--org"]), explicitBooleanValues: true },
96248
+ ...["list", "get", "create", "update", "rename", "delete", "set-default", "unset-default"].map((command) => ({
96249
+ command: ["admin", "preset", command],
96250
+ booleanOptions: new Set(command === "delete" ? ["--force", "-f"] : ["list", "get"].includes(command) ? ["--json"] : []),
96251
+ valueOptions: /* @__PURE__ */ new Set(["--org", ...command === "list" ? ["--page", "--pageSize"] : []]),
96252
+ explicitBooleanValues: true,
96253
+ booleanAliases: { "-f": "--force" }
96254
+ })),
96255
+ ...["invite", "remove-member", "update-member-role"].map((command) => ({
96256
+ command: ["admin", "org", command],
96257
+ booleanOptions: new Set(command === "remove-member" ? ["--force", "-f"] : []),
96258
+ valueOptions: /* @__PURE__ */ new Set(["--org", ...command !== "remove-member" ? ["--role"] : []]),
96259
+ explicitBooleanValues: true,
96260
+ booleanAliases: { "-f": "--force" }
96261
+ })),
96262
+ {
96263
+ command: ["org", "exit"],
96264
+ booleanOptions: /* @__PURE__ */ new Set(["--force", "-f"]),
96265
+ valueOptions: /* @__PURE__ */ new Set(["--org"]),
96266
+ explicitBooleanValues: true,
96267
+ booleanAliases: { "-f": "--force" }
96268
+ },
96269
+ ...["list", "get"].map((command) => ({
96270
+ command: ["automation", command],
96271
+ booleanOptions: /* @__PURE__ */ new Set(["--json"]),
96272
+ valueOptions: /* @__PURE__ */ new Set(["--org", ...command === "list" ? ["--name"] : []]),
96273
+ explicitBooleanValues: true
96274
+ })),
96275
+ {
96276
+ command: ["automation", "delete"],
96277
+ booleanOptions: /* @__PURE__ */ new Set(["--force", "-f"]),
96278
+ valueOptions: /* @__PURE__ */ new Set(["--org"]),
96279
+ explicitBooleanValues: true,
96280
+ booleanAliases: { "-f": "--force" }
96281
+ },
96282
+ {
96283
+ command: ["drive", "delete"],
96284
+ booleanOptions: /* @__PURE__ */ new Set(["--force", "-f"]),
96285
+ valueOptions: /* @__PURE__ */ new Set(["--org"])
96286
+ },
96287
+ {
96288
+ command: ["automation", "history"],
96289
+ booleanOptions: /* @__PURE__ */ new Set(),
96290
+ valueOptions: /* @__PURE__ */ new Set(["--page", "--org"])
96291
+ },
96292
+ {
96293
+ command: ["automation", "triggers"],
96294
+ booleanOptions: /* @__PURE__ */ new Set(),
96295
+ valueOptions: /* @__PURE__ */ new Set(["--account-id", "--folder-id", "--service-type", "--org"])
96296
+ },
96297
+ {
96298
+ command: ["admin", "skill", "github", "import"],
96299
+ booleanOptions: /* @__PURE__ */ new Set(["--overwrite", "--json"]),
96300
+ valueOptions: /* @__PURE__ */ new Set(["--org", "--pat-env"])
96301
+ }
96302
+ ];
96303
+ const getOptionName = (arg) => arg.split("=", 1)[0];
96304
+ const findTrailingOptionSpec = (args) => trailingOptionSpecs.find((spec) => spec.command.every((part, index) => args[index] === part));
96305
+ const isNativeRootCommand = (args) => NATIVE_ROOT_COMMANDS.has(args[0] ?? "");
96306
+ const isBooleanOption = (arg, spec) => spec.booleanOptions.has(arg);
96307
+ const isValueOption = (arg, spec) => spec.valueOptions.has(getOptionName(arg));
96308
+ const normalizeTrailingOptions = (args, spec) => {
96309
+ const options = [];
96310
+ const rest = [];
96311
+ for (let index = 0; index < args.length; index += 1) {
96312
+ const arg = args[index];
96313
+ if (arg === void 0) {
96314
+ continue;
96315
+ }
96316
+ if (spec.explicitBooleanValues && spec.booleanOptions.has(getOptionName(arg))) {
96317
+ const nextArg = args[index + 1];
96318
+ const optionName = spec.booleanAliases?.[getOptionName(arg)] ?? getOptionName(arg);
96319
+ if (arg.includes("=")) {
96320
+ options.push(`${optionName}${arg.slice(arg.indexOf("="))}`);
96321
+ } else if (nextArg === "true" || nextArg === "false") {
96322
+ options.push(`${optionName}=${nextArg}`);
96323
+ index += 1;
96324
+ } else {
96325
+ options.push(`${optionName}=true`);
96326
+ }
96327
+ continue;
96328
+ }
96329
+ if (isBooleanOption(arg, spec)) {
96330
+ options.push(arg);
96331
+ continue;
96332
+ }
96333
+ if (isValueOption(arg, spec)) {
96334
+ options.push(arg);
96335
+ const nextArg = args[index + 1];
96336
+ if (!arg.includes("=") && nextArg !== void 0 && !nextArg.startsWith("-")) {
96337
+ index += 1;
96338
+ options.push(nextArg);
96339
+ }
96340
+ continue;
96341
+ }
96342
+ rest.push(arg);
96343
+ }
96344
+ return [...options, ...rest];
96345
+ };
96346
+ const normalizeAipArgs = (args) => {
96347
+ if (isNativeRootCommand(args)) {
96348
+ return [...args];
96349
+ }
96350
+ const forcedArgsIndex = args.indexOf(FORCED_ARGS_SEPARATOR);
96351
+ const parsedArgs = forcedArgsIndex === -1 ? args : args.slice(0, forcedArgsIndex);
96352
+ const forcedArgs = forcedArgsIndex === -1 ? [] : args.slice(forcedArgsIndex);
96353
+ const spec = findTrailingOptionSpec(parsedArgs);
96354
+ if (!spec) {
96355
+ return [...args];
96356
+ }
96357
+ const commandPrefix = parsedArgs.slice(0, spec.command.length);
96358
+ const suffix = parsedArgs.slice(spec.command.length);
96359
+ return [
96360
+ ...commandPrefix,
96361
+ ...normalizeTrailingOptions(suffix, spec),
96362
+ ...forcedArgs
96363
+ ];
96364
+ };
96365
+
96366
+ const CUSTOMER_AVAILABILITIES = /* @__PURE__ */ new Set([
96367
+ "IMPLEMENTED",
96368
+ "AVAILABLE"
96369
+ ]);
96370
+ const isCustomerAvailable = (entry) => CUSTOMER_AVAILABILITIES.has(entry.availability);
96371
+ const normalizeCliArgCase = (arg) => arg.toLowerCase();
96372
+ const commandSegments = (command) => command.split(" ");
96373
+ const PROD_DISABLED_BUILT_INS = /* @__PURE__ */ new Set(["--completions", "--wizard"]);
96374
+ const isCommandPrefix = (entry, args) => {
96375
+ const segments = commandSegments(entry.command);
96376
+ return segments.length <= args.length && segments.every((segment, index) => args[index] === segment);
96377
+ };
96378
+ const commandPathBeforeOptions = (args) => args.slice(0, args.findIndex((arg) => arg.startsWith("-")) === -1 ? args.length : args.findIndex((arg) => arg.startsWith("-")));
96379
+ const formatUnavailableMessage = (command) => `Command "aipctl ${command}" is not available in this aipctl release. Run "aipctl --help" to see supported commands.`;
96380
+ const formatUnavailableOptionMessage = (option) => `Option "aipctl ${option}" is not available in this aipctl release. Run "aipctl --help" to see supported commands.`;
96381
+ const commandArgsForAvailability = (args) => {
96382
+ const commandArgs = [];
96383
+ for (let index = 0; index < args.length; index += 1) {
96384
+ const arg = args[index];
96385
+ if (arg === "--log-level") {
96386
+ index += 1;
96387
+ continue;
96388
+ }
96389
+ commandArgs.push(arg);
96390
+ }
96391
+ return commandArgs;
96392
+ };
96393
+ const getUnavailableCommandMessage = (args, buildEnv) => {
96394
+ if (buildEnv !== "prod" || args.length === 0) {
96395
+ return null;
96396
+ }
96397
+ const normalizedArgs = args.map(normalizeCliArgCase);
96398
+ const disabledBuiltIn = normalizedArgs.find((arg) => PROD_DISABLED_BUILT_INS.has(arg));
96399
+ if (disabledBuiltIn) {
96400
+ return formatUnavailableOptionMessage(disabledBuiltIn);
96401
+ }
96402
+ const commandArgs = commandArgsForAvailability(normalizedArgs);
96403
+ const entry = commandManifest.filter((candidate) => isCommandPrefix(candidate, commandArgs)).sort((left, right) => commandSegments(right.command).length - commandSegments(left.command).length).at(0);
96404
+ if (entry) {
96405
+ return isCustomerAvailable(entry) ? null : formatUnavailableMessage(entry.command);
96406
+ }
96407
+ const path = commandPathBeforeOptions(commandArgs).join(" ");
96408
+ if (!path) {
96409
+ return null;
96410
+ }
96411
+ const descendants = commandManifest.filter(({ command }) => command.startsWith(`${path} `));
96412
+ if (descendants.length > 0 && descendants.every((candidate) => !isCustomerAvailable(candidate))) {
96413
+ return formatUnavailableMessage(path);
96414
+ }
96415
+ return null;
96416
+ };
96417
+
96097
96418
  const orgOption = text("org").pipe(
96098
96419
  withDescription$3("Organization slug (overrides current organization)"),
96099
96420
  optional
@@ -99066,15 +99387,16 @@ function loginEffect(authFlow, organizationSelection = _void) {
99066
99387
  return gen(function* () {
99067
99388
  yield* log("Starting login flow...");
99068
99389
  const nextCredentials = yield* authFlow.pipe(
99069
- catchAll(
99070
- (error) => gen(function* () {
99390
+ catchAll((error) => {
99391
+ if (error instanceof OAuthRequestError) return fail$3(error);
99392
+ return gen(function* () {
99071
99393
  yield* error$1(`Login failed: ${error.message}`);
99072
99394
  yield* sync$1(() => {
99073
99395
  process.exitCode = 1;
99074
99396
  });
99075
99397
  return null;
99076
- })
99077
- )
99398
+ });
99399
+ })
99078
99400
  );
99079
99401
  if (!nextCredentials) {
99080
99402
  return;
@@ -101707,6 +102029,43 @@ const skillCommand = make$4("skill", {}).pipe(
101707
102029
  withSubcommands(skillSubcommands)
101708
102030
  );
101709
102031
 
102032
+ const quotaStatusCommand = make$4(
102033
+ "status",
102034
+ { org: orgOption, json: boolean("json").pipe(withDescription$3("Output quota status as JSON")) },
102035
+ ({ org, json }) => gen(function* () {
102036
+ const api = yield* ApiService;
102037
+ const slug = yield* resolveOrgSlug(org, api);
102038
+ const quota = yield* api.getMyCliQuota(slug);
102039
+ if (json) {
102040
+ yield* log(jsonFormat(quota));
102041
+ return;
102042
+ }
102043
+ yield* log(`CLI quota for organization "${slug}":`);
102044
+ yield* log(` Metadata requests: ${quota.userLimits.metadataRequestsPerMinute}/min, burst ${quota.userLimits.metadataRequestBurst}`);
102045
+ yield* log(` Text requests: ${quota.userLimits.textRequestsPerMinute}/min, burst ${quota.userLimits.textRequestBurst}`);
102046
+ yield* log(` Daily text limit: ${quota.userLimits.dailyTextAdmissions}`);
102047
+ yield* log(` Concurrent text limit: ${quota.userLimits.concurrentTextExecutions}`);
102048
+ yield* log(` Organization shared requests: metadata ${quota.organizationSharedLimits.metadataRequestsPerMinute}/min (burst ${quota.organizationSharedLimits.metadataRequestBurst}), text ${quota.organizationSharedLimits.textRequestsPerMinute}/min (burst ${quota.organizationSharedLimits.textRequestBurst})`);
102049
+ yield* log(` Organization concurrent text limit: ${quota.organizationSharedLimits.concurrentTextExecutions}`);
102050
+ yield* log(` Policy versions: organization ${quota.organizationPolicyVersion ?? "inherited"}, user ${quota.userPolicyVersion ?? "inherited"}`);
102051
+ if (quota.usage.status === "UNAVAILABLE") {
102052
+ yield* log(" Usage: unavailable. Usage could not be checked; available capacity is unknown.");
102053
+ return;
102054
+ }
102055
+ yield* log(` Daily text used: ${quota.usage.dailyTextAdmissionsUsed}`);
102056
+ yield* log(` Daily reset (UTC): ${quota.usage.dailyResetAt}`);
102057
+ yield* log(` Active text executions: ${quota.usage.activeTextExecutions}`);
102058
+ yield* log(` Unresolved text executions: ${quota.usage.unresolvedTextExecutions}`);
102059
+ yield* log(" Usage is a snapshot. Unresolved executions still occupy capacity.");
102060
+ })
102061
+ ).pipe(withDescription("Show your CLI limits and text usage in the selected organization"));
102062
+ const quotaCommandDescription = "Inspect your CLI limits and usage";
102063
+ const quotaSubcommands = [quotaStatusCommand];
102064
+ const quotaCommand = make$4("quota", {}).pipe(
102065
+ withDescription(quotaCommandDescription),
102066
+ withSubcommands(quotaSubcommands)
102067
+ );
102068
+
101710
102069
  const mainCommandDescription = "AIP command-line interface for managing organizations, skills, and native MCP commands";
101711
102070
  const rootSubcommands = [
101712
102071
  adminCommand,
@@ -101720,6 +102079,7 @@ const rootSubcommands = [
101720
102079
  modelCommand,
101721
102080
  modelExecCommand,
101722
102081
  orgCommand,
102082
+ quotaCommand,
101723
102083
  skillCommand,
101724
102084
  ...nativeSubcommands
101725
102085
  ];
@@ -101743,6 +102103,7 @@ const HELP_GROUPS = [
101743
102103
  { path: ["model-exec"], description: modelExecCommandDescription, subcommands: modelExecSubcommands },
101744
102104
  { path: ["model-exec", "image"], description: imageCommandDescription, subcommands: imageSubcommands },
101745
102105
  { path: ["org"], description: orgCommandDescription, subcommands: orgSubcommands },
102106
+ { path: ["quota"], description: quotaCommandDescription, subcommands: quotaSubcommands },
101746
102107
  { path: ["skill"], description: skillCommandDescription, subcommands: skillSubcommands },
101747
102108
  { path: ["admin", "org"], description: adminOrgCommandDescription, subcommands: adminOrgSubcommands },
101748
102109
  { path: ["admin", "agent"], description: adminAgentCommandDescription, subcommands: adminAgentSubcommands },
@@ -101846,6 +102207,7 @@ const runNativeHelpIfRequested = (args, options = {}) => {
101846
102207
  };
101847
102208
 
101848
102209
  const args = process.argv.slice(2);
102210
+ const json = jsonOutputRequested(args);
101849
102211
  const unavailableMessage = getUnavailableCommandMessage(args, BUILD_ENV);
101850
102212
  if (unavailableMessage) {
101851
102213
  process.stderr.write(`${unavailableMessage}
@@ -101874,5 +102236,6 @@ const argv = [
101874
102236
  cli(argv).pipe(
101875
102237
  provide$1(AppLayer),
101876
102238
  provide$1(layer),
101877
- runMain
102239
+ (program) => withCliFailureOutput(program, json),
102240
+ runMain({ teardown: cliTeardown(json) })
101878
102241
  );