aipctl 2026.10.2 → 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,1239 +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.2".length > 0 ? "2026.10.2" : "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"].map((command) => ({
89736
- command: ["automation", command],
89737
- booleanOptions: /* @__PURE__ */ new Set(["--json"]),
89738
- valueOptions: /* @__PURE__ */ new Set(["--org", ...command === "list" ? ["--name"] : []]),
89739
- explicitBooleanValues: true
89740
- })),
89741
- {
89742
- command: ["automation", "delete"],
89743
- booleanOptions: /* @__PURE__ */ new Set(["--force", "-f"]),
89744
- valueOptions: /* @__PURE__ */ new Set(["--org"]),
89745
- explicitBooleanValues: true,
89746
- booleanAliases: { "-f": "--force" }
89747
- },
89748
- {
89749
- command: ["drive", "delete"],
89750
- booleanOptions: /* @__PURE__ */ new Set(["--force", "-f"]),
89751
- valueOptions: /* @__PURE__ */ new Set(["--org"])
89752
- },
89753
- {
89754
- command: ["automation", "history"],
89755
- booleanOptions: /* @__PURE__ */ new Set(),
89756
- valueOptions: /* @__PURE__ */ new Set(["--page", "--org"])
89757
- },
89758
- {
89759
- command: ["automation", "triggers"],
89760
- booleanOptions: /* @__PURE__ */ new Set(),
89761
- valueOptions: /* @__PURE__ */ new Set(["--account-id", "--folder-id", "--service-type", "--org"])
89762
- },
89763
- {
89764
- command: ["admin", "skill", "github", "import"],
89765
- booleanOptions: /* @__PURE__ */ new Set(["--overwrite", "--json"]),
89766
- 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;
89767
89712
  }
89768
- ];
89769
- const getOptionName = (arg) => arg.split("=", 1)[0];
89770
- const findTrailingOptionSpec = (args) => trailingOptionSpecs.find((spec) => spec.command.every((part, index) => args[index] === part));
89771
- const isNativeRootCommand = (args) => NATIVE_ROOT_COMMANDS.has(args[0] ?? "");
89772
- const isBooleanOption = (arg, spec) => spec.booleanOptions.has(arg);
89773
- const isValueOption = (arg, spec) => spec.valueOptions.has(getOptionName(arg));
89774
- const normalizeTrailingOptions = (args, spec) => {
89775
- const options = [];
89776
- const rest = [];
89777
- for (let index = 0; index < args.length; index += 1) {
89778
- const arg = args[index];
89779
- if (arg === void 0) {
89780
- continue;
89781
- }
89782
- if (spec.explicitBooleanValues && spec.booleanOptions.has(getOptionName(arg))) {
89783
- const nextArg = args[index + 1];
89784
- const optionName = spec.booleanAliases?.[getOptionName(arg)] ?? getOptionName(arg);
89785
- if (arg.includes("=")) {
89786
- options.push(`${optionName}${arg.slice(arg.indexOf("="))}`);
89787
- } else if (nextArg === "true" || nextArg === "false") {
89788
- options.push(`${optionName}=${nextArg}`);
89789
- index += 1;
89790
- } else {
89791
- options.push(`${optionName}=true`);
89792
- }
89793
- continue;
89794
- }
89795
- if (isBooleanOption(arg, spec)) {
89796
- options.push(arg);
89797
- continue;
89798
- }
89799
- if (isValueOption(arg, spec)) {
89800
- options.push(arg);
89801
- const nextArg = args[index + 1];
89802
- if (!arg.includes("=") && nextArg !== void 0 && !nextArg.startsWith("-")) {
89803
- index += 1;
89804
- options.push(nextArg);
89805
- }
89806
- 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
+ };
89807
89817
  }
89808
- rest.push(arg);
89818
+ throw error;
89809
89819
  }
89810
- return [...options, ...rest];
89811
- };
89812
- const normalizeAipArgs = (args) => {
89813
- if (isNativeRootCommand(args)) {
89814
- return [...args];
89820
+ }
89821
+ function requireAppBaseUrl(config) {
89822
+ const rawValue = config.appBaseUrl;
89823
+ if (!rawValue) {
89824
+ throw new AppUrlNotConfiguredError();
89815
89825
  }
89816
- const forcedArgsIndex = args.indexOf(FORCED_ARGS_SEPARATOR);
89817
- const parsedArgs = forcedArgsIndex === -1 ? args : args.slice(0, forcedArgsIndex);
89818
- const forcedArgs = forcedArgsIndex === -1 ? [] : args.slice(forcedArgsIndex);
89819
- const spec = findTrailingOptionSpec(parsedArgs);
89820
- if (!spec) {
89821
- 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));
89822
89851
  }
89823
- const commandPrefix = parsedArgs.slice(0, spec.command.length);
89824
- const suffix = parsedArgs.slice(spec.command.length);
89825
- return [
89826
- ...commandPrefix,
89827
- ...normalizeTrailingOptions(suffix, spec),
89828
- ...forcedArgs
89829
- ];
89830
- };
89831
-
89832
- const implementedCommandOperationIds = /* @__PURE__ */ new Set([
89833
- "listCliAgents",
89834
- "getCliAgent",
89835
- "listCliAgentTemplates",
89836
- "createCliAgent",
89837
- "updateCliAgent",
89838
- "deleteCliAgent",
89839
- "updateCliAgentStatus",
89840
- "getCliAgentShare",
89841
- "getCliMe",
89842
- "getCliUserSettings",
89843
- "listCliOrganizations",
89844
- "getCliOrganizationCapabilities",
89845
- "listCliOrganizationMembers",
89846
- "listCliModels",
89847
- "listCliModelExecModels",
89848
- "createCliModelChatExecution",
89849
- "listCliSkills",
89850
- "getCliSkill",
89851
- "deleteCliSkill",
89852
- "listCliSkillLibrary",
89853
- "createCliSkillClones",
89854
- "listCliBuiltInSkills",
89855
- "createCliBuiltInSkillClones",
89856
- "listCliAdminSkills",
89857
- "getCliAdminSkill",
89858
- "deleteCliAdminSkill",
89859
- "updateCliAdminSkill",
89860
- "listCliAdminBuiltInSkills",
89861
- "createCliAdminBuiltInSkillClones",
89862
- "listCliDriveEntries",
89863
- "getCliDriveUsage",
89864
- "createCliDriveFolder",
89865
- "updateCliDriveEntryName",
89866
- "deleteCliDriveEntries",
89867
- "listCliChats",
89868
- "getCliChat",
89869
- "listCliChatMessages",
89870
- "listCliIntegrations",
89871
- "listCliAvailableIntegrations",
89872
- "getCliAdminIntegration",
89873
- "listCliIntegrationTools",
89874
- "listCliAutomations",
89875
- "getCliAutomation",
89876
- "listCliAutomationTriggers",
89877
- "listCliAutomationHistory",
89878
- "createCliAutomation",
89879
- "updateCliAutomation",
89880
- "deleteCliAutomation",
89881
- "updateCliAutomationStatus",
89882
- "getCliCreditUsage",
89883
- "listCliTopUsers",
89884
- "getCliDailyUsageGraph",
89885
- "listCliDailyUsers",
89886
- "listCliTopMcpTools",
89887
- "listCliAuditLogs",
89888
- "listCliAuditEventTypes"
89889
- ]);
89890
- const releaseEnabledCommandOperationIds = /* @__PURE__ */ new Set([
89891
- "listCliAgents",
89892
- "getCliAgent",
89893
- "listCliAgentTemplates",
89894
- "createCliAgent",
89895
- "updateCliAgent",
89896
- "deleteCliAgent",
89897
- "updateCliAgentStatus",
89898
- "getCliAgentShare",
89899
- "getCliMe",
89900
- "getCliUserSettings",
89901
- "listCliOrganizations",
89902
- "getCliOrganizationCapabilities",
89903
- "listCliOrganizationMembers",
89904
- "listCliModels",
89905
- "listCliModelExecModels",
89906
- "listCliSkills",
89907
- "getCliSkill",
89908
- "deleteCliSkill",
89909
- "listCliSkillLibrary",
89910
- "createCliSkillClones",
89911
- "listCliBuiltInSkills",
89912
- "createCliBuiltInSkillClones",
89913
- "listCliAdminSkills",
89914
- "getCliAdminSkill",
89915
- "deleteCliAdminSkill",
89916
- "updateCliAdminSkill",
89917
- "listCliAdminBuiltInSkills",
89918
- "createCliAdminBuiltInSkillClones",
89919
- "listCliDriveEntries",
89920
- "getCliDriveUsage",
89921
- "createCliDriveFolder",
89922
- "updateCliDriveEntryName",
89923
- "deleteCliDriveEntries",
89924
- "listCliChats",
89925
- "getCliChat",
89926
- "listCliChatMessages",
89927
- "listCliIntegrations",
89928
- "listCliAvailableIntegrations",
89929
- "getCliAdminIntegration",
89930
- "listCliIntegrationTools",
89931
- "listCliAutomations",
89932
- "getCliAutomation",
89933
- "listCliAutomationTriggers",
89934
- "listCliAutomationHistory",
89935
- "createCliAutomation",
89936
- "updateCliAutomation",
89937
- "deleteCliAutomation",
89938
- "updateCliAutomationStatus",
89939
- "getCliCreditUsage",
89940
- "listCliTopUsers",
89941
- "getCliDailyUsageGraph",
89942
- "listCliDailyUsers",
89943
- "listCliTopMcpTools",
89944
- "listCliAuditLogs",
89945
- "listCliAuditEventTypes"
89946
- ]);
89947
- const direct = (commands, operation) => commands.map((command) => ({
89948
- command,
89949
- tier: "GA_DIRECT",
89950
- availability: !implementedCommandOperationIds.has(operation.operationId ?? "") ? "PLANNED" : releaseEnabledCommandOperationIds.has(operation.operationId ?? "") ? "IMPLEMENTED" : "GATED",
89951
- ...operation
89952
- }));
89953
- const candidate = (commands, owner, authBoundary, requiredGates) => commands.map((command) => ({
89954
- command,
89955
- tier: "GA_CANDIDATE",
89956
- owner,
89957
- authBoundary,
89958
- quotaClass: "endpoint-guard",
89959
- availability: "GATED",
89960
- capability: `cli.${command.replaceAll(" ", ".")}`,
89961
- requiredGates
89962
- }));
89963
- const fixedBoundary = (commands, tier, owner, authBoundary) => commands.map((command) => ({
89964
- command,
89965
- tier,
89966
- owner,
89967
- authBoundary,
89968
- quotaClass: "none",
89969
- availability: tier === "INTERNAL_HIDDEN" ? "HIDDEN" : "AVAILABLE"
89970
- }));
89971
- const orgPath = "/api/cli/v1/organizations/{organizationSlug}";
89972
- const commandManifest = [
89973
- ...direct(["auth whoami"], {
89974
- owner: "backend",
89975
- authBoundary: "user-oauth",
89976
- quotaClass: "bootstrap",
89977
- endpoint: { method: "GET", path: "/api/cli/v1/me" },
89978
- operationId: "getCliMe",
89979
- canonicalOperation: "cli.identity.me.read",
89980
- capability: "cli.identity.me"
89981
- }),
89982
- ...direct(["org list", "org use", "org select"], {
89983
- owner: "backend",
89984
- authBoundary: "user-oauth",
89985
- quotaClass: "bootstrap",
89986
- endpoint: { method: "GET", path: "/api/cli/v1/organizations" },
89987
- operationId: "listCliOrganizations",
89988
- canonicalOperation: "cli.organization.list",
89989
- capability: "cli.organization.discovery"
89990
- }),
89991
- ...direct(["org capabilities"], {
89992
- owner: "backend",
89993
- authBoundary: "organization-oauth",
89994
- quotaClass: "metadata",
89995
- endpoint: { method: "GET", path: `${orgPath}/capabilities` },
89996
- operationId: "getCliOrganizationCapabilities",
89997
- canonicalOperation: "cli.organization.capabilities.read",
89998
- capability: "cli.organization.capabilities"
89999
- }),
90000
- ...direct(["org settings"], {
90001
- owner: "backend",
90002
- authBoundary: "user-oauth",
90003
- quotaClass: "bootstrap",
90004
- endpoint: { method: "GET", path: "/api/cli/v1/me/settings" },
90005
- operationId: "getCliUserSettings",
90006
- canonicalOperation: "cli.user.settings.read",
90007
- capability: "cli.user.settings"
90008
- }),
90009
- ...direct(["org members"], {
90010
- owner: "backend",
90011
- authBoundary: "organization-oauth",
90012
- quotaClass: "metadata",
90013
- endpoint: { method: "GET", path: `${orgPath}/members` },
90014
- operationId: "listCliOrganizationMembers",
90015
- canonicalOperation: "cli.organization.members.list",
90016
- capability: "cli.organization.members.read"
90017
- }),
90018
- ...direct(["org exit"], {
90019
- owner: "backend",
90020
- authBoundary: "organization-oauth",
90021
- quotaClass: "metadata",
90022
- endpoint: { method: "DELETE", path: `${orgPath}/membership` },
90023
- operationId: "deleteCliOrganizationMembership",
90024
- canonicalOperation: "cli.organization.membership.exit",
90025
- capability: "cli.organization.exit"
90026
- }),
90027
- ...direct(["admin org invite"], {
90028
- owner: "backend",
90029
- authBoundary: "organization-oauth",
90030
- quotaClass: "metadata",
90031
- endpoint: { method: "POST", path: `${orgPath}/members/invitations` },
90032
- operationId: "createCliOrganizationMemberInvitations",
90033
- canonicalOperation: "cli.organization.members.invite",
90034
- capability: "cli.organization.members.write"
90035
- }),
90036
- ...direct(["admin org remove-member"], {
90037
- owner: "backend",
90038
- authBoundary: "organization-oauth",
90039
- quotaClass: "metadata",
90040
- endpoint: { method: "DELETE", path: `${orgPath}/members` },
90041
- operationId: "deleteCliOrganizationMembers",
90042
- canonicalOperation: "cli.organization.members.remove",
90043
- capability: "cli.organization.members.write"
90044
- }),
90045
- ...direct(["admin org update-member-role"], {
90046
- owner: "backend",
90047
- authBoundary: "organization-oauth",
90048
- quotaClass: "metadata",
90049
- endpoint: { method: "PUT", path: `${orgPath}/members/role` },
90050
- operationId: "updateCliOrganizationMemberRoles",
90051
- canonicalOperation: "cli.organization.members.role.update",
90052
- capability: "cli.organization.members.write"
90053
- }),
90054
- ...direct(["model list"], {
90055
- owner: "chat",
90056
- authBoundary: "organization-oauth",
90057
- quotaClass: "metadata",
90058
- endpoint: { method: "GET", path: `${orgPath}/models` },
90059
- operationId: "listCliModels",
90060
- canonicalOperation: "cli.model.catalog.read",
90061
- capability: "cli.model.catalog"
90062
- }),
90063
- ...direct(["model-exec models", "model-exec get", "model-exec sample"], {
90064
- owner: "chat",
90065
- authBoundary: "organization-oauth",
90066
- quotaClass: "metadata",
90067
- endpoint: { method: "GET", path: `${orgPath}/model-exec/models` },
90068
- operationId: "listCliModelExecModels",
90069
- canonicalOperation: "cli.model.catalog.read",
90070
- capability: "cli.model.catalog"
90071
- }),
90072
- ...direct(["model-exec chat"], {
90073
- owner: "chat",
90074
- authBoundary: "organization-oauth",
90075
- quotaClass: "text-execution",
90076
- endpoint: { method: "POST", path: `${orgPath}/model-exec/chat` },
90077
- operationId: "createCliModelChatExecution",
90078
- canonicalOperation: "cli.model.text.execute",
90079
- capability: "cli.model.text.execute"
90080
- }),
90081
- ...direct(["agent list"], {
90082
- owner: "backend",
90083
- authBoundary: "organization-oauth",
90084
- quotaClass: "metadata",
90085
- endpoint: { method: "GET", path: `${orgPath}/agents` },
90086
- operationId: "listCliAgents",
90087
- canonicalOperation: "cli.agent.list",
90088
- capability: "cli.agent.read"
90089
- }),
90090
- ...direct(["agent get"], {
90091
- owner: "backend",
90092
- authBoundary: "organization-oauth",
90093
- quotaClass: "metadata",
90094
- endpoint: { method: "GET", path: `${orgPath}/agents/{installedAgentId}` },
90095
- operationId: "getCliAgent",
90096
- canonicalOperation: "cli.agent.get",
90097
- capability: "cli.agent.read"
90098
- }),
90099
- ...direct(["agent enable", "agent disable"], {
90100
- owner: "backend",
90101
- authBoundary: "organization-oauth",
90102
- quotaClass: "metadata",
90103
- endpoint: { method: "PATCH", path: `${orgPath}/agents/{installedAgentId}/status` },
90104
- operationId: "updateCliAgentStatus",
90105
- canonicalOperation: "cli.agent.status.update",
90106
- capability: "cli.agent.write"
90107
- }),
90108
- ...direct(["admin agent templates"], {
90109
- owner: "backend",
90110
- authBoundary: "organization-oauth",
90111
- quotaClass: "metadata",
90112
- endpoint: { method: "GET", path: `${orgPath}/agents/templates` },
90113
- operationId: "listCliAgentTemplates",
90114
- canonicalOperation: "cli.agent.templates.list",
90115
- capability: "cli.agent.read"
90116
- }),
90117
- ...direct(["admin agent create"], {
90118
- owner: "backend",
90119
- authBoundary: "organization-oauth",
90120
- quotaClass: "metadata",
90121
- endpoint: { method: "POST", path: `${orgPath}/agents` },
90122
- operationId: "createCliAgent",
90123
- canonicalOperation: "cli.agent.create",
90124
- capability: "cli.agent.write"
90125
- }),
90126
- ...direct(["admin agent update"], {
90127
- owner: "backend",
90128
- authBoundary: "organization-oauth",
90129
- quotaClass: "metadata",
90130
- endpoint: { method: "PATCH", path: `${orgPath}/agents/{installedAgentId}` },
90131
- operationId: "updateCliAgent",
90132
- canonicalOperation: "cli.agent.update",
90133
- capability: "cli.agent.write"
90134
- }),
90135
- ...direct(["admin agent delete"], {
90136
- owner: "backend",
90137
- authBoundary: "organization-oauth",
90138
- quotaClass: "metadata",
90139
- endpoint: { method: "DELETE", path: `${orgPath}/agents/{installedAgentId}` },
90140
- operationId: "deleteCliAgent",
90141
- canonicalOperation: "cli.agent.delete",
90142
- capability: "cli.agent.write"
90143
- }),
90144
- ...direct(["admin agent share"], {
90145
- owner: "backend",
90146
- authBoundary: "organization-oauth",
90147
- quotaClass: "metadata",
90148
- endpoint: { method: "GET", path: `${orgPath}/agents/{installedAgentId}/share` },
90149
- operationId: "getCliAgentShare",
90150
- canonicalOperation: "cli.agent.share.read",
90151
- capability: "cli.agent.read"
90152
- }),
90153
- ...direct(["skill list"], {
90154
- owner: "backend",
90155
- authBoundary: "organization-oauth",
90156
- quotaClass: "metadata",
90157
- endpoint: { method: "GET", path: `${orgPath}/skills` },
90158
- operationId: "listCliSkills",
90159
- canonicalOperation: "cli.skill.list",
90160
- capability: "cli.skill.read"
90161
- }),
90162
- ...direct(["skill get"], {
90163
- owner: "backend",
90164
- authBoundary: "organization-oauth",
90165
- quotaClass: "metadata",
90166
- endpoint: { method: "GET", path: `${orgPath}/skills/{skillId}` },
90167
- operationId: "getCliSkill",
90168
- canonicalOperation: "cli.skill.get",
90169
- capability: "cli.skill.read"
90170
- }),
90171
- ...direct(["skill delete"], {
90172
- owner: "backend",
90173
- authBoundary: "organization-oauth",
90174
- quotaClass: "metadata",
90175
- endpoint: { method: "DELETE", path: `${orgPath}/skills/{skillId}` },
90176
- operationId: "deleteCliSkill",
90177
- canonicalOperation: "cli.skill.delete",
90178
- capability: "cli.skill.write"
90179
- }),
90180
- ...direct(["skill library"], {
90181
- owner: "backend",
90182
- authBoundary: "organization-oauth",
90183
- quotaClass: "metadata",
90184
- endpoint: { method: "GET", path: `${orgPath}/skills/library` },
90185
- operationId: "listCliSkillLibrary",
90186
- canonicalOperation: "cli.skill.library.list",
90187
- capability: "cli.skill.read"
90188
- }),
90189
- ...direct(["skill clone"], {
90190
- owner: "backend",
90191
- authBoundary: "organization-oauth",
90192
- quotaClass: "metadata",
90193
- endpoint: { method: "POST", path: `${orgPath}/skills/library/clone` },
90194
- operationId: "createCliSkillClones",
90195
- canonicalOperation: "cli.skill.library.clone",
90196
- capability: "cli.skill.write"
90197
- }),
90198
- ...direct(["skill built-in"], {
90199
- owner: "backend",
90200
- authBoundary: "organization-oauth",
90201
- quotaClass: "metadata",
90202
- endpoint: { method: "GET", path: `${orgPath}/skills/built-in` },
90203
- operationId: "listCliBuiltInSkills",
90204
- canonicalOperation: "cli.skill.built-in.list",
90205
- capability: "cli.skill.read"
90206
- }),
90207
- ...direct(["skill clone-built-in"], {
90208
- owner: "backend",
90209
- authBoundary: "organization-oauth",
90210
- quotaClass: "metadata",
90211
- endpoint: { method: "POST", path: `${orgPath}/skills/built-in/clone` },
90212
- operationId: "createCliBuiltInSkillClones",
90213
- canonicalOperation: "cli.skill.built-in.clone",
90214
- capability: "cli.skill.write"
90215
- }),
90216
- ...direct(["admin skill list"], {
90217
- owner: "backend",
90218
- authBoundary: "organization-oauth",
90219
- quotaClass: "metadata",
90220
- endpoint: { method: "GET", path: `${orgPath}/admin/skills` },
90221
- operationId: "listCliAdminSkills",
90222
- canonicalOperation: "cli.admin.skill.list",
90223
- capability: "cli.admin.skill.read"
90224
- }),
90225
- ...direct(["admin skill get"], {
90226
- owner: "backend",
90227
- authBoundary: "organization-oauth",
90228
- quotaClass: "metadata",
90229
- endpoint: { method: "GET", path: `${orgPath}/admin/skills/{skillId}` },
90230
- operationId: "getCliAdminSkill",
90231
- canonicalOperation: "cli.admin.skill.get",
90232
- capability: "cli.admin.skill.read"
90233
- }),
90234
- ...direct(["admin skill delete"], {
90235
- owner: "backend",
90236
- authBoundary: "organization-oauth",
90237
- quotaClass: "metadata",
90238
- endpoint: { method: "DELETE", path: `${orgPath}/admin/skills/{skillId}` },
90239
- operationId: "deleteCliAdminSkill",
90240
- canonicalOperation: "cli.admin.skill.delete",
90241
- capability: "cli.admin.skill.write"
90242
- }),
90243
- ...direct(["admin skill publish", "admin skill unpublish"], {
90244
- owner: "backend",
90245
- authBoundary: "organization-oauth",
90246
- quotaClass: "metadata",
90247
- endpoint: { method: "PATCH", path: `${orgPath}/admin/skills/{skillId}` },
90248
- operationId: "updateCliAdminSkill",
90249
- canonicalOperation: "cli.admin.skill.update",
90250
- capability: "cli.admin.skill.write"
90251
- }),
90252
- ...direct(["admin skill built-in"], {
90253
- owner: "backend",
90254
- authBoundary: "organization-oauth",
90255
- quotaClass: "metadata",
90256
- endpoint: { method: "GET", path: `${orgPath}/admin/skills/built-in` },
90257
- operationId: "listCliAdminBuiltInSkills",
90258
- canonicalOperation: "cli.admin.skill.built-in.list",
90259
- capability: "cli.admin.skill.read"
90260
- }),
90261
- ...direct(["admin skill clone-built-in"], {
90262
- owner: "backend",
90263
- authBoundary: "organization-oauth",
90264
- quotaClass: "metadata",
90265
- endpoint: { method: "POST", path: `${orgPath}/admin/skills/built-in/clone` },
90266
- operationId: "createCliAdminBuiltInSkillClones",
90267
- canonicalOperation: "cli.admin.skill.built-in.clone",
90268
- capability: "cli.admin.skill.write"
90269
- }),
90270
- ...direct(["drive list"], {
90271
- owner: "backend",
90272
- authBoundary: "organization-oauth",
90273
- quotaClass: "metadata",
90274
- endpoint: { method: "GET", path: `${orgPath}/drive/entries` },
90275
- operationId: "listCliDriveEntries",
90276
- canonicalOperation: "cli.drive.entries.list",
90277
- capability: "cli.drive.read"
90278
- }),
90279
- ...direct(["drive usage"], {
90280
- owner: "backend",
90281
- authBoundary: "organization-oauth",
90282
- quotaClass: "metadata",
90283
- endpoint: { method: "GET", path: `${orgPath}/drive/usage` },
90284
- operationId: "getCliDriveUsage",
90285
- canonicalOperation: "cli.drive.usage.read",
90286
- capability: "cli.drive.read"
90287
- }),
90288
- ...direct(["drive mkdir"], {
90289
- owner: "backend",
90290
- authBoundary: "organization-oauth",
90291
- quotaClass: "metadata",
90292
- endpoint: { method: "POST", path: `${orgPath}/drive/folders` },
90293
- operationId: "createCliDriveFolder",
90294
- canonicalOperation: "cli.drive.folder.create",
90295
- capability: "cli.drive.write"
90296
- }),
90297
- ...direct(["drive rename"], {
90298
- owner: "backend",
90299
- authBoundary: "organization-oauth",
90300
- quotaClass: "metadata",
90301
- endpoint: { method: "PATCH", path: `${orgPath}/drive/entries/{entryId}` },
90302
- operationId: "updateCliDriveEntryName",
90303
- canonicalOperation: "cli.drive.entry.rename",
90304
- capability: "cli.drive.write"
90305
- }),
90306
- ...direct(["drive delete"], {
90307
- owner: "backend",
90308
- authBoundary: "organization-oauth",
90309
- quotaClass: "metadata",
90310
- endpoint: { method: "POST", path: `${orgPath}/drive/entries/delete` },
90311
- operationId: "deleteCliDriveEntries",
90312
- canonicalOperation: "cli.drive.entries.delete",
90313
- capability: "cli.drive.write"
90314
- }),
90315
- ...direct(["chat list"], {
90316
- owner: "chat",
90317
- authBoundary: "organization-oauth",
90318
- quotaClass: "metadata",
90319
- endpoint: { method: "GET", path: `${orgPath}/chats` },
90320
- operationId: "listCliChats",
90321
- canonicalOperation: "cli.chat.list",
90322
- capability: "cli.chat.read"
90323
- }),
90324
- ...direct(["chat get"], {
90325
- owner: "chat",
90326
- authBoundary: "organization-oauth",
90327
- quotaClass: "metadata",
90328
- endpoint: { method: "GET", path: `${orgPath}/chats/{conversationId}` },
90329
- operationId: "getCliChat",
90330
- canonicalOperation: "cli.chat.get",
90331
- capability: "cli.chat.read"
90332
- }),
90333
- ...direct(["chat messages"], {
90334
- owner: "chat",
90335
- authBoundary: "organization-oauth",
90336
- quotaClass: "metadata",
90337
- endpoint: { method: "GET", path: `${orgPath}/chats/{conversationId}/messages` },
90338
- operationId: "listCliChatMessages",
90339
- canonicalOperation: "cli.chat.messages.list",
90340
- capability: "cli.chat.read"
90341
- }),
90342
- ...direct(["integration list"], {
90343
- owner: "backend",
90344
- authBoundary: "organization-oauth",
90345
- quotaClass: "metadata",
90346
- endpoint: { method: "GET", path: `${orgPath}/integrations` },
90347
- operationId: "listCliIntegrations",
90348
- canonicalOperation: "cli.integration.list",
90349
- capability: "cli.integration.read"
90350
- }),
90351
- ...direct(["admin integration available"], {
90352
- owner: "backend",
90353
- authBoundary: "organization-oauth",
90354
- quotaClass: "metadata",
90355
- endpoint: { method: "GET", path: `${orgPath}/admin/integrations/available` },
90356
- operationId: "listCliAvailableIntegrations",
90357
- canonicalOperation: "cli.admin.integration.available.list",
90358
- capability: "cli.admin.integration.read"
90359
- }),
90360
- ...direct(["admin integration get"], {
90361
- owner: "backend",
90362
- authBoundary: "organization-oauth",
90363
- quotaClass: "metadata",
90364
- endpoint: { method: "GET", path: `${orgPath}/admin/integrations/{integrationId}` },
90365
- operationId: "getCliAdminIntegration",
90366
- canonicalOperation: "cli.admin.integration.get",
90367
- capability: "cli.admin.integration.read"
90368
- }),
90369
- ...direct(["admin integration tools"], {
90370
- owner: "backend",
90371
- authBoundary: "organization-oauth",
90372
- quotaClass: "metadata",
90373
- endpoint: { method: "GET", path: `${orgPath}/admin/integrations/{integrationId}/tools` },
90374
- operationId: "listCliIntegrationTools",
90375
- canonicalOperation: "cli.admin.integration.tools.list",
90376
- capability: "cli.admin.integration.read"
90377
- }),
90378
- ...direct(["automation list"], {
90379
- owner: "backend",
90380
- authBoundary: "organization-oauth",
90381
- quotaClass: "metadata",
90382
- endpoint: { method: "GET", path: `${orgPath}/automations` },
90383
- operationId: "listCliAutomations",
90384
- canonicalOperation: "cli.automation.list",
90385
- capability: "cli.automation.read"
90386
- }),
90387
- ...direct(["automation get"], {
90388
- owner: "backend",
90389
- authBoundary: "organization-oauth",
90390
- quotaClass: "metadata",
90391
- endpoint: { method: "GET", path: `${orgPath}/automations/{automationId}` },
90392
- operationId: "getCliAutomation",
90393
- canonicalOperation: "cli.automation.get",
90394
- capability: "cli.automation.read"
90395
- }),
90396
- ...direct(["automation triggers"], {
90397
- owner: "backend",
90398
- authBoundary: "organization-oauth",
90399
- quotaClass: "metadata",
90400
- endpoint: { method: "GET", path: `${orgPath}/automations/triggers` },
90401
- operationId: "listCliAutomationTriggers",
90402
- canonicalOperation: "cli.automation.triggers.list",
90403
- capability: "cli.automation.read"
90404
- }),
90405
- ...direct(["automation history"], {
90406
- owner: "backend",
90407
- authBoundary: "organization-oauth",
90408
- quotaClass: "metadata",
90409
- endpoint: { method: "GET", path: `${orgPath}/automations/{automationId}/history` },
90410
- operationId: "listCliAutomationHistory",
90411
- canonicalOperation: "cli.automation.history.list",
90412
- capability: "cli.automation.read"
90413
- }),
90414
- ...direct(["automation create"], {
90415
- owner: "backend",
90416
- authBoundary: "organization-oauth",
90417
- quotaClass: "metadata",
90418
- endpoint: { method: "POST", path: `${orgPath}/automations` },
90419
- operationId: "createCliAutomation",
90420
- canonicalOperation: "cli.automation.create",
90421
- capability: "cli.automation.write"
90422
- }),
90423
- ...direct(["automation update"], {
90424
- owner: "backend",
90425
- authBoundary: "organization-oauth",
90426
- quotaClass: "metadata",
90427
- endpoint: { method: "PUT", path: `${orgPath}/automations/{automationId}` },
90428
- operationId: "updateCliAutomation",
90429
- canonicalOperation: "cli.automation.update",
90430
- capability: "cli.automation.write"
90431
- }),
90432
- ...direct(["automation delete"], {
90433
- owner: "backend",
90434
- authBoundary: "organization-oauth",
90435
- quotaClass: "metadata",
90436
- endpoint: { method: "DELETE", path: `${orgPath}/automations/{automationId}` },
90437
- operationId: "deleteCliAutomation",
90438
- canonicalOperation: "cli.automation.delete",
90439
- capability: "cli.automation.write"
90440
- }),
90441
- ...direct(["automation enable", "automation disable"], {
90442
- owner: "backend",
90443
- authBoundary: "organization-oauth",
90444
- quotaClass: "metadata",
90445
- endpoint: { method: "PATCH", path: `${orgPath}/automations/{automationId}/status` },
90446
- operationId: "updateCliAutomationStatus",
90447
- canonicalOperation: "cli.automation.status.update",
90448
- capability: "cli.automation.write"
90449
- }),
90450
- ...direct(["admin usage credit"], {
90451
- owner: "backend",
90452
- authBoundary: "organization-oauth",
90453
- quotaClass: "metadata",
90454
- endpoint: { method: "GET", path: `${orgPath}/admin/usage/credit` },
90455
- operationId: "getCliCreditUsage",
90456
- canonicalOperation: "cli.admin.usage.credit.read",
90457
- capability: "cli.admin.usage.read"
90458
- }),
90459
- ...direct(["admin usage top-users"], {
90460
- owner: "backend",
90461
- authBoundary: "organization-oauth",
90462
- quotaClass: "metadata",
90463
- endpoint: { method: "GET", path: `${orgPath}/admin/usage/top-users` },
90464
- operationId: "listCliTopUsers",
90465
- canonicalOperation: "cli.admin.usage.top-users.read",
90466
- capability: "cli.admin.usage.read"
90467
- }),
90468
- ...direct(["admin usage daily-graph"], {
90469
- owner: "backend",
90470
- authBoundary: "organization-oauth",
90471
- quotaClass: "metadata",
90472
- endpoint: { method: "GET", path: `${orgPath}/admin/usage/daily-graph` },
90473
- operationId: "getCliDailyUsageGraph",
90474
- canonicalOperation: "cli.admin.usage.daily-graph.read",
90475
- capability: "cli.admin.usage.read"
90476
- }),
90477
- ...direct(["admin usage daily-users"], {
90478
- owner: "backend",
90479
- authBoundary: "organization-oauth",
90480
- quotaClass: "metadata",
90481
- endpoint: { method: "GET", path: `${orgPath}/admin/usage/daily-users` },
90482
- operationId: "listCliDailyUsers",
90483
- canonicalOperation: "cli.admin.usage.daily-users.read",
90484
- capability: "cli.admin.usage.read"
90485
- }),
90486
- ...direct(["admin usage mcp-top"], {
90487
- owner: "backend",
90488
- authBoundary: "organization-oauth",
90489
- quotaClass: "metadata",
90490
- endpoint: { method: "GET", path: `${orgPath}/admin/usage/mcp-top` },
90491
- operationId: "listCliTopMcpTools",
90492
- canonicalOperation: "cli.admin.usage.mcp-top.read",
90493
- capability: "cli.admin.usage.read"
90494
- }),
90495
- ...direct(["admin audit list"], {
90496
- owner: "backend",
90497
- authBoundary: "organization-oauth",
90498
- quotaClass: "metadata",
90499
- endpoint: { method: "GET", path: `${orgPath}/admin/audit` },
90500
- operationId: "listCliAuditLogs",
90501
- canonicalOperation: "cli.admin.audit.list",
90502
- capability: "cli.admin.audit.read"
90503
- }),
90504
- ...direct(["admin audit types"], {
90505
- owner: "backend",
90506
- authBoundary: "organization-oauth",
90507
- quotaClass: "metadata",
90508
- endpoint: { method: "GET", path: `${orgPath}/admin/audit/types` },
90509
- operationId: "listCliAuditEventTypes",
90510
- canonicalOperation: "cli.admin.audit.types.list",
90511
- capability: "cli.admin.audit.read"
90512
- }),
90513
- ...direct(["admin preset list"], {
90514
- owner: "backend",
90515
- authBoundary: "organization-oauth",
90516
- quotaClass: "metadata",
90517
- endpoint: { method: "GET", path: `${orgPath}/admin/presets` },
90518
- operationId: "listCliPresets",
90519
- canonicalOperation: "cli.admin.preset.list",
90520
- capability: "cli.admin.preset.read"
90521
- }),
90522
- ...direct(["admin preset get"], {
90523
- owner: "backend",
90524
- authBoundary: "organization-oauth",
90525
- quotaClass: "metadata",
90526
- endpoint: { method: "GET", path: `${orgPath}/admin/presets/{presetId}` },
90527
- operationId: "getCliPreset",
90528
- canonicalOperation: "cli.admin.preset.get",
90529
- capability: "cli.admin.preset.read"
90530
- }),
90531
- ...direct(["admin preset create"], {
90532
- owner: "backend",
90533
- authBoundary: "organization-oauth",
90534
- quotaClass: "metadata",
90535
- endpoint: { method: "POST", path: `${orgPath}/admin/presets` },
90536
- operationId: "createCliPreset",
90537
- canonicalOperation: "cli.admin.preset.create",
90538
- capability: "cli.admin.preset.write"
90539
- }),
90540
- ...direct(["admin preset update"], {
90541
- owner: "backend",
90542
- authBoundary: "organization-oauth",
90543
- quotaClass: "metadata",
90544
- endpoint: { method: "PUT", path: `${orgPath}/admin/presets/{presetId}` },
90545
- operationId: "updateCliPreset",
90546
- canonicalOperation: "cli.admin.preset.update",
90547
- capability: "cli.admin.preset.write"
90548
- }),
90549
- ...direct(["admin preset rename"], {
90550
- owner: "backend",
90551
- authBoundary: "organization-oauth",
90552
- quotaClass: "metadata",
90553
- endpoint: { method: "PATCH", path: `${orgPath}/admin/presets/{presetId}` },
90554
- operationId: "updateCliPresetName",
90555
- canonicalOperation: "cli.admin.preset.rename",
90556
- capability: "cli.admin.preset.write"
90557
- }),
90558
- ...direct(["admin preset delete"], {
90559
- owner: "backend",
90560
- authBoundary: "organization-oauth",
90561
- quotaClass: "metadata",
90562
- endpoint: { method: "DELETE", path: `${orgPath}/admin/presets/{presetId}` },
90563
- operationId: "deleteCliPreset",
90564
- canonicalOperation: "cli.admin.preset.delete",
90565
- capability: "cli.admin.preset.write"
90566
- }),
90567
- ...direct(["admin preset set-default"], {
90568
- owner: "backend",
90569
- authBoundary: "organization-oauth",
90570
- quotaClass: "metadata",
90571
- endpoint: { method: "PUT", path: `${orgPath}/admin/presets/{presetId}/default` },
90572
- operationId: "updateCliDefaultPreset",
90573
- canonicalOperation: "cli.admin.preset.default.set",
90574
- capability: "cli.admin.preset.write"
90575
- }),
90576
- ...direct(["admin preset unset-default"], {
90577
- owner: "backend",
90578
- authBoundary: "organization-oauth",
90579
- quotaClass: "metadata",
90580
- endpoint: { method: "DELETE", path: `${orgPath}/admin/presets/{presetId}/default` },
90581
- operationId: "deleteCliDefaultPreset",
90582
- canonicalOperation: "cli.admin.preset.default.unset",
90583
- capability: "cli.admin.preset.write"
90584
- }),
90585
- ...direct(["admin tunnel status"], {
90586
- owner: "backend",
90587
- authBoundary: "organization-oauth",
90588
- quotaClass: "metadata",
90589
- endpoint: { method: "GET", path: `${orgPath}/admin/tunnel/status` },
90590
- operationId: "getCliTunnelStatus",
90591
- canonicalOperation: "cli.admin.tunnel.status.read",
90592
- capability: "cli.admin.tunnel.read"
90593
- }),
90594
- ...candidate(["agent chat"], "chat", "organization-oauth", [
90595
- "streaming-performance",
90596
- "execution-permit-lifetime",
90597
- "disconnect-cancel-recovery"
90598
- ]),
90599
- ...candidate(["admin agent export"], "backend", "organization-oauth", [
90600
- "bounded-download",
90601
- "partial-file-cleanup",
90602
- "authorization-audit"
90603
- ]),
90604
- ...candidate(["skill upload", "skill download", "admin skill upload", "admin skill download"], "backend", "organization-oauth", [
90605
- "archive-size-mime-validation",
90606
- "presigned-host-policy",
90607
- "abort-complete-recovery"
90608
- ]),
90609
- ...candidate([
90610
- "admin skill github inspect",
90611
- "admin skill github import",
90612
- "admin skill github sync"
90613
- ], "backend", "organization-oauth", [
90614
- "external-timeout",
90615
- "repository-size-limit",
90616
- "duplicate-import-protection",
90617
- "credential-redaction"
90618
- ]),
90619
- ...candidate([
90620
- "admin skill github credentials set",
90621
- "admin skill github credentials clear"
90622
- ], "backend", "organization-oauth", [
90623
- "secret-redaction",
90624
- "rotation-revoke-audit"
90625
- ]),
90626
- ...candidate(["drive upload", "drive download"], "backend", "organization-oauth", [
90627
- "byte-timeout-bound",
90628
- "presigned-host-policy",
90629
- "storage-quota",
90630
- "partial-file-cleanup"
90631
- ]),
90632
- ...candidate(["chat send"], "chat", "organization-oauth", [
90633
- "conversation-idempotency",
90634
- "paid-execution-deduplication",
90635
- "timeout-cancel-recovery"
90636
- ]),
90637
- ...candidate(["integration test"], "backend", "organization-oauth", [
90638
- "external-timeout",
90639
- "credential-redaction"
90640
- ]),
90641
- ...candidate(["admin integration update", "admin integration delete"], "backend", "organization-oauth", [
90642
- "typed-contract",
90643
- "credential-redaction",
90644
- "mutation-idempotency"
90645
- ]),
90646
- ...candidate(["automation run", "automation cancel", "automation webhook-regen"], "backend", "organization-oauth", [
90647
- "operation-idempotency",
90648
- "state-transition-validation",
90649
- "execution-quota",
90650
- "secret-rotation"
90651
- ]),
90652
- ...candidate(["admin preset regen-key", "admin preset regen-static-key"], "backend", "organization-oauth", [
90653
- "key-redaction",
90654
- "rotation-audit",
90655
- "retry-rollback-safety"
90656
- ]),
90657
- ...candidate(["admin tunnel config", "admin tunnel token"], "backend", "organization-oauth", [
90658
- "sensitive-output-policy",
90659
- "token-ttl-redaction",
90660
- "audit"
90661
- ]),
90662
- {
90663
- command: "model-exec image generate",
90664
- tier: "DEFERRED",
90665
- owner: "chat",
90666
- authBoundary: "organization-oauth",
90667
- quotaClass: "endpoint-guard",
90668
- availability: "DEFERRED",
90669
- capability: "cli.model.image.generate",
90670
- requiredGates: ["async-job-lifecycle", "artifact-ttl", "my-drive-output", "cost-reservation"]
90671
- },
90672
- ...fixedBoundary(["auth login", "auth refresh"], "STANDARD_OAUTH", "backend", "standard-oauth"),
90673
- ...fixedBoundary([
90674
- "auth status",
90675
- "auth logout",
90676
- "config set",
90677
- "config status",
90678
- "org current"
90679
- ], "LOCAL_ONLY", "desktop", "local"),
90680
- ...fixedBoundary(["install", "run", "tunnel"], "EXISTING_NATIVE", "native", "native"),
90681
- ...fixedBoundary(["logs"], "INTERNAL_HIDDEN", "native", "hidden")
90682
- ];
90683
-
90684
- const CUSTOMER_AVAILABILITIES = /* @__PURE__ */ new Set([
90685
- "IMPLEMENTED",
90686
- "AVAILABLE"
90687
- ]);
90688
- const isCustomerAvailable = (entry) => CUSTOMER_AVAILABILITIES.has(entry.availability);
90689
- const normalizeCliArgCase = (arg) => arg.toLowerCase();
90690
- const commandSegments = (command) => command.split(" ");
90691
- const PROD_DISABLED_BUILT_INS = /* @__PURE__ */ new Set(["--completions", "--wizard"]);
90692
- const isCommandPrefix = (entry, args) => {
90693
- const segments = commandSegments(entry.command);
90694
- return segments.length <= args.length && segments.every((segment, index) => args[index] === segment);
90695
- };
90696
- const commandPathBeforeOptions = (args) => args.slice(0, args.findIndex((arg) => arg.startsWith("-")) === -1 ? args.length : args.findIndex((arg) => arg.startsWith("-")));
90697
- const formatUnavailableMessage = (command) => `Command "aipctl ${command}" is not available in this aipctl release. Run "aipctl --help" to see supported commands.`;
90698
- const formatUnavailableOptionMessage = (option) => `Option "aipctl ${option}" is not available in this aipctl release. Run "aipctl --help" to see supported commands.`;
90699
- const commandArgsForAvailability = (args) => {
90700
- const commandArgs = [];
90701
- for (let index = 0; index < args.length; index += 1) {
90702
- const arg = args[index];
90703
- if (arg === "--log-level") {
90704
- index += 1;
90705
- continue;
90706
- }
90707
- commandArgs.push(arg);
90708
- }
90709
- return commandArgs;
90710
- };
90711
- const getUnavailableCommandMessage = (args, buildEnv) => {
90712
- if (buildEnv !== "prod" || args.length === 0) {
90713
- return null;
90714
- }
90715
- const normalizedArgs = args.map(normalizeCliArgCase);
90716
- const disabledBuiltIn = normalizedArgs.find((arg) => PROD_DISABLED_BUILT_INS.has(arg));
90717
- if (disabledBuiltIn) {
90718
- return formatUnavailableOptionMessage(disabledBuiltIn);
90719
- }
90720
- const commandArgs = commandArgsForAvailability(normalizedArgs);
90721
- const entry = commandManifest.filter((candidate) => isCommandPrefix(candidate, commandArgs)).sort((left, right) => commandSegments(right.command).length - commandSegments(left.command).length).at(0);
90722
- if (entry) {
90723
- return isCustomerAvailable(entry) ? null : formatUnavailableMessage(entry.command);
90724
- }
90725
- const path = commandPathBeforeOptions(commandArgs).join(" ");
90726
- if (!path) {
90727
- return null;
90728
- }
90729
- const descendants = commandManifest.filter(({ command }) => command.startsWith(`${path} `));
90730
- if (descendants.length > 0 && descendants.every((candidate) => !isCustomerAvailable(candidate))) {
90731
- return formatUnavailableMessage(path);
90732
- }
90733
- return null;
90734
- };
90735
-
90736
- const NOT_LOGGED_IN_MESSAGE = 'Not logged in. Please run "aipctl auth login" first.';
90737
- const SESSION_EXPIRED_MESSAGE = 'Session expired. Run "aipctl auth login" to continue.';
90738
-
90739
- const CONFIG_SET_HINT = "aipctl config set --app-url https://app.example.com";
90740
- const CONFIG_DIR$2 = path__namespace.join(os__namespace.homedir(), ".config", "aip");
90741
- const CONFIG_FILE = path__namespace.join(CONFIG_DIR$2, "config.json");
90742
- let cachedConfig;
90743
- class ConfigServiceTag extends Tag$1("ConfigService")() {
90744
- }
90745
- class AppUrlNotConfiguredError extends Error {
90746
- constructor() {
90747
- super(`App URL is not configured. Run "${CONFIG_SET_HINT}" first.`);
90748
- this.name = "AppUrlNotConfiguredError";
90749
- }
90750
- }
90751
- class InvalidAppUrlError extends Error {
90752
- rawValue;
90753
- constructor(rawValue, reason) {
90754
- super(`App URL is invalid: ${reason}. Run "${CONFIG_SET_HINT}" to fix it.`);
90755
- this.name = "InvalidAppUrlError";
90756
- this.rawValue = rawValue;
90757
- }
90758
- }
90759
- function isRecord$1(value) {
90760
- return typeof value === "object" && value !== null;
90761
- }
90762
- function optionalString$1(value) {
90763
- return typeof value === "string" ? value : void 0;
90764
- }
90765
- function parseCurrentOrganization(value) {
90766
- if (!isRecord$1(value)) {
90767
- return void 0;
90768
- }
90769
- const id = optionalString$1(value["id"]);
90770
- const slug = optionalString$1(value["slug"]);
90771
- const name = optionalString$1(value["name"]);
90772
- if (!id || !slug || !name) {
90773
- return void 0;
90774
- }
90775
- return { id, slug, name };
90776
- }
90777
- function normalizeLoadedConfig(value) {
90778
- if (!isRecord$1(value)) {
90779
- return {};
90780
- }
90781
- return {
90782
- appBaseUrl: optionalString$1(value["appBaseUrl"]),
90783
- currentOrganization: parseCurrentOrganization(value["currentOrganization"])
90784
- };
90785
- }
90786
- function cloneConfig(config) {
90787
- return {
90788
- appBaseUrl: config.appBaseUrl,
90789
- currentOrganization: config.currentOrganization ? { ...config.currentOrganization } : void 0
90790
- };
90791
- }
90792
- function readConfigFile() {
90793
- try {
90794
- const content = fs__namespace.readFileSync(CONFIG_FILE, "utf-8");
90795
- return normalizeLoadedConfig(JSON.parse(content));
90796
- } catch {
90797
- return {};
90798
- }
90799
- }
90800
- function isSameCurrentOrganization(left, right) {
90801
- return left?.id === right?.id && left?.slug === right?.slug && left?.name === right?.name;
90802
- }
90803
- function isSameConfig(left, right) {
90804
- return left.appBaseUrl === right.appBaseUrl && isSameCurrentOrganization(left.currentOrganization, right.currentOrganization);
90805
- }
90806
- function isLoopbackHostname(hostname) {
90807
- const normalized = hostname.toLowerCase();
90808
- return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1" || normalized === "[::1]";
90809
- }
90810
- function hasExplicitAppUrlProtocol(value) {
90811
- const protocolMatch = /^[a-z][a-z\d+.-]*:/i.exec(value);
90812
- if (!protocolMatch) {
90813
- return false;
90814
- }
90815
- const valueAfterProtocol = value.slice(protocolMatch[0].length);
90816
- return !/^\d+(?:$|[/?#])/.test(valueAfterProtocol);
90817
- }
90818
- function normalizeAppUrl(rawValue) {
90819
- const trimmed = rawValue.trim();
90820
- if (trimmed.length === 0) {
90821
- throw new InvalidAppUrlError(rawValue, "value must not be empty");
90822
- }
90823
- const appUrl = hasExplicitAppUrlProtocol(trimmed) ? trimmed : `https://${trimmed}`;
90824
- let url;
90825
- try {
90826
- url = new URL(appUrl);
90827
- } catch {
90828
- throw new InvalidAppUrlError(rawValue, "value must be a valid URL");
90829
- }
90830
- if (url.protocol !== "http:" && url.protocol !== "https:") {
90831
- throw new InvalidAppUrlError(rawValue, "only https:// URLs are supported, with http:// allowed for localhost development");
90832
- }
90833
- if (url.protocol === "http:" && !isLoopbackHostname(url.hostname)) {
90834
- throw new InvalidAppUrlError(rawValue, "http:// is only supported for localhost development; use https:// for app URLs");
90835
- }
90836
- return url.origin;
90837
- }
90838
- function deriveInternalBaseUrls(appBaseUrl) {
90839
- const url = new URL(normalizeAppUrl(appBaseUrl));
90840
- return {
90841
- apiBaseUrl: `${url.protocol}//api.${url.host}`,
90842
- chatBaseUrl: `${url.protocol}//chat.${url.host}`
90843
- };
90844
- }
90845
- function getAppUrlStatus(config) {
90846
- const rawValue = config.appBaseUrl;
90847
- if (!rawValue) {
90848
- return { state: "unconfigured" };
90849
- }
90850
- try {
90851
- return {
90852
- state: "configured",
90853
- value: normalizeAppUrl(rawValue)
90854
- };
90855
- } catch (error) {
90856
- if (error instanceof InvalidAppUrlError) {
90857
- return {
90858
- state: "invalid",
90859
- value: rawValue,
90860
- reason: error.message
90861
- };
90862
- }
90863
- throw error;
90864
- }
90865
- }
90866
- function requireAppBaseUrl(config) {
90867
- const rawValue = config.appBaseUrl;
90868
- if (!rawValue) {
90869
- throw new AppUrlNotConfiguredError();
90870
- }
90871
- return normalizeAppUrl(rawValue);
90872
- }
90873
- function requireApiBaseUrl(config) {
90874
- return deriveInternalBaseUrls(requireAppBaseUrl(config)).apiBaseUrl;
90875
- }
90876
- function requireChatBaseUrl(config) {
90877
- return deriveInternalBaseUrls(requireAppBaseUrl(config)).chatBaseUrl;
90878
- }
90879
- const ConfigServiceLive = succeed$2(ConfigServiceTag, {
90880
- load: () => {
90881
- cachedConfig ??= readConfigFile();
90882
- return cloneConfig(cachedConfig);
90883
- },
90884
- save: (config, currentConfig) => {
90885
- const current = currentConfig ?? cachedConfig ?? readConfigFile();
90886
- const merged = cloneConfig({
90887
- ...current,
90888
- ...config
90889
- });
90890
- cachedConfig = merged;
90891
- if (isSameConfig(current, merged)) {
90892
- return;
90893
- }
90894
- fs__namespace.mkdirSync(CONFIG_DIR$2, { recursive: true });
90895
- fs__namespace.writeFileSync(CONFIG_FILE, JSON.stringify(merged, null, 2));
90896
- }
90897
- });
90898
- const ConfigService = ConfigServiceTag;
89852
+ });
89853
+ const ConfigService = ConfigServiceTag;
90899
89854
 
90900
89855
  var properLockfile = {exports: {}};
90901
89856
 
@@ -93791,6 +92746,7 @@ const CLI_FLAG_PATTERN = /(\-\-(?:access-token|refresh-token|token|secret|client
93791
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;
93792
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;
93793
92748
  const AUTH_HEADER_PATTERN = /(Authorization\s*:\s*(?:Bearer|Basic)\s+)([^\s,;]+)/gi;
92749
+ const BEARER_PATTERN = /(\bBearer\s+)([^\s,;]+)/gi;
93794
92750
  const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/gi;
93795
92751
  function normalizeKey(value) {
93796
92752
  return value.replace(/[^a-z0-9]/gi, "").toLowerCase();
@@ -93903,6 +92859,7 @@ function sanitizeOAuthAuthorizeUrlForDisplay(value) {
93903
92859
  function maskSensitiveText(value) {
93904
92860
  let masked = value;
93905
92861
  masked = masked.replace(AUTH_HEADER_PATTERN, `$1${REDACTED_VALUE}`);
92862
+ masked = masked.replace(BEARER_PATTERN, `$1${REDACTED_VALUE}`);
93906
92863
  masked = masked.replace(CLI_FLAG_PATTERN, `$1${REDACTED_VALUE}`);
93907
92864
  masked = masked.replace(HIGH_RISK_KEY_VALUE_PATTERN, `$1${REDACTED_VALUE}`);
93908
92865
  masked = masked.replace(KEY_VALUE_PATTERN, `$1${REDACTED_VALUE}`);
@@ -93963,31 +92920,270 @@ function maskSensitiveData(value, options = {}, context = {}) {
93963
92920
  masked[key] = maskDictionaryString(entry, options);
93964
92921
  continue;
93965
92922
  }
93966
- if (isFullyRedactedKey(key)) {
93967
- if (entry !== null && typeof entry === "object") {
93968
- masked[key] = maskSensitiveData(entry, options, {
93969
- key,
93970
- forceMaskPrimitives: true
93971
- });
93972
- } else {
93973
- 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();
93974
93050
  }
93975
- continue;
93976
- }
93977
- if (normalizedKey === MASKED_COMMAND_KEY && typeof entry === "string") {
93978
- masked[key] = entry;
93979
- continue;
93980
- }
93981
- if (normalizedKey === COMMAND_KEY && typeof entry === "string") {
93982
- masked[key] = maskSensitiveText(entry);
93983
- continue;
93051
+ return id;
93984
93052
  }
93985
- masked[key] = maskSensitiveData(entry, options, {
93986
- key,
93987
- 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(() => {
93988
93182
  });
93183
+ void response?.body?.cancel().catch(() => {
93184
+ });
93185
+ if (acquired) await release(lease);
93989
93186
  }
93990
- return masked;
93991
93187
  }
93992
93188
 
93993
93189
  const CALLBACK_HOST = "127.0.0.1";
@@ -94007,13 +93203,18 @@ const CALLBACK_RESPONSE_HEADERS$1 = {
94007
93203
  Connection: "close"
94008
93204
  };
94009
93205
  class OAuthRequestError extends Error {
93206
+ _tag = "OAuthRequestError";
94010
93207
  statusCode;
94011
93208
  code;
94012
- constructor(message, statusCode, code) {
94013
- 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." : ""));
94014
93213
  this.name = "OAuthRequestError";
94015
93214
  this.statusCode = statusCode;
94016
- 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;
94017
93218
  }
94018
93219
  }
94019
93220
  function generateState$1() {
@@ -94026,6 +93227,7 @@ function trimTrailingSlash(value) {
94026
93227
  return value.replace(/\/+$/, "");
94027
93228
  }
94028
93229
  function toError$1(error, fallbackMessage) {
93230
+ if (error instanceof OAuthRequestError) return error;
94029
93231
  return error instanceof Error ? new Error(maskSensitiveText(error.message)) : new Error(maskSensitiveText(fallbackMessage));
94030
93232
  }
94031
93233
  function isRecord(value) {
@@ -94055,39 +93257,49 @@ function parseOAuthTokenResponse(value) {
94055
93257
  scope: optionalString(value["scope"])
94056
93258
  };
94057
93259
  }
94058
- async function fetchJson(input, init) {
94059
- const abortController = new AbortController();
94060
- const abortTimeout = setTimeout(() => abortController.abort(), OAUTH_REQUEST_TIMEOUT_MS);
94061
- let response;
93260
+ async function fetchJson(input, init, parse = (value) => value) {
94062
93261
  try {
94063
- 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 });
94064
93286
  } catch (error) {
94065
- if (abortController.signal.aborted) {
93287
+ if (error instanceof OAuthRequestError) throw error;
93288
+ if (error instanceof HttpRequestError && error.code === "CLI_REQUEST_TIMEOUT") {
94066
93289
  throw new OAuthRequestError(
94067
93290
  `OAuth request timed out after ${OAUTH_REQUEST_TIMEOUT_SECONDS} seconds`,
94068
93291
  void 0,
94069
- "timeout"
93292
+ "timeout",
93293
+ { outcome: error.outcome, requestId: error.requestId }
94070
93294
  );
94071
93295
  }
94072
93296
  throw new OAuthRequestError(
94073
93297
  error instanceof Error ? maskSensitiveText(error.message) : "OAuth request failed",
94074
93298
  void 0,
94075
- "request_failed"
93299
+ "request_failed",
93300
+ error instanceof HttpRequestError ? { outcome: error.outcome, requestId: error.requestId } : {}
94076
93301
  );
94077
- } finally {
94078
- clearTimeout(abortTimeout);
94079
- }
94080
- if (!response.ok) {
94081
- let errorData = {};
94082
- try {
94083
- errorData = await response.json();
94084
- } catch {
94085
- }
94086
- const message = errorData.error_description ?? errorData.message ?? errorData.error ?? `HTTP ${response.status}: ${response.statusText}`;
94087
- const code = errorData.error ?? errorData.code;
94088
- throw new OAuthRequestError(maskSensitiveText(message), response.status, code);
94089
93302
  }
94090
- return await response.json();
94091
93303
  }
94092
93304
  async function discoverOAuthMetadata(apiBaseUrl) {
94093
93305
  const normalizedBaseUrl = trimTrailingSlash(apiBaseUrl);
@@ -94114,7 +93326,7 @@ async function discoverOAuthMetadata(apiBaseUrl) {
94114
93326
  }
94115
93327
  }
94116
93328
  async function registerCliOAuthClient(metadata) {
94117
- const response = await fetchJson(metadata.registrationEndpoint, {
93329
+ return fetchJson(metadata.registrationEndpoint, {
94118
93330
  method: "POST",
94119
93331
  headers: {
94120
93332
  "Content-Type": "application/json"
@@ -94128,13 +93340,11 @@ async function registerCliOAuthClient(metadata) {
94128
93340
  token_endpoint_auth_method: "none",
94129
93341
  scope: OAUTH_SCOPE
94130
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 };
94131
93347
  });
94132
- if (!response.client_id) {
94133
- throw new Error("OAuth client registration did not return client_id");
94134
- }
94135
- return {
94136
- clientId: response.client_id
94137
- };
94138
93348
  }
94139
93349
  function generatePkcePair() {
94140
93350
  const verifier = toBase64Url(crypto__namespace.randomBytes(64));
@@ -94175,14 +93385,13 @@ async function exchangeAuthorizationCode(input) {
94175
93385
  code: input.code,
94176
93386
  code_verifier: input.codeVerifier
94177
93387
  });
94178
- const response = await fetchJson(input.tokenEndpoint, {
93388
+ return fetchJson(input.tokenEndpoint, {
94179
93389
  method: "POST",
94180
93390
  headers: {
94181
93391
  "Content-Type": "application/x-www-form-urlencoded"
94182
93392
  },
94183
93393
  body
94184
- });
94185
- return parseOAuthTokenResponse(response);
93394
+ }, parseOAuthTokenResponse);
94186
93395
  }
94187
93396
  async function refreshOAuthToken(input) {
94188
93397
  const body = new URLSearchParams({
@@ -94190,14 +93399,13 @@ async function refreshOAuthToken(input) {
94190
93399
  client_id: input.clientId,
94191
93400
  refresh_token: input.refreshToken
94192
93401
  });
94193
- const response = await fetchJson(input.tokenEndpoint, {
93402
+ return fetchJson(input.tokenEndpoint, {
94194
93403
  method: "POST",
94195
93404
  headers: {
94196
93405
  "Content-Type": "application/x-www-form-urlencoded"
94197
93406
  },
94198
93407
  body
94199
- });
94200
- return parseOAuthTokenResponse(response);
93408
+ }, parseOAuthTokenResponse);
94201
93409
  }
94202
93410
  function tokenExpiresAt(now, expiresInSeconds, fallbackMs) {
94203
93411
  return now + (expiresInSeconds === void 0 ? fallbackMs : expiresInSeconds * 1e3);
@@ -94242,330 +93450,1159 @@ const OAUTH_RESULT_PAGE = {
94242
93450
  title: "Authentication successful",
94243
93451
  message: "You can close this window."
94244
93452
  },
94245
- error: {
94246
- title: "Authentication failed",
94247
- message: 'Check the terminal, then run "aipctl auth login" again.'
94248
- }
94249
- };
94250
- function buildOAuthResultHtml(variant) {
94251
- const { title, message } = OAUTH_RESULT_PAGE[variant];
94252
- return `
94253
- <!DOCTYPE html>
94254
- <html lang="en">
94255
- <head>
94256
- <meta charset="utf-8" />
94257
- <meta name="viewport" content="width=device-width, initial-scale=1" />
94258
- <title>${title}</title>
94259
- <style>
94260
- :root {
94261
- color-scheme: light dark;
94262
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
94263
- --background: #ffffff;
94264
- --foreground: #171717;
94265
- --muted-foreground: #737373;
94266
- background: var(--background);
94267
- color: var(--foreground);
94268
- }
94269
- @media (prefers-color-scheme: dark) {
94270
- :root {
94271
- --background: #171717;
94272
- --foreground: #fafafa;
94273
- --muted-foreground: #a3a3a3;
94274
- }
94275
- }
94276
- * { box-sizing: border-box; }
94277
- body {
94278
- margin: 0;
94279
- min-height: 100vh;
94280
- min-height: 100svh;
94281
- display: grid;
94282
- place-items: center;
94283
- padding: 24px;
94284
- background: var(--background);
94285
- color: var(--foreground);
94286
- }
94287
- main {
94288
- max-width: 48rem;
94289
- text-align: center;
94290
- }
94291
- h1 {
94292
- margin: 0;
94293
- font-size: clamp(1.75rem, 5vw, 2.5rem);
94294
- font-weight: 600;
94295
- line-height: 1.15;
94296
- letter-spacing: -0.03em;
94297
- }
94298
- p {
94299
- margin: 1rem 0 0;
94300
- color: var(--muted-foreground);
94301
- font-size: 1rem;
94302
- line-height: 1.6;
94303
- }
94304
- </style>
94305
- </head>
94306
- <body data-variant="${variant}">
94307
- <main aria-labelledby="result-title">
94308
- <h1 id="result-title">${title}</h1>
94309
- <p>${message}</p>
94310
- </main>
94311
- </body>
94312
- </html>
94313
- `;
94314
- }
94315
- const successHtml$1 = buildOAuthResultHtml("success");
94316
- const errorHtml$1 = buildOAuthResultHtml("error");
94317
- function createServerCloser$1(server) {
94318
- let closePromise;
94319
- return () => {
94320
- if (!closePromise) {
94321
- closePromise = new Promise((resolve) => {
94322
- if (!server.listening) {
94323
- resolve();
94324
- return;
94325
- }
94326
- let settled = false;
94327
- const finish = () => {
94328
- if (settled) {
94329
- return;
94330
- }
94331
- settled = true;
94332
- clearTimeout(forceCloseTimeout);
94333
- resolve();
94334
- };
94335
- const forceCloseTimeout = setTimeout(() => {
94336
- server.closeAllConnections?.();
94337
- finish();
94338
- }, CALLBACK_SERVER_CLOSE_TIMEOUT_MS$1);
94339
- server.close(finish);
94340
- server.closeIdleConnections?.();
94341
- });
94342
- }
94343
- return closePromise;
94344
- };
94345
- }
94346
- async function listenOnCallbackPort$1(server) {
94347
- await new Promise((resolve, reject) => {
94348
- let settled = false;
94349
- const onError = (error) => {
94350
- if (settled) {
94351
- return;
94352
- }
94353
- settled = true;
94354
- server.off("error", onError);
94355
- if (error.code === "EADDRINUSE") {
94356
- reject(new Error(CALLBACK_PORT_IN_USE_MESSAGE$1));
94357
- return;
94358
- }
94359
- reject(error);
94360
- };
94361
- server.on("error", onError);
94362
- server.listen(CALLBACK_PORT, CALLBACK_HOST, () => {
94363
- if (settled) {
94364
- return;
94365
- }
94366
- settled = true;
94367
- server.off("error", onError);
94368
- resolve();
94369
- });
94370
- });
94371
- }
94372
- const startOAuthFlow = gen(function* () {
94373
- const config = yield* ConfigService;
94374
- const credentials = yield* CredentialService;
94375
- const apiBaseUrl = yield* try_({
94376
- try: () => requireApiBaseUrl(config.load()),
94377
- catch: (error) => toError$1(error, "App URL validation failed")
94378
- });
94379
- const pkce = generatePkcePair();
94380
- const state = generateState$1();
94381
- const deferred = yield* make$m();
94382
- const server = Http__namespace.createServer((req, res) => {
94383
- const url = new URL(req.url || "/", CALLBACK_URL);
94384
- if (url.pathname !== CALLBACK_PATH) {
94385
- res.writeHead(404);
94386
- res.end("Not Found");
94387
- return;
94388
- }
94389
- try {
94390
- const callback = parseOAuthCallback(url.searchParams, state);
94391
- res.writeHead(200, CALLBACK_RESPONSE_HEADERS$1);
94392
- res.end(successHtml$1);
94393
- runSync(succeed$5(deferred, callback));
94394
- } catch (error) {
94395
- res.writeHead(400, CALLBACK_RESPONSE_HEADERS$1);
94396
- res.end(errorHtml$1);
94397
- runSync(fail$4(deferred, toError$1(error, "Authentication failed")));
94398
- } finally {
94399
- void closeServer();
94400
- }
94401
- });
94402
- const closeServer = createServerCloser$1(server);
94403
- yield* tryPromise({
94404
- try: () => listenOnCallbackPort$1(server),
94405
- catch: (error) => toError$1(error, "Failed to start OAuth callback server")
94406
- });
94407
- return yield* gen(function* () {
94408
- const metadata = yield* tryPromise({
94409
- try: () => discoverOAuthMetadata(apiBaseUrl),
94410
- catch: (error) => toError$1(error, "OAuth metadata discovery failed")
94411
- });
94412
- const registration = yield* tryPromise({
94413
- try: () => registerCliOAuthClient(metadata),
94414
- catch: (error) => toError$1(error, "OAuth client registration failed")
94415
- });
94416
- const authorizeUrl = buildAuthorizeUrl({
94417
- authorizationEndpoint: metadata.authorizationEndpoint,
94418
- clientId: registration.clientId,
94419
- state,
94420
- codeChallenge: pkce.challenge
94421
- });
94422
- yield* sync$1(() => {
94423
- console.log("Opening browser for login...");
94424
- console.log(`If browser doesn't open, visit: ${sanitizeOAuthAuthorizeUrlForDisplay(authorizeUrl)}`);
94425
- void open(authorizeUrl).catch(() => void 0);
94426
- });
94427
- const callback = yield* raceFirst(
94428
- _await(deferred),
94429
- sleep$1("5 minutes").pipe(flatMap$5(() => fail$3(new Error("Login timeout"))))
94430
- );
94431
- yield* sync$1(() => {
94432
- console.log("Authorization received. Exchanging token...");
94433
- });
94434
- const tokenResponse = yield* tryPromise({
94435
- try: () => exchangeAuthorizationCode({
94436
- tokenEndpoint: metadata.tokenEndpoint,
94437
- clientId: registration.clientId,
94438
- code: callback.code,
94439
- codeVerifier: pkce.verifier
94440
- }),
94441
- catch: (error) => toError$1(error, "OAuth token exchange failed")
94442
- });
94443
- const nextCredentials = toCredentialsFromTokenResponse({
94444
- tokenResponse,
94445
- clientId: registration.clientId,
94446
- issuer: metadata.issuer
94447
- });
94448
- credentials.save(nextCredentials);
94449
- return nextCredentials;
94450
- }).pipe(ensuring$1(promise$1(() => closeServer())));
94451
- });
94452
-
94453
- const MAX_CONCURRENCY = 3;
94454
- const MAX_RATE_REQUESTS = 10;
94455
- const RATE_WINDOW_MS = 5e3;
94456
- const POLL_INTERVAL_MS = 300;
94457
- const CONFIG_DIR = path__namespace.join(os__namespace.homedir(), ".config", "aip");
94458
- const STATE_FILE = path__namespace.join(CONFIG_DIR, "rate-limit.json");
94459
- function pruneOldRequests(recentRequests, now = Date.now()) {
94460
- return recentRequests.filter((ts) => now - new Date(ts).getTime() < RATE_WINDOW_MS);
94461
- }
94462
- function pruneDeadSlots(slots) {
94463
- return slots.filter((slot) => {
94464
- try {
94465
- process.kill(slot.pid, 0);
94466
- return true;
94467
- } catch {
94468
- return false;
94469
- }
94470
- });
94471
- }
94472
- function getRateLimitWaitMs(recentRequests, now = Date.now()) {
94473
- const active = pruneOldRequests(recentRequests, now);
94474
- if (active.length < MAX_RATE_REQUESTS) return 0;
94475
- const oldestMs = Math.min(...active.map((ts) => new Date(ts).getTime()));
94476
- return oldestMs + RATE_WINDOW_MS - now;
94477
- }
94478
- function ensureConfigDir() {
94479
- fs__namespace.mkdirSync(CONFIG_DIR, { recursive: true });
94480
- }
94481
- function readState() {
94482
- try {
94483
- const raw = fs__namespace.readFileSync(STATE_FILE, "utf-8");
94484
- return JSON.parse(raw);
94485
- } catch {
94486
- return { slots: [], recentRequests: [] };
94487
- }
94488
- }
94489
- function writeState(state) {
94490
- fs__namespace.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
94491
- }
94492
- async function withLock(fn) {
94493
- ensureConfigDir();
94494
- if (!fs__namespace.existsSync(STATE_FILE)) {
94495
- writeState({ slots: [], recentRequests: [] });
94496
- }
94497
- const release2 = await lockfile.lock(STATE_FILE, {
94498
- retries: { retries: 20, minTimeout: 50, maxTimeout: 200 },
94499
- stale: 5e3
94500
- });
94501
- try {
94502
- return fn();
94503
- } finally {
94504
- await release2();
94505
- }
94506
- }
94507
- async function release() {
94508
- try {
94509
- await withLock(() => {
94510
- const state = readState();
94511
- state.slots = state.slots.filter((s) => s.pid !== process.pid);
94512
- writeState(state);
94513
- });
94514
- } catch {
94515
- 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");
94516
- }
94517
- }
94518
- async function acquire() {
94519
- let waitStart = null;
94520
- while (true) {
94521
- let concurrencyFull = false;
94522
- let rateLimitWaitMs = 0;
94523
- try {
94524
- await withLock(() => {
94525
- const state = readState();
94526
- state.slots = pruneDeadSlots(state.slots);
94527
- const now = Date.now();
94528
- state.recentRequests = pruneOldRequests(state.recentRequests, now);
94529
- if (state.slots.length >= MAX_CONCURRENCY) {
94530
- concurrencyFull = true;
94531
- writeState(state);
94532
- return;
94533
- }
94534
- rateLimitWaitMs = getRateLimitWaitMs(state.recentRequests, now);
94535
- if (rateLimitWaitMs > 0) {
94536
- writeState(state);
94537
- return;
94538
- }
94539
- state.slots.push({ pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString() });
94540
- state.recentRequests.push((/* @__PURE__ */ new Date()).toISOString());
94541
- writeState(state);
94542
- });
94543
- } catch {
94544
- process.stderr.write("\n[Rate limit] \uB77D \uD68D\uB4DD \uC2E4\uD328. \uC7A0\uC2DC \uD6C4 \uC7AC\uC2DC\uB3C4\uD569\uB2C8\uB2E4...\n");
94545
- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
94546
- continue;
94547
- }
94548
- if (!concurrencyFull && rateLimitWaitMs === 0) {
94549
- if (waitStart !== null) {
94550
- process.stderr.write("\r" + " ".repeat(80) + "\r");
94551
- }
94552
- return;
94553
- }
94554
- if (waitStart === null) waitStart = Date.now();
94555
- const elapsed = Math.floor((Date.now() - waitStart) / 1e3);
94556
- if (concurrencyFull) {
94557
- process.stderr.write(
94558
- `\r[Rate limit] \uB3D9\uC2DC \uC2E4\uD589: ${MAX_CONCURRENCY}/${MAX_CONCURRENCY} | \uC2AC\uB86F \uB300\uAE30 \uC911... (${elapsed}\uCD08 \uACBD\uACFC)`
94559
- );
94560
- } else if (rateLimitWaitMs > 0) {
94561
- const remainSec = Math.ceil(rateLimitWaitMs / 1e3);
94562
- process.stderr.write(
94563
- `\r[Rate limit] \uC694\uCCAD \uD55C\uB3C4 \uCD08\uACFC (${MAX_RATE_REQUESTS}/${RATE_WINDOW_MS / 1e3}\uCD08) | ${remainSec}\uCD08 \uD6C4 \uC7AC\uC2DC\uB3C4...`
94564
- );
94565
- }
94566
- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
94567
- }
94568
- }
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
+ ];
94569
94606
 
94570
94607
  class ApiError extends TaggedError$1("ApiError") {
94571
94608
  }
@@ -94598,6 +94635,14 @@ function apiErrorFromUnknown(error, fallbackMessage) {
94598
94635
  if (error instanceof ApiError) {
94599
94636
  return error;
94600
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
+ }
94601
94646
  return createApiError({
94602
94647
  message: error instanceof Error ? error.message : fallbackMessage
94603
94648
  });
@@ -94608,6 +94653,7 @@ class AgentChatStreamIncompleteError extends Error {
94608
94653
  this.sawOnlyTerminalEnvelope = sawOnlyTerminalEnvelope;
94609
94654
  this.name = "AgentChatStreamIncompleteError";
94610
94655
  }
94656
+ _tag = "AgentChatStreamIncompleteError";
94611
94657
  }
94612
94658
  function normalizeAutomationPagination(pagination) {
94613
94659
  return {
@@ -94698,14 +94744,6 @@ function normalizeSharedUserList(sharedUserList) {
94698
94744
  return { userId, userName };
94699
94745
  });
94700
94746
  }
94701
- async function rateLimitedFetch(input, init) {
94702
- await acquire();
94703
- try {
94704
- return await fetch(input, init);
94705
- } finally {
94706
- await release();
94707
- }
94708
- }
94709
94747
  async function sleep(ms) {
94710
94748
  await new Promise((resolve) => setTimeout(resolve, ms));
94711
94749
  }
@@ -94713,7 +94751,8 @@ async function toApiError(response) {
94713
94751
  let errorData = {};
94714
94752
  try {
94715
94753
  errorData = await response.json();
94716
- } catch {
94754
+ } catch (error) {
94755
+ if (error instanceof HttpRequestError) throw error;
94717
94756
  }
94718
94757
  const code = errorData.code ?? errorData.errorCode;
94719
94758
  const details = isCliQuotaErrorCode(code) ? parseCliQuotaErrorDetails(errorData.details, code) : void 0;
@@ -94723,7 +94762,8 @@ async function toApiError(response) {
94723
94762
  statusCode: response.status,
94724
94763
  code,
94725
94764
  ...details ? { details } : {},
94726
- ...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) } : {}
94727
94767
  });
94728
94768
  }
94729
94769
  function isCliQuotaErrorCode(code) {
@@ -94791,29 +94831,23 @@ function parseRetryAfterSeconds(value) {
94791
94831
  return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : void 0;
94792
94832
  }
94793
94833
  const makeRequest = (baseUrl, path, accessToken, options) => tryPromise({
94794
- try: async () => {
94834
+ try: async (signal) => {
94795
94835
  const resolvedBaseUrl = typeof baseUrl === "function" ? baseUrl() : baseUrl;
94796
- const response = await rateLimitedFetch(`${resolvedBaseUrl}${path}`, {
94836
+ return withHttpResponse(`${resolvedBaseUrl}${path}`, {
94797
94837
  method: options?.method || "GET",
94798
94838
  headers: jsonBearerHeaders(accessToken),
94799
94839
  body: options?.body ? JSON.stringify(options.body) : void 0
94800
- });
94801
- if (!response.ok) {
94802
- throw await toApiError(response);
94803
- }
94804
- if (options?.skipJsonParse || response.status === 202 || response.status === 204) {
94805
- return void 0;
94806
- }
94807
- 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 } : {} });
94808
94849
  },
94809
- catch: (error) => {
94810
- if (error instanceof ApiError) {
94811
- return error;
94812
- }
94813
- return createApiError({
94814
- message: error instanceof Error ? error.message : "Unknown error"
94815
- });
94816
- }
94850
+ catch: (error) => apiErrorFromUnknown(error, "The request could not be completed.")
94817
94851
  });
94818
94852
  const getSseData = (line) => {
94819
94853
  if (!line.startsWith("data:")) {
@@ -94948,6 +94982,14 @@ const makeApiServiceLive = (buildEnv) => effect$1(
94948
94982
  });
94949
94983
  const requireApiBaseUrlEffect = () => requireConfiguredBaseUrlEffect(loadConfiguredApiBaseUrl);
94950
94984
  const requireChatBaseUrlEffect = () => requireConfiguredBaseUrlEffect(loadConfiguredChatBaseUrl);
94985
+ const presetPath = (presetId, orgSlug) => try_({
94986
+ try: () => {
94987
+ const slug = orgSlug ?? configService.load().currentOrganization?.slug;
94988
+ if (!slug) throw new Error("No organization selected. Use --org or select an organization.");
94989
+ return `/api/cli/v1/organizations/${encodeURIComponent(slug)}/admin/presets/${encodeURIComponent(presetId)}`;
94990
+ },
94991
+ catch: configuredBaseUrlError
94992
+ });
94951
94993
  const toRefreshFailure = (error) => {
94952
94994
  if (error instanceof ApiError || error instanceof NotLoggedInError) {
94953
94995
  return error;
@@ -94959,7 +95001,9 @@ const makeApiServiceLive = (buildEnv) => effect$1(
94959
95001
  return createApiError({
94960
95002
  message: error.message,
94961
95003
  statusCode: error.statusCode,
94962
- code: error.code
95004
+ code: error.code,
95005
+ outcome: error.outcome,
95006
+ requestId: error.requestId
94963
95007
  });
94964
95008
  }
94965
95009
  return createApiError({
@@ -95058,21 +95102,23 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95058
95102
  const resolvedChatBaseUrl = yield* requireChatBaseUrlEffect();
95059
95103
  const path = `/api/${encodeURIComponent(orgSlug)}/conversations/${encodeURIComponent(conversationId)}/stream`;
95060
95104
  return yield* tryPromise({
95061
- try: async () => {
95105
+ try: async (signal) => {
95106
+ const deadline = Date.now() + TRANSFER_DEADLINE_MS;
95062
95107
  for (let attempt = 1; attempt <= AGENT_CHAT_STREAM_MAX_ATTEMPTS; attempt += 1) {
95063
- const response = await rateLimitedFetch(`${resolvedChatBaseUrl}${path}`, {
95064
- method: "POST",
95065
- headers: jsonBearerHeaders(token),
95066
- body: JSON.stringify({})
95067
- });
95068
- if (!response.ok) {
95069
- throw await toApiError(response);
95070
- }
95071
- if (!response.body) {
95072
- throw createApiError({ message: "No response body from agent chat stream endpoint" });
95073
- }
95074
95108
  try {
95075
- 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()) });
95076
95122
  } catch (error) {
95077
95123
  if (error instanceof AgentChatStreamIncompleteError && error.sawOnlyTerminalEnvelope && attempt < AGENT_CHAT_STREAM_MAX_ATTEMPTS) {
95078
95124
  await sleep(AGENT_CHAT_STREAM_RETRY_DELAY_MS);
@@ -95086,11 +95132,13 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95086
95132
  catch: (error) => {
95087
95133
  if (error instanceof ApiError) return error;
95088
95134
  if (error instanceof AgentChatStreamIncompleteError) {
95089
- 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
+ });
95090
95140
  }
95091
- return createApiError({
95092
- message: error instanceof Error ? error.message : "Agent chat failed"
95093
- });
95141
+ return apiErrorFromUnknown(error, "Agent chat failed");
95094
95142
  }
95095
95143
  });
95096
95144
  });
@@ -95118,6 +95166,13 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95118
95166
  return conversation.agentInstallationId;
95119
95167
  });
95120
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
+ }),
95121
95176
  listOrganizations: () => gen(function* () {
95122
95177
  const token = yield* getAccessToken();
95123
95178
  yield* requireReleaseEnabledOperation("listCliOrganizations");
@@ -95195,19 +95250,17 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95195
95250
  });
95196
95251
  }),
95197
95252
  uploadToS3: (uploadUrl, headers, fileBuffer) => tryPromise({
95198
- try: async () => {
95199
- const response = await fetch(uploadUrl, {
95200
- method: "PUT",
95201
- headers,
95202
- body: fileBuffer
95203
- });
95253
+ try: async (signal) => withHttpResponse(uploadUrl, {
95254
+ method: "PUT",
95255
+ headers,
95256
+ body: fileBuffer
95257
+ }, async (response) => {
95204
95258
  if (!response.ok) {
95205
- throw new Error(`S3 upload failed: ${response.status} ${response.statusText}`);
95259
+ throw createApiError({ message: `S3 upload failed: ${response.status}`, statusCode: response.status });
95206
95260
  }
95207
- },
95208
- catch: (error) => createApiError({
95209
- message: error instanceof Error ? error.message : "S3 upload failed"
95210
- })
95261
+ await response.arrayBuffer();
95262
+ }, { signal, timeoutMs: TRANSFER_DEADLINE_MS, localAdmission: false }),
95263
+ catch: (error) => apiErrorFromUnknown(error, "S3 upload failed")
95211
95264
  }),
95212
95265
  completeUpload: (orgSlug, skillId, overwrite) => gen(function* () {
95213
95266
  const token = yield* getAccessToken();
@@ -95340,17 +95393,14 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95340
95393
  });
95341
95394
  }),
95342
95395
  downloadFromUrl: (url) => tryPromise({
95343
- try: async () => {
95344
- const response = await fetch(url);
95396
+ try: async (signal) => withHttpResponse(url, {}, async (response) => {
95345
95397
  if (!response.ok) {
95346
- throw new Error(`Download failed: ${response.status} ${response.statusText}`);
95398
+ throw createApiError({ message: `Download failed: ${response.status}`, statusCode: response.status });
95347
95399
  }
95348
95400
  const arrayBuffer = await response.arrayBuffer();
95349
95401
  return Buffer.from(arrayBuffer);
95350
- },
95351
- catch: (error) => createApiError({
95352
- message: error instanceof Error ? error.message : "Download failed"
95353
- })
95402
+ }, { signal, timeoutMs: TRANSFER_DEADLINE_MS, maxResponseBytes: TRANSFER_MAX_RESPONSE_BYTES, localAdmission: false }),
95403
+ catch: (error) => apiErrorFromUnknown(error, "Download failed")
95354
95404
  }),
95355
95405
  listLibrarySkills: (orgSlug, options) => gen(function* () {
95356
95406
  const token = yield* getAccessToken();
@@ -95522,7 +95572,8 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95522
95572
  const path = `/api/cli/v1/organizations/${encodeURIComponent(orgSlug)}/model-exec/chat`;
95523
95573
  return yield* makeRequest(chatBaseUrl, path, token, {
95524
95574
  method: "POST",
95525
- body
95575
+ body,
95576
+ timeoutMs: TRANSFER_DEADLINE_MS + 1e4
95526
95577
  });
95527
95578
  }),
95528
95579
  executeModelExecImageGeneration: (orgSlug, body) => gen(function* () {
@@ -95741,20 +95792,16 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95741
95792
  const token = yield* getAccessToken();
95742
95793
  const path = `/web/admin/organizations/slug/${encodeURIComponent(orgSlug)}/installed-agents/${encodeURIComponent(agentId)}/export`;
95743
95794
  return yield* tryPromise({
95744
- try: async () => {
95745
- const response = await rateLimitedFetch(`${resolvedApiBaseUrl}${path}`, {
95746
- headers: bearerHeaders(token)
95747
- });
95795
+ try: async (signal) => withHttpResponse(`${resolvedApiBaseUrl}${path}`, {
95796
+ headers: bearerHeaders(token)
95797
+ }, async (response) => {
95748
95798
  if (!response.ok) {
95749
95799
  throw await toApiError(response);
95750
95800
  }
95751
95801
  const arrayBuffer = await response.arrayBuffer();
95752
95802
  return Buffer.from(arrayBuffer);
95753
- },
95754
- catch: (error) => {
95755
- if (error instanceof ApiError) return error;
95756
- return createApiError({ message: error instanceof Error ? error.message : "Export failed" });
95757
- }
95803
+ }, { signal, timeoutMs: TRANSFER_DEADLINE_MS, maxResponseBytes: TRANSFER_MAX_RESPONSE_BYTES }),
95804
+ catch: (error) => apiErrorFromUnknown(error, "Export failed")
95758
95805
  });
95759
95806
  }),
95760
95807
  getInstalledAgentShare: (orgSlug, agentId) => gen(function* () {
@@ -95776,9 +95823,39 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95776
95823
  yield* requireReleaseEnabledOperation("listCliAgentTemplates");
95777
95824
  const path = `/api/cli/v1/organizations/${encodeURIComponent(orgSlug)}/agents/templates`;
95778
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;
95779
95830
  let page = 1;
95780
95831
  while (true) {
95781
- 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
+ }
95782
95859
  templates.push(...raw.list);
95783
95860
  if (raw.list.length === 0 || page * raw.pagination.pageSize >= raw.pagination.total) break;
95784
95861
  page += 1;
@@ -95908,7 +95985,8 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95908
95985
  // Tunnel management
95909
95986
  getTunnelStatus: (orgSlug) => gen(function* () {
95910
95987
  const token = yield* getAccessToken();
95911
- const path = `/api/web/edge-tunnel/v2/organizations/slug/${encodeURIComponent(orgSlug)}/status`;
95988
+ yield* requireReleaseEnabledOperation("getCliTunnelStatus");
95989
+ const path = `/api/cli/v1/organizations/${encodeURIComponent(orgSlug)}/admin/tunnel/status`;
95912
95990
  return yield* makeRequest(baseUrl, path, token);
95913
95991
  }),
95914
95992
  getTunnelConfig: (orgSlug) => gen(function* () {
@@ -95922,49 +96000,60 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95922
96000
  return yield* makeRequest(baseUrl, path, token, { method: "POST" });
95923
96001
  }),
95924
96002
  // Preset management
95925
- listPresets: (orgSlug) => gen(function* () {
96003
+ listPresets: (orgSlug, page = 1, pageSize = 100) => gen(function* () {
95926
96004
  const token = yield* getAccessToken();
95927
- const path = `/api/web/presets/v2?organizationSlug=${encodeURIComponent(orgSlug)}`;
95928
- return yield* makeRequest(baseUrl, path, token);
96005
+ yield* requireReleaseEnabledOperation("listCliPresets");
96006
+ const path = `/api/cli/v1/organizations/${encodeURIComponent(orgSlug)}/admin/presets?page=${page}&pageSize=${pageSize}`;
96007
+ const response = yield* makeRequest(baseUrl, path, token);
96008
+ return response.list;
95929
96009
  }),
95930
- getPreset: (presetId) => gen(function* () {
96010
+ getPreset: (presetId, orgSlug) => gen(function* () {
95931
96011
  const token = yield* getAccessToken();
95932
- const path = `/api/web/presets/${encodeURIComponent(presetId)}`;
96012
+ yield* requireReleaseEnabledOperation("getCliPreset");
96013
+ const path = yield* presetPath(presetId, orgSlug);
95933
96014
  return yield* makeRequest(baseUrl, path, token);
95934
96015
  }),
95935
96016
  createPreset: (body) => gen(function* () {
95936
96017
  const token = yield* getAccessToken();
95937
- return yield* makeRequest(baseUrl, "/api/web/presets/v2", token, {
96018
+ yield* requireReleaseEnabledOperation("createCliPreset");
96019
+ const { organizationSlug, ...request } = body;
96020
+ const path = `/api/cli/v1/organizations/${encodeURIComponent(organizationSlug)}/admin/presets`;
96021
+ return yield* makeRequest(baseUrl, path, token, {
95938
96022
  method: "POST",
95939
- body
96023
+ body: request
95940
96024
  });
95941
96025
  }),
95942
- updatePreset: (presetId, body) => gen(function* () {
96026
+ updatePreset: (presetId, body, orgSlug) => gen(function* () {
95943
96027
  const token = yield* getAccessToken();
95944
- const path = `/api/web/presets/${encodeURIComponent(presetId)}`;
96028
+ yield* requireReleaseEnabledOperation("updateCliPreset");
96029
+ const path = yield* presetPath(presetId, orgSlug);
95945
96030
  return yield* makeRequest(baseUrl, path, token, { method: "PUT", body });
95946
96031
  }),
95947
- renamePreset: (presetId, name) => gen(function* () {
96032
+ renamePreset: (presetId, name, orgSlug) => gen(function* () {
95948
96033
  const token = yield* getAccessToken();
95949
- const path = `/api/web/presets/${encodeURIComponent(presetId)}`;
96034
+ yield* requireReleaseEnabledOperation("updateCliPresetName");
96035
+ const path = yield* presetPath(presetId, orgSlug);
95950
96036
  return yield* makeRequest(baseUrl, path, token, {
95951
96037
  method: "PATCH",
95952
96038
  body: { name }
95953
96039
  });
95954
96040
  }),
95955
- deletePreset: (presetId) => gen(function* () {
96041
+ deletePreset: (presetId, orgSlug) => gen(function* () {
95956
96042
  const token = yield* getAccessToken();
95957
- const path = `/api/web/presets/${encodeURIComponent(presetId)}`;
96043
+ yield* requireReleaseEnabledOperation("deleteCliPreset");
96044
+ const path = yield* presetPath(presetId, orgSlug);
95958
96045
  return yield* makeRequest(baseUrl, path, token, { method: "DELETE", skipJsonParse: true });
95959
96046
  }),
95960
- setPresetAsDefault: (presetId) => gen(function* () {
96047
+ setPresetAsDefault: (presetId, orgSlug) => gen(function* () {
95961
96048
  const token = yield* getAccessToken();
95962
- const path = `/api/web/presets/${encodeURIComponent(presetId)}/default`;
95963
- return yield* makeRequest(baseUrl, path, token, { method: "POST" });
96049
+ yield* requireReleaseEnabledOperation("updateCliDefaultPreset");
96050
+ const path = `${yield* presetPath(presetId, orgSlug)}/default`;
96051
+ return yield* makeRequest(baseUrl, path, token, { method: "PUT" });
95964
96052
  }),
95965
- unsetPresetAsDefault: (presetId) => gen(function* () {
96053
+ unsetPresetAsDefault: (presetId, orgSlug) => gen(function* () {
95966
96054
  const token = yield* getAccessToken();
95967
- const path = `/api/web/presets/${encodeURIComponent(presetId)}/default`;
96055
+ yield* requireReleaseEnabledOperation("deleteCliDefaultPreset");
96056
+ const path = `${yield* presetPath(presetId, orgSlug)}/default`;
95968
96057
  return yield* makeRequest(baseUrl, path, token, { method: "DELETE" });
95969
96058
  }),
95970
96059
  regenPresetKey: (presetId) => gen(function* () {
@@ -95980,29 +96069,33 @@ const makeApiServiceLive = (buildEnv) => effect$1(
95980
96069
  // Org member management
95981
96070
  inviteOrgMembers: (req) => gen(function* () {
95982
96071
  const token = yield* getAccessToken();
95983
- return yield* makeRequest(baseUrl, `/api/web/organizations/slug/${encodeURIComponent(req.organizationSlug)}/invite`, token, {
96072
+ yield* requireReleaseEnabledOperation("createCliOrganizationMemberInvitations");
96073
+ return yield* makeRequest(baseUrl, `/api/cli/v1/organizations/${encodeURIComponent(req.organizationSlug)}/members/invitations`, token, {
95984
96074
  method: "POST",
95985
96075
  body: { emails: req.emails, role: req.role }
95986
96076
  });
95987
96077
  }),
95988
96078
  removeOrgMembers: (req) => gen(function* () {
95989
96079
  const token = yield* getAccessToken();
95990
- yield* makeRequest(baseUrl, `/api/web/organizations/slug/${encodeURIComponent(req.organizationSlug)}/members`, token, {
96080
+ yield* requireReleaseEnabledOperation("deleteCliOrganizationMembers");
96081
+ yield* makeRequest(baseUrl, `/api/cli/v1/organizations/${encodeURIComponent(req.organizationSlug)}/members`, token, {
95991
96082
  method: "DELETE",
95992
96083
  body: { members: req.members }
95993
96084
  });
95994
96085
  }),
95995
96086
  updateOrgMemberRoles: (req) => gen(function* () {
95996
96087
  const token = yield* getAccessToken();
95997
- yield* makeRequest(baseUrl, `/api/web/organizations/slug/${encodeURIComponent(req.organizationSlug)}/members`, token, {
96088
+ yield* requireReleaseEnabledOperation("updateCliOrganizationMemberRoles");
96089
+ yield* makeRequest(baseUrl, `/api/cli/v1/organizations/${encodeURIComponent(req.organizationSlug)}/members/role`, token, {
95998
96090
  method: "PUT",
95999
96091
  body: { members: req.members, role: req.role }
96000
96092
  });
96001
96093
  }),
96002
96094
  exitOrg: (slug) => gen(function* () {
96003
96095
  const token = yield* getAccessToken();
96004
- yield* makeRequest(baseUrl, `/api/web/organizations/slug/${encodeURIComponent(slug)}/exit`, token, {
96005
- method: "POST"
96096
+ yield* requireReleaseEnabledOperation("deleteCliOrganizationMembership");
96097
+ yield* makeRequest(baseUrl, `/api/cli/v1/organizations/${encodeURIComponent(slug)}/membership`, token, {
96098
+ method: "DELETE"
96006
96099
  });
96007
96100
  }),
96008
96101
  // Agent headless chat
@@ -96023,6 +96116,305 @@ const makeApiServiceLive = (buildEnv) => effect$1(
96023
96116
  const ApiServiceLive = makeApiServiceLive(BUILD_ENV);
96024
96117
  const ApiService = ApiServiceTag;
96025
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
+
96026
96418
  const orgOption = text("org").pipe(
96027
96419
  withDescription$3("Organization slug (overrides current organization)"),
96028
96420
  optional
@@ -96959,13 +97351,13 @@ const deleteCommand$4 = make$4(
96959
97351
  { id: idArg$7, org: orgOption, force: forceOption$5 },
96960
97352
  ({ id, org, force }) => gen(function* () {
96961
97353
  const api = yield* ApiService;
96962
- yield* resolveOrgSlug(org, api);
97354
+ const orgSlug = yield* resolveOrgSlug(org, api);
96963
97355
  if (!force) {
96964
97356
  yield* log(`Warning: This will permanently delete preset "${id}".`);
96965
97357
  yield* log("Use --force (-f) to skip this confirmation.");
96966
97358
  return;
96967
97359
  }
96968
- yield* api.deletePreset(id).pipe(
97360
+ yield* api.deletePreset(id, orgSlug).pipe(
96969
97361
  catchTag(
96970
97362
  "NotLoggedInError",
96971
97363
  (e) => gen(function* () {
@@ -96998,8 +97390,8 @@ const getCommand$6 = make$4(
96998
97390
  { id: idArg$6, org: orgOption, json: jsonOption$h },
96999
97391
  ({ id, org, json }) => gen(function* () {
97000
97392
  const api = yield* ApiService;
97001
- yield* resolveOrgSlug(org, api);
97002
- const preset = yield* api.getPreset(id).pipe(
97393
+ const orgSlug = yield* resolveOrgSlug(org, api);
97394
+ const preset = yield* api.getPreset(id, orgSlug).pipe(
97003
97395
  catchTag(
97004
97396
  "NotLoggedInError",
97005
97397
  (e) => gen(function* () {
@@ -97054,11 +97446,19 @@ function formatPresetListPrompt(prompt) {
97054
97446
  }
97055
97447
  const listCommand$9 = make$4(
97056
97448
  "list",
97057
- { org: orgOption, json: jsonOption$g },
97058
- ({ org, json }) => gen(function* () {
97449
+ {
97450
+ org: orgOption,
97451
+ json: jsonOption$g,
97452
+ page: integer("page").pipe(withDescription$3("Page number, starting at 1"), withDefault(1)),
97453
+ pageSize: integer("pageSize").pipe(withDescription$3("Presets per page (1\u2013100)"), withDefault(100))
97454
+ },
97455
+ ({ org, json, page, pageSize }) => gen(function* () {
97456
+ if (page < 1 || pageSize < 1 || pageSize > 100) {
97457
+ return yield* fail$3(new ApiError({ message: "Use --page 1 or higher and --pageSize between 1 and 100." }));
97458
+ }
97059
97459
  const api = yield* ApiService;
97060
97460
  const orgSlug = yield* resolveOrgSlug(org, api);
97061
- const result = yield* api.listPresets(orgSlug).pipe(
97461
+ const result = yield* api.listPresets(orgSlug, page, pageSize).pipe(
97062
97462
  catchTag(
97063
97463
  "NotLoggedInError",
97064
97464
  (e) => gen(function* () {
@@ -97079,10 +97479,10 @@ const listCommand$9 = make$4(
97079
97479
  return;
97080
97480
  }
97081
97481
  if (result.length === 0) {
97082
- yield* log("No presets found.");
97482
+ yield* log(`No presets found on page ${page}.`);
97083
97483
  return;
97084
97484
  }
97085
- yield* log(`Presets in organization "${orgSlug}":
97485
+ yield* log(`Presets in organization "${orgSlug}" (page ${page}):
97086
97486
  `);
97087
97487
  for (const preset of result) {
97088
97488
  const defaultMark = preset.isDefault ? " (default)" : "";
@@ -97158,8 +97558,8 @@ const renameCommand$1 = make$4(
97158
97558
  { id: idArg$3, name: nameArg$1, org: orgOption },
97159
97559
  ({ id, name, org }) => gen(function* () {
97160
97560
  const api = yield* ApiService;
97161
- yield* resolveOrgSlug(org, api);
97162
- yield* api.renamePreset(id, name).pipe(
97561
+ const orgSlug = yield* resolveOrgSlug(org, api);
97562
+ yield* api.renamePreset(id, name, orgSlug).pipe(
97163
97563
  catchTag(
97164
97564
  "NotLoggedInError",
97165
97565
  (e) => gen(function* () {
@@ -97185,8 +97585,8 @@ const setDefaultCommand = make$4(
97185
97585
  { id: idArg$2, org: orgOption },
97186
97586
  ({ id, org }) => gen(function* () {
97187
97587
  const api = yield* ApiService;
97188
- yield* resolveOrgSlug(org, api);
97189
- yield* api.setPresetAsDefault(id).pipe(
97588
+ const orgSlug = yield* resolveOrgSlug(org, api);
97589
+ yield* api.setPresetAsDefault(id, orgSlug).pipe(
97190
97590
  catchTag(
97191
97591
  "NotLoggedInError",
97192
97592
  (e) => gen(function* () {
@@ -97212,8 +97612,8 @@ const unsetDefaultCommand = make$4(
97212
97612
  { id: idArg$1, org: orgOption },
97213
97613
  ({ id, org }) => gen(function* () {
97214
97614
  const api = yield* ApiService;
97215
- yield* resolveOrgSlug(org, api);
97216
- yield* api.unsetPresetAsDefault(id).pipe(
97615
+ const orgSlug = yield* resolveOrgSlug(org, api);
97616
+ yield* api.unsetPresetAsDefault(id, orgSlug).pipe(
97217
97617
  catchTag(
97218
97618
  "NotLoggedInError",
97219
97619
  (e) => gen(function* () {
@@ -97242,7 +97642,7 @@ const updateCommand$1 = make$4(
97242
97642
  { id: idArg, jsonFile: jsonFileArg$2, org: orgOption },
97243
97643
  ({ id, jsonFile, org }) => gen(function* () {
97244
97644
  const api = yield* ApiService;
97245
- yield* resolveOrgSlug(org, api);
97645
+ const orgSlug = yield* resolveOrgSlug(org, api);
97246
97646
  const body = yield* try_({
97247
97647
  try: () => {
97248
97648
  const content = fs__namespace.readFileSync(jsonFile, "utf-8");
@@ -97257,7 +97657,7 @@ const updateCommand$1 = make$4(
97257
97657
  })
97258
97658
  )
97259
97659
  );
97260
- yield* api.updatePreset(id, body).pipe(
97660
+ yield* api.updatePreset(id, body, orgSlug).pipe(
97261
97661
  catchTag(
97262
97662
  "NotLoggedInError",
97263
97663
  (e) => gen(function* () {
@@ -98987,15 +99387,16 @@ function loginEffect(authFlow, organizationSelection = _void) {
98987
99387
  return gen(function* () {
98988
99388
  yield* log("Starting login flow...");
98989
99389
  const nextCredentials = yield* authFlow.pipe(
98990
- catchAll(
98991
- (error) => gen(function* () {
99390
+ catchAll((error) => {
99391
+ if (error instanceof OAuthRequestError) return fail$3(error);
99392
+ return gen(function* () {
98992
99393
  yield* error$1(`Login failed: ${error.message}`);
98993
99394
  yield* sync$1(() => {
98994
99395
  process.exitCode = 1;
98995
99396
  });
98996
99397
  return null;
98997
- })
98998
- )
99398
+ });
99399
+ })
98999
99400
  );
99000
99401
  if (!nextCredentials) {
99001
99402
  return;
@@ -101628,6 +102029,43 @@ const skillCommand = make$4("skill", {}).pipe(
101628
102029
  withSubcommands(skillSubcommands)
101629
102030
  );
101630
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
+
101631
102069
  const mainCommandDescription = "AIP command-line interface for managing organizations, skills, and native MCP commands";
101632
102070
  const rootSubcommands = [
101633
102071
  adminCommand,
@@ -101641,6 +102079,7 @@ const rootSubcommands = [
101641
102079
  modelCommand,
101642
102080
  modelExecCommand,
101643
102081
  orgCommand,
102082
+ quotaCommand,
101644
102083
  skillCommand,
101645
102084
  ...nativeSubcommands
101646
102085
  ];
@@ -101664,6 +102103,7 @@ const HELP_GROUPS = [
101664
102103
  { path: ["model-exec"], description: modelExecCommandDescription, subcommands: modelExecSubcommands },
101665
102104
  { path: ["model-exec", "image"], description: imageCommandDescription, subcommands: imageSubcommands },
101666
102105
  { path: ["org"], description: orgCommandDescription, subcommands: orgSubcommands },
102106
+ { path: ["quota"], description: quotaCommandDescription, subcommands: quotaSubcommands },
101667
102107
  { path: ["skill"], description: skillCommandDescription, subcommands: skillSubcommands },
101668
102108
  { path: ["admin", "org"], description: adminOrgCommandDescription, subcommands: adminOrgSubcommands },
101669
102109
  { path: ["admin", "agent"], description: adminAgentCommandDescription, subcommands: adminAgentSubcommands },
@@ -101767,6 +102207,7 @@ const runNativeHelpIfRequested = (args, options = {}) => {
101767
102207
  };
101768
102208
 
101769
102209
  const args = process.argv.slice(2);
102210
+ const json = jsonOutputRequested(args);
101770
102211
  const unavailableMessage = getUnavailableCommandMessage(args, BUILD_ENV);
101771
102212
  if (unavailableMessage) {
101772
102213
  process.stderr.write(`${unavailableMessage}
@@ -101795,5 +102236,6 @@ const argv = [
101795
102236
  cli(argv).pipe(
101796
102237
  provide$1(AppLayer),
101797
102238
  provide$1(layer),
101798
- runMain
102239
+ (program) => withCliFailureOutput(program, json),
102240
+ runMain({ teardown: cliTeardown(json) })
101799
102241
  );