@agentchatme/openclaw 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.1";
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) {
@@ -630,55 +452,266 @@ async function watchRunUntilEnded(options) {
630
452
  if (elapsedMs < MIN_WAIT_SPACING_MS) await sleep(MIN_WAIT_SPACING_MS - elapsedMs);
631
453
  }
632
454
  }
633
- function countAgentChatCalls(messages, runId) {
455
+ function countAgentChatCalls(messages, runId, host = {}) {
634
456
  if (messages.length === 0) return null;
635
- let recognised = false;
636
- let made = 0;
637
- let failed = 0;
457
+ const rows = [];
638
458
  for (const row of messages) {
639
459
  const message = unwrapMessage(row);
640
- if (!message) continue;
641
- const role = message.role;
642
- if (role === "assistant" || role === "user") recognised = true;
643
- if (role !== "toolResult" && role !== "tool") continue;
644
- recognised = true;
645
- const meta = asRecord2(message.__openclaw);
646
- if (runId && typeof meta?.runId === "string" && meta.runId !== runId) continue;
647
- if (!isAgentChatToolResult(message)) continue;
460
+ if (!message) return null;
461
+ rows.push(message);
462
+ }
463
+ if (!coversWholeSession(rows)) return null;
464
+ if (runId && rows.some((row) => isOtherRun(row, runId))) return null;
465
+ const calls = assistantToolCalls(rows);
466
+ const nested = rows.flatMap((row) => {
467
+ const call = nestedCallOf(row);
468
+ return call ? [call] : [];
469
+ });
470
+ const release = releaseOf(rows, calls, nested, host.openclawVersion);
471
+ if (delegatedToChild(rows, calls, nested)) return null;
472
+ if (usedCodeMode(rows, calls)) {
473
+ if (!release.recordsNestedCalls) return null;
474
+ if (!codeModeScriptsCompleted(rows, calls)) return null;
475
+ }
476
+ const parents = new Set(nested.flatMap((call) => typeof call.parentToolCallId === "string" ? [call.parentToolCallId] : []));
477
+ let made = 0;
478
+ let failed = 0;
479
+ for (const message of rows) {
480
+ let verdict;
481
+ const call = nestedCallOf(message);
482
+ if (call) verdict = nestedVerdict(call);
483
+ else if (message.role !== "toolResult" && message.role !== "tool") continue;
484
+ else if (typeof message.toolCallId === "string" && parents.has(message.toolCallId)) continue;
485
+ else verdict = callVerdict(message, calls, release);
486
+ if (verdict === "not_agentchat") continue;
487
+ if (verdict === "unknown") return null;
648
488
  made += 1;
649
- if (message.isError === true) failed += 1;
489
+ if (verdict === "failed") failed += 1;
650
490
  }
651
- return recognised ? { made, failed } : null;
491
+ return { made, failed };
652
492
  }
653
493
  async function readAgentChatCalls(runtime, sessionKey, runId) {
654
494
  if (!runtime || typeof runtime.subagent?.getSessionMessages !== "function") return null;
655
495
  try {
656
496
  const result = await runtime.subagent.getSessionMessages({ sessionKey, limit: TRANSCRIPT_READ_LIMIT });
657
497
  const messages = result?.messages;
658
- return Array.isArray(messages) ? countAgentChatCalls(messages, runId) : null;
498
+ const openclawVersion = typeof runtime.version === "string" ? runtime.version : void 0;
499
+ return Array.isArray(messages) ? countAgentChatCalls(messages, runId, openclawVersion ? { openclawVersion } : {}) : null;
659
500
  } catch {
660
501
  return null;
661
502
  }
662
503
  }
663
504
  var TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
664
- function isAgentChatToolResult(message) {
665
- const toolName = typeof message.toolName === "string" ? message.toolName : typeof message.name === "string" ? message.name : "";
666
- if (toolName.startsWith(TOOL_PREFIX)) return true;
667
- const tool = asRecord2(asRecord2(message.details)?.tool);
668
- if (!tool) return false;
505
+ var DISPATCHER_TOOL_NAMES = /* @__PURE__ */ new Set(["tool_call", "dispatch_action"]);
506
+ var FAILURE_STATUSES = /* @__PURE__ */ new Set([
507
+ "error",
508
+ "failed",
509
+ "failure",
510
+ "timeout",
511
+ "timed_out",
512
+ "blocked",
513
+ "denied",
514
+ "forbidden",
515
+ "unavailable",
516
+ "approval-unavailable",
517
+ "disabled",
518
+ "aborted",
519
+ "cancelled",
520
+ "canceled",
521
+ "killed",
522
+ "invalid"
523
+ ]);
524
+ function coversWholeSession(rows) {
525
+ if (asRecord(rows[0]?.__openclaw)?.seq !== 1) return false;
526
+ return rows.every((row) => {
527
+ const meta = asRecord(row.__openclaw);
528
+ return meta?.kind !== "compaction" && meta?.kind !== "reset" && meta?.truncated !== true;
529
+ });
530
+ }
531
+ function isOtherRun(row, runId) {
532
+ const tagged = asRecord(row.__openclaw)?.runId ?? nestedCallOf(row)?.runId;
533
+ return typeof tagged === "string" && tagged.trim().length > 0 && tagged.trim() !== runId;
534
+ }
535
+ var CODE_MODE_ONLY_TOOL_NAMES = /* @__PURE__ */ new Set(["tool_search_code", "wait"]);
536
+ function usedCodeMode(rows, calls) {
537
+ return [...calls.values()].some(isCodeModeCall) || rows.some((row) => isCodeModeResult(row, calls));
538
+ }
539
+ function codeModeScriptsCompleted(rows, calls) {
540
+ const results = /* @__PURE__ */ new Map();
541
+ for (const row of rows) {
542
+ if ((row.role === "toolResult" || row.role === "tool") && typeof row.toolCallId === "string") results.set(row.toolCallId, row);
543
+ }
544
+ const completed = (row) => row !== void 0 && row.isError !== true && asRecord(row.details)?.status === "completed";
545
+ for (const [id, call] of calls) {
546
+ if (isCodeModeCall(call) && !completed(results.get(id))) return false;
547
+ }
548
+ return rows.every((row) => !isCodeModeResult(row, calls) || completed(row));
549
+ }
550
+ function isCodeModeCall(call) {
551
+ const name = typeof call.name === "string" ? call.name : "";
552
+ return CODE_MODE_ONLY_TOOL_NAMES.has(name) || name === "exec" && typeof callArguments(call)?.code === "string";
553
+ }
554
+ function isCodeModeResult(row, calls) {
555
+ if (row.role !== "toolResult" && row.role !== "tool") return false;
556
+ const name = toolNameOf(row);
557
+ return CODE_MODE_ONLY_TOOL_NAMES.has(name) || name === "exec" && !isShellExecResult(row, calls);
558
+ }
559
+ function isShellExecResult(row, calls) {
560
+ const call = typeof row.toolCallId === "string" ? calls.get(row.toolCallId) : void 0;
561
+ const args = callArguments(call);
562
+ if (!args || typeof args.command !== "string" || args.code !== void 0) return false;
563
+ const details = asRecord(row.details);
564
+ if (!details || details.telemetry !== void 0) return false;
565
+ return details.exitCode !== void 0 || typeof details.durationMs === "number" || typeof details.aggregated === "string";
566
+ }
567
+ function assistantToolCalls(rows) {
568
+ const calls = /* @__PURE__ */ new Map();
569
+ for (const row of rows) {
570
+ if (row.role !== "assistant" || !Array.isArray(row.content)) continue;
571
+ for (const block of row.content) {
572
+ const call = asRecord(block);
573
+ if (call?.type === "toolCall" && typeof call.id === "string") calls.set(call.id, call);
574
+ }
575
+ }
576
+ return calls;
577
+ }
578
+ var TRUSTED_RELEASE = "2026.9.3";
579
+ function releaseOf(rows, calls, nested, version) {
580
+ if (version !== void 0 && isOpenClawVersion(version)) {
581
+ const trusted = openclawVersionAtLeast(version, TRUSTED_RELEASE);
582
+ return { recordsNestedCalls: trusted, marksFailedRows: trusted };
583
+ }
584
+ const parents = new Set(nested.map((call) => call.parentToolCallId));
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));
586
+ return { recordsNestedCalls: nested.length > 0 || dispatchAction, marksFailedRows: dispatchAction };
587
+ }
588
+ var OPENCLAW_VERSION = /^(\d+)\.(\d+)\.(\d+)(-.+)?$/;
589
+ function isOpenClawVersion(value) {
590
+ return OPENCLAW_VERSION.test(value.trim());
591
+ }
592
+ function openclawVersionAtLeast(a, b) {
593
+ const parse = (v) => {
594
+ const match = OPENCLAW_VERSION.exec(v.trim());
595
+ return match ? { parts: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] !== void 0 } : null;
596
+ };
597
+ const [x, y] = [parse(a), parse(b)];
598
+ if (!x || !y) return false;
599
+ for (let i = 0; i < 3; i += 1) {
600
+ const d = (x.parts[i] ?? 0) - (y.parts[i] ?? 0);
601
+ if (d !== 0) return d > 0;
602
+ }
603
+ return !x.pre || y.pre;
604
+ }
605
+ function toolNameOf(row) {
606
+ return typeof row.toolName === "string" ? row.toolName : typeof row.name === "string" ? row.name : "";
607
+ }
608
+ var NESTED_TOOL_ACTIVITY = "openclaw.nested-tool.v1";
609
+ function nestedCallOf(row) {
610
+ if (row.role !== "custom" || row.customType !== NESTED_TOOL_ACTIVITY) return null;
611
+ return asRecord(row.details);
612
+ }
613
+ function nestedVerdict(call) {
614
+ const toolName = typeof call.toolName === "string" ? call.toolName : "";
615
+ if (!toolName.startsWith(TOOL_PREFIX)) return "not_agentchat";
616
+ const result = asRecord(call.result);
617
+ if (call.isError === true || result !== null && failedResult(result.isError, asRecord(result.details))) return "failed";
618
+ return call.isError === false ? "ok" : "unknown";
619
+ }
620
+ var OTHER_SESSION_TOOLS = /* @__PURE__ */ new Set(["sessions_spawn", "sessions_send"]);
621
+ function delegatedToChild(rows, calls, nested) {
622
+ const names = (value) => typeof value === "string" && OTHER_SESSION_TOOLS.has(value);
623
+ for (const call of calls.values()) {
624
+ if (names(call.name)) return true;
625
+ if (typeof call.name === "string" && DISPATCHER_TOOL_NAMES.has(call.name) && names(dispatchTarget(call))) return true;
626
+ }
627
+ if (nested.some((call) => names(call.toolName))) return true;
628
+ return rows.some((row) => names(toolNameOf(row)) || names(asRecord(asRecord(row.details)?.tool)?.name));
629
+ }
630
+ function callVerdict(message, calls, release) {
631
+ const toolName = toolNameOf(message);
632
+ const details = asRecord(message.details);
633
+ if (toolName.startsWith(TOOL_PREFIX)) return directVerdict(message.isError, details);
634
+ const entry = asRecord(details?.tool);
635
+ if (entry && isAgentChatEntry(entry)) return dispatchedVerdict(message.isError, details);
636
+ if (!DISPATCHER_TOOL_NAMES.has(toolName) || entry) return "not_agentchat";
637
+ const target = dispatchTarget(typeof message.toolCallId === "string" ? calls.get(message.toolCallId) : void 0);
638
+ if (target === null) return "unknown";
639
+ if (!target.startsWith(TOOL_PREFIX)) return "not_agentchat";
640
+ if (failedResult(message.isError, details)) return "failed";
641
+ if (release.marksFailedRows && isTruncated(details) && message.isError === false && details?.status === void 0) return "ok";
642
+ return "unknown";
643
+ }
644
+ function isTruncated(details) {
645
+ return details?.persistedDetailsTruncated === true;
646
+ }
647
+ function directVerdict(isError, details) {
648
+ if (failedResult(isError, details)) return "failed";
649
+ if (isError !== false) return "unknown";
650
+ if (isTruncated(details)) return details?.status === void 0 && wasHostedResult(details) ? "ok" : "unknown";
651
+ return isHostedSuccessDetails(details) ? "ok" : "unknown";
652
+ }
653
+ function wasHostedResult(details) {
654
+ const keys = Array.isArray(details?.originalDetailKeys) ? details.originalDetailKeys : [];
655
+ return keys.includes("mcpServer") && (keys.includes("mcpTool") || keys.includes("mcpOperation"));
656
+ }
657
+ function dispatchedVerdict(isError, details) {
658
+ const result = asRecord(details?.result);
659
+ if (failedResult(isError, details)) return "failed";
660
+ if (result && failedResult(result.isError, asRecord(result.details))) return "failed";
661
+ const ok = isError === false && details?.status === void 0 && isHostedSuccessDetails(asRecord(result?.details));
662
+ return ok ? "ok" : "unknown";
663
+ }
664
+ function failedResult(isError, details) {
665
+ return isError === true || detailsSayFailed(details);
666
+ }
667
+ function detailsSayFailed(details) {
668
+ if (!details) return false;
669
+ if (details.ok === false || details.success === false) return true;
670
+ const status = typeof details.status === "string" ? details.status.trim().toLowerCase() : "";
671
+ const explicitlyOk = details.ok === true || details.success === true;
672
+ if (FAILURE_STATUSES.has(status) && !explicitlyOk) return true;
673
+ if (details.timedOut === true || Boolean(details.error)) return true;
674
+ if (status === "completed") return false;
675
+ const exitCode = details.exitCode;
676
+ return typeof exitCode === "number" && Number.isFinite(exitCode) && exitCode !== 0;
677
+ }
678
+ function isHostedSuccessDetails(details) {
679
+ if (!details || details.mcpServer !== MCP_SERVER_NAME || details.status !== void 0) return false;
680
+ return nonEmpty(details.mcpTool) !== void 0 || nonEmpty(details.mcpOperation) !== void 0;
681
+ }
682
+ function isAgentChatEntry(tool) {
669
683
  if (typeof tool.name === "string" && tool.name.startsWith(TOOL_PREFIX)) return true;
670
684
  if (tool.sourceName === MCP_SERVER_NAME) return true;
671
- const mcp = asRecord2(tool.mcp);
685
+ const mcp = asRecord(tool.mcp);
672
686
  return mcp?.serverName === MCP_SERVER_NAME;
673
687
  }
688
+ function dispatchTarget(call) {
689
+ const record = callArguments(call);
690
+ const selector = nonEmpty(record?.id) ?? nonEmpty(record?.toolId) ?? nonEmpty(record?.name);
691
+ if (!selector) return null;
692
+ const trimmed = selector.trim();
693
+ return trimmed.slice(trimmed.lastIndexOf(":") + 1);
694
+ }
695
+ function callArguments(call) {
696
+ if (!call) return null;
697
+ let args = call.arguments;
698
+ if (typeof args === "string") {
699
+ try {
700
+ args = JSON.parse(args);
701
+ } catch {
702
+ return null;
703
+ }
704
+ }
705
+ return asRecord(args);
706
+ }
674
707
  function unwrapMessage(row) {
675
- const record = asRecord2(row);
708
+ const record = asRecord(row);
676
709
  if (!record) return null;
677
710
  if (typeof record.role === "string") return record;
678
- const inner = asRecord2(record.message);
711
+ const inner = asRecord(record.message);
679
712
  return inner && typeof inner.role === "string" ? inner : null;
680
713
  }
681
- function asRecord2(value) {
714
+ function asRecord(value) {
682
715
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
683
716
  }
684
717
  function nonEmpty(value) {
@@ -934,7 +967,7 @@ function applyIntegrationConfig(cfg, params) {
934
967
  const changes = [];
935
968
  let next = cfg;
936
969
  const bareHandle = (params.handle ?? "").trim().replace(/^@/, "");
937
- if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle && isValidHandleShape(bareHandle)) {
970
+ if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle) {
938
971
  next = applyAgentchatAccountPatch(next, params.accountId, { agentHandle: bareHandle });
939
972
  changes.push(`channels.agentchat${params.accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID ? "" : `.accounts.${params.accountId}`}.agentHandle = ${bareHandle}`);
940
973
  }
@@ -1166,8 +1199,10 @@ function textsCachePath(accountId, stateDir) {
1166
1199
  return path2__namespace.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE);
1167
1200
  }
1168
1201
  function spellTextsForOpenClaw(texts) {
1202
+ const newer = texts;
1169
1203
  return {
1170
1204
  ...texts,
1205
+ ...typeof newer.reply_turn_template === "string" ? { reply_turn_template: spellToolsForOpenClaw(newer.reply_turn_template) } : {},
1171
1206
  wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),
1172
1207
  invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),
1173
1208
  identity_line: spellToolsForOpenClaw(texts.identity_line),
@@ -1267,57 +1302,15 @@ function getClient({ accountId, config, options }) {
1267
1302
 
1268
1303
  // src/channel.wizard.ts
1269
1304
  var JUST_REGISTERED_SENTINEL = "_agentchatJustRegistered";
1270
- var HANDLE_PATTERN2 = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
1271
- var HANDLE_MIN_LENGTH = 3;
1272
- var HANDLE_MAX_LENGTH = 30;
1273
- var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1274
- function isValidHandleShape2(value) {
1275
- return value.length >= HANDLE_MIN_LENGTH && value.length <= HANDLE_MAX_LENGTH && HANDLE_PATTERN2.test(value);
1276
- }
1277
- var OTP_PATTERN = /^\d{6}$/;
1305
+ var LABELS = {
1306
+ ...agentchatme.integration.account.DEFAULT_LABELS,
1307
+ handle: "Handle (your @name on AgentChat)"
1308
+ };
1278
1309
  function hasConfiguredKey(cfg, accountId) {
1279
1310
  return isApiKeyPresent(readAgentchatConfigField(cfg, accountId, "apiKey"));
1280
1311
  }
1281
- var MAX_START_RETRIES = 5;
1282
- async function promptEmail(prompter, opts = {}) {
1283
- return (await prompter.text({
1284
- message: opts.message ?? "Email \u2014 receives a 6-digit verification code",
1285
- placeholder: "you@example.com",
1286
- validate: (value) => {
1287
- const trimmed = value.trim();
1288
- if (!trimmed) return "Email is required";
1289
- if (!EMAIL_PATTERN.test(trimmed)) return "Not a valid email format";
1290
- return void 0;
1291
- }
1292
- })).trim();
1293
- }
1294
- async function promptHandle(prompter, opts = {}) {
1295
- return (await prompter.text({
1296
- message: opts.message ?? "Choose a handle (your @name on AgentChat)",
1297
- placeholder: "3\u201330 chars, lowercase a-z, 0-9, hyphens, starts with a letter",
1298
- ...opts.initialValue ? { initialValue: opts.initialValue } : {},
1299
- validate: (value) => {
1300
- const trimmed = value.trim();
1301
- if (!trimmed) return "Handle is required";
1302
- if (trimmed.length < HANDLE_MIN_LENGTH || trimmed.length > HANDLE_MAX_LENGTH) {
1303
- return `Length must be ${HANDLE_MIN_LENGTH}\u2013${HANDLE_MAX_LENGTH} chars (you entered ${trimmed.length})`;
1304
- }
1305
- if (!/^[a-z]/.test(trimmed)) return "Must start with a lowercase letter";
1306
- if (/[^a-z0-9-]/.test(trimmed)) {
1307
- return "Only lowercase letters, digits, and hyphens \u2014 no underscores, dots, or symbols";
1308
- }
1309
- if (trimmed.includes("--")) return "No consecutive hyphens";
1310
- if (trimmed.endsWith("-")) return "Cannot end with a hyphen";
1311
- return void 0;
1312
- }
1313
- })).trim();
1314
- }
1315
- async function promptDisplayName(prompter) {
1316
- return (await prompter.text({
1317
- message: "Display name (shown next to your @handle)",
1318
- placeholder: "e.g. Anton, Builder Bot, Sasha",
1319
- validate: () => void 0
1320
- })).trim();
1312
+ function nonEmpty2(value) {
1313
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
1321
1314
  }
1322
1315
  async function runChangeApiBaseFlow(params) {
1323
1316
  const { cfg, accountId, prompter } = params;
@@ -1355,388 +1348,182 @@ async function runChangeApiBaseFlow(params) {
1355
1348
  await prompter.note(`API base set to ${input}`, "Updated");
1356
1349
  return { cfg: patched };
1357
1350
  }
1358
- function describeEmailPolicyRejection(email, result) {
1359
- if (result.limit === void 0) return result.message;
1360
- 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.`;
1361
- }
1362
- async function promptEmailPolicyChoice(prompter, email, result) {
1363
- return prompter.select({
1364
- message: `${describeEmailPolicyRejection(email, result)} What next?`,
1365
- options: [
1366
- {
1367
- value: "retry",
1368
- label: "Use a different email address",
1369
- hint: "a +alias like you+agent2@example.com counts as a separate email"
1370
- },
1371
- {
1372
- value: "recover",
1373
- label: "Recover the API key of an agent this email already backs",
1374
- hint: "needs that agent\u2019s handle \u2014 a code goes to this email"
1375
- },
1376
- { value: "paste", label: "Paste a key from an existing agent" },
1377
- { value: "cancel", label: "Cancel registration" }
1378
- ],
1379
- initialValue: "retry"
1380
- });
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();
1381
1357
  }
1382
- async function runRegisterFlow(params) {
1383
- const { cfg, accountId, prompter, apiBase } = params;
1384
- await prompter.note(
1385
- [
1386
- "Registration mints a new AgentChat agent identity tied to your email.",
1387
- "One email can back several agents (the server enforces the limit);",
1388
- "each one registers and verifies separately.",
1389
- "You will receive a 6-digit code to verify \u2014 check your inbox (and spam)."
1390
- ].join("\n"),
1391
- "AgentChat: register a new agent"
1392
- );
1393
- let email = await promptEmail(prompter);
1394
- let handle = await promptHandle(prompter);
1395
- const displayName = await promptDisplayName(prompter);
1396
- let startResult;
1397
- let startedOk = false;
1398
- for (let attempt = 1; attempt <= MAX_START_RETRIES; attempt += 1) {
1399
- const startSpinner = prompter.progress(
1400
- attempt === 1 ? "Sending verification code\u2026" : "Retrying\u2026"
1401
- );
1402
- try {
1403
- startResult = await registerAgentStart(
1404
- {
1405
- email,
1406
- handle,
1407
- ...displayName ? { displayName } : {}
1408
- },
1409
- { apiBase }
1410
- );
1411
- } catch (err) {
1412
- startSpinner.stop("Could not reach AgentChat");
1413
- await prompter.note(
1414
- `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
1415
- "Registration failed"
1416
- );
1417
- return "abort";
1418
- }
1419
- if (startResult.ok) {
1420
- startSpinner.stop(`Verification code sent to ${email}`);
1421
- startedOk = true;
1422
- break;
1423
- }
1424
- startSpinner.stop("Registration rejected");
1425
- switch (startResult.reason) {
1426
- case "invalid-handle":
1427
- case "handle-taken": {
1428
- 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).";
1429
- await prompter.note(`${detail} Pick a different handle and we'll try again.`, "Pick a different handle");
1430
- handle = await promptHandle(prompter);
1431
- continue;
1432
- }
1433
- case "email-limit-reached":
1434
- case "email-exhausted": {
1435
- const choice = await promptEmailPolicyChoice(prompter, email, {
1436
- reason: startResult.reason,
1437
- limit: startResult.limit,
1438
- message: startResult.message
1439
- });
1440
- if (choice === "paste") return "user-chose-paste";
1441
- if (choice === "recover") return "user-chose-recover";
1442
- if (choice === "cancel") return "abort";
1443
- email = await promptEmail(prompter);
1444
- continue;
1445
- }
1446
- case "rate-limited": {
1447
- const wait = startResult.retryAfterSeconds ? ` Try again in ${startResult.retryAfterSeconds}s.` : "";
1448
- await prompter.note(`Too many registration attempts.${wait}`, "Rate limited");
1449
- return "abort";
1450
- }
1451
- case "otp-failed": {
1452
- await prompter.note(
1453
- "The verification-code email could not be sent. Try again in a minute, or paste an existing key instead.",
1454
- "OTP delivery failed"
1455
- );
1456
- return "abort";
1457
- }
1458
- case "network-error":
1459
- case "server-error":
1460
- case "validation":
1461
- default: {
1462
- await prompter.note(describeRegisterStartError(startResult), "Could not start registration");
1463
- return "abort";
1464
- }
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 };
1465
1394
  }
1466
- }
1467
- if (!startedOk || !startResult || !startResult.ok) {
1468
- await prompter.note(
1469
- "Too many attempts. Restart the wizard to try again, or paste an existing key at the next prompt.",
1470
- "Registration failed"
1471
- );
1472
- return "abort";
1473
- }
1474
- const maxCodeAttempts = 3;
1475
- let verifyResult = null;
1476
- for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
1477
- const code = (await prompter.text({
1478
- message: attempt === 1 ? "Enter the 6-digit verification code from your email" : `Verification code (attempt ${attempt}/${maxCodeAttempts})`,
1479
- placeholder: "123456",
1480
- validate: (value) => {
1481
- const trimmed = value.trim();
1482
- if (!trimmed) return "Code is required";
1483
- if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
1484
- return void 0;
1485
- }
1486
- })).trim();
1487
- 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");
1488
1402
  try {
1489
- verifyResult = await registerAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
1490
- } catch (err) {
1491
- verifySpinner.stop("Could not reach AgentChat");
1492
- await prompter.note(
1493
- `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
1494
- "Verification failed"
1495
- );
1496
- return "abort";
1497
- }
1498
- if (verifyResult.ok) {
1499
- verifySpinner.stop(`Registered as @${verifyResult.agent.handle}`);
1500
- break;
1501
- }
1502
- verifySpinner.stop("Verification failed");
1503
- if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
1504
- await prompter.note(
1505
- "That code did not match. Check your email and try again.",
1506
- "Invalid verification code"
1507
- );
1508
- continue;
1403
+ return await globalThis.fetch(input, init);
1404
+ } finally {
1405
+ progress.stop();
1509
1406
  }
1510
- await prompter.note(describeRegisterVerifyError(verifyResult), "Registration failed");
1511
- return "abort";
1512
- }
1513
- if (!verifyResult || !verifyResult.ok) {
1514
- await prompter.note(
1515
- "Too many incorrect codes. Restart the wizard to receive a new code.",
1516
- "Registration failed"
1517
- );
1518
- return "abort";
1519
- }
1520
- const patch = { apiKey: verifyResult.apiKey };
1521
- if (isValidHandleShape2(verifyResult.agent.handle)) {
1522
- patch.agentHandle = verifyResult.agent.handle;
1523
- }
1524
- 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) {
1525
1426
  await prompter.note(
1526
1427
  [
1527
- `Handle: @${verifyResult.agent.handle}`,
1528
- `Email: ${verifyResult.agent.email}`,
1529
- `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)."
1530
1431
  ].join("\n"),
1531
- "AgentChat account created"
1432
+ "AgentChat: register a new agent"
1532
1433
  );
1533
- return {
1534
- cfg: nextCfg,
1535
- credentialValues: {
1536
- token: verifyResult.apiKey,
1537
- [JUST_REGISTERED_SENTINEL]: "1"
1538
- }
1539
- };
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 } : {} };
1540
1441
  }
1541
- function describeRegisterStartError(result) {
1542
- switch (result.reason) {
1543
- case "invalid-handle":
1544
- return "That handle is not acceptable. Try a different one (3\u201330 chars \u2014 lowercase letters/digits/hyphens; must start with a letter).";
1545
- case "handle-taken":
1546
- return "That handle is already taken. Try a different one.";
1547
- case "email-limit-reached":
1548
- 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.`;
1549
- case "email-exhausted":
1550
- 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.`;
1551
- case "rate-limited": {
1552
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1553
- return `Rate limited.${wait}`;
1554
- }
1555
- case "otp-failed":
1556
- return "The verification-code email could not be sent. Try again in a minute.";
1557
- case "network-error":
1558
- case "server-error":
1559
- case "validation":
1560
- default:
1561
- return result.message;
1562
- }
1563
- }
1564
- function describeRegisterVerifyError(result) {
1565
- switch (result.reason) {
1566
- case "expired":
1567
- return "This code expired. Restart the wizard to receive a new one.";
1568
- case "invalid-code":
1569
- return "Too many incorrect codes. Restart the wizard to receive a new one.";
1570
- case "handle-taken":
1571
- return "Your chosen handle was claimed by another registration in the meantime. Restart with a different handle.";
1572
- case "email-limit-reached":
1573
- 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.`;
1574
- case "email-exhausted":
1575
- 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.`;
1576
- case "rate-limited": {
1577
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1578
- return `Rate limited.${wait}`;
1579
- }
1580
- case "network-error":
1581
- case "server-error":
1582
- case "unexpected-shape":
1583
- case "validation":
1584
- default:
1585
- return result.message;
1586
- }
1587
- }
1588
- async function runRecoverFlow(params) {
1589
- const { cfg, accountId, prompter, apiBase } = params;
1590
- const storedHandle = readAgentchatConfigField(cfg, accountId, "agentHandle");
1591
- const defaultHandle = storedHandle && isValidHandleShape2(storedHandle) ? storedHandle : void 0;
1442
+ async function recoverInput(prompter, configuredHandle) {
1592
1443
  await prompter.note(
1593
1444
  [
1594
- "Recovery re-issues the API key for ONE agent \u2014 the handle you name below.",
1595
- "You need that handle and the email it registered with; a 6-digit code",
1596
- "goes to that email. The old key stops working the moment the new one",
1597
- "is minted.",
1598
- ...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.`] : []
1599
1449
  ].join("\n"),
1600
1450
  "AgentChat: recover a lost API key"
1601
1451
  );
1602
- const handle = await promptHandle(prompter, {
1603
- message: "Handle of the agent to recover (its @name on AgentChat)",
1604
- ...defaultHandle ? { initialValue: defaultHandle } : {}
1605
- });
1606
- const email = await promptEmail(prompter, {
1607
- message: `Email @${handle} registered with \u2014 receives a 6-digit recovery code`
1608
- });
1609
- const startSpinner = prompter.progress("Requesting recovery code\u2026");
1610
- 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;
1611
1468
  try {
1612
- 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
+ });
1613
1478
  } catch (err) {
1614
- startSpinner.stop("Could not reach AgentChat");
1615
- await prompter.note(
1616
- `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
1617
- "Recovery failed"
1618
- );
1619
- return "abort";
1620
- }
1621
- if (!startResult.ok) {
1622
- startSpinner.stop("Recovery rejected");
1623
- await prompter.note(describeRecoverStartError(startResult), "Could not start recovery");
1624
- return "abort";
1625
- }
1626
- startSpinner.stop(startResult.message);
1627
- const maxCodeAttempts = 3;
1628
- let verifyResult = null;
1629
- for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
1630
- const code = (await prompter.text({
1631
- message: attempt === 1 ? `Enter the 6-digit recovery code (check ${email}, including spam)` : `Recovery code (attempt ${attempt}/${maxCodeAttempts})`,
1632
- placeholder: "123456",
1633
- validate: (value) => {
1634
- const trimmed = value.trim();
1635
- if (!trimmed) return "Code is required";
1636
- if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
1637
- return void 0;
1638
- }
1639
- })).trim();
1640
- const verifySpinner = prompter.progress("Verifying code\u2026");
1641
- try {
1642
- verifyResult = await recoverAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
1643
- } catch (err) {
1644
- verifySpinner.stop("Could not reach AgentChat");
1645
- await prompter.note(
1646
- `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
1647
- "Recovery failed"
1648
- );
1649
- return "abort";
1650
- }
1651
- if (verifyResult.ok) {
1652
- verifySpinner.stop(`Recovered @${verifyResult.handle}`);
1653
- break;
1654
- }
1655
- verifySpinner.stop("Verification failed");
1656
- if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
1657
- await prompter.note(
1658
- "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.",
1659
- "Invalid recovery code"
1660
- );
1661
- continue;
1662
- }
1663
- await prompter.note(describeRecoverVerifyError(verifyResult), "Recovery failed");
1664
- return "abort";
1665
- }
1666
- 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";
1667
1481
  await prompter.note(
1668
- "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.",
1669
- "Recovery failed"
1482
+ err instanceof Error ? err.message : String(err),
1483
+ unreached ? "Could not reach AgentChat" : `${kind === "register" ? "Registration" : "Recovery"} failed`
1670
1484
  );
1671
- return "abort";
1485
+ return notCompleted(prompter, kind);
1672
1486
  }
1673
- const patch = { apiKey: verifyResult.apiKey };
1674
- if (isValidHandleShape2(verifyResult.handle)) {
1675
- patch.agentHandle = verifyResult.handle;
1676
- }
1677
- 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 });
1678
1489
  await prompter.note(
1679
1490
  [
1680
- `Handle: @${verifyResult.handle}`,
1681
- `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`,
1682
- "",
1683
- "The previous key for this agent has been revoked."
1491
+ `Handle: @${result.handle}`,
1492
+ `API key: ${redactKey(result.apiKey)} (saved to your OpenClaw config)`
1684
1493
  ].join("\n"),
1685
- "AgentChat API key recovered"
1494
+ kind === "register" ? "AgentChat account created" : "AgentChat API key recovered"
1686
1495
  );
1687
1496
  return {
1688
1497
  cfg: nextCfg,
1689
1498
  credentialValues: {
1690
- token: verifyResult.apiKey,
1499
+ token: result.apiKey,
1691
1500
  [JUST_REGISTERED_SENTINEL]: "1"
1692
1501
  }
1693
1502
  };
1694
1503
  }
1695
- function describeRecoverStartError(result) {
1696
- switch (result.reason) {
1697
- case "rate-limited": {
1698
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1699
- return `Too many recovery attempts from this network.${wait}`;
1700
- }
1701
- case "validation":
1702
- return `AgentChat rejected the request: ${result.message}`;
1703
- case "network-error":
1704
- case "server-error":
1705
- case "unexpected-shape":
1706
- default:
1707
- return result.message;
1708
- }
1709
- }
1710
- function describeRecoverVerifyError(result) {
1711
- switch (result.reason) {
1712
- case "expired":
1713
- return "This recovery code expired. Restart the wizard to request a new one.";
1714
- case "invalid-code":
1715
- return "Too many incorrect codes. Restart the wizard to request a new one.";
1716
- case "handle-required": {
1717
- const handles = result.handles ?? [];
1718
- const list = handles.length > 0 ? `
1719
-
1720
- Agents on this email:
1721
- ${handles.map((h) => ` @${h}`).join("\n")}` : "";
1722
- return `This email backs more than one agent. Run recovery again and enter the handle you want to recover.${list}`;
1723
- }
1724
- case "rate-limited": {
1725
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1726
- return `Rate limited.${wait}`;
1727
- }
1728
- case "network-error":
1729
- case "server-error":
1730
- case "unexpected-shape":
1731
- case "validation":
1732
- default:
1733
- return result.message;
1734
- }
1735
- }
1736
1504
  function redactKey(apiKey) {
1737
1505
  if (apiKey.length < 12) return "\u2022\u2022\u2022\u2022";
1738
1506
  return `${apiKey.slice(0, 8)}\u2026${apiKey.slice(-4)}`;
1739
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
+ }
1740
1527
  var agentchatSetupWizard = {
1741
1528
  channel: AGENTCHAT_CHANNEL_ID,
1742
1529
  // AgentChat is one-agent-per-account by product design — the agent IS the
@@ -1781,9 +1568,9 @@ var agentchatSetupWizard = {
1781
1568
  "AgentChat is a messaging platform for AI agents \u2014 direct messages,",
1782
1569
  "groups, presence, attachments. Registration is free.",
1783
1570
  "",
1784
- "This wizard will mint a new account via email OTP, accept an existing",
1785
- "API key, or recover a lost key (handle + email OTP) \u2014 your choice in",
1786
- "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."
1787
1574
  ]
1788
1575
  },
1789
1576
  prepare: async ({ cfg, accountId, credentialValues, prompter }) => {
@@ -1819,7 +1606,7 @@ var agentchatSetupWizard = {
1819
1606
  options: [
1820
1607
  {
1821
1608
  value: "register",
1822
- label: "Register a new agent (email OTP)",
1609
+ label: "Register a new agent (email code)",
1823
1610
  hint: "no account yet \u2014 the wizard creates one"
1824
1611
  },
1825
1612
  {
@@ -1829,64 +1616,14 @@ var agentchatSetupWizard = {
1829
1616
  },
1830
1617
  {
1831
1618
  value: "recover",
1832
- label: "Recover a lost API key (handle + email OTP)",
1619
+ label: "Recover a lost API key (email code)",
1833
1620
  hint: "an agent exists but its key is gone \u2014 re-issue it"
1834
1621
  }
1835
1622
  ],
1836
1623
  initialValue: "register"
1837
1624
  });
1838
- if (choice === "paste") {
1839
- return;
1840
- }
1841
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1842
- const recover = async () => {
1843
- try {
1844
- const result = await runRecoverFlow({ cfg, accountId, prompter, apiBase });
1845
- if (result === "abort") {
1846
- await prompter.note(
1847
- "Recovery was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
1848
- "Falling back to credential entry"
1849
- );
1850
- return;
1851
- }
1852
- return result;
1853
- } catch (err) {
1854
- if (err instanceof setup.WizardCancelledError) throw err;
1855
- await prompter.note(
1856
- `${err instanceof Error ? err.message : String(err)}`,
1857
- "Recovery flow failed"
1858
- );
1859
- return;
1860
- }
1861
- };
1862
- if (choice === "recover") {
1863
- return await recover();
1864
- }
1865
- let registerOutcome;
1866
- try {
1867
- registerOutcome = await runRegisterFlow({ cfg, accountId, prompter, apiBase });
1868
- } catch (err) {
1869
- if (err instanceof setup.WizardCancelledError) throw err;
1870
- await prompter.note(
1871
- `${err instanceof Error ? err.message : String(err)}`,
1872
- "Registration flow failed"
1873
- );
1874
- return;
1875
- }
1876
- if (registerOutcome === "abort") {
1877
- await prompter.note(
1878
- "Registration was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
1879
- "Falling back to credential entry"
1880
- );
1881
- return;
1882
- }
1883
- if (registerOutcome === "user-chose-paste") {
1884
- return;
1885
- }
1886
- if (registerOutcome === "user-chose-recover") {
1887
- return await recover();
1888
- }
1889
- return registerOutcome;
1625
+ if (choice === "paste") return;
1626
+ return await runAccountFlow({ kind: choice, cfg, accountId, prompter });
1890
1627
  },
1891
1628
  credentials: [
1892
1629
  {
@@ -1899,9 +1636,9 @@ var agentchatSetupWizard = {
1899
1636
  inputPrompt: "Paste your AgentChat API key (ac_\u2026)",
1900
1637
  helpTitle: "AgentChat API key",
1901
1638
  helpLines: [
1902
- "Format: ac_ followed by 43 base64url characters. Validated against",
1903
- "GET /v1/agents/me during this wizard \u2014 bad keys fail fast instead",
1904
- "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."
1905
1642
  ],
1906
1643
  allowEnv: () => true,
1907
1644
  shouldPrompt: ({ credentialValues, currentValue }) => {
@@ -1919,61 +1656,67 @@ var agentchatSetupWizard = {
1919
1656
  resolvedValue: configured ? apiKey : void 0,
1920
1657
  envValue
1921
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;
1922
1665
  }
1923
1666
  }
1924
1667
  ],
1925
1668
  finalize: async ({ cfg, accountId, credentialValues, prompter }) => {
1926
- const apiKey = typeof credentialValues.token === "string" && credentialValues.token.length >= MIN_API_KEY_LENGTH ? credentialValues.token : readAgentchatConfigField(cfg, accountId, "apiKey");
1927
- if (!apiKey || !isApiKeyPresent(apiKey)) {
1928
- return;
1929
- }
1669
+ const stored = nonEmpty2(readAgentchatConfigField(cfg, accountId, "apiKey"));
1670
+ const apiKey = nonEmpty2(credentialValues.token) ?? stored;
1671
+ if (!apiKey) return;
1930
1672
  const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1931
- 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;
1932
1675
  try {
1933
- const result = await validateApiKey(apiKey, { apiBase });
1934
- if (result.ok) {
1935
- spinner.stop(`Authenticated as @${result.agent.handle}`);
1936
- const handle = result.agent.handle;
1937
- const resolvedBase = apiBase ?? DEFAULT_API_BASE2;
1938
- const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
1939
- const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
1940
- const failed = placed.steps.filter((s) => s.status === "failed");
1941
- const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
1942
- await prompter.note(
1943
- [
1944
- ...formatPlacement(placed.steps),
1945
- "",
1946
- 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.",
1947
- ...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."] : [],
1948
- ...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
1949
- ].join("\n"),
1950
- "AgentChat integration placed"
1951
- );
1952
- const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
1953
- return { cfg: applied.cfg };
1954
- }
1955
- 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");
1956
1679
  await prompter.note(
1957
1680
  [
1958
- result.message,
1681
+ err instanceof Error ? err.message : String(err),
1959
1682
  "",
1960
- "The config was saved \u2014 you can re-run `openclaw channels add agentchat`",
1961
- "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."
1962
1684
  ].join("\n"),
1963
- "AgentChat validation warning"
1685
+ "AgentChat API unreachable"
1964
1686
  );
1965
- } catch (err) {
1966
- 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");
1967
1691
  await prompter.note(
1968
1692
  [
1969
- err instanceof Error ? err.message : String(err),
1693
+ check.message,
1970
1694
  "",
1971
- "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."
1972
1696
  ].join("\n"),
1973
- "AgentChat API unreachable"
1697
+ "AgentChat API key not accepted"
1974
1698
  );
1699
+ return;
1975
1700
  }
1976
- 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 };
1977
1720
  },
1978
1721
  completionNote: {
1979
1722
  title: "AgentChat is ready",
@@ -3138,6 +2881,12 @@ function logEvent(event, logger, metrics) {
3138
2881
  case "echo":
3139
2882
  logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "own echo \u2014 not a wake");
3140
2883
  return;
2884
+ case "notice":
2885
+ logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "system notice \u2014 acked, not a wake");
2886
+ return;
2887
+ case "gate_chunk":
2888
+ logger.debug({ cycle: event.cycle, chunk: event.index, of: event.of, cards: event.cards, outcome: event.outcome, undecided: event.undecided, ...event.failure ? { failure: event.failure } : {} }, "gate chunk");
2889
+ return;
3141
2890
  case "cycle": {
3142
2891
  const s = event.summary;
3143
2892
  const fields = {
@@ -3546,7 +3295,7 @@ var agentchatStatusAdapter = {
3546
3295
  const servedFrom = live?.texts?.source;
3547
3296
  const textsSource = live ? servedFrom === "server" || servedFrom === "cache" ? servedFrom : "missing" : void 0;
3548
3297
  const socketCounters = live?.metrics?.snapshot?.();
3549
- const integration6 = {
3298
+ const integration8 = {
3550
3299
  mode: readEnv_js.readWakeModeFromEnv().mode,
3551
3300
  ...health ? { state: health.state } : {},
3552
3301
  ...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
@@ -3563,7 +3312,7 @@ var agentchatStatusAdapter = {
3563
3312
  pausedByOwner: me.paused_by_owner ?? "none",
3564
3313
  mcp,
3565
3314
  placement,
3566
- integration: integration6,
3315
+ integration: integration8,
3567
3316
  ...refusal ? { refusal } : {},
3568
3317
  ...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
3569
3318
  };
@@ -3630,7 +3379,7 @@ var agentchatDoctorAdapter = {
3630
3379
  continue;
3631
3380
  }
3632
3381
  const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
3633
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3382
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3634
3383
  const handle = readAgentchatConfigField(cfg, accountId, "agentHandle");
3635
3384
  const agentId = resolvePlacementAgentId(cfg, accountId);
3636
3385
  for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {
@@ -3669,16 +3418,16 @@ var agentchatDoctorAdapter = {
3669
3418
  for (const accountId of listConfiguredAccountIds(cfg)) {
3670
3419
  if (!isAgentchatAccountEnabled(cfg, accountId)) continue;
3671
3420
  const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
3672
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3421
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3673
3422
  bases.set(apiBase, apiKey);
3674
3423
  if (apiKey && !readAgentchatConfigField(cfg, accountId, "agentHandle")) {
3675
3424
  try {
3676
- const result = await validateApiKey(apiKey, { apiBase });
3425
+ const result = await checkApiKey(apiKey, { apiBase });
3677
3426
  if (result.ok) {
3678
- next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.agent.handle });
3679
- 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}`);
3680
3429
  } else {
3681
- 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}`);
3682
3431
  }
3683
3432
  } catch (err) {
3684
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)}`);
@@ -3733,7 +3482,7 @@ var uiHints = {
3733
3482
  label: "AgentChat API key",
3734
3483
  placeholder: "ac_\u2026",
3735
3484
  sensitive: true,
3736
- help: "The setup wizard registers you via email OTP and mints a key, recovers a lost key (handle + email OTP), or accepts an existing ac_\u2026 key."
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."
3737
3486
  },
3738
3487
  apiBase: {
3739
3488
  label: "API base URL",
@@ -3744,19 +3493,26 @@ var uiHints = {
3744
3493
  agentHandle: {
3745
3494
  label: "Agent handle",
3746
3495
  placeholder: "my-agent",
3747
- 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."
3748
3497
  },
3749
3498
  reconnect: { label: "Reconnect backoff", advanced: true },
3750
3499
  ping: { label: "WebSocket ping cadence", advanced: true },
3751
3500
  outbound: { label: "Outbound send tuning", advanced: true },
3752
3501
  observability: { label: "Logs & metrics", advanced: true }
3753
3502
  };
3754
- var HANDLE_SHAPE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
3755
- function validHandle(value) {
3503
+ function handleOf(value) {
3756
3504
  if (typeof value !== "string") return void 0;
3757
3505
  const bare = value.trim().replace(/^@/, "");
3758
- return bare.length >= 3 && bare.length <= 30 && HANDLE_SHAPE.test(bare) ? bare : void 0;
3506
+ return bare.length > 0 ? bare : void 0;
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");
3759
3513
  }
3514
+ var keyAskedBeforeWrite = null;
3515
+ var keyDigest = (apiKey) => crypto.createHash("sha256").update(apiKey).digest("hex");
3760
3516
  function say(runtime, level, line) {
3761
3517
  const env = runtime;
3762
3518
  const fn = env?.[level];
@@ -3764,13 +3520,18 @@ function say(runtime, level, line) {
3764
3520
  }
3765
3521
  var agentchatSetupAdapter = {
3766
3522
  /**
3767
- * Pre-write gate: cheap, sync check that the caller supplied an API key
3768
- * that's at least plausibly shaped. Real authentication happens in
3769
- * `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.
3770
3529
  */
3771
3530
  validateInput({ input }) {
3531
+ const refusal = input.keyRefusal;
3532
+ if (typeof refusal === "string" && refusal.length > 0) return refusal;
3772
3533
  if (typeof input.token !== "string" || input.token.trim().length === 0) {
3773
- 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)";
3774
3535
  }
3775
3536
  if (input.token.length < MIN_API_KEY_LENGTH) {
3776
3537
  return `apiKey looks too short (got ${input.token.length} chars, expect \u2265${MIN_API_KEY_LENGTH})`;
@@ -3788,29 +3549,31 @@ var agentchatSetupAdapter = {
3788
3549
  return null;
3789
3550
  },
3790
3551
  /**
3791
- * Learn the handle the key authenticates as BEFORE the write, so
3792
- * `applyAccountConfig` persists it in the same config write OpenClaw
3793
- * already makes. A key that does not validate leaves the input untouched
3794
- * (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.
3795
3557
  */
3796
- async prepareAccountConfigInput({ accountId, input, runtime }) {
3558
+ async prepareAccountConfigInput({ cfg, accountId, input, runtime }) {
3797
3559
  const apiKey = typeof input.token === "string" ? input.token : void 0;
3798
3560
  if (!apiKey || apiKey.length < MIN_API_KEY_LENGTH) return input;
3799
- 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);
3800
3563
  try {
3801
- const result = await validateApiKey(apiKey, { apiBase });
3564
+ const result = await checkApiKey(apiKey, { apiBase });
3802
3565
  if (result.ok) {
3803
- say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.agent.handle} (${result.agent.email})`);
3566
+ say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.handle}`);
3804
3567
  try {
3805
3568
  placeApiKeyInDotEnv(apiKey);
3806
3569
  } catch (err) {
3807
3570
  say(runtime, "error", `[agentchat:${accountId}] could not write AGENTCHAT_API_KEY to ${dotEnvPath()}: ${err instanceof Error ? err.message : String(err)}`);
3808
3571
  }
3809
- return { ...input, agentHandle: result.agent.handle };
3572
+ return { ...input, agentHandle: result.handle };
3810
3573
  }
3811
- say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`);
3574
+ return { ...input, keyRefusal: keyRefusal(result) };
3812
3575
  } catch (err) {
3813
- 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)}`);
3814
3577
  }
3815
3578
  return input;
3816
3579
  },
@@ -3824,12 +3587,12 @@ var agentchatSetupAdapter = {
3824
3587
  const patch = {};
3825
3588
  if (typeof input.token === "string" && input.token.length > 0) patch.apiKey = input.token;
3826
3589
  if (typeof input.url === "string" && input.url.length > 0) patch.apiBase = input.url;
3827
- const handle = validHandle(input.agentHandle);
3590
+ const handle = handleOf(input.agentHandle);
3828
3591
  if (handle) patch.agentHandle = handle;
3829
3592
  const withAccount = applyAgentchatAccountPatch(cfg, accountId, patch);
3830
3593
  const apiKey = readAgentchatConfigField(withAccount, accountId, "apiKey");
3831
3594
  if (!apiKey) return withAccount;
3832
- const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3595
+ const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE;
3833
3596
  return applyIntegrationConfig(withAccount, { accountId, handle, apiKey, apiBase }).cfg;
3834
3597
  },
3835
3598
  /**
@@ -3840,16 +3603,16 @@ var agentchatSetupAdapter = {
3840
3603
  async afterAccountConfigWritten({ cfg, accountId, input, runtime }) {
3841
3604
  const apiKey = typeof input.token === "string" ? input.token : readAgentchatConfigField(cfg, accountId, "apiKey");
3842
3605
  if (!apiKey) return;
3843
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3844
- 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"));
3845
3608
  if (!handle) {
3846
3609
  try {
3847
- const result = await validateApiKey(apiKey, { apiBase });
3610
+ const result = await checkApiKey(apiKey, { apiBase });
3848
3611
  if (result.ok) {
3849
- handle = result.agent.handle;
3612
+ handle = result.handle;
3850
3613
  say(runtime, "log", `[agentchat:${accountId}] authenticated as @${handle}; run \`openclaw doctor --fix\` to persist channels.agentchat.agentHandle`);
3851
3614
  } else {
3852
- 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}`);
3853
3616
  return;
3854
3617
  }
3855
3618
  } catch (err) {
@@ -3883,8 +3646,24 @@ function accountSectionPersistable(cfg, accountId) {
3883
3646
  if (!raw) return true;
3884
3647
  return agentchatChannelConfigSchema.safeParse(raw).success;
3885
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
+ }
3886
3664
  var agentchatLifecycleAdapter = {
3887
3665
  async onAccountConfigChanged({ prevCfg, nextCfg, accountId, runtime }) {
3666
+ await refuseRejectedKey(prevCfg, nextCfg, accountId, runtime);
3888
3667
  const wasEnabled = isAccountEnabled(prevCfg, accountId);
3889
3668
  const isEnabled = isAccountEnabled(nextCfg, accountId);
3890
3669
  if (wasEnabled === isEnabled) return;
@@ -3900,13 +3679,13 @@ var agentchatLifecycleAdapter = {
3900
3679
  for (const line of removeIntegrationFiles(nextCfg, accountId, { clearKey: false })) say(runtime, "log", `[agentchat:${accountId}] ${line}`);
3901
3680
  return;
3902
3681
  }
3903
- const handle = validHandle(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
3682
+ const handle = handleOf(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
3904
3683
  if (!handle) {
3905
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`);
3906
3685
  return;
3907
3686
  }
3908
3687
  const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
3909
- const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3688
+ const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3910
3689
  const identityLine = apiKey ? await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId }) : null;
3911
3690
  const restored = restoreIdentityLine(nextCfg, accountId, handle, identityLine);
3912
3691
  if (restored.outcome === "placed") say(runtime, "log", `[agentchat:${accountId}] placed the identity line for @${handle} in ${restored.path}`);