@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.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.2";
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) {
@@ -741,14 +541,14 @@ var FAILURE_STATUSES = /* @__PURE__ */ new Set([
741
541
  "invalid"
742
542
  ]);
743
543
  function coversWholeSession(rows) {
744
- if (asRecord2(rows[0]?.__openclaw)?.seq !== 1) return false;
544
+ if (asRecord(rows[0]?.__openclaw)?.seq !== 1) return false;
745
545
  return rows.every((row) => {
746
- const meta = asRecord2(row.__openclaw);
546
+ const meta = asRecord(row.__openclaw);
747
547
  return meta?.kind !== "compaction" && meta?.kind !== "reset" && meta?.truncated !== true;
748
548
  });
749
549
  }
750
550
  function isOtherRun(row, runId) {
751
- const tagged = asRecord2(row.__openclaw)?.runId ?? nestedCallOf(row)?.runId;
551
+ const tagged = asRecord(row.__openclaw)?.runId ?? nestedCallOf(row)?.runId;
752
552
  return typeof tagged === "string" && tagged.trim().length > 0 && tagged.trim() !== runId;
753
553
  }
754
554
  var CODE_MODE_ONLY_TOOL_NAMES = /* @__PURE__ */ new Set(["tool_search_code", "wait"]);
@@ -760,7 +560,7 @@ function codeModeScriptsCompleted(rows, calls) {
760
560
  for (const row of rows) {
761
561
  if ((row.role === "toolResult" || row.role === "tool") && typeof row.toolCallId === "string") results.set(row.toolCallId, row);
762
562
  }
763
- const completed = (row) => row !== void 0 && row.isError !== true && asRecord2(row.details)?.status === "completed";
563
+ const completed = (row) => row !== void 0 && row.isError !== true && asRecord(row.details)?.status === "completed";
764
564
  for (const [id, call] of calls) {
765
565
  if (isCodeModeCall(call) && !completed(results.get(id))) return false;
766
566
  }
@@ -779,7 +579,7 @@ function isShellExecResult(row, calls) {
779
579
  const call = typeof row.toolCallId === "string" ? calls.get(row.toolCallId) : void 0;
780
580
  const args = callArguments(call);
781
581
  if (!args || typeof args.command !== "string" || args.code !== void 0) return false;
782
- const details = asRecord2(row.details);
582
+ const details = asRecord(row.details);
783
583
  if (!details || details.telemetry !== void 0) return false;
784
584
  return details.exitCode !== void 0 || typeof details.durationMs === "number" || typeof details.aggregated === "string";
785
585
  }
@@ -788,7 +588,7 @@ function assistantToolCalls(rows) {
788
588
  for (const row of rows) {
789
589
  if (row.role !== "assistant" || !Array.isArray(row.content)) continue;
790
590
  for (const block of row.content) {
791
- const call = asRecord2(block);
591
+ const call = asRecord(block);
792
592
  if (call?.type === "toolCall" && typeof call.id === "string") calls.set(call.id, call);
793
593
  }
794
594
  }
@@ -801,7 +601,7 @@ function releaseOf(rows, calls, nested, version) {
801
601
  return { recordsNestedCalls: trusted, marksFailedRows: trusted };
802
602
  }
803
603
  const parents = new Set(nested.map((call) => call.parentToolCallId));
804
- 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));
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));
805
605
  return { recordsNestedCalls: nested.length > 0 || dispatchAction, marksFailedRows: dispatchAction };
806
606
  }
807
607
  var OPENCLAW_VERSION = /^(\d+)\.(\d+)\.(\d+)(-.+)?$/;
@@ -827,13 +627,13 @@ function toolNameOf(row) {
827
627
  var NESTED_TOOL_ACTIVITY = "openclaw.nested-tool.v1";
828
628
  function nestedCallOf(row) {
829
629
  if (row.role !== "custom" || row.customType !== NESTED_TOOL_ACTIVITY) return null;
830
- return asRecord2(row.details);
630
+ return asRecord(row.details);
831
631
  }
832
632
  function nestedVerdict(call) {
833
633
  const toolName = typeof call.toolName === "string" ? call.toolName : "";
834
634
  if (!toolName.startsWith(TOOL_PREFIX)) return "not_agentchat";
835
- const result = asRecord2(call.result);
836
- if (call.isError === true || result !== null && failedResult(result.isError, asRecord2(result.details))) return "failed";
635
+ const result = asRecord(call.result);
636
+ if (call.isError === true || result !== null && failedResult(result.isError, asRecord(result.details))) return "failed";
837
637
  return call.isError === false ? "ok" : "unknown";
838
638
  }
839
639
  var OTHER_SESSION_TOOLS = /* @__PURE__ */ new Set(["sessions_spawn", "sessions_send"]);
@@ -844,13 +644,13 @@ function delegatedToChild(rows, calls, nested) {
844
644
  if (typeof call.name === "string" && DISPATCHER_TOOL_NAMES.has(call.name) && names(dispatchTarget(call))) return true;
845
645
  }
846
646
  if (nested.some((call) => names(call.toolName))) return true;
847
- return rows.some((row) => names(toolNameOf(row)) || names(asRecord2(asRecord2(row.details)?.tool)?.name));
647
+ return rows.some((row) => names(toolNameOf(row)) || names(asRecord(asRecord(row.details)?.tool)?.name));
848
648
  }
849
649
  function callVerdict(message, calls, release) {
850
650
  const toolName = toolNameOf(message);
851
- const details = asRecord2(message.details);
651
+ const details = asRecord(message.details);
852
652
  if (toolName.startsWith(TOOL_PREFIX)) return directVerdict(message.isError, details);
853
- const entry = asRecord2(details?.tool);
653
+ const entry = asRecord(details?.tool);
854
654
  if (entry && isAgentChatEntry(entry)) return dispatchedVerdict(message.isError, details);
855
655
  if (!DISPATCHER_TOOL_NAMES.has(toolName) || entry) return "not_agentchat";
856
656
  const target = dispatchTarget(typeof message.toolCallId === "string" ? calls.get(message.toolCallId) : void 0);
@@ -874,10 +674,10 @@ function wasHostedResult(details) {
874
674
  return keys.includes("mcpServer") && (keys.includes("mcpTool") || keys.includes("mcpOperation"));
875
675
  }
876
676
  function dispatchedVerdict(isError, details) {
877
- const result = asRecord2(details?.result);
677
+ const result = asRecord(details?.result);
878
678
  if (failedResult(isError, details)) return "failed";
879
- if (result && failedResult(result.isError, asRecord2(result.details))) return "failed";
880
- const ok = isError === false && details?.status === void 0 && isHostedSuccessDetails(asRecord2(result?.details));
679
+ if (result && failedResult(result.isError, asRecord(result.details))) return "failed";
680
+ const ok = isError === false && details?.status === void 0 && isHostedSuccessDetails(asRecord(result?.details));
881
681
  return ok ? "ok" : "unknown";
882
682
  }
883
683
  function failedResult(isError, details) {
@@ -901,7 +701,7 @@ function isHostedSuccessDetails(details) {
901
701
  function isAgentChatEntry(tool) {
902
702
  if (typeof tool.name === "string" && tool.name.startsWith(TOOL_PREFIX)) return true;
903
703
  if (tool.sourceName === MCP_SERVER_NAME) return true;
904
- const mcp = asRecord2(tool.mcp);
704
+ const mcp = asRecord(tool.mcp);
905
705
  return mcp?.serverName === MCP_SERVER_NAME;
906
706
  }
907
707
  function dispatchTarget(call) {
@@ -921,16 +721,16 @@ function callArguments(call) {
921
721
  return null;
922
722
  }
923
723
  }
924
- return asRecord2(args);
724
+ return asRecord(args);
925
725
  }
926
726
  function unwrapMessage(row) {
927
- const record = asRecord2(row);
727
+ const record = asRecord(row);
928
728
  if (!record) return null;
929
729
  if (typeof record.role === "string") return record;
930
- const inner = asRecord2(record.message);
730
+ const inner = asRecord(record.message);
931
731
  return inner && typeof inner.role === "string" ? inner : null;
932
732
  }
933
- function asRecord2(value) {
733
+ function asRecord(value) {
934
734
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
935
735
  }
936
736
  function nonEmpty(value) {
@@ -1186,7 +986,7 @@ function applyIntegrationConfig(cfg, params) {
1186
986
  const changes = [];
1187
987
  let next = cfg;
1188
988
  const bareHandle = (params.handle ?? "").trim().replace(/^@/, "");
1189
- if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle && isValidHandleShape(bareHandle)) {
989
+ if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle) {
1190
990
  next = applyAgentchatAccountPatch(next, params.accountId, { agentHandle: bareHandle });
1191
991
  changes.push(`channels.agentchat${params.accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID ? "" : `.accounts.${params.accountId}`}.agentHandle = ${bareHandle}`);
1192
992
  }
@@ -1521,57 +1321,15 @@ function getClient({ accountId, config, options }) {
1521
1321
 
1522
1322
  // src/channel.wizard.ts
1523
1323
  var JUST_REGISTERED_SENTINEL = "_agentchatJustRegistered";
1524
- var HANDLE_PATTERN2 = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
1525
- var HANDLE_MIN_LENGTH = 3;
1526
- var HANDLE_MAX_LENGTH = 30;
1527
- var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1528
- function isValidHandleShape2(value) {
1529
- return value.length >= HANDLE_MIN_LENGTH && value.length <= HANDLE_MAX_LENGTH && HANDLE_PATTERN2.test(value);
1530
- }
1531
- var OTP_PATTERN = /^\d{6}$/;
1324
+ var LABELS = {
1325
+ ...agentchatme.integration.account.DEFAULT_LABELS,
1326
+ handle: "Handle (your @name on AgentChat)"
1327
+ };
1532
1328
  function hasConfiguredKey(cfg, accountId) {
1533
1329
  return isApiKeyPresent(readAgentchatConfigField(cfg, accountId, "apiKey"));
1534
1330
  }
1535
- var MAX_START_RETRIES = 5;
1536
- async function promptEmail(prompter, opts = {}) {
1537
- return (await prompter.text({
1538
- message: opts.message ?? "Email \u2014 receives a 6-digit verification code",
1539
- placeholder: "you@example.com",
1540
- validate: (value) => {
1541
- const trimmed = value.trim();
1542
- if (!trimmed) return "Email is required";
1543
- if (!EMAIL_PATTERN.test(trimmed)) return "Not a valid email format";
1544
- return void 0;
1545
- }
1546
- })).trim();
1547
- }
1548
- async function promptHandle(prompter, opts = {}) {
1549
- return (await prompter.text({
1550
- message: opts.message ?? "Choose a handle (your @name on AgentChat)",
1551
- placeholder: "3\u201330 chars, lowercase a-z, 0-9, hyphens, starts with a letter",
1552
- ...opts.initialValue ? { initialValue: opts.initialValue } : {},
1553
- validate: (value) => {
1554
- const trimmed = value.trim();
1555
- if (!trimmed) return "Handle is required";
1556
- if (trimmed.length < HANDLE_MIN_LENGTH || trimmed.length > HANDLE_MAX_LENGTH) {
1557
- return `Length must be ${HANDLE_MIN_LENGTH}\u2013${HANDLE_MAX_LENGTH} chars (you entered ${trimmed.length})`;
1558
- }
1559
- if (!/^[a-z]/.test(trimmed)) return "Must start with a lowercase letter";
1560
- if (/[^a-z0-9-]/.test(trimmed)) {
1561
- return "Only lowercase letters, digits, and hyphens \u2014 no underscores, dots, or symbols";
1562
- }
1563
- if (trimmed.includes("--")) return "No consecutive hyphens";
1564
- if (trimmed.endsWith("-")) return "Cannot end with a hyphen";
1565
- return void 0;
1566
- }
1567
- })).trim();
1568
- }
1569
- async function promptDisplayName(prompter) {
1570
- return (await prompter.text({
1571
- message: "Display name (shown next to your @handle)",
1572
- placeholder: "e.g. Anton, Builder Bot, Sasha",
1573
- validate: () => void 0
1574
- })).trim();
1331
+ function nonEmpty2(value) {
1332
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
1575
1333
  }
1576
1334
  async function runChangeApiBaseFlow(params) {
1577
1335
  const { cfg, accountId, prompter } = params;
@@ -1609,388 +1367,182 @@ async function runChangeApiBaseFlow(params) {
1609
1367
  await prompter.note(`API base set to ${input}`, "Updated");
1610
1368
  return { cfg: patched };
1611
1369
  }
1612
- function describeEmailPolicyRejection(email, result) {
1613
- if (result.limit === void 0) return result.message;
1614
- 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.`;
1615
- }
1616
- async function promptEmailPolicyChoice(prompter, email, result) {
1617
- return prompter.select({
1618
- message: `${describeEmailPolicyRejection(email, result)} What next?`,
1619
- options: [
1620
- {
1621
- value: "retry",
1622
- label: "Use a different email address",
1623
- hint: "a +alias like you+agent2@example.com counts as a separate email"
1624
- },
1625
- {
1626
- value: "recover",
1627
- label: "Recover the API key of an agent this email already backs",
1628
- hint: "needs that agent\u2019s handle \u2014 a code goes to this email"
1629
- },
1630
- { value: "paste", label: "Paste a key from an existing agent" },
1631
- { value: "cancel", label: "Cancel registration" }
1632
- ],
1633
- initialValue: "retry"
1634
- });
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();
1635
1376
  }
1636
- async function runRegisterFlow(params) {
1637
- const { cfg, accountId, prompter, apiBase } = params;
1638
- await prompter.note(
1639
- [
1640
- "Registration mints a new AgentChat agent identity tied to your email.",
1641
- "One email can back several agents (the server enforces the limit);",
1642
- "each one registers and verifies separately.",
1643
- "You will receive a 6-digit code to verify \u2014 check your inbox (and spam)."
1644
- ].join("\n"),
1645
- "AgentChat: register a new agent"
1646
- );
1647
- let email = await promptEmail(prompter);
1648
- let handle = await promptHandle(prompter);
1649
- const displayName = await promptDisplayName(prompter);
1650
- let startResult;
1651
- let startedOk = false;
1652
- for (let attempt = 1; attempt <= MAX_START_RETRIES; attempt += 1) {
1653
- const startSpinner = prompter.progress(
1654
- attempt === 1 ? "Sending verification code\u2026" : "Retrying\u2026"
1655
- );
1656
- try {
1657
- startResult = await registerAgentStart(
1658
- {
1659
- email,
1660
- handle,
1661
- ...displayName ? { displayName } : {}
1662
- },
1663
- { apiBase }
1664
- );
1665
- } catch (err) {
1666
- startSpinner.stop("Could not reach AgentChat");
1667
- await prompter.note(
1668
- `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
1669
- "Registration failed"
1670
- );
1671
- return "abort";
1672
- }
1673
- if (startResult.ok) {
1674
- startSpinner.stop(`Verification code sent to ${email}`);
1675
- startedOk = true;
1676
- break;
1677
- }
1678
- startSpinner.stop("Registration rejected");
1679
- switch (startResult.reason) {
1680
- case "invalid-handle":
1681
- case "handle-taken": {
1682
- 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).";
1683
- await prompter.note(`${detail} Pick a different handle and we'll try again.`, "Pick a different handle");
1684
- handle = await promptHandle(prompter);
1685
- continue;
1686
- }
1687
- case "email-limit-reached":
1688
- case "email-exhausted": {
1689
- const choice = await promptEmailPolicyChoice(prompter, email, {
1690
- reason: startResult.reason,
1691
- limit: startResult.limit,
1692
- message: startResult.message
1693
- });
1694
- if (choice === "paste") return "user-chose-paste";
1695
- if (choice === "recover") return "user-chose-recover";
1696
- if (choice === "cancel") return "abort";
1697
- email = await promptEmail(prompter);
1698
- continue;
1699
- }
1700
- case "rate-limited": {
1701
- const wait = startResult.retryAfterSeconds ? ` Try again in ${startResult.retryAfterSeconds}s.` : "";
1702
- await prompter.note(`Too many registration attempts.${wait}`, "Rate limited");
1703
- return "abort";
1704
- }
1705
- case "otp-failed": {
1706
- await prompter.note(
1707
- "The verification-code email could not be sent. Try again in a minute, or paste an existing key instead.",
1708
- "OTP delivery failed"
1709
- );
1710
- return "abort";
1711
- }
1712
- case "network-error":
1713
- case "server-error":
1714
- case "validation":
1715
- default: {
1716
- await prompter.note(describeRegisterStartError(startResult), "Could not start registration");
1717
- return "abort";
1718
- }
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 };
1719
1413
  }
1720
- }
1721
- if (!startedOk || !startResult || !startResult.ok) {
1722
- await prompter.note(
1723
- "Too many attempts. Restart the wizard to try again, or paste an existing key at the next prompt.",
1724
- "Registration failed"
1725
- );
1726
- return "abort";
1727
- }
1728
- const maxCodeAttempts = 3;
1729
- let verifyResult = null;
1730
- for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
1731
- const code = (await prompter.text({
1732
- message: attempt === 1 ? "Enter the 6-digit verification code from your email" : `Verification code (attempt ${attempt}/${maxCodeAttempts})`,
1733
- placeholder: "123456",
1734
- validate: (value) => {
1735
- const trimmed = value.trim();
1736
- if (!trimmed) return "Code is required";
1737
- if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
1738
- return void 0;
1739
- }
1740
- })).trim();
1741
- 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");
1742
1421
  try {
1743
- verifyResult = await registerAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
1744
- } catch (err) {
1745
- verifySpinner.stop("Could not reach AgentChat");
1746
- await prompter.note(
1747
- `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
1748
- "Verification failed"
1749
- );
1750
- return "abort";
1751
- }
1752
- if (verifyResult.ok) {
1753
- verifySpinner.stop(`Registered as @${verifyResult.agent.handle}`);
1754
- break;
1755
- }
1756
- verifySpinner.stop("Verification failed");
1757
- if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
1758
- await prompter.note(
1759
- "That code did not match. Check your email and try again.",
1760
- "Invalid verification code"
1761
- );
1762
- continue;
1422
+ return await globalThis.fetch(input, init);
1423
+ } finally {
1424
+ progress.stop();
1763
1425
  }
1764
- await prompter.note(describeRegisterVerifyError(verifyResult), "Registration failed");
1765
- return "abort";
1766
- }
1767
- if (!verifyResult || !verifyResult.ok) {
1768
- await prompter.note(
1769
- "Too many incorrect codes. Restart the wizard to receive a new code.",
1770
- "Registration failed"
1771
- );
1772
- return "abort";
1773
- }
1774
- const patch = { apiKey: verifyResult.apiKey };
1775
- if (isValidHandleShape2(verifyResult.agent.handle)) {
1776
- patch.agentHandle = verifyResult.agent.handle;
1777
- }
1778
- 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) {
1779
1445
  await prompter.note(
1780
1446
  [
1781
- `Handle: @${verifyResult.agent.handle}`,
1782
- `Email: ${verifyResult.agent.email}`,
1783
- `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)."
1784
1450
  ].join("\n"),
1785
- "AgentChat account created"
1451
+ "AgentChat: register a new agent"
1786
1452
  );
1787
- return {
1788
- cfg: nextCfg,
1789
- credentialValues: {
1790
- token: verifyResult.apiKey,
1791
- [JUST_REGISTERED_SENTINEL]: "1"
1792
- }
1793
- };
1794
- }
1795
- function describeRegisterStartError(result) {
1796
- switch (result.reason) {
1797
- case "invalid-handle":
1798
- return "That handle is not acceptable. Try a different one (3\u201330 chars \u2014 lowercase letters/digits/hyphens; must start with a letter).";
1799
- case "handle-taken":
1800
- return "That handle is already taken. Try a different one.";
1801
- case "email-limit-reached":
1802
- 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.`;
1803
- case "email-exhausted":
1804
- 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.`;
1805
- case "rate-limited": {
1806
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1807
- return `Rate limited.${wait}`;
1808
- }
1809
- case "otp-failed":
1810
- return "The verification-code email could not be sent. Try again in a minute.";
1811
- case "network-error":
1812
- case "server-error":
1813
- case "validation":
1814
- default:
1815
- return result.message;
1816
- }
1817
- }
1818
- function describeRegisterVerifyError(result) {
1819
- switch (result.reason) {
1820
- case "expired":
1821
- return "This code expired. Restart the wizard to receive a new one.";
1822
- case "invalid-code":
1823
- return "Too many incorrect codes. Restart the wizard to receive a new one.";
1824
- case "handle-taken":
1825
- return "Your chosen handle was claimed by another registration in the meantime. Restart with a different handle.";
1826
- case "email-limit-reached":
1827
- 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.`;
1828
- case "email-exhausted":
1829
- 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.`;
1830
- case "rate-limited": {
1831
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1832
- return `Rate limited.${wait}`;
1833
- }
1834
- case "network-error":
1835
- case "server-error":
1836
- case "unexpected-shape":
1837
- case "validation":
1838
- default:
1839
- return result.message;
1840
- }
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 } : {} };
1841
1460
  }
1842
- async function runRecoverFlow(params) {
1843
- const { cfg, accountId, prompter, apiBase } = params;
1844
- const storedHandle = readAgentchatConfigField(cfg, accountId, "agentHandle");
1845
- const defaultHandle = storedHandle && isValidHandleShape2(storedHandle) ? storedHandle : void 0;
1461
+ async function recoverInput(prompter, configuredHandle) {
1846
1462
  await prompter.note(
1847
1463
  [
1848
- "Recovery re-issues the API key for ONE agent \u2014 the handle you name below.",
1849
- "You need that handle and the email it registered with; a 6-digit code",
1850
- "goes to that email. The old key stops working the moment the new one",
1851
- "is minted.",
1852
- ...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.`] : []
1853
1468
  ].join("\n"),
1854
1469
  "AgentChat: recover a lost API key"
1855
1470
  );
1856
- const handle = await promptHandle(prompter, {
1857
- message: "Handle of the agent to recover (its @name on AgentChat)",
1858
- ...defaultHandle ? { initialValue: defaultHandle } : {}
1859
- });
1860
- const email = await promptEmail(prompter, {
1861
- message: `Email @${handle} registered with \u2014 receives a 6-digit recovery code`
1862
- });
1863
- const startSpinner = prompter.progress("Requesting recovery code\u2026");
1864
- 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;
1865
1487
  try {
1866
- 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
+ });
1867
1497
  } catch (err) {
1868
- startSpinner.stop("Could not reach AgentChat");
1869
- await prompter.note(
1870
- `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
1871
- "Recovery failed"
1872
- );
1873
- return "abort";
1874
- }
1875
- if (!startResult.ok) {
1876
- startSpinner.stop("Recovery rejected");
1877
- await prompter.note(describeRecoverStartError(startResult), "Could not start recovery");
1878
- return "abort";
1879
- }
1880
- startSpinner.stop(startResult.message);
1881
- const maxCodeAttempts = 3;
1882
- let verifyResult = null;
1883
- for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
1884
- const code = (await prompter.text({
1885
- message: attempt === 1 ? `Enter the 6-digit recovery code (check ${email}, including spam)` : `Recovery code (attempt ${attempt}/${maxCodeAttempts})`,
1886
- placeholder: "123456",
1887
- validate: (value) => {
1888
- const trimmed = value.trim();
1889
- if (!trimmed) return "Code is required";
1890
- if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
1891
- return void 0;
1892
- }
1893
- })).trim();
1894
- const verifySpinner = prompter.progress("Verifying code\u2026");
1895
- try {
1896
- verifyResult = await recoverAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
1897
- } catch (err) {
1898
- verifySpinner.stop("Could not reach AgentChat");
1899
- await prompter.note(
1900
- `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
1901
- "Recovery failed"
1902
- );
1903
- return "abort";
1904
- }
1905
- if (verifyResult.ok) {
1906
- verifySpinner.stop(`Recovered @${verifyResult.handle}`);
1907
- break;
1908
- }
1909
- verifySpinner.stop("Verification failed");
1910
- if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
1911
- await prompter.note(
1912
- "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.",
1913
- "Invalid recovery code"
1914
- );
1915
- continue;
1916
- }
1917
- await prompter.note(describeRecoverVerifyError(verifyResult), "Recovery failed");
1918
- return "abort";
1919
- }
1920
- 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";
1921
1500
  await prompter.note(
1922
- "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.",
1923
- "Recovery failed"
1501
+ err instanceof Error ? err.message : String(err),
1502
+ unreached ? "Could not reach AgentChat" : `${kind === "register" ? "Registration" : "Recovery"} failed`
1924
1503
  );
1925
- return "abort";
1926
- }
1927
- const patch = { apiKey: verifyResult.apiKey };
1928
- if (isValidHandleShape2(verifyResult.handle)) {
1929
- patch.agentHandle = verifyResult.handle;
1504
+ return notCompleted(prompter, kind);
1930
1505
  }
1931
- 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 });
1932
1508
  await prompter.note(
1933
1509
  [
1934
- `Handle: @${verifyResult.handle}`,
1935
- `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`,
1936
- "",
1937
- "The previous key for this agent has been revoked."
1510
+ `Handle: @${result.handle}`,
1511
+ `API key: ${redactKey(result.apiKey)} (saved to your OpenClaw config)`
1938
1512
  ].join("\n"),
1939
- "AgentChat API key recovered"
1513
+ kind === "register" ? "AgentChat account created" : "AgentChat API key recovered"
1940
1514
  );
1941
1515
  return {
1942
1516
  cfg: nextCfg,
1943
1517
  credentialValues: {
1944
- token: verifyResult.apiKey,
1518
+ token: result.apiKey,
1945
1519
  [JUST_REGISTERED_SENTINEL]: "1"
1946
1520
  }
1947
1521
  };
1948
1522
  }
1949
- function describeRecoverStartError(result) {
1950
- switch (result.reason) {
1951
- case "rate-limited": {
1952
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1953
- return `Too many recovery attempts from this network.${wait}`;
1954
- }
1955
- case "validation":
1956
- return `AgentChat rejected the request: ${result.message}`;
1957
- case "network-error":
1958
- case "server-error":
1959
- case "unexpected-shape":
1960
- default:
1961
- return result.message;
1962
- }
1963
- }
1964
- function describeRecoverVerifyError(result) {
1965
- switch (result.reason) {
1966
- case "expired":
1967
- return "This recovery code expired. Restart the wizard to request a new one.";
1968
- case "invalid-code":
1969
- return "Too many incorrect codes. Restart the wizard to request a new one.";
1970
- case "handle-required": {
1971
- const handles = result.handles ?? [];
1972
- const list = handles.length > 0 ? `
1973
-
1974
- Agents on this email:
1975
- ${handles.map((h) => ` @${h}`).join("\n")}` : "";
1976
- return `This email backs more than one agent. Run recovery again and enter the handle you want to recover.${list}`;
1977
- }
1978
- case "rate-limited": {
1979
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1980
- return `Rate limited.${wait}`;
1981
- }
1982
- case "network-error":
1983
- case "server-error":
1984
- case "unexpected-shape":
1985
- case "validation":
1986
- default:
1987
- return result.message;
1988
- }
1989
- }
1990
1523
  function redactKey(apiKey) {
1991
1524
  if (apiKey.length < 12) return "\u2022\u2022\u2022\u2022";
1992
1525
  return `${apiKey.slice(0, 8)}\u2026${apiKey.slice(-4)}`;
1993
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
+ }
1994
1546
  var agentchatSetupWizard = {
1995
1547
  channel: AGENTCHAT_CHANNEL_ID,
1996
1548
  // AgentChat is one-agent-per-account by product design — the agent IS the
@@ -2035,9 +1587,9 @@ var agentchatSetupWizard = {
2035
1587
  "AgentChat is a messaging platform for AI agents \u2014 direct messages,",
2036
1588
  "groups, presence, attachments. Registration is free.",
2037
1589
  "",
2038
- "This wizard will mint a new account via email OTP, accept an existing",
2039
- "API key, or recover a lost key (handle + email OTP) \u2014 your choice in",
2040
- "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."
2041
1593
  ]
2042
1594
  },
2043
1595
  prepare: async ({ cfg, accountId, credentialValues, prompter }) => {
@@ -2073,7 +1625,7 @@ var agentchatSetupWizard = {
2073
1625
  options: [
2074
1626
  {
2075
1627
  value: "register",
2076
- label: "Register a new agent (email OTP)",
1628
+ label: "Register a new agent (email code)",
2077
1629
  hint: "no account yet \u2014 the wizard creates one"
2078
1630
  },
2079
1631
  {
@@ -2083,64 +1635,14 @@ var agentchatSetupWizard = {
2083
1635
  },
2084
1636
  {
2085
1637
  value: "recover",
2086
- label: "Recover a lost API key (handle + email OTP)",
1638
+ label: "Recover a lost API key (email code)",
2087
1639
  hint: "an agent exists but its key is gone \u2014 re-issue it"
2088
1640
  }
2089
1641
  ],
2090
1642
  initialValue: "register"
2091
1643
  });
2092
- if (choice === "paste") {
2093
- return;
2094
- }
2095
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
2096
- const recover = async () => {
2097
- try {
2098
- const result = await runRecoverFlow({ cfg, accountId, prompter, apiBase });
2099
- if (result === "abort") {
2100
- await prompter.note(
2101
- "Recovery was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
2102
- "Falling back to credential entry"
2103
- );
2104
- return;
2105
- }
2106
- return result;
2107
- } catch (err) {
2108
- if (err instanceof setup.WizardCancelledError) throw err;
2109
- await prompter.note(
2110
- `${err instanceof Error ? err.message : String(err)}`,
2111
- "Recovery flow failed"
2112
- );
2113
- return;
2114
- }
2115
- };
2116
- if (choice === "recover") {
2117
- return await recover();
2118
- }
2119
- let registerOutcome;
2120
- try {
2121
- registerOutcome = await runRegisterFlow({ cfg, accountId, prompter, apiBase });
2122
- } catch (err) {
2123
- if (err instanceof setup.WizardCancelledError) throw err;
2124
- await prompter.note(
2125
- `${err instanceof Error ? err.message : String(err)}`,
2126
- "Registration flow failed"
2127
- );
2128
- return;
2129
- }
2130
- if (registerOutcome === "abort") {
2131
- await prompter.note(
2132
- "Registration was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
2133
- "Falling back to credential entry"
2134
- );
2135
- return;
2136
- }
2137
- if (registerOutcome === "user-chose-paste") {
2138
- return;
2139
- }
2140
- if (registerOutcome === "user-chose-recover") {
2141
- return await recover();
2142
- }
2143
- return registerOutcome;
1644
+ if (choice === "paste") return;
1645
+ return await runAccountFlow({ kind: choice, cfg, accountId, prompter });
2144
1646
  },
2145
1647
  credentials: [
2146
1648
  {
@@ -2153,9 +1655,9 @@ var agentchatSetupWizard = {
2153
1655
  inputPrompt: "Paste your AgentChat API key (ac_\u2026)",
2154
1656
  helpTitle: "AgentChat API key",
2155
1657
  helpLines: [
2156
- "Format: ac_ followed by 43 base64url characters. Validated against",
2157
- "GET /v1/agents/me during this wizard \u2014 bad keys fail fast instead",
2158
- "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."
2159
1661
  ],
2160
1662
  allowEnv: () => true,
2161
1663
  shouldPrompt: ({ credentialValues, currentValue }) => {
@@ -2173,61 +1675,67 @@ var agentchatSetupWizard = {
2173
1675
  resolvedValue: configured ? apiKey : void 0,
2174
1676
  envValue
2175
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;
2176
1684
  }
2177
1685
  }
2178
1686
  ],
2179
1687
  finalize: async ({ cfg, accountId, credentialValues, prompter }) => {
2180
- const apiKey = typeof credentialValues.token === "string" && credentialValues.token.length >= MIN_API_KEY_LENGTH ? credentialValues.token : readAgentchatConfigField(cfg, accountId, "apiKey");
2181
- if (!apiKey || !isApiKeyPresent(apiKey)) {
2182
- return;
2183
- }
1688
+ const stored = nonEmpty2(readAgentchatConfigField(cfg, accountId, "apiKey"));
1689
+ const apiKey = nonEmpty2(credentialValues.token) ?? stored;
1690
+ if (!apiKey) return;
2184
1691
  const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
2185
- 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;
2186
1694
  try {
2187
- const result = await validateApiKey(apiKey, { apiBase });
2188
- if (result.ok) {
2189
- spinner.stop(`Authenticated as @${result.agent.handle}`);
2190
- const handle = result.agent.handle;
2191
- const resolvedBase = apiBase ?? DEFAULT_API_BASE2;
2192
- const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
2193
- const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
2194
- const failed = placed.steps.filter((s) => s.status === "failed");
2195
- const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
2196
- await prompter.note(
2197
- [
2198
- ...formatPlacement(placed.steps),
2199
- "",
2200
- 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.",
2201
- ...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."] : [],
2202
- ...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
2203
- ].join("\n"),
2204
- "AgentChat integration placed"
2205
- );
2206
- const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
2207
- return { cfg: applied.cfg };
2208
- }
2209
- 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");
2210
1698
  await prompter.note(
2211
1699
  [
2212
- result.message,
1700
+ err instanceof Error ? err.message : String(err),
2213
1701
  "",
2214
- "The config was saved \u2014 you can re-run `openclaw channels add agentchat`",
2215
- "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."
2216
1703
  ].join("\n"),
2217
- "AgentChat validation warning"
1704
+ "AgentChat API unreachable"
2218
1705
  );
2219
- } catch (err) {
2220
- 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");
2221
1710
  await prompter.note(
2222
1711
  [
2223
- err instanceof Error ? err.message : String(err),
1712
+ check.message,
2224
1713
  "",
2225
- "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."
2226
1715
  ].join("\n"),
2227
- "AgentChat API unreachable"
1716
+ "AgentChat API key not accepted"
2228
1717
  );
1718
+ return;
2229
1719
  }
2230
- 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 };
2231
1739
  },
2232
1740
  completionNote: {
2233
1741
  title: "AgentChat is ready",
@@ -3842,7 +3350,7 @@ var agentchatStatusAdapter = {
3842
3350
  const servedFrom = live?.texts?.source;
3843
3351
  const textsSource = live ? servedFrom === "server" || servedFrom === "cache" ? servedFrom : "missing" : void 0;
3844
3352
  const socketCounters = live?.metrics?.snapshot?.();
3845
- const integration6 = {
3353
+ const integration8 = {
3846
3354
  mode: readEnv_js.readWakeModeFromEnv().mode,
3847
3355
  ...health ? { state: health.state } : {},
3848
3356
  ...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
@@ -3859,7 +3367,7 @@ var agentchatStatusAdapter = {
3859
3367
  pausedByOwner: me.paused_by_owner ?? "none",
3860
3368
  mcp,
3861
3369
  placement,
3862
- integration: integration6,
3370
+ integration: integration8,
3863
3371
  ...refusal ? { refusal } : {},
3864
3372
  ...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
3865
3373
  };
@@ -3926,7 +3434,7 @@ var agentchatDoctorAdapter = {
3926
3434
  continue;
3927
3435
  }
3928
3436
  const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
3929
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3437
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3930
3438
  const handle = readAgentchatConfigField(cfg, accountId, "agentHandle");
3931
3439
  const agentId = resolvePlacementAgentId(cfg, accountId);
3932
3440
  for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {
@@ -3965,16 +3473,16 @@ var agentchatDoctorAdapter = {
3965
3473
  for (const accountId of listConfiguredAccountIds(cfg)) {
3966
3474
  if (!isAgentchatAccountEnabled(cfg, accountId)) continue;
3967
3475
  const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
3968
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3476
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3969
3477
  bases.set(apiBase, apiKey);
3970
3478
  if (apiKey && !readAgentchatConfigField(cfg, accountId, "agentHandle")) {
3971
3479
  try {
3972
- const result = await validateApiKey(apiKey, { apiBase });
3480
+ const result = await checkApiKey(apiKey, { apiBase });
3973
3481
  if (result.ok) {
3974
- next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.agent.handle });
3975
- 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}`);
3976
3484
  } else {
3977
- 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}`);
3978
3486
  }
3979
3487
  } catch (err) {
3980
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)}`);
@@ -4029,7 +3537,7 @@ var uiHints = {
4029
3537
  label: "AgentChat API key",
4030
3538
  placeholder: "ac_\u2026",
4031
3539
  sensitive: true,
4032
- 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."
4033
3541
  },
4034
3542
  apiBase: {
4035
3543
  label: "API base URL",
@@ -4040,19 +3548,26 @@ var uiHints = {
4040
3548
  agentHandle: {
4041
3549
  label: "Agent handle",
4042
3550
  placeholder: "my-agent",
4043
- 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."
4044
3552
  },
4045
3553
  reconnect: { label: "Reconnect backoff", advanced: true },
4046
3554
  ping: { label: "WebSocket ping cadence", advanced: true },
4047
3555
  outbound: { label: "Outbound send tuning", advanced: true },
4048
3556
  observability: { label: "Logs & metrics", advanced: true }
4049
3557
  };
4050
- var HANDLE_SHAPE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
4051
- function validHandle(value) {
3558
+ function handleOf(value) {
4052
3559
  if (typeof value !== "string") return void 0;
4053
3560
  const bare = value.trim().replace(/^@/, "");
4054
- return bare.length >= 3 && bare.length <= 30 && HANDLE_SHAPE.test(bare) ? bare : void 0;
3561
+ return bare.length > 0 ? bare : void 0;
4055
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");
3568
+ }
3569
+ var keyAskedBeforeWrite = null;
3570
+ var keyDigest = (apiKey) => crypto.createHash("sha256").update(apiKey).digest("hex");
4056
3571
  function say(runtime, level, line) {
4057
3572
  const env = runtime;
4058
3573
  const fn = env?.[level];
@@ -4060,13 +3575,18 @@ function say(runtime, level, line) {
4060
3575
  }
4061
3576
  var agentchatSetupAdapter = {
4062
3577
  /**
4063
- * Pre-write gate: cheap, sync check that the caller supplied an API key
4064
- * that's at least plausibly shaped. Real authentication happens in
4065
- * `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.
4066
3584
  */
4067
3585
  validateInput({ input }) {
3586
+ const refusal = input.keyRefusal;
3587
+ if (typeof refusal === "string" && refusal.length > 0) return refusal;
4068
3588
  if (typeof input.token !== "string" || input.token.trim().length === 0) {
4069
- 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)";
4070
3590
  }
4071
3591
  if (input.token.length < MIN_API_KEY_LENGTH) {
4072
3592
  return `apiKey looks too short (got ${input.token.length} chars, expect \u2265${MIN_API_KEY_LENGTH})`;
@@ -4084,29 +3604,31 @@ var agentchatSetupAdapter = {
4084
3604
  return null;
4085
3605
  },
4086
3606
  /**
4087
- * Learn the handle the key authenticates as BEFORE the write, so
4088
- * `applyAccountConfig` persists it in the same config write OpenClaw
4089
- * already makes. A key that does not validate leaves the input untouched
4090
- * (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.
4091
3612
  */
4092
- async prepareAccountConfigInput({ accountId, input, runtime }) {
3613
+ async prepareAccountConfigInput({ cfg, accountId, input, runtime }) {
4093
3614
  const apiKey = typeof input.token === "string" ? input.token : void 0;
4094
3615
  if (!apiKey || apiKey.length < MIN_API_KEY_LENGTH) return input;
4095
- 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);
4096
3618
  try {
4097
- const result = await validateApiKey(apiKey, { apiBase });
3619
+ const result = await checkApiKey(apiKey, { apiBase });
4098
3620
  if (result.ok) {
4099
- say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.agent.handle} (${result.agent.email})`);
3621
+ say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.handle}`);
4100
3622
  try {
4101
3623
  placeApiKeyInDotEnv(apiKey);
4102
3624
  } catch (err) {
4103
3625
  say(runtime, "error", `[agentchat:${accountId}] could not write AGENTCHAT_API_KEY to ${dotEnvPath()}: ${err instanceof Error ? err.message : String(err)}`);
4104
3626
  }
4105
- return { ...input, agentHandle: result.agent.handle };
3627
+ return { ...input, agentHandle: result.handle };
4106
3628
  }
4107
- say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`);
3629
+ return { ...input, keyRefusal: keyRefusal(result) };
4108
3630
  } catch (err) {
4109
- 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)}`);
4110
3632
  }
4111
3633
  return input;
4112
3634
  },
@@ -4120,12 +3642,12 @@ var agentchatSetupAdapter = {
4120
3642
  const patch = {};
4121
3643
  if (typeof input.token === "string" && input.token.length > 0) patch.apiKey = input.token;
4122
3644
  if (typeof input.url === "string" && input.url.length > 0) patch.apiBase = input.url;
4123
- const handle = validHandle(input.agentHandle);
3645
+ const handle = handleOf(input.agentHandle);
4124
3646
  if (handle) patch.agentHandle = handle;
4125
3647
  const withAccount = applyAgentchatAccountPatch(cfg, accountId, patch);
4126
3648
  const apiKey = readAgentchatConfigField(withAccount, accountId, "apiKey");
4127
3649
  if (!apiKey) return withAccount;
4128
- const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3650
+ const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE;
4129
3651
  return applyIntegrationConfig(withAccount, { accountId, handle, apiKey, apiBase }).cfg;
4130
3652
  },
4131
3653
  /**
@@ -4136,16 +3658,16 @@ var agentchatSetupAdapter = {
4136
3658
  async afterAccountConfigWritten({ cfg, accountId, input, runtime }) {
4137
3659
  const apiKey = typeof input.token === "string" ? input.token : readAgentchatConfigField(cfg, accountId, "apiKey");
4138
3660
  if (!apiKey) return;
4139
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
4140
- 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"));
4141
3663
  if (!handle) {
4142
3664
  try {
4143
- const result = await validateApiKey(apiKey, { apiBase });
3665
+ const result = await checkApiKey(apiKey, { apiBase });
4144
3666
  if (result.ok) {
4145
- handle = result.agent.handle;
3667
+ handle = result.handle;
4146
3668
  say(runtime, "log", `[agentchat:${accountId}] authenticated as @${handle}; run \`openclaw doctor --fix\` to persist channels.agentchat.agentHandle`);
4147
3669
  } else {
4148
- 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}`);
4149
3671
  return;
4150
3672
  }
4151
3673
  } catch (err) {
@@ -4179,8 +3701,24 @@ function accountSectionPersistable(cfg, accountId) {
4179
3701
  if (!raw) return true;
4180
3702
  return agentchatChannelConfigSchema.safeParse(raw).success;
4181
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
+ }
4182
3719
  var agentchatLifecycleAdapter = {
4183
3720
  async onAccountConfigChanged({ prevCfg, nextCfg, accountId, runtime }) {
3721
+ await refuseRejectedKey(prevCfg, nextCfg, accountId, runtime);
4184
3722
  const wasEnabled = isAccountEnabled(prevCfg, accountId);
4185
3723
  const isEnabled = isAccountEnabled(nextCfg, accountId);
4186
3724
  if (wasEnabled === isEnabled) return;
@@ -4196,13 +3734,13 @@ var agentchatLifecycleAdapter = {
4196
3734
  for (const line of removeIntegrationFiles(nextCfg, accountId, { clearKey: false })) say(runtime, "log", `[agentchat:${accountId}] ${line}`);
4197
3735
  return;
4198
3736
  }
4199
- const handle = validHandle(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
3737
+ const handle = handleOf(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
4200
3738
  if (!handle) {
4201
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`);
4202
3740
  return;
4203
3741
  }
4204
3742
  const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
4205
- const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3743
+ const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
4206
3744
  const identityLine = apiKey ? await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId }) : null;
4207
3745
  const restored = restoreIdentityLine(nextCfg, accountId, handle, identityLine);
4208
3746
  if (restored.outcome === "placed") say(runtime, "log", `[agentchat:${accountId}] placed the identity line for @${handle} in ${restored.path}`);
@@ -4365,6 +3903,20 @@ function hasAgentChatConfiguredState(config) {
4365
3903
  return true;
4366
3904
  }
4367
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
+
4368
3920
  exports.AGENTCHAT_CHANNEL_ID = AGENTCHAT_CHANNEL_ID;
4369
3921
  exports.AGENTCHAT_DEFAULT_ACCOUNT_ID = AGENTCHAT_DEFAULT_ACCOUNT_ID;
4370
3922
  exports.AgentChatChannelError = AgentChatChannelError;
@@ -4373,12 +3925,13 @@ exports.MAX_HUNG_TURNS = MAX_HUNG_TURNS;
4373
3925
  exports.MCP_SERVER_NAME = MCP_SERVER_NAME;
4374
3926
  exports.OPENCLAW_TOOL_NAMER = OPENCLAW_TOOL_NAMER;
4375
3927
  exports.OpenClawTexts = OpenClawTexts;
3928
+ exports.accountCallOptions = accountCallOptions;
4376
3929
  exports.accountTurns = accountTurns;
4377
3930
  exports.agentchatChannelEntry = agentchatChannelEntry;
4378
3931
  exports.agentchatPlugin = agentchatPlugin;
4379
3932
  exports.agentchatSetupEntry = agentchatSetupEntry;
4380
3933
  exports.agentchatSetupPlugin = agentchatPlugin;
4381
- exports.assertApiKeyValid = assertApiKeyValid;
3934
+ exports.checkApiKey = checkApiKey;
4382
3935
  exports.createInMemoryMetrics = createInMemoryMetrics;
4383
3936
  exports.createIntegrationLoop = createIntegrationLoop;
4384
3937
  exports.createLoopTurnStarter = createLoopTurnStarter;
@@ -4395,14 +3948,9 @@ exports.mcpToolName = mcpToolName;
4395
3948
  exports.parseChannelConfig = parseChannelConfig;
4396
3949
  exports.probeHostedMcp = probeHostedMcp;
4397
3950
  exports.realtimeOptionsFor = realtimeOptionsFor;
4398
- exports.recoverAgentStart = recoverAgentStart;
4399
- exports.recoverAgentVerify = recoverAgentVerify;
4400
- exports.registerAgentStart = registerAgentStart;
4401
- exports.registerAgentVerify = registerAgentVerify;
4402
3951
  exports.spellTextsForOpenClaw = spellTextsForOpenClaw;
4403
3952
  exports.spellToolsForOpenClaw = spellToolsForOpenClaw;
4404
3953
  exports.trackerFor = trackerFor;
4405
3954
  exports.turnEndOf = turnEndOf;
4406
- exports.validateApiKey = validateApiKey;
4407
3955
  //# sourceMappingURL=index.cjs.map
4408
3956
  //# sourceMappingURL=index.cjs.map