@agentchatme/claude-code 0.5.2 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4244,7 +4244,7 @@ var init_wrapper = __esm({
4244
4244
  import * as fs11 from "fs";
4245
4245
  import { parseArgs } from "util";
4246
4246
 
4247
- // node_modules/.pnpm/@agentchatme+agent-core@0.5.2/node_modules/@agentchatme/agent-core/dist/chunk-AFDD53DD.js
4247
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.3/node_modules/@agentchatme/agent-core/dist/chunk-3OUDKIQV.js
4248
4248
  var import_cross_spawn = __toESM(require_cross_spawn(), 1);
4249
4249
  import { randomBytes } from "crypto";
4250
4250
  import * as fs from "fs";
@@ -4345,24 +4345,6 @@ function readJsonFile(filePath) {
4345
4345
  return null;
4346
4346
  }
4347
4347
  }
4348
- var LEVELS = ["silent", "error", "warn", "info", "debug"];
4349
- function activeLevel() {
4350
- const raw = (process.env["AGENTCHAT_LOG_LEVEL"] ?? "warn").toLowerCase();
4351
- const idx = LEVELS.indexOf(raw);
4352
- return idx === -1 ? LEVELS.indexOf("warn") : idx;
4353
- }
4354
- function emit(level, msg) {
4355
- if (LEVELS.indexOf(level) <= activeLevel() && level !== "silent") {
4356
- process.stderr.write(`[agentchat:${level}] ${msg}
4357
- `);
4358
- }
4359
- }
4360
- var log = {
4361
- error: (msg) => emit("error", msg),
4362
- warn: (msg) => emit("warn", msg),
4363
- info: (msg) => emit("info", msg),
4364
- debug: (msg) => emit("debug", msg)
4365
- };
4366
4348
  var RUN_PROFILES = ["answer", "work", "full"];
4367
4349
  var PEER_RUN_WARNING = "runs started by peers' messages can read and change this machine";
4368
4350
  function runProfileWarning(profile2) {
@@ -4430,6 +4412,24 @@ function integrationDisabled(env = process.env) {
4430
4412
  var RUN_BUDGET_ENV = "AGENTCHAT_RUN_BUDGET_MS";
4431
4413
  var DEFAULT_RUN_BUDGET_MS = 10 * 6e4;
4432
4414
  var MAX_RUN_BUDGET_MS = 2 * 60 * 6e4;
4415
+ var LEVELS = ["silent", "error", "warn", "info", "debug"];
4416
+ function activeLevel() {
4417
+ const raw = (process.env["AGENTCHAT_LOG_LEVEL"] ?? "warn").toLowerCase();
4418
+ const idx = LEVELS.indexOf(raw);
4419
+ return idx === -1 ? LEVELS.indexOf("warn") : idx;
4420
+ }
4421
+ function emit(level, msg) {
4422
+ if (LEVELS.indexOf(level) <= activeLevel() && level !== "silent") {
4423
+ process.stderr.write(`[agentchat:${level}] ${msg}
4424
+ `);
4425
+ }
4426
+ }
4427
+ var log = {
4428
+ error: (msg) => emit("error", msg),
4429
+ warn: (msg) => emit("warn", msg),
4430
+ info: (msg) => emit("info", msg),
4431
+ debug: (msg) => emit("debug", msg)
4432
+ };
4433
4433
  var spawnCommand = import_cross_spawn.default;
4434
4434
  var spawnCommandSync = import_cross_spawn.default.sync;
4435
4435
  var DEFAULT_GRACE_MS = 5e3;
@@ -4700,7 +4700,7 @@ function spawnRun(spec) {
4700
4700
  });
4701
4701
  }
4702
4702
 
4703
- // node_modules/.pnpm/@agentchatme+agent-core@0.5.2/node_modules/@agentchatme/agent-core/dist/chunk-CDJASQ3X.js
4703
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.3/node_modules/@agentchatme/agent-core/dist/chunk-CQSL6X4D.js
4704
4704
  import * as path3 from "path";
4705
4705
 
4706
4706
  // node_modules/.pnpm/agentchatme@1.4.0_ws@8.21.1/node_modules/agentchatme/dist/index.js
@@ -10910,7 +10910,7 @@ var DAY = 24 * HOUR;
10910
10910
  var INBOX_TRAY_MAX_LIMIT = 50;
10911
10911
  var MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024;
10912
10912
 
10913
- // node_modules/.pnpm/@agentchatme+agent-core@0.5.2/node_modules/@agentchatme/agent-core/dist/chunk-CDJASQ3X.js
10913
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.3/node_modules/@agentchatme/agent-core/dist/chunk-CQSL6X4D.js
10914
10914
  import * as fs3 from "fs";
10915
10915
  import * as path22 from "path";
10916
10916
  import { createHash } from "crypto";
@@ -15009,19 +15009,6 @@ function resolveIdentity(home, options = {}) {
15009
15009
  const envKey = options.envKey === false ? void 0 : process.env["AGENTCHAT_API_KEY"];
15010
15010
  const envBase = process.env["AGENTCHAT_API_BASE"];
15011
15011
  const file = readCredentials(home);
15012
- if (envKey && envKey.trim().length >= 20) {
15013
- return {
15014
- apiKey: envKey.trim(),
15015
- apiBase: envBase?.trim() || file?.api_base || DEFAULT_API_BASE2,
15016
- handle: file?.handle ?? null,
15017
- source: "env"
15018
- };
15019
- }
15020
- if (envKey && envKey.trim().length > 0 && file) {
15021
- log.warn(
15022
- "AGENTCHAT_API_KEY is set but malformed (under 20 chars); using the credentials-file identity instead"
15023
- );
15024
- }
15025
15012
  if (file) {
15026
15013
  return {
15027
15014
  apiKey: file.api_key,
@@ -15030,8 +15017,23 @@ function resolveIdentity(home, options = {}) {
15030
15017
  source: "file"
15031
15018
  };
15032
15019
  }
15020
+ if (envKey && envKey.trim().length >= 20) {
15021
+ return {
15022
+ apiKey: envKey.trim(),
15023
+ apiBase: envBase?.trim() || DEFAULT_API_BASE2,
15024
+ handle: null,
15025
+ source: "env"
15026
+ };
15027
+ }
15033
15028
  return null;
15034
15029
  }
15030
+ function envKeyConflict(home, env = process.env) {
15031
+ const exported = env["AGENTCHAT_API_KEY"]?.trim();
15032
+ if (exported === void 0 || exported.length === 0) return null;
15033
+ const stored = readCredentials(home);
15034
+ if (stored === null || stored.api_key === exported) return null;
15035
+ return `AGENTCHAT_API_KEY is exported and is not the key ${credentialsPath(home)} holds (it is another agent's key, or an old one); commands for this agent act only with that file's key`;
15036
+ }
15035
15037
  function writeCredentials(home, creds) {
15036
15038
  atomicWriteFile(credentialsPath(home), JSON.stringify(creds, null, 2) + "\n", 384);
15037
15039
  }
@@ -15550,8 +15552,8 @@ function agentLockDir(env = process.env, system = process.platform, home = os22.
15550
15552
  return p.join(home, ".local", "state", "agentchat", "locks");
15551
15553
  }
15552
15554
 
15553
- // node_modules/.pnpm/@agentchatme+agent-core@0.5.2/node_modules/@agentchatme/agent-core/dist/chunk-WDHXWAWF.js
15554
- var VERSION2 = "0.5.2";
15555
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.3/node_modules/@agentchatme/agent-core/dist/chunk-JL2L4WRG.js
15556
+ var VERSION2 = "0.5.3";
15555
15557
  var HOSTED_MCP_PATH2 = integration_exports.HOSTED_MCP_PATH;
15556
15558
  function hostedMcpUrl2(apiBase) {
15557
15559
  return integration_exports.hostedMcpUrl(apiBase);
@@ -15627,7 +15629,7 @@ function runProbe(command, args, options) {
15627
15629
  });
15628
15630
  }
15629
15631
 
15630
- // node_modules/.pnpm/@agentchatme+agent-core@0.5.2/node_modules/@agentchatme/agent-core/dist/index.js
15632
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.3/node_modules/@agentchatme/agent-core/dist/index.js
15631
15633
  import * as fs5 from "fs";
15632
15634
  import * as path5 from "path";
15633
15635
  import * as readline from "readline";
@@ -15835,7 +15837,7 @@ function renderUnregisteredBlock(copy) {
15835
15837
  "**Run the commands yourself, and ask the user one question per turn.** Each command prints AgentChat\u2019s answer, then the command to run next. Relay the answer to the user as it is; ask them for what the next command needs (a value it leaves as `<\u2026>`, such as the code AgentChat emailed them); if it says to wait, wait; then run it. When a command prints no command to run next, stop and tell the user what it said.",
15836
15838
  "",
15837
15839
  `- **New account:** ask for their email, then for the @handle they want (offer a suggestion if they like). Run: \`${invoke} register --email <email> --handle <handle>\`. Never submit a handle the user has not chosen or accepted.`,
15838
- `- **Existing account, with its API key:** run: \`${invoke} login --api-key <ac_\u2026>\``,
15840
+ `- **Existing account, with its API key:** ask the user to run \`${invoke} login\` in their own terminal and paste the key when it asks. Never ask them to paste the key into this conversation, and never put a key in a command you run: a command line is visible to every user of the machine.`,
15839
15841
  `- **Existing account, key lost:** recovery replaces the old API key, so anything still using it stops working; say so and ask before going on. Ask for the email the account uses, then which @handle it is. Run: \`${invoke} recover --handle <handle> --email <email>\``,
15840
15842
  "- **When it is done:** tell the user the @handle and where the API key is stored, exactly as the command printed them.",
15841
15843
  "- Never reuse another active coding agent\u2019s account; each reachable agent needs its own.",
@@ -15952,6 +15954,11 @@ function createIdentityCommands(profile2) {
15952
15954
  const invocation2 = () => profile2.invocation();
15953
15955
  const LABEL2 = profile2.label;
15954
15956
  const clientIdentity = clientIdentityOf(profile2.client);
15957
+ function envKeyRefusal() {
15958
+ const conflict = envKeyConflict(profile2.home());
15959
+ if (conflict === null) return null;
15960
+ return `${conflict}. Unset AGENTCHAT_API_KEY, or, to sign this home in with that key on purpose: printenv AGENTCHAT_API_KEY | ${invocation2()} login --api-key -`;
15961
+ }
15955
15962
  const apiClient = (apiKey, apiBase) => new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 5e3, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } });
15956
15963
  const accountOptions = (apiBase) => ({ clientIdentity, apiBase, timeoutMs: 15e3 });
15957
15964
  async function served(apiKey, apiBase) {
@@ -16198,16 +16205,23 @@ ${runLine(codeCommand(kind, pending.flow, code))} again.`);
16198
16205
  const home = profile2.home();
16199
16206
  const apiBase = opts.apiBase ?? process.env["AGENTCHAT_API_BASE"] ?? DEFAULT_API_BASE2;
16200
16207
  let apiKey = opts.apiKey?.trim();
16208
+ const onArgv = apiKey !== void 0 && apiKey.length > 0 && apiKey !== "-";
16201
16209
  if (apiKey === "-") {
16202
16210
  apiKey = await readAllStdin();
16203
16211
  } else if (!apiKey) {
16204
16212
  const fromEnv = process.env["AGENTCHAT_API_KEY"]?.trim();
16213
+ const refusal2 = fromEnv ? envKeyRefusal() : null;
16214
+ if (refusal2 !== null) {
16215
+ console.error(`${refusal2}
16216
+ login does not adopt an exported key in place of the one this home holds; nothing was saved.`);
16217
+ return 1;
16218
+ }
16205
16219
  if (fromEnv) {
16206
16220
  apiKey = fromEnv;
16207
16221
  console.log("Using the key from AGENTCHAT_API_KEY.");
16208
16222
  } else if (process.stdin.isTTY !== true) {
16209
16223
  console.error(
16210
- `Missing API key. Pipe it in: printf %s "$KEY" | ${invocation2()} login --api-key - (or set AGENTCHAT_API_KEY, or pass --api-key ac_live_\u2026, which \`ps\` and shell history can see)`
16224
+ `Missing API key. Run \`${invocation2()} login\` in a terminal and paste the key when it asks, or pipe it in from a file: \`${invocation2()} login --api-key - < key.txt\`. Never put the key itself on a command line: \`ps\` and shell history can see it there.`
16211
16225
  );
16212
16226
  return 1;
16213
16227
  } else {
@@ -16243,7 +16257,10 @@ The key was not saved.`);
16243
16257
  `Signed in as @${check.handle} for ${LABEL2}.`,
16244
16258
  `API key stored at ${credentialsPath(home)} (never commit this file).`,
16245
16259
  ...await placeIdentity(check.handle, apiKey, apiBase),
16246
- NEXT_HINT
16260
+ NEXT_HINT,
16261
+ ...onArgv ? [
16262
+ `Note: the key was on this command line, where \`ps\` and shell history can see it. Next time run \`${invocation2()} login\` and paste it, or pipe it in: \`${invocation2()} login --api-key - < key.txt\`.`
16263
+ ] : []
16247
16264
  ].join("\n")
16248
16265
  );
16249
16266
  return 0;
@@ -16284,6 +16301,12 @@ The key was not saved.`);
16284
16301
  async function runStatus2(opts) {
16285
16302
  const home = profile2.home();
16286
16303
  const anchorFile2 = profile2.anchorFile?.() ?? null;
16304
+ const refusal2 = envKeyRefusal();
16305
+ if (refusal2 !== null) {
16306
+ if (opts.json) console.log(JSON.stringify({ configured: true, host: profile2.id, error: { kind: "env_key_conflict", detail: refusal2 }, home }));
16307
+ else console.error(refusal2);
16308
+ return 1;
16309
+ }
16287
16310
  const identity = resolveIdentity(home);
16288
16311
  const pending = readPending(home);
16289
16312
  const integration = readIntegrationStatus(home);
@@ -16476,6 +16499,8 @@ The key was not saved.`);
16476
16499
  let texts = NO_TEXTS;
16477
16500
  checks.push({ name: "node", verdict: "PASS", detail: process.version });
16478
16501
  checks.push({ name: "home", verdict: "PASS", detail: home });
16502
+ const refusal2 = envKeyRefusal();
16503
+ if (refusal2 !== null) checks.push({ name: "env-key", verdict: "FAIL", detail: refusal2 });
16479
16504
  const creds = readCredentials(home);
16480
16505
  if (creds === null) {
16481
16506
  checks.push({
@@ -17203,7 +17228,7 @@ function serviceDefinitionCurrent(opts) {
17203
17228
  import * as os5 from "os";
17204
17229
  import * as path8 from "path";
17205
17230
 
17206
- // node_modules/.pnpm/@agentchatme+agent-core@0.5.2/node_modules/@agentchatme/agent-core/dist/presets.js
17231
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.3/node_modules/@agentchatme/agent-core/dist/presets.js
17207
17232
  import * as fs6 from "fs";
17208
17233
  import * as os4 from "os";
17209
17234
  import * as path6 from "path";
@@ -18221,7 +18246,7 @@ var PRESETS = Object.freeze({
18221
18246
  });
18222
18247
 
18223
18248
  // src/version.ts
18224
- var VERSION3 = "0.5.2";
18249
+ var VERSION3 = "0.5.3";
18225
18250
 
18226
18251
  // src/host.ts
18227
18252
  function claudeConfigOverride() {
@@ -18313,6 +18338,13 @@ import * as path10 from "path";
18313
18338
  // src/runner.ts
18314
18339
  import * as fs7 from "fs";
18315
18340
  import * as path9 from "path";
18341
+
18342
+ // src/home-identity.ts
18343
+ function homeIdentity(home) {
18344
+ return resolveIdentity(home, { envKey: readCredentials(home) === null });
18345
+ }
18346
+
18347
+ // src/runner.ts
18316
18348
  function denyReadPathsFor(configDirOverride) {
18317
18349
  return [identityHomeFor(configDirOverride), claudeUserStatePathFor2(configDirOverride)];
18318
18350
  }
@@ -18320,7 +18352,7 @@ function answerToolConfigFor(identityHome2) {
18320
18352
  return claudeMcpConfigPath(identityHome2);
18321
18353
  }
18322
18354
  function answerRunKey(identityHome2, apiBase, handle) {
18323
- const id = resolveIdentity(identityHome2);
18355
+ const id = homeIdentity(identityHome2);
18324
18356
  if (id === null || id.apiBase !== apiBase) return null;
18325
18357
  if (handle !== void 0 && id.source === "file" && id.handle !== null && id.handle !== handle) return null;
18326
18358
  return id.apiKey;
@@ -18404,6 +18436,79 @@ function runClaude(args, timeout = 2e4) {
18404
18436
  ${result.stdout ?? ""}`.trim();
18405
18437
  return { ok: result.status === 0, detail: output || `exited ${result.status}` };
18406
18438
  }
18439
+ function headersHelperPath() {
18440
+ return path10.join(identityHome(), "bin", "mcp-headers.mjs");
18441
+ }
18442
+ var HEADERS_HELPER_SOURCE = [
18443
+ "// Written by @agentchatme/claude-code. Claude Code runs this on each connection to the",
18444
+ '// user MCP server "agentchat" (its headersHelper) and sends what it prints as headers:',
18445
+ "// the Authorization header for the key in the credentials file of this identity home,",
18446
+ "// or nothing when there is none. It reads no environment variable. Do not edit: install",
18447
+ "// and doctor --fix rewrite it.",
18448
+ "import { readFileSync } from 'node:fs'",
18449
+ "let headers = {}",
18450
+ "try {",
18451
+ " const creds = JSON.parse(readFileSync(new URL('../credentials', import.meta.url), 'utf8'))",
18452
+ " const key = creds !== null && typeof creds.api_key === 'string' ? creds.api_key.trim() : ''",
18453
+ " if (key.length >= 20 && !/\\s/.test(key)) headers = { Authorization: `Bearer ${key}` }",
18454
+ "} catch {}",
18455
+ "process.stdout.write(JSON.stringify(headers))",
18456
+ ""
18457
+ ].join("\n");
18458
+ function headersHelperCommand(node = process.execPath, script = headersHelperPath(), platform = process.platform) {
18459
+ const paths = [node, script];
18460
+ if (paths.some((p) => /[\r\n]/.test(p))) return null;
18461
+ if (platform === "win32") return paths.some((p) => /["%$`]/.test(p)) ? null : paths.map((p) => `"${p}"`).join(" ");
18462
+ return paths.map((p) => `'${p.replace(/'/g, `'\\''`)}'`).join(" ");
18463
+ }
18464
+ var POSIX_TOKEN = "'((?:[^'\\r\\n]|'\\\\'')*)'";
18465
+ function parseHeadersHelper(command) {
18466
+ if (typeof command !== "string") return null;
18467
+ const posix3 = new RegExp(`^${POSIX_TOKEN} ${POSIX_TOKEN}$`).exec(command);
18468
+ if (posix3 !== null) return { node: posix3[1].replace(/'\\''/g, "'"), script: posix3[2].replace(/'\\''/g, "'") };
18469
+ const win = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
18470
+ return win === null ? null : { node: win[1], script: win[2] };
18471
+ }
18472
+ function helperSourceCurrent() {
18473
+ try {
18474
+ return fs8.readFileSync(headersHelperPath(), "utf-8") === HEADERS_HELPER_SOURCE;
18475
+ } catch {
18476
+ return false;
18477
+ }
18478
+ }
18479
+ function isExecutable(file) {
18480
+ try {
18481
+ fs8.accessSync(file, fs8.constants.X_OK);
18482
+ return fs8.statSync(file).isFile();
18483
+ } catch {
18484
+ return false;
18485
+ }
18486
+ }
18487
+ function writeHeadersHelper() {
18488
+ if (helperSourceCurrent()) return;
18489
+ atomicWriteFile(headersHelperPath(), HEADERS_HELPER_SOURCE, 384);
18490
+ }
18491
+ function headersHelperStateOf(command) {
18492
+ const parsed = parseHeadersHelper(command);
18493
+ if (parsed === null || path10.resolve(parsed.script) !== path10.resolve(headersHelperPath())) return "missing";
18494
+ return helperSourceCurrent() && isExecutable(parsed.node) ? "current" : "stale";
18495
+ }
18496
+ function headersHelperProblem(command, apiKey) {
18497
+ const parsed = parseHeadersHelper(command);
18498
+ if (parsed === null) return "the entry has no headers helper of this integration";
18499
+ const result = spawnCommandSync(parsed.node, [parsed.script], { encoding: "utf-8", timeout: 1e4, windowsHide: true, cwd: claudeHome() });
18500
+ if (result.error) return `its helper could not run (${result.error.message})`;
18501
+ if (result.status !== 0) return `its helper exited ${result.status}`;
18502
+ let headers;
18503
+ try {
18504
+ headers = JSON.parse(String(result.stdout ?? ""));
18505
+ } catch {
18506
+ return "its helper printed something other than a JSON object";
18507
+ }
18508
+ const auth = headers !== null && typeof headers === "object" ? headers["Authorization"] : void 0;
18509
+ if (auth === void 0) return `its helper finds no key in ${path10.join(identityHome(), "credentials")}`;
18510
+ return auth === `Bearer ${apiKey}` ? null : "its helper yields a key other than this agent's credentials";
18511
+ }
18407
18512
  function clientHeaders() {
18408
18513
  return clientHeadersOf(CLIENT);
18409
18514
  }
@@ -18421,6 +18526,15 @@ function readUserState() {
18421
18526
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not a JSON object");
18422
18527
  return parsed;
18423
18528
  }
18529
+ function readEntryField(field) {
18530
+ try {
18531
+ const servers = readUserState()?.["mcpServers"];
18532
+ const entry = servers !== null && typeof servers === "object" ? servers[MCP_SERVER_NAME] : void 0;
18533
+ return entry !== null && typeof entry === "object" ? entry[field] : void 0;
18534
+ } catch {
18535
+ return void 0;
18536
+ }
18537
+ }
18424
18538
  function isLegacyStdioEntry(entry) {
18425
18539
  const args = Array.isArray(entry["args"]) ? entry["args"] : [];
18426
18540
  return (entry["type"] === void 0 || entry["type"] === "stdio") && entry["command"] === "node" && args.length === 2 && typeof args[0] === "string" && args[0].replace(/\\/g, "/").endsWith("/agentchat/bin/agentchat.mjs") && args[1] === "mcp-proxy";
@@ -18444,12 +18558,13 @@ function inspectHostedMcp(apiKey, apiBase) {
18444
18558
  const type = record["type"];
18445
18559
  const url = record["url"];
18446
18560
  const headers = record["headers"];
18447
- const auth = headers && typeof headers === "object" && !Array.isArray(headers) ? headers["Authorization"] ?? headers["authorization"] : void 0;
18561
+ const auth = headers && typeof headers === "object" && !Array.isArray(headers) ? Object.entries(headers).find(([name]) => name.toLowerCase() === "authorization")?.[1] : void 0;
18448
18562
  const currentKey = apiKey !== null && typeof auth === "string" && auth === `Bearer ${apiKey}`;
18449
18563
  const isHttp = type === "http" || type === "streamable-http";
18450
18564
  const named = clientHeadersStateOf(headers);
18451
- if (isHttp && typeof url === "string" && (url === hostedMcpUrl2(apiBase) || currentKey)) {
18452
- return { state: "ours", url, currentKey, clientHeaders: named };
18565
+ const helper = headersHelperStateOf(record["headersHelper"]);
18566
+ if (isHttp && typeof url === "string" && (url === hostedMcpUrl2(apiBase) || currentKey || helper !== "missing")) {
18567
+ return { state: "ours", url, currentKey, staticKey: auth !== void 0, helper, clientHeaders: named };
18453
18568
  }
18454
18569
  return { state: "foreign", detail: `the user-scope server named "agentchat" points at ${typeof url === "string" ? url : "a different command"} and is not this integration's`, clientHeaders: named };
18455
18570
  }
@@ -18465,27 +18580,40 @@ function placeHostedMcp(identity) {
18465
18580
  if (current.state === "foreign") {
18466
18581
  return { name: "mcp", status: "skipped", detail: `${current.detail} \u2014 left untouched; rename or remove it, then re-run` };
18467
18582
  }
18468
- if (current.state === "ours" && current.currentKey && current.clientHeaders === "current") {
18583
+ try {
18584
+ writeHeadersHelper();
18585
+ } catch (err) {
18586
+ return { name: "mcp", status: "failed", detail: `could not write the headers helper ${headersHelperPath()}: ${String(err)}` };
18587
+ }
18588
+ const keyNote = `the key stays in ${path10.join(identityHome(), "credentials")}; Claude Code asks ${headersHelperPath()} for it on each connection`;
18589
+ if (current.state === "ours" && !current.staticKey && current.helper === "current" && current.clientHeaders === "current") {
18469
18590
  tightenUserStateMode();
18470
- return { name: "mcp", status: "ok", detail: `hosted tools registered as user MCP "${MCP_SERVER_NAME}" \u2192 ${current.url}` };
18591
+ return { name: "mcp", status: "ok", detail: `hosted tools registered as user MCP "${MCP_SERVER_NAME}" \u2192 ${current.url} (${keyNote})` };
18471
18592
  }
18593
+ const command = headersHelperCommand();
18594
+ if (command === null) {
18595
+ return { name: "mcp", status: "failed", detail: `the path of Node (${process.execPath}) or of ${headersHelperPath()} holds a character a shell command cannot carry quoted; move it, then re-run` };
18596
+ }
18597
+ const problem = headersHelperProblem(command, identity.apiKey);
18598
+ if (problem !== null) return { name: "mcp", status: "failed", detail: `the user MCP "${MCP_SERVER_NAME}" was left as it was: ${problem}` };
18472
18599
  if (current.state === "ours" || current.state === "legacy") {
18473
18600
  const removed = runClaude(["mcp", "remove", "--scope", "user", MCP_SERVER_NAME]);
18474
18601
  if (!removed.ok) return { name: "mcp", status: "failed", detail: `could not replace the existing "${MCP_SERVER_NAME}" MCP entry: ${removed.detail}` };
18475
18602
  }
18476
18603
  const url = hostedMcpUrl2(identity.apiBase);
18477
- const headerArgs = Object.entries(clientHeaders()).flatMap(([name, value]) => ["--header", `${name}: ${value}`]);
18478
- const added = runClaude(["mcp", "add", "--transport", "http", "--scope", "user", MCP_SERVER_NAME, url, "--header", `Authorization: Bearer ${identity.apiKey}`, ...headerArgs]);
18479
- if (!added.ok) return { name: "mcp", status: "failed", detail: `claude mcp add failed: ${added.detail}` };
18604
+ const entry = { type: "http", url, headers: clientHeaders(), headersHelper: command };
18605
+ const added = runClaude(["mcp", "add-json", "--scope", "user", MCP_SERVER_NAME, JSON.stringify(entry)]);
18606
+ if (!added.ok) return { name: "mcp", status: "failed", detail: `claude mcp add-json failed: ${added.detail}` };
18480
18607
  const after = inspectHostedMcp(identity.apiKey, identity.apiBase);
18481
- if (after.state !== "ours" || !after.currentKey || after.clientHeaders !== "current") {
18482
- return { name: "mcp", status: "failed", detail: `claude mcp add reported success but ${claudeUserStatePath()} does not carry the entry with this key and the client headers` };
18608
+ if (after.state !== "ours" || after.staticKey || after.helper !== "current" || after.clientHeaders !== "current") {
18609
+ return { name: "mcp", status: "failed", detail: `claude mcp add-json reported success but ${claudeUserStatePath()} does not carry the entry with the headers helper and the client headers` };
18483
18610
  }
18484
18611
  tightenUserStateMode();
18612
+ const replaced = current.state === "legacy" ? "; the local stdio server was replaced" : current.state === "ours" && current.staticKey ? current.currentKey ? `; the key an earlier release wrote into ${claudeUserStatePath()} is taken out of it (copies Claude Code made of that file under ${path10.join(claudeHome(), "backups")} may still hold it)` : `; the entry held a key other than this agent's in ${claudeUserStatePath()} (an old one, or another agent's) and was replaced \u2014 if it was another agent's, that agent's own credentials still hold it` : current.state === "ours" && current.clientHeaders !== "current" ? "; re-registered with the client headers" : "";
18485
18613
  return {
18486
18614
  name: "mcp",
18487
18615
  status: "changed",
18488
- detail: `hosted tools registered as user MCP "${MCP_SERVER_NAME}" \u2192 ${url} (Authorization header with this agent's key, named as Claude Code ${CLIENT.version}${current.state === "legacy" ? "; the local stdio server was replaced" : current.state === "ours" && current.clientHeaders !== "current" ? "; re-registered with the client headers" : ""})`
18616
+ detail: `hosted tools registered as user MCP "${MCP_SERVER_NAME}" \u2192 ${url} (${keyNote}; named as Claude Code ${CLIENT.version}${replaced})`
18489
18617
  };
18490
18618
  }
18491
18619
  function removeHostedMcp(identity) {
@@ -18675,6 +18803,10 @@ function removePlacement(identity) {
18675
18803
  const leftovers = removeAnswerRunLeftovers();
18676
18804
  if (leftovers) steps.push(leftovers);
18677
18805
  steps.push(removeSkill());
18806
+ try {
18807
+ fs8.rmSync(headersHelperPath(), { force: true });
18808
+ } catch {
18809
+ }
18678
18810
  try {
18679
18811
  steps.push({
18680
18812
  name: "identity",
@@ -18712,13 +18844,14 @@ function checkPlacement(identity, manual) {
18712
18844
  checks.push({ name: "manual", ok: skill.state === "current" || skill.state === "unchecked", verdict: skill.verdict, detail: skill.detail });
18713
18845
  const mcp = inspectHostedMcp(identity?.apiKey ?? null, identity?.apiBase ?? "https://api.agentchat.me");
18714
18846
  const headerHint = Object.entries(clientHeaders()).map(([name, value]) => `--header "${name}: ${value}"`).join(" ");
18847
+ const helperProblem = mcp.state === "ours" && identity !== null && !mcp.staticKey && mcp.helper === "current" ? headersHelperProblem(readEntryField("headersHelper"), identity.apiKey) : null;
18715
18848
  checks.push({
18716
18849
  name: "mcp",
18717
- ok: mcp.state === "ours" ? (identity === null || mcp.currentKey) && mcp.clientHeaders !== "missing" : false,
18850
+ ok: mcp.state === "ours" ? (identity === null || !mcp.staticKey && mcp.helper === "current" && helperProblem === null) && mcp.clientHeaders !== "missing" : false,
18718
18851
  // A user-scope "agentchat" that is not this integration's (another URL,
18719
- // another key) is never touched; the check says, too, when it does not
18852
+ // another helper) is never touched; the check says, too, when it does not
18720
18853
  // name this runtime to the hosted tools.
18721
- detail: mcp.state === "ours" ? identity !== null && !mcp.currentKey ? `user MCP "${MCP_SERVER_NAME}" carries a different key than this agent's credentials` : mcp.clientHeaders === "missing" ? `user MCP "${MCP_SERVER_NAME}" \u2192 ${mcp.url} does not send ${Object.keys(clientHeaders())[0]}, so the hosted tools take this agent for an unknown client and show it the wake-webhook tools` : `hosted tools registered as user MCP "${MCP_SERVER_NAME}" \u2192 ${mcp.url}${mcp.clientHeaders === "stale" ? ` (named by an earlier release; install or \`doctor --fix\` names it as Claude Code ${CLIENT.version})` : ""}` : mcp.state === "legacy" ? `user MCP "${MCP_SERVER_NAME}" is the old local stdio server` : mcp.state === "missing" ? `no user MCP "${MCP_SERVER_NAME}" \u2014 the agent has no AgentChat tools` : mcp.state === "foreign" && mcp.clientHeaders === "missing" ? `${mcp.detail}; it does not send ${Object.keys(clientHeaders())[0]}, so the hosted tools show this agent the wake-webhook tools \u2014 add ${headerHint} to it` : mcp.detail
18854
+ detail: mcp.state === "ours" ? identity !== null && mcp.staticKey ? mcp.currentKey ? `user MCP "${MCP_SERVER_NAME}" holds this agent's key in ${claudeUserStatePath()} (an earlier release's registration) \u2014 install or \`doctor --fix\` takes it out and has Claude Code read it from ${path10.join(identityHome(), "credentials")}` : `user MCP "${MCP_SERVER_NAME}" carries a different key than this agent's credentials, in ${claudeUserStatePath()}` : identity !== null && mcp.helper !== "current" ? `user MCP "${MCP_SERVER_NAME}" ${mcp.helper === "stale" ? `asks a headers helper that is out of date or whose Node is gone (${headersHelperPath()})` : "has no headers helper of this integration"}, so no key reaches the hosted tools` : helperProblem !== null ? `user MCP "${MCP_SERVER_NAME}" \u2192 ${mcp.url}: ${helperProblem}` : mcp.clientHeaders === "missing" ? `user MCP "${MCP_SERVER_NAME}" \u2192 ${mcp.url} does not send ${Object.keys(clientHeaders())[0]}, so the hosted tools take this agent for an unknown client and show it the wake-webhook tools` : `hosted tools registered as user MCP "${MCP_SERVER_NAME}" \u2192 ${mcp.url}${identity !== null ? ` (the key stays in ${path10.join(identityHome(), "credentials")}; Claude Code asks ${headersHelperPath()} for it)` : ""}${mcp.clientHeaders === "stale" ? ` (named by an earlier release; install or \`doctor --fix\` names it as Claude Code ${CLIENT.version})` : ""}` : mcp.state === "legacy" ? `user MCP "${MCP_SERVER_NAME}" is the old local stdio server` : mcp.state === "missing" ? `no user MCP "${MCP_SERVER_NAME}" \u2014 the agent has no AgentChat tools` : mcp.state === "foreign" && mcp.clientHeaders === "missing" ? `${mcp.detail}; it does not send ${Object.keys(clientHeaders())[0]}, so the hosted tools show this agent the wake-webhook tools \u2014 add ${headerHint} to it` : mcp.detail
18722
18855
  });
18723
18856
  const leftovers = [legacyHooksPresent() ? "hooks in settings.json" : null, legacyBundlePresent() ? "stable CLI bundle" : null].filter(
18724
18857
  (v) => v !== null
@@ -18797,7 +18930,7 @@ function removeListenerService() {
18797
18930
  // src/identity.ts
18798
18931
  var NO_IDENTITY_TEXTS = { identityLine: null, identityLineTemplate: null };
18799
18932
  function currentPlacementIdentity(texts = NO_IDENTITY_TEXTS) {
18800
- const identity = resolveIdentity(identityHome());
18933
+ const identity = homeIdentity(identityHome());
18801
18934
  if (identity === null || identity.handle === null) return null;
18802
18935
  return {
18803
18936
  handle: identity.handle,
@@ -18829,7 +18962,7 @@ var profile = {
18829
18962
  // the identity line and the manual they announce. Writing the block needs no
18830
18963
  // template (it is found by its fences), so none is passed here.
18831
18964
  place: async (handle, apiKey, identityLine, manual) => {
18832
- const identity = resolveIdentity(identityHome());
18965
+ const identity = homeIdentity(identityHome());
18833
18966
  const steps = await placeAll({ handle, apiKey, apiBase: identity?.apiBase ?? "https://api.agentchat.me", identityLine, identityLineTemplate: null }, manual);
18834
18967
  return steps.map((s) => ` ${s.status === "failed" ? "FAILED" : s.name}: ${s.detail}`);
18835
18968
  },
@@ -18939,7 +19072,7 @@ function daemonRunner(settings = runSettings()) {
18939
19072
  configDir: claudeConfigOverride(),
18940
19073
  workdir: settings.workdir,
18941
19074
  profile: settings.profile,
18942
- apiBase: resolveIdentity(identityHome())?.apiBase ?? DEFAULT_API_BASE2
19075
+ apiBase: homeIdentity(identityHome())?.apiBase ?? DEFAULT_API_BASE2
18943
19076
  });
18944
19077
  }
18945
19078
  function profileCheck() {
@@ -19077,7 +19210,7 @@ Usage:
19077
19210
  ${invocation()} register --email <e> --handle <h>
19078
19211
  ${invocation()} register --code <6-digit-code>
19079
19212
  ${invocation()} register --not-now stop offering to set this up
19080
- ${invocation()} login --api-key - already have an account: key on stdin (or AGENTCHAT_API_KEY=\u2026, or --api-key <ac_\u2026>)
19213
+ ${invocation()} login already have an account: paste the key when asked (or pipe it: login --api-key - < key.txt)
19081
19214
  ${invocation()} recover --handle <h> --email <e> lost your key (rotates it; --handle defaults to yours)
19082
19215
  ${invocation()} recover --code <6-digit-code>
19083
19216
  ${invocation()} status [--json]
@@ -19103,7 +19236,10 @@ Switches (captured into the service from the shell that runs install, \`daemon i
19103
19236
  AGENTCHAT_RUN_BUDGET_MS kill a run past this (default 600000)
19104
19237
  AGENTCHAT_RUN_CWD the run's work folder (default ~/.claude/agentchat-workdir); one that is your
19105
19238
  home folder or contains it gives answer runs ~/.claude/agentchat-answer-workdir
19106
- AGENTCHAT_API_KEY / AGENTCHAT_API_BASE override the stored identity
19239
+ AGENTCHAT_API_BASE the API base (default: the one stored with the identity, else https://api.agentchat.me)
19240
+
19241
+ The key is in ${identityHome()}/credentials only. An exported AGENTCHAT_API_KEY never
19242
+ replaces it: commands and placements act as the agent that file names.
19107
19243
  `;
19108
19244
  async function main(argv = process.argv.slice(2)) {
19109
19245
  let parsed;
@@ -19228,7 +19364,7 @@ function runUninstall() {
19228
19364
  warnings.push(`could not fully remove the integration service: ${String(err)}`);
19229
19365
  }
19230
19366
  markAlwaysOnOptOut(home);
19231
- const identity = resolveIdentity(identityHome());
19367
+ const identity = homeIdentity(identityHome());
19232
19368
  const steps = removePlacement({
19233
19369
  apiKey: identity?.apiKey ?? null,
19234
19370
  apiBase: identity?.apiBase ?? process.env["AGENTCHAT_API_BASE"]?.trim() ?? "https://api.agentchat.me"