@agentchatme/openclaw 0.10.2 → 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.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { buildChannelConfigSchema, defineChannelPluginEntry, defineSetupPluginEntry } from 'openclaw/plugin-sdk/channel-core';
2
2
  import { setAccountEnabledInConfigSection, deleteAccountFromConfigSection } from 'openclaw/plugin-sdk/channel-plugin-common';
3
3
  import { setSetupChannelEnabled, WizardCancelledError } from 'openclaw/plugin-sdk/setup';
4
- import { integration, AgentChatClient, AgentChatError, RateLimitedError, RealtimeClient } from 'agentchatme';
4
+ import { createHash } from 'crypto';
5
+ import { integration, AgentChatClient, ConnectionError, RealtimeClient } from 'agentchatme';
6
+ import { WAKE_MODE_ENV, LEGACY_WAKE_MODE_ENV, readWakeModeFromEnv, readLegacyReplyGateFailOpenFromEnv, LEGACY_REPLY_GATE_FAIL_OPEN_ENV, readReplyGateTimeoutMsFromEnv, API_KEY_ENV, readReplyGateEnabledFromEnv } from './credentials/read-env.js';
5
7
  import { readApiKeyFromEnv } from './credentials/read-env.js';
6
8
  import * as fs from 'fs';
7
9
  import * as path2 from 'path';
8
- import { WAKE_MODE_ENV, LEGACY_WAKE_MODE_ENV, readWakeModeFromEnv, readLegacyReplyGateFailOpenFromEnv, LEGACY_REPLY_GATE_FAIL_OPEN_ENV, readReplyGateTimeoutMsFromEnv, API_KEY_ENV, readReplyGateEnabledFromEnv } from './credentials/read-env.js';
9
10
  import { resolveBoundAgentId, resolveOpenClawDefaultAgentId, resolveOpenClawStateDir } from './openclaw-layout.js';
10
11
  import { removeAgentsAnchor, agentsAnchorPath, hasAgentsAnchorFor, writeAgentsAnchor, readAgentsAnchor } from './binding/agents-anchor.js';
11
12
  import { z } from 'zod';
@@ -105,22 +106,8 @@ function applyAgentchatAccountPatch(cfg, accountId, patch) {
105
106
  return { ...cfg ?? {}, channels };
106
107
  }
107
108
 
108
- // src/errors.ts
109
- var AgentChatChannelError = class extends Error {
110
- class_;
111
- retryAfterMs;
112
- statusCode;
113
- constructor(class_, message, options = {}) {
114
- super(message, { cause: options.cause });
115
- this.name = "AgentChatChannelError";
116
- this.class_ = class_;
117
- this.retryAfterMs = options.retryAfterMs;
118
- this.statusCode = options.statusCode;
119
- }
120
- };
121
-
122
109
  // src/version.ts
123
- var PACKAGE_VERSION = "0.10.2";
110
+ var PACKAGE_VERSION = "0.11.0";
124
111
 
125
112
  // src/client-identity.ts
126
113
  var AGENTCHAT_CLIENT_NAME = "openclaw";
@@ -129,227 +116,6 @@ var AGENTCHAT_CLIENT_IDENTITY = {
129
116
  version: PACKAGE_VERSION
130
117
  };
131
118
 
132
- // src/setup-client.ts
133
- var DEFAULT_API_BASE = "https://api.agentchat.me";
134
- var DEFAULT_TIMEOUT_MS = 1e4;
135
- async function validateApiKey(apiKey, opts = {}) {
136
- if (!apiKey || typeof apiKey !== "string") {
137
- return { ok: false, reason: "unauthorized", message: "API key is empty" };
138
- }
139
- const client = new AgentChatClient({
140
- apiKey,
141
- baseUrl: apiBaseOf(opts.apiBase),
142
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
143
- timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
144
- retry: ONE_ATTEMPT,
145
- ...opts.fetch ? { fetch: opts.fetch } : {}
146
- });
147
- let me;
148
- try {
149
- me = await client.getMe();
150
- } catch (err) {
151
- const failure = describeFailure(err);
152
- if (failure.kind === "network") {
153
- const unreachable = failure.timedOut || /ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(failure.message);
154
- return {
155
- ok: false,
156
- reason: unreachable ? "unreachable" : "network-error",
157
- message: `agentchat: GET /v1/agents/me failed: ${failure.message}`
158
- };
159
- }
160
- const status = failure.status;
161
- if (status === 401) return { ok: false, reason: "unauthorized", status, message: "API key is invalid or revoked" };
162
- if (status === 403) return { ok: false, reason: "forbidden", status, message: "API key lacks permission to read /agents/me" };
163
- if (status === 410) return { ok: false, reason: "deleted", status, message: "Agent account has been deleted" };
164
- return { ok: false, reason: "server-error", status, message: `AgentChat API returned ${status}` };
165
- }
166
- const body = asRecord(me);
167
- const email = typeof body?.email === "string" ? body.email : typeof body?.email_masked === "string" ? body.email_masked : null;
168
- if (!body || typeof body.handle !== "string" || email === null || typeof body.created_at !== "string") {
169
- return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/me returned an unrecognized shape" };
170
- }
171
- return {
172
- ok: true,
173
- agent: {
174
- handle: body.handle,
175
- displayName: typeof body.display_name === "string" ? body.display_name : null,
176
- email,
177
- createdAt: body.created_at
178
- }
179
- };
180
- }
181
- async function registerAgentStart(input, opts = {}) {
182
- let data;
183
- try {
184
- data = await AgentChatClient.register({
185
- email: input.email,
186
- handle: input.handle,
187
- ...input.displayName !== void 0 ? { display_name: input.displayName } : {},
188
- ...input.description !== void 0 ? { description: input.description } : {},
189
- baseUrl: apiBaseOf(opts.apiBase),
190
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
191
- });
192
- } catch (err) {
193
- const failure = describeFailure(err);
194
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
195
- const { status, code, message } = failure;
196
- if (status === 400 && code === "INVALID_HANDLE") return { ok: false, reason: "invalid-handle", message, status };
197
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
198
- if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
199
- const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
200
- if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
201
- if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
202
- if (status >= 500 || code === "OTP_FAILED") return { ok: false, reason: "otp-failed", message, status };
203
- return { ok: false, reason: "server-error", status, message };
204
- }
205
- const pendingId = asRecord(data)?.pending_id;
206
- if (typeof pendingId !== "string") {
207
- return { ok: false, reason: "server-error", status: 200, message: "AgentChat /register returned no pending_id" };
208
- }
209
- return { ok: true, pendingId };
210
- }
211
- async function registerAgentVerify(input, opts = {}) {
212
- let verified;
213
- try {
214
- verified = await AgentChatClient.verify(input.pendingId, input.code, {
215
- baseUrl: apiBaseOf(opts.apiBase),
216
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
217
- });
218
- } catch (err) {
219
- const failure = describeFailure(err);
220
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
221
- const { status, code, message } = failure;
222
- if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
223
- if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
224
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
225
- if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
226
- const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
227
- if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
228
- if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
229
- return { ok: false, reason: "server-error", status, message };
230
- }
231
- const agent = asRecord(verified.agent);
232
- if (typeof verified.apiKey !== "string" || !agent || typeof agent.handle !== "string" || typeof agent.email !== "string" || typeof agent.created_at !== "string") {
233
- return { ok: false, reason: "unexpected-shape", status: 201, message: "AgentChat /register/verify returned an unrecognized shape" };
234
- }
235
- return {
236
- ok: true,
237
- apiKey: verified.apiKey,
238
- agent: {
239
- handle: agent.handle,
240
- displayName: typeof agent.display_name === "string" ? agent.display_name : null,
241
- email: agent.email,
242
- createdAt: agent.created_at
243
- }
244
- };
245
- }
246
- async function recoverAgentStart(input, opts = {}) {
247
- let data;
248
- try {
249
- data = await AgentChatClient.recover(input.email, {
250
- handle: input.handle,
251
- baseUrl: apiBaseOf(opts.apiBase),
252
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
253
- });
254
- } catch (err) {
255
- const failure = describeFailure(err);
256
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
257
- const { status, code, message: message2 } = failure;
258
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message: message2, status };
259
- if (status === 429) return { ok: false, reason: "rate-limited", message: message2, status, retryAfterSeconds: failure.retryAfterSeconds };
260
- return { ok: false, reason: "server-error", status, message: message2 };
261
- }
262
- const body = asRecord(data);
263
- const message = typeof body?.message === "string" ? body.message : "status 200";
264
- if (typeof body?.pending_id !== "string") {
265
- return {
266
- ok: false,
267
- reason: "unexpected-shape",
268
- status: 200,
269
- message: "AgentChat did not start a recovery (no pending_id in the response). Check that the email is the one this agent registered with."
270
- };
271
- }
272
- return { ok: true, pendingId: body.pending_id, message };
273
- }
274
- async function recoverAgentVerify(input, opts = {}) {
275
- let recovered;
276
- try {
277
- recovered = await AgentChatClient.recoverVerify(input.pendingId, input.code, {
278
- baseUrl: apiBaseOf(opts.apiBase),
279
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
280
- });
281
- } catch (err) {
282
- const failure = describeFailure(err);
283
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
284
- const { status, code, message } = failure;
285
- if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
286
- if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
287
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
288
- if (status === 409 && code === "HANDLE_REQUIRED") {
289
- return { ok: false, reason: "handle-required", message, status, handles: readHandleList(failure.details) };
290
- }
291
- if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
292
- return { ok: false, reason: "server-error", status, message };
293
- }
294
- if (typeof recovered.apiKey !== "string" || typeof recovered.handle !== "string") {
295
- return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/recover/verify returned an unrecognized shape" };
296
- }
297
- return { ok: true, apiKey: recovered.apiKey, handle: recovered.handle };
298
- }
299
- function classifyEmailPolicyRejection(code) {
300
- if (code === "EMAIL_LIMIT_REACHED" || code === "EMAIL_TAKEN") return "email-limit-reached";
301
- if (code === "EMAIL_EXHAUSTED") return "email-exhausted";
302
- return void 0;
303
- }
304
- function readPolicyLimit(details) {
305
- if (!details || typeof details !== "object") return void 0;
306
- const limit = details.limit;
307
- return typeof limit === "number" && Number.isInteger(limit) && limit > 0 ? limit : void 0;
308
- }
309
- function readHandleList(details) {
310
- if (!details || typeof details !== "object") return [];
311
- const handles = details.handles;
312
- if (!Array.isArray(handles)) return [];
313
- return handles.filter((h) => typeof h === "string" && h.length > 0);
314
- }
315
- var ONE_ATTEMPT = { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 };
316
- function apiBaseOf(apiBase) {
317
- return (apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, "");
318
- }
319
- function describeFailure(err) {
320
- if (err instanceof AgentChatError) {
321
- const raw = asRecord(asRecord(err.details)?.body);
322
- const code = typeof raw?.code === "string" ? raw.code : String(err.code ?? "");
323
- const message2 = raw ? typeof raw.message === "string" ? raw.message : `status ${err.status}` : err.message || `status ${err.status}`;
324
- const retryAfterMs = err instanceof RateLimitedError ? err.retryAfterMs : null;
325
- return {
326
- kind: "http",
327
- status: err.status,
328
- code,
329
- message: message2,
330
- details: raw ? raw.details : err.details,
331
- ...typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) ? { retryAfterSeconds: Math.ceil(retryAfterMs / 1e3) } : {}
332
- };
333
- }
334
- const message = err instanceof Error ? err.message : String(err);
335
- const timedOut = err instanceof Error && err.name === "AbortError" || /timed out|abort/i.test(message);
336
- return { kind: "network", message, timedOut };
337
- }
338
- function networkMessage(failure) {
339
- return failure.timedOut ? "request timed out" : failure.message;
340
- }
341
- function asRecord(value) {
342
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
343
- }
344
- async function assertApiKeyValid(apiKey, opts = {}) {
345
- const result = await validateApiKey(apiKey, opts);
346
- if (result.ok) return result.agent;
347
- const class_ = result.reason === "unauthorized" || result.reason === "forbidden" || result.reason === "deleted" ? "terminal-auth" : result.reason === "server-error" ? "retry-transient" : "retry-transient";
348
- throw new AgentChatChannelError(class_, `${result.message} [reason=${result.reason}]`, {
349
- statusCode: result.status
350
- });
351
- }
352
-
353
119
  // src/integration/turn.ts
354
120
  var MCP_SERVER_NAME = "agentchat";
355
121
  var MCP_TOOL_DELIMITER = "__";
@@ -386,8 +152,8 @@ function sanitizeKeyPart(value) {
386
152
  // src/integration/mcp.ts
387
153
  var MCP_PATH = "/mcp";
388
154
  var AUTH_HEADER_TEMPLATE = `Bearer \${${API_KEY_ENV}}`;
389
- var DEFAULT_API_BASE2 = "https://api.agentchat.me";
390
- function hostedMcpUrl(apiBase = DEFAULT_API_BASE2) {
155
+ var DEFAULT_API_BASE = "https://api.agentchat.me";
156
+ function hostedMcpUrl(apiBase = DEFAULT_API_BASE) {
391
157
  return `${apiBase.replace(/\/+$/, "")}${MCP_PATH}`;
392
158
  }
393
159
  var CLIENT_HEADER = "X-AgentChat-Client";
@@ -397,14 +163,14 @@ function clientIdentityHeaders() {
397
163
  function clientIdentityText() {
398
164
  return `${CLIENT_HEADER}: ${AGENTCHAT_CLIENT_NAME}`;
399
165
  }
400
- function hostedMcpServerEntry(apiBase = DEFAULT_API_BASE2) {
166
+ function hostedMcpServerEntry(apiBase = DEFAULT_API_BASE) {
401
167
  return {
402
168
  url: hostedMcpUrl(apiBase),
403
169
  transport: "streamable-http",
404
170
  headers: { Authorization: AUTH_HEADER_TEMPLATE, ...clientIdentityHeaders() }
405
171
  };
406
172
  }
407
- function hostedMcpSnippet(apiBase = DEFAULT_API_BASE2) {
173
+ function hostedMcpSnippet(apiBase = DEFAULT_API_BASE) {
408
174
  const identity = clientIdentityHeaders();
409
175
  return [
410
176
  "{",
@@ -423,7 +189,7 @@ function hostedMcpSnippet(apiBase = DEFAULT_API_BASE2) {
423
189
  "}"
424
190
  ].join("\n");
425
191
  }
426
- function describeMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
192
+ function describeMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
427
193
  const servers = cfg?.mcp?.servers;
428
194
  if (!servers || typeof servers !== "object" || Array.isArray(servers)) return "missing";
429
195
  const entry = servers[MCP_SERVER_NAME];
@@ -456,7 +222,7 @@ function describeMcpIdentity(cfg) {
456
222
  const client = clients[0];
457
223
  return clients.length === 1 && typeof client === "string" && client.trim().toLowerCase() === want[CLIENT_HEADER] ? "current" : "missing";
458
224
  }
459
- function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
225
+ function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
460
226
  const state = describeMcpEntry(cfg, apiBase, apiKey);
461
227
  const base = cfg ?? {};
462
228
  if (state === "user_managed") return { cfg: base, outcome: "user_managed" };
@@ -469,7 +235,7 @@ function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
469
235
  mcp.servers = servers;
470
236
  return { cfg: { ...base, mcp }, outcome: state === "ours" ? "updated" : "added" };
471
237
  }
472
- function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE2) {
238
+ function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE) {
473
239
  const headers = isRecord(entry.headers) ? entry.headers : {};
474
240
  const kept = Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== CLIENT_HEADER.toLowerCase()));
475
241
  return {
@@ -479,7 +245,7 @@ function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE2) {
479
245
  headers: { ...kept, ...clientIdentityHeaders() }
480
246
  };
481
247
  }
482
- function upgradeHostedMcpEntryInPlace(draft, apiBase = DEFAULT_API_BASE2, apiKey) {
248
+ function upgradeHostedMcpEntryInPlace(draft, apiBase = DEFAULT_API_BASE, apiKey) {
483
249
  if (describeMcpEntry(draft, apiBase, apiKey) !== "ours" || describeMcpIdentity(draft) === "current") return false;
484
250
  const servers = draft.mcp.servers;
485
251
  const existing = servers[MCP_SERVER_NAME];
@@ -496,7 +262,7 @@ var NoChange = class extends Error {
496
262
  };
497
263
  var NIX_MODE_ERROR_CODE = "OPENCLAW_NIX_MODE_CONFIG_IMMUTABLE";
498
264
  async function refreshHostedMcpEntry(params) {
499
- const apiBase = params.apiBase ?? DEFAULT_API_BASE2;
265
+ const apiBase = params.apiBase ?? DEFAULT_API_BASE;
500
266
  if (describeMcpEntry(params.liveCfg, apiBase, params.apiKey) !== "ours") return { outcome: "not_ours" };
501
267
  if (describeMcpIdentity(params.liveCfg) === "current") return { outcome: "current" };
502
268
  const mutate = params.config?.mutateConfigFile;
@@ -533,7 +299,7 @@ function headerValues(headers, name) {
533
299
  const wanted = name.toLowerCase();
534
300
  return Object.entries(headers).filter(([key]) => key.toLowerCase() === wanted).map(([, value]) => value);
535
301
  }
536
- function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
302
+ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
537
303
  if (describeMcpEntry(cfg, apiBase, apiKey) !== "ours") return { cfg, removed: false };
538
304
  const mcp = { ...cfg.mcp ?? {} };
539
305
  const servers = { ...mcp.servers ?? {} };
@@ -543,7 +309,7 @@ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
543
309
  }
544
310
  async function probeHostedMcp(params) {
545
311
  const result = await integration.probeHostedTools({
546
- apiBase: params.apiBase ?? DEFAULT_API_BASE2,
312
+ apiBase: params.apiBase ?? DEFAULT_API_BASE,
547
313
  apiKey: params.apiKey,
548
314
  clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
549
315
  ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
@@ -562,6 +328,40 @@ async function probeHostedMcp(params) {
562
328
  };
563
329
  }
564
330
 
331
+ // src/setup-client.ts
332
+ var KEY_CHECK_TIMEOUT_MS = 1e4;
333
+ function accountCallOptions(params = {}) {
334
+ return {
335
+ clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
336
+ apiBase: (params.apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, ""),
337
+ ...params.fetch ? { fetch: params.fetch } : {},
338
+ ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {}
339
+ };
340
+ }
341
+ var KeyCheckUnanswered = class extends Error {
342
+ constructor(message) {
343
+ super(message);
344
+ this.name = "KeyCheckUnanswered";
345
+ }
346
+ };
347
+ async function checkApiKey(apiKey, params = {}) {
348
+ let status;
349
+ const send = params.fetch ?? ((input, init) => globalThis.fetch(input, init));
350
+ const observed = (async (input, init) => {
351
+ const response = await send(input, init);
352
+ status = response.status;
353
+ return response;
354
+ });
355
+ const check = await integration.account.checkKey(
356
+ apiKey,
357
+ accountCallOptions({ timeoutMs: KEY_CHECK_TIMEOUT_MS, ...params, fetch: observed })
358
+ );
359
+ if (!check.ok && status !== 401 && status !== 403) {
360
+ throw new KeyCheckUnanswered(`AgentChat answered ${status ?? "without a status"} (${check.code}): ${check.message}`);
361
+ }
362
+ return check;
363
+ }
364
+
565
365
  // src/integration/runtime-holder.ts
566
366
  var current = null;
567
367
  function isUsablePluginRuntime(runtime) {
@@ -713,14 +513,14 @@ var FAILURE_STATUSES = /* @__PURE__ */ new Set([
713
513
  "invalid"
714
514
  ]);
715
515
  function coversWholeSession(rows) {
716
- if (asRecord2(rows[0]?.__openclaw)?.seq !== 1) return false;
516
+ if (asRecord(rows[0]?.__openclaw)?.seq !== 1) return false;
717
517
  return rows.every((row) => {
718
- const meta = asRecord2(row.__openclaw);
518
+ const meta = asRecord(row.__openclaw);
719
519
  return meta?.kind !== "compaction" && meta?.kind !== "reset" && meta?.truncated !== true;
720
520
  });
721
521
  }
722
522
  function isOtherRun(row, runId) {
723
- const tagged = asRecord2(row.__openclaw)?.runId ?? nestedCallOf(row)?.runId;
523
+ const tagged = asRecord(row.__openclaw)?.runId ?? nestedCallOf(row)?.runId;
724
524
  return typeof tagged === "string" && tagged.trim().length > 0 && tagged.trim() !== runId;
725
525
  }
726
526
  var CODE_MODE_ONLY_TOOL_NAMES = /* @__PURE__ */ new Set(["tool_search_code", "wait"]);
@@ -732,7 +532,7 @@ function codeModeScriptsCompleted(rows, calls) {
732
532
  for (const row of rows) {
733
533
  if ((row.role === "toolResult" || row.role === "tool") && typeof row.toolCallId === "string") results.set(row.toolCallId, row);
734
534
  }
735
- const completed = (row) => row !== void 0 && row.isError !== true && asRecord2(row.details)?.status === "completed";
535
+ const completed = (row) => row !== void 0 && row.isError !== true && asRecord(row.details)?.status === "completed";
736
536
  for (const [id, call] of calls) {
737
537
  if (isCodeModeCall(call) && !completed(results.get(id))) return false;
738
538
  }
@@ -751,7 +551,7 @@ function isShellExecResult(row, calls) {
751
551
  const call = typeof row.toolCallId === "string" ? calls.get(row.toolCallId) : void 0;
752
552
  const args = callArguments(call);
753
553
  if (!args || typeof args.command !== "string" || args.code !== void 0) return false;
754
- const details = asRecord2(row.details);
554
+ const details = asRecord(row.details);
755
555
  if (!details || details.telemetry !== void 0) return false;
756
556
  return details.exitCode !== void 0 || typeof details.durationMs === "number" || typeof details.aggregated === "string";
757
557
  }
@@ -760,7 +560,7 @@ function assistantToolCalls(rows) {
760
560
  for (const row of rows) {
761
561
  if (row.role !== "assistant" || !Array.isArray(row.content)) continue;
762
562
  for (const block of row.content) {
763
- const call = asRecord2(block);
563
+ const call = asRecord(block);
764
564
  if (call?.type === "toolCall" && typeof call.id === "string") calls.set(call.id, call);
765
565
  }
766
566
  }
@@ -773,7 +573,7 @@ function releaseOf(rows, calls, nested, version) {
773
573
  return { recordsNestedCalls: trusted, marksFailedRows: trusted };
774
574
  }
775
575
  const parents = new Set(nested.map((call) => call.parentToolCallId));
776
- const dispatchAction = rows.some((row) => (row.role === "toolResult" || row.role === "tool") && toolNameOf(row) === "dispatch_action" && asRecord2(asRecord2(row.details)?.tool) !== null) || [...calls].some(([id, call]) => call.name === "dispatch_action" && parents.has(id));
576
+ 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));
777
577
  return { recordsNestedCalls: nested.length > 0 || dispatchAction, marksFailedRows: dispatchAction };
778
578
  }
779
579
  var OPENCLAW_VERSION = /^(\d+)\.(\d+)\.(\d+)(-.+)?$/;
@@ -799,13 +599,13 @@ function toolNameOf(row) {
799
599
  var NESTED_TOOL_ACTIVITY = "openclaw.nested-tool.v1";
800
600
  function nestedCallOf(row) {
801
601
  if (row.role !== "custom" || row.customType !== NESTED_TOOL_ACTIVITY) return null;
802
- return asRecord2(row.details);
602
+ return asRecord(row.details);
803
603
  }
804
604
  function nestedVerdict(call) {
805
605
  const toolName = typeof call.toolName === "string" ? call.toolName : "";
806
606
  if (!toolName.startsWith(TOOL_PREFIX)) return "not_agentchat";
807
- const result = asRecord2(call.result);
808
- if (call.isError === true || result !== null && failedResult(result.isError, asRecord2(result.details))) return "failed";
607
+ const result = asRecord(call.result);
608
+ if (call.isError === true || result !== null && failedResult(result.isError, asRecord(result.details))) return "failed";
809
609
  return call.isError === false ? "ok" : "unknown";
810
610
  }
811
611
  var OTHER_SESSION_TOOLS = /* @__PURE__ */ new Set(["sessions_spawn", "sessions_send"]);
@@ -816,13 +616,13 @@ function delegatedToChild(rows, calls, nested) {
816
616
  if (typeof call.name === "string" && DISPATCHER_TOOL_NAMES.has(call.name) && names(dispatchTarget(call))) return true;
817
617
  }
818
618
  if (nested.some((call) => names(call.toolName))) return true;
819
- return rows.some((row) => names(toolNameOf(row)) || names(asRecord2(asRecord2(row.details)?.tool)?.name));
619
+ return rows.some((row) => names(toolNameOf(row)) || names(asRecord(asRecord(row.details)?.tool)?.name));
820
620
  }
821
621
  function callVerdict(message, calls, release) {
822
622
  const toolName = toolNameOf(message);
823
- const details = asRecord2(message.details);
623
+ const details = asRecord(message.details);
824
624
  if (toolName.startsWith(TOOL_PREFIX)) return directVerdict(message.isError, details);
825
- const entry = asRecord2(details?.tool);
625
+ const entry = asRecord(details?.tool);
826
626
  if (entry && isAgentChatEntry(entry)) return dispatchedVerdict(message.isError, details);
827
627
  if (!DISPATCHER_TOOL_NAMES.has(toolName) || entry) return "not_agentchat";
828
628
  const target = dispatchTarget(typeof message.toolCallId === "string" ? calls.get(message.toolCallId) : void 0);
@@ -846,10 +646,10 @@ function wasHostedResult(details) {
846
646
  return keys.includes("mcpServer") && (keys.includes("mcpTool") || keys.includes("mcpOperation"));
847
647
  }
848
648
  function dispatchedVerdict(isError, details) {
849
- const result = asRecord2(details?.result);
649
+ const result = asRecord(details?.result);
850
650
  if (failedResult(isError, details)) return "failed";
851
- if (result && failedResult(result.isError, asRecord2(result.details))) return "failed";
852
- const ok = isError === false && details?.status === void 0 && isHostedSuccessDetails(asRecord2(result?.details));
651
+ if (result && failedResult(result.isError, asRecord(result.details))) return "failed";
652
+ const ok = isError === false && details?.status === void 0 && isHostedSuccessDetails(asRecord(result?.details));
853
653
  return ok ? "ok" : "unknown";
854
654
  }
855
655
  function failedResult(isError, details) {
@@ -873,7 +673,7 @@ function isHostedSuccessDetails(details) {
873
673
  function isAgentChatEntry(tool) {
874
674
  if (typeof tool.name === "string" && tool.name.startsWith(TOOL_PREFIX)) return true;
875
675
  if (tool.sourceName === MCP_SERVER_NAME) return true;
876
- const mcp = asRecord2(tool.mcp);
676
+ const mcp = asRecord(tool.mcp);
877
677
  return mcp?.serverName === MCP_SERVER_NAME;
878
678
  }
879
679
  function dispatchTarget(call) {
@@ -893,16 +693,16 @@ function callArguments(call) {
893
693
  return null;
894
694
  }
895
695
  }
896
- return asRecord2(args);
696
+ return asRecord(args);
897
697
  }
898
698
  function unwrapMessage(row) {
899
- const record = asRecord2(row);
699
+ const record = asRecord(row);
900
700
  if (!record) return null;
901
701
  if (typeof record.role === "string") return record;
902
- const inner = asRecord2(record.message);
702
+ const inner = asRecord(record.message);
903
703
  return inner && typeof inner.role === "string" ? inner : null;
904
704
  }
905
- function asRecord2(value) {
705
+ function asRecord(value) {
906
706
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
907
707
  }
908
708
  function nonEmpty(value) {
@@ -1158,7 +958,7 @@ function applyIntegrationConfig(cfg, params) {
1158
958
  const changes = [];
1159
959
  let next = cfg;
1160
960
  const bareHandle = (params.handle ?? "").trim().replace(/^@/, "");
1161
- if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle && isValidHandleShape(bareHandle)) {
961
+ if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle) {
1162
962
  next = applyAgentchatAccountPatch(next, params.accountId, { agentHandle: bareHandle });
1163
963
  changes.push(`channels.agentchat${params.accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID ? "" : `.accounts.${params.accountId}`}.agentHandle = ${bareHandle}`);
1164
964
  }
@@ -1493,57 +1293,15 @@ function getClient({ accountId, config, options }) {
1493
1293
 
1494
1294
  // src/channel.wizard.ts
1495
1295
  var JUST_REGISTERED_SENTINEL = "_agentchatJustRegistered";
1496
- var HANDLE_PATTERN2 = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
1497
- var HANDLE_MIN_LENGTH = 3;
1498
- var HANDLE_MAX_LENGTH = 30;
1499
- var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1500
- function isValidHandleShape2(value) {
1501
- return value.length >= HANDLE_MIN_LENGTH && value.length <= HANDLE_MAX_LENGTH && HANDLE_PATTERN2.test(value);
1502
- }
1503
- var OTP_PATTERN = /^\d{6}$/;
1296
+ var LABELS = {
1297
+ ...integration.account.DEFAULT_LABELS,
1298
+ handle: "Handle (your @name on AgentChat)"
1299
+ };
1504
1300
  function hasConfiguredKey(cfg, accountId) {
1505
1301
  return isApiKeyPresent(readAgentchatConfigField(cfg, accountId, "apiKey"));
1506
1302
  }
1507
- var MAX_START_RETRIES = 5;
1508
- async function promptEmail(prompter, opts = {}) {
1509
- return (await prompter.text({
1510
- message: opts.message ?? "Email \u2014 receives a 6-digit verification code",
1511
- placeholder: "you@example.com",
1512
- validate: (value) => {
1513
- const trimmed = value.trim();
1514
- if (!trimmed) return "Email is required";
1515
- if (!EMAIL_PATTERN.test(trimmed)) return "Not a valid email format";
1516
- return void 0;
1517
- }
1518
- })).trim();
1519
- }
1520
- async function promptHandle(prompter, opts = {}) {
1521
- return (await prompter.text({
1522
- message: opts.message ?? "Choose a handle (your @name on AgentChat)",
1523
- placeholder: "3\u201330 chars, lowercase a-z, 0-9, hyphens, starts with a letter",
1524
- ...opts.initialValue ? { initialValue: opts.initialValue } : {},
1525
- validate: (value) => {
1526
- const trimmed = value.trim();
1527
- if (!trimmed) return "Handle is required";
1528
- if (trimmed.length < HANDLE_MIN_LENGTH || trimmed.length > HANDLE_MAX_LENGTH) {
1529
- return `Length must be ${HANDLE_MIN_LENGTH}\u2013${HANDLE_MAX_LENGTH} chars (you entered ${trimmed.length})`;
1530
- }
1531
- if (!/^[a-z]/.test(trimmed)) return "Must start with a lowercase letter";
1532
- if (/[^a-z0-9-]/.test(trimmed)) {
1533
- return "Only lowercase letters, digits, and hyphens \u2014 no underscores, dots, or symbols";
1534
- }
1535
- if (trimmed.includes("--")) return "No consecutive hyphens";
1536
- if (trimmed.endsWith("-")) return "Cannot end with a hyphen";
1537
- return void 0;
1538
- }
1539
- })).trim();
1540
- }
1541
- async function promptDisplayName(prompter) {
1542
- return (await prompter.text({
1543
- message: "Display name (shown next to your @handle)",
1544
- placeholder: "e.g. Anton, Builder Bot, Sasha",
1545
- validate: () => void 0
1546
- })).trim();
1303
+ function nonEmpty2(value) {
1304
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
1547
1305
  }
1548
1306
  async function runChangeApiBaseFlow(params) {
1549
1307
  const { cfg, accountId, prompter } = params;
@@ -1581,388 +1339,182 @@ async function runChangeApiBaseFlow(params) {
1581
1339
  await prompter.note(`API base set to ${input}`, "Updated");
1582
1340
  return { cfg: patched };
1583
1341
  }
1584
- function describeEmailPolicyRejection(email, result) {
1585
- if (result.limit === void 0) return result.message;
1586
- 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.`;
1587
- }
1588
- async function promptEmailPolicyChoice(prompter, email, result) {
1589
- return prompter.select({
1590
- message: `${describeEmailPolicyRejection(email, result)} What next?`,
1591
- options: [
1592
- {
1593
- value: "retry",
1594
- label: "Use a different email address",
1595
- hint: "a +alias like you+agent2@example.com counts as a separate email"
1596
- },
1597
- {
1598
- value: "recover",
1599
- label: "Recover the API key of an agent this email already backs",
1600
- hint: "needs that agent\u2019s handle \u2014 a code goes to this email"
1601
- },
1602
- { value: "paste", label: "Paste a key from an existing agent" },
1603
- { value: "cancel", label: "Cancel registration" }
1604
- ],
1605
- initialValue: "retry"
1606
- });
1342
+ async function askText(prompter, message, opts = {}) {
1343
+ return (await prompter.text({
1344
+ message,
1345
+ ...opts,
1346
+ validate: (value) => value.trim() ? void 0 : "Required"
1347
+ })).trim();
1607
1348
  }
1608
- async function runRegisterFlow(params) {
1609
- const { cfg, accountId, prompter, apiBase } = params;
1610
- await prompter.note(
1611
- [
1612
- "Registration mints a new AgentChat agent identity tied to your email.",
1613
- "One email can back several agents (the server enforces the limit);",
1614
- "each one registers and verifies separately.",
1615
- "You will receive a 6-digit code to verify \u2014 check your inbox (and spam)."
1616
- ].join("\n"),
1617
- "AgentChat: register a new agent"
1618
- );
1619
- let email = await promptEmail(prompter);
1620
- let handle = await promptHandle(prompter);
1621
- const displayName = await promptDisplayName(prompter);
1622
- let startResult;
1623
- let startedOk = false;
1624
- for (let attempt = 1; attempt <= MAX_START_RETRIES; attempt += 1) {
1625
- const startSpinner = prompter.progress(
1626
- attempt === 1 ? "Sending verification code\u2026" : "Retrying\u2026"
1627
- );
1628
- try {
1629
- startResult = await registerAgentStart(
1630
- {
1631
- email,
1632
- handle,
1633
- ...displayName ? { displayName } : {}
1634
- },
1635
- { apiBase }
1636
- );
1637
- } catch (err) {
1638
- startSpinner.stop("Could not reach AgentChat");
1639
- await prompter.note(
1640
- `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
1641
- "Registration failed"
1642
- );
1643
- return "abort";
1644
- }
1645
- if (startResult.ok) {
1646
- startSpinner.stop(`Verification code sent to ${email}`);
1647
- startedOk = true;
1648
- break;
1649
- }
1650
- startSpinner.stop("Registration rejected");
1651
- switch (startResult.reason) {
1652
- case "invalid-handle":
1653
- case "handle-taken": {
1654
- 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).";
1655
- await prompter.note(`${detail} Pick a different handle and we'll try again.`, "Pick a different handle");
1656
- handle = await promptHandle(prompter);
1657
- continue;
1658
- }
1659
- case "email-limit-reached":
1660
- case "email-exhausted": {
1661
- const choice = await promptEmailPolicyChoice(prompter, email, {
1662
- reason: startResult.reason,
1663
- limit: startResult.limit,
1664
- message: startResult.message
1665
- });
1666
- if (choice === "paste") return "user-chose-paste";
1667
- if (choice === "recover") return "user-chose-recover";
1668
- if (choice === "cancel") return "abort";
1669
- email = await promptEmail(prompter);
1670
- continue;
1671
- }
1672
- case "rate-limited": {
1673
- const wait = startResult.retryAfterSeconds ? ` Try again in ${startResult.retryAfterSeconds}s.` : "";
1674
- await prompter.note(`Too many registration attempts.${wait}`, "Rate limited");
1675
- return "abort";
1676
- }
1677
- case "otp-failed": {
1678
- await prompter.note(
1679
- "The verification-code email could not be sent. Try again in a minute, or paste an existing key instead.",
1680
- "OTP delivery failed"
1681
- );
1682
- return "abort";
1683
- }
1684
- case "network-error":
1685
- case "server-error":
1686
- case "validation":
1687
- default: {
1688
- await prompter.note(describeRegisterStartError(startResult), "Could not start registration");
1689
- return "abort";
1690
- }
1349
+ var EMAIL_PLACEHOLDER = "you@example.com";
1350
+ async function askCode(prompter, label) {
1351
+ for (; ; ) {
1352
+ const code = (await prompter.text({ message: label, placeholder: "leave blank for a new code or to cancel" })).trim();
1353
+ if (code) return { answer: "value", value: code };
1354
+ const choice = await prompter.select({
1355
+ message: "What would you like to do?",
1356
+ options: [
1357
+ { value: "new_code", label: "Send a new code" },
1358
+ { value: "enter", label: "Enter the code" },
1359
+ { value: "cancel", label: "Cancel", hint: "paste an existing key instead, or leave setup" }
1360
+ ],
1361
+ initialValue: "new_code"
1362
+ });
1363
+ if (choice === "new_code") return { answer: "new_code" };
1364
+ if (choice === "cancel") return { answer: "cancel" };
1365
+ }
1366
+ }
1367
+ function askThrough(prompter) {
1368
+ return async (question) => {
1369
+ if (question.field === "new_code") {
1370
+ const yes = await prompter.confirm({ message: "Send a new code?", initialValue: true });
1371
+ return yes ? { answer: "new_code" } : { answer: "cancel" };
1372
+ }
1373
+ if (question.field === "code") return askCode(prompter, question.label ?? LABELS.code);
1374
+ const label = question.label ?? LABELS[question.field];
1375
+ const handles = (question.handles ?? []).filter((handle) => handle.length > 0);
1376
+ if (handles.length > 0) {
1377
+ const picked = await prompter.select({
1378
+ message: label,
1379
+ options: [
1380
+ ...handles.map((handle) => ({ value: handle, label: `@${handle}` })),
1381
+ { value: "", label: "Another handle" }
1382
+ ]
1383
+ });
1384
+ if (picked) return { answer: "value", value: picked };
1691
1385
  }
1692
- }
1693
- if (!startedOk || !startResult || !startResult.ok) {
1694
- await prompter.note(
1695
- "Too many attempts. Restart the wizard to try again, or paste an existing key at the next prompt.",
1696
- "Registration failed"
1697
- );
1698
- return "abort";
1699
- }
1700
- const maxCodeAttempts = 3;
1701
- let verifyResult = null;
1702
- for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
1703
- const code = (await prompter.text({
1704
- message: attempt === 1 ? "Enter the 6-digit verification code from your email" : `Verification code (attempt ${attempt}/${maxCodeAttempts})`,
1705
- placeholder: "123456",
1706
- validate: (value) => {
1707
- const trimmed = value.trim();
1708
- if (!trimmed) return "Code is required";
1709
- if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
1710
- return void 0;
1711
- }
1712
- })).trim();
1713
- const verifySpinner = prompter.progress("Verifying code\u2026");
1386
+ const typed = await askText(prompter, label, question.field === "email" ? { placeholder: EMAIL_PLACEHOLDER } : {});
1387
+ return { answer: "value", value: typed };
1388
+ };
1389
+ }
1390
+ function fetchWithProgress(prompter) {
1391
+ return (async (input, init) => {
1392
+ const progress = prompter.progress("Contacting AgentChat\u2026");
1714
1393
  try {
1715
- verifyResult = await registerAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
1716
- } catch (err) {
1717
- verifySpinner.stop("Could not reach AgentChat");
1718
- await prompter.note(
1719
- `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
1720
- "Verification failed"
1721
- );
1722
- return "abort";
1723
- }
1724
- if (verifyResult.ok) {
1725
- verifySpinner.stop(`Registered as @${verifyResult.agent.handle}`);
1726
- break;
1727
- }
1728
- verifySpinner.stop("Verification failed");
1729
- if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
1730
- await prompter.note(
1731
- "That code did not match. Check your email and try again.",
1732
- "Invalid verification code"
1733
- );
1734
- continue;
1394
+ return await globalThis.fetch(input, init);
1395
+ } finally {
1396
+ progress.stop();
1735
1397
  }
1736
- await prompter.note(describeRegisterVerifyError(verifyResult), "Registration failed");
1737
- return "abort";
1738
- }
1739
- if (!verifyResult || !verifyResult.ok) {
1740
- await prompter.note(
1741
- "Too many incorrect codes. Restart the wizard to receive a new code.",
1742
- "Registration failed"
1743
- );
1744
- return "abort";
1745
- }
1746
- const patch = { apiKey: verifyResult.apiKey };
1747
- if (isValidHandleShape2(verifyResult.agent.handle)) {
1748
- patch.agentHandle = verifyResult.agent.handle;
1749
- }
1750
- const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch);
1398
+ });
1399
+ }
1400
+ function sleepWithProgress(prompter) {
1401
+ const label = (seconds) => `Waiting ${seconds} s\u2026`;
1402
+ return (ms) => new Promise((resolve) => {
1403
+ let left = Math.ceil(ms / 1e3);
1404
+ const progress = prompter.progress(label(left));
1405
+ const tick = setInterval(() => {
1406
+ left -= 1;
1407
+ if (left > 0) progress.update(label(left));
1408
+ }, 1e3);
1409
+ setTimeout(() => {
1410
+ clearInterval(tick);
1411
+ progress.stop();
1412
+ resolve();
1413
+ }, ms);
1414
+ });
1415
+ }
1416
+ async function registerInput(prompter) {
1751
1417
  await prompter.note(
1752
1418
  [
1753
- `Handle: @${verifyResult.agent.handle}`,
1754
- `Email: ${verifyResult.agent.email}`,
1755
- `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`
1419
+ "Registration creates a new AgentChat agent tied to your email address.",
1420
+ "Your handle is the agent\u2019s @name on AgentChat. AgentChat emails you a",
1421
+ "code to confirm the address \u2014 check your inbox (and spam)."
1756
1422
  ].join("\n"),
1757
- "AgentChat account created"
1423
+ "AgentChat: register a new agent"
1758
1424
  );
1759
- return {
1760
- cfg: nextCfg,
1761
- credentialValues: {
1762
- token: verifyResult.apiKey,
1763
- [JUST_REGISTERED_SENTINEL]: "1"
1764
- }
1765
- };
1766
- }
1767
- function describeRegisterStartError(result) {
1768
- switch (result.reason) {
1769
- case "invalid-handle":
1770
- return "That handle is not acceptable. Try a different one (3\u201330 chars \u2014 lowercase letters/digits/hyphens; must start with a letter).";
1771
- case "handle-taken":
1772
- return "That handle is already taken. Try a different one.";
1773
- case "email-limit-reached":
1774
- 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.`;
1775
- case "email-exhausted":
1776
- 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.`;
1777
- case "rate-limited": {
1778
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1779
- return `Rate limited.${wait}`;
1780
- }
1781
- case "otp-failed":
1782
- return "The verification-code email could not be sent. Try again in a minute.";
1783
- case "network-error":
1784
- case "server-error":
1785
- case "validation":
1786
- default:
1787
- return result.message;
1788
- }
1789
- }
1790
- function describeRegisterVerifyError(result) {
1791
- switch (result.reason) {
1792
- case "expired":
1793
- return "This code expired. Restart the wizard to receive a new one.";
1794
- case "invalid-code":
1795
- return "Too many incorrect codes. Restart the wizard to receive a new one.";
1796
- case "handle-taken":
1797
- return "Your chosen handle was claimed by another registration in the meantime. Restart with a different handle.";
1798
- case "email-limit-reached":
1799
- 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.`;
1800
- case "email-exhausted":
1801
- 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.`;
1802
- case "rate-limited": {
1803
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1804
- return `Rate limited.${wait}`;
1805
- }
1806
- case "network-error":
1807
- case "server-error":
1808
- case "unexpected-shape":
1809
- case "validation":
1810
- default:
1811
- return result.message;
1812
- }
1425
+ const email = await askText(prompter, LABELS.email, { placeholder: EMAIL_PLACEHOLDER });
1426
+ const handle = await askText(prompter, LABELS.handle);
1427
+ const displayName = (await prompter.text({
1428
+ message: "Display name (shown next to your @handle)",
1429
+ placeholder: "e.g. Anton, Builder Bot, Sasha"
1430
+ })).trim();
1431
+ return { email, handle, ...displayName ? { display_name: displayName } : {} };
1813
1432
  }
1814
- async function runRecoverFlow(params) {
1815
- const { cfg, accountId, prompter, apiBase } = params;
1816
- const storedHandle = readAgentchatConfigField(cfg, accountId, "agentHandle");
1817
- const defaultHandle = storedHandle && isValidHandleShape2(storedHandle) ? storedHandle : void 0;
1433
+ async function recoverInput(prompter, configuredHandle) {
1818
1434
  await prompter.note(
1819
1435
  [
1820
- "Recovery re-issues the API key for ONE agent \u2014 the handle you name below.",
1821
- "You need that handle and the email it registered with; a 6-digit code",
1822
- "goes to that email. The old key stops working the moment the new one",
1823
- "is minted.",
1824
- ...defaultHandle ? ["", `@${defaultHandle} is configured here \u2014 press Enter at the handle prompt to recover it.`] : []
1436
+ "Recovery issues a new API key for an agent you registered. AgentChat",
1437
+ "emails a code to the address the agent registered with; the old key",
1438
+ "stops working once the new one is issued.",
1439
+ ...configuredHandle ? ["", `@${configuredHandle} is configured here \u2014 press Enter at the handle prompt to recover it.`] : []
1825
1440
  ].join("\n"),
1826
1441
  "AgentChat: recover a lost API key"
1827
1442
  );
1828
- const handle = await promptHandle(prompter, {
1829
- message: "Handle of the agent to recover (its @name on AgentChat)",
1830
- ...defaultHandle ? { initialValue: defaultHandle } : {}
1831
- });
1832
- const email = await promptEmail(prompter, {
1833
- message: `Email @${handle} registered with \u2014 receives a 6-digit recovery code`
1834
- });
1835
- const startSpinner = prompter.progress("Requesting recovery code\u2026");
1836
- let startResult;
1443
+ if (!configuredHandle) return {};
1444
+ const handle = (await prompter.text({ message: LABELS.handle, initialValue: configuredHandle })).trim();
1445
+ return handle ? { handle } : {};
1446
+ }
1447
+ async function notCompleted(prompter, kind) {
1448
+ await prompter.note(
1449
+ `${kind === "register" ? "Registration" : "Recovery"} was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.`,
1450
+ "Falling back to credential entry"
1451
+ );
1452
+ return void 0;
1453
+ }
1454
+ async function runAccountFlow(params) {
1455
+ const { kind, cfg, accountId, prompter } = params;
1456
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1457
+ const input = kind === "register" ? await registerInput(prompter) : await recoverInput(prompter, nonEmpty2(readAgentchatConfigField(cfg, accountId, "agentHandle")));
1458
+ let result;
1837
1459
  try {
1838
- startResult = await recoverAgentStart({ email, handle }, { apiBase });
1460
+ result = await integration.account.run({
1461
+ kind,
1462
+ input,
1463
+ labels: LABELS,
1464
+ ask: askThrough(prompter),
1465
+ show: (message) => prompter.note(message, "AgentChat"),
1466
+ sleep: sleepWithProgress(prompter),
1467
+ ...accountCallOptions({ apiBase, fetch: fetchWithProgress(prompter) })
1468
+ });
1839
1469
  } catch (err) {
1840
- startSpinner.stop("Could not reach AgentChat");
1841
- await prompter.note(
1842
- `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
1843
- "Recovery failed"
1844
- );
1845
- return "abort";
1846
- }
1847
- if (!startResult.ok) {
1848
- startSpinner.stop("Recovery rejected");
1849
- await prompter.note(describeRecoverStartError(startResult), "Could not start recovery");
1850
- return "abort";
1851
- }
1852
- startSpinner.stop(startResult.message);
1853
- const maxCodeAttempts = 3;
1854
- let verifyResult = null;
1855
- for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
1856
- const code = (await prompter.text({
1857
- message: attempt === 1 ? `Enter the 6-digit recovery code (check ${email}, including spam)` : `Recovery code (attempt ${attempt}/${maxCodeAttempts})`,
1858
- placeholder: "123456",
1859
- validate: (value) => {
1860
- const trimmed = value.trim();
1861
- if (!trimmed) return "Code is required";
1862
- if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
1863
- return void 0;
1864
- }
1865
- })).trim();
1866
- const verifySpinner = prompter.progress("Verifying code\u2026");
1867
- try {
1868
- verifyResult = await recoverAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
1869
- } catch (err) {
1870
- verifySpinner.stop("Could not reach AgentChat");
1871
- await prompter.note(
1872
- `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
1873
- "Recovery failed"
1874
- );
1875
- return "abort";
1876
- }
1877
- if (verifyResult.ok) {
1878
- verifySpinner.stop(`Recovered @${verifyResult.handle}`);
1879
- break;
1880
- }
1881
- verifySpinner.stop("Verification failed");
1882
- if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
1883
- await prompter.note(
1884
- "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.",
1885
- "Invalid recovery code"
1886
- );
1887
- continue;
1888
- }
1889
- await prompter.note(describeRecoverVerifyError(verifyResult), "Recovery failed");
1890
- return "abort";
1891
- }
1892
- if (!verifyResult || !verifyResult.ok) {
1470
+ if (err instanceof WizardCancelledError) throw err;
1471
+ const unreached = err instanceof ConnectionError || err instanceof Error && err.name === "AbortError";
1893
1472
  await prompter.note(
1894
- "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.",
1895
- "Recovery failed"
1473
+ err instanceof Error ? err.message : String(err),
1474
+ unreached ? "Could not reach AgentChat" : `${kind === "register" ? "Registration" : "Recovery"} failed`
1896
1475
  );
1897
- return "abort";
1898
- }
1899
- const patch = { apiKey: verifyResult.apiKey };
1900
- if (isValidHandleShape2(verifyResult.handle)) {
1901
- patch.agentHandle = verifyResult.handle;
1476
+ return notCompleted(prompter, kind);
1902
1477
  }
1903
- const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch);
1478
+ if (result.outcome !== "done") return notCompleted(prompter, kind);
1479
+ const nextCfg = applyAgentchatAccountPatch(cfg, accountId, { apiKey: result.apiKey, agentHandle: result.handle });
1904
1480
  await prompter.note(
1905
1481
  [
1906
- `Handle: @${verifyResult.handle}`,
1907
- `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`,
1908
- "",
1909
- "The previous key for this agent has been revoked."
1482
+ `Handle: @${result.handle}`,
1483
+ `API key: ${redactKey(result.apiKey)} (saved to your OpenClaw config)`
1910
1484
  ].join("\n"),
1911
- "AgentChat API key recovered"
1485
+ kind === "register" ? "AgentChat account created" : "AgentChat API key recovered"
1912
1486
  );
1913
1487
  return {
1914
1488
  cfg: nextCfg,
1915
1489
  credentialValues: {
1916
- token: verifyResult.apiKey,
1490
+ token: result.apiKey,
1917
1491
  [JUST_REGISTERED_SENTINEL]: "1"
1918
1492
  }
1919
1493
  };
1920
1494
  }
1921
- function describeRecoverStartError(result) {
1922
- switch (result.reason) {
1923
- case "rate-limited": {
1924
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1925
- return `Too many recovery attempts from this network.${wait}`;
1926
- }
1927
- case "validation":
1928
- return `AgentChat rejected the request: ${result.message}`;
1929
- case "network-error":
1930
- case "server-error":
1931
- case "unexpected-shape":
1932
- default:
1933
- return result.message;
1934
- }
1935
- }
1936
- function describeRecoverVerifyError(result) {
1937
- switch (result.reason) {
1938
- case "expired":
1939
- return "This recovery code expired. Restart the wizard to request a new one.";
1940
- case "invalid-code":
1941
- return "Too many incorrect codes. Restart the wizard to request a new one.";
1942
- case "handle-required": {
1943
- const handles = result.handles ?? [];
1944
- const list = handles.length > 0 ? `
1945
-
1946
- Agents on this email:
1947
- ${handles.map((h) => ` @${h}`).join("\n")}` : "";
1948
- return `This email backs more than one agent. Run recovery again and enter the handle you want to recover.${list}`;
1949
- }
1950
- case "rate-limited": {
1951
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1952
- return `Rate limited.${wait}`;
1953
- }
1954
- case "network-error":
1955
- case "server-error":
1956
- case "unexpected-shape":
1957
- case "validation":
1958
- default:
1959
- return result.message;
1960
- }
1961
- }
1962
1495
  function redactKey(apiKey) {
1963
1496
  if (apiKey.length < 12) return "\u2022\u2022\u2022\u2022";
1964
1497
  return `${apiKey.slice(0, 8)}\u2026${apiKey.slice(-4)}`;
1965
1498
  }
1499
+ async function saveEnteredKey(cfg, accountId, value, key) {
1500
+ if (typeof value !== "string" || !nonEmpty2(key)) return cfg;
1501
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1502
+ let check;
1503
+ try {
1504
+ check = await checkApiKey(key, { apiBase });
1505
+ } catch {
1506
+ check = null;
1507
+ }
1508
+ if (check !== null && !check.ok) return cfg;
1509
+ const handle = check?.handle;
1510
+ const sameKey = readAgentchatConfigField(cfg, accountId, "apiKey") === value;
1511
+ const withKey = applyAgentchatAccountPatch(cfg, accountId, {
1512
+ apiKey: value,
1513
+ // A new key whose handle is unknown must not keep the old key's handle.
1514
+ ...handle ? { agentHandle: handle } : sameKey ? {} : { agentHandle: void 0 }
1515
+ });
1516
+ return applyIntegrationConfig(withKey, { accountId, handle, apiKey: key, apiBase: apiBase ?? DEFAULT_API_BASE }).cfg;
1517
+ }
1966
1518
  var agentchatSetupWizard = {
1967
1519
  channel: AGENTCHAT_CHANNEL_ID,
1968
1520
  // AgentChat is one-agent-per-account by product design — the agent IS the
@@ -2007,9 +1559,9 @@ var agentchatSetupWizard = {
2007
1559
  "AgentChat is a messaging platform for AI agents \u2014 direct messages,",
2008
1560
  "groups, presence, attachments. Registration is free.",
2009
1561
  "",
2010
- "This wizard will mint a new account via email OTP, accept an existing",
2011
- "API key, or recover a lost key (handle + email OTP) \u2014 your choice in",
2012
- "the next prompt."
1562
+ "This wizard registers a new agent by email code, accepts an existing",
1563
+ "API key, or recovers a lost key by email code \u2014 your choice in the",
1564
+ "next prompt."
2013
1565
  ]
2014
1566
  },
2015
1567
  prepare: async ({ cfg, accountId, credentialValues, prompter }) => {
@@ -2045,7 +1597,7 @@ var agentchatSetupWizard = {
2045
1597
  options: [
2046
1598
  {
2047
1599
  value: "register",
2048
- label: "Register a new agent (email OTP)",
1600
+ label: "Register a new agent (email code)",
2049
1601
  hint: "no account yet \u2014 the wizard creates one"
2050
1602
  },
2051
1603
  {
@@ -2055,64 +1607,14 @@ var agentchatSetupWizard = {
2055
1607
  },
2056
1608
  {
2057
1609
  value: "recover",
2058
- label: "Recover a lost API key (handle + email OTP)",
1610
+ label: "Recover a lost API key (email code)",
2059
1611
  hint: "an agent exists but its key is gone \u2014 re-issue it"
2060
1612
  }
2061
1613
  ],
2062
1614
  initialValue: "register"
2063
1615
  });
2064
- if (choice === "paste") {
2065
- return;
2066
- }
2067
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
2068
- const recover = async () => {
2069
- try {
2070
- const result = await runRecoverFlow({ cfg, accountId, prompter, apiBase });
2071
- if (result === "abort") {
2072
- await prompter.note(
2073
- "Recovery was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
2074
- "Falling back to credential entry"
2075
- );
2076
- return;
2077
- }
2078
- return result;
2079
- } catch (err) {
2080
- if (err instanceof WizardCancelledError) throw err;
2081
- await prompter.note(
2082
- `${err instanceof Error ? err.message : String(err)}`,
2083
- "Recovery flow failed"
2084
- );
2085
- return;
2086
- }
2087
- };
2088
- if (choice === "recover") {
2089
- return await recover();
2090
- }
2091
- let registerOutcome;
2092
- try {
2093
- registerOutcome = await runRegisterFlow({ cfg, accountId, prompter, apiBase });
2094
- } catch (err) {
2095
- if (err instanceof WizardCancelledError) throw err;
2096
- await prompter.note(
2097
- `${err instanceof Error ? err.message : String(err)}`,
2098
- "Registration flow failed"
2099
- );
2100
- return;
2101
- }
2102
- if (registerOutcome === "abort") {
2103
- await prompter.note(
2104
- "Registration was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
2105
- "Falling back to credential entry"
2106
- );
2107
- return;
2108
- }
2109
- if (registerOutcome === "user-chose-paste") {
2110
- return;
2111
- }
2112
- if (registerOutcome === "user-chose-recover") {
2113
- return await recover();
2114
- }
2115
- return registerOutcome;
1616
+ if (choice === "paste") return;
1617
+ return await runAccountFlow({ kind: choice, cfg, accountId, prompter });
2116
1618
  },
2117
1619
  credentials: [
2118
1620
  {
@@ -2125,9 +1627,9 @@ var agentchatSetupWizard = {
2125
1627
  inputPrompt: "Paste your AgentChat API key (ac_\u2026)",
2126
1628
  helpTitle: "AgentChat API key",
2127
1629
  helpLines: [
2128
- "Format: ac_ followed by 43 base64url characters. Validated against",
2129
- "GET /v1/agents/me during this wizard \u2014 bad keys fail fast instead",
2130
- "of flapping reconnects at runtime."
1630
+ "AgentChat checks the key before it is saved: a key it does not",
1631
+ "accept is not saved, so a bad key fails here instead of flapping",
1632
+ "reconnects at runtime."
2131
1633
  ],
2132
1634
  allowEnv: () => true,
2133
1635
  shouldPrompt: ({ credentialValues, currentValue }) => {
@@ -2145,61 +1647,67 @@ var agentchatSetupWizard = {
2145
1647
  resolvedValue: configured ? apiKey : void 0,
2146
1648
  envValue
2147
1649
  };
1650
+ },
1651
+ // The key the person entered, checked before it is saved.
1652
+ applySet: ({ cfg, accountId, value, resolvedValue }) => saveEnteredKey(cfg, accountId, value, resolvedValue),
1653
+ applyUseEnv: ({ cfg, accountId }) => {
1654
+ const key = readApiKeyFromEnv(MIN_API_KEY_LENGTH);
1655
+ return key ? saveEnteredKey(cfg, accountId, key, key) : cfg;
2148
1656
  }
2149
1657
  }
2150
1658
  ],
2151
1659
  finalize: async ({ cfg, accountId, credentialValues, prompter }) => {
2152
- const apiKey = typeof credentialValues.token === "string" && credentialValues.token.length >= MIN_API_KEY_LENGTH ? credentialValues.token : readAgentchatConfigField(cfg, accountId, "apiKey");
2153
- if (!apiKey || !isApiKeyPresent(apiKey)) {
2154
- return;
2155
- }
1660
+ const stored = nonEmpty2(readAgentchatConfigField(cfg, accountId, "apiKey"));
1661
+ const apiKey = nonEmpty2(credentialValues.token) ?? stored;
1662
+ if (!apiKey) return;
2156
1663
  const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
2157
- const spinner = prompter.progress("Validating API key against AgentChat\u2026");
1664
+ const spinner = prompter.progress("Checking the API key with AgentChat\u2026");
1665
+ let check;
2158
1666
  try {
2159
- const result = await validateApiKey(apiKey, { apiBase });
2160
- if (result.ok) {
2161
- spinner.stop(`Authenticated as @${result.agent.handle}`);
2162
- const handle = result.agent.handle;
2163
- const resolvedBase = apiBase ?? DEFAULT_API_BASE2;
2164
- const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
2165
- const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
2166
- const failed = placed.steps.filter((s) => s.status === "failed");
2167
- const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
2168
- await prompter.note(
2169
- [
2170
- ...formatPlacement(placed.steps),
2171
- "",
2172
- 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.",
2173
- ...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."] : [],
2174
- ...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
2175
- ].join("\n"),
2176
- "AgentChat integration placed"
2177
- );
2178
- const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
2179
- return { cfg: applied.cfg };
2180
- }
2181
- spinner.stop(`API key did not pass the live check (${result.reason})`);
1667
+ check = await checkApiKey(apiKey, { apiBase });
1668
+ } catch (err) {
1669
+ spinner.stop("Could not reach AgentChat to check the key");
2182
1670
  await prompter.note(
2183
1671
  [
2184
- result.message,
1672
+ err instanceof Error ? err.message : String(err),
2185
1673
  "",
2186
- "The config was saved \u2014 you can re-run `openclaw channels add agentchat`",
2187
- "to replace the key, or edit ~/.openclaw/config.yaml directly."
1674
+ stored === apiKey ? "The config was saved \u2014 the runtime will retry on startup." : "The key was not saved."
2188
1675
  ].join("\n"),
2189
- "AgentChat validation warning"
1676
+ "AgentChat API unreachable"
2190
1677
  );
2191
- } catch (err) {
2192
- spinner.stop("Could not reach AgentChat for validation");
1678
+ return;
1679
+ }
1680
+ if (!check.ok) {
1681
+ spinner.stop("AgentChat did not accept the API key");
2193
1682
  await prompter.note(
2194
1683
  [
2195
- err instanceof Error ? err.message : String(err),
1684
+ check.message,
2196
1685
  "",
2197
- "The config was saved \u2014 the runtime will retry on startup."
1686
+ 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."
2198
1687
  ].join("\n"),
2199
- "AgentChat API unreachable"
1688
+ "AgentChat API key not accepted"
2200
1689
  );
1690
+ return;
2201
1691
  }
2202
- return;
1692
+ spinner.stop(`Authenticated as @${check.handle}`);
1693
+ const handle = check.handle;
1694
+ const resolvedBase = apiBase ?? DEFAULT_API_BASE;
1695
+ const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
1696
+ const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
1697
+ const failed = placed.steps.filter((s) => s.status === "failed");
1698
+ const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
1699
+ await prompter.note(
1700
+ [
1701
+ ...formatPlacement(placed.steps),
1702
+ "",
1703
+ 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.",
1704
+ ...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."] : [],
1705
+ ...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
1706
+ ].join("\n"),
1707
+ "AgentChat integration placed"
1708
+ );
1709
+ const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
1710
+ return { cfg: applied.cfg };
2203
1711
  },
2204
1712
  completionNote: {
2205
1713
  title: "AgentChat is ready",
@@ -3814,7 +3322,7 @@ var agentchatStatusAdapter = {
3814
3322
  const servedFrom = live?.texts?.source;
3815
3323
  const textsSource = live ? servedFrom === "server" || servedFrom === "cache" ? servedFrom : "missing" : void 0;
3816
3324
  const socketCounters = live?.metrics?.snapshot?.();
3817
- const integration6 = {
3325
+ const integration8 = {
3818
3326
  mode: readWakeModeFromEnv().mode,
3819
3327
  ...health ? { state: health.state } : {},
3820
3328
  ...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
@@ -3831,7 +3339,7 @@ var agentchatStatusAdapter = {
3831
3339
  pausedByOwner: me.paused_by_owner ?? "none",
3832
3340
  mcp,
3833
3341
  placement,
3834
- integration: integration6,
3342
+ integration: integration8,
3835
3343
  ...refusal ? { refusal } : {},
3836
3344
  ...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
3837
3345
  };
@@ -3898,7 +3406,7 @@ var agentchatDoctorAdapter = {
3898
3406
  continue;
3899
3407
  }
3900
3408
  const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
3901
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3409
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3902
3410
  const handle = readAgentchatConfigField(cfg, accountId, "agentHandle");
3903
3411
  const agentId = resolvePlacementAgentId(cfg, accountId);
3904
3412
  for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {
@@ -3937,16 +3445,16 @@ var agentchatDoctorAdapter = {
3937
3445
  for (const accountId of listConfiguredAccountIds(cfg)) {
3938
3446
  if (!isAgentchatAccountEnabled(cfg, accountId)) continue;
3939
3447
  const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
3940
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3448
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3941
3449
  bases.set(apiBase, apiKey);
3942
3450
  if (apiKey && !readAgentchatConfigField(cfg, accountId, "agentHandle")) {
3943
3451
  try {
3944
- const result = await validateApiKey(apiKey, { apiBase });
3452
+ const result = await checkApiKey(apiKey, { apiBase });
3945
3453
  if (result.ok) {
3946
- next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.agent.handle });
3947
- changes.push(`set channels.agentchat${accountId === "default" ? "" : `.accounts.${accountId}`}.agentHandle = ${result.agent.handle}`);
3454
+ next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.handle });
3455
+ changes.push(`set channels.agentchat${accountId === "default" ? "" : `.accounts.${accountId}`}.agentHandle = ${result.handle}`);
3948
3456
  } else {
3949
- warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and the key did not pass the live check (${result.reason}): ${result.message}`);
3457
+ warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and the key did not pass the live check (${result.code}): ${result.message}`);
3950
3458
  }
3951
3459
  } catch (err) {
3952
3460
  warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and AgentChat was not reachable to learn it: ${err instanceof Error ? err.message : String(err)}`);
@@ -4001,7 +3509,7 @@ var uiHints = {
4001
3509
  label: "AgentChat API key",
4002
3510
  placeholder: "ac_\u2026",
4003
3511
  sensitive: true,
4004
- 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."
3512
+ 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."
4005
3513
  },
4006
3514
  apiBase: {
4007
3515
  label: "API base URL",
@@ -4012,19 +3520,26 @@ var uiHints = {
4012
3520
  agentHandle: {
4013
3521
  label: "Agent handle",
4014
3522
  placeholder: "my-agent",
4015
- help: "3\u201330 chars, lowercase letters/digits/hyphens; must start with a letter."
3523
+ help: "The handle the API key belongs to, as AgentChat returned it; setup and `openclaw doctor --fix` write it."
4016
3524
  },
4017
3525
  reconnect: { label: "Reconnect backoff", advanced: true },
4018
3526
  ping: { label: "WebSocket ping cadence", advanced: true },
4019
3527
  outbound: { label: "Outbound send tuning", advanced: true },
4020
3528
  observability: { label: "Logs & metrics", advanced: true }
4021
3529
  };
4022
- var HANDLE_SHAPE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
4023
- function validHandle(value) {
3530
+ function handleOf(value) {
4024
3531
  if (typeof value !== "string") return void 0;
4025
3532
  const bare = value.trim().replace(/^@/, "");
4026
- return bare.length >= 3 && bare.length <= 30 && HANDLE_SHAPE.test(bare) ? bare : void 0;
3533
+ return bare.length > 0 ? bare : void 0;
4027
3534
  }
3535
+ function keyRefusal(check) {
3536
+ return [
3537
+ `AgentChat did not accept the API key (${check.code}): ${check.message}`,
3538
+ "The key was not saved. Run `openclaw channels add agentchat` to register a new agent or recover a lost key (email code)."
3539
+ ].join("\n");
3540
+ }
3541
+ var keyAskedBeforeWrite = null;
3542
+ var keyDigest = (apiKey) => createHash("sha256").update(apiKey).digest("hex");
4028
3543
  function say(runtime, level, line) {
4029
3544
  const env = runtime;
4030
3545
  const fn = env?.[level];
@@ -4032,13 +3547,18 @@ function say(runtime, level, line) {
4032
3547
  }
4033
3548
  var agentchatSetupAdapter = {
4034
3549
  /**
4035
- * Pre-write gate: cheap, sync check that the caller supplied an API key
4036
- * that's at least plausibly shaped. Real authentication happens in
4037
- * `prepareAccountConfigInput` / `afterAccountConfigWritten`.
3550
+ * Pre-write gate: a key AgentChat turned away in
3551
+ * `prepareAccountConfigInput` ends here (OpenClaw prints the line and
3552
+ * writes nothing); otherwise a cheap, sync check that the caller supplied
3553
+ * an API key that's at least plausibly shaped. On an OpenClaw without
3554
+ * `prepareAccountConfigInput`, the lifecycle hook refuses a rejected key
3555
+ * before the write.
4038
3556
  */
4039
3557
  validateInput({ input }) {
3558
+ const refusal = input.keyRefusal;
3559
+ if (typeof refusal === "string" && refusal.length > 0) return refusal;
4040
3560
  if (typeof input.token !== "string" || input.token.trim().length === 0) {
4041
- 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)";
3561
+ 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)";
4042
3562
  }
4043
3563
  if (input.token.length < MIN_API_KEY_LENGTH) {
4044
3564
  return `apiKey looks too short (got ${input.token.length} chars, expect \u2265${MIN_API_KEY_LENGTH})`;
@@ -4056,29 +3576,31 @@ var agentchatSetupAdapter = {
4056
3576
  return null;
4057
3577
  },
4058
3578
  /**
4059
- * Learn the handle the key authenticates as BEFORE the write, so
4060
- * `applyAccountConfig` persists it in the same config write OpenClaw
4061
- * already makes. A key that does not validate leaves the input untouched
4062
- * (the write still happens; the error line says what to fix).
3579
+ * Ask AgentChat about the key BEFORE the write. Accepted: the handle it
3580
+ * belongs to goes into the same config write OpenClaw already makes.
3581
+ * Turned away (401 / 403): the input carries the refusal, `validateInput`
3582
+ * returns it, and OpenClaw writes nothing. No verdict (unreachable, a
3583
+ * 5xx): the key is written for the runtime to try, as the wizard does.
4063
3584
  */
4064
- async prepareAccountConfigInput({ accountId, input, runtime }) {
3585
+ async prepareAccountConfigInput({ cfg, accountId, input, runtime }) {
4065
3586
  const apiKey = typeof input.token === "string" ? input.token : void 0;
4066
3587
  if (!apiKey || apiKey.length < MIN_API_KEY_LENGTH) return input;
4067
- const apiBase = typeof input.url === "string" && input.url.length > 0 ? input.url : void 0;
3588
+ const apiBase = typeof input.url === "string" && input.url.length > 0 ? input.url : readAgentchatConfigField(cfg, accountId, "apiBase");
3589
+ keyAskedBeforeWrite = keyDigest(apiKey);
4068
3590
  try {
4069
- const result = await validateApiKey(apiKey, { apiBase });
3591
+ const result = await checkApiKey(apiKey, { apiBase });
4070
3592
  if (result.ok) {
4071
- say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.agent.handle} (${result.agent.email})`);
3593
+ say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.handle}`);
4072
3594
  try {
4073
3595
  placeApiKeyInDotEnv(apiKey);
4074
3596
  } catch (err) {
4075
3597
  say(runtime, "error", `[agentchat:${accountId}] could not write AGENTCHAT_API_KEY to ${dotEnvPath()}: ${err instanceof Error ? err.message : String(err)}`);
4076
3598
  }
4077
- return { ...input, agentHandle: result.agent.handle };
3599
+ return { ...input, agentHandle: result.handle };
4078
3600
  }
4079
- say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`);
3601
+ return { ...input, keyRefusal: keyRefusal(result) };
4080
3602
  } catch (err) {
4081
- say(runtime, "error", `[agentchat:${accountId}] live key validation failed: ${err instanceof Error ? err.message : String(err)}`);
3603
+ 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)}`);
4082
3604
  }
4083
3605
  return input;
4084
3606
  },
@@ -4092,12 +3614,12 @@ var agentchatSetupAdapter = {
4092
3614
  const patch = {};
4093
3615
  if (typeof input.token === "string" && input.token.length > 0) patch.apiKey = input.token;
4094
3616
  if (typeof input.url === "string" && input.url.length > 0) patch.apiBase = input.url;
4095
- const handle = validHandle(input.agentHandle);
3617
+ const handle = handleOf(input.agentHandle);
4096
3618
  if (handle) patch.agentHandle = handle;
4097
3619
  const withAccount = applyAgentchatAccountPatch(cfg, accountId, patch);
4098
3620
  const apiKey = readAgentchatConfigField(withAccount, accountId, "apiKey");
4099
3621
  if (!apiKey) return withAccount;
4100
- const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3622
+ const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE;
4101
3623
  return applyIntegrationConfig(withAccount, { accountId, handle, apiKey, apiBase }).cfg;
4102
3624
  },
4103
3625
  /**
@@ -4108,16 +3630,16 @@ var agentchatSetupAdapter = {
4108
3630
  async afterAccountConfigWritten({ cfg, accountId, input, runtime }) {
4109
3631
  const apiKey = typeof input.token === "string" ? input.token : readAgentchatConfigField(cfg, accountId, "apiKey");
4110
3632
  if (!apiKey) return;
4111
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
4112
- let handle = validHandle(input.agentHandle) ?? readAgentchatConfigField(cfg, accountId, "agentHandle");
3633
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3634
+ let handle = handleOf(input.agentHandle) ?? handleOf(readAgentchatConfigField(cfg, accountId, "agentHandle"));
4113
3635
  if (!handle) {
4114
3636
  try {
4115
- const result = await validateApiKey(apiKey, { apiBase });
3637
+ const result = await checkApiKey(apiKey, { apiBase });
4116
3638
  if (result.ok) {
4117
- handle = result.agent.handle;
3639
+ handle = result.handle;
4118
3640
  say(runtime, "log", `[agentchat:${accountId}] authenticated as @${handle}; run \`openclaw doctor --fix\` to persist channels.agentchat.agentHandle`);
4119
3641
  } else {
4120
- say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`);
3642
+ say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.code}): ${result.message}`);
4121
3643
  return;
4122
3644
  }
4123
3645
  } catch (err) {
@@ -4151,8 +3673,24 @@ function accountSectionPersistable(cfg, accountId) {
4151
3673
  if (!raw) return true;
4152
3674
  return agentchatChannelConfigSchema.safeParse(raw).success;
4153
3675
  }
3676
+ async function refuseRejectedKey(prevCfg, nextCfg, accountId, runtime) {
3677
+ const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
3678
+ if (!apiKey || apiKey === readAgentchatConfigField(prevCfg, accountId, "apiKey")) return;
3679
+ if (keyAskedBeforeWrite === keyDigest(apiKey)) return;
3680
+ let check;
3681
+ try {
3682
+ check = await checkApiKey(apiKey, { apiBase: readAgentchatConfigField(nextCfg, accountId, "apiBase") });
3683
+ } catch (err) {
3684
+ 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)}`);
3685
+ return;
3686
+ }
3687
+ if (check.ok) return;
3688
+ say(runtime, "error", keyRefusal(check));
3689
+ throw new WizardCancelledError("AgentChat did not accept the API key");
3690
+ }
4154
3691
  var agentchatLifecycleAdapter = {
4155
3692
  async onAccountConfigChanged({ prevCfg, nextCfg, accountId, runtime }) {
3693
+ await refuseRejectedKey(prevCfg, nextCfg, accountId, runtime);
4156
3694
  const wasEnabled = isAccountEnabled(prevCfg, accountId);
4157
3695
  const isEnabled = isAccountEnabled(nextCfg, accountId);
4158
3696
  if (wasEnabled === isEnabled) return;
@@ -4168,13 +3706,13 @@ var agentchatLifecycleAdapter = {
4168
3706
  for (const line of removeIntegrationFiles(nextCfg, accountId, { clearKey: false })) say(runtime, "log", `[agentchat:${accountId}] ${line}`);
4169
3707
  return;
4170
3708
  }
4171
- const handle = validHandle(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
3709
+ const handle = handleOf(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
4172
3710
  if (!handle) {
4173
3711
  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`);
4174
3712
  return;
4175
3713
  }
4176
3714
  const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
4177
- const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3715
+ const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
4178
3716
  const identityLine = apiKey ? await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId }) : null;
4179
3717
  const restored = restoreIdentityLine(nextCfg, accountId, handle, identityLine);
4180
3718
  if (restored.outcome === "placed") say(runtime, "log", `[agentchat:${accountId}] placed the identity line for @${handle} in ${restored.path}`);
@@ -4337,6 +3875,20 @@ function hasAgentChatConfiguredState(config) {
4337
3875
  return true;
4338
3876
  }
4339
3877
 
4340
- export { AGENTCHAT_CHANNEL_ID, AGENTCHAT_DEFAULT_ACCOUNT_ID, AgentChatChannelError, IntegrationSocket, MAX_HUNG_TURNS, MCP_SERVER_NAME, OPENCLAW_TOOL_NAMER, OpenClawTexts, accountTurns, agentchatChannelEntry, agentchatPlugin, agentchatSetupEntry, agentchatPlugin as agentchatSetupPlugin, assertApiKeyValid, createInMemoryMetrics, createIntegrationLoop, createLoopTurnStarter, createMetrics, createNoopMetrics, createTextsCache, agentchatChannelEntry as default, hasAgentChatConfiguredState, hostedMcpServerEntry, hostedMcpSnippet, hostedMcpUrl, loadIdentityLine, mcpToolName, parseChannelConfig, probeHostedMcp, realtimeOptionsFor, recoverAgentStart, recoverAgentVerify, registerAgentStart, registerAgentVerify, spellTextsForOpenClaw, spellToolsForOpenClaw, trackerFor, turnEndOf, validateApiKey };
3878
+ // src/errors.ts
3879
+ var AgentChatChannelError = class extends Error {
3880
+ class_;
3881
+ retryAfterMs;
3882
+ statusCode;
3883
+ constructor(class_, message, options = {}) {
3884
+ super(message, { cause: options.cause });
3885
+ this.name = "AgentChatChannelError";
3886
+ this.class_ = class_;
3887
+ this.retryAfterMs = options.retryAfterMs;
3888
+ this.statusCode = options.statusCode;
3889
+ }
3890
+ };
3891
+
3892
+ export { AGENTCHAT_CHANNEL_ID, AGENTCHAT_DEFAULT_ACCOUNT_ID, AgentChatChannelError, IntegrationSocket, MAX_HUNG_TURNS, MCP_SERVER_NAME, OPENCLAW_TOOL_NAMER, OpenClawTexts, accountCallOptions, accountTurns, agentchatChannelEntry, agentchatPlugin, agentchatSetupEntry, agentchatPlugin as agentchatSetupPlugin, checkApiKey, createInMemoryMetrics, createIntegrationLoop, createLoopTurnStarter, createMetrics, createNoopMetrics, createTextsCache, agentchatChannelEntry as default, hasAgentChatConfiguredState, hostedMcpServerEntry, hostedMcpSnippet, hostedMcpUrl, loadIdentityLine, mcpToolName, parseChannelConfig, probeHostedMcp, realtimeOptionsFor, spellTextsForOpenClaw, spellToolsForOpenClaw, trackerFor, turnEndOf };
4341
3893
  //# sourceMappingURL=index.js.map
4342
3894
  //# sourceMappingURL=index.js.map