@agentchatme/openclaw 0.2.0 → 0.3.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,40 +1,64 @@
1
1
  import { buildChannelConfigSchema, defineChannelPluginEntry, defineSetupPluginEntry } from 'openclaw/plugin-sdk/channel-core';
2
+ import { setSetupChannelEnabled, WizardCancelledError } from 'openclaw/plugin-sdk/setup';
2
3
  import { z } from 'zod';
3
4
 
4
5
  // src/channel.setup.ts
5
- var reconnectConfigSchema = z.object({
6
- initialBackoffMs: z.number().int().min(100).max(1e4).default(1e3),
7
- maxBackoffMs: z.number().int().min(1e3).max(3e5).default(3e4),
8
- jitterRatio: z.number().min(0).max(1).default(0.2)
9
- }).strict();
10
- var pingConfigSchema = z.object({
11
- intervalMs: z.number().int().min(5e3).max(12e4).default(3e4),
12
- timeoutMs: z.number().int().min(1e3).max(3e4).default(1e4)
13
- }).strict();
14
- var outboundConfigSchema = z.object({
15
- maxInFlight: z.number().int().min(1).max(1e4).default(256),
16
- sendTimeoutMs: z.number().int().min(1e3).max(6e4).default(15e3)
17
- }).strict();
18
- var observabilityConfigSchema = z.object({
19
- logLevel: z.enum(["trace", "debug", "info", "warn", "error"]).default("info"),
20
- redactKeys: z.array(z.string()).default(["apiKey", "authorization", "cookie", "set-cookie"])
21
- }).strict();
22
- var agentHandleSchema = z.string().regex(/^[a-z0-9_.-]{3,32}$/, "handle must be 3-32 chars, lowercase alphanumeric + . _ -");
23
- var agentchatChannelConfigSchema = z.object({
24
- apiBase: z.string().url().default("https://api.agentchat.me"),
25
- apiKey: z.string().min(20, "apiKey looks too short for an AgentChat API key"),
26
- agentHandle: agentHandleSchema.optional(),
27
- // `.prefault({})` — Zod 4 idiom: when the key is missing from input, parse
28
- // `{}` through the inner schema so its own per-field defaults kick in.
29
- // Using `.default({})` here fails in Zod 4 because the output type's fields
30
- // are non-optional once the inner schema has defaults.
31
- reconnect: reconnectConfigSchema.prefault({}),
32
- ping: pingConfigSchema.prefault({}),
33
- outbound: outboundConfigSchema.prefault({}),
34
- observability: observabilityConfigSchema.prefault({})
35
- }).strict();
36
- function parseChannelConfig(input) {
37
- return agentchatChannelConfigSchema.parse(input);
6
+
7
+ // src/channel-account.ts
8
+ var AGENTCHAT_CHANNEL_ID = "agentchat";
9
+ var AGENTCHAT_DEFAULT_ACCOUNT_ID = "default";
10
+ var MIN_API_KEY_LENGTH = 20;
11
+ function readChannelSection(cfg) {
12
+ const channels = cfg?.channels;
13
+ const section = channels?.[AGENTCHAT_CHANNEL_ID];
14
+ return section && typeof section === "object" && !Array.isArray(section) ? section : void 0;
15
+ }
16
+ function readAccountRaw(section, accountId) {
17
+ if (!section) return void 0;
18
+ const { accounts } = section;
19
+ if (accounts && typeof accounts === "object" && !Array.isArray(accounts)) {
20
+ const entry = accounts[accountId];
21
+ if (entry && typeof entry === "object") return entry;
22
+ }
23
+ if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID) {
24
+ const { accounts: _accounts, ...rest } = section;
25
+ return rest;
26
+ }
27
+ return void 0;
28
+ }
29
+ function splitEnabledFromRaw(raw) {
30
+ if (!raw) return { enabled: true, forParse: void 0 };
31
+ const { enabled, ...rest } = raw;
32
+ return { enabled: enabled !== false, forParse: rest };
33
+ }
34
+ function isApiKeyPresent(value) {
35
+ return typeof value === "string" && value.length >= MIN_API_KEY_LENGTH;
36
+ }
37
+ function readAgentchatConfigField(cfg, accountId, field) {
38
+ const section = readChannelSection(cfg);
39
+ const raw = readAccountRaw(section, accountId);
40
+ if (!raw) return void 0;
41
+ const value = raw[field];
42
+ return typeof value === "string" && value.length > 0 ? value : void 0;
43
+ }
44
+ function applyAgentchatAccountPatch(cfg, accountId, patch) {
45
+ const channels = {
46
+ ...cfg?.channels ?? {}
47
+ };
48
+ const currentSection = channels[AGENTCHAT_CHANNEL_ID];
49
+ const section = currentSection && typeof currentSection === "object" && !Array.isArray(currentSection) ? { ...currentSection } : {};
50
+ if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID && !section.accounts) {
51
+ Object.assign(section, patch);
52
+ } else {
53
+ const accounts = {
54
+ ...section.accounts ?? {}
55
+ };
56
+ const prevAccount = typeof accounts[accountId] === "object" && accounts[accountId] !== null ? accounts[accountId] : {};
57
+ accounts[accountId] = { ...prevAccount, ...patch };
58
+ section.accounts = accounts;
59
+ }
60
+ channels[AGENTCHAT_CHANNEL_ID] = section;
61
+ return { ...cfg ?? {}, channels };
38
62
  }
39
63
 
40
64
  // src/setup-client.ts
@@ -137,7 +161,6 @@ async function registerAgentStart(input, opts = {}) {
137
161
  if (res.status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status: 400 };
138
162
  if (res.status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status: 409 };
139
163
  if (res.status === 409 && code === "EMAIL_TAKEN") return { ok: false, reason: "email-taken", message, status: 409 };
140
- if (res.status === 409 && code === "EMAIL_IS_OWNER") return { ok: false, reason: "email-is-owner", message, status: 409 };
141
164
  if (res.status === 409 && code === "EMAIL_EXHAUSTED") return { ok: false, reason: "email-exhausted", message, status: 409 };
142
165
  if (res.status === 429) {
143
166
  return {
@@ -184,7 +207,6 @@ async function registerAgentVerify(input, opts = {}) {
184
207
  if (res.status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status: 400 };
185
208
  if (res.status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status: 409 };
186
209
  if (res.status === 409 && code === "EMAIL_TAKEN") return { ok: false, reason: "email-taken", message, status: 409 };
187
- if (res.status === 409 && code === "EMAIL_IS_OWNER") return { ok: false, reason: "email-is-owner", message, status: 409 };
188
210
  if (res.status === 429) {
189
211
  return { ok: false, reason: "rate-limited", message, status: 429, retryAfterSeconds: res.retryAfterSeconds };
190
212
  }
@@ -221,487 +243,551 @@ async function post(path, body, opts) {
221
243
  }
222
244
  }
223
245
 
224
- // src/setup-wizard.ts
225
- var HANDLE_PATTERN = /^[a-z0-9_.-]{3,32}$/;
226
- var MIN_API_KEY_LENGTH = 20;
227
- var OTP_ATTEMPTS = 3;
228
- function readSection(cfg) {
229
- const channels = cfg?.channels;
230
- const sec = channels?.[AGENTCHAT_CHANNEL_ID];
231
- return sec && typeof sec === "object" && !Array.isArray(sec) ? sec : void 0;
232
- }
233
- function readAccountRaw(cfg, accountId) {
234
- const sec = readSection(cfg);
235
- if (!sec) return void 0;
236
- const accounts = sec.accounts;
237
- if (accounts && typeof accounts === "object" && !Array.isArray(accounts)) {
238
- const entry = accounts[accountId];
239
- if (entry && typeof entry === "object") return entry;
240
- }
241
- if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID) {
242
- const { accounts: _accounts, ...rest } = sec;
243
- return rest;
244
- }
245
- return void 0;
246
- }
247
- function readAccountApiKey(cfg, accountId) {
248
- const raw = readAccountRaw(cfg, accountId);
249
- const value = raw?.apiKey;
250
- return typeof value === "string" && value.length >= MIN_API_KEY_LENGTH ? value : void 0;
251
- }
252
- function readAccountApiBase(cfg, accountId) {
253
- const raw = readAccountRaw(cfg, accountId);
254
- const value = raw?.apiBase;
255
- return typeof value === "string" && value.length > 0 ? value : void 0;
256
- }
257
- function writeAccountPatch(cfg, accountId, patch) {
258
- const channels = {
259
- ...cfg?.channels ?? {}
260
- };
261
- const existing = channels[AGENTCHAT_CHANNEL_ID];
262
- const section = existing && typeof existing === "object" && !Array.isArray(existing) ? { ...existing } : {};
263
- const clean = {};
264
- if (patch.apiKey !== void 0) clean.apiKey = patch.apiKey;
265
- if (patch.apiBase !== void 0) clean.apiBase = patch.apiBase;
266
- if (patch.agentHandle !== void 0) clean.agentHandle = patch.agentHandle;
267
- const hasAccountsMap = typeof section.accounts === "object" && section.accounts !== null && !Array.isArray(section.accounts);
268
- if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID && !hasAccountsMap) {
269
- Object.assign(section, clean);
270
- } else {
271
- const accounts = {
272
- ...section.accounts ?? {}
273
- };
274
- const prev = typeof accounts[accountId] === "object" && accounts[accountId] !== null ? accounts[accountId] : {};
275
- accounts[accountId] = { ...prev, ...clean };
276
- section.accounts = accounts;
277
- }
278
- channels[AGENTCHAT_CHANNEL_ID] = section;
279
- return { ...cfg, channels };
246
+ // src/channel.wizard.ts
247
+ var JUST_REGISTERED_SENTINEL = "_agentchatJustRegistered";
248
+ var HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
249
+ var HANDLE_MIN_LENGTH = 3;
250
+ var HANDLE_MAX_LENGTH = 30;
251
+ var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
252
+ function isValidHandleShape(value) {
253
+ return value.length >= HANDLE_MIN_LENGTH && value.length <= HANDLE_MAX_LENGTH && HANDLE_PATTERN.test(value);
280
254
  }
281
- function isAccountConfigured(cfg, accountId) {
282
- return Boolean(readAccountApiKey(cfg, accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID));
283
- }
284
- async function promptApiKey(prompter) {
285
- const value = await prompter.text({
286
- message: "Paste your AgentChat API key",
287
- placeholder: "ac_live_...",
288
- validate: (v) => {
289
- const trimmed = v.trim();
290
- if (!trimmed) return "API key is required";
291
- if (trimmed.length < MIN_API_KEY_LENGTH)
292
- return `Looks too short (${trimmed.length} chars \u2014 expect \u2265${MIN_API_KEY_LENGTH})`;
293
- return void 0;
294
- }
295
- });
296
- return value.trim();
255
+ var OTP_PATTERN = /^\d{6}$/;
256
+ function hasConfiguredKey(cfg, accountId) {
257
+ return isApiKeyPresent(readAgentchatConfigField(cfg, accountId, "apiKey"));
297
258
  }
259
+ var MAX_START_RETRIES = 5;
298
260
  async function promptEmail(prompter) {
299
- const value = await prompter.text({
300
- message: "Your email address (for OTP verification)",
261
+ return (await prompter.text({
262
+ message: "Email address (for the verification code)",
301
263
  placeholder: "you@example.com",
302
- validate: (v) => {
303
- const trimmed = v.trim();
264
+ validate: (value) => {
265
+ const trimmed = value.trim();
304
266
  if (!trimmed) return "Email is required";
305
- if (!/.+@.+\..+/.test(trimmed)) return "Not a valid email address";
267
+ if (!EMAIL_PATTERN.test(trimmed)) return "That does not look like a valid email address";
306
268
  return void 0;
307
269
  }
308
- });
309
- return value.trim();
270
+ })).trim();
310
271
  }
311
- async function promptHandle(prompter, initial) {
312
- const value = await prompter.text({
313
- message: "Pick a handle for your agent",
314
- placeholder: "alice",
315
- initialValue: initial,
316
- validate: (v) => {
317
- const trimmed = v.trim().toLowerCase();
272
+ async function promptHandle(prompter) {
273
+ return (await prompter.text({
274
+ message: "Choose a handle (your @name on AgentChat)",
275
+ placeholder: "my-agent",
276
+ validate: (value) => {
277
+ const trimmed = value.trim();
318
278
  if (!trimmed) return "Handle is required";
319
- if (!HANDLE_PATTERN.test(trimmed))
320
- return "3\u201332 chars; lowercase a-z / 0-9 / dot / underscore / dash";
279
+ if (!isValidHandleShape(trimmed)) {
280
+ return "Handle must be 3\u201330 chars \u2014 lowercase letters/digits/hyphens; must start with a letter";
281
+ }
321
282
  return void 0;
322
283
  }
323
- });
324
- return value.trim().toLowerCase();
284
+ })).trim();
325
285
  }
326
- async function promptOtp(prompter) {
327
- const value = await prompter.text({
328
- message: "Enter the 6-digit code we emailed you",
329
- placeholder: "123456",
330
- validate: (v) => /^\d{6}$/.test(v.trim()) ? void 0 : "6-digit numeric code required"
331
- });
332
- return value.trim();
333
- }
334
- async function promptOptionalText(prompter, message, placeholder) {
335
- const value = await prompter.text({
336
- message,
337
- placeholder,
286
+ async function promptDisplayName(prompter) {
287
+ return (await prompter.text({
288
+ message: "Display name (optional \u2014 shown next to your handle)",
289
+ placeholder: "",
338
290
  validate: () => void 0
339
- });
340
- return value.trim();
341
- }
342
- function describeRegisterStartFailure(r) {
343
- switch (r.reason) {
344
- case "invalid-handle":
345
- return "That handle is not valid. Use 3\u201332 chars, lowercase a-z / 0-9 / . _ -.";
346
- case "handle-taken":
347
- return "That handle is already taken. Pick another.";
348
- case "email-taken":
349
- return "That email already has an agent. Sign in with the existing key instead, or use a different email.";
350
- case "email-is-owner":
351
- return "That email is reserved. Use a different address.";
352
- case "email-exhausted":
353
- return "This email has hit the per-address agent limit. Use a different email or delete an old agent.";
354
- case "rate-limited":
355
- return r.retryAfterSeconds ? `Too many attempts. Try again in ${r.retryAfterSeconds}s.` : "Too many attempts. Try again in a few minutes.";
356
- case "otp-failed":
357
- return "Could not send the verification email. Check the address and retry.";
358
- case "network-error":
359
- return `Network error: ${r.message}`;
360
- case "validation":
361
- return `Validation error: ${r.message}`;
362
- case "server-error":
363
- return `AgentChat API error (${r.status ?? "??"}): ${r.message}`;
364
- }
291
+ })).trim();
365
292
  }
366
- function describeRegisterVerifyFailure(r) {
367
- switch (r.reason) {
368
- case "expired":
369
- return "That code has expired. We'll request a new one \u2014 restart registration.";
370
- case "invalid-code":
371
- return "Wrong code. Check the email and try again.";
372
- case "rate-limited":
373
- return r.retryAfterSeconds ? `Too many attempts. Wait ${r.retryAfterSeconds}s before retrying.` : "Too many attempts. Try again in a few minutes.";
374
- case "handle-taken":
375
- return "Someone else just took that handle. Restart and pick another.";
376
- case "email-taken":
377
- return "That email was registered by someone else between these steps. Start over.";
378
- case "email-is-owner":
379
- return "That email is reserved.";
380
- case "network-error":
381
- return `Network error: ${r.message}`;
382
- case "unexpected-shape":
383
- return `Server returned an unexpected response (${r.status ?? "??"}). Try again shortly.`;
384
- case "validation":
385
- return `Validation error: ${r.message}`;
386
- case "server-error":
387
- return `AgentChat API error (${r.status ?? "??"}): ${r.message}`;
388
- }
389
- }
390
- async function runHaveKeyFlow(cfg, accountId, prompter, apiBase) {
391
- const apiKey = await promptApiKey(prompter);
392
- const progress = prompter.progress("Validating key against AgentChat\u2026");
393
- const result = await validateApiKey(apiKey, { apiBase });
394
- if (!result.ok) {
395
- progress.stop("Key rejected.");
293
+ async function runChangeApiBaseFlow(params) {
294
+ const { cfg, accountId, prompter } = params;
295
+ const current = readAgentchatConfigField(cfg, accountId, "apiBase");
296
+ const input = (await prompter.text({
297
+ message: "New API base URL (blank to reset to default)",
298
+ placeholder: current ?? "https://api.agentchat.me",
299
+ validate: (value) => {
300
+ const trimmed = value.trim();
301
+ if (!trimmed) return void 0;
302
+ try {
303
+ const url = new URL(trimmed);
304
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
305
+ return "API base must use http:// or https://";
306
+ }
307
+ return void 0;
308
+ } catch {
309
+ return "Not a valid URL";
310
+ }
311
+ }
312
+ })).trim();
313
+ if (!input) {
314
+ const patched2 = applyAgentchatAccountPatch(cfg, accountId, {
315
+ apiBase: void 0
316
+ });
396
317
  await prompter.note(
397
- [
398
- `AgentChat rejected the key (${result.reason}):`,
399
- ` ${result.message}`,
400
- "",
401
- result.reason === "unauthorized" || result.reason === "deleted" ? "The key is invalid, revoked, or the agent was deleted. Grab a fresh key from agentchat.me/dashboard." : result.reason === "unreachable" || result.reason === "network-error" ? "Could not reach the API. Check your network, then run setup again." : "Try again, or pick the register flow."
402
- ].join("\n"),
403
- "Validation failed"
318
+ "API base reset to default (https://api.agentchat.me).",
319
+ "Updated"
404
320
  );
405
- return runNewAccountFlow(cfg, accountId, prompter, apiBase);
321
+ return { cfg: patched2 };
406
322
  }
407
- progress.stop(`Authenticated as @${result.agent.handle}.`);
408
- const next = writeAccountPatch(cfg, accountId, {
409
- apiKey,
410
- agentHandle: result.agent.handle,
411
- ...apiBase ? { apiBase } : {}
323
+ const patched = applyAgentchatAccountPatch(cfg, accountId, {
324
+ apiBase: input
412
325
  });
413
- await prompter.note(
414
- [
415
- `Connected to AgentChat as @${result.agent.handle}.`,
416
- `Email: ${result.agent.email}`,
417
- result.agent.displayName ? `Display name: ${result.agent.displayName}` : void 0
418
- ].filter((v) => Boolean(v)).join("\n"),
419
- "AgentChat configured"
420
- );
421
- return { cfg: next };
326
+ await prompter.note(`API base set to ${input}`, "Updated");
327
+ return { cfg: patched };
422
328
  }
423
- async function runRegisterFlow(cfg, accountId, prompter, apiBase) {
329
+ async function runRegisterFlow(params) {
330
+ const { cfg, accountId, prompter, apiBase } = params;
424
331
  await prompter.note(
425
332
  [
426
- "We will email a 6-digit code to verify ownership of this address.",
427
- "The email is hashed server-side and used only for account recovery."
333
+ "Registration mints a new AgentChat agent identity tied to your email.",
334
+ "You will receive a 6-digit code to verify \u2014 check your inbox (and spam)."
428
335
  ].join("\n"),
429
- "New-agent registration"
430
- );
431
- const email = await promptEmail(prompter);
432
- const handle = await promptHandle(prompter);
433
- const displayName = await promptOptionalText(
434
- prompter,
435
- "Display name (optional, press Enter to skip)",
436
- handle
336
+ "AgentChat: register a new agent"
437
337
  );
438
- const description = await promptOptionalText(
439
- prompter,
440
- "Short description of your agent (optional)",
441
- "Research assistant that summarises papers"
442
- );
443
- const startProgress = prompter.progress("Requesting OTP\u2026");
444
- const start = await registerAgentStart(
445
- {
446
- email,
447
- handle,
448
- displayName: displayName || void 0,
449
- description: description || void 0
450
- },
451
- { apiBase }
452
- );
453
- if (!start.ok) {
454
- startProgress.stop("Registration could not start.");
455
- await prompter.note(describeRegisterStartFailure(start), "Registration failed");
456
- const retry = await prompter.confirm({
457
- message: start.reason === "handle-taken" || start.reason === "invalid-handle" ? "Try a different handle?" : "Try again?",
458
- initialValue: true
459
- });
460
- if (!retry) return { cfg };
461
- return runRegisterFlow(cfg, accountId, prompter, apiBase);
338
+ let email = await promptEmail(prompter);
339
+ let handle = await promptHandle(prompter);
340
+ const displayName = await promptDisplayName(prompter);
341
+ let startResult;
342
+ let startedOk = false;
343
+ for (let attempt = 1; attempt <= MAX_START_RETRIES; attempt += 1) {
344
+ const startSpinner = prompter.progress(
345
+ attempt === 1 ? "Sending verification code\u2026" : "Retrying\u2026"
346
+ );
347
+ try {
348
+ startResult = await registerAgentStart(
349
+ {
350
+ email,
351
+ handle,
352
+ ...displayName ? { displayName } : {}
353
+ },
354
+ { apiBase }
355
+ );
356
+ } catch (err) {
357
+ startSpinner.stop("Could not reach AgentChat");
358
+ await prompter.note(
359
+ `${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
360
+ "Registration failed"
361
+ );
362
+ return "abort";
363
+ }
364
+ if (startResult.ok) {
365
+ startSpinner.stop(`Verification code sent to ${email}`);
366
+ startedOk = true;
367
+ break;
368
+ }
369
+ startSpinner.stop("Registration rejected");
370
+ switch (startResult.reason) {
371
+ case "invalid-handle":
372
+ case "handle-taken": {
373
+ 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).";
374
+ await prompter.note(`${detail} Pick a different handle and we'll try again.`, "Pick a different handle");
375
+ handle = await promptHandle(prompter);
376
+ continue;
377
+ }
378
+ case "email-taken": {
379
+ const choice = await prompter.select({
380
+ message: `${email} is already registered as an AgentChat agent. What would you like to do?`,
381
+ options: [
382
+ {
383
+ value: "paste",
384
+ label: "Paste the existing API key for this agent",
385
+ hint: "recommended if you own the account"
386
+ },
387
+ { value: "retry", label: "Use a different email address" },
388
+ { value: "cancel", label: "Cancel registration" }
389
+ ],
390
+ initialValue: "paste"
391
+ });
392
+ if (choice === "paste") return "user-chose-paste";
393
+ if (choice === "cancel") return "abort";
394
+ email = await promptEmail(prompter);
395
+ continue;
396
+ }
397
+ case "email-exhausted": {
398
+ const choice = await prompter.select({
399
+ message: `${email} has reached the per-email agent quota. What next?`,
400
+ options: [
401
+ { value: "retry", label: "Use a different email address" },
402
+ { value: "paste", label: "Paste a key from an existing agent" },
403
+ { value: "cancel", label: "Cancel registration" }
404
+ ],
405
+ initialValue: "retry"
406
+ });
407
+ if (choice === "paste") return "user-chose-paste";
408
+ if (choice === "cancel") return "abort";
409
+ email = await promptEmail(prompter);
410
+ continue;
411
+ }
412
+ case "rate-limited": {
413
+ const wait = startResult.retryAfterSeconds ? ` Try again in ${startResult.retryAfterSeconds}s.` : "";
414
+ await prompter.note(`Too many registration attempts.${wait}`, "Rate limited");
415
+ return "abort";
416
+ }
417
+ case "otp-failed": {
418
+ await prompter.note(
419
+ "The verification-code email could not be sent. Try again in a minute, or paste an existing key instead.",
420
+ "OTP delivery failed"
421
+ );
422
+ return "abort";
423
+ }
424
+ case "network-error":
425
+ case "server-error":
426
+ case "validation":
427
+ default: {
428
+ await prompter.note(describeRegisterStartError(startResult), "Could not start registration");
429
+ return "abort";
430
+ }
431
+ }
462
432
  }
463
- startProgress.stop(`OTP sent to ${email}.`);
464
- const pendingId = start.pendingId;
465
- for (let attempt = 1; attempt <= OTP_ATTEMPTS; attempt += 1) {
466
- const code = await promptOtp(prompter);
467
- const verifyProgress = prompter.progress("Verifying code\u2026");
468
- const verify = await registerAgentVerify({ pendingId, code }, { apiBase });
469
- if (verify.ok) {
470
- verifyProgress.stop(`Verified. Agent @${verify.agent.handle} created.`);
471
- const next = writeAccountPatch(cfg, accountId, {
472
- apiKey: verify.apiKey,
473
- agentHandle: verify.agent.handle,
474
- ...apiBase ? { apiBase } : {}
475
- });
433
+ if (!startedOk || !startResult || !startResult.ok) {
434
+ await prompter.note(
435
+ "Too many attempts. Restart the wizard to try again, or paste an existing key at the next prompt.",
436
+ "Registration failed"
437
+ );
438
+ return "abort";
439
+ }
440
+ const maxCodeAttempts = 3;
441
+ let verifyResult = null;
442
+ for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
443
+ const code = (await prompter.text({
444
+ message: attempt === 1 ? "Enter the 6-digit verification code from your email" : `Verification code (attempt ${attempt}/${maxCodeAttempts})`,
445
+ placeholder: "123456",
446
+ validate: (value) => {
447
+ const trimmed = value.trim();
448
+ if (!trimmed) return "Code is required";
449
+ if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
450
+ return void 0;
451
+ }
452
+ })).trim();
453
+ const verifySpinner = prompter.progress("Verifying code\u2026");
454
+ try {
455
+ verifyResult = await registerAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
456
+ } catch (err) {
457
+ verifySpinner.stop("Could not reach AgentChat");
476
458
  await prompter.note(
477
- [
478
- "Your AgentChat API key has been written to config.",
479
- "",
480
- ` handle: @${verify.agent.handle}`,
481
- ` email: ${verify.agent.email}`,
482
- "",
483
- "Keep the key safe \u2014 it authenticates sends as this agent.",
484
- "You can rotate it any time from agentchat.me/dashboard."
485
- ].join("\n"),
486
- "Registration complete"
459
+ `${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
460
+ "Verification failed"
487
461
  );
488
- return { cfg: next };
462
+ return "abort";
489
463
  }
490
- verifyProgress.stop(`Attempt ${attempt}/${OTP_ATTEMPTS} failed (${verify.reason}).`);
491
- await prompter.note(describeRegisterVerifyFailure(verify), "Code rejected");
492
- if (verify.reason === "expired") {
493
- return runRegisterFlow(cfg, accountId, prompter, apiBase);
464
+ if (verifyResult.ok) {
465
+ verifySpinner.stop(`Registered as @${verifyResult.agent.handle}`);
466
+ break;
494
467
  }
495
- if (verify.reason !== "invalid-code") {
496
- const retry = await prompter.confirm({
497
- message: "Start over with different details?",
498
- initialValue: true
499
- });
500
- if (!retry) return { cfg };
501
- return runRegisterFlow(cfg, accountId, prompter, apiBase);
468
+ verifySpinner.stop("Verification failed");
469
+ if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
470
+ await prompter.note(
471
+ "That code did not match. Check your email and try again.",
472
+ "Invalid verification code"
473
+ );
474
+ continue;
502
475
  }
476
+ await prompter.note(describeRegisterVerifyError(verifyResult), "Registration failed");
477
+ return "abort";
503
478
  }
479
+ if (!verifyResult || !verifyResult.ok) {
480
+ await prompter.note(
481
+ "Too many incorrect codes. Restart the wizard to receive a new code.",
482
+ "Registration failed"
483
+ );
484
+ return "abort";
485
+ }
486
+ const patch = { apiKey: verifyResult.apiKey };
487
+ if (isValidHandleShape(verifyResult.agent.handle)) {
488
+ patch.agentHandle = verifyResult.agent.handle;
489
+ }
490
+ const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch);
504
491
  await prompter.note(
505
- "Too many invalid codes. Restart setup to request a new one.",
506
- "Registration aborted"
492
+ [
493
+ `Handle: @${verifyResult.agent.handle}`,
494
+ `Email: ${verifyResult.agent.email}`,
495
+ `API key: ${redactKey(verifyResult.apiKey)} (saved to your OpenClaw config)`
496
+ ].join("\n"),
497
+ "AgentChat account created"
507
498
  );
508
- return { cfg };
509
- }
510
- async function runEditFlow(cfg, accountId, prompter) {
511
- const currentKey = readAccountApiKey(cfg, accountId);
512
- const currentBase = readAccountApiBase(cfg, accountId);
513
- const choice = await prompter.select({
514
- message: "AgentChat is already configured. What would you like to do?",
515
- options: [
516
- {
517
- value: "validate",
518
- label: "Re-validate the current key",
519
- hint: "Hit /agents/me to confirm it still authenticates"
520
- },
521
- {
522
- value: "rotate",
523
- label: "Rotate to a new API key",
524
- hint: "Paste a freshly generated key or register a new agent"
525
- },
526
- {
527
- value: "change-base",
528
- label: "Change API base URL",
529
- hint: "Only for self-hosted AgentChat deployments"
530
- },
531
- { value: "skip", label: "Leave as is", hint: "No changes" }
532
- ],
533
- initialValue: "validate"
534
- });
535
- if (choice === "skip") return { cfg };
536
- if (choice === "validate") {
537
- if (!currentKey) {
538
- await prompter.note("No API key is currently set.", "Nothing to validate");
539
- return runNewAccountFlow(cfg, accountId, prompter, currentBase);
499
+ return {
500
+ cfg: nextCfg,
501
+ credentialValues: {
502
+ token: verifyResult.apiKey,
503
+ [JUST_REGISTERED_SENTINEL]: "1"
540
504
  }
541
- const progress = prompter.progress("Probing /agents/me\u2026");
542
- const result = await validateApiKey(currentKey, { apiBase: currentBase });
543
- if (result.ok) {
544
- progress.stop(`Still authenticated as @${result.agent.handle}.`);
545
- return { cfg };
505
+ };
506
+ }
507
+ function describeRegisterStartError(result) {
508
+ switch (result.reason) {
509
+ case "invalid-handle":
510
+ return "That handle is not acceptable. Try a different one (3\u201330 chars \u2014 lowercase letters/digits/hyphens; must start with a letter).";
511
+ case "handle-taken":
512
+ return "That handle is already taken. Try a different one.";
513
+ case "email-taken":
514
+ return "That email is already registered as an agent. Paste the existing key instead, or use a different email.";
515
+ case "email-exhausted":
516
+ return "This email has reached the agent quota. Use a different email, or paste a key from an existing agent.";
517
+ case "rate-limited": {
518
+ const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
519
+ return `Rate limited.${wait}`;
546
520
  }
547
- progress.stop("Key no longer works.");
548
- await prompter.note(`${result.message} [reason=${result.reason}]`, "Re-validation failed");
549
- const doRotate = await prompter.confirm({
550
- message: "Rotate to a new key now?",
551
- initialValue: true
552
- });
553
- if (doRotate) return runNewAccountFlow(cfg, accountId, prompter, currentBase);
554
- return { cfg };
555
- }
556
- if (choice === "rotate") {
557
- return runNewAccountFlow(cfg, accountId, prompter, currentBase);
521
+ case "otp-failed":
522
+ return "The verification-code email could not be sent. Try again in a minute.";
523
+ case "network-error":
524
+ case "server-error":
525
+ case "validation":
526
+ default:
527
+ return result.message;
558
528
  }
559
- const nextBase = await promptOptionalText(
560
- prompter,
561
- "New API base URL (blank to reset to default)",
562
- currentBase ?? "https://api.agentchat.me"
563
- );
564
- if (nextBase) {
565
- try {
566
- const url = new URL(nextBase);
567
- if (url.protocol !== "https:" && url.protocol !== "http:") {
568
- await prompter.note("API base must use http:// or https://. Not updated.", "Ignored");
569
- return { cfg };
570
- }
571
- } catch {
572
- await prompter.note("Not a valid URL. API base not updated.", "Ignored");
573
- return { cfg };
529
+ }
530
+ function describeRegisterVerifyError(result) {
531
+ switch (result.reason) {
532
+ case "expired":
533
+ return "This code expired. Restart the wizard to receive a new one.";
534
+ case "invalid-code":
535
+ return "Too many incorrect codes. Restart the wizard to receive a new one.";
536
+ case "handle-taken":
537
+ return "Your chosen handle was claimed by another registration in the meantime. Restart with a different handle.";
538
+ case "email-taken":
539
+ return "This email is already registered. Paste the existing key instead.";
540
+ case "rate-limited": {
541
+ const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
542
+ return `Rate limited.${wait}`;
574
543
  }
544
+ case "network-error":
545
+ case "server-error":
546
+ case "unexpected-shape":
547
+ case "validation":
548
+ default:
549
+ return result.message;
575
550
  }
576
- const next = writeAccountPatch(cfg, accountId, { apiBase: nextBase || void 0 });
577
- await prompter.note(
578
- nextBase ? `API base set to ${nextBase}` : "API base reset to default",
579
- "Updated"
580
- );
581
- return { cfg: next };
582
551
  }
583
- async function runNewAccountFlow(cfg, accountId, prompter, apiBase) {
584
- const choice = await prompter.select({
585
- message: "How do you want to connect this agent?",
586
- options: [
587
- {
588
- value: "register",
589
- label: "Register a new agent (email + OTP)",
590
- hint: "Mint a fresh API key \u2014 ~60 seconds"
591
- },
592
- {
593
- value: "have-key",
594
- label: "I already have an API key",
595
- hint: "Paste ac_live_..."
596
- }
597
- ],
598
- initialValue: "register"
599
- });
600
- if (choice === "have-key") return runHaveKeyFlow(cfg, accountId, prompter, apiBase);
601
- return runRegisterFlow(cfg, accountId, prompter, apiBase);
552
+ function redactKey(apiKey) {
553
+ if (apiKey.length < 12) return "\u2022\u2022\u2022\u2022";
554
+ return `${apiKey.slice(0, 8)}\u2026${apiKey.slice(-4)}`;
602
555
  }
603
556
  var agentchatSetupWizard = {
604
557
  channel: AGENTCHAT_CHANNEL_ID,
605
- resolveShouldPromptAccountIds: () => false,
606
558
  status: {
607
- configuredLabel: "connected",
608
- unconfiguredLabel: "needs API key",
609
- configuredHint: "configured",
610
- unconfiguredHint: "needs agent credentials",
611
- configuredScore: 2,
612
- unconfiguredScore: 0,
613
- resolveConfigured: ({ cfg, accountId }) => isAccountConfigured(cfg, accountId),
614
- resolveStatusLines: async ({ cfg, accountId, configured }) => {
615
- if (!configured) return ["AgentChat: needs API key \u2014 run setup to register or paste one"];
616
- const id = accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID;
617
- const key = readAccountApiKey(cfg, id);
618
- const apiBase = readAccountApiBase(cfg, id);
619
- if (!key) return ["AgentChat: configured (no key visible)"];
620
- try {
621
- const result = await validateApiKey(key, { apiBase, timeoutMs: 3e3 });
622
- if (result.ok) return [`AgentChat: connected as @${result.agent.handle}`];
623
- return [`AgentChat: configured (live probe failed: ${result.reason})`];
624
- } catch {
625
- return ["AgentChat: configured (live probe unreachable)"];
559
+ configuredLabel: "configured",
560
+ unconfiguredLabel: "not configured",
561
+ configuredHint: "AgentChat agent is ready to receive messages",
562
+ unconfiguredHint: "connect your agent to the AgentChat messaging platform",
563
+ configuredScore: 90,
564
+ unconfiguredScore: 30,
565
+ resolveConfigured: ({ cfg, accountId }) => {
566
+ return hasConfiguredKey(cfg, accountId ?? "default");
567
+ },
568
+ resolveStatusLines: ({ cfg, accountId, configured }) => {
569
+ const id = accountId ?? "default";
570
+ if (!configured) {
571
+ return ["AgentChat: not configured \u2014 the wizard will register you or accept an existing key."];
626
572
  }
573
+ const handle = readAgentchatConfigField(cfg, id, "agentHandle");
574
+ return [`AgentChat: configured${handle ? ` (@${handle})` : ""}`];
627
575
  }
628
576
  },
629
577
  introNote: {
630
578
  title: "AgentChat",
631
579
  lines: [
632
- "A messaging platform for AI agents \u2014 handle-based routing, realtime WebSocket,",
633
- "typed error taxonomy, idempotent sends.",
580
+ "AgentChat is a messaging platform for AI agents \u2014 direct messages,",
581
+ "groups, presence, attachments. Registration is free.",
634
582
  "",
635
- "You can paste an existing API key, or register a new agent inline (email + OTP)."
583
+ "This wizard will either mint a new account via email OTP, or accept",
584
+ "an existing API key \u2014 your choice in the next prompt."
636
585
  ]
637
586
  },
638
- prepare: async ({ cfg, accountId, credentialValues }) => {
639
- const flow = isAccountConfigured(cfg, accountId) ? "edit" : "new";
640
- return { credentialValues: { ...credentialValues, _flow: flow } };
587
+ prepare: async ({ cfg, accountId, credentialValues, prompter }) => {
588
+ if (hasConfiguredKey(cfg, accountId) && typeof credentialValues.token === "string") {
589
+ const editChoice = await prompter.select({
590
+ message: "AgentChat is already configured. What would you like to do?",
591
+ options: [
592
+ {
593
+ value: "keep",
594
+ label: "Keep current config",
595
+ hint: "the credential step will still re-validate on the next run"
596
+ },
597
+ {
598
+ value: "change-base",
599
+ label: "Change API base URL",
600
+ hint: "only for self-hosted AgentChat deployments"
601
+ },
602
+ {
603
+ value: "replace-key",
604
+ label: "Replace the API key",
605
+ hint: "paste a new key, or register a new agent"
606
+ }
607
+ ],
608
+ initialValue: "keep"
609
+ });
610
+ if (editChoice === "keep") return;
611
+ if (editChoice === "change-base") {
612
+ return await runChangeApiBaseFlow({ cfg, accountId, prompter });
613
+ }
614
+ }
615
+ const choice = await prompter.select({
616
+ message: "How would you like to configure AgentChat?",
617
+ options: [
618
+ {
619
+ value: "register",
620
+ label: "Register a new agent (email OTP)",
621
+ hint: "no account yet \u2014 the wizard creates one"
622
+ },
623
+ {
624
+ value: "paste",
625
+ label: "I already have an API key",
626
+ hint: "paste ac_live_\u2026 on the next prompt"
627
+ }
628
+ ],
629
+ initialValue: "register"
630
+ });
631
+ if (choice === "paste") {
632
+ return;
633
+ }
634
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
635
+ try {
636
+ const result = await runRegisterFlow({ cfg, accountId, prompter, apiBase });
637
+ if (result === "abort") {
638
+ await prompter.note(
639
+ "Registration was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
640
+ "Falling back to credential entry"
641
+ );
642
+ return;
643
+ }
644
+ if (result === "user-chose-paste") {
645
+ return;
646
+ }
647
+ return result;
648
+ } catch (err) {
649
+ if (err instanceof WizardCancelledError) throw err;
650
+ await prompter.note(
651
+ `${err instanceof Error ? err.message : String(err)}`,
652
+ "Registration flow failed"
653
+ );
654
+ return;
655
+ }
641
656
  },
642
- credentials: [],
643
- finalize: async ({ cfg, accountId, prompter, credentialValues }) => {
644
- const rawFlow = credentialValues._flow;
645
- const flow = rawFlow === "edit" ? "edit" : "new";
646
- const apiBase = readAccountApiBase(cfg, accountId);
647
- return flow === "edit" ? await runEditFlow(cfg, accountId, prompter) : await runNewAccountFlow(cfg, accountId, prompter, apiBase);
657
+ credentials: [
658
+ {
659
+ inputKey: "token",
660
+ providerHint: "agentchat",
661
+ credentialLabel: "API key",
662
+ preferredEnvVar: "AGENTCHAT_API_KEY",
663
+ envPrompt: "AGENTCHAT_API_KEY detected in env. Use it?",
664
+ keepPrompt: "AgentChat API key already configured. Keep it?",
665
+ inputPrompt: "Paste your AgentChat API key (ac_live_\u2026)",
666
+ helpTitle: "AgentChat API key",
667
+ helpLines: [
668
+ "Format: ac_live_<base64>, \u226520 chars. Validated against",
669
+ "GET /v1/agents/me during this wizard \u2014 bad keys fail fast instead",
670
+ "of flapping reconnects at runtime."
671
+ ],
672
+ allowEnv: () => true,
673
+ shouldPrompt: ({ credentialValues, currentValue }) => {
674
+ if (credentialValues[JUST_REGISTERED_SENTINEL] === "1") return false;
675
+ if (!currentValue) return true;
676
+ return true;
677
+ },
678
+ inspect: ({ cfg, accountId }) => {
679
+ const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
680
+ const configured = isApiKeyPresent(apiKey);
681
+ const envValue = process.env.AGENTCHAT_API_KEY?.trim();
682
+ return {
683
+ accountConfigured: configured,
684
+ hasConfiguredValue: configured,
685
+ resolvedValue: configured ? apiKey : void 0,
686
+ envValue: envValue && envValue.length >= MIN_API_KEY_LENGTH ? envValue : void 0
687
+ };
688
+ }
689
+ }
690
+ ],
691
+ finalize: async ({ cfg, accountId, credentialValues, prompter }) => {
692
+ const apiKey = typeof credentialValues.token === "string" && credentialValues.token.length >= MIN_API_KEY_LENGTH ? credentialValues.token : readAgentchatConfigField(cfg, accountId, "apiKey");
693
+ if (!apiKey || !isApiKeyPresent(apiKey)) {
694
+ return;
695
+ }
696
+ const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
697
+ const spinner = prompter.progress("Validating API key against AgentChat\u2026");
698
+ try {
699
+ const result = await validateApiKey(apiKey, { apiBase });
700
+ if (result.ok) {
701
+ spinner.stop(`Authenticated as @${result.agent.handle}`);
702
+ const existingHandle = readAgentchatConfigField(cfg, accountId, "agentHandle");
703
+ if (!existingHandle && isValidHandleShape(result.agent.handle)) {
704
+ return {
705
+ cfg: applyAgentchatAccountPatch(cfg, accountId, {
706
+ agentHandle: result.agent.handle
707
+ })
708
+ };
709
+ }
710
+ return;
711
+ }
712
+ spinner.stop(`API key did not pass the live check (${result.reason})`);
713
+ await prompter.note(
714
+ [
715
+ result.message,
716
+ "",
717
+ "The config was saved \u2014 you can re-run `openclaw channels add agentchat`",
718
+ "to replace the key, or edit ~/.openclaw/config.yaml directly."
719
+ ].join("\n"),
720
+ "AgentChat validation warning"
721
+ );
722
+ } catch (err) {
723
+ spinner.stop("Could not reach AgentChat for validation");
724
+ await prompter.note(
725
+ [
726
+ err instanceof Error ? err.message : String(err),
727
+ "",
728
+ "The config was saved \u2014 the runtime will retry on startup."
729
+ ].join("\n"),
730
+ "AgentChat API unreachable"
731
+ );
732
+ }
733
+ return;
648
734
  },
649
735
  completionNote: {
650
736
  title: "AgentChat is ready",
651
737
  lines: [
652
- "The channel runtime will auto-connect on the next `openclaw` boot.",
653
- "Messages addressed to your handle arrive over WebSocket; sends go out",
654
- "over HTTPS with at-least-once + idempotent semantics."
738
+ "Next steps:",
739
+ " \u2022 Start OpenClaw \u2014 the AgentChat channel auto-connects via WebSocket.",
740
+ " \u2022 DM another agent: @<handle> <message>",
741
+ " \u2022 Docs: https://agentchat.me/docs"
655
742
  ]
656
743
  },
657
- disable: (cfg) => {
658
- const channels = {
659
- ...cfg?.channels ?? {}
660
- };
661
- const existing = channels[AGENTCHAT_CHANNEL_ID];
662
- const section = existing && typeof existing === "object" && !Array.isArray(existing) ? { ...existing } : {};
663
- section.enabled = false;
664
- channels[AGENTCHAT_CHANNEL_ID] = section;
665
- return { ...cfg, channels };
666
- }
744
+ disable: (cfg) => setSetupChannelEnabled(cfg, AGENTCHAT_CHANNEL_ID, false)
667
745
  };
746
+ var reconnectConfigSchema = z.object({
747
+ initialBackoffMs: z.number().int().min(100).max(1e4).default(1e3),
748
+ maxBackoffMs: z.number().int().min(1e3).max(3e5).default(3e4),
749
+ jitterRatio: z.number().min(0).max(1).default(0.2)
750
+ }).strict();
751
+ var pingConfigSchema = z.object({
752
+ intervalMs: z.number().int().min(5e3).max(12e4).default(3e4),
753
+ timeoutMs: z.number().int().min(1e3).max(3e4).default(1e4)
754
+ }).strict();
755
+ var outboundConfigSchema = z.object({
756
+ maxInFlight: z.number().int().min(1).max(1e4).default(256),
757
+ sendTimeoutMs: z.number().int().min(1e3).max(6e4).default(15e3)
758
+ }).strict();
759
+ var observabilityConfigSchema = z.object({
760
+ logLevel: z.enum(["trace", "debug", "info", "warn", "error"]).default("info"),
761
+ redactKeys: z.array(z.string()).default(["apiKey", "authorization", "cookie", "set-cookie"])
762
+ }).strict();
763
+ var agentHandleSchema = z.string().regex(
764
+ /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,
765
+ "handle must be lowercase letters/digits/hyphens; start with a letter; no trailing or doubled hyphens"
766
+ ).min(3, "handle must be at least 3 characters").max(30, "handle must be at most 30 characters");
767
+ var agentchatChannelConfigSchema = z.object({
768
+ apiBase: z.string().url().default("https://api.agentchat.me"),
769
+ apiKey: z.string().min(20, "apiKey looks too short for an AgentChat API key"),
770
+ agentHandle: agentHandleSchema.optional(),
771
+ // `.prefault({})` — Zod 4 idiom: when the key is missing from input, parse
772
+ // `{}` through the inner schema so its own per-field defaults kick in.
773
+ // Using `.default({})` here fails in Zod 4 because the output type's fields
774
+ // are non-optional once the inner schema has defaults.
775
+ reconnect: reconnectConfigSchema.prefault({}),
776
+ ping: pingConfigSchema.prefault({}),
777
+ outbound: outboundConfigSchema.prefault({}),
778
+ observability: observabilityConfigSchema.prefault({})
779
+ }).strict();
780
+ function parseChannelConfig(input) {
781
+ return agentchatChannelConfigSchema.parse(input);
782
+ }
668
783
 
669
784
  // src/channel.ts
670
- var AGENTCHAT_CHANNEL_ID = "agentchat";
671
- var AGENTCHAT_DEFAULT_ACCOUNT_ID = "default";
672
- var MIN_API_KEY_LENGTH2 = 20;
673
- function readChannelSection(cfg) {
674
- const channels = cfg?.channels;
675
- const section = channels?.[AGENTCHAT_CHANNEL_ID];
676
- return section && typeof section === "object" && !Array.isArray(section) ? section : void 0;
677
- }
678
- function readAccountRaw2(section, accountId) {
679
- if (!section) return void 0;
680
- const { accounts } = section;
681
- if (accounts && typeof accounts === "object" && !Array.isArray(accounts)) {
682
- const entry = accounts[accountId];
683
- if (entry && typeof entry === "object") return entry;
684
- }
685
- if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID) {
686
- const { accounts: _accounts, ...rest } = section;
687
- return rest;
688
- }
689
- return void 0;
690
- }
691
- function splitEnabledFromRaw(raw) {
692
- if (!raw) return { enabled: true, forParse: void 0 };
693
- const { enabled, ...rest } = raw;
694
- return { enabled: enabled !== false, forParse: rest };
695
- }
696
- function isApiKeyPresent(value) {
697
- return typeof value === "string" && value.length >= MIN_API_KEY_LENGTH2;
698
- }
699
785
  var uiHints = {
700
786
  apiKey: {
701
787
  label: "AgentChat API key",
702
788
  placeholder: "ac_live_...",
703
789
  sensitive: true,
704
- help: "Obtain from AgentChat dashboard \u2192 Settings \u2192 API keys."
790
+ help: "The setup wizard registers you via email OTP and mints a key \u2014 or paste an existing ac_live_\u2026 key."
705
791
  },
706
792
  apiBase: {
707
793
  label: "API base URL",
@@ -712,7 +798,7 @@ var uiHints = {
712
798
  agentHandle: {
713
799
  label: "Agent handle",
714
800
  placeholder: "my-agent",
715
- help: "3\u201332 chars, lowercase alphanumeric plus . _ -"
801
+ help: "3\u201330 chars, lowercase letters/digits/hyphens; must start with a letter."
716
802
  },
717
803
  reconnect: { label: "Reconnect backoff", advanced: true },
718
804
  ping: { label: "WebSocket ping cadence", advanced: true },
@@ -763,7 +849,7 @@ var agentchatPlugin = {
763
849
  resolveAccount(cfg, accountId) {
764
850
  const id = accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID;
765
851
  const section = readChannelSection(cfg);
766
- const raw = readAccountRaw2(section, id);
852
+ const raw = readAccountRaw(section, id);
767
853
  const { enabled, forParse } = splitEnabledFromRaw(raw);
768
854
  let config = null;
769
855
  let parseError = null;
@@ -828,8 +914,8 @@ var agentchatPlugin = {
828
914
  if (typeof input.token !== "string" || input.token.trim().length === 0) {
829
915
  return "apiKey is required \u2014 pass via --token or run the register flow";
830
916
  }
831
- if (input.token.length < MIN_API_KEY_LENGTH2) {
832
- return `apiKey looks too short (got ${input.token.length} chars, expect \u2265${MIN_API_KEY_LENGTH2})`;
917
+ if (input.token.length < MIN_API_KEY_LENGTH) {
918
+ return `apiKey looks too short (got ${input.token.length} chars, expect \u2265${MIN_API_KEY_LENGTH})`;
833
919
  }
834
920
  if (typeof input.url === "string" && input.url.length > 0) {
835
921
  try {
@@ -844,26 +930,10 @@ var agentchatPlugin = {
844
930
  return null;
845
931
  },
846
932
  applyAccountConfig({ cfg, accountId, input }) {
847
- const channels = {
848
- ...cfg?.channels ?? {}
849
- };
850
- const currentSection = channels[AGENTCHAT_CHANNEL_ID];
851
- const section = currentSection && typeof currentSection === "object" && !Array.isArray(currentSection) ? { ...currentSection } : {};
852
933
  const patch = {};
853
934
  if (typeof input.token === "string" && input.token.length > 0) patch.apiKey = input.token;
854
935
  if (typeof input.url === "string" && input.url.length > 0) patch.apiBase = input.url;
855
- if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID && !section.accounts) {
856
- Object.assign(section, patch);
857
- } else {
858
- const accounts = {
859
- ...section.accounts ?? {}
860
- };
861
- const prevAccount = typeof accounts[accountId] === "object" && accounts[accountId] !== null ? accounts[accountId] : {};
862
- accounts[accountId] = { ...prevAccount, ...patch };
863
- section.accounts = accounts;
864
- }
865
- channels[AGENTCHAT_CHANNEL_ID] = section;
866
- return { ...cfg, channels };
936
+ return applyAgentchatAccountPatch(cfg, accountId, patch);
867
937
  },
868
938
  /**
869
939
  * Post-write probe: call `GET /v1/agents/me` with the key we just wrote