@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.
@@ -133,7 +133,7 @@ function applyAgentchatAccountPatch(cfg, accountId, patch) {
133
133
  }
134
134
 
135
135
  // src/version.ts
136
- var PACKAGE_VERSION = "0.9.0";
136
+ var PACKAGE_VERSION = "0.9.1";
137
137
 
138
138
  // src/client-identity.ts
139
139
  var AGENTCHAT_CLIENT_NAME = "openclaw";
@@ -414,6 +414,7 @@ var MCP_TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
414
414
  function mcpToolName(tool) {
415
415
  return `${MCP_TOOL_PREFIX}${tool}`;
416
416
  }
417
+ var DECIDE_TOOL = mcpToolName("agentchat_decide");
417
418
  var GET_CONVERSATION_TOOL = mcpToolName("agentchat_get_conversation");
418
419
  var OPENCLAW_TOOL_NAMER = (tool) => tool.startsWith(MCP_TOOL_PREFIX) ? tool : mcpToolName(tool);
419
420
  var HOSTED_TOOL_TOKEN = /\bagentchat_(?!_)[a-z0-9_]+\b/g;
@@ -428,7 +429,7 @@ function wakeTurnPrompt(texts, conversationId) {
428
429
  ${conversationLine(conversationId)}`;
429
430
  }
430
431
  function conversationLine(conversationId) {
431
- 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.`;
432
+ 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.`;
432
433
  }
433
434
  function inviteTurnPrompt(texts) {
434
435
  return texts.invite_prompt.trim();
@@ -591,8 +592,6 @@ function setPluginRuntime(runtime) {
591
592
  function getPluginRuntime() {
592
593
  return current;
593
594
  }
594
-
595
- // src/integration/model.ts
596
595
  var DEFAULT_AGENT_ID = "main";
597
596
  var GATE_TEMPERATURE = 0;
598
597
  var DEFAULT_GATE_MAX_TOKENS = 2048;
@@ -660,6 +659,36 @@ function resolveGateAgent(params) {
660
659
  const ambient = params.ambientAgentId?.trim().toLowerCase();
661
660
  return { agentId: routed, agentIdOverride: routed === (ambient ?? routed) ? void 0 : routed };
662
661
  }
662
+ function readLiveConfig(fallback, runtime = getPluginRuntime) {
663
+ try {
664
+ const loaded = runtime()?.config?.loadConfig?.();
665
+ if (loaded && typeof loaded === "object") return { cfg: loaded, live: true };
666
+ } catch {
667
+ }
668
+ return { cfg: fallback, live: false };
669
+ }
670
+ function turnReadiness(params) {
671
+ const env = params.env ?? process.env;
672
+ const restart = params.live === false ? ", then restart the gateway (this gateway cannot re-read its config while running)" : "";
673
+ switch (describeMcpEntry(params.cfg, params.apiBase, params.apiKey)) {
674
+ case "missing":
675
+ return { ready: false, reason: `mcp.servers.${MCP_SERVER_NAME} is not in the gateway config \u2014 run \`openclaw doctor --fix\`${restart}` };
676
+ case "disabled":
677
+ return { ready: false, reason: `mcp.servers.${MCP_SERVER_NAME} is disabled in the gateway config \u2014 enable it${restart}` };
678
+ case "user_managed":
679
+ return { ready: true };
680
+ case "ours": {
681
+ const value = env[readEnv_js.API_KEY_ENV];
682
+ if (typeof value !== "string" || value.trim().length === 0) {
683
+ return {
684
+ ready: false,
685
+ reason: `${readEnv_js.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`
686
+ };
687
+ }
688
+ return { ready: true };
689
+ }
690
+ }
691
+ }
663
692
  function createRuntimeTurnStarter(params = {}) {
664
693
  const getRuntime = params.runtime ?? getPluginRuntime;
665
694
  const waitMs = params.waitMs ?? DEFAULT_TURN_WAIT_MS;
@@ -2009,6 +2038,25 @@ function wrapPino(p) {
2009
2038
  }
2010
2039
 
2011
2040
  // src/metrics.ts
2041
+ function createInMemoryMetrics() {
2042
+ let state = "idle";
2043
+ const wakes = /* @__PURE__ */ new Map();
2044
+ const disconnects = /* @__PURE__ */ new Map();
2045
+ const errors = /* @__PURE__ */ new Map();
2046
+ const bump = (map, key) => {
2047
+ map.set(key, (map.get(key) ?? 0) + 1);
2048
+ };
2049
+ const plain = (map) => Object.fromEntries([...map.entries()].sort(([a], [b]) => a.localeCompare(b)));
2050
+ return {
2051
+ incDisconnect: ({ code, initiator }) => bump(disconnects, `${code}/${initiator}`),
2052
+ incError: ({ errorClass }) => bump(errors, errorClass),
2053
+ setConnectionState: (kind) => {
2054
+ state = kind;
2055
+ },
2056
+ incWake: ({ source }) => bump(wakes, source),
2057
+ snapshot: () => ({ state, wakes: plain(wakes), disconnects: plain(disconnects), errors: plain(errors) })
2058
+ };
2059
+ }
2012
2060
  function createNoopMetrics() {
2013
2061
  return {
2014
2062
  incDisconnect: () => void 0,
@@ -2325,7 +2373,14 @@ function registerIntegration(params) {
2325
2373
  const create = params.createSocket ?? ((options) => new IntegrationSocket(options));
2326
2374
  const socket = create({ config: params.config, logger: params.logger, handlers, ...params.socketOptions ?? {} });
2327
2375
  built = params.build(socket);
2328
- const entry = { socket, invoker: built.invoker, texts: built.texts ?? null, config: params.config, logger: params.logger };
2376
+ const entry = {
2377
+ socket,
2378
+ invoker: built.invoker,
2379
+ texts: built.texts ?? null,
2380
+ metrics: params.socketOptions?.metrics ?? null,
2381
+ config: params.config,
2382
+ logger: params.logger
2383
+ };
2329
2384
  registry.set(params.accountId, entry);
2330
2385
  try {
2331
2386
  await socket.start();
@@ -2479,6 +2534,7 @@ var AgentInvoker = class {
2479
2534
  invites;
2480
2535
  logger;
2481
2536
  metrics;
2537
+ readiness;
2482
2538
  gateEnabled;
2483
2539
  ladder;
2484
2540
  now;
@@ -2490,6 +2546,17 @@ var AgentInvoker = class {
2490
2546
  invitesDirty = false;
2491
2547
  retryRung = 0;
2492
2548
  turnsInFlight = 0;
2549
+ /**
2550
+ * Conversations whose reply turn is running. Their verdict is recorded
2551
+ * only when the turn completes, so the card stays on the tray meanwhile
2552
+ * and every wake in between would re-gate it and queue a second turn.
2553
+ * Such cards are left out of the cycle; once the turn ends the tray is
2554
+ * read again if any were.
2555
+ */
2556
+ replyTurnsInFlight = /* @__PURE__ */ new Set();
2557
+ skippedWhileInFlight = false;
2558
+ /** The reason the tools were last found unavailable; logged when it changes, not per wake. */
2559
+ unreadyReason = null;
2493
2560
  cycles = 0;
2494
2561
  turns = 0;
2495
2562
  inviteTurns = 0;
@@ -2503,6 +2570,7 @@ var AgentInvoker = class {
2503
2570
  this.invites = options.invites;
2504
2571
  this.logger = options.logger.child({ component: "integration", accountId: options.accountId });
2505
2572
  this.metrics = options.metrics ?? createNoopMetrics();
2573
+ this.readiness = options.readiness ?? (() => ({ ready: true }));
2506
2574
  this.gateEnabled = options.gateEnabled ?? true;
2507
2575
  this.ladder = options.retryLadderMs ?? RETRY_LADDER_MS;
2508
2576
  this.now = options.now ?? Date.now;
@@ -2610,24 +2678,44 @@ var AgentInvoker = class {
2610
2678
  this.logger.warn({ err: describe4(err), ...this.retry() }, "tray read failed \u2014 re-waking later");
2611
2679
  return this.result("tray_failed", 0, false, started, describe4(err));
2612
2680
  }
2613
- const cards = agentchatme.gate.cardsOf(tray);
2681
+ const allCards = agentchatme.gate.cardsOf(tray);
2614
2682
  const truncated = tray.truncated === true;
2615
- if (cards.length === 0) {
2683
+ if (allCards.length === 0) {
2616
2684
  this.logger.info({ deferred: tray.deferred ?? 0 }, "tray empty \u2014 nothing to decide");
2617
2685
  this.retryRung = 0;
2618
2686
  return this.result("empty", 0, truncated, started);
2619
2687
  }
2688
+ const cards = allCards.filter((card) => !this.replyTurnsInFlight.has(card.conversation_id));
2689
+ const skippedInFlight = allCards.length - cards.length;
2690
+ if (skippedInFlight > 0) this.skippedWhileInFlight = true;
2691
+ if (cards.length === 0) {
2692
+ this.logger.info({ skippedInFlight }, "every card on the tray has a reply turn running \u2014 nothing new to decide");
2693
+ return { ...this.result("empty", 0, truncated, started), skippedInFlight };
2694
+ }
2620
2695
  const texts = await this.texts.ensure();
2621
2696
  if (!texts) {
2622
2697
  this.logger.warn({ cards: cards.length, ...this.retry() }, "served texts not available \u2014 not gating; the cards wait on the tray");
2623
- return this.result("texts_missing", cards.length, truncated, started, "texts missing");
2698
+ return { ...this.result("texts_missing", cards.length, truncated, started, "texts missing"), skippedInFlight };
2699
+ }
2700
+ const readiness = this.readiness();
2701
+ if (!readiness.ready) {
2702
+ const changed = this.unreadyReason !== readiness.reason;
2703
+ this.unreadyReason = readiness.reason;
2704
+ 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");
2705
+ return { ...this.result("tools_unavailable", cards.length, truncated, started, readiness.reason), skippedInFlight };
2706
+ }
2707
+ if (this.unreadyReason !== null) {
2708
+ this.unreadyReason = null;
2709
+ this.logger.info({}, "AgentChat tools available to turns again");
2624
2710
  }
2625
2711
  let result;
2626
2712
  if (!this.gateEnabled) {
2627
2713
  result = await this.runUngated(cards.length, texts, truncated, started);
2628
2714
  } else {
2629
- result = await this.runGated(tray, cards.length, texts, truncated, started);
2715
+ const trayToGate = skippedInFlight > 0 ? { ...tray, conversations: cards } : tray;
2716
+ result = await this.runGated(trayToGate, cards.length, texts, truncated, started, skippedInFlight);
2630
2717
  }
2718
+ if (skippedInFlight > 0) result = { ...result, skippedInFlight };
2631
2719
  if (truncated && result.outcome !== "fail_closed") {
2632
2720
  this.logger.info({}, "tray truncated \u2014 waking again for the rest");
2633
2721
  this.coalescer.wake();
@@ -2652,7 +2740,7 @@ var AgentInvoker = class {
2652
2740
  turnsRefused: admission.ran ? 0 : 1
2653
2741
  };
2654
2742
  }
2655
- async runGated(tray, cards, texts, truncated, started) {
2743
+ async runGated(tray, cards, texts, truncated, started, skippedInFlight = 0) {
2656
2744
  const decided = await agentchatme.gate.run({ tray, callModel: this.callModel, client: this.client, toolNamer: OPENCLAW_TOOL_NAMER });
2657
2745
  const latencyMs = this.now() - started;
2658
2746
  const counts = { reply: 0, dismiss: 0, defer: 0 };
@@ -2667,9 +2755,13 @@ var AgentInvoker = class {
2667
2755
  }
2668
2756
  let turnsStarted = 0;
2669
2757
  let turnsRefused = 0;
2670
- let recordFailures = decided.recordFailures.length;
2671
- let recorded = decided.recorded;
2758
+ const recordFailures = decided.recordFailures.length;
2759
+ const recorded = decided.recorded;
2672
2760
  for (const entry of decided.reply) {
2761
+ if (this.replyTurnsInFlight.has(entry.conversationId)) {
2762
+ this.skippedWhileInFlight = true;
2763
+ continue;
2764
+ }
2673
2765
  const sessionKey = wakeSessionKey(this.agentId, this.now());
2674
2766
  this.logger.info({ sessionKey, conversationId: entry.conversationId }, "turn start");
2675
2767
  const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts, entry.conversationId), lane: integrationLane(this.accountId) });
@@ -2679,14 +2771,8 @@ var AgentInvoker = class {
2679
2771
  continue;
2680
2772
  }
2681
2773
  turnsStarted += 1;
2682
- this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)");
2683
- try {
2684
- await entry.record();
2685
- recorded += 1;
2686
- } catch (err) {
2687
- recordFailures += 1;
2688
- this.logger.warn({ conversationId: entry.conversationId, err: describe4(err) }, "reply verdict not recorded \u2014 the turn runs; the conversation stays unread until it decides");
2689
- }
2774
+ this.replyTurnsInFlight.add(entry.conversationId);
2775
+ this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)", entry);
2690
2776
  }
2691
2777
  const summary = {
2692
2778
  cards,
@@ -2698,6 +2784,7 @@ var AgentInvoker = class {
2698
2784
  recordFailures,
2699
2785
  turnsStarted,
2700
2786
  turnsRefused,
2787
+ skippedInFlight,
2701
2788
  latencyMs
2702
2789
  };
2703
2790
  if (turnsRefused > 0) {
@@ -2722,6 +2809,7 @@ var AgentInvoker = class {
2722
2809
  recordFailures: 0,
2723
2810
  turnsStarted: 0,
2724
2811
  turnsRefused: 0,
2812
+ skippedInFlight: 0,
2725
2813
  truncated,
2726
2814
  latencyMs: this.now() - started,
2727
2815
  failure
@@ -2744,24 +2832,72 @@ var AgentInvoker = class {
2744
2832
  /**
2745
2833
  * Book an admitted turn and log its end whenever it comes. The cycle moves
2746
2834
  * on at once; OpenClaw's lane keeps the runs of one account in order.
2835
+ *
2836
+ * For a reply turn the end is also when the `reply` verdict is recorded —
2837
+ * only if the run completed (`status: ok`, no error): a turn that looked
2838
+ * and chose not to send still counts as read. A run that ended in error,
2839
+ * on the wait timeout, or whose wait failed records nothing: the card stays
2840
+ * on the tray and the ladder re-wakes so the conversation is gated again.
2747
2841
  */
2748
- admitted(sessionKey, admission, completeLine) {
2842
+ admitted(sessionKey, admission, completeLine, reply) {
2749
2843
  this.turns += 1;
2750
2844
  this.turnsInFlight += 1;
2751
2845
  void admission.done.then(
2752
- (outcome) => {
2846
+ async (outcome) => {
2753
2847
  this.turnsInFlight -= 1;
2754
- this.logger[outcome.error ? "warn" : "info"](
2848
+ const completed = outcome.ran && outcome.status === "ok" && !outcome.error;
2849
+ this.logger[completed ? "info" : "warn"](
2755
2850
  { sessionKey, runId: outcome.runId, status: outcome.status, ...outcome.error ? { error: outcome.error } : {} },
2756
2851
  completeLine
2757
2852
  );
2853
+ if (!reply) return;
2854
+ try {
2855
+ if (!completed) {
2856
+ this.logger.warn(
2857
+ { sessionKey, conversationId: reply.conversationId, status: outcome.status, ...outcome.error ? { error: outcome.error } : {}, ...this.retry() },
2858
+ "turn did not complete \u2014 reply not recorded; the conversation stays unread and is gated again"
2859
+ );
2860
+ return;
2861
+ }
2862
+ await this.recordReply(sessionKey, reply);
2863
+ } finally {
2864
+ this.replyTurnEnded(reply.conversationId);
2865
+ }
2758
2866
  },
2759
- (err) => {
2867
+ async (err) => {
2760
2868
  this.turnsInFlight -= 1;
2761
2869
  this.logger.warn({ sessionKey, runId: admission.runId, err: describe4(err) }, `${completeLine} \u2014 the wait failed`);
2870
+ if (reply) {
2871
+ this.logger.warn(
2872
+ { sessionKey, conversationId: reply.conversationId, err: describe4(err), ...this.retry() },
2873
+ "turn did not complete \u2014 reply not recorded; the conversation stays unread and is gated again"
2874
+ );
2875
+ this.replyTurnEnded(reply.conversationId);
2876
+ }
2762
2877
  }
2763
2878
  );
2764
2879
  }
2880
+ /** The reply turn for `conversationId` is over: its card may be gated again, and a tray that held skipped cards is read once more. */
2881
+ replyTurnEnded(conversationId) {
2882
+ this.replyTurnsInFlight.delete(conversationId);
2883
+ if (this.skippedWhileInFlight && !this.stopped) {
2884
+ this.skippedWhileInFlight = false;
2885
+ this.logger.debug({ conversationId }, "reply turn ended \u2014 re-reading the tray for the cards left out meanwhile");
2886
+ this.coalescer.wake();
2887
+ }
2888
+ }
2889
+ /** The `reply` verdict for a completed turn. A record the server refuses leaves the conversation unread; the ladder re-wakes. */
2890
+ async recordReply(sessionKey, reply) {
2891
+ try {
2892
+ await reply.record();
2893
+ this.logger.info({ sessionKey, conversationId: reply.conversationId }, "reply verdict recorded \u2014 turn completed");
2894
+ } catch (err) {
2895
+ this.logger.warn(
2896
+ { sessionKey, conversationId: reply.conversationId, err: describe4(err), ...this.retry() },
2897
+ "reply verdict not recorded after the turn completed \u2014 the conversation stays unread; the next wake gates it again"
2898
+ );
2899
+ }
2900
+ }
2765
2901
  /**
2766
2902
  * Every pending invite gets one attempt. An invite leaves the pending list
2767
2903
  * only once its turn was admitted (and is then remembered in the ledger);
@@ -2770,6 +2906,15 @@ var AgentInvoker = class {
2770
2906
  */
2771
2907
  async runInviteTurns() {
2772
2908
  const batch = [...this.pendingInvites];
2909
+ if (batch.length > 0) {
2910
+ const readiness = this.readiness();
2911
+ if (!readiness.ready) {
2912
+ const changed = this.unreadyReason !== readiness.reason;
2913
+ this.unreadyReason = readiness.reason;
2914
+ 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");
2915
+ return;
2916
+ }
2917
+ }
2773
2918
  let texts = null;
2774
2919
  let refused = 0;
2775
2920
  let waitingForTexts = 0;
@@ -2901,11 +3046,12 @@ var agentchatGatewayAdapter = {
2901
3046
  accountId: ctx.accountId,
2902
3047
  onWriteError: (err) => ctx.log?.warn?.(`[agentchat:${ctx.accountId}] invite ledger could not be written: ${err instanceof Error ? err.message : String(err)}`)
2903
3048
  });
3049
+ const metrics = createInMemoryMetrics();
2904
3050
  await registerIntegration({
2905
3051
  accountId: ctx.accountId,
2906
3052
  config,
2907
3053
  logger,
2908
- socketOptions: { client },
3054
+ socketOptions: { client, metrics },
2909
3055
  build: (socket) => {
2910
3056
  const invoker = new AgentInvoker({
2911
3057
  accountId: ctx.accountId,
@@ -2913,9 +3059,18 @@ var agentchatGatewayAdapter = {
2913
3059
  client,
2914
3060
  callModel: createRuntimeModelCall({ agentIdOverride, ...gateTimeoutMs !== void 0 ? { timeoutMs: gateTimeoutMs } : {} }),
2915
3061
  startTurn: createRuntimeTurnStarter(),
3062
+ // Gating waits until a turn can have the hosted tools (the MCP
3063
+ // entry in the LIVE config — OpenClaw hot-applies `mcp.*` — and
3064
+ // its key in this process): a connect wake on a cold gateway
3065
+ // otherwise spends a gate call and runs a turn that cannot look.
3066
+ readiness: () => {
3067
+ const live = readLiveConfig(ctx.cfg);
3068
+ return turnReadiness({ cfg: live.cfg, apiBase: config.apiBase, apiKey: config.apiKey, live: live.live });
3069
+ },
2916
3070
  texts,
2917
3071
  invites,
2918
3072
  logger,
3073
+ metrics,
2919
3074
  gateEnabled: readEnv_js.readReplyGateEnabledFromEnv()
2920
3075
  });
2921
3076
  let blocked = false;
@@ -3007,6 +3162,10 @@ async function catchUpInvites(accountId, client, invoker, logger) {
3007
3162
  }
3008
3163
  var PROBE_MIN_MS = 1e3;
3009
3164
  var PROBE_MAX_MS = 1e4;
3165
+ function formatCounts(counts) {
3166
+ const parts = Object.entries(counts).map(([label, n]) => `${label} ${n}`);
3167
+ return parts.length > 0 ? parts.join(", ") : "none";
3168
+ }
3010
3169
  var agentchatStatusAdapter = {
3011
3170
  async probeAccount({ account, timeoutMs, cfg }) {
3012
3171
  if (!account.config) {
@@ -3044,11 +3203,13 @@ var agentchatStatusAdapter = {
3044
3203
  const health = live?.socket.getHealth();
3045
3204
  const counters = live?.invoker?.counters();
3046
3205
  const textsSource = live ? live.texts?.source ?? "missing" : void 0;
3206
+ const socketCounters = live?.metrics?.snapshot?.();
3047
3207
  const integration = {
3048
3208
  mode: readEnv_js.readWakeModeFromEnv().mode,
3049
3209
  ...health ? { state: health.state } : {},
3050
3210
  ...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
3051
- ...textsSource ? { texts: textsSource } : {}
3211
+ ...textsSource ? { texts: textsSource } : {},
3212
+ ...socketCounters ? { socket: socketCounters } : {}
3052
3213
  };
3053
3214
  const refusal = multiAccountRefusal(cfg);
3054
3215
  return {
@@ -3090,6 +3251,12 @@ var agentchatStatusAdapter = {
3090
3251
  text: `integration ${d.state} \u2014 wakes ${d.wakes ?? 0}, cycles ${d.cycles ?? 0}, turns ${d.turns ?? 0}`,
3091
3252
  tone: d.state === "ready" ? "success" : "warn"
3092
3253
  });
3254
+ if (d.socket) {
3255
+ lines.push({
3256
+ text: `socket \u2014 wakes: ${formatCounts(d.socket.wakes)} \xB7 closes: ${formatCounts(d.socket.disconnects)} \xB7 notices: ${formatCounts(d.socket.errors)}`,
3257
+ tone: "muted"
3258
+ });
3259
+ }
3093
3260
  if (d.texts === "missing") {
3094
3261
  lines.push({ text: "served texts not available yet (AgentChat unreachable, nothing cached) \u2014 turns wait for the first copy", tone: "error" });
3095
3262
  } else if (d.texts === "cache") {