@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.
@@ -1,11 +1,12 @@
1
1
  import { buildChannelConfigSchema, defineChannelPluginEntry, defineSetupPluginEntry } from 'openclaw/plugin-sdk/channel-core';
2
2
  import { setAccountEnabledInConfigSection, deleteAccountFromConfigSection } from 'openclaw/plugin-sdk/channel-plugin-common';
3
3
  import { setSetupChannelEnabled, WizardCancelledError } from 'openclaw/plugin-sdk/setup';
4
- import { integration, AgentChatClient, AgentChatError, RateLimitedError, RealtimeClient } from 'agentchatme';
4
+ import { createHash } from 'crypto';
5
+ import { integration, AgentChatClient, ConnectionError, RealtimeClient } from 'agentchatme';
6
+ import { WAKE_MODE_ENV, LEGACY_WAKE_MODE_ENV, readWakeModeFromEnv, readLegacyReplyGateFailOpenFromEnv, LEGACY_REPLY_GATE_FAIL_OPEN_ENV, readReplyGateTimeoutMsFromEnv, API_KEY_ENV, readReplyGateEnabledFromEnv } from './credentials/read-env.js';
5
7
  import { readApiKeyFromEnv } from './credentials/read-env.js';
6
8
  import * as fs from 'fs';
7
9
  import * as path2 from 'path';
8
- import { WAKE_MODE_ENV, LEGACY_WAKE_MODE_ENV, readWakeModeFromEnv, readLegacyReplyGateFailOpenFromEnv, LEGACY_REPLY_GATE_FAIL_OPEN_ENV, readReplyGateTimeoutMsFromEnv, API_KEY_ENV, readReplyGateEnabledFromEnv } from './credentials/read-env.js';
9
10
  import { resolveBoundAgentId, resolveOpenClawDefaultAgentId, resolveOpenClawStateDir } from './openclaw-layout.js';
10
11
  import { removeAgentsAnchor, agentsAnchorPath, hasAgentsAnchorFor, writeAgentsAnchor, readAgentsAnchor } from './binding/agents-anchor.js';
11
12
  import { z } from 'zod';
@@ -106,7 +107,7 @@ function applyAgentchatAccountPatch(cfg, accountId, patch) {
106
107
  }
107
108
 
108
109
  // src/version.ts
109
- var PACKAGE_VERSION = "0.10.1";
110
+ var PACKAGE_VERSION = "0.11.0";
110
111
 
111
112
  // src/client-identity.ts
112
113
  var AGENTCHAT_CLIENT_NAME = "openclaw";
@@ -115,219 +116,6 @@ var AGENTCHAT_CLIENT_IDENTITY = {
115
116
  version: PACKAGE_VERSION
116
117
  };
117
118
 
118
- // src/setup-client.ts
119
- var DEFAULT_API_BASE = "https://api.agentchat.me";
120
- var DEFAULT_TIMEOUT_MS = 1e4;
121
- async function validateApiKey(apiKey, opts = {}) {
122
- if (!apiKey || typeof apiKey !== "string") {
123
- return { ok: false, reason: "unauthorized", message: "API key is empty" };
124
- }
125
- const client = new AgentChatClient({
126
- apiKey,
127
- baseUrl: apiBaseOf(opts.apiBase),
128
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
129
- timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
130
- retry: ONE_ATTEMPT,
131
- ...opts.fetch ? { fetch: opts.fetch } : {}
132
- });
133
- let me;
134
- try {
135
- me = await client.getMe();
136
- } catch (err) {
137
- const failure = describeFailure(err);
138
- if (failure.kind === "network") {
139
- const unreachable = failure.timedOut || /ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(failure.message);
140
- return {
141
- ok: false,
142
- reason: unreachable ? "unreachable" : "network-error",
143
- message: `agentchat: GET /v1/agents/me failed: ${failure.message}`
144
- };
145
- }
146
- const status = failure.status;
147
- if (status === 401) return { ok: false, reason: "unauthorized", status, message: "API key is invalid or revoked" };
148
- if (status === 403) return { ok: false, reason: "forbidden", status, message: "API key lacks permission to read /agents/me" };
149
- if (status === 410) return { ok: false, reason: "deleted", status, message: "Agent account has been deleted" };
150
- return { ok: false, reason: "server-error", status, message: `AgentChat API returned ${status}` };
151
- }
152
- const body = asRecord(me);
153
- const email = typeof body?.email === "string" ? body.email : typeof body?.email_masked === "string" ? body.email_masked : null;
154
- if (!body || typeof body.handle !== "string" || email === null || typeof body.created_at !== "string") {
155
- return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/me returned an unrecognized shape" };
156
- }
157
- return {
158
- ok: true,
159
- agent: {
160
- handle: body.handle,
161
- displayName: typeof body.display_name === "string" ? body.display_name : null,
162
- email,
163
- createdAt: body.created_at
164
- }
165
- };
166
- }
167
- async function registerAgentStart(input, opts = {}) {
168
- let data;
169
- try {
170
- data = await AgentChatClient.register({
171
- email: input.email,
172
- handle: input.handle,
173
- ...input.displayName !== void 0 ? { display_name: input.displayName } : {},
174
- ...input.description !== void 0 ? { description: input.description } : {},
175
- baseUrl: apiBaseOf(opts.apiBase),
176
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
177
- });
178
- } catch (err) {
179
- const failure = describeFailure(err);
180
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
181
- const { status, code, message } = failure;
182
- if (status === 400 && code === "INVALID_HANDLE") return { ok: false, reason: "invalid-handle", message, status };
183
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
184
- if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
185
- const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
186
- if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
187
- if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
188
- if (status >= 500 || code === "OTP_FAILED") return { ok: false, reason: "otp-failed", message, status };
189
- return { ok: false, reason: "server-error", status, message };
190
- }
191
- const pendingId = asRecord(data)?.pending_id;
192
- if (typeof pendingId !== "string") {
193
- return { ok: false, reason: "server-error", status: 200, message: "AgentChat /register returned no pending_id" };
194
- }
195
- return { ok: true, pendingId };
196
- }
197
- async function registerAgentVerify(input, opts = {}) {
198
- let verified;
199
- try {
200
- verified = await AgentChatClient.verify(input.pendingId, input.code, {
201
- baseUrl: apiBaseOf(opts.apiBase),
202
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
203
- });
204
- } catch (err) {
205
- const failure = describeFailure(err);
206
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
207
- const { status, code, message } = failure;
208
- if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
209
- if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
210
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
211
- if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
212
- const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
213
- if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
214
- if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
215
- return { ok: false, reason: "server-error", status, message };
216
- }
217
- const agent = asRecord(verified.agent);
218
- if (typeof verified.apiKey !== "string" || !agent || typeof agent.handle !== "string" || typeof agent.email !== "string" || typeof agent.created_at !== "string") {
219
- return { ok: false, reason: "unexpected-shape", status: 201, message: "AgentChat /register/verify returned an unrecognized shape" };
220
- }
221
- return {
222
- ok: true,
223
- apiKey: verified.apiKey,
224
- agent: {
225
- handle: agent.handle,
226
- displayName: typeof agent.display_name === "string" ? agent.display_name : null,
227
- email: agent.email,
228
- createdAt: agent.created_at
229
- }
230
- };
231
- }
232
- async function recoverAgentStart(input, opts = {}) {
233
- let data;
234
- try {
235
- data = await AgentChatClient.recover(input.email, {
236
- handle: input.handle,
237
- baseUrl: apiBaseOf(opts.apiBase),
238
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
239
- });
240
- } catch (err) {
241
- const failure = describeFailure(err);
242
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
243
- const { status, code, message: message2 } = failure;
244
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message: message2, status };
245
- if (status === 429) return { ok: false, reason: "rate-limited", message: message2, status, retryAfterSeconds: failure.retryAfterSeconds };
246
- return { ok: false, reason: "server-error", status, message: message2 };
247
- }
248
- const body = asRecord(data);
249
- const message = typeof body?.message === "string" ? body.message : "status 200";
250
- if (typeof body?.pending_id !== "string") {
251
- return {
252
- ok: false,
253
- reason: "unexpected-shape",
254
- status: 200,
255
- message: "AgentChat did not start a recovery (no pending_id in the response). Check that the email is the one this agent registered with."
256
- };
257
- }
258
- return { ok: true, pendingId: body.pending_id, message };
259
- }
260
- async function recoverAgentVerify(input, opts = {}) {
261
- let recovered;
262
- try {
263
- recovered = await AgentChatClient.recoverVerify(input.pendingId, input.code, {
264
- baseUrl: apiBaseOf(opts.apiBase),
265
- clientIdentity: AGENTCHAT_CLIENT_IDENTITY
266
- });
267
- } catch (err) {
268
- const failure = describeFailure(err);
269
- if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
270
- const { status, code, message } = failure;
271
- if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
272
- if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
273
- if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
274
- if (status === 409 && code === "HANDLE_REQUIRED") {
275
- return { ok: false, reason: "handle-required", message, status, handles: readHandleList(failure.details) };
276
- }
277
- if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
278
- return { ok: false, reason: "server-error", status, message };
279
- }
280
- if (typeof recovered.apiKey !== "string" || typeof recovered.handle !== "string") {
281
- return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/recover/verify returned an unrecognized shape" };
282
- }
283
- return { ok: true, apiKey: recovered.apiKey, handle: recovered.handle };
284
- }
285
- function classifyEmailPolicyRejection(code) {
286
- if (code === "EMAIL_LIMIT_REACHED" || code === "EMAIL_TAKEN") return "email-limit-reached";
287
- if (code === "EMAIL_EXHAUSTED") return "email-exhausted";
288
- return void 0;
289
- }
290
- function readPolicyLimit(details) {
291
- if (!details || typeof details !== "object") return void 0;
292
- const limit = details.limit;
293
- return typeof limit === "number" && Number.isInteger(limit) && limit > 0 ? limit : void 0;
294
- }
295
- function readHandleList(details) {
296
- if (!details || typeof details !== "object") return [];
297
- const handles = details.handles;
298
- if (!Array.isArray(handles)) return [];
299
- return handles.filter((h) => typeof h === "string" && h.length > 0);
300
- }
301
- var ONE_ATTEMPT = { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 };
302
- function apiBaseOf(apiBase) {
303
- return (apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, "");
304
- }
305
- function describeFailure(err) {
306
- if (err instanceof AgentChatError) {
307
- const raw = asRecord(asRecord(err.details)?.body);
308
- const code = typeof raw?.code === "string" ? raw.code : String(err.code ?? "");
309
- const message2 = raw ? typeof raw.message === "string" ? raw.message : `status ${err.status}` : err.message || `status ${err.status}`;
310
- const retryAfterMs = err instanceof RateLimitedError ? err.retryAfterMs : null;
311
- return {
312
- kind: "http",
313
- status: err.status,
314
- code,
315
- message: message2,
316
- details: raw ? raw.details : err.details,
317
- ...typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) ? { retryAfterSeconds: Math.ceil(retryAfterMs / 1e3) } : {}
318
- };
319
- }
320
- const message = err instanceof Error ? err.message : String(err);
321
- const timedOut = err instanceof Error && err.name === "AbortError" || /timed out|abort/i.test(message);
322
- return { kind: "network", message, timedOut };
323
- }
324
- function networkMessage(failure) {
325
- return failure.timedOut ? "request timed out" : failure.message;
326
- }
327
- function asRecord(value) {
328
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
329
- }
330
-
331
119
  // src/integration/turn.ts
332
120
  var MCP_SERVER_NAME = "agentchat";
333
121
  var MCP_TOOL_DELIMITER = "__";
@@ -364,8 +152,8 @@ function sanitizeKeyPart(value) {
364
152
  // src/integration/mcp.ts
365
153
  var MCP_PATH = "/mcp";
366
154
  var AUTH_HEADER_TEMPLATE = `Bearer \${${API_KEY_ENV}}`;
367
- var DEFAULT_API_BASE2 = "https://api.agentchat.me";
368
- function hostedMcpUrl(apiBase = DEFAULT_API_BASE2) {
155
+ var DEFAULT_API_BASE = "https://api.agentchat.me";
156
+ function hostedMcpUrl(apiBase = DEFAULT_API_BASE) {
369
157
  return `${apiBase.replace(/\/+$/, "")}${MCP_PATH}`;
370
158
  }
371
159
  var CLIENT_HEADER = "X-AgentChat-Client";
@@ -375,14 +163,14 @@ function clientIdentityHeaders() {
375
163
  function clientIdentityText() {
376
164
  return `${CLIENT_HEADER}: ${AGENTCHAT_CLIENT_NAME}`;
377
165
  }
378
- function hostedMcpServerEntry(apiBase = DEFAULT_API_BASE2) {
166
+ function hostedMcpServerEntry(apiBase = DEFAULT_API_BASE) {
379
167
  return {
380
168
  url: hostedMcpUrl(apiBase),
381
169
  transport: "streamable-http",
382
170
  headers: { Authorization: AUTH_HEADER_TEMPLATE, ...clientIdentityHeaders() }
383
171
  };
384
172
  }
385
- function describeMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
173
+ function describeMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
386
174
  const servers = cfg?.mcp?.servers;
387
175
  if (!servers || typeof servers !== "object" || Array.isArray(servers)) return "missing";
388
176
  const entry = servers[MCP_SERVER_NAME];
@@ -415,7 +203,7 @@ function describeMcpIdentity(cfg) {
415
203
  const client = clients[0];
416
204
  return clients.length === 1 && typeof client === "string" && client.trim().toLowerCase() === want[CLIENT_HEADER] ? "current" : "missing";
417
205
  }
418
- function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
206
+ function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
419
207
  const state = describeMcpEntry(cfg, apiBase, apiKey);
420
208
  const base = cfg ?? {};
421
209
  if (state === "user_managed") return { cfg: base, outcome: "user_managed" };
@@ -428,7 +216,7 @@ function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
428
216
  mcp.servers = servers;
429
217
  return { cfg: { ...base, mcp }, outcome: state === "ours" ? "updated" : "added" };
430
218
  }
431
- function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE2) {
219
+ function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE) {
432
220
  const headers = isRecord(entry.headers) ? entry.headers : {};
433
221
  const kept = Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== CLIENT_HEADER.toLowerCase()));
434
222
  return {
@@ -438,7 +226,7 @@ function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE2) {
438
226
  headers: { ...kept, ...clientIdentityHeaders() }
439
227
  };
440
228
  }
441
- function upgradeHostedMcpEntryInPlace(draft, apiBase = DEFAULT_API_BASE2, apiKey) {
229
+ function upgradeHostedMcpEntryInPlace(draft, apiBase = DEFAULT_API_BASE, apiKey) {
442
230
  if (describeMcpEntry(draft, apiBase, apiKey) !== "ours" || describeMcpIdentity(draft) === "current") return false;
443
231
  const servers = draft.mcp.servers;
444
232
  const existing = servers[MCP_SERVER_NAME];
@@ -455,7 +243,7 @@ var NoChange = class extends Error {
455
243
  };
456
244
  var NIX_MODE_ERROR_CODE = "OPENCLAW_NIX_MODE_CONFIG_IMMUTABLE";
457
245
  async function refreshHostedMcpEntry(params) {
458
- const apiBase = params.apiBase ?? DEFAULT_API_BASE2;
246
+ const apiBase = params.apiBase ?? DEFAULT_API_BASE;
459
247
  if (describeMcpEntry(params.liveCfg, apiBase, params.apiKey) !== "ours") return { outcome: "not_ours" };
460
248
  if (describeMcpIdentity(params.liveCfg) === "current") return { outcome: "current" };
461
249
  const mutate = params.config?.mutateConfigFile;
@@ -492,7 +280,7 @@ function headerValues(headers, name) {
492
280
  const wanted = name.toLowerCase();
493
281
  return Object.entries(headers).filter(([key]) => key.toLowerCase() === wanted).map(([, value]) => value);
494
282
  }
495
- function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
283
+ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
496
284
  if (describeMcpEntry(cfg, apiBase, apiKey) !== "ours") return { cfg, removed: false };
497
285
  const mcp = { ...cfg.mcp ?? {} };
498
286
  const servers = { ...mcp.servers ?? {} };
@@ -502,7 +290,7 @@ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
502
290
  }
503
291
  async function probeHostedMcp(params) {
504
292
  const result = await integration.probeHostedTools({
505
- apiBase: params.apiBase ?? DEFAULT_API_BASE2,
293
+ apiBase: params.apiBase ?? DEFAULT_API_BASE,
506
294
  apiKey: params.apiKey,
507
295
  clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
508
296
  ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
@@ -521,6 +309,40 @@ async function probeHostedMcp(params) {
521
309
  };
522
310
  }
523
311
 
312
+ // src/setup-client.ts
313
+ var KEY_CHECK_TIMEOUT_MS = 1e4;
314
+ function accountCallOptions(params = {}) {
315
+ return {
316
+ clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
317
+ apiBase: (params.apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, ""),
318
+ ...params.fetch ? { fetch: params.fetch } : {},
319
+ ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {}
320
+ };
321
+ }
322
+ var KeyCheckUnanswered = class extends Error {
323
+ constructor(message) {
324
+ super(message);
325
+ this.name = "KeyCheckUnanswered";
326
+ }
327
+ };
328
+ async function checkApiKey(apiKey, params = {}) {
329
+ let status;
330
+ const send = params.fetch ?? ((input, init) => globalThis.fetch(input, init));
331
+ const observed = (async (input, init) => {
332
+ const response = await send(input, init);
333
+ status = response.status;
334
+ return response;
335
+ });
336
+ const check = await integration.account.checkKey(
337
+ apiKey,
338
+ accountCallOptions({ timeoutMs: KEY_CHECK_TIMEOUT_MS, ...params, fetch: observed })
339
+ );
340
+ if (!check.ok && status !== 401 && status !== 403) {
341
+ throw new KeyCheckUnanswered(`AgentChat answered ${status ?? "without a status"} (${check.code}): ${check.message}`);
342
+ }
343
+ return check;
344
+ }
345
+
524
346
  // src/integration/runtime-holder.ts
525
347
  var current = null;
526
348
  function isUsablePluginRuntime(runtime) {
@@ -602,55 +424,266 @@ async function watchRunUntilEnded(options) {
602
424
  if (elapsedMs < MIN_WAIT_SPACING_MS) await sleep(MIN_WAIT_SPACING_MS - elapsedMs);
603
425
  }
604
426
  }
605
- function countAgentChatCalls(messages, runId) {
427
+ function countAgentChatCalls(messages, runId, host = {}) {
606
428
  if (messages.length === 0) return null;
607
- let recognised = false;
608
- let made = 0;
609
- let failed = 0;
429
+ const rows = [];
610
430
  for (const row of messages) {
611
431
  const message = unwrapMessage(row);
612
- if (!message) continue;
613
- const role = message.role;
614
- if (role === "assistant" || role === "user") recognised = true;
615
- if (role !== "toolResult" && role !== "tool") continue;
616
- recognised = true;
617
- const meta = asRecord2(message.__openclaw);
618
- if (runId && typeof meta?.runId === "string" && meta.runId !== runId) continue;
619
- if (!isAgentChatToolResult(message)) continue;
432
+ if (!message) return null;
433
+ rows.push(message);
434
+ }
435
+ if (!coversWholeSession(rows)) return null;
436
+ if (runId && rows.some((row) => isOtherRun(row, runId))) return null;
437
+ const calls = assistantToolCalls(rows);
438
+ const nested = rows.flatMap((row) => {
439
+ const call = nestedCallOf(row);
440
+ return call ? [call] : [];
441
+ });
442
+ const release = releaseOf(rows, calls, nested, host.openclawVersion);
443
+ if (delegatedToChild(rows, calls, nested)) return null;
444
+ if (usedCodeMode(rows, calls)) {
445
+ if (!release.recordsNestedCalls) return null;
446
+ if (!codeModeScriptsCompleted(rows, calls)) return null;
447
+ }
448
+ const parents = new Set(nested.flatMap((call) => typeof call.parentToolCallId === "string" ? [call.parentToolCallId] : []));
449
+ let made = 0;
450
+ let failed = 0;
451
+ for (const message of rows) {
452
+ let verdict;
453
+ const call = nestedCallOf(message);
454
+ if (call) verdict = nestedVerdict(call);
455
+ else if (message.role !== "toolResult" && message.role !== "tool") continue;
456
+ else if (typeof message.toolCallId === "string" && parents.has(message.toolCallId)) continue;
457
+ else verdict = callVerdict(message, calls, release);
458
+ if (verdict === "not_agentchat") continue;
459
+ if (verdict === "unknown") return null;
620
460
  made += 1;
621
- if (message.isError === true) failed += 1;
461
+ if (verdict === "failed") failed += 1;
622
462
  }
623
- return recognised ? { made, failed } : null;
463
+ return { made, failed };
624
464
  }
625
465
  async function readAgentChatCalls(runtime, sessionKey, runId) {
626
466
  if (!runtime || typeof runtime.subagent?.getSessionMessages !== "function") return null;
627
467
  try {
628
468
  const result = await runtime.subagent.getSessionMessages({ sessionKey, limit: TRANSCRIPT_READ_LIMIT });
629
469
  const messages = result?.messages;
630
- return Array.isArray(messages) ? countAgentChatCalls(messages, runId) : null;
470
+ const openclawVersion = typeof runtime.version === "string" ? runtime.version : void 0;
471
+ return Array.isArray(messages) ? countAgentChatCalls(messages, runId, openclawVersion ? { openclawVersion } : {}) : null;
631
472
  } catch {
632
473
  return null;
633
474
  }
634
475
  }
635
476
  var TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
636
- function isAgentChatToolResult(message) {
637
- const toolName = typeof message.toolName === "string" ? message.toolName : typeof message.name === "string" ? message.name : "";
638
- if (toolName.startsWith(TOOL_PREFIX)) return true;
639
- const tool = asRecord2(asRecord2(message.details)?.tool);
640
- if (!tool) return false;
477
+ var DISPATCHER_TOOL_NAMES = /* @__PURE__ */ new Set(["tool_call", "dispatch_action"]);
478
+ var FAILURE_STATUSES = /* @__PURE__ */ new Set([
479
+ "error",
480
+ "failed",
481
+ "failure",
482
+ "timeout",
483
+ "timed_out",
484
+ "blocked",
485
+ "denied",
486
+ "forbidden",
487
+ "unavailable",
488
+ "approval-unavailable",
489
+ "disabled",
490
+ "aborted",
491
+ "cancelled",
492
+ "canceled",
493
+ "killed",
494
+ "invalid"
495
+ ]);
496
+ function coversWholeSession(rows) {
497
+ if (asRecord(rows[0]?.__openclaw)?.seq !== 1) return false;
498
+ return rows.every((row) => {
499
+ const meta = asRecord(row.__openclaw);
500
+ return meta?.kind !== "compaction" && meta?.kind !== "reset" && meta?.truncated !== true;
501
+ });
502
+ }
503
+ function isOtherRun(row, runId) {
504
+ const tagged = asRecord(row.__openclaw)?.runId ?? nestedCallOf(row)?.runId;
505
+ return typeof tagged === "string" && tagged.trim().length > 0 && tagged.trim() !== runId;
506
+ }
507
+ var CODE_MODE_ONLY_TOOL_NAMES = /* @__PURE__ */ new Set(["tool_search_code", "wait"]);
508
+ function usedCodeMode(rows, calls) {
509
+ return [...calls.values()].some(isCodeModeCall) || rows.some((row) => isCodeModeResult(row, calls));
510
+ }
511
+ function codeModeScriptsCompleted(rows, calls) {
512
+ const results = /* @__PURE__ */ new Map();
513
+ for (const row of rows) {
514
+ if ((row.role === "toolResult" || row.role === "tool") && typeof row.toolCallId === "string") results.set(row.toolCallId, row);
515
+ }
516
+ const completed = (row) => row !== void 0 && row.isError !== true && asRecord(row.details)?.status === "completed";
517
+ for (const [id, call] of calls) {
518
+ if (isCodeModeCall(call) && !completed(results.get(id))) return false;
519
+ }
520
+ return rows.every((row) => !isCodeModeResult(row, calls) || completed(row));
521
+ }
522
+ function isCodeModeCall(call) {
523
+ const name = typeof call.name === "string" ? call.name : "";
524
+ return CODE_MODE_ONLY_TOOL_NAMES.has(name) || name === "exec" && typeof callArguments(call)?.code === "string";
525
+ }
526
+ function isCodeModeResult(row, calls) {
527
+ if (row.role !== "toolResult" && row.role !== "tool") return false;
528
+ const name = toolNameOf(row);
529
+ return CODE_MODE_ONLY_TOOL_NAMES.has(name) || name === "exec" && !isShellExecResult(row, calls);
530
+ }
531
+ function isShellExecResult(row, calls) {
532
+ const call = typeof row.toolCallId === "string" ? calls.get(row.toolCallId) : void 0;
533
+ const args = callArguments(call);
534
+ if (!args || typeof args.command !== "string" || args.code !== void 0) return false;
535
+ const details = asRecord(row.details);
536
+ if (!details || details.telemetry !== void 0) return false;
537
+ return details.exitCode !== void 0 || typeof details.durationMs === "number" || typeof details.aggregated === "string";
538
+ }
539
+ function assistantToolCalls(rows) {
540
+ const calls = /* @__PURE__ */ new Map();
541
+ for (const row of rows) {
542
+ if (row.role !== "assistant" || !Array.isArray(row.content)) continue;
543
+ for (const block of row.content) {
544
+ const call = asRecord(block);
545
+ if (call?.type === "toolCall" && typeof call.id === "string") calls.set(call.id, call);
546
+ }
547
+ }
548
+ return calls;
549
+ }
550
+ var TRUSTED_RELEASE = "2026.9.3";
551
+ function releaseOf(rows, calls, nested, version) {
552
+ if (version !== void 0 && isOpenClawVersion(version)) {
553
+ const trusted = openclawVersionAtLeast(version, TRUSTED_RELEASE);
554
+ return { recordsNestedCalls: trusted, marksFailedRows: trusted };
555
+ }
556
+ const parents = new Set(nested.map((call) => call.parentToolCallId));
557
+ 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));
558
+ return { recordsNestedCalls: nested.length > 0 || dispatchAction, marksFailedRows: dispatchAction };
559
+ }
560
+ var OPENCLAW_VERSION = /^(\d+)\.(\d+)\.(\d+)(-.+)?$/;
561
+ function isOpenClawVersion(value) {
562
+ return OPENCLAW_VERSION.test(value.trim());
563
+ }
564
+ function openclawVersionAtLeast(a, b) {
565
+ const parse = (v) => {
566
+ const match = OPENCLAW_VERSION.exec(v.trim());
567
+ return match ? { parts: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] !== void 0 } : null;
568
+ };
569
+ const [x, y] = [parse(a), parse(b)];
570
+ if (!x || !y) return false;
571
+ for (let i = 0; i < 3; i += 1) {
572
+ const d = (x.parts[i] ?? 0) - (y.parts[i] ?? 0);
573
+ if (d !== 0) return d > 0;
574
+ }
575
+ return !x.pre || y.pre;
576
+ }
577
+ function toolNameOf(row) {
578
+ return typeof row.toolName === "string" ? row.toolName : typeof row.name === "string" ? row.name : "";
579
+ }
580
+ var NESTED_TOOL_ACTIVITY = "openclaw.nested-tool.v1";
581
+ function nestedCallOf(row) {
582
+ if (row.role !== "custom" || row.customType !== NESTED_TOOL_ACTIVITY) return null;
583
+ return asRecord(row.details);
584
+ }
585
+ function nestedVerdict(call) {
586
+ const toolName = typeof call.toolName === "string" ? call.toolName : "";
587
+ if (!toolName.startsWith(TOOL_PREFIX)) return "not_agentchat";
588
+ const result = asRecord(call.result);
589
+ if (call.isError === true || result !== null && failedResult(result.isError, asRecord(result.details))) return "failed";
590
+ return call.isError === false ? "ok" : "unknown";
591
+ }
592
+ var OTHER_SESSION_TOOLS = /* @__PURE__ */ new Set(["sessions_spawn", "sessions_send"]);
593
+ function delegatedToChild(rows, calls, nested) {
594
+ const names = (value) => typeof value === "string" && OTHER_SESSION_TOOLS.has(value);
595
+ for (const call of calls.values()) {
596
+ if (names(call.name)) return true;
597
+ if (typeof call.name === "string" && DISPATCHER_TOOL_NAMES.has(call.name) && names(dispatchTarget(call))) return true;
598
+ }
599
+ if (nested.some((call) => names(call.toolName))) return true;
600
+ return rows.some((row) => names(toolNameOf(row)) || names(asRecord(asRecord(row.details)?.tool)?.name));
601
+ }
602
+ function callVerdict(message, calls, release) {
603
+ const toolName = toolNameOf(message);
604
+ const details = asRecord(message.details);
605
+ if (toolName.startsWith(TOOL_PREFIX)) return directVerdict(message.isError, details);
606
+ const entry = asRecord(details?.tool);
607
+ if (entry && isAgentChatEntry(entry)) return dispatchedVerdict(message.isError, details);
608
+ if (!DISPATCHER_TOOL_NAMES.has(toolName) || entry) return "not_agentchat";
609
+ const target = dispatchTarget(typeof message.toolCallId === "string" ? calls.get(message.toolCallId) : void 0);
610
+ if (target === null) return "unknown";
611
+ if (!target.startsWith(TOOL_PREFIX)) return "not_agentchat";
612
+ if (failedResult(message.isError, details)) return "failed";
613
+ if (release.marksFailedRows && isTruncated(details) && message.isError === false && details?.status === void 0) return "ok";
614
+ return "unknown";
615
+ }
616
+ function isTruncated(details) {
617
+ return details?.persistedDetailsTruncated === true;
618
+ }
619
+ function directVerdict(isError, details) {
620
+ if (failedResult(isError, details)) return "failed";
621
+ if (isError !== false) return "unknown";
622
+ if (isTruncated(details)) return details?.status === void 0 && wasHostedResult(details) ? "ok" : "unknown";
623
+ return isHostedSuccessDetails(details) ? "ok" : "unknown";
624
+ }
625
+ function wasHostedResult(details) {
626
+ const keys = Array.isArray(details?.originalDetailKeys) ? details.originalDetailKeys : [];
627
+ return keys.includes("mcpServer") && (keys.includes("mcpTool") || keys.includes("mcpOperation"));
628
+ }
629
+ function dispatchedVerdict(isError, details) {
630
+ const result = asRecord(details?.result);
631
+ if (failedResult(isError, details)) return "failed";
632
+ if (result && failedResult(result.isError, asRecord(result.details))) return "failed";
633
+ const ok = isError === false && details?.status === void 0 && isHostedSuccessDetails(asRecord(result?.details));
634
+ return ok ? "ok" : "unknown";
635
+ }
636
+ function failedResult(isError, details) {
637
+ return isError === true || detailsSayFailed(details);
638
+ }
639
+ function detailsSayFailed(details) {
640
+ if (!details) return false;
641
+ if (details.ok === false || details.success === false) return true;
642
+ const status = typeof details.status === "string" ? details.status.trim().toLowerCase() : "";
643
+ const explicitlyOk = details.ok === true || details.success === true;
644
+ if (FAILURE_STATUSES.has(status) && !explicitlyOk) return true;
645
+ if (details.timedOut === true || Boolean(details.error)) return true;
646
+ if (status === "completed") return false;
647
+ const exitCode = details.exitCode;
648
+ return typeof exitCode === "number" && Number.isFinite(exitCode) && exitCode !== 0;
649
+ }
650
+ function isHostedSuccessDetails(details) {
651
+ if (!details || details.mcpServer !== MCP_SERVER_NAME || details.status !== void 0) return false;
652
+ return nonEmpty(details.mcpTool) !== void 0 || nonEmpty(details.mcpOperation) !== void 0;
653
+ }
654
+ function isAgentChatEntry(tool) {
641
655
  if (typeof tool.name === "string" && tool.name.startsWith(TOOL_PREFIX)) return true;
642
656
  if (tool.sourceName === MCP_SERVER_NAME) return true;
643
- const mcp = asRecord2(tool.mcp);
657
+ const mcp = asRecord(tool.mcp);
644
658
  return mcp?.serverName === MCP_SERVER_NAME;
645
659
  }
660
+ function dispatchTarget(call) {
661
+ const record = callArguments(call);
662
+ const selector = nonEmpty(record?.id) ?? nonEmpty(record?.toolId) ?? nonEmpty(record?.name);
663
+ if (!selector) return null;
664
+ const trimmed = selector.trim();
665
+ return trimmed.slice(trimmed.lastIndexOf(":") + 1);
666
+ }
667
+ function callArguments(call) {
668
+ if (!call) return null;
669
+ let args = call.arguments;
670
+ if (typeof args === "string") {
671
+ try {
672
+ args = JSON.parse(args);
673
+ } catch {
674
+ return null;
675
+ }
676
+ }
677
+ return asRecord(args);
678
+ }
646
679
  function unwrapMessage(row) {
647
- const record = asRecord2(row);
680
+ const record = asRecord(row);
648
681
  if (!record) return null;
649
682
  if (typeof record.role === "string") return record;
650
- const inner = asRecord2(record.message);
683
+ const inner = asRecord(record.message);
651
684
  return inner && typeof inner.role === "string" ? inner : null;
652
685
  }
653
- function asRecord2(value) {
686
+ function asRecord(value) {
654
687
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
655
688
  }
656
689
  function nonEmpty(value) {
@@ -906,7 +939,7 @@ function applyIntegrationConfig(cfg, params) {
906
939
  const changes = [];
907
940
  let next = cfg;
908
941
  const bareHandle = (params.handle ?? "").trim().replace(/^@/, "");
909
- if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle && isValidHandleShape(bareHandle)) {
942
+ if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle) {
910
943
  next = applyAgentchatAccountPatch(next, params.accountId, { agentHandle: bareHandle });
911
944
  changes.push(`channels.agentchat${params.accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID ? "" : `.accounts.${params.accountId}`}.agentHandle = ${bareHandle}`);
912
945
  }
@@ -1138,8 +1171,10 @@ function textsCachePath(accountId, stateDir) {
1138
1171
  return path2.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE);
1139
1172
  }
1140
1173
  function spellTextsForOpenClaw(texts) {
1174
+ const newer = texts;
1141
1175
  return {
1142
1176
  ...texts,
1177
+ ...typeof newer.reply_turn_template === "string" ? { reply_turn_template: spellToolsForOpenClaw(newer.reply_turn_template) } : {},
1143
1178
  wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),
1144
1179
  invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),
1145
1180
  identity_line: spellToolsForOpenClaw(texts.identity_line),
@@ -1239,57 +1274,15 @@ function getClient({ accountId, config, options }) {
1239
1274
 
1240
1275
  // src/channel.wizard.ts
1241
1276
  var JUST_REGISTERED_SENTINEL = "_agentchatJustRegistered";
1242
- var HANDLE_PATTERN2 = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
1243
- var HANDLE_MIN_LENGTH = 3;
1244
- var HANDLE_MAX_LENGTH = 30;
1245
- var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1246
- function isValidHandleShape2(value) {
1247
- return value.length >= HANDLE_MIN_LENGTH && value.length <= HANDLE_MAX_LENGTH && HANDLE_PATTERN2.test(value);
1248
- }
1249
- var OTP_PATTERN = /^\d{6}$/;
1277
+ var LABELS = {
1278
+ ...integration.account.DEFAULT_LABELS,
1279
+ handle: "Handle (your @name on AgentChat)"
1280
+ };
1250
1281
  function hasConfiguredKey(cfg, accountId) {
1251
1282
  return isApiKeyPresent(readAgentchatConfigField(cfg, accountId, "apiKey"));
1252
1283
  }
1253
- var MAX_START_RETRIES = 5;
1254
- async function promptEmail(prompter, opts = {}) {
1255
- return (await prompter.text({
1256
- message: opts.message ?? "Email \u2014 receives a 6-digit verification code",
1257
- placeholder: "you@example.com",
1258
- validate: (value) => {
1259
- const trimmed = value.trim();
1260
- if (!trimmed) return "Email is required";
1261
- if (!EMAIL_PATTERN.test(trimmed)) return "Not a valid email format";
1262
- return void 0;
1263
- }
1264
- })).trim();
1265
- }
1266
- async function promptHandle(prompter, opts = {}) {
1267
- return (await prompter.text({
1268
- message: opts.message ?? "Choose a handle (your @name on AgentChat)",
1269
- placeholder: "3\u201330 chars, lowercase a-z, 0-9, hyphens, starts with a letter",
1270
- ...opts.initialValue ? { initialValue: opts.initialValue } : {},
1271
- validate: (value) => {
1272
- const trimmed = value.trim();
1273
- if (!trimmed) return "Handle is required";
1274
- if (trimmed.length < HANDLE_MIN_LENGTH || trimmed.length > HANDLE_MAX_LENGTH) {
1275
- return `Length must be ${HANDLE_MIN_LENGTH}\u2013${HANDLE_MAX_LENGTH} chars (you entered ${trimmed.length})`;
1276
- }
1277
- if (!/^[a-z]/.test(trimmed)) return "Must start with a lowercase letter";
1278
- if (/[^a-z0-9-]/.test(trimmed)) {
1279
- return "Only lowercase letters, digits, and hyphens \u2014 no underscores, dots, or symbols";
1280
- }
1281
- if (trimmed.includes("--")) return "No consecutive hyphens";
1282
- if (trimmed.endsWith("-")) return "Cannot end with a hyphen";
1283
- return void 0;
1284
- }
1285
- })).trim();
1286
- }
1287
- async function promptDisplayName(prompter) {
1288
- return (await prompter.text({
1289
- message: "Display name (shown next to your @handle)",
1290
- placeholder: "e.g. Anton, Builder Bot, Sasha",
1291
- validate: () => void 0
1292
- })).trim();
1284
+ function nonEmpty2(value) {
1285
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
1293
1286
  }
1294
1287
  async function runChangeApiBaseFlow(params) {
1295
1288
  const { cfg, accountId, prompter } = params;
@@ -1327,388 +1320,182 @@ async function runChangeApiBaseFlow(params) {
1327
1320
  await prompter.note(`API base set to ${input}`, "Updated");
1328
1321
  return { cfg: patched };
1329
1322
  }
1330
- function describeEmailPolicyRejection(email, result) {
1331
- if (result.limit === void 0) return result.message;
1332
- 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.`;
1333
- }
1334
- async function promptEmailPolicyChoice(prompter, email, result) {
1335
- return prompter.select({
1336
- message: `${describeEmailPolicyRejection(email, result)} What next?`,
1337
- options: [
1338
- {
1339
- value: "retry",
1340
- label: "Use a different email address",
1341
- hint: "a +alias like you+agent2@example.com counts as a separate email"
1342
- },
1343
- {
1344
- value: "recover",
1345
- label: "Recover the API key of an agent this email already backs",
1346
- hint: "needs that agent\u2019s handle \u2014 a code goes to this email"
1347
- },
1348
- { value: "paste", label: "Paste a key from an existing agent" },
1349
- { value: "cancel", label: "Cancel registration" }
1350
- ],
1351
- initialValue: "retry"
1352
- });
1323
+ async function askText(prompter, message, opts = {}) {
1324
+ return (await prompter.text({
1325
+ message,
1326
+ ...opts,
1327
+ validate: (value) => value.trim() ? void 0 : "Required"
1328
+ })).trim();
1353
1329
  }
1354
- async function runRegisterFlow(params) {
1355
- const { cfg, accountId, prompter, apiBase } = params;
1356
- await prompter.note(
1357
- [
1358
- "Registration mints a new AgentChat agent identity tied to your email.",
1359
- "One email can back several agents (the server enforces the limit);",
1360
- "each one registers and verifies separately.",
1361
- "You will receive a 6-digit code to verify \u2014 check your inbox (and spam)."
1362
- ].join("\n"),
1363
- "AgentChat: register a new agent"
1364
- );
1365
- let email = await promptEmail(prompter);
1366
- let handle = await promptHandle(prompter);
1367
- const displayName = await promptDisplayName(prompter);
1368
- let startResult;
1369
- let startedOk = false;
1370
- for (let attempt = 1; attempt <= MAX_START_RETRIES; attempt += 1) {
1371
- const startSpinner = prompter.progress(
1372
- attempt === 1 ? "Sending verification code\u2026" : "Retrying\u2026"
1373
- );
1374
- try {
1375
- startResult = await registerAgentStart(
1376
- {
1377
- email,
1378
- handle,
1379
- ...displayName ? { displayName } : {}
1380
- },
1381
- { apiBase }
1382
- );
1383
- } catch (err) {
1384
- startSpinner.stop("Could not reach AgentChat");
1385
- await prompter.note(
1386
- `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
1387
- "Registration failed"
1388
- );
1389
- return "abort";
1390
- }
1391
- if (startResult.ok) {
1392
- startSpinner.stop(`Verification code sent to ${email}`);
1393
- startedOk = true;
1394
- break;
1395
- }
1396
- startSpinner.stop("Registration rejected");
1397
- switch (startResult.reason) {
1398
- case "invalid-handle":
1399
- case "handle-taken": {
1400
- 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).";
1401
- await prompter.note(`${detail} Pick a different handle and we'll try again.`, "Pick a different handle");
1402
- handle = await promptHandle(prompter);
1403
- continue;
1404
- }
1405
- case "email-limit-reached":
1406
- case "email-exhausted": {
1407
- const choice = await promptEmailPolicyChoice(prompter, email, {
1408
- reason: startResult.reason,
1409
- limit: startResult.limit,
1410
- message: startResult.message
1411
- });
1412
- if (choice === "paste") return "user-chose-paste";
1413
- if (choice === "recover") return "user-chose-recover";
1414
- if (choice === "cancel") return "abort";
1415
- email = await promptEmail(prompter);
1416
- continue;
1417
- }
1418
- case "rate-limited": {
1419
- const wait = startResult.retryAfterSeconds ? ` Try again in ${startResult.retryAfterSeconds}s.` : "";
1420
- await prompter.note(`Too many registration attempts.${wait}`, "Rate limited");
1421
- return "abort";
1422
- }
1423
- case "otp-failed": {
1424
- await prompter.note(
1425
- "The verification-code email could not be sent. Try again in a minute, or paste an existing key instead.",
1426
- "OTP delivery failed"
1427
- );
1428
- return "abort";
1429
- }
1430
- case "network-error":
1431
- case "server-error":
1432
- case "validation":
1433
- default: {
1434
- await prompter.note(describeRegisterStartError(startResult), "Could not start registration");
1435
- return "abort";
1436
- }
1330
+ var EMAIL_PLACEHOLDER = "you@example.com";
1331
+ async function askCode(prompter, label) {
1332
+ for (; ; ) {
1333
+ const code = (await prompter.text({ message: label, placeholder: "leave blank for a new code or to cancel" })).trim();
1334
+ if (code) return { answer: "value", value: code };
1335
+ const choice = await prompter.select({
1336
+ message: "What would you like to do?",
1337
+ options: [
1338
+ { value: "new_code", label: "Send a new code" },
1339
+ { value: "enter", label: "Enter the code" },
1340
+ { value: "cancel", label: "Cancel", hint: "paste an existing key instead, or leave setup" }
1341
+ ],
1342
+ initialValue: "new_code"
1343
+ });
1344
+ if (choice === "new_code") return { answer: "new_code" };
1345
+ if (choice === "cancel") return { answer: "cancel" };
1346
+ }
1347
+ }
1348
+ function askThrough(prompter) {
1349
+ return async (question) => {
1350
+ if (question.field === "new_code") {
1351
+ const yes = await prompter.confirm({ message: "Send a new code?", initialValue: true });
1352
+ return yes ? { answer: "new_code" } : { answer: "cancel" };
1353
+ }
1354
+ if (question.field === "code") return askCode(prompter, question.label ?? LABELS.code);
1355
+ const label = question.label ?? LABELS[question.field];
1356
+ const handles = (question.handles ?? []).filter((handle) => handle.length > 0);
1357
+ if (handles.length > 0) {
1358
+ const picked = await prompter.select({
1359
+ message: label,
1360
+ options: [
1361
+ ...handles.map((handle) => ({ value: handle, label: `@${handle}` })),
1362
+ { value: "", label: "Another handle" }
1363
+ ]
1364
+ });
1365
+ if (picked) return { answer: "value", value: picked };
1437
1366
  }
1438
- }
1439
- if (!startedOk || !startResult || !startResult.ok) {
1440
- await prompter.note(
1441
- "Too many attempts. Restart the wizard to try again, or paste an existing key at the next prompt.",
1442
- "Registration failed"
1443
- );
1444
- return "abort";
1445
- }
1446
- const maxCodeAttempts = 3;
1447
- let verifyResult = null;
1448
- for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
1449
- const code = (await prompter.text({
1450
- message: attempt === 1 ? "Enter the 6-digit verification code from your email" : `Verification code (attempt ${attempt}/${maxCodeAttempts})`,
1451
- placeholder: "123456",
1452
- validate: (value) => {
1453
- const trimmed = value.trim();
1454
- if (!trimmed) return "Code is required";
1455
- if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
1456
- return void 0;
1457
- }
1458
- })).trim();
1459
- const verifySpinner = prompter.progress("Verifying code\u2026");
1367
+ const typed = await askText(prompter, label, question.field === "email" ? { placeholder: EMAIL_PLACEHOLDER } : {});
1368
+ return { answer: "value", value: typed };
1369
+ };
1370
+ }
1371
+ function fetchWithProgress(prompter) {
1372
+ return (async (input, init) => {
1373
+ const progress = prompter.progress("Contacting AgentChat\u2026");
1460
1374
  try {
1461
- verifyResult = await registerAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
1462
- } catch (err) {
1463
- verifySpinner.stop("Could not reach AgentChat");
1464
- await prompter.note(
1465
- `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
1466
- "Verification failed"
1467
- );
1468
- return "abort";
1469
- }
1470
- if (verifyResult.ok) {
1471
- verifySpinner.stop(`Registered as @${verifyResult.agent.handle}`);
1472
- break;
1473
- }
1474
- verifySpinner.stop("Verification failed");
1475
- if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
1476
- await prompter.note(
1477
- "That code did not match. Check your email and try again.",
1478
- "Invalid verification code"
1479
- );
1480
- continue;
1375
+ return await globalThis.fetch(input, init);
1376
+ } finally {
1377
+ progress.stop();
1481
1378
  }
1482
- await prompter.note(describeRegisterVerifyError(verifyResult), "Registration failed");
1483
- return "abort";
1484
- }
1485
- if (!verifyResult || !verifyResult.ok) {
1486
- await prompter.note(
1487
- "Too many incorrect codes. Restart the wizard to receive a new code.",
1488
- "Registration failed"
1489
- );
1490
- return "abort";
1491
- }
1492
- const patch = { apiKey: verifyResult.apiKey };
1493
- if (isValidHandleShape2(verifyResult.agent.handle)) {
1494
- patch.agentHandle = verifyResult.agent.handle;
1495
- }
1496
- const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch);
1379
+ });
1380
+ }
1381
+ function sleepWithProgress(prompter) {
1382
+ const label = (seconds) => `Waiting ${seconds} s\u2026`;
1383
+ return (ms) => new Promise((resolve) => {
1384
+ let left = Math.ceil(ms / 1e3);
1385
+ const progress = prompter.progress(label(left));
1386
+ const tick = setInterval(() => {
1387
+ left -= 1;
1388
+ if (left > 0) progress.update(label(left));
1389
+ }, 1e3);
1390
+ setTimeout(() => {
1391
+ clearInterval(tick);
1392
+ progress.stop();
1393
+ resolve();
1394
+ }, ms);
1395
+ });
1396
+ }
1397
+ async function registerInput(prompter) {
1497
1398
  await prompter.note(
1498
1399
  [
1499
- `Handle: @${verifyResult.agent.handle}`,
1500
- `Email: ${verifyResult.agent.email}`,
1501
- `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`
1400
+ "Registration creates a new AgentChat agent tied to your email address.",
1401
+ "Your handle is the agent\u2019s @name on AgentChat. AgentChat emails you a",
1402
+ "code to confirm the address \u2014 check your inbox (and spam)."
1502
1403
  ].join("\n"),
1503
- "AgentChat account created"
1404
+ "AgentChat: register a new agent"
1504
1405
  );
1505
- return {
1506
- cfg: nextCfg,
1507
- credentialValues: {
1508
- token: verifyResult.apiKey,
1509
- [JUST_REGISTERED_SENTINEL]: "1"
1510
- }
1511
- };
1406
+ const email = await askText(prompter, LABELS.email, { placeholder: EMAIL_PLACEHOLDER });
1407
+ const handle = await askText(prompter, LABELS.handle);
1408
+ const displayName = (await prompter.text({
1409
+ message: "Display name (shown next to your @handle)",
1410
+ placeholder: "e.g. Anton, Builder Bot, Sasha"
1411
+ })).trim();
1412
+ return { email, handle, ...displayName ? { display_name: displayName } : {} };
1512
1413
  }
1513
- function describeRegisterStartError(result) {
1514
- switch (result.reason) {
1515
- case "invalid-handle":
1516
- return "That handle is not acceptable. Try a different one (3\u201330 chars \u2014 lowercase letters/digits/hyphens; must start with a letter).";
1517
- case "handle-taken":
1518
- return "That handle is already taken. Try a different one.";
1519
- case "email-limit-reached":
1520
- 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.`;
1521
- case "email-exhausted":
1522
- 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.`;
1523
- case "rate-limited": {
1524
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1525
- return `Rate limited.${wait}`;
1526
- }
1527
- case "otp-failed":
1528
- return "The verification-code email could not be sent. Try again in a minute.";
1529
- case "network-error":
1530
- case "server-error":
1531
- case "validation":
1532
- default:
1533
- return result.message;
1534
- }
1535
- }
1536
- function describeRegisterVerifyError(result) {
1537
- switch (result.reason) {
1538
- case "expired":
1539
- return "This code expired. Restart the wizard to receive a new one.";
1540
- case "invalid-code":
1541
- return "Too many incorrect codes. Restart the wizard to receive a new one.";
1542
- case "handle-taken":
1543
- return "Your chosen handle was claimed by another registration in the meantime. Restart with a different handle.";
1544
- case "email-limit-reached":
1545
- 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.`;
1546
- case "email-exhausted":
1547
- 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.`;
1548
- case "rate-limited": {
1549
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1550
- return `Rate limited.${wait}`;
1551
- }
1552
- case "network-error":
1553
- case "server-error":
1554
- case "unexpected-shape":
1555
- case "validation":
1556
- default:
1557
- return result.message;
1558
- }
1559
- }
1560
- async function runRecoverFlow(params) {
1561
- const { cfg, accountId, prompter, apiBase } = params;
1562
- const storedHandle = readAgentchatConfigField(cfg, accountId, "agentHandle");
1563
- const defaultHandle = storedHandle && isValidHandleShape2(storedHandle) ? storedHandle : void 0;
1414
+ async function recoverInput(prompter, configuredHandle) {
1564
1415
  await prompter.note(
1565
1416
  [
1566
- "Recovery re-issues the API key for ONE agent \u2014 the handle you name below.",
1567
- "You need that handle and the email it registered with; a 6-digit code",
1568
- "goes to that email. The old key stops working the moment the new one",
1569
- "is minted.",
1570
- ...defaultHandle ? ["", `@${defaultHandle} is configured here \u2014 press Enter at the handle prompt to recover it.`] : []
1417
+ "Recovery issues a new API key for an agent you registered. AgentChat",
1418
+ "emails a code to the address the agent registered with; the old key",
1419
+ "stops working once the new one is issued.",
1420
+ ...configuredHandle ? ["", `@${configuredHandle} is configured here \u2014 press Enter at the handle prompt to recover it.`] : []
1571
1421
  ].join("\n"),
1572
1422
  "AgentChat: recover a lost API key"
1573
1423
  );
1574
- const handle = await promptHandle(prompter, {
1575
- message: "Handle of the agent to recover (its @name on AgentChat)",
1576
- ...defaultHandle ? { initialValue: defaultHandle } : {}
1577
- });
1578
- const email = await promptEmail(prompter, {
1579
- message: `Email @${handle} registered with \u2014 receives a 6-digit recovery code`
1580
- });
1581
- const startSpinner = prompter.progress("Requesting recovery code\u2026");
1582
- let startResult;
1424
+ if (!configuredHandle) return {};
1425
+ const handle = (await prompter.text({ message: LABELS.handle, initialValue: configuredHandle })).trim();
1426
+ return handle ? { handle } : {};
1427
+ }
1428
+ async function notCompleted(prompter, kind) {
1429
+ await prompter.note(
1430
+ `${kind === "register" ? "Registration" : "Recovery"} was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.`,
1431
+ "Falling back to credential entry"
1432
+ );
1433
+ return void 0;
1434
+ }
1435
+ async function runAccountFlow(params) {
1436
+ const { kind, cfg, accountId, prompter } = params;
1437
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1438
+ const input = kind === "register" ? await registerInput(prompter) : await recoverInput(prompter, nonEmpty2(readAgentchatConfigField(cfg, accountId, "agentHandle")));
1439
+ let result;
1583
1440
  try {
1584
- startResult = await recoverAgentStart({ email, handle }, { apiBase });
1441
+ result = await integration.account.run({
1442
+ kind,
1443
+ input,
1444
+ labels: LABELS,
1445
+ ask: askThrough(prompter),
1446
+ show: (message) => prompter.note(message, "AgentChat"),
1447
+ sleep: sleepWithProgress(prompter),
1448
+ ...accountCallOptions({ apiBase, fetch: fetchWithProgress(prompter) })
1449
+ });
1585
1450
  } catch (err) {
1586
- startSpinner.stop("Could not reach AgentChat");
1587
- await prompter.note(
1588
- `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
1589
- "Recovery failed"
1590
- );
1591
- return "abort";
1592
- }
1593
- if (!startResult.ok) {
1594
- startSpinner.stop("Recovery rejected");
1595
- await prompter.note(describeRecoverStartError(startResult), "Could not start recovery");
1596
- return "abort";
1597
- }
1598
- startSpinner.stop(startResult.message);
1599
- const maxCodeAttempts = 3;
1600
- let verifyResult = null;
1601
- for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
1602
- const code = (await prompter.text({
1603
- message: attempt === 1 ? `Enter the 6-digit recovery code (check ${email}, including spam)` : `Recovery code (attempt ${attempt}/${maxCodeAttempts})`,
1604
- placeholder: "123456",
1605
- validate: (value) => {
1606
- const trimmed = value.trim();
1607
- if (!trimmed) return "Code is required";
1608
- if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
1609
- return void 0;
1610
- }
1611
- })).trim();
1612
- const verifySpinner = prompter.progress("Verifying code\u2026");
1613
- try {
1614
- verifyResult = await recoverAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
1615
- } catch (err) {
1616
- verifySpinner.stop("Could not reach AgentChat");
1617
- await prompter.note(
1618
- `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
1619
- "Recovery failed"
1620
- );
1621
- return "abort";
1622
- }
1623
- if (verifyResult.ok) {
1624
- verifySpinner.stop(`Recovered @${verifyResult.handle}`);
1625
- break;
1626
- }
1627
- verifySpinner.stop("Verification failed");
1628
- if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
1629
- await prompter.note(
1630
- "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.",
1631
- "Invalid recovery code"
1632
- );
1633
- continue;
1634
- }
1635
- await prompter.note(describeRecoverVerifyError(verifyResult), "Recovery failed");
1636
- return "abort";
1637
- }
1638
- if (!verifyResult || !verifyResult.ok) {
1451
+ if (err instanceof WizardCancelledError) throw err;
1452
+ const unreached = err instanceof ConnectionError || err instanceof Error && err.name === "AbortError";
1639
1453
  await prompter.note(
1640
- "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.",
1641
- "Recovery failed"
1454
+ err instanceof Error ? err.message : String(err),
1455
+ unreached ? "Could not reach AgentChat" : `${kind === "register" ? "Registration" : "Recovery"} failed`
1642
1456
  );
1643
- return "abort";
1457
+ return notCompleted(prompter, kind);
1644
1458
  }
1645
- const patch = { apiKey: verifyResult.apiKey };
1646
- if (isValidHandleShape2(verifyResult.handle)) {
1647
- patch.agentHandle = verifyResult.handle;
1648
- }
1649
- const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch);
1459
+ if (result.outcome !== "done") return notCompleted(prompter, kind);
1460
+ const nextCfg = applyAgentchatAccountPatch(cfg, accountId, { apiKey: result.apiKey, agentHandle: result.handle });
1650
1461
  await prompter.note(
1651
1462
  [
1652
- `Handle: @${verifyResult.handle}`,
1653
- `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`,
1654
- "",
1655
- "The previous key for this agent has been revoked."
1463
+ `Handle: @${result.handle}`,
1464
+ `API key: ${redactKey(result.apiKey)} (saved to your OpenClaw config)`
1656
1465
  ].join("\n"),
1657
- "AgentChat API key recovered"
1466
+ kind === "register" ? "AgentChat account created" : "AgentChat API key recovered"
1658
1467
  );
1659
1468
  return {
1660
1469
  cfg: nextCfg,
1661
1470
  credentialValues: {
1662
- token: verifyResult.apiKey,
1471
+ token: result.apiKey,
1663
1472
  [JUST_REGISTERED_SENTINEL]: "1"
1664
1473
  }
1665
1474
  };
1666
1475
  }
1667
- function describeRecoverStartError(result) {
1668
- switch (result.reason) {
1669
- case "rate-limited": {
1670
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1671
- return `Too many recovery attempts from this network.${wait}`;
1672
- }
1673
- case "validation":
1674
- return `AgentChat rejected the request: ${result.message}`;
1675
- case "network-error":
1676
- case "server-error":
1677
- case "unexpected-shape":
1678
- default:
1679
- return result.message;
1680
- }
1681
- }
1682
- function describeRecoverVerifyError(result) {
1683
- switch (result.reason) {
1684
- case "expired":
1685
- return "This recovery code expired. Restart the wizard to request a new one.";
1686
- case "invalid-code":
1687
- return "Too many incorrect codes. Restart the wizard to request a new one.";
1688
- case "handle-required": {
1689
- const handles = result.handles ?? [];
1690
- const list = handles.length > 0 ? `
1691
-
1692
- Agents on this email:
1693
- ${handles.map((h) => ` @${h}`).join("\n")}` : "";
1694
- return `This email backs more than one agent. Run recovery again and enter the handle you want to recover.${list}`;
1695
- }
1696
- case "rate-limited": {
1697
- const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
1698
- return `Rate limited.${wait}`;
1699
- }
1700
- case "network-error":
1701
- case "server-error":
1702
- case "unexpected-shape":
1703
- case "validation":
1704
- default:
1705
- return result.message;
1706
- }
1707
- }
1708
1476
  function redactKey(apiKey) {
1709
1477
  if (apiKey.length < 12) return "\u2022\u2022\u2022\u2022";
1710
1478
  return `${apiKey.slice(0, 8)}\u2026${apiKey.slice(-4)}`;
1711
1479
  }
1480
+ async function saveEnteredKey(cfg, accountId, value, key) {
1481
+ if (typeof value !== "string" || !nonEmpty2(key)) return cfg;
1482
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1483
+ let check;
1484
+ try {
1485
+ check = await checkApiKey(key, { apiBase });
1486
+ } catch {
1487
+ check = null;
1488
+ }
1489
+ if (check !== null && !check.ok) return cfg;
1490
+ const handle = check?.handle;
1491
+ const sameKey = readAgentchatConfigField(cfg, accountId, "apiKey") === value;
1492
+ const withKey = applyAgentchatAccountPatch(cfg, accountId, {
1493
+ apiKey: value,
1494
+ // A new key whose handle is unknown must not keep the old key's handle.
1495
+ ...handle ? { agentHandle: handle } : sameKey ? {} : { agentHandle: void 0 }
1496
+ });
1497
+ return applyIntegrationConfig(withKey, { accountId, handle, apiKey: key, apiBase: apiBase ?? DEFAULT_API_BASE }).cfg;
1498
+ }
1712
1499
  var agentchatSetupWizard = {
1713
1500
  channel: AGENTCHAT_CHANNEL_ID,
1714
1501
  // AgentChat is one-agent-per-account by product design — the agent IS the
@@ -1753,9 +1540,9 @@ var agentchatSetupWizard = {
1753
1540
  "AgentChat is a messaging platform for AI agents \u2014 direct messages,",
1754
1541
  "groups, presence, attachments. Registration is free.",
1755
1542
  "",
1756
- "This wizard will mint a new account via email OTP, accept an existing",
1757
- "API key, or recover a lost key (handle + email OTP) \u2014 your choice in",
1758
- "the next prompt."
1543
+ "This wizard registers a new agent by email code, accepts an existing",
1544
+ "API key, or recovers a lost key by email code \u2014 your choice in the",
1545
+ "next prompt."
1759
1546
  ]
1760
1547
  },
1761
1548
  prepare: async ({ cfg, accountId, credentialValues, prompter }) => {
@@ -1791,7 +1578,7 @@ var agentchatSetupWizard = {
1791
1578
  options: [
1792
1579
  {
1793
1580
  value: "register",
1794
- label: "Register a new agent (email OTP)",
1581
+ label: "Register a new agent (email code)",
1795
1582
  hint: "no account yet \u2014 the wizard creates one"
1796
1583
  },
1797
1584
  {
@@ -1801,64 +1588,14 @@ var agentchatSetupWizard = {
1801
1588
  },
1802
1589
  {
1803
1590
  value: "recover",
1804
- label: "Recover a lost API key (handle + email OTP)",
1591
+ label: "Recover a lost API key (email code)",
1805
1592
  hint: "an agent exists but its key is gone \u2014 re-issue it"
1806
1593
  }
1807
1594
  ],
1808
1595
  initialValue: "register"
1809
1596
  });
1810
- if (choice === "paste") {
1811
- return;
1812
- }
1813
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1814
- const recover = async () => {
1815
- try {
1816
- const result = await runRecoverFlow({ cfg, accountId, prompter, apiBase });
1817
- if (result === "abort") {
1818
- await prompter.note(
1819
- "Recovery was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
1820
- "Falling back to credential entry"
1821
- );
1822
- return;
1823
- }
1824
- return result;
1825
- } catch (err) {
1826
- if (err instanceof WizardCancelledError) throw err;
1827
- await prompter.note(
1828
- `${err instanceof Error ? err.message : String(err)}`,
1829
- "Recovery flow failed"
1830
- );
1831
- return;
1832
- }
1833
- };
1834
- if (choice === "recover") {
1835
- return await recover();
1836
- }
1837
- let registerOutcome;
1838
- try {
1839
- registerOutcome = await runRegisterFlow({ cfg, accountId, prompter, apiBase });
1840
- } catch (err) {
1841
- if (err instanceof WizardCancelledError) throw err;
1842
- await prompter.note(
1843
- `${err instanceof Error ? err.message : String(err)}`,
1844
- "Registration flow failed"
1845
- );
1846
- return;
1847
- }
1848
- if (registerOutcome === "abort") {
1849
- await prompter.note(
1850
- "Registration was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
1851
- "Falling back to credential entry"
1852
- );
1853
- return;
1854
- }
1855
- if (registerOutcome === "user-chose-paste") {
1856
- return;
1857
- }
1858
- if (registerOutcome === "user-chose-recover") {
1859
- return await recover();
1860
- }
1861
- return registerOutcome;
1597
+ if (choice === "paste") return;
1598
+ return await runAccountFlow({ kind: choice, cfg, accountId, prompter });
1862
1599
  },
1863
1600
  credentials: [
1864
1601
  {
@@ -1871,9 +1608,9 @@ var agentchatSetupWizard = {
1871
1608
  inputPrompt: "Paste your AgentChat API key (ac_\u2026)",
1872
1609
  helpTitle: "AgentChat API key",
1873
1610
  helpLines: [
1874
- "Format: ac_ followed by 43 base64url characters. Validated against",
1875
- "GET /v1/agents/me during this wizard \u2014 bad keys fail fast instead",
1876
- "of flapping reconnects at runtime."
1611
+ "AgentChat checks the key before it is saved: a key it does not",
1612
+ "accept is not saved, so a bad key fails here instead of flapping",
1613
+ "reconnects at runtime."
1877
1614
  ],
1878
1615
  allowEnv: () => true,
1879
1616
  shouldPrompt: ({ credentialValues, currentValue }) => {
@@ -1891,61 +1628,67 @@ var agentchatSetupWizard = {
1891
1628
  resolvedValue: configured ? apiKey : void 0,
1892
1629
  envValue
1893
1630
  };
1631
+ },
1632
+ // The key the person entered, checked before it is saved.
1633
+ applySet: ({ cfg, accountId, value, resolvedValue }) => saveEnteredKey(cfg, accountId, value, resolvedValue),
1634
+ applyUseEnv: ({ cfg, accountId }) => {
1635
+ const key = readApiKeyFromEnv(MIN_API_KEY_LENGTH);
1636
+ return key ? saveEnteredKey(cfg, accountId, key, key) : cfg;
1894
1637
  }
1895
1638
  }
1896
1639
  ],
1897
1640
  finalize: async ({ cfg, accountId, credentialValues, prompter }) => {
1898
- const apiKey = typeof credentialValues.token === "string" && credentialValues.token.length >= MIN_API_KEY_LENGTH ? credentialValues.token : readAgentchatConfigField(cfg, accountId, "apiKey");
1899
- if (!apiKey || !isApiKeyPresent(apiKey)) {
1900
- return;
1901
- }
1641
+ const stored = nonEmpty2(readAgentchatConfigField(cfg, accountId, "apiKey"));
1642
+ const apiKey = nonEmpty2(credentialValues.token) ?? stored;
1643
+ if (!apiKey) return;
1902
1644
  const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
1903
- const spinner = prompter.progress("Validating API key against AgentChat\u2026");
1645
+ const spinner = prompter.progress("Checking the API key with AgentChat\u2026");
1646
+ let check;
1904
1647
  try {
1905
- const result = await validateApiKey(apiKey, { apiBase });
1906
- if (result.ok) {
1907
- spinner.stop(`Authenticated as @${result.agent.handle}`);
1908
- const handle = result.agent.handle;
1909
- const resolvedBase = apiBase ?? DEFAULT_API_BASE2;
1910
- const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
1911
- const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
1912
- const failed = placed.steps.filter((s) => s.status === "failed");
1913
- const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
1914
- await prompter.note(
1915
- [
1916
- ...formatPlacement(placed.steps),
1917
- "",
1918
- 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.",
1919
- ...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."] : [],
1920
- ...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
1921
- ].join("\n"),
1922
- "AgentChat integration placed"
1923
- );
1924
- const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
1925
- return { cfg: applied.cfg };
1926
- }
1927
- spinner.stop(`API key did not pass the live check (${result.reason})`);
1648
+ check = await checkApiKey(apiKey, { apiBase });
1649
+ } catch (err) {
1650
+ spinner.stop("Could not reach AgentChat to check the key");
1928
1651
  await prompter.note(
1929
1652
  [
1930
- result.message,
1653
+ err instanceof Error ? err.message : String(err),
1931
1654
  "",
1932
- "The config was saved \u2014 you can re-run `openclaw channels add agentchat`",
1933
- "to replace the key, or edit ~/.openclaw/config.yaml directly."
1655
+ stored === apiKey ? "The config was saved \u2014 the runtime will retry on startup." : "The key was not saved."
1934
1656
  ].join("\n"),
1935
- "AgentChat validation warning"
1657
+ "AgentChat API unreachable"
1936
1658
  );
1937
- } catch (err) {
1938
- spinner.stop("Could not reach AgentChat for validation");
1659
+ return;
1660
+ }
1661
+ if (!check.ok) {
1662
+ spinner.stop("AgentChat did not accept the API key");
1939
1663
  await prompter.note(
1940
1664
  [
1941
- err instanceof Error ? err.message : String(err),
1665
+ check.message,
1942
1666
  "",
1943
- "The config was saved \u2014 the runtime will retry on startup."
1667
+ 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."
1944
1668
  ].join("\n"),
1945
- "AgentChat API unreachable"
1669
+ "AgentChat API key not accepted"
1946
1670
  );
1671
+ return;
1947
1672
  }
1948
- return;
1673
+ spinner.stop(`Authenticated as @${check.handle}`);
1674
+ const handle = check.handle;
1675
+ const resolvedBase = apiBase ?? DEFAULT_API_BASE;
1676
+ const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
1677
+ const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
1678
+ const failed = placed.steps.filter((s) => s.status === "failed");
1679
+ const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
1680
+ await prompter.note(
1681
+ [
1682
+ ...formatPlacement(placed.steps),
1683
+ "",
1684
+ 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.",
1685
+ ...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."] : [],
1686
+ ...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
1687
+ ].join("\n"),
1688
+ "AgentChat integration placed"
1689
+ );
1690
+ const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
1691
+ return { cfg: applied.cfg };
1949
1692
  },
1950
1693
  completionNote: {
1951
1694
  title: "AgentChat is ready",
@@ -3110,6 +2853,12 @@ function logEvent(event, logger, metrics) {
3110
2853
  case "echo":
3111
2854
  logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "own echo \u2014 not a wake");
3112
2855
  return;
2856
+ case "notice":
2857
+ logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "system notice \u2014 acked, not a wake");
2858
+ return;
2859
+ case "gate_chunk":
2860
+ 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");
2861
+ return;
3113
2862
  case "cycle": {
3114
2863
  const s = event.summary;
3115
2864
  const fields = {
@@ -3518,7 +3267,7 @@ var agentchatStatusAdapter = {
3518
3267
  const servedFrom = live?.texts?.source;
3519
3268
  const textsSource = live ? servedFrom === "server" || servedFrom === "cache" ? servedFrom : "missing" : void 0;
3520
3269
  const socketCounters = live?.metrics?.snapshot?.();
3521
- const integration6 = {
3270
+ const integration8 = {
3522
3271
  mode: readWakeModeFromEnv().mode,
3523
3272
  ...health ? { state: health.state } : {},
3524
3273
  ...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
@@ -3535,7 +3284,7 @@ var agentchatStatusAdapter = {
3535
3284
  pausedByOwner: me.paused_by_owner ?? "none",
3536
3285
  mcp,
3537
3286
  placement,
3538
- integration: integration6,
3287
+ integration: integration8,
3539
3288
  ...refusal ? { refusal } : {},
3540
3289
  ...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
3541
3290
  };
@@ -3602,7 +3351,7 @@ var agentchatDoctorAdapter = {
3602
3351
  continue;
3603
3352
  }
3604
3353
  const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
3605
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3354
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3606
3355
  const handle = readAgentchatConfigField(cfg, accountId, "agentHandle");
3607
3356
  const agentId = resolvePlacementAgentId(cfg, accountId);
3608
3357
  for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {
@@ -3641,16 +3390,16 @@ var agentchatDoctorAdapter = {
3641
3390
  for (const accountId of listConfiguredAccountIds(cfg)) {
3642
3391
  if (!isAgentchatAccountEnabled(cfg, accountId)) continue;
3643
3392
  const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
3644
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3393
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3645
3394
  bases.set(apiBase, apiKey);
3646
3395
  if (apiKey && !readAgentchatConfigField(cfg, accountId, "agentHandle")) {
3647
3396
  try {
3648
- const result = await validateApiKey(apiKey, { apiBase });
3397
+ const result = await checkApiKey(apiKey, { apiBase });
3649
3398
  if (result.ok) {
3650
- next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.agent.handle });
3651
- changes.push(`set channels.agentchat${accountId === "default" ? "" : `.accounts.${accountId}`}.agentHandle = ${result.agent.handle}`);
3399
+ next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.handle });
3400
+ changes.push(`set channels.agentchat${accountId === "default" ? "" : `.accounts.${accountId}`}.agentHandle = ${result.handle}`);
3652
3401
  } else {
3653
- warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and the key did not pass the live check (${result.reason}): ${result.message}`);
3402
+ warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and the key did not pass the live check (${result.code}): ${result.message}`);
3654
3403
  }
3655
3404
  } catch (err) {
3656
3405
  warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and AgentChat was not reachable to learn it: ${err instanceof Error ? err.message : String(err)}`);
@@ -3705,7 +3454,7 @@ var uiHints = {
3705
3454
  label: "AgentChat API key",
3706
3455
  placeholder: "ac_\u2026",
3707
3456
  sensitive: true,
3708
- 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."
3457
+ 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."
3709
3458
  },
3710
3459
  apiBase: {
3711
3460
  label: "API base URL",
@@ -3716,19 +3465,26 @@ var uiHints = {
3716
3465
  agentHandle: {
3717
3466
  label: "Agent handle",
3718
3467
  placeholder: "my-agent",
3719
- help: "3\u201330 chars, lowercase letters/digits/hyphens; must start with a letter."
3468
+ help: "The handle the API key belongs to, as AgentChat returned it; setup and `openclaw doctor --fix` write it."
3720
3469
  },
3721
3470
  reconnect: { label: "Reconnect backoff", advanced: true },
3722
3471
  ping: { label: "WebSocket ping cadence", advanced: true },
3723
3472
  outbound: { label: "Outbound send tuning", advanced: true },
3724
3473
  observability: { label: "Logs & metrics", advanced: true }
3725
3474
  };
3726
- var HANDLE_SHAPE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
3727
- function validHandle(value) {
3475
+ function handleOf(value) {
3728
3476
  if (typeof value !== "string") return void 0;
3729
3477
  const bare = value.trim().replace(/^@/, "");
3730
- return bare.length >= 3 && bare.length <= 30 && HANDLE_SHAPE.test(bare) ? bare : void 0;
3478
+ return bare.length > 0 ? bare : void 0;
3479
+ }
3480
+ function keyRefusal(check) {
3481
+ return [
3482
+ `AgentChat did not accept the API key (${check.code}): ${check.message}`,
3483
+ "The key was not saved. Run `openclaw channels add agentchat` to register a new agent or recover a lost key (email code)."
3484
+ ].join("\n");
3731
3485
  }
3486
+ var keyAskedBeforeWrite = null;
3487
+ var keyDigest = (apiKey) => createHash("sha256").update(apiKey).digest("hex");
3732
3488
  function say(runtime, level, line) {
3733
3489
  const env = runtime;
3734
3490
  const fn = env?.[level];
@@ -3736,13 +3492,18 @@ function say(runtime, level, line) {
3736
3492
  }
3737
3493
  var agentchatSetupAdapter = {
3738
3494
  /**
3739
- * Pre-write gate: cheap, sync check that the caller supplied an API key
3740
- * that's at least plausibly shaped. Real authentication happens in
3741
- * `prepareAccountConfigInput` / `afterAccountConfigWritten`.
3495
+ * Pre-write gate: a key AgentChat turned away in
3496
+ * `prepareAccountConfigInput` ends here (OpenClaw prints the line and
3497
+ * writes nothing); otherwise a cheap, sync check that the caller supplied
3498
+ * an API key that's at least plausibly shaped. On an OpenClaw without
3499
+ * `prepareAccountConfigInput`, the lifecycle hook refuses a rejected key
3500
+ * before the write.
3742
3501
  */
3743
3502
  validateInput({ input }) {
3503
+ const refusal = input.keyRefusal;
3504
+ if (typeof refusal === "string" && refusal.length > 0) return refusal;
3744
3505
  if (typeof input.token !== "string" || input.token.trim().length === 0) {
3745
- 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)";
3506
+ 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)";
3746
3507
  }
3747
3508
  if (input.token.length < MIN_API_KEY_LENGTH) {
3748
3509
  return `apiKey looks too short (got ${input.token.length} chars, expect \u2265${MIN_API_KEY_LENGTH})`;
@@ -3760,29 +3521,31 @@ var agentchatSetupAdapter = {
3760
3521
  return null;
3761
3522
  },
3762
3523
  /**
3763
- * Learn the handle the key authenticates as BEFORE the write, so
3764
- * `applyAccountConfig` persists it in the same config write OpenClaw
3765
- * already makes. A key that does not validate leaves the input untouched
3766
- * (the write still happens; the error line says what to fix).
3524
+ * Ask AgentChat about the key BEFORE the write. Accepted: the handle it
3525
+ * belongs to goes into the same config write OpenClaw already makes.
3526
+ * Turned away (401 / 403): the input carries the refusal, `validateInput`
3527
+ * returns it, and OpenClaw writes nothing. No verdict (unreachable, a
3528
+ * 5xx): the key is written for the runtime to try, as the wizard does.
3767
3529
  */
3768
- async prepareAccountConfigInput({ accountId, input, runtime }) {
3530
+ async prepareAccountConfigInput({ cfg, accountId, input, runtime }) {
3769
3531
  const apiKey = typeof input.token === "string" ? input.token : void 0;
3770
3532
  if (!apiKey || apiKey.length < MIN_API_KEY_LENGTH) return input;
3771
- const apiBase = typeof input.url === "string" && input.url.length > 0 ? input.url : void 0;
3533
+ const apiBase = typeof input.url === "string" && input.url.length > 0 ? input.url : readAgentchatConfigField(cfg, accountId, "apiBase");
3534
+ keyAskedBeforeWrite = keyDigest(apiKey);
3772
3535
  try {
3773
- const result = await validateApiKey(apiKey, { apiBase });
3536
+ const result = await checkApiKey(apiKey, { apiBase });
3774
3537
  if (result.ok) {
3775
- say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.agent.handle} (${result.agent.email})`);
3538
+ say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.handle}`);
3776
3539
  try {
3777
3540
  placeApiKeyInDotEnv(apiKey);
3778
3541
  } catch (err) {
3779
3542
  say(runtime, "error", `[agentchat:${accountId}] could not write AGENTCHAT_API_KEY to ${dotEnvPath()}: ${err instanceof Error ? err.message : String(err)}`);
3780
3543
  }
3781
- return { ...input, agentHandle: result.agent.handle };
3544
+ return { ...input, agentHandle: result.handle };
3782
3545
  }
3783
- say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`);
3546
+ return { ...input, keyRefusal: keyRefusal(result) };
3784
3547
  } catch (err) {
3785
- say(runtime, "error", `[agentchat:${accountId}] live key validation failed: ${err instanceof Error ? err.message : String(err)}`);
3548
+ 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)}`);
3786
3549
  }
3787
3550
  return input;
3788
3551
  },
@@ -3796,12 +3559,12 @@ var agentchatSetupAdapter = {
3796
3559
  const patch = {};
3797
3560
  if (typeof input.token === "string" && input.token.length > 0) patch.apiKey = input.token;
3798
3561
  if (typeof input.url === "string" && input.url.length > 0) patch.apiBase = input.url;
3799
- const handle = validHandle(input.agentHandle);
3562
+ const handle = handleOf(input.agentHandle);
3800
3563
  if (handle) patch.agentHandle = handle;
3801
3564
  const withAccount = applyAgentchatAccountPatch(cfg, accountId, patch);
3802
3565
  const apiKey = readAgentchatConfigField(withAccount, accountId, "apiKey");
3803
3566
  if (!apiKey) return withAccount;
3804
- const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3567
+ const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE;
3805
3568
  return applyIntegrationConfig(withAccount, { accountId, handle, apiKey, apiBase }).cfg;
3806
3569
  },
3807
3570
  /**
@@ -3812,16 +3575,16 @@ var agentchatSetupAdapter = {
3812
3575
  async afterAccountConfigWritten({ cfg, accountId, input, runtime }) {
3813
3576
  const apiKey = typeof input.token === "string" ? input.token : readAgentchatConfigField(cfg, accountId, "apiKey");
3814
3577
  if (!apiKey) return;
3815
- const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3816
- let handle = validHandle(input.agentHandle) ?? readAgentchatConfigField(cfg, accountId, "agentHandle");
3578
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3579
+ let handle = handleOf(input.agentHandle) ?? handleOf(readAgentchatConfigField(cfg, accountId, "agentHandle"));
3817
3580
  if (!handle) {
3818
3581
  try {
3819
- const result = await validateApiKey(apiKey, { apiBase });
3582
+ const result = await checkApiKey(apiKey, { apiBase });
3820
3583
  if (result.ok) {
3821
- handle = result.agent.handle;
3584
+ handle = result.handle;
3822
3585
  say(runtime, "log", `[agentchat:${accountId}] authenticated as @${handle}; run \`openclaw doctor --fix\` to persist channels.agentchat.agentHandle`);
3823
3586
  } else {
3824
- say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.reason}): ${result.message}`);
3587
+ say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.code}): ${result.message}`);
3825
3588
  return;
3826
3589
  }
3827
3590
  } catch (err) {
@@ -3855,8 +3618,24 @@ function accountSectionPersistable(cfg, accountId) {
3855
3618
  if (!raw) return true;
3856
3619
  return agentchatChannelConfigSchema.safeParse(raw).success;
3857
3620
  }
3621
+ async function refuseRejectedKey(prevCfg, nextCfg, accountId, runtime) {
3622
+ const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
3623
+ if (!apiKey || apiKey === readAgentchatConfigField(prevCfg, accountId, "apiKey")) return;
3624
+ if (keyAskedBeforeWrite === keyDigest(apiKey)) return;
3625
+ let check;
3626
+ try {
3627
+ check = await checkApiKey(apiKey, { apiBase: readAgentchatConfigField(nextCfg, accountId, "apiBase") });
3628
+ } catch (err) {
3629
+ 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)}`);
3630
+ return;
3631
+ }
3632
+ if (check.ok) return;
3633
+ say(runtime, "error", keyRefusal(check));
3634
+ throw new WizardCancelledError("AgentChat did not accept the API key");
3635
+ }
3858
3636
  var agentchatLifecycleAdapter = {
3859
3637
  async onAccountConfigChanged({ prevCfg, nextCfg, accountId, runtime }) {
3638
+ await refuseRejectedKey(prevCfg, nextCfg, accountId, runtime);
3860
3639
  const wasEnabled = isAccountEnabled(prevCfg, accountId);
3861
3640
  const isEnabled = isAccountEnabled(nextCfg, accountId);
3862
3641
  if (wasEnabled === isEnabled) return;
@@ -3872,13 +3651,13 @@ var agentchatLifecycleAdapter = {
3872
3651
  for (const line of removeIntegrationFiles(nextCfg, accountId, { clearKey: false })) say(runtime, "log", `[agentchat:${accountId}] ${line}`);
3873
3652
  return;
3874
3653
  }
3875
- const handle = validHandle(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
3654
+ const handle = handleOf(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
3876
3655
  if (!handle) {
3877
3656
  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`);
3878
3657
  return;
3879
3658
  }
3880
3659
  const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
3881
- const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
3660
+ const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
3882
3661
  const identityLine = apiKey ? await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId }) : null;
3883
3662
  const restored = restoreIdentityLine(nextCfg, accountId, handle, identityLine);
3884
3663
  if (restored.outcome === "placed") say(runtime, "log", `[agentchat:${accountId}] placed the identity line for @${handle} in ${restored.path}`);