@agentchatme/openclaw 0.9.2 → 0.10.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.
@@ -5,15 +5,16 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
  var channelCore = require('openclaw/plugin-sdk/channel-core');
6
6
  var channelPluginCommon = require('openclaw/plugin-sdk/channel-plugin-common');
7
7
  var setup = require('openclaw/plugin-sdk/setup');
8
+ var agentchatme = require('agentchatme');
8
9
  var readEnv_js$1 = require('./credentials/read-env.cjs');
9
10
  var fs = require('fs');
10
11
  var path2 = require('path');
11
12
  var readEnv_js = require('./credentials/read-env.cjs');
12
13
  var openclawLayout_js = require('./openclaw-layout.cjs');
13
14
  var agentsAnchor_js = require('./binding/agents-anchor.cjs');
14
- var agentchatme = require('agentchatme');
15
15
  var zod = require('zod');
16
16
  var pino = require('pino');
17
+ var async_hooks = require('async_hooks');
17
18
 
18
19
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
19
20
 
@@ -52,9 +53,9 @@ function readChannelSection(cfg) {
52
53
  }
53
54
  function readAccountRaw(section, accountId) {
54
55
  if (!section) return void 0;
55
- const { accounts } = section;
56
- if (accounts && typeof accounts === "object" && !Array.isArray(accounts)) {
57
- const entry = accounts[accountId];
56
+ const { accounts: accounts2 } = section;
57
+ if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
58
+ const entry = accounts2[accountId];
58
59
  if (entry && typeof entry === "object") return entry;
59
60
  }
60
61
  if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID) {
@@ -79,8 +80,8 @@ function agentchatEnabledConfigPath(cfg, accountId) {
79
80
  const section = readChannelSection(cfg);
80
81
  const sectionPath = `channels.${AGENTCHAT_CHANNEL_ID}.enabled`;
81
82
  if (!section || section.enabled === false) return sectionPath;
82
- const { accounts } = section;
83
- const entry = accounts && typeof accounts === "object" && !Array.isArray(accounts) ? accounts[accountId] : void 0;
83
+ const { accounts: accounts2 } = section;
84
+ const entry = accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2) ? accounts2[accountId] : void 0;
84
85
  if (entry && typeof entry === "object") return `channels.${AGENTCHAT_CHANNEL_ID}.accounts.${accountId}.enabled`;
85
86
  return sectionPath;
86
87
  }
@@ -90,9 +91,9 @@ function agentchatReenableHint(cfg, accountId) {
90
91
  function listConfiguredAccountIds(cfg) {
91
92
  const section = readChannelSection(cfg);
92
93
  if (!section) return [];
93
- const { accounts } = section;
94
- if (accounts && typeof accounts === "object" && !Array.isArray(accounts)) {
95
- const ids = Object.keys(accounts);
94
+ const { accounts: accounts2 } = section;
95
+ if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
96
+ const ids = Object.keys(accounts2);
96
97
  if (ids.length > 0) return ids;
97
98
  }
98
99
  return typeof section.apiKey === "string" ? [AGENTCHAT_DEFAULT_ACCOUNT_ID] : [];
@@ -121,19 +122,19 @@ function applyAgentchatAccountPatch(cfg, accountId, patch) {
121
122
  if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID && !section.accounts) {
122
123
  Object.assign(section, patch);
123
124
  } else {
124
- const accounts = {
125
+ const accounts2 = {
125
126
  ...section.accounts ?? {}
126
127
  };
127
- const prevAccount = typeof accounts[accountId] === "object" && accounts[accountId] !== null ? accounts[accountId] : {};
128
- accounts[accountId] = { ...prevAccount, ...patch };
129
- section.accounts = accounts;
128
+ const prevAccount = typeof accounts2[accountId] === "object" && accounts2[accountId] !== null ? accounts2[accountId] : {};
129
+ accounts2[accountId] = { ...prevAccount, ...patch };
130
+ section.accounts = accounts2;
130
131
  }
131
132
  channels[AGENTCHAT_CHANNEL_ID] = section;
132
133
  return { ...cfg ?? {}, channels };
133
134
  }
134
135
 
135
136
  // src/version.ts
136
- var PACKAGE_VERSION = "0.9.2";
137
+ var PACKAGE_VERSION = "0.10.1";
137
138
 
138
139
  // src/client-identity.ts
139
140
  var AGENTCHAT_CLIENT_NAME = "openclaw";
@@ -141,10 +142,6 @@ var AGENTCHAT_CLIENT_IDENTITY = {
141
142
  name: AGENTCHAT_CLIENT_NAME,
142
143
  version: PACKAGE_VERSION
143
144
  };
144
- var AGENTCHAT_CLIENT_HEADERS = {
145
- "X-AgentChat-Client": AGENTCHAT_CLIENT_NAME,
146
- "X-AgentChat-Client-Version": PACKAGE_VERSION
147
- };
148
145
 
149
146
  // src/setup-client.ts
150
147
  var DEFAULT_API_BASE = "https://api.agentchat.me";
@@ -153,63 +150,37 @@ async function validateApiKey(apiKey, opts = {}) {
153
150
  if (!apiKey || typeof apiKey !== "string") {
154
151
  return { ok: false, reason: "unauthorized", message: "API key is empty" };
155
152
  }
156
- const base = (opts.apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, "");
157
- const url = `${base}/v1/agents/me`;
158
- const controller = new AbortController();
159
- const fetchImpl = opts.fetch ?? fetch;
160
- const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
161
- const timer = setTimeout(() => controller.abort(), timeoutMs);
162
- let res;
153
+ const client = new agentchatme.AgentChatClient({
154
+ apiKey,
155
+ baseUrl: apiBaseOf(opts.apiBase),
156
+ clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
157
+ timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
158
+ retry: ONE_ATTEMPT,
159
+ ...opts.fetch ? { fetch: opts.fetch } : {}
160
+ });
161
+ let me;
163
162
  try {
164
- res = await fetchImpl(url, {
165
- method: "GET",
166
- headers: {
167
- Authorization: `Bearer ${apiKey}`,
168
- Accept: "application/json",
169
- ...AGENTCHAT_CLIENT_HEADERS
170
- },
171
- signal: controller.signal
172
- });
163
+ me = await client.getMe();
173
164
  } catch (err) {
174
- const message = err instanceof Error ? err.message : String(err);
175
- const unreachable = err instanceof Error && (err.name === "AbortError" || /ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(message));
176
- return {
177
- ok: false,
178
- reason: unreachable ? "unreachable" : "network-error",
179
- message: `agentchat: GET /v1/agents/me failed: ${message}`
180
- };
181
- } finally {
182
- clearTimeout(timer);
183
- }
184
- if (res.status === 401) {
185
- return { ok: false, reason: "unauthorized", status: 401, message: "API key is invalid or revoked" };
186
- }
187
- if (res.status === 403) {
188
- return { ok: false, reason: "forbidden", status: 403, message: "API key lacks permission to read /agents/me" };
189
- }
190
- if (res.status === 410) {
191
- return { ok: false, reason: "deleted", status: 410, message: "Agent account has been deleted" };
192
- }
193
- if (res.status >= 500) {
194
- return { ok: false, reason: "server-error", status: res.status, message: `AgentChat API returned ${res.status}` };
195
- }
196
- if (!res.ok) {
197
- return {
198
- ok: false,
199
- reason: "server-error",
200
- status: res.status,
201
- message: `AgentChat API returned ${res.status}`
202
- };
165
+ const failure = describeFailure(err);
166
+ if (failure.kind === "network") {
167
+ const unreachable = failure.timedOut || /ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(failure.message);
168
+ return {
169
+ ok: false,
170
+ reason: unreachable ? "unreachable" : "network-error",
171
+ message: `agentchat: GET /v1/agents/me failed: ${failure.message}`
172
+ };
173
+ }
174
+ const status = failure.status;
175
+ if (status === 401) return { ok: false, reason: "unauthorized", status, message: "API key is invalid or revoked" };
176
+ if (status === 403) return { ok: false, reason: "forbidden", status, message: "API key lacks permission to read /agents/me" };
177
+ if (status === 410) return { ok: false, reason: "deleted", status, message: "Agent account has been deleted" };
178
+ return { ok: false, reason: "server-error", status, message: `AgentChat API returned ${status}` };
203
179
  }
204
- const body = await res.json().catch(() => null);
180
+ const body = asRecord(me);
205
181
  const email = typeof body?.email === "string" ? body.email : typeof body?.email_masked === "string" ? body.email_masked : null;
206
182
  if (!body || typeof body.handle !== "string" || email === null || typeof body.created_at !== "string") {
207
- return {
208
- ok: false,
209
- reason: "unexpected-shape",
210
- status: res.status,
211
- message: "AgentChat /agents/me returned an unrecognized shape"
212
- };
183
+ return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/me returned an unrecognized shape" };
213
184
  }
214
185
  return {
215
186
  ok: true,
@@ -222,139 +193,122 @@ async function validateApiKey(apiKey, opts = {}) {
222
193
  };
223
194
  }
224
195
  async function registerAgentStart(input, opts = {}) {
225
- const res = await post("/v1/register", input, opts);
226
- if (res.kind === "network") {
227
- return { ok: false, reason: "network-error", message: res.message };
228
- }
229
- if (res.kind === "timeout") {
230
- return { ok: false, reason: "network-error", message: "request timed out" };
231
- }
232
- const body = res.body ?? {};
233
- if (res.status === 200) {
234
- if (typeof body.pending_id !== "string") {
235
- return {
236
- ok: false,
237
- reason: "server-error",
238
- status: 200,
239
- message: "AgentChat /register returned no pending_id"
240
- };
241
- }
242
- return { ok: true, pendingId: body.pending_id };
243
- }
244
- const code = typeof body.code === "string" ? body.code : "";
245
- const message = typeof body.message === "string" ? body.message : `status ${res.status}`;
246
- if (res.status === 400 && code === "INVALID_HANDLE") return { ok: false, reason: "invalid-handle", message, status: 400 };
247
- if (res.status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status: 400 };
248
- if (res.status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status: 409 };
249
- const emailPolicy = res.status === 409 ? classifyEmailPolicyRejection(code) : void 0;
250
- if (emailPolicy) {
251
- return { ok: false, reason: emailPolicy, message, status: 409, limit: readPolicyLimit(body.details) };
252
- }
253
- if (res.status === 429) {
254
- return {
255
- ok: false,
256
- reason: "rate-limited",
257
- message,
258
- status: 429,
259
- retryAfterSeconds: res.retryAfterSeconds
260
- };
261
- }
262
- if (res.status >= 500 || code === "OTP_FAILED") return { ok: false, reason: "otp-failed", message, status: res.status };
263
- return { ok: false, reason: "server-error", status: res.status, message };
196
+ let data;
197
+ try {
198
+ data = await agentchatme.AgentChatClient.register({
199
+ email: input.email,
200
+ handle: input.handle,
201
+ ...input.displayName !== void 0 ? { display_name: input.displayName } : {},
202
+ ...input.description !== void 0 ? { description: input.description } : {},
203
+ baseUrl: apiBaseOf(opts.apiBase),
204
+ clientIdentity: AGENTCHAT_CLIENT_IDENTITY
205
+ });
206
+ } catch (err) {
207
+ const failure = describeFailure(err);
208
+ if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
209
+ const { status, code, message } = failure;
210
+ if (status === 400 && code === "INVALID_HANDLE") return { ok: false, reason: "invalid-handle", message, status };
211
+ if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
212
+ if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
213
+ const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
214
+ if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
215
+ if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
216
+ if (status >= 500 || code === "OTP_FAILED") return { ok: false, reason: "otp-failed", message, status };
217
+ return { ok: false, reason: "server-error", status, message };
218
+ }
219
+ const pendingId = asRecord(data)?.pending_id;
220
+ if (typeof pendingId !== "string") {
221
+ return { ok: false, reason: "server-error", status: 200, message: "AgentChat /register returned no pending_id" };
222
+ }
223
+ return { ok: true, pendingId };
264
224
  }
265
225
  async function registerAgentVerify(input, opts = {}) {
266
- const res = await post("/v1/register/verify", { pending_id: input.pendingId, code: input.code }, opts);
267
- if (res.kind === "network") return { ok: false, reason: "network-error", message: res.message };
268
- if (res.kind === "timeout") return { ok: false, reason: "network-error", message: "request timed out" };
269
- const body = res.body ?? {};
270
- if (res.status === 201) {
271
- const agent = body.agent;
272
- if (typeof body.api_key !== "string" || !agent || typeof agent.handle !== "string" || typeof agent.email !== "string" || typeof agent.created_at !== "string") {
273
- return {
274
- ok: false,
275
- reason: "unexpected-shape",
276
- status: 201,
277
- message: "AgentChat /register/verify returned an unrecognized shape"
278
- };
279
- }
280
- return {
281
- ok: true,
282
- apiKey: body.api_key,
283
- agent: {
284
- handle: agent.handle,
285
- displayName: typeof agent.display_name === "string" ? agent.display_name : null,
286
- email: agent.email,
287
- createdAt: agent.created_at
288
- }
289
- };
290
- }
291
- const code = typeof body.code === "string" ? body.code : "";
292
- const message = typeof body.message === "string" ? body.message : `status ${res.status}`;
293
- if (res.status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status: 400 };
294
- if (res.status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status: 400 };
295
- if (res.status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status: 400 };
296
- if (res.status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status: 409 };
297
- const emailPolicy = res.status === 409 ? classifyEmailPolicyRejection(code) : void 0;
298
- if (emailPolicy) {
299
- return { ok: false, reason: emailPolicy, message, status: 409, limit: readPolicyLimit(body.details) };
300
- }
301
- if (res.status === 429) {
302
- return { ok: false, reason: "rate-limited", message, status: 429, retryAfterSeconds: res.retryAfterSeconds };
226
+ let verified;
227
+ try {
228
+ verified = await agentchatme.AgentChatClient.verify(input.pendingId, input.code, {
229
+ baseUrl: apiBaseOf(opts.apiBase),
230
+ clientIdentity: AGENTCHAT_CLIENT_IDENTITY
231
+ });
232
+ } catch (err) {
233
+ const failure = describeFailure(err);
234
+ if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
235
+ const { status, code, message } = failure;
236
+ if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
237
+ if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
238
+ if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
239
+ if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
240
+ const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
241
+ if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
242
+ if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
243
+ return { ok: false, reason: "server-error", status, message };
244
+ }
245
+ const agent = asRecord(verified.agent);
246
+ if (typeof verified.apiKey !== "string" || !agent || typeof agent.handle !== "string" || typeof agent.email !== "string" || typeof agent.created_at !== "string") {
247
+ return { ok: false, reason: "unexpected-shape", status: 201, message: "AgentChat /register/verify returned an unrecognized shape" };
303
248
  }
304
- return { ok: false, reason: "server-error", status: res.status, message };
249
+ return {
250
+ ok: true,
251
+ apiKey: verified.apiKey,
252
+ agent: {
253
+ handle: agent.handle,
254
+ displayName: typeof agent.display_name === "string" ? agent.display_name : null,
255
+ email: agent.email,
256
+ createdAt: agent.created_at
257
+ }
258
+ };
305
259
  }
306
260
  async function recoverAgentStart(input, opts = {}) {
307
- const res = await post("/v1/agents/recover", { email: input.email, handle: input.handle }, opts);
308
- if (res.kind === "network") return { ok: false, reason: "network-error", message: res.message };
309
- if (res.kind === "timeout") return { ok: false, reason: "network-error", message: "request timed out" };
310
- const body = res.body ?? {};
311
- const message = typeof body.message === "string" ? body.message : `status ${res.status}`;
312
- if (res.status === 200) {
313
- if (typeof body.pending_id !== "string") {
314
- return {
315
- ok: false,
316
- reason: "unexpected-shape",
317
- status: 200,
318
- message: "AgentChat did not start a recovery (no pending_id in the response). Check that the email is the one this agent registered with."
319
- };
320
- }
321
- return { ok: true, pendingId: body.pending_id, message };
322
- }
323
- const code = typeof body.code === "string" ? body.code : "";
324
- if (res.status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status: 400 };
325
- if (res.status === 429) {
326
- return { ok: false, reason: "rate-limited", message, status: 429, retryAfterSeconds: res.retryAfterSeconds };
261
+ let data;
262
+ try {
263
+ data = await agentchatme.AgentChatClient.recover(input.email, {
264
+ handle: input.handle,
265
+ baseUrl: apiBaseOf(opts.apiBase),
266
+ clientIdentity: AGENTCHAT_CLIENT_IDENTITY
267
+ });
268
+ } catch (err) {
269
+ const failure = describeFailure(err);
270
+ if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
271
+ const { status, code, message: message2 } = failure;
272
+ if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message: message2, status };
273
+ if (status === 429) return { ok: false, reason: "rate-limited", message: message2, status, retryAfterSeconds: failure.retryAfterSeconds };
274
+ return { ok: false, reason: "server-error", status, message: message2 };
275
+ }
276
+ const body = asRecord(data);
277
+ const message = typeof body?.message === "string" ? body.message : "status 200";
278
+ if (typeof body?.pending_id !== "string") {
279
+ return {
280
+ ok: false,
281
+ reason: "unexpected-shape",
282
+ status: 200,
283
+ message: "AgentChat did not start a recovery (no pending_id in the response). Check that the email is the one this agent registered with."
284
+ };
327
285
  }
328
- return { ok: false, reason: "server-error", status: res.status, message };
286
+ return { ok: true, pendingId: body.pending_id, message };
329
287
  }
330
288
  async function recoverAgentVerify(input, opts = {}) {
331
- const res = await post("/v1/agents/recover/verify", { pending_id: input.pendingId, code: input.code }, opts);
332
- if (res.kind === "network") return { ok: false, reason: "network-error", message: res.message };
333
- if (res.kind === "timeout") return { ok: false, reason: "network-error", message: "request timed out" };
334
- const body = res.body ?? {};
335
- if (res.status === 200) {
336
- if (typeof body.api_key !== "string" || typeof body.handle !== "string") {
337
- return {
338
- ok: false,
339
- reason: "unexpected-shape",
340
- status: 200,
341
- message: "AgentChat /agents/recover/verify returned an unrecognized shape"
342
- };
289
+ let recovered;
290
+ try {
291
+ recovered = await agentchatme.AgentChatClient.recoverVerify(input.pendingId, input.code, {
292
+ baseUrl: apiBaseOf(opts.apiBase),
293
+ clientIdentity: AGENTCHAT_CLIENT_IDENTITY
294
+ });
295
+ } catch (err) {
296
+ const failure = describeFailure(err);
297
+ if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
298
+ const { status, code, message } = failure;
299
+ if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
300
+ if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
301
+ if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
302
+ if (status === 409 && code === "HANDLE_REQUIRED") {
303
+ return { ok: false, reason: "handle-required", message, status, handles: readHandleList(failure.details) };
343
304
  }
344
- return { ok: true, apiKey: body.api_key, handle: body.handle };
305
+ if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
306
+ return { ok: false, reason: "server-error", status, message };
345
307
  }
346
- const code = typeof body.code === "string" ? body.code : "";
347
- const message = typeof body.message === "string" ? body.message : `status ${res.status}`;
348
- if (res.status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status: 400 };
349
- if (res.status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status: 400 };
350
- if (res.status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status: 400 };
351
- if (res.status === 409 && code === "HANDLE_REQUIRED") {
352
- return { ok: false, reason: "handle-required", message, status: 409, handles: readHandleList(body.details) };
308
+ if (typeof recovered.apiKey !== "string" || typeof recovered.handle !== "string") {
309
+ return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/recover/verify returned an unrecognized shape" };
353
310
  }
354
- if (res.status === 429) {
355
- return { ok: false, reason: "rate-limited", message, status: 429, retryAfterSeconds: res.retryAfterSeconds };
356
- }
357
- return { ok: false, reason: "server-error", status: res.status, message };
311
+ return { ok: true, apiKey: recovered.apiKey, handle: recovered.handle };
358
312
  }
359
313
  function classifyEmailPolicyRejection(code) {
360
314
  if (code === "EMAIL_LIMIT_REACHED" || code === "EMAIL_TAKEN") return "email-limit-reached";
@@ -372,39 +326,34 @@ function readHandleList(details) {
372
326
  if (!Array.isArray(handles)) return [];
373
327
  return handles.filter((h) => typeof h === "string" && h.length > 0);
374
328
  }
375
- async function post(path5, body, opts) {
376
- const base = (opts.apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, "");
377
- const url = `${base}${path5}`;
378
- const controller = new AbortController();
379
- const fetchImpl = opts.fetch ?? fetch;
380
- const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
381
- const timer = setTimeout(() => controller.abort(), timeoutMs);
382
- try {
383
- const res = await fetchImpl(url, {
384
- method: "POST",
385
- headers: {
386
- "content-type": "application/json",
387
- accept: "application/json",
388
- ...AGENTCHAT_CLIENT_HEADERS
389
- },
390
- body: JSON.stringify(body),
391
- signal: controller.signal
392
- });
393
- const parsed = await res.json().catch(() => null);
394
- const retryAfterHeader = res.headers.get("retry-after");
395
- const retryAfterSeconds = retryAfterHeader ? Number(retryAfterHeader) : void 0;
329
+ var ONE_ATTEMPT = { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 };
330
+ function apiBaseOf(apiBase) {
331
+ return (apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, "");
332
+ }
333
+ function describeFailure(err) {
334
+ if (err instanceof agentchatme.AgentChatError) {
335
+ const raw = asRecord(asRecord(err.details)?.body);
336
+ const code = typeof raw?.code === "string" ? raw.code : String(err.code ?? "");
337
+ const message2 = raw ? typeof raw.message === "string" ? raw.message : `status ${err.status}` : err.message || `status ${err.status}`;
338
+ const retryAfterMs = err instanceof agentchatme.RateLimitedError ? err.retryAfterMs : null;
396
339
  return {
397
340
  kind: "http",
398
- status: res.status,
399
- body: parsed,
400
- retryAfterSeconds: Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : void 0
341
+ status: err.status,
342
+ code,
343
+ message: message2,
344
+ details: raw ? raw.details : err.details,
345
+ ...typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) ? { retryAfterSeconds: Math.ceil(retryAfterMs / 1e3) } : {}
401
346
  };
402
- } catch (err) {
403
- if (err instanceof Error && err.name === "AbortError") return { kind: "timeout" };
404
- return { kind: "network", message: err instanceof Error ? err.message : String(err) };
405
- } finally {
406
- clearTimeout(timer);
407
347
  }
348
+ const message = err instanceof Error ? err.message : String(err);
349
+ const timedOut = err instanceof Error && err.name === "AbortError" || /timed out|abort/i.test(message);
350
+ return { kind: "network", message, timedOut };
351
+ }
352
+ function networkMessage(failure) {
353
+ return failure.timedOut ? "request timed out" : failure.message;
354
+ }
355
+ function asRecord(value) {
356
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
408
357
  }
409
358
 
410
359
  // src/integration/turn.ts
@@ -414,34 +363,20 @@ var MCP_TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
414
363
  function mcpToolName(tool) {
415
364
  return `${MCP_TOOL_PREFIX}${tool}`;
416
365
  }
417
- var DECIDE_TOOL = mcpToolName("agentchat_decide");
418
- var GET_CONVERSATION_TOOL = mcpToolName("agentchat_get_conversation");
419
366
  var OPENCLAW_TOOL_NAMER = (tool) => tool.startsWith(MCP_TOOL_PREFIX) ? tool : mcpToolName(tool);
420
367
  var HOSTED_TOOL_TOKEN = /\bagentchat_(?!_)[a-z0-9_]+\b/g;
421
368
  function spellToolsForOpenClaw(text) {
422
369
  return text.replace(HOSTED_TOOL_TOKEN, (token) => OPENCLAW_TOOL_NAMER(token));
423
370
  }
424
- function wakeTurnPrompt(texts, conversationId) {
425
- const instruction = texts.wake_instruction.trim();
426
- if (!conversationId) return instruction;
427
- return `${instruction}
428
-
429
- ${conversationLine(conversationId)}`;
430
- }
431
- function conversationLine(conversationId) {
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 unless you record one yourself with ${DECIDE_TOOL} (reply after your answer is sent, or dismiss if you read and choose not to answer) \u2014 open it with ${GET_CONVERSATION_TOOL} and reply.`;
433
- }
434
- function inviteTurnPrompt(texts) {
435
- return texts.invite_prompt.trim();
436
- }
437
371
  function wakeSessionKey(agentId, now = Date.now(), nonce = randomNonce()) {
438
372
  return `agent:${agentId}:subagent:agentchat-wake-${utcStamp(now)}-${nonce}`;
439
373
  }
440
- function inviteSessionKey(agentId, inviteId) {
441
- return `agent:${agentId}:subagent:agentchat-invite-${sanitizeKeyPart(inviteId)}`;
374
+ function inviteSessionKey(agentId, inviteId, now = Date.now(), nonce = randomNonce()) {
375
+ return `agent:${agentId}:subagent:agentchat-invite-${sanitizeKeyPart(inviteId)}-${utcStamp(now)}-${nonce}`;
442
376
  }
443
- function integrationLane(accountId) {
444
- return `agentchat-integration:${sanitizeKeyPart(accountId)}`;
377
+ function integrationLane(accountId, generation2 = 0) {
378
+ const base = `agentchat-integration:${sanitizeKeyPart(accountId)}`;
379
+ return generation2 > 0 ? `${base}:${generation2}` : base;
445
380
  }
446
381
  function utcStamp(ms) {
447
382
  return new Date(ms).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
@@ -458,15 +393,21 @@ function sanitizeKeyPart(value) {
458
393
  var MCP_PATH = "/mcp";
459
394
  var AUTH_HEADER_TEMPLATE = `Bearer \${${readEnv_js.API_KEY_ENV}}`;
460
395
  var DEFAULT_API_BASE2 = "https://api.agentchat.me";
461
- var MCP_PROTOCOL_VERSION = "2025-06-18";
462
396
  function hostedMcpUrl(apiBase = DEFAULT_API_BASE2) {
463
397
  return `${apiBase.replace(/\/+$/, "")}${MCP_PATH}`;
464
398
  }
399
+ var CLIENT_HEADER = "X-AgentChat-Client";
400
+ function clientIdentityHeaders() {
401
+ return { [CLIENT_HEADER]: AGENTCHAT_CLIENT_NAME };
402
+ }
403
+ function clientIdentityText() {
404
+ return `${CLIENT_HEADER}: ${AGENTCHAT_CLIENT_NAME}`;
405
+ }
465
406
  function hostedMcpServerEntry(apiBase = DEFAULT_API_BASE2) {
466
407
  return {
467
408
  url: hostedMcpUrl(apiBase),
468
409
  transport: "streamable-http",
469
- headers: { Authorization: AUTH_HEADER_TEMPLATE }
410
+ headers: { Authorization: AUTH_HEADER_TEMPLATE, ...clientIdentityHeaders() }
470
411
  };
471
412
  }
472
413
  function describeMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
@@ -485,23 +426,99 @@ function pointsAtUs(entry, apiBase, apiKey) {
485
426
  const headers = entry.headers;
486
427
  if (headers === void 0) return true;
487
428
  if (!headers || typeof headers !== "object" || Array.isArray(headers)) return false;
488
- const auth = headers.Authorization ?? headers.authorization;
429
+ const auths = headerValues(headers, "Authorization");
430
+ if (auths.length > 1) return false;
431
+ const auth = auths[0];
489
432
  if (auth === void 0) return true;
490
433
  if (typeof auth !== "string") return false;
491
434
  if (auth === AUTH_HEADER_TEMPLATE || auth.includes(`\${${readEnv_js.API_KEY_ENV}}`)) return true;
492
435
  return apiKey !== void 0 && apiKey.length > 0 && auth.trim() === `Bearer ${apiKey}`;
493
436
  }
437
+ function describeMcpIdentity(cfg) {
438
+ const entry = agentchatEntry(cfg);
439
+ const headers = entry && isRecord(entry.headers) ? entry.headers : void 0;
440
+ if (!headers) return "missing";
441
+ const want = clientIdentityHeaders();
442
+ const clients = headerValues(headers, CLIENT_HEADER);
443
+ const client = clients[0];
444
+ return clients.length === 1 && typeof client === "string" && client.trim().toLowerCase() === want[CLIENT_HEADER] ? "current" : "missing";
445
+ }
494
446
  function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
495
447
  const state = describeMcpEntry(cfg, apiBase, apiKey);
496
448
  const base = cfg ?? {};
497
- if (state === "ours") return { cfg: base, outcome: "present" };
498
449
  if (state === "user_managed") return { cfg: base, outcome: "user_managed" };
499
450
  if (state === "disabled") return { cfg: base, outcome: "disabled" };
451
+ if (state === "ours" && describeMcpIdentity(base) === "current") return { cfg: base, outcome: "present" };
500
452
  const mcp = { ...base.mcp ?? {} };
501
453
  const servers = { ...mcp.servers ?? {} };
502
- servers[MCP_SERVER_NAME] = hostedMcpServerEntry(apiBase);
454
+ const existing = servers[MCP_SERVER_NAME];
455
+ servers[MCP_SERVER_NAME] = state === "ours" && isRecord(existing) ? upgradedHostedMcpEntry(existing, apiBase) : hostedMcpServerEntry(apiBase);
503
456
  mcp.servers = servers;
504
- return { cfg: { ...base, mcp }, outcome: "added" };
457
+ return { cfg: { ...base, mcp }, outcome: state === "ours" ? "updated" : "added" };
458
+ }
459
+ function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE2) {
460
+ const headers = isRecord(entry.headers) ? entry.headers : {};
461
+ const kept = Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== CLIENT_HEADER.toLowerCase()));
462
+ return {
463
+ ...entry,
464
+ url: hostedMcpUrl(apiBase),
465
+ transport: "streamable-http",
466
+ headers: { ...kept, ...clientIdentityHeaders() }
467
+ };
468
+ }
469
+ function upgradeHostedMcpEntryInPlace(draft, apiBase = DEFAULT_API_BASE2, apiKey) {
470
+ if (describeMcpEntry(draft, apiBase, apiKey) !== "ours" || describeMcpIdentity(draft) === "current") return false;
471
+ const servers = draft.mcp.servers;
472
+ const existing = servers[MCP_SERVER_NAME];
473
+ if (!isRecord(existing)) return false;
474
+ servers[MCP_SERVER_NAME] = upgradedHostedMcpEntry(existing, apiBase);
475
+ return true;
476
+ }
477
+ var NoChange = class extends Error {
478
+ constructor(outcome) {
479
+ super(`no change (${outcome})`);
480
+ this.outcome = outcome;
481
+ }
482
+ outcome;
483
+ };
484
+ var NIX_MODE_ERROR_CODE = "OPENCLAW_NIX_MODE_CONFIG_IMMUTABLE";
485
+ async function refreshHostedMcpEntry(params) {
486
+ const apiBase = params.apiBase ?? DEFAULT_API_BASE2;
487
+ if (describeMcpEntry(params.liveCfg, apiBase, params.apiKey) !== "ours") return { outcome: "not_ours" };
488
+ if (describeMcpIdentity(params.liveCfg) === "current") return { outcome: "current" };
489
+ const mutate = params.config?.mutateConfigFile;
490
+ if (typeof mutate !== "function") return { outcome: "unsupported" };
491
+ try {
492
+ await mutate.call(params.config, {
493
+ afterWrite: { mode: "auto" },
494
+ mutate: ((draft) => {
495
+ if (describeMcpEntry(draft, apiBase, params.apiKey) !== "ours") throw new NoChange("not_ours");
496
+ if (!upgradeHostedMcpEntryInPlace(draft, apiBase, params.apiKey)) throw new NoChange("current");
497
+ })
498
+ });
499
+ return { outcome: "updated" };
500
+ } catch (err) {
501
+ if (err instanceof NoChange) return { outcome: err.outcome };
502
+ const code = err?.code;
503
+ return {
504
+ outcome: "failed",
505
+ error: err instanceof Error ? err.message : String(err),
506
+ ...typeof code === "string" ? { code } : {}
507
+ };
508
+ }
509
+ }
510
+ function isRecord(value) {
511
+ return value !== null && typeof value === "object" && !Array.isArray(value);
512
+ }
513
+ function agentchatEntry(cfg) {
514
+ const servers = cfg?.mcp?.servers;
515
+ if (!isRecord(servers)) return void 0;
516
+ const entry = servers[MCP_SERVER_NAME];
517
+ return isRecord(entry) ? entry : void 0;
518
+ }
519
+ function headerValues(headers, name) {
520
+ const wanted = name.toLowerCase();
521
+ return Object.entries(headers).filter(([key]) => key.toLowerCase() === wanted).map(([, value]) => value);
505
522
  }
506
523
  function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
507
524
  if (describeMcpEntry(cfg, apiBase, apiKey) !== "ours") return { cfg, removed: false };
@@ -512,67 +529,24 @@ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
512
529
  return { cfg: { ...cfg, mcp }, removed: true };
513
530
  }
514
531
  async function probeHostedMcp(params) {
515
- const fetchImpl = params.fetch ?? fetch;
516
- const controller = new AbortController();
517
- const timer = setTimeout(() => controller.abort(), params.timeoutMs ?? 1e4);
518
- try {
519
- const res = await fetchImpl(hostedMcpUrl(params.apiBase ?? DEFAULT_API_BASE2), {
520
- method: "POST",
521
- headers: {
522
- authorization: `Bearer ${params.apiKey}`,
523
- "content-type": "application/json",
524
- accept: "application/json, text/event-stream",
525
- ...AGENTCHAT_CLIENT_HEADERS
526
- },
527
- body: JSON.stringify({
528
- jsonrpc: "2.0",
529
- id: 1,
530
- method: "initialize",
531
- params: {
532
- protocolVersion: MCP_PROTOCOL_VERSION,
533
- capabilities: {},
534
- clientInfo: { name: "@agentchatme/openclaw doctor", version: "0" }
535
- }
536
- }),
537
- signal: controller.signal
538
- });
539
- if (!res.ok) {
540
- return { ok: false, status: res.status, error: res.status === 401 ? "the key does not authenticate against the hosted MCP server" : `HTTP ${res.status}` };
541
- }
542
- const text = await res.text();
543
- const result = readInitializeResult(text);
544
- if (!result) return { ok: false, status: res.status, error: "no initialize result in the answer" };
545
- const serverInfo = result.serverInfo ?? {};
546
- return {
547
- ok: true,
548
- status: res.status,
549
- serverName: typeof serverInfo.name === "string" ? serverInfo.name : void 0,
550
- serverVersion: typeof serverInfo.version === "string" ? serverInfo.version : void 0,
551
- protocolVersion: typeof result.protocolVersion === "string" ? result.protocolVersion : void 0,
552
- hasInstructions: typeof result.instructions === "string" && result.instructions.trim().length > 0
553
- };
554
- } catch (err) {
555
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
556
- } finally {
557
- clearTimeout(timer);
558
- }
559
- }
560
- function readInitializeResult(text) {
561
- const candidates = [];
562
- const trimmed = text.trim();
563
- if (trimmed.startsWith("{")) candidates.push(trimmed);
564
- for (const line of text.split(/\r?\n/)) {
565
- if (line.startsWith("data:")) candidates.push(line.slice(5).trim());
566
- }
567
- for (const candidate of candidates) {
568
- try {
569
- const parsed = JSON.parse(candidate);
570
- const result = parsed.result;
571
- if (result && typeof result === "object" && !Array.isArray(result)) return result;
572
- } catch {
573
- }
574
- }
575
- return null;
532
+ const result = await agentchatme.integration.probeHostedTools({
533
+ apiBase: params.apiBase ?? DEFAULT_API_BASE2,
534
+ apiKey: params.apiKey,
535
+ clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
536
+ ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
537
+ ...params.fetch ? { fetch: params.fetch } : {}
538
+ });
539
+ const missing = result.missing ?? [];
540
+ return {
541
+ ok: result.ok,
542
+ ...result.status !== void 0 ? { status: result.status } : {},
543
+ ...result.serverName ? { serverName: result.serverName } : {},
544
+ ...result.serverVersion ? { serverVersion: result.serverVersion } : {},
545
+ ...result.protocolVersion ? { protocolVersion: result.protocolVersion } : {},
546
+ ...result.tools ? { tools: result.tools } : {},
547
+ ...missing.length > 0 ? { missing } : {},
548
+ ...result.error ? { error: result.error } : !result.ok && missing.length > 0 ? { error: `the server lists no ${missing.join(", ")} for this key` } : {}
549
+ };
576
550
  }
577
551
 
578
552
  // src/integration/runtime-holder.ts
@@ -592,11 +566,137 @@ function setPluginRuntime(runtime) {
592
566
  function getPluginRuntime() {
593
567
  return current;
594
568
  }
569
+
570
+ // src/integration/run.ts
571
+ var DEFAULT_RUN_WAIT_CHUNK_MS = 5 * 6e4;
572
+ var RUN_WAIT_RETRY_MS = [1e3, 5e3, 15e3, 3e4, 6e4];
573
+ var MIN_WAIT_SPACING_MS = 1e3;
574
+ var TRANSCRIPT_READ_LIMIT = 200;
575
+ var METADATA_KEYS = ["endedAt", "stopReason", "livenessState", "pendingError", "timeoutPhase", "startedAt", "providerStarted"];
576
+ function runEndOf(wait, timing) {
577
+ const status = wait?.status;
578
+ const error = nonEmpty(wait?.error);
579
+ if (status === "ok") return { ended: true, status: "ok" };
580
+ if (status === "error") {
581
+ if (error && error.trim().toLowerCase() === "completed") return { ended: true, status: "ok" };
582
+ return { ended: true, status: "error", ...error ? { error } : {} };
583
+ }
584
+ if (status !== "timeout") {
585
+ return { ended: false };
586
+ }
587
+ const ended = { ended: true, status: "timeout", ...error ? { error } : {} };
588
+ const hasMetadata = wait !== null && wait !== void 0 && METADATA_KEYS.some((key) => key in wait);
589
+ if (!hasMetadata) {
590
+ return timing.elapsedMs < timing.requestedMs / 2 ? ended : { ended: false };
591
+ }
592
+ if (wait.pendingError === true) return { ended: false };
593
+ if (typeof wait.endedAt === "number" || nonEmpty(wait.stopReason) || nonEmpty(wait.livenessState)) return ended;
594
+ if (isHardTimeout(wait)) return ended;
595
+ return error ? ended : { ended: false };
596
+ }
597
+ var HARD_TIMEOUT_PHASES = /* @__PURE__ */ new Set(["preflight", "provider", "tool_execution", "post_turn"]);
598
+ function isHardTimeout(wait) {
599
+ const phase = typeof wait.timeoutPhase === "string" ? wait.timeoutPhase.trim() : "";
600
+ if (HARD_TIMEOUT_PHASES.has(phase)) return true;
601
+ return wait.status === "timeout" && wait.providerStarted === true && nonEmpty(wait.stopReason) !== "restart";
602
+ }
603
+ async function watchRunUntilEnded(options) {
604
+ const chunkMs = options.chunkMs ?? DEFAULT_RUN_WAIT_CHUNK_MS;
605
+ const retryMs = options.retryMs ?? RUN_WAIT_RETRY_MS;
606
+ const now = options.now ?? Date.now;
607
+ const sleep = options.sleep ?? defaultSleep;
608
+ const started = now();
609
+ let failures = 0;
610
+ for (; ; ) {
611
+ const runtime = options.runtime();
612
+ if (!runtime) return { ended: false, reason: "gone", elapsedMs: now() - started };
613
+ const waitStarted = now();
614
+ let observation;
615
+ try {
616
+ observation = await runtime.subagent.waitForRun({ runId: options.runId, timeoutMs: chunkMs });
617
+ } catch (err) {
618
+ const message = describe(err);
619
+ const delay = retryMs[Math.min(failures, retryMs.length - 1)] ?? 6e4;
620
+ failures += 1;
621
+ options.onWaitError?.(message, failures, delay);
622
+ await sleep(delay);
623
+ continue;
624
+ }
625
+ failures = 0;
626
+ const elapsedMs = now() - waitStarted;
627
+ const end = runEndOf(observation, { requestedMs: chunkMs, elapsedMs });
628
+ if (end.ended) return { ...end, elapsedMs: now() - started };
629
+ options.onStillRunning?.(now() - started);
630
+ if (elapsedMs < MIN_WAIT_SPACING_MS) await sleep(MIN_WAIT_SPACING_MS - elapsedMs);
631
+ }
632
+ }
633
+ function countAgentChatCalls(messages, runId) {
634
+ if (messages.length === 0) return null;
635
+ let recognised = false;
636
+ let made = 0;
637
+ let failed = 0;
638
+ for (const row of messages) {
639
+ const message = unwrapMessage(row);
640
+ if (!message) continue;
641
+ const role = message.role;
642
+ if (role === "assistant" || role === "user") recognised = true;
643
+ if (role !== "toolResult" && role !== "tool") continue;
644
+ recognised = true;
645
+ const meta = asRecord2(message.__openclaw);
646
+ if (runId && typeof meta?.runId === "string" && meta.runId !== runId) continue;
647
+ if (!isAgentChatToolResult(message)) continue;
648
+ made += 1;
649
+ if (message.isError === true) failed += 1;
650
+ }
651
+ return recognised ? { made, failed } : null;
652
+ }
653
+ async function readAgentChatCalls(runtime, sessionKey, runId) {
654
+ if (!runtime || typeof runtime.subagent?.getSessionMessages !== "function") return null;
655
+ try {
656
+ const result = await runtime.subagent.getSessionMessages({ sessionKey, limit: TRANSCRIPT_READ_LIMIT });
657
+ const messages = result?.messages;
658
+ return Array.isArray(messages) ? countAgentChatCalls(messages, runId) : null;
659
+ } catch {
660
+ return null;
661
+ }
662
+ }
663
+ var TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
664
+ function isAgentChatToolResult(message) {
665
+ const toolName = typeof message.toolName === "string" ? message.toolName : typeof message.name === "string" ? message.name : "";
666
+ if (toolName.startsWith(TOOL_PREFIX)) return true;
667
+ const tool = asRecord2(asRecord2(message.details)?.tool);
668
+ if (!tool) return false;
669
+ if (typeof tool.name === "string" && tool.name.startsWith(TOOL_PREFIX)) return true;
670
+ if (tool.sourceName === MCP_SERVER_NAME) return true;
671
+ const mcp = asRecord2(tool.mcp);
672
+ return mcp?.serverName === MCP_SERVER_NAME;
673
+ }
674
+ function unwrapMessage(row) {
675
+ const record = asRecord2(row);
676
+ if (!record) return null;
677
+ if (typeof record.role === "string") return record;
678
+ const inner = asRecord2(record.message);
679
+ return inner && typeof inner.role === "string" ? inner : null;
680
+ }
681
+ function asRecord2(value) {
682
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
683
+ }
684
+ function nonEmpty(value) {
685
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
686
+ }
687
+ function describe(err) {
688
+ return err instanceof Error ? err.message : String(err);
689
+ }
690
+ function defaultSleep(ms) {
691
+ return new Promise((resolve) => {
692
+ const timer = setTimeout(resolve, ms);
693
+ timer.unref?.();
694
+ });
695
+ }
595
696
  var DEFAULT_AGENT_ID = "main";
596
697
  var GATE_TEMPERATURE = 0;
597
698
  var DEFAULT_GATE_MAX_TOKENS = 2048;
598
699
  var DEFAULT_GATE_TIMEOUT_MS = 2e4;
599
- var DEFAULT_TURN_WAIT_MS = 15 * 6e4;
600
700
  var RuntimeUnavailableError = class extends Error {
601
701
  constructor(what) {
602
702
  super(`OpenClaw plugin runtime unavailable \u2014 ${what} needs setRuntime(...) from defineChannelPluginEntry`);
@@ -621,16 +721,21 @@ function createRuntimeModelCall(params) {
621
721
  const getRuntime = params.runtime ?? getPluginRuntime;
622
722
  const maxTokens = params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS;
623
723
  const timeoutMs = params.timeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
624
- return async (prompt) => {
724
+ return async (prompt, options) => {
625
725
  const runtime = getRuntime();
626
726
  if (!runtime) throw new RuntimeUnavailableError("the gate call");
727
+ const signals = [
728
+ ...Number.isFinite(timeoutMs) && timeoutMs > 0 ? [AbortSignal.timeout(timeoutMs)] : [],
729
+ ...options?.signal ? [options.signal] : []
730
+ ];
731
+ const signal = signals.length === 0 ? void 0 : signals.length === 1 ? signals[0] : AbortSignal.any(signals);
627
732
  const result = await runtime.llm.complete({
628
733
  messages: [{ role: "user", content: prompt }],
629
734
  maxTokens,
630
735
  temperature: GATE_TEMPERATURE,
631
736
  ...params.agentIdOverride ? { agentId: params.agentIdOverride } : {},
632
737
  purpose: "AgentChat reply gate: the server's question about the server's cards (tool-free triage)",
633
- ...Number.isFinite(timeoutMs) && timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}
738
+ ...signal ? { signal } : {}
634
739
  });
635
740
  return typeof result?.text === "string" ? result.text : "";
636
741
  };
@@ -660,10 +765,14 @@ function resolveGateAgent(params) {
660
765
  return { agentId: routed, agentIdOverride: routed === (ambient ?? routed) ? void 0 : routed };
661
766
  }
662
767
  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 {
768
+ const config = runtime()?.config;
769
+ for (const read of [config?.current, config?.loadConfig]) {
770
+ if (typeof read !== "function") continue;
771
+ try {
772
+ const loaded = read.call(config);
773
+ if (loaded && typeof loaded === "object") return { cfg: loaded, live: true };
774
+ } catch {
775
+ }
667
776
  }
668
777
  return { cfg: fallback, live: false };
669
778
  }
@@ -691,11 +800,11 @@ function turnReadiness(params) {
691
800
  }
692
801
  function createRuntimeTurnStarter(params = {}) {
693
802
  const getRuntime = params.runtime ?? getPluginRuntime;
694
- const waitMs = params.waitMs ?? DEFAULT_TURN_WAIT_MS;
695
803
  return async (request) => {
696
804
  const runtime = getRuntime();
697
805
  if (!runtime) return { ran: false, error: new RuntimeUnavailableError("the agent turn").message };
698
806
  let runId;
807
+ let sessionKey = request.sessionKey;
699
808
  try {
700
809
  const admitted = await runtime.subagent.run({
701
810
  sessionKey: request.sessionKey,
@@ -704,15 +813,46 @@ function createRuntimeTurnStarter(params = {}) {
704
813
  deliver: false
705
814
  });
706
815
  runId = admitted.runId;
816
+ const accepted = admitted.sessionKey;
817
+ if (typeof accepted === "string" && accepted.trim().length > 0) sessionKey = accepted.trim();
707
818
  } catch (err) {
708
819
  return { ran: false, error: err instanceof Error ? err.message : String(err) };
709
820
  }
710
- const done = runtime.subagent.waitForRun({ runId, timeoutMs: waitMs }).then(
711
- (waited) => ({ ran: true, runId, status: waited.status, ...waited.error ? { error: waited.error } : {} }),
712
- // The run was admitted; only the wait failed. The turn is OpenClaw's now.
713
- (err) => ({ ran: true, runId, status: "unknown", error: err instanceof Error ? err.message : String(err) })
714
- );
715
- return { ran: true, runId, done };
821
+ const done = watchRunUntilEnded({
822
+ runtime: getRuntime,
823
+ runId,
824
+ ...params.waitChunkMs !== void 0 ? { chunkMs: params.waitChunkMs } : {},
825
+ ...params.onStillRunning ? { onStillRunning: (elapsedMs) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {},
826
+ ...params.onWaitError ? { onWaitError: (error, attempt, retryInMs) => params.onWaitError?.({ runId, sessionKey, error, attempt, retryInMs }) } : {},
827
+ ...params.now ? { now: params.now } : {},
828
+ ...params.sleep ? { sleep: params.sleep } : {}
829
+ }).then(async (watched) => {
830
+ if (!watched.ended) return { ran: true, runId, status: "gone", elapsedMs: watched.elapsedMs };
831
+ const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId);
832
+ return {
833
+ ran: true,
834
+ runId,
835
+ status: watched.status,
836
+ ...watched.error ? { error: watched.error } : {},
837
+ agentchatCalls,
838
+ elapsedMs: watched.elapsedMs
839
+ };
840
+ });
841
+ return { ran: true, runId, sessionKey, done };
842
+ };
843
+ }
844
+ function createRunWatcher(params = {}) {
845
+ const getRuntime = params.runtime ?? getPluginRuntime;
846
+ return async ({ runId, sessionKey }) => {
847
+ const watched = await watchRunUntilEnded({
848
+ runtime: getRuntime,
849
+ runId,
850
+ ...params.waitChunkMs !== void 0 ? { chunkMs: params.waitChunkMs } : {},
851
+ ...params.onStillRunning ? { onStillRunning: (elapsedMs) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {}
852
+ });
853
+ if (!watched.ended) return null;
854
+ const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId);
855
+ return { ran: true, runId, status: watched.status, ...watched.error ? { error: watched.error } : {}, agentchatCalls, elapsedMs: watched.elapsedMs };
716
856
  };
717
857
  }
718
858
  var HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
@@ -801,6 +941,7 @@ function applyIntegrationConfig(cfg, params) {
801
941
  const mcp = withHostedMcpEntry(next, params.apiBase, params.apiKey);
802
942
  next = mcp.cfg;
803
943
  if (mcp.outcome === "added") changes.push(`mcp.servers.agentchat \u2192 ${hostedMcpUrl(params.apiBase)} (bearer template on ${readEnv_js.API_KEY_ENV})`);
944
+ if (mcp.outcome === "updated") changes.push(`mcp.servers.agentchat names this client (${clientIdentityText()})`);
804
945
  const bound = openclawLayout_js.resolveBoundAgentId(next, AGENTCHAT_CHANNEL_ID, params.accountId);
805
946
  const ambient = openclawLayout_js.resolveOpenClawDefaultAgentId(next);
806
947
  if (bound && bound !== (ambient ?? bound)) {
@@ -851,7 +992,7 @@ function restoreIdentityLine(cfg, accountId, handle, identityLine) {
851
992
  const written = agentsAnchor_js.writeAgentsAnchor({ cfg, handle: bare, text: identityLine, agentId });
852
993
  return { outcome: "placed", path: written.path };
853
994
  } catch (err) {
854
- return { outcome: "failed", path: filePath, detail: describe(err) };
995
+ return { outcome: "failed", path: filePath, detail: describe2(err) };
855
996
  }
856
997
  }
857
998
  function refreshIdentityLine(cfg, accountId, handle, identityLine) {
@@ -863,7 +1004,7 @@ function refreshIdentityLine(cfg, accountId, handle, identityLine) {
863
1004
  const written = agentsAnchor_js.writeAgentsAnchor({ cfg, handle, text: identityLine, agentId });
864
1005
  return { outcome: "updated", path: written.path };
865
1006
  } catch (err) {
866
- return { outcome: "failed", path: agentsAnchor_js.agentsAnchorPath(cfg, agentId), detail: describe(err) };
1007
+ return { outcome: "failed", path: agentsAnchor_js.agentsAnchorPath(cfg, agentId), detail: describe2(err) };
867
1008
  }
868
1009
  }
869
1010
  function placeIntegration(params) {
@@ -877,7 +1018,7 @@ function placeIntegration(params) {
877
1018
  detail: `${readEnv_js.API_KEY_ENV} in ${key.path}${key.changed ? ` (a gateway started before this needs a restart, or a config reload, to resolve \${${readEnv_js.API_KEY_ENV}})` : ""}`
878
1019
  });
879
1020
  } catch (err) {
880
- steps.push({ name: "key", status: "failed", detail: `could not write ${readEnv_js.API_KEY_ENV} to the OpenClaw .env: ${describe(err)}` });
1021
+ steps.push({ name: "key", status: "failed", detail: `could not write ${readEnv_js.API_KEY_ENV} to the OpenClaw .env: ${describe2(err)}` });
881
1022
  }
882
1023
  }
883
1024
  const agentId = params.agentId ?? resolvePlacementAgentId(params.cfg, params.accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID);
@@ -893,7 +1034,7 @@ function placeIntegration(params) {
893
1034
  const anchor = agentsAnchor_js.writeAgentsAnchor({ cfg: params.cfg, handle: params.handle, text: params.identityLine, agentId });
894
1035
  steps.push({ name: "anchor", status: "ok", detail: `identity line for @${handle} in ${anchor.path}` });
895
1036
  } catch (err) {
896
- steps.push({ name: "anchor", status: "failed", detail: `could not write the identity line to AGENTS.md: ${describe(err)}` });
1037
+ steps.push({ name: "anchor", status: "failed", detail: `could not write the identity line to AGENTS.md: ${describe2(err)}` });
897
1038
  }
898
1039
  }
899
1040
  steps.push({ name: "manual", status: "ok", detail: "manual bundled as the agentchat skill (skills/agentchat/SKILL.md, https://agentchat.me/skill.md verbatim)" });
@@ -905,6 +1046,8 @@ function describeMcpOutcome(outcome, apiBase) {
905
1046
  switch (outcome) {
906
1047
  case "added":
907
1048
  return { name: "mcp", status: "changed", detail: `hosted tools registered as mcp.servers.agentchat \u2192 ${hostedMcpUrl(apiBase)} (bearer template on ${readEnv_js.API_KEY_ENV})` };
1049
+ case "updated":
1050
+ return { name: "mcp", status: "changed", detail: `mcp.servers.agentchat now names this client to the hosted tools (${clientIdentityText()})` };
908
1051
  case "present":
909
1052
  return { name: "mcp", status: "ok", detail: "hosted tools already registered as mcp.servers.agentchat" };
910
1053
  case "disabled":
@@ -946,15 +1089,40 @@ function checkPlacement(params) {
946
1089
  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)")}` });
947
1090
  }
948
1091
  checks.push({ name: "manual", ok: true, detail: "manual bundled as the agentchat skill" });
949
- const mcpState = describeMcpEntry(params.cfg, params.apiBase, params.apiKey);
950
- checks.push({
951
- name: "mcp",
952
- ok: mcpState === "ours" || mcpState === "user_managed",
953
- 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)")}`
954
- });
1092
+ checks.push(checkMcpEntry(params.cfg, params.apiBase, params.apiKey, remedy));
955
1093
  return checks;
956
1094
  }
957
- function describe(err) {
1095
+ function checkMcpEntry(cfg, apiBase, apiKey, remedy) {
1096
+ const unknownClient = "AgentChat treats the agent as an unknown client and lists the webhook-setup tools it does not need";
1097
+ switch (describeMcpEntry(cfg, apiBase, apiKey)) {
1098
+ case "ours": {
1099
+ const identity = describeMcpIdentity(cfg);
1100
+ if (identity === "current") return { name: "mcp", ok: true, detail: "hosted tools registered as mcp.servers.agentchat" };
1101
+ return {
1102
+ name: "mcp",
1103
+ ok: true,
1104
+ notice: true,
1105
+ repair: true,
1106
+ 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`
1107
+ };
1108
+ }
1109
+ case "user_managed": {
1110
+ if (describeMcpIdentity(cfg) === "current") return { name: "mcp", ok: true, detail: "mcp.servers.agentchat is managed by hand" };
1111
+ const identity = clientIdentityHeaders();
1112
+ return {
1113
+ name: "mcp",
1114
+ ok: true,
1115
+ notice: true,
1116
+ 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`
1117
+ };
1118
+ }
1119
+ case "disabled":
1120
+ return { name: "mcp", ok: false, detail: "mcp.servers.agentchat is disabled \u2014 the agent has no AgentChat tools" };
1121
+ case "missing":
1122
+ return { name: "mcp", ok: false, repair: true, detail: `mcp.servers.agentchat missing \u2014 ${remedy("run openclaw doctor --fix (or openclaw channels add agentchat)")}` };
1123
+ }
1124
+ }
1125
+ function describe2(err) {
958
1126
  return err instanceof Error ? err.message : String(err);
959
1127
  }
960
1128
  var PLUGIN_STATE_DIRNAME = "agentchat";
@@ -965,236 +1133,115 @@ function safeSegment(value) {
965
1133
  function integrationStateDir(accountId, stateDir = openclawLayout_js.resolveOpenClawStateDir()) {
966
1134
  return path2__namespace.join(stateDir, PLUGIN_STATE_DIRNAME, safeSegment(accountId));
967
1135
  }
968
- function readJsonFile(file) {
969
- let raw;
970
- try {
971
- raw = fs__namespace.readFileSync(file, "utf8");
972
- } catch {
973
- return null;
974
- }
1136
+ var OLD_INVITE_LEDGER_FILE = "invites.json";
1137
+ function removeOldStateFiles(accountId, stateDir) {
1138
+ const dir = integrationStateDir(accountId, stateDir);
1139
+ const removed = [];
1140
+ const ledger = path2__namespace.join(dir, OLD_INVITE_LEDGER_FILE);
1141
+ if (tryUnlink(ledger)) removed.push(ledger);
1142
+ const texts = path2__namespace.join(dir, "texts.json");
975
1143
  try {
976
- return JSON.parse(raw);
977
- } catch {
978
- return null;
1144
+ const entry = JSON.parse(fs__namespace.readFileSync(texts, "utf8"));
1145
+ if (entry.version !== 1 || typeof entry.runtime !== "string") {
1146
+ if (tryUnlink(texts)) removed.push(texts);
1147
+ }
1148
+ } catch (err) {
1149
+ if (err?.code !== "ENOENT" && tryUnlink(texts)) removed.push(texts);
979
1150
  }
1151
+ return removed;
980
1152
  }
981
- function writeJsonFile(file, value) {
982
- fs__namespace.mkdirSync(path2__namespace.dirname(file), { recursive: true });
983
- const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
984
- fs__namespace.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}
985
- `, "utf8");
1153
+ function tryUnlink(file) {
986
1154
  try {
987
- fs__namespace.renameSync(tmp, file);
988
- } catch (err) {
989
- try {
990
- fs__namespace.unlinkSync(tmp);
991
- } catch {
992
- }
993
- throw err;
1155
+ fs__namespace.unlinkSync(file);
1156
+ return true;
1157
+ } catch {
1158
+ return false;
994
1159
  }
995
1160
  }
996
1161
 
997
1162
  // src/integration/texts.ts
998
1163
  var TEXTS_RUNTIME = "openclaw";
999
- var TEXTS_REFRESH_MS = 24 * 60 * 6e4;
1000
- var TEXTS_RETRY_MS = 5 * 6e4;
1001
- var TEXTS_FETCH_TIMEOUT_MS = 1e4;
1002
1164
  var TEXTS_CACHE_FILE = "texts.json";
1003
- function isTexts(value) {
1004
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1005
- const t = value;
1006
- const manual = t.manual;
1007
- return typeof t.version === "string" && typeof t.wake_instruction === "string" && t.wake_instruction.length > 0 && typeof t.invite_prompt === "string" && t.invite_prompt.length > 0 && typeof t.identity_line === "string" && t.identity_line.length > 0 && typeof t.identity_line_template === "string" && !!manual && typeof manual === "object" && typeof manual.url === "string" && typeof manual.version === "string";
1008
- }
1009
1165
  function textsCachePath(accountId, stateDir) {
1010
1166
  return path2__namespace.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE);
1011
1167
  }
1012
- function readCachedTexts(accountId, stateDir) {
1013
- const raw = readJsonFile(textsCachePath(accountId, stateDir));
1014
- if (!raw || typeof raw !== "object") return null;
1015
- const entry = raw;
1016
- if (typeof entry.fetched_at !== "string" || !isTexts(entry.texts)) return null;
1017
- return { fetched_at: entry.fetched_at, texts: entry.texts };
1018
- }
1019
- function writeCachedTexts(accountId, texts, fetchedAt, stateDir) {
1020
- const file = textsCachePath(accountId, stateDir);
1021
- const entry = { fetched_at: fetchedAt.toISOString(), texts };
1022
- writeJsonFile(file, entry);
1023
- return file;
1024
- }
1025
1168
  function spellTextsForOpenClaw(texts) {
1026
1169
  return {
1027
1170
  ...texts,
1028
1171
  wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),
1029
1172
  invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),
1030
1173
  identity_line: spellToolsForOpenClaw(texts.identity_line),
1031
- identity_line_template: spellToolsForOpenClaw(texts.identity_line_template)
1174
+ identity_line_template: spellToolsForOpenClaw(texts.identity_line_template),
1175
+ ...typeof texts.gate_call_preamble === "string" ? { gate_call_preamble: spellToolsForOpenClaw(texts.gate_call_preamble) } : {},
1176
+ ...typeof texts.gate_call_answer_format === "string" ? { gate_call_answer_format: spellToolsForOpenClaw(texts.gate_call_answer_format) } : {}
1032
1177
  };
1033
1178
  }
1034
- async function fetchTexts(client, timeoutMs = TEXTS_FETCH_TIMEOUT_MS) {
1035
- const texts = await client.texts.get({ runtime: TEXTS_RUNTIME, timeoutMs });
1036
- if (!isTexts(texts)) throw new Error("GET /v1/texts: answer is not a texts set (missing wake_instruction, invite_prompt or identity_line)");
1037
- return texts;
1179
+ function createTextsCache(params) {
1180
+ return new agentchatme.integration.TextsCache({
1181
+ client: params.client,
1182
+ runtime: TEXTS_RUNTIME,
1183
+ filePath: textsCachePath(params.accountId, params.stateDir),
1184
+ ...params.logger ? { onError: (err) => params.logger?.warn({ err: err.message }, "served texts") } : {}
1185
+ });
1038
1186
  }
1039
- async function loadTexts(params) {
1040
- const now = params.now ?? Date.now;
1041
- try {
1042
- const texts = await fetchTexts(params.client, params.timeoutMs);
1043
- const fetchedAt = new Date(now());
1044
- try {
1045
- writeCachedTexts(params.accountId, texts, fetchedAt, params.stateDir);
1046
- } catch (err) {
1047
- params.log?.warn({ err: describe2(err) }, "texts fetched but the cache could not be written");
1048
- }
1049
- return { texts: spellTextsForOpenClaw(texts), source: "server", fetchedAt: fetchedAt.toISOString() };
1050
- } catch (err) {
1051
- const cached = readCachedTexts(params.accountId, params.stateDir);
1052
- if (cached) {
1053
- params.log?.info({ err: describe2(err), fetchedAt: cached.fetched_at }, "texts: server unreachable \u2014 using the cached copy");
1054
- return { texts: spellTextsForOpenClaw(cached.texts), source: "cache", fetchedAt: cached.fetched_at };
1055
- }
1056
- params.log?.debug({ err: describe2(err) }, "texts: server unreachable and nothing cached");
1057
- return null;
1187
+ var OpenClawTexts = class {
1188
+ constructor(cache2) {
1189
+ this.cache = cache2;
1058
1190
  }
1059
- }
1060
- async function loadIdentityLine(params) {
1061
- const loaded = await loadTexts(params);
1062
- return loaded ? loaded.texts.identity_line : null;
1063
- }
1064
- function cachedIdentityLine(accountId, stateDir) {
1065
- const cached = readCachedTexts(accountId, stateDir);
1066
- return cached ? spellToolsForOpenClaw(cached.texts.identity_line) : null;
1067
- }
1068
- var TextsStore = class {
1069
- client;
1070
- accountId;
1071
- logger;
1072
- stateDir;
1073
- refreshMs;
1074
- retryMs;
1075
- fetchTimeoutMs;
1076
- now;
1077
- _setTimeout;
1078
- _clearTimeout;
1079
- loaded = null;
1080
- timer = null;
1081
- inFlight = null;
1082
- stopped = false;
1083
- missingAnnounced = false;
1084
- listeners = /* @__PURE__ */ new Set();
1085
- loads = 0;
1086
- serverLoads = 0;
1087
- constructor(options) {
1088
- this.client = options.client;
1089
- this.accountId = options.accountId;
1090
- this.logger = options.logger.child({ component: "texts", accountId: options.accountId });
1091
- this.stateDir = options.stateDir;
1092
- this.refreshMs = options.refreshMs ?? TEXTS_REFRESH_MS;
1093
- this.retryMs = options.retryMs ?? TEXTS_RETRY_MS;
1094
- this.fetchTimeoutMs = options.fetchTimeoutMs ?? TEXTS_FETCH_TIMEOUT_MS;
1095
- this.now = options.now ?? Date.now;
1096
- this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
1097
- this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h));
1191
+ cache;
1192
+ spelledFrom = null;
1193
+ spelled = null;
1194
+ current() {
1195
+ return this.spell(this.cache.current());
1098
1196
  }
1099
- /** The texts spelled for OpenClaw, or null until the first copy exists. */
1100
- get current() {
1101
- return this.loaded?.texts ?? null;
1197
+ async ensure() {
1198
+ return this.spell(await this.cache.ensure());
1102
1199
  }
1103
1200
  get source() {
1104
- return this.loaded?.source ?? null;
1201
+ return this.cache.source;
1105
1202
  }
1106
1203
  get fetchedAt() {
1107
- return this.loaded?.fetchedAt ?? null;
1204
+ return this.cache.fetchedAt;
1108
1205
  }
1109
- /** Called with every copy that arrives from the server (not with a cached one). */
1110
- onServerCopy(listener) {
1111
- this.listeners.add(listener);
1112
- return () => {
1113
- this.listeners.delete(listener);
1114
- };
1206
+ get lastError() {
1207
+ return this.cache.lastError;
1115
1208
  }
1116
- /** First load (server, then cache), then the timer. Resolves after the first attempt; never throws. */
1117
- async start() {
1118
- const texts = await this.load();
1119
- if (!texts && !this.missingAnnounced) {
1120
- this.missingAnnounced = true;
1121
- this.logger.warn(
1122
- { retryMs: this.retryMs },
1123
- "AgentChat texts unreachable and nothing cached \u2014 starting anyway; turns wait for the first copy, retried until it arrives"
1124
- );
1209
+ spell(texts) {
1210
+ if (texts === null) return null;
1211
+ if (texts !== this.spelledFrom) {
1212
+ this.spelledFrom = texts;
1213
+ this.spelled = spellTextsForOpenClaw(texts);
1125
1214
  }
1126
- this.arm();
1127
- return texts;
1128
- }
1129
- /** The current copy, or one load attempt now (coalesced with any in flight). */
1130
- async ensure() {
1131
- if (this.loaded) return this.loaded.texts;
1132
- if (this.stopped) return null;
1133
- return this.load();
1215
+ return this.spelled;
1134
1216
  }
1135
- /** Force a refresh (tests, operators). Coalesced. */
1136
- refresh() {
1137
- return this.load();
1217
+ };
1218
+ async function loadIdentityLine(params) {
1219
+ const cache2 = createTextsCache(params);
1220
+ try {
1221
+ const texts = await cache2.start();
1222
+ return texts ? spellToolsForOpenClaw(texts.identity_line) : null;
1223
+ } catch {
1224
+ return null;
1225
+ } finally {
1226
+ cache2.stop();
1138
1227
  }
1139
- stop() {
1140
- this.stopped = true;
1141
- if (this.timer !== null) {
1142
- this._clearTimeout(this.timer);
1143
- this.timer = null;
1144
- }
1145
- this.listeners.clear();
1228
+ }
1229
+ function cachedIdentityLine(accountId, stateDir) {
1230
+ let raw;
1231
+ try {
1232
+ raw = fs__namespace.readFileSync(textsCachePath(accountId, stateDir), "utf8");
1233
+ } catch {
1234
+ return null;
1146
1235
  }
1147
- load() {
1148
- if (this.inFlight) return this.inFlight;
1149
- this.inFlight = (async () => {
1150
- this.loads += 1;
1151
- const next = await loadTexts({
1152
- client: this.client,
1153
- accountId: this.accountId,
1154
- stateDir: this.stateDir,
1155
- now: this.now,
1156
- log: this.logger,
1157
- timeoutMs: this.fetchTimeoutMs
1158
- });
1159
- if (this.stopped) return next?.texts ?? null;
1160
- if (next) {
1161
- const changed = this.loaded?.texts.version !== next.texts.version || this.loaded?.texts.wake_instruction !== next.texts.wake_instruction;
1162
- this.loaded = next;
1163
- if (next.source === "server") {
1164
- this.serverLoads += 1;
1165
- this.logger[changed ? "info" : "debug"](
1166
- { version: next.texts.version, manual: next.texts.manual.version },
1167
- "texts fetched from the server"
1168
- );
1169
- for (const listener of this.listeners) {
1170
- try {
1171
- listener(next.texts, next.source);
1172
- } catch (err) {
1173
- this.logger.warn({ err: describe2(err) }, "texts listener threw \u2014 continuing");
1174
- }
1175
- }
1176
- }
1177
- }
1178
- return next?.texts ?? null;
1179
- })().finally(() => {
1180
- this.inFlight = null;
1181
- });
1182
- return this.inFlight;
1183
- }
1184
- arm() {
1185
- if (this.stopped) return;
1186
- if (this.timer !== null) this._clearTimeout(this.timer);
1187
- const delay = this.loaded === null ? this.retryMs : this.loaded.source === "cache" ? this.retryMs : this.refreshMs;
1188
- this.timer = this._setTimeout(() => {
1189
- this.timer = null;
1190
- void this.load().finally(() => this.arm());
1191
- }, delay);
1192
- this.timer.unref?.();
1236
+ try {
1237
+ const entry = JSON.parse(raw);
1238
+ if (entry.runtime !== TEXTS_RUNTIME || !isTexts(entry.texts)) return null;
1239
+ return spellToolsForOpenClaw(entry.texts.identity_line);
1240
+ } catch {
1241
+ return null;
1193
1242
  }
1194
- };
1195
- function describe2(err) {
1196
- return err instanceof Error ? err.message : String(err);
1197
1243
  }
1244
+ var isTexts = agentchatme.integration.isTexts;
1198
1245
  var cache = /* @__PURE__ */ new Map();
1199
1246
  function createSdkClient(params) {
1200
1247
  return new agentchatme.AgentChatClient({
@@ -1778,7 +1825,7 @@ var agentchatSetupWizard = {
1778
1825
  {
1779
1826
  value: "paste",
1780
1827
  label: "I already have an API key",
1781
- hint: "paste ac_live_\u2026 on the next prompt"
1828
+ hint: "paste ac_\u2026 on the next prompt"
1782
1829
  },
1783
1830
  {
1784
1831
  value: "recover",
@@ -1849,10 +1896,10 @@ var agentchatSetupWizard = {
1849
1896
  preferredEnvVar: "AGENTCHAT_API_KEY",
1850
1897
  envPrompt: "AGENTCHAT_API_KEY detected in env. Use it?",
1851
1898
  keepPrompt: "AgentChat API key already configured. Keep it?",
1852
- inputPrompt: "Paste your AgentChat API key (ac_live_\u2026)",
1899
+ inputPrompt: "Paste your AgentChat API key (ac_\u2026)",
1853
1900
  helpTitle: "AgentChat API key",
1854
1901
  helpLines: [
1855
- "Format: ac_live_<base64>, \u226520 chars. Validated against",
1902
+ "Format: ac_ followed by 43 base64url characters. Validated against",
1856
1903
  "GET /v1/agents/me during this wizard \u2014 bad keys fail fast instead",
1857
1904
  "of flapping reconnects at runtime."
1858
1905
  ],
@@ -2000,10 +2047,644 @@ var agentchatChannelConfigSchema = zod.z.object({
2000
2047
  function parseChannelConfig(input) {
2001
2048
  return agentchatChannelConfigSchema.parse(input);
2002
2049
  }
2003
- function createLogger(options) {
2004
- if (options.delegate) {
2005
- return options.delegate;
2006
- }
2050
+ var TRAY_LIMIT = 50;
2051
+ function createAfterTurnRecorder(options) {
2052
+ const { client, logger } = options;
2053
+ return async (record, end) => {
2054
+ if (end.status === "still_running" || record.kind === "run") return;
2055
+ let fresh;
2056
+ try {
2057
+ fresh = await client.inbox.tray({ waitMs: 0, limit: TRAY_LIMIT, includeInvites: true });
2058
+ } catch (err) {
2059
+ logger.warn({ runId: record.runId, err: describe3(err) }, "after-turn tray read failed \u2014 nothing recorded; the server re-wakes the card");
2060
+ fresh = null;
2061
+ }
2062
+ try {
2063
+ if (record.kind === "reply") {
2064
+ if (!record.card) return;
2065
+ const outcome2 = agentchatme.integration.turnOutcome({
2066
+ turn: end,
2067
+ turnStartedAt: record.startedAt,
2068
+ gateCard: record.card,
2069
+ category: record.category ?? null,
2070
+ freshTray: fresh,
2071
+ silentBefore: 0
2072
+ });
2073
+ const recorded2 = await agentchatme.integration.applyOutcome(client, outcome2);
2074
+ logger.info({ runId: record.runId, conversationId: record.id, action: outcome2.action, reason: outcome2.reason, recorded: recorded2 }, "after-turn rule applied (turn ended outside the loop\u2019s watch)");
2075
+ return;
2076
+ }
2077
+ if (!record.invite) return;
2078
+ const outcome = agentchatme.integration.inviteOutcome({ turn: end, invite: record.invite, freshTray: fresh, silentBefore: 0 });
2079
+ const recorded = await agentchatme.integration.applyInviteOutcome(client, outcome);
2080
+ logger.info({ runId: record.runId, inviteId: record.id, action: outcome.action, reason: outcome.reason, recorded }, "after-turn rule applied to the invite (turn ended outside the loop\u2019s watch)");
2081
+ } catch (err) {
2082
+ logger.warn({ runId: record.runId, err: describe3(err) }, "after-turn recording failed \u2014 the card stays on the tray; the server re-wakes it");
2083
+ }
2084
+ };
2085
+ }
2086
+ function cardFromStored(stored) {
2087
+ return { preview: null, ...stored };
2088
+ }
2089
+ function describe3(err) {
2090
+ return err instanceof Error ? err.message : String(err);
2091
+ }
2092
+ var TURN_STORE_FILE = "turns.json";
2093
+ var KEEP_ENDED_MS = 6e4;
2094
+ function storedCard(card, anchor) {
2095
+ return {
2096
+ conversation_id: card.conversation_id,
2097
+ ...anchor ? { last_message_id: anchor } : {},
2098
+ ...card.your_last_message_at !== void 0 ? { your_last_message_at: card.your_last_message_at } : {},
2099
+ ...card.you_owe_reply !== void 0 ? { you_owe_reply: card.you_owe_reply } : {},
2100
+ ...card.your_last_decision !== void 0 ? { your_last_decision: card.your_last_decision } : {}
2101
+ };
2102
+ }
2103
+ var TurnStore = class {
2104
+ file;
2105
+ constructor(accountId, stateDir) {
2106
+ this.file = path2__namespace.join(integrationStateDir(accountId, stateDir), TURN_STORE_FILE);
2107
+ }
2108
+ /** What the last process left. Empty when there is no file or it cannot be read. */
2109
+ load() {
2110
+ let parsed;
2111
+ try {
2112
+ parsed = JSON.parse(fs__namespace.readFileSync(this.file, "utf8"));
2113
+ } catch {
2114
+ return [];
2115
+ }
2116
+ const turns = parsed?.turns;
2117
+ if (parsed?.version !== 1 || !Array.isArray(turns)) return [];
2118
+ return turns.filter(isStoredTurn);
2119
+ }
2120
+ /** Replace the file with `turns` (removed when empty). Returns false when the write failed. */
2121
+ write(turns) {
2122
+ try {
2123
+ if (turns.length === 0) {
2124
+ fs__namespace.rmSync(this.file, { force: true });
2125
+ return true;
2126
+ }
2127
+ fs__namespace.mkdirSync(path2__namespace.dirname(this.file), { recursive: true });
2128
+ const body = { version: 1, turns };
2129
+ const tmp = `${this.file}.${process.pid}.tmp`;
2130
+ fs__namespace.writeFileSync(tmp, `${JSON.stringify(body)}
2131
+ `, { mode: 384 });
2132
+ fs__namespace.renameSync(tmp, this.file);
2133
+ return true;
2134
+ } catch {
2135
+ return false;
2136
+ }
2137
+ }
2138
+ };
2139
+ function isStoredTurn(value) {
2140
+ const turn = value;
2141
+ return typeof turn === "object" && turn !== null && typeof turn.runId === "string" && (turn.kind === "reply" || turn.kind === "invite") && typeof turn.id === "string" && turn.id.length > 0 && typeof turn.sessionKey === "string" && turn.sessionKey.length > 0 && typeof turn.startedAt === "number" && (turn.anchor === null || typeof turn.anchor === "string");
2142
+ }
2143
+
2144
+ // src/integration/running.ts
2145
+ var TURN_OVERDUE_MS = 30 * 6e4;
2146
+ var OVERDUE_SLACK_MS = 5e3;
2147
+ function isOverdue(elapsedMs) {
2148
+ return elapsedMs + OVERDUE_SLACK_MS >= TURN_OVERDUE_MS;
2149
+ }
2150
+ var MAX_HUNG_TURNS = 2;
2151
+ var OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS = 2880 * 60;
2152
+ var RESTART_HOLD_MS = 3 * 6e4;
2153
+ var STORED_TURN_MAX_AGE_MS = 24 * 60 * 6e4;
2154
+ var RESTART_END_DETAIL = "the gateway restarted during the turn";
2155
+ function trackerKey(kind, id) {
2156
+ return kind === "reply" ? `conversation:${id}` : kind === "invite" ? `invite:${id}` : `run:${id}`;
2157
+ }
2158
+ function trackedTurn(record) {
2159
+ if (record.kind === "reply") return { kind: "reply", conversationId: record.id, anchor: record.anchor };
2160
+ if (record.kind === "invite") return { kind: "invite", inviteId: record.id };
2161
+ return null;
2162
+ }
2163
+ function storedOf(record) {
2164
+ if (record.kind === "run") return null;
2165
+ return {
2166
+ runId: record.runId,
2167
+ kind: record.kind,
2168
+ id: record.id,
2169
+ anchor: record.anchor,
2170
+ sessionKey: record.sessionKey,
2171
+ startedAt: record.startedAt,
2172
+ ...record.firstStartedAt !== void 0 ? { firstStartedAt: record.firstStartedAt } : {},
2173
+ ...record.category !== void 0 ? { category: record.category } : {},
2174
+ ...record.kind === "reply" && record.card ? { card: storedCard(record.card, record.anchor) } : {}
2175
+ };
2176
+ }
2177
+ function recordOf(stored) {
2178
+ return {
2179
+ runId: stored.runId,
2180
+ kind: stored.kind,
2181
+ id: stored.id,
2182
+ anchor: stored.anchor,
2183
+ sessionKey: stored.sessionKey,
2184
+ startedAt: stored.startedAt,
2185
+ firstStartedAt: stored.firstStartedAt ?? stored.startedAt,
2186
+ owner: "previous-process",
2187
+ ...stored.category !== void 0 ? { category: stored.category } : {},
2188
+ ...stored.kind === "reply" && stored.card ? { card: cardFromStored(stored.card) } : {},
2189
+ ...stored.kind === "invite" ? { invite: { invite_id: stored.id } } : {}
2190
+ };
2191
+ }
2192
+ var AccountTurns = class {
2193
+ /** The kit's tracker for the account, shared by every loop for it. */
2194
+ tracker;
2195
+ entries = /* @__PURE__ */ new Map();
2196
+ /** Turns the last process left in flight, by session key. */
2197
+ adopted = /* @__PURE__ */ new Map();
2198
+ /** Turns OpenClaw is admitting right now. */
2199
+ admitting = /* @__PURE__ */ new Set();
2200
+ /** Ended runs still written to the store (`KEEP_ENDED_MS`). */
2201
+ kept = /* @__PURE__ */ new Map();
2202
+ keptTimer = null;
2203
+ live = null;
2204
+ wiring = {};
2205
+ /** Which OpenClaw lane new turns go to; moves on at every hand-off (a hung run blocks its lane). */
2206
+ lane = 0;
2207
+ now;
2208
+ constructor(options = {}) {
2209
+ this.now = options.now ?? Date.now;
2210
+ this.tracker = new agentchatme.integration.TurnTracker({ now: this.now });
2211
+ this.tracker.onRelease((handle) => {
2212
+ for (const admission of this.admitting) if (admission.key === handle.key) admission.released = true;
2213
+ });
2214
+ }
2215
+ /** The account's after-turn recorder, store and run watcher (each account start; the latest wins). */
2216
+ configure(wiring) {
2217
+ this.wiring = { ...this.wiring, ...wiring };
2218
+ }
2219
+ /** The loop now receiving for the account; a held run that ends wakes it. `run` = the loop's own async context (default: as called). */
2220
+ setLive(owner, wake, run = (fn) => fn()) {
2221
+ this.live = { owner, wake, run };
2222
+ }
2223
+ clearLive(owner) {
2224
+ if (this.live?.owner === owner) this.live = null;
2225
+ }
2226
+ /** A turn is about to be admitted by OpenClaw: watch whether its kit hold is released meanwhile. */
2227
+ admission(kind, id) {
2228
+ const admission = { key: trackerKey(kind, id), released: false };
2229
+ this.admitting.add(admission);
2230
+ return admission;
2231
+ }
2232
+ /** OpenClaw refused the turn: nothing to watch. */
2233
+ admitted(admission) {
2234
+ this.admitting.delete(admission);
2235
+ }
2236
+ /**
2237
+ * A run OpenClaw admitted. `letGo` (gate-off runs): ends the cycle waiting
2238
+ * on it when it is handed off or released. `admission`: a turn whose kit
2239
+ * hold was released during admission starts out let go of.
2240
+ */
2241
+ started(record, options = {}) {
2242
+ const releasedMeanwhile = options.admission?.released === true;
2243
+ if (options.admission) this.admitting.delete(options.admission);
2244
+ this.entries.set(record.runId, {
2245
+ record,
2246
+ state: releasedMeanwhile ? "released" : "kit",
2247
+ handle: null,
2248
+ since: 0,
2249
+ ...options.letGo ? { letGo: options.letGo } : {}
2250
+ });
2251
+ this.persist();
2252
+ }
2253
+ run(runId) {
2254
+ return this.entries.get(runId)?.record;
2255
+ }
2256
+ /** Where the run stands (`null`: not a run of this account, or ended). */
2257
+ stateOf(runId) {
2258
+ return this.entries.get(runId)?.state ?? null;
2259
+ }
2260
+ /** Every run OpenClaw has not reported ended that still holds something, oldest first. */
2261
+ runningRuns() {
2262
+ return [...this.entries.values()].filter((entry) => entry.state !== "released").map((entry) => entry.record).sort((a, b) => a.startedAt - b.startedAt);
2263
+ }
2264
+ hungRuns() {
2265
+ return [...this.entries.values()].filter((entry) => entry.state === "hung").map((entry) => entry.record);
2266
+ }
2267
+ get hungCount() {
2268
+ let count = 0;
2269
+ for (const entry of this.entries.values()) if (entry.state === "hung") count += 1;
2270
+ return count;
2271
+ }
2272
+ /** The handed-off gate-off run still going, if any: no new run starts while it lives. */
2273
+ hungSingleRun() {
2274
+ for (const entry of this.entries.values()) if (entry.state === "hung" && entry.record.kind === "run") return entry.record;
2275
+ return null;
2276
+ }
2277
+ /** Conversations (and invites) held after a restart: adopted (until when), or continued by a run OpenClaw started. */
2278
+ restartHolds() {
2279
+ const holds = [...this.adopted.values()].map((a) => ({
2280
+ record: a.record,
2281
+ until: a.until,
2282
+ watching: null
2283
+ }));
2284
+ for (const entry of this.entries.values()) if (entry.state === "watch") holds.push({ record: entry.record, until: null, watching: entry.record.runId });
2285
+ return holds;
2286
+ }
2287
+ /** The lane generation new turns start on (`integrationLane(accountId, laneGeneration)`). */
2288
+ get laneGeneration() {
2289
+ return this.lane;
2290
+ }
2291
+ /**
2292
+ * OpenClaw reported the run ended (`end`: what it did, when known). A turn
2293
+ * held here (handed off, or continued after a restart) gets the after-turn
2294
+ * rule, then its hold drops and the live loop is woken. A turn the kit
2295
+ * still holds is the kit's to record; the live loop is woken once the card
2296
+ * is free, only when an earlier loop started it. A run let go of records
2297
+ * nothing.
2298
+ */
2299
+ async ended(runId, end) {
2300
+ const entry = this.entries.get(runId);
2301
+ if (!entry) return;
2302
+ this.entries.delete(runId);
2303
+ if (entry.state !== "released") this.keep(entry.record);
2304
+ else this.persist();
2305
+ if (entry.state === "hung" || entry.state === "watch") {
2306
+ try {
2307
+ if (end && this.wiring.recorder && entry.record.kind !== "run") await this.wiring.recorder(entry.record, end);
2308
+ } finally {
2309
+ if (entry.handle) this.tracker.end(entry.handle);
2310
+ this.live?.wake();
2311
+ }
2312
+ return;
2313
+ }
2314
+ if (entry.state === "released" || entry.record.kind === "run") return;
2315
+ if (!this.live || this.live.owner === entry.record.owner) return;
2316
+ this.wakeWhenFree(trackerKey(entry.record.kind, entry.record.id));
2317
+ }
2318
+ /**
2319
+ * Hand a long run off, once, by run id: release the kit's slot for it (its
2320
+ * loop records nothing for it and may start other turns) and hold the
2321
+ * conversation here until the run ends. A gate-off run: the cycle waiting
2322
+ * on it is let go of. A continued run is already held here: it becomes
2323
+ * hung (counted toward `MAX_HUNG_TURNS`). Returns the record when it was
2324
+ * handed off now; null when it was already handed off or let go of.
2325
+ */
2326
+ handOff(runId) {
2327
+ const entry = this.entries.get(runId);
2328
+ if (!entry || entry.state !== "kit" && entry.state !== "watch") return null;
2329
+ const record = entry.record;
2330
+ entry.since = this.now();
2331
+ if (entry.state === "watch") {
2332
+ entry.state = "hung";
2333
+ this.live?.wake();
2334
+ return record;
2335
+ }
2336
+ this.lane += 1;
2337
+ entry.state = "hung";
2338
+ const turn = trackedTurn(record);
2339
+ if (turn === null) {
2340
+ entry.letGo?.();
2341
+ } else {
2342
+ this.tracker.release(trackerKey(record.kind, record.id));
2343
+ entry.handle = this.tracker.begin(turn);
2344
+ if (!entry.handle) entry.state = "released";
2345
+ }
2346
+ this.live?.wake();
2347
+ return entry.state === "hung" ? record : null;
2348
+ }
2349
+ /**
2350
+ * An operator lets go of a conversation's (or invite's) turn: a hung hold,
2351
+ * a restart hold, or — past `TURN_OVERDUE_MS`, or with `force` — a turn
2352
+ * still running. Its run may still be live and answer: a second reply is
2353
+ * then possible, which is why a turn under 30 minutes (most likely still
2354
+ * working) is refused without `force`. A gate-off run always needs
2355
+ * `force`: it reads the whole tray, so a new run would answer the same
2356
+ * cards while it may still be going.
2357
+ */
2358
+ release(id, options = {}) {
2359
+ const live = this.live;
2360
+ return live ? live.run(() => this.releaseNow(id, options.force === true)) : this.releaseNow(id, options.force === true);
2361
+ }
2362
+ releaseNow(id, force) {
2363
+ const matches = (record) => record.id === id || record.runId === id;
2364
+ for (const entry of this.entries.values()) {
2365
+ if (entry.state !== "hung" || !matches(entry.record)) continue;
2366
+ if (entry.record.kind === "run" && !force) return this.refuseSingleRun(entry.record);
2367
+ entry.state = "released";
2368
+ if (entry.handle) this.tracker.end(entry.handle);
2369
+ entry.handle = null;
2370
+ this.persist();
2371
+ this.live?.wake();
2372
+ return { released: true, what: "hung", key: trackerKey(entry.record.kind, entry.record.id), runId: entry.record.runId };
2373
+ }
2374
+ for (const [sessionKey, adopted] of this.adopted) {
2375
+ if (adopted.record.id !== id) continue;
2376
+ this.finishAdopted(sessionKey);
2377
+ return { released: true, what: "restart", key: trackerKey(adopted.record.kind, adopted.record.id), runId: null };
2378
+ }
2379
+ for (const entry of this.entries.values()) {
2380
+ if (entry.state !== "kit" && entry.state !== "watch" || !matches(entry.record)) continue;
2381
+ const refused = this.refuseYoung(entry.record.kind, entry.record.id, entry.record.startedAt, force);
2382
+ if (refused) return refused;
2383
+ const key = trackerKey(entry.record.kind, entry.record.id);
2384
+ if (entry.state === "watch") {
2385
+ if (entry.handle) this.tracker.end(entry.handle);
2386
+ entry.handle = null;
2387
+ } else {
2388
+ this.lane += 1;
2389
+ if (entry.record.kind === "run") entry.letGo?.();
2390
+ else this.tracker.release(key);
2391
+ }
2392
+ entry.state = "released";
2393
+ this.persist();
2394
+ this.live?.wake();
2395
+ return { released: true, what: "running", key, runId: entry.record.runId };
2396
+ }
2397
+ for (const held of this.tracker.running()) {
2398
+ const heldId = held.kind === "reply" ? held.conversationId : held.inviteId;
2399
+ if (heldId !== id) continue;
2400
+ const refused = this.refuseYoung(held.kind, heldId, held.startedAt, force);
2401
+ if (refused) return refused;
2402
+ this.lane += 1;
2403
+ const key = trackerKey(held.kind, heldId);
2404
+ if (this.tracker.release(key)) {
2405
+ this.live?.wake();
2406
+ return { released: true, what: "running", key, runId: null };
2407
+ }
2408
+ }
2409
+ return { released: false, reason: `no turn holds ${id}` };
2410
+ }
2411
+ refuseYoung(kind, id, startedAt, force) {
2412
+ const age = this.now() - startedAt;
2413
+ if (force || age >= TURN_OVERDUE_MS) return null;
2414
+ return {
2415
+ released: false,
2416
+ reason: `the turn for ${whatOf(kind, id)} has run ${Math.floor(age / 6e4)} min \u2014 under ${TURN_OVERDUE_MS / 6e4} min it is most likely still working, and releasing it lets the conversation be gated again while that run can still send its answer (the peer would get two replies); wait, or repeat with --force`
2417
+ };
2418
+ }
2419
+ refuseSingleRun(record) {
2420
+ return {
2421
+ released: false,
2422
+ reason: `${whatOf("run", record.runId)} has run ${Math.floor((this.now() - record.startedAt) / 6e4)} min and reads the whole tray \u2014 releasing it lets a new run answer the same cards while this one may still be going (the peers would get two replies); repeat with --force`
2423
+ };
2424
+ }
2425
+ /**
2426
+ * Adopt the turns the last process left in flight (the store). Each one's
2427
+ * conversation (or invite) is held at once — before the loop's first gate —
2428
+ * for `RESTART_HOLD_MS`; the after-turn rule is applied to what the ended
2429
+ * run did now and again when the hold expires. A run OpenClaw starts in the
2430
+ * turn's session meanwhile (`observeRun`) takes the hold over. A turn first
2431
+ * started more than `STORED_TURN_MAX_AGE_MS` ago is dropped. Returns what
2432
+ * was adopted.
2433
+ */
2434
+ adopt(stored = this.wiring.store?.load() ?? []) {
2435
+ const adopted = [];
2436
+ const now = this.now();
2437
+ for (const turn of stored) {
2438
+ if (this.entries.has(turn.runId) || this.adopted.has(turn.sessionKey) || this.kept.has(turn.runId)) continue;
2439
+ const first = turn.firstStartedAt ?? turn.startedAt;
2440
+ if (now - first > STORED_TURN_MAX_AGE_MS) {
2441
+ this.wiring.logger?.info({ runId: turn.runId, [turn.kind === "reply" ? "conversationId" : "inviteId"]: turn.id }, "a stored turn older than a day was dropped, not adopted again");
2442
+ continue;
2443
+ }
2444
+ const record = recordOf(turn);
2445
+ const tracked = trackedTurn(record);
2446
+ const handle = tracked ? this.tracker.begin(tracked) : null;
2447
+ if (!handle) continue;
2448
+ const entry = { stored: { ...turn, firstStartedAt: first }, record, handle, until: now + RESTART_HOLD_MS, end: null, timer: null };
2449
+ this.adopted.set(turn.sessionKey, entry);
2450
+ entry.timer = setTimeout(() => this.expireAdopted(turn.sessionKey, entry), RESTART_HOLD_MS);
2451
+ entry.timer.unref?.();
2452
+ adopted.push(record);
2453
+ void this.recordRestartEnded(entry);
2454
+ }
2455
+ this.persist();
2456
+ return adopted;
2457
+ }
2458
+ /**
2459
+ * A run started in some session (the `model_call_started` hook). One in
2460
+ * the session of a turn adopted after a restart is OpenClaw continuing
2461
+ * that turn: it takes the hold over as a turn of its own (`watch`), handed
2462
+ * off past `TURN_OVERDUE_MS` like any other.
2463
+ */
2464
+ observeRun(runId, sessionKey) {
2465
+ if (!sessionKey || this.entries.has(runId)) return;
2466
+ const adopted = this.adopted.get(sessionKey);
2467
+ if (!adopted) return;
2468
+ this.adopted.delete(sessionKey);
2469
+ if (adopted.timer) clearTimeout(adopted.timer);
2470
+ const record = { ...adopted.record, runId, startedAt: this.now(), owner: "restart" };
2471
+ this.entries.set(runId, { record, state: "watch", handle: adopted.handle, since: 0 });
2472
+ this.persist();
2473
+ this.wiring.logger?.info(
2474
+ { runId, sessionKey, [record.kind === "reply" ? "conversationId" : "inviteId"]: record.id },
2475
+ "OpenClaw continued a turn session after the restart \u2014 its conversation stays held until that run ends"
2476
+ );
2477
+ void this.watchContinued(record);
2478
+ }
2479
+ async watchContinued(record) {
2480
+ let end = null;
2481
+ try {
2482
+ end = this.wiring.watch ? await this.wiring.watch(record) : null;
2483
+ } catch {
2484
+ end = null;
2485
+ }
2486
+ if (end === null) return;
2487
+ await this.ended(record.runId, end);
2488
+ }
2489
+ async recordRestartEnded(adopted) {
2490
+ const { record } = adopted;
2491
+ let calls = null;
2492
+ try {
2493
+ calls = this.wiring.readCalls ? await this.wiring.readCalls(record.sessionKey, record.runId) : null;
2494
+ } catch {
2495
+ calls = null;
2496
+ }
2497
+ adopted.end = { status: "failed", agentchatCalls: calls, detail: RESTART_END_DETAIL };
2498
+ if (this.adopted.get(record.sessionKey) !== adopted || !this.wiring.recorder) return;
2499
+ await this.wiring.recorder(record, adopted.end);
2500
+ }
2501
+ /**
2502
+ * The hold expired with nothing continuing the turn: the after-turn rule
2503
+ * once more — the resumed main session may have answered the card
2504
+ * meanwhile — then the conversation is free.
2505
+ */
2506
+ expireAdopted(sessionKey, adopted) {
2507
+ if (this.adopted.get(sessionKey) !== adopted) return;
2508
+ void (async () => {
2509
+ try {
2510
+ if (this.wiring.recorder) await this.wiring.recorder(adopted.record, adopted.end ?? { status: "failed", agentchatCalls: null, detail: RESTART_END_DETAIL });
2511
+ } catch {
2512
+ }
2513
+ if (this.adopted.get(sessionKey) === adopted) this.finishAdopted(sessionKey);
2514
+ })();
2515
+ }
2516
+ finishAdopted(sessionKey) {
2517
+ const adopted = this.adopted.get(sessionKey);
2518
+ if (!adopted) return;
2519
+ this.adopted.delete(sessionKey);
2520
+ if (adopted.timer) clearTimeout(adopted.timer);
2521
+ this.tracker.end(adopted.handle);
2522
+ this.persist();
2523
+ this.live?.wake();
2524
+ }
2525
+ /** An ended run stays in the store a little longer: a restart ends the run before it ends the process. */
2526
+ keep(record) {
2527
+ const turn = storedOf(record);
2528
+ if (turn) this.kept.set(record.runId, { turn, endedAt: this.now() });
2529
+ this.persist();
2530
+ if (!this.keptTimer) this.schedulePrune();
2531
+ }
2532
+ /** The next prune at the oldest kept entry's expiry. */
2533
+ schedulePrune() {
2534
+ let oldest = Infinity;
2535
+ for (const kept of this.kept.values()) oldest = Math.min(oldest, kept.endedAt);
2536
+ if (oldest === Infinity) return;
2537
+ this.keptTimer = setTimeout(() => this.pruneKept(), Math.max(0, oldest + KEEP_ENDED_MS - this.now()));
2538
+ this.keptTimer.unref?.();
2539
+ }
2540
+ pruneKept() {
2541
+ this.keptTimer = null;
2542
+ const cutoff = this.now() - KEEP_ENDED_MS;
2543
+ for (const [runId, kept] of this.kept) if (kept.endedAt <= cutoff) this.kept.delete(runId);
2544
+ this.persist();
2545
+ this.schedulePrune();
2546
+ }
2547
+ persist() {
2548
+ const store = this.wiring.store;
2549
+ if (!store) return;
2550
+ const turns = /* @__PURE__ */ new Map();
2551
+ for (const entry of this.entries.values()) {
2552
+ if (entry.state === "released") continue;
2553
+ const turn = storedOf(entry.record);
2554
+ if (turn) turns.set(turn.runId, turn);
2555
+ }
2556
+ for (const [runId, kept] of this.kept) turns.set(runId, kept.turn);
2557
+ for (const adopted of this.adopted.values()) turns.set(adopted.stored.runId, adopted.stored);
2558
+ if (!store.write([...turns.values()])) this.wiring.logger?.debug({ file: store.file }, "turns in flight could not be written (the restart defense is off until the next write)");
2559
+ }
2560
+ wakeWhenFree(key, attempts = 300) {
2561
+ const held = key.startsWith("conversation:") ? this.tracker.conversationRunning(key.slice("conversation:".length)) : this.tracker.inviteRunning(key.slice("invite:".length));
2562
+ if (!held || attempts <= 0) {
2563
+ this.live?.wake();
2564
+ return;
2565
+ }
2566
+ const timer = setTimeout(() => this.wakeWhenFree(key, attempts - 1), 100);
2567
+ timer.unref?.();
2568
+ }
2569
+ };
2570
+ var accounts = /* @__PURE__ */ new Map();
2571
+ function accountTurns(accountId) {
2572
+ let turns = accounts.get(accountId);
2573
+ if (!turns) {
2574
+ turns = new AccountTurns();
2575
+ accounts.set(accountId, turns);
2576
+ }
2577
+ return turns;
2578
+ }
2579
+ function findAccountTurns(accountId) {
2580
+ return accounts.get(accountId);
2581
+ }
2582
+ function observeRunStarted(runId, sessionKey) {
2583
+ if (typeof runId !== "string" || runId.length === 0 || typeof sessionKey !== "string" || sessionKey.length === 0) return;
2584
+ for (const turns of accounts.values()) turns.observeRun(runId, sessionKey);
2585
+ }
2586
+ function runDeadline(cfg) {
2587
+ const value = cfg?.agents?.defaults?.timeoutSeconds;
2588
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return { seconds: Math.floor(value), configured: true };
2589
+ return { seconds: OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS, configured: false };
2590
+ }
2591
+ function whatOf(kind, id) {
2592
+ return kind === "reply" ? `conversation ${id}` : kind === "invite" ? `invite ${id}` : `the gate-off run ${id}`;
2593
+ }
2594
+ function deadlineText(cfg) {
2595
+ const deadline = runDeadline(cfg);
2596
+ return deadline.seconds === 0 ? "agents.defaults.timeoutSeconds is 0 (no deadline), so it may never end" : `OpenClaw ends it at its run deadline, agents.defaults.timeoutSeconds = ${deadline.seconds}${deadline.configured ? "" : " (OpenClaw's default, 48 h)"}`;
2597
+ }
2598
+ function overdueTurnLine(turn, cfg) {
2599
+ const minutes = Math.round(turn.elapsedMs / 6e4);
2600
+ if (turn.kind === "run") {
2601
+ return `${whatOf(turn.kind, turn.id)} has run ${minutes} min \u2014 no new run starts until it ends (one run reads the whole tray); ${deadlineText(cfg)}`;
2602
+ }
2603
+ return `a turn for ${whatOf(turn.kind, turn.id)} has run ${minutes} min \u2014 that conversation stays held (no second reply) until the run ends; ${deadlineText(cfg)}; other conversations are not held up by it`;
2604
+ }
2605
+ function overdueTurnLines(runs, cfg, now = Date.now()) {
2606
+ return runs.filter((run) => now - run.startedAt > TURN_OVERDUE_MS).map((run) => overdueTurnLine({ kind: run.kind, id: run.id, elapsedMs: now - run.startedAt }, cfg));
2607
+ }
2608
+ function restartHoldLines(turns, now = Date.now()) {
2609
+ return turns.restartHolds().map(
2610
+ ({ record, until, watching }) => watching || until === null ? `${whatOf(record.kind, record.id)} is held: OpenClaw continued its turn's session after the gateway restart (run ${watching ?? "unknown"}) \u2014 gated again once that run ends (handed off like any turn past 30 min)` : `${whatOf(record.kind, record.id)} is held for ${Math.max(0, Math.ceil((until - now) / 6e4))} more min: its turn was running when the gateway restarted, and OpenClaw may continue that turn's session`
2611
+ );
2612
+ }
2613
+ function hungTurnsReason(turns, cfg, now = Date.now()) {
2614
+ const single = turns.hungSingleRun();
2615
+ if (single) {
2616
+ return `${whatOf("run", single.runId)} has run ${Math.floor((now - single.startedAt) / 6e4)} min and is still going in OpenClaw \u2014 no new run starts while it lives (one run reads the whole tray; a second would answer the same cards), so the cards wait on the tray; ${deadlineText(cfg)}. \`openclaw agentchat release ${single.runId} --force\` lets a new run start (the old one may still answer)`;
2617
+ }
2618
+ if (turns.hungCount < MAX_HUNG_TURNS) return null;
2619
+ const held = turns.hungRuns().map((run) => `${whatOf(run.kind, run.id)} for ${Math.floor((now - run.startedAt) / 6e4)} min`).join(", ");
2620
+ return `${turns.hungCount} turns are hung in OpenClaw (${held}) \u2014 no gate calls until one ends, so other cards are waiting on the tray; ${deadlineText(cfg)}. \`openclaw agentchat release <conversation_id>\` lets go of one (its run may still answer, so a second reply is possible), or restart the gateway`;
2621
+ }
2622
+
2623
+ // src/binding/release.ts
2624
+ var RELEASE_METHOD = "agentchat.release";
2625
+ function releaseTurnFor(params) {
2626
+ const id = typeof params.id === "string" ? params.id.trim() : "";
2627
+ if (!id) return { ok: false, error: "a conversation (or invite) id is required" };
2628
+ const accountId = typeof params.accountId === "string" && params.accountId.trim() ? params.accountId.trim() : "default";
2629
+ const turns = findAccountTurns(accountId);
2630
+ if (!turns) return { ok: true, result: { released: false, reason: `the AgentChat account "${accountId}" has no turns in this gateway` } };
2631
+ return { ok: true, result: turns.release(id, { force: params.force === true }) };
2632
+ }
2633
+ function registerReleaseGatewayMethod(api) {
2634
+ api.registerGatewayMethod(
2635
+ RELEASE_METHOD,
2636
+ ({ params, respond }) => {
2637
+ const outcome = releaseTurnFor(params);
2638
+ if (!outcome.ok) {
2639
+ respond(false, void 0, { code: "INVALID_REQUEST", message: outcome.error });
2640
+ return;
2641
+ }
2642
+ respond(true, outcome.result);
2643
+ },
2644
+ { scope: "operator.admin" }
2645
+ );
2646
+ }
2647
+ function registerReleaseCli(api) {
2648
+ api.registerCli(
2649
+ ({ program }) => {
2650
+ const root = program.command(AGENTCHAT_CHANNEL_ID).description("The AgentChat integration");
2651
+ root.command("release <id>").description(
2652
+ `Let go of the turn holding a conversation (or invite) whose OpenClaw run never ended. The run is not stopped: if it answers later, the peer can get a second reply. A turn under ${TURN_OVERDUE_MS / 6e4} minutes is refused without --force.`
2653
+ ).option("--account <accountId>", "the AgentChat account", "default").option("--force", `release a turn that has run under ${TURN_OVERDUE_MS / 6e4} minutes (it is most likely still working: two replies are possible)`).option("--url <url>", "gateway URL (default: the configured gateway)").option("--token <token>", "gateway token (default: the configured one)").option("--json", "print the raw result").action(async (id, opts) => {
2654
+ const { callGatewayFromCli } = await import('openclaw/plugin-sdk/gateway-runtime');
2655
+ const result = await callGatewayFromCli(
2656
+ RELEASE_METHOD,
2657
+ { ...opts.url ? { url: opts.url } : {}, ...opts.token ? { token: opts.token } : {}, ...opts.json ? { json: true } : {} },
2658
+ { id, accountId: opts.account ?? "default", ...opts.force ? { force: true } : {} }
2659
+ );
2660
+ process.stdout.write(opts.json ? `${JSON.stringify(result)}
2661
+ ` : `${releaseLine(id, result)}
2662
+ `);
2663
+ });
2664
+ },
2665
+ {
2666
+ commands: [AGENTCHAT_CHANNEL_ID],
2667
+ descriptors: [{ name: AGENTCHAT_CHANNEL_ID, description: "The AgentChat integration (release a hung turn)", hasSubcommands: true }]
2668
+ }
2669
+ );
2670
+ }
2671
+ function releaseLine(id, result) {
2672
+ if (!result?.released) return `nothing released: ${result?.reason ?? "unknown"}`;
2673
+ if (result.what === "restart") return `released ${id} (held after a gateway restart) \u2014 it may be gated again now`;
2674
+ const what = result.what === "hung" ? "a hung turn" : "a running turn";
2675
+ return `released ${id} (${what}) \u2014 it may be gated again now; its OpenClaw run was not stopped, and if it still sends an answer the peer gets two replies`;
2676
+ }
2677
+
2678
+ // src/binding/run-observer.ts
2679
+ function registerRunObserver(api) {
2680
+ api.on("model_call_started", (event, ctx) => {
2681
+ observeRunStarted(event.runId, event.sessionKey ?? ctx?.sessionKey);
2682
+ });
2683
+ }
2684
+ function createLogger(options) {
2685
+ if (options.delegate) {
2686
+ return options.delegate;
2687
+ }
2007
2688
  const pinoLogger = pino__default.default({
2008
2689
  level: options.level,
2009
2690
  base: { plugin: "@agentchatme/openclaw" },
@@ -2065,85 +2746,12 @@ function createNoopMetrics() {
2065
2746
  incWake: () => void 0
2066
2747
  };
2067
2748
  }
2068
- function groupInviteFromRecord(record) {
2069
- if (!record || typeof record !== "object" || Array.isArray(record)) return null;
2070
- const row = record;
2071
- const inviteId = str(row.id);
2072
- const groupId = str(row.group_id);
2073
- if (!inviteId || !groupId) return null;
2074
- return {
2075
- inviteId,
2076
- groupId,
2077
- groupName: str(row.group_name) ?? "",
2078
- inviterHandle: (str(row.inviter_handle) ?? "").replace(/^@/, "")
2079
- };
2080
- }
2081
- function str(value) {
2082
- return typeof value === "string" && value.length > 0 ? value : void 0;
2083
- }
2084
- var INVITE_LEDGER_FILE = "invites.json";
2085
- var INVITE_LEDGER_MAX_AGE_MS = 30 * 24 * 60 * 6e4;
2086
- function inviteLedgerPath(accountId, stateDir) {
2087
- return path2__namespace.join(integrationStateDir(accountId, stateDir), INVITE_LEDGER_FILE);
2088
- }
2089
- var InviteLedger = class {
2090
- file;
2091
- now;
2092
- maxAgeMs;
2093
- onWriteError;
2094
- offered;
2095
- constructor(options) {
2096
- this.file = options.file ?? inviteLedgerPath(options.accountId, options.stateDir);
2097
- this.now = options.now ?? Date.now;
2098
- this.maxAgeMs = options.maxAgeMs ?? INVITE_LEDGER_MAX_AGE_MS;
2099
- this.onWriteError = options.onWriteError;
2100
- this.offered = this.read();
2101
- }
2102
- get path() {
2103
- return this.file;
2104
- }
2105
- get size() {
2106
- return this.offered.size;
2107
- }
2108
- /** True when a turn for this invite was started before (in this process or an earlier one). */
2109
- isOffered(inviteId) {
2110
- return this.offered.has(inviteId);
2111
- }
2112
- /** Record that a turn for this invite was admitted. Persists at once. */
2113
- markOffered(inviteId) {
2114
- this.offered.set(inviteId, new Date(this.now()).toISOString());
2115
- this.prune();
2116
- try {
2117
- writeJsonFile(this.file, { offered: Object.fromEntries(this.offered) });
2118
- } catch (err) {
2119
- this.onWriteError?.(err);
2120
- }
2121
- }
2122
- read() {
2123
- const raw = readJsonFile(this.file);
2124
- const out = /* @__PURE__ */ new Map();
2125
- if (!raw || typeof raw !== "object") return out;
2126
- const offered = raw.offered;
2127
- if (!offered || typeof offered !== "object" || Array.isArray(offered)) return out;
2128
- for (const [id, at] of Object.entries(offered)) {
2129
- if (typeof at === "string" && id.length > 0) out.set(id, at);
2130
- }
2131
- this.offered = out;
2132
- this.prune();
2133
- return this.offered;
2134
- }
2135
- prune() {
2136
- const cutoff = this.now() - this.maxAgeMs;
2137
- for (const [id, at] of this.offered) {
2138
- const t = Date.parse(at);
2139
- if (!Number.isFinite(t) || t < cutoff) this.offered.delete(id);
2140
- }
2141
- }
2142
- };
2143
2749
 
2144
2750
  // src/integration/socket.ts
2145
2751
  function wakeSourceOf(reason) {
2146
- return reason === "reminder" ? "reminder" : "other";
2752
+ if (reason === "reminder") return "reminder";
2753
+ if (reason === "unanswered") return "unanswered";
2754
+ return "other";
2147
2755
  }
2148
2756
  function realtimeOptionsFor(config, extra = {}) {
2149
2757
  return {
@@ -2151,6 +2759,10 @@ function realtimeOptionsFor(config, extra = {}) {
2151
2759
  baseUrl: config.apiBase.replace(/^http/, "ws").replace(/\/+$/, ""),
2152
2760
  clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
2153
2761
  ackOnReceipt: true,
2762
+ // `rewake`: the server re-wakes this socket while cards stay unanswered
2763
+ // (contract v1, D3) — the integration keeps no retry ladder of its own.
2764
+ // `heartbeat` is offered by default (the idle watchdog's proof of life).
2765
+ capabilities: { rewake: true },
2154
2766
  reconnect: true,
2155
2767
  reconnectInterval: config.reconnect.initialBackoffMs,
2156
2768
  maxReconnectInterval: config.reconnect.maxBackoffMs,
@@ -2159,169 +2771,118 @@ function realtimeOptionsFor(config, extra = {}) {
2159
2771
  };
2160
2772
  }
2161
2773
  var IntegrationSocket = class {
2162
- config;
2774
+ /** The SDK client: handed to the receive loop, which connects and disconnects it. */
2775
+ realtime;
2163
2776
  logger;
2164
2777
  handlers;
2165
2778
  metrics;
2166
- client;
2167
- createRealtime;
2168
- webSocket;
2169
2779
  now;
2170
- selfHandle;
2171
- realtime = null;
2172
- /** The SDK's state as last reported through its `state` event; `stopped` is set here only for a stop before any start. */
2780
+ /** The SDK's state as last reported through its `state` event. */
2173
2781
  state = "idle";
2174
2782
  connectedAt = null;
2783
+ bound = false;
2175
2784
  stopping = false;
2176
- frames = 0;
2177
- selfFiltered = 0;
2178
- wakes = 0;
2179
- invites = 0;
2785
+ unbind = [];
2786
+ wakeFrames = 0;
2180
2787
  disconnects = 0;
2181
2788
  constructor(options) {
2182
- this.config = options.config;
2183
2789
  this.logger = options.logger.child({ component: "socket" });
2184
2790
  this.handlers = options.handlers ?? {};
2185
2791
  this.metrics = options.metrics ?? createNoopMetrics();
2186
- this.client = options.client;
2187
- this.createRealtime = options.createRealtime ?? ((opts) => new agentchatme.RealtimeClient(opts));
2188
- this.webSocket = options.webSocket;
2189
2792
  this.now = options.now ?? Date.now;
2190
- this.selfHandle = this.config.agentHandle?.replace(/^@/, "").toLowerCase();
2793
+ const create = options.createRealtime ?? ((opts) => new agentchatme.RealtimeClient(opts));
2794
+ this.realtime = create(realtimeOptionsFor(options.config, { client: options.client, webSocket: options.webSocket }));
2191
2795
  this.metrics.setConnectionState(this.state);
2192
2796
  }
2193
- /**
2194
- * Open the socket. Idempotent. Resolves once the SDK has started its
2195
- * connect loop; a failure to resolve a WebSocket implementation is logged
2196
- * and left to the SDK's own retry. Never throws.
2197
- */
2198
- async start() {
2199
- if (this.realtime || this.stopping) return;
2200
- const realtime = this.createRealtime(realtimeOptionsFor(this.config, { client: this.client, webSocket: this.webSocket }));
2201
- this.realtime = realtime;
2202
- this.bind(realtime);
2203
- try {
2204
- await realtime.connect();
2205
- } catch (err) {
2206
- this.logger.warn({ err: describe3(err) }, "socket connect failed \u2014 the SDK retries on its own schedule");
2207
- }
2797
+ /** Attach the lifecycle handlers. Idempotent. The receive loop connects the client. */
2798
+ bind() {
2799
+ if (this.bound || this.stopping) return;
2800
+ this.bound = true;
2801
+ const realtime = this.realtime;
2802
+ this.unbind.push(
2803
+ realtime.on("state", (next, prev) => this.onState(next, prev)),
2804
+ realtime.onConnect(() => {
2805
+ const at = this.now();
2806
+ this.connectedAt = at;
2807
+ this.logger.info({ at: new Date(at).toISOString() }, "connected (HELLO accepted)");
2808
+ this.metrics.incWake({ source: "connect" });
2809
+ this.guard("onConnected", () => this.handlers.onConnected?.(at));
2810
+ }),
2811
+ realtime.onDisconnect((info) => {
2812
+ if (this.stopping) return;
2813
+ this.disconnects += 1;
2814
+ this.connectedAt = null;
2815
+ this.metrics.incDisconnect({ code: String(info.code), initiator: info.initiator });
2816
+ this.logger.info({ code: info.code, reason: info.reason, initiator: info.initiator }, "socket closed \u2014 the SDK decides what follows (backoff or blocked)");
2817
+ this.guard("onDisconnected", () => this.handlers.onDisconnected?.(info));
2818
+ }),
2819
+ realtime.on("blocked", (info) => {
2820
+ if (this.stopping) return;
2821
+ this.metrics.incError({ errorClass: "auth" });
2822
+ this.logger.warn(
2823
+ { code: info.code, reason: info.reason, retryInMs: info.retryInMs },
2824
+ "the server rejected the key during the handshake \u2014 the SDK retries a fresh HELLO on its own"
2825
+ );
2826
+ this.guard("onBlocked", () => this.handlers.onBlocked?.(info));
2827
+ }),
2828
+ realtime.onError((error) => {
2829
+ if (this.stopping) return;
2830
+ if (realtime.state === "blocked") {
2831
+ this.logger.debug({ err: error.message }, "SDK notice while blocked");
2832
+ return;
2833
+ }
2834
+ this.metrics.incError({ errorClass: classifyRealtimeError(error) });
2835
+ this.logger.debug({ err: error.message }, "socket error");
2836
+ this.guard("onError", () => this.handlers.onError?.(error));
2837
+ }),
2838
+ // The loop turns a wake frame into a cycle; here it is only labelled
2839
+ // by its reason for the log line and the metric.
2840
+ realtime.on("wake", (frame) => {
2841
+ this.wakeFrames += 1;
2842
+ const payload = frame.payload ?? {};
2843
+ const conversations = Array.isArray(payload.conversation_ids) ? payload.conversation_ids.length : void 0;
2844
+ this.metrics.incWake({ source: wakeSourceOf(payload.reason) });
2845
+ this.logger.info(
2846
+ {
2847
+ reason: payload.reason,
2848
+ step: payload.step,
2849
+ ...typeof payload.conversation_id === "string" ? { conversationId: payload.conversation_id } : {},
2850
+ ...conversations !== void 0 ? { conversations } : {}
2851
+ },
2852
+ "wake \u2014 server wake frame"
2853
+ );
2854
+ })
2855
+ );
2208
2856
  }
2209
- /** Close the socket for good; a stopped socket does not reconnect. Idempotent. */
2210
- async stop() {
2857
+ /** The loop has disconnected the client (or never started it): report `stopped`, detach. Idempotent. */
2858
+ stopped() {
2211
2859
  this.stopping = true;
2212
- const realtime = this.realtime;
2213
- this.realtime = null;
2214
2860
  this.connectedAt = null;
2215
- if (realtime) {
2861
+ for (const off of this.unbind.splice(0)) {
2216
2862
  try {
2217
- realtime.disconnect();
2218
- } catch (err) {
2219
- this.logger.warn({ err: describe3(err) }, "socket disconnect threw \u2014 continuing");
2863
+ off();
2864
+ } catch {
2220
2865
  }
2221
2866
  }
2222
2867
  if (this.state !== "stopped") this.onState("stopped", this.state);
2223
2868
  }
2224
2869
  getHealth() {
2225
- return {
2226
- state: this.state,
2227
- connectedAt: this.connectedAt,
2228
- counters: { frames: this.frames, selfFiltered: this.selfFiltered, wakes: this.wakes, invites: this.invites, disconnects: this.disconnects }
2229
- };
2230
- }
2231
- // ─── Internals ─────────────────────────────────────────────────────
2232
- bind(realtime) {
2233
- realtime.on("state", (next, prev) => this.onState(next, prev));
2234
- realtime.onConnect(() => {
2235
- const at = this.now();
2236
- this.connectedAt = at;
2237
- this.logger.info({ at: new Date(at).toISOString() }, "connected (HELLO accepted)");
2238
- this.guard("onConnected", () => this.handlers.onConnected?.(at));
2239
- this.wake("connect", {});
2240
- });
2241
- realtime.onDisconnect((info) => {
2242
- if (this.stopping) return;
2243
- this.disconnects += 1;
2244
- this.connectedAt = null;
2245
- this.metrics.incDisconnect({ code: String(info.code), initiator: info.initiator });
2246
- this.logger.info({ code: info.code, reason: info.reason, initiator: info.initiator }, "socket closed \u2014 the SDK decides what follows (backoff or blocked)");
2247
- this.guard("onDisconnected", () => this.handlers.onDisconnected?.(info));
2248
- });
2249
- realtime.on("blocked", (info) => {
2250
- if (this.stopping) return;
2251
- this.metrics.incError({ errorClass: "auth" });
2252
- this.logger.warn(
2253
- { code: info.code, reason: info.reason, retryInMs: info.retryInMs },
2254
- "the server rejected the key during the handshake \u2014 the SDK retries a fresh HELLO on its own"
2255
- );
2256
- this.guard("onBlocked", () => this.handlers.onBlocked?.(info));
2257
- });
2258
- realtime.onError((error) => {
2259
- if (this.stopping) return;
2260
- if (realtime.state === "blocked") {
2261
- this.logger.debug({ err: error.message }, "SDK notice while blocked");
2262
- return;
2263
- }
2264
- this.metrics.incError({ errorClass: classifyRealtimeError(error) });
2265
- this.logger.debug({ err: error.message }, "socket error");
2266
- this.guard("onError", () => this.handlers.onError?.(error));
2267
- });
2268
- realtime.on("message.new", (message) => this.onMessageNew(message));
2269
- realtime.on("wake", (frame) => this.onWakeFrame(frame));
2270
- realtime.on("group.invite.received", (message) => this.onInvite(message));
2271
- }
2272
- onMessageNew(message) {
2273
- this.frames += 1;
2274
- const payload = message.payload ?? {};
2275
- const senderRaw = payload.sender ?? payload.from ?? "";
2276
- const sender = typeof senderRaw === "string" ? senderRaw.replace(/^@/, "").toLowerCase() : "";
2277
- const detail = {
2278
- ...typeof payload.conversation_id === "string" ? { conversationId: payload.conversation_id } : {},
2279
- ...typeof payload.id === "string" ? { messageId: payload.id } : {},
2280
- ...sender ? { from: sender } : {}
2281
- };
2282
- if (this.selfHandle && sender === this.selfHandle) {
2283
- this.selfFiltered += 1;
2284
- this.logger.debug(detail, "own echo \u2014 not a wake");
2285
- return;
2286
- }
2287
- this.logger.debug(detail, "wake \u2014 message.new");
2288
- this.wake("message", detail);
2289
- }
2290
- onWakeFrame(frame) {
2291
- this.frames += 1;
2292
- const reason = frame.payload?.reason;
2293
- const detail = { conversationId: frame.payload.conversation_id };
2294
- this.logger.info({ ...detail, reason, step: frame.payload.step }, "wake \u2014 server wake frame");
2295
- this.wake(wakeSourceOf(reason), detail);
2296
- }
2297
- onInvite(message) {
2298
- this.frames += 1;
2299
- const invite = groupInviteFromRecord(message.payload);
2300
- if (!invite) {
2301
- this.logger.warn({ keys: Object.keys(message.payload ?? {}).sort() }, "group.invite.received without ids \u2014 dropped");
2302
- return;
2303
- }
2304
- this.invites += 1;
2305
- this.guard("onGroupInvite", () => this.handlers.onGroupInvite?.(invite));
2306
- }
2307
- wake(source, detail) {
2308
- this.wakes += 1;
2309
- this.metrics.incWake({ source });
2310
- this.guard("onWake", () => this.handlers.onWake?.(source, detail));
2870
+ return { state: this.state, connectedAt: this.connectedAt, counters: { wakeFrames: this.wakeFrames, disconnects: this.disconnects } };
2311
2871
  }
2312
2872
  /** The SDK's state transition, mirrored for the health probe and the gauge, then handed on. */
2313
2873
  onState(next, prev) {
2874
+ if (this.state === next) return;
2314
2875
  this.state = next;
2315
2876
  this.metrics.setConnectionState(next);
2316
2877
  this.logger.debug({ from: prev, to: next }, "socket state");
2317
2878
  this.guard("onStateChanged", () => this.handlers.onStateChanged?.(next, prev));
2318
2879
  }
2319
- /** A failing handler never takes the socket down; the next frame wakes again and the tray keeps the cards. */
2880
+ /** A failing handler never takes the socket down. */
2320
2881
  guard(name, fn) {
2321
2882
  try {
2322
2883
  fn();
2323
2884
  } catch (err) {
2324
- this.logger.error({ err: describe3(err), handler: name }, "handler threw \u2014 continuing");
2885
+ this.logger.error({ err: describe4(err), handler: name }, "handler threw \u2014 continuing");
2325
2886
  }
2326
2887
  }
2327
2888
  };
@@ -2332,7 +2893,7 @@ function classifyRealtimeError(error) {
2332
2893
  if (error.name === "ConnectionError" || /websocket|hello|handshake|liveness|reconnecting|sync drain|sync ack/i.test(message)) return "transport";
2333
2894
  return "other";
2334
2895
  }
2335
- function describe3(err) {
2896
+ function describe4(err) {
2336
2897
  return err instanceof Error ? err.message : String(err);
2337
2898
  }
2338
2899
 
@@ -2362,8 +2923,6 @@ function registerIntegration(params) {
2362
2923
  }
2363
2924
  let built = null;
2364
2925
  const handlers = {
2365
- onWake: (source, detail) => built?.handlers.onWake?.(source, detail),
2366
- onGroupInvite: (invite) => built?.handlers.onGroupInvite?.(invite),
2367
2926
  onConnected: (at) => built?.handlers.onConnected?.(at),
2368
2927
  onDisconnected: (info) => built?.handlers.onDisconnected?.(info),
2369
2928
  onBlocked: (info) => built?.handlers.onBlocked?.(info),
@@ -2375,19 +2934,20 @@ function registerIntegration(params) {
2375
2934
  built = params.build(socket);
2376
2935
  const entry = {
2377
2936
  socket,
2378
- invoker: built.invoker,
2937
+ loop: built.loop,
2379
2938
  texts: built.texts ?? null,
2939
+ textsCache: built.textsCache ?? null,
2380
2940
  metrics: params.socketOptions?.metrics ?? null,
2381
2941
  config: params.config,
2382
2942
  logger: params.logger
2383
2943
  };
2384
2944
  registry.set(params.accountId, entry);
2945
+ socket.bind();
2385
2946
  try {
2386
- await socket.start();
2947
+ await built.loop?.loop.start();
2387
2948
  } catch (err) {
2388
2949
  registry.delete(params.accountId);
2389
- built.invoker?.stop();
2390
- built.texts?.stop();
2950
+ await stopEntry(entry);
2391
2951
  throw err;
2392
2952
  }
2393
2953
  return entry;
@@ -2402,591 +2962,272 @@ function unregisterIntegration(accountId) {
2402
2962
  });
2403
2963
  }
2404
2964
  async function stopEntry(entry) {
2405
- entry.invoker?.stop();
2406
- entry.texts?.stop();
2407
2965
  try {
2408
- await entry.socket.stop();
2966
+ await entry.loop?.stop();
2409
2967
  } catch (err) {
2410
- entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "socket.stop threw during unregister");
2411
- }
2412
- }
2413
- function getIntegration(accountId) {
2414
- return registry.get(accountId);
2415
- }
2416
-
2417
- // src/integration/wake.ts
2418
- var DEFAULT_DEBOUNCE_MS = 2e3;
2419
- var DEFAULT_MAX_WINDOW_MS = 6e3;
2420
- var WakeCoalescer = class {
2421
- onFire;
2422
- onDelayedWake;
2423
- debounceMs;
2424
- maxWindowMs;
2425
- now;
2426
- _setTimeout;
2427
- _clearTimeout;
2428
- timer = null;
2429
- burstStartedAt = null;
2430
- delayed = null;
2431
- delayedDeadline = null;
2432
- stopped = false;
2433
- wakes = 0;
2434
- absorbed = 0;
2435
- fires = 0;
2436
- constructor(options) {
2437
- const debounce = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
2438
- if (!(debounce >= 0)) throw new RangeError("debounceMs must be >= 0");
2439
- const maxWindow = options.maxWindowMs ?? DEFAULT_MAX_WINDOW_MS;
2440
- if (!(maxWindow >= debounce)) throw new RangeError("maxWindowMs must be >= debounceMs");
2441
- this.onFire = options.onFire;
2442
- this.onDelayedWake = options.onDelayedWake;
2443
- this.debounceMs = debounce;
2444
- this.maxWindowMs = maxWindow;
2445
- this.now = options.now ?? Date.now;
2446
- this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
2447
- this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h));
2448
- }
2449
- /** True while a debounce timer is armed. */
2450
- get armed() {
2451
- return this.timer !== null;
2452
- }
2453
- /** True while a retry wake is scheduled and has not fired. */
2454
- get delayedPending() {
2455
- return this.delayed !== null;
2968
+ entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "receive loop stop threw during unregister");
2456
2969
  }
2457
- /**
2458
- * A wake. The first one of a burst arms the window; every later one is
2459
- * absorbed and restarts it (trailing edge), never past the burst's cap.
2460
- */
2461
- wake() {
2462
- if (this.stopped) return;
2463
- this.wakes += 1;
2464
- const now = this.now();
2465
- if (this.timer === null) {
2466
- this.burstStartedAt = now;
2467
- this.timer = this._setTimeout(() => this.fire(), this.debounceMs);
2468
- return;
2469
- }
2470
- this.absorbed += 1;
2471
- const capAt = (this.burstStartedAt ?? now) + this.maxWindowMs;
2472
- const delay = Math.max(0, Math.min(this.debounceMs, capAt - now));
2473
- this._clearTimeout(this.timer);
2474
- this.timer = this._setTimeout(() => this.fire(), delay);
2475
- }
2476
- /** A delayed wake (retry ladder). The sooner pending deadline is kept. */
2477
- wakeAfter(delayMs) {
2478
- if (this.stopped) return;
2479
- const delay = Math.max(0, delayMs);
2480
- const deadline = this.now() + delay;
2481
- if (this.delayed !== null) {
2482
- if (this.delayedDeadline !== null && this.delayedDeadline <= deadline) {
2483
- return;
2484
- }
2485
- this._clearTimeout(this.delayed);
2486
- }
2487
- this.delayedDeadline = deadline;
2488
- this.delayed = this._setTimeout(() => {
2489
- this.delayed = null;
2490
- this.delayedDeadline = null;
2491
- if (this.stopped) return;
2492
- try {
2493
- this.onDelayedWake?.();
2494
- } catch {
2495
- }
2496
- this.wake();
2497
- }, delay);
2498
- }
2499
- /** Cancel everything; later wakes are ignored. */
2500
- stop() {
2501
- this.stopped = true;
2502
- if (this.timer !== null) {
2503
- this._clearTimeout(this.timer);
2504
- this.timer = null;
2505
- this.burstStartedAt = null;
2506
- }
2507
- if (this.delayed !== null) {
2508
- this._clearTimeout(this.delayed);
2509
- this.delayed = null;
2510
- this.delayedDeadline = null;
2511
- }
2512
- }
2513
- fire() {
2514
- this.timer = null;
2515
- this.burstStartedAt = null;
2516
- if (this.stopped) return;
2517
- this.fires += 1;
2970
+ if (!entry.loop) {
2518
2971
  try {
2519
- this.onFire();
2972
+ entry.socket.realtime.disconnect();
2520
2973
  } catch {
2521
2974
  }
2522
2975
  }
2523
- };
2976
+ entry.socket.stopped();
2977
+ entry.textsCache?.stop();
2978
+ }
2979
+ function getIntegration(accountId) {
2980
+ return registry.get(accountId);
2981
+ }
2982
+ function listActiveAccounts() {
2983
+ return [...registry.keys()];
2984
+ }
2524
2985
 
2525
- // src/integration/invoker.ts
2526
- var RETRY_LADDER_MS = [6e4, 3e5, 18e5];
2527
- var AgentInvoker = class {
2528
- accountId;
2529
- agentId;
2530
- client;
2531
- callModel;
2532
- startTurn;
2533
- texts;
2534
- invites;
2535
- logger;
2536
- metrics;
2537
- readiness;
2538
- gateEnabled;
2539
- ladder;
2540
- now;
2541
- coalescer;
2542
- cycleDue = false;
2543
- running = null;
2544
- stopped = false;
2545
- pendingInvites = [];
2546
- invitesDirty = false;
2547
- retryRung = 0;
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;
2560
- cycles = 0;
2561
- turns = 0;
2562
- inviteTurns = 0;
2563
- constructor(options) {
2564
- this.accountId = options.accountId;
2565
- this.agentId = options.agentId;
2566
- this.client = options.client;
2567
- this.callModel = options.callModel;
2568
- this.startTurn = options.startTurn;
2569
- this.texts = options.texts;
2570
- this.invites = options.invites;
2571
- this.logger = options.logger.child({ component: "integration", accountId: options.accountId });
2572
- this.metrics = options.metrics ?? createNoopMetrics();
2573
- this.readiness = options.readiness ?? (() => ({ ready: true }));
2574
- this.gateEnabled = options.gateEnabled ?? true;
2575
- this.ladder = options.retryLadderMs ?? RETRY_LADDER_MS;
2576
- this.now = options.now ?? Date.now;
2577
- this.coalescer = new WakeCoalescer({
2578
- onFire: () => this.onWakeFired(),
2579
- onDelayedWake: () => {
2580
- this.logger.debug({ source: "retry" }, "wake");
2581
- this.metrics.incWake({ source: "retry" });
2582
- },
2583
- debounceMs: options.debounceMs ?? DEFAULT_DEBOUNCE_MS,
2584
- now: this.now,
2585
- ...options.setTimeout ? { setTimeout: options.setTimeout } : {},
2586
- ...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}
2587
- });
2588
- }
2589
- // ─── wakes ──────────────────────────────────────────────────────────
2590
- /** A wake from the socket (a frame, a connect, a reminder) or any other source. Coalesced, then cycled. */
2591
- wake(source) {
2592
- if (this.stopped) return;
2593
- this.logger.debug({ source }, "wake");
2594
- this.coalescer.wake();
2595
- }
2596
- /**
2597
- * The second wake kind. An invite already offered (this process or an
2598
- * earlier one, per the ledger) or already pending is ignored, so an
2599
- * invite seen live and again on a connect-time catch-up is decided once.
2600
- * Returns true when newly queued.
2601
- */
2602
- groupInvite(invite, source) {
2603
- if (this.stopped) return false;
2604
- if (this.invites.isOffered(invite.inviteId)) return false;
2605
- if (this.pendingInvites.some((pending) => pending.inviteId === invite.inviteId)) return false;
2606
- this.logger.info(
2607
- { groupId: invite.groupId, groupName: invite.groupName, inviter: invite.inviterHandle, inviteId: invite.inviteId, source },
2608
- "group invite \u2014 queuing one invite turn"
2609
- );
2610
- this.pendingInvites.push(invite);
2611
- this.invitesDirty = true;
2612
- this.schedule();
2613
- return true;
2614
- }
2615
- /** Cancel timers; a cycle in flight finishes on its own. */
2616
- stop() {
2617
- this.stopped = true;
2618
- this.coalescer.stop();
2619
- }
2620
- /** The promise of the work currently running, for tests and for graceful stops. */
2621
- settled() {
2622
- return this.running ?? Promise.resolve();
2623
- }
2624
- counters() {
2625
- return {
2626
- cycles: this.cycles,
2627
- turns: this.turns,
2628
- inviteTurns: this.inviteTurns,
2629
- turnsInFlight: this.turnsInFlight,
2630
- wakes: this.coalescer.wakes,
2631
- absorbed: this.coalescer.absorbed,
2632
- retryRung: this.retryRung,
2633
- pendingInvites: this.pendingInvites.length
2634
- };
2635
- }
2636
- // ─── worker ─────────────────────────────────────────────────────────
2637
- onWakeFired() {
2638
- this.cycleDue = true;
2639
- if (this.pendingInvites.length > 0) this.invitesDirty = true;
2640
- this.schedule();
2641
- }
2642
- /** Run the worker if idle. One cycle at a time; work that lands mid-cycle runs afterwards. */
2643
- schedule() {
2644
- if (this.running) return;
2645
- this.running = this.drain().finally(() => {
2646
- this.running = null;
2647
- if (!this.stopped && (this.cycleDue || this.invitesDirty)) this.schedule();
2648
- });
2649
- }
2650
- async drain() {
2651
- while (!this.stopped) {
2652
- if (this.invitesDirty) {
2653
- this.invitesDirty = false;
2654
- await this.runInviteTurns();
2655
- continue;
2656
- }
2657
- if (this.cycleDue) {
2658
- this.cycleDue = false;
2659
- try {
2660
- await this.runCycle();
2661
- } catch (err) {
2662
- this.logger.error({ err: describe4(err), ...this.retry() }, "cycle failed with an unhandled error \u2014 re-waking later");
2663
- }
2664
- continue;
2665
- }
2666
- return;
2667
- }
2668
- }
2669
- // ─── one cycle ──────────────────────────────────────────────────────
2670
- /** Read the tray, gate it, start a turn per reply. Public so tests can drive one cycle. */
2671
- async runCycle() {
2672
- this.cycles += 1;
2673
- const started = this.now();
2674
- let tray;
2675
- try {
2676
- tray = await this.client.inbox.tray({ waitMs: 0 });
2677
- } catch (err) {
2678
- this.logger.warn({ err: describe4(err), ...this.retry() }, "tray read failed \u2014 re-waking later");
2679
- return this.result("tray_failed", 0, false, started, describe4(err));
2680
- }
2681
- const allCards = agentchatme.gate.cardsOf(tray);
2682
- const truncated = tray.truncated === true;
2683
- if (allCards.length === 0) {
2684
- this.logger.info({ deferred: tray.deferred ?? 0 }, "tray empty \u2014 nothing to decide");
2685
- this.retryRung = 0;
2686
- return this.result("empty", 0, truncated, started);
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
- }
2695
- const texts = await this.texts.ensure();
2696
- if (!texts) {
2697
- this.logger.warn({ cards: cards.length, ...this.retry() }, "served texts not available \u2014 not gating; the cards wait on the tray");
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");
2710
- }
2711
- let result;
2712
- if (!this.gateEnabled) {
2713
- result = await this.runUngated(cards.length, texts, truncated, started);
2714
- } else {
2715
- const trayToGate = skippedInFlight > 0 ? { ...tray, conversations: cards } : tray;
2716
- result = await this.runGated(trayToGate, cards.length, texts, truncated, started, skippedInFlight);
2717
- }
2718
- if (skippedInFlight > 0) result = { ...result, skippedInFlight };
2719
- if (truncated && result.outcome !== "fail_closed") {
2720
- this.logger.info({}, "tray truncated \u2014 waking again for the rest");
2721
- this.coalescer.wake();
2722
- }
2723
- return result;
2724
- }
2725
- /** Gate off: the agent judges in-turn with the hosted tools. One turn, nothing recorded here. */
2726
- async runUngated(cards, texts, truncated, started) {
2727
- this.logger.info({ cards }, "gate off \u2014 starting one turn with the served wake instruction");
2728
- const sessionKey = wakeSessionKey(this.agentId, this.now());
2729
- this.logger.info({ sessionKey }, "turn start");
2730
- const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts), lane: integrationLane(this.accountId) });
2986
+ // src/integration/turns.ts
2987
+ function createLoopTurnStarter(options) {
2988
+ const now = options.now ?? Date.now;
2989
+ return async (request) => {
2990
+ const id = request.kind === "reply" ? request.conversationId : request.invite.invite_id;
2991
+ const sessionKey = request.kind === "reply" ? wakeSessionKey(options.agentId, now()) : inviteSessionKey(options.agentId, id, now());
2992
+ const watch = options.turns.admission(request.kind, id);
2993
+ const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) });
2731
2994
  if (!admission.ran) {
2732
- this.logger.warn({ sessionKey, error: admission.error, ...this.retry() }, "turn not started \u2014 re-waking later");
2733
- } else {
2734
- this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)");
2735
- this.retryRung = 0;
2736
- }
2737
- return {
2738
- ...this.result("gate_off", cards, truncated, started),
2739
- turnsStarted: admission.ran ? 1 : 0,
2740
- turnsRefused: admission.ran ? 0 : 1
2741
- };
2742
- }
2743
- async runGated(tray, cards, texts, truncated, started, skippedInFlight = 0) {
2744
- const decided = await agentchatme.gate.run({ tray, callModel: this.callModel, client: this.client, toolNamer: OPENCLAW_TOOL_NAMER });
2745
- const latencyMs = this.now() - started;
2746
- const counts = { reply: 0, dismiss: 0, defer: 0 };
2747
- for (const verdict of decided.verdicts) counts[verdict.decision] += 1;
2748
- if (decided.outcome === "fail_closed") {
2749
- this.logger.warn({ cards, failure: decided.failure, latencyMs, ...this.retry() }, "gate failed closed \u2014 nothing recorded, no turn started");
2750
- return { ...this.result("fail_closed", cards, truncated, started, decided.failure), undecided: cards, latencyMs };
2751
- }
2752
- if (decided.outcome === "empty") {
2753
- this.retryRung = 0;
2754
- return this.result("empty", cards, truncated, started);
2755
- }
2756
- let turnsStarted = 0;
2757
- let turnsRefused = 0;
2758
- const recordFailures = decided.recordFailures.length;
2759
- const recorded = decided.recorded;
2760
- for (const entry of decided.reply) {
2761
- if (this.replyTurnsInFlight.has(entry.conversationId)) {
2762
- this.skippedWhileInFlight = true;
2763
- continue;
2764
- }
2765
- const sessionKey = wakeSessionKey(this.agentId, this.now());
2766
- this.logger.info({ sessionKey, conversationId: entry.conversationId }, "turn start");
2767
- const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts, entry.conversationId), lane: integrationLane(this.accountId) });
2768
- if (!admission.ran) {
2769
- turnsRefused += 1;
2770
- this.logger.warn({ sessionKey, conversationId: entry.conversationId, error: admission.error }, "turn not started \u2014 reply not recorded; the conversation stays unread");
2771
- continue;
2995
+ options.turns.admitted(watch);
2996
+ return { started: false, error: admission.error };
2997
+ }
2998
+ options.turns.started({
2999
+ runId: admission.runId,
3000
+ kind: request.kind,
3001
+ id,
3002
+ anchor: request.kind === "reply" ? request.anchor : null,
3003
+ sessionKey: admission.sessionKey,
3004
+ startedAt: now(),
3005
+ owner: options.owner,
3006
+ // What the after-turn rule compares when the turn ends outside the
3007
+ // kit's watch (handed off, or after a restart).
3008
+ ...request.kind === "reply" ? { card: request.card, category: request.category } : { invite: request.invite }
3009
+ }, { admission: watch });
3010
+ options.logger.info(
3011
+ { kind: request.kind, sessionKey, runId: admission.runId, ...request.kind === "reply" ? { conversationId: id } : { inviteId: id } },
3012
+ request.kind === "reply" ? "turn start" : "group-invite turn start"
3013
+ );
3014
+ const done = admission.done.then((outcome) => {
3015
+ if (outcome.status === "gone") {
3016
+ options.logger.warn({ sessionKey, runId: outcome.runId }, "turn end not confirmed: the plugin runtime is gone \u2014 its card stays held");
3017
+ return { status: "still_running", detail: "the plugin runtime is gone" };
2772
3018
  }
2773
- turnsStarted += 1;
2774
- this.replyTurnsInFlight.add(entry.conversationId);
2775
- this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)", entry);
2776
- }
2777
- const summary = {
2778
- cards,
2779
- reply: counts.reply,
2780
- dismiss: counts.dismiss,
2781
- defer: counts.defer,
2782
- undecided: decided.undecided.length,
2783
- recorded,
2784
- recordFailures,
2785
- turnsStarted,
2786
- turnsRefused,
2787
- skippedInFlight,
2788
- latencyMs
2789
- };
2790
- if (turnsRefused > 0) {
2791
- this.logger.warn({ ...summary, ...this.retry() }, "gate \u2014 some turns were refused; re-waking later");
2792
- } else if (recordFailures > 0 || decided.undecided.length > 0) {
2793
- this.logger.warn({ ...summary, ...this.retry() }, "gate \u2014 cards left on the tray; re-waking later");
2794
- } else {
2795
- this.retryRung = 0;
2796
- this.logger.info(summary, "gate");
3019
+ const end = turnEndOf(outcome);
3020
+ void options.turns.ended(admission.runId, end);
3021
+ options.logger[outcome.status === "ok" ? "info" : "warn"](
3022
+ {
3023
+ sessionKey,
3024
+ runId: outcome.runId,
3025
+ status: outcome.status,
3026
+ ...outcome.error ? { error: outcome.error } : {},
3027
+ ...outcome.elapsedMs !== void 0 ? { elapsedMs: outcome.elapsedMs } : {},
3028
+ agentchatCalls: outcome.agentchatCalls ?? null
3029
+ },
3030
+ request.kind === "reply" ? "turn ended (final text discarded; the send is a hosted-tool call)" : "group-invite turn ended"
3031
+ );
3032
+ return end;
3033
+ });
3034
+ return { started: true, done };
3035
+ };
3036
+ }
3037
+ function turnEndOf(outcome) {
3038
+ const agentchatCalls = outcome.agentchatCalls ?? null;
3039
+ if (outcome.status === "ok" && !outcome.error) return { status: "completed", agentchatCalls };
3040
+ return { status: "failed", agentchatCalls, detail: outcome.error ?? `run ended: ${outcome.status ?? "unknown"}` };
3041
+ }
3042
+
3043
+ // src/integration/loop.ts
3044
+ var generation = 0;
3045
+ function createIntegrationLoop(options) {
3046
+ const logger = options.logger.child({ component: "integration", accountId: options.accountId });
3047
+ const metrics = options.metrics ?? createNoopMetrics();
3048
+ const now = options.now ?? Date.now;
3049
+ generation += 1;
3050
+ const owner = `${options.accountId}#${generation}`;
3051
+ const gateEnabled = options.gateEnabled ?? true;
3052
+ let unreadyReason = null;
3053
+ const readiness = options.readiness ? () => {
3054
+ const ready = options.readiness();
3055
+ if (ready.ready) {
3056
+ if (unreadyReason !== null) logger.info({}, "turns can start again \u2014 gating resumes");
3057
+ unreadyReason = null;
3058
+ return ready;
3059
+ }
3060
+ if (unreadyReason !== ready.reason) logger.warn({ reason: ready.reason }, "not gating \u2014 no turn can start now; the cards wait on the tray");
3061
+ unreadyReason = ready.reason;
3062
+ return ready;
3063
+ } : void 0;
3064
+ const startTurn = createLoopTurnStarter({ accountId: options.accountId, agentId: options.agentId, startRun: options.startRun, turns: options.turns, owner, logger, now });
3065
+ const loop = new agentchatme.integration.ReceiveLoop({
3066
+ client: options.client,
3067
+ texts: options.texts,
3068
+ mode: gateEnabled ? "gateCall" : "singleRun",
3069
+ ...gateEnabled ? { callModel: options.callModel, startTurn } : { startRun: singleRunStarter(options, owner, logger, now) },
3070
+ socket: options.socket,
3071
+ ...options.handle ? { handle: options.handle } : {},
3072
+ toolNamer: OPENCLAW_TOOL_NAMER,
3073
+ // One account's turns run on one OpenClaw lane anyway; one slot keeps
3074
+ // the rest held out of the gate (no second model call decides them).
3075
+ maxConcurrentTurns: 1,
3076
+ tracker: options.turns.tracker,
3077
+ ...readiness ? { readiness } : {},
3078
+ ...options.paceMs !== void 0 ? { paceMs: options.paceMs } : {},
3079
+ ...options.quietMs !== void 0 ? { quietMs: options.quietMs } : {},
3080
+ ...options.maxMs !== void 0 ? { maxMs: options.maxMs } : {},
3081
+ now,
3082
+ ...options.setTimeout ? { setTimeout: options.setTimeout } : {},
3083
+ ...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {},
3084
+ onEvent: (event) => logEvent(event, logger, metrics)
3085
+ });
3086
+ const inLoopContext = async_hooks.AsyncLocalStorage.snapshot();
3087
+ options.turns.setLive(
3088
+ owner,
3089
+ () => inLoopContext(() => loop.wake()),
3090
+ (fn) => inLoopContext(fn)
3091
+ );
3092
+ return {
3093
+ loop,
3094
+ async stop() {
3095
+ options.turns.clearLive(owner);
3096
+ await loop.stop();
2797
3097
  }
2798
- return { ...this.result("decided", cards, truncated, started), ...summary };
2799
- }
2800
- result(outcome, cards, truncated, started, failure = null) {
2801
- return {
2802
- outcome,
2803
- cards,
2804
- reply: 0,
2805
- dismiss: 0,
2806
- defer: 0,
2807
- undecided: 0,
2808
- recorded: 0,
2809
- recordFailures: 0,
2810
- turnsStarted: 0,
2811
- turnsRefused: 0,
2812
- skippedInFlight: 0,
2813
- truncated,
2814
- latencyMs: this.now() - started,
2815
- failure
3098
+ };
3099
+ }
3100
+ function singleRunStarter(options, owner, logger, now) {
3101
+ return async (request) => {
3102
+ const hung = options.turns.hungSingleRun();
3103
+ if (hung) {
3104
+ logger.warn({ runId: hung.runId }, "gate off \u2014 a handed-off run is still going; no second run while it lives (the cards wait on the tray)");
3105
+ return { status: "not_started", detail: `the gate-off run ${hung.runId} is still going` };
3106
+ }
3107
+ const sessionKey = wakeSessionKey(options.agentId, now());
3108
+ logger.info({ sessionKey, cards: request.cards, invites: request.invites }, "gate off \u2014 one run with the served wake instruction");
3109
+ const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) });
3110
+ if (!admission.ran) return { status: "not_started", detail: admission.error };
3111
+ let letGo = () => {
2816
3112
  };
2817
- }
2818
- /** Arm the next rung (or report why not). Returned as log fields so every caller writes ONE line. */
2819
- retry() {
2820
- if (this.coalescer.delayedPending) {
2821
- return { retry: { kind: "pending" } };
2822
- }
2823
- if (this.retryRung >= this.ladder.length) {
2824
- return { retry: { kind: "exhausted" } };
3113
+ const handedOff = new Promise((resolve) => {
3114
+ letGo = () => resolve("let_go");
3115
+ });
3116
+ const { runId } = admission;
3117
+ options.turns.started({ runId, kind: "run", id: runId, anchor: null, sessionKey: admission.sessionKey, startedAt: now(), owner }, { letGo });
3118
+ const ended = admission.done.then((outcome) => {
3119
+ if (outcome.status !== "gone") void options.turns.ended(runId);
3120
+ logger[outcome.status === "ok" ? "info" : "warn"]({ sessionKey, runId, status: outcome.status, agentchatCalls: outcome.agentchatCalls ?? null }, "gate off \u2014 run ended");
3121
+ return outcome;
3122
+ });
3123
+ const first = await Promise.race([ended, handedOff]);
3124
+ if (first === "let_go") {
3125
+ logger.warn({ sessionKey, runId }, "gate off \u2014 the run is still going after 30 min; no new run starts until it ends (or `openclaw agentchat release <run id> --force`)");
3126
+ return { status: "failed", detail: "the run was handed off while still going" };
2825
3127
  }
2826
- const delayMs = this.ladder[this.retryRung] ?? this.ladder[this.ladder.length - 1] ?? 6e4;
2827
- this.retryRung += 1;
2828
- this.coalescer.wakeAfter(delayMs);
2829
- return { retry: { kind: "armed", delayMs, rung: this.retryRung } };
2830
- }
2831
- // ─── turns ──────────────────────────────────────────────────────────
2832
- /**
2833
- * Book an admitted turn and log its end whenever it comes. The cycle moves
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.
2841
- */
2842
- admitted(sessionKey, admission, completeLine, reply) {
2843
- this.turns += 1;
2844
- this.turnsInFlight += 1;
2845
- void admission.done.then(
2846
- async (outcome) => {
2847
- this.turnsInFlight -= 1;
2848
- const completed = outcome.ran && outcome.status === "ok" && !outcome.error;
2849
- this.logger[completed ? "info" : "warn"](
2850
- { sessionKey, runId: outcome.runId, status: outcome.status, ...outcome.error ? { error: outcome.error } : {} },
2851
- completeLine
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
- if (await this.decidedInTurn(reply)) {
2863
- this.logger.info(
2864
- { sessionKey, conversationId: reply.conversationId },
2865
- "the turn recorded its own verdict \u2014 reply not recorded again"
2866
- );
2867
- return;
2868
- }
2869
- await this.recordReply(sessionKey, reply);
2870
- } finally {
2871
- this.replyTurnEnded(reply.conversationId);
2872
- }
2873
- },
2874
- async (err) => {
2875
- this.turnsInFlight -= 1;
2876
- this.logger.warn({ sessionKey, runId: admission.runId, err: describe4(err) }, `${completeLine} \u2014 the wait failed`);
2877
- if (reply) {
2878
- this.logger.warn(
2879
- { sessionKey, conversationId: reply.conversationId, err: describe4(err), ...this.retry() },
2880
- "turn did not complete \u2014 reply not recorded; the conversation stays unread and is gated again"
2881
- );
2882
- this.replyTurnEnded(reply.conversationId);
3128
+ return first.status === "ok" && !first.error ? { status: "completed" } : { status: "failed", detail: first.error ?? `run ended: ${first.status ?? "unknown"}` };
3129
+ };
3130
+ }
3131
+ function logEvent(event, logger, metrics) {
3132
+ switch (event.type) {
3133
+ case "wake":
3134
+ if (event.source === "message") metrics.incWake({ source: "message" });
3135
+ else if (event.source === "invite") metrics.incWake({ source: "invite" });
3136
+ logger.debug({ source: event.source, ...event.conversationId ? { conversationId: event.conversationId } : {} }, "wake");
3137
+ return;
3138
+ case "echo":
3139
+ logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "own echo \u2014 not a wake");
3140
+ return;
3141
+ case "cycle": {
3142
+ const s = event.summary;
3143
+ const fields = {
3144
+ outcome: s.outcome,
3145
+ cards: s.cards,
3146
+ invites: s.invites,
3147
+ reply: s.reply,
3148
+ dismiss: s.dismiss,
3149
+ defer: s.defer,
3150
+ undecided: s.undecided,
3151
+ recordFailures: s.recordFailures,
3152
+ turnsStarted: s.turnsStarted,
3153
+ turnsRefused: s.turnsRefused,
3154
+ heldByTurns: s.heldByTurns,
3155
+ ...s.truncated ? { truncated: true } : {},
3156
+ ...s.failure ? { failure: s.failure } : {}
3157
+ };
3158
+ switch (s.outcome) {
3159
+ case "empty":
3160
+ logger.info({}, "tray empty \u2014 nothing to decide");
3161
+ return;
3162
+ case "nothing_owed":
3163
+ logger.info(fields, "nothing new to decide (muted cards, or cards a running turn holds)");
3164
+ return;
3165
+ case "fail_closed":
3166
+ logger.warn(fields, "gate failed closed \u2014 nothing recorded, no turn started; the server re-wakes");
3167
+ return;
3168
+ case "tray_failed":
3169
+ logger.warn(fields, "tray read failed \u2014 the cards stay on the tray; the server re-wakes");
3170
+ return;
3171
+ case "texts_missing":
3172
+ logger.warn(fields, "served texts not available \u2014 not gating; the cards wait on the tray");
3173
+ return;
3174
+ case "tools_unavailable":
3175
+ logger.debug(fields, "not gating \u2014 no turn can start now");
3176
+ return;
3177
+ case "abandoned":
3178
+ logger.warn(fields, "cycle abandoned \u2014 it ran past its deadline; nothing more is done for it, the next wake starts a new one");
3179
+ return;
3180
+ default: {
3181
+ const incomplete = s.turnsRefused > 0 || s.recordFailures > 0 || s.undecided > 0;
3182
+ logger[incomplete ? "warn" : "info"](fields, incomplete ? "gate \u2014 some cards were left on the tray; the server re-wakes" : "gate");
3183
+ return;
2883
3184
  }
2884
3185
  }
2885
- );
2886
- }
2887
- /** The reply turn for `conversationId` is over: its card may be gated again, and a tray that held skipped cards is read once more. */
2888
- replyTurnEnded(conversationId) {
2889
- this.replyTurnsInFlight.delete(conversationId);
2890
- if (this.skippedWhileInFlight && !this.stopped) {
2891
- this.skippedWhileInFlight = false;
2892
- this.logger.debug({ conversationId }, "reply turn ended \u2014 re-reading the tray for the cards left out meanwhile");
2893
- this.coalescer.wake();
2894
3186
  }
2895
- }
2896
- /**
2897
- * Whether the completed turn recorded a verdict for its conversation
2898
- * itself, seen on one fresh tray read. A card that left the tray was read
2899
- * (a verdict or a mark-read) or hidden by a `defer` — by the turn, since
2900
- * the host had recorded nothing for it. A card still there whose
2901
- * `your_last_decision` differs from the gate's copy got a verdict in the
2902
- * turn (a newer message keeps it on the tray). A card still there,
2903
- * unchanged, got nothing. A failed read, or a missing card past a
2904
- * truncated tray, claims nothing: `reply` is recorded as before.
2905
- */
2906
- async decidedInTurn(reply) {
2907
- let tray;
2908
- try {
2909
- tray = await this.client.inbox.tray({ waitMs: 0, limit: POST_TURN_TRAY_LIMIT });
2910
- } catch (err) {
2911
- this.logger.info({ conversationId: reply.conversationId, err: describe4(err) }, "tray re-read after the turn failed \u2014 recording reply");
2912
- return false;
2913
- }
2914
- const card = agentchatme.gate.cardsOf(tray).find((c) => c.conversation_id === reply.conversationId);
2915
- if (!card) return tray.truncated !== true;
2916
- return lastDecisionAt(card) !== lastDecisionAt(reply.card);
2917
- }
2918
- /** The `reply` verdict for a completed turn. A record the server refuses leaves the conversation unread; the ladder re-wakes. */
2919
- async recordReply(sessionKey, reply) {
2920
- try {
2921
- await reply.record();
2922
- this.logger.info({ sessionKey, conversationId: reply.conversationId }, "reply verdict recorded \u2014 turn completed");
2923
- } catch (err) {
2924
- this.logger.warn(
2925
- { sessionKey, conversationId: reply.conversationId, err: describe4(err), ...this.retry() },
2926
- "reply verdict not recorded after the turn completed \u2014 the conversation stays unread; the next wake gates it again"
3187
+ case "turn_started":
3188
+ return;
3189
+ // the turn starter logs it with the OpenClaw session and run
3190
+ case "turn_refused":
3191
+ logger.warn({ kind: event.kind, id: event.id, error: event.error }, "turn not started \u2014 nothing recorded; the card stays on the tray");
3192
+ return;
3193
+ case "turn_outcome": {
3194
+ const o = event.outcome;
3195
+ logger.info(
3196
+ { conversationId: o.conversationId, action: o.action, reason: o.reason, recorded: event.recorded, ...o.action !== "none" ? { through: o.throughMessageId } : {} },
3197
+ event.recorded ? `${o.action === "record_reply" ? "reply" : "dismiss"} recorded after the turn (${o.reason})` : `nothing recorded after the turn (${o.reason})`
2927
3198
  );
3199
+ return;
2928
3200
  }
3201
+ case "invite_outcome":
3202
+ logger.info(
3203
+ { inviteId: event.outcome.inviteId, action: event.outcome.action, reason: event.outcome.reason, recorded: event.recorded },
3204
+ event.recorded ? "invite dismissed after a second silent turn (left pending)" : `nothing recorded for the invite (${event.outcome.reason})`
3205
+ );
3206
+ return;
3207
+ case "run":
3208
+ return;
3209
+ // single-run mode logs the run itself
3210
+ case "error":
3211
+ logger.debug({ err: event.error.message }, "receive loop notice");
3212
+ return;
2929
3213
  }
2930
- /**
2931
- * Every pending invite gets one attempt. An invite leaves the pending list
2932
- * only once its turn was admitted (and is then remembered in the ledger);
2933
- * a refused one stays there for the next wake. Invites that arrive while
2934
- * this runs are appended and get their pass on the next drain.
2935
- */
2936
- async runInviteTurns() {
2937
- const batch = [...this.pendingInvites];
2938
- if (batch.length > 0) {
2939
- const readiness = this.readiness();
2940
- if (!readiness.ready) {
2941
- const changed = this.unreadyReason !== readiness.reason;
2942
- this.unreadyReason = readiness.reason;
2943
- 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");
2944
- return;
2945
- }
2946
- }
2947
- let texts = null;
2948
- let refused = 0;
2949
- let waitingForTexts = 0;
2950
- for (const invite of batch) {
2951
- if (this.stopped) return;
2952
- texts ??= await this.texts.ensure();
2953
- if (!texts) {
2954
- waitingForTexts = batch.length;
2955
- break;
2956
- }
2957
- const sessionKey = inviteSessionKey(this.agentId, invite.inviteId);
2958
- this.logger.info({ sessionKey, groupId: invite.groupId, inviteId: invite.inviteId }, "group-invite turn start");
2959
- let admission;
2960
- try {
2961
- admission = await this.startTurn({ sessionKey, prompt: inviteTurnPrompt(texts), lane: integrationLane(this.accountId) });
2962
- } catch (err) {
2963
- admission = { ran: false, error: describe4(err) };
2964
- }
2965
- if (!admission.ran) {
2966
- refused += 1;
2967
- this.logger.warn({ sessionKey, inviteId: invite.inviteId, error: admission.error }, "group-invite turn not started \u2014 the invite stays pending; retried on the next wake");
2968
- continue;
2969
- }
2970
- this.inviteTurns += 1;
2971
- this.invites.markOffered(invite.inviteId);
2972
- this.pendingInvites = this.pendingInvites.filter((pending) => pending.inviteId !== invite.inviteId);
2973
- this.admitted(sessionKey, admission, "group-invite turn complete");
2974
- }
2975
- if (this.stopped) return;
2976
- if (waitingForTexts > 0) {
2977
- this.logger.warn({ pending: waitingForTexts, ...this.retry() }, "served texts not available \u2014 invite turns wait; re-waking later");
2978
- } else if (refused > 0) {
2979
- this.logger.warn({ pending: refused, ...this.retry() }, "invite turns refused \u2014 re-waking later");
2980
- }
2981
- }
2982
- };
2983
- var POST_TURN_TRAY_LIMIT = 50;
2984
- function lastDecisionAt(card) {
2985
- const at = card.your_last_decision?.at;
2986
- return typeof at === "string" && at.length > 0 ? at : null;
2987
3214
  }
2988
- function describe4(err) {
2989
- return err instanceof Error ? err.message : String(err);
3215
+ var TROUBLE_OUTCOMES = /* @__PURE__ */ new Set(["fail_closed", "tools_unavailable", "texts_missing", "abandoned"]);
3216
+ var CYCLE_TROUBLE_RUN = 3;
3217
+ var TROUBLE_MEANING = {
3218
+ fail_closed: "the gate call failed (model unreachable, too slow, or nothing usable)",
3219
+ tools_unavailable: "no turn could have the hosted tools",
3220
+ texts_missing: "the served texts are not available",
3221
+ abandoned: "the cycle ran past its deadline and was abandoned"
3222
+ };
3223
+ function cycleTroubleLine(recentCycles) {
3224
+ let run = 0;
3225
+ for (let i = recentCycles.length - 1; i >= 0 && TROUBLE_OUTCOMES.has(recentCycles[i].outcome); i -= 1) run += 1;
3226
+ if (run < CYCLE_TROUBLE_RUN) return null;
3227
+ const last = recentCycles[recentCycles.length - 1];
3228
+ const kinds = [...new Set(recentCycles.slice(-run).map((c) => c.outcome))];
3229
+ const meaning = kinds.map((k) => TROUBLE_MEANING[k] ?? k).join("; ");
3230
+ return `the last ${run} cycles decided nothing (${kinds.join(", ")}): ${meaning}${last.failure ? ` \u2014 latest: ${last.failure}` : ""}; the cards wait on the tray and AgentChat re-wakes them`;
2990
3231
  }
2991
3232
  function adaptLog(log) {
2992
3233
  if (!log) return void 0;
@@ -3019,6 +3260,32 @@ async function waitUntilAbort(signal, onAbort) {
3019
3260
  }
3020
3261
  await onAbort();
3021
3262
  }
3263
+ var mcpUpdateWarned = /* @__PURE__ */ new Set();
3264
+ async function updateHostedMcpEntry(ctx, apiBase, apiKey, runtime = getPluginRuntime) {
3265
+ const prefix = `[agentchat:${ctx.accountId}]`;
3266
+ const warnOnce = (line) => {
3267
+ if (mcpUpdateWarned.has(ctx.accountId)) return;
3268
+ mcpUpdateWarned.add(ctx.accountId);
3269
+ ctx.log?.warn?.(`${prefix} ${line}`);
3270
+ };
3271
+ try {
3272
+ const { cfg: liveCfg } = readLiveConfig(ctx.cfg, runtime);
3273
+ const config = runtime()?.config;
3274
+ const result = await refreshHostedMcpEntry({ liveCfg, config, apiBase, apiKey });
3275
+ if (result.outcome === "updated") {
3276
+ mcpUpdateWarned.delete(ctx.accountId);
3277
+ 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`);
3278
+ } else if (result.outcome === "unsupported") {
3279
+ 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\``);
3280
+ } else if (result.outcome === "failed") {
3281
+ warnOnce(
3282
+ 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\``
3283
+ );
3284
+ }
3285
+ } catch (err) {
3286
+ warnOnce(`mcp.servers.agentchat check failed: ${err instanceof Error ? err.message : String(err)}`);
3287
+ }
3288
+ }
3022
3289
  var agentchatGatewayAdapter = {
3023
3290
  async startAccount(ctx) {
3024
3291
  const account = ctx.account;
@@ -3033,6 +3300,7 @@ var agentchatGatewayAdapter = {
3033
3300
  const config = account.config;
3034
3301
  const logger = adaptLog(ctx.log) ?? createLogger({ level: config.observability.logLevel, redactKeys: config.observability.redactKeys });
3035
3302
  ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: false }, "starting"));
3303
+ void updateHostedMcpEntry(ctx, config.apiBase, config.apiKey);
3036
3304
  const wakeMode = readEnv_js.readWakeModeFromEnv();
3037
3305
  if (wakeMode.mode === "off") {
3038
3306
  ctx.log?.info?.(
@@ -3044,7 +3312,7 @@ var agentchatGatewayAdapter = {
3044
3312
  }
3045
3313
  if (readEnv_js.readLegacyReplyGateFailOpenFromEnv()) {
3046
3314
  ctx.log?.warn?.(
3047
- `[agentchat:${ctx.accountId}] ${readEnv_js.LEGACY_REPLY_GATE_FAIL_OPEN_ENV} is set but no longer honoured \u2014 a gate that cannot run fails closed (nothing recorded, no turn) and re-wakes on the ladder`
3315
+ `[agentchat:${ctx.accountId}] ${readEnv_js.LEGACY_REPLY_GATE_FAIL_OPEN_ENV} is set but no longer honoured \u2014 a gate that cannot run fails closed (nothing recorded, no turn); the server re-wakes the cards`
3048
3316
  );
3049
3317
  }
3050
3318
  const refusal = multiAccountRefusal(ctx.cfg);
@@ -3066,20 +3334,57 @@ var agentchatGatewayAdapter = {
3066
3334
  }
3067
3335
  const client = getClient({ accountId: ctx.accountId, config });
3068
3336
  const gateTimeoutMs = readEnv_js.readReplyGateTimeoutMsFromEnv();
3069
- const texts = new TextsStore({ client, accountId: ctx.accountId, logger });
3337
+ const overdueWarned = /* @__PURE__ */ new Map();
3338
+ const turns = accountTurns(ctx.accountId);
3339
+ const reportOverdue = (runId, kind, id, elapsedMs, handed) => {
3340
+ const mark = Math.floor((elapsedMs + OVERDUE_SLACK_MS) / TURN_OVERDUE_MS);
3341
+ if (!handed && overdueWarned.get(runId) === mark) return;
3342
+ overdueWarned.set(runId, mark);
3343
+ ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${overdueTurnLine({ kind, id, elapsedMs }, readLiveConfig(ctx.cfg).cfg)}`);
3344
+ };
3345
+ const onStillRunning = ({ runId, sessionKey, elapsedMs }) => {
3346
+ const run = turns.run(runId);
3347
+ if (turns.stateOf(runId) === "released") {
3348
+ logger.debug({ runId, sessionKey, elapsedMin: Math.round(elapsedMs / 6e4) }, "released turn still running in OpenClaw \u2014 it holds nothing");
3349
+ return;
3350
+ }
3351
+ logger.info(
3352
+ { runId, sessionKey, elapsedMin: Math.round(elapsedMs / 6e4), ...run ? { [run.kind === "reply" ? "conversationId" : run.kind === "invite" ? "inviteId" : "run"]: run.id } : {} },
3353
+ "turn still running \u2014 its conversation stays in flight until OpenClaw reports the run ended"
3354
+ );
3355
+ if (!run || !isOverdue(elapsedMs)) return;
3356
+ const handed = turns.handOff(runId) !== null;
3357
+ reportOverdue(runId, run.kind, run.id, elapsedMs, handed);
3358
+ };
3359
+ const watchRun = createRunWatcher({ onStillRunning });
3360
+ turns.configure({
3361
+ recorder: createAfterTurnRecorder({ client, logger }),
3362
+ store: new TurnStore(ctx.accountId),
3363
+ watch: async (record) => {
3364
+ const outcome = await watchRun(record);
3365
+ return outcome ? turnEndOf(outcome) : null;
3366
+ },
3367
+ readCalls: (sessionKey, runId) => readAgentChatCalls(getPluginRuntime(), sessionKey, runId),
3368
+ logger
3369
+ });
3370
+ turns.adopt();
3371
+ for (const line of restartHoldLines(turns)) ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${line}`);
3372
+ for (const file of removeOldStateFiles(ctx.accountId)) logger.info({ file }, "removed a file an earlier release kept (no longer used)");
3373
+ const textsCache = createTextsCache({ client, accountId: ctx.accountId, logger });
3374
+ const texts = new OpenClawTexts(textsCache);
3375
+ const first = await textsCache.start();
3376
+ if (first) logger.info({ version: first.version, manual: first.manual?.version, source: textsCache.source }, "served texts in hand");
3377
+ else logger.warn({ err: textsCache.lastError }, "served texts not available yet (AgentChat unreachable, nothing cached) \u2014 nothing is gated until the first copy arrives");
3070
3378
  const handle = config.agentHandle;
3071
3379
  if (handle) {
3072
- texts.onServerCopy((copy) => {
3073
- const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, copy.identity_line);
3380
+ const refresh = (copy) => {
3381
+ const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, spellTextsForOpenClaw(copy).identity_line);
3074
3382
  if (refreshed.outcome === "updated") ctx.log?.info?.(`[agentchat:${ctx.accountId}] identity line refreshed from the served texts in ${refreshed.path}`);
3075
3383
  else if (refreshed.outcome === "failed") ctx.log?.warn?.(`[agentchat:${ctx.accountId}] identity line could not be refreshed in ${refreshed.path}: ${refreshed.detail ?? "unknown error"}`);
3076
- });
3384
+ };
3385
+ if (first) refresh(first);
3386
+ textsCache.onChange((copy) => refresh(copy));
3077
3387
  }
3078
- await texts.start();
3079
- const invites = new InviteLedger({
3080
- accountId: ctx.accountId,
3081
- onWriteError: (err) => ctx.log?.warn?.(`[agentchat:${ctx.accountId}] invite ledger could not be written: ${err instanceof Error ? err.message : String(err)}`)
3082
- });
3083
3388
  const metrics = createInMemoryMetrics();
3084
3389
  await registerIntegration({
3085
3390
  accountId: ctx.accountId,
@@ -3087,33 +3392,44 @@ var agentchatGatewayAdapter = {
3087
3392
  logger,
3088
3393
  socketOptions: { client, metrics },
3089
3394
  build: (socket) => {
3090
- const invoker = new AgentInvoker({
3395
+ const loop = createIntegrationLoop({
3091
3396
  accountId: ctx.accountId,
3092
3397
  agentId,
3093
3398
  client,
3399
+ texts,
3400
+ socket: socket.realtime,
3401
+ handle: config.agentHandle,
3094
3402
  callModel: createRuntimeModelCall({ agentIdOverride, ...gateTimeoutMs !== void 0 ? { timeoutMs: gateTimeoutMs } : {} }),
3095
- startTurn: createRuntimeTurnStarter(),
3403
+ // A turn holds its conversation until OpenClaw confirms its run
3404
+ // ended; a wait that elapses is asked again (`integration/run.ts`).
3405
+ startRun: createRuntimeTurnStarter({
3406
+ onStillRunning,
3407
+ onWaitError: ({ runId, sessionKey, error, attempt, retryInMs }) => logger[attempt === 1 ? "warn" : "debug"]({ runId, sessionKey, error, attempt, retryInMs }, "waiting for the turn to end failed \u2014 asking OpenClaw again")
3408
+ }),
3096
3409
  // Gating waits until a turn can have the hosted tools (the MCP
3097
3410
  // entry in the LIVE config — OpenClaw hot-applies `mcp.*` — and
3098
3411
  // its key in this process): a connect wake on a cold gateway
3099
3412
  // otherwise spends a gate call and runs a turn that cannot look.
3100
3413
  readiness: () => {
3101
3414
  const live = readLiveConfig(ctx.cfg);
3415
+ const hung = hungTurnsReason(turns, live.cfg);
3416
+ if (hung) return { ready: false, reason: hung };
3102
3417
  return turnReadiness({ cfg: live.cfg, apiBase: config.apiBase, apiKey: config.apiKey, live: live.live });
3103
3418
  },
3104
- texts,
3105
- invites,
3419
+ // The account's runs outlive this loop: a config change restarts
3420
+ // the account while its runs go on in OpenClaw, so every loop for
3421
+ // the account shares the same turns (and the kit tracker in them).
3422
+ turns,
3106
3423
  logger,
3107
3424
  metrics,
3108
3425
  gateEnabled: readEnv_js.readReplyGateEnabledFromEnv()
3109
3426
  });
3110
3427
  let blocked = false;
3111
3428
  return {
3112
- invoker,
3429
+ loop,
3113
3430
  texts,
3431
+ textsCache,
3114
3432
  handlers: {
3115
- onWake: (source) => invoker.wake(source),
3116
- onGroupInvite: (invite) => invoker.groupInvite(invite, "live"),
3117
3433
  onConnected: (at) => {
3118
3434
  if (blocked) {
3119
3435
  blocked = false;
@@ -3121,7 +3437,6 @@ var agentchatGatewayAdapter = {
3121
3437
  }
3122
3438
  ctx.log?.info?.(`[agentchat:${ctx.accountId}] connected at ${new Date(at).toISOString()} (agent ${agentId})`);
3123
3439
  ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: true, linked: true, statusState: "linked", lastConnectedAt: at }, "ready"));
3124
- void catchUpInvites(ctx.accountId, client, invoker, logger);
3125
3440
  },
3126
3441
  onBlocked: (info) => {
3127
3442
  const close = `close ${info.code}${info.reason ? ` ${info.reason}` : ""}`;
@@ -3177,23 +3492,6 @@ var agentchatGatewayAdapter = {
3177
3492
  ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false }, "stopped"));
3178
3493
  }
3179
3494
  };
3180
- async function catchUpInvites(accountId, client, invoker, logger) {
3181
- try {
3182
- const invites = await client.listGroupInvites();
3183
- if (!Array.isArray(invites)) return;
3184
- let surfaced = 0;
3185
- for (const row of invites) {
3186
- const invite = groupInviteFromRecord(row);
3187
- if (invite && invoker.groupInvite(invite, "catch-up")) surfaced += 1;
3188
- }
3189
- if (surfaced > 0) logger.info({ accountId, surfaced }, "pending group invites surfaced on connect");
3190
- } catch (err) {
3191
- logger.warn(
3192
- { accountId, err: err instanceof Error ? err.message : String(err) },
3193
- "pending-invite catch-up failed \u2014 live invite frames are unaffected and the agent can still list invites with the hosted tools"
3194
- );
3195
- }
3196
- }
3197
3495
  var PROBE_MIN_MS = 1e3;
3198
3496
  var PROBE_MAX_MS = 1e4;
3199
3497
  function formatCounts(counts) {
@@ -3235,15 +3533,27 @@ var agentchatStatusAdapter = {
3235
3533
  const enabled = account.enabled && isAgentchatAccountEnabled(cfg, account.accountId);
3236
3534
  const live = getIntegration(account.accountId);
3237
3535
  const health = live?.socket.getHealth();
3238
- const counters = live?.invoker?.counters();
3239
- const textsSource = live ? live.texts?.source ?? "missing" : void 0;
3536
+ const loopStatus = live?.loop?.loop.status();
3537
+ const counters = loopStatus ? {
3538
+ wakes: loopStatus.coalescer.wakes,
3539
+ cycles: loopStatus.coalescer.cycles,
3540
+ turns: loopStatus.counters.turnsStarted + loopStatus.counters.inviteTurnsStarted + loopStatus.counters.runsStarted
3541
+ } : void 0;
3542
+ const turnsHere = live ? findAccountTurns(account.accountId) ?? null : null;
3543
+ const hungReason = turnsHere ? hungTurnsReason(turnsHere, cfg) : null;
3544
+ const overdue = turnsHere ? [...hungReason ? [hungReason] : [], ...overdueTurnLines(turnsHere.runningRuns(), cfg), ...restartHoldLines(turnsHere)] : [];
3545
+ const trouble = loopStatus ? cycleTroubleLine(loopStatus.recentCycles ?? []) : null;
3546
+ const servedFrom = live?.texts?.source;
3547
+ const textsSource = live ? servedFrom === "server" || servedFrom === "cache" ? servedFrom : "missing" : void 0;
3240
3548
  const socketCounters = live?.metrics?.snapshot?.();
3241
- const integration = {
3549
+ const integration6 = {
3242
3550
  mode: readEnv_js.readWakeModeFromEnv().mode,
3243
3551
  ...health ? { state: health.state } : {},
3244
3552
  ...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
3245
3553
  ...textsSource ? { texts: textsSource } : {},
3246
- ...socketCounters ? { socket: socketCounters } : {}
3554
+ ...socketCounters ? { socket: socketCounters } : {},
3555
+ ...overdue.length > 0 ? { overdue } : {},
3556
+ ...trouble ? { trouble } : {}
3247
3557
  };
3248
3558
  const refusal = multiAccountRefusal(cfg);
3249
3559
  return {
@@ -3253,7 +3563,7 @@ var agentchatStatusAdapter = {
3253
3563
  pausedByOwner: me.paused_by_owner ?? "none",
3254
3564
  mcp,
3255
3565
  placement,
3256
- integration,
3566
+ integration: integration6,
3257
3567
  ...refusal ? { refusal } : {},
3258
3568
  ...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
3259
3569
  };
@@ -3274,7 +3584,7 @@ var agentchatStatusAdapter = {
3274
3584
  }
3275
3585
  if (probe.mcp) lines.push({ text: probe.mcp.detail, tone: probe.mcp.ok ? "success" : "error" });
3276
3586
  for (const check of probe.placement ?? []) {
3277
- lines.push({ text: `${check.name}: ${check.detail}`, tone: check.ok ? "muted" : "warn" });
3587
+ lines.push({ text: `${check.name}: ${check.detail}`, tone: check.ok && !check.notice ? "muted" : "warn" });
3278
3588
  }
3279
3589
  if (probe.refusal) lines.push({ text: `integration not started \u2014 ${probe.refusal}`, tone: "error" });
3280
3590
  if (probe.integration) {
@@ -3291,6 +3601,8 @@ var agentchatStatusAdapter = {
3291
3601
  tone: "muted"
3292
3602
  });
3293
3603
  }
3604
+ if (d.trouble) lines.push({ text: d.trouble, tone: "warn" });
3605
+ for (const line of d.overdue ?? []) lines.push({ text: line, tone: "warn" });
3294
3606
  if (d.texts === "missing") {
3295
3607
  lines.push({ text: "served texts not available yet (AgentChat unreachable, nothing cached) \u2014 turns wait for the first copy", tone: "error" });
3296
3608
  } else if (d.texts === "cache") {
@@ -3322,8 +3634,8 @@ var agentchatDoctorAdapter = {
3322
3634
  const handle = readAgentchatConfigField(cfg, accountId, "agentHandle");
3323
3635
  const agentId = resolvePlacementAgentId(cfg, accountId);
3324
3636
  for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {
3325
- if (check.ok) continue;
3326
- const fix = check.name === "mcp" ? ` (${doctorFixCommand} adds it)` : "";
3637
+ if (check.ok && !check.notice) continue;
3638
+ const fix = check.name === "mcp" && check.repair && !check.ok ? ` (${doctorFixCommand} adds it)` : "";
3327
3639
  warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${check.name}: ${check.detail}${fix}`);
3328
3640
  }
3329
3641
  const bound = openclawLayout_js.resolveBoundAgentId(cfg, AGENTCHAT_CHANNEL_ID, accountId);
@@ -3334,6 +3646,18 @@ var agentchatDoctorAdapter = {
3334
3646
  );
3335
3647
  }
3336
3648
  }
3649
+ for (const accountId of listActiveAccounts()) {
3650
+ const status = getIntegration(accountId)?.loop?.loop.status();
3651
+ if (!status) continue;
3652
+ const turns = findAccountTurns(accountId);
3653
+ if (turns) {
3654
+ const hung = hungTurnsReason(turns, cfg);
3655
+ if (hung) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${hung}`);
3656
+ for (const line of [...overdueTurnLines(turns.runningRuns(), cfg), ...restartHoldLines(turns)]) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${line}`);
3657
+ }
3658
+ const trouble = cycleTroubleLine(status.recentCycles ?? []);
3659
+ if (trouble) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${trouble}`);
3660
+ }
3337
3661
  return warnings;
3338
3662
  },
3339
3663
  async repairConfig({ cfg }) {
@@ -3380,6 +3704,7 @@ var agentchatDoctorAdapter = {
3380
3704
  const result = withHostedMcpEntry(next, apiBase, apiKey);
3381
3705
  next = result.cfg;
3382
3706
  if (result.outcome === "added") changes.push(`added mcp.servers.agentchat \u2192 ${apiBase}/mcp (bearer template on AGENTCHAT_API_KEY)`);
3707
+ if (result.outcome === "updated") changes.push(`updated mcp.servers.agentchat to name this client (${clientIdentityText()})`);
3383
3708
  }
3384
3709
  return { config: next, changes, ...warnings.length > 0 ? { warnings } : {} };
3385
3710
  }
@@ -3406,9 +3731,9 @@ function resolveAgentchatAccount(cfg, accountId) {
3406
3731
  var uiHints = {
3407
3732
  apiKey: {
3408
3733
  label: "AgentChat API key",
3409
- placeholder: "ac_live_...",
3734
+ placeholder: "ac_\u2026",
3410
3735
  sensitive: true,
3411
- 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."
3736
+ 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."
3412
3737
  },
3413
3738
  apiBase: {
3414
3739
  label: "API base URL",
@@ -3619,8 +3944,14 @@ var agentchatPlugin = {
3619
3944
  threads: false,
3620
3945
  nativeCommands: false
3621
3946
  },
3947
+ // OpenClaw matches a reload prefix as `path === prefix` or `path` starting
3948
+ // with `prefix.` (src/gateway/config-reload-plan.ts), so the prefix carries
3949
+ // no trailing dot: `channels.agentchat.` matched nothing, and every
3950
+ // channels.agentchat change restarted the gateway (2026.6.x–2026.8.x) or
3951
+ // reloaded the plugin (2026.11.x). With this one OpenClaw restarts just the
3952
+ // channel, after a running turn has ended.
3622
3953
  reload: {
3623
- configPrefixes: [`channels.${AGENTCHAT_CHANNEL_ID}.`]
3954
+ configPrefixes: [`channels.${AGENTCHAT_CHANNEL_ID}`]
3624
3955
  },
3625
3956
  configSchema: channelCore.buildChannelConfigSchema(agentchatChannelConfigSchema, { uiHints }),
3626
3957
  setupWizard: agentchatSetupWizard,
@@ -3628,9 +3959,9 @@ var agentchatPlugin = {
3628
3959
  listAccountIds(cfg) {
3629
3960
  const section = readChannelSection(cfg);
3630
3961
  if (!section) return [];
3631
- const { accounts } = section;
3632
- if (accounts && typeof accounts === "object" && !Array.isArray(accounts)) {
3633
- const ids = Object.keys(accounts);
3962
+ const { accounts: accounts2 } = section;
3963
+ if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
3964
+ const ids = Object.keys(accounts2);
3634
3965
  if (ids.length > 0) return ids;
3635
3966
  }
3636
3967
  const hasFlatFields = typeof section.apiKey === "string" || typeof section.apiBase === "string" || typeof section.agentHandle === "string";
@@ -3670,9 +4001,9 @@ var agentchatPlugin = {
3670
4001
  hasConfiguredState({ cfg }) {
3671
4002
  const section = readChannelSection(cfg);
3672
4003
  if (!section) return false;
3673
- const { accounts } = section;
3674
- if (accounts && typeof accounts === "object" && !Array.isArray(accounts)) {
3675
- for (const entry of Object.values(accounts)) {
4004
+ const { accounts: accounts2 } = section;
4005
+ if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
4006
+ for (const entry of Object.values(accounts2)) {
3676
4007
  if (entry && typeof entry === "object") {
3677
4008
  const candidate = entry.apiKey;
3678
4009
  if (isApiKeyPresent(candidate)) return true;
@@ -3716,7 +4047,15 @@ channelCore.defineChannelPluginEntry({
3716
4047
  // (docs.openclaw.ai/plugins/sdk-entrypoints/define-channel-plugin-entry).
3717
4048
  // The integration reads `runtime.llm.complete` (the gate on the agent's own
3718
4049
  // model) and `runtime.subagent.run` (one turn, `deliver: false`) from it.
3719
- setRuntime: (runtime) => setPluginRuntime(runtime)
4050
+ setRuntime: (runtime) => setPluginRuntime(runtime),
4051
+ // `openclaw agentchat release <conversation_id>`: the CLI half is
4052
+ // registered for every CLI (parse-time metadata), the gateway half only
4053
+ // where the integration runs.
4054
+ registerCliMetadata: (api) => registerReleaseCli(api),
4055
+ registerFull: (api) => {
4056
+ registerReleaseGatewayMethod(api);
4057
+ registerRunObserver(api);
4058
+ }
3720
4059
  });
3721
4060
 
3722
4061
  // src/channel.setup.ts