@agentchatme/agent-core 0.4.1 → 0.5.1

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,13 +1,12 @@
1
1
  import {
2
+ AGENT_LOCK_DIR_ENV,
3
+ DAEMON_LOCK_FILE,
2
4
  DEFAULT_API_BASE,
3
- DEFAULT_RUN_BUDGET_MS,
4
- DEFAULT_RUN_PROFILE,
5
5
  FAILED_CYCLE_OUTCOMES,
6
6
  HEARTBEAT_FILE,
7
- INTEGRATION_ENV,
8
- INTEGRATION_ENV_LEGACY,
9
- INTEGRATION_ENV_LEGACY_REMOVAL,
10
7
  INTEGRATION_STATUS_FILE,
8
+ LEASE_RENEW_MS,
9
+ LEASE_STALE_MS,
11
10
  LEGACY_STATUS_FILE,
12
11
  MANUAL,
13
12
  MANUAL_FETCH_TIMEOUT_MS,
@@ -17,17 +16,21 @@ import {
17
16
  MANUAL_SKILL_NAME,
18
17
  MANUAL_URL,
19
18
  REPEATED_FAILED_CYCLES,
20
- RUN_BUDGET_ENV,
21
- RUN_PROFILES,
22
- RUN_PROFILE_ENV,
23
19
  SOCKET_STATES,
20
+ STANDBY_MARKER_FRESH_MS,
24
21
  TEXTS_CACHE_FILE,
22
+ acquireAgentLock,
25
23
  acquireLeaderLock,
24
+ acquireLease,
25
+ agentLockDir,
26
+ agentLockPath,
27
+ agentLockRefusal,
26
28
  alwaysOnHealth,
27
29
  alwaysOnOptedOut,
28
30
  alwaysOnState,
29
31
  alwaysOnWanted,
30
32
  beat,
33
+ bootedAt,
31
34
  checkManual,
32
35
  clearAlwaysOnInstalledVersion,
33
36
  clearAlwaysOnOptOut,
@@ -35,6 +38,7 @@ import {
35
38
  clearCredentials,
36
39
  clearIntegrationStatus,
37
40
  clearPending,
41
+ clearStandby,
38
42
  credentialsPath,
39
43
  describeManualSync,
40
44
  envApiKey,
@@ -44,13 +48,13 @@ import {
44
48
  fetchServedTexts,
45
49
  formatIntegrationStatus,
46
50
  fromKitResult,
51
+ holderLive,
52
+ identityLineOf,
47
53
  idle,
48
- integrationDisabled,
49
- integrationDisabledBy,
50
54
  integrationStatusAge,
51
55
  integrationStatusPath,
52
- isRunProfile,
53
56
  isRunnerFactory,
57
+ leaseHolder,
54
58
  loadTexts,
55
59
  manualFrontMatter,
56
60
  manualPointer,
@@ -58,40 +62,63 @@ import {
58
62
  markAlwaysOnInstalledVersion,
59
63
  markAlwaysOnOptOut,
60
64
  markAlwaysOnWanted,
65
+ markStandby,
66
+ normalizeHandle,
67
+ parseLease,
61
68
  pendingPath,
69
+ pidAlive,
62
70
  readAlwaysOnInstalledVersion,
63
71
  readCachedTexts,
64
72
  readCredentials,
65
73
  readIntegrationStatus,
66
74
  readManualVersion,
67
75
  readPending,
76
+ resetLeaseObservations,
68
77
  resolveIdentity,
69
- resolveRunBudgetMs,
70
- resolveRunProfile,
78
+ standbyMarkerPath,
79
+ standbyWaiting,
71
80
  statePath,
72
81
  syncManual,
73
82
  textsCachePath,
74
83
  writeCredentials,
75
84
  writeIntegrationStatus,
76
85
  writePending
77
- } from "./chunk-7LAAAXUO.js";
86
+ } from "./chunk-CDJASQ3X.js";
78
87
  import {
79
88
  HOSTED_MCP_PATH,
89
+ PROBE_KILL_WAIT_MS,
80
90
  VERSION,
81
91
  hostedMcpUrl,
82
- probeHostedMcp
83
- } from "./chunk-XDWBTX5J.js";
92
+ probeHostedMcp,
93
+ runProbe
94
+ } from "./chunk-3ERPUP4M.js";
84
95
  import {
96
+ DEFAULT_RUN_BUDGET_MS,
97
+ DEFAULT_RUN_PROFILE,
98
+ INTEGRATION_ENV,
99
+ INTEGRATION_ENV_LEGACY,
100
+ INTEGRATION_ENV_LEGACY_REMOVAL,
101
+ PEER_RUN_WARNING,
102
+ RUN_BUDGET_ENV,
103
+ RUN_PROFILES,
104
+ RUN_PROFILE_ENV,
85
105
  atomicCopyFile,
86
106
  atomicWriteFile,
87
107
  clientHeadersOf,
88
108
  clientIdentityOf,
89
109
  clientNameOf,
110
+ integrationDisabled,
111
+ integrationDisabledBy,
112
+ isRunProfile,
90
113
  log,
91
114
  readJsonFile,
115
+ resolveRunBudgetMs,
116
+ resolveRunProfile,
117
+ runProfileWarning,
92
118
  spawnCommand,
93
- spawnCommandSync
94
- } from "./chunk-QDM4EFI7.js";
119
+ spawnCommandSync,
120
+ workdirExposesHome
121
+ } from "./chunk-AFDD53DD.js";
95
122
 
96
123
  // src/integration/tray.ts
97
124
  import { INBOX_TRAY_MAX_LIMIT } from "agentchatme";
@@ -137,45 +164,36 @@ function clearOfferDeclined(home) {
137
164
  writeState(home, state);
138
165
  }
139
166
 
140
- // src/skill/identity-line.ts
141
- import { integration as kit } from "agentchatme";
142
- function identityLineOf(texts) {
143
- return texts.identity_line;
144
- }
145
- function normalizeHandle(handle) {
146
- return kit.anchor.normalizeHandle(handle);
147
- }
148
-
149
167
  // src/anchor/block.ts
150
168
  import * as fs from "fs";
151
169
  import * as path from "path";
152
- import { integration as kit2 } from "agentchatme";
153
- var ANCHOR_START = kit2.anchor.START_MARKER;
154
- var ANCHOR_END = kit2.anchor.END_MARKER;
170
+ import { integration as kit } from "agentchatme";
171
+ var ANCHOR_START = kit.anchor.START_MARKER;
172
+ var ANCHOR_END = kit.anchor.END_MARKER;
155
173
  var MARKER_LINES = /* @__PURE__ */ new Set([
156
- kit2.anchor.START_MARKER,
157
- kit2.anchor.END_MARKER,
158
- kit2.anchor.LEGACY_START_MARKER,
159
- kit2.anchor.LEGACY_END_MARKER
174
+ kit.anchor.START_MARKER,
175
+ kit.anchor.END_MARKER,
176
+ kit.anchor.LEGACY_START_MARKER,
177
+ kit.anchor.LEGACY_END_MARKER
160
178
  ]);
161
179
  function renderAnchorBlock(identityLine, handle) {
162
180
  if (typeof identityLine !== "string" || identityLine.trim().length === 0) throw new Error("renderAnchorBlock: the identity line is empty");
163
- if (typeof handle !== "string" || kit2.anchor.normalizeHandle(handle).length === 0) throw new Error("renderAnchorBlock: the handle is empty");
181
+ if (typeof handle !== "string" || kit.anchor.normalizeHandle(handle).length === 0) throw new Error("renderAnchorBlock: the handle is empty");
164
182
  if (identityLine.split(/\r?\n/).some((line) => MARKER_LINES.has(line.trim()))) {
165
183
  throw new Error("renderAnchorBlock: the identity line holds an AgentChat marker line");
166
184
  }
167
- return kit2.anchor.render({ identity_line: identityLine, identity_line_template: "" }, handle);
185
+ return kit.anchor.render({ identity_line: identityLine, identity_line_template: "" }, handle);
168
186
  }
169
187
  function writeAnchor(filePath, block, expectHandle) {
170
188
  if (expectHandle !== void 0) {
171
- const bare = kit2.anchor.normalizeHandle(expectHandle);
172
- const claimed = kit2.anchor.find(block)?.handle ?? null;
189
+ const bare = kit.anchor.normalizeHandle(expectHandle);
190
+ const claimed = kit.anchor.find(block)?.handle ?? null;
173
191
  if (claimed !== bare) {
174
192
  throw new Error(`writeAnchor: the block for ${filePath} does not name @${bare} \u2014 nothing was written`);
175
193
  }
176
194
  }
177
195
  const existing = readInstructionFile(filePath) ?? { bom: "", text: "" };
178
- const next = untilStable(existing.text, (text) => kit2.anchor.replace(text, block));
196
+ const next = untilStable(existing.text, (text) => kit.anchor.replace(text, block));
179
197
  if (next !== existing.text) writeInstructionFile(filePath, existing.bom + next);
180
198
  if (expectHandle !== void 0 && readInstructionFile(filePath)?.text !== next) {
181
199
  throw new Error(`writeAnchor: ${filePath} did not read back as written \u2014 remove the agentchat block manually and re-run`);
@@ -194,14 +212,14 @@ function untilStable(text, step) {
194
212
  function removeAnchorAt(filePath) {
195
213
  const existing = readInstructionFile(filePath);
196
214
  if (existing === null) return "noop";
197
- const next = untilStable(existing.text, (text) => kit2.anchor.remove(text));
215
+ const next = untilStable(existing.text, (text) => kit.anchor.remove(text));
198
216
  if (next === existing.text) return "noop";
199
217
  writeInstructionFile(filePath, existing.bom + next);
200
218
  return "removed";
201
219
  }
202
220
  function hasAnchorAt(filePath) {
203
221
  const file = readInstructionFile(filePath);
204
- return file !== null && kit2.anchor.find(file.text) !== null;
222
+ return file !== null && kit.anchor.find(file.text) !== null;
205
223
  }
206
224
  function anchorIsCurrentAt(filePath, identityLine, handle) {
207
225
  const file = readInstructionFile(filePath);
@@ -212,21 +230,21 @@ function anchorIsCurrentAt(filePath, identityLine, handle) {
212
230
  } catch {
213
231
  return false;
214
232
  }
215
- if (kit2.anchor.find(file.text) === null) return false;
216
- return kit2.anchor.replace(file.text, expected) === file.text;
233
+ if (kit.anchor.find(file.text) === null) return false;
234
+ return kit.anchor.replace(file.text, expected) === file.text;
217
235
  }
218
236
  function readAnchorHandleAt(filePath, template) {
219
237
  const file = readInstructionFile(filePath);
220
238
  return file === null ? null : readAnchorHandleFrom(file.text, template);
221
239
  }
222
240
  function readAnchorHandleFrom(text, template) {
223
- return kit2.anchor.find(text.replace(/^\uFEFF/, ""), { template })?.handle ?? null;
241
+ return kit.anchor.find(text.replace(/^\uFEFF/, ""), { template })?.handle ?? null;
224
242
  }
225
243
  function upsertAnchorBlock(existing, block) {
226
- return kit2.anchor.replace(existing, block);
244
+ return kit.anchor.replace(existing, block);
227
245
  }
228
246
  function stripAnchorBlock(existing) {
229
- return kit2.anchor.remove(existing);
247
+ return kit.anchor.remove(existing);
230
248
  }
231
249
  var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
232
250
  function readInstructionFile(filePath) {
@@ -316,34 +334,13 @@ function renderUnregisteredBlock(copy) {
316
334
  "",
317
335
  `FIRST ask exactly: "Do you already have an AgentChat account for this ${label} agent, or should I create a new one?"`,
318
336
  "",
319
- "If they want a new account:",
320
- " **Ask only one question per turn. Never ask for the email and handle in the same message.**",
321
- ' 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."',
322
- ' 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."',
323
- ' Explain the rules simply: "Use 3\u201330 characters: lowercase letters, numbers, and hyphens. Start with a letter; no double or trailing hyphens."',
324
- ' 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."',
325
- ` 3. Once there is an email and handle, run: ${invoke} register --email <email> --handle <handle>`,
326
- " Registration is the authoritative availability check. Never promise availability before it succeeds.",
327
- " 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.",
328
- " Never submit a handle the user has not chosen or accepted.",
329
- ' 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."',
330
- ` 5. Run: ${invoke} register --code <code>`,
331
- ' 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.",
332
338
  "",
333
- `If they already have an account for this ${label} agent:`,
334
- " **Ask one question per turn. Run the commands yourself.**",
335
- ' 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."',
336
- ` 2. If they provide it, run: ${invoke} login --api-key <ac_\u2026>`,
337
- ' 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>."',
338
- ' 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."',
339
- ' 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?"',
340
- ' 4. Then ask only: "Which @handle is the account? One email can back several agents, so recovery needs both."',
341
- ` 5. Run: ${invoke} recover --handle <handle> --email <email>`,
342
- ' 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."',
343
- ` 7. Run: ${invoke} recover --code <code>`,
344
- ' 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."',
345
- ' If the code fails, say: "That code didn\u2019t work. Check the 6 digits and paste it again."',
346
- " 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.",
347
344
  "",
348
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.`,
349
346
  ANCHOR_END
@@ -364,7 +361,7 @@ function renderDeclinedBlock(copy) {
364
361
 
365
362
  // src/identity/commands.ts
366
363
  import * as readline from "readline";
367
- import { AgentChatClient } from "agentchatme";
364
+ import { AgentChatClient, integration as kit2 } from "agentchatme";
368
365
 
369
366
  // src/identity/host-profile.ts
370
367
  function anchorLabelOf(profile) {
@@ -376,10 +373,6 @@ function anchorLabelOf(profile) {
376
373
  }
377
374
 
378
375
  // src/identity/commands.ts
379
- var HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
380
- function validHandle(handle) {
381
- return handle.length >= 3 && handle.length <= 30 && HANDLE_PATTERN.test(handle);
382
- }
383
376
  var NO_TEXTS = Object.freeze({ identityLine: null, identityLineTemplate: null, manual: null });
384
377
  function errorText(err) {
385
378
  return err instanceof Error ? err.message : String(err);
@@ -390,24 +383,26 @@ function contextOf(texts) {
390
383
  async function prompt(question) {
391
384
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
392
385
  try {
393
- const answer = await new Promise((resolve2) => rl.question(question, resolve2));
394
- return answer.trim();
386
+ return await new Promise((resolve2) => {
387
+ rl.once("close", () => resolve2(null));
388
+ rl.question(question, (answer) => resolve2(answer.trim()));
389
+ });
395
390
  } finally {
396
391
  rl.close();
397
392
  }
398
393
  }
394
+ function interactive() {
395
+ return process.stdin.isTTY === true && process.stdout.isTTY === true;
396
+ }
399
397
  async function readAllStdin() {
400
398
  const chunks = [];
401
399
  for await (const chunk of process.stdin) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
402
400
  return Buffer.concat(chunks).toString("utf-8").trim();
403
401
  }
404
- function limitOf(e) {
405
- const limit = e.details?.["limit"];
406
- return typeof limit === "number" && Number.isFinite(limit) ? limit : null;
407
- }
408
- function handlesOf(e) {
409
- const handles = e.details?.["handles"];
410
- 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;
411
406
  }
412
407
  function httpStatusOf(err) {
413
408
  const status = err?.status;
@@ -416,50 +411,59 @@ function httpStatusOf(err) {
416
411
  function recoverUsage(invocation) {
417
412
  return `${invocation} recover --handle <handle> --email <email>`;
418
413
  }
419
- function describeApiError(err, invocation) {
420
- const e = err ?? {};
421
- const code = typeof e.code === "string" ? e.code : void 0;
422
- const message = typeof e.message === "string" ? e.message : String(err);
423
- switch (code) {
424
- case "HANDLE_TAKEN":
425
- return "That handle is already taken \u2014 pick another and re-run.";
426
- // An email backs a bounded number of live agents, and the bound is a
427
- // server-side setting — so the number is always the one the server just
428
- // reported, never a constant here. `EMAIL_TAKEN` is what a not-yet-upgraded
429
- // server says in the same situation (its bound was one).
430
- case "EMAIL_LIMIT_REACHED":
431
- case "EMAIL_TAKEN": {
432
- const limit = limitOf(e);
433
- const lead = limit !== null ? `This email already backs ${limit} active agent${limit === 1 ? "" : "s"} \u2014 its maximum.` : message;
434
- 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).`;
435
- }
436
- case "EMAIL_EXHAUSTED": {
437
- const limit = limitOf(e);
438
- const lead = limit !== null ? `This email has reached its lifetime maximum of ${limit} account registrations.` : message;
439
- return `${lead} Register with a different email (a + alias such as you+agent@example.com counts as a different email).`;
440
- }
441
- case "HANDLE_REQUIRED": {
442
- const handles = handlesOf(e);
443
- const listed = handles.length > 0 ? ` Agents on this email: ${handles.map((h) => `@${h}`).join(", ")}.` : "";
444
- 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)}`;
445
- }
446
- case "INVALID_HANDLE":
447
- return "The server rejected the handle (invalid or reserved word).";
448
- case "INVALID_CODE":
449
- return `Wrong or expired code. Re-check the 6 digits; after too many misses you must restart with \`${invocation} register\`.`;
450
- case "EXPIRED":
451
- return `This registration expired (codes last 10 minutes). Start over with \`${invocation} register\`.`;
452
- default:
453
- 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;
454
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)) ?? "" };
455
459
  }
456
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.";
457
461
  function createIdentityCommands(profile) {
458
462
  const invocation = () => profile.invocation();
459
- const apiErr = (err) => describeApiError(err, invocation());
460
463
  const LABEL = profile.label;
461
464
  const clientIdentity = clientIdentityOf(profile.client);
462
- 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 });
463
467
  async function served(apiKey, apiBase) {
464
468
  const loaded = await loadTexts({ home: profile.home(), runtime: profile.client.runtime, client: apiClient(apiKey, apiBase), timeoutMs: 5e3 });
465
469
  return loaded === null ? NO_TEXTS : contextOf(loaded.texts);
@@ -500,132 +504,205 @@ function createIdentityCommands(profile) {
500
504
  return [` ${label}: FAILED \u2014 ${String(err)}`];
501
505
  }
502
506
  }
503
- async function runRegister(opts) {
504
- const home = profile.home();
505
- const apiBase = opts.apiBase ?? process.env["AGENTCHAT_API_BASE"] ?? DEFAULT_API_BASE;
506
- if (opts.code !== void 0) {
507
- const code = opts.code.trim();
508
- if (!/^\d{6}$/.test(code)) {
509
- console.error("The code is the 6-digit number from the verification email.");
510
- return 1;
511
- }
512
- const pending = readPending(home);
513
- if (pending === null) {
514
- console.error(
515
- `No registration in progress. Start with: ${invocation()} register --email <email> --handle <handle>`
516
- );
517
- return 1;
518
- }
519
- if (pending.kind === "recover") {
520
- console.error(
521
- `The pending code belongs to an account RECOVERY \u2014 complete it with: ${invocation()} recover --code ${code}`
522
- );
523
- return 1;
524
- }
525
- const pendingHandle = pending.handle;
526
- if (pendingHandle === void 0) {
527
- clearPending(home);
528
- console.error(`Pending registration was corrupt \u2014 start again with: ${invocation()} register`);
529
- 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}`];
530
536
  }
531
- try {
532
- const result = await AgentChatClient.verify(pending.pending_id, code, {
533
- baseUrl: pending.api_base ?? apiBase,
534
- clientIdentity
535
- });
536
- writeCredentials(home, {
537
- api_key: result.apiKey,
538
- handle: pendingHandle,
539
- ...pending.api_base ? { api_base: pending.api_base } : {},
540
- created_at: (/* @__PURE__ */ new Date()).toISOString()
541
- });
542
- clearPending(home);
543
- clearOfferDeclined(home);
544
- console.log(
545
- [
546
- `Registered: @${pendingHandle} for ${LABEL}.`,
547
- `API key stored at ${credentialsPath(home)} (never commit this file).`,
548
- ...await placeIdentity(pendingHandle, result.apiKey, pending.api_base ?? apiBase),
549
- "",
550
- `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.`,
551
- `Other agents can DM you at @${pendingHandle}. Check \`${invocation()} status\` any time.`,
552
- NEXT_HINT
553
- ].join("\n")
554
- );
555
- return 0;
556
- } catch (err) {
557
- console.error(`Verification failed. ${apiErr(err)}`);
558
- 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];
559
542
  }
543
+ case "stop":
544
+ return heldCode;
560
545
  }
561
- 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) {
562
618
  console.error(
563
- `${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())}`
564
620
  );
565
621
  return 1;
566
622
  }
567
- const inFlight = readPending(home);
568
- if (inFlight?.kind === "recover") {
623
+ if (pending.kind !== kind) {
569
624
  console.error(
570
- `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)}`
571
626
  );
572
627
  return 1;
573
628
  }
574
- let email = opts.email?.trim().toLowerCase();
575
- let handle = opts.handle?.trim().toLowerCase();
576
- const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true;
577
- if (!email) {
578
- if (!interactive) {
579
- console.error(`Missing --email. Usage: ${invocation()} register --email <email> --handle <handle>`);
580
- return 1;
581
- }
582
- 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;
583
633
  }
584
- if (!handle) {
585
- if (!interactive) {
586
- console.error(`Missing --handle. Usage: ${invocation()} register --email <email> --handle <handle>`);
587
- return 1;
588
- }
589
- 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;
590
642
  }
591
- if (!email.includes("@")) {
592
- console.error(`"${email}" does not look like an email address.`);
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;
655
+ }
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)}`);
593
670
  return 1;
594
671
  }
595
- 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) {
596
681
  console.error(
597
- `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.`
598
683
  );
599
684
  return 1;
600
685
  }
601
- try {
602
- const result = await AgentChatClient.register({
603
- email,
604
- handle,
605
- ...opts.displayName ? { display_name: opts.displayName } : {},
606
- ...opts.description ? { description: opts.description } : {},
607
- baseUrl: apiBase,
608
- clientIdentity
609
- });
610
- writePending(home, {
611
- kind: "register",
612
- pending_id: result.pending_id,
613
- email,
614
- handle,
615
- ...apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {},
616
- created_at: (/* @__PURE__ */ new Date()).toISOString()
617
- });
618
- console.log(
619
- [
620
- `Verification code sent to ${email} (valid ~10 minutes).`,
621
- `Complete with: ${invocation()} register --code <6-digit-code>`
622
- ].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.`
623
689
  );
624
- return 0;
625
- } catch (err) {
626
- console.error(`Registration failed. ${apiErr(err)}`);
627
690
  return 1;
628
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);
629
706
  }
630
707
  async function runLogin(opts) {
631
708
  const home = profile.home();
@@ -644,140 +721,65 @@ function createIdentityCommands(profile) {
644
721
  );
645
722
  return 1;
646
723
  } else {
647
- apiKey = await prompt("AgentChat API key (ac_\u2026): ");
724
+ apiKey = await prompt("AgentChat API key (ac_\u2026): ") ?? "";
648
725
  }
649
726
  }
650
- if (apiKey.length < 20) {
651
- 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.");
652
729
  return 1;
653
730
  }
731
+ let check;
654
732
  try {
655
- const client = apiClient(apiKey, apiBase, "patient");
656
- const me = await client.getMe();
657
- writeCredentials(home, {
658
- api_key: apiKey,
659
- handle: me.handle,
660
- ...apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {},
661
- created_at: (/* @__PURE__ */ new Date()).toISOString()
662
- });
663
- clearOfferDeclined(home);
664
- console.log(
665
- [
666
- `Signed in as @${me.handle} for ${LABEL}.`,
667
- `API key stored at ${credentialsPath(home)} (never commit this file).`,
668
- ...await placeIdentity(me.handle, apiKey, apiBase),
669
- NEXT_HINT
670
- ].join("\n")
671
- );
672
- return 0;
733
+ check = await kit2.account.checkKey(apiKey, accountOptions(apiBase));
673
734
  } catch (err) {
674
- 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.`);
675
742
  return 1;
676
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;
677
760
  }
678
761
  async function runRecover(opts) {
679
762
  const home = profile.home();
680
763
  const apiBase = opts.apiBase ?? process.env["AGENTCHAT_API_BASE"] ?? DEFAULT_API_BASE;
681
- const usage = recoverUsage(invocation());
682
- if (opts.code !== void 0) {
683
- const code = opts.code.trim();
684
- if (!/^\d{6}$/.test(code)) {
685
- console.error("The code is the 6-digit number from the recovery email.");
686
- return 1;
687
- }
688
- const pending = readPending(home);
689
- if (pending === null || pending.kind !== "recover") {
690
- console.error(`No recovery in progress. Start with: ${usage}`);
691
- return 1;
692
- }
693
- try {
694
- const result = await AgentChatClient.recoverVerify(pending.pending_id, code, {
695
- baseUrl: pending.api_base ?? apiBase,
696
- clientIdentity
697
- });
698
- writeCredentials(home, {
699
- api_key: result.apiKey,
700
- handle: result.handle,
701
- ...pending.api_base ? { api_base: pending.api_base } : {},
702
- created_at: (/* @__PURE__ */ new Date()).toISOString()
703
- });
704
- clearPending(home);
705
- clearOfferDeclined(home);
706
- console.log(
707
- [
708
- `Recovered: @${result.handle} for ${LABEL}.`,
709
- `New API key stored at ${credentialsPath(home)} (the old key is now revoked; never commit this file).`,
710
- ...await placeIdentity(result.handle, result.apiKey, pending.api_base ?? apiBase),
711
- NEXT_HINT
712
- ].join("\n")
713
- );
714
- return 0;
715
- } catch (err) {
716
- if (err?.code === "HANDLE_REQUIRED") clearPending(home);
717
- console.error(`Recovery failed. ${apiErr(err)}`);
718
- return 1;
719
- }
720
- }
721
- const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true;
722
- let handle = opts.handle?.trim().replace(/^@/, "").toLowerCase();
723
- 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) {
724
767
  const stored = readCredentials(home)?.handle;
725
768
  if (stored !== void 0) {
726
769
  handle = stored;
727
770
  console.log(`Recovering @${stored} \u2014 this agent's stored handle (pass --handle to recover a different agent).`);
728
- } else if (interactive) {
729
- handle = (await prompt("Handle of the agent to recover (e.g. sanim-dev): ")).replace(/^@/, "").toLowerCase();
730
- } else {
731
- console.error(
732
- `Missing --handle. An email can back more than one agent, so recovery needs the handle too. Usage: ${usage}`
733
- );
734
- return 1;
735
771
  }
736
772
  }
737
- if (!validHandle(handle)) {
738
- console.error(
739
- `Handle "@${handle}" is invalid. Rules: 3\u201330 characters, lowercase letters/digits/hyphens, must start with a letter, no trailing or doubled hyphens.`
740
- );
741
- return 1;
742
- }
743
- let email = opts.email?.trim().toLowerCase();
744
- if (!email) {
745
- if (!interactive) {
746
- 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())}`);
747
777
  return 1;
748
778
  }
749
- email = (await prompt(`Email @${handle} was registered with: `)).toLowerCase();
750
- }
751
- if (!email.includes("@")) {
752
- console.error(`"${email}" does not look like an email address.`);
753
- return 1;
754
- }
755
- try {
756
- const result = await AgentChatClient.recover(email, { handle, baseUrl: apiBase, clientIdentity });
757
- if (!result.pending_id) {
758
- console.log(result.message || "If an agent is registered with that email, a recovery code was sent to it.");
759
- return 0;
760
- }
761
- writePending(home, {
762
- kind: "recover",
763
- pending_id: result.pending_id,
764
- email,
765
- handle,
766
- ...apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {},
767
- created_at: (/* @__PURE__ */ new Date()).toISOString()
768
- });
769
- console.log(
770
- [
771
- `If @${handle} is registered with ${email}, a recovery code was sent there (valid ~10 minutes).`,
772
- `Complete with: ${invocation()} recover --code <6-digit-code>`,
773
- "Note: completing recovery rotates the API key \u2014 anything using the old key stops working."
774
- ].join("\n")
775
- );
776
- return 0;
777
- } catch (err) {
778
- console.error(`Recovery failed. ${apiErr(err)}`);
779
- 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);
780
781
  }
782
+ return startSignup("recover", { email, ...handle !== void 0 ? { handle } : {} }, apiBase);
781
783
  }
782
784
  function anchorView(file, identityLine, handle) {
783
785
  if (file === null) return { present: null, current: null, error: null };
@@ -806,14 +808,10 @@ function createIdentityCommands(profile) {
806
808
  integration
807
809
  })
808
810
  );
809
- } else if (pending?.kind === "recover") {
810
- const who = pending.handle !== void 0 ? ` for @${pending.handle}` : "";
811
- console.log(
812
- `No identity yet, but an account recovery${who} is waiting on its emailed code \u2014 finish with: ${invocation()} recover --code <code>`
813
- );
814
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 ?? "?"}`;
815
813
  console.log(
816
- `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)}`
817
815
  );
818
816
  } else {
819
817
  console.log(`No AgentChat identity for this ${LABEL} agent. Set one up with: ${invocation()} register`);
@@ -827,7 +825,7 @@ function createIdentityCommands(profile) {
827
825
  } catch (err) {
828
826
  const status = httpStatusOf(err);
829
827
  const refused = status === 401 || status === 403;
830
- const detail = apiErr(err);
828
+ const detail = describeApiError(err);
831
829
  if (opts.json) {
832
830
  const offline = anchorView(anchorFile, null, null);
833
831
  console.log(
@@ -966,15 +964,15 @@ function createIdentityCommands(profile) {
966
964
  }
967
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}`;
968
966
  if (fix) {
969
- const report = await placeIdentity(creds.handle, creds.api_key, apiBase);
970
- const failed = report.some((l) => l.includes("FAILED") || l.includes("not written"));
971
- 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("; ")}` };
972
970
  try {
973
971
  const after = readIdentityLine(anchorFile, creds.handle, texts);
974
972
  if (after.claimed === creds.handle && after.current !== false) {
975
973
  return { name: "identity-line", verdict: "PASS", detail: `repaired \u2192 @${creds.handle}` };
976
974
  }
977
- 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()})` : ""}` };
978
976
  } catch (err) {
979
977
  return { name: "identity-line", verdict: "FAIL", detail: `cannot read ${anchorFile} after the repair: ${errorText(err)}` };
980
978
  }
@@ -1028,6 +1026,29 @@ function createIdentityCommands(profile) {
1028
1026
  if (anchorFile !== null) checks.push(await identityLineCheck(anchorFile, creds, apiBase, texts, opts.fix === true));
1029
1027
  }
1030
1028
  const integration = readIntegrationStatus(home);
1029
+ const runsFailing = integration?.runs_failing ?? null;
1030
+ const gaveUp = integration?.unservable ?? null;
1031
+ if (gaveUp !== null) {
1032
+ checks.push({
1033
+ name: "runs",
1034
+ verdict: "FAIL",
1035
+ detail: gaveUp.reason === "key_refused" ? `this home gave the agent up: the server refuses its key (${gaveUp.detail}); it looks again at ${gaveUp.retry_at} (every 5 min) and takes the agent back whenever no other listener holds it, but only a key the server accepts can serve \u2014 sign in again here (login/recover; that clears this at once), or log out if another home serves the agent` : `this home gave the agent up: ${gaveUp.detail} (since ${gaveUp.since}); its runtime is checked again at ${gaveUp.retry_at} (every 60 s) and a check that passes clears this; it takes the agent back whenever no other listener holds it`
1036
+ });
1037
+ } else if (runsFailing !== null) {
1038
+ checks.push({
1039
+ name: "runs",
1040
+ verdict: "FAIL",
1041
+ detail: `runs failing: ${runsFailing.reason} \u2014 since ${runsFailing.since}, ${runsFailing.runs_missed} run(s) missed (checked ${runsFailing.checked_at}); fix that, and the next run that succeeds clears this`
1042
+ });
1043
+ }
1044
+ const standby = integration?.standby ?? null;
1045
+ if (standby !== null) {
1046
+ checks.push({
1047
+ name: "single-listener",
1048
+ verdict: "WARN",
1049
+ detail: `another listener serves this agent: ${standby.home ?? "another identity home"}${standby.pid !== null ? ` (pid ${standby.pid})` : ""}; this one stands by (no socket, no run) so no message is answered twice`
1050
+ });
1051
+ }
1031
1052
  const cycles = integration?.recent_cycles ?? [];
1032
1053
  if (cycles.length > 0) {
1033
1054
  const failing = failedCyclesInARow(integration);
@@ -1551,9 +1572,11 @@ function killLauncher(label, mode) {
1551
1572
  return run(mode === "win32" ? "powershell" : "powershell.exe", ["-NoProfile", "-Command", ps]);
1552
1573
  }
1553
1574
  function lockedDaemonPid(home) {
1575
+ const file = path2.join(home, DAEMON_LOCK_FILE);
1554
1576
  try {
1555
- const pid = Number.parseInt(fs2.readFileSync(path2.join(home, "daemon.lock"), "utf-8").trim(), 10);
1556
- return Number.isInteger(pid) && pid > 0 ? pid : null;
1577
+ const holder = parseLease(fs2.readFileSync(file, "utf-8"));
1578
+ if (holder === null || !Number.isInteger(holder.pid) || holder.pid <= 0) return null;
1579
+ return holderLive(holder, { mtimeMs: fs2.statSync(file).mtimeMs }) ? holder.pid : null;
1557
1580
  } catch {
1558
1581
  return null;
1559
1582
  }
@@ -1710,8 +1733,10 @@ function serviceInstalled(opts) {
1710
1733
  return unitInstalled(serviceLabel(opts.label));
1711
1734
  }
1712
1735
  export {
1736
+ AGENT_LOCK_DIR_ENV,
1713
1737
  ANCHOR_END,
1714
1738
  ANCHOR_START,
1739
+ DAEMON_LOCK_FILE,
1715
1740
  DEFAULT_API_BASE,
1716
1741
  DEFAULT_RUN_BUDGET_MS,
1717
1742
  DEFAULT_RUN_PROFILE,
@@ -1722,6 +1747,8 @@ export {
1722
1747
  INTEGRATION_ENV_LEGACY,
1723
1748
  INTEGRATION_ENV_LEGACY_REMOVAL,
1724
1749
  INTEGRATION_STATUS_FILE,
1750
+ LEASE_RENEW_MS,
1751
+ LEASE_STALE_MS,
1725
1752
  LEGACY_STATUS_FILE,
1726
1753
  MANUAL,
1727
1754
  MANUAL_FETCH_TIMEOUT_MS,
@@ -1730,14 +1757,22 @@ export {
1730
1757
  MANUAL_MAX_REDIRECTS,
1731
1758
  MANUAL_SKILL_NAME,
1732
1759
  MANUAL_URL,
1760
+ PEER_RUN_WARNING,
1761
+ PROBE_KILL_WAIT_MS,
1733
1762
  REPEATED_FAILED_CYCLES,
1734
1763
  RUN_BUDGET_ENV,
1735
1764
  RUN_PROFILES,
1736
1765
  RUN_PROFILE_ENV,
1737
1766
  SOCKET_STATES,
1767
+ STANDBY_MARKER_FRESH_MS,
1738
1768
  TEXTS_CACHE_FILE,
1739
1769
  VERSION,
1770
+ acquireAgentLock,
1740
1771
  acquireLeaderLock,
1772
+ acquireLease,
1773
+ agentLockDir,
1774
+ agentLockPath,
1775
+ agentLockRefusal,
1741
1776
  alwaysOnHealth,
1742
1777
  alwaysOnOptedOut,
1743
1778
  alwaysOnState,
@@ -1747,6 +1782,7 @@ export {
1747
1782
  atomicCopyFile,
1748
1783
  atomicWriteFile,
1749
1784
  beat,
1785
+ bootedAt,
1750
1786
  checkManual,
1751
1787
  clearAlwaysOnInstalledVersion,
1752
1788
  clearAlwaysOnOptOut,
@@ -1755,6 +1791,7 @@ export {
1755
1791
  clearIntegrationStatus,
1756
1792
  clearOfferDeclined,
1757
1793
  clearPending,
1794
+ clearStandby,
1758
1795
  clientHeadersOf,
1759
1796
  clientIdentityOf,
1760
1797
  clientNameOf,
@@ -1768,6 +1805,7 @@ export {
1768
1805
  formatIntegrationStatus,
1769
1806
  fromKitResult,
1770
1807
  hasAnchorAt,
1808
+ holderLive,
1771
1809
  hostedMcpUrl,
1772
1810
  identityLineOf,
1773
1811
  idle,
@@ -1779,6 +1817,7 @@ export {
1779
1817
  isRunProfile,
1780
1818
  isRunnerFactory,
1781
1819
  launchdPlist,
1820
+ leaseHolder,
1782
1821
  loadTexts,
1783
1822
  log,
1784
1823
  manualFrontMatter,
@@ -1787,10 +1826,13 @@ export {
1787
1826
  markAlwaysOnInstalledVersion,
1788
1827
  markAlwaysOnOptOut,
1789
1828
  markAlwaysOnWanted,
1829
+ markStandby,
1790
1830
  normalizeHandle,
1791
1831
  offerDeclined,
1832
+ parseLease,
1792
1833
  parseServiceHome,
1793
1834
  pendingPath,
1835
+ pidAlive,
1794
1836
  planForTest,
1795
1837
  probeHostedMcp,
1796
1838
  readAlwaysOnInstalledVersion,
@@ -1808,9 +1850,12 @@ export {
1808
1850
  renderAnchorBlock,
1809
1851
  renderDeclinedBlock,
1810
1852
  renderUnregisteredBlock,
1853
+ resetLeaseObservations,
1811
1854
  resolveIdentity,
1812
1855
  resolveRunBudgetMs,
1813
1856
  resolveRunProfile,
1857
+ runProbe,
1858
+ runProfileWarning,
1814
1859
  serviceDefinitionCurrent,
1815
1860
  serviceInstalled,
1816
1861
  serviceLabelFor,
@@ -1819,6 +1864,8 @@ export {
1819
1864
  setServiceHostOsForTests,
1820
1865
  spawnCommand,
1821
1866
  spawnCommandSync,
1867
+ standbyMarkerPath,
1868
+ standbyWaiting,
1822
1869
  statePath,
1823
1870
  stripAnchorBlock,
1824
1871
  syncManual,
@@ -1828,6 +1875,7 @@ export {
1828
1875
  traySummary,
1829
1876
  uninstallService,
1830
1877
  upsertAnchorBlock,
1878
+ workdirExposesHome,
1831
1879
  writeAnchor,
1832
1880
  writeCredentials,
1833
1881
  writeIntegrationStatus,