@seaveyon/harness-switch 0.26.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7061,6 +7061,7 @@ var ERROR_CODES = {
7061
7061
  adapterModelRequired: "adapter.modelRequired",
7062
7062
  adapterApiKeyRequired: "adapter.apiKeyRequired",
7063
7063
  officialLoginUnsupported: "activation.officialLoginUnsupported",
7064
+ officialLoginMissing: "activation.officialLoginMissing",
7064
7065
  noActiveProfile: "activation.noActiveProfile",
7065
7066
  officialProfileCannotAdopt: "activation.officialProfileCannotAdopt",
7066
7067
  adoptUnsupported: "activation.adoptUnsupported",
@@ -7209,6 +7210,167 @@ var en_default = {
7209
7210
  switchHarness: "Switch harness"
7210
7211
  },
7211
7212
  harness: {
7213
+ field: {
7214
+ toggle: {
7215
+ on: "On",
7216
+ off: "Off"
7217
+ },
7218
+ providerId: {
7219
+ label: "Provider ID (optional)",
7220
+ placeholder: "Defaults to the profile name"
7221
+ },
7222
+ contextLength: {
7223
+ label: "Context length"
7224
+ },
7225
+ maxTokens: {
7226
+ label: "Max output tokens"
7227
+ },
7228
+ claude: {
7229
+ authVar: {
7230
+ label: "Credential variable",
7231
+ help: "Third-party relays usually require ANTHROPIC_AUTH_TOKEN; use ANTHROPIC_API_KEY for an official API key.",
7232
+ option: {
7233
+ authToken: "ANTHROPIC_AUTH_TOKEN (third-party relay)",
7234
+ official: "ANTHROPIC_API_KEY (official)"
7235
+ }
7236
+ },
7237
+ haikuModel: {
7238
+ label: "Haiku model mapping"
7239
+ },
7240
+ sonnetModel: {
7241
+ label: "Sonnet model mapping"
7242
+ },
7243
+ opusModel: {
7244
+ label: "Opus model mapping"
7245
+ },
7246
+ fableModel: {
7247
+ label: "Fable model mapping (optional)",
7248
+ help: "Written to ANTHROPIC_DEFAULT_FABLE_MODEL, for newer Claude Code builds that support the Fable tier."
7249
+ },
7250
+ subagentModel: {
7251
+ label: "Subagent model (optional)",
7252
+ help: "Written to CLAUDE_CODE_SUBAGENT_MODEL, so subagents can use a faster or cheaper model."
7253
+ },
7254
+ haikuModelName: {
7255
+ label: "Haiku display name (optional)"
7256
+ },
7257
+ sonnetModelName: {
7258
+ label: "Sonnet display name (optional)"
7259
+ },
7260
+ opusModelName: {
7261
+ label: "Opus display name (optional)"
7262
+ },
7263
+ fableModelName: {
7264
+ label: "Fable display name (optional)"
7265
+ },
7266
+ modelMapping: {
7267
+ help: "Written to {{envVar}}."
7268
+ },
7269
+ modelName: {
7270
+ help: "Written to {{envVar}}; left empty, Claude Code shows the model ID itself.",
7271
+ placeholder: "Leave empty to use the {{role}} model ID"
7272
+ },
7273
+ example: {
7274
+ placeholder: "e.g. {{value}}"
7275
+ },
7276
+ extraEnv: {
7277
+ label: "Extra environment variables (optional)",
7278
+ help: "One KEY=VALUE per line, merged into the env block of settings.json."
7279
+ },
7280
+ oneM: {
7281
+ subagentLabel: "Declare 1M support for subagents",
7282
+ label: "Declare 1M support for {{role}}",
7283
+ help: "Appends [1m] to the model ID to declare a 1M context window to Claude Code, which strips the suffix before calling the provider. Enable it only when the model really supports 1M."
7284
+ }
7285
+ },
7286
+ codex: {
7287
+ envNote: "Only the environment-variable auth mode needs env.sh; the other modes keep their credential inside config.toml.",
7288
+ authMode: {
7289
+ label: "Authentication mode",
7290
+ help: "auth.json is Codex's own login cache. Overwriting it loses the ChatGPT session, so it is left alone by default.",
7291
+ option: {
7292
+ bearerToken: "Write to config.toml (recommended, keeps official login)",
7293
+ envKey: "Environment variable (requires sourcing env.sh)",
7294
+ openaiAuth: "Write to auth.json (overwrites the ChatGPT login cache)"
7295
+ }
7296
+ },
7297
+ providerId: {
7298
+ help: "openai, ollama, lmstudio, amazon-bedrock and similar are reserved by Codex and get renamed automatically."
7299
+ },
7300
+ envKeyName: {
7301
+ label: "Environment variable name",
7302
+ help: "Only used by the environment-variable mode."
7303
+ },
7304
+ reasoningEffort: {
7305
+ label: "Reasoning effort (optional)",
7306
+ option: {
7307
+ unset: "Not set"
7308
+ }
7309
+ },
7310
+ target: {
7311
+ auth: "auth.json (auth.json mode only)"
7312
+ }
7313
+ },
7314
+ kimi: {
7315
+ envNote: "Kimi Code does not read credentials from the shell, so env.sh has no effect on it.",
7316
+ providerType: {
7317
+ label: "Provider type",
7318
+ help: "Decides which protocol implementation Kimi Code uses.",
7319
+ option: {
7320
+ kimi: "kimi (Moonshot / Kimi Code)"
7321
+ }
7322
+ },
7323
+ maxContextSize: {
7324
+ help: "Kimi Code requires every models entry to declare max_context_size."
7325
+ }
7326
+ },
7327
+ pi: {
7328
+ envNote: "The API key is written straight into models.json, so no environment variable is needed; --model still overrides at run time.",
7329
+ providerId: {
7330
+ help: "Models are referenced as provider/model."
7331
+ },
7332
+ api: {
7333
+ label: "Protocol"
7334
+ },
7335
+ authHeader: {
7336
+ label: "Authorization header",
7337
+ help: "Sent as Authorization: Bearer <key>."
7338
+ },
7339
+ reasoning: {
7340
+ label: "Reasoning support",
7341
+ help: "Maps to reasoning in models.json. Enable it for thinking models such as GPT or Claude."
7342
+ }
7343
+ },
7344
+ dsh: {
7345
+ envNote: "The API key is written securely to DSH's .credentials.yaml and referenced from settings.yaml.",
7346
+ providerType: {
7347
+ label: "Provider type",
7348
+ option: {
7349
+ custom: "Custom provider",
7350
+ official: "DeepSeek official"
7351
+ }
7352
+ },
7353
+ providerId: {
7354
+ help: "DSH's model routing identifier; it must start with a lowercase letter."
7355
+ },
7356
+ models: {
7357
+ label: "Model catalog (optional)",
7358
+ placeholder: "One model ID per line; left empty, only the default model above is registered",
7359
+ help: "One provider can register several models; the Model field above is the default for new sessions."
7360
+ },
7361
+ api: {
7362
+ label: "API protocol"
7363
+ },
7364
+ reasoningEfforts: {
7365
+ label: "Supported reasoning levels",
7366
+ help: "DSH only shows the levels declared here that the upstream model actually supports.",
7367
+ option: {
7368
+ unset: "Not declared (provider default)",
7369
+ none: "Model does not support reasoning levels"
7370
+ }
7371
+ }
7372
+ }
7373
+ },
7212
7374
  subtitle: "Manage profiles and safely write this tool's native configuration files.",
7213
7375
  newProfile: "New profile",
7214
7376
  addCustomProvider: "Add custom provider",
@@ -7245,6 +7407,7 @@ var en_default = {
7245
7407
  officialSwitch: "Back to official",
7246
7408
  officialHintClaude: "Use Claude Code's own Anthropic account login",
7247
7409
  officialHintCodex: "Use Codex's own ChatGPT / OpenAI account login",
7410
+ officialHintKimi: "Use Kimi Code's own Kimi account login (the OAuth credential written by /login)",
7248
7411
  application: "Application",
7249
7412
  writeMode: "Write mode",
7250
7413
  modeReplace: "Replace current configuration",
@@ -7376,12 +7539,18 @@ var en_default = {
7376
7539
  },
7377
7540
  activate: {
7378
7541
  title: "Activate profile?",
7542
+ officialTitle: "Return to official login?",
7379
7543
  body: 'This switches {{harness}} to "{{profile}}" and writes its native configuration files{{changed}}. Target local user: {{user}}. A backup is taken first.',
7544
+ officialBody: "This returns {{harness}} to its official login and writes its native configuration files{{changed}}. Target local user: {{user}}. A backup is taken first.",
7380
7545
  changedFiles_one: ", of which {{count}} file will change",
7381
7546
  changedFiles_other: ", of which {{count}} files will change",
7382
7547
  loadFailed: "Could not read the content to be written: {{reason}}",
7383
7548
  loading: "Loading the content to be written…",
7384
- confirm: "Confirm activation"
7549
+ confirm: "Confirm activation",
7550
+ executing: "Writing…",
7551
+ failed: "Writing failed: {{reason}}. The configuration was not switched; fix the issue and retry.",
7552
+ retry: "Retry activation",
7553
+ retryPreview: "Reload preview"
7385
7554
  },
7386
7555
  env: {
7387
7556
  title: "Environment file compatibility",
@@ -7504,12 +7673,7 @@ var en_default = {
7504
7673
  }
7505
7674
  },
7506
7675
  notice: {
7507
- title: "Written to disk",
7508
- close: "Close",
7509
- activated: '{{harness}} switched to "{{profile}}" (user: {{user}}); its native configuration files have been written.',
7510
- activatedHint: "Claude Code picks this up immediately; Codex, Kimi Code and Pi need a restart.",
7511
- officialRestored: "{{harness}} switched back to its official login (user: {{user}}); the third-party API route was removed from the native configuration.",
7512
- officialHint: "If you have not logged in yet, start the tool in a terminal and complete its official login once.",
7676
+ switchDone: "Switch complete",
7513
7677
  warningPrefix: "Note: {{message}}",
7514
7678
  currentUser: "the current user",
7515
7679
  transferImported: "Import finished.",
@@ -7592,6 +7756,7 @@ var en_default = {
7592
7756
  },
7593
7757
  activation: {
7594
7758
  officialLoginUnsupported: "{{harness}} does not support official account login",
7759
+ officialLoginMissing: "No official login entry was found for {{harness}}; complete its official login in a terminal once first",
7595
7760
  noActiveProfile: "This tool has no active profile, so there is nothing to render",
7596
7761
  officialProfileCannotAdopt: "The official login is active, so there is no profile to adopt into",
7597
7762
  adoptUnsupported: "This tool cannot adopt a live configuration",
@@ -7953,6 +8118,167 @@ var zh_CN_default = {
7953
8118
  switchHarness: "切换 Harness"
7954
8119
  },
7955
8120
  harness: {
8121
+ field: {
8122
+ toggle: {
8123
+ on: "开启",
8124
+ off: "关闭"
8125
+ },
8126
+ providerId: {
8127
+ label: "Provider ID(可选)",
8128
+ placeholder: "默认取配置名称"
8129
+ },
8130
+ contextLength: {
8131
+ label: "上下文长度"
8132
+ },
8133
+ maxTokens: {
8134
+ label: "最大输出 tokens"
8135
+ },
8136
+ claude: {
8137
+ authVar: {
8138
+ label: "凭据变量",
8139
+ help: "第三方中转通常要求 ANTHROPIC_AUTH_TOKEN;官方 API key 用 ANTHROPIC_API_KEY。",
8140
+ option: {
8141
+ authToken: "ANTHROPIC_AUTH_TOKEN(第三方中转)",
8142
+ official: "ANTHROPIC_API_KEY(官方)"
8143
+ }
8144
+ },
8145
+ haikuModel: {
8146
+ label: "Haiku 模型映射"
8147
+ },
8148
+ sonnetModel: {
8149
+ label: "Sonnet 模型映射"
8150
+ },
8151
+ opusModel: {
8152
+ label: "Opus 模型映射"
8153
+ },
8154
+ fableModel: {
8155
+ label: "Fable 模型映射(可选)",
8156
+ help: "写入 ANTHROPIC_DEFAULT_FABLE_MODEL;用于支持 Fable 档位的新版 Claude Code。"
8157
+ },
8158
+ subagentModel: {
8159
+ label: "子代理模型(可选)",
8160
+ help: "写入 CLAUDE_CODE_SUBAGENT_MODEL,可让子代理使用更快或成本更低的模型。"
8161
+ },
8162
+ haikuModelName: {
8163
+ label: "Haiku 显示名称(选填)"
8164
+ },
8165
+ sonnetModelName: {
8166
+ label: "Sonnet 显示名称(选填)"
8167
+ },
8168
+ opusModelName: {
8169
+ label: "Opus 显示名称(选填)"
8170
+ },
8171
+ fableModelName: {
8172
+ label: "Fable 显示名称(选填)"
8173
+ },
8174
+ modelMapping: {
8175
+ help: "写入 {{envVar}}。"
8176
+ },
8177
+ modelName: {
8178
+ help: "写入 {{envVar}};留空时 Claude Code 默认显示对应模型 ID。",
8179
+ placeholder: "留空则使用 {{role}} 模型 ID"
8180
+ },
8181
+ example: {
8182
+ placeholder: "例如:{{value}}"
8183
+ },
8184
+ extraEnv: {
8185
+ label: "追加环境变量(可选)",
8186
+ help: "每行一个 KEY=VALUE,会合并进 settings.json 的 env。"
8187
+ },
8188
+ oneM: {
8189
+ subagentLabel: "子代理 声明支持 1M",
8190
+ label: "{{role}} 声明支持 1M",
8191
+ help: "在模型 ID 末尾追加 [1m],向 Claude Code 声明 1M 上下文;Claude Code 请求上游前会去掉该后缀。仅在该模型确实支持 1M 时开启。"
8192
+ }
8193
+ },
8194
+ codex: {
8195
+ envNote: "仅「环境变量」认证模式需要 env.sh,其余模式的凭据自包含在 config.toml 里。",
8196
+ authMode: {
8197
+ label: "认证方式",
8198
+ help: "auth.json 就是 Codex 的登录缓存,覆盖它会丢失 ChatGPT 登录态,所以默认不碰它。",
8199
+ option: {
8200
+ bearerToken: "写入 config.toml(推荐,保留官方登录)",
8201
+ envKey: "环境变量(需要 source env.sh)",
8202
+ openaiAuth: "写入 auth.json(会覆盖 ChatGPT 登录缓存)"
8203
+ }
8204
+ },
8205
+ providerId: {
8206
+ help: "openai / ollama / lmstudio / amazon-bedrock 等是 Codex 保留字,会自动改名。"
8207
+ },
8208
+ envKeyName: {
8209
+ label: "环境变量名",
8210
+ help: "仅「环境变量」模式生效。"
8211
+ },
8212
+ reasoningEffort: {
8213
+ label: "推理强度(可选)",
8214
+ option: {
8215
+ unset: "不设置"
8216
+ }
8217
+ },
8218
+ target: {
8219
+ auth: "auth.json(仅 auth.json 模式)"
8220
+ }
8221
+ },
8222
+ kimi: {
8223
+ envNote: "Kimi Code 不从 shell 读取凭据,env.sh 对它无效。",
8224
+ providerType: {
8225
+ label: "Provider 类型",
8226
+ help: "决定 Kimi Code 使用哪套协议实现。",
8227
+ option: {
8228
+ kimi: "kimi(Moonshot / Kimi Code)"
8229
+ }
8230
+ },
8231
+ maxContextSize: {
8232
+ help: "Kimi Code 要求 models 条目必须声明 max_context_size。"
8233
+ }
8234
+ },
8235
+ pi: {
8236
+ envNote: "API key 直接写入 models.json,无需环境变量;运行时仍可用 --model 覆盖。",
8237
+ providerId: {
8238
+ help: "模型引用格式为 provider/model。"
8239
+ },
8240
+ api: {
8241
+ label: "协议"
8242
+ },
8243
+ authHeader: {
8244
+ label: "Authorization 头",
8245
+ help: "以 Authorization: Bearer <key> 发送。"
8246
+ },
8247
+ reasoning: {
8248
+ label: "推理能力",
8249
+ help: "对应 models.json 的 reasoning。GPT / Claude 思考模型需要开启。"
8250
+ }
8251
+ },
8252
+ dsh: {
8253
+ envNote: "API key 安全写入 DSH 的 .credentials.yaml,并由 settings.yaml 引用。",
8254
+ providerType: {
8255
+ label: "提供方类型",
8256
+ option: {
8257
+ custom: "自定义提供方",
8258
+ official: "DeepSeek 官方"
8259
+ }
8260
+ },
8261
+ providerId: {
8262
+ help: "DSH 的模型路由标识;必须以小写字母开头。"
8263
+ },
8264
+ models: {
8265
+ label: "模型目录(可选)",
8266
+ placeholder: "每行一个模型 ID;留空时只注册上方的默认模型",
8267
+ help: "一个提供方可注册多个模型;上方“模型”作为新会话的默认模型。"
8268
+ },
8269
+ api: {
8270
+ label: "API 协议"
8271
+ },
8272
+ reasoningEfforts: {
8273
+ label: "支持的思考程度",
8274
+ help: "DSH 只会显示这里声明且上游模型实际支持的档位。",
8275
+ option: {
8276
+ unset: "不声明(提供方默认)",
8277
+ none: "模型不支持思考程度"
8278
+ }
8279
+ }
8280
+ }
8281
+ },
7956
8282
  subtitle: "管理配置档案并安全写入该工具的原生配置文件。",
7957
8283
  newProfile: "新增配置",
7958
8284
  addCustomProvider: "添加自定义提供方",
@@ -7989,6 +8315,7 @@ var zh_CN_default = {
7989
8315
  officialSwitch: "切回官方",
7990
8316
  officialHintClaude: "使用 Claude Code 自身的 Anthropic 账号登录",
7991
8317
  officialHintCodex: "使用 Codex 自身的 ChatGPT / OpenAI 账号登录",
8318
+ officialHintKimi: "使用 Kimi Code 自身的 Kimi 账号登录(/login 写入的 OAuth 凭据)",
7992
8319
  application: "应用",
7993
8320
  writeMode: "写入模式",
7994
8321
  modeReplace: "替换当前配置",
@@ -8120,12 +8447,18 @@ var zh_CN_default = {
8120
8447
  },
8121
8448
  activate: {
8122
8449
  title: "激活配置?",
8450
+ officialTitle: "切回官方登录?",
8123
8451
  body: "将把 {{harness}} 切换到「{{profile}}」并写入原生配置文件{{changed}}。目标本地用户:{{user}}。写入前会自动备份。",
8452
+ officialBody: "将把 {{harness}} 切回官方登录并写入原生配置文件{{changed}}。目标本地用户:{{user}}。写入前会自动备份。",
8124
8453
  changedFiles_one: ",其中 {{count}} 个文件将变更",
8125
8454
  changedFiles_other: ",其中 {{count}} 个文件将变更",
8126
8455
  loadFailed: "无法读取将要写入的内容:{{reason}}",
8127
8456
  loading: "正在读取将要写入的内容…",
8128
- confirm: "确认激活"
8457
+ confirm: "确认激活",
8458
+ executing: "正在写入…",
8459
+ failed: "写入失败:{{reason}}。配置未切换,请修正后重试。",
8460
+ retry: "重试激活",
8461
+ retryPreview: "重新读取预览"
8129
8462
  },
8130
8463
  env: {
8131
8464
  title: "环境变量文件兼容性",
@@ -8248,12 +8581,7 @@ var zh_CN_default = {
8248
8581
  }
8249
8582
  },
8250
8583
  notice: {
8251
- title: "已写入磁盘",
8252
- close: "关闭",
8253
- activated: "{{harness}} 已切换到「{{profile}}」(用户:{{user}}),原生配置文件已写入。",
8254
- activatedHint: "Claude Code 会立即生效;Codex、Kimi Code、Pi 需要重新启动进程。",
8255
- officialRestored: "{{harness}} 已切回官方登录(用户:{{user}}),第三方 API 路由已从原生配置中移除。",
8256
- officialHint: "如尚未登录,请在终端启动对应工具并完成一次官方登录。",
8584
+ switchDone: "切换完成",
8257
8585
  warningPrefix: "注意:{{message}}",
8258
8586
  currentUser: "当前用户",
8259
8587
  transferImported: "导入完成。",
@@ -8336,6 +8664,7 @@ var zh_CN_default = {
8336
8664
  },
8337
8665
  activation: {
8338
8666
  officialLoginUnsupported: "{{harness}} 不支持官方账号登录模式",
8667
+ officialLoginMissing: "未检测到 {{harness}} 的官方登录条目,请先在终端完成一次官方登录",
8339
8668
  noActiveProfile: "该工具未激活任何配置,无可渲染的内容",
8340
8669
  officialProfileCannotAdopt: "当前处于官方登录状态,没有可回填的配置档案",
8341
8670
  adoptUnsupported: "该工具不支持采纳现场配置",
@@ -22959,7 +23288,7 @@ var extrasSchema = exports_external.record(mapKey, optionalText(MAX_EXTRA_VALUE)
22959
23288
  var overridesSchema = exports_external.record(mapKey, optionalText(MAX_OVERRIDE));
22960
23289
  var conflictPolicySchema = exports_external.enum(["skip", "overwrite"]);
22961
23290
  var loginRequestSchema = exports_external.object({
22962
- password: optionalText(MAX_KEY)
23291
+ password: exports_external.string().trim().min(1, "password 不能为空").max(MAX_KEY)
22963
23292
  });
22964
23293
  var createProfileRequestSchema = exports_external.object({
22965
23294
  name: entityName,
@@ -24674,7 +25003,6 @@ function localizeMessage(language, code, data) {
24674
25003
  }
24675
25004
  return value.replace(/{{\s*([\w.]+)\s*}}/g, (_match, name) => data?.[name] === undefined ? "" : String(data[name]));
24676
25005
  }
24677
- var localizeError = localizeMessage;
24678
25006
  function getPath2(value, path) {
24679
25007
  return path.split(".").reduce((current, key) => {
24680
25008
  if (typeof current !== "object" || current === null || Array.isArray(current))
@@ -25485,12 +25813,16 @@ class AuthService {
25485
25813
  ensurePassword() {
25486
25814
  const file2 = this.environment.managerFiles.password;
25487
25815
  if (!this.files.exists(file2)) {
25488
- const password = this.crypto.randomPassword();
25489
- this.files.writeSecure(file2, `${password}
25816
+ const password2 = this.crypto.randomPassword();
25817
+ this.files.writeSecure(file2, `${password2}
25490
25818
  `);
25491
- this.log.info(`Initial web password: ${password}`);
25819
+ this.log.info(`Initial web password: ${password2}`);
25820
+ }
25821
+ const password = this.files.readText(file2).trim();
25822
+ if (!password) {
25823
+ throw new Error(`web password file is empty: ${file2}`);
25492
25824
  }
25493
- return this.files.readText(file2).trim();
25825
+ return password;
25494
25826
  }
25495
25827
  login(password) {
25496
25828
  const expected = this.ensurePassword();
@@ -25779,29 +26111,6 @@ import { basename as basename3, join as join8, resolve as resolve2 } from "node:
25779
26111
  // src/services/adapters/claude.ts
25780
26112
  import { join as join3 } from "node:path";
25781
26113
 
25782
- // src/services/adapters/detect.ts
25783
- function seedProfile(extras = {}) {
25784
- return { name: "", baseUrl: "", apiKey: "", model: "", extras };
25785
- }
25786
- function toCandidate(key, seed, values, active) {
25787
- const baseUrl = values.baseUrl ?? "";
25788
- const apiKey = values.apiKey ?? "";
25789
- if (!baseUrl && !apiKey) {
25790
- return null;
25791
- }
25792
- return {
25793
- key,
25794
- baseUrl,
25795
- apiKey,
25796
- model: values.model ?? "",
25797
- extras: { ...seed.extras, ...values.extras },
25798
- active
25799
- };
25800
- }
25801
- function compact(candidates) {
25802
- return candidates.filter((candidate) => candidate !== null);
25803
- }
25804
-
25805
26114
  // ../../node_modules/smol-toml/dist/date.js
25806
26115
  /*!
25807
26116
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -26884,6 +27193,13 @@ function parseJsonObject(text) {
26884
27193
  const parsed = JSON.parse(text);
26885
27194
  return isPlainObject2(parsed) ? parsed : {};
26886
27195
  }
27196
+ function tryParseJsonObject(text) {
27197
+ try {
27198
+ return parseJsonObject(text);
27199
+ } catch {
27200
+ return;
27201
+ }
27202
+ }
26887
27203
  function stringifyJson(value) {
26888
27204
  return `${JSON.stringify(value, null, 2)}
26889
27205
  `;
@@ -26895,6 +27211,13 @@ function parseTomlObject(text) {
26895
27211
  const parsed = parse6(text);
26896
27212
  return isPlainObject2(parsed) ? parsed : {};
26897
27213
  }
27214
+ function tryParseTomlObject(text) {
27215
+ try {
27216
+ return parseTomlObject(text);
27217
+ } catch {
27218
+ return;
27219
+ }
27220
+ }
26898
27221
  function stringifyToml(value) {
26899
27222
  return `${stringify(value)}
26900
27223
  `;
@@ -26906,6 +27229,13 @@ function parseYamlDocument(text) {
26906
27229
  }
26907
27230
  return document;
26908
27231
  }
27232
+ function tryParseYamlDocument(text) {
27233
+ try {
27234
+ return parseYamlDocument(text);
27235
+ } catch {
27236
+ return;
27237
+ }
27238
+ }
26909
27239
  function assertParsable(format, path, content) {
26910
27240
  try {
26911
27241
  if (format === "json") {
@@ -26948,6 +27278,13 @@ function readString(source, key) {
26948
27278
  const value = source[key];
26949
27279
  return typeof value === "string" ? value : "";
26950
27280
  }
27281
+ function numeric(raw2, fallback) {
27282
+ const parsed = Number(raw2);
27283
+ return Number.isFinite(parsed) && parsed > 0 ? Math.trunc(parsed) : fallback;
27284
+ }
27285
+ function valueString(value, fallback) {
27286
+ return typeof value === "number" && Number.isFinite(value) ? String(value) : fallback || "";
27287
+ }
26951
27288
  function slugify2(value, fallback) {
26952
27289
  const slug = value.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
26953
27290
  return slug || `${fallback}-${shortHash(value)}`;
@@ -26961,6 +27298,32 @@ function shortHash(value) {
26961
27298
  return (hash2 >>> 0).toString(36);
26962
27299
  }
26963
27300
 
27301
+ // src/services/adapters/detect.ts
27302
+ function providerId(profile) {
27303
+ return slugify2(profile.extras.providerId || profile.name, "provider");
27304
+ }
27305
+ function seedProfile(extras = {}) {
27306
+ return { name: "", baseUrl: "", apiKey: "", model: "", extras };
27307
+ }
27308
+ function toCandidate(key, seed, values, active) {
27309
+ const baseUrl = values.baseUrl ?? "";
27310
+ const apiKey = values.apiKey ?? "";
27311
+ if (!baseUrl && !apiKey) {
27312
+ return null;
27313
+ }
27314
+ return {
27315
+ key,
27316
+ baseUrl,
27317
+ apiKey,
27318
+ model: values.model ?? "",
27319
+ extras: { ...seed.extras, ...values.extras },
27320
+ active
27321
+ };
27322
+ }
27323
+ function compact(candidates) {
27324
+ return candidates.filter((candidate) => candidate !== null);
27325
+ }
27326
+
26964
27327
  // src/services/adapters/claude.ts
26965
27328
  var SETTINGS = "settings";
26966
27329
  var BASE_URL_VAR = "ANTHROPIC_BASE_URL";
@@ -26998,17 +27361,20 @@ var MODEL_MAPPINGS = [
26998
27361
  { field: "subagentModel", envVar: "CLAUDE_CODE_SUBAGENT_MODEL", oneMField: "subagentModel1m" }
26999
27362
  ];
27000
27363
  var ONE_M_OPTIONS = [
27001
- { value: "false", label: "关闭" },
27002
- { value: "true", label: "开启" }
27364
+ { value: "false", label: "关闭", labelCode: "harness.field.toggle.off" },
27365
+ { value: "true", label: "开启", labelCode: "harness.field.toggle.on" }
27003
27366
  ];
27004
- function oneMField(role, key) {
27367
+ function oneMField(role, key, labelCode) {
27005
27368
  return {
27006
27369
  key,
27007
27370
  label: `${role} 声明支持 1M`,
27371
+ labelCode: labelCode ?? "harness.field.claude.oneM.label",
27372
+ ...labelCode ? {} : { params: { role } },
27008
27373
  kind: "select",
27009
27374
  defaultValue: "false",
27010
27375
  options: ONE_M_OPTIONS,
27011
- help: "在模型 ID 末尾追加 [1m],向 Claude Code 声明 1M 上下文;Claude Code 请求上游前会去掉该后缀。仅在该模型确实支持 1M 时开启。"
27376
+ help: "在模型 ID 末尾追加 [1m],向 Claude Code 声明 1M 上下文;Claude Code 请求上游前会去掉该后缀。仅在该模型确实支持 1M 时开启。",
27377
+ helpCode: "harness.field.claude.oneM.help"
27012
27378
  };
27013
27379
  }
27014
27380
 
@@ -27026,92 +27392,140 @@ class ClaudeAdapter {
27026
27392
  {
27027
27393
  key: "authVar",
27028
27394
  label: "凭据变量",
27395
+ labelCode: "harness.field.claude.authVar.label",
27029
27396
  kind: "select",
27030
27397
  defaultValue: "ANTHROPIC_AUTH_TOKEN",
27031
27398
  help: "第三方中转通常要求 ANTHROPIC_AUTH_TOKEN;官方 API key 用 ANTHROPIC_API_KEY。",
27399
+ helpCode: "harness.field.claude.authVar.help",
27032
27400
  fullWidth: true,
27033
27401
  options: [
27034
- { value: "ANTHROPIC_AUTH_TOKEN", label: "ANTHROPIC_AUTH_TOKEN(第三方中转)" },
27035
- { value: "ANTHROPIC_API_KEY", label: "ANTHROPIC_API_KEY(官方)" }
27402
+ {
27403
+ value: "ANTHROPIC_AUTH_TOKEN",
27404
+ label: "ANTHROPIC_AUTH_TOKEN(第三方中转)",
27405
+ labelCode: "harness.field.claude.authVar.option.authToken"
27406
+ },
27407
+ {
27408
+ value: "ANTHROPIC_API_KEY",
27409
+ label: "ANTHROPIC_API_KEY(官方)",
27410
+ labelCode: "harness.field.claude.authVar.option.official"
27411
+ }
27036
27412
  ]
27037
27413
  },
27038
27414
  {
27039
27415
  key: "haikuModel",
27040
27416
  label: "Haiku 模型映射",
27417
+ labelCode: "harness.field.claude.haikuModel.label",
27041
27418
  kind: "text",
27042
27419
  required: true,
27043
27420
  placeholder: "例如:glm-5-air",
27044
- help: "写入 ANTHROPIC_DEFAULT_HAIKU_MODEL。"
27421
+ placeholderCode: "harness.field.claude.example.placeholder",
27422
+ help: "写入 ANTHROPIC_DEFAULT_HAIKU_MODEL。",
27423
+ helpCode: "harness.field.claude.modelMapping.help",
27424
+ params: { value: "glm-5-air", envVar: "ANTHROPIC_DEFAULT_HAIKU_MODEL" }
27045
27425
  },
27046
27426
  {
27047
27427
  key: "haikuModelName",
27048
27428
  label: "Haiku 显示名称(选填)",
27429
+ labelCode: "harness.field.claude.haikuModelName.label",
27049
27430
  kind: "text",
27050
27431
  placeholder: "留空则使用 Haiku 模型 ID",
27051
- help: "写入 ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME;留空时 Claude Code 默认显示对应模型 ID。"
27432
+ placeholderCode: "harness.field.claude.modelName.placeholder",
27433
+ help: "写入 ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME;留空时 Claude Code 默认显示对应模型 ID。",
27434
+ helpCode: "harness.field.claude.modelName.help",
27435
+ params: { role: "Haiku", envVar: "ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME" }
27052
27436
  },
27053
27437
  {
27054
27438
  key: "sonnetModel",
27055
27439
  label: "Sonnet 模型映射",
27440
+ labelCode: "harness.field.claude.sonnetModel.label",
27056
27441
  kind: "text",
27057
27442
  required: true,
27058
27443
  placeholder: "例如:glm-5",
27059
- help: "写入 ANTHROPIC_DEFAULT_SONNET_MODEL。"
27444
+ placeholderCode: "harness.field.claude.example.placeholder",
27445
+ help: "写入 ANTHROPIC_DEFAULT_SONNET_MODEL。",
27446
+ helpCode: "harness.field.claude.modelMapping.help",
27447
+ params: { value: "glm-5", envVar: "ANTHROPIC_DEFAULT_SONNET_MODEL" }
27060
27448
  },
27061
27449
  {
27062
27450
  key: "sonnetModelName",
27063
27451
  label: "Sonnet 显示名称(选填)",
27452
+ labelCode: "harness.field.claude.sonnetModelName.label",
27064
27453
  kind: "text",
27065
27454
  placeholder: "留空则使用 Sonnet 模型 ID",
27066
- help: "写入 ANTHROPIC_DEFAULT_SONNET_MODEL_NAME;留空时 Claude Code 默认显示对应模型 ID。"
27455
+ placeholderCode: "harness.field.claude.modelName.placeholder",
27456
+ help: "写入 ANTHROPIC_DEFAULT_SONNET_MODEL_NAME;留空时 Claude Code 默认显示对应模型 ID。",
27457
+ helpCode: "harness.field.claude.modelName.help",
27458
+ params: { role: "Sonnet", envVar: "ANTHROPIC_DEFAULT_SONNET_MODEL_NAME" }
27067
27459
  },
27068
27460
  oneMField("Sonnet", "sonnetModel1m"),
27069
27461
  {
27070
27462
  key: "opusModel",
27071
27463
  label: "Opus 模型映射",
27464
+ labelCode: "harness.field.claude.opusModel.label",
27072
27465
  kind: "text",
27073
27466
  required: true,
27074
27467
  placeholder: "例如:glm-5",
27075
- help: "写入 ANTHROPIC_DEFAULT_OPUS_MODEL。"
27468
+ placeholderCode: "harness.field.claude.example.placeholder",
27469
+ help: "写入 ANTHROPIC_DEFAULT_OPUS_MODEL。",
27470
+ helpCode: "harness.field.claude.modelMapping.help",
27471
+ params: { value: "glm-5", envVar: "ANTHROPIC_DEFAULT_OPUS_MODEL" }
27076
27472
  },
27077
27473
  {
27078
27474
  key: "opusModelName",
27079
27475
  label: "Opus 显示名称(选填)",
27476
+ labelCode: "harness.field.claude.opusModelName.label",
27080
27477
  kind: "text",
27081
27478
  placeholder: "留空则使用 Opus 模型 ID",
27082
- help: "写入 ANTHROPIC_DEFAULT_OPUS_MODEL_NAME;留空时 Claude Code 默认显示对应模型 ID。"
27479
+ placeholderCode: "harness.field.claude.modelName.placeholder",
27480
+ help: "写入 ANTHROPIC_DEFAULT_OPUS_MODEL_NAME;留空时 Claude Code 默认显示对应模型 ID。",
27481
+ helpCode: "harness.field.claude.modelName.help",
27482
+ params: { role: "Opus", envVar: "ANTHROPIC_DEFAULT_OPUS_MODEL_NAME" }
27083
27483
  },
27084
27484
  oneMField("Opus", "opusModel1m"),
27085
27485
  {
27086
27486
  key: "fableModel",
27087
27487
  label: "Fable 模型映射(可选)",
27488
+ labelCode: "harness.field.claude.fableModel.label",
27088
27489
  kind: "text",
27089
27490
  placeholder: "例如:glm-5",
27090
- help: "写入 ANTHROPIC_DEFAULT_FABLE_MODEL;用于支持 Fable 档位的新版 Claude Code。"
27491
+ placeholderCode: "harness.field.claude.example.placeholder",
27492
+ help: "写入 ANTHROPIC_DEFAULT_FABLE_MODEL;用于支持 Fable 档位的新版 Claude Code。",
27493
+ helpCode: "harness.field.claude.fableModel.help",
27494
+ params: { value: "glm-5" }
27091
27495
  },
27092
27496
  {
27093
27497
  key: "fableModelName",
27094
27498
  label: "Fable 显示名称(选填)",
27499
+ labelCode: "harness.field.claude.fableModelName.label",
27095
27500
  kind: "text",
27096
27501
  placeholder: "留空则使用 Fable 模型 ID",
27097
- help: "写入 ANTHROPIC_DEFAULT_FABLE_MODEL_NAME;留空时 Claude Code 默认显示对应模型 ID。"
27502
+ placeholderCode: "harness.field.claude.modelName.placeholder",
27503
+ help: "写入 ANTHROPIC_DEFAULT_FABLE_MODEL_NAME;留空时 Claude Code 默认显示对应模型 ID。",
27504
+ helpCode: "harness.field.claude.modelName.help",
27505
+ params: { role: "Fable", envVar: "ANTHROPIC_DEFAULT_FABLE_MODEL_NAME" }
27098
27506
  },
27099
27507
  oneMField("Fable", "fableModel1m"),
27100
27508
  {
27101
27509
  key: "subagentModel",
27102
27510
  label: "子代理模型(可选)",
27511
+ labelCode: "harness.field.claude.subagentModel.label",
27103
27512
  kind: "text",
27104
27513
  placeholder: "例如:glm-5-air",
27105
- help: "写入 CLAUDE_CODE_SUBAGENT_MODEL,可让子代理使用更快或成本更低的模型。"
27514
+ placeholderCode: "harness.field.claude.example.placeholder",
27515
+ help: "写入 CLAUDE_CODE_SUBAGENT_MODEL,可让子代理使用更快或成本更低的模型。",
27516
+ helpCode: "harness.field.claude.subagentModel.help",
27517
+ params: { value: "glm-5-air" }
27106
27518
  },
27107
- oneMField("子代理", "subagentModel1m"),
27519
+ oneMField("子代理", "subagentModel1m", "harness.field.claude.oneM.subagentLabel"),
27108
27520
  {
27109
27521
  key: "extraEnv",
27110
27522
  label: "追加环境变量(可选)",
27523
+ labelCode: "harness.field.claude.extraEnv.label",
27111
27524
  kind: "textarea",
27112
27525
  placeholder: `ANTHROPIC_DEFAULT_SONNET_MODEL=glm-5.2
27113
27526
  API_TIMEOUT_MS=3000000`,
27114
- help: "每行一个 KEY=VALUE,会合并进 settings.json 的 env。"
27527
+ help: "每行一个 KEY=VALUE,会合并进 settings.json 的 env。",
27528
+ helpCode: "harness.field.claude.extraEnv.help"
27115
27529
  }
27116
27530
  ];
27117
27531
  constructor(environment) {
@@ -27202,7 +27616,7 @@ API_TIMEOUT_MS=3000000`,
27202
27616
  return { [SETTINGS]: stringifyJson(settings) };
27203
27617
  }
27204
27618
  backfill(profile, current) {
27205
- const settings = safeParse3(current[SETTINGS]);
27619
+ const settings = tryParseJsonObject(current[SETTINGS]) ?? {};
27206
27620
  const env = settings.env;
27207
27621
  const authVar = this.authVar(profile);
27208
27622
  const apiKey = readString(env, authVar);
@@ -27224,7 +27638,7 @@ API_TIMEOUT_MS=3000000`,
27224
27638
  };
27225
27639
  }
27226
27640
  detect(current) {
27227
- const env = safeParse3(current[SETTINGS]).env;
27641
+ const env = (tryParseJsonObject(current[SETTINGS]) ?? {}).env;
27228
27642
  const authVar = AUTH_VARS.find((name) => readString(env, name)) ?? AUTH_VARS[0];
27229
27643
  const seed = seedProfile({ authVar });
27230
27644
  return compact([toCandidate("claude", seed, this.backfill(seed, current), true)]);
@@ -27241,13 +27655,6 @@ function withOneM(value, enabled) {
27241
27655
  function withoutOneM(value) {
27242
27656
  return value.endsWith(ONE_M_SUFFIX) ? value.slice(0, -ONE_M_SUFFIX.length) : value;
27243
27657
  }
27244
- function safeParse3(text) {
27245
- try {
27246
- return parseJsonObject(text);
27247
- } catch {
27248
- return {};
27249
- }
27250
- }
27251
27658
  function parseEnvLines(raw2) {
27252
27659
  if (!raw2) {
27253
27660
  return [];
@@ -27289,40 +27696,65 @@ class CodexAdapter {
27289
27696
  mode = "replace";
27290
27697
  envVarNames = [DEFAULT_ENV_KEY];
27291
27698
  envNote = "仅「环境变量」认证模式需要 env.sh,其余模式的凭据自包含在 config.toml 里。";
27699
+ envNoteCode = "harness.field.codex.envNote";
27292
27700
  fields = [
27293
27701
  {
27294
27702
  key: "authMode",
27295
27703
  label: "认证方式",
27704
+ labelCode: "harness.field.codex.authMode.label",
27296
27705
  kind: "select",
27297
27706
  defaultValue: "bearer_token",
27298
27707
  help: "auth.json 就是 Codex 的登录缓存,覆盖它会丢失 ChatGPT 登录态,所以默认不碰它。",
27708
+ helpCode: "harness.field.codex.authMode.help",
27299
27709
  options: [
27300
- { value: "bearer_token", label: "写入 config.toml(推荐,保留官方登录)" },
27301
- { value: "env_key", label: "环境变量(需要 source env.sh)" },
27302
- { value: "openai_auth", label: "写入 auth.json(会覆盖 ChatGPT 登录缓存)" }
27710
+ {
27711
+ value: "bearer_token",
27712
+ label: "写入 config.toml(推荐,保留官方登录)",
27713
+ labelCode: "harness.field.codex.authMode.option.bearerToken"
27714
+ },
27715
+ {
27716
+ value: "env_key",
27717
+ label: "环境变量(需要 source env.sh)",
27718
+ labelCode: "harness.field.codex.authMode.option.envKey"
27719
+ },
27720
+ {
27721
+ value: "openai_auth",
27722
+ label: "写入 auth.json(会覆盖 ChatGPT 登录缓存)",
27723
+ labelCode: "harness.field.codex.authMode.option.openaiAuth"
27724
+ }
27303
27725
  ]
27304
27726
  },
27305
27727
  {
27306
27728
  key: "providerId",
27307
27729
  label: "Provider ID(可选)",
27730
+ labelCode: "harness.field.providerId.label",
27308
27731
  kind: "text",
27309
27732
  placeholder: "默认取配置名称",
27310
- help: "openai / ollama / lmstudio / amazon-bedrock 等是 Codex 保留字,会自动改名。"
27733
+ placeholderCode: "harness.field.providerId.placeholder",
27734
+ help: "openai / ollama / lmstudio / amazon-bedrock 等是 Codex 保留字,会自动改名。",
27735
+ helpCode: "harness.field.codex.providerId.help"
27311
27736
  },
27312
27737
  {
27313
27738
  key: "envKeyName",
27314
27739
  label: "环境变量名",
27740
+ labelCode: "harness.field.codex.envKeyName.label",
27315
27741
  kind: "text",
27316
27742
  defaultValue: DEFAULT_ENV_KEY,
27317
- help: "仅「环境变量」模式生效。"
27743
+ help: "仅「环境变量」模式生效。",
27744
+ helpCode: "harness.field.codex.envKeyName.help"
27318
27745
  },
27319
27746
  {
27320
27747
  key: "reasoningEffort",
27321
27748
  label: "推理强度(可选)",
27749
+ labelCode: "harness.field.codex.reasoningEffort.label",
27322
27750
  kind: "select",
27323
27751
  defaultValue: "",
27324
27752
  options: [
27325
- { value: "", label: "不设置" },
27753
+ {
27754
+ value: "",
27755
+ label: "不设置",
27756
+ labelCode: "harness.field.codex.reasoningEffort.option.unset"
27757
+ },
27326
27758
  { value: "low", label: "low" },
27327
27759
  { value: "medium", label: "medium" },
27328
27760
  { value: "high", label: "high" }
@@ -27343,6 +27775,7 @@ class CodexAdapter {
27343
27775
  {
27344
27776
  key: AUTH,
27345
27777
  label: "auth.json(仅 auth.json 模式)",
27778
+ labelCode: "harness.field.codex.target.auth",
27346
27779
  path: join4(this.environment.harnessHomes.codex, "auth.json"),
27347
27780
  format: "json"
27348
27781
  }
@@ -27355,10 +27788,10 @@ class CodexAdapter {
27355
27788
  return { [this.envKeyName(profile)]: profile.apiKey };
27356
27789
  }
27357
27790
  render(profile, current) {
27358
- const providerId = this.providerId(profile);
27791
+ const providerId2 = this.providerId(profile);
27359
27792
  const config2 = parseTomlObject(current[CONFIG]);
27360
27793
  const mode = this.authMode(profile);
27361
- config2.model_provider = providerId;
27794
+ config2.model_provider = providerId2;
27362
27795
  if (profile.model) {
27363
27796
  config2.model = profile.model;
27364
27797
  }
@@ -27367,7 +27800,7 @@ class CodexAdapter {
27367
27800
  config2.model_reasoning_effort = effort;
27368
27801
  }
27369
27802
  const providers = ensureObject(config2, "model_providers");
27370
- const provider = ensureObject(providers, providerId);
27803
+ const provider = ensureObject(providers, providerId2);
27371
27804
  provider.name = profile.name;
27372
27805
  provider.base_url = profile.baseUrl;
27373
27806
  provider.wire_api = "responses";
@@ -27406,16 +27839,14 @@ class CodexAdapter {
27406
27839
  return rendered;
27407
27840
  }
27408
27841
  backfill(profile, current) {
27409
- let config2 = {};
27410
- try {
27411
- config2 = parseTomlObject(current[CONFIG]);
27412
- } catch {
27842
+ const config2 = tryParseTomlObject(current[CONFIG]);
27843
+ if (!config2) {
27413
27844
  return {};
27414
27845
  }
27415
27846
  const providers = config2.model_providers;
27416
27847
  const provider = isPlainObject2(providers) ? providers[this.providerId(profile)] : undefined;
27417
27848
  const mode = this.authMode(profile);
27418
- const token = mode === "bearer_token" ? readString(provider, "experimental_bearer_token") : mode === "openai_auth" ? readString(safeJson(current[AUTH]), DEFAULT_ENV_KEY) : "";
27849
+ const token = mode === "bearer_token" ? readString(provider, "experimental_bearer_token") : mode === "openai_auth" ? readString(tryParseJsonObject(current[AUTH]) ?? {}, DEFAULT_ENV_KEY) : "";
27419
27850
  return {
27420
27851
  baseUrl: readString(provider, "base_url") || profile.baseUrl,
27421
27852
  model: readString(config2, "model"),
@@ -27423,10 +27854,8 @@ class CodexAdapter {
27423
27854
  };
27424
27855
  }
27425
27856
  detect(current) {
27426
- let config2;
27427
- try {
27428
- config2 = parseTomlObject(current[CONFIG]);
27429
- } catch {
27857
+ const config2 = tryParseTomlObject(current[CONFIG]);
27858
+ if (!config2) {
27430
27859
  return [];
27431
27860
  }
27432
27861
  const providers = config2.model_providers;
@@ -27456,17 +27885,10 @@ class CodexAdapter {
27456
27885
  return profile.extras.envKeyName?.trim() || DEFAULT_ENV_KEY;
27457
27886
  }
27458
27887
  providerId(profile) {
27459
- const slug = slugify2(profile.extras.providerId || profile.name, "provider");
27888
+ const slug = providerId(profile);
27460
27889
  return RESERVED_PROVIDER_IDS.has(slug) ? `${slug}-hsw` : slug;
27461
27890
  }
27462
27891
  }
27463
- function safeJson(text) {
27464
- try {
27465
- return parseJsonObject(text);
27466
- } catch {
27467
- return {};
27468
- }
27469
- }
27470
27892
 
27471
27893
  // src/services/adapters/dsh.ts
27472
27894
  import { join as join5 } from "node:path";
@@ -27482,35 +27904,52 @@ class DshAdapter {
27482
27904
  modelRequired = true;
27483
27905
  envVarNames = [];
27484
27906
  envNote = "API key 安全写入 DSH 的 .credentials.yaml,并由 settings.yaml 引用。";
27907
+ envNoteCode = "harness.field.dsh.envNote";
27485
27908
  fields = [
27486
27909
  {
27487
27910
  key: "providerType",
27488
27911
  label: "提供方类型",
27912
+ labelCode: "harness.field.dsh.providerType.label",
27489
27913
  kind: "select",
27490
27914
  defaultValue: "custom",
27491
27915
  options: [
27492
- { value: "custom", label: "自定义提供方" },
27493
- { value: "official", label: "DeepSeek 官方" }
27916
+ {
27917
+ value: "custom",
27918
+ label: "自定义提供方",
27919
+ labelCode: "harness.field.dsh.providerType.option.custom"
27920
+ },
27921
+ {
27922
+ value: "official",
27923
+ label: "DeepSeek 官方",
27924
+ labelCode: "harness.field.dsh.providerType.option.official"
27925
+ }
27494
27926
  ]
27495
27927
  },
27496
27928
  {
27497
27929
  key: "providerId",
27498
27930
  label: "Provider ID(可选)",
27931
+ labelCode: "harness.field.providerId.label",
27499
27932
  kind: "text",
27500
27933
  placeholder: "默认取配置名称",
27501
- help: "DSH 的模型路由标识;必须以小写字母开头。"
27934
+ placeholderCode: "harness.field.providerId.placeholder",
27935
+ help: "DSH 的模型路由标识;必须以小写字母开头。",
27936
+ helpCode: "harness.field.dsh.providerId.help"
27502
27937
  },
27503
27938
  {
27504
27939
  key: "models",
27505
27940
  label: "模型目录(可选)",
27941
+ labelCode: "harness.field.dsh.models.label",
27506
27942
  kind: "textarea",
27507
27943
  fullWidth: true,
27508
27944
  placeholder: "每行一个模型 ID;留空时只注册上方的默认模型",
27509
- help: "一个提供方可注册多个模型;上方“模型”作为新会话的默认模型。"
27945
+ placeholderCode: "harness.field.dsh.models.placeholder",
27946
+ help: "一个提供方可注册多个模型;上方“模型”作为新会话的默认模型。",
27947
+ helpCode: "harness.field.dsh.models.help"
27510
27948
  },
27511
27949
  {
27512
27950
  key: "api",
27513
27951
  label: "API 协议",
27952
+ labelCode: "harness.field.dsh.api.label",
27514
27953
  kind: "select",
27515
27954
  defaultValue: "openai-responses",
27516
27955
  options: [
@@ -27522,27 +27961,39 @@ class DshAdapter {
27522
27961
  {
27523
27962
  key: "contextWindow",
27524
27963
  label: "上下文长度",
27964
+ labelCode: "harness.field.contextLength.label",
27525
27965
  kind: "text",
27526
27966
  defaultValue: String(DEFAULT_CONTEXT)
27527
27967
  },
27528
27968
  {
27529
27969
  key: "maxTokens",
27530
27970
  label: "最大输出 tokens",
27971
+ labelCode: "harness.field.maxTokens.label",
27531
27972
  kind: "text",
27532
27973
  defaultValue: String(DEFAULT_MAX_TOKENS)
27533
27974
  },
27534
27975
  {
27535
27976
  key: "reasoningEfforts",
27536
27977
  label: "支持的思考程度",
27978
+ labelCode: "harness.field.dsh.reasoningEfforts.label",
27537
27979
  kind: "select",
27538
27980
  defaultValue: "",
27539
27981
  help: "DSH 只会显示这里声明且上游模型实际支持的档位。",
27982
+ helpCode: "harness.field.dsh.reasoningEfforts.help",
27540
27983
  options: [
27541
- { value: "", label: "不声明(提供方默认)" },
27984
+ {
27985
+ value: "",
27986
+ label: "不声明(提供方默认)",
27987
+ labelCode: "harness.field.dsh.reasoningEfforts.option.unset"
27988
+ },
27542
27989
  { value: "low,medium,high,xhigh,max", label: "Low / Medium / High / XHigh / Max" },
27543
27990
  { value: "low,medium,high,xhigh", label: "Low / Medium / High / XHigh" },
27544
27991
  { value: "minimal,low,medium,high", label: "Minimal / Low / Medium / High" },
27545
- { value: "false", label: "模型不支持思考程度" }
27992
+ {
27993
+ value: "false",
27994
+ label: "模型不支持思考程度",
27995
+ labelCode: "harness.field.dsh.reasoningEfforts.option.none"
27996
+ }
27546
27997
  ]
27547
27998
  }
27548
27999
  ];
@@ -27585,17 +28036,17 @@ class DshAdapter {
27585
28036
  render(profile, current) {
27586
28037
  this.validate(profile);
27587
28038
  const official = this.isOfficial(profile);
27588
- const providerId = official ? "deepseek-official" : this.providerId(profile);
27589
- const credentialRef = this.credentialRef(providerId);
28039
+ const providerId2 = official ? "deepseek-official" : this.providerId(profile);
28040
+ const credentialRef = this.credentialRef(providerId2);
27590
28041
  const settings = parseYamlDocument(current[SETTINGS2]);
27591
28042
  const models = this.models(profile, official);
27592
28043
  if (official) {
27593
28044
  settings.setIn(["llm-deepseek", "apiKeyEnv"], credentialRef);
27594
28045
  settings.setIn(["llm-deepseek", "baseURL"], profile.baseUrl || "https://api.deepseek.com");
27595
28046
  settings.setIn(["llm-deepseek", "models"], models);
27596
- settings.setIn(["llm-deepseek", "maxTokens"], this.numeric(profile.extras.maxTokens, 256000));
28047
+ settings.setIn(["llm-deepseek", "maxTokens"], numeric(profile.extras.maxTokens, 256000));
27597
28048
  } else {
27598
- settings.setIn(["llm-pi-ai", "providers", providerId], {
28049
+ settings.setIn(["llm-pi-ai", "providers", providerId2], {
27599
28050
  displayName: profile.name,
27600
28051
  apiKeyEnv: credentialRef,
27601
28052
  api: profile.extras.api || "openai-responses",
@@ -27603,7 +28054,7 @@ class DshAdapter {
27603
28054
  models
27604
28055
  });
27605
28056
  }
27606
- settings.setIn(["agent-default-model", "provider"], providerId);
28057
+ settings.setIn(["agent-default-model", "provider"], providerId2);
27607
28058
  settings.setIn(["agent-default-model", "model"], profile.model);
27608
28059
  settings.deleteIn(["agent-default-model", "reasoningEffort"]);
27609
28060
  const credentials = parseYamlDocument(current[CREDENTIALS]);
@@ -27629,72 +28080,68 @@ class DshAdapter {
27629
28080
  }
27630
28081
  revoke(profile, current) {
27631
28082
  const official = this.isOfficial(profile);
27632
- const providerId = official ? "deepseek-official" : this.providerId(profile);
28083
+ const providerId2 = official ? "deepseek-official" : this.providerId(profile);
27633
28084
  const rendered = {};
27634
28085
  if (current[SETTINGS2] !== undefined) {
27635
- try {
27636
- const settings = parseYamlDocument(current[SETTINGS2]);
28086
+ const settings = tryParseYamlDocument(current[SETTINGS2]);
28087
+ if (settings) {
27637
28088
  if (official)
27638
28089
  settings.deleteIn(["llm-deepseek"]);
27639
28090
  else
27640
- settings.deleteIn(["llm-pi-ai", "providers", providerId]);
27641
- if (settings.getIn(["agent-default-model", "provider"]) === providerId) {
28091
+ settings.deleteIn(["llm-pi-ai", "providers", providerId2]);
28092
+ if (settings.getIn(["agent-default-model", "provider"]) === providerId2) {
27642
28093
  settings.deleteIn(["agent-default-model"]);
27643
28094
  }
27644
28095
  rendered[SETTINGS2] = settings.toString();
27645
- } catch {}
28096
+ }
27646
28097
  }
27647
28098
  if (current[CREDENTIALS] !== undefined) {
27648
- try {
27649
- const credentials = parseYamlDocument(current[CREDENTIALS]);
28099
+ const credentials = tryParseYamlDocument(current[CREDENTIALS]);
28100
+ if (credentials) {
27650
28101
  this.normalizeCredentials(credentials);
27651
- credentials.deleteIn(["refs", this.credentialRef(providerId)]);
28102
+ credentials.deleteIn(["refs", this.credentialRef(providerId2)]);
27652
28103
  rendered[CREDENTIALS] = credentials.toString();
27653
- } catch {}
28104
+ }
27654
28105
  }
27655
28106
  return rendered;
27656
28107
  }
27657
28108
  backfill(profile, current) {
27658
- try {
27659
- const official = this.isOfficial(profile);
27660
- const providerId = official ? "deepseek-official" : this.providerId(profile);
27661
- const settings = parseYamlDocument(current[SETTINGS2]);
27662
- const credentials = parseYamlDocument(current[CREDENTIALS]);
27663
- const route = toPlain(settings.getIn(official ? ["llm-deepseek"] : ["llm-pi-ai", "providers", providerId]));
27664
- const models = Array.isArray(route?.models) ? route.models : [];
27665
- const firstModel = toPlain(models[0]);
27666
- const ref = this.credentialRef(providerId);
27667
- const apiKey = credentials.getIn(["refs", ref]) ?? credentials.getIn([ref]);
27668
- return {
27669
- baseUrl: typeof route?.baseURL === "string" ? route.baseURL : profile.baseUrl,
27670
- apiKey: typeof apiKey === "string" && apiKey ? apiKey : profile.apiKey,
27671
- model: typeof firstModel?.id === "string" ? firstModel.id : profile.model,
27672
- extras: {
27673
- ...profile.extras,
27674
- providerType: official ? "official" : "custom",
27675
- api: typeof route?.api === "string" ? route.api : profile.extras.api || "",
27676
- models: models.map((entry) => toPlain(entry)?.id).filter((id) => typeof id === "string").join(`
27677
- `),
27678
- contextWindow: valueString(firstModel?.contextWindow, profile.extras.contextWindow),
27679
- maxTokens: valueString(firstModel?.maxTokens, profile.extras.maxTokens),
27680
- reasoningEfforts: reasoningEffortsString(firstModel?.reasoningEfforts, profile.extras.reasoningEfforts)
27681
- }
27682
- };
27683
- } catch {
28109
+ const official = this.isOfficial(profile);
28110
+ const providerId2 = official ? "deepseek-official" : this.providerId(profile);
28111
+ const settings = tryParseYamlDocument(current[SETTINGS2]);
28112
+ const credentials = tryParseYamlDocument(current[CREDENTIALS]);
28113
+ if (!settings || !credentials) {
27684
28114
  return {};
27685
28115
  }
28116
+ const route = toPlain(settings.getIn(official ? ["llm-deepseek"] : ["llm-pi-ai", "providers", providerId2]));
28117
+ const models = Array.isArray(route?.models) ? route.models : [];
28118
+ const firstModel = toPlain(models[0]);
28119
+ const ref = this.credentialRef(providerId2);
28120
+ const apiKey = credentials.getIn(["refs", ref]) ?? credentials.getIn([ref]);
28121
+ return {
28122
+ baseUrl: typeof route?.baseURL === "string" ? route.baseURL : profile.baseUrl,
28123
+ apiKey: typeof apiKey === "string" && apiKey ? apiKey : profile.apiKey,
28124
+ model: typeof firstModel?.id === "string" ? firstModel.id : profile.model,
28125
+ extras: {
28126
+ ...profile.extras,
28127
+ providerType: official ? "official" : "custom",
28128
+ api: typeof route?.api === "string" ? route.api : profile.extras.api || "",
28129
+ models: models.map((entry) => toPlain(entry)?.id).filter((id) => typeof id === "string").join(`
28130
+ `),
28131
+ contextWindow: valueString(firstModel?.contextWindow, profile.extras.contextWindow),
28132
+ maxTokens: valueString(firstModel?.maxTokens, profile.extras.maxTokens),
28133
+ reasoningEfforts: reasoningEffortsString(firstModel?.reasoningEfforts, profile.extras.reasoningEfforts)
28134
+ }
28135
+ };
27686
28136
  }
27687
28137
  detect(current) {
27688
- let providers;
27689
- let selected = "";
27690
- try {
27691
- const settings = parseYamlDocument(current[SETTINGS2]);
27692
- providers = toPlain(settings.getIn(["llm-pi-ai", "providers"]));
27693
- const active = settings.getIn(["agent-default-model", "provider"]);
27694
- selected = typeof active === "string" ? active : "";
27695
- } catch {
28138
+ const settings = tryParseYamlDocument(current[SETTINGS2]);
28139
+ if (!settings) {
27696
28140
  return [];
27697
28141
  }
28142
+ const providers = toPlain(settings.getIn(["llm-pi-ai", "providers"]));
28143
+ const active = settings.getIn(["agent-default-model", "provider"]);
28144
+ const selected = typeof active === "string" ? active : "";
27698
28145
  if (!providers) {
27699
28146
  return [];
27700
28147
  }
@@ -27708,19 +28155,19 @@ class DshAdapter {
27708
28155
  }));
27709
28156
  }
27710
28157
  providerId(profile) {
27711
- const id = slugify2(profile.extras.providerId || profile.name, "provider");
28158
+ const id = providerId(profile);
27712
28159
  return /^[a-z]/.test(id) ? id : `provider-${id}`;
27713
28160
  }
27714
- credentialRef(providerId) {
27715
- return providerId === "deepseek-official" ? "DEEPSEEK_API_KEY" : `${providerId.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}_API_KEY`;
28161
+ credentialRef(providerId2) {
28162
+ return providerId2 === "deepseek-official" ? "DEEPSEEK_API_KEY" : `${providerId2.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}_API_KEY`;
27716
28163
  }
27717
28164
  isOfficial(profile) {
27718
28165
  return profile.extras.providerType === "official";
27719
28166
  }
27720
28167
  models(profile, official) {
27721
28168
  const ids = [profile.model, ...(profile.extras.models || "").split(/[\n,]/)].map((id) => id.trim()).filter(Boolean);
27722
- const contextWindow = this.numeric(profile.extras.contextWindow, official ? 1e6 : DEFAULT_CONTEXT);
27723
- const maxTokens = this.numeric(profile.extras.maxTokens, official ? 256000 : DEFAULT_MAX_TOKENS);
28169
+ const contextWindow = numeric(profile.extras.contextWindow, official ? 1e6 : DEFAULT_CONTEXT);
28170
+ const maxTokens = numeric(profile.extras.maxTokens, official ? 256000 : DEFAULT_MAX_TOKENS);
27724
28171
  const reasoningEfforts = this.reasoningEfforts(profile.extras.reasoningEfforts);
27725
28172
  return [...new Set(ids)].map((id) => ({
27726
28173
  id,
@@ -27740,10 +28187,6 @@ class DshAdapter {
27740
28187
  credentials.deleteIn([key]);
27741
28188
  }
27742
28189
  }
27743
- numeric(raw2, fallback) {
27744
- const parsed = Number(raw2);
27745
- return Number.isFinite(parsed) && parsed > 0 ? Math.trunc(parsed) : fallback;
27746
- }
27747
28190
  reasoningEfforts(raw2) {
27748
28191
  if (!raw2) {
27749
28192
  return;
@@ -27762,9 +28205,6 @@ function toPlain(value) {
27762
28205
  function isYamlNode(value) {
27763
28206
  return typeof value === "object" && value !== null && "toJSON" in value;
27764
28207
  }
27765
- function valueString(value, fallback) {
27766
- return typeof value === "number" && Number.isFinite(value) ? String(value) : fallback || "";
27767
- }
27768
28208
  function reasoningEffortsString(value, fallback) {
27769
28209
  if (value === false) {
27770
28210
  return "false";
@@ -27785,15 +28225,22 @@ class KimiAdapter {
27785
28225
  modelRequired = true;
27786
28226
  envVarNames = [];
27787
28227
  envNote = "Kimi Code 不从 shell 读取凭据,env.sh 对它无效。";
28228
+ envNoteCode = "harness.field.kimi.envNote";
27788
28229
  fields = [
27789
28230
  {
27790
28231
  key: "providerType",
27791
28232
  label: "Provider 类型",
28233
+ labelCode: "harness.field.kimi.providerType.label",
27792
28234
  kind: "select",
27793
28235
  defaultValue: "kimi",
27794
28236
  help: "决定 Kimi Code 使用哪套协议实现。",
28237
+ helpCode: "harness.field.kimi.providerType.help",
27795
28238
  options: [
27796
- { value: "kimi", label: "kimi(Moonshot / Kimi Code)" },
28239
+ {
28240
+ value: "kimi",
28241
+ label: "kimi(Moonshot / Kimi Code)",
28242
+ labelCode: "harness.field.kimi.providerType.option.kimi"
28243
+ },
27797
28244
  { value: "anthropic", label: "anthropic" },
27798
28245
  { value: "openai_responses", label: "openai_responses" },
27799
28246
  { value: "openai_legacy", label: "openai_legacy" }
@@ -27802,15 +28249,19 @@ class KimiAdapter {
27802
28249
  {
27803
28250
  key: "providerId",
27804
28251
  label: "Provider ID(可选)",
28252
+ labelCode: "harness.field.providerId.label",
27805
28253
  kind: "text",
27806
- placeholder: "默认取配置名称"
28254
+ placeholder: "默认取配置名称",
28255
+ placeholderCode: "harness.field.providerId.placeholder"
27807
28256
  },
27808
28257
  {
27809
28258
  key: "maxContextSize",
27810
28259
  label: "上下文长度",
28260
+ labelCode: "harness.field.contextLength.label",
27811
28261
  kind: "text",
27812
28262
  defaultValue: String(DEFAULT_CONTEXT2),
27813
- help: "Kimi Code 要求 models 条目必须声明 max_context_size。"
28263
+ help: "Kimi Code 要求 models 条目必须声明 max_context_size。",
28264
+ helpCode: "harness.field.kimi.maxContextSize.help"
27814
28265
  }
27815
28266
  ];
27816
28267
  constructor(environment) {
@@ -27839,7 +28290,7 @@ class KimiAdapter {
27839
28290
  }
27840
28291
  render(profile, current) {
27841
28292
  this.validate(profile);
27842
- const id = this.providerId(profile);
28293
+ const id = providerId(profile);
27843
28294
  const config2 = parseTomlObject(current[CONFIG2]);
27844
28295
  const provider = ensureObject(ensureObject(config2, "providers"), id);
27845
28296
  provider.type = profile.extras.providerType || "kimi";
@@ -27848,19 +28299,17 @@ class KimiAdapter {
27848
28299
  const model = ensureObject(ensureObject(config2, "models"), id);
27849
28300
  model.provider = id;
27850
28301
  model.model = profile.model;
27851
- model.max_context_size = this.contextSize(profile);
28302
+ model.max_context_size = numeric(profile.extras.maxContextSize, DEFAULT_CONTEXT2);
27852
28303
  config2.default_model = id;
27853
28304
  return { [CONFIG2]: stringifyToml(config2) };
27854
28305
  }
27855
28306
  revoke(profile, current) {
27856
- const id = this.providerId(profile);
28307
+ const id = providerId(profile);
27857
28308
  if (current[CONFIG2] === undefined) {
27858
28309
  return {};
27859
28310
  }
27860
- let config2;
27861
- try {
27862
- config2 = parseTomlObject(current[CONFIG2]);
27863
- } catch {
28311
+ const config2 = tryParseTomlObject(current[CONFIG2]);
28312
+ if (!config2) {
27864
28313
  return {};
27865
28314
  }
27866
28315
  const providers = config2.providers;
@@ -27881,14 +28330,30 @@ class KimiAdapter {
27881
28330
  }
27882
28331
  return { [CONFIG2]: stringifyToml(config2) };
27883
28332
  }
28333
+ renderOfficial(_profile, current) {
28334
+ if (current[CONFIG2] === undefined) {
28335
+ return {};
28336
+ }
28337
+ const config2 = tryParseTomlObject(current[CONFIG2]);
28338
+ if (!config2) {
28339
+ return {};
28340
+ }
28341
+ const official = officialModel(config2);
28342
+ if (official === undefined) {
28343
+ throw new HttpError(400, "未检测到 Kimi Code 官方登录条目,请先在终端运行 kimi 并完成 /login", {
28344
+ code: ERROR_CODES.officialLoginMissing,
28345
+ params: { harness: "Kimi Code" }
28346
+ });
28347
+ }
28348
+ config2.default_model = official;
28349
+ return { [CONFIG2]: stringifyToml(config2) };
28350
+ }
27884
28351
  backfill(profile, current) {
27885
- let config2;
27886
- try {
27887
- config2 = parseTomlObject(current[CONFIG2]);
27888
- } catch {
28352
+ const config2 = tryParseTomlObject(current[CONFIG2]);
28353
+ if (!config2) {
27889
28354
  return {};
27890
28355
  }
27891
- const id = this.providerId(profile);
28356
+ const id = providerId(profile);
27892
28357
  const providers = config2.providers;
27893
28358
  const provider = isPlainObject2(providers) ? providers[id] : undefined;
27894
28359
  const models = config2.models;
@@ -27901,10 +28366,8 @@ class KimiAdapter {
27901
28366
  };
27902
28367
  }
27903
28368
  detect(current) {
27904
- let config2;
27905
- try {
27906
- config2 = parseTomlObject(current[CONFIG2]);
27907
- } catch {
28369
+ const config2 = tryParseTomlObject(current[CONFIG2]);
28370
+ if (!config2) {
27908
28371
  return [];
27909
28372
  }
27910
28373
  const providers = config2.providers;
@@ -27921,21 +28384,19 @@ class KimiAdapter {
27921
28384
  const seed = seedProfile({
27922
28385
  providerId: id,
27923
28386
  providerType: readString(provider, "type") || "kimi",
27924
- maxContextSize: contextString(isPlainObject2(model) ? model.max_context_size : undefined)
28387
+ maxContextSize: valueString(isPlainObject2(model) ? model.max_context_size : undefined, String(DEFAULT_CONTEXT2))
27925
28388
  });
27926
28389
  return toCandidate(id, seed, this.backfill(seed, current), id === selected);
27927
28390
  }));
27928
28391
  }
27929
- providerId(profile) {
27930
- return slugify2(profile.extras.providerId || profile.name, "provider");
27931
- }
27932
- contextSize(profile) {
27933
- const parsed = Number(profile.extras.maxContextSize);
27934
- return Number.isFinite(parsed) && parsed > 0 ? Math.trunc(parsed) : DEFAULT_CONTEXT2;
27935
- }
27936
28392
  }
27937
- function contextString(value) {
27938
- return typeof value === "number" && Number.isFinite(value) ? String(Math.trunc(value)) : String(DEFAULT_CONTEXT2);
28393
+ var PREFERRED_OFFICIAL_MODELS = ["kimi-code/k3-256k", "kimi-code/kimi-for-coding"];
28394
+ function officialModel(config2) {
28395
+ const providers = isPlainObject2(config2.providers) ? config2.providers : {};
28396
+ const models = isPlainObject2(config2.models) ? config2.models : {};
28397
+ const managed = new Set(Object.entries(providers).filter(([id, provider]) => id.startsWith("managed:") || isPlainObject2(provider) && isPlainObject2(provider.oauth)).map(([id]) => id));
28398
+ const aliases = Object.entries(models).filter(([, model]) => isPlainObject2(model) && typeof model.provider === "string" && managed.has(model.provider)).map(([alias]) => alias);
28399
+ return PREFERRED_OFFICIAL_MODELS.find((preferred) => aliases.includes(preferred)) ?? aliases[0];
27939
28400
  }
27940
28401
 
27941
28402
  // src/services/adapters/pi.ts
@@ -27952,17 +28413,22 @@ class PiAdapter {
27952
28413
  modelRequired = true;
27953
28414
  envVarNames = [];
27954
28415
  envNote = "API key 直接写入 models.json,无需环境变量;运行时仍可用 --model 覆盖。";
28416
+ envNoteCode = "harness.field.pi.envNote";
27955
28417
  fields = [
27956
28418
  {
27957
28419
  key: "providerId",
27958
28420
  label: "Provider ID(可选)",
28421
+ labelCode: "harness.field.providerId.label",
27959
28422
  kind: "text",
27960
28423
  placeholder: "默认取配置名称",
27961
- help: "模型引用格式为 provider/model。"
28424
+ placeholderCode: "harness.field.providerId.placeholder",
28425
+ help: "模型引用格式为 provider/model。",
28426
+ helpCode: "harness.field.pi.providerId.help"
27962
28427
  },
27963
28428
  {
27964
28429
  key: "api",
27965
28430
  label: "协议",
28431
+ labelCode: "harness.field.pi.api.label",
27966
28432
  kind: "select",
27967
28433
  defaultValue: "openai-completions",
27968
28434
  options: [
@@ -27974,35 +28440,41 @@ class PiAdapter {
27974
28440
  {
27975
28441
  key: "authHeader",
27976
28442
  label: "Authorization 头",
28443
+ labelCode: "harness.field.pi.authHeader.label",
27977
28444
  kind: "select",
27978
28445
  defaultValue: "true",
27979
28446
  help: "以 Authorization: Bearer <key> 发送。",
28447
+ helpCode: "harness.field.pi.authHeader.help",
27980
28448
  options: [
27981
- { value: "true", label: "开启" },
27982
- { value: "false", label: "关闭" }
28449
+ { value: "true", label: "开启", labelCode: "harness.field.toggle.on" },
28450
+ { value: "false", label: "关闭", labelCode: "harness.field.toggle.off" }
27983
28451
  ]
27984
28452
  },
27985
28453
  {
27986
28454
  key: "contextWindow",
27987
28455
  label: "上下文长度",
28456
+ labelCode: "harness.field.contextLength.label",
27988
28457
  kind: "text",
27989
28458
  defaultValue: String(DEFAULT_CONTEXT3)
27990
28459
  },
27991
28460
  {
27992
28461
  key: "maxTokens",
27993
28462
  label: "最大输出 tokens",
28463
+ labelCode: "harness.field.maxTokens.label",
27994
28464
  kind: "text",
27995
28465
  defaultValue: String(DEFAULT_MAX_TOKENS2)
27996
28466
  },
27997
28467
  {
27998
28468
  key: "reasoning",
27999
28469
  label: "推理能力",
28470
+ labelCode: "harness.field.pi.reasoning.label",
28000
28471
  kind: "select",
28001
28472
  defaultValue: "false",
28002
28473
  help: "对应 models.json 的 reasoning。GPT / Claude 思考模型需要开启。",
28474
+ helpCode: "harness.field.pi.reasoning.help",
28003
28475
  options: [
28004
- { value: "false", label: "关闭" },
28005
- { value: "true", label: "开启" }
28476
+ { value: "false", label: "关闭", labelCode: "harness.field.toggle.off" },
28477
+ { value: "true", label: "开启", labelCode: "harness.field.toggle.on" }
28006
28478
  ]
28007
28479
  }
28008
28480
  ];
@@ -28044,14 +28516,14 @@ class PiAdapter {
28044
28516
  }
28045
28517
  render(profile, current) {
28046
28518
  this.validate(profile);
28047
- const id = this.providerId(profile);
28519
+ const id = providerId(profile);
28048
28520
  const models = parseJsonObject(current[MODELS]);
28049
28521
  const provider = ensureObject(ensureObject(models, "providers"), id);
28050
28522
  const model = {
28051
28523
  id: profile.model,
28052
28524
  name: profile.model,
28053
- contextWindow: this.numeric(profile.extras.contextWindow, DEFAULT_CONTEXT3),
28054
- maxTokens: this.numeric(profile.extras.maxTokens, DEFAULT_MAX_TOKENS2)
28525
+ contextWindow: numeric(profile.extras.contextWindow, DEFAULT_CONTEXT3),
28526
+ maxTokens: numeric(profile.extras.maxTokens, DEFAULT_MAX_TOKENS2)
28055
28527
  };
28056
28528
  if (profile.extras.reasoning === "true") {
28057
28529
  model.reasoning = true;
@@ -28070,66 +28542,64 @@ class PiAdapter {
28070
28542
  };
28071
28543
  }
28072
28544
  revoke(profile, current) {
28073
- const id = this.providerId(profile);
28545
+ const id = providerId(profile);
28074
28546
  const rendered = {};
28075
28547
  if (current[MODELS] !== undefined) {
28076
- try {
28077
- const models = parseJsonObject(current[MODELS]);
28548
+ const models = tryParseJsonObject(current[MODELS]);
28549
+ if (models) {
28078
28550
  const providers = models.providers;
28079
28551
  if (isPlainObject2(providers)) {
28080
28552
  delete providers[id];
28081
28553
  }
28082
28554
  rendered[MODELS] = stringifyJson(models);
28083
- } catch {}
28555
+ }
28084
28556
  }
28085
28557
  if (current[SETTINGS3] !== undefined) {
28086
- try {
28087
- const settings = parseJsonObject(current[SETTINGS3]);
28558
+ const settings = tryParseJsonObject(current[SETTINGS3]);
28559
+ if (settings) {
28088
28560
  if (settings.defaultProvider === id) {
28089
28561
  delete settings.defaultProvider;
28090
28562
  delete settings.defaultModel;
28091
28563
  }
28092
28564
  rendered[SETTINGS3] = stringifyJson(settings);
28093
- } catch {}
28565
+ }
28094
28566
  }
28095
28567
  return rendered;
28096
28568
  }
28097
28569
  backfill(profile, current) {
28098
- try {
28099
- const models = parseJsonObject(current[MODELS]);
28100
- const id = this.providerId(profile);
28101
- const providers = models.providers;
28102
- const provider = isPlainObject2(providers) ? providers[id] : undefined;
28103
- if (!isPlainObject2(provider)) {
28104
- return {};
28105
- }
28106
- const firstModel = Array.isArray(provider.models) ? provider.models.find((entry) => isPlainObject2(entry)) : undefined;
28107
- const apiKey = readString(provider, "apiKey");
28108
- return {
28109
- baseUrl: readString(provider, "baseUrl") || profile.baseUrl,
28110
- apiKey: apiKey || profile.apiKey,
28111
- model: readString(firstModel, "id") || profile.model,
28112
- extras: {
28113
- ...profile.extras,
28114
- api: readString(provider, "api") || profile.extras.api || "",
28115
- contextWindow: valueString2(firstModel?.contextWindow, profile.extras.contextWindow),
28116
- maxTokens: valueString2(firstModel?.maxTokens, profile.extras.maxTokens),
28117
- reasoning: firstModel?.reasoning === true ? "true" : profile.extras.reasoning || "false"
28118
- }
28119
- };
28120
- } catch {
28570
+ const models = tryParseJsonObject(current[MODELS]);
28571
+ if (!models) {
28572
+ return {};
28573
+ }
28574
+ const id = providerId(profile);
28575
+ const providers = models.providers;
28576
+ const provider = isPlainObject2(providers) ? providers[id] : undefined;
28577
+ if (!isPlainObject2(provider)) {
28121
28578
  return {};
28122
28579
  }
28580
+ const firstModel = Array.isArray(provider.models) ? provider.models.find((entry) => isPlainObject2(entry)) : undefined;
28581
+ const apiKey = readString(provider, "apiKey");
28582
+ return {
28583
+ baseUrl: readString(provider, "baseUrl") || profile.baseUrl,
28584
+ apiKey: apiKey || profile.apiKey,
28585
+ model: readString(firstModel, "id") || profile.model,
28586
+ extras: {
28587
+ ...profile.extras,
28588
+ api: readString(provider, "api") || profile.extras.api || "",
28589
+ contextWindow: valueString(firstModel?.contextWindow, profile.extras.contextWindow),
28590
+ maxTokens: valueString(firstModel?.maxTokens, profile.extras.maxTokens),
28591
+ reasoning: firstModel?.reasoning === true ? "true" : profile.extras.reasoning || "false"
28592
+ }
28593
+ };
28123
28594
  }
28124
28595
  detect(current) {
28125
- let providers;
28126
- let selected = "";
28127
- try {
28128
- providers = parseJsonObject(current[MODELS]).providers;
28129
- selected = readString(parseJsonObject(current[SETTINGS3]), "defaultProvider");
28130
- } catch {
28596
+ const models = tryParseJsonObject(current[MODELS]);
28597
+ const settings = tryParseJsonObject(current[SETTINGS3]);
28598
+ if (!models || !settings) {
28131
28599
  return [];
28132
28600
  }
28601
+ const providers = models.providers;
28602
+ const selected = readString(settings, "defaultProvider");
28133
28603
  if (!isPlainObject2(providers)) {
28134
28604
  return [];
28135
28605
  }
@@ -28144,16 +28614,6 @@ class PiAdapter {
28144
28614
  return toCandidate(id, seed, this.backfill(seed, current), id === selected);
28145
28615
  }));
28146
28616
  }
28147
- providerId(profile) {
28148
- return slugify2(profile.extras.providerId || profile.name, "provider");
28149
- }
28150
- numeric(raw2, fallback) {
28151
- const parsed = Number(raw2);
28152
- return Number.isFinite(parsed) && parsed > 0 ? Math.trunc(parsed) : fallback;
28153
- }
28154
- }
28155
- function valueString2(value, fallback) {
28156
- return typeof value === "number" && Number.isFinite(value) ? String(value) : fallback || "";
28157
28617
  }
28158
28618
 
28159
28619
  // src/services/adapters/index.ts
@@ -28925,9 +29385,6 @@ class LiveWriteService {
28925
29385
  }
28926
29386
  transaction(plan, operation) {
28927
29387
  const { harness, profile, writes } = plan;
28928
- if (writes.length === 0) {
28929
- return operation();
28930
- }
28931
29388
  for (const write of writes) {
28932
29389
  this.files.assertManaged(write.path);
28933
29390
  assertParsable(write.format, write.path, write.content);
@@ -28937,7 +29394,7 @@ class LiveWriteService {
28937
29394
  path: write.path,
28938
29395
  content: this.files.readOptional(write.path)
28939
29396
  }));
28940
- const backupId = this.backups.create(harness, profile, snapshots);
29397
+ const backupId = writes.length === 0 ? null : this.backups.create(harness, profile, snapshots);
28941
29398
  const entry = this.journal.begin({
28942
29399
  kind: plan.kind,
28943
29400
  harness,
@@ -29282,15 +29739,15 @@ class ProfileService {
29282
29739
  });
29283
29740
  }
29284
29741
  const hasProvider = input.providerId !== undefined;
29285
- const providerId = input.providerId?.trim() || undefined;
29742
+ const providerId2 = input.providerId?.trim() || undefined;
29286
29743
  const providerEndpoint = input.providerEndpoint?.trim() || undefined;
29287
29744
  const hasInlineKey = input.apiKey !== undefined && input.apiKey.trim() !== "";
29288
29745
  const inlineKey = (input.apiKey ?? "").trim();
29289
29746
  let nextProviderId = prior?.provider_id;
29290
29747
  let nextProviderEndpoint = prior?.provider_endpoint;
29291
29748
  let apiKey = "";
29292
- if (hasProvider && providerId) {
29293
- const entry = this.vault.get(providerId);
29749
+ if (hasProvider && providerId2) {
29750
+ const entry = this.vault.get(providerId2);
29294
29751
  if (providerEndpoint) {
29295
29752
  const endpoint = entry.endpoints.find((candidate) => candidate.key === providerEndpoint);
29296
29753
  if (!endpoint) {
@@ -29303,9 +29760,9 @@ class ProfileService {
29303
29760
  } else {
29304
29761
  nextProviderEndpoint = undefined;
29305
29762
  }
29306
- nextProviderId = providerId;
29307
- apiKey = this.vault.decrypt(providerId);
29308
- } else if (hasProvider && !providerId) {
29763
+ nextProviderId = providerId2;
29764
+ apiKey = this.vault.decrypt(providerId2);
29765
+ } else if (hasProvider && !providerId2) {
29309
29766
  nextProviderId = undefined;
29310
29767
  nextProviderEndpoint = undefined;
29311
29768
  apiKey = hasInlineKey ? inlineKey : prior ? this.crypto.decrypt(prior.api_key) : "";
@@ -29319,7 +29776,7 @@ class ProfileService {
29319
29776
  if (isCreate && !apiKey) {
29320
29777
  throw new HttpError(400, "apiKey is required", { code: ERROR_CODES.profileApiKeyRequired });
29321
29778
  }
29322
- const baseUrl = this.resolveBaseUrl((input.baseUrl ?? prior?.base_url ?? "").trim(), providerId || nextProviderId, providerEndpoint || nextProviderEndpoint);
29779
+ const baseUrl = this.resolveBaseUrl((input.baseUrl ?? prior?.base_url ?? "").trim(), providerId2 || nextProviderId, providerEndpoint || nextProviderEndpoint);
29323
29780
  const next = {
29324
29781
  base_url: baseUrl,
29325
29782
  api_key: this.crypto.encrypt(apiKey),
@@ -29458,15 +29915,15 @@ class ProfileService {
29458
29915
  return this.crypto.decrypt(stored.api_key);
29459
29916
  }
29460
29917
  }
29461
- resolveBaseUrl(fallback, providerId, providerEndpoint) {
29462
- if (!providerId || !providerEndpoint) {
29918
+ resolveBaseUrl(fallback, providerId2, providerEndpoint) {
29919
+ if (!providerId2 || !providerEndpoint) {
29463
29920
  return fallback;
29464
29921
  }
29465
29922
  let entry;
29466
29923
  try {
29467
- entry = this.vault.get(providerId);
29924
+ entry = this.vault.get(providerId2);
29468
29925
  } catch {
29469
- this.log.warn(`profile 引用的 provider ${providerId} 不存在,回退到内联 base_url`);
29926
+ this.log.warn(`profile 引用的 provider ${providerId2} 不存在,回退到内联 base_url`);
29470
29927
  return fallback;
29471
29928
  }
29472
29929
  const endpoint = entry.endpoints.find((candidate) => candidate.key === providerEndpoint);
@@ -29474,7 +29931,7 @@ class ProfileService {
29474
29931
  return endpoint.baseUrl;
29475
29932
  }
29476
29933
  if (entry.endpoints.length > 0) {
29477
- this.log.warn(`endpoint ${providerEndpoint} 已不存在,回退到 provider ${providerId} 的首个 endpoint`);
29934
+ this.log.warn(`endpoint ${providerEndpoint} 已不存在,回退到 provider ${providerId2} 的首个 endpoint`);
29478
29935
  return entry.endpoints[0].baseUrl;
29479
29936
  }
29480
29937
  return fallback;
@@ -29643,6 +30100,20 @@ class ActivationService {
29643
30100
  };
29644
30101
  });
29645
30102
  }
30103
+ previewOfficial(harness) {
30104
+ return this.expectedOfficialWrites(harness).map((write) => {
30105
+ const target = this.requireTarget(this.adapters.get(harness).targets(), write.key);
30106
+ return {
30107
+ key: write.key,
30108
+ label: target.label,
30109
+ path: write.path,
30110
+ format: write.format,
30111
+ content: write.content,
30112
+ overridden: false,
30113
+ currentContent: this.files.readOptional(write.path) ?? null
30114
+ };
30115
+ });
30116
+ }
29646
30117
  reconcileProfileUpdate(harness, previousName, nextName) {
29647
30118
  const adapter = this.adapters.get(harness);
29648
30119
  if (previousName !== nextName && adapter.revoke) {
@@ -30144,8 +30615,8 @@ class ProbeService {
30144
30615
  params: { status: response.status }
30145
30616
  });
30146
30617
  }
30147
- const text = await response.text();
30148
- if (text.length > MAX_BODY_BYTES) {
30618
+ const text = await readBody(response);
30619
+ if (text === null) {
30149
30620
  return failure(PROBE_CODES.invalidResponse, "响应体过大,不是模型目录", shared);
30150
30621
  }
30151
30622
  const models = extractModels(text);
@@ -30159,6 +30630,33 @@ ProbeService = __decorateElement(_init, 0, "ProbeService", _dec, ProbeService);
30159
30630
  __runInitializers(_init, 1, ProbeService);
30160
30631
  __decoratorMetadata(_init, ProbeService);
30161
30632
  let _ProbeService = ProbeService;
30633
+ async function readBody(response) {
30634
+ const declaredLength = response.headers.get("content-length");
30635
+ if (declaredLength && Number(declaredLength) > MAX_BODY_BYTES) {
30636
+ return null;
30637
+ }
30638
+ if (!response.body)
30639
+ return "";
30640
+ const reader = response.body.getReader();
30641
+ const chunks = [];
30642
+ let size = 0;
30643
+ try {
30644
+ while (true) {
30645
+ const { done, value } = await reader.read();
30646
+ if (done)
30647
+ break;
30648
+ size += value.byteLength;
30649
+ if (size > MAX_BODY_BYTES) {
30650
+ await reader.cancel("catalog body too large");
30651
+ return null;
30652
+ }
30653
+ chunks.push(value);
30654
+ }
30655
+ } finally {
30656
+ reader.releaseLock();
30657
+ }
30658
+ return new TextDecoder().decode(Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))));
30659
+ }
30162
30660
  function joinUrl(base, suffix) {
30163
30661
  const next = new URL(base.toString());
30164
30662
  next.pathname = `${next.pathname.replace(/\/+$/, "")}/${suffix}`;
@@ -31509,6 +32007,7 @@ function createHarnessRoutes(services) {
31509
32007
  targets: adapter.targets(),
31510
32008
  envVars: adapter.envVarNames,
31511
32009
  envNote: adapter.envNote,
32010
+ envNoteCode: adapter.envNoteCode,
31512
32011
  supportsOfficialAuth: adapter.renderOfficial !== undefined
31513
32012
  };
31514
32013
  }
@@ -31594,6 +32093,10 @@ function createHarnessRoutes(services) {
31594
32093
  const name = decodeURIComponent(c.req.param("name"));
31595
32094
  return c.json({ targets: activation.preview(harnessId, name) });
31596
32095
  });
32096
+ app.get("/:harnessId/official/preview", (c) => {
32097
+ const harnessId = harnesses.require(c.req.param("harnessId"));
32098
+ return c.json({ targets: activation.previewOfficial(harnessId) });
32099
+ });
31597
32100
  app.post("/:harnessId/profiles/:name/probe", async (c) => {
31598
32101
  const harnessId = harnesses.require(c.req.param("harnessId"));
31599
32102
  const name = decodeURIComponent(c.req.param("name"));
@@ -31823,20 +32326,20 @@ class ScanService {
31823
32326
  return { ok: true, imported, skipped, providersCreated, warnings };
31824
32327
  }
31825
32328
  save(harness, candidate, selection, replacing) {
31826
- let providerId;
32329
+ let providerId2;
31827
32330
  let created = 0;
31828
32331
  const apiKey = candidate.apiKey || selection.apiKey?.trim() || "";
31829
32332
  if (selection.target === "vault") {
31830
32333
  if (selection.providerId) {
31831
32334
  this.vault.get(selection.providerId);
31832
- providerId = selection.providerId;
32335
+ providerId2 = selection.providerId;
31833
32336
  } else {
31834
32337
  if (!apiKey) {
31835
32338
  throw new HttpError(400, "这条配置里没有可提取的凭据,请先填写 API key", {
31836
32339
  code: ERROR_CODES.scanApiKeyRequired
31837
32340
  });
31838
32341
  }
31839
- providerId = this.vault.create({
32342
+ providerId2 = this.vault.create({
31840
32343
  name: selection.providerName ?? selection.name,
31841
32344
  apiKey,
31842
32345
  endpoints: candidate.baseUrl ? [{ key: "default", label: "默认", baseUrl: candidate.baseUrl }] : []
@@ -31856,7 +32359,7 @@ class ScanService {
31856
32359
  model: candidate.model,
31857
32360
  notes: `从 ${harness} 现有配置导入(${candidate.key})`,
31858
32361
  extras: candidate.extras,
31859
- ...providerId ? { providerId, providerEndpoint: "default" } : {}
32362
+ ...providerId2 ? { providerId: providerId2, providerEndpoint: "default" } : {}
31860
32363
  }, !replacing);
31861
32364
  return created;
31862
32365
  }
@@ -32377,14 +32880,14 @@ class UserSyncService {
32377
32880
  return isDeepStrictEqual2(this.comparableProfile(source, sourceProviders), this.comparableProfile(target, targetProviders));
32378
32881
  }
32379
32882
  comparableProfile(profile, providers) {
32380
- const { updated_at: _updatedAt, provider_id: providerId, ...content } = profile;
32381
- const provider = providerId ? providers[providerId] : undefined;
32883
+ const { updated_at: _updatedAt, provider_id: providerId2, ...content } = profile;
32884
+ const provider = providerId2 ? providers[providerId2] : undefined;
32382
32885
  const comparableProvider = provider ? {
32383
32886
  name: provider.name,
32384
32887
  notes: provider.notes,
32385
32888
  endpoints: provider.endpoints,
32386
32889
  apiKey: provider.apiKey
32387
- } : providerId ? { missing: true } : undefined;
32890
+ } : providerId2 ? { missing: true } : undefined;
32388
32891
  return { ...content, provider: comparableProvider };
32389
32892
  }
32390
32893
  readVault() {
@@ -32545,7 +33048,7 @@ function createApp(services) {
32545
33048
  }
32546
33049
  app.notFound((c) => {
32547
33050
  const code = ERROR_CODES.requestFailed;
32548
- return c.json({ code, msg: localizeError(requestLanguage(c.req.header("Accept-Language")), code) }, 404);
33051
+ return c.json({ code, msg: localizeMessage(requestLanguage(c.req.header("Accept-Language")), code) }, 404);
32549
33052
  });
32550
33053
  app.onError((error52, c) => {
32551
33054
  const request = `${c.req.method} ${new URL(c.req.url).pathname}`;
@@ -32557,14 +33060,14 @@ function createApp(services) {
32557
33060
  return c.json({
32558
33061
  code: error52.code,
32559
33062
  ...data ? { data } : {},
32560
- msg: localizeError(requestLanguage(c.req.header("Accept-Language")), error52.code, data)
33063
+ msg: localizeMessage(requestLanguage(c.req.header("Accept-Language")), error52.code, data)
32561
33064
  }, error52.status);
32562
33065
  }
32563
33066
  log.error(`unhandled error on ${request}`, error52);
32564
33067
  const code = ERROR_CODES.internalServerError;
32565
33068
  return c.json({
32566
33069
  code,
32567
- msg: localizeError(requestLanguage(c.req.header("Accept-Language")), code)
33070
+ msg: localizeMessage(requestLanguage(c.req.header("Accept-Language")), code)
32568
33071
  }, 500);
32569
33072
  });
32570
33073
  return app;
@@ -33609,6 +34112,16 @@ function fail(error52, json2) {
33609
34112
  }
33610
34113
 
33611
34114
  // src/main.ts
34115
+ var MAX_HTTP_BODY_BYTES = 16 * 1024 * 1024;
34116
+
34117
+ class BodyTooLargeError extends Error {
34118
+ kind;
34119
+ constructor(kind) {
34120
+ super(`${kind} body exceeds ${MAX_HTTP_BODY_BYTES} bytes`);
34121
+ this.kind = kind;
34122
+ this.name = "BodyTooLargeError";
34123
+ }
34124
+ }
33612
34125
  async function runServer() {
33613
34126
  const services = createServices();
33614
34127
  const environment = services.get(IEnvironmentService);
@@ -33629,7 +34142,7 @@ async function runServer() {
33629
34142
  async function handleNodeRequest(handler, request, response) {
33630
34143
  try {
33631
34144
  const origin = `http://${request.headers.host ?? "localhost"}`;
33632
- const body = ["GET", "HEAD"].includes(request.method ?? "") ? undefined : await readBody(request);
34145
+ const body = ["GET", "HEAD"].includes(request.method ?? "") ? undefined : await readBody2(request);
33633
34146
  const headers = new Headers;
33634
34147
  for (const [name, value] of Object.entries(request.headers)) {
33635
34148
  if (value !== undefined)
@@ -33640,6 +34153,7 @@ async function handleNodeRequest(handler, request, response) {
33640
34153
  headers,
33641
34154
  ...body ? { body, duplex: "half" } : {}
33642
34155
  }));
34156
+ const resultBody = await readResponseBody(result, MAX_HTTP_BODY_BYTES);
33643
34157
  response.statusCode = result.status;
33644
34158
  const cookies = result.headers.getSetCookie?.() ?? [];
33645
34159
  for (const [name, value] of result.headers) {
@@ -33648,18 +34162,63 @@ async function handleNodeRequest(handler, request, response) {
33648
34162
  }
33649
34163
  if (cookies.length > 0)
33650
34164
  response.setHeader("set-cookie", cookies);
33651
- response.end(Buffer.from(await result.arrayBuffer()));
33652
- } catch {
33653
- response.statusCode = 500;
33654
- response.end("internal server error");
34165
+ response.end(resultBody);
34166
+ } catch (error52) {
34167
+ if (response.headersSent) {
34168
+ response.destroy();
34169
+ return;
34170
+ }
34171
+ response.statusCode = error52 instanceof BodyTooLargeError && error52.kind === "request" ? 413 : 500;
34172
+ response.end(error52 instanceof BodyTooLargeError && error52.kind === "request" ? "request body too large" : "internal server error");
33655
34173
  }
33656
34174
  }
33657
- async function readBody(request) {
34175
+ async function readBody2(request) {
34176
+ const declaredLength = request.headers["content-length"];
34177
+ const contentLength = declaredLength ? Number(declaredLength) : undefined;
34178
+ if (contentLength !== undefined && Number.isFinite(contentLength) && contentLength > MAX_HTTP_BODY_BYTES) {
34179
+ request.resume();
34180
+ throw new BodyTooLargeError("request");
34181
+ }
33658
34182
  const chunks = [];
33659
- for await (const chunk of request)
33660
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
34183
+ let size = 0;
34184
+ for await (const chunk of request) {
34185
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
34186
+ size += buffer.byteLength;
34187
+ if (size > MAX_HTTP_BODY_BYTES) {
34188
+ request.resume();
34189
+ throw new BodyTooLargeError("request");
34190
+ }
34191
+ chunks.push(buffer);
34192
+ }
33661
34193
  return chunks.length > 0 ? Buffer.concat(chunks) : undefined;
33662
34194
  }
34195
+ async function readResponseBody(response, limit) {
34196
+ const declaredLength = response.headers.get("content-length");
34197
+ if (declaredLength && Number(declaredLength) > limit) {
34198
+ throw new BodyTooLargeError("response");
34199
+ }
34200
+ if (!response.body)
34201
+ return Buffer.alloc(0);
34202
+ const reader = response.body.getReader();
34203
+ const chunks = [];
34204
+ let size = 0;
34205
+ try {
34206
+ while (true) {
34207
+ const { done, value } = await reader.read();
34208
+ if (done)
34209
+ break;
34210
+ size += value.byteLength;
34211
+ if (size > limit) {
34212
+ await reader.cancel("response body too large");
34213
+ throw new BodyTooLargeError("response");
34214
+ }
34215
+ chunks.push(value);
34216
+ }
34217
+ } finally {
34218
+ reader.releaseLock();
34219
+ }
34220
+ return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));
34221
+ }
33663
34222
  var [command, ...rest] = process.argv.slice(2);
33664
34223
  if (command === "help" || command === "--help" || command === "-h") {
33665
34224
  console.log(cliUsage());