@agentchatme/openclaw 0.9.0 → 0.9.1

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.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { L as Logger } from './setup-entry-Dq5Dwg8O.cjs';
2
- export { A as AgentInvoker, a as AgentInvokerOptions, b as AgentchatChannelConfig, c as AgentchatResolvedAccount, C as CycleOutcome, d as CycleResult, G as GroupInvite, I as IntegrationSocket, e as IntegrationSocketOptions, f as InviteLedger, S as SocketBlocked, g as SocketDisconnect, h as SocketHandlers, i as SocketHealth, j as SocketState, W as WakeSource, k as agentchatChannelEntry, l as agentchatPlugin, m as agentchatSetupEntry, l as agentchatSetupPlugin, k as default, n as groupInviteFromRecord, p as parseChannelConfig, r as realtimeOptionsFor } from './setup-entry-Dq5Dwg8O.cjs';
1
+ import { L as Logger } from './setup-entry-Dh6dRH2F.cjs';
2
+ export { A as AgentInvoker, a as AgentInvokerOptions, b as AgentchatChannelConfig, c as AgentchatResolvedAccount, C as CreateMetricsOptions, d as CycleOutcome, e as CycleResult, G as GroupInvite, I as IntegrationSocket, f as IntegrationSocketOptions, g as InviteLedger, M as MetricsRecorder, h as MetricsSnapshot, P as PromFactory, i as PromRegistryLike, S as SocketBlocked, j as SocketDisconnect, k as SocketHandlers, l as SocketHealth, m as SocketState, W as WakeSource, n as agentchatChannelEntry, o as agentchatPlugin, p as agentchatSetupEntry, o as agentchatSetupPlugin, q as createInMemoryMetrics, r as createMetrics, s as createNoopMetrics, n as default, t as groupInviteFromRecord, u as parseChannelConfig, v as realtimeOptionsFor } from './setup-entry-Dh6dRH2F.cjs';
3
3
  export { hasAgentChatConfiguredState } from './configured-state.cjs';
4
4
  import { AgentChatClient, Texts, ToolNamer } from 'agentchatme';
5
5
  import 'openclaw/plugin-sdk/channel-core';
@@ -239,11 +239,11 @@ declare function spellToolsForOpenClaw(text: string): string;
239
239
  /**
240
240
  * The prompt a wake turn starts with: the served wake instruction and, when
241
241
  * the gate decided a specific conversation, one factual line naming it. The
242
- * `reply` verdict is recorded as the turn is admitted, which marks the
243
- * conversation read and takes it off the tray — so the turn is told which
244
- * conversation to open, and that the verdict is already taken care of.
245
- * Whether the tray still shows the card when the turn looks depends on the
246
- * race between the record and the turn's first call, so the line says so.
242
+ * `reply` verdict is recorded when the turn has completed — never at its
243
+ * start — so while the turn runs the conversation is still unread and its
244
+ * card still on the tray; the line says so, names the conversation to open,
245
+ * and says the verdict is taken care of (recording it in the turn as well is
246
+ * idempotent).
247
247
  */
248
248
  declare function wakeTurnPrompt(texts: Pick<Texts, 'wake_instruction'>, conversationId?: string): string;
249
249
  /** The prompt a group-invite turn starts with: the served invite prompt. */
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { L as Logger } from './setup-entry-Dq5Dwg8O.js';
2
- export { A as AgentInvoker, a as AgentInvokerOptions, b as AgentchatChannelConfig, c as AgentchatResolvedAccount, C as CycleOutcome, d as CycleResult, G as GroupInvite, I as IntegrationSocket, e as IntegrationSocketOptions, f as InviteLedger, S as SocketBlocked, g as SocketDisconnect, h as SocketHandlers, i as SocketHealth, j as SocketState, W as WakeSource, k as agentchatChannelEntry, l as agentchatPlugin, m as agentchatSetupEntry, l as agentchatSetupPlugin, k as default, n as groupInviteFromRecord, p as parseChannelConfig, r as realtimeOptionsFor } from './setup-entry-Dq5Dwg8O.js';
1
+ import { L as Logger } from './setup-entry-Dh6dRH2F.js';
2
+ export { A as AgentInvoker, a as AgentInvokerOptions, b as AgentchatChannelConfig, c as AgentchatResolvedAccount, C as CreateMetricsOptions, d as CycleOutcome, e as CycleResult, G as GroupInvite, I as IntegrationSocket, f as IntegrationSocketOptions, g as InviteLedger, M as MetricsRecorder, h as MetricsSnapshot, P as PromFactory, i as PromRegistryLike, S as SocketBlocked, j as SocketDisconnect, k as SocketHandlers, l as SocketHealth, m as SocketState, W as WakeSource, n as agentchatChannelEntry, o as agentchatPlugin, p as agentchatSetupEntry, o as agentchatSetupPlugin, q as createInMemoryMetrics, r as createMetrics, s as createNoopMetrics, n as default, t as groupInviteFromRecord, u as parseChannelConfig, v as realtimeOptionsFor } from './setup-entry-Dh6dRH2F.js';
3
3
  export { hasAgentChatConfiguredState } from './configured-state.js';
4
4
  import { AgentChatClient, Texts, ToolNamer } from 'agentchatme';
5
5
  import 'openclaw/plugin-sdk/channel-core';
@@ -239,11 +239,11 @@ declare function spellToolsForOpenClaw(text: string): string;
239
239
  /**
240
240
  * The prompt a wake turn starts with: the served wake instruction and, when
241
241
  * the gate decided a specific conversation, one factual line naming it. The
242
- * `reply` verdict is recorded as the turn is admitted, which marks the
243
- * conversation read and takes it off the tray — so the turn is told which
244
- * conversation to open, and that the verdict is already taken care of.
245
- * Whether the tray still shows the card when the turn looks depends on the
246
- * race between the record and the turn's first call, so the line says so.
242
+ * `reply` verdict is recorded when the turn has completed — never at its
243
+ * start — so while the turn runs the conversation is still unread and its
244
+ * card still on the tray; the line says so, names the conversation to open,
245
+ * and says the verdict is taken care of (recording it in the turn as well is
246
+ * idempotent).
247
247
  */
248
248
  declare function wakeTurnPrompt(texts: Pick<Texts, 'wake_instruction'>, conversationId?: string): string;
249
249
  /** The prompt a group-invite turn starts with: the served invite prompt. */
package/dist/index.js CHANGED
@@ -119,7 +119,7 @@ var AgentChatChannelError = class extends Error {
119
119
  };
120
120
 
121
121
  // src/version.ts
122
- var PACKAGE_VERSION = "0.9.0";
122
+ var PACKAGE_VERSION = "0.9.1";
123
123
 
124
124
  // src/client-identity.ts
125
125
  var AGENTCHAT_CLIENT_NAME = "openclaw";
@@ -408,6 +408,7 @@ var MCP_TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
408
408
  function mcpToolName(tool) {
409
409
  return `${MCP_TOOL_PREFIX}${tool}`;
410
410
  }
411
+ var DECIDE_TOOL = mcpToolName("agentchat_decide");
411
412
  var GET_CONVERSATION_TOOL = mcpToolName("agentchat_get_conversation");
412
413
  var OPENCLAW_TOOL_NAMER = (tool) => tool.startsWith(MCP_TOOL_PREFIX) ? tool : mcpToolName(tool);
413
414
  var HOSTED_TOOL_TOKEN = /\bagentchat_(?!_)[a-z0-9_]+\b/g;
@@ -422,7 +423,7 @@ function wakeTurnPrompt(texts, conversationId) {
422
423
  ${conversationLine(conversationId)}`;
423
424
  }
424
425
  function conversationLine(conversationId) {
425
- return `Conversation to answer in this turn: ${conversationId}. The gate decided reply and your reply verdict for it is being recorded; if this conversation still shows on the tray, do not record another verdict for it \u2014 open it with ${GET_CONVERSATION_TOOL} and reply.`;
426
+ return `Conversation to answer in this turn: ${conversationId}. The gate decided reply; its card is still on the tray while you work, and the reply verdict for it is recorded for you when this turn completes (recording it yourself with ${DECIDE_TOOL} is idempotent) \u2014 open it with ${GET_CONVERSATION_TOOL} and reply.`;
426
427
  }
427
428
  function inviteTurnPrompt(texts) {
428
429
  return texts.invite_prompt.trim();
@@ -600,8 +601,6 @@ function setPluginRuntime(runtime) {
600
601
  function getPluginRuntime() {
601
602
  return current;
602
603
  }
603
-
604
- // src/integration/model.ts
605
604
  var DEFAULT_AGENT_ID = "main";
606
605
  var GATE_TEMPERATURE = 0;
607
606
  var DEFAULT_GATE_MAX_TOKENS = 2048;
@@ -669,6 +668,36 @@ function resolveGateAgent(params) {
669
668
  const ambient = params.ambientAgentId?.trim().toLowerCase();
670
669
  return { agentId: routed, agentIdOverride: routed === (ambient ?? routed) ? void 0 : routed };
671
670
  }
671
+ function readLiveConfig(fallback, runtime = getPluginRuntime) {
672
+ try {
673
+ const loaded = runtime()?.config?.loadConfig?.();
674
+ if (loaded && typeof loaded === "object") return { cfg: loaded, live: true };
675
+ } catch {
676
+ }
677
+ return { cfg: fallback, live: false };
678
+ }
679
+ function turnReadiness(params) {
680
+ const env = params.env ?? process.env;
681
+ const restart = params.live === false ? ", then restart the gateway (this gateway cannot re-read its config while running)" : "";
682
+ switch (describeMcpEntry(params.cfg, params.apiBase, params.apiKey)) {
683
+ case "missing":
684
+ return { ready: false, reason: `mcp.servers.${MCP_SERVER_NAME} is not in the gateway config \u2014 run \`openclaw doctor --fix\`${restart}` };
685
+ case "disabled":
686
+ return { ready: false, reason: `mcp.servers.${MCP_SERVER_NAME} is disabled in the gateway config \u2014 enable it${restart}` };
687
+ case "user_managed":
688
+ return { ready: true };
689
+ case "ours": {
690
+ const value = env[API_KEY_ENV];
691
+ if (typeof value !== "string" || value.trim().length === 0) {
692
+ return {
693
+ ready: false,
694
+ reason: `${API_KEY_ENV} is not set in the gateway process, so the hosted tools' bearer template cannot resolve \u2014 restart the gateway (or reload its config) once ~/.openclaw/.env carries it`
695
+ };
696
+ }
697
+ return { ready: true };
698
+ }
699
+ }
700
+ }
672
701
  function createRuntimeTurnStarter(params = {}) {
673
702
  const getRuntime = params.runtime ?? getPluginRuntime;
674
703
  const waitMs = params.waitMs ?? DEFAULT_TURN_WAIT_MS;
@@ -2018,6 +2047,58 @@ function wrapPino(p) {
2018
2047
  }
2019
2048
 
2020
2049
  // src/metrics.ts
2050
+ function createMetrics(options) {
2051
+ const { registry: registry2, factory } = options;
2052
+ const disconnects = new factory.Counter({
2053
+ name: "agentchat_channel_disconnect_total",
2054
+ help: "WebSocket closes reported by the SDK, by close code and initiator (server | client).",
2055
+ labelNames: ["code", "initiator"],
2056
+ registers: [registry2]
2057
+ });
2058
+ const errors = new factory.Counter({
2059
+ name: "agentchat_channel_error_total",
2060
+ help: "Rejected HELLOs (auth) and the other notices the SDK surfaced, labeled by error class.",
2061
+ labelNames: ["errorClass"],
2062
+ registers: [registry2]
2063
+ });
2064
+ const connectionState = new factory.Gauge({
2065
+ name: "agentchat_channel_connection_state",
2066
+ help: "Current connection state (1 = active kind, 0 = otherwise).",
2067
+ labelNames: ["kind"],
2068
+ registers: [registry2]
2069
+ });
2070
+ const wakes = new factory.Counter({
2071
+ name: "agentchat_channel_wake_total",
2072
+ help: "Wakes handed to the integration (message frames, connects, server wake frames).",
2073
+ labelNames: ["source"],
2074
+ registers: [registry2]
2075
+ });
2076
+ return {
2077
+ incDisconnect: ({ code, initiator }) => disconnects.inc({ code, initiator }),
2078
+ incError: ({ errorClass }) => errors.inc({ errorClass }),
2079
+ setConnectionState: (kind) => connectionState.set({ kind }, 1),
2080
+ incWake: ({ source }) => wakes.inc({ source })
2081
+ };
2082
+ }
2083
+ function createInMemoryMetrics() {
2084
+ let state = "idle";
2085
+ const wakes = /* @__PURE__ */ new Map();
2086
+ const disconnects = /* @__PURE__ */ new Map();
2087
+ const errors = /* @__PURE__ */ new Map();
2088
+ const bump = (map, key) => {
2089
+ map.set(key, (map.get(key) ?? 0) + 1);
2090
+ };
2091
+ const plain = (map) => Object.fromEntries([...map.entries()].sort(([a], [b]) => a.localeCompare(b)));
2092
+ return {
2093
+ incDisconnect: ({ code, initiator }) => bump(disconnects, `${code}/${initiator}`),
2094
+ incError: ({ errorClass }) => bump(errors, errorClass),
2095
+ setConnectionState: (kind) => {
2096
+ state = kind;
2097
+ },
2098
+ incWake: ({ source }) => bump(wakes, source),
2099
+ snapshot: () => ({ state, wakes: plain(wakes), disconnects: plain(disconnects), errors: plain(errors) })
2100
+ };
2101
+ }
2021
2102
  function createNoopMetrics() {
2022
2103
  return {
2023
2104
  incDisconnect: () => void 0,
@@ -2334,7 +2415,14 @@ function registerIntegration(params) {
2334
2415
  const create = params.createSocket ?? ((options) => new IntegrationSocket(options));
2335
2416
  const socket = create({ config: params.config, logger: params.logger, handlers, ...params.socketOptions ?? {} });
2336
2417
  built = params.build(socket);
2337
- const entry = { socket, invoker: built.invoker, texts: built.texts ?? null, config: params.config, logger: params.logger };
2418
+ const entry = {
2419
+ socket,
2420
+ invoker: built.invoker,
2421
+ texts: built.texts ?? null,
2422
+ metrics: params.socketOptions?.metrics ?? null,
2423
+ config: params.config,
2424
+ logger: params.logger
2425
+ };
2338
2426
  registry.set(params.accountId, entry);
2339
2427
  try {
2340
2428
  await socket.start();
@@ -2488,6 +2576,7 @@ var AgentInvoker = class {
2488
2576
  invites;
2489
2577
  logger;
2490
2578
  metrics;
2579
+ readiness;
2491
2580
  gateEnabled;
2492
2581
  ladder;
2493
2582
  now;
@@ -2499,6 +2588,17 @@ var AgentInvoker = class {
2499
2588
  invitesDirty = false;
2500
2589
  retryRung = 0;
2501
2590
  turnsInFlight = 0;
2591
+ /**
2592
+ * Conversations whose reply turn is running. Their verdict is recorded
2593
+ * only when the turn completes, so the card stays on the tray meanwhile
2594
+ * and every wake in between would re-gate it and queue a second turn.
2595
+ * Such cards are left out of the cycle; once the turn ends the tray is
2596
+ * read again if any were.
2597
+ */
2598
+ replyTurnsInFlight = /* @__PURE__ */ new Set();
2599
+ skippedWhileInFlight = false;
2600
+ /** The reason the tools were last found unavailable; logged when it changes, not per wake. */
2601
+ unreadyReason = null;
2502
2602
  cycles = 0;
2503
2603
  turns = 0;
2504
2604
  inviteTurns = 0;
@@ -2512,6 +2612,7 @@ var AgentInvoker = class {
2512
2612
  this.invites = options.invites;
2513
2613
  this.logger = options.logger.child({ component: "integration", accountId: options.accountId });
2514
2614
  this.metrics = options.metrics ?? createNoopMetrics();
2615
+ this.readiness = options.readiness ?? (() => ({ ready: true }));
2515
2616
  this.gateEnabled = options.gateEnabled ?? true;
2516
2617
  this.ladder = options.retryLadderMs ?? RETRY_LADDER_MS;
2517
2618
  this.now = options.now ?? Date.now;
@@ -2619,24 +2720,44 @@ var AgentInvoker = class {
2619
2720
  this.logger.warn({ err: describe4(err), ...this.retry() }, "tray read failed \u2014 re-waking later");
2620
2721
  return this.result("tray_failed", 0, false, started, describe4(err));
2621
2722
  }
2622
- const cards = gate.cardsOf(tray);
2723
+ const allCards = gate.cardsOf(tray);
2623
2724
  const truncated = tray.truncated === true;
2624
- if (cards.length === 0) {
2725
+ if (allCards.length === 0) {
2625
2726
  this.logger.info({ deferred: tray.deferred ?? 0 }, "tray empty \u2014 nothing to decide");
2626
2727
  this.retryRung = 0;
2627
2728
  return this.result("empty", 0, truncated, started);
2628
2729
  }
2730
+ const cards = allCards.filter((card) => !this.replyTurnsInFlight.has(card.conversation_id));
2731
+ const skippedInFlight = allCards.length - cards.length;
2732
+ if (skippedInFlight > 0) this.skippedWhileInFlight = true;
2733
+ if (cards.length === 0) {
2734
+ this.logger.info({ skippedInFlight }, "every card on the tray has a reply turn running \u2014 nothing new to decide");
2735
+ return { ...this.result("empty", 0, truncated, started), skippedInFlight };
2736
+ }
2629
2737
  const texts = await this.texts.ensure();
2630
2738
  if (!texts) {
2631
2739
  this.logger.warn({ cards: cards.length, ...this.retry() }, "served texts not available \u2014 not gating; the cards wait on the tray");
2632
- return this.result("texts_missing", cards.length, truncated, started, "texts missing");
2740
+ return { ...this.result("texts_missing", cards.length, truncated, started, "texts missing"), skippedInFlight };
2741
+ }
2742
+ const readiness = this.readiness();
2743
+ if (!readiness.ready) {
2744
+ const changed = this.unreadyReason !== readiness.reason;
2745
+ this.unreadyReason = readiness.reason;
2746
+ this.logger[changed ? "warn" : "debug"]({ cards: cards.length, reason: readiness.reason, ...this.retry() }, "AgentChat tools not available to a turn \u2014 not gating; the cards wait on the tray");
2747
+ return { ...this.result("tools_unavailable", cards.length, truncated, started, readiness.reason), skippedInFlight };
2748
+ }
2749
+ if (this.unreadyReason !== null) {
2750
+ this.unreadyReason = null;
2751
+ this.logger.info({}, "AgentChat tools available to turns again");
2633
2752
  }
2634
2753
  let result;
2635
2754
  if (!this.gateEnabled) {
2636
2755
  result = await this.runUngated(cards.length, texts, truncated, started);
2637
2756
  } else {
2638
- result = await this.runGated(tray, cards.length, texts, truncated, started);
2757
+ const trayToGate = skippedInFlight > 0 ? { ...tray, conversations: cards } : tray;
2758
+ result = await this.runGated(trayToGate, cards.length, texts, truncated, started, skippedInFlight);
2639
2759
  }
2760
+ if (skippedInFlight > 0) result = { ...result, skippedInFlight };
2640
2761
  if (truncated && result.outcome !== "fail_closed") {
2641
2762
  this.logger.info({}, "tray truncated \u2014 waking again for the rest");
2642
2763
  this.coalescer.wake();
@@ -2661,7 +2782,7 @@ var AgentInvoker = class {
2661
2782
  turnsRefused: admission.ran ? 0 : 1
2662
2783
  };
2663
2784
  }
2664
- async runGated(tray, cards, texts, truncated, started) {
2785
+ async runGated(tray, cards, texts, truncated, started, skippedInFlight = 0) {
2665
2786
  const decided = await gate.run({ tray, callModel: this.callModel, client: this.client, toolNamer: OPENCLAW_TOOL_NAMER });
2666
2787
  const latencyMs = this.now() - started;
2667
2788
  const counts = { reply: 0, dismiss: 0, defer: 0 };
@@ -2676,9 +2797,13 @@ var AgentInvoker = class {
2676
2797
  }
2677
2798
  let turnsStarted = 0;
2678
2799
  let turnsRefused = 0;
2679
- let recordFailures = decided.recordFailures.length;
2680
- let recorded = decided.recorded;
2800
+ const recordFailures = decided.recordFailures.length;
2801
+ const recorded = decided.recorded;
2681
2802
  for (const entry of decided.reply) {
2803
+ if (this.replyTurnsInFlight.has(entry.conversationId)) {
2804
+ this.skippedWhileInFlight = true;
2805
+ continue;
2806
+ }
2682
2807
  const sessionKey = wakeSessionKey(this.agentId, this.now());
2683
2808
  this.logger.info({ sessionKey, conversationId: entry.conversationId }, "turn start");
2684
2809
  const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts, entry.conversationId), lane: integrationLane(this.accountId) });
@@ -2688,14 +2813,8 @@ var AgentInvoker = class {
2688
2813
  continue;
2689
2814
  }
2690
2815
  turnsStarted += 1;
2691
- this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)");
2692
- try {
2693
- await entry.record();
2694
- recorded += 1;
2695
- } catch (err) {
2696
- recordFailures += 1;
2697
- this.logger.warn({ conversationId: entry.conversationId, err: describe4(err) }, "reply verdict not recorded \u2014 the turn runs; the conversation stays unread until it decides");
2698
- }
2816
+ this.replyTurnsInFlight.add(entry.conversationId);
2817
+ this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)", entry);
2699
2818
  }
2700
2819
  const summary = {
2701
2820
  cards,
@@ -2707,6 +2826,7 @@ var AgentInvoker = class {
2707
2826
  recordFailures,
2708
2827
  turnsStarted,
2709
2828
  turnsRefused,
2829
+ skippedInFlight,
2710
2830
  latencyMs
2711
2831
  };
2712
2832
  if (turnsRefused > 0) {
@@ -2731,6 +2851,7 @@ var AgentInvoker = class {
2731
2851
  recordFailures: 0,
2732
2852
  turnsStarted: 0,
2733
2853
  turnsRefused: 0,
2854
+ skippedInFlight: 0,
2734
2855
  truncated,
2735
2856
  latencyMs: this.now() - started,
2736
2857
  failure
@@ -2753,24 +2874,72 @@ var AgentInvoker = class {
2753
2874
  /**
2754
2875
  * Book an admitted turn and log its end whenever it comes. The cycle moves
2755
2876
  * on at once; OpenClaw's lane keeps the runs of one account in order.
2877
+ *
2878
+ * For a reply turn the end is also when the `reply` verdict is recorded —
2879
+ * only if the run completed (`status: ok`, no error): a turn that looked
2880
+ * and chose not to send still counts as read. A run that ended in error,
2881
+ * on the wait timeout, or whose wait failed records nothing: the card stays
2882
+ * on the tray and the ladder re-wakes so the conversation is gated again.
2756
2883
  */
2757
- admitted(sessionKey, admission, completeLine) {
2884
+ admitted(sessionKey, admission, completeLine, reply) {
2758
2885
  this.turns += 1;
2759
2886
  this.turnsInFlight += 1;
2760
2887
  void admission.done.then(
2761
- (outcome) => {
2888
+ async (outcome) => {
2762
2889
  this.turnsInFlight -= 1;
2763
- this.logger[outcome.error ? "warn" : "info"](
2890
+ const completed = outcome.ran && outcome.status === "ok" && !outcome.error;
2891
+ this.logger[completed ? "info" : "warn"](
2764
2892
  { sessionKey, runId: outcome.runId, status: outcome.status, ...outcome.error ? { error: outcome.error } : {} },
2765
2893
  completeLine
2766
2894
  );
2895
+ if (!reply) return;
2896
+ try {
2897
+ if (!completed) {
2898
+ this.logger.warn(
2899
+ { sessionKey, conversationId: reply.conversationId, status: outcome.status, ...outcome.error ? { error: outcome.error } : {}, ...this.retry() },
2900
+ "turn did not complete \u2014 reply not recorded; the conversation stays unread and is gated again"
2901
+ );
2902
+ return;
2903
+ }
2904
+ await this.recordReply(sessionKey, reply);
2905
+ } finally {
2906
+ this.replyTurnEnded(reply.conversationId);
2907
+ }
2767
2908
  },
2768
- (err) => {
2909
+ async (err) => {
2769
2910
  this.turnsInFlight -= 1;
2770
2911
  this.logger.warn({ sessionKey, runId: admission.runId, err: describe4(err) }, `${completeLine} \u2014 the wait failed`);
2912
+ if (reply) {
2913
+ this.logger.warn(
2914
+ { sessionKey, conversationId: reply.conversationId, err: describe4(err), ...this.retry() },
2915
+ "turn did not complete \u2014 reply not recorded; the conversation stays unread and is gated again"
2916
+ );
2917
+ this.replyTurnEnded(reply.conversationId);
2918
+ }
2771
2919
  }
2772
2920
  );
2773
2921
  }
2922
+ /** The reply turn for `conversationId` is over: its card may be gated again, and a tray that held skipped cards is read once more. */
2923
+ replyTurnEnded(conversationId) {
2924
+ this.replyTurnsInFlight.delete(conversationId);
2925
+ if (this.skippedWhileInFlight && !this.stopped) {
2926
+ this.skippedWhileInFlight = false;
2927
+ this.logger.debug({ conversationId }, "reply turn ended \u2014 re-reading the tray for the cards left out meanwhile");
2928
+ this.coalescer.wake();
2929
+ }
2930
+ }
2931
+ /** The `reply` verdict for a completed turn. A record the server refuses leaves the conversation unread; the ladder re-wakes. */
2932
+ async recordReply(sessionKey, reply) {
2933
+ try {
2934
+ await reply.record();
2935
+ this.logger.info({ sessionKey, conversationId: reply.conversationId }, "reply verdict recorded \u2014 turn completed");
2936
+ } catch (err) {
2937
+ this.logger.warn(
2938
+ { sessionKey, conversationId: reply.conversationId, err: describe4(err), ...this.retry() },
2939
+ "reply verdict not recorded after the turn completed \u2014 the conversation stays unread; the next wake gates it again"
2940
+ );
2941
+ }
2942
+ }
2774
2943
  /**
2775
2944
  * Every pending invite gets one attempt. An invite leaves the pending list
2776
2945
  * only once its turn was admitted (and is then remembered in the ledger);
@@ -2779,6 +2948,15 @@ var AgentInvoker = class {
2779
2948
  */
2780
2949
  async runInviteTurns() {
2781
2950
  const batch = [...this.pendingInvites];
2951
+ if (batch.length > 0) {
2952
+ const readiness = this.readiness();
2953
+ if (!readiness.ready) {
2954
+ const changed = this.unreadyReason !== readiness.reason;
2955
+ this.unreadyReason = readiness.reason;
2956
+ this.logger[changed ? "warn" : "debug"]({ pending: batch.length, reason: readiness.reason, ...this.retry() }, "AgentChat tools not available to a turn \u2014 invite turns wait; re-waking later");
2957
+ return;
2958
+ }
2959
+ }
2782
2960
  let texts = null;
2783
2961
  let refused = 0;
2784
2962
  let waitingForTexts = 0;
@@ -2910,11 +3088,12 @@ var agentchatGatewayAdapter = {
2910
3088
  accountId: ctx.accountId,
2911
3089
  onWriteError: (err) => ctx.log?.warn?.(`[agentchat:${ctx.accountId}] invite ledger could not be written: ${err instanceof Error ? err.message : String(err)}`)
2912
3090
  });
3091
+ const metrics = createInMemoryMetrics();
2913
3092
  await registerIntegration({
2914
3093
  accountId: ctx.accountId,
2915
3094
  config,
2916
3095
  logger,
2917
- socketOptions: { client },
3096
+ socketOptions: { client, metrics },
2918
3097
  build: (socket) => {
2919
3098
  const invoker = new AgentInvoker({
2920
3099
  accountId: ctx.accountId,
@@ -2922,9 +3101,18 @@ var agentchatGatewayAdapter = {
2922
3101
  client,
2923
3102
  callModel: createRuntimeModelCall({ agentIdOverride, ...gateTimeoutMs !== void 0 ? { timeoutMs: gateTimeoutMs } : {} }),
2924
3103
  startTurn: createRuntimeTurnStarter(),
3104
+ // Gating waits until a turn can have the hosted tools (the MCP
3105
+ // entry in the LIVE config — OpenClaw hot-applies `mcp.*` — and
3106
+ // its key in this process): a connect wake on a cold gateway
3107
+ // otherwise spends a gate call and runs a turn that cannot look.
3108
+ readiness: () => {
3109
+ const live = readLiveConfig(ctx.cfg);
3110
+ return turnReadiness({ cfg: live.cfg, apiBase: config.apiBase, apiKey: config.apiKey, live: live.live });
3111
+ },
2925
3112
  texts,
2926
3113
  invites,
2927
3114
  logger,
3115
+ metrics,
2928
3116
  gateEnabled: readReplyGateEnabledFromEnv()
2929
3117
  });
2930
3118
  let blocked = false;
@@ -3016,6 +3204,10 @@ async function catchUpInvites(accountId, client, invoker, logger) {
3016
3204
  }
3017
3205
  var PROBE_MIN_MS = 1e3;
3018
3206
  var PROBE_MAX_MS = 1e4;
3207
+ function formatCounts(counts) {
3208
+ const parts = Object.entries(counts).map(([label, n]) => `${label} ${n}`);
3209
+ return parts.length > 0 ? parts.join(", ") : "none";
3210
+ }
3019
3211
  var agentchatStatusAdapter = {
3020
3212
  async probeAccount({ account, timeoutMs, cfg }) {
3021
3213
  if (!account.config) {
@@ -3053,11 +3245,13 @@ var agentchatStatusAdapter = {
3053
3245
  const health = live?.socket.getHealth();
3054
3246
  const counters = live?.invoker?.counters();
3055
3247
  const textsSource = live ? live.texts?.source ?? "missing" : void 0;
3248
+ const socketCounters = live?.metrics?.snapshot?.();
3056
3249
  const integration = {
3057
3250
  mode: readWakeModeFromEnv().mode,
3058
3251
  ...health ? { state: health.state } : {},
3059
3252
  ...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
3060
- ...textsSource ? { texts: textsSource } : {}
3253
+ ...textsSource ? { texts: textsSource } : {},
3254
+ ...socketCounters ? { socket: socketCounters } : {}
3061
3255
  };
3062
3256
  const refusal = multiAccountRefusal(cfg);
3063
3257
  return {
@@ -3099,6 +3293,12 @@ var agentchatStatusAdapter = {
3099
3293
  text: `integration ${d.state} \u2014 wakes ${d.wakes ?? 0}, cycles ${d.cycles ?? 0}, turns ${d.turns ?? 0}`,
3100
3294
  tone: d.state === "ready" ? "success" : "warn"
3101
3295
  });
3296
+ if (d.socket) {
3297
+ lines.push({
3298
+ text: `socket \u2014 wakes: ${formatCounts(d.socket.wakes)} \xB7 closes: ${formatCounts(d.socket.disconnects)} \xB7 notices: ${formatCounts(d.socket.errors)}`,
3299
+ tone: "muted"
3300
+ });
3301
+ }
3102
3302
  if (d.texts === "missing") {
3103
3303
  lines.push({ text: "served texts not available yet (AgentChat unreachable, nothing cached) \u2014 turns wait for the first copy", tone: "error" });
3104
3304
  } else if (d.texts === "cache") {
@@ -3538,6 +3738,6 @@ function hasAgentChatConfiguredState(config) {
3538
3738
  return true;
3539
3739
  }
3540
3740
 
3541
- export { AGENTCHAT_CHANNEL_ID, AGENTCHAT_DEFAULT_ACCOUNT_ID, AgentChatChannelError, AgentInvoker, IntegrationSocket, InviteLedger, MCP_SERVER_NAME, OPENCLAW_TOOL_NAMER, TextsStore, WakeCoalescer, agentchatChannelEntry, agentchatPlugin, agentchatSetupEntry, agentchatPlugin as agentchatSetupPlugin, assertApiKeyValid, agentchatChannelEntry as default, groupInviteFromRecord, hasAgentChatConfiguredState, hostedMcpServerEntry, hostedMcpSnippet, hostedMcpUrl, inviteTurnPrompt, loadIdentityLine, loadTexts, mcpToolName, parseChannelConfig, probeHostedMcp, realtimeOptionsFor, recoverAgentStart, recoverAgentVerify, registerAgentStart, registerAgentVerify, spellToolsForOpenClaw, validateApiKey, wakeTurnPrompt };
3741
+ export { AGENTCHAT_CHANNEL_ID, AGENTCHAT_DEFAULT_ACCOUNT_ID, AgentChatChannelError, AgentInvoker, IntegrationSocket, InviteLedger, MCP_SERVER_NAME, OPENCLAW_TOOL_NAMER, TextsStore, WakeCoalescer, agentchatChannelEntry, agentchatPlugin, agentchatSetupEntry, agentchatPlugin as agentchatSetupPlugin, assertApiKeyValid, createInMemoryMetrics, createMetrics, createNoopMetrics, agentchatChannelEntry as default, groupInviteFromRecord, hasAgentChatConfiguredState, hostedMcpServerEntry, hostedMcpSnippet, hostedMcpUrl, inviteTurnPrompt, loadIdentityLine, loadTexts, mcpToolName, parseChannelConfig, probeHostedMcp, realtimeOptionsFor, recoverAgentStart, recoverAgentVerify, registerAgentStart, registerAgentVerify, spellToolsForOpenClaw, validateApiKey, wakeTurnPrompt };
3542
3742
  //# sourceMappingURL=index.js.map
3543
3743
  //# sourceMappingURL=index.js.map