@agentchatme/openclaw 0.10.0 → 0.10.2

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.cjs CHANGED
@@ -148,7 +148,7 @@ var AgentChatChannelError = class extends Error {
148
148
  };
149
149
 
150
150
  // src/version.ts
151
- var PACKAGE_VERSION = "0.10.0";
151
+ var PACKAGE_VERSION = "0.10.2";
152
152
 
153
153
  // src/client-identity.ts
154
154
  var AGENTCHAT_CLIENT_NAME = "openclaw";
@@ -418,14 +418,22 @@ var DEFAULT_API_BASE2 = "https://api.agentchat.me";
418
418
  function hostedMcpUrl(apiBase = DEFAULT_API_BASE2) {
419
419
  return `${apiBase.replace(/\/+$/, "")}${MCP_PATH}`;
420
420
  }
421
+ var CLIENT_HEADER = "X-AgentChat-Client";
422
+ function clientIdentityHeaders() {
423
+ return { [CLIENT_HEADER]: AGENTCHAT_CLIENT_NAME };
424
+ }
425
+ function clientIdentityText() {
426
+ return `${CLIENT_HEADER}: ${AGENTCHAT_CLIENT_NAME}`;
427
+ }
421
428
  function hostedMcpServerEntry(apiBase = DEFAULT_API_BASE2) {
422
429
  return {
423
430
  url: hostedMcpUrl(apiBase),
424
431
  transport: "streamable-http",
425
- headers: { Authorization: AUTH_HEADER_TEMPLATE }
432
+ headers: { Authorization: AUTH_HEADER_TEMPLATE, ...clientIdentityHeaders() }
426
433
  };
427
434
  }
428
435
  function hostedMcpSnippet(apiBase = DEFAULT_API_BASE2) {
436
+ const identity = clientIdentityHeaders();
429
437
  return [
430
438
  "{",
431
439
  " mcp: {",
@@ -433,7 +441,10 @@ function hostedMcpSnippet(apiBase = DEFAULT_API_BASE2) {
433
441
  ` ${MCP_SERVER_NAME}: {`,
434
442
  ` url: "${hostedMcpUrl(apiBase)}",`,
435
443
  ' transport: "streamable-http",',
436
- ` headers: { Authorization: "${AUTH_HEADER_TEMPLATE}" },`,
444
+ " headers: {",
445
+ ` Authorization: "${AUTH_HEADER_TEMPLATE}",`,
446
+ ` "${CLIENT_HEADER}": "${identity[CLIENT_HEADER]}",`,
447
+ " },",
437
448
  " },",
438
449
  " },",
439
450
  " },",
@@ -456,23 +467,99 @@ function pointsAtUs(entry, apiBase, apiKey) {
456
467
  const headers = entry.headers;
457
468
  if (headers === void 0) return true;
458
469
  if (!headers || typeof headers !== "object" || Array.isArray(headers)) return false;
459
- const auth = headers.Authorization ?? headers.authorization;
470
+ const auths = headerValues(headers, "Authorization");
471
+ if (auths.length > 1) return false;
472
+ const auth = auths[0];
460
473
  if (auth === void 0) return true;
461
474
  if (typeof auth !== "string") return false;
462
475
  if (auth === AUTH_HEADER_TEMPLATE || auth.includes(`\${${readEnv_js.API_KEY_ENV}}`)) return true;
463
476
  return apiKey !== void 0 && apiKey.length > 0 && auth.trim() === `Bearer ${apiKey}`;
464
477
  }
478
+ function describeMcpIdentity(cfg) {
479
+ const entry = agentchatEntry(cfg);
480
+ const headers = entry && isRecord(entry.headers) ? entry.headers : void 0;
481
+ if (!headers) return "missing";
482
+ const want = clientIdentityHeaders();
483
+ const clients = headerValues(headers, CLIENT_HEADER);
484
+ const client = clients[0];
485
+ return clients.length === 1 && typeof client === "string" && client.trim().toLowerCase() === want[CLIENT_HEADER] ? "current" : "missing";
486
+ }
465
487
  function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
466
488
  const state = describeMcpEntry(cfg, apiBase, apiKey);
467
489
  const base = cfg ?? {};
468
- if (state === "ours") return { cfg: base, outcome: "present" };
469
490
  if (state === "user_managed") return { cfg: base, outcome: "user_managed" };
470
491
  if (state === "disabled") return { cfg: base, outcome: "disabled" };
492
+ if (state === "ours" && describeMcpIdentity(base) === "current") return { cfg: base, outcome: "present" };
471
493
  const mcp = { ...base.mcp ?? {} };
472
494
  const servers = { ...mcp.servers ?? {} };
473
- servers[MCP_SERVER_NAME] = hostedMcpServerEntry(apiBase);
495
+ const existing = servers[MCP_SERVER_NAME];
496
+ servers[MCP_SERVER_NAME] = state === "ours" && isRecord(existing) ? upgradedHostedMcpEntry(existing, apiBase) : hostedMcpServerEntry(apiBase);
474
497
  mcp.servers = servers;
475
- return { cfg: { ...base, mcp }, outcome: "added" };
498
+ return { cfg: { ...base, mcp }, outcome: state === "ours" ? "updated" : "added" };
499
+ }
500
+ function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE2) {
501
+ const headers = isRecord(entry.headers) ? entry.headers : {};
502
+ const kept = Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== CLIENT_HEADER.toLowerCase()));
503
+ return {
504
+ ...entry,
505
+ url: hostedMcpUrl(apiBase),
506
+ transport: "streamable-http",
507
+ headers: { ...kept, ...clientIdentityHeaders() }
508
+ };
509
+ }
510
+ function upgradeHostedMcpEntryInPlace(draft, apiBase = DEFAULT_API_BASE2, apiKey) {
511
+ if (describeMcpEntry(draft, apiBase, apiKey) !== "ours" || describeMcpIdentity(draft) === "current") return false;
512
+ const servers = draft.mcp.servers;
513
+ const existing = servers[MCP_SERVER_NAME];
514
+ if (!isRecord(existing)) return false;
515
+ servers[MCP_SERVER_NAME] = upgradedHostedMcpEntry(existing, apiBase);
516
+ return true;
517
+ }
518
+ var NoChange = class extends Error {
519
+ constructor(outcome) {
520
+ super(`no change (${outcome})`);
521
+ this.outcome = outcome;
522
+ }
523
+ outcome;
524
+ };
525
+ var NIX_MODE_ERROR_CODE = "OPENCLAW_NIX_MODE_CONFIG_IMMUTABLE";
526
+ async function refreshHostedMcpEntry(params) {
527
+ const apiBase = params.apiBase ?? DEFAULT_API_BASE2;
528
+ if (describeMcpEntry(params.liveCfg, apiBase, params.apiKey) !== "ours") return { outcome: "not_ours" };
529
+ if (describeMcpIdentity(params.liveCfg) === "current") return { outcome: "current" };
530
+ const mutate = params.config?.mutateConfigFile;
531
+ if (typeof mutate !== "function") return { outcome: "unsupported" };
532
+ try {
533
+ await mutate.call(params.config, {
534
+ afterWrite: { mode: "auto" },
535
+ mutate: ((draft) => {
536
+ if (describeMcpEntry(draft, apiBase, params.apiKey) !== "ours") throw new NoChange("not_ours");
537
+ if (!upgradeHostedMcpEntryInPlace(draft, apiBase, params.apiKey)) throw new NoChange("current");
538
+ })
539
+ });
540
+ return { outcome: "updated" };
541
+ } catch (err) {
542
+ if (err instanceof NoChange) return { outcome: err.outcome };
543
+ const code = err?.code;
544
+ return {
545
+ outcome: "failed",
546
+ error: err instanceof Error ? err.message : String(err),
547
+ ...typeof code === "string" ? { code } : {}
548
+ };
549
+ }
550
+ }
551
+ function isRecord(value) {
552
+ return value !== null && typeof value === "object" && !Array.isArray(value);
553
+ }
554
+ function agentchatEntry(cfg) {
555
+ const servers = cfg?.mcp?.servers;
556
+ if (!isRecord(servers)) return void 0;
557
+ const entry = servers[MCP_SERVER_NAME];
558
+ return isRecord(entry) ? entry : void 0;
559
+ }
560
+ function headerValues(headers, name) {
561
+ const wanted = name.toLowerCase();
562
+ return Object.entries(headers).filter(([key]) => key.toLowerCase() === wanted).map(([, value]) => value);
476
563
  }
477
564
  function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
478
565
  if (describeMcpEntry(cfg, apiBase, apiKey) !== "ours") return { cfg, removed: false };
@@ -584,47 +671,258 @@ async function watchRunUntilEnded(options) {
584
671
  if (elapsedMs < MIN_WAIT_SPACING_MS) await sleep(MIN_WAIT_SPACING_MS - elapsedMs);
585
672
  }
586
673
  }
587
- function countAgentChatCalls(messages, runId) {
674
+ function countAgentChatCalls(messages, runId, host = {}) {
588
675
  if (messages.length === 0) return null;
589
- let recognised = false;
590
- let made = 0;
591
- let failed = 0;
676
+ const rows = [];
592
677
  for (const row of messages) {
593
678
  const message = unwrapMessage(row);
594
- if (!message) continue;
595
- const role = message.role;
596
- if (role === "assistant" || role === "user") recognised = true;
597
- if (role !== "toolResult" && role !== "tool") continue;
598
- recognised = true;
599
- const meta = asRecord2(message.__openclaw);
600
- if (runId && typeof meta?.runId === "string" && meta.runId !== runId) continue;
601
- if (!isAgentChatToolResult(message)) continue;
679
+ if (!message) return null;
680
+ rows.push(message);
681
+ }
682
+ if (!coversWholeSession(rows)) return null;
683
+ if (runId && rows.some((row) => isOtherRun(row, runId))) return null;
684
+ const calls = assistantToolCalls(rows);
685
+ const nested = rows.flatMap((row) => {
686
+ const call = nestedCallOf(row);
687
+ return call ? [call] : [];
688
+ });
689
+ const release = releaseOf(rows, calls, nested, host.openclawVersion);
690
+ if (delegatedToChild(rows, calls, nested)) return null;
691
+ if (usedCodeMode(rows, calls)) {
692
+ if (!release.recordsNestedCalls) return null;
693
+ if (!codeModeScriptsCompleted(rows, calls)) return null;
694
+ }
695
+ const parents = new Set(nested.flatMap((call) => typeof call.parentToolCallId === "string" ? [call.parentToolCallId] : []));
696
+ let made = 0;
697
+ let failed = 0;
698
+ for (const message of rows) {
699
+ let verdict;
700
+ const call = nestedCallOf(message);
701
+ if (call) verdict = nestedVerdict(call);
702
+ else if (message.role !== "toolResult" && message.role !== "tool") continue;
703
+ else if (typeof message.toolCallId === "string" && parents.has(message.toolCallId)) continue;
704
+ else verdict = callVerdict(message, calls, release);
705
+ if (verdict === "not_agentchat") continue;
706
+ if (verdict === "unknown") return null;
602
707
  made += 1;
603
- if (message.isError === true) failed += 1;
708
+ if (verdict === "failed") failed += 1;
604
709
  }
605
- return recognised ? { made, failed } : null;
710
+ return { made, failed };
606
711
  }
607
712
  async function readAgentChatCalls(runtime, sessionKey, runId) {
608
713
  if (!runtime || typeof runtime.subagent?.getSessionMessages !== "function") return null;
609
714
  try {
610
715
  const result = await runtime.subagent.getSessionMessages({ sessionKey, limit: TRANSCRIPT_READ_LIMIT });
611
716
  const messages = result?.messages;
612
- return Array.isArray(messages) ? countAgentChatCalls(messages, runId) : null;
717
+ const openclawVersion = typeof runtime.version === "string" ? runtime.version : void 0;
718
+ return Array.isArray(messages) ? countAgentChatCalls(messages, runId, openclawVersion ? { openclawVersion } : {}) : null;
613
719
  } catch {
614
720
  return null;
615
721
  }
616
722
  }
617
723
  var TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
618
- function isAgentChatToolResult(message) {
619
- const toolName = typeof message.toolName === "string" ? message.toolName : typeof message.name === "string" ? message.name : "";
620
- if (toolName.startsWith(TOOL_PREFIX)) return true;
621
- const tool = asRecord2(asRecord2(message.details)?.tool);
622
- if (!tool) return false;
724
+ var DISPATCHER_TOOL_NAMES = /* @__PURE__ */ new Set(["tool_call", "dispatch_action"]);
725
+ var FAILURE_STATUSES = /* @__PURE__ */ new Set([
726
+ "error",
727
+ "failed",
728
+ "failure",
729
+ "timeout",
730
+ "timed_out",
731
+ "blocked",
732
+ "denied",
733
+ "forbidden",
734
+ "unavailable",
735
+ "approval-unavailable",
736
+ "disabled",
737
+ "aborted",
738
+ "cancelled",
739
+ "canceled",
740
+ "killed",
741
+ "invalid"
742
+ ]);
743
+ function coversWholeSession(rows) {
744
+ if (asRecord2(rows[0]?.__openclaw)?.seq !== 1) return false;
745
+ return rows.every((row) => {
746
+ const meta = asRecord2(row.__openclaw);
747
+ return meta?.kind !== "compaction" && meta?.kind !== "reset" && meta?.truncated !== true;
748
+ });
749
+ }
750
+ function isOtherRun(row, runId) {
751
+ const tagged = asRecord2(row.__openclaw)?.runId ?? nestedCallOf(row)?.runId;
752
+ return typeof tagged === "string" && tagged.trim().length > 0 && tagged.trim() !== runId;
753
+ }
754
+ var CODE_MODE_ONLY_TOOL_NAMES = /* @__PURE__ */ new Set(["tool_search_code", "wait"]);
755
+ function usedCodeMode(rows, calls) {
756
+ return [...calls.values()].some(isCodeModeCall) || rows.some((row) => isCodeModeResult(row, calls));
757
+ }
758
+ function codeModeScriptsCompleted(rows, calls) {
759
+ const results = /* @__PURE__ */ new Map();
760
+ for (const row of rows) {
761
+ if ((row.role === "toolResult" || row.role === "tool") && typeof row.toolCallId === "string") results.set(row.toolCallId, row);
762
+ }
763
+ const completed = (row) => row !== void 0 && row.isError !== true && asRecord2(row.details)?.status === "completed";
764
+ for (const [id, call] of calls) {
765
+ if (isCodeModeCall(call) && !completed(results.get(id))) return false;
766
+ }
767
+ return rows.every((row) => !isCodeModeResult(row, calls) || completed(row));
768
+ }
769
+ function isCodeModeCall(call) {
770
+ const name = typeof call.name === "string" ? call.name : "";
771
+ return CODE_MODE_ONLY_TOOL_NAMES.has(name) || name === "exec" && typeof callArguments(call)?.code === "string";
772
+ }
773
+ function isCodeModeResult(row, calls) {
774
+ if (row.role !== "toolResult" && row.role !== "tool") return false;
775
+ const name = toolNameOf(row);
776
+ return CODE_MODE_ONLY_TOOL_NAMES.has(name) || name === "exec" && !isShellExecResult(row, calls);
777
+ }
778
+ function isShellExecResult(row, calls) {
779
+ const call = typeof row.toolCallId === "string" ? calls.get(row.toolCallId) : void 0;
780
+ const args = callArguments(call);
781
+ if (!args || typeof args.command !== "string" || args.code !== void 0) return false;
782
+ const details = asRecord2(row.details);
783
+ if (!details || details.telemetry !== void 0) return false;
784
+ return details.exitCode !== void 0 || typeof details.durationMs === "number" || typeof details.aggregated === "string";
785
+ }
786
+ function assistantToolCalls(rows) {
787
+ const calls = /* @__PURE__ */ new Map();
788
+ for (const row of rows) {
789
+ if (row.role !== "assistant" || !Array.isArray(row.content)) continue;
790
+ for (const block of row.content) {
791
+ const call = asRecord2(block);
792
+ if (call?.type === "toolCall" && typeof call.id === "string") calls.set(call.id, call);
793
+ }
794
+ }
795
+ return calls;
796
+ }
797
+ var TRUSTED_RELEASE = "2026.9.3";
798
+ function releaseOf(rows, calls, nested, version) {
799
+ if (version !== void 0 && isOpenClawVersion(version)) {
800
+ const trusted = openclawVersionAtLeast(version, TRUSTED_RELEASE);
801
+ return { recordsNestedCalls: trusted, marksFailedRows: trusted };
802
+ }
803
+ const parents = new Set(nested.map((call) => call.parentToolCallId));
804
+ const dispatchAction = rows.some((row) => (row.role === "toolResult" || row.role === "tool") && toolNameOf(row) === "dispatch_action" && asRecord2(asRecord2(row.details)?.tool) !== null) || [...calls].some(([id, call]) => call.name === "dispatch_action" && parents.has(id));
805
+ return { recordsNestedCalls: nested.length > 0 || dispatchAction, marksFailedRows: dispatchAction };
806
+ }
807
+ var OPENCLAW_VERSION = /^(\d+)\.(\d+)\.(\d+)(-.+)?$/;
808
+ function isOpenClawVersion(value) {
809
+ return OPENCLAW_VERSION.test(value.trim());
810
+ }
811
+ function openclawVersionAtLeast(a, b) {
812
+ const parse = (v) => {
813
+ const match = OPENCLAW_VERSION.exec(v.trim());
814
+ return match ? { parts: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] !== void 0 } : null;
815
+ };
816
+ const [x, y] = [parse(a), parse(b)];
817
+ if (!x || !y) return false;
818
+ for (let i = 0; i < 3; i += 1) {
819
+ const d = (x.parts[i] ?? 0) - (y.parts[i] ?? 0);
820
+ if (d !== 0) return d > 0;
821
+ }
822
+ return !x.pre || y.pre;
823
+ }
824
+ function toolNameOf(row) {
825
+ return typeof row.toolName === "string" ? row.toolName : typeof row.name === "string" ? row.name : "";
826
+ }
827
+ var NESTED_TOOL_ACTIVITY = "openclaw.nested-tool.v1";
828
+ function nestedCallOf(row) {
829
+ if (row.role !== "custom" || row.customType !== NESTED_TOOL_ACTIVITY) return null;
830
+ return asRecord2(row.details);
831
+ }
832
+ function nestedVerdict(call) {
833
+ const toolName = typeof call.toolName === "string" ? call.toolName : "";
834
+ if (!toolName.startsWith(TOOL_PREFIX)) return "not_agentchat";
835
+ const result = asRecord2(call.result);
836
+ if (call.isError === true || result !== null && failedResult(result.isError, asRecord2(result.details))) return "failed";
837
+ return call.isError === false ? "ok" : "unknown";
838
+ }
839
+ var OTHER_SESSION_TOOLS = /* @__PURE__ */ new Set(["sessions_spawn", "sessions_send"]);
840
+ function delegatedToChild(rows, calls, nested) {
841
+ const names = (value) => typeof value === "string" && OTHER_SESSION_TOOLS.has(value);
842
+ for (const call of calls.values()) {
843
+ if (names(call.name)) return true;
844
+ if (typeof call.name === "string" && DISPATCHER_TOOL_NAMES.has(call.name) && names(dispatchTarget(call))) return true;
845
+ }
846
+ if (nested.some((call) => names(call.toolName))) return true;
847
+ return rows.some((row) => names(toolNameOf(row)) || names(asRecord2(asRecord2(row.details)?.tool)?.name));
848
+ }
849
+ function callVerdict(message, calls, release) {
850
+ const toolName = toolNameOf(message);
851
+ const details = asRecord2(message.details);
852
+ if (toolName.startsWith(TOOL_PREFIX)) return directVerdict(message.isError, details);
853
+ const entry = asRecord2(details?.tool);
854
+ if (entry && isAgentChatEntry(entry)) return dispatchedVerdict(message.isError, details);
855
+ if (!DISPATCHER_TOOL_NAMES.has(toolName) || entry) return "not_agentchat";
856
+ const target = dispatchTarget(typeof message.toolCallId === "string" ? calls.get(message.toolCallId) : void 0);
857
+ if (target === null) return "unknown";
858
+ if (!target.startsWith(TOOL_PREFIX)) return "not_agentchat";
859
+ if (failedResult(message.isError, details)) return "failed";
860
+ if (release.marksFailedRows && isTruncated(details) && message.isError === false && details?.status === void 0) return "ok";
861
+ return "unknown";
862
+ }
863
+ function isTruncated(details) {
864
+ return details?.persistedDetailsTruncated === true;
865
+ }
866
+ function directVerdict(isError, details) {
867
+ if (failedResult(isError, details)) return "failed";
868
+ if (isError !== false) return "unknown";
869
+ if (isTruncated(details)) return details?.status === void 0 && wasHostedResult(details) ? "ok" : "unknown";
870
+ return isHostedSuccessDetails(details) ? "ok" : "unknown";
871
+ }
872
+ function wasHostedResult(details) {
873
+ const keys = Array.isArray(details?.originalDetailKeys) ? details.originalDetailKeys : [];
874
+ return keys.includes("mcpServer") && (keys.includes("mcpTool") || keys.includes("mcpOperation"));
875
+ }
876
+ function dispatchedVerdict(isError, details) {
877
+ const result = asRecord2(details?.result);
878
+ if (failedResult(isError, details)) return "failed";
879
+ if (result && failedResult(result.isError, asRecord2(result.details))) return "failed";
880
+ const ok = isError === false && details?.status === void 0 && isHostedSuccessDetails(asRecord2(result?.details));
881
+ return ok ? "ok" : "unknown";
882
+ }
883
+ function failedResult(isError, details) {
884
+ return isError === true || detailsSayFailed(details);
885
+ }
886
+ function detailsSayFailed(details) {
887
+ if (!details) return false;
888
+ if (details.ok === false || details.success === false) return true;
889
+ const status = typeof details.status === "string" ? details.status.trim().toLowerCase() : "";
890
+ const explicitlyOk = details.ok === true || details.success === true;
891
+ if (FAILURE_STATUSES.has(status) && !explicitlyOk) return true;
892
+ if (details.timedOut === true || Boolean(details.error)) return true;
893
+ if (status === "completed") return false;
894
+ const exitCode = details.exitCode;
895
+ return typeof exitCode === "number" && Number.isFinite(exitCode) && exitCode !== 0;
896
+ }
897
+ function isHostedSuccessDetails(details) {
898
+ if (!details || details.mcpServer !== MCP_SERVER_NAME || details.status !== void 0) return false;
899
+ return nonEmpty(details.mcpTool) !== void 0 || nonEmpty(details.mcpOperation) !== void 0;
900
+ }
901
+ function isAgentChatEntry(tool) {
623
902
  if (typeof tool.name === "string" && tool.name.startsWith(TOOL_PREFIX)) return true;
624
903
  if (tool.sourceName === MCP_SERVER_NAME) return true;
625
904
  const mcp = asRecord2(tool.mcp);
626
905
  return mcp?.serverName === MCP_SERVER_NAME;
627
906
  }
907
+ function dispatchTarget(call) {
908
+ const record = callArguments(call);
909
+ const selector = nonEmpty(record?.id) ?? nonEmpty(record?.toolId) ?? nonEmpty(record?.name);
910
+ if (!selector) return null;
911
+ const trimmed = selector.trim();
912
+ return trimmed.slice(trimmed.lastIndexOf(":") + 1);
913
+ }
914
+ function callArguments(call) {
915
+ if (!call) return null;
916
+ let args = call.arguments;
917
+ if (typeof args === "string") {
918
+ try {
919
+ args = JSON.parse(args);
920
+ } catch {
921
+ return null;
922
+ }
923
+ }
924
+ return asRecord2(args);
925
+ }
628
926
  function unwrapMessage(row) {
629
927
  const record = asRecord2(row);
630
928
  if (!record) return null;
@@ -895,6 +1193,7 @@ function applyIntegrationConfig(cfg, params) {
895
1193
  const mcp = withHostedMcpEntry(next, params.apiBase, params.apiKey);
896
1194
  next = mcp.cfg;
897
1195
  if (mcp.outcome === "added") changes.push(`mcp.servers.agentchat \u2192 ${hostedMcpUrl(params.apiBase)} (bearer template on ${readEnv_js.API_KEY_ENV})`);
1196
+ if (mcp.outcome === "updated") changes.push(`mcp.servers.agentchat names this client (${clientIdentityText()})`);
898
1197
  const bound = openclawLayout_js.resolveBoundAgentId(next, AGENTCHAT_CHANNEL_ID, params.accountId);
899
1198
  const ambient = openclawLayout_js.resolveOpenClawDefaultAgentId(next);
900
1199
  if (bound && bound !== (ambient ?? bound)) {
@@ -999,6 +1298,8 @@ function describeMcpOutcome(outcome, apiBase) {
999
1298
  switch (outcome) {
1000
1299
  case "added":
1001
1300
  return { name: "mcp", status: "changed", detail: `hosted tools registered as mcp.servers.agentchat \u2192 ${hostedMcpUrl(apiBase)} (bearer template on ${readEnv_js.API_KEY_ENV})` };
1301
+ case "updated":
1302
+ return { name: "mcp", status: "changed", detail: `mcp.servers.agentchat now names this client to the hosted tools (${clientIdentityText()})` };
1002
1303
  case "present":
1003
1304
  return { name: "mcp", status: "ok", detail: "hosted tools already registered as mcp.servers.agentchat" };
1004
1305
  case "disabled":
@@ -1040,14 +1341,39 @@ function checkPlacement(params) {
1040
1341
  checks.push({ name: "anchor", ok: false, detail: `agentHandle not in config \u2014 the identity line cannot be checked; ${remedy("run openclaw doctor --fix (it learns the handle from the key)")}` });
1041
1342
  }
1042
1343
  checks.push({ name: "manual", ok: true, detail: "manual bundled as the agentchat skill" });
1043
- const mcpState = describeMcpEntry(params.cfg, params.apiBase, params.apiKey);
1044
- checks.push({
1045
- name: "mcp",
1046
- ok: mcpState === "ours" || mcpState === "user_managed",
1047
- detail: mcpState === "ours" ? "hosted tools registered as mcp.servers.agentchat" : mcpState === "user_managed" ? "mcp.servers.agentchat is managed by hand" : mcpState === "disabled" ? "mcp.servers.agentchat is disabled \u2014 the agent has no AgentChat tools" : `mcp.servers.agentchat missing \u2014 ${remedy("run openclaw doctor --fix (or openclaw channels add agentchat)")}`
1048
- });
1344
+ checks.push(checkMcpEntry(params.cfg, params.apiBase, params.apiKey, remedy));
1049
1345
  return checks;
1050
1346
  }
1347
+ function checkMcpEntry(cfg, apiBase, apiKey, remedy) {
1348
+ const unknownClient = "AgentChat treats the agent as an unknown client and lists the webhook-setup tools it does not need";
1349
+ switch (describeMcpEntry(cfg, apiBase, apiKey)) {
1350
+ case "ours": {
1351
+ const identity = describeMcpIdentity(cfg);
1352
+ if (identity === "current") return { name: "mcp", ok: true, detail: "hosted tools registered as mcp.servers.agentchat" };
1353
+ return {
1354
+ name: "mcp",
1355
+ ok: true,
1356
+ notice: true,
1357
+ repair: true,
1358
+ detail: `hosted tools registered as mcp.servers.agentchat, without ${CLIENT_HEADER} \u2014 ${unknownClient}; the gateway adds ${clientIdentityText()} to the entry when it starts (its log says if it could not), and openclaw doctor --fix does now`
1359
+ };
1360
+ }
1361
+ case "user_managed": {
1362
+ if (describeMcpIdentity(cfg) === "current") return { name: "mcp", ok: true, detail: "mcp.servers.agentchat is managed by hand" };
1363
+ const identity = clientIdentityHeaders();
1364
+ return {
1365
+ name: "mcp",
1366
+ ok: true,
1367
+ notice: true,
1368
+ detail: `mcp.servers.agentchat is managed by hand and does not name this client, so ${unknownClient} \u2014 add "${CLIENT_HEADER}": "${identity[CLIENT_HEADER]}" to its headers`
1369
+ };
1370
+ }
1371
+ case "disabled":
1372
+ return { name: "mcp", ok: false, detail: "mcp.servers.agentchat is disabled \u2014 the agent has no AgentChat tools" };
1373
+ case "missing":
1374
+ return { name: "mcp", ok: false, repair: true, detail: `mcp.servers.agentchat missing \u2014 ${remedy("run openclaw doctor --fix (or openclaw channels add agentchat)")}` };
1375
+ }
1376
+ }
1051
1377
  function describe2(err) {
1052
1378
  return err instanceof Error ? err.message : String(err);
1053
1379
  }
@@ -1092,8 +1418,10 @@ function textsCachePath(accountId, stateDir) {
1092
1418
  return path2__namespace.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE);
1093
1419
  }
1094
1420
  function spellTextsForOpenClaw(texts) {
1421
+ const newer = texts;
1095
1422
  return {
1096
1423
  ...texts,
1424
+ ...typeof newer.reply_turn_template === "string" ? { reply_turn_template: spellToolsForOpenClaw(newer.reply_turn_template) } : {},
1097
1425
  wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),
1098
1426
  invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),
1099
1427
  identity_line: spellToolsForOpenClaw(texts.identity_line),
@@ -1751,7 +2079,7 @@ var agentchatSetupWizard = {
1751
2079
  {
1752
2080
  value: "paste",
1753
2081
  label: "I already have an API key",
1754
- hint: "paste ac_live_\u2026 on the next prompt"
2082
+ hint: "paste ac_\u2026 on the next prompt"
1755
2083
  },
1756
2084
  {
1757
2085
  value: "recover",
@@ -1822,10 +2150,10 @@ var agentchatSetupWizard = {
1822
2150
  preferredEnvVar: "AGENTCHAT_API_KEY",
1823
2151
  envPrompt: "AGENTCHAT_API_KEY detected in env. Use it?",
1824
2152
  keepPrompt: "AgentChat API key already configured. Keep it?",
1825
- inputPrompt: "Paste your AgentChat API key (ac_live_\u2026)",
2153
+ inputPrompt: "Paste your AgentChat API key (ac_\u2026)",
1826
2154
  helpTitle: "AgentChat API key",
1827
2155
  helpLines: [
1828
- "Format: ac_live_<base64>, \u226520 chars. Validated against",
2156
+ "Format: ac_ followed by 43 base64url characters. Validated against",
1829
2157
  "GET /v1/agents/me during this wizard \u2014 bad keys fail fast instead",
1830
2158
  "of flapping reconnects at runtime."
1831
2159
  ],
@@ -3100,6 +3428,12 @@ function logEvent(event, logger, metrics) {
3100
3428
  case "echo":
3101
3429
  logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "own echo \u2014 not a wake");
3102
3430
  return;
3431
+ case "notice":
3432
+ logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "system notice \u2014 acked, not a wake");
3433
+ return;
3434
+ case "gate_chunk":
3435
+ logger.debug({ cycle: event.cycle, chunk: event.index, of: event.of, cards: event.cards, outcome: event.outcome, undecided: event.undecided, ...event.failure ? { failure: event.failure } : {} }, "gate chunk");
3436
+ return;
3103
3437
  case "cycle": {
3104
3438
  const s = event.summary;
3105
3439
  const fields = {
@@ -3222,6 +3556,32 @@ async function waitUntilAbort(signal, onAbort) {
3222
3556
  }
3223
3557
  await onAbort();
3224
3558
  }
3559
+ var mcpUpdateWarned = /* @__PURE__ */ new Set();
3560
+ async function updateHostedMcpEntry(ctx, apiBase, apiKey, runtime = getPluginRuntime) {
3561
+ const prefix = `[agentchat:${ctx.accountId}]`;
3562
+ const warnOnce = (line) => {
3563
+ if (mcpUpdateWarned.has(ctx.accountId)) return;
3564
+ mcpUpdateWarned.add(ctx.accountId);
3565
+ ctx.log?.warn?.(`${prefix} ${line}`);
3566
+ };
3567
+ try {
3568
+ const { cfg: liveCfg } = readLiveConfig(ctx.cfg, runtime);
3569
+ const config = runtime()?.config;
3570
+ const result = await refreshHostedMcpEntry({ liveCfg, config, apiBase, apiKey });
3571
+ if (result.outcome === "updated") {
3572
+ mcpUpdateWarned.delete(ctx.accountId);
3573
+ ctx.log?.info?.(`${prefix} mcp.servers.agentchat now names this client to the hosted tools (${clientIdentityText()}); under the default reload mode OpenClaw applies it without a restart`);
3574
+ } else if (result.outcome === "unsupported") {
3575
+ warnOnce(`mcp.servers.agentchat does not name this client (${clientIdentityText()}) and this OpenClaw cannot update its config from a plugin \u2014 run \`openclaw doctor --fix\``);
3576
+ } else if (result.outcome === "failed") {
3577
+ warnOnce(
3578
+ result.code === NIX_MODE_ERROR_CODE ? `mcp.servers.agentchat does not name this client and OpenClaw's config is read-only here (Nix mode) \u2014 add ${clientIdentityText()} to its headers in the Nix-managed config` : `mcp.servers.agentchat could not be updated to name this client (${result.error ?? "unknown error"}) \u2014 run \`openclaw doctor --fix\``
3579
+ );
3580
+ }
3581
+ } catch (err) {
3582
+ warnOnce(`mcp.servers.agentchat check failed: ${err instanceof Error ? err.message : String(err)}`);
3583
+ }
3584
+ }
3225
3585
  var agentchatGatewayAdapter = {
3226
3586
  async startAccount(ctx) {
3227
3587
  const account = ctx.account;
@@ -3236,6 +3596,7 @@ var agentchatGatewayAdapter = {
3236
3596
  const config = account.config;
3237
3597
  const logger = adaptLog(ctx.log) ?? createLogger({ level: config.observability.logLevel, redactKeys: config.observability.redactKeys });
3238
3598
  ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: false }, "starting"));
3599
+ void updateHostedMcpEntry(ctx, config.apiBase, config.apiKey);
3239
3600
  const wakeMode = readEnv_js.readWakeModeFromEnv();
3240
3601
  if (wakeMode.mode === "off") {
3241
3602
  ctx.log?.info?.(
@@ -3519,7 +3880,7 @@ var agentchatStatusAdapter = {
3519
3880
  }
3520
3881
  if (probe.mcp) lines.push({ text: probe.mcp.detail, tone: probe.mcp.ok ? "success" : "error" });
3521
3882
  for (const check of probe.placement ?? []) {
3522
- lines.push({ text: `${check.name}: ${check.detail}`, tone: check.ok ? "muted" : "warn" });
3883
+ lines.push({ text: `${check.name}: ${check.detail}`, tone: check.ok && !check.notice ? "muted" : "warn" });
3523
3884
  }
3524
3885
  if (probe.refusal) lines.push({ text: `integration not started \u2014 ${probe.refusal}`, tone: "error" });
3525
3886
  if (probe.integration) {
@@ -3569,8 +3930,8 @@ var agentchatDoctorAdapter = {
3569
3930
  const handle = readAgentchatConfigField(cfg, accountId, "agentHandle");
3570
3931
  const agentId = resolvePlacementAgentId(cfg, accountId);
3571
3932
  for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {
3572
- if (check.ok) continue;
3573
- const fix = check.name === "mcp" ? ` (${doctorFixCommand} adds it)` : "";
3933
+ if (check.ok && !check.notice) continue;
3934
+ const fix = check.name === "mcp" && check.repair && !check.ok ? ` (${doctorFixCommand} adds it)` : "";
3574
3935
  warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${check.name}: ${check.detail}${fix}`);
3575
3936
  }
3576
3937
  const bound = openclawLayout_js.resolveBoundAgentId(cfg, AGENTCHAT_CHANNEL_ID, accountId);
@@ -3639,6 +4000,7 @@ var agentchatDoctorAdapter = {
3639
4000
  const result = withHostedMcpEntry(next, apiBase, apiKey);
3640
4001
  next = result.cfg;
3641
4002
  if (result.outcome === "added") changes.push(`added mcp.servers.agentchat \u2192 ${apiBase}/mcp (bearer template on AGENTCHAT_API_KEY)`);
4003
+ if (result.outcome === "updated") changes.push(`updated mcp.servers.agentchat to name this client (${clientIdentityText()})`);
3642
4004
  }
3643
4005
  return { config: next, changes, ...warnings.length > 0 ? { warnings } : {} };
3644
4006
  }
@@ -3665,9 +4027,9 @@ function resolveAgentchatAccount(cfg, accountId) {
3665
4027
  var uiHints = {
3666
4028
  apiKey: {
3667
4029
  label: "AgentChat API key",
3668
- placeholder: "ac_live_...",
4030
+ placeholder: "ac_\u2026",
3669
4031
  sensitive: true,
3670
- help: "The setup wizard registers you via email OTP and mints a key, recovers a lost key (handle + email OTP), or accepts an existing ac_live_\u2026 key."
4032
+ help: "The setup wizard registers you via email OTP and mints a key, recovers a lost key (handle + email OTP), or accepts an existing ac_\u2026 key."
3671
4033
  },
3672
4034
  apiBase: {
3673
4035
  label: "API base URL",
@@ -3878,8 +4240,14 @@ var agentchatPlugin = {
3878
4240
  threads: false,
3879
4241
  nativeCommands: false
3880
4242
  },
4243
+ // OpenClaw matches a reload prefix as `path === prefix` or `path` starting
4244
+ // with `prefix.` (src/gateway/config-reload-plan.ts), so the prefix carries
4245
+ // no trailing dot: `channels.agentchat.` matched nothing, and every
4246
+ // channels.agentchat change restarted the gateway (2026.6.x–2026.8.x) or
4247
+ // reloaded the plugin (2026.11.x). With this one OpenClaw restarts just the
4248
+ // channel, after a running turn has ended.
3881
4249
  reload: {
3882
- configPrefixes: [`channels.${AGENTCHAT_CHANNEL_ID}.`]
4250
+ configPrefixes: [`channels.${AGENTCHAT_CHANNEL_ID}`]
3883
4251
  },
3884
4252
  configSchema: channelCore.buildChannelConfigSchema(agentchatChannelConfigSchema, { uiHints }),
3885
4253
  setupWizard: agentchatSetupWizard,