@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.
@@ -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');
@@ -134,7 +135,7 @@ function applyAgentchatAccountPatch(cfg, accountId, patch) {
134
135
  }
135
136
 
136
137
  // src/version.ts
137
- var PACKAGE_VERSION = "0.10.2";
138
+ var PACKAGE_VERSION = "0.11.0";
138
139
 
139
140
  // src/client-identity.ts
140
141
  var AGENTCHAT_CLIENT_NAME = "openclaw";
@@ -143,219 +144,6 @@ var AGENTCHAT_CLIENT_IDENTITY = {
143
144
  version: PACKAGE_VERSION
144
145
  };
145
146
 
146
- // src/setup-client.ts
147
- var DEFAULT_API_BASE = "https://api.agentchat.me";
148
- var DEFAULT_TIMEOUT_MS = 1e4;
149
- async function validateApiKey(apiKey, opts = {}) {
150
- if (!apiKey || typeof apiKey !== "string") {
151
- return { ok: false, reason: "unauthorized", message: "API key is empty" };
152
- }
153
- const client = new agentchatme.AgentChatClient({
154
- apiKey,
155
- baseUrl: apiBaseOf(opts.apiBase),
156
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
157
- timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
158
- retry: ONE_ATTEMPT,
159
- ...opts.fetch ? { fetch: opts.fetch } : {}
160
- });
161
- let me;
162
- try {
163
- me = await client.getMe();
164
- } catch (err) {
165
- const failure = describeFailure(err);
166
- if (failure.kind === "network") {
167
- const unreachable = failure.timedOut || /ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(failure.message);
168
- return {
169
- ok: false,
170
- reason: unreachable ? "unreachable" : "network-error",
171
- message: `agentchat: GET /v1/agents/me failed: ${failure.message}`
172
- };
173
- }
174
- const status = failure.status;
175
- if (status === 401) return { ok: false, reason: "unauthorized", status, message: "API key is invalid or revoked" };
176
- if (status === 403) return { ok: false, reason: "forbidden", status, message: "API key lacks permission to read /agents/me" };
177
- if (status === 410) return { ok: false, reason: "deleted", status, message: "Agent account has been deleted" };
178
- return { ok: false, reason: "server-error", status, message: `AgentChat API returned ${status}` };
179
- }
180
- const body = asRecord(me);
181
- const email = typeof body?.email === "string" ? body.email : typeof body?.email_masked === "string" ? body.email_masked : null;
182
- if (!body || typeof body.handle !== "string" || email === null || typeof body.created_at !== "string") {
183
- return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/me returned an unrecognized shape" };
184
- }
185
- return {
186
- ok: true,
187
- agent: {
188
- handle: body.handle,
189
- displayName: typeof body.display_name === "string" ? body.display_name : null,
190
- email,
191
- createdAt: body.created_at
192
- }
193
- };
194
- }
195
- async function registerAgentStart(input, opts = {}) {
196
- let data;
197
- try {
198
- data = await agentchatme.AgentChatClient.register({
199
- email: input.email,
200
- handle: input.handle,
201
- ...input.displayName !== void 0 ? { display_name: input.displayName } : {},
202
- ...input.description !== void 0 ? { description: input.description } : {},
203
- baseUrl: apiBaseOf(opts.apiBase),
204
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
205
- });
206
- } catch (err) {
207
- const failure = describeFailure(err);
208
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
209
- const { status, code, message } = failure;
210
- if (status === 400 && code === "INVALID_HANDLE") return { ok: false, reason: "invalid-handle", message, status };
211
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
212
- if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
213
- const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
214
- if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
215
- if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
216
- if (status >= 500 || code === "OTP_FAILED") return { ok: false, reason: "otp-failed", message, status };
217
- return { ok: false, reason: "server-error", status, message };
218
- }
219
- const pendingId = asRecord(data)?.pending_id;
220
- if (typeof pendingId !== "string") {
221
- return { ok: false, reason: "server-error", status: 200, message: "AgentChat /register returned no pending_id" };
222
- }
223
- return { ok: true, pendingId };
224
- }
225
- async function registerAgentVerify(input, opts = {}) {
226
- let verified;
227
- try {
228
- verified = await agentchatme.AgentChatClient.verify(input.pendingId, input.code, {
229
- baseUrl: apiBaseOf(opts.apiBase),
230
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
231
- });
232
- } catch (err) {
233
- const failure = describeFailure(err);
234
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
235
- const { status, code, message } = failure;
236
- if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
237
- if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
238
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
239
- if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
240
- const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
241
- if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
242
- if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
243
- return { ok: false, reason: "server-error", status, message };
244
- }
245
- const agent = asRecord(verified.agent);
246
- if (typeof verified.apiKey !== "string" || !agent || typeof agent.handle !== "string" || typeof agent.email !== "string" || typeof agent.created_at !== "string") {
247
- return { ok: false, reason: "unexpected-shape", status: 201, message: "AgentChat /register/verify returned an unrecognized shape" };
248
- }
249
- return {
250
- ok: true,
251
- apiKey: verified.apiKey,
252
- agent: {
253
- handle: agent.handle,
254
- displayName: typeof agent.display_name === "string" ? agent.display_name : null,
255
- email: agent.email,
256
- createdAt: agent.created_at
257
- }
258
- };
259
- }
260
- async function recoverAgentStart(input, opts = {}) {
261
- let data;
262
- try {
263
- data = await agentchatme.AgentChatClient.recover(input.email, {
264
- handle: input.handle,
265
- baseUrl: apiBaseOf(opts.apiBase),
266
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
267
- });
268
- } catch (err) {
269
- const failure = describeFailure(err);
270
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
271
- const { status, code, message: message2 } = failure;
272
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message: message2, status };
273
- if (status === 429) return { ok: false, reason: "rate-limited", message: message2, status, retryAfterSeconds: failure.retryAfterSeconds };
274
- return { ok: false, reason: "server-error", status, message: message2 };
275
- }
276
- const body = asRecord(data);
277
- const message = typeof body?.message === "string" ? body.message : "status 200";
278
- if (typeof body?.pending_id !== "string") {
279
- return {
280
- ok: false,
281
- reason: "unexpected-shape",
282
- status: 200,
283
- message: "AgentChat did not start a recovery (no pending_id in the response). Check that the email is the one this agent registered with."
284
- };
285
- }
286
- return { ok: true, pendingId: body.pending_id, message };
287
- }
288
- async function recoverAgentVerify(input, opts = {}) {
289
- let recovered;
290
- try {
291
- recovered = await agentchatme.AgentChatClient.recoverVerify(input.pendingId, input.code, {
292
- baseUrl: apiBaseOf(opts.apiBase),
293
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
294
- });
295
- } catch (err) {
296
- const failure = describeFailure(err);
297
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
298
- const { status, code, message } = failure;
299
- if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
300
- if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
301
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
302
- if (status === 409 && code === "HANDLE_REQUIRED") {
303
- return { ok: false, reason: "handle-required", message, status, handles: readHandleList(failure.details) };
304
- }
305
- if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
306
- return { ok: false, reason: "server-error", status, message };
307
- }
308
- if (typeof recovered.apiKey !== "string" || typeof recovered.handle !== "string") {
309
- return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/recover/verify returned an unrecognized shape" };
310
- }
311
- return { ok: true, apiKey: recovered.apiKey, handle: recovered.handle };
312
- }
313
- function classifyEmailPolicyRejection(code) {
314
- if (code === "EMAIL_LIMIT_REACHED" || code === "EMAIL_TAKEN") return "email-limit-reached";
315
- if (code === "EMAIL_EXHAUSTED") return "email-exhausted";
316
- return void 0;
317
- }
318
- function readPolicyLimit(details) {
319
- if (!details || typeof details !== "object") return void 0;
320
- const limit = details.limit;
321
- return typeof limit === "number" && Number.isInteger(limit) && limit > 0 ? limit : void 0;
322
- }
323
- function readHandleList(details) {
324
- if (!details || typeof details !== "object") return [];
325
- const handles = details.handles;
326
- if (!Array.isArray(handles)) return [];
327
- return handles.filter((h) => typeof h === "string" && h.length > 0);
328
- }
329
- var ONE_ATTEMPT = { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 };
330
- function apiBaseOf(apiBase) {
331
- return (apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, "");
332
- }
333
- function describeFailure(err) {
334
- if (err instanceof agentchatme.AgentChatError) {
335
- const raw = asRecord(asRecord(err.details)?.body);
336
- const code = typeof raw?.code === "string" ? raw.code : String(err.code ?? "");
337
- const message2 = raw ? typeof raw.message === "string" ? raw.message : `status ${err.status}` : err.message || `status ${err.status}`;
338
- const retryAfterMs = err instanceof agentchatme.RateLimitedError ? err.retryAfterMs : null;
339
- return {
340
- kind: "http",
341
- status: err.status,
342
- code,
343
- message: message2,
344
- details: raw ? raw.details : err.details,
345
- ...typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) ? { retryAfterSeconds: Math.ceil(retryAfterMs / 1e3) } : {}
346
- };
347
- }
348
- const message = err instanceof Error ? err.message : String(err);
349
- const timedOut = err instanceof Error && err.name === "AbortError" || /timed out|abort/i.test(message);
350
- return { kind: "network", message, timedOut };
351
- }
352
- function networkMessage(failure) {
353
- return failure.timedOut ? "request timed out" : failure.message;
354
- }
355
- function asRecord(value) {
356
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
357
- }
358
-
359
147
  // src/integration/turn.ts
360
148
  var MCP_SERVER_NAME = "agentchat";
361
149
  var MCP_TOOL_DELIMITER = "__";
@@ -392,8 +180,8 @@ function sanitizeKeyPart(value) {
392
180
  // src/integration/mcp.ts
393
181
  var MCP_PATH = "/mcp";
394
182
  var AUTH_HEADER_TEMPLATE = `Bearer \${${readEnv_js.API_KEY_ENV}}`;
395
- var DEFAULT_API_BASE2 = "https://api.agentchat.me";
396
- function hostedMcpUrl(apiBase = DEFAULT_API_BASE2) {
183
+ var DEFAULT_API_BASE = "https://api.agentchat.me";
184
+ function hostedMcpUrl(apiBase = DEFAULT_API_BASE) {
397
185
  return `${apiBase.replace(/\/+$/, "")}${MCP_PATH}`;
398
186
  }
399
187
  var CLIENT_HEADER = "X-AgentChat-Client";
@@ -403,14 +191,14 @@ function clientIdentityHeaders() {
403
191
  function clientIdentityText() {
404
192
  return `${CLIENT_HEADER}: ${AGENTCHAT_CLIENT_NAME}`;
405
193
  }
406
- function hostedMcpServerEntry(apiBase = DEFAULT_API_BASE2) {
194
+ function hostedMcpServerEntry(apiBase = DEFAULT_API_BASE) {
407
195
  return {
408
196
  url: hostedMcpUrl(apiBase),
409
197
  transport: "streamable-http",
410
198
  headers: { Authorization: AUTH_HEADER_TEMPLATE, ...clientIdentityHeaders() }
411
199
  };
412
200
  }
413
- function describeMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
201
+ function describeMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
414
202
  const servers = cfg?.mcp?.servers;
415
203
  if (!servers || typeof servers !== "object" || Array.isArray(servers)) return "missing";
416
204
  const entry = servers[MCP_SERVER_NAME];
@@ -443,7 +231,7 @@ function describeMcpIdentity(cfg) {
443
231
  const client = clients[0];
444
232
  return clients.length === 1 && typeof client === "string" && client.trim().toLowerCase() === want[CLIENT_HEADER] ? "current" : "missing";
445
233
  }
446
- function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
234
+ function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
447
235
  const state = describeMcpEntry(cfg, apiBase, apiKey);
448
236
  const base = cfg ?? {};
449
237
  if (state === "user_managed") return { cfg: base, outcome: "user_managed" };
@@ -456,7 +244,7 @@ function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
456
244
  mcp.servers = servers;
457
245
  return { cfg: { ...base, mcp }, outcome: state === "ours" ? "updated" : "added" };
458
246
  }
459
- function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE2) {
247
+ function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE) {
460
248
  const headers = isRecord(entry.headers) ? entry.headers : {};
461
249
  const kept = Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== CLIENT_HEADER.toLowerCase()));
462
250
  return {
@@ -466,7 +254,7 @@ function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE2) {
466
254
  headers: { ...kept, ...clientIdentityHeaders() }
467
255
  };
468
256
  }
469
- function upgradeHostedMcpEntryInPlace(draft, apiBase = DEFAULT_API_BASE2, apiKey) {
257
+ function upgradeHostedMcpEntryInPlace(draft, apiBase = DEFAULT_API_BASE, apiKey) {
470
258
  if (describeMcpEntry(draft, apiBase, apiKey) !== "ours" || describeMcpIdentity(draft) === "current") return false;
471
259
  const servers = draft.mcp.servers;
472
260
  const existing = servers[MCP_SERVER_NAME];
@@ -483,7 +271,7 @@ var NoChange = class extends Error {
483
271
  };
484
272
  var NIX_MODE_ERROR_CODE = "OPENCLAW_NIX_MODE_CONFIG_IMMUTABLE";
485
273
  async function refreshHostedMcpEntry(params) {
486
- const apiBase = params.apiBase ?? DEFAULT_API_BASE2;
274
+ const apiBase = params.apiBase ?? DEFAULT_API_BASE;
487
275
  if (describeMcpEntry(params.liveCfg, apiBase, params.apiKey) !== "ours") return { outcome: "not_ours" };
488
276
  if (describeMcpIdentity(params.liveCfg) === "current") return { outcome: "current" };
489
277
  const mutate = params.config?.mutateConfigFile;
@@ -520,7 +308,7 @@ function headerValues(headers, name) {
520
308
  const wanted = name.toLowerCase();
521
309
  return Object.entries(headers).filter(([key]) => key.toLowerCase() === wanted).map(([, value]) => value);
522
310
  }
523
- function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
311
+ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
524
312
  if (describeMcpEntry(cfg, apiBase, apiKey) !== "ours") return { cfg, removed: false };
525
313
  const mcp = { ...cfg.mcp ?? {} };
526
314
  const servers = { ...mcp.servers ?? {} };
@@ -530,7 +318,7 @@ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
530
318
  }
531
319
  async function probeHostedMcp(params) {
532
320
  const result = await agentchatme.integration.probeHostedTools({
533
- apiBase: params.apiBase ?? DEFAULT_API_BASE2,
321
+ apiBase: params.apiBase ?? DEFAULT_API_BASE,
534
322
  apiKey: params.apiKey,
535
323
  clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
536
324
  ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
@@ -549,6 +337,40 @@ async function probeHostedMcp(params) {
549
337
  };
550
338
  }
551
339
 
340
+ // src/setup-client.ts
341
+ var KEY_CHECK_TIMEOUT_MS = 1e4;
342
+ function accountCallOptions(params = {}) {
343
+ return {
344
+ clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
345
+ apiBase: (params.apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, ""),
346
+ ...params.fetch ? { fetch: params.fetch } : {},
347
+ ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {}
348
+ };
349
+ }
350
+ var KeyCheckUnanswered = class extends Error {
351
+ constructor(message) {
352
+ super(message);
353
+ this.name = "KeyCheckUnanswered";
354
+ }
355
+ };
356
+ async function checkApiKey(apiKey, params = {}) {
357
+ let status;
358
+ const send = params.fetch ?? ((input, init) => globalThis.fetch(input, init));
359
+ const observed = (async (input, init) => {
360
+ const response = await send(input, init);
361
+ status = response.status;
362
+ return response;
363
+ });
364
+ const check = await agentchatme.integration.account.checkKey(
365
+ apiKey,
366
+ accountCallOptions({ timeoutMs: KEY_CHECK_TIMEOUT_MS, ...params, fetch: observed })
367
+ );
368
+ if (!check.ok && status !== 401 && status !== 403) {
369
+ throw new KeyCheckUnanswered(`AgentChat answered ${status ?? "without a status"} (${check.code}): ${check.message}`);
370
+ }
371
+ return check;
372
+ }
373
+
552
374
  // src/integration/runtime-holder.ts
553
375
  var current = null;
554
376
  function isUsablePluginRuntime(runtime) {
@@ -700,14 +522,14 @@ var FAILURE_STATUSES = /* @__PURE__ */ new Set([
700
522
  "invalid"
701
523
  ]);
702
524
  function coversWholeSession(rows) {
703
- if (asRecord2(rows[0]?.__openclaw)?.seq !== 1) return false;
525
+ if (asRecord(rows[0]?.__openclaw)?.seq !== 1) return false;
704
526
  return rows.every((row) => {
705
- const meta = asRecord2(row.__openclaw);
527
+ const meta = asRecord(row.__openclaw);
706
528
  return meta?.kind !== "compaction" && meta?.kind !== "reset" && meta?.truncated !== true;
707
529
  });
708
530
  }
709
531
  function isOtherRun(row, runId) {
710
- const tagged = asRecord2(row.__openclaw)?.runId ?? nestedCallOf(row)?.runId;
532
+ const tagged = asRecord(row.__openclaw)?.runId ?? nestedCallOf(row)?.runId;
711
533
  return typeof tagged === "string" && tagged.trim().length > 0 && tagged.trim() !== runId;
712
534
  }
713
535
  var CODE_MODE_ONLY_TOOL_NAMES = /* @__PURE__ */ new Set(["tool_search_code", "wait"]);
@@ -719,7 +541,7 @@ function codeModeScriptsCompleted(rows, calls) {
719
541
  for (const row of rows) {
720
542
  if ((row.role === "toolResult" || row.role === "tool") && typeof row.toolCallId === "string") results.set(row.toolCallId, row);
721
543
  }
722
- const completed = (row) => row !== void 0 && row.isError !== true && asRecord2(row.details)?.status === "completed";
544
+ const completed = (row) => row !== void 0 && row.isError !== true && asRecord(row.details)?.status === "completed";
723
545
  for (const [id, call] of calls) {
724
546
  if (isCodeModeCall(call) && !completed(results.get(id))) return false;
725
547
  }
@@ -738,7 +560,7 @@ function isShellExecResult(row, calls) {
738
560
  const call = typeof row.toolCallId === "string" ? calls.get(row.toolCallId) : void 0;
739
561
  const args = callArguments(call);
740
562
  if (!args || typeof args.command !== "string" || args.code !== void 0) return false;
741
- const details = asRecord2(row.details);
563
+ const details = asRecord(row.details);
742
564
  if (!details || details.telemetry !== void 0) return false;
743
565
  return details.exitCode !== void 0 || typeof details.durationMs === "number" || typeof details.aggregated === "string";
744
566
  }
@@ -747,7 +569,7 @@ function assistantToolCalls(rows) {
747
569
  for (const row of rows) {
748
570
  if (row.role !== "assistant" || !Array.isArray(row.content)) continue;
749
571
  for (const block of row.content) {
750
- const call = asRecord2(block);
572
+ const call = asRecord(block);
751
573
  if (call?.type === "toolCall" && typeof call.id === "string") calls.set(call.id, call);
752
574
  }
753
575
  }
@@ -760,7 +582,7 @@ function releaseOf(rows, calls, nested, version) {
760
582
  return { recordsNestedCalls: trusted, marksFailedRows: trusted };
761
583
  }
762
584
  const parents = new Set(nested.map((call) => call.parentToolCallId));
763
- 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));
585
+ 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));
764
586
  return { recordsNestedCalls: nested.length > 0 || dispatchAction, marksFailedRows: dispatchAction };
765
587
  }
766
588
  var OPENCLAW_VERSION = /^(\d+)\.(\d+)\.(\d+)(-.+)?$/;
@@ -786,13 +608,13 @@ function toolNameOf(row) {
786
608
  var NESTED_TOOL_ACTIVITY = "openclaw.nested-tool.v1";
787
609
  function nestedCallOf(row) {
788
610
  if (row.role !== "custom" || row.customType !== NESTED_TOOL_ACTIVITY) return null;
789
- return asRecord2(row.details);
611
+ return asRecord(row.details);
790
612
  }
791
613
  function nestedVerdict(call) {
792
614
  const toolName = typeof call.toolName === "string" ? call.toolName : "";
793
615
  if (!toolName.startsWith(TOOL_PREFIX)) return "not_agentchat";
794
- const result = asRecord2(call.result);
795
- if (call.isError === true || result !== null && failedResult(result.isError, asRecord2(result.details))) return "failed";
616
+ const result = asRecord(call.result);
617
+ if (call.isError === true || result !== null && failedResult(result.isError, asRecord(result.details))) return "failed";
796
618
  return call.isError === false ? "ok" : "unknown";
797
619
  }
798
620
  var OTHER_SESSION_TOOLS = /* @__PURE__ */ new Set(["sessions_spawn", "sessions_send"]);
@@ -803,13 +625,13 @@ function delegatedToChild(rows, calls, nested) {
803
625
  if (typeof call.name === "string" && DISPATCHER_TOOL_NAMES.has(call.name) && names(dispatchTarget(call))) return true;
804
626
  }
805
627
  if (nested.some((call) => names(call.toolName))) return true;
806
- return rows.some((row) => names(toolNameOf(row)) || names(asRecord2(asRecord2(row.details)?.tool)?.name));
628
+ return rows.some((row) => names(toolNameOf(row)) || names(asRecord(asRecord(row.details)?.tool)?.name));
807
629
  }
808
630
  function callVerdict(message, calls, release) {
809
631
  const toolName = toolNameOf(message);
810
- const details = asRecord2(message.details);
632
+ const details = asRecord(message.details);
811
633
  if (toolName.startsWith(TOOL_PREFIX)) return directVerdict(message.isError, details);
812
- const entry = asRecord2(details?.tool);
634
+ const entry = asRecord(details?.tool);
813
635
  if (entry && isAgentChatEntry(entry)) return dispatchedVerdict(message.isError, details);
814
636
  if (!DISPATCHER_TOOL_NAMES.has(toolName) || entry) return "not_agentchat";
815
637
  const target = dispatchTarget(typeof message.toolCallId === "string" ? calls.get(message.toolCallId) : void 0);
@@ -833,10 +655,10 @@ function wasHostedResult(details) {
833
655
  return keys.includes("mcpServer") && (keys.includes("mcpTool") || keys.includes("mcpOperation"));
834
656
  }
835
657
  function dispatchedVerdict(isError, details) {
836
- const result = asRecord2(details?.result);
658
+ const result = asRecord(details?.result);
837
659
  if (failedResult(isError, details)) return "failed";
838
- if (result && failedResult(result.isError, asRecord2(result.details))) return "failed";
839
- const ok = isError === false && details?.status === void 0 && isHostedSuccessDetails(asRecord2(result?.details));
660
+ if (result && failedResult(result.isError, asRecord(result.details))) return "failed";
661
+ const ok = isError === false && details?.status === void 0 && isHostedSuccessDetails(asRecord(result?.details));
840
662
  return ok ? "ok" : "unknown";
841
663
  }
842
664
  function failedResult(isError, details) {
@@ -860,7 +682,7 @@ function isHostedSuccessDetails(details) {
860
682
  function isAgentChatEntry(tool) {
861
683
  if (typeof tool.name === "string" && tool.name.startsWith(TOOL_PREFIX)) return true;
862
684
  if (tool.sourceName === MCP_SERVER_NAME) return true;
863
- const mcp = asRecord2(tool.mcp);
685
+ const mcp = asRecord(tool.mcp);
864
686
  return mcp?.serverName === MCP_SERVER_NAME;
865
687
  }
866
688
  function dispatchTarget(call) {
@@ -880,16 +702,16 @@ function callArguments(call) {
880
702
  return null;
881
703
  }
882
704
  }
883
- return asRecord2(args);
705
+ return asRecord(args);
884
706
  }
885
707
  function unwrapMessage(row) {
886
- const record = asRecord2(row);
708
+ const record = asRecord(row);
887
709
  if (!record) return null;
888
710
  if (typeof record.role === "string") return record;
889
- const inner = asRecord2(record.message);
711
+ const inner = asRecord(record.message);
890
712
  return inner && typeof inner.role === "string" ? inner : null;
891
713
  }
892
- function asRecord2(value) {
714
+ function asRecord(value) {
893
715
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
894
716
  }
895
717
  function nonEmpty(value) {
@@ -1145,7 +967,7 @@ function applyIntegrationConfig(cfg, params) {
1145
967
  const changes = [];
1146
968
  let next = cfg;
1147
969
  const bareHandle = (params.handle ?? "").trim().replace(/^@/, "");
1148
- if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle && isValidHandleShape(bareHandle)) {
970
+ if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle) {
1149
971
  next = applyAgentchatAccountPatch(next, params.accountId, { agentHandle: bareHandle });
1150
972
  changes.push(`channels.agentchat${params.accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID ? "" : `.accounts.${params.accountId}`}.agentHandle = ${bareHandle}`);
1151
973
  }
@@ -1480,57 +1302,15 @@ function getClient({ accountId, config, options }) {
1480
1302
 
1481
1303
  // src/channel.wizard.ts
1482
1304
  var JUST_REGISTERED_SENTINEL = "_agentchatJustRegistered";
1483
- var HANDLE_PATTERN2 = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
1484
- var HANDLE_MIN_LENGTH = 3;
1485
- var HANDLE_MAX_LENGTH = 30;
1486
- var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1487
- function isValidHandleShape2(value) {
1488
- return value.length >= HANDLE_MIN_LENGTH && value.length <= HANDLE_MAX_LENGTH && HANDLE_PATTERN2.test(value);
1489
- }
1490
- var OTP_PATTERN = /^\d{6}$/;
1305
+ var LABELS = {
1306
+ ...agentchatme.integration.account.DEFAULT_LABELS,
1307
+ handle: "Handle (your @name on AgentChat)"
1308
+ };
1491
1309
  function hasConfiguredKey(cfg, accountId) {
1492
1310
  return isApiKeyPresent(readAgentchatConfigField(cfg, accountId, "apiKey"));
1493
1311
  }
1494
- var MAX_START_RETRIES = 5;
1495
- async function promptEmail(prompter, opts = {}) {
1496
- return (await prompter.text({
1497
- message: opts.message ?? "Email \u2014 receives a 6-digit verification code",
1498
- placeholder: "you@example.com",
1499
- validate: (value) => {
1500
- const trimmed = value.trim();
1501
- if (!trimmed) return "Email is required";
1502
- if (!EMAIL_PATTERN.test(trimmed)) return "Not a valid email format";
1503
- return void 0;
1504
- }
1505
- })).trim();
1506
- }
1507
- async function promptHandle(prompter, opts = {}) {
1508
- return (await prompter.text({
1509
- message: opts.message ?? "Choose a handle (your @name on AgentChat)",
1510
- placeholder: "3\u201330 chars, lowercase a-z, 0-9, hyphens, starts with a letter",
1511
- ...opts.initialValue ? { initialValue: opts.initialValue } : {},
1512
- validate: (value) => {
1513
- const trimmed = value.trim();
1514
- if (!trimmed) return "Handle is required";
1515
- if (trimmed.length < HANDLE_MIN_LENGTH || trimmed.length > HANDLE_MAX_LENGTH) {
1516
- return `Length must be ${HANDLE_MIN_LENGTH}\u2013${HANDLE_MAX_LENGTH} chars (you entered ${trimmed.length})`;
1517
- }
1518
- if (!/^[a-z]/.test(trimmed)) return "Must start with a lowercase letter";
1519
- if (/[^a-z0-9-]/.test(trimmed)) {
1520
- return "Only lowercase letters, digits, and hyphens \u2014 no underscores, dots, or symbols";
1521
- }
1522
- if (trimmed.includes("--")) return "No consecutive hyphens";
1523
- if (trimmed.endsWith("-")) return "Cannot end with a hyphen";
1524
- return void 0;
1525
- }
1526
- })).trim();
1527
- }
1528
- async function promptDisplayName(prompter) {
1529
- return (await prompter.text({
1530
- message: "Display name (shown next to your @handle)",
1531
- placeholder: "e.g. Anton, Builder Bot, Sasha",
1532
- validate: () => void 0
1533
- })).trim();
1312
+ function nonEmpty2(value) {
1313
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
1534
1314
  }
1535
1315
  async function runChangeApiBaseFlow(params) {
1536
1316
  const { cfg, accountId, prompter } = params;
@@ -1568,388 +1348,182 @@ async function runChangeApiBaseFlow(params) {
1568
1348
  await prompter.note(`API base set to ${input}`, "Updated");
1569
1349
  return { cfg: patched };
1570
1350
  }
1571
- function describeEmailPolicyRejection(email, result) {
1572
- if (result.limit === void 0) return result.message;
1573
- 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.`;
1574
- }
1575
- async function promptEmailPolicyChoice(prompter, email, result) {
1576
- return prompter.select({
1577
- message: `${describeEmailPolicyRejection(email, result)} What next?`,
1578
- options: [
1579
- {
1580
- value: "retry",
1581
- label: "Use a different email address",
1582
- hint: "a +alias like you+agent2@example.com counts as a separate email"
1583
- },
1584
- {
1585
- value: "recover",
1586
- label: "Recover the API key of an agent this email already backs",
1587
- hint: "needs that agent\u2019s handle \u2014 a code goes to this email"
1588
- },
1589
- { value: "paste", label: "Paste a key from an existing agent" },
1590
- { value: "cancel", label: "Cancel registration" }
1591
- ],
1592
- initialValue: "retry"
1593
- });
1351
+ async function askText(prompter, message, opts = {}) {
1352
+ return (await prompter.text({
1353
+ message,
1354
+ ...opts,
1355
+ validate: (value) => value.trim() ? void 0 : "Required"
1356
+ })).trim();
1594
1357
  }
1595
- async function runRegisterFlow(params) {
1596
- const { cfg, accountId, prompter, apiBase } = params;
1597
- await prompter.note(
1598
- [
1599
- "Registration mints a new AgentChat agent identity tied to your email.",
1600
- "One email can back several agents (the server enforces the limit);",
1601
- "each one registers and verifies separately.",
1602
- "You will receive a 6-digit code to verify \u2014 check your inbox (and spam)."
1603
- ].join("\n"),
1604
- "AgentChat: register a new agent"
1605
- );
1606
- let email = await promptEmail(prompter);
1607
- let handle = await promptHandle(prompter);
1608
- const displayName = await promptDisplayName(prompter);
1609
- let startResult;
1610
- let startedOk = false;
1611
- for (let attempt = 1; attempt <= MAX_START_RETRIES; attempt += 1) {
1612
- const startSpinner = prompter.progress(
1613
- attempt === 1 ? "Sending verification code\u2026" : "Retrying\u2026"
1614
- );
1615
- try {
1616
- startResult = await registerAgentStart(
1617
- {
1618
- email,
1619
- handle,
1620
- ...displayName ? { displayName } : {}
1621
- },
1622
- { apiBase }
1623
- );
1624
- } catch (err) {
1625
- startSpinner.stop("Could not reach AgentChat");
1626
- await prompter.note(
1627
- `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
1628
- "Registration failed"
1629
- );
1630
- return "abort";
1631
- }
1632
- if (startResult.ok) {
1633
- startSpinner.stop(`Verification code sent to ${email}`);
1634
- startedOk = true;
1635
- break;
1636
- }
1637
- startSpinner.stop("Registration rejected");
1638
- switch (startResult.reason) {
1639
- case "invalid-handle":
1640
- case "handle-taken": {
1641
- 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).";
1642
- await prompter.note(`${detail} Pick a different handle and we'll try again.`, "Pick a different handle");
1643
- handle = await promptHandle(prompter);
1644
- continue;
1645
- }
1646
- case "email-limit-reached":
1647
- case "email-exhausted": {
1648
- const choice = await promptEmailPolicyChoice(prompter, email, {
1649
- reason: startResult.reason,
1650
- limit: startResult.limit,
1651
- message: startResult.message
1652
- });
1653
- if (choice === "paste") return "user-chose-paste";
1654
- if (choice === "recover") return "user-chose-recover";
1655
- if (choice === "cancel") return "abort";
1656
- email = await promptEmail(prompter);
1657
- continue;
1658
- }
1659
- case "rate-limited": {
1660
- const wait = startResult.retryAfterSeconds ? ` Try again in ${startResult.retryAfterSeconds}s.` : "";
1661
- await prompter.note(`Too many registration attempts.${wait}`, "Rate limited");
1662
- return "abort";
1663
- }
1664
- case "otp-failed": {
1665
- await prompter.note(
1666
- "The verification-code email could not be sent. Try again in a minute, or paste an existing key instead.",
1667
- "OTP delivery failed"
1668
- );
1669
- return "abort";
1670
- }
1671
- case "network-error":
1672
- case "server-error":
1673
- case "validation":
1674
- default: {
1675
- await prompter.note(describeRegisterStartError(startResult), "Could not start registration");
1676
- return "abort";
1677
- }
1358
+ var EMAIL_PLACEHOLDER = "you@example.com";
1359
+ async function askCode(prompter, label) {
1360
+ for (; ; ) {
1361
+ const code = (await prompter.text({ message: label, placeholder: "leave blank for a new code or to cancel" })).trim();
1362
+ if (code) return { answer: "value", value: code };
1363
+ const choice = await prompter.select({
1364
+ message: "What would you like to do?",
1365
+ options: [
1366
+ { value: "new_code", label: "Send a new code" },
1367
+ { value: "enter", label: "Enter the code" },
1368
+ { value: "cancel", label: "Cancel", hint: "paste an existing key instead, or leave setup" }
1369
+ ],
1370
+ initialValue: "new_code"
1371
+ });
1372
+ if (choice === "new_code") return { answer: "new_code" };
1373
+ if (choice === "cancel") return { answer: "cancel" };
1374
+ }
1375
+ }
1376
+ function askThrough(prompter) {
1377
+ return async (question) => {
1378
+ if (question.field === "new_code") {
1379
+ const yes = await prompter.confirm({ message: "Send a new code?", initialValue: true });
1380
+ return yes ? { answer: "new_code" } : { answer: "cancel" };
1381
+ }
1382
+ if (question.field === "code") return askCode(prompter, question.label ?? LABELS.code);
1383
+ const label = question.label ?? LABELS[question.field];
1384
+ const handles = (question.handles ?? []).filter((handle) => handle.length > 0);
1385
+ if (handles.length > 0) {
1386
+ const picked = await prompter.select({
1387
+ message: label,
1388
+ options: [
1389
+ ...handles.map((handle) => ({ value: handle, label: `@${handle}` })),
1390
+ { value: "", label: "Another handle" }
1391
+ ]
1392
+ });
1393
+ if (picked) return { answer: "value", value: picked };
1678
1394
  }
1679
- }
1680
- if (!startedOk || !startResult || !startResult.ok) {
1681
- await prompter.note(
1682
- "Too many attempts. Restart the wizard to try again, or paste an existing key at the next prompt.",
1683
- "Registration failed"
1684
- );
1685
- return "abort";
1686
- }
1687
- const maxCodeAttempts = 3;
1688
- let verifyResult = null;
1689
- for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
1690
- const code = (await prompter.text({
1691
- message: attempt === 1 ? "Enter the 6-digit verification code from your email" : `Verification code (attempt ${attempt}/${maxCodeAttempts})`,
1692
- placeholder: "123456",
1693
- validate: (value) => {
1694
- const trimmed = value.trim();
1695
- if (!trimmed) return "Code is required";
1696
- if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
1697
- return void 0;
1698
- }
1699
- })).trim();
1700
- const verifySpinner = prompter.progress("Verifying code\u2026");
1395
+ const typed = await askText(prompter, label, question.field === "email" ? { placeholder: EMAIL_PLACEHOLDER } : {});
1396
+ return { answer: "value", value: typed };
1397
+ };
1398
+ }
1399
+ function fetchWithProgress(prompter) {
1400
+ return (async (input, init) => {
1401
+ const progress = prompter.progress("Contacting AgentChat\u2026");
1701
1402
  try {
1702
- verifyResult = await registerAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
1703
- } catch (err) {
1704
- verifySpinner.stop("Could not reach AgentChat");
1705
- await prompter.note(
1706
- `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
1707
- "Verification failed"
1708
- );
1709
- return "abort";
1710
- }
1711
- if (verifyResult.ok) {
1712
- verifySpinner.stop(`Registered as @${verifyResult.agent.handle}`);
1713
- break;
1714
- }
1715
- verifySpinner.stop("Verification failed");
1716
- if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
1717
- await prompter.note(
1718
- "That code did not match. Check your email and try again.",
1719
- "Invalid verification code"
1720
- );
1721
- continue;
1403
+ return await globalThis.fetch(input, init);
1404
+ } finally {
1405
+ progress.stop();
1722
1406
  }
1723
- await prompter.note(describeRegisterVerifyError(verifyResult), "Registration failed");
1724
- return "abort";
1725
- }
1726
- if (!verifyResult || !verifyResult.ok) {
1727
- await prompter.note(
1728
- "Too many incorrect codes. Restart the wizard to receive a new code.",
1729
- "Registration failed"
1730
- );
1731
- return "abort";
1732
- }
1733
- const patch = { apiKey: verifyResult.apiKey };
1734
- if (isValidHandleShape2(verifyResult.agent.handle)) {
1735
- patch.agentHandle = verifyResult.agent.handle;
1736
- }
1737
- const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch);
1407
+ });
1408
+ }
1409
+ function sleepWithProgress(prompter) {
1410
+ const label = (seconds) => `Waiting ${seconds} s\u2026`;
1411
+ return (ms) => new Promise((resolve) => {
1412
+ let left = Math.ceil(ms / 1e3);
1413
+ const progress = prompter.progress(label(left));
1414
+ const tick = setInterval(() => {
1415
+ left -= 1;
1416
+ if (left > 0) progress.update(label(left));
1417
+ }, 1e3);
1418
+ setTimeout(() => {
1419
+ clearInterval(tick);
1420
+ progress.stop();
1421
+ resolve();
1422
+ }, ms);
1423
+ });
1424
+ }
1425
+ async function registerInput(prompter) {
1738
1426
  await prompter.note(
1739
1427
  [
1740
- `Handle: @${verifyResult.agent.handle}`,
1741
- `Email: ${verifyResult.agent.email}`,
1742
- `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`
1428
+ "Registration creates a new AgentChat agent tied to your email address.",
1429
+ "Your handle is the agent\u2019s @name on AgentChat. AgentChat emails you a",
1430
+ "code to confirm the address \u2014 check your inbox (and spam)."
1743
1431
  ].join("\n"),
1744
- "AgentChat account created"
1432
+ "AgentChat: register a new agent"
1745
1433
  );
1746
- return {
1747
- cfg: nextCfg,
1748
- credentialValues: {
1749
- token: verifyResult.apiKey,
1750
- [JUST_REGISTERED_SENTINEL]: "1"
1751
- }
1752
- };
1753
- }
1754
- function describeRegisterStartError(result) {
1755
- switch (result.reason) {
1756
- case "invalid-handle":
1757
- return "That handle is not acceptable. Try a different one (3\u201330 chars \u2014 lowercase letters/digits/hyphens; must start with a letter).";
1758
- case "handle-taken":
1759
- return "That handle is already taken. Try a different one.";
1760
- case "email-limit-reached":
1761
- 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.`;
1762
- case "email-exhausted":
1763
- 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.`;
1764
- case "rate-limited": {
1765
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1766
- return `Rate limited.${wait}`;
1767
- }
1768
- case "otp-failed":
1769
- return "The verification-code email could not be sent. Try again in a minute.";
1770
- case "network-error":
1771
- case "server-error":
1772
- case "validation":
1773
- default:
1774
- return result.message;
1775
- }
1776
- }
1777
- function describeRegisterVerifyError(result) {
1778
- switch (result.reason) {
1779
- case "expired":
1780
- return "This code expired. Restart the wizard to receive a new one.";
1781
- case "invalid-code":
1782
- return "Too many incorrect codes. Restart the wizard to receive a new one.";
1783
- case "handle-taken":
1784
- return "Your chosen handle was claimed by another registration in the meantime. Restart with a different handle.";
1785
- case "email-limit-reached":
1786
- 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.`;
1787
- case "email-exhausted":
1788
- 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.`;
1789
- case "rate-limited": {
1790
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1791
- return `Rate limited.${wait}`;
1792
- }
1793
- case "network-error":
1794
- case "server-error":
1795
- case "unexpected-shape":
1796
- case "validation":
1797
- default:
1798
- return result.message;
1799
- }
1434
+ const email = await askText(prompter, LABELS.email, { placeholder: EMAIL_PLACEHOLDER });
1435
+ const handle = await askText(prompter, LABELS.handle);
1436
+ const displayName = (await prompter.text({
1437
+ message: "Display name (shown next to your @handle)",
1438
+ placeholder: "e.g. Anton, Builder Bot, Sasha"
1439
+ })).trim();
1440
+ return { email, handle, ...displayName ? { display_name: displayName } : {} };
1800
1441
  }
1801
- async function runRecoverFlow(params) {
1802
- const { cfg, accountId, prompter, apiBase } = params;
1803
- const storedHandle = readAgentchatConfigField(cfg, accountId, "agentHandle");
1804
- const defaultHandle = storedHandle && isValidHandleShape2(storedHandle) ? storedHandle : void 0;
1442
+ async function recoverInput(prompter, configuredHandle) {
1805
1443
  await prompter.note(
1806
1444
  [
1807
- "Recovery re-issues the API key for ONE agent \u2014 the handle you name below.",
1808
- "You need that handle and the email it registered with; a 6-digit code",
1809
- "goes to that email. The old key stops working the moment the new one",
1810
- "is minted.",
1811
- ...defaultHandle ? ["", `@${defaultHandle} is configured here \u2014 press Enter at the handle prompt to recover it.`] : []
1445
+ "Recovery issues a new API key for an agent you registered. AgentChat",
1446
+ "emails a code to the address the agent registered with; the old key",
1447
+ "stops working once the new one is issued.",
1448
+ ...configuredHandle ? ["", `@${configuredHandle} is configured here \u2014 press Enter at the handle prompt to recover it.`] : []
1812
1449
  ].join("\n"),
1813
1450
  "AgentChat: recover a lost API key"
1814
1451
  );
1815
- const handle = await promptHandle(prompter, {
1816
- message: "Handle of the agent to recover (its @name on AgentChat)",
1817
- ...defaultHandle ? { initialValue: defaultHandle } : {}
1818
- });
1819
- const email = await promptEmail(prompter, {
1820
- message: `Email @${handle} registered with \u2014 receives a 6-digit recovery code`
1821
- });
1822
- const startSpinner = prompter.progress("Requesting recovery code\u2026");
1823
- let startResult;
1452
+ if (!configuredHandle) return {};
1453
+ const handle = (await prompter.text({ message: LABELS.handle, initialValue: configuredHandle })).trim();
1454
+ return handle ? { handle } : {};
1455
+ }
1456
+ async function notCompleted(prompter, kind) {
1457
+ await prompter.note(
1458
+ `${kind === "register" ? "Registration" : "Recovery"} was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.`,
1459
+ "Falling back to credential entry"
1460
+ );
1461
+ return void 0;
1462
+ }
1463
+ async function runAccountFlow(params) {
1464
+ const { kind, cfg, accountId, prompter } = params;
1465
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1466
+ const input = kind === "register" ? await registerInput(prompter) : await recoverInput(prompter, nonEmpty2(readAgentchatConfigField(cfg, accountId, "agentHandle")));
1467
+ let result;
1824
1468
  try {
1825
- startResult = await recoverAgentStart({ email, handle }, { apiBase });
1469
+ result = await agentchatme.integration.account.run({
1470
+ kind,
1471
+ input,
1472
+ labels: LABELS,
1473
+ ask: askThrough(prompter),
1474
+ show: (message) => prompter.note(message, "AgentChat"),
1475
+ sleep: sleepWithProgress(prompter),
1476
+ ...accountCallOptions({ apiBase, fetch: fetchWithProgress(prompter) })
1477
+ });
1826
1478
  } catch (err) {
1827
- startSpinner.stop("Could not reach AgentChat");
1828
- await prompter.note(
1829
- `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
1830
- "Recovery failed"
1831
- );
1832
- return "abort";
1833
- }
1834
- if (!startResult.ok) {
1835
- startSpinner.stop("Recovery rejected");
1836
- await prompter.note(describeRecoverStartError(startResult), "Could not start recovery");
1837
- return "abort";
1838
- }
1839
- startSpinner.stop(startResult.message);
1840
- const maxCodeAttempts = 3;
1841
- let verifyResult = null;
1842
- for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
1843
- const code = (await prompter.text({
1844
- message: attempt === 1 ? `Enter the 6-digit recovery code (check ${email}, including spam)` : `Recovery code (attempt ${attempt}/${maxCodeAttempts})`,
1845
- placeholder: "123456",
1846
- validate: (value) => {
1847
- const trimmed = value.trim();
1848
- if (!trimmed) return "Code is required";
1849
- if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
1850
- return void 0;
1851
- }
1852
- })).trim();
1853
- const verifySpinner = prompter.progress("Verifying code\u2026");
1854
- try {
1855
- verifyResult = await recoverAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
1856
- } catch (err) {
1857
- verifySpinner.stop("Could not reach AgentChat");
1858
- await prompter.note(
1859
- `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
1860
- "Recovery failed"
1861
- );
1862
- return "abort";
1863
- }
1864
- if (verifyResult.ok) {
1865
- verifySpinner.stop(`Recovered @${verifyResult.handle}`);
1866
- break;
1867
- }
1868
- verifySpinner.stop("Verification failed");
1869
- if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
1870
- await prompter.note(
1871
- "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.",
1872
- "Invalid recovery code"
1873
- );
1874
- continue;
1875
- }
1876
- await prompter.note(describeRecoverVerifyError(verifyResult), "Recovery failed");
1877
- return "abort";
1878
- }
1879
- if (!verifyResult || !verifyResult.ok) {
1479
+ if (err instanceof setup.WizardCancelledError) throw err;
1480
+ const unreached = err instanceof agentchatme.ConnectionError || err instanceof Error && err.name === "AbortError";
1880
1481
  await prompter.note(
1881
- "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.",
1882
- "Recovery failed"
1482
+ err instanceof Error ? err.message : String(err),
1483
+ unreached ? "Could not reach AgentChat" : `${kind === "register" ? "Registration" : "Recovery"} failed`
1883
1484
  );
1884
- return "abort";
1485
+ return notCompleted(prompter, kind);
1885
1486
  }
1886
- const patch = { apiKey: verifyResult.apiKey };
1887
- if (isValidHandleShape2(verifyResult.handle)) {
1888
- patch.agentHandle = verifyResult.handle;
1889
- }
1890
- const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch);
1487
+ if (result.outcome !== "done") return notCompleted(prompter, kind);
1488
+ const nextCfg = applyAgentchatAccountPatch(cfg, accountId, { apiKey: result.apiKey, agentHandle: result.handle });
1891
1489
  await prompter.note(
1892
1490
  [
1893
- `Handle: @${verifyResult.handle}`,
1894
- `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`,
1895
- "",
1896
- "The previous key for this agent has been revoked."
1491
+ `Handle: @${result.handle}`,
1492
+ `API key: ${redactKey(result.apiKey)} (saved to your OpenClaw config)`
1897
1493
  ].join("\n"),
1898
- "AgentChat API key recovered"
1494
+ kind === "register" ? "AgentChat account created" : "AgentChat API key recovered"
1899
1495
  );
1900
1496
  return {
1901
1497
  cfg: nextCfg,
1902
1498
  credentialValues: {
1903
- token: verifyResult.apiKey,
1499
+ token: result.apiKey,
1904
1500
  [JUST_REGISTERED_SENTINEL]: "1"
1905
1501
  }
1906
1502
  };
1907
1503
  }
1908
- function describeRecoverStartError(result) {
1909
- switch (result.reason) {
1910
- case "rate-limited": {
1911
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1912
- return `Too many recovery attempts from this network.${wait}`;
1913
- }
1914
- case "validation":
1915
- return `AgentChat rejected the request: ${result.message}`;
1916
- case "network-error":
1917
- case "server-error":
1918
- case "unexpected-shape":
1919
- default:
1920
- return result.message;
1921
- }
1922
- }
1923
- function describeRecoverVerifyError(result) {
1924
- switch (result.reason) {
1925
- case "expired":
1926
- return "This recovery code expired. Restart the wizard to request a new one.";
1927
- case "invalid-code":
1928
- return "Too many incorrect codes. Restart the wizard to request a new one.";
1929
- case "handle-required": {
1930
- const handles = result.handles ?? [];
1931
- const list = handles.length > 0 ? `
1932
-
1933
- Agents on this email:
1934
- ${handles.map((h) => ` @${h}`).join("\n")}` : "";
1935
- return `This email backs more than one agent. Run recovery again and enter the handle you want to recover.${list}`;
1936
- }
1937
- case "rate-limited": {
1938
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1939
- return `Rate limited.${wait}`;
1940
- }
1941
- case "network-error":
1942
- case "server-error":
1943
- case "unexpected-shape":
1944
- case "validation":
1945
- default:
1946
- return result.message;
1947
- }
1948
- }
1949
1504
  function redactKey(apiKey) {
1950
1505
  if (apiKey.length < 12) return "\u2022\u2022\u2022\u2022";
1951
1506
  return `${apiKey.slice(0, 8)}\u2026${apiKey.slice(-4)}`;
1952
1507
  }
1508
+ async function saveEnteredKey(cfg, accountId, value, key) {
1509
+ if (typeof value !== "string" || !nonEmpty2(key)) return cfg;
1510
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1511
+ let check;
1512
+ try {
1513
+ check = await checkApiKey(key, { apiBase });
1514
+ } catch {
1515
+ check = null;
1516
+ }
1517
+ if (check !== null && !check.ok) return cfg;
1518
+ const handle = check?.handle;
1519
+ const sameKey = readAgentchatConfigField(cfg, accountId, "apiKey") === value;
1520
+ const withKey = applyAgentchatAccountPatch(cfg, accountId, {
1521
+ apiKey: value,
1522
+ // A new key whose handle is unknown must not keep the old key's handle.
1523
+ ...handle ? { agentHandle: handle } : sameKey ? {} : { agentHandle: void 0 }
1524
+ });
1525
+ return applyIntegrationConfig(withKey, { accountId, handle, apiKey: key, apiBase: apiBase ?? DEFAULT_API_BASE }).cfg;
1526
+ }
1953
1527
  var agentchatSetupWizard = {
1954
1528
  channel: AGENTCHAT_CHANNEL_ID,
1955
1529
  // AgentChat is one-agent-per-account by product design — the agent IS the
@@ -1994,9 +1568,9 @@ var agentchatSetupWizard = {
1994
1568
  "AgentChat is a messaging platform for AI agents \u2014 direct messages,",
1995
1569
  "groups, presence, attachments. Registration is free.",
1996
1570
  "",
1997
- "This wizard will mint a new account via email OTP, accept an existing",
1998
- "API key, or recover a lost key (handle + email OTP) \u2014 your choice in",
1999
- "the next prompt."
1571
+ "This wizard registers a new agent by email code, accepts an existing",
1572
+ "API key, or recovers a lost key by email code \u2014 your choice in the",
1573
+ "next prompt."
2000
1574
  ]
2001
1575
  },
2002
1576
  prepare: async ({ cfg, accountId, credentialValues, prompter }) => {
@@ -2032,7 +1606,7 @@ var agentchatSetupWizard = {
2032
1606
  options: [
2033
1607
  {
2034
1608
  value: "register",
2035
- label: "Register a new agent (email OTP)",
1609
+ label: "Register a new agent (email code)",
2036
1610
  hint: "no account yet \u2014 the wizard creates one"
2037
1611
  },
2038
1612
  {
@@ -2042,64 +1616,14 @@ var agentchatSetupWizard = {
2042
1616
  },
2043
1617
  {
2044
1618
  value: "recover",
2045
- label: "Recover a lost API key (handle + email OTP)",
1619
+ label: "Recover a lost API key (email code)",
2046
1620
  hint: "an agent exists but its key is gone \u2014 re-issue it"
2047
1621
  }
2048
1622
  ],
2049
1623
  initialValue: "register"
2050
1624
  });
2051
- if (choice === "paste") {
2052
- return;
2053
- }
2054
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
2055
- const recover = async () => {
2056
- try {
2057
- const result = await runRecoverFlow({ cfg, accountId, prompter, apiBase });
2058
- if (result === "abort") {
2059
- await prompter.note(
2060
- "Recovery was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
2061
- "Falling back to credential entry"
2062
- );
2063
- return;
2064
- }
2065
- return result;
2066
- } catch (err) {
2067
- if (err instanceof setup.WizardCancelledError) throw err;
2068
- await prompter.note(
2069
- `${err instanceof Error ? err.message : String(err)}`,
2070
- "Recovery flow failed"
2071
- );
2072
- return;
2073
- }
2074
- };
2075
- if (choice === "recover") {
2076
- return await recover();
2077
- }
2078
- let registerOutcome;
2079
- try {
2080
- registerOutcome = await runRegisterFlow({ cfg, accountId, prompter, apiBase });
2081
- } catch (err) {
2082
- if (err instanceof setup.WizardCancelledError) throw err;
2083
- await prompter.note(
2084
- `${err instanceof Error ? err.message : String(err)}`,
2085
- "Registration flow failed"
2086
- );
2087
- return;
2088
- }
2089
- if (registerOutcome === "abort") {
2090
- await prompter.note(
2091
- "Registration was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
2092
- "Falling back to credential entry"
2093
- );
2094
- return;
2095
- }
2096
- if (registerOutcome === "user-chose-paste") {
2097
- return;
2098
- }
2099
- if (registerOutcome === "user-chose-recover") {
2100
- return await recover();
2101
- }
2102
- return registerOutcome;
1625
+ if (choice === "paste") return;
1626
+ return await runAccountFlow({ kind: choice, cfg, accountId, prompter });
2103
1627
  },
2104
1628
  credentials: [
2105
1629
  {
@@ -2112,9 +1636,9 @@ var agentchatSetupWizard = {
2112
1636
  inputPrompt: "Paste your AgentChat API key (ac_\u2026)",
2113
1637
  helpTitle: "AgentChat API key",
2114
1638
  helpLines: [
2115
- "Format: ac_ followed by 43 base64url characters. Validated against",
2116
- "GET /v1/agents/me during this wizard \u2014 bad keys fail fast instead",
2117
- "of flapping reconnects at runtime."
1639
+ "AgentChat checks the key before it is saved: a key it does not",
1640
+ "accept is not saved, so a bad key fails here instead of flapping",
1641
+ "reconnects at runtime."
2118
1642
  ],
2119
1643
  allowEnv: () => true,
2120
1644
  shouldPrompt: ({ credentialValues, currentValue }) => {
@@ -2132,61 +1656,67 @@ var agentchatSetupWizard = {
2132
1656
  resolvedValue: configured ? apiKey : void 0,
2133
1657
  envValue
2134
1658
  };
1659
+ },
1660
+ // The key the person entered, checked before it is saved.
1661
+ applySet: ({ cfg, accountId, value, resolvedValue }) => saveEnteredKey(cfg, accountId, value, resolvedValue),
1662
+ applyUseEnv: ({ cfg, accountId }) => {
1663
+ const key = readEnv_js$1.readApiKeyFromEnv(MIN_API_KEY_LENGTH);
1664
+ return key ? saveEnteredKey(cfg, accountId, key, key) : cfg;
2135
1665
  }
2136
1666
  }
2137
1667
  ],
2138
1668
  finalize: async ({ cfg, accountId, credentialValues, prompter }) => {
2139
- const apiKey = typeof credentialValues.token === "string" && credentialValues.token.length >= MIN_API_KEY_LENGTH ? credentialValues.token : readAgentchatConfigField(cfg, accountId, "apiKey");
2140
- if (!apiKey || !isApiKeyPresent(apiKey)) {
2141
- return;
2142
- }
1669
+ const stored = nonEmpty2(readAgentchatConfigField(cfg, accountId, "apiKey"));
1670
+ const apiKey = nonEmpty2(credentialValues.token) ?? stored;
1671
+ if (!apiKey) return;
2143
1672
  const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
2144
- const spinner = prompter.progress("Validating API key against AgentChat\u2026");
1673
+ const spinner = prompter.progress("Checking the API key with AgentChat\u2026");
1674
+ let check;
2145
1675
  try {
2146
- const result = await validateApiKey(apiKey, { apiBase });
2147
- if (result.ok) {
2148
- spinner.stop(`Authenticated as @${result.agent.handle}`);
2149
- const handle = result.agent.handle;
2150
- const resolvedBase = apiBase ?? DEFAULT_API_BASE2;
2151
- const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
2152
- const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
2153
- const failed = placed.steps.filter((s) => s.status === "failed");
2154
- const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
2155
- await prompter.note(
2156
- [
2157
- ...formatPlacement(placed.steps),
2158
- "",
2159
- 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.",
2160
- ...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."] : [],
2161
- ...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
2162
- ].join("\n"),
2163
- "AgentChat integration placed"
2164
- );
2165
- const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
2166
- return { cfg: applied.cfg };
2167
- }
2168
- spinner.stop(`API key did not pass the live check (${result.reason})`);
1676
+ check = await checkApiKey(apiKey, { apiBase });
1677
+ } catch (err) {
1678
+ spinner.stop("Could not reach AgentChat to check the key");
2169
1679
  await prompter.note(
2170
1680
  [
2171
- result.message,
1681
+ err instanceof Error ? err.message : String(err),
2172
1682
  "",
2173
- "The config was saved \u2014 you can re-run `openclaw channels add agentchat`",
2174
- "to replace the key, or edit ~/.openclaw/config.yaml directly."
1683
+ stored === apiKey ? "The config was saved \u2014 the runtime will retry on startup." : "The key was not saved."
2175
1684
  ].join("\n"),
2176
- "AgentChat validation warning"
1685
+ "AgentChat API unreachable"
2177
1686
  );
2178
- } catch (err) {
2179
- spinner.stop("Could not reach AgentChat for validation");
1687
+ return;
1688
+ }
1689
+ if (!check.ok) {
1690
+ spinner.stop("AgentChat did not accept the API key");
2180
1691
  await prompter.note(
2181
1692
  [
2182
- err instanceof Error ? err.message : String(err),
1693
+ check.message,
2183
1694
  "",
2184
- "The config was saved \u2014 the runtime will retry on startup."
1695
+ 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."
2185
1696
  ].join("\n"),
2186
- "AgentChat API unreachable"
1697
+ "AgentChat API key not accepted"
2187
1698
  );
1699
+ return;
2188
1700
  }
2189
- return;
1701
+ spinner.stop(`Authenticated as @${check.handle}`);
1702
+ const handle = check.handle;
1703
+ const resolvedBase = apiBase ?? DEFAULT_API_BASE;
1704
+ const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
1705
+ const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
1706
+ const failed = placed.steps.filter((s) => s.status === "failed");
1707
+ const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
1708
+ await prompter.note(
1709
+ [
1710
+ ...formatPlacement(placed.steps),
1711
+ "",
1712
+ 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.",
1713
+ ...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."] : [],
1714
+ ...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
1715
+ ].join("\n"),
1716
+ "AgentChat integration placed"
1717
+ );
1718
+ const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
1719
+ return { cfg: applied.cfg };
2190
1720
  },
2191
1721
  completionNote: {
2192
1722
  title: "AgentChat is ready",
@@ -3765,7 +3295,7 @@ var agentchatStatusAdapter = {
3765
3295
  const servedFrom = live?.texts?.source;
3766
3296
  const textsSource = live ? servedFrom === "server" || servedFrom === "cache" ? servedFrom : "missing" : void 0;
3767
3297
  const socketCounters = live?.metrics?.snapshot?.();
3768
- const integration6 = {
3298
+ const integration8 = {
3769
3299
  mode: readEnv_js.readWakeModeFromEnv().mode,
3770
3300
  ...health ? { state: health.state } : {},
3771
3301
  ...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
@@ -3782,7 +3312,7 @@ var agentchatStatusAdapter = {
3782
3312
  pausedByOwner: me.paused_by_owner ?? "none",
3783
3313
  mcp,
3784
3314
  placement,
3785
- integration: integration6,
3315
+ integration: integration8,
3786
3316
  ...refusal ? { refusal } : {},
3787
3317
  ...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
3788
3318
  };
@@ -3849,7 +3379,7 @@ var agentchatDoctorAdapter = {
3849
3379
  continue;
3850
3380
  }
3851
3381
  const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
3852
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3382
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3853
3383
  const handle = readAgentchatConfigField(cfg, accountId, "agentHandle");
3854
3384
  const agentId = resolvePlacementAgentId(cfg, accountId);
3855
3385
  for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {
@@ -3888,16 +3418,16 @@ var agentchatDoctorAdapter = {
3888
3418
  for (const accountId of listConfiguredAccountIds(cfg)) {
3889
3419
  if (!isAgentchatAccountEnabled(cfg, accountId)) continue;
3890
3420
  const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
3891
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3421
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3892
3422
  bases.set(apiBase, apiKey);
3893
3423
  if (apiKey && !readAgentchatConfigField(cfg, accountId, "agentHandle")) {
3894
3424
  try {
3895
- const result = await validateApiKey(apiKey, { apiBase });
3425
+ const result = await checkApiKey(apiKey, { apiBase });
3896
3426
  if (result.ok) {
3897
- next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.agent.handle });
3898
- changes.push(`set channels.agentchat${accountId === "default" ? "" : `.accounts.${accountId}`}.agentHandle = ${result.agent.handle}`);
3427
+ next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.handle });
3428
+ changes.push(`set channels.agentchat${accountId === "default" ? "" : `.accounts.${accountId}`}.agentHandle = ${result.handle}`);
3899
3429
  } else {
3900
- warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and the key did not pass the live check (${result.reason}): ${result.message}`);
3430
+ warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and the key did not pass the live check (${result.code}): ${result.message}`);
3901
3431
  }
3902
3432
  } catch (err) {
3903
3433
  warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and AgentChat was not reachable to learn it: ${err instanceof Error ? err.message : String(err)}`);
@@ -3952,7 +3482,7 @@ var uiHints = {
3952
3482
  label: "AgentChat API key",
3953
3483
  placeholder: "ac_\u2026",
3954
3484
  sensitive: true,
3955
- 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."
3485
+ 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."
3956
3486
  },
3957
3487
  apiBase: {
3958
3488
  label: "API base URL",
@@ -3963,19 +3493,26 @@ var uiHints = {
3963
3493
  agentHandle: {
3964
3494
  label: "Agent handle",
3965
3495
  placeholder: "my-agent",
3966
- help: "3\u201330 chars, lowercase letters/digits/hyphens; must start with a letter."
3496
+ help: "The handle the API key belongs to, as AgentChat returned it; setup and `openclaw doctor --fix` write it."
3967
3497
  },
3968
3498
  reconnect: { label: "Reconnect backoff", advanced: true },
3969
3499
  ping: { label: "WebSocket ping cadence", advanced: true },
3970
3500
  outbound: { label: "Outbound send tuning", advanced: true },
3971
3501
  observability: { label: "Logs & metrics", advanced: true }
3972
3502
  };
3973
- var HANDLE_SHAPE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
3974
- function validHandle(value) {
3503
+ function handleOf(value) {
3975
3504
  if (typeof value !== "string") return void 0;
3976
3505
  const bare = value.trim().replace(/^@/, "");
3977
- return bare.length >= 3 && bare.length <= 30 && HANDLE_SHAPE.test(bare) ? bare : void 0;
3506
+ return bare.length > 0 ? bare : void 0;
3978
3507
  }
3508
+ function keyRefusal(check) {
3509
+ return [
3510
+ `AgentChat did not accept the API key (${check.code}): ${check.message}`,
3511
+ "The key was not saved. Run `openclaw channels add agentchat` to register a new agent or recover a lost key (email code)."
3512
+ ].join("\n");
3513
+ }
3514
+ var keyAskedBeforeWrite = null;
3515
+ var keyDigest = (apiKey) => crypto.createHash("sha256").update(apiKey).digest("hex");
3979
3516
  function say(runtime, level, line) {
3980
3517
  const env = runtime;
3981
3518
  const fn = env?.[level];
@@ -3983,13 +3520,18 @@ function say(runtime, level, line) {
3983
3520
  }
3984
3521
  var agentchatSetupAdapter = {
3985
3522
  /**
3986
- * Pre-write gate: cheap, sync check that the caller supplied an API key
3987
- * that's at least plausibly shaped. Real authentication happens in
3988
- * `prepareAccountConfigInput` / `afterAccountConfigWritten`.
3523
+ * Pre-write gate: a key AgentChat turned away in
3524
+ * `prepareAccountConfigInput` ends here (OpenClaw prints the line and
3525
+ * writes nothing); otherwise a cheap, sync check that the caller supplied
3526
+ * an API key that's at least plausibly shaped. On an OpenClaw without
3527
+ * `prepareAccountConfigInput`, the lifecycle hook refuses a rejected key
3528
+ * before the write.
3989
3529
  */
3990
3530
  validateInput({ input }) {
3531
+ const refusal = input.keyRefusal;
3532
+ if (typeof refusal === "string" && refusal.length > 0) return refusal;
3991
3533
  if (typeof input.token !== "string" || input.token.trim().length === 0) {
3992
- 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)";
3534
+ 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)";
3993
3535
  }
3994
3536
  if (input.token.length < MIN_API_KEY_LENGTH) {
3995
3537
  return `apiKey looks too short (got ${input.token.length} chars, expect \u2265${MIN_API_KEY_LENGTH})`;
@@ -4007,29 +3549,31 @@ var agentchatSetupAdapter = {
4007
3549
  return null;
4008
3550
  },
4009
3551
  /**
4010
- * Learn the handle the key authenticates as BEFORE the write, so
4011
- * `applyAccountConfig` persists it in the same config write OpenClaw
4012
- * already makes. A key that does not validate leaves the input untouched
4013
- * (the write still happens; the error line says what to fix).
3552
+ * Ask AgentChat about the key BEFORE the write. Accepted: the handle it
3553
+ * belongs to goes into the same config write OpenClaw already makes.
3554
+ * Turned away (401 / 403): the input carries the refusal, `validateInput`
3555
+ * returns it, and OpenClaw writes nothing. No verdict (unreachable, a
3556
+ * 5xx): the key is written for the runtime to try, as the wizard does.
4014
3557
  */
4015
- async prepareAccountConfigInput({ accountId, input, runtime }) {
3558
+ async prepareAccountConfigInput({ cfg, accountId, input, runtime }) {
4016
3559
  const apiKey = typeof input.token === "string" ? input.token : void 0;
4017
3560
  if (!apiKey || apiKey.length < MIN_API_KEY_LENGTH) return input;
4018
- const apiBase = typeof input.url === "string" && input.url.length > 0 ? input.url : void 0;
3561
+ const apiBase = typeof input.url === "string" && input.url.length > 0 ? input.url : readAgentchatConfigField(cfg, accountId, "apiBase");
3562
+ keyAskedBeforeWrite = keyDigest(apiKey);
4019
3563
  try {
4020
- const result = await validateApiKey(apiKey, { apiBase });
3564
+ const result = await checkApiKey(apiKey, { apiBase });
4021
3565
  if (result.ok) {
4022
- say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.agent.handle} (${result.agent.email})`);
3566
+ say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.handle}`);
4023
3567
  try {
4024
3568
  placeApiKeyInDotEnv(apiKey);
4025
3569
  } catch (err) {
4026
3570
  say(runtime, "error", `[agentchat:${accountId}] could not write AGENTCHAT_API_KEY to ${dotEnvPath()}: ${err instanceof Error ? err.message : String(err)}`);
4027
3571
  }
4028
- return { ...input, agentHandle: result.agent.handle };
3572
+ return { ...input, agentHandle: result.handle };
4029
3573
  }
4030
- say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`);
3574
+ return { ...input, keyRefusal: keyRefusal(result) };
4031
3575
  } catch (err) {
4032
- say(runtime, "error", `[agentchat:${accountId}] live key validation failed: ${err instanceof Error ? err.message : String(err)}`);
3576
+ 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)}`);
4033
3577
  }
4034
3578
  return input;
4035
3579
  },
@@ -4043,12 +3587,12 @@ var agentchatSetupAdapter = {
4043
3587
  const patch = {};
4044
3588
  if (typeof input.token === "string" && input.token.length > 0) patch.apiKey = input.token;
4045
3589
  if (typeof input.url === "string" && input.url.length > 0) patch.apiBase = input.url;
4046
- const handle = validHandle(input.agentHandle);
3590
+ const handle = handleOf(input.agentHandle);
4047
3591
  if (handle) patch.agentHandle = handle;
4048
3592
  const withAccount = applyAgentchatAccountPatch(cfg, accountId, patch);
4049
3593
  const apiKey = readAgentchatConfigField(withAccount, accountId, "apiKey");
4050
3594
  if (!apiKey) return withAccount;
4051
- const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3595
+ const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE;
4052
3596
  return applyIntegrationConfig(withAccount, { accountId, handle, apiKey, apiBase }).cfg;
4053
3597
  },
4054
3598
  /**
@@ -4059,16 +3603,16 @@ var agentchatSetupAdapter = {
4059
3603
  async afterAccountConfigWritten({ cfg, accountId, input, runtime }) {
4060
3604
  const apiKey = typeof input.token === "string" ? input.token : readAgentchatConfigField(cfg, accountId, "apiKey");
4061
3605
  if (!apiKey) return;
4062
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
4063
- let handle = validHandle(input.agentHandle) ?? readAgentchatConfigField(cfg, accountId, "agentHandle");
3606
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3607
+ let handle = handleOf(input.agentHandle) ?? handleOf(readAgentchatConfigField(cfg, accountId, "agentHandle"));
4064
3608
  if (!handle) {
4065
3609
  try {
4066
- const result = await validateApiKey(apiKey, { apiBase });
3610
+ const result = await checkApiKey(apiKey, { apiBase });
4067
3611
  if (result.ok) {
4068
- handle = result.agent.handle;
3612
+ handle = result.handle;
4069
3613
  say(runtime, "log", `[agentchat:${accountId}] authenticated as @${handle}; run \`openclaw doctor --fix\` to persist channels.agentchat.agentHandle`);
4070
3614
  } else {
4071
- say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`);
3615
+ say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.code}): ${result.message}`);
4072
3616
  return;
4073
3617
  }
4074
3618
  } catch (err) {
@@ -4102,8 +3646,24 @@ function accountSectionPersistable(cfg, accountId) {
4102
3646
  if (!raw) return true;
4103
3647
  return agentchatChannelConfigSchema.safeParse(raw).success;
4104
3648
  }
3649
+ async function refuseRejectedKey(prevCfg, nextCfg, accountId, runtime) {
3650
+ const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
3651
+ if (!apiKey || apiKey === readAgentchatConfigField(prevCfg, accountId, "apiKey")) return;
3652
+ if (keyAskedBeforeWrite === keyDigest(apiKey)) return;
3653
+ let check;
3654
+ try {
3655
+ check = await checkApiKey(apiKey, { apiBase: readAgentchatConfigField(nextCfg, accountId, "apiBase") });
3656
+ } catch (err) {
3657
+ 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)}`);
3658
+ return;
3659
+ }
3660
+ if (check.ok) return;
3661
+ say(runtime, "error", keyRefusal(check));
3662
+ throw new setup.WizardCancelledError("AgentChat did not accept the API key");
3663
+ }
4105
3664
  var agentchatLifecycleAdapter = {
4106
3665
  async onAccountConfigChanged({ prevCfg, nextCfg, accountId, runtime }) {
3666
+ await refuseRejectedKey(prevCfg, nextCfg, accountId, runtime);
4107
3667
  const wasEnabled = isAccountEnabled(prevCfg, accountId);
4108
3668
  const isEnabled = isAccountEnabled(nextCfg, accountId);
4109
3669
  if (wasEnabled === isEnabled) return;
@@ -4119,13 +3679,13 @@ var agentchatLifecycleAdapter = {
4119
3679
  for (const line of removeIntegrationFiles(nextCfg, accountId, { clearKey: false })) say(runtime, "log", `[agentchat:${accountId}] ${line}`);
4120
3680
  return;
4121
3681
  }
4122
- const handle = validHandle(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
3682
+ const handle = handleOf(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
4123
3683
  if (!handle) {
4124
3684
  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`);
4125
3685
  return;
4126
3686
  }
4127
3687
  const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
4128
- const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3688
+ const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
4129
3689
  const identityLine = apiKey ? await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId }) : null;
4130
3690
  const restored = restoreIdentityLine(nextCfg, accountId, handle, identityLine);
4131
3691
  if (restored.outcome === "placed") say(runtime, "log", `[agentchat:${accountId}] placed the identity line for @${handle} in ${restored.path}`);