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