@agentchatme/openclaw 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -5,11 +5,12 @@ 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 crypto = require('crypto');
8
9
  var agentchatme = require('agentchatme');
10
+ var readEnv_js = require('./credentials/read-env.cjs');
9
11
  var readEnv_js$1 = require('./credentials/read-env.cjs');
10
12
  var fs = require('fs');
11
13
  var path2 = require('path');
12
- var readEnv_js = require('./credentials/read-env.cjs');
13
14
  var openclawLayout_js = require('./openclaw-layout.cjs');
14
15
  var agentsAnchor_js = require('./binding/agents-anchor.cjs');
15
16
  var zod = require('zod');
@@ -133,22 +134,8 @@ function applyAgentchatAccountPatch(cfg, accountId, patch) {
133
134
  return { ...cfg ?? {}, channels };
134
135
  }
135
136
 
136
- // src/errors.ts
137
- var AgentChatChannelError = class extends Error {
138
- class_;
139
- retryAfterMs;
140
- statusCode;
141
- constructor(class_, message, options = {}) {
142
- super(message, { cause: options.cause });
143
- this.name = "AgentChatChannelError";
144
- this.class_ = class_;
145
- this.retryAfterMs = options.retryAfterMs;
146
- this.statusCode = options.statusCode;
147
- }
148
- };
149
-
150
137
  // src/version.ts
151
- var PACKAGE_VERSION = "0.10.1";
138
+ var PACKAGE_VERSION = "0.11.0";
152
139
 
153
140
  // src/client-identity.ts
154
141
  var AGENTCHAT_CLIENT_NAME = "openclaw";
@@ -157,227 +144,6 @@ var AGENTCHAT_CLIENT_IDENTITY = {
157
144
  version: PACKAGE_VERSION
158
145
  };
159
146
 
160
- // src/setup-client.ts
161
- var DEFAULT_API_BASE = "https://api.agentchat.me";
162
- var DEFAULT_TIMEOUT_MS = 1e4;
163
- async function validateApiKey(apiKey, opts = {}) {
164
- if (!apiKey || typeof apiKey !== "string") {
165
- return { ok: false, reason: "unauthorized", message: "API key is empty" };
166
- }
167
- const client = new agentchatme.AgentChatClient({
168
- apiKey,
169
- baseUrl: apiBaseOf(opts.apiBase),
170
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
171
- timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
172
- retry: ONE_ATTEMPT,
173
- ...opts.fetch ? { fetch: opts.fetch } : {}
174
- });
175
- let me;
176
- try {
177
- me = await client.getMe();
178
- } catch (err) {
179
- const failure = describeFailure(err);
180
- if (failure.kind === "network") {
181
- const unreachable = failure.timedOut || /ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(failure.message);
182
- return {
183
- ok: false,
184
- reason: unreachable ? "unreachable" : "network-error",
185
- message: `agentchat: GET /v1/agents/me failed: ${failure.message}`
186
- };
187
- }
188
- const status = failure.status;
189
- if (status === 401) return { ok: false, reason: "unauthorized", status, message: "API key is invalid or revoked" };
190
- if (status === 403) return { ok: false, reason: "forbidden", status, message: "API key lacks permission to read /agents/me" };
191
- if (status === 410) return { ok: false, reason: "deleted", status, message: "Agent account has been deleted" };
192
- return { ok: false, reason: "server-error", status, message: `AgentChat API returned ${status}` };
193
- }
194
- const body = asRecord(me);
195
- const email = typeof body?.email === "string" ? body.email : typeof body?.email_masked === "string" ? body.email_masked : null;
196
- if (!body || typeof body.handle !== "string" || email === null || typeof body.created_at !== "string") {
197
- return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/me returned an unrecognized shape" };
198
- }
199
- return {
200
- ok: true,
201
- agent: {
202
- handle: body.handle,
203
- displayName: typeof body.display_name === "string" ? body.display_name : null,
204
- email,
205
- createdAt: body.created_at
206
- }
207
- };
208
- }
209
- async function registerAgentStart(input, opts = {}) {
210
- let data;
211
- try {
212
- data = await agentchatme.AgentChatClient.register({
213
- email: input.email,
214
- handle: input.handle,
215
- ...input.displayName !== void 0 ? { display_name: input.displayName } : {},
216
- ...input.description !== void 0 ? { description: input.description } : {},
217
- baseUrl: apiBaseOf(opts.apiBase),
218
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
219
- });
220
- } catch (err) {
221
- const failure = describeFailure(err);
222
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
223
- const { status, code, message } = failure;
224
- if (status === 400 && code === "INVALID_HANDLE") return { ok: false, reason: "invalid-handle", message, status };
225
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
226
- if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
227
- const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
228
- if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
229
- if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
230
- if (status >= 500 || code === "OTP_FAILED") return { ok: false, reason: "otp-failed", message, status };
231
- return { ok: false, reason: "server-error", status, message };
232
- }
233
- const pendingId = asRecord(data)?.pending_id;
234
- if (typeof pendingId !== "string") {
235
- return { ok: false, reason: "server-error", status: 200, message: "AgentChat /register returned no pending_id" };
236
- }
237
- return { ok: true, pendingId };
238
- }
239
- async function registerAgentVerify(input, opts = {}) {
240
- let verified;
241
- try {
242
- verified = await agentchatme.AgentChatClient.verify(input.pendingId, input.code, {
243
- baseUrl: apiBaseOf(opts.apiBase),
244
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
245
- });
246
- } catch (err) {
247
- const failure = describeFailure(err);
248
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
249
- const { status, code, message } = failure;
250
- if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
251
- if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
252
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
253
- if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
254
- const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
255
- if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
256
- if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
257
- return { ok: false, reason: "server-error", status, message };
258
- }
259
- const agent = asRecord(verified.agent);
260
- if (typeof verified.apiKey !== "string" || !agent || typeof agent.handle !== "string" || typeof agent.email !== "string" || typeof agent.created_at !== "string") {
261
- return { ok: false, reason: "unexpected-shape", status: 201, message: "AgentChat /register/verify returned an unrecognized shape" };
262
- }
263
- return {
264
- ok: true,
265
- apiKey: verified.apiKey,
266
- agent: {
267
- handle: agent.handle,
268
- displayName: typeof agent.display_name === "string" ? agent.display_name : null,
269
- email: agent.email,
270
- createdAt: agent.created_at
271
- }
272
- };
273
- }
274
- async function recoverAgentStart(input, opts = {}) {
275
- let data;
276
- try {
277
- data = await agentchatme.AgentChatClient.recover(input.email, {
278
- handle: input.handle,
279
- baseUrl: apiBaseOf(opts.apiBase),
280
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
281
- });
282
- } catch (err) {
283
- const failure = describeFailure(err);
284
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
285
- const { status, code, message: message2 } = failure;
286
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message: message2, status };
287
- if (status === 429) return { ok: false, reason: "rate-limited", message: message2, status, retryAfterSeconds: failure.retryAfterSeconds };
288
- return { ok: false, reason: "server-error", status, message: message2 };
289
- }
290
- const body = asRecord(data);
291
- const message = typeof body?.message === "string" ? body.message : "status 200";
292
- if (typeof body?.pending_id !== "string") {
293
- return {
294
- ok: false,
295
- reason: "unexpected-shape",
296
- status: 200,
297
- message: "AgentChat did not start a recovery (no pending_id in the response). Check that the email is the one this agent registered with."
298
- };
299
- }
300
- return { ok: true, pendingId: body.pending_id, message };
301
- }
302
- async function recoverAgentVerify(input, opts = {}) {
303
- let recovered;
304
- try {
305
- recovered = await agentchatme.AgentChatClient.recoverVerify(input.pendingId, input.code, {
306
- baseUrl: apiBaseOf(opts.apiBase),
307
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
308
- });
309
- } catch (err) {
310
- const failure = describeFailure(err);
311
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
312
- const { status, code, message } = failure;
313
- if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
314
- if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
315
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
316
- if (status === 409 && code === "HANDLE_REQUIRED") {
317
- return { ok: false, reason: "handle-required", message, status, handles: readHandleList(failure.details) };
318
- }
319
- if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
320
- return { ok: false, reason: "server-error", status, message };
321
- }
322
- if (typeof recovered.apiKey !== "string" || typeof recovered.handle !== "string") {
323
- return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/recover/verify returned an unrecognized shape" };
324
- }
325
- return { ok: true, apiKey: recovered.apiKey, handle: recovered.handle };
326
- }
327
- function classifyEmailPolicyRejection(code) {
328
- if (code === "EMAIL_LIMIT_REACHED" || code === "EMAIL_TAKEN") return "email-limit-reached";
329
- if (code === "EMAIL_EXHAUSTED") return "email-exhausted";
330
- return void 0;
331
- }
332
- function readPolicyLimit(details) {
333
- if (!details || typeof details !== "object") return void 0;
334
- const limit = details.limit;
335
- return typeof limit === "number" && Number.isInteger(limit) && limit > 0 ? limit : void 0;
336
- }
337
- function readHandleList(details) {
338
- if (!details || typeof details !== "object") return [];
339
- const handles = details.handles;
340
- if (!Array.isArray(handles)) return [];
341
- return handles.filter((h) => typeof h === "string" && h.length > 0);
342
- }
343
- var ONE_ATTEMPT = { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 };
344
- function apiBaseOf(apiBase) {
345
- return (apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, "");
346
- }
347
- function describeFailure(err) {
348
- if (err instanceof agentchatme.AgentChatError) {
349
- const raw = asRecord(asRecord(err.details)?.body);
350
- const code = typeof raw?.code === "string" ? raw.code : String(err.code ?? "");
351
- const message2 = raw ? typeof raw.message === "string" ? raw.message : `status ${err.status}` : err.message || `status ${err.status}`;
352
- const retryAfterMs = err instanceof agentchatme.RateLimitedError ? err.retryAfterMs : null;
353
- return {
354
- kind: "http",
355
- status: err.status,
356
- code,
357
- message: message2,
358
- details: raw ? raw.details : err.details,
359
- ...typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) ? { retryAfterSeconds: Math.ceil(retryAfterMs / 1e3) } : {}
360
- };
361
- }
362
- const message = err instanceof Error ? err.message : String(err);
363
- const timedOut = err instanceof Error && err.name === "AbortError" || /timed out|abort/i.test(message);
364
- return { kind: "network", message, timedOut };
365
- }
366
- function networkMessage(failure) {
367
- return failure.timedOut ? "request timed out" : failure.message;
368
- }
369
- function asRecord(value) {
370
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
371
- }
372
- async function assertApiKeyValid(apiKey, opts = {}) {
373
- const result = await validateApiKey(apiKey, opts);
374
- if (result.ok) return result.agent;
375
- const class_ = result.reason === "unauthorized" || result.reason === "forbidden" || result.reason === "deleted" ? "terminal-auth" : result.reason === "server-error" ? "retry-transient" : "retry-transient";
376
- throw new AgentChatChannelError(class_, `${result.message} [reason=${result.reason}]`, {
377
- statusCode: result.status
378
- });
379
- }
380
-
381
147
  // src/integration/turn.ts
382
148
  var MCP_SERVER_NAME = "agentchat";
383
149
  var MCP_TOOL_DELIMITER = "__";
@@ -414,8 +180,8 @@ function sanitizeKeyPart(value) {
414
180
  // src/integration/mcp.ts
415
181
  var MCP_PATH = "/mcp";
416
182
  var AUTH_HEADER_TEMPLATE = `Bearer \${${readEnv_js.API_KEY_ENV}}`;
417
- var DEFAULT_API_BASE2 = "https://api.agentchat.me";
418
- function hostedMcpUrl(apiBase = DEFAULT_API_BASE2) {
183
+ var DEFAULT_API_BASE = "https://api.agentchat.me";
184
+ function hostedMcpUrl(apiBase = DEFAULT_API_BASE) {
419
185
  return `${apiBase.replace(/\/+$/, "")}${MCP_PATH}`;
420
186
  }
421
187
  var CLIENT_HEADER = "X-AgentChat-Client";
@@ -425,14 +191,14 @@ function clientIdentityHeaders() {
425
191
  function clientIdentityText() {
426
192
  return `${CLIENT_HEADER}: ${AGENTCHAT_CLIENT_NAME}`;
427
193
  }
428
- function hostedMcpServerEntry(apiBase = DEFAULT_API_BASE2) {
194
+ function hostedMcpServerEntry(apiBase = DEFAULT_API_BASE) {
429
195
  return {
430
196
  url: hostedMcpUrl(apiBase),
431
197
  transport: "streamable-http",
432
198
  headers: { Authorization: AUTH_HEADER_TEMPLATE, ...clientIdentityHeaders() }
433
199
  };
434
200
  }
435
- function hostedMcpSnippet(apiBase = DEFAULT_API_BASE2) {
201
+ function hostedMcpSnippet(apiBase = DEFAULT_API_BASE) {
436
202
  const identity = clientIdentityHeaders();
437
203
  return [
438
204
  "{",
@@ -451,7 +217,7 @@ function hostedMcpSnippet(apiBase = DEFAULT_API_BASE2) {
451
217
  "}"
452
218
  ].join("\n");
453
219
  }
454
- function describeMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
220
+ function describeMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
455
221
  const servers = cfg?.mcp?.servers;
456
222
  if (!servers || typeof servers !== "object" || Array.isArray(servers)) return "missing";
457
223
  const entry = servers[MCP_SERVER_NAME];
@@ -484,7 +250,7 @@ function describeMcpIdentity(cfg) {
484
250
  const client = clients[0];
485
251
  return clients.length === 1 && typeof client === "string" && client.trim().toLowerCase() === want[CLIENT_HEADER] ? "current" : "missing";
486
252
  }
487
- function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
253
+ function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
488
254
  const state = describeMcpEntry(cfg, apiBase, apiKey);
489
255
  const base = cfg ?? {};
490
256
  if (state === "user_managed") return { cfg: base, outcome: "user_managed" };
@@ -497,7 +263,7 @@ function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
497
263
  mcp.servers = servers;
498
264
  return { cfg: { ...base, mcp }, outcome: state === "ours" ? "updated" : "added" };
499
265
  }
500
- function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE2) {
266
+ function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE) {
501
267
  const headers = isRecord(entry.headers) ? entry.headers : {};
502
268
  const kept = Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== CLIENT_HEADER.toLowerCase()));
503
269
  return {
@@ -507,7 +273,7 @@ function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE2) {
507
273
  headers: { ...kept, ...clientIdentityHeaders() }
508
274
  };
509
275
  }
510
- function upgradeHostedMcpEntryInPlace(draft, apiBase = DEFAULT_API_BASE2, apiKey) {
276
+ function upgradeHostedMcpEntryInPlace(draft, apiBase = DEFAULT_API_BASE, apiKey) {
511
277
  if (describeMcpEntry(draft, apiBase, apiKey) !== "ours" || describeMcpIdentity(draft) === "current") return false;
512
278
  const servers = draft.mcp.servers;
513
279
  const existing = servers[MCP_SERVER_NAME];
@@ -524,7 +290,7 @@ var NoChange = class extends Error {
524
290
  };
525
291
  var NIX_MODE_ERROR_CODE = "OPENCLAW_NIX_MODE_CONFIG_IMMUTABLE";
526
292
  async function refreshHostedMcpEntry(params) {
527
- const apiBase = params.apiBase ?? DEFAULT_API_BASE2;
293
+ const apiBase = params.apiBase ?? DEFAULT_API_BASE;
528
294
  if (describeMcpEntry(params.liveCfg, apiBase, params.apiKey) !== "ours") return { outcome: "not_ours" };
529
295
  if (describeMcpIdentity(params.liveCfg) === "current") return { outcome: "current" };
530
296
  const mutate = params.config?.mutateConfigFile;
@@ -561,7 +327,7 @@ function headerValues(headers, name) {
561
327
  const wanted = name.toLowerCase();
562
328
  return Object.entries(headers).filter(([key]) => key.toLowerCase() === wanted).map(([, value]) => value);
563
329
  }
564
- function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
330
+ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
565
331
  if (describeMcpEntry(cfg, apiBase, apiKey) !== "ours") return { cfg, removed: false };
566
332
  const mcp = { ...cfg.mcp ?? {} };
567
333
  const servers = { ...mcp.servers ?? {} };
@@ -571,7 +337,7 @@ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
571
337
  }
572
338
  async function probeHostedMcp(params) {
573
339
  const result = await agentchatme.integration.probeHostedTools({
574
- apiBase: params.apiBase ?? DEFAULT_API_BASE2,
340
+ apiBase: params.apiBase ?? DEFAULT_API_BASE,
575
341
  apiKey: params.apiKey,
576
342
  clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
577
343
  ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
@@ -590,6 +356,40 @@ async function probeHostedMcp(params) {
590
356
  };
591
357
  }
592
358
 
359
+ // src/setup-client.ts
360
+ var KEY_CHECK_TIMEOUT_MS = 1e4;
361
+ function accountCallOptions(params = {}) {
362
+ return {
363
+ clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
364
+ apiBase: (params.apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, ""),
365
+ ...params.fetch ? { fetch: params.fetch } : {},
366
+ ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {}
367
+ };
368
+ }
369
+ var KeyCheckUnanswered = class extends Error {
370
+ constructor(message) {
371
+ super(message);
372
+ this.name = "KeyCheckUnanswered";
373
+ }
374
+ };
375
+ async function checkApiKey(apiKey, params = {}) {
376
+ let status;
377
+ const send = params.fetch ?? ((input, init) => globalThis.fetch(input, init));
378
+ const observed = (async (input, init) => {
379
+ const response = await send(input, init);
380
+ status = response.status;
381
+ return response;
382
+ });
383
+ const check = await agentchatme.integration.account.checkKey(
384
+ apiKey,
385
+ accountCallOptions({ timeoutMs: KEY_CHECK_TIMEOUT_MS, ...params, fetch: observed })
386
+ );
387
+ if (!check.ok && status !== 401 && status !== 403) {
388
+ throw new KeyCheckUnanswered(`AgentChat answered ${status ?? "without a status"} (${check.code}): ${check.message}`);
389
+ }
390
+ return check;
391
+ }
392
+
593
393
  // src/integration/runtime-holder.ts
594
394
  var current = null;
595
395
  function isUsablePluginRuntime(runtime) {
@@ -671,55 +471,266 @@ async function watchRunUntilEnded(options) {
671
471
  if (elapsedMs < MIN_WAIT_SPACING_MS) await sleep(MIN_WAIT_SPACING_MS - elapsedMs);
672
472
  }
673
473
  }
674
- function countAgentChatCalls(messages, runId) {
474
+ function countAgentChatCalls(messages, runId, host = {}) {
675
475
  if (messages.length === 0) return null;
676
- let recognised = false;
677
- let made = 0;
678
- let failed = 0;
476
+ const rows = [];
679
477
  for (const row of messages) {
680
478
  const message = unwrapMessage(row);
681
- if (!message) continue;
682
- const role = message.role;
683
- if (role === "assistant" || role === "user") recognised = true;
684
- if (role !== "toolResult" && role !== "tool") continue;
685
- recognised = true;
686
- const meta = asRecord2(message.__openclaw);
687
- if (runId && typeof meta?.runId === "string" && meta.runId !== runId) continue;
688
- if (!isAgentChatToolResult(message)) continue;
479
+ if (!message) return null;
480
+ rows.push(message);
481
+ }
482
+ if (!coversWholeSession(rows)) return null;
483
+ if (runId && rows.some((row) => isOtherRun(row, runId))) return null;
484
+ const calls = assistantToolCalls(rows);
485
+ const nested = rows.flatMap((row) => {
486
+ const call = nestedCallOf(row);
487
+ return call ? [call] : [];
488
+ });
489
+ const release = releaseOf(rows, calls, nested, host.openclawVersion);
490
+ if (delegatedToChild(rows, calls, nested)) return null;
491
+ if (usedCodeMode(rows, calls)) {
492
+ if (!release.recordsNestedCalls) return null;
493
+ if (!codeModeScriptsCompleted(rows, calls)) return null;
494
+ }
495
+ const parents = new Set(nested.flatMap((call) => typeof call.parentToolCallId === "string" ? [call.parentToolCallId] : []));
496
+ let made = 0;
497
+ let failed = 0;
498
+ for (const message of rows) {
499
+ let verdict;
500
+ const call = nestedCallOf(message);
501
+ if (call) verdict = nestedVerdict(call);
502
+ else if (message.role !== "toolResult" && message.role !== "tool") continue;
503
+ else if (typeof message.toolCallId === "string" && parents.has(message.toolCallId)) continue;
504
+ else verdict = callVerdict(message, calls, release);
505
+ if (verdict === "not_agentchat") continue;
506
+ if (verdict === "unknown") return null;
689
507
  made += 1;
690
- if (message.isError === true) failed += 1;
508
+ if (verdict === "failed") failed += 1;
691
509
  }
692
- return recognised ? { made, failed } : null;
510
+ return { made, failed };
693
511
  }
694
512
  async function readAgentChatCalls(runtime, sessionKey, runId) {
695
513
  if (!runtime || typeof runtime.subagent?.getSessionMessages !== "function") return null;
696
514
  try {
697
515
  const result = await runtime.subagent.getSessionMessages({ sessionKey, limit: TRANSCRIPT_READ_LIMIT });
698
516
  const messages = result?.messages;
699
- return Array.isArray(messages) ? countAgentChatCalls(messages, runId) : null;
517
+ const openclawVersion = typeof runtime.version === "string" ? runtime.version : void 0;
518
+ return Array.isArray(messages) ? countAgentChatCalls(messages, runId, openclawVersion ? { openclawVersion } : {}) : null;
700
519
  } catch {
701
520
  return null;
702
521
  }
703
522
  }
704
523
  var TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
705
- function isAgentChatToolResult(message) {
706
- const toolName = typeof message.toolName === "string" ? message.toolName : typeof message.name === "string" ? message.name : "";
707
- if (toolName.startsWith(TOOL_PREFIX)) return true;
708
- const tool = asRecord2(asRecord2(message.details)?.tool);
709
- if (!tool) return false;
524
+ var DISPATCHER_TOOL_NAMES = /* @__PURE__ */ new Set(["tool_call", "dispatch_action"]);
525
+ var FAILURE_STATUSES = /* @__PURE__ */ new Set([
526
+ "error",
527
+ "failed",
528
+ "failure",
529
+ "timeout",
530
+ "timed_out",
531
+ "blocked",
532
+ "denied",
533
+ "forbidden",
534
+ "unavailable",
535
+ "approval-unavailable",
536
+ "disabled",
537
+ "aborted",
538
+ "cancelled",
539
+ "canceled",
540
+ "killed",
541
+ "invalid"
542
+ ]);
543
+ function coversWholeSession(rows) {
544
+ if (asRecord(rows[0]?.__openclaw)?.seq !== 1) return false;
545
+ return rows.every((row) => {
546
+ const meta = asRecord(row.__openclaw);
547
+ return meta?.kind !== "compaction" && meta?.kind !== "reset" && meta?.truncated !== true;
548
+ });
549
+ }
550
+ function isOtherRun(row, runId) {
551
+ const tagged = asRecord(row.__openclaw)?.runId ?? nestedCallOf(row)?.runId;
552
+ return typeof tagged === "string" && tagged.trim().length > 0 && tagged.trim() !== runId;
553
+ }
554
+ var CODE_MODE_ONLY_TOOL_NAMES = /* @__PURE__ */ new Set(["tool_search_code", "wait"]);
555
+ function usedCodeMode(rows, calls) {
556
+ return [...calls.values()].some(isCodeModeCall) || rows.some((row) => isCodeModeResult(row, calls));
557
+ }
558
+ function codeModeScriptsCompleted(rows, calls) {
559
+ const results = /* @__PURE__ */ new Map();
560
+ for (const row of rows) {
561
+ if ((row.role === "toolResult" || row.role === "tool") && typeof row.toolCallId === "string") results.set(row.toolCallId, row);
562
+ }
563
+ const completed = (row) => row !== void 0 && row.isError !== true && asRecord(row.details)?.status === "completed";
564
+ for (const [id, call] of calls) {
565
+ if (isCodeModeCall(call) && !completed(results.get(id))) return false;
566
+ }
567
+ return rows.every((row) => !isCodeModeResult(row, calls) || completed(row));
568
+ }
569
+ function isCodeModeCall(call) {
570
+ const name = typeof call.name === "string" ? call.name : "";
571
+ return CODE_MODE_ONLY_TOOL_NAMES.has(name) || name === "exec" && typeof callArguments(call)?.code === "string";
572
+ }
573
+ function isCodeModeResult(row, calls) {
574
+ if (row.role !== "toolResult" && row.role !== "tool") return false;
575
+ const name = toolNameOf(row);
576
+ return CODE_MODE_ONLY_TOOL_NAMES.has(name) || name === "exec" && !isShellExecResult(row, calls);
577
+ }
578
+ function isShellExecResult(row, calls) {
579
+ const call = typeof row.toolCallId === "string" ? calls.get(row.toolCallId) : void 0;
580
+ const args = callArguments(call);
581
+ if (!args || typeof args.command !== "string" || args.code !== void 0) return false;
582
+ const details = asRecord(row.details);
583
+ if (!details || details.telemetry !== void 0) return false;
584
+ return details.exitCode !== void 0 || typeof details.durationMs === "number" || typeof details.aggregated === "string";
585
+ }
586
+ function assistantToolCalls(rows) {
587
+ const calls = /* @__PURE__ */ new Map();
588
+ for (const row of rows) {
589
+ if (row.role !== "assistant" || !Array.isArray(row.content)) continue;
590
+ for (const block of row.content) {
591
+ const call = asRecord(block);
592
+ if (call?.type === "toolCall" && typeof call.id === "string") calls.set(call.id, call);
593
+ }
594
+ }
595
+ return calls;
596
+ }
597
+ var TRUSTED_RELEASE = "2026.9.3";
598
+ function releaseOf(rows, calls, nested, version) {
599
+ if (version !== void 0 && isOpenClawVersion(version)) {
600
+ const trusted = openclawVersionAtLeast(version, TRUSTED_RELEASE);
601
+ return { recordsNestedCalls: trusted, marksFailedRows: trusted };
602
+ }
603
+ const parents = new Set(nested.map((call) => call.parentToolCallId));
604
+ const dispatchAction = rows.some((row) => (row.role === "toolResult" || row.role === "tool") && toolNameOf(row) === "dispatch_action" && asRecord(asRecord(row.details)?.tool) !== null) || [...calls].some(([id, call]) => call.name === "dispatch_action" && parents.has(id));
605
+ return { recordsNestedCalls: nested.length > 0 || dispatchAction, marksFailedRows: dispatchAction };
606
+ }
607
+ var OPENCLAW_VERSION = /^(\d+)\.(\d+)\.(\d+)(-.+)?$/;
608
+ function isOpenClawVersion(value) {
609
+ return OPENCLAW_VERSION.test(value.trim());
610
+ }
611
+ function openclawVersionAtLeast(a, b) {
612
+ const parse = (v) => {
613
+ const match = OPENCLAW_VERSION.exec(v.trim());
614
+ return match ? { parts: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] !== void 0 } : null;
615
+ };
616
+ const [x, y] = [parse(a), parse(b)];
617
+ if (!x || !y) return false;
618
+ for (let i = 0; i < 3; i += 1) {
619
+ const d = (x.parts[i] ?? 0) - (y.parts[i] ?? 0);
620
+ if (d !== 0) return d > 0;
621
+ }
622
+ return !x.pre || y.pre;
623
+ }
624
+ function toolNameOf(row) {
625
+ return typeof row.toolName === "string" ? row.toolName : typeof row.name === "string" ? row.name : "";
626
+ }
627
+ var NESTED_TOOL_ACTIVITY = "openclaw.nested-tool.v1";
628
+ function nestedCallOf(row) {
629
+ if (row.role !== "custom" || row.customType !== NESTED_TOOL_ACTIVITY) return null;
630
+ return asRecord(row.details);
631
+ }
632
+ function nestedVerdict(call) {
633
+ const toolName = typeof call.toolName === "string" ? call.toolName : "";
634
+ if (!toolName.startsWith(TOOL_PREFIX)) return "not_agentchat";
635
+ const result = asRecord(call.result);
636
+ if (call.isError === true || result !== null && failedResult(result.isError, asRecord(result.details))) return "failed";
637
+ return call.isError === false ? "ok" : "unknown";
638
+ }
639
+ var OTHER_SESSION_TOOLS = /* @__PURE__ */ new Set(["sessions_spawn", "sessions_send"]);
640
+ function delegatedToChild(rows, calls, nested) {
641
+ const names = (value) => typeof value === "string" && OTHER_SESSION_TOOLS.has(value);
642
+ for (const call of calls.values()) {
643
+ if (names(call.name)) return true;
644
+ if (typeof call.name === "string" && DISPATCHER_TOOL_NAMES.has(call.name) && names(dispatchTarget(call))) return true;
645
+ }
646
+ if (nested.some((call) => names(call.toolName))) return true;
647
+ return rows.some((row) => names(toolNameOf(row)) || names(asRecord(asRecord(row.details)?.tool)?.name));
648
+ }
649
+ function callVerdict(message, calls, release) {
650
+ const toolName = toolNameOf(message);
651
+ const details = asRecord(message.details);
652
+ if (toolName.startsWith(TOOL_PREFIX)) return directVerdict(message.isError, details);
653
+ const entry = asRecord(details?.tool);
654
+ if (entry && isAgentChatEntry(entry)) return dispatchedVerdict(message.isError, details);
655
+ if (!DISPATCHER_TOOL_NAMES.has(toolName) || entry) return "not_agentchat";
656
+ const target = dispatchTarget(typeof message.toolCallId === "string" ? calls.get(message.toolCallId) : void 0);
657
+ if (target === null) return "unknown";
658
+ if (!target.startsWith(TOOL_PREFIX)) return "not_agentchat";
659
+ if (failedResult(message.isError, details)) return "failed";
660
+ if (release.marksFailedRows && isTruncated(details) && message.isError === false && details?.status === void 0) return "ok";
661
+ return "unknown";
662
+ }
663
+ function isTruncated(details) {
664
+ return details?.persistedDetailsTruncated === true;
665
+ }
666
+ function directVerdict(isError, details) {
667
+ if (failedResult(isError, details)) return "failed";
668
+ if (isError !== false) return "unknown";
669
+ if (isTruncated(details)) return details?.status === void 0 && wasHostedResult(details) ? "ok" : "unknown";
670
+ return isHostedSuccessDetails(details) ? "ok" : "unknown";
671
+ }
672
+ function wasHostedResult(details) {
673
+ const keys = Array.isArray(details?.originalDetailKeys) ? details.originalDetailKeys : [];
674
+ return keys.includes("mcpServer") && (keys.includes("mcpTool") || keys.includes("mcpOperation"));
675
+ }
676
+ function dispatchedVerdict(isError, details) {
677
+ const result = asRecord(details?.result);
678
+ if (failedResult(isError, details)) return "failed";
679
+ if (result && failedResult(result.isError, asRecord(result.details))) return "failed";
680
+ const ok = isError === false && details?.status === void 0 && isHostedSuccessDetails(asRecord(result?.details));
681
+ return ok ? "ok" : "unknown";
682
+ }
683
+ function failedResult(isError, details) {
684
+ return isError === true || detailsSayFailed(details);
685
+ }
686
+ function detailsSayFailed(details) {
687
+ if (!details) return false;
688
+ if (details.ok === false || details.success === false) return true;
689
+ const status = typeof details.status === "string" ? details.status.trim().toLowerCase() : "";
690
+ const explicitlyOk = details.ok === true || details.success === true;
691
+ if (FAILURE_STATUSES.has(status) && !explicitlyOk) return true;
692
+ if (details.timedOut === true || Boolean(details.error)) return true;
693
+ if (status === "completed") return false;
694
+ const exitCode = details.exitCode;
695
+ return typeof exitCode === "number" && Number.isFinite(exitCode) && exitCode !== 0;
696
+ }
697
+ function isHostedSuccessDetails(details) {
698
+ if (!details || details.mcpServer !== MCP_SERVER_NAME || details.status !== void 0) return false;
699
+ return nonEmpty(details.mcpTool) !== void 0 || nonEmpty(details.mcpOperation) !== void 0;
700
+ }
701
+ function isAgentChatEntry(tool) {
710
702
  if (typeof tool.name === "string" && tool.name.startsWith(TOOL_PREFIX)) return true;
711
703
  if (tool.sourceName === MCP_SERVER_NAME) return true;
712
- const mcp = asRecord2(tool.mcp);
704
+ const mcp = asRecord(tool.mcp);
713
705
  return mcp?.serverName === MCP_SERVER_NAME;
714
706
  }
707
+ function dispatchTarget(call) {
708
+ const record = callArguments(call);
709
+ const selector = nonEmpty(record?.id) ?? nonEmpty(record?.toolId) ?? nonEmpty(record?.name);
710
+ if (!selector) return null;
711
+ const trimmed = selector.trim();
712
+ return trimmed.slice(trimmed.lastIndexOf(":") + 1);
713
+ }
714
+ function callArguments(call) {
715
+ if (!call) return null;
716
+ let args = call.arguments;
717
+ if (typeof args === "string") {
718
+ try {
719
+ args = JSON.parse(args);
720
+ } catch {
721
+ return null;
722
+ }
723
+ }
724
+ return asRecord(args);
725
+ }
715
726
  function unwrapMessage(row) {
716
- const record = asRecord2(row);
727
+ const record = asRecord(row);
717
728
  if (!record) return null;
718
729
  if (typeof record.role === "string") return record;
719
- const inner = asRecord2(record.message);
730
+ const inner = asRecord(record.message);
720
731
  return inner && typeof inner.role === "string" ? inner : null;
721
732
  }
722
- function asRecord2(value) {
733
+ function asRecord(value) {
723
734
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
724
735
  }
725
736
  function nonEmpty(value) {
@@ -975,7 +986,7 @@ function applyIntegrationConfig(cfg, params) {
975
986
  const changes = [];
976
987
  let next = cfg;
977
988
  const bareHandle = (params.handle ?? "").trim().replace(/^@/, "");
978
- if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle && isValidHandleShape(bareHandle)) {
989
+ if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle) {
979
990
  next = applyAgentchatAccountPatch(next, params.accountId, { agentHandle: bareHandle });
980
991
  changes.push(`channels.agentchat${params.accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID ? "" : `.accounts.${params.accountId}`}.agentHandle = ${bareHandle}`);
981
992
  }
@@ -1207,8 +1218,10 @@ function textsCachePath(accountId, stateDir) {
1207
1218
  return path2__namespace.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE);
1208
1219
  }
1209
1220
  function spellTextsForOpenClaw(texts) {
1221
+ const newer = texts;
1210
1222
  return {
1211
1223
  ...texts,
1224
+ ...typeof newer.reply_turn_template === "string" ? { reply_turn_template: spellToolsForOpenClaw(newer.reply_turn_template) } : {},
1212
1225
  wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),
1213
1226
  invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),
1214
1227
  identity_line: spellToolsForOpenClaw(texts.identity_line),
@@ -1308,57 +1321,15 @@ function getClient({ accountId, config, options }) {
1308
1321
 
1309
1322
  // src/channel.wizard.ts
1310
1323
  var JUST_REGISTERED_SENTINEL = "_agentchatJustRegistered";
1311
- var HANDLE_PATTERN2 = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
1312
- var HANDLE_MIN_LENGTH = 3;
1313
- var HANDLE_MAX_LENGTH = 30;
1314
- var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1315
- function isValidHandleShape2(value) {
1316
- return value.length >= HANDLE_MIN_LENGTH && value.length <= HANDLE_MAX_LENGTH && HANDLE_PATTERN2.test(value);
1317
- }
1318
- var OTP_PATTERN = /^\d{6}$/;
1324
+ var LABELS = {
1325
+ ...agentchatme.integration.account.DEFAULT_LABELS,
1326
+ handle: "Handle (your @name on AgentChat)"
1327
+ };
1319
1328
  function hasConfiguredKey(cfg, accountId) {
1320
1329
  return isApiKeyPresent(readAgentchatConfigField(cfg, accountId, "apiKey"));
1321
1330
  }
1322
- var MAX_START_RETRIES = 5;
1323
- async function promptEmail(prompter, opts = {}) {
1324
- return (await prompter.text({
1325
- message: opts.message ?? "Email \u2014 receives a 6-digit verification code",
1326
- placeholder: "you@example.com",
1327
- validate: (value) => {
1328
- const trimmed = value.trim();
1329
- if (!trimmed) return "Email is required";
1330
- if (!EMAIL_PATTERN.test(trimmed)) return "Not a valid email format";
1331
- return void 0;
1332
- }
1333
- })).trim();
1334
- }
1335
- async function promptHandle(prompter, opts = {}) {
1336
- return (await prompter.text({
1337
- message: opts.message ?? "Choose a handle (your @name on AgentChat)",
1338
- placeholder: "3\u201330 chars, lowercase a-z, 0-9, hyphens, starts with a letter",
1339
- ...opts.initialValue ? { initialValue: opts.initialValue } : {},
1340
- validate: (value) => {
1341
- const trimmed = value.trim();
1342
- if (!trimmed) return "Handle is required";
1343
- if (trimmed.length < HANDLE_MIN_LENGTH || trimmed.length > HANDLE_MAX_LENGTH) {
1344
- return `Length must be ${HANDLE_MIN_LENGTH}\u2013${HANDLE_MAX_LENGTH} chars (you entered ${trimmed.length})`;
1345
- }
1346
- if (!/^[a-z]/.test(trimmed)) return "Must start with a lowercase letter";
1347
- if (/[^a-z0-9-]/.test(trimmed)) {
1348
- return "Only lowercase letters, digits, and hyphens \u2014 no underscores, dots, or symbols";
1349
- }
1350
- if (trimmed.includes("--")) return "No consecutive hyphens";
1351
- if (trimmed.endsWith("-")) return "Cannot end with a hyphen";
1352
- return void 0;
1353
- }
1354
- })).trim();
1355
- }
1356
- async function promptDisplayName(prompter) {
1357
- return (await prompter.text({
1358
- message: "Display name (shown next to your @handle)",
1359
- placeholder: "e.g. Anton, Builder Bot, Sasha",
1360
- validate: () => void 0
1361
- })).trim();
1331
+ function nonEmpty2(value) {
1332
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
1362
1333
  }
1363
1334
  async function runChangeApiBaseFlow(params) {
1364
1335
  const { cfg, accountId, prompter } = params;
@@ -1396,388 +1367,182 @@ async function runChangeApiBaseFlow(params) {
1396
1367
  await prompter.note(`API base set to ${input}`, "Updated");
1397
1368
  return { cfg: patched };
1398
1369
  }
1399
- function describeEmailPolicyRejection(email, result) {
1400
- if (result.limit === void 0) return result.message;
1401
- return result.reason === "email-limit-reached" ? `${email} already backs ${result.limit} active agents \u2014 the per-email limit.` : `${email} has used all ${result.limit} of its lifetime account registrations.`;
1402
- }
1403
- async function promptEmailPolicyChoice(prompter, email, result) {
1404
- return prompter.select({
1405
- message: `${describeEmailPolicyRejection(email, result)} What next?`,
1406
- options: [
1407
- {
1408
- value: "retry",
1409
- label: "Use a different email address",
1410
- hint: "a +alias like you+agent2@example.com counts as a separate email"
1411
- },
1412
- {
1413
- value: "recover",
1414
- label: "Recover the API key of an agent this email already backs",
1415
- hint: "needs that agent\u2019s handle \u2014 a code goes to this email"
1416
- },
1417
- { value: "paste", label: "Paste a key from an existing agent" },
1418
- { value: "cancel", label: "Cancel registration" }
1419
- ],
1420
- initialValue: "retry"
1421
- });
1370
+ async function askText(prompter, message, opts = {}) {
1371
+ return (await prompter.text({
1372
+ message,
1373
+ ...opts,
1374
+ validate: (value) => value.trim() ? void 0 : "Required"
1375
+ })).trim();
1422
1376
  }
1423
- async function runRegisterFlow(params) {
1424
- const { cfg, accountId, prompter, apiBase } = params;
1425
- await prompter.note(
1426
- [
1427
- "Registration mints a new AgentChat agent identity tied to your email.",
1428
- "One email can back several agents (the server enforces the limit);",
1429
- "each one registers and verifies separately.",
1430
- "You will receive a 6-digit code to verify \u2014 check your inbox (and spam)."
1431
- ].join("\n"),
1432
- "AgentChat: register a new agent"
1433
- );
1434
- let email = await promptEmail(prompter);
1435
- let handle = await promptHandle(prompter);
1436
- const displayName = await promptDisplayName(prompter);
1437
- let startResult;
1438
- let startedOk = false;
1439
- for (let attempt = 1; attempt <= MAX_START_RETRIES; attempt += 1) {
1440
- const startSpinner = prompter.progress(
1441
- attempt === 1 ? "Sending verification code\u2026" : "Retrying\u2026"
1442
- );
1443
- try {
1444
- startResult = await registerAgentStart(
1445
- {
1446
- email,
1447
- handle,
1448
- ...displayName ? { displayName } : {}
1449
- },
1450
- { apiBase }
1451
- );
1452
- } catch (err) {
1453
- startSpinner.stop("Could not reach AgentChat");
1454
- await prompter.note(
1455
- `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
1456
- "Registration failed"
1457
- );
1458
- return "abort";
1459
- }
1460
- if (startResult.ok) {
1461
- startSpinner.stop(`Verification code sent to ${email}`);
1462
- startedOk = true;
1463
- break;
1464
- }
1465
- startSpinner.stop("Registration rejected");
1466
- switch (startResult.reason) {
1467
- case "invalid-handle":
1468
- case "handle-taken": {
1469
- const detail = startResult.reason === "handle-taken" ? `Handle @${handle} is already taken.` : "That handle is not acceptable (3\u201330 chars \u2014 lowercase letters/digits/hyphens; must start with a letter).";
1470
- await prompter.note(`${detail} Pick a different handle and we'll try again.`, "Pick a different handle");
1471
- handle = await promptHandle(prompter);
1472
- continue;
1473
- }
1474
- case "email-limit-reached":
1475
- case "email-exhausted": {
1476
- const choice = await promptEmailPolicyChoice(prompter, email, {
1477
- reason: startResult.reason,
1478
- limit: startResult.limit,
1479
- message: startResult.message
1480
- });
1481
- if (choice === "paste") return "user-chose-paste";
1482
- if (choice === "recover") return "user-chose-recover";
1483
- if (choice === "cancel") return "abort";
1484
- email = await promptEmail(prompter);
1485
- continue;
1486
- }
1487
- case "rate-limited": {
1488
- const wait = startResult.retryAfterSeconds ? ` Try again in ${startResult.retryAfterSeconds}s.` : "";
1489
- await prompter.note(`Too many registration attempts.${wait}`, "Rate limited");
1490
- return "abort";
1491
- }
1492
- case "otp-failed": {
1493
- await prompter.note(
1494
- "The verification-code email could not be sent. Try again in a minute, or paste an existing key instead.",
1495
- "OTP delivery failed"
1496
- );
1497
- return "abort";
1498
- }
1499
- case "network-error":
1500
- case "server-error":
1501
- case "validation":
1502
- default: {
1503
- await prompter.note(describeRegisterStartError(startResult), "Could not start registration");
1504
- return "abort";
1505
- }
1377
+ var EMAIL_PLACEHOLDER = "you@example.com";
1378
+ async function askCode(prompter, label) {
1379
+ for (; ; ) {
1380
+ const code = (await prompter.text({ message: label, placeholder: "leave blank for a new code or to cancel" })).trim();
1381
+ if (code) return { answer: "value", value: code };
1382
+ const choice = await prompter.select({
1383
+ message: "What would you like to do?",
1384
+ options: [
1385
+ { value: "new_code", label: "Send a new code" },
1386
+ { value: "enter", label: "Enter the code" },
1387
+ { value: "cancel", label: "Cancel", hint: "paste an existing key instead, or leave setup" }
1388
+ ],
1389
+ initialValue: "new_code"
1390
+ });
1391
+ if (choice === "new_code") return { answer: "new_code" };
1392
+ if (choice === "cancel") return { answer: "cancel" };
1393
+ }
1394
+ }
1395
+ function askThrough(prompter) {
1396
+ return async (question) => {
1397
+ if (question.field === "new_code") {
1398
+ const yes = await prompter.confirm({ message: "Send a new code?", initialValue: true });
1399
+ return yes ? { answer: "new_code" } : { answer: "cancel" };
1400
+ }
1401
+ if (question.field === "code") return askCode(prompter, question.label ?? LABELS.code);
1402
+ const label = question.label ?? LABELS[question.field];
1403
+ const handles = (question.handles ?? []).filter((handle) => handle.length > 0);
1404
+ if (handles.length > 0) {
1405
+ const picked = await prompter.select({
1406
+ message: label,
1407
+ options: [
1408
+ ...handles.map((handle) => ({ value: handle, label: `@${handle}` })),
1409
+ { value: "", label: "Another handle" }
1410
+ ]
1411
+ });
1412
+ if (picked) return { answer: "value", value: picked };
1506
1413
  }
1507
- }
1508
- if (!startedOk || !startResult || !startResult.ok) {
1509
- await prompter.note(
1510
- "Too many attempts. Restart the wizard to try again, or paste an existing key at the next prompt.",
1511
- "Registration failed"
1512
- );
1513
- return "abort";
1514
- }
1515
- const maxCodeAttempts = 3;
1516
- let verifyResult = null;
1517
- for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
1518
- const code = (await prompter.text({
1519
- message: attempt === 1 ? "Enter the 6-digit verification code from your email" : `Verification code (attempt ${attempt}/${maxCodeAttempts})`,
1520
- placeholder: "123456",
1521
- validate: (value) => {
1522
- const trimmed = value.trim();
1523
- if (!trimmed) return "Code is required";
1524
- if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
1525
- return void 0;
1526
- }
1527
- })).trim();
1528
- const verifySpinner = prompter.progress("Verifying code\u2026");
1414
+ const typed = await askText(prompter, label, question.field === "email" ? { placeholder: EMAIL_PLACEHOLDER } : {});
1415
+ return { answer: "value", value: typed };
1416
+ };
1417
+ }
1418
+ function fetchWithProgress(prompter) {
1419
+ return (async (input, init) => {
1420
+ const progress = prompter.progress("Contacting AgentChat\u2026");
1529
1421
  try {
1530
- verifyResult = await registerAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
1531
- } catch (err) {
1532
- verifySpinner.stop("Could not reach AgentChat");
1533
- await prompter.note(
1534
- `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
1535
- "Verification failed"
1536
- );
1537
- return "abort";
1538
- }
1539
- if (verifyResult.ok) {
1540
- verifySpinner.stop(`Registered as @${verifyResult.agent.handle}`);
1541
- break;
1542
- }
1543
- verifySpinner.stop("Verification failed");
1544
- if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
1545
- await prompter.note(
1546
- "That code did not match. Check your email and try again.",
1547
- "Invalid verification code"
1548
- );
1549
- continue;
1422
+ return await globalThis.fetch(input, init);
1423
+ } finally {
1424
+ progress.stop();
1550
1425
  }
1551
- await prompter.note(describeRegisterVerifyError(verifyResult), "Registration failed");
1552
- return "abort";
1553
- }
1554
- if (!verifyResult || !verifyResult.ok) {
1555
- await prompter.note(
1556
- "Too many incorrect codes. Restart the wizard to receive a new code.",
1557
- "Registration failed"
1558
- );
1559
- return "abort";
1560
- }
1561
- const patch = { apiKey: verifyResult.apiKey };
1562
- if (isValidHandleShape2(verifyResult.agent.handle)) {
1563
- patch.agentHandle = verifyResult.agent.handle;
1564
- }
1565
- const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch);
1426
+ });
1427
+ }
1428
+ function sleepWithProgress(prompter) {
1429
+ const label = (seconds) => `Waiting ${seconds} s\u2026`;
1430
+ return (ms) => new Promise((resolve) => {
1431
+ let left = Math.ceil(ms / 1e3);
1432
+ const progress = prompter.progress(label(left));
1433
+ const tick = setInterval(() => {
1434
+ left -= 1;
1435
+ if (left > 0) progress.update(label(left));
1436
+ }, 1e3);
1437
+ setTimeout(() => {
1438
+ clearInterval(tick);
1439
+ progress.stop();
1440
+ resolve();
1441
+ }, ms);
1442
+ });
1443
+ }
1444
+ async function registerInput(prompter) {
1566
1445
  await prompter.note(
1567
1446
  [
1568
- `Handle: @${verifyResult.agent.handle}`,
1569
- `Email: ${verifyResult.agent.email}`,
1570
- `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`
1447
+ "Registration creates a new AgentChat agent tied to your email address.",
1448
+ "Your handle is the agent\u2019s @name on AgentChat. AgentChat emails you a",
1449
+ "code to confirm the address \u2014 check your inbox (and spam)."
1571
1450
  ].join("\n"),
1572
- "AgentChat account created"
1451
+ "AgentChat: register a new agent"
1573
1452
  );
1574
- return {
1575
- cfg: nextCfg,
1576
- credentialValues: {
1577
- token: verifyResult.apiKey,
1578
- [JUST_REGISTERED_SENTINEL]: "1"
1579
- }
1580
- };
1581
- }
1582
- function describeRegisterStartError(result) {
1583
- switch (result.reason) {
1584
- case "invalid-handle":
1585
- return "That handle is not acceptable. Try a different one (3\u201330 chars \u2014 lowercase letters/digits/hyphens; must start with a letter).";
1586
- case "handle-taken":
1587
- return "That handle is already taken. Try a different one.";
1588
- case "email-limit-reached":
1589
- return `${result.limit === void 0 ? result.message : `This email already backs ${result.limit} active agents \u2014 the per-email limit.`} Use a different email (a +alias works), recover a key for one of its agents, or paste an existing key.`;
1590
- case "email-exhausted":
1591
- return `${result.limit === void 0 ? result.message : `This email has used all ${result.limit} of its lifetime account registrations.`} Use a different email (a +alias works), or paste a key from an existing agent.`;
1592
- case "rate-limited": {
1593
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1594
- return `Rate limited.${wait}`;
1595
- }
1596
- case "otp-failed":
1597
- return "The verification-code email could not be sent. Try again in a minute.";
1598
- case "network-error":
1599
- case "server-error":
1600
- case "validation":
1601
- default:
1602
- return result.message;
1603
- }
1604
- }
1605
- function describeRegisterVerifyError(result) {
1606
- switch (result.reason) {
1607
- case "expired":
1608
- return "This code expired. Restart the wizard to receive a new one.";
1609
- case "invalid-code":
1610
- return "Too many incorrect codes. Restart the wizard to receive a new one.";
1611
- case "handle-taken":
1612
- return "Your chosen handle was claimed by another registration in the meantime. Restart with a different handle.";
1613
- case "email-limit-reached":
1614
- return `${result.limit === void 0 ? result.message : `This email reached its limit of ${result.limit} active agents while you were verifying.`} Restart with a different email (a +alias works), or paste an existing key.`;
1615
- case "email-exhausted":
1616
- return `${result.limit === void 0 ? result.message : `This email used all ${result.limit} of its lifetime account registrations while you were verifying.`} Restart with a different email (a +alias works), or paste an existing key.`;
1617
- case "rate-limited": {
1618
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1619
- return `Rate limited.${wait}`;
1620
- }
1621
- case "network-error":
1622
- case "server-error":
1623
- case "unexpected-shape":
1624
- case "validation":
1625
- default:
1626
- return result.message;
1627
- }
1453
+ const email = await askText(prompter, LABELS.email, { placeholder: EMAIL_PLACEHOLDER });
1454
+ const handle = await askText(prompter, LABELS.handle);
1455
+ const displayName = (await prompter.text({
1456
+ message: "Display name (shown next to your @handle)",
1457
+ placeholder: "e.g. Anton, Builder Bot, Sasha"
1458
+ })).trim();
1459
+ return { email, handle, ...displayName ? { display_name: displayName } : {} };
1628
1460
  }
1629
- async function runRecoverFlow(params) {
1630
- const { cfg, accountId, prompter, apiBase } = params;
1631
- const storedHandle = readAgentchatConfigField(cfg, accountId, "agentHandle");
1632
- const defaultHandle = storedHandle && isValidHandleShape2(storedHandle) ? storedHandle : void 0;
1461
+ async function recoverInput(prompter, configuredHandle) {
1633
1462
  await prompter.note(
1634
1463
  [
1635
- "Recovery re-issues the API key for ONE agent \u2014 the handle you name below.",
1636
- "You need that handle and the email it registered with; a 6-digit code",
1637
- "goes to that email. The old key stops working the moment the new one",
1638
- "is minted.",
1639
- ...defaultHandle ? ["", `@${defaultHandle} is configured here \u2014 press Enter at the handle prompt to recover it.`] : []
1464
+ "Recovery issues a new API key for an agent you registered. AgentChat",
1465
+ "emails a code to the address the agent registered with; the old key",
1466
+ "stops working once the new one is issued.",
1467
+ ...configuredHandle ? ["", `@${configuredHandle} is configured here \u2014 press Enter at the handle prompt to recover it.`] : []
1640
1468
  ].join("\n"),
1641
1469
  "AgentChat: recover a lost API key"
1642
1470
  );
1643
- const handle = await promptHandle(prompter, {
1644
- message: "Handle of the agent to recover (its @name on AgentChat)",
1645
- ...defaultHandle ? { initialValue: defaultHandle } : {}
1646
- });
1647
- const email = await promptEmail(prompter, {
1648
- message: `Email @${handle} registered with \u2014 receives a 6-digit recovery code`
1649
- });
1650
- const startSpinner = prompter.progress("Requesting recovery code\u2026");
1651
- let startResult;
1471
+ if (!configuredHandle) return {};
1472
+ const handle = (await prompter.text({ message: LABELS.handle, initialValue: configuredHandle })).trim();
1473
+ return handle ? { handle } : {};
1474
+ }
1475
+ async function notCompleted(prompter, kind) {
1476
+ await prompter.note(
1477
+ `${kind === "register" ? "Registration" : "Recovery"} was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.`,
1478
+ "Falling back to credential entry"
1479
+ );
1480
+ return void 0;
1481
+ }
1482
+ async function runAccountFlow(params) {
1483
+ const { kind, cfg, accountId, prompter } = params;
1484
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1485
+ const input = kind === "register" ? await registerInput(prompter) : await recoverInput(prompter, nonEmpty2(readAgentchatConfigField(cfg, accountId, "agentHandle")));
1486
+ let result;
1652
1487
  try {
1653
- startResult = await recoverAgentStart({ email, handle }, { apiBase });
1488
+ result = await agentchatme.integration.account.run({
1489
+ kind,
1490
+ input,
1491
+ labels: LABELS,
1492
+ ask: askThrough(prompter),
1493
+ show: (message) => prompter.note(message, "AgentChat"),
1494
+ sleep: sleepWithProgress(prompter),
1495
+ ...accountCallOptions({ apiBase, fetch: fetchWithProgress(prompter) })
1496
+ });
1654
1497
  } catch (err) {
1655
- startSpinner.stop("Could not reach AgentChat");
1656
- await prompter.note(
1657
- `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
1658
- "Recovery failed"
1659
- );
1660
- return "abort";
1661
- }
1662
- if (!startResult.ok) {
1663
- startSpinner.stop("Recovery rejected");
1664
- await prompter.note(describeRecoverStartError(startResult), "Could not start recovery");
1665
- return "abort";
1666
- }
1667
- startSpinner.stop(startResult.message);
1668
- const maxCodeAttempts = 3;
1669
- let verifyResult = null;
1670
- for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
1671
- const code = (await prompter.text({
1672
- message: attempt === 1 ? `Enter the 6-digit recovery code (check ${email}, including spam)` : `Recovery code (attempt ${attempt}/${maxCodeAttempts})`,
1673
- placeholder: "123456",
1674
- validate: (value) => {
1675
- const trimmed = value.trim();
1676
- if (!trimmed) return "Code is required";
1677
- if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
1678
- return void 0;
1679
- }
1680
- })).trim();
1681
- const verifySpinner = prompter.progress("Verifying code\u2026");
1682
- try {
1683
- verifyResult = await recoverAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
1684
- } catch (err) {
1685
- verifySpinner.stop("Could not reach AgentChat");
1686
- await prompter.note(
1687
- `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
1688
- "Recovery failed"
1689
- );
1690
- return "abort";
1691
- }
1692
- if (verifyResult.ok) {
1693
- verifySpinner.stop(`Recovered @${verifyResult.handle}`);
1694
- break;
1695
- }
1696
- verifySpinner.stop("Verification failed");
1697
- if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
1698
- await prompter.note(
1699
- "That code did not match. Check your email and try again \u2014 if no code arrived, the handle and email may not belong to the same agent.",
1700
- "Invalid recovery code"
1701
- );
1702
- continue;
1703
- }
1704
- await prompter.note(describeRecoverVerifyError(verifyResult), "Recovery failed");
1705
- return "abort";
1706
- }
1707
- if (!verifyResult || !verifyResult.ok) {
1498
+ if (err instanceof setup.WizardCancelledError) throw err;
1499
+ const unreached = err instanceof agentchatme.ConnectionError || err instanceof Error && err.name === "AbortError";
1708
1500
  await prompter.note(
1709
- "Too many incorrect codes. Restart the wizard to request a new one \u2014 and double-check the handle and email belong to the same agent.",
1710
- "Recovery failed"
1501
+ err instanceof Error ? err.message : String(err),
1502
+ unreached ? "Could not reach AgentChat" : `${kind === "register" ? "Registration" : "Recovery"} failed`
1711
1503
  );
1712
- return "abort";
1504
+ return notCompleted(prompter, kind);
1713
1505
  }
1714
- const patch = { apiKey: verifyResult.apiKey };
1715
- if (isValidHandleShape2(verifyResult.handle)) {
1716
- patch.agentHandle = verifyResult.handle;
1717
- }
1718
- const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch);
1506
+ if (result.outcome !== "done") return notCompleted(prompter, kind);
1507
+ const nextCfg = applyAgentchatAccountPatch(cfg, accountId, { apiKey: result.apiKey, agentHandle: result.handle });
1719
1508
  await prompter.note(
1720
1509
  [
1721
- `Handle: @${verifyResult.handle}`,
1722
- `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`,
1723
- "",
1724
- "The previous key for this agent has been revoked."
1510
+ `Handle: @${result.handle}`,
1511
+ `API key: ${redactKey(result.apiKey)} (saved to your OpenClaw config)`
1725
1512
  ].join("\n"),
1726
- "AgentChat API key recovered"
1513
+ kind === "register" ? "AgentChat account created" : "AgentChat API key recovered"
1727
1514
  );
1728
1515
  return {
1729
1516
  cfg: nextCfg,
1730
1517
  credentialValues: {
1731
- token: verifyResult.apiKey,
1518
+ token: result.apiKey,
1732
1519
  [JUST_REGISTERED_SENTINEL]: "1"
1733
1520
  }
1734
1521
  };
1735
1522
  }
1736
- function describeRecoverStartError(result) {
1737
- switch (result.reason) {
1738
- case "rate-limited": {
1739
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1740
- return `Too many recovery attempts from this network.${wait}`;
1741
- }
1742
- case "validation":
1743
- return `AgentChat rejected the request: ${result.message}`;
1744
- case "network-error":
1745
- case "server-error":
1746
- case "unexpected-shape":
1747
- default:
1748
- return result.message;
1749
- }
1750
- }
1751
- function describeRecoverVerifyError(result) {
1752
- switch (result.reason) {
1753
- case "expired":
1754
- return "This recovery code expired. Restart the wizard to request a new one.";
1755
- case "invalid-code":
1756
- return "Too many incorrect codes. Restart the wizard to request a new one.";
1757
- case "handle-required": {
1758
- const handles = result.handles ?? [];
1759
- const list = handles.length > 0 ? `
1760
-
1761
- Agents on this email:
1762
- ${handles.map((h) => ` @${h}`).join("\n")}` : "";
1763
- return `This email backs more than one agent. Run recovery again and enter the handle you want to recover.${list}`;
1764
- }
1765
- case "rate-limited": {
1766
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1767
- return `Rate limited.${wait}`;
1768
- }
1769
- case "network-error":
1770
- case "server-error":
1771
- case "unexpected-shape":
1772
- case "validation":
1773
- default:
1774
- return result.message;
1775
- }
1776
- }
1777
1523
  function redactKey(apiKey) {
1778
1524
  if (apiKey.length < 12) return "\u2022\u2022\u2022\u2022";
1779
1525
  return `${apiKey.slice(0, 8)}\u2026${apiKey.slice(-4)}`;
1780
1526
  }
1527
+ async function saveEnteredKey(cfg, accountId, value, key) {
1528
+ if (typeof value !== "string" || !nonEmpty2(key)) return cfg;
1529
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1530
+ let check;
1531
+ try {
1532
+ check = await checkApiKey(key, { apiBase });
1533
+ } catch {
1534
+ check = null;
1535
+ }
1536
+ if (check !== null && !check.ok) return cfg;
1537
+ const handle = check?.handle;
1538
+ const sameKey = readAgentchatConfigField(cfg, accountId, "apiKey") === value;
1539
+ const withKey = applyAgentchatAccountPatch(cfg, accountId, {
1540
+ apiKey: value,
1541
+ // A new key whose handle is unknown must not keep the old key's handle.
1542
+ ...handle ? { agentHandle: handle } : sameKey ? {} : { agentHandle: void 0 }
1543
+ });
1544
+ return applyIntegrationConfig(withKey, { accountId, handle, apiKey: key, apiBase: apiBase ?? DEFAULT_API_BASE }).cfg;
1545
+ }
1781
1546
  var agentchatSetupWizard = {
1782
1547
  channel: AGENTCHAT_CHANNEL_ID,
1783
1548
  // AgentChat is one-agent-per-account by product design — the agent IS the
@@ -1822,9 +1587,9 @@ var agentchatSetupWizard = {
1822
1587
  "AgentChat is a messaging platform for AI agents \u2014 direct messages,",
1823
1588
  "groups, presence, attachments. Registration is free.",
1824
1589
  "",
1825
- "This wizard will mint a new account via email OTP, accept an existing",
1826
- "API key, or recover a lost key (handle + email OTP) \u2014 your choice in",
1827
- "the next prompt."
1590
+ "This wizard registers a new agent by email code, accepts an existing",
1591
+ "API key, or recovers a lost key by email code \u2014 your choice in the",
1592
+ "next prompt."
1828
1593
  ]
1829
1594
  },
1830
1595
  prepare: async ({ cfg, accountId, credentialValues, prompter }) => {
@@ -1860,7 +1625,7 @@ var agentchatSetupWizard = {
1860
1625
  options: [
1861
1626
  {
1862
1627
  value: "register",
1863
- label: "Register a new agent (email OTP)",
1628
+ label: "Register a new agent (email code)",
1864
1629
  hint: "no account yet \u2014 the wizard creates one"
1865
1630
  },
1866
1631
  {
@@ -1870,64 +1635,14 @@ var agentchatSetupWizard = {
1870
1635
  },
1871
1636
  {
1872
1637
  value: "recover",
1873
- label: "Recover a lost API key (handle + email OTP)",
1638
+ label: "Recover a lost API key (email code)",
1874
1639
  hint: "an agent exists but its key is gone \u2014 re-issue it"
1875
1640
  }
1876
1641
  ],
1877
1642
  initialValue: "register"
1878
1643
  });
1879
- if (choice === "paste") {
1880
- return;
1881
- }
1882
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1883
- const recover = async () => {
1884
- try {
1885
- const result = await runRecoverFlow({ cfg, accountId, prompter, apiBase });
1886
- if (result === "abort") {
1887
- await prompter.note(
1888
- "Recovery was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
1889
- "Falling back to credential entry"
1890
- );
1891
- return;
1892
- }
1893
- return result;
1894
- } catch (err) {
1895
- if (err instanceof setup.WizardCancelledError) throw err;
1896
- await prompter.note(
1897
- `${err instanceof Error ? err.message : String(err)}`,
1898
- "Recovery flow failed"
1899
- );
1900
- return;
1901
- }
1902
- };
1903
- if (choice === "recover") {
1904
- return await recover();
1905
- }
1906
- let registerOutcome;
1907
- try {
1908
- registerOutcome = await runRegisterFlow({ cfg, accountId, prompter, apiBase });
1909
- } catch (err) {
1910
- if (err instanceof setup.WizardCancelledError) throw err;
1911
- await prompter.note(
1912
- `${err instanceof Error ? err.message : String(err)}`,
1913
- "Registration flow failed"
1914
- );
1915
- return;
1916
- }
1917
- if (registerOutcome === "abort") {
1918
- await prompter.note(
1919
- "Registration was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
1920
- "Falling back to credential entry"
1921
- );
1922
- return;
1923
- }
1924
- if (registerOutcome === "user-chose-paste") {
1925
- return;
1926
- }
1927
- if (registerOutcome === "user-chose-recover") {
1928
- return await recover();
1929
- }
1930
- return registerOutcome;
1644
+ if (choice === "paste") return;
1645
+ return await runAccountFlow({ kind: choice, cfg, accountId, prompter });
1931
1646
  },
1932
1647
  credentials: [
1933
1648
  {
@@ -1940,9 +1655,9 @@ var agentchatSetupWizard = {
1940
1655
  inputPrompt: "Paste your AgentChat API key (ac_\u2026)",
1941
1656
  helpTitle: "AgentChat API key",
1942
1657
  helpLines: [
1943
- "Format: ac_ followed by 43 base64url characters. Validated against",
1944
- "GET /v1/agents/me during this wizard \u2014 bad keys fail fast instead",
1945
- "of flapping reconnects at runtime."
1658
+ "AgentChat checks the key before it is saved: a key it does not",
1659
+ "accept is not saved, so a bad key fails here instead of flapping",
1660
+ "reconnects at runtime."
1946
1661
  ],
1947
1662
  allowEnv: () => true,
1948
1663
  shouldPrompt: ({ credentialValues, currentValue }) => {
@@ -1960,61 +1675,67 @@ var agentchatSetupWizard = {
1960
1675
  resolvedValue: configured ? apiKey : void 0,
1961
1676
  envValue
1962
1677
  };
1678
+ },
1679
+ // The key the person entered, checked before it is saved.
1680
+ applySet: ({ cfg, accountId, value, resolvedValue }) => saveEnteredKey(cfg, accountId, value, resolvedValue),
1681
+ applyUseEnv: ({ cfg, accountId }) => {
1682
+ const key = readEnv_js$1.readApiKeyFromEnv(MIN_API_KEY_LENGTH);
1683
+ return key ? saveEnteredKey(cfg, accountId, key, key) : cfg;
1963
1684
  }
1964
1685
  }
1965
1686
  ],
1966
1687
  finalize: async ({ cfg, accountId, credentialValues, prompter }) => {
1967
- const apiKey = typeof credentialValues.token === "string" && credentialValues.token.length >= MIN_API_KEY_LENGTH ? credentialValues.token : readAgentchatConfigField(cfg, accountId, "apiKey");
1968
- if (!apiKey || !isApiKeyPresent(apiKey)) {
1969
- return;
1970
- }
1688
+ const stored = nonEmpty2(readAgentchatConfigField(cfg, accountId, "apiKey"));
1689
+ const apiKey = nonEmpty2(credentialValues.token) ?? stored;
1690
+ if (!apiKey) return;
1971
1691
  const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1972
- const spinner = prompter.progress("Validating API key against AgentChat\u2026");
1692
+ const spinner = prompter.progress("Checking the API key with AgentChat\u2026");
1693
+ let check;
1973
1694
  try {
1974
- const result = await validateApiKey(apiKey, { apiBase });
1975
- if (result.ok) {
1976
- spinner.stop(`Authenticated as @${result.agent.handle}`);
1977
- const handle = result.agent.handle;
1978
- const resolvedBase = apiBase ?? DEFAULT_API_BASE2;
1979
- const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
1980
- const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
1981
- const failed = placed.steps.filter((s) => s.status === "failed");
1982
- const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
1983
- await prompter.note(
1984
- [
1985
- ...formatPlacement(placed.steps),
1986
- "",
1987
- placed.mcp === "added" || placed.steps.some((s) => s.name === "key" && s.status === "changed") ? "Restart the gateway once so its environment carries the key and it connects the hosted tools. Then `openclaw channels status` shows the integration and the tools." : "The agent is reachable: a peer's message wakes it; the agent decides with its own model; it answers through the hosted AgentChat tools.",
1988
- ...failed.length > 0 ? ["", "Some placement failed (above). Your account is configured; re-run `openclaw channels add agentchat` after fixing the path, or `openclaw doctor --fix` for the config entry."] : [],
1989
- ...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
1990
- ].join("\n"),
1991
- "AgentChat integration placed"
1992
- );
1993
- const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
1994
- return { cfg: applied.cfg };
1995
- }
1996
- spinner.stop(`API key did not pass the live check (${result.reason})`);
1695
+ check = await checkApiKey(apiKey, { apiBase });
1696
+ } catch (err) {
1697
+ spinner.stop("Could not reach AgentChat to check the key");
1997
1698
  await prompter.note(
1998
1699
  [
1999
- result.message,
1700
+ err instanceof Error ? err.message : String(err),
2000
1701
  "",
2001
- "The config was saved \u2014 you can re-run `openclaw channels add agentchat`",
2002
- "to replace the key, or edit ~/.openclaw/config.yaml directly."
1702
+ stored === apiKey ? "The config was saved \u2014 the runtime will retry on startup." : "The key was not saved."
2003
1703
  ].join("\n"),
2004
- "AgentChat validation warning"
1704
+ "AgentChat API unreachable"
2005
1705
  );
2006
- } catch (err) {
2007
- spinner.stop("Could not reach AgentChat for validation");
1706
+ return;
1707
+ }
1708
+ if (!check.ok) {
1709
+ spinner.stop("AgentChat did not accept the API key");
2008
1710
  await prompter.note(
2009
1711
  [
2010
- err instanceof Error ? err.message : String(err),
1712
+ check.message,
2011
1713
  "",
2012
- "The config was saved \u2014 the runtime will retry on startup."
1714
+ stored === apiKey ? "This key is the one in your OpenClaw config. Re-run `openclaw channels add agentchat` \u2192 Replace the API key to recover a lost key or paste another one." : "The key was not saved. Re-run `openclaw channels add agentchat` to paste another key, register a new agent, or recover a lost key."
2013
1715
  ].join("\n"),
2014
- "AgentChat API unreachable"
1716
+ "AgentChat API key not accepted"
2015
1717
  );
1718
+ return;
2016
1719
  }
2017
- return;
1720
+ spinner.stop(`Authenticated as @${check.handle}`);
1721
+ const handle = check.handle;
1722
+ const resolvedBase = apiBase ?? DEFAULT_API_BASE;
1723
+ const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
1724
+ const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
1725
+ const failed = placed.steps.filter((s) => s.status === "failed");
1726
+ const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
1727
+ await prompter.note(
1728
+ [
1729
+ ...formatPlacement(placed.steps),
1730
+ "",
1731
+ placed.mcp === "added" || placed.steps.some((s) => s.name === "key" && s.status === "changed") ? "Restart the gateway once so its environment carries the key and it connects the hosted tools. Then `openclaw channels status` shows the integration and the tools." : "The agent is reachable: a peer's message wakes it; the agent decides with its own model; it answers through the hosted AgentChat tools.",
1732
+ ...failed.length > 0 ? ["", "Some placement failed (above). Your account is configured; re-run `openclaw channels add agentchat` after fixing the path, or `openclaw doctor --fix` for the config entry."] : [],
1733
+ ...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
1734
+ ].join("\n"),
1735
+ "AgentChat integration placed"
1736
+ );
1737
+ const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
1738
+ return { cfg: applied.cfg };
2018
1739
  },
2019
1740
  completionNote: {
2020
1741
  title: "AgentChat is ready",
@@ -3215,6 +2936,12 @@ function logEvent(event, logger, metrics) {
3215
2936
  case "echo":
3216
2937
  logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "own echo \u2014 not a wake");
3217
2938
  return;
2939
+ case "notice":
2940
+ logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "system notice \u2014 acked, not a wake");
2941
+ return;
2942
+ case "gate_chunk":
2943
+ logger.debug({ cycle: event.cycle, chunk: event.index, of: event.of, cards: event.cards, outcome: event.outcome, undecided: event.undecided, ...event.failure ? { failure: event.failure } : {} }, "gate chunk");
2944
+ return;
3218
2945
  case "cycle": {
3219
2946
  const s = event.summary;
3220
2947
  const fields = {
@@ -3623,7 +3350,7 @@ var agentchatStatusAdapter = {
3623
3350
  const servedFrom = live?.texts?.source;
3624
3351
  const textsSource = live ? servedFrom === "server" || servedFrom === "cache" ? servedFrom : "missing" : void 0;
3625
3352
  const socketCounters = live?.metrics?.snapshot?.();
3626
- const integration6 = {
3353
+ const integration8 = {
3627
3354
  mode: readEnv_js.readWakeModeFromEnv().mode,
3628
3355
  ...health ? { state: health.state } : {},
3629
3356
  ...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
@@ -3640,7 +3367,7 @@ var agentchatStatusAdapter = {
3640
3367
  pausedByOwner: me.paused_by_owner ?? "none",
3641
3368
  mcp,
3642
3369
  placement,
3643
- integration: integration6,
3370
+ integration: integration8,
3644
3371
  ...refusal ? { refusal } : {},
3645
3372
  ...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
3646
3373
  };
@@ -3707,7 +3434,7 @@ var agentchatDoctorAdapter = {
3707
3434
  continue;
3708
3435
  }
3709
3436
  const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
3710
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3437
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3711
3438
  const handle = readAgentchatConfigField(cfg, accountId, "agentHandle");
3712
3439
  const agentId = resolvePlacementAgentId(cfg, accountId);
3713
3440
  for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {
@@ -3746,16 +3473,16 @@ var agentchatDoctorAdapter = {
3746
3473
  for (const accountId of listConfiguredAccountIds(cfg)) {
3747
3474
  if (!isAgentchatAccountEnabled(cfg, accountId)) continue;
3748
3475
  const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
3749
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3476
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3750
3477
  bases.set(apiBase, apiKey);
3751
3478
  if (apiKey && !readAgentchatConfigField(cfg, accountId, "agentHandle")) {
3752
3479
  try {
3753
- const result = await validateApiKey(apiKey, { apiBase });
3480
+ const result = await checkApiKey(apiKey, { apiBase });
3754
3481
  if (result.ok) {
3755
- next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.agent.handle });
3756
- changes.push(`set channels.agentchat${accountId === "default" ? "" : `.accounts.${accountId}`}.agentHandle = ${result.agent.handle}`);
3482
+ next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.handle });
3483
+ changes.push(`set channels.agentchat${accountId === "default" ? "" : `.accounts.${accountId}`}.agentHandle = ${result.handle}`);
3757
3484
  } else {
3758
- warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and the key did not pass the live check (${result.reason}): ${result.message}`);
3485
+ warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and the key did not pass the live check (${result.code}): ${result.message}`);
3759
3486
  }
3760
3487
  } catch (err) {
3761
3488
  warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and AgentChat was not reachable to learn it: ${err instanceof Error ? err.message : String(err)}`);
@@ -3810,7 +3537,7 @@ var uiHints = {
3810
3537
  label: "AgentChat API key",
3811
3538
  placeholder: "ac_\u2026",
3812
3539
  sensitive: true,
3813
- 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."
3540
+ help: "The setup wizard registers a new agent or recovers a lost key by email code, or accepts an existing ac_\u2026 key; setup checks a key with AgentChat before saving it."
3814
3541
  },
3815
3542
  apiBase: {
3816
3543
  label: "API base URL",
@@ -3821,19 +3548,26 @@ var uiHints = {
3821
3548
  agentHandle: {
3822
3549
  label: "Agent handle",
3823
3550
  placeholder: "my-agent",
3824
- help: "3\u201330 chars, lowercase letters/digits/hyphens; must start with a letter."
3551
+ help: "The handle the API key belongs to, as AgentChat returned it; setup and `openclaw doctor --fix` write it."
3825
3552
  },
3826
3553
  reconnect: { label: "Reconnect backoff", advanced: true },
3827
3554
  ping: { label: "WebSocket ping cadence", advanced: true },
3828
3555
  outbound: { label: "Outbound send tuning", advanced: true },
3829
3556
  observability: { label: "Logs & metrics", advanced: true }
3830
3557
  };
3831
- var HANDLE_SHAPE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
3832
- function validHandle(value) {
3558
+ function handleOf(value) {
3833
3559
  if (typeof value !== "string") return void 0;
3834
3560
  const bare = value.trim().replace(/^@/, "");
3835
- return bare.length >= 3 && bare.length <= 30 && HANDLE_SHAPE.test(bare) ? bare : void 0;
3561
+ return bare.length > 0 ? bare : void 0;
3562
+ }
3563
+ function keyRefusal(check) {
3564
+ return [
3565
+ `AgentChat did not accept the API key (${check.code}): ${check.message}`,
3566
+ "The key was not saved. Run `openclaw channels add agentchat` to register a new agent or recover a lost key (email code)."
3567
+ ].join("\n");
3836
3568
  }
3569
+ var keyAskedBeforeWrite = null;
3570
+ var keyDigest = (apiKey) => crypto.createHash("sha256").update(apiKey).digest("hex");
3837
3571
  function say(runtime, level, line) {
3838
3572
  const env = runtime;
3839
3573
  const fn = env?.[level];
@@ -3841,13 +3575,18 @@ function say(runtime, level, line) {
3841
3575
  }
3842
3576
  var agentchatSetupAdapter = {
3843
3577
  /**
3844
- * Pre-write gate: cheap, sync check that the caller supplied an API key
3845
- * that's at least plausibly shaped. Real authentication happens in
3846
- * `prepareAccountConfigInput` / `afterAccountConfigWritten`.
3578
+ * Pre-write gate: a key AgentChat turned away in
3579
+ * `prepareAccountConfigInput` ends here (OpenClaw prints the line and
3580
+ * writes nothing); otherwise a cheap, sync check that the caller supplied
3581
+ * an API key that's at least plausibly shaped. On an OpenClaw without
3582
+ * `prepareAccountConfigInput`, the lifecycle hook refuses a rejected key
3583
+ * before the write.
3847
3584
  */
3848
3585
  validateInput({ input }) {
3586
+ const refusal = input.keyRefusal;
3587
+ if (typeof refusal === "string" && refusal.length > 0) return refusal;
3849
3588
  if (typeof input.token !== "string" || input.token.trim().length === 0) {
3850
- return "apiKey is required \u2014 pass via --token, or run `openclaw channels add agentchat` to register a new agent or recover a lost key (handle + email OTP)";
3589
+ return "apiKey is required \u2014 pass via --token, or run `openclaw channels add agentchat` to register a new agent or recover a lost key (email code)";
3851
3590
  }
3852
3591
  if (input.token.length < MIN_API_KEY_LENGTH) {
3853
3592
  return `apiKey looks too short (got ${input.token.length} chars, expect \u2265${MIN_API_KEY_LENGTH})`;
@@ -3865,29 +3604,31 @@ var agentchatSetupAdapter = {
3865
3604
  return null;
3866
3605
  },
3867
3606
  /**
3868
- * Learn the handle the key authenticates as BEFORE the write, so
3869
- * `applyAccountConfig` persists it in the same config write OpenClaw
3870
- * already makes. A key that does not validate leaves the input untouched
3871
- * (the write still happens; the error line says what to fix).
3607
+ * Ask AgentChat about the key BEFORE the write. Accepted: the handle it
3608
+ * belongs to goes into the same config write OpenClaw already makes.
3609
+ * Turned away (401 / 403): the input carries the refusal, `validateInput`
3610
+ * returns it, and OpenClaw writes nothing. No verdict (unreachable, a
3611
+ * 5xx): the key is written for the runtime to try, as the wizard does.
3872
3612
  */
3873
- async prepareAccountConfigInput({ accountId, input, runtime }) {
3613
+ async prepareAccountConfigInput({ cfg, accountId, input, runtime }) {
3874
3614
  const apiKey = typeof input.token === "string" ? input.token : void 0;
3875
3615
  if (!apiKey || apiKey.length < MIN_API_KEY_LENGTH) return input;
3876
- const apiBase = typeof input.url === "string" && input.url.length > 0 ? input.url : void 0;
3616
+ const apiBase = typeof input.url === "string" && input.url.length > 0 ? input.url : readAgentchatConfigField(cfg, accountId, "apiBase");
3617
+ keyAskedBeforeWrite = keyDigest(apiKey);
3877
3618
  try {
3878
- const result = await validateApiKey(apiKey, { apiBase });
3619
+ const result = await checkApiKey(apiKey, { apiBase });
3879
3620
  if (result.ok) {
3880
- say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.agent.handle} (${result.agent.email})`);
3621
+ say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.handle}`);
3881
3622
  try {
3882
3623
  placeApiKeyInDotEnv(apiKey);
3883
3624
  } catch (err) {
3884
3625
  say(runtime, "error", `[agentchat:${accountId}] could not write AGENTCHAT_API_KEY to ${dotEnvPath()}: ${err instanceof Error ? err.message : String(err)}`);
3885
3626
  }
3886
- return { ...input, agentHandle: result.agent.handle };
3627
+ return { ...input, agentHandle: result.handle };
3887
3628
  }
3888
- say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`);
3629
+ return { ...input, keyRefusal: keyRefusal(result) };
3889
3630
  } catch (err) {
3890
- say(runtime, "error", `[agentchat:${accountId}] live key validation failed: ${err instanceof Error ? err.message : String(err)}`);
3631
+ say(runtime, "error", `[agentchat:${accountId}] no verdict on the API key, saving it for the runtime to try: ${err instanceof Error ? err.message : String(err)}`);
3891
3632
  }
3892
3633
  return input;
3893
3634
  },
@@ -3901,12 +3642,12 @@ var agentchatSetupAdapter = {
3901
3642
  const patch = {};
3902
3643
  if (typeof input.token === "string" && input.token.length > 0) patch.apiKey = input.token;
3903
3644
  if (typeof input.url === "string" && input.url.length > 0) patch.apiBase = input.url;
3904
- const handle = validHandle(input.agentHandle);
3645
+ const handle = handleOf(input.agentHandle);
3905
3646
  if (handle) patch.agentHandle = handle;
3906
3647
  const withAccount = applyAgentchatAccountPatch(cfg, accountId, patch);
3907
3648
  const apiKey = readAgentchatConfigField(withAccount, accountId, "apiKey");
3908
3649
  if (!apiKey) return withAccount;
3909
- const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3650
+ const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE;
3910
3651
  return applyIntegrationConfig(withAccount, { accountId, handle, apiKey, apiBase }).cfg;
3911
3652
  },
3912
3653
  /**
@@ -3917,16 +3658,16 @@ var agentchatSetupAdapter = {
3917
3658
  async afterAccountConfigWritten({ cfg, accountId, input, runtime }) {
3918
3659
  const apiKey = typeof input.token === "string" ? input.token : readAgentchatConfigField(cfg, accountId, "apiKey");
3919
3660
  if (!apiKey) return;
3920
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3921
- let handle = validHandle(input.agentHandle) ?? readAgentchatConfigField(cfg, accountId, "agentHandle");
3661
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3662
+ let handle = handleOf(input.agentHandle) ?? handleOf(readAgentchatConfigField(cfg, accountId, "agentHandle"));
3922
3663
  if (!handle) {
3923
3664
  try {
3924
- const result = await validateApiKey(apiKey, { apiBase });
3665
+ const result = await checkApiKey(apiKey, { apiBase });
3925
3666
  if (result.ok) {
3926
- handle = result.agent.handle;
3667
+ handle = result.handle;
3927
3668
  say(runtime, "log", `[agentchat:${accountId}] authenticated as @${handle}; run \`openclaw doctor --fix\` to persist channels.agentchat.agentHandle`);
3928
3669
  } else {
3929
- say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`);
3670
+ say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.code}): ${result.message}`);
3930
3671
  return;
3931
3672
  }
3932
3673
  } catch (err) {
@@ -3960,8 +3701,24 @@ function accountSectionPersistable(cfg, accountId) {
3960
3701
  if (!raw) return true;
3961
3702
  return agentchatChannelConfigSchema.safeParse(raw).success;
3962
3703
  }
3704
+ async function refuseRejectedKey(prevCfg, nextCfg, accountId, runtime) {
3705
+ const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
3706
+ if (!apiKey || apiKey === readAgentchatConfigField(prevCfg, accountId, "apiKey")) return;
3707
+ if (keyAskedBeforeWrite === keyDigest(apiKey)) return;
3708
+ let check;
3709
+ try {
3710
+ check = await checkApiKey(apiKey, { apiBase: readAgentchatConfigField(nextCfg, accountId, "apiBase") });
3711
+ } catch (err) {
3712
+ say(runtime, "error", `[agentchat:${accountId}] no verdict on the API key, saving it for the runtime to try: ${err instanceof Error ? err.message : String(err)}`);
3713
+ return;
3714
+ }
3715
+ if (check.ok) return;
3716
+ say(runtime, "error", keyRefusal(check));
3717
+ throw new setup.WizardCancelledError("AgentChat did not accept the API key");
3718
+ }
3963
3719
  var agentchatLifecycleAdapter = {
3964
3720
  async onAccountConfigChanged({ prevCfg, nextCfg, accountId, runtime }) {
3721
+ await refuseRejectedKey(prevCfg, nextCfg, accountId, runtime);
3965
3722
  const wasEnabled = isAccountEnabled(prevCfg, accountId);
3966
3723
  const isEnabled = isAccountEnabled(nextCfg, accountId);
3967
3724
  if (wasEnabled === isEnabled) return;
@@ -3977,13 +3734,13 @@ var agentchatLifecycleAdapter = {
3977
3734
  for (const line of removeIntegrationFiles(nextCfg, accountId, { clearKey: false })) say(runtime, "log", `[agentchat:${accountId}] ${line}`);
3978
3735
  return;
3979
3736
  }
3980
- const handle = validHandle(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
3737
+ const handle = handleOf(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
3981
3738
  if (!handle) {
3982
3739
  say(runtime, "log", `[agentchat:${accountId}] agentHandle not in config \u2014 run \`openclaw doctor --fix\` to learn it from the key and place the identity line`);
3983
3740
  return;
3984
3741
  }
3985
3742
  const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
3986
- const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3743
+ const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3987
3744
  const identityLine = apiKey ? await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId }) : null;
3988
3745
  const restored = restoreIdentityLine(nextCfg, accountId, handle, identityLine);
3989
3746
  if (restored.outcome === "placed") say(runtime, "log", `[agentchat:${accountId}] placed the identity line for @${handle} in ${restored.path}`);
@@ -4146,6 +3903,20 @@ function hasAgentChatConfiguredState(config) {
4146
3903
  return true;
4147
3904
  }
4148
3905
 
3906
+ // src/errors.ts
3907
+ var AgentChatChannelError = class extends Error {
3908
+ class_;
3909
+ retryAfterMs;
3910
+ statusCode;
3911
+ constructor(class_, message, options = {}) {
3912
+ super(message, { cause: options.cause });
3913
+ this.name = "AgentChatChannelError";
3914
+ this.class_ = class_;
3915
+ this.retryAfterMs = options.retryAfterMs;
3916
+ this.statusCode = options.statusCode;
3917
+ }
3918
+ };
3919
+
4149
3920
  exports.AGENTCHAT_CHANNEL_ID = AGENTCHAT_CHANNEL_ID;
4150
3921
  exports.AGENTCHAT_DEFAULT_ACCOUNT_ID = AGENTCHAT_DEFAULT_ACCOUNT_ID;
4151
3922
  exports.AgentChatChannelError = AgentChatChannelError;
@@ -4154,12 +3925,13 @@ exports.MAX_HUNG_TURNS = MAX_HUNG_TURNS;
4154
3925
  exports.MCP_SERVER_NAME = MCP_SERVER_NAME;
4155
3926
  exports.OPENCLAW_TOOL_NAMER = OPENCLAW_TOOL_NAMER;
4156
3927
  exports.OpenClawTexts = OpenClawTexts;
3928
+ exports.accountCallOptions = accountCallOptions;
4157
3929
  exports.accountTurns = accountTurns;
4158
3930
  exports.agentchatChannelEntry = agentchatChannelEntry;
4159
3931
  exports.agentchatPlugin = agentchatPlugin;
4160
3932
  exports.agentchatSetupEntry = agentchatSetupEntry;
4161
3933
  exports.agentchatSetupPlugin = agentchatPlugin;
4162
- exports.assertApiKeyValid = assertApiKeyValid;
3934
+ exports.checkApiKey = checkApiKey;
4163
3935
  exports.createInMemoryMetrics = createInMemoryMetrics;
4164
3936
  exports.createIntegrationLoop = createIntegrationLoop;
4165
3937
  exports.createLoopTurnStarter = createLoopTurnStarter;
@@ -4176,14 +3948,9 @@ exports.mcpToolName = mcpToolName;
4176
3948
  exports.parseChannelConfig = parseChannelConfig;
4177
3949
  exports.probeHostedMcp = probeHostedMcp;
4178
3950
  exports.realtimeOptionsFor = realtimeOptionsFor;
4179
- exports.recoverAgentStart = recoverAgentStart;
4180
- exports.recoverAgentVerify = recoverAgentVerify;
4181
- exports.registerAgentStart = registerAgentStart;
4182
- exports.registerAgentVerify = registerAgentVerify;
4183
3951
  exports.spellTextsForOpenClaw = spellTextsForOpenClaw;
4184
3952
  exports.spellToolsForOpenClaw = spellToolsForOpenClaw;
4185
3953
  exports.trackerFor = trackerFor;
4186
3954
  exports.turnEndOf = turnEndOf;
4187
- exports.validateApiKey = validateApiKey;
4188
3955
  //# sourceMappingURL=index.cjs.map
4189
3956
  //# sourceMappingURL=index.cjs.map