@agentchatme/agent-core 0.5.0 → 0.5.2

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
@@ -83,7 +83,7 @@ import {
83
83
  writeCredentials,
84
84
  writeIntegrationStatus,
85
85
  writePending
86
- } from "./chunk-NAAHIK7Z.js";
86
+ } from "./chunk-CDJASQ3X.js";
87
87
  import {
88
88
  HOSTED_MCP_PATH,
89
89
  PROBE_KILL_WAIT_MS,
@@ -91,7 +91,7 @@ import {
91
91
  hostedMcpUrl,
92
92
  probeHostedMcp,
93
93
  runProbe
94
- } from "./chunk-UE7DKW3C.js";
94
+ } from "./chunk-WDHXWAWF.js";
95
95
  import {
96
96
  DEFAULT_RUN_BUDGET_MS,
97
97
  DEFAULT_RUN_PROFILE,
@@ -334,34 +334,13 @@ function renderUnregisteredBlock(copy) {
334
334
  "",
335
335
  `FIRST ask exactly: "Do you already have an AgentChat account for this ${label} agent, or should I create a new one?"`,
336
336
  "",
337
- "If they want a new account:",
338
- " **Ask only one question per turn. Never ask for the email and handle in the same message.**",
339
- ' 1. Ask only: "I need an email for verification and recovery. Which email should I use? After we choose my handle, AgentChat will send a 6-digit code there, and I\u2019ll ask you to paste it here."',
340
- ' 2. After they answer, say: "Now we need to choose an AgentChat username for me\u2014my @handle, which other agents will use to reach me."',
341
- ' Explain the rules simply: "Use 3\u201330 characters: lowercase letters, numbers, and hyphens. Start with a letter; no double or trailing hyphens."',
342
- ' If there is a concrete, relevant candidate, ask: "How about @<candidate>?" Otherwise ask: "What username should I use? If you want, I can suggest one."',
343
- ` 3. Once there is an email and handle, run: ${invoke} register --email <email> --handle <handle>`,
344
- " Registration is the authoritative availability check. Never promise availability before it succeeds.",
345
- " If their handle is taken or invalid, ask only for another handle, keep the same email, and retry only after they choose or accept the replacement.",
346
- " Never submit a handle the user has not chosen or accepted.",
347
- ' 4. Only after registration confirms the code was sent, say: "AgentChat sent a 6-digit code to <email>. Paste it here and I\u2019ll finish setup."',
348
- ` 5. Run: ${invoke} register --code <code>`,
349
- ' 6. On success, use the command\u2019s exact handle and path: "Done\u2014I\u2019m registered as @<handle>. The API key is stored at <credentials-path>."',
337
+ "**Run the commands yourself, and ask the user one question per turn.** Each command prints AgentChat\u2019s answer, then the command to run next. Relay the answer to the user as it is; ask them for what the next command needs (a value it leaves as `<\u2026>`, such as the code AgentChat emailed them); if it says to wait, wait; then run it. When a command prints no command to run next, stop and tell the user what it said.",
350
338
  "",
351
- `If they already have an account for this ${label} agent:`,
352
- " **Ask one question per turn. Run the commands yourself.**",
353
- ' 1. Ask exactly: "Give me the AgentChat API key for this account. If you no longer have it, I can help you recover the account."',
354
- ` 2. If they provide it, run: ${invoke} login --api-key <ac_\u2026>`,
355
- ' On success, use the command\u2019s exact handle and path: "Done\u2014I\u2019m signed in as @<handle>. The API key is stored at <credentials-path>."',
356
- ' If login fails, say: "That API key didn\u2019t work. Please check it and send it again, or tell me if you need to recover the account."',
357
- ' 3. If they no longer have the key, ask exactly: "I can recover the account. This will replace the old API key, so anything still using it will stop working. What email did you use for this AgentChat account?"',
358
- ' 4. Then ask only: "Which @handle is the account? One email can back several agents, so recovery needs both."',
359
- ` 5. Run: ${invoke} recover --handle <handle> --email <email>`,
360
- ' 6. Once recovery accepts the request, say: "If @<handle> is registered with <email>, AgentChat sent a 6-digit recovery code to <email>. Paste it here and I\u2019ll finish signing in."',
361
- ` 7. Run: ${invoke} recover --code <code>`,
362
- ' On success, use the command\u2019s exact handle and path: "Done\u2014I recovered the account and signed in as @<handle>. The new API key is stored at <credentials-path>. The old key no longer works."',
363
- ' If the code fails, say: "That code didn\u2019t work. Check the 6 digits and paste it again."',
364
- " 8. Never reuse another active coding agent\u2019s account; each reachable agent needs its own.",
339
+ `- **New account:** ask for their email, then for the @handle they want (offer a suggestion if they like). Run: \`${invoke} register --email <email> --handle <handle>\`. Never submit a handle the user has not chosen or accepted.`,
340
+ `- **Existing account, with its API key:** run: \`${invoke} login --api-key <ac_\u2026>\``,
341
+ `- **Existing account, key lost:** recovery replaces the old API key, so anything still using it stops working; say so and ask before going on. Ask for the email the account uses, then which @handle it is. Run: \`${invoke} recover --handle <handle> --email <email>\``,
342
+ "- **When it is done:** tell the user the @handle and where the API key is stored, exactly as the command printed them.",
343
+ "- Never reuse another active coding agent\u2019s account; each reachable agent needs its own.",
365
344
  "",
366
345
  `**If they decline or say "later", run \`${invoke} register --not-now\` immediately.** That records the answer and removes this prompt \u2014 otherwise you will re-read it and ask again every session.`,
367
346
  ANCHOR_END
@@ -382,7 +361,7 @@ function renderDeclinedBlock(copy) {
382
361
 
383
362
  // src/identity/commands.ts
384
363
  import * as readline from "readline";
385
- import { AgentChatClient } from "agentchatme";
364
+ import { AgentChatClient, integration as kit2 } from "agentchatme";
386
365
 
387
366
  // src/identity/host-profile.ts
388
367
  function anchorLabelOf(profile) {
@@ -394,10 +373,6 @@ function anchorLabelOf(profile) {
394
373
  }
395
374
 
396
375
  // src/identity/commands.ts
397
- var HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
398
- function validHandle(handle) {
399
- return handle.length >= 3 && handle.length <= 30 && HANDLE_PATTERN.test(handle);
400
- }
401
376
  var NO_TEXTS = Object.freeze({ identityLine: null, identityLineTemplate: null, manual: null });
402
377
  function errorText(err) {
403
378
  return err instanceof Error ? err.message : String(err);
@@ -408,24 +383,26 @@ function contextOf(texts) {
408
383
  async function prompt(question) {
409
384
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
410
385
  try {
411
- const answer = await new Promise((resolve2) => rl.question(question, resolve2));
412
- return answer.trim();
386
+ return await new Promise((resolve2) => {
387
+ rl.once("close", () => resolve2(null));
388
+ rl.question(question, (answer) => resolve2(answer.trim()));
389
+ });
413
390
  } finally {
414
391
  rl.close();
415
392
  }
416
393
  }
394
+ function interactive() {
395
+ return process.stdin.isTTY === true && process.stdout.isTTY === true;
396
+ }
417
397
  async function readAllStdin() {
418
398
  const chunks = [];
419
399
  for await (const chunk of process.stdin) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
420
400
  return Buffer.concat(chunks).toString("utf-8").trim();
421
401
  }
422
- function limitOf(e) {
423
- const limit = e.details?.["limit"];
424
- return typeof limit === "number" && Number.isFinite(limit) ? limit : null;
425
- }
426
- function handlesOf(e) {
427
- const handles = e.details?.["handles"];
428
- return Array.isArray(handles) ? handles.filter((h) => typeof h === "string") : [];
402
+ function describeApiError(err) {
403
+ const e = err ?? {};
404
+ const message = typeof e.message === "string" ? e.message : String(err);
405
+ return typeof e.code === "string" ? `${e.code}: ${message}` : message;
429
406
  }
430
407
  function httpStatusOf(err) {
431
408
  const status = err?.status;
@@ -434,50 +411,59 @@ function httpStatusOf(err) {
434
411
  function recoverUsage(invocation) {
435
412
  return `${invocation} recover --handle <handle> --email <email>`;
436
413
  }
437
- function describeApiError(err, invocation) {
438
- const e = err ?? {};
439
- const code = typeof e.code === "string" ? e.code : void 0;
440
- const message = typeof e.message === "string" ? e.message : String(err);
441
- switch (code) {
442
- case "HANDLE_TAKEN":
443
- return "That handle is already taken \u2014 pick another and re-run.";
444
- // An email backs a bounded number of live agents, and the bound is a
445
- // server-side setting — so the number is always the one the server just
446
- // reported, never a constant here. `EMAIL_TAKEN` is what a not-yet-upgraded
447
- // server says in the same situation (its bound was one).
448
- case "EMAIL_LIMIT_REACHED":
449
- case "EMAIL_TAKEN": {
450
- const limit = limitOf(e);
451
- const lead = limit !== null ? `This email already backs ${limit} active agent${limit === 1 ? "" : "s"} \u2014 its maximum.` : message;
452
- return `${lead} Delete one, sign in to one with \`${invocation} login\`, re-key one with \`${recoverUsage(invocation)}\`, or register with a different email (a + alias such as you+agent@example.com counts as a different email).`;
453
- }
454
- case "EMAIL_EXHAUSTED": {
455
- const limit = limitOf(e);
456
- const lead = limit !== null ? `This email has reached its lifetime maximum of ${limit} account registrations.` : message;
457
- return `${lead} Register with a different email (a + alias such as you+agent@example.com counts as a different email).`;
458
- }
459
- case "HANDLE_REQUIRED": {
460
- const handles = handlesOf(e);
461
- const listed = handles.length > 0 ? ` Agents on this email: ${handles.map((h) => `@${h}`).join(", ")}.` : "";
462
- return `This email backs more than one agent, so the server needs to know which one to re-key.${listed} Run recovery again with the handle: ${recoverUsage(invocation)}`;
463
- }
464
- case "INVALID_HANDLE":
465
- return "The server rejected the handle (invalid or reserved word).";
466
- case "INVALID_CODE":
467
- return `Wrong or expired code. Re-check the 6 digits; after too many misses you must restart with \`${invocation} register\`.`;
468
- case "EXPIRED":
469
- return `This registration expired (codes last 10 minutes). Start over with \`${invocation} register\`.`;
470
- default:
471
- return code ? `${code}: ${message}` : message;
414
+ function emailInput(raw) {
415
+ const email = raw?.trim().toLowerCase();
416
+ return email ? email : void 0;
417
+ }
418
+ function handleInput(raw) {
419
+ const handle = raw?.trim().replace(/^@/, "").toLowerCase();
420
+ return handle ? handle : void 0;
421
+ }
422
+ var VERIFY_STEP = { register: "verify", recover: "recover_verify" };
423
+ function shellValue(value) {
424
+ return /^[A-Za-z0-9@%+=:,./_-]+$/.test(value) ? value : JSON.stringify(value);
425
+ }
426
+ function receivedAtMs(pending) {
427
+ const at = Date.parse(pending.received_at);
428
+ return Number.isFinite(at) ? at : null;
429
+ }
430
+ function codeMayWork(pending, now = Date.now()) {
431
+ const received = receivedAtMs(pending);
432
+ if (pending.flow.expires_in_s !== void 0 && received !== null) return received + pending.flow.expires_in_s * 1e3 > now;
433
+ if (pending.flow.expires_at !== void 0) {
434
+ const at = Date.parse(pending.flow.expires_at);
435
+ if (Number.isFinite(at)) return at > now;
472
436
  }
437
+ return true;
438
+ }
439
+ function resendLeftS(pending, now = Date.now()) {
440
+ if (pending === null || pending.flow.resend_after_s === void 0) return 0;
441
+ const received = receivedAtMs(pending);
442
+ if (received === null) return 0;
443
+ return Math.max(0, Math.ceil((pending.flow.resend_after_s * 1e3 - (now - received)) / 1e3));
444
+ }
445
+ function runLine(command, waitS = 0) {
446
+ return waitS > 0 ? `Wait ${waitS} s, then run \`${command}\`` : `Run \`${command}\``;
447
+ }
448
+ async function askOnTerminal(question) {
449
+ if (question.field === "new_code") {
450
+ const answer2 = await prompt("Send a new code? [y/N] ");
451
+ return answer2 !== null && /^y(es)?$/i.test(answer2) ? { answer: "new_code" } : { answer: "cancel" };
452
+ }
453
+ const choices = question.handles !== void 0 && question.handles.length > 0 ? ` (${question.handles.map((h) => `@${h}`).join(", ")})` : "";
454
+ const hint = question.field === "code" ? ' (or "new" for a new code)' : "";
455
+ const answer = await prompt(`${question.label ?? question.field}${choices}${hint}: `);
456
+ if (answer === null) return { answer: "cancel" };
457
+ if (question.field === "code") return answer.toLowerCase() === "new" ? { answer: "new_code" } : { answer: "value", value: answer };
458
+ return { answer: "value", value: (question.field === "handle" ? handleInput(answer) : emailInput(answer)) ?? "" };
473
459
  }
474
460
  var NEXT_HINT = "Open a new session for the hosted AgentChat tools to pick up the key; the integration daemon follows the credential on its own.";
475
461
  function createIdentityCommands(profile) {
476
462
  const invocation = () => profile.invocation();
477
- const apiErr = (err) => describeApiError(err, invocation());
478
463
  const LABEL = profile.label;
479
464
  const clientIdentity = clientIdentityOf(profile.client);
480
- const apiClient = (apiKey, apiBase, budget = "quick") => budget === "quick" ? new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 5e3, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } }) : new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 15e3 });
465
+ const apiClient = (apiKey, apiBase) => new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 5e3, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } });
466
+ const accountOptions = (apiBase) => ({ clientIdentity, apiBase, timeoutMs: 15e3 });
481
467
  async function served(apiKey, apiBase) {
482
468
  const loaded = await loadTexts({ home: profile.home(), runtime: profile.client.runtime, client: apiClient(apiKey, apiBase), timeoutMs: 5e3 });
483
469
  return loaded === null ? NO_TEXTS : contextOf(loaded.texts);
@@ -518,132 +504,205 @@ function createIdentityCommands(profile) {
518
504
  return [` ${label}: FAILED \u2014 ${String(err)}`];
519
505
  }
520
506
  }
521
- async function runRegister(opts) {
522
- const home = profile.home();
523
- const apiBase = opts.apiBase ?? process.env["AGENTCHAT_API_BASE"] ?? DEFAULT_API_BASE;
524
- if (opts.code !== void 0) {
525
- const code = opts.code.trim();
526
- if (!/^\d{6}$/.test(code)) {
527
- console.error("The code is the 6-digit number from the verification email.");
528
- return 1;
529
- }
530
- const pending = readPending(home);
531
- if (pending === null) {
532
- console.error(
533
- `No registration in progress. Start with: ${invocation()} register --email <email> --handle <handle>`
534
- );
535
- return 1;
536
- }
537
- if (pending.kind === "recover") {
538
- console.error(
539
- `The pending code belongs to an account RECOVERY \u2014 complete it with: ${invocation()} recover --code ${code}`
540
- );
541
- return 1;
542
- }
543
- const pendingHandle = pending.handle;
544
- if (pendingHandle === void 0) {
545
- clearPending(home);
546
- console.error(`Pending registration was corrupt \u2014 start again with: ${invocation()} register`);
547
- return 1;
507
+ function startCommand(kind, input, blank) {
508
+ const email = blank === "email" ? "<email>" : shellValue(input.email);
509
+ const handle = blank === "handle" ? "<handle>" : input.handle !== void 0 ? shellValue(input.handle) : null;
510
+ if (kind === "recover") return `${invocation()} recover${handle !== null ? ` --handle ${handle}` : ""} --email ${email}`;
511
+ return [
512
+ `${invocation()} register --email ${email} --handle ${handle ?? "<handle>"}`,
513
+ ...input.display_name !== void 0 ? [`--display-name ${shellValue(input.display_name)}`] : [],
514
+ ...input.description !== void 0 ? [`--description ${shellValue(input.description)}`] : []
515
+ ].join(" ");
516
+ }
517
+ function codeCommand(kind, flow, code) {
518
+ const value = code !== void 0 ? shellValue(code) : flow.code_length !== void 0 ? `<${flow.code_length} digits>` : "<code>";
519
+ return `${invocation()} ${kind} --code ${value}`;
520
+ }
521
+ function nextSteps(kind, result, called, input, code, held) {
522
+ const beforeNewCode = Math.max(result.flow.retry_after_s ?? 0, result.flow.resend_after_s ?? resendLeftS(held));
523
+ const heldCode = called === "start" && result.httpStatus === 429 && held !== null && held.handle === input.handle && codeMayWork(held) ? [`Or enter the code already sent: \`${codeCommand(kind, held.flow)}\``] : [];
524
+ switch (result.action) {
525
+ case "done":
526
+ return [];
527
+ case "ask_code":
528
+ return [runLine(codeCommand(kind, result.flow))];
529
+ case "ask_param": {
530
+ const param = result.flow.param;
531
+ const field = param === "email" ? "email" : param === "handle" ? "handle" : null;
532
+ if (field === null) return [];
533
+ const handles = field === "handle" ? result.handles ?? [] : [];
534
+ const choices = handles.length > 0 ? `, with one of: ${handles.map((h) => `@${h}`).join(", ")}` : "";
535
+ return [`${runLine(startCommand(kind, input, field), beforeNewCode)}${choices}`];
548
536
  }
549
- try {
550
- const result = await AgentChatClient.verify(pending.pending_id, code, {
551
- baseUrl: pending.api_base ?? apiBase,
552
- clientIdentity
553
- });
554
- writeCredentials(home, {
555
- api_key: result.apiKey,
556
- handle: pendingHandle,
557
- ...pending.api_base ? { api_base: pending.api_base } : {},
558
- created_at: (/* @__PURE__ */ new Date()).toISOString()
559
- });
560
- clearPending(home);
561
- clearOfferDeclined(home);
562
- console.log(
563
- [
564
- `Registered: @${pendingHandle} for ${LABEL}.`,
565
- `API key stored at ${credentialsPath(home)} (never commit this file).`,
566
- ...await placeIdentity(pendingHandle, result.apiKey, pending.api_base ?? apiBase),
567
- "",
568
- `This handle belongs to your ${LABEL} agent. Another coding agent on this machine is a separate peer with its own handle \u2014 you can DM each other.`,
569
- `Other agents can DM you at @${pendingHandle}. Check \`${invocation()} status\` any time.`,
570
- NEXT_HINT
571
- ].join("\n")
572
- );
573
- return 0;
574
- } catch (err) {
575
- console.error(`Verification failed. ${apiErr(err)}`);
576
- return 1;
537
+ case "offer_new_code":
538
+ return [`For a new code: ${runLine(startCommand(kind, input), beforeNewCode)}`];
539
+ case "wait_then_retry": {
540
+ const again = called === "verify" ? codeCommand(kind, result.flow, code) : startCommand(kind, input);
541
+ return [runLine(again, result.flow.retry_after_s ?? 0), ...heldCode];
577
542
  }
543
+ case "stop":
544
+ return heldCode;
578
545
  }
579
- if (resolveIdentity(home) !== null) {
546
+ }
547
+ function report(result, lines, ok) {
548
+ const said = result.message.length > 0 ? result.message : result.code ?? `HTTP ${result.httpStatus}`;
549
+ const text = [said, ...lines].join("\n");
550
+ if (ok) console.log(text);
551
+ else console.error(text);
552
+ return ok ? 0 : 1;
553
+ }
554
+ async function finishSignup(kind, apiKey, handle, apiBase, message) {
555
+ const home = profile.home();
556
+ writeCredentials(home, {
557
+ api_key: apiKey,
558
+ handle,
559
+ ...apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {},
560
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
561
+ });
562
+ clearPending(home);
563
+ clearOfferDeclined(home);
564
+ const placed = await placeIdentity(handle, apiKey, apiBase);
565
+ const lines = kind === "register" ? [
566
+ `API key for @${handle} stored at ${credentialsPath(home)} (never commit this file).`,
567
+ ...placed,
568
+ "",
569
+ `This handle belongs to your ${LABEL} agent. Another coding agent on this machine is a separate peer with its own handle \u2014 you can DM each other.`,
570
+ `Other agents can DM you at @${handle}. Check \`${invocation()} status\` any time.`,
571
+ NEXT_HINT
572
+ ] : [`New API key for @${handle} stored at ${credentialsPath(home)} (never commit this file).`, ...placed, NEXT_HINT];
573
+ console.log([...message !== null && message.length > 0 ? [message] : [], ...lines].join("\n"));
574
+ return 0;
575
+ }
576
+ async function startSignup(kind, input, apiBase) {
577
+ const home = profile.home();
578
+ const before = readPending(home);
579
+ const held = before !== null && before.kind === kind && before.email === input.email ? before : null;
580
+ let result;
581
+ try {
582
+ result = kind === "register" ? await kit2.account.start(
583
+ "register",
584
+ {
585
+ email: input.email,
586
+ handle: input.handle ?? "",
587
+ ...input.display_name !== void 0 ? { display_name: input.display_name } : {},
588
+ ...input.description !== void 0 ? { description: input.description } : {}
589
+ },
590
+ accountOptions(apiBase)
591
+ ) : await kit2.account.start(
592
+ "recover",
593
+ { email: input.email, ...input.handle !== void 0 ? { handle: input.handle } : {} },
594
+ accountOptions(apiBase)
595
+ );
596
+ } catch (err) {
597
+ console.error(`Could not reach AgentChat: ${errorText(err)}
598
+ ${runLine(startCommand(kind, input))} again.`);
599
+ return 1;
600
+ }
601
+ if (result.action === "ask_code") {
602
+ writePending(home, {
603
+ kind,
604
+ flow: result.flow,
605
+ received_at: (/* @__PURE__ */ new Date()).toISOString(),
606
+ ...input,
607
+ ...apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}
608
+ });
609
+ }
610
+ return report(result, nextSteps(kind, result, "start", input, void 0, held), result.action === "ask_code");
611
+ }
612
+ async function submitPendingCode(kind, rawCode, apiBase) {
613
+ const home = profile.home();
614
+ const code = rawCode.trim();
615
+ const pending = readPending(home);
616
+ const noun = kind === "register" ? "registration" : "recovery";
617
+ if (pending === null) {
580
618
  console.error(
581
- `${LABEL} already has an AgentChat identity (see \`${invocation()} status\`). Run \`${invocation()} logout\` first to replace it.`
619
+ `No ${noun} in progress. Start with: ${kind === "register" ? `${invocation()} register --email <email> --handle <handle>` : recoverUsage(invocation())}`
582
620
  );
583
621
  return 1;
584
622
  }
585
- const inFlight = readPending(home);
586
- if (inFlight?.kind === "recover") {
623
+ if (pending.kind !== kind) {
587
624
  console.error(
588
- `An account recovery is in progress \u2014 finish it with \`${invocation()} recover --code <code>\`, or discard it with \`${invocation()} logout\` before registering.`
625
+ pending.kind === "recover" ? `The pending code belongs to an account RECOVERY \u2014 complete it with: ${invocation()} recover --code ${shellValue(code)}` : `The pending code belongs to a REGISTRATION \u2014 complete it with: ${invocation()} register --code ${shellValue(code)}`
589
626
  );
590
627
  return 1;
591
628
  }
592
- let email = opts.email?.trim().toLowerCase();
593
- let handle = opts.handle?.trim().toLowerCase();
594
- const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true;
595
- if (!email) {
596
- if (!interactive) {
597
- console.error(`Missing --email. Usage: ${invocation()} register --email <email> --handle <handle>`);
598
- return 1;
599
- }
600
- email = (await prompt("Email for verification codes: ")).toLowerCase();
629
+ if (pending.flow.next_step !== VERIFY_STEP[kind] || pending.flow.pending_id === void 0) {
630
+ clearPending(home);
631
+ console.error(`The saved ${noun} is not waiting for a code. Start again with: ${startCommand(kind, pending)}`);
632
+ return 1;
601
633
  }
602
- if (!handle) {
603
- if (!interactive) {
604
- console.error(`Missing --handle. Usage: ${invocation()} register --email <email> --handle <handle>`);
605
- return 1;
606
- }
607
- handle = (await prompt("Desired handle (3\u201330 chars, e.g. sanim-dev): ")).toLowerCase();
634
+ const base = pending.api_base ?? apiBase;
635
+ let result;
636
+ try {
637
+ result = await kit2.account.submitCode(pending.flow, code, accountOptions(base));
638
+ } catch (err) {
639
+ console.error(`Could not reach AgentChat: ${errorText(err)}
640
+ ${runLine(codeCommand(kind, pending.flow, code))} again.`);
641
+ return 1;
642
+ }
643
+ switch (result.action) {
644
+ case "done":
645
+ return finishSignup(kind, result.apiKey, result.handle, base, result.message);
646
+ case "ask_code":
647
+ writePending(home, { ...pending, flow: result.flow, received_at: (/* @__PURE__ */ new Date()).toISOString() });
648
+ break;
649
+ case "offer_new_code":
650
+ case "ask_param":
651
+ clearPending(home);
652
+ break;
653
+ default:
654
+ break;
608
655
  }
609
- if (!email.includes("@")) {
610
- console.error(`"${email}" does not look like an email address.`);
656
+ return report(result, nextSteps(kind, result, "verify", pending, code, pending), false);
657
+ }
658
+ async function converse(kind, input, apiBase) {
659
+ let outcome;
660
+ try {
661
+ outcome = await kit2.account.run({
662
+ kind,
663
+ input,
664
+ ...accountOptions(apiBase),
665
+ show: (message) => console.log(message),
666
+ ask: askOnTerminal
667
+ });
668
+ } catch (err) {
669
+ console.error(`Could not reach AgentChat: ${errorText(err)}`);
611
670
  return 1;
612
671
  }
613
- if (!validHandle(handle)) {
672
+ if (outcome.outcome === "done") return finishSignup(kind, outcome.apiKey, outcome.handle, apiBase, null);
673
+ if (outcome.outcome === "cancelled") console.error("Cancelled.");
674
+ return 1;
675
+ }
676
+ async function runRegister(opts) {
677
+ const home = profile.home();
678
+ const apiBase = opts.apiBase ?? process.env["AGENTCHAT_API_BASE"] ?? DEFAULT_API_BASE;
679
+ if (opts.code !== void 0) return submitPendingCode("register", opts.code, apiBase);
680
+ if (resolveIdentity(home) !== null) {
614
681
  console.error(
615
- `Handle "@${handle}" is invalid. Rules: 3\u201330 characters, lowercase letters/digits/hyphens, must start with a letter, no trailing or doubled hyphens.`
682
+ `${LABEL} already has an AgentChat identity (see \`${invocation()} status\`). Run \`${invocation()} logout\` first to replace it.`
616
683
  );
617
684
  return 1;
618
685
  }
619
- try {
620
- const result = await AgentChatClient.register({
621
- email,
622
- handle,
623
- ...opts.displayName ? { display_name: opts.displayName } : {},
624
- ...opts.description ? { description: opts.description } : {},
625
- baseUrl: apiBase,
626
- clientIdentity
627
- });
628
- writePending(home, {
629
- kind: "register",
630
- pending_id: result.pending_id,
631
- email,
632
- handle,
633
- ...apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {},
634
- created_at: (/* @__PURE__ */ new Date()).toISOString()
635
- });
636
- console.log(
637
- [
638
- `Verification code sent to ${email} (valid ~10 minutes).`,
639
- `Complete with: ${invocation()} register --code <6-digit-code>`
640
- ].join("\n")
686
+ if (readPending(home)?.kind === "recover") {
687
+ console.error(
688
+ `An account recovery is in progress \u2014 finish it with \`${invocation()} recover --code <code>\`, or discard it with \`${invocation()} logout\` before registering.`
641
689
  );
642
- return 0;
643
- } catch (err) {
644
- console.error(`Registration failed. ${apiErr(err)}`);
645
690
  return 1;
646
691
  }
692
+ const email = emailInput(opts.email);
693
+ const handle = handleInput(opts.handle);
694
+ const extras = {
695
+ ...opts.displayName ? { display_name: opts.displayName } : {},
696
+ ...opts.description ? { description: opts.description } : {}
697
+ };
698
+ if (email === void 0 || handle === void 0) {
699
+ if (interactive()) {
700
+ return converse("register", { ...email !== void 0 ? { email } : {}, ...handle !== void 0 ? { handle } : {}, ...extras }, apiBase);
701
+ }
702
+ console.error(`Missing --${email === void 0 ? "email" : "handle"}. Usage: ${invocation()} register --email <email> --handle <handle>`);
703
+ return 1;
704
+ }
705
+ return startSignup("register", { email, handle, ...extras }, apiBase);
647
706
  }
648
707
  async function runLogin(opts) {
649
708
  const home = profile.home();
@@ -662,140 +721,65 @@ function createIdentityCommands(profile) {
662
721
  );
663
722
  return 1;
664
723
  } else {
665
- apiKey = await prompt("AgentChat API key (ac_\u2026): ");
724
+ apiKey = await prompt("AgentChat API key (ac_\u2026): ") ?? "";
666
725
  }
667
726
  }
668
- if (apiKey.length < 20) {
669
- console.error("That does not look like an AgentChat API key (too short).");
727
+ if (!apiKey) {
728
+ console.error("No API key given; nothing was saved.");
670
729
  return 1;
671
730
  }
731
+ let check;
672
732
  try {
673
- const client = apiClient(apiKey, apiBase, "patient");
674
- const me = await client.getMe();
675
- writeCredentials(home, {
676
- api_key: apiKey,
677
- handle: me.handle,
678
- ...apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {},
679
- created_at: (/* @__PURE__ */ new Date()).toISOString()
680
- });
681
- clearOfferDeclined(home);
682
- console.log(
683
- [
684
- `Signed in as @${me.handle} for ${LABEL}.`,
685
- `API key stored at ${credentialsPath(home)} (never commit this file).`,
686
- ...await placeIdentity(me.handle, apiKey, apiBase),
687
- NEXT_HINT
688
- ].join("\n")
689
- );
690
- return 0;
733
+ check = await kit2.account.checkKey(apiKey, accountOptions(apiBase));
691
734
  } catch (err) {
692
- console.error(`Login failed. ${apiErr(err)}`);
735
+ console.error(`Login failed: ${errorText(err)}
736
+ The key was not saved.`);
737
+ return 1;
738
+ }
739
+ if (!check.ok) {
740
+ console.error(`Login failed. ${check.code}: ${check.message}
741
+ The key was not saved.`);
693
742
  return 1;
694
743
  }
744
+ writeCredentials(home, {
745
+ api_key: apiKey,
746
+ handle: check.handle,
747
+ ...apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {},
748
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
749
+ });
750
+ clearOfferDeclined(home);
751
+ console.log(
752
+ [
753
+ `Signed in as @${check.handle} for ${LABEL}.`,
754
+ `API key stored at ${credentialsPath(home)} (never commit this file).`,
755
+ ...await placeIdentity(check.handle, apiKey, apiBase),
756
+ NEXT_HINT
757
+ ].join("\n")
758
+ );
759
+ return 0;
695
760
  }
696
761
  async function runRecover(opts) {
697
762
  const home = profile.home();
698
763
  const apiBase = opts.apiBase ?? process.env["AGENTCHAT_API_BASE"] ?? DEFAULT_API_BASE;
699
- const usage = recoverUsage(invocation());
700
- if (opts.code !== void 0) {
701
- const code = opts.code.trim();
702
- if (!/^\d{6}$/.test(code)) {
703
- console.error("The code is the 6-digit number from the recovery email.");
704
- return 1;
705
- }
706
- const pending = readPending(home);
707
- if (pending === null || pending.kind !== "recover") {
708
- console.error(`No recovery in progress. Start with: ${usage}`);
709
- return 1;
710
- }
711
- try {
712
- const result = await AgentChatClient.recoverVerify(pending.pending_id, code, {
713
- baseUrl: pending.api_base ?? apiBase,
714
- clientIdentity
715
- });
716
- writeCredentials(home, {
717
- api_key: result.apiKey,
718
- handle: result.handle,
719
- ...pending.api_base ? { api_base: pending.api_base } : {},
720
- created_at: (/* @__PURE__ */ new Date()).toISOString()
721
- });
722
- clearPending(home);
723
- clearOfferDeclined(home);
724
- console.log(
725
- [
726
- `Recovered: @${result.handle} for ${LABEL}.`,
727
- `New API key stored at ${credentialsPath(home)} (the old key is now revoked; never commit this file).`,
728
- ...await placeIdentity(result.handle, result.apiKey, pending.api_base ?? apiBase),
729
- NEXT_HINT
730
- ].join("\n")
731
- );
732
- return 0;
733
- } catch (err) {
734
- if (err?.code === "HANDLE_REQUIRED") clearPending(home);
735
- console.error(`Recovery failed. ${apiErr(err)}`);
736
- return 1;
737
- }
738
- }
739
- const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true;
740
- let handle = opts.handle?.trim().replace(/^@/, "").toLowerCase();
741
- if (!handle) {
764
+ if (opts.code !== void 0) return submitPendingCode("recover", opts.code, apiBase);
765
+ let handle = handleInput(opts.handle);
766
+ if (handle === void 0) {
742
767
  const stored = readCredentials(home)?.handle;
743
768
  if (stored !== void 0) {
744
769
  handle = stored;
745
770
  console.log(`Recovering @${stored} \u2014 this agent's stored handle (pass --handle to recover a different agent).`);
746
- } else if (interactive) {
747
- handle = (await prompt("Handle of the agent to recover (e.g. sanim-dev): ")).replace(/^@/, "").toLowerCase();
748
- } else {
749
- console.error(
750
- `Missing --handle. An email can back more than one agent, so recovery needs the handle too. Usage: ${usage}`
751
- );
752
- return 1;
753
771
  }
754
772
  }
755
- if (!validHandle(handle)) {
756
- console.error(
757
- `Handle "@${handle}" is invalid. Rules: 3\u201330 characters, lowercase letters/digits/hyphens, must start with a letter, no trailing or doubled hyphens.`
758
- );
759
- return 1;
760
- }
761
- let email = opts.email?.trim().toLowerCase();
762
- if (!email) {
763
- if (!interactive) {
764
- console.error(`Missing --email. Usage: ${usage}`);
773
+ const email = emailInput(opts.email);
774
+ if (email === void 0) {
775
+ if (!interactive()) {
776
+ console.error(`Missing --email. Usage: ${recoverUsage(invocation())}`);
765
777
  return 1;
766
778
  }
767
- email = (await prompt(`Email @${handle} was registered with: `)).toLowerCase();
768
- }
769
- if (!email.includes("@")) {
770
- console.error(`"${email}" does not look like an email address.`);
771
- return 1;
772
- }
773
- try {
774
- const result = await AgentChatClient.recover(email, { handle, baseUrl: apiBase, clientIdentity });
775
- if (!result.pending_id) {
776
- console.log(result.message || "If an agent is registered with that email, a recovery code was sent to it.");
777
- return 0;
778
- }
779
- writePending(home, {
780
- kind: "recover",
781
- pending_id: result.pending_id,
782
- email,
783
- handle,
784
- ...apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {},
785
- created_at: (/* @__PURE__ */ new Date()).toISOString()
786
- });
787
- console.log(
788
- [
789
- `If @${handle} is registered with ${email}, a recovery code was sent there (valid ~10 minutes).`,
790
- `Complete with: ${invocation()} recover --code <6-digit-code>`,
791
- "Note: completing recovery rotates the API key \u2014 anything using the old key stops working."
792
- ].join("\n")
793
- );
794
- return 0;
795
- } catch (err) {
796
- console.error(`Recovery failed. ${apiErr(err)}`);
797
- return 1;
779
+ if (handle === void 0) handle = handleInput(await prompt("Handle of the agent to recover: ") ?? void 0);
780
+ return converse("recover", handle !== void 0 ? { handle } : {}, apiBase);
798
781
  }
782
+ return startSignup("recover", { email, ...handle !== void 0 ? { handle } : {} }, apiBase);
799
783
  }
800
784
  function anchorView(file, identityLine, handle) {
801
785
  if (file === null) return { present: null, current: null, error: null };
@@ -824,14 +808,10 @@ function createIdentityCommands(profile) {
824
808
  integration
825
809
  })
826
810
  );
827
- } else if (pending?.kind === "recover") {
828
- const who = pending.handle !== void 0 ? ` for @${pending.handle}` : "";
829
- console.log(
830
- `No identity yet, but an account recovery${who} is waiting on its emailed code \u2014 finish with: ${invocation()} recover --code <code>`
831
- );
832
811
  } else if (pending !== null) {
812
+ const what = pending.kind === "recover" ? `an account recovery${pending.handle !== void 0 ? ` for @${pending.handle}` : ""}` : `a registration for @${pending.handle ?? "?"}`;
833
813
  console.log(
834
- `No identity yet, but a registration for @${pending.handle ?? "?"} is waiting on its emailed code \u2014 finish with: ${invocation()} register --code <code>`
814
+ codeMayWork(pending) ? `No identity yet, but ${what} is waiting on its emailed code \u2014 finish with: ${codeCommand(pending.kind, pending.flow)}` : `No identity yet; the code for ${what} has expired \u2014 for a new one, run: ${startCommand(pending.kind, pending)}`
835
815
  );
836
816
  } else {
837
817
  console.log(`No AgentChat identity for this ${LABEL} agent. Set one up with: ${invocation()} register`);
@@ -845,7 +825,7 @@ function createIdentityCommands(profile) {
845
825
  } catch (err) {
846
826
  const status = httpStatusOf(err);
847
827
  const refused = status === 401 || status === 403;
848
- const detail = apiErr(err);
828
+ const detail = describeApiError(err);
849
829
  if (opts.json) {
850
830
  const offline = anchorView(anchorFile, null, null);
851
831
  console.log(
@@ -984,15 +964,15 @@ function createIdentityCommands(profile) {
984
964
  }
985
965
  const why = claimed === null ? `no identity line in ${anchorFile}` : claimed !== creds.handle ? `${anchorFile} says @${claimed} but this agent is @${creds.handle}` : `${anchorFile} carries an older identity text for @${claimed}`;
986
966
  if (fix) {
987
- const report = await placeIdentity(creds.handle, creds.api_key, apiBase);
988
- const failed = report.some((l) => l.includes("FAILED") || l.includes("not written"));
989
- if (failed) return { name: "identity-line", verdict: "FAIL", detail: `could not repair: ${report.join("; ")}` };
967
+ const report2 = await placeIdentity(creds.handle, creds.api_key, apiBase);
968
+ const failed = report2.some((l) => l.includes("FAILED") || l.includes("not written"));
969
+ if (failed) return { name: "identity-line", verdict: "FAIL", detail: `could not repair: ${report2.join("; ")}` };
990
970
  try {
991
971
  const after = readIdentityLine(anchorFile, creds.handle, texts);
992
972
  if (after.claimed === creds.handle && after.current !== false) {
993
973
  return { name: "identity-line", verdict: "PASS", detail: `repaired \u2192 @${creds.handle}` };
994
974
  }
995
- return { name: "identity-line", verdict: "FAIL", detail: `repair did not take: ${anchorFile} still ${after.claimed === null ? "has no identity line" : after.claimed !== creds.handle ? `says @${after.claimed}` : "differs from the served block"}${report.length > 0 ? ` (${report.join("; ").trim()})` : ""}` };
975
+ return { name: "identity-line", verdict: "FAIL", detail: `repair did not take: ${anchorFile} still ${after.claimed === null ? "has no identity line" : after.claimed !== creds.handle ? `says @${after.claimed}` : "differs from the served block"}${report2.length > 0 ? ` (${report2.join("; ").trim()})` : ""}` };
996
976
  } catch (err) {
997
977
  return { name: "identity-line", verdict: "FAIL", detail: `cannot read ${anchorFile} after the repair: ${errorText(err)}` };
998
978
  }